From fa8d9efb35b2ed5ec1d18f60510167767c8fb2bf Mon Sep 17 00:00:00 2001 From: meixiezichuan Date: Tue, 9 Aug 2022 16:20:49 +0800 Subject: [PATCH] Reconstruction (#227) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * delete service ticketinfo (#178) * Station food (#177) * 修改station-food-service 主要是重命名 * 修改数据库名称 * 删除不必要的代码文件 * 修改quickstart-k8s中的mongo和service名 * 修改pom.xml * 修改父pom.xml * 修改url调用关系 * feat: 拆分ts-food-map-service为ts-trainfood-service (#179) * Log optimization 20220117 (#183) * log fixed by Chen Miao 0119 * log fixed by Tianyi Zhang 0120 * log fixed by Tianyi Zhang 0120-1 * log fixed by Tianyi Zhang 0120-2 * log fixed by Tianyi Zhang 0121-1 * Service access address configuration collation * nacos初步修改 (#181) * nacos初步修改 * nacos修改硬编码 * nacos k8s cluster * nacos 部署删除不必要文件 * Gateway (#185) * add gateway * fix gateway * fix: gateway中uri用通配符形式匹配 * use NACOS_ADDRS instead of ip Co-authored-by: wangyongli.0510 Co-authored-by: Rananism * 统一数据库为mongo * 版本问题修改 * 版本问题修改 * fix test error * fix dockerfile * nacos数据库修改 * fix gateway and trainFood * Cqq mysql (#187) * 改mysql yml * 改mysql * mysql train * mysql * mysql useSSL=false * update * Ws mysql (#188) * change to mysql yml * change to mysql yml * change to mysql ts-auth * change to mysql ts-auth * change to mysql ts-contacts * revert change to mysql ts-route * change to mysql ts-train * fix bug * change to mysql ts-user * change to mysql ts-consign-price * Update uuid length to 36 Co-authored-by: meixiezichuan * Reconstruction (#190) * log fixed by Tianyi Zhang mysql modified for delivery-service * log fixed by Tianyi Zhang mysql modified * log fixed by Tianyi Zhang mysql modified * Reconstruction (#191) * log fixed by Tianyi Zhang mysql modified for delivery-service * log fixed by Tianyi Zhang mysql modified * log fixed by Tianyi Zhang mysql modified * fixed by Tianyi Zhang mysql modified * Hd mysql refactoring data access layer transfer to MySQL ts-route ts-food ts-security * mysql (#196) * reconstruction (#195) * reconstruction * reconstructionon_fixURL * adjust the configuration (#198) * Zbc mysql (#194) * ts-travel-service: migrate from mongo to mysql * ts-travel2-service: migrate from mogo to mysql * ts-train-food-service: migrate from mongo to mysql * Fix bug. * mysql modified * Modify mysql config. * adjust the configuration (#198) * ts-travel-service: migrate from mongo to mysql * ts-travel2-service: migrate from mogo to mysql * ts-train-food-service: migrate from mongo to mysql * Fix bug. * mysql modified * Modify mysql config. Co-authored-by: Kyle-Dwyer <34733051+Kyle-Dwyer@users.noreply.github.com> Co-authored-by: meixiezichuan * Reconstruction (#193) * log fixed by Tianyi Zhang mysql modified for delivery-service * log fixed by Tianyi Zhang mysql modified * log fixed by Tianyi Zhang mysql modified * fixed by Tianyi Zhang mysql modified * fixed by Tianyi Zhang mysql modified * fixed by Tianyi Zhang mysql modified * fixed by Tianyi Zhang mysql modified * fixed by Tianyi Zhang mysql modified * update: mysql config in application.yml * Reconstruction (#204) * inside-payment stop * ts-gateway finished * mysql * change length * fix rabbitmq port type error * rm ts-nacos dir * Use discoveryClient in ts-admin-basic-info-service * Reconstruction (#205) * fixed by Tianyi Zhang mysql modified * adjust the configuration (#206) * Re cqq (#207) * mysql * fix ts-auth ts-consign-price ts-train ts-contacts ts-user * fix nacos related (#209) * fix ts-admin-* & basic & cancel & preserve & rebook to use discoveryclient * fix execute order order-other route-plan seat travel-plan * Fix nacos config. (#211) * Fix getServiceUrl * refactor: nacos config (#213) * fix getServiceUrl for food & security * update gateway service(fix dependency bugs & add sentinal flow control feature) (#212) * fix getServiceUrl for food & security * remove ribbon & openfeign * add dialect for mysql * add jakarta.validation dependency * fix admin-basic application.yaml * Add unique for index of consign price * fix delivery swagger version * fix order, order-other findById * fix payment * fix price findById * Fix entiry defination in payment, insidepsyment, train, travel, travel2 * fix price findById.get * update guava version in verfication-code to fix dependency error * fix station * Fix voucher to use mysql env * fix port type in mysql_config * Fix getServiceUrl and mysqlDriver * Fix route entity duplicated definition * Fix station findById get * Fix travel/travel2 check null before traverse list * remove duplicated Entity of Trip in travel2 * use trip2 in travel2 * add travel/travel2 repository bean * Data (#218) * Tidy data definition * tidy and formalize data * refactor: forwards the service request to Gateway (#217) * remove unique constraint of consign price * Feature update header (#219) * update header (add token) * update header (add token) * Prometheus skywalking (#208) * Add prometheus config. * Add skywalking config. * Change deployment yaml for skywalking. * fix auth-user and user to use same user_id * optimize travel and seat loop dependency * add orderColumn for route_stations and route_distances * rm auto genetate id for price * Modify gateway addr in nginx.conf * query basic infos by batch * feat: Modified the form for adding information and added options. (#221) * feat: Modified the form for adding information and added options. * fix: form for adding new travel. * Fix route plan and travel plan * Format startStation and end Station in route * update deployment file * fix admin bugs (#222) * update: Modified parameters of some interfaces. Updated descriptions of some forms. * fix ticket-office use mysql * user environment var of mysql * Fix trainfood stationFood * add quickstart-k8s deployment * Feature bugs fix (#223) * fix admin bugs * fix bugs * optimize seat Co-authored-by: meixiezichuan * Fix food service * Ts food delivery service (#220) * Add ts-food-delivery-service. * Add ts-food-delivery-service * Add rpc to station-food-service. * Add rpc to station-food-service. * Test controller. * Solve reviewed problems. * Rename TripInfo. * fix stationfood url * Feature train update fix (#224) * update header (add token) * fix train update * Modify Date type to String * fix Order/Orderother about date type bug * fix: Complete front-end request parameters. (#225) fix: Front-end display problems. * fix travel update method * modify Date to String in Trip * Fix admin-route admin-travel add methoud * fix date type bug * set default price rate when priceconfig not found * edit deployment/ (#226) * edit deployment/ * edit ts-consign-price-mysql * Set tarvel date format yyyy-mm-dd hh:mm:ss * Fix bug in getTripAllDetailInfo * Add Release note 1.0 * Fix get seat bug in travel plan * Completed waiting order service, and modified some configuration files. (#229) * edit deployment/ * edit ts-consign-price-mysql * edit entity * change to Date * edit repository * feature: wait list order service * fix: Judgment of the waiting period * update: Modified configuration file of ts-wait-order-service. Co-authored-by: winterStreet Co-authored-by: WinterStreett <53975807+WinterStreett@users.noreply.github.com> * docs(CHANGLOG-1.0.md) update sentinel part and bugfix part * Fix String2Date * fix contacts * update release note * modify pom * Add deploy file and doc * add nacos helm charts * Update deploy files * fix charts and yamls * update readme & changelog & deploy file * update architecute png * remove datasource from gateway * add sample file for deploy yamls Co-authored-by: Kyle-Dwyer <34733051+Kyle-Dwyer@users.noreply.github.com> Co-authored-by: cqqqqc <50789602+cqqqqc@users.noreply.github.com> Co-authored-by: Yongli0510 <1415193349@qq.com> Co-authored-by: SakuraX99 <57907184+SakuraX99@users.noreply.github.com> Co-authored-by: WangShang <1005284123@qq.com> Co-authored-by: wangyongli.0510 Co-authored-by: 程千骞 <1617095973@qq.com> Co-authored-by: akasakaisami Co-authored-by: Deep-Yellow <957822635@qq.com> Co-authored-by: water423 <48052788+water423@users.noreply.github.com> Co-authored-by: zbcdd <52142931+zbcdd@users.noreply.github.com> Co-authored-by: Deep-Yellow <51702118+Deep-Yellow@users.noreply.github.com> Co-authored-by: WinterStreett <53975807+WinterStreett@users.noreply.github.com> Co-authored-by: winterStreet --- CHANGELOG-1.0.md | 159 + Makefile | 20 +- README.md | 78 +- .../docker-compose-with-jaeger.yml | 242 +- .../quickstart-docker-compose.yml | 227 +- .../prometheus-deployment/configmap.yaml | 156 - .../kube-state-metrics.yaml | 194 - .../prometheus-deployment/node-exporter.yaml | 40 - .../prometheus-deployment/prometheus.yaml | 64 - .../prometheus-deployment/rbac.yaml | 39 - .../prometheus/alert-manager-configmap.yml | 31 + .../prometheus/alert-manager.yml | 77 + .../prometheus/alertsnitch.yml | 99 + .../grafana.yaml => prometheus/grafana.yml} | 3 + .../prometheus/node-exporter.yml | 64 + .../prometheus/prometheus-configmap.yml | 189 + .../prometheus/prometheus.yml | 329 + .../quickstart-k8s/charts/mysql/Chart.yaml | 38 + .../quickstart-k8s/charts/mysql/README.md | 187 + .../mysql/templates/.statefulset.yaml.swp | Bin 0 -> 16384 bytes .../charts/mysql/templates/NOTES.txt | 29 + .../charts/mysql/templates/_helpers.tpl | 45 + .../charts/mysql/templates/configmap.yaml | 38 + .../charts/mysql/templates/rbac.yaml | 36 + .../charts/mysql/templates/secrets.yaml | 30 + .../charts/mysql/templates/service.yaml | 109 + .../mysql/templates/serviceaccount.yaml | 11 + .../mysql/templates/servicemonitor.yaml | 27 + .../charts/mysql/templates/statefulset.yaml | 343 + .../quickstart-k8s/charts/mysql/values.yaml | 211 + .../quickstart-k8s/charts/nacos/Chart.yaml | 5 + .../quickstart-k8s/charts/nacos/README.md | 53 + .../charts/nacos/templates/_helpers.tpl | 45 + .../charts/nacos/templates/configmap.yaml | 7 + .../charts/nacos/templates/secrets.yaml | 14 + .../charts/nacos/templates/service.yaml | 42 + .../charts/nacos/templates/statefulset.yaml | 73 + .../quickstart-k8s/charts/nacos/values.yaml | 57 + .../quickstart-k8s/charts/rabbitmq/Chart.yaml | 5 + .../quickstart-k8s/charts/rabbitmq/README.md | 167 + .../charts/rabbitmq/templates/configmap.yaml | 7 + .../charts/rabbitmq/templates/deployment.yaml | 25 + .../charts/rabbitmq/templates/service.yaml | 10 + .../charts/rabbitmq/values.yaml | 36 + .../quickstart-ts-deployment-part1.yml | 966 - .../quickstart-ts-deployment-part3.yml | 43 - .../deploy.yaml.sample} | 1452 +- .../quickstart-k8s/yamls/svc.yaml | 487 + .../yamls/sw_deploy.yaml.sample | 3131 +++ .../kubernetes-manifests/skywalking/es.yml | 60 + .../skywalking/skywalking.yml | 144 + hack/deploy/deploy.sh | 100 + hack/deploy/gen-mysql-secret.sh | 93 + hack/deploy/reset.sh | 19 + hack/deploy/utils.sh | 117 + image/2.png | Bin 128670 -> 254814 bytes old-docs/Lib/ms-monitoring-core/pom.xml | 2 +- .../src/test/java/TestServiceTravel.java | 8 +- pom.xml | 67 +- ts-admin-basic-info-service/pom.xml | 16 +- .../adminbasic/AdminBasicInfoApplication.java | 4 + .../controller/AdminBasicInfoController.java | 56 +- .../main/java/adminbasic/entity/Contacts.java | 54 - .../main/java/adminbasic/entity/Station.java | 40 - .../java/adminbasic/entity/TrainType.java | 38 - .../service/AdminBasicInfoService.java | 14 +- .../service/AdminBasicInfoServiceImpl.java | 101 +- .../src/main/resources/application.yml | 6 +- .../AdminBasicInfoControllerTest.java | 8 +- .../AdminBasicInfoServiceImplTest.java | 8 +- ts-admin-order-service/pom.xml | 4 +- .../adminorder/AdminOrderApplication.java | 4 + .../controller/AdminOrderController.java | 10 +- .../main/java/adminorder/entity/Order.java | 95 - .../java/adminorder/entity/OrderStatus.java | 63 - .../java/adminorder/entity/SeatClass.java | 70 - .../adminorder/service/AdminOrderService.java | 2 +- .../service/AdminOrderServiceImpl.java | 63 +- .../src/main/resources/application.yml | 8 +- .../controller/AdminOrderControllerTest.java | 6 +- .../service/AdminOrderServiceImplTest.java | 10 +- ts-admin-route-service/pom.xml | 4 +- .../adminroute/AdminRouteApplication.java | 4 + .../controller/AdminRouteController.java | 8 +- .../main/java/adminroute/entity/Route.java | 25 - .../java/adminroute/entity/RouteInfo.java | 24 - .../adminroute/service/AdminRouteService.java | 2 +- .../service/AdminRouteServiceImpl.java | 72 +- .../src/main/resources/application.yml | 4 + .../controller/AdminRouteControllerTest.java | 2 +- .../service/AdminRouteServiceImplTest.java | 4 +- ts-admin-travel-service/pom.xml | 4 +- .../admintravel/AdminTravelApplication.java | 4 + .../controller/AdminTravelController.java | 14 +- .../main/java/admintravel/entity/Route.java | 26 - .../java/admintravel/entity/TrainType.java | 36 - .../java/admintravel/entity/TravelInfo.java | 33 - .../main/java/admintravel/entity/Trip.java | 49 - .../main/java/admintravel/entity/TripId.java | 42 - .../main/java/admintravel/entity/Type.java | 63 - .../service/AdminTravelService.java | 2 +- .../service/AdminTravelServiceImpl.java | 185 +- .../src/main/resources/application.yml | 4 + .../controller/AdminTravelControllerTest.java | 2 +- .../service/AdminTravelServiceImplTest.java | 22 +- ts-admin-user-service/pom.xml | 7 +- .../java/adminuser/AdminUserApplication.java | 4 + .../controller/AdminUserController.java | 8 +- .../src/main/java/adminuser/dto/UserDto.java | 1 + .../java/adminuser/entity/DocumentType.java | 50 - .../main/java/adminuser/entity/Gender.java | 51 - .../src/main/java/adminuser/entity/User.java | 31 - .../service/AdminUserServiceImpl.java | 52 +- .../src/main/resources/application.yml | 4 + .../service/AdminUserServiceImplTest.java | 2 +- ts-assurance-service/pom.xml | 17 +- .../java/assurance/AssuranceApplication.java | 4 + .../controller/AssuranceController.java | 16 +- .../main/java/assurance/entity/Assurance.java | 17 +- .../java/assurance/entity/PlainAssurance.java | 4 +- .../main/java/assurance/init/InitData.java | 65 + .../repository/AssuranceRepository.java | 20 +- .../assurance/service/AssuranceService.java | 3 + .../service/AssuranceServiceImpl.java | 55 +- .../src/main/resources/application.yml | 28 +- .../service/AssuranceServiceImplTest.java | 42 +- ts-auth-service/pom.xml | 9 +- .../src/main/java/auth/AuthApplication.java | 5 +- .../java/auth/controller/AuthController.java | 2 +- .../java/auth/controller/UserController.java | 8 +- .../src/main/java/auth/dto/TokenDto.java | 2 +- .../src/main/java/auth/entity/User.java | 19 +- .../src/main/java/auth/init/InitUser.java | 4 +- .../java/auth/repository/UserRepository.java | 6 +- .../auth/security/UserDetailsServiceImpl.java | 2 +- .../main/java/auth/service/UserService.java | 2 +- .../auth/service/impl/TokenServiceImpl.java | 22 +- .../auth/service/impl/UserServiceImpl.java | 16 +- .../src/main/resources/application.yaml | 23 +- .../auth/controller/UserControllerTest.java | 2 +- .../auth/service/UserServiceImplTest.java | 4 +- ts-basic-service/pom.xml | 9 +- .../fdse/microservice/BasicApplication.java | 4 + .../controller/BasicController.java | 15 +- .../java/fdse/microservice/entity/Route.java | 28 - .../fdse/microservice/entity/TrainType.java | 29 - .../java/fdse/microservice/entity/Travel.java | 24 - .../microservice/entity/TravelResult.java | 25 - .../java/fdse/microservice/entity/Trip.java | 73 - .../java/fdse/microservice/entity/TripId.java | 40 - .../java/fdse/microservice/entity/Type.java | 63 - .../microservice/service/BasicService.java | 7 +- .../service/BasicServiceImpl.java | 396 +- .../src/main/resources/application.yml | 4 + .../controller/BasicControllerTest.java | 2 +- .../service/BasicServiceImplTest.java | 19 +- ts-cancel-service/pom.xml | 4 +- .../main/java/cancel/CancelApplication.java | 4 + .../cancel/controller/CancelController.java | 6 +- .../src/main/java/cancel/entity/Account.java | 38 - .../main/java/cancel/entity/DocumentType.java | 50 - .../cancel/entity/GetAccountByIdResult.java | 2 + .../main/java/cancel/entity/NotifyInfo.java | 26 - .../src/main/java/cancel/entity/Order.java | 108 - .../main/java/cancel/entity/OrderStatus.java | 63 - .../main/java/cancel/entity/SeatClass.java | 70 - .../src/main/java/cancel/entity/User.java | 31 - .../main/java/cancel/entity/VerifyResult.java | 19 - .../cancel/service/CancelServiceImpl.java | 109 +- .../src/main/resources/application.yml | 6 +- .../cancel/service/CancelServiceImplTest.java | 6 +- ts-common/pom.xml | 8 + .../fudan/common/config/SwaggerConfig.java | 2 +- .../edu/fudan/common}/entity/Account.java | 2 +- .../edu/fudan/common}/entity/AdminTrip.java | 9 +- .../edu/fudan/common}/entity/Assurance.java | 2 +- .../fudan/common}/entity/AssuranceType.java | 2 +- .../java/edu/fudan/common}/entity/Config.java | 2 +- .../edu/fudan/common}/entity/Consign.java | 13 +- .../edu/fudan/common}/entity/Contacts.java | 4 +- .../fudan/common}/entity/DocumentType.java | 2 +- .../java/edu/fudan/common}/entity/Food.java | 4 +- .../edu/fudan/common}/entity/FoodOrder.java | 6 +- .../java/edu/fudan/common}/entity/Gender.java | 2 +- .../fudan/common}/entity/LeftTicketInfo.java | 2 +- .../edu/fudan/common}/entity/NotifyInfo.java | 6 +- .../java/edu/fudan/common}/entity/Order.java | 35 +- .../fudan/common/entity/OrderAlterInfo.java | 24 + .../fudan/common}/entity/OrderSecurity.java | 2 +- .../edu/fudan/common}/entity/OrderStatus.java | 2 +- .../common}/entity/OrderTicketsInfo.java | 21 +- .../common}/entity/PaymentDifferenceInfo.java | 2 +- .../edu/fudan/common}/entity/PriceConfig.java | 2 +- .../java/edu/fudan/common/entity/Route.java | 45 + .../edu/fudan/common/entity/RouteInfo.java | 39 + .../fudan/common/entity/RoutePlanInfo.java | 35 + .../common/entity/RoutePlanResultUnit.java | 38 + .../java/edu/fudan/common}/entity/Seat.java | 16 +- .../edu/fudan/common}/entity/SeatClass.java | 2 +- .../edu/fudan/common}/entity/SoldTicket.java | 2 +- .../java/edu/fudan/common/entity/Station.java | 33 + .../fudan/common/entity/StationFoodStore.java | 8 +- .../java/edu/fudan/common}/entity/Ticket.java | 5 +- .../edu/fudan/common}/entity/TrainFood.java | 2 +- .../edu/fudan/common}/entity/TrainType.java | 21 +- .../java/edu/fudan/common}/entity/Travel.java | 7 +- .../edu/fudan/common/entity/TravelInfo.java | 51 + .../fudan/common}/entity/TravelResult.java | 4 +- .../java/edu/fudan/common/entity/Trip.java | 79 + .../fudan/common}/entity/TripAllDetail.java | 10 +- .../common/entity/TripAllDetailInfo.java | 43 + .../java/edu/fudan/common}/entity/TripId.java | 12 +- .../edu/fudan/common/entity/TripInfo.java | 47 + .../fudan/common}/entity/TripResponse.java | 35 +- .../java/edu/fudan/common}/entity/Type.java | 3 +- .../java/edu/fudan/common}/entity/User.java | 4 +- .../fudan/common}/entity/VerifyResult.java | 0 .../fudan/common/security/jwt/JWTUtil.java | 10 +- .../java/edu/fudan/common/util/JsonUtils.java | 6 +- .../edu/fudan/common/util/StringUtils.java | 35 + ts-config-service/pom.xml | 19 +- .../main/java/config/ConfigApplication.java | 4 + .../config/controller/ConfigController.java | 10 +- .../src/main/java/config/entity/Config.java | 6 +- .../config/service/ConfigServiceImpl.java | 20 +- .../src/main/resources/application.yml | 27 +- ts-consign-price-service/pom.xml | 15 +- .../consignprice/ConsignPriceApplication.java | 6 +- .../controller/ConsignPriceController.java | 8 +- .../consignprice/entity/ConsignPrice.java | 19 +- .../main/java/consignprice/init/InitData.java | 4 +- .../ConsignPriceConfigRepository.java | 7 +- .../service/ConsignPriceServiceImpl.java | 2 +- .../src/main/resources/application.yml | 20 +- .../service/ConsignPriceServiceImplTest.java | 12 +- ts-consign-service/pom.xml | 12 +- .../main/java/consign/ConsignApplication.java | 4 + .../consign/controller/ConsignController.java | 10 +- .../src/main/java/consign/entity/Consign.java | 15 +- .../java/consign/entity/ConsignRecord.java | 19 +- .../src/main/java/consign/init/InitData.java | 75 + .../consign/repository/ConsignRepository.java | 12 +- .../consign/service/ConsignServiceImpl.java | 52 +- .../src/main/resources/application.yml | 24 +- .../service/ConsignServiceImplTest.java | 24 +- ts-contacts-service/pom.xml | 15 +- .../java/contacts/ContactsApplication.java | 4 + .../controller/ContactsController.java | 24 +- .../main/java/contacts/entity/Contacts.java | 26 +- .../src/main/java/contacts/init/InitData.java | 8 +- .../repository/ContactsRepository.java | 21 +- .../contacts/service/ContactsService.java | 6 +- .../contacts/service/ContactsServiceImpl.java | 49 +- .../src/main/resources/application.yml | 21 +- .../controller/ContactsControllerTest.java | 6 +- .../service/ContactsServiceImplTest.java | 45 +- ts-delivery-service/pom.xml | 22 +- .../java/delivery/DeliveryApplication.java | 4 + .../main/java/delivery/entity/Delivery.java | 16 +- .../main/java/delivery/mq/RabbitReceive.java | 10 +- .../repository/DeliveryRepository.java | 16 +- .../src/main/resources/application.yml | 22 +- ts-execute-service/pom.xml | 5 +- .../main/java/execute/ExecuteApplication.java | 4 + .../controller/ExecuteControlller.java | 4 +- .../src/main/java/execute/entity/Order.java | 110 - .../execute/serivce/ExecuteServiceImpl.java | 49 +- .../src/main/resources/application.yml | 4 + .../service/ExecuteServiceImplTest.java | 2 +- ts-food-delivery-service/Dockerfile | 8 + ts-food-delivery-service/pom.xml | 56 + .../FoodDeliveryApplication.java | 32 + .../food_delivery/config/SecurityConfig.java | 74 + .../controller/FoodDeliveryController.java | 81 + .../food_delivery/entity/DeliveryInfo.java | 13 + .../entity/FoodDeliveryOrder.java | 40 + .../java/food_delivery/entity/SeatInfo.java | 13 + .../entity/StationFoodStoreInfo.java | 31 + .../food_delivery/entity/TripOrderInfo.java | 13 + .../java/food_delivery/init/InitData.java | 54 + .../FoodDeliveryOrderRepository.java | 15 + .../service/FoodDeliveryService.java | 27 + .../service/FoodDeliveryServiceImpl.java | 172 + .../src/main/resources/application.yml | 26 + .../main/resources/food_delivery_orders.txt | 5 + .../FoodDeliveryControllerTest.java | 130 + .../service/FoodDeliveryServiceImplTest.java | 26 + .../food/controller/FoodStoreController.java | 49 - .../src/main/java/food/entity/FoodStore.java | 38 - .../src/main/java/food/entity/TrainFood.java | 30 - .../food/repository/FoodStoreRepository.java | 25 - .../food/repository/TrainFoodRepository.java | 24 - .../java/food/service/FoodMapService.java | 27 - .../java/food/service/FoodMapServiceImpl.java | 108 - .../src/main/resources/application.yml | 16 - .../controller/TrainFoodControllerTest.java | 63 - .../food/service/FoodMapServiceImplTest.java | 155 - ts-food-service/pom.xml | 16 +- .../main/java/foodsearch/FoodApplication.java | 4 + .../foodsearch/controller/FoodController.java | 12 +- .../java/foodsearch/entity/AllTripFood.java | 7 +- .../src/main/java/foodsearch/entity/Food.java | 18 - .../java/foodsearch/entity/FoodOrder.java | 16 +- .../main/java/foodsearch/entity/Route.java | 30 - .../repository/FoodOrderRepository.java | 14 +- .../foodsearch/service/FoodServiceImpl.java | 133 +- .../src/main/resources/application.yml | 38 +- .../service/FoodServiceImplTest.java | 23 +- .../Dockerfile | 6 +- ts-gateway-service/pom.xml | 55 + .../main/java/gateway/GatewayApplication.java | 12 +- .../java/gateway/GatewayConfiguration.java | 120 + .../src/main/resources/application.yml | 209 + ts-inside-payment-service/pom.xml | 15 +- .../InsidePaymentApplication.java | 4 + .../java/inside_payment/async/AsyncTask.java | 4 +- .../controller/InsidePaymentController.java | 16 +- .../java/inside_payment/entity/Money.java | 15 +- .../java/inside_payment/entity/Order.java | 110 - .../inside_payment/entity/OrderStatus.java | 63 - .../java/inside_payment/entity/Payment.java | 17 +- .../inside_payment/entity/PaymentInfo.java | 3 + .../java/inside_payment/entity/SeatClass.java | 70 - .../repository/AddMoneyRepository.java | 1 + .../repository/PaymentRepository.java | 4 +- .../service/InsidePaymentServiceImpl.java | 47 +- .../src/main/resources/application.yml | 25 +- .../service/InsidePaymentServiceImplTest.java | 3 +- ts-notification-service/pom.xml | 22 +- .../notification/NotificationApplication.java | 4 + .../controller/NotificationController.java | 4 +- .../java/notification/entity/NotifyInfo.java | 21 +- .../java/notification/mq/RabbitReceive.java | 21 +- .../repository/NotifyRepository.java | 11 +- .../service/NotificationServiceImpl.java | 24 +- .../src/main/resources/application.yml | 22 +- .../templates/order_changed_success.ftl | 2 +- .../templates/order_create_success.ftl | 2 +- .../resources/templates/preserve_success.ftl | 2 +- ts-order-other-service/pom.xml | 14 +- .../java/other/OrderOtherApplication.java | 4 + .../controller/OrderOtherController.java | 47 +- .../java/other/entity/LeftTicketInfo.java | 28 - .../src/main/java/other/entity/Order.java | 49 +- .../java/other/entity/OrderAlterInfo.java | 12 +- .../main/java/other/entity/OrderSecurity.java | 21 - .../main/java/other/entity/OrderStatus.java | 63 - .../src/main/java/other/entity/QueryInfo.java | 25 +- .../src/main/java/other/entity/Seat.java | 45 - .../src/main/java/other/entity/SeatClass.java | 70 - .../main/java/other/entity/SoldTicket.java | 47 - .../src/main/java/other/entity/Ticket.java | 21 - .../src/main/java/other/entity/TrainType.java | 74 - .../src/main/java/other/init/InitData.java | 15 +- .../repository/OrderOtherRepository.java | 23 +- .../java/other/service/OrderOtherService.java | 11 +- .../other/service/OrderOtherServiceImpl.java | 200 +- .../src/main/resources/application.yml | 27 +- .../controller/OrderOtherControllerTest.java | 2 +- .../service/OrderOtherServiceImplTest.java | 108 +- ts-order-service/pom.xml | 20 +- .../src/main/java/order/OrderApplication.java | 4 + .../order/controller/OrderController.java | 40 +- .../src/main/java/order/entity/Order.java | 45 +- .../java/order/entity/OrderAlterInfo.java | 12 +- .../src/main/java/order/entity/OrderInfo.java | 29 +- .../main/java/order/entity/OrderSecurity.java | 21 - .../main/java/order/entity/OrderStatus.java | 63 - .../src/main/java/order/entity/Seat.java | 43 - .../src/main/java/order/entity/SeatClass.java | 70 - .../main/java/order/entity/SoldTicket.java | 47 - .../src/main/java/order/entity/TrainType.java | 74 - .../src/main/java/order/init/InitData.java | 28 +- .../order/repository/OrderRepository.java | 20 +- .../main/java/order/service/OrderService.java | 5 +- .../java/order/service/OrderServiceImpl.java | 205 +- .../src/main/resources/application.yml | 22 +- .../order/controller/OrderControllerTest.java | 2 +- .../order/service/OrderServiceImplTest.java | 83 +- ts-payment-service/pom.xml | 22 +- .../com/trainticket/PaymentApplication.java | 12 + .../controller/PaymentController.java | 6 +- .../java/com/trainticket/entity/Money.java | 23 +- .../java/com/trainticket/entity/Payment.java | 18 +- .../java/com/trainticket/init/InitData.java | 32 + .../repository/PaymentRepository.java | 3 +- .../service/PaymentServiceImpl.java | 14 +- .../src/main/resources/application.yml | 24 +- .../service/PaymentServiceImplTest.java | 4 +- ts-preserve-other-service/pom.xml | 7 +- .../PreserveOtherApplication.java | 4 + .../controller/PreserveOtherController.java | 4 +- .../java/preserveOther/entity/Account.java | 38 - .../java/preserveOther/entity/Consign.java | 32 - .../java/preserveOther/entity/Contacts.java | 57 - .../java/preserveOther/entity/FoodOrder.java | 34 - .../java/preserveOther/entity/Gender.java | 51 - .../java/preserveOther/entity/NotifyInfo.java | 26 - .../main/java/preserveOther/entity/Order.java | 108 - .../preserveOther/entity/OrderStatus.java | 63 - .../main/java/preserveOther/entity/Seat.java | 29 - .../java/preserveOther/entity/SeatClass.java | 70 - .../java/preserveOther/entity/Ticket.java | 21 - .../java/preserveOther/entity/TrainType.java | 31 - .../main/java/preserveOther/entity/Trip.java | 72 - .../preserveOther/entity/TripAllDetail.java | 27 - .../entity/TripAllDetailInfo.java | 25 - .../java/preserveOther/entity/TripId.java | 41 - .../preserveOther/entity/TripResponse.java | 49 - .../main/java/preserveOther/entity/Type.java | 63 - .../main/java/preserveOther/entity/User.java | 31 - .../service/PreserveOtherService.java | 3 +- .../service/PreserveOtherServiceImpl.java | 173 +- .../src/main/resources/application.yml | 6 +- .../PreserveOtherControllerTest.java | 2 +- .../service/PreserveOtherServiceImplTest.java | 17 +- ts-preserve-service/pom.xml | 7 +- .../java/preserve/PreserveApplication.java | 4 + .../controller/PreserveController.java | 4 +- .../main/java/preserve/entity/Account.java | 38 - .../main/java/preserve/entity/Assurance.java | 39 - .../java/preserve/entity/AssuranceType.java | 69 - .../main/java/preserve/entity/Contacts.java | 57 - .../java/preserve/entity/DocumentType.java | 50 - .../src/main/java/preserve/entity/Gender.java | 51 - .../src/main/java/preserve/entity/Order.java | 103 - .../preserve/entity/OrderTicketsInfo.java | 58 - .../preserve/entity/OrderTicketsResult.java | 21 - .../src/main/java/preserve/entity/Seat.java | 29 - .../main/java/preserve/entity/SeatClass.java | 70 - .../src/main/java/preserve/entity/Ticket.java | 21 - .../main/java/preserve/entity/TrainType.java | 31 - .../src/main/java/preserve/entity/Travel.java | 25 - .../java/preserve/entity/TravelResult.java | 24 - .../src/main/java/preserve/entity/Trip.java | 73 - .../preserve/entity/TripAllDetailInfo.java | 25 - .../src/main/java/preserve/entity/TripId.java | 41 - .../java/preserve/entity/TripResponse.java | 47 - .../src/main/java/preserve/entity/Type.java | 63 - .../preserve/service/PreserveService.java | 2 +- .../preserve/service/PreserveServiceImpl.java | 177 +- .../src/main/resources/application.yml | 8 +- .../controller/PreserveControllerTest.java | 2 +- .../service/PreserveServiceImplTest.java | 17 +- ts-price-service/pom.xml | 43 +- .../src/main/java/price/PriceApplication.java | 4 + .../price/controller/PriceController.java | 27 +- .../main/java/price/entity/PriceConfig.java | 16 +- .../src/main/java/price/init/InitData.java | 20 +- .../repository/PriceConfigRepository.java | 16 +- .../main/java/price/service/PriceService.java | 7 +- .../java/price/service/PriceServiceImpl.java | 79 +- .../src/main/resources/application.yml | 22 +- .../price/controller/PriceControllerTest.java | 2 +- .../price/service/PriceServiceImplTest.java | 18 +- ts-rebook-service/pom.xml | 9 +- .../main/java/rebook/RebookApplication.java | 4 + .../rebook/controller/RebookController.java | 4 +- .../src/main/java/rebook/entity/Contacts.java | 56 - .../main/java/rebook/entity/OrderStatus.java | 63 - .../java/rebook/entity/OrderTicketsInfo.java | 33 - .../main/java/rebook/entity/RebookInfo.java | 5 +- .../main/java/rebook/entity/SeatClass.java | 70 - .../src/main/java/rebook/entity/Ticket.java | 21 - .../src/main/java/rebook/entity/Trip.java | 50 - .../java/rebook/entity/TripAllDetail.java | 19 - .../java/rebook/entity/TripAllDetailInfo.java | 25 - .../main/java/rebook/entity/TripResponse.java | 73 - .../rebook/service/RebookServiceImpl.java | 148 +- .../src/main/resources/application.yml | 6 +- .../rebook/service/RebookServiceImplTest.java | 17 +- ts-route-plan-service/pom.xml | 4 +- .../main/java/plan/RoutePlanApplication.java | 4 + .../plan/controller/RoutePlanController.java | 8 +- .../src/main/java/plan/entity/Route.java | 29 - .../main/java/plan/entity/RoutePlanInfo.java | 32 - .../java/plan/entity/RoutePlanResultUnit.java | 36 - .../src/main/java/plan/entity/Trip.java | 49 - .../main/java/plan/entity/TripAllDetail.java | 23 - .../java/plan/entity/TripAllDetailInfo.java | 25 - .../src/main/java/plan/entity/TripId.java | 39 - .../src/main/java/plan/entity/TripInfo.java | 23 - .../main/java/plan/entity/TripResponse.java | 37 - .../src/main/java/plan/entity/Type.java | 63 - .../java/plan/service/RoutePlanService.java | 2 +- .../plan/service/RoutePlanServiceImpl.java | 119 +- .../src/main/resources/application.yml | 6 +- .../controller/RoutePlanControllerTest.java | 2 +- .../service/RoutePlanServiceImplTest.java | 14 +- ts-route-service/pom.xml | 11 +- .../src/main/java/route/RouteApplication.java | 4 + .../route/controller/RouteController.java | 26 +- .../src/main/java/route/entity/Route.java | 42 +- .../src/main/java/route/entity/RouteInfo.java | 8 +- .../route/repository/RouteRepository.java | 27 +- .../main/java/route/service/RouteService.java | 13 +- .../java/route/service/RouteServiceImpl.java | 73 +- .../src/main/resources/application.yml | 22 +- .../route/controller/RouteControllerTest.java | 2 +- .../route/service/RouteServiceImplTest.java | 11 +- ts-seat-service/pom.xml | 9 +- .../src/main/java/seat/SeatApplication.java | 4 + .../java/seat/controller/SeatController.java | 6 +- .../src/main/java/seat/entity/Config.java | 26 - .../main/java/seat/entity/LeftTicketInfo.java | 28 - .../src/main/java/seat/entity/Route.java | 29 - .../src/main/java/seat/entity/Seat.java | 54 - .../src/main/java/seat/entity/SeatClass.java | 70 - .../src/main/java/seat/entity/Ticket.java | 21 - .../src/main/java/seat/entity/TrainType.java | 40 - .../main/java/seat/service/SeatService.java | 2 +- .../java/seat/service/SeatServiceImpl.java | 186 +- .../src/main/resources/application.yml | 6 +- .../seat/controller/SeatControllerTest.java | 2 +- .../seat/service/SeatServiceImplTest.java | 2 +- ts-security-service/pom.xml | 11 +- .../java/security/SecurityApplication.java | 4 + .../controller/SecurityController.java | 10 +- .../src/main/java/security/entity/Order.java | 110 - .../java/security/entity/OrderStatus.java | 63 - .../main/java/security/entity/SeatClass.java | 70 - .../java/security/entity/SecurityConfig.java | 16 +- .../repository/SecurityRepository.java | 16 +- .../security/service/SecurityServiceImpl.java | 53 +- .../src/main/resources/application.yml | 32 +- .../service/SecurityServiceImplTest.java | 15 +- ts-station-food-service/Dockerfile | 8 + .../pom.xml | 26 +- .../java/food/StationFoodApplication.java | 11 +- .../main/java/food/config/SecurityConfig.java | 2 +- .../controller/StationFoodController.java | 54 + .../java/food/entity/StationFoodStore.java | 47 + .../src/main/java/food/init/InitData.java | 57 +- .../repository/StationFoodRepository.java | 26 + .../java/food/service/StationFoodService.java | 30 + .../food/service/StationFoodServiceImpl.java | 121 + .../src/main/resources/application.yml | 25 + .../src/main/resources/foodstores.txt | 0 .../controller/StationFoodControllerTest.java | 26 +- .../service/StationFoodServiceImplTest.java | 155 + ts-station-service/pom.xml | 18 +- .../fdse/microservice/StationApplication.java | 12 + .../controller/StationController.java | 20 +- .../fdse/microservice/entity/Station.java | 32 +- .../java/fdse/microservice/init/InitData.java | 27 +- .../repository/StationRepository.java | 10 +- .../microservice/service/StationService.java | 2 +- .../service/StationServiceImpl.java | 66 +- .../src/main/resources/application.yml | 19 +- .../controller/StationControllerTest.java | 2 +- .../service/StationServiceImplTest.java | 16 +- ts-ticket-office-service/app.js | 4 +- ts-ticket-office-service/bin/db.js | 175 +- ts-ticket-office-service/bin/router.js | 2 + .../node_modules/.bin/acorn | 16 +- .../node_modules/.bin/cleancss | 16 +- .../node_modules/.bin/jade | 16 +- .../node_modules/.bin/mime | 16 +- .../node_modules/.bin/mkdirp | 16 +- .../node_modules/.bin/semver | 15 - .../node_modules/.bin/uglifyjs | 16 +- .../node_modules/.package-lock.json | 1157 ++ .../node_modules/@types/node/LICENSE | 21 + .../node_modules/@types/node/README.md | 16 + .../node_modules/@types/node/assert.d.ts | 911 + .../@types/node/assert/strict.d.ts | 8 + .../node_modules/@types/node/async_hooks.d.ts | 501 + .../node_modules/@types/node/buffer.d.ts | 2238 +++ .../@types/node/child_process.d.ts | 1369 ++ .../node_modules/@types/node/cluster.d.ts | 410 + .../node_modules/@types/node/console.d.ts | 412 + .../node_modules/@types/node/constants.d.ts | 18 + .../node_modules/@types/node/crypto.d.ts | 3964 ++++ .../node_modules/@types/node/dgram.d.ts | 545 + .../@types/node/diagnostics_channel.d.ts | 153 + .../node_modules/@types/node/dns.d.ts | 659 + .../@types/node/dns/promises.d.ts | 370 + .../node_modules/@types/node/domain.d.ts | 170 + .../node_modules/@types/node/events.d.ts | 641 + .../node_modules/@types/node/fs.d.ts | 3858 ++++ .../node_modules/@types/node/fs/promises.d.ts | 1114 + .../node_modules/@types/node/globals.d.ts | 294 + .../@types/node/globals.global.d.ts | 1 + .../node_modules/@types/node/http.d.ts | 1452 ++ .../node_modules/@types/node/http2.d.ts | 2106 ++ .../node_modules/@types/node/https.d.ts | 401 + .../node_modules/@types/node/index.d.ts | 131 + .../node_modules/@types/node/inspector.d.ts | 2741 +++ .../node_modules/@types/node/module.d.ts | 114 + .../node_modules/@types/node/net.d.ts | 816 + .../node_modules/@types/node/os.d.ts | 456 + .../node_modules/@types/node/package.json | 225 + .../node_modules/@types/node/path.d.ts | 180 + .../node_modules/@types/node/perf_hooks.d.ts | 571 + .../node_modules/@types/node/process.d.ts | 1482 ++ .../node_modules/@types/node/punycode.d.ts | 117 + .../node_modules/@types/node/querystring.d.ts | 131 + .../node_modules/@types/node/readline.d.ts | 650 + .../node_modules/@types/node/repl.d.ts | 424 + .../node_modules/@types/node/stream.d.ts | 1339 ++ .../@types/node/stream/consumers.d.ts | 24 + .../@types/node/stream/promises.d.ts | 42 + .../node_modules/@types/node/stream/web.d.ts | 330 + .../@types/node/string_decoder.d.ts | 67 + .../node_modules/@types/node/test.d.ts | 176 + .../node_modules/@types/node/timers.d.ts | 94 + .../@types/node/timers/promises.d.ts | 68 + .../node_modules/@types/node/tls.d.ts | 1028 + .../@types/node/trace_events.d.ts | 171 + .../node_modules/@types/node/tty.d.ts | 206 + .../node_modules/@types/node/url.d.ts | 897 + .../node_modules/@types/node/util.d.ts | 1605 ++ .../node_modules/@types/node/v8.d.ts | 396 + .../node_modules/@types/node/vm.d.ts | 509 + .../node_modules/@types/node/wasi.d.ts | 158 + .../@types/node/worker_threads.d.ts | 646 + .../node_modules/@types/node/zlib.d.ts | 517 + .../@types/webidl-conversions/LICENSE | 21 + .../@types/webidl-conversions/README.md | 16 + .../@types/webidl-conversions/index.d.ts | 103 + .../@types/webidl-conversions/package.json | 25 + .../node_modules/@types/whatwg-url/LICENSE | 21 + .../node_modules/@types/whatwg-url/README.md | 16 + .../node_modules/@types/whatwg-url/index.d.ts | 162 + .../@types/whatwg-url/package.json | 33 + .../@types/whatwg-url/webidl2js-wrapper.d.ts | 4 + .../node_modules/acorn/bin/acorn | 0 .../license => base64-js/LICENSE} | 2 +- .../node_modules/base64-js/README.md | 34 + .../node_modules/base64-js/base64js.min.js | 1 + .../node_modules/base64-js/index.d.ts | 3 + .../node_modules/base64-js/index.js | 150 + .../node_modules/base64-js/package.json | 47 + .../node_modules/bignumber.js/CHANGELOG.md | 266 + .../node_modules/bignumber.js/LICENCE | 23 + .../node_modules/bignumber.js/README.md | 268 + .../node_modules/bignumber.js/bignumber.d.ts | 1829 ++ .../node_modules/bignumber.js/bignumber.js | 2902 +++ .../bignumber.js/bignumber.min.js | 1 + .../bignumber.js/bignumber.min.js.map | 1 + .../node_modules/bignumber.js/bignumber.mjs | 2888 +++ .../node_modules/bignumber.js/doc/API.html | 2237 +++ .../node_modules/bignumber.js/package.json | 40 + .../node_modules/bson/HISTORY.md | 199 - .../node_modules/bson/README.md | 407 +- .../node_modules/bson/bower.json | 5 +- .../node_modules/bson/browser_build/bson.js | 16734 ---------------- .../bson/browser_build/package.json | 8 - .../node_modules/bson/bson.d.ts | 1235 ++ .../node_modules/bson/etc/prepare.js | 19 + .../node_modules/bson/index.js | 46 - .../node_modules/bson/lib/binary.js | 247 + .../node_modules/bson/lib/binary.js.map | 1 + .../node_modules/bson/lib/bson.js | 265 + .../node_modules/bson/lib/bson.js.map | 1 + .../node_modules/bson/lib/bson/binary.js | 347 - .../node_modules/bson/lib/bson/bson.js | 358 - .../node_modules/bson/lib/bson/code.js | 24 - .../node_modules/bson/lib/bson/db_ref.js | 32 - .../node_modules/bson/lib/bson/decimal128.js | 728 - .../node_modules/bson/lib/bson/double.js | 33 - .../bson/lib/bson/float_parser.js | 121 - .../node_modules/bson/lib/bson/int_32.js | 26 - .../node_modules/bson/lib/bson/long.js | 856 - .../node_modules/bson/lib/bson/map.js | 126 - .../node_modules/bson/lib/bson/max_key.js | 14 - .../node_modules/bson/lib/bson/min_key.js | 14 - .../node_modules/bson/lib/bson/objectid.js | 362 - .../bson/lib/bson/parser/calculate_size.js | 152 - .../bson/lib/bson/parser/deserializer.js | 653 - .../bson/lib/bson/parser/serializer.js | 1001 - .../node_modules/bson/lib/bson/regexp.js | 30 - .../node_modules/bson/lib/bson/symbol.js | 47 - .../node_modules/bson/lib/bson/timestamp.js | 856 - .../node_modules/bson/lib/code.js | 46 + .../node_modules/bson/lib/code.js.map | 1 + .../node_modules/bson/lib/constants.js | 82 + .../node_modules/bson/lib/constants.js.map | 1 + .../node_modules/bson/lib/db_ref.js | 97 + .../node_modules/bson/lib/db_ref.js.map | 1 + .../node_modules/bson/lib/decimal128.js | 669 + .../node_modules/bson/lib/decimal128.js.map | 1 + .../node_modules/bson/lib/double.js | 76 + .../node_modules/bson/lib/double.js.map | 1 + .../node_modules/bson/lib/ensure_buffer.js | 25 + .../bson/lib/ensure_buffer.js.map | 1 + .../node_modules/bson/lib/error.js | 55 + .../node_modules/bson/lib/error.js.map | 1 + .../node_modules/bson/lib/extended_json.js | 390 + .../bson/lib/extended_json.js.map | 1 + .../node_modules/bson/lib/int_32.js | 58 + .../node_modules/bson/lib/int_32.js.map | 1 + .../node_modules/bson/lib/long.js | 900 + .../node_modules/bson/lib/long.js.map | 1 + .../node_modules/bson/lib/map.js | 123 + .../node_modules/bson/lib/map.js.map | 1 + .../node_modules/bson/lib/max_key.js | 33 + .../node_modules/bson/lib/max_key.js.map | 1 + .../node_modules/bson/lib/min_key.js | 33 + .../node_modules/bson/lib/min_key.js.map | 1 + .../node_modules/bson/lib/objectid.js | 299 + .../node_modules/bson/lib/objectid.js.map | 1 + .../bson/lib/parser/calculate_size.js | 194 + .../bson/lib/parser/calculate_size.js.map | 1 + .../bson/lib/parser/deserializer.js | 659 + .../bson/lib/parser/deserializer.js.map | 1 + .../bson/lib/parser/serializer.js | 867 + .../bson/lib/parser/serializer.js.map | 1 + .../node_modules/bson/lib/parser/utils.js | 115 + .../node_modules/bson/lib/parser/utils.js.map | 1 + .../node_modules/bson/lib/regexp.js | 74 + .../node_modules/bson/lib/regexp.js.map | 1 + .../node_modules/bson/lib/symbol.js | 48 + .../node_modules/bson/lib/symbol.js.map | 1 + .../node_modules/bson/lib/timestamp.js | 102 + .../node_modules/bson/lib/timestamp.js.map | 1 + .../node_modules/bson/lib/utils/global.js | 18 + .../node_modules/bson/lib/utils/global.js.map | 1 + .../node_modules/bson/lib/uuid.js | 179 + .../node_modules/bson/lib/uuid.js.map | 1 + .../node_modules/bson/lib/uuid_utils.js | 35 + .../node_modules/bson/lib/uuid_utils.js.map | 1 + .../node_modules/bson/lib/validate_utf8.js | 47 + .../bson/lib/validate_utf8.js.map | 1 + .../node_modules/bson/package.json | 205 +- .../node_modules/bson/src/binary.ts | 294 + .../node_modules/bson/src/bson.ts | 335 + .../node_modules/bson/src/code.ts | 61 + .../node_modules/bson/src/constants.ts | 110 + .../node_modules/bson/src/db_ref.ts | 124 + .../node_modules/bson/src/decimal128.ts | 773 + .../node_modules/bson/src/double.ts | 91 + .../node_modules/bson/src/ensure_buffer.ts | 27 + .../node_modules/bson/src/error.ts | 23 + .../node_modules/bson/src/extended_json.ts | 462 + .../node_modules/bson/src/int_32.ts | 70 + .../node_modules/bson/src/long.ts | 1040 + .../node_modules/bson/src/map.ts | 119 + .../node_modules/bson/src/max_key.ts | 38 + .../node_modules/bson/src/min_key.ts | 38 + .../node_modules/bson/src/objectid.ts | 354 + .../bson/src/parser/calculate_size.ts | 228 + .../bson/src/parser/deserializer.ts | 777 + .../bson/src/parser/serializer.ts | 1076 + .../node_modules/bson/src/parser/utils.ts | 127 + .../node_modules/bson/src/regexp.ts | 105 + .../node_modules/bson/src/symbol.ts | 58 + .../node_modules/bson/src/timestamp.ts | 119 + .../node_modules/bson/src/utils/global.ts | 22 + .../node_modules/bson/src/uuid.ts | 209 + .../node_modules/bson/src/uuid_utils.ts | 33 + .../node_modules/bson/src/validate_utf8.ts | 47 + .../node_modules/buffer-shims/index.js | 108 - .../node_modules/buffer-shims/package.json | 85 - .../node_modules/buffer-shims/readme.md | 21 - .../node_modules/buffer/AUTHORS.md | 70 + .../node_modules/buffer/LICENSE | 21 + .../node_modules/buffer/README.md | 410 + .../node_modules/buffer/index.d.ts | 186 + .../node_modules/buffer/index.js | 1817 ++ .../node_modules/buffer/package.json | 96 + .../node_modules/clean-css/bin/cleancss | 0 .../node_modules/denque/CHANGELOG.md | 29 + .../{require_optional => denque}/LICENSE | 4 +- .../node_modules/denque/README.md | 77 + .../node_modules/denque/index.d.ts | 47 + .../node_modules/denque/index.js | 481 + .../node_modules/denque/package.json | 58 + .../node_modules/es6-promise/CHANGELOG.md | 65 - .../node_modules/es6-promise/README.md | 74 - .../es6-promise/dist/es6-promise.js | 959 - .../es6-promise/dist/es6-promise.min.js | 9 - .../es6-promise/lib/es6-promise.umd.js | 18 - .../es6-promise/lib/es6-promise/-internal.js | 273 - .../es6-promise/lib/es6-promise/asap.js | 119 - .../es6-promise/lib/es6-promise/enumerator.js | 118 - .../es6-promise/lib/es6-promise/polyfill.js | 26 - .../es6-promise/lib/es6-promise/promise.js | 384 - .../lib/es6-promise/promise/all.js | 52 - .../lib/es6-promise/promise/race.js | 86 - .../lib/es6-promise/promise/reject.js | 46 - .../lib/es6-promise/promise/resolve.js | 48 - .../es6-promise/lib/es6-promise/then.js | 34 - .../es6-promise/lib/es6-promise/utils.js | 22 - .../node_modules/es6-promise/package.json | 130 - .../node_modules/ieee754/LICENSE | 11 + .../node_modules/ieee754/README.md | 51 + .../node_modules/ieee754/index.d.ts | 10 + .../node_modules/ieee754/index.js | 85 + .../node_modules/ieee754/package.json | 52 + .../node_modules/ip/README.md | 90 + .../node_modules/ip/lib/ip.js | 422 + .../node_modules/ip/package.json | 25 + .../node_modules/jade/bin/jade.js | 0 .../{es6-promise => memory-pager}/LICENSE | 24 +- .../node_modules/memory-pager/README.md | 65 + .../node_modules/memory-pager/index.js | 160 + .../node_modules/memory-pager/package.json | 24 + .../node_modules/memory-pager/test.js | 80 + .../node_modules/mime/cli.js | 0 .../node_modules/minimist/.travis.yml | 4 + .../node_modules/minimist/example/parse.js | 2 +- .../node_modules/minimist/index.js | 168 +- .../node_modules/minimist/package.json | 104 +- .../node_modules/minimist/readme.markdown | 37 +- .../node_modules/minimist/test/all_bool.js | 32 + .../node_modules/minimist/test/bool.js | 178 + .../node_modules/minimist/test/dash.js | 7 + .../minimist/test/default_bool.js | 15 + .../node_modules/minimist/test/dotted.js | 6 + .../node_modules/minimist/test/kv_short.js | 16 + .../node_modules/minimist/test/num.js | 36 + .../node_modules/minimist/test/parse.js | 167 +- .../minimist/test/parse_modified.js | 2 +- .../node_modules/minimist/test/proto.js | 60 + .../node_modules/minimist/test/stop_early.js | 15 + .../node_modules/minimist/test/unknown.js | 102 + .../node_modules/mkdirp/.travis.yml | 8 - .../node_modules/mkdirp/bin/cmd.js | 0 .../node_modules/mkdirp/examples/pow.js | 6 - .../node_modules/mkdirp/index.js | 12 +- .../node_modules/mkdirp/package.json | 98 +- .../node_modules/mkdirp/readme.markdown | 4 +- .../node_modules/mkdirp/test/chmod.js | 41 - .../node_modules/mkdirp/test/clobber.js | 38 - .../node_modules/mkdirp/test/mkdirp.js | 28 - .../node_modules/mkdirp/test/opts_fs.js | 29 - .../node_modules/mkdirp/test/opts_fs_sync.js | 27 - .../node_modules/mkdirp/test/perm.js | 32 - .../node_modules/mkdirp/test/perm_sync.js | 36 - .../node_modules/mkdirp/test/race.js | 37 - .../node_modules/mkdirp/test/rel.js | 32 - .../node_modules/mkdirp/test/return.js | 25 - .../node_modules/mkdirp/test/return_sync.js | 24 - .../node_modules/mkdirp/test/root.js | 19 - .../node_modules/mkdirp/test/sync.js | 32 - .../node_modules/mkdirp/test/umask.js | 28 - .../node_modules/mkdirp/test/umask_sync.js | 32 - .../.esm-wrapper.mjs | 6 + .../LICENSE | 19 +- .../mongodb-connection-string-url/README.md | 25 + .../lib/index.d.ts | 62 + .../lib/index.js | 213 + .../lib/index.js.map | 1 + .../lib/redact.d.ts | 7 + .../lib/redact.js | 87 + .../lib/redact.js.map | 1 + .../package.json | 62 + .../node_modules/mongodb-core/.coveralls.yml | 1 - .../node_modules/mongodb-core/.eslintrc | 15 - .../node_modules/mongodb-core/HISTORY.md | 691 - .../node_modules/mongodb-core/Makefile | 11 - .../node_modules/mongodb-core/README.md | 228 - .../node_modules/mongodb-core/TESTING.md | 18 - .../mongodb-core/THIRD-PARTY-NOTICES | 41 - .../node_modules/mongodb-core/conf.json | 59 - .../node_modules/mongodb-core/index.js | 32 - .../mongodb-core/lib/auth/gssapi.js | 262 - .../mongodb-core/lib/auth/mongocr.js | 181 - .../mongodb-core/lib/auth/plain.js | 170 - .../mongodb-core/lib/auth/scram.js | 339 - .../mongodb-core/lib/auth/sspi.js | 250 - .../mongodb-core/lib/auth/x509.js | 164 - .../lib/connection/command_result.js | 34 - .../mongodb-core/lib/connection/commands.js | 546 - .../mongodb-core/lib/connection/connection.js | 611 - .../mongodb-core/lib/connection/logger.js | 228 - .../mongodb-core/lib/connection/pool.js | 1387 -- .../mongodb-core/lib/connection/utils.js | 86 - .../node_modules/mongodb-core/lib/cursor.js | 702 - .../node_modules/mongodb-core/lib/error.js | 44 - .../mongodb-core/lib/tools/smoke_plugin.js | 59 - .../mongodb-core/lib/topologies/mongos.js | 1307 -- .../lib/topologies/read_preference.js | 118 - .../mongodb-core/lib/topologies/replset.js | 1454 -- .../lib/topologies/replset_state.js | 1001 - .../mongodb-core/lib/topologies/server.js | 880 - .../mongodb-core/lib/topologies/shared.js | 328 - .../node_modules/mongodb-core/lib/utils.js | 32 - .../lib/wireprotocol/2_4_support.js | 570 - .../lib/wireprotocol/2_6_support.js | 334 - .../lib/wireprotocol/3_2_support.js | 549 - .../mongodb-core/lib/wireprotocol/commands.js | 357 - .../mongodb-core/lib/wireprotocol/shared.js | 27 - .../node_modules/mongodb-core/package.json | 114 - .../node_modules/mongodb-core/test.js | 71 - .../node_modules/mongodb-core/test1.js | 72 - .../node_modules/mongodb-core/yarn.lock | 2588 --- .../node_modules/mongodb/.coveralls.yml | 1 - .../node_modules/mongodb/.eslintrc | 15 - .../node_modules/mongodb/HISTORY.md | 1748 -- .../LICENSE => mongodb/LICENSE.md} | 0 .../node_modules/mongodb/Makefile | 11 - .../node_modules/mongodb/README.md | 473 +- .../node_modules/mongodb/THIRD-PARTY-NOTICES | 41 - .../node_modules/mongodb/boot_auth.js | 52 - .../node_modules/mongodb/conf.json | 76 - .../node_modules/mongodb/etc/prepare.js | 12 + .../node_modules/mongodb/index.js | 56 - .../node_modules/mongodb/insert_bench.js | 231 - .../node_modules/mongodb/lib/admin.js | 666 +- .../node_modules/mongodb/lib/admin.js.map | 1 + .../mongodb/lib/aggregation_cursor.js | 438 - .../node_modules/mongodb/lib/apm.js | 596 - .../node_modules/mongodb/lib/authenticate.js | 109 - .../node_modules/mongodb/lib/bson.js | 69 + .../node_modules/mongodb/lib/bson.js.map | 1 + .../node_modules/mongodb/lib/bulk/common.js | 1356 +- .../mongodb/lib/bulk/common.js.map | 1 + .../node_modules/mongodb/lib/bulk/ordered.js | 597 +- .../mongodb/lib/bulk/ordered.js.map | 1 + .../mongodb/lib/bulk/unordered.js | 624 +- .../mongodb/lib/bulk/unordered.js.map | 1 + .../node_modules/mongodb/lib/change_stream.js | 374 + .../mongodb/lib/change_stream.js.map | 1 + .../mongodb/lib/cmap/auth/auth_provider.js | 36 + .../lib/cmap/auth/auth_provider.js.map | 1 + .../mongodb/lib/cmap/auth/gssapi.js | 190 + .../mongodb/lib/cmap/auth/gssapi.js.map | 1 + .../lib/cmap/auth/mongo_credentials.js | 134 + .../lib/cmap/auth/mongo_credentials.js.map | 1 + .../mongodb/lib/cmap/auth/mongocr.js | 44 + .../mongodb/lib/cmap/auth/mongocr.js.map | 1 + .../mongodb/lib/cmap/auth/mongodb_aws.js | 204 + .../mongodb/lib/cmap/auth/mongodb_aws.js.map | 1 + .../mongodb/lib/cmap/auth/plain.js | 27 + .../mongodb/lib/cmap/auth/plain.js.map | 1 + .../mongodb/lib/cmap/auth/providers.js | 21 + .../mongodb/lib/cmap/auth/providers.js.map | 1 + .../mongodb/lib/cmap/auth/scram.js | 288 + .../mongodb/lib/cmap/auth/scram.js.map | 1 + .../mongodb/lib/cmap/auth/x509.js | 39 + .../mongodb/lib/cmap/auth/x509.js.map | 1 + .../lib/cmap/command_monitoring_events.js | 272 + .../lib/cmap/command_monitoring_events.js.map | 1 + .../node_modules/mongodb/lib/cmap/commands.js | 633 + .../mongodb/lib/cmap/commands.js.map | 1 + .../node_modules/mongodb/lib/cmap/connect.js | 390 + .../mongodb/lib/cmap/connect.js.map | 1 + .../mongodb/lib/cmap/connection.js | 532 + .../mongodb/lib/cmap/connection.js.map | 1 + .../mongodb/lib/cmap/connection_pool.js | 497 + .../mongodb/lib/cmap/connection_pool.js.map | 1 + .../lib/cmap/connection_pool_events.js | 147 + .../lib/cmap/connection_pool_events.js.map | 1 + .../node_modules/mongodb/lib/cmap/errors.js | 33 + .../mongodb/lib/cmap/errors.js.map | 1 + .../mongodb/lib/cmap/message_stream.js | 175 + .../mongodb/lib/cmap/message_stream.js.map | 1 + .../node_modules/mongodb/lib/cmap/metrics.js | 62 + .../mongodb/lib/cmap/metrics.js.map | 1 + .../mongodb/lib/cmap/stream_description.js | 51 + .../lib/cmap/stream_description.js.map | 1 + .../lib/cmap/wire_protocol/compression.js | 96 + .../lib/cmap/wire_protocol/compression.js.map | 1 + .../lib/cmap/wire_protocol/constants.js | 17 + .../lib/cmap/wire_protocol/constants.js.map | 1 + .../mongodb/lib/cmap/wire_protocol/shared.js | 55 + .../lib/cmap/wire_protocol/shared.js.map | 1 + .../node_modules/mongodb/lib/collection.js | 3870 +--- .../mongodb/lib/collection.js.map | 1 + .../mongodb/lib/command_cursor.js | 320 - .../mongodb/lib/connection_string.js | 1094 + .../mongodb/lib/connection_string.js.map | 1 + .../node_modules/mongodb/lib/constants.js | 129 + .../node_modules/mongodb/lib/constants.js.map | 1 + .../node_modules/mongodb/lib/cursor.js | 1208 -- .../mongodb/lib/cursor/abstract_cursor.js | 652 + .../mongodb/lib/cursor/abstract_cursor.js.map | 1 + .../mongodb/lib/cursor/aggregation_cursor.js | 172 + .../lib/cursor/aggregation_cursor.js.map | 1 + .../lib/cursor/change_stream_cursor.js | 115 + .../lib/cursor/change_stream_cursor.js.map | 1 + .../mongodb/lib/cursor/find_cursor.js | 382 + .../mongodb/lib/cursor/find_cursor.js.map | 1 + .../lib/cursor/list_collections_cursor.js | 37 + .../lib/cursor/list_collections_cursor.js.map | 1 + .../mongodb/lib/cursor/list_indexes_cursor.js | 36 + .../lib/cursor/list_indexes_cursor.js.map | 1 + .../node_modules/mongodb/lib/db.js | 2075 +- .../node_modules/mongodb/lib/db.js.map | 1 + .../node_modules/mongodb/lib/deps.js | 63 + .../node_modules/mongodb/lib/deps.js.map | 1 + .../node_modules/mongodb/lib/encrypter.js | 112 + .../node_modules/mongodb/lib/encrypter.js.map | 1 + .../node_modules/mongodb/lib/error.js | 799 + .../node_modules/mongodb/lib/error.js.map | 1 + .../node_modules/mongodb/lib/explain.js | 35 + .../node_modules/mongodb/lib/explain.js.map | 1 + .../mongodb/lib/gridfs-stream/download.js | 408 - .../mongodb/lib/gridfs-stream/index.js | 367 - .../mongodb/lib/gridfs-stream/upload.js | 527 - .../node_modules/mongodb/lib/gridfs/chunk.js | 230 - .../mongodb/lib/gridfs/download.js | 317 + .../mongodb/lib/gridfs/download.js.map | 1 + .../mongodb/lib/gridfs/grid_store.js | 1954 -- .../node_modules/mongodb/lib/gridfs/index.js | 152 + .../mongodb/lib/gridfs/index.js.map | 1 + .../node_modules/mongodb/lib/gridfs/upload.js | 376 + .../mongodb/lib/gridfs/upload.js.map | 1 + .../node_modules/mongodb/lib/index.js | 159 + .../node_modules/mongodb/lib/index.js.map | 1 + .../node_modules/mongodb/lib/logger.js | 217 + .../node_modules/mongodb/lib/logger.js.map | 1 + .../node_modules/mongodb/lib/metadata.js | 64 - .../node_modules/mongodb/lib/mongo_client.js | 775 +- .../mongodb/lib/mongo_client.js.map | 1 + .../node_modules/mongodb/lib/mongo_types.js | 41 + .../mongodb/lib/mongo_types.js.map | 1 + .../node_modules/mongodb/lib/mongos.js | 533 - .../mongodb/lib/operations/add_user.js | 72 + .../mongodb/lib/operations/add_user.js.map | 1 + .../mongodb/lib/operations/aggregate.js | 90 + .../mongodb/lib/operations/aggregate.js.map | 1 + .../mongodb/lib/operations/bulk_write.js | 43 + .../mongodb/lib/operations/bulk_write.js.map | 1 + .../mongodb/lib/operations/collections.js | 29 + .../mongodb/lib/operations/collections.js.map | 1 + .../mongodb/lib/operations/command.js | 95 + .../mongodb/lib/operations/command.js.map | 1 + .../lib/operations/common_functions.js | 71 + .../lib/operations/common_functions.js.map | 1 + .../mongodb/lib/operations/connect.js | 85 + .../mongodb/lib/operations/connect.js.map | 1 + .../mongodb/lib/operations/count.js | 39 + .../mongodb/lib/operations/count.js.map | 1 + .../mongodb/lib/operations/count_documents.js | 37 + .../lib/operations/count_documents.js.map | 1 + .../lib/operations/create_collection.js | 100 + .../lib/operations/create_collection.js.map | 1 + .../mongodb/lib/operations/delete.js | 135 + .../mongodb/lib/operations/delete.js.map | 1 + .../mongodb/lib/operations/distinct.js | 67 + .../mongodb/lib/operations/distinct.js.map | 1 + .../mongodb/lib/operations/drop.js | 84 + .../mongodb/lib/operations/drop.js.map | 1 + .../operations/estimated_document_count.js | 38 + .../estimated_document_count.js.map | 1 + .../mongodb/lib/operations/eval.js | 55 + .../mongodb/lib/operations/eval.js.map | 1 + .../lib/operations/execute_operation.js | 185 + .../lib/operations/execute_operation.js.map | 1 + .../mongodb/lib/operations/find.js | 162 + .../mongodb/lib/operations/find.js.map | 1 + .../mongodb/lib/operations/find_and_modify.js | 156 + .../lib/operations/find_and_modify.js.map | 1 + .../mongodb/lib/operations/get_more.js | 33 + .../mongodb/lib/operations/get_more.js.map | 1 + .../mongodb/lib/operations/indexes.js | 265 + .../mongodb/lib/operations/indexes.js.map | 1 + .../mongodb/lib/operations/insert.js | 99 + .../mongodb/lib/operations/insert.js.map | 1 + .../mongodb/lib/operations/is_capped.js | 30 + .../mongodb/lib/operations/is_capped.js.map | 1 + .../mongodb/lib/operations/kill_cursors.js | 22 + .../lib/operations/kill_cursors.js.map | 1 + .../lib/operations/list_collections.js | 46 + .../lib/operations/list_collections.js.map | 1 + .../mongodb/lib/operations/list_databases.js | 35 + .../lib/operations/list_databases.js.map | 1 + .../mongodb/lib/operations/map_reduce.js | 166 + .../mongodb/lib/operations/map_reduce.js.map | 1 + .../mongodb/lib/operations/operation.js | 70 + .../mongodb/lib/operations/operation.js.map | 1 + .../lib/operations/options_operation.js | 29 + .../lib/operations/options_operation.js.map | 1 + .../mongodb/lib/operations/profiling_level.js | 33 + .../lib/operations/profiling_level.js.map | 1 + .../mongodb/lib/operations/remove_user.js | 21 + .../mongodb/lib/operations/remove_user.js.map | 1 + .../mongodb/lib/operations/rename.js | 46 + .../mongodb/lib/operations/rename.js.map | 1 + .../mongodb/lib/operations/run_command.js | 26 + .../mongodb/lib/operations/run_command.js.map | 1 + .../lib/operations/set_profiling_level.js | 51 + .../lib/operations/set_profiling_level.js.map | 1 + .../mongodb/lib/operations/stats.js | 48 + .../mongodb/lib/operations/stats.js.map | 1 + .../mongodb/lib/operations/update.js | 200 + .../mongodb/lib/operations/update.js.map | 1 + .../lib/operations/validate_collection.js | 41 + .../lib/operations/validate_collection.js.map | 1 + .../mongodb/lib/promise_provider.js | 36 + .../mongodb/lib/promise_provider.js.map | 1 + .../node_modules/mongodb/lib/read_concern.js | 74 + .../mongodb/lib/read_concern.js.map | 1 + .../mongodb/lib/read_preference.js | 321 +- .../mongodb/lib/read_preference.js.map | 1 + .../node_modules/mongodb/lib/replset.js | 582 - .../node_modules/mongodb/lib/sdam/common.js | 55 + .../mongodb/lib/sdam/common.js.map | 1 + .../node_modules/mongodb/lib/sdam/events.js | 125 + .../mongodb/lib/sdam/events.js.map | 1 + .../node_modules/mongodb/lib/sdam/monitor.js | 326 + .../mongodb/lib/sdam/monitor.js.map | 1 + .../node_modules/mongodb/lib/sdam/server.js | 396 + .../mongodb/lib/sdam/server.js.map | 1 + .../mongodb/lib/sdam/server_description.js | 197 + .../lib/sdam/server_description.js.map | 1 + .../mongodb/lib/sdam/server_selection.js | 228 + .../mongodb/lib/sdam/server_selection.js.map | 1 + .../mongodb/lib/sdam/srv_polling.js | 122 + .../mongodb/lib/sdam/srv_polling.js.map | 1 + .../node_modules/mongodb/lib/sdam/topology.js | 645 + .../mongodb/lib/sdam/topology.js.map | 1 + .../mongodb/lib/sdam/topology_description.js | 358 + .../lib/sdam/topology_description.js.map | 1 + .../node_modules/mongodb/lib/server.js | 518 - .../node_modules/mongodb/lib/sessions.js | 745 + .../node_modules/mongodb/lib/sessions.js.map | 1 + .../node_modules/mongodb/lib/sort.js | 97 + .../node_modules/mongodb/lib/sort.js.map | 1 + .../node_modules/mongodb/lib/topology_base.js | 191 - .../node_modules/mongodb/lib/transactions.js | 138 + .../mongodb/lib/transactions.js.map | 1 + .../node_modules/mongodb/lib/url_parser.js | 412 - .../node_modules/mongodb/lib/utils.js | 1484 +- .../node_modules/mongodb/lib/utils.js.map | 1 + .../node_modules/mongodb/lib/write_concern.js | 71 + .../mongodb/lib/write_concern.js.map | 1 + .../node_modules/mongodb/mongodb.d.ts | 6684 ++++++ .../node_modules/mongodb/package.json | 230 +- .../node_modules/mongodb/src/admin.ts | 314 + .../node_modules/mongodb/src/bson.ts | 112 + .../node_modules/mongodb/src/bulk/common.ts | 1383 ++ .../node_modules/mongodb/src/bulk/ordered.ts | 82 + .../mongodb/src/bulk/unordered.ts | 109 + .../node_modules/mongodb/src/change_stream.ts | 941 + .../mongodb/src/cmap/auth/auth_provider.ts | 60 + .../mongodb/src/cmap/auth/gssapi.ts | 241 + .../src/cmap/auth/mongo_credentials.ts | 190 + .../mongodb/src/cmap/auth/mongocr.ts | 47 + .../mongodb/src/cmap/auth/mongodb_aws.ts | 293 + .../mongodb/src/cmap/auth/plain.ts | 25 + .../mongodb/src/cmap/auth/providers.ts | 21 + .../mongodb/src/cmap/auth/scram.ts | 384 + .../mongodb/src/cmap/auth/x509.ts | 53 + .../src/cmap/command_monitoring_events.ts | 334 + .../node_modules/mongodb/src/cmap/commands.ts | 891 + .../node_modules/mongodb/src/cmap/connect.ts | 512 + .../mongodb/src/cmap/connection.ts | 863 + .../mongodb/src/cmap/connection_pool.ts | 708 + .../src/cmap/connection_pool_events.ts | 179 + .../node_modules/mongodb/src/cmap/errors.ts | 38 + .../mongodb/src/cmap/message_stream.ts | 243 + .../node_modules/mongodb/src/cmap/metrics.ts | 58 + .../mongodb/src/cmap/stream_description.ts | 76 + .../src/cmap/wire_protocol/compression.ts | 130 + .../src/cmap/wire_protocol/constants.ts | 13 + .../mongodb/src/cmap/wire_protocol/shared.ts | 76 + .../node_modules/mongodb/src/collection.ts | 1700 ++ .../mongodb/src/connection_string.ts | 1267 ++ .../node_modules/mongodb/src/constants.ts | 134 + .../mongodb/src/cursor/abstract_cursor.ts | 915 + .../mongodb/src/cursor/aggregation_cursor.ts | 219 + .../src/cursor/change_stream_cursor.ts | 194 + .../mongodb/src/cursor/find_cursor.ts | 480 + .../src/cursor/list_collections_cursor.ts | 52 + .../mongodb/src/cursor/list_indexes_cursor.ts | 41 + .../node_modules/mongodb/src/db.ts | 770 + .../node_modules/mongodb/src/deps.ts | 378 + .../node_modules/mongodb/src/encrypter.ts | 137 + .../node_modules/mongodb/src/error.ts | 924 + .../node_modules/mongodb/src/explain.ts | 52 + .../mongodb/src/gridfs/download.ts | 458 + .../node_modules/mongodb/src/gridfs/index.ts | 257 + .../node_modules/mongodb/src/gridfs/upload.ts | 566 + .../node_modules/mongodb/src/index.ts | 476 + .../node_modules/mongodb/src/logger.ts | 265 + .../node_modules/mongodb/src/mongo_client.ts | 769 + .../node_modules/mongodb/src/mongo_types.ts | 548 + .../mongodb/src/operations/add_user.ts | 118 + .../mongodb/src/operations/aggregate.ts | 144 + .../mongodb/src/operations/bulk_write.ts | 67 + .../mongodb/src/operations/collections.ts | 48 + .../mongodb/src/operations/command.ts | 193 + .../src/operations/common_functions.ts | 102 + .../mongodb/src/operations/connect.ts | 107 + .../mongodb/src/operations/count.ts | 68 + .../mongodb/src/operations/count_documents.ts | 57 + .../src/operations/create_collection.ts | 201 + .../mongodb/src/operations/delete.ts | 194 + .../mongodb/src/operations/distinct.ts | 92 + .../mongodb/src/operations/drop.ts | 120 + .../operations/estimated_document_count.ts | 62 + .../mongodb/src/operations/eval.ts | 82 + .../src/operations/execute_operation.ts | 298 + .../mongodb/src/operations/find.ts | 279 + .../mongodb/src/operations/find_and_modify.ts | 295 + .../mongodb/src/operations/get_more.ts | 63 + .../mongodb/src/operations/indexes.ts | 500 + .../mongodb/src/operations/insert.ts | 158 + .../mongodb/src/operations/is_capped.ts | 42 + .../mongodb/src/operations/kill_cursors.ts | 27 + .../src/operations/list_collections.ts | 91 + .../mongodb/src/operations/list_databases.ts | 65 + .../mongodb/src/operations/map_reduce.ts | 250 + .../mongodb/src/operations/operation.ts | 125 + .../src/operations/options_operation.ts | 42 + .../mongodb/src/operations/profiling_level.ts | 39 + .../mongodb/src/operations/remove_user.ts | 33 + .../mongodb/src/operations/rename.ts | 67 + .../mongodb/src/operations/run_command.ts | 36 + .../src/operations/set_profiling_level.ts | 74 + .../mongodb/src/operations/stats.ts | 271 + .../mongodb/src/operations/update.ts | 334 + .../src/operations/validate_collection.ts | 59 + .../mongodb/src/promise_provider.ts | 41 + .../node_modules/mongodb/src/read_concern.ts | 88 + .../mongodb/src/read_preference.ts | 271 + .../node_modules/mongodb/src/sdam/common.ts | 77 + .../node_modules/mongodb/src/sdam/events.ts | 182 + .../node_modules/mongodb/src/sdam/monitor.ts | 471 + .../node_modules/mongodb/src/sdam/server.ts | 620 + .../mongodb/src/sdam/server_description.ts | 272 + .../mongodb/src/sdam/server_selection.ts | 324 + .../mongodb/src/sdam/srv_polling.ts | 165 + .../node_modules/mongodb/src/sdam/topology.ts | 1007 + .../mongodb/src/sdam/topology_description.ts | 510 + .../node_modules/mongodb/src/sessions.ts | 1074 + .../node_modules/mongodb/src/sort.ts | 132 + .../node_modules/mongodb/src/transactions.ts | 187 + .../node_modules/mongodb/src/utils.ts | 1432 ++ .../node_modules/mongodb/src/write_concern.ts | 114 + .../node_modules/mongodb/tsconfig.json | 40 + .../node_modules/mongodb/yarn.lock | 3292 --- .../node_modules/morgan/HISTORY.md | 7 + .../node_modules/morgan/README.md | 17 +- .../node_modules/morgan/index.js | 12 +- .../morgan/node_modules/depd/History.md | 96 + .../morgan/node_modules/depd/LICENSE | 22 + .../morgan/node_modules/depd/Readme.md | 280 + .../morgan/node_modules/depd/index.js | 522 + .../node_modules/depd/lib/browser/index.js | 77 + .../depd/lib/compat/callsite-tostring.js | 103 + .../depd/lib/compat/event-listener-count.js | 22 + .../node_modules/depd/lib/compat/index.js | 79 + .../morgan/node_modules/depd/package.json | 41 + .../node_modules/morgan/package.json | 120 +- .../node_modules/mysql/Changes.md | 569 + .../node_modules/mysql/License | 19 + .../node_modules/mysql/Readme.md | 1548 ++ .../node_modules/mysql/index.js | 161 + .../node_modules/mysql/lib/Connection.js | 529 + .../mysql/lib/ConnectionConfig.js | 209 + .../node_modules/mysql/lib/Pool.js | 294 + .../node_modules/mysql/lib/PoolCluster.js | 288 + .../node_modules/mysql/lib/PoolConfig.js | 32 + .../node_modules/mysql/lib/PoolConnection.js | 65 + .../node_modules/mysql/lib/PoolNamespace.js | 136 + .../node_modules/mysql/lib/PoolSelector.js | 31 + .../node_modules/mysql/lib/protocol/Auth.js | 168 + .../mysql/lib/protocol/BufferList.js | 25 + .../mysql/lib/protocol/PacketHeader.js | 5 + .../mysql/lib/protocol/PacketWriter.js | 211 + .../node_modules/mysql/lib/protocol/Parser.js | 491 + .../mysql/lib/protocol/Protocol.js | 463 + .../mysql/lib/protocol/ResultSet.js | 7 + .../mysql/lib/protocol/SqlString.js | 1 + .../node_modules/mysql/lib/protocol/Timer.js | 33 + .../mysql/lib/protocol/constants/charsets.js | 262 + .../mysql/lib/protocol/constants/client.js | 26 + .../mysql/lib/protocol/constants/errors.js | 2476 +++ .../lib/protocol/constants/field_flags.js | 18 + .../lib/protocol/constants/server_status.js | 39 + .../lib/protocol/constants/ssl_profiles.js | 1480 ++ .../mysql/lib/protocol/constants/types.js | 72 + .../packets/AuthSwitchRequestPacket.js | 20 + .../packets/AuthSwitchResponsePacket.js | 14 + .../packets/ClientAuthenticationPacket.js | 54 + .../protocol/packets/ComChangeUserPacket.js | 26 + .../lib/protocol/packets/ComPingPacket.js | 12 + .../lib/protocol/packets/ComQueryPacket.js | 15 + .../lib/protocol/packets/ComQuitPacket.js | 12 + .../protocol/packets/ComStatisticsPacket.js | 12 + .../mysql/lib/protocol/packets/EmptyPacket.js | 9 + .../mysql/lib/protocol/packets/EofPacket.js | 25 + .../mysql/lib/protocol/packets/ErrorPacket.js | 35 + .../mysql/lib/protocol/packets/Field.js | 26 + .../mysql/lib/protocol/packets/FieldPacket.js | 93 + .../packets/HandshakeInitializationPacket.js | 103 + .../protocol/packets/LocalDataFilePacket.js | 15 + .../packets/LocalInfileRequestPacket.js | 21 + .../mysql/lib/protocol/packets/OkPacket.js | 44 + .../lib/protocol/packets/OldPasswordPacket.js | 14 + .../protocol/packets/ResultSetHeaderPacket.js | 14 + .../lib/protocol/packets/RowDataPacket.js | 130 + .../lib/protocol/packets/SSLRequestPacket.js | 27 + .../lib/protocol/packets/StatisticsPacket.js | 20 + .../protocol/packets/UseOldPasswordPacket.js | 14 + .../mysql/lib/protocol/packets/index.js | 23 + .../lib/protocol/sequences/ChangeUser.js | 67 + .../mysql/lib/protocol/sequences/Handshake.js | 126 + .../mysql/lib/protocol/sequences/Ping.js | 19 + .../mysql/lib/protocol/sequences/Query.js | 228 + .../mysql/lib/protocol/sequences/Quit.js | 40 + .../mysql/lib/protocol/sequences/Sequence.js | 125 + .../lib/protocol/sequences/Statistics.js | 30 + .../mysql/lib/protocol/sequences/index.js | 7 + .../process-nextick-args/index.js | 8 +- .../process-nextick-args/license.md | 0 .../process-nextick-args/package.json | 25 + .../process-nextick-args/readme.md | 4 +- .../readable-stream/CONTRIBUTING.md | 0 .../readable-stream/GOVERNANCE.md | 0 .../node_modules}/readable-stream/LICENSE | 0 .../node_modules}/readable-stream/README.md | 5 +- .../doc/wg-meetings/2015-01-30.md | 0 .../readable-stream/duplex-browser.js | 0 .../node_modules}/readable-stream/duplex.js | 0 .../readable-stream/lib/_stream_duplex.js | 131 + .../lib/_stream_passthrough.js | 47 + .../readable-stream/lib/_stream_readable.js | 322 +- .../readable-stream/lib/_stream_transform.js | 98 +- .../readable-stream/lib/_stream_writable.js | 264 +- .../lib/internal/streams/BufferList.js | 79 + .../lib/internal/streams/destroy.js | 74 + .../lib/internal/streams/stream-browser.js | 1 + .../lib/internal/streams/stream.js | 1 + .../node_modules/readable-stream/package.json | 52 + .../readable-stream/passthrough.js | 0 .../readable-stream/readable-browser.js | 0 .../node_modules}/readable-stream/readable.js | 0 .../readable-stream/transform.js | 0 .../readable-stream/writable-browser.js | 0 .../node_modules}/readable-stream/writable.js | 4 +- .../mysql/node_modules/safe-buffer/LICENSE | 21 + .../mysql/node_modules/safe-buffer/README.md | 584 + .../mysql/node_modules/safe-buffer/index.d.ts | 187 + .../mysql/node_modules/safe-buffer/index.js | 62 + .../node_modules/safe-buffer/package.json | 37 + .../node_modules}/string_decoder/LICENSE | 0 .../node_modules/string_decoder/README.md | 47 + .../string_decoder/lib/string_decoder.js | 46 +- .../node_modules/string_decoder/package.json | 31 + .../node_modules/mysql/package.json | 46 + .../process-nextick-args/.travis.yml | 12 - .../process-nextick-args/package.json | 83 - .../node_modules/process-nextick-args/test.js | 24 - .../node_modules/punycode/LICENSE-MIT.txt | 20 + .../node_modules/punycode/README.md | 122 + .../node_modules/punycode/package.json | 58 + .../node_modules/punycode/punycode.es6.js | 441 + .../node_modules/punycode/punycode.js | 440 + .../node_modules/readable-stream/.npmignore | 9 - .../node_modules/readable-stream/.travis.yml | 49 - .../readable-stream/lib/_stream_duplex.js | 75 - .../lib/_stream_passthrough.js | 26 - .../lib/internal/streams/BufferList.js | 64 - .../node_modules/readable-stream/package.json | 136 - .../node_modules/require_optional/.npmignore | 33 - .../node_modules/require_optional/.travis.yml | 9 - .../node_modules/require_optional/HISTORY.md | 7 - .../node_modules/require_optional/README.md | 2 - .../node_modules/require_optional/index.js | 128 - .../require_optional/package.json | 103 - .../require_optional/test/nestedTest/index.js | 8 - .../test/nestedTest/package.json | 11 - .../test/require_optional_tests.js | 59 - .../node_modules/resolve-from/index.js | 23 - .../node_modules/resolve-from/package.json | 98 - .../node_modules/resolve-from/readme.md | 58 - .../node_modules/saslprep/.editorconfig | 10 + .../node_modules/saslprep/.gitattributes | 1 + .../node_modules/saslprep/CHANGELOG.md | 19 + .../node_modules/saslprep/LICENSE | 22 + .../node_modules/saslprep/code-points.mem | Bin 0 -> 419864 bytes .../saslprep/generate-code-points.js | 51 + .../node_modules/saslprep/index.js | 157 + .../node_modules/saslprep/lib/code-points.js | 996 + .../saslprep/lib/memory-code-points.js | 39 + .../node_modules/saslprep/lib/util.js | 21 + .../node_modules/saslprep/package.json | 72 + .../node_modules/saslprep/readme.md | 31 + .../node_modules/saslprep/test/index.js | 76 + .../node_modules/saslprep/test/util.js | 16 + .../node_modules/semver/LICENSE | 15 - .../node_modules/semver/README.md | 366 - .../node_modules/semver/bin/semver | 133 - .../node_modules/semver/package.json | 95 - .../node_modules/semver/range.bnf | 16 - .../node_modules/semver/semver.js | 1296 -- .../node_modules/smart-buffer/LICENSE | 20 + .../node_modules/smart-buffer/README.md | 633 + .../smart-buffer/build/smartbuffer.js | 1233 ++ .../smart-buffer/build/smartbuffer.js.map | 1 + .../node_modules/smart-buffer/build/utils.js | 108 + .../smart-buffer/build/utils.js.map | 1 + .../smart-buffer/docs/CHANGELOG.md | 70 + .../smart-buffer/docs/README_v3.md | 367 + .../node_modules/smart-buffer/docs/ROADMAP.md | 0 .../node_modules/smart-buffer/package.json | 79 + .../node_modules/socks/.eslintrc.cjs | 11 + .../node_modules/socks/LICENSE | 20 + .../node_modules/socks/README.md | 686 + .../socks/build/client/socksclient.js | 795 + .../socks/build/client/socksclient.js.map | 1 + .../socks/build/common/constants.js | 114 + .../socks/build/common/constants.js.map | 1 + .../socks/build/common/helpers.js | 128 + .../socks/build/common/helpers.js.map | 1 + .../socks/build/common/receivebuffer.js | 43 + .../socks/build/common/receivebuffer.js.map | 1 + .../node_modules/socks/build/common/util.js | 25 + .../socks/build/common/util.js.map | 1 + .../node_modules/socks/build/index.js | 18 + .../node_modules/socks/build/index.js.map | 1 + .../node_modules/socks/docs/examples/index.md | 17 + .../examples/javascript/associateExample.md | 90 + .../docs/examples/javascript/bindExample.md | 83 + .../examples/javascript/connectExample.md | 258 + .../examples/typescript/associateExample.md | 93 + .../docs/examples/typescript/bindExample.md | 86 + .../examples/typescript/connectExample.md | 265 + .../node_modules/socks/docs/index.md | 5 + .../socks/docs/migratingFromV1.md | 86 + .../node_modules/socks/package.json | 58 + .../node_modules/sparse-bitfield/.npmignore | 1 + .../node_modules/sparse-bitfield/LICENSE | 21 + .../node_modules/sparse-bitfield/README.md | 62 + .../node_modules/sparse-bitfield/index.js | 95 + .../node_modules/sparse-bitfield/package.json | 27 + .../node_modules/sparse-bitfield/test.js | 79 + .../node_modules/sqlstring/HISTORY.md | 43 + .../node_modules/sqlstring/LICENSE | 19 + .../node_modules/sqlstring/README.md | 206 + .../node_modules/sqlstring/index.js | 1 + .../node_modules/sqlstring/lib/SqlString.js | 237 + .../node_modules/sqlstring/package.json | 47 + .../node_modules/string_decoder/.npmignore | 2 - .../node_modules/string_decoder/README.md | 28 - .../node_modules/string_decoder/package.json | 108 - .../license.md => tr46/LICENSE.md} | 8 +- .../node_modules/tr46/README.md | 78 + .../node_modules/tr46/index.js | 298 + .../node_modules/tr46/lib/mappingTable.json | 1 + .../node_modules/tr46/lib/regexes.js | 29 + .../node_modules/tr46/lib/statusMapping.js | 11 + .../node_modules/tr46/package.json | 47 + .../transformers/node_modules/.bin/uglifyjs | 16 +- .../node_modules/uglify-js/bin/uglifyjs | 0 .../node_modules/uglify-js/bin/uglifyjs | 0 .../webidl-conversions/LICENSE.md | 12 + .../node_modules/webidl-conversions/README.md | 99 + .../webidl-conversions/lib/index.js | 450 + .../webidl-conversions/package.json | 35 + .../node_modules/whatwg-url/LICENSE.txt | 21 + .../node_modules/whatwg-url/README.md | 106 + .../node_modules/whatwg-url/index.js | 27 + .../node_modules/whatwg-url/lib/Function.js | 42 + .../node_modules/whatwg-url/lib/URL-impl.js | 209 + .../node_modules/whatwg-url/lib/URL.js | 442 + .../whatwg-url/lib/URLSearchParams-impl.js | 130 + .../whatwg-url/lib/URLSearchParams.js | 472 + .../whatwg-url/lib/VoidFunction.js | 26 + .../node_modules/whatwg-url/lib/encoding.js | 16 + .../node_modules/whatwg-url/lib/infra.js | 26 + .../whatwg-url/lib/percent-encoding.js | 142 + .../whatwg-url/lib/url-state-machine.js | 1244 ++ .../node_modules/whatwg-url/lib/urlencoded.js | 106 + .../node_modules/whatwg-url/lib/utils.js | 190 + .../node_modules/whatwg-url/package.json | 58 + .../whatwg-url/webidl2js-wrapper.js | 7 + .../node_modules/with/node_modules/.bin/acorn | 16 +- .../with/node_modules/acorn/bin/acorn | 0 ts-ticket-office-service/package-lock.json | 1937 ++ ts-ticket-office-service/package.json | 1 + ts-ticket-office-service/test.sh | 21 + .../controller/TicketInfoController.java | 46 - .../java/ticketinfo/entity/TrainType.java | 25 - .../main/java/ticketinfo/entity/Travel.java | 22 - .../java/ticketinfo/entity/TravelResult.java | 23 - .../src/main/java/ticketinfo/entity/Trip.java | 70 - .../main/java/ticketinfo/entity/TripId.java | 40 - .../src/main/java/ticketinfo/entity/Type.java | 41 - .../ticketinfo/service/TicketInfoService.java | 13 - .../service/TicketInfoServiceImpl.java | 44 - .../src/main/resources/application.yml | 11 - .../controller/TicketInfoControllerTest.java | 66 - .../service/TicketInfoServiceImplTest.java | 62 - .../Dockerfile | 6 +- .../pom.xml | 50 +- .../java/trainFood/TrainFoodApplication.java | 31 + .../trainFood}/config/SecurityConfig.java | 4 +- .../controller/TrainFoodController.java | 12 +- .../main/java/trainFood/entity/TrainFood.java | 38 + .../main/java/trainFood/init/InitData.java | 67 + .../repository/TrainFoodRepository.java | 22 + .../trainFood/service/TrainFoodService.java | 13 + .../service/TrainFoodServiceImpl.java | 61 + .../src/main/resources/application.yml | 25 + .../src/main/resources/trainfood.txt | 0 ts-train-service/pom.xml | 19 +- .../src/main/java/train/TrainApplication.java | 11 + .../train/controller/TrainController.java | 34 +- .../src/main/java/train/entity/TrainType.java | 33 +- .../src/main/java/train/init/InitData.java | 17 +- .../train/repository/TrainTypeRepository.java | 13 +- .../main/java/train/service/TrainService.java | 4 + .../java/train/service/TrainServiceImpl.java | 52 +- .../src/main/resources/application.yml | 23 +- .../train/service/TrainServiceImplTest.java | 8 +- ts-travel-plan-service/pom.xml | 5 +- .../travelplan/TravelPlanApplication.java | 4 + .../controller/TravelPlanController.java | 10 +- .../java/travelplan/entity/RoutePlanInfo.java | 32 - .../entity/RoutePlanResultUnit.java | 36 - .../src/main/java/travelplan/entity/Seat.java | 27 - .../java/travelplan/entity/SeatClass.java | 70 - .../java/travelplan/entity/TrainTypeEnum.java | 63 - .../travelplan/entity/TransferTravelInfo.java | 20 +- .../entity/TransferTravelResult.java | 2 + .../entity/TravelAdvanceResultUnit.java | 8 +- .../src/main/java/travelplan/entity/Trip.java | 49 - .../main/java/travelplan/entity/TripId.java | 44 - .../main/java/travelplan/entity/TripInfo.java | 24 - .../java/travelplan/entity/TripResponse.java | 37 - .../travelplan/service/TravelPlanService.java | 3 +- .../service/TravelPlanServiceImpl.java | 158 +- .../src/main/resources/application.yml | 6 +- .../controller/TravelPlanControllerTest.java | 2 +- .../service/TravelPlanServiceImplTest.java | 17 +- ts-travel-service/pom.xml | 13 +- .../main/java/travel/TravelApplication.java | 4 + .../travel/controller/TravelController.java | 40 +- .../main/java/travel/entity/AdminTrip.java | 3 + .../src/main/java/travel/entity/Route.java | 37 - .../src/main/java/travel/entity/Seat.java | 54 - .../main/java/travel/entity/SeatClass.java | 70 - .../main/java/travel/entity/TrainType.java | 44 - .../src/main/java/travel/entity/Travel.java | 8 +- .../main/java/travel/entity/TravelInfo.java | 33 - .../main/java/travel/entity/TravelResult.java | 26 - .../src/main/java/travel/entity/Trip.java | 65 +- .../java/travel/entity/TripAllDetail.java | 3 + .../java/travel/entity/TripAllDetailInfo.java | 25 - .../src/main/java/travel/entity/TripId.java | 44 - .../src/main/java/travel/entity/TripInfo.java | 36 - .../main/java/travel/entity/TripResponse.java | 37 - .../src/main/java/travel/entity/Type.java | 51 - .../src/main/java/travel/init/InitData.java | 62 +- .../travel/repository/TripRepository.java | 8 +- .../java/travel/service/TravelService.java | 7 +- .../travel/service/TravelServiceImpl.java | 359 +- .../src/main/resources/application.yml | 41 +- .../controller/TravelControllerTest.java | 10 +- .../travel/service/TravelServiceImplTest.java | 5 +- ts-travel2-service/pom.xml | 15 +- .../main/java/travel2/Travel2Application.java | 4 + .../travel2/controller/Travel2Controller.java | 42 +- .../main/java/travel2/entity/AdminTrip.java | 2 + .../src/main/java/travel2/entity/Route.java | 33 - .../src/main/java/travel2/entity/Seat.java | 44 - .../main/java/travel2/entity/SeatClass.java | 70 - .../main/java/travel2/entity/SoldTicket.java | 47 - .../main/java/travel2/entity/TrainType.java | 43 - .../src/main/java/travel2/entity/Travel.java | 7 +- .../main/java/travel2/entity/TravelInfo.java | 33 - .../java/travel2/entity/TravelResult.java | 28 - .../src/main/java/travel2/entity/Trip.java | 66 +- .../java/travel2/entity/TripAllDetail.java | 9 +- .../travel2/entity/TripAllDetailInfo.java | 27 - .../src/main/java/travel2/entity/TripId.java | 39 - .../main/java/travel2/entity/TripInfo.java | 35 - .../src/main/java/travel2/entity/Type.java | 55 - .../src/main/java/travel2/init/InitData.java | 66 +- .../travel2/repository/TripRepository.java | 10 +- .../travel2/service/Travel2ServiceImpl.java | 431 - ...Travel2Service.java => TravelService.java} | 12 +- .../travel2/service/TravelServiceImpl.java | 497 + .../src/main/resources/application.yml | 25 +- ...lerTest.java => TravelControllerTest.java} | 16 +- ...plTest.java => TravelServiceImplTest.java} | 40 +- ts-ui-dashboard/nginx.conf | 353 +- ts-ui-dashboard/static/add&delete.html | 16 +- ts-ui-dashboard/static/admin.html | 69 +- ts-ui-dashboard/static/admin_station.html | 9 - ts-ui-dashboard/static/admin_train.html | 16 +- ts-ui-dashboard/static/admin_travel.html | 116 +- ts-ui-dashboard/static/admin_user.html | 17 +- .../assets/css/amazeui.datetimepicker.css | 10 + .../static/assets/js/admin_price.js | 9 +- .../static/assets/js/admin_station.js | 9 +- .../static/assets/js/admin_train.js | 7 +- .../static/assets/js/admin_travel.js | 204 +- .../static/assets/js/admin_user.js | 4 +- .../assets/js/amazeui.datetimepicker.min.js | 1 + .../static/assets/js/client_adsearch.js | 10 +- .../static/assets/js/client_order_list.js | 8 +- .../static/assets/js/client_ticket_book.js | 2 + ts-ui-dashboard/static/assets/js/index.js | 6 +- ts-ui-dashboard/static/assets/js/old_index.js | 199 +- ts-ui-dashboard/static/client_adsearch.html | 8 +- ts-ui-dashboard/static/client_order_list.html | 4 +- ts-ui-dashboard/static/index.html | 6 +- ts-ui-dashboard/static/js/basicInformation.js | 12 +- ts-ui-dashboard/static/js/bs_main.js | 6 +- .../static/js/flowAdvancedSearch.js | 20 +- ts-ui-dashboard/static/js/flowPreserve.js | 6 +- ts-ui-dashboard/static/js/flowRebook.js | 6 +- ts-ui-dashboard/static/js/myflow.js | 6 +- ts-ui-dashboard/static/js/notification.js | 8 +- ts-ui-dashboard/static/js/routePlan.js | 26 +- .../static/js/ticketInformation.js | 12 +- ts-ui-dashboard/static/js/travel.js | 24 +- ts-ui-dashboard/static/js/travelTransit.js | 14 +- ts-ui-dashboard/static/old_index.html | 44 +- ts-user-service/pom.xml | 13 +- .../src/main/java/user/UserApplication.java | 19 + .../java/user/controller/UserController.java | 14 +- .../src/main/java/user/dto/UserDto.java | 2 +- .../src/main/java/user/entity/User.java | 21 +- .../src/main/java/user/init/InitUser.java | 3 +- .../java/user/repository/UserRepository.java | 12 +- .../main/java/user/service/UserService.java | 2 +- .../user/service/impl/UserServiceImpl.java | 77 +- .../src/main/resources/application.yaml | 23 +- .../user/controller/UserControllerTest.java | 2 +- .../user/service/UserServiceImplTest.java | 20 +- ts-verification-code-service/pom.xml | 8 +- .../verifycode/VerifyCodeApplication.java | 11 + .../controller/VerifyCodeController.java | 6 +- .../service/impl/VerifyCodeServiceImpl.java | 8 +- .../src/main/resources/application.yml | 5 +- ts-voucher-service/server.py | 91 +- ts-wait-order-service/pom.xml | 57 + .../java/waitorder/WaitOrderApplication.java | 33 + .../java/waitorder/config/SecurityConfig.java | 90 + .../controller/WaitListOrderController.java | 52 + .../java/waitorder/entity/WaitListOrder.java | 106 + .../waitorder/entity/WaitListOrderStatus.java | 25 +- .../waitorder/entity/WaitListOrderVO.java | 46 + .../repository/WaitListOrderRepository.java | 25 + .../Impl/WaitListOrderServiceImpl.java | 174 + .../service/WaitListOrderService.java | 30 + .../main/java/waitorder/utils/PollThread.java | 84 + .../src/main/resources/application.yml | 25 + .../waitorder/WaitOrderApplicationTests.java | 13 + .../Impl/WaitListOrderServiceImplTest.java | 52 + 1639 files changed, 174058 insertions(+), 83329 deletions(-) create mode 100644 CHANGELOG-1.0.md delete mode 100644 deployment/kubernetes-manifests/prometheus-deployment/configmap.yaml delete mode 100644 deployment/kubernetes-manifests/prometheus-deployment/kube-state-metrics.yaml delete mode 100644 deployment/kubernetes-manifests/prometheus-deployment/node-exporter.yaml delete mode 100644 deployment/kubernetes-manifests/prometheus-deployment/prometheus.yaml delete mode 100644 deployment/kubernetes-manifests/prometheus-deployment/rbac.yaml create mode 100644 deployment/kubernetes-manifests/prometheus/alert-manager-configmap.yml create mode 100644 deployment/kubernetes-manifests/prometheus/alert-manager.yml create mode 100644 deployment/kubernetes-manifests/prometheus/alertsnitch.yml rename deployment/kubernetes-manifests/{prometheus-deployment/grafana.yaml => prometheus/grafana.yml} (93%) create mode 100644 deployment/kubernetes-manifests/prometheus/node-exporter.yml create mode 100644 deployment/kubernetes-manifests/prometheus/prometheus-configmap.yml create mode 100644 deployment/kubernetes-manifests/prometheus/prometheus.yml create mode 100644 deployment/kubernetes-manifests/quickstart-k8s/charts/mysql/Chart.yaml create mode 100644 deployment/kubernetes-manifests/quickstart-k8s/charts/mysql/README.md create mode 100644 deployment/kubernetes-manifests/quickstart-k8s/charts/mysql/templates/.statefulset.yaml.swp create mode 100644 deployment/kubernetes-manifests/quickstart-k8s/charts/mysql/templates/NOTES.txt create mode 100644 deployment/kubernetes-manifests/quickstart-k8s/charts/mysql/templates/_helpers.tpl create mode 100644 deployment/kubernetes-manifests/quickstart-k8s/charts/mysql/templates/configmap.yaml create mode 100644 deployment/kubernetes-manifests/quickstart-k8s/charts/mysql/templates/rbac.yaml create mode 100644 deployment/kubernetes-manifests/quickstart-k8s/charts/mysql/templates/secrets.yaml create mode 100644 deployment/kubernetes-manifests/quickstart-k8s/charts/mysql/templates/service.yaml create mode 100644 deployment/kubernetes-manifests/quickstart-k8s/charts/mysql/templates/serviceaccount.yaml create mode 100644 deployment/kubernetes-manifests/quickstart-k8s/charts/mysql/templates/servicemonitor.yaml create mode 100644 deployment/kubernetes-manifests/quickstart-k8s/charts/mysql/templates/statefulset.yaml create mode 100644 deployment/kubernetes-manifests/quickstart-k8s/charts/mysql/values.yaml create mode 100644 deployment/kubernetes-manifests/quickstart-k8s/charts/nacos/Chart.yaml create mode 100644 deployment/kubernetes-manifests/quickstart-k8s/charts/nacos/README.md create mode 100644 deployment/kubernetes-manifests/quickstart-k8s/charts/nacos/templates/_helpers.tpl create mode 100644 deployment/kubernetes-manifests/quickstart-k8s/charts/nacos/templates/configmap.yaml create mode 100644 deployment/kubernetes-manifests/quickstart-k8s/charts/nacos/templates/secrets.yaml create mode 100644 deployment/kubernetes-manifests/quickstart-k8s/charts/nacos/templates/service.yaml create mode 100644 deployment/kubernetes-manifests/quickstart-k8s/charts/nacos/templates/statefulset.yaml create mode 100644 deployment/kubernetes-manifests/quickstart-k8s/charts/nacos/values.yaml create mode 100644 deployment/kubernetes-manifests/quickstart-k8s/charts/rabbitmq/Chart.yaml create mode 100644 deployment/kubernetes-manifests/quickstart-k8s/charts/rabbitmq/README.md create mode 100644 deployment/kubernetes-manifests/quickstart-k8s/charts/rabbitmq/templates/configmap.yaml create mode 100644 deployment/kubernetes-manifests/quickstart-k8s/charts/rabbitmq/templates/deployment.yaml create mode 100644 deployment/kubernetes-manifests/quickstart-k8s/charts/rabbitmq/templates/service.yaml create mode 100644 deployment/kubernetes-manifests/quickstart-k8s/charts/rabbitmq/values.yaml delete mode 100644 deployment/kubernetes-manifests/quickstart-k8s/quickstart-ts-deployment-part1.yml delete mode 100644 deployment/kubernetes-manifests/quickstart-k8s/quickstart-ts-deployment-part3.yml rename deployment/kubernetes-manifests/quickstart-k8s/{quickstart-ts-deployment-part2.yml => yamls/deploy.yaml.sample} (66%) create mode 100644 deployment/kubernetes-manifests/quickstart-k8s/yamls/svc.yaml create mode 100644 deployment/kubernetes-manifests/quickstart-k8s/yamls/sw_deploy.yaml.sample create mode 100644 deployment/kubernetes-manifests/skywalking/es.yml create mode 100644 deployment/kubernetes-manifests/skywalking/skywalking.yml create mode 100755 hack/deploy/deploy.sh create mode 100755 hack/deploy/gen-mysql-secret.sh create mode 100755 hack/deploy/reset.sh create mode 100755 hack/deploy/utils.sh delete mode 100644 ts-admin-basic-info-service/src/main/java/adminbasic/entity/Contacts.java delete mode 100644 ts-admin-basic-info-service/src/main/java/adminbasic/entity/Station.java delete mode 100644 ts-admin-basic-info-service/src/main/java/adminbasic/entity/TrainType.java delete mode 100644 ts-admin-order-service/src/main/java/adminorder/entity/Order.java delete mode 100644 ts-admin-order-service/src/main/java/adminorder/entity/OrderStatus.java delete mode 100644 ts-admin-order-service/src/main/java/adminorder/entity/SeatClass.java delete mode 100644 ts-admin-route-service/src/main/java/adminroute/entity/Route.java delete mode 100644 ts-admin-route-service/src/main/java/adminroute/entity/RouteInfo.java delete mode 100644 ts-admin-travel-service/src/main/java/admintravel/entity/Route.java delete mode 100644 ts-admin-travel-service/src/main/java/admintravel/entity/TrainType.java delete mode 100644 ts-admin-travel-service/src/main/java/admintravel/entity/TravelInfo.java delete mode 100644 ts-admin-travel-service/src/main/java/admintravel/entity/Trip.java delete mode 100644 ts-admin-travel-service/src/main/java/admintravel/entity/TripId.java delete mode 100644 ts-admin-travel-service/src/main/java/admintravel/entity/Type.java delete mode 100644 ts-admin-user-service/src/main/java/adminuser/entity/DocumentType.java delete mode 100644 ts-admin-user-service/src/main/java/adminuser/entity/Gender.java delete mode 100644 ts-admin-user-service/src/main/java/adminuser/entity/User.java delete mode 100644 ts-basic-service/src/main/java/fdse/microservice/entity/Route.java delete mode 100644 ts-basic-service/src/main/java/fdse/microservice/entity/TrainType.java delete mode 100644 ts-basic-service/src/main/java/fdse/microservice/entity/Travel.java delete mode 100644 ts-basic-service/src/main/java/fdse/microservice/entity/TravelResult.java delete mode 100644 ts-basic-service/src/main/java/fdse/microservice/entity/Trip.java delete mode 100644 ts-basic-service/src/main/java/fdse/microservice/entity/TripId.java delete mode 100644 ts-basic-service/src/main/java/fdse/microservice/entity/Type.java delete mode 100644 ts-cancel-service/src/main/java/cancel/entity/Account.java delete mode 100644 ts-cancel-service/src/main/java/cancel/entity/DocumentType.java delete mode 100644 ts-cancel-service/src/main/java/cancel/entity/NotifyInfo.java delete mode 100644 ts-cancel-service/src/main/java/cancel/entity/Order.java delete mode 100644 ts-cancel-service/src/main/java/cancel/entity/OrderStatus.java delete mode 100644 ts-cancel-service/src/main/java/cancel/entity/SeatClass.java delete mode 100644 ts-cancel-service/src/main/java/cancel/entity/User.java delete mode 100644 ts-cancel-service/src/main/java/cancel/entity/VerifyResult.java rename {ts-admin-user-service/src/main/java/adminuser => ts-common/src/main/java/edu/fudan/common}/entity/Account.java (95%) rename {ts-admin-travel-service/src/main/java/admintravel => ts-common/src/main/java/edu/fudan/common}/entity/AdminTrip.java (62%) rename {ts-preserve-other-service/src/main/java/preserveOther => ts-common/src/main/java/edu/fudan/common}/entity/Assurance.java (95%) rename {ts-preserve-other-service/src/main/java/preserveOther => ts-common/src/main/java/edu/fudan/common}/entity/AssuranceType.java (97%) rename {ts-admin-basic-info-service/src/main/java/adminbasic => ts-common/src/main/java/edu/fudan/common}/entity/Config.java (89%) rename {ts-preserve-service/src/main/java/preserve => ts-common/src/main/java/edu/fudan/common}/entity/Consign.java (63%) rename {ts-basic-service/src/main/java/fdse/microservice => ts-common/src/main/java/edu/fudan/common}/entity/Contacts.java (97%) rename {ts-preserve-other-service/src/main/java/preserveOther => ts-common/src/main/java/edu/fudan/common}/entity/DocumentType.java (96%) rename {ts-food-map-service/src/main/java/food => ts-common/src/main/java/edu/fudan/common}/entity/Food.java (72%) rename {ts-preserve-service/src/main/java/preserve => ts-common/src/main/java/edu/fudan/common}/entity/FoodOrder.java (81%) rename {ts-cancel-service/src/main/java/cancel => ts-common/src/main/java/edu/fudan/common}/entity/Gender.java (96%) rename {ts-order-service/src/main/java/order => ts-common/src/main/java/edu/fudan/common}/entity/LeftTicketInfo.java (93%) rename {ts-preserve-service/src/main/java/preserve => ts-common/src/main/java/edu/fudan/common}/entity/NotifyInfo.java (79%) rename {ts-rebook-service/src/main/java/rebook => ts-common/src/main/java/edu/fudan/common}/entity/Order.java (74%) create mode 100644 ts-common/src/main/java/edu/fudan/common/entity/OrderAlterInfo.java rename {ts-security-service/src/main/java/security => ts-common/src/main/java/edu/fudan/common}/entity/OrderSecurity.java (89%) rename {ts-execute-service/src/main/java/execute => ts-common/src/main/java/edu/fudan/common}/entity/OrderStatus.java (97%) rename {ts-preserve-other-service/src/main/java/preserveOther => ts-common/src/main/java/edu/fudan/common}/entity/OrderTicketsInfo.java (67%) rename {ts-rebook-service/src/main/java/rebook => ts-common/src/main/java/edu/fudan/common}/entity/PaymentDifferenceInfo.java (89%) rename {ts-basic-service/src/main/java/fdse/microservice => ts-common/src/main/java/edu/fudan/common}/entity/PriceConfig.java (92%) create mode 100644 ts-common/src/main/java/edu/fudan/common/entity/Route.java create mode 100644 ts-common/src/main/java/edu/fudan/common/entity/RouteInfo.java create mode 100644 ts-common/src/main/java/edu/fudan/common/entity/RoutePlanInfo.java create mode 100644 ts-common/src/main/java/edu/fudan/common/entity/RoutePlanResultUnit.java rename {ts-rebook-service/src/main/java/rebook => ts-common/src/main/java/edu/fudan/common}/entity/Seat.java (69%) rename {ts-execute-service/src/main/java/execute => ts-common/src/main/java/edu/fudan/common}/entity/SeatClass.java (97%) rename {ts-travel-service/src/main/java/travel => ts-common/src/main/java/edu/fudan/common}/entity/SoldTicket.java (95%) create mode 100644 ts-common/src/main/java/edu/fudan/common/entity/Station.java rename ts-food-service/src/main/java/foodsearch/entity/FoodStore.java => ts-common/src/main/java/edu/fudan/common/entity/StationFoodStore.java (68%) rename {ts-order-service/src/main/java/order => ts-common/src/main/java/edu/fudan/common}/entity/Ticket.java (86%) rename {ts-food-service/src/main/java/foodsearch => ts-common/src/main/java/edu/fudan/common}/entity/TrainFood.java (90%) rename {ts-price-service/src/main/java/price => ts-common/src/main/java/edu/fudan/common}/entity/TrainType.java (61%) rename {ts-preserve-other-service/src/main/java/preserveOther => ts-common/src/main/java/edu/fudan/common}/entity/Travel.java (60%) create mode 100644 ts-common/src/main/java/edu/fudan/common/entity/TravelInfo.java rename {ts-preserve-other-service/src/main/java/preserveOther => ts-common/src/main/java/edu/fudan/common}/entity/TravelResult.java (85%) create mode 100644 ts-common/src/main/java/edu/fudan/common/entity/Trip.java rename {ts-preserve-service/src/main/java/preserve => ts-common/src/main/java/edu/fudan/common}/entity/TripAllDetail.java (67%) create mode 100644 ts-common/src/main/java/edu/fudan/common/entity/TripAllDetailInfo.java rename {ts-rebook-service/src/main/java/rebook => ts-common/src/main/java/edu/fudan/common}/entity/TripId.java (83%) create mode 100644 ts-common/src/main/java/edu/fudan/common/entity/TripInfo.java rename {ts-travel2-service/src/main/java/travel2 => ts-common/src/main/java/edu/fudan/common}/entity/TripResponse.java (56%) rename {ts-rebook-service/src/main/java/rebook => ts-common/src/main/java/edu/fudan/common}/entity/Type.java (96%) rename {ts-preserve-service/src/main/java/preserve => ts-common/src/main/java/edu/fudan/common}/entity/User.java (92%) rename {ts-rebook-service/src/main/java/rebook => ts-common/src/main/java/edu/fudan/common}/entity/VerifyResult.java (100%) create mode 100644 ts-common/src/main/java/edu/fudan/common/util/StringUtils.java create mode 100644 ts-consign-service/src/main/java/consign/init/InitData.java delete mode 100644 ts-execute-service/src/main/java/execute/entity/Order.java create mode 100644 ts-food-delivery-service/Dockerfile create mode 100644 ts-food-delivery-service/pom.xml create mode 100644 ts-food-delivery-service/src/main/java/food_delivery/FoodDeliveryApplication.java create mode 100644 ts-food-delivery-service/src/main/java/food_delivery/config/SecurityConfig.java create mode 100644 ts-food-delivery-service/src/main/java/food_delivery/controller/FoodDeliveryController.java create mode 100644 ts-food-delivery-service/src/main/java/food_delivery/entity/DeliveryInfo.java create mode 100644 ts-food-delivery-service/src/main/java/food_delivery/entity/FoodDeliveryOrder.java create mode 100644 ts-food-delivery-service/src/main/java/food_delivery/entity/SeatInfo.java create mode 100644 ts-food-delivery-service/src/main/java/food_delivery/entity/StationFoodStoreInfo.java create mode 100644 ts-food-delivery-service/src/main/java/food_delivery/entity/TripOrderInfo.java create mode 100644 ts-food-delivery-service/src/main/java/food_delivery/init/InitData.java create mode 100644 ts-food-delivery-service/src/main/java/food_delivery/repository/FoodDeliveryOrderRepository.java create mode 100644 ts-food-delivery-service/src/main/java/food_delivery/service/FoodDeliveryService.java create mode 100644 ts-food-delivery-service/src/main/java/food_delivery/service/FoodDeliveryServiceImpl.java create mode 100644 ts-food-delivery-service/src/main/resources/application.yml create mode 100644 ts-food-delivery-service/src/main/resources/food_delivery_orders.txt create mode 100644 ts-food-delivery-service/src/test/java/food_delivery/controller/FoodDeliveryControllerTest.java create mode 100644 ts-food-delivery-service/src/test/java/food_delivery/service/FoodDeliveryServiceImplTest.java delete mode 100644 ts-food-map-service/src/main/java/food/controller/FoodStoreController.java delete mode 100644 ts-food-map-service/src/main/java/food/entity/FoodStore.java delete mode 100644 ts-food-map-service/src/main/java/food/entity/TrainFood.java delete mode 100644 ts-food-map-service/src/main/java/food/repository/FoodStoreRepository.java delete mode 100644 ts-food-map-service/src/main/java/food/repository/TrainFoodRepository.java delete mode 100644 ts-food-map-service/src/main/java/food/service/FoodMapService.java delete mode 100644 ts-food-map-service/src/main/java/food/service/FoodMapServiceImpl.java delete mode 100644 ts-food-map-service/src/main/resources/application.yml delete mode 100644 ts-food-map-service/src/test/java/food/controller/TrainFoodControllerTest.java delete mode 100644 ts-food-map-service/src/test/java/food/service/FoodMapServiceImplTest.java delete mode 100644 ts-food-service/src/main/java/foodsearch/entity/Food.java delete mode 100644 ts-food-service/src/main/java/foodsearch/entity/Route.java rename {ts-food-map-service => ts-gateway-service}/Dockerfile (50%) create mode 100644 ts-gateway-service/pom.xml rename ts-food-map-service/src/main/java/food/FoodMapApplication.java => ts-gateway-service/src/main/java/gateway/GatewayApplication.java (70%) create mode 100644 ts-gateway-service/src/main/java/gateway/GatewayConfiguration.java create mode 100644 ts-gateway-service/src/main/resources/application.yml delete mode 100644 ts-inside-payment-service/src/main/java/inside_payment/entity/Order.java delete mode 100644 ts-inside-payment-service/src/main/java/inside_payment/entity/OrderStatus.java delete mode 100644 ts-inside-payment-service/src/main/java/inside_payment/entity/SeatClass.java delete mode 100644 ts-order-other-service/src/main/java/other/entity/LeftTicketInfo.java delete mode 100644 ts-order-other-service/src/main/java/other/entity/OrderSecurity.java delete mode 100644 ts-order-other-service/src/main/java/other/entity/OrderStatus.java delete mode 100644 ts-order-other-service/src/main/java/other/entity/Seat.java delete mode 100644 ts-order-other-service/src/main/java/other/entity/SeatClass.java delete mode 100644 ts-order-other-service/src/main/java/other/entity/SoldTicket.java delete mode 100644 ts-order-other-service/src/main/java/other/entity/Ticket.java delete mode 100644 ts-order-other-service/src/main/java/other/entity/TrainType.java delete mode 100644 ts-order-service/src/main/java/order/entity/OrderSecurity.java delete mode 100644 ts-order-service/src/main/java/order/entity/OrderStatus.java delete mode 100644 ts-order-service/src/main/java/order/entity/Seat.java delete mode 100644 ts-order-service/src/main/java/order/entity/SeatClass.java delete mode 100644 ts-order-service/src/main/java/order/entity/SoldTicket.java delete mode 100644 ts-order-service/src/main/java/order/entity/TrainType.java delete mode 100644 ts-preserve-other-service/src/main/java/preserveOther/entity/Account.java delete mode 100644 ts-preserve-other-service/src/main/java/preserveOther/entity/Consign.java delete mode 100644 ts-preserve-other-service/src/main/java/preserveOther/entity/Contacts.java delete mode 100644 ts-preserve-other-service/src/main/java/preserveOther/entity/FoodOrder.java delete mode 100644 ts-preserve-other-service/src/main/java/preserveOther/entity/Gender.java delete mode 100644 ts-preserve-other-service/src/main/java/preserveOther/entity/NotifyInfo.java delete mode 100644 ts-preserve-other-service/src/main/java/preserveOther/entity/Order.java delete mode 100644 ts-preserve-other-service/src/main/java/preserveOther/entity/OrderStatus.java delete mode 100644 ts-preserve-other-service/src/main/java/preserveOther/entity/Seat.java delete mode 100644 ts-preserve-other-service/src/main/java/preserveOther/entity/SeatClass.java delete mode 100644 ts-preserve-other-service/src/main/java/preserveOther/entity/Ticket.java delete mode 100644 ts-preserve-other-service/src/main/java/preserveOther/entity/TrainType.java delete mode 100644 ts-preserve-other-service/src/main/java/preserveOther/entity/Trip.java delete mode 100644 ts-preserve-other-service/src/main/java/preserveOther/entity/TripAllDetail.java delete mode 100644 ts-preserve-other-service/src/main/java/preserveOther/entity/TripAllDetailInfo.java delete mode 100644 ts-preserve-other-service/src/main/java/preserveOther/entity/TripId.java delete mode 100644 ts-preserve-other-service/src/main/java/preserveOther/entity/TripResponse.java delete mode 100644 ts-preserve-other-service/src/main/java/preserveOther/entity/Type.java delete mode 100644 ts-preserve-other-service/src/main/java/preserveOther/entity/User.java delete mode 100644 ts-preserve-service/src/main/java/preserve/entity/Account.java delete mode 100644 ts-preserve-service/src/main/java/preserve/entity/Assurance.java delete mode 100644 ts-preserve-service/src/main/java/preserve/entity/AssuranceType.java delete mode 100644 ts-preserve-service/src/main/java/preserve/entity/Contacts.java delete mode 100644 ts-preserve-service/src/main/java/preserve/entity/DocumentType.java delete mode 100644 ts-preserve-service/src/main/java/preserve/entity/Gender.java delete mode 100644 ts-preserve-service/src/main/java/preserve/entity/Order.java delete mode 100644 ts-preserve-service/src/main/java/preserve/entity/OrderTicketsInfo.java delete mode 100644 ts-preserve-service/src/main/java/preserve/entity/OrderTicketsResult.java delete mode 100644 ts-preserve-service/src/main/java/preserve/entity/Seat.java delete mode 100644 ts-preserve-service/src/main/java/preserve/entity/SeatClass.java delete mode 100644 ts-preserve-service/src/main/java/preserve/entity/Ticket.java delete mode 100644 ts-preserve-service/src/main/java/preserve/entity/TrainType.java delete mode 100644 ts-preserve-service/src/main/java/preserve/entity/Travel.java delete mode 100644 ts-preserve-service/src/main/java/preserve/entity/TravelResult.java delete mode 100644 ts-preserve-service/src/main/java/preserve/entity/Trip.java delete mode 100644 ts-preserve-service/src/main/java/preserve/entity/TripAllDetailInfo.java delete mode 100644 ts-preserve-service/src/main/java/preserve/entity/TripId.java delete mode 100644 ts-preserve-service/src/main/java/preserve/entity/TripResponse.java delete mode 100644 ts-preserve-service/src/main/java/preserve/entity/Type.java delete mode 100644 ts-rebook-service/src/main/java/rebook/entity/Contacts.java delete mode 100644 ts-rebook-service/src/main/java/rebook/entity/OrderStatus.java delete mode 100644 ts-rebook-service/src/main/java/rebook/entity/OrderTicketsInfo.java delete mode 100644 ts-rebook-service/src/main/java/rebook/entity/SeatClass.java delete mode 100644 ts-rebook-service/src/main/java/rebook/entity/Ticket.java delete mode 100644 ts-rebook-service/src/main/java/rebook/entity/Trip.java delete mode 100644 ts-rebook-service/src/main/java/rebook/entity/TripAllDetail.java delete mode 100644 ts-rebook-service/src/main/java/rebook/entity/TripAllDetailInfo.java delete mode 100644 ts-rebook-service/src/main/java/rebook/entity/TripResponse.java delete mode 100644 ts-route-plan-service/src/main/java/plan/entity/Route.java delete mode 100644 ts-route-plan-service/src/main/java/plan/entity/RoutePlanInfo.java delete mode 100644 ts-route-plan-service/src/main/java/plan/entity/RoutePlanResultUnit.java delete mode 100644 ts-route-plan-service/src/main/java/plan/entity/Trip.java delete mode 100644 ts-route-plan-service/src/main/java/plan/entity/TripAllDetail.java delete mode 100644 ts-route-plan-service/src/main/java/plan/entity/TripAllDetailInfo.java delete mode 100644 ts-route-plan-service/src/main/java/plan/entity/TripId.java delete mode 100644 ts-route-plan-service/src/main/java/plan/entity/TripInfo.java delete mode 100644 ts-route-plan-service/src/main/java/plan/entity/TripResponse.java delete mode 100644 ts-route-plan-service/src/main/java/plan/entity/Type.java delete mode 100644 ts-seat-service/src/main/java/seat/entity/Config.java delete mode 100644 ts-seat-service/src/main/java/seat/entity/LeftTicketInfo.java delete mode 100644 ts-seat-service/src/main/java/seat/entity/Route.java delete mode 100644 ts-seat-service/src/main/java/seat/entity/Seat.java delete mode 100644 ts-seat-service/src/main/java/seat/entity/SeatClass.java delete mode 100644 ts-seat-service/src/main/java/seat/entity/Ticket.java delete mode 100644 ts-seat-service/src/main/java/seat/entity/TrainType.java delete mode 100644 ts-security-service/src/main/java/security/entity/Order.java delete mode 100644 ts-security-service/src/main/java/security/entity/OrderStatus.java delete mode 100644 ts-security-service/src/main/java/security/entity/SeatClass.java create mode 100644 ts-station-food-service/Dockerfile rename {ts-ticketinfo-service => ts-station-food-service}/pom.xml (64%) rename ts-ticketinfo-service/src/main/java/ticketinfo/TicketInfoApplication.java => ts-station-food-service/src/main/java/food/StationFoodApplication.java (74%) rename {ts-food-map-service => ts-station-food-service}/src/main/java/food/config/SecurityConfig.java (97%) create mode 100644 ts-station-food-service/src/main/java/food/controller/StationFoodController.java create mode 100644 ts-station-food-service/src/main/java/food/entity/StationFoodStore.java rename {ts-food-map-service => ts-station-food-service}/src/main/java/food/init/InitData.java (65%) create mode 100644 ts-station-food-service/src/main/java/food/repository/StationFoodRepository.java create mode 100644 ts-station-food-service/src/main/java/food/service/StationFoodService.java create mode 100644 ts-station-food-service/src/main/java/food/service/StationFoodServiceImpl.java create mode 100644 ts-station-food-service/src/main/resources/application.yml rename {ts-food-map-service => ts-station-food-service}/src/main/resources/foodstores.txt (100%) rename ts-food-map-service/src/test/java/food/controller/FoodStoreControllerTest.java => ts-station-food-service/src/test/java/food/controller/StationFoodControllerTest.java (71%) create mode 100644 ts-station-food-service/src/test/java/food/service/StationFoodServiceImplTest.java mode change 100644 => 120000 ts-ticket-office-service/node_modules/.bin/acorn mode change 100644 => 120000 ts-ticket-office-service/node_modules/.bin/cleancss mode change 100644 => 120000 ts-ticket-office-service/node_modules/.bin/jade mode change 100644 => 120000 ts-ticket-office-service/node_modules/.bin/mime mode change 100644 => 120000 ts-ticket-office-service/node_modules/.bin/mkdirp delete mode 100644 ts-ticket-office-service/node_modules/.bin/semver mode change 100644 => 120000 ts-ticket-office-service/node_modules/.bin/uglifyjs create mode 100644 ts-ticket-office-service/node_modules/.package-lock.json create mode 100755 ts-ticket-office-service/node_modules/@types/node/LICENSE create mode 100755 ts-ticket-office-service/node_modules/@types/node/README.md create mode 100755 ts-ticket-office-service/node_modules/@types/node/assert.d.ts create mode 100755 ts-ticket-office-service/node_modules/@types/node/assert/strict.d.ts create mode 100755 ts-ticket-office-service/node_modules/@types/node/async_hooks.d.ts create mode 100755 ts-ticket-office-service/node_modules/@types/node/buffer.d.ts create mode 100755 ts-ticket-office-service/node_modules/@types/node/child_process.d.ts create mode 100755 ts-ticket-office-service/node_modules/@types/node/cluster.d.ts create mode 100755 ts-ticket-office-service/node_modules/@types/node/console.d.ts create mode 100755 ts-ticket-office-service/node_modules/@types/node/constants.d.ts create mode 100755 ts-ticket-office-service/node_modules/@types/node/crypto.d.ts create mode 100755 ts-ticket-office-service/node_modules/@types/node/dgram.d.ts create mode 100755 ts-ticket-office-service/node_modules/@types/node/diagnostics_channel.d.ts create mode 100755 ts-ticket-office-service/node_modules/@types/node/dns.d.ts create mode 100755 ts-ticket-office-service/node_modules/@types/node/dns/promises.d.ts create mode 100755 ts-ticket-office-service/node_modules/@types/node/domain.d.ts create mode 100755 ts-ticket-office-service/node_modules/@types/node/events.d.ts create mode 100755 ts-ticket-office-service/node_modules/@types/node/fs.d.ts create mode 100755 ts-ticket-office-service/node_modules/@types/node/fs/promises.d.ts create mode 100755 ts-ticket-office-service/node_modules/@types/node/globals.d.ts create mode 100755 ts-ticket-office-service/node_modules/@types/node/globals.global.d.ts create mode 100755 ts-ticket-office-service/node_modules/@types/node/http.d.ts create mode 100755 ts-ticket-office-service/node_modules/@types/node/http2.d.ts create mode 100755 ts-ticket-office-service/node_modules/@types/node/https.d.ts create mode 100755 ts-ticket-office-service/node_modules/@types/node/index.d.ts create mode 100755 ts-ticket-office-service/node_modules/@types/node/inspector.d.ts create mode 100755 ts-ticket-office-service/node_modules/@types/node/module.d.ts create mode 100755 ts-ticket-office-service/node_modules/@types/node/net.d.ts create mode 100755 ts-ticket-office-service/node_modules/@types/node/os.d.ts create mode 100755 ts-ticket-office-service/node_modules/@types/node/package.json create mode 100755 ts-ticket-office-service/node_modules/@types/node/path.d.ts create mode 100755 ts-ticket-office-service/node_modules/@types/node/perf_hooks.d.ts create mode 100755 ts-ticket-office-service/node_modules/@types/node/process.d.ts create mode 100755 ts-ticket-office-service/node_modules/@types/node/punycode.d.ts create mode 100755 ts-ticket-office-service/node_modules/@types/node/querystring.d.ts create mode 100755 ts-ticket-office-service/node_modules/@types/node/readline.d.ts create mode 100755 ts-ticket-office-service/node_modules/@types/node/repl.d.ts create mode 100755 ts-ticket-office-service/node_modules/@types/node/stream.d.ts create mode 100755 ts-ticket-office-service/node_modules/@types/node/stream/consumers.d.ts create mode 100755 ts-ticket-office-service/node_modules/@types/node/stream/promises.d.ts create mode 100755 ts-ticket-office-service/node_modules/@types/node/stream/web.d.ts create mode 100755 ts-ticket-office-service/node_modules/@types/node/string_decoder.d.ts create mode 100755 ts-ticket-office-service/node_modules/@types/node/test.d.ts create mode 100755 ts-ticket-office-service/node_modules/@types/node/timers.d.ts create mode 100755 ts-ticket-office-service/node_modules/@types/node/timers/promises.d.ts create mode 100755 ts-ticket-office-service/node_modules/@types/node/tls.d.ts create mode 100755 ts-ticket-office-service/node_modules/@types/node/trace_events.d.ts create mode 100755 ts-ticket-office-service/node_modules/@types/node/tty.d.ts create mode 100755 ts-ticket-office-service/node_modules/@types/node/url.d.ts create mode 100755 ts-ticket-office-service/node_modules/@types/node/util.d.ts create mode 100755 ts-ticket-office-service/node_modules/@types/node/v8.d.ts create mode 100755 ts-ticket-office-service/node_modules/@types/node/vm.d.ts create mode 100755 ts-ticket-office-service/node_modules/@types/node/wasi.d.ts create mode 100755 ts-ticket-office-service/node_modules/@types/node/worker_threads.d.ts create mode 100755 ts-ticket-office-service/node_modules/@types/node/zlib.d.ts create mode 100755 ts-ticket-office-service/node_modules/@types/webidl-conversions/LICENSE create mode 100755 ts-ticket-office-service/node_modules/@types/webidl-conversions/README.md create mode 100755 ts-ticket-office-service/node_modules/@types/webidl-conversions/index.d.ts create mode 100755 ts-ticket-office-service/node_modules/@types/webidl-conversions/package.json create mode 100755 ts-ticket-office-service/node_modules/@types/whatwg-url/LICENSE create mode 100755 ts-ticket-office-service/node_modules/@types/whatwg-url/README.md create mode 100755 ts-ticket-office-service/node_modules/@types/whatwg-url/index.d.ts create mode 100755 ts-ticket-office-service/node_modules/@types/whatwg-url/package.json create mode 100755 ts-ticket-office-service/node_modules/@types/whatwg-url/webidl2js-wrapper.d.ts mode change 100644 => 100755 ts-ticket-office-service/node_modules/acorn/bin/acorn rename ts-ticket-office-service/node_modules/{resolve-from/license => base64-js/LICENSE} (93%) create mode 100644 ts-ticket-office-service/node_modules/base64-js/README.md create mode 100644 ts-ticket-office-service/node_modules/base64-js/base64js.min.js create mode 100644 ts-ticket-office-service/node_modules/base64-js/index.d.ts create mode 100644 ts-ticket-office-service/node_modules/base64-js/index.js create mode 100644 ts-ticket-office-service/node_modules/base64-js/package.json create mode 100644 ts-ticket-office-service/node_modules/bignumber.js/CHANGELOG.md create mode 100644 ts-ticket-office-service/node_modules/bignumber.js/LICENCE create mode 100644 ts-ticket-office-service/node_modules/bignumber.js/README.md create mode 100644 ts-ticket-office-service/node_modules/bignumber.js/bignumber.d.ts create mode 100644 ts-ticket-office-service/node_modules/bignumber.js/bignumber.js create mode 100644 ts-ticket-office-service/node_modules/bignumber.js/bignumber.min.js create mode 100644 ts-ticket-office-service/node_modules/bignumber.js/bignumber.min.js.map create mode 100644 ts-ticket-office-service/node_modules/bignumber.js/bignumber.mjs create mode 100644 ts-ticket-office-service/node_modules/bignumber.js/doc/API.html create mode 100644 ts-ticket-office-service/node_modules/bignumber.js/package.json delete mode 100644 ts-ticket-office-service/node_modules/bson/HISTORY.md delete mode 100644 ts-ticket-office-service/node_modules/bson/browser_build/bson.js delete mode 100644 ts-ticket-office-service/node_modules/bson/browser_build/package.json create mode 100644 ts-ticket-office-service/node_modules/bson/bson.d.ts create mode 100755 ts-ticket-office-service/node_modules/bson/etc/prepare.js delete mode 100644 ts-ticket-office-service/node_modules/bson/index.js create mode 100644 ts-ticket-office-service/node_modules/bson/lib/binary.js create mode 100644 ts-ticket-office-service/node_modules/bson/lib/binary.js.map create mode 100644 ts-ticket-office-service/node_modules/bson/lib/bson.js create mode 100644 ts-ticket-office-service/node_modules/bson/lib/bson.js.map delete mode 100644 ts-ticket-office-service/node_modules/bson/lib/bson/binary.js delete mode 100644 ts-ticket-office-service/node_modules/bson/lib/bson/bson.js delete mode 100644 ts-ticket-office-service/node_modules/bson/lib/bson/code.js delete mode 100644 ts-ticket-office-service/node_modules/bson/lib/bson/db_ref.js delete mode 100644 ts-ticket-office-service/node_modules/bson/lib/bson/decimal128.js delete mode 100644 ts-ticket-office-service/node_modules/bson/lib/bson/double.js delete mode 100644 ts-ticket-office-service/node_modules/bson/lib/bson/float_parser.js delete mode 100644 ts-ticket-office-service/node_modules/bson/lib/bson/int_32.js delete mode 100644 ts-ticket-office-service/node_modules/bson/lib/bson/long.js delete mode 100644 ts-ticket-office-service/node_modules/bson/lib/bson/map.js delete mode 100644 ts-ticket-office-service/node_modules/bson/lib/bson/max_key.js delete mode 100644 ts-ticket-office-service/node_modules/bson/lib/bson/min_key.js delete mode 100644 ts-ticket-office-service/node_modules/bson/lib/bson/objectid.js delete mode 100644 ts-ticket-office-service/node_modules/bson/lib/bson/parser/calculate_size.js delete mode 100644 ts-ticket-office-service/node_modules/bson/lib/bson/parser/deserializer.js delete mode 100644 ts-ticket-office-service/node_modules/bson/lib/bson/parser/serializer.js delete mode 100644 ts-ticket-office-service/node_modules/bson/lib/bson/regexp.js delete mode 100644 ts-ticket-office-service/node_modules/bson/lib/bson/symbol.js delete mode 100644 ts-ticket-office-service/node_modules/bson/lib/bson/timestamp.js create mode 100644 ts-ticket-office-service/node_modules/bson/lib/code.js create mode 100644 ts-ticket-office-service/node_modules/bson/lib/code.js.map create mode 100644 ts-ticket-office-service/node_modules/bson/lib/constants.js create mode 100644 ts-ticket-office-service/node_modules/bson/lib/constants.js.map create mode 100644 ts-ticket-office-service/node_modules/bson/lib/db_ref.js create mode 100644 ts-ticket-office-service/node_modules/bson/lib/db_ref.js.map create mode 100644 ts-ticket-office-service/node_modules/bson/lib/decimal128.js create mode 100644 ts-ticket-office-service/node_modules/bson/lib/decimal128.js.map create mode 100644 ts-ticket-office-service/node_modules/bson/lib/double.js create mode 100644 ts-ticket-office-service/node_modules/bson/lib/double.js.map create mode 100644 ts-ticket-office-service/node_modules/bson/lib/ensure_buffer.js create mode 100644 ts-ticket-office-service/node_modules/bson/lib/ensure_buffer.js.map create mode 100644 ts-ticket-office-service/node_modules/bson/lib/error.js create mode 100644 ts-ticket-office-service/node_modules/bson/lib/error.js.map create mode 100644 ts-ticket-office-service/node_modules/bson/lib/extended_json.js create mode 100644 ts-ticket-office-service/node_modules/bson/lib/extended_json.js.map create mode 100644 ts-ticket-office-service/node_modules/bson/lib/int_32.js create mode 100644 ts-ticket-office-service/node_modules/bson/lib/int_32.js.map create mode 100644 ts-ticket-office-service/node_modules/bson/lib/long.js create mode 100644 ts-ticket-office-service/node_modules/bson/lib/long.js.map create mode 100644 ts-ticket-office-service/node_modules/bson/lib/map.js create mode 100644 ts-ticket-office-service/node_modules/bson/lib/map.js.map create mode 100644 ts-ticket-office-service/node_modules/bson/lib/max_key.js create mode 100644 ts-ticket-office-service/node_modules/bson/lib/max_key.js.map create mode 100644 ts-ticket-office-service/node_modules/bson/lib/min_key.js create mode 100644 ts-ticket-office-service/node_modules/bson/lib/min_key.js.map create mode 100644 ts-ticket-office-service/node_modules/bson/lib/objectid.js create mode 100644 ts-ticket-office-service/node_modules/bson/lib/objectid.js.map create mode 100644 ts-ticket-office-service/node_modules/bson/lib/parser/calculate_size.js create mode 100644 ts-ticket-office-service/node_modules/bson/lib/parser/calculate_size.js.map create mode 100644 ts-ticket-office-service/node_modules/bson/lib/parser/deserializer.js create mode 100644 ts-ticket-office-service/node_modules/bson/lib/parser/deserializer.js.map create mode 100644 ts-ticket-office-service/node_modules/bson/lib/parser/serializer.js create mode 100644 ts-ticket-office-service/node_modules/bson/lib/parser/serializer.js.map create mode 100644 ts-ticket-office-service/node_modules/bson/lib/parser/utils.js create mode 100644 ts-ticket-office-service/node_modules/bson/lib/parser/utils.js.map create mode 100644 ts-ticket-office-service/node_modules/bson/lib/regexp.js create mode 100644 ts-ticket-office-service/node_modules/bson/lib/regexp.js.map create mode 100644 ts-ticket-office-service/node_modules/bson/lib/symbol.js create mode 100644 ts-ticket-office-service/node_modules/bson/lib/symbol.js.map create mode 100644 ts-ticket-office-service/node_modules/bson/lib/timestamp.js create mode 100644 ts-ticket-office-service/node_modules/bson/lib/timestamp.js.map create mode 100644 ts-ticket-office-service/node_modules/bson/lib/utils/global.js create mode 100644 ts-ticket-office-service/node_modules/bson/lib/utils/global.js.map create mode 100644 ts-ticket-office-service/node_modules/bson/lib/uuid.js create mode 100644 ts-ticket-office-service/node_modules/bson/lib/uuid.js.map create mode 100644 ts-ticket-office-service/node_modules/bson/lib/uuid_utils.js create mode 100644 ts-ticket-office-service/node_modules/bson/lib/uuid_utils.js.map create mode 100644 ts-ticket-office-service/node_modules/bson/lib/validate_utf8.js create mode 100644 ts-ticket-office-service/node_modules/bson/lib/validate_utf8.js.map create mode 100644 ts-ticket-office-service/node_modules/bson/src/binary.ts create mode 100644 ts-ticket-office-service/node_modules/bson/src/bson.ts create mode 100644 ts-ticket-office-service/node_modules/bson/src/code.ts create mode 100644 ts-ticket-office-service/node_modules/bson/src/constants.ts create mode 100644 ts-ticket-office-service/node_modules/bson/src/db_ref.ts create mode 100644 ts-ticket-office-service/node_modules/bson/src/decimal128.ts create mode 100644 ts-ticket-office-service/node_modules/bson/src/double.ts create mode 100644 ts-ticket-office-service/node_modules/bson/src/ensure_buffer.ts create mode 100644 ts-ticket-office-service/node_modules/bson/src/error.ts create mode 100644 ts-ticket-office-service/node_modules/bson/src/extended_json.ts create mode 100644 ts-ticket-office-service/node_modules/bson/src/int_32.ts create mode 100644 ts-ticket-office-service/node_modules/bson/src/long.ts create mode 100644 ts-ticket-office-service/node_modules/bson/src/map.ts create mode 100644 ts-ticket-office-service/node_modules/bson/src/max_key.ts create mode 100644 ts-ticket-office-service/node_modules/bson/src/min_key.ts create mode 100644 ts-ticket-office-service/node_modules/bson/src/objectid.ts create mode 100644 ts-ticket-office-service/node_modules/bson/src/parser/calculate_size.ts create mode 100644 ts-ticket-office-service/node_modules/bson/src/parser/deserializer.ts create mode 100644 ts-ticket-office-service/node_modules/bson/src/parser/serializer.ts create mode 100644 ts-ticket-office-service/node_modules/bson/src/parser/utils.ts create mode 100644 ts-ticket-office-service/node_modules/bson/src/regexp.ts create mode 100644 ts-ticket-office-service/node_modules/bson/src/symbol.ts create mode 100644 ts-ticket-office-service/node_modules/bson/src/timestamp.ts create mode 100644 ts-ticket-office-service/node_modules/bson/src/utils/global.ts create mode 100644 ts-ticket-office-service/node_modules/bson/src/uuid.ts create mode 100644 ts-ticket-office-service/node_modules/bson/src/uuid_utils.ts create mode 100644 ts-ticket-office-service/node_modules/bson/src/validate_utf8.ts delete mode 100644 ts-ticket-office-service/node_modules/buffer-shims/index.js delete mode 100644 ts-ticket-office-service/node_modules/buffer-shims/package.json delete mode 100644 ts-ticket-office-service/node_modules/buffer-shims/readme.md create mode 100644 ts-ticket-office-service/node_modules/buffer/AUTHORS.md create mode 100644 ts-ticket-office-service/node_modules/buffer/LICENSE create mode 100644 ts-ticket-office-service/node_modules/buffer/README.md create mode 100644 ts-ticket-office-service/node_modules/buffer/index.d.ts create mode 100644 ts-ticket-office-service/node_modules/buffer/index.js create mode 100644 ts-ticket-office-service/node_modules/buffer/package.json mode change 100644 => 100755 ts-ticket-office-service/node_modules/clean-css/bin/cleancss create mode 100644 ts-ticket-office-service/node_modules/denque/CHANGELOG.md rename ts-ticket-office-service/node_modules/{require_optional => denque}/LICENSE (99%) create mode 100644 ts-ticket-office-service/node_modules/denque/README.md create mode 100644 ts-ticket-office-service/node_modules/denque/index.d.ts create mode 100644 ts-ticket-office-service/node_modules/denque/index.js create mode 100644 ts-ticket-office-service/node_modules/denque/package.json delete mode 100644 ts-ticket-office-service/node_modules/es6-promise/CHANGELOG.md delete mode 100644 ts-ticket-office-service/node_modules/es6-promise/README.md delete mode 100644 ts-ticket-office-service/node_modules/es6-promise/dist/es6-promise.js delete mode 100644 ts-ticket-office-service/node_modules/es6-promise/dist/es6-promise.min.js delete mode 100644 ts-ticket-office-service/node_modules/es6-promise/lib/es6-promise.umd.js delete mode 100644 ts-ticket-office-service/node_modules/es6-promise/lib/es6-promise/-internal.js delete mode 100644 ts-ticket-office-service/node_modules/es6-promise/lib/es6-promise/asap.js delete mode 100644 ts-ticket-office-service/node_modules/es6-promise/lib/es6-promise/enumerator.js delete mode 100644 ts-ticket-office-service/node_modules/es6-promise/lib/es6-promise/polyfill.js delete mode 100644 ts-ticket-office-service/node_modules/es6-promise/lib/es6-promise/promise.js delete mode 100644 ts-ticket-office-service/node_modules/es6-promise/lib/es6-promise/promise/all.js delete mode 100644 ts-ticket-office-service/node_modules/es6-promise/lib/es6-promise/promise/race.js delete mode 100644 ts-ticket-office-service/node_modules/es6-promise/lib/es6-promise/promise/reject.js delete mode 100644 ts-ticket-office-service/node_modules/es6-promise/lib/es6-promise/promise/resolve.js delete mode 100644 ts-ticket-office-service/node_modules/es6-promise/lib/es6-promise/then.js delete mode 100644 ts-ticket-office-service/node_modules/es6-promise/lib/es6-promise/utils.js delete mode 100644 ts-ticket-office-service/node_modules/es6-promise/package.json create mode 100644 ts-ticket-office-service/node_modules/ieee754/LICENSE create mode 100644 ts-ticket-office-service/node_modules/ieee754/README.md create mode 100644 ts-ticket-office-service/node_modules/ieee754/index.d.ts create mode 100644 ts-ticket-office-service/node_modules/ieee754/index.js create mode 100644 ts-ticket-office-service/node_modules/ieee754/package.json create mode 100644 ts-ticket-office-service/node_modules/ip/README.md create mode 100644 ts-ticket-office-service/node_modules/ip/lib/ip.js create mode 100644 ts-ticket-office-service/node_modules/ip/package.json mode change 100644 => 100755 ts-ticket-office-service/node_modules/jade/bin/jade.js rename ts-ticket-office-service/node_modules/{es6-promise => memory-pager}/LICENSE (51%) create mode 100644 ts-ticket-office-service/node_modules/memory-pager/README.md create mode 100644 ts-ticket-office-service/node_modules/memory-pager/index.js create mode 100644 ts-ticket-office-service/node_modules/memory-pager/package.json create mode 100644 ts-ticket-office-service/node_modules/memory-pager/test.js mode change 100644 => 100755 ts-ticket-office-service/node_modules/mime/cli.js create mode 100644 ts-ticket-office-service/node_modules/minimist/test/all_bool.js create mode 100644 ts-ticket-office-service/node_modules/minimist/test/bool.js create mode 100644 ts-ticket-office-service/node_modules/minimist/test/kv_short.js create mode 100644 ts-ticket-office-service/node_modules/minimist/test/num.js create mode 100644 ts-ticket-office-service/node_modules/minimist/test/proto.js create mode 100644 ts-ticket-office-service/node_modules/minimist/test/stop_early.js create mode 100644 ts-ticket-office-service/node_modules/minimist/test/unknown.js delete mode 100644 ts-ticket-office-service/node_modules/mkdirp/.travis.yml mode change 100644 => 100755 ts-ticket-office-service/node_modules/mkdirp/bin/cmd.js delete mode 100644 ts-ticket-office-service/node_modules/mkdirp/examples/pow.js delete mode 100644 ts-ticket-office-service/node_modules/mkdirp/test/chmod.js delete mode 100644 ts-ticket-office-service/node_modules/mkdirp/test/clobber.js delete mode 100644 ts-ticket-office-service/node_modules/mkdirp/test/mkdirp.js delete mode 100644 ts-ticket-office-service/node_modules/mkdirp/test/opts_fs.js delete mode 100644 ts-ticket-office-service/node_modules/mkdirp/test/opts_fs_sync.js delete mode 100644 ts-ticket-office-service/node_modules/mkdirp/test/perm.js delete mode 100644 ts-ticket-office-service/node_modules/mkdirp/test/perm_sync.js delete mode 100644 ts-ticket-office-service/node_modules/mkdirp/test/race.js delete mode 100644 ts-ticket-office-service/node_modules/mkdirp/test/rel.js delete mode 100644 ts-ticket-office-service/node_modules/mkdirp/test/return.js delete mode 100644 ts-ticket-office-service/node_modules/mkdirp/test/return_sync.js delete mode 100644 ts-ticket-office-service/node_modules/mkdirp/test/root.js delete mode 100644 ts-ticket-office-service/node_modules/mkdirp/test/sync.js delete mode 100644 ts-ticket-office-service/node_modules/mkdirp/test/umask.js delete mode 100644 ts-ticket-office-service/node_modules/mkdirp/test/umask_sync.js create mode 100644 ts-ticket-office-service/node_modules/mongodb-connection-string-url/.esm-wrapper.mjs rename ts-ticket-office-service/node_modules/{mongodb => mongodb-connection-string-url}/LICENSE (94%) create mode 100644 ts-ticket-office-service/node_modules/mongodb-connection-string-url/README.md create mode 100644 ts-ticket-office-service/node_modules/mongodb-connection-string-url/lib/index.d.ts create mode 100644 ts-ticket-office-service/node_modules/mongodb-connection-string-url/lib/index.js create mode 100644 ts-ticket-office-service/node_modules/mongodb-connection-string-url/lib/index.js.map create mode 100644 ts-ticket-office-service/node_modules/mongodb-connection-string-url/lib/redact.d.ts create mode 100644 ts-ticket-office-service/node_modules/mongodb-connection-string-url/lib/redact.js create mode 100644 ts-ticket-office-service/node_modules/mongodb-connection-string-url/lib/redact.js.map create mode 100644 ts-ticket-office-service/node_modules/mongodb-connection-string-url/package.json delete mode 100644 ts-ticket-office-service/node_modules/mongodb-core/.coveralls.yml delete mode 100644 ts-ticket-office-service/node_modules/mongodb-core/.eslintrc delete mode 100644 ts-ticket-office-service/node_modules/mongodb-core/HISTORY.md delete mode 100644 ts-ticket-office-service/node_modules/mongodb-core/Makefile delete mode 100644 ts-ticket-office-service/node_modules/mongodb-core/README.md delete mode 100644 ts-ticket-office-service/node_modules/mongodb-core/TESTING.md delete mode 100644 ts-ticket-office-service/node_modules/mongodb-core/THIRD-PARTY-NOTICES delete mode 100644 ts-ticket-office-service/node_modules/mongodb-core/conf.json delete mode 100644 ts-ticket-office-service/node_modules/mongodb-core/index.js delete mode 100644 ts-ticket-office-service/node_modules/mongodb-core/lib/auth/gssapi.js delete mode 100644 ts-ticket-office-service/node_modules/mongodb-core/lib/auth/mongocr.js delete mode 100644 ts-ticket-office-service/node_modules/mongodb-core/lib/auth/plain.js delete mode 100644 ts-ticket-office-service/node_modules/mongodb-core/lib/auth/scram.js delete mode 100644 ts-ticket-office-service/node_modules/mongodb-core/lib/auth/sspi.js delete mode 100644 ts-ticket-office-service/node_modules/mongodb-core/lib/auth/x509.js delete mode 100644 ts-ticket-office-service/node_modules/mongodb-core/lib/connection/command_result.js delete mode 100644 ts-ticket-office-service/node_modules/mongodb-core/lib/connection/commands.js delete mode 100644 ts-ticket-office-service/node_modules/mongodb-core/lib/connection/connection.js delete mode 100644 ts-ticket-office-service/node_modules/mongodb-core/lib/connection/logger.js delete mode 100644 ts-ticket-office-service/node_modules/mongodb-core/lib/connection/pool.js delete mode 100644 ts-ticket-office-service/node_modules/mongodb-core/lib/connection/utils.js delete mode 100644 ts-ticket-office-service/node_modules/mongodb-core/lib/cursor.js delete mode 100644 ts-ticket-office-service/node_modules/mongodb-core/lib/error.js delete mode 100644 ts-ticket-office-service/node_modules/mongodb-core/lib/tools/smoke_plugin.js delete mode 100644 ts-ticket-office-service/node_modules/mongodb-core/lib/topologies/mongos.js delete mode 100644 ts-ticket-office-service/node_modules/mongodb-core/lib/topologies/read_preference.js delete mode 100644 ts-ticket-office-service/node_modules/mongodb-core/lib/topologies/replset.js delete mode 100644 ts-ticket-office-service/node_modules/mongodb-core/lib/topologies/replset_state.js delete mode 100644 ts-ticket-office-service/node_modules/mongodb-core/lib/topologies/server.js delete mode 100644 ts-ticket-office-service/node_modules/mongodb-core/lib/topologies/shared.js delete mode 100644 ts-ticket-office-service/node_modules/mongodb-core/lib/utils.js delete mode 100644 ts-ticket-office-service/node_modules/mongodb-core/lib/wireprotocol/2_4_support.js delete mode 100644 ts-ticket-office-service/node_modules/mongodb-core/lib/wireprotocol/2_6_support.js delete mode 100644 ts-ticket-office-service/node_modules/mongodb-core/lib/wireprotocol/3_2_support.js delete mode 100644 ts-ticket-office-service/node_modules/mongodb-core/lib/wireprotocol/commands.js delete mode 100644 ts-ticket-office-service/node_modules/mongodb-core/lib/wireprotocol/shared.js delete mode 100644 ts-ticket-office-service/node_modules/mongodb-core/package.json delete mode 100644 ts-ticket-office-service/node_modules/mongodb-core/test.js delete mode 100644 ts-ticket-office-service/node_modules/mongodb-core/test1.js delete mode 100644 ts-ticket-office-service/node_modules/mongodb-core/yarn.lock delete mode 100644 ts-ticket-office-service/node_modules/mongodb/.coveralls.yml delete mode 100644 ts-ticket-office-service/node_modules/mongodb/.eslintrc delete mode 100644 ts-ticket-office-service/node_modules/mongodb/HISTORY.md rename ts-ticket-office-service/node_modules/{mongodb-core/LICENSE => mongodb/LICENSE.md} (100%) delete mode 100644 ts-ticket-office-service/node_modules/mongodb/Makefile delete mode 100644 ts-ticket-office-service/node_modules/mongodb/THIRD-PARTY-NOTICES delete mode 100644 ts-ticket-office-service/node_modules/mongodb/boot_auth.js delete mode 100644 ts-ticket-office-service/node_modules/mongodb/conf.json create mode 100755 ts-ticket-office-service/node_modules/mongodb/etc/prepare.js delete mode 100644 ts-ticket-office-service/node_modules/mongodb/index.js delete mode 100644 ts-ticket-office-service/node_modules/mongodb/insert_bench.js create mode 100644 ts-ticket-office-service/node_modules/mongodb/lib/admin.js.map delete mode 100644 ts-ticket-office-service/node_modules/mongodb/lib/aggregation_cursor.js delete mode 100644 ts-ticket-office-service/node_modules/mongodb/lib/apm.js delete mode 100644 ts-ticket-office-service/node_modules/mongodb/lib/authenticate.js create mode 100644 ts-ticket-office-service/node_modules/mongodb/lib/bson.js create mode 100644 ts-ticket-office-service/node_modules/mongodb/lib/bson.js.map create mode 100644 ts-ticket-office-service/node_modules/mongodb/lib/bulk/common.js.map create mode 100644 ts-ticket-office-service/node_modules/mongodb/lib/bulk/ordered.js.map create mode 100644 ts-ticket-office-service/node_modules/mongodb/lib/bulk/unordered.js.map create mode 100644 ts-ticket-office-service/node_modules/mongodb/lib/change_stream.js create mode 100644 ts-ticket-office-service/node_modules/mongodb/lib/change_stream.js.map create mode 100644 ts-ticket-office-service/node_modules/mongodb/lib/cmap/auth/auth_provider.js create mode 100644 ts-ticket-office-service/node_modules/mongodb/lib/cmap/auth/auth_provider.js.map create mode 100644 ts-ticket-office-service/node_modules/mongodb/lib/cmap/auth/gssapi.js create mode 100644 ts-ticket-office-service/node_modules/mongodb/lib/cmap/auth/gssapi.js.map create mode 100644 ts-ticket-office-service/node_modules/mongodb/lib/cmap/auth/mongo_credentials.js create mode 100644 ts-ticket-office-service/node_modules/mongodb/lib/cmap/auth/mongo_credentials.js.map create mode 100644 ts-ticket-office-service/node_modules/mongodb/lib/cmap/auth/mongocr.js create mode 100644 ts-ticket-office-service/node_modules/mongodb/lib/cmap/auth/mongocr.js.map create mode 100644 ts-ticket-office-service/node_modules/mongodb/lib/cmap/auth/mongodb_aws.js create mode 100644 ts-ticket-office-service/node_modules/mongodb/lib/cmap/auth/mongodb_aws.js.map create mode 100644 ts-ticket-office-service/node_modules/mongodb/lib/cmap/auth/plain.js create mode 100644 ts-ticket-office-service/node_modules/mongodb/lib/cmap/auth/plain.js.map create mode 100644 ts-ticket-office-service/node_modules/mongodb/lib/cmap/auth/providers.js create mode 100644 ts-ticket-office-service/node_modules/mongodb/lib/cmap/auth/providers.js.map create mode 100644 ts-ticket-office-service/node_modules/mongodb/lib/cmap/auth/scram.js create mode 100644 ts-ticket-office-service/node_modules/mongodb/lib/cmap/auth/scram.js.map create mode 100644 ts-ticket-office-service/node_modules/mongodb/lib/cmap/auth/x509.js create mode 100644 ts-ticket-office-service/node_modules/mongodb/lib/cmap/auth/x509.js.map create mode 100644 ts-ticket-office-service/node_modules/mongodb/lib/cmap/command_monitoring_events.js create mode 100644 ts-ticket-office-service/node_modules/mongodb/lib/cmap/command_monitoring_events.js.map create mode 100644 ts-ticket-office-service/node_modules/mongodb/lib/cmap/commands.js create mode 100644 ts-ticket-office-service/node_modules/mongodb/lib/cmap/commands.js.map create mode 100644 ts-ticket-office-service/node_modules/mongodb/lib/cmap/connect.js create mode 100644 ts-ticket-office-service/node_modules/mongodb/lib/cmap/connect.js.map create mode 100644 ts-ticket-office-service/node_modules/mongodb/lib/cmap/connection.js create mode 100644 ts-ticket-office-service/node_modules/mongodb/lib/cmap/connection.js.map create mode 100644 ts-ticket-office-service/node_modules/mongodb/lib/cmap/connection_pool.js create mode 100644 ts-ticket-office-service/node_modules/mongodb/lib/cmap/connection_pool.js.map create mode 100644 ts-ticket-office-service/node_modules/mongodb/lib/cmap/connection_pool_events.js create mode 100644 ts-ticket-office-service/node_modules/mongodb/lib/cmap/connection_pool_events.js.map create mode 100644 ts-ticket-office-service/node_modules/mongodb/lib/cmap/errors.js create mode 100644 ts-ticket-office-service/node_modules/mongodb/lib/cmap/errors.js.map create mode 100644 ts-ticket-office-service/node_modules/mongodb/lib/cmap/message_stream.js create mode 100644 ts-ticket-office-service/node_modules/mongodb/lib/cmap/message_stream.js.map create mode 100644 ts-ticket-office-service/node_modules/mongodb/lib/cmap/metrics.js create mode 100644 ts-ticket-office-service/node_modules/mongodb/lib/cmap/metrics.js.map create mode 100644 ts-ticket-office-service/node_modules/mongodb/lib/cmap/stream_description.js create mode 100644 ts-ticket-office-service/node_modules/mongodb/lib/cmap/stream_description.js.map create mode 100644 ts-ticket-office-service/node_modules/mongodb/lib/cmap/wire_protocol/compression.js create mode 100644 ts-ticket-office-service/node_modules/mongodb/lib/cmap/wire_protocol/compression.js.map create mode 100644 ts-ticket-office-service/node_modules/mongodb/lib/cmap/wire_protocol/constants.js create mode 100644 ts-ticket-office-service/node_modules/mongodb/lib/cmap/wire_protocol/constants.js.map create mode 100644 ts-ticket-office-service/node_modules/mongodb/lib/cmap/wire_protocol/shared.js create mode 100644 ts-ticket-office-service/node_modules/mongodb/lib/cmap/wire_protocol/shared.js.map create mode 100644 ts-ticket-office-service/node_modules/mongodb/lib/collection.js.map delete mode 100644 ts-ticket-office-service/node_modules/mongodb/lib/command_cursor.js create mode 100644 ts-ticket-office-service/node_modules/mongodb/lib/connection_string.js create mode 100644 ts-ticket-office-service/node_modules/mongodb/lib/connection_string.js.map create mode 100644 ts-ticket-office-service/node_modules/mongodb/lib/constants.js create mode 100644 ts-ticket-office-service/node_modules/mongodb/lib/constants.js.map delete mode 100644 ts-ticket-office-service/node_modules/mongodb/lib/cursor.js create mode 100644 ts-ticket-office-service/node_modules/mongodb/lib/cursor/abstract_cursor.js create mode 100644 ts-ticket-office-service/node_modules/mongodb/lib/cursor/abstract_cursor.js.map create mode 100644 ts-ticket-office-service/node_modules/mongodb/lib/cursor/aggregation_cursor.js create mode 100644 ts-ticket-office-service/node_modules/mongodb/lib/cursor/aggregation_cursor.js.map create mode 100644 ts-ticket-office-service/node_modules/mongodb/lib/cursor/change_stream_cursor.js create mode 100644 ts-ticket-office-service/node_modules/mongodb/lib/cursor/change_stream_cursor.js.map create mode 100644 ts-ticket-office-service/node_modules/mongodb/lib/cursor/find_cursor.js create mode 100644 ts-ticket-office-service/node_modules/mongodb/lib/cursor/find_cursor.js.map create mode 100644 ts-ticket-office-service/node_modules/mongodb/lib/cursor/list_collections_cursor.js create mode 100644 ts-ticket-office-service/node_modules/mongodb/lib/cursor/list_collections_cursor.js.map create mode 100644 ts-ticket-office-service/node_modules/mongodb/lib/cursor/list_indexes_cursor.js create mode 100644 ts-ticket-office-service/node_modules/mongodb/lib/cursor/list_indexes_cursor.js.map create mode 100644 ts-ticket-office-service/node_modules/mongodb/lib/db.js.map create mode 100644 ts-ticket-office-service/node_modules/mongodb/lib/deps.js create mode 100644 ts-ticket-office-service/node_modules/mongodb/lib/deps.js.map create mode 100644 ts-ticket-office-service/node_modules/mongodb/lib/encrypter.js create mode 100644 ts-ticket-office-service/node_modules/mongodb/lib/encrypter.js.map create mode 100644 ts-ticket-office-service/node_modules/mongodb/lib/error.js create mode 100644 ts-ticket-office-service/node_modules/mongodb/lib/error.js.map create mode 100644 ts-ticket-office-service/node_modules/mongodb/lib/explain.js create mode 100644 ts-ticket-office-service/node_modules/mongodb/lib/explain.js.map delete mode 100644 ts-ticket-office-service/node_modules/mongodb/lib/gridfs-stream/download.js delete mode 100644 ts-ticket-office-service/node_modules/mongodb/lib/gridfs-stream/index.js delete mode 100644 ts-ticket-office-service/node_modules/mongodb/lib/gridfs-stream/upload.js delete mode 100644 ts-ticket-office-service/node_modules/mongodb/lib/gridfs/chunk.js create mode 100644 ts-ticket-office-service/node_modules/mongodb/lib/gridfs/download.js create mode 100644 ts-ticket-office-service/node_modules/mongodb/lib/gridfs/download.js.map delete mode 100644 ts-ticket-office-service/node_modules/mongodb/lib/gridfs/grid_store.js create mode 100644 ts-ticket-office-service/node_modules/mongodb/lib/gridfs/index.js create mode 100644 ts-ticket-office-service/node_modules/mongodb/lib/gridfs/index.js.map create mode 100644 ts-ticket-office-service/node_modules/mongodb/lib/gridfs/upload.js create mode 100644 ts-ticket-office-service/node_modules/mongodb/lib/gridfs/upload.js.map create mode 100644 ts-ticket-office-service/node_modules/mongodb/lib/index.js create mode 100644 ts-ticket-office-service/node_modules/mongodb/lib/index.js.map create mode 100644 ts-ticket-office-service/node_modules/mongodb/lib/logger.js create mode 100644 ts-ticket-office-service/node_modules/mongodb/lib/logger.js.map delete mode 100644 ts-ticket-office-service/node_modules/mongodb/lib/metadata.js create mode 100644 ts-ticket-office-service/node_modules/mongodb/lib/mongo_client.js.map create mode 100644 ts-ticket-office-service/node_modules/mongodb/lib/mongo_types.js create mode 100644 ts-ticket-office-service/node_modules/mongodb/lib/mongo_types.js.map delete mode 100644 ts-ticket-office-service/node_modules/mongodb/lib/mongos.js create mode 100644 ts-ticket-office-service/node_modules/mongodb/lib/operations/add_user.js create mode 100644 ts-ticket-office-service/node_modules/mongodb/lib/operations/add_user.js.map create mode 100644 ts-ticket-office-service/node_modules/mongodb/lib/operations/aggregate.js create mode 100644 ts-ticket-office-service/node_modules/mongodb/lib/operations/aggregate.js.map create mode 100644 ts-ticket-office-service/node_modules/mongodb/lib/operations/bulk_write.js create mode 100644 ts-ticket-office-service/node_modules/mongodb/lib/operations/bulk_write.js.map create mode 100644 ts-ticket-office-service/node_modules/mongodb/lib/operations/collections.js create mode 100644 ts-ticket-office-service/node_modules/mongodb/lib/operations/collections.js.map create mode 100644 ts-ticket-office-service/node_modules/mongodb/lib/operations/command.js create mode 100644 ts-ticket-office-service/node_modules/mongodb/lib/operations/command.js.map create mode 100644 ts-ticket-office-service/node_modules/mongodb/lib/operations/common_functions.js create mode 100644 ts-ticket-office-service/node_modules/mongodb/lib/operations/common_functions.js.map create mode 100644 ts-ticket-office-service/node_modules/mongodb/lib/operations/connect.js create mode 100644 ts-ticket-office-service/node_modules/mongodb/lib/operations/connect.js.map create mode 100644 ts-ticket-office-service/node_modules/mongodb/lib/operations/count.js create mode 100644 ts-ticket-office-service/node_modules/mongodb/lib/operations/count.js.map create mode 100644 ts-ticket-office-service/node_modules/mongodb/lib/operations/count_documents.js create mode 100644 ts-ticket-office-service/node_modules/mongodb/lib/operations/count_documents.js.map create mode 100644 ts-ticket-office-service/node_modules/mongodb/lib/operations/create_collection.js create mode 100644 ts-ticket-office-service/node_modules/mongodb/lib/operations/create_collection.js.map create mode 100644 ts-ticket-office-service/node_modules/mongodb/lib/operations/delete.js create mode 100644 ts-ticket-office-service/node_modules/mongodb/lib/operations/delete.js.map create mode 100644 ts-ticket-office-service/node_modules/mongodb/lib/operations/distinct.js create mode 100644 ts-ticket-office-service/node_modules/mongodb/lib/operations/distinct.js.map create mode 100644 ts-ticket-office-service/node_modules/mongodb/lib/operations/drop.js create mode 100644 ts-ticket-office-service/node_modules/mongodb/lib/operations/drop.js.map create mode 100644 ts-ticket-office-service/node_modules/mongodb/lib/operations/estimated_document_count.js create mode 100644 ts-ticket-office-service/node_modules/mongodb/lib/operations/estimated_document_count.js.map create mode 100644 ts-ticket-office-service/node_modules/mongodb/lib/operations/eval.js create mode 100644 ts-ticket-office-service/node_modules/mongodb/lib/operations/eval.js.map create mode 100644 ts-ticket-office-service/node_modules/mongodb/lib/operations/execute_operation.js create mode 100644 ts-ticket-office-service/node_modules/mongodb/lib/operations/execute_operation.js.map create mode 100644 ts-ticket-office-service/node_modules/mongodb/lib/operations/find.js create mode 100644 ts-ticket-office-service/node_modules/mongodb/lib/operations/find.js.map create mode 100644 ts-ticket-office-service/node_modules/mongodb/lib/operations/find_and_modify.js create mode 100644 ts-ticket-office-service/node_modules/mongodb/lib/operations/find_and_modify.js.map create mode 100644 ts-ticket-office-service/node_modules/mongodb/lib/operations/get_more.js create mode 100644 ts-ticket-office-service/node_modules/mongodb/lib/operations/get_more.js.map create mode 100644 ts-ticket-office-service/node_modules/mongodb/lib/operations/indexes.js create mode 100644 ts-ticket-office-service/node_modules/mongodb/lib/operations/indexes.js.map create mode 100644 ts-ticket-office-service/node_modules/mongodb/lib/operations/insert.js create mode 100644 ts-ticket-office-service/node_modules/mongodb/lib/operations/insert.js.map create mode 100644 ts-ticket-office-service/node_modules/mongodb/lib/operations/is_capped.js create mode 100644 ts-ticket-office-service/node_modules/mongodb/lib/operations/is_capped.js.map create mode 100644 ts-ticket-office-service/node_modules/mongodb/lib/operations/kill_cursors.js create mode 100644 ts-ticket-office-service/node_modules/mongodb/lib/operations/kill_cursors.js.map create mode 100644 ts-ticket-office-service/node_modules/mongodb/lib/operations/list_collections.js create mode 100644 ts-ticket-office-service/node_modules/mongodb/lib/operations/list_collections.js.map create mode 100644 ts-ticket-office-service/node_modules/mongodb/lib/operations/list_databases.js create mode 100644 ts-ticket-office-service/node_modules/mongodb/lib/operations/list_databases.js.map create mode 100644 ts-ticket-office-service/node_modules/mongodb/lib/operations/map_reduce.js create mode 100644 ts-ticket-office-service/node_modules/mongodb/lib/operations/map_reduce.js.map create mode 100644 ts-ticket-office-service/node_modules/mongodb/lib/operations/operation.js create mode 100644 ts-ticket-office-service/node_modules/mongodb/lib/operations/operation.js.map create mode 100644 ts-ticket-office-service/node_modules/mongodb/lib/operations/options_operation.js create mode 100644 ts-ticket-office-service/node_modules/mongodb/lib/operations/options_operation.js.map create mode 100644 ts-ticket-office-service/node_modules/mongodb/lib/operations/profiling_level.js create mode 100644 ts-ticket-office-service/node_modules/mongodb/lib/operations/profiling_level.js.map create mode 100644 ts-ticket-office-service/node_modules/mongodb/lib/operations/remove_user.js create mode 100644 ts-ticket-office-service/node_modules/mongodb/lib/operations/remove_user.js.map create mode 100644 ts-ticket-office-service/node_modules/mongodb/lib/operations/rename.js create mode 100644 ts-ticket-office-service/node_modules/mongodb/lib/operations/rename.js.map create mode 100644 ts-ticket-office-service/node_modules/mongodb/lib/operations/run_command.js create mode 100644 ts-ticket-office-service/node_modules/mongodb/lib/operations/run_command.js.map create mode 100644 ts-ticket-office-service/node_modules/mongodb/lib/operations/set_profiling_level.js create mode 100644 ts-ticket-office-service/node_modules/mongodb/lib/operations/set_profiling_level.js.map create mode 100644 ts-ticket-office-service/node_modules/mongodb/lib/operations/stats.js create mode 100644 ts-ticket-office-service/node_modules/mongodb/lib/operations/stats.js.map create mode 100644 ts-ticket-office-service/node_modules/mongodb/lib/operations/update.js create mode 100644 ts-ticket-office-service/node_modules/mongodb/lib/operations/update.js.map create mode 100644 ts-ticket-office-service/node_modules/mongodb/lib/operations/validate_collection.js create mode 100644 ts-ticket-office-service/node_modules/mongodb/lib/operations/validate_collection.js.map create mode 100644 ts-ticket-office-service/node_modules/mongodb/lib/promise_provider.js create mode 100644 ts-ticket-office-service/node_modules/mongodb/lib/promise_provider.js.map create mode 100644 ts-ticket-office-service/node_modules/mongodb/lib/read_concern.js create mode 100644 ts-ticket-office-service/node_modules/mongodb/lib/read_concern.js.map create mode 100644 ts-ticket-office-service/node_modules/mongodb/lib/read_preference.js.map delete mode 100644 ts-ticket-office-service/node_modules/mongodb/lib/replset.js create mode 100644 ts-ticket-office-service/node_modules/mongodb/lib/sdam/common.js create mode 100644 ts-ticket-office-service/node_modules/mongodb/lib/sdam/common.js.map create mode 100644 ts-ticket-office-service/node_modules/mongodb/lib/sdam/events.js create mode 100644 ts-ticket-office-service/node_modules/mongodb/lib/sdam/events.js.map create mode 100644 ts-ticket-office-service/node_modules/mongodb/lib/sdam/monitor.js create mode 100644 ts-ticket-office-service/node_modules/mongodb/lib/sdam/monitor.js.map create mode 100644 ts-ticket-office-service/node_modules/mongodb/lib/sdam/server.js create mode 100644 ts-ticket-office-service/node_modules/mongodb/lib/sdam/server.js.map create mode 100644 ts-ticket-office-service/node_modules/mongodb/lib/sdam/server_description.js create mode 100644 ts-ticket-office-service/node_modules/mongodb/lib/sdam/server_description.js.map create mode 100644 ts-ticket-office-service/node_modules/mongodb/lib/sdam/server_selection.js create mode 100644 ts-ticket-office-service/node_modules/mongodb/lib/sdam/server_selection.js.map create mode 100644 ts-ticket-office-service/node_modules/mongodb/lib/sdam/srv_polling.js create mode 100644 ts-ticket-office-service/node_modules/mongodb/lib/sdam/srv_polling.js.map create mode 100644 ts-ticket-office-service/node_modules/mongodb/lib/sdam/topology.js create mode 100644 ts-ticket-office-service/node_modules/mongodb/lib/sdam/topology.js.map create mode 100644 ts-ticket-office-service/node_modules/mongodb/lib/sdam/topology_description.js create mode 100644 ts-ticket-office-service/node_modules/mongodb/lib/sdam/topology_description.js.map delete mode 100644 ts-ticket-office-service/node_modules/mongodb/lib/server.js create mode 100644 ts-ticket-office-service/node_modules/mongodb/lib/sessions.js create mode 100644 ts-ticket-office-service/node_modules/mongodb/lib/sessions.js.map create mode 100644 ts-ticket-office-service/node_modules/mongodb/lib/sort.js create mode 100644 ts-ticket-office-service/node_modules/mongodb/lib/sort.js.map delete mode 100644 ts-ticket-office-service/node_modules/mongodb/lib/topology_base.js create mode 100644 ts-ticket-office-service/node_modules/mongodb/lib/transactions.js create mode 100644 ts-ticket-office-service/node_modules/mongodb/lib/transactions.js.map delete mode 100644 ts-ticket-office-service/node_modules/mongodb/lib/url_parser.js create mode 100644 ts-ticket-office-service/node_modules/mongodb/lib/utils.js.map create mode 100644 ts-ticket-office-service/node_modules/mongodb/lib/write_concern.js create mode 100644 ts-ticket-office-service/node_modules/mongodb/lib/write_concern.js.map create mode 100644 ts-ticket-office-service/node_modules/mongodb/mongodb.d.ts create mode 100644 ts-ticket-office-service/node_modules/mongodb/src/admin.ts create mode 100644 ts-ticket-office-service/node_modules/mongodb/src/bson.ts create mode 100644 ts-ticket-office-service/node_modules/mongodb/src/bulk/common.ts create mode 100644 ts-ticket-office-service/node_modules/mongodb/src/bulk/ordered.ts create mode 100644 ts-ticket-office-service/node_modules/mongodb/src/bulk/unordered.ts create mode 100644 ts-ticket-office-service/node_modules/mongodb/src/change_stream.ts create mode 100644 ts-ticket-office-service/node_modules/mongodb/src/cmap/auth/auth_provider.ts create mode 100644 ts-ticket-office-service/node_modules/mongodb/src/cmap/auth/gssapi.ts create mode 100644 ts-ticket-office-service/node_modules/mongodb/src/cmap/auth/mongo_credentials.ts create mode 100644 ts-ticket-office-service/node_modules/mongodb/src/cmap/auth/mongocr.ts create mode 100644 ts-ticket-office-service/node_modules/mongodb/src/cmap/auth/mongodb_aws.ts create mode 100644 ts-ticket-office-service/node_modules/mongodb/src/cmap/auth/plain.ts create mode 100644 ts-ticket-office-service/node_modules/mongodb/src/cmap/auth/providers.ts create mode 100644 ts-ticket-office-service/node_modules/mongodb/src/cmap/auth/scram.ts create mode 100644 ts-ticket-office-service/node_modules/mongodb/src/cmap/auth/x509.ts create mode 100644 ts-ticket-office-service/node_modules/mongodb/src/cmap/command_monitoring_events.ts create mode 100644 ts-ticket-office-service/node_modules/mongodb/src/cmap/commands.ts create mode 100644 ts-ticket-office-service/node_modules/mongodb/src/cmap/connect.ts create mode 100644 ts-ticket-office-service/node_modules/mongodb/src/cmap/connection.ts create mode 100644 ts-ticket-office-service/node_modules/mongodb/src/cmap/connection_pool.ts create mode 100644 ts-ticket-office-service/node_modules/mongodb/src/cmap/connection_pool_events.ts create mode 100644 ts-ticket-office-service/node_modules/mongodb/src/cmap/errors.ts create mode 100644 ts-ticket-office-service/node_modules/mongodb/src/cmap/message_stream.ts create mode 100644 ts-ticket-office-service/node_modules/mongodb/src/cmap/metrics.ts create mode 100644 ts-ticket-office-service/node_modules/mongodb/src/cmap/stream_description.ts create mode 100644 ts-ticket-office-service/node_modules/mongodb/src/cmap/wire_protocol/compression.ts create mode 100644 ts-ticket-office-service/node_modules/mongodb/src/cmap/wire_protocol/constants.ts create mode 100644 ts-ticket-office-service/node_modules/mongodb/src/cmap/wire_protocol/shared.ts create mode 100644 ts-ticket-office-service/node_modules/mongodb/src/collection.ts create mode 100644 ts-ticket-office-service/node_modules/mongodb/src/connection_string.ts create mode 100644 ts-ticket-office-service/node_modules/mongodb/src/constants.ts create mode 100644 ts-ticket-office-service/node_modules/mongodb/src/cursor/abstract_cursor.ts create mode 100644 ts-ticket-office-service/node_modules/mongodb/src/cursor/aggregation_cursor.ts create mode 100644 ts-ticket-office-service/node_modules/mongodb/src/cursor/change_stream_cursor.ts create mode 100644 ts-ticket-office-service/node_modules/mongodb/src/cursor/find_cursor.ts create mode 100644 ts-ticket-office-service/node_modules/mongodb/src/cursor/list_collections_cursor.ts create mode 100644 ts-ticket-office-service/node_modules/mongodb/src/cursor/list_indexes_cursor.ts create mode 100644 ts-ticket-office-service/node_modules/mongodb/src/db.ts create mode 100644 ts-ticket-office-service/node_modules/mongodb/src/deps.ts create mode 100644 ts-ticket-office-service/node_modules/mongodb/src/encrypter.ts create mode 100644 ts-ticket-office-service/node_modules/mongodb/src/error.ts create mode 100644 ts-ticket-office-service/node_modules/mongodb/src/explain.ts create mode 100644 ts-ticket-office-service/node_modules/mongodb/src/gridfs/download.ts create mode 100644 ts-ticket-office-service/node_modules/mongodb/src/gridfs/index.ts create mode 100644 ts-ticket-office-service/node_modules/mongodb/src/gridfs/upload.ts create mode 100644 ts-ticket-office-service/node_modules/mongodb/src/index.ts create mode 100644 ts-ticket-office-service/node_modules/mongodb/src/logger.ts create mode 100644 ts-ticket-office-service/node_modules/mongodb/src/mongo_client.ts create mode 100644 ts-ticket-office-service/node_modules/mongodb/src/mongo_types.ts create mode 100644 ts-ticket-office-service/node_modules/mongodb/src/operations/add_user.ts create mode 100644 ts-ticket-office-service/node_modules/mongodb/src/operations/aggregate.ts create mode 100644 ts-ticket-office-service/node_modules/mongodb/src/operations/bulk_write.ts create mode 100644 ts-ticket-office-service/node_modules/mongodb/src/operations/collections.ts create mode 100644 ts-ticket-office-service/node_modules/mongodb/src/operations/command.ts create mode 100644 ts-ticket-office-service/node_modules/mongodb/src/operations/common_functions.ts create mode 100644 ts-ticket-office-service/node_modules/mongodb/src/operations/connect.ts create mode 100644 ts-ticket-office-service/node_modules/mongodb/src/operations/count.ts create mode 100644 ts-ticket-office-service/node_modules/mongodb/src/operations/count_documents.ts create mode 100644 ts-ticket-office-service/node_modules/mongodb/src/operations/create_collection.ts create mode 100644 ts-ticket-office-service/node_modules/mongodb/src/operations/delete.ts create mode 100644 ts-ticket-office-service/node_modules/mongodb/src/operations/distinct.ts create mode 100644 ts-ticket-office-service/node_modules/mongodb/src/operations/drop.ts create mode 100644 ts-ticket-office-service/node_modules/mongodb/src/operations/estimated_document_count.ts create mode 100644 ts-ticket-office-service/node_modules/mongodb/src/operations/eval.ts create mode 100644 ts-ticket-office-service/node_modules/mongodb/src/operations/execute_operation.ts create mode 100644 ts-ticket-office-service/node_modules/mongodb/src/operations/find.ts create mode 100644 ts-ticket-office-service/node_modules/mongodb/src/operations/find_and_modify.ts create mode 100644 ts-ticket-office-service/node_modules/mongodb/src/operations/get_more.ts create mode 100644 ts-ticket-office-service/node_modules/mongodb/src/operations/indexes.ts create mode 100644 ts-ticket-office-service/node_modules/mongodb/src/operations/insert.ts create mode 100644 ts-ticket-office-service/node_modules/mongodb/src/operations/is_capped.ts create mode 100644 ts-ticket-office-service/node_modules/mongodb/src/operations/kill_cursors.ts create mode 100644 ts-ticket-office-service/node_modules/mongodb/src/operations/list_collections.ts create mode 100644 ts-ticket-office-service/node_modules/mongodb/src/operations/list_databases.ts create mode 100644 ts-ticket-office-service/node_modules/mongodb/src/operations/map_reduce.ts create mode 100644 ts-ticket-office-service/node_modules/mongodb/src/operations/operation.ts create mode 100644 ts-ticket-office-service/node_modules/mongodb/src/operations/options_operation.ts create mode 100644 ts-ticket-office-service/node_modules/mongodb/src/operations/profiling_level.ts create mode 100644 ts-ticket-office-service/node_modules/mongodb/src/operations/remove_user.ts create mode 100644 ts-ticket-office-service/node_modules/mongodb/src/operations/rename.ts create mode 100644 ts-ticket-office-service/node_modules/mongodb/src/operations/run_command.ts create mode 100644 ts-ticket-office-service/node_modules/mongodb/src/operations/set_profiling_level.ts create mode 100644 ts-ticket-office-service/node_modules/mongodb/src/operations/stats.ts create mode 100644 ts-ticket-office-service/node_modules/mongodb/src/operations/update.ts create mode 100644 ts-ticket-office-service/node_modules/mongodb/src/operations/validate_collection.ts create mode 100644 ts-ticket-office-service/node_modules/mongodb/src/promise_provider.ts create mode 100644 ts-ticket-office-service/node_modules/mongodb/src/read_concern.ts create mode 100644 ts-ticket-office-service/node_modules/mongodb/src/read_preference.ts create mode 100644 ts-ticket-office-service/node_modules/mongodb/src/sdam/common.ts create mode 100644 ts-ticket-office-service/node_modules/mongodb/src/sdam/events.ts create mode 100644 ts-ticket-office-service/node_modules/mongodb/src/sdam/monitor.ts create mode 100644 ts-ticket-office-service/node_modules/mongodb/src/sdam/server.ts create mode 100644 ts-ticket-office-service/node_modules/mongodb/src/sdam/server_description.ts create mode 100644 ts-ticket-office-service/node_modules/mongodb/src/sdam/server_selection.ts create mode 100644 ts-ticket-office-service/node_modules/mongodb/src/sdam/srv_polling.ts create mode 100644 ts-ticket-office-service/node_modules/mongodb/src/sdam/topology.ts create mode 100644 ts-ticket-office-service/node_modules/mongodb/src/sdam/topology_description.ts create mode 100644 ts-ticket-office-service/node_modules/mongodb/src/sessions.ts create mode 100644 ts-ticket-office-service/node_modules/mongodb/src/sort.ts create mode 100644 ts-ticket-office-service/node_modules/mongodb/src/transactions.ts create mode 100644 ts-ticket-office-service/node_modules/mongodb/src/utils.ts create mode 100644 ts-ticket-office-service/node_modules/mongodb/src/write_concern.ts create mode 100644 ts-ticket-office-service/node_modules/mongodb/tsconfig.json delete mode 100644 ts-ticket-office-service/node_modules/mongodb/yarn.lock create mode 100644 ts-ticket-office-service/node_modules/morgan/node_modules/depd/History.md create mode 100644 ts-ticket-office-service/node_modules/morgan/node_modules/depd/LICENSE create mode 100644 ts-ticket-office-service/node_modules/morgan/node_modules/depd/Readme.md create mode 100644 ts-ticket-office-service/node_modules/morgan/node_modules/depd/index.js create mode 100644 ts-ticket-office-service/node_modules/morgan/node_modules/depd/lib/browser/index.js create mode 100644 ts-ticket-office-service/node_modules/morgan/node_modules/depd/lib/compat/callsite-tostring.js create mode 100644 ts-ticket-office-service/node_modules/morgan/node_modules/depd/lib/compat/event-listener-count.js create mode 100644 ts-ticket-office-service/node_modules/morgan/node_modules/depd/lib/compat/index.js create mode 100644 ts-ticket-office-service/node_modules/morgan/node_modules/depd/package.json create mode 100644 ts-ticket-office-service/node_modules/mysql/Changes.md create mode 100644 ts-ticket-office-service/node_modules/mysql/License create mode 100644 ts-ticket-office-service/node_modules/mysql/Readme.md create mode 100644 ts-ticket-office-service/node_modules/mysql/index.js create mode 100644 ts-ticket-office-service/node_modules/mysql/lib/Connection.js create mode 100644 ts-ticket-office-service/node_modules/mysql/lib/ConnectionConfig.js create mode 100644 ts-ticket-office-service/node_modules/mysql/lib/Pool.js create mode 100644 ts-ticket-office-service/node_modules/mysql/lib/PoolCluster.js create mode 100644 ts-ticket-office-service/node_modules/mysql/lib/PoolConfig.js create mode 100644 ts-ticket-office-service/node_modules/mysql/lib/PoolConnection.js create mode 100644 ts-ticket-office-service/node_modules/mysql/lib/PoolNamespace.js create mode 100644 ts-ticket-office-service/node_modules/mysql/lib/PoolSelector.js create mode 100644 ts-ticket-office-service/node_modules/mysql/lib/protocol/Auth.js create mode 100644 ts-ticket-office-service/node_modules/mysql/lib/protocol/BufferList.js create mode 100644 ts-ticket-office-service/node_modules/mysql/lib/protocol/PacketHeader.js create mode 100644 ts-ticket-office-service/node_modules/mysql/lib/protocol/PacketWriter.js create mode 100644 ts-ticket-office-service/node_modules/mysql/lib/protocol/Parser.js create mode 100644 ts-ticket-office-service/node_modules/mysql/lib/protocol/Protocol.js create mode 100644 ts-ticket-office-service/node_modules/mysql/lib/protocol/ResultSet.js create mode 100644 ts-ticket-office-service/node_modules/mysql/lib/protocol/SqlString.js create mode 100644 ts-ticket-office-service/node_modules/mysql/lib/protocol/Timer.js create mode 100644 ts-ticket-office-service/node_modules/mysql/lib/protocol/constants/charsets.js create mode 100644 ts-ticket-office-service/node_modules/mysql/lib/protocol/constants/client.js create mode 100644 ts-ticket-office-service/node_modules/mysql/lib/protocol/constants/errors.js create mode 100644 ts-ticket-office-service/node_modules/mysql/lib/protocol/constants/field_flags.js create mode 100644 ts-ticket-office-service/node_modules/mysql/lib/protocol/constants/server_status.js create mode 100644 ts-ticket-office-service/node_modules/mysql/lib/protocol/constants/ssl_profiles.js create mode 100644 ts-ticket-office-service/node_modules/mysql/lib/protocol/constants/types.js create mode 100644 ts-ticket-office-service/node_modules/mysql/lib/protocol/packets/AuthSwitchRequestPacket.js create mode 100644 ts-ticket-office-service/node_modules/mysql/lib/protocol/packets/AuthSwitchResponsePacket.js create mode 100644 ts-ticket-office-service/node_modules/mysql/lib/protocol/packets/ClientAuthenticationPacket.js create mode 100644 ts-ticket-office-service/node_modules/mysql/lib/protocol/packets/ComChangeUserPacket.js create mode 100644 ts-ticket-office-service/node_modules/mysql/lib/protocol/packets/ComPingPacket.js create mode 100644 ts-ticket-office-service/node_modules/mysql/lib/protocol/packets/ComQueryPacket.js create mode 100644 ts-ticket-office-service/node_modules/mysql/lib/protocol/packets/ComQuitPacket.js create mode 100644 ts-ticket-office-service/node_modules/mysql/lib/protocol/packets/ComStatisticsPacket.js create mode 100644 ts-ticket-office-service/node_modules/mysql/lib/protocol/packets/EmptyPacket.js create mode 100644 ts-ticket-office-service/node_modules/mysql/lib/protocol/packets/EofPacket.js create mode 100644 ts-ticket-office-service/node_modules/mysql/lib/protocol/packets/ErrorPacket.js create mode 100644 ts-ticket-office-service/node_modules/mysql/lib/protocol/packets/Field.js create mode 100644 ts-ticket-office-service/node_modules/mysql/lib/protocol/packets/FieldPacket.js create mode 100644 ts-ticket-office-service/node_modules/mysql/lib/protocol/packets/HandshakeInitializationPacket.js create mode 100644 ts-ticket-office-service/node_modules/mysql/lib/protocol/packets/LocalDataFilePacket.js create mode 100644 ts-ticket-office-service/node_modules/mysql/lib/protocol/packets/LocalInfileRequestPacket.js create mode 100644 ts-ticket-office-service/node_modules/mysql/lib/protocol/packets/OkPacket.js create mode 100644 ts-ticket-office-service/node_modules/mysql/lib/protocol/packets/OldPasswordPacket.js create mode 100644 ts-ticket-office-service/node_modules/mysql/lib/protocol/packets/ResultSetHeaderPacket.js create mode 100644 ts-ticket-office-service/node_modules/mysql/lib/protocol/packets/RowDataPacket.js create mode 100644 ts-ticket-office-service/node_modules/mysql/lib/protocol/packets/SSLRequestPacket.js create mode 100644 ts-ticket-office-service/node_modules/mysql/lib/protocol/packets/StatisticsPacket.js create mode 100644 ts-ticket-office-service/node_modules/mysql/lib/protocol/packets/UseOldPasswordPacket.js create mode 100644 ts-ticket-office-service/node_modules/mysql/lib/protocol/packets/index.js create mode 100644 ts-ticket-office-service/node_modules/mysql/lib/protocol/sequences/ChangeUser.js create mode 100644 ts-ticket-office-service/node_modules/mysql/lib/protocol/sequences/Handshake.js create mode 100644 ts-ticket-office-service/node_modules/mysql/lib/protocol/sequences/Ping.js create mode 100644 ts-ticket-office-service/node_modules/mysql/lib/protocol/sequences/Query.js create mode 100644 ts-ticket-office-service/node_modules/mysql/lib/protocol/sequences/Quit.js create mode 100644 ts-ticket-office-service/node_modules/mysql/lib/protocol/sequences/Sequence.js create mode 100644 ts-ticket-office-service/node_modules/mysql/lib/protocol/sequences/Statistics.js create mode 100644 ts-ticket-office-service/node_modules/mysql/lib/protocol/sequences/index.js rename ts-ticket-office-service/node_modules/{ => mysql/node_modules}/process-nextick-args/index.js (87%) rename ts-ticket-office-service/node_modules/{ => mysql/node_modules}/process-nextick-args/license.md (100%) create mode 100644 ts-ticket-office-service/node_modules/mysql/node_modules/process-nextick-args/package.json rename ts-ticket-office-service/node_modules/{ => mysql/node_modules}/process-nextick-args/readme.md (82%) rename ts-ticket-office-service/node_modules/{ => mysql/node_modules}/readable-stream/CONTRIBUTING.md (100%) rename ts-ticket-office-service/node_modules/{ => mysql/node_modules}/readable-stream/GOVERNANCE.md (100%) rename ts-ticket-office-service/node_modules/{ => mysql/node_modules}/readable-stream/LICENSE (100%) rename ts-ticket-office-service/node_modules/{ => mysql/node_modules}/readable-stream/README.md (89%) rename ts-ticket-office-service/node_modules/{ => mysql/node_modules}/readable-stream/doc/wg-meetings/2015-01-30.md (100%) rename ts-ticket-office-service/node_modules/{ => mysql/node_modules}/readable-stream/duplex-browser.js (100%) rename ts-ticket-office-service/node_modules/{ => mysql/node_modules}/readable-stream/duplex.js (100%) create mode 100644 ts-ticket-office-service/node_modules/mysql/node_modules/readable-stream/lib/_stream_duplex.js create mode 100644 ts-ticket-office-service/node_modules/mysql/node_modules/readable-stream/lib/_stream_passthrough.js rename ts-ticket-office-service/node_modules/{ => mysql/node_modules}/readable-stream/lib/_stream_readable.js (75%) rename ts-ticket-office-service/node_modules/{ => mysql/node_modules}/readable-stream/lib/_stream_transform.js (68%) rename ts-ticket-office-service/node_modules/{ => mysql/node_modules}/readable-stream/lib/_stream_writable.js (70%) create mode 100644 ts-ticket-office-service/node_modules/mysql/node_modules/readable-stream/lib/internal/streams/BufferList.js create mode 100644 ts-ticket-office-service/node_modules/mysql/node_modules/readable-stream/lib/internal/streams/destroy.js create mode 100644 ts-ticket-office-service/node_modules/mysql/node_modules/readable-stream/lib/internal/streams/stream-browser.js create mode 100644 ts-ticket-office-service/node_modules/mysql/node_modules/readable-stream/lib/internal/streams/stream.js create mode 100644 ts-ticket-office-service/node_modules/mysql/node_modules/readable-stream/package.json rename ts-ticket-office-service/node_modules/{ => mysql/node_modules}/readable-stream/passthrough.js (100%) rename ts-ticket-office-service/node_modules/{ => mysql/node_modules}/readable-stream/readable-browser.js (100%) rename ts-ticket-office-service/node_modules/{ => mysql/node_modules}/readable-stream/readable.js (100%) rename ts-ticket-office-service/node_modules/{ => mysql/node_modules}/readable-stream/transform.js (100%) rename ts-ticket-office-service/node_modules/{ => mysql/node_modules}/readable-stream/writable-browser.js (100%) rename ts-ticket-office-service/node_modules/{ => mysql/node_modules}/readable-stream/writable.js (83%) create mode 100644 ts-ticket-office-service/node_modules/mysql/node_modules/safe-buffer/LICENSE create mode 100644 ts-ticket-office-service/node_modules/mysql/node_modules/safe-buffer/README.md create mode 100644 ts-ticket-office-service/node_modules/mysql/node_modules/safe-buffer/index.d.ts create mode 100644 ts-ticket-office-service/node_modules/mysql/node_modules/safe-buffer/index.js create mode 100644 ts-ticket-office-service/node_modules/mysql/node_modules/safe-buffer/package.json rename ts-ticket-office-service/node_modules/{ => mysql/node_modules}/string_decoder/LICENSE (100%) create mode 100644 ts-ticket-office-service/node_modules/mysql/node_modules/string_decoder/README.md rename ts-ticket-office-service/node_modules/{ => mysql/node_modules}/string_decoder/lib/string_decoder.js (82%) create mode 100644 ts-ticket-office-service/node_modules/mysql/node_modules/string_decoder/package.json create mode 100644 ts-ticket-office-service/node_modules/mysql/package.json delete mode 100644 ts-ticket-office-service/node_modules/process-nextick-args/.travis.yml delete mode 100644 ts-ticket-office-service/node_modules/process-nextick-args/package.json delete mode 100644 ts-ticket-office-service/node_modules/process-nextick-args/test.js create mode 100644 ts-ticket-office-service/node_modules/punycode/LICENSE-MIT.txt create mode 100644 ts-ticket-office-service/node_modules/punycode/README.md create mode 100644 ts-ticket-office-service/node_modules/punycode/package.json create mode 100644 ts-ticket-office-service/node_modules/punycode/punycode.es6.js create mode 100644 ts-ticket-office-service/node_modules/punycode/punycode.js delete mode 100644 ts-ticket-office-service/node_modules/readable-stream/.npmignore delete mode 100644 ts-ticket-office-service/node_modules/readable-stream/.travis.yml delete mode 100644 ts-ticket-office-service/node_modules/readable-stream/lib/_stream_duplex.js delete mode 100644 ts-ticket-office-service/node_modules/readable-stream/lib/_stream_passthrough.js delete mode 100644 ts-ticket-office-service/node_modules/readable-stream/lib/internal/streams/BufferList.js delete mode 100644 ts-ticket-office-service/node_modules/readable-stream/package.json delete mode 100644 ts-ticket-office-service/node_modules/require_optional/.npmignore delete mode 100644 ts-ticket-office-service/node_modules/require_optional/.travis.yml delete mode 100644 ts-ticket-office-service/node_modules/require_optional/HISTORY.md delete mode 100644 ts-ticket-office-service/node_modules/require_optional/README.md delete mode 100644 ts-ticket-office-service/node_modules/require_optional/index.js delete mode 100644 ts-ticket-office-service/node_modules/require_optional/package.json delete mode 100644 ts-ticket-office-service/node_modules/require_optional/test/nestedTest/index.js delete mode 100644 ts-ticket-office-service/node_modules/require_optional/test/nestedTest/package.json delete mode 100644 ts-ticket-office-service/node_modules/require_optional/test/require_optional_tests.js delete mode 100644 ts-ticket-office-service/node_modules/resolve-from/index.js delete mode 100644 ts-ticket-office-service/node_modules/resolve-from/package.json delete mode 100644 ts-ticket-office-service/node_modules/resolve-from/readme.md create mode 100644 ts-ticket-office-service/node_modules/saslprep/.editorconfig create mode 100644 ts-ticket-office-service/node_modules/saslprep/.gitattributes create mode 100644 ts-ticket-office-service/node_modules/saslprep/CHANGELOG.md create mode 100644 ts-ticket-office-service/node_modules/saslprep/LICENSE create mode 100644 ts-ticket-office-service/node_modules/saslprep/code-points.mem create mode 100644 ts-ticket-office-service/node_modules/saslprep/generate-code-points.js create mode 100644 ts-ticket-office-service/node_modules/saslprep/index.js create mode 100644 ts-ticket-office-service/node_modules/saslprep/lib/code-points.js create mode 100644 ts-ticket-office-service/node_modules/saslprep/lib/memory-code-points.js create mode 100644 ts-ticket-office-service/node_modules/saslprep/lib/util.js create mode 100644 ts-ticket-office-service/node_modules/saslprep/package.json create mode 100644 ts-ticket-office-service/node_modules/saslprep/readme.md create mode 100644 ts-ticket-office-service/node_modules/saslprep/test/index.js create mode 100644 ts-ticket-office-service/node_modules/saslprep/test/util.js delete mode 100644 ts-ticket-office-service/node_modules/semver/LICENSE delete mode 100644 ts-ticket-office-service/node_modules/semver/README.md delete mode 100644 ts-ticket-office-service/node_modules/semver/bin/semver delete mode 100644 ts-ticket-office-service/node_modules/semver/package.json delete mode 100644 ts-ticket-office-service/node_modules/semver/range.bnf delete mode 100644 ts-ticket-office-service/node_modules/semver/semver.js create mode 100644 ts-ticket-office-service/node_modules/smart-buffer/LICENSE create mode 100644 ts-ticket-office-service/node_modules/smart-buffer/README.md create mode 100644 ts-ticket-office-service/node_modules/smart-buffer/build/smartbuffer.js create mode 100644 ts-ticket-office-service/node_modules/smart-buffer/build/smartbuffer.js.map create mode 100644 ts-ticket-office-service/node_modules/smart-buffer/build/utils.js create mode 100644 ts-ticket-office-service/node_modules/smart-buffer/build/utils.js.map create mode 100644 ts-ticket-office-service/node_modules/smart-buffer/docs/CHANGELOG.md create mode 100644 ts-ticket-office-service/node_modules/smart-buffer/docs/README_v3.md create mode 100644 ts-ticket-office-service/node_modules/smart-buffer/docs/ROADMAP.md create mode 100644 ts-ticket-office-service/node_modules/smart-buffer/package.json create mode 100644 ts-ticket-office-service/node_modules/socks/.eslintrc.cjs create mode 100644 ts-ticket-office-service/node_modules/socks/LICENSE create mode 100644 ts-ticket-office-service/node_modules/socks/README.md create mode 100644 ts-ticket-office-service/node_modules/socks/build/client/socksclient.js create mode 100644 ts-ticket-office-service/node_modules/socks/build/client/socksclient.js.map create mode 100644 ts-ticket-office-service/node_modules/socks/build/common/constants.js create mode 100644 ts-ticket-office-service/node_modules/socks/build/common/constants.js.map create mode 100644 ts-ticket-office-service/node_modules/socks/build/common/helpers.js create mode 100644 ts-ticket-office-service/node_modules/socks/build/common/helpers.js.map create mode 100644 ts-ticket-office-service/node_modules/socks/build/common/receivebuffer.js create mode 100644 ts-ticket-office-service/node_modules/socks/build/common/receivebuffer.js.map create mode 100644 ts-ticket-office-service/node_modules/socks/build/common/util.js create mode 100644 ts-ticket-office-service/node_modules/socks/build/common/util.js.map create mode 100644 ts-ticket-office-service/node_modules/socks/build/index.js create mode 100644 ts-ticket-office-service/node_modules/socks/build/index.js.map create mode 100644 ts-ticket-office-service/node_modules/socks/docs/examples/index.md create mode 100644 ts-ticket-office-service/node_modules/socks/docs/examples/javascript/associateExample.md create mode 100644 ts-ticket-office-service/node_modules/socks/docs/examples/javascript/bindExample.md create mode 100644 ts-ticket-office-service/node_modules/socks/docs/examples/javascript/connectExample.md create mode 100644 ts-ticket-office-service/node_modules/socks/docs/examples/typescript/associateExample.md create mode 100644 ts-ticket-office-service/node_modules/socks/docs/examples/typescript/bindExample.md create mode 100644 ts-ticket-office-service/node_modules/socks/docs/examples/typescript/connectExample.md create mode 100644 ts-ticket-office-service/node_modules/socks/docs/index.md create mode 100644 ts-ticket-office-service/node_modules/socks/docs/migratingFromV1.md create mode 100644 ts-ticket-office-service/node_modules/socks/package.json create mode 100644 ts-ticket-office-service/node_modules/sparse-bitfield/.npmignore create mode 100644 ts-ticket-office-service/node_modules/sparse-bitfield/LICENSE create mode 100644 ts-ticket-office-service/node_modules/sparse-bitfield/README.md create mode 100644 ts-ticket-office-service/node_modules/sparse-bitfield/index.js create mode 100644 ts-ticket-office-service/node_modules/sparse-bitfield/package.json create mode 100644 ts-ticket-office-service/node_modules/sparse-bitfield/test.js create mode 100644 ts-ticket-office-service/node_modules/sqlstring/HISTORY.md create mode 100644 ts-ticket-office-service/node_modules/sqlstring/LICENSE create mode 100644 ts-ticket-office-service/node_modules/sqlstring/README.md create mode 100644 ts-ticket-office-service/node_modules/sqlstring/index.js create mode 100644 ts-ticket-office-service/node_modules/sqlstring/lib/SqlString.js create mode 100644 ts-ticket-office-service/node_modules/sqlstring/package.json delete mode 100644 ts-ticket-office-service/node_modules/string_decoder/.npmignore delete mode 100644 ts-ticket-office-service/node_modules/string_decoder/README.md delete mode 100644 ts-ticket-office-service/node_modules/string_decoder/package.json rename ts-ticket-office-service/node_modules/{buffer-shims/license.md => tr46/LICENSE.md} (87%) create mode 100644 ts-ticket-office-service/node_modules/tr46/README.md create mode 100644 ts-ticket-office-service/node_modules/tr46/index.js create mode 100644 ts-ticket-office-service/node_modules/tr46/lib/mappingTable.json create mode 100644 ts-ticket-office-service/node_modules/tr46/lib/regexes.js create mode 100644 ts-ticket-office-service/node_modules/tr46/lib/statusMapping.js create mode 100644 ts-ticket-office-service/node_modules/tr46/package.json mode change 100644 => 120000 ts-ticket-office-service/node_modules/transformers/node_modules/.bin/uglifyjs mode change 100644 => 100755 ts-ticket-office-service/node_modules/transformers/node_modules/uglify-js/bin/uglifyjs mode change 100644 => 100755 ts-ticket-office-service/node_modules/uglify-js/bin/uglifyjs create mode 100644 ts-ticket-office-service/node_modules/webidl-conversions/LICENSE.md create mode 100644 ts-ticket-office-service/node_modules/webidl-conversions/README.md create mode 100644 ts-ticket-office-service/node_modules/webidl-conversions/lib/index.js create mode 100644 ts-ticket-office-service/node_modules/webidl-conversions/package.json create mode 100644 ts-ticket-office-service/node_modules/whatwg-url/LICENSE.txt create mode 100644 ts-ticket-office-service/node_modules/whatwg-url/README.md create mode 100644 ts-ticket-office-service/node_modules/whatwg-url/index.js create mode 100644 ts-ticket-office-service/node_modules/whatwg-url/lib/Function.js create mode 100644 ts-ticket-office-service/node_modules/whatwg-url/lib/URL-impl.js create mode 100644 ts-ticket-office-service/node_modules/whatwg-url/lib/URL.js create mode 100644 ts-ticket-office-service/node_modules/whatwg-url/lib/URLSearchParams-impl.js create mode 100644 ts-ticket-office-service/node_modules/whatwg-url/lib/URLSearchParams.js create mode 100644 ts-ticket-office-service/node_modules/whatwg-url/lib/VoidFunction.js create mode 100644 ts-ticket-office-service/node_modules/whatwg-url/lib/encoding.js create mode 100644 ts-ticket-office-service/node_modules/whatwg-url/lib/infra.js create mode 100644 ts-ticket-office-service/node_modules/whatwg-url/lib/percent-encoding.js create mode 100644 ts-ticket-office-service/node_modules/whatwg-url/lib/url-state-machine.js create mode 100644 ts-ticket-office-service/node_modules/whatwg-url/lib/urlencoded.js create mode 100644 ts-ticket-office-service/node_modules/whatwg-url/lib/utils.js create mode 100644 ts-ticket-office-service/node_modules/whatwg-url/package.json create mode 100644 ts-ticket-office-service/node_modules/whatwg-url/webidl2js-wrapper.js mode change 100644 => 120000 ts-ticket-office-service/node_modules/with/node_modules/.bin/acorn mode change 100644 => 100755 ts-ticket-office-service/node_modules/with/node_modules/acorn/bin/acorn create mode 100644 ts-ticket-office-service/package-lock.json create mode 100755 ts-ticket-office-service/test.sh delete mode 100644 ts-ticketinfo-service/src/main/java/ticketinfo/controller/TicketInfoController.java delete mode 100644 ts-ticketinfo-service/src/main/java/ticketinfo/entity/TrainType.java delete mode 100644 ts-ticketinfo-service/src/main/java/ticketinfo/entity/Travel.java delete mode 100644 ts-ticketinfo-service/src/main/java/ticketinfo/entity/TravelResult.java delete mode 100644 ts-ticketinfo-service/src/main/java/ticketinfo/entity/Trip.java delete mode 100644 ts-ticketinfo-service/src/main/java/ticketinfo/entity/TripId.java delete mode 100644 ts-ticketinfo-service/src/main/java/ticketinfo/entity/Type.java delete mode 100644 ts-ticketinfo-service/src/main/java/ticketinfo/service/TicketInfoService.java delete mode 100644 ts-ticketinfo-service/src/main/java/ticketinfo/service/TicketInfoServiceImpl.java delete mode 100644 ts-ticketinfo-service/src/main/resources/application.yml delete mode 100644 ts-ticketinfo-service/src/test/java/ticketinfo/controller/TicketInfoControllerTest.java delete mode 100644 ts-ticketinfo-service/src/test/java/ticketinfo/service/TicketInfoServiceImplTest.java rename {ts-ticketinfo-service => ts-train-food-service}/Dockerfile (50%) rename {ts-food-map-service => ts-train-food-service}/pom.xml (75%) create mode 100644 ts-train-food-service/src/main/java/trainFood/TrainFoodApplication.java rename {ts-ticketinfo-service/src/main/java/ticketinfo => ts-train-food-service/src/main/java/trainFood}/config/SecurityConfig.java (96%) rename {ts-food-map-service/src/main/java/food => ts-train-food-service/src/main/java/trainFood}/controller/TrainFoodController.java (79%) create mode 100644 ts-train-food-service/src/main/java/trainFood/entity/TrainFood.java create mode 100644 ts-train-food-service/src/main/java/trainFood/init/InitData.java create mode 100644 ts-train-food-service/src/main/java/trainFood/repository/TrainFoodRepository.java create mode 100644 ts-train-food-service/src/main/java/trainFood/service/TrainFoodService.java create mode 100644 ts-train-food-service/src/main/java/trainFood/service/TrainFoodServiceImpl.java create mode 100644 ts-train-food-service/src/main/resources/application.yml rename {ts-food-map-service => ts-train-food-service}/src/main/resources/trainfood.txt (100%) delete mode 100644 ts-travel-plan-service/src/main/java/travelplan/entity/RoutePlanInfo.java delete mode 100644 ts-travel-plan-service/src/main/java/travelplan/entity/RoutePlanResultUnit.java delete mode 100644 ts-travel-plan-service/src/main/java/travelplan/entity/Seat.java delete mode 100644 ts-travel-plan-service/src/main/java/travelplan/entity/SeatClass.java delete mode 100644 ts-travel-plan-service/src/main/java/travelplan/entity/TrainTypeEnum.java delete mode 100644 ts-travel-plan-service/src/main/java/travelplan/entity/Trip.java delete mode 100644 ts-travel-plan-service/src/main/java/travelplan/entity/TripId.java delete mode 100644 ts-travel-plan-service/src/main/java/travelplan/entity/TripInfo.java delete mode 100644 ts-travel-plan-service/src/main/java/travelplan/entity/TripResponse.java delete mode 100644 ts-travel-service/src/main/java/travel/entity/Route.java delete mode 100644 ts-travel-service/src/main/java/travel/entity/Seat.java delete mode 100644 ts-travel-service/src/main/java/travel/entity/SeatClass.java delete mode 100644 ts-travel-service/src/main/java/travel/entity/TrainType.java delete mode 100644 ts-travel-service/src/main/java/travel/entity/TravelInfo.java delete mode 100644 ts-travel-service/src/main/java/travel/entity/TravelResult.java delete mode 100644 ts-travel-service/src/main/java/travel/entity/TripAllDetailInfo.java delete mode 100644 ts-travel-service/src/main/java/travel/entity/TripId.java delete mode 100644 ts-travel-service/src/main/java/travel/entity/TripInfo.java delete mode 100644 ts-travel-service/src/main/java/travel/entity/TripResponse.java delete mode 100644 ts-travel-service/src/main/java/travel/entity/Type.java delete mode 100644 ts-travel2-service/src/main/java/travel2/entity/Route.java delete mode 100644 ts-travel2-service/src/main/java/travel2/entity/Seat.java delete mode 100644 ts-travel2-service/src/main/java/travel2/entity/SeatClass.java delete mode 100644 ts-travel2-service/src/main/java/travel2/entity/SoldTicket.java delete mode 100644 ts-travel2-service/src/main/java/travel2/entity/TrainType.java delete mode 100644 ts-travel2-service/src/main/java/travel2/entity/TravelInfo.java delete mode 100644 ts-travel2-service/src/main/java/travel2/entity/TravelResult.java delete mode 100644 ts-travel2-service/src/main/java/travel2/entity/TripAllDetailInfo.java delete mode 100644 ts-travel2-service/src/main/java/travel2/entity/TripId.java delete mode 100644 ts-travel2-service/src/main/java/travel2/entity/TripInfo.java delete mode 100644 ts-travel2-service/src/main/java/travel2/entity/Type.java delete mode 100644 ts-travel2-service/src/main/java/travel2/service/Travel2ServiceImpl.java rename ts-travel2-service/src/main/java/travel2/service/{Travel2Service.java => TravelService.java} (62%) create mode 100644 ts-travel2-service/src/main/java/travel2/service/TravelServiceImpl.java rename ts-travel2-service/src/test/java/travel2/controller/{Travel2ControllerTest.java => TravelControllerTest.java} (95%) rename ts-travel2-service/src/test/java/travel2/service/{Travel2ServiceImplTest.java => TravelServiceImplTest.java} (86%) create mode 100644 ts-ui-dashboard/static/assets/css/amazeui.datetimepicker.css create mode 100644 ts-ui-dashboard/static/assets/js/amazeui.datetimepicker.min.js create mode 100644 ts-wait-order-service/pom.xml create mode 100644 ts-wait-order-service/src/main/java/waitorder/WaitOrderApplication.java create mode 100644 ts-wait-order-service/src/main/java/waitorder/config/SecurityConfig.java create mode 100644 ts-wait-order-service/src/main/java/waitorder/controller/WaitListOrderController.java create mode 100644 ts-wait-order-service/src/main/java/waitorder/entity/WaitListOrder.java rename ts-preserve-service/src/main/java/preserve/entity/OrderStatus.java => ts-wait-order-service/src/main/java/waitorder/entity/WaitListOrderStatus.java (75%) create mode 100644 ts-wait-order-service/src/main/java/waitorder/entity/WaitListOrderVO.java create mode 100644 ts-wait-order-service/src/main/java/waitorder/repository/WaitListOrderRepository.java create mode 100644 ts-wait-order-service/src/main/java/waitorder/service/Impl/WaitListOrderServiceImpl.java create mode 100644 ts-wait-order-service/src/main/java/waitorder/service/WaitListOrderService.java create mode 100644 ts-wait-order-service/src/main/java/waitorder/utils/PollThread.java create mode 100644 ts-wait-order-service/src/main/resources/application.yml create mode 100644 ts-wait-order-service/src/test/java/waitorder/WaitOrderApplicationTests.java create mode 100644 ts-wait-order-service/src/test/java/waitorder/service/Impl/WaitListOrderServiceImplTest.java diff --git a/CHANGELOG-1.0.md b/CHANGELOG-1.0.md new file mode 100644 index 000000000..f0281e59d --- /dev/null +++ b/CHANGELOG-1.0.md @@ -0,0 +1,159 @@ + + + * [v1.0.0](#v100-beta0) + * [Deploy v1.0.0](#deploy-v1.0.0) + * [For Quick Start](#for-quick-start) + * [Deploy Mysql Clusters For Each Services](#deploy-mysql-clusters-for-each-services) + * [With Moinitorig](#with-moinitorig) + * [With Distributed Tracing](#with-distributed-tracing) + * [Deploy All](#deploy-all) + * [Customise Deployment](#customise-deployment) + * [Reset Deployment](#reset-deployment) + + * [Changelog since 0.2.1](#changelog-since-v021) + * [Features Added](#features-added) + * [Notable Changes](#notable-changes) + * [Test Support](#test-support) + * [Bug fix](#bug-fix) + + +# v1.0.0 + +## Deploy v1.0.0 + +### For Quick Start +```bash +git clone https://github.com/FudanSELab/train-ticket.git release-1.0.0 +cd train-ticket +make deploy + +``` + +Note: if you want specify namespace, set Namespace paramter: + +```bash +make deploy Namespace=yournamespace +``` + +### Deploy Mysql Clusters For Each Services + +```bash +git clone https://github.com/FudanSELab/train-ticket.git release-1.0.0 +cd train-ticket +make deploy DeployArgs="--independent-db" +``` + +### With Moinitorig +```bash +git clone https://github.com/FudanSELab/train-ticket.git release-1.0.0 +cd train-ticket +make deploy DeployArgs="--with-monitoring" +``` + +### With Distributed Tracing +```bash +git clone https://github.com/FudanSELab/train-ticket.git release-1.0.0 +cd train-ticket +make deploy DeployArgs="--with-tracing" +``` + +### Deploy All +```bash +git clone https://github.com/FudanSELab/train-ticket.git release-1.0.0 +cd train-ticket +make deploy DeployArgs="--all" +``` + +### Customise Deployment +You can freely combine parameters for custom deployment, for example, deploy with monitoring and tracing: + +```bash +git clone https://github.com/FudanSELab/train-ticket.git release-1.0.0 +cd train-ticket +make deploy DeployArgs="--with-tracing --with-monitoring" +``` + +### Reset Deployment + +``` +make reset-deploy +# if you specify namespace when deploy, set namespace as well when reset +# make reset-deploy Namespace=yournamespace +``` + +## Changelog since v0.2.1 + +### Features Added + +**Service Discovery: Nacos** + +Use nacos as service register and discovery component. + +Nacos use mysql cluster to store config information. + +We use nacos 2.0.1 version, for more infromation of nacos, to see: [https://nacos.io/zh-cn/docs/what-is-nacos.html +](https://nacos.io/zh-cn/docs/what-is-nacos.html) + +**Gateway** + +Using gateway as the only entry point for all service calls. A series of cross-cutting functions can be completed in the service gateway, such as permission verification, current limiting and monitoring, etc., which can be completed through filters. + +We use spring-cloud-gateway to implement the gateway function. + +**Flow Control: Sentinel** + +We use Sentinel to implement the flow control for gateway. For now, the flow control rule is simply defined in route level. We simply limited the QPS towards admin-basic-info-service to no more than 20. + +To customize the flow control rule, update the configuration for Sentinel in `GatewayConfiguration.java` file. + +**Monitoring: Promethues+Grafana Deployment** + +We support prometheus + grafana solution in k8s deployment. + +The deployment manifests of prometheus are located at:deployment/kubernetes-manifests/prometheus + +**Distributed Tracing: Skywalking+ES Supoort** + +We support skywalking + es solution in k8s deployment. + +The deployment manifests of prometheus are located at:deployment/kubernetes-manifests/skywalking + + +### Notable Changes + +**Log Format Unification** + +Unified log format for all services + +**Framework Upgrade** + +Upgrade spring-boot version from 1.5.0 to 2.3.12.RELEASE. + +Upgrade related dependency of services. + +**Data Structrue Redesign** + +Extract the common data structure of the service and put it in ts-common, instead of redefining them each service once. And data field naming is normalized. + +**Dynamic Service Configuration** + +Each service can dynamically configure its own database information, service discovery information, message queue information etc., (k8s deployment through configmap and secret, docker-compose deployment through environment variables) without the need to repackage the image. + +**Mysql Cluster Mode Support** + +Because the relational nature of the train ticket business is complex, we use a relational database, ie mysql. To support clustered deployment of mysql, we use randondb's solution for mysql deployment. For more details, see: [https://radondb.io/](https://radondb.io/) + +### Test Support + +We provide test scripts for functional and performance testing of train-tickets. The script provides some scenarios, such as administrator_operations, normal_query_and_booking, rebooking, rebooking_failure, search_failure, and consign_preserve. +At the same time, the script supports qos parameter setting, which can easily implement performance testing. +Access test scripts at: [https://github.com/FudanSELab/train-ticket-auto-query ](https://github.com/FudanSELab/train-ticket-auto-query) + + +### Bug Fix + +* update order failed by the administrator. +* delete order failed by the administrator. +* delete user failed by the administrator. +* delete price failed by the administrator. +* delete station failed by the administrator. diff --git a/Makefile b/Makefile index da46a33d5..24ceab756 100644 --- a/Makefile +++ b/Makefile @@ -2,6 +2,9 @@ Repo=codewisdom Tag=latest +Namespace="default" +DeployArgs="" + # build image .PHONY: build @@ -9,7 +12,7 @@ build: clean-image package build-image .PHONY: package package: - @mvn clean package -DskipTests + @mvn clean package -Dmaven.test.skip=true .PHONY: build-image build-image: @@ -24,6 +27,21 @@ push-image: publish-image: @script/publish-docker-images.sh $(Repo) $(Tag) +# deploy +# DeployArgs "" : deploy train-ticket with all-in-one mysql cluster +# DeployArgs "--independent-db" : deploy train-ticket with mysql cluster each service +# DeployArgs "--with-monitoring" : deploy train-ticket with prometheus +# DeployArgs "--with-tracing" : deploy train-ticket with skywalking +# DeployArgs "--all" : deploy train-ticket with mysql cluster each service +.PHONY: deploy +deploy: + @hack/deploy/deploy.sh $(Namespace) "$(DeployArgs)" + +# deploy +.PHONY: reset-deploy +reset-deploy: + @hack/deploy/reset.sh $(Namespace) + .PHONY: clean clean: @mvn clean diff --git a/README.md b/README.md index 15c98789d..c1884e259 100644 --- a/README.md +++ b/README.md @@ -14,66 +14,84 @@ You can get more details at [Wiki Pages](https://github.com/FudanSELab/train-tic ![architecture](./image/2.png) ## Quick Start -We provide two options to quickly deploy our application: [Using Docker Compose](#Using-Docker-Compose) and [Using Kubernetes](#Using-Kubernetes). +We provide k8s deployment to quickly deploy our application: [Using Kubernetes](#Using-Kubernetes). -### Using Docker Compose -The easiest way to get start with the Train Ticket application is by using [Docker](https://www.docker.com/) and [Docker Compose](https://docs.docker.com/compose/). - -> If you don't have Docker and Docker Compose installed, you can refer to [the Docker website](https://www.docker.com/) to install them. +### Using Kubernetes +Here is the steps to deploy the Train Ticket onto any existing Kubernetes cluster. #### Presequisite -* Docker -* Docker Compose +* An existing Kubernetes cluster +* Helm supported, you can see https://helm.sh/docs/helm/helm_install/ for helm install +* PVC supported, you can see https://openebs.io/docs/2.12.x/user-guides/installation for localPV support. #### 1. Clone the Repository ```bash -git clone --depth=1 https://github.com/FudanSELab/train-ticket.git +git clone --depth=1 https://github.com/FudanSELab/train-ticket.git cd train-ticket/ ``` -#### 2. Start the Application +#### 2. Deploy the application +### For Quick Start ```bash -docker-compose -f deployment/docker-compose-manifests/quickstart-docker-compose.yml up +make deploy + ``` -Once the application starts, you can visit the Train Ticket web page at [http://localhost:8080](http://localhost:8080). -### Using Kubernetes -Here is the steps to deploy the Train Ticket onto any existing Kubernetes cluster. +Note: if you want specify namespace, set Namespace paramter: -#### Presequisite -* An existing Kubernetes cluster +```bash +make deploy Namespace=yournamespace +``` + +### Deploy Mysql Clusters For Each Services -#### 1. Clone the Repository ```bash -git clone --depth=1 https://github.com/FudanSELab/train-ticket.git -cd train-ticket/ +make deploy DeployArgs="--independent-db" ``` -#### 2. Deploy the application +### With Moinitorig ```bash -cd deployment/kubernetes-manifests/quickstart-k8s - -# Deploy the databases -kubectl apply -f quickstart-ts-deployment-part1.yml -# Deploy the services -kubectl apply -f quickstart-ts-deployment-part2.yml -# Deploy the UI Dashboard -kubectl apply -f quickstart-ts-deployment-part3.yml +make deploy DeployArgs="--with-monitoring" +``` + +### With Distributed Tracing +```bash +make deploy DeployArgs="--with-tracing" +``` + +### Deploy All +```bash +make deploy DeployArgs="--all" +``` + +### Customise Deployment +You can freely combine parameters for custom deployment, for example, deploy with monitoring and tracing: + +```bash +make deploy DeployArgs="--with-tracing --with-monitoring" +``` + +### Reset Deployment + +``` +make reset-deploy +# if you specify namespace when deploy, set namespace as well when reset +# make reset-deploy Namespace=yournamespace ``` #### 3. Run `kubectl get pods` to see pods are in a ready state #### 4. Visit the Train Ticket web page at [http://[Node-IP]:32677](http://[Node-IP]:32677). -### More Deployment Ways - -There are many other quick deployment ways in [deployment folder](). For example, you can deploy this system [with Jaeger](), and then visit the Jaeger Webpage to view traces. ## Build From Source In the above, We use pre-built images to quickly deploy the application. If you want to build the application from source, you can refer to [the Installation Guide](https://github.com/FudanSELab/train-ticket/wiki/Installation-Guide). +## test scripts +Use scripts to test train-ticket: [https://github.com/FudanSELab/train-ticket-auto-query](https://github.com/FudanSELab/train-ticket-auto-query) + ## Screenshot ![screenshot](./image/main_interface.png) In order to know how to use the application, you can refer to [the User Guide](https://github.com/FudanSELab/train-ticket/wiki/User-Guide). diff --git a/deployment/docker-compose-manifests/docker-compose-with-jaeger.yml b/deployment/docker-compose-manifests/docker-compose-with-jaeger.yml index 1f26f67aa..198b2c97a 100644 --- a/deployment/docker-compose-manifests/docker-compose-with-jaeger.yml +++ b/deployment/docker-compose-manifests/docker-compose-with-jaeger.yml @@ -48,8 +48,8 @@ services: networks: - my-network - ts-auth-mongo: - image: mongo + ts-auth-mysql: + image: mysql:5.7 networks: - my-network @@ -61,8 +61,8 @@ services: networks: - my-network - ts-user-mongo: - image: mongo + ts-user-mysql: + image: mysql:5.7 networks: - my-network @@ -75,10 +75,10 @@ services: - my-network - ts-account-mongo: - image: mongo - networks: - - my-network +# ts-account-mongo: +# image: mongo +# networks: +# - my-network ts-route-service: image: codewisdom/ts-route-service-with-jaeger:v1 @@ -88,8 +88,8 @@ services: networks: - my-network - ts-route-mongo: - image: mongo + ts-route-mysql: + image: mysql:5.7 networks: - my-network @@ -101,8 +101,8 @@ services: networks: - my-network - ts-contacts-mongo: - image: mongo + ts-contacts-mysql: + image: mysql:5.7 networks: - my-network @@ -114,8 +114,8 @@ services: networks: - my-network - ts-order-mongo: - image: mongo + ts-order-mysql: + image: mysql:5.7 networks: - my-network @@ -128,8 +128,8 @@ services: networks: - my-network - ts-order-other-mongo: - image: mongo + ts-order-other-mysql: + image: mysql:5.7 networks: - my-network @@ -142,8 +142,8 @@ services: networks: - my-network - ts-config-mongo: - image: mongo + ts-config-mysql: + image: mysql:5.7 networks: - my-network @@ -155,8 +155,8 @@ services: networks: - my-network - ts-station-mongo: - image: mongo + ts-station-mysql: + image: mysql:5.7 networks: - my-network @@ -168,8 +168,8 @@ services: networks: - my-network - ts-train-mongo: - image: mongo + ts-train-mysql: + image: mysql:5.7 networks: - my-network @@ -181,8 +181,8 @@ services: networks: - my-network - ts-travel-mongo: - image: mongo + ts-travel-mysql: + image: mysql:5.7 networks: - my-network @@ -194,8 +194,8 @@ services: networks: - my-network - ts-travel2-mongo: - image: mongo + ts-travel2-mysql: + image: mysql:5.7 networks: - my-network @@ -224,13 +224,13 @@ services: networks: - my-network - ts-ticketinfo-service: - image: codewisdom/ts-ticketinfo-service-with-jaeger:v1 - restart: always - ports: - - 15681:15681 - networks: - - my-network +# ts-ticketinfo-service: +# image: codewisdom/ts-ticketinfo-service-with-jaeger:v1 +# restart: always +# ports: +# - 15681:15681 +# networks: +# - my-network ts-price-service: image: codewisdom/ts-price-service-with-jaeger:v1 @@ -240,8 +240,8 @@ services: networks: - my-network - ts-price-mongo: - image: mongo + ts-price-mysql: + image: mysql:5.7 networks: - my-network @@ -253,6 +253,11 @@ services: networks: - my-network + ts-notification-mysql: + image: mysql:5.7 + networks: + - my-network + ts-security-service: image: codewisdom/ts-security-service-with-jaeger:v1 restart: always @@ -261,8 +266,8 @@ services: networks: - my-network - ts-security-mongo: - image: mongo + ts-security-mysql: + image: mysql:5.7 networks: - my-network @@ -274,8 +279,8 @@ services: networks: - my-network - ts-inside-payment-mongo: - image: mongo + ts-inside-payment-mysql: + image: mysql:5.7 networks: - my-network @@ -295,8 +300,8 @@ services: networks: - my-network - ts-payment-mongo: - image: mongo + ts-payment-mysql: + image: mysql:5.7 networks: - my-network @@ -308,8 +313,8 @@ services: networks: - my-network - ts-rebook-mongo: - image: mongo + ts-rebook-mysql: + image: mysql:5.7 networks: - my-network @@ -329,8 +334,8 @@ services: networks: - my-network - ts-assurance-mongo: - image: mongo + ts-assurance-mysql: + image: mysql:5.7 networks: - my-network @@ -350,18 +355,18 @@ services: networks: - my-network - ts-ticket-office-service: - image: codewisdom/ts-ticket-office-service-with-jaeger:v1 - restart: always - ports: - - 16108:16108 - networks: - - my-network - - ts-ticket-office-mongo: - image: mongo - networks: - - my-network +# ts-ticket-office-service: +# image: codewisdom/ts-ticket-office-service-with-jaeger:v1 +# restart: always +# ports: +# - 16108:16108 +# networks: +# - my-network +# +# ts-ticket-office-mongo: +# image: mongo +# networks: +# - my-network ts-news-service: image: codewisdom/ts-news-service-with-jaeger:v1 @@ -371,8 +376,8 @@ services: networks: - my-network - ts-news-mongo: - image: mongo + ts-news-mysql: + image: mysql:5.7 networks: - my-network @@ -397,18 +402,18 @@ services: networks: - my-network - ts-food-map-service: - image: codewisdom/ts-food-map-service-with-jaeger:v1 - restart: always - ports: - - 18855:18855 - networks: - - my-network - - ts-food-map-mongo: - image: mongo - networks: - - my-network +# ts-food-map-service: +# image: codewisdom/ts-food-map-service-with-jaeger:v1 +# restart: always +# ports: +# - 18855:18855 +# networks: +# - my-network +# +# ts-food-map-mongo: +# image: mongo +# networks: +# - my-network ts-route-plan-service: image: codewisdom/ts-route-plan-service-with-jaeger:v1 @@ -426,6 +431,12 @@ services: networks: - my-network + + ts-food-mysql: + image: mysql:5.7 + networks: + - my-network + ts-consign-service: image: codewisdom/ts-consign-service-with-jaeger:v1 restart: always @@ -434,8 +445,8 @@ services: networks: - my-network - ts-consign-mongo: - image: mongo + ts-consign-mysql: + image: mysql:5.7 networks: - my-network @@ -447,15 +458,11 @@ services: networks: - my-network - ts-consign-price-mongo: - image: mongo + ts-consign-price-mysql: + image: mysql:5.7 networks: - my-network - ts-food-mongo: - image: mongo - networks: - - my-network ts-admin-basic-info-service: image: codewisdom/ts-admin-basic-info-service-with-jaeger:v1 @@ -509,6 +516,83 @@ services: networks: - my-network + ts-avatar-service: + image: codewisdom/ts-avatar-service-with-jaeger:v1 + restart: always + ports: + - 17001:17001 + networks: + - my-network + + + ts-delivery-service: + image: ${NAMESPACE}/ts-delivery-servicee-with-jaeger:v1 + restart: always + ports: + - 18808:18808 + networks: + - my-network + + ts-delivery-mysql: + image: mysql:5.7 + networks: + - my-network + + + ts-food-delivery-service: + image: ${NAMESPACE}/ts-food-delivery-service-with-jaeger:v1 + restart: always + ports: + - 18957:18957 + networks: + - my-network + + ts-food-delivery-mysql: + image: mysql:5.7 + networks: + - my-network + + + ts-gateway-service: + image: ${NAMESPACE}/ts-gateway-service-with-jaeger:v1 + restart: always + ports: + - 18888:18888 + networks: + - my-network + + ts-gateway-mysql: + image: mysql:5.7 + networks: + - my-network + + ts-station-food-service: + image: ${NAMESPACE}/ts-station-food-service-with-jaeger:v1 + restart: always + ports: + - 18855:18855 + networks: + - my-network + + ts-station-food-mysql: + image: mysql:5.7 + networks: + - my-network + + ts-train-food-service: + image: ${NAMESPACE}/ts-train-food-service-with-jaeger:v1 + restart: always + ports: + - 19999:19999 + networks: + - my-network + + ts-train-food-mysql: + image: mysql:5.7 + networks: + - my-network + + jaeger: image: jaegertracing/all-in-one:1.15 ports: diff --git a/deployment/docker-compose-manifests/quickstart-docker-compose.yml b/deployment/docker-compose-manifests/quickstart-docker-compose.yml index c55dcacfa..2c36ff9a0 100644 --- a/deployment/docker-compose-manifests/quickstart-docker-compose.yml +++ b/deployment/docker-compose-manifests/quickstart-docker-compose.yml @@ -48,8 +48,8 @@ services: networks: - my-network - ts-auth-mongo: - image: mongo + ts-auth-mysql: + image: mysql:5.7 networks: - my-network @@ -61,8 +61,8 @@ services: networks: - my-network - ts-user-mongo: - image: mongo + ts-user-mysql: + image: mysql:5.7 networks: - my-network @@ -75,10 +75,10 @@ services: - my-network - ts-account-mongo: - image: mongo - networks: - - my-network +# ts-account-mongo: +# image: mongo +# networks: +# - my-network ts-route-service: image: ${NAMESPACE}/ts-route-service:${TAG} @@ -88,8 +88,8 @@ services: networks: - my-network - ts-route-mongo: - image: mongo + ts-route-mysql: + image: mysql:5.7 networks: - my-network @@ -101,8 +101,8 @@ services: networks: - my-network - ts-contacts-mongo: - image: mongo + ts-contacts-mysql: + image: mysql:5.7 networks: - my-network @@ -114,8 +114,8 @@ services: networks: - my-network - ts-order-mongo: - image: mongo + ts-order-mysql: + image: mysql:5.7 networks: - my-network @@ -128,8 +128,8 @@ services: networks: - my-network - ts-order-other-mongo: - image: mongo + ts-order-other-mysql: + image: mysql:5.7 networks: - my-network @@ -142,8 +142,8 @@ services: networks: - my-network - ts-config-mongo: - image: mongo + ts-config-mysql: + image: mysql:5.7 networks: - my-network @@ -155,8 +155,8 @@ services: networks: - my-network - ts-station-mongo: - image: mongo + ts-station-mysql: + image: mysql:5.7 networks: - my-network @@ -168,8 +168,8 @@ services: networks: - my-network - ts-train-mongo: - image: mongo + ts-train-mysql: + image: mysql:5.7 networks: - my-network @@ -181,8 +181,8 @@ services: networks: - my-network - ts-travel-mongo: - image: mongo + ts-travel-mysql: + image: mysql:5.7 networks: - my-network @@ -194,8 +194,8 @@ services: networks: - my-network - ts-travel2-mongo: - image: mongo + ts-travel2-mysql: + image: mysql:5.7 networks: - my-network @@ -224,13 +224,13 @@ services: networks: - my-network - ts-ticketinfo-service: - image: ${NAMESPACE}/ts-ticketinfo-service:${TAG} - restart: always - ports: - - 15681:15681 - networks: - - my-network +# ts-ticketinfo-service: +# image: ${NAMESPACE}/ts-ticketinfo-service:${TAG} +# restart: always +# ports: +# - 15681:15681 +# networks: +# - my-network ts-price-service: image: ${NAMESPACE}/ts-price-service:${TAG} @@ -240,8 +240,8 @@ services: networks: - my-network - ts-price-mongo: - image: mongo + ts-price-mysql: + image: mysql:5.7 networks: - my-network @@ -253,6 +253,11 @@ services: networks: - my-network + ts-notification-mysql: + image: mysql:5.7 + networks: + - my-network + ts-security-service: image: ${NAMESPACE}/ts-security-service:${TAG} restart: always @@ -261,8 +266,8 @@ services: networks: - my-network - ts-security-mongo: - image: mongo + ts-security-mysql: + image: mysql:5.7 networks: - my-network @@ -274,8 +279,8 @@ services: networks: - my-network - ts-inside-payment-mongo: - image: mongo + ts-inside-payment-mysql: + image: mysql:5.7 networks: - my-network @@ -295,8 +300,8 @@ services: networks: - my-network - ts-payment-mongo: - image: mongo + ts-payment-mysql: + image: mysql:5.7 networks: - my-network @@ -308,8 +313,8 @@ services: networks: - my-network - ts-rebook-mongo: - image: mongo + ts-rebook-mysql: + image: mysql:5.7 networks: - my-network @@ -329,8 +334,8 @@ services: networks: - my-network - ts-assurance-mongo: - image: mongo + ts-assurance-mysql: + image: mysql:5.7 networks: - my-network @@ -350,18 +355,18 @@ services: networks: - my-network - ts-ticket-office-service: - image: ${NAMESPACE}/ts-ticket-office-service:${TAG} - restart: always - ports: - - 16108:16108 - networks: - - my-network - - ts-ticket-office-mongo: - image: mongo - networks: - - my-network +# ts-ticket-office-service: +# image: ${NAMESPACE}/ts-ticket-office-service:${TAG} +# restart: always +# ports: +# - 16108:16108 +# networks: +# - my-network +# +# ts-ticket-office-mongo: +# image: mongo +# networks: +# - my-network ts-news-service: image: ${NAMESPACE}/ts-news-service:${TAG} @@ -371,8 +376,8 @@ services: networks: - my-network - ts-news-mongo: - image: mongo + ts-news-mysql: + image: mysql:5.7 networks: - my-network @@ -397,18 +402,18 @@ services: networks: - my-network - ts-food-map-service: - image: ${NAMESPACE}/ts-food-map-service:${TAG} - restart: always - ports: - - 18855:18855 - networks: - - my-network - - ts-food-map-mongo: - image: mongo - networks: - - my-network +# ts-food-map-service: +# image: ${NAMESPACE}/ts-food-map-service:${TAG} +# restart: always +# ports: +# - 18855:18855 +# networks: +# - my-network +# +# ts-food-map-mongo: +# image: mongo +# networks: +# - my-network ts-route-plan-service: image: ${NAMESPACE}/ts-route-plan-service:${TAG} @@ -434,8 +439,8 @@ services: networks: - my-network - ts-consign-mongo: - image: mongo + ts-consign-mysql: + image: mysql:5.7 networks: - my-network @@ -447,13 +452,13 @@ services: networks: - my-network - ts-consign-price-mongo: - image: mongo + ts-consign-price-mysql: + image: mysql:5.7 networks: - my-network - ts-food-mongo: - image: mongo + ts-food-mysql: + image: mysql:5.7 networks: - my-network @@ -517,6 +522,74 @@ services: networks: - my-network + ts-delivery-service: + image: ${NAMESPACE}/ts-delivery-servicee:${TAG} + restart: always + ports: + - 18808:18808 + networks: + - my-network + + ts-delivery-mysql: + image: mysql:5.7 + networks: + - my-network + + ts-food-delivery-service: + image: ${NAMESPACE}/ts-food-delivery-service:${TAG} + restart: always + ports: + - 18957:18957 + networks: + - my-network + + ts-food-delivery-mysql: + image: mysql:5.7 + networks: + - my-network + + ts-gateway-service: + image: ${NAMESPACE}/ts-gateway-service:${TAG} + restart: always + ports: + - 18888:18888 + networks: + - my-network + + ts-gateway-mysql: + image: mysql:5.7 + networks: + - my-network + + + ts-station-food-service: + image: ${NAMESPACE}/ts-station-food-service:${TAG} + restart: always + ports: + - 18855:18855 + networks: + - my-network + + ts-station-food-mysql: + image: mysql:5.7 + networks: + - my-network + + + ts-train-food-service: + image: ${NAMESPACE}/ts-train-food-service:${TAG} + restart: always + ports: + - 19999:19999 + networks: + - my-network + + ts-train-food-mysql: + image: mysql:5.7 + networks: + - my-network + + networks: my-network: # driver: overlay diff --git a/deployment/kubernetes-manifests/prometheus-deployment/configmap.yaml b/deployment/kubernetes-manifests/prometheus-deployment/configmap.yaml deleted file mode 100644 index 93bd2df1b..000000000 --- a/deployment/kubernetes-manifests/prometheus-deployment/configmap.yaml +++ /dev/null @@ -1,156 +0,0 @@ -apiVersion: v1 -kind: ConfigMap -metadata: - name: prometheus-config - namespace: kube-system -data: - prometheus.yml: | - global: - scrape_interval: 15s - evaluation_interval: 15s - scrape_configs: - - - job_name: 'kubernetes-apiservers' - kubernetes_sd_configs: - - role: endpoints - scheme: https - tls_config: - ca_file: /var/run/secrets/kubernetes.io/serviceaccount/ca.crt - bearer_token_file: /var/run/secrets/kubernetes.io/serviceaccount/token - relabel_configs: - - source_labels: [__meta_kubernetes_namespace, __meta_kubernetes_service_name, __meta_kubernetes_endpoint_port_name] - action: keep - regex: default;kubernetes;https - - - job_name: 'kubernetes-nodes' - kubernetes_sd_configs: - - role: node - scheme: https - tls_config: - ca_file: /var/run/secrets/kubernetes.io/serviceaccount/ca.crt - bearer_token_file: /var/run/secrets/kubernetes.io/serviceaccount/token - relabel_configs: - - action: labelmap - regex: __meta_kubernetes_node_label_(.+) - - target_label: __address__ - replacement: kubernetes.default.svc:443 - - source_labels: [__meta_kubernetes_node_name] - regex: (.+) - target_label: __metrics_path__ - replacement: /api/v1/nodes/${1}/proxy/metrics - - - job_name: 'kubernetes-cadvisor' - kubernetes_sd_configs: - - role: node - scheme: https - tls_config: - ca_file: /var/run/secrets/kubernetes.io/serviceaccount/ca.crt - bearer_token_file: /var/run/secrets/kubernetes.io/serviceaccount/token - relabel_configs: - - action: labelmap - regex: __meta_kubernetes_node_label_(.+) - - target_label: __address__ - replacement: kubernetes.default.svc:443 - - source_labels: [__meta_kubernetes_node_name] - regex: (.+) - target_label: __metrics_path__ - replacement: /api/v1/nodes/${1}/proxy/metrics/cadvisor - - - job_name: 'kubernetes-service-endpoints' - kubernetes_sd_configs: - - role: endpoints - relabel_configs: - - source_labels: [__meta_kubernetes_service_annotation_prometheus_io_scrape] - action: drop - regex: false - - source_labels: [__meta_kubernetes_service_annotation_prometheus_io_scheme] - action: replace - target_label: __scheme__ - regex: (https?) - - source_labels: [__meta_kubernetes_service_annotation_prometheus_io_path] - action: replace - target_label: __metrics_path__ - regex: (.+) - - source_labels: [__address__, __meta_kubernetes_service_annotation_prometheus_io_port] - action: replace - target_label: __address__ - regex: ([^:]+)(?::\d+)?;(\d+) - replacement: $1:$2 - - action: labelmap - regex: __meta_kubernetes_service_label_(.+) - - source_labels: [__meta_kubernetes_namespace] - action: replace - target_label: kubernetes_namespace - - source_labels: [__meta_kubernetes_service_name] - action: replace - target_label: kubernetes_name - - - job_name: 'kubernetes-services' - kubernetes_sd_configs: - - role: service - metrics_path: /probe - params: - module: [http_2xx] - relabel_configs: - - source_labels: [__meta_kubernetes_service_annotation_prometheus_io_probe] - action: keep - regex: true - - source_labels: [__address__] - target_label: __param_target - - target_label: __address__ - replacement: blackbox-exporter.example.com:9115 - - source_labels: [__param_target] - target_label: instance - - action: labelmap - regex: __meta_kubernetes_service_label_(.+) - - source_labels: [__meta_kubernetes_namespace] - target_label: kubernetes_namespace - - source_labels: [__meta_kubernetes_service_name] - target_label: kubernetes_name - - - job_name: 'kubernetes-ingresses' - kubernetes_sd_configs: - - role: ingress - relabel_configs: - - source_labels: [__meta_kubernetes_ingress_annotation_prometheus_io_probe] - action: keep - regex: true - - source_labels: [__meta_kubernetes_ingress_scheme,__address__,__meta_kubernetes_ingress_path] - regex: (.+);(.+);(.+) - replacement: ${1}://${2}${3} - target_label: __param_target - - target_label: __address__ - replacement: blackbox-exporter.example.com:9115 - - source_labels: [__param_target] - target_label: instance - - action: labelmap - regex: __meta_kubernetes_ingress_label_(.+) - - source_labels: [__meta_kubernetes_namespace] - target_label: kubernetes_namespace - - source_labels: [__meta_kubernetes_ingress_name] - target_label: kubernetes_name - - - job_name: 'kubernetes-pods' - kubernetes_sd_configs: - - role: pod - relabel_configs: - - source_labels: [__meta_kubernetes_pod_annotation_prometheus_io_scrape] - action: keep - regex: true - - source_labels: [__meta_kubernetes_pod_annotation_prometheus_io_path] - action: replace - target_label: __metrics_path__ - regex: (.+) - - source_labels: [__address__, __meta_kubernetes_pod_annotation_prometheus_io_port] - action: replace - regex: ([^:]+)(?::\d+)?;(\d+) - replacement: $1:$2 - target_label: __address__ - - action: labelmap - regex: __meta_kubernetes_pod_label_(.+) - - source_labels: [__meta_kubernetes_namespace] - action: replace - target_label: kubernetes_namespace - - source_labels: [__meta_kubernetes_pod_name] - action: replace - target_label: kubernetes_pod_name diff --git a/deployment/kubernetes-manifests/prometheus-deployment/kube-state-metrics.yaml b/deployment/kubernetes-manifests/prometheus-deployment/kube-state-metrics.yaml deleted file mode 100644 index 79390a5d7..000000000 --- a/deployment/kubernetes-manifests/prometheus-deployment/kube-state-metrics.yaml +++ /dev/null @@ -1,194 +0,0 @@ ---- -apiVersion: rbac.authorization.k8s.io/v1 -# kubernetes versions before 1.8.0 should use rbac.authorization.k8s.io/v1beta1 -kind: Role -metadata: - namespace: kube-system - name: kube-state-metrics-resizer -rules: -- apiGroups: [""] - resources: - - pods - verbs: ["get"] -- apiGroups: ["apps"] - resources: - - deployments - resourceNames: ["kube-state-metrics"] - verbs: ["get", "update"] -- apiGroups: ["extensions"] - resources: - - deployments - resourceNames: ["kube-state-metrics"] - verbs: ["get", "update"] ---- -apiVersion: rbac.authorization.k8s.io/v1 -# kubernetes versions before 1.8.0 should use rbac.authorization.k8s.io/v1beta1 -kind: RoleBinding -metadata: - name: kube-state-metrics - namespace: kube-system -roleRef: - apiGroup: rbac.authorization.k8s.io - kind: Role - name: kube-state-metrics-resizer -subjects: -- kind: ServiceAccount - name: kube-state-metrics - namespace: kube-system ---- -apiVersion: rbac.authorization.k8s.io/v1 -# kubernetes versions before 1.8.0 should use rbac.authorization.k8s.io/v1beta1 -kind: ClusterRole -metadata: - name: kube-state-metrics -rules: -- apiGroups: [""] - resources: - - configmaps - - secrets - - nodes - - pods - - services - - resourcequotas - - replicationcontrollers - - limitranges - - persistentvolumeclaims - - persistentvolumes - - namespaces - - endpoints - verbs: ["list", "watch"] -- apiGroups: ["extensions"] - resources: - - daemonsets - - deployments - - replicasets - - ingresses - verbs: ["list", "watch"] -- apiGroups: ["apps"] - resources: - - daemonsets - - deployments - - replicasets - - statefulsets - verbs: ["list", "watch"] -- apiGroups: ["batch"] - resources: - - cronjobs - - jobs - verbs: ["list", "watch"] -- apiGroups: ["autoscaling"] - resources: - - horizontalpodautoscalers - verbs: ["list", "watch"] -- apiGroups: ["policy"] - resources: - - poddisruptionbudgets - verbs: ["list", "watch"] -- apiGroups: ["certificates.k8s.io"] - resources: - - certificatesigningrequests - verbs: ["list", "watch"] ---- -apiVersion: rbac.authorization.k8s.io/v1 -# kubernetes versions before 1.8.0 should use rbac.authorization.k8s.io/v1beta1 -kind: ClusterRoleBinding -metadata: - name: kube-state-metrics -roleRef: - apiGroup: rbac.authorization.k8s.io - kind: ClusterRole - name: kube-state-metrics -subjects: -- kind: ServiceAccount - name: kube-state-metrics - namespace: kube-system ---- -apiVersion: v1 -kind: ServiceAccount -metadata: - name: kube-state-metrics - namespace: kube-system ---- -apiVersion: v1 -kind: Service -metadata: - name: kube-state-metrics - namespace: kube-system - labels: - k8s-app: kube-state-metrics - annotations: - prometheus.io/scrape: ‘true‘ -spec: - type: NodePort - ports: - - name: http-metrics - port: 8080 - nodePort: 30006 - targetPort: http-metrics - protocol: TCP - - name: telemetry - port: 8081 - targetPort: telemetry - protocol: TCP - selector: - k8s-app: kube-state-metrics ---- -apiVersion: apps/v1 -# Kubernetes version 1.8.x should use apps/v1beta2 -# Kubernetes versions before 1.8.0 should use apps/v1beta1 or extensions/v1beta1 -kind: Deployment -metadata: - name: kube-state-metrics - namespace: kube-system -spec: - selector: - matchLabels: - k8s-app: kube-state-metrics - replicas: 1 - template: - metadata: - labels: - k8s-app: kube-state-metrics - spec: - serviceAccountName: kube-state-metrics - containers: - - name: kube-state-metrics - image: carlosedp/kube-state-metrics:v1.5.0 - ports: - - name: http-metrics - containerPort: 8080 - - name: telemetry - containerPort: 8081 - readinessProbe: - httpGet: - path: /healthz - port: 8080 - initialDelaySeconds: 5 - timeoutSeconds: 5 - - name: addon-resizer - image: carlosedp/addon-resizer:v1.8.4 - resources: - limits: - cpu: 150m - memory: 50Mi - requests: - cpu: 150m - memory: 50Mi - env: - - name: MY_POD_NAME - valueFrom: - fieldRef: - fieldPath: metadata.name - - name: MY_POD_NAMESPACE - valueFrom: - fieldRef: - fieldPath: metadata.namespace - command: - - /pod_nanny - - --container=kube-state-metrics - - --cpu=100m - - --extra-cpu=1m - - --memory=100Mi - - --extra-memory=2Mi - - --threshold=5 - - --deployment=kube-state-metrics diff --git a/deployment/kubernetes-manifests/prometheus-deployment/node-exporter.yaml b/deployment/kubernetes-manifests/prometheus-deployment/node-exporter.yaml deleted file mode 100644 index 392766cdc..000000000 --- a/deployment/kubernetes-manifests/prometheus-deployment/node-exporter.yaml +++ /dev/null @@ -1,40 +0,0 @@ -apiVersion: apps/v1 -kind: DaemonSet -metadata: - name: node-exporter - namespace: kube-system - labels: - k8s-app: node-exporter -spec: - selector: - matchLabels: - k8s-app: node-exporter - template: - metadata: - labels: - k8s-app: node-exporter - spec: - containers: - - image: prom/node-exporter - name: node-exporter - ports: - - containerPort: 9100 - protocol: TCP - name: http ---- -apiVersion: v1 -kind: Service -metadata: - labels: - k8s-app: node-exporter - name: node-exporter - namespace: kube-system -spec: - ports: - - name: http - port: 9100 - nodePort: 31672 - protocol: TCP - type: NodePort - selector: - k8s-app: node-exporter diff --git a/deployment/kubernetes-manifests/prometheus-deployment/prometheus.yaml b/deployment/kubernetes-manifests/prometheus-deployment/prometheus.yaml deleted file mode 100644 index 333b4dc4e..000000000 --- a/deployment/kubernetes-manifests/prometheus-deployment/prometheus.yaml +++ /dev/null @@ -1,64 +0,0 @@ -apiVersion: apps/v1 -kind: Deployment -metadata: - labels: - name: prometheus-deployment - name: prometheus - namespace: kube-system -spec: - replicas: 1 - selector: - matchLabels: - app: prometheus - template: - metadata: - labels: - app: prometheus - spec: - containers: - - image: prom/prometheus:v2.0.0 - name: prometheus - command: - - "/bin/prometheus" - args: - - "--config.file=/etc/prometheus/prometheus.yml" - - "--storage.tsdb.path=/prometheus" - - "--storage.tsdb.retention=24h" - ports: - - containerPort: 9090 - protocol: TCP - volumeMounts: - - mountPath: "/prometheus" - name: data - - mountPath: "/etc/prometheus" - name: config-volume - resources: - requests: - cpu: 100m - memory: 100Mi - limits: - cpu: 500m - memory: 2500Mi - serviceAccountName: prometheus - volumes: - - name: data - emptyDir: {} - - name: config-volume - configMap: - name: prometheus-config ---- -kind: Service -apiVersion: v1 -metadata: - labels: - app: prometheus - name: prometheus - namespace: kube-system -spec: - type: NodePort - ports: - - port: 9090 - targetPort: 9090 - nodePort: 30003 - selector: - app: prometheus diff --git a/deployment/kubernetes-manifests/prometheus-deployment/rbac.yaml b/deployment/kubernetes-manifests/prometheus-deployment/rbac.yaml deleted file mode 100644 index b79eef7aa..000000000 --- a/deployment/kubernetes-manifests/prometheus-deployment/rbac.yaml +++ /dev/null @@ -1,39 +0,0 @@ -apiVersion: rbac.authorization.k8s.io/v1 -kind: ClusterRole -metadata: - name: prometheus -rules: -- apiGroups: [""] - resources: - - nodes - - nodes/proxy - - services - - endpoints - - pods - verbs: ["get", "list", "watch"] -- apiGroups: - - extensions - resources: - - ingresses - verbs: ["get", "list", "watch"] -- nonResourceURLs: ["/metrics"] - verbs: ["get"] ---- -apiVersion: v1 -kind: ServiceAccount -metadata: - name: prometheus - namespace: kube-system ---- -apiVersion: rbac.authorization.k8s.io/v1 -kind: ClusterRoleBinding -metadata: - name: prometheus -roleRef: - apiGroup: rbac.authorization.k8s.io - kind: ClusterRole - name: prometheus -subjects: -- kind: ServiceAccount - name: prometheus - namespace: kube-system diff --git a/deployment/kubernetes-manifests/prometheus/alert-manager-configmap.yml b/deployment/kubernetes-manifests/prometheus/alert-manager-configmap.yml new file mode 100644 index 000000000..0fde3fa99 --- /dev/null +++ b/deployment/kubernetes-manifests/prometheus/alert-manager-configmap.yml @@ -0,0 +1,31 @@ +apiVersion: v1 +kind: ConfigMap +metadata: + name: alertmanager-config + namespace: kube-system + labels: + kubernetes.io/cluster-service: "true" + addonmanager.kubernetes.io/mode: EnsureExists +data: + alertmanager.yml: | + global: + resolve_timeout: 5m + receivers: + - name: default-receiver + email_configs: + - to: 'xxxxxxxxxxxx@126.com' + - name: alertsnitch + webhook_configs: + - url: http://alertsnitch:9567/webhook + + route: + group_interval: 5m # 如果组内内容不变化,合并为一条警报信息,5m后发送。 + group_wait: 30s # 在组内等待所配置的时间,如果同组内,30秒内出现相同报警,在一个组内出现。 + receiver: default-receiver + repeat_interval: 24h # 发送报警间隔,如果指定时间内没有修复,则重新发送报警。 + group_by: [alertname] # 报警分组 + routes: + - receiver: default-receiver + continue: true + - receiver: alertsnitch + continue: true diff --git a/deployment/kubernetes-manifests/prometheus/alert-manager.yml b/deployment/kubernetes-manifests/prometheus/alert-manager.yml new file mode 100644 index 000000000..5adaa9d3f --- /dev/null +++ b/deployment/kubernetes-manifests/prometheus/alert-manager.yml @@ -0,0 +1,77 @@ +apiVersion: apps/v1 +kind: Deployment +metadata: + name: alertmanager + namespace: kube-system + labels: + k8s-app: alertmanager + kubernetes.io/cluster-service: "true" + addonmanager.kubernetes.io/mode: Reconcile + version: v0.14.0 +spec: + replicas: 1 + selector: + matchLabels: + k8s-app: alertmanager + version: v0.14.0 + template: + metadata: + labels: + k8s-app: alertmanager + version: v0.14.0 + annotations: + scheduler.alpha.kubernetes.io/critical-pod: '' + spec: + priorityClassName: system-cluster-critical + containers: + - name: prometheus-alertmanager + image: "prom/alertmanager:v0.14.0" + imagePullPolicy: "IfNotPresent" + args: + - --config.file=/etc/config/alertmanager.yml + - --storage.path=/data + - --web.external-url=/ + ports: + - containerPort: 9093 + readinessProbe: + httpGet: + path: /#/status + port: 9093 + initialDelaySeconds: 30 + timeoutSeconds: 30 + volumeMounts: + - name: config-volume + mountPath: /etc/config + resources: + limits: + cpu: 10m + memory: 50Mi + requests: + cpu: 10m + memory: 50Mi + volumes: + - name: config-volume + configMap: + name: alertmanager-config + - name: timezone + hostPath: + path: /usr/share/zoneinfo/Asia/Shanghai + +--- +apiVersion: v1 +kind: Service +metadata: + name: alertmanager + namespace: kube-system + labels: + kubernetes.io/cluster-service: "true" + addonmanager.kubernetes.io/mode: Reconcile + kubernetes.io/name: "Alertmanager" +spec: + type: NodePort + ports: + - port: 9093 + targetPort: 9093 + nodePort: 30004 + selector: + k8s-app: alertmanager diff --git a/deployment/kubernetes-manifests/prometheus/alertsnitch.yml b/deployment/kubernetes-manifests/prometheus/alertsnitch.yml new file mode 100644 index 000000000..1014acd2d --- /dev/null +++ b/deployment/kubernetes-manifests/prometheus/alertsnitch.yml @@ -0,0 +1,99 @@ +apiVersion: apps/v1 +kind: Deployment +metadata: + name: alertsnitch-mysql + namespace: kube-system +spec: + selector: + matchLabels: + app: alertsnitch-mysql + replicas: 1 + template: + metadata: + labels: + app: alertsnitch-mysql + spec: + containers: + - name: alertsnitch-mysql + image: 569107519/alertsnitch-mysql:v1.0 + imagePullPolicy: IfNotPresent + env: + - name: MYSQL_ROOT_PASSWORD + value: root + - name: MYSQL_DATABASE + value: alertsnitch + ports: + - containerPort: 3306 + resources: + requests: + cpu: 50m + memory: 100Mi + +--- + +apiVersion: v1 +kind: Service +metadata: + name: alertsnitch-mysql + namespace: kube-system +spec: + ports: + - port: 3306 + selector: + app: alertsnitch-mysql + +--- + +apiVersion: apps/v1 +kind: Deployment +metadata: + name: alertsnitch + namespace: kube-system +spec: + replicas: 1 + selector: + matchLabels: + app.kubernetes.io/name: alertsnitch + template: + metadata: + labels: + app.kubernetes.io/name: alertsnitch + spec: + containers: + - image: registry.gitlab.com/yakshaving.art/alertsnitch + name: alertsnitch + ports: + - containerPort: 9567 + name: http + env: + - name: ALERTSNITCH_BACKEND + value: mysql + - name: ALERTSNITCH_DSN + value: root:root@tcp(alertsnitch-mysql:3306)/alertsnitch + readinessProbe: + httpGet: + path: /-/ready + port: 9567 + initialDelaySeconds: 30 + periodSeconds: 10 + livenessProbe: + httpGet: + path: /-/health + port: 9567 + initialDelaySeconds: 60 + periodSeconds: 10 + +--- + +apiVersion: v1 +kind: Service +metadata: + name: alertsnitch + namespace: kube-system +spec: + ports: + - name: http + port: 9567 + targetPort: http + selector: + app.kubernetes.io/name: alertsnitch diff --git a/deployment/kubernetes-manifests/prometheus-deployment/grafana.yaml b/deployment/kubernetes-manifests/prometheus/grafana.yml similarity index 93% rename from deployment/kubernetes-manifests/prometheus-deployment/grafana.yaml rename to deployment/kubernetes-manifests/prometheus/grafana.yml index 5bf5d6dc3..072736321 100644 --- a/deployment/kubernetes-manifests/prometheus-deployment/grafana.yaml +++ b/deployment/kubernetes-manifests/prometheus/grafana.yml @@ -42,6 +42,9 @@ spec: - name: grafana-persistent-storage mountPath: /var volumes: + - name: timezone + hostPath: + path: /usr/share/zoneinfo/Asia/Shanghai - name: grafana-persistent-storage emptyDir: {} diff --git a/deployment/kubernetes-manifests/prometheus/node-exporter.yml b/deployment/kubernetes-manifests/prometheus/node-exporter.yml new file mode 100644 index 000000000..827d5951f --- /dev/null +++ b/deployment/kubernetes-manifests/prometheus/node-exporter.yml @@ -0,0 +1,64 @@ +--- +kind: Service +apiVersion: v1 +metadata: + name: node-exporter + namespace: kube-system + annotations: + prometheus.io/scrape: 'true' + prometheus.io/port: '9100' +spec: + selector: + app: node-exporter + ports: + - name: node-exporter + protocol: TCP + port: 9100 + targetPort: 9100 +--- +apiVersion: apps/v1 +kind: DaemonSet +metadata: + name: node-exporter + namespace: kube-system +spec: + revisionHistoryLimit: 10 + selector: + matchLabels: + app: node-exporter + template: + metadata: + annotations: + prometheus.io/path: metrics + prometheus.io/port: "9100" + prometheus.io/scrape: "true" + labels: + app: node-exporter + name: node-exporter + spec: + containers: + - image: prom/node-exporter + imagePullPolicy: IfNotPresent + name: node-exporter + ports: + - containerPort: 9100 + hostPort: 9100 + name: scrape + protocol: TCP + resources: {} + terminationMessagePath: /dev/termination-log + terminationMessagePolicy: File + dnsPolicy: ClusterFirst + hostNetwork: true + hostPID: true + restartPolicy: Always + terminationGracePeriodSeconds: 30 + tolerations: + - effect: NoSchedule + key: node-role.kubernetes.io/master + operator: Exists + volumes: + - hostPath: + path: /usr/share/zoneinfo/Asia/Shanghai + type: "" + name: timezone diff --git a/deployment/kubernetes-manifests/prometheus/prometheus-configmap.yml b/deployment/kubernetes-manifests/prometheus/prometheus-configmap.yml new file mode 100644 index 000000000..cfe5d95b2 --- /dev/null +++ b/deployment/kubernetes-manifests/prometheus/prometheus-configmap.yml @@ -0,0 +1,189 @@ +apiVersion: v1 +kind: ConfigMap +metadata: + name: prometheus-config + namespace: kube-system + labels: + kubernetes.io/cluster-service: "true" + addonmanager.kubernetes.io/mode: EnsureExists +data: + prometheus.yml: | + rule_files: + - /etc/config/rules/*.rules + + scrape_configs: + - job_name: prometheus + static_configs: + - targets: + - localhost:9090 + + - job_name: 'node-exporter' + kubernetes_sd_configs: + - role: endpoints + relabel_configs: + - source_labels: [__meta_kubernetes_endpoints_name] + regex: 'node-exporter' + action: keep + + - job_name: kubernetes-apiservers + kubernetes_sd_configs: + - role: endpoints + relabel_configs: + - action: keep + regex: default;kubernetes;https + source_labels: + - __meta_kubernetes_namespace + - __meta_kubernetes_service_name + - __meta_kubernetes_endpoint_port_name + scheme: https + tls_config: + ca_file: /var/run/secrets/kubernetes.io/serviceaccount/ca.crt + insecure_skip_verify: true + bearer_token_file: /var/run/secrets/kubernetes.io/serviceaccount/token + + - job_name: kubernetes-nodes-kubelet + kubernetes_sd_configs: + - role: node + relabel_configs: + - action: labelmap + regex: __meta_kubernetes_node_label_(.+) + scheme: https + tls_config: + ca_file: /var/run/secrets/kubernetes.io/serviceaccount/ca.crt + insecure_skip_verify: true + bearer_token_file: /var/run/secrets/kubernetes.io/serviceaccount/token + + - job_name: kubernetes-nodes-cadvisor + kubernetes_sd_configs: + - role: node + relabel_configs: + - action: labelmap + regex: __meta_kubernetes_node_label_(.+) + - target_label: __metrics_path__ + replacement: /metrics/cadvisor + scheme: https + tls_config: + ca_file: /var/run/secrets/kubernetes.io/serviceaccount/ca.crt + insecure_skip_verify: true + bearer_token_file: /var/run/secrets/kubernetes.io/serviceaccount/token + + - job_name: kubernetes-service-endpoints + kubernetes_sd_configs: + - role: endpoints + relabel_configs: + - action: keep + regex: true + source_labels: + - __meta_kubernetes_service_annotation_prometheus_io_scrape + - action: replace + regex: (https?) + source_labels: + - __meta_kubernetes_service_annotation_prometheus_io_scheme + target_label: __scheme__ + - action: replace + regex: (.+) + source_labels: + - __meta_kubernetes_service_annotation_prometheus_io_path + target_label: __metrics_path__ + - action: replace + regex: ([^:]+)(?::\d+)?;(\d+) + replacement: $1:$2 + source_labels: + - __address__ + - __meta_kubernetes_service_annotation_prometheus_io_port + target_label: __address__ + - action: labelmap + regex: __meta_kubernetes_service_label_(.+) + - action: replace + source_labels: + - __meta_kubernetes_namespace + target_label: kubernetes_namespace + - action: replace + source_labels: + - __meta_kubernetes_service_name + target_label: kubernetes_name + + - job_name: kubernetes-services + kubernetes_sd_configs: + - role: service + metrics_path: /probe + params: + module: + - http_2xx + relabel_configs: + - action: keep + regex: true + source_labels: + - __meta_kubernetes_service_annotation_prometheus_io_probe + - source_labels: + - __address__ + target_label: __param_target + - replacement: blackbox + target_label: __address__ + - source_labels: + - __param_target + target_label: instance + - action: labelmap + regex: __meta_kubernetes_service_label_(.+) + - source_labels: + - __meta_kubernetes_namespace + target_label: kubernetes_namespace + - source_labels: + - __meta_kubernetes_service_name + target_label: kubernetes_name + + - job_name: kubernetes-pods + kubernetes_sd_configs: + - role: pod + relabel_configs: + - action: keep + regex: true + source_labels: + - __meta_kubernetes_pod_annotation_prometheus_io_scrape + - action: replace + regex: (.+) + source_labels: + - __meta_kubernetes_pod_annotation_prometheus_io_path + target_label: __metrics_path__ + - action: replace + regex: ([^:]+)(?::\d+)?;(\d+) + replacement: $1:$2 + source_labels: + - __address__ + - __meta_kubernetes_pod_annotation_prometheus_io_port + target_label: __address__ + - action: labelmap + regex: __meta_kubernetes_pod_label_(.+) + - action: replace + source_labels: + - __meta_kubernetes_namespace + target_label: kubernetes_namespace + - action: replace + source_labels: + - __meta_kubernetes_pod_name + target_label: kubernetes_pod_name + alerting: + alertmanagers: + - static_configs: + - targets: ["alertmanager:9093"] + +--- + +apiVersion: v1 +kind: ConfigMap +metadata: + name: prometheus-rules + namespace: kube-system +data: + pod.rules: | + groups: + - name: kubernetes pod failures + rules: + - alert: kubernetes pod failures + expr: up == 0 + for: 5m + labels: + severity: warning + annotations: + summary: "Pod {{ $labels.kubernetes_pod_name }} down" + description: "{{ $labels.kubernetes_pod_name }} of namespace {{ $labels.kubernetes_namespace }} has been down for more than 5 minutes." diff --git a/deployment/kubernetes-manifests/prometheus/prometheus.yml b/deployment/kubernetes-manifests/prometheus/prometheus.yml new file mode 100644 index 000000000..23bbdb83a --- /dev/null +++ b/deployment/kubernetes-manifests/prometheus/prometheus.yml @@ -0,0 +1,329 @@ +apiVersion: rbac.authorization.k8s.io/v1 +kind: ClusterRoleBinding +metadata: + labels: + app.kubernetes.io/name: kube-state-metrics + app.kubernetes.io/version: v1.9.8 + name: kube-state-metrics +roleRef: + apiGroup: rbac.authorization.k8s.io + kind: ClusterRole + name: kube-state-metrics +subjects: +- kind: ServiceAccount + name: kube-state-metrics + namespace: kube-system + +--- + +apiVersion: rbac.authorization.k8s.io/v1 +kind: ClusterRole +metadata: + labels: + app.kubernetes.io/name: kube-state-metrics + app.kubernetes.io/version: v1.9.8 + name: kube-state-metrics +rules: +- apiGroups: + - "" + resources: + - configmaps + - secrets + - nodes + - pods + - services + - resourcequotas + - replicationcontrollers + - limitranges + - persistentvolumeclaims + - persistentvolumes + - namespaces + - endpoints + verbs: + - list + - watch +- apiGroups: + - extensions + resources: + - daemonsets + - deployments + - replicasets + - ingresses + verbs: + - list + - watch +- apiGroups: + - apps + resources: + - statefulsets + - daemonsets + - deployments + - replicasets + verbs: + - list + - watch +- apiGroups: + - batch + resources: + - cronjobs + - jobs + verbs: + - list + - watch +- apiGroups: + - autoscaling + resources: + - horizontalpodautoscalers + verbs: + - list + - watch +- apiGroups: + - authentication.k8s.io + resources: + - tokenreviews + verbs: + - create +- apiGroups: + - authorization.k8s.io + resources: + - subjectaccessreviews + verbs: + - create +- apiGroups: + - policy + resources: + - poddisruptionbudgets + verbs: + - list + - watch +- apiGroups: + - certificates.k8s.io + resources: + - certificatesigningrequests + verbs: + - list + - watch +- apiGroups: + - storage.k8s.io + resources: + - storageclasses + - volumeattachments + verbs: + - list + - watch +- apiGroups: + - admissionregistration.k8s.io + resources: + - mutatingwebhookconfigurations + - validatingwebhookconfigurations + verbs: + - list + - watch +- apiGroups: + - networking.k8s.io + resources: + - networkpolicies + verbs: + - list + - watch + +--- + +apiVersion: apps/v1 +kind: Deployment +metadata: + labels: + app.kubernetes.io/name: kube-state-metrics + app.kubernetes.io/version: v1.9.8 + name: kube-state-metrics + namespace: kube-system +spec: + replicas: 1 + selector: + matchLabels: + app.kubernetes.io/name: kube-state-metrics + template: + metadata: + labels: + app.kubernetes.io/name: kube-state-metrics + app.kubernetes.io/version: v1.9.8 + spec: + containers: + - image: quay.io/coreos/kube-state-metrics:v1.9.8 + livenessProbe: + httpGet: + path: /healthz + port: 8080 + initialDelaySeconds: 5 + timeoutSeconds: 5 + name: kube-state-metrics + ports: + - containerPort: 8080 + name: http-metrics + - containerPort: 8081 + name: telemetry + readinessProbe: + httpGet: + path: / + port: 8081 + initialDelaySeconds: 5 + timeoutSeconds: 5 + nodeSelector: + kubernetes.io/os: linux + serviceAccountName: kube-state-metrics + +--- + +apiVersion: v1 +kind: ServiceAccount +metadata: + labels: + app.kubernetes.io/name: kube-state-metrics + app.kubernetes.io/version: v1.9.8 + name: kube-state-metrics + namespace: kube-system + +--- + +apiVersion: v1 +kind: Service +metadata: + labels: + app.kubernetes.io/name: kube-state-metrics + app.kubernetes.io/version: v1.9.8 + name: kube-state-metrics + namespace: kube-system + annotations: + prometheus.io/scrape: "true" +spec: + clusterIP: None + ports: + - name: http-metrics + port: 8080 + targetPort: http-metrics + - name: telemetry + port: 8081 + targetPort: telemetry + selector: + app.kubernetes.io/name: kube-state-metrics + +--- + +apiVersion: v1 +kind: ServiceAccount +metadata: + name: prometheus + namespace: kube-system + labels: + kubernetes.io/cluster-service: "true" + addonmanager.kubernetes.io/mode: Reconcile +--- +apiVersion: rbac.authorization.k8s.io/v1 +kind: ClusterRole +metadata: + name: prometheus + labels: + kubernetes.io/cluster-service: "true" + addonmanager.kubernetes.io/mode: Reconcile +rules: + - apiGroups: [""] + resources: ["nodes", "nodes/metrics", "services", "endpoints", "pods"] + verbs: ["get", "list", "watch"] + - apiGroups: [""] + resources: ["configmaps"] + verbs: ["get"] + - nonResourceURLs: ["/metrics"] + verbs: ["get"] +--- +apiVersion: rbac.authorization.k8s.io/v1 +kind: ClusterRoleBinding +metadata: + name: prometheus + labels: + kubernetes.io/cluster-service: "true" + addonmanager.kubernetes.io/mode: Reconcile +roleRef: + apiGroup: rbac.authorization.k8s.io + kind: ClusterRole + name: prometheus +subjects: +- kind: ServiceAccount + name: prometheus + namespace: kube-system + +--- + +apiVersion: apps/v1 +kind: Deployment +metadata: + labels: + name: prometheus-deployment + name: prometheus + namespace: kube-system +spec: + replicas: 1 + selector: + matchLabels: + app: prometheus + template: + metadata: + labels: + app: prometheus + spec: + containers: + - image: prom/prometheus:v2.0.0 + imagePullPolicy: IfNotPresent + name: prometheus + command: + - "/bin/prometheus" + args: + - "--config.file=/etc/prometheus/prometheus.yml" + - "--storage.tsdb.path=/prometheus" + - "--storage.tsdb.retention=24h" + - "--web.enable-lifecycle" + ports: + - containerPort: 9090 + protocol: TCP + volumeMounts: + - mountPath: "/prometheus" + name: data + - mountPath: "/etc/prometheus" + name: config-volume + - mountPath: "/etc/config/rules" + name: prometheus-rules + resources: + requests: + cpu: 100m + memory: 100Mi + limits: + cpu: 200m + memory: 1000Mi + serviceAccountName: prometheus + volumes: + - name: timezone + hostPath: + path: /usr/share/zoneinfo/Asia/Shanghai + - name: prometheus-rules + configMap: + name: prometheus-rules + - name: data + emptyDir: {} + - name: config-volume + configMap: + name: prometheus-config +--- +kind: Service +apiVersion: v1 +metadata: + labels: + app: prometheus + name: prometheus + namespace: kube-system +spec: + type: NodePort + ports: + - port: 9090 + targetPort: 9090 + nodePort: 30003 + selector: + app: prometheus diff --git a/deployment/kubernetes-manifests/quickstart-k8s/charts/mysql/Chart.yaml b/deployment/kubernetes-manifests/quickstart-k8s/charts/mysql/Chart.yaml new file mode 100644 index 000000000..c9b10c7f6 --- /dev/null +++ b/deployment/kubernetes-manifests/quickstart-k8s/charts/mysql/Chart.yaml @@ -0,0 +1,38 @@ +apiVersion: v2 +name: mysql +description: High Availability MySQL Cluster, Open Source. +home: https://github.com/radondb/radondb-mysql-kubernetes.git + +# A chart can be either an 'application' or a 'library' chart. +# +# Application charts are a collection of templates that can be packaged into versioned archives +# to be deployed. +# +# Library charts provide useful utilities or functions for the chart developer. They're included as +# a dependency of application charts to inject those utilities and functions into the rendering +# pipeline. Library charts do not define any templates and therefore cannot be deployed. +type: application + +# This is the chart version. This version number should be incremented each time you make changes +# to the chart and its templates, including the app version. +# Versions are expected to follow Semantic Versioning (https://semver.org/) +version: 1.0.0 + +# This is the version number of the application being deployed. This version number should be +# incremented each time you make changes to the application. Versions are not expected to +# follow Semantic Versioning. They should reflect the version the application is using. +# It is recommended to use it with quotes. +appVersion: "5.7.34" + +kubeVersion: ">=1.17.0-0" +sources: +- https://github.com/radondb/radondb-mysql-kubernetes +keywords: +- radondb-mysql-kubernetes +- MySQL HA +- database +- kubernetes + +icon: https://xenondb.pek3b.qingstor.com/icons/radondb-mysql.svg +annotations: + "app.kubesphere.io/category": "Database & Cache" diff --git a/deployment/kubernetes-manifests/quickstart-k8s/charts/mysql/README.md b/deployment/kubernetes-manifests/quickstart-k8s/charts/mysql/README.md new file mode 100644 index 000000000..ca096606a --- /dev/null +++ b/deployment/kubernetes-manifests/quickstart-k8s/charts/mysql/README.md @@ -0,0 +1,187 @@ +# RadonDB MySQL + +RadonDB MySQL is an open-source, cloud-native, High-Availability cluster solutions based on MySQL. + +# Github + +https://github.com/radondb/radondb-mysql-kubernetes + +# Features + +- High availability MySQL database + - Non-centralized automatic leader election + - Second level switch leader to follower + - Strongly consistent data for cluster switching +- Cluster management +- Monitoring and alerting +- Logs +- Account management + +# Introduction + +This chart bootstraps a single leader and multiple followers [MySQL](https://MySQL.org) deployment on a [Kubernetes](http://kubernetes.io) cluster using the [Helm](https://helm.sh) package manager. + +# Prerequisites + +- Kubernetes 1.10+ with Beta APIs enabled +- PV provisioner support in the underlying infrastructure +- Helm 2.11+ or Helm 3.0-beta3+ + +# Installing the Chart + +To install the chart with the release name `my-release`: + +```bash +## For Helm v2 +$ helm install . --name my-release + +## For Helm v3 +$ helm install --name my-release . +``` + +The command deploys MySQL cluster on the Kubernetes cluster in the default configuration. The [configuration](#configuration) section lists the parameters that can be configured during installation. + +# Uninstall + +To uninstall/delete the `my-release` deployment: + +```bash +$ helm delete my-release +``` + +To delete the pvc: + +``` +kubectl delete pvc data-my-release-radondb-mysql-0 +kubectl delete pvc data-my-release-radondb-mysql-1 +kubectl delete pvc data-my-release-radondb-mysql-2 +``` + +The commands remove all the Kubernetes components associated with the chart and deletes the release completely. + +# Configuration + +The following table lists the configurable parameters of the RadonDB MySQL chart and their default values. + +| Parameter | Description | Default | +| -------------------------------------------- | ------------------------------------------------------------------------------------------------- | ------------------------------------------- | +| `imagePullPolicy` | Image pull policy | `IfNotPresent` | +| `fullnameOverride` | Custom fullname override for the chart | | +| `nameOverride` | Custom name override for the chart | | +| `replicaCount` | The number of pods | `3` | +| `busybox.image` | `busybox` image repository. | `busybox` | +| `busybox.tag` | `busybox` image tag. | `1.32` | +| `mysql.image` | `mysql` image repository. | `radondb/percona` | +| `mysql.tag` | `mysql` image tag. | `5.7.34` | +| `mysql.allowEmptyRootPassword` | If set true, allow a empty root password. | `true` | +| `mysql.mysqlRootPassword` | Password for the `root` user. | | +| `mysql.mysqlReplicationPassword` | Password for the `qc_repl` user. | `Repl_123`, random 12 characters if not set | +| `mysql.mysqlUser` | Username of new user to create. | `qingcloud` | +| `mysql.mysqlPassword` | Password for the new user. | `Qing@123`, random 12 characters if not set | +| `mysql.mysqlDatabase` | Name for new database to create. | `qingcloud` | +| `mysql.initTokudb` | Install tokudb engine. | `false` | +| `mysql.args` | Additional arguments to pass to the MySQL container. | `[]` | +| `mysqlconfigFiles.node.cnf` | Mysql configuration file | See `values.yaml` | +| `mysql.livenessProbe.initialDelaySeconds` | Delay before mysql liveness probe is initiated | 30 | +| `mysql.livenessProbe.periodSeconds` | How often to perform the mysql probe | 10 | +| `mysql.livenessProbe.timeoutSeconds` | When the mysql probe times out | 5 | +| `mysql.livenessProbe.successThreshold` | Minimum consecutive successes for the mysql probe to be considered successful after having failed.| 1 | +| `mysql.livenessProbe.failureThreshold` | Minimum consecutive failures for the mysql probe to be considered failed after having succeeded. | 3 | +| `mysql.readinessProbe.initialDelaySeconds` | Delay before mysql readiness probe is initiated | 10 | +| `mysql.readinessProbe.periodSeconds` | How often to perform the mysql probe | 10 | +| `mysql.readinessProbe.timeoutSeconds` | When the mysql probe times out | 1 | +| `mysql.readinessProbe.successThreshold` | Minimum consecutive successes for the mysql probe to be considered successful after having failed.| 1 | +| `mysql.readinessProbe.failureThreshold` | Minimum consecutive failures for the mysql probe to be considered failed after having succeeded. | 3 | +| `mysql.extraEnvVars` | Additional environment variables as a string to be passed to the `tpl` function | | +| `mysql.resources` | CPU/Memory resource requests/limits for mysql. | Memory: `256Mi`, CPU: `100m` | +| `xenon.image` | `xenon` image repository. | `radondb/xenon` | +| `xenon.tag` | `xenon` image tag. | `1.1.5-alpha` | +| `xenon.args` | Additional arguments to pass to the xenon container. | `[]` | +| `xenon.extraEnvVars` | Additional environment variables as a string to be passed to the `tpl` function | | +| `xenon.livenessProbe.initialDelaySeconds` | Delay before xenon liveness probe is initiated | 30 | +| `xenon.livenessProbe.periodSeconds` | How often to perform the xenon probe | 10 | +| `xenon.livenessProbe.timeoutSeconds` | When the xenon probe times out | 5 | +| `xenon.livenessProbe.successThreshold` | Minimum consecutive successes for xenon probe to be considered successful after having failed. | 1 | +| `xenon.livenessProbe.failureThreshold` | Minimum consecutive failures for the xenon probe to be considered failed after having succeeded. | 3 | +| `xenon.readinessProbe.initialDelaySeconds` | Delay before xenon readiness probe is initiated | 10 | +| `xenon.readinessProbe.periodSeconds` | How often to perform the xenon probe | 10 | +| `xenon.readinessProbe.timeoutSeconds` | When the xenon probe times out | 1 | +| `xenon.readinessProbe.successThreshold` | Minimum consecutive successes for xenon probe to be considered successful after having failed. | 1 | +| `xenon.readinessProbe.failureThreshold` | Minimum consecutive failures for the xenon probe to be considered failed after having succeeded. | 3 | +| `xenon.resources` | CPU/Memory resource requests/limits for xenon. | Memory: `128Mi`, CPU: `50m` | +| `metrics.enabled` | Start a side-car prometheus exporter | `true` | +| `metrics.image` | Exporter image | `prom/mysqld-exporter` | +| `metrics.tag` | Exporter image | `v0.12.1` | +| `metrics.annotations` | Exporter annotations | `{}` | +| `metrics.livenessProbe.initialDelaySeconds` | Delay before metrics liveness probe is initiated | 15 | +| `metrics.livenessProbe.timeoutSeconds` | When the probe times out | 5 | +| `metrics.readinessProbe.initialDelaySeconds` | Delay before metrics readiness probe is initiated | 5 | +| `metrics.readinessProbe.timeoutSeconds` | When the probe times out | 1 | +| `metrics.serviceMonitor.enabled` | Set this to `true` to create ServiceMonitor for Prometheus operator | `true` | +| `metrics.serviceMonitor.namespace` | Optional namespace in which to create ServiceMonitor | `nil` | +| `metrics.serviceMonitor.interval` | Scrape interval. If not set, the Prometheus default scrape interval is used | 10s | +| `metrics.serviceMonitor.scrapeTimeout` | Scrape timeout. If not set, the Prometheus default scrape timeout is used | `nil` | +| `metrics.serviceMonitor.selector` | Default to kube-prometheus install, but should be set according to Prometheus install | `{ prometheus: kube-prometheus }` | +| `slowLogTail` | If set to `true` runs a container to tail mysql-slow.log in the pod | `true` | +| `resources` | Resource requests/limit | Memory: `32Mi`, CPU: `10m` | +| `service.annotations` | Kubernetes annotations for service | {} | +| `service.type` | Kubernetes service type | NodePort | +| `service.loadBalancerIP` | The service loadBalancer IP | `""` | +| `service.nodePort` | The service nodePort | `""` | +| `service.clusterIP` | The service clusterIP | `""` | +| `service.port` | The service port | `3306` | +| `rbac.create` | If true, create & use RBAC resources | `true` | +| `serviceAccount.create` | Specifies whether a ServiceAccount should be created | `true` | +| `serviceAccount.name` | The name of the ServiceAccount to use | | +| `persistence.enabled` | Create a volume to store data | true | +| `persistence.storageClass` | Type of persistent volume claim | nil | +| `persistence.accessMode` | Access mode | ReadWriteOnce | +| `persistence.size` | Size of persistent volume claim | 10Gi | +| `persistence.annotations` | Persistent Volume annotations | {} | +| `priorityClassName` | Set pod priorityClassName | `{}` | +| `schedulerName` | Name of the k8s scheduler (other than default) | `nil` | +| `statefulsetAnnotations` | Map of annotations for statefulset | `{}` | +| `podAnnotations` | Map of annotations to add to the pods | `{}` | +| `podLabels` | Map of labels to add to the pods | `{}` | + +Specify each parameter using the `--set key=value[,key=value]` argument to `helm install`. For example, + +```bash +$ cd charts +$ helm install my-release \ + --set mysql.mysqlUser=my-user,mysql.mysqlPassword=my-password,mysql.database=my-database . +``` + +The above command creates a standard database user named `my-user`, with the password `my-password`, who has access to a database named `my-database`. + +Alternatively, a YAML file that specifies the values for the parameters can be provided while installing the chart. For example, + +```bash +$ cd charts +$ helm install my-release -f values.yaml . +``` + +# Persistence + +The [MySQL](https://hub.docker.com/repository/docker/radondb/percona) image stores the MySQL data and configurations at the `/var/lib/mysql` path of the container. + +By default a PersistentVolumeClaim is created and mounted into the directory. In order to disable this functionality, you can change the `values.yaml` to disable persistence and use an emptyDir instead. + +> *"An emptyDir volume is first created when a Pod is assigned to a Node, and exists as long as that Pod is running on that node. When a Pod is removed from a node for any reason, the data in the emptyDir is deleted forever."* + +**Notice**: You may need to increase the value of `livenessProbe.initialDelaySeconds` when enabling persistence by using PersistentVolumeClaim from PersistentVolume with varying properties. Since its IO performance has impact on the database initialization performance. The default limit for database initialization is `60` seconds (`livenessProbe.initialDelaySeconds` + `livenessProbe.periodSeconds` * `livenessProbe.failureThreshold`). Once such initialization process takes more time than this limit, kubelet will restart the database container, which will interrupt database initialization then causing persisent data in an unusable state. + +# Custom MySQL configuration + +You can add or modify the mysql configuration on the `mysql.configFiles`. + +```yaml + configFiles: + node.cnf: | + [mysqld] + default_storage_engine=InnoDB + max_connections=65535 + + # custom mysql configuration. + expire_logs_days=7 +``` diff --git a/deployment/kubernetes-manifests/quickstart-k8s/charts/mysql/templates/.statefulset.yaml.swp b/deployment/kubernetes-manifests/quickstart-k8s/charts/mysql/templates/.statefulset.yaml.swp new file mode 100644 index 0000000000000000000000000000000000000000..58f48ada6963cbaead1cca76c01dd89007066d31 GIT binary patch literal 16384 zcmeI3Uu+yl9mltSptPkx=o3XmlZ(N2o!zz5ByCT1 zSGN7k_r0_IFr>mb{iRj$9Mu75?P|E6;N7WMm(`fex#nH`m^zqA5c0j+>mKr5gX&;GmfJ@+h@D3J1{s?{v zu7mG@tKccH3cdh71762s%*)_K@NIAo8~}U3yJ)As0@+@_lWkV|kithWCt~qQHdtb< zrjcLRq<)_rk9d$Lnk1wFYm$Yt%a5H}TROIQYHjhz^788GrK7_eFJCqZ3te*c>M$uS zv&#lek{;ZMIFHR96#@r5+)B38!sW{(JH|m8IKkn|-#lC;%PoF+h@4VL{A&-f* zBI_@##AA#4KEH4*=*5F2_`axIFM7km&88vU=4Wxzq;h-21n)-<6XXio5+NpmRSN}g^m)vRh05$WO4DX#-DuPnWiuCWx~Af>%v3DP3uv1yq9GQ! z?>T5mX;ev6xmM>&lBG!+g}YK=lM67^9JvzHHqsj^JhISB?ow$E4`b?uEGkroz_Ho@ z40u08!^NE@u{&JErWlAq=w;>CT#^MMD6-lrze6uR!@GTVy{OWTtOsFiyELXX)+@;s z%RSW86EO=NX0ed2`)uSfE7nrlfkZ8@Z3eVgW3BcgA=NU36M4P3POQ-@qjyUqR`DUv zl$IBUPHl3(AFu`4My1BwQc&h}I0@M%i^$=;LG7+Q5a!zfPJtovads@iv$odhw^cP0 zYcDy@BRt_ac;@?f70CFo40$E{RGM`AVA`_wQ9#V7mHH!N#`Y1>Q!U6>R9gBIv4C$f zl3(A}ogGA&(+RjsrY@$&RRq}g8d(M9x6>o0@-B}t`(8_Q%6IMHrcCCN_NDvwl6l@6 z5ZdcS9Bqjce+Wx40tvObx~5A z@Ky`w7p2>DlY1^&G|2}aGQVc0Nzz%DtD+p49h*p=m9Yu=YLngQB{NsUaC^aBs_CNsg^yozbZWG%q|w~n&ir`uyRM^@F1X}+a%}4MQ429xao{P zQPW`#dqQ}*)2_180et|S(|TVF*7-%Nu6xR^)pt-HI)?Oos?tFw%#ZX`vhh5J9dR7_ z&U-W&R-p^b2R)-1O2eO#UQRe2=JtISrDYX++R~*$pIUhrRkJ1jiym{zg9SCXlg_H4 zPTo=v6gxv%d}(BXz&R3PY(?=}4NId7`0jK?KT!RZY(Ot`{JzV`MDl(nW7ZjUtk-&& z3MM;p(oosayCuha88$JmU z^BKHO19K_;VabNdT_o}imSo6dpmyNvCsxyH1T3cV{V#uIw`CRFfz2IR3~20h(yGd$ z1-y4+9?8EW*27?siqZq866a-Hr`1!TTodG#3Z}t^f(y}I8)pa7f-B8B5^#m{-!*~P zVUdStxY8=i>4S-wE{&(RRZ;o}^>{I$Pc)R-L)X`y#f1y^MTmb-2iqO%_LF+-g@rW>k9$HTJ24 zJr1#erP0E)xR98dE3PSw7?z9dZw3u6;yZZ_d`LUzj51MHCV< z0n!2Q8B&!DsoyvX>qAC8BA?q-8R`RSfIU3mCSs;ifd$fw|RPf-p+Rmw#irBKG-I! zbU>L-n`5|3P^)Zl3!~&sR-sa2{pN#-^(C3jPSiC8HUROz>h0{wmu=H9Tcw}ajq>w^ LY{BzGvB>#9$Pb%$ literal 0 HcmV?d00001 diff --git a/deployment/kubernetes-manifests/quickstart-k8s/charts/mysql/templates/NOTES.txt b/deployment/kubernetes-manifests/quickstart-k8s/charts/mysql/templates/NOTES.txt new file mode 100644 index 000000000..e66794d1a --- /dev/null +++ b/deployment/kubernetes-manifests/quickstart-k8s/charts/mysql/templates/NOTES.txt @@ -0,0 +1,29 @@ +The cluster is comprised of {{ .Values.replicaCount }} pods: 1 leader and {{ sub .Values.replicaCount 1 }} followers. Each instance is accessible within the cluster through: + + .{{ template "fullname" . }} + +To connect to your database: + +1. Get mysql user `{{ .Values.mysql.mysqlUser}}`'s password: + + kubectl get secret -n {{ .Release.Namespace }} {{ template "fullname" . }} -o jsonpath="{.data.mysql-password}" | base64 --decode; echo + +2. Run an Ubuntu pod that you can use as a client: + + kubectl run ubuntu -n {{ .Release.Namespace }} --image=ubuntu:focal -it --rm --restart='Never' -- bash -il + +3. Install the mysql client: + + apt-get update && apt-get install mysql-client -y + +4. To connect to leader service in the Ubuntu pod: + + mysql -h {{ template "fullname" . }}-leader -u {{ .Values.mysql.mysqlUser }} -p + +{{- if lt 1 (.Values.replicaCount | int64) }} + +5. To connect to follower service (read-only) in the Ubuntu pod: + + mysql -h {{ template "fullname" . }}-follower -u {{ .Values.mysql.mysqlUser }} -p + +{{- end }} diff --git a/deployment/kubernetes-manifests/quickstart-k8s/charts/mysql/templates/_helpers.tpl b/deployment/kubernetes-manifests/quickstart-k8s/charts/mysql/templates/_helpers.tpl new file mode 100644 index 000000000..56954719c --- /dev/null +++ b/deployment/kubernetes-manifests/quickstart-k8s/charts/mysql/templates/_helpers.tpl @@ -0,0 +1,45 @@ +{{/* vim: set filetype=mustache: */}} +{{/* +Expand the name of the chart. +*/}} +{{- define "name" -}} +{{- default .Chart.Name .Values.nameOverride | trunc 63 | trimSuffix "-" -}} +{{- end -}} + +{{/* +Create a default fully qualified app name. +The format of host is "fullname"-0."fullname"."namespace" (podname.servicename.namespace), +and the MySQL limits the total length of master_host to 60 byte, +so the length of "fullname" must be limited to '(60-4-len(namespace))/2'. +*/}} +{{- define "fullname" -}} +{{- $length := div (sub 56 (len .Release.Namespace )) 2 | int }} +{{- if .Values.fullnameOverride -}} +{{- .Values.fullnameOverride | trunc $length | trimSuffix "-" -}} +{{- else -}} +{{- $name := default .Chart.Name .Values.nameOverride -}} +{{- if contains $name .Release.Name -}} +{{- .Release.Name | trunc $length | trimSuffix "-" -}} +{{- else -}} +{{- printf "%s-%s" .Release.Name $name | trunc $length | trimSuffix "-" -}} +{{- end -}} +{{- end -}} +{{- end -}} + +{{/* +Create the name of the service account to use +*/}} +{{- define "serviceAccountName" -}} +{{- if .Values.serviceAccount.create -}} + {{ default (include "fullname" .) .Values.serviceAccount.name }} +{{- else -}} + {{ default "default" .Values.serviceAccount.name }} +{{- end -}} +{{- end -}} + +{{/* +Create chart name and version as used by the chart label. +*/}} +{{- define "radondb-mysql.chart" -}} +{{- printf "%s-%s" .Chart.Name .Chart.Version | replace "+" "_" | trunc 63 | trimSuffix "-" -}} +{{- end -}} diff --git a/deployment/kubernetes-manifests/quickstart-k8s/charts/mysql/templates/configmap.yaml b/deployment/kubernetes-manifests/quickstart-k8s/charts/mysql/templates/configmap.yaml new file mode 100644 index 000000000..62ddcbd05 --- /dev/null +++ b/deployment/kubernetes-manifests/quickstart-k8s/charts/mysql/templates/configmap.yaml @@ -0,0 +1,38 @@ +apiVersion: v1 +kind: ConfigMap +metadata: + name: {{ template "fullname" . }} + labels: + app: {{ template "fullname" . }} + chart: {{ template "radondb-mysql.chart" . }} + release: {{ .Release.Name | quote }} + heritage: {{ .Release.Service | quote }} +data: +{{ toYaml .Values.mysql.configFiles | indent 2 }} + server-id.cnf: | + [mysqld] + server-id=@@SERVER_ID@@ + create-peers.sh: | + #!/bin/sh + set -eu + i=0 + while [ $i -lt {{ .Values.replicaCount }} ] + do + if [ $i = 0 ] + then + echo -n "{{ template "fullname" . }}-${i}.{{ template "fullname" . }}.{{ .Release.Namespace }}:8801" + else + echo -n ",{{ template "fullname" . }}-${i}.{{ template "fullname" . }}.{{ .Release.Namespace }}:8801" + fi + i=$((i+1)) + done + leader-start.sh: | + #!/usr/bin/env bash + curl -X PATCH -H "Authorization: Bearer $(cat /var/run/secrets/kubernetes.io/serviceaccount/token)" -H "Content-Type: application/json-patch+json" \ + --cacert /var/run/secrets/kubernetes.io/serviceaccount/ca.crt https://$KUBERNETES_SERVICE_HOST:$KUBERNETES_PORT_443_TCP_PORT/api/v1/namespaces/{{ .Release.Namespace }}/pods/$HOSTNAME \ + -d '[{"op": "replace", "path": "/metadata/labels/role", "value": "leader"}]' + leader-stop.sh: | + #!/usr/bin/env bash + curl -X PATCH -H "Authorization: Bearer $(cat /var/run/secrets/kubernetes.io/serviceaccount/token)" -H "Content-Type: application/json-patch+json" \ + --cacert /var/run/secrets/kubernetes.io/serviceaccount/ca.crt https://$KUBERNETES_SERVICE_HOST:$KUBERNETES_PORT_443_TCP_PORT/api/v1/namespaces/{{ .Release.Namespace }}/pods/$HOSTNAME \ + -d '[{"op": "replace", "path": "/metadata/labels/role", "value": "follower"}]' diff --git a/deployment/kubernetes-manifests/quickstart-k8s/charts/mysql/templates/rbac.yaml b/deployment/kubernetes-manifests/quickstart-k8s/charts/mysql/templates/rbac.yaml new file mode 100644 index 000000000..6af7bea27 --- /dev/null +++ b/deployment/kubernetes-manifests/quickstart-k8s/charts/mysql/templates/rbac.yaml @@ -0,0 +1,36 @@ +{{- if and .Values.serviceAccount.create .Values.rbac.create }} +apiVersion: rbac.authorization.k8s.io/v1 +kind: Role +metadata: + name: {{ template "fullname" . }} + labels: + app: {{ template "fullname" . }} + chart: {{ template "radondb-mysql.chart" . }} + release: {{ .Release.Name | quote }} + heritage: {{ .Release.Service | quote }} +rules: +- apiGroups: + - "" + resources: + - pods + verbs: + - get + - patch +--- +kind: RoleBinding +apiVersion: rbac.authorization.k8s.io/v1 +metadata: + name: {{ template "fullname" . }} + labels: + app: {{ template "fullname" . }} + chart: {{ template "radondb-mysql.chart" . }} + release: {{ .Release.Name | quote }} + heritage: {{ .Release.Service | quote }} +roleRef: + kind: Role + name: {{ template "fullname" . }} + apiGroup: rbac.authorization.k8s.io +subjects: +- kind: ServiceAccount + name: {{ template "serviceAccountName" . }} +{{- end }} diff --git a/deployment/kubernetes-manifests/quickstart-k8s/charts/mysql/templates/secrets.yaml b/deployment/kubernetes-manifests/quickstart-k8s/charts/mysql/templates/secrets.yaml new file mode 100644 index 000000000..52bb6f2bd --- /dev/null +++ b/deployment/kubernetes-manifests/quickstart-k8s/charts/mysql/templates/secrets.yaml @@ -0,0 +1,30 @@ +apiVersion: v1 +kind: Secret +metadata: + name: {{ template "fullname" . }} + labels: + app: {{ template "fullname" . }} + chart: {{ template "radondb-mysql.chart" . }} + release: {{ .Release.Name | quote }} + heritage: {{ .Release.Service | quote }} +type: Opaque +data: + {{- if not .Values.mysql.allowEmptyRootPassword }} + {{- if .Values.mysql.mysqlRootPassword }} + mysql-root-password: {{ .Values.mysql.mysqlRootPassword | b64enc | quote }} + {{- else }} + mysql-root-password: {{ randAlphaNum 12 | b64enc | quote }} + {{- end }} + {{- end }} + {{- if and .Values.mysql.mysqlUser (and (ne .Values.mysql.mysqlUser "radondb_repl") (ne .Values.mysql.mysqlUser "root")) }} + {{- if .Values.mysql.mysqlPassword }} + mysql-password: {{ .Values.mysql.mysqlPassword | b64enc | quote }} + {{- else }} + mysql-password: {{ randAlphaNum 12 | b64enc | quote }} + {{- end }} + {{- end }} + {{- if .Values.mysql.mysqlReplicationPassword }} + mysql-replication-password: {{ .Values.mysql.mysqlReplicationPassword | b64enc | quote }} + {{- else }} + mysql-replication-password: {{ randAlphaNum 12 | b64enc | quote }} + {{- end }} diff --git a/deployment/kubernetes-manifests/quickstart-k8s/charts/mysql/templates/service.yaml b/deployment/kubernetes-manifests/quickstart-k8s/charts/mysql/templates/service.yaml new file mode 100644 index 000000000..ae1ffd0b5 --- /dev/null +++ b/deployment/kubernetes-manifests/quickstart-k8s/charts/mysql/templates/service.yaml @@ -0,0 +1,109 @@ +# Headless service for stable DNS entries of StatefulSet members. +apiVersion: v1 +kind: Service +metadata: + name: {{ template "fullname" . }} + labels: + app: {{ template "fullname" . }} + chart: {{ template "radondb-mysql.chart" . }} + release: {{ .Release.Name | quote }} + heritage: {{ .Release.Service | quote }} + {{- if .Values.service.annotations }} + annotations: +{{ toYaml .Values.service.annotations | indent 4 }} + {{- end }} +spec: + ports: + - name: {{ template "fullname" . }} + port: 3306 + clusterIP: None + publishNotReadyAddresses: true + selector: + app: {{ template "fullname" . }} + release: {{ .Release.Name | quote }} +--- +# Client service for connecting to any MySQL instance for writes. +apiVersion: v1 +kind: Service +metadata: + name: {{ template "fullname" . }}-leader + labels: + app: {{ template "fullname" . }} + chart: {{ template "radondb-mysql.chart" . }} + release: {{ .Release.Name | quote }} + heritage: {{ .Release.Service | quote }} +spec: + type: {{ .Values.service.type }} + {{- if (and (eq .Values.service.type "ClusterIP") (not (empty .Values.service.clusterIP))) }} + clusterIP: {{ .Values.service.clusterIP }} + {{- end }} + {{- if (and (eq .Values.service.type "LoadBalancer") (not (empty .Values.service.loadBalancerIP))) }} + loadBalancerIP: {{ .Values.service.loadBalancerIP }} + {{- end }} + ports: + - name: mysql + port: {{ .Values.service.port }} + targetPort: mysql + {{- if .Values.service.nodePort }} + nodePort: {{ .Values.service.nodePort }} + {{- end }} + selector: + app: {{ template "fullname" . }} + release: {{ .Release.Name | quote }} + role: leader +{{- if lt 1 (.Values.replicaCount | int64) }} +--- +# Client service for connecting to any MySQL instance for reads. +apiVersion: v1 +kind: Service +metadata: + name: {{ template "fullname" . }}-follower + labels: + app: {{ template "fullname" . }} + chart: {{ template "radondb-mysql.chart" . }} + release: {{ .Release.Name | quote }} + heritage: {{ .Release.Service | quote }} +spec: + type: {{ .Values.service.type }} + {{- if (and (eq .Values.service.type "ClusterIP") (not (empty .Values.service.clusterIP))) }} + clusterIP: {{ .Values.service.clusterIP }} + {{- end }} + {{- if (and (eq .Values.service.type "LoadBalancer") (not (empty .Values.service.loadBalancerIP))) }} + loadBalancerIP: {{ .Values.service.loadBalancerIP }} + {{- end }} + ports: + - name: mysql + port: {{ .Values.service.port }} + targetPort: mysql + {{- if .Values.service.nodePort }} + nodePort: {{ .Values.service.nodePort }} + {{- end }} + selector: + app: {{ template "fullname" . }} + release: {{ .Release.Name | quote }} + role: follower +{{- end }} +{{ if .Values.metrics.enabled }} +--- +apiVersion: v1 +kind: Service +metadata: + name: "{{ template "fullname" . }}-metrics" + labels: + app: {{ template "fullname" . }} + chart: {{ template "radondb-mysql.chart" . }} + release: {{ .Release.Name | quote }} + heritage: {{ .Release.Service | quote }} + {{- if .Values.metrics.annotations }} + annotations: +{{ toYaml .Values.metrics.annotations | indent 4 }} + {{- end }} +spec: + clusterIP: None + ports: + - name: metrics + port: 9104 + selector: + app: {{ template "fullname" . }} + release: {{ .Release.Name | quote }} +{{ end }} diff --git a/deployment/kubernetes-manifests/quickstart-k8s/charts/mysql/templates/serviceaccount.yaml b/deployment/kubernetes-manifests/quickstart-k8s/charts/mysql/templates/serviceaccount.yaml new file mode 100644 index 000000000..80fca2373 --- /dev/null +++ b/deployment/kubernetes-manifests/quickstart-k8s/charts/mysql/templates/serviceaccount.yaml @@ -0,0 +1,11 @@ +{{- if .Values.serviceAccount.create -}} +apiVersion: v1 +kind: ServiceAccount +metadata: + name: {{ template "fullname" . }} + labels: + app: {{ template "fullname" . }} + chart: {{ template "radondb-mysql.chart" . }} + release: {{ .Release.Name | quote }} + heritage: {{ .Release.Service | quote }} +{{- end -}} diff --git a/deployment/kubernetes-manifests/quickstart-k8s/charts/mysql/templates/servicemonitor.yaml b/deployment/kubernetes-manifests/quickstart-k8s/charts/mysql/templates/servicemonitor.yaml new file mode 100644 index 000000000..072144c7c --- /dev/null +++ b/deployment/kubernetes-manifests/quickstart-k8s/charts/mysql/templates/servicemonitor.yaml @@ -0,0 +1,27 @@ +{{ if and .Values.metrics.enabled .Values.metrics.serviceMonitor.enabled }} +apiVersion: monitoring.coreos.com/v1 +kind: ServiceMonitor +metadata: + name: {{ template "fullname" . }} + {{- if .Values.metrics.serviceMonitor.namespace }} + namespace: {{ .Values.metrics.serviceMonitor.namespace }} + {{- end }} + labels: + app: {{ template "fullname" . }} + chart: {{ template "radondb-mysql.chart" . }} + release: {{ .Release.Name | quote }} + heritage: {{ .Release.Service | quote }} + {{- if .Values.metrics.serviceMonitor.selector }} +{{ toYaml .Values.metrics.serviceMonitor.selector | indent 2 }} + {{- end }} +spec: + selector: + matchLabels: + app: {{ template "fullname" . }} + release: {{ .Release.Name }} + endpoints: + - port: metrics + interval: {{ .Values.metrics.serviceMonitor.interval }} + namespaceSelector: + any: true +{{ end }} diff --git a/deployment/kubernetes-manifests/quickstart-k8s/charts/mysql/templates/statefulset.yaml b/deployment/kubernetes-manifests/quickstart-k8s/charts/mysql/templates/statefulset.yaml new file mode 100644 index 000000000..4bffd5580 --- /dev/null +++ b/deployment/kubernetes-manifests/quickstart-k8s/charts/mysql/templates/statefulset.yaml @@ -0,0 +1,343 @@ +apiVersion: apps/v1 +kind: StatefulSet +metadata: + name: {{ template "fullname" . }} + namespace: {{ .Release.Namespace }} + labels: + app: {{ template "fullname" . }} + chart: {{ template "radondb-mysql.chart" . }} + release: {{ .Release.Name | quote }} + heritage: {{ .Release.Service | quote }} + {{- with .Values.statefulsetAnnotations }} + annotations: +{{ toYaml . | indent 4 }} + {{- end }} + +spec: + serviceName: {{ template "fullname" . }} + replicas: {{ .Values.replicaCount }} + selector: + matchLabels: + app: {{ template "fullname" . }} + release: {{ .Release.Name }} + template: + metadata: + labels: + app: {{ template "fullname" . }} + release: {{ .Release.Name }} + role: candidate + {{- with .Values.podLabels }} +{{ toYaml . | indent 8 }} + {{- end }} + annotations: + checksum/config: {{include (print $.Template.BasePath "/configmap.yaml") . | sha256sum }} + {{- with .Values.podAnnotations }} +{{ toYaml . | indent 8 }} + {{- end }} + spec: + {{- if .Values.schedulerName }} + schedulerName: "{{ .Values.schedulerName }}" + {{- end }} + serviceAccountName: {{ template "serviceAccountName" . }} + initContainers: + - name: init-mysql + image: "{{ .Values.busybox.image }}:{{ .Values.busybox.tag }}" + imagePullPolicy: {{ .Values.imagePullPolicy | quote }} + resources: +{{ toYaml .Values.resources | indent 10 }} + command: ['sh','-c'] + args: + - | + # Generate mysql server-id from pod ordinal index. + ordinal=$(echo $(hostname) | tr -cd "[0-9]") + # Copy server-id.conf adding offset to avoid reserved server-id=0 value. + cat /mnt/config-map/server-id.cnf | sed s/@@SERVER_ID@@/$((100 + $ordinal))/g > /mnt/conf.d/server-id.cnf + # Copy appropriate conf.d files from config-map to config mount. + cp -f /mnt/config-map/node.cnf /mnt/conf.d/ + cp -f /mnt/config-map/*.sh /mnt/scripts/ + chmod +x /mnt/scripts/* + {{- if .Values.persistence.enabled }} + # remove lost+found. + rm -rf /mnt/data/lost+found + {{- end }} + {{- if .Values.mysql.initTokudb }} + # For install tokudb. + printf '\nloose_tokudb_directio = ON\n' >> /mnt/conf.d/node.cnf + echo never > /host-sys/kernel/mm/transparent_hugepage/enabled + {{- end }} + volumeMounts: + - name: conf + mountPath: /mnt/conf.d + - name: scripts + mountPath: /mnt/scripts + - name: config-map + mountPath: /mnt/config-map + {{- if .Values.persistence.enabled }} + - name: data + mountPath: /mnt/data + {{- end }} + {{- if .Values.mysql.initTokudb }} + - name: host-sys + mountPath: /host-sys + {{- end }} + containers: + - name: mysql + image: "{{ .Values.mysql.image }}:{{ .Values.mysql.tag }}" + imagePullPolicy: {{ .Values.imagePullPolicy | quote }} + {{- with .Values.mysql.args }} + args: + {{- range . }} + - {{ . | quote }} + {{- end }} + {{- end }} + resources: +{{ toYaml .Values.mysql.resources | indent 10 }} + env: + {{- if not .Values.mysql.allowEmptyRootPassword }} + - name: MYSQL_ROOT_PASSWORD + valueFrom: + secretKeyRef: + name: {{ template "fullname" . }} + key: mysql-root-password + {{- end }} + - name: MYSQL_REPL_PASSWORD + valueFrom: + secretKeyRef: + name: {{ template "fullname" . }} + key: mysql-replication-password + {{- if .Values.mysql.mysqlDatabase }} + - name: MYSQL_DATABASE + value: {{ .Values.mysql.mysqlDatabase | quote }} + {{- end }} + {{- if .Values.mysql.mysqlUser }} + - name: MYSQL_USER + value: {{ .Values.mysql.mysqlUser | quote }} + - name: MYSQL_PASSWORD + valueFrom: + secretKeyRef: + name: {{ template "fullname" . }} + key: mysql-password + {{- end }} + {{- if .Values.mysql.initTokudb }} + - name: INIT_TOKUDB + value: "1" + {{- end }} + {{- if .Values.mysql.extraEnvVars }} +{{ tpl .Values.mysql.extraEnvVars . | indent 8 }} + {{- end }} + ports: + - name: mysql + containerPort: 3306 + volumeMounts: + - name: data + mountPath: /var/lib/mysql + - name: conf + mountPath: /etc/mysql/conf.d + - name: logs + mountPath: /var/log/mysql + livenessProbe: + exec: + command: + {{- if .Values.mysql.allowEmptyRootPassword }} + - sh + - -c + - mysqladmin ping -uroot + {{- else }} + - sh + - -c + - mysqladmin ping -uroot -p${MYSQL_ROOT_PASSWORD} + {{- end }} + initialDelaySeconds: {{ .Values.mysql.livenessProbe.initialDelaySeconds }} + periodSeconds: {{ .Values.mysql.livenessProbe.periodSeconds }} + timeoutSeconds: {{ .Values.mysql.livenessProbe.timeoutSeconds }} + successThreshold: {{ .Values.mysql.livenessProbe.successThreshold }} + failureThreshold: {{ .Values.mysql.livenessProbe.failureThreshold }} + readinessProbe: + exec: + command: + {{- if .Values.mysql.allowEmptyRootPassword }} + - sh + - -c + - mysql -uroot -e "SELECT 1" + {{- else }} + - sh + - -c + - mysql -uroot -p${MYSQL_ROOT_PASSWORD} -e "SELECT 1" + {{- end }} + initialDelaySeconds: {{ .Values.mysql.readinessProbe.initialDelaySeconds }} + periodSeconds: {{ .Values.mysql.readinessProbe.periodSeconds }} + timeoutSeconds: {{ .Values.mysql.readinessProbe.timeoutSeconds }} + successThreshold: {{ .Values.mysql.readinessProbe.successThreshold }} + failureThreshold: {{ .Values.mysql.readinessProbe.failureThreshold }} + - name: xenon + image: "{{ .Values.xenon.image }}:{{ .Values.xenon.tag }}" + imagePullPolicy: {{ .Values.imagePullPolicy | quote }} + {{- with .Values.xenon.args }} + args: + {{- range . }} + - {{ . | quote }} + {{- end }} + {{- end }} + lifecycle: + postStart: + exec: + {{- if lt 1 (.Values.replicaCount | int64) }} + command: ['sh', '-c', 'until (xenoncli xenon ping && xenoncli cluster add "$(/scripts/create-peers.sh)") > /dev/null 2>&1; do sleep 2; done'] + {{- else }} + command: ['sh', '-c', 'until (xenoncli xenon ping > /dev/null 2>&1 && xenoncli raft trytoleader) > /dev/null 2>&1; do sleep 2; done'] + {{- end }} + resources: +{{ toYaml .Values.xenon.resources | indent 10 }} + volumeMounts: + - name: scripts + mountPath: /scripts + env: + {{- if not .Values.mysql.allowEmptyRootPassword }} + - name: MYSQL_ROOT_PASSWORD + valueFrom: + secretKeyRef: + name: {{ template "fullname" . }} + key: mysql-root-password + {{- end }} + - name: MYSQL_REPL_PASSWORD + valueFrom: + secretKeyRef: + name: {{ template "fullname" . }} + key: mysql-replication-password + - name: POD_HOSTNAME + valueFrom: + fieldRef: + fieldPath: metadata.name + - name: HOST + value: $(POD_HOSTNAME).{{ template "fullname" . }}.{{ .Release.Namespace }} + - name: LEADER_START_CMD + value: "/scripts/leader-start.sh" + - name: LEADER_STOP_CMD + value: "/scripts/leader-stop.sh" + {{- if .Values.mysql.initTokudb }} + - name: Master_SysVars + value: "tokudb_fsync_log_period=default;sync_binlog=default;innodb_flush_log_at_trx_commit=default" + - name: Slave_SysVars + value: "tokudb_fsync_log_period=1000;sync_binlog=1000;innodb_flush_log_at_trx_commit=1" + {{- else }} + - name: Master_SysVars + value: "sync_binlog=default;innodb_flush_log_at_trx_commit=default" + - name: Slave_SysVars + value: "sync_binlog=1000;innodb_flush_log_at_trx_commit=1" + {{- end }} + {{- if .Values.xenon.extraEnvVars }} +{{ tpl .Values.xenon.extraEnvVars . | indent 8 }} + {{- end }} + ports: + - name: xenon + containerPort: 8801 + livenessProbe: + exec: + command: + - pgrep + - xenon + initialDelaySeconds: {{ .Values.xenon.livenessProbe.initialDelaySeconds }} + periodSeconds: {{ .Values.xenon.livenessProbe.periodSeconds }} + timeoutSeconds: {{ .Values.xenon.livenessProbe.timeoutSeconds }} + successThreshold: {{ .Values.xenon.livenessProbe.successThreshold }} + failureThreshold: {{ .Values.xenon.livenessProbe.failureThreshold }} + readinessProbe: + exec: + command: + - sh + - -c + - "xenoncli xenon ping" + initialDelaySeconds: {{ .Values.xenon.readinessProbe.initialDelaySeconds }} + periodSeconds: {{ .Values.xenon.readinessProbe.periodSeconds }} + timeoutSeconds: {{ .Values.xenon.readinessProbe.timeoutSeconds }} + successThreshold: {{ .Values.xenon.readinessProbe.successThreshold }} + failureThreshold: {{ .Values.xenon.readinessProbe.failureThreshold }} + {{- if .Values.metrics.enabled }} + - name: metrics + image: "{{ .Values.metrics.image }}:{{ .Values.metrics.tag }}" + imagePullPolicy: {{ .Values.imagePullPolicy | quote }} + resources: +{{ toYaml .Values.resources | indent 10 }} + {{- if not .Values.mysql.allowEmptyRootPassword }} + env: + - name: MYSQL_ROOT_PASSWORD + valueFrom: + secretKeyRef: + name: {{ template "fullname" . }} + key: mysql-root-password + command: ['sh', '-c', 'DATA_SOURCE_NAME="root:$MYSQL_ROOT_PASSWORD@(localhost:3306)/" /bin/mysqld_exporter' ] + {{- else }} + command: ['sh', '-c', 'DATA_SOURCE_NAME="root@(localhost:3306)/" /bin/mysqld_exporter' ] + {{- end }} + ports: + - name: metrics + containerPort: 9104 + livenessProbe: + httpGet: + path: / + port: metrics + initialDelaySeconds: {{ .Values.metrics.livenessProbe.initialDelaySeconds }} + timeoutSeconds: {{ .Values.metrics.livenessProbe.timeoutSeconds }} + readinessProbe: + httpGet: + path: / + port: metrics + initialDelaySeconds: {{ .Values.metrics.readinessProbe.initialDelaySeconds }} + timeoutSeconds: {{ .Values.metrics.readinessProbe.timeoutSeconds }} + {{- end }} + {{- if .Values.slowLogTail }} + - name: slowlog + image: "{{ .Values.busybox.image }}:{{ .Values.busybox.tag }}" + imagePullPolicy: {{ .Values.imagePullPolicy | quote }} + resources: +{{ toYaml .Values.resources | indent 10 }} + command: + - "tail" + - "-f" + - "/logs/mysql-slow.log" + volumeMounts: + - name: logs + mountPath: /logs + {{- end }} + volumes: + - name: conf + emptyDir: {} + - name: scripts + emptyDir: {} + - name: logs + emptyDir: {} + - name: config-map + configMap: + name: {{ template "fullname" . }} + {{- if .Values.mysql.initTokudb }} + - name: host-sys + hostPath: + path: /sys + {{- end }} + {{- if .Values.persistence.enabled }} + volumeClaimTemplates: + - metadata: + name: data + annotations: + {{- range $key, $value := .Values.persistence.annotations }} + {{ $key }}: {{ $value }} + {{- end }} + spec: + accessModes: + {{- range .Values.persistence.accessModes }} + - {{ . | quote }} + {{- end }} + resources: + requests: + storage: {{ .Values.persistence.size | quote }} + {{- if .Values.persistence.storageClass }} + {{- if (eq "-" .Values.persistence.storageClass) }} + storageClassName: "" + {{- else }} + storageClassName: "{{ .Values.persistence.storageClass }}" + {{- end }} + {{- end }} + {{- else }} + - name: data + emptyDir: {} + {{- end }} diff --git a/deployment/kubernetes-manifests/quickstart-k8s/charts/mysql/values.yaml b/deployment/kubernetes-manifests/quickstart-k8s/charts/mysql/values.yaml new file mode 100644 index 000000000..070beaa35 --- /dev/null +++ b/deployment/kubernetes-manifests/quickstart-k8s/charts/mysql/values.yaml @@ -0,0 +1,211 @@ +# Default values for radondb-mysql. +# This is a YAML-formatted file. +# Declare variables to be passed into your templates. + +## Specify an imagePullPolicy (Required) +## It's recommended to change this to 'Always' if the image tag is 'latest' +## ref: http://kubernetes.io/docs/user-guide/images/#updating-images +## Always IfNotPresent Never +imagePullPolicy: IfNotPresent + +## String to partially override fullname template (will maintain the release name) +## +# nameOverride: "" +## String to fully override fullname template +## +# fullnameOverride: "" + +# Please donot modify `replicaCount`, after the cluster is created. +replicaCount: 3 + +busybox: + image: busybox + tag: 1.32 + +mysql: + image: radondb/percona + tag: 5.7.34 + + allowEmptyRootPassword: true + # mysqlRootPassword: + mysqlReplicationPassword: Repl_123 + + mysqlUser: radondb + mysqlPassword: RadonDB@123 + mysqlDatabase: radondb + + initTokudb: false + ## Additionnal arguments that are passed to the MySQL container. + ## For example use --default-authentication-plugin=mysql_native_password if older clients need to + ## connect to a MySQL 8 instance. + args: [] + + configFiles: + node.cnf: | + [mysqld] + default_storage_engine=InnoDB + max_connections=65535 + + livenessProbe: + initialDelaySeconds: 30 + periodSeconds: 10 + timeoutSeconds: 5 + successThreshold: 1 + failureThreshold: 3 + + readinessProbe: + initialDelaySeconds: 10 + periodSeconds: 10 + timeoutSeconds: 1 + successThreshold: 1 + failureThreshold: 3 + + ## A string to add extra environment variables + # extraEnvVars: | + # - name: EXTRA_VAR + # value: "extra" + + ## Configure resource requests and limits + ## ref: http://kubernetes.io/docs/user-guide/compute-resources/ + ## + resources: + requests: + memory: 256Mi + cpu: 100m + limits: + memory: 1Gi + cpu: 500m + +xenon: + image: radondb/xenon + tag: 1.1.5-helm + args: [] + + ## A string to add extra environment variables + # extraEnvVars: | + # - name: EXTRA_VAR + # value: "extra" + + ## Configure resource requests and limits + ## ref: http://kubernetes.io/docs/user-guide/compute-resources/ + ## + livenessProbe: + initialDelaySeconds: 30 + periodSeconds: 10 + timeoutSeconds: 5 + successThreshold: 1 + failureThreshold: 3 + + readinessProbe: + initialDelaySeconds: 10 + periodSeconds: 10 + timeoutSeconds: 1 + successThreshold: 1 + failureThreshold: 3 + + resources: + requests: + memory: 128Mi + cpu: 50m + limits: + memory: 256Mi + cpu: 100m + +metrics: + enabled: false + image: prom/mysqld-exporter + tag: v0.12.1 + annotations: {} + + livenessProbe: + initialDelaySeconds: 15 + timeoutSeconds: 5 + readinessProbe: + initialDelaySeconds: 5 + timeoutSeconds: 1 + + # Enable this if you're using https://github.com/coreos/prometheus-operator + serviceMonitor: + enabled: false + ## Specify a namespace if needed + # namespace: monitoring + # fallback to the prometheus default unless specified + interval: 10s + # scrapeTimeout: 10s + ## Defaults to what's used if you follow CoreOS [Prometheus Install Instructions](https://github.com/helm/charts/tree/master/stable/prometheus-operator#tldr) + ## [Prometheus Selector Label](https://github.com/helm/charts/tree/master/stable/prometheus-operator#prometheus-operator-1) + ## [Kube Prometheus Selector Label](https://github.com/helm/charts/tree/master/stable/prometheus-operator#exporters) + # selector: + # prometheus: kube-prometheus + +## When set to true will create sidecar to tail mysql slow log. +slowLogTail: true + +resources: {} +# limits: +# cpu: 100m +# memory: 128Mi +# requests: +# cpu: 10m +# memory: 32Mi + +## Configure the service +## ref: http://kubernetes.io/docs/user-guide/services/ +service: + annotations: {} + ## Specify a service type, NodePort|ClusterIP|LoadBalancer + ## ref: https://kubernetes.io/docs/concepts/services-networking/service/#publishing-services---service-types + type: ClusterIP + # clusterIP: None + port: 3306 + # nodePort: 32000 + # loadBalancerIP: + +rbac: + # Specifies whether RBAC resources should be created + create: true + +serviceAccount: + # Specifies whether a service account should be created + create: true + # The name of the service account to use. + # If not set and create is true, a name is generated using the serviceAccountName template + name: + +## Enable persistence using Persistent Volume Claims +## ref: http://kubernetes.io/docs/user-guide/persistent-volumes/ +## +persistence: + enabled: true + ## If defined, storageClassName: + ## If set to "-", storageClassName: "", which disables dynamic provisioning + ## If undefined (the default) or set to null, no storageClassName spec is + ## set, choosing the default provisioner. (gp2 on AWS, azure-disk on + ## Azure, standard on GKE, AWS & OpenStack) + ## + # storageClass: "-" + accessModes: + - ReadWriteOnce + size: 1Gi + annotations: {} + reclaimPolicy: "" + +## Set pod priorityClassName +# priorityClassName: {} + +## Use an alternate scheduler, e.g. "stork". +## ref: https://kubernetes.io/docs/tasks/administer-cluster/configure-multiple-schedulers/ +## +# schedulerName: + +# statefulset Annotations +statefulsetAnnotations: {} + +# To be added to the database server pod(s) +podAnnotations: {} +podLabels: {} + +nodeSelector: {} +hardAntiAffinity: true +additionalAffinities: {} +affinity: {} diff --git a/deployment/kubernetes-manifests/quickstart-k8s/charts/nacos/Chart.yaml b/deployment/kubernetes-manifests/quickstart-k8s/charts/nacos/Chart.yaml new file mode 100644 index 000000000..325ff00ea --- /dev/null +++ b/deployment/kubernetes-manifests/quickstart-k8s/charts/nacos/Chart.yaml @@ -0,0 +1,5 @@ +apiVersion: v1 +appVersion: "1.0" +description: A Helm chart for Kubernetes +name: nacos +version: 0.1.5 diff --git a/deployment/kubernetes-manifests/quickstart-k8s/charts/nacos/README.md b/deployment/kubernetes-manifests/quickstart-k8s/charts/nacos/README.md new file mode 100644 index 000000000..910ab1514 --- /dev/null +++ b/deployment/kubernetes-manifests/quickstart-k8s/charts/nacos/README.md @@ -0,0 +1,53 @@ +# Nacos Helm Chart + +Nacos is committed to help you discover, configure, and manage your microservices. It provides a set of simple and useful features enabling you to realize dynamic service discovery, service configuration, service metadata and traffic management. + + +## Prerequisites + + - Kubernetes 1.10+ + - Helm v3 + - PV provisioner support in the underlying infrastructure + +## Tips +If you use a custom database, please initialize the database script yourself first. + + + +## Installing the Chart + +To install the chart with `release name`: + +```shell +$ helm install `release name` ./nacos +``` + +## Configuration + +The following table lists the configurable parameters of the Skywalking chart and their default values. + +| Parameter | Description | Default | +|---------------------|--------------------------------------------------------------------|-------------------------------------| +| `global.mode` | Run Mode (~~quickstart,~~ standalone, cluster; ) | `standalone` | +| `resources` | The [resources] to allocate for nacos container | `{}` | +| `nodeSelector` | Nacos labels for pod assignment | `{}` | +| `affinity` | Nacos affinity policy | `{}` | +| `tolerations` | Nacos tolerations | `{}` | +| `resources.requests.cpu`|nacos requests cpu resource|`500m`| +| `resources.requests.memory`|nacos requests memory resource|`2G`| +| `nacos.replicaCount` | Number of desired nacos pods, the number should be 1 as run standalone mode| `1` | +| `nacos.image.repository` | Nacos container image name | `nacos/nacos-server` | +| `nacos.image.tag` | Nacos container image tag | `2.0.1` | +| `nacos.image.pullPolicy` | Nacos container image pull policy | `IfNotPresent` | +| `nacos.health.enabled` | Enable health check or not | `false` | +| `nacos.secretName` | secret name of db for nacos | `nacos-mysql` | +| `nacos.db.host` | mysql host | | +| `nacos.db.name` | mysql database name | | +| `nacos.db.port` | mysql port | 3306 | +| `nacos.db.username` | username of database | | +| `nacos.db.password` | password of database | | +| `nacos.env.preferhostmode` | Enable Nacos cluster node domain name support | `hostname` | +| `nacos.env.serverPort` | Nacos port | `8848` | +| `service.type` | http service type | `NodePort` | +| `service.port` | http service port | `8848` | +| `service.nodePort` | http service nodeport | `30000` | diff --git a/deployment/kubernetes-manifests/quickstart-k8s/charts/nacos/templates/_helpers.tpl b/deployment/kubernetes-manifests/quickstart-k8s/charts/nacos/templates/_helpers.tpl new file mode 100644 index 000000000..650b09236 --- /dev/null +++ b/deployment/kubernetes-manifests/quickstart-k8s/charts/nacos/templates/_helpers.tpl @@ -0,0 +1,45 @@ +{{/* vim: set filetype=mustache: */}} +{{/* +Expand the name of the chart. +*/}} +{{- define "nacos.name" -}} +{{- default .Chart.Name .Values.nameOverride | trunc 63 | trimSuffix "-" -}} +{{- end -}} + +{{/* +Create a default fully qualified app name. +We truncate at 63 chars because some Kubernetes name fields are limited to this (by the DNS naming spec). +If release name contains chart name it will be used as a full name. +*/}} +{{- define "nacos.fullname" -}} +{{- if .Values.fullnameOverride -}} +{{- .Values.fullnameOverride | trunc 63 | trimSuffix "-" -}} +{{- else -}} +{{- $name := default .Chart.Name .Values.nameOverride -}} +{{- if contains $name .Release.Name -}} +{{- .Release.Name | trunc 63 | trimSuffix "-" -}} +{{- else -}} +{{- printf "%s-%s" .Release.Name $name | trunc 63 | trimSuffix "-" -}} +{{- end -}} +{{- end -}} +{{- end -}} + +{{/* +Create chart name and version as used by the chart label. +*/}} +{{- define "nacos.chart" -}} +{{- printf "%s-%s" .Chart.Name .Chart.Version | replace "+" "_" | trunc 63 | trimSuffix "-" -}} +{{- end -}} + +{{/* +Common labels +*/}} +{{- define "nacos.labels" -}} +app.kubernetes.io/name: {{ include "nacos.name" . }} +helm.sh/chart: {{ include "nacos.chart" . }} +app.kubernetes.io/instance: {{ .Release.Name }} +{{- if .Chart.AppVersion }} +app.kubernetes.io/version: {{ .Chart.AppVersion | quote }} +{{- end }} +app.kubernetes.io/managed-by: {{ .Release.Service }} +{{- end -}} \ No newline at end of file diff --git a/deployment/kubernetes-manifests/quickstart-k8s/charts/nacos/templates/configmap.yaml b/deployment/kubernetes-manifests/quickstart-k8s/charts/nacos/templates/configmap.yaml new file mode 100644 index 000000000..d49e44351 --- /dev/null +++ b/deployment/kubernetes-manifests/quickstart-k8s/charts/nacos/templates/configmap.yaml @@ -0,0 +1,7 @@ +apiVersion: v1 +kind: ConfigMap +metadata: + name: {{ .Release.Name }} + namespace: {{ .Release.Namespace }} +data: + NACOS_ADDRS: "{{ .Release.Name }}-0.{{ .Values.nacos.headlessService }}.{{ .Release.Namespace }}.svc.{{ .Values.nacos.domainName }}:{{ .Values.nacos.serverPort}},{{ .Release.Name }}-1.{{ .Values.nacos.headlessService }}.{{ .Release.Namespace }}.svc.{{ .Values.nacos.domainName }}:{{ .Values.nacos.serverPort}},{{ .Release.Name }}-2.{{ .Values.nacos.headlessService }}.{{ .Release.Namespace }}.svc.{{ .Values.nacos.domainName }}:{{ .Values.nacos.serverPort}}" \ No newline at end of file diff --git a/deployment/kubernetes-manifests/quickstart-k8s/charts/nacos/templates/secrets.yaml b/deployment/kubernetes-manifests/quickstart-k8s/charts/nacos/templates/secrets.yaml new file mode 100644 index 000000000..b95f2bbf4 --- /dev/null +++ b/deployment/kubernetes-manifests/quickstart-k8s/charts/nacos/templates/secrets.yaml @@ -0,0 +1,14 @@ +apiVersion: v1 +kind: Secret +metadata: + name: {{ .Values.nacos.secretName }} + namespace: {{ .Release.Namespace }} +type: Opaque +stringData: + {{- with .Values.nacos.db }} + MYSQL_SERVICE_HOST: {{.host}} + MYSQL_SERVICE_PORT: "{{ .port | default 3306}}" + MYSQL_SERVICE_DB_NAME: {{ .name }} + MYSQL_SERVICE_USER: {{ .username }} + MYSQL_SERVICE_PASSWORD: {{ .passowrd }} + {{- end }} \ No newline at end of file diff --git a/deployment/kubernetes-manifests/quickstart-k8s/charts/nacos/templates/service.yaml b/deployment/kubernetes-manifests/quickstart-k8s/charts/nacos/templates/service.yaml new file mode 100644 index 000000000..804d8b12c --- /dev/null +++ b/deployment/kubernetes-manifests/quickstart-k8s/charts/nacos/templates/service.yaml @@ -0,0 +1,42 @@ +{{- if and (eq .Values.global.mode "cluster") }} +apiVersion: v1 +kind: Service +metadata: + name: {{ .Values.nacos.headlessService }} + namespace: {{ .Release.Namespace }} +spec: + type: ClusterIP + clusterIP: None + ports: + - port: 8848 + name: server + targetPort: 8848 + - port: 9848 + name: client-rpc + targetPort: 9848 + - port: 9849 + name: raft-rpc + targetPort: 9849 + - port: 7848 + name: old-rpc + targetPort: 7848 + selector: + app: {{ .Release.Name }} +--- +apiVersion: v1 +kind: Service +metadata: + name: {{ .Release.Name }} + namespace: {{ .Release.Namespace }} +spec: + ports: + - port: 8848 + name: server + targetPort: 8848 + - port: 7848 + name: rpc + targetPort: 7848 + selector: + app: {{ .Release.Name }} + type: {{ .Values.service.type }} +{{end}} diff --git a/deployment/kubernetes-manifests/quickstart-k8s/charts/nacos/templates/statefulset.yaml b/deployment/kubernetes-manifests/quickstart-k8s/charts/nacos/templates/statefulset.yaml new file mode 100644 index 000000000..d4893f8f4 --- /dev/null +++ b/deployment/kubernetes-manifests/quickstart-k8s/charts/nacos/templates/statefulset.yaml @@ -0,0 +1,73 @@ +apiVersion: apps/v1 +kind: StatefulSet +metadata: + name: {{ .Release.Name }} + namespace: {{ .Release.Namespace }} +spec: + podManagementPolicy: OrderedReady + replicas: 3 + revisionHistoryLimit: 10 + selector: + matchLabels: + app: {{ .Release.Name }} + serviceName: {{ .Values.nacos.headlessService }} + template: + metadata: + labels: + app: {{ .Release.Name }} + spec: + initContainers: + - name: initmysql + image: {{ .Values.initmysql.image }} + imagePullPolicy: IfNotPresent + envFrom: + - secretRef: + name: {{ .Values.nacos.secretName }} + containers: + - name: k8snacos + env: + - name: NACOS_REPLICAS + value: "3" + - name: NACOS_SERVER_PORT + value: "8848" + - name: NACOS_APPLICATION_PORT + value: "8848" + - name: PREFER_HOST_MODE + value: hostname + - name: MODE + value: cluster + - name: NACOS_SERVERS + value: "{{ .Release.Name }}-0.{{ .Values.nacos.headlessService }}.{{ .Release.Namespace }}.svc.{{ .Values.nacos.domainName }}:{{ .Values.nacos.serverPort}} {{ .Release.Name }}-1.{{ .Values.nacos.headlessService }}.{{ .Release.Namespace }}.svc.{{ .Values.nacos.domainName }}:{{ .Values.nacos.serverPort}} {{ .Release.Name }}-2.{{ .Values.nacos.headlessService }}.{{ .Release.Namespace }}.svc.{{ .Values.nacos.domainName }}:{{ .Values.nacos.serverPort}}" + envFrom: + - secretRef: + name: {{ .Values.nacos.secretName }} + image: "{{ .Values.nacos.image.repository }}:{{ .Values.nacos.image.tag }}" + imagePullPolicy: {{ .Values.nacos.image.pullPolicy }} + ports: + - containerPort: {{ .Values.nacos.serverPort }} + name: client + protocol: TCP + - containerPort: 7848 + name: old-rpc + protocol: TCP + - containerPort: 9848 + name: client-rpc + protocol: TCP + - containerPort: 9849 + name: raft-rpc + protocol: TCP + resources: + requests: + cpu: {{ .Values.resources.requests.cpu }} + memory: {{ .Values.resources.requests.memory }} + terminationMessagePath: /dev/termination-log + terminationMessagePolicy: File + dnsPolicy: ClusterFirst + restartPolicy: Always + schedulerName: default-scheduler + securityContext: { } + terminationGracePeriodSeconds: 30 + updateStrategy: + rollingUpdate: + partition: 0 + type: RollingUpdate \ No newline at end of file diff --git a/deployment/kubernetes-manifests/quickstart-k8s/charts/nacos/values.yaml b/deployment/kubernetes-manifests/quickstart-k8s/charts/nacos/values.yaml new file mode 100644 index 000000000..9e3415e64 --- /dev/null +++ b/deployment/kubernetes-manifests/quickstart-k8s/charts/nacos/values.yaml @@ -0,0 +1,57 @@ +# Default values for nacos. +# This is a YAML-formatted file. +# Declare variables to be passed into your templates. + +global: + mode: cluster + +############################nacos########################### +nacos: + image: + repository: nacos/nacos-server + tag: 2.0.1 + pullPolicy: IfNotPresent + replicaCount: 3 + domainName: cluster.local + preferhostmode: hostname + serverPort: 8848 + health: + enabled: false + secretName: nacos-mysql + db: + name: "nacos" + host: "nacos-mysql-leader" + username: "nacos" + passowrd: "Abcd1234#" + port: "3306" + headlessService: "nacos-headless" +service: + #type: ClusterIP + type: NodePort + port: 8848 + +initmysql: + image: "codewisdom/mysqlclient:0.1" + + + +resources: + requests: + cpu: 500m + memory: 1Gi + # limits: + # cpu: 1000m + # memory: 4Gi + # We usually recommend not to specify default resources and to leave this as a conscious + # choice for the user. This also increases chances charts run on environments with little + # resources, such as Minikube. If you do want to specify resources, uncomment the following + # lines, adjust them as necessary, and remove the curly braces after 'resources:'. + + +annotations: { } + +nodeSelector: { } + +tolerations: [ ] + +affinity: { } diff --git a/deployment/kubernetes-manifests/quickstart-k8s/charts/rabbitmq/Chart.yaml b/deployment/kubernetes-manifests/quickstart-k8s/charts/rabbitmq/Chart.yaml new file mode 100644 index 000000000..a24b20fae --- /dev/null +++ b/deployment/kubernetes-manifests/quickstart-k8s/charts/rabbitmq/Chart.yaml @@ -0,0 +1,5 @@ +apiVersion: v1 +appVersion: "1.0" +description: A Helm chart for Kubernetes +name: rabbitmq +version: 3 diff --git a/deployment/kubernetes-manifests/quickstart-k8s/charts/rabbitmq/README.md b/deployment/kubernetes-manifests/quickstart-k8s/charts/rabbitmq/README.md new file mode 100644 index 000000000..e03a24f7d --- /dev/null +++ b/deployment/kubernetes-manifests/quickstart-k8s/charts/rabbitmq/README.md @@ -0,0 +1,167 @@ + + +# RabbitMQ packaged by helm + +RabbitMQ is an open source general-purpose message broker that is designed for consistent, highly-available messaging scenarios (both synchronous and asynchronous). + +[Overview of RabbitMQ](https://www.rabbitmq.com) + +Trademarks: This software listing is packaged by Bitnami. The respective trademarks mentioned in the offering are owned by the respective companies, and use of them does not imply any affiliation or endorsement. + +## TL;DR + +```bash +$ helm install my-release bitnami/rabbitmq +``` + +## Introduction + +This chart bootstraps a [RabbitMQ](https://github.com/bitnami/containers/tree/main/bitnami/rabbitmq) deployment on a [Kubernetes](https://kubernetes.io) cluster using the [Helm](https://helm.sh) package manager. +## Prerequisites + +- Kubernetes 1.19+ +- Helm 3.2.0+ +- PV provisioner support in the underlying infrastructure + +## Installing the Chart + +To install the chart with the release name `my-release`: + +```bash +$ helm install my-release ./rabbitmq +``` + +The command deploys RabbitMQ on the Kubernetes cluster in the default configuration. The [Parameters](#parameters) section lists the parameters that can be configured during installation. + +> **Tip**: List all releases using `helm list` + +## Uninstalling the Chart + +To uninstall/delete the `my-release` deployment: + +```bash +$ helm delete my-release +``` + +The command removes all the Kubernetes components associated with the chart and deletes the release. + +## Parameters + +### Global parameters + +| Name | Description | Value | +| ------------------------- | ----------------------------------------------- | ----- | +| `global.imageRegistry` | Global Docker image registry | `""` | +| `global.imagePullSecrets` | Global Docker registry secret names as an array | `[]` | +| `global.storageClass` | Global StorageClass for Persistent Volume(s) | `""` | + + +### RabbitMQ Image parameters + +| Name | Description | Value | +| ------------------- | -------------------------------------------------------------- | --------------------- | +| `image.registry` | RabbitMQ image registry | `docker.io` | +| `image.repository` | RabbitMQ image repository | `bitnami/rabbitmq` | +| `image.tag` | RabbitMQ image tag (immutable tags are recommended) | `3.10.7-debian-11-r2` | +| `image.pullPolicy` | RabbitMQ image pull policy | `IfNotPresent` | +| `image.pullSecrets` | Specify docker-registry secret names as an array | `[]` | +| `image.debug` | Set to true if you would like to see extra information on logs | `false` | + + +### Common parameters + +| Name | Description | Value | +| ---------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------- | +| `nameOverride` | String to partially override rabbitmq.fullname template (will maintain the release name) | `""` | +| `fullnameOverride` | String to fully override rabbitmq.fullname template | `""` | +| `namespaceOverride` | String to fully override common.names.namespace | `""` | +| `kubeVersion` | Force target Kubernetes version (using Helm capabilities if not set) | `""` | +| `clusterDomain` | Kubernetes Cluster Domain | `cluster.local` | +| `dnsPolicy` | DNS Policy for pod | `""` | +| `dnsConfig` | DNS Configuration pod | `{}` | + +### Statefulset parameters + +| Name | Description | Value | +| --------------------------------------- | ------------------------------------------------------------------------------------------------------------------------ | --------------- | +| `replicaCount` | Number of RabbitMQ replicas to deploy | `1` | +| `schedulerName` | Use an alternate scheduler, e.g. "stork". | `""` | +| `podManagementPolicy` | Pod management policy | `OrderedReady` | +| `podLabels` | RabbitMQ Pod labels. Evaluated as a template | `{}` | +| `podAnnotations` | RabbitMQ Pod annotations. Evaluated as a template | `{}` | +| `updateStrategy.type` | Update strategy type for RabbitMQ statefulset | `RollingUpdate` | +| `statefulsetLabels` | RabbitMQ statefulset labels. Evaluated as a template | `{}` | +| `priorityClassName` | Name of the priority class to be used by RabbitMQ pods, priority class needs to be created beforehand | `""` | +| `podAffinityPreset` | Pod affinity preset. Ignored if `affinity` is set. Allowed values: `soft` or `hard` | `""` | +| `podAntiAffinityPreset` | Pod anti-affinity preset. Ignored if `affinity` is set. Allowed values: `soft` or `hard` | `soft` | +| `nodeAffinityPreset.type` | Node affinity preset type. Ignored if `affinity` is set. Allowed values: `soft` or `hard` | `""` | +| `nodeAffinityPreset.key` | Node label key to match Ignored if `affinity` is set. | `""` | +| `nodeAffinityPreset.values` | Node label values to match. Ignored if `affinity` is set. | `[]` | +| `affinity` | Affinity for pod assignment. Evaluated as a template | `{}` | +| `nodeSelector` | Node labels for pod assignment. Evaluated as a template | `{}` | +| `tolerations` | Tolerations for pod assignment. Evaluated as a template | `[]` | +| `containerSecurityContext.runAsNonRoot` | Set RabbitMQ container's Security Context runAsNonRoot | `true` | +| `resources.limits` | The resources limits for RabbitMQ containers | `{}` | +| `resources.requests` | The requested resources for RabbitMQ containers | `{}` | + + +### RBAC parameters + +| Name | Description | Value | +| --------------------------------------------- | ------------------------------------------------------------------------------------------ | ------ | +| `serviceAccount.create` | Enable creation of ServiceAccount for RabbitMQ pods | `true` | +| `serviceAccount.name` | Name of the created serviceAccount | `""` | +| `serviceAccount.automountServiceAccountToken` | Auto-mount the service account token in the pod | `true` | +| `serviceAccount.annotations` | Annotations for service account. Evaluated as a template. Only used if `create` is `true`. | `{}` | +| `rbac.create` | Whether RBAC rules should be created | `true` | + + +### Persistence parameters + +| Name | Description | Value | +| --------------------------- | ------------------------------------------------ | -------------------------- | +| `persistence.enabled` | Enable RabbitMQ data persistence using PVC | `true` | +| `persistence.storageClass` | PVC Storage Class for RabbitMQ data volume | `""` | +| `persistence.selector` | Selector to match an existing Persistent Volume | `{}` | +| `persistence.accessModes` | PVC Access Modes for RabbitMQ data volume | `["ReadWriteOnce"]` | +| `persistence.existingClaim` | Provide an existing PersistentVolumeClaims | `""` | +| `persistence.mountPath` | The path the volume will be mounted at | `/bitnami/rabbitmq/mnesia` | +| `persistence.subPath` | The subdirectory of the volume to mount to | `""` | +| `persistence.size` | PVC Storage Request for RabbitMQ data volume | `8Gi` | +| `persistence.annotations` | Persistence annotations. Evaluated as a template | `{}` | + +Alternatively, a YAML file that specifies the values for the parameters can be provided while installing the chart. For example, + +```bash +$ helm install my-release -f values.yaml ./rabbitmq +``` + +> **Tip**: You can use the default [values.yaml](values.yaml) + +## Configuration and installation details + +### [Rolling vs Immutable tags](https://docs.bitnami.com/containers/how-to/understand-rolling-tags-containers/) + +It is strongly recommended to use immutable tags in a production environment. This ensures your deployment does not change automatically if the same tag is updated with a different image. + +Bitnami will release a new chart updating its containers if a new version of the main container, significant changes, or critical vulnerabilities exist. + +### Set pod affinity + +This chart allows you to set your custom affinity using the `affinity` parameter. Find more information about Pod's affinity in the [kubernetes documentation](https://kubernetes.io/docs/concepts/configuration/assign-pod-node/#affinity-and-anti-affinity). + +As an alternative, you can use of the preset configurations for pod affinity, pod anti-affinity, and node affinity available at the [bitnami/common](https://github.com/bitnami/charts/tree/master/bitnami/common#affinities) chart. To do so, set the `podAffinityPreset`, `podAntiAffinityPreset`, or `nodeAffinityPreset` parameters. + +### Scale horizontally + +To horizontally scale this chart once it has been deployed, two options are available: + +- Use the `kubectl scale` command. +- Upgrade the chart modifying the `replicaCount` parameter. + +> NOTE: It is mandatory to specify the password and Erlang cookie that was set the first time the chart was installed when upgrading the chart. + +When scaling down the solution, unnecessary RabbitMQ nodes are automatically stopped, but they are not removed from the cluster. You need to manually remove them by running the `rabbitmqctl forget_cluster_node` command. + +Refer to the chart documentation for [more information on scaling the Rabbit cluster horizontally](https://docs.bitnami.com/kubernetes/infrastructure/rabbitmq/administration/scale-deployment/). + diff --git a/deployment/kubernetes-manifests/quickstart-k8s/charts/rabbitmq/templates/configmap.yaml b/deployment/kubernetes-manifests/quickstart-k8s/charts/rabbitmq/templates/configmap.yaml new file mode 100644 index 000000000..551de6ccb --- /dev/null +++ b/deployment/kubernetes-manifests/quickstart-k8s/charts/rabbitmq/templates/configmap.yaml @@ -0,0 +1,7 @@ +apiVersion: v1 +kind: ConfigMap +metadata: + name: {{ .Release.Name }} + namespace: {{ .Release.Namespace }} +data: + rabbitmq_host: {{ .Release.Name }} \ No newline at end of file diff --git a/deployment/kubernetes-manifests/quickstart-k8s/charts/rabbitmq/templates/deployment.yaml b/deployment/kubernetes-manifests/quickstart-k8s/charts/rabbitmq/templates/deployment.yaml new file mode 100644 index 000000000..ec2be281b --- /dev/null +++ b/deployment/kubernetes-manifests/quickstart-k8s/charts/rabbitmq/templates/deployment.yaml @@ -0,0 +1,25 @@ +apiVersion: apps/v1 +kind: Deployment +metadata: + name: {{ .Release.Name }} + namespace: {{ .Release.Namespace }} +spec: + selector: + matchLabels: + app: {{ .Release.Name }} + replicas: {{ .Values.rabbitmq.replicaCount }} + template: + metadata: + labels: + app: {{ .Release.Name }} + spec: + containers: + - name: rabbitmq + image: "{{ .Values.rabbitmq.image.repository }}:{{ .Values.rabbitmq.image.tag }}" + imagePullPolicy: {{ .Values.rabbitmq.image.pullPolicy }} + ports: + - containerPort: {{ .Values.rabbitmq.serverPort }} + resources: + requests: + cpu: {{ .Values.resources.requests.cpu }} + memory: {{ .Values.resources.requests.memory }} \ No newline at end of file diff --git a/deployment/kubernetes-manifests/quickstart-k8s/charts/rabbitmq/templates/service.yaml b/deployment/kubernetes-manifests/quickstart-k8s/charts/rabbitmq/templates/service.yaml new file mode 100644 index 000000000..540fa9b67 --- /dev/null +++ b/deployment/kubernetes-manifests/quickstart-k8s/charts/rabbitmq/templates/service.yaml @@ -0,0 +1,10 @@ +apiVersion: v1 +kind: Service +metadata: + name: {{ .Release.Name }} + namespace: {{ .Release.Namespace }} +spec: + ports: + - port: {{ .Values.rabbitmq.serverPort }} + selector: + app: {{ .Release.Name }} diff --git a/deployment/kubernetes-manifests/quickstart-k8s/charts/rabbitmq/values.yaml b/deployment/kubernetes-manifests/quickstart-k8s/charts/rabbitmq/values.yaml new file mode 100644 index 000000000..ed740a706 --- /dev/null +++ b/deployment/kubernetes-manifests/quickstart-k8s/charts/rabbitmq/values.yaml @@ -0,0 +1,36 @@ +# Default values for nacos. +# This is a YAML-formatted file. +# Declare variables to be passed into your templates. + +global: + mode: cluster + +############################nacos########################### +rabbitmq: + image: + repository: codewisdom/rabbitmq + tag: 3 + pullPolicy: IfNotPresent + replicaCount: 1 + serverPort: 5672 + +resources: + requests: + cpu: 100m + memory: 200Mi + # limits: + # cpu: 1000m + # memory: 4Gi + # We usually recommend not to specify default resources and to leave this as a conscious + # choice for the user. This also increases chances charts run on environments with little + # resources, such as Minikube. If you do want to specify resources, uncomment the following + # lines, adjust them as necessary, and remove the curly braces after 'resources:'. + + +annotations: { } + +nodeSelector: { } + +tolerations: [ ] + +affinity: { } diff --git a/deployment/kubernetes-manifests/quickstart-k8s/quickstart-ts-deployment-part1.yml b/deployment/kubernetes-manifests/quickstart-k8s/quickstart-ts-deployment-part1.yml deleted file mode 100644 index bad38b05f..000000000 --- a/deployment/kubernetes-manifests/quickstart-k8s/quickstart-ts-deployment-part1.yml +++ /dev/null @@ -1,966 +0,0 @@ -apiVersion: apps/v1 -kind: Deployment -metadata: - name: ts-user-mongo -spec: - selector: - matchLabels: - app: ts-user-mongo - replicas: 1 - template: - metadata: - labels: - app: ts-user-mongo - spec: - containers: - - name: ts-user-mongo - image: mongo - imagePullPolicy: IfNotPresent - ports: - - containerPort: 27017 - resources: - requests: - cpu: 50m - memory: 100Mi ---- - -apiVersion: apps/v1 -kind: Deployment -metadata: - name: ts-auth-mongo -spec: - selector: - matchLabels: - app: ts-auth-mongo - replicas: 1 - template: - metadata: - labels: - app: ts-auth-mongo - spec: - containers: - - name: ts-auth-mongo - image: mongo - imagePullPolicy: IfNotPresent - ports: - - containerPort: 27017 - resources: - requests: - cpu: 50m - memory: 100Mi ---- - -apiVersion: apps/v1 -kind: Deployment -metadata: - name: ts-route-mongo -spec: - selector: - matchLabels: - app: ts-route-mongo - replicas: 1 - template: - metadata: - labels: - app: ts-route-mongo - spec: - containers: - - name: ts-route-mongo - image: mongo - imagePullPolicy: IfNotPresent - ports: - - containerPort: 27017 - resources: - requests: - cpu: 50m - memory: 100Mi - ---- - -apiVersion: apps/v1 -kind: Deployment -metadata: - name: ts-contacts-mongo -spec: - selector: - matchLabels: - app: ts-contacts-mongo - replicas: 1 - template: - metadata: - labels: - app: ts-contacts-mongo - spec: - containers: - - name: ts-contacts-mongo - image: mongo - imagePullPolicy: IfNotPresent - ports: - - containerPort: 27017 - resources: - requests: - cpu: 50m - memory: 100Mi - ---- - -apiVersion: apps/v1 -kind: Deployment -metadata: - name: ts-order-mongo -spec: - selector: - matchLabels: - app: ts-order-mongo - replicas: 1 - template: - metadata: - labels: - app: ts-order-mongo - spec: - containers: - - name: ts-order-mongo - image: mongo - imagePullPolicy: IfNotPresent - ports: - - containerPort: 27017 - resources: - requests: - cpu: 50m - memory: 100Mi - ---- - -apiVersion: apps/v1 -kind: Deployment -metadata: - name: ts-order-other-mongo -spec: - selector: - matchLabels: - app: ts-order-other-mongo - replicas: 1 - template: - metadata: - labels: - app: ts-order-other-mongo - spec: - containers: - - name: ts-order-other-mongo - image: mongo - imagePullPolicy: IfNotPresent - ports: - - containerPort: 27017 - resources: - requests: - cpu: 50m - memory: 100Mi - ---- - -apiVersion: apps/v1 -kind: Deployment -metadata: - name: ts-config-mongo -spec: - selector: - matchLabels: - app: ts-config-mongo - replicas: 1 - template: - metadata: - labels: - app: ts-config-mongo - spec: - containers: - - name: ts-config-mongo - image: mongo - imagePullPolicy: IfNotPresent - ports: - - containerPort: 27017 - resources: - requests: - cpu: 50m - memory: 100Mi - ---- - -apiVersion: apps/v1 -kind: Deployment -metadata: - name: ts-station-mongo -spec: - selector: - matchLabels: - app: ts-station-mongo - replicas: 1 - template: - metadata: - labels: - app: ts-station-mongo - spec: - containers: - - name: ts-station-mongo - image: mongo - imagePullPolicy: IfNotPresent - ports: - - containerPort: 27017 - resources: - requests: - cpu: 50m - memory: 100Mi - ---- - -apiVersion: apps/v1 -kind: Deployment -metadata: - name: ts-train-mongo -spec: - selector: - matchLabels: - app: ts-train-mongo - replicas: 1 - template: - metadata: - labels: - app: ts-train-mongo - spec: - containers: - - name: ts-train-mongo - image: mongo - imagePullPolicy: IfNotPresent - ports: - - containerPort: 27017 - resources: - requests: - cpu: 50m - memory: 100Mi - ---- - -apiVersion: apps/v1 -kind: Deployment -metadata: - name: ts-travel-mongo -spec: - selector: - matchLabels: - app: ts-travel-mongo - replicas: 1 - template: - metadata: - labels: - app: ts-travel-mongo - spec: - containers: - - name: ts-travel-mongo - image: mongo - imagePullPolicy: IfNotPresent - ports: - - containerPort: 27017 - resources: - requests: - cpu: 50m - memory: 100Mi - ---- - -apiVersion: apps/v1 -kind: Deployment -metadata: - name: ts-travel2-mongo -spec: - selector: - matchLabels: - app: ts-travel2-mongo - replicas: 1 - template: - metadata: - labels: - app: ts-travel2-mongo - spec: - containers: - - name: ts-travel2-mongo - image: mongo - imagePullPolicy: IfNotPresent - ports: - - containerPort: 27017 - resources: - requests: - cpu: 50m - memory: 100Mi - ---- - -apiVersion: apps/v1 -kind: Deployment -metadata: - name: ts-price-mongo -spec: - selector: - matchLabels: - app: ts-price-mongo - replicas: 1 - template: - metadata: - labels: - app: ts-price-mongo - spec: - containers: - - name: ts-price-mongo - image: mongo - imagePullPolicy: IfNotPresent - ports: - - containerPort: 27017 - resources: - requests: - cpu: 50m - memory: 100Mi - ---- - -apiVersion: apps/v1 -kind: Deployment -metadata: - name: ts-security-mongo -spec: - selector: - matchLabels: - app: ts-security-mongo - replicas: 1 - template: - metadata: - labels: - app: ts-security-mongo - spec: - containers: - - name: ts-security-mongo - image: mongo - imagePullPolicy: IfNotPresent - ports: - - containerPort: 27017 - resources: - requests: - cpu: 50m - memory: 100Mi - ---- - -apiVersion: apps/v1 -kind: Deployment -metadata: - name: ts-inside-payment-mongo -spec: - selector: - matchLabels: - app: ts-inside-payment-mongo - replicas: 1 - template: - metadata: - labels: - app: ts-inside-payment-mongo - spec: - containers: - - name: ts-inside-payment-mongo - image: mongo - imagePullPolicy: IfNotPresent - ports: - - containerPort: 27017 - resources: - requests: - cpu: 50m - memory: 100Mi - ---- - -apiVersion: apps/v1 -kind: Deployment -metadata: - name: ts-payment-mongo -spec: - selector: - matchLabels: - app: ts-payment-mongo - replicas: 1 - template: - metadata: - labels: - app: ts-payment-mongo - spec: - containers: - - name: ts-payment-mongo - image: mongo - imagePullPolicy: IfNotPresent - ports: - - containerPort: 27017 - resources: - requests: - cpu: 50m - memory: 100Mi - ---- - -apiVersion: apps/v1 -kind: Deployment -metadata: - name: ts-assurance-mongo -spec: - selector: - matchLabels: - app: ts-assurance-mongo - replicas: 1 - template: - metadata: - labels: - app: ts-assurance-mongo - spec: - containers: - - name: ts-assurance-mongo - image: mongo - imagePullPolicy: IfNotPresent - ports: - - containerPort: 27017 - resources: - requests: - cpu: 50m - memory: 100Mi - ---- - -apiVersion: apps/v1 -kind: Deployment -metadata: - name: ts-ticket-office-mongo -spec: - selector: - matchLabels: - app: ts-ticket-office-mongo - replicas: 1 - template: - metadata: - labels: - app: ts-ticket-office-mongo - spec: - containers: - - name: ts-ticket-office-mongo - image: mongo - imagePullPolicy: IfNotPresent - ports: - - containerPort: 27017 - resources: - requests: - cpu: 50m - memory: 100Mi - - ---- - -apiVersion: apps/v1 -kind: Deployment -metadata: - name: ts-voucher-mysql -spec: - selector: - matchLabels: - app: ts-voucher-mysql - replicas: 1 - template: - metadata: - labels: - app: ts-voucher-mysql - spec: - containers: - - name: ts-voucher-mysql - image: mysql:5.6.35 - imagePullPolicy: IfNotPresent - env: - # Use secret in real usage - - name: MYSQL_ROOT_PASSWORD - value: root - ports: - - containerPort: 3306 - resources: - requests: - cpu: 50m - memory: 100Mi - ---- - -apiVersion: apps/v1 -kind: Deployment -metadata: - name: ts-food-map-mongo -spec: - selector: - matchLabels: - app: ts-food-map-mongo - replicas: 1 - template: - metadata: - labels: - app: ts-food-map-mongo - spec: - containers: - - name: ts-food-map-mongo - image: mongo - imagePullPolicy: IfNotPresent - ports: - - containerPort: 27017 - resources: - requests: - cpu: 50m - memory: 100Mi - ---- - -apiVersion: apps/v1 -kind: Deployment -metadata: - name: ts-consign-mongo -spec: - selector: - matchLabels: - app: ts-consign-mongo - replicas: 1 - template: - metadata: - labels: - app: ts-consign-mongo - spec: - containers: - - name: ts-consign-mongo - image: mongo - imagePullPolicy: IfNotPresent - ports: - - containerPort: 27017 - resources: - requests: - cpu: 50m - memory: 100Mi - ---- - -apiVersion: apps/v1 -kind: Deployment -metadata: - name: ts-consign-price-mongo -spec: - selector: - matchLabels: - app: ts-consign-price-mongo - replicas: 1 - template: - metadata: - labels: - app: ts-consign-price-mongo - spec: - containers: - - name: ts-consign-price-mongo - image: mongo - imagePullPolicy: IfNotPresent - ports: - - containerPort: 27017 - resources: - requests: - cpu: 50m - memory: 100Mi - ---- - -apiVersion: apps/v1 -kind: Deployment -metadata: - name: ts-food-mongo -spec: - selector: - matchLabels: - app: ts-food-mongo - replicas: 1 - template: - metadata: - labels: - app: ts-food-mongo - spec: - containers: - - name: ts-food-mongo - image: mongo - imagePullPolicy: IfNotPresent - ports: - - containerPort: 27017 - resources: - requests: - cpu: 50m - memory: 100Mi ---- -apiVersion: apps/v1 -kind: Deployment -metadata: - name: ts-notification-mongo -spec: - selector: - matchLabels: - app: ts-notification-mongo - replicas: 1 - template: - metadata: - labels: - app: ts-notification-mongo - spec: - containers: - - name: ts-notification-mongo - image: mongo - imagePullPolicy: IfNotPresent - ports: - - containerPort: 27017 - resources: - requests: - cpu: 50m - memory: 100Mi ---- -apiVersion: v1 -kind: Service -metadata: - name: ts-notification-mongo -spec: - ports: - - port: 27017 - selector: - app: ts-notification-mongo - ---- - -apiVersion: apps/v1 -kind: Deployment -metadata: - name: ts-delivery-mongo -spec: - selector: - matchLabels: - app: ts-delivery-mongo - replicas: 1 - template: - metadata: - labels: - app: ts-delivery-mongo - spec: - containers: - - name: ts-delivery-mongo - image: mongo - imagePullPolicy: IfNotPresent - ports: - - containerPort: 27017 - resources: - requests: - cpu: 50m - memory: 100Mi - ---- -apiVersion: v1 -kind: Service -metadata: - name: ts-delivery-mongo -spec: - ports: - - port: 27017 - selector: - app: ts-delivery-mongo - ---- - -apiVersion: apps/v1 -kind: Deployment -metadata: - name: rabbitmq -spec: - selector: - matchLabels: - app: rabbitmq - replicas: 1 - template: - metadata: - labels: - app: rabbitmq - spec: - containers: - - name: rabbitmq - image: rabbitmq:3 - imagePullPolicy: IfNotPresent - ports: - - containerPort: 5672 - resources: - requests: - cpu: 100m - memory: 200Mi ---- -apiVersion: v1 -kind: Service -metadata: - name: rabbitmq -spec: - ports: - - port: 5672 - selector: - app: rabbitmq - ---- -apiVersion: v1 -kind: Service -metadata: - name: ts-user-mongo -spec: - ports: - - port: 27017 - selector: - app: ts-user-mongo - ---- -apiVersion: v1 -kind: Service -metadata: - name: ts-auth-mongo -spec: - ports: - - port: 27017 - selector: - app: ts-auth-mongo ---- - -apiVersion: v1 -kind: Service -metadata: - name: ts-route-mongo -spec: - ports: - - port: 27017 - selector: - app: ts-route-mongo - ---- - -apiVersion: v1 -kind: Service -metadata: - name: ts-contacts-mongo -spec: - ports: - - port: 27017 - selector: - app: ts-contacts-mongo - ---- - -apiVersion: v1 -kind: Service -metadata: - name: ts-order-mongo -spec: - ports: - - port: 27017 - selector: - app: ts-order-mongo - ---- - -apiVersion: v1 -kind: Service -metadata: - name: ts-order-other-mongo -spec: - ports: - - port: 27017 - selector: - app: ts-order-other-mongo - ---- - -apiVersion: v1 -kind: Service -metadata: - name: ts-config-mongo -spec: - ports: - - port: 27017 - selector: - app: ts-config-mongo - ---- - -apiVersion: v1 -kind: Service -metadata: - name: ts-station-mongo -spec: - ports: - - port: 27017 - selector: - app: ts-station-mongo - ---- - -apiVersion: v1 -kind: Service -metadata: - name: ts-train-mongo -spec: - ports: - - port: 27017 - selector: - app: ts-train-mongo - ---- - -apiVersion: v1 -kind: Service -metadata: - name: ts-travel-mongo -spec: - ports: - - port: 27017 - selector: - app: ts-travel-mongo - ---- - -apiVersion: v1 -kind: Service -metadata: - name: ts-travel2-mongo -spec: - ports: - - port: 27017 - selector: - app: ts-travel2-mongo - ---- - -apiVersion: v1 -kind: Service -metadata: - name: ts-price-mongo -spec: - ports: - - port: 27017 - selector: - app: ts-price-mongo - ---- - -apiVersion: v1 -kind: Service -metadata: - name: ts-security-mongo -spec: - ports: - - port: 27017 - selector: - app: ts-security-mongo - ---- - -apiVersion: v1 -kind: Service -metadata: - name: ts-inside-payment-mongo -spec: - ports: - - port: 27017 - selector: - app: ts-inside-payment-mongo - ---- - -apiVersion: v1 -kind: Service -metadata: - name: ts-payment-mongo -spec: - ports: - - port: 27017 - selector: - app: ts-payment-mongo - ---- - -apiVersion: v1 -kind: Service -metadata: - name: ts-assurance-mongo -spec: - ports: - - port: 27017 - selector: - app: ts-assurance-mongo - ---- - -apiVersion: v1 -kind: Service -metadata: - name: ts-ticket-office-mongo -spec: - ports: - - port: 27017 - selector: - app: ts-ticket-office-mongo - ---- - -apiVersion: v1 -kind: Service -metadata: - name: ts-voucher-mysql -spec: - ports: - - port: 3306 - selector: - app: ts-voucher-mysql - ---- - -apiVersion: v1 -kind: Service -metadata: - name: ts-food-map-mongo -spec: - ports: - - port: 27017 - selector: - app: ts-food-map-mongo - ---- - -apiVersion: v1 -kind: Service -metadata: - name: ts-consign-mongo -spec: - ports: - - port: 27017 - selector: - app: ts-consign-mongo - ---- - -apiVersion: v1 -kind: Service -metadata: - name: ts-consign-price-mongo -spec: - ports: - - port: 27017 - selector: - app: ts-consign-price-mongo - ---- - -apiVersion: v1 -kind: Service -metadata: - name: ts-food-mongo -spec: - ports: - - port: 27017 - selector: - app: ts-food-mongo - diff --git a/deployment/kubernetes-manifests/quickstart-k8s/quickstart-ts-deployment-part3.yml b/deployment/kubernetes-manifests/quickstart-k8s/quickstart-ts-deployment-part3.yml deleted file mode 100644 index 67ff2f7aa..000000000 --- a/deployment/kubernetes-manifests/quickstart-k8s/quickstart-ts-deployment-part3.yml +++ /dev/null @@ -1,43 +0,0 @@ -apiVersion: apps/v1 -kind: Deployment -metadata: - name: ts-ui-dashboard -spec: - selector: - matchLabels: - app: ts-ui-dashboard - replicas: 1 - template: - metadata: - labels: - app: ts-ui-dashboard - spec: - containers: - - name: ts-ui-dashboard - image: codewisdom/ts-ui-dashboard:0.2.0 - imagePullPolicy: Always - ports: - - containerPort: 8080 - resources: - requests: - cpu: 50m - memory: 100Mi - limits: - cpu: 500m - memory: 500Mi - ---- -apiVersion: v1 -kind: Service -metadata: - name: ts-ui-dashboard -spec: - type: NodePort - ports: - - name: http - port: 8080 - nodePort: 32677 - selector: - app: ts-ui-dashboard ---- - diff --git a/deployment/kubernetes-manifests/quickstart-k8s/quickstart-ts-deployment-part2.yml b/deployment/kubernetes-manifests/quickstart-k8s/yamls/deploy.yaml.sample similarity index 66% rename from deployment/kubernetes-manifests/quickstart-k8s/quickstart-ts-deployment-part2.yml rename to deployment/kubernetes-manifests/quickstart-k8s/yamls/deploy.yaml.sample index 38d6a87dc..88b8a89a5 100644 --- a/deployment/kubernetes-manifests/quickstart-k8s/quickstart-ts-deployment-part2.yml +++ b/deployment/kubernetes-manifests/quickstart-k8s/yamls/deploy.yaml.sample @@ -14,22 +14,25 @@ spec: spec: containers: - name: ts-admin-basic-info-service - image: codewisdom/ts-admin-basic-info-service:0.2.0 - imagePullPolicy: Always + image: codewisdom/ts-admin-basic-info-service:1.0.0 + imagePullPolicy: IfNotPresent env: - name: NODE_IP valueFrom: fieldRef: fieldPath: status.hostIP + envFrom: + - configMapRef: + name: nacos ports: - containerPort: 18767 resources: requests: cpu: 100m - memory: 100Mi + memory: 300Mi limits: cpu: 500m - memory: 500Mi + memory: 2000Mi readinessProbe: tcpSocket: port: 18767 @@ -37,8 +40,6 @@ spec: periodSeconds: 10 timeoutSeconds: 5 --- - - apiVersion: apps/v1 kind: Deployment metadata: @@ -55,22 +56,25 @@ spec: spec: containers: - name: ts-admin-order-service - image: codewisdom/ts-admin-order-service:0.2.0 - imagePullPolicy: Always + image: codewisdom/ts-admin-order-service:1.0.0 + imagePullPolicy: IfNotPresent env: - name: NODE_IP valueFrom: fieldRef: fieldPath: status.hostIP + envFrom: + - configMapRef: + name: nacos ports: - containerPort: 16112 resources: requests: cpu: 100m - memory: 100Mi + memory: 300Mi limits: cpu: 500m - memory: 500Mi + memory: 2000Mi readinessProbe: tcpSocket: port: 16112 @@ -78,7 +82,6 @@ spec: periodSeconds: 10 timeoutSeconds: 5 --- - apiVersion: apps/v1 kind: Deployment metadata: @@ -95,22 +98,25 @@ spec: spec: containers: - name: ts-admin-route-service - image: codewisdom/ts-admin-route-service:0.2.0 - imagePullPolicy: Always + image: codewisdom/ts-admin-route-service:1.0.0 + imagePullPolicy: IfNotPresent env: - name: NODE_IP valueFrom: fieldRef: fieldPath: status.hostIP + envFrom: + - configMapRef: + name: nacos ports: - containerPort: 16113 resources: requests: cpu: 100m - memory: 100Mi + memory: 300Mi limits: cpu: 500m - memory: 500Mi + memory: 2000Mi readinessProbe: tcpSocket: port: 16113 @@ -118,7 +124,6 @@ spec: periodSeconds: 10 timeoutSeconds: 5 --- - apiVersion: apps/v1 kind: Deployment metadata: @@ -135,22 +140,25 @@ spec: spec: containers: - name: ts-admin-travel-service - image: codewisdom/ts-admin-travel-service:0.2.0 - imagePullPolicy: Always + image: codewisdom/ts-admin-travel-service:1.0.0 + imagePullPolicy: IfNotPresent env: - name: NODE_IP valueFrom: fieldRef: fieldPath: status.hostIP + envFrom: + - configMapRef: + name: nacos ports: - containerPort: 16114 resources: requests: cpu: 100m - memory: 100Mi + memory: 300Mi limits: cpu: 500m - memory: 500Mi + memory: 2000Mi readinessProbe: tcpSocket: port: 16114 @@ -158,7 +166,6 @@ spec: periodSeconds: 10 timeoutSeconds: 5 --- - apiVersion: apps/v1 kind: Deployment metadata: @@ -175,22 +182,25 @@ spec: spec: containers: - name: ts-admin-user-service - image: codewisdom/ts-admin-user-service:0.2.0 - imagePullPolicy: Always + image: codewisdom/ts-admin-user-service:1.0.0 + imagePullPolicy: IfNotPresent env: - name: NODE_IP valueFrom: fieldRef: fieldPath: status.hostIP + envFrom: + - configMapRef: + name: nacos ports: - containerPort: 16115 resources: requests: cpu: 100m - memory: 100Mi + memory: 300Mi limits: cpu: 500m - memory: 500Mi + memory: 2000Mi readinessProbe: tcpSocket: port: 16115 @@ -198,7 +208,6 @@ spec: periodSeconds: 10 timeoutSeconds: 5 --- - apiVersion: apps/v1 kind: Deployment metadata: @@ -215,22 +224,27 @@ spec: spec: containers: - name: ts-assurance-service - image: codewisdom/ts-assurance-service:0.2.0 - imagePullPolicy: Always + image: codewisdom/ts-assurance-service:1.0.0 + imagePullPolicy: IfNotPresent env: - name: NODE_IP valueFrom: fieldRef: fieldPath: status.hostIP + envFrom: + - secretRef: + name: ts-assurance-mysql + - configMapRef: + name: nacos ports: - containerPort: 18888 resources: requests: cpu: 100m - memory: 100Mi + memory: 300Mi limits: cpu: 500m - memory: 500Mi + memory: 2000Mi readinessProbe: tcpSocket: port: 18888 @@ -238,7 +252,92 @@ spec: periodSeconds: 10 timeoutSeconds: 5 --- - +apiVersion: apps/v1 +kind: Deployment +metadata: + name: ts-auth-service +spec: + selector: + matchLabels: + app: ts-auth-service + replicas: 1 + template: + metadata: + labels: + app: ts-auth-service + spec: + containers: + - name: ts-auth-service + image: codewisdom/ts-auth-service:1.0.0 + imagePullPolicy: IfNotPresent + env: + - name: NODE_IP + valueFrom: + fieldRef: + fieldPath: status.hostIP + envFrom: + - secretRef: + name: ts-auth-mysql + - configMapRef: + name: nacos + ports: + - containerPort: 12340 + resources: + requests: + cpu: 100m + memory: 300Mi + limits: + cpu: 500m + memory: 2000Mi + readinessProbe: + tcpSocket: + port: 12340 + initialDelaySeconds: 60 + periodSeconds: 10 + timeoutSeconds: 5 +--- +apiVersion: apps/v1 +kind: Deployment +metadata: + name: ts-avatar-service +spec: + selector: + matchLabels: + app: ts-avatar-service + replicas: 1 + template: + metadata: + labels: + app: ts-avatar-service + spec: + containers: + - name: ts-avatar-service + image: codewisdom/ts-avatar-service:0.2.0 + imagePullPolicy: IfNotPresent + env: + - name: NODE_IP + valueFrom: + fieldRef: + fieldPath: status.hostIP + envFrom: + - configMapRef: + name: nacos + ports: + - containerPort: 17001 + resources: + requests: + cpu: 100m + memory: 300Mi + limits: + cpu: 500m + memory: 2000Mi + readinessProbe: + tcpSocket: + port: 17001 + initialDelaySeconds: 60 + periodSeconds: 10 + timeoutSeconds: 5 +--- apiVersion: apps/v1 kind: Deployment metadata: @@ -255,22 +354,25 @@ spec: spec: containers: - name: ts-basic-service - image: codewisdom/ts-basic-service:0.2.0 - imagePullPolicy: Always + image: codewisdom/ts-basic-service:1.0.0 + imagePullPolicy: IfNotPresent env: - name: NODE_IP valueFrom: fieldRef: fieldPath: status.hostIP + envFrom: + - configMapRef: + name: nacos ports: - containerPort: 15680 resources: requests: cpu: 100m - memory: 100Mi + memory: 300Mi limits: cpu: 500m - memory: 500Mi + memory: 2000Mi readinessProbe: tcpSocket: port: 15680 @@ -278,7 +380,6 @@ spec: periodSeconds: 10 timeoutSeconds: 5 --- - apiVersion: apps/v1 kind: Deployment metadata: @@ -295,22 +396,25 @@ spec: spec: containers: - name: ts-cancel-service - image: codewisdom/ts-cancel-service:0.2.0 - imagePullPolicy: Always + image: codewisdom/ts-cancel-service:1.0.0 + imagePullPolicy: IfNotPresent env: - name: NODE_IP valueFrom: fieldRef: fieldPath: status.hostIP + envFrom: + - configMapRef: + name: nacos ports: - containerPort: 18885 resources: requests: cpu: 100m - memory: 100Mi + memory: 300Mi limits: cpu: 500m - memory: 500Mi + memory: 2000Mi readinessProbe: tcpSocket: port: 18885 @@ -318,7 +422,6 @@ spec: periodSeconds: 10 timeoutSeconds: 5 --- - apiVersion: apps/v1 kind: Deployment metadata: @@ -335,22 +438,27 @@ spec: spec: containers: - name: ts-config-service - image: codewisdom/ts-config-service:0.2.0 - imagePullPolicy: Always + image: codewisdom/ts-config-service:1.0.0 + imagePullPolicy: IfNotPresent env: - name: NODE_IP valueFrom: fieldRef: fieldPath: status.hostIP + envFrom: + - secretRef: + name: ts-config-mysql + - configMapRef: + name: nacos ports: - containerPort: 15679 resources: requests: cpu: 100m - memory: 100Mi + memory: 300Mi limits: cpu: 500m - memory: 500Mi + memory: 2000Mi readinessProbe: tcpSocket: port: 15679 @@ -358,7 +466,6 @@ spec: periodSeconds: 10 timeoutSeconds: 5 --- - apiVersion: apps/v1 kind: Deployment metadata: @@ -375,22 +482,27 @@ spec: spec: containers: - name: ts-consign-price-service - image: codewisdom/ts-consign-price-service:0.2.0 - imagePullPolicy: Always + image: codewisdom/ts-consign-price-service:1.0.0 + imagePullPolicy: IfNotPresent env: - name: NODE_IP valueFrom: fieldRef: fieldPath: status.hostIP + envFrom: + - secretRef: + name: ts-consign-price-mysql + - configMapRef: + name: nacos ports: - containerPort: 16110 resources: requests: cpu: 100m - memory: 100Mi + memory: 300Mi limits: cpu: 500m - memory: 500Mi + memory: 2000Mi readinessProbe: tcpSocket: port: 16110 @@ -398,7 +510,6 @@ spec: periodSeconds: 10 timeoutSeconds: 5 --- - apiVersion: apps/v1 kind: Deployment metadata: @@ -415,22 +526,27 @@ spec: spec: containers: - name: ts-consign-service - image: codewisdom/ts-consign-service:0.2.0 - imagePullPolicy: Always + image: codewisdom/ts-consign-service:1.0.0 + imagePullPolicy: IfNotPresent env: - name: NODE_IP valueFrom: fieldRef: fieldPath: status.hostIP + envFrom: + - secretRef: + name: ts-consign-mysql + - configMapRef: + name: nacos ports: - containerPort: 16111 resources: requests: cpu: 100m - memory: 100Mi + memory: 300Mi limits: cpu: 500m - memory: 500Mi + memory: 2000Mi readinessProbe: tcpSocket: port: 16111 @@ -438,7 +554,6 @@ spec: periodSeconds: 10 timeoutSeconds: 5 --- - apiVersion: apps/v1 kind: Deployment metadata: @@ -455,22 +570,27 @@ spec: spec: containers: - name: ts-contacts-service - image: codewisdom/ts-contacts-service:0.2.0 - imagePullPolicy: Always + image: codewisdom/ts-contacts-service:1.0.0 + imagePullPolicy: IfNotPresent env: - name: NODE_IP valueFrom: fieldRef: fieldPath: status.hostIP + envFrom: + - secretRef: + name: ts-contacts-mysql + - configMapRef: + name: nacos ports: - containerPort: 12347 resources: requests: cpu: 100m - memory: 100Mi + memory: 300Mi limits: cpu: 500m - memory: 500Mi + memory: 2000Mi readinessProbe: tcpSocket: port: 12347 @@ -478,87 +598,94 @@ spec: periodSeconds: 10 timeoutSeconds: 5 --- - apiVersion: apps/v1 kind: Deployment metadata: - name: ts-execute-service + name: ts-delivery-service spec: selector: matchLabels: - app: ts-execute-service + app: ts-delivery-service replicas: 1 template: metadata: labels: - app: ts-execute-service + app: ts-delivery-service spec: containers: - - name: ts-execute-service - image: codewisdom/ts-execute-service:0.2.0 - imagePullPolicy: Always + - name: ts-delivery-service + image: codewisdom/ts-delivery-service:1.0.0 + imagePullPolicy: IfNotPresent env: - name: NODE_IP valueFrom: fieldRef: fieldPath: status.hostIP + envFrom: + - secretRef: + name: ts-delivery-mysql + - configMapRef: + name: rabbitmq + - configMapRef: + name: nacos ports: - - containerPort: 12386 + - containerPort: 18808 resources: requests: cpu: 100m - memory: 100Mi + memory: 300Mi limits: cpu: 500m - memory: 500Mi + memory: 2000Mi readinessProbe: tcpSocket: - port: 12386 + port: 18808 initialDelaySeconds: 60 periodSeconds: 10 timeoutSeconds: 5 --- - apiVersion: apps/v1 kind: Deployment metadata: - name: ts-food-map-service + name: ts-execute-service spec: selector: matchLabels: - app: ts-food-map-service + app: ts-execute-service replicas: 1 template: metadata: labels: - app: ts-food-map-service + app: ts-execute-service spec: containers: - - name: ts-food-map-service - image: codewisdom/ts-food-map-service:0.2.0 - imagePullPolicy: Always + - name: ts-execute-service + image: codewisdom/ts-execute-service:1.0.0 + imagePullPolicy: IfNotPresent env: - name: NODE_IP valueFrom: fieldRef: fieldPath: status.hostIP + envFrom: + - configMapRef: + name: nacos ports: - - containerPort: 18855 + - containerPort: 12386 resources: requests: cpu: 100m - memory: 100Mi + memory: 300Mi limits: cpu: 500m - memory: 500Mi + memory: 2000Mi readinessProbe: tcpSocket: - port: 18855 + port: 12386 initialDelaySeconds: 60 periodSeconds: 10 timeoutSeconds: 5 --- - apiVersion: apps/v1 kind: Deployment metadata: @@ -575,26 +702,29 @@ spec: spec: containers: - name: ts-food-service - image: codewisdom/ts-food-service:0.2.0 - imagePullPolicy: Always + image: codewisdom/ts-food-service:1.0.0 + imagePullPolicy: IfNotPresent env: - name: NODE_IP valueFrom: fieldRef: fieldPath: status.hostIP - - name: rabbitmq_host - value: "rabbitmq" - - name: rabbitmq_port - value: "5672" + envFrom: + - configMapRef: + name: nacos + - configMapRef: + name: rabbitmq + - secretRef: + name: ts-food-mysql ports: - containerPort: 18856 resources: requests: cpu: 100m - memory: 100Mi + memory: 300Mi limits: cpu: 500m - memory: 500Mi + memory: 2000Mi readinessProbe: tcpSocket: port: 18856 @@ -602,87 +732,136 @@ spec: periodSeconds: 10 timeoutSeconds: 5 --- - apiVersion: apps/v1 kind: Deployment metadata: - name: ts-inside-payment-service + name: ts-food-delivery-service spec: selector: matchLabels: - app: ts-inside-payment-service + app: ts-food-delivery-service replicas: 1 template: metadata: labels: - app: ts-inside-payment-service + app: ts-food-delivery-service spec: containers: - - name: ts-inside-payment-service - image: codewisdom/ts-inside-payment-service:0.2.0 - imagePullPolicy: Always + - name: ts-food-delivery-service + image: codewisdom/ts-food-delivery-service:1.0.0 + imagePullPolicy: IfNotPresent env: - name: NODE_IP valueFrom: fieldRef: fieldPath: status.hostIP + envFrom: + - secretRef: + name: ts-food-delivery-mysql + - configMapRef: + name: nacos ports: - - containerPort: 18673 + - containerPort: 18957 resources: requests: cpu: 100m - memory: 100Mi + memory: 300Mi limits: cpu: 500m - memory: 500Mi + memory: 2000Mi readinessProbe: tcpSocket: - port: 18673 + port: 18957 initialDelaySeconds: 60 periodSeconds: 10 timeoutSeconds: 5 --- - apiVersion: apps/v1 kind: Deployment metadata: - name: ts-auth-service + name: ts-gateway-service spec: selector: matchLabels: - app: ts-auth-service + app: ts-gateway-service replicas: 1 template: metadata: labels: - app: ts-auth-service + app: ts-gateway-service spec: containers: - - name: ts-auth-service - image: codewisdom/ts-auth-service:0.2.0 - imagePullPolicy: Always + - name: ts-gateway-service + image: codewisdom/ts-gateway-service:1.0.0 + imagePullPolicy: IfNotPresent env: - name: NODE_IP valueFrom: fieldRef: fieldPath: status.hostIP + envFrom: + - configMapRef: + name: nacos ports: - - containerPort: 12340 + - containerPort: 18888 resources: requests: cpu: 100m - memory: 100Mi + memory: 300Mi limits: cpu: 500m - memory: 500Mi + memory: 2000Mi readinessProbe: tcpSocket: - port: 12340 + port: 18888 + initialDelaySeconds: 60 + periodSeconds: 10 + timeoutSeconds: 5 +--- +apiVersion: apps/v1 +kind: Deployment +metadata: + name: ts-inside-payment-service +spec: + selector: + matchLabels: + app: ts-inside-payment-service + replicas: 1 + template: + metadata: + labels: + app: ts-inside-payment-service + spec: + containers: + - name: ts-inside-payment-service + image: codewisdom/ts-inside-payment-service:1.0.0 + imagePullPolicy: IfNotPresent + env: + - name: NODE_IP + valueFrom: + fieldRef: + fieldPath: status.hostIP + envFrom: + - secretRef: + name: ts-inside-payment-mysql + - configMapRef: + name: nacos + ports: + - containerPort: 18673 + resources: + requests: + cpu: 100m + memory: 300Mi + limits: + cpu: 500m + memory: 2000Mi + readinessProbe: + tcpSocket: + port: 18673 initialDelaySeconds: 60 periodSeconds: 10 timeoutSeconds: 5 --- - apiVersion: apps/v1 kind: Deployment metadata: @@ -699,22 +878,25 @@ spec: spec: containers: - name: ts-news-service - image: codewisdom/ts-news-service:0.2.0 - imagePullPolicy: Always + image: codewisdom/ts-news-service:1.0.0 + imagePullPolicy: IfNotPresent env: - name: NODE_IP valueFrom: fieldRef: fieldPath: status.hostIP + envFrom: + - configMapRef: + name: nacos ports: - containerPort: 12862 resources: requests: cpu: 100m - memory: 100Mi + memory: 300Mi limits: cpu: 500m - memory: 500Mi + memory: 2000Mi readinessProbe: tcpSocket: port: 12862 @@ -722,7 +904,6 @@ spec: periodSeconds: 10 timeoutSeconds: 5 --- - apiVersion: apps/v1 kind: Deployment metadata: @@ -739,30 +920,29 @@ spec: spec: containers: - name: ts-notification-service - image: codewisdom/ts-notification-service:0.2.0 - imagePullPolicy: Always + image: codewisdom/ts-notification-service:1.0.0 + imagePullPolicy: IfNotPresent env: - name: NODE_IP valueFrom: fieldRef: fieldPath: status.hostIP - - name: email_address - value: "trainticket_notify@163.com" - - name: email_password - value: "GZKSCXHBOLKMCLDQ" - - name: rabbitmq_host - value: "rabbitmq" - - name: rabbitmq_port - value: "5672" + envFrom: + - secretRef: + name: ts-notification-mysql + - configMapRef: + name: nacos + - configMapRef: + name: rabbitmq ports: - containerPort: 17853 resources: requests: cpu: 100m - memory: 100Mi + memory: 300Mi limits: cpu: 500m - memory: 500Mi + memory: 2000Mi readinessProbe: tcpSocket: port: 17853 @@ -770,7 +950,6 @@ spec: periodSeconds: 10 timeoutSeconds: 5 --- - apiVersion: apps/v1 kind: Deployment metadata: @@ -787,22 +966,29 @@ spec: spec: containers: - name: ts-order-other-service - image: codewisdom/ts-order-other-service:0.2.0 - imagePullPolicy: Always + image: codewisdom/ts-order-other-service:1.0.0 + imagePullPolicy: IfNotPresent env: - name: NODE_IP valueFrom: fieldRef: fieldPath: status.hostIP + envFrom: + - secretRef: + name: ts-order-other-mysql + - configMapRef: + name: nacos + - configMapRef: + name: rabbitmq ports: - containerPort: 12032 resources: requests: cpu: 100m - memory: 100Mi + memory: 300Mi limits: cpu: 500m - memory: 500Mi + memory: 2000Mi readinessProbe: tcpSocket: port: 12032 @@ -810,7 +996,6 @@ spec: periodSeconds: 10 timeoutSeconds: 5 --- - apiVersion: apps/v1 kind: Deployment metadata: @@ -827,22 +1012,29 @@ spec: spec: containers: - name: ts-order-service - image: codewisdom/ts-order-service:0.2.0 - imagePullPolicy: Always + image: codewisdom/ts-order-service:1.0.0 + imagePullPolicy: IfNotPresent env: - name: NODE_IP valueFrom: fieldRef: fieldPath: status.hostIP + envFrom: + - secretRef: + name: ts-order-mysql + - configMapRef: + name: nacos + - configMapRef: + name: rabbitmq ports: - containerPort: 12031 resources: requests: cpu: 100m - memory: 100Mi + memory: 300Mi limits: cpu: 500m - memory: 500Mi + memory: 2000Mi readinessProbe: tcpSocket: port: 12031 @@ -850,7 +1042,6 @@ spec: periodSeconds: 10 timeoutSeconds: 5 --- - apiVersion: apps/v1 kind: Deployment metadata: @@ -867,22 +1058,27 @@ spec: spec: containers: - name: ts-payment-service - image: codewisdom/ts-payment-service:0.2.0 - imagePullPolicy: Always + image: codewisdom/ts-payment-service:1.0.0 + imagePullPolicy: IfNotPresent env: - name: NODE_IP valueFrom: fieldRef: fieldPath: status.hostIP + envFrom: + - secretRef: + name: ts-payment-mysql + - configMapRef: + name: nacos ports: - containerPort: 19001 resources: requests: cpu: 100m - memory: 100Mi + memory: 300Mi limits: cpu: 500m - memory: 500Mi + memory: 2000Mi readinessProbe: tcpSocket: port: 19001 @@ -890,7 +1086,6 @@ spec: periodSeconds: 10 timeoutSeconds: 5 --- - apiVersion: apps/v1 kind: Deployment metadata: @@ -907,26 +1102,27 @@ spec: spec: containers: - name: ts-preserve-other-service - image: codewisdom/ts-preserve-other-service:0.2.0 - imagePullPolicy: Always + image: codewisdom/ts-preserve-other-service:1.0.0 + imagePullPolicy: IfNotPresent env: - name: NODE_IP valueFrom: fieldRef: fieldPath: status.hostIP - - name: rabbitmq_host - value: "rabbitmq" - - name: rabbitmq_port - value: "5672" + envFrom: + - configMapRef: + name: nacos + - configMapRef: + name: rabbitmq ports: - containerPort: 14569 resources: requests: cpu: 100m - memory: 100Mi + memory: 300Mi limits: cpu: 500m - memory: 500Mi + memory: 2000Mi readinessProbe: tcpSocket: port: 14569 @@ -934,7 +1130,6 @@ spec: periodSeconds: 10 timeoutSeconds: 5 --- - apiVersion: apps/v1 kind: Deployment metadata: @@ -951,26 +1146,27 @@ spec: spec: containers: - name: ts-preserve-service - image: codewisdom/ts-preserve-service:0.2.0 - imagePullPolicy: Always + image: codewisdom/ts-preserve-service:1.0.0 + imagePullPolicy: IfNotPresent env: - name: NODE_IP valueFrom: fieldRef: fieldPath: status.hostIP - - name: rabbitmq_host - value: "rabbitmq" - - name: rabbitmq_port - value: "5672" + envFrom: + - configMapRef: + name: nacos + - configMapRef: + name: rabbitmq ports: - containerPort: 14568 resources: requests: cpu: 100m - memory: 100Mi + memory: 300Mi limits: cpu: 500m - memory: 500Mi + memory: 2000Mi readinessProbe: tcpSocket: port: 14568 @@ -978,7 +1174,6 @@ spec: periodSeconds: 10 timeoutSeconds: 5 --- - apiVersion: apps/v1 kind: Deployment metadata: @@ -995,22 +1190,27 @@ spec: spec: containers: - name: ts-price-service - image: codewisdom/ts-price-service:0.2.0 - imagePullPolicy: Always + image: codewisdom/ts-price-service:1.0.0 + imagePullPolicy: IfNotPresent env: - name: NODE_IP valueFrom: fieldRef: fieldPath: status.hostIP + envFrom: + - secretRef: + name: ts-price-mysql + - configMapRef: + name: nacos ports: - containerPort: 16579 resources: requests: cpu: 100m - memory: 100Mi + memory: 300Mi limits: cpu: 500m - memory: 500Mi + memory: 2000Mi readinessProbe: tcpSocket: port: 16579 @@ -1018,7 +1218,6 @@ spec: periodSeconds: 10 timeoutSeconds: 5 --- - apiVersion: apps/v1 kind: Deployment metadata: @@ -1035,22 +1234,27 @@ spec: spec: containers: - name: ts-rebook-service - image: codewisdom/ts-rebook-service:0.2.0 - imagePullPolicy: Always + image: codewisdom/ts-rebook-service:1.0.0 + imagePullPolicy: IfNotPresent env: - name: NODE_IP valueFrom: fieldRef: fieldPath: status.hostIP + envFrom: + - configMapRef: + name: nacos + - configMapRef: + name: rabbitmq ports: - containerPort: 18886 resources: requests: cpu: 100m - memory: 100Mi + memory: 300Mi limits: cpu: 500m - memory: 500Mi + memory: 2000Mi readinessProbe: tcpSocket: port: 18886 @@ -1058,7 +1262,6 @@ spec: periodSeconds: 10 timeoutSeconds: 5 --- - apiVersion: apps/v1 kind: Deployment metadata: @@ -1075,22 +1278,25 @@ spec: spec: containers: - name: ts-route-plan-service - image: codewisdom/ts-route-plan-service:0.2.0 - imagePullPolicy: Always + image: codewisdom/ts-route-plan-service:1.0.0 + imagePullPolicy: IfNotPresent env: - name: NODE_IP valueFrom: fieldRef: fieldPath: status.hostIP + envFrom: + - configMapRef: + name: nacos ports: - containerPort: 14578 resources: requests: cpu: 100m - memory: 100Mi + memory: 300Mi limits: cpu: 500m - memory: 500Mi + memory: 2000Mi readinessProbe: tcpSocket: port: 14578 @@ -1098,7 +1304,6 @@ spec: periodSeconds: 10 timeoutSeconds: 5 --- - apiVersion: apps/v1 kind: Deployment metadata: @@ -1115,22 +1320,27 @@ spec: spec: containers: - name: ts-route-service - image: codewisdom/ts-route-service:0.2.0 - imagePullPolicy: Always + image: codewisdom/ts-route-service:1.0.0 + imagePullPolicy: IfNotPresent env: - name: NODE_IP valueFrom: fieldRef: fieldPath: status.hostIP + envFrom: + - secretRef: + name: ts-route-mysql + - configMapRef: + name: nacos ports: - containerPort: 11178 resources: requests: cpu: 100m - memory: 100Mi + memory: 300Mi limits: cpu: 500m - memory: 500Mi + memory: 2000Mi readinessProbe: tcpSocket: port: 11178 @@ -1138,7 +1348,6 @@ spec: periodSeconds: 10 timeoutSeconds: 5 --- - apiVersion: apps/v1 kind: Deployment metadata: @@ -1155,22 +1364,25 @@ spec: spec: containers: - name: ts-seat-service - image: codewisdom/ts-seat-service:0.2.0 - imagePullPolicy: Always + image: codewisdom/ts-seat-service:1.0.0 + imagePullPolicy: IfNotPresent env: - name: NODE_IP valueFrom: fieldRef: fieldPath: status.hostIP + envFrom: + - configMapRef: + name: nacos ports: - containerPort: 18898 resources: requests: cpu: 100m - memory: 100Mi + memory: 300Mi limits: cpu: 500m - memory: 500Mi + memory: 2000Mi readinessProbe: tcpSocket: port: 18898 @@ -1178,7 +1390,6 @@ spec: periodSeconds: 10 timeoutSeconds: 5 --- - apiVersion: apps/v1 kind: Deployment metadata: @@ -1195,22 +1406,27 @@ spec: spec: containers: - name: ts-security-service - image: codewisdom/ts-security-service:0.2.0 - imagePullPolicy: Always + image: codewisdom/ts-security-service:1.0.0 + imagePullPolicy: IfNotPresent env: - name: NODE_IP valueFrom: fieldRef: fieldPath: status.hostIP + envFrom: + - secretRef: + name: ts-security-mysql + - configMapRef: + name: nacos ports: - containerPort: 11188 resources: requests: cpu: 100m - memory: 100Mi + memory: 300Mi limits: cpu: 500m - memory: 500Mi + memory: 2000Mi readinessProbe: tcpSocket: port: 11188 @@ -1218,47 +1434,50 @@ spec: periodSeconds: 10 timeoutSeconds: 5 --- - apiVersion: apps/v1 kind: Deployment metadata: - name: ts-user-service + name: ts-station-food-service spec: selector: matchLabels: - app: ts-user-service + app: ts-station-food-service replicas: 1 template: metadata: labels: - app: ts-user-service + app: ts-station-food-service spec: containers: - - name: ts-user-service - image: codewisdom/ts-user-service:0.2.0 - imagePullPolicy: Always + - name: ts-station-food-service + image: codewisdom/ts-station-food-service:1.0.0 + imagePullPolicy: IfNotPresent env: - name: NODE_IP valueFrom: fieldRef: fieldPath: status.hostIP + envFrom: + - secretRef: + name: ts-station-food-mysql + - configMapRef: + name: nacos ports: - - containerPort: 12342 + - containerPort: 18855 resources: requests: cpu: 100m - memory: 100Mi + memory: 300Mi limits: cpu: 500m - memory: 500Mi + memory: 2000Mi readinessProbe: tcpSocket: - port: 12342 + port: 18855 initialDelaySeconds: 60 periodSeconds: 10 timeoutSeconds: 5 --- - apiVersion: apps/v1 kind: Deployment metadata: @@ -1275,22 +1494,27 @@ spec: spec: containers: - name: ts-station-service - image: codewisdom/ts-station-service:0.2.0 - imagePullPolicy: Always + image: codewisdom/ts-station-service:1.0.0 + imagePullPolicy: IfNotPresent env: - name: NODE_IP valueFrom: fieldRef: fieldPath: status.hostIP + envFrom: + - secretRef: + name: ts-station-mysql + - configMapRef: + name: nacos ports: - containerPort: 12345 resources: requests: cpu: 100m - memory: 100Mi + memory: 300Mi limits: cpu: 500m - memory: 500Mi + memory: 2000Mi readinessProbe: tcpSocket: port: 12345 @@ -1298,7 +1522,6 @@ spec: periodSeconds: 10 timeoutSeconds: 5 --- - apiVersion: apps/v1 kind: Deployment metadata: @@ -1315,22 +1538,27 @@ spec: spec: containers: - name: ts-ticket-office-service - image: codewisdom/ts-ticket-office-service:0.2.0 - imagePullPolicy: Always + image: codewisdom/ts-ticket-office-service:1.0.0 + imagePullPolicy: IfNotPresent env: - name: NODE_IP valueFrom: fieldRef: fieldPath: status.hostIP + envFrom: + - secretRef: + name: ts-ticket-office-mysql + - configMapRef: + name: nacos ports: - containerPort: 16108 resources: requests: cpu: 100m - memory: 100Mi + memory: 300Mi limits: cpu: 500m - memory: 500Mi + memory: 2000Mi readinessProbe: tcpSocket: port: 16108 @@ -1338,47 +1566,50 @@ spec: periodSeconds: 10 timeoutSeconds: 5 --- - apiVersion: apps/v1 kind: Deployment metadata: - name: ts-ticketinfo-service + name: ts-train-food-service spec: selector: matchLabels: - app: ts-ticketinfo-service + app: ts-train-food-service replicas: 1 template: metadata: labels: - app: ts-ticketinfo-service + app: ts-train-food-service spec: containers: - - name: ts-ticketinfo-service - image: codewisdom/ts-ticketinfo-service:0.2.0 - imagePullPolicy: Always + - name: ts-train-food-service + image: codewisdom/ts-train-food-service:1.0.0 + imagePullPolicy: IfNotPresent env: - name: NODE_IP valueFrom: fieldRef: fieldPath: status.hostIP + envFrom: + - secretRef: + name: ts-train-food-mysql + - configMapRef: + name: nacos ports: - - containerPort: 15681 + - containerPort: 19999 resources: requests: cpu: 100m - memory: 100Mi + memory: 300Mi limits: cpu: 500m - memory: 500Mi + memory: 2000Mi readinessProbe: tcpSocket: - port: 15681 + port: 19999 initialDelaySeconds: 60 periodSeconds: 10 timeoutSeconds: 5 --- - apiVersion: apps/v1 kind: Deployment metadata: @@ -1395,22 +1626,27 @@ spec: spec: containers: - name: ts-train-service - image: codewisdom/ts-train-service:0.2.0 - imagePullPolicy: Always + image: codewisdom/ts-train-service:1.0.0 + imagePullPolicy: IfNotPresent env: - name: NODE_IP valueFrom: fieldRef: fieldPath: status.hostIP + envFrom: + - secretRef: + name: ts-train-mysql + - configMapRef: + name: nacos ports: - containerPort: 14567 resources: requests: cpu: 100m - memory: 100Mi + memory: 300Mi limits: cpu: 500m - memory: 500Mi + memory: 2000Mi readinessProbe: tcpSocket: port: 14567 @@ -1418,172 +1654,180 @@ spec: periodSeconds: 10 timeoutSeconds: 5 --- - apiVersion: apps/v1 kind: Deployment metadata: - name: ts-travel2-service + name: ts-travel-plan-service spec: selector: matchLabels: - app: ts-travel2-service + app: ts-travel-plan-service replicas: 1 template: metadata: labels: - app: ts-travel2-service + app: ts-travel-plan-service spec: containers: - - name: ts-travel2-service - image: codewisdom/ts-travel2-service:0.2.0 - imagePullPolicy: Always + - name: ts-travel-plan-service + image: codewisdom/ts-travel-plan-service:1.0.0 + imagePullPolicy: IfNotPresent env: - name: NODE_IP valueFrom: fieldRef: fieldPath: status.hostIP + envFrom: + - configMapRef: + name: nacos ports: - - containerPort: 16346 + - containerPort: 14322 resources: requests: cpu: 100m - memory: 100Mi + memory: 300Mi limits: cpu: 500m - memory: 500Mi + memory: 2000Mi readinessProbe: tcpSocket: - port: 16346 + port: 14322 initialDelaySeconds: 60 periodSeconds: 10 timeoutSeconds: 5 --- - apiVersion: apps/v1 kind: Deployment metadata: - name: ts-travel-plan-service + name: ts-travel-service spec: selector: matchLabels: - app: ts-travel-plan-service + app: ts-travel-service replicas: 1 template: metadata: labels: - app: ts-travel-plan-service + app: ts-travel-service spec: containers: - - name: ts-travel-plan-service - image: codewisdom/ts-travel-plan-service:0.2.0 - imagePullPolicy: Always + - name: ts-travel-service + image: codewisdom/ts-travel-service:1.0.0 + imagePullPolicy: IfNotPresent env: - name: NODE_IP valueFrom: fieldRef: fieldPath: status.hostIP + envFrom: + - secretRef: + name: ts-travel-mysql + - configMapRef: + name: nacos ports: - - containerPort: 14322 + - containerPort: 12346 resources: requests: cpu: 100m - memory: 100Mi + memory: 300Mi limits: cpu: 500m - memory: 500Mi + memory: 2000Mi readinessProbe: tcpSocket: - port: 14322 + port: 12346 initialDelaySeconds: 60 periodSeconds: 10 timeoutSeconds: 5 --- - apiVersion: apps/v1 kind: Deployment metadata: - name: ts-travel-service + name: ts-travel2-service spec: selector: matchLabels: - app: ts-travel-service + app: ts-travel2-service replicas: 1 template: metadata: labels: - app: ts-travel-service + app: ts-travel2-service spec: containers: - - name: ts-travel-service - image: codewisdom/ts-travel-service:0.2.0 - imagePullPolicy: Always + - name: ts-travel2-service + image: codewisdom/ts-travel2-service:1.0.0 + imagePullPolicy: IfNotPresent env: - name: NODE_IP valueFrom: fieldRef: fieldPath: status.hostIP + envFrom: + - secretRef: + name: ts-travel2-mysql + - configMapRef: + name: nacos ports: - - containerPort: 12346 + - containerPort: 16346 resources: requests: cpu: 100m - memory: 100Mi + memory: 300Mi limits: cpu: 500m - memory: 500Mi + memory: 2000Mi readinessProbe: tcpSocket: - port: 12346 + port: 16346 initialDelaySeconds: 60 periodSeconds: 10 timeoutSeconds: 5 - --- apiVersion: apps/v1 kind: Deployment metadata: - name: ts-delivery-service + name: ts-user-service spec: selector: matchLabels: - app: ts-delivery-service + app: ts-user-service replicas: 1 template: metadata: labels: - app: ts-delivery-service + app: ts-user-service spec: containers: - - name: ts-delivery-service - image: codewisdom/ts-delivery-service:0.2.0 - imagePullPolicy: Always + - name: ts-user-service + image: codewisdom/ts-user-service:1.0.0 + imagePullPolicy: IfNotPresent env: - name: NODE_IP valueFrom: fieldRef: fieldPath: status.hostIP - - name: rabbitmq_host - value: "rabbitmq" - - name: rabbitmq_port - value: "5672" + envFrom: + - secretRef: + name: ts-user-mysql + - configMapRef: + name: nacos ports: - - containerPort: 18808 + - containerPort: 12342 resources: requests: cpu: 100m - memory: 100Mi + memory: 300Mi limits: cpu: 500m - memory: 500Mi + memory: 2000Mi readinessProbe: tcpSocket: - port: 18808 + port: 12342 initialDelaySeconds: 60 periodSeconds: 10 timeoutSeconds: 5 - --- - apiVersion: apps/v1 kind: Deployment metadata: @@ -1600,22 +1844,25 @@ spec: spec: containers: - name: ts-verification-code-service - image: codewisdom/ts-verification-code-service:0.2.0 - imagePullPolicy: Always + image: codewisdom/ts-verification-code-service:1.0.0 + imagePullPolicy: IfNotPresent env: - name: NODE_IP valueFrom: fieldRef: fieldPath: status.hostIP + envFrom: + - configMapRef: + name: nacos ports: - containerPort: 15678 resources: requests: cpu: 100m - memory: 100Mi + memory: 300Mi limits: cpu: 500m - memory: 500Mi + memory: 2000Mi readinessProbe: tcpSocket: port: 15678 @@ -1623,7 +1870,6 @@ spec: periodSeconds: 10 timeoutSeconds: 5 --- - apiVersion: apps/v1 kind: Deployment metadata: @@ -1640,22 +1886,27 @@ spec: spec: containers: - name: ts-voucher-service - image: codewisdom/ts-voucher-service:0.2.0 - imagePullPolicy: Always + image: codewisdom/ts-voucher-service:1.0.0 + imagePullPolicy: IfNotPresent env: - name: NODE_IP valueFrom: fieldRef: fieldPath: status.hostIP + envFrom: + - secretRef: + name: ts-voucher-mysql + - configMapRef: + name: nacos ports: - containerPort: 16101 resources: requests: cpu: 100m - memory: 100Mi + memory: 300Mi limits: cpu: 500m - memory: 500Mi + memory: 2000Mi readinessProbe: tcpSocket: port: 16101 @@ -1663,585 +1914,74 @@ spec: periodSeconds: 10 timeoutSeconds: 5 --- -apiVersion: v1 -kind: Service -metadata: - name: ts-admin-basic-info-service -spec: - ports: - - name: http - port: 18767 - selector: - app: ts-admin-basic-info-service - ---- -apiVersion: v1 -kind: Service -metadata: - name: ts-delivery-service -spec: - ports: - - name: http - port: 18808 - selector: - app: ts-delivery-service - ---- - -apiVersion: v1 -kind: Service -metadata: - name: ts-admin-order-service -spec: - ports: - - name: http - port: 16112 - selector: - app: ts-admin-order-service - ---- - -apiVersion: v1 -kind: Service -metadata: - name: ts-admin-route-service -spec: - ports: - - name: http - port: 16113 - selector: - app: ts-admin-route-service - ---- - -apiVersion: v1 -kind: Service -metadata: - name: ts-admin-travel-service -spec: - ports: - - name: http - port: 16114 - selector: - app: ts-admin-travel-service - ---- - -apiVersion: v1 -kind: Service -metadata: - name: ts-admin-user-service -spec: - ports: - - name: http - port: 16115 - selector: - app: ts-admin-user-service - ---- - -apiVersion: v1 -kind: Service -metadata: - name: ts-assurance-service -spec: - ports: - - name: http - port: 18888 - selector: - app: ts-assurance-service - ---- - -apiVersion: v1 -kind: Service -metadata: - name: ts-basic-service -spec: - ports: - - name: http - port: 15680 - selector: - app: ts-basic-service - ---- - -apiVersion: v1 -kind: Service -metadata: - name: ts-cancel-service -spec: - ports: - - name: http - port: 18885 - selector: - app: ts-cancel-service - ---- - -apiVersion: v1 -kind: Service -metadata: - name: ts-config-service -spec: - ports: - - name: http - port: 15679 - selector: - app: ts-config-service - ---- - -apiVersion: v1 -kind: Service -metadata: - name: ts-consign-price-service -spec: - ports: - - name: http - port: 16110 - selector: - app: ts-consign-price-service - ---- - -apiVersion: v1 -kind: Service -metadata: - name: ts-consign-service -spec: - ports: - - name: http - port: 16111 - selector: - app: ts-consign-service - ---- - -apiVersion: v1 -kind: Service -metadata: - name: ts-contacts-service -spec: - ports: - - name: http - port: 12347 - selector: - app: ts-contacts-service - ---- - -apiVersion: v1 -kind: Service -metadata: - name: ts-execute-service -spec: - ports: - - name: http - port: 12386 - selector: - app: ts-execute-service - ---- - -apiVersion: v1 -kind: Service -metadata: - name: ts-food-map-service -spec: - ports: - - name: http - port: 18855 - selector: - app: ts-food-map-service - ---- - -apiVersion: v1 -kind: Service -metadata: - name: ts-food-service -spec: - ports: - - name: http - port: 18856 - selector: - app: ts-food-service - ---- - -apiVersion: v1 -kind: Service -metadata: - name: ts-inside-payment-service -spec: - ports: - - name: http - port: 18673 - selector: - app: ts-inside-payment-service - ---- - -apiVersion: v1 -kind: Service -metadata: - name: ts-user-service -spec: - ports: - - name: http - port: 12342 - selector: - app: ts-user-service - ---- - -apiVersion: v1 -kind: Service -metadata: - name: ts-notification-service -spec: - ports: - - name: http - port: 17853 - selector: - app: ts-notification-service - ---- - -apiVersion: v1 -kind: Service -metadata: - name: ts-news-service -spec: - ports: - - name: http - port: 12862 - selector: - app: ts-news-service - ---- - -apiVersion: v1 -kind: Service -metadata: - name: ts-order-other-service -spec: - ports: - - name: http - port: 12032 - selector: - app: ts-order-other-service - ---- - -apiVersion: v1 -kind: Service -metadata: - name: ts-order-service -spec: - ports: - - name: http - port: 12031 - selector: - app: ts-order-service - ---- - -apiVersion: v1 -kind: Service -metadata: - name: ts-payment-service -spec: - ports: - - name: http - port: 19001 - selector: - app: ts-payment-service - ---- - -apiVersion: v1 -kind: Service -metadata: - name: ts-preserve-other-service -spec: - ports: - - name: http - port: 14569 - selector: - app: ts-preserve-other-service - ---- - -apiVersion: v1 -kind: Service -metadata: - name: ts-preserve-service -spec: - ports: - - name: http - port: 14568 - selector: - app: ts-preserve-service - ---- - -apiVersion: v1 -kind: Service -metadata: - name: ts-price-service -spec: - ports: - - name: http - port: 16579 - selector: - app: ts-price-service - ---- - -apiVersion: v1 -kind: Service -metadata: - name: ts-rebook-service -spec: - ports: - - name: http - port: 18886 - selector: - app: ts-rebook-service - ---- - -apiVersion: v1 -kind: Service -metadata: - name: ts-route-plan-service -spec: - ports: - - name: http - port: 14578 - selector: - app: ts-route-plan-service - ---- - -apiVersion: v1 -kind: Service -metadata: - name: ts-route-service -spec: - ports: - - name: http - port: 11178 - selector: - app: ts-route-service - ---- - -apiVersion: v1 -kind: Service -metadata: - name: ts-seat-service -spec: - ports: - - name: http - port: 18898 - selector: - app: ts-seat-service - ---- - -apiVersion: v1 -kind: Service -metadata: - name: ts-security-service -spec: - ports: - - name: http - port: 11188 - selector: - app: ts-security-service - ---- - -apiVersion: v1 -kind: Service -metadata: - name: ts-auth-service -spec: - type: NodePort - ports: - - name: http - port: 12340 - nodePort: 30000 - selector: - app: ts-auth-service - ---- - -apiVersion: v1 -kind: Service -metadata: - name: ts-station-service -spec: - ports: - - name: http - port: 12345 - selector: - app: ts-station-service - ---- - -apiVersion: v1 -kind: Service -metadata: - name: ts-ticket-office-service -spec: - ports: - - name: http - port: 16108 - selector: - app: ts-ticket-office-service - ---- - -apiVersion: v1 -kind: Service -metadata: - name: ts-ticketinfo-service -spec: - ports: - - name: http - port: 15681 - selector: - app: ts-ticketinfo-service - ---- - -apiVersion: v1 -kind: Service -metadata: - name: ts-train-service -spec: - ports: - - name: http - port: 14567 - selector: - app: ts-train-service - ---- - -apiVersion: v1 -kind: Service -metadata: - name: ts-travel2-service -spec: - ports: - - name: http - port: 16346 - selector: - app: ts-travel2-service - ---- - -apiVersion: v1 -kind: Service -metadata: - name: ts-travel-plan-service -spec: - ports: - - name: http - port: 14322 - selector: - app: ts-travel-plan-service - ---- - -apiVersion: v1 -kind: Service -metadata: - name: ts-travel-service -spec: - ports: - - name: http - port: 12346 - selector: - app: ts-travel-service - - ---- - -apiVersion: v1 -kind: Service -metadata: - name: ts-verification-code-service -spec: - ports: - - name: http - port: 15678 - selector: - app: ts-verification-code-service - - ---- - -apiVersion: v1 -kind: Service -metadata: - name: ts-voucher-service -spec: - ports: - - name: http - port: 16101 - selector: - app: ts-voucher-service - ---- - apiVersion: apps/v1 kind: Deployment metadata: - name: ts-avatar-service + name: ts-wait-order-service spec: selector: matchLabels: - app: ts-avatar-service + app: ts-wait-order-service replicas: 1 template: metadata: labels: - app: ts-avatar-service + app: ts-wait-order-service spec: containers: - - name: ts-avatar-service - image: codewisdom/ts-avatar-service:0.2.0 - imagePullPolicy: Always - ports: - - containerPort: 17001 - resources: - requests: - cpu: 50m - memory: 200Mi - limits: - cpu: 200m - memory: 500Mi - readinessProbe: - tcpSocket: - port: 17001 - initialDelaySeconds: 160 - periodSeconds: 10 - timeoutSeconds: 5 + - name: ts-wait-order-service + image: codewisdom/ts-wait-order-service:1.0.0 + imagePullPolicy: IfNotPresent + env: + - name: NODE_IP + valueFrom: + fieldRef: + fieldPath: status.hostIP + envFrom: + - secretRef: + name: ts-wait-order-service + - configMapRef: + name: nacos + ports: + - containerPort: 17525 + resources: + requests: + cpu: 100m + memory: 300Mi + limits: + cpu: 500m + memory: 2000Mi + readinessProbe: + tcpSocket: + port: 17525 + initialDelaySeconds: 60 + periodSeconds: 10 + timeoutSeconds: 5 --- - -apiVersion: v1 -kind: Service +apiVersion: apps/v1 +kind: Deployment metadata: - name: ts-avatar-service + name: ts-ui-dashboard spec: - ports: - - name: http - port: 17001 selector: - app: ts-avatar-service - + matchLabels: + app: ts-ui-dashboard + replicas: 1 + template: + metadata: + labels: + app: ts-ui-dashboard + spec: + containers: + - name: ts-ui-dashboard + image: codewisdom/ts-ui-dashboard:1.0.0 + imagePullPolicy: IfNotPresent + ports: + - containerPort: 8080 + resources: + requests: + cpu: 50m + memory: 100Mi + limits: + cpu: 500m + memory: 500Mi \ No newline at end of file diff --git a/deployment/kubernetes-manifests/quickstart-k8s/yamls/svc.yaml b/deployment/kubernetes-manifests/quickstart-k8s/yamls/svc.yaml new file mode 100644 index 000000000..9eadbcb1f --- /dev/null +++ b/deployment/kubernetes-manifests/quickstart-k8s/yamls/svc.yaml @@ -0,0 +1,487 @@ +apiVersion: v1 +kind: Service +metadata: + name: ts-admin-basic-info-service +spec: + ports: + - name: http + port: 18767 + selector: + app: ts-admin-basic-info-service +--- +apiVersion: v1 +kind: Service +metadata: + name: ts-admin-order-service +spec: + ports: + - name: http + port: 16112 + selector: + app: ts-admin-order-service +--- +apiVersion: v1 +kind: Service +metadata: + name: ts-admin-route-service +spec: + ports: + - name: http + port: 16113 + selector: + app: ts-admin-route-service +--- +apiVersion: v1 +kind: Service +metadata: + name: ts-admin-travel-service +spec: + ports: + - name: http + port: 16114 + selector: + app: ts-admin-travel-service +--- +apiVersion: v1 +kind: Service +metadata: + name: ts-admin-user-service +spec: + ports: + - name: http + port: 16115 + selector: + app: ts-admin-user-service +--- +apiVersion: v1 +kind: Service +metadata: + name: ts-assurance-service +spec: + ports: + - name: http + port: 18888 + selector: + app: ts-assurance-service +--- +apiVersion: v1 +kind: Service +metadata: + name: ts-auth-service +spec: + ports: + - name: http + port: 12340 + selector: + app: ts-auth-service +--- +apiVersion: v1 +kind: Service +metadata: + name: ts-avatar-service +spec: + ports: + - name: http + port: 17001 + selector: + app: ts-avatar-service +--- +apiVersion: v1 +kind: Service +metadata: + name: ts-basic-service +spec: + ports: + - name: http + port: 15680 + selector: + app: ts-basic-service +--- +apiVersion: v1 +kind: Service +metadata: + name: ts-cancel-service +spec: + ports: + - name: http + port: 18885 + selector: + app: ts-cancel-service +--- +apiVersion: v1 +kind: Service +metadata: + name: ts-config-service +spec: + ports: + - name: http + port: 15679 + selector: + app: ts-config-service +--- +apiVersion: v1 +kind: Service +metadata: + name: ts-consign-price-service +spec: + ports: + - name: http + port: 16110 + selector: + app: ts-consign-price-service +--- +apiVersion: v1 +kind: Service +metadata: + name: ts-consign-service +spec: + ports: + - name: http + port: 16111 + selector: + app: ts-consign-service +--- +apiVersion: v1 +kind: Service +metadata: + name: ts-contacts-service +spec: + ports: + - name: http + port: 12347 + selector: + app: ts-contacts-service +--- +apiVersion: v1 +kind: Service +metadata: + name: ts-delivery-service +spec: + ports: + - name: http + port: 18808 + selector: + app: ts-delivery-service +--- +apiVersion: v1 +kind: Service +metadata: + name: ts-execute-service +spec: + ports: + - name: http + port: 12386 + selector: + app: ts-execute-service +--- +apiVersion: v1 +kind: Service +metadata: + name: ts-food-service +spec: + ports: + - name: http + port: 18856 + selector: + app: ts-food-service +--- +apiVersion: v1 +kind: Service +metadata: + name: ts-gateway-service +spec: + ports: + - name: http + port: 18888 + nodePort: 30467 + selector: + app: ts-gateway-service + type: NodePort +--- +apiVersion: v1 +kind: Service +metadata: + name: ts-inside-payment-service +spec: + ports: + - name: http + port: 18673 + selector: + app: ts-inside-payment-service +--- +apiVersion: v1 +kind: Service +metadata: + name: ts-news-service +spec: + ports: + - name: http + port: 12862 + selector: + app: ts-news-service +--- +apiVersion: v1 +kind: Service +metadata: + name: ts-notification-service +spec: + ports: + - name: http + port: 17853 + selector: + app: ts-notification-service +--- +apiVersion: v1 +kind: Service +metadata: + name: ts-order-other-service +spec: + ports: + - name: http + port: 12032 + selector: + app: ts-order-other-service +--- +apiVersion: v1 +kind: Service +metadata: + name: ts-order-service +spec: + ports: + - name: http + port: 12031 + selector: + app: ts-order-service +--- +apiVersion: v1 +kind: Service +metadata: + name: ts-payment-service +spec: + ports: + - name: http + port: 19001 + selector: + app: ts-payment-service +--- +apiVersion: v1 +kind: Service +metadata: + name: ts-preserve-other-service +spec: + ports: + - name: http + port: 14569 + selector: + app: ts-preserve-other-service +--- +apiVersion: v1 +kind: Service +metadata: + name: ts-preserve-service +spec: + ports: + - name: http + port: 14568 + selector: + app: ts-preserve-service +--- +apiVersion: v1 +kind: Service +metadata: + name: ts-price-service +spec: + ports: + - name: http + port: 16579 + selector: + app: ts-price-service +--- +apiVersion: v1 +kind: Service +metadata: + name: ts-rebook-service +spec: + ports: + - name: http + port: 18886 + selector: + app: ts-rebook-service +--- +apiVersion: v1 +kind: Service +metadata: + name: ts-route-plan-service +spec: + ports: + - name: http + port: 14578 + selector: + app: ts-route-plan-service +--- +apiVersion: v1 +kind: Service +metadata: + name: ts-route-service +spec: + ports: + - name: http + port: 11178 + selector: + app: ts-route-service +--- +apiVersion: v1 +kind: Service +metadata: + name: ts-seat-service +spec: + ports: + - name: http + port: 18898 + selector: + app: ts-seat-service +--- +apiVersion: v1 +kind: Service +metadata: + name: ts-security-service +spec: + ports: + - name: http + port: 11188 + selector: + app: ts-security-service +--- +apiVersion: v1 +kind: Service +metadata: + name: ts-station-food-service +spec: + ports: + - name: http + port: 18855 + selector: + app: ts-station-food-service +--- +apiVersion: v1 +kind: Service +metadata: + name: ts-station-service +spec: + ports: + - name: http + port: 12345 + selector: + app: ts-station-service +--- +apiVersion: v1 +kind: Service +metadata: + name: ts-ticket-office-service +spec: + ports: + - name: http + port: 16108 + selector: + app: ts-ticket-office-service +--- +apiVersion: v1 +kind: Service +metadata: + name: ts-train-food-service +spec: + ports: + - name: http + port: 19999 + selector: + app: ts-train-food-service +--- +apiVersion: v1 +kind: Service +metadata: + name: ts-train-service +spec: + ports: + - name: http + port: 14567 + selector: + app: ts-train-service +--- +apiVersion: v1 +kind: Service +metadata: + name: ts-travel-plan-service +spec: + ports: + - name: http + port: 14322 + selector: + app: ts-travel-plan-service +--- +apiVersion: v1 +kind: Service +metadata: + name: ts-travel-service +spec: + ports: + - name: http + port: 12346 + selector: + app: ts-travel-service +--- +apiVersion: v1 +kind: Service +metadata: + name: ts-travel2-service +spec: + ports: + - name: http + port: 16346 + selector: + app: ts-travel2-service +--- +apiVersion: v1 +kind: Service +metadata: + name: ts-user-service +spec: + ports: + - name: http + port: 12342 + selector: + app: ts-user-service +--- +apiVersion: v1 +kind: Service +metadata: + name: ts-verification-code-service +spec: + ports: + - name: http + port: 15678 + selector: + app: ts-verification-code-service +--- +apiVersion: v1 +kind: Service +metadata: + name: ts-voucher-service +spec: + ports: + - name: http + port: 16101 + selector: + app: ts-voucher-service +--- +apiVersion: v1 +kind: Service +metadata: + name: ts-ui-dashboard +spec: + type: NodePort + ports: + - name: http + port: 8080 + nodePort: 32677 + selector: + app: ts-ui-dashboard \ No newline at end of file diff --git a/deployment/kubernetes-manifests/quickstart-k8s/yamls/sw_deploy.yaml.sample b/deployment/kubernetes-manifests/quickstart-k8s/yamls/sw_deploy.yaml.sample new file mode 100644 index 000000000..db42a8ef9 --- /dev/null +++ b/deployment/kubernetes-manifests/quickstart-k8s/yamls/sw_deploy.yaml.sample @@ -0,0 +1,3131 @@ +apiVersion: apps/v1 +kind: Deployment +metadata: + name: ts-admin-basic-info-service +spec: + selector: + matchLabels: + app: ts-admin-basic-info-service + replicas: 1 + template: + metadata: + labels: + app: ts-admin-basic-info-service + spec: + volumes: + - name: skywalking-agent + emptyDir: {} + initContainers: + - name: agent-container + image: apache/skywalking-java-agent:8.8.0-alpine + volumeMounts: + - name: skywalking-agent + mountPath: /agent + command: [ "/bin/sh" ] + args: [ "-c", "cp -R /skywalking/agent /agent/" ] + containers: + - name: ts-admin-basic-info-service + image: codewisdom/ts-admin-basic-info-service:1.0.0 + imagePullPolicy: IfNotPresent + volumeMounts: + - name: skywalking-agent + mountPath: /skywalking + env: + - name: NODE_IP + valueFrom: + fieldRef: + fieldPath: status.hostIP + - name: SW_AGENT_COLLECTOR_BACKEND_SERVICES + value: "skywalking:11800" + - name: SW_GRPC_LOG_SERVER_HOST + value: "skywalking" + - name: SW_GRPC_LOG_SERVER_PORT + value: "11800" + - name: SW_AGENT_NAME + valueFrom: + fieldRef: + fieldPath: metadata.labels['app'] + - name: JAVA_TOOL_OPTIONS + value: "-javaagent:/skywalking/agent/skywalking-agent.jar" + envFrom: + - configMapRef: + name: nacos + ports: + - containerPort: 18767 + resources: + requests: + cpu: 100m + memory: 300Mi + limits: + cpu: 500m + memory: 2000Mi + readinessProbe: + tcpSocket: + port: 18767 + initialDelaySeconds: 60 + periodSeconds: 10 + timeoutSeconds: 5 +--- +apiVersion: apps/v1 +kind: Deployment +metadata: + name: ts-admin-order-service +spec: + selector: + matchLabels: + app: ts-admin-order-service + replicas: 1 + template: + metadata: + labels: + app: ts-admin-order-service + spec: + volumes: + - name: skywalking-agent + emptyDir: {} + initContainers: + - name: agent-container + image: apache/skywalking-java-agent:8.8.0-alpine + volumeMounts: + - name: skywalking-agent + mountPath: /agent + command: [ "/bin/sh" ] + args: [ "-c", "cp -R /skywalking/agent /agent/" ] + containers: + - name: ts-admin-order-service + image: codewisdom/ts-admin-order-service:1.0.0 + imagePullPolicy: IfNotPresent + volumeMounts: + - name: skywalking-agent + mountPath: /skywalking + env: + - name: NODE_IP + valueFrom: + fieldRef: + fieldPath: status.hostIP + - name: SW_AGENT_COLLECTOR_BACKEND_SERVICES + value: "skywalking:11800" + - name: SW_GRPC_LOG_SERVER_HOST + value: "skywalking" + - name: SW_GRPC_LOG_SERVER_PORT + value: "11800" + - name: SW_AGENT_NAME + valueFrom: + fieldRef: + fieldPath: metadata.labels['app'] + - name: JAVA_TOOL_OPTIONS + value: "-javaagent:/skywalking/agent/skywalking-agent.jar" + envFrom: + - configMapRef: + name: nacos + ports: + - containerPort: 16112 + resources: + requests: + cpu: 100m + memory: 300Mi + limits: + cpu: 500m + memory: 2000Mi + readinessProbe: + tcpSocket: + port: 16112 + initialDelaySeconds: 60 + periodSeconds: 10 + timeoutSeconds: 5 +--- +apiVersion: apps/v1 +kind: Deployment +metadata: + name: ts-admin-route-service +spec: + selector: + matchLabels: + app: ts-admin-route-service + replicas: 1 + template: + metadata: + labels: + app: ts-admin-route-service + spec: + volumes: + - name: skywalking-agent + emptyDir: {} + initContainers: + - name: agent-container + image: apache/skywalking-java-agent:8.8.0-alpine + volumeMounts: + - name: skywalking-agent + mountPath: /agent + command: [ "/bin/sh" ] + args: [ "-c", "cp -R /skywalking/agent /agent/" ] + containers: + - name: ts-admin-route-service + image: codewisdom/ts-admin-route-service:1.0.0 + imagePullPolicy: IfNotPresent + volumeMounts: + - name: skywalking-agent + mountPath: /skywalking + env: + - name: NODE_IP + valueFrom: + fieldRef: + fieldPath: status.hostIP + - name: SW_AGENT_COLLECTOR_BACKEND_SERVICES + value: "skywalking:11800" + - name: SW_GRPC_LOG_SERVER_HOST + value: "skywalking" + - name: SW_GRPC_LOG_SERVER_PORT + value: "11800" + - name: SW_AGENT_NAME + valueFrom: + fieldRef: + fieldPath: metadata.labels['app'] + - name: JAVA_TOOL_OPTIONS + value: "-javaagent:/skywalking/agent/skywalking-agent.jar" + envFrom: + - configMapRef: + name: nacos + ports: + - containerPort: 16113 + resources: + requests: + cpu: 100m + memory: 300Mi + limits: + cpu: 500m + memory: 2000Mi + readinessProbe: + tcpSocket: + port: 16113 + initialDelaySeconds: 60 + periodSeconds: 10 + timeoutSeconds: 5 +--- +apiVersion: apps/v1 +kind: Deployment +metadata: + name: ts-admin-travel-service +spec: + selector: + matchLabels: + app: ts-admin-travel-service + replicas: 1 + template: + metadata: + labels: + app: ts-admin-travel-service + spec: + volumes: + - name: skywalking-agent + emptyDir: {} + initContainers: + - name: agent-container + image: apache/skywalking-java-agent:8.8.0-alpine + volumeMounts: + - name: skywalking-agent + mountPath: /agent + command: [ "/bin/sh" ] + args: [ "-c", "cp -R /skywalking/agent /agent/" ] + containers: + - name: ts-admin-travel-service + image: codewisdom/ts-admin-travel-service:1.0.0 + imagePullPolicy: IfNotPresent + volumeMounts: + - name: skywalking-agent + mountPath: /skywalking + env: + - name: NODE_IP + valueFrom: + fieldRef: + fieldPath: status.hostIP + - name: SW_AGENT_COLLECTOR_BACKEND_SERVICES + value: "skywalking:11800" + - name: SW_GRPC_LOG_SERVER_HOST + value: "skywalking" + - name: SW_GRPC_LOG_SERVER_PORT + value: "11800" + - name: SW_AGENT_NAME + valueFrom: + fieldRef: + fieldPath: metadata.labels['app'] + - name: JAVA_TOOL_OPTIONS + value: "-javaagent:/skywalking/agent/skywalking-agent.jar" + envFrom: + - configMapRef: + name: nacos + ports: + - containerPort: 16114 + resources: + requests: + cpu: 100m + memory: 300Mi + limits: + cpu: 500m + memory: 2000Mi + readinessProbe: + tcpSocket: + port: 16114 + initialDelaySeconds: 60 + periodSeconds: 10 + timeoutSeconds: 5 +--- +apiVersion: apps/v1 +kind: Deployment +metadata: + name: ts-admin-user-service +spec: + selector: + matchLabels: + app: ts-admin-user-service + replicas: 1 + template: + metadata: + labels: + app: ts-admin-user-service + spec: + volumes: + - name: skywalking-agent + emptyDir: {} + initContainers: + - name: agent-container + image: apache/skywalking-java-agent:8.8.0-alpine + volumeMounts: + - name: skywalking-agent + mountPath: /agent + command: [ "/bin/sh" ] + args: [ "-c", "cp -R /skywalking/agent /agent/" ] + containers: + - name: ts-admin-user-service + image: codewisdom/ts-admin-user-service:1.0.0 + imagePullPolicy: IfNotPresent + volumeMounts: + - name: skywalking-agent + mountPath: /skywalking + env: + - name: NODE_IP + valueFrom: + fieldRef: + fieldPath: status.hostIP + - name: SW_AGENT_COLLECTOR_BACKEND_SERVICES + value: "skywalking:11800" + - name: SW_GRPC_LOG_SERVER_HOST + value: "skywalking" + - name: SW_GRPC_LOG_SERVER_PORT + value: "11800" + - name: SW_AGENT_NAME + valueFrom: + fieldRef: + fieldPath: metadata.labels['app'] + - name: JAVA_TOOL_OPTIONS + value: "-javaagent:/skywalking/agent/skywalking-agent.jar" + envFrom: + - configMapRef: + name: nacos + ports: + - containerPort: 16115 + resources: + requests: + cpu: 100m + memory: 300Mi + limits: + cpu: 500m + memory: 2000Mi + readinessProbe: + tcpSocket: + port: 16115 + initialDelaySeconds: 60 + periodSeconds: 10 + timeoutSeconds: 5 +--- +apiVersion: apps/v1 +kind: Deployment +metadata: + name: ts-assurance-service +spec: + selector: + matchLabels: + app: ts-assurance-service + replicas: 1 + template: + metadata: + labels: + app: ts-assurance-service + spec: + volumes: + - name: skywalking-agent + emptyDir: {} + initContainers: + - name: agent-container + image: apache/skywalking-java-agent:8.8.0-alpine + volumeMounts: + - name: skywalking-agent + mountPath: /agent + command: [ "/bin/sh" ] + args: [ "-c", "cp -R /skywalking/agent /agent/" ] + containers: + - name: ts-assurance-service + image: codewisdom/ts-assurance-service:1.0.0 + imagePullPolicy: IfNotPresent + volumeMounts: + - name: skywalking-agent + mountPath: /skywalking + env: + - name: NODE_IP + valueFrom: + fieldRef: + fieldPath: status.hostIP + - name: SW_AGENT_COLLECTOR_BACKEND_SERVICES + value: "skywalking:11800" + - name: SW_GRPC_LOG_SERVER_HOST + value: "skywalking" + - name: SW_GRPC_LOG_SERVER_PORT + value: "11800" + - name: SW_AGENT_NAME + valueFrom: + fieldRef: + fieldPath: metadata.labels['app'] + - name: JAVA_TOOL_OPTIONS + value: "-javaagent:/skywalking/agent/skywalking-agent.jar" + envFrom: + - secretRef: + name: ts-assurance-mysql + - configMapRef: + name: nacos + ports: + - containerPort: 18888 + resources: + requests: + cpu: 100m + memory: 300Mi + limits: + cpu: 500m + memory: 2000Mi + readinessProbe: + tcpSocket: + port: 18888 + initialDelaySeconds: 60 + periodSeconds: 10 + timeoutSeconds: 5 +--- +apiVersion: apps/v1 +kind: Deployment +metadata: + name: ts-auth-service +spec: + selector: + matchLabels: + app: ts-auth-service + replicas: 1 + template: + metadata: + labels: + app: ts-auth-service + spec: + volumes: + - name: skywalking-agent + emptyDir: {} + initContainers: + - name: agent-container + image: apache/skywalking-java-agent:8.8.0-alpine + volumeMounts: + - name: skywalking-agent + mountPath: /agent + command: [ "/bin/sh" ] + args: [ "-c", "cp -R /skywalking/agent /agent/" ] + containers: + - name: ts-auth-service + image: codewisdom/ts-auth-service:1.0.0 + imagePullPolicy: IfNotPresent + volumeMounts: + - name: skywalking-agent + mountPath: /skywalking + env: + - name: NODE_IP + valueFrom: + fieldRef: + fieldPath: status.hostIP + - name: SW_AGENT_COLLECTOR_BACKEND_SERVICES + value: "skywalking:11800" + - name: SW_GRPC_LOG_SERVER_HOST + value: "skywalking" + - name: SW_GRPC_LOG_SERVER_PORT + value: "11800" + - name: SW_AGENT_NAME + valueFrom: + fieldRef: + fieldPath: metadata.labels['app'] + - name: JAVA_TOOL_OPTIONS + value: "-javaagent:/skywalking/agent/skywalking-agent.jar" + envFrom: + - secretRef: + name: ts-auth-mysql + - configMapRef: + name: nacos + ports: + - containerPort: 12340 + resources: + requests: + cpu: 100m + memory: 300Mi + limits: + cpu: 500m + memory: 2000Mi + readinessProbe: + tcpSocket: + port: 12340 + initialDelaySeconds: 60 + periodSeconds: 10 + timeoutSeconds: 5 +--- +apiVersion: apps/v1 +kind: Deployment +metadata: + name: ts-avatar-service +spec: + selector: + matchLabels: + app: ts-avatar-service + replicas: 1 + template: + metadata: + labels: + app: ts-avatar-service + spec: + volumes: + - name: skywalking-agent + emptyDir: {} + initContainers: + - name: agent-container + image: apache/skywalking-java-agent:8.8.0-alpine + volumeMounts: + - name: skywalking-agent + mountPath: /agent + command: [ "/bin/sh" ] + args: [ "-c", "cp -R /skywalking/agent /agent/" ] + containers: + - name: ts-avatar-service + image: codewisdom/ts-avatar-service:0.2.0 + imagePullPolicy: IfNotPresent + volumeMounts: + - name: skywalking-agent + mountPath: /skywalking + env: + - name: NODE_IP + valueFrom: + fieldRef: + fieldPath: status.hostIP + - name: SW_AGENT_COLLECTOR_BACKEND_SERVICES + value: "skywalking:11800" + - name: SW_GRPC_LOG_SERVER_HOST + value: "skywalking" + - name: SW_GRPC_LOG_SERVER_PORT + value: "11800" + - name: SW_AGENT_NAME + valueFrom: + fieldRef: + fieldPath: metadata.labels['app'] + - name: JAVA_TOOL_OPTIONS + value: "-javaagent:/skywalking/agent/skywalking-agent.jar" + envFrom: + - configMapRef: + name: nacos + ports: + - containerPort: 17001 + resources: + requests: + cpu: 100m + memory: 300Mi + limits: + cpu: 500m + memory: 2000Mi + readinessProbe: + tcpSocket: + port: 17001 + initialDelaySeconds: 60 + periodSeconds: 10 + timeoutSeconds: 5 +--- +apiVersion: apps/v1 +kind: Deployment +metadata: + name: ts-basic-service +spec: + selector: + matchLabels: + app: ts-basic-service + replicas: 1 + template: + metadata: + labels: + app: ts-basic-service + spec: + volumes: + - name: skywalking-agent + emptyDir: {} + initContainers: + - name: agent-container + image: apache/skywalking-java-agent:8.8.0-alpine + volumeMounts: + - name: skywalking-agent + mountPath: /agent + command: [ "/bin/sh" ] + args: [ "-c", "cp -R /skywalking/agent /agent/" ] + containers: + - name: ts-basic-service + image: codewisdom/ts-basic-service:1.0.0 + imagePullPolicy: IfNotPresent + volumeMounts: + - name: skywalking-agent + mountPath: /skywalking + env: + - name: NODE_IP + valueFrom: + fieldRef: + fieldPath: status.hostIP + - name: SW_AGENT_COLLECTOR_BACKEND_SERVICES + value: "skywalking:11800" + - name: SW_GRPC_LOG_SERVER_HOST + value: "skywalking" + - name: SW_GRPC_LOG_SERVER_PORT + value: "11800" + - name: SW_AGENT_NAME + valueFrom: + fieldRef: + fieldPath: metadata.labels['app'] + - name: JAVA_TOOL_OPTIONS + value: "-javaagent:/skywalking/agent/skywalking-agent.jar" + envFrom: + - configMapRef: + name: nacos + ports: + - containerPort: 15680 + resources: + requests: + cpu: 100m + memory: 300Mi + limits: + cpu: 500m + memory: 2000Mi + readinessProbe: + tcpSocket: + port: 15680 + initialDelaySeconds: 60 + periodSeconds: 10 + timeoutSeconds: 5 +--- +apiVersion: apps/v1 +kind: Deployment +metadata: + name: ts-cancel-service +spec: + selector: + matchLabels: + app: ts-cancel-service + replicas: 1 + template: + metadata: + labels: + app: ts-cancel-service + spec: + volumes: + - name: skywalking-agent + emptyDir: {} + initContainers: + - name: agent-container + image: apache/skywalking-java-agent:8.8.0-alpine + volumeMounts: + - name: skywalking-agent + mountPath: /agent + command: [ "/bin/sh" ] + args: [ "-c", "cp -R /skywalking/agent /agent/" ] + containers: + - name: ts-cancel-service + image: codewisdom/ts-cancel-service:1.0.0 + imagePullPolicy: IfNotPresent + volumeMounts: + - name: skywalking-agent + mountPath: /skywalking + env: + - name: NODE_IP + valueFrom: + fieldRef: + fieldPath: status.hostIP + - name: SW_AGENT_COLLECTOR_BACKEND_SERVICES + value: "skywalking:11800" + - name: SW_GRPC_LOG_SERVER_HOST + value: "skywalking" + - name: SW_GRPC_LOG_SERVER_PORT + value: "11800" + - name: SW_AGENT_NAME + valueFrom: + fieldRef: + fieldPath: metadata.labels['app'] + - name: JAVA_TOOL_OPTIONS + value: "-javaagent:/skywalking/agent/skywalking-agent.jar" + envFrom: + - configMapRef: + name: nacos + ports: + - containerPort: 18885 + resources: + requests: + cpu: 100m + memory: 300Mi + limits: + cpu: 500m + memory: 2000Mi + readinessProbe: + tcpSocket: + port: 18885 + initialDelaySeconds: 60 + periodSeconds: 10 + timeoutSeconds: 5 +--- +apiVersion: apps/v1 +kind: Deployment +metadata: + name: ts-config-service +spec: + selector: + matchLabels: + app: ts-config-service + replicas: 1 + template: + metadata: + labels: + app: ts-config-service + spec: + volumes: + - name: skywalking-agent + emptyDir: {} + initContainers: + - name: agent-container + image: apache/skywalking-java-agent:8.8.0-alpine + volumeMounts: + - name: skywalking-agent + mountPath: /agent + command: [ "/bin/sh" ] + args: [ "-c", "cp -R /skywalking/agent /agent/" ] + containers: + - name: ts-config-service + image: codewisdom/ts-config-service:1.0.0 + imagePullPolicy: IfNotPresent + volumeMounts: + - name: skywalking-agent + mountPath: /skywalking + env: + - name: NODE_IP + valueFrom: + fieldRef: + fieldPath: status.hostIP + - name: SW_AGENT_COLLECTOR_BACKEND_SERVICES + value: "skywalking:11800" + - name: SW_GRPC_LOG_SERVER_HOST + value: "skywalking" + - name: SW_GRPC_LOG_SERVER_PORT + value: "11800" + - name: SW_AGENT_NAME + valueFrom: + fieldRef: + fieldPath: metadata.labels['app'] + - name: JAVA_TOOL_OPTIONS + value: "-javaagent:/skywalking/agent/skywalking-agent.jar" + envFrom: + - secretRef: + name: ts-config-mysql + - configMapRef: + name: nacos + ports: + - containerPort: 15679 + resources: + requests: + cpu: 100m + memory: 300Mi + limits: + cpu: 500m + memory: 2000Mi + readinessProbe: + tcpSocket: + port: 15679 + initialDelaySeconds: 60 + periodSeconds: 10 + timeoutSeconds: 5 +--- +apiVersion: apps/v1 +kind: Deployment +metadata: + name: ts-consign-price-service +spec: + selector: + matchLabels: + app: ts-consign-price-service + replicas: 1 + template: + metadata: + labels: + app: ts-consign-price-service + spec: + volumes: + - name: skywalking-agent + emptyDir: {} + initContainers: + - name: agent-container + image: apache/skywalking-java-agent:8.8.0-alpine + volumeMounts: + - name: skywalking-agent + mountPath: /agent + command: [ "/bin/sh" ] + args: [ "-c", "cp -R /skywalking/agent /agent/" ] + containers: + - name: ts-consign-price-service + image: codewisdom/ts-consign-price-service:1.0.0 + imagePullPolicy: IfNotPresent + volumeMounts: + - name: skywalking-agent + mountPath: /skywalking + env: + - name: NODE_IP + valueFrom: + fieldRef: + fieldPath: status.hostIP + - name: SW_AGENT_COLLECTOR_BACKEND_SERVICES + value: "skywalking:11800" + - name: SW_GRPC_LOG_SERVER_HOST + value: "skywalking" + - name: SW_GRPC_LOG_SERVER_PORT + value: "11800" + - name: SW_AGENT_NAME + valueFrom: + fieldRef: + fieldPath: metadata.labels['app'] + - name: JAVA_TOOL_OPTIONS + value: "-javaagent:/skywalking/agent/skywalking-agent.jar" + envFrom: + - secretRef: + name: ts-consign-price-mysql + - configMapRef: + name: nacos + ports: + - containerPort: 16110 + resources: + requests: + cpu: 100m + memory: 300Mi + limits: + cpu: 500m + memory: 2000Mi + readinessProbe: + tcpSocket: + port: 16110 + initialDelaySeconds: 60 + periodSeconds: 10 + timeoutSeconds: 5 +--- +apiVersion: apps/v1 +kind: Deployment +metadata: + name: ts-consign-service +spec: + selector: + matchLabels: + app: ts-consign-service + replicas: 1 + template: + metadata: + labels: + app: ts-consign-service + spec: + volumes: + - name: skywalking-agent + emptyDir: {} + initContainers: + - name: agent-container + image: apache/skywalking-java-agent:8.8.0-alpine + volumeMounts: + - name: skywalking-agent + mountPath: /agent + command: [ "/bin/sh" ] + args: [ "-c", "cp -R /skywalking/agent /agent/" ] + containers: + - name: ts-consign-service + image: codewisdom/ts-consign-service:1.0.0 + imagePullPolicy: IfNotPresent + volumeMounts: + - name: skywalking-agent + mountPath: /skywalking + env: + - name: NODE_IP + valueFrom: + fieldRef: + fieldPath: status.hostIP + - name: SW_AGENT_COLLECTOR_BACKEND_SERVICES + value: "skywalking:11800" + - name: SW_GRPC_LOG_SERVER_HOST + value: "skywalking" + - name: SW_GRPC_LOG_SERVER_PORT + value: "11800" + - name: SW_AGENT_NAME + valueFrom: + fieldRef: + fieldPath: metadata.labels['app'] + - name: JAVA_TOOL_OPTIONS + value: "-javaagent:/skywalking/agent/skywalking-agent.jar" + envFrom: + - secretRef: + name: ts-consign-mysql + - configMapRef: + name: nacos + ports: + - containerPort: 16111 + resources: + requests: + cpu: 100m + memory: 300Mi + limits: + cpu: 500m + memory: 2000Mi + readinessProbe: + tcpSocket: + port: 16111 + initialDelaySeconds: 60 + periodSeconds: 10 + timeoutSeconds: 5 +--- +apiVersion: apps/v1 +kind: Deployment +metadata: + name: ts-contacts-service +spec: + selector: + matchLabels: + app: ts-contacts-service + replicas: 1 + template: + metadata: + labels: + app: ts-contacts-service + spec: + volumes: + - name: skywalking-agent + emptyDir: {} + initContainers: + - name: agent-container + image: apache/skywalking-java-agent:8.8.0-alpine + volumeMounts: + - name: skywalking-agent + mountPath: /agent + command: [ "/bin/sh" ] + args: [ "-c", "cp -R /skywalking/agent /agent/" ] + containers: + - name: ts-contacts-service + image: codewisdom/ts-contacts-service:1.0.0 + imagePullPolicy: IfNotPresent + volumeMounts: + - name: skywalking-agent + mountPath: /skywalking + env: + - name: NODE_IP + valueFrom: + fieldRef: + fieldPath: status.hostIP + - name: SW_AGENT_COLLECTOR_BACKEND_SERVICES + value: "skywalking:11800" + - name: SW_GRPC_LOG_SERVER_HOST + value: "skywalking" + - name: SW_GRPC_LOG_SERVER_PORT + value: "11800" + - name: SW_AGENT_NAME + valueFrom: + fieldRef: + fieldPath: metadata.labels['app'] + - name: JAVA_TOOL_OPTIONS + value: "-javaagent:/skywalking/agent/skywalking-agent.jar" + envFrom: + - secretRef: + name: ts-contacts-mysql + - configMapRef: + name: nacos + ports: + - containerPort: 12347 + resources: + requests: + cpu: 100m + memory: 300Mi + limits: + cpu: 500m + memory: 2000Mi + readinessProbe: + tcpSocket: + port: 12347 + initialDelaySeconds: 60 + periodSeconds: 10 + timeoutSeconds: 5 +--- +apiVersion: apps/v1 +kind: Deployment +metadata: + name: ts-delivery-service +spec: + selector: + matchLabels: + app: ts-delivery-service + replicas: 1 + template: + metadata: + labels: + app: ts-delivery-service + spec: + volumes: + - name: skywalking-agent + emptyDir: {} + initContainers: + - name: agent-container + image: apache/skywalking-java-agent:8.8.0-alpine + volumeMounts: + - name: skywalking-agent + mountPath: /agent + command: [ "/bin/sh" ] + args: [ "-c", "cp -R /skywalking/agent /agent/" ] + containers: + - name: ts-delivery-service + image: codewisdom/ts-delivery-service:1.0.0 + imagePullPolicy: IfNotPresent + volumeMounts: + - name: skywalking-agent + mountPath: /skywalking + env: + - name: NODE_IP + valueFrom: + fieldRef: + fieldPath: status.hostIP + - name: SW_AGENT_COLLECTOR_BACKEND_SERVICES + value: "skywalking:11800" + - name: SW_GRPC_LOG_SERVER_HOST + value: "skywalking" + - name: SW_GRPC_LOG_SERVER_PORT + value: "11800" + - name: SW_AGENT_NAME + valueFrom: + fieldRef: + fieldPath: metadata.labels['app'] + - name: JAVA_TOOL_OPTIONS + value: "-javaagent:/skywalking/agent/skywalking-agent.jar" + envFrom: + - secretRef: + name: ts-delivery-mysql + - configMapRef: + name: nacos + - configMapRef: + name: rabbitmq + ports: + - containerPort: 18808 + resources: + requests: + cpu: 100m + memory: 300Mi + limits: + cpu: 500m + memory: 2000Mi + readinessProbe: + tcpSocket: + port: 18808 + initialDelaySeconds: 60 + periodSeconds: 10 + timeoutSeconds: 5 +--- +apiVersion: apps/v1 +kind: Deployment +metadata: + name: ts-execute-service +spec: + selector: + matchLabels: + app: ts-execute-service + replicas: 1 + template: + metadata: + labels: + app: ts-execute-service + spec: + volumes: + - name: skywalking-agent + emptyDir: {} + initContainers: + - name: agent-container + image: apache/skywalking-java-agent:8.8.0-alpine + volumeMounts: + - name: skywalking-agent + mountPath: /agent + command: [ "/bin/sh" ] + args: [ "-c", "cp -R /skywalking/agent /agent/" ] + containers: + - name: ts-execute-service + image: codewisdom/ts-execute-service:1.0.0 + imagePullPolicy: IfNotPresent + volumeMounts: + - name: skywalking-agent + mountPath: /skywalking + env: + - name: NODE_IP + valueFrom: + fieldRef: + fieldPath: status.hostIP + - name: SW_AGENT_COLLECTOR_BACKEND_SERVICES + value: "skywalking:11800" + - name: SW_GRPC_LOG_SERVER_HOST + value: "skywalking" + - name: SW_GRPC_LOG_SERVER_PORT + value: "11800" + - name: SW_AGENT_NAME + valueFrom: + fieldRef: + fieldPath: metadata.labels['app'] + - name: JAVA_TOOL_OPTIONS + value: "-javaagent:/skywalking/agent/skywalking-agent.jar" + envFrom: + - configMapRef: + name: nacos + ports: + - containerPort: 12386 + resources: + requests: + cpu: 100m + memory: 300Mi + limits: + cpu: 500m + memory: 2000Mi + readinessProbe: + tcpSocket: + port: 12386 + initialDelaySeconds: 60 + periodSeconds: 10 + timeoutSeconds: 5 +--- +apiVersion: apps/v1 +kind: Deployment +metadata: + name: ts-food-delivery-service +spec: + selector: + matchLabels: + app: ts-food-delivery-service + replicas: 1 + template: + metadata: + labels: + app: ts-food-delivery-service + spec: + volumes: + - name: skywalking-agent + emptyDir: {} + initContainers: + - name: agent-container + image: apache/skywalking-java-agent:8.8.0-alpine + volumeMounts: + - name: skywalking-agent + mountPath: /agent + command: [ "/bin/sh" ] + args: [ "-c", "cp -R /skywalking/agent /agent/" ] + containers: + - name: ts-food-delivery-service + image: codewisdom/ts-food-delivery-service:1.0.0 + imagePullPolicy: IfNotPresent + volumeMounts: + - name: skywalking-agent + mountPath: /skywalking + env: + - name: NODE_IP + valueFrom: + fieldRef: + fieldPath: status.hostIP + - name: SW_AGENT_COLLECTOR_BACKEND_SERVICES + value: "skywalking:11800" + - name: SW_GRPC_LOG_SERVER_HOST + value: "skywalking" + - name: SW_GRPC_LOG_SERVER_PORT + value: "11800" + - name: SW_AGENT_NAME + valueFrom: + fieldRef: + fieldPath: metadata.labels['app'] + - name: JAVA_TOOL_OPTIONS + value: "-javaagent:/skywalking/agent/skywalking-agent.jar" + envFrom: + - secretRef: + name: ts-food-delivery-mysql + - configMapRef: + name: nacos + ports: + - containerPort: 18957 + resources: + requests: + cpu: 100m + memory: 300Mi + limits: + cpu: 500m + memory: 2000Mi + readinessProbe: + tcpSocket: + port: 18957 + initialDelaySeconds: 60 + periodSeconds: 10 + timeoutSeconds: 5 +--- +apiVersion: apps/v1 +kind: Deployment +metadata: + name: ts-food-service +spec: + selector: + matchLabels: + app: ts-food-service + replicas: 1 + template: + metadata: + labels: + app: ts-food-service + spec: + volumes: + - name: skywalking-agent + emptyDir: {} + initContainers: + - name: agent-container + image: apache/skywalking-java-agent:8.8.0-alpine + volumeMounts: + - name: skywalking-agent + mountPath: /agent + command: [ "/bin/sh" ] + args: [ "-c", "cp -R /skywalking/agent /agent/" ] + containers: + - name: ts-food-service + image: codewisdom/ts-food-service:1.0.0 + imagePullPolicy: IfNotPresent + volumeMounts: + - name: skywalking-agent + mountPath: /skywalking + env: + - name: NODE_IP + valueFrom: + fieldRef: + fieldPath: status.hostIP + - name: SW_AGENT_COLLECTOR_BACKEND_SERVICES + value: "skywalking:11800" + - name: SW_GRPC_LOG_SERVER_HOST + value: "skywalking" + - name: SW_GRPC_LOG_SERVER_PORT + value: "11800" + - name: SW_AGENT_NAME + valueFrom: + fieldRef: + fieldPath: metadata.labels['app'] + - name: JAVA_TOOL_OPTIONS + value: "-javaagent:/skywalking/agent/skywalking-agent.jar" + envFrom: + - configMapRef: + name: nacos + - configMapRef: + name: rabbitmq + - secretRef: + name: ts-food-mysql + ports: + - containerPort: 18856 + resources: + requests: + cpu: 100m + memory: 300Mi + limits: + cpu: 500m + memory: 2000Mi + readinessProbe: + tcpSocket: + port: 18856 + initialDelaySeconds: 60 + periodSeconds: 10 + timeoutSeconds: 5 +--- +apiVersion: apps/v1 +kind: Deployment +metadata: + name: ts-gateway-service +spec: + selector: + matchLabels: + app: ts-gateway-service + replicas: 1 + template: + metadata: + labels: + app: ts-gateway-service + spec: + volumes: + - name: skywalking-agent + emptyDir: {} + initContainers: + - name: agent-container + image: apache/skywalking-java-agent:8.8.0-alpine + volumeMounts: + - name: skywalking-agent + mountPath: /agent + command: [ "/bin/sh" ] + args: [ "-c", "cp -R /skywalking/agent /agent/" ] + containers: + - name: ts-gateway-service + image: codewisdom/ts-gateway-service:1.0.0 + imagePullPolicy: IfNotPresent + volumeMounts: + - name: skywalking-agent + mountPath: /skywalking + env: + - name: NODE_IP + valueFrom: + fieldRef: + fieldPath: status.hostIP + - name: SW_AGENT_COLLECTOR_BACKEND_SERVICES + value: "skywalking:11800" + - name: SW_GRPC_LOG_SERVER_HOST + value: "skywalking" + - name: SW_GRPC_LOG_SERVER_PORT + value: "11800" + - name: SW_AGENT_NAME + valueFrom: + fieldRef: + fieldPath: metadata.labels['app'] + - name: JAVA_TOOL_OPTIONS + value: "-javaagent:/skywalking/agent/skywalking-agent.jar" + envFrom: + - configMapRef: + name: nacos + ports: + - containerPort: 18888 + resources: + requests: + cpu: 100m + memory: 300Mi + limits: + cpu: 4000m + memory: 4000Mi + readinessProbe: + tcpSocket: + port: 18888 + initialDelaySeconds: 60 + periodSeconds: 10 + timeoutSeconds: 5 +--- +apiVersion: apps/v1 +kind: Deployment +metadata: + name: ts-inside-payment-service +spec: + selector: + matchLabels: + app: ts-inside-payment-service + replicas: 1 + template: + metadata: + labels: + app: ts-inside-payment-service + spec: + volumes: + - name: skywalking-agent + emptyDir: {} + initContainers: + - name: agent-container + image: apache/skywalking-java-agent:8.8.0-alpine + volumeMounts: + - name: skywalking-agent + mountPath: /agent + command: [ "/bin/sh" ] + args: [ "-c", "cp -R /skywalking/agent /agent/" ] + containers: + - name: ts-inside-payment-service + image: codewisdom/ts-inside-payment-service:1.0.0 + imagePullPolicy: IfNotPresent + volumeMounts: + - name: skywalking-agent + mountPath: /skywalking + env: + - name: NODE_IP + valueFrom: + fieldRef: + fieldPath: status.hostIP + - name: SW_AGENT_COLLECTOR_BACKEND_SERVICES + value: "skywalking:11800" + - name: SW_GRPC_LOG_SERVER_HOST + value: "skywalking" + - name: SW_GRPC_LOG_SERVER_PORT + value: "11800" + - name: SW_AGENT_NAME + valueFrom: + fieldRef: + fieldPath: metadata.labels['app'] + - name: JAVA_TOOL_OPTIONS + value: "-javaagent:/skywalking/agent/skywalking-agent.jar" + envFrom: + - secretRef: + name: ts-inside-payment-mysql + - configMapRef: + name: nacos + ports: + - containerPort: 18673 + resources: + requests: + cpu: 100m + memory: 300Mi + limits: + cpu: 500m + memory: 2000Mi + readinessProbe: + tcpSocket: + port: 18673 + initialDelaySeconds: 60 + periodSeconds: 10 + timeoutSeconds: 5 +--- +apiVersion: apps/v1 +kind: Deployment +metadata: + name: ts-news-service +spec: + selector: + matchLabels: + app: ts-news-service + replicas: 1 + template: + metadata: + labels: + app: ts-news-service + spec: + volumes: + - name: skywalking-agent + emptyDir: {} + initContainers: + - name: agent-container + image: apache/skywalking-java-agent:8.8.0-alpine + volumeMounts: + - name: skywalking-agent + mountPath: /agent + command: [ "/bin/sh" ] + args: [ "-c", "cp -R /skywalking/agent /agent/" ] + containers: + - name: ts-news-service + image: codewisdom/ts-news-service:1.0.0 + imagePullPolicy: IfNotPresent + volumeMounts: + - name: skywalking-agent + mountPath: /skywalking + env: + - name: NODE_IP + valueFrom: + fieldRef: + fieldPath: status.hostIP + - name: SW_AGENT_COLLECTOR_BACKEND_SERVICES + value: "skywalking:11800" + - name: SW_GRPC_LOG_SERVER_HOST + value: "skywalking" + - name: SW_GRPC_LOG_SERVER_PORT + value: "11800" + - name: SW_AGENT_NAME + valueFrom: + fieldRef: + fieldPath: metadata.labels['app'] + - name: JAVA_TOOL_OPTIONS + value: "-javaagent:/skywalking/agent/skywalking-agent.jar" + envFrom: + - configMapRef: + name: nacos + ports: + - containerPort: 12862 + resources: + requests: + cpu: 100m + memory: 300Mi + limits: + cpu: 500m + memory: 2000Mi + readinessProbe: + tcpSocket: + port: 12862 + initialDelaySeconds: 60 + periodSeconds: 10 + timeoutSeconds: 5 +--- +apiVersion: apps/v1 +kind: Deployment +metadata: + name: ts-notification-service +spec: + selector: + matchLabels: + app: ts-notification-service + replicas: 1 + template: + metadata: + labels: + app: ts-notification-service + spec: + volumes: + - name: skywalking-agent + emptyDir: {} + initContainers: + - name: agent-container + image: apache/skywalking-java-agent:8.8.0-alpine + volumeMounts: + - name: skywalking-agent + mountPath: /agent + command: [ "/bin/sh" ] + args: [ "-c", "cp -R /skywalking/agent /agent/" ] + containers: + - name: ts-notification-service + image: codewisdom/ts-notification-service:1.0.0 + imagePullPolicy: IfNotPresent + volumeMounts: + - name: skywalking-agent + mountPath: /skywalking + env: + - name: NODE_IP + valueFrom: + fieldRef: + fieldPath: status.hostIP + - name: SW_AGENT_COLLECTOR_BACKEND_SERVICES + value: "skywalking:11800" + - name: SW_GRPC_LOG_SERVER_HOST + value: "skywalking" + - name: SW_GRPC_LOG_SERVER_PORT + value: "11800" + - name: SW_AGENT_NAME + valueFrom: + fieldRef: + fieldPath: metadata.labels['app'] + - name: JAVA_TOOL_OPTIONS + value: "-javaagent:/skywalking/agent/skywalking-agent.jar" + envFrom: + - secretRef: + name: ts-notification-mysql + - configMapRef: + name: nacos + - configMapRef: + name: rabbitmq + ports: + - containerPort: 17853 + resources: + requests: + cpu: 100m + memory: 300Mi + limits: + cpu: 500m + memory: 2000Mi + readinessProbe: + tcpSocket: + port: 17853 + initialDelaySeconds: 60 + periodSeconds: 10 + timeoutSeconds: 5 +--- +apiVersion: apps/v1 +kind: Deployment +metadata: + name: ts-order-other-service +spec: + selector: + matchLabels: + app: ts-order-other-service + replicas: 1 + template: + metadata: + labels: + app: ts-order-other-service + spec: + volumes: + - name: skywalking-agent + emptyDir: {} + initContainers: + - name: agent-container + image: apache/skywalking-java-agent:8.8.0-alpine + volumeMounts: + - name: skywalking-agent + mountPath: /agent + command: [ "/bin/sh" ] + args: [ "-c", "cp -R /skywalking/agent /agent/" ] + containers: + - name: ts-order-other-service + image: codewisdom/ts-order-other-service:1.0.0 + imagePullPolicy: IfNotPresent + volumeMounts: + - name: skywalking-agent + mountPath: /skywalking + env: + - name: NODE_IP + valueFrom: + fieldRef: + fieldPath: status.hostIP + - name: SW_AGENT_COLLECTOR_BACKEND_SERVICES + value: "skywalking:11800" + - name: SW_GRPC_LOG_SERVER_HOST + value: "skywalking" + - name: SW_GRPC_LOG_SERVER_PORT + value: "11800" + - name: SW_AGENT_NAME + valueFrom: + fieldRef: + fieldPath: metadata.labels['app'] + - name: JAVA_TOOL_OPTIONS + value: "-javaagent:/skywalking/agent/skywalking-agent.jar" + envFrom: + - secretRef: + name: ts-order-other-mysql + - configMapRef: + name: nacos + - configMapRef: + name: rabbitmq + ports: + - containerPort: 12032 + resources: + requests: + cpu: 100m + memory: 300Mi + limits: + cpu: 500m + memory: 2000Mi + readinessProbe: + tcpSocket: + port: 12032 + initialDelaySeconds: 60 + periodSeconds: 10 + timeoutSeconds: 5 +--- +apiVersion: apps/v1 +kind: Deployment +metadata: + name: ts-order-service +spec: + selector: + matchLabels: + app: ts-order-service + replicas: 1 + template: + metadata: + labels: + app: ts-order-service + spec: + volumes: + - name: skywalking-agent + emptyDir: {} + initContainers: + - name: agent-container + image: apache/skywalking-java-agent:8.8.0-alpine + volumeMounts: + - name: skywalking-agent + mountPath: /agent + command: [ "/bin/sh" ] + args: [ "-c", "cp -R /skywalking/agent /agent/" ] + containers: + - name: ts-order-service + image: codewisdom/ts-order-service:1.0.0 + imagePullPolicy: IfNotPresent + volumeMounts: + - name: skywalking-agent + mountPath: /skywalking + env: + - name: NODE_IP + valueFrom: + fieldRef: + fieldPath: status.hostIP + - name: SW_AGENT_COLLECTOR_BACKEND_SERVICES + value: "skywalking:11800" + - name: SW_GRPC_LOG_SERVER_HOST + value: "skywalking" + - name: SW_GRPC_LOG_SERVER_PORT + value: "11800" + - name: SW_AGENT_NAME + valueFrom: + fieldRef: + fieldPath: metadata.labels['app'] + - name: JAVA_TOOL_OPTIONS + value: "-javaagent:/skywalking/agent/skywalking-agent.jar" + envFrom: + - secretRef: + name: ts-order-mysql + - configMapRef: + name: nacos + - configMapRef: + name: rabbitmq + ports: + - containerPort: 12031 + resources: + requests: + cpu: 100m + memory: 300Mi + limits: + cpu: 500m + memory: 2000Mi + readinessProbe: + tcpSocket: + port: 12031 + initialDelaySeconds: 60 + periodSeconds: 10 + timeoutSeconds: 5 +--- +apiVersion: apps/v1 +kind: Deployment +metadata: + name: ts-payment-service +spec: + selector: + matchLabels: + app: ts-payment-service + replicas: 1 + template: + metadata: + labels: + app: ts-payment-service + spec: + volumes: + - name: skywalking-agent + emptyDir: {} + initContainers: + - name: agent-container + image: apache/skywalking-java-agent:8.8.0-alpine + volumeMounts: + - name: skywalking-agent + mountPath: /agent + command: [ "/bin/sh" ] + args: [ "-c", "cp -R /skywalking/agent /agent/" ] + containers: + - name: ts-payment-service + image: codewisdom/ts-payment-service:1.0.0 + imagePullPolicy: IfNotPresent + volumeMounts: + - name: skywalking-agent + mountPath: /skywalking + env: + - name: NODE_IP + valueFrom: + fieldRef: + fieldPath: status.hostIP + - name: SW_AGENT_COLLECTOR_BACKEND_SERVICES + value: "skywalking:11800" + - name: SW_GRPC_LOG_SERVER_HOST + value: "skywalking" + - name: SW_GRPC_LOG_SERVER_PORT + value: "11800" + - name: SW_AGENT_NAME + valueFrom: + fieldRef: + fieldPath: metadata.labels['app'] + - name: JAVA_TOOL_OPTIONS + value: "-javaagent:/skywalking/agent/skywalking-agent.jar" + envFrom: + - secretRef: + name: ts-payment-mysql + - configMapRef: + name: nacos + ports: + - containerPort: 19001 + resources: + requests: + cpu: 100m + memory: 300Mi + limits: + cpu: 500m + memory: 2000Mi + readinessProbe: + tcpSocket: + port: 19001 + initialDelaySeconds: 60 + periodSeconds: 10 + timeoutSeconds: 5 +--- +apiVersion: apps/v1 +kind: Deployment +metadata: + name: ts-preserve-other-service +spec: + selector: + matchLabels: + app: ts-preserve-other-service + replicas: 1 + template: + metadata: + labels: + app: ts-preserve-other-service + spec: + volumes: + - name: skywalking-agent + emptyDir: {} + initContainers: + - name: agent-container + image: apache/skywalking-java-agent:8.8.0-alpine + volumeMounts: + - name: skywalking-agent + mountPath: /agent + command: [ "/bin/sh" ] + args: [ "-c", "cp -R /skywalking/agent /agent/" ] + containers: + - name: ts-preserve-other-service + image: codewisdom/ts-preserve-other-service:1.0.0 + imagePullPolicy: IfNotPresent + volumeMounts: + - name: skywalking-agent + mountPath: /skywalking + env: + - name: NODE_IP + valueFrom: + fieldRef: + fieldPath: status.hostIP + - name: SW_AGENT_COLLECTOR_BACKEND_SERVICES + value: "skywalking:11800" + - name: SW_GRPC_LOG_SERVER_HOST + value: "skywalking" + - name: SW_GRPC_LOG_SERVER_PORT + value: "11800" + - name: SW_AGENT_NAME + valueFrom: + fieldRef: + fieldPath: metadata.labels['app'] + - name: JAVA_TOOL_OPTIONS + value: "-javaagent:/skywalking/agent/skywalking-agent.jar" + envFrom: + - configMapRef: + name: nacos + - configMapRef: + name: rabbitmq + ports: + - containerPort: 14569 + resources: + requests: + cpu: 100m + memory: 300Mi + limits: + cpu: 500m + memory: 2000Mi + readinessProbe: + tcpSocket: + port: 14569 + initialDelaySeconds: 60 + periodSeconds: 10 + timeoutSeconds: 5 +--- +apiVersion: apps/v1 +kind: Deployment +metadata: + name: ts-preserve-service +spec: + selector: + matchLabels: + app: ts-preserve-service + replicas: 1 + template: + metadata: + labels: + app: ts-preserve-service + spec: + volumes: + - name: skywalking-agent + emptyDir: {} + initContainers: + - name: agent-container + image: apache/skywalking-java-agent:8.8.0-alpine + volumeMounts: + - name: skywalking-agent + mountPath: /agent + command: [ "/bin/sh" ] + args: [ "-c", "cp -R /skywalking/agent /agent/" ] + containers: + - name: ts-preserve-service + image: codewisdom/ts-preserve-service:1.0.0 + imagePullPolicy: IfNotPresent + volumeMounts: + - name: skywalking-agent + mountPath: /skywalking + env: + - name: NODE_IP + valueFrom: + fieldRef: + fieldPath: status.hostIP + - name: SW_AGENT_COLLECTOR_BACKEND_SERVICES + value: "skywalking:11800" + - name: SW_GRPC_LOG_SERVER_HOST + value: "skywalking" + - name: SW_GRPC_LOG_SERVER_PORT + value: "11800" + - name: SW_AGENT_NAME + valueFrom: + fieldRef: + fieldPath: metadata.labels['app'] + - name: JAVA_TOOL_OPTIONS + value: "-javaagent:/skywalking/agent/skywalking-agent.jar" + envFrom: + - configMapRef: + name: nacos + - configMapRef: + name: rabbitmq + ports: + - containerPort: 14568 + resources: + requests: + cpu: 100m + memory: 300Mi + limits: + cpu: 500m + memory: 2000Mi + readinessProbe: + tcpSocket: + port: 14568 + initialDelaySeconds: 60 + periodSeconds: 10 + timeoutSeconds: 5 +--- +apiVersion: apps/v1 +kind: Deployment +metadata: + name: ts-price-service +spec: + selector: + matchLabels: + app: ts-price-service + replicas: 1 + template: + metadata: + labels: + app: ts-price-service + spec: + volumes: + - name: skywalking-agent + emptyDir: {} + initContainers: + - name: agent-container + image: apache/skywalking-java-agent:8.8.0-alpine + volumeMounts: + - name: skywalking-agent + mountPath: /agent + command: [ "/bin/sh" ] + args: [ "-c", "cp -R /skywalking/agent /agent/" ] + containers: + - name: ts-price-service + image: codewisdom/ts-price-service:1.0.0 + imagePullPolicy: IfNotPresent + volumeMounts: + - name: skywalking-agent + mountPath: /skywalking + env: + - name: NODE_IP + valueFrom: + fieldRef: + fieldPath: status.hostIP + - name: SW_AGENT_COLLECTOR_BACKEND_SERVICES + value: "skywalking:11800" + - name: SW_GRPC_LOG_SERVER_HOST + value: "skywalking" + - name: SW_GRPC_LOG_SERVER_PORT + value: "11800" + - name: SW_AGENT_NAME + valueFrom: + fieldRef: + fieldPath: metadata.labels['app'] + - name: JAVA_TOOL_OPTIONS + value: "-javaagent:/skywalking/agent/skywalking-agent.jar" + envFrom: + - secretRef: + name: ts-price-mysql + - configMapRef: + name: nacos + ports: + - containerPort: 16579 + resources: + requests: + cpu: 100m + memory: 300Mi + limits: + cpu: 500m + memory: 2000Mi + readinessProbe: + tcpSocket: + port: 16579 + initialDelaySeconds: 60 + periodSeconds: 10 + timeoutSeconds: 5 +--- +apiVersion: apps/v1 +kind: Deployment +metadata: + name: ts-rebook-service +spec: + selector: + matchLabels: + app: ts-rebook-service + replicas: 1 + template: + metadata: + labels: + app: ts-rebook-service + spec: + volumes: + - name: skywalking-agent + emptyDir: {} + initContainers: + - name: agent-container + image: apache/skywalking-java-agent:8.8.0-alpine + volumeMounts: + - name: skywalking-agent + mountPath: /agent + command: [ "/bin/sh" ] + args: [ "-c", "cp -R /skywalking/agent /agent/" ] + containers: + - name: ts-rebook-service + image: codewisdom/ts-rebook-service:1.0.0 + imagePullPolicy: IfNotPresent + volumeMounts: + - name: skywalking-agent + mountPath: /skywalking + env: + - name: NODE_IP + valueFrom: + fieldRef: + fieldPath: status.hostIP + - name: SW_AGENT_COLLECTOR_BACKEND_SERVICES + value: "skywalking:11800" + - name: SW_GRPC_LOG_SERVER_HOST + value: "skywalking" + - name: SW_GRPC_LOG_SERVER_PORT + value: "11800" + - name: SW_AGENT_NAME + valueFrom: + fieldRef: + fieldPath: metadata.labels['app'] + - name: JAVA_TOOL_OPTIONS + value: "-javaagent:/skywalking/agent/skywalking-agent.jar" + envFrom: + - configMapRef: + name: nacos + - configMapRef: + name: rabbitmq + ports: + - containerPort: 18886 + resources: + requests: + cpu: 100m + memory: 300Mi + limits: + cpu: 500m + memory: 2000Mi + readinessProbe: + tcpSocket: + port: 18886 + initialDelaySeconds: 60 + periodSeconds: 10 + timeoutSeconds: 5 +--- +apiVersion: apps/v1 +kind: Deployment +metadata: + name: ts-route-plan-service +spec: + selector: + matchLabels: + app: ts-route-plan-service + replicas: 1 + template: + metadata: + labels: + app: ts-route-plan-service + spec: + volumes: + - name: skywalking-agent + emptyDir: {} + initContainers: + - name: agent-container + image: apache/skywalking-java-agent:8.8.0-alpine + volumeMounts: + - name: skywalking-agent + mountPath: /agent + command: [ "/bin/sh" ] + args: [ "-c", "cp -R /skywalking/agent /agent/" ] + containers: + - name: ts-route-plan-service + image: codewisdom/ts-route-plan-service:1.0.0 + imagePullPolicy: IfNotPresent + volumeMounts: + - name: skywalking-agent + mountPath: /skywalking + env: + - name: NODE_IP + valueFrom: + fieldRef: + fieldPath: status.hostIP + - name: SW_AGENT_COLLECTOR_BACKEND_SERVICES + value: "skywalking:11800" + - name: SW_GRPC_LOG_SERVER_HOST + value: "skywalking" + - name: SW_GRPC_LOG_SERVER_PORT + value: "11800" + - name: SW_AGENT_NAME + valueFrom: + fieldRef: + fieldPath: metadata.labels['app'] + - name: JAVA_TOOL_OPTIONS + value: "-javaagent:/skywalking/agent/skywalking-agent.jar" + envFrom: + - configMapRef: + name: nacos + ports: + - containerPort: 14578 + resources: + requests: + cpu: 100m + memory: 300Mi + limits: + cpu: 500m + memory: 2000Mi + readinessProbe: + tcpSocket: + port: 14578 + initialDelaySeconds: 60 + periodSeconds: 10 + timeoutSeconds: 5 +--- +apiVersion: apps/v1 +kind: Deployment +metadata: + name: ts-route-service +spec: + selector: + matchLabels: + app: ts-route-service + replicas: 1 + template: + metadata: + labels: + app: ts-route-service + spec: + volumes: + - name: skywalking-agent + emptyDir: {} + initContainers: + - name: agent-container + image: apache/skywalking-java-agent:8.8.0-alpine + volumeMounts: + - name: skywalking-agent + mountPath: /agent + command: [ "/bin/sh" ] + args: [ "-c", "cp -R /skywalking/agent /agent/" ] + containers: + - name: ts-route-service + image: codewisdom/ts-route-service:1.0.0 + imagePullPolicy: IfNotPresent + volumeMounts: + - name: skywalking-agent + mountPath: /skywalking + env: + - name: NODE_IP + valueFrom: + fieldRef: + fieldPath: status.hostIP + - name: SW_AGENT_COLLECTOR_BACKEND_SERVICES + value: "skywalking:11800" + - name: SW_GRPC_LOG_SERVER_HOST + value: "skywalking" + - name: SW_GRPC_LOG_SERVER_PORT + value: "11800" + - name: SW_AGENT_NAME + valueFrom: + fieldRef: + fieldPath: metadata.labels['app'] + - name: JAVA_TOOL_OPTIONS + value: "-javaagent:/skywalking/agent/skywalking-agent.jar" + envFrom: + - secretRef: + name: ts-route-mysql + - configMapRef: + name: nacos + ports: + - containerPort: 11178 + resources: + requests: + cpu: 100m + memory: 300Mi + limits: + cpu: 500m + memory: 2000Mi + readinessProbe: + tcpSocket: + port: 11178 + initialDelaySeconds: 60 + periodSeconds: 10 + timeoutSeconds: 5 +--- +apiVersion: apps/v1 +kind: Deployment +metadata: + name: ts-seat-service +spec: + selector: + matchLabels: + app: ts-seat-service + replicas: 1 + template: + metadata: + labels: + app: ts-seat-service + spec: + volumes: + - name: skywalking-agent + emptyDir: {} + initContainers: + - name: agent-container + image: apache/skywalking-java-agent:8.8.0-alpine + volumeMounts: + - name: skywalking-agent + mountPath: /agent + command: [ "/bin/sh" ] + args: [ "-c", "cp -R /skywalking/agent /agent/" ] + containers: + - name: ts-seat-service + image: codewisdom/ts-seat-service:1.0.0 + imagePullPolicy: IfNotPresent + volumeMounts: + - name: skywalking-agent + mountPath: /skywalking + env: + - name: NODE_IP + valueFrom: + fieldRef: + fieldPath: status.hostIP + - name: SW_AGENT_COLLECTOR_BACKEND_SERVICES + value: "skywalking:11800" + - name: SW_GRPC_LOG_SERVER_HOST + value: "skywalking" + - name: SW_GRPC_LOG_SERVER_PORT + value: "11800" + - name: SW_AGENT_NAME + valueFrom: + fieldRef: + fieldPath: metadata.labels['app'] + - name: JAVA_TOOL_OPTIONS + value: "-javaagent:/skywalking/agent/skywalking-agent.jar" + envFrom: + - configMapRef: + name: nacos + ports: + - containerPort: 18898 + resources: + requests: + cpu: 100m + memory: 300Mi + limits: + cpu: 500m + memory: 2000Mi + readinessProbe: + tcpSocket: + port: 18898 + initialDelaySeconds: 60 + periodSeconds: 10 + timeoutSeconds: 5 +--- +apiVersion: apps/v1 +kind: Deployment +metadata: + name: ts-security-service +spec: + selector: + matchLabels: + app: ts-security-service + replicas: 1 + template: + metadata: + labels: + app: ts-security-service + spec: + volumes: + - name: skywalking-agent + emptyDir: {} + initContainers: + - name: agent-container + image: apache/skywalking-java-agent:8.8.0-alpine + volumeMounts: + - name: skywalking-agent + mountPath: /agent + command: [ "/bin/sh" ] + args: [ "-c", "cp -R /skywalking/agent /agent/" ] + containers: + - name: ts-security-service + image: codewisdom/ts-security-service:1.0.0 + imagePullPolicy: IfNotPresent + volumeMounts: + - name: skywalking-agent + mountPath: /skywalking + env: + - name: NODE_IP + valueFrom: + fieldRef: + fieldPath: status.hostIP + - name: SW_AGENT_COLLECTOR_BACKEND_SERVICES + value: "skywalking:11800" + - name: SW_GRPC_LOG_SERVER_HOST + value: "skywalking" + - name: SW_GRPC_LOG_SERVER_PORT + value: "11800" + - name: SW_AGENT_NAME + valueFrom: + fieldRef: + fieldPath: metadata.labels['app'] + - name: JAVA_TOOL_OPTIONS + value: "-javaagent:/skywalking/agent/skywalking-agent.jar" + envFrom: + - secretRef: + name: ts-security-mysql + - configMapRef: + name: nacos + ports: + - containerPort: 11188 + resources: + requests: + cpu: 100m + memory: 300Mi + limits: + cpu: 500m + memory: 2000Mi + readinessProbe: + tcpSocket: + port: 11188 + initialDelaySeconds: 60 + periodSeconds: 10 + timeoutSeconds: 5 +--- +apiVersion: apps/v1 +kind: Deployment +metadata: + name: ts-station-food-service +spec: + selector: + matchLabels: + app: ts-station-food-service + replicas: 1 + template: + metadata: + labels: + app: ts-station-food-service + spec: + volumes: + - name: skywalking-agent + emptyDir: {} + initContainers: + - name: agent-container + image: apache/skywalking-java-agent:8.8.0-alpine + volumeMounts: + - name: skywalking-agent + mountPath: /agent + command: [ "/bin/sh" ] + args: [ "-c", "cp -R /skywalking/agent /agent/" ] + containers: + - name: ts-station-food-service + image: codewisdom/ts-station-food-service:1.0.0 + imagePullPolicy: IfNotPresent + volumeMounts: + - name: skywalking-agent + mountPath: /skywalking + env: + - name: NODE_IP + valueFrom: + fieldRef: + fieldPath: status.hostIP + - name: SW_AGENT_COLLECTOR_BACKEND_SERVICES + value: "skywalking:11800" + - name: SW_GRPC_LOG_SERVER_HOST + value: "skywalking" + - name: SW_GRPC_LOG_SERVER_PORT + value: "11800" + - name: SW_AGENT_NAME + valueFrom: + fieldRef: + fieldPath: metadata.labels['app'] + - name: JAVA_TOOL_OPTIONS + value: "-javaagent:/skywalking/agent/skywalking-agent.jar" + envFrom: + - secretRef: + name: ts-station-food-mysql + - configMapRef: + name: nacos + ports: + - containerPort: 18855 + resources: + requests: + cpu: 100m + memory: 300Mi + limits: + cpu: 500m + memory: 2000Mi + readinessProbe: + tcpSocket: + port: 18855 + initialDelaySeconds: 60 + periodSeconds: 10 + timeoutSeconds: 5 +--- +apiVersion: apps/v1 +kind: Deployment +metadata: + name: ts-station-service +spec: + selector: + matchLabels: + app: ts-station-service + replicas: 1 + template: + metadata: + labels: + app: ts-station-service + spec: + volumes: + - name: skywalking-agent + emptyDir: {} + initContainers: + - name: agent-container + image: apache/skywalking-java-agent:8.8.0-alpine + volumeMounts: + - name: skywalking-agent + mountPath: /agent + command: [ "/bin/sh" ] + args: [ "-c", "cp -R /skywalking/agent /agent/" ] + containers: + - name: ts-station-service + image: codewisdom/ts-station-service:1.0.0 + imagePullPolicy: IfNotPresent + volumeMounts: + - name: skywalking-agent + mountPath: /skywalking + env: + - name: NODE_IP + valueFrom: + fieldRef: + fieldPath: status.hostIP + - name: SW_AGENT_COLLECTOR_BACKEND_SERVICES + value: "skywalking:11800" + - name: SW_GRPC_LOG_SERVER_HOST + value: "skywalking" + - name: SW_GRPC_LOG_SERVER_PORT + value: "11800" + - name: SW_AGENT_NAME + valueFrom: + fieldRef: + fieldPath: metadata.labels['app'] + - name: JAVA_TOOL_OPTIONS + value: "-javaagent:/skywalking/agent/skywalking-agent.jar" + envFrom: + - secretRef: + name: ts-station-mysql + - configMapRef: + name: nacos + ports: + - containerPort: 12345 + resources: + requests: + cpu: 100m + memory: 300Mi + limits: + cpu: 500m + memory: 2000Mi + readinessProbe: + tcpSocket: + port: 12345 + initialDelaySeconds: 60 + periodSeconds: 10 + timeoutSeconds: 5 +--- +apiVersion: apps/v1 +kind: Deployment +metadata: + name: ts-ticket-office-service +spec: + selector: + matchLabels: + app: ts-ticket-office-service + replicas: 1 + template: + metadata: + labels: + app: ts-ticket-office-service + spec: + volumes: + - name: skywalking-agent + emptyDir: {} + initContainers: + - name: agent-container + image: apache/skywalking-java-agent:8.8.0-alpine + volumeMounts: + - name: skywalking-agent + mountPath: /agent + command: [ "/bin/sh" ] + args: [ "-c", "cp -R /skywalking/agent /agent/" ] + containers: + - name: ts-ticket-office-service + image: codewisdom/ts-ticket-office-service:1.0.0 + imagePullPolicy: IfNotPresent + volumeMounts: + - name: skywalking-agent + mountPath: /skywalking + env: + - name: NODE_IP + valueFrom: + fieldRef: + fieldPath: status.hostIP + - name: SW_AGENT_COLLECTOR_BACKEND_SERVICES + value: "skywalking:11800" + - name: SW_GRPC_LOG_SERVER_HOST + value: "skywalking" + - name: SW_GRPC_LOG_SERVER_PORT + value: "11800" + - name: SW_AGENT_NAME + valueFrom: + fieldRef: + fieldPath: metadata.labels['app'] + - name: JAVA_TOOL_OPTIONS + value: "-javaagent:/skywalking/agent/skywalking-agent.jar" + envFrom: + - secretRef: + name: ts-ticket-office-mysql + - configMapRef: + name: nacos + ports: + - containerPort: 16108 + resources: + requests: + cpu: 100m + memory: 300Mi + limits: + cpu: 500m + memory: 2000Mi + readinessProbe: + tcpSocket: + port: 16108 + initialDelaySeconds: 60 + periodSeconds: 10 + timeoutSeconds: 5 +--- +apiVersion: apps/v1 +kind: Deployment +metadata: + name: ts-train-food-service +spec: + selector: + matchLabels: + app: ts-train-food-service + replicas: 1 + template: + metadata: + labels: + app: ts-train-food-service + spec: + volumes: + - name: skywalking-agent + emptyDir: {} + initContainers: + - name: agent-container + image: apache/skywalking-java-agent:8.8.0-alpine + volumeMounts: + - name: skywalking-agent + mountPath: /agent + command: [ "/bin/sh" ] + args: [ "-c", "cp -R /skywalking/agent /agent/" ] + containers: + - name: ts-train-food-service + image: codewisdom/ts-train-food-service:1.0.0 + imagePullPolicy: IfNotPresent + volumeMounts: + - name: skywalking-agent + mountPath: /skywalking + env: + - name: NODE_IP + valueFrom: + fieldRef: + fieldPath: status.hostIP + - name: SW_AGENT_COLLECTOR_BACKEND_SERVICES + value: "skywalking:11800" + - name: SW_GRPC_LOG_SERVER_HOST + value: "skywalking" + - name: SW_GRPC_LOG_SERVER_PORT + value: "11800" + - name: SW_AGENT_NAME + valueFrom: + fieldRef: + fieldPath: metadata.labels['app'] + - name: JAVA_TOOL_OPTIONS + value: "-javaagent:/skywalking/agent/skywalking-agent.jar" + envFrom: + - secretRef: + name: ts-train-food-mysql + - configMapRef: + name: nacos + ports: + - containerPort: 19999 + resources: + requests: + cpu: 100m + memory: 300Mi + limits: + cpu: 500m + memory: 2000Mi + readinessProbe: + tcpSocket: + port: 19999 + initialDelaySeconds: 60 + periodSeconds: 10 + timeoutSeconds: 5 +--- +apiVersion: apps/v1 +kind: Deployment +metadata: + name: ts-train-service +spec: + selector: + matchLabels: + app: ts-train-service + replicas: 1 + template: + metadata: + labels: + app: ts-train-service + spec: + volumes: + - name: skywalking-agent + emptyDir: {} + initContainers: + - name: agent-container + image: apache/skywalking-java-agent:8.8.0-alpine + volumeMounts: + - name: skywalking-agent + mountPath: /agent + command: [ "/bin/sh" ] + args: [ "-c", "cp -R /skywalking/agent /agent/" ] + containers: + - name: ts-train-service + image: codewisdom/ts-train-service:1.0.0 + imagePullPolicy: IfNotPresent + volumeMounts: + - name: skywalking-agent + mountPath: /skywalking + env: + - name: NODE_IP + valueFrom: + fieldRef: + fieldPath: status.hostIP + - name: SW_AGENT_COLLECTOR_BACKEND_SERVICES + value: "skywalking:11800" + - name: SW_GRPC_LOG_SERVER_HOST + value: "skywalking" + - name: SW_GRPC_LOG_SERVER_PORT + value: "11800" + - name: SW_AGENT_NAME + valueFrom: + fieldRef: + fieldPath: metadata.labels['app'] + - name: JAVA_TOOL_OPTIONS + value: "-javaagent:/skywalking/agent/skywalking-agent.jar" + envFrom: + - secretRef: + name: ts-train-mysql + - configMapRef: + name: nacos + ports: + - containerPort: 14567 + resources: + requests: + cpu: 100m + memory: 300Mi + limits: + cpu: 500m + memory: 2000Mi + readinessProbe: + tcpSocket: + port: 14567 + initialDelaySeconds: 60 + periodSeconds: 10 + timeoutSeconds: 5 +--- +apiVersion: apps/v1 +kind: Deployment +metadata: + name: ts-travel-plan-service +spec: + selector: + matchLabels: + app: ts-travel-plan-service + replicas: 1 + template: + metadata: + labels: + app: ts-travel-plan-service + spec: + volumes: + - name: skywalking-agent + emptyDir: {} + initContainers: + - name: agent-container + image: apache/skywalking-java-agent:8.8.0-alpine + volumeMounts: + - name: skywalking-agent + mountPath: /agent + command: [ "/bin/sh" ] + args: [ "-c", "cp -R /skywalking/agent /agent/" ] + containers: + - name: ts-travel-plan-service + image: codewisdom/ts-travel-plan-service:1.0.0 + imagePullPolicy: IfNotPresent + volumeMounts: + - name: skywalking-agent + mountPath: /skywalking + env: + - name: NODE_IP + valueFrom: + fieldRef: + fieldPath: status.hostIP + - name: SW_AGENT_COLLECTOR_BACKEND_SERVICES + value: "skywalking:11800" + - name: SW_GRPC_LOG_SERVER_HOST + value: "skywalking" + - name: SW_GRPC_LOG_SERVER_PORT + value: "11800" + - name: SW_AGENT_NAME + valueFrom: + fieldRef: + fieldPath: metadata.labels['app'] + - name: JAVA_TOOL_OPTIONS + value: "-javaagent:/skywalking/agent/skywalking-agent.jar" + envFrom: + - configMapRef: + name: nacos + ports: + - containerPort: 14322 + resources: + requests: + cpu: 100m + memory: 300Mi + limits: + cpu: 500m + memory: 2000Mi + readinessProbe: + tcpSocket: + port: 14322 + initialDelaySeconds: 60 + periodSeconds: 10 + timeoutSeconds: 5 +--- +apiVersion: apps/v1 +kind: Deployment +metadata: + name: ts-travel-service +spec: + selector: + matchLabels: + app: ts-travel-service + replicas: 1 + template: + metadata: + labels: + app: ts-travel-service + spec: + volumes: + - name: skywalking-agent + emptyDir: {} + initContainers: + - name: agent-container + image: apache/skywalking-java-agent:8.8.0-alpine + volumeMounts: + - name: skywalking-agent + mountPath: /agent + command: [ "/bin/sh" ] + args: [ "-c", "cp -R /skywalking/agent /agent/" ] + containers: + - name: ts-travel-service + image: codewisdom/ts-travel-service:1.0.0 + imagePullPolicy: IfNotPresent + volumeMounts: + - name: skywalking-agent + mountPath: /skywalking + env: + - name: NODE_IP + valueFrom: + fieldRef: + fieldPath: status.hostIP + - name: SW_AGENT_COLLECTOR_BACKEND_SERVICES + value: "skywalking:11800" + - name: SW_GRPC_LOG_SERVER_HOST + value: "skywalking" + - name: SW_GRPC_LOG_SERVER_PORT + value: "11800" + - name: SW_AGENT_NAME + valueFrom: + fieldRef: + fieldPath: metadata.labels['app'] + - name: JAVA_TOOL_OPTIONS + value: "-javaagent:/skywalking/agent/skywalking-agent.jar" + envFrom: + - secretRef: + name: ts-travel-mysql + - configMapRef: + name: nacos + ports: + - containerPort: 12346 + resources: + requests: + cpu: 100m + memory: 300Mi + limits: + cpu: 500m + memory: 2000Mi + readinessProbe: + tcpSocket: + port: 12346 + initialDelaySeconds: 60 + periodSeconds: 10 + timeoutSeconds: 5 +--- +apiVersion: apps/v1 +kind: Deployment +metadata: + name: ts-travel2-service +spec: + selector: + matchLabels: + app: ts-travel2-service + replicas: 1 + template: + metadata: + labels: + app: ts-travel2-service + spec: + volumes: + - name: skywalking-agent + emptyDir: {} + initContainers: + - name: agent-container + image: apache/skywalking-java-agent:8.8.0-alpine + volumeMounts: + - name: skywalking-agent + mountPath: /agent + command: [ "/bin/sh" ] + args: [ "-c", "cp -R /skywalking/agent /agent/" ] + containers: + - name: ts-travel2-service + image: codewisdom/ts-travel2-service:1.0.0 + imagePullPolicy: IfNotPresent + volumeMounts: + - name: skywalking-agent + mountPath: /skywalking + env: + - name: NODE_IP + valueFrom: + fieldRef: + fieldPath: status.hostIP + - name: SW_AGENT_COLLECTOR_BACKEND_SERVICES + value: "skywalking:11800" + - name: SW_GRPC_LOG_SERVER_HOST + value: "skywalking" + - name: SW_GRPC_LOG_SERVER_PORT + value: "11800" + - name: SW_AGENT_NAME + valueFrom: + fieldRef: + fieldPath: metadata.labels['app'] + - name: JAVA_TOOL_OPTIONS + value: "-javaagent:/skywalking/agent/skywalking-agent.jar" + envFrom: + - secretRef: + name: ts-travel2-mysql + - configMapRef: + name: nacos + ports: + - containerPort: 16346 + resources: + requests: + cpu: 100m + memory: 300Mi + limits: + cpu: 500m + memory: 2000Mi + readinessProbe: + tcpSocket: + port: 16346 + initialDelaySeconds: 60 + periodSeconds: 10 + timeoutSeconds: 5 +--- +apiVersion: apps/v1 +kind: Deployment +metadata: + name: ts-user-service +spec: + selector: + matchLabels: + app: ts-user-service + replicas: 1 + template: + metadata: + labels: + app: ts-user-service + spec: + volumes: + - name: skywalking-agent + emptyDir: {} + initContainers: + - name: agent-container + image: apache/skywalking-java-agent:8.8.0-alpine + volumeMounts: + - name: skywalking-agent + mountPath: /agent + command: [ "/bin/sh" ] + args: [ "-c", "cp -R /skywalking/agent /agent/" ] + containers: + - name: ts-user-service + image: codewisdom/ts-user-service:1.0.0 + imagePullPolicy: IfNotPresent + volumeMounts: + - name: skywalking-agent + mountPath: /skywalking + env: + - name: NODE_IP + valueFrom: + fieldRef: + fieldPath: status.hostIP + - name: SW_AGENT_COLLECTOR_BACKEND_SERVICES + value: "skywalking:11800" + - name: SW_GRPC_LOG_SERVER_HOST + value: "skywalking" + - name: SW_GRPC_LOG_SERVER_PORT + value: "11800" + - name: SW_AGENT_NAME + valueFrom: + fieldRef: + fieldPath: metadata.labels['app'] + - name: JAVA_TOOL_OPTIONS + value: "-javaagent:/skywalking/agent/skywalking-agent.jar" + envFrom: + - secretRef: + name: ts-user-mysql + - configMapRef: + name: nacos + ports: + - containerPort: 12342 + resources: + requests: + cpu: 100m + memory: 300Mi + limits: + cpu: 500m + memory: 2000Mi + readinessProbe: + tcpSocket: + port: 12342 + initialDelaySeconds: 60 + periodSeconds: 10 + timeoutSeconds: 5 +--- +apiVersion: apps/v1 +kind: Deployment +metadata: + name: ts-verification-code-service +spec: + selector: + matchLabels: + app: ts-verification-code-service + replicas: 1 + template: + metadata: + labels: + app: ts-verification-code-service + spec: + volumes: + - name: skywalking-agent + emptyDir: {} + initContainers: + - name: agent-container + image: apache/skywalking-java-agent:8.8.0-alpine + volumeMounts: + - name: skywalking-agent + mountPath: /agent + command: [ "/bin/sh" ] + args: [ "-c", "cp -R /skywalking/agent /agent/" ] + containers: + - name: ts-verification-code-service + image: codewisdom/ts-verification-code-service:1.0.0 + imagePullPolicy: IfNotPresent + volumeMounts: + - name: skywalking-agent + mountPath: /skywalking + env: + - name: NODE_IP + valueFrom: + fieldRef: + fieldPath: status.hostIP + - name: SW_AGENT_COLLECTOR_BACKEND_SERVICES + value: "skywalking:11800" + - name: SW_GRPC_LOG_SERVER_HOST + value: "skywalking" + - name: SW_GRPC_LOG_SERVER_PORT + value: "11800" + - name: SW_AGENT_NAME + valueFrom: + fieldRef: + fieldPath: metadata.labels['app'] + - name: JAVA_TOOL_OPTIONS + value: "-javaagent:/skywalking/agent/skywalking-agent.jar" + envFrom: + - configMapRef: + name: nacos + ports: + - containerPort: 15678 + resources: + requests: + cpu: 100m + memory: 300Mi + limits: + cpu: 500m + memory: 2000Mi + readinessProbe: + tcpSocket: + port: 15678 + initialDelaySeconds: 60 + periodSeconds: 10 + timeoutSeconds: 5 +--- +apiVersion: apps/v1 +kind: Deployment +metadata: + name: ts-voucher-service +spec: + selector: + matchLabels: + app: ts-voucher-service + replicas: 1 + template: + metadata: + labels: + app: ts-voucher-service + spec: + containers: + - name: ts-voucher-service + image: codewisdom/ts-voucher-service:1.0.0 + imagePullPolicy: IfNotPresent + env: + - name: NODE_IP + valueFrom: + fieldRef: + fieldPath: status.hostIP + envFrom: + - secretRef: + name: ts-voucher-mysql + - configMapRef: + name: nacos + ports: + - containerPort: 16101 + resources: + requests: + cpu: 100m + memory: 300Mi + limits: + cpu: 500m + memory: 2000Mi + readinessProbe: + tcpSocket: + port: 16101 + initialDelaySeconds: 60 + periodSeconds: 10 + timeoutSeconds: 5 +--- +apiVersion: apps/v1 +kind: Deployment +metadata: + name: ts-wait-order-service +spec: + selector: + matchLabels: + app: ts-wait-order-service + replicas: 1 + template: + metadata: + labels: + app: ts-wait-order-service + spec: + volumes: + - name: skywalking-agent + emptyDir: {} + initContainers: + - name: agent-container + image: apache/skywalking-java-agent:8.8.0-alpine + volumeMounts: + - name: skywalking-agent + mountPath: /agent + command: [ "/bin/sh" ] + args: [ "-c", "cp -R /skywalking/agent /agent/" ] + containers: + - name: ts-wait-order-service + image: codewisdom/ts-wait-order-service:1.0.0 + imagePullPolicy: IfNotPresent + volumeMounts: + - name: skywalking-agent + mountPath: /skywalking + env: + - name: NODE_IP + valueFrom: + fieldRef: + fieldPath: status.hostIP + - name: SW_AGENT_COLLECTOR_BACKEND_SERVICES + value: "skywalking:11800" + - name: SW_GRPC_LOG_SERVER_HOST + value: "skywalking" + - name: SW_GRPC_LOG_SERVER_PORT + value: "11800" + - name: SW_AGENT_NAME + valueFrom: + fieldRef: + fieldPath: metadata.labels['app'] + - name: JAVA_TOOL_OPTIONS + value: "-javaagent:/skywalking/agent/skywalking-agent.jar" + envFrom: + - secretRef: + name: ts-wait-order-mysql + - configMapRef: + name: nacos + ports: + - containerPort: 17525 + resources: + requests: + cpu: 100m + memory: 300Mi + limits: + cpu: 500m + memory: 2000Mi + readinessProbe: + tcpSocket: + port: 17525 + initialDelaySeconds: 60 + periodSeconds: 10 + timeoutSeconds: 5 +--- +apiVersion: apps/v1 +kind: Deployment +metadata: + name: ts-ui-dashboard +spec: + selector: + matchLabels: + app: ts-ui-dashboard + replicas: 1 + template: + metadata: + labels: + app: ts-ui-dashboard + spec: + containers: + - name: ts-ui-dashboard + image: codewisdom/ts-ui-dashboard:1.0.0 + imagePullPolicy: IfNotPresent + ports: + - containerPort: 8080 + resources: + requests: + cpu: 50m + memory: 100Mi + limits: + cpu: 500m + memory: 500Mi diff --git a/deployment/kubernetes-manifests/skywalking/es.yml b/deployment/kubernetes-manifests/skywalking/es.yml new file mode 100644 index 000000000..c5c458e2d --- /dev/null +++ b/deployment/kubernetes-manifests/skywalking/es.yml @@ -0,0 +1,60 @@ +apiVersion: v1 +kind: Service +metadata: + creationTimestamp: null + name: elasticsearch +spec: + ports: + - name: db + port: 9200 + protocol: TCP + targetPort: 9200 + - name: transport + port: 9300 + protocol: TCP + targetPort: 9300 + selector: + run: elasticsearch +status: + loadBalancer: {} +--- +apiVersion: apps/v1 +kind: Deployment +metadata: + creationTimestamp: null + labels: + run: elasticsearch + name: elasticsearch +spec: + replicas: 1 + selector: + matchLabels: + run: elasticsearch + strategy: {} + template: + metadata: + creationTimestamp: null + labels: + run: elasticsearch + spec: + containers: + - env: + - name: discovery.type + value: single-node + image: docker.elastic.co/elasticsearch/elasticsearch:7.1.0 + name: elasticsearch + ports: + - containerPort: 9200 + name: db + protocol: TCP + - containerPort: 9300 + name: tramsport + protocol: TCP + resources: + limits: + cpu: 500m + memory: 2Gi + requests: + cpu: 500m + memory: 2Gi +status: {} diff --git a/deployment/kubernetes-manifests/skywalking/skywalking.yml b/deployment/kubernetes-manifests/skywalking/skywalking.yml new file mode 100644 index 000000000..679e5513a --- /dev/null +++ b/deployment/kubernetes-manifests/skywalking/skywalking.yml @@ -0,0 +1,144 @@ +apiVersion: v1 +kind: ConfigMap +metadata: + name: skywalking-cm +data: + STORAGE: 'elasticsearch7' + STORAGE_ES_CLUSTER_NODES: 'elasticsearch:9200' + CORE_GRPC_PORT: '11800' + CORE_REST_PORT: '12800' + +--- + +apiVersion: apps/v1 +kind: Deployment +metadata: + labels: + app: skywalking + name: skywalking +spec: + replicas: 1 + selector: + matchLabels: + app: skywalking + template: + metadata: + labels: + app: skywalking + spec: + containers: + - envFrom: + - prefix: SW_ + configMapRef: + name: skywalking-cm + image: apache/skywalking-oap-server:8.5.0-es7 + imagePullPolicy: IfNotPresent + name: skywalking + ports: + - containerPort: 12800 + name: http + protocol: TCP + - containerPort: 11800 + name: grpc + protocol: TCP + resources: + limits: + cpu: '2' + memory: 2Gi + requests: + cpu: '1' + memory: 2Gi + volumeMounts: + - mountPath: /etc/localtime + name: volume-localtime + volumes: + - hostPath: + path: /etc/localtime + type: '' + name: volume-localtime + +--- + +apiVersion: v1 +kind: Service +metadata: + name: skywalking + labels: + app: skywalking +spec: + type: ClusterIP + ports: + - name: http + port: 12800 + protocol: TCP + targetPort: 12800 + - name: grpc + port: 11800 + protocol: TCP + targetPort: 11800 + selector: + app: skywalking + +--- + +apiVersion: apps/v1 +kind: Deployment +metadata: + labels: + app: skywalking-ui + name: skywalking-ui +spec: + replicas: 1 + selector: + matchLabels: + app: skywalking-ui + template: + metadata: + labels: + app: skywalking-ui + spec: + containers: + - env: + - name: SW_OAP_ADDRESS + value: "skywalking:12800" + image: apache/skywalking-ui:8.5.0 + imagePullPolicy: IfNotPresent + name: skywalking-ui + ports: + - containerPort: 8080 + name: http + protocol: TCP + resources: + limits: + cpu: '2' + memory: 1Gi + requests: + cpu: '1' + memory: 1Gi + volumeMounts: + - mountPath: /etc/localtime + name: volume-localtime + volumes: + - hostPath: + path: /etc/localtime + type: '' + name: volume-localtime + +--- + +apiVersion: v1 +kind: Service +metadata: + name: skywalking-ui + labels: + app: skywalking-ui +spec: + type: NodePort + ports: + - name: http + port: 8080 + protocol: TCP + targetPort: 8080 + nodePort: 30005 + selector: + app: skywalking-ui diff --git a/hack/deploy/deploy.sh b/hack/deploy/deploy.sh new file mode 100755 index 000000000..fcb25a9ab --- /dev/null +++ b/hack/deploy/deploy.sh @@ -0,0 +1,100 @@ +#!/bin/bash + +TT_ROOT=$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd ) + +source "$TT_ROOT/utils.sh" + + + +namespace="$1" +args="$2" + +argNone=1 +argDB=0 +argMonitoring=0 +argTracing=0 +argAll=0 + +function quick_start { + echo "quick start" + deploy_infrastructures $namespace + deploy_tt_mysql_all_in_one $namespace + deploy_tt_secret $namespace + deploy_tt_svc $namespace + deploy_tt_dp $namespace +} + +function deploy_all { + deploy_infrastructures $namespace + deploy_tt_mysql_each_service $namespace + deploy_tt_secret $namespace + deploy_tt_svc $namespace + deploy_tt_dp_sw $namespace + deploy_tracing $namespace + deploy_monitoring +} + + +function deploy { + if [ $argNone == 1 ]; then + quick_start + exit $? + fi + + if [ $argAll == 1 ]; then + deploy_all + exit $? + fi + + deploy_infrastructures $namespace + + if [ $argDB == 1 ]; then + deploy_tt_mysql_each_service $namespace + else + deploy_tt_mysql_all_in_one $namespace + fi + + deploy_tt_secret $namespace + deploy_tt_svc $namespace + + if [ $argTracing == 1 ]; then + deploy_tt_dp_sw $namespace + deploy_tracing $namespace + else + deploy_tt_dp $namespace + fi + + if [ $argMonitoring == 1 ]; then + deploy_monitoring + fi +} + +#deploy +function parse_args { + echo "Parse DeployArgs" + for arg in $args + do + echo $arg + case $arg in + "--all") + argAll=1 + ;; + "--independent-db") + argDB=1 + ;; + "--with-monitoring") + argMonitoring=1 + ;; + "--with-tracing") + argTracing=1 + ;; + esac + done +} + +echo "args num: $#" +if [ $# == 2 ]; then + argNone=0 + parse_args $args +fi +deploy \ No newline at end of file diff --git a/hack/deploy/gen-mysql-secret.sh b/hack/deploy/gen-mysql-secret.sh new file mode 100755 index 000000000..03136d7ba --- /dev/null +++ b/hack/deploy/gen-mysql-secret.sh @@ -0,0 +1,93 @@ +#!/bin/bash +svc_list="assurance auth config consign-price consign contacts delivery food food-delivery inside-payment notification order-other order payment price route security station-food station ticket-office train-food train travel travel2 user voucher wait-order" + +secret_yaml="deployment/kubernetes-manifests/quickstart-k8s/yamls/secret.yaml" +dp_sample_yaml="deployment/kubernetes-manifests/quickstart-k8s/yamls/deploy.yaml.sample" +sw_dp_sample_yaml="deployment/kubernetes-manifests/quickstart-k8s/yamls/sw_deploy.yaml.sample" + +dp_yaml="deployment/kubernetes-manifests/quickstart-k8s/yamls/deploy.yaml" +sw_dp_yaml="deployment/kubernetes-manifests/quickstart-k8s/yamls/sw_deploy.yaml" + + +function gen_secret_for_tt { + s="$1" + name="ts-$s-mysql" + hostVal="$2" + userVal="$3" + passVal="$4" + dbVal="$5" + + prefix=`echo "${s}-mysql-" | tr '-' '_' | tr a-z A-Z` + host=$prefix"HOST" + port=$prefix"PORT" + database=$prefix"DATABASE" + user=$prefix"USER" + pwd=$prefix"PASSWORD" + + cat>>$secret_yaml< /dev/null 2>&1 + touch $secret_yaml + for s in $svc_list + do + if [ useOneHost == 0 ]; then + mysqlHost="ts-$s-mysql-leader" + fi + gen_secret_for_tt $s $mysqlHost $mysqlUser $mysqlPassword $mysqlDatabase + done +} + +function update_tt_dp_cm { + nacosCM="$1" + rabbitmqCM="$2" + + cp $dp_sample_yaml $dp_yaml + + if [ "$(uname)"="Darwin" ]; then + sed -i "" "s/nacos/${nacosCM}/g" $dp_yaml + sed -i "" "s/rabbitmq/${rabbitmqCM}/g" $dp_yaml + else + sed -i "s/nacos/${nacosCM}/g" $dp_yaml + sed -i "s/rabbitmq/${rabbitmqCM}/g" $dp_yaml + fi +} + +function update_tt_sw_dp_cm { + nacosCM="$1" + rabbitmqCM="$2" + + cp $sw_dp_sample_yaml $sw_dp_yaml + if [ "$(uname)"="Darwin" ]; then + sed -i "" "s/nacos/${nacosCM}/g" $sw_dp_yaml + sed -i "" "s/rabbitmq/${rabbitmqCM}/g" $sw_dp_yaml + else + sed -i "s/nacos/${nacosCM}/g" $sw_dp_yaml + sed -i "s/rabbitmq/${rabbitmqCM}/g" $sw_dp_yaml + fi +} + diff --git a/hack/deploy/reset.sh b/hack/deploy/reset.sh new file mode 100755 index 000000000..1555782ae --- /dev/null +++ b/hack/deploy/reset.sh @@ -0,0 +1,19 @@ +#!/bin/bash + +TT_ROOT=$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd ) + +source "$TT_ROOT/utils.sh" + +namespace="$1" + +kubectl delete -f deployment/kubernetes-manifests/quickstart-k8s/yamls -n $namespace + +helm ls -n $namespace | grep ts- | awk '{print $1}' | xargs helm uninstall -n $namespace + +helm uninstall $rabbitmqRelease -n $namespace +helm uninstall $nacosRelease -n $namespace +helm uninstall $nacosDBRelease -n $namespace + + +kubectl delete -f deployment/kubernetes-manifests/skywalking -n $namespace + diff --git a/hack/deploy/utils.sh b/hack/deploy/utils.sh new file mode 100755 index 000000000..b45c7468e --- /dev/null +++ b/hack/deploy/utils.sh @@ -0,0 +1,117 @@ +#!/bin/bash + + +TT_ROOT=$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd ) +source "$TT_ROOT/gen-mysql-secret.sh" + +mysqlCharts=deployment/kubernetes-manifests/quickstart-k8s/charts/mysql +nacosCharts=deployment/kubernetes-manifests/quickstart-k8s/charts/nacos +rabbitmqCharts=deployment/kubernetes-manifests/quickstart-k8s/charts/rabbitmq + +# nacos mysql parameters +nacosDBRelease="nacosdb" +nacosDBHost="${nacosDBRelease}-mysql-leader" +nacosDBUser="nacos" +nacosDBPass="Abcd1234#" +nacosDBName="nacos" + +# nacos server parameters +nacosRelease="nacos" + +# rabbitmq parameters +rabbitmqRelease="rabbitmq" + +# mysql of train ticket parameters +tsUser="ts" +tsPassword="Ts_123456" +tsDB="ts" + + +function deploy_infrastructures { + namespace=$1 + echo "Start deployment Step <1/3>------------------------------------" + echo "Start to deploy mysql cluster for nacos." + helm install $nacosDBRelease --set mysql.mysqlUser=$nacosDBUser --set mysql.mysqlPassword=$nacosDBPass --set mysql.mysqlDatabase=$nacosDBName $mysqlCharts -n $namespace + echo "Waiting for mysql cluster of nacos to be ready ......" + kubectl rollout status statefulset/$nacosDBRelease-mysql -n $namespace + echo "Start to deploy nacos." + helm install $nacosRelease --set nacos.db.host=$nacosDBHost --set nacos.db.username=$nacosDBUser --set nacos.db.name=$nacosDBName --set nacos.db.password=$nacosDBPass $nacosCharts -n $namespace + echo "Waiting for nacos to be ready ......" + kubectl rollout status statefulset/$nacosRelease -n $namespace + echo "Start to deploy rabbitmq." + helm install $rabbitmqRelease $rabbitmqCharts -n $namespace + echo "Waiting for rabbitmq to be ready ......" + kubectl rollout status deployment/$rabbitmqRelease -n $namespace + echo "End deployment Step <1/3>--------------------------------------" +} + +function deploy_monitoring { + echo "Start deploy prometheus and grafana" + kubectl apply -f deployment/kubernetes-manifests/prometheus +} + +function deploy_tracing { + echo "Start deploy skywalking" + namespace=$1 + kubectl apply -f deployment/kubernetes-manifests/skywalking -n $namespace +} + +function deploy_tt_mysql_all_in_one { + namespace=$1 + tsMysqlName="tsdb" + echo "Start deployment Step <2/3>: mysql cluster of train-ticket services----------------------" + helm install $tsMysqlName --set mysql.mysqlUser=$tsUser --set mysql.mysqlPassword=$tsPassword --set mysql.mysqlDatabase=$tsDB $mysqlCharts -n $namespace 1>/dev/null + echo "Waiting for mysql cluster of train-ticket to be ready ......" + kubectl rollout status statefulset/${tsMysqlName}-mysql -n $namespace + gen_secret_for_services $tsUser $tsPassword $tsDB "${tsMysqlName}-mysql-leader" + echo "End deployment Step <2/3>-----------------------------------------------------------------" +} + +function deploy_tt_mysql_each_service { + echo "Start deployment Step <2/3>: mysql clusters of train-ticket services. ----------------------" + namespace=$1 + for s in $svc_list + do + mysqlName="ts-$s" + helm install $mysqlName --set mysql.mysqlUser=$tsUser --set mysql.mysqlPassword=$tsPassword --set mysql.mysqlDatabase=$tsDB $mysqlCharts -n $namespace 1>/dev/null + done + + echo "Waiting for mysql clusters of train-ticket services to be ready ......" + for s in $svc_list + do + mysqlName="ts-$s" + kubectl rollout status statefulset/$mysqlName-mysql -n $namespace + done + + gen_secret_for_services $tsUser $tsPassword $tsDB + echo "End deployment Step <2/3>---------------------------------------------------------------------" +} + +function deploy_tt_secret { + namespace=$1 + echo "Start deployment Step <3/3>: train-ticket services--------------------------------------------" + echo "Start to deploy secret of train-ticket services." + kubectl apply -f deployment/kubernetes-manifests/quickstart-k8s/yamls/secret.yaml -n $namespace > /dev/null +} + +function deploy_tt_svc { + namespace=$1 + kubectl apply -f deployment/kubernetes-manifests/quickstart-k8s/yamls/svc.yaml -n $namespace > /dev/null +} + +function deploy_tt_dp { + namespace=$1 + echo "Start to deploy train-ticket deployments." + update_tt_dp_cm $nacosRelease $rabbitmqRelease + kubectl apply -f deployment/kubernetes-manifests/quickstart-k8s/yamls/deploy.yaml -n $namespace > /dev/null + echo "End deployment Step <3/3>----------------------------------------------------------------------" +} + +function deploy_tt_dp_sw { + namespace=$1 + echo "Start to deploy train-ticket deployments with skywalking agent." + update_tt_sw_dp_cm $nacosRelease $rabbitmqRelease + kubectl apply -f deployment/kubernetes-manifests/quickstart-k8s/yamls/sw_deploy.yaml -n $namespace > /dev/null + echo "End deployment Step <3/3>----------------------------------------------------------------------" +} + diff --git a/image/2.png b/image/2.png index a40434a0dfe041e0b6fdd565708885f0f0ae8f67..6053d2cb4218a49a7d66e304910bd45bc637b8d0 100644 GIT binary patch literal 254814 zcmeFZc|6qX-#A<%$%z(GSxY4e$!@Y$sD!eHP^s)B%wRCI2_Z)+>yWL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SAyfjuNAK9VQ?eVj#*8`% zY;NWqNckb*cFMRk-1X)^H(~!jzOMfd2jL$K1hJA})18w`^)fMzn~waU8&t)_EDBfv z>p~T&_v=Qo5nv6wZrVOe4T!1vFVaQya%Fduah90Djr&cy5bM4NzI)ugG=Xe7vE~nt zg3sZi+*Rj-X8{eVo_{e(#5euq|N1Tp6j=mNL;#ULf1QZA<6`zjEg;X$xV(9ZjVVo& zl>S4gn6?^tDi){|lT?7nlRriO1USX!N`=B*NMoB#x_`ILl;p*x1GCQgCnl=c zm;iw^EdbNUWz+5w5OW3~(hQFQESZt35`r04De9i=@3$xq+Kbs*CB*smb2c$kL)AIi zsS9)H<*468q%nZn0}j_WKlb=S2c}$RC2(FbG1p7>+{&=+P|t87F`` z-2TN*3J3D-TYAlz&U}{50O)8xMs0F@F8>W9O%>o|y_ofR@ut+6){>!zOUIGp{=@P6 qUq;LOO&gSu`2UVai1Dackhz}LkXSgkZAScpbEhp&m7KhM_x}Oa8gsA! diff --git a/old-docs/Lib/ms-monitoring-core/pom.xml b/old-docs/Lib/ms-monitoring-core/pom.xml index 77394331c..65a2ee11e 100644 --- a/old-docs/Lib/ms-monitoring-core/pom.xml +++ b/old-docs/Lib/ms-monitoring-core/pom.xml @@ -14,7 +14,7 @@ org.services ts-service 0.1.0 - ../ + ../pom.xml diff --git a/old-docs/ts-ui-test/src/test/java/TestServiceTravel.java b/old-docs/ts-ui-test/src/test/java/TestServiceTravel.java index ba1ca151f..4c2c9aa60 100644 --- a/old-docs/ts-ui-test/src/test/java/TestServiceTravel.java +++ b/old-docs/ts-ui-test/src/test/java/TestServiceTravel.java @@ -20,7 +20,7 @@ public class TestServiceTravel { public class TravelInfo{ String tripId; String trainTypeId; - String startingStationId; + String startStationName; String stationsId; String terminalStationId; String startingTime; @@ -28,7 +28,7 @@ public class TravelInfo{ TravelInfo ( String tripId, String trainTypeId, - String startingStationId, + String startStationName, String stationsId, String terminalStationId, String startingTime, @@ -36,7 +36,7 @@ public class TravelInfo{ ){ this.tripId = tripId; this.trainTypeId = trainTypeId; - this.startingStationId = startingStationId; + this.startStationName = startingStationId; this.stationsId = stationsId; this.terminalStationId = terminalStationId; this.startingTime = startingTime; @@ -67,7 +67,7 @@ public void testTravel(TravelInfo travelinfo) throws Exception{ driver.findElement(By.id("travel_update_trainTypeId")).sendKeys(travelinfo.trainTypeId); driver.findElement(By.id("travel_update_startingStationId")).clear(); - driver.findElement(By.id("travel_update_startingStationId")).sendKeys(travelinfo.startingStationId); + driver.findElement(By.id("travel_update_startingStationId")).sendKeys(travelinfo.startStationName); driver.findElement(By.id("travel_update_stationsId")).clear(); driver.findElement(By.id("travel_update_stationsId")).sendKeys(travelinfo.stationsId); diff --git a/pom.xml b/pom.xml index a6ce6c259..119a77797 100644 --- a/pom.xml +++ b/pom.xml @@ -11,10 +11,11 @@ org.springframework.boot spring-boot-starter-parent - 1.5.22.RELEASE + 2.3.12.RELEASE + ts-common ts-verification-code-service ts-contacts-service ts-order-service @@ -27,7 +28,6 @@ ts-preserve-service ts-preserve-other-service ts-basic-service - ts-ticketinfo-service ts-price-service ts-notification-service ts-security-service @@ -41,8 +41,8 @@ ts-seat-service ts-travel-plan-service ts-route-plan-service - ts-food-map-service ts-food-service + ts-station-food-service ts-consign-price-service ts-consign-service ts-admin-order-service @@ -50,20 +50,33 @@ ts-admin-route-service ts-admin-travel-service ts-admin-user-service - ts-common ts-auth-service ts-user-service ts-delivery-service - - + ts-train-food-service + ts-gateway-service + ts-food-delivery-service + ts-wait-order-service + + + + + + + com.alibaba.cloud + spring-cloud-starter-alibaba-nacos-discovery + 2.2.7.RELEASE + + org.springframework.boot spring-boot-starter-web + 2.3.12.RELEASE org.springframework.boot @@ -77,10 +90,13 @@ org.springframework.boot spring-boot-starter-actuator + org.projectlombok lombok + + io.springfox springfox-swagger2 @@ -92,6 +108,7 @@ 2.4.0 + org.springframework.boot spring-boot-starter-test @@ -108,6 +125,8 @@ mockito-core test + + com.alibaba fastjson @@ -130,16 +149,27 @@ - - - - - - - - - - + + + + + + + org.springframework.cloud + spring-cloud-dependencies + Hoxton.SR12 + pom + import + + + com.alibaba.cloud + spring-cloud-alibaba-dependencies + 2.2.7.RELEASE + pom + import + + + @@ -173,11 +203,6 @@ - - - target/jacoco.exec - - diff --git a/ts-admin-basic-info-service/pom.xml b/ts-admin-basic-info-service/pom.xml index 4ca3860e9..b1044be98 100644 --- a/ts-admin-basic-info-service/pom.xml +++ b/ts-admin-basic-info-service/pom.xml @@ -16,7 +16,7 @@ org.services ts-service 0.1.0 - ../ + ../pom.xml @@ -25,21 +25,15 @@ - - org.springframework.boot - spring-boot-starter-web - - - org.springframework.boot - spring-boot-starter-actuator - org.services ts-common 0.1.0 - - + + jakarta.validation + jakarta.validation-api + diff --git a/ts-admin-basic-info-service/src/main/java/adminbasic/AdminBasicInfoApplication.java b/ts-admin-basic-info-service/src/main/java/adminbasic/AdminBasicInfoApplication.java index e838cecb2..49062853b 100644 --- a/ts-admin-basic-info-service/src/main/java/adminbasic/AdminBasicInfoApplication.java +++ b/ts-admin-basic-info-service/src/main/java/adminbasic/AdminBasicInfoApplication.java @@ -3,6 +3,8 @@ import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.boot.web.client.RestTemplateBuilder; +import org.springframework.cloud.client.discovery.EnableDiscoveryClient; +import org.springframework.cloud.client.loadbalancer.LoadBalanced; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.EnableAspectJAutoProxy; import org.springframework.integration.annotation.IntegrationComponentScan; @@ -18,12 +20,14 @@ @EnableAsync @IntegrationComponentScan @EnableSwagger2 +@EnableDiscoveryClient public class AdminBasicInfoApplication { public static void main(String[] args) { SpringApplication.run(AdminBasicInfoApplication.class, args); } + @LoadBalanced @Bean public RestTemplate restTemplate(RestTemplateBuilder builder) { return builder.build(); diff --git a/ts-admin-basic-info-service/src/main/java/adminbasic/controller/AdminBasicInfoController.java b/ts-admin-basic-info-service/src/main/java/adminbasic/controller/AdminBasicInfoController.java index 8d25812bb..a4909d81e 100644 --- a/ts-admin-basic-info-service/src/main/java/adminbasic/controller/AdminBasicInfoController.java +++ b/ts-admin-basic-info-service/src/main/java/adminbasic/controller/AdminBasicInfoController.java @@ -2,6 +2,10 @@ import adminbasic.entity.*; import adminbasic.service.AdminBasicInfoService; +import edu.fudan.common.entity.Config; +import edu.fudan.common.entity.Contacts; +import edu.fudan.common.entity.Station; +import edu.fudan.common.entity.TrainType; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; @@ -30,140 +34,140 @@ public String home(@RequestHeader HttpHeaders headers) { @CrossOrigin(origins = "*") @GetMapping(path = "/adminbasic/contacts") public HttpEntity getAllContacts(@RequestHeader HttpHeaders headers) { - AdminBasicInfoController.LOGGER.info("[Admin Basic Info Service][Find All Contacts by admin "); + AdminBasicInfoController.LOGGER.info("[getAllContacts][Find All Contacts by admin][getAllContacts] "); return ok(adminBasicInfoService.getAllContacts(headers)); } @CrossOrigin(origins = "*") @DeleteMapping(path = "/adminbasic/contacts/{contactsId}") public HttpEntity deleteContacts(@PathVariable String contactsId, @RequestHeader HttpHeaders headers) { - AdminBasicInfoController.LOGGER.info("[Admin Basic Info Service][Delete Contacts by admin "); + AdminBasicInfoController.LOGGER.info("[deleteContacts][Delete Contacts by admin][contactsId: {}]", contactsId); return ok(adminBasicInfoService.deleteContact(contactsId, headers)); } @CrossOrigin(origins = "*") @PutMapping(path = "/adminbasic/contacts") public HttpEntity modifyContacts(@RequestBody Contacts mci, @RequestHeader HttpHeaders headers) { - AdminBasicInfoController.LOGGER.info("[Admin Basic Info Service][Modify Contacts by admin: "); + AdminBasicInfoController.LOGGER.info("[modifyContacts][Modify Contacts by admin][Contacts name:{}]", mci.getName()); return ok(adminBasicInfoService.modifyContact(mci, headers)); } @CrossOrigin(origins = "*") @PostMapping(path = "/adminbasic/contacts") public HttpEntity addContacts(@RequestBody Contacts c, @RequestHeader HttpHeaders headers) { - AdminBasicInfoController.LOGGER.info("[Admin Basic Info Service][Modify Contacts by admin "); + AdminBasicInfoController.LOGGER.info("[addContacts][Modify Contacts by admin][Contacts name: {}]", c.getName()); return ok(adminBasicInfoService.addContact(c, headers)); } @CrossOrigin(origins = "*") @GetMapping(path = "/adminbasic/stations") public HttpEntity getAllStations(@RequestHeader HttpHeaders headers) { - AdminBasicInfoController.LOGGER.info("[Admin Basic Info Service][Find All Station by admin "); + AdminBasicInfoController.LOGGER.info("[getAllStations][Find All Station by admin][getAllStations]"); return ok(adminBasicInfoService.getAllStations(headers)); } @CrossOrigin(origins = "*") - @DeleteMapping(path = "/adminbasic/stations") - public HttpEntity deleteStation(@RequestBody Station s, @RequestHeader HttpHeaders headers) { - AdminBasicInfoController.LOGGER.info("[Admin Basic Info Service][Delete Station by admin "); - return ok(adminBasicInfoService.deleteStation(s, headers)); + @DeleteMapping(path = "/adminbasic/stations/{id}") + public HttpEntity deleteStation(@PathVariable String id, @RequestHeader HttpHeaders headers) { + AdminBasicInfoController.LOGGER.info("[deleteStation][Delete Station by admin][Station id: {}]", id); + return ok(adminBasicInfoService.deleteStation(id, headers)); } @CrossOrigin(origins = "*") @PutMapping(path = "/adminbasic/stations") public HttpEntity modifyStation(@RequestBody Station s, @RequestHeader HttpHeaders headers) { - AdminBasicInfoController.LOGGER.info("[Admin Basic Info Service][Modify Station by admin "); + AdminBasicInfoController.LOGGER.info("[modifyStation][Modify Station by admin][Station id: {}]", s.getId()); return ok(adminBasicInfoService.modifyStation(s, headers)); } @CrossOrigin(origins = "*") @PostMapping(path = "/adminbasic/stations") public HttpEntity addStation(@RequestBody Station s, @RequestHeader HttpHeaders headers) { - AdminBasicInfoController.LOGGER.info("[Admin Basic Info Service][Modify Station by admin"); + AdminBasicInfoController.LOGGER.info("[addStation][Add Station by admin][Station id: {}]", s.getId()); return ok(adminBasicInfoService.addStation(s, headers)); } @CrossOrigin(origins = "*") @GetMapping(path = "/adminbasic/trains") public HttpEntity getAllTrains(@RequestHeader HttpHeaders headers) { - AdminBasicInfoController.LOGGER.info("[Admin Basic Info Service][Find All Train by admin: "); + AdminBasicInfoController.LOGGER.info("[getAllTrains][Find All Train by admin][getAllStations]"); return ok(adminBasicInfoService.getAllTrains(headers)); } @CrossOrigin(origins = "*") @DeleteMapping(path = "/adminbasic/trains/{id}") public HttpEntity deleteTrain(@PathVariable String id, @RequestHeader HttpHeaders headers) { - AdminBasicInfoController.LOGGER.info("[Admin Basic Info Service][Delete Train by admin"); + AdminBasicInfoController.LOGGER.info("[deleteTrain][Delete Train by admin][train id: {}]", id); return ok(adminBasicInfoService.deleteTrain(id, headers)); } @CrossOrigin(origins = "*") @PutMapping(path = "/adminbasic/trains") public HttpEntity modifyTrain(@RequestBody TrainType t, @RequestHeader HttpHeaders headers) { - AdminBasicInfoController.LOGGER.info("[Admin Basic Info Service][Modify Train by admin "); + AdminBasicInfoController.LOGGER.info("[modifyTrain][Modify Train by admin][TrainType id: {}]", t.getId()); return ok(adminBasicInfoService.modifyTrain(t, headers)); } @CrossOrigin(origins = "*") @PostMapping(path = "/adminbasic/trains") public HttpEntity addTrain(@RequestBody TrainType t, @RequestHeader HttpHeaders headers) { - AdminBasicInfoController.LOGGER.info("[Admin Basic Info Service][Modify Train by admin "); + AdminBasicInfoController.LOGGER.info("[addTrain][Add Train by admin][TrainType id: {}]", t.getId()); return ok(adminBasicInfoService.addTrain(t, headers)); } @CrossOrigin(origins = "*") @GetMapping(path = "/adminbasic/configs") public HttpEntity getAllConfigs(@RequestHeader HttpHeaders headers) { - AdminBasicInfoController.LOGGER.info("[Admin Basic Info Service][Find All Config by admin "); + AdminBasicInfoController.LOGGER.info("[getAllConfigs][Find All Config by admin][getAllConfigs]"); return ok(adminBasicInfoService.getAllConfigs(headers)); } @CrossOrigin(origins = "*") @DeleteMapping(path = "/adminbasic/configs/{name}") public HttpEntity deleteConfig(@PathVariable String name, @RequestHeader HttpHeaders headers) { - AdminBasicInfoController.LOGGER.info("[Admin Basic Info Service][Delete Config by admin "); + AdminBasicInfoController.LOGGER.info("[deleteConfig][Delete Config by admin][Config name: {}]", name); return ok(adminBasicInfoService.deleteConfig(name, headers)); } @CrossOrigin(origins = "*") @PutMapping(path = "/adminbasic/configs") public HttpEntity modifyConfig(@RequestBody Config c, @RequestHeader HttpHeaders headers) { - AdminBasicInfoController.LOGGER.info("[Admin Basic Info Service][Modify Config by admin "); + AdminBasicInfoController.LOGGER.info("[modifyConfig][Modify Config by admin][Config name: {}]", c.getName()); return ok(adminBasicInfoService.modifyConfig(c, headers)); } @CrossOrigin(origins = "*") @PostMapping(path = "/adminbasic/configs") public HttpEntity addConfig(@RequestBody Config c, @RequestHeader HttpHeaders headers) { - AdminBasicInfoController.LOGGER.info("[Admin Basic Info Service][Modify Config by admin "); + AdminBasicInfoController.LOGGER.info("[addConfig][Add Config by admin][Config name: {}]", c.getName()); return ok(adminBasicInfoService.addConfig(c, headers)); } @CrossOrigin(origins = "*") @GetMapping(path = "/adminbasic/prices") public HttpEntity getAllPrices(@RequestHeader HttpHeaders headers) { - AdminBasicInfoController.LOGGER.info("[Admin Basic Info Service][Find All Price by admin "); + AdminBasicInfoController.LOGGER.info("[getAllPrices][Find All Price by admin][getAllPrices]"); return ok(adminBasicInfoService.getAllPrices(headers)); } @CrossOrigin(origins = "*") - @DeleteMapping(path = "/adminbasic/prices") - public HttpEntity deletePrice(@RequestBody PriceInfo pi, @RequestHeader HttpHeaders headers) { - AdminBasicInfoController.LOGGER.info("[Admin Basic Info Service][Delete Price by admin "); - return ok(adminBasicInfoService.deletePrice(pi, headers)); + @DeleteMapping(path = "/adminbasic/prices/{pricesId}") + public HttpEntity deletePrice(@PathVariable String pricesId, @RequestHeader HttpHeaders headers) { + AdminBasicInfoController.LOGGER.info("[deletePrice][Delete Price by admin][PriceInfo id: {}]", pricesId); + return ok(adminBasicInfoService.deletePrice(pricesId, headers)); } @CrossOrigin(origins = "*") @PutMapping(path = "/adminbasic/prices") public HttpEntity modifyPrice(@RequestBody PriceInfo pi, @RequestHeader HttpHeaders headers) { - AdminBasicInfoController.LOGGER.info("[Admin Basic Info Service][Modify Price by admin "); + AdminBasicInfoController.LOGGER.info("[modifyPrice][Modify Price by admin][PriceInfo id: {}]", pi.getId()); return ok(adminBasicInfoService.modifyPrice(pi, headers)); } @CrossOrigin(origins = "*") @PostMapping(path = "/adminbasic/prices") public HttpEntity addPrice(@RequestBody PriceInfo pi, @RequestHeader HttpHeaders headers) { - AdminBasicInfoController.LOGGER.info("[Admin Basic Info Service][Add Price by admin"); + AdminBasicInfoController.LOGGER.info("[addPrice][Add Price by admin[PriceInfo id: {}]", pi.getId()); return ok(adminBasicInfoService.addPrice(pi, headers)); } diff --git a/ts-admin-basic-info-service/src/main/java/adminbasic/entity/Contacts.java b/ts-admin-basic-info-service/src/main/java/adminbasic/entity/Contacts.java deleted file mode 100644 index 6bb2bcc1c..000000000 --- a/ts-admin-basic-info-service/src/main/java/adminbasic/entity/Contacts.java +++ /dev/null @@ -1,54 +0,0 @@ -package adminbasic.entity; - -import lombok.Data; -import lombok.ToString; - -import java.io.Serializable; -import java.util.UUID; - -/** - * @author fdse - */ -@ToString -@Data -public class Contacts implements Serializable { - - private UUID id; - - private UUID accountId; - - private String name; - - private int documentType; - - private String documentNumber; - - private String phoneNumber; - - - @Override - public boolean equals(Object obj) { - if (this == obj) { - return true; - } - if (obj == null) { - return false; - } - if (getClass() != obj.getClass()) { - return false; - } - Contacts other = (Contacts) obj; - return name.equals(other.getName()) - && accountId.equals(other.getAccountId()) - && documentNumber.equals(other.getDocumentNumber()) - && phoneNumber.equals(other.getPhoneNumber()) - && documentType == other.getDocumentType(); - } - - @Override - public int hashCode() { - int result = 17; - result = 31 * result + (id == null ? 0 : id.hashCode()); - return result; - } -} diff --git a/ts-admin-basic-info-service/src/main/java/adminbasic/entity/Station.java b/ts-admin-basic-info-service/src/main/java/adminbasic/entity/Station.java deleted file mode 100644 index b42ec4326..000000000 --- a/ts-admin-basic-info-service/src/main/java/adminbasic/entity/Station.java +++ /dev/null @@ -1,40 +0,0 @@ -package adminbasic.entity; - -import lombok.Data; - -import javax.validation.Valid; -import javax.validation.constraints.NotNull; - -/** - * @author fdse - */ -@Data -public class Station { - - private String id; - - @Valid - @NotNull - private String name; - - private int stayTime; - - public Station(){ - this.name = ""; - } - - - - public Station(String id, String name) { - this.id = id; - this.name = name; - } - - - public Station(String id, String name, int stayTime) { - this.id = id; - this.name = name; - this.stayTime = stayTime; - } - -} diff --git a/ts-admin-basic-info-service/src/main/java/adminbasic/entity/TrainType.java b/ts-admin-basic-info-service/src/main/java/adminbasic/entity/TrainType.java deleted file mode 100644 index d61b06ab1..000000000 --- a/ts-admin-basic-info-service/src/main/java/adminbasic/entity/TrainType.java +++ /dev/null @@ -1,38 +0,0 @@ -package adminbasic.entity; - - -import lombok.Data; -import lombok.NoArgsConstructor; - -/** - * @author fdse - */ -@Data -public class TrainType { - - private String id; - - private int economyClass; - - private int confortClass; - - private int averageSpeed; - - public TrainType(){ - //Default Constructor - } - - public TrainType(String id, int economyClass, int confortClass) { - this.id = id; - this.economyClass = economyClass; - this.confortClass = confortClass; - } - - public TrainType(String id, int economyClass, int confortClass, int averageSpeed) { - this.id = id; - this.economyClass = economyClass; - this.confortClass = confortClass; - this.averageSpeed = averageSpeed; - } - -} diff --git a/ts-admin-basic-info-service/src/main/java/adminbasic/service/AdminBasicInfoService.java b/ts-admin-basic-info-service/src/main/java/adminbasic/service/AdminBasicInfoService.java index aaa19168b..db1f0f75d 100644 --- a/ts-admin-basic-info-service/src/main/java/adminbasic/service/AdminBasicInfoService.java +++ b/ts-admin-basic-info-service/src/main/java/adminbasic/service/AdminBasicInfoService.java @@ -1,6 +1,10 @@ package adminbasic.service; import adminbasic.entity.*; +import edu.fudan.common.entity.Config; +import edu.fudan.common.entity.Contacts; +import edu.fudan.common.entity.Station; +import edu.fudan.common.entity.TrainType; import edu.fudan.common.util.Response; import org.springframework.http.HttpHeaders; @@ -25,7 +29,7 @@ public interface AdminBasicInfoService { * @param headers headers * @return Response */ - Response addContact( Contacts c, HttpHeaders headers); + Response addContact(Contacts c, HttpHeaders headers); /** * delete contact with contact id @@ -67,11 +71,11 @@ public interface AdminBasicInfoService { /** * delete station with station information * - * @param s station information + * @param id station id * @param headers headers * @return Response */ - Response deleteStation(Station s, HttpHeaders headers); + Response deleteStation(String id, HttpHeaders headers); /** * modify station with station information @@ -178,11 +182,11 @@ public interface AdminBasicInfoService { /** * delete price with price info * - * @param pi price info + * @param pricesId price config id * @param headers headers * @return Response */ - Response deletePrice(PriceInfo pi, HttpHeaders headers); + Response deletePrice(String pricesId, HttpHeaders headers); /** * modify price with price info diff --git a/ts-admin-basic-info-service/src/main/java/adminbasic/service/AdminBasicInfoServiceImpl.java b/ts-admin-basic-info-service/src/main/java/adminbasic/service/AdminBasicInfoServiceImpl.java index ad970e89a..3d5898831 100644 --- a/ts-admin-basic-info-service/src/main/java/adminbasic/service/AdminBasicInfoServiceImpl.java +++ b/ts-admin-basic-info-service/src/main/java/adminbasic/service/AdminBasicInfoServiceImpl.java @@ -1,10 +1,15 @@ package adminbasic.service; import adminbasic.entity.*; +import edu.fudan.common.entity.Config; +import edu.fudan.common.entity.Contacts; +import edu.fudan.common.entity.Station; +import edu.fudan.common.entity.TrainType; import edu.fudan.common.util.Response; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.cloud.client.discovery.DiscoveryClient; import org.springframework.http.HttpEntity; import org.springframework.http.HttpHeaders; import org.springframework.http.HttpMethod; @@ -22,20 +27,22 @@ public class AdminBasicInfoServiceImpl implements AdminBasicInfoService { @Autowired private RestTemplate restTemplate; + @Autowired + private DiscoveryClient discoveryClient; + private static final Logger LOGGER = LoggerFactory.getLogger(AdminBasicInfoServiceImpl.class); - String stations = "http://ts-station-service:12345/api/v1/stationservice/stations"; - String trains = "http://ts-train-service:14567/api/v1/trainservice/trains"; - String configs = "http://ts-config-service:15679/api/v1/configservice/configs"; - String prices = "http://ts-price-service:16579/api/v1/priceservice/prices"; + private String getServiceUrl(String serviceName) { + return "http://" + serviceName; + } @Override public Response getAllContacts(HttpHeaders headers) { Response result; - HttpEntity requestEntity = new HttpEntity(headers); + String contacts_service_url = getServiceUrl("ts-contacts-service"); ResponseEntity re = restTemplate.exchange( - "http://ts-contacts-service:12347/api/v1/contactservice/contacts", + contacts_service_url + "/api/v1/contactservice/contacts", HttpMethod.GET, requestEntity, Response.class); @@ -47,10 +54,10 @@ public Response getAllContacts(HttpHeaders headers) { @Override public Response deleteContact(String contactsId, HttpHeaders headers) { Response result; - HttpEntity requestEntity = new HttpEntity(headers); + String contacts_service_url = getServiceUrl("ts-contacts-service"); ResponseEntity re = restTemplate.exchange( - "http://ts-contacts-service:12347/api/v1/contactservice/contacts/" + contactsId, + contacts_service_url + "/api/v1/contactservice/contacts/" + contactsId, HttpMethod.DELETE, requestEntity, Response.class); @@ -62,10 +69,10 @@ public Response deleteContact(String contactsId, HttpHeaders headers) { @Override public Response modifyContact(Contacts mci, HttpHeaders headers) { Response result; - LOGGER.info("MODIFY CONTACTS: " + mci.toString()); HttpEntity requestEntity = new HttpEntity(mci, headers); + String contacts_service_url = getServiceUrl("ts-contacts-service"); ResponseEntity re = restTemplate.exchange( - "http://ts-contacts-service:12347/api/v1/contactservice/contacts", + contacts_service_url + "/api/v1/contactservice/contacts", HttpMethod.PUT, requestEntity, Response.class); @@ -78,10 +85,10 @@ public Response modifyContact(Contacts mci, HttpHeaders headers) { @Override public Response addContact(Contacts c, HttpHeaders headers) { Response result; - HttpEntity requestEntity = new HttpEntity(c, headers); + String contacts_service_url = getServiceUrl("ts-contacts-service"); ResponseEntity re = restTemplate.exchange( - "http://ts-contacts-service:12347/api/v1/contactservice/contacts/admin", + contacts_service_url + "/api/v1/contactservice/contacts/admin", HttpMethod.POST, requestEntity, Response.class); @@ -92,8 +99,9 @@ public Response addContact(Contacts c, HttpHeaders headers) { @Override public Response getAllStations(HttpHeaders headers) { - HttpEntity requestEntity = new HttpEntity(headers); + String station_service_url = getServiceUrl("ts-station-service"); + String stations = station_service_url + "/api/v1/stationservice/stations"; ResponseEntity re = restTemplate.exchange( stations, HttpMethod.GET, @@ -108,8 +116,9 @@ public Response getAllStations(HttpHeaders headers) { @Override public Response addStation(Station s, HttpHeaders headers) { Response result; - HttpEntity requestEntity = new HttpEntity(s, headers); + String station_service_url = getServiceUrl("ts-station-service"); + String stations = station_service_url + "/api/v1/stationservice/stations"; ResponseEntity re = restTemplate.exchange( stations, HttpMethod.POST, @@ -120,25 +129,26 @@ public Response addStation(Station s, HttpHeaders headers) { } @Override - public Response deleteStation(Station s, HttpHeaders headers) { + public Response deleteStation(String id, HttpHeaders headers) { Response result; - - HttpEntity requestEntity = new HttpEntity(s, headers); + HttpEntity requestEntity = new HttpEntity(headers); + String station_service_url = getServiceUrl("ts-station-service"); + String path = station_service_url + "/api/v1/stationservice/stations/" + id; ResponseEntity re = restTemplate.exchange( - stations, + path, HttpMethod.DELETE, requestEntity, Response.class); result = re.getBody(); return result; - } @Override public Response modifyStation(Station s, HttpHeaders headers) { Response result; - HttpEntity requestEntity = new HttpEntity(s, headers); + String station_service_url = getServiceUrl("ts-station-service"); + String stations = station_service_url + "/api/v1/stationservice/stations"; ResponseEntity re = restTemplate.exchange( stations, HttpMethod.PUT, @@ -152,8 +162,9 @@ public Response modifyStation(Station s, HttpHeaders headers) { @Override public Response getAllTrains(HttpHeaders headers) { - HttpEntity requestEntity = new HttpEntity(headers); + String train_service_url = getServiceUrl("ts-train-service"); + String trains = train_service_url + "/api/v1/trainservice/trains"; ResponseEntity re = restTemplate.exchange( trains, HttpMethod.GET, @@ -167,8 +178,9 @@ public Response getAllTrains(HttpHeaders headers) { @Override public Response addTrain(TrainType t, HttpHeaders headers) { Response result; - HttpEntity requestEntity = new HttpEntity(t, headers); + String train_service_url = getServiceUrl("ts-train-service"); + String trains = train_service_url + "/api/v1/trainservice/trains"; ResponseEntity re = restTemplate.exchange( trains, HttpMethod.POST, @@ -182,10 +194,10 @@ public Response addTrain(TrainType t, HttpHeaders headers) { @Override public Response deleteTrain(String id, HttpHeaders headers) { Response result; - HttpEntity requestEntity = new HttpEntity(headers); + String train_service_url = getServiceUrl("ts-train-service"); ResponseEntity re = restTemplate.exchange( - "http://ts-train-service:14567/api/v1/trainservice/trains/" + id, + train_service_url + "/api/v1/trainservice/trains/" + id, HttpMethod.DELETE, requestEntity, Response.class); @@ -196,8 +208,9 @@ public Response deleteTrain(String id, HttpHeaders headers) { @Override public Response modifyTrain(TrainType t, HttpHeaders headers) { Response result; - HttpEntity requestEntity = new HttpEntity(t, headers); + String train_service_url = getServiceUrl("ts-train-service"); + String trains = train_service_url + "/api/v1/trainservice/trains"; ResponseEntity re = restTemplate.exchange( trains, HttpMethod.PUT, @@ -209,9 +222,9 @@ public Response modifyTrain(TrainType t, HttpHeaders headers) { @Override public Response getAllConfigs(HttpHeaders headers) { - - HttpEntity requestEntity = new HttpEntity(headers); + String config_service_url = getServiceUrl("ts-config-service"); + String configs = config_service_url + "/api/v1/configservice/configs"; ResponseEntity re = restTemplate.exchange( configs, HttpMethod.GET, @@ -223,9 +236,9 @@ public Response getAllConfigs(HttpHeaders headers) { @Override public Response addConfig(Config c, HttpHeaders headers) { - - HttpEntity requestEntity = new HttpEntity(c, headers); + String config_service_url = getServiceUrl("ts-config-service"); + String configs = config_service_url + "/api/v1/configservice/configs"; ResponseEntity re = restTemplate.exchange( configs, HttpMethod.POST, @@ -236,10 +249,10 @@ public Response addConfig(Config c, HttpHeaders headers) { @Override public Response deleteConfig(String name, HttpHeaders headers) { - HttpEntity requestEntity = new HttpEntity(headers); + String config_service_url = getServiceUrl("ts-config-service"); ResponseEntity re = restTemplate.exchange( - "http://ts-config-service:15679/api/v1/configservice/configs/" + name, + config_service_url + "/api/v1/configservice/configs/" + name, HttpMethod.DELETE, requestEntity, Response.class); @@ -248,9 +261,9 @@ public Response deleteConfig(String name, HttpHeaders headers) { @Override public Response modifyConfig(Config c, HttpHeaders headers) { - - HttpEntity requestEntity = new HttpEntity(c, headers); + String config_service_url = getServiceUrl("ts-config-service"); + String configs = config_service_url + "/api/v1/configservice/configs"; ResponseEntity re = restTemplate.exchange( configs, HttpMethod.PUT, @@ -261,23 +274,22 @@ public Response modifyConfig(Config c, HttpHeaders headers) { @Override public Response getAllPrices(HttpHeaders headers) { - - HttpEntity requestEntity = new HttpEntity(headers); + String price_service_url = getServiceUrl("ts-price-service"); + String prices = price_service_url + "/api/v1/priceservice/prices"; ResponseEntity re = restTemplate.exchange( prices, HttpMethod.GET, requestEntity, Response.class); - - AdminBasicInfoServiceImpl.LOGGER.info("[!!!!GetAllPriceResult] "); return re.getBody(); } @Override public Response addPrice(PriceInfo pi, HttpHeaders headers) { - HttpEntity requestEntity = new HttpEntity(pi, headers); + String price_service_url = getServiceUrl("ts-price-service"); + String prices = price_service_url + "/api/v1/priceservice/prices"; ResponseEntity re = restTemplate.exchange( prices, HttpMethod.POST, @@ -288,23 +300,24 @@ public Response addPrice(PriceInfo pi, HttpHeaders headers) { } @Override - public Response deletePrice(PriceInfo pi, HttpHeaders headers) { - - - HttpEntity requestEntity = new HttpEntity(pi, headers); + public Response deletePrice(String pricesId, HttpHeaders headers) { + HttpEntity requestEntity = new HttpEntity(headers); + String price_service_url = getServiceUrl("ts-price-service"); + String path = price_service_url + "/api/v1/priceservice/prices/" + pricesId; ResponseEntity re = restTemplate.exchange( - prices, + path, HttpMethod.DELETE, requestEntity, Response.class); return re.getBody(); - } @Override public Response modifyPrice(PriceInfo pi, HttpHeaders headers) { HttpEntity requestEntity = new HttpEntity(pi, headers); + String price_service_url = getServiceUrl("ts-price-service"); + String prices = price_service_url + "/api/v1/priceservice/prices"; ResponseEntity re = restTemplate.exchange( prices, HttpMethod.PUT, diff --git a/ts-admin-basic-info-service/src/main/resources/application.yml b/ts-admin-basic-info-service/src/main/resources/application.yml index 664ddc2ed..77366ca61 100644 --- a/ts-admin-basic-info-service/src/main/resources/application.yml +++ b/ts-admin-basic-info-service/src/main/resources/application.yml @@ -2,8 +2,12 @@ server: port: 18767 spring: + cloud: + nacos: + discovery: + server-addr: ${NACOS_ADDRS:nacos-0.nacos-headless.default.svc.cluster.local,nacos-1.nacos-headless.default.svc.cluster.local,nacos-2.nacos-headless.default.svc.cluster.local} application: name: ts-admin-basic-info-service swagger: - controllerPackage: adminbasic.microservice \ No newline at end of file + controllerPackage: adminbasic.microservice diff --git a/ts-admin-basic-info-service/src/test/java/adminbasic/controller/AdminBasicInfoControllerTest.java b/ts-admin-basic-info-service/src/test/java/adminbasic/controller/AdminBasicInfoControllerTest.java index 3deb7caca..a07d95c3d 100644 --- a/ts-admin-basic-info-service/src/test/java/adminbasic/controller/AdminBasicInfoControllerTest.java +++ b/ts-admin-basic-info-service/src/test/java/adminbasic/controller/AdminBasicInfoControllerTest.java @@ -3,6 +3,10 @@ import adminbasic.entity.*; import adminbasic.service.AdminBasicInfoService; import com.alibaba.fastjson.JSONObject; +import edu.fudan.common.entity.Config; +import edu.fudan.common.entity.Contacts; +import edu.fudan.common.entity.Station; +import edu.fudan.common.entity.TrainType; import edu.fudan.common.util.Response; import org.junit.Assert; import org.junit.Before; @@ -95,7 +99,7 @@ public void testGetAllStations() throws Exception { @Test public void testDeleteStation() throws Exception { Station s = new Station(); - Mockito.when(adminBasicInfoService.deleteStation(Mockito.any(Station.class), Mockito.any(HttpHeaders.class))).thenReturn(response); + Mockito.when(adminBasicInfoService.deleteStation(Mockito.anyString(), Mockito.any(HttpHeaders.class))).thenReturn(response); String requestJson = JSONObject.toJSONString(s); String result = mockMvc.perform(MockMvcRequestBuilders.delete("/api/v1/adminbasicservice/adminbasic/stations").contentType(MediaType.APPLICATION_JSON).content(requestJson)) .andExpect(MockMvcResultMatchers.status().isOk()) @@ -217,7 +221,7 @@ public void testGetAllPrices() throws Exception { @Test public void testDeletePrice() throws Exception { PriceInfo pi = new PriceInfo(); - Mockito.when(adminBasicInfoService.deletePrice(Mockito.any(PriceInfo.class), Mockito.any(HttpHeaders.class))).thenReturn(response); + Mockito.when(adminBasicInfoService.deletePrice(Mockito.anyString(), Mockito.any(HttpHeaders.class))).thenReturn(response); String requestJson = JSONObject.toJSONString(pi); String result = mockMvc.perform(MockMvcRequestBuilders.delete("/api/v1/adminbasicservice/adminbasic/prices").contentType(MediaType.APPLICATION_JSON).content(requestJson)) .andExpect(MockMvcResultMatchers.status().isOk()) diff --git a/ts-admin-basic-info-service/src/test/java/adminbasic/service/AdminBasicInfoServiceImplTest.java b/ts-admin-basic-info-service/src/test/java/adminbasic/service/AdminBasicInfoServiceImplTest.java index 87a86e50c..c63a0db2f 100644 --- a/ts-admin-basic-info-service/src/test/java/adminbasic/service/AdminBasicInfoServiceImplTest.java +++ b/ts-admin-basic-info-service/src/test/java/adminbasic/service/AdminBasicInfoServiceImplTest.java @@ -1,6 +1,10 @@ package adminbasic.service; import adminbasic.entity.*; +import edu.fudan.common.entity.Config; +import edu.fudan.common.entity.Contacts; +import edu.fudan.common.entity.Station; +import edu.fudan.common.entity.TrainType; import edu.fudan.common.util.Response; import org.junit.Assert; import org.junit.Before; @@ -111,7 +115,7 @@ public void testDeleteStation() { HttpMethod.DELETE, requestEntity, Response.class)).thenReturn(re); - response = adminBasicInfoService.deleteStation(s, headers); + response = adminBasicInfoService.deleteStation(s.getId(), headers); Assert.assertEquals(new Response<>(null, null, null), response); } @@ -257,7 +261,7 @@ public void testDeletePrice() { HttpMethod.DELETE, requestEntity, Response.class)).thenReturn(re); - response = adminBasicInfoService.deletePrice(pi, headers); + response = adminBasicInfoService.deletePrice(pi.getId(), headers); Assert.assertEquals(new Response<>(null, null, null), response); } diff --git a/ts-admin-order-service/pom.xml b/ts-admin-order-service/pom.xml index e67208a88..493a51007 100644 --- a/ts-admin-order-service/pom.xml +++ b/ts-admin-order-service/pom.xml @@ -15,7 +15,7 @@ ts-service org.services 0.1.0 - ../ + ../pom.xml @@ -29,8 +29,6 @@ ts-common 0.1.0 - - diff --git a/ts-admin-order-service/src/main/java/adminorder/AdminOrderApplication.java b/ts-admin-order-service/src/main/java/adminorder/AdminOrderApplication.java index 0956388c0..20978c1b6 100644 --- a/ts-admin-order-service/src/main/java/adminorder/AdminOrderApplication.java +++ b/ts-admin-order-service/src/main/java/adminorder/AdminOrderApplication.java @@ -3,6 +3,8 @@ import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.boot.web.client.RestTemplateBuilder; +import org.springframework.cloud.client.discovery.EnableDiscoveryClient; +import org.springframework.cloud.client.loadbalancer.LoadBalanced; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.EnableAspectJAutoProxy; import org.springframework.integration.annotation.IntegrationComponentScan; @@ -18,11 +20,13 @@ @EnableAsync @IntegrationComponentScan @EnableSwagger2 +@EnableDiscoveryClient public class AdminOrderApplication { public static void main(String[] args) { SpringApplication.run(AdminOrderApplication.class, args); } + @LoadBalanced @Bean public RestTemplate restTemplate(RestTemplateBuilder builder) { return builder.build(); diff --git a/ts-admin-order-service/src/main/java/adminorder/controller/AdminOrderController.java b/ts-admin-order-service/src/main/java/adminorder/controller/AdminOrderController.java index 607a53931..37677af82 100644 --- a/ts-admin-order-service/src/main/java/adminorder/controller/AdminOrderController.java +++ b/ts-admin-order-service/src/main/java/adminorder/controller/AdminOrderController.java @@ -1,6 +1,6 @@ package adminorder.controller; -import adminorder.entity.*; +import edu.fudan.common.entity.*; import adminorder.service.AdminOrderService; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -31,25 +31,25 @@ public String home(@RequestHeader HttpHeaders headers) { @CrossOrigin(origins = "*") @GetMapping(path = "/adminorder") public HttpEntity getAllOrders(@RequestHeader HttpHeaders headers) { - logger.info("Get all order"); + logger.info("[getAllOrders][Get all orders][getAllOrders]"); return ok(adminOrderService.getAllOrders(headers)); } @PostMapping(value = "/adminorder") public HttpEntity addOrder(@RequestBody Order request, @RequestHeader HttpHeaders headers) { - logger.info("Add new order, AccountID: {}", request.getAccountId()); + logger.info("[addOrder][Add new order][AccountID: {}]", request.getAccountId()); return ok(adminOrderService.addOrder(request, headers)); } @PutMapping(value = "/adminorder") public HttpEntity updateOrder(@RequestBody Order request, @RequestHeader HttpHeaders headers) { - logger.info("Update order, AccountID: {}, OrderId: {}", request.getAccountId(), request.getId()); + logger.info("[updateOrder][Update order][AccountID: {}, OrderId: {}]", request.getAccountId(), request.getId()); return ok(adminOrderService.updateOrder(request, headers)); } @DeleteMapping(value = "/adminorder/{orderId}/{trainNumber}") public HttpEntity deleteOrder(@PathVariable String orderId, @PathVariable String trainNumber, @RequestHeader HttpHeaders headers) { - logger.info("Delete order, OrderId: {}, TrainNumber: {}", orderId, trainNumber); + logger.info("[deleteOrder][Delete order][OrderId: {}, TrainNumber: {}]", orderId, trainNumber); return ok(adminOrderService.deleteOrder(orderId, trainNumber, headers)); } diff --git a/ts-admin-order-service/src/main/java/adminorder/entity/Order.java b/ts-admin-order-service/src/main/java/adminorder/entity/Order.java deleted file mode 100644 index c6b5e4c71..000000000 --- a/ts-admin-order-service/src/main/java/adminorder/entity/Order.java +++ /dev/null @@ -1,95 +0,0 @@ -package adminorder.entity; - -import lombok.AllArgsConstructor; -import lombok.Data; -import lombok.NoArgsConstructor; -import lombok.ToString; - -import java.util.Date; -import java.util.UUID; - -/** - * @author fdse - */ -@ToString -@Data -@NoArgsConstructor -@AllArgsConstructor -public class Order { - - - private UUID id; - - private Date boughtDate; - - private Date travelDate; - - private Date travelTime; - - /** - * Which Account Bought it - */ - private UUID accountId; - - /** - * Tickets bought for whom - */ - private String contactsName; - - private int documentType; - - private String contactsDocumentNumber; - - private String trainNumber; - - private int coachNumber; - - private int seatClass; - - private String seatNumber; - - private String from; - - private String to; - - private int status; - - private String price; - - - @Override - public boolean equals(Object obj) { - if (this == obj) { - return true; - } - if (obj == null) { - return false; - } - if (getClass() != obj.getClass()) { - return false; - } - Order other = (Order) obj; - return boughtDate.equals(other.getBoughtDate()) - && travelDate.equals(other.getTravelDate()) - && travelTime.equals(other.getTravelTime()) - && accountId.equals(other.getAccountId()) - && contactsName.equals(other.getContactsName()) - && contactsDocumentNumber.equals(other.getContactsDocumentNumber()) - && documentType == other.getDocumentType() - && trainNumber.equals(other.getTrainNumber()) - && coachNumber == other.getCoachNumber() - && seatClass == other.getSeatClass() - && seatNumber.equals(other.getSeatNumber()) - && from.equals(other.getFrom()) - && to.equals(other.getTo()) - && status == other.getStatus() - && price.equals(other.price); - } - - @Override - public int hashCode() { - int result = 17; - result = 31 * result + (id == null ? 0 : id.hashCode()); - return result; - } -} diff --git a/ts-admin-order-service/src/main/java/adminorder/entity/OrderStatus.java b/ts-admin-order-service/src/main/java/adminorder/entity/OrderStatus.java deleted file mode 100644 index d65e1947e..000000000 --- a/ts-admin-order-service/src/main/java/adminorder/entity/OrderStatus.java +++ /dev/null @@ -1,63 +0,0 @@ -package adminorder.entity; - -/** - * @author fdse - */ -public enum OrderStatus { - - /** - * not paid - */ - NOTPAID (0,"Not Paid"), - /** - * paid and not collected - */ - PAID (1,"Paid & Not Collected"), - /** - * collected - */ - COLLECTED (2,"Collected"), - /** - * cancel and rebook - */ - CHANGE (3,"Cancel & Rebook"), - /** - * cancel - */ - CANCEL (4,"Cancel"), - /** - * refunded - */ - REFUNDS (5,"Refunded"), - /** - * used - */ - USED (6,"Used"); - - private int code; - private String name; - - OrderStatus(int code, String name){ - this.code = code; - this.name = name; - } - - public int getCode(){ - return code; - } - - public String getName() { - return name; - } - - public static String getNameByCode(int code){ - OrderStatus[] orderStatusSet = OrderStatus.values(); - for(OrderStatus orderStatus : orderStatusSet){ - if(orderStatus.getCode() == code){ - return orderStatus.getName(); - } - } - return orderStatusSet[0].getName(); - } - -} diff --git a/ts-admin-order-service/src/main/java/adminorder/entity/SeatClass.java b/ts-admin-order-service/src/main/java/adminorder/entity/SeatClass.java deleted file mode 100644 index 25c6c152f..000000000 --- a/ts-admin-order-service/src/main/java/adminorder/entity/SeatClass.java +++ /dev/null @@ -1,70 +0,0 @@ -package adminorder.entity; - -/** - * @author fdse - */ -public enum SeatClass { - - /** - * no seat - */ - NONE (0,"NoSeat"), - /** - * greenseat - */ - BUSINESS (1,"GreenSeat"), - /** - * first class seat - */ - FIRSTCLASS (2,"FirstClassSeat"), - /** - * second class seat - */ - SECONDCLASS (3,"SecondClassSeat"), - /** - * hard seat - */ - HARDSEAT (4,"HardSeat"), - /** - * soft seat - */ - SOFTSEAT (5,"SoftSeat"), - /** - * hard bed - */ - HARDBED (6,"HardBed"), - /** - * soft bed - */ - SOFTBED (7,"SoftBed"), - /** - * high soft seat - */ - HIGHSOFTBED (8,"HighSoftSeat"); - - private int code; - private String name; - - SeatClass(int code, String name){ - this.code = code; - this.name = name; - } - - public int getCode(){ - return code; - } - - public String getName() { - return name; - } - - public static String getNameByCode(int code){ - SeatClass[] seatClassSet = SeatClass.values(); - for(SeatClass seatClass : seatClassSet){ - if(seatClass.getCode() == code){ - return seatClass.getName(); - } - } - return seatClassSet[0].getName(); - } -} diff --git a/ts-admin-order-service/src/main/java/adminorder/service/AdminOrderService.java b/ts-admin-order-service/src/main/java/adminorder/service/AdminOrderService.java index 117e83900..370d84b50 100644 --- a/ts-admin-order-service/src/main/java/adminorder/service/AdminOrderService.java +++ b/ts-admin-order-service/src/main/java/adminorder/service/AdminOrderService.java @@ -1,6 +1,6 @@ package adminorder.service; -import adminorder.entity.*; +import edu.fudan.common.entity.*; import edu.fudan.common.util.Response; import org.springframework.http.HttpHeaders; diff --git a/ts-admin-order-service/src/main/java/adminorder/service/AdminOrderServiceImpl.java b/ts-admin-order-service/src/main/java/adminorder/service/AdminOrderServiceImpl.java index 142f12ec3..f5be363a4 100644 --- a/ts-admin-order-service/src/main/java/adminorder/service/AdminOrderServiceImpl.java +++ b/ts-admin-order-service/src/main/java/adminorder/service/AdminOrderServiceImpl.java @@ -1,10 +1,13 @@ package adminorder.service; -import adminorder.entity.*; +import edu.fudan.common.entity.*; import edu.fudan.common.util.Response; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.cloud.client.ServiceInstance; +import org.springframework.cloud.client.discovery.DiscoveryClient; import org.springframework.core.ParameterizedTypeReference; import org.springframework.http.HttpEntity; import org.springframework.http.HttpHeaders; @@ -14,6 +17,7 @@ import org.springframework.web.client.RestTemplate; import java.util.ArrayList; +import java.util.List; /** * @author fdse @@ -22,18 +26,27 @@ public class AdminOrderServiceImpl implements AdminOrderService { @Autowired private RestTemplate restTemplate; + @Autowired + private DiscoveryClient discoveryClient; + private static final Logger LOGGER = LoggerFactory.getLogger(AdminOrderServiceImpl.class); + private String getServiceUrl(String serviceName) { + return "http://" + serviceName; + } + @Override public Response getAllOrders(HttpHeaders headers) { - AdminOrderServiceImpl.LOGGER.info("[Get All Orders]"); + AdminOrderServiceImpl.LOGGER.info("[getAllOrders][Get All Orders: Generate Reponse Begin]"); //Get all of the orders ArrayList orders = new ArrayList<>(); //From ts-order-service HttpEntity requestEntity = new HttpEntity(null); + + String order_service_url = getServiceUrl("ts-order-service"); ResponseEntity>> re = restTemplate.exchange( - "http://ts-order-service:12031/api/v1/orderservice/order", + order_service_url + "/api/v1/orderservice/order", HttpMethod.GET, requestEntity, new ParameterizedTypeReference>>() { @@ -41,16 +54,17 @@ public Response getAllOrders(HttpHeaders headers) { Response> result = re.getBody(); if (result.getStatus() == 1) { - AdminOrderServiceImpl.LOGGER.info("[Get Orders From ts-order-service successfully!]"); + AdminOrderServiceImpl.LOGGER.info("[getAllOrders][Get Orders From ts-order-service successfully!]"); ArrayList orders1 = result.getData(); orders.addAll(orders1); } else { - AdminOrderServiceImpl.LOGGER.error("[Get Orders From ts-order-service fail!]"); + AdminOrderServiceImpl.LOGGER.error("[getAllOrders][receive response][Get Orders From ts-order-service fail!]"); } //From ts-order-other-service HttpEntity requestEntity2 = new HttpEntity(null); + String order_other_service_url = getServiceUrl("ts-order-other-service"); ResponseEntity>> re2 = restTemplate.exchange( - "http://ts-order-other-service:12032/api/v1/orderOtherService/orderOther", + order_other_service_url + "/api/v1/orderOtherService/orderOther", HttpMethod.GET, requestEntity2, new ParameterizedTypeReference>>() { @@ -58,11 +72,11 @@ public Response getAllOrders(HttpHeaders headers) { result = re2.getBody(); if (result.getStatus() == 1) { - AdminOrderServiceImpl.LOGGER.info("[Get Orders From ts-order-other-service successfully!]"); + AdminOrderServiceImpl.LOGGER.info("[getAllOrders][Get Orders From ts-order-other-service successfully!]"); ArrayList orders1 = (ArrayList) result.getData(); orders.addAll(orders1); } else { - AdminOrderServiceImpl.LOGGER.error("[Get Orders From ts-order-other-service fail!]"); + AdminOrderServiceImpl.LOGGER.error("[getAllOrders][receive response][Get Orders From ts-order-other-service fail!]"); } //Return orders return new Response<>(1, "Get the orders successfully!", orders); @@ -73,20 +87,22 @@ public Response getAllOrders(HttpHeaders headers) { public Response deleteOrder(String orderId, String trainNumber, HttpHeaders headers) { Response deleteOrderResult; if (trainNumber.startsWith("G") || trainNumber.startsWith("D")) { - AdminOrderServiceImpl.LOGGER.info("[Delete Order]"); + AdminOrderServiceImpl.LOGGER.info("[deleteOrder][Delete Order][orderId: {}, trainNumber: {}]", orderId, trainNumber); HttpEntity requestEntity = new HttpEntity(null); + String order_service_url = getServiceUrl("ts-order-service"); ResponseEntity re = restTemplate.exchange( - "http://ts-order-service:12031/api/v1/orderservice/order/" + orderId, + order_service_url + "/api/v1/orderservice/order/" + orderId, HttpMethod.DELETE, requestEntity, Response.class); deleteOrderResult = re.getBody(); } else { - AdminOrderServiceImpl.LOGGER.info("[Delete Order Other]"); + AdminOrderServiceImpl.LOGGER.info("[deleteOrder][Delete Order Other][trainNumber doesn't starts With G or D]"); HttpEntity requestEntity = new HttpEntity(null); + String order_other_service_url = getServiceUrl("ts-order-other-service"); ResponseEntity re = restTemplate.exchange( - "http://ts-order-other-service:12032/api/v1/orderOtherService/orderOther/" + orderId, + order_other_service_url + "/api/v1/orderOtherService/orderOther/" + orderId, HttpMethod.DELETE, requestEntity, Response.class); @@ -101,23 +117,25 @@ public Response deleteOrder(String orderId, String trainNumber, HttpHeaders head public Response updateOrder(Order request, HttpHeaders headers) { Response updateOrderResult; - LOGGER.info("UPDATE ORDER INFO : " + request.toString()); + LOGGER.info("[updateOrder][UPDATE ORDER INFO][request info: {}]", request.toString()); if (request.getTrainNumber().startsWith("G") || request.getTrainNumber().startsWith("D")) { - AdminOrderServiceImpl.LOGGER.info("[Update Order]"); + AdminOrderServiceImpl.LOGGER.info("[updateOrder][Update Order][trainNumber starts With G or D]"); HttpEntity requestEntity = new HttpEntity(request, null); + String order_service_url = getServiceUrl("ts-order-service"); ResponseEntity re = restTemplate.exchange( - "http://ts-order-service:12031/api/v1/orderservice/order/admin", + order_service_url + "/api/v1/orderservice/order/admin", HttpMethod.PUT, requestEntity, Response.class); updateOrderResult = re.getBody(); } else { - AdminOrderServiceImpl.LOGGER.info("[Add New Order Other]"); + AdminOrderServiceImpl.LOGGER.info("[updateOrder][Add New Order Other][trainNumber doesn't starts With G or D]"); HttpEntity requestEntity = new HttpEntity(request, null); + String order_other_service_url = getServiceUrl("ts-order-other-service"); ResponseEntity re = restTemplate.exchange( - "http://ts-order-other-service:12032/api/v1/orderOtherService/orderOther/admin", + order_other_service_url + "/api/v1/orderOtherService/orderOther/admin", HttpMethod.PUT, requestEntity, Response.class); @@ -131,21 +149,24 @@ public Response updateOrder(Order request, HttpHeaders headers) { public Response addOrder(Order request, HttpHeaders headers) { Response addOrderResult; + LOGGER.info("[addOrder][ADD ORDER][request info: {}]", request.toString()); if (request.getTrainNumber().startsWith("G") || request.getTrainNumber().startsWith("D")) { - AdminOrderServiceImpl.LOGGER.info("[Add New Order]"); + AdminOrderServiceImpl.LOGGER.info("[addOrder][Add New Order][trainNumber starts With G or D]"); HttpEntity requestEntity = new HttpEntity(request, null); + String order_service_url = getServiceUrl("ts-order-service"); ResponseEntity re = restTemplate.exchange( - "http://ts-order-service:12031/api/v1/orderservice/order/admin", + order_service_url + "/api/v1/orderservice/order/admin", HttpMethod.POST, requestEntity, Response.class); addOrderResult = re.getBody(); } else { - AdminOrderServiceImpl.LOGGER.info("[Add New Order Other]"); + AdminOrderServiceImpl.LOGGER.info("[addOrder][Add New Order Other][trainNumber doesn't starts With G or D]"); HttpEntity requestEntity = new HttpEntity(request, null); + String order_other_service_url = getServiceUrl("ts-order-other-service"); ResponseEntity re = restTemplate.exchange( - "http://ts-order-other-service:12032/api/v1/orderOtherService/orderOther/admin", + order_other_service_url + "/api/v1/orderOtherService/orderOther/admin", HttpMethod.POST, requestEntity, Response.class); diff --git a/ts-admin-order-service/src/main/resources/application.yml b/ts-admin-order-service/src/main/resources/application.yml index 87f3bc28c..9d485255f 100644 --- a/ts-admin-order-service/src/main/resources/application.yml +++ b/ts-admin-order-service/src/main/resources/application.yml @@ -2,9 +2,15 @@ server: port: 16112 spring: + cloud: + nacos: + discovery: + server-addr: ${NACOS_ADDRS:nacos-0.nacos-headless.default.svc.cluster.local,nacos-1.nacos-headless.default.svc.cluster.local,nacos-2.nacos-headless.default.svc.cluster.local} application: name: ts-admin-order-service swagger: - controllerPackage: adminorder.controller \ No newline at end of file + controllerPackage: adminorder.controller + + diff --git a/ts-admin-order-service/src/test/java/adminorder/controller/AdminOrderControllerTest.java b/ts-admin-order-service/src/test/java/adminorder/controller/AdminOrderControllerTest.java index f74300b13..cc0d4e2df 100644 --- a/ts-admin-order-service/src/test/java/adminorder/controller/AdminOrderControllerTest.java +++ b/ts-admin-order-service/src/test/java/adminorder/controller/AdminOrderControllerTest.java @@ -1,9 +1,9 @@ package adminorder.controller; -import adminorder.entity.Order; import adminorder.service.AdminOrderService; import com.alibaba.fastjson.JSONObject; import edu.fudan.common.util.Response; +import edu.fudan.common.entity.*; import org.junit.Assert; import org.junit.Before; import org.junit.Test; @@ -54,7 +54,7 @@ public void testGetAllOrders() throws Exception { @Test public void testAddOrder() throws Exception { - Order order = new Order(null, null, null, null, null, null, 0, null, "G", 0, 0, null, null, null, 0, null); + Order order = new Order(null, null, null, null, null, null, 0, null, "G", 0, 0, null, null, null, 0, null, null); Mockito.when(adminOrderService.addOrder(Mockito.any(Order.class), Mockito.any(HttpHeaders.class))).thenReturn(response); String requestJson = JSONObject.toJSONString(order); String result = mockMvc.perform(MockMvcRequestBuilders.post("/api/v1/adminorderservice/adminorder").contentType(MediaType.APPLICATION_JSON).content(requestJson)) @@ -65,7 +65,7 @@ public void testAddOrder() throws Exception { @Test public void testUpdateOrder() throws Exception { - Order order = new Order(null, null, null, null, null, null, 0, null, "G", 0, 0, null, null, null, 0, null); + Order order = new Order(null, null, null, null, null, null, 0, null, "G", 0, 0, null, null, null, 0, null, null); Mockito.when(adminOrderService.updateOrder(Mockito.any(Order.class), Mockito.any(HttpHeaders.class))).thenReturn(response); String requestJson = JSONObject.toJSONString(order); String result = mockMvc.perform(MockMvcRequestBuilders.put("/api/v1/adminorderservice/adminorder").contentType(MediaType.APPLICATION_JSON).content(requestJson)) diff --git a/ts-admin-order-service/src/test/java/adminorder/service/AdminOrderServiceImplTest.java b/ts-admin-order-service/src/test/java/adminorder/service/AdminOrderServiceImplTest.java index 98e8dcd06..8bbe4833e 100644 --- a/ts-admin-order-service/src/test/java/adminorder/service/AdminOrderServiceImplTest.java +++ b/ts-admin-order-service/src/test/java/adminorder/service/AdminOrderServiceImplTest.java @@ -1,7 +1,7 @@ package adminorder.service; -import adminorder.entity.Order; import edu.fudan.common.util.Response; +import edu.fudan.common.entity.*; import org.junit.Assert; import org.junit.Before; import org.junit.Test; @@ -104,7 +104,7 @@ public void testDeleteOrder2() { @Test public void testUpdateOrder1() { - Order order = new Order(null, null, null, null, null, null, 0, null, "G", 0, 0, null, null, null, 0, null); + Order order = new Order(null, null, null, null, null, null, 0, null, "G", 0, 0, null, null, null, 0, null, null); HttpEntity requestEntity2 = new HttpEntity<>(order, headers); Response response = new Response(); ResponseEntity re = new ResponseEntity<>(response, HttpStatus.OK); @@ -119,7 +119,7 @@ public void testUpdateOrder1() { @Test public void testUpdateOrder2() { - Order order = new Order(null, null, null, null, null, null, 0, null, "K", 0, 0, null, null, null, 0, null); + Order order = new Order(null, null, null, null, null, null, 0, null, "K", 0, 0, null, null, null, 0, null, null); HttpEntity requestEntity2 = new HttpEntity<>(order, headers); Response response = new Response(); ResponseEntity re = new ResponseEntity<>(response, HttpStatus.OK); @@ -134,7 +134,7 @@ public void testUpdateOrder2() { @Test public void testAddOrder1() { - Order order = new Order(null, null, null, null, null, null, 0, null, "G", 0, 0, null, null, null, 0, null); + Order order = new Order(null, null, null, null, null, null, 0, null, "G", 0, 0, null, null, null, 0, null,null); HttpEntity requestEntity2 = new HttpEntity<>(order, headers); Response response = new Response(); ResponseEntity re = new ResponseEntity<>(response, HttpStatus.OK); @@ -149,7 +149,7 @@ public void testAddOrder1() { @Test public void testAddOrder2() { - Order order = new Order(null, null, null, null, null, null, 0, null, "K", 0, 0, null, null, null, 0, null); + Order order = new Order(null, null, null, null, null, null, 0, null, "K", 0, 0, null, null, null, 0, null, null); HttpEntity requestEntity2 = new HttpEntity<>(order, headers); Response response = new Response(); ResponseEntity re = new ResponseEntity<>(response, HttpStatus.OK); diff --git a/ts-admin-route-service/pom.xml b/ts-admin-route-service/pom.xml index 21450ed6a..c71557fa9 100644 --- a/ts-admin-route-service/pom.xml +++ b/ts-admin-route-service/pom.xml @@ -15,7 +15,7 @@ ts-service org.services 0.1.0 - ../ + ../pom.xml @@ -29,8 +29,6 @@ ts-common 0.1.0 - - diff --git a/ts-admin-route-service/src/main/java/adminroute/AdminRouteApplication.java b/ts-admin-route-service/src/main/java/adminroute/AdminRouteApplication.java index f97ebc4b1..874da0983 100644 --- a/ts-admin-route-service/src/main/java/adminroute/AdminRouteApplication.java +++ b/ts-admin-route-service/src/main/java/adminroute/AdminRouteApplication.java @@ -3,6 +3,8 @@ import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.boot.web.client.RestTemplateBuilder; +import org.springframework.cloud.client.discovery.EnableDiscoveryClient; +import org.springframework.cloud.client.loadbalancer.LoadBalanced; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.EnableAspectJAutoProxy; import org.springframework.integration.annotation.IntegrationComponentScan; @@ -18,11 +20,13 @@ @EnableAsync @IntegrationComponentScan @EnableSwagger2 +@EnableDiscoveryClient public class AdminRouteApplication { public static void main(String[] args) { SpringApplication.run(AdminRouteApplication.class, args); } + @LoadBalanced @Bean public RestTemplate restTemplate(RestTemplateBuilder builder) { return builder.build(); diff --git a/ts-admin-route-service/src/main/java/adminroute/controller/AdminRouteController.java b/ts-admin-route-service/src/main/java/adminroute/controller/AdminRouteController.java index 71d6825cc..7c6b7a73e 100644 --- a/ts-admin-route-service/src/main/java/adminroute/controller/AdminRouteController.java +++ b/ts-admin-route-service/src/main/java/adminroute/controller/AdminRouteController.java @@ -1,6 +1,6 @@ package adminroute.controller; -import adminroute.entity.RouteInfo; +import edu.fudan.common.entity.RouteInfo; import adminroute.service.AdminRouteService; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -31,20 +31,20 @@ public String home(@RequestHeader HttpHeaders headers) { @CrossOrigin(origins = "*") @GetMapping(path = "/adminroute") public HttpEntity getAllRoutes(@RequestHeader HttpHeaders headers) { - logger.info("Get all routes request"); + logger.info("[getAllRoutes][Get all routes request]"); return ok(adminRouteService.getAllRoutes(headers)); } @PostMapping(value = "/adminroute") public HttpEntity addRoute(@RequestBody RouteInfo request, @RequestHeader HttpHeaders headers) { - logger.info("Create and modify route, route id: {}, from station {} to station {}", + logger.info("[addRoute][Create and modify route][route id: {}, from station {} to station {}]", request.getId(), request.getStartStation(), request.getEndStation()); return ok(adminRouteService.createAndModifyRoute(request, headers)); } @DeleteMapping(value = "/adminroute/{routeId}") public HttpEntity deleteRoute(@PathVariable String routeId, @RequestHeader HttpHeaders headers) { - logger.info("Delete route, route id: {}", routeId); + logger.info("[deleteRoute][Delete route][route id: {}]", routeId); return ok(adminRouteService.deleteRoute(routeId, headers)); } diff --git a/ts-admin-route-service/src/main/java/adminroute/entity/Route.java b/ts-admin-route-service/src/main/java/adminroute/entity/Route.java deleted file mode 100644 index 662a3a414..000000000 --- a/ts-admin-route-service/src/main/java/adminroute/entity/Route.java +++ /dev/null @@ -1,25 +0,0 @@ -package adminroute.entity; - -import lombok.Data; -import lombok.NoArgsConstructor; - -import java.util.List; - -/** - * @author fdse - */ -@Data -@NoArgsConstructor -public class Route { - - private String id; - - private List stations; - - private List distances; - - private String startStationId; - - private String terminalStationId; - -} diff --git a/ts-admin-route-service/src/main/java/adminroute/entity/RouteInfo.java b/ts-admin-route-service/src/main/java/adminroute/entity/RouteInfo.java deleted file mode 100644 index e394655e4..000000000 --- a/ts-admin-route-service/src/main/java/adminroute/entity/RouteInfo.java +++ /dev/null @@ -1,24 +0,0 @@ -package adminroute.entity; - -import lombok.Data; -import lombok.NoArgsConstructor; - -/** - * @author fdse - */ -@Data -@NoArgsConstructor -public class RouteInfo { - private String loginId; - - private String startStation; - - private String endStation; - - private String stationList; - - private String distanceList; - - private String id; - -} diff --git a/ts-admin-route-service/src/main/java/adminroute/service/AdminRouteService.java b/ts-admin-route-service/src/main/java/adminroute/service/AdminRouteService.java index c8799f066..14e54c19f 100644 --- a/ts-admin-route-service/src/main/java/adminroute/service/AdminRouteService.java +++ b/ts-admin-route-service/src/main/java/adminroute/service/AdminRouteService.java @@ -1,6 +1,6 @@ package adminroute.service; -import adminroute.entity.RouteInfo; +import edu.fudan.common.entity.RouteInfo; import edu.fudan.common.util.Response; import org.springframework.http.HttpHeaders; diff --git a/ts-admin-route-service/src/main/java/adminroute/service/AdminRouteServiceImpl.java b/ts-admin-route-service/src/main/java/adminroute/service/AdminRouteServiceImpl.java index 3227b4c30..063cfd1e3 100644 --- a/ts-admin-route-service/src/main/java/adminroute/service/AdminRouteServiceImpl.java +++ b/ts-admin-route-service/src/main/java/adminroute/service/AdminRouteServiceImpl.java @@ -1,16 +1,21 @@ package adminroute.service; -import adminroute.entity.Route; -import adminroute.entity.RouteInfo; +import edu.fudan.common.entity.Route; +import edu.fudan.common.entity.RouteInfo; import edu.fudan.common.util.Response; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.cloud.client.discovery.DiscoveryClient; import org.springframework.core.ParameterizedTypeReference; import org.springframework.http.*; import org.springframework.stereotype.Service; import org.springframework.web.client.RestTemplate; +import java.util.ArrayList; +import java.util.List; +import java.util.Map; + /** * @author fdse */ @@ -18,20 +23,27 @@ public class AdminRouteServiceImpl implements AdminRouteService { @Autowired private RestTemplate restTemplate; + @Autowired + private DiscoveryClient discoveryClient; public static final Logger logger = LoggerFactory.getLogger(AdminRouteServiceImpl.class); + private String getServiceUrl(String serviceName) { + return "http://" + serviceName; + } + @Override public Response getAllRoutes(HttpHeaders headers) { HttpEntity requestEntity = new HttpEntity(null); + String route_service_url = getServiceUrl("ts-route-service"); ResponseEntity re = restTemplate.exchange( - "http://ts-route-service:11178/api/v1/routeservice/routes", + route_service_url + "/api/v1/routeservice/routes", HttpMethod.GET, requestEntity, Response.class); if (re.getStatusCode() != HttpStatus.ACCEPTED) { - logger.error("Get routes error, response code: {}", re.getStatusCodeValue()); + logger.error("[getAllRoutes][receive response][Get routes error][response code: {}]", re.getStatusCodeValue()); } return re.getBody(); @@ -39,16 +51,30 @@ public Response getAllRoutes(HttpHeaders headers) { @Override public Response createAndModifyRoute(RouteInfo request, HttpHeaders headers) { + // check stations + String start = request.getStartStation(); + String end = request.getEndStation(); + List stations = request.getStations(); + if(!stations.contains(start) || !stations.contains(end)){ + logger.error("[createAndModifyRoute][check stations][start or end not included in stationList][start: {}, end: {}]", start, end); + return new Response(0, "start or end station not include in stationList.", null); + } + + Response response = checkStationsExists(stations, headers); + if(response.getStatus() ==0) { + return response; + } HttpEntity requestEntity = new HttpEntity(request, null); + String route_service_url = getServiceUrl("ts-route-service"); ResponseEntity> re = restTemplate.exchange( - "http://ts-route-service:11178/api/v1/routeservice/routes", + route_service_url + "/api/v1/routeservice/routes", HttpMethod.POST, requestEntity, new ParameterizedTypeReference>() { }); if (re.getStatusCode() != HttpStatus.ACCEPTED) { - logger.error("Get status error, response code: {}", re.getStatusCodeValue()); + logger.error("[createAndModifyRoute][receive response][Get status error][response code: {}]", re.getStatusCodeValue()); } return re.getBody(); } @@ -57,15 +83,43 @@ public Response createAndModifyRoute(RouteInfo request, HttpHeaders headers) { public Response deleteRoute(String routeId, HttpHeaders headers) { HttpEntity requestEntity = new HttpEntity(null); + String route_service_url = getServiceUrl("ts-route-service"); ResponseEntity re = restTemplate.exchange( - "http://ts-route-service:11178/api/v1/routeservice/routes/" + routeId, + route_service_url + "/api/v1/routeservice/routes/" + routeId, HttpMethod.DELETE, requestEntity, Response.class); if (re.getStatusCode() != HttpStatus.ACCEPTED) { - logger.error("Delete error, response code: {}", re.getStatusCodeValue()); + logger.error("[deleteRoute][response response][Delete error][response code: {}]", re.getStatusCodeValue()); } return re.getBody(); } -} + + public Response checkStationsExists(List stationNames, HttpHeaders headers) { + logger.info("[checkStationsExists][Check Stations Exists][stationNames: {}]", stationNames); + HttpEntity requestEntity = new HttpEntity(stationNames, null); + String station_service_url=getServiceUrl("ts-station-service"); + ResponseEntity re = restTemplate.exchange( + station_service_url + "/api/v1/stationservice/stations/idlist", + HttpMethod.POST, + requestEntity, + Response.class); + Response> r = re.getBody(); + if(r.getStatus() == 0) { + return r; + } + Map stationMap = r.getData(); + List notExists = new ArrayList<>(); + for(Map.Entry s : stationMap.entrySet()){ + if(s.getValue() == null ){ + // station not exist + notExists.add(s.getKey()); + } + } + if(notExists.size() > 0) { + return new Response<>(0, "some station not exists", notExists); + } + return new Response<>(1, "check stations Exist succeed", null); + } +} \ No newline at end of file diff --git a/ts-admin-route-service/src/main/resources/application.yml b/ts-admin-route-service/src/main/resources/application.yml index b57f62231..6774accb4 100644 --- a/ts-admin-route-service/src/main/resources/application.yml +++ b/ts-admin-route-service/src/main/resources/application.yml @@ -2,6 +2,10 @@ server: port: 16113 spring: + cloud: + nacos: + discovery: + server-addr: ${NACOS_ADDRS:nacos-0.nacos-headless.default.svc.cluster.local,nacos-1.nacos-headless.default.svc.cluster.local,nacos-2.nacos-headless.default.svc.cluster.local} application: name: ts-admin-route-service diff --git a/ts-admin-route-service/src/test/java/adminroute/controller/AdminRouteControllerTest.java b/ts-admin-route-service/src/test/java/adminroute/controller/AdminRouteControllerTest.java index 174856729..729363c83 100644 --- a/ts-admin-route-service/src/test/java/adminroute/controller/AdminRouteControllerTest.java +++ b/ts-admin-route-service/src/test/java/adminroute/controller/AdminRouteControllerTest.java @@ -1,6 +1,6 @@ package adminroute.controller; -import adminroute.entity.RouteInfo; +import edu.fudan.common.entity.RouteInfo; import adminroute.service.AdminRouteService; import com.alibaba.fastjson.JSONObject; import edu.fudan.common.util.Response; diff --git a/ts-admin-route-service/src/test/java/adminroute/service/AdminRouteServiceImplTest.java b/ts-admin-route-service/src/test/java/adminroute/service/AdminRouteServiceImplTest.java index 152dcf2e4..ecbe4248d 100644 --- a/ts-admin-route-service/src/test/java/adminroute/service/AdminRouteServiceImplTest.java +++ b/ts-admin-route-service/src/test/java/adminroute/service/AdminRouteServiceImplTest.java @@ -1,7 +1,7 @@ package adminroute.service; -import adminroute.entity.Route; -import adminroute.entity.RouteInfo; +import edu.fudan.common.entity.Route; +import edu.fudan.common.entity.RouteInfo; import edu.fudan.common.util.Response; import org.junit.Assert; import org.junit.Before; diff --git a/ts-admin-travel-service/pom.xml b/ts-admin-travel-service/pom.xml index 33baa0a63..c6e3d8fb6 100644 --- a/ts-admin-travel-service/pom.xml +++ b/ts-admin-travel-service/pom.xml @@ -15,7 +15,7 @@ ts-service org.services 0.1.0 - ../ + ../pom.xml @@ -29,8 +29,6 @@ ts-common 0.1.0 - - diff --git a/ts-admin-travel-service/src/main/java/admintravel/AdminTravelApplication.java b/ts-admin-travel-service/src/main/java/admintravel/AdminTravelApplication.java index d9a43a4e6..0b39f5a93 100644 --- a/ts-admin-travel-service/src/main/java/admintravel/AdminTravelApplication.java +++ b/ts-admin-travel-service/src/main/java/admintravel/AdminTravelApplication.java @@ -3,6 +3,8 @@ import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.boot.web.client.RestTemplateBuilder; +import org.springframework.cloud.client.discovery.EnableDiscoveryClient; +import org.springframework.cloud.client.loadbalancer.LoadBalanced; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.EnableAspectJAutoProxy; import org.springframework.integration.annotation.IntegrationComponentScan; @@ -18,11 +20,13 @@ @EnableAsync @IntegrationComponentScan @EnableSwagger2 +@EnableDiscoveryClient public class AdminTravelApplication { public static void main(String[] args) { SpringApplication.run(AdminTravelApplication.class, args); } + @LoadBalanced @Bean public RestTemplate restTemplate(RestTemplateBuilder builder) { return builder.build(); diff --git a/ts-admin-travel-service/src/main/java/admintravel/controller/AdminTravelController.java b/ts-admin-travel-service/src/main/java/admintravel/controller/AdminTravelController.java index b25ebb4dd..c7faff6cd 100644 --- a/ts-admin-travel-service/src/main/java/admintravel/controller/AdminTravelController.java +++ b/ts-admin-travel-service/src/main/java/admintravel/controller/AdminTravelController.java @@ -1,7 +1,7 @@ package admintravel.controller; -import admintravel.entity.TravelInfo; import admintravel.service.AdminTravelService; +import edu.fudan.common.entity.TravelInfo; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; @@ -30,27 +30,27 @@ public String home(@RequestHeader HttpHeaders headers) { @CrossOrigin(origins = "*") @GetMapping(path = "/admintravel") public HttpEntity getAllTravels(@RequestHeader HttpHeaders headers) { - logger.info("Get all travels"); + logger.info("[getAllTravels][Get all travels]"); return ok(adminTravelService.getAllTravels(headers)); } @PostMapping(value = "/admintravel") public HttpEntity addTravel(@RequestBody TravelInfo request, @RequestHeader HttpHeaders headers) { - logger.info("Add travel, trip id: {}, train type id: {}, form station {} to station {}, login id: {}", - request.getTripId(), request.getTrainTypeId(), request.getStartingStationId(), request.getStationsId(), request.getLoginId()); + logger.info("[addTravel][Add travel][trip id: {}, train type name: {}, form station {} to station {}, login id: {}]", + request.getTripId(), request.getTrainTypeName(), request.getStartStationName(), request.getStationsName(), request.getLoginId()); return ok(adminTravelService.addTravel(request, headers)); } @PutMapping(value = "/admintravel") public HttpEntity updateTravel(@RequestBody TravelInfo request, @RequestHeader HttpHeaders headers) { - logger.info("Update travel, trip id: {}, train type id: {}, form station {} to station {}, login id: {}", - request.getTripId(), request.getTrainTypeId(), request.getStartingStationId(), request.getStationsId(), request.getLoginId()); + logger.info("[updateTravel][Update travel][trip id: {}, train type id: {}, form station {} to station {}, login id: {}]", + request.getTripId(), request.getTrainTypeName(), request.getStartStationName(), request.getStationsName(), request.getLoginId()); return ok(adminTravelService.updateTravel(request, headers)); } @DeleteMapping(value = "/admintravel/{tripId}") public HttpEntity deleteTravel(@PathVariable String tripId, @RequestHeader HttpHeaders headers) { - logger.info("Delete travel: trip id: {}", tripId); + logger.info("[deleteTravel][Delete travel][trip id: {}]", tripId); return ok(adminTravelService.deleteTravel(tripId, headers)); } diff --git a/ts-admin-travel-service/src/main/java/admintravel/entity/Route.java b/ts-admin-travel-service/src/main/java/admintravel/entity/Route.java deleted file mode 100644 index 8389ef4e9..000000000 --- a/ts-admin-travel-service/src/main/java/admintravel/entity/Route.java +++ /dev/null @@ -1,26 +0,0 @@ -package admintravel.entity; - - -import lombok.Data; -import lombok.NoArgsConstructor; - -import java.util.List; - -/** - * @author fdse - */ -@Data -@NoArgsConstructor -public class Route { - - private String id; - - private List stations; - - private List distances; - - private String startStationId; - - private String terminalStationId; - -} diff --git a/ts-admin-travel-service/src/main/java/admintravel/entity/TrainType.java b/ts-admin-travel-service/src/main/java/admintravel/entity/TrainType.java deleted file mode 100644 index 49dcef0e4..000000000 --- a/ts-admin-travel-service/src/main/java/admintravel/entity/TrainType.java +++ /dev/null @@ -1,36 +0,0 @@ -package admintravel.entity; - -import lombok.Data; - -/** - * @author fdse - */ -@Data -public class TrainType { - - private String id; - - private int economyClass; - - private int confortClass; - - private int averageSpeed; - - public TrainType(){ - //Default Constructor - } - - public TrainType(String id, int economyClass, int confortClass) { - this.id = id; - this.economyClass = economyClass; - this.confortClass = confortClass; - } - - public TrainType(String id, int economyClass, int confortClass, int averageSpeed) { - this.id = id; - this.economyClass = economyClass; - this.confortClass = confortClass; - this.averageSpeed = averageSpeed; - } - -} diff --git a/ts-admin-travel-service/src/main/java/admintravel/entity/TravelInfo.java b/ts-admin-travel-service/src/main/java/admintravel/entity/TravelInfo.java deleted file mode 100644 index c7cdcd69a..000000000 --- a/ts-admin-travel-service/src/main/java/admintravel/entity/TravelInfo.java +++ /dev/null @@ -1,33 +0,0 @@ -package admintravel.entity; - -import java.util.Date; -import lombok.AllArgsConstructor; -import lombok.Data; -import lombok.NoArgsConstructor; - -/** - * @author fdse - */ -@Data -@NoArgsConstructor -@AllArgsConstructor -public class TravelInfo { - private String loginId; - - private String tripId; - - private String trainTypeId; - - private String routeId; - - private String startingStationId; - - private String stationsId; - - private String terminalStationId; - - private Date startingTime; - - private Date endTime; - -} diff --git a/ts-admin-travel-service/src/main/java/admintravel/entity/Trip.java b/ts-admin-travel-service/src/main/java/admintravel/entity/Trip.java deleted file mode 100644 index 01493228c..000000000 --- a/ts-admin-travel-service/src/main/java/admintravel/entity/Trip.java +++ /dev/null @@ -1,49 +0,0 @@ -package admintravel.entity; - -import lombok.Data; - -import java.util.Date; - -/** - * @author fdse - */ -@Data -public class Trip { - - private TripId tripId; - - private String trainTypeId; - - private String routeId; - - private String startingStationId; - - private String stationsId; - - private String terminalStationId; - - private Date startingTime; - - private Date endTime; - - public Trip(TripId tripId, String trainTypeId, String startingStationId, String stationsId, String terminalStationId, Date startingTime, Date endTime) { - this.tripId = tripId; - this.trainTypeId = trainTypeId; - this.startingStationId = startingStationId; - this.stationsId = stationsId; - this.terminalStationId = terminalStationId; - this.startingTime = startingTime; - this.endTime = endTime; - } - - public Trip(TripId tripId, String trainTypeId, String routeId) { - this.tripId = tripId; - this.trainTypeId = trainTypeId; - this.routeId = routeId; - } - - public Trip(){ - //Default Constructor - } - -} diff --git a/ts-admin-travel-service/src/main/java/admintravel/entity/TripId.java b/ts-admin-travel-service/src/main/java/admintravel/entity/TripId.java deleted file mode 100644 index 20e14233e..000000000 --- a/ts-admin-travel-service/src/main/java/admintravel/entity/TripId.java +++ /dev/null @@ -1,42 +0,0 @@ -package admintravel.entity; - -import lombok.Data; - -import java.io.Serializable; - -/** - * @author fdse - */ -@Data -public class TripId implements Serializable{ - private Type type; - private String number; - - public TripId(){ - //Default Constructor - } - - public TripId(String trainNumber){ - char type0 = trainNumber.charAt(0); - switch(type0){ - case 'G': this.type = Type.G; - break; - case 'D': this.type = Type.D; - break; - case 'Z': this.type = Type.Z; - break; - case 'T': this.type = Type.T; - break; - case 'K': this.type = Type.K; - break; - default:break; - } - - this.number = trainNumber.substring(1); - } - - @Override - public String toString(){ - return type.getName() + number; - } -} diff --git a/ts-admin-travel-service/src/main/java/admintravel/entity/Type.java b/ts-admin-travel-service/src/main/java/admintravel/entity/Type.java deleted file mode 100644 index 7599cae19..000000000 --- a/ts-admin-travel-service/src/main/java/admintravel/entity/Type.java +++ /dev/null @@ -1,63 +0,0 @@ -package admintravel.entity; - -import java.io.Serializable; - -/** - * @author fdse - */ -public enum Type implements Serializable{ - - /** - * 1 - */ - G("G", 1), - /** - * 2 - */ - D("D", 2), - /** - * 3 - */ - Z("Z",3), - /** - * 4 - */ - T("T", 4), - /** - * 5 - */ - K("K", 5); - - private String name; - private int index; - - Type(String name, int index) { - this.name = name; - this.index = index; - } - - public static String getName(int index) { - for (Type type : Type.values()) { - if (type.getIndex() == index) { - return type.name; - } - } - return null; - } - - public String getName() { - return name; - } - - void setName(String name) { - this.name = name; - } - - public int getIndex() { - return index; - } - - void setIndex(int index) { - this.index = index; - } -} diff --git a/ts-admin-travel-service/src/main/java/admintravel/service/AdminTravelService.java b/ts-admin-travel-service/src/main/java/admintravel/service/AdminTravelService.java index 4eea37667..ddc3cdcb3 100644 --- a/ts-admin-travel-service/src/main/java/admintravel/service/AdminTravelService.java +++ b/ts-admin-travel-service/src/main/java/admintravel/service/AdminTravelService.java @@ -1,6 +1,6 @@ package admintravel.service; -import admintravel.entity.TravelInfo; +import edu.fudan.common.entity.TravelInfo; import edu.fudan.common.util.Response; import org.springframework.http.HttpHeaders; diff --git a/ts-admin-travel-service/src/main/java/admintravel/service/AdminTravelServiceImpl.java b/ts-admin-travel-service/src/main/java/admintravel/service/AdminTravelServiceImpl.java index e44ee1eb7..ae980dae7 100644 --- a/ts-admin-travel-service/src/main/java/admintravel/service/AdminTravelServiceImpl.java +++ b/ts-admin-travel-service/src/main/java/admintravel/service/AdminTravelServiceImpl.java @@ -1,11 +1,15 @@ package admintravel.service; -import admintravel.entity.AdminTrip; -import admintravel.entity.TravelInfo; +import edu.fudan.common.entity.AdminTrip; +import edu.fudan.common.entity.Route; +import edu.fudan.common.entity.TrainType; +import edu.fudan.common.entity.TravelInfo; +import edu.fudan.common.util.JsonUtils; import edu.fudan.common.util.Response; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.cloud.client.discovery.DiscoveryClient; import org.springframework.core.ParameterizedTypeReference; import org.springframework.http.HttpEntity; import org.springframework.http.HttpHeaders; @@ -15,6 +19,8 @@ import org.springframework.web.client.RestTemplate; import java.util.ArrayList; +import java.util.List; +import java.util.Map; /** * @author fdse @@ -24,17 +30,24 @@ public class AdminTravelServiceImpl implements AdminTravelService { @Autowired private RestTemplate restTemplate; + @Autowired + private DiscoveryClient discoveryClient; private static final Logger LOGGER = LoggerFactory.getLogger(AdminTravelServiceImpl.class); + private String getServiceUrl(String serviceName) { + return "http://" + serviceName; + } + @Override public Response getAllTravels(HttpHeaders headers) { Response> result; ArrayList trips = new ArrayList<>(); - AdminTravelServiceImpl.LOGGER.info("[Get All Travels]"); + AdminTravelServiceImpl.LOGGER.info("[getAllTravels][Get All Travels]"); HttpEntity requestEntity = new HttpEntity(headers); + String travel_service_url = getServiceUrl("ts-travel-service"); ResponseEntity>> re = restTemplate.exchange( - "http://ts-travel-service:12346/api/v1/travelservice/admin_trip", + travel_service_url + "/api/v1/travelservice/admin_trip", HttpMethod.GET, requestEntity, new ParameterizedTypeReference>>() { @@ -43,15 +56,16 @@ public Response getAllTravels(HttpHeaders headers) { if (result.getStatus() == 1) { ArrayList adminTrips = result.getData(); - AdminTravelServiceImpl.LOGGER.info("[Get Travel From ts-travel-service successfully!]"); + AdminTravelServiceImpl.LOGGER.info("[getAllTravels][Get Travel From ts-travel-service successfully!]"); trips.addAll(adminTrips); } else { - AdminTravelServiceImpl.LOGGER.error("[Get Travel From ts-travel-service fail!]"); + AdminTravelServiceImpl.LOGGER.error("[getAllTravels][receive response][Get Travel From ts-travel-service fail!]"); } HttpEntity requestEntity2 = new HttpEntity(headers); + String travel2_service_url = getServiceUrl("ts-travel2-service"); ResponseEntity>> re2 = restTemplate.exchange( - "http://ts-travel2-service:16346/api/v1/travel2service/admin_trip", + travel2_service_url + "/api/v1/travel2service/admin_trip", HttpMethod.GET, requestEntity2, new ParameterizedTypeReference>>() { @@ -59,11 +73,11 @@ public Response getAllTravels(HttpHeaders headers) { result = re2.getBody(); if (result.getStatus() == 1) { - AdminTravelServiceImpl.LOGGER.info("[Get Travel From ts-travel2-service successfully!]"); + AdminTravelServiceImpl.LOGGER.info("[getAllTravels][Get Travel From ts-travel2-service successfully!]"); ArrayList adminTrips = result.getData(); trips.addAll(adminTrips); } else { - AdminTravelServiceImpl.LOGGER.error("[Get Travel From ts-travel2-service fail!]"); + AdminTravelServiceImpl.LOGGER.error("[getAllTravels][receive response][Get Travel From ts-travel2-service fail!]"); } result.setData(trips); @@ -72,12 +86,22 @@ public Response getAllTravels(HttpHeaders headers) { @Override public Response addTravel(TravelInfo request, HttpHeaders headers) { + // check for travel info + Response response = checkTravelInfo(request, headers); + if(response.getStatus() == 0){ + return response; + } + Response result; String requestUrl; - if (request.getTrainTypeId().charAt(0) == 'G' || request.getTrainTypeId().charAt(0) == 'D') { - requestUrl = "http://ts-travel-service:12346/api/v1/travelservice/trips"; + + String travel_service_url = getServiceUrl("ts-travel-service"); + String travel2_service_url = getServiceUrl("ts-travel2-service"); + String tripId = request.getTripId(); + if (tripId.charAt(0) == 'G' || tripId.charAt(0) == 'D'){ + requestUrl = travel_service_url + "/api/v1/travelservice/trips"; } else { - requestUrl = "http://ts-travel2-service:16346/api/v1/travel2service/trips"; + requestUrl = travel2_service_url + "/api/v1/travel2service/trips"; } HttpEntity requestEntity = new HttpEntity(request, headers); ResponseEntity re = restTemplate.exchange( @@ -88,23 +112,31 @@ public Response addTravel(TravelInfo request, HttpHeaders headers) { result = re.getBody(); if (result.getStatus() == 1) { - AdminTravelServiceImpl.LOGGER.info("Admin add new travel"); + AdminTravelServiceImpl.LOGGER.info("[addTravel][Admin add new travel][success]"); return new Response<>(1, "[Admin add new travel]", null); } else { - AdminTravelServiceImpl.LOGGER.error("Admin add new travel failed, trip id: {}", request.getTripId()); + AdminTravelServiceImpl.LOGGER.error("[addTravel][receive response][Admin add new travel failed][trip id: {}]", request.getTripId()); return new Response<>(0, "Admin add new travel failed", null); } } @Override public Response updateTravel(TravelInfo request, HttpHeaders headers) { - Response result; + // check for travel info + Response response = checkTravelInfo(request, headers); + if(response.getStatus() == 0){ + return response; + } + Response result; String requestUrl = ""; - if (request.getTrainTypeId().charAt(0) == 'G' || request.getTrainTypeId().charAt(0) == 'D') { - requestUrl = "http://ts-travel-service:12346/api/v1/travelservice/trips"; + String travel_service_url = getServiceUrl("ts-travel-service"); + String travel2_service_url = getServiceUrl("ts-travel2-service"); + String tripId = request.getTripId(); + if (tripId.charAt(0) == 'G' || tripId.charAt(0) == 'D'){ + requestUrl = travel_service_url + "/api/v1/travelservice/trips"; } else { - requestUrl = "http://ts-travel2-service:16346/api/v1/travel2service/trips"; + requestUrl = travel2_service_url + "/api/v1/travel2service/trips"; } HttpEntity requestEntity = new HttpEntity(request, headers); ResponseEntity re = restTemplate.exchange( @@ -115,11 +147,11 @@ public Response updateTravel(TravelInfo request, HttpHeaders headers) { result = re.getBody(); if (result.getStatus() != 1) { - AdminTravelServiceImpl.LOGGER.info("[Admin update travel failed]"); + AdminTravelServiceImpl.LOGGER.info("[updateTravel][Admin update travel failed]"); return new Response<>(0, "Admin update travel failed", null); } - AdminTravelServiceImpl.LOGGER.info("[Admin update travel success]"); + AdminTravelServiceImpl.LOGGER.info("[updateTravel][Admin update travel][success]"); return result; } @@ -128,10 +160,12 @@ public Response deleteTravel(String tripId, HttpHeaders headers) { Response result; String requestUtl = ""; + String travel_service_url = getServiceUrl("ts-travel-service"); + String travel2_service_url = getServiceUrl("ts-travel2-service"); if (tripId.charAt(0) == 'G' || tripId.charAt(0) == 'D') { - requestUtl = "http://ts-travel-service:12346/api/v1/travelservice/trips/" + tripId; + requestUtl = travel_service_url + "/api/v1/travelservice/trips/" + tripId; } else { - requestUtl = "http://ts-travel2-service:16346/api/v1/travel2service/trips/" + tripId; + requestUtl = travel2_service_url + "/api/v1/travel2service/trips/" + tripId; } HttpEntity requestEntity = new HttpEntity(headers); ResponseEntity re = restTemplate.exchange( @@ -142,11 +176,114 @@ public Response deleteTravel(String tripId, HttpHeaders headers) { result = re.getBody(); if (result.getStatus() != 1) { - AdminTravelServiceImpl.LOGGER.error("Admin delete travel failed, trip id: {}", tripId); + AdminTravelServiceImpl.LOGGER.error("[deleteTravel][receive response][Admin delete travel failed][trip id: {}]", tripId); return new Response<>(0, "Admin delete travel failed", null); } - AdminTravelServiceImpl.LOGGER.info("Admin delete travel success, trip id: {}", tripId); + AdminTravelServiceImpl.LOGGER.info("[deleteTravel][Admin delete travel success][trip id: {}]", tripId); return result; } + + public Response checkTravelInfo(TravelInfo info, HttpHeaders headers) { + String start = info.getStartStationName(); + String end = info.getTerminalStationName(); + List stations = new ArrayList<>(); + stations.add(start); + stations.add(end); + Response response = checkStationsExists(stations, headers); + if(response.getStatus() ==0) { + return response; + } + + TrainType trainType = queryTrainTypeByName(info.getTrainTypeName(), headers); + if (trainType == null) { + AdminTravelServiceImpl.LOGGER.warn( + "[queryForTravel][traintype doesn't exist][trainTypeName: {}]", + info.getTrainTypeName()); + response.setStatus(0); + response.setMsg("Train type doesn't exist"); + return response; + } + String routeId = info.getRouteId(); + Route route = getRouteByRouteId(routeId, headers); + if (route == null) { + response.setStatus(0); + response.setMsg("Route doesn't exist"); + return response; + } + + // Check the route list for this train. Check that the required start and arrival stations are + // in the list of stops that are not on the route, and check that the location of the start + // station is before the stop + if (!route.getStations().contains(start) + || !route.getStations().contains(end) + || (route.getStations().indexOf(start) >= route.getStations().indexOf(end))) { + response.setStatus(0); + response.setMsg("Station not correct in Route"); + return response; + } + response.setStatus(1); + return response; + } + + public Response checkStationsExists(List stationNames, HttpHeaders headers) { + AdminTravelServiceImpl.LOGGER.info("[checkStationsExists][Check Stations Exists][stationNames: {}]", stationNames); + HttpEntity requestEntity = new HttpEntity(stationNames, null); + String station_service_url=getServiceUrl("ts-station-service"); + ResponseEntity re = restTemplate.exchange( + station_service_url + "/api/v1/stationservice/stations/idlist", + HttpMethod.POST, + requestEntity, + Response.class); + Response> r = re.getBody(); + if(r.getStatus() == 0) { + return r; + } + Map stationMap = r.getData(); + List notExists = new ArrayList<>(); + for(Map.Entry s : stationMap.entrySet()){ + if(s.getValue() == null ){ + // station not exist + notExists.add(s.getKey()); + } + } + if(notExists.size() > 0) { + return new Response<>(0, "some station not exists", notExists); + } + return new Response<>(1, "check stations Exist succeed", null); + } + + public TrainType queryTrainTypeByName(String trainTypeName, HttpHeaders headers) { + AdminTravelServiceImpl.LOGGER.info("[queryTrainTypeByName][Query Train Type][Train Type name: {}]", trainTypeName); + HttpEntity requestEntity = new HttpEntity(null); + String train_service_url=getServiceUrl("ts-train-service"); + ResponseEntity re = restTemplate.exchange( + train_service_url + "/api/v1/trainservice/trains/byName/" + trainTypeName, + HttpMethod.GET, + requestEntity, + Response.class); + Response response = re.getBody(); + + return JsonUtils.conveterObject(response.getData(), TrainType.class); + } + + private Route getRouteByRouteId(String routeId, HttpHeaders headers) { + AdminTravelServiceImpl.LOGGER.info("[getRouteByRouteId][Get Route By Id][Route ID:{}]", routeId); + HttpEntity requestEntity = new HttpEntity(null); + String route_service_url=getServiceUrl("ts-route-service"); + ResponseEntity re = restTemplate.exchange( + route_service_url + "/api/v1/routeservice/routes/" + routeId, + HttpMethod.GET, + requestEntity, + Response.class); + Response result = re.getBody(); + if ( result.getStatus() == 0) { + AdminTravelServiceImpl.LOGGER.warn("[getRouteByRouteId][Get Route By Id Failed][Fail msg: {}]", result.getMsg()); + return null; + } else { + AdminTravelServiceImpl.LOGGER.info("[getRouteByRouteId][Get Route By Id][Success]"); + return JsonUtils.conveterObject(result.getData(), Route.class); + } + } + } diff --git a/ts-admin-travel-service/src/main/resources/application.yml b/ts-admin-travel-service/src/main/resources/application.yml index 7cfc96ea7..8f57dbfa1 100644 --- a/ts-admin-travel-service/src/main/resources/application.yml +++ b/ts-admin-travel-service/src/main/resources/application.yml @@ -2,6 +2,10 @@ server: port: 16114 spring: + cloud: + nacos: + discovery: + server-addr: ${NACOS_ADDRS:nacos-0.nacos-headless.default.svc.cluster.local,nacos-1.nacos-headless.default.svc.cluster.local,nacos-2.nacos-headless.default.svc.cluster.local} application: name: ts-admin-travel-service diff --git a/ts-admin-travel-service/src/test/java/admintravel/controller/AdminTravelControllerTest.java b/ts-admin-travel-service/src/test/java/admintravel/controller/AdminTravelControllerTest.java index 7b7ffc353..08f777f1f 100644 --- a/ts-admin-travel-service/src/test/java/admintravel/controller/AdminTravelControllerTest.java +++ b/ts-admin-travel-service/src/test/java/admintravel/controller/AdminTravelControllerTest.java @@ -1,8 +1,8 @@ package admintravel.controller; -import admintravel.entity.TravelInfo; import admintravel.service.AdminTravelService; import com.alibaba.fastjson.JSONObject; +import edu.fudan.common.entity.TravelInfo; import edu.fudan.common.util.Response; import org.junit.Assert; import org.junit.Before; diff --git a/ts-admin-travel-service/src/test/java/admintravel/service/AdminTravelServiceImplTest.java b/ts-admin-travel-service/src/test/java/admintravel/service/AdminTravelServiceImplTest.java index 3557f69ef..29c153801 100644 --- a/ts-admin-travel-service/src/test/java/admintravel/service/AdminTravelServiceImplTest.java +++ b/ts-admin-travel-service/src/test/java/admintravel/service/AdminTravelServiceImplTest.java @@ -1,7 +1,7 @@ package admintravel.service; -import admintravel.entity.AdminTrip; -import admintravel.entity.TravelInfo; +import edu.fudan.common.entity.AdminTrip; +import edu.fudan.common.entity.TravelInfo; import edu.fudan.common.util.Response; import org.junit.Assert; import org.junit.Before; @@ -79,7 +79,8 @@ public void testGetAllTravels2() { @Test public void testAddTravel1() { - TravelInfo request = new TravelInfo(null, null, "G", null, null, null, null, null, null); + TravelInfo request = new TravelInfo(); + request.setTrainTypeName("G"); HttpEntity requestEntity2 = new HttpEntity<>(request, headers); Response response = new Response<>(0, null, null); ResponseEntity re = new ResponseEntity<>(response, HttpStatus.OK); @@ -94,7 +95,8 @@ public void testAddTravel1() { @Test public void testAddTravel2() { - TravelInfo request = new TravelInfo(null, null, "G", null, null, null, null, null, null); + TravelInfo request = new TravelInfo(); + request.setTrainTypeName("G"); HttpEntity requestEntity2 = new HttpEntity<>(request, headers); Response response = new Response<>(1, null, null); ResponseEntity re = new ResponseEntity<>(response, HttpStatus.OK); @@ -109,7 +111,8 @@ public void testAddTravel2() { @Test public void testAddTravel3() { - TravelInfo request = new TravelInfo(null, null, "K", null, null, null, null, null, null); + TravelInfo request = new TravelInfo(); + request.setTrainTypeName("K"); HttpEntity requestEntity2 = new HttpEntity<>(request, headers); Response response = new Response<>(0, null, null); ResponseEntity re = new ResponseEntity<>(response, HttpStatus.OK); @@ -124,7 +127,8 @@ public void testAddTravel3() { @Test public void testAddTravel4() { - TravelInfo request = new TravelInfo(null, null, "K", null, null, null, null, null, null); + TravelInfo request = new TravelInfo(); + request.setTrainTypeName("K"); HttpEntity requestEntity2 = new HttpEntity<>(request, headers); Response response = new Response<>(1, null, null); ResponseEntity re = new ResponseEntity<>(response, HttpStatus.OK); @@ -140,7 +144,8 @@ public void testAddTravel4() { @Test public void testUpdateTravel1() { - TravelInfo request = new TravelInfo(null, null, "G", null, null, null, null, null, null); + TravelInfo request = new TravelInfo(); + request.setTrainTypeName("G"); HttpEntity requestEntity2 = new HttpEntity<>(request, headers); Response response = new Response(1, null, null); ResponseEntity re = new ResponseEntity<>(response, HttpStatus.OK); @@ -155,7 +160,8 @@ public void testUpdateTravel1() { @Test public void testUpdateTravel2() { - TravelInfo request = new TravelInfo(null, null, "K", null, null, null, null, null, null); + TravelInfo request = new TravelInfo(); + request.setTrainTypeName("K"); HttpEntity requestEntity2 = new HttpEntity<>(request, headers); Response response = new Response(1, null, null); ResponseEntity re = new ResponseEntity<>(response, HttpStatus.OK); diff --git a/ts-admin-user-service/pom.xml b/ts-admin-user-service/pom.xml index a2af51de4..de0532c8f 100644 --- a/ts-admin-user-service/pom.xml +++ b/ts-admin-user-service/pom.xml @@ -15,7 +15,7 @@ ts-service org.services 0.1.0 - ../ + ../pom.xml @@ -24,17 +24,14 @@ - org.services ts-common 0.1.0 - - - + diff --git a/ts-admin-user-service/src/main/java/adminuser/AdminUserApplication.java b/ts-admin-user-service/src/main/java/adminuser/AdminUserApplication.java index 559ee167a..d8a1ae478 100644 --- a/ts-admin-user-service/src/main/java/adminuser/AdminUserApplication.java +++ b/ts-admin-user-service/src/main/java/adminuser/AdminUserApplication.java @@ -3,6 +3,8 @@ import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.boot.web.client.RestTemplateBuilder; +import org.springframework.cloud.client.discovery.EnableDiscoveryClient; +import org.springframework.cloud.client.loadbalancer.LoadBalanced; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.EnableAspectJAutoProxy; import org.springframework.integration.annotation.IntegrationComponentScan; @@ -18,11 +20,13 @@ @EnableAsync @IntegrationComponentScan @EnableSwagger2 +@EnableDiscoveryClient public class AdminUserApplication { public static void main(String[] args) { SpringApplication.run(AdminUserApplication.class, args); } + @LoadBalanced @Bean public RestTemplate restTemplate(RestTemplateBuilder builder) { return builder.build(); diff --git a/ts-admin-user-service/src/main/java/adminuser/controller/AdminUserController.java b/ts-admin-user-service/src/main/java/adminuser/controller/AdminUserController.java index 8a5e662ab..86cbc6ed7 100644 --- a/ts-admin-user-service/src/main/java/adminuser/controller/AdminUserController.java +++ b/ts-admin-user-service/src/main/java/adminuser/controller/AdminUserController.java @@ -30,26 +30,26 @@ public String home(@RequestHeader HttpHeaders headers) { @CrossOrigin(origins = "*") @GetMapping public HttpEntity getAllUsers(@RequestHeader HttpHeaders headers) { - logger.info("Get all user"); + logger.info("[getAllUsers][Get all users]"); return ok(adminUserService.getAllUsers(headers)); } @PutMapping public HttpEntity updateUser(@RequestBody UserDto userDto, @RequestHeader HttpHeaders headers) { - logger.info("Update User, userName: {}", userDto.getUserName()); + logger.info("[updateUser][Update User][userName: {}]", userDto.getUserName()); return ok(adminUserService.updateUser(userDto, headers)); } @PostMapping public HttpEntity addUser(@RequestBody UserDto userDto, @RequestHeader HttpHeaders headers) { - logger.info("Add user, userName: {}", userDto.getUserName()); + logger.info("[addUser][Add user][userName: {}]", userDto.getUserName()); return ok(adminUserService.addUser(userDto, headers)); } @DeleteMapping(value = "/{userId}") public HttpEntity deleteUser(@PathVariable String userId, @RequestHeader HttpHeaders headers) { - logger.info("Delete user, userId: {}", userId); + logger.info("[deleteUser][Delete user][userId: {}]", userId); return ok(adminUserService.deleteUser(userId, headers)); } diff --git a/ts-admin-user-service/src/main/java/adminuser/dto/UserDto.java b/ts-admin-user-service/src/main/java/adminuser/dto/UserDto.java index d8061e70f..82500bc91 100644 --- a/ts-admin-user-service/src/main/java/adminuser/dto/UserDto.java +++ b/ts-admin-user-service/src/main/java/adminuser/dto/UserDto.java @@ -11,6 +11,7 @@ @NoArgsConstructor @ToString public class UserDto { + private String accountId; private String userName; diff --git a/ts-admin-user-service/src/main/java/adminuser/entity/DocumentType.java b/ts-admin-user-service/src/main/java/adminuser/entity/DocumentType.java deleted file mode 100644 index 984e1f880..000000000 --- a/ts-admin-user-service/src/main/java/adminuser/entity/DocumentType.java +++ /dev/null @@ -1,50 +0,0 @@ -package adminuser.entity; - -/** - * @author fdse - */ -public enum DocumentType { - - /** - * null - */ - NONE (0,"Null"), - /** - * id card - */ - ID_CARD (1,"ID Card"), - /** - * passport - */ - PASSPORT (2,"Passport"), - /** - * other - */ - OTHER (3,"Other"); - - private int code; - private String name; - - DocumentType(int code, String name){ - this.code = code; - this.name = name; - } - - public int getCode(){ - return code; - } - - public String getName() { - return name; - } - - public static String getNameByCode(int code){ - DocumentType[] documentTypeSet = DocumentType.values(); - for(DocumentType documentType : documentTypeSet){ - if(documentType.getCode() == code){ - return documentType.getName(); - } - } - return documentTypeSet[0].getName(); - } -} diff --git a/ts-admin-user-service/src/main/java/adminuser/entity/Gender.java b/ts-admin-user-service/src/main/java/adminuser/entity/Gender.java deleted file mode 100644 index f5145c945..000000000 --- a/ts-admin-user-service/src/main/java/adminuser/entity/Gender.java +++ /dev/null @@ -1,51 +0,0 @@ -package adminuser.entity; - -/** - * @author fdse - */ -public enum Gender { - - /** - * null - */ - NONE (0, "Null"), - /** - * male - */ - MALE (1, "Male"), - /** - * female - */ - FEMALE (2, "Female"), - /** - * other - */ - OTHER (3, "Other"); - - private int code; - private String name; - - Gender(int code, String name){ - this.code = code; - this.name = name; - } - - public int getCode(){ - return code; - } - - public String getName() { - return name; - } - - public static String getNameByCode(int code){ - Gender[] genderSet = Gender.values(); - for(Gender gender : genderSet){ - if(gender.getCode() == code){ - return gender.getName(); - } - } - return genderSet[0].getName(); - } - -} diff --git a/ts-admin-user-service/src/main/java/adminuser/entity/User.java b/ts-admin-user-service/src/main/java/adminuser/entity/User.java deleted file mode 100644 index 6520979ed..000000000 --- a/ts-admin-user-service/src/main/java/adminuser/entity/User.java +++ /dev/null @@ -1,31 +0,0 @@ -package adminuser.entity; - - -import lombok.AllArgsConstructor; -import lombok.Builder; -import lombok.Data; -import lombok.NoArgsConstructor; - -import java.util.UUID; - -/** - * @author fdse - */ -@Data -@Builder -@AllArgsConstructor -@NoArgsConstructor -public class User { - private UUID userId; - private String userName; - private String password; - - private int gender; - - private int documentType; - - private String documentNum; - - private String email; - -} diff --git a/ts-admin-user-service/src/main/java/adminuser/service/AdminUserServiceImpl.java b/ts-admin-user-service/src/main/java/adminuser/service/AdminUserServiceImpl.java index 4362dfa09..84b056d7d 100644 --- a/ts-admin-user-service/src/main/java/adminuser/service/AdminUserServiceImpl.java +++ b/ts-admin-user-service/src/main/java/adminuser/service/AdminUserServiceImpl.java @@ -1,11 +1,12 @@ package adminuser.service; import adminuser.dto.UserDto; -import adminuser.entity.*; +import edu.fudan.common.entity.User; import edu.fudan.common.util.Response; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.cloud.client.discovery.DiscoveryClient; import org.springframework.core.ParameterizedTypeReference; import org.springframework.http.HttpEntity; import org.springframework.http.HttpHeaders; @@ -24,14 +25,23 @@ public class AdminUserServiceImpl implements AdminUserService { @Autowired private RestTemplate restTemplate; + @Autowired + private DiscoveryClient discoveryClient; private static final Logger LOGGER = LoggerFactory.getLogger(AdminUserServiceImpl.class); - private static final String USER_SERVICE_IP_URI = "http://ts-user-service:12342/api/v1/userservice/users"; +// @Value("${user-service.url}") +// String user_service_url; +// private final String USER_SERVICE_IP_URI = user_service_url + "/api/v1/userservice/users"; + private String getServiceUrl(String serviceName) { + return "http://" + serviceName; + } @Override public Response getAllUsers(HttpHeaders headers) { HttpEntity requestEntity = new HttpEntity(null); + String user_service_url = getServiceUrl("ts-user-service"); + String USER_SERVICE_IP_URI = user_service_url + "/api/v1/userservice/users"; ResponseEntity>> re = restTemplate.exchange( USER_SERVICE_IP_URI, HttpMethod.GET, @@ -39,34 +49,48 @@ public Response getAllUsers(HttpHeaders headers) { new ParameterizedTypeReference>>() { }); if (re.getBody() == null || re.getBody().getStatus() != 1) { - AdminUserServiceImpl.LOGGER.error("Get All Users error"); + AdminUserServiceImpl.LOGGER.error("[getAllUsers][receive response][Get All Users error]"); return new Response<>(0, "get all users error", null); } - AdminUserServiceImpl.LOGGER.info("Get All Users"); + AdminUserServiceImpl.LOGGER.info("[getAllUsers][Get All Users][success]"); return re.getBody(); } @Override public Response deleteUser(String userId, HttpHeaders headers) { - HttpEntity requestEntity = new HttpEntity(null); + HttpHeaders newHeaders = new HttpHeaders(); + String token = headers.getFirst(HttpHeaders.AUTHORIZATION); + newHeaders.set(HttpHeaders.AUTHORIZATION, token); + + HttpEntity requestEntity = new HttpEntity<>(newHeaders); + + String user_service_url = getServiceUrl("ts-user-service"); + String USER_SERVICE_IP_URI = user_service_url + "/api/v1/userservice/users"; ResponseEntity re = restTemplate.exchange( USER_SERVICE_IP_URI + "/" + userId, HttpMethod.DELETE, requestEntity, Response.class); if (re.getBody() == null || re.getBody().getStatus() != 1) { - AdminUserServiceImpl.LOGGER.error("Delete user error, userId: {}", userId); + AdminUserServiceImpl.LOGGER.error("[deleteUser][receive response][Delete user error][userId: {}]", userId); return new Response<>(0, "delete user error", null); } - AdminUserServiceImpl.LOGGER.info("Delete user success, userId: {}", userId); + AdminUserServiceImpl.LOGGER.info("[deleteUser][Delete user success][userId: {}]", userId); return re.getBody(); } @Override public Response updateUser(UserDto userDto, HttpHeaders headers) { LOGGER.info("UPDATE USER: " + userDto.toString()); - HttpEntity requestEntity = new HttpEntity(userDto, null); + + HttpHeaders newHeaders = new HttpHeaders(); + String token = headers.getFirst(HttpHeaders.AUTHORIZATION); + newHeaders.set(HttpHeaders.AUTHORIZATION, token); + + HttpEntity requestEntity = new HttpEntity(userDto, newHeaders); + String user_service_url = getServiceUrl("ts-user-service"); + String USER_SERVICE_IP_URI = user_service_url + "/api/v1/userservice/users"; ResponseEntity re = restTemplate.exchange( USER_SERVICE_IP_URI, HttpMethod.PUT, @@ -75,17 +99,19 @@ public Response updateUser(UserDto userDto, HttpHeaders headers) { String userName = userDto.getUserName(); if (re.getBody() == null || re.getBody().getStatus() != 1) { - AdminUserServiceImpl.LOGGER.error("Update user error, userName: {}", userName); + AdminUserServiceImpl.LOGGER.error("[updateUser][receive response][Update user error][userName: {}]", userName); return new Response<>(0, "Update user error", null); } - AdminUserServiceImpl.LOGGER.info("Update user success, userName: {}", userName); + AdminUserServiceImpl.LOGGER.info("[updateUser][Update user success][userName: {}]", userName); return re.getBody(); } @Override public Response addUser(UserDto userDto, HttpHeaders headers) { - LOGGER.info("ADD USER INFO : "+userDto.toString()); + LOGGER.info("[addUser][ADD USER INFO][UserDto: {}]", userDto.toString()); HttpEntity requestEntity = new HttpEntity(userDto, null); + String user_service_url = getServiceUrl("ts-user-service"); + String USER_SERVICE_IP_URI = user_service_url + "/api/v1/userservice/users"; ResponseEntity> re = restTemplate.exchange( USER_SERVICE_IP_URI + "/register", HttpMethod.POST, @@ -95,10 +121,10 @@ public Response addUser(UserDto userDto, HttpHeaders headers) { String userName = userDto.getUserName(); if (re.getBody() == null || re.getBody().getStatus() != 1) { - AdminUserServiceImpl.LOGGER.error("Add user error, userName: {}", userName); + AdminUserServiceImpl.LOGGER.error("[addUser][receive response][Add user error][userName: {}]", userName); return new Response<>(0, "Add user error", null); } - AdminUserServiceImpl.LOGGER.info("Add user success, userName: {}", userName); + AdminUserServiceImpl.LOGGER.info("[addUser][Add user success][userName: {}]", userName); return re.getBody(); } } diff --git a/ts-admin-user-service/src/main/resources/application.yml b/ts-admin-user-service/src/main/resources/application.yml index 213d693c1..2435e538e 100644 --- a/ts-admin-user-service/src/main/resources/application.yml +++ b/ts-admin-user-service/src/main/resources/application.yml @@ -2,6 +2,10 @@ server: port: 16115 spring: + cloud: + nacos: + discovery: + server-addr: ${NACOS_ADDRS:nacos-0.nacos-headless.default.svc.cluster.local,nacos-1.nacos-headless.default.svc.cluster.local,nacos-2.nacos-headless.default.svc.cluster.local} application: name: ts-admin-user-service diff --git a/ts-admin-user-service/src/test/java/adminuser/service/AdminUserServiceImplTest.java b/ts-admin-user-service/src/test/java/adminuser/service/AdminUserServiceImplTest.java index 3d0da90d5..d968055eb 100644 --- a/ts-admin-user-service/src/test/java/adminuser/service/AdminUserServiceImplTest.java +++ b/ts-admin-user-service/src/test/java/adminuser/service/AdminUserServiceImplTest.java @@ -1,7 +1,7 @@ package adminuser.service; import adminuser.dto.UserDto; -import adminuser.entity.User; +import edu.fudan.common.entity.User; import edu.fudan.common.util.Response; import org.junit.Assert; import org.junit.Before; diff --git a/ts-assurance-service/pom.xml b/ts-assurance-service/pom.xml index 717b1434f..3e298f52e 100644 --- a/ts-assurance-service/pom.xml +++ b/ts-assurance-service/pom.xml @@ -15,7 +15,7 @@ org.services ts-service 0.1.0 - ../ + ../pom.xml @@ -26,17 +26,24 @@ org.springframework.boot - spring-boot-starter-data-mongodb + spring-boot-starter-data-jpa + + + mysql + mysql-connector-java + runtime org.services ts-common 0.1.0 - - + + jakarta.validation + jakarta.validation-api + 2.0.2 + - diff --git a/ts-assurance-service/src/main/java/assurance/AssuranceApplication.java b/ts-assurance-service/src/main/java/assurance/AssuranceApplication.java index efa71cf29..700e1d5a0 100644 --- a/ts-assurance-service/src/main/java/assurance/AssuranceApplication.java +++ b/ts-assurance-service/src/main/java/assurance/AssuranceApplication.java @@ -3,6 +3,8 @@ import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.boot.web.client.RestTemplateBuilder; +import org.springframework.cloud.client.discovery.EnableDiscoveryClient; +import org.springframework.cloud.client.loadbalancer.LoadBalanced; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.EnableAspectJAutoProxy; import org.springframework.integration.annotation.IntegrationComponentScan; @@ -18,12 +20,14 @@ @EnableAsync @IntegrationComponentScan @EnableSwagger2 +@EnableDiscoveryClient public class AssuranceApplication { public static void main(String[] args) { SpringApplication.run(AssuranceApplication.class, args); } + @LoadBalanced @Bean public RestTemplate restTemplate(RestTemplateBuilder builder) { return builder.build(); diff --git a/ts-assurance-service/src/main/java/assurance/controller/AssuranceController.java b/ts-assurance-service/src/main/java/assurance/controller/AssuranceController.java index e9497c83d..3c22d090a 100644 --- a/ts-assurance-service/src/main/java/assurance/controller/AssuranceController.java +++ b/ts-assurance-service/src/main/java/assurance/controller/AssuranceController.java @@ -32,28 +32,28 @@ public String home(@RequestHeader HttpHeaders headers) { @CrossOrigin(origins = "*") @GetMapping(path = "/assurances") public HttpEntity getAllAssurances(@RequestHeader HttpHeaders headers) { - AssuranceController.LOGGER.info("Get All Assurances"); + AssuranceController.LOGGER.info("[getAllAssurances][Get All Assurances]"); return ok(assuranceService.getAllAssurances(headers)); } @CrossOrigin(origins = "*") @GetMapping(path = "/assurances/types") public HttpEntity getAllAssuranceType(@RequestHeader HttpHeaders headers) { - AssuranceController.LOGGER.info("Get Assurance Type"); + AssuranceController.LOGGER.info("[getAllAssuranceType][Get Assurance Type]"); return ok(assuranceService.getAllAssuranceTypes(headers)); } @CrossOrigin(origins = "*") @DeleteMapping(path = "/assurances/assuranceid/{assuranceId}") public HttpEntity deleteAssurance(@PathVariable String assuranceId, @RequestHeader HttpHeaders headers) { - AssuranceController.LOGGER.info("Delete Assurance, assuranceId: {}", assuranceId); + AssuranceController.LOGGER.info("[deleteAssurance][Delete Assurance][assuranceId: {}]", assuranceId); return ok(assuranceService.deleteById(UUID.fromString(assuranceId), headers)); } @CrossOrigin(origins = "*") @DeleteMapping(path = "/assurances/orderid/{orderId}") public HttpEntity deleteAssuranceByOrderId(@PathVariable String orderId, @RequestHeader HttpHeaders headers) { - AssuranceController.LOGGER.info("Delete Assurance by orderId: {}", orderId); + AssuranceController.LOGGER.info("[deleteAssuranceByOrderId][Delete Assurance by orderId][orderId: {}]", orderId); return ok(assuranceService.deleteByOrderId(UUID.fromString(orderId), headers)); } @@ -62,7 +62,7 @@ public HttpEntity deleteAssuranceByOrderId(@PathVariable String orderId, @Reques public HttpEntity modifyAssurance(@PathVariable String assuranceId, @PathVariable String orderId, @PathVariable int typeIndex, @RequestHeader HttpHeaders headers) { - AssuranceController.LOGGER.info("Modify Assurance, assuranceId: {}, orderId: {}, typeIndex: {}", + AssuranceController.LOGGER.info("[modifyAssurance][Modify Assurance][assuranceId: {}, orderId: {}, typeIndex: {}]", assuranceId, orderId, typeIndex); return ok(assuranceService.modify(assuranceId, orderId, typeIndex, headers)); } @@ -72,21 +72,21 @@ public HttpEntity modifyAssurance(@PathVariable String assuranceId, @GetMapping(path = "/assurances/{typeIndex}/{orderId}") public HttpEntity createNewAssurance(@PathVariable int typeIndex, @PathVariable String orderId, @RequestHeader HttpHeaders headers) { //Assurance - AssuranceController.LOGGER.info("Create new assurance, typeIndex: {}, orderId: {}", typeIndex, orderId); + AssuranceController.LOGGER.info("[createNewAssurance][Create new assurance][typeIndex: {}, orderId: {}]", typeIndex, orderId); return ok(assuranceService.create(typeIndex, orderId, headers)); } @CrossOrigin(origins = "*") @GetMapping(path = "/assurances/assuranceid/{assuranceId}") public HttpEntity getAssuranceById(@PathVariable String assuranceId, @RequestHeader HttpHeaders headers) { - AssuranceController.LOGGER.info("Find assurance by assuranceId: {}", assuranceId); + AssuranceController.LOGGER.info("[getAssuranceById][Find assurance by assuranceId][assureId: {}]", assuranceId); return ok(assuranceService.findAssuranceById(UUID.fromString(assuranceId), headers)); } @CrossOrigin(origins = "*") @GetMapping(path = "/assurance/orderid/{orderId}") public HttpEntity findAssuranceByOrderId(@PathVariable String orderId, @RequestHeader HttpHeaders headers) { - AssuranceController.LOGGER.info("Find assurance by orderId: {}", orderId); + AssuranceController.LOGGER.info("[findAssuranceByOrderId][Find assurance by orderId][orderId: {}]", orderId); return ok(assuranceService.findAssuranceByOrderId(UUID.fromString(orderId), headers)); } diff --git a/ts-assurance-service/src/main/java/assurance/entity/Assurance.java b/ts-assurance-service/src/main/java/assurance/entity/Assurance.java index 24bef5d7e..532a7f037 100644 --- a/ts-assurance-service/src/main/java/assurance/entity/Assurance.java +++ b/ts-assurance-service/src/main/java/assurance/entity/Assurance.java @@ -2,9 +2,9 @@ import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import lombok.Data; -import org.springframework.data.annotation.Id; -import org.springframework.data.mongodb.core.mapping.Document; +import org.hibernate.annotations.GenericGenerator; +import javax.persistence.*; import javax.validation.constraints.NotNull; import java.util.UUID; @@ -12,29 +12,32 @@ * @author fdse */ @Data -@Document(collection = "assurance") +@Entity @JsonIgnoreProperties(ignoreUnknown = true) public class Assurance { @Id - private UUID id; + @Column(name = "assurance_id") + private String id; //主键 /** * which order the assurance is related to */ @NotNull - private UUID orderId; + private String orderId; //这个保险关联的订单 /** * the type of assurance */ + @Enumerated(EnumType.STRING) + @Column(name = "assurance_type") private AssuranceType type; public Assurance(){ - this.orderId = UUID.randomUUID(); + this.orderId = UUID.randomUUID().toString(); } - public Assurance(UUID id, UUID orderId, AssuranceType type){ + public Assurance(String id, String orderId, AssuranceType type){ this.id = id; this.orderId = orderId; this.type = type; diff --git a/ts-assurance-service/src/main/java/assurance/entity/PlainAssurance.java b/ts-assurance-service/src/main/java/assurance/entity/PlainAssurance.java index ac3377b3a..843dca0a3 100644 --- a/ts-assurance-service/src/main/java/assurance/entity/PlainAssurance.java +++ b/ts-assurance-service/src/main/java/assurance/entity/PlainAssurance.java @@ -14,9 +14,9 @@ @AllArgsConstructor public class PlainAssurance implements Serializable { - private UUID id; + private String id; - private UUID orderId; + private String orderId; private int typeIndex; diff --git a/ts-assurance-service/src/main/java/assurance/init/InitData.java b/ts-assurance-service/src/main/java/assurance/init/InitData.java index f385ec10e..0782f7d29 100644 --- a/ts-assurance-service/src/main/java/assurance/init/InitData.java +++ b/ts-assurance-service/src/main/java/assurance/init/InitData.java @@ -1,15 +1,80 @@ package assurance.init; +import assurance.entity.Assurance; +import assurance.entity.AssuranceType; +import assurance.entity.AssuranceTypeBean; +import assurance.entity.PlainAssurance; +import assurance.repository.AssuranceRepository; +import assurance.service.AssuranceService; +import edu.fudan.common.util.Response; +import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.CommandLineRunner; import org.springframework.stereotype.Component; +import java.util.ArrayList; +import java.util.List; +import java.util.UUID; /** * @author fdse */ @Component public class InitData implements CommandLineRunner { + @Autowired + AssuranceService service; + + @Autowired + AssuranceRepository repository; + @Override public void run(String... args) throws Exception { //do nothing + + /* Assurance assurance1=new Assurance(); + String id="ff8080817b3e4c27017b3e4c3bee0000"; + assurance1.setId(id); + assurance1.setType(AssuranceType.TRAFFIC_ACCIDENT); + repository.save(assurance1); + + Assurance res1=repository.findById(id).get(); + System.out.println("ID: " + id + " orderID: " + res1.getOrderId()); //根据ID查找 , 打印orderID + Assurance res2=repository.findByOrderId(res1.getOrderId()); + System.out.println("ID: " + res2.getId() + " orderID: " + res1.getOrderId()); //根据orderID查找 , 打印ID + + Assurance assurance2=new Assurance(); + String id2="ff8080817b3e4c27017b3e4c3bee1111"; + assurance2.setId(id2); + assurance2.setType(AssuranceType.TRAFFIC_ACCIDENT); + repository.save(assurance2); + + ArrayList res3 = repository.findAll(); //查找所有 + System.out.println("num: " + res3.size()); + + repository.deleteById(res3.get(0).getId()); //用ID删除第一个 + System.out.println("delete successfully"); + repository.removeAssuranceByOrderId(res3.get(1).getOrderId()); //用orderID删除第二个 + System.out.println("delete successfully"); + + //测试service + String id_1 = UUID.randomUUID().toString(); + Response r_1 = service.create(1,id_1,null); //create + Assurance assurance_1 = (Assurance)r_1.getData(); + String id_2 = UUID.randomUUID().toString(); + Response r_2 = service.create(1,id_2,null); + Assurance assurance_2 = (Assurance)r_2.getData(); + + service.findAssuranceById(UUID.fromString(id_1),null); //findAssuranceById + service.findAssuranceByOrderId(UUID.fromString(assurance_2.getOrderId()),null); //findAssuranceByOrderId + Response r_3 = service.getAllAssurances(null); + ArrayList data_1 = (ArrayList)r_3.getData(); + System.out.println(data_1.size()); + Response r_4 = service.getAllAssuranceTypes(null); + List data_2 = (List)r_4.getData(); + System.out.println(data_2.size()); + + service.modify(assurance_2.getId(),assurance_2.getOrderId(),2,null); //modify实际上2不存在日志中error + + service.deleteById(UUID.fromString(assurance_1.getId()),null); //deleteById + service.deleteByOrderId(UUID.fromString(assurance_2.getOrderId()),null); //deleteByOrderId +*/ } } diff --git a/ts-assurance-service/src/main/java/assurance/repository/AssuranceRepository.java b/ts-assurance-service/src/main/java/assurance/repository/AssuranceRepository.java index 89f4488a8..bd8709edf 100644 --- a/ts-assurance-service/src/main/java/assurance/repository/AssuranceRepository.java +++ b/ts-assurance-service/src/main/java/assurance/repository/AssuranceRepository.java @@ -1,17 +1,18 @@ package assurance.repository; import assurance.entity.Assurance; -import org.springframework.data.mongodb.repository.MongoRepository; -import org.springframework.data.mongodb.repository.Query; +import org.springframework.data.repository.CrudRepository; import org.springframework.stereotype.Repository; + +import javax.transaction.Transactional; import java.util.ArrayList; -import java.util.UUID; +import java.util.Optional; /** * @author fdse */ @Repository -public interface AssuranceRepository extends MongoRepository { +public interface AssuranceRepository extends CrudRepository { /** * find by id @@ -19,7 +20,7 @@ public interface AssuranceRepository extends MongoRepository * @param id id * @return Assurance */ - Assurance findById(UUID id); + Optional findById(String id); /** * find by order id @@ -27,8 +28,7 @@ public interface AssuranceRepository extends MongoRepository * @param orderId order id * @return Assurance */ - @Query("{ 'orderId' : ?0 }") - Assurance findByOrderId(UUID orderId); + Assurance findByOrderId(String orderId); /** * delete by id @@ -36,7 +36,8 @@ public interface AssuranceRepository extends MongoRepository * @param id id * @return null */ - void deleteById(UUID id); + @Transactional + void deleteById(String id); /** * remove assurance by order id @@ -44,7 +45,8 @@ public interface AssuranceRepository extends MongoRepository * @param orderId order id * @return null */ - void removeAssuranceByOrderId(UUID orderId); + @Transactional + void removeAssuranceByOrderId(String orderId); /** * find all diff --git a/ts-assurance-service/src/main/java/assurance/service/AssuranceService.java b/ts-assurance-service/src/main/java/assurance/service/AssuranceService.java index f20427826..9884c6e56 100644 --- a/ts-assurance-service/src/main/java/assurance/service/AssuranceService.java +++ b/ts-assurance-service/src/main/java/assurance/service/AssuranceService.java @@ -3,6 +3,7 @@ import edu.fudan.common.util.Response; import org.springframework.http.HttpHeaders; +import javax.transaction.Transactional; import java.util.UUID; /** @@ -45,6 +46,7 @@ public interface AssuranceService { * @param headers headers * @return Response */ + @Transactional Response deleteById(UUID assuranceId, HttpHeaders headers); /** @@ -54,6 +56,7 @@ public interface AssuranceService { * @param headers headers * @return Response */ + @Transactional Response deleteByOrderId(UUID orderId, HttpHeaders headers); /** diff --git a/ts-assurance-service/src/main/java/assurance/service/AssuranceServiceImpl.java b/ts-assurance-service/src/main/java/assurance/service/AssuranceServiceImpl.java index af0e509c7..c127aa6f0 100644 --- a/ts-assurance-service/src/main/java/assurance/service/AssuranceServiceImpl.java +++ b/ts-assurance-service/src/main/java/assurance/service/AssuranceServiceImpl.java @@ -11,6 +11,7 @@ import java.util.ArrayList; import java.util.List; +import java.util.Optional; import java.util.UUID; /** @@ -26,68 +27,68 @@ public class AssuranceServiceImpl implements AssuranceService { @Override public Response findAssuranceById(UUID id, HttpHeaders headers) { - Assurance assurance = assuranceRepository.findById(id); + Optional assurance = assuranceRepository.findById(id.toString()); if (assurance == null) { - AssuranceServiceImpl.LOGGER.warn("No content, id: {}", id); + AssuranceServiceImpl.LOGGER.warn("[findAssuranceById][find assurance][No content][assurance id: {}]", id); return new Response<>(0, "No Content by this id", null); } else { - AssuranceServiceImpl.LOGGER.info("Find Assurance, id: {}", id); + AssuranceServiceImpl.LOGGER.info("[findAssuranceById][Find Assurance][assurance id: {}]", id); return new Response<>(1, "Find Assurance Success", assurance); } } @Override public Response findAssuranceByOrderId(UUID orderId, HttpHeaders headers) { - Assurance assurance = assuranceRepository.findByOrderId(orderId); + Assurance assurance = assuranceRepository.findByOrderId(orderId.toString()); if (assurance == null) { - AssuranceServiceImpl.LOGGER.warn("No content, orderId: {}", orderId); + AssuranceServiceImpl.LOGGER.warn("[findAssuranceByOrderId][find assurance][No content][orderId: {}]", orderId); return new Response<>(0, "No Content by this orderId", null); } else { - AssuranceServiceImpl.LOGGER.info("Find assurance, orderId: {}", orderId); + AssuranceServiceImpl.LOGGER.info("[findAssuranceByOrderId][find assurance success][orderId: {}]", orderId); return new Response<>(1, "Find Assurance Success", assurance); } } @Override public Response create(int typeIndex, String orderId, HttpHeaders headers) { - Assurance a = assuranceRepository.findByOrderId(UUID.fromString(orderId)); + Assurance a = assuranceRepository.findByOrderId(orderId); AssuranceType at = AssuranceType.getTypeByIndex(typeIndex); if (a != null) { - AssuranceServiceImpl.LOGGER.error("[AddAssurance] Fail.Assurance already exists, typeIndex: {}, orderId: {}", typeIndex, orderId); + AssuranceServiceImpl.LOGGER.error("[create][AddAssurance Fail][Assurance already exists][typeIndex: {}, orderId: {}]", typeIndex, orderId); return new Response<>(0, "Fail.Assurance already exists", null); } else if (at == null) { - AssuranceServiceImpl.LOGGER.warn("[AddAssurance] Fail.Assurance type doesn't exist, typeIndex: {}, orderId: {}", typeIndex, orderId); + AssuranceServiceImpl.LOGGER.warn("[create][AddAssurance Fail][Assurance type doesn't exist][typeIndex: {}, orderId: {}]", typeIndex, orderId); return new Response<>(0, "Fail.Assurance type doesn't exist", null); } else { - Assurance assurance = new Assurance(UUID.randomUUID(), UUID.fromString(orderId), at); + Assurance assurance = new Assurance(UUID.randomUUID().toString(), UUID.fromString(orderId).toString(), at); assuranceRepository.save(assurance); - AssuranceServiceImpl.LOGGER.info("[AddAssurance] Success."); + AssuranceServiceImpl.LOGGER.info("[create][AddAssurance][Success]"); return new Response<>(1, "Success", assurance); } } @Override public Response deleteById(UUID assuranceId, HttpHeaders headers) { - assuranceRepository.deleteById(assuranceId); - Assurance a = assuranceRepository.findById(assuranceId); + assuranceRepository.deleteById(assuranceId.toString()); + Optional a = assuranceRepository.findById(assuranceId.toString()); if (a == null) { - AssuranceServiceImpl.LOGGER.info("[DeleteAssurance] Success, assuranceId: {}", assuranceId); + AssuranceServiceImpl.LOGGER.info("[deleteById][DeleteAssurance success][assuranceId: {}]", assuranceId); return new Response<>(1, "Delete Success with Assurance id", null); } else { - AssuranceServiceImpl.LOGGER.error("[DeleteAssurance] Fail.Assurance not clear, assuranceId: {}", assuranceId); + AssuranceServiceImpl.LOGGER.error("[deleteById][DeleteAssurance Fail][Assurance not clear][assuranceId: {}]", assuranceId); return new Response<>(0, "Fail.Assurance not clear", assuranceId); } } @Override public Response deleteByOrderId(UUID orderId, HttpHeaders headers) { - assuranceRepository.removeAssuranceByOrderId(orderId); - Assurance isExistAssurace = assuranceRepository.findByOrderId(orderId); + assuranceRepository.removeAssuranceByOrderId(orderId.toString()); + Assurance isExistAssurace = assuranceRepository.findByOrderId(orderId.toString()); if (isExistAssurace == null) { - AssuranceServiceImpl.LOGGER.info("[DeleteAssurance] Success, orderId: {}", orderId); + AssuranceServiceImpl.LOGGER.info("[deleteByOrderId][DeleteAssurance Success][orderId: {}]", orderId); return new Response<>(1, "Delete Success with Order Id", null); } else { - AssuranceServiceImpl.LOGGER.error("[DeleteAssurance] Fail.Assurance not clear, orderId: {}", orderId); + AssuranceServiceImpl.LOGGER.error("[deleteByOrderId][DeleteAssurance Fail][Assurance not clear][orderId: {}]", orderId); return new Response<>(0, "Fail.Assurance not clear", orderId); } } @@ -95,19 +96,19 @@ public Response deleteByOrderId(UUID orderId, HttpHeaders headers) { @Override public Response modify(String assuranceId, String orderId, int typeIndex, HttpHeaders headers) { Response oldAssuranceResponse = findAssuranceById(UUID.fromString(assuranceId), headers); - Assurance oldAssurance = (Assurance) oldAssuranceResponse.getData(); + Assurance oldAssurance = ((Optional)oldAssuranceResponse.getData()).get(); if (oldAssurance == null) { - AssuranceServiceImpl.LOGGER.error("[ModifyAssurance] Fail.Assurance not found, assuranceId: {}, orderId: {}, typeIndex: {}", assuranceId, orderId, typeIndex); + AssuranceServiceImpl.LOGGER.error("[modify][ModifyAssurance Fail][Assurance not found][assuranceId: {}, orderId: {}, typeIndex: {}]", assuranceId, orderId, typeIndex); return new Response<>(0, "Fail.Assurance not found.", null); } else { AssuranceType at = AssuranceType.getTypeByIndex(typeIndex); if (at != null) { oldAssurance.setType(at); assuranceRepository.save(oldAssurance); - AssuranceServiceImpl.LOGGER.info("[ModifyAssurance] Success, assuranceId: {}, orderId: {}, typeIndex: {}", assuranceId, orderId, typeIndex); + AssuranceServiceImpl.LOGGER.info("[modify][ModifyAssurance Success][assuranceId: {}, orderId: {}, typeIndex: {}]", assuranceId, orderId, typeIndex); return new Response<>(1, "Modify Success", oldAssurance); } else { - AssuranceServiceImpl.LOGGER.error("[ModifyAssurance] Fail.Assurance Type not exist, assuranceId: {}, orderId: {}, typeIndex: {}", assuranceId, orderId, typeIndex); + AssuranceServiceImpl.LOGGER.error("[modify][ModifyAssurance Fail][Assurance Type not exist][assuranceId: {}, orderId: {}, typeIndex: {}]", assuranceId, orderId, typeIndex); return new Response<>(0, "Assurance Type not exist", null); } } @@ -127,10 +128,10 @@ public Response getAllAssurances(HttpHeaders headers) { pa.setTypePrice(a.getType().getPrice()); result.add(pa); } - AssuranceServiceImpl.LOGGER.info("find all assurance success, list size: {}", as.size()); + AssuranceServiceImpl.LOGGER.info("[getAllAssurances][find all assurance success][list size: {}]", as.size()); return new Response<>(1, "Success", result); } else { - AssuranceServiceImpl.LOGGER.warn("find all assurance: No content"); + AssuranceServiceImpl.LOGGER.warn("[getAllAssurances][find all assurance][No content]"); return new Response<>(0, "No Content, Assurance is empty", null); } } @@ -147,10 +148,10 @@ public Response getAllAssuranceTypes(HttpHeaders headers) { atlist.add(atb); } if (!atlist.isEmpty()) { - AssuranceServiceImpl.LOGGER.info("find all assurance type success, list size: {}", atlist.size()); + AssuranceServiceImpl.LOGGER.info("[getAllAssuranceTypes][find all assurance type success][list size: {}]", atlist.size()); return new Response<>(1, "Find All Assurance", atlist); } else { - AssuranceServiceImpl.LOGGER.warn("find all assurance type: No content"); + AssuranceServiceImpl.LOGGER.warn("[getAllAssuranceTypes][find all assurance type][No content]"); return new Response<>(0, "Assurance is Empty", null); } } diff --git a/ts-assurance-service/src/main/resources/application.yml b/ts-assurance-service/src/main/resources/application.yml index e71824562..ff9158e4a 100644 --- a/ts-assurance-service/src/main/resources/application.yml +++ b/ts-assurance-service/src/main/resources/application.yml @@ -1,16 +1,24 @@ -server: - port: 18888 - spring: + cloud: + nacos: + discovery: + server-addr: ${NACOS_ADDRS:nacos-0.nacos-headless.default.svc.cluster.local,nacos-1.nacos-headless.default.svc.cluster.local,nacos-2.nacos-headless.default.svc.cluster.local} application: name: ts-assurance-service - data: - mongodb: - host: ts-assurance-mongo -# username: user -# password: ${MONGODB_PASSWORD} - database: ts - port: 27017 + datasource: + url: jdbc:mysql://${ASSURANCE_MYSQL_HOST:ts-assurance-mysql}:${ASSURANCE_MYSQL_PORT:3306}/${ASSURANCE_MYSQL_DATABASE:ts-assurance-mysql}?useUnicode=true&characterEncoding=UTF-8&useSSL=false&serverTimezone=UTC + username: ${ASSURANCE_MYSQL_USER:root} + password: ${ASSURANCE_MYSQL_PASSWORD:root} + driver-class-name: com.mysql.cj.jdbc.Driver + jpa: + hibernate: + ddl-auto: update + properties: + hibernate: + dialect: org.hibernate.dialect.MySQL5Dialect + +server: + port: 18888 swagger: controllerPackage: assurance.controller \ No newline at end of file diff --git a/ts-assurance-service/src/test/java/assurance/service/AssuranceServiceImplTest.java b/ts-assurance-service/src/test/java/assurance/service/AssuranceServiceImplTest.java index 125e8de6b..436c8a37d 100644 --- a/ts-assurance-service/src/test/java/assurance/service/AssuranceServiceImplTest.java +++ b/ts-assurance-service/src/test/java/assurance/service/AssuranceServiceImplTest.java @@ -40,7 +40,7 @@ public void setUp() { @Test public void testFindAssuranceById1() { UUID id = UUID.randomUUID(); - Mockito.when(assuranceRepository.findById(id)).thenReturn(null); + Mockito.when(assuranceRepository.findById(id.toString())).thenReturn(null); Response result = assuranceServiceImpl.findAssuranceById(id, headers); Assert.assertEquals(new Response<>(0, "No Content by this id", null), result); } @@ -48,16 +48,16 @@ public void testFindAssuranceById1() { @Test public void testFindAssuranceById2() { UUID id = UUID.randomUUID(); - Assurance assurance = new Assurance(id, null, null); - Mockito.when(assuranceRepository.findById(id)).thenReturn(assurance); + Assurance assurance = new Assurance(id.toString(), null, null); + Mockito.when(assuranceRepository.findById(id.toString())).thenReturn(java.util.Optional.of(assurance)); Response result = assuranceServiceImpl.findAssuranceById(id, headers); - Assert.assertEquals(new Response<>(1, "Find Assurance Success", assurance), result); + Assert.assertEquals(new Response<>(1, "Find Assurance Success", java.util.Optional.of(assurance)), result); } @Test public void testFindAssuranceByOrderId1() { UUID orderId = UUID.randomUUID(); - Mockito.when(assuranceRepository.findByOrderId(orderId)).thenReturn(null); + Mockito.when(assuranceRepository.findByOrderId(orderId.toString())).thenReturn(null); Response result = assuranceServiceImpl.findAssuranceByOrderId(orderId, headers); Assert.assertEquals(new Response<>(0, "No Content by this orderId", null), result); } @@ -65,8 +65,8 @@ public void testFindAssuranceByOrderId1() { @Test public void testFindAssuranceByOrderId2() { UUID orderId = UUID.randomUUID(); - Assurance assurance = new Assurance(null, orderId, null); - Mockito.when(assuranceRepository.findByOrderId(orderId)).thenReturn(assurance); + Assurance assurance = new Assurance(null, orderId.toString(), null); + Mockito.when(assuranceRepository.findByOrderId(orderId.toString())).thenReturn(assurance); Response result = assuranceServiceImpl.findAssuranceByOrderId(orderId, headers); Assert.assertEquals(new Response<>(1, "Find Assurance Success", assurance), result); } @@ -75,7 +75,7 @@ public void testFindAssuranceByOrderId2() { public void testCreate1() { UUID orderId = UUID.randomUUID(); Assurance assurance = new Assurance(); - Mockito.when(assuranceRepository.findByOrderId(orderId)).thenReturn(assurance); + Mockito.when(assuranceRepository.findByOrderId(orderId.toString())).thenReturn(assurance); Response result = assuranceServiceImpl.create(0, orderId.toString(), headers); Assert.assertEquals(new Response<>(0, "Fail.Assurance already exists", null), result); } @@ -83,7 +83,7 @@ public void testCreate1() { @Test public void tesCreate2() { UUID orderId = UUID.randomUUID(); - Mockito.when(assuranceRepository.findByOrderId(orderId)).thenReturn(null); + Mockito.when(assuranceRepository.findByOrderId(orderId.toString())).thenReturn(null); Response result = assuranceServiceImpl.create(0, orderId.toString(), headers); Assert.assertEquals(new Response<>(0, "Fail.Assurance type doesn't exist", null), result); } @@ -91,8 +91,8 @@ public void tesCreate2() { @Test public void testCreate3() { UUID orderId = UUID.randomUUID(); - Mockito.when(assuranceRepository.findByOrderId(orderId)).thenReturn(null); - Mockito.when(assuranceRepository.save(Mockito.anyCollection())).thenReturn(null); + Mockito.when(assuranceRepository.findByOrderId(orderId.toString())).thenReturn(null); + Mockito.when(assuranceRepository.save(Mockito.any(Assurance.class))).thenReturn(null); Response result = assuranceServiceImpl.create(1, orderId.toString(), headers); Assert.assertNotNull(result); } @@ -100,8 +100,8 @@ public void testCreate3() { @Test public void testDeleteById1() { UUID assuranceId = UUID.randomUUID(); - Mockito.doNothing().doThrow(new RuntimeException()).when(assuranceRepository).deleteById(assuranceId); - Mockito.when(assuranceRepository.findById(assuranceId)).thenReturn(null); + Mockito.doNothing().doThrow(new RuntimeException()).when(assuranceRepository).deleteById(assuranceId.toString()); + Mockito.when(assuranceRepository.findById(assuranceId.toString())).thenReturn(null); Response result = assuranceServiceImpl.deleteById(assuranceId, headers); Assert.assertEquals(new Response<>(1, "Delete Success with Assurance id", null), result); } @@ -109,9 +109,9 @@ public void testDeleteById1() { @Test public void testDeleteById2() { UUID assuranceId = UUID.randomUUID(); - Mockito.doNothing().doThrow(new RuntimeException()).when(assuranceRepository).deleteById(assuranceId); + Mockito.doNothing().doThrow(new RuntimeException()).when(assuranceRepository).deleteById(assuranceId.toString()); Assurance assurance = new Assurance(); - Mockito.when(assuranceRepository.findById(assuranceId)).thenReturn(assurance); + Mockito.when(assuranceRepository.findById(assuranceId.toString())).thenReturn(java.util.Optional.of(assurance)); Response result = assuranceServiceImpl.deleteById(assuranceId, headers); Assert.assertEquals(new Response<>(0, "Fail.Assurance not clear", assuranceId), result); } @@ -119,8 +119,8 @@ public void testDeleteById2() { @Test public void testDeleteByOrderId1() { UUID orderId = UUID.randomUUID(); - Mockito.doNothing().doThrow(new RuntimeException()).when(assuranceRepository).removeAssuranceByOrderId(orderId); - Mockito.when(assuranceRepository.findByOrderId(orderId)).thenReturn(null); + Mockito.doNothing().doThrow(new RuntimeException()).when(assuranceRepository).removeAssuranceByOrderId(orderId.toString()); + Mockito.when(assuranceRepository.findByOrderId(orderId.toString())).thenReturn(null); Response result = assuranceServiceImpl.deleteByOrderId(orderId, headers); Assert.assertEquals(new Response<>(1, "Delete Success with Order Id", null), result); } @@ -128,9 +128,9 @@ public void testDeleteByOrderId1() { @Test public void testDeleteByOrderId2() { UUID orderId = UUID.randomUUID(); - Mockito.doNothing().doThrow(new RuntimeException()).when(assuranceRepository).removeAssuranceByOrderId(orderId); + Mockito.doNothing().doThrow(new RuntimeException()).when(assuranceRepository).removeAssuranceByOrderId(orderId.toString()); Assurance assurance = new Assurance(); - Mockito.when(assuranceRepository.findByOrderId(orderId)).thenReturn(assurance); + Mockito.when(assuranceRepository.findByOrderId(orderId.toString())).thenReturn(assurance); Response result = assuranceServiceImpl.deleteByOrderId(orderId, headers); Assert.assertEquals(new Response<>(0, "Fail.Assurance not clear", orderId), result); } @@ -139,7 +139,7 @@ public void testDeleteByOrderId2() { public void testModify2() { UUID assuranceId = UUID.randomUUID(); Assurance assurance = new Assurance(null, null, null); - Mockito.when(assuranceRepository.findById(assuranceId)).thenReturn(assurance); + Mockito.when(assuranceRepository.findById(assuranceId.toString())).thenReturn(java.util.Optional.of(assurance)); Mockito.when(assuranceRepository.save(assurance)).thenReturn(null); Response result = assuranceServiceImpl.modify(assuranceId.toString(), "orderId", 1, headers); Assert.assertEquals(new Response<>(1, "Modify Success", new Assurance(null, null, AssuranceType.TRAFFIC_ACCIDENT)), result); @@ -149,7 +149,7 @@ public void testModify2() { public void testModify3() { UUID assuranceId = UUID.randomUUID(); Assurance assurance = new Assurance(null, null, null); - Mockito.when(assuranceRepository.findById(assuranceId)).thenReturn(assurance); + Mockito.when(assuranceRepository.findById(assuranceId.toString())).thenReturn(java.util.Optional.of(assurance)); Mockito.when(assuranceRepository.save(assurance)).thenReturn(null); Response result = assuranceServiceImpl.modify(assuranceId.toString(), "orderId", 0, headers); Assert.assertEquals(new Response<>(0, "Assurance Type not exist", null), result); diff --git a/ts-auth-service/pom.xml b/ts-auth-service/pom.xml index f8b40ea25..5a7478999 100644 --- a/ts-auth-service/pom.xml +++ b/ts-auth-service/pom.xml @@ -19,7 +19,11 @@ org.springframework.boot - spring-boot-starter-data-mongodb + spring-boot-starter-data-jpa + + + mysql + mysql-connector-java org.services @@ -35,11 +39,8 @@ org.springframework.boot spring-boot-starter-security - - - diff --git a/ts-auth-service/src/main/java/auth/AuthApplication.java b/ts-auth-service/src/main/java/auth/AuthApplication.java index 9b47421b4..9d8d88c8e 100644 --- a/ts-auth-service/src/main/java/auth/AuthApplication.java +++ b/ts-auth-service/src/main/java/auth/AuthApplication.java @@ -3,6 +3,8 @@ import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.boot.web.client.RestTemplateBuilder; +import org.springframework.cloud.client.discovery.EnableDiscoveryClient; +import org.springframework.cloud.client.loadbalancer.LoadBalanced; import org.springframework.context.annotation.Bean; import org.springframework.web.client.RestTemplate; @@ -10,12 +12,13 @@ * @author fdse */ @SpringBootApplication +@EnableDiscoveryClient public class AuthApplication { - public static void main(String[] args) { SpringApplication.run(AuthApplication.class, args); } + @LoadBalanced @Bean public RestTemplate restTemplate(RestTemplateBuilder builder) { return builder.build(); diff --git a/ts-auth-service/src/main/java/auth/controller/AuthController.java b/ts-auth-service/src/main/java/auth/controller/AuthController.java index 05be422d9..0c9ee0de4 100644 --- a/ts-auth-service/src/main/java/auth/controller/AuthController.java +++ b/ts-auth-service/src/main/java/auth/controller/AuthController.java @@ -35,7 +35,7 @@ public String getHello() { @PostMapping public HttpEntity createDefaultUser(@RequestBody AuthDto authDto) { - logger.info("Create default auth user with authDto: {}", authDto.toString()); + logger.info("[createDefaultUser][Create default auth user with authDto][AuthDto: {}]", authDto.toString()); userService.createDefaultAuthUser(authDto); Response response = new Response(1, "SUCCESS", authDto); return new ResponseEntity<>(response, HttpStatus.CREATED); diff --git a/ts-auth-service/src/main/java/auth/controller/UserController.java b/ts-auth-service/src/main/java/auth/controller/UserController.java index 8165e922e..2077c3a1a 100644 --- a/ts-auth-service/src/main/java/auth/controller/UserController.java +++ b/ts-auth-service/src/main/java/auth/controller/UserController.java @@ -45,21 +45,21 @@ public ResponseEntity getToken(@RequestBody BasicAuthDto dao , @Reques Response res = tokenService.getToken(dao, headers); return ResponseEntity.ok(res); } catch (UserOperationException e) { - logger.error("Get token error, message: {}", e.getMessage()); + logger.error("[getToken][tokenService.getToken error][UserOperationException, message: {}]", e.getMessage()); return ResponseEntity.ok(new Response<>(0, "get token error", null)); } } @GetMapping public ResponseEntity> getAllUser(@RequestHeader HttpHeaders headers) { - logger.info("Get all users"); + logger.info("[getAllUser][Get all users]"); return ResponseEntity.ok().body(userService.getAllUser(headers)); } @DeleteMapping("/{userId}") public ResponseEntity deleteUserById(@PathVariable String userId, @RequestHeader HttpHeaders headers) { - logger.info("Delete user, userId: {}", userId); - return ResponseEntity.ok(userService.deleteByUserId(UUID.fromString(userId), headers)); + logger.info("[deleteUserById][Delete user][userId: {}]", userId); + return ResponseEntity.ok(userService.deleteByUserId(userId, headers)); } } diff --git a/ts-auth-service/src/main/java/auth/dto/TokenDto.java b/ts-auth-service/src/main/java/auth/dto/TokenDto.java index cf78ce6fb..aac055841 100644 --- a/ts-auth-service/src/main/java/auth/dto/TokenDto.java +++ b/ts-auth-service/src/main/java/auth/dto/TokenDto.java @@ -19,7 +19,7 @@ @NoArgsConstructor public class TokenDto implements Serializable { private static final long serialVersionUID = 8460179745119402516L; - private UUID userId; + private String userId; private String username; private String token; } diff --git a/ts-auth-service/src/main/java/auth/entity/User.java b/ts-auth-service/src/main/java/auth/entity/User.java index 0613ca40f..ccf6a0a76 100644 --- a/ts-auth-service/src/main/java/auth/entity/User.java +++ b/ts-auth-service/src/main/java/auth/entity/User.java @@ -8,27 +8,34 @@ import org.springframework.security.core.authority.SimpleGrantedAuthority; import org.springframework.security.core.userdetails.UserDetails; -import java.util.Collection; -import java.util.HashSet; -import java.util.Set; -import java.util.UUID; +import org.hibernate.annotations.GenericGenerator; + +import javax.persistence.*; +import java.util.*; import java.util.stream.Collectors; /** * @author fdse */ @Data +@GenericGenerator(name = "jpa-uuid", strategy = "org.hibernate.id.UUIDGenerator") @Builder @AllArgsConstructor @NoArgsConstructor +@Entity +@Table(name = "auth_user") public class User implements UserDetails { + @Id + @Column(length=36, name = "user_id") + private String userId; - private UUID userId; - + @Column(length=36, name = "user_name") private String username; private String password; + @ElementCollection + @CollectionTable(joinColumns = @JoinColumn(name = "user_id")) private Set roles = new HashSet<>(); @Override diff --git a/ts-auth-service/src/main/java/auth/init/InitUser.java b/ts-auth-service/src/main/java/auth/init/InitUser.java index c89c8982f..20dc5b4ba 100644 --- a/ts-auth-service/src/main/java/auth/init/InitUser.java +++ b/ts-auth-service/src/main/java/auth/init/InitUser.java @@ -29,7 +29,7 @@ public void run(String... strings) throws Exception { User whetherExistUser = userRepository.findByUsername("fdse_microservice").orElse(new User()); if (whetherExistUser.getUsername() == null) { User user = User.builder() - .userId(UUID.fromString("4d2a46c7-71cb-4cf1-b5bb-b68406d9da6f")) + .userId("4d2a46c7-71cb-4cf1-b5bb-b68406d9da6f") .username("fdse_microservice") .password(passwordEncoder.encode("111111")) .roles(new HashSet<>(Arrays.asList("ROLE_USER"))) @@ -40,7 +40,7 @@ public void run(String... strings) throws Exception { User whetherExistAdmin = userRepository.findByUsername("admin").orElse(new User()); if (whetherExistAdmin.getUsername() == null) { User admin = User.builder() - .userId(UUID.randomUUID()) + .userId(UUID.randomUUID().toString()) .username("admin") .password(passwordEncoder.encode("222222")) .roles(new HashSet<>(Arrays.asList("ROLE_ADMIN"))) diff --git a/ts-auth-service/src/main/java/auth/repository/UserRepository.java b/ts-auth-service/src/main/java/auth/repository/UserRepository.java index c2e27e915..f0d948134 100644 --- a/ts-auth-service/src/main/java/auth/repository/UserRepository.java +++ b/ts-auth-service/src/main/java/auth/repository/UserRepository.java @@ -1,7 +1,7 @@ package auth.repository; import auth.entity.User; -import org.springframework.data.mongodb.repository.MongoRepository; +import org.springframework.data.repository.CrudRepository; import java.util.Optional; import java.util.UUID; @@ -9,7 +9,7 @@ /** * @author fdse */ -public interface UserRepository extends MongoRepository { +public interface UserRepository extends CrudRepository { /** * find by username @@ -25,5 +25,5 @@ public interface UserRepository extends MongoRepository { * @param userId user id * @return null */ - void deleteByUserId(UUID userId); + void deleteByUserId(String userId); } diff --git a/ts-auth-service/src/main/java/auth/security/UserDetailsServiceImpl.java b/ts-auth-service/src/main/java/auth/security/UserDetailsServiceImpl.java index fdbba03ee..e62392eb3 100644 --- a/ts-auth-service/src/main/java/auth/security/UserDetailsServiceImpl.java +++ b/ts-auth-service/src/main/java/auth/security/UserDetailsServiceImpl.java @@ -25,7 +25,7 @@ public class UserDetailsServiceImpl implements UserDetailsService { @Override public UserDetails loadUserByUsername(String s) throws UsernameNotFoundException { - LOGGER.info("UsernamePasswordAuthenticationToken username :" + s); + LOGGER.info("[loadUserByUsername][load UsernamePasswordAuthenticationToken][username: {}]", s); return userRepository.findByUsername(s) .orElseThrow(() -> new UsernameNotFoundException( MessageFormat.format(InfoConstant.USER_NAME_NOT_FOUND_1, s) diff --git a/ts-auth-service/src/main/java/auth/service/UserService.java b/ts-auth-service/src/main/java/auth/service/UserService.java index 926c52160..de15d461b 100644 --- a/ts-auth-service/src/main/java/auth/service/UserService.java +++ b/ts-auth-service/src/main/java/auth/service/UserService.java @@ -44,6 +44,6 @@ public interface UserService { * @param headers headers * @return Response */ - Response deleteByUserId(UUID userId, HttpHeaders headers); + Response deleteByUserId(String userId, HttpHeaders headers); } diff --git a/ts-auth-service/src/main/java/auth/service/impl/TokenServiceImpl.java b/ts-auth-service/src/main/java/auth/service/impl/TokenServiceImpl.java index 66a763297..450b1e8af 100644 --- a/ts-auth-service/src/main/java/auth/service/impl/TokenServiceImpl.java +++ b/ts-auth-service/src/main/java/auth/service/impl/TokenServiceImpl.java @@ -12,6 +12,9 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.cloud.client.ServiceInstance; +import org.springframework.cloud.client.discovery.DiscoveryClient; import org.springframework.http.HttpEntity; import org.springframework.http.HttpHeaders; import org.springframework.http.HttpMethod; @@ -24,6 +27,7 @@ import org.springframework.web.client.RestTemplate; import java.text.MessageFormat; +import java.util.List; /** * @author fdse @@ -44,17 +48,24 @@ public class TokenServiceImpl implements TokenService { @Autowired private RestTemplate restTemplate; + @Autowired + private DiscoveryClient discoveryClient; + + private String getServiceUrl(String serviceName) { + return "http://" + serviceName; + } + @Override public Response getToken(BasicAuthDto dto, HttpHeaders headers) throws UserOperationException { String username = dto.getUsername(); String password = dto.getPassword(); String verifyCode = dto.getVerificationCode(); // LOGGER.info("LOGIN USER :" + username + " __ " + password + " __ " + verifyCode); - + String verification_code_service_url = getServiceUrl("ts-verification-code-service"); if (!StringUtils.isEmpty(verifyCode)) { HttpEntity requestEntity = new HttpEntity(headers); ResponseEntity re = restTemplate.exchange( - "http://ts-verification-code-service:15678/api/v1/verifycode/verify/" + verifyCode, + verification_code_service_url + "/api/v1/verifycode/verify/" + verifyCode, HttpMethod.GET, requestEntity, Boolean.class); @@ -62,7 +73,7 @@ public Response getToken(BasicAuthDto dto, HttpHeaders headers) throws UserOpera // failed code if (!id) { - LOGGER.info("Verification failed, userName: {}", username); + LOGGER.info("[getToken][Verification failed][userName: {}]", username); return new Response<>(0, "Verification failed.", null); } } @@ -72,7 +83,7 @@ public Response getToken(BasicAuthDto dto, HttpHeaders headers) throws UserOpera try { authenticationManager.authenticate(upat); } catch (AuthenticationException e) { - LOGGER.warn("Incorrect username or password, username: {}, password: {}", username, password); + LOGGER.warn("[getToken][Incorrect username or password][username: {}, password: {}]", username, password); return new Response<>(0, "Incorrect username or password.", null); } @@ -81,8 +92,7 @@ public Response getToken(BasicAuthDto dto, HttpHeaders headers) throws UserOpera InfoConstant.USER_NAME_NOT_FOUND_1, username ))); String token = jwtProvider.createToken(user); - LOGGER.info("USER TOKEN: "+ token); - LOGGER.info("USER ID: " + user.getUserId()); + LOGGER.info("[getToken][success][USER TOKEN: {} USER ID: {}]", token, user.getUserId()); return new Response<>(1, "login success", new TokenDto(user.getUserId(), username, token)); } } diff --git a/ts-auth-service/src/main/java/auth/service/impl/UserServiceImpl.java b/ts-auth-service/src/main/java/auth/service/impl/UserServiceImpl.java index 2931fbf46..1bf0cb2a0 100644 --- a/ts-auth-service/src/main/java/auth/service/impl/UserServiceImpl.java +++ b/ts-auth-service/src/main/java/auth/service/impl/UserServiceImpl.java @@ -14,6 +14,7 @@ import org.springframework.http.HttpHeaders; import org.springframework.security.crypto.password.PasswordEncoder; import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; import java.text.MessageFormat; import java.util.*; @@ -38,7 +39,7 @@ public User saveUser(User user) { @Override public List getAllUser(HttpHeaders headers) { - return userRepository.findAll(); + return (List) userRepository.findAll(); } /** @@ -49,9 +50,9 @@ public List getAllUser(HttpHeaders headers) { */ @Override public User createDefaultAuthUser(AuthDto dto) { - LOGGER.info("Register User Info is: " + dto.getUserName()); + LOGGER.info("[createDefaultAuthUser][Register User Info][AuthDto name: {}]", dto.getUserName()); User user = User.builder() - .userId(UUID.fromString(dto.getUserId())) + .userId(dto.getUserId()) .username(dto.getUserName()) .password(passwordEncoder.encode(dto.getPassword())) .roles(new HashSet<>(Arrays.asList(AuthConstant.ROLE_USER))) @@ -59,14 +60,15 @@ public User createDefaultAuthUser(AuthDto dto) { try { checkUserCreateInfo(user); } catch (UserOperationException e) { - LOGGER.error("Create default auth user error, message: {}", e.getMessage()); + LOGGER.error("[createDefaultAuthUser][Create default auth user][UserOperationException][message: {}]", e.getMessage()); } return userRepository.save(user); } @Override - public Response deleteByUserId(UUID userId, HttpHeaders headers) { - LOGGER.info("DELETE USER :" + userId); + @Transactional + public Response deleteByUserId(String userId, HttpHeaders headers) { + LOGGER.info("[deleteByUserId][DELETE USER][user id: {}]", userId); userRepository.deleteByUserId(userId); return new Response(1, "DELETE USER SUCCESS", null); } @@ -77,7 +79,7 @@ public Response deleteByUserId(UUID userId, HttpHeaders headers) { * @param user */ private void checkUserCreateInfo(User user) throws UserOperationException { - LOGGER.info("Check user create info, userId: {}, userName: {}", user.getUserId(), user.getUsername()); + LOGGER.info("[checkUserCreateInfo][Check user create info][userId: {}, userName: {}]", user.getUserId(), user.getUsername()); List infos = new ArrayList<>(); if (null == user.getUsername() || "".equals(user.getUsername())) { diff --git a/ts-auth-service/src/main/resources/application.yaml b/ts-auth-service/src/main/resources/application.yaml index 02f7e91b8..3545ea5ef 100644 --- a/ts-auth-service/src/main/resources/application.yaml +++ b/ts-auth-service/src/main/resources/application.yaml @@ -1,13 +1,24 @@ server: port: 12340 spring: + cloud: + nacos: + discovery: + server-addr: ${NACOS_ADDRS:nacos-0.nacos-headless.default.svc.cluster.local,nacos-1.nacos-headless.default.svc.cluster.local,nacos-2.nacos-headless.default.svc.cluster.local} application: name: ts-auth-service - data: - mongodb: - host: ts-auth-mongo - database: ts-auth-mongo - port: 27017 + datasource: + url: jdbc:mysql://${AUTH_MYSQL_HOST:ts-auth-mysql}:${AUTH_MYSQL_PORT:3306}/${AUTH_MYSQL_DATABASE:ts-auth-mysql}?useSSL=false + username: ${AUTH_MYSQL_USER:root} + password: ${AUTH_MYSQL_PASSWORD:Abcd1234#} + driver-class-name: com.mysql.cj.jdbc.Driver + jpa: + hibernate: + ddl-auto: update + properties: + hibernate: + dialect: org.hibernate.dialect.MySQL5Dialect + swagger: - controllerPackage: auth.controller \ No newline at end of file + controllerPackage: auth.controller diff --git a/ts-auth-service/src/test/java/auth/controller/UserControllerTest.java b/ts-auth-service/src/test/java/auth/controller/UserControllerTest.java index 83ad06155..372a9f099 100644 --- a/ts-auth-service/src/test/java/auth/controller/UserControllerTest.java +++ b/ts-auth-service/src/test/java/auth/controller/UserControllerTest.java @@ -75,7 +75,7 @@ public void testGetAllUser() throws Exception { @Test public void testDeleteUserById() throws Exception { UUID userId = UUID.randomUUID(); - Mockito.when(userService.deleteByUserId(Mockito.any(UUID.class), Mockito.any(HttpHeaders.class))).thenReturn(response); + Mockito.when(userService.deleteByUserId(Mockito.any(UUID.class).toString(), Mockito.any(HttpHeaders.class))).thenReturn(response); String result = mockMvc.perform(MockMvcRequestBuilders.delete("/api/v1/users/" + userId.toString())) .andExpect(MockMvcResultMatchers.status().isOk()) .andReturn().getResponse().getContentAsString(); diff --git a/ts-auth-service/src/test/java/auth/service/UserServiceImplTest.java b/ts-auth-service/src/test/java/auth/service/UserServiceImplTest.java index 0a5e4df3e..245174835 100644 --- a/ts-auth-service/src/test/java/auth/service/UserServiceImplTest.java +++ b/ts-auth-service/src/test/java/auth/service/UserServiceImplTest.java @@ -63,8 +63,8 @@ public void testCreateDefaultAuthUser() { @Test public void testDeleteByUserId() { UUID userId = UUID.randomUUID(); - Mockito.doNothing().doThrow(new RuntimeException()).when(userRepository).deleteByUserId(userId); - Assert.assertEquals(new Response(1, "DELETE USER SUCCESS", null), userServiceImpl.deleteByUserId(userId, headers)); + Mockito.doNothing().doThrow(new RuntimeException()).when(userRepository).deleteByUserId(userId.toString()); + Assert.assertEquals(new Response(1, "DELETE USER SUCCESS", null), userServiceImpl.deleteByUserId(userId.toString(), headers)); } } diff --git a/ts-basic-service/pom.xml b/ts-basic-service/pom.xml index 869715e9d..d459f1eb0 100644 --- a/ts-basic-service/pom.xml +++ b/ts-basic-service/pom.xml @@ -15,7 +15,7 @@ org.services ts-service 0.1.0 - ../ + ../pom.xml @@ -30,10 +30,11 @@ ts-common 0.1.0 - - + + jakarta.validation + jakarta.validation-api + - diff --git a/ts-basic-service/src/main/java/fdse/microservice/BasicApplication.java b/ts-basic-service/src/main/java/fdse/microservice/BasicApplication.java index e94a78e46..c2208f145 100644 --- a/ts-basic-service/src/main/java/fdse/microservice/BasicApplication.java +++ b/ts-basic-service/src/main/java/fdse/microservice/BasicApplication.java @@ -3,6 +3,8 @@ import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.boot.web.client.RestTemplateBuilder; +import org.springframework.cloud.client.discovery.EnableDiscoveryClient; +import org.springframework.cloud.client.loadbalancer.LoadBalanced; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.EnableAspectJAutoProxy; import org.springframework.integration.annotation.IntegrationComponentScan; @@ -18,12 +20,14 @@ @EnableAsync @IntegrationComponentScan @EnableSwagger2 +@EnableDiscoveryClient public class BasicApplication { public static void main(String[] args) { SpringApplication.run(BasicApplication.class, args); } + @LoadBalanced @Bean public RestTemplate restTemplate(RestTemplateBuilder builder) { return builder.build(); diff --git a/ts-basic-service/src/main/java/fdse/microservice/controller/BasicController.java b/ts-basic-service/src/main/java/fdse/microservice/controller/BasicController.java index f60da200e..6d7c85308 100644 --- a/ts-basic-service/src/main/java/fdse/microservice/controller/BasicController.java +++ b/ts-basic-service/src/main/java/fdse/microservice/controller/BasicController.java @@ -1,6 +1,6 @@ package fdse.microservice.controller; -import fdse.microservice.entity.Travel; +import edu.fudan.common.entity.Travel; import fdse.microservice.service.BasicService; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -9,6 +9,8 @@ import org.springframework.http.HttpHeaders; import org.springframework.web.bind.annotation.*; +import java.util.List; + import static org.springframework.http.ResponseEntity.ok; /** @@ -33,14 +35,21 @@ public String home(@RequestHeader HttpHeaders headers) { @PostMapping(value = "/basic/travel") public HttpEntity queryForTravel(@RequestBody Travel info, @RequestHeader HttpHeaders headers) { // TravelResult - logger.info("Query for travel: {}", info.toString()); + logger.info("[queryForTravel][Query for travel][Travel: {}]", info.toString()); return ok(service.queryForTravel(info, headers)); } + @PostMapping(value = "/basic/travels") + public HttpEntity queryForTravels(@RequestBody List infos, @RequestHeader HttpHeaders headers) { + // TravelResult + logger.info("[queryForTravels][Query for travels][Travels: {}]", infos); + return ok(service.queryForTravels(infos, headers)); + } + @GetMapping(value = "/basic/{stationName}") public HttpEntity queryForStationId(@PathVariable String stationName, @RequestHeader HttpHeaders headers) { // String id - logger.info("Query for stationId by stationName: {}", stationName); + logger.info("[queryForStationId][Query for stationId by stationName][stationName: {}]", stationName); return ok(service.queryForStationId(stationName, headers)); } diff --git a/ts-basic-service/src/main/java/fdse/microservice/entity/Route.java b/ts-basic-service/src/main/java/fdse/microservice/entity/Route.java deleted file mode 100644 index 1675ae50f..000000000 --- a/ts-basic-service/src/main/java/fdse/microservice/entity/Route.java +++ /dev/null @@ -1,28 +0,0 @@ -package fdse.microservice.entity; - -import com.fasterxml.jackson.annotation.JsonIgnoreProperties; -import java.util.List; -import lombok.*; - -/** - * @author fdse - */ -@Data -@JsonIgnoreProperties(ignoreUnknown = true) -public class Route { - - private String id; - - private List stations; - - private List distances; - - private String startStationId; - - private String terminalStationId; - - public Route() { - //Default Constructor - } - -} diff --git a/ts-basic-service/src/main/java/fdse/microservice/entity/TrainType.java b/ts-basic-service/src/main/java/fdse/microservice/entity/TrainType.java deleted file mode 100644 index fc89bc349..000000000 --- a/ts-basic-service/src/main/java/fdse/microservice/entity/TrainType.java +++ /dev/null @@ -1,29 +0,0 @@ -package fdse.microservice.entity; - -import lombok.Data; - -/** - * @author fdse - */ -@Data -public class TrainType { - - private String id; - - private int economyClass; - - private int confortClass; - - private int averageSpeed; - - public TrainType(){ - - } - - public TrainType(String id, int economyClass, int confortClass) { - this.id = id; - this.economyClass = economyClass; - this.confortClass = confortClass; - } - -} diff --git a/ts-basic-service/src/main/java/fdse/microservice/entity/Travel.java b/ts-basic-service/src/main/java/fdse/microservice/entity/Travel.java deleted file mode 100644 index c0f21fa2f..000000000 --- a/ts-basic-service/src/main/java/fdse/microservice/entity/Travel.java +++ /dev/null @@ -1,24 +0,0 @@ -package fdse.microservice.entity; - -import lombok.AllArgsConstructor; -import lombok.Data; - -import java.util.Date; - -/** - * @author fdse - */ -@Data -@AllArgsConstructor -public class Travel { - - private Trip trip; - private String startingPlace; - private String endPlace; - private Date departureTime; - - public Travel(){ - //Default Constructor - } - -} diff --git a/ts-basic-service/src/main/java/fdse/microservice/entity/TravelResult.java b/ts-basic-service/src/main/java/fdse/microservice/entity/TravelResult.java deleted file mode 100644 index e2163d15c..000000000 --- a/ts-basic-service/src/main/java/fdse/microservice/entity/TravelResult.java +++ /dev/null @@ -1,25 +0,0 @@ -package fdse.microservice.entity; - -import java.util.Map; -import lombok.*; - -/** - * @author fdse - */ -@Data -public class TravelResult { - private boolean status; - private double percent; - private TrainType trainType; - - private Map prices; - - public TravelResult(){ - //Default Constructor - } - - public boolean isStatus() { - return status; - } - -} diff --git a/ts-basic-service/src/main/java/fdse/microservice/entity/Trip.java b/ts-basic-service/src/main/java/fdse/microservice/entity/Trip.java deleted file mode 100644 index e716fdfcb..000000000 --- a/ts-basic-service/src/main/java/fdse/microservice/entity/Trip.java +++ /dev/null @@ -1,73 +0,0 @@ -package fdse.microservice.entity; - -import lombok.AllArgsConstructor; -import lombok.Data; - -import javax.validation.Valid; -import javax.validation.constraints.NotNull; -import java.util.Date; - -/** - * @author fdse - */ -@Data -@AllArgsConstructor -public class Trip { - @Valid - private TripId tripId; - - @Valid - @NotNull - private String trainTypeId; - - private String routeId; - - @Valid - @NotNull - private String startingStationId; - - @Valid - private String stationsId; - - @Valid - @NotNull - private String terminalStationId; - - @Valid - @NotNull - private Date startingTime; - - @Valid - @NotNull - private Date endTime; - - public Trip(TripId tripId, String trainTypeId, String startingStationId, String stationsId, String terminalStationId, Date startingTime, Date endTime) { - this.tripId = tripId; - this.trainTypeId = trainTypeId; - this.startingStationId = startingStationId; - this.stationsId = stationsId; - this.terminalStationId = terminalStationId; - this.startingTime = startingTime; - this.endTime = endTime; - } - - public Trip(TripId tripId, String trainTypeId, String routeId) { - this.tripId = tripId; - this.trainTypeId = trainTypeId; - this.routeId = routeId; - this.startingStationId = ""; - this.terminalStationId = ""; - this.startingTime = new Date(); - this.endTime = new Date(); - } - - public Trip(){ - //Default Constructor - this.startingStationId = ""; - this.trainTypeId = ""; - this.terminalStationId = ""; - this.startingTime = new Date(); - this.endTime = new Date(); - } - -} diff --git a/ts-basic-service/src/main/java/fdse/microservice/entity/TripId.java b/ts-basic-service/src/main/java/fdse/microservice/entity/TripId.java deleted file mode 100644 index 109f26348..000000000 --- a/ts-basic-service/src/main/java/fdse/microservice/entity/TripId.java +++ /dev/null @@ -1,40 +0,0 @@ -package fdse.microservice.entity; - -import lombok.Data; - -import java.io.Serializable; - -/** - * @author fdse - */ -@Data -public class TripId implements Serializable{ - private Type type; - private String number; - - public TripId(){} - - public TripId(String trainNumber){ - char type0 = trainNumber.charAt(0); - switch(type0){ - case 'G': this.type = Type.G; - break; - case 'D': this.type = Type.D; - break; - case 'Z': this.type = Type.Z; - break; - case 'T': this.type = Type.T; - break; - case 'K': this.type = Type.K; - break; - default:break; - } - - this.number = trainNumber.substring(1); - } - - @Override - public String toString(){ - return type.getName() + number; - } -} diff --git a/ts-basic-service/src/main/java/fdse/microservice/entity/Type.java b/ts-basic-service/src/main/java/fdse/microservice/entity/Type.java deleted file mode 100644 index c031947db..000000000 --- a/ts-basic-service/src/main/java/fdse/microservice/entity/Type.java +++ /dev/null @@ -1,63 +0,0 @@ -package fdse.microservice.entity; - -import java.io.Serializable; - -/** - * @author fdse - */ -public enum Type implements Serializable{ - - /** - * 1 - */ - G("G", 1), - /** - * 2 - */ - D("D", 2), - /** - * 3 - */ - Z("Z",3), - /** - * 4 - */ - T("T", 4), - /** - * 5 - */ - K("K", 5); - - private String name; - private int index; - - Type(String name, int index) { - this.name = name; - this.index = index; - } - - public static String getName(int index) { - for (Type type : Type.values()) { - if (type.getIndex() == index) { - return type.name; - } - } - return null; - } - - public String getName() { - return name; - } - - void setName(String name) { - this.name = name; - } - - public int getIndex() { - return index; - } - - void setIndex(int index) { - this.index = index; - } -} diff --git a/ts-basic-service/src/main/java/fdse/microservice/service/BasicService.java b/ts-basic-service/src/main/java/fdse/microservice/service/BasicService.java index 7e3d7288c..32b14df3d 100644 --- a/ts-basic-service/src/main/java/fdse/microservice/service/BasicService.java +++ b/ts-basic-service/src/main/java/fdse/microservice/service/BasicService.java @@ -1,9 +1,12 @@ package fdse.microservice.service; +import edu.fudan.common.entity.Travel; import edu.fudan.common.util.Response; -import fdse.microservice.entity.*; +import edu.fudan.common.entity.*; import org.springframework.http.HttpHeaders; +import java.util.List; + /** * @author Chenjie * @date 2017/6/6. @@ -19,6 +22,8 @@ public interface BasicService { */ Response queryForTravel(Travel info, HttpHeaders headers); + Response queryForTravels(List infos, HttpHeaders headers); + /** * query for station id with station name * diff --git a/ts-basic-service/src/main/java/fdse/microservice/service/BasicServiceImpl.java b/ts-basic-service/src/main/java/fdse/microservice/service/BasicServiceImpl.java index 18a028c56..4020b0b04 100644 --- a/ts-basic-service/src/main/java/fdse/microservice/service/BasicServiceImpl.java +++ b/ts-basic-service/src/main/java/fdse/microservice/service/BasicServiceImpl.java @@ -1,11 +1,14 @@ package fdse.microservice.service; +import com.fasterxml.jackson.core.type.TypeReference; +import com.fasterxml.jackson.databind.ObjectMapper; +import edu.fudan.common.entity.*; import edu.fudan.common.util.JsonUtils; import edu.fudan.common.util.Response; -import fdse.microservice.entity.*; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.cloud.client.discovery.DiscoveryClient; import org.springframework.http.HttpEntity; import org.springframework.http.HttpHeaders; import org.springframework.http.HttpMethod; @@ -13,7 +16,7 @@ import org.springframework.stereotype.Service; import org.springframework.web.client.RestTemplate; -import java.util.HashMap; +import java.util.*; /** * @author fdse @@ -24,8 +27,15 @@ public class BasicServiceImpl implements BasicService { @Autowired private RestTemplate restTemplate; + @Autowired + private DiscoveryClient discoveryClient; + private static final Logger LOGGER = LoggerFactory.getLogger(BasicServiceImpl.class); + private String getServiceUrl(String serviceName) { + return "http://" + serviceName; + } + @Override public Response queryForTravel(Travel info, HttpHeaders headers) { @@ -34,59 +44,62 @@ public Response queryForTravel(Travel info, HttpHeaders headers) { result.setStatus(true); response.setStatus(1); response.setMsg("Success"); - boolean startingPlaceExist = checkStationExists(info.getStartingPlace(), headers); - boolean endPlaceExist = checkStationExists(info.getEndPlace(), headers); + String start = info.getStartPlace(); + String end = info.getEndPlace(); + boolean startingPlaceExist = checkStationExists(start, headers); + boolean endPlaceExist = checkStationExists(end, headers); if (!startingPlaceExist || !endPlaceExist) { result.setStatus(false); response.setStatus(0); response.setMsg("Start place or end place not exist!"); if (!startingPlaceExist) - BasicServiceImpl.LOGGER.warn("Start place {} not exist", info.getStartingPlace()); + BasicServiceImpl.LOGGER.warn("[queryForTravel][Start place not exist][start place: {}]", info.getStartPlace()); if (!endPlaceExist) - BasicServiceImpl.LOGGER.warn("End place {} not exist", info.getEndPlace()); + BasicServiceImpl.LOGGER.warn("[queryForTravel][End place not exist][end place: {}]", info.getEndPlace()); } - TrainType trainType = queryTrainType(info.getTrip().getTrainTypeId(), headers); + TrainType trainType = queryTrainTypeByName(info.getTrip().getTrainTypeName(), headers); if (trainType == null) { - BasicServiceImpl.LOGGER.warn("traintype doesn't exist, trainTypeId: {}", info.getTrip().getTrainTypeId()); + BasicServiceImpl.LOGGER.warn("[queryForTravel][traintype doesn't exist][trainTypeName: {}]", info.getTrip().getTrainTypeName()); result.setStatus(false); response.setStatus(0); response.setMsg("Train type doesn't exist"); + return response; } else { result.setTrainType(trainType); } String routeId = info.getTrip().getRouteId(); - String trainTypeString = ""; - if (trainType != null){ - trainTypeString = trainType.getId(); - } Route route = getRouteByRouteId(routeId, headers); - PriceConfig priceConfig = queryPriceConfigByRouteIdAndTrainType(routeId, trainTypeString, headers); - - String startingPlaceId = (String) queryForStationId(info.getStartingPlace(), headers).getData(); - String endPlaceId = (String) queryForStationId(info.getEndPlace(), headers).getData(); - - LOGGER.info("startingPlaceId: " + startingPlaceId + "endPlaceId: " + endPlaceId); + if(route == null){ + result.setStatus(false); + response.setStatus(0); + response.setMsg("Route doesn't exist"); + return response; + } + //Check the route list for this train. Check that the required start and arrival stations are in the list of stops that are not on the route, and check that the location of the start station is before the stop + //Trains that meet the above criteria are added to the return list int indexStart = 0; int indexEnd = 0; - if (route != null) { - indexStart = route.getStations().indexOf(startingPlaceId); - indexEnd = route.getStations().indexOf(endPlaceId); - } - - LOGGER.info("indexStart: " + indexStart + " __ " + "indexEnd: " + indexEnd); - if (route != null){ - LOGGER.info("route.getDistances().size: " + route.getDistances().size()); + if (route.getStations().contains(start) && + route.getStations().contains(end) && + route.getStations().indexOf(start) < route.getStations().indexOf(end)){ + indexStart = route.getStations().indexOf(start); + indexEnd = route.getStations().indexOf(end); + LOGGER.info("[queryForTravel][query start index and end index][indexStart: {} indexEnd: {}]", indexStart, indexEnd); + LOGGER.info("[queryForTravel][query stations and distances][stations: {} distances: {}]", route.getStations(), route.getDistances()); + }else { + result.setStatus(false); + response.setStatus(0); + response.setMsg("Station not correct in Route"); + return response; } + PriceConfig priceConfig = queryPriceConfigByRouteIdAndTrainType(routeId, trainType.getName(), headers); HashMap prices = new HashMap<>(); try { int distance = 0; - if (route != null){ - distance = route.getDistances().get(indexEnd) - route.getDistances().get(indexStart); - } - + distance = route.getDistances().get(indexEnd) - route.getDistances().get(indexStart); /** * We need the price Rate and distance (starting station). */ @@ -95,38 +108,259 @@ public Response queryForTravel(Travel info, HttpHeaders headers) { prices.put("economyClass", "" + priceForEconomyClass); prices.put("confortClass", "" + priceForConfortClass); }catch (Exception e){ - prices.put("economyClass", "95.0"); - prices.put("confortClass", "120.0"); + prices.put("economyClass", "95.0"); + prices.put("confortClass", "120.0"); } + result.setRoute(route); result.setPrices(prices); result.setPercent(1.0); response.setData(result); + BasicServiceImpl.LOGGER.info("[queryForTravel][all done][result: {}]", result); + return response; } + @Override + public Response queryForTravels(List infos, HttpHeaders headers) { + Response response = new Response<>(); + response.setStatus(1); + response.setMsg("Success"); + + HashMap tripInfos = new HashMap<>(); + HashMap> startTrips = new HashMap<>(); + HashMap> endTrips = new HashMap<>(); + HashMap> routeTrips = new HashMap<>(); + HashMap> typeTrips = new HashMap<>(); + Set stationNames = new HashSet<>(); + Set trainTypeNames = new HashSet<>(); + Set routeIds = new HashSet<>(); + Set avaTrips = new HashSet<>(); + for(Travel info: infos){ + stationNames.add(info.getStartPlace()); + stationNames.add(info.getEndPlace()); + trainTypeNames.add(info.getTrip().getTrainTypeName()); + routeIds.add(info.getTrip().getRouteId()); + + String tripNumber = info.getTrip().getTripId().toString(); + avaTrips.add(tripNumber); + tripInfos.put(tripNumber, info); + + String start = info.getStartPlace(); + List trips = startTrips.get(start); + if(trips == null) { + trips = new ArrayList<>(); + } + trips.add(tripNumber); + startTrips.put(start, trips); + + String end = info.getEndPlace(); + trips = endTrips.get(end); + if(trips == null) { + trips = new ArrayList<>(); + } + trips.add(tripNumber); + endTrips.put(end, trips); + + String routeId = info.getTrip().getRouteId(); + trips = routeTrips.get(routeId); + if(trips == null) { + trips = new ArrayList<>(); + } + trips.add(tripNumber); + routeTrips.put(routeId, trips); + + String trainTypeName = info.getTrip().getTrainTypeName(); + trips = typeTrips.get(trainTypeName); + if(trips == null) { + trips = new ArrayList<>(); + } + trips.add(tripNumber); + typeTrips.put(trainTypeName, trips); + } + + //List invalidTrips = new ArrayList<>(); + + // check if station exist to exclude invalid travel info + Map stationMap = checkStationsExists(new ArrayList<>(stationNames), headers); + if(stationMap == null) { + response.setStatus(0); + response.setMsg("all stations don't exist"); + return response; + } + for(Map.Entry s : stationMap.entrySet()){ + if(s.getValue() == null ){ + // station not exist + if(startTrips.get(s.getKey()) != null){ + avaTrips.removeAll(startTrips.get(s.getKey())); + } + if(endTrips.get(s.getKey()) != null){ + avaTrips.removeAll(endTrips.get(s.getKey())); + } + } + } + + if(avaTrips.size() == 0){ + response.setStatus(0); + response.setMsg("no travel info available"); + return response; + } + + // check if train_type exist + List tts = queryTrainTypeByNames(new ArrayList<>(trainTypeNames), headers); + if(tts == null){ + response.setStatus(0); + response.setMsg("all train_type don't exist"); + return response; + } + Map trainTypeMap = new HashMap<>(); + for(TrainType t: tts){ + trainTypeMap.put(t.getName(), t); + } + for(Map.Entry> typeTrip: typeTrips.entrySet()){ + String ttype = typeTrip.getKey(); + if(trainTypeMap.get(ttype) == null){ + avaTrips.removeAll(typeTrip.getValue()); + } + } + if(avaTrips.size() ==0){ + response.setStatus(0); + response.setMsg("no travel info available"); + return response; + } + + // check if route exist to exclude invalid travel info + List routes = getRoutesByRouteIds(new ArrayList<>(routeIds), headers); + if(routes == null) { + response.setStatus(0); + response.setMsg("all routes don't exist"); + return response; + } + Map routeMap = new HashMap<>(); + for(Route r: routes){ + routeMap.put(r.getId(), r); + } + for(Map.Entry> routeTrip: routeTrips.entrySet()){ + String routeId = routeTrip.getKey(); + if(routeMap.get(routeId) == null){ + avaTrips.removeAll(routeTrip.getValue()); + }else{ + Route route = routeMap.get(routeId); + List trips = routeTrip.getValue(); + for(String t: trips){ + String start = tripInfos.get(t).getStartPlace(); + String end = tripInfos.get(t).getEndPlace(); + if (!route.getStations().contains(start) || + !route.getStations().contains(end) || + route.getStations().indexOf(start) >= route.getStations().indexOf(end)){ + avaTrips.remove(t); + } + } + } + } + if(avaTrips.size() == 0){ + response.setStatus(0); + response.setMsg("no travel info available"); + return response; + } + + List routeIdAndTypes = new ArrayList<>(); + for(String tripNumber: avaTrips){ + String routeId = tripInfos.get(tripNumber).getTrip().getRouteId(); + String trainType = tripInfos.get(tripNumber).getTrip().getTrainTypeName(); + routeIdAndTypes.add(routeId+":"+trainType); + } + Map pcMap = queryPriceConfigByRouteIdsAndTrainTypes(routeIdAndTypes, headers); + + Map trMap = new HashMap<>(); + for(String tripNumber: avaTrips){ + Travel info = tripInfos.get(tripNumber); + String trainType = info.getTrip().getTrainTypeName(); + String routeId = info.getTrip().getRouteId(); + Route route = routeMap.get(routeId); + + int indexStart = route.getStations().indexOf(info.getStartPlace()); + int indexEnd = route.getStations().indexOf(info.getEndPlace()); + + double basicPriceRate = 0.75; + double firstPriceRate = 1; + PriceConfig priceConfig = pcMap.get(routeId+":"+trainType); + if(priceConfig != null){ + basicPriceRate = priceConfig.getBasicPriceRate(); + firstPriceRate = priceConfig.getFirstClassPriceRate(); + } + + HashMap prices = new HashMap<>(); + try { + int distance = 0; + distance = route.getDistances().get(indexEnd) - route.getDistances().get(indexStart); + /** + * We need the price Rate and distance (starting station). + */ + double priceForEconomyClass = distance * basicPriceRate; + double priceForConfortClass = distance * firstPriceRate; + prices.put("economyClass", "" + priceForEconomyClass); + prices.put("confortClass", "" + priceForConfortClass); + }catch (Exception e){ + prices.put("economyClass", "95.0"); + prices.put("confortClass", "120.0"); + } + + + TravelResult result = new TravelResult(); + result.setStatus(true); + result.setTrainType(trainTypeMap.get(trainType)); + result.setRoute(route); + result.setPrices(prices); + result.setPercent(1.0); + + trMap.put(tripNumber, result); + } + response.setData(trMap); + BasicServiceImpl.LOGGER.info("[queryForTravels][all done][result map: {}]", trMap); + return response; + } @Override public Response queryForStationId(String stationName, HttpHeaders headers) { - BasicServiceImpl.LOGGER.info("[Query For Station Id] stationName: {}", stationName); + BasicServiceImpl.LOGGER.info("[queryForStationId][Query For Station Id][stationName: {}]", stationName); HttpEntity requestEntity = new HttpEntity(null); + String station_service_url=getServiceUrl("ts-station-service"); ResponseEntity re = restTemplate.exchange( - "http://ts-station-service:12345/api/v1/stationservice/stations/id/" + stationName, + station_service_url + "/api/v1/stationservice/stations/id/" + stationName, HttpMethod.GET, requestEntity, Response.class); if (re.getBody().getStatus() != 1) { String msg = re.getBody().getMsg(); - BasicServiceImpl.LOGGER.warn("Query for stationId error, stationName: {}, message: {}", stationName, msg); + BasicServiceImpl.LOGGER.warn("[queryForStationId][Query for stationId error][stationName: {}, message: {}]", stationName, msg); return new Response<>(0, msg, null); } return re.getBody(); } + public Map checkStationsExists(List stationNames, HttpHeaders headers) { + BasicServiceImpl.LOGGER.info("[checkStationsExists][Check Stations Exists][stationNames: {}]", stationNames); + HttpEntity requestEntity = new HttpEntity(stationNames, null); + String station_service_url=getServiceUrl("ts-station-service"); + ResponseEntity re = restTemplate.exchange( + station_service_url + "/api/v1/stationservice/stations/idlist", + HttpMethod.POST, + requestEntity, + Response.class); + Response> r = re.getBody(); + if(r.getStatus() == 0) { + return null; + } + Map stationMap = r.getData(); + return stationMap; + } + public boolean checkStationExists(String stationName, HttpHeaders headers) { - BasicServiceImpl.LOGGER.info("[Check Station Exists] stationName: {}", stationName); + BasicServiceImpl.LOGGER.info("[checkStationExists][Check Station Exists][stationName: {}]", stationName); HttpEntity requestEntity = new HttpEntity(null); + String station_service_url=getServiceUrl("ts-station-service"); ResponseEntity re = restTemplate.exchange( - "http://ts-station-service:12345/api/v1/stationservice/stations/id/" + stationName, + station_service_url + "/api/v1/stationservice/stations/id/" + stationName, HttpMethod.GET, requestEntity, Response.class); @@ -135,11 +369,29 @@ public boolean checkStationExists(String stationName, HttpHeaders headers) { return exist.getStatus() == 1; } - public TrainType queryTrainType(String trainTypeId, HttpHeaders headers) { - BasicServiceImpl.LOGGER.info("[Query Train Type] Train Type: {}", trainTypeId); + public List queryTrainTypeByNames(List trainTypeNames, HttpHeaders headers) { + BasicServiceImpl.LOGGER.info("[queryTrainTypeByNames][Query Train Type][Train Type names: {}]", trainTypeNames); + HttpEntity requestEntity = new HttpEntity(trainTypeNames, null); + String train_service_url=getServiceUrl("ts-train-service"); + ResponseEntity re = restTemplate.exchange( + train_service_url + "/api/v1/trainservice/trains/byNames", + HttpMethod.POST, + requestEntity, + Response.class); + Response> response = re.getBody(); + if(response.getStatus() == 0){ + return null; + } + List tts = Arrays.asList(JsonUtils.conveterObject(response.getData(), TrainType[].class)); + return tts; + } + + public TrainType queryTrainTypeByName(String trainTypeName, HttpHeaders headers) { + BasicServiceImpl.LOGGER.info("[queryTrainTypeByName][Query Train Type][Train Type name: {}]", trainTypeName); HttpEntity requestEntity = new HttpEntity(null); + String train_service_url=getServiceUrl("ts-train-service"); ResponseEntity re = restTemplate.exchange( - "http://ts-train-service:14567/api/v1/trainservice/trains/" + trainTypeId, + train_service_url + "/api/v1/trainservice/trains/byName/" + trainTypeName, HttpMethod.GET, requestEntity, Response.class); @@ -148,36 +400,86 @@ public TrainType queryTrainType(String trainTypeId, HttpHeaders headers) { return JsonUtils.conveterObject(response.getData(), TrainType.class); } + private List getRoutesByRouteIds(List routeIds, HttpHeaders headers) { + BasicServiceImpl.LOGGER.info("[getRoutesByRouteIds][Get Route By Ids][Route IDs:{}]", routeIds); + HttpEntity requestEntity = new HttpEntity(routeIds, null); + String route_service_url=getServiceUrl("ts-route-service"); + ResponseEntity re = restTemplate.exchange( + route_service_url + "/api/v1/routeservice/routes/byIds/", + HttpMethod.POST, + requestEntity, + Response.class); + Response> result = re.getBody(); + if ( result.getStatus() == 0) { + BasicServiceImpl.LOGGER.warn("[getRoutesByRouteIds][Get Route By Ids Failed][Fail msg: {}]", result.getMsg()); + return null; + } else { + BasicServiceImpl.LOGGER.info("[getRoutesByRouteIds][Get Route By Ids][Success]"); + List routes = Arrays.asList(JsonUtils.conveterObject(result.getData(), Route[].class));; + return routes; + } + } + private Route getRouteByRouteId(String routeId, HttpHeaders headers) { - BasicServiceImpl.LOGGER.info("[Get Route By Id] Route ID:{}", routeId); + BasicServiceImpl.LOGGER.info("[getRouteByRouteId][Get Route By Id][Route ID:{}]", routeId); HttpEntity requestEntity = new HttpEntity(null); + String route_service_url=getServiceUrl("ts-route-service"); ResponseEntity re = restTemplate.exchange( - "http://ts-route-service:11178/api/v1/routeservice/routes/" + routeId, + route_service_url + "/api/v1/routeservice/routes/" + routeId, HttpMethod.GET, requestEntity, Response.class); Response result = re.getBody(); if ( result.getStatus() == 0) { - BasicServiceImpl.LOGGER.warn("[Get Route By Id] Fail. {}", result.getMsg()); + BasicServiceImpl.LOGGER.warn("[getRouteByRouteId][Get Route By Id Failed][Fail msg: {}]", result.getMsg()); return null; } else { - BasicServiceImpl.LOGGER.info("[Get Route By Id] Success."); + BasicServiceImpl.LOGGER.info("[getRouteByRouteId][Get Route By Id][Success]"); return JsonUtils.conveterObject(result.getData(), Route.class); } } private PriceConfig queryPriceConfigByRouteIdAndTrainType(String routeId, String trainType, HttpHeaders headers) { - BasicServiceImpl.LOGGER.info("[Query For Price Config] RouteId: {} ,TrainType: {}", routeId, trainType); + BasicServiceImpl.LOGGER.info("[queryPriceConfigByRouteIdAndTrainType][Query For Price Config][RouteId: {} ,TrainType: {}]", routeId, trainType); HttpEntity requestEntity = new HttpEntity(null, null); + String price_service_url=getServiceUrl("ts-price-service"); ResponseEntity re = restTemplate.exchange( - "http://ts-price-service:16579/api/v1/priceservice/prices/" + routeId + "/" + trainType, + price_service_url + "/api/v1/priceservice/prices/" + routeId + "/" + trainType, HttpMethod.GET, requestEntity, Response.class); Response result = re.getBody(); - BasicServiceImpl.LOGGER.info("Response Resutl to String {}", result.toString()); + BasicServiceImpl.LOGGER.info("[queryPriceConfigByRouteIdAndTrainType][Response Resutl to String][result: {}]", result.toString()); return JsonUtils.conveterObject(result.getData(), PriceConfig.class); } + private Map queryPriceConfigByRouteIdsAndTrainTypes(List routeIdsTypes, HttpHeaders headers) { + BasicServiceImpl.LOGGER.info("[queryPriceConfigByRouteIdsAndTrainTypes][Query For Price Config][RouteId and TrainType: {}]", routeIdsTypes); + HttpEntity requestEntity = new HttpEntity(routeIdsTypes, null); + String price_service_url=getServiceUrl("ts-price-service"); + ResponseEntity re = restTemplate.exchange( + price_service_url + "/api/v1/priceservice/prices/byRouteIdsAndTrainTypes", + HttpMethod.POST, + requestEntity, + Response.class); + Response> result = re.getBody(); + + Map pcMap; + if ( result.getStatus() == 0) { + BasicServiceImpl.LOGGER.warn("[queryPriceConfigByRouteIdsAndTrainTypes][Get Price Config by routeId and trainType Failed][Fail msg: {}]", result.getMsg()); + return null; + } else { + ObjectMapper mapper = new ObjectMapper(); + try{ + pcMap = mapper.readValue(JsonUtils.object2Json(result.getData()), new TypeReference>(){}); + }catch(Exception e) { + BasicServiceImpl.LOGGER.warn("[queryPriceConfigByRouteIdsAndTrainTypes][Get Price Config by routeId and trainType Failed][Fail msg: {}]", e.getMessage()); + return null; + } + BasicServiceImpl.LOGGER.info("[queryPriceConfigByRouteIdsAndTrainTypes][Get Price Config by routeId and trainType][Success][priceConfigs: {}]", result.getData()); + return pcMap; + } + } + } diff --git a/ts-basic-service/src/main/resources/application.yml b/ts-basic-service/src/main/resources/application.yml index c70eea8ab..ec0b3dd1e 100644 --- a/ts-basic-service/src/main/resources/application.yml +++ b/ts-basic-service/src/main/resources/application.yml @@ -2,6 +2,10 @@ server: port: 15680 spring: + cloud: + nacos: + discovery: + server-addr: ${NACOS_ADDRS:nacos-0.nacos-headless.default.svc.cluster.local,nacos-1.nacos-headless.default.svc.cluster.local,nacos-2.nacos-headless.default.svc.cluster.local} application: name: ts-basic-service diff --git a/ts-basic-service/src/test/java/fdse/microservice/controller/BasicControllerTest.java b/ts-basic-service/src/test/java/fdse/microservice/controller/BasicControllerTest.java index bc7b526da..4604993f4 100644 --- a/ts-basic-service/src/test/java/fdse/microservice/controller/BasicControllerTest.java +++ b/ts-basic-service/src/test/java/fdse/microservice/controller/BasicControllerTest.java @@ -1,8 +1,8 @@ package fdse.microservice.controller; import com.alibaba.fastjson.JSONObject; +import edu.fudan.common.entity.Travel; import edu.fudan.common.util.Response; -import fdse.microservice.entity.Travel; import fdse.microservice.service.BasicService; import org.junit.Assert; import org.junit.Before; diff --git a/ts-basic-service/src/test/java/fdse/microservice/service/BasicServiceImplTest.java b/ts-basic-service/src/test/java/fdse/microservice/service/BasicServiceImplTest.java index 396a811f6..40a076a94 100644 --- a/ts-basic-service/src/test/java/fdse/microservice/service/BasicServiceImplTest.java +++ b/ts-basic-service/src/test/java/fdse/microservice/service/BasicServiceImplTest.java @@ -1,7 +1,8 @@ package fdse.microservice.service; +import edu.fudan.common.entity.*; import edu.fudan.common.util.Response; -import fdse.microservice.entity.*; +import edu.fudan.common.util.StringUtils; import org.junit.Assert; import org.junit.Before; import org.junit.Test; @@ -36,8 +37,16 @@ public void setUp() { @Test public void testQueryForTravel() { - Trip trip = new Trip(new TripId(), "", "route_id", "", "", "", new Date(), new Date()); - Travel info = new Travel(trip, "starting_place", "end_place", new Date()); + Trip trip = new Trip(); + trip.setTripId(new TripId()); + trip.setRouteId("route_id"); + trip.setStartTime(StringUtils.Date2String(new Date())); + trip.setEndTime(StringUtils.Date2String(new Date())); + Travel info = new Travel(); + info.setTrip(trip); + info.setStartPlace("starting_place"); + info.setEndPlace("end_place"); + info.setDepartureTime(StringUtils.Date2String(new Date())); Response response = new Response<>(1, null, null); ResponseEntity re = new ResponseEntity<>(response, HttpStatus.OK); //mock checkStationExists() and queryForStationId() @@ -108,11 +117,11 @@ public void testQueryTrainType() { Response response = new Response<>(1, null, null); ResponseEntity re = new ResponseEntity<>(response, HttpStatus.OK); Mockito.when(restTemplate.exchange( - "http://ts-train-service:14567/api/v1/trainservice/trains/" + "trainTypeId", + "http://ts-train-service:14567/api/v1/trainservice/trains/byName/" + "trainTypeName", HttpMethod.GET, requestEntity, Response.class)).thenReturn(re); - TrainType result = basicServiceImpl.queryTrainType("trainTypeId", headers); + TrainType result = basicServiceImpl.queryTrainTypeByName("trainTypeId", headers); Assert.assertNull(result); } diff --git a/ts-cancel-service/pom.xml b/ts-cancel-service/pom.xml index 2860d48e4..b011d3ebb 100644 --- a/ts-cancel-service/pom.xml +++ b/ts-cancel-service/pom.xml @@ -14,7 +14,7 @@ org.services ts-service 0.1.0 - ../ + ../pom.xml @@ -28,8 +28,6 @@ ts-common 0.1.0 - - diff --git a/ts-cancel-service/src/main/java/cancel/CancelApplication.java b/ts-cancel-service/src/main/java/cancel/CancelApplication.java index 7e7944dff..a053abc92 100644 --- a/ts-cancel-service/src/main/java/cancel/CancelApplication.java +++ b/ts-cancel-service/src/main/java/cancel/CancelApplication.java @@ -3,6 +3,8 @@ import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.boot.web.client.RestTemplateBuilder; +import org.springframework.cloud.client.discovery.EnableDiscoveryClient; +import org.springframework.cloud.client.loadbalancer.LoadBalanced; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.EnableAspectJAutoProxy; import org.springframework.integration.annotation.IntegrationComponentScan; @@ -18,12 +20,14 @@ @EnableAsync @IntegrationComponentScan @EnableSwagger2 +@EnableDiscoveryClient public class CancelApplication { public static void main(String[] args) { SpringApplication.run(CancelApplication.class, args); } + @LoadBalanced @Bean public RestTemplate restTemplate(RestTemplateBuilder builder) { return builder.build(); diff --git a/ts-cancel-service/src/main/java/cancel/controller/CancelController.java b/ts-cancel-service/src/main/java/cancel/controller/CancelController.java index 28fd1ef37..cd0753d39 100644 --- a/ts-cancel-service/src/main/java/cancel/controller/CancelController.java +++ b/ts-cancel-service/src/main/java/cancel/controller/CancelController.java @@ -32,7 +32,7 @@ public String home(@RequestHeader HttpHeaders headers) { @CrossOrigin(origins = "*") @GetMapping(path = "/cancel/refound/{orderId}") public HttpEntity calculate(@PathVariable String orderId, @RequestHeader HttpHeaders headers) { - CancelController.LOGGER.info("[Calculate Cancel Refund] OrderId: {}", orderId); + CancelController.LOGGER.info("[calculate][Calculate Cancel Refund][OrderId: {}]", orderId); return ok(cancelService.calculateRefund(orderId, headers)); } @@ -41,9 +41,9 @@ public HttpEntity calculate(@PathVariable String orderId, @RequestHeader HttpHea public HttpEntity cancelTicket(@PathVariable String orderId, @PathVariable String loginId, @RequestHeader HttpHeaders headers) { - CancelController.LOGGER.info("[Cancel Ticket] info: {}", orderId); + CancelController.LOGGER.info("[cancelTicket][Cancel Ticket][info: {}]", orderId); try { - CancelController.LOGGER.info("[Cancel Ticket] Verify Success"); + CancelController.LOGGER.info("[cancelTicket][Cancel Ticket, Verify Success]"); return ok(cancelService.cancelOrder(orderId, loginId, headers)); } catch (Exception e) { CancelController.LOGGER.error(e.getMessage()); diff --git a/ts-cancel-service/src/main/java/cancel/entity/Account.java b/ts-cancel-service/src/main/java/cancel/entity/Account.java deleted file mode 100644 index 29b5729e0..000000000 --- a/ts-cancel-service/src/main/java/cancel/entity/Account.java +++ /dev/null @@ -1,38 +0,0 @@ -package cancel.entity; - -import com.fasterxml.jackson.annotation.JsonIgnoreProperties; -import lombok.Data; - -import java.util.UUID; - -/** - * @author fdse - */ -@Data -@JsonIgnoreProperties(ignoreUnknown = true) -public class Account { - - private UUID id; - - private String password; - - private int gender; - - private String name; - - private int documentType; - - private String documentNum; - - private String email; - - public Account(){ - gender = Gender.OTHER.getCode(); - password = "defaultPassword"; //NOSONAR - name = "None"; - documentType = DocumentType.NONE.getCode(); - documentNum = "0123456789"; - email = "0123456789"; - } - -} diff --git a/ts-cancel-service/src/main/java/cancel/entity/DocumentType.java b/ts-cancel-service/src/main/java/cancel/entity/DocumentType.java deleted file mode 100644 index d97f088fe..000000000 --- a/ts-cancel-service/src/main/java/cancel/entity/DocumentType.java +++ /dev/null @@ -1,50 +0,0 @@ -package cancel.entity; - -/** - * @author fdse - */ -public enum DocumentType { - - /** - * null - */ - NONE (0,"Null"), - /** - * id card - */ - ID_CARD (1,"ID Card"), - /** - * passport - */ - PASSPORT (2,"Passport"), - /** - * other - */ - OTHER (3,"Other"); - - private int code; - private String name; - - DocumentType(int code, String name){ - this.code = code; - this.name = name; - } - - public int getCode(){ - return code; - } - - public String getName() { - return name; - } - - public static String getNameByCode(int code){ - DocumentType[] documentTypeSet = DocumentType.values(); - for(DocumentType documentType : documentTypeSet){ - if(documentType.getCode() == code){ - return documentType.getName(); - } - } - return documentTypeSet[0].getName(); - } -} diff --git a/ts-cancel-service/src/main/java/cancel/entity/GetAccountByIdResult.java b/ts-cancel-service/src/main/java/cancel/entity/GetAccountByIdResult.java index 8c4e996fd..cd317dc0b 100644 --- a/ts-cancel-service/src/main/java/cancel/entity/GetAccountByIdResult.java +++ b/ts-cancel-service/src/main/java/cancel/entity/GetAccountByIdResult.java @@ -1,6 +1,8 @@ package cancel.entity; +import edu.fudan.common.entity.Account; import lombok.Data; +import edu.fudan.common.entity.Account; /** * @author fdse diff --git a/ts-cancel-service/src/main/java/cancel/entity/NotifyInfo.java b/ts-cancel-service/src/main/java/cancel/entity/NotifyInfo.java deleted file mode 100644 index 42fe54036..000000000 --- a/ts-cancel-service/src/main/java/cancel/entity/NotifyInfo.java +++ /dev/null @@ -1,26 +0,0 @@ -package cancel.entity; - -import lombok.Data; - -/** - * @author fdse - */ -@Data -public class NotifyInfo { - - public NotifyInfo(){ - //Default Constructor - } - - private String email; - private String orderNumber; - private String username; - private String startingPlace; - private String endPlace; - private String startingTime; - private String date; - private String seatClass; - private String seatNumber; - private String price; - -} diff --git a/ts-cancel-service/src/main/java/cancel/entity/Order.java b/ts-cancel-service/src/main/java/cancel/entity/Order.java deleted file mode 100644 index b4e1712a9..000000000 --- a/ts-cancel-service/src/main/java/cancel/entity/Order.java +++ /dev/null @@ -1,108 +0,0 @@ -package cancel.entity; - -import com.fasterxml.jackson.annotation.JsonIgnoreProperties; -import lombok.Data; - -import java.util.Date; -import java.util.UUID; - -/** - * @author fdse - */ -@Data -@JsonIgnoreProperties(ignoreUnknown = true) -public class Order { - - private UUID id; - - private Date boughtDate; - - private Date travelDate; - - private Date travelTime; - - /** - * Which Account Bought it - */ - private UUID accountId; - - /** - * Tickets bought for whom - */ - private String contactsName; - - private int documentType; - - private String contactsDocumentNumber; - - private String trainNumber; - - private int coachNumber; - - private int seatClass; - - private String seatNumber; - - private String from; - - private String to; - - private int status; - - private String price; - - public Order(){ - boughtDate = new Date(System.currentTimeMillis()); - travelDate = new Date(123456789); - trainNumber = "G1235"; - coachNumber = 5; - seatClass = SeatClass.FIRSTCLASS.getCode(); - seatNumber = "5A"; - from = "shanghai"; - to = "taiyuan"; - status = OrderStatus.PAID.getCode(); - price = "0.0"; - } - - @Override - public boolean equals(Object obj) { - if (this == obj) { - return true; - } - if (obj == null) { - return false; - } - if (getClass() != obj.getClass()) { - return false; - } - Order other = (Order) obj; - return boughtDate.equals(other.getBoughtDate()) - && travelDate.equals(other.getTravelDate()) - && travelTime.equals(other.getTravelTime()) - && accountId .equals( other.getAccountId() ) - && contactsName.equals(other.getContactsName()) - && contactsDocumentNumber.equals(other.getContactsDocumentNumber()) - && documentType == other.getDocumentType() - && trainNumber.equals(other.getTrainNumber()) - && coachNumber == other.getCoachNumber() - && seatClass == other.getSeatClass() - && seatNumber .equals(other.getSeatNumber()) - && from.equals(other.getFrom()) - && to.equals(other.getTo()) - && status == other.getStatus() - && price.equals(other.price); - } - - @Override - public int hashCode() { - int result = 17; - result = 31 * result + (id == null ? 0 : id.hashCode()); - return result; - } - - public void setTravelDate(int year,int month,int day){ - Date date = new Date(year,month,day,0,0,0); //NOSONAR - this.travelDate = date; - } - -} diff --git a/ts-cancel-service/src/main/java/cancel/entity/OrderStatus.java b/ts-cancel-service/src/main/java/cancel/entity/OrderStatus.java deleted file mode 100644 index 6718a9ee9..000000000 --- a/ts-cancel-service/src/main/java/cancel/entity/OrderStatus.java +++ /dev/null @@ -1,63 +0,0 @@ -package cancel.entity; - -/** - * @author fdse - */ -public enum OrderStatus { - - /** - * not paid - */ - NOTPAID (0,"Not Paid"), - /** - * paid and not collected - */ - PAID (1,"Paid & Not Collected"), - /** - * collected - */ - COLLECTED (2,"Collected"), - /** - * cancel and rebook - */ - CHANGE (3,"Cancel & Rebook"), - /** - * cancel - */ - CANCEL (4,"Cancel"), - /** - * refunded - */ - REFUNDS (5,"Refunded"), - /** - * used - */ - USED (6,"Used"); - - private int code; - private String name; - - OrderStatus(int code, String name){ - this.code = code; - this.name = name; - } - - public int getCode(){ - return code; - } - - public String getName() { - return name; - } - - public static String getNameByCode(int code){ - OrderStatus[] orderStatusSet = OrderStatus.values(); - for(OrderStatus orderStatus : orderStatusSet){ - if(orderStatus.getCode() == code){ - return orderStatus.getName(); - } - } - return orderStatusSet[0].getName(); - } - -} diff --git a/ts-cancel-service/src/main/java/cancel/entity/SeatClass.java b/ts-cancel-service/src/main/java/cancel/entity/SeatClass.java deleted file mode 100644 index 6d5cbf96b..000000000 --- a/ts-cancel-service/src/main/java/cancel/entity/SeatClass.java +++ /dev/null @@ -1,70 +0,0 @@ -package cancel.entity; - -/** - * @author fdse - */ -public enum SeatClass { - - /** - * no seat - */ - NONE (0,"NoSeat"), - /** - * green seat - */ - BUSINESS (1,"GreenSeat"), - /** - * first class seat - */ - FIRSTCLASS (2,"FirstClassSeat"), - /** - * second class seat - */ - SECONDCLASS (3,"SecondClassSeat"), - /** - * hard seat - */ - HARDSEAT (4,"HardSeat"), - /** - * soft seat - */ - SOFTSEAT (5,"SoftSeat"), - /** - * hard bed - */ - HARDBED (6,"HardBed"), - /** - * soft bed - */ - SOFTBED (7,"SoftBed"), - /** - * high soft seat - */ - HIGHSOFTBED (8,"HighSoftSeat"); - - private int code; - private String name; - - SeatClass(int code, String name){ - this.code = code; - this.name = name; - } - - public int getCode(){ - return code; - } - - public String getName() { - return name; - } - - public static String getNameByCode(int code){ - SeatClass[] seatClassSet = SeatClass.values(); - for(SeatClass seatClass : seatClassSet){ - if(seatClass.getCode() == code){ - return seatClass.getName(); - } - } - return seatClassSet[0].getName(); - } -} diff --git a/ts-cancel-service/src/main/java/cancel/entity/User.java b/ts-cancel-service/src/main/java/cancel/entity/User.java deleted file mode 100644 index cda71dd47..000000000 --- a/ts-cancel-service/src/main/java/cancel/entity/User.java +++ /dev/null @@ -1,31 +0,0 @@ -package cancel.entity; - -import lombok.AllArgsConstructor; -import lombok.Builder; -import lombok.Data; -import lombok.NoArgsConstructor; - -import java.util.UUID; - -/** - * @author fdse - */ -@Data -@Builder -@AllArgsConstructor -@NoArgsConstructor -public class User { - - private UUID userId; - private String userName; - private String password; - - private int gender; - - private int documentType; - - private String documentNum; - - private String email; - -} diff --git a/ts-cancel-service/src/main/java/cancel/entity/VerifyResult.java b/ts-cancel-service/src/main/java/cancel/entity/VerifyResult.java deleted file mode 100644 index 8a74b608f..000000000 --- a/ts-cancel-service/src/main/java/cancel/entity/VerifyResult.java +++ /dev/null @@ -1,19 +0,0 @@ -package cancel.entity; - -import lombok.Data; - -/** - * @author fdse - */ -@Data -public class VerifyResult { - - private boolean status; - - private String message; - - public VerifyResult() { - //Default Constructor - } - -} diff --git a/ts-cancel-service/src/main/java/cancel/service/CancelServiceImpl.java b/ts-cancel-service/src/main/java/cancel/service/CancelServiceImpl.java index 03f6718eb..023aa6673 100644 --- a/ts-cancel-service/src/main/java/cancel/service/CancelServiceImpl.java +++ b/ts-cancel-service/src/main/java/cancel/service/CancelServiceImpl.java @@ -1,10 +1,16 @@ package cancel.service; -import cancel.entity.*; +import edu.fudan.common.entity.NotifyInfo; +import edu.fudan.common.entity.OrderStatus; +import edu.fudan.common.entity.Order; +import edu.fudan.common.entity.SeatClass; +import edu.fudan.common.entity.User; import edu.fudan.common.util.Response; +import edu.fudan.common.util.StringUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.cloud.client.discovery.DiscoveryClient; import org.springframework.core.ParameterizedTypeReference; import org.springframework.http.HttpEntity; import org.springframework.http.HttpHeaders; @@ -25,17 +31,23 @@ public class CancelServiceImpl implements CancelService { @Autowired private RestTemplate restTemplate; + @Autowired + private DiscoveryClient discoveryClient; private static final Logger LOGGER = LoggerFactory.getLogger(CancelServiceImpl.class); String orderStatusCancelNotPermitted = "Order Status Cancel Not Permitted"; + private String getServiceUrl(String serviceName) { + return "http://" + serviceName; + } + @Override public Response cancelOrder(String orderId, String loginId, HttpHeaders headers) { Response orderResult = getOrderByIdFromOrder(orderId, headers); if (orderResult.getStatus() == 1) { - CancelServiceImpl.LOGGER.info("[Cancel Order] Order found G|H"); + CancelServiceImpl.LOGGER.info("[cancelOrder][Cancel Order, Order found G|H]"); Order order = orderResult.getData(); if (order.getStatus() == OrderStatus.NOTPAID.getCode() || order.getStatus() == OrderStatus.PAID.getCode() || order.getStatus() == OrderStatus.CHANGE.getCode()) { @@ -46,12 +58,12 @@ public Response cancelOrder(String orderId, String loginId, HttpHeaders headers) // 0 -- not find order 1 - cancel success if (changeOrderResult.getStatus() == 1) { - CancelServiceImpl.LOGGER.info("[Cancel Order] Success."); + CancelServiceImpl.LOGGER.info("[cancelOrder][Cancel Order Success]"); //Draw back money String money = calculateRefund(order); boolean status = drawbackMoney(money, loginId, headers); if (status) { - CancelServiceImpl.LOGGER.info("[Draw Back Money] Success."); + CancelServiceImpl.LOGGER.info("[cancelOrder][Draw Back Money Success]"); @@ -62,78 +74,79 @@ public Response cancelOrder(String orderId, String loginId, HttpHeaders headers) NotifyInfo notifyInfo = new NotifyInfo(); notifyInfo.setDate(new Date().toString()); notifyInfo.setEmail(result.getData().getEmail()); - notifyInfo.setStartingPlace(order.getFrom()); + notifyInfo.setStartPlace(order.getFrom()); notifyInfo.setEndPlace(order.getTo()); notifyInfo.setUsername(result.getData().getUserName()); notifyInfo.setSeatNumber(order.getSeatNumber()); notifyInfo.setOrderNumber(order.getId().toString()); notifyInfo.setPrice(order.getPrice()); notifyInfo.setSeatClass(SeatClass.getNameByCode(order.getSeatClass())); - notifyInfo.setStartingTime(order.getTravelTime().toString()); + notifyInfo.setStartTime(order.getTravelTime().toString()); // TODO: change to async message serivce // sendEmail(notifyInfo, headers); } else { - CancelServiceImpl.LOGGER.error("[Draw Back Money] Fail, loginId: {}, orderId: {}", loginId, orderId); + CancelServiceImpl.LOGGER.error("[cancelOrder][Draw Back Money Failed][loginId: {}, orderId: {}]", loginId, orderId); } return new Response<>(1, "Success.", "test not null"); } else { - CancelServiceImpl.LOGGER.error("[Cancel Order] Fail, orderId: {}, Reason: {}", orderId, changeOrderResult.getMsg()); + CancelServiceImpl.LOGGER.error("[cancelOrder][Cancel Order Failed][orderId: {}, Reason: {}]", orderId, changeOrderResult.getMsg()); return new Response<>(0, changeOrderResult.getMsg(), null); } } else { - CancelServiceImpl.LOGGER.info("[Cancel Order] Order Status Not Permitted, loginId: {}, orderId: {}", loginId, orderId); + CancelServiceImpl.LOGGER.info("[cancelOrder][Cancel Order, Order Status Not Permitted][loginId: {}, orderId: {}]", loginId, orderId); return new Response<>(0, orderStatusCancelNotPermitted, null); } } else { Response orderOtherResult = getOrderByIdFromOrderOther(orderId, headers); if (orderOtherResult.getStatus() == 1) { - CancelServiceImpl.LOGGER.info("[Cancel Order] Order found Z|K|Other"); + CancelServiceImpl.LOGGER.info("[cancelOrder][Cancel Order, Order found Z|K|Other]"); Order order = orderOtherResult.getData(); if (order.getStatus() == OrderStatus.NOTPAID.getCode() || order.getStatus() == OrderStatus.PAID.getCode() || order.getStatus() == OrderStatus.CHANGE.getCode()) { - CancelServiceImpl.LOGGER.info("[Cancel Order] Order status ok"); + CancelServiceImpl.LOGGER.info("[cancelOrder][Cancel Order, Order status ok]"); // order.setStatus(OrderStatus.CANCEL.getCode()); Response changeOrderResult = cancelFromOtherOrder(order, headers); if (changeOrderResult.getStatus() == 1) { - CancelServiceImpl.LOGGER.info("[Cancel Order] Success."); + CancelServiceImpl.LOGGER.info("[cancelOrder][Cancel Order Success]"); //Draw back money String money = calculateRefund(order); boolean status = drawbackMoney(money, loginId, headers); if (status) { - CancelServiceImpl.LOGGER.info("[Draw Back Money] Success."); + CancelServiceImpl.LOGGER.info("[cancelOrder][Draw Back Money Success]"); } else { - CancelServiceImpl.LOGGER.error("[Draw Back Money] Fail, loginId: {}, orderId: {}", loginId, orderId); + CancelServiceImpl.LOGGER.error("[cancelOrder][Draw Back Money Failed][loginId: {}, orderId: {}]", loginId, orderId); } return new Response<>(1, "Success.", null); } else { - CancelServiceImpl.LOGGER.error("[Cancel Order] Fail, orderId: {}, Reason: {}", orderId, changeOrderResult.getMsg()); + CancelServiceImpl.LOGGER.error("[cancelOrder][Cancel Order Failed][orderId: {}, Reason: {}]", orderId, changeOrderResult.getMsg()); return new Response<>(0, "Fail.Reason:" + changeOrderResult.getMsg(), null); } } else { - CancelServiceImpl.LOGGER.warn("[Cancel Order] Order Status Not Permitted, loginId: {}, orderId: {}", loginId, orderId); + CancelServiceImpl.LOGGER.warn("[cancelOrder][Cancel Order, Order Status Not Permitted][loginId: {}, orderId: {}]", loginId, orderId); return new Response<>(0, orderStatusCancelNotPermitted, null); } } else { - CancelServiceImpl.LOGGER.warn("[Cancel Order] Order Not Found, loginId: {}, orderId: {}", loginId, orderId); + CancelServiceImpl.LOGGER.warn("[cancelOrder][Cancel Order, Order Not Found][loginId: {}, orderId: {}]", loginId, orderId); return new Response<>(0, "Order Not Found.", null); } } } public boolean sendEmail(NotifyInfo notifyInfo, HttpHeaders headers) { - CancelServiceImpl.LOGGER.info("[Send Email]"); + CancelServiceImpl.LOGGER.info("[sendEmail][Send Email]"); HttpHeaders newHeaders = getAuthorizationHeadersFrom(headers); HttpEntity requestEntity = new HttpEntity(notifyInfo, newHeaders); + String notification_service_url = getServiceUrl("ts-notification-service"); ResponseEntity re = restTemplate.exchange( - "http://ts-notification-service:17853/api/v1/notifyservice/notification/order_cancel_success", + notification_service_url + "/api/v1/notifyservice/notification/order_cancel_success", HttpMethod.POST, requestEntity, Boolean.class); @@ -149,14 +162,14 @@ public Response calculateRefund(String orderId, HttpHeaders headers) { if (order.getStatus() == OrderStatus.NOTPAID.getCode() || order.getStatus() == OrderStatus.PAID.getCode()) { if (order.getStatus() == OrderStatus.NOTPAID.getCode()) { - CancelServiceImpl.LOGGER.info("[Cancel Order][Refund Price] From Order Service.Not Paid."); + CancelServiceImpl.LOGGER.info("[calculateRefund][Cancel Order, Refund Price From Order Service.Not Paid][orderId: {}]", orderId); return new Response<>(1, "Success. Refoud 0", "0"); } else { - CancelServiceImpl.LOGGER.info("[Cancel Order][Refund Price] From Order Service.Paid."); + CancelServiceImpl.LOGGER.info("[calculateRefund][Cancel Order, Refund Price From Order Service.Paid][orderId: {}]", orderId); return new Response<>(1, "Success. ", calculateRefund(order)); } } else { - CancelServiceImpl.LOGGER.info("[Cancel Order][Refund Price] Order. Cancel Not Permitted."); + CancelServiceImpl.LOGGER.info("[calculateRefund][Cancel Order Refund Price Order.Cancel Not Permitted][orderId: {}]", orderId); return new Response<>(0, "Order Status Cancel Not Permitted, Refound error", null); } } else { @@ -167,18 +180,18 @@ public Response calculateRefund(String orderId, HttpHeaders headers) { if (order.getStatus() == OrderStatus.NOTPAID.getCode() || order.getStatus() == OrderStatus.PAID.getCode()) { if (order.getStatus() == OrderStatus.NOTPAID.getCode()) { - CancelServiceImpl.LOGGER.info("[Cancel Order][Refund Price] From Order Other Service.Not Paid."); + CancelServiceImpl.LOGGER.info("[calculateRefund][Cancel Order, Refund Price From Order Other Service.Not Paid][orderId: {}]", orderId); return new Response<>(1, "Success, Refound 0", "0"); } else { - CancelServiceImpl.LOGGER.info("[Cancel Order][Refund Price] From Order Other Service.Paid."); + CancelServiceImpl.LOGGER.info("[Cancel Order][Refund Price From Order Other Service.Paid][orderId: {}]", orderId); return new Response<>(1, "Success", calculateRefund(order)); } } else { - CancelServiceImpl.LOGGER.warn("[Cancel Order][Refund Price] Order Other. Cancel Not Permitted."); + CancelServiceImpl.LOGGER.warn("[Cancel Order][Refund Price, Order Other. Cancel Not Permitted][orderId: {}]", orderId); return new Response<>(0, orderStatusCancelNotPermitted, null); } } else { - CancelServiceImpl.LOGGER.error("[Cancel Order][Refund Price] Order not found."); + CancelServiceImpl.LOGGER.error("[Cancel Order][Refund Price][Order not found][orderId: {}]", orderId); return new Response<>(0, "Order Not Found", null); } } @@ -188,15 +201,15 @@ private String calculateRefund(Order order) { if (order.getStatus() == OrderStatus.NOTPAID.getCode()) { return "0.00"; } - CancelServiceImpl.LOGGER.info("[Cancel Order] Order Travel Date: {}", order.getTravelDate().toString()); + CancelServiceImpl.LOGGER.info("[calculateRefund][Cancel Order][Order Travel Date: {}]", order.getTravelDate().toString()); Date nowDate = new Date(); Calendar cal = Calendar.getInstance(); - cal.setTime(order.getTravelDate()); + cal.setTime(StringUtils.String2Date(order.getTravelDate())); int year = cal.get(Calendar.YEAR); int month = cal.get(Calendar.MONTH); int day = cal.get(Calendar.DAY_OF_MONTH); Calendar cal2 = Calendar.getInstance(); - cal2.setTime(order.getTravelTime()); + cal2.setTime(StringUtils.String2Date(order.getTravelTime())); int hour = cal2.get(Calendar.HOUR); int minute = cal2.get(Calendar.MINUTE); int second = cal2.get(Calendar.SECOND); @@ -206,30 +219,31 @@ private String calculateRefund(Order order) { hour, minute, second); - CancelServiceImpl.LOGGER.info("[Cancel Order] nowDate : {}", nowDate); - CancelServiceImpl.LOGGER.info("[Cancel Order] startTime: {}", startTime); + CancelServiceImpl.LOGGER.info("[calculateRefund][Cancel Order][nowDate : {}]", nowDate); + CancelServiceImpl.LOGGER.info("[calculateRefund][Cancel Order][startTime: {}]", startTime); if (nowDate.after(startTime)) { - CancelServiceImpl.LOGGER.warn("[Cancel Order] Ticket expire refund 0"); + CancelServiceImpl.LOGGER.warn("[calculateRefund][Cancel Order, Ticket expire refund 0]"); return "0"; } else { double totalPrice = Double.parseDouble(order.getPrice()); double price = totalPrice * 0.8; DecimalFormat priceFormat = new java.text.DecimalFormat("0.00"); String str = priceFormat.format(price); - CancelServiceImpl.LOGGER.info("[Cancel Order]calculate refund - {}", str); + CancelServiceImpl.LOGGER.info("[calculateRefund][calculate refund][refund: {}]", str); return str; } } private Response cancelFromOrder(Order order, HttpHeaders headers) { - CancelServiceImpl.LOGGER.info("[Change Order Status] Changing...."); + CancelServiceImpl.LOGGER.info("[cancelFromOrder][Change Order Status]"); order.setStatus(OrderStatus.CANCEL.getCode()); // add authorization header HttpHeaders newHeaders = getAuthorizationHeadersFrom(headers); HttpEntity requestEntity = new HttpEntity(order, newHeaders); + String order_service_url = getServiceUrl("ts-order-service"); ResponseEntity re = restTemplate.exchange( - "http://ts-order-service:12031/api/v1/orderservice/order", + order_service_url + "/api/v1/orderservice/order", HttpMethod.PUT, requestEntity, Response.class); @@ -247,12 +261,13 @@ public static HttpHeaders getAuthorizationHeadersFrom(HttpHeaders oldHeaders) { private Response cancelFromOtherOrder(Order order, HttpHeaders headers) { - CancelServiceImpl.LOGGER.info("[Change Order Status] Changing...."); + CancelServiceImpl.LOGGER.info("[cancelFromOtherOrder][Change Order Status]"); order.setStatus(OrderStatus.CANCEL.getCode()); HttpHeaders newHeaders = getAuthorizationHeadersFrom(headers); HttpEntity requestEntity = new HttpEntity(order, newHeaders); + String order_other_service_url = getServiceUrl("ts-order-other-service"); ResponseEntity re = restTemplate.exchange( - "http://ts-order-other-service:12032/api/v1/orderOtherService/orderOther", + order_other_service_url + "/api/v1/orderOtherService/orderOther", HttpMethod.PUT, requestEntity, Response.class); @@ -261,12 +276,13 @@ private Response cancelFromOtherOrder(Order order, HttpHeaders headers) { } public boolean drawbackMoney(String money, String userId, HttpHeaders headers) { - CancelServiceImpl.LOGGER.info("[Draw Back Money] Draw back money..."); + CancelServiceImpl.LOGGER.info("[drawbackMoney][Draw Back Money]"); HttpHeaders newHeaders = getAuthorizationHeadersFrom(headers); HttpEntity requestEntity = new HttpEntity(newHeaders); + String inside_payment_service_url = getServiceUrl("ts-inside-payment-service"); ResponseEntity re = restTemplate.exchange( - "http://ts-inside-payment-service:18673/api/v1/inside_pay_service/inside_payment/drawback/" + userId + "/" + money, + inside_payment_service_url + "/api/v1/inside_pay_service/inside_payment/drawback/" + userId + "/" + money, HttpMethod.GET, requestEntity, Response.class); @@ -276,11 +292,12 @@ public boolean drawbackMoney(String money, String userId, HttpHeaders headers) { } public Response getAccount(String orderId, HttpHeaders headers) { - CancelServiceImpl.LOGGER.info("[Get By Id]"); + CancelServiceImpl.LOGGER.info("[getAccount][Get By Id][orderId: {}]", orderId); HttpHeaders newHeaders = getAuthorizationHeadersFrom(headers); HttpEntity requestEntity = new HttpEntity(newHeaders); + String user_service_url = getServiceUrl("ts-user-service"); ResponseEntity> re = restTemplate.exchange( - "http://ts-user-service:12342/api/v1/userservice/users/id/" + orderId, + user_service_url + "/api/v1/userservice/users/id/" + orderId, HttpMethod.GET, requestEntity, new ParameterizedTypeReference>() { @@ -289,11 +306,12 @@ public Response getAccount(String orderId, HttpHeaders headers) { } private Response getOrderByIdFromOrder(String orderId, HttpHeaders headers) { - CancelServiceImpl.LOGGER.info("[Get Order] Getting...."); + CancelServiceImpl.LOGGER.info("[getOrderByIdFromOrder][Get Order][orderId: {}]", orderId); HttpHeaders newHeaders = getAuthorizationHeadersFrom(headers); HttpEntity requestEntity = new HttpEntity(newHeaders); + String order_service_url = getServiceUrl("ts-order-service"); ResponseEntity> re = restTemplate.exchange( - "http://ts-order-service:12031/api/v1/orderservice/order/" + orderId, + order_service_url + "/api/v1/orderservice/order/" + orderId, HttpMethod.GET, requestEntity, new ParameterizedTypeReference>() { @@ -302,11 +320,12 @@ private Response getOrderByIdFromOrder(String orderId, HttpHeaders header } private Response getOrderByIdFromOrderOther(String orderId, HttpHeaders headers) { - CancelServiceImpl.LOGGER.info("[Get Order] Getting...."); + CancelServiceImpl.LOGGER.info("[getOrderByIdFromOrderOther][Get Order][orderId: {}]", orderId); HttpHeaders newHeaders = getAuthorizationHeadersFrom(headers); HttpEntity requestEntity = new HttpEntity(newHeaders); + String order_other_service_url = getServiceUrl("ts-order-other-service"); ResponseEntity> re = restTemplate.exchange( - "http://ts-order-other-service:12032/api/v1/orderOtherService/orderOther/" + orderId, + order_other_service_url + "/api/v1/orderOtherService/orderOther/" + orderId, HttpMethod.GET, requestEntity, new ParameterizedTypeReference>() { diff --git a/ts-cancel-service/src/main/resources/application.yml b/ts-cancel-service/src/main/resources/application.yml index ca9cfc28c..adbcb47cb 100644 --- a/ts-cancel-service/src/main/resources/application.yml +++ b/ts-cancel-service/src/main/resources/application.yml @@ -2,8 +2,12 @@ server: port: 18885 # HTTP (Tomcat) port spring: + cloud: + nacos: + discovery: + server-addr: ${NACOS_ADDRS:nacos-0.nacos-headless.default.svc.cluster.local,nacos-1.nacos-headless.default.svc.cluster.local,nacos-2.nacos-headless.default.svc.cluster.local} application: name: ts-cancel-service swagger: - controllerPackage: cancel.controller \ No newline at end of file + controllerPackage: cancel.controller diff --git a/ts-cancel-service/src/test/java/cancel/service/CancelServiceImplTest.java b/ts-cancel-service/src/test/java/cancel/service/CancelServiceImplTest.java index c6b5f49a8..97f1af73d 100644 --- a/ts-cancel-service/src/test/java/cancel/service/CancelServiceImplTest.java +++ b/ts-cancel-service/src/test/java/cancel/service/CancelServiceImplTest.java @@ -1,8 +1,8 @@ package cancel.service; -import cancel.entity.NotifyInfo; -import cancel.entity.Order; -import cancel.entity.User; +import edu.fudan.common.entity.NotifyInfo; +import edu.fudan.common.entity.Order; +import edu.fudan.common.entity.User; import edu.fudan.common.util.Response; import org.junit.Assert; import org.junit.Before; diff --git a/ts-common/pom.xml b/ts-common/pom.xml index 0eaf13e07..ada2e02ac 100644 --- a/ts-common/pom.xml +++ b/ts-common/pom.xml @@ -21,6 +21,14 @@ org.springframework.boot spring-boot-starter-security + + jakarta.validation + jakarta.validation-api + + + javax.persistence + javax.persistence-api + diff --git a/ts-common/src/main/java/edu/fudan/common/config/SwaggerConfig.java b/ts-common/src/main/java/edu/fudan/common/config/SwaggerConfig.java index 993c47cc8..34ab9017b 100644 --- a/ts-common/src/main/java/edu/fudan/common/config/SwaggerConfig.java +++ b/ts-common/src/main/java/edu/fudan/common/config/SwaggerConfig.java @@ -25,7 +25,7 @@ public class SwaggerConfig { @Bean public Docket createRestApi() { - SwaggerConfig.LOGGER.info("====-- {}", controllerPackagePath); + SwaggerConfig.LOGGER.info("[createRestApi][create][controllerPackagePath: {}]", controllerPackagePath); return new Docket(DocumentationType.SWAGGER_2) .apiInfo(apiInfo()) .select().apis(RequestHandlerSelectors.basePackage(controllerPackagePath)) diff --git a/ts-admin-user-service/src/main/java/adminuser/entity/Account.java b/ts-common/src/main/java/edu/fudan/common/entity/Account.java similarity index 95% rename from ts-admin-user-service/src/main/java/adminuser/entity/Account.java rename to ts-common/src/main/java/edu/fudan/common/entity/Account.java index 5700aeeea..f95c04088 100644 --- a/ts-admin-user-service/src/main/java/adminuser/entity/Account.java +++ b/ts-common/src/main/java/edu/fudan/common/entity/Account.java @@ -1,4 +1,4 @@ -package adminuser.entity; +package edu.fudan.common.entity; import lombok.Data; import lombok.NoArgsConstructor; diff --git a/ts-admin-travel-service/src/main/java/admintravel/entity/AdminTrip.java b/ts-common/src/main/java/edu/fudan/common/entity/AdminTrip.java similarity index 62% rename from ts-admin-travel-service/src/main/java/admintravel/entity/AdminTrip.java rename to ts-common/src/main/java/edu/fudan/common/entity/AdminTrip.java index 77aea3ec3..dfa1442e5 100644 --- a/ts-admin-travel-service/src/main/java/admintravel/entity/AdminTrip.java +++ b/ts-common/src/main/java/edu/fudan/common/entity/AdminTrip.java @@ -1,15 +1,18 @@ -package admintravel.entity; +package edu.fudan.common.entity; import lombok.Data; -import lombok.NoArgsConstructor; /** * @author fdse */ @Data -@NoArgsConstructor public class AdminTrip { private Trip trip; private TrainType trainType; private Route route; + + public AdminTrip(){ + //Default Constructor + } + } diff --git a/ts-preserve-other-service/src/main/java/preserveOther/entity/Assurance.java b/ts-common/src/main/java/edu/fudan/common/entity/Assurance.java similarity index 95% rename from ts-preserve-other-service/src/main/java/preserveOther/entity/Assurance.java rename to ts-common/src/main/java/edu/fudan/common/entity/Assurance.java index a5dce98d6..ca2db5cdf 100644 --- a/ts-preserve-other-service/src/main/java/preserveOther/entity/Assurance.java +++ b/ts-common/src/main/java/edu/fudan/common/entity/Assurance.java @@ -1,4 +1,4 @@ -package preserveOther.entity; +package edu.fudan.common.entity; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import lombok.Data; diff --git a/ts-preserve-other-service/src/main/java/preserveOther/entity/AssuranceType.java b/ts-common/src/main/java/edu/fudan/common/entity/AssuranceType.java similarity index 97% rename from ts-preserve-other-service/src/main/java/preserveOther/entity/AssuranceType.java rename to ts-common/src/main/java/edu/fudan/common/entity/AssuranceType.java index 0299d7c92..7fef015eb 100644 --- a/ts-preserve-other-service/src/main/java/preserveOther/entity/AssuranceType.java +++ b/ts-common/src/main/java/edu/fudan/common/entity/AssuranceType.java @@ -1,4 +1,4 @@ -package preserveOther.entity; +package edu.fudan.common.entity; import java.io.Serializable; diff --git a/ts-admin-basic-info-service/src/main/java/adminbasic/entity/Config.java b/ts-common/src/main/java/edu/fudan/common/entity/Config.java similarity index 89% rename from ts-admin-basic-info-service/src/main/java/adminbasic/entity/Config.java rename to ts-common/src/main/java/edu/fudan/common/entity/Config.java index 92e6398d0..e9f97f518 100644 --- a/ts-admin-basic-info-service/src/main/java/adminbasic/entity/Config.java +++ b/ts-common/src/main/java/edu/fudan/common/entity/Config.java @@ -1,4 +1,4 @@ -package adminbasic.entity; +package edu.fudan.common.entity; import lombok.AllArgsConstructor; import lombok.Data; diff --git a/ts-preserve-service/src/main/java/preserve/entity/Consign.java b/ts-common/src/main/java/edu/fudan/common/entity/Consign.java similarity index 63% rename from ts-preserve-service/src/main/java/preserve/entity/Consign.java rename to ts-common/src/main/java/edu/fudan/common/entity/Consign.java index cd3c060d4..abde906ea 100644 --- a/ts-preserve-service/src/main/java/preserve/entity/Consign.java +++ b/ts-common/src/main/java/edu/fudan/common/entity/Consign.java @@ -1,4 +1,4 @@ -package preserve.entity; +package edu.fudan.common.entity; import lombok.AllArgsConstructor; import lombok.Data; @@ -6,17 +6,14 @@ import java.util.UUID; -/** - * @author fdse - */ @Data @AllArgsConstructor @NoArgsConstructor public class Consign { + private String id; //id主键改成String类型的 自定义生成策略 + private String orderId; //这次托运关联订单 + private String accountId; //这次托运关联的账户 - private UUID id; - private UUID orderId; - private UUID accountId; private String handleDate; private String targetDate; private String from; @@ -25,6 +22,4 @@ public class Consign { private String phone; private double weight; private boolean isWithin; - - } diff --git a/ts-basic-service/src/main/java/fdse/microservice/entity/Contacts.java b/ts-common/src/main/java/edu/fudan/common/entity/Contacts.java similarity index 97% rename from ts-basic-service/src/main/java/fdse/microservice/entity/Contacts.java rename to ts-common/src/main/java/edu/fudan/common/entity/Contacts.java index 2a8d59659..eb261bce0 100644 --- a/ts-basic-service/src/main/java/fdse/microservice/entity/Contacts.java +++ b/ts-common/src/main/java/edu/fudan/common/entity/Contacts.java @@ -1,4 +1,4 @@ -package fdse.microservice.entity; +package edu.fudan.common.entity; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import lombok.AllArgsConstructor; @@ -11,9 +11,9 @@ * @author fdse */ @Data +@JsonIgnoreProperties(ignoreUnknown = true) @NoArgsConstructor @AllArgsConstructor -@JsonIgnoreProperties(ignoreUnknown = true) public class Contacts { private UUID id; diff --git a/ts-preserve-other-service/src/main/java/preserveOther/entity/DocumentType.java b/ts-common/src/main/java/edu/fudan/common/entity/DocumentType.java similarity index 96% rename from ts-preserve-other-service/src/main/java/preserveOther/entity/DocumentType.java rename to ts-common/src/main/java/edu/fudan/common/entity/DocumentType.java index c1f21c2ac..5f43f45e3 100644 --- a/ts-preserve-other-service/src/main/java/preserveOther/entity/DocumentType.java +++ b/ts-common/src/main/java/edu/fudan/common/entity/DocumentType.java @@ -1,4 +1,4 @@ -package preserveOther.entity; +package edu.fudan.common.entity; /** * @author fdse diff --git a/ts-food-map-service/src/main/java/food/entity/Food.java b/ts-common/src/main/java/edu/fudan/common/entity/Food.java similarity index 72% rename from ts-food-map-service/src/main/java/food/entity/Food.java rename to ts-common/src/main/java/edu/fudan/common/entity/Food.java index ad2873bdb..3882994e0 100644 --- a/ts-food-map-service/src/main/java/food/entity/Food.java +++ b/ts-common/src/main/java/edu/fudan/common/entity/Food.java @@ -1,11 +1,13 @@ -package food.entity; +package edu.fudan.common.entity; import lombok.Data; +import javax.persistence.Embeddable; import java.io.Serializable; @Data +@Embeddable public class Food implements Serializable{ private String foodName; diff --git a/ts-preserve-service/src/main/java/preserve/entity/FoodOrder.java b/ts-common/src/main/java/edu/fudan/common/entity/FoodOrder.java similarity index 81% rename from ts-preserve-service/src/main/java/preserve/entity/FoodOrder.java rename to ts-common/src/main/java/edu/fudan/common/entity/FoodOrder.java index 302ffcc78..b888084a8 100644 --- a/ts-preserve-service/src/main/java/preserve/entity/FoodOrder.java +++ b/ts-common/src/main/java/edu/fudan/common/entity/FoodOrder.java @@ -1,4 +1,4 @@ -package preserve.entity; +package edu.fudan.common.entity; import lombok.Data; @@ -10,9 +10,9 @@ @Data public class FoodOrder { - private UUID id; + private String id; - private UUID orderId; + private String orderId; /** * 1:train food;2:food store diff --git a/ts-cancel-service/src/main/java/cancel/entity/Gender.java b/ts-common/src/main/java/edu/fudan/common/entity/Gender.java similarity index 96% rename from ts-cancel-service/src/main/java/cancel/entity/Gender.java rename to ts-common/src/main/java/edu/fudan/common/entity/Gender.java index 9d4c58446..caf2ff8b7 100644 --- a/ts-cancel-service/src/main/java/cancel/entity/Gender.java +++ b/ts-common/src/main/java/edu/fudan/common/entity/Gender.java @@ -1,4 +1,4 @@ -package cancel.entity; +package edu.fudan.common.entity; /** * @author fdse diff --git a/ts-order-service/src/main/java/order/entity/LeftTicketInfo.java b/ts-common/src/main/java/edu/fudan/common/entity/LeftTicketInfo.java similarity index 93% rename from ts-order-service/src/main/java/order/entity/LeftTicketInfo.java rename to ts-common/src/main/java/edu/fudan/common/entity/LeftTicketInfo.java index 44a6dcc04..f9bcd31da 100644 --- a/ts-order-service/src/main/java/order/entity/LeftTicketInfo.java +++ b/ts-common/src/main/java/edu/fudan/common/entity/LeftTicketInfo.java @@ -1,4 +1,4 @@ -package order.entity; +package edu.fudan.common.entity; import lombok.Data; diff --git a/ts-preserve-service/src/main/java/preserve/entity/NotifyInfo.java b/ts-common/src/main/java/edu/fudan/common/entity/NotifyInfo.java similarity index 79% rename from ts-preserve-service/src/main/java/preserve/entity/NotifyInfo.java rename to ts-common/src/main/java/edu/fudan/common/entity/NotifyInfo.java index 0d8796fca..0be9a4c81 100644 --- a/ts-preserve-service/src/main/java/preserve/entity/NotifyInfo.java +++ b/ts-common/src/main/java/edu/fudan/common/entity/NotifyInfo.java @@ -1,4 +1,4 @@ -package preserve.entity; +package edu.fudan.common.entity; import lombok.Data; @@ -15,9 +15,9 @@ public NotifyInfo(){ private String email; private String orderNumber; private String username; - private String startingPlace; + private String startPlace; private String endPlace; - private String startingTime; + private String startTime; private String date; private String seatClass; private String seatNumber; diff --git a/ts-rebook-service/src/main/java/rebook/entity/Order.java b/ts-common/src/main/java/edu/fudan/common/entity/Order.java similarity index 74% rename from ts-rebook-service/src/main/java/rebook/entity/Order.java rename to ts-common/src/main/java/edu/fudan/common/entity/Order.java index 48c5d7533..cf8f1285f 100644 --- a/ts-rebook-service/src/main/java/rebook/entity/Order.java +++ b/ts-common/src/main/java/edu/fudan/common/entity/Order.java @@ -1,7 +1,11 @@ -package rebook.entity; +package edu.fudan.common.entity; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import edu.fudan.common.entity.SeatClass; +import edu.fudan.common.util.StringUtils; +import lombok.AllArgsConstructor; import lombok.Data; +import lombok.NoArgsConstructor; import java.util.Date; import java.util.UUID; @@ -11,20 +15,21 @@ */ @Data @JsonIgnoreProperties(ignoreUnknown = true) +@AllArgsConstructor public class Order { - private UUID id; + private String id; - private Date boughtDate; + private String boughtDate; - private Date travelDate; + private String travelDate; - private Date travelTime; + private String travelTime; /** * Which Account Bought it */ - private UUID accountId; + private String accountId; /** * Tickets bought for whom.... @@ -54,8 +59,8 @@ public class Order { private String differenceMoney; public Order(){ - boughtDate = new Date(System.currentTimeMillis()); - travelDate = new Date(123456789); + boughtDate = StringUtils.Date2String(new Date(System.currentTimeMillis())); + travelDate = StringUtils.Date2String(new Date(123456789)); trainNumber = "G1235"; coachNumber = 5; seatClass = SeatClass.FIRSTCLASS.getCode(); @@ -67,7 +72,6 @@ public Order(){ differenceMoney ="0.0"; } - @Override public boolean equals(Object obj) { if (this == obj) { return true; @@ -79,9 +83,9 @@ public boolean equals(Object obj) { return false; } Order other = (Order) obj; - return boughtDate.equals(other.getBoughtDate()) - && travelDate.equals(other.getTravelDate()) - && travelTime.equals(other.getTravelTime()) + return getBoughtDate().equals(other.getBoughtDate()) + && getBoughtDate().equals(other.getTravelDate()) + && getTravelTime().equals(other.getTravelTime()) && accountId .equals( other.getAccountId() ) && contactsName.equals(other.getContactsName()) && contactsDocumentNumber.equals(other.getContactsDocumentNumber()) @@ -93,7 +97,7 @@ public boolean equals(Object obj) { && from.equals(other.getFrom()) && to.equals(other.getTo()) && status == other.getStatus() - && price == other.price; + && price.equals(other.price); } @Override @@ -103,9 +107,4 @@ public int hashCode() { return result; } - public void setTravelDate(int year,int month,int day){ - Date date = new Date(year,month,day,0,0,0); //NOSONAR - this.travelDate = date; - } - } diff --git a/ts-common/src/main/java/edu/fudan/common/entity/OrderAlterInfo.java b/ts-common/src/main/java/edu/fudan/common/entity/OrderAlterInfo.java new file mode 100644 index 000000000..812c87f7f --- /dev/null +++ b/ts-common/src/main/java/edu/fudan/common/entity/OrderAlterInfo.java @@ -0,0 +1,24 @@ +package edu.fudan.common.entity; + +import lombok.AllArgsConstructor; +import lombok.Data; + + +/** + * @author fdse + */ +@Data +@AllArgsConstructor +public class OrderAlterInfo { + private String accountId; + + private String previousOrderId; + + private String loginToken; + + private Order newOrderInfo; + + public OrderAlterInfo(){ + newOrderInfo = new Order(); + } +} diff --git a/ts-security-service/src/main/java/security/entity/OrderSecurity.java b/ts-common/src/main/java/edu/fudan/common/entity/OrderSecurity.java similarity index 89% rename from ts-security-service/src/main/java/security/entity/OrderSecurity.java rename to ts-common/src/main/java/edu/fudan/common/entity/OrderSecurity.java index d1b515110..773acbe1d 100644 --- a/ts-security-service/src/main/java/security/entity/OrderSecurity.java +++ b/ts-common/src/main/java/edu/fudan/common/entity/OrderSecurity.java @@ -1,4 +1,4 @@ -package security.entity; +package edu.fudan.common.entity; import lombok.AllArgsConstructor; import lombok.Data; diff --git a/ts-execute-service/src/main/java/execute/entity/OrderStatus.java b/ts-common/src/main/java/edu/fudan/common/entity/OrderStatus.java similarity index 97% rename from ts-execute-service/src/main/java/execute/entity/OrderStatus.java rename to ts-common/src/main/java/edu/fudan/common/entity/OrderStatus.java index 840a52ee4..6c8daadfa 100644 --- a/ts-execute-service/src/main/java/execute/entity/OrderStatus.java +++ b/ts-common/src/main/java/edu/fudan/common/entity/OrderStatus.java @@ -1,4 +1,4 @@ -package execute.entity; +package edu.fudan.common.entity; /** * @author fdse diff --git a/ts-preserve-other-service/src/main/java/preserveOther/entity/OrderTicketsInfo.java b/ts-common/src/main/java/edu/fudan/common/entity/OrderTicketsInfo.java similarity index 67% rename from ts-preserve-other-service/src/main/java/preserveOther/entity/OrderTicketsInfo.java rename to ts-common/src/main/java/edu/fudan/common/entity/OrderTicketsInfo.java index 11226dcbb..6a680e63c 100644 --- a/ts-preserve-other-service/src/main/java/preserveOther/entity/OrderTicketsInfo.java +++ b/ts-common/src/main/java/edu/fudan/common/entity/OrderTicketsInfo.java @@ -1,8 +1,10 @@ -package preserveOther.entity; +package edu.fudan.common.entity; +import edu.fudan.common.util.StringUtils; import lombok.AllArgsConstructor; import lombok.Builder; import lombok.Data; +import lombok.NoArgsConstructor; import java.util.Date; @@ -10,26 +12,26 @@ * @author fdse */ @Data -@AllArgsConstructor @Builder +@NoArgsConstructor +@AllArgsConstructor public class OrderTicketsInfo { private String accountId; - private String contactsId; private String tripId; private int seatType; - private Date date; + private String loginToken; + + private String date; private String from; private String to; - private int assurance; - private int foodType = 0; private String stationName; @@ -51,9 +53,12 @@ public class OrderTicketsInfo { private boolean isWithin; + public String getFrom() { + return StringUtils.String2Lower(this.from); + } - public OrderTicketsInfo(){ - //Default Constructor + public String getTo() { + return StringUtils.String2Lower(this.to); } } diff --git a/ts-rebook-service/src/main/java/rebook/entity/PaymentDifferenceInfo.java b/ts-common/src/main/java/edu/fudan/common/entity/PaymentDifferenceInfo.java similarity index 89% rename from ts-rebook-service/src/main/java/rebook/entity/PaymentDifferenceInfo.java rename to ts-common/src/main/java/edu/fudan/common/entity/PaymentDifferenceInfo.java index 238f82dce..f09e0688f 100644 --- a/ts-rebook-service/src/main/java/rebook/entity/PaymentDifferenceInfo.java +++ b/ts-common/src/main/java/edu/fudan/common/entity/PaymentDifferenceInfo.java @@ -1,4 +1,4 @@ -package rebook.entity; +package edu.fudan.common.entity; import lombok.Data; diff --git a/ts-basic-service/src/main/java/fdse/microservice/entity/PriceConfig.java b/ts-common/src/main/java/edu/fudan/common/entity/PriceConfig.java similarity index 92% rename from ts-basic-service/src/main/java/fdse/microservice/entity/PriceConfig.java rename to ts-common/src/main/java/edu/fudan/common/entity/PriceConfig.java index 005ddbb55..7113eb09b 100644 --- a/ts-basic-service/src/main/java/fdse/microservice/entity/PriceConfig.java +++ b/ts-common/src/main/java/edu/fudan/common/entity/PriceConfig.java @@ -1,4 +1,4 @@ -package fdse.microservice.entity; +package edu.fudan.common.entity; import lombok.AllArgsConstructor; import lombok.Data; diff --git a/ts-common/src/main/java/edu/fudan/common/entity/Route.java b/ts-common/src/main/java/edu/fudan/common/entity/Route.java new file mode 100644 index 000000000..64c933a3b --- /dev/null +++ b/ts-common/src/main/java/edu/fudan/common/entity/Route.java @@ -0,0 +1,45 @@ +package edu.fudan.common.entity; + +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import lombok.Data; +import lombok.NoArgsConstructor; + +import java.util.List; +import java.util.UUID; + +/** + * @author fdse + */ +@Data +@JsonIgnoreProperties(ignoreUnknown = true) +public class Route { + private String id; + + private List stations; + + private List distances; + + private String startStation; + + private String endStation; + + public Route(){ + this.id = UUID.randomUUID().toString(); + } + + public Route(String id, List stations, List distances, String startStationName, String terminalStationName) { + this.id = id; + this.stations = stations; + this.distances = distances; + this.startStation = startStationName; + this.endStation = terminalStationName; + } + + public Route(List stations, List distances, String startStationName, String terminalStationName) { + this.id = UUID.randomUUID().toString(); + this.stations = stations; + this.distances = distances; + this.startStation = startStationName; + this.endStation = terminalStationName; + } +} \ No newline at end of file diff --git a/ts-common/src/main/java/edu/fudan/common/entity/RouteInfo.java b/ts-common/src/main/java/edu/fudan/common/entity/RouteInfo.java new file mode 100644 index 000000000..51ea70d93 --- /dev/null +++ b/ts-common/src/main/java/edu/fudan/common/entity/RouteInfo.java @@ -0,0 +1,39 @@ +package edu.fudan.common.entity; + +import edu.fudan.common.util.Response; +import lombok.Data; +import lombok.NoArgsConstructor; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; + +/** + * @author fdse + */ +@Data +@NoArgsConstructor +public class RouteInfo { + private String loginId; + + private String startStation; + + private String endStation; + + private String stationList; + + private String distanceList; + + private String id; + + public List getStations(){ + String[] stations = stationList.split(","); + return Arrays.asList(stations); + } + + public List getDistances(){ + String[] distances = distanceList.split(","); + return Arrays.asList(distances); + } + +} diff --git a/ts-common/src/main/java/edu/fudan/common/entity/RoutePlanInfo.java b/ts-common/src/main/java/edu/fudan/common/entity/RoutePlanInfo.java new file mode 100644 index 000000000..c085d8a51 --- /dev/null +++ b/ts-common/src/main/java/edu/fudan/common/entity/RoutePlanInfo.java @@ -0,0 +1,35 @@ +package edu.fudan.common.entity; + +import edu.fudan.common.util.StringUtils; +import lombok.AllArgsConstructor; +import lombok.Data; + +import java.util.Date; + +/** + * @author fdse + */ +@Data +@AllArgsConstructor +public class RoutePlanInfo { + + private String startStation; + + private String endStation; + + private String travelDate; + + private int num; + + public RoutePlanInfo() { + //Empty Constructor + } + + public String getStartStation() { + return StringUtils.String2Lower(this.startStation); + } + + public String getEndStation() { + return StringUtils.String2Lower(this.endStation); + } +} diff --git a/ts-common/src/main/java/edu/fudan/common/entity/RoutePlanResultUnit.java b/ts-common/src/main/java/edu/fudan/common/entity/RoutePlanResultUnit.java new file mode 100644 index 000000000..e10865084 --- /dev/null +++ b/ts-common/src/main/java/edu/fudan/common/entity/RoutePlanResultUnit.java @@ -0,0 +1,38 @@ +package edu.fudan.common.entity; + +import edu.fudan.common.util.StringUtils; +import lombok.AllArgsConstructor; +import lombok.Data; +import lombok.NoArgsConstructor; + +import java.util.List; +import java.util.Date; + +/** + * @author fdse + */ +@Data +@NoArgsConstructor +@AllArgsConstructor +public class RoutePlanResultUnit { + + private String tripId; + + private String trainTypeName; + + private String startStation; + + private String endStation; + + private List stopStations; + + private String priceForSecondClassSeat; + + private String priceForFirstClassSeat; + + private String startTime; + + private String endTime; + + +} diff --git a/ts-rebook-service/src/main/java/rebook/entity/Seat.java b/ts-common/src/main/java/edu/fudan/common/entity/Seat.java similarity index 69% rename from ts-rebook-service/src/main/java/rebook/entity/Seat.java rename to ts-common/src/main/java/edu/fudan/common/entity/Seat.java index 50a1f4911..abcc552b6 100644 --- a/ts-rebook-service/src/main/java/rebook/entity/Seat.java +++ b/ts-common/src/main/java/edu/fudan/common/entity/Seat.java @@ -1,11 +1,13 @@ -package rebook.entity; +package edu.fudan.common.entity; +import edu.fudan.common.util.StringUtils; import lombok.AllArgsConstructor; import lombok.Data; import javax.validation.Valid; import javax.validation.constraints.NotNull; import java.util.Date; +import java.util.List; /** * @author fdse @@ -15,7 +17,7 @@ public class Seat { @Valid @NotNull - private Date travelDate; + private String travelDate; @Valid @NotNull @@ -34,12 +36,20 @@ public class Seat { @NotNull private int seatType; + private int totalNum; + + private List stations; + public Seat(){ //Default Constructor - this.travelDate = new Date(); + this.travelDate = ""; this.trainNumber = ""; this.startStation = ""; this.destStation = ""; this.seatType = 0; + this.totalNum = 0; + this.stations = null; } + + } diff --git a/ts-execute-service/src/main/java/execute/entity/SeatClass.java b/ts-common/src/main/java/edu/fudan/common/entity/SeatClass.java similarity index 97% rename from ts-execute-service/src/main/java/execute/entity/SeatClass.java rename to ts-common/src/main/java/edu/fudan/common/entity/SeatClass.java index 79bc72d9f..513735e96 100644 --- a/ts-execute-service/src/main/java/execute/entity/SeatClass.java +++ b/ts-common/src/main/java/edu/fudan/common/entity/SeatClass.java @@ -1,4 +1,4 @@ -package execute.entity; +package edu.fudan.common.entity; /** * @author fdse diff --git a/ts-travel-service/src/main/java/travel/entity/SoldTicket.java b/ts-common/src/main/java/edu/fudan/common/entity/SoldTicket.java similarity index 95% rename from ts-travel-service/src/main/java/travel/entity/SoldTicket.java rename to ts-common/src/main/java/edu/fudan/common/entity/SoldTicket.java index e3e230975..dd8f0330f 100644 --- a/ts-travel-service/src/main/java/travel/entity/SoldTicket.java +++ b/ts-common/src/main/java/edu/fudan/common/entity/SoldTicket.java @@ -1,4 +1,4 @@ -package travel.entity; +package edu.fudan.common.entity; import lombok.Data; diff --git a/ts-common/src/main/java/edu/fudan/common/entity/Station.java b/ts-common/src/main/java/edu/fudan/common/entity/Station.java new file mode 100644 index 000000000..8cec10ac7 --- /dev/null +++ b/ts-common/src/main/java/edu/fudan/common/entity/Station.java @@ -0,0 +1,33 @@ +package edu.fudan.common.entity; + +import lombok.Data; + +import java.util.Locale; + +@Data +public class Station { + private String id; + + private String name; + + private int stayTime; + + public Station(){ + this.name = ""; + } + + public void setName(String name) { + this.name = name.replace(" ", "").toLowerCase(Locale.ROOT); + } + + public Station(String name) { + this.name = name.replace(" ", "").toLowerCase(Locale.ROOT); + } + + + public Station(String name, int stayTime) { + this.name = name.replace(" ", "").toLowerCase(Locale.ROOT);; + this.stayTime = stayTime; + } +} + diff --git a/ts-food-service/src/main/java/foodsearch/entity/FoodStore.java b/ts-common/src/main/java/edu/fudan/common/entity/StationFoodStore.java similarity index 68% rename from ts-food-service/src/main/java/foodsearch/entity/FoodStore.java rename to ts-common/src/main/java/edu/fudan/common/entity/StationFoodStore.java index 717615a09..991718754 100644 --- a/ts-food-service/src/main/java/foodsearch/entity/FoodStore.java +++ b/ts-common/src/main/java/edu/fudan/common/entity/StationFoodStore.java @@ -1,4 +1,4 @@ -package foodsearch.entity; +package edu.fudan.common.entity; import lombok.Data; @@ -7,11 +7,11 @@ import java.util.UUID; @Data -public class FoodStore implements Serializable{ +public class StationFoodStore implements Serializable{ private UUID id; - private String stationId; + private String stationName; private String storeName; @@ -23,7 +23,7 @@ public class FoodStore implements Serializable{ private List foodList; - public FoodStore(){ + public StationFoodStore(){ //Default Constructor } diff --git a/ts-order-service/src/main/java/order/entity/Ticket.java b/ts-common/src/main/java/edu/fudan/common/entity/Ticket.java similarity index 86% rename from ts-order-service/src/main/java/order/entity/Ticket.java rename to ts-common/src/main/java/edu/fudan/common/entity/Ticket.java index df044b2b1..343a8e006 100644 --- a/ts-order-service/src/main/java/order/entity/Ticket.java +++ b/ts-common/src/main/java/edu/fudan/common/entity/Ticket.java @@ -1,4 +1,4 @@ -package order.entity; +package edu.fudan.common.entity; import lombok.Data; @@ -15,7 +15,7 @@ public class Ticket { private String destStation; public Ticket(){ - + //Default Constructor } public Ticket(int seatNo, String startStation, String destStation) { @@ -23,5 +23,4 @@ public Ticket(int seatNo, String startStation, String destStation) { this.startStation = startStation; this.destStation = destStation; } - } diff --git a/ts-food-service/src/main/java/foodsearch/entity/TrainFood.java b/ts-common/src/main/java/edu/fudan/common/entity/TrainFood.java similarity index 90% rename from ts-food-service/src/main/java/foodsearch/entity/TrainFood.java rename to ts-common/src/main/java/edu/fudan/common/entity/TrainFood.java index 9dca31ae8..f42a637db 100644 --- a/ts-food-service/src/main/java/foodsearch/entity/TrainFood.java +++ b/ts-common/src/main/java/edu/fudan/common/entity/TrainFood.java @@ -1,4 +1,4 @@ -package foodsearch.entity; +package edu.fudan.common.entity; import lombok.Data; diff --git a/ts-price-service/src/main/java/price/entity/TrainType.java b/ts-common/src/main/java/edu/fudan/common/entity/TrainType.java similarity index 61% rename from ts-price-service/src/main/java/price/entity/TrainType.java rename to ts-common/src/main/java/edu/fudan/common/entity/TrainType.java index 768f9b5ba..fca05069d 100644 --- a/ts-price-service/src/main/java/price/entity/TrainType.java +++ b/ts-common/src/main/java/edu/fudan/common/entity/TrainType.java @@ -1,22 +1,20 @@ -package price.entity; +package edu.fudan.common.entity; import lombok.Data; -import org.springframework.data.annotation.Id; import javax.validation.Valid; +import javax.validation.constraints.NotNull; /** * @author fdse */ @Data public class TrainType { - @Valid - @Id private String id; - @Valid + private String name; + private int economyClass; - @Valid private int confortClass; private int averageSpeed; @@ -25,17 +23,16 @@ public TrainType(){ //Default Constructor } - public TrainType(String id, int economyClass, int confortClass) { - this.id = id; + public TrainType(String name, int economyClass, int confortClass) { + this.name = name; this.economyClass = economyClass; this.confortClass = confortClass; } - public TrainType(String id, int economyClass, int confortClass, int averageSpeed) { - this.id = id; + public TrainType(String name, int economyClass, int confortClass, int averageSpeed) { + this.name = name; this.economyClass = economyClass; this.confortClass = confortClass; this.averageSpeed = averageSpeed; } - -} +} \ No newline at end of file diff --git a/ts-preserve-other-service/src/main/java/preserveOther/entity/Travel.java b/ts-common/src/main/java/edu/fudan/common/entity/Travel.java similarity index 60% rename from ts-preserve-other-service/src/main/java/preserveOther/entity/Travel.java rename to ts-common/src/main/java/edu/fudan/common/entity/Travel.java index b1b93a487..ce2569a63 100644 --- a/ts-preserve-other-service/src/main/java/preserveOther/entity/Travel.java +++ b/ts-common/src/main/java/edu/fudan/common/entity/Travel.java @@ -1,5 +1,6 @@ -package preserveOther.entity; +package edu.fudan.common.entity; +import edu.fudan.common.util.StringUtils; import lombok.Data; import java.util.Date; @@ -12,11 +13,11 @@ public class Travel { private Trip trip; - private String startingPlace; + private String startPlace; private String endPlace; - private Date departureTime; + private String departureTime; public Travel(){ //Default Constructor diff --git a/ts-common/src/main/java/edu/fudan/common/entity/TravelInfo.java b/ts-common/src/main/java/edu/fudan/common/entity/TravelInfo.java new file mode 100644 index 000000000..03e39ecf1 --- /dev/null +++ b/ts-common/src/main/java/edu/fudan/common/entity/TravelInfo.java @@ -0,0 +1,51 @@ +package edu.fudan.common.entity; + +import edu.fudan.common.util.StringUtils; +import lombok.AllArgsConstructor; +import lombok.Data; +import lombok.NoArgsConstructor; + +import java.util.Date; + +/** + * @author fdse + */ +@Data +@NoArgsConstructor +@AllArgsConstructor +public class TravelInfo { + private String loginId; + + private String tripId; + + private String trainTypeName; + + private String routeId; + + private String startStationName; + + private String stationsName; + + private String terminalStationName; + + private String startTime; + + private String endTime; + +// public Date getStartTime(){ +// return StringUtils.String2Date(this.startTime); +// } +// +// public Date getEndTime(){ +// return StringUtils.String2Date(this.endTime); +// } +// +// public String getStartStationName() { +// return StringUtils.String2Lower(this.startStationName); +// } +// +// public String getTerminalStationName() { +// return StringUtils.String2Lower(this.terminalStationName); +// } + +} diff --git a/ts-preserve-other-service/src/main/java/preserveOther/entity/TravelResult.java b/ts-common/src/main/java/edu/fudan/common/entity/TravelResult.java similarity index 85% rename from ts-preserve-other-service/src/main/java/preserveOther/entity/TravelResult.java rename to ts-common/src/main/java/edu/fudan/common/entity/TravelResult.java index bf0e4cd4b..74ac8f5fb 100644 --- a/ts-preserve-other-service/src/main/java/preserveOther/entity/TravelResult.java +++ b/ts-common/src/main/java/edu/fudan/common/entity/TravelResult.java @@ -1,4 +1,4 @@ -package preserveOther.entity; +package edu.fudan.common.entity; import java.util.Map; import lombok.*; @@ -15,6 +15,8 @@ public class TravelResult { private TrainType trainType; + private Route route; + private Map prices; public TravelResult(){ diff --git a/ts-common/src/main/java/edu/fudan/common/entity/Trip.java b/ts-common/src/main/java/edu/fudan/common/entity/Trip.java new file mode 100644 index 000000000..116a9e375 --- /dev/null +++ b/ts-common/src/main/java/edu/fudan/common/entity/Trip.java @@ -0,0 +1,79 @@ +package edu.fudan.common.entity; + +import edu.fudan.common.util.StringUtils; + +import lombok.Data; + +import javax.validation.Valid; +import javax.validation.constraints.NotNull; +import java.util.Date; +import java.util.UUID; + +/** + * @author fdse + */ +@Data +public class Trip { + private String id; + + private TripId tripId; + + private String trainTypeName; + + private String routeId; + private String startStationName; + + private String stationsName; + + private String terminalStationName; + + private String startTime; + + private String endTime; + + public Trip(edu.fudan.common.entity.TripId tripId, String trainTypeName, String startStationName, String stationsName, String terminalStationName, String startTime, String endTime) { + this.tripId = tripId; + this.trainTypeName = trainTypeName; + this.startStationName = StringUtils.String2Lower(startStationName); + this.stationsName = StringUtils.String2Lower(stationsName); + this.terminalStationName = StringUtils.String2Lower(terminalStationName); + this.startTime = startTime; + this.endTime = endTime; + } + + public Trip(TripId tripId, String trainTypeName, String routeId) { + this.tripId = tripId; + this.trainTypeName = trainTypeName; + this.routeId = routeId; + this.startStationName = ""; + this.terminalStationName = ""; + this.startTime = ""; + this.endTime = ""; + } + + public Trip(){ + //Default Constructor + this.trainTypeName = ""; + this.startStationName = ""; + this.terminalStationName = ""; + this.startTime = ""; + this.endTime = ""; + } + +// public Date getStartTime(){ +// return StringUtils.String2Date(this.startTime); +// } +// +// public Date getEndTime(){ +// return StringUtils.String2Date(this.endTime); +// } +// +// public void setStartTime(Date startTime){ +// this.startTime = StringUtils.Date2String(startTime); +// } +// +// public void setEndTime(Date endTime){ +// this.endTime = StringUtils.Date2String(endTime); +// } + +} \ No newline at end of file diff --git a/ts-preserve-service/src/main/java/preserve/entity/TripAllDetail.java b/ts-common/src/main/java/edu/fudan/common/entity/TripAllDetail.java similarity index 67% rename from ts-preserve-service/src/main/java/preserve/entity/TripAllDetail.java rename to ts-common/src/main/java/edu/fudan/common/entity/TripAllDetail.java index 910b3118d..13f48f970 100644 --- a/ts-preserve-service/src/main/java/preserve/entity/TripAllDetail.java +++ b/ts-common/src/main/java/edu/fudan/common/entity/TripAllDetail.java @@ -1,15 +1,15 @@ -package preserve.entity; +package edu.fudan.common.entity; import lombok.AllArgsConstructor; import lombok.Data; -import lombok.ToString; +import lombok.NoArgsConstructor; /** * @author fdse */ @Data +@NoArgsConstructor @AllArgsConstructor -@ToString public class TripAllDetail { private boolean status; @@ -20,8 +20,4 @@ public class TripAllDetail { private Trip trip; - public TripAllDetail() { - //Default Constructor - } - } diff --git a/ts-common/src/main/java/edu/fudan/common/entity/TripAllDetailInfo.java b/ts-common/src/main/java/edu/fudan/common/entity/TripAllDetailInfo.java new file mode 100644 index 000000000..8451445a3 --- /dev/null +++ b/ts-common/src/main/java/edu/fudan/common/entity/TripAllDetailInfo.java @@ -0,0 +1,43 @@ +package edu.fudan.common.entity; + +import edu.fudan.common.util.StringUtils; +import lombok.Data; +import lombok.ToString; + +import java.util.Date; + +/** + * @author fdse + */ +@Data +@ToString +public class TripAllDetailInfo { + + private String tripId; + + private String travelDate; + + private String from; + + private String to; + + public TripAllDetailInfo() { + //Default Constructor + } + + public String getFrom() { + return StringUtils.String2Lower(this.from); + } + + public String getTo() { + return StringUtils.String2Lower(this.to); + } + +// public Date getTravelDate() { +// return StringUtils.String2Date(travelDate); +// } +// +// public void setTravelDate(Date travelDate) { +// this.travelDate = StringUtils.Date2String(travelDate); +// } +} diff --git a/ts-rebook-service/src/main/java/rebook/entity/TripId.java b/ts-common/src/main/java/edu/fudan/common/entity/TripId.java similarity index 83% rename from ts-rebook-service/src/main/java/rebook/entity/TripId.java rename to ts-common/src/main/java/edu/fudan/common/entity/TripId.java index bc3ed68b9..31cfdf1fb 100644 --- a/ts-rebook-service/src/main/java/rebook/entity/TripId.java +++ b/ts-common/src/main/java/edu/fudan/common/entity/TripId.java @@ -1,4 +1,4 @@ -package rebook.entity; +package edu.fudan.common.entity; import lombok.Data; @@ -20,16 +20,18 @@ public TripId(){ public TripId(String trainNumber){ char type0 = trainNumber.charAt(0); switch(type0){ - case 'G': this.type = Type.G; - break; - case 'D': this.type = Type.D; - break; case 'Z': this.type = Type.Z; break; case 'T': this.type = Type.T; break; case 'K': this.type = Type.K; break; + case 'G': + this.type = Type.G; + break; + case 'D': + this.type = Type.D; + break; default:break; } diff --git a/ts-common/src/main/java/edu/fudan/common/entity/TripInfo.java b/ts-common/src/main/java/edu/fudan/common/entity/TripInfo.java new file mode 100644 index 000000000..d406402d7 --- /dev/null +++ b/ts-common/src/main/java/edu/fudan/common/entity/TripInfo.java @@ -0,0 +1,47 @@ +package edu.fudan.common.entity; + +import edu.fudan.common.util.StringUtils; +import lombok.AllArgsConstructor; +import lombok.Data; + +import javax.validation.Valid; +import javax.validation.constraints.NotNull; +import java.util.Date; + +/** + * @author fdse + */ +@Data +@AllArgsConstructor +public class TripInfo { + @Valid + @NotNull + private String startPlace; + + @Valid + @NotNull + private String endPlace; + + @Valid + @NotNull + private String departureTime; + + public TripInfo(){ + //Default Constructor + this.startPlace = ""; + this.endPlace = ""; + this.departureTime = ""; + } + + public String getStartPlace() { + return StringUtils.String2Lower(this.startPlace); + } + + public String getEndPlace() { + return StringUtils.String2Lower(this.endPlace); + } + +// public Date getDepartureTime(){ +// return StringUtils.String2Date(this.departureTime); +// } +} diff --git a/ts-travel2-service/src/main/java/travel2/entity/TripResponse.java b/ts-common/src/main/java/edu/fudan/common/entity/TripResponse.java similarity index 56% rename from ts-travel2-service/src/main/java/travel2/entity/TripResponse.java rename to ts-common/src/main/java/edu/fudan/common/entity/TripResponse.java index d895f0049..67bddeeba 100644 --- a/ts-travel2-service/src/main/java/travel2/entity/TripResponse.java +++ b/ts-common/src/main/java/edu/fudan/common/entity/TripResponse.java @@ -1,7 +1,7 @@ -package travel2.entity; +package edu.fudan.common.entity; +import edu.fudan.common.util.StringUtils; import lombok.Data; -import org.springframework.data.annotation.Id; import javax.validation.Valid; import javax.validation.constraints.NotNull; @@ -13,16 +13,15 @@ @Data public class TripResponse { @Valid - @Id private TripId tripId; @Valid @NotNull - private String trainTypeId; + private String trainTypeName; @Valid @NotNull - private String startingStation; + private String startStation; @Valid @NotNull @@ -30,11 +29,11 @@ public class TripResponse { @Valid @NotNull - private Date startingTime; + private String startTime; @Valid @NotNull - private Date endTime; + private String endTime; /** * the number of economy seats @@ -60,15 +59,29 @@ public class TripResponse { public TripResponse(){ //Default Constructor - this.trainTypeId = ""; - this.startingStation = ""; + this.trainTypeName = ""; + this.startStation = ""; this.terminalStation = ""; - this.startingTime = new Date(); - this.endTime = new Date(); + this.startTime = ""; + this.endTime = ""; this.economyClass = 0; this.confortClass = 0; this.priceForEconomyClass = ""; this.priceForConfortClass = ""; } +// public Date getStartTime(){ +// return StringUtils.String2Date(startTime); +// } +// public Date getEndTime(){ +// return StringUtils.String2Date(endTime); +// } +// +// public void setStartTime(Date startTime){ +// this.startTime = StringUtils.Date2String(startTime); +// } +// public void setEndTime(Date endTime){ +// this.endTime = StringUtils.Date2String(endTime); +// } + } diff --git a/ts-rebook-service/src/main/java/rebook/entity/Type.java b/ts-common/src/main/java/edu/fudan/common/entity/Type.java similarity index 96% rename from ts-rebook-service/src/main/java/rebook/entity/Type.java rename to ts-common/src/main/java/edu/fudan/common/entity/Type.java index 737d0ba5e..3085274af 100644 --- a/ts-rebook-service/src/main/java/rebook/entity/Type.java +++ b/ts-common/src/main/java/edu/fudan/common/entity/Type.java @@ -1,4 +1,4 @@ -package rebook.entity; +package edu.fudan.common.entity; import java.io.Serializable; @@ -6,7 +6,6 @@ * @author fdse */ public enum Type implements Serializable{ - /** * G */ diff --git a/ts-preserve-service/src/main/java/preserve/entity/User.java b/ts-common/src/main/java/edu/fudan/common/entity/User.java similarity index 92% rename from ts-preserve-service/src/main/java/preserve/entity/User.java rename to ts-common/src/main/java/edu/fudan/common/entity/User.java index 530473375..cfa6afb63 100644 --- a/ts-preserve-service/src/main/java/preserve/entity/User.java +++ b/ts-common/src/main/java/edu/fudan/common/entity/User.java @@ -1,4 +1,5 @@ -package preserve.entity; +package edu.fudan.common.entity; + import lombok.AllArgsConstructor; import lombok.Builder; @@ -15,7 +16,6 @@ @AllArgsConstructor @NoArgsConstructor public class User { - private UUID userId; private String userName; private String password; diff --git a/ts-rebook-service/src/main/java/rebook/entity/VerifyResult.java b/ts-common/src/main/java/edu/fudan/common/entity/VerifyResult.java similarity index 100% rename from ts-rebook-service/src/main/java/rebook/entity/VerifyResult.java rename to ts-common/src/main/java/edu/fudan/common/entity/VerifyResult.java diff --git a/ts-common/src/main/java/edu/fudan/common/security/jwt/JWTUtil.java b/ts-common/src/main/java/edu/fudan/common/security/jwt/JWTUtil.java index 1e976c891..792fd6851 100644 --- a/ts-common/src/main/java/edu/fudan/common/security/jwt/JWTUtil.java +++ b/ts-common/src/main/java/edu/fudan/common/security/jwt/JWTUtil.java @@ -99,19 +99,19 @@ private static boolean validateToken(String token) { Jws claimsJws = getClaims(token); return !claimsJws.getBody().getExpiration().before(new Date()); } catch (ExpiredJwtException e) { - LOGGER.error("Token expired: {} " + e); + LOGGER.error("[validateToken][getClaims][Token expired][ExpiredJwtException: {} ]" , e); throw new TokenException("Token expired"); } catch (UnsupportedJwtException e) { - LOGGER.error("Token format error: {} " + e); + LOGGER.error("[validateToken][getClaims][Token format error][UnsupportedJwtException: {}]", e); throw new TokenException("Token format error"); } catch (MalformedJwtException e) { - LOGGER.error("Token is not properly constructed: {} " + e); + LOGGER.error("[validateToken][getClaims][Token is not properly constructed][MalformedJwtException: {}]", e); throw new TokenException("Token is not properly constructed"); } catch (SignatureException e) { - LOGGER.error("Signature failure: {} " + e); + LOGGER.error("[validateToken][getClaims][Signature failure][SignatureException: {}]", e); throw new TokenException("Signature failure"); } catch (IllegalArgumentException e) { - LOGGER.error("Illegal parameter exception: {} " + e); + LOGGER.error("[validateToken][getClaims][Illegal parameter exception][IllegalArgumentException: {}]", e); throw new TokenException("Illegal parameter exception"); } } diff --git a/ts-common/src/main/java/edu/fudan/common/util/JsonUtils.java b/ts-common/src/main/java/edu/fudan/common/util/JsonUtils.java index caf716f0d..0e5dc6470 100644 --- a/ts-common/src/main/java/edu/fudan/common/util/JsonUtils.java +++ b/ts-common/src/main/java/edu/fudan/common/util/JsonUtils.java @@ -29,7 +29,7 @@ public static String object2Json(Object obj) { ObjectMapper objectMapper = new ObjectMapper(); result = objectMapper.writeValueAsString(obj); } catch (IOException e) { - JsonUtils.LOGGER.error(e.getMessage()); + JsonUtils.LOGGER.error("[object2Json][writeValueAsString][IOException: {}]", e.getMessage()); } return result; } @@ -61,9 +61,9 @@ public static T json2Object(String json, Class cls) { ObjectMapper objectMapper = new ObjectMapper(); result = objectMapper.readValue(json, cls); } catch (NullPointerException e) { - JsonUtils.LOGGER.error(e.getMessage()); + JsonUtils.LOGGER.error("[json2Object][objectMapper.readValue][NullPointerException: {}]",e.getMessage()); } catch (IOException e) { - JsonUtils.LOGGER.error(e.getMessage()); + JsonUtils.LOGGER.error("[json2Object][objectMapper.readValue][IOException: {}]",e.getMessage()); } return result; diff --git a/ts-common/src/main/java/edu/fudan/common/util/StringUtils.java b/ts-common/src/main/java/edu/fudan/common/util/StringUtils.java new file mode 100644 index 000000000..f100525ab --- /dev/null +++ b/ts-common/src/main/java/edu/fudan/common/util/StringUtils.java @@ -0,0 +1,35 @@ +package edu.fudan.common.util; + +import java.text.SimpleDateFormat; +import java.util.Locale; +import java.util.Date; + +public class StringUtils { + public static String String2Lower(String str){ + if(str == null || str.isEmpty()) { + return str; + } + return str.replace(" ", "").toLowerCase(Locale.ROOT); + } + + public static Date String2Date(String str){ + SimpleDateFormat formatter; + if(str.length() > 10){ + formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); + }else{ + formatter = new SimpleDateFormat("yyyy-MM-dd"); + } + + try{ + Date d = formatter.parse(str); + return d; + }catch(Exception e){ + return new Date(0); + } + } + + public static String Date2String(Date date){ + SimpleDateFormat formatter= new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); + return formatter.format(date); + } +} diff --git a/ts-config-service/pom.xml b/ts-config-service/pom.xml index be47733d6..fdde77d90 100644 --- a/ts-config-service/pom.xml +++ b/ts-config-service/pom.xml @@ -15,7 +15,7 @@ org.services ts-service 0.1.0 - ../ + ../pom.xml @@ -24,19 +24,28 @@ + + + + org.springframework.boot - spring-boot-starter-data-mongodb + spring-boot-starter-data-jpa + + + mysql + mysql-connector-java org.services ts-common 0.1.0 - - + + jakarta.validation + jakarta.validation-api + - diff --git a/ts-config-service/src/main/java/config/ConfigApplication.java b/ts-config-service/src/main/java/config/ConfigApplication.java index f2a32e7b6..61f83c7c2 100644 --- a/ts-config-service/src/main/java/config/ConfigApplication.java +++ b/ts-config-service/src/main/java/config/ConfigApplication.java @@ -3,6 +3,8 @@ import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.boot.web.client.RestTemplateBuilder; +import org.springframework.cloud.client.discovery.EnableDiscoveryClient; +import org.springframework.cloud.client.loadbalancer.LoadBalanced; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.EnableAspectJAutoProxy; import org.springframework.integration.annotation.IntegrationComponentScan; @@ -18,12 +20,14 @@ @EnableAsync @IntegrationComponentScan @EnableSwagger2 +@EnableDiscoveryClient public class ConfigApplication { public static void main(String[] args) { SpringApplication.run(ConfigApplication.class, args); } + @LoadBalanced @Bean public RestTemplate restTemplate(RestTemplateBuilder builder) { return builder.build(); diff --git a/ts-config-service/src/main/java/config/controller/ConfigController.java b/ts-config-service/src/main/java/config/controller/ConfigController.java index aae9ff5bc..d3a29d1bd 100644 --- a/ts-config-service/src/main/java/config/controller/ConfigController.java +++ b/ts-config-service/src/main/java/config/controller/ConfigController.java @@ -35,21 +35,21 @@ public String home(@RequestHeader HttpHeaders headers) { @CrossOrigin(origins = "*") @GetMapping(value = "/configs") public HttpEntity queryAll(@RequestHeader HttpHeaders headers) { - logger.info("Query all config"); + logger.info("[queryAll][Query all configs]"); return ok(configService.queryAll(headers)); } @CrossOrigin(origins = "*") @PostMapping(value = "/configs") public HttpEntity createConfig(@RequestBody Config info, @RequestHeader HttpHeaders headers) { - logger.info("Create config"); + logger.info("[createConfig][Create config][Config name: {}]", info.getName()); return new ResponseEntity<>(configService.create(info, headers), HttpStatus.CREATED); } @CrossOrigin(origins = "*") @PutMapping(value = "/configs") public HttpEntity updateConfig(@RequestBody Config info, @RequestHeader HttpHeaders headers) { - logger.info("Update config"); + logger.info("[updateConfig][Update config][Config name: {}]", info.getName()); return ok(configService.update(info, headers)); } @@ -57,14 +57,14 @@ public HttpEntity updateConfig(@RequestBody Config info, @RequestHeader HttpHead @CrossOrigin(origins = "*") @DeleteMapping(value = "/configs/{configName}") public HttpEntity deleteConfig(@PathVariable String configName, @RequestHeader HttpHeaders headers) { - logger.info("Delete config"); + logger.info("[deleteConfig][Delete config][configName: {}]", configName); return ok(configService.delete(configName, headers)); } @CrossOrigin(origins = "*") @GetMapping(value = "/configs/{configName}") public HttpEntity retrieve(@PathVariable String configName, @RequestHeader HttpHeaders headers) { - logger.info("Retrieve config: {}", configName); + logger.info("[retrieve][Retrieve config][configName: {}]", configName); return ok(configService.query(configName, headers)); } diff --git a/ts-config-service/src/main/java/config/entity/Config.java b/ts-config-service/src/main/java/config/entity/Config.java index 2bf5c12a4..0d6a91a97 100644 --- a/ts-config-service/src/main/java/config/entity/Config.java +++ b/ts-config-service/src/main/java/config/entity/Config.java @@ -1,9 +1,9 @@ package config.entity; import lombok.Data; -import org.springframework.data.annotation.Id; -import org.springframework.data.mongodb.core.mapping.Document; +import javax.persistence.Id; +import javax.persistence.Entity; import javax.validation.Valid; import javax.validation.constraints.NotNull; @@ -11,7 +11,7 @@ * @author fdse */ @Data -@Document(collection="config") +@Entity public class Config { @Valid @Id diff --git a/ts-config-service/src/main/java/config/service/ConfigServiceImpl.java b/ts-config-service/src/main/java/config/service/ConfigServiceImpl.java index f1fe65002..952c24898 100644 --- a/ts-config-service/src/main/java/config/service/ConfigServiceImpl.java +++ b/ts-config-service/src/main/java/config/service/ConfigServiceImpl.java @@ -8,6 +8,7 @@ import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpHeaders; import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; import java.util.List; @@ -29,12 +30,12 @@ public class ConfigServiceImpl implements ConfigService { public Response create(Config info, HttpHeaders headers) { if (repository.findByName(info.getName()) != null) { String result = config0 + info.getName() + " already exists."; - logger.warn(result); + logger.warn("[create][{} already exists][config info: {}]", config0, info.getName()); return new Response<>(0, result, null); } else { Config config = new Config(info.getName(), info.getValue(), info.getDescription()); repository.save(config); - logger.info("Config: ({}) create success", info); + logger.info("[create][create success][Config: {}]", info); return new Response<>(1, "Create success", config); } } @@ -48,7 +49,7 @@ public Response update(Config info, HttpHeaders headers) { } else { Config config = new Config(info.getName(), info.getValue(), info.getDescription()); repository.save(config); - logger.info("Config: ({}) update success", config); + logger.info("[update][update success][Config: {}]", config); return new Response<>(1, "Update success", config); } } @@ -58,24 +59,25 @@ public Response update(Config info, HttpHeaders headers) { public Response query(String name, HttpHeaders headers) { Config config = repository.findByName(name); if (config == null) { - logger.warn("Config does not exist, name: {}, message: {}", name, "No content"); + logger.warn("[query][Config does not exist][name: {}, message: {}]", name, "No content"); return new Response<>(0, "No content", null); } else { - logger.info("Query config {} success", name); + logger.info("[query][Query config success][config name: {}]", name); return new Response<>(1, "Success", config); } } @Override + @Transactional public Response delete(String name, HttpHeaders headers) { Config config = repository.findByName(name); if (config == null) { String result = config0 + name + " doesn't exist."; - logger.warn(result); + logger.warn("[delete][config doesn't exist][config name: {}]", name); return new Response<>(0, result, null); } else { repository.deleteByName(name); - logger.info("Config {} delete success", name); + logger.info("[delete][Config delete success][config name: {}]", name); return new Response<>(1, "Delete success", config); } } @@ -85,10 +87,10 @@ public Response queryAll(HttpHeaders headers) { List configList = repository.findAll(); if (configList != null && !configList.isEmpty()) { - logger.info("Query all config success"); + logger.info("[queryAll][Query all config success]"); return new Response<>(1, "Find all config success", configList); } else { - logger.warn("Query config: {}", "No content"); + logger.warn("[queryAll][Query config, No content]"); return new Response<>(0, "No content", null); } } diff --git a/ts-config-service/src/main/resources/application.yml b/ts-config-service/src/main/resources/application.yml index bd825aa34..10ecea2a2 100644 --- a/ts-config-service/src/main/resources/application.yml +++ b/ts-config-service/src/main/resources/application.yml @@ -1,13 +1,22 @@ spring: - application: - name: ts-config-service - data: - mongodb: - host: ts-config-mongo -# username: user -# password: ${MONGODB_PASSWORD} - database: ts - port: 27017 + cloud: + nacos: + discovery: + server-addr: ${NACOS_ADDRS:nacos-0.nacos-headless.default.svc.cluster.local,nacos-1.nacos-headless.default.svc.cluster.local,nacos-2.nacos-headless.default.svc.cluster.local} + application: + name: ts-config-service + datasource: + url: jdbc:mysql://${CONFIG_MYSQL_HOST:ts-config-mysql}:${CONFIG_MYSQL_PORT:3306}/${CONFIG_MYSQL_DATABASE:ts-config-mysql}?useSSL=false + username: ${CONFIG_MYSQL_USER:root} + password: ${CONFIG_MYSQL_PASSWORD:root} + driver-class-name: com.mysql.cj.jdbc.Driver + jpa: + hibernate: + ddl-auto: update + properties: + hibernate: + dialect: org.hibernate.dialect.MySQL5Dialect + # HTTP Server server: diff --git a/ts-consign-price-service/pom.xml b/ts-consign-price-service/pom.xml index da9d6dd43..0dade879b 100644 --- a/ts-consign-price-service/pom.xml +++ b/ts-consign-price-service/pom.xml @@ -15,7 +15,7 @@ ts-service org.services 0.1.0 - ../ + ../pom.xml @@ -24,19 +24,24 @@ + + + + org.springframework.boot - spring-boot-starter-data-mongodb + spring-boot-starter-data-jpa + + + mysql + mysql-connector-java org.services ts-common 0.1.0 - - - diff --git a/ts-consign-price-service/src/main/java/consignprice/ConsignPriceApplication.java b/ts-consign-price-service/src/main/java/consignprice/ConsignPriceApplication.java index 6e3f04658..07023e2c5 100644 --- a/ts-consign-price-service/src/main/java/consignprice/ConsignPriceApplication.java +++ b/ts-consign-price-service/src/main/java/consignprice/ConsignPriceApplication.java @@ -5,6 +5,8 @@ import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.boot.web.client.RestTemplateBuilder; +import org.springframework.cloud.client.discovery.EnableDiscoveryClient; +import org.springframework.cloud.client.loadbalancer.LoadBalanced; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.EnableAspectJAutoProxy; import org.springframework.integration.annotation.IntegrationComponentScan; @@ -22,15 +24,17 @@ @EnableAsync @IntegrationComponentScan @EnableSwagger2 +@EnableDiscoveryClient public class ConsignPriceApplication { private static final Logger LOGGER = LoggerFactory.getLogger(ConsignPriceApplication.class); public static void main(String[] args) { - ConsignPriceApplication.LOGGER.info("{}", new Date()); + ConsignPriceApplication.LOGGER.info("[ConsignPriceApplication.main][launch date: {}]", new Date()); SpringApplication.run(ConsignPriceApplication.class, args); } + @LoadBalanced @Bean public RestTemplate restTemplate(RestTemplateBuilder builder) { return builder.build(); diff --git a/ts-consign-price-service/src/main/java/consignprice/controller/ConsignPriceController.java b/ts-consign-price-service/src/main/java/consignprice/controller/ConsignPriceController.java index b5b4ff1a9..3e2d49c3d 100644 --- a/ts-consign-price-service/src/main/java/consignprice/controller/ConsignPriceController.java +++ b/ts-consign-price-service/src/main/java/consignprice/controller/ConsignPriceController.java @@ -31,27 +31,27 @@ public String home(@RequestHeader HttpHeaders headers) { @GetMapping(value = "/consignprice/{weight}/{isWithinRegion}") public HttpEntity getPriceByWeightAndRegion(@PathVariable String weight, @PathVariable String isWithinRegion, @RequestHeader HttpHeaders headers) { - logger.info("Get price by weight: {}, regin: {}", weight, isWithinRegion); + logger.info("[getPriceByWeightAndRegion][Get price by weight and region][weight: {}, region: {}]", weight, isWithinRegion); return ok(service.getPriceByWeightAndRegion(Double.parseDouble(weight), Boolean.parseBoolean(isWithinRegion), headers)); } @GetMapping(value = "/consignprice/price") public HttpEntity getPriceInfo(@RequestHeader HttpHeaders headers) { - logger.info("Get price info"); + logger.info("[getPriceInfo][Get price info]"); return ok(service.queryPriceInformation(headers)); } @GetMapping(value = "/consignprice/config") public HttpEntity getPriceConfig(@RequestHeader HttpHeaders headers) { - logger.info("Get price config"); + logger.info("[getPriceConfig][Get price config]"); return ok(service.getPriceConfig(headers)); } @PostMapping(value = "/consignprice") public HttpEntity modifyPriceConfig(@RequestBody ConsignPrice priceConfig, @RequestHeader HttpHeaders headers) { - logger.info("Create and modify price, config: {}", priceConfig); + logger.info("[modifyPriceConfig][Create and modify price][config: {}]", priceConfig); return ok(service.createAndModifyPrice(priceConfig, headers)); } } diff --git a/ts-consign-price-service/src/main/java/consignprice/entity/ConsignPrice.java b/ts-consign-price-service/src/main/java/consignprice/entity/ConsignPrice.java index 2ca61f6e4..f57356a5c 100644 --- a/ts-consign-price-service/src/main/java/consignprice/entity/ConsignPrice.java +++ b/ts-consign-price-service/src/main/java/consignprice/entity/ConsignPrice.java @@ -2,8 +2,9 @@ import lombok.AllArgsConstructor; import lombok.Data; -import org.springframework.data.annotation.Id; -import org.springframework.data.mongodb.core.mapping.Document; +import org.hibernate.annotations.GenericGenerator; + +import javax.persistence.*; import java.util.UUID; @@ -12,14 +13,24 @@ */ @Data @AllArgsConstructor -@Document(collection = "consign_price") +@Entity +@GenericGenerator(name = "jpa-uuid", strategy = "org.hibernate.id.UUIDGenerator") +@Table(name="consign_price") public class ConsignPrice { @Id - private UUID id; + @GeneratedValue(generator = "jpa-uuid") + @Column(length = 36) + private String id; + + @Column(name = "idx") private int index; + @Column(name = "initial_weight") private double initialWeight; + @Column(name = "initial_price") private double initialPrice; + @Column(name = "within_price") private double withinPrice; + @Column(name = "beyond_price") private double beyondPrice; public ConsignPrice(){ diff --git a/ts-consign-price-service/src/main/java/consignprice/init/InitData.java b/ts-consign-price-service/src/main/java/consignprice/init/InitData.java index 9a21f8d28..539918eba 100644 --- a/ts-consign-price-service/src/main/java/consignprice/init/InitData.java +++ b/ts-consign-price-service/src/main/java/consignprice/init/InitData.java @@ -22,9 +22,9 @@ public class InitData implements CommandLineRunner { @Override public void run(String... strings) throws Exception { - InitData.LOGGER.info("[Consign price service] [Init data operation]"); + InitData.LOGGER.info("[InitData.run][Consign price service][Init data operation]"); ConsignPrice config = new ConsignPrice(); - config.setId(UUID.randomUUID()); + config.setId(UUID.randomUUID().toString()); config.setIndex(0); config.setInitialPrice(8); config.setInitialWeight(1); diff --git a/ts-consign-price-service/src/main/java/consignprice/repository/ConsignPriceConfigRepository.java b/ts-consign-price-service/src/main/java/consignprice/repository/ConsignPriceConfigRepository.java index 91780ee42..c39528261 100644 --- a/ts-consign-price-service/src/main/java/consignprice/repository/ConsignPriceConfigRepository.java +++ b/ts-consign-price-service/src/main/java/consignprice/repository/ConsignPriceConfigRepository.java @@ -1,15 +1,14 @@ package consignprice.repository; import consignprice.entity.ConsignPrice; -import org.springframework.data.mongodb.repository.MongoRepository; -import org.springframework.data.mongodb.repository.Query; +import org.springframework.data.repository.CrudRepository; import org.springframework.stereotype.Repository; /** * @author fdse */ @Repository -public interface ConsignPriceConfigRepository extends MongoRepository { +public interface ConsignPriceConfigRepository extends CrudRepository { /** * find by index @@ -17,7 +16,7 @@ public interface ConsignPriceConfigRepository extends MongoRepository(1, "Success", 3.0), result); @@ -42,7 +42,7 @@ public void testGetPriceByWeightAndRegion1() { @Test public void testGetPriceByWeightAndRegion2() { - ConsignPrice priceConfig = new ConsignPrice(UUID.randomUUID(), 1, 2.0, 3.0, 3.5, 4.0); + ConsignPrice priceConfig = new ConsignPrice(UUID.randomUUID().toString(), 1, 2.0, 3.0, 3.5, 4.0); Mockito.when(repository.findByIndex(0)).thenReturn(priceConfig); Response result = consignPriceServiceImpl.getPriceByWeightAndRegion(3.0, true, headers); Assert.assertEquals(new Response<>(1, "Success", 6.5), result); @@ -50,7 +50,7 @@ public void testGetPriceByWeightAndRegion2() { @Test public void testGetPriceByWeightAndRegion3() { - ConsignPrice priceConfig = new ConsignPrice(UUID.randomUUID(), 1, 2.0, 3.0, 3.5, 4.0); + ConsignPrice priceConfig = new ConsignPrice(UUID.randomUUID().toString(), 1, 2.0, 3.0, 3.5, 4.0); Mockito.when(repository.findByIndex(0)).thenReturn(priceConfig); Response result = consignPriceServiceImpl.getPriceByWeightAndRegion(3.0, false, headers); Assert.assertEquals(new Response<>(1, "Success", 7.0), result); @@ -58,7 +58,7 @@ public void testGetPriceByWeightAndRegion3() { @Test public void testQueryPriceInformation() { - ConsignPrice priceConfig = new ConsignPrice(UUID.randomUUID(), 1, 2.0, 3.0, 3.5, 4.0); + ConsignPrice priceConfig = new ConsignPrice(UUID.randomUUID().toString(), 1, 2.0, 3.0, 3.5, 4.0); Mockito.when(repository.findByIndex(0)).thenReturn(priceConfig); Response result = consignPriceServiceImpl.queryPriceInformation(headers); String str = "The price of weight within 2.0 is 3.0. The price of extra weight within the region is 3.5 and beyond the region is 4.0\n"; @@ -67,7 +67,7 @@ public void testQueryPriceInformation() { @Test public void testCreateAndModifyPrice1() { - ConsignPrice config = new ConsignPrice(UUID.randomUUID(), 1, 2.0, 3.0, 3.5, 4.0); + ConsignPrice config = new ConsignPrice(UUID.randomUUID().toString(), 1, 2.0, 3.0, 3.5, 4.0); Mockito.when(repository.findByIndex(0)).thenReturn(config); Mockito.when(repository.save(Mockito.any(ConsignPrice.class))).thenReturn(null); Response result = consignPriceServiceImpl.createAndModifyPrice(config, headers); @@ -76,7 +76,7 @@ public void testCreateAndModifyPrice1() { @Test public void testCreateAndModifyPrice2() { - ConsignPrice config = new ConsignPrice(UUID.randomUUID(), 0, 2.0, 3.0, 3.5, 4.0); + ConsignPrice config = new ConsignPrice(UUID.randomUUID().toString(), 0, 2.0, 3.0, 3.5, 4.0); Mockito.when(repository.findByIndex(0)).thenReturn(null); Mockito.when(repository.save(Mockito.any(ConsignPrice.class))).thenReturn(null); Response result = consignPriceServiceImpl.createAndModifyPrice(config, headers); diff --git a/ts-consign-service/pom.xml b/ts-consign-service/pom.xml index 82b79ae3a..9899aebfe 100644 --- a/ts-consign-service/pom.xml +++ b/ts-consign-service/pom.xml @@ -15,7 +15,7 @@ ts-service org.services 0.1.0 - ../ + ../pom.xml @@ -26,17 +26,19 @@ org.springframework.boot - spring-boot-starter-data-mongodb + spring-boot-starter-data-jpa + + + mysql + mysql-connector-java + runtime org.services ts-common 0.1.0 - - - diff --git a/ts-consign-service/src/main/java/consign/ConsignApplication.java b/ts-consign-service/src/main/java/consign/ConsignApplication.java index 8d40b6923..be1f0c409 100644 --- a/ts-consign-service/src/main/java/consign/ConsignApplication.java +++ b/ts-consign-service/src/main/java/consign/ConsignApplication.java @@ -3,6 +3,8 @@ import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.boot.web.client.RestTemplateBuilder; +import org.springframework.cloud.client.discovery.EnableDiscoveryClient; +import org.springframework.cloud.client.loadbalancer.LoadBalanced; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.EnableAspectJAutoProxy; import org.springframework.integration.annotation.IntegrationComponentScan; @@ -18,11 +20,13 @@ @EnableAsync @IntegrationComponentScan @EnableSwagger2 +@EnableDiscoveryClient public class ConsignApplication { public static void main(String[] args) { SpringApplication.run(ConsignApplication.class, args); } + @LoadBalanced @Bean public RestTemplate restTemplate(RestTemplateBuilder builder) { return builder.build(); diff --git a/ts-consign-service/src/main/java/consign/controller/ConsignController.java b/ts-consign-service/src/main/java/consign/controller/ConsignController.java index 11f46a22a..62b8434a6 100644 --- a/ts-consign-service/src/main/java/consign/controller/ConsignController.java +++ b/ts-consign-service/src/main/java/consign/controller/ConsignController.java @@ -33,33 +33,33 @@ public String home(@RequestHeader HttpHeaders headers) { @PostMapping(value = "/consigns") public HttpEntity insertConsign(@RequestBody Consign request, @RequestHeader HttpHeaders headers) { - logger.info("Insert consign record, id:{}", request.getId()); + logger.info("[insertConsign][Insert consign record][id:{}]", request.getId()); return ok(service.insertConsignRecord(request, headers)); } @PutMapping(value = "/consigns") public HttpEntity updateConsign(@RequestBody Consign request, @RequestHeader HttpHeaders headers) { - logger.info("Update consign record, id: {}", request.getId()); + logger.info("[updateConsign][Update consign record][id: {}]", request.getId()); return ok(service.updateConsignRecord(request, headers)); } @GetMapping(value = "/consigns/account/{id}") public HttpEntity findByAccountId(@PathVariable String id, @RequestHeader HttpHeaders headers) { - logger.info("Find consign by account id: {}", id); + logger.info("[findByAccountId][Find consign by account id][id: {}]", id); UUID newid = UUID.fromString(id); return ok(service.queryByAccountId(newid, headers)); } @GetMapping(value = "/consigns/order/{id}") public HttpEntity findByOrderId(@PathVariable String id, @RequestHeader HttpHeaders headers) { - logger.info("Find consign by order id: {}", id); + logger.info("[findByOrderId][Find consign by order id][id: {}]", id); UUID newid = UUID.fromString(id); return ok(service.queryByOrderId(newid, headers)); } @GetMapping(value = "/consigns/{consignee}") public HttpEntity findByConsignee(@PathVariable String consignee, @RequestHeader HttpHeaders headers) { - logger.info("Find consign by consignee: {}", consignee); + logger.info("[findByConsignee][Find consign by consignee][consignee: {}]", consignee); return ok(service.queryByConsignee(consignee, headers)); } diff --git a/ts-consign-service/src/main/java/consign/entity/Consign.java b/ts-consign-service/src/main/java/consign/entity/Consign.java index e8c4ba7e1..ce02cb832 100644 --- a/ts-consign-service/src/main/java/consign/entity/Consign.java +++ b/ts-consign-service/src/main/java/consign/entity/Consign.java @@ -3,9 +3,10 @@ import lombok.AllArgsConstructor; import lombok.Data; import lombok.NoArgsConstructor; -import org.springframework.data.annotation.Id; +import org.hibernate.annotations.GenericGenerator; + +import javax.persistence.*; -import java.util.UUID; /** * @author fdse @@ -13,11 +14,15 @@ @Data @AllArgsConstructor @NoArgsConstructor +@GenericGenerator(name="jpa-uuid",strategy ="uuid") public class Consign { @Id - private UUID id; - private UUID orderId; - private UUID accountId; + @GeneratedValue(generator = "jpa-uuid") + @Column(length = 36) + private String id; //id主键改成String类型的 自定义生成策略 + private String orderId; //这次托运关联订单 + private String accountId; //这次托运关联的账户 + private String handleDate; private String targetDate; private String from; diff --git a/ts-consign-service/src/main/java/consign/entity/ConsignRecord.java b/ts-consign-service/src/main/java/consign/entity/ConsignRecord.java index a2667b98d..05145315c 100644 --- a/ts-consign-service/src/main/java/consign/entity/ConsignRecord.java +++ b/ts-consign-service/src/main/java/consign/entity/ConsignRecord.java @@ -4,10 +4,8 @@ import lombok.AllArgsConstructor; import lombok.Data; import lombok.NoArgsConstructor; -import org.springframework.data.annotation.Id; -import org.springframework.data.mongodb.core.mapping.Document; -import java.util.UUID; +import javax.persistence.*; /** * @author fdse @@ -15,21 +13,28 @@ @Data @AllArgsConstructor @NoArgsConstructor -@Document(collection = "consign_record") +@Entity @JsonIgnoreProperties(ignoreUnknown = true) +@Table(schema = "ts-consign-mysql") public class ConsignRecord { @Id - private UUID id; - private UUID orderId; - private UUID accountId; + @Column(name = "consign_record_id") + private String id; + private String orderId; + @Column(name = "user_id") + private String accountId; private String handleDate; private String targetDate; + @Column(name = "from_place") private String from; + @Column(name = "to_place") private String to; private String consignee; + @Column(name = "consign_record_phone") private String phone; private double weight; + @Column(name = "consign_record_price") private double price; } diff --git a/ts-consign-service/src/main/java/consign/init/InitData.java b/ts-consign-service/src/main/java/consign/init/InitData.java new file mode 100644 index 000000000..e77da0209 --- /dev/null +++ b/ts-consign-service/src/main/java/consign/init/InitData.java @@ -0,0 +1,75 @@ +package consign.init; + +import consign.entity.Consign; +import consign.entity.ConsignRecord; +import consign.repository.ConsignRepository; +import consign.service.ConsignService; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.CommandLineRunner; +import org.springframework.stereotype.Component; + +import java.util.ArrayList; + +@Component +public class InitData implements CommandLineRunner { + @Autowired + ConsignService service; + + @Autowired + ConsignRepository repository; + + @Override + public void run(String... args) throws Exception { + //do nothing + /* ConsignRecord c_1 = new ConsignRecord(); + String id_1 = "ff8080817b3e4c27017b3e4c3bee0000"; + String orderID_1 = "ff8080817b3e4c27017b3e4order0000"; + String accountID_1 = "ff8080817b3e4c27017b3e4c3acc0000"; + String consignee_1 = "xxx1"; + c_1.setId(id_1); + c_1.setAccountId(accountID_1); + c_1.setOrderId(orderID_1); + c_1.setConsignee(consignee_1); + c_1.setFrom("from"); + c_1.setTo("to"); + c_1.setHandleDate("handle_date"); + c_1.setTargetDate("target_date"); + c_1.setPhone("12345"); + c_1.setWeight(10); + repository.save(c_1); + + ConsignRecord c_2 = new ConsignRecord(); + String id_2 = "ff8080817b3e4c27017b3e4c3bee1111"; + String orderID_2 = "ff8080817b3e4c27017b3e4order1111"; + String accountID_2 = "ff8080817b3e4c27017b3e4c3acc0000"; //同一个account + String consignee_2 = "xxx2"; + c_2.setId(id_2); + c_2.setAccountId(accountID_2); + c_2.setOrderId(orderID_2); + c_2.setConsignee(consignee_2); + c_2.setFrom("from2"); + c_2.setTo("to2"); + c_2.setHandleDate("handle_date2"); + c_2.setTargetDate("target_date2"); + c_2.setPhone("12345"); + c_2.setWeight(12); + repository.save(c_2); + + ConsignRecord res1 = repository.findById(id_1).get(); + System.out.println("id查找成功 : " + res1.getId()); + ConsignRecord res2 = repository.findByOrderId(orderID_1); + System.out.println("orderID查找成功 : "+ res2.getId()); + ArrayList res3 = repository.findByAccountId(accountID_1); + System.out.println("accountID查找成功 : " + res3.size()); + ArrayList res4 = repository.findByConsignee(consignee_1); + System.out.println("consignee查找成功 : " + res4.size()); +*/ + + + } + + + + + +} diff --git a/ts-consign-service/src/main/java/consign/repository/ConsignRepository.java b/ts-consign-service/src/main/java/consign/repository/ConsignRepository.java index 4e0108482..002b59413 100644 --- a/ts-consign-service/src/main/java/consign/repository/ConsignRepository.java +++ b/ts-consign-service/src/main/java/consign/repository/ConsignRepository.java @@ -1,17 +1,17 @@ package consign.repository; import consign.entity.ConsignRecord; -import org.springframework.data.mongodb.repository.MongoRepository; +import org.springframework.data.repository.CrudRepository; import org.springframework.stereotype.Repository; import java.util.ArrayList; -import java.util.UUID; +import java.util.Optional; /** * @author fdse */ @Repository -public interface ConsignRepository extends MongoRepository { +public interface ConsignRepository extends CrudRepository { /** * find by account id @@ -19,7 +19,7 @@ public interface ConsignRepository extends MongoRepository */ - ArrayList findByAccountId(UUID accountId); + ArrayList findByAccountId(String accountId); /** * find by order id @@ -27,7 +27,7 @@ public interface ConsignRepository extends MongoRepository findById(String id); } diff --git a/ts-consign-service/src/main/java/consign/service/ConsignServiceImpl.java b/ts-consign-service/src/main/java/consign/service/ConsignServiceImpl.java index d03239dc9..37d62149d 100644 --- a/ts-consign-service/src/main/java/consign/service/ConsignServiceImpl.java +++ b/ts-consign-service/src/main/java/consign/service/ConsignServiceImpl.java @@ -7,6 +7,9 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.cloud.client.ServiceInstance; +import org.springframework.cloud.client.discovery.DiscoveryClient; import org.springframework.core.ParameterizedTypeReference; import org.springframework.http.HttpEntity; import org.springframework.http.HttpHeaders; @@ -16,6 +19,7 @@ import org.springframework.web.client.RestTemplate; import java.util.List; +import java.util.Optional; import java.util.UUID; /** @@ -29,20 +33,26 @@ public class ConsignServiceImpl implements ConsignService { @Autowired RestTemplate restTemplate; + @Autowired + private DiscoveryClient discoveryClient; + private static final Logger LOGGER = LoggerFactory.getLogger(ConsignServiceImpl.class); + private String getServiceUrl(String serviceName) { + return "http://" + serviceName; + } + + @Override public Response insertConsignRecord(Consign consignRequest, HttpHeaders headers) { - ConsignServiceImpl.LOGGER.info("[ Insert new consign record] {}", consignRequest.getOrderId()); + ConsignServiceImpl.LOGGER.info("[insertConsignRecord][Insert Start][consignRequest.getOrderId: {}]", consignRequest.getOrderId()); ConsignRecord consignRecord = new ConsignRecord(); //Set the record attribute - consignRecord.setId(UUID.randomUUID()); - LOGGER.info("Order ID is :" + consignRequest.getOrderId()); - consignRecord.setOrderId(consignRequest.getOrderId()); - consignRecord.setAccountId(consignRequest.getAccountId()); - ConsignServiceImpl.LOGGER.info("The handle date is {}", consignRequest.getHandleDate()); - ConsignServiceImpl.LOGGER.info("The target date is {}", consignRequest.getTargetDate()); + consignRecord.setId(UUID.randomUUID().toString()); + consignRecord.setOrderId(consignRequest.getOrderId().toString()); + consignRecord.setAccountId(consignRequest.getAccountId().toString()); + ConsignServiceImpl.LOGGER.info("[insertConsignRecord][Insert Info][handle date: {}, target date: {}]", consignRequest.getHandleDate(), consignRequest.getTargetDate()); consignRecord.setHandleDate(consignRequest.getHandleDate()); consignRecord.setTargetDate(consignRequest.getTargetDate()); consignRecord.setFrom(consignRequest.getFrom()); @@ -53,29 +63,30 @@ public Response insertConsignRecord(Consign consignRequest, HttpHeaders headers) //get the price HttpEntity requestEntity = new HttpEntity(null, headers); + String consign_price_service_url = getServiceUrl("ts-consign-price-service"); ResponseEntity> re = restTemplate.exchange( - "http://ts-consign-price-service:16110/api/v1/consignpriceservice/consignprice/" + consignRequest.getWeight() + "/" + consignRequest.isWithin(), + consign_price_service_url + "/api/v1/consignpriceservice/consignprice/" + consignRequest.getWeight() + "/" + consignRequest.isWithin(), HttpMethod.GET, requestEntity, new ParameterizedTypeReference>() { }); consignRecord.setPrice(re.getBody().getData()); - LOGGER.info("SAVE consign info : " + consignRecord.toString()); + LOGGER.info("[insertConsignRecord][SAVE consign info][consignRecord : {}]", consignRecord.toString()); ConsignRecord result = repository.save(consignRecord); - LOGGER.info("SAVE consign result : " + result.toString()); + LOGGER.info("[insertConsignRecord][SAVE consign result][result: {}]", result.toString()); return new Response<>(1, "You have consigned successfully! The price is " + result.getPrice(), result); } @Override public Response updateConsignRecord(Consign consignRequest, HttpHeaders headers) { - ConsignServiceImpl.LOGGER.info("[ Update consign record]"); + ConsignServiceImpl.LOGGER.info("[updateConsignRecord][Update Start]"); - ConsignRecord originalRecord = repository.findById(consignRequest.getId()); - if (originalRecord == null) { + if (!repository.findById(consignRequest.getId()).isPresent()) { return insertConsignRecord(consignRequest, headers); } - originalRecord.setAccountId(consignRequest.getAccountId()); + ConsignRecord originalRecord = repository.findById(consignRequest.getId()).get(); + originalRecord.setAccountId(consignRequest.getAccountId().toString()); originalRecord.setHandleDate(consignRequest.getHandleDate()); originalRecord.setTargetDate(consignRequest.getTargetDate()); originalRecord.setFrom(consignRequest.getFrom()); @@ -85,8 +96,9 @@ public Response updateConsignRecord(Consign consignRequest, HttpHeaders headers) //Recalculate price if (originalRecord.getWeight() != consignRequest.getWeight()) { HttpEntity requestEntity = new HttpEntity<>(null, headers); + String consign_price_service_url = getServiceUrl("ts-consign-price-service"); ResponseEntity> re = restTemplate.exchange( - "http://ts-consign-price-service:16110/api/v1/consignpriceservice/consignprice/" + consignRequest.getWeight() + "/" + consignRequest.isWithin(), + consign_price_service_url + "/api/v1/consignpriceservice/consignprice/" + consignRequest.getWeight() + "/" + consignRequest.isWithin(), HttpMethod.GET, requestEntity, new ParameterizedTypeReference>() { @@ -105,22 +117,22 @@ public Response updateConsignRecord(Consign consignRequest, HttpHeaders headers) @Override public Response queryByAccountId(UUID accountId, HttpHeaders headers) { - List consignRecords = repository.findByAccountId(accountId); + List consignRecords = repository.findByAccountId(accountId.toString()); if (consignRecords != null && !consignRecords.isEmpty()) { return new Response<>(1, "Find consign by account id success", consignRecords); }else { - LOGGER.warn("No Content according to accountId: {}", accountId); + LOGGER.warn("[queryByAccountId][No Content according to accountId][accountId: {}]", accountId); return new Response<>(0, "No Content according to accountId", null); } } @Override public Response queryByOrderId(UUID orderId, HttpHeaders headers) { - ConsignRecord consignRecords = repository.findByOrderId(orderId); + ConsignRecord consignRecords = repository.findByOrderId(orderId.toString()); if (consignRecords != null ) { return new Response<>(1, "Find consign by order id success", consignRecords); }else { - LOGGER.warn("No Content according to orderId: {}", orderId); + LOGGER.warn("[queryByOrderId][No Content according to orderId][orderId: {}]", orderId); return new Response<>(0, "No Content according to order id", null); } } @@ -131,7 +143,7 @@ public Response queryByConsignee(String consignee, HttpHeaders headers) { if (consignRecords != null && !consignRecords.isEmpty()) { return new Response<>(1, "Find consign by consignee success", consignRecords); }else { - LOGGER.warn("No Content according to consignee: {}", consignee); + LOGGER.warn("[queryByConsignee][No Content according to consignee][consignee: {}]", consignee); return new Response<>(0, "No Content according to consignee", null); } } diff --git a/ts-consign-service/src/main/resources/application.yml b/ts-consign-service/src/main/resources/application.yml index aa1ddb3f6..78b06e00e 100644 --- a/ts-consign-service/src/main/resources/application.yml +++ b/ts-consign-service/src/main/resources/application.yml @@ -1,11 +1,22 @@ spring: + cloud: + nacos: + discovery: + server-addr: ${NACOS_ADDRS:nacos-0.nacos-headless.default.svc.cluster.local,nacos-1.nacos-headless.default.svc.cluster.local,nacos-2.nacos-headless.default.svc.cluster.local} application: name: ts-consign-service - data: - mongodb: - host: ts-consign-mongo - database: ts - port: 27017 + datasource: + url: jdbc:mysql://${CONSIGN_MYSQL_HOST:ts-consign-mysql}:${CONSIGN_MYSQL_PORT:3306}/${CONSIGN_MYSQL_DATABASE:ts-consign-mysql}?useUnicode=true&characterEncoding=UTF-8&useSSL=false&serverTimezone=UTC + username: ${CONSIGN_MYSQL_USER:root} + password: ${CONSIGN_MYSQL_PASSWORD:root} + driver-class-name: com.mysql.cj.jdbc.Driver + + jpa: + hibernate: + ddl-auto: update + properties: + hibernate: + dialect: org.hibernate.dialect.MySQL5Dialect # HTTP Server @@ -13,4 +24,5 @@ server: port: 16111 swagger: - controllerPackage: consign.controller \ No newline at end of file + controllerPackage: consign.controller + diff --git a/ts-consign-service/src/test/java/consign/service/ConsignServiceImplTest.java b/ts-consign-service/src/test/java/consign/service/ConsignServiceImplTest.java index f2c48ef9c..f3998e73a 100644 --- a/ts-consign-service/src/test/java/consign/service/ConsignServiceImplTest.java +++ b/ts-consign-service/src/test/java/consign/service/ConsignServiceImplTest.java @@ -45,8 +45,8 @@ public void testInsertConsignRecord() { HttpEntity requestEntity = new HttpEntity(null, headers); Response response = new Response<>(1, null, 3.0); ResponseEntity> re = new ResponseEntity<>(response, HttpStatus.OK); - Consign consignRequest = new Consign(UUID.randomUUID(), UUID.randomUUID(), UUID.randomUUID(), "handle_date", "target_date", "place_from", "place_to", "consignee", "10001", 1.0, true); - ConsignRecord consignRecord = new ConsignRecord(UUID.randomUUID(), UUID.randomUUID(), UUID.randomUUID(), "handle_date", "target_date", "place_from", "place_to", "consignee", "10001", 1.0, 3.0); + Consign consignRequest = new Consign(UUID.randomUUID().toString(), UUID.randomUUID(), UUID.randomUUID(), "handle_date", "target_date", "place_from", "place_to", "consignee", "10001", 1.0, true); + ConsignRecord consignRecord = new ConsignRecord(UUID.randomUUID().toString(), UUID.randomUUID().toString(), UUID.randomUUID().toString(), "handle_date", "target_date", "place_from", "place_to", "consignee", "10001", 1.0, 3.0); Mockito.when(restTemplate.exchange( "http://ts-consign-price-service:16110/api/v1/consignpriceservice/consignprice/" + consignRequest.getWeight() + "/" + consignRequest.isWithin(), HttpMethod.GET, @@ -63,9 +63,9 @@ public void testUpdateConsignRecord1() { HttpEntity requestEntity = new HttpEntity(null, headers); Response response = new Response<>(1, null, 3.0); ResponseEntity> re = new ResponseEntity<>(response, HttpStatus.OK); - Consign consignRequest = new Consign(UUID.randomUUID(), UUID.randomUUID(), UUID.randomUUID(), "handle_date", "target_date", "place_from", "place_to", "consignee", "10001", 1.0, true); - ConsignRecord consignRecord = new ConsignRecord(UUID.randomUUID(), UUID.randomUUID(), UUID.randomUUID(), "handle_date", "target_date", "place_from", "place_to", "consignee", "10001", 2.0, 3.0); - Mockito.when(repository.findById(Mockito.any(UUID.class))).thenReturn(consignRecord); + Consign consignRequest = new Consign(UUID.randomUUID().toString(), UUID.randomUUID(), UUID.randomUUID(), "handle_date", "target_date", "place_from", "place_to", "consignee", "10001", 1.0, true); + ConsignRecord consignRecord = new ConsignRecord(UUID.randomUUID().toString(), UUID.randomUUID().toString(), UUID.randomUUID().toString(), "handle_date", "target_date", "place_from", "place_to", "consignee", "10001", 2.0, 3.0); + Mockito.when(repository.findById(Mockito.anyString())).thenReturn(java.util.Optional.of(consignRecord)); Mockito.when(restTemplate.exchange( "http://ts-consign-price-service:16110/api/v1/consignpriceservice/consignprice/" + consignRequest.getWeight() + "/" + consignRequest.isWithin(), HttpMethod.GET, @@ -80,9 +80,9 @@ public void testUpdateConsignRecord1() { @Test public void testUpdateConsignRecord2() { - Consign consignRequest = new Consign(UUID.randomUUID(), UUID.randomUUID(), UUID.randomUUID(), "handle_date", "target_date", "place_from", "place_to", "consignee", "10001", 1.0, true); - ConsignRecord consignRecord = new ConsignRecord(UUID.randomUUID(), UUID.randomUUID(), UUID.randomUUID(), "handle_date", "target_date", "place_from", "place_to", "consignee", "10001", 1.0, 3.0); - Mockito.when(repository.findById(Mockito.any(UUID.class))).thenReturn(consignRecord); + Consign consignRequest = new Consign(UUID.randomUUID().toString(), UUID.randomUUID(), UUID.randomUUID(), "handle_date", "target_date", "place_from", "place_to", "consignee", "10001", 1.0, true); + ConsignRecord consignRecord = new ConsignRecord(UUID.randomUUID().toString(), UUID.randomUUID().toString(), UUID.randomUUID().toString(), "handle_date", "target_date", "place_from", "place_to", "consignee", "10001", 1.0, 3.0); + Mockito.when(repository.findById(Mockito.anyString())).thenReturn(java.util.Optional.of(consignRecord)); Mockito.when(repository.save(Mockito.any(ConsignRecord.class))).thenReturn(null); Response result = consignServiceImpl.updateConsignRecord(consignRequest, headers); Assert.assertEquals(new Response<>(1, "Update consign success", consignRecord), result); @@ -93,7 +93,7 @@ public void testQueryByAccountId1() { UUID accountId = UUID.randomUUID(); ArrayList consignRecords = new ArrayList<>(); consignRecords.add(new ConsignRecord()); - Mockito.when(repository.findByAccountId(Mockito.any(UUID.class))).thenReturn(consignRecords); + Mockito.when(repository.findByAccountId(Mockito.anyString())).thenReturn(consignRecords); Response result = consignServiceImpl.queryByAccountId(accountId, headers); Assert.assertEquals(new Response<>(1, "Find consign by account id success", consignRecords), result); } @@ -101,7 +101,7 @@ public void testQueryByAccountId1() { @Test public void testQueryByAccountId2() { UUID accountId = UUID.randomUUID(); - Mockito.when(repository.findByAccountId(Mockito.any(UUID.class))).thenReturn(null); + Mockito.when(repository.findByAccountId(Mockito.anyString())).thenReturn(null); Response result = consignServiceImpl.queryByAccountId(accountId, headers); Assert.assertEquals(new Response<>(0, "No Content according to accountId", null), result); } @@ -110,7 +110,7 @@ public void testQueryByAccountId2() { public void testQueryByOrderId1() { UUID orderId = UUID.randomUUID(); ConsignRecord consignRecords = new ConsignRecord(); - Mockito.when(repository.findByOrderId(Mockito.any(UUID.class))).thenReturn(consignRecords); + Mockito.when(repository.findByOrderId(Mockito.anyString())).thenReturn(consignRecords); Response result = consignServiceImpl.queryByOrderId(orderId, headers); Assert.assertEquals(new Response<>(1, "Find consign by order id success", consignRecords), result); } @@ -118,7 +118,7 @@ public void testQueryByOrderId1() { @Test public void testQueryByOrderId2() { UUID orderId = UUID.randomUUID(); - Mockito.when(repository.findByOrderId(Mockito.any(UUID.class))).thenReturn(null); + Mockito.when(repository.findByOrderId(Mockito.anyString())).thenReturn(null); Response result = consignServiceImpl.queryByOrderId(orderId, headers); Assert.assertEquals(new Response<>(0, "No Content according to order id", null), result); } diff --git a/ts-contacts-service/pom.xml b/ts-contacts-service/pom.xml index 620ab29be..660edc2f7 100644 --- a/ts-contacts-service/pom.xml +++ b/ts-contacts-service/pom.xml @@ -15,7 +15,7 @@ org.services ts-service 0.1.0 - ../ + ../pom.xml @@ -24,19 +24,24 @@ + + + + org.springframework.boot - spring-boot-starter-data-mongodb + spring-boot-starter-data-jpa + + + mysql + mysql-connector-java org.services ts-common 0.1.0 - - - diff --git a/ts-contacts-service/src/main/java/contacts/ContactsApplication.java b/ts-contacts-service/src/main/java/contacts/ContactsApplication.java index a3a297ddc..4b2e9c8db 100644 --- a/ts-contacts-service/src/main/java/contacts/ContactsApplication.java +++ b/ts-contacts-service/src/main/java/contacts/ContactsApplication.java @@ -3,6 +3,8 @@ import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.boot.web.client.RestTemplateBuilder; +import org.springframework.cloud.client.discovery.EnableDiscoveryClient; +import org.springframework.cloud.client.loadbalancer.LoadBalanced; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.EnableAspectJAutoProxy; import org.springframework.integration.annotation.IntegrationComponentScan; @@ -18,12 +20,14 @@ @EnableAsync @IntegrationComponentScan @EnableSwagger2 +@EnableDiscoveryClient public class ContactsApplication { public static void main(String[] args) { SpringApplication.run(ContactsApplication.class, args); } + @LoadBalanced @Bean public RestTemplate restTemplate(RestTemplateBuilder builder) { return builder.build(); diff --git a/ts-contacts-service/src/main/java/contacts/controller/ContactsController.java b/ts-contacts-service/src/main/java/contacts/controller/ContactsController.java index 0deb44c87..bc8417542 100644 --- a/ts-contacts-service/src/main/java/contacts/controller/ContactsController.java +++ b/ts-contacts-service/src/main/java/contacts/controller/ContactsController.java @@ -34,7 +34,7 @@ public String home() { @CrossOrigin(origins = "*") @GetMapping(path = "/contacts") public HttpEntity getAllContacts(@RequestHeader HttpHeaders headers) { - ContactsController.LOGGER.info("[Contacts Service][Get All Contacts]"); + ContactsController.LOGGER.info("[getAllContacts][Get All Contacts]"); return ok(contactsService.getAllContacts(headers)); } @@ -42,15 +42,15 @@ public HttpEntity getAllContacts(@RequestHeader HttpHeaders headers) { @PostMapping(path = "/contacts") public ResponseEntity createNewContacts(@RequestBody Contacts aci, @RequestHeader HttpHeaders headers) { - ContactsController.LOGGER.info("[ContactsService][VerifyLogin] Success"); + ContactsController.LOGGER.info("[createNewContacts][VerifyLogin Success]"); return new ResponseEntity<>(contactsService.create(aci, headers), HttpStatus.CREATED); } @CrossOrigin(origins = "*") @PostMapping(path = "/contacts/admin") public HttpEntity createNewContactsAdmin(@RequestBody Contacts aci, @RequestHeader HttpHeaders headers) { - aci.setId(UUID.randomUUID()); - ContactsController.LOGGER.info("[ContactsService][Create Contacts In Admin]"); + aci.setId(UUID.randomUUID().toString()); + ContactsController.LOGGER.info("[createNewContactsAdmin][Create Contacts In Admin]"); return new ResponseEntity<>(contactsService.createContacts(aci, headers), HttpStatus.CREATED); } @@ -58,31 +58,31 @@ public HttpEntity createNewContactsAdmin(@RequestBody Contacts aci, @RequestH @CrossOrigin(origins = "*") @DeleteMapping(path = "/contacts/{contactsId}") public HttpEntity deleteContacts(@PathVariable String contactsId, @RequestHeader HttpHeaders headers) { - return ok(contactsService.delete(UUID.fromString(contactsId), headers)); + return ok(contactsService.delete(contactsId, headers)); } @CrossOrigin(origins = "*") @PutMapping(path = "/contacts") public HttpEntity modifyContacts(@RequestBody Contacts info, @RequestHeader HttpHeaders headers) { - ContactsController.LOGGER.info("[Contacts Service][Modify Contacts] ContactsId: {}", info.getId()); + ContactsController.LOGGER.info("[Contacts modifyContacts][Modify Contacts] ContactsId: {}", info.getId()); return ok(contactsService.modify(info, headers)); } @CrossOrigin(origins = "*") @GetMapping(path = "/contacts/account/{accountId}") public HttpEntity findContactsByAccountId(@PathVariable String accountId, @RequestHeader HttpHeaders headers) { - ContactsController.LOGGER.info("[Contacts Service][Find Contacts By Account Id: {}", accountId); - ContactsController.LOGGER.info("[ContactsService][VerifyLogin] Success"); - return ok(contactsService.findContactsByAccountId(UUID.fromString(accountId), headers)); + ContactsController.LOGGER.info("[findContactsByAccountId][Find Contacts By Account Id][accountId: {}]", accountId); + ContactsController.LOGGER.info("[ContactsService][VerifyLogin Success]"); + return ok(contactsService.findContactsByAccountId(accountId, headers)); } @CrossOrigin(origins = "*") @GetMapping(path = "/contacts/{id}") public HttpEntity getContactsByContactsId(@PathVariable String id, @RequestHeader HttpHeaders headers) { - ContactsController.LOGGER.info("[ContactsService][Contacts Id Print] {}", id); - ContactsController.LOGGER.info("[ContactsService][VerifyLogin] Success."); - return ok(contactsService.findContactsById(UUID.fromString(id), headers)); + ContactsController.LOGGER.info("[ContactsService][Contacts Id Print][id: {}]", id); + ContactsController.LOGGER.info("[ContactsService][VerifyLogin Success]"); + return ok(contactsService.findContactsById(id, headers)); } diff --git a/ts-contacts-service/src/main/java/contacts/entity/Contacts.java b/ts-contacts-service/src/main/java/contacts/entity/Contacts.java index 0b8d8a133..2a346d53d 100644 --- a/ts-contacts-service/src/main/java/contacts/entity/Contacts.java +++ b/ts-contacts-service/src/main/java/contacts/entity/Contacts.java @@ -3,8 +3,11 @@ import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import lombok.AllArgsConstructor; import lombok.Data; -import org.springframework.data.annotation.Id; -import org.springframework.data.mongodb.core.mapping.Document; + +import javax.persistence.*; + +import org.hibernate.annotations.GenericGenerator; + import java.util.UUID; /** @@ -12,21 +15,26 @@ */ @Data @AllArgsConstructor -@Document(collection = "contacts") +@Entity +@GenericGenerator(name = "jpa-uuid", strategy = "org.hibernate.id.UUIDGenerator") @JsonIgnoreProperties(ignoreUnknown = true) +@Table(indexes = {@Index(name = "account_document_idx", columnList = "account_id, document_number, document_type", unique = true)}) public class Contacts { @Id - private UUID id; - - private UUID accountId; +// private UUID id; + @GeneratedValue(generator = "jpa-uuid") + @Column(length = 36) + private String id; + @Column(name = "account_id") + private String accountId; private String name; - + @Column(name = "document_type") private int documentType; - + @Column(name = "document_number") private String documentNumber; - + @Column(name = "phone_number") private String phoneNumber; public Contacts() { diff --git a/ts-contacts-service/src/main/java/contacts/init/InitData.java b/ts-contacts-service/src/main/java/contacts/init/InitData.java index 06a9d39b3..1c1a6dbe2 100644 --- a/ts-contacts-service/src/main/java/contacts/init/InitData.java +++ b/ts-contacts-service/src/main/java/contacts/init/InitData.java @@ -20,21 +20,21 @@ public class InitData implements CommandLineRunner{ @Override public void run(String... args)throws Exception{ Contacts contactsOne = new Contacts(); - contactsOne.setAccountId(UUID.fromString("4d2a46c7-71cb-4cf1-b5bb-b68406d9da6f")); + contactsOne.setAccountId(UUID.fromString("4d2a46c7-71cb-4cf1-b5bb-b68406d9da6f").toString()); contactsOne.setDocumentType(DocumentType.ID_CARD.getCode()); contactsOne.setName("Contacts_One"); contactsOne.setDocumentNumber("DocumentNumber_One"); contactsOne.setPhoneNumber("ContactsPhoneNum_One"); - contactsOne.setId(UUID.fromString("4d2a46c7-71cb-4cf1-a5bb-b68406d9da6f")); + contactsOne.setId(UUID.fromString("4d2a46c7-71cb-4cf1-a5bb-b68406d9da6f").toString()); service.create(contactsOne ,null); Contacts contactsTwo = new Contacts(); - contactsTwo.setAccountId(UUID.fromString("4d2a46c7-71cb-4cf1-b5bb-b68406d9da6f")); + contactsTwo.setAccountId(UUID.fromString("4d2a46c7-71cb-4cf1-b5bb-b68406d9da6f").toString()); contactsTwo.setDocumentType(DocumentType.ID_CARD.getCode()); contactsTwo.setName("Contacts_Two"); contactsTwo.setDocumentNumber("DocumentNumber_Two"); contactsTwo.setPhoneNumber("ContactsPhoneNum_Two"); - contactsTwo.setId(UUID.fromString("4d2546c7-71cb-4cf1-a5bb-b68406d9da6f")); + contactsTwo.setId(UUID.fromString("4d2546c7-71cb-4cf1-a5bb-b68406d9da6f").toString()); service.create(contactsTwo,null); } } diff --git a/ts-contacts-service/src/main/java/contacts/repository/ContactsRepository.java b/ts-contacts-service/src/main/java/contacts/repository/ContactsRepository.java index 87421d5f7..1d0b3ac73 100644 --- a/ts-contacts-service/src/main/java/contacts/repository/ContactsRepository.java +++ b/ts-contacts-service/src/main/java/contacts/repository/ContactsRepository.java @@ -1,17 +1,17 @@ package contacts.repository; -import org.springframework.data.mongodb.repository.MongoRepository; -import org.springframework.data.mongodb.repository.Query; +import org.springframework.data.jpa.repository.Query; +import org.springframework.data.repository.CrudRepository; import org.springframework.stereotype.Repository; import contacts.entity.Contacts; -import java.util.ArrayList; -import java.util.UUID; + +import java.util.*; /** * @author fdse */ @Repository -public interface ContactsRepository extends MongoRepository { +public interface ContactsRepository extends CrudRepository { /** * find by id @@ -19,7 +19,7 @@ public interface ContactsRepository extends MongoRepository { * @param id id * @return Contacts */ - Contacts findById(UUID id); + Optional findById(String id); /** * find by account id @@ -27,8 +27,8 @@ public interface ContactsRepository extends MongoRepository { * @param accountId account id * @return ArrayList */ - @Query("{ 'accountId' : ?0 }") - ArrayList findByAccountId(UUID accountId); +// @Query("{ 'accountId' : ?0 }") + ArrayList findByAccountId(String accountId); /** * delete by id @@ -36,7 +36,7 @@ public interface ContactsRepository extends MongoRepository { * @param id id * @return null */ - void deleteById(UUID id); + void deleteById(String id); /** * find all @@ -46,4 +46,7 @@ public interface ContactsRepository extends MongoRepository { @Override ArrayList findAll(); + @Query(value="SELECT * FROM contacts WHERE account_id = ?1 AND document_number = ?2 AND document_type = ?3", nativeQuery = true) + Contacts findByAccountIdAndDocumentTypeAndDocumentType(String account_id, String document_number, int document_type); + } diff --git a/ts-contacts-service/src/main/java/contacts/service/ContactsService.java b/ts-contacts-service/src/main/java/contacts/service/ContactsService.java index 32ebd01a5..7ff27eabe 100644 --- a/ts-contacts-service/src/main/java/contacts/service/ContactsService.java +++ b/ts-contacts-service/src/main/java/contacts/service/ContactsService.java @@ -36,7 +36,7 @@ public interface ContactsService { * @param headers headers * @return Reaponse */ - Response delete(UUID contactsId, HttpHeaders headers); + Response delete(String contactsId, HttpHeaders headers); /** * modify @@ -62,7 +62,7 @@ public interface ContactsService { * @param headers headers * @return Reaponse */ - Response findContactsById(UUID id, HttpHeaders headers); + Response findContactsById(String id, HttpHeaders headers); /** * find contacts by account id @@ -71,6 +71,6 @@ public interface ContactsService { * @param headers headers * @return Reaponse */ - Response findContactsByAccountId(UUID accountId, HttpHeaders headers); + Response findContactsByAccountId(String accountId, HttpHeaders headers); } diff --git a/ts-contacts-service/src/main/java/contacts/service/ContactsServiceImpl.java b/ts-contacts-service/src/main/java/contacts/service/ContactsServiceImpl.java index fe9d9cb41..60add6733 100644 --- a/ts-contacts-service/src/main/java/contacts/service/ContactsServiceImpl.java +++ b/ts-contacts-service/src/main/java/contacts/service/ContactsServiceImpl.java @@ -27,29 +27,29 @@ public class ContactsServiceImpl implements ContactsService { private static final Logger LOGGER = LoggerFactory.getLogger(ContactsServiceImpl.class); @Override - public Response findContactsById(UUID id, HttpHeaders headers) { + public Response findContactsById(String id, HttpHeaders headers) { LOGGER.info("FIND CONTACTS BY ID: " + id); - Contacts contacts = contactsRepository.findById(id); + Contacts contacts = contactsRepository.findById(id).orElse(null); if (contacts != null) { return new Response<>(1, success, contacts); } else { - LOGGER.error("No contacts according to contactsId: {}", id); + LOGGER.error("[findContactsById][contactsRepository.findById][No contacts according to contactsId][contactsId: {}]", id); return new Response<>(0, "No contacts according to contacts id", null); } } @Override - public Response findContactsByAccountId(UUID accountId, HttpHeaders headers) { + public Response findContactsByAccountId(String accountId, HttpHeaders headers) { ArrayList arr = contactsRepository.findByAccountId(accountId); - ContactsServiceImpl.LOGGER.info("[Contacts-Query-Service][Query-Contacts] Result Size: {}", arr.size()); + ContactsServiceImpl.LOGGER.info("[findContactsByAccountId][Query Contacts][Result Size: {}]", arr.size()); return new Response<>(1, success, arr); } @Override public Response createContacts(Contacts contacts, HttpHeaders headers) { - Contacts contactsTemp = contactsRepository.findById(contacts.getId()); + Contacts contactsTemp = contactsRepository.findByAccountIdAndDocumentTypeAndDocumentType(contacts.getAccountId(), contacts.getDocumentNumber(), contacts.getDocumentType()); if (contactsTemp != null) { - ContactsServiceImpl.LOGGER.warn("[Contacts Service][Init Contacts] Already Exists Id: {}", contacts.getId()); + ContactsServiceImpl.LOGGER.warn("[createContacts][Init Contacts, Already Exists][Id: {}]", contacts.getId()); return new Response<>(0, "Already Exists", contactsTemp); } else { contactsRepository.save(contacts); @@ -59,35 +59,28 @@ public Response createContacts(Contacts contacts, HttpHeaders headers) { @Override public Response create(Contacts addContacts, HttpHeaders headers) { - Contacts contacts = new Contacts(); - contacts.setId(UUID.randomUUID()); - contacts.setName(addContacts.getName()); - contacts.setPhoneNumber(addContacts.getPhoneNumber()); - contacts.setDocumentNumber(addContacts.getDocumentNumber()); - contacts.setAccountId(addContacts.getAccountId()); - contacts.setDocumentType(addContacts.getDocumentType()); - - ArrayList accountContacts = contactsRepository.findByAccountId(addContacts.getAccountId()); - - if (accountContacts.contains(contacts)) { - ContactsServiceImpl.LOGGER.warn("[Contacts-Add&Delete-Service][AddContacts] Fail.Contacts already exists, contactId: {}", addContacts.getId()); + + Contacts c = contactsRepository.findByAccountIdAndDocumentTypeAndDocumentType(addContacts.getAccountId(), addContacts.getDocumentNumber(), addContacts.getDocumentType()); + + if (c != null) { + ContactsServiceImpl.LOGGER.warn("[Contacts-Add&Delete-Service.create][AddContacts][Fail.Contacts already exists][contactId: {}]", addContacts.getId()); return new Response<>(0, "Contacts already exists", null); } else { - contactsRepository.save(contacts); - ContactsServiceImpl.LOGGER.info("[Contacts-Add&Delete-Service][AddContacts] Success."); + Contacts contacts = contactsRepository.save(addContacts); + ContactsServiceImpl.LOGGER.info("[Contacts-Add&Delete-Service.create][AddContacts Success]"); return new Response<>(1, "Create contacts success", contacts); } } @Override - public Response delete(UUID contactsId, HttpHeaders headers) { + public Response delete(String contactsId, HttpHeaders headers) { contactsRepository.deleteById(contactsId); - Contacts contacts = contactsRepository.findById(contactsId); + Contacts contacts = contactsRepository.findById(contactsId).orElse(null); if (contacts == null) { - ContactsServiceImpl.LOGGER.info("[Contacts-Add&Delete-Service][DeleteContacts] Success."); + ContactsServiceImpl.LOGGER.info("[Contacts-Add&Delete-Service][DeleteContacts Success]"); return new Response<>(1, "Delete success", contactsId); } else { - ContactsServiceImpl.LOGGER.error("[Contacts-Add&Delete-Service][DeleteContacts] Fail.Reason not clear, contactsId: {}", contactsId); + ContactsServiceImpl.LOGGER.error("[Contacts-Add&Delete-Service][DeleteContacts][Fail.Reason not clear][contactsId: {}]", contactsId); return new Response<>(0, "Delete failed", contactsId); } } @@ -99,7 +92,7 @@ public Response modify(Contacts contacts, HttpHeaders headers) { LOGGER.info(oldContactResponse.toString()); Contacts oldContacts = (Contacts) oldContactResponse.getData(); if (oldContacts == null) { - ContactsServiceImpl.LOGGER.error("[Contacts-Modify-Service][ModifyContacts] Fail.Contacts not found, contactId: {}", contacts.getId()); + ContactsServiceImpl.LOGGER.error("[Contacts-Modify-Service.modify][ModifyContacts][Fail.Contacts not found][contactId: {}]", contacts.getId()); return new Response<>(0, "Contacts not found", null); } else { oldContacts.setName(contacts.getName()); @@ -107,7 +100,7 @@ public Response modify(Contacts contacts, HttpHeaders headers) { oldContacts.setDocumentNumber(contacts.getDocumentNumber()); oldContacts.setPhoneNumber(contacts.getPhoneNumber()); contactsRepository.save(oldContacts); - ContactsServiceImpl.LOGGER.info("[Contacts-Modify-Service][ModifyContacts] Success."); + ContactsServiceImpl.LOGGER.info("[Contacts-Modify-Service.modify][ModifyContacts Success]"); return new Response<>(1, "Modify success", oldContacts); } } @@ -118,7 +111,7 @@ public Response getAllContacts(HttpHeaders headers) { if (contacts != null && !contacts.isEmpty()) { return new Response<>(1, success, contacts); } else { - LOGGER.error("Get all contacts error, message: {}", "No content"); + LOGGER.error("[getAllContacts][contactsRepository.findAll][Get all contacts error][message: {}]", "No content"); return new Response<>(0, "No content", null); } } diff --git a/ts-contacts-service/src/main/resources/application.yml b/ts-contacts-service/src/main/resources/application.yml index fda8f6f1e..2d4471ae6 100644 --- a/ts-contacts-service/src/main/resources/application.yml +++ b/ts-contacts-service/src/main/resources/application.yml @@ -2,13 +2,24 @@ server: port: 12347 spring: + cloud: + nacos: + discovery: + server-addr: ${NACOS_ADDRS:nacos-0.nacos-headless.default.svc.cluster.local,nacos-1.nacos-headless.default.svc.cluster.local,nacos-2.nacos-headless.default.svc.cluster.local} application: name: ts-contacts-service - data: - mongodb: - host: ts-contacts-mongo - database: ts - port: 27017 + datasource: + url: jdbc:mysql://${CONTACTS_MYSQL_HOST:ts-contacts-mysql}:${CONTACTS_MYSQL_PORT:3306}/${CONTACTS_MYSQL_DATABASE:ts-contacts-mysql}?useSSL=false + username: ${CONTACTS_MYSQL_USER:root} + password: ${CONTACTS_MYSQL_PASSWORD:Abcd1234#} + driver-class-name: com.mysql.cj.jdbc.Driver + jpa: + hibernate: + ddl-auto: update + properties: + hibernate: + dialect: org.hibernate.dialect.MySQL5Dialect + swagger: controllerPackage: contacts.controller \ No newline at end of file diff --git a/ts-contacts-service/src/test/java/contacts/controller/ContactsControllerTest.java b/ts-contacts-service/src/test/java/contacts/controller/ContactsControllerTest.java index 0f559efba..e6796e986 100644 --- a/ts-contacts-service/src/test/java/contacts/controller/ContactsControllerTest.java +++ b/ts-contacts-service/src/test/java/contacts/controller/ContactsControllerTest.java @@ -79,7 +79,7 @@ public void testCreateNewContactsAdmin() throws Exception { @Test public void testDeleteContacts() throws Exception { UUID contactsId = UUID.randomUUID(); - Mockito.when(contactsService.delete(Mockito.any(UUID.class), Mockito.any(HttpHeaders.class))).thenReturn(response); + Mockito.when(contactsService.delete(Mockito.any(UUID.class).toString(), Mockito.any(HttpHeaders.class))).thenReturn(response); String result = mockMvc.perform(MockMvcRequestBuilders.delete("/api/v1/contactservice/contacts/" + contactsId.toString())) .andExpect(MockMvcResultMatchers.status().isOk()) .andReturn().getResponse().getContentAsString(); @@ -100,7 +100,7 @@ public void testModifyContacts() throws Exception { @Test public void testFindContactsByAccountId() throws Exception { UUID accountId = UUID.randomUUID(); - Mockito.when(contactsService.findContactsByAccountId(Mockito.any(UUID.class), Mockito.any(HttpHeaders.class))).thenReturn(response); + Mockito.when(contactsService.findContactsByAccountId(Mockito.any(UUID.class).toString(), Mockito.any(HttpHeaders.class))).thenReturn(response); String result = mockMvc.perform(MockMvcRequestBuilders.get("/api/v1/contactservice/contacts/account/" + accountId.toString())) .andExpect(MockMvcResultMatchers.status().isOk()) .andReturn().getResponse().getContentAsString(); @@ -110,7 +110,7 @@ public void testFindContactsByAccountId() throws Exception { @Test public void testGetContactsByContactsId() throws Exception { UUID id = UUID.randomUUID(); - Mockito.when(contactsService.findContactsById(Mockito.any(UUID.class), Mockito.any(HttpHeaders.class))).thenReturn(response); + Mockito.when(contactsService.findContactsById(Mockito.any(UUID.class).toString(), Mockito.any(HttpHeaders.class))).thenReturn(response); String result = mockMvc.perform(MockMvcRequestBuilders.get("/api/v1/contactservice/contacts/" + id.toString())) .andExpect(MockMvcResultMatchers.status().isOk()) .andReturn().getResponse().getContentAsString(); diff --git a/ts-contacts-service/src/test/java/contacts/service/ContactsServiceImplTest.java b/ts-contacts-service/src/test/java/contacts/service/ContactsServiceImplTest.java index d6ed783fe..21ec2d0b4 100644 --- a/ts-contacts-service/src/test/java/contacts/service/ContactsServiceImplTest.java +++ b/ts-contacts-service/src/test/java/contacts/service/ContactsServiceImplTest.java @@ -15,6 +15,7 @@ import org.springframework.http.HttpHeaders; import java.util.ArrayList; +import java.util.Optional; import java.util.UUID; @RunWith(JUnit4.class) @@ -37,16 +38,16 @@ public void setUp() { public void testFindContactsById1() { UUID id = UUID.randomUUID(); Contacts contacts = new Contacts(); - Mockito.when(contactsRepository.findById(Mockito.any(UUID.class))).thenReturn(contacts); - Response result = contactsServiceImpl.findContactsById(id, headers); + Mockito.when(contactsRepository.findById(Mockito.any(UUID.class).toString())).thenReturn(Optional.of(contacts)); + Response result = contactsServiceImpl.findContactsById(id.toString(), headers); Assert.assertEquals(new Response<>(1, "Success", contacts), result); } @Test public void testFindContactsById2() { UUID id = UUID.randomUUID(); - Mockito.when(contactsRepository.findById(Mockito.any(UUID.class))).thenReturn(null); - Response result = contactsServiceImpl.findContactsById(id, headers); + Mockito.when(contactsRepository.findById(Mockito.any(UUID.class).toString())).thenReturn(Optional.empty()); + Response result = contactsServiceImpl.findContactsById(id.toString(), headers); Assert.assertEquals(new Response<>(0, "No contacts according to contacts id", null), result); } @@ -54,15 +55,15 @@ public void testFindContactsById2() { public void testFindContactsByAccountId() { UUID accountId = UUID.randomUUID(); ArrayList arr = new ArrayList<>(); - Mockito.when(contactsRepository.findByAccountId(Mockito.any(UUID.class))).thenReturn(arr); - Response result = contactsServiceImpl.findContactsByAccountId(accountId, headers); + Mockito.when(contactsRepository.findByAccountId(Mockito.any(UUID.class).toString())).thenReturn(arr); + Response result = contactsServiceImpl.findContactsByAccountId(accountId.toString(), headers); Assert.assertEquals(new Response<>(1, "Success", arr), result); } @Test public void testCreateContacts1() { Contacts contacts = new Contacts(); - Mockito.when(contactsRepository.findById(Mockito.any(UUID.class))).thenReturn(contacts); + Mockito.when(contactsRepository.findById(Mockito.any(UUID.class).toString())).thenReturn(Optional.of(contacts)); Response result = contactsServiceImpl.createContacts(contacts, headers); Assert.assertEquals(new Response<>(0, "Already Exists", contacts), result); } @@ -70,7 +71,7 @@ public void testCreateContacts1() { @Test public void testCreateContacts2() { Contacts contacts = new Contacts(); - Mockito.when(contactsRepository.findById(Mockito.any(UUID.class))).thenReturn(null); + Mockito.when(contactsRepository.findById(Mockito.any(UUID.class).toString())).thenReturn(Optional.empty()); Mockito.when(contactsRepository.save(Mockito.any(Contacts.class))).thenReturn(null); Response result = contactsServiceImpl.createContacts(contacts, headers); Assert.assertEquals(new Response<>(1, "Create Success", null), result); @@ -78,19 +79,19 @@ public void testCreateContacts2() { @Test public void testCreate1() { - Contacts addContacts = new Contacts(UUID.randomUUID(), UUID.randomUUID(), "name", 1, "12", "10001"); + Contacts addContacts = new Contacts(UUID.randomUUID().toString(), UUID.randomUUID().toString(), "name", 1, "12", "10001"); ArrayList accountContacts = new ArrayList<>(); accountContacts.add(addContacts); - Mockito.when(contactsRepository.findByAccountId(Mockito.any(UUID.class))).thenReturn(accountContacts); + Mockito.when(contactsRepository.findByAccountId(Mockito.any(UUID.class).toString())).thenReturn(accountContacts); Response result = contactsServiceImpl.create(addContacts, headers); Assert.assertEquals(new Response<>(0, "Contacts already exists", null), result); } @Test public void testCreate2() { - Contacts addContacts = new Contacts(UUID.randomUUID(), UUID.randomUUID(), "name", 1, "12", "10001"); + Contacts addContacts = new Contacts(UUID.randomUUID().toString(), UUID.randomUUID().toString(), "name", 1, "12", "10001"); ArrayList accountContacts = new ArrayList<>(); - Mockito.when(contactsRepository.findByAccountId(Mockito.any(UUID.class))).thenReturn(accountContacts); + Mockito.when(contactsRepository.findByAccountId(Mockito.any(UUID.class).toString())).thenReturn(accountContacts); Mockito.when(contactsRepository.save(Mockito.any(Contacts.class))).thenReturn(null); Response result = contactsServiceImpl.create(addContacts, headers); Assert.assertEquals(new Response<>(1, "Create contacts success", addContacts), result); @@ -99,9 +100,9 @@ public void testCreate2() { @Test public void testDelete1() { UUID contactsId = UUID.randomUUID(); - Mockito.doNothing().doThrow(new RuntimeException()).when(contactsRepository).deleteById(Mockito.any(UUID.class)); - Mockito.when(contactsRepository.findById(Mockito.any(UUID.class))).thenReturn(null); - Response result = contactsServiceImpl.delete(contactsId, headers); + Mockito.doNothing().doThrow(new RuntimeException()).when(contactsRepository).deleteById(Mockito.any(UUID.class).toString()); + Mockito.when(contactsRepository.findById(Mockito.any(UUID.class).toString())).thenReturn(Optional.empty()); + Response result = contactsServiceImpl.delete(contactsId.toString(), headers); Assert.assertEquals(new Response<>(1, "Delete success", contactsId), result); } @@ -109,24 +110,24 @@ public void testDelete1() { public void testDelete2() { UUID contactsId = UUID.randomUUID(); Contacts contacts = new Contacts(); - Mockito.doNothing().doThrow(new RuntimeException()).when(contactsRepository).deleteById(Mockito.any(UUID.class)); - Mockito.when(contactsRepository.findById(Mockito.any(UUID.class))).thenReturn(contacts); - Response result = contactsServiceImpl.delete(contactsId, headers); + Mockito.doNothing().doThrow(new RuntimeException()).when(contactsRepository).deleteById(Mockito.any(UUID.class).toString()); + Mockito.when(contactsRepository.findById(Mockito.any(UUID.class).toString())).thenReturn(Optional.of(contacts)); + Response result = contactsServiceImpl.delete(contactsId.toString(), headers); Assert.assertEquals(new Response<>(0, "Delete failed", contactsId), result); } @Test public void testModify1() { - Contacts contacts = new Contacts(UUID.randomUUID(), UUID.randomUUID(), "name", 1, "12", "10001"); - Mockito.when(contactsRepository.findById(Mockito.any(UUID.class))).thenReturn(null); + Contacts contacts = new Contacts(UUID.randomUUID().toString(), UUID.randomUUID().toString(), "name", 1, "12", "10001"); + Mockito.when(contactsRepository.findById(Mockito.any(UUID.class).toString())).thenReturn(Optional.empty()); Response result = contactsServiceImpl.modify(contacts, headers); Assert.assertEquals(new Response<>(0, "Contacts not found", null), result); } @Test public void testModify2() { - Contacts contacts = new Contacts(UUID.randomUUID(), UUID.randomUUID(), "name", 1, "12", "10001"); - Mockito.when(contactsRepository.findById(Mockito.any(UUID.class))).thenReturn(contacts); + Contacts contacts = new Contacts(UUID.randomUUID().toString(), UUID.randomUUID().toString(), "name", 1, "12", "10001"); + Mockito.when(contactsRepository.findById(Mockito.any(UUID.class).toString())).thenReturn(Optional.of(contacts)); Mockito.when(contactsRepository.save(Mockito.any(Contacts.class))).thenReturn(null); Response result = contactsServiceImpl.modify(contacts, headers); Assert.assertEquals(new Response<>(1, "Modify success", contacts), result); diff --git a/ts-delivery-service/pom.xml b/ts-delivery-service/pom.xml index 6d80ce0a2..eb057432a 100644 --- a/ts-delivery-service/pom.xml +++ b/ts-delivery-service/pom.xml @@ -14,7 +14,7 @@ org.services ts-service 0.1.0 - ../ + ../pom.xml @@ -27,20 +27,34 @@ org.springframework.boot - spring-boot-starter-data-mongodb + spring-boot-starter-data-jpa + + + + mysql + mysql-connector-java + runtime org.springframework.boot spring-boot-starter-amqp - org.services ts-common 0.1.0 - + + io.springfox + springfox-swagger2 + 2.9.2 + + + io.springfox + springfox-swagger-ui + 2.9.2 + diff --git a/ts-delivery-service/src/main/java/delivery/DeliveryApplication.java b/ts-delivery-service/src/main/java/delivery/DeliveryApplication.java index a10b60b31..863a73c47 100644 --- a/ts-delivery-service/src/main/java/delivery/DeliveryApplication.java +++ b/ts-delivery-service/src/main/java/delivery/DeliveryApplication.java @@ -3,6 +3,8 @@ import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.boot.web.client.RestTemplateBuilder; +import org.springframework.cloud.client.discovery.EnableDiscoveryClient; +import org.springframework.cloud.client.loadbalancer.LoadBalanced; import org.springframework.context.annotation.Bean; import org.springframework.web.client.RestTemplate; import springfox.documentation.swagger2.annotations.EnableSwagger2; @@ -13,12 +15,14 @@ */ @SpringBootApplication @EnableSwagger2 +@EnableDiscoveryClient public class DeliveryApplication { public static void main(String[] args) { SpringApplication.run(DeliveryApplication.class, args); } + @LoadBalanced @Bean public RestTemplate restTemplate(RestTemplateBuilder builder) { return builder.build(); diff --git a/ts-delivery-service/src/main/java/delivery/entity/Delivery.java b/ts-delivery-service/src/main/java/delivery/entity/Delivery.java index c86a28756..21c6175c9 100644 --- a/ts-delivery-service/src/main/java/delivery/entity/Delivery.java +++ b/ts-delivery-service/src/main/java/delivery/entity/Delivery.java @@ -3,14 +3,20 @@ import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import lombok.AllArgsConstructor; import lombok.Data; -import org.springframework.data.annotation.Id; -import org.springframework.data.mongodb.core.mapping.Document; +import org.hibernate.annotations.GeneratorType; +import org.hibernate.annotations.GenericGenerator; +import org.hibernate.annotations.GenericGenerators; +import javax.persistence.Column; +import javax.persistence.GeneratedValue; +import javax.persistence.Id; +import javax.persistence.Entity; import java.util.UUID; @Data @AllArgsConstructor -@Document(collection = "delivery") +@Entity +@GenericGenerator(name = "jpa-uuid", strategy = "org.hibernate.id.UUIDGenerator") @JsonIgnoreProperties(ignoreUnknown = true) public class Delivery { public Delivery() { @@ -18,7 +24,9 @@ public Delivery() { } @Id - private UUID id; + @GeneratedValue(generator = "jpa-uuid") + @Column(length = 36) + private String id; private UUID orderId; private String foodName; diff --git a/ts-delivery-service/src/main/java/delivery/mq/RabbitReceive.java b/ts-delivery-service/src/main/java/delivery/mq/RabbitReceive.java index e6108d367..d9b592d92 100644 --- a/ts-delivery-service/src/main/java/delivery/mq/RabbitReceive.java +++ b/ts-delivery-service/src/main/java/delivery/mq/RabbitReceive.java @@ -37,20 +37,20 @@ public void process(String payload) { Delivery delivery = JsonUtils.json2Object(payload, Delivery.class); if (delivery == null) { - logger.error("Receive delivery object is null, error."); + logger.error("[process][json2Object][Receive delivery object is null error]"); return; } - logger.info("Receive delivery object:" + delivery); + logger.info("[process][Receive delivery object][delivery object: {}]" + delivery); if (delivery.getId() == null) { - delivery.setId(UUID.randomUUID()); + delivery.setId(UUID.randomUUID().toString()); } try { deliveryRepository.save(delivery); - logger.info("Save delivery object into database success"); + logger.info("[process][Save delivery object into database success]"); } catch (Exception e) { - logger.error("Save delivery object into database failed, exception [{}]", e.toString()); + logger.error("[process][deliveryRepository.save][Save delivery object into database failed][exception: {}]", e.toString()); } } } diff --git a/ts-delivery-service/src/main/java/delivery/repository/DeliveryRepository.java b/ts-delivery-service/src/main/java/delivery/repository/DeliveryRepository.java index a4999d42e..0aeea70aa 100644 --- a/ts-delivery-service/src/main/java/delivery/repository/DeliveryRepository.java +++ b/ts-delivery-service/src/main/java/delivery/repository/DeliveryRepository.java @@ -1,26 +1,28 @@ package delivery.repository; import delivery.entity.Delivery; -import org.springframework.data.mongodb.repository.MongoRepository; -import org.springframework.data.mongodb.repository.Query; +import org.springframework.data.repository.CrudRepository; + +import org.springframework.scheduling.Trigger; import org.springframework.stereotype.Repository; import java.util.List; +import java.util.Optional; import java.util.UUID; @Repository -public interface DeliveryRepository extends MongoRepository { +public interface DeliveryRepository extends CrudRepository { + - Delivery findById(UUID id); + Optional findById(String id); - @Query("{ 'orderId' : ?0 }") Delivery findByOrderId(UUID orderId); @Override List findAll(); - void deleteById(UUID id); + void deleteById(String id); - void deleteFoodOrderByOrderId(UUID id); + void deleteFoodOrderByOrderId(String id); } diff --git a/ts-delivery-service/src/main/resources/application.yml b/ts-delivery-service/src/main/resources/application.yml index fc879bd22..ae8c57375 100644 --- a/ts-delivery-service/src/main/resources/application.yml +++ b/ts-delivery-service/src/main/resources/application.yml @@ -2,13 +2,23 @@ server: port: 18808 spring: + cloud: + nacos: + discovery: + server-addr: ${NACOS_ADDRS:nacos-0.nacos-headless.default.svc.cluster.local,nacos-1.nacos-headless.default.svc.cluster.local,nacos-2.nacos-headless.default.svc.cluster.local} application: name: ts-delivery-service - data: - mongodb: - host: ${mongohost:ts-delivery-mongo} - database: ts - port: 27017 + datasource: + url: jdbc:mysql://${DELIVERY_MYSQL_HOST:ts-delivery-mysql}:${DELIVERY_MYSQL_PORT:3306}/${DELIVERY_MYSQL_DATABASE:ts-delivery-mysql}?useSSL=false + username: ${DELIVERY_MYSQL_USER:root} + password: ${DELIVERY_MYSQL_PASSWORD:Abcd1234#} + driver-class-name: com.mysql.cj.jdbc.Driver rabbitmq: host: ${rabbitmq_host:localhost} - port: ${rabbitmq_port:5672} + port: 5672 + jpa: + hibernate: + ddl-auto: update + properties: + hibernate: + dialect: org.hibernate.dialect.MySQL5Dialect diff --git a/ts-execute-service/pom.xml b/ts-execute-service/pom.xml index 9fc91efd8..3a7e882ce 100644 --- a/ts-execute-service/pom.xml +++ b/ts-execute-service/pom.xml @@ -15,7 +15,7 @@ org.services ts-service 0.1.0 - ../ + ../pom.xml @@ -29,10 +29,7 @@ ts-common 0.1.0 - - - diff --git a/ts-execute-service/src/main/java/execute/ExecuteApplication.java b/ts-execute-service/src/main/java/execute/ExecuteApplication.java index f9d266a32..c79bf8a8f 100644 --- a/ts-execute-service/src/main/java/execute/ExecuteApplication.java +++ b/ts-execute-service/src/main/java/execute/ExecuteApplication.java @@ -3,6 +3,8 @@ import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.boot.web.client.RestTemplateBuilder; +import org.springframework.cloud.client.discovery.EnableDiscoveryClient; +import org.springframework.cloud.client.loadbalancer.LoadBalanced; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.EnableAspectJAutoProxy; import org.springframework.integration.annotation.IntegrationComponentScan; @@ -18,12 +20,14 @@ @EnableAsync @IntegrationComponentScan @EnableSwagger2 +@EnableDiscoveryClient public class ExecuteApplication { public static void main(String[] args) { SpringApplication.run(ExecuteApplication.class, args); } + @LoadBalanced @Bean public RestTemplate restTemplate(RestTemplateBuilder builder) { return builder.build(); diff --git a/ts-execute-service/src/main/java/execute/controller/ExecuteControlller.java b/ts-execute-service/src/main/java/execute/controller/ExecuteControlller.java index 0d85594a7..881576b5c 100644 --- a/ts-execute-service/src/main/java/execute/controller/ExecuteControlller.java +++ b/ts-execute-service/src/main/java/execute/controller/ExecuteControlller.java @@ -30,7 +30,7 @@ public String home(@RequestHeader HttpHeaders headers) { @CrossOrigin(origins = "*") @GetMapping(path = "/execute/execute/{orderId}") public HttpEntity executeTicket(@PathVariable String orderId, @RequestHeader HttpHeaders headers) { - ExecuteControlller.LOGGER.info("[Execute] Id: {}", orderId); + ExecuteControlller.LOGGER.info("[executeTicket][Execute][Id: {}]", orderId); // null return ok(executeService.ticketExecute(orderId, headers)); } @@ -38,7 +38,7 @@ public HttpEntity executeTicket(@PathVariable String orderId, @RequestHeader Htt @CrossOrigin(origins = "*") @GetMapping(path = "/execute/collected/{orderId}") public HttpEntity collectTicket(@PathVariable String orderId, @RequestHeader HttpHeaders headers) { - ExecuteControlller.LOGGER.info("[Collect] Id: {}", orderId); + ExecuteControlller.LOGGER.info("[collectTicket][Collect][Id: {}]", orderId); // null return ok(executeService.ticketCollect(orderId, headers)); } diff --git a/ts-execute-service/src/main/java/execute/entity/Order.java b/ts-execute-service/src/main/java/execute/entity/Order.java deleted file mode 100644 index 2d4a7ea0b..000000000 --- a/ts-execute-service/src/main/java/execute/entity/Order.java +++ /dev/null @@ -1,110 +0,0 @@ -package execute.entity; - -import com.fasterxml.jackson.annotation.JsonIgnoreProperties; -import lombok.Data; - -import java.util.Date; -import java.util.UUID; - -/** - * @author fdse - */ -@Data -@JsonIgnoreProperties(ignoreUnknown = true) -public class Order { - - private UUID id; - - private Date boughtDate; - - - private Date travelDate; - - - private Date travelTime; - - /** - * Which Account Bought it - */ - private UUID accountId; - - /** - * Tickets bought for whom.... - */ - private String contactsName; - - private int documentType; - - private String contactsDocumentNumber; - - private String trainNumber; - - private int coachNumber; - - private int seatClass; - - private String seatNumber; - - private String from; - - private String to; - - private int status; - - private String price; - - public Order(){ - boughtDate = new Date(System.currentTimeMillis()); - travelDate = new Date(123456789); - trainNumber = "G1235"; - coachNumber = 5; - seatClass = SeatClass.FIRSTCLASS.getCode(); - seatNumber = "5A"; - from = "上海"; - to = "太原"; - status = OrderStatus.PAID.getCode(); - price = "0.0"; - } - - @Override - public boolean equals(Object obj) { - if (this == obj) { - return true; - } - if (obj == null) { - return false; - } - if (getClass() != obj.getClass()) { - return false; - } - Order other = (Order) obj; - return boughtDate.equals(other.getBoughtDate()) - && travelDate.equals(other.getTravelDate()) - && travelTime.equals(other.getTravelTime()) - && accountId .equals( other.getAccountId() ) - && contactsName.equals(other.getContactsName()) - && contactsDocumentNumber.equals(other.getContactsDocumentNumber()) - && documentType == other.getDocumentType() - && trainNumber.equals(other.getTrainNumber()) - && coachNumber == other.getCoachNumber() - && seatClass == other.getSeatClass() - && seatNumber .equals(other.getSeatNumber()) - && from.equals(other.getFrom()) - && to.equals(other.getTo()) - && status == other.getStatus() - && price.equals(other.price); - } - - @Override - public int hashCode() { - int result = 17; - result = 31 * result + (id == null ? 0 : id.hashCode()); - return result; - } - - public void setTravelDate(int year,int month,int day){ - Date date = new Date(year,month,day,0,0,0); //NOSONAR - this.travelDate = date; - } - -} diff --git a/ts-execute-service/src/main/java/execute/serivce/ExecuteServiceImpl.java b/ts-execute-service/src/main/java/execute/serivce/ExecuteServiceImpl.java index 06f20390c..c4ba35472 100644 --- a/ts-execute-service/src/main/java/execute/serivce/ExecuteServiceImpl.java +++ b/ts-execute-service/src/main/java/execute/serivce/ExecuteServiceImpl.java @@ -1,10 +1,13 @@ package execute.serivce; import edu.fudan.common.util.Response; -import execute.entity.*; +import edu.fudan.common.entity.*; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.cloud.client.ServiceInstance; +import org.springframework.cloud.client.discovery.DiscoveryClient; import org.springframework.core.ParameterizedTypeReference; import org.springframework.http.HttpEntity; import org.springframework.http.HttpHeaders; @@ -13,6 +16,8 @@ import org.springframework.stereotype.Service; import org.springframework.web.client.RestTemplate; +import java.util.List; + /** * @author fdse */ @@ -21,10 +26,16 @@ public class ExecuteServiceImpl implements ExecuteService { @Autowired private RestTemplate restTemplate; + @Autowired + private DiscoveryClient discoveryClient; String orderStatusWrong = "Order Status Wrong"; private static final Logger LOGGER = LoggerFactory.getLogger(ExecuteServiceImpl.class); + private String getServiceUrl(String serviceName) { + return "http://" + serviceName; + } + @Override public Response ticketExecute(String orderId, HttpHeaders headers) { @@ -34,10 +45,10 @@ public Response ticketExecute(String orderId, HttpHeaders headers) { Response resultFromOrder = getOrderByIdFromOrder(orderId, headers); Order order; if (resultFromOrder.getStatus() == 1) { - order = resultFromOrder.getData(); + order = resultFromOrder.getData(); //2.Check if the order can come in if (order.getStatus() != OrderStatus.COLLECTED.getCode()) { - LOGGER.error("ticket execute error: {}, orderId: {}", orderStatusWrong, orderId); + LOGGER.error("[ticketExecute][getOrderByIdFromOrder][ticket execute error: {}][orderId: {}]", orderStatusWrong, orderId); return new Response<>(0, orderStatusWrong, null); } //3.Confirm inbound, request change order information @@ -46,7 +57,7 @@ public Response ticketExecute(String orderId, HttpHeaders headers) { if (resultExecute.getStatus() == 1) { return new Response<>(1, "Success.", null); } else { - LOGGER.error("executeOrder error: {}, orderId: {}", resultExecute.getMsg(), orderId); + LOGGER.error("[ticketExecute][executeOrder][executeOrder error: {}][orderId: {}]", resultExecute.getMsg(), orderId); return new Response<>(0, resultExecute.getMsg(), null); } } else { @@ -55,7 +66,7 @@ public Response ticketExecute(String orderId, HttpHeaders headers) { order = resultFromOrder.getData(); //2.Check if the order can come in if (order.getStatus() != OrderStatus.COLLECTED.getCode()) { - LOGGER.error("ticket execute error: {}, orderId: {}", orderStatusWrong, orderId); + LOGGER.error("[ticketExecute][getOrderByIdFromOrderOther][ticket execute error: {}][orderId: {}]", orderStatusWrong, orderId); return new Response<>(0, orderStatusWrong, null); } //3.Confirm inbound, request change order information @@ -64,11 +75,11 @@ public Response ticketExecute(String orderId, HttpHeaders headers) { if (resultExecute.getStatus() == 1) { return new Response<>(1, "Success", null); } else { - LOGGER.error("executeOrderOther error: {}, orderId: {}", resultExecute.getMsg(), orderId); + LOGGER.error("[ticketExecute][executeOrderOther][executeOrderOther error: {}][orderId: {}]", resultExecute.getMsg(), orderId); return new Response<>(0, resultExecute.getMsg(), null); } } else { - LOGGER.error("ticker execute error: {}, , orderId: {}", "Order Not Found", orderId); + LOGGER.error("[ticketExecute][getOrderByIdFromOrderOther][ticker execute error: {}][orderId: {}]", "Order Not Found", orderId); return new Response<>(0, "Order Not Found", null); } } @@ -85,7 +96,7 @@ public Response ticketCollect(String orderId, HttpHeaders headers) { order = resultFromOrder.getData(); //2.Check if the order can come in if (order.getStatus() != OrderStatus.PAID.getCode() && order.getStatus() != OrderStatus.CHANGE.getCode()) { - LOGGER.error("ticket collect error: {}, orderId: {}", orderStatusWrong, orderId); + LOGGER.error("[ticketCollect][getOrderByIdFromOrder][ticket collect error: {}][orderId: {}]", orderStatusWrong, orderId); return new Response<>(0, orderStatusWrong, null); } //3.Confirm inbound, request change order information @@ -94,7 +105,7 @@ public Response ticketCollect(String orderId, HttpHeaders headers) { if (resultExecute.getStatus() == 1) { return new Response<>(1, "Success", null); } else { - LOGGER.error("ticket collect error: {}, orderId: {}", resultExecute.getMsg(), orderId); + LOGGER.error("[ticketCollect][executeOrder][ticket collect error: {}][orderId: {}]", resultExecute.getMsg(), orderId); return new Response<>(0, resultExecute.getMsg(), null); } } else { @@ -103,7 +114,7 @@ public Response ticketCollect(String orderId, HttpHeaders headers) { order = (Order) resultFromOrder.getData(); //2.Check if the order can come in if (order.getStatus() != OrderStatus.PAID.getCode() && order.getStatus() != OrderStatus.CHANGE.getCode()) { - LOGGER.error("ticket collect error: {}, orderId: {}", orderStatusWrong, orderId); + LOGGER.error("[ticketCollect][getOrderByIdFromOrderOther][ticket collect error: {}][orderId: {}]", orderStatusWrong, orderId); return new Response<>(0, orderStatusWrong, null); } //3.Confirm inbound, request change order information @@ -111,11 +122,11 @@ public Response ticketCollect(String orderId, HttpHeaders headers) { if (resultExecute.getStatus() == 1) { return new Response<>(1, "Success.", null); } else { - LOGGER.error("ticket collect error: {}, orderId: {}", resultExecute.getMsg(), orderId); + LOGGER.error("[ticketCollect][executeOrderOther][ticket collect error: {}][orderId: {}]", resultExecute.getMsg(), orderId); return new Response<>(0, resultExecute.getMsg(), null); } } else { - LOGGER.error("ticket collect error: {}, orderId: {}", "Order Not Found", orderId); + LOGGER.error("[ticketCollect][getOrderByIdFromOrderOther][ticket collect error: {}][orderId: {}]", "Order Not Found", orderId); return new Response<>(0, "Order Not Found", null); } } @@ -126,8 +137,9 @@ private Response executeOrder(String orderId, int status, HttpHeaders headers) { ExecuteServiceImpl.LOGGER.info("[Execute Service][Execute Order] Executing...."); headers = null; HttpEntity requestEntity = new HttpEntity(headers); + String order_service_url=getServiceUrl("ts-order-service"); ResponseEntity re = restTemplate.exchange( - "http://ts-order-service:12031/api/v1/orderservice/order/status/" + orderId + "/" + status, + order_service_url + "/api/v1/orderservice/order/status/" + orderId + "/" + status, HttpMethod.GET, requestEntity, Response.class); @@ -139,8 +151,9 @@ private Response executeOrderOther(String orderId, int status, HttpHeaders heade ExecuteServiceImpl.LOGGER.info("[Execute Service][Execute Order] Executing...."); headers = null; HttpEntity requestEntity = new HttpEntity(headers); + String order_other_service_url=getServiceUrl("ts-order-other-service"); ResponseEntity re = restTemplate.exchange( - "http://ts-order-other-service:12032/api/v1/orderOtherService/orderOther/status/" + orderId + "/" + status, + order_other_service_url + "/api/v1/orderOtherService/orderOther/status/" + orderId + "/" + status, HttpMethod.GET, requestEntity, Response.class); @@ -151,8 +164,9 @@ private Response getOrderByIdFromOrder(String orderId, HttpHeaders header ExecuteServiceImpl.LOGGER.info("[Execute Service][Get Order] Getting...."); headers = null; HttpEntity requestEntity = new HttpEntity(headers); + String order_service_url=getServiceUrl("ts-order-service"); ResponseEntity> re = restTemplate.exchange( - "http://ts-order-service:12031/api/v1/orderservice/order/" + orderId, + order_service_url + "/api/v1/orderservice/order/" + orderId, HttpMethod.GET, requestEntity, new ParameterizedTypeReference>() { @@ -161,11 +175,12 @@ private Response getOrderByIdFromOrder(String orderId, HttpHeaders header } private Response getOrderByIdFromOrderOther(String orderId, HttpHeaders headers) { - ExecuteServiceImpl.LOGGER.info("[Execute Service][Get Order] Getting...."); + ExecuteServiceImpl.LOGGER.info("[getOrderByIdFromOrderOther][Execute Service, Get Order]"); headers = null; HttpEntity requestEntity = new HttpEntity(headers); + String order_other_service_url=getServiceUrl("ts-order-other-service"); ResponseEntity> re = restTemplate.exchange( - "http://ts-order-other-service:12032/api/v1/orderOtherService/orderOther/" + orderId, + order_other_service_url + "/api/v1/orderOtherService/orderOther/" + orderId, HttpMethod.GET, requestEntity, new ParameterizedTypeReference>() { diff --git a/ts-execute-service/src/main/resources/application.yml b/ts-execute-service/src/main/resources/application.yml index eeacf1414..dedac10da 100644 --- a/ts-execute-service/src/main/resources/application.yml +++ b/ts-execute-service/src/main/resources/application.yml @@ -2,6 +2,10 @@ server: port: 12386 spring: + cloud: + nacos: + discovery: + server-addr: ${NACOS_ADDRS:nacos-0.nacos-headless.default.svc.cluster.local,nacos-1.nacos-headless.default.svc.cluster.local,nacos-2.nacos-headless.default.svc.cluster.local} application: name: ts-execute-service swagger: diff --git a/ts-execute-service/src/test/java/execute/service/ExecuteServiceImplTest.java b/ts-execute-service/src/test/java/execute/service/ExecuteServiceImplTest.java index 21b3a3665..09dacd195 100644 --- a/ts-execute-service/src/test/java/execute/service/ExecuteServiceImplTest.java +++ b/ts-execute-service/src/test/java/execute/service/ExecuteServiceImplTest.java @@ -1,7 +1,7 @@ package execute.service; import edu.fudan.common.util.Response; -import execute.entity.Order; +import edu.fudan.common.entity.Order; import execute.serivce.ExecuteServiceImpl; import org.junit.Assert; import org.junit.Before; diff --git a/ts-food-delivery-service/Dockerfile b/ts-food-delivery-service/Dockerfile new file mode 100644 index 000000000..fcca1fb4a --- /dev/null +++ b/ts-food-delivery-service/Dockerfile @@ -0,0 +1,8 @@ +FROM java:8-jre + +RUN /bin/cp /usr/share/zoneinfo/Asia/Shanghai /etc/localtime && echo 'Asia/Shanghai' >/etc/timezone + +ADD ./target/ts-food-delivery-service-1.0.jar /app/ +CMD ["java", "-Xmx200m", "-jar", "/app/ts-food-delivery-service-1.0.jar"] + +EXPOSE 18957 diff --git a/ts-food-delivery-service/pom.xml b/ts-food-delivery-service/pom.xml new file mode 100644 index 000000000..78bed3dd6 --- /dev/null +++ b/ts-food-delivery-service/pom.xml @@ -0,0 +1,56 @@ + + + 4.0.0 + + fdse.microservice + ts-food-delivery-service + 1.0 + jar + + ts-food-delivery-service + + + org.services + ts-service + 0.1.0 + ../pom.xml + + + + UTF-8 + 1.8 + + + + + org.springframework.boot + spring-boot-starter-data-jpa + + + mysql + mysql-connector-java + + + org.services + ts-common + 0.1.0 + + + jakarta.validation + jakarta.validation-api + 2.0.2 + + + + + + org.springframework.boot + spring-boot-maven-plugin + + + + + + \ No newline at end of file diff --git a/ts-food-delivery-service/src/main/java/food_delivery/FoodDeliveryApplication.java b/ts-food-delivery-service/src/main/java/food_delivery/FoodDeliveryApplication.java new file mode 100644 index 000000000..c36976303 --- /dev/null +++ b/ts-food-delivery-service/src/main/java/food_delivery/FoodDeliveryApplication.java @@ -0,0 +1,32 @@ +package food_delivery; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.boot.web.client.RestTemplateBuilder; +import org.springframework.cloud.client.discovery.EnableDiscoveryClient; +import org.springframework.cloud.client.loadbalancer.LoadBalanced; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.EnableAspectJAutoProxy; +import org.springframework.integration.annotation.IntegrationComponentScan; +import org.springframework.scheduling.annotation.EnableAsync; +import org.springframework.web.client.RestTemplate; +import springfox.documentation.swagger2.annotations.EnableSwagger2; + +@SpringBootApplication +@EnableAspectJAutoProxy(proxyTargetClass = true) +@EnableAsync +@IntegrationComponentScan +@EnableSwagger2 +@EnableDiscoveryClient +public class FoodDeliveryApplication { + + public static void main(String[] args) { + SpringApplication.run(FoodDeliveryApplication.class, args); + } + + @LoadBalanced + @Bean + public RestTemplate restTemplate(RestTemplateBuilder builder) { + return builder.build(); + } +} diff --git a/ts-food-delivery-service/src/main/java/food_delivery/config/SecurityConfig.java b/ts-food-delivery-service/src/main/java/food_delivery/config/SecurityConfig.java new file mode 100644 index 000000000..6902a0c4e --- /dev/null +++ b/ts-food-delivery-service/src/main/java/food_delivery/config/SecurityConfig.java @@ -0,0 +1,74 @@ +package food_delivery.config; + +import edu.fudan.common.security.jwt.JWTFilter; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity; +import org.springframework.security.config.annotation.web.builders.HttpSecurity; +import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; +import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; +import org.springframework.security.config.http.SessionCreationPolicy; +import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; +import org.springframework.security.crypto.password.PasswordEncoder; +import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter; +import org.springframework.web.servlet.config.annotation.CorsRegistry; +import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; +import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter; + +import static org.springframework.web.cors.CorsConfiguration.ALL; + +@Configuration +@EnableWebSecurity +@EnableGlobalMethodSecurity(prePostEnabled = true) +public class SecurityConfig extends WebSecurityConfigurerAdapter { + + // load password encoder + @Bean + public PasswordEncoder passwordEncoder() { + return new BCryptPasswordEncoder(); + } + + /** + * allow cors domain + * header 在默认的情况下只能从头部取出6个字段,想要其他字段只能自己在头里指定 + * credentials 默认不发送Cookie, 如果需要Cookie,这个值只能为true + * 本次请求检查的有效期 + * + * @return + */ + @Bean + public WebMvcConfigurer corsConfigurer() { + return new WebMvcConfigurerAdapter() { + @Override + public void addCorsMappings(CorsRegistry registry) { + registry.addMapping("/**") + .allowedOrigins(ALL) + .allowedMethods(ALL) + .allowedHeaders(ALL) + .allowCredentials(false) + .maxAge(3600); + } + }; + } + + + @Override + protected void configure(HttpSecurity httpSecurity) throws Exception { + httpSecurity.httpBasic().disable() + // close default csrf + .csrf().disable() + // close session + .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS) + .and() + .authorizeRequests() + .antMatchers("/api/v1/fooddeliveryservice/**").permitAll() + .antMatchers("/swagger-ui.html", "/webjars/**", "/images/**", + "/configuration/**", "/swagger-resources/**", "/v2/**").permitAll() + .anyRequest().authenticated() + .and() + .addFilterBefore(new JWTFilter(), UsernamePasswordAuthenticationFilter.class); + + // close cache + httpSecurity.headers().cacheControl(); + } +} diff --git a/ts-food-delivery-service/src/main/java/food_delivery/controller/FoodDeliveryController.java b/ts-food-delivery-service/src/main/java/food_delivery/controller/FoodDeliveryController.java new file mode 100644 index 000000000..e24f5802c --- /dev/null +++ b/ts-food-delivery-service/src/main/java/food_delivery/controller/FoodDeliveryController.java @@ -0,0 +1,81 @@ +package food_delivery.controller; + + +import edu.fudan.common.util.Response; +import food_delivery.entity.DeliveryInfo; +import food_delivery.entity.FoodDeliveryOrder; +import food_delivery.entity.SeatInfo; +import food_delivery.entity.TripOrderInfo; +import food_delivery.service.FoodDeliveryService; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.http.HttpEntity; +import org.springframework.http.HttpHeaders; +import org.springframework.web.bind.annotation.*; + +import static org.springframework.http.ResponseEntity.ok; + +@RestController +@RequestMapping("/api/v1/fooddeliveryservice") +public class FoodDeliveryController { + + @Autowired + private FoodDeliveryService foodDeliveryService; + + private static final Logger LOGGER = LoggerFactory.getLogger(FoodDeliveryController.class); + + @GetMapping(path = "/welcome") + public String home() { + return "Welcome to [ food delivery service ] !"; + } + + + @PostMapping("/orders") + public HttpEntity createFoodDeliveryOrder(@RequestBody FoodDeliveryOrder fd, @RequestHeader HttpHeaders headers) { + LOGGER.info("[Food Delivery Service][Create Food Delivery Order]"); + return ok(foodDeliveryService.createFoodDeliveryOrder(fd, headers)); + } + + @DeleteMapping("/orders/d/{orderId}") + public HttpEntity deleteFoodDeliveryOrder(@PathVariable String orderId, @RequestHeader HttpHeaders headers) { + LOGGER.info("[Food Delivery Service][Delete Food Delivery Order]"); + return ok(foodDeliveryService.deleteFoodDeliveryOrder(orderId, headers)); + } + + @GetMapping("/orders/{orderId}") + public HttpEntity getFoodDeliveryOrderById(@PathVariable String orderId, @RequestHeader HttpHeaders headers) { + LOGGER.info("[Food Delivery Service][Get Food Delivery Order By Id]"); + return ok(foodDeliveryService.getFoodDeliveryOrderById(orderId, headers)); + } + + @GetMapping("/orders/all") + public HttpEntity getAllFoodDeliveryOrders(@RequestHeader HttpHeaders headers) { + LOGGER.info("[Food Delivery Service][Get All Food Delivery Orders]"); + return ok(foodDeliveryService.getAllFoodDeliveryOrders(headers)); + } + + @GetMapping("/orders/store/{storeId}") + public HttpEntity getFoodDeliveryOrderByStoreId(@PathVariable String storeId, @RequestHeader HttpHeaders headers) { + LOGGER.info("[Food Delivery Service][Get Food Delivery Order By StoreId]"); + return ok(foodDeliveryService.getFoodDeliveryOrderByStoreId(storeId, headers)); + } + + @PutMapping("/orders/tripid") + public HttpEntity updateTripId(@RequestBody TripOrderInfo tripOrderInfo, @RequestHeader HttpHeaders headers) { + LOGGER.info("[Food Delivery Service][Update Trip Id]"); + return ok(foodDeliveryService.updateTripId(tripOrderInfo, headers)); + } + + @PutMapping("/orders/seatno") + public HttpEntity updateSeatNo(@RequestBody SeatInfo seatInfo, @RequestHeader HttpHeaders headers) { + LOGGER.info("[Food Delivery Service][Update Seat No]"); + return ok(foodDeliveryService.updateSeatNo(seatInfo, headers)); + } + + @PutMapping("/orders/dtime") + public HttpEntity updateDeliveryTime(@RequestBody DeliveryInfo deliveryInfo, @RequestHeader HttpHeaders headers) { + LOGGER.info("[Food Delivery Service][Update Delivery Time]"); + return ok(foodDeliveryService.updateDeliveryTime(deliveryInfo, headers)); + } +} diff --git a/ts-food-delivery-service/src/main/java/food_delivery/entity/DeliveryInfo.java b/ts-food-delivery-service/src/main/java/food_delivery/entity/DeliveryInfo.java new file mode 100644 index 000000000..2e2cb1815 --- /dev/null +++ b/ts-food-delivery-service/src/main/java/food_delivery/entity/DeliveryInfo.java @@ -0,0 +1,13 @@ +package food_delivery.entity; + +import lombok.AllArgsConstructor; +import lombok.Data; +import lombok.NoArgsConstructor; + +@Data +@NoArgsConstructor +@AllArgsConstructor +public class DeliveryInfo { + private String orderId; + private String deliveryTime; +} diff --git a/ts-food-delivery-service/src/main/java/food_delivery/entity/FoodDeliveryOrder.java b/ts-food-delivery-service/src/main/java/food_delivery/entity/FoodDeliveryOrder.java new file mode 100644 index 000000000..a27f5861d --- /dev/null +++ b/ts-food-delivery-service/src/main/java/food_delivery/entity/FoodDeliveryOrder.java @@ -0,0 +1,40 @@ +package food_delivery.entity; + +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import lombok.AllArgsConstructor; +import lombok.Data; +import lombok.NoArgsConstructor; +import org.hibernate.annotations.GenericGenerator; + +import javax.persistence.*; +import java.util.List; +import edu.fudan.common.entity.Food; + +@Data +@Entity +@GenericGenerator(name = "jpa-uuid", strategy = "uuid") +@JsonIgnoreProperties(ignoreUnknown = true) +@AllArgsConstructor +@NoArgsConstructor +public class FoodDeliveryOrder { + + @Id + @GeneratedValue(generator = "jpa-uuid") + @Column(length = 36) + private String id; + + private String stationFoodStoreId; + + @ElementCollection(targetClass = Food.class) + private List foodList; + + private String tripId; + + private int seatNo; + + private String createdTime; + + private String deliveryTime; + + private double deliveryFee; +} diff --git a/ts-food-delivery-service/src/main/java/food_delivery/entity/SeatInfo.java b/ts-food-delivery-service/src/main/java/food_delivery/entity/SeatInfo.java new file mode 100644 index 000000000..615fccc52 --- /dev/null +++ b/ts-food-delivery-service/src/main/java/food_delivery/entity/SeatInfo.java @@ -0,0 +1,13 @@ +package food_delivery.entity; + +import lombok.AllArgsConstructor; +import lombok.Data; +import lombok.NoArgsConstructor; + +@Data +@NoArgsConstructor +@AllArgsConstructor +public class SeatInfo { + private String orderId; + private int seatNo; +} \ No newline at end of file diff --git a/ts-food-delivery-service/src/main/java/food_delivery/entity/StationFoodStoreInfo.java b/ts-food-delivery-service/src/main/java/food_delivery/entity/StationFoodStoreInfo.java new file mode 100644 index 000000000..6138db449 --- /dev/null +++ b/ts-food-delivery-service/src/main/java/food_delivery/entity/StationFoodStoreInfo.java @@ -0,0 +1,31 @@ +package food_delivery.entity; + +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import lombok.AllArgsConstructor; +import lombok.Data; +import lombok.NoArgsConstructor; + +import java.util.List; +import edu.fudan.common.entity.Food; + +@Data +@NoArgsConstructor +@AllArgsConstructor +@JsonIgnoreProperties(ignoreUnknown = true) +public class StationFoodStoreInfo { + + private String id; + + private String stationId; + + private String storeName; + + private String telephone; + + private String businessTime; + + private double deliveryFee; + + private List foodList; + +} diff --git a/ts-food-delivery-service/src/main/java/food_delivery/entity/TripOrderInfo.java b/ts-food-delivery-service/src/main/java/food_delivery/entity/TripOrderInfo.java new file mode 100644 index 000000000..eda0a58a5 --- /dev/null +++ b/ts-food-delivery-service/src/main/java/food_delivery/entity/TripOrderInfo.java @@ -0,0 +1,13 @@ +package food_delivery.entity; + +import lombok.AllArgsConstructor; +import lombok.Data; +import lombok.NoArgsConstructor; + +@Data +@NoArgsConstructor +@AllArgsConstructor +public class TripOrderInfo { + private String orderId; + private String tripId; +} diff --git a/ts-food-delivery-service/src/main/java/food_delivery/init/InitData.java b/ts-food-delivery-service/src/main/java/food_delivery/init/InitData.java new file mode 100644 index 000000000..90b99061b --- /dev/null +++ b/ts-food-delivery-service/src/main/java/food_delivery/init/InitData.java @@ -0,0 +1,54 @@ +package food_delivery.init; + +import food_delivery.service.FoodDeliveryService; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.CommandLineRunner; +import org.springframework.stereotype.Component; + +import java.io.BufferedReader; +import java.io.InputStreamReader; +import edu.fudan.common.entity.Food; + +@Component +public class InitData implements CommandLineRunner { + + @Autowired + FoodDeliveryService foodDeliveryService; + + private static final Logger LOGGER = LoggerFactory.getLogger(InitData.class); + + + @Override + public void run(String... args) { + BufferedReader br = new BufferedReader(new InputStreamReader(this.getClass().getResourceAsStream("/food_delivery_orders.txt"))); + try { // 有限制,不能随意init初始化数据,因此先注释掉。 +// String line; +// while ((line = br.readLine()) != null) { +// String[] strs = line.trim().split("\\|"); +// String[] foods = strs[1].trim().split(","); +// List foodList = new ArrayList<>(); +// for (String food : foods) { +// String[] food_info = food.trim().split("_"); +// foodList.add(new Food(food_info[0], Double.parseDouble(food_info[1]))); +// } +// FoodDeliveryOrder foodDeliveryOrder = new FoodDeliveryOrder( +// UUID.randomUUID().toString(), // id +// strs[0], // stationFoodStoreId +// foodList, // foodList +// strs[2], // tripId +// Integer.parseInt(strs[3]), // seatNo +// strs[4], // createdTime +// strs[5], // deliveryTime +// Double.parseDouble(strs[6]) // deliveryFee +// ); +// foodDeliveryService.createFoodDeliveryOrder(foodDeliveryOrder, null); +// } + } catch(Exception e) { + InitData.LOGGER.info("food_delivery_orders.txt has format error!"); + InitData.LOGGER.error(e.getMessage()); + System.exit(1); + } + } +} diff --git a/ts-food-delivery-service/src/main/java/food_delivery/repository/FoodDeliveryOrderRepository.java b/ts-food-delivery-service/src/main/java/food_delivery/repository/FoodDeliveryOrderRepository.java new file mode 100644 index 000000000..e4bce03a1 --- /dev/null +++ b/ts-food-delivery-service/src/main/java/food_delivery/repository/FoodDeliveryOrderRepository.java @@ -0,0 +1,15 @@ +package food_delivery.repository; + +import food_delivery.entity.FoodDeliveryOrder; +import org.springframework.data.repository.CrudRepository; + +import java.util.List; + +public interface FoodDeliveryOrderRepository extends CrudRepository { + + List findByStationFoodStoreId(String stationFoodStoreId); + + @Override + List findAll(); + +} diff --git a/ts-food-delivery-service/src/main/java/food_delivery/service/FoodDeliveryService.java b/ts-food-delivery-service/src/main/java/food_delivery/service/FoodDeliveryService.java new file mode 100644 index 000000000..8a6c76abe --- /dev/null +++ b/ts-food-delivery-service/src/main/java/food_delivery/service/FoodDeliveryService.java @@ -0,0 +1,27 @@ +package food_delivery.service; + +import edu.fudan.common.util.Response; +import food_delivery.entity.DeliveryInfo; +import food_delivery.entity.FoodDeliveryOrder; +import food_delivery.entity.SeatInfo; +import food_delivery.entity.TripOrderInfo; +import org.springframework.http.HttpHeaders; + +public interface FoodDeliveryService { + + Response createFoodDeliveryOrder(FoodDeliveryOrder fd, HttpHeaders headers); + + Response deleteFoodDeliveryOrder(String id, HttpHeaders headers); + + Response getFoodDeliveryOrderById(String id, HttpHeaders headers); + + Response getAllFoodDeliveryOrders(HttpHeaders headers); + + Response getFoodDeliveryOrderByStoreId(String storeId, HttpHeaders headers); + + Response updateTripId(TripOrderInfo tripOrderInfo, HttpHeaders headers); + + Response updateSeatNo(SeatInfo seatInfo, HttpHeaders headers); + + Response updateDeliveryTime(DeliveryInfo deliveryInfo, HttpHeaders headers); +} diff --git a/ts-food-delivery-service/src/main/java/food_delivery/service/FoodDeliveryServiceImpl.java b/ts-food-delivery-service/src/main/java/food_delivery/service/FoodDeliveryServiceImpl.java new file mode 100644 index 000000000..5447bdd7f --- /dev/null +++ b/ts-food-delivery-service/src/main/java/food_delivery/service/FoodDeliveryServiceImpl.java @@ -0,0 +1,172 @@ +package food_delivery.service; + + +import edu.fudan.common.util.Response; +import food_delivery.entity.*; +import edu.fudan.common.entity.*; +import food_delivery.repository.FoodDeliveryOrderRepository; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.cloud.client.ServiceInstance; +import org.springframework.cloud.client.discovery.DiscoveryClient; +import org.springframework.core.ParameterizedTypeReference; +import org.springframework.http.HttpEntity; +import org.springframework.http.HttpHeaders; +import org.springframework.http.HttpMethod; +import org.springframework.http.ResponseEntity; +import org.springframework.stereotype.Service; +import org.springframework.web.client.RestTemplate; + +import java.util.List; +import java.util.Map; +import java.util.stream.Collectors; + +@Service +public class FoodDeliveryServiceImpl implements FoodDeliveryService { + + @Autowired + FoodDeliveryOrderRepository foodDeliveryOrderRepository; + + private static final Logger LOGGER = LoggerFactory.getLogger(FoodDeliveryServiceImpl.class); + + @Autowired + private RestTemplate restTemplate; + + @Autowired + private DiscoveryClient discoveryClient; + + private String getServiceUrl(String serviceName) { + return "http://" + serviceName; + } + + @Override + public Response createFoodDeliveryOrder(FoodDeliveryOrder fd, HttpHeaders headers) { + String stationFoodStoreId = fd.getStationFoodStoreId(); + + String staion_food_service_url = getServiceUrl("ts-station-food-service"); +// staion_food_service_url = "http://ts-station-food-service"; // 测试 + ResponseEntity> getStationFoodStore = restTemplate.exchange( + staion_food_service_url + "/api/v1/stationfoodservice/stationfoodstores/bystoreid/" + stationFoodStoreId, + HttpMethod.GET, + new HttpEntity(headers), + new ParameterizedTypeReference>() { + }); + Response result = getStationFoodStore.getBody(); + StationFoodStoreInfo stationFoodStoreInfo = result.getData(); + List storeFoodList = stationFoodStoreInfo.getFoodList(); + Map foodPrice = storeFoodList.stream() + .collect(Collectors.toMap(Food::getFoodName, Food::getPrice)); + List orderFoodList = fd.getFoodList(); + double deliveryFee = 0; + for (Food food : orderFoodList) { + Double fee = foodPrice.get(food.getFoodName()); + if (fee == null) { + LOGGER.error("{}:{} have no such food: {}", stationFoodStoreId, stationFoodStoreInfo.getStoreName(), food.getFoodName()); + return new Response<>(0, "Food not in store", null); + } + deliveryFee += fee; + } + deliveryFee += stationFoodStoreInfo.getDeliveryFee(); + fd.setDeliveryFee(deliveryFee); + FoodDeliveryOrder res = foodDeliveryOrderRepository.save(fd); + return new Response<>(1, "Save success", res); + } + + @Override + public Response deleteFoodDeliveryOrder(String id, HttpHeaders headers) { + FoodDeliveryOrder t = foodDeliveryOrderRepository.findById(id).orElse(null); + if (t == null) { + LOGGER.error("[deleteFoodDeliveryOrder] No such food delivery order id: {}", id); + return new Response<>(0, "No such food delivery order id", id); + } else { + foodDeliveryOrderRepository.deleteById(id); + LOGGER.info("[deleteFoodDeliveryOrder] Delete success, food delivery order id: {}", id); + return new Response<>(1, "Delete success", null); + } + } + + @Override + public Response getFoodDeliveryOrderById(String id, HttpHeaders headers) { + FoodDeliveryOrder t = foodDeliveryOrderRepository.findById(id).orElse(null); + if (t == null) { + LOGGER.error("[deleteFoodDeliveryOrder] No such food delivery order id: {}", id); + return new Response<>(0, "No such food delivery order id", id); + } else { + LOGGER.info("[getFoodDeliveryOrderById] Get success, food delivery order id: {}", id); + return new Response<>(1, "Get success", t); + } + } + + @Override + public Response getAllFoodDeliveryOrders(HttpHeaders headers) { + List foodDeliveryOrders = foodDeliveryOrderRepository.findAll(); + if (foodDeliveryOrders == null) { + LOGGER.error("[getAllFoodDeliveryOrders] Food delivery orders query error"); + return new Response<>(0, "food delivery orders query error", null); + } else { + LOGGER.info("[getAllFoodDeliveryOrders] Get all food delivery orders success"); + return new Response<>(1, "Get success", foodDeliveryOrders); + } + } + + @Override + public Response getFoodDeliveryOrderByStoreId(String storeId, HttpHeaders headers) { + List foodDeliveryOrders = foodDeliveryOrderRepository.findByStationFoodStoreId(storeId); + if (foodDeliveryOrders == null) { + LOGGER.error("[getAllFoodDeliveryOrders] Food delivery orders query error"); + return new Response<>(0, "food delivery orders query error", storeId); + } else { + LOGGER.info("[getAllFoodDeliveryOrders] Get food delivery orders by storeId {} success", storeId); + return new Response<>(1, "Get success", foodDeliveryOrders); + } + } + + @Override + public Response updateTripId(TripOrderInfo tripInfo, HttpHeaders headers) { + String id = tripInfo.getOrderId(); + String tripId = tripInfo.getTripId(); + FoodDeliveryOrder t = foodDeliveryOrderRepository.findById(id).orElse(null); + if (t == null) { + LOGGER.error("[updateTripId] No such delivery order id: {}", id); + return new Response<>(0, "No such delivery order id", id); + } else { + t.setTripId(tripId); + foodDeliveryOrderRepository.save(t); + LOGGER.info("[updateTripId] update tripId success. id:{}, tripId:{}", id, tripId); + return new Response<>(1, "update tripId success", t); + } + } + + @Override + public Response updateSeatNo(SeatInfo seatInfo, HttpHeaders headers) { + String id = seatInfo.getOrderId(); + int seatNo = seatInfo.getSeatNo(); + FoodDeliveryOrder t = foodDeliveryOrderRepository.findById(id).orElse(null); + if (t == null) { + LOGGER.error("[updateSeatNo] No such delivery order id: {}", id); + return new Response<>(0, "No such delivery order id", id); + } else { + t.setSeatNo(seatNo); + foodDeliveryOrderRepository.save(t); + LOGGER.info("[updateSeatNo] update seatNo success. id:{}, seatNo:{}", id, seatNo); + return new Response<>(1, "update seatNo success", t); + } + } + + @Override + public Response updateDeliveryTime(DeliveryInfo deliveryInfo, HttpHeaders headers) { + String id = deliveryInfo.getOrderId(); + String deliveryTime = deliveryInfo.getDeliveryTime(); + FoodDeliveryOrder t = foodDeliveryOrderRepository.findById(id).orElse(null); + if (t == null) { + LOGGER.error("[updateDeliveryTime] No such delivery order id: {}", id); + return new Response<>(0, "No such delivery order id", id); + } else { + t.setDeliveryTime(deliveryTime); + foodDeliveryOrderRepository.save(t); + LOGGER.info("[updateDeliveryTime] update deliveryTime success. id:{}, deliveryTime:{}", id, deliveryTime); + return new Response<>(1, "update deliveryTime success", t); + } + } +} diff --git a/ts-food-delivery-service/src/main/resources/application.yml b/ts-food-delivery-service/src/main/resources/application.yml new file mode 100644 index 000000000..1dfe690ae --- /dev/null +++ b/ts-food-delivery-service/src/main/resources/application.yml @@ -0,0 +1,26 @@ +server: + port: 18957 + +spring: + cloud: + nacos: + discovery: + server-addr: ${NACOS_ADDRS:nacos-0.nacos-headless.default.svc.cluster.local,nacos-1.nacos-headless.default.svc.cluster.local,nacos-2.nacos-headless.default.svc.cluster.local} +# server-addr: 10.176.122.80:8848 + application: + name: ts-food-delivery-service + datasource: +# url: jdbc:mysql://localhost:30001/ts-food-delivery-mysql?useSSL=false + url: jdbc:mysql://${FOOD_DELIVERY_MYSQL_HOST:ts-food-delivery-mysql}:${FOOD_DELIVERY_MYSQL_PORT:3306}/${FOOD_DELIVERY_MYSQL_DATABASE:ts-food-delivery-mysql}?useSSL=false + username: ${FOOD_DELIVERY_MYSQL_USER:root} + password: ${FOOD_DELIVERY_MYSQL_PASSWORD:root} + driver-class-name: com.mysql.jdbc.Driver + jpa: + hibernate: + ddl-auto: update + properties: + hibernate: + dialect: org.hibernate.dialect.MySQL5Dialect + +swagger: + controllerPackage: fooddelivery.controller \ No newline at end of file diff --git a/ts-food-delivery-service/src/main/resources/food_delivery_orders.txt b/ts-food-delivery-service/src/main/resources/food_delivery_orders.txt new file mode 100644 index 000000000..511b58693 --- /dev/null +++ b/ts-food-delivery-service/src/main/resources/food_delivery_orders.txt @@ -0,0 +1,5 @@ +random_station_food_store_id_1|food1_13.5,food2_13.5,food3_13.5,food4_13.5,food5_13.5|random_trip_id_1|101|random_created_time_1|random_delivery_time1|1.88 +random_station_food_store_id_2|food1_13.5,food4_13.5,food7_13.5|random_trip_id_2|102|random_created_time_2|random_delivery_time2|2.88 +random_station_food_store_id_3|food2_13.5,food6_13.5,food10_13.5|random_trip_id_3|103|random_created_time_3|random_delivery_time3|3.88 +random_station_food_store_id_4|food3_13.5,food4_13.5,food5_13.5|random_trip_id_4|104|random_created_time_4|random_delivery_time4|4.88 +random_station_food_store_id_5|food2_13.5,food7_13.5,food9_13.5|random_trip_id_5|105|random_created_time_5|random_delivery_time5|5.88 \ No newline at end of file diff --git a/ts-food-delivery-service/src/test/java/food_delivery/controller/FoodDeliveryControllerTest.java b/ts-food-delivery-service/src/test/java/food_delivery/controller/FoodDeliveryControllerTest.java new file mode 100644 index 000000000..4c389751f --- /dev/null +++ b/ts-food-delivery-service/src/test/java/food_delivery/controller/FoodDeliveryControllerTest.java @@ -0,0 +1,130 @@ +package food_delivery.controller; + +import com.alibaba.fastjson.JSONObject; +import edu.fudan.common.util.Response; +import food_delivery.entity.DeliveryInfo; +import food_delivery.entity.FoodDeliveryOrder; +import food_delivery.entity.SeatInfo; +import food_delivery.entity.TripOrderInfo; +import food_delivery.service.FoodDeliveryService; +import org.junit.Assert; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.junit.runners.JUnit4; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.Mockito; +import org.mockito.MockitoAnnotations; +import org.springframework.http.HttpHeaders; +import org.springframework.http.MediaType; +import org.springframework.test.web.servlet.MockMvc; +import org.springframework.test.web.servlet.request.MockMvcRequestBuilders; +import org.springframework.test.web.servlet.result.MockMvcResultMatchers; +import org.springframework.test.web.servlet.setup.MockMvcBuilders; + +@RunWith(JUnit4.class) +public class FoodDeliveryControllerTest { + + @InjectMocks + private FoodDeliveryController foodDeliveryController; + + @Mock + private FoodDeliveryService foodDeliveryService; + private MockMvc mockMvc; + private Response response = new Response(); + + @Before + public void setUp() { + MockitoAnnotations.initMocks(this); + mockMvc = MockMvcBuilders.standaloneSetup(foodDeliveryController).build(); + } + + @Test + public void testHome() throws Exception { + mockMvc.perform(MockMvcRequestBuilders.get("/api/v1/fooddeliveryservice/welcome")) + .andExpect(MockMvcResultMatchers.status().isOk()) + .andExpect(MockMvcResultMatchers.content().string("Welcome to [ food delivery service ] !")); + } + + @Test + public void testCreateFoodDeliveryOrder() throws Exception { + FoodDeliveryOrder foodDeliveryOrder = new FoodDeliveryOrder(); + Mockito.when(foodDeliveryService.createFoodDeliveryOrder(Mockito.any(FoodDeliveryOrder.class), Mockito.any(HttpHeaders.class))).thenReturn(response); + String requestJson = JSONObject.toJSONString(foodDeliveryOrder); + String result = mockMvc.perform(MockMvcRequestBuilders.post("/api/v1/fooddeliveryservice/orders").contentType(MediaType.APPLICATION_JSON).content(requestJson)) + .andExpect(MockMvcResultMatchers.status().isOk()) + .andReturn().getResponse().getContentAsString(); + Assert.assertEquals(response, JSONObject.parseObject(result, Response.class)); + } + + @Test + public void testDeleteFoodDeliveryOrder() throws Exception { + Mockito.when(foodDeliveryService.deleteFoodDeliveryOrder(Mockito.anyString(), Mockito.any(HttpHeaders.class))).thenReturn(response); + String result = mockMvc.perform(MockMvcRequestBuilders.delete("/api/v1/fooddeliveryservice/orders/d/123")) + .andExpect(MockMvcResultMatchers.status().isOk()) + .andReturn().getResponse().getContentAsString(); + Assert.assertEquals(response, JSONObject.parseObject(result, Response.class)); + } + + @Test + public void testGetFoodDeliveryOrderById() throws Exception { + Mockito.when(foodDeliveryService.getFoodDeliveryOrderById(Mockito.anyString(), Mockito.any(HttpHeaders.class))).thenReturn(response); + String result = mockMvc.perform(MockMvcRequestBuilders.get("/api/v1/fooddeliveryservice/orders/123")) + .andExpect(MockMvcResultMatchers.status().isOk()) + .andReturn().getResponse().getContentAsString(); + Assert.assertEquals(response, JSONObject.parseObject(result, Response.class)); + } + + @Test + public void testGetFoodDeliveryOrderByStoreId() throws Exception { + Mockito.when(foodDeliveryService.getFoodDeliveryOrderByStoreId(Mockito.anyString(), Mockito.any(HttpHeaders.class))).thenReturn(response); + String result = mockMvc.perform(MockMvcRequestBuilders.get("/api/v1/fooddeliveryservice/orders/store/1234")) + .andExpect(MockMvcResultMatchers.status().isOk()) + .andReturn().getResponse().getContentAsString(); + Assert.assertEquals(response, JSONObject.parseObject(result, Response.class)); + } + + @Test + public void testGetAllFoodDeliveryOrders() throws Exception { + Mockito.when(foodDeliveryService.getAllFoodDeliveryOrders(Mockito.any(HttpHeaders.class))).thenReturn(response); + String result = mockMvc.perform(MockMvcRequestBuilders.get("/api/v1/fooddeliveryservice/orders/all")) + .andExpect(MockMvcResultMatchers.status().isOk()) + .andReturn().getResponse().getContentAsString(); + Assert.assertEquals(response, JSONObject.parseObject(result, Response.class)); + } + + @Test + public void testUpdateTripId() throws Exception { + TripOrderInfo tripOrderInfo = new TripOrderInfo(); + Mockito.when(foodDeliveryService.updateTripId(Mockito.any(TripOrderInfo.class), Mockito.any(HttpHeaders.class))).thenReturn(response); + String requestJson = JSONObject.toJSONString(tripOrderInfo); + String result = mockMvc.perform(MockMvcRequestBuilders.put("/api/v1/fooddeliveryservice/orders/tripid").contentType(MediaType.APPLICATION_JSON).content(requestJson)) + .andExpect(MockMvcResultMatchers.status().isOk()) + .andReturn().getResponse().getContentAsString(); + Assert.assertEquals(response, JSONObject.parseObject(result, Response.class)); + } + + @Test + public void testUpdateSeatNo() throws Exception { + SeatInfo seatInfo = new SeatInfo(); + Mockito.when(foodDeliveryService.updateSeatNo(Mockito.any(SeatInfo.class), Mockito.any(HttpHeaders.class))).thenReturn(response); + String requestJson = JSONObject.toJSONString(seatInfo); + String result = mockMvc.perform(MockMvcRequestBuilders.put("/api/v1/fooddeliveryservice/orders/seatno").contentType(MediaType.APPLICATION_JSON).content(requestJson)) + .andExpect(MockMvcResultMatchers.status().isOk()) + .andReturn().getResponse().getContentAsString(); + Assert.assertEquals(response, JSONObject.parseObject(result, Response.class)); + } + + @Test + public void testUpdateDeliveryTime() throws Exception { + DeliveryInfo deliveryInfo = new DeliveryInfo(); + Mockito.when(foodDeliveryService.updateDeliveryTime(Mockito.any(DeliveryInfo.class), Mockito.any(HttpHeaders.class))).thenReturn(response); + String requestJson = JSONObject.toJSONString(deliveryInfo); + String result = mockMvc.perform(MockMvcRequestBuilders.put("/api/v1/fooddeliveryservice/orders/dtime").contentType(MediaType.APPLICATION_JSON).content(requestJson)) + .andExpect(MockMvcResultMatchers.status().isOk()) + .andReturn().getResponse().getContentAsString(); + Assert.assertEquals(response, JSONObject.parseObject(result, Response.class)); + } + +} diff --git a/ts-food-delivery-service/src/test/java/food_delivery/service/FoodDeliveryServiceImplTest.java b/ts-food-delivery-service/src/test/java/food_delivery/service/FoodDeliveryServiceImplTest.java new file mode 100644 index 000000000..5e0559a18 --- /dev/null +++ b/ts-food-delivery-service/src/test/java/food_delivery/service/FoodDeliveryServiceImplTest.java @@ -0,0 +1,26 @@ +package food_delivery.service; + +import org.junit.Before; +import org.junit.Test; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.MockitoAnnotations; +import org.springframework.http.*; +import org.springframework.web.client.RestTemplate; + +public class FoodDeliveryServiceImplTest { + @InjectMocks + private FoodDeliveryServiceImpl foodDeliveryServiceImpl; + + @Mock + private RestTemplate restTemplate; + + private HttpHeaders headers = new HttpHeaders(); + private HttpEntity requestEntity = new HttpEntity(headers); + + @Before + public void setUp() { + MockitoAnnotations.initMocks(this); + } + +} diff --git a/ts-food-map-service/src/main/java/food/controller/FoodStoreController.java b/ts-food-map-service/src/main/java/food/controller/FoodStoreController.java deleted file mode 100644 index 0ea96fc18..000000000 --- a/ts-food-map-service/src/main/java/food/controller/FoodStoreController.java +++ /dev/null @@ -1,49 +0,0 @@ -package food.controller; - -import food.service.FoodMapService; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.http.HttpEntity; -import org.springframework.http.HttpHeaders; -import org.springframework.web.bind.annotation.*; - -import java.util.List; - -import static org.springframework.http.ResponseEntity.ok; - -@RestController -@RequestMapping("/api/v1/foodmapservice") -public class FoodStoreController { - - @Autowired - FoodMapService foodMapService; - - private static final Logger LOGGER = LoggerFactory.getLogger(FoodStoreController.class); - - @GetMapping(path = "/foodstores/welcome") - public String home() { - return "Welcome to [ Food store Service ] !"; - } - - @CrossOrigin(origins = "*") - @GetMapping("/foodstores") - public HttpEntity getAllFoodStores(@RequestHeader HttpHeaders headers) { - FoodStoreController.LOGGER.info("[Food Map Service][Get All FoodStores]"); - return ok(foodMapService.listFoodStores(headers)); - } - - @CrossOrigin(origins = "*") - @GetMapping("/foodstores/{stationId}") - public HttpEntity getFoodStoresOfStation(@PathVariable String stationId, @RequestHeader HttpHeaders headers) { - FoodStoreController.LOGGER.info("[Food Map Service][Get FoodStores By StationId]"); - return ok(foodMapService.listFoodStoresByStationId(stationId, headers)); - } - - @CrossOrigin(origins = "*") - @PostMapping("/foodstores") - public HttpEntity getFoodStoresByStationIds(@RequestBody List stationIdList) { - FoodStoreController.LOGGER.info("[Food Map Service][Get FoodStores By StationIds]"); - return ok(foodMapService.getFoodStoresByStationIds(stationIdList)); - } -} diff --git a/ts-food-map-service/src/main/java/food/entity/FoodStore.java b/ts-food-map-service/src/main/java/food/entity/FoodStore.java deleted file mode 100644 index f2cf06dcc..000000000 --- a/ts-food-map-service/src/main/java/food/entity/FoodStore.java +++ /dev/null @@ -1,38 +0,0 @@ -package food.entity; - -import com.fasterxml.jackson.annotation.JsonIgnoreProperties; -import lombok.Data; -import org.springframework.data.annotation.Id; -import org.springframework.data.mongodb.core.mapping.Document; - -import javax.validation.constraints.NotNull; -import java.util.List; -import java.util.UUID; - -@Data -@Document(collection = "stores") -@JsonIgnoreProperties(ignoreUnknown = true) -public class FoodStore { - - @Id - private UUID id; - - @NotNull - private String stationId; - - private String storeName; - - private String telephone; - - private String businessTime; - - private double deliveryFee; - - private List foodList; - - public FoodStore(){ - //Default Constructor - this.stationId = ""; - } - -} diff --git a/ts-food-map-service/src/main/java/food/entity/TrainFood.java b/ts-food-map-service/src/main/java/food/entity/TrainFood.java deleted file mode 100644 index c40044f3c..000000000 --- a/ts-food-map-service/src/main/java/food/entity/TrainFood.java +++ /dev/null @@ -1,30 +0,0 @@ -package food.entity; - -import com.fasterxml.jackson.annotation.JsonIgnoreProperties; -import lombok.Data; -import org.springframework.data.annotation.Id; -import org.springframework.data.mongodb.core.mapping.Document; - -import javax.validation.constraints.NotNull; -import java.util.List; -import java.util.UUID; - -@Data -@Document(collection = "trainfoods") -@JsonIgnoreProperties(ignoreUnknown = true) -public class TrainFood { - - @Id - private UUID id; - - @NotNull - private String tripId; - - private List foodList; - - public TrainFood(){ - //Default Constructor - this.tripId = ""; - } - -} diff --git a/ts-food-map-service/src/main/java/food/repository/FoodStoreRepository.java b/ts-food-map-service/src/main/java/food/repository/FoodStoreRepository.java deleted file mode 100644 index e23ec6e41..000000000 --- a/ts-food-map-service/src/main/java/food/repository/FoodStoreRepository.java +++ /dev/null @@ -1,25 +0,0 @@ -package food.repository; - -import food.entity.FoodStore; -import org.springframework.data.mongodb.repository.MongoRepository; -import org.springframework.data.mongodb.repository.Query; -import org.springframework.stereotype.Repository; - -import java.util.List; -import java.util.UUID; - -@Repository -public interface FoodStoreRepository extends MongoRepository { - - FoodStore findById(UUID id); - - @Query("{ 'stationId' : ?0 }") - List findByStationId(String stationId); - List findByStationIdIn(List stationIds); - - - @Override - List findAll(); - - void deleteById(UUID id); -} diff --git a/ts-food-map-service/src/main/java/food/repository/TrainFoodRepository.java b/ts-food-map-service/src/main/java/food/repository/TrainFoodRepository.java deleted file mode 100644 index c00b2e3bc..000000000 --- a/ts-food-map-service/src/main/java/food/repository/TrainFoodRepository.java +++ /dev/null @@ -1,24 +0,0 @@ -package food.repository; - - -import food.entity.TrainFood; -import org.springframework.data.mongodb.repository.MongoRepository; -import org.springframework.data.mongodb.repository.Query; -import org.springframework.stereotype.Repository; - -import java.util.List; -import java.util.UUID; - -@Repository -public interface TrainFoodRepository extends MongoRepository { - - TrainFood findById(UUID id); - - @Override - List findAll(); - - @Query("{ 'tripId' : ?0 }") - List findByTripId(String tripId); - - void deleteById(UUID id); -} diff --git a/ts-food-map-service/src/main/java/food/service/FoodMapService.java b/ts-food-map-service/src/main/java/food/service/FoodMapService.java deleted file mode 100644 index ab6e0c7c4..000000000 --- a/ts-food-map-service/src/main/java/food/service/FoodMapService.java +++ /dev/null @@ -1,27 +0,0 @@ -package food.service; - -import edu.fudan.common.util.Response; -import food.entity.*; -import org.springframework.http.HttpHeaders; - -import java.util.List; - -public interface FoodMapService { - - // create data - Response createFoodStore(FoodStore fs, HttpHeaders headers); - - TrainFood createTrainFood(TrainFood tf, HttpHeaders headers); - - // query all food - Response listFoodStores(HttpHeaders headers); - - Response listTrainFood(HttpHeaders headers); - - // query according id - Response listFoodStoresByStationId(String stationId, HttpHeaders headers); - - Response listTrainFoodByTripId(String tripId, HttpHeaders headers); - - Response getFoodStoresByStationIds(List stationIds); -} diff --git a/ts-food-map-service/src/main/java/food/service/FoodMapServiceImpl.java b/ts-food-map-service/src/main/java/food/service/FoodMapServiceImpl.java deleted file mode 100644 index a12273305..000000000 --- a/ts-food-map-service/src/main/java/food/service/FoodMapServiceImpl.java +++ /dev/null @@ -1,108 +0,0 @@ -package food.service; - -import edu.fudan.common.util.Response; -import food.entity.FoodStore; -import food.entity.TrainFood; -import food.repository.FoodStoreRepository; -import food.repository.TrainFoodRepository; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.http.HttpHeaders; -import org.springframework.stereotype.Service; - -import java.util.List; - - -@Service -public class FoodMapServiceImpl implements FoodMapService { - - @Autowired - FoodStoreRepository foodStoreRepository; - - @Autowired - TrainFoodRepository trainFoodRepository; - - private static final Logger LOGGER = LoggerFactory.getLogger(FoodMapServiceImpl.class); - - String success = "Success"; - String noContent = "No content"; - - @Override - public Response createFoodStore(FoodStore fs, HttpHeaders headers) { - FoodStore fsTemp = foodStoreRepository.findById(fs.getId()); - if (fsTemp != null) { - FoodMapServiceImpl.LOGGER.error("[Init FoodStore] Already Exists Id: {}", fs.getId()); - return new Response<>(0, "Already Exists Id", null); - } else { - foodStoreRepository.save(fs); - return new Response<>(1, "Save Success", fs); - } - } - - @Override - public TrainFood createTrainFood(TrainFood tf, HttpHeaders headers) { - TrainFood tfTemp = trainFoodRepository.findById(tf.getId()); - if (tfTemp != null) { - FoodMapServiceImpl.LOGGER.error("[Init TrainFood] Already Exists Id: {}", tf.getId()); - } else { - trainFoodRepository.save(tf); - } - return tf; - } - - @Override - public Response listFoodStores(HttpHeaders headers) { - List foodStores = foodStoreRepository.findAll(); - if (foodStores != null && !foodStores.isEmpty()) { - return new Response<>(1, success, foodStores); - } else { - FoodMapServiceImpl.LOGGER.error("List food stores error: {}", "Food store is empty"); - return new Response<>(0, "Food store is empty", null); - } - } - - @Override - public Response listTrainFood(HttpHeaders headers) { - List trainFoodList = trainFoodRepository.findAll(); - if (trainFoodList != null && !trainFoodList.isEmpty()) { - return new Response<>(1, success, trainFoodList); - } else { - FoodMapServiceImpl.LOGGER.error("List train food error: {}", noContent); - return new Response<>(0, noContent, null); - } - } - - @Override - public Response listFoodStoresByStationId(String stationId, HttpHeaders headers) { - List foodStoreList = foodStoreRepository.findByStationId(stationId); - if (foodStoreList != null && !foodStoreList.isEmpty()) { - return new Response<>(1, success, foodStoreList); - } else { - FoodMapServiceImpl.LOGGER.error("List food stores by station id error: {}, stationId: {}", "Food store is empty", stationId); - return new Response<>(0, "Food store is empty", null); - } - } - - @Override - public Response listTrainFoodByTripId(String tripId, HttpHeaders headers) { - List trainFoodList = trainFoodRepository.findByTripId(tripId); - if (trainFoodList != null) { - return new Response<>(1, success, trainFoodList); - } else { - FoodMapServiceImpl.LOGGER.error("List train food by trip id error: {}, tripId: {}", noContent, tripId); - return new Response<>(0, noContent, null); - } - } - - @Override - public Response getFoodStoresByStationIds(List stationIds) { - List foodStoreList = foodStoreRepository.findByStationIdIn(stationIds); - if (foodStoreList != null) { - return new Response<>(1, success, foodStoreList); - } else { - FoodMapServiceImpl.LOGGER.error("List food stores by station ids error: {}, stationId list: {}", "Food store is empty", stationIds); - return new Response<>(0, noContent, null); - } - } -} diff --git a/ts-food-map-service/src/main/resources/application.yml b/ts-food-map-service/src/main/resources/application.yml deleted file mode 100644 index 7289f1766..000000000 --- a/ts-food-map-service/src/main/resources/application.yml +++ /dev/null @@ -1,16 +0,0 @@ -server: - port: 18855 - -spring: - application: - name: ts-food-map-service - data: - mongodb: - host: ts-food-map-mongo -# username: user -# password: ${MONGODB_PASSWORD} - database: ts - port: 27017 - -swagger: - controllerPackage: food.controller \ No newline at end of file diff --git a/ts-food-map-service/src/test/java/food/controller/TrainFoodControllerTest.java b/ts-food-map-service/src/test/java/food/controller/TrainFoodControllerTest.java deleted file mode 100644 index 0bc76e083..000000000 --- a/ts-food-map-service/src/test/java/food/controller/TrainFoodControllerTest.java +++ /dev/null @@ -1,63 +0,0 @@ -package food.controller; - -import com.alibaba.fastjson.JSONObject; -import edu.fudan.common.util.Response; -import food.service.FoodMapService; -import org.junit.Assert; -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.JUnit4; -import org.mockito.InjectMocks; -import org.mockito.Mock; -import org.mockito.Mockito; -import org.mockito.MockitoAnnotations; -import org.springframework.http.HttpHeaders; -import org.springframework.test.web.servlet.MockMvc; -import org.springframework.test.web.servlet.request.MockMvcRequestBuilders; -import org.springframework.test.web.servlet.result.MockMvcResultMatchers; -import org.springframework.test.web.servlet.setup.MockMvcBuilders; - -@RunWith(JUnit4.class) -public class TrainFoodControllerTest { - - @InjectMocks - private TrainFoodController trainFoodController; - - @Mock - private FoodMapService foodMapService; - private MockMvc mockMvc; - private Response response = new Response(); - - @Before - public void setUp() { - MockitoAnnotations.initMocks(this); - mockMvc = MockMvcBuilders.standaloneSetup(trainFoodController).build(); - } - - @Test - public void testHome() throws Exception { - mockMvc.perform(MockMvcRequestBuilders.get("/api/v1/foodmapservice/trainfoods/welcome")) - .andExpect(MockMvcResultMatchers.status().isOk()) - .andExpect(MockMvcResultMatchers.content().string("Welcome to [ Train Food Service ] !")); - } - - @Test - public void testGetAllTrainFood() throws Exception { - Mockito.when(foodMapService.listTrainFood(Mockito.any(HttpHeaders.class))).thenReturn(response); - String result = mockMvc.perform(MockMvcRequestBuilders.get("/api/v1/foodmapservice/trainfoods")) - .andExpect(MockMvcResultMatchers.status().isOk()) - .andReturn().getResponse().getContentAsString(); - Assert.assertEquals(response, JSONObject.parseObject(result, Response.class)); - } - - @Test - public void testGetTrainFoodOfTrip() throws Exception { - Mockito.when(foodMapService.listTrainFoodByTripId(Mockito.anyString(), Mockito.any(HttpHeaders.class))).thenReturn(response); - String result = mockMvc.perform(MockMvcRequestBuilders.get("/api/v1/foodmapservice/trainfoods/trip_id")) - .andExpect(MockMvcResultMatchers.status().isOk()) - .andReturn().getResponse().getContentAsString(); - Assert.assertEquals(response, JSONObject.parseObject(result, Response.class)); - } - -} diff --git a/ts-food-map-service/src/test/java/food/service/FoodMapServiceImplTest.java b/ts-food-map-service/src/test/java/food/service/FoodMapServiceImplTest.java deleted file mode 100644 index b01b388fe..000000000 --- a/ts-food-map-service/src/test/java/food/service/FoodMapServiceImplTest.java +++ /dev/null @@ -1,155 +0,0 @@ -package food.service; - -import edu.fudan.common.util.Response; -import food.entity.FoodStore; -import food.entity.TrainFood; -import food.repository.FoodStoreRepository; -import food.repository.TrainFoodRepository; -import org.junit.Assert; -import org.junit.Before; -import org.junit.Test; -import org.mockito.InjectMocks; -import org.mockito.Mock; -import org.mockito.Mockito; -import org.mockito.MockitoAnnotations; -import org.springframework.http.HttpHeaders; - -import java.util.ArrayList; -import java.util.List; -import java.util.UUID; - -public class FoodMapServiceImplTest { - - @InjectMocks - private FoodMapServiceImpl foodMapServiceImpl; - - @Mock - private FoodStoreRepository foodStoreRepository; - - @Mock - private TrainFoodRepository trainFoodRepository; - - private HttpHeaders headers = new HttpHeaders(); - - @Before - public void setUp() { - MockitoAnnotations.initMocks(this); - } - - @Test - public void testCreateFoodStore1() { - FoodStore fs = new FoodStore(); - Mockito.when(foodStoreRepository.findById(Mockito.any(UUID.class))).thenReturn(fs); - Response result = foodMapServiceImpl.createFoodStore(fs, headers); - Assert.assertEquals(new Response<>(0, "Already Exists Id", null), result); - } - - @Test - public void testCreateFoodStore2() { - FoodStore fs = new FoodStore(); - Mockito.when(foodStoreRepository.findById(Mockito.any(UUID.class))).thenReturn(null); - Mockito.when(foodStoreRepository.save(Mockito.any(FoodStore.class))).thenReturn(null); - Response result = foodMapServiceImpl.createFoodStore(fs, headers); - Assert.assertEquals(new Response<>(1, "Save Success", fs), result); - } - - @Test - public void testCreateTrainFood1() { - TrainFood tf = new TrainFood(); - Mockito.when(trainFoodRepository.findById(Mockito.any(UUID.class))).thenReturn(tf); - TrainFood result = foodMapServiceImpl.createTrainFood(tf, headers); - Assert.assertEquals(tf, result); - } - - @Test - public void testCreateTrainFood2() { - TrainFood tf = new TrainFood(); - Mockito.when(trainFoodRepository.findById(Mockito.any(UUID.class))).thenReturn(null); - Mockito.when(trainFoodRepository.save(Mockito.any(TrainFood.class))).thenReturn(null); - TrainFood result = foodMapServiceImpl.createTrainFood(tf, headers); - Assert.assertEquals(tf, result); - } - - @Test - public void testListFoodStores1() { - List foodStores = new ArrayList<>(); - foodStores.add(new FoodStore()); - Mockito.when(foodStoreRepository.findAll()).thenReturn(foodStores); - Response result = foodMapServiceImpl.listFoodStores(headers); - Assert.assertEquals(new Response<>(1, "Success", foodStores), result); - } - - @Test - public void testListFoodStores2() { - Mockito.when(foodStoreRepository.findAll()).thenReturn(null); - Response result = foodMapServiceImpl.listFoodStores(headers); - Assert.assertEquals(new Response<>(0, "Food store is empty", null), result); - } - - @Test - public void testListTrainFood1() { - List trainFoodList = new ArrayList<>(); - trainFoodList.add(new TrainFood()); - Mockito.when(trainFoodRepository.findAll()).thenReturn(trainFoodList); - Response result = foodMapServiceImpl.listTrainFood(headers); - Assert.assertEquals(new Response<>(1, "Success", trainFoodList), result); - } - - @Test - public void testListTrainFood2() { - Mockito.when(trainFoodRepository.findAll()).thenReturn(null); - Response result = foodMapServiceImpl.listTrainFood(headers); - Assert.assertEquals(new Response<>(0, "No content", null), result); - } - - @Test - public void testListFoodStoresByStationId1() { - List foodStoreList = new ArrayList<>(); - foodStoreList.add(new FoodStore()); - Mockito.when(foodStoreRepository.findByStationId(Mockito.anyString())).thenReturn(foodStoreList); - Response result = foodMapServiceImpl.listFoodStoresByStationId("station_id", headers); - Assert.assertEquals(new Response<>(1, "Success", foodStoreList), result); - } - - @Test - public void testListFoodStoresByStationId2() { - Mockito.when(foodStoreRepository.findByStationId(Mockito.anyString())).thenReturn(null); - Response result = foodMapServiceImpl.listFoodStoresByStationId("station_id", headers); - Assert.assertEquals(new Response<>(0, "Food store is empty", null), result); - } - - @Test - public void testListTrainFoodByTripId1() { - List trainFoodList = new ArrayList<>(); - trainFoodList.add(new TrainFood()); - Mockito.when(trainFoodRepository.findByTripId(Mockito.anyString())).thenReturn(trainFoodList); - Response result = foodMapServiceImpl.listTrainFoodByTripId("trip_id", headers); - Assert.assertEquals(new Response<>(1, "Success", trainFoodList), result); - } - - @Test - public void testListTrainFoodByTripId2() { - Mockito.when(trainFoodRepository.findByTripId(Mockito.anyString())).thenReturn(null); - Response result = foodMapServiceImpl.listTrainFoodByTripId("trip_id", headers); - Assert.assertEquals(new Response<>(0, "No content", null), result); - } - - @Test - public void testGetFoodStoresByStationIds1() { - List stationIds = new ArrayList<>(); - List foodStoreList = new ArrayList<>(); - foodStoreList.add(new FoodStore()); - Mockito.when(foodStoreRepository.findByStationIdIn(Mockito.anyList())).thenReturn(foodStoreList); - Response result = foodMapServiceImpl.getFoodStoresByStationIds(stationIds); - Assert.assertEquals(new Response<>(1, "Success", foodStoreList), result); - } - - @Test - public void testGetFoodStoresByStationIds2() { - List stationIds = new ArrayList<>(); - Mockito.when(foodStoreRepository.findByStationIdIn(Mockito.anyList())).thenReturn(null); - Response result = foodMapServiceImpl.getFoodStoresByStationIds(stationIds); - Assert.assertEquals(new Response<>(0, "No content", null), result); - } - -} diff --git a/ts-food-service/pom.xml b/ts-food-service/pom.xml index eab4c983b..72ef7bfee 100644 --- a/ts-food-service/pom.xml +++ b/ts-food-service/pom.xml @@ -15,7 +15,7 @@ org.services ts-service 0.1.0 - ../ + ../pom.xml @@ -26,29 +26,21 @@ org.springframework.boot - spring-boot-starter-web + spring-boot-starter-data-jpa - org.springframework.boot - spring-boot-starter-data-mongodb - - - org.springframework.boot - spring-boot-starter-actuator + mysql + mysql-connector-java - org.springframework.boot spring-boot-starter-amqp - org.services ts-common 0.1.0 - - diff --git a/ts-food-service/src/main/java/foodsearch/FoodApplication.java b/ts-food-service/src/main/java/foodsearch/FoodApplication.java index 1ca22e872..5eeaf3cd9 100644 --- a/ts-food-service/src/main/java/foodsearch/FoodApplication.java +++ b/ts-food-service/src/main/java/foodsearch/FoodApplication.java @@ -3,6 +3,8 @@ import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.boot.web.client.RestTemplateBuilder; +import org.springframework.cloud.client.discovery.EnableDiscoveryClient; +import org.springframework.cloud.client.loadbalancer.LoadBalanced; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.EnableAspectJAutoProxy; import org.springframework.integration.annotation.IntegrationComponentScan; @@ -15,12 +17,14 @@ @EnableAsync @IntegrationComponentScan @EnableSwagger2 +@EnableDiscoveryClient public class FoodApplication { public static void main(String[] args) { SpringApplication.run(FoodApplication.class, args); } + @LoadBalanced @Bean public RestTemplate restTemplate(RestTemplateBuilder builder) { return builder.build(); diff --git a/ts-food-service/src/main/java/foodsearch/controller/FoodController.java b/ts-food-service/src/main/java/foodsearch/controller/FoodController.java index 7663fab57..41c8d66c6 100644 --- a/ts-food-service/src/main/java/foodsearch/controller/FoodController.java +++ b/ts-food-service/src/main/java/foodsearch/controller/FoodController.java @@ -55,33 +55,33 @@ public HttpEntity findAllFoodOrder(@RequestHeader HttpHeaders headers) { @PostMapping(path = "/orders") public HttpEntity createFoodOrder(@RequestBody FoodOrder addFoodOrder, @RequestHeader HttpHeaders headers) { - FoodController.LOGGER.info("[Food Service]Try to Create a FoodOrder!"); + FoodController.LOGGER.info("[createFoodOrder][Try to Create a FoodOrder!]"); return ok(foodService.createFoodOrder(addFoodOrder, headers)); } @PostMapping(path = "/createOrderBatch") public HttpEntity createFoodBatches(@RequestBody List foodOrderList, @RequestHeader HttpHeaders headers) { - FoodController.LOGGER.info("[Food Service]Try to Create Food Batches!"); + FoodController.LOGGER.info("[createFoodBatches][Try to Create Food Batches!]"); return ok(foodService.createFoodOrdersInBatch(foodOrderList, headers)); } @PutMapping(path = "/orders") public HttpEntity updateFoodOrder(@RequestBody FoodOrder updateFoodOrder, @RequestHeader HttpHeaders headers) { - FoodController.LOGGER.info("[Food Service]Try to Update a FoodOrder!"); + FoodController.LOGGER.info("[updateFoodOrder][Try to Update a FoodOrder!]"); return ok(foodService.updateFoodOrder(updateFoodOrder, headers)); } @ResponseStatus(HttpStatus.ACCEPTED) @DeleteMapping(path = "/orders/{orderId}") public HttpEntity deleteFoodOrder(@PathVariable String orderId, @RequestHeader HttpHeaders headers) { - FoodController.LOGGER.info("[Food Service]Try to Cancel a FoodOrder!"); + FoodController.LOGGER.info("[deleteFoodOrder][Try to Cancel a FoodOrder!]"); return ok(foodService.deleteFoodOrder(orderId, headers)); } @GetMapping(path = "/orders/{orderId}") public HttpEntity findFoodOrderByOrderId(@PathVariable String orderId, @RequestHeader HttpHeaders headers) { - FoodController.LOGGER.info("[Food Service]Try to Find all FoodOrder!"); + FoodController.LOGGER.info("[findFoodOrderByOrderId][Try to Find FoodOrder By orderId!][orderId: {}]", orderId); return ok(foodService.findByOrderId(orderId, headers)); } @@ -90,7 +90,7 @@ public HttpEntity findFoodOrderByOrderId(@PathVariable String orderId, @RequestH public HttpEntity getAllFood(@PathVariable String date, @PathVariable String startStation, @PathVariable String endStation, @PathVariable String tripId, @RequestHeader HttpHeaders headers) { - FoodController.LOGGER.info("[Food Service]Get the Get Food Request!"); + FoodController.LOGGER.info("[getAllFood][Get Food Request!]"); return ok(foodService.getAllFood(date, startStation, endStation, tripId, headers)); } diff --git a/ts-food-service/src/main/java/foodsearch/entity/AllTripFood.java b/ts-food-service/src/main/java/foodsearch/entity/AllTripFood.java index 59aa0bbd2..3d3513b3a 100644 --- a/ts-food-service/src/main/java/foodsearch/entity/AllTripFood.java +++ b/ts-food-service/src/main/java/foodsearch/entity/AllTripFood.java @@ -1,5 +1,8 @@ package foodsearch.entity; +import edu.fudan.common.entity.Food; +import edu.fudan.common.entity.StationFoodStore; +import edu.fudan.common.entity.TrainFood; import lombok.Data; import java.util.List; @@ -8,9 +11,9 @@ @Data public class AllTripFood { - private List trainFoodList; + private List trainFoodList; - private Map> foodStoreListMap; + private Map> foodStoreListMap; public AllTripFood(){ //Default Constructor diff --git a/ts-food-service/src/main/java/foodsearch/entity/Food.java b/ts-food-service/src/main/java/foodsearch/entity/Food.java deleted file mode 100644 index 063eb3d11..000000000 --- a/ts-food-service/src/main/java/foodsearch/entity/Food.java +++ /dev/null @@ -1,18 +0,0 @@ -package foodsearch.entity; - - -import lombok.Data; - -import java.io.Serializable; - -@Data -public class Food implements Serializable{ - - public Food(){ - //Default Constructor - } - - private String foodName; - private double price; - -} diff --git a/ts-food-service/src/main/java/foodsearch/entity/FoodOrder.java b/ts-food-service/src/main/java/foodsearch/entity/FoodOrder.java index 0ebaef295..5e2193640 100644 --- a/ts-food-service/src/main/java/foodsearch/entity/FoodOrder.java +++ b/ts-food-service/src/main/java/foodsearch/entity/FoodOrder.java @@ -3,21 +3,27 @@ import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import lombok.AllArgsConstructor; import lombok.Data; -import org.springframework.data.annotation.Id; -import org.springframework.data.mongodb.core.mapping.Document; +import org.hibernate.annotations.GenericGenerator; +import javax.persistence.Column; +import javax.persistence.GeneratedValue; +import javax.persistence.Id; +import javax.persistence.Entity; import java.util.UUID; @Data @AllArgsConstructor -@Document(collection = "foodorder") +@Entity @JsonIgnoreProperties(ignoreUnknown = true) +@GenericGenerator(name = "jpa-uuid", strategy = "org.hibernate.id.UUIDGenerator") public class FoodOrder { @Id - private UUID id; + @GeneratedValue(generator = "jpa-uuid") + @Column(length = 36) + private String id; - private UUID orderId; + private String orderId; //1:train food;2:food store private int foodType; diff --git a/ts-food-service/src/main/java/foodsearch/entity/Route.java b/ts-food-service/src/main/java/foodsearch/entity/Route.java deleted file mode 100644 index 19ca38824..000000000 --- a/ts-food-service/src/main/java/foodsearch/entity/Route.java +++ /dev/null @@ -1,30 +0,0 @@ -package foodsearch.entity; - -import lombok.*; -import com.fasterxml.jackson.annotation.JsonIgnoreProperties; -import org.springframework.data.annotation.Id; -import org.springframework.data.mongodb.core.mapping.Document; - -import java.util.List; - -@Data -@Document(collection = "routes") -@JsonIgnoreProperties(ignoreUnknown = true) -public class Route { - - @Id - private String id; - - private List stations; - - private List distances; - - private String startStationId; - - private String terminalStationId; - - public Route() { - //Default Constructor - } - -} diff --git a/ts-food-service/src/main/java/foodsearch/repository/FoodOrderRepository.java b/ts-food-service/src/main/java/foodsearch/repository/FoodOrderRepository.java index e9b0737fb..476c38415 100644 --- a/ts-food-service/src/main/java/foodsearch/repository/FoodOrderRepository.java +++ b/ts-food-service/src/main/java/foodsearch/repository/FoodOrderRepository.java @@ -1,26 +1,26 @@ package foodsearch.repository; import foodsearch.entity.FoodOrder; -import org.springframework.data.mongodb.repository.MongoRepository; -import org.springframework.data.mongodb.repository.Query; + +import org.springframework.data.repository.CrudRepository; import org.springframework.stereotype.Repository; import java.util.List; +import java.util.Optional; import java.util.UUID; @Repository -public interface FoodOrderRepository extends MongoRepository { +public interface FoodOrderRepository extends CrudRepository { - FoodOrder findById(UUID id); + Optional findById(String id); - @Query("{ 'orderId' : ?0 }") - FoodOrder findByOrderId(UUID orderId); + FoodOrder findByOrderId(String orderId); @Override List findAll(); void deleteById(UUID id); - void deleteFoodOrderByOrderId(UUID id); + void deleteFoodOrderByOrderId(String id); } diff --git a/ts-food-service/src/main/java/foodsearch/service/FoodServiceImpl.java b/ts-food-service/src/main/java/foodsearch/service/FoodServiceImpl.java index 9126147ac..81cf59c2f 100644 --- a/ts-food-service/src/main/java/foodsearch/service/FoodServiceImpl.java +++ b/ts-food-service/src/main/java/foodsearch/service/FoodServiceImpl.java @@ -1,19 +1,25 @@ package foodsearch.service; +import edu.fudan.common.entity.Food; +import edu.fudan.common.entity.StationFoodStore; +import edu.fudan.common.entity.TrainFood; import edu.fudan.common.util.JsonUtils; import edu.fudan.common.util.Response; +import edu.fudan.common.entity.Route; import foodsearch.entity.*; import foodsearch.mq.RabbitSend; import foodsearch.repository.FoodOrderRepository; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.cloud.client.discovery.DiscoveryClient; import org.springframework.core.ParameterizedTypeReference; import org.springframework.http.HttpEntity; import org.springframework.http.HttpHeaders; import org.springframework.http.HttpMethod; import org.springframework.http.ResponseEntity; import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; import org.springframework.web.client.RestTemplate; import java.util.ArrayList; @@ -35,11 +41,19 @@ public class FoodServiceImpl implements FoodService { @Autowired private RabbitSend sender; + @Autowired + private DiscoveryClient discoveryClient; + private static final Logger LOGGER = LoggerFactory.getLogger(FoodServiceImpl.class); + private String getServiceUrl(String serviceName) { + return "http://" + serviceName; + } + String success = "Success."; String orderIdNotExist = "Order Id Is Non-Existent."; + @Override public Response createFoodOrdersInBatch(List orders, HttpHeaders headers) { boolean error = false; String errorOrderId = ""; @@ -48,7 +62,7 @@ public Response createFoodOrdersInBatch(List orders, HttpHeaders head for (FoodOrder addFoodOrder : orders) { FoodOrder fo = foodOrderRepository.findByOrderId(addFoodOrder.getOrderId()); if (fo != null) { - LOGGER.error("[AddFoodOrder] Order Id Has Existed, OrderId: {}", addFoodOrder.getOrderId()); + LOGGER.error("[createFoodOrdersInBatch][AddFoodOrder][Order Id Has Existed][OrderId: {}]", addFoodOrder.getOrderId()); error = true; errorOrderId = addFoodOrder.getOrderId().toString(); break; @@ -61,7 +75,7 @@ public Response createFoodOrdersInBatch(List orders, HttpHeaders head List deliveryJsons = new ArrayList<>(); for (FoodOrder addFoodOrder : orders) { FoodOrder fo = new FoodOrder(); - fo.setId(UUID.randomUUID()); + fo.setId(UUID.randomUUID().toString()); fo.setOrderId(addFoodOrder.getOrderId()); fo.setFoodType(addFoodOrder.getFoodType()); if (addFoodOrder.getFoodType() == 2) { @@ -71,11 +85,11 @@ public Response createFoodOrdersInBatch(List orders, HttpHeaders head fo.setFoodName(addFoodOrder.getFoodName()); fo.setPrice(addFoodOrder.getPrice()); foodOrderRepository.save(fo); - LOGGER.info("[AddFoodOrderBatch] Success Save One Order [{}]", fo.getOrderId()); + LOGGER.info("[createFoodOrdersInBatch][AddFoodOrderBatch][Success Save One Order][FoodOrderId: {}]", fo.getOrderId()); Delivery delivery = new Delivery(); delivery.setFoodName(addFoodOrder.getFoodName()); - delivery.setOrderId(addFoodOrder.getOrderId()); + delivery.setOrderId(UUID.fromString(addFoodOrder.getOrderId())); delivery.setStationName(addFoodOrder.getStationName()); delivery.setStoreName(addFoodOrder.getStoreName()); @@ -85,11 +99,11 @@ public Response createFoodOrdersInBatch(List orders, HttpHeaders head // 批量发送消息 for(String deliveryJson: deliveryJsons) { - LOGGER.info("[AddFoodOrder] delivery info [{}] send to mq", deliveryJson); + LOGGER.info("[createFoodOrdersInBatch][AddFoodOrder][delivery info send to mq][delivery info: {}]", deliveryJson); try { sender.send(deliveryJson); } catch (Exception e) { - LOGGER.error("[AddFoodOrder] send delivery info to mq error, exception is [{}]", e.toString()); + LOGGER.error("[createFoodOrdersInBatch][AddFoodOrder][send delivery info to mq error][exception: {}]", e.toString()); } } @@ -101,11 +115,11 @@ public Response createFoodOrder(FoodOrder addFoodOrder, HttpHeaders headers) { FoodOrder fo = foodOrderRepository.findByOrderId(addFoodOrder.getOrderId()); if (fo != null) { - FoodServiceImpl.LOGGER.error("[AddFoodOrder] Order Id Has Existed, OrderId: {}", addFoodOrder.getOrderId()); + FoodServiceImpl.LOGGER.error("[createFoodOrder][AddFoodOrder][Order Id Has Existed][OrderId: {}]", addFoodOrder.getOrderId()); return new Response<>(0, "Order Id Has Existed.", null); } else { fo = new FoodOrder(); - fo.setId(UUID.randomUUID()); + fo.setId(UUID.randomUUID().toString()); fo.setOrderId(addFoodOrder.getOrderId()); fo.setFoodType(addFoodOrder.getFoodType()); if (addFoodOrder.getFoodType() == 2) { @@ -115,35 +129,37 @@ public Response createFoodOrder(FoodOrder addFoodOrder, HttpHeaders headers) { fo.setFoodName(addFoodOrder.getFoodName()); fo.setPrice(addFoodOrder.getPrice()); foodOrderRepository.save(fo); - FoodServiceImpl.LOGGER.info("[AddFoodOrder] Success."); + FoodServiceImpl.LOGGER.info("[createFoodOrder][AddFoodOrder Success]"); Delivery delivery = new Delivery(); delivery.setFoodName(addFoodOrder.getFoodName()); - delivery.setOrderId(addFoodOrder.getOrderId()); + delivery.setOrderId(UUID.fromString(addFoodOrder.getOrderId())); delivery.setStationName(addFoodOrder.getStationName()); delivery.setStoreName(addFoodOrder.getStoreName()); String deliveryJson = JsonUtils.object2Json(delivery); - LOGGER.info("[AddFoodOrder] delivery info [{}] send to mq", deliveryJson); + LOGGER.info("[createFoodOrder][AddFoodOrder, delivery info send to mq][delivery info: {}]", deliveryJson); try { sender.send(deliveryJson); } catch (Exception e) { - LOGGER.error("[AddFoodOrder] send delivery info to mq error, exception is [{}]", e.toString()); + LOGGER.error("[createFoodOrder][AddFoodOrder][send delivery info to mq error][exception: {}]", e.toString()); } return new Response<>(1, success, fo); } } + @Transactional @Override public Response deleteFoodOrder(String orderId, HttpHeaders headers) { - FoodOrder foodOrder = foodOrderRepository.findByOrderId(UUID.fromString(orderId)); + FoodOrder foodOrder = foodOrderRepository.findByOrderId(UUID.fromString(orderId).toString()); if (foodOrder == null) { - FoodServiceImpl.LOGGER.error("[Cancel FoodOrder] Order Id Is Non-Existent, orderId: {}", orderId); + FoodServiceImpl.LOGGER.error("[deleteFoodOrder][Cancel FoodOrder][Order Id Is Non-Existent][orderId: {}]", orderId); return new Response<>(0, orderIdNotExist, null); } else { - foodOrderRepository.deleteFoodOrderByOrderId(UUID.fromString(orderId)); - FoodServiceImpl.LOGGER.info("[Cancel FoodOrder] Success."); +// foodOrderRepository.deleteFoodOrderByOrderId(UUID.fromString(orderId)); + foodOrderRepository.deleteFoodOrderByOrderId(orderId); + FoodServiceImpl.LOGGER.info("[deleteFoodOrder][Cancel FoodOrder Success]"); return new Response<>(1, success, null); } } @@ -154,7 +170,7 @@ public Response findAllFoodOrder(HttpHeaders headers) { if (foodOrders != null && !foodOrders.isEmpty()) { return new Response<>(1, success, foodOrders); } else { - FoodServiceImpl.LOGGER.error("Find all food order error: {}", "No Content"); + FoodServiceImpl.LOGGER.error("[findAllFoodOrder][Find all food order error: {}]", "No Content"); return new Response<>(0, "No Content", null); } } @@ -162,9 +178,9 @@ public Response findAllFoodOrder(HttpHeaders headers) { @Override public Response updateFoodOrder(FoodOrder updateFoodOrder, HttpHeaders headers) { - FoodOrder fo = foodOrderRepository.findById(updateFoodOrder.getId()); + FoodOrder fo = foodOrderRepository.findById(updateFoodOrder.getId()).orElse(null); if (fo == null) { - FoodServiceImpl.LOGGER.info("[Update FoodOrder] Order Id Is Non-Existent, orderId: {}", updateFoodOrder.getOrderId()); + FoodServiceImpl.LOGGER.info("[updateFoodOrder][Update FoodOrder][Order Id Is Non-Existent][orderId: {}]", updateFoodOrder.getOrderId()); return new Response<>(0, orderIdNotExist, null); } else { fo.setFoodType(updateFoodOrder.getFoodType()); @@ -175,19 +191,19 @@ public Response updateFoodOrder(FoodOrder updateFoodOrder, HttpHeaders headers) fo.setFoodName(updateFoodOrder.getFoodName()); fo.setPrice(updateFoodOrder.getPrice()); foodOrderRepository.save(fo); - FoodServiceImpl.LOGGER.info("[Update FoodOrder] Success."); + FoodServiceImpl.LOGGER.info("[updateFoodOrder][Update FoodOrder Success]"); return new Response<>(1, "Success", fo); } } @Override public Response findByOrderId(String orderId, HttpHeaders headers) { - FoodOrder fo = foodOrderRepository.findByOrderId(UUID.fromString(orderId)); + FoodOrder fo = foodOrderRepository.findByOrderId(UUID.fromString(orderId).toString()); if (fo != null) { - FoodServiceImpl.LOGGER.info("[Find Order by id] Success."); + FoodServiceImpl.LOGGER.info("[findByOrderId][Find Order by id Success][orderId: {}]", orderId); return new Response<>(1, success, fo); } else { - FoodServiceImpl.LOGGER.info("[Find Order by id] Order Id Is Non-Existent, orderId: {}", orderId); + FoodServiceImpl.LOGGER.warn("[findByOrderId][Find Order by id][Order Id Is Non-Existent][orderId: {}]", orderId); return new Response<>(0, orderIdNotExist, null); } } @@ -195,41 +211,45 @@ public Response findByOrderId(String orderId, HttpHeaders headers) { @Override public Response getAllFood(String date, String startStation, String endStation, String tripId, HttpHeaders headers) { - FoodServiceImpl.LOGGER.info("data={} start={} end={} tripid={}", date, startStation, endStation, tripId); + FoodServiceImpl.LOGGER.info("[getAllFood][get All Food with info][data:{} start:{} end:{} tripid:{}]", date, startStation, endStation, tripId); AllTripFood allTripFood = new AllTripFood(); if (null == tripId || tripId.length() <= 2) { - FoodServiceImpl.LOGGER.error("Get the Get Food Request Failed! Trip id is not suitable, date: {}, tripId: {}", date, tripId); + FoodServiceImpl.LOGGER.error("[getAllFood][Get the Get Food Request Failed][Trip id is not suitable][date: {}, tripId: {}]", date, tripId); return new Response<>(0, "Trip id is not suitable", null); } // need return this tow element - List trainFoodList = null; - Map> foodStoreListMap = new HashMap<>(); + List trainFoodList = null; + Map> foodStoreListMap = new HashMap<>(); /**--------------------------------------------------------------------------------------*/ HttpEntity requestEntityGetTrainFoodListResult = new HttpEntity(null); - ResponseEntity>> reGetTrainFoodListResult = restTemplate.exchange( - "http://ts-food-map-service:18855/api/v1/foodmapservice/trainfoods/" + tripId, + String train_food_service_url = getServiceUrl("ts-train-food-service"); + ResponseEntity>> reGetTrainFoodListResult = restTemplate.exchange( + train_food_service_url + "/api/v1/trainfoodservice/trainfoods/" + tripId, HttpMethod.GET, requestEntityGetTrainFoodListResult, - new ParameterizedTypeReference>>() { + new ParameterizedTypeReference>>() { }); - List trainFoodListResult = reGetTrainFoodListResult.getBody().getData(); + + + List trainFoodListResult = reGetTrainFoodListResult.getBody().getData(); if (trainFoodListResult != null) { trainFoodList = trainFoodListResult; - FoodServiceImpl.LOGGER.info("Get Train Food List!"); + FoodServiceImpl.LOGGER.info("[getAllFood][Get Train Food List!]"); } else { - FoodServiceImpl.LOGGER.error("Get the Get Food Request Failed!, date: {}, tripId: {}", date, tripId); + FoodServiceImpl.LOGGER.error("[getAllFood][reGetTrainFoodListResult][Get the Get Food Request Failed!][date: {}, tripId: {}]", date, tripId); return new Response<>(0, "Get the Get Food Request Failed!", null); } //车次途经的车站 /**--------------------------------------------------------------------------------------*/ HttpEntity requestEntityGetRouteResult = new HttpEntity(null, null); + String travel_service_url = getServiceUrl("ts-travel-service"); ResponseEntity> reGetRouteResult = restTemplate.exchange( - "http://ts-travel-service:12346/api/v1/travelservice/routes/" + tripId, + travel_service_url + "/api/v1/travelservice/routes/" + tripId, HttpMethod.GET, requestEntityGetRouteResult, new ParameterizedTypeReference>() { @@ -242,17 +262,8 @@ public Response getAllFood(String date, String startStation, String endStation, //去除不经过的站,如果起点终点有的话 if (null != startStation && !"".equals(startStation)) { /**--------------------------------------------------------------------------------------*/ - HttpEntity requestEntityStartStationId = new HttpEntity(null); - ResponseEntity> reStartStationId = restTemplate.exchange( - "http://ts-station-service:12345/api/v1/stationservice/stations/id/" + startStation, - HttpMethod.GET, - requestEntityStartStationId, - new ParameterizedTypeReference>() { - }); - Response startStationId = reStartStationId.getBody(); - for (int i = 0; i < stations.size(); i++) { - if (stations.get(i).equals(startStationId.getData())) { + if (stations.get(i).equals(startStation)) { break; } else { stations.remove(i); @@ -261,17 +272,8 @@ public Response getAllFood(String date, String startStation, String endStation, } if (null != endStation && !"".equals(endStation)) { /**--------------------------------------------------------------------------------------*/ - HttpEntity requestEntityEndStationId = new HttpEntity(null); - ResponseEntity> reEndStationId = restTemplate.exchange( - "http://ts-station-service:12345/api/v1/stationservice/stations/id/" + endStation, - HttpMethod.GET, - requestEntityEndStationId, - new ParameterizedTypeReference>() { - }); - Response endStationId = reEndStationId.getBody(); - for (int i = stations.size() - 1; i >= 0; i--) { - if (stations.get(i).equals(endStationId.getData())) { + if (stations.get(i).equals(endStation)) { break; } else { stations.remove(i); @@ -280,26 +282,27 @@ public Response getAllFood(String date, String startStation, String endStation, } HttpEntity requestEntityFoodStoresListResult = new HttpEntity(stations, null); - ResponseEntity>> reFoodStoresListResult = restTemplate.exchange( - "http://ts-food-map-service:18855/api/v1/foodmapservice/foodstores", + String station_food_service_url = getServiceUrl("ts-station-food-service"); + ResponseEntity>> reFoodStoresListResult = restTemplate.exchange( + station_food_service_url + "/api/v1/stationfoodservice/stationfoodstores", HttpMethod.POST, requestEntityFoodStoresListResult, - new ParameterizedTypeReference>>() { + new ParameterizedTypeReference>>() { }); - List foodStoresListResult = reFoodStoresListResult.getBody().getData(); - if (foodStoresListResult != null && !foodStoresListResult.isEmpty()) { - for (String stationId : stations) { - List res = foodStoresListResult.stream() - .filter(foodStore -> (foodStore.getStationId().equals(stationId))) + List stationFoodStoresListResult = reFoodStoresListResult.getBody().getData(); + if (stationFoodStoresListResult != null && !stationFoodStoresListResult.isEmpty()) { + for (String station : stations) { + List res = stationFoodStoresListResult.stream() + .filter(stationFoodStore -> (stationFoodStore.getStationName().equals(station))) .collect(Collectors.toList()); - foodStoreListMap.put(stationId, res); + foodStoreListMap.put(station, res); } } else { - FoodServiceImpl.LOGGER.error("Get the Get Food Request Failed! foodStoresListResult is null, date: {}, tripId: {}", date, tripId); + FoodServiceImpl.LOGGER.error("[getAllFood][Get the Get Food Request Failed!][foodStoresListResult is null][date: {}, tripId: {}]", date, tripId); return new Response<>(0, "Get All Food Failed", allTripFood); } } else { - FoodServiceImpl.LOGGER.error("Get the Get Food Request Failed! station status error, date: {}, tripId: {}", date, tripId); + FoodServiceImpl.LOGGER.error("[getAllFood][Get the Get Food Request Failed!][station status error][date: {}, tripId: {}]", date, tripId); return new Response<>(0, "Get All Food Failed", allTripFood); } allTripFood.setTrainFoodList(trainFoodList); diff --git a/ts-food-service/src/main/resources/application.yml b/ts-food-service/src/main/resources/application.yml index 1cc28fd4e..b8cf01297 100644 --- a/ts-food-service/src/main/resources/application.yml +++ b/ts-food-service/src/main/resources/application.yml @@ -2,17 +2,37 @@ server: port: 18856 spring: + cloud: + nacos: + discovery: + server-addr: ${NACOS_ADDRS:nacos-0.nacos-headless.default.svc.cluster.local,nacos-1.nacos-headless.default.svc.cluster.local,nacos-2.nacos-headless.default.svc.cluster.local} application: name: ts-food-service - data: - mongodb: - host: ts-food-mongo -# username: user -# password: ${MONGODB_PASSWORD} - database: ts - port: 27017 + datasource: + url: jdbc:mysql://${FOOD_MYSQL_HOST:ts-food-mysql}:${FOOD_MYSQL_PORT:3306}/${FOOD_MYSQL_DATABASE:ts-food-mysql}?useSSL=false + username: ${FOOD_MYSQL_USER:root} + password: ${FOOD_MYSQL_PASSWORD:root} + driver-class-name: com.mysql.cj.jdbc.Driver + jpa: + hibernate: + ddl-auto: update + properties: + hibernate: + dialect: org.hibernate.dialect.MySQL5Dialect rabbitmq: host: ${rabbitmq_host:localhost} - port: ${rabbitmq_port:5672} + port: 5672 swagger: - controllerPackage: foodsearch.controller \ No newline at end of file + controllerPackage: foodsearch.controller + +station-service: + url: http://${STATION_SERVICE_HOST:ts-station-service}:${STATION_SERVICE_PORT:12345} + +travel-service: + url: http://${TRAVEL_SERVICE_HOST:ts-travel-service}:${TRAVEL_SERVICE_PORT:12346} + +train-food-service: + url: http://${TRAIN_FOOD_SERVICE_HOST:ts-train-food-service}:${TRAIN_FOOD_SERVICE_PORT:19999} + +station-food-service: + url: http://${STATION_FOOD_SERVICE_HOST:ts-station-food-service}:${STATION_FOOD_SERVICE_PORT:18855} diff --git a/ts-food-service/src/test/java/adminorder/service/FoodServiceImplTest.java b/ts-food-service/src/test/java/adminorder/service/FoodServiceImplTest.java index 04bdbd83b..ba2cd6d43 100644 --- a/ts-food-service/src/test/java/adminorder/service/FoodServiceImplTest.java +++ b/ts-food-service/src/test/java/adminorder/service/FoodServiceImplTest.java @@ -17,6 +17,7 @@ import java.util.ArrayList; import java.util.List; +import java.util.Optional; import java.util.UUID; @RunWith(JUnit4.class) @@ -38,15 +39,15 @@ public void setUp() { @Test public void testCreateFoodOrder1() { FoodOrder fo = new FoodOrder(); - Mockito.when(foodOrderRepository.findByOrderId(Mockito.any(UUID.class))).thenReturn(fo); + Mockito.when(foodOrderRepository.findByOrderId(Mockito.any(UUID.class).toString())).thenReturn(fo); Response result = foodServiceImpl.createFoodOrder(fo, headers); Assert.assertEquals(new Response<>(0, "Order Id Has Existed.", null), result); } @Test public void testCreateFoodOrder2() { - FoodOrder fo = new FoodOrder(UUID.randomUUID(), UUID.randomUUID(), 2, "station_name", "store_name", "food_name", 3.0); - Mockito.when(foodOrderRepository.findByOrderId(Mockito.any(UUID.class))).thenReturn(null); + FoodOrder fo = new FoodOrder(UUID.randomUUID().toString(), UUID.randomUUID().toString(), 2, "station_name", "store_name", "food_name", 3.0); + Mockito.when(foodOrderRepository.findByOrderId(Mockito.any(UUID.class).toString())).thenReturn(null); Mockito.when(foodOrderRepository.save(Mockito.any(FoodOrder.class))).thenReturn(null); Response result = foodServiceImpl.createFoodOrder(fo, headers); Assert.assertEquals("Success.", result.getMsg()); @@ -55,7 +56,7 @@ public void testCreateFoodOrder2() { @Test public void testDeleteFoodOrder1() { UUID orderId = UUID.randomUUID(); - Mockito.when(foodOrderRepository.findByOrderId(Mockito.any(UUID.class))).thenReturn(null); + Mockito.when(foodOrderRepository.findByOrderId(Mockito.any(UUID.class).toString())).thenReturn(null); Response result = foodServiceImpl.deleteFoodOrder(orderId.toString(), headers); Assert.assertEquals(new Response<>(0, "Order Id Is Non-Existent.", null), result); } @@ -64,8 +65,8 @@ public void testDeleteFoodOrder1() { public void testDeleteFoodOrder2() { UUID orderId = UUID.randomUUID(); FoodOrder foodOrder = new FoodOrder(); - Mockito.when(foodOrderRepository.findByOrderId(Mockito.any(UUID.class))).thenReturn(foodOrder); - Mockito.doNothing().doThrow(new RuntimeException()).when(foodOrderRepository).deleteFoodOrderByOrderId(Mockito.any(UUID.class)); + Mockito.when(foodOrderRepository.findByOrderId(Mockito.any(UUID.class).toString())).thenReturn(foodOrder); + Mockito.doNothing().doThrow(new RuntimeException()).when(foodOrderRepository).deleteFoodOrderByOrderId(Mockito.any(UUID.class).toString()); Response result = foodServiceImpl.deleteFoodOrder(orderId.toString(), headers); Assert.assertEquals(new Response<>(1, "Success.", null), result); } @@ -89,15 +90,15 @@ public void testFindAllFoodOrder2() { @Test public void testUpdateFoodOrder1() { FoodOrder updateFoodOrder = new FoodOrder(); - Mockito.when(foodOrderRepository.findById(Mockito.any(UUID.class))).thenReturn(null); + Mockito.when(foodOrderRepository.findById(Mockito.any(UUID.class).toString())).thenReturn(null); Response result = foodServiceImpl.updateFoodOrder(updateFoodOrder, headers); Assert.assertEquals(new Response<>(0, "Order Id Is Non-Existent.", null), result); } @Test public void testUpdateFoodOrder2() { - FoodOrder updateFoodOrder = new FoodOrder(UUID.randomUUID(), UUID.randomUUID(), 1, "station_name", "store_name", "food_name", 3.0); - Mockito.when(foodOrderRepository.findById(Mockito.any(UUID.class))).thenReturn(updateFoodOrder); + FoodOrder updateFoodOrder = new FoodOrder(UUID.randomUUID().toString(), UUID.randomUUID().toString(), 1, "station_name", "store_name", "food_name", 3.0); + Mockito.when(foodOrderRepository.findById(Mockito.any(UUID.class).toString())).thenReturn(Optional.of(updateFoodOrder)); Mockito.when(foodOrderRepository.save(Mockito.any(FoodOrder.class))).thenReturn(null); Response result = foodServiceImpl.updateFoodOrder(updateFoodOrder, headers); Assert.assertEquals(new Response<>(1, "Success", updateFoodOrder), result); @@ -107,7 +108,7 @@ public void testUpdateFoodOrder2() { public void testFindByOrderId1() { UUID orderId = UUID.randomUUID(); FoodOrder fo = new FoodOrder(); - Mockito.when(foodOrderRepository.findByOrderId(Mockito.any(UUID.class))).thenReturn(fo); + Mockito.when(foodOrderRepository.findByOrderId(Mockito.any(UUID.class).toString())).thenReturn(fo); Response result = foodServiceImpl.findByOrderId(orderId.toString(), headers); Assert.assertEquals(new Response<>(1, "Success.", fo), result); } @@ -115,7 +116,7 @@ public void testFindByOrderId1() { @Test public void testFindByOrderId2() { UUID orderId = UUID.randomUUID(); - Mockito.when(foodOrderRepository.findByOrderId(Mockito.any(UUID.class))).thenReturn(null); + Mockito.when(foodOrderRepository.findByOrderId(Mockito.any(UUID.class).toString())).thenReturn(null); Response result = foodServiceImpl.findByOrderId(orderId.toString(), headers); Assert.assertEquals(new Response<>(0, "Order Id Is Non-Existent.", null), result); } diff --git a/ts-food-map-service/Dockerfile b/ts-gateway-service/Dockerfile similarity index 50% rename from ts-food-map-service/Dockerfile rename to ts-gateway-service/Dockerfile index a1fee049f..3468588f2 100644 --- a/ts-food-map-service/Dockerfile +++ b/ts-gateway-service/Dockerfile @@ -2,7 +2,7 @@ FROM java:8-jre RUN /bin/cp /usr/share/zoneinfo/Asia/Shanghai /etc/localtime && echo 'Asia/Shanghai' >/etc/timezone -ADD ./target/ts-food-map-service-1.0.jar /app/ -CMD ["java", "-Xmx200m", "-jar", "/app/ts-food-map-service-1.0.jar"] +ADD ./target/ts-gateway-service-1.0.jar /app/ +CMD ["java", "-Xmx1024m", "-jar", "/app/ts-gateway-service-1.0.jar"] -EXPOSE 18855 \ No newline at end of file +EXPOSE 18888 diff --git a/ts-gateway-service/pom.xml b/ts-gateway-service/pom.xml new file mode 100644 index 000000000..5593608a7 --- /dev/null +++ b/ts-gateway-service/pom.xml @@ -0,0 +1,55 @@ + + + 4.0.0 + + fdse.microservice + ts-gateway-service + 1.0 + jar + + ts-gateway-service + + + org.services + ts-service + 0.1.0 + ../pom.xml + + + + UTF-8 + 1.8 + + + + + + + + org.springframework.cloud + spring-cloud-starter-gateway + + + io.netty + netty-all + + + + + com.alibaba.csp + sentinel-spring-cloud-gateway-adapter + + + + + + + org.springframework.boot + spring-boot-maven-plugin + + + + + \ No newline at end of file diff --git a/ts-food-map-service/src/main/java/food/FoodMapApplication.java b/ts-gateway-service/src/main/java/gateway/GatewayApplication.java similarity index 70% rename from ts-food-map-service/src/main/java/food/FoodMapApplication.java rename to ts-gateway-service/src/main/java/gateway/GatewayApplication.java index 7189985cc..c78b427e8 100644 --- a/ts-food-map-service/src/main/java/food/FoodMapApplication.java +++ b/ts-gateway-service/src/main/java/gateway/GatewayApplication.java @@ -1,20 +1,20 @@ -package food; +package gateway; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.cloud.client.discovery.EnableDiscoveryClient; import org.springframework.context.annotation.EnableAspectJAutoProxy; import org.springframework.integration.annotation.IntegrationComponentScan; import org.springframework.scheduling.annotation.EnableAsync; -import springfox.documentation.swagger2.annotations.EnableSwagger2; @SpringBootApplication @EnableAspectJAutoProxy(proxyTargetClass = true) @EnableAsync @IntegrationComponentScan -@EnableSwagger2 -public class FoodMapApplication { - +@EnableDiscoveryClient +public class GatewayApplication { public static void main(String[] args) { - SpringApplication.run(FoodMapApplication.class, args); + SpringApplication.run(GatewayApplication.class, args); } + } diff --git a/ts-gateway-service/src/main/java/gateway/GatewayConfiguration.java b/ts-gateway-service/src/main/java/gateway/GatewayConfiguration.java new file mode 100644 index 000000000..2b22e7ece --- /dev/null +++ b/ts-gateway-service/src/main/java/gateway/GatewayConfiguration.java @@ -0,0 +1,120 @@ +package gateway; + +import com.alibaba.csp.sentinel.adapter.gateway.common.rule.GatewayFlowRule; +import com.alibaba.csp.sentinel.adapter.gateway.common.rule.GatewayRuleManager; +import com.alibaba.csp.sentinel.adapter.gateway.sc.SentinelGatewayFilter; +import com.alibaba.csp.sentinel.adapter.gateway.sc.callback.BlockRequestHandler; +import com.alibaba.csp.sentinel.adapter.gateway.sc.callback.GatewayCallbackManager; +import com.alibaba.csp.sentinel.adapter.gateway.sc.exception.SentinelGatewayBlockExceptionHandler; +import com.alibaba.csp.sentinel.slots.block.RuleConstant; +import org.springframework.beans.factory.ObjectProvider; +import org.springframework.cloud.gateway.filter.GlobalFilter; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.core.Ordered; +import org.springframework.core.annotation.Order; +import org.springframework.http.HttpStatus; +import org.springframework.http.MediaType; +import org.springframework.http.codec.ServerCodecConfigurer; +import org.springframework.web.reactive.function.BodyInserters; +import org.springframework.web.reactive.function.server.ServerResponse; +import org.springframework.web.reactive.result.view.ViewResolver; + +import javax.annotation.PostConstruct; +import java.util.*; + +/** + * 网关配置类 + * + *

主要是基于sentinel的网关限流策略配置

+ * + * @author Akasaka Isami + * @since 2022-06-30 15:13:58 + */ + +@Configuration +public class GatewayConfiguration { + + private final List viewResolvers; + private final ServerCodecConfigurer serverCodecConfigurer; + + public GatewayConfiguration(ObjectProvider> viewResolversProvider, + ServerCodecConfigurer serverCodecConfigurer) { + this.viewResolvers = viewResolversProvider.getIfAvailable(Collections::emptyList); + this.serverCodecConfigurer = serverCodecConfigurer; + } + + + /** + * 配置限流的异常处理器 + * + * @return 限流的异常处理器 + */ + @Bean + @Order(Ordered.HIGHEST_PRECEDENCE) + public SentinelGatewayBlockExceptionHandler sentinelGatewayBlockExceptionHandler() { + // Register the block exception handler for Spring Cloud Gateway. + return new SentinelGatewayBlockExceptionHandler(viewResolvers, serverCodecConfigurer); + } + + /** + * 初始化一个限流的过滤器 + * + * @return 限流过滤器 + */ + @Bean + @Order(-1) + public GlobalFilter sentinelGatewayFilter() { + return new SentinelGatewayFilter(); + } + + /** + * 配置初始化的限流参数 + */ + @PostConstruct + public void doInit() { + initGatewayRules(); +// initBlockHandlers(); + + System.out.println("===== begin to do flow control"); + System.out.println("only 20 requests per second can pass"); + } + + /** + * 注册函数用于实现自定义的逻辑处理被限流的请求 + * + *

默认是返回错误信息: “Blocked by Sentinel: FlowException”。 这里自定义了异常处理,封装了自然语句。

+ */ + private void initBlockHandlers() { + BlockRequestHandler blockRequestHandler = (serverWebExchange, throwable) -> { + Map map = new HashMap<>(); + map.put("code", 0); + map.put("message", "接口被限流了"); + return ServerResponse.status(HttpStatus.OK). + contentType(MediaType.APPLICATION_JSON_UTF8). + body(BodyInserters.fromObject(map)); + }; + GatewayCallbackManager.setBlockHandler(blockRequestHandler); + } + + + /** + * 初始化流量控制规则 + * + *

Sentinal 的流量控制只能基于 route 或自定义 api 分组,这里的限流还是基于 application.yml 中定义的路由(即每个服务)采用 QPS 流量控制策略。 + * 当前是简单的对转发到 admin-basic-info-service 服务的流量做了QPS限制,每秒不超过20个请求。

+ */ + private void initGatewayRules() { + Set rules = new HashSet<>(); + + // 对于转发到 admin-basic-info 的请求 set limit qps to 20 + // qps 超过 20 直接拒绝 + rules.add(new GatewayFlowRule("admin-basic-info") //资源名称,对应路由 id + .setControlBehavior(RuleConstant.CONTROL_BEHAVIOR_DEFAULT) + .setCount(20) // 限流qps阈值 + .setIntervalSec(1) // 统计时间窗口,单位是秒,默认是 1 秒 + ); + + GatewayRuleManager.loadRules(rules); + } +} diff --git a/ts-gateway-service/src/main/resources/application.yml b/ts-gateway-service/src/main/resources/application.yml new file mode 100644 index 000000000..b79e5c1d3 --- /dev/null +++ b/ts-gateway-service/src/main/resources/application.yml @@ -0,0 +1,209 @@ +# HTTP Server +server: + port: 18888 # HTTP (Tomcat) port + +spring: + main: + web-application-type: reactive + application: + name: ts-gateway-service + cloud: + nacos: + discovery: + server-addr: ${NACOS_ADDRS:127.0.0.1:8848} + gateway: + routes: + - id: admin-basic-info + uri: lb://${ADMIN_BASIC_INFO_SERVICE_HOST:ts-admin-basic-info-service} + predicates: + - Path=/api/v1/adminbasicservice/** + + - id: admin-order + uri: lb://${ADMIN_ORDER_SERVICE_HOST:ts-admin-order-service} + predicates: + - Path=/api/v1/adminorderservice/** + + - id: admin-route + uri: lb://${ADMIN_ROUTE_SERVICE_HOST:ts-admin-route-service} + predicates: + - Path=/api/v1/adminrouteservice/** + + - id: admin-travel + uri: lb://${ADMIN_TRAVEL_SERVICE_HOST:ts-admin-travel-service} + predicates: + - Path=/api/v1/admintravelservice/** + + - id: admin-user + uri: lb://${ADMIN_USER_SERVICE_HOST:ts-admin-user-service} + predicates: + - Path=/api/v1/adminuserservice/users/** + + - id: assurance + uri: lb://${ASSURANCE_SERVICE_HOST:ts-assurance-service} + predicates: + - Path=/api/v1/assuranceservice/** + + - id: auth + uri: lb://${AUTH_SERVICE_HOST:ts-auth-service} + predicates: + - Path=/api/v1/auth/** + + - id: auth-user + uri: lb://${AUTH_SERVICE_HOST:ts-auth-service} + predicates: + - Path=/api/v1/users/** + + - id: avatar + uri: lb://${AVATAR_SERVICE_HOST:ts-avatar-service} + predicates: + - Path=/api/v1/avatar/** + + - id: basic + uri: lb://${BASIC_SERVICE_HOST:ts-basic-service} + predicates: + - Path=/api/v1/basicservice/** + + - id: cancel + uri: lb://${CANCEL_SERVICE_HOST:ts-cancel-service} + predicates: + - Path=/api/v1/cancelservice/** + + - id: config + uri: lb://${CONFIG_SERVICE_HOST:ts-config-service} + predicates: + - Path=/api/v1/configservice/** + + - id: consign-price + uri: lb://${CONSIGN_PRICE_SERVICE_HOST:ts-consign-price-service} + predicates: + - Path=/api/v1/consignpriceservice/** + + - id: consign + uri: lb://${CONSIGN_SERVICE_HOST:ts-consign-service} + predicates: + - Path=/api/v1/consignservice/** + + - id: contacts + uri: lb://${CONTACTS_SERVICE_HOST:ts-contacts-service} + predicates: + - Path=/api/v1/contactservice/** + + - id: execute + uri: lb://${EXECUTE_SERVICE_HOST:ts-execute-service} + predicates: + - Path=/api/v1/executeservice/** + + - id: food + uri: lb://${FOOD_SERVICE_HOST:ts-food-service} + predicates: + - Path=/api/v1/foodservice/** + + - id: inside-payment + uri: lb://${INSIDE_PAYMENT_SERVICE_HOST:ts-inside-payment-service} + predicates: + - Path=/api/v1/inside_pay_service/** + + - id: notification + uri: lb://${NOTIFICATION_SERVICE_HOST:ts-notification-service} + predicates: + - Path=/api/v1/notifyservice/** + + - id: order-other + uri: lb://${ORDER_OTHER_SERVICE_HOST:ts-order-other-service} + predicates: + - Path=/api/v1/orderOtherService/** + + - id: order + uri: lb://${ORDER_SERVICE_HOST:ts-order-service} + predicates: + - Path=/api/v1/orderservice/** + + - id: payment + uri: lb://${PAYMENT_SERVICE_HOST:ts-payment-service} + predicates: + - Path=/api/v1/paymentservice/** + + - id: preserve-other + uri: lb://${PRESERVE_OTHER_SERVICE_HOST:ts-preserve-other-service} + predicates: + - Path=/api/v1/preserveotherservice/** + + - id: preserve + uri: lb://${PRESERVE_SERVICE_HOST:ts-preserve-service} + predicates: + - Path=/api/v1/preserveservice/** + + - id: price + uri: lb://${PRICE_SERVICE_HOST:ts-price-service} + predicates: + - Path=/api/v1/priceservice/** + + - id: rebook + uri: lb://${REBOOK_SERVICE_HOST:ts-rebook-service} + predicates: + - Path=/api/v1/rebookservice/** + + - id: route-plan + uri: lb://${ROUTE_PLAN_SERVICE_HOST:ts-route-plan-service} + predicates: + - Path=/api/v1/routeplanservice/** + + - id: route + uri: lb://${ROUTE_SERVICE_HOST:ts-route-service} + predicates: + - Path=/api/v1/routeservice/** + + - id: seat + uri: lb://${SEAT_SERVICE_HOST:ts-seat-service} + predicates: + - Path=/api/v1/seatservice/** + + - id: security + uri: lb://${SECURITY_SERVICE_HOST:ts-security-service} + predicates: + - Path=/api/v1/securityservice/** + + - id: station-food + uri: lb://${STATION_FOOD_SERVICE_HOST:ts-station-food-service} + predicates: + - Path=/api/v1/stationfoodservice/** + + - id: station + uri: lb://${STATION_SERVICE_HOST:ts-station-service} + predicates: + - Path=/api/v1/stationservice/** + + - id: train-food + uri: lb://${TRAIN_FOOD_SERVICE_HOST:ts-train-food-service} + predicates: + - Path=/api/v1/trainfoodservice/** + + - id: train + uri: lb://${TRAIN_SERVICE_HOST:ts-train-service} + predicates: + - Path=/api/v1/trainservice/** + + - id: travel2 + uri: lb://${TRAVEL2_SERVICE_HOST:ts-travel2-service} + predicates: + - Path=/api/v1/travel2service/** + + - id: travel-plan + uri: lb://${TRAVEL_PLAN_SERVICE_HOST:ts-travel-plan-service} + predicates: + - Path=/api/v1/travelplanservice/** + + - id: travel + uri: lb://${TRAVEL_SERVICE_HOST:ts-travel-service} + predicates: + - Path=/api/v1/travelservice/** + + - id: user + uri: lb://${USER_SERVICE_HOST:ts-user-service} + predicates: + - Path=/api/v1/userservice/users/** + + - id: verification-code + uri: lb://${VERIFICATION_CODE_SERVICE_HOST:ts-verification-code-service} + predicates: + - Path=/api/v1/verifycode/** diff --git a/ts-inside-payment-service/pom.xml b/ts-inside-payment-service/pom.xml index ac539d9a4..dc7318b04 100644 --- a/ts-inside-payment-service/pom.xml +++ b/ts-inside-payment-service/pom.xml @@ -16,7 +16,7 @@ org.services ts-service 0.1.0 - ../ + ../pom.xml @@ -28,15 +28,22 @@ org.springframework.boot - spring-boot-starter-data-mongodb + spring-boot-starter-data-jpa + + + mysql + mysql-connector-java + runtime org.services ts-common 0.1.0 - - + + jakarta.validation + jakarta.validation-api + diff --git a/ts-inside-payment-service/src/main/java/inside_payment/InsidePaymentApplication.java b/ts-inside-payment-service/src/main/java/inside_payment/InsidePaymentApplication.java index 5ca21bb46..ac232a4fc 100644 --- a/ts-inside-payment-service/src/main/java/inside_payment/InsidePaymentApplication.java +++ b/ts-inside-payment-service/src/main/java/inside_payment/InsidePaymentApplication.java @@ -3,6 +3,8 @@ import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.boot.web.client.RestTemplateBuilder; +import org.springframework.cloud.client.discovery.EnableDiscoveryClient; +import org.springframework.cloud.client.loadbalancer.LoadBalanced; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.EnableAspectJAutoProxy; import org.springframework.integration.annotation.IntegrationComponentScan; @@ -18,12 +20,14 @@ @EnableAsync @IntegrationComponentScan @EnableSwagger2 +@EnableDiscoveryClient public class InsidePaymentApplication { public static void main(String[] args) { SpringApplication.run(InsidePaymentApplication.class, args); } + @LoadBalanced @Bean public RestTemplate restTemplate(RestTemplateBuilder builder) { return builder.build(); diff --git a/ts-inside-payment-service/src/main/java/inside_payment/async/AsyncTask.java b/ts-inside-payment-service/src/main/java/inside_payment/async/AsyncTask.java index c3633b81d..028aeee0f 100644 --- a/ts-inside-payment-service/src/main/java/inside_payment/async/AsyncTask.java +++ b/ts-inside-payment-service/src/main/java/inside_payment/async/AsyncTask.java @@ -23,9 +23,9 @@ public class AsyncTask { @Async("mySimpleAsync") public Future sendAsyncCallToPaymentService(OutsidePaymentInfo outsidePaymentInfo) { - AsyncTask.LOGGER.info("[Inside Payment Service][Async Task] Begin."); + AsyncTask.LOGGER.info("[sendAsyncCallToPaymentService][Inside Payment Service, Async Task,Begin]"); Boolean value = restTemplate.getForObject("http://rest-service-external:16100/greet", Boolean.class); - AsyncTask.LOGGER.info("[Inside Payment Service][Async Task] Receive call Value directly back: {}", value); + AsyncTask.LOGGER.info("[sendAsyncCallToPaymentService][Inside Payment Service, Async Task][Receive call Value directly back: {}]", value); return new AsyncResult<>(value); } diff --git a/ts-inside-payment-service/src/main/java/inside_payment/controller/InsidePaymentController.java b/ts-inside-payment-service/src/main/java/inside_payment/controller/InsidePaymentController.java index 2a38ae5b1..97da1e2d0 100644 --- a/ts-inside-payment-service/src/main/java/inside_payment/controller/InsidePaymentController.java +++ b/ts-inside-payment-service/src/main/java/inside_payment/controller/InsidePaymentController.java @@ -30,50 +30,50 @@ public String home() { @PostMapping(value = "/inside_payment") public HttpEntity pay(@RequestBody PaymentInfo info, @RequestHeader HttpHeaders headers) { - InsidePaymentController.LOGGER.info("[Inside Payment Service][Pay] Pay for: {}", info.getOrderId()); + InsidePaymentController.LOGGER.info("[pay][Inside Payment Service.Pay][Pay for: {}]", info.getOrderId()); return ok(service.pay(info, headers)); } @PostMapping(value = "/inside_payment/account") public HttpEntity createAccount(@RequestBody AccountInfo info, @RequestHeader HttpHeaders headers) { - LOGGER.info("Create account, accountInfo: {}", info); + LOGGER.info("[createAccount][Create account][accountInfo: {}]", info); return ok(service.createAccount(info, headers)); } @GetMapping(value = "/inside_payment/{userId}/{money}") public HttpEntity addMoney(@PathVariable String userId, @PathVariable String money, @RequestHeader HttpHeaders headers) { - LOGGER.info("add money, userId: {}, money: {}", userId, money); + LOGGER.info("[addMoney][add money][userId: {}, money: {}]", userId, money); return ok(service.addMoney(userId, money, headers)); } @GetMapping(value = "/inside_payment/payment") public HttpEntity queryPayment(@RequestHeader HttpHeaders headers) { - LOGGER.info("query payment"); + LOGGER.info("[queryPayment][query payment]"); return ok(service.queryPayment(headers)); } @GetMapping(value = "/inside_payment/account") public HttpEntity queryAccount(@RequestHeader HttpHeaders headers) { - LOGGER.info("query account"); + LOGGER.info("[queryAccount][query account]"); return ok(service.queryAccount(headers)); } @GetMapping(value = "/inside_payment/drawback/{userId}/{money}") public HttpEntity drawBack(@PathVariable String userId, @PathVariable String money, @RequestHeader HttpHeaders headers) { - LOGGER.info("draw back payment, userId: {}, money: {}", userId, money); + LOGGER.info("[drawBack][draw back payment][userId: {}, money: {}]", userId, money); return ok(service.drawBack(userId, money, headers)); } @PostMapping(value = "/inside_payment/difference") public HttpEntity payDifference(@RequestBody PaymentInfo info, @RequestHeader HttpHeaders headers) { - LOGGER.info("pay difference"); + LOGGER.info("[payDifference][pay difference]"); return ok(service.payDifference(info, headers)); } @GetMapping(value = "/inside_payment/money") public HttpEntity queryAddMoney(@RequestHeader HttpHeaders headers) { - LOGGER.info("query add money"); + LOGGER.info("[queryAddMoney][query add money]"); return ok(service.queryAddMoney(headers)); } diff --git a/ts-inside-payment-service/src/main/java/inside_payment/entity/Money.java b/ts-inside-payment-service/src/main/java/inside_payment/entity/Money.java index 06595cec2..b80f35621 100644 --- a/ts-inside-payment-service/src/main/java/inside_payment/entity/Money.java +++ b/ts-inside-payment-service/src/main/java/inside_payment/entity/Money.java @@ -1,8 +1,10 @@ package inside_payment.entity; import lombok.Data; -import org.springframework.data.annotation.Id; -import org.springframework.data.mongodb.core.mapping.Document; +import org.hibernate.annotations.GenericGenerator; + +import javax.persistence.*; +//import org.springframework.data.mongodb.core.mapping.Document; import javax.validation.Valid; import javax.validation.constraints.NotNull; @@ -12,16 +14,21 @@ * @author fdse */ @Data -@Document(collection="addMoney") +@Entity +@GenericGenerator(name = "jpa-uuid", strategy = "org.hibernate.id.UUIDGenerator") +@Table(name = "inside_money") public class Money { @Valid @NotNull @Id + @Column(length = 36) + @GeneratedValue(generator = "jpa-uuid") private String id; @Valid @NotNull + @Column(length = 36) private String userId; @Valid @@ -30,10 +37,10 @@ public class Money { @Valid @NotNull + @Enumerated(EnumType.STRING) private MoneyType type; public Money(){ - this.id = UUID.randomUUID().toString(); this.userId = ""; this.money = ""; diff --git a/ts-inside-payment-service/src/main/java/inside_payment/entity/Order.java b/ts-inside-payment-service/src/main/java/inside_payment/entity/Order.java deleted file mode 100644 index 538dde041..000000000 --- a/ts-inside-payment-service/src/main/java/inside_payment/entity/Order.java +++ /dev/null @@ -1,110 +0,0 @@ -package inside_payment.entity; - -import com.fasterxml.jackson.annotation.JsonIgnoreProperties; -import lombok.Data; - -import java.util.Date; -import java.util.UUID; - -/** - * @author fdse - */ -@Data -@JsonIgnoreProperties(ignoreUnknown = true) -public class Order { - - private UUID id; - - private Date boughtDate; - - - private Date travelDate; - - - private Date travelTime; - - /** - * Which Account Bought it - */ - private UUID accountId; - - /** - * Tickets bought for whom.... - */ - private String contactsName; - - private int documentType; - - private String contactsDocumentNumber; - - private String trainNumber; - - private int coachNumber; - - private int seatClass; - - private String seatNumber; - - private String from; - - private String to; - - private int status; - - private String price; - - public Order(){ - boughtDate = new Date(System.currentTimeMillis()); - travelDate = new Date(123456789); - trainNumber = "G1235"; - coachNumber = 5; - seatClass = SeatClass.FIRSTCLASS.getCode(); - seatNumber = "5A"; - from = "shanghai"; - to = "太原"; - status = OrderStatus.PAID.getCode(); - price = "0.0"; - } - - @Override - public boolean equals(Object obj) { - if (this == obj) { - return true; - } - if (obj == null) { - return false; - } - if (getClass() != obj.getClass()) { - return false; - } - Order other = (Order) obj; - return boughtDate.equals(other.getBoughtDate()) - && travelDate.equals(other.getTravelDate()) - && travelTime.equals(other.getTravelTime()) - && accountId .equals( other.getAccountId() ) - && contactsName.equals(other.getContactsName()) - && contactsDocumentNumber.equals(other.getContactsDocumentNumber()) - && documentType == other.getDocumentType() - && trainNumber.equals(other.getTrainNumber()) - && coachNumber == other.getCoachNumber() - && seatClass == other.getSeatClass() - && seatNumber .equals(other.getSeatNumber()) - && from.equals(other.getFrom()) - && to.equals(other.getTo()) - && status == other.getStatus() - && price.equals(other.price); - } - - @Override - public int hashCode() { - int result = 17; - result = 31 * result + (id == null ? 0 : id.hashCode()); - return result; - } - - public void setTravelDate(int year,int month,int day){ - Date date = new Date(year,month,day,0,0,0); //NOSONAR - this.travelDate = date; - } - -} diff --git a/ts-inside-payment-service/src/main/java/inside_payment/entity/OrderStatus.java b/ts-inside-payment-service/src/main/java/inside_payment/entity/OrderStatus.java deleted file mode 100644 index 2b77b2271..000000000 --- a/ts-inside-payment-service/src/main/java/inside_payment/entity/OrderStatus.java +++ /dev/null @@ -1,63 +0,0 @@ -package inside_payment.entity; - -/** - * @author fdse - */ -public enum OrderStatus { - - /** - * not paid - */ - NOTPAID (0,"Not Paid"), - /** - * paid and not collected - */ - PAID (1,"Paid & Not Collected"), - /** - * collected - */ - COLLECTED (2,"Collected"), - /** - * cancel and rebook - */ - CHANGE (3,"Cancel & Rebook"), - /** - * cancel - */ - CANCEL (4,"Cancel"), - /** - * refunded - */ - REFUNDS (5,"Refunded"), - /** - * used - */ - USED (6,"Used"); - - private int code; - private String name; - - OrderStatus(int code, String name){ - this.code = code; - this.name = name; - } - - public int getCode(){ - return code; - } - - public String getName() { - return name; - } - - public static String getNameByCode(int code){ - OrderStatus[] orderStatusSet = OrderStatus.values(); - for(OrderStatus orderStatus : orderStatusSet){ - if(orderStatus.getCode() == code){ - return orderStatus.getName(); - } - } - return orderStatusSet[0].getName(); - } - -} diff --git a/ts-inside-payment-service/src/main/java/inside_payment/entity/Payment.java b/ts-inside-payment-service/src/main/java/inside_payment/entity/Payment.java index 6f3a11ad1..5385a7c87 100644 --- a/ts-inside-payment-service/src/main/java/inside_payment/entity/Payment.java +++ b/ts-inside-payment-service/src/main/java/inside_payment/entity/Payment.java @@ -1,8 +1,10 @@ package inside_payment.entity; import lombok.Data; -import org.springframework.data.annotation.Id; -import org.springframework.data.mongodb.core.mapping.Document; +import org.hibernate.annotations.GenericGenerator; + +import javax.persistence.*; +//import org.springframework.data.mongodb.core.mapping.Document; import javax.validation.Valid; import javax.validation.constraints.NotNull; @@ -12,19 +14,24 @@ * @author fdse */ @Data -@Document(collection="payment") +@Entity +@GenericGenerator(name = "jpa-uuid", strategy = "org.hibernate.id.UUIDGenerator") +@Table(name="inside_payment") public class Payment { @Id @NotNull - @Valid + @Column(length = 36) + @GeneratedValue(generator = "jpa-uuid") private String id; @NotNull @Valid + @Column(length = 36) private String orderId; @NotNull @Valid + @Column(length = 36) private String userId; @NotNull @@ -33,10 +40,10 @@ public class Payment { @NotNull @Valid + @Enumerated(EnumType.STRING) private PaymentType type; public Payment(){ - this.id = UUID.randomUUID().toString().replace("-", "").toUpperCase(); this.orderId = ""; this.userId = ""; this.price = ""; diff --git a/ts-inside-payment-service/src/main/java/inside_payment/entity/PaymentInfo.java b/ts-inside-payment-service/src/main/java/inside_payment/entity/PaymentInfo.java index 62a10e7d0..1c3772c4c 100644 --- a/ts-inside-payment-service/src/main/java/inside_payment/entity/PaymentInfo.java +++ b/ts-inside-payment-service/src/main/java/inside_payment/entity/PaymentInfo.java @@ -18,4 +18,7 @@ public PaymentInfo(){ private String tripId; private String price; +// public String getOrderId(){ +// return this.orderId; +// } } diff --git a/ts-inside-payment-service/src/main/java/inside_payment/entity/SeatClass.java b/ts-inside-payment-service/src/main/java/inside_payment/entity/SeatClass.java deleted file mode 100644 index 094343b5f..000000000 --- a/ts-inside-payment-service/src/main/java/inside_payment/entity/SeatClass.java +++ /dev/null @@ -1,70 +0,0 @@ -package inside_payment.entity; - -/** - * @author fdse - */ -public enum SeatClass { - - /** - * no seat - */ - NONE (0,"NoSeat"), - /** - * green seat - */ - BUSINESS (1,"GreenSeat"), - /** - * first class seat - */ - FIRSTCLASS (2,"FirstClassSeat"), - /** - * second class seat - */ - SECONDCLASS (3,"SecondClassSeat"), - /** - * hard seat - */ - HARDSEAT (4,"HardSeat"), - /** - * soft seat - */ - SOFTSEAT (5,"SoftSeat"), - /** - * hard bed - */ - HARDBED (6,"HardBed"), - /** - * soft bed - */ - SOFTBED (7,"SoftBed"), - /** - * high soft seat - */ - HIGHSOFTBED (8,"HighSoftSeat"); - - private int code; - private String name; - - SeatClass(int code, String name){ - this.code = code; - this.name = name; - } - - public int getCode(){ - return code; - } - - public String getName() { - return name; - } - - public static String getNameByCode(int code){ - SeatClass[] seatClassSet = SeatClass.values(); - for(SeatClass seatClass : seatClassSet){ - if(seatClass.getCode() == code){ - return seatClass.getName(); - } - } - return seatClassSet[0].getName(); - } -} diff --git a/ts-inside-payment-service/src/main/java/inside_payment/repository/AddMoneyRepository.java b/ts-inside-payment-service/src/main/java/inside_payment/repository/AddMoneyRepository.java index b73cb0e65..fe021134e 100644 --- a/ts-inside-payment-service/src/main/java/inside_payment/repository/AddMoneyRepository.java +++ b/ts-inside-payment-service/src/main/java/inside_payment/repository/AddMoneyRepository.java @@ -1,6 +1,7 @@ package inside_payment.repository; import inside_payment.entity.Money; +//import org.springframework.data.mongodb.repository.MongoRepository; import org.springframework.data.repository.CrudRepository; import java.util.List; diff --git a/ts-inside-payment-service/src/main/java/inside_payment/repository/PaymentRepository.java b/ts-inside-payment-service/src/main/java/inside_payment/repository/PaymentRepository.java index 8ca086466..d256d5ced 100644 --- a/ts-inside-payment-service/src/main/java/inside_payment/repository/PaymentRepository.java +++ b/ts-inside-payment-service/src/main/java/inside_payment/repository/PaymentRepository.java @@ -1,9 +1,11 @@ package inside_payment.repository; import inside_payment.entity.Payment; +//import org.springframework.data.mongodb.repository.MongoRepository; import org.springframework.data.repository.CrudRepository; import java.util.List; +import java.util.Optional; /** * @author fdse @@ -16,7 +18,7 @@ public interface PaymentRepository extends CrudRepository { * @param id id * @return Payment */ - Payment findById(String id); + Optional findById(String id); /** * find by order id diff --git a/ts-inside-payment-service/src/main/java/inside_payment/service/InsidePaymentServiceImpl.java b/ts-inside-payment-service/src/main/java/inside_payment/service/InsidePaymentServiceImpl.java index a2b86ab4f..6c8354555 100644 --- a/ts-inside-payment-service/src/main/java/inside_payment/service/InsidePaymentServiceImpl.java +++ b/ts-inside-payment-service/src/main/java/inside_payment/service/InsidePaymentServiceImpl.java @@ -1,5 +1,7 @@ package inside_payment.service; +import edu.fudan.common.entity.OrderStatus; +import edu.fudan.common.entity.Order; import edu.fudan.common.util.Response; import inside_payment.entity.*; import inside_payment.repository.AddMoneyRepository; @@ -7,6 +9,7 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.annotation.Value; import org.springframework.core.ParameterizedTypeReference; import org.springframework.http.HttpEntity; import org.springframework.http.HttpHeaders; @@ -35,16 +38,22 @@ public class InsidePaymentServiceImpl implements InsidePaymentService { private static final Logger LOGGER = LoggerFactory.getLogger(InsidePaymentServiceImpl.class); + private String getServiceUrl(String serviceName) { + return "http://" + serviceName; + } + @Override public Response pay(PaymentInfo info, HttpHeaders headers) { String userId = info.getUserId(); String requestOrderURL = ""; + String order_service_url = getServiceUrl("ts-order-service"); + String order_other_service_url = getServiceUrl("ts-order-other-service"); if (info.getTripId().startsWith("G") || info.getTripId().startsWith("D")) { - requestOrderURL = "http://ts-order-service:12031/api/v1/orderservice/order/" + info.getOrderId(); + requestOrderURL = order_service_url + "/api/v1/orderservice/order/" + info.getOrderId(); } else { - requestOrderURL = "http://ts-order-other-service:12032/api/v1/orderOtherService/orderOther/" + info.getOrderId(); + requestOrderURL = order_other_service_url + "/api/v1/orderOtherService/orderOther/" + info.getOrderId(); } HttpEntity requestGetOrderResults = new HttpEntity(headers); ResponseEntity> reGetOrderResults = restTemplate.exchange( @@ -59,7 +68,7 @@ public Response pay(PaymentInfo info, HttpHeaders headers) { if (result.getStatus() == 1) { Order order = result.getData(); if (order.getStatus() != OrderStatus.NOTPAID.getCode()) { - InsidePaymentServiceImpl.LOGGER.info("[Inside Payment Service][Pay] Error. Order status Not allowed to Pay."); + InsidePaymentServiceImpl.LOGGER.warn("[Inside Payment Service.pay][Order status Not allowed to Pay]"); return new Response<>(0, "Error. Order status Not allowed to Pay.", null); } @@ -97,14 +106,15 @@ public Response pay(PaymentInfo info, HttpHeaders headers) { /****这里调用第三方支付***/ HttpEntity requestEntityOutsidePaySuccess = new HttpEntity(outsidePaymentInfo, headers); + String payment_service_url = getServiceUrl("ts-payment-service"); ResponseEntity reOutsidePaySuccess = restTemplate.exchange( - "http://ts-payment-service:19001/api/v1/paymentservice/payment", + payment_service_url + "/api/v1/paymentservice/payment", HttpMethod.POST, requestEntityOutsidePaySuccess, Response.class); Response outsidePaySuccess = reOutsidePaySuccess.getBody(); - InsidePaymentServiceImpl.LOGGER.info("Out pay result: {}", outsidePaySuccess.toString()); + InsidePaymentServiceImpl.LOGGER.info("[Inside Payment Service.pay][outside Pay][Out pay result: {}]", outsidePaySuccess.toString()); if (outsidePaySuccess.getStatus() == 1) { payment.setType(PaymentType.O); paymentRepository.save(payment); @@ -119,11 +129,11 @@ public Response pay(PaymentInfo info, HttpHeaders headers) { payment.setType(PaymentType.P); paymentRepository.save(payment); } - LOGGER.info("Payment success, orderId: {}", info.getOrderId()); + LOGGER.info("[Inside Payment Service.pay][Payment success][orderId: {}]", info.getOrderId()); return new Response<>(1, "Payment Success", null); } else { - LOGGER.error("Payment failed: Order not exists, orderId: {}", info.getOrderId()); + LOGGER.error("[Inside Payment Service.pay][Payment failed][Order not exists][orderId: {}]", info.getOrderId()); return new Response<>(0, "Payment Failed, Order Not Exists", null); } } @@ -139,7 +149,7 @@ public Response createAccount(AccountInfo info, HttpHeaders headers) { addMoneyRepository.save(addMoney); return new Response<>(1, "Create Account Success", null); } else { - LOGGER.error("Create Account Failed, Account already Exists, userId: {}", info.getUserId()); + LOGGER.error("[createAccount][Create Account Failed][Account already Exists][userId: {}]", info.getUserId()); return new Response<>(0, "Create Account Failed, Account already Exists", null); } } @@ -226,7 +236,7 @@ public Response queryPayment(HttpHeaders headers) { if (payments != null && !payments.isEmpty()) { return new Response<>(1, "Query Payment Success", payments); }else { - LOGGER.error("Query payment failed"); + LOGGER.error("[queryPayment][Query payment failed][payment is null]"); return new Response<>(0, "Query Payment Failed", null); } } @@ -241,7 +251,7 @@ public Response drawBack(String userId, String money, HttpHeaders headers) { addMoneyRepository.save(addMoney); return new Response<>(1, "Draw Back Money Success", null); } else { - LOGGER.error("Draw Back Money Failed"); + LOGGER.error("[drawBack][Draw Back Money Failed][addMoneyRepository.findByUserId null][userId: {}]", userId); return new Response<>(0, "Draw Back Money Failed", null); } } @@ -283,8 +293,9 @@ public Response payDifference(PaymentInfo info, HttpHeaders headers) { outsidePaymentInfo.setPrice(info.getPrice()); HttpEntity requestEntityOutsidePaySuccess = new HttpEntity(outsidePaymentInfo, headers); + String payment_service_url = getServiceUrl("ts-payment-service"); ResponseEntity reOutsidePaySuccess = restTemplate.exchange( - "http://ts-payment-service:19001/api/v1/paymentservice/payment", + payment_service_url + "/api/v1/paymentservice/payment", HttpMethod.POST, requestEntityOutsidePaySuccess, Response.class); @@ -295,7 +306,7 @@ public Response payDifference(PaymentInfo info, HttpHeaders headers) { paymentRepository.save(payment); return new Response<>(1, "Pay Difference Success", null); } else { - LOGGER.error("Pay Difference Failed, orderId: {}", info.getOrderId()); + LOGGER.error("[payDifference][Pay Difference Failed][outsidePaySuccess status not 1][orderId: {}]", info.getOrderId()); return new Response<>(0, "Pay Difference Failed", null); } } else { @@ -311,7 +322,7 @@ public Response queryAddMoney(HttpHeaders headers) { if (monies != null && !monies.isEmpty()) { return new Response<>(1, "Query Money Success", null); } else { - LOGGER.error("Query money failed"); + LOGGER.error("[queryAddMoney][Query money failed][addMoneyRepository.findAll null]"); return new Response<>(0, "Query money failed", null); } } @@ -324,8 +335,9 @@ private Response setOrderStatus(String tripId, String orderId, HttpHeaders heade if (tripId.startsWith("G") || tripId.startsWith("D")) { HttpEntity requestEntityModifyOrderStatusResult = new HttpEntity(headers); + String order_service_url = getServiceUrl("ts-order-service"); ResponseEntity reModifyOrderStatusResult = restTemplate.exchange( - "http://ts-order-service:12031/api/v1/orderservice/order/status/" + orderId + "/" + orderStatus, + order_service_url + "/api/v1/orderservice/order/status/" + orderId + "/" + orderStatus, HttpMethod.GET, requestEntityModifyOrderStatusResult, Response.class); @@ -333,8 +345,9 @@ private Response setOrderStatus(String tripId, String orderId, HttpHeaders heade } else { HttpEntity requestEntityModifyOrderStatusResult = new HttpEntity(headers); + String order_other_service_url = getServiceUrl("ts-order-other-service"); ResponseEntity reModifyOrderStatusResult = restTemplate.exchange( - "http://ts-order-other-service:12032/api/v1/orderOtherService/orderOther/status/" + orderId + "/" + orderStatus, + order_other_service_url + "/api/v1/orderOtherService/orderOther/status/" + orderId + "/" + orderStatus, HttpMethod.GET, requestEntityModifyOrderStatusResult, Response.class); @@ -346,11 +359,11 @@ private Response setOrderStatus(String tripId, String orderId, HttpHeaders heade @Override public void initPayment(Payment payment, HttpHeaders headers) { - Payment paymentTemp = paymentRepository.findById(payment.getId()); + Optional paymentTemp = paymentRepository.findById(payment.getId()); if (paymentTemp == null) { paymentRepository.save(payment); } else { - InsidePaymentServiceImpl.LOGGER.error("[Init Payment] Already Exists, paymentId: {}, orderId: {}", payment.getId(), payment.getOrderId()); + InsidePaymentServiceImpl.LOGGER.error("[initPayment][paymentTemp Already Exists][paymentId: {}, orderId: {}]", payment.getId(), payment.getOrderId()); } } diff --git a/ts-inside-payment-service/src/main/resources/application.yml b/ts-inside-payment-service/src/main/resources/application.yml index 907915cc3..cb6396bdd 100644 --- a/ts-inside-payment-service/src/main/resources/application.yml +++ b/ts-inside-payment-service/src/main/resources/application.yml @@ -2,16 +2,25 @@ server: port: 18673 spring: + cloud: + nacos: + discovery: + server-addr: ${NACOS_ADDRS:nacos-0.nacos-headless.default.svc.cluster.local,nacos-1.nacos-headless.default.svc.cluster.local,nacos-2.nacos-headless.default.svc.cluster.local} application: name: ts-inside-payment-service - data: - mongodb: - host: ts-inside-payment-mongo -# username: user -# password: ${MONGODB_PASSWORD} - database: ts - port: 27017 + datasource: + url: jdbc:mysql://${INSIDE_PAYMENT_MYSQL_HOST:ts-inside-payment-mysql}:${INSIDE_PAYMENT_MYSQL_PORT:3306}/${INSIDE_PAYMENT_MYSQL_DATABASE:ts-inside-payment-mysql}?useSSL=false + username: ${INSIDE_PAYMENT_MYSQL_USER:root} + password: ${INSIDE_PAYMENT_MYSQL_PASSWORD:Abcd1234#} + driver-class-name: com.mysql.cj.jdbc.Driver + jpa: + hibernate: + ddl-auto: update + properties: + hibernate: + dialect: org.hibernate.dialect.MySQL5Dialect + swagger: - controllerPackage: inside_payment.controller \ No newline at end of file + controllerPackage: inside_payment.controller diff --git a/ts-inside-payment-service/src/test/java/inside_payment/service/InsidePaymentServiceImplTest.java b/ts-inside-payment-service/src/test/java/inside_payment/service/InsidePaymentServiceImplTest.java index 4d3df1ac9..e2e0f8bca 100644 --- a/ts-inside-payment-service/src/test/java/inside_payment/service/InsidePaymentServiceImplTest.java +++ b/ts-inside-payment-service/src/test/java/inside_payment/service/InsidePaymentServiceImplTest.java @@ -1,5 +1,6 @@ package inside_payment.service; +import edu.fudan.common.entity.Order; import edu.fudan.common.util.Response; import inside_payment.entity.*; import inside_payment.repository.AddMoneyRepository; @@ -199,7 +200,7 @@ public void testInitPayment1() { @Test public void testInitPayment2() { Payment payment = new Payment(); - Mockito.when(paymentRepository.findById(Mockito.anyString())).thenReturn(payment); + Mockito.when(paymentRepository.findById(Mockito.anyString()).get()).thenReturn(payment); Mockito.when(paymentRepository.save(Mockito.any(Payment.class))).thenReturn(null); insidePaymentServiceImpl.initPayment(payment, headers); Mockito.verify(paymentRepository, times(0)).save(Mockito.any(Payment.class)); diff --git a/ts-notification-service/pom.xml b/ts-notification-service/pom.xml index 76a38c392..ac53376c3 100644 --- a/ts-notification-service/pom.xml +++ b/ts-notification-service/pom.xml @@ -15,7 +15,7 @@ org.services ts-service 0.1.0 - ../ + ../pom.xml @@ -29,12 +29,6 @@ org.springframework.boot spring-boot-starter-mail - - - org.springframework.boot - spring-boot-starter-data-mongodb - - org.springframework.boot spring-boot-starter-freemarker @@ -44,14 +38,20 @@ ts-common 0.1.0 - org.springframework.boot spring-boot-starter-amqp - - - + + org.springframework.boot + spring-boot-starter-data-jpa + + + mysql + mysql-connector-java + runtime + + diff --git a/ts-notification-service/src/main/java/notification/NotificationApplication.java b/ts-notification-service/src/main/java/notification/NotificationApplication.java index 47c3656bf..8ed24a7cb 100644 --- a/ts-notification-service/src/main/java/notification/NotificationApplication.java +++ b/ts-notification-service/src/main/java/notification/NotificationApplication.java @@ -3,6 +3,8 @@ import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.boot.web.client.RestTemplateBuilder; +import org.springframework.cloud.client.discovery.EnableDiscoveryClient; +import org.springframework.cloud.client.loadbalancer.LoadBalanced; import org.springframework.context.annotation.Bean; import org.springframework.web.client.RestTemplate; import springfox.documentation.swagger2.annotations.EnableSwagger2; @@ -12,11 +14,13 @@ */ @SpringBootApplication @EnableSwagger2 +@EnableDiscoveryClient public class NotificationApplication{ public static void main(String[] args) { SpringApplication.run(NotificationApplication.class, args); } + @LoadBalanced @Bean public RestTemplate restTemplate(RestTemplateBuilder builder) { return builder.build(); diff --git a/ts-notification-service/src/main/java/notification/controller/NotificationController.java b/ts-notification-service/src/main/java/notification/controller/NotificationController.java index 580a81418..9f552488b 100644 --- a/ts-notification-service/src/main/java/notification/controller/NotificationController.java +++ b/ts-notification-service/src/main/java/notification/controller/NotificationController.java @@ -42,12 +42,12 @@ public boolean test_send_mail() { notifyInfo.setDate("Wed Jul 21 09:49:44 CST 2021"); notifyInfo.setEmail(test_mail_user); notifyInfo.setEndPlace("Test"); - notifyInfo.setStartingPlace("Test"); + notifyInfo.setStartPlace("Test"); notifyInfo.setOrderNumber("111-111-111"); notifyInfo.setPrice("100"); notifyInfo.setSeatClass("1"); notifyInfo.setSeatNumber("1102"); - notifyInfo.setStartingTime("Sat May 04 07:00:00 CST 2013"); + notifyInfo.setStartTime("Sat May 04 07:00:00 CST 2013"); notifyInfo.setUsername("h10g"); service.preserveSuccess(notifyInfo, null); diff --git a/ts-notification-service/src/main/java/notification/entity/NotifyInfo.java b/ts-notification-service/src/main/java/notification/entity/NotifyInfo.java index 3f249471a..378eb470a 100644 --- a/ts-notification-service/src/main/java/notification/entity/NotifyInfo.java +++ b/ts-notification-service/src/main/java/notification/entity/NotifyInfo.java @@ -3,19 +3,26 @@ import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import lombok.AllArgsConstructor; import lombok.Data; -import org.springframework.data.annotation.Id; -import org.springframework.data.mongodb.core.mapping.Document; +import javax.persistence.Column; +import javax.persistence.Id; + + +import javax.persistence.Entity; +import org.hibernate.annotations.GenericGenerator; import java.util.UUID; import lombok.Data; +import javax.persistence.Entity; + /** * @author fdse */ @Data @AllArgsConstructor -@Document(collection = "notification") +@Entity +@GenericGenerator(name = "jpa-uuid", strategy = "org.hibernate.id.UUIDGenerator") @JsonIgnoreProperties(ignoreUnknown = true) public class NotifyInfo { @@ -24,16 +31,18 @@ public NotifyInfo(){ } @Id - private UUID id; + @JsonIgnoreProperties(ignoreUnknown = true) + @Column(length = 36) + private String id; private Boolean sendStatus; private String email; private String orderNumber; private String username; - private String startingPlace; + private String startPlace; private String endPlace; - private String startingTime; + private String startTime; private String date; private String seatClass; private String seatNumber; diff --git a/ts-notification-service/src/main/java/notification/mq/RabbitReceive.java b/ts-notification-service/src/main/java/notification/mq/RabbitReceive.java index 2083443a8..f30b0ac53 100644 --- a/ts-notification-service/src/main/java/notification/mq/RabbitReceive.java +++ b/ts-notification-service/src/main/java/notification/mq/RabbitReceive.java @@ -40,9 +40,9 @@ public class RabbitReceive { @Value("${email_address:trainticket_notify@163.com}") String email; String username = "username"; - String startingPlace = "startingPlace"; + String startPlace = "startPlace"; String endPlace = "endPlace"; - String startingTime = "startingTime"; + String startTime = "startTime"; String seatClass = "seatClass"; String seatNumber = "seatNumber"; String date = "date"; @@ -53,11 +53,11 @@ public void process(String payload) { NotifyInfo info = JsonUtils.json2Object(payload, NotifyInfo.class); if (info == null) { - logger.error("Receive email object is null, error."); + logger.error("[process][json2Object][Receive email object is null, error]"); return; } - logger.info("Receive email object:" + info); + logger.info("[process][Receive email object][info: {}]", info); Mail mail = new Mail(); mail.setMailFrom(email); @@ -66,9 +66,9 @@ public void process(String payload) { Map model = new HashMap<>(); model.put(username, info.getUsername()); - model.put(startingPlace,info.getStartingPlace()); + model.put(startPlace,info.getStartPlace()); model.put(endPlace,info.getEndPlace()); - model.put(startingTime,info.getStartingTime()); + model.put(startTime,info.getStartTime()); model.put(date,info.getDate()); model.put(seatClass,info.getSeatClass()); model.put(seatNumber,info.getSeatNumber()); @@ -77,15 +77,16 @@ public void process(String payload) { try { mailService.sendEmail(mail, "preserve_success.ftl"); - logger.info("Send email to user " + username + " success"); + logger.info("[process][Send email to user {} success]", username); info.setSendStatus(true); } catch (Exception e) { - logger.error("Send email error: " + e); + logger.error("[process][mailService.sendEmail][Send email error][Exception: {}]", e.getMessage()); info.setSendStatus(false); } - info.setId(UUID.randomUUID()); - logger.info("Save notify info object [{}] into database", info.getId()); + + info.setId(UUID.randomUUID().toString()); + logger.info("[process][Save notify info object [{}] into database]", info.getId()); notifyRepository.save(info); } } diff --git a/ts-notification-service/src/main/java/notification/repository/NotifyRepository.java b/ts-notification-service/src/main/java/notification/repository/NotifyRepository.java index 121a3450e..29356d9da 100644 --- a/ts-notification-service/src/main/java/notification/repository/NotifyRepository.java +++ b/ts-notification-service/src/main/java/notification/repository/NotifyRepository.java @@ -2,20 +2,19 @@ import notification.entity.NotifyInfo; -import org.springframework.data.mongodb.repository.MongoRepository; -import org.springframework.data.mongodb.repository.Query; +import org.springframework.data.repository.CrudRepository; import org.springframework.stereotype.Repository; import java.util.List; -import java.util.UUID; +import java.util.Optional; @Repository -public interface NotifyRepository extends MongoRepository { +public interface NotifyRepository extends CrudRepository { - NotifyInfo findById(UUID id); + Optional findById(String id); @Override List findAll(); - void deleteById(UUID id); + void deleteById(String id); } diff --git a/ts-notification-service/src/main/java/notification/service/NotificationServiceImpl.java b/ts-notification-service/src/main/java/notification/service/NotificationServiceImpl.java index 76d6ca279..8355f9620 100644 --- a/ts-notification-service/src/main/java/notification/service/NotificationServiceImpl.java +++ b/ts-notification-service/src/main/java/notification/service/NotificationServiceImpl.java @@ -27,9 +27,9 @@ public class NotificationServiceImpl implements NotificationService{ String email = "trainticket_notify@163.com"; String username = "username"; - String startingPlace = "startingPlace"; + String startPlace = "startPlace"; String endPlace = "endPlace"; - String startingTime = "startingTime"; + String startTime = "startTime"; String seatClass = "seatClass"; String seatNumber = "seatNumber"; @@ -42,9 +42,9 @@ public boolean preserveSuccess(NotifyInfo info, HttpHeaders headers){ Map model = new HashMap<>(); model.put(username, info.getUsername()); - model.put(startingPlace,info.getStartingPlace()); + model.put(startPlace,info.getStartPlace()); model.put(endPlace,info.getEndPlace()); - model.put(startingTime,info.getStartingTime()); + model.put(startTime,info.getStartTime()); model.put("date",info.getDate()); model.put(seatClass,info.getSeatClass()); model.put(seatNumber,info.getSeatNumber()); @@ -55,7 +55,7 @@ public boolean preserveSuccess(NotifyInfo info, HttpHeaders headers){ mailService.sendEmail(mail,"preserve_success.ftl"); return true; } catch (Exception e) { - LOGGER.error(e.getMessage()); + LOGGER.error("[preserveSuccess][mailService.sendEmai][Exception: {}]", e.getMessage()); return false; } } @@ -69,9 +69,9 @@ public boolean orderCreateSuccess(NotifyInfo info, HttpHeaders headers){ Map model = new HashMap<>(); model.put(username, info.getUsername()); - model.put(startingPlace,info.getStartingPlace()); + model.put(startPlace,info.getStartPlace()); model.put(endPlace,info.getEndPlace()); - model.put(startingTime,info.getStartingTime()); + model.put(startTime,info.getStartTime()); model.put("date",info.getDate()); model.put(seatClass,info.getSeatClass()); model.put(seatNumber,info.getSeatNumber()); @@ -82,7 +82,7 @@ public boolean orderCreateSuccess(NotifyInfo info, HttpHeaders headers){ mailService.sendEmail(mail,"order_create_success.ftl"); return true; } catch (Exception e) { - LOGGER.error(e.getMessage()); + LOGGER.error("[orderCreateSuccess][mailService.sendEmai][Exception: {}]", e.getMessage()); return false; } } @@ -96,9 +96,9 @@ public boolean orderChangedSuccess(NotifyInfo info, HttpHeaders headers){ Map model = new HashMap<>(); model.put(username, info.getUsername()); - model.put(startingPlace,info.getStartingPlace()); + model.put(startPlace,info.getStartPlace()); model.put(endPlace,info.getEndPlace()); - model.put(startingTime,info.getStartingTime()); + model.put(startTime,info.getStartTime()); model.put("date",info.getDate()); model.put(seatClass,info.getSeatClass()); model.put(seatNumber,info.getSeatNumber()); @@ -109,7 +109,7 @@ public boolean orderChangedSuccess(NotifyInfo info, HttpHeaders headers){ mailService.sendEmail(mail,"order_changed_success.ftl"); return true; } catch (Exception e) { - LOGGER.error(e.getMessage()); + LOGGER.error("[orderChangedSuccess][mailService.sendEmai][Exception: {}]", e.getMessage()); return false; } } @@ -130,7 +130,7 @@ public boolean orderCancelSuccess(NotifyInfo info, HttpHeaders headers){ mailService.sendEmail(mail,"order_cancel_success.ftl"); return true; } catch (Exception e) { - LOGGER.error(e.getMessage()); + LOGGER.error("[orderCancelSuccess][mailService.sendEmai][Exception: {}]", e.getMessage()); return false; } } diff --git a/ts-notification-service/src/main/resources/application.yml b/ts-notification-service/src/main/resources/application.yml index dcc047176..66d2984b4 100644 --- a/ts-notification-service/src/main/resources/application.yml +++ b/ts-notification-service/src/main/resources/application.yml @@ -3,6 +3,10 @@ server: port: 17853 # HTTP (Tomcat) port spring: + cloud: + nacos: + discovery: + server-addr: ${NACOS_ADDRS:nacos-0.nacos-headless.default.svc.cluster.local,nacos-1.nacos-headless.default.svc.cluster.local,nacos-2.nacos-headless.default.svc.cluster.local} application: name: ts-notification-service mail: @@ -19,15 +23,21 @@ spring: starttls: enable: true required: true - data: - mongodb: - host: ${mongohost:ts-notification-mongo} - database: ts - port: 27017 + datasource: + url: jdbc:mysql://${NOTIFICATION_MYSQL_HOST:ts-notification-mysql}:${NOTIFICATION_MYSQL_PORT:3306}/${NOTIFICATION_MYSQL_DATABASE:ts-notification-mysql}?useSSL=false + username: ${NOTIFICATION_MYSQL_USER:root} + password: ${NOTIFICATION_MYSQL_PASSWORD:root} + driver-class-name: com.mysql.cj.jdbc.Driver + jpa: + hibernate: + ddl-auto: update + properties: + hibernate: + dialect: org.hibernate.dialect.MySQL5Dialect rabbitmq: host: ${rabbitmq_host:localhost} - port: ${rabbitmq_port:5672} + port: 5672 swagger: diff --git a/ts-notification-service/src/main/resources/templates/order_changed_success.ftl b/ts-notification-service/src/main/resources/templates/order_changed_success.ftl index 5da74f5a8..107850932 100644 --- a/ts-notification-service/src/main/resources/templates/order_changed_success.ftl +++ b/ts-notification-service/src/main/resources/templates/order_changed_success.ftl @@ -2,7 +2,7 @@

Dear ${username} ,

-

You have changed the ticket. The new ticket is from ${startingPlace} to ${endPlace} at ${startingTime} on

+

You have changed the ticket. The new ticket is from ${startPlace} to ${endPlace} at ${startTime} on

${date}.The seat is ${seatClass} and the seat number is ${seatNumber}.The new order number is ${orderNumber}

\ No newline at end of file diff --git a/ts-notification-service/src/main/resources/templates/order_create_success.ftl b/ts-notification-service/src/main/resources/templates/order_create_success.ftl index 0f109ed9a..49e64699f 100644 --- a/ts-notification-service/src/main/resources/templates/order_create_success.ftl +++ b/ts-notification-service/src/main/resources/templates/order_create_success.ftl @@ -2,7 +2,7 @@

Dear ${username} ,

-

You have payed the ticket from ${startingPlace} to ${endPlace} at ${startingTime} on ${date},the seat is ${seatClass}

+

You have payed the ticket from ${startPlace} to ${endPlace} at ${startTime} on ${date},the seat is ${seatClass}

and the seat number is ${seatNumber}.The order number is ${orderNumber}

\ No newline at end of file diff --git a/ts-notification-service/src/main/resources/templates/preserve_success.ftl b/ts-notification-service/src/main/resources/templates/preserve_success.ftl index efa07d689..ef93bc867 100644 --- a/ts-notification-service/src/main/resources/templates/preserve_success.ftl +++ b/ts-notification-service/src/main/resources/templates/preserve_success.ftl @@ -2,7 +2,7 @@

Dear ${username} ,

-

You have reserved the ticket from ${startingPlace} to ${endPlace} at ${startingTime} on ${date},the seat is ${seatClass}

+

You have reserved the ticket from ${startPlace} to ${endPlace} at ${startTime} on ${date},the seat is ${seatClass}

and the seat number is ${seatNumber}.The price is ${price} and you shall pay in 30 minutes.

\ No newline at end of file diff --git a/ts-order-other-service/pom.xml b/ts-order-other-service/pom.xml index 06909d3a2..c59d8773f 100644 --- a/ts-order-other-service/pom.xml +++ b/ts-order-other-service/pom.xml @@ -15,7 +15,7 @@ org.services ts-service 0.1.0 - ../ + ../pom.xml @@ -26,15 +26,21 @@ org.springframework.boot - spring-boot-starter-data-mongodb + spring-boot-starter-data-jpa + + + mysql + mysql-connector-java org.services ts-common 0.1.0 - - + + jakarta.validation + jakarta.validation-api + diff --git a/ts-order-other-service/src/main/java/other/OrderOtherApplication.java b/ts-order-other-service/src/main/java/other/OrderOtherApplication.java index b70c0bae2..5438d6d4f 100644 --- a/ts-order-other-service/src/main/java/other/OrderOtherApplication.java +++ b/ts-order-other-service/src/main/java/other/OrderOtherApplication.java @@ -3,6 +3,8 @@ import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.boot.web.client.RestTemplateBuilder; +import org.springframework.cloud.client.discovery.EnableDiscoveryClient; +import org.springframework.cloud.client.loadbalancer.LoadBalanced; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.EnableAspectJAutoProxy; import org.springframework.integration.annotation.IntegrationComponentScan; @@ -18,6 +20,7 @@ @EnableAsync @IntegrationComponentScan @EnableSwagger2 +@EnableDiscoveryClient public class OrderOtherApplication { public static void main(String[] args) { @@ -25,6 +28,7 @@ public static void main(String[] args) { SpringApplication.run(OrderOtherApplication.class, args); } + @LoadBalanced @Bean public RestTemplate restTemplate(RestTemplateBuilder builder) { return builder.build(); diff --git a/ts-order-other-service/src/main/java/other/controller/OrderOtherController.java b/ts-order-other-service/src/main/java/other/controller/OrderOtherController.java index dacd542bb..2933f3fda 100644 --- a/ts-order-other-service/src/main/java/other/controller/OrderOtherController.java +++ b/ts-order-other-service/src/main/java/other/controller/OrderOtherController.java @@ -1,12 +1,17 @@ package other.controller; +import edu.fudan.common.entity.Seat; +import edu.fudan.common.util.StringUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpEntity; import org.springframework.http.HttpHeaders; import org.springframework.web.bind.annotation.*; -import other.entity.*; + + +import other.entity.Order; +import other.entity.QueryInfo; import other.service.OrderOtherService; import java.util.Date; @@ -34,23 +39,21 @@ public String home() { @PostMapping(value = "/orderOther/tickets") public HttpEntity getTicketListByDateAndTripId(@RequestBody Seat seatRequest, @RequestHeader HttpHeaders headers) { - OrderOtherController.LOGGER.info("[Get Sold Ticket] Date: {}", seatRequest.getTravelDate().toString()); + OrderOtherController.LOGGER.info("[getSoldTickets][Get Sold Ticket][Travel Date: {}]", seatRequest.getTravelDate().toString()); return ok(orderService.getSoldTickets(seatRequest, headers)); } @CrossOrigin(origins = "*") @PostMapping(path = "/orderOther") public HttpEntity createNewOrder(@RequestBody Order createOrder, @RequestHeader HttpHeaders headers) { - OrderOtherController.LOGGER.info("[Create Order] Create Order form {} ---> {} at {}", createOrder.getFrom(), createOrder.getTo(), createOrder.getTravelDate()); - - OrderOtherController.LOGGER.info("[Verify Login] Success"); + OrderOtherController.LOGGER.info("[create][Create Order][from {} to {} at {}]", createOrder.getFrom(), createOrder.getTo(), createOrder.getTravelDate()); return ok(orderService.create(createOrder, headers)); } @CrossOrigin(origins = "*") @PostMapping(path = "/orderOther/admin") public HttpEntity addcreateNewOrder(@RequestBody Order order, @RequestHeader HttpHeaders headers) { - OrderOtherController.LOGGER.info("Add new order, OrderId: {}", order.getId()); + OrderOtherController.LOGGER.info("[addNewOrder][Add new order][OrderId: {}]", order.getId()); return ok(orderService.addNewOrder(order, headers)); } @@ -58,7 +61,7 @@ public HttpEntity addcreateNewOrder(@RequestBody Order order, @RequestHeader Htt @PostMapping(path = "/orderOther/query") public HttpEntity queryOrders(@RequestBody QueryInfo qi, @RequestHeader HttpHeaders headers) { - OrderOtherController.LOGGER.info("[Query Orders] Query Orders for {}", qi.getLoginId()); + OrderOtherController.LOGGER.info("[queryOrders][Query Orders][for LoginId :{}]", qi.getLoginId()); return ok(orderService.queryOrders(qi, qi.getLoginId(), headers)); } @@ -67,53 +70,53 @@ public HttpEntity queryOrders(@RequestBody QueryInfo qi, @PostMapping(path = "/orderOther/refresh") public HttpEntity queryOrdersForRefresh(@RequestBody QueryInfo qi, @RequestHeader HttpHeaders headers) { - OrderOtherController.LOGGER.info("[Query Orders] Query Orders for {}", qi.getLoginId()); + OrderOtherController.LOGGER.info("[queryOrdersForRefresh][Query Orders][for LoginId:{}]", qi.getLoginId()); return ok(orderService.queryOrdersForRefresh(qi, qi.getLoginId(), headers)); } @CrossOrigin(origins = "*") @GetMapping(path = "/orderOther/{travelDate}/{trainNumber}") - public HttpEntity calculateSoldTicket(@PathVariable Date travelDate, @PathVariable String trainNumber, + public HttpEntity calculateSoldTicket(@PathVariable String travelDate, @PathVariable String trainNumber, @RequestHeader HttpHeaders headers) { - OrderOtherController.LOGGER.info("[Calculate Sold Tickets] Date: {} TrainNumber: {}", travelDate, trainNumber); - return ok(orderService.queryAlreadySoldOrders(travelDate, trainNumber, headers)); + OrderOtherController.LOGGER.info("[queryAlreadySoldOrders][Calculate Sold Tickets][Date: {} TrainNumber: {}]", travelDate, trainNumber); + return ok(orderService.queryAlreadySoldOrders(StringUtils.String2Date(travelDate), trainNumber, headers)); } @CrossOrigin(origins = "*") @GetMapping(path = "/orderOther/price/{orderId}") public HttpEntity getOrderPrice(@PathVariable String orderId, @RequestHeader HttpHeaders headers) { - OrderOtherController.LOGGER.info("[Get Order Price] Order Id: {}", orderId); + OrderOtherController.LOGGER.info("[getOrderPrice][Get Order Price][Order Id: {}]", orderId); return ok(orderService.getOrderPrice(orderId, headers)); } @CrossOrigin(origins = "*") @GetMapping(path = "/orderOther/orderPay/{orderId}") public HttpEntity payOrder(@PathVariable String orderId, @RequestHeader HttpHeaders headers) { - OrderOtherController.LOGGER.info("[Pay Order] Order Id: {}", orderId); + OrderOtherController.LOGGER.info("[payOrder][Pay Order][Order Id: {}]", orderId); return ok(orderService.payOrder(orderId, headers)); } @CrossOrigin(origins = "*") @GetMapping(path = "/orderOther/{orderId}") public HttpEntity getOrderById(@PathVariable String orderId, @RequestHeader HttpHeaders headers) { - OrderOtherController.LOGGER.info("[Get Order By Id] Order Id: {}", orderId); + OrderOtherController.LOGGER.info("[getOrderById][Get Order By Id][Order Id: {}]", orderId); return ok(orderService.getOrderById(orderId, headers)); } @CrossOrigin(origins = "*") @GetMapping(path = "/orderOther/status/{orderId}/{status}") public HttpEntity modifyOrder(@PathVariable String orderId, @PathVariable int status, @RequestHeader HttpHeaders headers) { - OrderOtherController.LOGGER.info("[Modify Order Status] Order Id: {}", orderId); + OrderOtherController.LOGGER.info("[modifyOrder][Modify Order Status][Order Id: {}]", orderId); return ok(orderService.modifyOrder(orderId, status, headers)); } @CrossOrigin(origins = "*") @GetMapping(path = "/orderOther/security/{checkDate}/{accountId}") - public HttpEntity securityInfoCheck(@PathVariable Date checkDate, @PathVariable String accountId, + public HttpEntity securityInfoCheck(@PathVariable String checkDate, @PathVariable String accountId, @RequestHeader HttpHeaders headers) { - OrderOtherController.LOGGER.info("[Security Info Get]"); - return ok(orderService.checkSecurityAboutOrder(checkDate, accountId, headers)); + OrderOtherController.LOGGER.info("[checkSecurityAboutOrder][Security Info Get][CheckDate:{} , AccountId:{}]",checkDate,accountId); + return ok(orderService.checkSecurityAboutOrder(StringUtils.String2Date(checkDate), accountId, headers)); } @CrossOrigin(origins = "*") @@ -121,21 +124,21 @@ public HttpEntity securityInfoCheck(@PathVariable Date checkDate, @PathVariable public HttpEntity saveOrderInfo(@RequestBody Order orderInfo, @RequestHeader HttpHeaders headers) { - OrderOtherController.LOGGER.info("[Verify Login] Success"); + OrderOtherController.LOGGER.info("[saveChanges][Save Order Info][OrderId:{}]",orderInfo.getId()); return ok(orderService.saveChanges(orderInfo, headers)); } @CrossOrigin(origins = "*") @PutMapping(path = "/orderOther/admin") public HttpEntity updateOrder(@RequestBody Order order, @RequestHeader HttpHeaders headers) { - OrderOtherController.LOGGER.info("Update Order, OrderId: {}", order.getId()); + OrderOtherController.LOGGER.info("[updateOrder][Update Order][OrderId: {}]", order.getId()); return ok(orderService.updateOrder(order, headers)); } @CrossOrigin(origins = "*") @DeleteMapping(path = "/orderOther/{orderId}") public HttpEntity deleteOrder(@PathVariable String orderId, @RequestHeader HttpHeaders headers) { - OrderOtherController.LOGGER.info("[Delete Order] Order Id: {}", orderId); + OrderOtherController.LOGGER.info("[deleteOrder][Delete Order][OrderId: {}]", orderId); return ok(orderService.deleteOrder(orderId, headers)); } @@ -144,7 +147,7 @@ public HttpEntity deleteOrder(@PathVariable String orderId, @RequestHeader HttpH @CrossOrigin(origins = "*") @GetMapping(path = "/orderOther") public HttpEntity findAllOrder(@RequestHeader HttpHeaders headers) { - OrderOtherController.LOGGER.info("[Find All Order]"); + OrderOtherController.LOGGER.info("[getAllOrders][Find All Order]"); return ok(orderService.getAllOrders(headers)); } diff --git a/ts-order-other-service/src/main/java/other/entity/LeftTicketInfo.java b/ts-order-other-service/src/main/java/other/entity/LeftTicketInfo.java deleted file mode 100644 index 177b98a75..000000000 --- a/ts-order-other-service/src/main/java/other/entity/LeftTicketInfo.java +++ /dev/null @@ -1,28 +0,0 @@ -package other.entity; - -import lombok.Data; - -import javax.validation.Valid; -import javax.validation.constraints.NotNull; -import java.util.Set; - -/** - * @author fdse - */ -@Data -public class LeftTicketInfo { - @Valid - @NotNull - private Set soldTickets; - - public LeftTicketInfo(){ - //Default Constructor - } - - @Override - public String toString() { - return "LeftTicketInfo{" + - "soldTickets=" + soldTickets + - '}'; - } -} diff --git a/ts-order-other-service/src/main/java/other/entity/Order.java b/ts-order-other-service/src/main/java/other/entity/Order.java index dc45a47f5..759634932 100644 --- a/ts-order-other-service/src/main/java/other/entity/Order.java +++ b/ts-order-other-service/src/main/java/other/entity/Order.java @@ -1,37 +1,47 @@ package other.entity; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import edu.fudan.common.entity.OrderStatus; +import edu.fudan.common.entity.SeatClass; +import edu.fudan.common.util.StringUtils; import lombok.Data; -import org.springframework.data.annotation.Id; -import org.springframework.data.mongodb.core.mapping.Document; +import lombok.ToString; +import org.hibernate.annotations.GenericGenerator; +import javax.persistence.*; import java.util.Date; -import java.util.UUID; /** * @author fdse */ @Data -@Document(collection = "orders") +@Table(name = "orders_other") +@Entity +@GenericGenerator(name = "jpa-uuid", strategy = "org.hibernate.id.UUIDGenerator") +@ToString @JsonIgnoreProperties(ignoreUnknown = true) public class Order { - @Id - private UUID id; + @Column(length = 36) + @GeneratedValue(generator = "jpa-uuid") + private String id; + + private String boughtDate; + - private Date boughtDate; + private String travelDate; - private Date travelDate; - private Date travelTime; + private String travelTime; /** * Which Account Bought it */ - private UUID accountId; + @Column(length = 36) + private String accountId; /** - * Tickets bought for whom + * Tickets bought for whom.... */ private String contactsName; @@ -47,8 +57,10 @@ public class Order { private String seatNumber; + @Column(name = "from_station") private String from; + @Column(name = "to_station") private String to; private int status; @@ -56,8 +68,8 @@ public class Order { private String price; public Order(){ - boughtDate = new Date(System.currentTimeMillis()); - travelDate = new Date(123456789); + boughtDate = StringUtils.Date2String(new Date(System.currentTimeMillis())); + travelDate = StringUtils.Date2String(new Date(123456789)); trainNumber = "G1235"; coachNumber = 5; seatClass = SeatClass.FIRSTCLASS.getCode(); @@ -80,9 +92,9 @@ public boolean equals(Object obj) { return false; } Order other = (Order) obj; - return boughtDate.equals(other.getBoughtDate()) - && travelDate.equals(other.getTravelDate()) - && travelTime.equals(other.getTravelTime()) + return getBoughtDate().equals(other.getBoughtDate()) + && getBoughtDate().equals(other.getTravelDate()) + && getTravelTime().equals(other.getTravelTime()) && accountId .equals( other.getAccountId() ) && contactsName.equals(other.getContactsName()) && contactsDocumentNumber.equals(other.getContactsDocumentNumber()) @@ -104,9 +116,4 @@ public int hashCode() { return result; } - public void setTravelDate(int year,int month,int day){ - Date date = new Date(year,month,day,0,0,0); //NOSONAR - this.travelDate = date; - } - } diff --git a/ts-order-other-service/src/main/java/other/entity/OrderAlterInfo.java b/ts-order-other-service/src/main/java/other/entity/OrderAlterInfo.java index addad8d99..3bb964416 100644 --- a/ts-order-other-service/src/main/java/other/entity/OrderAlterInfo.java +++ b/ts-order-other-service/src/main/java/other/entity/OrderAlterInfo.java @@ -2,7 +2,10 @@ import lombok.AllArgsConstructor; import lombok.Data; +import org.hibernate.annotations.GenericGenerator; +import javax.persistence.Column; +import javax.persistence.GeneratedValue; import java.util.UUID; /** @@ -10,11 +13,16 @@ */ @Data @AllArgsConstructor +@GenericGenerator(name = "jpa-uuid", strategy = "org.hibernate.id.UUIDGenerator") public class OrderAlterInfo { - private UUID accountId; + @GeneratedValue(generator = "jpa-uuid") + @Column(length = 36) + private String accountId; - private UUID previousOrderId; + @GeneratedValue(generator = "jpa-uuid") + @Column(length = 36) + private String previousOrderId; private String loginToken; diff --git a/ts-order-other-service/src/main/java/other/entity/OrderSecurity.java b/ts-order-other-service/src/main/java/other/entity/OrderSecurity.java deleted file mode 100644 index 523fc4b68..000000000 --- a/ts-order-other-service/src/main/java/other/entity/OrderSecurity.java +++ /dev/null @@ -1,21 +0,0 @@ -package other.entity; - -import lombok.AllArgsConstructor; -import lombok.Data; - -/** - * @author fdse - */ -@Data -@AllArgsConstructor -public class OrderSecurity { - - private int orderNumInLastOneHour; - - private int orderNumOfValidOrder; - - public OrderSecurity() { - //Default Constructor - } - -} diff --git a/ts-order-other-service/src/main/java/other/entity/OrderStatus.java b/ts-order-other-service/src/main/java/other/entity/OrderStatus.java deleted file mode 100644 index cb8026723..000000000 --- a/ts-order-other-service/src/main/java/other/entity/OrderStatus.java +++ /dev/null @@ -1,63 +0,0 @@ -package other.entity; - -/** - * @author fdse - */ -public enum OrderStatus { - - /** - * not paid - */ - NOTPAID (0,"Not Paid"), - /** - * paid and not collected - */ - PAID (1,"Paid & Not Collected"), - /** - * colleacted - */ - COLLECTED (2,"Collected"), - /** - * cancel and rebook - */ - CHANGE (3,"Cancel & Rebook"), - /** - * cancel - */ - CANCEL (4,"Cancel"), - /** - * refunded - */ - REFUNDS (5,"Refunded"), - /** - * used - */ - USED (6,"Used"); - - private int code; - private String name; - - OrderStatus(int code, String name){ - this.code = code; - this.name = name; - } - - public int getCode(){ - return code; - } - - public String getName() { - return name; - } - - public static String getNameByCode(int code){ - OrderStatus[] orderStatusSet = OrderStatus.values(); - for(OrderStatus orderStatus : orderStatusSet){ - if(orderStatus.getCode() == code){ - return orderStatus.getName(); - } - } - return orderStatusSet[0].getName(); - } - -} diff --git a/ts-order-other-service/src/main/java/other/entity/QueryInfo.java b/ts-order-other-service/src/main/java/other/entity/QueryInfo.java index 41ea66399..66be8023f 100644 --- a/ts-order-other-service/src/main/java/other/entity/QueryInfo.java +++ b/ts-order-other-service/src/main/java/other/entity/QueryInfo.java @@ -1,5 +1,6 @@ package other.entity; +import edu.fudan.common.util.StringUtils; import lombok.Data; import java.util.Date; @@ -15,13 +16,13 @@ public class QueryInfo { */ private String loginId; - private Date travelDateStart; + private String travelDateStart; - private Date travelDateEnd; + private String travelDateEnd; - private Date boughtDateStart; + private String boughtDateStart; - private Date boughtDateEnd; + private String boughtDateEnd; private int state; @@ -35,7 +36,7 @@ public QueryInfo() { //Default Constructor } - public void enableTravelDateQuery(Date startTime, Date endTime) { + public void enableTravelDateQuery(String startTime, String endTime) { enableTravelDateQuery = true; travelDateStart = startTime; travelDateEnd = endTime; @@ -47,7 +48,7 @@ public void disableTravelDateQuery() { travelDateEnd = null; } - public void enableBoughtDateQuery(Date startTime, Date endTime) { + public void enableBoughtDateQuery(String startTime, String endTime) { enableBoughtDateQuery = true; boughtDateStart = startTime; boughtDateEnd = endTime; @@ -68,16 +69,4 @@ public void disableStateQuery() { enableTravelDateQuery = false; state = -1; } - - public boolean isEnableTravelDateQuery() { - return enableTravelDateQuery; - } - - public boolean isEnableBoughtDateQuery() { - return enableBoughtDateQuery; - } - - public boolean isEnableStateQuery() { - return enableStateQuery; - } } diff --git a/ts-order-other-service/src/main/java/other/entity/Seat.java b/ts-order-other-service/src/main/java/other/entity/Seat.java deleted file mode 100644 index 36f7f5109..000000000 --- a/ts-order-other-service/src/main/java/other/entity/Seat.java +++ /dev/null @@ -1,45 +0,0 @@ -package other.entity; - -import lombok.AllArgsConstructor; -import lombok.Data; - -import javax.validation.Valid; -import javax.validation.constraints.NotNull; -import java.util.Date; - -/** - * @author fdse - */ -@Data -@AllArgsConstructor -public class Seat { - @Valid - @NotNull - private Date travelDate; - - @Valid - @NotNull - private String trainNumber; - - @Valid - @NotNull - private String startStation; - - @Valid - @NotNull - private String destStation; - - @Valid - @NotNull - private int seatType; - - public Seat(){ - //Default Constructor - this.travelDate = new Date(); - this.trainNumber = ""; - this.startStation = ""; - this.destStation = ""; - this.seatType = 0; - } - -} diff --git a/ts-order-other-service/src/main/java/other/entity/SeatClass.java b/ts-order-other-service/src/main/java/other/entity/SeatClass.java deleted file mode 100644 index 2742a2a4a..000000000 --- a/ts-order-other-service/src/main/java/other/entity/SeatClass.java +++ /dev/null @@ -1,70 +0,0 @@ -package other.entity; - -/** - * @author fdse - */ -public enum SeatClass { - - /** - * no seat - */ - NONE (0,"NoSeat"), - /** - * green seat - */ - BUSINESS (1,"GreenSeat"), - /** - * first class seat - */ - FIRSTCLASS (2,"FirstClassSeat"), - /** - * second class seat - */ - SECONDCLASS (3,"SecondClassSeat"), - /** - * hard seat - */ - HARDSEAT (4,"HardSeat"), - /** - * soft seat - */ - SOFTSEAT (5,"SoftSeat"), - /** - * hard bed - */ - HARDBED (6,"HardBed"), - /** - * soft bed - */ - SOFTBED (7,"SoftBed"), - /** - * high soft seat - */ - HIGHSOFTBED (8,"HighSoftSeat"); - - private int code; - private String name; - - SeatClass(int code, String name){ - this.code = code; - this.name = name; - } - - public int getCode(){ - return code; - } - - public String getName() { - return name; - } - - public static String getNameByCode(int code){ - SeatClass[] seatClassSet = SeatClass.values(); - for(SeatClass seatClass : seatClassSet){ - if(seatClass.getCode() == code){ - return seatClass.getName(); - } - } - return seatClassSet[0].getName(); - } -} diff --git a/ts-order-other-service/src/main/java/other/entity/SoldTicket.java b/ts-order-other-service/src/main/java/other/entity/SoldTicket.java deleted file mode 100644 index e470977b3..000000000 --- a/ts-order-other-service/src/main/java/other/entity/SoldTicket.java +++ /dev/null @@ -1,47 +0,0 @@ -package other.entity; - -import lombok.Data; - -import java.util.Date; - -/** - * @author fdse - */ -@Data -public class SoldTicket { - - private Date travelDate; - - private String trainNumber; - - private int noSeat; - - private int businessSeat; - - private int firstClassSeat; - - private int secondClassSeat; - - private int hardSeat; - - private int softSeat; - - private int hardBed; - - private int softBed; - - private int highSoftBed; - - public SoldTicket(){ - noSeat = 0; - businessSeat = 0; - firstClassSeat = 0; - secondClassSeat = 0; - hardSeat = 0; - softSeat = 0; - hardBed = 0; - softBed = 0; - highSoftBed = 0; - } - -} diff --git a/ts-order-other-service/src/main/java/other/entity/Ticket.java b/ts-order-other-service/src/main/java/other/entity/Ticket.java deleted file mode 100644 index 12f09bc67..000000000 --- a/ts-order-other-service/src/main/java/other/entity/Ticket.java +++ /dev/null @@ -1,21 +0,0 @@ -package other.entity; - -import lombok.Data; - -/** - * @author fdse - */ -@Data -public class Ticket { - - private int seatNo; - - private String startStation; - - private String destStation; - - public Ticket(){ - //Default Constructor - } - -} diff --git a/ts-order-other-service/src/main/java/other/entity/TrainType.java b/ts-order-other-service/src/main/java/other/entity/TrainType.java deleted file mode 100644 index 5a0c7f17d..000000000 --- a/ts-order-other-service/src/main/java/other/entity/TrainType.java +++ /dev/null @@ -1,74 +0,0 @@ -package other.entity; - -/** - * @author fdse - */ -public enum TrainType { - - /** - * G - */ - GAOTIE (0,"G"), - /** - * D - */ - DONGCHE (1,"D"), - /** - * C - */ - CHENGJI (2,"C"), - /** - * Z - */ - ZHIDA (3,"Z"), - /** - * T - */ - TEKUAI (4,"T"), - /** - * E - */ - KUAISU (5,"K"), - /** - * L - */ - LINKE (6,"L"), - /** - * Y - */ - YOULAN (7,"Y"), - /** - * S - */ - CHENGJIAO (8,"S"), - /** - * - */ - OTHER (9,""); - - private int code; - private String name; - - TrainType(int code, String name){ - this.code = code; - this.name = name; - } - - public int getCode(){ - return code; - } - - public String getName() { - return name; - } - - public static String getNameByCode(int code){ - TrainType[] trainTypeSet = TrainType.values(); - for(TrainType trainType : trainTypeSet){ - if(trainType.getCode() == code){ - return trainType.getName(); - } - } - return trainTypeSet[0].getName(); - } -} diff --git a/ts-order-other-service/src/main/java/other/init/InitData.java b/ts-order-other-service/src/main/java/other/init/InitData.java index 0f6fef08b..e9117b1d4 100644 --- a/ts-order-other-service/src/main/java/other/init/InitData.java +++ b/ts-order-other-service/src/main/java/other/init/InitData.java @@ -1,6 +1,10 @@ package other.init; -import other.entity.*; +import edu.fudan.common.entity.OrderStatus; +import edu.fudan.common.util.StringUtils; +import org.apache.tomcat.jni.Time; +import other.entity.Order; +import edu.fudan.common.entity.SeatClass; import other.service.OrderOtherService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.CommandLineRunner; @@ -22,22 +26,21 @@ public void run(String... args)throws Exception{ Order order1 = new Order(); - order1.setAccountId(UUID.fromString("4d2a46c7-71cb-4cf1-b5bb-b68406d9da6f")); - order1.setBoughtDate(new Date(System.currentTimeMillis())); + order1.setAccountId("4d2a46c7-71cb-4cf1-b5bb-b68406d9da6f"); order1.setCoachNumber(5); order1.setContactsDocumentNumber("Test"); order1.setContactsName("Test"); order1.setDocumentType(1); order1.setFrom("shanghai"); - order1.setId(UUID.fromString("4d2a46c7-71cb-4cf1-c5bb-b68406d9da6f")); + order1.setId("4d2a46c7-71cb-4cf1-c5bb-b68406d9da6f"); order1.setPrice("100"); order1.setSeatClass(SeatClass.FIRSTCLASS.getCode()); order1.setSeatNumber("6A"); order1.setStatus(OrderStatus.PAID.getCode()); order1.setTo("taiyuan"); order1.setTrainNumber("K1235"); - order1.setTravelDate(new Date(123456799)); - order1.setTravelTime(new Date(123456799)); + order1.setTravelDate("2022-10-01 00:00:00"); //NOSONAR + order1.setTravelTime("2022-10-01 00:00:00"); //NOSONAR service.create(order1,null); } diff --git a/ts-order-other-service/src/main/java/other/repository/OrderOtherRepository.java b/ts-order-other-service/src/main/java/other/repository/OrderOtherRepository.java index 7bda896ae..876aa88f6 100644 --- a/ts-order-other-service/src/main/java/other/repository/OrderOtherRepository.java +++ b/ts-order-other-service/src/main/java/other/repository/OrderOtherRepository.java @@ -1,18 +1,19 @@ package other.repository; +import org.springframework.data.jpa.repository.Query; +import org.springframework.data.repository.CrudRepository; import other.entity.Order; -import org.springframework.data.mongodb.repository.MongoRepository; -import org.springframework.data.mongodb.repository.Query; import org.springframework.stereotype.Repository; import java.util.ArrayList; import java.util.Date; +import java.util.Optional; import java.util.UUID; /** * @author fdse */ @Repository -public interface OrderOtherRepository extends MongoRepository { +public interface OrderOtherRepository extends CrudRepository { /** * find order by id @@ -20,8 +21,9 @@ public interface OrderOtherRepository extends MongoRepository { * @param id id * @return Order */ - @Query("{ 'id': ?0 }") - Order findById(UUID id); +// @Query("{ 'id': ?0 }") + @Override + Optional findById(String id); /** * find all orders @@ -37,8 +39,8 @@ public interface OrderOtherRepository extends MongoRepository { * @param accountId account id * @return ArrayList */ - @Query("{ 'accountId' : ?0 }") - ArrayList findByAccountId(UUID accountId); +// @Query("{ 'accountId' : ?0 }") + ArrayList findByAccountId(String accountId); /** * find orders by travel date and train number @@ -47,8 +49,8 @@ public interface OrderOtherRepository extends MongoRepository { * @param trainNumber train number * @return ArrayList */ - @Query("{ 'travelDate' : ?0 , trainNumber : ?1 }") - ArrayList findByTravelDateAndTrainNumber(Date travelDate, String trainNumber); +// @Query("{ 'travelDate' : ?0 , trainNumber : ?1 }") + ArrayList findByTravelDateAndTrainNumber(String travelDate, String trainNumber); /** * delete order by id @@ -56,5 +58,6 @@ public interface OrderOtherRepository extends MongoRepository { * @param id id * @return null */ - void deleteById(UUID id); + @Override + void deleteById(String id); } diff --git a/ts-order-other-service/src/main/java/other/service/OrderOtherService.java b/ts-order-other-service/src/main/java/other/service/OrderOtherService.java index 0f6ddd653..defa509cd 100644 --- a/ts-order-other-service/src/main/java/other/service/OrderOtherService.java +++ b/ts-order-other-service/src/main/java/other/service/OrderOtherService.java @@ -1,18 +1,21 @@ package other.service; + +import edu.fudan.common.entity.Seat; import edu.fudan.common.util.Response; import org.springframework.http.HttpHeaders; -import other.entity.*; +import other.entity.Order; +import other.entity.QueryInfo; +import other.entity.OrderAlterInfo; import java.util.Date; -import java.util.UUID; /** * @author fdse */ public interface OrderOtherService { - Response findOrderById(UUID id, HttpHeaders headers); + Response findOrderById(String id, HttpHeaders headers); Response create(Order newOrder, HttpHeaders headers); @@ -20,7 +23,7 @@ public interface OrderOtherService { Response saveChanges(Order order, HttpHeaders headers); - Response cancelOrder(UUID accountId, UUID orderId, HttpHeaders headers); + Response cancelOrder(String accountId, String orderId, HttpHeaders headers); Response addNewOrder(Order order, HttpHeaders headers); diff --git a/ts-order-other-service/src/main/java/other/service/OrderOtherServiceImpl.java b/ts-order-other-service/src/main/java/other/service/OrderOtherServiceImpl.java index f8b0e0cfd..3295c8e52 100644 --- a/ts-order-other-service/src/main/java/other/service/OrderOtherServiceImpl.java +++ b/ts-order-other-service/src/main/java/other/service/OrderOtherServiceImpl.java @@ -1,8 +1,11 @@ package other.service; +import edu.fudan.common.entity.*; import edu.fudan.common.util.Response; +import edu.fudan.common.util.StringUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import org.springframework.cloud.client.discovery.DiscoveryClient; import org.springframework.core.ParameterizedTypeReference; import org.springframework.http.HttpEntity; import org.springframework.http.HttpHeaders; @@ -10,6 +13,8 @@ import org.springframework.http.ResponseEntity; import org.springframework.web.client.RestTemplate; import other.entity.*; +import other.entity.Order; +import other.entity.OrderAlterInfo; import other.repository.OrderOtherRepository; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; @@ -30,6 +35,16 @@ public class OrderOtherServiceImpl implements OrderOtherService { private static final Logger LOGGER = LoggerFactory.getLogger(OrderOtherServiceImpl.class); + @Autowired + private DiscoveryClient discoveryClient; + + private String getServiceUrl(String serviceName) { + return "http://" + serviceName; + } + +// @Value("${station-service.url}") +// String station_service_url; + String success = "Success"; String orderNotFound = "Order Not Found"; @@ -49,50 +64,53 @@ public Response getSoldTickets(Seat seatRequest, HttpHeaders headers) { LeftTicketInfo leftTicketInfo = new LeftTicketInfo(); leftTicketInfo.setSoldTickets(ticketSet); - OrderOtherServiceImpl.LOGGER.info("Left ticket info is: {}", leftTicketInfo.toString()); + OrderOtherServiceImpl.LOGGER.info("[getSoldTickets][Left ticket info][info is: {}]", leftTicketInfo.toString()); return new Response<>(1, success, leftTicketInfo); } else { - OrderOtherServiceImpl.LOGGER.warn("No content, seat from date: {}, train number: {}",seatRequest.getTravelDate(),seatRequest.getTrainNumber()); + OrderOtherServiceImpl.LOGGER.warn("[getSoldTickets][Seat][No content][seat from date: {}, train number: {}",seatRequest.getTravelDate(),seatRequest.getTrainNumber()); return new Response<>(0, "Seat is Null.", null); } } @Override - public Response findOrderById(UUID id, HttpHeaders headers) { - Order order = orderOtherRepository.findById(id); - if (order == null) { - OrderOtherServiceImpl.LOGGER.error("No content, id: {}",id); + public Response findOrderById(String id, HttpHeaders headers) { + Optional op = orderOtherRepository.findById(id); + if (!op.isPresent()) { + OrderOtherServiceImpl.LOGGER.warn("[findOrderById][Find Order By Id Fail][No content][id: {}]",id); return new Response<>(0, "No Content by this id", null); } else { + Order order = op.get(); + OrderOtherServiceImpl.LOGGER.info("[findOrderById][Find Order By Id Success][id: {}]",id); return new Response<>(1, success, order); } } @Override public Response create(Order order, HttpHeaders headers) { - OrderOtherServiceImpl.LOGGER.info("[Create Order] Ready Create Order"); + OrderOtherServiceImpl.LOGGER.info("[create][Create Order][Ready Create Order]"); ArrayList accountOrders = orderOtherRepository.findByAccountId(order.getAccountId()); if (accountOrders.contains(order)) { - OrderOtherServiceImpl.LOGGER.error("[Order Create] Fail.Order already exists, OrderId: {}", order.getId()); + OrderOtherServiceImpl.LOGGER.error("[create][Order Create Fail][Order already exists][OrderId: {}]", order.getId()); return new Response<>(0, "Order already exist", order); } else { - order.setId(UUID.randomUUID()); + order.setId(UUID.randomUUID().toString()); orderOtherRepository.save(order); - OrderOtherServiceImpl.LOGGER.info("[Order Create] Success."); - OrderOtherServiceImpl.LOGGER.info("[Order Create] Price: {}", order.getPrice()); + OrderOtherServiceImpl.LOGGER.info("[create][Order Create Success][OrderId:{},Price: {}]",order.getId(),order.getPrice()); return new Response<>(1, success, order); } } @Override public void initOrder(Order order, HttpHeaders headers) { - Order orderTemp = orderOtherRepository.findById(order.getId()); - if (orderTemp == null) { + Optional op = orderOtherRepository.findById(order.getId()); + if (!op.isPresent()) { orderOtherRepository.save(order); + OrderOtherServiceImpl.LOGGER.info("[initOrder][Init Order Success][OrderId: {}]", order.getId()); } else { - OrderOtherServiceImpl.LOGGER.error("[Init Order] Order Already Exists, OrderId: {}", order.getId()); + Order orderTemp = op.get(); + OrderOtherServiceImpl.LOGGER.error("[initOrder][Init Order Fail][Order Already Exists][OrderId: {}]", order.getId()); } } @@ -100,22 +118,23 @@ public void initOrder(Order order, HttpHeaders headers) { @Override public Response alterOrder(OrderAlterInfo oai, HttpHeaders headers) { - UUID oldOrderId = oai.getPreviousOrderId(); - Order oldOrder = orderOtherRepository.findById(oldOrderId); - if (oldOrder == null) { - OrderOtherServiceImpl.LOGGER.error("[Alter Order] Fail.Order do not exist, OrderId: {}", oldOrderId); + String oldOrderId = oai.getPreviousOrderId(); + + if (!orderOtherRepository.findById(oldOrderId).isPresent()) { + OrderOtherServiceImpl.LOGGER.error("[alterOrder][Alter Order Fail][Order do not exist][OrderId: {}]", oldOrderId); return new Response<>(0, "Old Order Does Not Exists", null); } + Order oldOrder = orderOtherRepository.findById(oldOrderId).get(); oldOrder.setStatus(OrderStatus.CANCEL.getCode()); saveChanges(oldOrder, headers); Order newOrder = oai.getNewOrderInfo(); - newOrder.setId(UUID.randomUUID()); + newOrder.setId(UUID.randomUUID().toString()); Response cor = create(oai.getNewOrderInfo(), headers); if (cor.getStatus() == 1) { - OrderOtherServiceImpl.LOGGER.info("[Alter Order] Success."); + OrderOtherServiceImpl.LOGGER.info("[alterOrder][Alter Order Success][newOrderId:{}]",newOrder.getId()); return new Response<>(1, "Alter Order Success", newOrder); } else { - OrderOtherServiceImpl.LOGGER.error("Alter Order Fail.Create new order fail, OrderId: {}", newOrder.getId()); + OrderOtherServiceImpl.LOGGER.error("[alterOrder][Alter Order Fail][Create new order fail][newOrderId: {}]", newOrder.getId()); return new Response<>(0, cor.getMsg(), null); } } @@ -123,8 +142,8 @@ public Response alterOrder(OrderAlterInfo oai, HttpHeaders headers) { @Override public Response> queryOrders(QueryInfo qi, String accountId, HttpHeaders headers) { //1.Get all orders of the user - ArrayList list = orderOtherRepository.findByAccountId(UUID.fromString(accountId)); - OrderOtherServiceImpl.LOGGER.info("[Query Order][Step 1] Get Orders Number of Account: {}", list.size()); + ArrayList list = orderOtherRepository.findByAccountId(accountId); + OrderOtherServiceImpl.LOGGER.info("[queryOrders][Step 1][Get Orders Number of Account][size: {}]", list.size()); //2.Check is these orders fit the requirement/ if (qi.isEnableStateQuery() || qi.isEnableBoughtDateQuery() || qi.isEnableTravelDateQuery()) { ArrayList finalList = new ArrayList<>(); @@ -142,11 +161,16 @@ public Response> queryOrders(QueryInfo qi, String accountId, Ht } else { statePassFlag = true; } - OrderOtherServiceImpl.LOGGER.info("[Query Order][Step 2][Check Status Fits End]"); + OrderOtherServiceImpl.LOGGER.info("[queryOrders][Step 2][Check Status Fits End]"); //4.Check order travel date requirement. + Date boughtDate = StringUtils.String2Date(tempOrder.getBoughtDate()); + Date travelDate = StringUtils.String2Date(tempOrder.getTravelDate()); + Date travelDateEnd = StringUtils.String2Date(qi.getTravelDateEnd()); + Date boughtDateStart = StringUtils.String2Date(qi.getBoughtDateStart()); + Date boughtDateEnd = StringUtils.String2Date(qi.getBoughtDateEnd()); if (qi.isEnableTravelDateQuery()) { - if (tempOrder.getTravelDate().before(qi.getTravelDateEnd()) && - tempOrder.getTravelDate().after(qi.getBoughtDateStart())) { + if (travelDate.before(travelDateEnd) && + travelDate.after(boughtDateStart)) { travelDatePassFlag = true; } else { travelDatePassFlag = false; @@ -154,11 +178,11 @@ public Response> queryOrders(QueryInfo qi, String accountId, Ht } else { travelDatePassFlag = true; } - OrderOtherServiceImpl.LOGGER.info("[Query Order][Step 2][Check Travel Date End]"); + OrderOtherServiceImpl.LOGGER.info("[queryOrders][Step 2][Check Travel Date End]"); //5.Check order bought date requirement. if (qi.isEnableBoughtDateQuery()) { - if (tempOrder.getBoughtDate().before(qi.getBoughtDateEnd()) && - tempOrder.getBoughtDate().after(qi.getBoughtDateStart())) { + if (boughtDate.before(boughtDateEnd) && + boughtDate.after(boughtDateStart)) { boughtDatePassFlag = true; } else { boughtDatePassFlag = false; @@ -166,17 +190,17 @@ public Response> queryOrders(QueryInfo qi, String accountId, Ht } else { boughtDatePassFlag = true; } - OrderOtherServiceImpl.LOGGER.info("[Query Order][Step 2][Check Bought Date End]"); + OrderOtherServiceImpl.LOGGER.info("[queryOrders][Step 2][Check Bought Date End]"); //6.check if all requirement fits. if (statePassFlag && boughtDatePassFlag && travelDatePassFlag) { finalList.add(tempOrder); } - OrderOtherServiceImpl.LOGGER.info("[Query Order][Step 2][Check All Requirement End]"); + OrderOtherServiceImpl.LOGGER.info("[queryOrders][Step 2][Check All Requirement End]"); } - OrderOtherServiceImpl.LOGGER.info("[Query Order] Get order num: {}", finalList.size()); + OrderOtherServiceImpl.LOGGER.info("[queryOrders][Get order num][size:{}]", finalList.size()); return new Response<>(1, "Get order num", finalList); } else { - OrderOtherServiceImpl.LOGGER.warn("[Query Order] Orders don't fit the requirement, loginId: {}", qi.getLoginId()); + OrderOtherServiceImpl.LOGGER.warn("[queryOrders][Orders don't fit the requirement][loginId: {}]", qi.getLoginId()); return new Response<>(1, "Get order num", list); } } @@ -189,10 +213,9 @@ public Response queryOrdersForRefresh(QueryInfo qi, String accountId, HttpHeader stationIds.add(order.getFrom()); stationIds.add(order.getTo()); } - List names = queryForStationId(stationIds, headers); for (int i = 0; i < orders.size(); i++) { - orders.get(i).setFrom(names.get(i * 2)); - orders.get(i).setTo(names.get(i * 2 + 1)); + orders.get(i).setFrom(stationIds.get(i * 2)); + orders.get(i).setTo(stationIds.get(i * 2 + 1)); } return new Response<>(1, success, orders); } @@ -200,23 +223,25 @@ public Response queryOrdersForRefresh(QueryInfo qi, String accountId, HttpHeader public List queryForStationId(List ids, HttpHeaders headers) { HttpEntity requestEntity = new HttpEntity(ids, null); + String station_service_url=getServiceUrl("ts-station-service"); ResponseEntity>> re = restTemplate.exchange( - "http://ts-station-service:12345/api/v1/stationservice/stations/namelist", + station_service_url + "/api/v1/stationservice/stations/namelist", HttpMethod.POST, requestEntity, new ParameterizedTypeReference>>() { }); - OrderOtherServiceImpl.LOGGER.info("Stations name list is : {}", re.getBody().toString()); + OrderOtherServiceImpl.LOGGER.info("[queryForStationId][Stations name list][Name List is : {}]", re.getBody().toString()); return re.getBody().getData(); } @Override public Response saveChanges(Order order, HttpHeaders headers) { - Order oldOrder = orderOtherRepository.findById(order.getId()); - if (oldOrder == null) { - OrderOtherServiceImpl.LOGGER.error("[Modify Order] Fail.Order not found, OrderId: {}", order.getId()); + Optional op = orderOtherRepository.findById(order.getId()); + if (!op.isPresent() ) { + OrderOtherServiceImpl.LOGGER.error("[saveChanges][Modify Order Fail][Order not found][OrderId: {}]", order.getId()); return new Response<>(0, orderNotFound, null); } else { + Order oldOrder = op.get(); oldOrder.setAccountId(order.getAccountId()); oldOrder.setBoughtDate(order.getBoughtDate()); oldOrder.setTravelDate(order.getTravelDate()); @@ -235,33 +260,34 @@ public Response saveChanges(Order order, HttpHeaders headers) { oldOrder.setContactsDocumentNumber(order.getContactsDocumentNumber()); orderOtherRepository.save(oldOrder); - OrderOtherServiceImpl.LOGGER.info(" Success."); + OrderOtherServiceImpl.LOGGER.info("[saveChanges][Modify Order Success][OrderId: {}]",order.getId()); return new Response<>(1, success, oldOrder); } } @Override - public Response cancelOrder(UUID accountId, UUID orderId, HttpHeaders headers) { + public Response cancelOrder(String accountId, String orderId, HttpHeaders headers) { - Order oldOrder = orderOtherRepository.findById(orderId); - if (oldOrder == null) { - OrderOtherServiceImpl.LOGGER.error("[Cancel Order] Fail.Order not found, OrderId: {}", orderId); + Optional op = orderOtherRepository.findById(orderId); + if (!op.isPresent()) { + OrderOtherServiceImpl.LOGGER.error("[cancelOrder][Cancel Order Fail][Order not found][OrderId: {}]", orderId); return new Response<>(0, orderNotFound, null); } else { + Order oldOrder = op.get(); oldOrder.setStatus(OrderStatus.CANCEL.getCode()); orderOtherRepository.save(oldOrder); - OrderOtherServiceImpl.LOGGER.info("[Cancel Order] Success."); + OrderOtherServiceImpl.LOGGER.info("[cancelOrder][Cancel Order Success][OrderId: {}]",oldOrder.getId()); return new Response<>(1, success, oldOrder); } } @Override public Response queryAlreadySoldOrders(Date travelDate, String trainNumber, HttpHeaders headers) { - ArrayList orders = orderOtherRepository.findByTravelDateAndTrainNumber(travelDate, trainNumber); + ArrayList orders = orderOtherRepository.findByTravelDateAndTrainNumber(StringUtils.Date2String(travelDate), trainNumber); SoldTicket cstr = new SoldTicket(); cstr.setTravelDate(travelDate); cstr.setTrainNumber(trainNumber); - OrderOtherServiceImpl.LOGGER.info("[Calculate Sold Ticket] Get Orders Number: {}", orders.size()); + OrderOtherServiceImpl.LOGGER.info("[queryAlreadySoldOrders][Calculate Sold Ticket][Get Orders Number: {}]", orders.size()); for (Order order : orders) { if (order.getStatus() >= OrderStatus.CHANGE.getCode()) { continue; @@ -285,7 +311,7 @@ public Response queryAlreadySoldOrders(Date travelDate, String trainNumber, Http } else if (order.getSeatClass() == SeatClass.HIGHSOFTBED.getCode()) { cstr.setHighSoftBed(cstr.getHighSoftBed() + 1); } else { - OrderOtherServiceImpl.LOGGER.info("[Calculate Sold Tickets] Seat class not exists. Order ID: {}", order.getId()); + OrderOtherServiceImpl.LOGGER.info("[queryAlreadySoldOrders][Calculate Sold Tickets][Seat class not exists][Order ID: {}]", order.getId()); } } return new Response<>(1, success, cstr); @@ -295,59 +321,67 @@ public Response queryAlreadySoldOrders(Date travelDate, String trainNumber, Http public Response getAllOrders(HttpHeaders headers) { ArrayList orders = orderOtherRepository.findAll(); if (orders == null) { - OrderOtherServiceImpl.LOGGER.warn("Find all orders warn: {}","No content"); + OrderOtherServiceImpl.LOGGER.warn("[getAllOrders][Find all orders warn][{}]","No content"); return new Response<>(0, "No Content", null); } else { + OrderOtherServiceImpl.LOGGER.info("[getAllOrders][Find all orders Success][size:{}]",orders.size()); return new Response<>(1, success, orders); } } @Override public Response modifyOrder(String orderId, int status, HttpHeaders headers) { - Order order = orderOtherRepository.findById(UUID.fromString(orderId)); - if (order == null) { - OrderOtherServiceImpl.LOGGER.error("Modify order error.Order not found, OrderId: {}",orderId); + Optional op = orderOtherRepository.findById(orderId); + if (!op.isPresent()) { + OrderOtherServiceImpl.LOGGER.error("[modifyOrder][Modify order Fail][Order not found][OrderId: {}]",orderId); return new Response<>(0, orderNotFound, null); } else { + Order order = op.get(); order.setStatus(status); orderOtherRepository.save(order); + OrderOtherServiceImpl.LOGGER.info("[modifyOrder][Modify order Success][OrderId: {}]",orderId); return new Response<>(1, success, order); } } @Override public Response getOrderPrice(String orderId, HttpHeaders headers) { - Order order = orderOtherRepository.findById(UUID.fromString(orderId)); - if (order == null) { - OrderOtherServiceImpl.LOGGER.error("Get order price error.Order not found, OrderId: {}",orderId); + Optional op = orderOtherRepository.findById(orderId); + if (!op.isPresent()) { + OrderOtherServiceImpl.LOGGER.error("[getOrderPrice][Get order price Fail][Order not found][OrderId: {}]",orderId); return new Response<>(0, orderNotFound, "-1.0"); } else { - OrderOtherServiceImpl.LOGGER.info("[Order Other Service][Get Order Price] Price: {}", order.getPrice()); + Order order = op.get(); + OrderOtherServiceImpl.LOGGER.info("[getOrderPrice][Get Order Price Success][OrderId:{} , Price: {}]", orderId,order.getPrice()); return new Response<>(1, success, order.getPrice()); } } @Override public Response payOrder(String orderId, HttpHeaders headers) { - Order order = orderOtherRepository.findById(UUID.fromString(orderId)); - if (order == null) { - OrderOtherServiceImpl.LOGGER.error("Pay order error.Order not found, OrderId: {}",orderId); + Optional op = orderOtherRepository.findById(orderId); + if (!op.isPresent()) { + OrderOtherServiceImpl.LOGGER.error("[payOrder][Pay order Fail][Order not found][OrderId: {}]",orderId); return new Response<>(0, orderNotFound, null); } else { + Order order = op.get(); order.setStatus(OrderStatus.PAID.getCode()); orderOtherRepository.save(order); + OrderOtherServiceImpl.LOGGER.info("[payOrder][Pay order Success][OrderId: {}]",orderId); return new Response<>(1, success, order); } } @Override public Response getOrderById(String orderId, HttpHeaders headers) { - Order order = orderOtherRepository.findById(UUID.fromString(orderId)); + Optional op = orderOtherRepository.findById(orderId); - if (order == null) { - OrderOtherServiceImpl.LOGGER.error("Order not found, OrderId: {}",orderId); + if(!op.isPresent()) { + OrderOtherServiceImpl.LOGGER.error("[getOrderById][Get Order By ID Fail][Order not found][OrderId: {}]",orderId); return new Response<>(0, orderNotFound, null); } else { + Order order = op.get(); + OrderOtherServiceImpl.LOGGER.info("[getOrderById][Get Order By ID Success][OrderId: {}]",orderId); return new Response<>(1, success, order); } } @@ -355,7 +389,7 @@ public Response getOrderById(String orderId, HttpHeaders headers) { @Override public Response checkSecurityAboutOrder(Date dateFrom, String accountId, HttpHeaders headers) { OrderSecurity result = new OrderSecurity(); - ArrayList orders = orderOtherRepository.findByAccountId(UUID.fromString(accountId)); + ArrayList orders = orderOtherRepository.findByAccountId(accountId); int countOrderInOneHour = 0; int countTotalValidOrder = 0; Calendar ca = Calendar.getInstance(); @@ -368,7 +402,8 @@ public Response checkSecurityAboutOrder(Date dateFrom, String accountId, HttpHea order.getStatus() == OrderStatus.COLLECTED.getCode()) { countTotalValidOrder += 1; } - if (order.getBoughtDate().after(dateFrom)) { + Date boughtDate = StringUtils.String2Date(order.getBoughtDate()); + if (boughtDate.after(dateFrom)) { countOrderInOneHour += 1; } } @@ -379,42 +414,45 @@ public Response checkSecurityAboutOrder(Date dateFrom, String accountId, HttpHea @Override public Response deleteOrder(String orderId, HttpHeaders headers) { - UUID orderUuid = UUID.fromString(orderId); - Order order = orderOtherRepository.findById(orderUuid); - if (order == null) { - OrderOtherServiceImpl.LOGGER.error("Delete order error.Order not found, OrderId: {}",orderId); + String orderUuid = UUID.fromString(orderId).toString(); + Optional op = orderOtherRepository.findById(orderUuid); + if(!op.isPresent()) { + OrderOtherServiceImpl.LOGGER.error("[deleteOrder][Delete order Fail][Order not found][OrderId: {}]",orderId); return new Response<>(0, "Order Not Exist.", null); } else { + Order order = op.get(); orderOtherRepository.deleteById(orderUuid); + OrderOtherServiceImpl.LOGGER.info("[deleteOrder][Delete order Success][OrderId: {}]",orderId); return new Response<>(1, success, orderUuid); } } @Override public Response addNewOrder(Order order, HttpHeaders headers) { - OrderOtherServiceImpl.LOGGER.info("[Admin Add Order] Ready Add Order."); + OrderOtherServiceImpl.LOGGER.info("[addNewOrder][Admin Add Order][Ready to Add Order]"); ArrayList accountOrders = orderOtherRepository.findByAccountId(order.getAccountId()); if (accountOrders.contains(order)) { - OrderOtherServiceImpl.LOGGER.error("[Admin Add Order] Fail.Order already exists, OrderId: {}",order.getId()); + OrderOtherServiceImpl.LOGGER.error("[addNewOrder][Admin Add Order Fail][Order already exists][OrderId: {}]",order.getId()); return new Response<>(0, "Order already exist", null); } else { - order.setId(UUID.randomUUID()); + order.setId(UUID.randomUUID().toString()); orderOtherRepository.save(order); - OrderOtherServiceImpl.LOGGER.info("[Admin Add Order] Success."); - OrderOtherServiceImpl.LOGGER.info("[Admin Add Order] Price: {}", order.getPrice()); + OrderOtherServiceImpl.LOGGER.info("[addNewOrder][Admin Add Order Success][OrderId:{} , Price:{}]",order.getId(),order.getPrice()); return new Response<>(1, success, order); } } @Override public Response updateOrder(Order order, HttpHeaders headers) { - LOGGER.info("UPDATE ORDER INFO :" + order.toString()); - Order oldOrder = orderOtherRepository.findById(order.getId()); - if (oldOrder == null) { - OrderOtherServiceImpl.LOGGER.error("[Admin Update Order] Fail.Order not found, OrderId: {}",order.getId()); + LOGGER.info("[updateOrder][Admin Update Order][Order Info:{}]",order.toString()); + + Optional op = orderOtherRepository.findById(order.getId()); + if(!op.isPresent()) { + OrderOtherServiceImpl.LOGGER.error("[updateOrder][Admin Update Order Fail][Order not found][OrderId: {}]",order.getId()); return new Response<>(0, orderNotFound, null); } else { - OrderOtherServiceImpl.LOGGER.info("{}", oldOrder.toString()); + Order oldOrder = op.get(); + //OrderOtherServiceImpl.LOGGER.info("{}", oldOrder.toString()); oldOrder.setAccountId(order.getAccountId()); oldOrder.setBoughtDate(order.getBoughtDate()); oldOrder.setTravelDate(order.getTravelDate()); @@ -431,7 +469,7 @@ public Response updateOrder(Order order, HttpHeaders headers) { oldOrder.setContactsDocumentNumber(order.getContactsDocumentNumber()); oldOrder.setDocumentType(order.getDocumentType()); orderOtherRepository.save(oldOrder); - OrderOtherServiceImpl.LOGGER.info("[Admin Update Order] Success."); + OrderOtherServiceImpl.LOGGER.info("[updateOrder][Admin Update Order Success][OrderId:{}]",oldOrder.getId()); return new Response<>(1, success, oldOrder); } } diff --git a/ts-order-other-service/src/main/resources/application.yml b/ts-order-other-service/src/main/resources/application.yml index 4a98f011b..2118972d1 100644 --- a/ts-order-other-service/src/main/resources/application.yml +++ b/ts-order-other-service/src/main/resources/application.yml @@ -3,15 +3,26 @@ server: port: 12032 # HTTP (Tomcat) port spring: + cloud: + nacos: + discovery: + server-addr: ${NACOS_ADDRS:nacos-0.nacos-headless.default.svc.cluster.local,nacos-1.nacos-headless.default.svc.cluster.local,nacos-2.nacos-headless.default.svc.cluster.local} application: name: ts-order-other-service - data: - mongodb: - host: ts-order-other-mongo -# username: user -# password: ${MONGODB_PASSWORD} - database: ts - port: 27017 + datasource: +# url: jdbc:mysql://localhost:3306/ts-order-other-mysql?useSSL=false + url: jdbc:mysql://${ORDER_OTHER_MYSQL_HOST:ts-order-other-mysql}:${ORDER_OTHER_MYSQL_PORT:3306}/${ORDER_OTHER_MYSQL_DATABASE:ts-order-other-mysql}?useSSL=false + username: ${ORDER_OTHER_MYSQL_USER:root} + password: ${ORDER_OTHER_MYSQL_PASSWORD:root} + driver-class-name: com.mysql.cj.jdbc.Driver + jpa: + hibernate: + ddl-auto: update + properties: + hibernate: + dialect: org.hibernate.dialect.MySQL5Dialect +# database-platform: org.hibernate.dialect.MySQL5InnoDBDialect + show-sql: true # rabbitmq: # host: rabbitmq @@ -38,4 +49,4 @@ spring: # binder: rabbit swagger: - controllerPackage: other.controller \ No newline at end of file + controllerPackage: other.controller diff --git a/ts-order-other-service/src/test/java/other/controller/OrderOtherControllerTest.java b/ts-order-other-service/src/test/java/other/controller/OrderOtherControllerTest.java index 2f67802dc..d201b9e05 100644 --- a/ts-order-other-service/src/test/java/other/controller/OrderOtherControllerTest.java +++ b/ts-order-other-service/src/test/java/other/controller/OrderOtherControllerTest.java @@ -1,6 +1,7 @@ package other.controller; import com.alibaba.fastjson.JSONObject; +import edu.fudan.common.entity.Seat; import edu.fudan.common.util.Response; import org.junit.Assert; import org.junit.Before; @@ -18,7 +19,6 @@ import org.springframework.test.web.servlet.setup.MockMvcBuilders; import other.entity.Order; import other.entity.QueryInfo; -import other.entity.Seat; import other.service.OrderOtherService; import java.util.Date; diff --git a/ts-order-other-service/src/test/java/other/service/OrderOtherServiceImplTest.java b/ts-order-other-service/src/test/java/other/service/OrderOtherServiceImplTest.java index 5d3696ca4..fda4c8d8a 100644 --- a/ts-order-other-service/src/test/java/other/service/OrderOtherServiceImplTest.java +++ b/ts-order-other-service/src/test/java/other/service/OrderOtherServiceImplTest.java @@ -1,6 +1,10 @@ package other.service; +import edu.fudan.common.entity.OrderSecurity;; +import edu.fudan.common.entity.Seat; import edu.fudan.common.util.Response; +import other.entity.Order; +import other.entity.OrderAlterInfo; import org.junit.Assert; import org.junit.Before; import org.junit.Test; @@ -47,7 +51,7 @@ public void testGetSoldTickets1() { Seat seatRequest = new Seat(); ArrayList list = new ArrayList<>(); list.add(new Order()); - Mockito.when(orderOtherRepository.findByTravelDateAndTrainNumber(Mockito.any(Date.class), Mockito.anyString())).thenReturn(list); + Mockito.when(orderOtherRepository.findByTravelDateAndTrainNumber(Mockito.any(String.class), Mockito.anyString())).thenReturn(list); Response result = orderOtherServiceImpl.getSoldTickets(seatRequest, headers); Assert.assertEquals("Success", result.getMsg()); } @@ -55,24 +59,24 @@ public void testGetSoldTickets1() { @Test public void testGetSoldTickets2() { Seat seatRequest = new Seat(); - Mockito.when(orderOtherRepository.findByTravelDateAndTrainNumber(Mockito.any(Date.class), Mockito.anyString())).thenReturn(null); + Mockito.when(orderOtherRepository.findByTravelDateAndTrainNumber(Mockito.any(String.class), Mockito.anyString())).thenReturn(null); Response result = orderOtherServiceImpl.getSoldTickets(seatRequest, headers); Assert.assertEquals(new Response<>(0, "Seat is Null.", null), result); } @Test public void testFindOrderById1() { - UUID id = UUID.randomUUID(); - Mockito.when(orderOtherRepository.findById(Mockito.any(UUID.class))).thenReturn(null); + String id = UUID.randomUUID().toString(); + Mockito.when(orderOtherRepository.findById(Mockito.any(String.class))).thenReturn(null); Response result = orderOtherServiceImpl.findOrderById(id, headers); Assert.assertEquals(new Response<>(0, "No Content by this id", null), result); } @Test public void testFindOrderById2() { - UUID id = UUID.randomUUID(); + String id = UUID.randomUUID().toString(); Order order = new Order(); - Mockito.when(orderOtherRepository.findById(Mockito.any(UUID.class))).thenReturn(order); + Mockito.when(orderOtherRepository.findById(Mockito.any(String.class)).get()).thenReturn(order); Response result = orderOtherServiceImpl.findOrderById(id, headers); Assert.assertEquals(new Response<>(1, "Success", order), result); } @@ -82,7 +86,7 @@ public void testCreate1() { Order order = new Order(); ArrayList accountOrders = new ArrayList<>(); accountOrders.add(order); - Mockito.when(orderOtherRepository.findByAccountId(Mockito.any(UUID.class))).thenReturn(accountOrders); + Mockito.when(orderOtherRepository.findByAccountId(Mockito.any(String.class))).thenReturn(accountOrders); Response result = orderOtherServiceImpl.create(order, headers); Assert.assertEquals(new Response<>(0, "Order already exist", order), result); } @@ -91,7 +95,7 @@ public void testCreate1() { public void testCreate2() { Order order = new Order(); ArrayList accountOrders = new ArrayList<>(); - Mockito.when(orderOtherRepository.findByAccountId(Mockito.any(UUID.class))).thenReturn(accountOrders); + Mockito.when(orderOtherRepository.findByAccountId(Mockito.any(String.class))).thenReturn(accountOrders); Mockito.when(orderOtherRepository.save(Mockito.any(Order.class))).thenReturn(null); Response result = orderOtherServiceImpl.create(order, headers); Assert.assertEquals("Success", result.getMsg()); @@ -100,7 +104,7 @@ public void testCreate2() { @Test public void testInitOrder1() { Order order = new Order(); - Mockito.when(orderOtherRepository.findById(Mockito.any(UUID.class))).thenReturn(null); + Mockito.when(orderOtherRepository.findById(Mockito.any(String.class))).thenReturn(null); Mockito.when(orderOtherRepository.save(Mockito.any(Order.class))).thenReturn(null); orderOtherServiceImpl.initOrder(order, headers); Mockito.verify(orderOtherRepository, times(1)).save(Mockito.any(Order.class)); @@ -109,7 +113,7 @@ public void testInitOrder1() { @Test public void testInitOrder2() { Order order = new Order(); - Mockito.when(orderOtherRepository.findById(Mockito.any(UUID.class))).thenReturn(order); + Mockito.when(orderOtherRepository.findById(Mockito.any(String.class)).get()).thenReturn(order); Mockito.when(orderOtherRepository.save(Mockito.any(Order.class))).thenReturn(null); orderOtherServiceImpl.initOrder(order, headers); Mockito.verify(orderOtherRepository, times(0)).save(Mockito.any(Order.class)); @@ -118,20 +122,20 @@ public void testInitOrder2() { @Test public void testAlterOrder1() { OrderAlterInfo oai = new OrderAlterInfo(); - Mockito.when(orderOtherRepository.findById(Mockito.any(UUID.class))).thenReturn(null); + Mockito.when(orderOtherRepository.findById(Mockito.any(String.class))).thenReturn(null); Response result = orderOtherServiceImpl.alterOrder(oai, headers); Assert.assertEquals(new Response<>(0, "Old Order Does Not Exists", null), result); } @Test public void testAlterOrder2() { - OrderAlterInfo oai = new OrderAlterInfo(UUID.randomUUID(), UUID.randomUUID(), "login_token", new Order()); + OrderAlterInfo oai = new OrderAlterInfo(UUID.randomUUID().toString(), UUID.randomUUID().toString(), "login_token", new Order()); Order order = new Order(); - Mockito.when(orderOtherRepository.findById(Mockito.any(UUID.class))).thenReturn(order); + Mockito.when(orderOtherRepository.findById(Mockito.any(String.class)).get()).thenReturn(order); Mockito.when(orderOtherRepository.save(Mockito.any(Order.class))).thenReturn(null); //mock create() ArrayList accountOrders = new ArrayList<>(); - Mockito.when(orderOtherRepository.findByAccountId(Mockito.any(UUID.class))).thenReturn(accountOrders); + Mockito.when(orderOtherRepository.findByAccountId(Mockito.any(String.class))).thenReturn(accountOrders); Response result = orderOtherServiceImpl.alterOrder(oai, headers); Assert.assertEquals("Alter Order Success", result.getMsg()); } @@ -142,20 +146,20 @@ public void testQueryOrders() { Order order = new Order(); order.setStatus(1); list.add(order); - Mockito.when(orderOtherRepository.findByAccountId(Mockito.any(UUID.class))).thenReturn(list); + Mockito.when(orderOtherRepository.findByAccountId(Mockito.any(String.class))).thenReturn(list); QueryInfo qi = new QueryInfo(); qi.setEnableStateQuery(true); qi.setEnableBoughtDateQuery(false); qi.setEnableTravelDateQuery(false); qi.setState(1); - Response result = orderOtherServiceImpl.queryOrders(qi, UUID.randomUUID().toString(), headers); + Response result = orderOtherServiceImpl.queryOrders(qi, UUID.randomUUID().toString().toString(), headers); Assert.assertEquals(new Response<>(1, "Get order num", list), result); } @Test public void testQueryOrdersForRefresh() { ArrayList list = new ArrayList<>(); - Mockito.when(orderOtherRepository.findByAccountId(Mockito.any(UUID.class))).thenReturn(list); + Mockito.when(orderOtherRepository.findByAccountId(Mockito.any(String.class))).thenReturn(list); //mock queryForStationId() Response> response = new Response<>(); ResponseEntity>> re = new ResponseEntity<>(response, HttpStatus.OK); @@ -169,7 +173,7 @@ public void testQueryOrdersForRefresh() { qi.setEnableStateQuery(false); qi.setEnableBoughtDateQuery(false); qi.setEnableTravelDateQuery(false); - Response result = orderOtherServiceImpl.queryOrdersForRefresh(qi, UUID.randomUUID().toString(), headers); + Response result = orderOtherServiceImpl.queryOrdersForRefresh(qi, UUID.randomUUID().toString().toString(), headers); Assert.assertEquals("Success", result.getMsg()); } @@ -192,7 +196,7 @@ public void testQueryForStationId() { @Test public void testSaveChanges1() { Order order = new Order(); - Mockito.when(orderOtherRepository.findById(Mockito.any(UUID.class))).thenReturn(null); + Mockito.when(orderOtherRepository.findById(Mockito.any(String.class))).thenReturn(null); Response result = orderOtherServiceImpl.saveChanges(order, headers); Assert.assertEquals(new Response<>(0, "Order Not Found", null), result); } @@ -200,7 +204,7 @@ public void testSaveChanges1() { @Test public void testSaveChanges2() { Order order = new Order(); - Mockito.when(orderOtherRepository.findById(Mockito.any(UUID.class))).thenReturn(order); + Mockito.when(orderOtherRepository.findById(Mockito.any(String.class)).get()).thenReturn(order); Mockito.when(orderOtherRepository.save(Mockito.any(Order.class))).thenReturn(null); Response result = orderOtherServiceImpl.saveChanges(order, headers); Assert.assertEquals(new Response<>(1, "Success", order), result); @@ -208,24 +212,24 @@ public void testSaveChanges2() { @Test public void testCancelOrder1() { - Mockito.when(orderOtherRepository.findById(Mockito.any(UUID.class))).thenReturn(null); - Response result = orderOtherServiceImpl.cancelOrder(UUID.randomUUID(), UUID.randomUUID(), headers); + Mockito.when(orderOtherRepository.findById(Mockito.any(String.class))).thenReturn(null); + Response result = orderOtherServiceImpl.cancelOrder(UUID.randomUUID().toString(), UUID.randomUUID().toString(), headers); Assert.assertEquals(new Response<>(0, "Order Not Found", null), result); } @Test public void testCancelOrder2() { Order oldOrder = new Order(); - Mockito.when(orderOtherRepository.findById(Mockito.any(UUID.class))).thenReturn(oldOrder); + Mockito.when(orderOtherRepository.findById(Mockito.any(String.class)).get()).thenReturn(oldOrder); Mockito.when(orderOtherRepository.save(Mockito.any(Order.class))).thenReturn(null); - Response result = orderOtherServiceImpl.cancelOrder(UUID.randomUUID(), UUID.randomUUID(), headers); + Response result = orderOtherServiceImpl.cancelOrder(UUID.randomUUID().toString(), UUID.randomUUID().toString(), headers); Assert.assertEquals("Success", result.getMsg()); } @Test public void testQueryAlreadySoldOrders() { ArrayList orders = new ArrayList<>(); - Mockito.when(orderOtherRepository.findByTravelDateAndTrainNumber(Mockito.any(Date.class), Mockito.anyString())).thenReturn(orders); + Mockito.when(orderOtherRepository.findByTravelDateAndTrainNumber(Mockito.any(String.class), Mockito.anyString())).thenReturn(orders); Response result = orderOtherServiceImpl.queryAlreadySoldOrders(new Date(), "G1234", headers); Assert.assertEquals("Success", result.getMsg()); } @@ -247,87 +251,87 @@ public void testGetAllOrders2() { @Test public void testModifyOrder1() { - Mockito.when(orderOtherRepository.findById(Mockito.any(UUID.class))).thenReturn(null); - Response result = orderOtherServiceImpl.modifyOrder(UUID.randomUUID().toString(), 1, headers); + Mockito.when(orderOtherRepository.findById(Mockito.any(String.class))).thenReturn(null); + Response result = orderOtherServiceImpl.modifyOrder(UUID.randomUUID().toString().toString(), 1, headers); Assert.assertEquals(new Response<>(0, "Order Not Found", null), result); } @Test public void testModifyOrder2() { Order order = new Order(); - Mockito.when(orderOtherRepository.findById(Mockito.any(UUID.class))).thenReturn(order); + Mockito.when(orderOtherRepository.findById(Mockito.any(String.class)).get()).thenReturn(order); Mockito.when(orderOtherRepository.save(Mockito.any(Order.class))).thenReturn(null); - Response result = orderOtherServiceImpl.modifyOrder(UUID.randomUUID().toString(), 1, headers); + Response result = orderOtherServiceImpl.modifyOrder(UUID.randomUUID().toString().toString(), 1, headers); Assert.assertEquals("Success", result.getMsg()); } @Test public void testGetOrderPrice1() { - Mockito.when(orderOtherRepository.findById(Mockito.any(UUID.class))).thenReturn(null); - Response result = orderOtherServiceImpl.getOrderPrice(UUID.randomUUID().toString(), headers); + Mockito.when(orderOtherRepository.findById(Mockito.any(String.class))).thenReturn(null); + Response result = orderOtherServiceImpl.getOrderPrice(UUID.randomUUID().toString().toString(), headers); Assert.assertEquals(new Response<>(0, "Order Not Found", "-1.0"), result); } @Test public void testGetOrderPrice2() { Order order = new Order(); - Mockito.when(orderOtherRepository.findById(Mockito.any(UUID.class))).thenReturn(order); - Response result = orderOtherServiceImpl.getOrderPrice(UUID.randomUUID().toString(), headers); + Mockito.when(orderOtherRepository.findById(Mockito.any(String.class)).get()).thenReturn(order); + Response result = orderOtherServiceImpl.getOrderPrice(UUID.randomUUID().toString().toString(), headers); Assert.assertEquals(new Response<>(1, "Success", order.getPrice()), result); } @Test public void testPayOrder1() { - Mockito.when(orderOtherRepository.findById(Mockito.any(UUID.class))).thenReturn(null); - Response result = orderOtherServiceImpl.payOrder(UUID.randomUUID().toString(), headers); + Mockito.when(orderOtherRepository.findById(Mockito.any(String.class))).thenReturn(null); + Response result = orderOtherServiceImpl.payOrder(UUID.randomUUID().toString().toString(), headers); Assert.assertEquals(new Response<>(0, "Order Not Found", null), result); } @Test public void testPayOrder2() { Order order = new Order(); - Mockito.when(orderOtherRepository.findById(Mockito.any(UUID.class))).thenReturn(order); + Mockito.when(orderOtherRepository.findById(Mockito.any(String.class)).get()).thenReturn(order); Mockito.when(orderOtherRepository.save(Mockito.any(Order.class))).thenReturn(null); - Response result = orderOtherServiceImpl.payOrder(UUID.randomUUID().toString(), headers); + Response result = orderOtherServiceImpl.payOrder(UUID.randomUUID().toString().toString(), headers); Assert.assertEquals("Success", result.getMsg()); } @Test public void testGetOrderById1() { - Mockito.when(orderOtherRepository.findById(Mockito.any(UUID.class))).thenReturn(null); - Response result = orderOtherServiceImpl.getOrderById(UUID.randomUUID().toString(), headers); + Mockito.when(orderOtherRepository.findById(Mockito.any(String.class))).thenReturn(null); + Response result = orderOtherServiceImpl.getOrderById(UUID.randomUUID().toString().toString(), headers); Assert.assertEquals(new Response<>(0, "Order Not Found", null), result); } @Test public void testGetOrderById2() { Order order = new Order(); - Mockito.when(orderOtherRepository.findById(Mockito.any(UUID.class))).thenReturn(order); - Response result = orderOtherServiceImpl.getOrderById(UUID.randomUUID().toString(), headers); + Mockito.when(orderOtherRepository.findById(Mockito.any(String.class)).get()).thenReturn(order); + Response result = orderOtherServiceImpl.getOrderById(UUID.randomUUID().toString().toString(), headers); Assert.assertEquals(new Response<>(1, "Success", order), result); } @Test public void testCheckSecurityAboutOrder() { ArrayList orders = new ArrayList<>(); - Mockito.when(orderOtherRepository.findByAccountId(Mockito.any(UUID.class))).thenReturn(orders); - Response result = orderOtherServiceImpl.checkSecurityAboutOrder(new Date(), UUID.randomUUID().toString(), headers); + Mockito.when(orderOtherRepository.findByAccountId(Mockito.any(String.class))).thenReturn(orders); + Response result = orderOtherServiceImpl.checkSecurityAboutOrder(new Date(), UUID.randomUUID().toString().toString(), headers); Assert.assertEquals(new Response<>(1, "Success", new OrderSecurity(0, 0)), result); } @Test public void testDeleteOrder1() { - Mockito.when(orderOtherRepository.findById(Mockito.any(UUID.class))).thenReturn(null); - Response result = orderOtherServiceImpl.deleteOrder(UUID.randomUUID().toString(), headers); + Mockito.when(orderOtherRepository.findById(Mockito.any(String.class))).thenReturn(null); + Response result = orderOtherServiceImpl.deleteOrder(UUID.randomUUID().toString().toString(), headers); Assert.assertEquals(new Response<>(0, "Order Not Exist.", null), result); } @Test public void testDeleteOrder2() { Order order = new Order(); - UUID orderUuid = UUID.randomUUID(); - Mockito.when(orderOtherRepository.findById(Mockito.any(UUID.class))).thenReturn(order); - Mockito.doNothing().doThrow(new RuntimeException()).when(orderOtherRepository).deleteById(Mockito.any(UUID.class)); + String orderUuid = UUID.randomUUID().toString(); + Mockito.when(orderOtherRepository.findById(Mockito.any(String.class)).get()).thenReturn(order); + Mockito.doNothing().doThrow(new RuntimeException()).when(orderOtherRepository).deleteById(Mockito.any(String.class)); Response result = orderOtherServiceImpl.deleteOrder(orderUuid.toString(), headers); Assert.assertEquals(new Response<>(1, "Success", orderUuid), result); } @@ -337,7 +341,7 @@ public void testAddNewOrder1() { Order order = new Order(); ArrayList accountOrders = new ArrayList<>(); accountOrders.add(order); - Mockito.when(orderOtherRepository.findByAccountId(Mockito.any(UUID.class))).thenReturn(accountOrders); + Mockito.when(orderOtherRepository.findByAccountId(Mockito.any(String.class))).thenReturn(accountOrders); Response result = orderOtherServiceImpl.addNewOrder(order, headers); Assert.assertEquals(new Response<>(0, "Order already exist", null), result); } @@ -346,7 +350,7 @@ public void testAddNewOrder1() { public void testAddNewOrder2() { Order order = new Order(); ArrayList accountOrders = new ArrayList<>(); - Mockito.when(orderOtherRepository.findByAccountId(Mockito.any(UUID.class))).thenReturn(accountOrders); + Mockito.when(orderOtherRepository.findByAccountId(Mockito.any(String.class))).thenReturn(accountOrders); Mockito.when(orderOtherRepository.save(Mockito.any(Order.class))).thenReturn(null); Response result = orderOtherServiceImpl.addNewOrder(order, headers); Assert.assertEquals("Success", result.getMsg()); @@ -355,7 +359,7 @@ public void testAddNewOrder2() { @Test public void testUpdateOrder1() { Order order = new Order(); - Mockito.when(orderOtherRepository.findById(Mockito.any(UUID.class))).thenReturn(null); + Mockito.when(orderOtherRepository.findById(Mockito.any(String.class))).thenReturn(null); Response result = orderOtherServiceImpl.updateOrder(order, headers); Assert.assertEquals(new Response<>(0, "Order Not Found", null), result); } @@ -363,7 +367,7 @@ public void testUpdateOrder1() { @Test public void testUpdateOrder2() { Order order = new Order(); - Mockito.when(orderOtherRepository.findById(Mockito.any(UUID.class))).thenReturn(order); + Mockito.when(orderOtherRepository.findById(Mockito.any(String.class)).get()).thenReturn(order); Mockito.when(orderOtherRepository.save(Mockito.any(Order.class))).thenReturn(null); Response result = orderOtherServiceImpl.updateOrder(order, headers); Assert.assertEquals("Success", result.getMsg()); diff --git a/ts-order-service/pom.xml b/ts-order-service/pom.xml index e2d7a9dc7..c54a99a6d 100644 --- a/ts-order-service/pom.xml +++ b/ts-order-service/pom.xml @@ -15,7 +15,7 @@ org.services ts-service 0.1.0 - ../ + ../pom.xml @@ -24,17 +24,29 @@ + + + + org.springframework.boot - spring-boot-starter-data-mongodb + spring-boot-starter-data-jpa + + + mysql + mysql-connector-java org.services ts-common 0.1.0 - - + + jakarta.validation + jakarta.validation-api + 2.0.2 + compile + diff --git a/ts-order-service/src/main/java/order/OrderApplication.java b/ts-order-service/src/main/java/order/OrderApplication.java index 1d014c145..70e5bb2a0 100644 --- a/ts-order-service/src/main/java/order/OrderApplication.java +++ b/ts-order-service/src/main/java/order/OrderApplication.java @@ -3,6 +3,8 @@ import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.boot.web.client.RestTemplateBuilder; +import org.springframework.cloud.client.discovery.EnableDiscoveryClient; +import org.springframework.cloud.client.loadbalancer.LoadBalanced; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.EnableAspectJAutoProxy; import org.springframework.integration.annotation.IntegrationComponentScan; @@ -18,11 +20,13 @@ @EnableAsync @IntegrationComponentScan @EnableSwagger2 +@EnableDiscoveryClient public class OrderApplication { public static void main(String[] args) { SpringApplication.run(OrderApplication.class, args); } + @LoadBalanced @Bean public RestTemplate restTemplate(RestTemplateBuilder builder) { return builder.build(); diff --git a/ts-order-service/src/main/java/order/controller/OrderController.java b/ts-order-service/src/main/java/order/controller/OrderController.java index 97193b5bd..fa989e885 100644 --- a/ts-order-service/src/main/java/order/controller/OrderController.java +++ b/ts-order-service/src/main/java/order/controller/OrderController.java @@ -1,5 +1,7 @@ package order.controller; +import edu.fudan.common.entity.Seat; +import edu.fudan.common.util.StringUtils; import order.entity.*; import order.service.OrderService; import org.slf4j.Logger; @@ -34,15 +36,14 @@ public String home() { @PostMapping(value = "/order/tickets") public HttpEntity getTicketListByDateAndTripId(@RequestBody Seat seatRequest, @RequestHeader HttpHeaders headers) { - OrderController.LOGGER.info("[Get Sold Ticket] Date: {}", seatRequest.getTravelDate().toString()); + OrderController.LOGGER.info("[getSoldTickets][Get Sold Ticket][Travel Date: {}]", seatRequest.getTravelDate().toString()); return ok(orderService.getSoldTickets(seatRequest, headers)); } @CrossOrigin(origins = "*") @PostMapping(path = "/order") public HttpEntity createNewOrder(@RequestBody Order createOrder, @RequestHeader HttpHeaders headers) { - OrderController.LOGGER.info("[Create Order] Create Order form {} ---> {} at {}", createOrder.getFrom(), createOrder.getTo(), createOrder.getTravelDate()); - OrderController.LOGGER.info("[Verify Login] Success"); + OrderController.LOGGER.info("[createNewOrder][Create Order][from {} to {} at {}]", createOrder.getFrom(), createOrder.getTo(), createOrder.getTravelDate()); return ok(orderService.create(createOrder, headers)); } @@ -56,8 +57,7 @@ public HttpEntity addcreateNewOrder(@RequestBody Order order, @RequestHeader Htt @PostMapping(path = "/order/query") public HttpEntity queryOrders(@RequestBody OrderInfo qi, @RequestHeader HttpHeaders headers) { - OrderController.LOGGER.info("[Query Orders] Query Orders for {}", qi.getLoginId()); - OrderController.LOGGER.info("[Verify Login] Success"); + OrderController.LOGGER.info("[queryOrders][Query Orders][for LoginId :{}]", qi.getLoginId()); return ok(orderService.queryOrders(qi, qi.getLoginId(), headers)); } @@ -65,22 +65,22 @@ public HttpEntity queryOrders(@RequestBody OrderInfo qi, @PostMapping(path = "/order/refresh") public HttpEntity queryOrdersForRefresh(@RequestBody OrderInfo qi, @RequestHeader HttpHeaders headers) { - OrderController.LOGGER.info("[Query Orders] Query Orders for {}", qi.getLoginId()); + OrderController.LOGGER.info("[queryOrdersForRefresh][Query Orders][for LoginId:{}]", qi.getLoginId()); return ok(orderService.queryOrdersForRefresh(qi, qi.getLoginId(), headers)); } @CrossOrigin(origins = "*") @GetMapping(path = "/order/{travelDate}/{trainNumber}") - public HttpEntity calculateSoldTicket(@PathVariable Date travelDate, @PathVariable String trainNumber, + public HttpEntity calculateSoldTicket(@PathVariable String travelDate, @PathVariable String trainNumber, @RequestHeader HttpHeaders headers) { - OrderController.LOGGER.info("[Calculate Sold Tickets] Date: {} TrainNumber: {}", travelDate, trainNumber); - return ok(orderService.queryAlreadySoldOrders(travelDate, trainNumber, headers)); + OrderController.LOGGER.info("[queryAlreadySoldOrders][Calculate Sold Tickets][Date: {} TrainNumber: {}]", travelDate, trainNumber); + return ok(orderService.queryAlreadySoldOrders(StringUtils.String2Date(travelDate), trainNumber, headers)); } @CrossOrigin(origins = "*") @GetMapping(path = "/order/price/{orderId}") public HttpEntity getOrderPrice(@PathVariable String orderId, @RequestHeader HttpHeaders headers) { - OrderController.LOGGER.info("[Get Order Price] Order Id: {}", orderId); + OrderController.LOGGER.info("[getOrderPrice][Get Order Price][OrderId: {}]", orderId); // String return ok(orderService.getOrderPrice(orderId, headers)); } @@ -89,7 +89,7 @@ public HttpEntity getOrderPrice(@PathVariable String orderId, @RequestHeader Htt @CrossOrigin(origins = "*") @GetMapping(path = "/order/orderPay/{orderId}") public HttpEntity payOrder(@PathVariable String orderId, @RequestHeader HttpHeaders headers) { - OrderController.LOGGER.info("[Pay Order] Order Id: {}", orderId); + OrderController.LOGGER.info("[payOrder][Pay Order][OrderId: {}]", orderId); // Order return ok(orderService.payOrder(orderId, headers)); } @@ -97,7 +97,7 @@ public HttpEntity payOrder(@PathVariable String orderId, @RequestHeader HttpHead @CrossOrigin(origins = "*") @GetMapping(path = "/order/{orderId}") public HttpEntity getOrderById(@PathVariable String orderId, @RequestHeader HttpHeaders headers) { - OrderController.LOGGER.info("[Get Order By Id] Order Id: {}", orderId); + OrderController.LOGGER.info("[getOrderById][Get Order By Id][OrderId: {}]", orderId); // Order return ok(orderService.getOrderById(orderId, headers)); } @@ -105,7 +105,7 @@ public HttpEntity getOrderById(@PathVariable String orderId, @RequestHeader Http @CrossOrigin(origins = "*") @GetMapping(path = "/order/status/{orderId}/{status}") public HttpEntity modifyOrder(@PathVariable String orderId, @PathVariable int status, @RequestHeader HttpHeaders headers) { - OrderController.LOGGER.info("[Modify Order Status] Order Id: {}", orderId); + OrderController.LOGGER.info("[modifyOrder][Modify Order Status][OrderId: {}]", orderId); // Order return ok(orderService.modifyOrder(orderId, status, headers)); } @@ -113,10 +113,10 @@ public HttpEntity modifyOrder(@PathVariable String orderId, @PathVariable int st @CrossOrigin(origins = "*") @GetMapping(path = "/order/security/{checkDate}/{accountId}") - public HttpEntity securityInfoCheck(@PathVariable Date checkDate, @PathVariable String accountId, + public HttpEntity securityInfoCheck(@PathVariable String checkDate, @PathVariable String accountId, @RequestHeader HttpHeaders headers) { - OrderController.LOGGER.info("[Security Info Get] {}", accountId); - return ok(orderService.checkSecurityAboutOrder(checkDate, accountId, headers)); + OrderController.LOGGER.info("[checkSecurityAboutOrder][Security Info Get][AccountId:{}]", accountId); + return ok(orderService.checkSecurityAboutOrder(StringUtils.String2Date(checkDate), accountId, headers)); } @@ -125,7 +125,7 @@ public HttpEntity securityInfoCheck(@PathVariable Date checkDate, @PathVariable public HttpEntity saveOrderInfo(@RequestBody Order orderInfo, @RequestHeader HttpHeaders headers) { - OrderController.LOGGER.info("[Verify Login] Success"); + OrderController.LOGGER.info("[saveChanges][Save Order Info][OrderId:{}]",orderInfo.getId()); return ok(orderService.saveChanges(orderInfo, headers)); } @@ -133,7 +133,7 @@ public HttpEntity saveOrderInfo(@RequestBody Order orderInfo, @PutMapping(path = "/order/admin") public HttpEntity updateOrder(@RequestBody Order order, @RequestHeader HttpHeaders headers) { // Order - OrderController.LOGGER.info("Update Order, OrderId: {}", order.getId()); + OrderController.LOGGER.info("[updateOrder][Update Order][OrderId: {}]", order.getId()); return ok(orderService.updateOrder(order, headers)); } @@ -141,7 +141,7 @@ public HttpEntity updateOrder(@RequestBody Order order, @RequestHeader HttpHeade @CrossOrigin(origins = "*") @DeleteMapping(path = "/order/{orderId}") public HttpEntity deleteOrder(@PathVariable String orderId, @RequestHeader HttpHeaders headers) { - OrderController.LOGGER.info("[Delete Order] Order Id: {}", orderId); + OrderController.LOGGER.info("[deleteOrder][Delete Order][OrderId: {}]", orderId); // Order return ok(orderService.deleteOrder(orderId, headers)); } @@ -151,7 +151,7 @@ public HttpEntity deleteOrder(@PathVariable String orderId, @RequestHeader HttpH @CrossOrigin(origins = "*") @GetMapping(path = "/order") public HttpEntity findAllOrder(@RequestHeader HttpHeaders headers) { - OrderController.LOGGER.info("[Find All Order]"); + OrderController.LOGGER.info("[getAllOrders][Find All Order]"); // ArrayList return ok(orderService.getAllOrders(headers)); } diff --git a/ts-order-service/src/main/java/order/entity/Order.java b/ts-order-service/src/main/java/order/entity/Order.java index 35902e29d..7184dfe7f 100644 --- a/ts-order-service/src/main/java/order/entity/Order.java +++ b/ts-order-service/src/main/java/order/entity/Order.java @@ -1,37 +1,47 @@ package order.entity; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import edu.fudan.common.entity.OrderStatus; +import edu.fudan.common.entity.SeatClass; +import edu.fudan.common.util.StringUtils; import lombok.Data; import lombok.ToString; -import org.springframework.data.annotation.Id; -import org.springframework.data.mongodb.core.mapping.Document; +import org.hibernate.annotations.GenericGenerator; + +import javax.persistence.*; import java.util.Date; -import java.util.UUID; + +import edu.fudan.common.entity.SeatClass; /** * @author fdse */ @Data -@Document(collection = "orders") +@Table(name = "orders") +@Entity +@GenericGenerator(name = "jpa-uuid", strategy = "org.hibernate.id.UUIDGenerator") @ToString @JsonIgnoreProperties(ignoreUnknown = true) public class Order { @Id - private UUID id; + @Column(length = 36) + @GeneratedValue(generator = "jpa-uuid") + private String id; - private Date boughtDate; + private String boughtDate; - private Date travelDate; + private String travelDate; - private Date travelTime; + private String travelTime; /** * Which Account Bought it */ - private UUID accountId; + @Column(length = 36) + private String accountId; /** * Tickets bought for whom.... @@ -50,8 +60,10 @@ public class Order { private String seatNumber; + @Column(name = "from_station") private String from; + @Column(name = "to_station") private String to; private int status; @@ -61,8 +73,8 @@ public class Order { public Order(){ - boughtDate = new Date(System.currentTimeMillis()); - travelDate = new Date(123456789); + boughtDate = StringUtils.Date2String(new Date(System.currentTimeMillis())); + travelDate = StringUtils.Date2String(new Date(123456789)); trainNumber = "G1235"; coachNumber = 5; seatClass = SeatClass.FIRSTCLASS.getCode(); @@ -85,9 +97,9 @@ public boolean equals(Object obj) { return false; } Order other = (Order) obj; - return boughtDate.equals(other.getBoughtDate()) - && travelDate.equals(other.getTravelDate()) - && travelTime.equals(other.getTravelTime()) + return getBoughtDate().equals(other.getBoughtDate()) + && getBoughtDate().equals(other.getTravelDate()) + && getTravelTime().equals(other.getTravelTime()) && accountId .equals( other.getAccountId() ) && contactsName.equals(other.getContactsName()) && contactsDocumentNumber.equals(other.getContactsDocumentNumber()) @@ -109,9 +121,4 @@ public int hashCode() { return result; } - public void setTravelDate(int year,int month,int day){ - Date date = new Date(year,month,day,0,0,0); //NOSONAR - this.travelDate = date; - } - } diff --git a/ts-order-service/src/main/java/order/entity/OrderAlterInfo.java b/ts-order-service/src/main/java/order/entity/OrderAlterInfo.java index 8c65ad36f..2da77adc6 100644 --- a/ts-order-service/src/main/java/order/entity/OrderAlterInfo.java +++ b/ts-order-service/src/main/java/order/entity/OrderAlterInfo.java @@ -2,7 +2,10 @@ import lombok.AllArgsConstructor; import lombok.Data; +import org.hibernate.annotations.GenericGenerator; +import javax.persistence.Column; +import javax.persistence.GeneratedValue; import java.util.UUID; /** @@ -10,11 +13,16 @@ */ @Data @AllArgsConstructor +@GenericGenerator(name = "jpa-uuid", strategy = "org.hibernate.id.UUIDGenerator") public class OrderAlterInfo { - private UUID accountId; + @GeneratedValue(generator = "jpa-uuid") + @Column(length = 36) + private String accountId; - private UUID previousOrderId; + @GeneratedValue(generator = "jpa-uuid") + @Column(length = 36) + private String previousOrderId; private String loginToken; diff --git a/ts-order-service/src/main/java/order/entity/OrderInfo.java b/ts-order-service/src/main/java/order/entity/OrderInfo.java index 3cb803cbd..469e40d6a 100644 --- a/ts-order-service/src/main/java/order/entity/OrderInfo.java +++ b/ts-order-service/src/main/java/order/entity/OrderInfo.java @@ -1,5 +1,6 @@ package order.entity; +import edu.fudan.common.util.StringUtils; import lombok.Data; import java.util.Date; @@ -15,13 +16,13 @@ public class OrderInfo { */ private String loginId; - private Date travelDateStart; + private String travelDateStart; - private Date travelDateEnd; + private String travelDateEnd; - private Date boughtDateStart; + private String boughtDateStart; - private Date boughtDateEnd; + private String boughtDateEnd; private int state; @@ -43,27 +44,11 @@ public void setLoginId(String loginId) { this.loginId = loginId; } - public Date getTravelDateStart() { - return travelDateStart; - } - - public Date getTravelDateEnd() { - return travelDateEnd; - } - - public Date getBoughtDateStart() { - return boughtDateStart; - } - - public Date getBoughtDateEnd() { - return boughtDateEnd; - } - public int getState() { return state; } - public void enableTravelDateQuery(Date startTime, Date endTime){ + public void enableTravelDateQuery(String startTime, String endTime){ enableTravelDateQuery = true; travelDateStart = startTime; travelDateEnd = endTime; @@ -75,7 +60,7 @@ public void disableTravelDateQuery(){ travelDateEnd = null; } - public void enableBoughtDateQuery(Date startTime, Date endTime){ + public void enableBoughtDateQuery(String startTime, String endTime){ enableBoughtDateQuery = true; boughtDateStart = startTime; boughtDateEnd = endTime; diff --git a/ts-order-service/src/main/java/order/entity/OrderSecurity.java b/ts-order-service/src/main/java/order/entity/OrderSecurity.java deleted file mode 100644 index 7a820e84a..000000000 --- a/ts-order-service/src/main/java/order/entity/OrderSecurity.java +++ /dev/null @@ -1,21 +0,0 @@ -package order.entity; - -import lombok.AllArgsConstructor; -import lombok.Data; - -/** - * @author fdse - */ -@Data -@AllArgsConstructor -public class OrderSecurity { - - private int orderNumInLastOneHour; - - private int orderNumOfValidOrder; - - public OrderSecurity() { - //Default Constructor - } - -} diff --git a/ts-order-service/src/main/java/order/entity/OrderStatus.java b/ts-order-service/src/main/java/order/entity/OrderStatus.java deleted file mode 100644 index 1b8225eeb..000000000 --- a/ts-order-service/src/main/java/order/entity/OrderStatus.java +++ /dev/null @@ -1,63 +0,0 @@ -package order.entity; - -/** - * @author fdse - */ -public enum OrderStatus { - - /** - * not paid - */ - NOTPAID (0,"Not Paid"), - /** - * paid and not collected - */ - PAID (1,"Paid & Not Collected"), - /** - * collected - */ - COLLECTED (2,"Collected"), - /** - * cancel and rebook - */ - CHANGE (3,"Cancel & Rebook"), - /** - * cancel - */ - CANCEL (4,"Cancel"), - /** - * refunded - */ - REFUNDS (5,"Refunded"), - /** - * used - */ - USED (6,"Used"); - - private int code; - private String name; - - OrderStatus(int code, String name){ - this.code = code; - this.name = name; - } - - public int getCode(){ - return code; - } - - public String getName() { - return name; - } - - public static String getNameByCode(int code){ - OrderStatus[] orderStatusSet = OrderStatus.values(); - for(OrderStatus orderStatus : orderStatusSet){ - if(orderStatus.getCode() == code){ - return orderStatus.getName(); - } - } - return orderStatusSet[0].getName(); - } - -} diff --git a/ts-order-service/src/main/java/order/entity/Seat.java b/ts-order-service/src/main/java/order/entity/Seat.java deleted file mode 100644 index 5f3051f70..000000000 --- a/ts-order-service/src/main/java/order/entity/Seat.java +++ /dev/null @@ -1,43 +0,0 @@ -package order.entity; - -import lombok.Data; - -import javax.validation.Valid; -import javax.validation.constraints.NotNull; -import java.util.Date; - -/** - * @author fdse - */ -@Data -public class Seat { - @Valid - @NotNull - private Date travelDate; - - @Valid - @NotNull - private String trainNumber; - - @Valid - @NotNull - private String startStation; - - @Valid - @NotNull - private String destStation; - - @Valid - @NotNull - private int seatType; - - public Seat(){ - //Default Constructor - this.travelDate = new Date(); - this.trainNumber = ""; - this.startStation = ""; - this.destStation = ""; - this.seatType = 0; - } - -} diff --git a/ts-order-service/src/main/java/order/entity/SeatClass.java b/ts-order-service/src/main/java/order/entity/SeatClass.java deleted file mode 100644 index f562570f2..000000000 --- a/ts-order-service/src/main/java/order/entity/SeatClass.java +++ /dev/null @@ -1,70 +0,0 @@ -package order.entity; - -/** - * @author fdse - */ -public enum SeatClass { - - /** - * no seat - */ - NONE (0,"NoSeat"), - /** - * green seat - */ - BUSINESS (1,"GreenSeat"), - /** - * first class seat - */ - FIRSTCLASS (2,"FirstClassSeat"), - /** - * second class seat - */ - SECONDCLASS (3,"SecondClassSeat"), - /** - * hard seat - */ - HARDSEAT (4,"HardSeat"), - /** - * soft seat - */ - SOFTSEAT (5,"SoftSeat"), - /** - * hard bed - */ - HARDBED (6,"HardBed"), - /** - * soft bed - */ - SOFTBED (7,"SoftBed"), - /** - * high soft seat - */ - HIGHSOFTBED (8,"HighSoftSeat"); - - private int code; - private String name; - - SeatClass(int code, String name){ - this.code = code; - this.name = name; - } - - public int getCode(){ - return code; - } - - public String getName() { - return name; - } - - public static String getNameByCode(int code){ - SeatClass[] seatClassSet = SeatClass.values(); - for(SeatClass seatClass : seatClassSet){ - if(seatClass.getCode() == code){ - return seatClass.getName(); - } - } - return seatClassSet[0].getName(); - } -} diff --git a/ts-order-service/src/main/java/order/entity/SoldTicket.java b/ts-order-service/src/main/java/order/entity/SoldTicket.java deleted file mode 100644 index 20e845c2f..000000000 --- a/ts-order-service/src/main/java/order/entity/SoldTicket.java +++ /dev/null @@ -1,47 +0,0 @@ -package order.entity; - -import lombok.Data; - -import java.util.Date; - -/** - * @author fdse - */ -@Data -public class SoldTicket { - - private Date travelDate; - - private String trainNumber; - - private int noSeat; - - private int businessSeat; - - private int firstClassSeat; - - private int secondClassSeat; - - private int hardSeat; - - private int softSeat; - - private int hardBed; - - private int softBed; - - private int highSoftBed; - - public SoldTicket(){ - noSeat = 0; - businessSeat = 0; - firstClassSeat = 0; - secondClassSeat = 0; - hardSeat = 0; - softSeat = 0; - hardBed = 0; - softBed = 0; - highSoftBed = 0; - } - -} diff --git a/ts-order-service/src/main/java/order/entity/TrainType.java b/ts-order-service/src/main/java/order/entity/TrainType.java deleted file mode 100644 index f58607ce6..000000000 --- a/ts-order-service/src/main/java/order/entity/TrainType.java +++ /dev/null @@ -1,74 +0,0 @@ -package order.entity; - -/** - * @author fdse - */ -public enum TrainType { - - /** - * G - */ - GAOTIE (0,"G"), - /** - * D - */ - DONGCHE (1,"D"), - /** - * C - */ - CHENGJI (2,"C"), - /** - * Z - */ - ZHIDA (3,"Z"), - /** - * T - */ - TEKUAI (4,"T"), - /** - * E - */ - KUAISU (5,"K"), - /** - * L - */ - LINKE (6,"L"), - /** - * Y - */ - YOULAN (7,"Y"), - /** - * S - */ - CHENGJIAO (8,"S"), - /** - * - */ - OTHER (9,""); - - private int code; - private String name; - - TrainType(int code, String name){ - this.code = code; - this.name = name; - } - - public int getCode(){ - return code; - } - - public String getName() { - return name; - } - - public static String getNameByCode(int code){ - TrainType[] trainTypeSet = TrainType.values(); - for(TrainType trainType : trainTypeSet){ - if(trainType.getCode() == code){ - return trainType.getName(); - } - } - return trainTypeSet[0].getName(); - } -} diff --git a/ts-order-service/src/main/java/order/init/InitData.java b/ts-order-service/src/main/java/order/init/InitData.java index 18fedbe66..3741bf587 100644 --- a/ts-order-service/src/main/java/order/init/InitData.java +++ b/ts-order-service/src/main/java/order/init/InitData.java @@ -1,5 +1,6 @@ package order.init; +import edu.fudan.common.util.StringUtils; import order.entity.Order; import order.service.OrderService; import org.springframework.beans.factory.annotation.Autowired; @@ -26,11 +27,10 @@ public class InitData implements CommandLineRunner { @Override public void run(String... args)throws Exception{ Order order = new Order(); - order.setId(UUID.fromString("5ad7750b-a68b-49c0-a8c0-32776b067703")); - order.setBoughtDate(new Date()); - order.setTravelDate(new Date("Sat Jul 29 00:00:00 GMT+0800 2017")); //NOSONAR - order.setTravelTime(new Date("Mon May 04 09:02:00 GMT+0800 2013")); //NOSONAR - order.setAccountId(UUID.fromString(accountId)); + order.setId("5ad7750b-a68b-49c0-a8c0-32776b067703"); + order.setTravelDate("2022-10-01 00:00:00"); //NOSONAR + order.setTravelTime("2022-10-01 00:00:00"); //NOSONAR + order.setAccountId(accountId); order.setContactsName(contactName); order.setDocumentType(1); order.setContactsDocumentNumber(contactDocumentNumber); @@ -46,11 +46,10 @@ public void run(String... args)throws Exception{ Order orderTwo = new Order(); - orderTwo.setId(UUID.fromString("8177ac5a-61ac-42f4-83f4-bd7b394d0531")); - orderTwo.setBoughtDate(new Date()); - orderTwo.setTravelDate(new Date("Sat Jul 29 00:00:00 GMT+0800 2017")); //NOSONAR - orderTwo.setTravelTime(new Date("Mon May 04 09:01:00 GMT+0800 2013")); //NOSONAR - orderTwo.setAccountId(UUID.fromString(accountId)); + orderTwo.setId("8177ac5a-61ac-42f4-83f4-bd7b394d0531"); + orderTwo.setTravelDate("2022-10-01 00:00:00"); //NOSONAR + orderTwo.setTravelTime("2022-10-01 00:00:00"); //NOSONAR + orderTwo.setAccountId(accountId); orderTwo.setContactsName(contactName); orderTwo.setDocumentType(1); orderTwo.setContactsDocumentNumber(contactDocumentNumber); @@ -65,11 +64,10 @@ public void run(String... args)throws Exception{ service.initOrder(orderTwo, null); Order orderThree = new Order(); - orderThree.setId(UUID.fromString("d3c91694-d5b8-424c-9974-e14c89226e49")); - orderThree.setBoughtDate(new Date()); - orderThree.setTravelDate(new Date("Sat Jul 29 00:00:00 GMT+0800 2017")); //NOSONAR - orderThree.setTravelTime(new Date("Mon May 04 09:00:00 GMT+0800 2013")); //NOSONAR - orderThree.setAccountId(UUID.fromString(accountId)); + orderThree.setId("d3c91694-d5b8-424c-9974-e14c89226e49"); + orderThree.setTravelDate("2022-10-01 00:00:00"); //NOSONAR + orderThree.setTravelTime("2022-10-01 00:00:00"); //NOSONAR + orderThree.setAccountId(accountId); orderThree.setContactsName(contactName); orderThree.setDocumentType(1); orderThree.setContactsDocumentNumber(contactDocumentNumber); diff --git a/ts-order-service/src/main/java/order/repository/OrderRepository.java b/ts-order-service/src/main/java/order/repository/OrderRepository.java index fdbd902f2..b9af5fbd1 100644 --- a/ts-order-service/src/main/java/order/repository/OrderRepository.java +++ b/ts-order-service/src/main/java/order/repository/OrderRepository.java @@ -1,30 +1,30 @@ package order.repository; import order.entity.Order; -import org.springframework.data.mongodb.repository.MongoRepository; -import org.springframework.data.mongodb.repository.Query; +import org.springframework.data.jpa.repository.JpaRepository; +import org.springframework.data.repository.CrudRepository; import org.springframework.stereotype.Repository; import java.util.ArrayList; import java.util.Date; +import java.util.Optional; import java.util.UUID; /** * @author fdse */ @Repository -public interface OrderRepository extends MongoRepository { +public interface OrderRepository extends JpaRepository { - @Query("{ 'id': ?0 }") - Order findById(UUID id); + @Override + Optional findById(String id); @Override ArrayList findAll(); - @Query("{ 'accountId' : ?0 }") - ArrayList findByAccountId(UUID accountId); + ArrayList findByAccountId(String accountId); - @Query("{ 'travelDate' : ?0 , trainNumber : ?1 }") - ArrayList findByTravelDateAndTrainNumber(Date travelDate,String trainNumber); + ArrayList findByTravelDateAndTrainNumber(String travelDate,String trainNumber); - void deleteById(UUID id); + @Override + void deleteById(String id); } diff --git a/ts-order-service/src/main/java/order/service/OrderService.java b/ts-order-service/src/main/java/order/service/OrderService.java index e5d657822..8328cd4ad 100644 --- a/ts-order-service/src/main/java/order/service/OrderService.java +++ b/ts-order-service/src/main/java/order/service/OrderService.java @@ -1,5 +1,6 @@ package order.service; +import edu.fudan.common.entity.Seat; import edu.fudan.common.util.Response; import order.entity.*; import org.springframework.http.HttpHeaders; @@ -12,13 +13,13 @@ */ public interface OrderService { - Response findOrderById(UUID id, HttpHeaders headers); + Response findOrderById(String id, HttpHeaders headers); Response create(Order newOrder, HttpHeaders headers); Response saveChanges(Order order, HttpHeaders headers); - Response cancelOrder(UUID accountId, UUID orderId, HttpHeaders headers); + Response cancelOrder(String accountId, String orderId, HttpHeaders headers); Response queryOrders(OrderInfo qi, String accountId, HttpHeaders headers); diff --git a/ts-order-service/src/main/java/order/service/OrderServiceImpl.java b/ts-order-service/src/main/java/order/service/OrderServiceImpl.java index d4ff1bffc..13a5e82ea 100644 --- a/ts-order-service/src/main/java/order/service/OrderServiceImpl.java +++ b/ts-order-service/src/main/java/order/service/OrderServiceImpl.java @@ -1,11 +1,18 @@ package order.service; +import edu.fudan.common.entity.*; import edu.fudan.common.util.Response; -import order.entity.*; +import edu.fudan.common.util.StringUtils; +import order.entity.OrderAlterInfo; +import order.entity.Order; +import order.entity.OrderInfo; import order.repository.OrderRepository; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.cloud.client.ServiceInstance; +import org.springframework.cloud.client.discovery.DiscoveryClient; import org.springframework.core.ParameterizedTypeReference; import org.springframework.http.HttpEntity; import org.springframework.http.HttpHeaders; @@ -30,9 +37,19 @@ public class OrderServiceImpl implements OrderService { private static final Logger LOGGER = LoggerFactory.getLogger(OrderServiceImpl.class); + @Autowired + private DiscoveryClient discoveryClient; + + private String getServiceUrl(String serviceName) { + return "http://" + serviceName; } + +// @Value("${station-service.url}") +// String station_service_url; + String success = "Success"; String orderNotFound = "Order Not Found"; + @Override public Response getSoldTickets(Seat seatRequest, HttpHeaders headers) { ArrayList list = orderRepository.findByTravelDateAndTrainNumber(seatRequest.getTravelDate(), @@ -45,37 +62,38 @@ public Response getSoldTickets(Seat seatRequest, HttpHeaders headers) { } LeftTicketInfo leftTicketInfo = new LeftTicketInfo(); leftTicketInfo.setSoldTickets(ticketSet); - OrderServiceImpl.LOGGER.info("Left ticket info is: {}", leftTicketInfo.toString()); + OrderServiceImpl.LOGGER.info("[getSoldTickets][Left ticket info][info is: {}]", leftTicketInfo.toString()); return new Response<>(1, success, leftTicketInfo); } else { - OrderServiceImpl.LOGGER.error("Left ticket info is empty, seat from date: {}, train number: {}",seatRequest.getTravelDate(),seatRequest.getTrainNumber()); + OrderServiceImpl.LOGGER.warn("[getSoldTickets][Seat][Left ticket info is empty][seat from date: {}, train number: {}]",seatRequest.getTravelDate(),seatRequest.getTrainNumber()); //warn级别,获取资源但资源为空 return new Response<>(0, "Order is Null.", null); } } @Override - public Response findOrderById(UUID id, HttpHeaders headers) { - Order order = orderRepository.findById(id); - if (order == null) { - OrderServiceImpl.LOGGER.error("No content, id: {}",id); + public Response findOrderById(String id, HttpHeaders headers) { + Optional op = orderRepository.findById(id); + if (!op.isPresent()) { + OrderServiceImpl.LOGGER.warn("[findOrderById][Find Order By Id Fail][No content][id: {}] ",id); //获取资源但资源为空 return new Response<>(0, "No Content by this id", null); } else { + Order order = op.get(); + OrderServiceImpl.LOGGER.warn("[findOrderById][Find Order By Id Success][id: {}] ",id); //获取资源但资源为空 return new Response<>(1, success, order); } } @Override public Response create(Order order, HttpHeaders headers) { - OrderServiceImpl.LOGGER.info("[Create Order] Ready Create Order."); + OrderServiceImpl.LOGGER.info("[create][Create Order][Ready to Create Order]"); ArrayList accountOrders = orderRepository.findByAccountId(order.getAccountId()); if (accountOrders.contains(order)) { - OrderServiceImpl.LOGGER.error("[Order Create] Fail.Order already exists, OrderId: {}", order.getId()); + OrderServiceImpl.LOGGER.error("[create][Order Create Fail][Order already exists][OrderId: {}]", order.getId()); return new Response<>(0, "Order already exist", null); } else { - order.setId(UUID.randomUUID()); + order.setId(UUID.randomUUID().toString()); orderRepository.save(order); - OrderServiceImpl.LOGGER.info("[Order Create] Success."); - OrderServiceImpl.LOGGER.info("[Order Create] Price: {}", order.getPrice()); + OrderServiceImpl.LOGGER.info("[create][Order Create Success][Order Price][OrderId:{} , Price: {}]",order.getId(),order.getPrice()); return new Response<>(1, success, order); } } @@ -83,22 +101,23 @@ public Response create(Order order, HttpHeaders headers) { @Override public Response alterOrder(OrderAlterInfo oai, HttpHeaders headers) { - UUID oldOrderId = oai.getPreviousOrderId(); - Order oldOrder = orderRepository.findById(oldOrderId); - if (oldOrder == null) { - OrderServiceImpl.LOGGER.error("[Alter Order] Fail.Order do not exist, OrderId: {}", oldOrderId); + String oldOrderId = oai.getPreviousOrderId(); + Optional op = orderRepository.findById(oldOrderId); + if (!op.isPresent()) { + OrderServiceImpl.LOGGER.error("[alterOrder][Alter Order Fail][Order do not exist][OrderId: {}]", oldOrderId); return new Response<>(0, "Old Order Does Not Exists", null); } + Order oldOrder = op.get(); oldOrder.setStatus(OrderStatus.CANCEL.getCode()); saveChanges(oldOrder, headers); Order newOrder = oai.getNewOrderInfo(); - newOrder.setId(UUID.randomUUID()); + newOrder.setId(UUID.randomUUID().toString()); Response cor = create(oai.getNewOrderInfo(), headers); if (cor.getStatus() == 1) { - OrderServiceImpl.LOGGER.info("[Alter Order] Success."); + OrderServiceImpl.LOGGER.info("[alterOrder][Alter Order Success][newOrderId: {}]",newOrder.getId()); return new Response<>(1, success, newOrder); } else { - OrderServiceImpl.LOGGER.error("Alter Order Fail.Create new order fail, OrderId: {}", newOrder.getId()); + OrderServiceImpl.LOGGER.error("[alterOrder][Alter Order Fail][Create new order fail][newOrderId: {}]", newOrder.getId()); return new Response<>(0, cor.getMsg(), null); } } @@ -106,8 +125,8 @@ public Response alterOrder(OrderAlterInfo oai, HttpHeaders headers) { @Override public Response> queryOrders(OrderInfo qi, String accountId, HttpHeaders headers) { //1.Get all orders of the user - ArrayList list = orderRepository.findByAccountId(UUID.fromString(accountId)); - OrderServiceImpl.LOGGER.info("[Query Order][Step 1] Get Orders Number of Account: {}", list.size()); + ArrayList list = orderRepository.findByAccountId(accountId); + OrderServiceImpl.LOGGER.info("[queryOrders][Step 1][Get Orders Number of Account][size: {}]", list.size()); //2.Check is these orders fit the requirement/ if (qi.isEnableStateQuery() || qi.isEnableBoughtDateQuery() || qi.isEnableTravelDateQuery()) { ArrayList finalList = new ArrayList<>(); @@ -125,11 +144,16 @@ public Response> queryOrders(OrderInfo qi, String accountId, Ht } else { statePassFlag = true; } - OrderServiceImpl.LOGGER.info("[Query Order][Step 2][Check Status Fits End]"); + OrderServiceImpl.LOGGER.info("[queryOrders][Step 2][Check Status Fits End]"); //4.Check order travel date requirement. + Date boughtDate = StringUtils.String2Date(tempOrder.getBoughtDate()); + Date travelDate = StringUtils.String2Date(tempOrder.getTravelDate()); + Date travelDateEnd = StringUtils.String2Date(qi.getTravelDateEnd()); + Date boughtDateStart = StringUtils.String2Date(qi.getBoughtDateStart()); + Date boughtDateEnd = StringUtils.String2Date(qi.getBoughtDateEnd()); if (qi.isEnableTravelDateQuery()) { - if (tempOrder.getTravelDate().before(qi.getTravelDateEnd()) && - tempOrder.getTravelDate().after(qi.getBoughtDateStart())) { + if (travelDate.before(travelDateEnd) && + travelDate.after(boughtDateStart)) { travelDatePassFlag = true; } else { travelDatePassFlag = false; @@ -137,11 +161,11 @@ public Response> queryOrders(OrderInfo qi, String accountId, Ht } else { travelDatePassFlag = true; } - OrderServiceImpl.LOGGER.info("[Query Order][Step 2][Check Travel Date End]"); + OrderServiceImpl.LOGGER.info("[queryOrders][Step 2][Check Travel Date End]"); //5.Check order bought date requirement. if (qi.isEnableBoughtDateQuery()) { - if (tempOrder.getBoughtDate().before(qi.getBoughtDateEnd()) && - tempOrder.getBoughtDate().after(qi.getBoughtDateStart())) { + if (boughtDate.before(boughtDateEnd) && + boughtDate.after(boughtDateStart)) { boughtDatePassFlag = true; } else { boughtDatePassFlag = false; @@ -149,17 +173,17 @@ public Response> queryOrders(OrderInfo qi, String accountId, Ht } else { boughtDatePassFlag = true; } - OrderServiceImpl.LOGGER.info("[Query Order][Step 2][Check Bought Date End]"); + OrderServiceImpl.LOGGER.info("[queryOrders][Step 2][Check Bought Date End]"); //6.check if all requirement fits. if (statePassFlag && boughtDatePassFlag && travelDatePassFlag) { finalList.add(tempOrder); } - OrderServiceImpl.LOGGER.info("[Query Order][Step 2][Check All Requirement End]"); + OrderServiceImpl.LOGGER.info("[queryOrders][Step 2][Check All Requirement End]"); } - OrderServiceImpl.LOGGER.info("[Query Order] Get order num: {}", finalList.size()); + OrderServiceImpl.LOGGER.info("[queryOrders][Get order num][size:{}]", finalList.size()); return new Response<>(1, "Get order num", finalList); } else { - OrderServiceImpl.LOGGER.warn("[Query Order] Orders don't fit the requirement, loginId: {}", qi.getLoginId()); + OrderServiceImpl.LOGGER.warn("[queryOrders][Orders don't fit the requirement][loginId: {}]", qi.getLoginId()); return new Response<>(1, "Get order num", list); } } @@ -173,10 +197,10 @@ public Response queryOrdersForRefresh(OrderInfo qi, String accountId, HttpHeader stationIds.add(order.getTo()); } - List names = queryForStationId(stationIds, headers); + // List names = queryForStationId(stationIds, headers); for (int i = 0; i < orders.size(); i++) { - orders.get(i).setFrom(names.get(i * 2)); - orders.get(i).setTo(names.get(i * 2 + 1)); + orders.get(i).setFrom(stationIds.get(i * 2)); + orders.get(i).setTo(stationIds.get(i * 2 + 1)); } return new Response<>(1, "Query Orders For Refresh Success", orders); } @@ -184,24 +208,25 @@ public Response queryOrdersForRefresh(OrderInfo qi, String accountId, HttpHeader public List queryForStationId(List ids, HttpHeaders headers) { HttpEntity requestEntity = new HttpEntity(ids, null); + String station_service_url=getServiceUrl("ts-station-service"); ResponseEntity>> re = restTemplate.exchange( - "http://ts-station-service:12345/api/v1/stationservice/stations/namelist", + station_service_url + "/api/v1/stationservice/stations/namelist", HttpMethod.POST, requestEntity, new ParameterizedTypeReference>>() { }); - OrderServiceImpl.LOGGER.info("Name List is: {}", re.getBody().toString()); + OrderServiceImpl.LOGGER.info("[queryForStationId][Station Name List][Name List is: {}]", re.getBody().toString()); return re.getBody().getData(); } @Override public Response saveChanges(Order order, HttpHeaders headers) { - - Order oldOrder = orderRepository.findById(order.getId()); - if (oldOrder == null) { - OrderServiceImpl.LOGGER.error("[Modify Order] Fail.Order not found, OrderId: {}", order.getId()); + Optional op = orderRepository.findById(order.getId()); + if (!op.isPresent()) { + OrderServiceImpl.LOGGER.error("[saveChanges][Modify Order Fail][Order not found][OrderId: {}]", order.getId()); return new Response<>(0, orderNotFound, null); } else { + Order oldOrder = op.get(); oldOrder.setAccountId(order.getAccountId()); oldOrder.setBoughtDate(order.getBoughtDate()); oldOrder.setTravelDate(order.getTravelDate()); @@ -218,32 +243,33 @@ public Response saveChanges(Order order, HttpHeaders headers) { oldOrder.setContactsDocumentNumber(order.getContactsDocumentNumber()); oldOrder.setDocumentType(order.getDocumentType()); orderRepository.save(oldOrder); - OrderServiceImpl.LOGGER.info("Success."); + OrderServiceImpl.LOGGER.info("[saveChanges][Modify Order Success][OrderId: {}]", order.getId()); return new Response<>(1, success, oldOrder); } } @Override - public Response cancelOrder(UUID accountId, UUID orderId, HttpHeaders headers) { - Order oldOrder = orderRepository.findById(orderId); - if (oldOrder == null) { - OrderServiceImpl.LOGGER.error("[Cancel Order] Fail.Order not found, OrderId: {}", orderId); + public Response cancelOrder(String accountId, String orderId, HttpHeaders headers) { + Optional op = orderRepository.findById(orderId); + if (!op.isPresent()) { + OrderServiceImpl.LOGGER.error("[cancelOrder][Cancel Order Fail][Order not found][OrderId: {}]", orderId); return new Response<>(0, orderNotFound, null); } else { + Order oldOrder = op.get(); oldOrder.setStatus(OrderStatus.CANCEL.getCode()); orderRepository.save(oldOrder); - OrderServiceImpl.LOGGER.info("[Cancel Order] Success."); + OrderServiceImpl.LOGGER.info("[cancelOrder][Cancel Order Success][OrderId: {}]", orderId); return new Response<>(1, success, oldOrder); } } @Override public Response queryAlreadySoldOrders(Date travelDate, String trainNumber, HttpHeaders headers) { - ArrayList orders = orderRepository.findByTravelDateAndTrainNumber(travelDate, trainNumber); + ArrayList orders = orderRepository.findByTravelDateAndTrainNumber(StringUtils.Date2String(travelDate), trainNumber); SoldTicket cstr = new SoldTicket(); cstr.setTravelDate(travelDate); cstr.setTrainNumber(trainNumber); - OrderServiceImpl.LOGGER.info("[Calculate Sold Ticket] Get Orders Number: {}", orders.size()); + OrderServiceImpl.LOGGER.info("[queryAlreadySoldOrders][Calculate Sold Ticket][Get Orders Number: {}]", orders.size()); for (Order order : orders) { if (order.getStatus() >= OrderStatus.CHANGE.getCode()) { continue; @@ -267,7 +293,7 @@ public Response queryAlreadySoldOrders(Date travelDate, String trainNumber, Http } else if (order.getSeatClass() == SeatClass.HIGHSOFTBED.getCode()) { cstr.setHighSoftBed(cstr.getHighSoftBed() + 1); } else { - OrderServiceImpl.LOGGER.info("[Calculate Sold Tickets] Seat class not exists. Order ID: {}", order.getId()); + OrderServiceImpl.LOGGER.info("[queryAlreadySoldOrders][Calculate Sold Tickets][Seat class not exists][Order ID: {}]", order.getId()); } } return new Response<>(1, success, cstr); @@ -277,76 +303,86 @@ public Response queryAlreadySoldOrders(Date travelDate, String trainNumber, Http public Response getAllOrders(HttpHeaders headers) { ArrayList orders = orderRepository.findAll(); if (orders != null && !orders.isEmpty()) { + OrderServiceImpl.LOGGER.warn("[getAllOrders][Find all orders Success][size:{}]",orders.size()); return new Response<>(1, "Success.", orders); } else { - OrderServiceImpl.LOGGER.warn("Find all orders warn: {}","No content"); + OrderServiceImpl.LOGGER.warn("[getAllOrders][Find all orders Fail][{}]","No content"); return new Response<>(0, "No Content.", null); } } @Override public Response modifyOrder(String orderId, int status, HttpHeaders headers) { - Order order = orderRepository.findById(UUID.fromString(orderId)); - if (order == null) { - OrderServiceImpl.LOGGER.error("Modify order error.Order not found, OrderId: {}",orderId); + Optional op = orderRepository.findById(orderId); + if (!op.isPresent()) { + OrderServiceImpl.LOGGER.error("[modifyOrder][Modify order Fail][Order not found][OrderId: {}]",orderId); return new Response<>(0, orderNotFound, null); } else { + Order order = op.get(); order.setStatus(status); orderRepository.save(order); + OrderServiceImpl.LOGGER.info("[modifyOrder][Modify order Success][OrderId: {}]",orderId); return new Response<>(1, "Modify Order Success", order); } } @Override public Response getOrderPrice(String orderId, HttpHeaders headers) { - Order order = orderRepository.findById(UUID.fromString(orderId)); - if (order == null) { - OrderServiceImpl.LOGGER.error("Get order price error.Order not found, OrderId: {}",orderId); + Optional op = orderRepository.findById(orderId); + if (!op.isPresent()) { + OrderServiceImpl.LOGGER.error("[getOrderPrice][Get order price Fail][Order not found][OrderId: {}]",orderId); return new Response<>(0, orderNotFound, "-1.0"); } else { - OrderServiceImpl.LOGGER.info("[Get Order Price] Price: {}", order.getPrice()); + Order order = op.get(); + OrderServiceImpl.LOGGER.info("[getOrderPrice][Get Order Price Success][OrderId: {} , Price: {}]",orderId ,order.getPrice()); return new Response<>(1, success, order.getPrice()); } } @Override public Response payOrder(String orderId, HttpHeaders headers) { - Order order = orderRepository.findById(UUID.fromString(orderId)); - if (order == null) { - OrderServiceImpl.LOGGER.error("Pay order error.Order not found, OrderId: {}",orderId); + Optional op = orderRepository.findById(orderId); + if (!op.isPresent()) { + OrderServiceImpl.LOGGER.error("[payOrder][Pay order Fail][Order not found][OrderId: {}]",orderId); return new Response<>(0, orderNotFound, null); } else { + Order order = op.get(); order.setStatus(OrderStatus.PAID.getCode()); orderRepository.save(order); + OrderServiceImpl.LOGGER.info("[payOrder][Pay order Success][OrderId: {}]",orderId); return new Response<>(1, "Pay Order Success.", order); } } @Override public Response getOrderById(String orderId, HttpHeaders headers) { - Order order = orderRepository.findById(UUID.fromString(orderId)); - if (order == null) { - OrderServiceImpl.LOGGER.error("Order not found, OrderId: {}",orderId); + Optional op = orderRepository.findById(orderId); + if (!op.isPresent()) { + OrderServiceImpl.LOGGER.warn("[getOrderById][Get Order By ID Fail][Order not found][OrderId: {}]",orderId); return new Response<>(0, orderNotFound, null); } else { + Order order = op.get(); + OrderServiceImpl.LOGGER.info("[getOrderById][Get Order By ID Success][OrderId: {}]",orderId); return new Response<>(1, "Success.", order); } } @Override public void initOrder(Order order, HttpHeaders headers) { - Order orderTemp = orderRepository.findById(order.getId()); - if (orderTemp == null) { + Optional op = orderRepository.findById(order.getId()); + if (!op.isPresent()) { orderRepository.save(order); + OrderServiceImpl.LOGGER.info("[initOrder][Init Order Success][OrderId: {}]", order.getId()); } else { - OrderServiceImpl.LOGGER.error("[Init Order] Order Already Exists, OrderId: {}", order.getId()); + Order orderTemp = op.get(); + OrderServiceImpl.LOGGER.error("[initOrder][Init Order Fail][Order Already Exists][OrderId: {}]", order.getId()); } } @Override public Response checkSecurityAboutOrder(Date dateFrom, String accountId, HttpHeaders headers) { OrderSecurity result = new OrderSecurity(); - ArrayList orders = orderRepository.findByAccountId(UUID.fromString(accountId)); + ArrayList orders = orderRepository.findByAccountId(accountId); int countOrderInOneHour = 0; int countTotalValidOrder = 0; Calendar ca = Calendar.getInstance(); @@ -359,7 +395,8 @@ public Response checkSecurityAboutOrder(Date dateFrom, String accountId, HttpHea order.getStatus() == OrderStatus.COLLECTED.getCode()) { countTotalValidOrder += 1; } - if (order.getBoughtDate().after(dateFrom)) { + Date boughtDate = StringUtils.String2Date(order.getBoughtDate()); + if (boughtDate.after(dateFrom)) { countOrderInOneHour += 1; } } @@ -370,43 +407,45 @@ public Response checkSecurityAboutOrder(Date dateFrom, String accountId, HttpHea @Override public Response deleteOrder(String orderId, HttpHeaders headers) { - UUID orderUuid = UUID.fromString(orderId); - Order order = orderRepository.findById(orderUuid); + String orderUuid = UUID.fromString(orderId).toString(); - if (order == null) { - OrderServiceImpl.LOGGER.error("Delete order error.Order not found, OrderId: {}",orderId); + Optional op = orderRepository.findById(orderUuid); + if (!op.isPresent()) { + OrderServiceImpl.LOGGER.error("[deleteOrder][Delete order Fail][Order not found][OrderId: {}]",orderId); return new Response<>(0, "Order Not Exist.", null); } else { + Order order = op.get(); orderRepository.deleteById(orderUuid); + OrderServiceImpl.LOGGER.info("[deleteOrder][Delete order Success][OrderId: {}]",orderId); return new Response<>(1, "Delete Order Success", order); } } @Override public Response addNewOrder(Order order, HttpHeaders headers) { - OrderServiceImpl.LOGGER.info("[Admin Add Order] Ready Add Order."); + OrderServiceImpl.LOGGER.info("[addNewOrder][Admin Add Order][Ready to Add Order]"); ArrayList accountOrders = orderRepository.findByAccountId(order.getAccountId()); if (accountOrders.contains(order)) { - OrderServiceImpl.LOGGER.error("[Admin Add Order] Fail.Order already exists, OrderId: {}",order.getId()); + OrderServiceImpl.LOGGER.error("[addNewOrder][Admin Add Order Fail][Order already exists][OrderId: {}]",order.getId()); return new Response<>(0, "Order already exist", null); } else { - order.setId(UUID.randomUUID()); + order.setId(UUID.randomUUID().toString()); orderRepository.save(order); - OrderServiceImpl.LOGGER.info("[Admin Add Order] Success."); - OrderServiceImpl.LOGGER.info("[Admin Add Order] Price: {}", order.getPrice()); + OrderServiceImpl.LOGGER.info("[addNewOrder][Admin Add Order Success][OrderId: {} , Price: {}]",order.getId() ,order.getPrice()); return new Response<>(1, "Add new Order Success", order); } } @Override public Response updateOrder(Order order, HttpHeaders headers) { - LOGGER.info("UPDATE ORDER INFO: " + order.toString()); - Order oldOrder = orderRepository.findById(order.getId()); - if (oldOrder == null) { - OrderServiceImpl.LOGGER.error("[Admin Update Order] Fail.Order not found, OrderId: {}",order.getId()); + LOGGER.info("[updateOrder][Admin Update Order][Order Info:{}] ", order.toString()); + Optional op = orderRepository.findById(order.getId()); + if (!op.isPresent()) { + OrderServiceImpl.LOGGER.error("[updateOrder][Admin Update Order Fail][Order not found][OrderId: {}]",order.getId()); return new Response<>(0, "Order Not Found, Can't update", null); } else { - OrderServiceImpl.LOGGER.info("{}", oldOrder.toString()); + Order oldOrder = op.get(); + //OrderServiceImpl.LOGGER.info("{}", oldOrder.toString()); oldOrder.setAccountId(order.getAccountId()); oldOrder.setBoughtDate(order.getBoughtDate()); oldOrder.setTravelDate(order.getTravelDate()); @@ -423,7 +462,7 @@ public Response updateOrder(Order order, HttpHeaders headers) { oldOrder.setContactsDocumentNumber(order.getContactsDocumentNumber()); oldOrder.setDocumentType(order.getDocumentType()); orderRepository.save(oldOrder); - OrderServiceImpl.LOGGER.info("[Admin Update Order] Success."); + OrderServiceImpl.LOGGER.info("[updateOrder][Admin Update Order Success][OrderId: {}]",order.getId()); return new Response<>(1, "Admin Update Order Success", oldOrder); } } diff --git a/ts-order-service/src/main/resources/application.yml b/ts-order-service/src/main/resources/application.yml index 77c34e788..dc93eb221 100644 --- a/ts-order-service/src/main/resources/application.yml +++ b/ts-order-service/src/main/resources/application.yml @@ -3,15 +3,23 @@ server: port: 12031 # HTTP (Tomcat) port spring: + cloud: + nacos: + discovery: + server-addr: ${NACOS_ADDRS:127.0.0.1:8848} application: name: ts-order-service - data: - mongodb: - host: ts-order-mongo -# username: user -# password: ${MONGODB_PASSWORD} - database: ts - port: 27017 + datasource: + url: jdbc:mysql://${ORDER_MYSQL_HOST:10.176.122.1}:${ORDER_MYSQL_PORT:3306}/${ORDER_MYSQL_DATABASE:ts}?useSSL=false + username: ${ORDER_MYSQL_USER:root} + password: ${ORDER_MYSQL_PASSWORD:Abcd1234#} + driver-class-name: com.mysql.cj.jdbc.Driver + jpa: + hibernate: + ddl-auto: update + properties: + hibernate: + dialect: org.hibernate.dialect.MySQL5Dialect swagger: controllerPackage: order.controller \ No newline at end of file diff --git a/ts-order-service/src/test/java/order/controller/OrderControllerTest.java b/ts-order-service/src/test/java/order/controller/OrderControllerTest.java index 79766ef2b..e4e97b1ea 100644 --- a/ts-order-service/src/test/java/order/controller/OrderControllerTest.java +++ b/ts-order-service/src/test/java/order/controller/OrderControllerTest.java @@ -1,10 +1,10 @@ package order.controller; import com.alibaba.fastjson.JSONObject; +import edu.fudan.common.entity.Seat; import edu.fudan.common.util.Response; import order.entity.Order; import order.entity.OrderInfo; -import order.entity.Seat; import order.service.OrderService; import org.junit.Assert; import org.junit.Before; diff --git a/ts-order-service/src/test/java/order/service/OrderServiceImplTest.java b/ts-order-service/src/test/java/order/service/OrderServiceImplTest.java index eb374784a..3c49d630d 100644 --- a/ts-order-service/src/test/java/order/service/OrderServiceImplTest.java +++ b/ts-order-service/src/test/java/order/service/OrderServiceImplTest.java @@ -1,5 +1,8 @@ package order.service; + +import edu.fudan.common.entity.OrderSecurity; +import edu.fudan.common.entity.Seat; import edu.fudan.common.util.Response; import order.entity.*; import order.repository.OrderRepository; @@ -47,7 +50,7 @@ public void testGetSoldTickets1() { Seat seatRequest = new Seat(); ArrayList list = new ArrayList<>(); list.add(new Order()); - Mockito.when(orderRepository.findByTravelDateAndTrainNumber(Mockito.any(Date.class), Mockito.anyString())).thenReturn(list); + Mockito.when(orderRepository.findByTravelDateAndTrainNumber(Mockito.any(String.class), Mockito.anyString())).thenReturn(list); Response result = orderServiceImpl.getSoldTickets(seatRequest, headers); Assert.assertEquals("Success", result.getMsg()); } @@ -55,24 +58,24 @@ public void testGetSoldTickets1() { @Test public void testGetSoldTickets2() { Seat seatRequest = new Seat(); - Mockito.when(orderRepository.findByTravelDateAndTrainNumber(Mockito.any(Date.class), Mockito.anyString())).thenReturn(null); + Mockito.when(orderRepository.findByTravelDateAndTrainNumber(Mockito.any(String.class), Mockito.anyString())).thenReturn(null); Response result = orderServiceImpl.getSoldTickets(seatRequest, headers); Assert.assertEquals(new Response<>(0, "Order is Null.", null), result); } @Test public void testFindOrderById1() { - UUID id = UUID.randomUUID(); - Mockito.when(orderRepository.findById(Mockito.any(UUID.class))).thenReturn(null); + String id = UUID.randomUUID().toString(); + Mockito.when(orderRepository.findById(Mockito.any(String.class))).thenReturn(null); Response result = orderServiceImpl.findOrderById(id, headers); Assert.assertEquals(new Response<>(0, "No Content by this id", null), result); } @Test public void testFindOrderById2() { - UUID id = UUID.randomUUID(); + String id = UUID.randomUUID().toString(); Order order = new Order(); - Mockito.when(orderRepository.findById(Mockito.any(UUID.class))).thenReturn(order); + Mockito.when(orderRepository.findById(Mockito.any(String.class)).get()).thenReturn(order); Response result = orderServiceImpl.findOrderById(id, headers); Assert.assertEquals(new Response<>(1, "Success", order), result); } @@ -82,7 +85,7 @@ public void testCreate1() { Order order = new Order(); ArrayList accountOrders = new ArrayList<>(); accountOrders.add(order); - Mockito.when(orderRepository.findByAccountId(Mockito.any(UUID.class))).thenReturn(accountOrders); + Mockito.when(orderRepository.findByAccountId(Mockito.any(String.class))).thenReturn(accountOrders); Response result = orderServiceImpl.create(order, headers); Assert.assertEquals(new Response<>(0, "Order already exist", null), result); } @@ -91,7 +94,7 @@ public void testCreate1() { public void testCreate2() { Order order = new Order(); ArrayList accountOrders = new ArrayList<>(); - Mockito.when(orderRepository.findByAccountId(Mockito.any(UUID.class))).thenReturn(accountOrders); + Mockito.when(orderRepository.findByAccountId(Mockito.any(String.class))).thenReturn(accountOrders); Mockito.when(orderRepository.save(Mockito.any(Order.class))).thenReturn(null); Response result = orderServiceImpl.create(order, headers); Assert.assertEquals("Success", result.getMsg()); @@ -100,7 +103,7 @@ public void testCreate2() { @Test public void testInitOrder1() { Order order = new Order(); - Mockito.when(orderRepository.findById(Mockito.any(UUID.class))).thenReturn(null); + Mockito.when(orderRepository.findById(Mockito.any(String.class))).thenReturn(null); Mockito.when(orderRepository.save(Mockito.any(Order.class))).thenReturn(null); orderServiceImpl.initOrder(order, headers); Mockito.verify(orderRepository, times(1)).save(Mockito.any(Order.class)); @@ -109,7 +112,7 @@ public void testInitOrder1() { @Test public void testInitOrder2() { Order order = new Order(); - Mockito.when(orderRepository.findById(Mockito.any(UUID.class))).thenReturn(order); + Mockito.when(orderRepository.findById(Mockito.any(String.class)).get()).thenReturn(order); Mockito.when(orderRepository.save(Mockito.any(Order.class))).thenReturn(null); orderServiceImpl.initOrder(order, headers); Mockito.verify(orderRepository, times(0)).save(Mockito.any(Order.class)); @@ -118,20 +121,20 @@ public void testInitOrder2() { @Test public void testAlterOrder1() { OrderAlterInfo oai = new OrderAlterInfo(); - Mockito.when(orderRepository.findById(Mockito.any(UUID.class))).thenReturn(null); + Mockito.when(orderRepository.findById(Mockito.any(String.class))).thenReturn(null); Response result = orderServiceImpl.alterOrder(oai, headers); Assert.assertEquals(new Response<>(0, "Old Order Does Not Exists", null), result); } @Test public void testAlterOrder2() { - OrderAlterInfo oai = new OrderAlterInfo(UUID.randomUUID(), UUID.randomUUID(), "login_token", new Order()); + OrderAlterInfo oai = new OrderAlterInfo(UUID.randomUUID().toString(), UUID.randomUUID().toString(), "login_token", new Order()); Order order = new Order(); - Mockito.when(orderRepository.findById(Mockito.any(UUID.class))).thenReturn(order); + Mockito.when(orderRepository.findById(Mockito.any(String.class)).get()).thenReturn(order); Mockito.when(orderRepository.save(Mockito.any(Order.class))).thenReturn(null); //mock create() ArrayList accountOrders = new ArrayList<>(); - Mockito.when(orderRepository.findByAccountId(Mockito.any(UUID.class))).thenReturn(accountOrders); + Mockito.when(orderRepository.findByAccountId(Mockito.any(String.class))).thenReturn(accountOrders); Response result = orderServiceImpl.alterOrder(oai, headers); Assert.assertEquals("Success", result.getMsg()); } @@ -142,7 +145,7 @@ public void testQueryOrders() { Order order = new Order(); order.setStatus(1); list.add(order); - Mockito.when(orderRepository.findByAccountId(Mockito.any(UUID.class))).thenReturn(list); + Mockito.when(orderRepository.findByAccountId(Mockito.any(String.class))).thenReturn(list); OrderInfo qi = new OrderInfo(); qi.setEnableStateQuery(true); qi.setEnableBoughtDateQuery(false); @@ -155,7 +158,7 @@ public void testQueryOrders() { @Test public void testQueryOrdersForRefresh() { ArrayList list = new ArrayList<>(); - Mockito.when(orderRepository.findByAccountId(Mockito.any(UUID.class))).thenReturn(list); + Mockito.when(orderRepository.findByAccountId(Mockito.any(String.class))).thenReturn(list); //mock queryForStationId() Response> response = new Response<>(); ResponseEntity>> re = new ResponseEntity<>(response, HttpStatus.OK); @@ -192,7 +195,7 @@ public void testQueryForStationId() { @Test public void testSaveChanges1() { Order order = new Order(); - Mockito.when(orderRepository.findById(Mockito.any(UUID.class))).thenReturn(null); + Mockito.when(orderRepository.findById(Mockito.any(String.class))).thenReturn(null); Response result = orderServiceImpl.saveChanges(order, headers); Assert.assertEquals(new Response<>(0, "Order Not Found", null), result); } @@ -200,7 +203,7 @@ public void testSaveChanges1() { @Test public void testSaveChanges2() { Order order = new Order(); - Mockito.when(orderRepository.findById(Mockito.any(UUID.class))).thenReturn(order); + Mockito.when(orderRepository.findById(Mockito.any(String.class)).get()).thenReturn(order); Mockito.when(orderRepository.save(Mockito.any(Order.class))).thenReturn(null); Response result = orderServiceImpl.saveChanges(order, headers); Assert.assertEquals(new Response<>(1, "Success", order), result); @@ -208,24 +211,24 @@ public void testSaveChanges2() { @Test public void testCancelOrder1() { - Mockito.when(orderRepository.findById(Mockito.any(UUID.class))).thenReturn(null); - Response result = orderServiceImpl.cancelOrder(UUID.randomUUID(), UUID.randomUUID(), headers); + Mockito.when(orderRepository.findById(Mockito.any(String.class))).thenReturn(null); + Response result = orderServiceImpl.cancelOrder(UUID.randomUUID().toString(), UUID.randomUUID().toString(), headers); Assert.assertEquals(new Response<>(0, "Order Not Found", null), result); } @Test public void testCancelOrder2() { Order oldOrder = new Order(); - Mockito.when(orderRepository.findById(Mockito.any(UUID.class))).thenReturn(oldOrder); + Mockito.when(orderRepository.findById(Mockito.any(String.class)).get()).thenReturn(oldOrder); Mockito.when(orderRepository.save(Mockito.any(Order.class))).thenReturn(null); - Response result = orderServiceImpl.cancelOrder(UUID.randomUUID(), UUID.randomUUID(), headers); + Response result = orderServiceImpl.cancelOrder(UUID.randomUUID().toString(), UUID.randomUUID().toString(), headers); Assert.assertEquals("Success", result.getMsg()); } @Test public void testQueryAlreadySoldOrders() { ArrayList orders = new ArrayList<>(); - Mockito.when(orderRepository.findByTravelDateAndTrainNumber(Mockito.any(Date.class), Mockito.anyString())).thenReturn(orders); + Mockito.when(orderRepository.findByTravelDateAndTrainNumber(Mockito.any(String.class), Mockito.anyString())).thenReturn(orders); Response result = orderServiceImpl.queryAlreadySoldOrders(new Date(), "G1234", headers); Assert.assertEquals("Success", result.getMsg()); } @@ -248,7 +251,7 @@ public void testGetAllOrders2() { @Test public void testModifyOrder1() { - Mockito.when(orderRepository.findById(Mockito.any(UUID.class))).thenReturn(null); + Mockito.when(orderRepository.findById(Mockito.any(String.class))).thenReturn(null); Response result = orderServiceImpl.modifyOrder(UUID.randomUUID().toString(), 1, headers); Assert.assertEquals(new Response<>(0, "Order Not Found", null), result); } @@ -256,7 +259,7 @@ public void testModifyOrder1() { @Test public void testModifyOrder2() { Order order = new Order(); - Mockito.when(orderRepository.findById(Mockito.any(UUID.class))).thenReturn(order); + Mockito.when(orderRepository.findById(Mockito.any(String.class)).get()).thenReturn(order); Mockito.when(orderRepository.save(Mockito.any(Order.class))).thenReturn(null); Response result = orderServiceImpl.modifyOrder(UUID.randomUUID().toString(), 1, headers); Assert.assertEquals("Modify Order Success", result.getMsg()); @@ -264,7 +267,7 @@ public void testModifyOrder2() { @Test public void testGetOrderPrice1() { - Mockito.when(orderRepository.findById(Mockito.any(UUID.class))).thenReturn(null); + Mockito.when(orderRepository.findById(Mockito.any(String.class))).thenReturn(null); Response result = orderServiceImpl.getOrderPrice(UUID.randomUUID().toString(), headers); Assert.assertEquals(new Response<>(0, "Order Not Found", "-1.0"), result); } @@ -272,14 +275,14 @@ public void testGetOrderPrice1() { @Test public void testGetOrderPrice2() { Order order = new Order(); - Mockito.when(orderRepository.findById(Mockito.any(UUID.class))).thenReturn(order); + Mockito.when(orderRepository.findById(Mockito.any(String.class)).get()).thenReturn(order); Response result = orderServiceImpl.getOrderPrice(UUID.randomUUID().toString(), headers); Assert.assertEquals(new Response<>(1, "Success", order.getPrice()), result); } @Test public void testPayOrder1() { - Mockito.when(orderRepository.findById(Mockito.any(UUID.class))).thenReturn(null); + Mockito.when(orderRepository.findById(Mockito.any(String.class))).thenReturn(null); Response result = orderServiceImpl.payOrder(UUID.randomUUID().toString(), headers); Assert.assertEquals(new Response<>(0, "Order Not Found", null), result); } @@ -287,7 +290,7 @@ public void testPayOrder1() { @Test public void testPayOrder2() { Order order = new Order(); - Mockito.when(orderRepository.findById(Mockito.any(UUID.class))).thenReturn(order); + Mockito.when(orderRepository.findById(Mockito.any(String.class)).get()).thenReturn(order); Mockito.when(orderRepository.save(Mockito.any(Order.class))).thenReturn(null); Response result = orderServiceImpl.payOrder(UUID.randomUUID().toString(), headers); Assert.assertEquals("Pay Order Success.", result.getMsg()); @@ -295,7 +298,7 @@ public void testPayOrder2() { @Test public void testGetOrderById1() { - Mockito.when(orderRepository.findById(Mockito.any(UUID.class))).thenReturn(null); + Mockito.when(orderRepository.findById(Mockito.any(String.class))).thenReturn(null); Response result = orderServiceImpl.getOrderById(UUID.randomUUID().toString(), headers); Assert.assertEquals(new Response<>(0, "Order Not Found", null), result); } @@ -303,7 +306,7 @@ public void testGetOrderById1() { @Test public void testGetOrderById2() { Order order = new Order(); - Mockito.when(orderRepository.findById(Mockito.any(UUID.class))).thenReturn(order); + Mockito.when(orderRepository.findById(Mockito.any(String.class)).get()).thenReturn(order); Response result = orderServiceImpl.getOrderById(UUID.randomUUID().toString(), headers); Assert.assertEquals(new Response<>(1, "Success.", order), result); } @@ -311,14 +314,14 @@ public void testGetOrderById2() { @Test public void testCheckSecurityAboutOrder() { ArrayList orders = new ArrayList<>(); - Mockito.when(orderRepository.findByAccountId(Mockito.any(UUID.class))).thenReturn(orders); + Mockito.when(orderRepository.findByAccountId(Mockito.any(String.class))).thenReturn(orders); Response result = orderServiceImpl.checkSecurityAboutOrder(new Date(), UUID.randomUUID().toString(), headers); Assert.assertEquals(new Response<>(1, "Check Security Success . ", new OrderSecurity(0, 0)), result); } @Test public void testDeleteOrder1() { - Mockito.when(orderRepository.findById(Mockito.any(UUID.class))).thenReturn(null); + Mockito.when(orderRepository.findById(Mockito.any(String.class))).thenReturn(null); Response result = orderServiceImpl.deleteOrder(UUID.randomUUID().toString(), headers); Assert.assertEquals(new Response<>(0, "Order Not Exist.", null), result); } @@ -326,9 +329,9 @@ public void testDeleteOrder1() { @Test public void testDeleteOrder2() { Order order = new Order(); - UUID orderUuid = UUID.randomUUID(); - Mockito.when(orderRepository.findById(Mockito.any(UUID.class))).thenReturn(order); - Mockito.doNothing().doThrow(new RuntimeException()).when(orderRepository).deleteById(Mockito.any(UUID.class)); + String orderUuid = UUID.randomUUID().toString(); + Mockito.when(orderRepository.findById(Mockito.any(String.class)).get()).thenReturn(order); + Mockito.doNothing().doThrow(new RuntimeException()).when(orderRepository).deleteById(Mockito.any(String.class)); Response result = orderServiceImpl.deleteOrder(orderUuid.toString(), headers); Assert.assertEquals(new Response<>(1, "Delete Order Success", order), result); } @@ -338,7 +341,7 @@ public void testAddNewOrder1() { Order order = new Order(); ArrayList accountOrders = new ArrayList<>(); accountOrders.add(order); - Mockito.when(orderRepository.findByAccountId(Mockito.any(UUID.class))).thenReturn(accountOrders); + Mockito.when(orderRepository.findByAccountId(Mockito.any(String.class))).thenReturn(accountOrders); Response result = orderServiceImpl.addNewOrder(order, headers); Assert.assertEquals(new Response<>(0, "Order already exist", null), result); } @@ -347,7 +350,7 @@ public void testAddNewOrder1() { public void testAddNewOrder2() { Order order = new Order(); ArrayList accountOrders = new ArrayList<>(); - Mockito.when(orderRepository.findByAccountId(Mockito.any(UUID.class))).thenReturn(accountOrders); + Mockito.when(orderRepository.findByAccountId(Mockito.any(String.class))).thenReturn(accountOrders); Mockito.when(orderRepository.save(Mockito.any(Order.class))).thenReturn(null); Response result = orderServiceImpl.addNewOrder(order, headers); Assert.assertEquals("Add new Order Success", result.getMsg()); @@ -356,7 +359,7 @@ public void testAddNewOrder2() { @Test public void testUpdateOrder1() { Order order = new Order(); - Mockito.when(orderRepository.findById(Mockito.any(UUID.class))).thenReturn(null); + Mockito.when(orderRepository.findById(Mockito.any(String.class))).thenReturn(null); Response result = orderServiceImpl.updateOrder(order, headers); Assert.assertEquals(new Response<>(0, "Order Not Found, Can't update", null), result); } @@ -364,7 +367,7 @@ public void testUpdateOrder1() { @Test public void testUpdateOrder2() { Order order = new Order(); - Mockito.when(orderRepository.findById(Mockito.any(UUID.class))).thenReturn(order); + Mockito.when(orderRepository.findById(Mockito.any(String.class)).get()).thenReturn(order); Mockito.when(orderRepository.save(Mockito.any(Order.class))).thenReturn(null); Response result = orderServiceImpl.updateOrder(order, headers); Assert.assertEquals("Admin Update Order Success", result.getMsg()); diff --git a/ts-payment-service/pom.xml b/ts-payment-service/pom.xml index 2a345c313..b051d42f8 100644 --- a/ts-payment-service/pom.xml +++ b/ts-payment-service/pom.xml @@ -9,13 +9,12 @@ jar ts-payment-service - org.services ts-service 0.1.0 - ../ + ../pom.xml @@ -27,16 +26,27 @@ org.springframework.boot - spring-boot-starter-data-mongodb + spring-boot-starter-data-jpa + + + mysql + mysql-connector-java + runtime + + + org.hibernate + hibernate-core org.services ts-common 0.1.0 - - - + + jakarta.validation + jakarta.validation-api + + diff --git a/ts-payment-service/src/main/java/com/trainticket/PaymentApplication.java b/ts-payment-service/src/main/java/com/trainticket/PaymentApplication.java index bdc5c86f2..cf6451bc4 100644 --- a/ts-payment-service/src/main/java/com/trainticket/PaymentApplication.java +++ b/ts-payment-service/src/main/java/com/trainticket/PaymentApplication.java @@ -2,9 +2,14 @@ import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.boot.web.client.RestTemplateBuilder; +import org.springframework.cloud.client.discovery.EnableDiscoveryClient; +import org.springframework.cloud.client.loadbalancer.LoadBalanced; +import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.EnableAspectJAutoProxy; import org.springframework.integration.annotation.IntegrationComponentScan; import org.springframework.scheduling.annotation.EnableAsync; +import org.springframework.web.client.RestTemplate; import springfox.documentation.swagger2.annotations.EnableSwagger2; /** @@ -15,9 +20,16 @@ @EnableAsync @IntegrationComponentScan @EnableSwagger2 +@EnableDiscoveryClient public class PaymentApplication { public static void main(String[] args) { SpringApplication.run(PaymentApplication.class, args); } + + @LoadBalanced + @Bean + public RestTemplate restTemplate(RestTemplateBuilder builder) { + return builder.build(); + } } diff --git a/ts-payment-service/src/main/java/com/trainticket/controller/PaymentController.java b/ts-payment-service/src/main/java/com/trainticket/controller/PaymentController.java index baf0f2207..0139c4f01 100644 --- a/ts-payment-service/src/main/java/com/trainticket/controller/PaymentController.java +++ b/ts-payment-service/src/main/java/com/trainticket/controller/PaymentController.java @@ -31,19 +31,19 @@ public String home() { @PostMapping(path = "/payment") public HttpEntity pay(@RequestBody Payment info, @RequestHeader HttpHeaders headers) { - PaymentController.LOGGER.info("Pay, PaymentId: {}", info.getId()); + PaymentController.LOGGER.info("[pay][Pay][PaymentId: {}]", info.getId()); return ok(service.pay(info, headers)); } @PostMapping(path = "/payment/money") public HttpEntity addMoney(@RequestBody Payment info, @RequestHeader HttpHeaders headers) { - PaymentController.LOGGER.info("Add money, PaymentId: {}", info.getId()); + PaymentController.LOGGER.info("[addMoney][Add money][PaymentId: {}]", info.getId()); return ok(service.addMoney(info, headers)); } @GetMapping(path = "/payment") public HttpEntity query(@RequestHeader HttpHeaders headers) { - PaymentController.LOGGER.info("Query payment"); + PaymentController.LOGGER.info("[query][Query payment]"); return ok(service.query(headers)); } } diff --git a/ts-payment-service/src/main/java/com/trainticket/entity/Money.java b/ts-payment-service/src/main/java/com/trainticket/entity/Money.java index 74a577c76..b1473e5c9 100644 --- a/ts-payment-service/src/main/java/com/trainticket/entity/Money.java +++ b/ts-payment-service/src/main/java/com/trainticket/entity/Money.java @@ -2,20 +2,31 @@ import lombok.AllArgsConstructor; import lombok.Data; -import org.springframework.data.mongodb.core.mapping.Document; +import lombok.NoArgsConstructor; +import org.hibernate.annotations.GenericGenerator; + +import javax.persistence.Column; +import javax.persistence.Entity; +import javax.persistence.GeneratedValue; +import javax.persistence.Id; +import java.util.UUID; /** * @author fdse */ @Data @AllArgsConstructor -@Document(collection="addMoney") +@NoArgsConstructor +@GenericGenerator(name = "jpa-uuid", strategy = "org.hibernate.id.UUIDGenerator") +@Entity public class Money { + @Id + @Column(length = 36) + @GeneratedValue(generator = "jpa-uuid") + private String id; + + @Column(length = 36) private String userId; private String money; //NOSONAR - public Money(){ - //Default Constructor - } - } diff --git a/ts-payment-service/src/main/java/com/trainticket/entity/Payment.java b/ts-payment-service/src/main/java/com/trainticket/entity/Payment.java index 6475d1860..3b47f76f1 100644 --- a/ts-payment-service/src/main/java/com/trainticket/entity/Payment.java +++ b/ts-payment-service/src/main/java/com/trainticket/entity/Payment.java @@ -1,9 +1,12 @@ package com.trainticket.entity; import lombok.Data; -import org.springframework.data.annotation.Id; -import org.springframework.data.mongodb.core.mapping.Document; +import org.hibernate.annotations.GenericGenerator; +import javax.persistence.Column; +import javax.persistence.Entity; +import javax.persistence.GeneratedValue; +import javax.persistence.Id; import javax.validation.Valid; import javax.validation.constraints.NotNull; import java.util.UUID; @@ -12,27 +15,32 @@ * @author fdse */ @Data -@Document(collection="payment") +@Entity +@GenericGenerator(name = "jpa-uuid", strategy = "org.hibernate.id.UUIDGenerator") public class Payment { @Id @NotNull - @Valid + @Column(length = 36) + @GeneratedValue(generator = "jpa-uuid") private String id; @NotNull @Valid + @Column(length = 36) private String orderId; @NotNull @Valid + @Column(length = 36) private String userId; @NotNull @Valid + @Column(name = "payment_price") private String price; public Payment(){ - this.id = UUID.randomUUID().toString().replace("-", "").toUpperCase(); + this.id = UUID.randomUUID().toString(); this.orderId = ""; this.userId = ""; this.price = ""; diff --git a/ts-payment-service/src/main/java/com/trainticket/init/InitData.java b/ts-payment-service/src/main/java/com/trainticket/init/InitData.java index e99d8e29a..1b0d4f446 100644 --- a/ts-payment-service/src/main/java/com/trainticket/init/InitData.java +++ b/ts-payment-service/src/main/java/com/trainticket/init/InitData.java @@ -3,10 +3,13 @@ import com.trainticket.entity.Payment; import com.trainticket.repository.PaymentRepository; import com.trainticket.service.PaymentService; +import edu.fudan.common.util.Response; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.CommandLineRunner; import org.springframework.stereotype.Component; +import java.util.List; + /** * @author fdse */ @@ -27,6 +30,35 @@ public void run(String... args) throws Exception{ payment.setPrice("10000.0"); payment.setUserId("4d2a46c7-71cb-4cf1-b5bb-b68406d9da6f"); service.initPayment(payment, null); + + /*Payment payment_1 = new Payment(); + payment_1.setId("5ad7750ba68b49c0a8c035276b060000"); + payment_1.setOrderId("5ad7750b-a68b-49c0-a8c0-32776b060000"); + payment_1.setPrice("10000.0"); + payment_1.setUserId("4d2a46c7-71cb-4cf1-b5bb-b68406d90000"); + service.initPayment(payment_1, null); //findById + + Payment payment_2 = new Payment(); + payment_2.setId("5ad7750ba68b49c0a8c035276b061111"); + payment_2.setOrderId("5ad7750b-a68b-49c0-a8c0-32776b061111"); + payment_2.setPrice("5000.0"); + payment_2.setUserId("4d2a46c7-71cb-4cf1-b5bb-b68406d91111"); + service.initPayment(payment_2, null); + + Response r1 = service.query(null); //findAll + List payments = (List) r1.getData(); + System.out.println(payments.size()); + + Payment payment_3 = new Payment(); + payment_3.setId("5ad7750ba68b49c0a8c035276b062222"); + payment_3.setOrderId("5ad7750b-a68b-49c0-a8c0-32776b062222"); + payment_3.setPrice("500.0"); + payment_3.setUserId("4d2a46c7-71cb-4cf1-b5bb-b68406d92222"); + service.pay(payment_3,null); //findByOrderID + + service.addMoney(payment_1,null); //addMoney + service.addMoney(payment_2,null); //addMoney*/ + } } diff --git a/ts-payment-service/src/main/java/com/trainticket/repository/PaymentRepository.java b/ts-payment-service/src/main/java/com/trainticket/repository/PaymentRepository.java index 7847ef56b..0e7be3f38 100644 --- a/ts-payment-service/src/main/java/com/trainticket/repository/PaymentRepository.java +++ b/ts-payment-service/src/main/java/com/trainticket/repository/PaymentRepository.java @@ -4,13 +4,14 @@ import org.springframework.data.repository.CrudRepository; import java.util.List; +import java.util.Optional; /** * @author fdse */ public interface PaymentRepository extends CrudRepository { - Payment findById(String id); + Optional findById(String id); Payment findByOrderId(String orderId); diff --git a/ts-payment-service/src/main/java/com/trainticket/service/PaymentServiceImpl.java b/ts-payment-service/src/main/java/com/trainticket/service/PaymentServiceImpl.java index 95d2fa2a9..d6bfa6e0c 100644 --- a/ts-payment-service/src/main/java/com/trainticket/service/PaymentServiceImpl.java +++ b/ts-payment-service/src/main/java/com/trainticket/service/PaymentServiceImpl.java @@ -12,6 +12,7 @@ import org.springframework.stereotype.Service; import java.util.List; +import java.util.Optional; /** * @author Administrator @@ -39,7 +40,7 @@ public Response pay(Payment info, HttpHeaders headers){ paymentRepository.save(payment); return new Response<>(1, "Pay Success", null); }else{ - PaymentServiceImpl.LOGGER.warn("Pay Failed.Order not found with order id, PaymentId: {}, OrderId: {}",info.getId(),info.getOrderId()); + PaymentServiceImpl.LOGGER.warn("[pay][Pay Failed][Order not found with order id][PaymentId: {}, OrderId: {}]",info.getId(),info.getOrderId()); return new Response<>(0, "Pay Failed, order not found with order id" +info.getOrderId(), null); } } @@ -57,21 +58,22 @@ public Response addMoney(Payment info, HttpHeaders headers){ public Response query(HttpHeaders headers){ List payments = paymentRepository.findAll(); if(payments!= null && !payments.isEmpty()){ + PaymentServiceImpl.LOGGER.info("[query][Find all payment Success][size:{}]",payments.size()); return new Response<>(1,"Query Success", payments); }else { - PaymentServiceImpl.LOGGER.warn("Find all payment warn: {}","No content"); + PaymentServiceImpl.LOGGER.warn("[query][Find all payment warn][{}]","No content"); return new Response<>(0, "No Content", null); } } @Override public void initPayment(Payment payment, HttpHeaders headers){ - Payment paymentTemp = paymentRepository.findById(payment.getId()); - if(paymentTemp == null){ - PaymentServiceImpl.LOGGER.error("Init payment error.Payment not found, PaymentId: {}",payment.getId()); + Optional paymentTemp = paymentRepository.findById(payment.getId()); + if(!paymentTemp.isPresent()){ paymentRepository.save(payment); + PaymentServiceImpl.LOGGER.error("[initPayment][Init payment error][Payment not found][PaymentId: {}]",payment.getId()); }else{ - PaymentServiceImpl.LOGGER.info("[Init Payment] Already Exists: {}", payment.getId()); + PaymentServiceImpl.LOGGER.info("[initPayment][Init Payment Already Exists][PaymentId: {}]", payment.getId()); } } } diff --git a/ts-payment-service/src/main/resources/application.yml b/ts-payment-service/src/main/resources/application.yml index aeba1617a..1af371b32 100644 --- a/ts-payment-service/src/main/resources/application.yml +++ b/ts-payment-service/src/main/resources/application.yml @@ -3,15 +3,25 @@ server: port: 19001 # HTTP (Tomcat) port spring: + cloud: + nacos: + discovery: + server-addr: ${NACOS_ADDRS:nacos-0.nacos-headless.default.svc.cluster.local,nacos-1.nacos-headless.default.svc.cluster.local,nacos-2.nacos-headless.default.svc.cluster.local} application: name: ts-payment-service - data: - mongodb: - host: ts-payment-mongo -# username: user -# password: ${MONGODB_PASSWORD} - database: ts - port: 27017 + datasource: + url: jdbc:mysql://${PAYMENT_MYSQL_HOST:ts-payment-mysql}:${PAYMENT_MYSQL_PORT:3306}/${PAYMENT_MYSQL_DATABASE:ts-payment-mysql}?useUnicode=true&characterEncoding=UTF-8&useSSL=false&serverTimezone=UTC + username: ${PAYMENT_MYSQL_USER:root} + password: ${PAYMENT_MYSQL_PASSWORD:Abcd1234#} + driver-class-name: com.mysql.cj.jdbc.Driver + + + jpa: + hibernate: + ddl-auto: update + properties: + hibernate: + dialect: org.hibernate.dialect.MySQL5Dialect swagger: controllerPackage: com.trainticket.controller \ No newline at end of file diff --git a/ts-payment-service/src/test/java/com/trainticket/service/PaymentServiceImplTest.java b/ts-payment-service/src/test/java/com/trainticket/service/PaymentServiceImplTest.java index 4e3ecf621..d5ba07765 100644 --- a/ts-payment-service/src/test/java/com/trainticket/service/PaymentServiceImplTest.java +++ b/ts-payment-service/src/test/java/com/trainticket/service/PaymentServiceImplTest.java @@ -60,7 +60,7 @@ public void testAddMoney() { Payment info = new Payment(); Mockito.when(addMoneyRepository.save(Mockito.any(Money.class))).thenReturn(null); Response result = paymentServiceImpl.addMoney(info, headers); - Assert.assertEquals(new Response<>(1,"Add Money Success", new Money("", "")), result); + Assert.assertEquals(new Response<>(1,"Add Money Success", null), result); } @Test @@ -91,7 +91,7 @@ public void testInitPayment1() { @Test public void testInitPayment2() { Payment payment = new Payment(); - Mockito.when(paymentRepository.findById(Mockito.anyString())).thenReturn(payment); + Mockito.when(paymentRepository.findById(Mockito.anyString())).thenReturn(java.util.Optional.of(payment)); Mockito.when(paymentRepository.save(Mockito.any(Payment.class))).thenReturn(null); paymentServiceImpl.initPayment(payment, headers); Mockito.verify(paymentRepository, Mockito.times(0)).save(Mockito.any(Payment.class)); diff --git a/ts-preserve-other-service/pom.xml b/ts-preserve-other-service/pom.xml index 040aa0dc0..16555d92a 100644 --- a/ts-preserve-other-service/pom.xml +++ b/ts-preserve-other-service/pom.xml @@ -15,7 +15,7 @@ org.services ts-service 0.1.0 - ../ + ../pom.xml @@ -30,10 +30,15 @@ 0.1.0 + org.springframework.boot spring-boot-starter-amqp + + jakarta.validation + jakarta.validation-api + diff --git a/ts-preserve-other-service/src/main/java/preserveOther/PreserveOtherApplication.java b/ts-preserve-other-service/src/main/java/preserveOther/PreserveOtherApplication.java index 1fe5be17e..178bdad07 100644 --- a/ts-preserve-other-service/src/main/java/preserveOther/PreserveOtherApplication.java +++ b/ts-preserve-other-service/src/main/java/preserveOther/PreserveOtherApplication.java @@ -3,6 +3,8 @@ import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.boot.web.client.RestTemplateBuilder; +import org.springframework.cloud.client.discovery.EnableDiscoveryClient; +import org.springframework.cloud.client.loadbalancer.LoadBalanced; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.EnableAspectJAutoProxy; import org.springframework.integration.annotation.IntegrationComponentScan; @@ -18,12 +20,14 @@ @EnableAsync @IntegrationComponentScan @EnableSwagger2 +@EnableDiscoveryClient public class PreserveOtherApplication { public static void main(String[] args) { SpringApplication.run(PreserveOtherApplication.class, args); } + @LoadBalanced @Bean public RestTemplate restTemplate(RestTemplateBuilder builder) { return builder.build(); diff --git a/ts-preserve-other-service/src/main/java/preserveOther/controller/PreserveOtherController.java b/ts-preserve-other-service/src/main/java/preserveOther/controller/PreserveOtherController.java index 771c15bd1..f1d830ee4 100644 --- a/ts-preserve-other-service/src/main/java/preserveOther/controller/PreserveOtherController.java +++ b/ts-preserve-other-service/src/main/java/preserveOther/controller/PreserveOtherController.java @@ -6,7 +6,7 @@ import org.springframework.http.HttpEntity; import org.springframework.http.HttpHeaders; import org.springframework.web.bind.annotation.*; -import preserveOther.entity.OrderTicketsInfo; +import edu.fudan.common.entity.OrderTicketsInfo; import preserveOther.service.PreserveOtherService; import static org.springframework.http.ResponseEntity.ok; @@ -32,7 +32,7 @@ public String home() { @PostMapping(value = "/preserveOther") public HttpEntity preserve(@RequestBody OrderTicketsInfo oti, @RequestHeader HttpHeaders headers) { - PreserveOtherController.LOGGER.info("[Preserve] Account order from {} -----> {} at {}", oti.getFrom(), oti.getTo(), oti.getDate()); + PreserveOtherController.LOGGER.info("[preserve][Preserve Account order][from {} to {} at {}]", oti.getFrom(), oti.getTo(), oti.getDate()); return ok(preserveService.preserve(oti, headers)); } diff --git a/ts-preserve-other-service/src/main/java/preserveOther/entity/Account.java b/ts-preserve-other-service/src/main/java/preserveOther/entity/Account.java deleted file mode 100644 index 037c6da21..000000000 --- a/ts-preserve-other-service/src/main/java/preserveOther/entity/Account.java +++ /dev/null @@ -1,38 +0,0 @@ -package preserveOther.entity; - -import com.fasterxml.jackson.annotation.JsonIgnoreProperties; -import lombok.Data; - -import java.util.UUID; - -/** - * @author fdse - */ -@Data -@JsonIgnoreProperties(ignoreUnknown = true) -public class Account { - - private UUID id; - - private String password; - - private int gender; - - private String name; - - private int documentType; - - private String documentNum; - - private String email; - - public Account(){ - gender = Gender.OTHER.getCode(); - password = "defaultPassword"; //NOSONAR - name = "None"; - documentType = DocumentType.NONE.getCode(); - documentNum = "0123456789"; - email = "0123456789"; - } - -} diff --git a/ts-preserve-other-service/src/main/java/preserveOther/entity/Consign.java b/ts-preserve-other-service/src/main/java/preserveOther/entity/Consign.java deleted file mode 100644 index fa4652062..000000000 --- a/ts-preserve-other-service/src/main/java/preserveOther/entity/Consign.java +++ /dev/null @@ -1,32 +0,0 @@ -package preserveOther.entity; - -import lombok.AllArgsConstructor; -import lombok.Data; -import lombok.NoArgsConstructor; - -import java.util.UUID; - -/** - * @author fdse - */ -@Data -@AllArgsConstructor -@NoArgsConstructor -public class Consign { - - private UUID id; - private UUID orderId; - private UUID accountId; - private String handleDate; - private String targetDate; - private String from; - private String to; - private String consignee; - private String phone; - private double weight; - private boolean isWithin; - - - - -} diff --git a/ts-preserve-other-service/src/main/java/preserveOther/entity/Contacts.java b/ts-preserve-other-service/src/main/java/preserveOther/entity/Contacts.java deleted file mode 100644 index cc056947c..000000000 --- a/ts-preserve-other-service/src/main/java/preserveOther/entity/Contacts.java +++ /dev/null @@ -1,57 +0,0 @@ -package preserveOther.entity; - -import com.fasterxml.jackson.annotation.JsonIgnoreProperties; -import lombok.Data; - -import java.util.UUID; - -/** - * @author fdse - */ -@Data -@JsonIgnoreProperties(ignoreUnknown = true) -public class Contacts { - - private UUID id; - - private UUID accountId; - - private String name; - - private int documentType; - - private String documentNumber; - - private String phoneNumber; - - public Contacts() { - //Default Constructor - } - - @Override - public boolean equals(Object obj) { - if (this == obj) { - return true; - } - if (obj == null) { - return false; - } - if (getClass() != obj.getClass()) { - return false; - } - Contacts other = (Contacts) obj; - return name.equals(other.getName()) - && accountId .equals( other.getAccountId() ) - && documentNumber.equals(other.getDocumentNumber()) - && phoneNumber.equals(other.getPhoneNumber()) - && documentType == other.getDocumentType(); - } - - @Override - public int hashCode() { - int result = 17; - result = 31 * result + (id == null ? 0 : id.hashCode()); - return result; - } - -} diff --git a/ts-preserve-other-service/src/main/java/preserveOther/entity/FoodOrder.java b/ts-preserve-other-service/src/main/java/preserveOther/entity/FoodOrder.java deleted file mode 100644 index 3428174d4..000000000 --- a/ts-preserve-other-service/src/main/java/preserveOther/entity/FoodOrder.java +++ /dev/null @@ -1,34 +0,0 @@ -package preserveOther.entity; - -import lombok.Data; - -import java.util.UUID; - -/** - * @author fdse - */ -@Data -public class FoodOrder { - - private UUID id; - - private UUID orderId; - - /** - * 1:train food;2:food store - */ - private int foodType; - - private String stationName; - - private String storeName; - - private String foodName; - - private double price; - - public FoodOrder(){ - //Default Constructor - } - -} diff --git a/ts-preserve-other-service/src/main/java/preserveOther/entity/Gender.java b/ts-preserve-other-service/src/main/java/preserveOther/entity/Gender.java deleted file mode 100644 index 95722ec0c..000000000 --- a/ts-preserve-other-service/src/main/java/preserveOther/entity/Gender.java +++ /dev/null @@ -1,51 +0,0 @@ -package preserveOther.entity; - -/** - * @author fdse - */ -public enum Gender { - - /** - * null - */ - NONE (0, "Null"), - /** - * male - */ - MALE (1, "Male"), - /** - * female - */ - FEMALE (2, "Female"), - /** - * other - */ - OTHER (3, "Other"); - - private int code; - private String name; - - Gender(int code, String name){ - this.code = code; - this.name = name; - } - - public int getCode(){ - return code; - } - - public String getName() { - return name; - } - - public static String getNameByCode(int code){ - Gender[] genderSet = Gender.values(); - for(Gender gender : genderSet){ - if(gender.getCode() == code){ - return gender.getName(); - } - } - return genderSet[0].getName(); - } - -} diff --git a/ts-preserve-other-service/src/main/java/preserveOther/entity/NotifyInfo.java b/ts-preserve-other-service/src/main/java/preserveOther/entity/NotifyInfo.java deleted file mode 100644 index 6adcf2099..000000000 --- a/ts-preserve-other-service/src/main/java/preserveOther/entity/NotifyInfo.java +++ /dev/null @@ -1,26 +0,0 @@ -package preserveOther.entity; - -import lombok.Data; - -/** - * @author fdse - */ -@Data -public class NotifyInfo { - - public NotifyInfo(){ - //Default Constructor - } - - private String email; - private String orderNumber; - private String username; - private String startingPlace; - private String endPlace; - private String startingTime; - private String date; - private String seatClass; - private String seatNumber; - private String price; - -} diff --git a/ts-preserve-other-service/src/main/java/preserveOther/entity/Order.java b/ts-preserve-other-service/src/main/java/preserveOther/entity/Order.java deleted file mode 100644 index 2936282a8..000000000 --- a/ts-preserve-other-service/src/main/java/preserveOther/entity/Order.java +++ /dev/null @@ -1,108 +0,0 @@ -package preserveOther.entity; - -import com.fasterxml.jackson.annotation.JsonIgnoreProperties; -import lombok.Data; - -import java.util.Date; -import java.util.UUID; - -/** - * @author fdse - */ -@Data -@JsonIgnoreProperties(ignoreUnknown = true) -public class Order { - - private UUID id; - - private Date boughtDate; - - private Date travelDate; - - private Date travelTime; - - /** - * Which Account Bought it - */ - private UUID accountId; - - /** - * Tickets bought for whom.... - */ - private String contactsName; - - private int documentType; - - private String contactsDocumentNumber; - - private String trainNumber; - - private int coachNumber; - - private int seatClass; - - private String seatNumber; - - private String from; - - private String to; - - private int status; - - private String price; - - public Order(){ - boughtDate = new Date(System.currentTimeMillis()); - travelDate = new Date(123456789); - trainNumber = "G1235"; - coachNumber = 5; - seatClass = SeatClass.FIRSTCLASS.getCode(); - seatNumber = "5A"; - from = "shanghai"; - to = "taiyuan"; - status = OrderStatus.PAID.getCode(); - price = "0.0"; - } - - @Override - public boolean equals(Object obj) { - if (this == obj) { - return true; - } - if (obj == null) { - return false; - } - if (getClass() != obj.getClass()) { - return false; - } - Order other = (Order) obj; - return boughtDate.equals(other.getBoughtDate()) - && travelDate.equals(other.getTravelDate()) - && travelTime.equals(other.getTravelTime()) - && accountId .equals( other.getAccountId() ) - && contactsName.equals(other.getContactsName()) - && contactsDocumentNumber.equals(other.getContactsDocumentNumber()) - && documentType == other.getDocumentType() - && trainNumber.equals(other.getTrainNumber()) - && coachNumber == other.getCoachNumber() - && seatClass == other.getSeatClass() - && seatNumber .equals(other.getSeatNumber()) - && from.equals(other.getFrom()) - && to.equals(other.getTo()) - && status == other.getStatus() - && price == other.price; - } - - @Override - public int hashCode() { - int result = 17; - result = 31 * result + (id == null ? 0 : id.hashCode()); - return result; - } - - public void setTravelDate(int year,int month,int day){ - Date date = new Date(year,month,day,0,0,0); //NOSONAR - this.travelDate = date; - } - -} diff --git a/ts-preserve-other-service/src/main/java/preserveOther/entity/OrderStatus.java b/ts-preserve-other-service/src/main/java/preserveOther/entity/OrderStatus.java deleted file mode 100644 index c5a004b3c..000000000 --- a/ts-preserve-other-service/src/main/java/preserveOther/entity/OrderStatus.java +++ /dev/null @@ -1,63 +0,0 @@ -package preserveOther.entity; - -/** - * @author fdse - */ -public enum OrderStatus { - - /** - * not paid - */ - NOTPAID (0,"Not Paid"), - /** - * paid and not collected - */ - PAID (1,"Paid & Not Collected"), - /** - * collected - */ - COLLECTED (2,"Collected"), - /** - * cancel and rebook - */ - CHANGE (3,"Cancel & Rebook"), - /** - * cancel - */ - CANCEL (4,"Cancel"), - /** - * refunded - */ - REFUNDS (5,"Refunded"), - /** - * used - */ - USED (6,"Used"); - - private int code; - private String name; - - OrderStatus(int code, String name){ - this.code = code; - this.name = name; - } - - public int getCode(){ - return code; - } - - public String getName() { - return name; - } - - public static String getNameByCode(int code){ - OrderStatus[] orderStatusSet = OrderStatus.values(); - for(OrderStatus orderStatus : orderStatusSet){ - if(orderStatus.getCode() == code){ - return orderStatus.getName(); - } - } - return orderStatusSet[0].getName(); - } - -} diff --git a/ts-preserve-other-service/src/main/java/preserveOther/entity/Seat.java b/ts-preserve-other-service/src/main/java/preserveOther/entity/Seat.java deleted file mode 100644 index d97b08449..000000000 --- a/ts-preserve-other-service/src/main/java/preserveOther/entity/Seat.java +++ /dev/null @@ -1,29 +0,0 @@ -package preserveOther.entity; - -import lombok.AllArgsConstructor; -import lombok.Data; - -import java.util.Date; - -/** - * @author fdse - */ -@Data -@AllArgsConstructor -public class Seat { - - private Date travelDate; - - private String trainNumber; - - private String startStation; - - private String destStation; - - private int seatType; - - public Seat(){ - //Default Constructor - } - -} diff --git a/ts-preserve-other-service/src/main/java/preserveOther/entity/SeatClass.java b/ts-preserve-other-service/src/main/java/preserveOther/entity/SeatClass.java deleted file mode 100644 index 9ccf665b5..000000000 --- a/ts-preserve-other-service/src/main/java/preserveOther/entity/SeatClass.java +++ /dev/null @@ -1,70 +0,0 @@ -package preserveOther.entity; - -/** - * @author fdse - */ -public enum SeatClass { - - /** - * no seat - */ - NONE (0,"NoSeat"), - /** - * green seat - */ - BUSINESS (1,"GreenSeat"), - /** - * first class seat - */ - FIRSTCLASS (2,"FirstClassSeat"), - /** - * second class seat - */ - SECONDCLASS (3,"SecondClassSeat"), - /** - * hard seat - */ - HARDSEAT (4,"HardSeat"), - /** - * soft seat - */ - SOFTSEAT (5,"SoftSeat"), - /** - * hard bed - */ - HARDBED (6,"HardBed"), - /** - * soft bed - */ - SOFTBED (7,"SoftBed"), - /** - * high soft seat - */ - HIGHSOFTBED (8,"HighSoftSeat"); - - private int code; - private String name; - - SeatClass(int code, String name){ - this.code = code; - this.name = name; - } - - public int getCode(){ - return code; - } - - public String getName() { - return name; - } - - public static String getNameByCode(int code){ - SeatClass[] seatClassSet = SeatClass.values(); - for(SeatClass seatClass : seatClassSet){ - if(seatClass.getCode() == code){ - return seatClass.getName(); - } - } - return seatClassSet[0].getName(); - } -} diff --git a/ts-preserve-other-service/src/main/java/preserveOther/entity/Ticket.java b/ts-preserve-other-service/src/main/java/preserveOther/entity/Ticket.java deleted file mode 100644 index 296d46856..000000000 --- a/ts-preserve-other-service/src/main/java/preserveOther/entity/Ticket.java +++ /dev/null @@ -1,21 +0,0 @@ -package preserveOther.entity; - -import lombok.Data; - -/** - * @author fdse - */ -@Data -public class Ticket { - - private int seatNo; - - private String startStation; - - private String destStation; - - public Ticket(){ - //Default Constructor. - } - -} diff --git a/ts-preserve-other-service/src/main/java/preserveOther/entity/TrainType.java b/ts-preserve-other-service/src/main/java/preserveOther/entity/TrainType.java deleted file mode 100644 index 0c5cecf20..000000000 --- a/ts-preserve-other-service/src/main/java/preserveOther/entity/TrainType.java +++ /dev/null @@ -1,31 +0,0 @@ -package preserveOther.entity; - -import lombok.Data; - -import javax.validation.Valid; - -/** - * @author fdse - */ -@Data -public class TrainType { - @Valid - private String id; - - @Valid - private int economyClass; - - @Valid - private int confortClass; - - public TrainType(){ - //Default Constructor - } - - public TrainType(String id, int economyClass, int confortClass) { - this.id = id; - this.economyClass = economyClass; - this.confortClass = confortClass; - } - -} diff --git a/ts-preserve-other-service/src/main/java/preserveOther/entity/Trip.java b/ts-preserve-other-service/src/main/java/preserveOther/entity/Trip.java deleted file mode 100644 index ad8abc519..000000000 --- a/ts-preserve-other-service/src/main/java/preserveOther/entity/Trip.java +++ /dev/null @@ -1,72 +0,0 @@ -package preserveOther.entity; - -import lombok.Data; - -import javax.validation.Valid; -import javax.validation.constraints.NotNull; -import java.util.Date; - -/** - * @author fdse - */ -@Data -public class Trip { - @Valid - private TripId tripId; - - @Valid - @NotNull - private String trainTypeId; - - private String routeId; - - - @Valid - @NotNull - private String startingStationId; - - @Valid - private String stationsId; - - @Valid - @NotNull - private String terminalStationId; - - @Valid - @NotNull - private Date startingTime; - - @Valid - @NotNull - private Date endTime; - - public Trip(TripId tripId, String trainTypeId, String startingStationId, String stationsId, String terminalStationId, Date startingTime, Date endTime) { - this.tripId = tripId; - this.trainTypeId = trainTypeId; - this.startingStationId = startingStationId; - this.stationsId = stationsId; - this.terminalStationId = terminalStationId; - this.startingTime = startingTime; - this.endTime = endTime; - } - - public Trip(TripId tripId, String trainTypeId, String routeId) { - this.tripId = tripId; - this.trainTypeId = trainTypeId; - this.routeId = routeId; - this.startingStationId = ""; - this.terminalStationId = ""; - this.startingTime = new Date(); - this.endTime = new Date(); - } - - public Trip(){ - //Default Constructor - this.trainTypeId = ""; - this.startingStationId = ""; - this.terminalStationId = ""; - this.startingTime = new Date(); - this.endTime = new Date(); - } - -} diff --git a/ts-preserve-other-service/src/main/java/preserveOther/entity/TripAllDetail.java b/ts-preserve-other-service/src/main/java/preserveOther/entity/TripAllDetail.java deleted file mode 100644 index 535283adf..000000000 --- a/ts-preserve-other-service/src/main/java/preserveOther/entity/TripAllDetail.java +++ /dev/null @@ -1,27 +0,0 @@ -package preserveOther.entity; - -import lombok.AllArgsConstructor; -import lombok.Data; -import lombok.ToString; - -/** - * @author fdse - */ -@Data -@AllArgsConstructor -@ToString -public class TripAllDetail { - - private boolean status; - - private String message; - - private TripResponse tripResponse; - - private Trip trip; - - public TripAllDetail() { - //Default Constructor - } - -} diff --git a/ts-preserve-other-service/src/main/java/preserveOther/entity/TripAllDetailInfo.java b/ts-preserve-other-service/src/main/java/preserveOther/entity/TripAllDetailInfo.java deleted file mode 100644 index 809a87149..000000000 --- a/ts-preserve-other-service/src/main/java/preserveOther/entity/TripAllDetailInfo.java +++ /dev/null @@ -1,25 +0,0 @@ -package preserveOther.entity; - -import lombok.Data; - -import java.util.Date; - -/** - * @author fdse - */ -@Data -public class TripAllDetailInfo { - - private String tripId; - - private Date travelDate; - - private String from; - - private String to; - - public TripAllDetailInfo() { - //Default Constructor - } - -} diff --git a/ts-preserve-other-service/src/main/java/preserveOther/entity/TripId.java b/ts-preserve-other-service/src/main/java/preserveOther/entity/TripId.java deleted file mode 100644 index 4065885a3..000000000 --- a/ts-preserve-other-service/src/main/java/preserveOther/entity/TripId.java +++ /dev/null @@ -1,41 +0,0 @@ -package preserveOther.entity; - -import lombok.Data; - -import java.io.Serializable; - -/** - * @author fdse - */ -@Data -public class TripId implements Serializable{ - private Type type; - private String number; - - - public TripId(){} - - public TripId(String trainNumber){ - char type0 = trainNumber.charAt(0); - switch(type0){ - case 'G': this.type = Type.G; - break; - case 'D': this.type = Type.D; - break; - case 'Z': this.type = Type.Z; - break; - case 'T': this.type = Type.T; - break; - case 'K': this.type = Type.K; - break; - default:break; - } - - this.number = trainNumber.substring(1); - } - - @Override - public String toString(){ - return type.getName() + number; - } -} diff --git a/ts-preserve-other-service/src/main/java/preserveOther/entity/TripResponse.java b/ts-preserve-other-service/src/main/java/preserveOther/entity/TripResponse.java deleted file mode 100644 index cf0062e1e..000000000 --- a/ts-preserve-other-service/src/main/java/preserveOther/entity/TripResponse.java +++ /dev/null @@ -1,49 +0,0 @@ -package preserveOther.entity; - -import lombok.Data; -import lombok.ToString; - -import javax.validation.Valid; -import javax.validation.constraints.NotNull; -import java.util.Date; - -/** - * @author fdse - */ -@Data -@ToString -public class TripResponse { - @Valid - private TripId tripId; - - @Valid - @NotNull - private String startingStation; - - @Valid - @NotNull - private String terminalStation; - - @Valid - @NotNull - private Date startingTime; - - @Valid - @NotNull - private Date endTime; - - /** - * The number of economy seat - */ - @Valid - @NotNull - private int economyClass; - - /** - * The number of confort seat - */ - @Valid - @NotNull - private int confortClass; - -} diff --git a/ts-preserve-other-service/src/main/java/preserveOther/entity/Type.java b/ts-preserve-other-service/src/main/java/preserveOther/entity/Type.java deleted file mode 100644 index 19c9aa2a4..000000000 --- a/ts-preserve-other-service/src/main/java/preserveOther/entity/Type.java +++ /dev/null @@ -1,63 +0,0 @@ -package preserveOther.entity; - -import java.io.Serializable; - -/** - * @author fdse - */ -public enum Type implements Serializable{ - - /** - * G - */ - G("G", 1), - /** - * D - */ - D("D", 2), - /** - * Z - */ - Z("Z",3), - /** - * T - */ - T("T", 4), - /** - * E - */ - K("K", 5); - - private String name; - private int index; - - Type(String name, int index) { - this.name = name; - this.index = index; - } - - public static String getName(int index) { - for (Type type : Type.values()) { - if (type.getIndex() == index) { - return type.name; - } - } - return null; - } - - public String getName() { - return name; - } - - void setName(String name) { - this.name = name; - } - - public int getIndex() { - return index; - } - - void setIndex(int index) { - this.index = index; - } -} diff --git a/ts-preserve-other-service/src/main/java/preserveOther/entity/User.java b/ts-preserve-other-service/src/main/java/preserveOther/entity/User.java deleted file mode 100644 index e6f57c85e..000000000 --- a/ts-preserve-other-service/src/main/java/preserveOther/entity/User.java +++ /dev/null @@ -1,31 +0,0 @@ -package preserveOther.entity; - -import lombok.AllArgsConstructor; -import lombok.Builder; -import lombok.Data; -import lombok.NoArgsConstructor; - -import java.util.UUID; - -/** - * @author fdse - */ -@Data -@Builder -@AllArgsConstructor -@NoArgsConstructor -public class User { - - private UUID userId; - private String userName; - private String password; - - private int gender; - - private int documentType; - - private String documentNum; - - private String email; - -} diff --git a/ts-preserve-other-service/src/main/java/preserveOther/service/PreserveOtherService.java b/ts-preserve-other-service/src/main/java/preserveOther/service/PreserveOtherService.java index 1a7242237..27fb6d7c4 100644 --- a/ts-preserve-other-service/src/main/java/preserveOther/service/PreserveOtherService.java +++ b/ts-preserve-other-service/src/main/java/preserveOther/service/PreserveOtherService.java @@ -1,8 +1,9 @@ package preserveOther.service; +import edu.fudan.common.entity.OrderTicketsInfo; import edu.fudan.common.util.Response; import org.springframework.http.HttpHeaders; -import preserveOther.entity.OrderTicketsInfo; + /** * @author fdse diff --git a/ts-preserve-other-service/src/main/java/preserveOther/service/PreserveOtherServiceImpl.java b/ts-preserve-other-service/src/main/java/preserveOther/service/PreserveOtherServiceImpl.java index 82490dd63..f8b3687de 100644 --- a/ts-preserve-other-service/src/main/java/preserveOther/service/PreserveOtherServiceImpl.java +++ b/ts-preserve-other-service/src/main/java/preserveOther/service/PreserveOtherServiceImpl.java @@ -1,10 +1,13 @@ package preserveOther.service; +import edu.fudan.common.entity.*; import edu.fudan.common.util.JsonUtils; import edu.fudan.common.util.Response; +import edu.fudan.common.util.StringUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.cloud.client.discovery.DiscoveryClient; import org.springframework.core.ParameterizedTypeReference; import org.springframework.http.HttpEntity; import org.springframework.http.HttpHeaders; @@ -12,10 +15,10 @@ import org.springframework.http.ResponseEntity; import org.springframework.stereotype.Service; import org.springframework.web.client.RestTemplate; -import preserveOther.entity.*; import preserveOther.mq.RabbitSend; import java.util.Date; +import java.util.List; import java.util.UUID; /** @@ -30,36 +33,41 @@ public class PreserveOtherServiceImpl implements PreserveOtherService { @Autowired private RabbitSend sendService; + @Autowired + private DiscoveryClient discoveryClient; + private static final Logger LOGGER = LoggerFactory.getLogger(PreserveOtherServiceImpl.class); + private String getServiceUrl(String serviceName) { + return "http://" + serviceName; + } + @Override public Response preserve(OrderTicketsInfo oti, HttpHeaders httpHeaders) { - PreserveOtherServiceImpl.LOGGER.info("[Verify Login] Success"); + PreserveOtherServiceImpl.LOGGER.info("[preserve][Verify Login] Success"); //1.detect ticket scalper - PreserveOtherServiceImpl.LOGGER.info("[Step 1] Check Security"); + //PreserveOtherServiceImpl.LOGGER.info("[preserve][Step 1][Check Security]"); Response result = checkSecurity(oti.getAccountId(), httpHeaders); if (result.getStatus() == 0) { - PreserveOtherServiceImpl.LOGGER.error("[Step 1] Check Security Fail, AccountId: {}",oti.getAccountId()); + PreserveOtherServiceImpl.LOGGER.error("[preserve][Step 1][Check Security Fail][AccountId: {}]",oti.getAccountId()); return new Response<>(0, result.getMsg(), null); } - PreserveOtherServiceImpl.LOGGER.info("[Step 1] Check Security Complete. "); + PreserveOtherServiceImpl.LOGGER.info("[preserve][Step 1][Check Security Complete][AccountId: {}]",oti.getAccountId()); //2.Querying contact information -- modification, mediated by the underlying information micro service - PreserveOtherServiceImpl.LOGGER.info("[Step 2] Find contacts"); - - PreserveOtherServiceImpl.LOGGER.info("[Step 2] Contacts Id: {}", oti.getContactsId()); + //PreserveOtherServiceImpl.LOGGER.info("[preserve][Step 2][Find contacts][Contacts Id: {}]", oti.getContactsId()); Response gcr = getContactsById(oti.getContactsId(), httpHeaders); if (gcr.getStatus() == 0) { - PreserveOtherServiceImpl.LOGGER.error("[Get Contacts] Fail,ContactsId: {},message: {}",oti.getContactsId(),gcr.getMsg()); + PreserveOtherServiceImpl.LOGGER.error("[preserve][Step 2][Find Contacts Fail][ContactsId: {},message: {}]",oti.getContactsId(),gcr.getMsg()); return new Response<>(0, gcr.getMsg(), null); } - PreserveOtherServiceImpl.LOGGER.info("[Step 2] Complete"); + PreserveOtherServiceImpl.LOGGER.info("[preserve][Step 2][Find contacts Complete][ContactsId: {}]",oti.getContactsId()); //3.Check the info of train and the number of remaining tickets - PreserveOtherServiceImpl.LOGGER.info("[Step 3] Check tickets num"); + //PreserveOtherServiceImpl.LOGGER.info("[Step 3] Check tickets num"); TripAllDetailInfo gtdi = new TripAllDetailInfo(); gtdi.setFrom(oti.getFrom()); @@ -67,45 +75,45 @@ public Response preserve(OrderTicketsInfo oti, HttpHeaders httpHeaders) { gtdi.setTravelDate(oti.getDate()); gtdi.setTripId(oti.getTripId()); - PreserveOtherServiceImpl.LOGGER.info("[Step 3] TripId: {}", oti.getTripId()); + PreserveOtherServiceImpl.LOGGER.info("[preserve][Step 3][Check tickets num][TripId: {}]", oti.getTripId()); Response response = getTripAllDetailInformation(gtdi, httpHeaders); TripAllDetail gtdr = response.getData(); - LOGGER.info("TripAllDetail : " + gtdr.toString()); + //LOGGER.info("TripAllDetail : " + gtdr.toString()); if (response.getStatus() == 0) { - PreserveOtherServiceImpl.LOGGER.error("[Search For Trip Detail Information] error, TripId: {}, message: {}", gtdi.getTripId(), response.getMsg()); + PreserveOtherServiceImpl.LOGGER.error("[preserve][Step 3][Check tickets num][Search For Trip Detail Information error][TripId: {}, message: {}]", gtdi.getTripId(), response.getMsg()); return new Response<>(0, response.getMsg(), null); } else { TripResponse tripResponse = gtdr.getTripResponse(); - LOGGER.info("TripResponse : " + tripResponse.toString()); + //LOGGER.info("TripResponse : " + tripResponse.toString()); if (oti.getSeatType() == SeatClass.FIRSTCLASS.getCode()) { if (tripResponse.getConfortClass() == 0) { - PreserveOtherServiceImpl.LOGGER.warn("[Check seat is enough], TripId: {}",oti.getTripId()); + PreserveOtherServiceImpl.LOGGER.warn("[preserve][Step 3][Check seat][Check seat is enough][TripId: {}]",oti.getTripId()); return new Response<>(0, "Seat Not Enough", null); } } else { if (tripResponse.getEconomyClass() == SeatClass.SECONDCLASS.getCode() && tripResponse.getConfortClass() == 0) { - PreserveOtherServiceImpl.LOGGER.warn("[Check seat is Not enough], TripId: {}",oti.getTripId()); + PreserveOtherServiceImpl.LOGGER.warn("[preserve][Step 3][Check seat][Check seat is Not enough][TripId: {}]",oti.getTripId()); return new Response<>(0, "Check Seat Not Enough", null); } } } Trip trip = gtdr.getTrip(); - PreserveOtherServiceImpl.LOGGER.info("[Step 3] Tickets Enough"); + PreserveOtherServiceImpl.LOGGER.info("[preserve][Step 3][Check tickets num][Tickets Enough]"); //4.send the order request and set the order information - PreserveOtherServiceImpl.LOGGER.info("[Step 4] Do Order"); + //PreserveOtherServiceImpl.LOGGER.info("[preserve][Step 4][Do Order]"); Contacts contacts = gcr.getData(); Order order = new Order(); - UUID orderId = UUID.randomUUID(); + String orderId = UUID.randomUUID().toString(); order.setId(orderId); order.setTrainNumber(oti.getTripId()); - order.setAccountId(UUID.fromString(oti.getAccountId())); + order.setAccountId(oti.getAccountId()); - String fromStationId = queryForStationId(oti.getFrom(), httpHeaders); - String toStationId = queryForStationId(oti.getTo(), httpHeaders); + String fromStationName = oti.getFrom(); + String toStationName = oti.getTo(); - order.setFrom(fromStationId); - order.setTo(toStationId); - order.setBoughtDate(new Date()); + order.setFrom(fromStationName); + order.setTo(toStationName); + order.setBoughtDate(StringUtils.Date2String(new Date())); order.setStatus(OrderStatus.NOTPAID.getCode()); order.setContactsDocumentNumber(contacts.getDocumentNumber()); order.setContactsName(contacts.getName()); @@ -114,64 +122,72 @@ public Response preserve(OrderTicketsInfo oti, HttpHeaders httpHeaders) { Travel query = new Travel(); query.setTrip(trip); - query.setStartingPlace(oti.getFrom()); + query.setStartPlace(oti.getFrom()); query.setEndPlace(oti.getTo()); - query.setDepartureTime(new Date()); + query.setDepartureTime(StringUtils.Date2String(new Date())); HttpEntity requestEntity = new HttpEntity(query, httpHeaders); + String basic_service_url = getServiceUrl("ts-basic-service"); ResponseEntity> re = restTemplate.exchange( - "http://ts-ticketinfo-service:15681/api/v1/ticketinfoservice/ticketinfo", + basic_service_url + "/api/v1/basicservice/basic/travel", HttpMethod.POST, requestEntity, new ParameterizedTypeReference>() { }); + if(re.getBody().getStatus() == 0){ + PreserveOtherServiceImpl.LOGGER.info("[Preserve 3][Get basic travel response status is 0][response is: {}]", re.getBody()); + return new Response<>(0, re.getBody().getMsg(), null); + } TravelResult resultForTravel = re.getBody().getData(); order.setSeatClass(oti.getSeatType()); - PreserveOtherServiceImpl.LOGGER.info("[Order] Order Travel Date: {}", oti.getDate().toString()); + PreserveOtherServiceImpl.LOGGER.info("[preserve][Step 4][Do Order][Travel Date][Date is: {}]", oti.getDate().toString()); order.setTravelDate(oti.getDate()); - order.setTravelTime(gtdr.getTripResponse().getStartingTime()); + order.setTravelTime(gtdr.getTripResponse().getStartTime()); //Dispatch the seat + List stationList = resultForTravel.getRoute().getStations(); if (oti.getSeatType() == SeatClass.FIRSTCLASS.getCode()) { + int firstClassTotalNum = resultForTravel.getTrainType().getConfortClass(); Ticket ticket = dipatchSeat(oti.getDate(), - order.getTrainNumber(), fromStationId, toStationId, - SeatClass.FIRSTCLASS.getCode(), httpHeaders); + order.getTrainNumber(), fromStationName, toStationName, + SeatClass.FIRSTCLASS.getCode(), firstClassTotalNum, stationList, httpHeaders); order.setSeatClass(SeatClass.FIRSTCLASS.getCode()); order.setSeatNumber("" + ticket.getSeatNo()); order.setPrice(resultForTravel.getPrices().get("confortClass")); } else { + int secondClassTotalNum = resultForTravel.getTrainType().getEconomyClass(); Ticket ticket = dipatchSeat(oti.getDate(), - order.getTrainNumber(), fromStationId, toStationId, - SeatClass.SECONDCLASS.getCode(), httpHeaders); + order.getTrainNumber(), fromStationName, toStationName, + SeatClass.SECONDCLASS.getCode(), secondClassTotalNum, stationList, httpHeaders); order.setSeatClass(SeatClass.SECONDCLASS.getCode()); order.setSeatNumber("" + ticket.getSeatNo()); order.setPrice(resultForTravel.getPrices().get("economyClass")); } - PreserveOtherServiceImpl.LOGGER.info("[Order Price] Price is: {}", order.getPrice()); + PreserveOtherServiceImpl.LOGGER.info("[preserve][Step 4][Do Order][Order Price][Price is: {}]", order.getPrice()); Response cor = createOrder(order, httpHeaders); if (cor.getStatus() == 0) { - PreserveOtherServiceImpl.LOGGER.error("[Create Order Fail] Create Order Fail. OrderId: {}, Reason: {}", order.getId(), cor.getMsg()); + PreserveOtherServiceImpl.LOGGER.error("[preserve][Step 4][Do Order][Create Order Fail][OrderId: {}, Reason: {}]", order.getId(), cor.getMsg()); return new Response<>(0, cor.getMsg(), null); } - PreserveOtherServiceImpl.LOGGER.info("[Step 4] Do Order Complete"); + PreserveOtherServiceImpl.LOGGER.info("[preserve][Step 4][Do Order][Do Order Complete]"); Response returnResponse = new Response<>(1, "Success.", cor.getMsg()); //5.Check insurance options if (oti.getAssurance() == 0) { - PreserveOtherServiceImpl.LOGGER.info("[Step 5] Do not need to buy assurance"); + PreserveOtherServiceImpl.LOGGER.info("[preserve][Step 5][Buy Assurance][Do not need to buy assurance]"); } else { Response addAssuranceResult = addAssuranceForOrder( oti.getAssurance(), cor.getData().getId().toString(), httpHeaders); if (addAssuranceResult.getStatus() == 1) { - PreserveOtherServiceImpl.LOGGER.info("[Step 5] Preserve Buy Assurance Success"); + PreserveOtherServiceImpl.LOGGER.info("[preserve][Step 5][Buy Assurance][Preserve Buy Assurance Success]"); } else { - PreserveOtherServiceImpl.LOGGER.warn("[Step 5] Buy Assurance Fail, assurance: {}, OrderId: {}", oti.getAssurance(),cor.getData().getId()); + PreserveOtherServiceImpl.LOGGER.warn("[preserve][Step 5][Buy Assurance][Buy Assurance Fail][assurance: {}, OrderId: {}]", oti.getAssurance(),cor.getData().getId()); returnResponse.setMsg("Success.But Buy Assurance Fail."); } } @@ -189,13 +205,13 @@ public Response preserve(OrderTicketsInfo oti, HttpHeaders httpHeaders) { } Response afor = createFoodOrder(foodOrder, httpHeaders); if (afor.getStatus() == 1) { - PreserveOtherServiceImpl.LOGGER.info("[Step 6] Buy Food Success"); + PreserveOtherServiceImpl.LOGGER.info("[preserve][Step 6][Buy Food][Buy Food Success]"); } else { - PreserveOtherServiceImpl.LOGGER.error("[Step 6] Buy Food Fail, OrderId: {}",cor.getData().getId()); + PreserveOtherServiceImpl.LOGGER.error("[preserve][Step 6][Buy Food][Buy Food Fail][OrderId: {}]",cor.getData().getId()); returnResponse.setMsg("Success.But Buy Food Fail."); } } else { - PreserveOtherServiceImpl.LOGGER.info("[Step 6] Do not need to buy food"); + PreserveOtherServiceImpl.LOGGER.info("[preserve][Step 6][Buy Food][Do not need to buy food]"); } //7.add consign @@ -211,16 +227,16 @@ public Response preserve(OrderTicketsInfo oti, HttpHeaders httpHeaders) { consignRequest.setPhone(oti.getConsigneePhone()); consignRequest.setWeight(oti.getConsigneeWeight()); consignRequest.setWithin(oti.isWithin()); - LOGGER.info("CONSIGN INFO : " + consignRequest.toString()); + //LOGGER.info("CONSIGN INFO : " + consignRequest.toString()); Response icresult = createConsign(consignRequest, httpHeaders); if (icresult.getStatus() == 1) { - PreserveOtherServiceImpl.LOGGER.info("[Step 7] Consign Success"); + PreserveOtherServiceImpl.LOGGER.info("[preserve][Step 7][Add Consign][Consign Success]"); } else { - PreserveOtherServiceImpl.LOGGER.error("[Step 7] Preserve Consign Fail, OrderId: {}", cor.getData().getId()); + PreserveOtherServiceImpl.LOGGER.error("[preserve][Step 7][Add Consign][Preserve Consign Fail][OrderId: {}]", cor.getData().getId()); returnResponse.setMsg("Consign Fail."); } } else { - PreserveOtherServiceImpl.LOGGER.info("[Step 7] Do not need to consign"); + PreserveOtherServiceImpl.LOGGER.info("[preserve][Step 7][Add Consign][Do not need to consign]"); } //8.send notification @@ -231,14 +247,14 @@ public Response preserve(OrderTicketsInfo oti, HttpHeaders httpHeaders) { notifyInfo.setDate(new Date().toString()); notifyInfo.setEmail(getUser.getEmail()); - notifyInfo.setStartingPlace(order.getFrom()); + notifyInfo.setStartPlace(order.getFrom()); notifyInfo.setEndPlace(order.getTo()); notifyInfo.setUsername(getUser.getUserName()); notifyInfo.setSeatNumber(order.getSeatNumber()); notifyInfo.setOrderNumber(order.getId().toString()); notifyInfo.setPrice(order.getPrice()); notifyInfo.setSeatClass(SeatClass.getNameByCode(order.getSeatClass())); - notifyInfo.setStartingTime(order.getTravelTime().toString()); + notifyInfo.setStartTime(order.getTravelTime().toString()); // TODO: change to async message serivce // sendEmail(notifyInfo, httpHeaders); @@ -246,17 +262,20 @@ public Response preserve(OrderTicketsInfo oti, HttpHeaders httpHeaders) { return returnResponse; } - public Ticket dipatchSeat(Date date, String tripId, String startStationId, String endStataionId, int seatType, HttpHeaders httpHeaders) { + public Ticket dipatchSeat(String date, String tripId, String startStationId, String endStataionId, int seatType, int totalNum, List stationList, HttpHeaders httpHeaders) { Seat seatRequest = new Seat(); seatRequest.setTravelDate(date); seatRequest.setTrainNumber(tripId); seatRequest.setStartStation(startStationId); seatRequest.setSeatType(seatType); seatRequest.setDestStation(endStataionId); + seatRequest.setTotalNum(totalNum); + seatRequest.setStations(stationList); HttpEntity requestEntityTicket = new HttpEntity(seatRequest, httpHeaders); + String seat_service_url = getServiceUrl("ts-seat-service"); ResponseEntity> reTicket = restTemplate.exchange( - "http://ts-seat-service:18898/api/v1/seatservice/seats", + seat_service_url + "/api/v1/seatservice/seats", HttpMethod.POST, requestEntityTicket, new ParameterizedTypeReference>() { @@ -266,13 +285,12 @@ public Ticket dipatchSeat(Date date, String tripId, String startStationId, Strin } public boolean sendEmail(NotifyInfo notifyInfo, HttpHeaders httpHeaders) { - PreserveOtherServiceImpl.LOGGER.info("[Preserve Other Service][Send Email] send email to mq"); - try { String infoJson = JsonUtils.object2Json(notifyInfo); sendService.send(infoJson); + PreserveOtherServiceImpl.LOGGER.info("[sendEmail][Send email to mq success]"); } catch (Exception e) { - PreserveOtherServiceImpl.LOGGER.error("[Preserve Other Service] send email to mq error, exception is:" + e); + PreserveOtherServiceImpl.LOGGER.error("[sendEmail][Send email to mq error] exception is:" + e); return false; } @@ -280,11 +298,12 @@ public boolean sendEmail(NotifyInfo notifyInfo, HttpHeaders httpHeaders) { } public User getAccount(String accountId, HttpHeaders httpHeaders) { - PreserveOtherServiceImpl.LOGGER.info("[Cancel Order Service][Get Order By Id]"); + PreserveOtherServiceImpl.LOGGER.info("[getAccount][Cancel Order Service][Get Order By Id]"); HttpEntity requestEntitySendEmail = new HttpEntity(httpHeaders); + String user_service_url = getServiceUrl("ts-user-service"); ResponseEntity> getAccount = restTemplate.exchange( - "http://ts-user-service:12342/api/v1/userservice/users/id/" + accountId, + user_service_url + "/api/v1/userservice/users/id/" + accountId, HttpMethod.GET, requestEntitySendEmail, new ParameterizedTypeReference>() { @@ -296,10 +315,11 @@ public User getAccount(String accountId, HttpHeaders httpHeaders) { } private Response addAssuranceForOrder(int assuranceType, String orderId, HttpHeaders httpHeaders) { - PreserveOtherServiceImpl.LOGGER.info("[Preserve Service][Add Assurance Type For Order]"); + PreserveOtherServiceImpl.LOGGER.info("[addAssuranceForOrder][Preserve Service][Add Assurance Type For Order]"); HttpEntity requestAddAssuranceResult = new HttpEntity(httpHeaders); + String assurance_service_url = getServiceUrl("ts-assurance-service"); ResponseEntity> reAddAssuranceResult = restTemplate.exchange( - "http://ts-assurance-service:18888/api/v1/assuranceservice/assurances/" + assuranceType + "/" + orderId, + assurance_service_url + "/api/v1/assuranceservice/assurances/" + assuranceType + "/" + orderId, HttpMethod.GET, requestAddAssuranceResult, new ParameterizedTypeReference>() { @@ -310,12 +330,13 @@ private Response addAssuranceForOrder(int assuranceType, String order private String queryForStationId(String stationName, HttpHeaders httpHeaders) { - PreserveOtherServiceImpl.LOGGER.info("[Preserve Other Service][Get Station By Name]"); + PreserveOtherServiceImpl.LOGGER.info("[queryForStationId][Preserve Other Service][Get Station By Name]"); HttpEntity requestQueryForStationId = new HttpEntity(httpHeaders); + String station_service_url = getServiceUrl("ts-station-service"); ResponseEntity> reQueryForStationId = restTemplate.exchange( - "http://ts-station-service:12345/api/v1/stationservice/stations/id/" + stationName, + station_service_url + "/api/v1/stationservice/stations/id/" + stationName, HttpMethod.GET, requestQueryForStationId, new ParameterizedTypeReference>() { @@ -324,11 +345,12 @@ private String queryForStationId(String stationName, HttpHeaders httpHeaders) { } private Response checkSecurity(String accountId, HttpHeaders httpHeaders) { - PreserveOtherServiceImpl.LOGGER.info("[Preserve Other Service][Check Account Security] Checking...."); + PreserveOtherServiceImpl.LOGGER.info("[checkSecurity][Preserve Other Service][Check Account Security]"); HttpEntity requestCheckResult = new HttpEntity(httpHeaders); + String security_service_url = getServiceUrl("ts-security-service"); ResponseEntity reCheckResult = restTemplate.exchange( - "http://ts-security-service:11188/api/v1/securityservice/securityConfigs/" + accountId, + security_service_url + "/api/v1/securityservice/securityConfigs/" + accountId, HttpMethod.GET, requestCheckResult, Response.class); @@ -338,11 +360,12 @@ private Response checkSecurity(String accountId, HttpHeaders httpHeaders) { private Response getTripAllDetailInformation(TripAllDetailInfo gtdi, HttpHeaders httpHeaders) { - PreserveOtherServiceImpl.LOGGER.info("[Preserve Other Service][Get Trip All Detail Information] Getting...."); + PreserveOtherServiceImpl.LOGGER.info("[getTripAllDetailInformation][Preserve Other Service][Get Trip All Detail Information]"); HttpEntity requestGetTripAllDetailResult = new HttpEntity(gtdi, httpHeaders); + String travel2_service_url = getServiceUrl("ts-travel2-service"); ResponseEntity> reGetTripAllDetailResult = restTemplate.exchange( - "http://ts-travel2-service:16346/api/v1/travel2service/trip_detail", + travel2_service_url + "/api/v1/travel2service/trip_detail", HttpMethod.POST, requestGetTripAllDetailResult, new ParameterizedTypeReference>() { @@ -352,11 +375,12 @@ private Response getTripAllDetailInformation(TripAllDetailInfo gt } private Response getContactsById(String contactsId, HttpHeaders httpHeaders) { - PreserveOtherServiceImpl.LOGGER.info("[Preserve Other Service][Get Contacts By Id is] Getting...."); + PreserveOtherServiceImpl.LOGGER.info("[getContactsById][Preserve Other Service][Get Contacts By Id is]"); HttpEntity requestGetContactsResult = new HttpEntity(httpHeaders); + String contacts_service_url = getServiceUrl("ts-contacts-service"); ResponseEntity> reGetContactsResult = restTemplate.exchange( - "http://ts-contacts-service:12347/api/v1/contactservice/contacts/" + contactsId, + contacts_service_url + "/api/v1/contactservice/contacts/" + contactsId, HttpMethod.GET, requestGetContactsResult, new ParameterizedTypeReference>() { @@ -366,11 +390,12 @@ private Response getContactsById(String contactsId, HttpHeaders httpHe } private Response createOrder(Order coi, HttpHeaders httpHeaders) { - PreserveOtherServiceImpl.LOGGER.info("[Preserve Other Service][Get Contacts By Id] Creating...."); + PreserveOtherServiceImpl.LOGGER.info("[createOrder][Preserve Other Service][Get Contacts By Id]"); HttpEntity requestEntityCreateOrderResult = new HttpEntity(coi, httpHeaders); + String order_other_service_url = getServiceUrl("ts-order-other-service"); ResponseEntity> reCreateOrderResult = restTemplate.exchange( - "http://ts-order-other-service:12032/api/v1/orderOtherService/orderOther", + order_other_service_url + "/api/v1/orderOtherService/orderOther", HttpMethod.POST, requestEntityCreateOrderResult, new ParameterizedTypeReference>() { @@ -381,11 +406,12 @@ private Response createOrder(Order coi, HttpHeaders httpHeaders) { } private Response createFoodOrder(FoodOrder afi, HttpHeaders httpHeaders) { - PreserveOtherServiceImpl.LOGGER.info("[Preserve Service][Add Preserve food Order] Creating...."); + PreserveOtherServiceImpl.LOGGER.info("[createFoodOrder][Preserve Service][Add Preserve food Order]"); HttpEntity requestEntityAddFoodOrderResult = new HttpEntity(afi, httpHeaders); + String food_service_url = getServiceUrl("ts-food-service"); ResponseEntity reAddFoodOrderResult = restTemplate.exchange( - "http://ts-food-service:18856/api/v1/foodservice/orders", + food_service_url + "/api/v1/foodservice/orders", HttpMethod.POST, requestEntityAddFoodOrderResult, Response.class); @@ -394,11 +420,12 @@ private Response createFoodOrder(FoodOrder afi, HttpHeaders httpHeaders) { } private Response createConsign(Consign cr, HttpHeaders httpHeaders) { - PreserveOtherServiceImpl.LOGGER.info("[Preserve Service][Add Condign] Creating Consign..."); + PreserveOtherServiceImpl.LOGGER.info("[createConsign][Preserve Service][Add Condign]"); HttpEntity requestEntityResultForTravel = new HttpEntity(cr, httpHeaders); + String consign_service_url = getServiceUrl("ts-consign-service"); ResponseEntity reResultForTravel = restTemplate.exchange( - "http://ts-consign-service:16111/api/v1/consignservice/consigns", + consign_service_url + "/api/v1/consignservice/consigns", HttpMethod.POST, requestEntityResultForTravel, Response.class); diff --git a/ts-preserve-other-service/src/main/resources/application.yml b/ts-preserve-other-service/src/main/resources/application.yml index a20cf0d38..a45738f89 100644 --- a/ts-preserve-other-service/src/main/resources/application.yml +++ b/ts-preserve-other-service/src/main/resources/application.yml @@ -12,11 +12,15 @@ server: port: 14569 # HTTP (Tomcat) port spring: + cloud: + nacos: + discovery: + server-addr: ${NACOS_ADDRS:nacos-0.nacos-headless.default.svc.cluster.local,nacos-1.nacos-headless.default.svc.cluster.local,nacos-2.nacos-headless.default.svc.cluster.local} application: name: ts-preserve-other-service rabbitmq: host: ${rabbitmq_host:localhost} - port: ${rabbitmq_port:5672} + port: 5672 swagger: controllerPackage: preserveOther.controller diff --git a/ts-preserve-other-service/src/test/java/preserveOther/controller/PreserveOtherControllerTest.java b/ts-preserve-other-service/src/test/java/preserveOther/controller/PreserveOtherControllerTest.java index a85a0938f..b75b042fc 100644 --- a/ts-preserve-other-service/src/test/java/preserveOther/controller/PreserveOtherControllerTest.java +++ b/ts-preserve-other-service/src/test/java/preserveOther/controller/PreserveOtherControllerTest.java @@ -16,7 +16,7 @@ import org.springframework.test.web.servlet.request.MockMvcRequestBuilders; import org.springframework.test.web.servlet.result.MockMvcResultMatchers; import org.springframework.test.web.servlet.setup.MockMvcBuilders; -import preserveOther.entity.OrderTicketsInfo; +import edu.fudan.common.entity.OrderTicketsInfo; import preserveOther.service.PreserveOtherService; @RunWith(JUnit4.class) diff --git a/ts-preserve-other-service/src/test/java/preserveOther/service/PreserveOtherServiceImplTest.java b/ts-preserve-other-service/src/test/java/preserveOther/service/PreserveOtherServiceImplTest.java index 4f7b7ddb3..16825358c 100644 --- a/ts-preserve-other-service/src/test/java/preserveOther/service/PreserveOtherServiceImplTest.java +++ b/ts-preserve-other-service/src/test/java/preserveOther/service/PreserveOtherServiceImplTest.java @@ -1,6 +1,7 @@ package preserveOther.service; import edu.fudan.common.util.Response; +import edu.fudan.common.util.StringUtils; import org.junit.Assert; import org.junit.Before; import org.junit.Test; @@ -13,7 +14,7 @@ import org.springframework.core.ParameterizedTypeReference; import org.springframework.http.*; import org.springframework.web.client.RestTemplate; -import preserveOther.entity.*; +import edu.fudan.common.entity.*; import java.util.Date; import java.util.HashMap; @@ -43,7 +44,7 @@ public void testPreserve() { .contactsId(UUID.randomUUID().toString()) .from("from_station") .to("to_station") - .date(new Date()) + .date(StringUtils.Date2String(new Date())) .handleDate("handle_date") .tripId("G1255") .seatType(2) @@ -85,7 +86,7 @@ public void testPreserve() { //response for getTripAllDetailInformation() TripResponse tripResponse = new TripResponse(); tripResponse.setConfortClass(1); - tripResponse.setStartingTime(new Date()); + tripResponse.setStartTime(StringUtils.Date2String(new Date())); TripAllDetail tripAllDetail = new TripAllDetail(true, "message", tripResponse, new Trip()); Response response3 = new Response<>(1, null, tripAllDetail); ResponseEntity> re3 = new ResponseEntity<>(response3, HttpStatus.OK); @@ -108,9 +109,9 @@ public void testPreserve() { //response for createOrder() Order order = new Order(); - order.setId(UUID.randomUUID()); - order.setAccountId(UUID.randomUUID()); - order.setTravelDate(new Date()); + order.setId(UUID.randomUUID().toString()); + order.setAccountId(UUID.randomUUID().toString()); + order.setTravelDate(StringUtils.Date2String(new Date())); order.setFrom("from_station"); order.setTo("to_station"); Response response7 = new Response<>(1, null, order); @@ -141,7 +142,7 @@ public void testPreserve() { @Test public void testDipatchSeat() { long mills = System.currentTimeMillis(); - Seat seatRequest = new Seat(new Date(mills), "G1234", "start_station", "dest_station", 2); + Seat seatRequest = new Seat(StringUtils.Date2String(new Date()), "G1234", "start_station", "dest_station", 2, 100, null); HttpEntity requestEntityTicket = new HttpEntity<>(seatRequest, headers); Response response = new Response<>(); ResponseEntity> reTicket = new ResponseEntity<>(response, HttpStatus.OK); @@ -151,7 +152,7 @@ public void testDipatchSeat() { requestEntityTicket, new ParameterizedTypeReference>() { })).thenReturn(reTicket); - Ticket result = preserveOtherServiceImpl.dipatchSeat(new Date(mills), "G1234", "start_station", "dest_station", 2, headers); + Ticket result = preserveOtherServiceImpl.dipatchSeat(StringUtils.Date2String(new Date()), "G1234", "start_station", "dest_station", 2, 100, null, headers); Assert.assertNull(result); } diff --git a/ts-preserve-service/pom.xml b/ts-preserve-service/pom.xml index 6a93e76fe..51d726058 100644 --- a/ts-preserve-service/pom.xml +++ b/ts-preserve-service/pom.xml @@ -15,7 +15,7 @@ org.services ts-service 0.1.0 - ../ + ../pom.xml @@ -29,11 +29,14 @@ ts-common 0.1.0 - org.springframework.boot spring-boot-starter-amqp + + jakarta.validation + jakarta.validation-api + diff --git a/ts-preserve-service/src/main/java/preserve/PreserveApplication.java b/ts-preserve-service/src/main/java/preserve/PreserveApplication.java index 454f99559..b71bc0898 100644 --- a/ts-preserve-service/src/main/java/preserve/PreserveApplication.java +++ b/ts-preserve-service/src/main/java/preserve/PreserveApplication.java @@ -3,6 +3,8 @@ import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.boot.web.client.RestTemplateBuilder; +import org.springframework.cloud.client.discovery.EnableDiscoveryClient; +import org.springframework.cloud.client.loadbalancer.LoadBalanced; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.EnableAspectJAutoProxy; import org.springframework.integration.annotation.IntegrationComponentScan; @@ -18,12 +20,14 @@ @EnableAsync @IntegrationComponentScan @EnableSwagger2 +@EnableDiscoveryClient public class PreserveApplication { public static void main(String[] args) { SpringApplication.run(PreserveApplication.class, args); } + @LoadBalanced @Bean public RestTemplate restTemplate(RestTemplateBuilder builder) { return builder.build(); diff --git a/ts-preserve-service/src/main/java/preserve/controller/PreserveController.java b/ts-preserve-service/src/main/java/preserve/controller/PreserveController.java index c717eee2b..4d623d582 100644 --- a/ts-preserve-service/src/main/java/preserve/controller/PreserveController.java +++ b/ts-preserve-service/src/main/java/preserve/controller/PreserveController.java @@ -6,7 +6,7 @@ import org.springframework.http.HttpEntity; import org.springframework.http.HttpHeaders; import org.springframework.web.bind.annotation.*; -import preserve.entity.*; +import edu.fudan.common.entity.*; import preserve.service.PreserveService; import static org.springframework.http.ResponseEntity.ok; @@ -32,7 +32,7 @@ public String home() { @PostMapping(value = "/preserve") public HttpEntity preserve(@RequestBody OrderTicketsInfo oti, @RequestHeader HttpHeaders headers) { - PreserveController.LOGGER.info("[Preserve] Account order from {} -----> {} at {}", oti.getFrom(), oti.getTo(), oti.getDate()); + PreserveController.LOGGER.info("[preserve][Preserve Account order][from {} to {} at {}]", oti.getFrom(), oti.getTo(), oti.getDate()); return ok(preserveService.preserve(oti, headers)); } diff --git a/ts-preserve-service/src/main/java/preserve/entity/Account.java b/ts-preserve-service/src/main/java/preserve/entity/Account.java deleted file mode 100644 index 6d31a563a..000000000 --- a/ts-preserve-service/src/main/java/preserve/entity/Account.java +++ /dev/null @@ -1,38 +0,0 @@ -package preserve.entity; - -import com.fasterxml.jackson.annotation.JsonIgnoreProperties; -import lombok.Data; - -import java.util.UUID; - -/** - * @author fdse - */ -@Data -@JsonIgnoreProperties(ignoreUnknown = true) -public class Account { - - private UUID id; - - private String password; - - private int gender; - - private String name; - - private int documentType; - - private String documentNum; - - private String email; - - public Account(){ - gender = Gender.OTHER.getCode(); - password = "defaultPassword"; //NOSONAR - name = "None"; - documentType = DocumentType.NONE.getCode(); - documentNum = "0123456789"; - email = "0123456789"; - } - -} diff --git a/ts-preserve-service/src/main/java/preserve/entity/Assurance.java b/ts-preserve-service/src/main/java/preserve/entity/Assurance.java deleted file mode 100644 index 96fa05d2c..000000000 --- a/ts-preserve-service/src/main/java/preserve/entity/Assurance.java +++ /dev/null @@ -1,39 +0,0 @@ -package preserve.entity; - -import com.fasterxml.jackson.annotation.JsonIgnoreProperties; -import lombok.Data; - -import javax.validation.constraints.NotNull; -import java.util.UUID; - -/** - * @author fdse - */ -@Data -@JsonIgnoreProperties(ignoreUnknown = true) -public class Assurance { - - private UUID id; - - /** - * which order the assurance is related to - */ - @NotNull - private UUID orderId; - - /** - * the type of assurance - */ - private AssuranceType type; - - public Assurance(){ - this.orderId = UUID.randomUUID(); - } - - public Assurance(UUID id, UUID orderId, AssuranceType type){ - this.id = id; - this.orderId = orderId; - this.type = type; - } - -} diff --git a/ts-preserve-service/src/main/java/preserve/entity/AssuranceType.java b/ts-preserve-service/src/main/java/preserve/entity/AssuranceType.java deleted file mode 100644 index 20ef88ad2..000000000 --- a/ts-preserve-service/src/main/java/preserve/entity/AssuranceType.java +++ /dev/null @@ -1,69 +0,0 @@ -package preserve.entity; - -import java.io.Serializable; - -/** - * @author fdse - */ -public enum AssuranceType implements Serializable{ - - /** - * traffic accident assurance - */ - TRAFFIC_ACCIDENT (1, "Traffic Accident Assurance", 3.0); - - /** - * index of assurance type - */ - private int index; - /** - * the assurance type name - */ - private String name; - /** - * the price of this type of assurence - */ - private double price; - - AssuranceType(int index, String name, double price){ - this.index = index; - this.name = name; - this.price = price; - } - - public int getIndex() { - return index; - } - - void setIndex(int index) { - this.index = index; - } - - public String getName() { - return name; - } - - void setName(String name) { - this.name = name; - } - - public double getPrice() { - return price; - } - - void setPrice(double price) { - this.price = price; - } - - public static AssuranceType getTypeByIndex(int index){ - AssuranceType[] ats = AssuranceType.values(); - for(AssuranceType at : ats){ - if(at.getIndex() == index){ - return at; - } - } - return null; - } - - -} diff --git a/ts-preserve-service/src/main/java/preserve/entity/Contacts.java b/ts-preserve-service/src/main/java/preserve/entity/Contacts.java deleted file mode 100644 index 2a3084dc4..000000000 --- a/ts-preserve-service/src/main/java/preserve/entity/Contacts.java +++ /dev/null @@ -1,57 +0,0 @@ -package preserve.entity; - -import com.fasterxml.jackson.annotation.JsonIgnoreProperties; -import lombok.Data; - -import java.util.UUID; - -/** - * @author fdse - */ -@Data -@JsonIgnoreProperties(ignoreUnknown = true) -public class Contacts { - - private UUID id; - - private UUID accountId; - - private String name; - - private int documentType; - - private String documentNumber; - - private String phoneNumber; - - public Contacts() { - //Default Constructor - } - - @Override - public boolean equals(Object obj) { - if (this == obj) { - return true; - } - if (obj == null) { - return false; - } - if (getClass() != obj.getClass()) { - return false; - } - Contacts other = (Contacts) obj; - return name.equals(other.getName()) - && accountId .equals( other.getAccountId() ) - && documentNumber.equals(other.getDocumentNumber()) - && phoneNumber.equals(other.getPhoneNumber()) - && documentType == other.getDocumentType(); - } - - @Override - public int hashCode() { - int result = 17; - result = 31 * result + (id == null ? 0 : id.hashCode()); - return result; - } - -} diff --git a/ts-preserve-service/src/main/java/preserve/entity/DocumentType.java b/ts-preserve-service/src/main/java/preserve/entity/DocumentType.java deleted file mode 100644 index c8cb3b9db..000000000 --- a/ts-preserve-service/src/main/java/preserve/entity/DocumentType.java +++ /dev/null @@ -1,50 +0,0 @@ -package preserve.entity; - -/** - * @author fdse - */ -public enum DocumentType { - - /** - * null - */ - NONE (0,"Null"), - /** - * id card - */ - ID_CARD (1,"ID Card"), - /** - * paaaport - */ - PASSPORT (2,"Passport"), - /** - * other - */ - OTHER (3,"Other"); - - private int code; - private String name; - - DocumentType(int code, String name){ - this.code = code; - this.name = name; - } - - public int getCode(){ - return code; - } - - public String getName() { - return name; - } - - public static String getNameByCode(int code){ - DocumentType[] documentTypeSet = DocumentType.values(); - for(DocumentType documentType : documentTypeSet){ - if(documentType.getCode() == code){ - return documentType.getName(); - } - } - return documentTypeSet[0].getName(); - } -} diff --git a/ts-preserve-service/src/main/java/preserve/entity/Gender.java b/ts-preserve-service/src/main/java/preserve/entity/Gender.java deleted file mode 100644 index 3234494ba..000000000 --- a/ts-preserve-service/src/main/java/preserve/entity/Gender.java +++ /dev/null @@ -1,51 +0,0 @@ -package preserve.entity; - -/** - * @author fdse - */ -public enum Gender { - - /** - * null - */ - NONE (0, "Null"), - /** - * male - */ - MALE (1, "Male"), - /** - * female - */ - FEMALE (2, "Female"), - /** - * other - */ - OTHER (3, "Other"); - - private int code; - private String name; - - Gender(int code, String name){ - this.code = code; - this.name = name; - } - - public int getCode(){ - return code; - } - - public String getName() { - return name; - } - - public static String getNameByCode(int code){ - Gender[] genderSet = Gender.values(); - for(Gender gender : genderSet){ - if(gender.getCode() == code){ - return gender.getName(); - } - } - return genderSet[0].getName(); - } - -} diff --git a/ts-preserve-service/src/main/java/preserve/entity/Order.java b/ts-preserve-service/src/main/java/preserve/entity/Order.java deleted file mode 100644 index 0aab1ae77..000000000 --- a/ts-preserve-service/src/main/java/preserve/entity/Order.java +++ /dev/null @@ -1,103 +0,0 @@ -package preserve.entity; - -import com.fasterxml.jackson.annotation.JsonIgnoreProperties; -import lombok.Data; - -import java.util.Date; -import java.util.UUID; - -/** - * @author fdse - */ -@Data -@JsonIgnoreProperties(ignoreUnknown = true) -public class Order { - - private UUID id; - - private Date boughtDate; - - private Date travelDate; - - private Date travelTime; - - /** - * Which Account Bought it - */ - private UUID accountId; - - /** - * Tickets bought for whom... - */ - private String contactsName; - - private int documentType; - - private String contactsDocumentNumber; - - private String trainNumber; - - private int coachNumber; - - private int seatClass; - - private String seatNumber; - - private String from; - - private String to; - - private int status; - - private String price; - - public Order(){ - boughtDate = new Date(System.currentTimeMillis()); - travelDate = new Date(123456789); - trainNumber = "G1235"; - coachNumber = 5; - seatClass = SeatClass.FIRSTCLASS.getCode(); - seatNumber = "5A"; - from = "shanghai"; - to = "taiyuan"; - status = OrderStatus.PAID.getCode(); - price = "0.0"; - } - - @Override - public boolean equals(Object obj) { - if (this == obj) { - return true; - } - if (obj == null) { - return false; - } - if (getClass() != obj.getClass()) { - return false; - } - Order other = (Order) obj; - return boughtDate.equals(other.getBoughtDate()) - && travelDate.equals(other.getTravelDate()) - && travelTime.equals(other.getTravelTime()) - && accountId .equals( other.getAccountId() ) - && contactsName.equals(other.getContactsName()) - && contactsDocumentNumber.equals(other.getContactsDocumentNumber()) - && documentType == other.getDocumentType() - && trainNumber.equals(other.getTrainNumber()) - && coachNumber == other.getCoachNumber() - && seatClass == other.getSeatClass() - && seatNumber .equals(other.getSeatNumber()) - && from.equals(other.getFrom()) - && to.equals(other.getTo()) - && status == other.getStatus() - && price == other.price; - } - - @Override - public int hashCode() { - int result = 17; - result = 31 * result + (id == null ? 0 : id.hashCode()); - return result; - } - -} diff --git a/ts-preserve-service/src/main/java/preserve/entity/OrderTicketsInfo.java b/ts-preserve-service/src/main/java/preserve/entity/OrderTicketsInfo.java deleted file mode 100644 index 84a5f5c2b..000000000 --- a/ts-preserve-service/src/main/java/preserve/entity/OrderTicketsInfo.java +++ /dev/null @@ -1,58 +0,0 @@ -package preserve.entity; - -import lombok.AllArgsConstructor; -import lombok.Builder; -import lombok.Data; - -import java.util.Date; - -/** - * @author fdse - */ -@Data -@AllArgsConstructor -@Builder -public class OrderTicketsInfo { - private String accountId; - - private String contactsId; - - private String tripId; - - private int seatType; - - private Date date; - - private String from; - - private String to; - - private int assurance; - - - private int foodType = 0; - - private String stationName; - - private String storeName; - - private String foodName; - - private double foodPrice; - - - private String handleDate; - - private String consigneeName = ""; - - private String consigneePhone = ""; - - private double consigneeWeight; - - private boolean isWithin; - - - public OrderTicketsInfo() { - //Default Constructor - } -} diff --git a/ts-preserve-service/src/main/java/preserve/entity/OrderTicketsResult.java b/ts-preserve-service/src/main/java/preserve/entity/OrderTicketsResult.java deleted file mode 100644 index 020f68a8a..000000000 --- a/ts-preserve-service/src/main/java/preserve/entity/OrderTicketsResult.java +++ /dev/null @@ -1,21 +0,0 @@ -package preserve.entity; - -import lombok.Data; - -/** - * @author fdse - */ -@Data -public class OrderTicketsResult { - - private boolean status; - - private String message; - - private Order order; - - public OrderTicketsResult(){ - //Default Constructor - } - -} diff --git a/ts-preserve-service/src/main/java/preserve/entity/Seat.java b/ts-preserve-service/src/main/java/preserve/entity/Seat.java deleted file mode 100644 index 2c5639b56..000000000 --- a/ts-preserve-service/src/main/java/preserve/entity/Seat.java +++ /dev/null @@ -1,29 +0,0 @@ -package preserve.entity; - -import lombok.AllArgsConstructor; -import lombok.Data; - -import java.util.Date; - -/** - * @author fdse - */ -@Data -@AllArgsConstructor -public class Seat { - - private Date travelDate; - - private String trainNumber; - - private String startStation; - - private String destStation; - - private int seatType; - - public Seat(){ - //Default Constructor - } - -} diff --git a/ts-preserve-service/src/main/java/preserve/entity/SeatClass.java b/ts-preserve-service/src/main/java/preserve/entity/SeatClass.java deleted file mode 100644 index 287b23f07..000000000 --- a/ts-preserve-service/src/main/java/preserve/entity/SeatClass.java +++ /dev/null @@ -1,70 +0,0 @@ -package preserve.entity; - -/** - * @author fdse - */ -public enum SeatClass { - - /** - * no seat - */ - NONE (0,"NoSeat"), - /** - * green seat - */ - BUSINESS (1,"GreenSeat"), - /** - * first class seat - */ - FIRSTCLASS (2,"FirstClassSeat"), - /** - * second class seat - */ - SECONDCLASS (3,"SecondClassSeat"), - /** - * hard seat - */ - HARDSEAT (4,"HardSeat"), - /** - * soft seat - */ - SOFTSEAT (5,"SoftSeat"), - /** - * hard bed - */ - HARDBED (6,"HardBed"), - /** - * soft bed - */ - SOFTBED (7,"SoftBed"), - /** - * high soft seat - */ - HIGHSOFTBED (8,"HighSoftSeat"); - - private int code; - private String name; - - SeatClass(int code, String name){ - this.code = code; - this.name = name; - } - - public int getCode(){ - return code; - } - - public String getName() { - return name; - } - - public static String getNameByCode(int code){ - SeatClass[] seatClassSet = SeatClass.values(); - for(SeatClass seatClass : seatClassSet){ - if(seatClass.getCode() == code){ - return seatClass.getName(); - } - } - return seatClassSet[0].getName(); - } -} diff --git a/ts-preserve-service/src/main/java/preserve/entity/Ticket.java b/ts-preserve-service/src/main/java/preserve/entity/Ticket.java deleted file mode 100644 index 9e08acc40..000000000 --- a/ts-preserve-service/src/main/java/preserve/entity/Ticket.java +++ /dev/null @@ -1,21 +0,0 @@ -package preserve.entity; - -import lombok.Data; - -/** - * @author fdse - */ -@Data -public class Ticket { - - private int seatNo; - - private String startStation; - - private String destStation; - - public Ticket(){ - //Default Constructor. - } - -} diff --git a/ts-preserve-service/src/main/java/preserve/entity/TrainType.java b/ts-preserve-service/src/main/java/preserve/entity/TrainType.java deleted file mode 100644 index 21d98e23f..000000000 --- a/ts-preserve-service/src/main/java/preserve/entity/TrainType.java +++ /dev/null @@ -1,31 +0,0 @@ -package preserve.entity; - -import lombok.Data; - -import javax.validation.Valid; - -/** - * @author fdse - */ -@Data -public class TrainType { - @Valid - private String id; - - @Valid - private int economyClass; - - @Valid - private int confortClass; - - public TrainType(){ - //Default Constructor - } - - public TrainType(String id, int economyClass, int confortClass) { - this.id = id; - this.economyClass = economyClass; - this.confortClass = confortClass; - } - -} diff --git a/ts-preserve-service/src/main/java/preserve/entity/Travel.java b/ts-preserve-service/src/main/java/preserve/entity/Travel.java deleted file mode 100644 index b9daeaf33..000000000 --- a/ts-preserve-service/src/main/java/preserve/entity/Travel.java +++ /dev/null @@ -1,25 +0,0 @@ -package preserve.entity; - -import lombok.Data; - -import java.util.Date; - -/** - * @author fdse - */ -@Data -public class Travel { - - private Trip trip; - - private String startingPlace; - - private String endPlace; - - private Date departureTime; - - public Travel(){ - //Default Constructor - } - -} diff --git a/ts-preserve-service/src/main/java/preserve/entity/TravelResult.java b/ts-preserve-service/src/main/java/preserve/entity/TravelResult.java deleted file mode 100644 index 1c77dea93..000000000 --- a/ts-preserve-service/src/main/java/preserve/entity/TravelResult.java +++ /dev/null @@ -1,24 +0,0 @@ -package preserve.entity; - -import java.util.Map; -import lombok.*; - -/** - * @author fdse - */ -@Data -public class TravelResult { - - private boolean status; - - private double percent; - - private TrainType trainType; - - private Map prices; - - public TravelResult(){ - //Default Constructor - } - -} diff --git a/ts-preserve-service/src/main/java/preserve/entity/Trip.java b/ts-preserve-service/src/main/java/preserve/entity/Trip.java deleted file mode 100644 index 0deb7348d..000000000 --- a/ts-preserve-service/src/main/java/preserve/entity/Trip.java +++ /dev/null @@ -1,73 +0,0 @@ -package preserve.entity; - -import lombok.Data; - -import javax.validation.Valid; -import javax.validation.constraints.NotNull; -import java.util.Date; - -/** - * @author fdse - */ -@Data -public class Trip { - @Valid - private TripId tripId; - - @Valid - @NotNull - private String trainTypeId; - - private String routeId; - - - @Valid - @NotNull - private String startingStationId; - - - @Valid - private String stationsId; - - @Valid - @NotNull - private String terminalStationId; - - @Valid - @NotNull - private Date startingTime; - - @Valid - @NotNull - private Date endTime; - - public Trip(TripId tripId, String trainTypeId, String startingStationId, String stationsId, String terminalStationId, Date startingTime, Date endTime) { - this.tripId = tripId; - this.trainTypeId = trainTypeId; - this.startingStationId = startingStationId; - this.stationsId = stationsId; - this.terminalStationId = terminalStationId; - this.startingTime = startingTime; - this.endTime = endTime; - } - - public Trip(TripId tripId, String trainTypeId, String routeId) { - this.tripId = tripId; - this.trainTypeId = trainTypeId; - this.routeId = routeId; - this.startingStationId = ""; - this.terminalStationId = ""; - this.startingTime = new Date(); - this.endTime = new Date(); - } - - public Trip(){ - //Default Constructor - this.trainTypeId = ""; - this.startingStationId = ""; - this.terminalStationId = ""; - this.startingTime = new Date(); - this.endTime = new Date(); - } - -} diff --git a/ts-preserve-service/src/main/java/preserve/entity/TripAllDetailInfo.java b/ts-preserve-service/src/main/java/preserve/entity/TripAllDetailInfo.java deleted file mode 100644 index 409da7e19..000000000 --- a/ts-preserve-service/src/main/java/preserve/entity/TripAllDetailInfo.java +++ /dev/null @@ -1,25 +0,0 @@ -package preserve.entity; - -import lombok.Data; - -import java.util.Date; - -/** - * @author fdse - */ -@Data -public class TripAllDetailInfo { - - private String tripId; - - private Date travelDate; - - private String from; - - private String to; - - public TripAllDetailInfo() { - //Default Constructor - } - -} diff --git a/ts-preserve-service/src/main/java/preserve/entity/TripId.java b/ts-preserve-service/src/main/java/preserve/entity/TripId.java deleted file mode 100644 index 1192e974a..000000000 --- a/ts-preserve-service/src/main/java/preserve/entity/TripId.java +++ /dev/null @@ -1,41 +0,0 @@ -package preserve.entity; - -import lombok.Data; - -import java.io.Serializable; - -/** - * @author fdse - */ -@Data -public class TripId implements Serializable{ - private Type type; - private String number; - - - public TripId(){} - - public TripId(String trainNumber){ - char type0 = trainNumber.charAt(0); - switch(type0){ - case 'G': this.type = Type.G; - break; - case 'D': this.type = Type.D; - break; - case 'Z': this.type = Type.Z; - break; - case 'T': this.type = Type.T; - break; - case 'K': this.type = Type.K; - break; - default:break; - } - - this.number = trainNumber.substring(1); - } - - @Override - public String toString(){ - return type.getName() + number; - } -} diff --git a/ts-preserve-service/src/main/java/preserve/entity/TripResponse.java b/ts-preserve-service/src/main/java/preserve/entity/TripResponse.java deleted file mode 100644 index b423445fc..000000000 --- a/ts-preserve-service/src/main/java/preserve/entity/TripResponse.java +++ /dev/null @@ -1,47 +0,0 @@ -package preserve.entity; - -import lombok.Data; - -import javax.validation.Valid; -import javax.validation.constraints.NotNull; -import java.util.Date; - -/** - * @author fdse - */ -@Data -public class TripResponse { - @Valid - private TripId tripId; - - @Valid - @NotNull - private String startingStation; - - @Valid - @NotNull - private String terminalStation; - - @Valid - @NotNull - private Date startingTime; - - @Valid - @NotNull - private Date endTime; - - /** - * the number of economy seat - */ - @Valid - @NotNull - private int economyClass; - - /** - * the number of confort seat - */ - @Valid - @NotNull - private int confortClass; - -} diff --git a/ts-preserve-service/src/main/java/preserve/entity/Type.java b/ts-preserve-service/src/main/java/preserve/entity/Type.java deleted file mode 100644 index d8df7a2f3..000000000 --- a/ts-preserve-service/src/main/java/preserve/entity/Type.java +++ /dev/null @@ -1,63 +0,0 @@ -package preserve.entity; - -import java.io.Serializable; - -/** - * @author fdse - */ -public enum Type implements Serializable{ - - /** - * G - */ - G("G", 1), - /** - * D - */ - D("D", 2), - /** - * Z - */ - Z("Z",3), - /** - * T - */ - T("T", 4), - /** - * K - */ - K("K", 5); - - private String name; - private int index; - - Type(String name, int index) { - this.name = name; - this.index = index; - } - - public static String getName(int index) { - for (Type type : Type.values()) { - if (type.getIndex() == index) { - return type.name; - } - } - return null; - } - - public String getName() { - return name; - } - - void setName(String name) { - this.name = name; - } - - public int getIndex() { - return index; - } - - void setIndex(int index) { - this.index = index; - } -} diff --git a/ts-preserve-service/src/main/java/preserve/service/PreserveService.java b/ts-preserve-service/src/main/java/preserve/service/PreserveService.java index cfda44289..828bc8989 100644 --- a/ts-preserve-service/src/main/java/preserve/service/PreserveService.java +++ b/ts-preserve-service/src/main/java/preserve/service/PreserveService.java @@ -2,7 +2,7 @@ import edu.fudan.common.util.Response; import org.springframework.http.HttpHeaders; -import preserve.entity.OrderTicketsInfo; +import edu.fudan.common.entity.OrderTicketsInfo; /** * @author fdse diff --git a/ts-preserve-service/src/main/java/preserve/service/PreserveServiceImpl.java b/ts-preserve-service/src/main/java/preserve/service/PreserveServiceImpl.java index e8c623d9a..45cec7ac2 100644 --- a/ts-preserve-service/src/main/java/preserve/service/PreserveServiceImpl.java +++ b/ts-preserve-service/src/main/java/preserve/service/PreserveServiceImpl.java @@ -2,9 +2,13 @@ import edu.fudan.common.util.JsonUtils; import edu.fudan.common.util.Response; +import edu.fudan.common.util.StringUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.cloud.client.ServiceInstance; +import org.springframework.cloud.client.discovery.DiscoveryClient; import org.springframework.core.ParameterizedTypeReference; import org.springframework.http.HttpEntity; import org.springframework.http.HttpHeaders; @@ -12,10 +16,11 @@ import org.springframework.http.ResponseEntity; import org.springframework.stereotype.Service; import org.springframework.web.client.RestTemplate; -import preserve.entity.*; +import edu.fudan.common.entity.*; import preserve.mq.RabbitSend; import java.util.Date; +import java.util.List; import java.util.UUID; /** @@ -30,31 +35,38 @@ public class PreserveServiceImpl implements PreserveService { @Autowired private RabbitSend sendService; + @Autowired + private DiscoveryClient discoveryClient; + + private static final Logger LOGGER = LoggerFactory.getLogger(PreserveServiceImpl.class); + private String getServiceUrl(String serviceName) { + return "http://" + serviceName; } + @Override public Response preserve(OrderTicketsInfo oti, HttpHeaders headers) { //1.detect ticket scalper - PreserveServiceImpl.LOGGER.info("[Step 1] Check Security"); + //PreserveServiceImpl.LOGGER.info("[Step 1] Check Security"); Response result = checkSecurity(oti.getAccountId(), headers); if (result.getStatus() == 0) { - PreserveServiceImpl.LOGGER.error("[Step 1] Check Security Fail, AccountId: {}",oti.getAccountId()); + PreserveServiceImpl.LOGGER.error("[preserve][Step 1][Check Security Fail][AccountId: {}]",oti.getAccountId()); return new Response<>(0, result.getMsg(), null); } - PreserveServiceImpl.LOGGER.info("[Step 1] Check Security Complete"); + PreserveServiceImpl.LOGGER.info("[preserve][Step 1][Check Security Complete][AccountId: {}]",oti.getAccountId()); //2.Querying contact information -- modification, mediated by the underlying information micro service - PreserveServiceImpl.LOGGER.info("[Step 2] Find contacts"); - PreserveServiceImpl.LOGGER.info("[Step 2] Contacts Id: {}", oti.getContactsId()); + //PreserveServiceImpl.LOGGER.info("[Step 2] Find contacts"); + //PreserveServiceImpl.LOGGER.info("[Step 2] Contacts Id: {}", oti.getContactsId()); Response gcr = getContactsById(oti.getContactsId(), headers); if (gcr.getStatus() == 0) { - PreserveServiceImpl.LOGGER.error("[Get Contacts] Fail,ContactsId: {},message: {}",oti.getContactsId(),gcr.getMsg()); + PreserveServiceImpl.LOGGER.error("[preserve][Step 2][Find Contacts Fail][ContactsId: {},message: {}]",oti.getContactsId(),gcr.getMsg()); return new Response<>(0, gcr.getMsg(), null); } - PreserveServiceImpl.LOGGER.info("[Step 2] Complete"); + PreserveServiceImpl.LOGGER.info("[preserve][Step 2][Find contacts Complete][ContactsId: {}]",oti.getContactsId()); //3.Check the info of train and the number of remaining tickets - PreserveServiceImpl.LOGGER.info("[Step 3] Check tickets num"); + //PreserveServiceImpl.LOGGER.info("[Step 3] Check tickets num"); TripAllDetailInfo gtdi = new TripAllDetailInfo(); gtdi.setFrom(oti.getFrom()); @@ -62,45 +74,45 @@ public Response preserve(OrderTicketsInfo oti, HttpHeaders headers) { gtdi.setTravelDate(oti.getDate()); gtdi.setTripId(oti.getTripId()); - PreserveServiceImpl.LOGGER.info("[Step 3] TripId: {}", oti.getTripId()); + PreserveServiceImpl.LOGGER.info("[preserve][Step 3][Check tickets num][TripId: {}]", oti.getTripId()); Response response = getTripAllDetailInformation(gtdi, headers); TripAllDetail gtdr = response.getData(); - LOGGER.info("TripAllDetail:" + gtdr.toString()); + //LOGGER.info("TripAllDetail:" + gtdr.toString()); if (response.getStatus() == 0) { - PreserveServiceImpl.LOGGER.error("[Search For Trip Detail Information] error, TripId: {}, message: {}", gtdi.getTripId(), response.getMsg()); + PreserveServiceImpl.LOGGER.error("[preserve][Step 3][Check tickets num][Search For Trip Detail Information error][TripId: {}, message: {}]", gtdi.getTripId(), response.getMsg()); return new Response<>(0, response.getMsg(), null); } else { TripResponse tripResponse = gtdr.getTripResponse(); - LOGGER.info("TripResponse:" + tripResponse.toString()); + //LOGGER.info("TripResponse:" + tripResponse.toString()); if (oti.getSeatType() == SeatClass.FIRSTCLASS.getCode()) { if (tripResponse.getConfortClass() == 0) { - PreserveServiceImpl.LOGGER.warn("[Check seat is enough], TripId: {}",oti.getTripId()); + PreserveServiceImpl.LOGGER.warn("[preserve][Step 3][Check seat][Check seat is enough][TripId: {}]",oti.getTripId()); return new Response<>(0, "Seat Not Enough", null); } } else { if (tripResponse.getEconomyClass() == SeatClass.SECONDCLASS.getCode() && tripResponse.getConfortClass() == 0) { - PreserveServiceImpl.LOGGER.warn("[Check seat is Not enough], TripId: {}",oti.getTripId()); + PreserveServiceImpl.LOGGER.warn("[preserve][Step 3][Check seat][Check seat is Not enough][TripId: {}]",oti.getTripId()); return new Response<>(0, "Seat Not Enough", null); } } } Trip trip = gtdr.getTrip(); - PreserveServiceImpl.LOGGER.info("[Step 3] Tickets Enough"); + PreserveServiceImpl.LOGGER.info("[preserve][Step 3][Check tickets num][Tickets Enough]"); //4.send the order request and set the order information - PreserveServiceImpl.LOGGER.info("[Step 4] Do Order"); + //PreserveServiceImpl.LOGGER.info("[Step 4] Do Order"); Contacts contacts = gcr.getData(); Order order = new Order(); UUID orderId = UUID.randomUUID(); - order.setId(orderId); + order.setId(orderId.toString()); order.setTrainNumber(oti.getTripId()); - order.setAccountId(UUID.fromString(oti.getAccountId())); + order.setAccountId(oti.getAccountId()); - String fromStationId = queryForStationId(oti.getFrom(), headers); - String toStationId = queryForStationId(oti.getTo(), headers); + String fromStationName = oti.getFrom(); + String toStationName = oti.getTo(); - order.setFrom(fromStationId); - order.setTo(toStationId); - order.setBoughtDate(new Date()); + order.setFrom(fromStationName); + order.setTo(toStationName); + order.setBoughtDate(StringUtils.Date2String(new Date())); order.setStatus(OrderStatus.NOTPAID.getCode()); order.setContactsDocumentNumber(contacts.getDocumentNumber()); order.setContactsName(contacts.getName()); @@ -108,63 +120,71 @@ public Response preserve(OrderTicketsInfo oti, HttpHeaders headers) { Travel query = new Travel(); query.setTrip(trip); - query.setStartingPlace(oti.getFrom()); + query.setStartPlace(oti.getFrom()); query.setEndPlace(oti.getTo()); - query.setDepartureTime(new Date()); + query.setDepartureTime(StringUtils.Date2String(new Date())); HttpEntity requestEntity = new HttpEntity(query, headers); + String basic_service_url = getServiceUrl("ts-basic-service"); ResponseEntity> re = restTemplate.exchange( - "http://ts-ticketinfo-service:15681/api/v1/ticketinfoservice/ticketinfo", + basic_service_url + "/api/v1/basicservice/basic/travel", HttpMethod.POST, requestEntity, new ParameterizedTypeReference>() { }); + if(re.getBody().getStatus() == 0){ + PreserveServiceImpl.LOGGER.info("[Preserve 3][Get basic travel response status is 0][response is: {}]", re.getBody()); + return new Response<>(0, re.getBody().getMsg(), null); + } TravelResult resultForTravel = re.getBody().getData(); order.setSeatClass(oti.getSeatType()); - PreserveServiceImpl.LOGGER.info("[Order] Order Travel Date: {}", oti.getDate().toString()); + PreserveServiceImpl.LOGGER.info("[preserve][Step 4][Do Order][Travel Date][Date is: {}]", oti.getDate().toString()); order.setTravelDate(oti.getDate()); - order.setTravelTime(gtdr.getTripResponse().getStartingTime()); + order.setTravelTime(gtdr.getTripResponse().getStartTime()); //Dispatch the seat + List stationList = resultForTravel.getRoute().getStations(); if (oti.getSeatType() == SeatClass.FIRSTCLASS.getCode()) { + int firstClassTotalNum = resultForTravel.getTrainType().getConfortClass(); Ticket ticket = dipatchSeat(oti.getDate(), - order.getTrainNumber(), fromStationId, toStationId, - SeatClass.FIRSTCLASS.getCode(), headers); + order.getTrainNumber(), fromStationName, toStationName, + SeatClass.FIRSTCLASS.getCode(), firstClassTotalNum, stationList, headers); order.setSeatNumber("" + ticket.getSeatNo()); order.setSeatClass(SeatClass.FIRSTCLASS.getCode()); order.setPrice(resultForTravel.getPrices().get("confortClass")); } else { + int secondClassTotalNum = resultForTravel.getTrainType().getEconomyClass(); Ticket ticket = dipatchSeat(oti.getDate(), - order.getTrainNumber(), fromStationId, toStationId, - SeatClass.SECONDCLASS.getCode(), headers); + order.getTrainNumber(), fromStationName, toStationName, + SeatClass.SECONDCLASS.getCode(), secondClassTotalNum, stationList, headers); order.setSeatClass(SeatClass.SECONDCLASS.getCode()); order.setSeatNumber("" + ticket.getSeatNo()); order.setPrice(resultForTravel.getPrices().get("economyClass")); } - PreserveServiceImpl.LOGGER.info("[Order Price] Price is: {}", order.getPrice()); + PreserveServiceImpl.LOGGER.info("[preserve][Step 4][Do Order][Order Price][Price is: {}]", order.getPrice()); Response cor = createOrder(order, headers); if (cor.getStatus() == 0) { - PreserveServiceImpl.LOGGER.error("[Create Order Fail] Create Order Fail. OrderId: {}, Reason: {}", order.getId(), cor.getMsg()); + PreserveServiceImpl.LOGGER.error("[preserve][Step 4][Do Order][Create Order Fail][OrderId: {}, Reason: {}]", order.getId(), cor.getMsg()); return new Response<>(0, cor.getMsg(), null); } - PreserveServiceImpl.LOGGER.info("[Step 4] Do Order Complete"); + PreserveServiceImpl.LOGGER.info("[preserve][Step 4][Do Order][Do Order Complete]"); Response returnResponse = new Response<>(1, "Success.", cor.getMsg()); //5.Check insurance options if (oti.getAssurance() == 0) { - PreserveServiceImpl.LOGGER.info("[Step 5] Do not need to buy assurance"); + PreserveServiceImpl.LOGGER.info("[preserve][Step 5][Buy Assurance][Do not need to buy assurance]"); } else { Response addAssuranceResult = addAssuranceForOrder( oti.getAssurance(), cor.getData().getId().toString(), headers); if (addAssuranceResult.getStatus() == 1) { - PreserveServiceImpl.LOGGER.info("[Step 5] Buy Assurance Success"); + PreserveServiceImpl.LOGGER.info("[preserve][Step 5][Buy Assurance][Preserve Buy Assurance Success]"); } else { - PreserveServiceImpl.LOGGER.warn("[Step 5] Buy Assurance Fail, assurance: {}, OrderId: {}", oti.getAssurance(),cor.getData().getId()); + PreserveServiceImpl.LOGGER.warn("[preserve][Step 5][Buy Assurance][Buy Assurance Fail][assurance: {}, OrderId: {}]", oti.getAssurance(),cor.getData().getId()); returnResponse.setMsg("Success.But Buy Assurance Fail."); } } @@ -181,17 +201,17 @@ public Response preserve(OrderTicketsInfo oti, HttpHeaders headers) { if (oti.getFoodType() == 2) { foodOrder.setStationName(oti.getStationName()); foodOrder.setStoreName(oti.getStoreName()); - PreserveServiceImpl.LOGGER.info("foodstore= {} {} {}", foodOrder.getFoodType(), foodOrder.getStationName(), foodOrder.getStoreName()); + //PreserveServiceImpl.LOGGER.info("foodstore= {} {} {}", foodOrder.getFoodType(), foodOrder.getStationName(), foodOrder.getStoreName()); } Response afor = createFoodOrder(foodOrder, headers); if (afor.getStatus() == 1) { - PreserveServiceImpl.LOGGER.info("[Step 6] Buy Food Success"); + PreserveServiceImpl.LOGGER.info("[preserve][Step 6][Buy Food][Buy Food Success]"); } else { - PreserveServiceImpl.LOGGER.error("[Step 6] Buy Food Fail, OrderId: {}",cor.getData().getId()); + PreserveServiceImpl.LOGGER.error("[preserve][Step 6][Buy Food][Buy Food Fail][OrderId: {}]",cor.getData().getId()); returnResponse.setMsg("Success.But Buy Food Fail."); } } else { - PreserveServiceImpl.LOGGER.info("[Step 6] Do not need to buy food"); + PreserveServiceImpl.LOGGER.info("[preserve][Step 6][Buy Food][Do not need to buy food]"); } //7.add consign @@ -211,13 +231,13 @@ public Response preserve(OrderTicketsInfo oti, HttpHeaders headers) { LOGGER.info("CONSIGN INFO : " +consignRequest.toString()); Response icresult = createConsign(consignRequest, headers); if (icresult.getStatus() == 1) { - PreserveServiceImpl.LOGGER.info("[Step 7] Consign Success"); + PreserveServiceImpl.LOGGER.info("[preserve][Step 7][Add Consign][Consign Success]"); } else { - PreserveServiceImpl.LOGGER.error("[Step 7] Preserve Consign Fail, OrderId: {}", cor.getData().getId()); + PreserveServiceImpl.LOGGER.error("[preserve][Step 7][Add Consign][Preserve Consign Fail][OrderId: {}]", cor.getData().getId()); returnResponse.setMsg("Consign Fail."); } } else { - PreserveServiceImpl.LOGGER.info("[Step 7] Do not need to consign"); + PreserveServiceImpl.LOGGER.info("[preserve][Step 7][Add Consign][Do not need to consign]"); } //8.send notification @@ -228,14 +248,14 @@ public Response preserve(OrderTicketsInfo oti, HttpHeaders headers) { notifyInfo.setDate(new Date().toString()); notifyInfo.setEmail(getUser.getEmail()); - notifyInfo.setStartingPlace(order.getFrom()); + notifyInfo.setStartPlace(order.getFrom()); notifyInfo.setEndPlace(order.getTo()); notifyInfo.setUsername(getUser.getUserName()); notifyInfo.setSeatNumber(order.getSeatNumber()); notifyInfo.setOrderNumber(order.getId().toString()); notifyInfo.setPrice(order.getPrice()); notifyInfo.setSeatClass(SeatClass.getNameByCode(order.getSeatClass())); - notifyInfo.setStartingTime(order.getTravelTime().toString()); + notifyInfo.setStartTime(order.getTravelTime().toString()); // TODO: change to async message serivce // sendEmail(notifyInfo, headers); @@ -243,17 +263,20 @@ public Response preserve(OrderTicketsInfo oti, HttpHeaders headers) { return returnResponse; } - public Ticket dipatchSeat(Date date, String tripId, String startStationId, String endStataionId, int seatType, HttpHeaders httpHeaders) { + public Ticket dipatchSeat(String date, String tripId, String startStation, String endStataion, int seatType, int totalNum, List stationList, HttpHeaders httpHeaders) { Seat seatRequest = new Seat(); seatRequest.setTravelDate(date); seatRequest.setTrainNumber(tripId); - seatRequest.setStartStation(startStationId); - seatRequest.setDestStation(endStataionId); + seatRequest.setStartStation(startStation); + seatRequest.setDestStation(endStataion); seatRequest.setSeatType(seatType); + seatRequest.setTotalNum(totalNum); + seatRequest.setStations(stationList); HttpEntity requestEntityTicket = new HttpEntity(seatRequest, httpHeaders); + String seat_service_url = getServiceUrl("ts-seat-service"); ResponseEntity> reTicket = restTemplate.exchange( - "http://ts-seat-service:18898/api/v1/seatservice/seats", + seat_service_url + "/api/v1/seatservice/seats", HttpMethod.POST, requestEntityTicket, new ParameterizedTypeReference>() { @@ -263,13 +286,12 @@ public Ticket dipatchSeat(Date date, String tripId, String startStationId, Strin } public boolean sendEmail(NotifyInfo notifyInfo, HttpHeaders httpHeaders) { - PreserveServiceImpl.LOGGER.info("[Preserve Service][Send Email] send email to mq"); - try { String infoJson = JsonUtils.object2Json(notifyInfo); sendService.send(infoJson); + PreserveServiceImpl.LOGGER.info("[sendEmail][Send email to mq success]"); } catch (Exception e) { - PreserveServiceImpl.LOGGER.error("[Preserve Service] send email to mq error, exception is:" + e); + PreserveServiceImpl.LOGGER.error("[sendEmail][Send email to mq error] exception is:" + e); return false; } @@ -277,11 +299,12 @@ public boolean sendEmail(NotifyInfo notifyInfo, HttpHeaders httpHeaders) { } public User getAccount(String accountId, HttpHeaders httpHeaders) { - PreserveServiceImpl.LOGGER.info("[Cancel Order Service][Get Order By Id]"); + PreserveServiceImpl.LOGGER.info("[getAccount][Cancel Order Service][Get Order By Id]"); HttpEntity requestEntitySendEmail = new HttpEntity(httpHeaders); + String user_service_url = getServiceUrl("ts-user-service"); ResponseEntity> getAccount = restTemplate.exchange( - "http://ts-user-service:12342/api/v1/userservice/users/id/" + accountId, + user_service_url + "/api/v1/userservice/users/id/" + accountId, HttpMethod.GET, requestEntitySendEmail, new ParameterizedTypeReference>() { @@ -291,10 +314,11 @@ public User getAccount(String accountId, HttpHeaders httpHeaders) { } private Response addAssuranceForOrder(int assuranceType, String orderId, HttpHeaders httpHeaders) { - PreserveServiceImpl.LOGGER.info("[Preserve Service][Add Assurance For Order]"); + PreserveServiceImpl.LOGGER.info("[addAssuranceForOrder][Preserve Service][Add Assurance Type For Order]"); HttpEntity requestAddAssuranceResult = new HttpEntity(httpHeaders); + String assurance_service_url = getServiceUrl("ts-assurance-service"); ResponseEntity reAddAssuranceResult = restTemplate.exchange( - "http://ts-assurance-service:18888/api/v1/assuranceservice/assurances/" + assuranceType + "/" + orderId, + assurance_service_url + "/api/v1/assuranceservice/assurances/" + assuranceType + "/" + orderId, HttpMethod.GET, requestAddAssuranceResult, Response.class); @@ -303,12 +327,13 @@ private Response addAssuranceForOrder(int assuranceType, String orderId, HttpHea } private String queryForStationId(String stationName, HttpHeaders httpHeaders) { - PreserveServiceImpl.LOGGER.info("[Preserve Other Service][Get Station Name]"); + PreserveServiceImpl.LOGGER.info("[queryForStationId][Preserve Other Service][Get Station By Name]"); HttpEntity requestQueryForStationId = new HttpEntity(httpHeaders); + String station_service_url = getServiceUrl("ts-station-service"); ResponseEntity> reQueryForStationId = restTemplate.exchange( - "http://ts-station-service:12345/api/v1/stationservice/stations/id/" + stationName, + station_service_url + "/api/v1/stationservice/stations/id/" + stationName, HttpMethod.GET, requestQueryForStationId, new ParameterizedTypeReference>() { @@ -318,11 +343,12 @@ private String queryForStationId(String stationName, HttpHeaders httpHeaders) { } private Response checkSecurity(String accountId, HttpHeaders httpHeaders) { - PreserveServiceImpl.LOGGER.info("[Preserve Other Service][Check Security] Checking...."); + PreserveServiceImpl.LOGGER.info("[checkSecurity][Preserve Other Service][Check Account Security]"); HttpEntity requestCheckResult = new HttpEntity(httpHeaders); + String security_service_url = getServiceUrl("ts-security-service"); ResponseEntity reCheckResult = restTemplate.exchange( - "http://ts-security-service:11188/api/v1/securityservice/securityConfigs/" + accountId, + security_service_url + "/api/v1/securityservice/securityConfigs/" + accountId, HttpMethod.GET, requestCheckResult, Response.class); @@ -332,11 +358,12 @@ private Response checkSecurity(String accountId, HttpHeaders httpHeaders) { private Response getTripAllDetailInformation(TripAllDetailInfo gtdi, HttpHeaders httpHeaders) { - PreserveServiceImpl.LOGGER.info("[Preserve Other Service][Get Trip All Detail Information] Getting...."); + PreserveServiceImpl.LOGGER.info("[getTripAllDetailInformation][Preserve Other Service][Get Trip All Detail Information]"); HttpEntity requestGetTripAllDetailResult = new HttpEntity(gtdi, httpHeaders); + String travel_service_url = getServiceUrl("ts-travel-service"); ResponseEntity> reGetTripAllDetailResult = restTemplate.exchange( - "http://ts-travel-service:12346/api/v1/travelservice/trip_detail", + travel_service_url + "/api/v1/travelservice/trip_detail", HttpMethod.POST, requestGetTripAllDetailResult, new ParameterizedTypeReference>() { @@ -347,11 +374,12 @@ private Response getTripAllDetailInformation(TripAllDetailInfo gt private Response getContactsById(String contactsId, HttpHeaders httpHeaders) { - PreserveServiceImpl.LOGGER.info("[Preserve Other Service][Get Contacts By Id] Getting...."); + PreserveServiceImpl.LOGGER.info("[getContactsById][Preserve Other Service][Get Contacts By Id is]"); HttpEntity requestGetContactsResult = new HttpEntity(httpHeaders); + String contacts_service_url = getServiceUrl("ts-contacts-service"); ResponseEntity> reGetContactsResult = restTemplate.exchange( - "http://ts-contacts-service:12347/api/v1/contactservice/contacts/" + contactsId, + contacts_service_url + "/api/v1/contactservice/contacts/" + contactsId, HttpMethod.GET, requestGetContactsResult, new ParameterizedTypeReference>() { @@ -361,11 +389,12 @@ private Response getContactsById(String contactsId, HttpHeaders httpHe } private Response createOrder(Order coi, HttpHeaders httpHeaders) { - PreserveServiceImpl.LOGGER.info("[Preserve Other Service][Get Contacts By Id] Creating...."); + PreserveServiceImpl.LOGGER.info("[createOrder][Preserve Other Service][Get Contacts By Id]"); HttpEntity requestEntityCreateOrderResult = new HttpEntity(coi, httpHeaders); + String order_service_url = getServiceUrl("ts-order-service"); ResponseEntity> reCreateOrderResult = restTemplate.exchange( - "http://ts-order-service:12031/api/v1/orderservice/order", + order_service_url + "/api/v1/orderservice/order", HttpMethod.POST, requestEntityCreateOrderResult, new ParameterizedTypeReference>() { @@ -375,11 +404,12 @@ private Response createOrder(Order coi, HttpHeaders httpHeaders) { } private Response createFoodOrder(FoodOrder afi, HttpHeaders httpHeaders) { - PreserveServiceImpl.LOGGER.info("[Preserve Service][Add food Order] Creating...."); + PreserveServiceImpl.LOGGER.info("[createFoodOrder][Preserve Service][Add Preserve food Order]"); HttpEntity requestEntityAddFoodOrderResult = new HttpEntity(afi, httpHeaders); + String food_service_url = getServiceUrl("ts-food-service"); ResponseEntity reAddFoodOrderResult = restTemplate.exchange( - "http://ts-food-service:18856/api/v1/foodservice/orders", + food_service_url + "/api/v1/foodservice/orders", HttpMethod.POST, requestEntityAddFoodOrderResult, Response.class); @@ -388,11 +418,12 @@ private Response createFoodOrder(FoodOrder afi, HttpHeaders httpHeaders) { } private Response createConsign(Consign cr, HttpHeaders httpHeaders) { - PreserveServiceImpl.LOGGER.info("[Preserve Service][Add Condign] Creating...."); + PreserveServiceImpl.LOGGER.info("[createConsign][Preserve Service][Add Condign"); HttpEntity requestEntityResultForTravel = new HttpEntity(cr, httpHeaders); + String consign_service_url = getServiceUrl("ts-consign-service"); ResponseEntity reResultForTravel = restTemplate.exchange( - "http://ts-consign-service:16111/api/v1/consignservice/consigns", + consign_service_url + "/api/v1/consignservice/consigns", HttpMethod.POST, requestEntityResultForTravel, Response.class); diff --git a/ts-preserve-service/src/main/resources/application.yml b/ts-preserve-service/src/main/resources/application.yml index 192f46007..f9b72eccc 100644 --- a/ts-preserve-service/src/main/resources/application.yml +++ b/ts-preserve-service/src/main/resources/application.yml @@ -12,11 +12,15 @@ server: port: 14568 # HTTP (Tomcat) port spring: + cloud: + nacos: + discovery: + server-addr: ${NACOS_ADDRS:nacos-0.nacos-headless.default.svc.cluster.local,nacos-1.nacos-headless.default.svc.cluster.local,nacos-2.nacos-headless.default.svc.cluster.local} application: name: ts-preserve-service rabbitmq: host: ${rabbitmq_host:localhost} - port: ${rabbitmq_port:5672} + port: 5672 swagger: - controllerPackage: preserve.controller \ No newline at end of file + controllerPackage: preserve.controller diff --git a/ts-preserve-service/src/test/java/preserve/controller/PreserveControllerTest.java b/ts-preserve-service/src/test/java/preserve/controller/PreserveControllerTest.java index f28adbeb4..6d0e280a3 100644 --- a/ts-preserve-service/src/test/java/preserve/controller/PreserveControllerTest.java +++ b/ts-preserve-service/src/test/java/preserve/controller/PreserveControllerTest.java @@ -16,7 +16,7 @@ import org.springframework.test.web.servlet.request.MockMvcRequestBuilders; import org.springframework.test.web.servlet.result.MockMvcResultMatchers; import org.springframework.test.web.servlet.setup.MockMvcBuilders; -import preserve.entity.OrderTicketsInfo; +import edu.fudan.common.entity.OrderTicketsInfo; import preserve.service.PreserveService; @RunWith(JUnit4.class) diff --git a/ts-preserve-service/src/test/java/preserve/service/PreserveServiceImplTest.java b/ts-preserve-service/src/test/java/preserve/service/PreserveServiceImplTest.java index 5fbee3490..e7d05c500 100644 --- a/ts-preserve-service/src/test/java/preserve/service/PreserveServiceImplTest.java +++ b/ts-preserve-service/src/test/java/preserve/service/PreserveServiceImplTest.java @@ -1,6 +1,7 @@ package preserve.service; import edu.fudan.common.util.Response; +import edu.fudan.common.util.StringUtils; import org.junit.Assert; import org.junit.Before; import org.junit.Test; @@ -13,7 +14,7 @@ import org.springframework.core.ParameterizedTypeReference; import org.springframework.http.*; import org.springframework.web.client.RestTemplate; -import preserve.entity.*; +import edu.fudan.common.entity.*; import java.util.Date; import java.util.HashMap; @@ -43,7 +44,7 @@ public void testPreserve() { .contactsId(UUID.randomUUID().toString()) .from("from_station") .to("to_station") - .date(new Date()) + .date(StringUtils.Date2String(new Date())) .handleDate("handle_date") .tripId("G1255") .seatType(2) @@ -85,7 +86,7 @@ public void testPreserve() { //response for getTripAllDetailInformation() TripResponse tripResponse = new TripResponse(); tripResponse.setConfortClass(1); - tripResponse.setStartingTime(new Date()); + tripResponse.setStartTime(StringUtils.Date2String(new Date())); TripAllDetail tripAllDetail = new TripAllDetail(true, "message", tripResponse, new Trip()); Response response3 = new Response<>(1, null, tripAllDetail); ResponseEntity> re3 = new ResponseEntity<>(response3, HttpStatus.OK); @@ -108,9 +109,9 @@ public void testPreserve() { //response for createOrder() Order order = new Order(); - order.setId(UUID.randomUUID()); - order.setAccountId(UUID.randomUUID()); - order.setTravelDate(new Date()); + order.setId(UUID.randomUUID().toString()); + order.setAccountId(UUID.randomUUID().toString()); + order.setTravelDate(StringUtils.Date2String(new Date())); order.setFrom("from_station"); order.setTo("to_station"); Response response7 = new Response<>(1, null, order); @@ -137,7 +138,7 @@ public void testPreserve() { @Test public void testDipatchSeat() { long mills = System.currentTimeMillis(); - Seat seatRequest = new Seat(new Date(mills), "G1234", "start_station", "dest_station", 2); + Seat seatRequest = new Seat(StringUtils.Date2String(new Date()), "G1234", "start_station", "dest_station", 2, 100, null); HttpEntity requestEntityTicket = new HttpEntity(seatRequest, headers); Response response = new Response<>(); ResponseEntity> reTicket = new ResponseEntity<>(response, HttpStatus.OK); @@ -147,7 +148,7 @@ public void testDipatchSeat() { requestEntityTicket, new ParameterizedTypeReference>() { })).thenReturn(reTicket); - Ticket result = preserveServiceImpl.dipatchSeat(new Date(mills), "G1234", "start_station", "dest_station", 2, headers); + Ticket result = preserveServiceImpl.dipatchSeat(StringUtils.Date2String(new Date()), "G1234", "start_station", "dest_station", 2, 100, null, headers); Assert.assertNull(result); } diff --git a/ts-price-service/pom.xml b/ts-price-service/pom.xml index 584d4b48c..a31d5eedf 100644 --- a/ts-price-service/pom.xml +++ b/ts-price-service/pom.xml @@ -15,7 +15,7 @@ org.services ts-service 0.1.0 - ../ + ../pom.xml @@ -24,17 +24,46 @@ - - org.springframework.boot - spring-boot-starter-data-mongodb - org.services ts-common 0.1.0 - - + + org.hibernate.javax.persistence + hibernate-jpa-2.1-api + 1.0.0.Final + compile + + + org.hibernate + hibernate-core + + + mysql + mysql-connector-java + runtime + + + mysql + mysql-connector-java + + + org.springframework.boot + spring-boot-starter-data-jpa + + + org.springframework.data + spring-data-commons + + + org.springframework.cloud + spring-cloud-commons + + + jakarta.validation + jakarta.validation-api + diff --git a/ts-price-service/src/main/java/price/PriceApplication.java b/ts-price-service/src/main/java/price/PriceApplication.java index b899dd66f..2d02a6114 100644 --- a/ts-price-service/src/main/java/price/PriceApplication.java +++ b/ts-price-service/src/main/java/price/PriceApplication.java @@ -3,6 +3,8 @@ import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.boot.web.client.RestTemplateBuilder; +import org.springframework.cloud.client.discovery.EnableDiscoveryClient; +import org.springframework.cloud.client.loadbalancer.LoadBalanced; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.EnableAspectJAutoProxy; import org.springframework.integration.annotation.IntegrationComponentScan; @@ -18,12 +20,14 @@ @EnableAsync @IntegrationComponentScan @EnableSwagger2 +@EnableDiscoveryClient public class PriceApplication { public static void main(String[] args) { SpringApplication.run(PriceApplication.class, args); } + @LoadBalanced @Bean public RestTemplate restTemplate(RestTemplateBuilder builder) { return builder.build(); diff --git a/ts-price-service/src/main/java/price/controller/PriceController.java b/ts-price-service/src/main/java/price/controller/PriceController.java index b73ba61c7..e83235207 100644 --- a/ts-price-service/src/main/java/price/controller/PriceController.java +++ b/ts-price-service/src/main/java/price/controller/PriceController.java @@ -10,6 +10,10 @@ import org.springframework.web.bind.annotation.*; import price.entity.PriceConfig; import price.service.PriceService; + +import java.util.List; +import java.util.Map; + import static org.springframework.http.ResponseEntity.ok; /** @@ -32,32 +36,39 @@ public String home() { @GetMapping(value = "/prices/{routeId}/{trainType}") public HttpEntity query(@PathVariable String routeId, @PathVariable String trainType, @RequestHeader HttpHeaders headers) { - PriceController.LOGGER.info("Query price, RouteId: {}, TrainType: {}",routeId,trainType); + PriceController.LOGGER.info("[findByRouteIdAndTrainType][Query price][RouteId: {}, TrainType: {}]",routeId,trainType); return ok(service.findByRouteIdAndTrainType(routeId, trainType, headers)); } + @PostMapping(value = "/prices/byRouteIdsAndTrainTypes") + public HttpEntity query(@RequestBody List ridsAndTts, + @RequestHeader HttpHeaders headers) { + PriceController.LOGGER.info("[findByRouteIdAndTrainType][Query price][routeId and Train Type: {}]", ridsAndTts); + return ok(service.findByRouteIdsAndTrainTypes(ridsAndTts, headers)); + } + @GetMapping(value = "/prices") public HttpEntity queryAll(@RequestHeader HttpHeaders headers) { - PriceController.LOGGER.info("Query all prices"); + PriceController.LOGGER.info("[findAllPriceConfig][Query all prices]"); return ok(service.findAllPriceConfig(headers)); } @PostMapping(value = "/prices") public HttpEntity create(@RequestBody PriceConfig info, @RequestHeader HttpHeaders headers) { - PriceController.LOGGER.info("Create price, RouteId: {}, TrainType: {}",info.getRouteId(),info.getTrainType()); + PriceController.LOGGER.info("[createNewPriceConfig][Create price][RouteId: {}, TrainType: {}]",info.getRouteId(),info.getTrainType()); return new ResponseEntity<>(service.createNewPriceConfig(info, headers), HttpStatus.CREATED); } - @DeleteMapping(value = "/prices") - public HttpEntity delete(@RequestBody PriceConfig info, @RequestHeader HttpHeaders headers) { - PriceController.LOGGER.info("Delete price, PriceConfigId: {}",info.getId()); - return ok(service.deletePriceConfig(info, headers)); + @DeleteMapping(value = "/prices/{pricesId}") + public HttpEntity delete(@PathVariable String pricesId, @RequestHeader HttpHeaders headers) { + PriceController.LOGGER.info("[deletePriceConfig][Delete price][PriceConfigId: {}]",pricesId); + return ok(service.deletePriceConfig(pricesId, headers)); } @PutMapping(value = "/prices") public HttpEntity update(@RequestBody PriceConfig info, @RequestHeader HttpHeaders headers) { - PriceController.LOGGER.info("Update price, PriceConfigId: {}",info.getId()); + PriceController.LOGGER.info("[updatePriceConfig][Update price][PriceConfigId: {}]",info.getId()); return ok(service.updatePriceConfig(info, headers)); } } diff --git a/ts-price-service/src/main/java/price/entity/PriceConfig.java b/ts-price-service/src/main/java/price/entity/PriceConfig.java index 59ca8e695..45d7a25f5 100644 --- a/ts-price-service/src/main/java/price/entity/PriceConfig.java +++ b/ts-price-service/src/main/java/price/entity/PriceConfig.java @@ -1,9 +1,11 @@ package price.entity; +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import lombok.AllArgsConstructor; import lombok.Data; -import org.springframework.data.annotation.Id; -import org.springframework.data.mongodb.core.mapping.Document; + +import javax.persistence.*; + import java.util.UUID; /** @@ -11,14 +13,19 @@ */ @Data @AllArgsConstructor -@Document(collection="price_config") +@Entity +@JsonIgnoreProperties(ignoreUnknown = true) +@Table(indexes = {@Index(name = "route_type_idx", columnList = "train_type, route_id", unique = true)}) public class PriceConfig { @Id - private UUID id; + @Column(length = 36) + private String id; + @Column(name="train_type") private String trainType; + @Column(name="route_id", length = 36) private String routeId; private double basicPriceRate; @@ -27,6 +34,7 @@ public class PriceConfig { public PriceConfig() { //Empty Constructor + this.id = UUID.randomUUID().toString(); } } diff --git a/ts-price-service/src/main/java/price/init/InitData.java b/ts-price-service/src/main/java/price/init/InitData.java index 4fef95032..84eb0ed95 100644 --- a/ts-price-service/src/main/java/price/init/InitData.java +++ b/ts-price-service/src/main/java/price/init/InitData.java @@ -24,69 +24,69 @@ public class InitData implements CommandLineRunner { @Override public void run(String... args)throws Exception{ PriceConfig priceConfig = new PriceConfig(); - priceConfig.setId(UUID.fromString("6d20b8cb-039c-474c-ae25-b6177ea41152")); + priceConfig.setId(UUID.fromString("6d20b8cb-039c-474c-ae25-b6177ea41152").toString()); priceConfig.setRouteId("92708982-77af-4318-be25-57ccb0ff69ad"); priceConfig.setTrainType(gaoTieOne); priceConfig.setBasicPriceRate(0.38); priceConfig.setFirstClassPriceRate(1.0); service.createNewPriceConfig(priceConfig, null); - priceConfig.setId(UUID.fromString("c5679b7e-4a54-4f52-9939-1ae86ba16fa7")); + priceConfig.setId(UUID.fromString("c5679b7e-4a54-4f52-9939-1ae86ba16fa7").toString()); priceConfig.setRouteId("aefcef3f-3f42-46e8-afd7-6cb2a928bd3d"); priceConfig.setTrainType(gaoTieOne); priceConfig.setBasicPriceRate(0.5); priceConfig.setFirstClassPriceRate(1.0); service.createNewPriceConfig(priceConfig, null); - priceConfig.setId(UUID.fromString("719287d6-d3e7-4b54-9a92-71d039748b22")); + priceConfig.setId(UUID.fromString("719287d6-d3e7-4b54-9a92-71d039748b22").toString()); priceConfig.setRouteId("a3f256c1-0e43-4f7d-9c21-121bf258101f"); priceConfig.setTrainType(gaoTieOne); priceConfig.setBasicPriceRate(0.7); priceConfig.setFirstClassPriceRate(1.0); service.createNewPriceConfig(priceConfig, null); - priceConfig.setId(UUID.fromString("7de18cf8-bb17-4bb2-aeb4-85d8176d3a93")); + priceConfig.setId(UUID.fromString("7de18cf8-bb17-4bb2-aeb4-85d8176d3a93").toString()); priceConfig.setRouteId("084837bb-53c8-4438-87c8-0321a4d09917"); priceConfig.setTrainType("GaoTieTwo"); priceConfig.setBasicPriceRate(0.6); priceConfig.setFirstClassPriceRate(1.0); service.createNewPriceConfig(priceConfig, null); - priceConfig.setId(UUID.fromString("d5c4523a-827c-468c-95be-e9024a40572e")); + priceConfig.setId(UUID.fromString("d5c4523a-827c-468c-95be-e9024a40572e").toString()); priceConfig.setRouteId("f3d4d4ef-693b-4456-8eed-59c0d717dd08"); priceConfig.setTrainType("DongCheOne"); priceConfig.setBasicPriceRate(0.45); priceConfig.setFirstClassPriceRate(1.0); service.createNewPriceConfig(priceConfig, null); - priceConfig.setId(UUID.fromString("b90a6ad7-ffad-4624-9655-48e9e185fa6c")); + priceConfig.setId(UUID.fromString("b90a6ad7-ffad-4624-9655-48e9e185fa6c").toString()); priceConfig.setRouteId("0b23bd3e-876a-4af3-b920-c50a90c90b04"); priceConfig.setTrainType(zhiDa); priceConfig.setBasicPriceRate(0.35); priceConfig.setFirstClassPriceRate(1.0); service.createNewPriceConfig(priceConfig, null); - priceConfig.setId(UUID.fromString("8fb01829-393f-4af4-9e96-f72866f94d14")); + priceConfig.setId(UUID.fromString("8fb01829-393f-4af4-9e96-f72866f94d14").toString()); priceConfig.setRouteId("9fc9c261-3263-4bfa-82f8-bb44e06b2f52"); priceConfig.setTrainType(zhiDa); priceConfig.setBasicPriceRate(0.35); priceConfig.setFirstClassPriceRate(1.0); service.createNewPriceConfig(priceConfig, null); - priceConfig.setId(UUID.fromString("8b059dc5-01a2-4f8f-8f94-6c886b38bb34")); + priceConfig.setId(UUID.fromString("8b059dc5-01a2-4f8f-8f94-6c886b38bb34").toString()); priceConfig.setRouteId("d693a2c5-ef87-4a3c-bef8-600b43f62c68"); priceConfig.setTrainType(zhiDa); priceConfig.setBasicPriceRate(0.32); service.createNewPriceConfig(priceConfig, null); - priceConfig.setId(UUID.fromString("dd0e572e-7443-420c-8280-7d8215636069")); + priceConfig.setId(UUID.fromString("dd0e572e-7443-420c-8280-7d8215636069").toString()); priceConfig.setRouteId("20eb7122-3a11-423f-b10a-be0dc5bce7db"); priceConfig.setTrainType("TeKuai"); priceConfig.setBasicPriceRate(0.30); priceConfig.setFirstClassPriceRate(1.0); service.createNewPriceConfig(priceConfig, null); - priceConfig.setId(UUID.fromString("0eb474c9-f8be-4119-8681-eb538a404a6a")); + priceConfig.setId(UUID.fromString("0eb474c9-f8be-4119-8681-eb538a404a6a").toString()); priceConfig.setRouteId("1367db1f-461e-4ab7-87ad-2bcc05fd9cb7"); priceConfig.setTrainType("KuaiSu"); priceConfig.setBasicPriceRate(0.2); diff --git a/ts-price-service/src/main/java/price/repository/PriceConfigRepository.java b/ts-price-service/src/main/java/price/repository/PriceConfigRepository.java index cbd707791..489a5d886 100644 --- a/ts-price-service/src/main/java/price/repository/PriceConfigRepository.java +++ b/ts-price-service/src/main/java/price/repository/PriceConfigRepository.java @@ -1,24 +1,26 @@ package price.repository; -import org.springframework.data.mongodb.repository.MongoRepository; -import org.springframework.data.mongodb.repository.Query; +import org.springframework.data.jpa.repository.Query; +import org.springframework.data.repository.CrudRepository; import org.springframework.stereotype.Repository; import price.entity.PriceConfig; import java.util.List; -import java.util.UUID; +import java.util.Optional; /** * @author fdse */ @Repository -public interface PriceConfigRepository extends MongoRepository { +public interface PriceConfigRepository extends CrudRepository { - @Query("{ 'id': ?0 }") - PriceConfig findById(UUID id); + @Override + Optional findById(String id); - @Query("{ 'routeId': ?0 , 'trainType': ?1 }") PriceConfig findByRouteIdAndTrainType(String routeId,String trainType); + @Query(value="SELECT * FROM price_config WHERE route_id IN ?1 AND train_type IN ?2", nativeQuery = true) + List findByRouteIdsAndTrainTypes(List routeIds, List trainTypes); + @Override List findAll(); diff --git a/ts-price-service/src/main/java/price/service/PriceService.java b/ts-price-service/src/main/java/price/service/PriceService.java index 007e6c651..54d1c46a3 100644 --- a/ts-price-service/src/main/java/price/service/PriceService.java +++ b/ts-price-service/src/main/java/price/service/PriceService.java @@ -5,6 +5,9 @@ import price.entity.PriceConfig; +import java.util.List; +import java.util.Map; + /** * @author fdse @@ -15,11 +18,13 @@ public interface PriceService { PriceConfig findById(String id, HttpHeaders headers); + Response findByRouteIdsAndTrainTypes(List ridsAndTts, HttpHeaders headers); + Response findByRouteIdAndTrainType(String routeId, String trainType, HttpHeaders headers); Response findAllPriceConfig(HttpHeaders headers); - Response deletePriceConfig(PriceConfig c, HttpHeaders headers); + Response deletePriceConfig(String pcId, HttpHeaders headers); Response updatePriceConfig(PriceConfig c, HttpHeaders headers); diff --git a/ts-price-service/src/main/java/price/service/PriceServiceImpl.java b/ts-price-service/src/main/java/price/service/PriceServiceImpl.java index e70f495f6..56de8eea5 100644 --- a/ts-price-service/src/main/java/price/service/PriceServiceImpl.java +++ b/ts-price-service/src/main/java/price/service/PriceServiceImpl.java @@ -9,9 +9,7 @@ import price.entity.PriceConfig; import price.repository.PriceConfigRepository; -import java.util.ArrayList; -import java.util.List; -import java.util.UUID; +import java.util.*; /** @@ -20,7 +18,7 @@ @Service public class PriceServiceImpl implements PriceService { - @Autowired + @Autowired(required=true) private PriceConfigRepository priceConfigRepository; private static final Logger LOGGER = LoggerFactory.getLogger(PriceServiceImpl.class); @@ -29,12 +27,12 @@ public class PriceServiceImpl implements PriceService { @Override public Response createNewPriceConfig(PriceConfig createAndModifyPriceConfig, HttpHeaders headers) { - PriceServiceImpl.LOGGER.info("[Create New Price Config]"); + PriceServiceImpl.LOGGER.info("[createNewPriceConfig]"); PriceConfig priceConfig = null; // create if (createAndModifyPriceConfig.getId() == null || createAndModifyPriceConfig.getId().toString().length() < 10) { priceConfig = new PriceConfig(); - priceConfig.setId(UUID.randomUUID()); + priceConfig.setId(UUID.randomUUID().toString()); priceConfig.setBasicPriceRate(createAndModifyPriceConfig.getBasicPriceRate()); priceConfig.setFirstClassPriceRate(createAndModifyPriceConfig.getFirstClassPriceRate()); priceConfig.setRouteId(createAndModifyPriceConfig.getRouteId()); @@ -42,10 +40,12 @@ public Response createNewPriceConfig(PriceConfig createAndModifyPriceConfig, Htt priceConfigRepository.save(priceConfig); } else { // modify - priceConfig = priceConfigRepository.findById(createAndModifyPriceConfig.getId()); - if (priceConfig == null) { + Optional op = priceConfigRepository.findById(createAndModifyPriceConfig.getId()); + if (!op.isPresent()) { priceConfig = new PriceConfig(); priceConfig.setId(createAndModifyPriceConfig.getId()); + }else{ + priceConfig = op.get(); } priceConfig.setBasicPriceRate(createAndModifyPriceConfig.getBasicPriceRate()); priceConfig.setFirstClassPriceRate(createAndModifyPriceConfig.getFirstClassPriceRate()); @@ -58,24 +58,53 @@ public Response createNewPriceConfig(PriceConfig createAndModifyPriceConfig, Htt @Override public PriceConfig findById(String id, HttpHeaders headers) { - PriceServiceImpl.LOGGER.info("[Find By Id] ID: {}", id); - return priceConfigRepository.findById(UUID.fromString(id)); + PriceServiceImpl.LOGGER.info("[findById][ID: {}]", id); + Optional op = priceConfigRepository.findById(UUID.fromString(id).toString()); + if(op.isPresent()){ + return op.get(); + } + return null; } @Override public Response findByRouteIdAndTrainType(String routeId, String trainType, HttpHeaders headers) { - PriceServiceImpl.LOGGER.info("[Find By Route And Train Type] Rote: {} Train Type: {}", routeId, trainType); + PriceServiceImpl.LOGGER.info("[findByRouteIdAndTrainType][Route: {} , Train Type: {}]", routeId, trainType); PriceConfig priceConfig = priceConfigRepository.findByRouteIdAndTrainType(routeId, trainType); - PriceServiceImpl.LOGGER.info("[Find By Route Id And Train Type]"); + //PriceServiceImpl.LOGGER.info("[findByRouteIdAndTrainType]"); if (priceConfig == null) { - PriceServiceImpl.LOGGER.warn("Find by route and train type warn. PricrConfig not found, RouteId: {}, TrainType: {}",routeId,trainType); + PriceServiceImpl.LOGGER.warn("[findByRouteIdAndTrainType][Find by route and train type warn][PricrConfig not found][RouteId: {}, TrainType: {}]",routeId,trainType); return new Response<>(0, noThatConfig, null); } else { return new Response<>(1, "Success", priceConfig); } } + @Override + public Response findByRouteIdsAndTrainTypes(List ridsAndTts, HttpHeaders headers){ + List routeIds = new ArrayList<>(); + List trainTypes = new ArrayList<>(); + for(String rts: ridsAndTts){ + List r_t = Arrays.asList(rts.split(":")); + routeIds.add(r_t.get(0)); + trainTypes.add(r_t.get(1)); + } + List pcs = priceConfigRepository.findByRouteIdsAndTrainTypes(routeIds, trainTypes); + Map pcMap = new HashMap<>(); + for(PriceConfig pc: pcs){ + String key = pc.getRouteId() + ":" + pc.getTrainType(); + if(ridsAndTts.contains(key)){ + pcMap.put(key, pc); + } + } + if (pcMap == null) { + PriceServiceImpl.LOGGER.warn("[findByRouteIdsAndTrainTypes][Find by routes and train types warn][PricrConfig not found][RouteIds: {}, TrainTypes: {}]",routeIds,trainTypes); + return new Response<>(0, noThatConfig, null); + } else { + return new Response<>(1, "Success", pcMap); + } + } + @Override public Response findAllPriceConfig(HttpHeaders headers) { @@ -85,7 +114,7 @@ public Response findAllPriceConfig(HttpHeaders headers) { } if (!list.isEmpty()) { - PriceServiceImpl.LOGGER.warn("Find all price config warn,{}","No Content"); + PriceServiceImpl.LOGGER.warn("[findAllPriceConfig][Find all price config warn][{}]","No Content"); return new Response<>(1, "Success", list); } else { return new Response<>(0, "No price config", null); @@ -94,18 +123,13 @@ public Response findAllPriceConfig(HttpHeaders headers) { } @Override - public Response deletePriceConfig(PriceConfig c, HttpHeaders headers) { - PriceConfig priceConfig = priceConfigRepository.findById(c.getId()); - if (priceConfig == null) { - PriceServiceImpl.LOGGER.error("Delete price config error. Price config not found, PriceConfigId: {}",c.getId()); + public Response deletePriceConfig(String pcId, HttpHeaders headers) { + Optional op = priceConfigRepository.findById(pcId); + if (!op.isPresent()) { + PriceServiceImpl.LOGGER.error("[deletePriceConfig][Delete price config error][Price config not found][PriceConfigId: {}]",pcId); return new Response<>(0, noThatConfig, null); } else { - PriceConfig pc = new PriceConfig(); - pc.setId(c.getId()); - pc.setRouteId(c.getRouteId()); - pc.setTrainType(c.getTrainType()); - pc.setBasicPriceRate(c.getBasicPriceRate()); - pc.setFirstClassPriceRate(c.getFirstClassPriceRate()); + PriceConfig pc = op.get(); priceConfigRepository.delete(pc); return new Response<>(1, "Delete success", pc); } @@ -113,11 +137,12 @@ public Response deletePriceConfig(PriceConfig c, HttpHeaders headers) { @Override public Response updatePriceConfig(PriceConfig c, HttpHeaders headers) { - PriceConfig priceConfig = priceConfigRepository.findById(c.getId()); - if (priceConfig == null) { - PriceServiceImpl.LOGGER.error("Update price config error. Price config not found, PriceConfigId: {}",c.getId()); + Optional op = priceConfigRepository.findById(c.getId()); + if (!op.isPresent()) { + PriceServiceImpl.LOGGER.error("[updatePriceConfig][Update price config error][Price config not found][PriceConfigId: {}]",c.getId()); return new Response<>(0, noThatConfig, null); } else { + PriceConfig priceConfig = op.get(); priceConfig.setId(c.getId()); priceConfig.setBasicPriceRate(c.getBasicPriceRate()); priceConfig.setFirstClassPriceRate(c.getFirstClassPriceRate()); diff --git a/ts-price-service/src/main/resources/application.yml b/ts-price-service/src/main/resources/application.yml index b1d23d57e..b2e2aa757 100644 --- a/ts-price-service/src/main/resources/application.yml +++ b/ts-price-service/src/main/resources/application.yml @@ -1,13 +1,21 @@ spring: + cloud: + nacos: + discovery: + server-addr: ${NACOS_ADDRS:127.0.0.1:8848} application: name: ts-price-service - data: - mongodb: - host: ts-price-mongo -# username: user -# password: ${MONGODB_PASSWORD} - database: ts - port: 27017 + datasource: + url: jdbc:mysql://${PRICE_MYSQL_HOST:10.176.122.1}:${PRICE_MYSQL_PORT:3306}/${PRICE_MYSQL_DATABASE:ts}?useSSL=false + username: ${PRICE_MYSQL_USER:root} + password: ${PRICE_MYSQL_PASSWORD:Abcd1234#} + driver-class-name: com.mysql.cj.jdbc.Driver + jpa: + hibernate: + ddl-auto: update + properties: + hibernate: + dialect: org.hibernate.dialect.MySQL5Dialect # HTTP Server diff --git a/ts-price-service/src/test/java/price/controller/PriceControllerTest.java b/ts-price-service/src/test/java/price/controller/PriceControllerTest.java index 70eadd9f8..37a386d41 100644 --- a/ts-price-service/src/test/java/price/controller/PriceControllerTest.java +++ b/ts-price-service/src/test/java/price/controller/PriceControllerTest.java @@ -75,7 +75,7 @@ public void testCreate() throws Exception { @Test public void testDelete() throws Exception { PriceConfig info = new PriceConfig(); - Mockito.when(service.deletePriceConfig(Mockito.any(PriceConfig.class), Mockito.any(HttpHeaders.class))).thenReturn(response); + Mockito.when(service.deletePriceConfig(Mockito.anyString(), Mockito.any(HttpHeaders.class))).thenReturn(response); String requestJson = JSONObject.toJSONString(info); String result = mockMvc.perform(MockMvcRequestBuilders.delete("/api/v1/priceservice/prices").contentType(MediaType.APPLICATION_JSON).content(requestJson)) .andExpect(MockMvcResultMatchers.status().isOk()) diff --git a/ts-price-service/src/test/java/price/service/PriceServiceImplTest.java b/ts-price-service/src/test/java/price/service/PriceServiceImplTest.java index 89e2c8f94..26bf180ee 100644 --- a/ts-price-service/src/test/java/price/service/PriceServiceImplTest.java +++ b/ts-price-service/src/test/java/price/service/PriceServiceImplTest.java @@ -44,8 +44,8 @@ public void testCreateNewPriceConfig1() { @Test public void testCreateNewPriceConfig2() { - PriceConfig createAndModifyPriceConfig = new PriceConfig(UUID.randomUUID(), "G", "G1255", 1.0, 2.0); - Mockito.when(priceConfigRepository.findById(Mockito.any(UUID.class))).thenReturn(null); + PriceConfig createAndModifyPriceConfig = new PriceConfig(UUID.randomUUID().toString(), "G", "G1255", 1.0, 2.0); + Mockito.when(priceConfigRepository.findById(Mockito.any(UUID.class).toString())).thenReturn(null); Mockito.when(priceConfigRepository.save(Mockito.any(PriceConfig.class))).thenReturn(null); Response result = priceServiceImpl.createNewPriceConfig(createAndModifyPriceConfig, headers); Assert.assertEquals(new Response<>(1, "Create success", createAndModifyPriceConfig), result); @@ -53,7 +53,7 @@ public void testCreateNewPriceConfig2() { @Test public void testFindById() { - Mockito.when(priceConfigRepository.findById(Mockito.any(UUID.class))).thenReturn(null); + Mockito.when(priceConfigRepository.findById(Mockito.any(UUID.class).toString())).thenReturn(null); PriceConfig result = priceServiceImpl.findById(UUID.randomUUID().toString(), headers); Assert.assertNull(result); } @@ -92,24 +92,24 @@ public void testFindAllPriceConfig2() { @Test public void testDeletePriceConfig1() { PriceConfig c = new PriceConfig(); - Mockito.when(priceConfigRepository.findById(Mockito.any(UUID.class))).thenReturn(null); - Response result = priceServiceImpl.deletePriceConfig(c, headers); + Mockito.when(priceConfigRepository.findById(Mockito.any(UUID.class).toString())).thenReturn(null); + Response result = priceServiceImpl.deletePriceConfig(c.getId(), headers); Assert.assertEquals(new Response<>(0, "No that config", null), result); } @Test public void testDeletePriceConfig2() { PriceConfig c = new PriceConfig(); - Mockito.when(priceConfigRepository.findById(Mockito.any(UUID.class))).thenReturn(c); + Mockito.when(priceConfigRepository.findById(Mockito.any(UUID.class).toString()).get()).thenReturn(c); Mockito.doNothing().doThrow(new RuntimeException()).when(priceConfigRepository).delete(Mockito.any(PriceConfig.class)); - Response result = priceServiceImpl.deletePriceConfig(c, headers); + Response result = priceServiceImpl.deletePriceConfig(c.getId(), headers); Assert.assertEquals(new Response<>(1, "Delete success", c), result); } @Test public void testUpdatePriceConfig1() { PriceConfig c = new PriceConfig(); - Mockito.when(priceConfigRepository.findById(Mockito.any(UUID.class))).thenReturn(null); + Mockito.when(priceConfigRepository.findById(Mockito.any(UUID.class).toString())).thenReturn(null); Response result = priceServiceImpl.updatePriceConfig(c, headers); Assert.assertEquals(new Response<>(0, "No that config", null), result); } @@ -117,7 +117,7 @@ public void testUpdatePriceConfig1() { @Test public void testUpdatePriceConfig2() { PriceConfig c = new PriceConfig(); - Mockito.when(priceConfigRepository.findById(Mockito.any(UUID.class))).thenReturn(c); + Mockito.when(priceConfigRepository.findById(Mockito.any(UUID.class).toString()).get()).thenReturn(c); Mockito.when(priceConfigRepository.save(Mockito.any(PriceConfig.class))).thenReturn(null); Response result = priceServiceImpl.updatePriceConfig(c, headers); Assert.assertEquals(new Response<>(1, "Update success", c), result); diff --git a/ts-rebook-service/pom.xml b/ts-rebook-service/pom.xml index 244c00764..96612f283 100644 --- a/ts-rebook-service/pom.xml +++ b/ts-rebook-service/pom.xml @@ -15,7 +15,7 @@ org.services ts-service 0.1.0 - ../ + ../pom.xml @@ -23,15 +23,16 @@ UTF-8 1.8 - org.services ts-common 0.1.0 - - + + jakarta.validation + jakarta.validation-api + diff --git a/ts-rebook-service/src/main/java/rebook/RebookApplication.java b/ts-rebook-service/src/main/java/rebook/RebookApplication.java index adae9dac3..4989cb9d3 100644 --- a/ts-rebook-service/src/main/java/rebook/RebookApplication.java +++ b/ts-rebook-service/src/main/java/rebook/RebookApplication.java @@ -3,6 +3,8 @@ import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.boot.web.client.RestTemplateBuilder; +import org.springframework.cloud.client.discovery.EnableDiscoveryClient; +import org.springframework.cloud.client.loadbalancer.LoadBalanced; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.EnableAspectJAutoProxy; import org.springframework.integration.annotation.IntegrationComponentScan; @@ -18,12 +20,14 @@ @EnableAsync @IntegrationComponentScan @EnableSwagger2 +@EnableDiscoveryClient public class RebookApplication { public static void main(String[] args) { SpringApplication.run(RebookApplication.class, args); } + @LoadBalanced @Bean public RestTemplate restTemplate(RestTemplateBuilder builder) { return builder.build(); diff --git a/ts-rebook-service/src/main/java/rebook/controller/RebookController.java b/ts-rebook-service/src/main/java/rebook/controller/RebookController.java index d5773645d..6e08b15c8 100644 --- a/ts-rebook-service/src/main/java/rebook/controller/RebookController.java +++ b/ts-rebook-service/src/main/java/rebook/controller/RebookController.java @@ -31,13 +31,13 @@ public String home() { @PostMapping(value = "/rebook/difference") public HttpEntity payDifference(@RequestBody RebookInfo info, @RequestHeader HttpHeaders headers) { - RebookController.LOGGER.info("Pay difference,OrderId: {}",info.getOrderId()); + RebookController.LOGGER.info("[payDifference][Pay difference][OrderId: {}]",info.getOrderId()); return ok(service.payDifference(info, headers)); } @PostMapping(value = "/rebook") public HttpEntity rebook(@RequestBody RebookInfo info, @RequestHeader HttpHeaders headers) { - RebookController.LOGGER.info("Rebook,OrderId: {} Old Trip Id: {} New Trip Id: {} Date: {} Seat Type: {}", info.getOrderId(), info.getOldTripId(), info.getTripId(), info.getDate(), info.getSeatType()); + RebookController.LOGGER.info("[rebook][Rebook][OrderId: {}, Old Trip Id: {}, New Trip Id: {}, Date: {}, Seat Type: {}]", info.getOrderId(), info.getOldTripId(), info.getTripId(), info.getDate(), info.getSeatType()); return ok(service.rebook(info, headers)); } diff --git a/ts-rebook-service/src/main/java/rebook/entity/Contacts.java b/ts-rebook-service/src/main/java/rebook/entity/Contacts.java deleted file mode 100644 index 71962b445..000000000 --- a/ts-rebook-service/src/main/java/rebook/entity/Contacts.java +++ /dev/null @@ -1,56 +0,0 @@ -package rebook.entity; - -import com.fasterxml.jackson.annotation.JsonIgnoreProperties; -import lombok.Data; - -import java.util.UUID; - -/** - * @author fdse - */ -@Data -@JsonIgnoreProperties(ignoreUnknown = true) -public class Contacts { - - private UUID id; - - private UUID accountId; - - private String name; - - private int documentType; - - private String documentNumber; - - private String phoneNumber; - - public Contacts() { - //Default Constructor - } - - @Override - public boolean equals(Object obj) { - if (this == obj) { - return true; - } - if (obj == null) { - return false; - } - if (getClass() != obj.getClass()) { - return false; - } - Contacts other = (Contacts) obj; - return name.equals(other.getName()) - && accountId .equals( other.getAccountId() ) - && documentNumber.equals(other.getDocumentNumber()) - && phoneNumber.equals(other.getPhoneNumber()) - && documentType == other.getDocumentType(); - } - - @Override - public int hashCode() { - int result = 17; - result = 31 * result + (id == null ? 0 : id.hashCode()); - return result; - } -} diff --git a/ts-rebook-service/src/main/java/rebook/entity/OrderStatus.java b/ts-rebook-service/src/main/java/rebook/entity/OrderStatus.java deleted file mode 100644 index 370843b9b..000000000 --- a/ts-rebook-service/src/main/java/rebook/entity/OrderStatus.java +++ /dev/null @@ -1,63 +0,0 @@ -package rebook.entity; - -/** - * @author fdse - */ -public enum OrderStatus { - - /** - * not paid - */ - NOTPAID (0,"Not Paid"), - /** - * paid and not collected - */ - PAID (1,"Paid & Not Collected"), - /** - * collected - */ - COLLECTED (2,"Collected"), - /** - * cancel and rebook - */ - CHANGE (3,"Cancel & Rebook"), - /** - * cancel - */ - CANCEL (4,"Cancel"), - /** - * refunded - */ - REFUNDS (5,"Refunded"), - /** - * used - */ - USED (6,"Used"); - - private int code; - private String name; - - OrderStatus(int code, String name){ - this.code = code; - this.name = name; - } - - public int getCode(){ - return code; - } - - public String getName() { - return name; - } - - public static String getNameByCode(int code){ - OrderStatus[] orderStatusSet = OrderStatus.values(); - for(OrderStatus orderStatus : orderStatusSet){ - if(orderStatus.getCode() == code){ - return orderStatus.getName(); - } - } - return orderStatusSet[0].getName(); - } - -} diff --git a/ts-rebook-service/src/main/java/rebook/entity/OrderTicketsInfo.java b/ts-rebook-service/src/main/java/rebook/entity/OrderTicketsInfo.java deleted file mode 100644 index 64e3e9894..000000000 --- a/ts-rebook-service/src/main/java/rebook/entity/OrderTicketsInfo.java +++ /dev/null @@ -1,33 +0,0 @@ -package rebook.entity; - -import lombok.Data; - -import java.util.Date; - -/** - * @author fdse - */ -@Data -public class OrderTicketsInfo { - - private String contactsId; - - private String tripId; - - private int seatType; - - private String loginToken; - - private String accountId; - - private Date date; - - private String from; - - private String to; - - public OrderTicketsInfo(){ - //Default Constructor - } - -} diff --git a/ts-rebook-service/src/main/java/rebook/entity/RebookInfo.java b/ts-rebook-service/src/main/java/rebook/entity/RebookInfo.java index 6cdc9d0b1..d43114a67 100644 --- a/ts-rebook-service/src/main/java/rebook/entity/RebookInfo.java +++ b/ts-rebook-service/src/main/java/rebook/entity/RebookInfo.java @@ -1,5 +1,6 @@ package rebook.entity; +import edu.fudan.common.util.StringUtils; import lombok.Data; import javax.validation.Valid; @@ -34,7 +35,7 @@ public class RebookInfo { @Valid @NotNull - private Date date; + private String date; public RebookInfo(){ //Default Constructor @@ -43,7 +44,7 @@ public RebookInfo(){ this.oldTripId = ""; this.tripId = ""; this.seatType = 0; - this.date = new Date(); + this.date = StringUtils.Date2String(new Date()); } } diff --git a/ts-rebook-service/src/main/java/rebook/entity/SeatClass.java b/ts-rebook-service/src/main/java/rebook/entity/SeatClass.java deleted file mode 100644 index 8ce04aabc..000000000 --- a/ts-rebook-service/src/main/java/rebook/entity/SeatClass.java +++ /dev/null @@ -1,70 +0,0 @@ -package rebook.entity; - -/** - * @author fdse - */ -public enum SeatClass { - - /** - * no seat - */ - NONE (0,"NoSeat"), - /** - * green seat - */ - BUSINESS (1,"GreenSeat"), - /** - * first class seat - */ - FIRSTCLASS (2,"FirstClassSeat"), - /** - * second class seat - */ - SECONDCLASS (3,"SecondClassSeat"), - /** - * hard seat - */ - HARDSEAT (4,"HardSeat"), - /** - * soft seat - */ - SOFTSEAT (5,"SoftSeat"), - /** - * hard bed - */ - HARDBED (6,"HardBed"), - /** - * soft bed - */ - SOFTBED (7,"SoftBed"), - /** - * high soft seat - */ - HIGHSOFTBED (8,"HighSoftSeat"); - - private int code; - private String name; - - SeatClass(int code, String name){ - this.code = code; - this.name = name; - } - - public int getCode(){ - return code; - } - - public String getName() { - return name; - } - - public static String getNameByCode(int code){ - SeatClass[] seatClassSet = SeatClass.values(); - for(SeatClass seatClass : seatClassSet){ - if(seatClass.getCode() == code){ - return seatClass.getName(); - } - } - return seatClassSet[0].getName(); - } -} diff --git a/ts-rebook-service/src/main/java/rebook/entity/Ticket.java b/ts-rebook-service/src/main/java/rebook/entity/Ticket.java deleted file mode 100644 index 6e64f2bc3..000000000 --- a/ts-rebook-service/src/main/java/rebook/entity/Ticket.java +++ /dev/null @@ -1,21 +0,0 @@ -package rebook.entity; - -import lombok.Data; - -/** - * @author fdse - */ -@Data -public class Ticket { - - private int seatNo; - - private String startStation; - - private String destStation; - - public Ticket(){ - //Default Constructor - } - -} diff --git a/ts-rebook-service/src/main/java/rebook/entity/Trip.java b/ts-rebook-service/src/main/java/rebook/entity/Trip.java deleted file mode 100644 index aa099aa7d..000000000 --- a/ts-rebook-service/src/main/java/rebook/entity/Trip.java +++ /dev/null @@ -1,50 +0,0 @@ -package rebook.entity; - -import lombok.Data; - -import java.util.Date; - -/** - * @author fdse - */ -@Data -public class Trip { - - private TripId tripId; - - private String trainTypeId; - - private String routeId; - - private String startingStationId; - - - private String stationsId; - - private String terminalStationId; - - private Date startingTime; - - private Date endTime; - - public Trip(TripId tripId, String trainTypeId, String startingStationId, String stationsId, String terminalStationId, Date startingTime, Date endTime) { - this.tripId = tripId; - this.trainTypeId = trainTypeId; - this.startingStationId = startingStationId; - this.stationsId = stationsId; - this.terminalStationId = terminalStationId; - this.startingTime = startingTime; - this.endTime = endTime; - } - - public Trip(TripId tripId, String trainTypeId, String routeId) { - this.tripId = tripId; - this.trainTypeId = trainTypeId; - this.routeId = routeId; - } - - public Trip(){ - //Default Constructor - } - -} diff --git a/ts-rebook-service/src/main/java/rebook/entity/TripAllDetail.java b/ts-rebook-service/src/main/java/rebook/entity/TripAllDetail.java deleted file mode 100644 index a31e93c05..000000000 --- a/ts-rebook-service/src/main/java/rebook/entity/TripAllDetail.java +++ /dev/null @@ -1,19 +0,0 @@ -package rebook.entity; - -import lombok.Data; - -/** - * @author fdse - */ -@Data -public class TripAllDetail { - - private TripResponse tripResponse; - - private Trip trip; - - public TripAllDetail() { - //Default Constructor - } - -} diff --git a/ts-rebook-service/src/main/java/rebook/entity/TripAllDetailInfo.java b/ts-rebook-service/src/main/java/rebook/entity/TripAllDetailInfo.java deleted file mode 100644 index ba55ee9f0..000000000 --- a/ts-rebook-service/src/main/java/rebook/entity/TripAllDetailInfo.java +++ /dev/null @@ -1,25 +0,0 @@ -package rebook.entity; - -import lombok.Data; - -import java.util.Date; - -/** - * @author fdse - */ -@Data -public class TripAllDetailInfo { - - private String tripId; - - private Date travelDate; - - private String from; - - private String to; - - public TripAllDetailInfo() { - //Default Constructor - } - -} diff --git a/ts-rebook-service/src/main/java/rebook/entity/TripResponse.java b/ts-rebook-service/src/main/java/rebook/entity/TripResponse.java deleted file mode 100644 index b8d1fd901..000000000 --- a/ts-rebook-service/src/main/java/rebook/entity/TripResponse.java +++ /dev/null @@ -1,73 +0,0 @@ -package rebook.entity; - -import lombok.Data; - -import javax.validation.Valid; -import javax.validation.constraints.NotNull; -import java.util.Date; - -/** - * @author fdse - */ -@Data -public class TripResponse { - @Valid - private TripId tripId; - - @Valid - @NotNull - private String trainTypeId; - - @Valid - @NotNull - private String startingStation; - - @Valid - @NotNull - private String terminalStation; - - @Valid - @NotNull - private Date startingTime; - - @Valid - @NotNull - private Date endTime; - - /** - * the number of economy seat - */ - @Valid - @NotNull - private int economyClass; - - /** - * the number of confort seat - */ - @Valid - @NotNull - private int confortClass; - - @Valid - @NotNull - private String priceForEconomyClass; - - @Valid - @NotNull - private String priceForConfortClass; - - public TripResponse(){ - //Default Constructor - this.trainTypeId = ""; - this.startingStation = ""; - this.terminalStation = ""; - this.startingTime = new Date(); - this.endTime = new Date(); - this.economyClass = 0; - this.confortClass = 0; - this.priceForEconomyClass = ""; - this.priceForConfortClass = ""; - - } - -} diff --git a/ts-rebook-service/src/main/java/rebook/service/RebookServiceImpl.java b/ts-rebook-service/src/main/java/rebook/service/RebookServiceImpl.java index efc78de9d..2d1d8befd 100644 --- a/ts-rebook-service/src/main/java/rebook/service/RebookServiceImpl.java +++ b/ts-rebook-service/src/main/java/rebook/service/RebookServiceImpl.java @@ -1,9 +1,17 @@ package rebook.service; +import edu.fudan.common.entity.Trip; +import edu.fudan.common.entity.TripAllDetail; +import edu.fudan.common.entity.TripAllDetailInfo; +import edu.fudan.common.entity.TripResponse; +import edu.fudan.common.util.JsonUtils; import edu.fudan.common.util.Response; +import edu.fudan.common.util.StringUtils; +import org.apache.tomcat.jni.Time; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.cloud.client.discovery.DiscoveryClient; import org.springframework.core.ParameterizedTypeReference; import org.springframework.http.HttpEntity; import org.springframework.http.HttpHeaders; @@ -11,12 +19,13 @@ import org.springframework.http.ResponseEntity; import org.springframework.stereotype.Service; import org.springframework.web.client.RestTemplate; +import edu.fudan.common.entity.*; import rebook.entity.*; -import rebook.entity.RebookInfo; import java.math.BigDecimal; import java.util.Calendar; import java.util.Date; +import java.util.List; /** * @author fdse @@ -26,9 +35,15 @@ public class RebookServiceImpl implements RebookService { @Autowired private RestTemplate restTemplate; + @Autowired + private DiscoveryClient discoveryClient; private static final Logger LOGGER = LoggerFactory.getLogger(RebookServiceImpl.class); + private String getServiceUrl(String serviceName) { + return "http://" + serviceName; + } + @Override public Response rebook(RebookInfo info, HttpHeaders httpHeaders) { @@ -36,59 +51,59 @@ public Response rebook(RebookInfo info, HttpHeaders httpHeaders) { if (queryOrderResult.getStatus() == 1) { if (queryOrderResult.getData().getStatus() != 1) { - RebookServiceImpl.LOGGER.warn("Rebook warn.Order not suitable to rebook,OrderId: {}",info.getOrderId()); + RebookServiceImpl.LOGGER.warn("[rebook][Rebook warn][Order not suitable to rebook][OrderId: {}]",info.getOrderId()); return new Response<>(0, "you order not suitable to rebook!", null); } } else { - RebookServiceImpl.LOGGER.warn("Rebook warn.Order not found,OrderId: {}",info.getOrderId()); + RebookServiceImpl.LOGGER.warn("[rebook][Rebook warn][Order not found][OrderId: {}]",info.getOrderId()); return new Response(0, "order not found", null); } Order order = queryOrderResult.getData(); int status = order.getStatus(); if (status == OrderStatus.NOTPAID.getCode()) { - RebookServiceImpl.LOGGER.warn("Rebook warn.Order not paid, OrderId: {}",info.getOrderId()); + RebookServiceImpl.LOGGER.warn("[rebook][Rebook warn][Order not paid][OrderId: {}]",info.getOrderId()); return new Response<>(0, "You haven't paid the original ticket!", null); } else if (status == OrderStatus.PAID.getCode()) { // do nothing } else if (status == OrderStatus.CHANGE.getCode()) { - RebookServiceImpl.LOGGER.warn("Rebook warn.Order can't change twice,OrderId: {}",info.getOrderId()); + RebookServiceImpl.LOGGER.warn("[rebook][Rebook warn][Order can't change twice][OrderId: {}]",info.getOrderId()); return new Response<>(0, "You have already changed your ticket and you can only change one time.", null); } else if (status == OrderStatus.COLLECTED.getCode()) { - RebookServiceImpl.LOGGER.warn("Rebook warn.Order already collected,OrderId: {}",info.getOrderId()); + RebookServiceImpl.LOGGER.warn("[rebook][Rebook warn][Order already collected][OrderId: {}]",info.getOrderId()); return new Response<>(0, "You have already collected your ticket and you can change it now.", null); } else { - RebookServiceImpl.LOGGER.warn("Rebook warn.Order can't change,OrderId: {}",info.getOrderId()); + RebookServiceImpl.LOGGER.warn("[rebook][Rebook warn][Order can't change][OrderId: {}]",info.getOrderId()); return new Response<>(0, "You can't change your ticket.", null); } //Check the current time and the bus time of the old order, and judge whether the ticket can be changed according to the time. The ticket cannot be changed after two hours. if (!checkTime(order.getTravelDate(), order.getTravelTime())) { - RebookServiceImpl.LOGGER.warn("Rebook warn.Order beyond change time,OrderId: {}",info.getOrderId()); + RebookServiceImpl.LOGGER.warn("[rebook][Rebook warn][Order beyond change time][OrderId: {}]",info.getOrderId()); return new Response<>(0, "You can only change the ticket before the train start or within 2 hours after the train start.", null); } //The departure and destination cannot be changed, only the train number, seat and time can be changed //Check the info of seat availability and trains TripAllDetailInfo gtdi = new TripAllDetailInfo(); - gtdi.setFrom(queryForStationName(order.getFrom(), httpHeaders)); - gtdi.setTo(queryForStationName(order.getTo(), httpHeaders)); + gtdi.setFrom(order.getFrom()); + gtdi.setTo(order.getTo()); gtdi.setTravelDate(info.getDate()); gtdi.setTripId(info.getTripId()); Response gtdr = getTripAllDetailInformation(gtdi, info.getTripId(), httpHeaders); if (gtdr.getStatus() == 0) { - RebookServiceImpl.LOGGER.warn("Rebook warn.Trip detail not found,OrderId: {}",info.getOrderId()); + RebookServiceImpl.LOGGER.warn("[rebook][Rebook warn][Trip detail not found][OrderId: {}]",info.getOrderId()); return new Response<>(0, gtdr.getMsg(), null); } else { TripResponse tripResponse = gtdr.getData().getTripResponse(); if (info.getSeatType() == SeatClass.FIRSTCLASS.getCode()) { if (tripResponse.getConfortClass() <= 0) { - RebookServiceImpl.LOGGER.warn("Rebook warn.Seat Not Enough,OrderId: {},SeatType: {}",info.getOrderId(),info.getSeatType()); + RebookServiceImpl.LOGGER.warn("[rebook][Rebook warn][Seat Not Enough][OrderId: {},SeatType: {}]",info.getOrderId(),info.getSeatType()); return new Response<>(0, "Seat Not Enough", null); } } else { if (tripResponse.getEconomyClass() == SeatClass.SECONDCLASS.getCode() && tripResponse.getConfortClass() <= 0) { - RebookServiceImpl.LOGGER.warn("Rebook warn.Seat Not Enough,OrderId: {},SeatType: {}",info.getOrderId(),info.getSeatType()); + RebookServiceImpl.LOGGER.warn("[rebook][Rebook warn][Seat Not Enough][OrderId: {},SeatType: {}]",info.getOrderId(),info.getSeatType()); return new Response<>(0, "Seat Not Enough", null); } } @@ -110,7 +125,7 @@ public Response rebook(RebookInfo info, HttpHeaders httpHeaders) { //Refund the difference String difference = priceOld.subtract(priceNew).toString(); if (!drawBackMoney(info.getLoginId(), difference, httpHeaders)) { - RebookServiceImpl.LOGGER.warn("Rebook warn.Can't draw back the difference money,OrderId: {},LoginId: {},difference: {}",info.getOrderId(),info.getLoginId(),difference); + RebookServiceImpl.LOGGER.warn("[rebook][Rebook warn][Can't draw back the difference money][OrderId: {},LoginId: {},difference: {}]",info.getOrderId(),info.getLoginId(),difference); return new Response<>(0, "Can't draw back the difference money, please try again!", null); } return updateOrder(order, info, (TripAllDetail) gtdr.getData(), ticketPrice, httpHeaders); @@ -139,8 +154,8 @@ public Response payDifference(RebookInfo info, HttpHeaders httpHeaders) { Order order = (Order) queryOrderResult.getData(); TripAllDetailInfo gtdi = new TripAllDetailInfo(); - gtdi.setFrom(queryForStationName(order.getFrom(), httpHeaders)); - gtdi.setTo(queryForStationName(order.getTo(), httpHeaders)); + gtdi.setFrom(order.getFrom()); + gtdi.setTo(order.getTo()); gtdi.setTravelDate(info.getDate()); gtdi.setTripId(info.getTripId()); // TripAllDetail @@ -160,7 +175,7 @@ public Response payDifference(RebookInfo info, HttpHeaders httpHeaders) { if (payDifferentMoney(info.getOrderId(), info.getTripId(), info.getLoginId(), priceNew.subtract(priceOld).toString(), httpHeaders)) { return updateOrder(order, info, gtdr, ticketPrice, httpHeaders); } else { - RebookServiceImpl.LOGGER.warn("Pay difference warn.Can't pay the difference money,OrderId: {},LoginId: {},TripId: {}",info.getOrderId(),info.getLoginId(),info.getTripId()); + RebookServiceImpl.LOGGER.warn("[payDifference][Pay difference warn][Can't pay the difference money][OrderId: {},LoginId: {},TripId: {}]",info.getOrderId(),info.getLoginId(),info.getTripId()); return new Response<>(0, "Can't pay the difference,please try again", null); } } @@ -171,25 +186,30 @@ private Response updateOrder(Order order, RebookInfo info, TripAllDetail gtdr, S Trip trip = gtdr.getTrip(); String oldTripId = order.getTrainNumber(); order.setTrainNumber(info.getTripId()); - order.setBoughtDate(new Date()); + order.setBoughtDate(StringUtils.Date2String(new Date())); order.setStatus(OrderStatus.CHANGE.getCode()); order.setPrice(ticketPrice);//Set ticket price order.setSeatClass(info.getSeatType()); order.setTravelDate(info.getDate()); - order.setTravelTime(trip.getStartingTime()); + order.setTravelTime(trip.getStartTime()); + Route route = getRouteByRouteId(trip.getRouteId(), httpHeaders); + TrainType trainType = queryTrainTypeByName(trip.getTrainTypeName(), httpHeaders); + List stations = route.getStations(); + int firstClassTotalNum = trainType.getConfortClass(); + int secondClassTotalNum = trainType.getEconomyClass(); if (info.getSeatType() == SeatClass.FIRSTCLASS.getCode()) {//Dispatch the seat Ticket ticket = dipatchSeat(info.getDate(), order.getTrainNumber(), order.getFrom(), order.getTo(), - SeatClass.FIRSTCLASS.getCode(), httpHeaders); + SeatClass.FIRSTCLASS.getCode(), firstClassTotalNum, stations, httpHeaders); order.setSeatClass(SeatClass.FIRSTCLASS.getCode()); order.setSeatNumber("" + ticket.getSeatNo()); } else { Ticket ticket = dipatchSeat(info.getDate(), order.getTrainNumber(), order.getFrom(), order.getTo(), - SeatClass.SECONDCLASS.getCode(), httpHeaders); + SeatClass.SECONDCLASS.getCode(), secondClassTotalNum, stations, httpHeaders); order.setSeatClass(SeatClass.SECONDCLASS.getCode()); order.setSeatNumber("" + ticket.getSeatNo()); } @@ -202,7 +222,7 @@ private Response updateOrder(Order order, RebookInfo info, TripAllDetail gtdr, S if (changeOrderResult.getStatus() == 1) { return new Response<>(1, "Success!", order); } else { - RebookServiceImpl.LOGGER.error("Update order error,OrderId: {},TripId: {}",info.getOrderId(),info.getTripId()); + RebookServiceImpl.LOGGER.error("[updateOrder][Update order error][OrderId: {},TripId: {}]",info.getOrderId(),info.getTripId()); return new Response<>(0, "Can't update Order!", null); } } else { @@ -214,18 +234,21 @@ private Response updateOrder(Order order, RebookInfo info, TripAllDetail gtdr, S } } - public Ticket dipatchSeat(Date date, String tripId, String startStationId, String endStataionId, int seatType, HttpHeaders httpHeaders) { + public Ticket dipatchSeat(String date, String tripId, String startStationId, String endStataionId, int seatType, int tatalNum, List stations, HttpHeaders httpHeaders) { Seat seatRequest = new Seat(); seatRequest.setTravelDate(date); seatRequest.setTrainNumber(tripId); seatRequest.setSeatType(seatType); seatRequest.setStartStation(startStationId); seatRequest.setDestStation(endStataionId); + seatRequest.setTotalNum(tatalNum); + seatRequest.setStations(stations); HttpHeaders newHeaders = getAuthorizationHeadersFrom(httpHeaders); HttpEntity requestEntityTicket = new HttpEntity(seatRequest, newHeaders); + String seat_service_url = getServiceUrl("ts-seat-service"); ResponseEntity> reTicket = restTemplate.exchange( - "http://ts-seat-service:18898/api/v1/seatservice/seats", + seat_service_url + "/api/v1/seatservice/seats", HttpMethod.POST, requestEntityTicket, new ParameterizedTypeReference>() { @@ -238,15 +261,15 @@ private boolean tripGD(String tripId) { return tripId.startsWith("G") || tripId.startsWith("D"); } - private boolean checkTime(Date travelDate, Date travelTime) { + private boolean checkTime(String travelDate, String travelTime) { boolean result = true; Calendar calDateA = Calendar.getInstance(); Date today = new Date(); calDateA.setTime(today); Calendar calDateB = Calendar.getInstance(); - calDateB.setTime(travelDate); + calDateB.setTime(StringUtils.String2Date(travelDate)); Calendar calDateC = Calendar.getInstance(); - calDateC.setTime(travelTime); + calDateC.setTime(StringUtils.String2Date(travelTime)); if (calDateA.get(Calendar.YEAR) > calDateB.get(Calendar.YEAR)) { result = false; } else if (calDateA.get(Calendar.YEAR) == calDateB.get(Calendar.YEAR)) { @@ -271,11 +294,13 @@ private boolean checkTime(Date travelDate, Date travelTime) { private Response getTripAllDetailInformation(TripAllDetailInfo gtdi, String tripId, HttpHeaders httpHeaders) { Response gtdr; String requestUrl = ""; + String travel_service_url = getServiceUrl("ts-travel-service"); + String travel2_service_url = getServiceUrl("ts-travel2-service"); if (tripId.startsWith("G") || tripId.startsWith("D")) { - requestUrl = "http://ts-travel-service:12346/api/v1/travelservice/trip_detail"; + requestUrl = travel_service_url + "/api/v1/travelservice/trip_detail"; // ts-travel-service:12346/travel/getTripAllDetailInfo } else { - requestUrl = "http://ts-travel2-service:16346/api/v1/travel2service/trip_detail"; + requestUrl = travel2_service_url + "/api/v1/travel2service/trip_detail"; //ts-travel2-service:16346/travel2/getTripAllDetailInfo } HttpHeaders newHeaders = getAuthorizationHeadersFrom(httpHeaders); @@ -292,12 +317,14 @@ private Response getTripAllDetailInformation(TripAllDetailInfo gt private Response createOrder(Order order, String tripId, HttpHeaders httpHeaders) { String requestUrl = ""; + String order_service_url = getServiceUrl("ts-order-service"); + String order_other_service_url = getServiceUrl("ts-order-other-service"); if (tripId.startsWith("G") || tripId.startsWith("D")) { // ts-order-service:12031/order/create - requestUrl = "http://ts-order-service:12031/api/v1/orderservice/order"; + requestUrl = order_service_url + "/api/v1/orderservice/order"; } else { //ts-order-other-service:12032/orderOther/create - requestUrl = "http://ts-order-other-service:12032/api/v1/orderOtherService/orderOther"; + requestUrl = order_other_service_url + "/api/v1/orderOtherService/orderOther"; } HttpHeaders newHeaders = getAuthorizationHeadersFrom(httpHeaders); HttpEntity requestCreateOrder = new HttpEntity(order, newHeaders); @@ -311,10 +338,12 @@ private Response createOrder(Order order, String tripId, HttpHeaders httpHeaders private Response updateOrder(Order info, String tripId, HttpHeaders httpHeaders) { String requestOrderUtl = ""; + String order_service_url = getServiceUrl("ts-order-service"); + String order_other_service_url = getServiceUrl("ts-order-other-service"); if (tripGD(tripId)) { - requestOrderUtl = "http://ts-order-service:12031/api/v1/orderservice/order"; + requestOrderUtl = order_service_url + "/api/v1/orderservice/order"; } else { - requestOrderUtl = "http://ts-order-other-service:12032/api/v1/orderOtherService/orderOther"; + requestOrderUtl = order_other_service_url + "/api/v1/orderOtherService/orderOther"; } HttpHeaders newHeaders = getAuthorizationHeadersFrom(httpHeaders); HttpEntity requestUpdateOrder = new HttpEntity(info, newHeaders); @@ -329,10 +358,12 @@ private Response updateOrder(Order info, String tripId, HttpHeaders httpHeaders) private Response deleteOrder(String orderId, String tripId, HttpHeaders httpHeaders) { String requestUrl = ""; + String order_service_url = getServiceUrl("ts-order-service"); + String order_other_service_url = getServiceUrl("ts-order-other-service"); if (tripGD(tripId)) { - requestUrl = "http://ts-order-service:12031/api/v1/orderservice/order/" + orderId; + requestUrl = order_service_url + "/api/v1/orderservice/order/" + orderId; } else { - requestUrl = "http://ts-order-other-service:12032/api/v1/orderOtherService/orderOther/" + orderId; + requestUrl = order_other_service_url + "/api/v1/orderOtherService/orderOther/" + orderId; } HttpHeaders newHeaders = getAuthorizationHeadersFrom(httpHeaders); HttpEntity requestDeleteOrder = new HttpEntity(newHeaders); @@ -349,10 +380,12 @@ private Response getOrderByRebookInfo(RebookInfo info, HttpHeaders httpHe Response queryOrderResult; //Change can only be changed once, check the status of the order to determine whether it has been changed String requestUrl = ""; + String order_service_url = getServiceUrl("ts-order-service"); + String order_other_service_url = getServiceUrl("ts-order-other-service"); if (info.getOldTripId().startsWith("G") || info.getOldTripId().startsWith("D")) { - requestUrl = "http://ts-order-service:12031/api/v1/orderservice/order/" + info.getOrderId(); + requestUrl = order_service_url + "/api/v1/orderservice/order/" + info.getOrderId(); } else { - requestUrl = "http://ts-order-other-service:12032/api/v1/orderOtherService/orderOther/" + info.getOrderId(); + requestUrl = order_other_service_url + "/api/v1/orderOtherService/orderOther/" + info.getOrderId(); } HttpHeaders newHeaders = getAuthorizationHeadersFrom(httpHeaders); HttpEntity requestEntityGetOrderByRebookInfo = new HttpEntity(newHeaders); @@ -366,16 +399,35 @@ private Response getOrderByRebookInfo(RebookInfo info, HttpHeaders httpHe return queryOrderResult; } - private String queryForStationName(String stationId, HttpHeaders httpHeaders) { - HttpHeaders newHeaders = getAuthorizationHeadersFrom(httpHeaders); - HttpEntity requestEntityQueryForStationName = new HttpEntity(newHeaders); - ResponseEntity reQueryForStationName = restTemplate.exchange( - "http://ts-station-service:12345/api/v1/stationservice/stations/name/" + stationId, + public TrainType queryTrainTypeByName(String trainTypeName, HttpHeaders headers) { + HttpEntity requestEntity = new HttpEntity(null); + String train_service_url=getServiceUrl("ts-train-service"); + ResponseEntity re = restTemplate.exchange( + train_service_url + "/api/v1/trainservice/trains/byName/" + trainTypeName, HttpMethod.GET, - requestEntityQueryForStationName, + requestEntity, Response.class); - Response station = reQueryForStationName.getBody(); - return (String) station.getData(); + Response response = re.getBody(); + + return JsonUtils.conveterObject(response.getData(), TrainType.class); + } + + private Route getRouteByRouteId(String routeId, HttpHeaders headers) { + HttpEntity requestEntity = new HttpEntity(null); + String route_service_url=getServiceUrl("ts-route-service"); + ResponseEntity re = restTemplate.exchange( + route_service_url + "/api/v1/routeservice/routes/" + routeId, + HttpMethod.GET, + requestEntity, + Response.class); + Response result = re.getBody(); + if ( result.getStatus() == 0) { + LOGGER.warn("[getRouteByRouteId][Get Route By Id Failed][Fail msg: {}]", result.getMsg()); + return null; + } else { + LOGGER.info("[getRouteByRouteId][Get Route By Id][Success]"); + return JsonUtils.conveterObject(result.getData(), Route.class); + } } private boolean payDifferentMoney(String orderId, String tripId, String userId, String money, HttpHeaders httpHeaders) { @@ -387,8 +439,9 @@ private boolean payDifferentMoney(String orderId, String tripId, String userId, HttpHeaders newHeaders = getAuthorizationHeadersFrom(httpHeaders); HttpEntity requestEntityPayDifferentMoney = new HttpEntity(info, newHeaders); + String inside_payment_service_url = getServiceUrl("ts-inside-payment-service"); ResponseEntity rePayDifferentMoney = restTemplate.exchange( - "http://ts-inside-payment-service:18673/api/v1/inside_pay_service/inside_payment/difference", + inside_payment_service_url + "/api/v1/inside_pay_service/inside_payment/difference", HttpMethod.POST, requestEntityPayDifferentMoney, Response.class); @@ -400,8 +453,9 @@ private boolean drawBackMoney(String userId, String money, HttpHeaders httpHeade HttpHeaders newHeaders = getAuthorizationHeadersFrom(httpHeaders); HttpEntity requestEntityDrawBackMoney = new HttpEntity(newHeaders); + String inside_payment_service_url = getServiceUrl("ts-inside-payment-service"); ResponseEntity reDrawBackMoney = restTemplate.exchange( - "http://ts-inside-payment-service:18673/api/v1/inside_pay_service/inside_payment/drawback/" + userId + "/" + money, + inside_payment_service_url + "/api/v1/inside_pay_service/inside_payment/drawback/" + userId + "/" + money, HttpMethod.GET, requestEntityDrawBackMoney, Response.class); diff --git a/ts-rebook-service/src/main/resources/application.yml b/ts-rebook-service/src/main/resources/application.yml index 4b4aae4cf..6886b223e 100644 --- a/ts-rebook-service/src/main/resources/application.yml +++ b/ts-rebook-service/src/main/resources/application.yml @@ -3,6 +3,10 @@ server: port: 18886 # HTTP (Tomcat) port spring: + cloud: + nacos: + discovery: + server-addr: ${NACOS_ADDRS:nacos-0.nacos-headless.default.svc.cluster.local,nacos-1.nacos-headless.default.svc.cluster.local,nacos-2.nacos-headless.default.svc.cluster.local} application: name: ts-rebook-service swagger: @@ -25,4 +29,4 @@ swagger: # group: queue-group-rebook # destination: ts-rebook-service-queue-output # contentType: text/plain -# binder: rabbit \ No newline at end of file +# binder: rabbit diff --git a/ts-rebook-service/src/test/java/rebook/service/RebookServiceImplTest.java b/ts-rebook-service/src/test/java/rebook/service/RebookServiceImplTest.java index 817929d4b..36639df00 100644 --- a/ts-rebook-service/src/test/java/rebook/service/RebookServiceImplTest.java +++ b/ts-rebook-service/src/test/java/rebook/service/RebookServiceImplTest.java @@ -1,6 +1,11 @@ package rebook.service; +import edu.fudan.common.entity.Seat; +import edu.fudan.common.entity.Ticket; +import edu.fudan.common.entity.TripAllDetail; +import edu.fudan.common.entity.TripResponse; import edu.fudan.common.util.Response; +import edu.fudan.common.util.StringUtils; import org.junit.Assert; import org.junit.Before; import org.junit.Test; @@ -13,7 +18,8 @@ import org.springframework.core.ParameterizedTypeReference; import org.springframework.http.*; import org.springframework.web.client.RestTemplate; -import rebook.entity.*; +import edu.fudan.common.entity.*; +import rebook.entity.RebookInfo; import java.util.Date; @@ -45,7 +51,7 @@ public void testRebook() { order.setFrom("from_station"); order.setTo("to_station"); order.setPrice("1.0"); - Date date = new Date(System.currentTimeMillis()); + String date = StringUtils.Date2String(new Date()); order.setTravelDate(date); order.setTravelTime(date); Response response = new Response<>(1, null, order); @@ -87,7 +93,7 @@ public void testPayDifference() { info.setTripId("G"); info.setOldTripId("G"); info.setLoginId("login_id"); - info.setDate(new Date()); + info.setDate(""); info.setSeatType(0); //mock getOrderByRebookInfo() and getTripAllDetailInformation() @@ -123,8 +129,7 @@ public void testPayDifference() { @Test public void testDipatchSeat() { - long mills = System.currentTimeMillis(); - Seat seatRequest = new Seat(new Date(mills), "G1234", "start_station", "dest_station", 2); + Seat seatRequest = new Seat(StringUtils.Date2String(new Date()), "G1234", "start_station", "dest_station", 2, 100, null); HttpEntity requestEntityTicket = new HttpEntity<>(seatRequest, headers); Response response = new Response<>(); ResponseEntity> reTicket = new ResponseEntity<>(response, HttpStatus.OK); @@ -134,7 +139,7 @@ public void testDipatchSeat() { requestEntityTicket, new ParameterizedTypeReference>() { })).thenReturn(reTicket); - Ticket result = rebookServiceImpl.dipatchSeat(new Date(mills), "G1234", "start_station", "dest_station", 2, headers); + Ticket result = rebookServiceImpl.dipatchSeat(StringUtils.Date2String(new Date()), "G1234", "start_station", "dest_station", 2, 100, null,headers); Assert.assertNull(result); } diff --git a/ts-route-plan-service/pom.xml b/ts-route-plan-service/pom.xml index 8c5bf5ddf..2ce019509 100644 --- a/ts-route-plan-service/pom.xml +++ b/ts-route-plan-service/pom.xml @@ -16,7 +16,7 @@ org.services ts-service 0.1.0 - ../ + ../pom.xml @@ -31,8 +31,6 @@ ts-common 0.1.0 - - diff --git a/ts-route-plan-service/src/main/java/plan/RoutePlanApplication.java b/ts-route-plan-service/src/main/java/plan/RoutePlanApplication.java index afcb3a8e6..99f827d2c 100644 --- a/ts-route-plan-service/src/main/java/plan/RoutePlanApplication.java +++ b/ts-route-plan-service/src/main/java/plan/RoutePlanApplication.java @@ -3,6 +3,8 @@ import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.boot.web.client.RestTemplateBuilder; +import org.springframework.cloud.client.discovery.EnableDiscoveryClient; +import org.springframework.cloud.client.loadbalancer.LoadBalanced; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.EnableAspectJAutoProxy; import org.springframework.integration.annotation.IntegrationComponentScan; @@ -18,12 +20,14 @@ @EnableAsync @IntegrationComponentScan @EnableSwagger2 +@EnableDiscoveryClient public class RoutePlanApplication { public static void main(String[] args) { SpringApplication.run(RoutePlanApplication.class, args); } + @LoadBalanced @Bean public RestTemplate restTemplate(RestTemplateBuilder builder) { return builder.build(); diff --git a/ts-route-plan-service/src/main/java/plan/controller/RoutePlanController.java b/ts-route-plan-service/src/main/java/plan/controller/RoutePlanController.java index ea403c8e0..71c45dd1a 100644 --- a/ts-route-plan-service/src/main/java/plan/controller/RoutePlanController.java +++ b/ts-route-plan-service/src/main/java/plan/controller/RoutePlanController.java @@ -6,7 +6,7 @@ import org.springframework.http.HttpEntity; import org.springframework.http.HttpHeaders; import org.springframework.web.bind.annotation.*; -import plan.entity.RoutePlanInfo; +import edu.fudan.common.entity.RoutePlanInfo; import plan.service.RoutePlanService; import static org.springframework.http.ResponseEntity.ok; @@ -29,19 +29,19 @@ public String home() { @PostMapping(value = "/routePlan/cheapestRoute") public HttpEntity getCheapestRoutes(@RequestBody RoutePlanInfo info, @RequestHeader HttpHeaders headers) { - RoutePlanController.LOGGER.info("[Get Cheapest Routes] From: {} To: {} Num: {} Date: {}", info.getFormStationName(), info.getToStationName(), + info.getNum(), info.getTravelDate()); + RoutePlanController.LOGGER.info("[searchCheapestResult][Get Cheapest Routes][From: {}, To: {}, Num: {}, Date: {}]", info.getStartStation(), info.getEndStation(), + info.getNum(), info.getTravelDate()); return ok(routePlanService.searchCheapestResult(info, headers)); } @PostMapping(value = "/routePlan/quickestRoute") public HttpEntity getQuickestRoutes(@RequestBody RoutePlanInfo info, @RequestHeader HttpHeaders headers) { - RoutePlanController.LOGGER.info("[Get Quickest Routes] From: {} To: {} Num: {} Date: {}", info.getFormStationName(), info.getToStationName(), info.getNum(), info.getTravelDate()); + RoutePlanController.LOGGER.info("[searchQuickestResult][Get Quickest Routes][From: {}, To: {}, Num: {}, Date: {}]", info.getStartStation(), info.getEndStation(), info.getNum(), info.getTravelDate()); return ok(routePlanService.searchQuickestResult(info, headers)); } @PostMapping(value = "/routePlan/minStopStations") public HttpEntity getMinStopStations(@RequestBody RoutePlanInfo info, @RequestHeader HttpHeaders headers) { - RoutePlanController.LOGGER.info("[Get Min Stop Stations] From: {} To: {} Num: {} Date: {}", info.getFormStationName(), info.getToStationName(), info.getNum(), info.getTravelDate()); + RoutePlanController.LOGGER.info("[searchMinStopStations][Get Min Stop Stations][From: {}, To: {}, Num: {}, Date: {}]", info.getStartStation(), info.getEndStation(), info.getNum(), info.getTravelDate()); return ok(routePlanService.searchMinStopStations(info, headers)); } diff --git a/ts-route-plan-service/src/main/java/plan/entity/Route.java b/ts-route-plan-service/src/main/java/plan/entity/Route.java deleted file mode 100644 index cf43fbc0f..000000000 --- a/ts-route-plan-service/src/main/java/plan/entity/Route.java +++ /dev/null @@ -1,29 +0,0 @@ -package plan.entity; - -import com.fasterxml.jackson.annotation.JsonIgnoreProperties; -import lombok.Data; - -import java.util.List; - -/** - * @author fdse - */ -@Data -@JsonIgnoreProperties(ignoreUnknown = true) -public class Route { - - private String id; - - private List stations; - - private List distances; - - private String startStationId; - - private String terminalStationId; - - public Route() { - //Default Constructor - } - -} diff --git a/ts-route-plan-service/src/main/java/plan/entity/RoutePlanInfo.java b/ts-route-plan-service/src/main/java/plan/entity/RoutePlanInfo.java deleted file mode 100644 index 0eed4bb93..000000000 --- a/ts-route-plan-service/src/main/java/plan/entity/RoutePlanInfo.java +++ /dev/null @@ -1,32 +0,0 @@ -package plan.entity; - -import lombok.Data; - -import java.util.Date; - -/** - * @author fdse - */ -@Data -public class RoutePlanInfo { - - private String formStationName; - - private String toStationName; - - private Date travelDate; - - private int num; - - public RoutePlanInfo() { - //Empty Constructor - } - - public RoutePlanInfo(String formStationName, String toStationName, Date travelDate, int num) { - this.formStationName = formStationName; - this.toStationName = toStationName; - this.travelDate = travelDate; - this.num = num; - } - -} diff --git a/ts-route-plan-service/src/main/java/plan/entity/RoutePlanResultUnit.java b/ts-route-plan-service/src/main/java/plan/entity/RoutePlanResultUnit.java deleted file mode 100644 index 04c7fe7a8..000000000 --- a/ts-route-plan-service/src/main/java/plan/entity/RoutePlanResultUnit.java +++ /dev/null @@ -1,36 +0,0 @@ -package plan.entity; - -import lombok.Data; - -import java.util.Date; -import java.util.List; - -/** - * @author fdse - */ -@Data -public class RoutePlanResultUnit { - - private String tripId; - - private String trainTypeId; - - private String fromStationName; - - private String toStationName; - - private List stopStations; - - private String priceForSecondClassSeat; - - private String priceForFirstClassSeat; - - private Date startingTime; - - private Date endTime; - - public RoutePlanResultUnit() { - //Default Constructor - } - -} diff --git a/ts-route-plan-service/src/main/java/plan/entity/Trip.java b/ts-route-plan-service/src/main/java/plan/entity/Trip.java deleted file mode 100644 index 377ea45f9..000000000 --- a/ts-route-plan-service/src/main/java/plan/entity/Trip.java +++ /dev/null @@ -1,49 +0,0 @@ -package plan.entity; - -import lombok.Data; - -import java.util.Date; - -/** - * @author fdse - */ -@Data -public class Trip { - - private TripId tripId; - - private String trainTypeId; - - private String routeId; - - private String startingStationId; - - private String stationsId; - - private String terminalStationId; - - private Date startingTime; - - private Date endTime; - - public Trip(TripId tripId, String trainTypeId, String startingStationId, String stationsId, String terminalStationId, Date startingTime, Date endTime) { - this.tripId = tripId; - this.trainTypeId = trainTypeId; - this.startingStationId = startingStationId; - this.stationsId = stationsId; - this.terminalStationId = terminalStationId; - this.startingTime = startingTime; - this.endTime = endTime; - } - - public Trip(TripId tripId, String trainTypeId, String routeId) { - this.tripId = tripId; - this.trainTypeId = trainTypeId; - this.routeId = routeId; - } - - public Trip(){ - //Default Constructor - } - -} diff --git a/ts-route-plan-service/src/main/java/plan/entity/TripAllDetail.java b/ts-route-plan-service/src/main/java/plan/entity/TripAllDetail.java deleted file mode 100644 index d9d3eee39..000000000 --- a/ts-route-plan-service/src/main/java/plan/entity/TripAllDetail.java +++ /dev/null @@ -1,23 +0,0 @@ -package plan.entity; - -import lombok.Data; - -/** - * @author fdse - */ -@Data -public class TripAllDetail { - - private boolean status; - - private String message; - - private TripResponse tripResponse; - - private Trip trip; - - public TripAllDetail() { - //Default Constructor - } - -} diff --git a/ts-route-plan-service/src/main/java/plan/entity/TripAllDetailInfo.java b/ts-route-plan-service/src/main/java/plan/entity/TripAllDetailInfo.java deleted file mode 100644 index 9a92e0554..000000000 --- a/ts-route-plan-service/src/main/java/plan/entity/TripAllDetailInfo.java +++ /dev/null @@ -1,25 +0,0 @@ -package plan.entity; - -import lombok.Data; - -import java.util.Date; - -/** - * @author fdse - */ -@Data -public class TripAllDetailInfo { - - private String tripId; - - private Date travelDate; - - private String from; - - private String to; - - public TripAllDetailInfo() { - //Default Constructor - } - -} diff --git a/ts-route-plan-service/src/main/java/plan/entity/TripId.java b/ts-route-plan-service/src/main/java/plan/entity/TripId.java deleted file mode 100644 index 12aa62977..000000000 --- a/ts-route-plan-service/src/main/java/plan/entity/TripId.java +++ /dev/null @@ -1,39 +0,0 @@ -package plan.entity; - -import lombok.Data; - -import java.io.Serializable; - -/** - * @author fdse - */ -@Data -public class TripId implements Serializable{ - private Type type; - private String number; - - - public TripId(){ - //Default Constructor - } - - public TripId(String trainNumber){ - char type0 = trainNumber.charAt(0); - switch(type0){ - case 'Z': this.type = Type.Z; - break; - case 'T': this.type = Type.T; - break; - case 'K': this.type = Type.K; - break; - default:break; - } - - this.number = trainNumber.substring(1); - } - - @Override - public String toString(){ - return type.getName() + number; - } -} diff --git a/ts-route-plan-service/src/main/java/plan/entity/TripInfo.java b/ts-route-plan-service/src/main/java/plan/entity/TripInfo.java deleted file mode 100644 index 7661f4490..000000000 --- a/ts-route-plan-service/src/main/java/plan/entity/TripInfo.java +++ /dev/null @@ -1,23 +0,0 @@ -package plan.entity; - -import lombok.Data; - -import java.util.Date; - -/** - * @author fdse - */ -@Data -public class TripInfo { - - private String startingPlace; - - private String endPlace; - - private Date departureTime; - - public TripInfo(){ - //Default Constructor - } - -} diff --git a/ts-route-plan-service/src/main/java/plan/entity/TripResponse.java b/ts-route-plan-service/src/main/java/plan/entity/TripResponse.java deleted file mode 100644 index 8ea17daeb..000000000 --- a/ts-route-plan-service/src/main/java/plan/entity/TripResponse.java +++ /dev/null @@ -1,37 +0,0 @@ -package plan.entity; - -import lombok.Data; - -import java.util.Date; - -/** - * @author fdse - */ -@Data -public class TripResponse { - - private TripId tripId; - - private String trainTypeId; - - private String startingStation; - - private String terminalStation; - - private Date startingTime; - - private Date endTime; - - private int economyClass; - - private int confortClass; - - private String priceForEconomyClass; - - private String priceForConfortClass; - - public TripResponse(){ - //Default Constructor - } - -} diff --git a/ts-route-plan-service/src/main/java/plan/entity/Type.java b/ts-route-plan-service/src/main/java/plan/entity/Type.java deleted file mode 100644 index a010f065e..000000000 --- a/ts-route-plan-service/src/main/java/plan/entity/Type.java +++ /dev/null @@ -1,63 +0,0 @@ -package plan.entity; - -import java.io.Serializable; - -/** - * @author fdse - */ -public enum Type implements Serializable{ - - /** - * G - */ - G("G", 1), - /** - * D - */ - D("D", 2), - /** - * Z - */ - Z("Z",3), - /** - * T - */ - T("T", 4), - /** - * K - */ - K("K", 5); - - private String name; - private int index; - - Type(String name, int index) { - this.name = name; - this.index = index; - } - - public static String getName(int index) { - for (Type type : Type.values()) { - if (type.getIndex() == index) { - return type.name; - } - } - return null; - } - - public String getName() { - return name; - } - - void setName(String name) { - this.name = name; - } - - public int getIndex() { - return index; - } - - void setIndex(int index) { - this.index = index; - } -} diff --git a/ts-route-plan-service/src/main/java/plan/service/RoutePlanService.java b/ts-route-plan-service/src/main/java/plan/service/RoutePlanService.java index e47b1a8fb..fc7b19507 100644 --- a/ts-route-plan-service/src/main/java/plan/service/RoutePlanService.java +++ b/ts-route-plan-service/src/main/java/plan/service/RoutePlanService.java @@ -2,7 +2,7 @@ import edu.fudan.common.util.Response; import org.springframework.http.HttpHeaders; -import plan.entity.RoutePlanInfo; +import edu.fudan.common.entity.RoutePlanInfo; /** * @author fdse diff --git a/ts-route-plan-service/src/main/java/plan/service/RoutePlanServiceImpl.java b/ts-route-plan-service/src/main/java/plan/service/RoutePlanServiceImpl.java index b64449590..2c4ede02c 100644 --- a/ts-route-plan-service/src/main/java/plan/service/RoutePlanServiceImpl.java +++ b/ts-route-plan-service/src/main/java/plan/service/RoutePlanServiceImpl.java @@ -1,9 +1,12 @@ package plan.service; +import edu.fudan.common.entity.*; import edu.fudan.common.util.Response; +import edu.fudan.common.util.StringUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.cloud.client.discovery.DiscoveryClient; import org.springframework.core.ParameterizedTypeReference; import org.springframework.http.HttpEntity; import org.springframework.http.HttpHeaders; @@ -11,9 +14,9 @@ import org.springframework.http.ResponseEntity; import org.springframework.stereotype.Service; import org.springframework.web.client.RestTemplate; -import plan.entity.*; import java.util.ArrayList; +import java.util.Date; import java.util.List; /** @@ -24,15 +27,21 @@ public class RoutePlanServiceImpl implements RoutePlanService { @Autowired private RestTemplate restTemplate; + @Autowired + private DiscoveryClient discoveryClient; private static final Logger LOGGER = LoggerFactory.getLogger(RoutePlanServiceImpl.class); + private String getServiceUrl(String serviceName) { + return "http://" + serviceName; + } + @Override public Response searchCheapestResult(RoutePlanInfo info, HttpHeaders headers) { //1.Violence pulls out all the results of travel-service and travle2-service TripInfo queryInfo = new TripInfo(); - queryInfo.setStartingPlace(info.getFormStationName()); - queryInfo.setEndPlace(info.getToStationName()); + queryInfo.setStartPlace(info.getStartStation()); + queryInfo.setEndPlace(info.getEndStation()); queryInfo.setDepartureTime(info.getTravelDate()); ArrayList highSpeed = getTripFromHighSpeedTravelServive(queryInfo, headers); @@ -68,14 +77,14 @@ public Response searchCheapestResult(RoutePlanInfo info, HttpHeaders headers) { RoutePlanResultUnit tempUnit = new RoutePlanResultUnit(); tempUnit.setTripId(tempResponse.getTripId().toString()); - tempUnit.setTrainTypeId(tempResponse.getTrainTypeId()); - tempUnit.setFromStationName(tempResponse.getStartingStation()); - tempUnit.setToStationName(tempResponse.getTerminalStation()); + tempUnit.setTrainTypeName(tempResponse.getTrainTypeName()); + tempUnit.setStartStation(tempResponse.getStartStation()); + tempUnit.setEndStation(tempResponse.getTerminalStation()); tempUnit.setStopStations(getStationList(tempResponse.getTripId().toString(), headers)); tempUnit.setPriceForSecondClassSeat(tempResponse.getPriceForEconomyClass()); tempUnit.setPriceForFirstClassSeat(tempResponse.getPriceForConfortClass()); tempUnit.setEndTime(tempResponse.getEndTime()); - tempUnit.setStartingTime(tempResponse.getStartingTime()); + tempUnit.setStartTime(tempResponse.getStartTime()); units.add(tempUnit); } @@ -88,8 +97,8 @@ public Response searchQuickestResult(RoutePlanInfo info, HttpHeaders headers) { //1.Violence pulls out all the results of travel-service and travle2-service TripInfo queryInfo = new TripInfo(); - queryInfo.setStartingPlace(info.getFormStationName()); - queryInfo.setEndPlace(info.getToStationName()); + queryInfo.setStartPlace(info.getStartStation()); + queryInfo.setEndPlace(info.getEndStation()); queryInfo.setDepartureTime(info.getTravelDate()); ArrayList highSpeed = getTripFromHighSpeedTravelServive(queryInfo, headers); @@ -114,8 +123,10 @@ public Response searchQuickestResult(RoutePlanInfo info, HttpHeaders headers) { minTime = Long.MAX_VALUE; for (int j = 0; j < finalResult.size(); j++) { TripResponse thisRes = finalResult.get(j); - if (thisRes.getEndTime().getTime() - thisRes.getStartingTime().getTime() < minTime) { - minTime = thisRes.getEndTime().getTime() - thisRes.getStartingTime().getTime(); + Date endTime = StringUtils.String2Date(thisRes.getEndTime()); + Date startTime = StringUtils.String2Date(thisRes.getStartTime()); + if (endTime.getTime() - startTime.getTime() < minTime) { + minTime = endTime.getTime() - startTime.getTime(); minIndex = j; } } @@ -131,15 +142,15 @@ public Response searchQuickestResult(RoutePlanInfo info, HttpHeaders headers) { RoutePlanResultUnit tempUnit = new RoutePlanResultUnit(); tempUnit.setTripId(tempResponse.getTripId().toString()); - tempUnit.setTrainTypeId(tempResponse.getTrainTypeId()); - tempUnit.setFromStationName(tempResponse.getStartingStation()); - tempUnit.setToStationName(tempResponse.getTerminalStation()); + tempUnit.setTrainTypeName(tempResponse.getTrainTypeName()); + tempUnit.setStartStation(tempResponse.getStartStation()); + tempUnit.setEndStation(tempResponse.getTerminalStation()); tempUnit.setStopStations(getStationList(tempResponse.getTripId().toString(), headers)); tempUnit.setPriceForSecondClassSeat(tempResponse.getPriceForEconomyClass()); tempUnit.setPriceForFirstClassSeat(tempResponse.getPriceForConfortClass()); - tempUnit.setStartingTime(tempResponse.getStartingTime()); + tempUnit.setStartTime(tempResponse.getStartTime()); tempUnit.setEndTime(tempResponse.getEndTime()); units.add(tempUnit); } @@ -148,14 +159,15 @@ public Response searchQuickestResult(RoutePlanInfo info, HttpHeaders headers) { @Override public Response searchMinStopStations(RoutePlanInfo info, HttpHeaders headers) { - String fromStationId = queryForStationId(info.getFormStationName(), headers); - String toStationId = queryForStationId(info.getToStationName(), headers); - RoutePlanServiceImpl.LOGGER.info("From Id: {} To: {}", fromStationId , toStationId); + String fromStationId = info.getStartStation(); + String toStationId = info.getEndStation(); + RoutePlanServiceImpl.LOGGER.info("[searchMinStopStations][Start and Finish][From Id: {} To: {}]", fromStationId , toStationId); //1.Get the route through the two stations HttpEntity requestEntity = new HttpEntity(null); + String route_service_url = getServiceUrl("ts-route-service"); ResponseEntity>> re = restTemplate.exchange( - "http://ts-route-service:11178/api/v1/routeservice/routes/" + fromStationId + "/" + toStationId, + route_service_url + "/api/v1/routeservice/routes/" + info.getStartStation() + "/" + info.getEndStation(), HttpMethod.GET, requestEntity, new ParameterizedTypeReference>>() { @@ -163,7 +175,7 @@ public Response searchMinStopStations(RoutePlanInfo info, HttpHeaders headers) { ArrayList routeList = re.getBody().getData(); - RoutePlanServiceImpl.LOGGER.info("Candidate Route Number: {}", routeList.size()); + RoutePlanServiceImpl.LOGGER.info("[searchMinStopStations][Get the route][Candidate Route Number: {}]", routeList.size()); //2.Calculate how many stops there are between the two stations ArrayList gapList = new ArrayList<>(); for (int i = 0; i < routeList.size(); i++) { @@ -189,8 +201,9 @@ public Response searchMinStopStations(RoutePlanInfo info, HttpHeaders headers) { } //4.Depending on the route, go to travel-service or travel2service to get the train information requestEntity = new HttpEntity(resultRoutes, null); + String travel_service_url=getServiceUrl("ts-travel-service"); ResponseEntity>>> re2 = restTemplate.exchange( - "http://ts-travel-service:12346/api/v1/travelservice/trips/routes", + travel_service_url + "/api/v1/travelservice/trips/routes", HttpMethod.POST, requestEntity, new ParameterizedTypeReference>>>() { @@ -198,9 +211,9 @@ public Response searchMinStopStations(RoutePlanInfo info, HttpHeaders headers) { ArrayList> travelTrips = re2.getBody().getData(); - + String travel2_service_url=getServiceUrl("ts-travel2-service"); re2 = restTemplate.exchange( - "http://ts-travel2-service:16346/api/v1/travel2service/trips/routes", + travel2_service_url + "/api/v1/travel2service/trips/routes", HttpMethod.POST, requestEntity, new ParameterizedTypeReference>>>() { @@ -214,7 +227,7 @@ public Response searchMinStopStations(RoutePlanInfo info, HttpHeaders headers) { tempList.addAll(travelTrips.get(i)); finalTripResult.add(tempList); } - RoutePlanServiceImpl.LOGGER.info("Trips Num: {}", finalTripResult.size()); + RoutePlanServiceImpl.LOGGER.info("[searchMinStopStations][Get train Information][Trips Num: {}]", finalTripResult.size()); //5.Then, get the price and the station information according to the train information ArrayList trips = new ArrayList<>(); for (ArrayList tempTrips : finalTripResult) { @@ -228,14 +241,14 @@ public Response searchMinStopStations(RoutePlanInfo info, HttpHeaders headers) { TripAllDetailInfo allDetailInfo = new TripAllDetailInfo(); allDetailInfo.setTripId(trip.getTripId().toString()); allDetailInfo.setTravelDate(info.getTravelDate()); - allDetailInfo.setFrom(info.getFormStationName()); - allDetailInfo.setTo(info.getToStationName()); + allDetailInfo.setFrom(info.getStartStation()); + allDetailInfo.setTo(info.getEndStation()); requestEntity = new HttpEntity(allDetailInfo, null); String requestUrl = ""; if (trip.getTripId().toString().charAt(0) == 'D' || trip.getTripId().toString().charAt(0) == 'G') { - requestUrl = "http://ts-travel-service:12346/api/v1/travelservice/trip_detail"; + requestUrl = travel_service_url + "/api/v1/travelservice/trip_detail"; } else { - requestUrl = "http://ts-travel2-service:16346/api/v1/travel2service/trip_detail"; + requestUrl = travel2_service_url + "/api/v1/travel2service/trip_detail"; } re3 = restTemplate.exchange( requestUrl, @@ -250,10 +263,10 @@ public Response searchMinStopStations(RoutePlanInfo info, HttpHeaders headers) { RoutePlanResultUnit unit = new RoutePlanResultUnit(); unit.setTripId(trip.getTripId().toString()); - unit.setTrainTypeId(tripResponse.getTrainTypeId()); - unit.setFromStationName(tripResponse.getStartingStation()); - unit.setToStationName(tripResponse.getTerminalStation()); - unit.setStartingTime(tripResponse.getStartingTime()); + unit.setTrainTypeName(tripResponse.getTrainTypeName()); + unit.setStartStation(tripResponse.getStartStation()); + unit.setEndStation(tripResponse.getTerminalStation()); + unit.setStartTime(tripResponse.getStartTime()); unit.setEndTime(tripResponse.getEndTime()); unit.setPriceForFirstClassSeat(tripResponse.getPriceForConfortClass()); unit.setPriceForSecondClassSeat(tripResponse.getPriceForEconomyClass()); @@ -266,28 +279,15 @@ public Response searchMinStopStations(RoutePlanInfo info, HttpHeaders headers) { tripResponses.add(unit); } - RoutePlanServiceImpl.LOGGER.info("Trips Response Unit Num: {}", tripResponses.size()); + RoutePlanServiceImpl.LOGGER.info("[searchMinStopStations][Trips Response Unit Num: {}]", tripResponses.size()); return new Response<>(1, "Success.", tripResponses); } - private String queryForStationId(String stationName, HttpHeaders headers) { - RoutePlanServiceImpl.LOGGER.info("[Get Station Name]"); - - HttpEntity requestEntity = new HttpEntity(null); - ResponseEntity> re = restTemplate.exchange( - "http://ts-station-service:12345/api/v1/stationservice/stations/id/" + stationName, - HttpMethod.GET, - requestEntity, - new ParameterizedTypeReference>() { - }); - return re.getBody().getData(); - } - private Route getRouteByRouteId(String routeId, HttpHeaders headers) { - RoutePlanServiceImpl.LOGGER.info("[Get Route By Id] Route ID:{}", routeId); HttpEntity requestEntity = new HttpEntity(null); + String route_service_url = getServiceUrl("ts-route-service"); ResponseEntity> re = restTemplate.exchange( - "http://ts-route-service:11178/api/v1/routeservice/routes/" + routeId, + route_service_url + "/api/v1/routeservice/routes/" + routeId, HttpMethod.GET, requestEntity, new ParameterizedTypeReference>() { @@ -295,50 +295,53 @@ private Route getRouteByRouteId(String routeId, HttpHeaders headers) { Response result = re.getBody(); if (result.getStatus() == 0) { - RoutePlanServiceImpl.LOGGER.error("[Get Route By Id] Fail, RouteId: {}", routeId); + RoutePlanServiceImpl.LOGGER.error("[getRouteByRouteId][Get Route By Id Fail][RouteId: {}]", routeId); return null; } else { - RoutePlanServiceImpl.LOGGER.info("[Get Route By Id] Success."); + RoutePlanServiceImpl.LOGGER.info("[getRouteByRouteId][Get Route By Id Success]"); return result.getData(); } } private ArrayList getTripFromHighSpeedTravelServive(TripInfo info, HttpHeaders headers) { + RoutePlanServiceImpl.LOGGER.info("[getTripFromHighSpeedTravelServive][trip info: {}]", info); HttpEntity requestEntity = new HttpEntity(info, null); - + String travel_service_url=getServiceUrl("ts-travel-service"); ResponseEntity>> re = restTemplate.exchange( - "http://ts-travel-service:12346/api/v1/travelservice/trips/left", + travel_service_url + "/api/v1/travelservice/trips/left", HttpMethod.POST, requestEntity, new ParameterizedTypeReference>>() { }); ArrayList tripResponses = re.getBody().getData(); - RoutePlanServiceImpl.LOGGER.info("[Route Plan Get Trip][Size] {}", tripResponses.size()); + RoutePlanServiceImpl.LOGGER.info("[getTripFromHighSpeedTravelServive][Route Plan Get Trip][Size:{}]", tripResponses.size()); return tripResponses; } private ArrayList getTripFromNormalTrainTravelService(TripInfo info, HttpHeaders headers) { HttpEntity requestEntity = new HttpEntity(info, null); - + String travel2_service_url=getServiceUrl("ts-travel2-service"); ResponseEntity>> re = restTemplate.exchange( - "http://ts-travel2-service:16346/api/v1/travel2service/trips/left", + travel2_service_url + "/api/v1/travel2service/trips/left", HttpMethod.POST, requestEntity, new ParameterizedTypeReference>>() { }); ArrayList list = re.getBody().getData(); - RoutePlanServiceImpl.LOGGER.info("[Route Plan Get TripOther][Size] {}", list.size()); + RoutePlanServiceImpl.LOGGER.info("[getTripFromNormalTrainTravelService][Route Plan Get TripOther][Size:{}]", list.size()); return list; } private List getStationList(String tripId, HttpHeaders headers) { String path; + String travel_service_url=getServiceUrl("ts-travel-service"); + String travel2_service_url=getServiceUrl("ts-travel2-service"); if (tripId.charAt(0) == 'G' || tripId.charAt(0) == 'D') { - path = "http://ts-travel-service:12346/api/v1/travelservice/routes/" + tripId; + path = travel_service_url + "/api/v1/travelservice/routes/" + tripId; } else { - path = "http://ts-travel2-service:16346/api/v1/travel2service/routes/" + tripId; + path = travel2_service_url + "/api/v1/travel2service/routes/" + tripId; } HttpEntity requestEntity = new HttpEntity(null); ResponseEntity> re = restTemplate.exchange( diff --git a/ts-route-plan-service/src/main/resources/application.yml b/ts-route-plan-service/src/main/resources/application.yml index 6d833b0dc..a9bc7206c 100644 --- a/ts-route-plan-service/src/main/resources/application.yml +++ b/ts-route-plan-service/src/main/resources/application.yml @@ -1,4 +1,8 @@ spring: + cloud: + nacos: + discovery: + server-addr: ${NACOS_ADDRS:nacos-0.nacos-headless.default.svc.cluster.local,nacos-1.nacos-headless.default.svc.cluster.local,nacos-2.nacos-headless.default.svc.cluster.local} application: name: ts-route-plan-service @@ -8,4 +12,4 @@ server: swagger: - controllerPackage: plan.controller \ No newline at end of file + controllerPackage: plan.controller diff --git a/ts-route-plan-service/src/test/java/plan/controller/RoutePlanControllerTest.java b/ts-route-plan-service/src/test/java/plan/controller/RoutePlanControllerTest.java index 01e34bdb7..f60918b42 100644 --- a/ts-route-plan-service/src/test/java/plan/controller/RoutePlanControllerTest.java +++ b/ts-route-plan-service/src/test/java/plan/controller/RoutePlanControllerTest.java @@ -17,7 +17,7 @@ import org.springframework.test.web.servlet.request.MockMvcRequestBuilders; import org.springframework.test.web.servlet.result.MockMvcResultMatchers; import org.springframework.test.web.servlet.setup.MockMvcBuilders; -import plan.entity.RoutePlanInfo; +import edu.fudan.common.entity.RoutePlanInfo; import plan.service.RoutePlanService; @RunWith(JUnit4.class) diff --git a/ts-route-plan-service/src/test/java/plan/service/RoutePlanServiceImplTest.java b/ts-route-plan-service/src/test/java/plan/service/RoutePlanServiceImplTest.java index 27e96daf1..ed3a7c810 100644 --- a/ts-route-plan-service/src/test/java/plan/service/RoutePlanServiceImplTest.java +++ b/ts-route-plan-service/src/test/java/plan/service/RoutePlanServiceImplTest.java @@ -1,5 +1,7 @@ package plan.service; +import edu.fudan.common.entity.Trip; +import edu.fudan.common.entity.TripResponse; import edu.fudan.common.util.Response; import org.junit.Assert; import org.junit.Before; @@ -13,10 +15,8 @@ import org.springframework.core.ParameterizedTypeReference; import org.springframework.http.*; import org.springframework.web.client.RestTemplate; -import plan.entity.Route; -import plan.entity.RoutePlanInfo; -import plan.entity.Trip; -import plan.entity.TripResponse; +import edu.fudan.common.entity.RoutePlanInfo; +import edu.fudan.common.entity.Route; import java.util.ArrayList; import java.util.Date; @@ -39,7 +39,7 @@ public void setUp() { @Test public void testSearchCheapestResult() { - RoutePlanInfo info = new RoutePlanInfo("form_station", "to_station", new Date(), 1); + RoutePlanInfo info = new RoutePlanInfo("form_station", "to_station", "", 1); //mock getTripFromHighSpeedTravelServive() and getTripFromNormalTrainTravelService() ArrayList tripResponses = new ArrayList<>(); Response> response1 = new Response<>(null, null, tripResponses); @@ -56,7 +56,7 @@ public void testSearchCheapestResult() { @Test public void testSearchQuickestResult() { - RoutePlanInfo info = new RoutePlanInfo("form_station", "to_station", new Date(), 1); + RoutePlanInfo info = new RoutePlanInfo("form_station", "to_station", "", 1); //mock getTripFromHighSpeedTravelServive() and getTripFromNormalTrainTravelService() ArrayList tripResponses = new ArrayList<>(); Response> response1 = new Response<>(null, null, tripResponses); @@ -73,7 +73,7 @@ public void testSearchQuickestResult() { @Test public void testSearchMinStopStations() { - RoutePlanInfo info = new RoutePlanInfo("form_station", "to_station", new Date(), 1); + RoutePlanInfo info = new RoutePlanInfo("form_station", "to_station", "", 1); Response response = new Response(null, null, ""); ResponseEntity> re = new ResponseEntity<>(response, HttpStatus.OK); diff --git a/ts-route-service/pom.xml b/ts-route-service/pom.xml index 2f8274da2..f92ec1e25 100644 --- a/ts-route-service/pom.xml +++ b/ts-route-service/pom.xml @@ -15,7 +15,7 @@ org.services ts-service 0.1.0 - ../ + ../pom.xml @@ -26,17 +26,18 @@ org.springframework.boot - spring-boot-starter-data-mongodb + spring-boot-starter-data-jpa + + + mysql + mysql-connector-java org.services ts-common 0.1.0 - - - diff --git a/ts-route-service/src/main/java/route/RouteApplication.java b/ts-route-service/src/main/java/route/RouteApplication.java index bd224012e..94ee9d77a 100644 --- a/ts-route-service/src/main/java/route/RouteApplication.java +++ b/ts-route-service/src/main/java/route/RouteApplication.java @@ -3,6 +3,8 @@ import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.boot.web.client.RestTemplateBuilder; +import org.springframework.cloud.client.discovery.EnableDiscoveryClient; +import org.springframework.cloud.client.loadbalancer.LoadBalanced; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.EnableAspectJAutoProxy; import org.springframework.integration.annotation.IntegrationComponentScan; @@ -18,12 +20,14 @@ @EnableAsync @IntegrationComponentScan @EnableSwagger2 +@EnableDiscoveryClient public class RouteApplication { public static void main(String[] args) { SpringApplication.run(RouteApplication.class, args); } + @LoadBalanced @Bean public RestTemplate restTemplate(RestTemplateBuilder builder) { return builder.build(); diff --git a/ts-route-service/src/main/java/route/controller/RouteController.java b/ts-route-service/src/main/java/route/controller/RouteController.java index 5f1eadca8..ff320f03e 100644 --- a/ts-route-service/src/main/java/route/controller/RouteController.java +++ b/ts-route-service/src/main/java/route/controller/RouteController.java @@ -11,6 +11,8 @@ import route.entity.RouteInfo; import route.service.RouteService; +import java.util.List; + import static org.springframework.http.ResponseEntity.ok; /** @@ -30,34 +32,40 @@ public String home() { @PostMapping(path = "/routes") public ResponseEntity createAndModifyRoute(@RequestBody RouteInfo createAndModifyRouteInfo, @RequestHeader HttpHeaders headers) { - RouteController.LOGGER.info("Create route, start: {}, end: {}", createAndModifyRouteInfo.getStartStation(),createAndModifyRouteInfo.getEndStation()); + RouteController.LOGGER.info("[createAndModify][Create route][start: {}, end: {}]", createAndModifyRouteInfo.getStartStation(),createAndModifyRouteInfo.getEndStation()); return ok(routeService.createAndModify(createAndModifyRouteInfo, headers)); } @DeleteMapping(path = "/routes/{routeId}") public HttpEntity deleteRoute(@PathVariable String routeId, @RequestHeader HttpHeaders headers) { - RouteController.LOGGER.info("Delete route,RouteId: {}", routeId); + RouteController.LOGGER.info("[deleteRoute][Delete route][RouteId: {}]", routeId); return ok(routeService.deleteRoute(routeId, headers)); } @GetMapping(path = "/routes/{routeId}") public HttpEntity queryById(@PathVariable String routeId, @RequestHeader HttpHeaders headers) { - RouteController.LOGGER.info("Query route by id, RouteId: {}", routeId); + RouteController.LOGGER.info("[getRouteById][Query route by id][RouteId: {}]", routeId); return ok(routeService.getRouteById(routeId, headers)); } + @PostMapping(path = "/routes/byIds") + public HttpEntity queryByIds(@RequestBody List routeIds, @RequestHeader HttpHeaders headers) { + RouteController.LOGGER.info("[getRouteById][Query route by id][RouteId: {}]", routeIds); + return ok(routeService.getRouteByIds(routeIds, headers)); + } + @GetMapping(path = "/routes") public HttpEntity queryAll(@RequestHeader HttpHeaders headers) { - RouteController.LOGGER.info("Query all routes"); + RouteController.LOGGER.info("[getAllRoutes][Query all routes]"); return ok(routeService.getAllRoutes(headers)); } - @GetMapping(path = "/routes/{startId}/{terminalId}") - public HttpEntity queryByStartAndTerminal(@PathVariable String startId, - @PathVariable String terminalId, + @GetMapping(path = "/routes/{start}/{end}") + public HttpEntity queryByStartAndTerminal(@PathVariable String start, + @PathVariable String end, @RequestHeader HttpHeaders headers) { - RouteController.LOGGER.info("Query routes, startId : {}, terminalId: {}", startId, terminalId); - return ok(routeService.getRouteByStartAndTerminal(startId, terminalId, headers)); + RouteController.LOGGER.info("[getRouteByStartAndEnd][Query routes][start: {}, end: {}]", start, end); + return ok(routeService.getRouteByStartAndEnd(start, end, headers)); } } \ No newline at end of file diff --git a/ts-route-service/src/main/java/route/entity/Route.java b/ts-route-service/src/main/java/route/entity/Route.java index c2b9c0a44..fc34c7514 100644 --- a/ts-route-service/src/main/java/route/entity/Route.java +++ b/ts-route-service/src/main/java/route/entity/Route.java @@ -1,33 +1,59 @@ package route.entity; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import io.swagger.models.auth.In; import lombok.AllArgsConstructor; import lombok.Data; -import org.springframework.data.annotation.Id; -import org.springframework.data.mongodb.core.mapping.Document; +import lombok.NoArgsConstructor; +import org.hibernate.annotations.GenericGenerator; + +import javax.persistence.*; + import java.util.List; +import java.util.UUID; /** * @author fdse */ @Data -@AllArgsConstructor -@Document(collection = "routes") +@Entity @JsonIgnoreProperties(ignoreUnknown = true) +@GenericGenerator(name = "jpa-uuid", strategy = "org.hibernate.id.UUIDGenerator") public class Route { @Id + @Column(length = 36) private String id; + @ElementCollection(targetClass = String.class) + @OrderColumn private List stations; + @ElementCollection(targetClass = Integer.class) + @OrderColumn private List distances; - private String startStationId; + private String startStation; + + private String endStation; - private String terminalStationId; + public Route(){ + this.id = UUID.randomUUID().toString(); + } + + public Route(String id, List stations, List distances, String startStation, String endStation) { + this.id = id; + this.stations = stations; + this.distances = distances; + this.startStation = startStation; + this.endStation = endStation; + } - public Route() { - //Default Constructor + public Route(List stations, List distances, String startStation, String endStation) { + this.id = UUID.randomUUID().toString(); + this.stations = stations; + this.distances = distances; + this.startStation = startStation; + this.endStation = endStation; } } diff --git a/ts-route-service/src/main/java/route/entity/RouteInfo.java b/ts-route-service/src/main/java/route/entity/RouteInfo.java index 60cc7a546..a892b4e4f 100644 --- a/ts-route-service/src/main/java/route/entity/RouteInfo.java +++ b/ts-route-service/src/main/java/route/entity/RouteInfo.java @@ -2,14 +2,16 @@ import lombok.AllArgsConstructor; import lombok.Data; +import lombok.NoArgsConstructor; /** * @author fdse */ @Data @AllArgsConstructor +@NoArgsConstructor public class RouteInfo { - private String id; + private String Id; private String startStation; @@ -19,8 +21,4 @@ public class RouteInfo { private String distanceList; - public RouteInfo() { - //Default Constructor - } - } diff --git a/ts-route-service/src/main/java/route/repository/RouteRepository.java b/ts-route-service/src/main/java/route/repository/RouteRepository.java index c1811d993..58e36a2d2 100644 --- a/ts-route-service/src/main/java/route/repository/RouteRepository.java +++ b/ts-route-service/src/main/java/route/repository/RouteRepository.java @@ -1,16 +1,18 @@ package route.repository; -import org.springframework.data.mongodb.repository.MongoRepository; -import org.springframework.data.mongodb.repository.Query; +import org.springframework.data.jpa.repository.Query; +import org.springframework.data.repository.CrudRepository; import org.springframework.stereotype.Repository; import route.entity.Route; import java.util.ArrayList; +import java.util.List; +import java.util.Optional; /** * @author fdse */ @Repository -public interface RouteRepository extends MongoRepository { +public interface RouteRepository extends CrudRepository { /** * find route by id @@ -18,8 +20,16 @@ public interface RouteRepository extends MongoRepository { * @param id id * @return Route */ - @Query("{ 'id': ?0 }") - Route findById(String id); + Optional findById(String id); + + /** + * find route by ids + * + * @param ids ids + * @return Route + */ + @Query(value="SELECT * from route where id in ?1", nativeQuery = true) + List findByIds(List ids); /** * find all routes @@ -39,11 +49,10 @@ public interface RouteRepository extends MongoRepository { /** * return route with id from StartStationId to TerminalStationId * - * @param startingId Start Station Id - * @param terminalId Terminal Station Id + * @param startStation Start Station Name + * @param endStation end Station Name * @return ArrayList */ - @Query("{ 'startStationId': ?0 , 'terminalStationId': ?1 }") - ArrayList findByStartStationIdAndTerminalStationId(String startingId, String terminalId); + ArrayList findByStartStationAndEndStation(String startStation, String endStation); } diff --git a/ts-route-service/src/main/java/route/service/RouteService.java b/ts-route-service/src/main/java/route/service/RouteService.java index ac94bdcbe..bd08e9512 100644 --- a/ts-route-service/src/main/java/route/service/RouteService.java +++ b/ts-route-service/src/main/java/route/service/RouteService.java @@ -4,6 +4,8 @@ import org.springframework.http.HttpHeaders; import route.entity.*; +import java.util.List; + /** * @author fdse @@ -18,7 +20,7 @@ public interface RouteService { * @param headers headers * @return Response */ - Response getRouteByStartAndTerminal(String startId, String terminalId, HttpHeaders headers); + Response getRouteByStartAndEnd(String startId, String terminalId, HttpHeaders headers); /** * get all routes @@ -37,6 +39,15 @@ public interface RouteService { */ Response getRouteById(String routeId, HttpHeaders headers); + /** + * get route by ids + * + * @param routeIds route ids + * @param headers headers + * @return Response + */ + Response getRouteByIds(List routeIds, HttpHeaders headers); + /** * delete route by id * diff --git a/ts-route-service/src/main/java/route/service/RouteServiceImpl.java b/ts-route-service/src/main/java/route/service/RouteServiceImpl.java index 936874d81..3a9ec6d10 100644 --- a/ts-route-service/src/main/java/route/service/RouteServiceImpl.java +++ b/ts-route-service/src/main/java/route/service/RouteServiceImpl.java @@ -6,12 +6,14 @@ import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpHeaders; import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; import route.entity.Route; import route.entity.RouteInfo; import route.repository.RouteRepository; import java.util.ArrayList; import java.util.List; +import java.util.Optional; import java.util.UUID; /** @@ -28,66 +30,58 @@ public class RouteServiceImpl implements RouteService { @Override public Response createAndModify(RouteInfo info, HttpHeaders headers) { - RouteServiceImpl.LOGGER.info("Create And Modify Start: {} End: {}", info.getStartStation(), info.getEndStation()); + RouteServiceImpl.LOGGER.info("[createAndModify][Create and modify start and end][Start: {} End: {}]", info.getStartStation(), info.getEndStation()); String[] stations = info.getStationList().split(","); String[] distances = info.getDistanceList().split(","); List stationList = new ArrayList<>(); List distanceList = new ArrayList<>(); if (stations.length != distances.length) { - RouteServiceImpl.LOGGER.error("Create and modify error.Station number not equal to distance number,RouteId: {}",info.getId()); + RouteServiceImpl.LOGGER.error("[createAndModify][Create and modify error][Station number not equal to distance number][RouteId: {}]",info.getId()); return new Response<>(0, "Station Number Not Equal To Distance Number", null); } for (int i = 0; i < stations.length; i++) { stationList.add(stations[i]); distanceList.add(Integer.parseInt(distances[i])); } - int maxIdArrayLen = 10; + int maxIdArrayLen = 32; + Route route = new Route(); if (info.getId() == null || info.getId().length() < maxIdArrayLen) { - Route route = new Route(); route.setId(UUID.randomUUID().toString()); - route.setStartStationId(info.getStartStation()); - route.setTerminalStationId(info.getEndStation()); - route.setStations(stationList); - route.setDistances(distanceList); - routeRepository.save(route); - RouteServiceImpl.LOGGER.info("Save success"); - - return new Response<>(1, "Save Success", route); - } else { - Route route = routeRepository.findById(info.getId()); - if (route == null) { - route = new Route(); + }else{ + Optional routeOld = routeRepository.findById(info.getId()); + if(routeOld.isPresent()) { + route = routeOld.get(); + } else { route.setId(info.getId()); } - - route.setStartStationId(info.getStartStation()); - route.setTerminalStationId(info.getEndStation()); - route.setStations(stationList); - route.setDistances(distanceList); - routeRepository.save(route); - RouteServiceImpl.LOGGER.info("Modify success"); - return new Response<>(1, "Modify success", route); } + route.setStartStation(info.getStartStation()); + route.setEndStation(info.getEndStation()); + route.setStations(stationList); + route.setDistances(distanceList); + routeRepository.save(route); + return new Response<>(1, "Save and Modify success", route); } @Override + @Transactional public Response deleteRoute(String routeId, HttpHeaders headers) { routeRepository.removeRouteById(routeId); - Route route = routeRepository.findById(routeId); - if (route == null) { + Optional route = routeRepository.findById(routeId); + if (!route.isPresent()) { return new Response<>(1, "Delete Success", routeId); } else { - RouteServiceImpl.LOGGER.error("Delete error.Route not found,RouteId: {}",routeId); + RouteServiceImpl.LOGGER.error("[deleteRoute][Delete error][Route not found][RouteId: {}]",routeId); return new Response<>(0, "Delete failed, Reason unKnown with this routeId", routeId); } } @Override public Response getRouteById(String routeId, HttpHeaders headers) { - Route route = routeRepository.findById(routeId); - if (route == null) { - RouteServiceImpl.LOGGER.error("Find route error.Route not found,RouteId: {}",routeId); + Optional route = routeRepository.findById(routeId); + if (!route.isPresent()) { + RouteServiceImpl.LOGGER.error("[getRouteById][Find route error][Route not found][RouteId: {}]",routeId); return new Response<>(0, "No content with the routeId", null); } else { return new Response<>(1, success, route); @@ -96,9 +90,20 @@ public Response getRouteById(String routeId, HttpHeaders headers) { } @Override - public Response getRouteByStartAndTerminal(String startId, String terminalId, HttpHeaders headers) { + public Response getRouteByIds(List routeIds, HttpHeaders headers) { + List routes = routeRepository.findByIds(routeIds); + if (routes == null || routes.isEmpty()) { + RouteServiceImpl.LOGGER.error("[getRouteById][Find route error][Route not found][RouteIds: {}]",routeIds); + return new Response<>(0, "No content with the routeIds", null); + } else { + return new Response<>(1, success, routes); + } + } + + @Override + public Response getRouteByStartAndEnd(String startId, String terminalId, HttpHeaders headers) { ArrayList routes = routeRepository.findAll(); - RouteServiceImpl.LOGGER.info("Find All: {}", routes.size()); + RouteServiceImpl.LOGGER.info("[getRouteByStartAndEnd][Find All][size:{}]", routes.size()); List resultList = new ArrayList<>(); for (Route route : routes) { if (route.getStations().contains(startId) && @@ -110,7 +115,7 @@ public Response getRouteByStartAndTerminal(String startId, String terminalId, Ht if (!resultList.isEmpty()) { return new Response<>(1, success, resultList); } else { - RouteServiceImpl.LOGGER.warn("Find by start and terminal warn.Routes not found,startId: {},terminalId: {}",startId,terminalId); + RouteServiceImpl.LOGGER.warn("[getRouteByStartAndEnd][Find by start and terminal warn][Routes not found][startId: {},terminalId: {}]",startId,terminalId); return new Response<>(0, "No routes with the startId and terminalId", null); } } @@ -121,7 +126,7 @@ public Response getAllRoutes(HttpHeaders headers) { if (routes != null && !routes.isEmpty()) { return new Response<>(1, success, routes); } else { - RouteServiceImpl.LOGGER.warn("Find all routes warn: {}","No Content"); + RouteServiceImpl.LOGGER.warn("[getAllRoutes][Find all routes warn][{}]","No Content"); return new Response<>(0, "No Content", null); } } diff --git a/ts-route-service/src/main/resources/application.yml b/ts-route-service/src/main/resources/application.yml index 41e778322..bf506909f 100644 --- a/ts-route-service/src/main/resources/application.yml +++ b/ts-route-service/src/main/resources/application.yml @@ -1,13 +1,21 @@ spring: + cloud: + nacos: + discovery: + server-addr: ${NACOS_ADDRS:127.0.0.1:8848} application: name: ts-route-service - data: - mongodb: - host: ts-route-mongo -# username: user -# password: ${MONGODB_PASSWORD} - database: ts - port: 27017 + datasource: + url: jdbc:mysql://${ROUTE_MYSQL_HOST:10.176.122.1}:${ROUTE_MYSQL_PORT:3306}/${ROUTE_MYSQL_DATABASE:ts}?useSSL=false + username: ${ROUTE_MYSQL_USER:root} + password: ${ROUTE_MYSQL_PASSWORD:Abcd1234#} + driver-class-name: com.mysql.cj.jdbc.Driver + jpa: + hibernate: + ddl-auto: update + properties: + hibernate: + dialect: org.hibernate.dialect.MySQL5Dialect # HTTP Server server: diff --git a/ts-route-service/src/test/java/route/controller/RouteControllerTest.java b/ts-route-service/src/test/java/route/controller/RouteControllerTest.java index f4a06452d..25bd3a066 100644 --- a/ts-route-service/src/test/java/route/controller/RouteControllerTest.java +++ b/ts-route-service/src/test/java/route/controller/RouteControllerTest.java @@ -83,7 +83,7 @@ public void testQueryAll() throws Exception { @Test public void testQueryByStartAndTerminal() throws Exception { - Mockito.when(routeService.getRouteByStartAndTerminal(Mockito.anyString(), Mockito.anyString(), Mockito.any(HttpHeaders.class))).thenReturn(response); + Mockito.when(routeService.getRouteByStartAndEnd(Mockito.anyString(), Mockito.anyString(), Mockito.any(HttpHeaders.class))).thenReturn(response); String result = mockMvc.perform(MockMvcRequestBuilders.get("/api/v1/routeservice/routes/start_id/terminal_id")) .andExpect(MockMvcResultMatchers.status().isOk()) .andReturn().getResponse().getContentAsString(); diff --git a/ts-route-service/src/test/java/route/service/RouteServiceImplTest.java b/ts-route-service/src/test/java/route/service/RouteServiceImplTest.java index 923ed8da2..572b13fda 100644 --- a/ts-route-service/src/test/java/route/service/RouteServiceImplTest.java +++ b/ts-route-service/src/test/java/route/service/RouteServiceImplTest.java @@ -17,6 +17,7 @@ import java.util.ArrayList; import java.util.List; +import java.util.UUID; @RunWith(JUnit4.class) public class RouteServiceImplTest { @@ -70,7 +71,7 @@ public void testDeleteRoute1() { public void testDeleteRoute2() { Route route = new Route(); Mockito.doNothing().doThrow(new RuntimeException()).when(routeRepository).removeRouteById(Mockito.anyString()); - Mockito.when(routeRepository.findById(Mockito.anyString())).thenReturn(route); + Mockito.when(routeRepository.findById(Mockito.anyString()).get()).thenReturn(route); Response result = routeServiceImpl.deleteRoute("route_id", headers); Assert.assertEquals(new Response<>(0, "Delete failed, Reason unKnown with this routeId", "route_id"), result); } @@ -85,7 +86,7 @@ public void testGetRouteById1() { @Test public void testGetRouteById2() { Route route = new Route(); - Mockito.when(routeRepository.findById(Mockito.anyString())).thenReturn(route); + Mockito.when(routeRepository.findById(Mockito.anyString()).get()).thenReturn(route); Response result = routeServiceImpl.getRouteById("route_id", headers); Assert.assertEquals(new Response<>(1, "Success", route), result); } @@ -98,11 +99,11 @@ public void testGetRouteByStartAndTerminal1() { List distances = new ArrayList<>(); distances.add(5); distances.add(10); - Route route = new Route("id", stations, distances, "shanghai", "nanjing"); + Route route = new Route(UUID.randomUUID().toString(), stations, distances, "shanghai", "nanjing"); ArrayList routes = new ArrayList<>(); routes.add(route); Mockito.when(routeRepository.findAll()).thenReturn(routes); - Response result = routeServiceImpl.getRouteByStartAndTerminal("shanghai", "nanjing", headers); + Response result = routeServiceImpl.getRouteByStartAndEnd("shanghai", "nanjing", headers); Assert.assertEquals("Success", result.getMsg()); } @@ -110,7 +111,7 @@ public void testGetRouteByStartAndTerminal1() { public void testGetRouteByStartAndTerminal2() { ArrayList routes = new ArrayList<>(); Mockito.when(routeRepository.findAll()).thenReturn(routes); - Response result = routeServiceImpl.getRouteByStartAndTerminal("shanghai", "nanjing", headers); + Response result = routeServiceImpl.getRouteByStartAndEnd("shanghai", "nanjing", headers); Assert.assertEquals("No routes with the startId and terminalId", result.getMsg()); } diff --git a/ts-seat-service/pom.xml b/ts-seat-service/pom.xml index a1db88cb5..5908e22a7 100644 --- a/ts-seat-service/pom.xml +++ b/ts-seat-service/pom.xml @@ -16,7 +16,7 @@ org.services ts-service 0.1.0 - ../ + ../pom.xml @@ -31,10 +31,11 @@ ts-common 0.1.0 - - + + jakarta.validation + jakarta.validation-api + - diff --git a/ts-seat-service/src/main/java/seat/SeatApplication.java b/ts-seat-service/src/main/java/seat/SeatApplication.java index 956fd091a..7c7f770b3 100644 --- a/ts-seat-service/src/main/java/seat/SeatApplication.java +++ b/ts-seat-service/src/main/java/seat/SeatApplication.java @@ -3,6 +3,8 @@ import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.boot.web.client.RestTemplateBuilder; +import org.springframework.cloud.client.discovery.EnableDiscoveryClient; +import org.springframework.cloud.client.loadbalancer.LoadBalanced; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.EnableAspectJAutoProxy; import org.springframework.integration.annotation.IntegrationComponentScan; @@ -18,12 +20,14 @@ @EnableAsync @IntegrationComponentScan @EnableSwagger2 +@EnableDiscoveryClient public class SeatApplication { public static void main(String[] args) { SpringApplication.run(SeatApplication.class, args); } + @LoadBalanced @Bean public RestTemplate restTemplate(RestTemplateBuilder builder) { return builder.build(); diff --git a/ts-seat-service/src/main/java/seat/controller/SeatController.java b/ts-seat-service/src/main/java/seat/controller/SeatController.java index 5ba08c703..3cad1b78d 100644 --- a/ts-seat-service/src/main/java/seat/controller/SeatController.java +++ b/ts-seat-service/src/main/java/seat/controller/SeatController.java @@ -6,7 +6,7 @@ import org.springframework.http.HttpEntity; import org.springframework.http.HttpHeaders; import org.springframework.web.bind.annotation.*; -import seat.entity.Seat; +import edu.fudan.common.entity.Seat; import seat.service.SeatService; import static org.springframework.http.ResponseEntity.ok; @@ -38,7 +38,7 @@ public String home() { @CrossOrigin(origins = "*") @PostMapping(value = "/seats") public HttpEntity create(@RequestBody Seat seatRequest, @RequestHeader HttpHeaders headers) { - SeatController.LOGGER.info("Create seat,TravelDate: {},TrainNumber: {},SeatType: {}",seatRequest.getTravelDate(),seatRequest.getTrainNumber(),seatRequest.getSeatType()); + SeatController.LOGGER.info("[distributeSeat][Create seat][TravelDate: {},TrainNumber: {},SeatType: {}]",seatRequest.getTravelDate(),seatRequest.getTrainNumber(),seatRequest.getSeatType()); return ok(seatService.distributeSeat(seatRequest, headers)); } @@ -54,7 +54,7 @@ public HttpEntity create(@RequestBody Seat seatRequest, @RequestHeader HttpHeade @PostMapping(value = "/seats/left_tickets") public HttpEntity getLeftTicketOfInterval(@RequestBody Seat seatRequest, @RequestHeader HttpHeaders headers) { // int - SeatController.LOGGER.info("Get left ticket of interval,TravelDate: {},TrainNumber: {},SeatType: {}",seatRequest.getTravelDate(),seatRequest.getTrainNumber(),seatRequest.getSeatType()); + SeatController.LOGGER.info("[getLeftTicketOfInterval][Get left ticket of interval][TravelDate: {},TrainNumber: {},SeatType: {}]",seatRequest.getTravelDate(),seatRequest.getTrainNumber(),seatRequest.getSeatType()); return ok(seatService.getLeftTicketOfInterval(seatRequest, headers)); } diff --git a/ts-seat-service/src/main/java/seat/entity/Config.java b/ts-seat-service/src/main/java/seat/entity/Config.java deleted file mode 100644 index f4629c9b4..000000000 --- a/ts-seat-service/src/main/java/seat/entity/Config.java +++ /dev/null @@ -1,26 +0,0 @@ -package seat.entity; - -import lombok.Data; - -/** - * @author fdse - */ -@Data -public class Config { - - private String name; - - private String value; - - private String description; - - public Config() { - } - - public Config(String name, String value, String description) { - this.name = name; - this.value = value; - this.description = description; - } - -} diff --git a/ts-seat-service/src/main/java/seat/entity/LeftTicketInfo.java b/ts-seat-service/src/main/java/seat/entity/LeftTicketInfo.java deleted file mode 100644 index e4f8c26cb..000000000 --- a/ts-seat-service/src/main/java/seat/entity/LeftTicketInfo.java +++ /dev/null @@ -1,28 +0,0 @@ -package seat.entity; - -import lombok.Data; - -import javax.validation.Valid; -import javax.validation.constraints.NotNull; -import java.util.Set; - -/** - * @author fdse - */ -@Data -public class LeftTicketInfo { - @Valid - @NotNull - private Set soldTickets; - - public LeftTicketInfo(){ - //Default Constructor - } - - @Override - public String toString() { - return "LeftTicketInfo{" + - "soldTickets=" + soldTickets + - '}'; - } -} diff --git a/ts-seat-service/src/main/java/seat/entity/Route.java b/ts-seat-service/src/main/java/seat/entity/Route.java deleted file mode 100644 index 164faccd0..000000000 --- a/ts-seat-service/src/main/java/seat/entity/Route.java +++ /dev/null @@ -1,29 +0,0 @@ -package seat.entity; - -import com.fasterxml.jackson.annotation.JsonIgnoreProperties; -import lombok.Data; - -import java.util.List; - -/** - * @author fdse - */ -@Data -@JsonIgnoreProperties(ignoreUnknown = true) -public class Route { - - private String id; - - private List stations; - - private List distances; - - private String startStationId; - - private String terminalStationId; - - public Route() { - //Default Constructor - } - -} diff --git a/ts-seat-service/src/main/java/seat/entity/Seat.java b/ts-seat-service/src/main/java/seat/entity/Seat.java deleted file mode 100644 index de0fd151a..000000000 --- a/ts-seat-service/src/main/java/seat/entity/Seat.java +++ /dev/null @@ -1,54 +0,0 @@ -package seat.entity; - -import lombok.Data; - -import javax.validation.Valid; -import javax.validation.constraints.NotNull; -import java.util.Date; - -/** - * @author fdse - */ -@Data -public class Seat { - @Valid - @NotNull - private Date travelDate; - - @Valid - @NotNull - private String trainNumber; - - - @Valid - @NotNull - private String startStation; - - @Valid - @NotNull - private String destStation; - - @Valid - @NotNull - private int seatType; - - public Seat(){ - //Default Constructor - this.travelDate = new Date(); - this.trainNumber = ""; - this.startStation = ""; - this.destStation = ""; - this.seatType = 0; - } - - @Override - public String toString() { - return "Seat{" + - "travelDate=" + travelDate + - ", trainNumber='" + trainNumber + '\'' + - ", startStation='" + startStation + '\'' + - ", destStation='" + destStation + '\'' + - ", seatType=" + seatType + - '}'; - } -} diff --git a/ts-seat-service/src/main/java/seat/entity/SeatClass.java b/ts-seat-service/src/main/java/seat/entity/SeatClass.java deleted file mode 100644 index 71b7c6e9d..000000000 --- a/ts-seat-service/src/main/java/seat/entity/SeatClass.java +++ /dev/null @@ -1,70 +0,0 @@ -package seat.entity; - -/** - * @author fdse - */ -public enum SeatClass { - - /** - * no seat - */ - NONE (0,"NoSeat"), - /** - * green seat - */ - BUSINESS (1,"GreenSeat"), - /** - * first class seat - */ - FIRSTCLASS (2,"FirstClassSeat"), - /** - * second class seat - */ - SECONDCLASS (3,"SecondClassSeat"), - /** - * hard seat - */ - HARDSEAT (4,"HardSeat"), - /** - * soft seat - */ - SOFTSEAT (5,"SoftSeat"), - /** - * hard bed - */ - HARDBED (6,"HardBed"), - /** - * soft bed - */ - SOFTBED (7,"SoftBed"), - /** - * high soft seat - */ - HIGHSOFTBED (8,"HighSoftSeat"); - - private int code; - private String name; - - SeatClass(int code, String name){ - this.code = code; - this.name = name; - } - - public int getCode(){ - return code; - } - - public String getName() { - return name; - } - - public static String getNameByCode(int code){ - SeatClass[] seatClassSet = SeatClass.values(); - for(SeatClass seatClass : seatClassSet){ - if(seatClass.getCode() == code){ - return seatClass.getName(); - } - } - return seatClassSet[0].getName(); - } -} diff --git a/ts-seat-service/src/main/java/seat/entity/Ticket.java b/ts-seat-service/src/main/java/seat/entity/Ticket.java deleted file mode 100644 index 8e6deba4f..000000000 --- a/ts-seat-service/src/main/java/seat/entity/Ticket.java +++ /dev/null @@ -1,21 +0,0 @@ -package seat.entity; - -import lombok.Data; - -/** - * @author fdse - */ -@Data -public class Ticket { - - private int seatNo; - - private String startStation; - - private String destStation; - - public Ticket(){ - //Default Constructor - } - -} diff --git a/ts-seat-service/src/main/java/seat/entity/TrainType.java b/ts-seat-service/src/main/java/seat/entity/TrainType.java deleted file mode 100644 index 1d8498fae..000000000 --- a/ts-seat-service/src/main/java/seat/entity/TrainType.java +++ /dev/null @@ -1,40 +0,0 @@ -package seat.entity; - -import lombok.Data; - -import javax.validation.Valid; - -/** - * @author fdse - */ -@Data -public class TrainType { - @Valid - private String id; - - @Valid - private int economyClass; - - @Valid - private int confortClass; - - private int averageSpeed; - - public TrainType(){ - //Default Constructor - } - - public TrainType(String id, int economyClass, int confortClass) { - this.id = id; - this.economyClass = economyClass; - this.confortClass = confortClass; - } - - public TrainType(String id, int economyClass, int confortClass, int averageSpeed) { - this.id = id; - this.economyClass = economyClass; - this.confortClass = confortClass; - this.averageSpeed = averageSpeed; - } - -} diff --git a/ts-seat-service/src/main/java/seat/service/SeatService.java b/ts-seat-service/src/main/java/seat/service/SeatService.java index 540fe972c..cf8b60842 100644 --- a/ts-seat-service/src/main/java/seat/service/SeatService.java +++ b/ts-seat-service/src/main/java/seat/service/SeatService.java @@ -2,7 +2,7 @@ import edu.fudan.common.util.Response; import org.springframework.http.HttpHeaders; -import seat.entity.Seat; +import edu.fudan.common.entity.Seat; /** * @author fdse diff --git a/ts-seat-service/src/main/java/seat/service/SeatServiceImpl.java b/ts-seat-service/src/main/java/seat/service/SeatServiceImpl.java index ebf0d9306..12cf549f1 100644 --- a/ts-seat-service/src/main/java/seat/service/SeatServiceImpl.java +++ b/ts-seat-service/src/main/java/seat/service/SeatServiceImpl.java @@ -4,6 +4,9 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.cloud.client.ServiceInstance; +import org.springframework.cloud.client.discovery.DiscoveryClient; import org.springframework.core.ParameterizedTypeReference; import org.springframework.http.HttpEntity; import org.springframework.http.HttpHeaders; @@ -11,7 +14,7 @@ import org.springframework.http.ResponseEntity; import org.springframework.stereotype.Service; import org.springframework.web.client.RestTemplate; -import seat.entity.*; +import edu.fudan.common.entity.*; import java.util.List; import java.util.Random; @@ -25,8 +28,15 @@ public class SeatServiceImpl implements SeatService { @Autowired RestTemplate restTemplate; + @Autowired + private DiscoveryClient discoveryClient; + private static final Logger LOGGER = LoggerFactory.getLogger(SeatServiceImpl.class); + private String getServiceUrl(String serviceName) { + return "http://" + serviceName; + } + @Override public Response distributeSeat(Seat seatRequest, HttpHeaders headers) { Response routeResult; @@ -41,90 +51,39 @@ public Response distributeSeat(Seat seatRequest, HttpHeaders headers) { String trainNumber = seatRequest.getTrainNumber(); if (trainNumber.startsWith("G") || trainNumber.startsWith("D")) { - SeatServiceImpl.LOGGER.info("TrainNumber start with G|D"); + SeatServiceImpl.LOGGER.info("[distributeSeat][TrainNumber start][G or D]"); - //Call the microservice to query all the station information for the train HttpEntity requestEntity = new HttpEntity(null); - re = restTemplate.exchange( - "http://ts-travel-service:12346/api/v1/travelservice/routes/" + trainNumber, - HttpMethod.GET, - requestEntity, - new ParameterizedTypeReference>() { - }); - routeResult = re.getBody(); - SeatServiceImpl.LOGGER.info("[distributeSeat] The result of getRouteResult is {}", routeResult.getMsg()); - //Call the microservice to query for residual Ticket information: the set of the Ticket sold for the specified seat type requestEntity = new HttpEntity(seatRequest, null); + String order_service_url=getServiceUrl("ts-order-service"); re3 = restTemplate.exchange( - "http://ts-order-service:12031/api/v1/orderservice/order/tickets", + order_service_url + "/api/v1/orderservice/order/tickets", HttpMethod.POST, requestEntity, new ParameterizedTypeReference>() { }); - SeatServiceImpl.LOGGER.info("Left ticket info is : {}", re3.getBody().toString()); + SeatServiceImpl.LOGGER.info("[distributeSeat][Left ticket info][info is : {}]", re3.getBody().toString()); leftTicketInfo = re3.getBody().getData(); - - //Calls the microservice to query the total number of seats specified for that vehicle - requestEntity = new HttpEntity(null); - re2 = restTemplate.exchange( - "http://ts-travel-service:12346/api/v1/travelservice/train_types/" + seatRequest.getTrainNumber(), - HttpMethod.GET, - requestEntity, - new ParameterizedTypeReference>() { - }); - Response trainTypeResponse = re2.getBody(); - trainTypeResult = trainTypeResponse.getData(); - - SeatServiceImpl.LOGGER.info("[distributeSeat 1] The result of getTrainTypeResult is {}", trainTypeResponse.toString()); } else { - SeatServiceImpl.LOGGER.info("TrainNumber start with other capital"); - //Call the micro service to query all the station information for the trains - HttpEntity requestEntity = new HttpEntity(null); - re = restTemplate.exchange( - "http://ts-travel2-service:16346/api/v1/travel2service/routes/" + seatRequest.getTrainNumber(), - HttpMethod.GET, - requestEntity, - new ParameterizedTypeReference>() { - }); - routeResult = re.getBody(); - SeatServiceImpl.LOGGER.info("[distributeSeat] The result of getRouteResult is {}", routeResult.toString()); - + SeatServiceImpl.LOGGER.info("[distributeSeat][TrainNumber start][Other Capital Except D and G]"); //Call the microservice to query for residual Ticket information: the set of the Ticket sold for the specified seat type - requestEntity = new HttpEntity(seatRequest, null); + HttpEntity requestEntity = new HttpEntity(seatRequest, null); + String order_other_service_url=getServiceUrl("ts-order-other-service"); re3 = restTemplate.exchange( - "http://ts-order-other-service:12032/api/v1/orderOtherService/orderOther/tickets", + order_other_service_url + "/api/v1/orderOtherService/orderOther/tickets", HttpMethod.POST, requestEntity, new ParameterizedTypeReference>() { }); - SeatServiceImpl.LOGGER.info("Left ticket info is : {}", re3.getBody().toString()); + SeatServiceImpl.LOGGER.info("[distributeSeat][Left ticket info][info is : {}]", re3.getBody().toString()); leftTicketInfo = re3.getBody().getData(); - - //Calls the microservice to query the total number of seats specified for that vehicle - requestEntity = new HttpEntity(null); - re2 = restTemplate.exchange( - "http://ts-travel2-service:16346/api/v1/travel2service/train_types/" + seatRequest.getTrainNumber(), - HttpMethod.GET, - requestEntity, - new ParameterizedTypeReference>() { - }); - Response trainTypeResponse = re2.getBody(); - trainTypeResult = trainTypeResponse.getData(); - SeatServiceImpl.LOGGER.info("[distributeSeat 2] The result of getTrainTypeResult is {}", trainTypeResponse.toString()); } - //Assign seats - List stationList = routeResult.getData().getStations(); - int seatTotalNum = 0; - if (seatRequest.getSeatType() == SeatClass.FIRSTCLASS.getCode()) { - seatTotalNum = trainTypeResult.getConfortClass(); - SeatServiceImpl.LOGGER.info("[distributeSeat] The request seat type is comfortClass and the total num is {}", seatTotalNum); - } else { - seatTotalNum = trainTypeResult.getEconomyClass(); - SeatServiceImpl.LOGGER.info("[distributeSeat] The request seat type is economyClass and the total num is {}", seatTotalNum); - } + List stationList = seatRequest.getStations(); + + int seatTotalNum = seatRequest.getTotalNum(); String startStation = seatRequest.getStartStation(); Ticket ticket = new Ticket(); ticket.setStartStation(startStation); @@ -143,7 +102,7 @@ public Response distributeSeat(Seat seatRequest, HttpHeaders headers) { //Tickets can be allocated if the sold ticket's end station before the start station of the request if (stationList.indexOf(soldTicketDestStation) < stationList.indexOf(startStation)) { ticket.setSeatNo(soldTicket.getSeatNo()); - SeatServiceImpl.LOGGER.info("[distributeSeat] Use the previous distributed seat number! {}", soldTicket.getSeatNo()); + SeatServiceImpl.LOGGER.info("[distributeSeat][Assign new tickets][Use the previous distributed seat number][seat number:{}]", soldTicket.getSeatNo()); return new Response<>(1, "Use the previous distributed seat number!", ticket); } } @@ -152,7 +111,7 @@ public Response distributeSeat(Seat seatRequest, HttpHeaders headers) { } } ticket.setSeatNo(seat); - SeatServiceImpl.LOGGER.info("[distributeSeat] Use a new seat number! {}", seat); + SeatServiceImpl.LOGGER.info("[distributeSeat][Assign new tickets][Use a new seat number][seat number:{}]", seat); return new Response<>(1, "Use a new seat number!", ticket); } @@ -170,105 +129,47 @@ private boolean isContained(Set soldTickets, int seat) { @Override public Response getLeftTicketOfInterval(Seat seatRequest, HttpHeaders headers) { int numOfLeftTicket = 0; - Response routeResult; - TrainType trainTypeResult; LeftTicketInfo leftTicketInfo; - - ResponseEntity> re; - ResponseEntity> re2; ResponseEntity> re3; //Distinguish G\D from other trains String trainNumber = seatRequest.getTrainNumber(); - SeatServiceImpl.LOGGER.info("Seat request To String: {}", seatRequest.toString()); + SeatServiceImpl.LOGGER.info("[getLeftTicketOfInterval][Seat request][request:{}]", seatRequest.toString()); if (trainNumber.startsWith("G") || trainNumber.startsWith("D")) { - SeatServiceImpl.LOGGER.info("[getLeftTicketOfInterval] TrainNumber start with G|D {}", trainNumber); + SeatServiceImpl.LOGGER.info("[getLeftTicketOfInterval][TrainNumber start with G|D][trainNumber:{}]", trainNumber); //Call the micro service to query all the station information for the trains - HttpEntity requestEntity = new HttpEntity(null); - re = restTemplate.exchange( - "http://ts-travel-service:12346/api/v1/travelservice/routes/" + trainNumber, - HttpMethod.GET, - requestEntity, - new ParameterizedTypeReference>() { - }); - routeResult = re.getBody(); - SeatServiceImpl.LOGGER.info("[ getLeftTicketOfInterval] The result of getRouteResult is {}", routeResult.getMsg()); - - //Call the micro service to query for residual Ticket information: the set of the Ticket sold for the specified seat type - requestEntity = new HttpEntity(seatRequest, null); + HttpEntity requestEntity = new HttpEntity(seatRequest, null); + String order_service_url=getServiceUrl("ts-order-service"); re3 = restTemplate.exchange( - "http://ts-order-service:12031/api/v1/orderservice/order/tickets", + order_service_url + "/api/v1/orderservice/order/tickets", HttpMethod.POST, requestEntity, new ParameterizedTypeReference>() { }); - SeatServiceImpl.LOGGER.info("Get Order tickets result is : {}", re3); + SeatServiceImpl.LOGGER.info("[getLeftTicketOfInterval][Get Order tickets result][result is {}]", re3); leftTicketInfo = re3.getBody().getData(); - - //Calls the microservice to query the total number of seats specified for that vehicle - requestEntity = new HttpEntity(null); - re2 = restTemplate.exchange( - "http://ts-travel-service:12346/api/v1/travelservice/train_types/" + seatRequest.getTrainNumber(), - HttpMethod.GET, - requestEntity, - new ParameterizedTypeReference>() { - }); - Response trainTypeResponse = re2.getBody(); - - - trainTypeResult = trainTypeResponse.getData(); - SeatServiceImpl.LOGGER.info("[getLeftTicketOfInterval] The result of getTrainTypeResult is {}", trainTypeResponse.toString()); } else { - SeatServiceImpl.LOGGER.info("[getLeftTicketOfInterval] TrainNumber start with other capital"); + SeatServiceImpl.LOGGER.info("[getLeftTicketOfInterval][TrainNumber start with other capital][trainNumber:{}]", trainNumber); //Call the micro service to query all the station information for the trains HttpEntity requestEntity = new HttpEntity(null); - re = restTemplate.exchange( - "http://ts-travel2-service:16346/api/v1/travel2service/routes/" + seatRequest.getTrainNumber(), - HttpMethod.GET, - requestEntity, - new ParameterizedTypeReference>() { - }); - routeResult = re.getBody(); - SeatServiceImpl.LOGGER.info("[getLeftTicketOfInterval] The result of getRouteResult is {}", routeResult.toString()); - //Call the micro service to query for residual Ticket information: the set of the Ticket sold for the specified seat type requestEntity = new HttpEntity(seatRequest, null); + String order_other_service_url=getServiceUrl("ts-order-other-service"); re3 = restTemplate.exchange( - "http://ts-order-other-service:12032/api/v1/orderOtherService/orderOther/tickets", + order_other_service_url + "/api/v1/orderOtherService/orderOther/tickets", HttpMethod.POST, requestEntity, new ParameterizedTypeReference>() { }); - SeatServiceImpl.LOGGER.info("Get Order tickets result is : {}", re3); + SeatServiceImpl.LOGGER.info("[getLeftTicketOfInterval][Get Order tickets result][result is {}]", re3); leftTicketInfo = re3.getBody().getData(); - - - //Calls the microservice to query the total number of seats specified for that vehicle - requestEntity = new HttpEntity(null); - re2 = restTemplate.exchange( - "http://ts-travel2-service:16346/api/v1/travel2service/train_types/" + seatRequest.getTrainNumber(), - HttpMethod.GET, - requestEntity, - new ParameterizedTypeReference>() { - }); - Response trainTypeResponse = re2.getBody(); - trainTypeResult = trainTypeResponse.getData(); - SeatServiceImpl.LOGGER.info("[getLeftTicketOfInterval] The result of getTrainTypeResult is {}", trainTypeResponse.toString()); } //Counting the seats remaining in certain sections - List stationList = routeResult.getData().getStations(); - int seatTotalNum; - if (seatRequest.getSeatType() == SeatClass.FIRSTCLASS.getCode()) { - seatTotalNum = trainTypeResult.getConfortClass(); - SeatServiceImpl.LOGGER.info("[getLeftTicketOfInterval] The request seat type is confortClass and the total num is {}", seatTotalNum); - } else { - seatTotalNum = trainTypeResult.getEconomyClass(); - SeatServiceImpl.LOGGER.info("[getLeftTicketOfInterval] The request seat type is economyClass and the total num is {}", seatTotalNum); - } - + List stationList = seatRequest.getStations(); + int seatTotalNum = seatRequest.getTotalNum(); int solidTicketSize = 0; if (leftTicketInfo != null) { String startStation = seatRequest.getStartStation(); @@ -279,7 +180,7 @@ public Response getLeftTicketOfInterval(Seat seatRequest, HttpHeaders headers) { String soldTicketDestStation = soldTicket.getDestStation(); //Tickets can be allocated if the sold ticket's end station before the start station of the request if (stationList.indexOf(soldTicketDestStation) < stationList.indexOf(startStation)) { - SeatServiceImpl.LOGGER.info("[getLeftTicketOfInterval] The previous distributed seat number is usable! {}", soldTicket.getSeatNo()); + SeatServiceImpl.LOGGER.info("[getLeftTicketOfInterval][Ticket available or sold][The previous distributed seat number is usable][{}]", soldTicket.getSeatNo()); numOfLeftTicket++; } } @@ -287,9 +188,9 @@ public Response getLeftTicketOfInterval(Seat seatRequest, HttpHeaders headers) { //Count the unsold tickets double direstPart = getDirectProportion(headers); - Route route = routeResult.getData(); - if (route.getStations().get(0).equals(seatRequest.getStartStation()) && - route.getStations().get(route.getStations().size() - 1).equals(seatRequest.getDestStation())) { + + if (stationList.get(0).equals(seatRequest.getStartStation()) && + stationList.get(stationList.size() - 1).equals(seatRequest.getDestStation())) { //do nothing } else { direstPart = 1.0 - direstPart; @@ -305,14 +206,15 @@ private double getDirectProportion(HttpHeaders headers) { String configName = "DirectTicketAllocationProportion"; HttpEntity requestEntity = new HttpEntity(null); + String config_service_url = getServiceUrl("ts-config-service"); ResponseEntity> re = restTemplate.exchange( - "http://ts-config-service:15679/api/v1/configservice/configs/" + configName, + config_service_url + "/api/v1/configservice/configs/" + configName, HttpMethod.GET, requestEntity, new ParameterizedTypeReference>() { }); Response configValue = re.getBody(); - SeatServiceImpl.LOGGER.info("Configs is : {}", configValue.getData().toString()); + SeatServiceImpl.LOGGER.info("[getDirectProportion][Configs is : {}]", configValue.getData().toString()); return Double.parseDouble(configValue.getData().getValue()); } } \ No newline at end of file diff --git a/ts-seat-service/src/main/resources/application.yml b/ts-seat-service/src/main/resources/application.yml index 566f26893..f0d3a8560 100644 --- a/ts-seat-service/src/main/resources/application.yml +++ b/ts-seat-service/src/main/resources/application.yml @@ -2,8 +2,12 @@ server: port: 18898 spring: + cloud: + nacos: + discovery: + server-addr: ${NACOS_ADDRS:nacos-0.nacos-headless.default.svc.cluster.local,nacos-1.nacos-headless.default.svc.cluster.local,nacos-2.nacos-headless.default.svc.cluster.local} application: name: ts-seat-service swagger: - controllerPackage: seat.controller \ No newline at end of file + controllerPackage: seat.controller diff --git a/ts-seat-service/src/test/java/seat/controller/SeatControllerTest.java b/ts-seat-service/src/test/java/seat/controller/SeatControllerTest.java index 367cbf0af..59c19f4e3 100644 --- a/ts-seat-service/src/test/java/seat/controller/SeatControllerTest.java +++ b/ts-seat-service/src/test/java/seat/controller/SeatControllerTest.java @@ -16,7 +16,7 @@ import org.springframework.test.web.servlet.request.MockMvcRequestBuilders; import org.springframework.test.web.servlet.result.MockMvcResultMatchers; import org.springframework.test.web.servlet.setup.MockMvcBuilders; -import seat.entity.Seat; +import edu.fudan.common.entity.Seat; import seat.service.SeatService; @RunWith(JUnit4.class) diff --git a/ts-seat-service/src/test/java/seat/service/SeatServiceImplTest.java b/ts-seat-service/src/test/java/seat/service/SeatServiceImplTest.java index aa71f986c..d5dcb27f6 100644 --- a/ts-seat-service/src/test/java/seat/service/SeatServiceImplTest.java +++ b/ts-seat-service/src/test/java/seat/service/SeatServiceImplTest.java @@ -13,7 +13,7 @@ import org.springframework.core.ParameterizedTypeReference; import org.springframework.http.*; import org.springframework.web.client.RestTemplate; -import seat.entity.*; +import edu.fudan.common.entity.*; import java.util.ArrayList; diff --git a/ts-security-service/pom.xml b/ts-security-service/pom.xml index 931362ab4..6a40d5ce5 100644 --- a/ts-security-service/pom.xml +++ b/ts-security-service/pom.xml @@ -15,7 +15,7 @@ org.services ts-service 0.1.0 - ../ + ../pom.xml @@ -26,17 +26,18 @@ org.springframework.boot - spring-boot-starter-data-mongodb + spring-boot-starter-data-jpa + + + mysql + mysql-connector-java org.services ts-common 0.1.0 - - - diff --git a/ts-security-service/src/main/java/security/SecurityApplication.java b/ts-security-service/src/main/java/security/SecurityApplication.java index 6607a8b1c..4ba18055b 100644 --- a/ts-security-service/src/main/java/security/SecurityApplication.java +++ b/ts-security-service/src/main/java/security/SecurityApplication.java @@ -3,6 +3,8 @@ import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.boot.web.client.RestTemplateBuilder; +import org.springframework.cloud.client.discovery.EnableDiscoveryClient; +import org.springframework.cloud.client.loadbalancer.LoadBalanced; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.EnableAspectJAutoProxy; import org.springframework.integration.annotation.IntegrationComponentScan; @@ -18,12 +20,14 @@ @EnableAsync @IntegrationComponentScan @EnableSwagger2 +@EnableDiscoveryClient public class SecurityApplication { public static void main(String[] args) { SpringApplication.run(SecurityApplication.class, args); } + @LoadBalanced @Bean public RestTemplate restTemplate(RestTemplateBuilder builder) { return builder.build(); diff --git a/ts-security-service/src/main/java/security/controller/SecurityController.java b/ts-security-service/src/main/java/security/controller/SecurityController.java index 09b35df54..396e06ae9 100644 --- a/ts-security-service/src/main/java/security/controller/SecurityController.java +++ b/ts-security-service/src/main/java/security/controller/SecurityController.java @@ -31,35 +31,35 @@ public String home(@RequestHeader HttpHeaders headers) { @CrossOrigin(origins = "*") @GetMapping(path = "/securityConfigs") public HttpEntity findAllSecurityConfig(@RequestHeader HttpHeaders headers) { - SecurityController.LOGGER.info("[Find All]"); + SecurityController.LOGGER.info("[findAllSecurityConfig][Find All]"); return ok(securityService.findAllSecurityConfig(headers)); } @CrossOrigin(origins = "*") @PostMapping(path = "/securityConfigs") public HttpEntity create(@RequestBody SecurityConfig info, @RequestHeader HttpHeaders headers) { - SecurityController.LOGGER.info("[Create] SecurityConfig Name: {}", info.getName()); + SecurityController.LOGGER.info("[addNewSecurityConfig][Create][SecurityConfig Name: {}]", info.getName()); return ok(securityService.addNewSecurityConfig(info, headers)); } @CrossOrigin(origins = "*") @PutMapping(path = "/securityConfigs") public HttpEntity update(@RequestBody SecurityConfig info, @RequestHeader HttpHeaders headers) { - SecurityController.LOGGER.info("[Update] SecurityConfig Name: {}", info.getName()); + SecurityController.LOGGER.info("[modifySecurityConfig][Update][SecurityConfig Name: {}]", info.getName()); return ok(securityService.modifySecurityConfig(info, headers)); } @CrossOrigin(origins = "*") @DeleteMapping(path = "/securityConfigs/{id}") public HttpEntity delete(@PathVariable String id, @RequestHeader HttpHeaders headers) { - SecurityController.LOGGER.info("[Delete] SecurityConfig Id: {}", id); + SecurityController.LOGGER.info("[deleteSecurityConfig][Delete][SecurityConfig Id: {}]", id); return ok(securityService.deleteSecurityConfig(id, headers)); } @CrossOrigin(origins = "*") @GetMapping(path = "/securityConfigs/{accountId}") public HttpEntity check(@PathVariable String accountId, @RequestHeader HttpHeaders headers) { - SecurityController.LOGGER.info("[Check Security] Check Account Id: {}", accountId); + SecurityController.LOGGER.info("[check][Check Security][Check Account Id: {}]", accountId); return ok(securityService.check(accountId, headers)); } diff --git a/ts-security-service/src/main/java/security/entity/Order.java b/ts-security-service/src/main/java/security/entity/Order.java deleted file mode 100644 index 59337ca48..000000000 --- a/ts-security-service/src/main/java/security/entity/Order.java +++ /dev/null @@ -1,110 +0,0 @@ -package security.entity; - -import com.fasterxml.jackson.annotation.JsonIgnoreProperties; -import lombok.Data; - -import java.util.Date; -import java.util.UUID; - -/** - * @author fdse - */ -@Data -@JsonIgnoreProperties(ignoreUnknown = true) -public class Order { - - private UUID id; - - private Date boughtDate; - - - private Date travelDate; - - - private Date travelTime; - - /** - * Which Account Bought it - */ - private UUID accountId; - - /** - * Tickets bought for whom.... - */ - private String contactsName; - - private int documentType; - - private String contactsDocumentNumber; - - private String trainNumber; - - private int coachNumber; - - private int seatClass; - - private String seatNumber; - - private String from; - - private String to; - - private int status; - - private String price; - - public Order(){ - boughtDate = new Date(System.currentTimeMillis()); - travelDate = new Date(123456789); - trainNumber = "G1235"; - coachNumber = 5; - seatClass = SeatClass.FIRSTCLASS.getCode(); - seatNumber = "5A"; - from = "上海"; - to = "太原"; - status = OrderStatus.PAID.getCode(); - price = "0.0"; - } - - @Override - public boolean equals(Object obj) { - if (this == obj) { - return true; - } - if (obj == null) { - return false; - } - if (getClass() != obj.getClass()) { - return false; - } - Order other = (Order) obj; - return boughtDate.equals(other.getBoughtDate()) - && travelDate.equals(other.getTravelDate()) - && travelTime.equals(other.getTravelTime()) - && accountId .equals( other.getAccountId() ) - && contactsName.equals(other.getContactsName()) - && contactsDocumentNumber.equals(other.getContactsDocumentNumber()) - && documentType == other.getDocumentType() - && trainNumber.equals(other.getTrainNumber()) - && coachNumber == other.getCoachNumber() - && seatClass == other.getSeatClass() - && seatNumber .equals(other.getSeatNumber()) - && from.equals(other.getFrom()) - && to.equals(other.getTo()) - && status == other.getStatus() - && price == other.price; - } - - @Override - public int hashCode() { - int result = 17; - result = 31 * result + (id == null ? 0 : id.hashCode()); - return result; - } - - public void setTravelDate(int year,int month,int day){ - Date date = new Date(year,month,day,0,0,0); //NOSONAR - this.travelDate = date; - } - -} diff --git a/ts-security-service/src/main/java/security/entity/OrderStatus.java b/ts-security-service/src/main/java/security/entity/OrderStatus.java deleted file mode 100644 index 429d8e3e3..000000000 --- a/ts-security-service/src/main/java/security/entity/OrderStatus.java +++ /dev/null @@ -1,63 +0,0 @@ -package security.entity; - -/** - * @author fdse - */ -public enum OrderStatus { - - /** - * not paid - */ - NOTPAID (0,"Not Paid"), - /** - * paid and not collected - */ - PAID (1,"Paid & Not Collected"), - /** - * collected - */ - COLLECTED (2,"Collected"), - /** - * cancel and rebook - */ - CHANGE (3,"Cancel & Rebook"), - /** - * cancel - */ - CANCEL (4,"Cancel"), - /** - * refunded - */ - REFUNDS (5,"Refunded"), - /** - * used - */ - USED (6,"Used"); - - private int code; - private String name; - - OrderStatus(int code, String name){ - this.code = code; - this.name = name; - } - - public int getCode(){ - return code; - } - - public String getName() { - return name; - } - - public static String getNameByCode(int code){ - OrderStatus[] orderStatusSet = OrderStatus.values(); - for(OrderStatus orderStatus : orderStatusSet){ - if(orderStatus.getCode() == code){ - return orderStatus.getName(); - } - } - return orderStatusSet[0].getName(); - } - -} diff --git a/ts-security-service/src/main/java/security/entity/SeatClass.java b/ts-security-service/src/main/java/security/entity/SeatClass.java deleted file mode 100644 index beb0e98c4..000000000 --- a/ts-security-service/src/main/java/security/entity/SeatClass.java +++ /dev/null @@ -1,70 +0,0 @@ -package security.entity; - -/** - * @author fdse - */ -public enum SeatClass { - - /** - * no seat - */ - NONE (0,"NoSeat"), - /** - * green seat - */ - BUSINESS (1,"GreenSeat"), - /** - * first class seat - */ - FIRSTCLASS (2,"FirstClassSeat"), - /** - * second class seat - */ - SECONDCLASS (3,"SecondClassSeat"), - /** - * hard seat - */ - HARDSEAT (4,"HardSeat"), - /** - * soft seat - */ - SOFTSEAT (5,"SoftSeat"), - /** - * hard bed - */ - HARDBED (6,"HardBed"), - /** - * soft bed - */ - SOFTBED (7,"SoftBed"), - /** - * high soft seat - */ - HIGHSOFTBED (8,"HighSoftSeat"); - - private int code; - private String name; - - SeatClass(int code, String name){ - this.code = code; - this.name = name; - } - - public int getCode(){ - return code; - } - - public String getName() { - return name; - } - - public static String getNameByCode(int code){ - SeatClass[] seatClassSet = SeatClass.values(); - for(SeatClass seatClass : seatClassSet){ - if(seatClass.getCode() == code){ - return seatClass.getName(); - } - } - return seatClassSet[0].getName(); - } -} diff --git a/ts-security-service/src/main/java/security/entity/SecurityConfig.java b/ts-security-service/src/main/java/security/entity/SecurityConfig.java index 755a937a7..e9f1bef76 100644 --- a/ts-security-service/src/main/java/security/entity/SecurityConfig.java +++ b/ts-security-service/src/main/java/security/entity/SecurityConfig.java @@ -2,18 +2,28 @@ import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import lombok.Data; -import org.springframework.data.mongodb.core.mapping.Document; +import org.hibernate.annotations.GenericGenerator; + +import javax.persistence.Column; +import javax.persistence.GeneratedValue; +import javax.persistence.Id; +import javax.persistence.Entity; + import java.util.UUID; /** * @author fdse */ @Data -@Document(collection = "security_config") +@Entity +@GenericGenerator(name = "jpa-uuid", strategy = "org.hibernate.id.UUIDGenerator") @JsonIgnoreProperties(ignoreUnknown = true) public class SecurityConfig { - private UUID id; + @Id + @GeneratedValue(generator = "jpa-uuid") + @Column(length = 36) + private String id; private String name; diff --git a/ts-security-service/src/main/java/security/repository/SecurityRepository.java b/ts-security-service/src/main/java/security/repository/SecurityRepository.java index 37052109f..9ed971502 100644 --- a/ts-security-service/src/main/java/security/repository/SecurityRepository.java +++ b/ts-security-service/src/main/java/security/repository/SecurityRepository.java @@ -1,26 +1,26 @@ package security.repository; -import org.springframework.data.mongodb.repository.MongoRepository; -import org.springframework.data.mongodb.repository.Query; + +import org.springframework.data.repository.CrudRepository; import org.springframework.stereotype.Repository; import security.entity.SecurityConfig; import java.util.ArrayList; -import java.util.UUID; +import java.util.Optional; /** * @author fdse */ @Repository -public interface SecurityRepository extends MongoRepository{ +public interface SecurityRepository extends CrudRepository { + - @Query("{ 'name': ?0 }") SecurityConfig findByName(String name); - @Query("{ 'id': ?0 }") - SecurityConfig findById(UUID id); + + Optional findById(String id); @Override ArrayList findAll(); - void deleteById(UUID id); + void deleteById(String id); } diff --git a/ts-security-service/src/main/java/security/service/SecurityServiceImpl.java b/ts-security-service/src/main/java/security/service/SecurityServiceImpl.java index 40aa84b37..d2e15d37f 100644 --- a/ts-security-service/src/main/java/security/service/SecurityServiceImpl.java +++ b/ts-security-service/src/main/java/security/service/SecurityServiceImpl.java @@ -1,22 +1,29 @@ package security.service; +import edu.fudan.common.entity.OrderSecurity; import edu.fudan.common.util.Response; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.cloud.client.ServiceInstance; +import org.springframework.cloud.client.discovery.DiscoveryClient; +import org.springframework.cloud.client.ServiceInstance; import org.springframework.core.ParameterizedTypeReference; import org.springframework.http.HttpEntity; import org.springframework.http.HttpHeaders; import org.springframework.http.HttpMethod; import org.springframework.http.ResponseEntity; import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; import org.springframework.web.client.RestTemplate; -import security.entity.*; +import security.entity.SecurityConfig; import security.repository.SecurityRepository; import java.util.ArrayList; import java.util.Date; +import java.util.List; import java.util.UUID; /** @@ -31,8 +38,15 @@ public class SecurityServiceImpl implements SecurityService { @Autowired RestTemplate restTemplate; + @Autowired + private DiscoveryClient discoveryClient; + private static final Logger LOGGER = LoggerFactory.getLogger(SecurityServiceImpl.class); + private String getServiceUrl(String serviceName) { + return "http://" + serviceName; + } + String success = "Success"; @Override @@ -41,7 +55,7 @@ public Response findAllSecurityConfig(HttpHeaders headers) { if (securityConfigs != null && !securityConfigs.isEmpty()) { return new Response<>(1, success, securityConfigs); } - SecurityServiceImpl.LOGGER.warn("Find all security config warn: {}","No content"); + SecurityServiceImpl.LOGGER.warn("[findAllSecurityConfig][Find all security config warn][{}]","No content"); return new Response<>(0, "No Content", null); } @@ -49,11 +63,11 @@ public Response findAllSecurityConfig(HttpHeaders headers) { public Response addNewSecurityConfig(SecurityConfig info, HttpHeaders headers) { SecurityConfig sc = securityRepository.findByName(info.getName()); if (sc != null) { - SecurityServiceImpl.LOGGER.warn("Add new Security config warn.Security config already exist, SecurityConfigId: {},Name: {}",sc.getId(),info.getName()); + SecurityServiceImpl.LOGGER.warn("[addNewSecurityConfig][Add new Security config warn][Security config already exist][SecurityConfigId: {},Name: {}]",sc.getId(),info.getName()); return new Response<>(0, "Security Config Already Exist", null); } else { SecurityConfig config = new SecurityConfig(); - config.setId(UUID.randomUUID()); + config.setId(UUID.randomUUID().toString()); config.setName(info.getName()); config.setValue(info.getValue()); config.setDescription(info.getDescription()); @@ -64,9 +78,9 @@ public Response addNewSecurityConfig(SecurityConfig info, HttpHeaders headers) { @Override public Response modifySecurityConfig(SecurityConfig info, HttpHeaders headers) { - SecurityConfig sc = securityRepository.findById(info.getId()); + SecurityConfig sc = securityRepository.findById(info.getId()).orElse(null); if (sc == null) { - SecurityServiceImpl.LOGGER.error("Modify Security config error.Security config not found, SecurityConfigId: {},Name: {}",info.getId(),info.getName()); + SecurityServiceImpl.LOGGER.error("[modifySecurityConfig][Modify Security config error][Security config not found][SecurityConfigId: {},Name: {}]",info.getId(),info.getName()); return new Response<>(0, "Security Config Not Exist", null); } else { sc.setName(info.getName()); @@ -77,14 +91,15 @@ public Response modifySecurityConfig(SecurityConfig info, HttpHeaders headers) { } } + @Transactional @Override public Response deleteSecurityConfig(String id, HttpHeaders headers) { - securityRepository.deleteById(UUID.fromString(id)); - SecurityConfig sc = securityRepository.findById(UUID.fromString(id)); + securityRepository.deleteById(id); + SecurityConfig sc = securityRepository.findById(id).orElse(null); if (sc == null) { return new Response<>(1, success, id); } else { - SecurityServiceImpl.LOGGER.error("Delete Security config error.Reason not clear, SecurityConfigId: {}",id); + SecurityServiceImpl.LOGGER.error("[deleteSecurityConfig][Delete Security config error][Reason not clear][SecurityConfigId: {}]",id); return new Response<>(0, "Reason Not clear", id); } } @@ -92,20 +107,20 @@ public Response deleteSecurityConfig(String id, HttpHeaders headers) { @Override public Response check(String accountId, HttpHeaders headers) { //1.Get the orders in the past one hour and the total effective votes - SecurityServiceImpl.LOGGER.info("[Get Order Num Info]"); + SecurityServiceImpl.LOGGER.debug("[check][Get Order Num Info]"); OrderSecurity orderResult = getSecurityOrderInfoFromOrder(new Date(), accountId, headers); OrderSecurity orderOtherResult = getSecurityOrderOtherInfoFromOrder(new Date(), accountId, headers); int orderInOneHour = orderOtherResult.getOrderNumInLastOneHour() + orderResult.getOrderNumInLastOneHour(); int totalValidOrder = orderOtherResult.getOrderNumOfValidOrder() + orderResult.getOrderNumOfValidOrder(); //2. get critical configuration information - SecurityServiceImpl.LOGGER.info("[Get Security Config Info]"); + SecurityServiceImpl.LOGGER.debug("[check][Get Security Config Info]"); SecurityConfig configMaxInHour = securityRepository.findByName("max_order_1_hour"); SecurityConfig configMaxNotUse = securityRepository.findByName("max_order_not_use"); - SecurityServiceImpl.LOGGER.info("Max In One Hour: {} Max Not Use: {}", configMaxInHour.getValue(), configMaxNotUse.getValue()); + SecurityServiceImpl.LOGGER.info("[check][Max][Max In One Hour: {} Max Not Use: {}]", configMaxInHour.getValue(), configMaxNotUse.getValue()); int oneHourLine = Integer.parseInt(configMaxInHour.getValue()); int totalValidLine = Integer.parseInt(configMaxNotUse.getValue()); if (orderInOneHour > oneHourLine || totalValidOrder > totalValidLine) { - SecurityServiceImpl.LOGGER.warn("Check Security config warn.Too much order in last one hour or too much valid order, AccountId: {}",accountId); + SecurityServiceImpl.LOGGER.warn("[check][Check Security config warn][Too much order in last one hour or too much valid order][AccountId: {}]",accountId); return new Response<>(0, "Too much order in last one hour or too much valid order", accountId); } else { return new Response<>(1, "Success.r", accountId); @@ -113,32 +128,32 @@ public Response check(String accountId, HttpHeaders headers) { } private OrderSecurity getSecurityOrderInfoFromOrder(Date checkDate, String accountId, HttpHeaders headers) { - SecurityServiceImpl.LOGGER.info("[Get Order Info For Security] Getting...."); HttpEntity requestEntity = new HttpEntity(null); + String order_service_url = getServiceUrl("ts-order-service"); ResponseEntity> re = restTemplate.exchange( - "http://ts-order-service:12031/api/v1/orderservice/order/security/" + checkDate + "/" + accountId, + order_service_url + "/api/v1/orderservice/order/security/" + checkDate + "/" + accountId, HttpMethod.GET, requestEntity, new ParameterizedTypeReference>() { }); Response response = re.getBody(); OrderSecurity result = response.getData(); - SecurityServiceImpl.LOGGER.info("[Get Order Info For Security] Last One Hour: {} Total Valid Order: {}", result.getOrderNumInLastOneHour(), result.getOrderNumOfValidOrder()); + SecurityServiceImpl.LOGGER.info("[getSecurityOrderInfoFromOrder][Get Order Info For Security][Last One Hour: {} Total Valid Order: {}]", result.getOrderNumInLastOneHour(), result.getOrderNumOfValidOrder()); return result; } private OrderSecurity getSecurityOrderOtherInfoFromOrder(Date checkDate, String accountId, HttpHeaders headers) { - SecurityServiceImpl.LOGGER.info("[Get Order Other Info For Security] Getting...."); HttpEntity requestEntity = new HttpEntity(null); + String order_other_service_url = getServiceUrl("ts-order-other-service"); ResponseEntity> re = restTemplate.exchange( - "http://ts-order-other-service:12032/api/v1/orderOtherService/orderOther/security/" + checkDate + "/" + accountId, + order_other_service_url + "/api/v1/orderOtherService/orderOther/security/" + checkDate + "/" + accountId, HttpMethod.GET, requestEntity, new ParameterizedTypeReference>() { }); Response response = re.getBody(); OrderSecurity result = response.getData(); - SecurityServiceImpl.LOGGER.info("[Get Order Other Info For Security] Last One Hour: {} Total Valid Order: {}", result.getOrderNumInLastOneHour(), result.getOrderNumOfValidOrder()); + SecurityServiceImpl.LOGGER.info("[getSecurityOrderOtherInfoFromOrder][Get Order Other Info For Security][Last One Hour: {} Total Valid Order: {}]", result.getOrderNumInLastOneHour(), result.getOrderNumOfValidOrder()); return result; } diff --git a/ts-security-service/src/main/resources/application.yml b/ts-security-service/src/main/resources/application.yml index 702460eba..47197e9b3 100644 --- a/ts-security-service/src/main/resources/application.yml +++ b/ts-security-service/src/main/resources/application.yml @@ -1,17 +1,33 @@ spring: + cloud: + nacos: + discovery: + server-addr: ${NACOS_ADDRS:nacos-0.nacos-headless.default.svc.cluster.local,nacos-1.nacos-headless.default.svc.cluster.local,nacos-2.nacos-headless.default.svc.cluster.local} application: name: ts-security-service - data: - mongodb: - host: ts-security-mongo -# username: user -# password: ${MONGODB_PASSWORD} - database: ts - port: 27017 + + datasource: + url: jdbc:mysql://${SECURITY_MYSQL_HOST:ts-security-mysql}:${SECURITY_MYSQL_PORT:3306}/${SECURITY_MYSQL_DATABASE:ts-security-mysql}?useSSL=false + username: ${SECURITY_MYSQL_USER:root} + password: ${SECURITY_MYSQL_PASSWORD:root} + driver-class-name: com.mysql.cj.jdbc.Driver + + jpa: + hibernate: + ddl-auto: update + properties: + hibernate: + dialect: org.hibernate.dialect.MySQL5Dialect # HTTP Server server: port: 11188 # HTTP (Tomcat) port swagger: - controllerPackage: security.controller \ No newline at end of file + controllerPackage: security.controller + +order-service: + url: http://${ORDER_SERVICE_HOST:ts-order-service}:${ORDER_SERVICE_PORT:12031} + +order-other-service: + url: http://${ORDER_OTHER_SERVICE_HOST:ts-order-other-service}:${ORDER_OTHER_SERVICE_PORT:12032} \ No newline at end of file diff --git a/ts-security-service/src/test/java/security/service/SecurityServiceImplTest.java b/ts-security-service/src/test/java/security/service/SecurityServiceImplTest.java index 4baa883b9..7e35c19bf 100644 --- a/ts-security-service/src/test/java/security/service/SecurityServiceImplTest.java +++ b/ts-security-service/src/test/java/security/service/SecurityServiceImplTest.java @@ -1,5 +1,6 @@ package security.service; +import edu.fudan.common.entity.OrderSecurity; import edu.fudan.common.util.Response; import org.junit.Assert; import org.junit.Before; @@ -13,11 +14,11 @@ import org.springframework.core.ParameterizedTypeReference; import org.springframework.http.*; import org.springframework.web.client.RestTemplate; -import security.entity.OrderSecurity; import security.entity.SecurityConfig; import security.repository.SecurityRepository; import java.util.ArrayList; +import java.util.Optional; import java.util.UUID; @RunWith(JUnit4.class) @@ -75,7 +76,7 @@ public void testAddNewSecurityConfig2() { @Test public void testModifySecurityConfig1() { SecurityConfig sc = new SecurityConfig(); - Mockito.when(securityRepository.findById(Mockito.any(UUID.class))).thenReturn(null); + Mockito.when(securityRepository.findById(Mockito.any(UUID.class).toString())).thenReturn(null); Response result = securityServiceImpl.modifySecurityConfig(sc, headers); Assert.assertEquals(new Response<>(0, "Security Config Not Exist", null), result); } @@ -83,7 +84,7 @@ public void testModifySecurityConfig1() { @Test public void testModifySecurityConfig2() { SecurityConfig sc = new SecurityConfig(); - Mockito.when(securityRepository.findById(Mockito.any(UUID.class))).thenReturn(sc); + Mockito.when(securityRepository.findById(Mockito.any(UUID.class).toString())).thenReturn(Optional.of(sc)); Mockito.when(securityRepository.save(Mockito.any(SecurityConfig.class))).thenReturn(null); Response result = securityServiceImpl.modifySecurityConfig(sc, headers); Assert.assertEquals(new Response<>(1, "Success", sc), result); @@ -92,8 +93,8 @@ public void testModifySecurityConfig2() { @Test public void testDeleteSecurityConfig1() { UUID id = UUID.randomUUID(); - Mockito.doNothing().doThrow(new RuntimeException()).when(securityRepository).deleteById(Mockito.any(UUID.class)); - Mockito.when(securityRepository.findById(Mockito.any(UUID.class))).thenReturn(null); + Mockito.doNothing().doThrow(new RuntimeException()).when(securityRepository).deleteById(Mockito.any(UUID.class).toString()); + Mockito.when(securityRepository.findById(Mockito.any(UUID.class).toString())).thenReturn(null); Response result = securityServiceImpl.deleteSecurityConfig(id.toString(), headers); Assert.assertEquals(new Response<>(1, "Success", id.toString()), result); } @@ -102,8 +103,8 @@ public void testDeleteSecurityConfig1() { public void testDeleteSecurityConfig2() { UUID id = UUID.randomUUID(); SecurityConfig sc = new SecurityConfig(); - Mockito.doNothing().doThrow(new RuntimeException()).when(securityRepository).deleteById(Mockito.any(UUID.class)); - Mockito.when(securityRepository.findById(Mockito.any(UUID.class))).thenReturn(sc); + Mockito.doNothing().doThrow(new RuntimeException()).when(securityRepository).deleteById(Mockito.any(UUID.class).toString()); + Mockito.when(securityRepository.findById(Mockito.any(UUID.class).toString())).thenReturn(Optional.of(sc)); Response result = securityServiceImpl.deleteSecurityConfig(id.toString(), headers); Assert.assertEquals("Reason Not clear", result.getMsg()); } diff --git a/ts-station-food-service/Dockerfile b/ts-station-food-service/Dockerfile new file mode 100644 index 000000000..0fc92f341 --- /dev/null +++ b/ts-station-food-service/Dockerfile @@ -0,0 +1,8 @@ +FROM java:8-jre + +RUN /bin/cp /usr/share/zoneinfo/Asia/Shanghai /etc/localtime && echo 'Asia/Shanghai' >/etc/timezone + +ADD ./target/ts-station-food-service-1.0.jar /app/ +CMD ["java", "-Xmx200m", "-jar", "/app/ts-station-food-service-1.0.jar"] + +EXPOSE 18855 diff --git a/ts-ticketinfo-service/pom.xml b/ts-station-food-service/pom.xml similarity index 64% rename from ts-ticketinfo-service/pom.xml rename to ts-station-food-service/pom.xml index 1357bb9f2..c660e4e12 100644 --- a/ts-ticketinfo-service/pom.xml +++ b/ts-station-food-service/pom.xml @@ -5,36 +5,44 @@ 4.0.0 fdse.microservice - ts-ticketinfo-service + ts-station-food-service 1.0 jar - ts-ticketinfo-service - ts-ticketinfo-service + ts-station-food-service org.services ts-service 0.1.0 - ../ + ../pom.xml UTF-8 - UTF-8 1.8 + + org.springframework.boot + spring-boot-starter-data-jpa + + + mysql + mysql-connector-java + org.services ts-common 0.1.0 - - + + jakarta.validation + jakarta.validation-api + 2.0.2 + - @@ -43,4 +51,6 @@ + + \ No newline at end of file diff --git a/ts-ticketinfo-service/src/main/java/ticketinfo/TicketInfoApplication.java b/ts-station-food-service/src/main/java/food/StationFoodApplication.java similarity index 74% rename from ts-ticketinfo-service/src/main/java/ticketinfo/TicketInfoApplication.java rename to ts-station-food-service/src/main/java/food/StationFoodApplication.java index 5f2d4e7a5..c4bdf5e38 100644 --- a/ts-ticketinfo-service/src/main/java/ticketinfo/TicketInfoApplication.java +++ b/ts-station-food-service/src/main/java/food/StationFoodApplication.java @@ -1,8 +1,10 @@ -package ticketinfo; +package food; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.boot.web.client.RestTemplateBuilder; +import org.springframework.cloud.client.discovery.EnableDiscoveryClient; +import org.springframework.cloud.client.loadbalancer.LoadBalanced; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.EnableAspectJAutoProxy; import org.springframework.integration.annotation.IntegrationComponentScan; @@ -10,18 +12,19 @@ import org.springframework.web.client.RestTemplate; import springfox.documentation.swagger2.annotations.EnableSwagger2; - @SpringBootApplication @EnableAspectJAutoProxy(proxyTargetClass = true) @EnableAsync @IntegrationComponentScan @EnableSwagger2 -public class TicketInfoApplication { +@EnableDiscoveryClient +public class StationFoodApplication { public static void main(String[] args) { - SpringApplication.run(TicketInfoApplication.class, args); + SpringApplication.run(StationFoodApplication.class, args); } + @LoadBalanced @Bean public RestTemplate restTemplate(RestTemplateBuilder builder) { return builder.build(); diff --git a/ts-food-map-service/src/main/java/food/config/SecurityConfig.java b/ts-station-food-service/src/main/java/food/config/SecurityConfig.java similarity index 97% rename from ts-food-map-service/src/main/java/food/config/SecurityConfig.java rename to ts-station-food-service/src/main/java/food/config/SecurityConfig.java index 1fe476724..14a8b86c4 100644 --- a/ts-food-map-service/src/main/java/food/config/SecurityConfig.java +++ b/ts-station-food-service/src/main/java/food/config/SecurityConfig.java @@ -61,7 +61,7 @@ protected void configure(HttpSecurity httpSecurity) throws Exception { .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS) .and() .authorizeRequests() - .antMatchers("/api/v1/foodmapservice/**").permitAll() + .antMatchers("/api/v1/stationfoodservice/**").permitAll() .antMatchers("/swagger-ui.html", "/webjars/**", "/images/**", "/configuration/**", "/swagger-resources/**", "/v2/**").permitAll() .anyRequest().authenticated() diff --git a/ts-station-food-service/src/main/java/food/controller/StationFoodController.java b/ts-station-food-service/src/main/java/food/controller/StationFoodController.java new file mode 100644 index 000000000..08e3e87b4 --- /dev/null +++ b/ts-station-food-service/src/main/java/food/controller/StationFoodController.java @@ -0,0 +1,54 @@ +package food.controller; + +import food.service.StationFoodService; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.http.HttpEntity; +import org.springframework.http.HttpHeaders; +import org.springframework.web.bind.annotation.*; + +import java.util.List; + +import static org.springframework.http.ResponseEntity.ok; + +@RestController +@RequestMapping("/api/v1/stationfoodservice") +public class StationFoodController { + + @Autowired + StationFoodService stationFoodService; + + private static final Logger LOGGER = LoggerFactory.getLogger(StationFoodController.class); + + @GetMapping(path = "/stationfoodstores/welcome") + public String home() { + return "Welcome to [ Food store Service ] !"; + } + + @CrossOrigin(origins = "*") + @GetMapping("/stationfoodstores") + public HttpEntity getAllFoodStores(@RequestHeader HttpHeaders headers) { + StationFoodController.LOGGER.info("[Food Map Service][Get All FoodStores]"); + return ok(stationFoodService.listFoodStores(headers)); + } + + @CrossOrigin(origins = "*") + @GetMapping("/stationfoodstores/{stationId}") + public HttpEntity getFoodStoresOfStation(@PathVariable String stationName, @RequestHeader HttpHeaders headers) { + StationFoodController.LOGGER.info("[Food Map Service][Get FoodStores By StationName]"); + return ok(stationFoodService.listFoodStoresByStationName(stationName, headers)); + } + + @CrossOrigin(origins = "*") + @PostMapping("/stationfoodstores") + public HttpEntity getFoodStoresByStationNames(@RequestBody List stationNameList) { + StationFoodController.LOGGER.info("[Food Map Service][Get FoodStores By StationNames]"); + return ok(stationFoodService.getFoodStoresByStationNames(stationNameList)); + } + @GetMapping("/stationfoodstores/bystoreid/{stationFoodStoreId}") + public HttpEntity getFoodListByStationFoodStoreId(@PathVariable String stationFoodStoreId, @RequestHeader HttpHeaders headers) { + StationFoodController.LOGGER.info("[Food Map Service][Get Foodlist By stationFoodStoreId]"); + return ok(stationFoodService.getStaionFoodStoreById(stationFoodStoreId)); + } +} diff --git a/ts-station-food-service/src/main/java/food/entity/StationFoodStore.java b/ts-station-food-service/src/main/java/food/entity/StationFoodStore.java new file mode 100644 index 000000000..4697893de --- /dev/null +++ b/ts-station-food-service/src/main/java/food/entity/StationFoodStore.java @@ -0,0 +1,47 @@ +package food.entity; + +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import edu.fudan.common.entity.Food; +import lombok.Data; +import lombok.ToString; +import org.hibernate.annotations.GenericGenerator; + +import javax.persistence.*; +import javax.validation.constraints.NotNull; +import java.util.List; + +@Data +@Entity +@GenericGenerator(name = "jpa-uuid", strategy = "org.hibernate.id.UUIDGenerator") +@ToString +@JsonIgnoreProperties(ignoreUnknown = true) +@Table(indexes = {@Index(name = "station_store_idx", columnList = "station_name, store_name", unique = true)}) +public class StationFoodStore { + + @Id + @Column(name = "store_id") + private String id; + + @NotNull + @Column(name = "station_name") + private String stationName; + + @Column(name = "store_name") + private String storeName; + + private String telephone; + + private String businessTime; + + private double deliveryFee; + + @ElementCollection(targetClass = Food.class, fetch = FetchType.EAGER) + @CollectionTable(name = "station_food_list", joinColumns = @JoinColumn(name = "store_id")) + private List foodList; + + public StationFoodStore(){ + //Default Constructor + this.stationName = ""; + } + +} diff --git a/ts-food-map-service/src/main/java/food/init/InitData.java b/ts-station-food-service/src/main/java/food/init/InitData.java similarity index 65% rename from ts-food-map-service/src/main/java/food/init/InitData.java rename to ts-station-food-service/src/main/java/food/init/InitData.java index 7dd773921..39d8e51b2 100644 --- a/ts-food-map-service/src/main/java/food/init/InitData.java +++ b/ts-station-food-service/src/main/java/food/init/InitData.java @@ -1,9 +1,8 @@ package food.init; -import food.entity.Food; -import food.entity.FoodStore; -import food.entity.TrainFood; -import food.service.FoodMapService; +import edu.fudan.common.entity.Food; +import food.entity.StationFoodStore; +import food.service.StationFoodService; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; @@ -20,7 +19,7 @@ public class InitData implements CommandLineRunner{ @Autowired - FoodMapService service; + StationFoodService service; private static final Logger LOGGER = LoggerFactory.getLogger(InitData.class); @@ -33,10 +32,10 @@ public void run(String... args) throws Exception { String line = br1.readLine(); while( line != null ){ if( !line.trim().equals("") ){ - FoodStore fs = new FoodStore(); - fs.setId(UUID.randomUUID()); + StationFoodStore fs = new StationFoodStore(); + fs.setId(UUID.randomUUID().toString()); String[] lineTemp = line.trim().split("="); - fs.setStationId(lineTemp[1]); + fs.setStationName(lineTemp[1]); lineTemp = br1.readLine().trim().split("="); fs.setStoreName(lineTemp[1]); @@ -64,27 +63,27 @@ public void run(String... args) throws Exception { System.exit(1); } - BufferedReader br2 = new BufferedReader(new InputStreamReader(this.getClass().getResourceAsStream("/trainfood.txt"))); - try{ - String line2 = br2.readLine(); - while( line2 != null ){ - if( !line2.trim().equals("") ){ - TrainFood tf = new TrainFood(); - tf.setId(UUID.randomUUID()); - String[] lineTemp = line2.trim().split("="); - tf.setTripId(lineTemp[1]); - lineTemp = br2.readLine().trim().split("="); - tf.setFoodList(toFoodList(lineTemp[1])); - service.createTrainFood(tf,null); - } - line2 = br2.readLine(); - } - - } catch(Exception e){ - InitData.LOGGER.info("the trainfood.txt has format error!"); - InitData.LOGGER.error(e.getMessage()); - System.exit(1); - } +// BufferedReader br2 = new BufferedReader(new InputStreamReader(this.getClass().getResourceAsStream("/trainfood.txt"))); +// try{ +// String line2 = br2.readLine(); +// while( line2 != null ){ +// if( !line2.trim().equals("") ){ +// TrainFood tf = new TrainFood(); +// tf.setId(UUID.randomUUID()); +// String[] lineTemp = line2.trim().split("="); +// tf.setTripId(lineTemp[1]); +// lineTemp = br2.readLine().trim().split("="); +// tf.setFoodList(toFoodList(lineTemp[1])); +// service.createTrainFood(tf,null); +// } +// line2 = br2.readLine(); +// } +// +// } catch(Exception e){ +// InitData.LOGGER.info("the trainfood.txt has format error!"); +// InitData.LOGGER.error(e.getMessage()); +// System.exit(1); +// } } private List toFoodList(String s){ diff --git a/ts-station-food-service/src/main/java/food/repository/StationFoodRepository.java b/ts-station-food-service/src/main/java/food/repository/StationFoodRepository.java new file mode 100644 index 000000000..ece37ee43 --- /dev/null +++ b/ts-station-food-service/src/main/java/food/repository/StationFoodRepository.java @@ -0,0 +1,26 @@ +package food.repository; + +import food.entity.StationFoodStore; +import org.springframework.data.repository.CrudRepository; +import org.springframework.stereotype.Repository; + +import java.util.List; +import java.util.Optional; +import java.util.UUID; + +@Repository +public interface StationFoodRepository extends CrudRepository { + + @Override + Optional findById(String id); + + List findByStationName(String stationName); + List findByStationNameIn(List stationNames); + + + @Override + List findAll(); + + @Override + void deleteById(String id); +} diff --git a/ts-station-food-service/src/main/java/food/service/StationFoodService.java b/ts-station-food-service/src/main/java/food/service/StationFoodService.java new file mode 100644 index 000000000..02a6e08d7 --- /dev/null +++ b/ts-station-food-service/src/main/java/food/service/StationFoodService.java @@ -0,0 +1,30 @@ +package food.service; + +import edu.fudan.common.util.Response; +import food.entity.*; +import org.springframework.http.HttpHeaders; + +import java.util.List; + +public interface StationFoodService { + + // create data + Response createFoodStore(StationFoodStore fs, HttpHeaders headers); + +// TrainFood createTrainFood(TrainFood tf, HttpHeaders headers); + + // query all food + Response listFoodStores(HttpHeaders headers); + +// Response listTrainFood(HttpHeaders headers); + + // query according id + Response listFoodStoresByStationName(String stationName, HttpHeaders headers); + +// Response listTrainFoodByTripId(String tripId, HttpHeaders headers); + + Response getStaionFoodStoreById(String id); + + Response getFoodStoresByStationNames(List stationNames); + +} diff --git a/ts-station-food-service/src/main/java/food/service/StationFoodServiceImpl.java b/ts-station-food-service/src/main/java/food/service/StationFoodServiceImpl.java new file mode 100644 index 000000000..0b07773af --- /dev/null +++ b/ts-station-food-service/src/main/java/food/service/StationFoodServiceImpl.java @@ -0,0 +1,121 @@ +package food.service; + +import edu.fudan.common.util.Response; +import food.entity.StationFoodStore; +import food.repository.StationFoodRepository; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.http.HttpHeaders; +import org.springframework.stereotype.Service; + +import java.util.List; + + +@Service +public class StationFoodServiceImpl implements StationFoodService { + + @Autowired + StationFoodRepository stationFoodRepository; + +// @Autowired +// TrainFoodRepository trainFoodRepository; + + private static final Logger LOGGER = LoggerFactory.getLogger(StationFoodServiceImpl.class); + + String success = "Success"; + String noContent = "No content"; + + @Override + public Response createFoodStore(StationFoodStore fs, HttpHeaders headers) { + StationFoodStore fsTemp = stationFoodRepository.findById(fs.getId()).orElse(null); + if (fsTemp != null) { + StationFoodServiceImpl.LOGGER.error("[Init FoodStore] Already Exists Id: {}", fs.getId()); + return new Response<>(0, "Already Exists Id", null); + } else { + try{ + stationFoodRepository.save(fs); + return new Response<>(1, "Save Success", fs); + }catch(Exception e){ + return new Response<>(0, "Save failed", e.getMessage()); + } + } + } + +// @Override +// public TrainFood createTrainFood(TrainFood tf, HttpHeaders headers) { +// TrainFood tfTemp = trainFoodRepository.findById(tf.getId()); +// if (tfTemp != null) { +// StationFoodServiceImpl.LOGGER.error("[Init TrainFood] Already Exists Id: {}", tf.getId()); +// } else { +// trainFoodRepository.save(tf); +// } +// return tf; +// } + + @Override + public Response listFoodStores(HttpHeaders headers) { + List stationFoodStores = stationFoodRepository.findAll(); + if (stationFoodStores != null && !stationFoodStores.isEmpty()) { + return new Response<>(1, success, stationFoodStores); + } else { + StationFoodServiceImpl.LOGGER.error("List food stores error: {}", "Food store is empty"); + return new Response<>(0, "Food store is empty", null); + } + } + +// @Override +// public Response listTrainFood(HttpHeaders headers) { +// List trainFoodList = trainFoodRepository.findAll(); +// if (trainFoodList != null && !trainFoodList.isEmpty()) { +// return new Response<>(1, success, trainFoodList); +// } else { +// StationFoodServiceImpl.LOGGER.error("List train food error: {}", noContent); +// return new Response<>(0, noContent, null); +// } +// } + + @Override + public Response listFoodStoresByStationName(String stationName, HttpHeaders headers) { + List stationFoodStoreList = stationFoodRepository.findByStationName(stationName); + if (stationFoodStoreList != null && !stationFoodStoreList.isEmpty()) { + return new Response<>(1, success, stationFoodStoreList); + } else { + StationFoodServiceImpl.LOGGER.error("List food stores by station id error: {}, stationName: {}", "Food store is empty", stationName); + return new Response<>(0, "Food store is empty", null); + } + } + +// @Override +// public Response listTrainFoodByTripId(String tripId, HttpHeaders headers) { +// List trainFoodList = trainFoodRepository.findByTripId(tripId); +// if (trainFoodList != null) { +// return new Response<>(1, success, trainFoodList); +// } else { +// StationFoodServiceImpl.LOGGER.error("List train food by trip id error: {}, tripId: {}", noContent, tripId); +// return new Response<>(0, noContent, null); +// } +// } + + @Override + public Response getFoodStoresByStationNames(List stationNames) { + List stationFoodStoreList = stationFoodRepository.findByStationNameIn(stationNames); + if (stationFoodStoreList != null) { + return new Response<>(1, success, stationFoodStoreList); + } else { + StationFoodServiceImpl.LOGGER.error("List food stores by station ids error: {}, stationName list: {}", "Food store is empty", stationNames); + return new Response<>(0, noContent, null); + } + } + + @Override + public Response getStaionFoodStoreById(String id) { + StationFoodStore stationFoodStore = stationFoodRepository.findById(id).orElse(null); + if (stationFoodStore == null) { + LOGGER.error("no such staionFoodStoreId: {}", id); + return new Response<>(0, noContent, null); + } else { + return new Response<>(1, success, stationFoodStore); + } + } +} diff --git a/ts-station-food-service/src/main/resources/application.yml b/ts-station-food-service/src/main/resources/application.yml new file mode 100644 index 000000000..b9f382309 --- /dev/null +++ b/ts-station-food-service/src/main/resources/application.yml @@ -0,0 +1,25 @@ +server: + port: 18855 + +spring: + cloud: + nacos: + discovery: + server-addr: ${NACOS_ADDRS:127.0.0.1:8848} + application: + name: ts-station-food-service + datasource: +# url: jdbc:mysql://localhost:3306/ts-station-food-mysql?useSSL=false + url: jdbc:mysql://${STATION_FOOD_MYSQL_HOST:10.176.122.1}:${STATION_FOOD_MYSQL_PORT:3306}/${STATION_FOOD_MYSQL_DATABASE:ts}?useSSL=false + username: ${STATION_FOOD_MYSQL_USER:root} + password: ${STATION_FOOD_MYSQL_PASSWORD:Abcd1234#} + driver-class-name: com.mysql.cj.jdbc.Driver + jpa: + hibernate: + ddl-auto: update + properties: + hibernate: + dialect: org.hibernate.dialect.MySQL5Dialect + +swagger: + controllerPackage: food.controller \ No newline at end of file diff --git a/ts-food-map-service/src/main/resources/foodstores.txt b/ts-station-food-service/src/main/resources/foodstores.txt similarity index 100% rename from ts-food-map-service/src/main/resources/foodstores.txt rename to ts-station-food-service/src/main/resources/foodstores.txt diff --git a/ts-food-map-service/src/test/java/food/controller/FoodStoreControllerTest.java b/ts-station-food-service/src/test/java/food/controller/StationFoodControllerTest.java similarity index 71% rename from ts-food-map-service/src/test/java/food/controller/FoodStoreControllerTest.java rename to ts-station-food-service/src/test/java/food/controller/StationFoodControllerTest.java index ce597dd99..d9458bac7 100644 --- a/ts-food-map-service/src/test/java/food/controller/FoodStoreControllerTest.java +++ b/ts-station-food-service/src/test/java/food/controller/StationFoodControllerTest.java @@ -2,7 +2,7 @@ import com.alibaba.fastjson.JSONObject; import edu.fudan.common.util.Response; -import food.service.FoodMapService; +import food.service.StationFoodService; import org.junit.Assert; import org.junit.Before; import org.junit.Test; @@ -22,33 +22,33 @@ import java.util.List; @RunWith(JUnit4.class) -public class FoodStoreControllerTest { +public class StationFoodControllerTest { @InjectMocks - private FoodStoreController foodStoreController; + private StationFoodController stationFoodController; @Mock - private FoodMapService foodMapService; + private StationFoodService stationFoodService; private MockMvc mockMvc; private Response response = new Response(); @Before public void setUp() { MockitoAnnotations.initMocks(this); - mockMvc = MockMvcBuilders.standaloneSetup(foodStoreController).build(); + mockMvc = MockMvcBuilders.standaloneSetup(stationFoodController).build(); } @Test public void testHome() throws Exception { - mockMvc.perform(MockMvcRequestBuilders.get("/api/v1/foodmapservice/foodstores/welcome")) + mockMvc.perform(MockMvcRequestBuilders.get("/api/v1/foodmapservice/stationfoodstores/welcome")) .andExpect(MockMvcResultMatchers.status().isOk()) .andExpect(MockMvcResultMatchers.content().string("Welcome to [ Food store Service ] !")); } @Test public void testGetAllFoodStores() throws Exception { - Mockito.when(foodMapService.listFoodStores(Mockito.any(HttpHeaders.class))).thenReturn(response); - String result = mockMvc.perform(MockMvcRequestBuilders.get("/api/v1/foodmapservice/foodstores")) + Mockito.when(stationFoodService.listFoodStores(Mockito.any(HttpHeaders.class))).thenReturn(response); + String result = mockMvc.perform(MockMvcRequestBuilders.get("/api/v1/foodmapservice/stationfoodstores")) .andExpect(MockMvcResultMatchers.status().isOk()) .andReturn().getResponse().getContentAsString(); Assert.assertEquals(response, JSONObject.parseObject(result, Response.class)); @@ -56,19 +56,19 @@ public void testGetAllFoodStores() throws Exception { @Test public void testGetFoodStoresOfStation() throws Exception { - Mockito.when(foodMapService.listFoodStoresByStationId(Mockito.anyString(), Mockito.any(HttpHeaders.class))).thenReturn(response); - String result = mockMvc.perform(MockMvcRequestBuilders.get("/api/v1/foodmapservice/foodstores/station_id")) + Mockito.when(stationFoodService.listFoodStoresByStationName(Mockito.anyString(), Mockito.any(HttpHeaders.class))).thenReturn(response); + String result = mockMvc.perform(MockMvcRequestBuilders.get("/api/v1/foodmapservice/stationfoodstores/station_id")) .andExpect(MockMvcResultMatchers.status().isOk()) .andReturn().getResponse().getContentAsString(); Assert.assertEquals(response, JSONObject.parseObject(result, Response.class)); } @Test - public void testGetFoodStoresByStationIds() throws Exception { + public void testGetFoodStoresByStationNames() throws Exception { List stationIdList = new ArrayList<>(); - Mockito.when(foodMapService.getFoodStoresByStationIds(Mockito.anyList())).thenReturn(response); + Mockito.when(stationFoodService.getFoodStoresByStationNames(Mockito.anyList())).thenReturn(response); String requestJson = JSONObject.toJSONString(stationIdList); - String result = mockMvc.perform(MockMvcRequestBuilders.post("/api/v1/foodmapservice/foodstores").contentType(MediaType.APPLICATION_JSON).content(requestJson)) + String result = mockMvc.perform(MockMvcRequestBuilders.post("/api/v1/foodmapservice/stationfoodstores").contentType(MediaType.APPLICATION_JSON).content(requestJson)) .andExpect(MockMvcResultMatchers.status().isOk()) .andReturn().getResponse().getContentAsString(); Assert.assertEquals(response, JSONObject.parseObject(result, Response.class)); diff --git a/ts-station-food-service/src/test/java/food/service/StationFoodServiceImplTest.java b/ts-station-food-service/src/test/java/food/service/StationFoodServiceImplTest.java new file mode 100644 index 000000000..39236fdbf --- /dev/null +++ b/ts-station-food-service/src/test/java/food/service/StationFoodServiceImplTest.java @@ -0,0 +1,155 @@ +package food.service; + +import edu.fudan.common.util.Response; +import food.entity.StationFoodStore; +import food.repository.StationFoodRepository; +import org.junit.Assert; +import org.junit.Before; +import org.junit.Test; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.Mockito; +import org.mockito.MockitoAnnotations; +import org.springframework.http.HttpHeaders; +import java.util.Optional; +import java.util.ArrayList; +import java.util.List; +import java.util.Optional; +import java.util.UUID; + +public class StationFoodServiceImplTest { + + @InjectMocks + private StationFoodServiceImpl foodMapServiceImpl; + + @Mock + private StationFoodRepository stationFoodRepository; + +// @Mock +// private TrainFoodRepository trainFoodRepository; + + private HttpHeaders headers = new HttpHeaders(); + + @Before + public void setUp() { + MockitoAnnotations.initMocks(this); + } + + @Test + public void testCreateFoodStore1() { + StationFoodStore fss=new StationFoodStore(); + Optional fs = Optional.ofNullable(fss); + Mockito.when(stationFoodRepository.findById(Mockito.any(String.class))).thenReturn(fs); + Response result = foodMapServiceImpl.createFoodStore(fs.get(), headers); + Assert.assertEquals(new Response<>(0, "Already Exists Id", null), result); + } + + @Test + public void testCreateFoodStore2() { + StationFoodStore fs = new StationFoodStore(); + Mockito.when(stationFoodRepository.findById(Mockito.any(String.class))).thenReturn(null); + Mockito.when(stationFoodRepository.save(Mockito.any(StationFoodStore.class))).thenReturn(null); + Response result = foodMapServiceImpl.createFoodStore(fs, headers); + Assert.assertEquals(new Response<>(1, "Save Success", fs), result); + } + +// @Test +// public void testCreateTrainFood1() { +// TrainFood tf = new TrainFood(); +// Mockito.when(trainFoodRepository.findById(Mockito.any(UUID.class))).thenReturn(tf); +// TrainFood result = foodMapServiceImpl.createTrainFood(tf, headers); +// Assert.assertEquals(tf, result); +// } +// +// @Test +// public void testCreateTrainFood2() { +// TrainFood tf = new TrainFood(); +// Mockito.when(trainFoodRepository.findById(Mockito.any(UUID.class))).thenReturn(null); +// Mockito.when(trainFoodRepository.save(Mockito.any(TrainFood.class))).thenReturn(null); +// TrainFood result = foodMapServiceImpl.createTrainFood(tf, headers); +// Assert.assertEquals(tf, result); +// } + + @Test + public void testListFoodStores1() { + List stationFoodStores = new ArrayList<>(); + stationFoodStores.add(new StationFoodStore()); + Mockito.when(stationFoodRepository.findAll()).thenReturn(stationFoodStores); + Response result = foodMapServiceImpl.listFoodStores(headers); + Assert.assertEquals(new Response<>(1, "Success", stationFoodStores), result); + } + + @Test + public void testListFoodStores2() { + Mockito.when(stationFoodRepository.findAll()).thenReturn(null); + Response result = foodMapServiceImpl.listFoodStores(headers); + Assert.assertEquals(new Response<>(0, "Food store is empty", null), result); + } + +// @Test +// public void testListTrainFood1() { +// List trainFoodList = new ArrayList<>(); +// trainFoodList.add(new TrainFood()); +// Mockito.when(trainFoodRepository.findAll()).thenReturn(trainFoodList); +// Response result = foodMapServiceImpl.listTrainFood(headers); +// Assert.assertEquals(new Response<>(1, "Success", trainFoodList), result); +// } +// +// @Test +// public void testListTrainFood2() { +// Mockito.when(trainFoodRepository.findAll()).thenReturn(null); +// Response result = foodMapServiceImpl.listTrainFood(headers); +// Assert.assertEquals(new Response<>(0, "No content", null), result); +// } + + @Test + public void testListFoodStoresByStationName1() { + List stationFoodStoreList = new ArrayList<>(); + stationFoodStoreList.add(new StationFoodStore()); + Mockito.when(stationFoodRepository.findByStationName(Mockito.anyString())).thenReturn(stationFoodStoreList); + Response result = foodMapServiceImpl.listFoodStoresByStationName("station_id", headers); + Assert.assertEquals(new Response<>(1, "Success", stationFoodStoreList), result); + } + + @Test + public void testListFoodStoresByStationName2() { + Mockito.when(stationFoodRepository.findByStationName(Mockito.anyString())).thenReturn(null); + Response result = foodMapServiceImpl.listFoodStoresByStationName("station_id", headers); + Assert.assertEquals(new Response<>(0, "Food store is empty", null), result); + } + +// @Test +// public void testListTrainFoodByTripId1() { +// List trainFoodList = new ArrayList<>(); +// trainFoodList.add(new TrainFood()); +// Mockito.when(trainFoodRepository.findByTripId(Mockito.anyString())).thenReturn(trainFoodList); +// Response result = foodMapServiceImpl.listTrainFoodByTripId("trip_id", headers); +// Assert.assertEquals(new Response<>(1, "Success", trainFoodList), result); +// } +// +// @Test +// public void testListTrainFoodByTripId2() { +// Mockito.when(trainFoodRepository.findByTripId(Mockito.anyString())).thenReturn(null); +// Response result = foodMapServiceImpl.listTrainFoodByTripId("trip_id", headers); +// Assert.assertEquals(new Response<>(0, "No content", null), result); +// } + + @Test + public void testGetFoodStoresByStationNames1() { + List stationIds = new ArrayList<>(); + List stationFoodStoreList = new ArrayList<>(); + stationFoodStoreList.add(new StationFoodStore()); + Mockito.when(stationFoodRepository.findByStationNameIn(Mockito.anyList())).thenReturn(stationFoodStoreList); + Response result = foodMapServiceImpl.getFoodStoresByStationNames(stationIds); + Assert.assertEquals(new Response<>(1, "Success", stationFoodStoreList), result); + } + + @Test + public void testGetFoodStoresByStationNames2() { + List stationIds = new ArrayList<>(); + Mockito.when(stationFoodRepository.findByStationNameIn(Mockito.anyList())).thenReturn(null); + Response result = foodMapServiceImpl.getFoodStoresByStationNames(stationIds); + Assert.assertEquals(new Response<>(0, "No content", null), result); + } + +} diff --git a/ts-station-service/pom.xml b/ts-station-service/pom.xml index 909a7410b..dccab77a9 100644 --- a/ts-station-service/pom.xml +++ b/ts-station-service/pom.xml @@ -15,7 +15,7 @@ org.services ts-service 0.1.0 - ../ + ../pom.xml @@ -25,17 +25,27 @@ + + + + org.springframework.boot - spring-boot-starter-data-mongodb + spring-boot-starter-data-jpa + + + mysql + mysql-connector-java org.services ts-common 0.1.0 - - + + jakarta.validation + jakarta.validation-api + diff --git a/ts-station-service/src/main/java/fdse/microservice/StationApplication.java b/ts-station-service/src/main/java/fdse/microservice/StationApplication.java index 376d7dd49..b30cf8f17 100644 --- a/ts-station-service/src/main/java/fdse/microservice/StationApplication.java +++ b/ts-station-service/src/main/java/fdse/microservice/StationApplication.java @@ -2,9 +2,14 @@ import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.boot.web.client.RestTemplateBuilder; +import org.springframework.cloud.client.discovery.EnableDiscoveryClient; +import org.springframework.cloud.client.loadbalancer.LoadBalanced; +import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.EnableAspectJAutoProxy; import org.springframework.integration.annotation.IntegrationComponentScan; import org.springframework.scheduling.annotation.EnableAsync; +import org.springframework.web.client.RestTemplate; import springfox.documentation.swagger2.annotations.EnableSwagger2; @SpringBootApplication @@ -12,9 +17,16 @@ @EnableAsync @IntegrationComponentScan @EnableSwagger2 +@EnableDiscoveryClient public class StationApplication { public static void main(String[] args) { SpringApplication.run(StationApplication.class, args); } + + @LoadBalanced + @Bean + public RestTemplate restTemplate(RestTemplateBuilder builder) { + return builder.build(); + } } diff --git a/ts-station-service/src/main/java/fdse/microservice/controller/StationController.java b/ts-station-service/src/main/java/fdse/microservice/controller/StationController.java index 60664c393..8bfee100b 100644 --- a/ts-station-service/src/main/java/fdse/microservice/controller/StationController.java +++ b/ts-station-service/src/main/java/fdse/microservice/controller/StationController.java @@ -37,20 +37,20 @@ public HttpEntity query(@RequestHeader HttpHeaders headers) { @PostMapping(value = "/stations") public ResponseEntity create(@RequestBody Station station, @RequestHeader HttpHeaders headers) { - StationController.LOGGER.info("Create station,name: {}",station.getName()); + StationController.LOGGER.info("[create][Create station][name: {}]",station.getName()); return new ResponseEntity<>(stationService.create(station, headers), HttpStatus.CREATED); } @PutMapping(value = "/stations") public HttpEntity update(@RequestBody Station station, @RequestHeader HttpHeaders headers) { - StationController.LOGGER.info("Update station,StationId: {}",station.getId()); + StationController.LOGGER.info("[update][Update station][StationId: {}]",station.getId()); return ok(stationService.update(station, headers)); } - @DeleteMapping(value = "/stations") - public ResponseEntity delete(@RequestBody Station station, @RequestHeader HttpHeaders headers) { - StationController.LOGGER.info("Delete station,StationId: {}",station.getId()); - return ok(stationService.delete(station, headers)); + @DeleteMapping(value = "/stations/{stationsId}") + public ResponseEntity delete(@PathVariable String stationsId, @RequestHeader HttpHeaders headers) { + StationController.LOGGER.info("[delete][Delete station][StationId: {}]",stationsId); + return ok(stationService.delete(stationsId, headers)); } @@ -60,7 +60,7 @@ public ResponseEntity delete(@RequestBody Station station, @RequestHea public HttpEntity queryForStationId(@PathVariable(value = "stationNameForId") String stationName, @RequestHeader HttpHeaders headers) { // string - StationController.LOGGER.info("Query for station id,StationName: {}",stationName); + StationController.LOGGER.info("[queryForId][Query for station id][StationName: {}]",stationName); return ok(stationService.queryForId(stationName, headers)); } @@ -68,7 +68,7 @@ public HttpEntity queryForStationId(@PathVariable(value = "stationNameForId") @CrossOrigin(origins = "*") @PostMapping(value = "/stations/idlist") public HttpEntity queryForIdBatch(@RequestBody List stationNameList, @RequestHeader HttpHeaders headers) { - StationController.LOGGER.info("Query stations for id batch,StationNameNumbers: {}",stationNameList.size()); + StationController.LOGGER.info("[queryForIdBatch][Query stations for id batch][StationNameNumbers: {}]",stationNameList.size()); return ok(stationService.queryForIdBatch(stationNameList, headers)); } @@ -77,7 +77,7 @@ public HttpEntity queryForIdBatch(@RequestBody List stationNameList, @Re @GetMapping(value = "/stations/name/{stationIdForName}") public HttpEntity queryById(@PathVariable(value = "stationIdForName") String stationId, @RequestHeader HttpHeaders headers) { - StationController.LOGGER.info("Query stations By Id: {}", stationId); + StationController.LOGGER.info("[queryById][Query stations By Id][Id: {}]", stationId); // string return ok(stationService.queryById(stationId, headers)); } @@ -86,7 +86,7 @@ public HttpEntity queryById(@PathVariable(value = "stationIdForName") @CrossOrigin(origins = "*") @PostMapping(value = "/stations/namelist") public HttpEntity queryForNameBatch(@RequestBody List stationIdList, @RequestHeader HttpHeaders headers) { - StationController.LOGGER.info("Query stations for name batch,StationIdNumbers: {}",stationIdList.size()); + StationController.LOGGER.info("[queryByIdBatch][Query stations for name batch][StationIdNumbers: {}]",stationIdList.size()); return ok(stationService.queryByIdBatch(stationIdList, headers)); } diff --git a/ts-station-service/src/main/java/fdse/microservice/entity/Station.java b/ts-station-service/src/main/java/fdse/microservice/entity/Station.java index 2d879866d..df6a34348 100644 --- a/ts-station-service/src/main/java/fdse/microservice/entity/Station.java +++ b/ts-station-service/src/main/java/fdse/microservice/entity/Station.java @@ -1,42 +1,48 @@ package fdse.microservice.entity; import lombok.Data; -import org.springframework.data.annotation.Id; -import org.springframework.data.mongodb.core.mapping.Document; +import org.hibernate.annotations.GenericGenerator; +import javax.persistence.Column; +import javax.persistence.Entity; +import javax.persistence.GeneratedValue; +import javax.persistence.Id; import javax.validation.Valid; import javax.validation.constraints.NotNull; +import java.util.Locale; import java.util.UUID; @Data -@Document(collection="station") +@Entity +@GenericGenerator(name = "jpa-uuid", strategy = "org.hibernate.id.UUIDGenerator") public class Station { - @Valid - @NotNull @Id + @GeneratedValue(generator = "jpa-uuid") + @Column(length = 36) private String id; @Valid @NotNull + @Column(unique = true) private String name; private int stayTime; public Station(){ - //Default Constructor - this.id = UUID.randomUUID().toString(); this.name = ""; } - public Station(String id, String name) { - this.id = id; - this.name = name; + public void setName(String name) { + this.name = name.replace(" ", "").toLowerCase(Locale.ROOT); + } + + public Station(String name) { + this.name = name.replace(" ", "").toLowerCase(Locale.ROOT); } - public Station(String id, String name, int stayTime) { - this.id = id; - this.name = name; + public Station(String name, int stayTime) { + this.name = name.replace(" ", "").toLowerCase(Locale.ROOT);; this.stayTime = stayTime; } diff --git a/ts-station-service/src/main/java/fdse/microservice/init/InitData.java b/ts-station-service/src/main/java/fdse/microservice/init/InitData.java index 4773cf3bc..81fa52d2d 100644 --- a/ts-station-service/src/main/java/fdse/microservice/init/InitData.java +++ b/ts-station-service/src/main/java/fdse/microservice/init/InitData.java @@ -15,69 +15,66 @@ public class InitData implements CommandLineRunner { @Override public void run(String... args) throws Exception{ Station info = new Station(); - - info.setId("shanghai"); info.setName("Shang Hai"); info.setStayTime(10); service.create(info,null); - info.setId("shanghaihongqiao"); + info = new Station(); info.setName("Shang Hai Hong Qiao"); info.setStayTime(10); service.create(info,null); - info.setId("taiyuan"); + info = new Station(); info.setName("Tai Yuan"); info.setStayTime(5); service.create(info,null); - info.setId("beijing"); + info = new Station(); info.setName("Bei Jing"); info.setStayTime(10); service.create(info,null); - info.setId("nanjing"); + info = new Station(); info.setName("Nan Jing"); info.setStayTime(8); service.create(info,null); - info.setId("shijiazhuang"); + info = new Station(); info.setName("Shi Jia Zhuang"); info.setStayTime(8); service.create(info,null); - info.setId("xuzhou"); + info = new Station(); info.setName("Xu Zhou"); info.setStayTime(7); service.create(info,null); - - info.setId("jinan"); + info = new Station(); info.setName("Ji Nan"); info.setStayTime(5); service.create(info,null); - info.setId("hangzhou"); + info = new Station(); info.setName("Hang Zhou"); info.setStayTime(9); service.create(info,null); - info.setId("jiaxingnan"); + info = new Station(); info.setName("Jia Xing Nan"); info.setStayTime(2); service.create(info,null); - info.setId("zhenjiang"); + info = new Station(); info.setName("Zhen Jiang"); info.setStayTime(2); service.create(info,null); - info.setId("wuxi"); + info = new Station(); info.setName("Wu Xi"); info.setStayTime(3); service.create(info,null); - info.setId("suzhou"); + info = new Station(); info.setName("Su Zhou"); info.setStayTime(3); service.create(info,null); diff --git a/ts-station-service/src/main/java/fdse/microservice/repository/StationRepository.java b/ts-station-service/src/main/java/fdse/microservice/repository/StationRepository.java index 97c54af45..f9513e22c 100644 --- a/ts-station-service/src/main/java/fdse/microservice/repository/StationRepository.java +++ b/ts-station-service/src/main/java/fdse/microservice/repository/StationRepository.java @@ -1,16 +1,22 @@ package fdse.microservice.repository; import fdse.microservice.entity.Station; +import org.springframework.data.jpa.repository.Query; import org.springframework.data.repository.CrudRepository; +import org.springframework.stereotype.Repository; import java.util.List; +import java.util.Optional; - +@Repository public interface StationRepository extends CrudRepository { Station findByName(String name); - Station findById(String id); + @Query(value="SELECT * from station where name in ?1", nativeQuery = true) + List findByNames(List names); + + Optional findById(String id); @Override List findAll(); diff --git a/ts-station-service/src/main/java/fdse/microservice/service/StationService.java b/ts-station-service/src/main/java/fdse/microservice/service/StationService.java index 8ed572c21..2efb657d1 100644 --- a/ts-station-service/src/main/java/fdse/microservice/service/StationService.java +++ b/ts-station-service/src/main/java/fdse/microservice/service/StationService.java @@ -14,7 +14,7 @@ public interface StationService { Response update(Station info, HttpHeaders headers); - Response delete(Station info, HttpHeaders headers); + Response delete(String stationsId, HttpHeaders headers); Response query(HttpHeaders headers); diff --git a/ts-station-service/src/main/java/fdse/microservice/service/StationServiceImpl.java b/ts-station-service/src/main/java/fdse/microservice/service/StationServiceImpl.java index 0f01d1e14..dc17ba087 100644 --- a/ts-station-service/src/main/java/fdse/microservice/service/StationServiceImpl.java +++ b/ts-station-service/src/main/java/fdse/microservice/service/StationServiceImpl.java @@ -9,8 +9,7 @@ import org.springframework.http.HttpHeaders; import org.springframework.stereotype.Service; -import java.util.ArrayList; -import java.util.List; +import java.util.*; @Service @@ -25,12 +24,16 @@ public class StationServiceImpl implements StationService { @Override public Response create(Station station, HttpHeaders headers) { - if (repository.findById(station.getId()) == null) { + if(station.getName().isEmpty()) { + StationServiceImpl.LOGGER.error("[create][Create station error][Name not specify]"); + return new Response<>(0, "Name not specify", station); + } + if (repository.findByName(station.getName()) == null) { station.setStayTime(station.getStayTime()); repository.save(station); return new Response<>(1, "Create success", station); } - StationServiceImpl.LOGGER.error("Create station error.Already exists, StationId: {}",station.getId()); + StationServiceImpl.LOGGER.error("[create][Create station error][Already exists][StationId: {}]",station.getId()); return new Response<>(0, "Already exists", station); } @@ -47,11 +50,12 @@ public boolean exist(String stationName, HttpHeaders headers) { @Override public Response update(Station info, HttpHeaders headers) { - if (repository.findById(info.getId()) == null) { - StationServiceImpl.LOGGER.error("Update station error.Station not found, StationId: {}",info.getId()); + Optional op = repository.findById(info.getId()); + if (!op.isPresent()) { + StationServiceImpl.LOGGER.error("[update][Update station error][Station not found][StationId: {}]",info.getId()); return new Response<>(0, "Station not exist", null); } else { - Station station = new Station(info.getId(), info.getName()); + Station station = op.get(); station.setStayTime(info.getStayTime()); repository.save(station); return new Response<>(1, "Update success", station); @@ -59,14 +63,14 @@ public Response update(Station info, HttpHeaders headers) { } @Override - public Response delete(Station info, HttpHeaders headers) { - - if (repository.findById(info.getId()) != null) { - Station station = new Station(info.getId(), info.getName()); + public Response delete(String stationsId, HttpHeaders headers) { + Optional op = repository.findById(stationsId); + if (op.isPresent()) { + Station station = op.get(); repository.delete(station); return new Response<>(1, "Delete success", station); } - StationServiceImpl.LOGGER.error("Delete station error.Station not found, StationId: {}",info.getId()); + StationServiceImpl.LOGGER.error("[delete][Delete station error][Station not found][StationId: {}]",stationsId); return new Response<>(0, "Station not exist", null); } @@ -76,7 +80,7 @@ public Response query(HttpHeaders headers) { if (stations != null && !stations.isEmpty()) { return new Response<>(1, "Find all content", stations); } else { - StationServiceImpl.LOGGER.warn("Query stations warn.Find all stations: {}","No content"); + StationServiceImpl.LOGGER.warn("[query][Query stations warn][Find all stations: {}]","No content"); return new Response<>(0, "No content", null); } } @@ -88,7 +92,7 @@ public Response queryForId(String stationName, HttpHeaders headers) { if (station != null) { return new Response<>(1, success, station.getId()); } else { - StationServiceImpl.LOGGER.warn("Find station id warn.Station not found, StationName: {}",stationName); + StationServiceImpl.LOGGER.warn("[queryForId][Find station id warn][Station not found][StationName: {}]",stationName); return new Response<>(0, "Not exists", stationName); } } @@ -96,20 +100,21 @@ public Response queryForId(String stationName, HttpHeaders headers) { @Override public Response queryForIdBatch(List nameList, HttpHeaders headers) { - ArrayList result = new ArrayList<>(); - for (int i = 0; i < nameList.size(); i++) { - Station station = repository.findByName(nameList.get(i)); - if (station == null) { - result.add("Not Exist"); - } else { - result.add(station.getId()); - } + Map result = new HashMap<>(); + List stations = repository.findByNames(nameList); + Map stationMap = new HashMap<>(); + for(Station s: stations) { + stationMap.put(s.getName(), s.getId()); + } + + for(String name: nameList){ + result.put(name, stationMap.get(name)); } if (!result.isEmpty()) { return new Response<>(1, success, result); } else { - StationServiceImpl.LOGGER.warn("Find station ids warn.Stations not found, StationNameNumber: {}",nameList.size()); + StationServiceImpl.LOGGER.warn("[queryForIdBatch][Find station ids warn][Stations not found][StationNameNumber: {}]",nameList.size()); return new Response<>(0, "No content according to name list", null); } @@ -117,11 +122,11 @@ public Response queryForIdBatch(List nameList, HttpHeaders headers) { @Override public Response queryById(String stationId, HttpHeaders headers) { - Station station = repository.findById(stationId); - if (station != null) { - return new Response<>(1, success, station.getName()); + Optional station = repository.findById(stationId); + if (station.isPresent()) { + return new Response<>(1, success, station.get().getName()); } else { - StationServiceImpl.LOGGER.error("Find station name error.Station not found, StationId: {}",stationId); + StationServiceImpl.LOGGER.error("[queryById][Find station name error][Station not found][StationId: {}]",stationId); return new Response<>(0, "No that stationId", stationId); } } @@ -130,8 +135,9 @@ public Response queryById(String stationId, HttpHeaders headers) { public Response queryByIdBatch(List idList, HttpHeaders headers) { ArrayList result = new ArrayList<>(); for (int i = 0; i < idList.size(); i++) { - Station station = repository.findById(idList.get(i)); - if (station != null) { + Optional stationOld = repository.findById(idList.get(i)); + if(stationOld.isPresent()){ + Station station=stationOld.get(); result.add(station.getName()); } } @@ -139,7 +145,7 @@ public Response queryByIdBatch(List idList, HttpHeaders headers) { if (!result.isEmpty()) { return new Response<>(1, success, result); } else { - StationServiceImpl.LOGGER.error("Find station names error.Stations not found, StationIdNumber: {}",idList.size()); + StationServiceImpl.LOGGER.error("[queryByIdBatch][Find station names error][Stations not found][StationIdNumber: {}]",idList.size()); return new Response<>(0, "No stationNamelist according to stationIdList", result); } diff --git a/ts-station-service/src/main/resources/application.yml b/ts-station-service/src/main/resources/application.yml index 31c9cadb5..3242965fd 100644 --- a/ts-station-service/src/main/resources/application.yml +++ b/ts-station-service/src/main/resources/application.yml @@ -1,13 +1,18 @@ spring: + cloud: + nacos: + discovery: + server-addr: ${NACOS_ADDRS:nacos-0.nacos-headless.default.svc.cluster.local,nacos-1.nacos-headless.default.svc.cluster.local,nacos-2.nacos-headless.default.svc.cluster.local} application: name: ts-station-service - data: - mongodb: - host: ts-station-mongo -# username: user -# password: ${MONGODB_PASSWORD} - database: ts - port: 27017 + datasource: + url: jdbc:mysql://${STATION_MYSQL_HOST:ts-station-mysql}:${STATION_MYSQL_PORT:3306}/${STATION_MYSQL_DATABASE:ts-station-mysql}?useSSL=false + username: ${STATION_MYSQL_USER:root} + password: ${STATION_MYSQL_PASSWORD:Abcd1234#} + driver-class-name: com.mysql.cj.jdbc.Driver + jpa: + hibernate: + ddl-auto: update # HTTP Server server: diff --git a/ts-station-service/src/test/java/fdse/microservice/controller/StationControllerTest.java b/ts-station-service/src/test/java/fdse/microservice/controller/StationControllerTest.java index a8bf482de..e71cc8cef 100644 --- a/ts-station-service/src/test/java/fdse/microservice/controller/StationControllerTest.java +++ b/ts-station-service/src/test/java/fdse/microservice/controller/StationControllerTest.java @@ -80,7 +80,7 @@ public void testUpdate() throws Exception { @Test public void testDelete() throws Exception { Station station = new Station(); - Mockito.when(stationService.delete(Mockito.any(Station.class), Mockito.any(HttpHeaders.class))).thenReturn(response); + Mockito.when(stationService.delete(Mockito.anyString(), Mockito.any(HttpHeaders.class))).thenReturn(response); String requestJson = JSONObject.toJSONString(station); String result = mockMvc.perform(MockMvcRequestBuilders.delete("/api/v1/stationservice/stations").contentType(MediaType.APPLICATION_JSON).content(requestJson)) .andExpect(MockMvcResultMatchers.status().isOk()) diff --git a/ts-station-service/src/test/java/fdse/microservice/service/StationServiceImplTest.java b/ts-station-service/src/test/java/fdse/microservice/service/StationServiceImplTest.java index 1bb080951..b7502e542 100644 --- a/ts-station-service/src/test/java/fdse/microservice/service/StationServiceImplTest.java +++ b/ts-station-service/src/test/java/fdse/microservice/service/StationServiceImplTest.java @@ -36,7 +36,7 @@ public void setUp() { @Test public void testCreate1() { Station station = new Station(); - Mockito.when(repository.findById(Mockito.anyString())).thenReturn(null); + Mockito.when(repository.findById(Mockito.anyString()).get()).thenReturn(null); Mockito.when(repository.save(Mockito.any(Station.class))).thenReturn(null); Response result = stationServiceImpl.create(station, headers); Assert.assertEquals(new Response<>(1, "Create success", station), result); @@ -45,7 +45,7 @@ public void testCreate1() { @Test public void testCreate2() { Station station = new Station(); - Mockito.when(repository.findById(Mockito.anyString())).thenReturn(station); + Mockito.when(repository.findById(Mockito.anyString()).get()).thenReturn(station); Response result = stationServiceImpl.create(station, headers); Assert.assertEquals(new Response<>(0, "Already exists", station), result); } @@ -74,7 +74,7 @@ public void testUpdate1() { @Test public void testUpdate2() { Station info = new Station(); - Mockito.when(repository.findById(Mockito.anyString())).thenReturn(info); + Mockito.when(repository.findById(Mockito.anyString()).get()).thenReturn(info); Mockito.when(repository.save(Mockito.any(Station.class))).thenReturn(null); Response result = stationServiceImpl.update(info, headers); Assert.assertEquals("Update success", result.getMsg()); @@ -83,9 +83,9 @@ public void testUpdate2() { @Test public void testDelete1() { Station info = new Station(); - Mockito.when(repository.findById(Mockito.anyString())).thenReturn(info); + Mockito.when(repository.findById(Mockito.anyString()).get()).thenReturn(info); Mockito.doNothing().doThrow(new RuntimeException()).when(repository).delete(Mockito.any(Station.class)); - Response result = stationServiceImpl.delete(info, headers); + Response result = stationServiceImpl.delete(info.getId(), headers); Assert.assertEquals("Delete success", result.getMsg()); } @@ -93,7 +93,7 @@ public void testDelete1() { public void testDelete2() { Station info = new Station(); Mockito.when(repository.findById(Mockito.anyString())).thenReturn(null); - Response result = stationServiceImpl.delete(info, headers); + Response result = stationServiceImpl.delete(info.getId(), headers); Assert.assertEquals(new Response<>(0, "Station not exist", null), result); } @@ -147,7 +147,7 @@ public void testQueryForIdBatch2() { @Test public void testQueryById1() { Station station = new Station(); - Mockito.when(repository.findById(Mockito.anyString())).thenReturn(station); + Mockito.when(repository.findById(Mockito.anyString()).get()).thenReturn(station); Response result = stationServiceImpl.queryById("station_id", headers); Assert.assertEquals(new Response<>(1, "Success", ""), result); } @@ -171,7 +171,7 @@ public void testQueryByIdBatch2() { Station station = new Station(); List idList = new ArrayList<>(); idList.add("station_id"); - Mockito.when(repository.findById(Mockito.anyString())).thenReturn(station); + Mockito.when(repository.findById(Mockito.anyString()).get()).thenReturn(station); Response result = stationServiceImpl.queryByIdBatch(idList, headers); Assert.assertEquals("Success", result.getMsg()); } diff --git a/ts-ticket-office-service/app.js b/ts-ticket-office-service/app.js index e3dbc243b..83f8b37da 100644 --- a/ts-ticket-office-service/app.js +++ b/ts-ticket-office-service/app.js @@ -23,8 +23,8 @@ app.use(express.static(path.join(__dirname, 'public'))); //初始化数据库 var db = require('./bin/db'); -db.initMongo(function (result) { - if(result.result.ok){ +db.initMysql(function (result) { + if(result.ok){ console.log("init data successful!"); } }); diff --git a/ts-ticket-office-service/bin/db.js b/ts-ticket-office-service/bin/db.js index 8425f8dcd..4e9423911 100644 --- a/ts-ticket-office-service/bin/db.js +++ b/ts-ticket-office-service/bin/db.js @@ -1,99 +1,69 @@ /** * Created by dingding on 2017/10/13. */ -var MongoClient = require('mongodb').MongoClient; +var HOST=process.env.TICKET_OFFICE_MYSQL_HOST +var PORT=process.env.TICKET_OFFICE_MYSQL_PORT +var USER=process.env.TICKET_OFFICE_MYSQL_USER +var PASSWORD=process.env.TICKET_OFFICE_MYSQL_PASSWORD +var DATABASE=process.env.TICKET_OFFICE_MYSQL_DATABASE +var DB_CONN_STR = "jdbc:mysql://" + HOST + ":" + PORT + "/" + DATABASE; +var MysqlClient = require('mysql').createConnection({ + host: HOST, + user: USER, + password: PASSWORD, + database: DATABASE +}); var fs = require('fs'); var path = require('path'); -// var DB_CONN_STR = 'mongodb://localhost:27017/test'; -var DB_CONN_STR = 'mongodb://ts-ticket-office-mongo/ticket-office'; - -var initData = function(db, callback){ - var collection = db.collection('office'); - if(collection.find()){ - collection.remove({}); - } - /*读取已存在的数据*/ - fs.readFile(path.join(__dirname, "./office.json"), 'utf8', function (err, data) { - data = JSON.parse( data ); - collection.insertMany(data, function(err, result){ - if(err){ - console.log('Error: ' + err); - return; - } - callback(result); - }); + + + +var initData = function(callback){ + var sql = "CREATE TABLE IF NOT EXISTS office (name VARCHAR(255), city VARCHAR(255), province VARCHAR(255),region VARCHAR(255), address VARCHAR(255), workTime VARCHAR(32), windowNum INT(10))"; + MysqlClient.query(sql, function (err, result) { + if (err) throw err; + console.log("Table created"); + callback(result); }); + + // init data + insertEntry('Jinqiao Road ticket sales outlets', 'Shanghai', 'Shanghai', 'Pudong New Area', 'Jinqiao Road 1320, Shanghai, Pudong New Area', '08:00-18:00', 1); + }; var getAllOffices = function(db, callback){ - var collection = db.collection('office'); - collection.find().toArray(function(err, result){ - if(err){ - console.log("Error:" + err); - return; - } + MysqlClient.query("SELECT * FROM office", function (err, result, fields) { + if (err) throw err; + console.log(result); callback(result); }); }; /*根据省市区信息获取该地区的代售点列表*/ var getSpecificOffices = function(province, city, region, db, callback){ - var collection = db.collection('office'); - var findString = {"province":province , - "city": city , - "region": region}; - collection.find(findString).toArray(function(err, result){ - if(err){ - console.log("Error:" + err); - return; - } + var where_sql= "WHERE province = '" + province + "' AND city = '" + city + "' AND region = '" + region + "'"; + var sql = "SELECT * FROM office " + where_sql; + console.log("getSpecificOffices sql:", sql); + MysqlClient.query(sql, function (err, result, fields) { + if (err) throw err; + console.log(result); callback(result); }); }; /*根据省市区信息添加代售点*/ var addOffice = function(province, city, region, office, db, callback){ - var collection = db.collection('office'); - var findString = {"province":province , - "city": city , - "region": region}; - var updateString = {$push:{ - "offices": { - 'officeName':office.officeName, - 'address': office.address, - 'workTime': office.workTime, - 'windowNum': office.windowNum - } - }}; - collection.update(findString, updateString, function(err, result){ - if(err){ - console.log("Update Error:" + err); - return; - } - callback(result); - }); + insertEntry(office.name, city, province, region, office.address, office.workTime, office.windowNum); + callback("insert succeed.") }; /*根据省市区和代售点名称删除代售点*/ var deleteOffice = function(province, city, region, officeName, db, callback){ - var collection = db.collection('office'); - var findString = { - "province":province , - "city": city , - "region": region - }; - var updateString = { - $pull:{ - "offices": { - "officeName": officeName - } - } - }; - collection.update(findString, updateString, function(err, result){ - if(err){ - console.log("Error:" + err); - return; - } + var where_sql= "WHERE name = '" + officeName + "' AND province = '" + province + "' AND city = '" + city + "' AND region = '" + region + "'"; + var sql = "DELETE FROM office " + where_sql; + MysqlClient.query(sql, function (err, result) { + if (err) throw err; + console.log("Number of records deleted: " + result.affectedRows); callback(result); }); }; @@ -101,87 +71,78 @@ var deleteOffice = function(province, city, region, officeName, db, callback){ /*根据省市区代售点信息更新代售点*/ var updateOffice = function(province, city, region, oldOfficeName, newOffice, db, callback){ - var collection = db.collection('office'); - var findString = { - "province":province , - "city": city , - "region": region, - "offices.officeName": oldOfficeName - }; - var updateString = { - $set:{ - 'offices.$.officeName':newOffice.officeName, - 'offices.$.address': newOffice.address, - 'offices.$.workTime': newOffice.workTime, - 'offices.$.windowNum': newOffice.windowNum - } - }; - collection.update(findString, updateString, function(err, result){ - if(err){ - console.log("Error:" + err); - return; - } + var where_sql= "WHERE name = '" + oldOfficeName + "' AND province = '" + province + "' AND city = '" + city + "' AND region = '" + region + "'"; + var set_sql = "SET name = '" + newOffice.name + "', address = '" + newOffice.address + "', workTime = '" + newOffice.workTime + "', windowNum = " + newOffice.windowNum; + var sql = "UPDATE office " + set_sql + " " + where_sql; + console.log("update sql:", sql); + MysqlClient.query(sql, function (err, result) { + if (err) throw err; + console.log("Number of records updated: " + result.affectedRows); callback(result); }); -}; +}; +var insertEntry = function(name, city, province, region, address, workTime, windowNum){ + values = "('" + name + "','" + city +"','" + province + "','" + region +"','"+address +"','"+workTime +"',"+windowNum+")"; + var sql = "INSERT INTO office (name, city, province, region, address, workTime, windowNum)" + + " VALUES " + values; + console.log("insert sql", sql); + MysqlClient.query(sql, function (err, result) { + if (err) throw err; + console.log("1 record inserted, ", result); + }); +} -exports.initMongo = function(callback){ - MongoClient.connect(DB_CONN_STR, function(err, db){ - console.log("initMongo连接上数据库啦!"); - initData(db, function(result){ - db.close(); +exports.initMysql = function(callback){ + MysqlClient.connect(function(err){ + console.log("initMysql连接上数据库啦!"); + initData(function(result){ callback(result); }); }) }; exports.getAll = function(callback){ - MongoClient.connect(DB_CONN_STR, function(err, db){ + MysqlClient.connect(DB_CONN_STR, function(err, db){ console.log("getAll连接上数据库啦!"); getAllOffices(db, function(result){ - db.close(); callback(result); }); }) }; exports.getSpecificOffices = function(province, city, region, callback){ - MongoClient.connect(DB_CONN_STR, function(err, db){ + MysqlClient.connect(DB_CONN_STR, function(err, db){ console.log("getSpecificOffices连接上数据库啦!"); getSpecificOffices(province, city, region, db, function(result){ - db.close(); callback(result); }); }) }; exports.addOffice = function(province, city, region, office, callback){ - MongoClient.connect(DB_CONN_STR, function(err, db){ + MysqlClient.connect(DB_CONN_STR, function(err, db){ console.log("addOffice连接上数据库啦!"); addOffice(province, city, region, office, db, function(result){ - db.close(); callback(result); }); }) }; exports.deleteOffice = function(province, city, region, officeName, callback){ - MongoClient.connect(DB_CONN_STR, function(err, db){ + MysqlClient.connect(DB_CONN_STR, function(err, db){ console.log("deleteOffice连接上数据库啦!"); deleteOffice(province, city, region, officeName, db, function(result){ - db.close(); callback(result); }); }) }; exports.updateOffice = function(province, city, region, oldOfficeName, newOffice, callback){ - MongoClient.connect(DB_CONN_STR, function(err, db){ + MysqlClient.connect(DB_CONN_STR, function(err, db){ console.log("updateOffice连接上数据库啦!"); updateOffice(province, city, region, oldOfficeName, newOffice, db, function(result){ - db.close(); callback(result); }); }) diff --git a/ts-ticket-office-service/bin/router.js b/ts-ticket-office-service/bin/router.js index 3a42ac22e..f182d86ac 100644 --- a/ts-ticket-office-service/bin/router.js +++ b/ts-ticket-office-service/bin/router.js @@ -37,6 +37,8 @@ router.get('/getAll', function(req, res, next) { }); router.post('/getSpecificOffices', function(req, res, next) { + console.log("getSpecificOffices, req.body", req.body); + console.log(req.body.province, req.body.city, req.body.region); db.getSpecificOffices(req.body.province, req.body.city, req.body.region, function(result){ res.set({'Content-Type':'text/json','Encodeing':'utf8'}); console.log("getSpecificOffices=" + JSON.stringify(result)); diff --git a/ts-ticket-office-service/node_modules/.bin/acorn b/ts-ticket-office-service/node_modules/.bin/acorn deleted file mode 100644 index 558ebb98b..000000000 --- a/ts-ticket-office-service/node_modules/.bin/acorn +++ /dev/null @@ -1,15 +0,0 @@ -#!/bin/sh -basedir=$(dirname "$(echo "$0" | sed -e 's,\\,/,g')") - -case `uname` in - *CYGWIN*) basedir=`cygpath -w "$basedir"`;; -esac - -if [ -x "$basedir/node" ]; then - "$basedir/node" "$basedir/../acorn/bin/acorn" "$@" - ret=$? -else - node "$basedir/../acorn/bin/acorn" "$@" - ret=$? -fi -exit $ret diff --git a/ts-ticket-office-service/node_modules/.bin/acorn b/ts-ticket-office-service/node_modules/.bin/acorn new file mode 120000 index 000000000..cf7676038 --- /dev/null +++ b/ts-ticket-office-service/node_modules/.bin/acorn @@ -0,0 +1 @@ +../acorn/bin/acorn \ No newline at end of file diff --git a/ts-ticket-office-service/node_modules/.bin/cleancss b/ts-ticket-office-service/node_modules/.bin/cleancss deleted file mode 100644 index c6992ac57..000000000 --- a/ts-ticket-office-service/node_modules/.bin/cleancss +++ /dev/null @@ -1,15 +0,0 @@ -#!/bin/sh -basedir=$(dirname "$(echo "$0" | sed -e 's,\\,/,g')") - -case `uname` in - *CYGWIN*) basedir=`cygpath -w "$basedir"`;; -esac - -if [ -x "$basedir/node" ]; then - "$basedir/node" "$basedir/../clean-css/bin/cleancss" "$@" - ret=$? -else - node "$basedir/../clean-css/bin/cleancss" "$@" - ret=$? -fi -exit $ret diff --git a/ts-ticket-office-service/node_modules/.bin/cleancss b/ts-ticket-office-service/node_modules/.bin/cleancss new file mode 120000 index 000000000..2a3439ebe --- /dev/null +++ b/ts-ticket-office-service/node_modules/.bin/cleancss @@ -0,0 +1 @@ +../clean-css/bin/cleancss \ No newline at end of file diff --git a/ts-ticket-office-service/node_modules/.bin/jade b/ts-ticket-office-service/node_modules/.bin/jade deleted file mode 100644 index c94f79259..000000000 --- a/ts-ticket-office-service/node_modules/.bin/jade +++ /dev/null @@ -1,15 +0,0 @@ -#!/bin/sh -basedir=$(dirname "$(echo "$0" | sed -e 's,\\,/,g')") - -case `uname` in - *CYGWIN*) basedir=`cygpath -w "$basedir"`;; -esac - -if [ -x "$basedir/node" ]; then - "$basedir/node" "$basedir/../jade/bin/jade.js" "$@" - ret=$? -else - node "$basedir/../jade/bin/jade.js" "$@" - ret=$? -fi -exit $ret diff --git a/ts-ticket-office-service/node_modules/.bin/jade b/ts-ticket-office-service/node_modules/.bin/jade new file mode 120000 index 000000000..65a3bac6f --- /dev/null +++ b/ts-ticket-office-service/node_modules/.bin/jade @@ -0,0 +1 @@ +../jade/bin/jade.js \ No newline at end of file diff --git a/ts-ticket-office-service/node_modules/.bin/mime b/ts-ticket-office-service/node_modules/.bin/mime deleted file mode 100644 index 0dbddf071..000000000 --- a/ts-ticket-office-service/node_modules/.bin/mime +++ /dev/null @@ -1,15 +0,0 @@ -#!/bin/sh -basedir=$(dirname "$(echo "$0" | sed -e 's,\\,/,g')") - -case `uname` in - *CYGWIN*) basedir=`cygpath -w "$basedir"`;; -esac - -if [ -x "$basedir/node" ]; then - "$basedir/node" "$basedir/../mime/cli.js" "$@" - ret=$? -else - node "$basedir/../mime/cli.js" "$@" - ret=$? -fi -exit $ret diff --git a/ts-ticket-office-service/node_modules/.bin/mime b/ts-ticket-office-service/node_modules/.bin/mime new file mode 120000 index 000000000..fbb7ee0ee --- /dev/null +++ b/ts-ticket-office-service/node_modules/.bin/mime @@ -0,0 +1 @@ +../mime/cli.js \ No newline at end of file diff --git a/ts-ticket-office-service/node_modules/.bin/mkdirp b/ts-ticket-office-service/node_modules/.bin/mkdirp deleted file mode 100644 index 4b0046722..000000000 --- a/ts-ticket-office-service/node_modules/.bin/mkdirp +++ /dev/null @@ -1,15 +0,0 @@ -#!/bin/sh -basedir=$(dirname "$(echo "$0" | sed -e 's,\\,/,g')") - -case `uname` in - *CYGWIN*) basedir=`cygpath -w "$basedir"`;; -esac - -if [ -x "$basedir/node" ]; then - "$basedir/node" "$basedir/../mkdirp/bin/cmd.js" "$@" - ret=$? -else - node "$basedir/../mkdirp/bin/cmd.js" "$@" - ret=$? -fi -exit $ret diff --git a/ts-ticket-office-service/node_modules/.bin/mkdirp b/ts-ticket-office-service/node_modules/.bin/mkdirp new file mode 120000 index 000000000..017896ceb --- /dev/null +++ b/ts-ticket-office-service/node_modules/.bin/mkdirp @@ -0,0 +1 @@ +../mkdirp/bin/cmd.js \ No newline at end of file diff --git a/ts-ticket-office-service/node_modules/.bin/semver b/ts-ticket-office-service/node_modules/.bin/semver deleted file mode 100644 index d592e6930..000000000 --- a/ts-ticket-office-service/node_modules/.bin/semver +++ /dev/null @@ -1,15 +0,0 @@ -#!/bin/sh -basedir=$(dirname "$(echo "$0" | sed -e 's,\\,/,g')") - -case `uname` in - *CYGWIN*) basedir=`cygpath -w "$basedir"`;; -esac - -if [ -x "$basedir/node" ]; then - "$basedir/node" "$basedir/../semver/bin/semver" "$@" - ret=$? -else - node "$basedir/../semver/bin/semver" "$@" - ret=$? -fi -exit $ret diff --git a/ts-ticket-office-service/node_modules/.bin/uglifyjs b/ts-ticket-office-service/node_modules/.bin/uglifyjs deleted file mode 100644 index de7b74f60..000000000 --- a/ts-ticket-office-service/node_modules/.bin/uglifyjs +++ /dev/null @@ -1,15 +0,0 @@ -#!/bin/sh -basedir=$(dirname "$(echo "$0" | sed -e 's,\\,/,g')") - -case `uname` in - *CYGWIN*) basedir=`cygpath -w "$basedir"`;; -esac - -if [ -x "$basedir/node" ]; then - "$basedir/node" "$basedir/../uglify-js/bin/uglifyjs" "$@" - ret=$? -else - node "$basedir/../uglify-js/bin/uglifyjs" "$@" - ret=$? -fi -exit $ret diff --git a/ts-ticket-office-service/node_modules/.bin/uglifyjs b/ts-ticket-office-service/node_modules/.bin/uglifyjs new file mode 120000 index 000000000..fef3468b6 --- /dev/null +++ b/ts-ticket-office-service/node_modules/.bin/uglifyjs @@ -0,0 +1 @@ +../uglify-js/bin/uglifyjs \ No newline at end of file diff --git a/ts-ticket-office-service/node_modules/.package-lock.json b/ts-ticket-office-service/node_modules/.package-lock.json new file mode 100644 index 000000000..767ef8ed7 --- /dev/null +++ b/ts-ticket-office-service/node_modules/.package-lock.json @@ -0,0 +1,1157 @@ +{ + "name": "ts-ticket-office-service", + "version": "0.0.0", + "lockfileVersion": 2, + "requires": true, + "packages": { + "node_modules/@types/node": { + "version": "18.6.1", + "resolved": "https://registry.npmjs.org/@types/node/-/node-18.6.1.tgz", + "integrity": "sha512-z+2vB6yDt1fNwKOeGbckpmirO+VBDuQqecXkgeIqDlaOtmKn6hPR/viQ8cxCfqLU4fTlvM3+YjM367TukWdxpg==" + }, + "node_modules/@types/webidl-conversions": { + "version": "6.1.1", + "resolved": "https://registry.npmjs.org/@types/webidl-conversions/-/webidl-conversions-6.1.1.tgz", + "integrity": "sha512-XAahCdThVuCFDQLT7R7Pk/vqeObFNL3YqRyFZg+AqAP/W1/w3xHaIxuW7WszQqTbIBOPRcItYJIou3i/mppu3Q==" + }, + "node_modules/@types/whatwg-url": { + "version": "8.2.2", + "resolved": "https://registry.npmjs.org/@types/whatwg-url/-/whatwg-url-8.2.2.tgz", + "integrity": "sha512-FtQu10RWgn3D9U4aazdwIE2yzphmTJREDqNdODHrbrZmmMqI0vMheC/6NE/J1Yveaj8H+ela+YwWTjq5PGmuhA==", + "dependencies": { + "@types/node": "*", + "@types/webidl-conversions": "*" + } + }, + "node_modules/accepts": { + "version": "1.3.4", + "license": "MIT", + "dependencies": { + "mime-types": "~2.1.16", + "negotiator": "0.6.1" + }, + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/acorn": { + "version": "2.7.0", + "license": "MIT", + "bin": { + "acorn": "bin/acorn" + }, + "engines": { + "node": ">=0.4.0" + } + }, + "node_modules/acorn-globals": { + "version": "1.0.9", + "license": "MIT", + "dependencies": { + "acorn": "^2.1.0" + } + }, + "node_modules/align-text": { + "version": "0.1.4", + "license": "MIT", + "dependencies": { + "kind-of": "^3.0.2", + "longest": "^1.0.1", + "repeat-string": "^1.5.2" + }, + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/amdefine": { + "version": "1.0.1", + "license": "BSD-3-Clause OR MIT", + "engines": { + "node": ">=0.4.2" + } + }, + "node_modules/array-flatten": { + "version": "1.1.1", + "license": "MIT" + }, + "node_modules/asap": { + "version": "1.0.0" + }, + "node_modules/base64-js": { + "version": "1.5.1", + "resolved": "https://registry.npmjs.org/base64-js/-/base64-js-1.5.1.tgz", + "integrity": "sha512-AKpaYlHn8t4SVbOHCy+b5+KKgvR4vrsD8vbvrbiQJps7fKDTkjkDry6ji0rUJjC0kzbNePLwzxq8iypo41qeWA==", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/feross" + }, + { + "type": "patreon", + "url": "https://www.patreon.com/feross" + }, + { + "type": "consulting", + "url": "https://feross.org/support" + } + ] + }, + "node_modules/basic-auth": { + "version": "2.0.0", + "license": "MIT", + "dependencies": { + "safe-buffer": "5.1.1" + }, + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/bignumber.js": { + "version": "9.0.0", + "resolved": "https://registry.npmjs.org/bignumber.js/-/bignumber.js-9.0.0.tgz", + "integrity": "sha512-t/OYhhJ2SD+YGBQcjY8GzzDHEk9f3nerxjtfa6tlMXfe7frs/WozhvCNoGvpM0P3bNf3Gq5ZRMlGr5f3r4/N8A==", + "engines": { + "node": "*" + } + }, + "node_modules/body-parser": { + "version": "1.18.2", + "license": "MIT", + "dependencies": { + "bytes": "3.0.0", + "content-type": "~1.0.4", + "debug": "2.6.9", + "depd": "~1.1.1", + "http-errors": "~1.6.2", + "iconv-lite": "0.4.19", + "on-finished": "~2.3.0", + "qs": "6.5.1", + "raw-body": "2.3.2", + "type-is": "~1.6.15" + }, + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/bson": { + "version": "4.6.5", + "resolved": "https://registry.npmjs.org/bson/-/bson-4.6.5.tgz", + "integrity": "sha512-uqrgcjyOaZsHfz7ea8zLRCLe1u+QGUSzMZmvXqO24CDW7DWoW1qiN9folSwa7hSneTSgM2ykDIzF5kcQQ8cwNw==", + "dependencies": { + "buffer": "^5.6.0" + }, + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/buffer": { + "version": "5.7.1", + "resolved": "https://registry.npmjs.org/buffer/-/buffer-5.7.1.tgz", + "integrity": "sha512-EHcyIPBQ4BSGlvjB16k5KgAJ27CIsHY/2JBmCRReo48y9rQ3MaUzWX3KVlBa4U7MyX02HdVj0K7C3WaB3ju7FQ==", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/feross" + }, + { + "type": "patreon", + "url": "https://www.patreon.com/feross" + }, + { + "type": "consulting", + "url": "https://feross.org/support" + } + ], + "dependencies": { + "base64-js": "^1.3.1", + "ieee754": "^1.1.13" + } + }, + "node_modules/bytes": { + "version": "3.0.0", + "license": "MIT", + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/camelcase": { + "version": "1.2.1", + "license": "MIT", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/center-align": { + "version": "0.1.3", + "license": "MIT", + "dependencies": { + "align-text": "^0.1.3", + "lazy-cache": "^1.0.3" + }, + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/character-parser": { + "version": "1.2.1", + "license": "MIT" + }, + "node_modules/clean-css": { + "version": "3.4.28", + "license": "MIT", + "dependencies": { + "commander": "2.8.x", + "source-map": "0.4.x" + }, + "bin": { + "cleancss": "bin/cleancss" + }, + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/clean-css/node_modules/commander": { + "version": "2.8.1", + "license": "MIT", + "dependencies": { + "graceful-readlink": ">= 1.0.0" + }, + "engines": { + "node": ">= 0.6.x" + } + }, + "node_modules/cliui": { + "version": "2.1.0", + "license": "ISC", + "dependencies": { + "center-align": "^0.1.1", + "right-align": "^0.1.1", + "wordwrap": "0.0.2" + } + }, + "node_modules/cliui/node_modules/wordwrap": { + "version": "0.0.2", + "license": "MIT/X11", + "engines": { + "node": ">=0.4.0" + } + }, + "node_modules/commander": { + "version": "2.6.0", + "license": "MIT", + "engines": { + "node": ">= 0.6.x" + } + }, + "node_modules/constantinople": { + "version": "3.0.2", + "license": "MIT", + "dependencies": { + "acorn": "^2.1.0" + } + }, + "node_modules/content-disposition": { + "version": "0.5.2", + "license": "MIT", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/content-type": { + "version": "1.0.4", + "license": "MIT", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/cookie": { + "version": "0.3.1", + "license": "MIT", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/cookie-parser": { + "version": "1.4.3", + "license": "MIT", + "dependencies": { + "cookie": "0.3.1", + "cookie-signature": "1.0.6" + }, + "engines": { + "node": ">= 0.8.0" + } + }, + "node_modules/cookie-signature": { + "version": "1.0.6", + "license": "MIT" + }, + "node_modules/core-util-is": { + "version": "1.0.2", + "license": "MIT" + }, + "node_modules/css": { + "version": "1.0.8", + "dependencies": { + "css-parse": "1.0.4", + "css-stringify": "1.0.5" + } + }, + "node_modules/css-parse": { + "version": "1.0.4" + }, + "node_modules/css-stringify": { + "version": "1.0.5" + }, + "node_modules/debug": { + "version": "2.6.9", + "license": "MIT", + "dependencies": { + "ms": "2.0.0" + } + }, + "node_modules/decamelize": { + "version": "1.2.0", + "license": "MIT", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/denque": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/denque/-/denque-2.1.0.tgz", + "integrity": "sha512-HVQE3AAb/pxF8fQAoiqpvg9i3evqug3hoiwakOyZAwJm+6vZehbkYXZ0l4JxS+I3QxM97v5aaRNhj8v5oBhekw==", + "engines": { + "node": ">=0.10" + } + }, + "node_modules/depd": { + "version": "1.1.1", + "license": "MIT", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/destroy": { + "version": "1.0.4", + "license": "MIT" + }, + "node_modules/ee-first": { + "version": "1.1.1", + "license": "MIT" + }, + "node_modules/encodeurl": { + "version": "1.0.1", + "license": "MIT", + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/escape-html": { + "version": "1.0.3", + "license": "MIT" + }, + "node_modules/etag": { + "version": "1.8.1", + "license": "MIT", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/express": { + "version": "4.15.5", + "license": "MIT", + "dependencies": { + "accepts": "~1.3.3", + "array-flatten": "1.1.1", + "content-disposition": "0.5.2", + "content-type": "~1.0.2", + "cookie": "0.3.1", + "cookie-signature": "1.0.6", + "debug": "2.6.9", + "depd": "~1.1.1", + "encodeurl": "~1.0.1", + "escape-html": "~1.0.3", + "etag": "~1.8.0", + "finalhandler": "~1.0.6", + "fresh": "0.5.2", + "merge-descriptors": "1.0.1", + "methods": "~1.1.2", + "on-finished": "~2.3.0", + "parseurl": "~1.3.1", + "path-to-regexp": "0.1.7", + "proxy-addr": "~1.1.5", + "qs": "6.5.0", + "range-parser": "~1.2.0", + "send": "0.15.6", + "serve-static": "1.12.6", + "setprototypeof": "1.0.3", + "statuses": "~1.3.1", + "type-is": "~1.6.15", + "utils-merge": "1.0.0", + "vary": "~1.1.1" + }, + "engines": { + "node": ">= 0.10.0" + } + }, + "node_modules/express/node_modules/qs": { + "version": "6.5.0", + "license": "BSD-3-Clause", + "engines": { + "node": ">=0.6" + } + }, + "node_modules/finalhandler": { + "version": "1.0.6", + "license": "MIT", + "dependencies": { + "debug": "2.6.9", + "encodeurl": "~1.0.1", + "escape-html": "~1.0.3", + "on-finished": "~2.3.0", + "parseurl": "~1.3.2", + "statuses": "~1.3.1", + "unpipe": "~1.0.0" + }, + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/forwarded": { + "version": "0.1.2", + "license": "MIT", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/fresh": { + "version": "0.5.2", + "license": "MIT", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/fs": { + "version": "0.0.1-security", + "license": "ISC" + }, + "node_modules/graceful-readlink": { + "version": "1.0.1", + "license": "MIT" + }, + "node_modules/http-errors": { + "version": "1.6.2", + "license": "MIT", + "dependencies": { + "depd": "1.1.1", + "inherits": "2.0.3", + "setprototypeof": "1.0.3", + "statuses": ">= 1.3.1 < 2" + }, + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/iconv-lite": { + "version": "0.4.19", + "license": "MIT", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/ieee754": { + "version": "1.2.1", + "resolved": "https://registry.npmjs.org/ieee754/-/ieee754-1.2.1.tgz", + "integrity": "sha512-dcyqhDvX1C46lXZcVqCpK+FtMRQVdIMN6/Df5js2zouUsqG7I6sFxitIC+7KYK29KdXOLHdu9zL4sFnoVQnqaA==", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/feross" + }, + { + "type": "patreon", + "url": "https://www.patreon.com/feross" + }, + { + "type": "consulting", + "url": "https://feross.org/support" + } + ] + }, + "node_modules/inherits": { + "version": "2.0.3", + "license": "ISC" + }, + "node_modules/ip": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/ip/-/ip-2.0.0.tgz", + "integrity": "sha512-WKa+XuLG1A1R0UWhl2+1XQSi+fZWMsYKffMZTTYsiZaUD8k2yDAj5atimTUD2TZkyCkNEeYE5NhFZmupOGtjYQ==" + }, + "node_modules/ipaddr.js": { + "version": "1.4.0", + "license": "MIT", + "engines": { + "node": ">= 0.10" + } + }, + "node_modules/is-buffer": { + "version": "1.1.5", + "license": "MIT" + }, + "node_modules/is-promise": { + "version": "2.1.0", + "license": "MIT" + }, + "node_modules/isarray": { + "version": "1.0.0", + "license": "MIT" + }, + "node_modules/jade": { + "version": "1.11.0", + "deprecated": "Jade has been renamed to pug, please install the latest version of pug instead of jade", + "license": "MIT", + "dependencies": { + "character-parser": "1.2.1", + "clean-css": "^3.1.9", + "commander": "~2.6.0", + "constantinople": "~3.0.1", + "jstransformer": "0.0.2", + "mkdirp": "~0.5.0", + "transformers": "2.1.0", + "uglify-js": "^2.4.19", + "void-elements": "~2.0.1", + "with": "~4.0.0" + }, + "bin": { + "jade": "bin/jade.js" + } + }, + "node_modules/jstransformer": { + "version": "0.0.2", + "license": "MIT", + "dependencies": { + "is-promise": "^2.0.0", + "promise": "^6.0.1" + } + }, + "node_modules/kind-of": { + "version": "3.2.2", + "license": "MIT", + "dependencies": { + "is-buffer": "^1.1.5" + }, + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/lazy-cache": { + "version": "1.0.4", + "license": "MIT", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/longest": { + "version": "1.0.1", + "license": "MIT", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/media-typer": { + "version": "0.3.0", + "license": "MIT", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/memory-pager": { + "version": "1.5.0", + "resolved": "https://registry.npmjs.org/memory-pager/-/memory-pager-1.5.0.tgz", + "integrity": "sha512-ZS4Bp4r/Zoeq6+NLJpP+0Zzm0pR8whtGPf1XExKLJBAczGMnSi3It14OiNCStjQjM6NU1okjQGSxgEZN8eBYKg==", + "optional": true + }, + "node_modules/merge-descriptors": { + "version": "1.0.1", + "license": "MIT" + }, + "node_modules/methods": { + "version": "1.1.2", + "license": "MIT", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/mime": { + "version": "1.3.4", + "bin": { + "mime": "cli.js" + } + }, + "node_modules/mime-db": { + "version": "1.30.0", + "license": "MIT", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/mime-types": { + "version": "2.1.17", + "license": "MIT", + "dependencies": { + "mime-db": "~1.30.0" + }, + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/minimist": { + "version": "1.2.6", + "resolved": "https://registry.npmjs.org/minimist/-/minimist-1.2.6.tgz", + "integrity": "sha512-Jsjnk4bw3YJqYzbdyBiNsPWHPfO++UGG749Cxs6peCu5Xg4nrena6OVxOYxrQTqww0Jmwt+Ref8rggumkTLz9Q==" + }, + "node_modules/mkdirp": { + "version": "0.5.6", + "resolved": "https://registry.npmjs.org/mkdirp/-/mkdirp-0.5.6.tgz", + "integrity": "sha512-FP+p8RB8OWpF3YZBCrP5gtADmtXApB5AMLn+vdyA+PyxCjrCs00mjyUozssO33cwDeT3wNGdLxJ5M//YqtHAJw==", + "dependencies": { + "minimist": "^1.2.6" + }, + "bin": { + "mkdirp": "bin/cmd.js" + } + }, + "node_modules/mongo": { + "version": "0.1.0", + "dependencies": { + "mongodb": "*" + }, + "engines": { + "node": ">= 0.4.0" + } + }, + "node_modules/mongodb": { + "version": "4.8.0", + "resolved": "https://registry.npmjs.org/mongodb/-/mongodb-4.8.0.tgz", + "integrity": "sha512-a0eVzm1e1kxwnzJV1wZXIS54KegM2y6wXTXOGTSAxr/E2YOUkl/zGBHNSI4z+6z+YQtVdzDqy1nJ4n5MxYJRnQ==", + "dependencies": { + "bson": "^4.6.5", + "denque": "^2.0.1", + "mongodb-connection-string-url": "^2.5.2", + "socks": "^2.6.2" + }, + "engines": { + "node": ">=12.9.0" + }, + "optionalDependencies": { + "saslprep": "^1.0.3" + } + }, + "node_modules/mongodb-connection-string-url": { + "version": "2.5.3", + "resolved": "https://registry.npmjs.org/mongodb-connection-string-url/-/mongodb-connection-string-url-2.5.3.tgz", + "integrity": "sha512-f+/WsED+xF4B74l3k9V/XkTVj5/fxFH2o5ToKXd8Iyi5UhM+sO9u0Ape17Mvl/GkZaFtM0HQnzAG5OTmhKw+tQ==", + "dependencies": { + "@types/whatwg-url": "^8.2.1", + "whatwg-url": "^11.0.0" + } + }, + "node_modules/morgan": { + "version": "1.9.1", + "resolved": "https://registry.npmjs.org/morgan/-/morgan-1.9.1.tgz", + "integrity": "sha512-HQStPIV4y3afTiCYVxirakhlCfGkI161c76kKFca7Fk1JusM//Qeo1ej2XaMniiNeaZklMVrh3vTtIzpzwbpmA==", + "dependencies": { + "basic-auth": "~2.0.0", + "debug": "2.6.9", + "depd": "~1.1.2", + "on-finished": "~2.3.0", + "on-headers": "~1.0.1" + }, + "engines": { + "node": ">= 0.8.0" + } + }, + "node_modules/morgan/node_modules/depd": { + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/depd/-/depd-1.1.2.tgz", + "integrity": "sha512-7emPTl6Dpo6JRXOXjLRxck+FlLRX5847cLKEn00PLAgc3g2hTZZgr+e4c2v6QpSmLeFP3n5yUo7ft6avBK/5jQ==", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/ms": { + "version": "2.0.0", + "license": "MIT" + }, + "node_modules/mysql": { + "version": "2.18.1", + "resolved": "https://registry.npmjs.org/mysql/-/mysql-2.18.1.tgz", + "integrity": "sha512-Bca+gk2YWmqp2Uf6k5NFEurwY/0td0cpebAucFpY/3jhrwrVGuxU2uQFCHjU19SJfje0yQvi+rVWdq78hR5lig==", + "dependencies": { + "bignumber.js": "9.0.0", + "readable-stream": "2.3.7", + "safe-buffer": "5.1.2", + "sqlstring": "2.3.1" + }, + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/mysql/node_modules/process-nextick-args": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/process-nextick-args/-/process-nextick-args-2.0.1.tgz", + "integrity": "sha512-3ouUOpQhtgrbOa17J7+uxOTpITYWaGP7/AhoR3+A+/1e9skrzelGi/dXzEYyvbxubEF6Wn2ypscTKiKJFFn1ag==" + }, + "node_modules/mysql/node_modules/readable-stream": { + "version": "2.3.7", + "resolved": "https://registry.npmjs.org/readable-stream/-/readable-stream-2.3.7.tgz", + "integrity": "sha512-Ebho8K4jIbHAxnuxi7o42OrZgF/ZTNcsZj6nRKyUmkhLFq8CHItp/fy6hQZuZmP/n3yZ9VBUbp4zz/mX8hmYPw==", + "dependencies": { + "core-util-is": "~1.0.0", + "inherits": "~2.0.3", + "isarray": "~1.0.0", + "process-nextick-args": "~2.0.0", + "safe-buffer": "~5.1.1", + "string_decoder": "~1.1.1", + "util-deprecate": "~1.0.1" + } + }, + "node_modules/mysql/node_modules/safe-buffer": { + "version": "5.1.2", + "resolved": "https://registry.npmjs.org/safe-buffer/-/safe-buffer-5.1.2.tgz", + "integrity": "sha512-Gd2UZBJDkXlY7GbJxfsE8/nvKkUEU1G38c1siN6QP6a9PT9MmHB8GnpscSmMJSoF8LOIrt8ud/wPtojys4G6+g==" + }, + "node_modules/mysql/node_modules/string_decoder": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/string_decoder/-/string_decoder-1.1.1.tgz", + "integrity": "sha512-n/ShnvDi6FHbbVfviro+WojiFzv+s8MPMHBczVePfUpDJLwoLT0ht1l4YwBCbi8pJAveEEdnkHyPyTP/mzRfwg==", + "dependencies": { + "safe-buffer": "~5.1.0" + } + }, + "node_modules/negotiator": { + "version": "0.6.1", + "license": "MIT", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/on-finished": { + "version": "2.3.0", + "license": "MIT", + "dependencies": { + "ee-first": "1.1.1" + }, + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/on-headers": { + "version": "1.0.1", + "license": "MIT", + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/optimist": { + "version": "0.3.7", + "license": "MIT/X11", + "dependencies": { + "wordwrap": "~0.0.2" + } + }, + "node_modules/parseurl": { + "version": "1.3.2", + "license": "MIT", + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/path-to-regexp": { + "version": "0.1.7", + "license": "MIT" + }, + "node_modules/promise": { + "version": "6.1.0", + "license": "MIT", + "dependencies": { + "asap": "~1.0.0" + } + }, + "node_modules/proxy-addr": { + "version": "1.1.5", + "license": "MIT", + "dependencies": { + "forwarded": "~0.1.0", + "ipaddr.js": "1.4.0" + }, + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/punycode": { + "version": "2.1.1", + "resolved": "https://registry.npmjs.org/punycode/-/punycode-2.1.1.tgz", + "integrity": "sha512-XRsRjdf+j5ml+y/6GKHPZbrF/8p2Yga0JPtdqTIY2Xe5ohJPD9saDJJLPvp9+NSBprVvevdXZybnj2cv8OEd0A==", + "engines": { + "node": ">=6" + } + }, + "node_modules/qs": { + "version": "6.5.1", + "license": "BSD-3-Clause", + "engines": { + "node": ">=0.6" + } + }, + "node_modules/range-parser": { + "version": "1.2.0", + "license": "MIT", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/raw-body": { + "version": "2.3.2", + "license": "MIT", + "dependencies": { + "bytes": "3.0.0", + "http-errors": "1.6.2", + "iconv-lite": "0.4.19", + "unpipe": "1.0.0" + }, + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/repeat-string": { + "version": "1.6.1", + "license": "MIT", + "engines": { + "node": ">=0.10" + } + }, + "node_modules/right-align": { + "version": "0.1.3", + "license": "MIT", + "dependencies": { + "align-text": "^0.1.1" + }, + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/safe-buffer": { + "version": "5.1.1", + "license": "MIT" + }, + "node_modules/saslprep": { + "version": "1.0.3", + "resolved": "https://registry.npmjs.org/saslprep/-/saslprep-1.0.3.tgz", + "integrity": "sha512-/MY/PEMbk2SuY5sScONwhUDsV2p77Znkb/q3nSVstq/yQzYJOH/Azh29p9oJLsl3LnQwSvZDKagDGBsBwSooag==", + "optional": true, + "dependencies": { + "sparse-bitfield": "^3.0.3" + }, + "engines": { + "node": ">=6" + } + }, + "node_modules/send": { + "version": "0.15.6", + "license": "MIT", + "dependencies": { + "debug": "2.6.9", + "depd": "~1.1.1", + "destroy": "~1.0.4", + "encodeurl": "~1.0.1", + "escape-html": "~1.0.3", + "etag": "~1.8.1", + "fresh": "0.5.2", + "http-errors": "~1.6.2", + "mime": "1.3.4", + "ms": "2.0.0", + "on-finished": "~2.3.0", + "range-parser": "~1.2.0", + "statuses": "~1.3.1" + }, + "engines": { + "node": ">= 0.8.0" + } + }, + "node_modules/serve-favicon": { + "version": "2.4.5", + "license": "MIT", + "dependencies": { + "etag": "~1.8.1", + "fresh": "0.5.2", + "ms": "2.0.0", + "parseurl": "~1.3.2", + "safe-buffer": "5.1.1" + }, + "engines": { + "node": ">= 0.8.0" + } + }, + "node_modules/serve-static": { + "version": "1.12.6", + "license": "MIT", + "dependencies": { + "encodeurl": "~1.0.1", + "escape-html": "~1.0.3", + "parseurl": "~1.3.2", + "send": "0.15.6" + }, + "engines": { + "node": ">= 0.8.0" + } + }, + "node_modules/setprototypeof": { + "version": "1.0.3", + "license": "ISC" + }, + "node_modules/smart-buffer": { + "version": "4.2.0", + "resolved": "https://registry.npmjs.org/smart-buffer/-/smart-buffer-4.2.0.tgz", + "integrity": "sha512-94hK0Hh8rPqQl2xXc3HsaBoOXKV20MToPkcXvwbISWLEs+64sBq5kFgn2kJDHb1Pry9yrP0dxrCI9RRci7RXKg==", + "engines": { + "node": ">= 6.0.0", + "npm": ">= 3.0.0" + } + }, + "node_modules/socks": { + "version": "2.7.0", + "resolved": "https://registry.npmjs.org/socks/-/socks-2.7.0.tgz", + "integrity": "sha512-scnOe9y4VuiNUULJN72GrM26BNOjVsfPXI+j+98PkyEfsIXroa5ofyjT+FzGvn/xHs73U2JtoBYAVx9Hl4quSA==", + "dependencies": { + "ip": "^2.0.0", + "smart-buffer": "^4.2.0" + }, + "engines": { + "node": ">= 10.13.0", + "npm": ">= 3.0.0" + } + }, + "node_modules/source-map": { + "version": "0.4.4", + "license": "BSD-3-Clause", + "dependencies": { + "amdefine": ">=0.0.4" + }, + "engines": { + "node": ">=0.8.0" + } + }, + "node_modules/sparse-bitfield": { + "version": "3.0.3", + "resolved": "https://registry.npmjs.org/sparse-bitfield/-/sparse-bitfield-3.0.3.tgz", + "integrity": "sha512-kvzhi7vqKTfkh0PZU+2D2PIllw2ymqJKujUcyPMd9Y75Nv4nPbGJZXNhxsgdQab2BmlDct1YnfQCguEvHr7VsQ==", + "optional": true, + "dependencies": { + "memory-pager": "^1.0.2" + } + }, + "node_modules/sqlstring": { + "version": "2.3.1", + "resolved": "https://registry.npmjs.org/sqlstring/-/sqlstring-2.3.1.tgz", + "integrity": "sha512-ooAzh/7dxIG5+uDik1z/Rd1vli0+38izZhGzSa34FwR7IbelPWCCKSNIl8jlL/F7ERvy8CB2jNeM1E9i9mXMAQ==", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/statuses": { + "version": "1.3.1", + "license": "MIT", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/tr46": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/tr46/-/tr46-3.0.0.tgz", + "integrity": "sha512-l7FvfAHlcmulp8kr+flpQZmVwtu7nfRV7NZujtN0OqES8EL4O4e0qqzL0DC5gAvx/ZC/9lk6rhcUwYvkBnBnYA==", + "dependencies": { + "punycode": "^2.1.1" + }, + "engines": { + "node": ">=12" + } + }, + "node_modules/transformers": { + "version": "2.1.0", + "deprecated": "Deprecated, use jstransformer", + "license": "MIT", + "dependencies": { + "css": "~1.0.8", + "promise": "~2.0", + "uglify-js": "~2.2.5" + } + }, + "node_modules/transformers/node_modules/is-promise": { + "version": "1.0.1", + "license": "MIT" + }, + "node_modules/transformers/node_modules/promise": { + "version": "2.0.0", + "license": "MIT", + "dependencies": { + "is-promise": "~1" + } + }, + "node_modules/transformers/node_modules/source-map": { + "version": "0.1.43", + "dependencies": { + "amdefine": ">=0.0.4" + }, + "engines": { + "node": ">=0.8.0" + } + }, + "node_modules/transformers/node_modules/uglify-js": { + "version": "2.2.5", + "dependencies": { + "optimist": "~0.3.5", + "source-map": "~0.1.7" + }, + "bin": { + "uglifyjs": "bin/uglifyjs" + }, + "engines": { + "node": ">=0.4.0" + } + }, + "node_modules/type-is": { + "version": "1.6.15", + "license": "MIT", + "dependencies": { + "media-typer": "0.3.0", + "mime-types": "~2.1.15" + }, + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/uglify-js": { + "version": "2.8.29", + "license": "BSD-2-Clause", + "dependencies": { + "source-map": "~0.5.1", + "yargs": "~3.10.0" + }, + "bin": { + "uglifyjs": "bin/uglifyjs" + }, + "engines": { + "node": ">=0.8.0" + }, + "optionalDependencies": { + "uglify-to-browserify": "~1.0.0" + } + }, + "node_modules/uglify-js/node_modules/source-map": { + "version": "0.5.7", + "license": "BSD-3-Clause", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/uglify-to-browserify": { + "version": "1.0.2", + "license": "MIT", + "optional": true + }, + "node_modules/unpipe": { + "version": "1.0.0", + "license": "MIT", + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/util-deprecate": { + "version": "1.0.2", + "license": "MIT" + }, + "node_modules/utils-merge": { + "version": "1.0.0", + "engines": { + "node": ">= 0.4.0" + } + }, + "node_modules/vary": { + "version": "1.1.2", + "license": "MIT", + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/void-elements": { + "version": "2.0.1", + "license": "MIT", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/webidl-conversions": { + "version": "7.0.0", + "resolved": "https://registry.npmjs.org/webidl-conversions/-/webidl-conversions-7.0.0.tgz", + "integrity": "sha512-VwddBukDzu71offAQR975unBIGqfKZpM+8ZX6ySk8nYhVoo5CYaZyzt3YBvYtRtO+aoGlqxPg/B87NGVZ/fu6g==", + "engines": { + "node": ">=12" + } + }, + "node_modules/whatwg-url": { + "version": "11.0.0", + "resolved": "https://registry.npmjs.org/whatwg-url/-/whatwg-url-11.0.0.tgz", + "integrity": "sha512-RKT8HExMpoYx4igMiVMY83lN6UeITKJlBQ+vR/8ZJ8OCdSiN3RwCq+9gH0+Xzj0+5IrM6i4j/6LuvzbZIQgEcQ==", + "dependencies": { + "tr46": "^3.0.0", + "webidl-conversions": "^7.0.0" + }, + "engines": { + "node": ">=12" + } + }, + "node_modules/window-size": { + "version": "0.1.0", + "engines": { + "node": ">= 0.8.0" + } + }, + "node_modules/with": { + "version": "4.0.3", + "license": "MIT", + "dependencies": { + "acorn": "^1.0.1", + "acorn-globals": "^1.0.3" + } + }, + "node_modules/with/node_modules/acorn": { + "version": "1.2.2", + "license": "MIT", + "bin": { + "acorn": "bin/acorn" + }, + "engines": { + "node": ">=0.4.0" + } + }, + "node_modules/wordwrap": { + "version": "0.0.3", + "license": "MIT", + "engines": { + "node": ">=0.4.0" + } + }, + "node_modules/yargs": { + "version": "3.10.0", + "license": "MIT", + "dependencies": { + "camelcase": "^1.0.2", + "cliui": "^2.1.0", + "decamelize": "^1.0.0", + "window-size": "0.1.0" + } + } + } +} diff --git a/ts-ticket-office-service/node_modules/@types/node/LICENSE b/ts-ticket-office-service/node_modules/@types/node/LICENSE new file mode 100755 index 000000000..9e841e7a2 --- /dev/null +++ b/ts-ticket-office-service/node_modules/@types/node/LICENSE @@ -0,0 +1,21 @@ + MIT License + + Copyright (c) Microsoft Corporation. + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated documentation files (the "Software"), to deal + in the Software without restriction, including without limitation the rights + to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + copies of the Software, and to permit persons to whom the Software is + furnished to do so, subject to the following conditions: + + The above copyright notice and this permission notice shall be included in all + copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + SOFTWARE diff --git a/ts-ticket-office-service/node_modules/@types/node/README.md b/ts-ticket-office-service/node_modules/@types/node/README.md new file mode 100755 index 000000000..245373ea7 --- /dev/null +++ b/ts-ticket-office-service/node_modules/@types/node/README.md @@ -0,0 +1,16 @@ +# Installation +> `npm install --save @types/node` + +# Summary +This package contains type definitions for Node.js (https://nodejs.org/). + +# Details +Files were exported from https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/node. + +### Additional Details + * Last updated: Mon, 25 Jul 2022 03:02:21 GMT + * Dependencies: none + * Global values: `AbortController`, `AbortSignal`, `__dirname`, `__filename`, `console`, `exports`, `gc`, `global`, `module`, `process`, `require`, `structuredClone` + +# Credits +These definitions were written by [Microsoft TypeScript](https://github.com/Microsoft), [DefinitelyTyped](https://github.com/DefinitelyTyped), [Alberto Schiabel](https://github.com/jkomyno), [Alvis HT Tang](https://github.com/alvis), [Andrew Makarov](https://github.com/r3nya), [Benjamin Toueg](https://github.com/btoueg), [Chigozirim C.](https://github.com/smac89), [David Junger](https://github.com/touffy), [Deividas Bakanas](https://github.com/DeividasBakanas), [Eugene Y. Q. Shen](https://github.com/eyqs), [Hannes Magnusson](https://github.com/Hannes-Magnusson-CK), [Huw](https://github.com/hoo29), [Kelvin Jin](https://github.com/kjin), [Klaus Meinhardt](https://github.com/ajafff), [Lishude](https://github.com/islishude), [Mariusz Wiktorczyk](https://github.com/mwiktorczyk), [Mohsen Azimi](https://github.com/mohsen1), [Nicolas Even](https://github.com/n-e), [Nikita Galkin](https://github.com/galkin), [Parambir Singh](https://github.com/parambirs), [Sebastian Silbermann](https://github.com/eps1lon), [Simon Schick](https://github.com/SimonSchick), [Thomas den Hollander](https://github.com/ThomasdenH), [Wilco Bakker](https://github.com/WilcoBakker), [wwwy3y3](https://github.com/wwwy3y3), [Samuel Ainsworth](https://github.com/samuela), [Kyle Uehlein](https://github.com/kuehlein), [Thanik Bhongbhibhat](https://github.com/bhongy), [Marcin Kopacz](https://github.com/chyzwar), [Trivikram Kamat](https://github.com/trivikr), [Junxiao Shi](https://github.com/yoursunny), [Ilia Baryshnikov](https://github.com/qwelias), [ExE Boss](https://github.com/ExE-Boss), [Piotr Błażejewicz](https://github.com/peterblazejewicz), [Anna Henningsen](https://github.com/addaleax), [Victor Perin](https://github.com/victorperin), [Yongsheng Zhang](https://github.com/ZYSzys), [NodeJS Contributors](https://github.com/NodeJS), [Linus Unnebäck](https://github.com/LinusU), [wafuwafu13](https://github.com/wafuwafu13), and [Matteo Collina](https://github.com/mcollina). diff --git a/ts-ticket-office-service/node_modules/@types/node/assert.d.ts b/ts-ticket-office-service/node_modules/@types/node/assert.d.ts new file mode 100755 index 000000000..8e02a66a0 --- /dev/null +++ b/ts-ticket-office-service/node_modules/@types/node/assert.d.ts @@ -0,0 +1,911 @@ +/** + * The `assert` module provides a set of assertion functions for verifying + * invariants. + * @see [source](https://github.com/nodejs/node/blob/v18.0.0/lib/assert.js) + */ +declare module 'assert' { + /** + * An alias of {@link ok}. + * @since v0.5.9 + * @param value The input that is checked for being truthy. + */ + function assert(value: unknown, message?: string | Error): asserts value; + namespace assert { + /** + * Indicates the failure of an assertion. All errors thrown by the `assert` module + * will be instances of the `AssertionError` class. + */ + class AssertionError extends Error { + actual: unknown; + expected: unknown; + operator: string; + generatedMessage: boolean; + code: 'ERR_ASSERTION'; + constructor(options?: { + /** If provided, the error message is set to this value. */ + message?: string | undefined; + /** The `actual` property on the error instance. */ + actual?: unknown | undefined; + /** The `expected` property on the error instance. */ + expected?: unknown | undefined; + /** The `operator` property on the error instance. */ + operator?: string | undefined; + /** If provided, the generated stack trace omits frames before this function. */ + // tslint:disable-next-line:ban-types + stackStartFn?: Function | undefined; + }); + } + /** + * This feature is currently experimental and behavior might still change. + * @since v14.2.0, v12.19.0 + * @experimental + */ + class CallTracker { + /** + * The wrapper function is expected to be called exactly `exact` times. If the + * function has not been called exactly `exact` times when `tracker.verify()` is called, then `tracker.verify()` will throw an + * error. + * + * ```js + * import assert from 'assert'; + * + * // Creates call tracker. + * const tracker = new assert.CallTracker(); + * + * function func() {} + * + * // Returns a function that wraps func() that must be called exact times + * // before tracker.verify(). + * const callsfunc = tracker.calls(func); + * ``` + * @since v14.2.0, v12.19.0 + * @param [fn='A no-op function'] + * @param [exact=1] + * @return that wraps `fn`. + */ + calls(exact?: number): () => void; + calls any>(fn?: Func, exact?: number): Func; + /** + * The arrays contains information about the expected and actual number of calls of + * the functions that have not been called the expected number of times. + * + * ```js + * import assert from 'assert'; + * + * // Creates call tracker. + * const tracker = new assert.CallTracker(); + * + * function func() {} + * + * function foo() {} + * + * // Returns a function that wraps func() that must be called exact times + * // before tracker.verify(). + * const callsfunc = tracker.calls(func, 2); + * + * // Returns an array containing information on callsfunc() + * tracker.report(); + * // [ + * // { + * // message: 'Expected the func function to be executed 2 time(s) but was + * // executed 0 time(s).', + * // actual: 0, + * // expected: 2, + * // operator: 'func', + * // stack: stack trace + * // } + * // ] + * ``` + * @since v14.2.0, v12.19.0 + * @return of objects containing information about the wrapper functions returned by `calls`. + */ + report(): CallTrackerReportInformation[]; + /** + * Iterates through the list of functions passed to `tracker.calls()` and will throw an error for functions that + * have not been called the expected number of times. + * + * ```js + * import assert from 'assert'; + * + * // Creates call tracker. + * const tracker = new assert.CallTracker(); + * + * function func() {} + * + * // Returns a function that wraps func() that must be called exact times + * // before tracker.verify(). + * const callsfunc = tracker.calls(func, 2); + * + * callsfunc(); + * + * // Will throw an error since callsfunc() was only called once. + * tracker.verify(); + * ``` + * @since v14.2.0, v12.19.0 + */ + verify(): void; + } + interface CallTrackerReportInformation { + message: string; + /** The actual number of times the function was called. */ + actual: number; + /** The number of times the function was expected to be called. */ + expected: number; + /** The name of the function that is wrapped. */ + operator: string; + /** A stack trace of the function. */ + stack: object; + } + type AssertPredicate = RegExp | (new () => object) | ((thrown: unknown) => boolean) | object | Error; + /** + * Throws an `AssertionError` with the provided error message or a default + * error message. If the `message` parameter is an instance of an `Error` then + * it will be thrown instead of the `AssertionError`. + * + * ```js + * import assert from 'assert/strict'; + * + * assert.fail(); + * // AssertionError [ERR_ASSERTION]: Failed + * + * assert.fail('boom'); + * // AssertionError [ERR_ASSERTION]: boom + * + * assert.fail(new TypeError('need array')); + * // TypeError: need array + * ``` + * + * Using `assert.fail()` with more than two arguments is possible but deprecated. + * See below for further details. + * @since v0.1.21 + * @param [message='Failed'] + */ + function fail(message?: string | Error): never; + /** @deprecated since v10.0.0 - use fail([message]) or other assert functions instead. */ + function fail( + actual: unknown, + expected: unknown, + message?: string | Error, + operator?: string, + // tslint:disable-next-line:ban-types + stackStartFn?: Function + ): never; + /** + * Tests if `value` is truthy. It is equivalent to`assert.equal(!!value, true, message)`. + * + * If `value` is not truthy, an `AssertionError` is thrown with a `message`property set equal to the value of the `message` parameter. If the `message`parameter is `undefined`, a default + * error message is assigned. If the `message`parameter is an instance of an `Error` then it will be thrown instead of the`AssertionError`. + * If no arguments are passed in at all `message` will be set to the string:`` 'No value argument passed to `assert.ok()`' ``. + * + * Be aware that in the `repl` the error message will be different to the one + * thrown in a file! See below for further details. + * + * ```js + * import assert from 'assert/strict'; + * + * assert.ok(true); + * // OK + * assert.ok(1); + * // OK + * + * assert.ok(); + * // AssertionError: No value argument passed to `assert.ok()` + * + * assert.ok(false, 'it\'s false'); + * // AssertionError: it's false + * + * // In the repl: + * assert.ok(typeof 123 === 'string'); + * // AssertionError: false == true + * + * // In a file (e.g. test.js): + * assert.ok(typeof 123 === 'string'); + * // AssertionError: The expression evaluated to a falsy value: + * // + * // assert.ok(typeof 123 === 'string') + * + * assert.ok(false); + * // AssertionError: The expression evaluated to a falsy value: + * // + * // assert.ok(false) + * + * assert.ok(0); + * // AssertionError: The expression evaluated to a falsy value: + * // + * // assert.ok(0) + * ``` + * + * ```js + * import assert from 'assert/strict'; + * + * // Using `assert()` works the same: + * assert(0); + * // AssertionError: The expression evaluated to a falsy value: + * // + * // assert(0) + * ``` + * @since v0.1.21 + */ + function ok(value: unknown, message?: string | Error): asserts value; + /** + * **Strict assertion mode** + * + * An alias of {@link strictEqual}. + * + * **Legacy assertion mode** + * + * > Stability: 3 - Legacy: Use {@link strictEqual} instead. + * + * Tests shallow, coercive equality between the `actual` and `expected` parameters + * using the [`==` operator](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Equality). `NaN` is specially handled + * and treated as being identical if both sides are `NaN`. + * + * ```js + * import assert from 'assert'; + * + * assert.equal(1, 1); + * // OK, 1 == 1 + * assert.equal(1, '1'); + * // OK, 1 == '1' + * assert.equal(NaN, NaN); + * // OK + * + * assert.equal(1, 2); + * // AssertionError: 1 == 2 + * assert.equal({ a: { b: 1 } }, { a: { b: 1 } }); + * // AssertionError: { a: { b: 1 } } == { a: { b: 1 } } + * ``` + * + * If the values are not equal, an `AssertionError` is thrown with a `message`property set equal to the value of the `message` parameter. If the `message`parameter is undefined, a default + * error message is assigned. If the `message`parameter is an instance of an `Error` then it will be thrown instead of the`AssertionError`. + * @since v0.1.21 + */ + function equal(actual: unknown, expected: unknown, message?: string | Error): void; + /** + * **Strict assertion mode** + * + * An alias of {@link notStrictEqual}. + * + * **Legacy assertion mode** + * + * > Stability: 3 - Legacy: Use {@link notStrictEqual} instead. + * + * Tests shallow, coercive inequality with the [`!=` operator](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Inequality). `NaN` is + * specially handled and treated as being identical if both sides are `NaN`. + * + * ```js + * import assert from 'assert'; + * + * assert.notEqual(1, 2); + * // OK + * + * assert.notEqual(1, 1); + * // AssertionError: 1 != 1 + * + * assert.notEqual(1, '1'); + * // AssertionError: 1 != '1' + * ``` + * + * If the values are equal, an `AssertionError` is thrown with a `message`property set equal to the value of the `message` parameter. If the `message`parameter is undefined, a default error + * message is assigned. If the `message`parameter is an instance of an `Error` then it will be thrown instead of the`AssertionError`. + * @since v0.1.21 + */ + function notEqual(actual: unknown, expected: unknown, message?: string | Error): void; + /** + * **Strict assertion mode** + * + * An alias of {@link deepStrictEqual}. + * + * **Legacy assertion mode** + * + * > Stability: 3 - Legacy: Use {@link deepStrictEqual} instead. + * + * Tests for deep equality between the `actual` and `expected` parameters. Consider + * using {@link deepStrictEqual} instead. {@link deepEqual} can have + * surprising results. + * + * _Deep equality_ means that the enumerable "own" properties of child objects + * are also recursively evaluated by the following rules. + * @since v0.1.21 + */ + function deepEqual(actual: unknown, expected: unknown, message?: string | Error): void; + /** + * **Strict assertion mode** + * + * An alias of {@link notDeepStrictEqual}. + * + * **Legacy assertion mode** + * + * > Stability: 3 - Legacy: Use {@link notDeepStrictEqual} instead. + * + * Tests for any deep inequality. Opposite of {@link deepEqual}. + * + * ```js + * import assert from 'assert'; + * + * const obj1 = { + * a: { + * b: 1 + * } + * }; + * const obj2 = { + * a: { + * b: 2 + * } + * }; + * const obj3 = { + * a: { + * b: 1 + * } + * }; + * const obj4 = Object.create(obj1); + * + * assert.notDeepEqual(obj1, obj1); + * // AssertionError: { a: { b: 1 } } notDeepEqual { a: { b: 1 } } + * + * assert.notDeepEqual(obj1, obj2); + * // OK + * + * assert.notDeepEqual(obj1, obj3); + * // AssertionError: { a: { b: 1 } } notDeepEqual { a: { b: 1 } } + * + * assert.notDeepEqual(obj1, obj4); + * // OK + * ``` + * + * If the values are deeply equal, an `AssertionError` is thrown with a`message` property set equal to the value of the `message` parameter. If the`message` parameter is undefined, a default + * error message is assigned. If the`message` parameter is an instance of an `Error` then it will be thrown + * instead of the `AssertionError`. + * @since v0.1.21 + */ + function notDeepEqual(actual: unknown, expected: unknown, message?: string | Error): void; + /** + * Tests strict equality between the `actual` and `expected` parameters as + * determined by [`Object.is()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/is). + * + * ```js + * import assert from 'assert/strict'; + * + * assert.strictEqual(1, 2); + * // AssertionError [ERR_ASSERTION]: Expected inputs to be strictly equal: + * // + * // 1 !== 2 + * + * assert.strictEqual(1, 1); + * // OK + * + * assert.strictEqual('Hello foobar', 'Hello World!'); + * // AssertionError [ERR_ASSERTION]: Expected inputs to be strictly equal: + * // + actual - expected + * // + * // + 'Hello foobar' + * // - 'Hello World!' + * // ^ + * + * const apples = 1; + * const oranges = 2; + * assert.strictEqual(apples, oranges, `apples ${apples} !== oranges ${oranges}`); + * // AssertionError [ERR_ASSERTION]: apples 1 !== oranges 2 + * + * assert.strictEqual(1, '1', new TypeError('Inputs are not identical')); + * // TypeError: Inputs are not identical + * ``` + * + * If the values are not strictly equal, an `AssertionError` is thrown with a`message` property set equal to the value of the `message` parameter. If the`message` parameter is undefined, a + * default error message is assigned. If the`message` parameter is an instance of an `Error` then it will be thrown + * instead of the `AssertionError`. + * @since v0.1.21 + */ + function strictEqual(actual: unknown, expected: T, message?: string | Error): asserts actual is T; + /** + * Tests strict inequality between the `actual` and `expected` parameters as + * determined by [`Object.is()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/is). + * + * ```js + * import assert from 'assert/strict'; + * + * assert.notStrictEqual(1, 2); + * // OK + * + * assert.notStrictEqual(1, 1); + * // AssertionError [ERR_ASSERTION]: Expected "actual" to be strictly unequal to: + * // + * // 1 + * + * assert.notStrictEqual(1, '1'); + * // OK + * ``` + * + * If the values are strictly equal, an `AssertionError` is thrown with a`message` property set equal to the value of the `message` parameter. If the`message` parameter is undefined, a + * default error message is assigned. If the`message` parameter is an instance of an `Error` then it will be thrown + * instead of the `AssertionError`. + * @since v0.1.21 + */ + function notStrictEqual(actual: unknown, expected: unknown, message?: string | Error): void; + /** + * Tests for deep equality between the `actual` and `expected` parameters. + * "Deep" equality means that the enumerable "own" properties of child objects + * are recursively evaluated also by the following rules. + * @since v1.2.0 + */ + function deepStrictEqual(actual: unknown, expected: T, message?: string | Error): asserts actual is T; + /** + * Tests for deep strict inequality. Opposite of {@link deepStrictEqual}. + * + * ```js + * import assert from 'assert/strict'; + * + * assert.notDeepStrictEqual({ a: 1 }, { a: '1' }); + * // OK + * ``` + * + * If the values are deeply and strictly equal, an `AssertionError` is thrown + * with a `message` property set equal to the value of the `message` parameter. If + * the `message` parameter is undefined, a default error message is assigned. If + * the `message` parameter is an instance of an `Error` then it will be thrown + * instead of the `AssertionError`. + * @since v1.2.0 + */ + function notDeepStrictEqual(actual: unknown, expected: unknown, message?: string | Error): void; + /** + * Expects the function `fn` to throw an error. + * + * If specified, `error` can be a [`Class`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes), + * [`RegExp`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions), a validation function, + * a validation object where each property will be tested for strict deep equality, + * or an instance of error where each property will be tested for strict deep + * equality including the non-enumerable `message` and `name` properties. When + * using an object, it is also possible to use a regular expression, when + * validating against a string property. See below for examples. + * + * If specified, `message` will be appended to the message provided by the`AssertionError` if the `fn` call fails to throw or in case the error validation + * fails. + * + * Custom validation object/error instance: + * + * ```js + * import assert from 'assert/strict'; + * + * const err = new TypeError('Wrong value'); + * err.code = 404; + * err.foo = 'bar'; + * err.info = { + * nested: true, + * baz: 'text' + * }; + * err.reg = /abc/i; + * + * assert.throws( + * () => { + * throw err; + * }, + * { + * name: 'TypeError', + * message: 'Wrong value', + * info: { + * nested: true, + * baz: 'text' + * } + * // Only properties on the validation object will be tested for. + * // Using nested objects requires all properties to be present. Otherwise + * // the validation is going to fail. + * } + * ); + * + * // Using regular expressions to validate error properties: + * throws( + * () => { + * throw err; + * }, + * { + * // The `name` and `message` properties are strings and using regular + * // expressions on those will match against the string. If they fail, an + * // error is thrown. + * name: /^TypeError$/, + * message: /Wrong/, + * foo: 'bar', + * info: { + * nested: true, + * // It is not possible to use regular expressions for nested properties! + * baz: 'text' + * }, + * // The `reg` property contains a regular expression and only if the + * // validation object contains an identical regular expression, it is going + * // to pass. + * reg: /abc/i + * } + * ); + * + * // Fails due to the different `message` and `name` properties: + * throws( + * () => { + * const otherErr = new Error('Not found'); + * // Copy all enumerable properties from `err` to `otherErr`. + * for (const [key, value] of Object.entries(err)) { + * otherErr[key] = value; + * } + * throw otherErr; + * }, + * // The error's `message` and `name` properties will also be checked when using + * // an error as validation object. + * err + * ); + * ``` + * + * Validate instanceof using constructor: + * + * ```js + * import assert from 'assert/strict'; + * + * assert.throws( + * () => { + * throw new Error('Wrong value'); + * }, + * Error + * ); + * ``` + * + * Validate error message using [`RegExp`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions): + * + * Using a regular expression runs `.toString` on the error object, and will + * therefore also include the error name. + * + * ```js + * import assert from 'assert/strict'; + * + * assert.throws( + * () => { + * throw new Error('Wrong value'); + * }, + * /^Error: Wrong value$/ + * ); + * ``` + * + * Custom error validation: + * + * The function must return `true` to indicate all internal validations passed. + * It will otherwise fail with an `AssertionError`. + * + * ```js + * import assert from 'assert/strict'; + * + * assert.throws( + * () => { + * throw new Error('Wrong value'); + * }, + * (err) => { + * assert(err instanceof Error); + * assert(/value/.test(err)); + * // Avoid returning anything from validation functions besides `true`. + * // Otherwise, it's not clear what part of the validation failed. Instead, + * // throw an error about the specific validation that failed (as done in this + * // example) and add as much helpful debugging information to that error as + * // possible. + * return true; + * }, + * 'unexpected error' + * ); + * ``` + * + * `error` cannot be a string. If a string is provided as the second + * argument, then `error` is assumed to be omitted and the string will be used for`message` instead. This can lead to easy-to-miss mistakes. Using the same + * message as the thrown error message is going to result in an`ERR_AMBIGUOUS_ARGUMENT` error. Please read the example below carefully if using + * a string as the second argument gets considered: + * + * ```js + * import assert from 'assert/strict'; + * + * function throwingFirst() { + * throw new Error('First'); + * } + * + * function throwingSecond() { + * throw new Error('Second'); + * } + * + * function notThrowing() {} + * + * // The second argument is a string and the input function threw an Error. + * // The first case will not throw as it does not match for the error message + * // thrown by the input function! + * assert.throws(throwingFirst, 'Second'); + * // In the next example the message has no benefit over the message from the + * // error and since it is not clear if the user intended to actually match + * // against the error message, Node.js throws an `ERR_AMBIGUOUS_ARGUMENT` error. + * assert.throws(throwingSecond, 'Second'); + * // TypeError [ERR_AMBIGUOUS_ARGUMENT] + * + * // The string is only used (as message) in case the function does not throw: + * assert.throws(notThrowing, 'Second'); + * // AssertionError [ERR_ASSERTION]: Missing expected exception: Second + * + * // If it was intended to match for the error message do this instead: + * // It does not throw because the error messages match. + * assert.throws(throwingSecond, /Second$/); + * + * // If the error message does not match, an AssertionError is thrown. + * assert.throws(throwingFirst, /Second$/); + * // AssertionError [ERR_ASSERTION] + * ``` + * + * Due to the confusing error-prone notation, avoid a string as the second + * argument. + * @since v0.1.21 + */ + function throws(block: () => unknown, message?: string | Error): void; + function throws(block: () => unknown, error: AssertPredicate, message?: string | Error): void; + /** + * Asserts that the function `fn` does not throw an error. + * + * Using `assert.doesNotThrow()` is actually not useful because there + * is no benefit in catching an error and then rethrowing it. Instead, consider + * adding a comment next to the specific code path that should not throw and keep + * error messages as expressive as possible. + * + * When `assert.doesNotThrow()` is called, it will immediately call the `fn`function. + * + * If an error is thrown and it is the same type as that specified by the `error`parameter, then an `AssertionError` is thrown. If the error is of a + * different type, or if the `error` parameter is undefined, the error is + * propagated back to the caller. + * + * If specified, `error` can be a [`Class`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes), + * [`RegExp`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions) or a validation + * function. See {@link throws} for more details. + * + * The following, for instance, will throw the `TypeError` because there is no + * matching error type in the assertion: + * + * ```js + * import assert from 'assert/strict'; + * + * assert.doesNotThrow( + * () => { + * throw new TypeError('Wrong value'); + * }, + * SyntaxError + * ); + * ``` + * + * However, the following will result in an `AssertionError` with the message + * 'Got unwanted exception...': + * + * ```js + * import assert from 'assert/strict'; + * + * assert.doesNotThrow( + * () => { + * throw new TypeError('Wrong value'); + * }, + * TypeError + * ); + * ``` + * + * If an `AssertionError` is thrown and a value is provided for the `message`parameter, the value of `message` will be appended to the `AssertionError` message: + * + * ```js + * import assert from 'assert/strict'; + * + * assert.doesNotThrow( + * () => { + * throw new TypeError('Wrong value'); + * }, + * /Wrong value/, + * 'Whoops' + * ); + * // Throws: AssertionError: Got unwanted exception: Whoops + * ``` + * @since v0.1.21 + */ + function doesNotThrow(block: () => unknown, message?: string | Error): void; + function doesNotThrow(block: () => unknown, error: AssertPredicate, message?: string | Error): void; + /** + * Throws `value` if `value` is not `undefined` or `null`. This is useful when + * testing the `error` argument in callbacks. The stack trace contains all frames + * from the error passed to `ifError()` including the potential new frames for`ifError()` itself. + * + * ```js + * import assert from 'assert/strict'; + * + * assert.ifError(null); + * // OK + * assert.ifError(0); + * // AssertionError [ERR_ASSERTION]: ifError got unwanted exception: 0 + * assert.ifError('error'); + * // AssertionError [ERR_ASSERTION]: ifError got unwanted exception: 'error' + * assert.ifError(new Error()); + * // AssertionError [ERR_ASSERTION]: ifError got unwanted exception: Error + * + * // Create some random error frames. + * let err; + * (function errorFrame() { + * err = new Error('test error'); + * })(); + * + * (function ifErrorFrame() { + * assert.ifError(err); + * })(); + * // AssertionError [ERR_ASSERTION]: ifError got unwanted exception: test error + * // at ifErrorFrame + * // at errorFrame + * ``` + * @since v0.1.97 + */ + function ifError(value: unknown): asserts value is null | undefined; + /** + * Awaits the `asyncFn` promise or, if `asyncFn` is a function, immediately + * calls the function and awaits the returned promise to complete. It will then + * check that the promise is rejected. + * + * If `asyncFn` is a function and it throws an error synchronously,`assert.rejects()` will return a rejected `Promise` with that error. If the + * function does not return a promise, `assert.rejects()` will return a rejected`Promise` with an `ERR_INVALID_RETURN_VALUE` error. In both cases the error + * handler is skipped. + * + * Besides the async nature to await the completion behaves identically to {@link throws}. + * + * If specified, `error` can be a [`Class`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes), + * [`RegExp`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions), a validation function, + * an object where each property will be tested for, or an instance of error where + * each property will be tested for including the non-enumerable `message` and`name` properties. + * + * If specified, `message` will be the message provided by the `AssertionError` if the `asyncFn` fails to reject. + * + * ```js + * import assert from 'assert/strict'; + * + * await assert.rejects( + * async () => { + * throw new TypeError('Wrong value'); + * }, + * { + * name: 'TypeError', + * message: 'Wrong value' + * } + * ); + * ``` + * + * ```js + * import assert from 'assert/strict'; + * + * await assert.rejects( + * async () => { + * throw new TypeError('Wrong value'); + * }, + * (err) => { + * assert.strictEqual(err.name, 'TypeError'); + * assert.strictEqual(err.message, 'Wrong value'); + * return true; + * } + * ); + * ``` + * + * ```js + * import assert from 'assert/strict'; + * + * assert.rejects( + * Promise.reject(new Error('Wrong value')), + * Error + * ).then(() => { + * // ... + * }); + * ``` + * + * `error` cannot be a string. If a string is provided as the second + * argument, then `error` is assumed to be omitted and the string will be used for`message` instead. This can lead to easy-to-miss mistakes. Please read the + * example in {@link throws} carefully if using a string as the second + * argument gets considered. + * @since v10.0.0 + */ + function rejects(block: (() => Promise) | Promise, message?: string | Error): Promise; + function rejects(block: (() => Promise) | Promise, error: AssertPredicate, message?: string | Error): Promise; + /** + * Awaits the `asyncFn` promise or, if `asyncFn` is a function, immediately + * calls the function and awaits the returned promise to complete. It will then + * check that the promise is not rejected. + * + * If `asyncFn` is a function and it throws an error synchronously,`assert.doesNotReject()` will return a rejected `Promise` with that error. If + * the function does not return a promise, `assert.doesNotReject()` will return a + * rejected `Promise` with an `ERR_INVALID_RETURN_VALUE` error. In both cases + * the error handler is skipped. + * + * Using `assert.doesNotReject()` is actually not useful because there is little + * benefit in catching a rejection and then rejecting it again. Instead, consider + * adding a comment next to the specific code path that should not reject and keep + * error messages as expressive as possible. + * + * If specified, `error` can be a [`Class`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes), + * [`RegExp`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions) or a validation + * function. See {@link throws} for more details. + * + * Besides the async nature to await the completion behaves identically to {@link doesNotThrow}. + * + * ```js + * import assert from 'assert/strict'; + * + * await assert.doesNotReject( + * async () => { + * throw new TypeError('Wrong value'); + * }, + * SyntaxError + * ); + * ``` + * + * ```js + * import assert from 'assert/strict'; + * + * assert.doesNotReject(Promise.reject(new TypeError('Wrong value'))) + * .then(() => { + * // ... + * }); + * ``` + * @since v10.0.0 + */ + function doesNotReject(block: (() => Promise) | Promise, message?: string | Error): Promise; + function doesNotReject(block: (() => Promise) | Promise, error: AssertPredicate, message?: string | Error): Promise; + /** + * Expects the `string` input to match the regular expression. + * + * ```js + * import assert from 'assert/strict'; + * + * assert.match('I will fail', /pass/); + * // AssertionError [ERR_ASSERTION]: The input did not match the regular ... + * + * assert.match(123, /pass/); + * // AssertionError [ERR_ASSERTION]: The "string" argument must be of type string. + * + * assert.match('I will pass', /pass/); + * // OK + * ``` + * + * If the values do not match, or if the `string` argument is of another type than`string`, an `AssertionError` is thrown with a `message` property set equal + * to the value of the `message` parameter. If the `message` parameter is + * undefined, a default error message is assigned. If the `message` parameter is an + * instance of an `Error` then it will be thrown instead of the `AssertionError`. + * @since v13.6.0, v12.16.0 + */ + function match(value: string, regExp: RegExp, message?: string | Error): void; + /** + * Expects the `string` input not to match the regular expression. + * + * ```js + * import assert from 'assert/strict'; + * + * assert.doesNotMatch('I will fail', /fail/); + * // AssertionError [ERR_ASSERTION]: The input was expected to not match the ... + * + * assert.doesNotMatch(123, /pass/); + * // AssertionError [ERR_ASSERTION]: The "string" argument must be of type string. + * + * assert.doesNotMatch('I will pass', /different/); + * // OK + * ``` + * + * If the values do match, or if the `string` argument is of another type than`string`, an `AssertionError` is thrown with a `message` property set equal + * to the value of the `message` parameter. If the `message` parameter is + * undefined, a default error message is assigned. If the `message` parameter is an + * instance of an `Error` then it will be thrown instead of the `AssertionError`. + * @since v13.6.0, v12.16.0 + */ + function doesNotMatch(value: string, regExp: RegExp, message?: string | Error): void; + const strict: Omit & { + (value: unknown, message?: string | Error): asserts value; + equal: typeof strictEqual; + notEqual: typeof notStrictEqual; + deepEqual: typeof deepStrictEqual; + notDeepEqual: typeof notDeepStrictEqual; + // Mapped types and assertion functions are incompatible? + // TS2775: Assertions require every name in the call target + // to be declared with an explicit type annotation. + ok: typeof ok; + strictEqual: typeof strictEqual; + deepStrictEqual: typeof deepStrictEqual; + ifError: typeof ifError; + strict: typeof strict; + }; + } + export = assert; +} +declare module 'node:assert' { + import assert = require('assert'); + export = assert; +} diff --git a/ts-ticket-office-service/node_modules/@types/node/assert/strict.d.ts b/ts-ticket-office-service/node_modules/@types/node/assert/strict.d.ts new file mode 100755 index 000000000..b4319b974 --- /dev/null +++ b/ts-ticket-office-service/node_modules/@types/node/assert/strict.d.ts @@ -0,0 +1,8 @@ +declare module 'assert/strict' { + import { strict } from 'node:assert'; + export = strict; +} +declare module 'node:assert/strict' { + import { strict } from 'node:assert'; + export = strict; +} diff --git a/ts-ticket-office-service/node_modules/@types/node/async_hooks.d.ts b/ts-ticket-office-service/node_modules/@types/node/async_hooks.d.ts new file mode 100755 index 000000000..0bf473965 --- /dev/null +++ b/ts-ticket-office-service/node_modules/@types/node/async_hooks.d.ts @@ -0,0 +1,501 @@ +/** + * The `async_hooks` module provides an API to track asynchronous resources. It + * can be accessed using: + * + * ```js + * import async_hooks from 'async_hooks'; + * ``` + * @experimental + * @see [source](https://github.com/nodejs/node/blob/v18.0.0/lib/async_hooks.js) + */ +declare module 'async_hooks' { + /** + * ```js + * import { executionAsyncId } from 'async_hooks'; + * + * console.log(executionAsyncId()); // 1 - bootstrap + * fs.open(path, 'r', (err, fd) => { + * console.log(executionAsyncId()); // 6 - open() + * }); + * ``` + * + * The ID returned from `executionAsyncId()` is related to execution timing, not + * causality (which is covered by `triggerAsyncId()`): + * + * ```js + * const server = net.createServer((conn) => { + * // Returns the ID of the server, not of the new connection, because the + * // callback runs in the execution scope of the server's MakeCallback(). + * async_hooks.executionAsyncId(); + * + * }).listen(port, () => { + * // Returns the ID of a TickObject (process.nextTick()) because all + * // callbacks passed to .listen() are wrapped in a nextTick(). + * async_hooks.executionAsyncId(); + * }); + * ``` + * + * Promise contexts may not get precise `executionAsyncIds` by default. + * See the section on `promise execution tracking`. + * @since v8.1.0 + * @return The `asyncId` of the current execution context. Useful to track when something calls. + */ + function executionAsyncId(): number; + /** + * Resource objects returned by `executionAsyncResource()` are most often internal + * Node.js handle objects with undocumented APIs. Using any functions or properties + * on the object is likely to crash your application and should be avoided. + * + * Using `executionAsyncResource()` in the top-level execution context will + * return an empty object as there is no handle or request object to use, + * but having an object representing the top-level can be helpful. + * + * ```js + * import { open } from 'fs'; + * import { executionAsyncId, executionAsyncResource } from 'async_hooks'; + * + * console.log(executionAsyncId(), executionAsyncResource()); // 1 {} + * open(new URL(import.meta.url), 'r', (err, fd) => { + * console.log(executionAsyncId(), executionAsyncResource()); // 7 FSReqWrap + * }); + * ``` + * + * This can be used to implement continuation local storage without the + * use of a tracking `Map` to store the metadata: + * + * ```js + * import { createServer } from 'http'; + * import { + * executionAsyncId, + * executionAsyncResource, + * createHook + * } from 'async_hooks'; + * const sym = Symbol('state'); // Private symbol to avoid pollution + * + * createHook({ + * init(asyncId, type, triggerAsyncId, resource) { + * const cr = executionAsyncResource(); + * if (cr) { + * resource[sym] = cr[sym]; + * } + * } + * }).enable(); + * + * const server = createServer((req, res) => { + * executionAsyncResource()[sym] = { state: req.url }; + * setTimeout(function() { + * res.end(JSON.stringify(executionAsyncResource()[sym])); + * }, 100); + * }).listen(3000); + * ``` + * @since v13.9.0, v12.17.0 + * @return The resource representing the current execution. Useful to store data within the resource. + */ + function executionAsyncResource(): object; + /** + * ```js + * const server = net.createServer((conn) => { + * // The resource that caused (or triggered) this callback to be called + * // was that of the new connection. Thus the return value of triggerAsyncId() + * // is the asyncId of "conn". + * async_hooks.triggerAsyncId(); + * + * }).listen(port, () => { + * // Even though all callbacks passed to .listen() are wrapped in a nextTick() + * // the callback itself exists because the call to the server's .listen() + * // was made. So the return value would be the ID of the server. + * async_hooks.triggerAsyncId(); + * }); + * ``` + * + * Promise contexts may not get valid `triggerAsyncId`s by default. See + * the section on `promise execution tracking`. + * @return The ID of the resource responsible for calling the callback that is currently being executed. + */ + function triggerAsyncId(): number; + interface HookCallbacks { + /** + * Called when a class is constructed that has the possibility to emit an asynchronous event. + * @param asyncId a unique ID for the async resource + * @param type the type of the async resource + * @param triggerAsyncId the unique ID of the async resource in whose execution context this async resource was created + * @param resource reference to the resource representing the async operation, needs to be released during destroy + */ + init?(asyncId: number, type: string, triggerAsyncId: number, resource: object): void; + /** + * When an asynchronous operation is initiated or completes a callback is called to notify the user. + * The before callback is called just before said callback is executed. + * @param asyncId the unique identifier assigned to the resource about to execute the callback. + */ + before?(asyncId: number): void; + /** + * Called immediately after the callback specified in before is completed. + * @param asyncId the unique identifier assigned to the resource which has executed the callback. + */ + after?(asyncId: number): void; + /** + * Called when a promise has resolve() called. This may not be in the same execution id + * as the promise itself. + * @param asyncId the unique id for the promise that was resolve()d. + */ + promiseResolve?(asyncId: number): void; + /** + * Called after the resource corresponding to asyncId is destroyed + * @param asyncId a unique ID for the async resource + */ + destroy?(asyncId: number): void; + } + interface AsyncHook { + /** + * Enable the callbacks for a given AsyncHook instance. If no callbacks are provided enabling is a noop. + */ + enable(): this; + /** + * Disable the callbacks for a given AsyncHook instance from the global pool of AsyncHook callbacks to be executed. Once a hook has been disabled it will not be called again until enabled. + */ + disable(): this; + } + /** + * Registers functions to be called for different lifetime events of each async + * operation. + * + * The callbacks `init()`/`before()`/`after()`/`destroy()` are called for the + * respective asynchronous event during a resource's lifetime. + * + * All callbacks are optional. For example, if only resource cleanup needs to + * be tracked, then only the `destroy` callback needs to be passed. The + * specifics of all functions that can be passed to `callbacks` is in the `Hook Callbacks` section. + * + * ```js + * import { createHook } from 'async_hooks'; + * + * const asyncHook = createHook({ + * init(asyncId, type, triggerAsyncId, resource) { }, + * destroy(asyncId) { } + * }); + * ``` + * + * The callbacks will be inherited via the prototype chain: + * + * ```js + * class MyAsyncCallbacks { + * init(asyncId, type, triggerAsyncId, resource) { } + * destroy(asyncId) {} + * } + * + * class MyAddedCallbacks extends MyAsyncCallbacks { + * before(asyncId) { } + * after(asyncId) { } + * } + * + * const asyncHook = async_hooks.createHook(new MyAddedCallbacks()); + * ``` + * + * Because promises are asynchronous resources whose lifecycle is tracked + * via the async hooks mechanism, the `init()`, `before()`, `after()`, and`destroy()` callbacks _must not_ be async functions that return promises. + * @since v8.1.0 + * @param callbacks The `Hook Callbacks` to register + * @return Instance used for disabling and enabling hooks + */ + function createHook(callbacks: HookCallbacks): AsyncHook; + interface AsyncResourceOptions { + /** + * The ID of the execution context that created this async event. + * @default executionAsyncId() + */ + triggerAsyncId?: number | undefined; + /** + * Disables automatic `emitDestroy` when the object is garbage collected. + * This usually does not need to be set (even if `emitDestroy` is called + * manually), unless the resource's `asyncId` is retrieved and the + * sensitive API's `emitDestroy` is called with it. + * @default false + */ + requireManualDestroy?: boolean | undefined; + } + /** + * The class `AsyncResource` is designed to be extended by the embedder's async + * resources. Using this, users can easily trigger the lifetime events of their + * own resources. + * + * The `init` hook will trigger when an `AsyncResource` is instantiated. + * + * The following is an overview of the `AsyncResource` API. + * + * ```js + * import { AsyncResource, executionAsyncId } from 'async_hooks'; + * + * // AsyncResource() is meant to be extended. Instantiating a + * // new AsyncResource() also triggers init. If triggerAsyncId is omitted then + * // async_hook.executionAsyncId() is used. + * const asyncResource = new AsyncResource( + * type, { triggerAsyncId: executionAsyncId(), requireManualDestroy: false } + * ); + * + * // Run a function in the execution context of the resource. This will + * // * establish the context of the resource + * // * trigger the AsyncHooks before callbacks + * // * call the provided function `fn` with the supplied arguments + * // * trigger the AsyncHooks after callbacks + * // * restore the original execution context + * asyncResource.runInAsyncScope(fn, thisArg, ...args); + * + * // Call AsyncHooks destroy callbacks. + * asyncResource.emitDestroy(); + * + * // Return the unique ID assigned to the AsyncResource instance. + * asyncResource.asyncId(); + * + * // Return the trigger ID for the AsyncResource instance. + * asyncResource.triggerAsyncId(); + * ``` + */ + class AsyncResource { + /** + * AsyncResource() is meant to be extended. Instantiating a + * new AsyncResource() also triggers init. If triggerAsyncId is omitted then + * async_hook.executionAsyncId() is used. + * @param type The type of async event. + * @param triggerAsyncId The ID of the execution context that created + * this async event (default: `executionAsyncId()`), or an + * AsyncResourceOptions object (since v9.3.0) + */ + constructor(type: string, triggerAsyncId?: number | AsyncResourceOptions); + /** + * Binds the given function to the current execution context. + * + * The returned function will have an `asyncResource` property referencing + * the `AsyncResource` to which the function is bound. + * @since v14.8.0, v12.19.0 + * @param fn The function to bind to the current execution context. + * @param type An optional name to associate with the underlying `AsyncResource`. + */ + static bind any, ThisArg>( + fn: Func, + type?: string, + thisArg?: ThisArg + ): Func & { + asyncResource: AsyncResource; + }; + /** + * Binds the given function to execute to this `AsyncResource`'s scope. + * + * The returned function will have an `asyncResource` property referencing + * the `AsyncResource` to which the function is bound. + * @since v14.8.0, v12.19.0 + * @param fn The function to bind to the current `AsyncResource`. + */ + bind any>( + fn: Func + ): Func & { + asyncResource: AsyncResource; + }; + /** + * Call the provided function with the provided arguments in the execution context + * of the async resource. This will establish the context, trigger the AsyncHooks + * before callbacks, call the function, trigger the AsyncHooks after callbacks, and + * then restore the original execution context. + * @since v9.6.0 + * @param fn The function to call in the execution context of this async resource. + * @param thisArg The receiver to be used for the function call. + * @param args Optional arguments to pass to the function. + */ + runInAsyncScope(fn: (this: This, ...args: any[]) => Result, thisArg?: This, ...args: any[]): Result; + /** + * Call all `destroy` hooks. This should only ever be called once. An error will + * be thrown if it is called more than once. This **must** be manually called. If + * the resource is left to be collected by the GC then the `destroy` hooks will + * never be called. + * @return A reference to `asyncResource`. + */ + emitDestroy(): this; + /** + * @return The unique `asyncId` assigned to the resource. + */ + asyncId(): number; + /** + * + * @return The same `triggerAsyncId` that is passed to the `AsyncResource` constructor. + */ + triggerAsyncId(): number; + } + /** + * This class creates stores that stay coherent through asynchronous operations. + * + * While you can create your own implementation on top of the `async_hooks` module,`AsyncLocalStorage` should be preferred as it is a performant and memory safe + * implementation that involves significant optimizations that are non-obvious to + * implement. + * + * The following example uses `AsyncLocalStorage` to build a simple logger + * that assigns IDs to incoming HTTP requests and includes them in messages + * logged within each request. + * + * ```js + * import http from 'http'; + * import { AsyncLocalStorage } from 'async_hooks'; + * + * const asyncLocalStorage = new AsyncLocalStorage(); + * + * function logWithId(msg) { + * const id = asyncLocalStorage.getStore(); + * console.log(`${id !== undefined ? id : '-'}:`, msg); + * } + * + * let idSeq = 0; + * http.createServer((req, res) => { + * asyncLocalStorage.run(idSeq++, () => { + * logWithId('start'); + * // Imagine any chain of async operations here + * setImmediate(() => { + * logWithId('finish'); + * res.end(); + * }); + * }); + * }).listen(8080); + * + * http.get('http://localhost:8080'); + * http.get('http://localhost:8080'); + * // Prints: + * // 0: start + * // 1: start + * // 0: finish + * // 1: finish + * ``` + * + * Each instance of `AsyncLocalStorage` maintains an independent storage context. + * Multiple instances can safely exist simultaneously without risk of interfering + * with each other's data. + * @since v13.10.0, v12.17.0 + */ + class AsyncLocalStorage { + /** + * Disables the instance of `AsyncLocalStorage`. All subsequent calls + * to `asyncLocalStorage.getStore()` will return `undefined` until`asyncLocalStorage.run()` or `asyncLocalStorage.enterWith()` is called again. + * + * When calling `asyncLocalStorage.disable()`, all current contexts linked to the + * instance will be exited. + * + * Calling `asyncLocalStorage.disable()` is required before the`asyncLocalStorage` can be garbage collected. This does not apply to stores + * provided by the `asyncLocalStorage`, as those objects are garbage collected + * along with the corresponding async resources. + * + * Use this method when the `asyncLocalStorage` is not in use anymore + * in the current process. + * @since v13.10.0, v12.17.0 + * @experimental + */ + disable(): void; + /** + * Returns the current store. + * If called outside of an asynchronous context initialized by + * calling `asyncLocalStorage.run()` or `asyncLocalStorage.enterWith()`, it + * returns `undefined`. + * @since v13.10.0, v12.17.0 + */ + getStore(): T | undefined; + /** + * Runs a function synchronously within a context and returns its + * return value. The store is not accessible outside of the callback function. + * The store is accessible to any asynchronous operations created within the + * callback. + * + * The optional `args` are passed to the callback function. + * + * If the callback function throws an error, the error is thrown by `run()` too. + * The stacktrace is not impacted by this call and the context is exited. + * + * Example: + * + * ```js + * const store = { id: 2 }; + * try { + * asyncLocalStorage.run(store, () => { + * asyncLocalStorage.getStore(); // Returns the store object + * setTimeout(() => { + * asyncLocalStorage.getStore(); // Returns the store object + * }, 200); + * throw new Error(); + * }); + * } catch (e) { + * asyncLocalStorage.getStore(); // Returns undefined + * // The error will be caught here + * } + * ``` + * @since v13.10.0, v12.17.0 + */ + run(store: T, callback: (...args: TArgs) => R, ...args: TArgs): R; + /** + * Runs a function synchronously outside of a context and returns its + * return value. The store is not accessible within the callback function or + * the asynchronous operations created within the callback. Any `getStore()`call done within the callback function will always return `undefined`. + * + * The optional `args` are passed to the callback function. + * + * If the callback function throws an error, the error is thrown by `exit()` too. + * The stacktrace is not impacted by this call and the context is re-entered. + * + * Example: + * + * ```js + * // Within a call to run + * try { + * asyncLocalStorage.getStore(); // Returns the store object or value + * asyncLocalStorage.exit(() => { + * asyncLocalStorage.getStore(); // Returns undefined + * throw new Error(); + * }); + * } catch (e) { + * asyncLocalStorage.getStore(); // Returns the same object or value + * // The error will be caught here + * } + * ``` + * @since v13.10.0, v12.17.0 + * @experimental + */ + exit(callback: (...args: TArgs) => R, ...args: TArgs): R; + /** + * Transitions into the context for the remainder of the current + * synchronous execution and then persists the store through any following + * asynchronous calls. + * + * Example: + * + * ```js + * const store = { id: 1 }; + * // Replaces previous store with the given store object + * asyncLocalStorage.enterWith(store); + * asyncLocalStorage.getStore(); // Returns the store object + * someAsyncOperation(() => { + * asyncLocalStorage.getStore(); // Returns the same object + * }); + * ``` + * + * This transition will continue for the _entire_ synchronous execution. + * This means that if, for example, the context is entered within an event + * handler subsequent event handlers will also run within that context unless + * specifically bound to another context with an `AsyncResource`. That is why`run()` should be preferred over `enterWith()` unless there are strong reasons + * to use the latter method. + * + * ```js + * const store = { id: 1 }; + * + * emitter.on('my-event', () => { + * asyncLocalStorage.enterWith(store); + * }); + * emitter.on('my-event', () => { + * asyncLocalStorage.getStore(); // Returns the same object + * }); + * + * asyncLocalStorage.getStore(); // Returns undefined + * emitter.emit('my-event'); + * asyncLocalStorage.getStore(); // Returns the same object + * ``` + * @since v13.11.0, v12.17.0 + * @experimental + */ + enterWith(store: T): void; + } +} +declare module 'node:async_hooks' { + export * from 'async_hooks'; +} diff --git a/ts-ticket-office-service/node_modules/@types/node/buffer.d.ts b/ts-ticket-office-service/node_modules/@types/node/buffer.d.ts new file mode 100755 index 000000000..34b28cf56 --- /dev/null +++ b/ts-ticket-office-service/node_modules/@types/node/buffer.d.ts @@ -0,0 +1,2238 @@ +/** + * `Buffer` objects are used to represent a fixed-length sequence of bytes. Many + * Node.js APIs support `Buffer`s. + * + * The `Buffer` class is a subclass of JavaScript's [`Uint8Array`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Uint8Array) class and + * extends it with methods that cover additional use cases. Node.js APIs accept + * plain [`Uint8Array`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Uint8Array) s wherever `Buffer`s are supported as well. + * + * While the `Buffer` class is available within the global scope, it is still + * recommended to explicitly reference it via an import or require statement. + * + * ```js + * import { Buffer } from 'buffer'; + * + * // Creates a zero-filled Buffer of length 10. + * const buf1 = Buffer.alloc(10); + * + * // Creates a Buffer of length 10, + * // filled with bytes which all have the value `1`. + * const buf2 = Buffer.alloc(10, 1); + * + * // Creates an uninitialized buffer of length 10. + * // This is faster than calling Buffer.alloc() but the returned + * // Buffer instance might contain old data that needs to be + * // overwritten using fill(), write(), or other functions that fill the Buffer's + * // contents. + * const buf3 = Buffer.allocUnsafe(10); + * + * // Creates a Buffer containing the bytes [1, 2, 3]. + * const buf4 = Buffer.from([1, 2, 3]); + * + * // Creates a Buffer containing the bytes [1, 1, 1, 1] – the entries + * // are all truncated using `(value & 255)` to fit into the range 0–255. + * const buf5 = Buffer.from([257, 257.5, -255, '1']); + * + * // Creates a Buffer containing the UTF-8-encoded bytes for the string 'tést': + * // [0x74, 0xc3, 0xa9, 0x73, 0x74] (in hexadecimal notation) + * // [116, 195, 169, 115, 116] (in decimal notation) + * const buf6 = Buffer.from('tést'); + * + * // Creates a Buffer containing the Latin-1 bytes [0x74, 0xe9, 0x73, 0x74]. + * const buf7 = Buffer.from('tést', 'latin1'); + * ``` + * @see [source](https://github.com/nodejs/node/blob/v18.0.0/lib/buffer.js) + */ +declare module 'buffer' { + import { BinaryLike } from 'node:crypto'; + export const INSPECT_MAX_BYTES: number; + export const kMaxLength: number; + export const kStringMaxLength: number; + export const constants: { + MAX_LENGTH: number; + MAX_STRING_LENGTH: number; + }; + export type TranscodeEncoding = 'ascii' | 'utf8' | 'utf16le' | 'ucs2' | 'latin1' | 'binary'; + /** + * Re-encodes the given `Buffer` or `Uint8Array` instance from one character + * encoding to another. Returns a new `Buffer` instance. + * + * Throws if the `fromEnc` or `toEnc` specify invalid character encodings or if + * conversion from `fromEnc` to `toEnc` is not permitted. + * + * Encodings supported by `buffer.transcode()` are: `'ascii'`, `'utf8'`,`'utf16le'`, `'ucs2'`, `'latin1'`, and `'binary'`. + * + * The transcoding process will use substitution characters if a given byte + * sequence cannot be adequately represented in the target encoding. For instance: + * + * ```js + * import { Buffer, transcode } from 'buffer'; + * + * const newBuf = transcode(Buffer.from('€'), 'utf8', 'ascii'); + * console.log(newBuf.toString('ascii')); + * // Prints: '?' + * ``` + * + * Because the Euro (`€`) sign is not representable in US-ASCII, it is replaced + * with `?` in the transcoded `Buffer`. + * @since v7.1.0 + * @param source A `Buffer` or `Uint8Array` instance. + * @param fromEnc The current encoding. + * @param toEnc To target encoding. + */ + export function transcode(source: Uint8Array, fromEnc: TranscodeEncoding, toEnc: TranscodeEncoding): Buffer; + export const SlowBuffer: { + /** @deprecated since v6.0.0, use `Buffer.allocUnsafeSlow()` */ + new (size: number): Buffer; + prototype: Buffer; + }; + /** + * Resolves a `'blob:nodedata:...'` an associated `Blob` object registered using + * a prior call to `URL.createObjectURL()`. + * @since v16.7.0 + * @experimental + * @param id A `'blob:nodedata:...` URL string returned by a prior call to `URL.createObjectURL()`. + */ + export function resolveObjectURL(id: string): Blob | undefined; + export { Buffer }; + /** + * @experimental + */ + export interface BlobOptions { + /** + * @default 'utf8' + */ + encoding?: BufferEncoding | undefined; + /** + * The Blob content-type. The intent is for `type` to convey + * the MIME media type of the data, however no validation of the type format + * is performed. + */ + type?: string | undefined; + } + /** + * A [`Blob`](https://developer.mozilla.org/en-US/docs/Web/API/Blob) encapsulates immutable, raw data that can be safely shared across + * multiple worker threads. + * @since v15.7.0, v14.18.0 + */ + export class Blob { + /** + * The total size of the `Blob` in bytes. + * @since v15.7.0, v14.18.0 + */ + readonly size: number; + /** + * The content-type of the `Blob`. + * @since v15.7.0, v14.18.0 + */ + readonly type: string; + /** + * Creates a new `Blob` object containing a concatenation of the given sources. + * + * {ArrayBuffer}, {TypedArray}, {DataView}, and {Buffer} sources are copied into + * the 'Blob' and can therefore be safely modified after the 'Blob' is created. + * + * String sources are also copied into the `Blob`. + */ + constructor(sources: Array, options?: BlobOptions); + /** + * Returns a promise that fulfills with an [ArrayBuffer](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer) containing a copy of + * the `Blob` data. + * @since v15.7.0, v14.18.0 + */ + arrayBuffer(): Promise; + /** + * Creates and returns a new `Blob` containing a subset of this `Blob` objects + * data. The original `Blob` is not altered. + * @since v15.7.0, v14.18.0 + * @param start The starting index. + * @param end The ending index. + * @param type The content-type for the new `Blob` + */ + slice(start?: number, end?: number, type?: string): Blob; + /** + * Returns a promise that fulfills with the contents of the `Blob` decoded as a + * UTF-8 string. + * @since v15.7.0, v14.18.0 + */ + text(): Promise; + /** + * Returns a new `ReadableStream` that allows the content of the `Blob` to be read. + * @since v16.7.0 + */ + stream(): unknown; // pending web streams types + } + export import atob = globalThis.atob; + export import btoa = globalThis.btoa; + global { + // Buffer class + type BufferEncoding = 'ascii' | 'utf8' | 'utf-8' | 'utf16le' | 'ucs2' | 'ucs-2' | 'base64' | 'base64url' | 'latin1' | 'binary' | 'hex'; + type WithImplicitCoercion = + | T + | { + valueOf(): T; + }; + /** + * Raw data is stored in instances of the Buffer class. + * A Buffer is similar to an array of integers but corresponds to a raw memory allocation outside the V8 heap. A Buffer cannot be resized. + * Valid string encodings: 'ascii'|'utf8'|'utf16le'|'ucs2'(alias of 'utf16le')|'base64'|'base64url'|'binary'(deprecated)|'hex' + */ + interface BufferConstructor { + /** + * Allocates a new buffer containing the given {str}. + * + * @param str String to store in buffer. + * @param encoding encoding to use, optional. Default is 'utf8' + * @deprecated since v10.0.0 - Use `Buffer.from(string[, encoding])` instead. + */ + new (str: string, encoding?: BufferEncoding): Buffer; + /** + * Allocates a new buffer of {size} octets. + * + * @param size count of octets to allocate. + * @deprecated since v10.0.0 - Use `Buffer.alloc()` instead (also see `Buffer.allocUnsafe()`). + */ + new (size: number): Buffer; + /** + * Allocates a new buffer containing the given {array} of octets. + * + * @param array The octets to store. + * @deprecated since v10.0.0 - Use `Buffer.from(array)` instead. + */ + new (array: Uint8Array): Buffer; + /** + * Produces a Buffer backed by the same allocated memory as + * the given {ArrayBuffer}/{SharedArrayBuffer}. + * + * + * @param arrayBuffer The ArrayBuffer with which to share memory. + * @deprecated since v10.0.0 - Use `Buffer.from(arrayBuffer[, byteOffset[, length]])` instead. + */ + new (arrayBuffer: ArrayBuffer | SharedArrayBuffer): Buffer; + /** + * Allocates a new buffer containing the given {array} of octets. + * + * @param array The octets to store. + * @deprecated since v10.0.0 - Use `Buffer.from(array)` instead. + */ + new (array: ReadonlyArray): Buffer; + /** + * Copies the passed {buffer} data onto a new {Buffer} instance. + * + * @param buffer The buffer to copy. + * @deprecated since v10.0.0 - Use `Buffer.from(buffer)` instead. + */ + new (buffer: Buffer): Buffer; + /** + * Allocates a new `Buffer` using an `array` of bytes in the range `0` – `255`. + * Array entries outside that range will be truncated to fit into it. + * + * ```js + * import { Buffer } from 'buffer'; + * + * // Creates a new Buffer containing the UTF-8 bytes of the string 'buffer'. + * const buf = Buffer.from([0x62, 0x75, 0x66, 0x66, 0x65, 0x72]); + * ``` + * + * A `TypeError` will be thrown if `array` is not an `Array` or another type + * appropriate for `Buffer.from()` variants. + * + * `Buffer.from(array)` and `Buffer.from(string)` may also use the internal`Buffer` pool like `Buffer.allocUnsafe()` does. + * @since v5.10.0 + */ + from(arrayBuffer: WithImplicitCoercion, byteOffset?: number, length?: number): Buffer; + /** + * Creates a new Buffer using the passed {data} + * @param data data to create a new Buffer + */ + from(data: Uint8Array | ReadonlyArray): Buffer; + from(data: WithImplicitCoercion | string>): Buffer; + /** + * Creates a new Buffer containing the given JavaScript string {str}. + * If provided, the {encoding} parameter identifies the character encoding. + * If not provided, {encoding} defaults to 'utf8'. + */ + from( + str: + | WithImplicitCoercion + | { + [Symbol.toPrimitive](hint: 'string'): string; + }, + encoding?: BufferEncoding + ): Buffer; + /** + * Creates a new Buffer using the passed {data} + * @param values to create a new Buffer + */ + of(...items: number[]): Buffer; + /** + * Returns `true` if `obj` is a `Buffer`, `false` otherwise. + * + * ```js + * import { Buffer } from 'buffer'; + * + * Buffer.isBuffer(Buffer.alloc(10)); // true + * Buffer.isBuffer(Buffer.from('foo')); // true + * Buffer.isBuffer('a string'); // false + * Buffer.isBuffer([]); // false + * Buffer.isBuffer(new Uint8Array(1024)); // false + * ``` + * @since v0.1.101 + */ + isBuffer(obj: any): obj is Buffer; + /** + * Returns `true` if `encoding` is the name of a supported character encoding, + * or `false` otherwise. + * + * ```js + * import { Buffer } from 'buffer'; + * + * console.log(Buffer.isEncoding('utf8')); + * // Prints: true + * + * console.log(Buffer.isEncoding('hex')); + * // Prints: true + * + * console.log(Buffer.isEncoding('utf/8')); + * // Prints: false + * + * console.log(Buffer.isEncoding('')); + * // Prints: false + * ``` + * @since v0.9.1 + * @param encoding A character encoding name to check. + */ + isEncoding(encoding: string): encoding is BufferEncoding; + /** + * Returns the byte length of a string when encoded using `encoding`. + * This is not the same as [`String.prototype.length`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/length), which does not account + * for the encoding that is used to convert the string into bytes. + * + * For `'base64'`, `'base64url'`, and `'hex'`, this function assumes valid input. + * For strings that contain non-base64/hex-encoded data (e.g. whitespace), the + * return value might be greater than the length of a `Buffer` created from the + * string. + * + * ```js + * import { Buffer } from 'buffer'; + * + * const str = '\u00bd + \u00bc = \u00be'; + * + * console.log(`${str}: ${str.length} characters, ` + + * `${Buffer.byteLength(str, 'utf8')} bytes`); + * // Prints: ½ + ¼ = ¾: 9 characters, 12 bytes + * ``` + * + * When `string` is a + * `Buffer`/[`DataView`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView)/[`TypedArray`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/- + * Reference/Global_Objects/TypedArray)/[`ArrayBuffer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer)/[`SharedArrayBuffer`](https://develop- + * er.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/SharedArrayBuffer), the byte length as reported by `.byteLength`is returned. + * @since v0.1.90 + * @param string A value to calculate the length of. + * @param [encoding='utf8'] If `string` is a string, this is its encoding. + * @return The number of bytes contained within `string`. + */ + byteLength(string: string | NodeJS.ArrayBufferView | ArrayBuffer | SharedArrayBuffer, encoding?: BufferEncoding): number; + /** + * Returns a new `Buffer` which is the result of concatenating all the `Buffer`instances in the `list` together. + * + * If the list has no items, or if the `totalLength` is 0, then a new zero-length`Buffer` is returned. + * + * If `totalLength` is not provided, it is calculated from the `Buffer` instances + * in `list` by adding their lengths. + * + * If `totalLength` is provided, it is coerced to an unsigned integer. If the + * combined length of the `Buffer`s in `list` exceeds `totalLength`, the result is + * truncated to `totalLength`. + * + * ```js + * import { Buffer } from 'buffer'; + * + * // Create a single `Buffer` from a list of three `Buffer` instances. + * + * const buf1 = Buffer.alloc(10); + * const buf2 = Buffer.alloc(14); + * const buf3 = Buffer.alloc(18); + * const totalLength = buf1.length + buf2.length + buf3.length; + * + * console.log(totalLength); + * // Prints: 42 + * + * const bufA = Buffer.concat([buf1, buf2, buf3], totalLength); + * + * console.log(bufA); + * // Prints: + * console.log(bufA.length); + * // Prints: 42 + * ``` + * + * `Buffer.concat()` may also use the internal `Buffer` pool like `Buffer.allocUnsafe()` does. + * @since v0.7.11 + * @param list List of `Buffer` or {@link Uint8Array} instances to concatenate. + * @param totalLength Total length of the `Buffer` instances in `list` when concatenated. + */ + concat(list: ReadonlyArray, totalLength?: number): Buffer; + /** + * Compares `buf1` to `buf2`, typically for the purpose of sorting arrays of`Buffer` instances. This is equivalent to calling `buf1.compare(buf2)`. + * + * ```js + * import { Buffer } from 'buffer'; + * + * const buf1 = Buffer.from('1234'); + * const buf2 = Buffer.from('0123'); + * const arr = [buf1, buf2]; + * + * console.log(arr.sort(Buffer.compare)); + * // Prints: [ , ] + * // (This result is equal to: [buf2, buf1].) + * ``` + * @since v0.11.13 + * @return Either `-1`, `0`, or `1`, depending on the result of the comparison. See `compare` for details. + */ + compare(buf1: Uint8Array, buf2: Uint8Array): -1 | 0 | 1; + /** + * Allocates a new `Buffer` of `size` bytes. If `fill` is `undefined`, the`Buffer` will be zero-filled. + * + * ```js + * import { Buffer } from 'buffer'; + * + * const buf = Buffer.alloc(5); + * + * console.log(buf); + * // Prints: + * ``` + * + * If `size` is larger than {@link constants.MAX_LENGTH} or smaller than 0, `ERR_INVALID_ARG_VALUE` is thrown. + * + * If `fill` is specified, the allocated `Buffer` will be initialized by calling `buf.fill(fill)`. + * + * ```js + * import { Buffer } from 'buffer'; + * + * const buf = Buffer.alloc(5, 'a'); + * + * console.log(buf); + * // Prints: + * ``` + * + * If both `fill` and `encoding` are specified, the allocated `Buffer` will be + * initialized by calling `buf.fill(fill, encoding)`. + * + * ```js + * import { Buffer } from 'buffer'; + * + * const buf = Buffer.alloc(11, 'aGVsbG8gd29ybGQ=', 'base64'); + * + * console.log(buf); + * // Prints: + * ``` + * + * Calling `Buffer.alloc()` can be measurably slower than the alternative `Buffer.allocUnsafe()` but ensures that the newly created `Buffer` instance + * contents will never contain sensitive data from previous allocations, including + * data that might not have been allocated for `Buffer`s. + * + * A `TypeError` will be thrown if `size` is not a number. + * @since v5.10.0 + * @param size The desired length of the new `Buffer`. + * @param [fill=0] A value to pre-fill the new `Buffer` with. + * @param [encoding='utf8'] If `fill` is a string, this is its encoding. + */ + alloc(size: number, fill?: string | Buffer | number, encoding?: BufferEncoding): Buffer; + /** + * Allocates a new `Buffer` of `size` bytes. If `size` is larger than {@link constants.MAX_LENGTH} or smaller than 0, `ERR_INVALID_ARG_VALUE` is thrown. + * + * The underlying memory for `Buffer` instances created in this way is _not_ + * _initialized_. The contents of the newly created `Buffer` are unknown and _may contain sensitive data_. Use `Buffer.alloc()` instead to initialize`Buffer` instances with zeroes. + * + * ```js + * import { Buffer } from 'buffer'; + * + * const buf = Buffer.allocUnsafe(10); + * + * console.log(buf); + * // Prints (contents may vary): + * + * buf.fill(0); + * + * console.log(buf); + * // Prints: + * ``` + * + * A `TypeError` will be thrown if `size` is not a number. + * + * The `Buffer` module pre-allocates an internal `Buffer` instance of + * size `Buffer.poolSize` that is used as a pool for the fast allocation of new`Buffer` instances created using `Buffer.allocUnsafe()`,`Buffer.from(array)`, `Buffer.concat()`, and the + * deprecated`new Buffer(size)` constructor only when `size` is less than or equal + * to `Buffer.poolSize >> 1` (floor of `Buffer.poolSize` divided by two). + * + * Use of this pre-allocated internal memory pool is a key difference between + * calling `Buffer.alloc(size, fill)` vs. `Buffer.allocUnsafe(size).fill(fill)`. + * Specifically, `Buffer.alloc(size, fill)` will _never_ use the internal `Buffer`pool, while `Buffer.allocUnsafe(size).fill(fill)`_will_ use the internal`Buffer` pool if `size` is less + * than or equal to half `Buffer.poolSize`. The + * difference is subtle but can be important when an application requires the + * additional performance that `Buffer.allocUnsafe()` provides. + * @since v5.10.0 + * @param size The desired length of the new `Buffer`. + */ + allocUnsafe(size: number): Buffer; + /** + * Allocates a new `Buffer` of `size` bytes. If `size` is larger than {@link constants.MAX_LENGTH} or smaller than 0, `ERR_INVALID_ARG_VALUE` is thrown. A zero-length `Buffer` is created + * if `size` is 0. + * + * The underlying memory for `Buffer` instances created in this way is _not_ + * _initialized_. The contents of the newly created `Buffer` are unknown and_may contain sensitive data_. Use `buf.fill(0)` to initialize + * such `Buffer` instances with zeroes. + * + * When using `Buffer.allocUnsafe()` to allocate new `Buffer` instances, + * allocations under 4 KB are sliced from a single pre-allocated `Buffer`. This + * allows applications to avoid the garbage collection overhead of creating many + * individually allocated `Buffer` instances. This approach improves both + * performance and memory usage by eliminating the need to track and clean up as + * many individual `ArrayBuffer` objects. + * + * However, in the case where a developer may need to retain a small chunk of + * memory from a pool for an indeterminate amount of time, it may be appropriate + * to create an un-pooled `Buffer` instance using `Buffer.allocUnsafeSlow()` and + * then copying out the relevant bits. + * + * ```js + * import { Buffer } from 'buffer'; + * + * // Need to keep around a few small chunks of memory. + * const store = []; + * + * socket.on('readable', () => { + * let data; + * while (null !== (data = readable.read())) { + * // Allocate for retained data. + * const sb = Buffer.allocUnsafeSlow(10); + * + * // Copy the data into the new allocation. + * data.copy(sb, 0, 0, 10); + * + * store.push(sb); + * } + * }); + * ``` + * + * A `TypeError` will be thrown if `size` is not a number. + * @since v5.12.0 + * @param size The desired length of the new `Buffer`. + */ + allocUnsafeSlow(size: number): Buffer; + /** + * This is the size (in bytes) of pre-allocated internal `Buffer` instances used + * for pooling. This value may be modified. + * @since v0.11.3 + */ + poolSize: number; + } + interface Buffer extends Uint8Array { + /** + * Writes `string` to `buf` at `offset` according to the character encoding in`encoding`. The `length` parameter is the number of bytes to write. If `buf` did + * not contain enough space to fit the entire string, only part of `string` will be + * written. However, partially encoded characters will not be written. + * + * ```js + * import { Buffer } from 'buffer'; + * + * const buf = Buffer.alloc(256); + * + * const len = buf.write('\u00bd + \u00bc = \u00be', 0); + * + * console.log(`${len} bytes: ${buf.toString('utf8', 0, len)}`); + * // Prints: 12 bytes: ½ + ¼ = ¾ + * + * const buffer = Buffer.alloc(10); + * + * const length = buffer.write('abcd', 8); + * + * console.log(`${length} bytes: ${buffer.toString('utf8', 8, 10)}`); + * // Prints: 2 bytes : ab + * ``` + * @since v0.1.90 + * @param string String to write to `buf`. + * @param [offset=0] Number of bytes to skip before starting to write `string`. + * @param [length=buf.length - offset] Maximum number of bytes to write (written bytes will not exceed `buf.length - offset`). + * @param [encoding='utf8'] The character encoding of `string`. + * @return Number of bytes written. + */ + write(string: string, encoding?: BufferEncoding): number; + write(string: string, offset: number, encoding?: BufferEncoding): number; + write(string: string, offset: number, length: number, encoding?: BufferEncoding): number; + /** + * Decodes `buf` to a string according to the specified character encoding in`encoding`. `start` and `end` may be passed to decode only a subset of `buf`. + * + * If `encoding` is `'utf8'` and a byte sequence in the input is not valid UTF-8, + * then each invalid byte is replaced with the replacement character `U+FFFD`. + * + * The maximum length of a string instance (in UTF-16 code units) is available + * as {@link constants.MAX_STRING_LENGTH}. + * + * ```js + * import { Buffer } from 'buffer'; + * + * const buf1 = Buffer.allocUnsafe(26); + * + * for (let i = 0; i < 26; i++) { + * // 97 is the decimal ASCII value for 'a'. + * buf1[i] = i + 97; + * } + * + * console.log(buf1.toString('utf8')); + * // Prints: abcdefghijklmnopqrstuvwxyz + * console.log(buf1.toString('utf8', 0, 5)); + * // Prints: abcde + * + * const buf2 = Buffer.from('tést'); + * + * console.log(buf2.toString('hex')); + * // Prints: 74c3a97374 + * console.log(buf2.toString('utf8', 0, 3)); + * // Prints: té + * console.log(buf2.toString(undefined, 0, 3)); + * // Prints: té + * ``` + * @since v0.1.90 + * @param [encoding='utf8'] The character encoding to use. + * @param [start=0] The byte offset to start decoding at. + * @param [end=buf.length] The byte offset to stop decoding at (not inclusive). + */ + toString(encoding?: BufferEncoding, start?: number, end?: number): string; + /** + * Returns a JSON representation of `buf`. [`JSON.stringify()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify) implicitly calls + * this function when stringifying a `Buffer` instance. + * + * `Buffer.from()` accepts objects in the format returned from this method. + * In particular, `Buffer.from(buf.toJSON())` works like `Buffer.from(buf)`. + * + * ```js + * import { Buffer } from 'buffer'; + * + * const buf = Buffer.from([0x1, 0x2, 0x3, 0x4, 0x5]); + * const json = JSON.stringify(buf); + * + * console.log(json); + * // Prints: {"type":"Buffer","data":[1,2,3,4,5]} + * + * const copy = JSON.parse(json, (key, value) => { + * return value && value.type === 'Buffer' ? + * Buffer.from(value) : + * value; + * }); + * + * console.log(copy); + * // Prints: + * ``` + * @since v0.9.2 + */ + toJSON(): { + type: 'Buffer'; + data: number[]; + }; + /** + * Returns `true` if both `buf` and `otherBuffer` have exactly the same bytes,`false` otherwise. Equivalent to `buf.compare(otherBuffer) === 0`. + * + * ```js + * import { Buffer } from 'buffer'; + * + * const buf1 = Buffer.from('ABC'); + * const buf2 = Buffer.from('414243', 'hex'); + * const buf3 = Buffer.from('ABCD'); + * + * console.log(buf1.equals(buf2)); + * // Prints: true + * console.log(buf1.equals(buf3)); + * // Prints: false + * ``` + * @since v0.11.13 + * @param otherBuffer A `Buffer` or {@link Uint8Array} with which to compare `buf`. + */ + equals(otherBuffer: Uint8Array): boolean; + /** + * Compares `buf` with `target` and returns a number indicating whether `buf`comes before, after, or is the same as `target` in sort order. + * Comparison is based on the actual sequence of bytes in each `Buffer`. + * + * * `0` is returned if `target` is the same as `buf` + * * `1` is returned if `target` should come _before_`buf` when sorted. + * * `-1` is returned if `target` should come _after_`buf` when sorted. + * + * ```js + * import { Buffer } from 'buffer'; + * + * const buf1 = Buffer.from('ABC'); + * const buf2 = Buffer.from('BCD'); + * const buf3 = Buffer.from('ABCD'); + * + * console.log(buf1.compare(buf1)); + * // Prints: 0 + * console.log(buf1.compare(buf2)); + * // Prints: -1 + * console.log(buf1.compare(buf3)); + * // Prints: -1 + * console.log(buf2.compare(buf1)); + * // Prints: 1 + * console.log(buf2.compare(buf3)); + * // Prints: 1 + * console.log([buf1, buf2, buf3].sort(Buffer.compare)); + * // Prints: [ , , ] + * // (This result is equal to: [buf1, buf3, buf2].) + * ``` + * + * The optional `targetStart`, `targetEnd`, `sourceStart`, and `sourceEnd`arguments can be used to limit the comparison to specific ranges within `target`and `buf` respectively. + * + * ```js + * import { Buffer } from 'buffer'; + * + * const buf1 = Buffer.from([1, 2, 3, 4, 5, 6, 7, 8, 9]); + * const buf2 = Buffer.from([5, 6, 7, 8, 9, 1, 2, 3, 4]); + * + * console.log(buf1.compare(buf2, 5, 9, 0, 4)); + * // Prints: 0 + * console.log(buf1.compare(buf2, 0, 6, 4)); + * // Prints: -1 + * console.log(buf1.compare(buf2, 5, 6, 5)); + * // Prints: 1 + * ``` + * + * `ERR_OUT_OF_RANGE` is thrown if `targetStart < 0`, `sourceStart < 0`,`targetEnd > target.byteLength`, or `sourceEnd > source.byteLength`. + * @since v0.11.13 + * @param target A `Buffer` or {@link Uint8Array} with which to compare `buf`. + * @param [targetStart=0] The offset within `target` at which to begin comparison. + * @param [targetEnd=target.length] The offset within `target` at which to end comparison (not inclusive). + * @param [sourceStart=0] The offset within `buf` at which to begin comparison. + * @param [sourceEnd=buf.length] The offset within `buf` at which to end comparison (not inclusive). + */ + compare(target: Uint8Array, targetStart?: number, targetEnd?: number, sourceStart?: number, sourceEnd?: number): -1 | 0 | 1; + /** + * Copies data from a region of `buf` to a region in `target`, even if the `target`memory region overlaps with `buf`. + * + * [`TypedArray.prototype.set()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray/set) performs the same operation, and is available + * for all TypedArrays, including Node.js `Buffer`s, although it takes + * different function arguments. + * + * ```js + * import { Buffer } from 'buffer'; + * + * // Create two `Buffer` instances. + * const buf1 = Buffer.allocUnsafe(26); + * const buf2 = Buffer.allocUnsafe(26).fill('!'); + * + * for (let i = 0; i < 26; i++) { + * // 97 is the decimal ASCII value for 'a'. + * buf1[i] = i + 97; + * } + * + * // Copy `buf1` bytes 16 through 19 into `buf2` starting at byte 8 of `buf2`. + * buf1.copy(buf2, 8, 16, 20); + * // This is equivalent to: + * // buf2.set(buf1.subarray(16, 20), 8); + * + * console.log(buf2.toString('ascii', 0, 25)); + * // Prints: !!!!!!!!qrst!!!!!!!!!!!!! + * ``` + * + * ```js + * import { Buffer } from 'buffer'; + * + * // Create a `Buffer` and copy data from one region to an overlapping region + * // within the same `Buffer`. + * + * const buf = Buffer.allocUnsafe(26); + * + * for (let i = 0; i < 26; i++) { + * // 97 is the decimal ASCII value for 'a'. + * buf[i] = i + 97; + * } + * + * buf.copy(buf, 0, 4, 10); + * + * console.log(buf.toString()); + * // Prints: efghijghijklmnopqrstuvwxyz + * ``` + * @since v0.1.90 + * @param target A `Buffer` or {@link Uint8Array} to copy into. + * @param [targetStart=0] The offset within `target` at which to begin writing. + * @param [sourceStart=0] The offset within `buf` from which to begin copying. + * @param [sourceEnd=buf.length] The offset within `buf` at which to stop copying (not inclusive). + * @return The number of bytes copied. + */ + copy(target: Uint8Array, targetStart?: number, sourceStart?: number, sourceEnd?: number): number; + /** + * Returns a new `Buffer` that references the same memory as the original, but + * offset and cropped by the `start` and `end` indices. + * + * This method is not compatible with the `Uint8Array.prototype.slice()`, + * which is a superclass of `Buffer`. To copy the slice, use`Uint8Array.prototype.slice()`. + * + * ```js + * import { Buffer } from 'buffer'; + * + * const buf = Buffer.from('buffer'); + * + * const copiedBuf = Uint8Array.prototype.slice.call(buf); + * copiedBuf[0]++; + * console.log(copiedBuf.toString()); + * // Prints: cuffer + * + * console.log(buf.toString()); + * // Prints: buffer + * + * // With buf.slice(), the original buffer is modified. + * const notReallyCopiedBuf = buf.slice(); + * notReallyCopiedBuf[0]++; + * console.log(notReallyCopiedBuf.toString()); + * // Prints: cuffer + * console.log(buf.toString()); + * // Also prints: cuffer (!) + * ``` + * @since v0.3.0 + * @deprecated Use `subarray` instead. + * @param [start=0] Where the new `Buffer` will start. + * @param [end=buf.length] Where the new `Buffer` will end (not inclusive). + */ + slice(start?: number, end?: number): Buffer; + /** + * Returns a new `Buffer` that references the same memory as the original, but + * offset and cropped by the `start` and `end` indices. + * + * Specifying `end` greater than `buf.length` will return the same result as + * that of `end` equal to `buf.length`. + * + * This method is inherited from [`TypedArray.prototype.subarray()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray/subarray). + * + * Modifying the new `Buffer` slice will modify the memory in the original `Buffer`because the allocated memory of the two objects overlap. + * + * ```js + * import { Buffer } from 'buffer'; + * + * // Create a `Buffer` with the ASCII alphabet, take a slice, and modify one byte + * // from the original `Buffer`. + * + * const buf1 = Buffer.allocUnsafe(26); + * + * for (let i = 0; i < 26; i++) { + * // 97 is the decimal ASCII value for 'a'. + * buf1[i] = i + 97; + * } + * + * const buf2 = buf1.subarray(0, 3); + * + * console.log(buf2.toString('ascii', 0, buf2.length)); + * // Prints: abc + * + * buf1[0] = 33; + * + * console.log(buf2.toString('ascii', 0, buf2.length)); + * // Prints: !bc + * ``` + * + * Specifying negative indexes causes the slice to be generated relative to the + * end of `buf` rather than the beginning. + * + * ```js + * import { Buffer } from 'buffer'; + * + * const buf = Buffer.from('buffer'); + * + * console.log(buf.subarray(-6, -1).toString()); + * // Prints: buffe + * // (Equivalent to buf.subarray(0, 5).) + * + * console.log(buf.subarray(-6, -2).toString()); + * // Prints: buff + * // (Equivalent to buf.subarray(0, 4).) + * + * console.log(buf.subarray(-5, -2).toString()); + * // Prints: uff + * // (Equivalent to buf.subarray(1, 4).) + * ``` + * @since v3.0.0 + * @param [start=0] Where the new `Buffer` will start. + * @param [end=buf.length] Where the new `Buffer` will end (not inclusive). + */ + subarray(start?: number, end?: number): Buffer; + /** + * Writes `value` to `buf` at the specified `offset` as big-endian. + * + * `value` is interpreted and written as a two's complement signed integer. + * + * ```js + * import { Buffer } from 'buffer'; + * + * const buf = Buffer.allocUnsafe(8); + * + * buf.writeBigInt64BE(0x0102030405060708n, 0); + * + * console.log(buf); + * // Prints: + * ``` + * @since v12.0.0, v10.20.0 + * @param value Number to be written to `buf`. + * @param [offset=0] Number of bytes to skip before starting to write. Must satisfy: `0 <= offset <= buf.length - 8`. + * @return `offset` plus the number of bytes written. + */ + writeBigInt64BE(value: bigint, offset?: number): number; + /** + * Writes `value` to `buf` at the specified `offset` as little-endian. + * + * `value` is interpreted and written as a two's complement signed integer. + * + * ```js + * import { Buffer } from 'buffer'; + * + * const buf = Buffer.allocUnsafe(8); + * + * buf.writeBigInt64LE(0x0102030405060708n, 0); + * + * console.log(buf); + * // Prints: + * ``` + * @since v12.0.0, v10.20.0 + * @param value Number to be written to `buf`. + * @param [offset=0] Number of bytes to skip before starting to write. Must satisfy: `0 <= offset <= buf.length - 8`. + * @return `offset` plus the number of bytes written. + */ + writeBigInt64LE(value: bigint, offset?: number): number; + /** + * Writes `value` to `buf` at the specified `offset` as big-endian. + * + * This function is also available under the `writeBigUint64BE` alias. + * + * ```js + * import { Buffer } from 'buffer'; + * + * const buf = Buffer.allocUnsafe(8); + * + * buf.writeBigUInt64BE(0xdecafafecacefaden, 0); + * + * console.log(buf); + * // Prints: + * ``` + * @since v12.0.0, v10.20.0 + * @param value Number to be written to `buf`. + * @param [offset=0] Number of bytes to skip before starting to write. Must satisfy: `0 <= offset <= buf.length - 8`. + * @return `offset` plus the number of bytes written. + */ + writeBigUInt64BE(value: bigint, offset?: number): number; + /** + * @alias Buffer.writeBigUInt64BE + * @since v14.10.0, v12.19.0 + */ + writeBigUint64BE(value: bigint, offset?: number): number; + /** + * Writes `value` to `buf` at the specified `offset` as little-endian + * + * ```js + * import { Buffer } from 'buffer'; + * + * const buf = Buffer.allocUnsafe(8); + * + * buf.writeBigUInt64LE(0xdecafafecacefaden, 0); + * + * console.log(buf); + * // Prints: + * ``` + * + * This function is also available under the `writeBigUint64LE` alias. + * @since v12.0.0, v10.20.0 + * @param value Number to be written to `buf`. + * @param [offset=0] Number of bytes to skip before starting to write. Must satisfy: `0 <= offset <= buf.length - 8`. + * @return `offset` plus the number of bytes written. + */ + writeBigUInt64LE(value: bigint, offset?: number): number; + /** + * @alias Buffer.writeBigUInt64LE + * @since v14.10.0, v12.19.0 + */ + writeBigUint64LE(value: bigint, offset?: number): number; + /** + * Writes `byteLength` bytes of `value` to `buf` at the specified `offset`as little-endian. Supports up to 48 bits of accuracy. Behavior is undefined + * when `value` is anything other than an unsigned integer. + * + * This function is also available under the `writeUintLE` alias. + * + * ```js + * import { Buffer } from 'buffer'; + * + * const buf = Buffer.allocUnsafe(6); + * + * buf.writeUIntLE(0x1234567890ab, 0, 6); + * + * console.log(buf); + * // Prints: + * ``` + * @since v0.5.5 + * @param value Number to be written to `buf`. + * @param offset Number of bytes to skip before starting to write. Must satisfy `0 <= offset <= buf.length - byteLength`. + * @param byteLength Number of bytes to write. Must satisfy `0 < byteLength <= 6`. + * @return `offset` plus the number of bytes written. + */ + writeUIntLE(value: number, offset: number, byteLength: number): number; + /** + * @alias Buffer.writeUIntLE + * @since v14.9.0, v12.19.0 + */ + writeUintLE(value: number, offset: number, byteLength: number): number; + /** + * Writes `byteLength` bytes of `value` to `buf` at the specified `offset`as big-endian. Supports up to 48 bits of accuracy. Behavior is undefined + * when `value` is anything other than an unsigned integer. + * + * This function is also available under the `writeUintBE` alias. + * + * ```js + * import { Buffer } from 'buffer'; + * + * const buf = Buffer.allocUnsafe(6); + * + * buf.writeUIntBE(0x1234567890ab, 0, 6); + * + * console.log(buf); + * // Prints: + * ``` + * @since v0.5.5 + * @param value Number to be written to `buf`. + * @param offset Number of bytes to skip before starting to write. Must satisfy `0 <= offset <= buf.length - byteLength`. + * @param byteLength Number of bytes to write. Must satisfy `0 < byteLength <= 6`. + * @return `offset` plus the number of bytes written. + */ + writeUIntBE(value: number, offset: number, byteLength: number): number; + /** + * @alias Buffer.writeUIntBE + * @since v14.9.0, v12.19.0 + */ + writeUintBE(value: number, offset: number, byteLength: number): number; + /** + * Writes `byteLength` bytes of `value` to `buf` at the specified `offset`as little-endian. Supports up to 48 bits of accuracy. Behavior is undefined + * when `value` is anything other than a signed integer. + * + * ```js + * import { Buffer } from 'buffer'; + * + * const buf = Buffer.allocUnsafe(6); + * + * buf.writeIntLE(0x1234567890ab, 0, 6); + * + * console.log(buf); + * // Prints: + * ``` + * @since v0.11.15 + * @param value Number to be written to `buf`. + * @param offset Number of bytes to skip before starting to write. Must satisfy `0 <= offset <= buf.length - byteLength`. + * @param byteLength Number of bytes to write. Must satisfy `0 < byteLength <= 6`. + * @return `offset` plus the number of bytes written. + */ + writeIntLE(value: number, offset: number, byteLength: number): number; + /** + * Writes `byteLength` bytes of `value` to `buf` at the specified `offset`as big-endian. Supports up to 48 bits of accuracy. Behavior is undefined when`value` is anything other than a + * signed integer. + * + * ```js + * import { Buffer } from 'buffer'; + * + * const buf = Buffer.allocUnsafe(6); + * + * buf.writeIntBE(0x1234567890ab, 0, 6); + * + * console.log(buf); + * // Prints: + * ``` + * @since v0.11.15 + * @param value Number to be written to `buf`. + * @param offset Number of bytes to skip before starting to write. Must satisfy `0 <= offset <= buf.length - byteLength`. + * @param byteLength Number of bytes to write. Must satisfy `0 < byteLength <= 6`. + * @return `offset` plus the number of bytes written. + */ + writeIntBE(value: number, offset: number, byteLength: number): number; + /** + * Reads an unsigned, big-endian 64-bit integer from `buf` at the specified`offset`. + * + * This function is also available under the `readBigUint64BE` alias. + * + * ```js + * import { Buffer } from 'buffer'; + * + * const buf = Buffer.from([0x00, 0x00, 0x00, 0x00, 0xff, 0xff, 0xff, 0xff]); + * + * console.log(buf.readBigUInt64BE(0)); + * // Prints: 4294967295n + * ``` + * @since v12.0.0, v10.20.0 + * @param [offset=0] Number of bytes to skip before starting to read. Must satisfy: `0 <= offset <= buf.length - 8`. + */ + readBigUInt64BE(offset?: number): bigint; + /** + * @alias Buffer.readBigUInt64BE + * @since v14.10.0, v12.19.0 + */ + readBigUint64BE(offset?: number): bigint; + /** + * Reads an unsigned, little-endian 64-bit integer from `buf` at the specified`offset`. + * + * This function is also available under the `readBigUint64LE` alias. + * + * ```js + * import { Buffer } from 'buffer'; + * + * const buf = Buffer.from([0x00, 0x00, 0x00, 0x00, 0xff, 0xff, 0xff, 0xff]); + * + * console.log(buf.readBigUInt64LE(0)); + * // Prints: 18446744069414584320n + * ``` + * @since v12.0.0, v10.20.0 + * @param [offset=0] Number of bytes to skip before starting to read. Must satisfy: `0 <= offset <= buf.length - 8`. + */ + readBigUInt64LE(offset?: number): bigint; + /** + * @alias Buffer.readBigUInt64LE + * @since v14.10.0, v12.19.0 + */ + readBigUint64LE(offset?: number): bigint; + /** + * Reads a signed, big-endian 64-bit integer from `buf` at the specified `offset`. + * + * Integers read from a `Buffer` are interpreted as two's complement signed + * values. + * @since v12.0.0, v10.20.0 + * @param [offset=0] Number of bytes to skip before starting to read. Must satisfy: `0 <= offset <= buf.length - 8`. + */ + readBigInt64BE(offset?: number): bigint; + /** + * Reads a signed, little-endian 64-bit integer from `buf` at the specified`offset`. + * + * Integers read from a `Buffer` are interpreted as two's complement signed + * values. + * @since v12.0.0, v10.20.0 + * @param [offset=0] Number of bytes to skip before starting to read. Must satisfy: `0 <= offset <= buf.length - 8`. + */ + readBigInt64LE(offset?: number): bigint; + /** + * Reads `byteLength` number of bytes from `buf` at the specified `offset`and interprets the result as an unsigned, little-endian integer supporting + * up to 48 bits of accuracy. + * + * This function is also available under the `readUintLE` alias. + * + * ```js + * import { Buffer } from 'buffer'; + * + * const buf = Buffer.from([0x12, 0x34, 0x56, 0x78, 0x90, 0xab]); + * + * console.log(buf.readUIntLE(0, 6).toString(16)); + * // Prints: ab9078563412 + * ``` + * @since v0.11.15 + * @param offset Number of bytes to skip before starting to read. Must satisfy `0 <= offset <= buf.length - byteLength`. + * @param byteLength Number of bytes to read. Must satisfy `0 < byteLength <= 6`. + */ + readUIntLE(offset: number, byteLength: number): number; + /** + * @alias Buffer.readUIntLE + * @since v14.9.0, v12.19.0 + */ + readUintLE(offset: number, byteLength: number): number; + /** + * Reads `byteLength` number of bytes from `buf` at the specified `offset`and interprets the result as an unsigned big-endian integer supporting + * up to 48 bits of accuracy. + * + * This function is also available under the `readUintBE` alias. + * + * ```js + * import { Buffer } from 'buffer'; + * + * const buf = Buffer.from([0x12, 0x34, 0x56, 0x78, 0x90, 0xab]); + * + * console.log(buf.readUIntBE(0, 6).toString(16)); + * // Prints: 1234567890ab + * console.log(buf.readUIntBE(1, 6).toString(16)); + * // Throws ERR_OUT_OF_RANGE. + * ``` + * @since v0.11.15 + * @param offset Number of bytes to skip before starting to read. Must satisfy `0 <= offset <= buf.length - byteLength`. + * @param byteLength Number of bytes to read. Must satisfy `0 < byteLength <= 6`. + */ + readUIntBE(offset: number, byteLength: number): number; + /** + * @alias Buffer.readUIntBE + * @since v14.9.0, v12.19.0 + */ + readUintBE(offset: number, byteLength: number): number; + /** + * Reads `byteLength` number of bytes from `buf` at the specified `offset`and interprets the result as a little-endian, two's complement signed value + * supporting up to 48 bits of accuracy. + * + * ```js + * import { Buffer } from 'buffer'; + * + * const buf = Buffer.from([0x12, 0x34, 0x56, 0x78, 0x90, 0xab]); + * + * console.log(buf.readIntLE(0, 6).toString(16)); + * // Prints: -546f87a9cbee + * ``` + * @since v0.11.15 + * @param offset Number of bytes to skip before starting to read. Must satisfy `0 <= offset <= buf.length - byteLength`. + * @param byteLength Number of bytes to read. Must satisfy `0 < byteLength <= 6`. + */ + readIntLE(offset: number, byteLength: number): number; + /** + * Reads `byteLength` number of bytes from `buf` at the specified `offset`and interprets the result as a big-endian, two's complement signed value + * supporting up to 48 bits of accuracy. + * + * ```js + * import { Buffer } from 'buffer'; + * + * const buf = Buffer.from([0x12, 0x34, 0x56, 0x78, 0x90, 0xab]); + * + * console.log(buf.readIntBE(0, 6).toString(16)); + * // Prints: 1234567890ab + * console.log(buf.readIntBE(1, 6).toString(16)); + * // Throws ERR_OUT_OF_RANGE. + * console.log(buf.readIntBE(1, 0).toString(16)); + * // Throws ERR_OUT_OF_RANGE. + * ``` + * @since v0.11.15 + * @param offset Number of bytes to skip before starting to read. Must satisfy `0 <= offset <= buf.length - byteLength`. + * @param byteLength Number of bytes to read. Must satisfy `0 < byteLength <= 6`. + */ + readIntBE(offset: number, byteLength: number): number; + /** + * Reads an unsigned 8-bit integer from `buf` at the specified `offset`. + * + * This function is also available under the `readUint8` alias. + * + * ```js + * import { Buffer } from 'buffer'; + * + * const buf = Buffer.from([1, -2]); + * + * console.log(buf.readUInt8(0)); + * // Prints: 1 + * console.log(buf.readUInt8(1)); + * // Prints: 254 + * console.log(buf.readUInt8(2)); + * // Throws ERR_OUT_OF_RANGE. + * ``` + * @since v0.5.0 + * @param [offset=0] Number of bytes to skip before starting to read. Must satisfy `0 <= offset <= buf.length - 1`. + */ + readUInt8(offset?: number): number; + /** + * @alias Buffer.readUInt8 + * @since v14.9.0, v12.19.0 + */ + readUint8(offset?: number): number; + /** + * Reads an unsigned, little-endian 16-bit integer from `buf` at the specified`offset`. + * + * This function is also available under the `readUint16LE` alias. + * + * ```js + * import { Buffer } from 'buffer'; + * + * const buf = Buffer.from([0x12, 0x34, 0x56]); + * + * console.log(buf.readUInt16LE(0).toString(16)); + * // Prints: 3412 + * console.log(buf.readUInt16LE(1).toString(16)); + * // Prints: 5634 + * console.log(buf.readUInt16LE(2).toString(16)); + * // Throws ERR_OUT_OF_RANGE. + * ``` + * @since v0.5.5 + * @param [offset=0] Number of bytes to skip before starting to read. Must satisfy `0 <= offset <= buf.length - 2`. + */ + readUInt16LE(offset?: number): number; + /** + * @alias Buffer.readUInt16LE + * @since v14.9.0, v12.19.0 + */ + readUint16LE(offset?: number): number; + /** + * Reads an unsigned, big-endian 16-bit integer from `buf` at the specified`offset`. + * + * This function is also available under the `readUint16BE` alias. + * + * ```js + * import { Buffer } from 'buffer'; + * + * const buf = Buffer.from([0x12, 0x34, 0x56]); + * + * console.log(buf.readUInt16BE(0).toString(16)); + * // Prints: 1234 + * console.log(buf.readUInt16BE(1).toString(16)); + * // Prints: 3456 + * ``` + * @since v0.5.5 + * @param [offset=0] Number of bytes to skip before starting to read. Must satisfy `0 <= offset <= buf.length - 2`. + */ + readUInt16BE(offset?: number): number; + /** + * @alias Buffer.readUInt16BE + * @since v14.9.0, v12.19.0 + */ + readUint16BE(offset?: number): number; + /** + * Reads an unsigned, little-endian 32-bit integer from `buf` at the specified`offset`. + * + * This function is also available under the `readUint32LE` alias. + * + * ```js + * import { Buffer } from 'buffer'; + * + * const buf = Buffer.from([0x12, 0x34, 0x56, 0x78]); + * + * console.log(buf.readUInt32LE(0).toString(16)); + * // Prints: 78563412 + * console.log(buf.readUInt32LE(1).toString(16)); + * // Throws ERR_OUT_OF_RANGE. + * ``` + * @since v0.5.5 + * @param [offset=0] Number of bytes to skip before starting to read. Must satisfy `0 <= offset <= buf.length - 4`. + */ + readUInt32LE(offset?: number): number; + /** + * @alias Buffer.readUInt32LE + * @since v14.9.0, v12.19.0 + */ + readUint32LE(offset?: number): number; + /** + * Reads an unsigned, big-endian 32-bit integer from `buf` at the specified`offset`. + * + * This function is also available under the `readUint32BE` alias. + * + * ```js + * import { Buffer } from 'buffer'; + * + * const buf = Buffer.from([0x12, 0x34, 0x56, 0x78]); + * + * console.log(buf.readUInt32BE(0).toString(16)); + * // Prints: 12345678 + * ``` + * @since v0.5.5 + * @param [offset=0] Number of bytes to skip before starting to read. Must satisfy `0 <= offset <= buf.length - 4`. + */ + readUInt32BE(offset?: number): number; + /** + * @alias Buffer.readUInt32BE + * @since v14.9.0, v12.19.0 + */ + readUint32BE(offset?: number): number; + /** + * Reads a signed 8-bit integer from `buf` at the specified `offset`. + * + * Integers read from a `Buffer` are interpreted as two's complement signed values. + * + * ```js + * import { Buffer } from 'buffer'; + * + * const buf = Buffer.from([-1, 5]); + * + * console.log(buf.readInt8(0)); + * // Prints: -1 + * console.log(buf.readInt8(1)); + * // Prints: 5 + * console.log(buf.readInt8(2)); + * // Throws ERR_OUT_OF_RANGE. + * ``` + * @since v0.5.0 + * @param [offset=0] Number of bytes to skip before starting to read. Must satisfy `0 <= offset <= buf.length - 1`. + */ + readInt8(offset?: number): number; + /** + * Reads a signed, little-endian 16-bit integer from `buf` at the specified`offset`. + * + * Integers read from a `Buffer` are interpreted as two's complement signed values. + * + * ```js + * import { Buffer } from 'buffer'; + * + * const buf = Buffer.from([0, 5]); + * + * console.log(buf.readInt16LE(0)); + * // Prints: 1280 + * console.log(buf.readInt16LE(1)); + * // Throws ERR_OUT_OF_RANGE. + * ``` + * @since v0.5.5 + * @param [offset=0] Number of bytes to skip before starting to read. Must satisfy `0 <= offset <= buf.length - 2`. + */ + readInt16LE(offset?: number): number; + /** + * Reads a signed, big-endian 16-bit integer from `buf` at the specified `offset`. + * + * Integers read from a `Buffer` are interpreted as two's complement signed values. + * + * ```js + * import { Buffer } from 'buffer'; + * + * const buf = Buffer.from([0, 5]); + * + * console.log(buf.readInt16BE(0)); + * // Prints: 5 + * ``` + * @since v0.5.5 + * @param [offset=0] Number of bytes to skip before starting to read. Must satisfy `0 <= offset <= buf.length - 2`. + */ + readInt16BE(offset?: number): number; + /** + * Reads a signed, little-endian 32-bit integer from `buf` at the specified`offset`. + * + * Integers read from a `Buffer` are interpreted as two's complement signed values. + * + * ```js + * import { Buffer } from 'buffer'; + * + * const buf = Buffer.from([0, 0, 0, 5]); + * + * console.log(buf.readInt32LE(0)); + * // Prints: 83886080 + * console.log(buf.readInt32LE(1)); + * // Throws ERR_OUT_OF_RANGE. + * ``` + * @since v0.5.5 + * @param [offset=0] Number of bytes to skip before starting to read. Must satisfy `0 <= offset <= buf.length - 4`. + */ + readInt32LE(offset?: number): number; + /** + * Reads a signed, big-endian 32-bit integer from `buf` at the specified `offset`. + * + * Integers read from a `Buffer` are interpreted as two's complement signed values. + * + * ```js + * import { Buffer } from 'buffer'; + * + * const buf = Buffer.from([0, 0, 0, 5]); + * + * console.log(buf.readInt32BE(0)); + * // Prints: 5 + * ``` + * @since v0.5.5 + * @param [offset=0] Number of bytes to skip before starting to read. Must satisfy `0 <= offset <= buf.length - 4`. + */ + readInt32BE(offset?: number): number; + /** + * Reads a 32-bit, little-endian float from `buf` at the specified `offset`. + * + * ```js + * import { Buffer } from 'buffer'; + * + * const buf = Buffer.from([1, 2, 3, 4]); + * + * console.log(buf.readFloatLE(0)); + * // Prints: 1.539989614439558e-36 + * console.log(buf.readFloatLE(1)); + * // Throws ERR_OUT_OF_RANGE. + * ``` + * @since v0.11.15 + * @param [offset=0] Number of bytes to skip before starting to read. Must satisfy `0 <= offset <= buf.length - 4`. + */ + readFloatLE(offset?: number): number; + /** + * Reads a 32-bit, big-endian float from `buf` at the specified `offset`. + * + * ```js + * import { Buffer } from 'buffer'; + * + * const buf = Buffer.from([1, 2, 3, 4]); + * + * console.log(buf.readFloatBE(0)); + * // Prints: 2.387939260590663e-38 + * ``` + * @since v0.11.15 + * @param [offset=0] Number of bytes to skip before starting to read. Must satisfy `0 <= offset <= buf.length - 4`. + */ + readFloatBE(offset?: number): number; + /** + * Reads a 64-bit, little-endian double from `buf` at the specified `offset`. + * + * ```js + * import { Buffer } from 'buffer'; + * + * const buf = Buffer.from([1, 2, 3, 4, 5, 6, 7, 8]); + * + * console.log(buf.readDoubleLE(0)); + * // Prints: 5.447603722011605e-270 + * console.log(buf.readDoubleLE(1)); + * // Throws ERR_OUT_OF_RANGE. + * ``` + * @since v0.11.15 + * @param [offset=0] Number of bytes to skip before starting to read. Must satisfy `0 <= offset <= buf.length - 8`. + */ + readDoubleLE(offset?: number): number; + /** + * Reads a 64-bit, big-endian double from `buf` at the specified `offset`. + * + * ```js + * import { Buffer } from 'buffer'; + * + * const buf = Buffer.from([1, 2, 3, 4, 5, 6, 7, 8]); + * + * console.log(buf.readDoubleBE(0)); + * // Prints: 8.20788039913184e-304 + * ``` + * @since v0.11.15 + * @param [offset=0] Number of bytes to skip before starting to read. Must satisfy `0 <= offset <= buf.length - 8`. + */ + readDoubleBE(offset?: number): number; + reverse(): this; + /** + * Interprets `buf` as an array of unsigned 16-bit integers and swaps the + * byte order _in-place_. Throws `ERR_INVALID_BUFFER_SIZE` if `buf.length` is not a multiple of 2. + * + * ```js + * import { Buffer } from 'buffer'; + * + * const buf1 = Buffer.from([0x1, 0x2, 0x3, 0x4, 0x5, 0x6, 0x7, 0x8]); + * + * console.log(buf1); + * // Prints: + * + * buf1.swap16(); + * + * console.log(buf1); + * // Prints: + * + * const buf2 = Buffer.from([0x1, 0x2, 0x3]); + * + * buf2.swap16(); + * // Throws ERR_INVALID_BUFFER_SIZE. + * ``` + * + * One convenient use of `buf.swap16()` is to perform a fast in-place conversion + * between UTF-16 little-endian and UTF-16 big-endian: + * + * ```js + * import { Buffer } from 'buffer'; + * + * const buf = Buffer.from('This is little-endian UTF-16', 'utf16le'); + * buf.swap16(); // Convert to big-endian UTF-16 text. + * ``` + * @since v5.10.0 + * @return A reference to `buf`. + */ + swap16(): Buffer; + /** + * Interprets `buf` as an array of unsigned 32-bit integers and swaps the + * byte order _in-place_. Throws `ERR_INVALID_BUFFER_SIZE` if `buf.length` is not a multiple of 4. + * + * ```js + * import { Buffer } from 'buffer'; + * + * const buf1 = Buffer.from([0x1, 0x2, 0x3, 0x4, 0x5, 0x6, 0x7, 0x8]); + * + * console.log(buf1); + * // Prints: + * + * buf1.swap32(); + * + * console.log(buf1); + * // Prints: + * + * const buf2 = Buffer.from([0x1, 0x2, 0x3]); + * + * buf2.swap32(); + * // Throws ERR_INVALID_BUFFER_SIZE. + * ``` + * @since v5.10.0 + * @return A reference to `buf`. + */ + swap32(): Buffer; + /** + * Interprets `buf` as an array of 64-bit numbers and swaps byte order _in-place_. + * Throws `ERR_INVALID_BUFFER_SIZE` if `buf.length` is not a multiple of 8. + * + * ```js + * import { Buffer } from 'buffer'; + * + * const buf1 = Buffer.from([0x1, 0x2, 0x3, 0x4, 0x5, 0x6, 0x7, 0x8]); + * + * console.log(buf1); + * // Prints: + * + * buf1.swap64(); + * + * console.log(buf1); + * // Prints: + * + * const buf2 = Buffer.from([0x1, 0x2, 0x3]); + * + * buf2.swap64(); + * // Throws ERR_INVALID_BUFFER_SIZE. + * ``` + * @since v6.3.0 + * @return A reference to `buf`. + */ + swap64(): Buffer; + /** + * Writes `value` to `buf` at the specified `offset`. `value` must be a + * valid unsigned 8-bit integer. Behavior is undefined when `value` is anything + * other than an unsigned 8-bit integer. + * + * This function is also available under the `writeUint8` alias. + * + * ```js + * import { Buffer } from 'buffer'; + * + * const buf = Buffer.allocUnsafe(4); + * + * buf.writeUInt8(0x3, 0); + * buf.writeUInt8(0x4, 1); + * buf.writeUInt8(0x23, 2); + * buf.writeUInt8(0x42, 3); + * + * console.log(buf); + * // Prints: + * ``` + * @since v0.5.0 + * @param value Number to be written to `buf`. + * @param [offset=0] Number of bytes to skip before starting to write. Must satisfy `0 <= offset <= buf.length - 1`. + * @return `offset` plus the number of bytes written. + */ + writeUInt8(value: number, offset?: number): number; + /** + * @alias Buffer.writeUInt8 + * @since v14.9.0, v12.19.0 + */ + writeUint8(value: number, offset?: number): number; + /** + * Writes `value` to `buf` at the specified `offset` as little-endian. The `value`must be a valid unsigned 16-bit integer. Behavior is undefined when `value` is + * anything other than an unsigned 16-bit integer. + * + * This function is also available under the `writeUint16LE` alias. + * + * ```js + * import { Buffer } from 'buffer'; + * + * const buf = Buffer.allocUnsafe(4); + * + * buf.writeUInt16LE(0xdead, 0); + * buf.writeUInt16LE(0xbeef, 2); + * + * console.log(buf); + * // Prints: + * ``` + * @since v0.5.5 + * @param value Number to be written to `buf`. + * @param [offset=0] Number of bytes to skip before starting to write. Must satisfy `0 <= offset <= buf.length - 2`. + * @return `offset` plus the number of bytes written. + */ + writeUInt16LE(value: number, offset?: number): number; + /** + * @alias Buffer.writeUInt16LE + * @since v14.9.0, v12.19.0 + */ + writeUint16LE(value: number, offset?: number): number; + /** + * Writes `value` to `buf` at the specified `offset` as big-endian. The `value`must be a valid unsigned 16-bit integer. Behavior is undefined when `value`is anything other than an + * unsigned 16-bit integer. + * + * This function is also available under the `writeUint16BE` alias. + * + * ```js + * import { Buffer } from 'buffer'; + * + * const buf = Buffer.allocUnsafe(4); + * + * buf.writeUInt16BE(0xdead, 0); + * buf.writeUInt16BE(0xbeef, 2); + * + * console.log(buf); + * // Prints: + * ``` + * @since v0.5.5 + * @param value Number to be written to `buf`. + * @param [offset=0] Number of bytes to skip before starting to write. Must satisfy `0 <= offset <= buf.length - 2`. + * @return `offset` plus the number of bytes written. + */ + writeUInt16BE(value: number, offset?: number): number; + /** + * @alias Buffer.writeUInt16BE + * @since v14.9.0, v12.19.0 + */ + writeUint16BE(value: number, offset?: number): number; + /** + * Writes `value` to `buf` at the specified `offset` as little-endian. The `value`must be a valid unsigned 32-bit integer. Behavior is undefined when `value` is + * anything other than an unsigned 32-bit integer. + * + * This function is also available under the `writeUint32LE` alias. + * + * ```js + * import { Buffer } from 'buffer'; + * + * const buf = Buffer.allocUnsafe(4); + * + * buf.writeUInt32LE(0xfeedface, 0); + * + * console.log(buf); + * // Prints: + * ``` + * @since v0.5.5 + * @param value Number to be written to `buf`. + * @param [offset=0] Number of bytes to skip before starting to write. Must satisfy `0 <= offset <= buf.length - 4`. + * @return `offset` plus the number of bytes written. + */ + writeUInt32LE(value: number, offset?: number): number; + /** + * @alias Buffer.writeUInt32LE + * @since v14.9.0, v12.19.0 + */ + writeUint32LE(value: number, offset?: number): number; + /** + * Writes `value` to `buf` at the specified `offset` as big-endian. The `value`must be a valid unsigned 32-bit integer. Behavior is undefined when `value`is anything other than an + * unsigned 32-bit integer. + * + * This function is also available under the `writeUint32BE` alias. + * + * ```js + * import { Buffer } from 'buffer'; + * + * const buf = Buffer.allocUnsafe(4); + * + * buf.writeUInt32BE(0xfeedface, 0); + * + * console.log(buf); + * // Prints: + * ``` + * @since v0.5.5 + * @param value Number to be written to `buf`. + * @param [offset=0] Number of bytes to skip before starting to write. Must satisfy `0 <= offset <= buf.length - 4`. + * @return `offset` plus the number of bytes written. + */ + writeUInt32BE(value: number, offset?: number): number; + /** + * @alias Buffer.writeUInt32BE + * @since v14.9.0, v12.19.0 + */ + writeUint32BE(value: number, offset?: number): number; + /** + * Writes `value` to `buf` at the specified `offset`. `value` must be a valid + * signed 8-bit integer. Behavior is undefined when `value` is anything other than + * a signed 8-bit integer. + * + * `value` is interpreted and written as a two's complement signed integer. + * + * ```js + * import { Buffer } from 'buffer'; + * + * const buf = Buffer.allocUnsafe(2); + * + * buf.writeInt8(2, 0); + * buf.writeInt8(-2, 1); + * + * console.log(buf); + * // Prints: + * ``` + * @since v0.5.0 + * @param value Number to be written to `buf`. + * @param [offset=0] Number of bytes to skip before starting to write. Must satisfy `0 <= offset <= buf.length - 1`. + * @return `offset` plus the number of bytes written. + */ + writeInt8(value: number, offset?: number): number; + /** + * Writes `value` to `buf` at the specified `offset` as little-endian. The `value`must be a valid signed 16-bit integer. Behavior is undefined when `value` is + * anything other than a signed 16-bit integer. + * + * The `value` is interpreted and written as a two's complement signed integer. + * + * ```js + * import { Buffer } from 'buffer'; + * + * const buf = Buffer.allocUnsafe(2); + * + * buf.writeInt16LE(0x0304, 0); + * + * console.log(buf); + * // Prints: + * ``` + * @since v0.5.5 + * @param value Number to be written to `buf`. + * @param [offset=0] Number of bytes to skip before starting to write. Must satisfy `0 <= offset <= buf.length - 2`. + * @return `offset` plus the number of bytes written. + */ + writeInt16LE(value: number, offset?: number): number; + /** + * Writes `value` to `buf` at the specified `offset` as big-endian. The `value`must be a valid signed 16-bit integer. Behavior is undefined when `value` is + * anything other than a signed 16-bit integer. + * + * The `value` is interpreted and written as a two's complement signed integer. + * + * ```js + * import { Buffer } from 'buffer'; + * + * const buf = Buffer.allocUnsafe(2); + * + * buf.writeInt16BE(0x0102, 0); + * + * console.log(buf); + * // Prints: + * ``` + * @since v0.5.5 + * @param value Number to be written to `buf`. + * @param [offset=0] Number of bytes to skip before starting to write. Must satisfy `0 <= offset <= buf.length - 2`. + * @return `offset` plus the number of bytes written. + */ + writeInt16BE(value: number, offset?: number): number; + /** + * Writes `value` to `buf` at the specified `offset` as little-endian. The `value`must be a valid signed 32-bit integer. Behavior is undefined when `value` is + * anything other than a signed 32-bit integer. + * + * The `value` is interpreted and written as a two's complement signed integer. + * + * ```js + * import { Buffer } from 'buffer'; + * + * const buf = Buffer.allocUnsafe(4); + * + * buf.writeInt32LE(0x05060708, 0); + * + * console.log(buf); + * // Prints: + * ``` + * @since v0.5.5 + * @param value Number to be written to `buf`. + * @param [offset=0] Number of bytes to skip before starting to write. Must satisfy `0 <= offset <= buf.length - 4`. + * @return `offset` plus the number of bytes written. + */ + writeInt32LE(value: number, offset?: number): number; + /** + * Writes `value` to `buf` at the specified `offset` as big-endian. The `value`must be a valid signed 32-bit integer. Behavior is undefined when `value` is + * anything other than a signed 32-bit integer. + * + * The `value` is interpreted and written as a two's complement signed integer. + * + * ```js + * import { Buffer } from 'buffer'; + * + * const buf = Buffer.allocUnsafe(4); + * + * buf.writeInt32BE(0x01020304, 0); + * + * console.log(buf); + * // Prints: + * ``` + * @since v0.5.5 + * @param value Number to be written to `buf`. + * @param [offset=0] Number of bytes to skip before starting to write. Must satisfy `0 <= offset <= buf.length - 4`. + * @return `offset` plus the number of bytes written. + */ + writeInt32BE(value: number, offset?: number): number; + /** + * Writes `value` to `buf` at the specified `offset` as little-endian. Behavior is + * undefined when `value` is anything other than a JavaScript number. + * + * ```js + * import { Buffer } from 'buffer'; + * + * const buf = Buffer.allocUnsafe(4); + * + * buf.writeFloatLE(0xcafebabe, 0); + * + * console.log(buf); + * // Prints: + * ``` + * @since v0.11.15 + * @param value Number to be written to `buf`. + * @param [offset=0] Number of bytes to skip before starting to write. Must satisfy `0 <= offset <= buf.length - 4`. + * @return `offset` plus the number of bytes written. + */ + writeFloatLE(value: number, offset?: number): number; + /** + * Writes `value` to `buf` at the specified `offset` as big-endian. Behavior is + * undefined when `value` is anything other than a JavaScript number. + * + * ```js + * import { Buffer } from 'buffer'; + * + * const buf = Buffer.allocUnsafe(4); + * + * buf.writeFloatBE(0xcafebabe, 0); + * + * console.log(buf); + * // Prints: + * ``` + * @since v0.11.15 + * @param value Number to be written to `buf`. + * @param [offset=0] Number of bytes to skip before starting to write. Must satisfy `0 <= offset <= buf.length - 4`. + * @return `offset` plus the number of bytes written. + */ + writeFloatBE(value: number, offset?: number): number; + /** + * Writes `value` to `buf` at the specified `offset` as little-endian. The `value`must be a JavaScript number. Behavior is undefined when `value` is anything + * other than a JavaScript number. + * + * ```js + * import { Buffer } from 'buffer'; + * + * const buf = Buffer.allocUnsafe(8); + * + * buf.writeDoubleLE(123.456, 0); + * + * console.log(buf); + * // Prints: + * ``` + * @since v0.11.15 + * @param value Number to be written to `buf`. + * @param [offset=0] Number of bytes to skip before starting to write. Must satisfy `0 <= offset <= buf.length - 8`. + * @return `offset` plus the number of bytes written. + */ + writeDoubleLE(value: number, offset?: number): number; + /** + * Writes `value` to `buf` at the specified `offset` as big-endian. The `value`must be a JavaScript number. Behavior is undefined when `value` is anything + * other than a JavaScript number. + * + * ```js + * import { Buffer } from 'buffer'; + * + * const buf = Buffer.allocUnsafe(8); + * + * buf.writeDoubleBE(123.456, 0); + * + * console.log(buf); + * // Prints: + * ``` + * @since v0.11.15 + * @param value Number to be written to `buf`. + * @param [offset=0] Number of bytes to skip before starting to write. Must satisfy `0 <= offset <= buf.length - 8`. + * @return `offset` plus the number of bytes written. + */ + writeDoubleBE(value: number, offset?: number): number; + /** + * Fills `buf` with the specified `value`. If the `offset` and `end` are not given, + * the entire `buf` will be filled: + * + * ```js + * import { Buffer } from 'buffer'; + * + * // Fill a `Buffer` with the ASCII character 'h'. + * + * const b = Buffer.allocUnsafe(50).fill('h'); + * + * console.log(b.toString()); + * // Prints: hhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhh + * ``` + * + * `value` is coerced to a `uint32` value if it is not a string, `Buffer`, or + * integer. If the resulting integer is greater than `255` (decimal), `buf` will be + * filled with `value & 255`. + * + * If the final write of a `fill()` operation falls on a multi-byte character, + * then only the bytes of that character that fit into `buf` are written: + * + * ```js + * import { Buffer } from 'buffer'; + * + * // Fill a `Buffer` with character that takes up two bytes in UTF-8. + * + * console.log(Buffer.allocUnsafe(5).fill('\u0222')); + * // Prints: + * ``` + * + * If `value` contains invalid characters, it is truncated; if no valid + * fill data remains, an exception is thrown: + * + * ```js + * import { Buffer } from 'buffer'; + * + * const buf = Buffer.allocUnsafe(5); + * + * console.log(buf.fill('a')); + * // Prints: + * console.log(buf.fill('aazz', 'hex')); + * // Prints: + * console.log(buf.fill('zz', 'hex')); + * // Throws an exception. + * ``` + * @since v0.5.0 + * @param value The value with which to fill `buf`. + * @param [offset=0] Number of bytes to skip before starting to fill `buf`. + * @param [end=buf.length] Where to stop filling `buf` (not inclusive). + * @param [encoding='utf8'] The encoding for `value` if `value` is a string. + * @return A reference to `buf`. + */ + fill(value: string | Uint8Array | number, offset?: number, end?: number, encoding?: BufferEncoding): this; + /** + * If `value` is: + * + * * a string, `value` is interpreted according to the character encoding in`encoding`. + * * a `Buffer` or [`Uint8Array`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Uint8Array), `value` will be used in its entirety. + * To compare a partial `Buffer`, use `buf.subarray`. + * * a number, `value` will be interpreted as an unsigned 8-bit integer + * value between `0` and `255`. + * + * ```js + * import { Buffer } from 'buffer'; + * + * const buf = Buffer.from('this is a buffer'); + * + * console.log(buf.indexOf('this')); + * // Prints: 0 + * console.log(buf.indexOf('is')); + * // Prints: 2 + * console.log(buf.indexOf(Buffer.from('a buffer'))); + * // Prints: 8 + * console.log(buf.indexOf(97)); + * // Prints: 8 (97 is the decimal ASCII value for 'a') + * console.log(buf.indexOf(Buffer.from('a buffer example'))); + * // Prints: -1 + * console.log(buf.indexOf(Buffer.from('a buffer example').slice(0, 8))); + * // Prints: 8 + * + * const utf16Buffer = Buffer.from('\u039a\u0391\u03a3\u03a3\u0395', 'utf16le'); + * + * console.log(utf16Buffer.indexOf('\u03a3', 0, 'utf16le')); + * // Prints: 4 + * console.log(utf16Buffer.indexOf('\u03a3', -4, 'utf16le')); + * // Prints: 6 + * ``` + * + * If `value` is not a string, number, or `Buffer`, this method will throw a`TypeError`. If `value` is a number, it will be coerced to a valid byte value, + * an integer between 0 and 255. + * + * If `byteOffset` is not a number, it will be coerced to a number. If the result + * of coercion is `NaN` or `0`, then the entire buffer will be searched. This + * behavior matches [`String.prototype.indexOf()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/indexOf). + * + * ```js + * import { Buffer } from 'buffer'; + * + * const b = Buffer.from('abcdef'); + * + * // Passing a value that's a number, but not a valid byte. + * // Prints: 2, equivalent to searching for 99 or 'c'. + * console.log(b.indexOf(99.9)); + * console.log(b.indexOf(256 + 99)); + * + * // Passing a byteOffset that coerces to NaN or 0. + * // Prints: 1, searching the whole buffer. + * console.log(b.indexOf('b', undefined)); + * console.log(b.indexOf('b', {})); + * console.log(b.indexOf('b', null)); + * console.log(b.indexOf('b', [])); + * ``` + * + * If `value` is an empty string or empty `Buffer` and `byteOffset` is less + * than `buf.length`, `byteOffset` will be returned. If `value` is empty and`byteOffset` is at least `buf.length`, `buf.length` will be returned. + * @since v1.5.0 + * @param value What to search for. + * @param [byteOffset=0] Where to begin searching in `buf`. If negative, then offset is calculated from the end of `buf`. + * @param [encoding='utf8'] If `value` is a string, this is the encoding used to determine the binary representation of the string that will be searched for in `buf`. + * @return The index of the first occurrence of `value` in `buf`, or `-1` if `buf` does not contain `value`. + */ + indexOf(value: string | number | Uint8Array, byteOffset?: number, encoding?: BufferEncoding): number; + /** + * Identical to `buf.indexOf()`, except the last occurrence of `value` is found + * rather than the first occurrence. + * + * ```js + * import { Buffer } from 'buffer'; + * + * const buf = Buffer.from('this buffer is a buffer'); + * + * console.log(buf.lastIndexOf('this')); + * // Prints: 0 + * console.log(buf.lastIndexOf('buffer')); + * // Prints: 17 + * console.log(buf.lastIndexOf(Buffer.from('buffer'))); + * // Prints: 17 + * console.log(buf.lastIndexOf(97)); + * // Prints: 15 (97 is the decimal ASCII value for 'a') + * console.log(buf.lastIndexOf(Buffer.from('yolo'))); + * // Prints: -1 + * console.log(buf.lastIndexOf('buffer', 5)); + * // Prints: 5 + * console.log(buf.lastIndexOf('buffer', 4)); + * // Prints: -1 + * + * const utf16Buffer = Buffer.from('\u039a\u0391\u03a3\u03a3\u0395', 'utf16le'); + * + * console.log(utf16Buffer.lastIndexOf('\u03a3', undefined, 'utf16le')); + * // Prints: 6 + * console.log(utf16Buffer.lastIndexOf('\u03a3', -5, 'utf16le')); + * // Prints: 4 + * ``` + * + * If `value` is not a string, number, or `Buffer`, this method will throw a`TypeError`. If `value` is a number, it will be coerced to a valid byte value, + * an integer between 0 and 255. + * + * If `byteOffset` is not a number, it will be coerced to a number. Any arguments + * that coerce to `NaN`, like `{}` or `undefined`, will search the whole buffer. + * This behavior matches [`String.prototype.lastIndexOf()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/lastIndexOf). + * + * ```js + * import { Buffer } from 'buffer'; + * + * const b = Buffer.from('abcdef'); + * + * // Passing a value that's a number, but not a valid byte. + * // Prints: 2, equivalent to searching for 99 or 'c'. + * console.log(b.lastIndexOf(99.9)); + * console.log(b.lastIndexOf(256 + 99)); + * + * // Passing a byteOffset that coerces to NaN. + * // Prints: 1, searching the whole buffer. + * console.log(b.lastIndexOf('b', undefined)); + * console.log(b.lastIndexOf('b', {})); + * + * // Passing a byteOffset that coerces to 0. + * // Prints: -1, equivalent to passing 0. + * console.log(b.lastIndexOf('b', null)); + * console.log(b.lastIndexOf('b', [])); + * ``` + * + * If `value` is an empty string or empty `Buffer`, `byteOffset` will be returned. + * @since v6.0.0 + * @param value What to search for. + * @param [byteOffset=buf.length - 1] Where to begin searching in `buf`. If negative, then offset is calculated from the end of `buf`. + * @param [encoding='utf8'] If `value` is a string, this is the encoding used to determine the binary representation of the string that will be searched for in `buf`. + * @return The index of the last occurrence of `value` in `buf`, or `-1` if `buf` does not contain `value`. + */ + lastIndexOf(value: string | number | Uint8Array, byteOffset?: number, encoding?: BufferEncoding): number; + /** + * Creates and returns an [iterator](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols) of `[index, byte]` pairs from the contents + * of `buf`. + * + * ```js + * import { Buffer } from 'buffer'; + * + * // Log the entire contents of a `Buffer`. + * + * const buf = Buffer.from('buffer'); + * + * for (const pair of buf.entries()) { + * console.log(pair); + * } + * // Prints: + * // [0, 98] + * // [1, 117] + * // [2, 102] + * // [3, 102] + * // [4, 101] + * // [5, 114] + * ``` + * @since v1.1.0 + */ + entries(): IterableIterator<[number, number]>; + /** + * Equivalent to `buf.indexOf() !== -1`. + * + * ```js + * import { Buffer } from 'buffer'; + * + * const buf = Buffer.from('this is a buffer'); + * + * console.log(buf.includes('this')); + * // Prints: true + * console.log(buf.includes('is')); + * // Prints: true + * console.log(buf.includes(Buffer.from('a buffer'))); + * // Prints: true + * console.log(buf.includes(97)); + * // Prints: true (97 is the decimal ASCII value for 'a') + * console.log(buf.includes(Buffer.from('a buffer example'))); + * // Prints: false + * console.log(buf.includes(Buffer.from('a buffer example').slice(0, 8))); + * // Prints: true + * console.log(buf.includes('this', 4)); + * // Prints: false + * ``` + * @since v5.3.0 + * @param value What to search for. + * @param [byteOffset=0] Where to begin searching in `buf`. If negative, then offset is calculated from the end of `buf`. + * @param [encoding='utf8'] If `value` is a string, this is its encoding. + * @return `true` if `value` was found in `buf`, `false` otherwise. + */ + includes(value: string | number | Buffer, byteOffset?: number, encoding?: BufferEncoding): boolean; + /** + * Creates and returns an [iterator](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols) of `buf` keys (indices). + * + * ```js + * import { Buffer } from 'buffer'; + * + * const buf = Buffer.from('buffer'); + * + * for (const key of buf.keys()) { + * console.log(key); + * } + * // Prints: + * // 0 + * // 1 + * // 2 + * // 3 + * // 4 + * // 5 + * ``` + * @since v1.1.0 + */ + keys(): IterableIterator; + /** + * Creates and returns an [iterator](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols) for `buf` values (bytes). This function is + * called automatically when a `Buffer` is used in a `for..of` statement. + * + * ```js + * import { Buffer } from 'buffer'; + * + * const buf = Buffer.from('buffer'); + * + * for (const value of buf.values()) { + * console.log(value); + * } + * // Prints: + * // 98 + * // 117 + * // 102 + * // 102 + * // 101 + * // 114 + * + * for (const value of buf) { + * console.log(value); + * } + * // Prints: + * // 98 + * // 117 + * // 102 + * // 102 + * // 101 + * // 114 + * ``` + * @since v1.1.0 + */ + values(): IterableIterator; + } + var Buffer: BufferConstructor; + /** + * Decodes a string of Base64-encoded data into bytes, and encodes those bytes + * into a string using Latin-1 (ISO-8859-1). + * + * The `data` may be any JavaScript-value that can be coerced into a string. + * + * **This function is only provided for compatibility with legacy web platform APIs** + * **and should never be used in new code, because they use strings to represent** + * **binary data and predate the introduction of typed arrays in JavaScript.** + * **For code running using Node.js APIs, converting between base64-encoded strings** + * **and binary data should be performed using `Buffer.from(str, 'base64')` and`buf.toString('base64')`.** + * @since v15.13.0, v14.17.0 + * @deprecated Use `Buffer.from(data, 'base64')` instead. + * @param data The Base64-encoded input string. + */ + function atob(data: string): string; + /** + * Decodes a string into bytes using Latin-1 (ISO-8859), and encodes those bytes + * into a string using Base64. + * + * The `data` may be any JavaScript-value that can be coerced into a string. + * + * **This function is only provided for compatibility with legacy web platform APIs** + * **and should never be used in new code, because they use strings to represent** + * **binary data and predate the introduction of typed arrays in JavaScript.** + * **For code running using Node.js APIs, converting between base64-encoded strings** + * **and binary data should be performed using `Buffer.from(str, 'base64')` and`buf.toString('base64')`.** + * @since v15.13.0, v14.17.0 + * @deprecated Use `buf.toString('base64')` instead. + * @param data An ASCII (Latin1) string. + */ + function btoa(data: string): string; + } +} +declare module 'node:buffer' { + export * from 'buffer'; +} diff --git a/ts-ticket-office-service/node_modules/@types/node/child_process.d.ts b/ts-ticket-office-service/node_modules/@types/node/child_process.d.ts new file mode 100755 index 000000000..79c7290e0 --- /dev/null +++ b/ts-ticket-office-service/node_modules/@types/node/child_process.d.ts @@ -0,0 +1,1369 @@ +/** + * The `child_process` module provides the ability to spawn subprocesses in + * a manner that is similar, but not identical, to [`popen(3)`](http://man7.org/linux/man-pages/man3/popen.3.html). This capability + * is primarily provided by the {@link spawn} function: + * + * ```js + * const { spawn } = require('child_process'); + * const ls = spawn('ls', ['-lh', '/usr']); + * + * ls.stdout.on('data', (data) => { + * console.log(`stdout: ${data}`); + * }); + * + * ls.stderr.on('data', (data) => { + * console.error(`stderr: ${data}`); + * }); + * + * ls.on('close', (code) => { + * console.log(`child process exited with code ${code}`); + * }); + * ``` + * + * By default, pipes for `stdin`, `stdout`, and `stderr` are established between + * the parent Node.js process and the spawned subprocess. These pipes have + * limited (and platform-specific) capacity. If the subprocess writes to + * stdout in excess of that limit without the output being captured, the + * subprocess blocks waiting for the pipe buffer to accept more data. This is + * identical to the behavior of pipes in the shell. Use the `{ stdio: 'ignore' }`option if the output will not be consumed. + * + * The command lookup is performed using the `options.env.PATH` environment + * variable if `env` is in the `options` object. Otherwise, `process.env.PATH` is + * used. If `options.env` is set without `PATH`, lookup on Unix is performed + * on a default search path search of `/usr/bin:/bin` (see your operating system's + * manual for execvpe/execvp), on Windows the current processes environment + * variable `PATH` is used. + * + * On Windows, environment variables are case-insensitive. Node.js + * lexicographically sorts the `env` keys and uses the first one that + * case-insensitively matches. Only first (in lexicographic order) entry will be + * passed to the subprocess. This might lead to issues on Windows when passing + * objects to the `env` option that have multiple variants of the same key, such as`PATH` and `Path`. + * + * The {@link spawn} method spawns the child process asynchronously, + * without blocking the Node.js event loop. The {@link spawnSync} function provides equivalent functionality in a synchronous manner that blocks + * the event loop until the spawned process either exits or is terminated. + * + * For convenience, the `child_process` module provides a handful of synchronous + * and asynchronous alternatives to {@link spawn} and {@link spawnSync}. Each of these alternatives are implemented on + * top of {@link spawn} or {@link spawnSync}. + * + * * {@link exec}: spawns a shell and runs a command within that + * shell, passing the `stdout` and `stderr` to a callback function when + * complete. + * * {@link execFile}: similar to {@link exec} except + * that it spawns the command directly without first spawning a shell by + * default. + * * {@link fork}: spawns a new Node.js process and invokes a + * specified module with an IPC communication channel established that allows + * sending messages between parent and child. + * * {@link execSync}: a synchronous version of {@link exec} that will block the Node.js event loop. + * * {@link execFileSync}: a synchronous version of {@link execFile} that will block the Node.js event loop. + * + * For certain use cases, such as automating shell scripts, the `synchronous counterparts` may be more convenient. In many cases, however, + * the synchronous methods can have significant impact on performance due to + * stalling the event loop while spawned processes complete. + * @see [source](https://github.com/nodejs/node/blob/v18.0.0/lib/child_process.js) + */ +declare module 'child_process' { + import { ObjectEncodingOptions } from 'node:fs'; + import { EventEmitter, Abortable } from 'node:events'; + import * as net from 'node:net'; + import { Writable, Readable, Stream, Pipe } from 'node:stream'; + import { URL } from 'node:url'; + type Serializable = string | object | number | boolean | bigint; + type SendHandle = net.Socket | net.Server; + /** + * Instances of the `ChildProcess` represent spawned child processes. + * + * Instances of `ChildProcess` are not intended to be created directly. Rather, + * use the {@link spawn}, {@link exec},{@link execFile}, or {@link fork} methods to create + * instances of `ChildProcess`. + * @since v2.2.0 + */ + class ChildProcess extends EventEmitter { + /** + * A `Writable Stream` that represents the child process's `stdin`. + * + * If a child process waits to read all of its input, the child will not continue + * until this stream has been closed via `end()`. + * + * If the child was spawned with `stdio[0]` set to anything other than `'pipe'`, + * then this will be `null`. + * + * `subprocess.stdin` is an alias for `subprocess.stdio[0]`. Both properties will + * refer to the same value. + * + * The `subprocess.stdin` property can be `undefined` if the child process could + * not be successfully spawned. + * @since v0.1.90 + */ + stdin: Writable | null; + /** + * A `Readable Stream` that represents the child process's `stdout`. + * + * If the child was spawned with `stdio[1]` set to anything other than `'pipe'`, + * then this will be `null`. + * + * `subprocess.stdout` is an alias for `subprocess.stdio[1]`. Both properties will + * refer to the same value. + * + * ```js + * const { spawn } = require('child_process'); + * + * const subprocess = spawn('ls'); + * + * subprocess.stdout.on('data', (data) => { + * console.log(`Received chunk ${data}`); + * }); + * ``` + * + * The `subprocess.stdout` property can be `null` if the child process could + * not be successfully spawned. + * @since v0.1.90 + */ + stdout: Readable | null; + /** + * A `Readable Stream` that represents the child process's `stderr`. + * + * If the child was spawned with `stdio[2]` set to anything other than `'pipe'`, + * then this will be `null`. + * + * `subprocess.stderr` is an alias for `subprocess.stdio[2]`. Both properties will + * refer to the same value. + * + * The `subprocess.stderr` property can be `null` if the child process could + * not be successfully spawned. + * @since v0.1.90 + */ + stderr: Readable | null; + /** + * The `subprocess.channel` property is a reference to the child's IPC channel. If + * no IPC channel currently exists, this property is `undefined`. + * @since v7.1.0 + */ + readonly channel?: Pipe | null | undefined; + /** + * A sparse array of pipes to the child process, corresponding with positions in + * the `stdio` option passed to {@link spawn} that have been set + * to the value `'pipe'`. `subprocess.stdio[0]`, `subprocess.stdio[1]`, and`subprocess.stdio[2]` are also available as `subprocess.stdin`,`subprocess.stdout`, and `subprocess.stderr`, + * respectively. + * + * In the following example, only the child's fd `1` (stdout) is configured as a + * pipe, so only the parent's `subprocess.stdio[1]` is a stream, all other values + * in the array are `null`. + * + * ```js + * const assert = require('assert'); + * const fs = require('fs'); + * const child_process = require('child_process'); + * + * const subprocess = child_process.spawn('ls', { + * stdio: [ + * 0, // Use parent's stdin for child. + * 'pipe', // Pipe child's stdout to parent. + * fs.openSync('err.out', 'w'), // Direct child's stderr to a file. + * ] + * }); + * + * assert.strictEqual(subprocess.stdio[0], null); + * assert.strictEqual(subprocess.stdio[0], subprocess.stdin); + * + * assert(subprocess.stdout); + * assert.strictEqual(subprocess.stdio[1], subprocess.stdout); + * + * assert.strictEqual(subprocess.stdio[2], null); + * assert.strictEqual(subprocess.stdio[2], subprocess.stderr); + * ``` + * + * The `subprocess.stdio` property can be `undefined` if the child process could + * not be successfully spawned. + * @since v0.7.10 + */ + readonly stdio: [ + Writable | null, + // stdin + Readable | null, + // stdout + Readable | null, + // stderr + Readable | Writable | null | undefined, + // extra + Readable | Writable | null | undefined // extra + ]; + /** + * The `subprocess.killed` property indicates whether the child process + * successfully received a signal from `subprocess.kill()`. The `killed` property + * does not indicate that the child process has been terminated. + * @since v0.5.10 + */ + readonly killed: boolean; + /** + * Returns the process identifier (PID) of the child process. If the child process + * fails to spawn due to errors, then the value is `undefined` and `error` is + * emitted. + * + * ```js + * const { spawn } = require('child_process'); + * const grep = spawn('grep', ['ssh']); + * + * console.log(`Spawned child pid: ${grep.pid}`); + * grep.stdin.end(); + * ``` + * @since v0.1.90 + */ + readonly pid?: number | undefined; + /** + * The `subprocess.connected` property indicates whether it is still possible to + * send and receive messages from a child process. When `subprocess.connected` is`false`, it is no longer possible to send or receive messages. + * @since v0.7.2 + */ + readonly connected: boolean; + /** + * The `subprocess.exitCode` property indicates the exit code of the child process. + * If the child process is still running, the field will be `null`. + */ + readonly exitCode: number | null; + /** + * The `subprocess.signalCode` property indicates the signal received by + * the child process if any, else `null`. + */ + readonly signalCode: NodeJS.Signals | null; + /** + * The `subprocess.spawnargs` property represents the full list of command-line + * arguments the child process was launched with. + */ + readonly spawnargs: string[]; + /** + * The `subprocess.spawnfile` property indicates the executable file name of + * the child process that is launched. + * + * For {@link fork}, its value will be equal to `process.execPath`. + * For {@link spawn}, its value will be the name of + * the executable file. + * For {@link exec}, its value will be the name of the shell + * in which the child process is launched. + */ + readonly spawnfile: string; + /** + * The `subprocess.kill()` method sends a signal to the child process. If no + * argument is given, the process will be sent the `'SIGTERM'` signal. See [`signal(7)`](http://man7.org/linux/man-pages/man7/signal.7.html) for a list of available signals. This function + * returns `true` if [`kill(2)`](http://man7.org/linux/man-pages/man2/kill.2.html) succeeds, and `false` otherwise. + * + * ```js + * const { spawn } = require('child_process'); + * const grep = spawn('grep', ['ssh']); + * + * grep.on('close', (code, signal) => { + * console.log( + * `child process terminated due to receipt of signal ${signal}`); + * }); + * + * // Send SIGHUP to process. + * grep.kill('SIGHUP'); + * ``` + * + * The `ChildProcess` object may emit an `'error'` event if the signal + * cannot be delivered. Sending a signal to a child process that has already exited + * is not an error but may have unforeseen consequences. Specifically, if the + * process identifier (PID) has been reassigned to another process, the signal will + * be delivered to that process instead which can have unexpected results. + * + * While the function is called `kill`, the signal delivered to the child process + * may not actually terminate the process. + * + * See [`kill(2)`](http://man7.org/linux/man-pages/man2/kill.2.html) for reference. + * + * On Windows, where POSIX signals do not exist, the `signal` argument will be + * ignored, and the process will be killed forcefully and abruptly (similar to`'SIGKILL'`). + * See `Signal Events` for more details. + * + * On Linux, child processes of child processes will not be terminated + * when attempting to kill their parent. This is likely to happen when running a + * new process in a shell or with the use of the `shell` option of `ChildProcess`: + * + * ```js + * 'use strict'; + * const { spawn } = require('child_process'); + * + * const subprocess = spawn( + * 'sh', + * [ + * '-c', + * `node -e "setInterval(() => { + * console.log(process.pid, 'is alive') + * }, 500);"`, + * ], { + * stdio: ['inherit', 'inherit', 'inherit'] + * } + * ); + * + * setTimeout(() => { + * subprocess.kill(); // Does not terminate the Node.js process in the shell. + * }, 2000); + * ``` + * @since v0.1.90 + */ + kill(signal?: NodeJS.Signals | number): boolean; + /** + * When an IPC channel has been established between the parent and child ( + * i.e. when using {@link fork}), the `subprocess.send()` method can + * be used to send messages to the child process. When the child process is a + * Node.js instance, these messages can be received via the `'message'` event. + * + * The message goes through serialization and parsing. The resulting + * message might not be the same as what is originally sent. + * + * For example, in the parent script: + * + * ```js + * const cp = require('child_process'); + * const n = cp.fork(`${__dirname}/sub.js`); + * + * n.on('message', (m) => { + * console.log('PARENT got message:', m); + * }); + * + * // Causes the child to print: CHILD got message: { hello: 'world' } + * n.send({ hello: 'world' }); + * ``` + * + * And then the child script, `'sub.js'` might look like this: + * + * ```js + * process.on('message', (m) => { + * console.log('CHILD got message:', m); + * }); + * + * // Causes the parent to print: PARENT got message: { foo: 'bar', baz: null } + * process.send({ foo: 'bar', baz: NaN }); + * ``` + * + * Child Node.js processes will have a `process.send()` method of their own + * that allows the child to send messages back to the parent. + * + * There is a special case when sending a `{cmd: 'NODE_foo'}` message. Messages + * containing a `NODE_` prefix in the `cmd` property are reserved for use within + * Node.js core and will not be emitted in the child's `'message'` event. Rather, such messages are emitted using the`'internalMessage'` event and are consumed internally by Node.js. + * Applications should avoid using such messages or listening for`'internalMessage'` events as it is subject to change without notice. + * + * The optional `sendHandle` argument that may be passed to `subprocess.send()` is + * for passing a TCP server or socket object to the child process. The child will + * receive the object as the second argument passed to the callback function + * registered on the `'message'` event. Any data that is received + * and buffered in the socket will not be sent to the child. + * + * The optional `callback` is a function that is invoked after the message is + * sent but before the child may have received it. The function is called with a + * single argument: `null` on success, or an `Error` object on failure. + * + * If no `callback` function is provided and the message cannot be sent, an`'error'` event will be emitted by the `ChildProcess` object. This can + * happen, for instance, when the child process has already exited. + * + * `subprocess.send()` will return `false` if the channel has closed or when the + * backlog of unsent messages exceeds a threshold that makes it unwise to send + * more. Otherwise, the method returns `true`. The `callback` function can be + * used to implement flow control. + * + * #### Example: sending a server object + * + * The `sendHandle` argument can be used, for instance, to pass the handle of + * a TCP server object to the child process as illustrated in the example below: + * + * ```js + * const subprocess = require('child_process').fork('subprocess.js'); + * + * // Open up the server object and send the handle. + * const server = require('net').createServer(); + * server.on('connection', (socket) => { + * socket.end('handled by parent'); + * }); + * server.listen(1337, () => { + * subprocess.send('server', server); + * }); + * ``` + * + * The child would then receive the server object as: + * + * ```js + * process.on('message', (m, server) => { + * if (m === 'server') { + * server.on('connection', (socket) => { + * socket.end('handled by child'); + * }); + * } + * }); + * ``` + * + * Once the server is now shared between the parent and child, some connections + * can be handled by the parent and some by the child. + * + * While the example above uses a server created using the `net` module, `dgram`module servers use exactly the same workflow with the exceptions of listening on + * a `'message'` event instead of `'connection'` and using `server.bind()` instead + * of `server.listen()`. This is, however, currently only supported on Unix + * platforms. + * + * #### Example: sending a socket object + * + * Similarly, the `sendHandler` argument can be used to pass the handle of a + * socket to the child process. The example below spawns two children that each + * handle connections with "normal" or "special" priority: + * + * ```js + * const { fork } = require('child_process'); + * const normal = fork('subprocess.js', ['normal']); + * const special = fork('subprocess.js', ['special']); + * + * // Open up the server and send sockets to child. Use pauseOnConnect to prevent + * // the sockets from being read before they are sent to the child process. + * const server = require('net').createServer({ pauseOnConnect: true }); + * server.on('connection', (socket) => { + * + * // If this is special priority... + * if (socket.remoteAddress === '74.125.127.100') { + * special.send('socket', socket); + * return; + * } + * // This is normal priority. + * normal.send('socket', socket); + * }); + * server.listen(1337); + * ``` + * + * The `subprocess.js` would receive the socket handle as the second argument + * passed to the event callback function: + * + * ```js + * process.on('message', (m, socket) => { + * if (m === 'socket') { + * if (socket) { + * // Check that the client socket exists. + * // It is possible for the socket to be closed between the time it is + * // sent and the time it is received in the child process. + * socket.end(`Request handled with ${process.argv[2]} priority`); + * } + * } + * }); + * ``` + * + * Do not use `.maxConnections` on a socket that has been passed to a subprocess. + * The parent cannot track when the socket is destroyed. + * + * Any `'message'` handlers in the subprocess should verify that `socket` exists, + * as the connection may have been closed during the time it takes to send the + * connection to the child. + * @since v0.5.9 + * @param options The `options` argument, if present, is an object used to parameterize the sending of certain types of handles. `options` supports the following properties: + */ + send(message: Serializable, callback?: (error: Error | null) => void): boolean; + send(message: Serializable, sendHandle?: SendHandle, callback?: (error: Error | null) => void): boolean; + send(message: Serializable, sendHandle?: SendHandle, options?: MessageOptions, callback?: (error: Error | null) => void): boolean; + /** + * Closes the IPC channel between parent and child, allowing the child to exit + * gracefully once there are no other connections keeping it alive. After calling + * this method the `subprocess.connected` and `process.connected` properties in + * both the parent and child (respectively) will be set to `false`, and it will be + * no longer possible to pass messages between the processes. + * + * The `'disconnect'` event will be emitted when there are no messages in the + * process of being received. This will most often be triggered immediately after + * calling `subprocess.disconnect()`. + * + * When the child process is a Node.js instance (e.g. spawned using {@link fork}), the `process.disconnect()` method can be invoked + * within the child process to close the IPC channel as well. + * @since v0.7.2 + */ + disconnect(): void; + /** + * By default, the parent will wait for the detached child to exit. To prevent the + * parent from waiting for a given `subprocess` to exit, use the`subprocess.unref()` method. Doing so will cause the parent's event loop to not + * include the child in its reference count, allowing the parent to exit + * independently of the child, unless there is an established IPC channel between + * the child and the parent. + * + * ```js + * const { spawn } = require('child_process'); + * + * const subprocess = spawn(process.argv[0], ['child_program.js'], { + * detached: true, + * stdio: 'ignore' + * }); + * + * subprocess.unref(); + * ``` + * @since v0.7.10 + */ + unref(): void; + /** + * Calling `subprocess.ref()` after making a call to `subprocess.unref()` will + * restore the removed reference count for the child process, forcing the parent + * to wait for the child to exit before exiting itself. + * + * ```js + * const { spawn } = require('child_process'); + * + * const subprocess = spawn(process.argv[0], ['child_program.js'], { + * detached: true, + * stdio: 'ignore' + * }); + * + * subprocess.unref(); + * subprocess.ref(); + * ``` + * @since v0.7.10 + */ + ref(): void; + /** + * events.EventEmitter + * 1. close + * 2. disconnect + * 3. error + * 4. exit + * 5. message + * 6. spawn + */ + addListener(event: string, listener: (...args: any[]) => void): this; + addListener(event: 'close', listener: (code: number | null, signal: NodeJS.Signals | null) => void): this; + addListener(event: 'disconnect', listener: () => void): this; + addListener(event: 'error', listener: (err: Error) => void): this; + addListener(event: 'exit', listener: (code: number | null, signal: NodeJS.Signals | null) => void): this; + addListener(event: 'message', listener: (message: Serializable, sendHandle: SendHandle) => void): this; + addListener(event: 'spawn', listener: () => void): this; + emit(event: string | symbol, ...args: any[]): boolean; + emit(event: 'close', code: number | null, signal: NodeJS.Signals | null): boolean; + emit(event: 'disconnect'): boolean; + emit(event: 'error', err: Error): boolean; + emit(event: 'exit', code: number | null, signal: NodeJS.Signals | null): boolean; + emit(event: 'message', message: Serializable, sendHandle: SendHandle): boolean; + emit(event: 'spawn', listener: () => void): boolean; + on(event: string, listener: (...args: any[]) => void): this; + on(event: 'close', listener: (code: number | null, signal: NodeJS.Signals | null) => void): this; + on(event: 'disconnect', listener: () => void): this; + on(event: 'error', listener: (err: Error) => void): this; + on(event: 'exit', listener: (code: number | null, signal: NodeJS.Signals | null) => void): this; + on(event: 'message', listener: (message: Serializable, sendHandle: SendHandle) => void): this; + on(event: 'spawn', listener: () => void): this; + once(event: string, listener: (...args: any[]) => void): this; + once(event: 'close', listener: (code: number | null, signal: NodeJS.Signals | null) => void): this; + once(event: 'disconnect', listener: () => void): this; + once(event: 'error', listener: (err: Error) => void): this; + once(event: 'exit', listener: (code: number | null, signal: NodeJS.Signals | null) => void): this; + once(event: 'message', listener: (message: Serializable, sendHandle: SendHandle) => void): this; + once(event: 'spawn', listener: () => void): this; + prependListener(event: string, listener: (...args: any[]) => void): this; + prependListener(event: 'close', listener: (code: number | null, signal: NodeJS.Signals | null) => void): this; + prependListener(event: 'disconnect', listener: () => void): this; + prependListener(event: 'error', listener: (err: Error) => void): this; + prependListener(event: 'exit', listener: (code: number | null, signal: NodeJS.Signals | null) => void): this; + prependListener(event: 'message', listener: (message: Serializable, sendHandle: SendHandle) => void): this; + prependListener(event: 'spawn', listener: () => void): this; + prependOnceListener(event: string, listener: (...args: any[]) => void): this; + prependOnceListener(event: 'close', listener: (code: number | null, signal: NodeJS.Signals | null) => void): this; + prependOnceListener(event: 'disconnect', listener: () => void): this; + prependOnceListener(event: 'error', listener: (err: Error) => void): this; + prependOnceListener(event: 'exit', listener: (code: number | null, signal: NodeJS.Signals | null) => void): this; + prependOnceListener(event: 'message', listener: (message: Serializable, sendHandle: SendHandle) => void): this; + prependOnceListener(event: 'spawn', listener: () => void): this; + } + // return this object when stdio option is undefined or not specified + interface ChildProcessWithoutNullStreams extends ChildProcess { + stdin: Writable; + stdout: Readable; + stderr: Readable; + readonly stdio: [ + Writable, + Readable, + Readable, + // stderr + Readable | Writable | null | undefined, + // extra, no modification + Readable | Writable | null | undefined // extra, no modification + ]; + } + // return this object when stdio option is a tuple of 3 + interface ChildProcessByStdio extends ChildProcess { + stdin: I; + stdout: O; + stderr: E; + readonly stdio: [ + I, + O, + E, + Readable | Writable | null | undefined, + // extra, no modification + Readable | Writable | null | undefined // extra, no modification + ]; + } + interface MessageOptions { + keepOpen?: boolean | undefined; + } + type IOType = 'overlapped' | 'pipe' | 'ignore' | 'inherit'; + type StdioOptions = IOType | Array; + type SerializationType = 'json' | 'advanced'; + interface MessagingOptions extends Abortable { + /** + * Specify the kind of serialization used for sending messages between processes. + * @default 'json' + */ + serialization?: SerializationType | undefined; + /** + * The signal value to be used when the spawned process will be killed by the abort signal. + * @default 'SIGTERM' + */ + killSignal?: NodeJS.Signals | number | undefined; + /** + * In milliseconds the maximum amount of time the process is allowed to run. + */ + timeout?: number | undefined; + } + interface ProcessEnvOptions { + uid?: number | undefined; + gid?: number | undefined; + cwd?: string | URL | undefined; + env?: NodeJS.ProcessEnv | undefined; + } + interface CommonOptions extends ProcessEnvOptions { + /** + * @default true + */ + windowsHide?: boolean | undefined; + /** + * @default 0 + */ + timeout?: number | undefined; + } + interface CommonSpawnOptions extends CommonOptions, MessagingOptions, Abortable { + argv0?: string | undefined; + stdio?: StdioOptions | undefined; + shell?: boolean | string | undefined; + windowsVerbatimArguments?: boolean | undefined; + } + interface SpawnOptions extends CommonSpawnOptions { + detached?: boolean | undefined; + } + interface SpawnOptionsWithoutStdio extends SpawnOptions { + stdio?: StdioPipeNamed | StdioPipe[] | undefined; + } + type StdioNull = 'inherit' | 'ignore' | Stream; + type StdioPipeNamed = 'pipe' | 'overlapped'; + type StdioPipe = undefined | null | StdioPipeNamed; + interface SpawnOptionsWithStdioTuple extends SpawnOptions { + stdio: [Stdin, Stdout, Stderr]; + } + /** + * The `child_process.spawn()` method spawns a new process using the given`command`, with command-line arguments in `args`. If omitted, `args` defaults + * to an empty array. + * + * **If the `shell` option is enabled, do not pass unsanitized user input to this** + * **function. Any input containing shell metacharacters may be used to trigger** + * **arbitrary command execution.** + * + * A third argument may be used to specify additional options, with these defaults: + * + * ```js + * const defaults = { + * cwd: undefined, + * env: process.env + * }; + * ``` + * + * Use `cwd` to specify the working directory from which the process is spawned. + * If not given, the default is to inherit the current working directory. If given, + * but the path does not exist, the child process emits an `ENOENT` error + * and exits immediately. `ENOENT` is also emitted when the command + * does not exist. + * + * Use `env` to specify environment variables that will be visible to the new + * process, the default is `process.env`. + * + * `undefined` values in `env` will be ignored. + * + * Example of running `ls -lh /usr`, capturing `stdout`, `stderr`, and the + * exit code: + * + * ```js + * const { spawn } = require('child_process'); + * const ls = spawn('ls', ['-lh', '/usr']); + * + * ls.stdout.on('data', (data) => { + * console.log(`stdout: ${data}`); + * }); + * + * ls.stderr.on('data', (data) => { + * console.error(`stderr: ${data}`); + * }); + * + * ls.on('close', (code) => { + * console.log(`child process exited with code ${code}`); + * }); + * ``` + * + * Example: A very elaborate way to run `ps ax | grep ssh` + * + * ```js + * const { spawn } = require('child_process'); + * const ps = spawn('ps', ['ax']); + * const grep = spawn('grep', ['ssh']); + * + * ps.stdout.on('data', (data) => { + * grep.stdin.write(data); + * }); + * + * ps.stderr.on('data', (data) => { + * console.error(`ps stderr: ${data}`); + * }); + * + * ps.on('close', (code) => { + * if (code !== 0) { + * console.log(`ps process exited with code ${code}`); + * } + * grep.stdin.end(); + * }); + * + * grep.stdout.on('data', (data) => { + * console.log(data.toString()); + * }); + * + * grep.stderr.on('data', (data) => { + * console.error(`grep stderr: ${data}`); + * }); + * + * grep.on('close', (code) => { + * if (code !== 0) { + * console.log(`grep process exited with code ${code}`); + * } + * }); + * ``` + * + * Example of checking for failed `spawn`: + * + * ```js + * const { spawn } = require('child_process'); + * const subprocess = spawn('bad_command'); + * + * subprocess.on('error', (err) => { + * console.error('Failed to start subprocess.'); + * }); + * ``` + * + * Certain platforms (macOS, Linux) will use the value of `argv[0]` for the process + * title while others (Windows, SunOS) will use `command`. + * + * Node.js currently overwrites `argv[0]` with `process.execPath` on startup, so`process.argv[0]` in a Node.js child process will not match the `argv0`parameter passed to `spawn` from the parent, + * retrieve it with the`process.argv0` property instead. + * + * If the `signal` option is enabled, calling `.abort()` on the corresponding`AbortController` is similar to calling `.kill()` on the child process except + * the error passed to the callback will be an `AbortError`: + * + * ```js + * const { spawn } = require('child_process'); + * const controller = new AbortController(); + * const { signal } = controller; + * const grep = spawn('grep', ['ssh'], { signal }); + * grep.on('error', (err) => { + * // This will be called with err being an AbortError if the controller aborts + * }); + * controller.abort(); // Stops the child process + * ``` + * @since v0.1.90 + * @param command The command to run. + * @param args List of string arguments. + */ + function spawn(command: string, options?: SpawnOptionsWithoutStdio): ChildProcessWithoutNullStreams; + function spawn(command: string, options: SpawnOptionsWithStdioTuple): ChildProcessByStdio; + function spawn(command: string, options: SpawnOptionsWithStdioTuple): ChildProcessByStdio; + function spawn(command: string, options: SpawnOptionsWithStdioTuple): ChildProcessByStdio; + function spawn(command: string, options: SpawnOptionsWithStdioTuple): ChildProcessByStdio; + function spawn(command: string, options: SpawnOptionsWithStdioTuple): ChildProcessByStdio; + function spawn(command: string, options: SpawnOptionsWithStdioTuple): ChildProcessByStdio; + function spawn(command: string, options: SpawnOptionsWithStdioTuple): ChildProcessByStdio; + function spawn(command: string, options: SpawnOptionsWithStdioTuple): ChildProcessByStdio; + function spawn(command: string, options: SpawnOptions): ChildProcess; + // overloads of spawn with 'args' + function spawn(command: string, args?: ReadonlyArray, options?: SpawnOptionsWithoutStdio): ChildProcessWithoutNullStreams; + function spawn(command: string, args: ReadonlyArray, options: SpawnOptionsWithStdioTuple): ChildProcessByStdio; + function spawn(command: string, args: ReadonlyArray, options: SpawnOptionsWithStdioTuple): ChildProcessByStdio; + function spawn(command: string, args: ReadonlyArray, options: SpawnOptionsWithStdioTuple): ChildProcessByStdio; + function spawn(command: string, args: ReadonlyArray, options: SpawnOptionsWithStdioTuple): ChildProcessByStdio; + function spawn(command: string, args: ReadonlyArray, options: SpawnOptionsWithStdioTuple): ChildProcessByStdio; + function spawn(command: string, args: ReadonlyArray, options: SpawnOptionsWithStdioTuple): ChildProcessByStdio; + function spawn(command: string, args: ReadonlyArray, options: SpawnOptionsWithStdioTuple): ChildProcessByStdio; + function spawn(command: string, args: ReadonlyArray, options: SpawnOptionsWithStdioTuple): ChildProcessByStdio; + function spawn(command: string, args: ReadonlyArray, options: SpawnOptions): ChildProcess; + interface ExecOptions extends CommonOptions { + shell?: string | undefined; + signal?: AbortSignal | undefined; + maxBuffer?: number | undefined; + killSignal?: NodeJS.Signals | number | undefined; + } + interface ExecOptionsWithStringEncoding extends ExecOptions { + encoding: BufferEncoding; + } + interface ExecOptionsWithBufferEncoding extends ExecOptions { + encoding: BufferEncoding | null; // specify `null`. + } + interface ExecException extends Error { + cmd?: string | undefined; + killed?: boolean | undefined; + code?: number | undefined; + signal?: NodeJS.Signals | undefined; + } + /** + * Spawns a shell then executes the `command` within that shell, buffering any + * generated output. The `command` string passed to the exec function is processed + * directly by the shell and special characters (vary based on [shell](https://en.wikipedia.org/wiki/List_of_command-line_interpreters)) + * need to be dealt with accordingly: + * + * ```js + * const { exec } = require('child_process'); + * + * exec('"/path/to/test file/test.sh" arg1 arg2'); + * // Double quotes are used so that the space in the path is not interpreted as + * // a delimiter of multiple arguments. + * + * exec('echo "The \\$HOME variable is $HOME"'); + * // The $HOME variable is escaped in the first instance, but not in the second. + * ``` + * + * **Never pass unsanitized user input to this function. Any input containing shell** + * **metacharacters may be used to trigger arbitrary command execution.** + * + * If a `callback` function is provided, it is called with the arguments`(error, stdout, stderr)`. On success, `error` will be `null`. On error,`error` will be an instance of `Error`. The + * `error.code` property will be + * the exit code of the process. By convention, any exit code other than `0`indicates an error. `error.signal` will be the signal that terminated the + * process. + * + * The `stdout` and `stderr` arguments passed to the callback will contain the + * stdout and stderr output of the child process. By default, Node.js will decode + * the output as UTF-8 and pass strings to the callback. The `encoding` option + * can be used to specify the character encoding used to decode the stdout and + * stderr output. If `encoding` is `'buffer'`, or an unrecognized character + * encoding, `Buffer` objects will be passed to the callback instead. + * + * ```js + * const { exec } = require('child_process'); + * exec('cat *.js missing_file | wc -l', (error, stdout, stderr) => { + * if (error) { + * console.error(`exec error: ${error}`); + * return; + * } + * console.log(`stdout: ${stdout}`); + * console.error(`stderr: ${stderr}`); + * }); + * ``` + * + * If `timeout` is greater than `0`, the parent will send the signal + * identified by the `killSignal` property (the default is `'SIGTERM'`) if the + * child runs longer than `timeout` milliseconds. + * + * Unlike the [`exec(3)`](http://man7.org/linux/man-pages/man3/exec.3.html) POSIX system call, `child_process.exec()` does not replace + * the existing process and uses a shell to execute the command. + * + * If this method is invoked as its `util.promisify()` ed version, it returns + * a `Promise` for an `Object` with `stdout` and `stderr` properties. The returned`ChildProcess` instance is attached to the `Promise` as a `child` property. In + * case of an error (including any error resulting in an exit code other than 0), a + * rejected promise is returned, with the same `error` object given in the + * callback, but with two additional properties `stdout` and `stderr`. + * + * ```js + * const util = require('util'); + * const exec = util.promisify(require('child_process').exec); + * + * async function lsExample() { + * const { stdout, stderr } = await exec('ls'); + * console.log('stdout:', stdout); + * console.error('stderr:', stderr); + * } + * lsExample(); + * ``` + * + * If the `signal` option is enabled, calling `.abort()` on the corresponding`AbortController` is similar to calling `.kill()` on the child process except + * the error passed to the callback will be an `AbortError`: + * + * ```js + * const { exec } = require('child_process'); + * const controller = new AbortController(); + * const { signal } = controller; + * const child = exec('grep ssh', { signal }, (error) => { + * console.log(error); // an AbortError + * }); + * controller.abort(); + * ``` + * @since v0.1.90 + * @param command The command to run, with space-separated arguments. + * @param callback called with the output when process terminates. + */ + function exec(command: string, callback?: (error: ExecException | null, stdout: string, stderr: string) => void): ChildProcess; + // `options` with `"buffer"` or `null` for `encoding` means stdout/stderr are definitely `Buffer`. + function exec( + command: string, + options: { + encoding: 'buffer' | null; + } & ExecOptions, + callback?: (error: ExecException | null, stdout: Buffer, stderr: Buffer) => void + ): ChildProcess; + // `options` with well known `encoding` means stdout/stderr are definitely `string`. + function exec( + command: string, + options: { + encoding: BufferEncoding; + } & ExecOptions, + callback?: (error: ExecException | null, stdout: string, stderr: string) => void + ): ChildProcess; + // `options` with an `encoding` whose type is `string` means stdout/stderr could either be `Buffer` or `string`. + // There is no guarantee the `encoding` is unknown as `string` is a superset of `BufferEncoding`. + function exec( + command: string, + options: { + encoding: BufferEncoding; + } & ExecOptions, + callback?: (error: ExecException | null, stdout: string | Buffer, stderr: string | Buffer) => void + ): ChildProcess; + // `options` without an `encoding` means stdout/stderr are definitely `string`. + function exec(command: string, options: ExecOptions, callback?: (error: ExecException | null, stdout: string, stderr: string) => void): ChildProcess; + // fallback if nothing else matches. Worst case is always `string | Buffer`. + function exec( + command: string, + options: (ObjectEncodingOptions & ExecOptions) | undefined | null, + callback?: (error: ExecException | null, stdout: string | Buffer, stderr: string | Buffer) => void + ): ChildProcess; + interface PromiseWithChild extends Promise { + child: ChildProcess; + } + namespace exec { + function __promisify__(command: string): PromiseWithChild<{ + stdout: string; + stderr: string; + }>; + function __promisify__( + command: string, + options: { + encoding: 'buffer' | null; + } & ExecOptions + ): PromiseWithChild<{ + stdout: Buffer; + stderr: Buffer; + }>; + function __promisify__( + command: string, + options: { + encoding: BufferEncoding; + } & ExecOptions + ): PromiseWithChild<{ + stdout: string; + stderr: string; + }>; + function __promisify__( + command: string, + options: ExecOptions + ): PromiseWithChild<{ + stdout: string; + stderr: string; + }>; + function __promisify__( + command: string, + options?: (ObjectEncodingOptions & ExecOptions) | null + ): PromiseWithChild<{ + stdout: string | Buffer; + stderr: string | Buffer; + }>; + } + interface ExecFileOptions extends CommonOptions, Abortable { + maxBuffer?: number | undefined; + killSignal?: NodeJS.Signals | number | undefined; + windowsVerbatimArguments?: boolean | undefined; + shell?: boolean | string | undefined; + signal?: AbortSignal | undefined; + } + interface ExecFileOptionsWithStringEncoding extends ExecFileOptions { + encoding: BufferEncoding; + } + interface ExecFileOptionsWithBufferEncoding extends ExecFileOptions { + encoding: 'buffer' | null; + } + interface ExecFileOptionsWithOtherEncoding extends ExecFileOptions { + encoding: BufferEncoding; + } + type ExecFileException = ExecException & NodeJS.ErrnoException; + /** + * The `child_process.execFile()` function is similar to {@link exec} except that it does not spawn a shell by default. Rather, the specified + * executable `file` is spawned directly as a new process making it slightly more + * efficient than {@link exec}. + * + * The same options as {@link exec} are supported. Since a shell is + * not spawned, behaviors such as I/O redirection and file globbing are not + * supported. + * + * ```js + * const { execFile } = require('child_process'); + * const child = execFile('node', ['--version'], (error, stdout, stderr) => { + * if (error) { + * throw error; + * } + * console.log(stdout); + * }); + * ``` + * + * The `stdout` and `stderr` arguments passed to the callback will contain the + * stdout and stderr output of the child process. By default, Node.js will decode + * the output as UTF-8 and pass strings to the callback. The `encoding` option + * can be used to specify the character encoding used to decode the stdout and + * stderr output. If `encoding` is `'buffer'`, or an unrecognized character + * encoding, `Buffer` objects will be passed to the callback instead. + * + * If this method is invoked as its `util.promisify()` ed version, it returns + * a `Promise` for an `Object` with `stdout` and `stderr` properties. The returned`ChildProcess` instance is attached to the `Promise` as a `child` property. In + * case of an error (including any error resulting in an exit code other than 0), a + * rejected promise is returned, with the same `error` object given in the + * callback, but with two additional properties `stdout` and `stderr`. + * + * ```js + * const util = require('util'); + * const execFile = util.promisify(require('child_process').execFile); + * async function getVersion() { + * const { stdout } = await execFile('node', ['--version']); + * console.log(stdout); + * } + * getVersion(); + * ``` + * + * **If the `shell` option is enabled, do not pass unsanitized user input to this** + * **function. Any input containing shell metacharacters may be used to trigger** + * **arbitrary command execution.** + * + * If the `signal` option is enabled, calling `.abort()` on the corresponding`AbortController` is similar to calling `.kill()` on the child process except + * the error passed to the callback will be an `AbortError`: + * + * ```js + * const { execFile } = require('child_process'); + * const controller = new AbortController(); + * const { signal } = controller; + * const child = execFile('node', ['--version'], { signal }, (error) => { + * console.log(error); // an AbortError + * }); + * controller.abort(); + * ``` + * @since v0.1.91 + * @param file The name or path of the executable file to run. + * @param args List of string arguments. + * @param callback Called with the output when process terminates. + */ + function execFile(file: string): ChildProcess; + function execFile(file: string, options: (ObjectEncodingOptions & ExecFileOptions) | undefined | null): ChildProcess; + function execFile(file: string, args?: ReadonlyArray | null): ChildProcess; + function execFile(file: string, args: ReadonlyArray | undefined | null, options: (ObjectEncodingOptions & ExecFileOptions) | undefined | null): ChildProcess; + // no `options` definitely means stdout/stderr are `string`. + function execFile(file: string, callback: (error: ExecFileException | null, stdout: string, stderr: string) => void): ChildProcess; + function execFile(file: string, args: ReadonlyArray | undefined | null, callback: (error: ExecFileException | null, stdout: string, stderr: string) => void): ChildProcess; + // `options` with `"buffer"` or `null` for `encoding` means stdout/stderr are definitely `Buffer`. + function execFile(file: string, options: ExecFileOptionsWithBufferEncoding, callback: (error: ExecFileException | null, stdout: Buffer, stderr: Buffer) => void): ChildProcess; + function execFile( + file: string, + args: ReadonlyArray | undefined | null, + options: ExecFileOptionsWithBufferEncoding, + callback: (error: ExecFileException | null, stdout: Buffer, stderr: Buffer) => void + ): ChildProcess; + // `options` with well known `encoding` means stdout/stderr are definitely `string`. + function execFile(file: string, options: ExecFileOptionsWithStringEncoding, callback: (error: ExecFileException | null, stdout: string, stderr: string) => void): ChildProcess; + function execFile( + file: string, + args: ReadonlyArray | undefined | null, + options: ExecFileOptionsWithStringEncoding, + callback: (error: ExecFileException | null, stdout: string, stderr: string) => void + ): ChildProcess; + // `options` with an `encoding` whose type is `string` means stdout/stderr could either be `Buffer` or `string`. + // There is no guarantee the `encoding` is unknown as `string` is a superset of `BufferEncoding`. + function execFile(file: string, options: ExecFileOptionsWithOtherEncoding, callback: (error: ExecFileException | null, stdout: string | Buffer, stderr: string | Buffer) => void): ChildProcess; + function execFile( + file: string, + args: ReadonlyArray | undefined | null, + options: ExecFileOptionsWithOtherEncoding, + callback: (error: ExecFileException | null, stdout: string | Buffer, stderr: string | Buffer) => void + ): ChildProcess; + // `options` without an `encoding` means stdout/stderr are definitely `string`. + function execFile(file: string, options: ExecFileOptions, callback: (error: ExecFileException | null, stdout: string, stderr: string) => void): ChildProcess; + function execFile( + file: string, + args: ReadonlyArray | undefined | null, + options: ExecFileOptions, + callback: (error: ExecFileException | null, stdout: string, stderr: string) => void + ): ChildProcess; + // fallback if nothing else matches. Worst case is always `string | Buffer`. + function execFile( + file: string, + options: (ObjectEncodingOptions & ExecFileOptions) | undefined | null, + callback: ((error: ExecFileException | null, stdout: string | Buffer, stderr: string | Buffer) => void) | undefined | null + ): ChildProcess; + function execFile( + file: string, + args: ReadonlyArray | undefined | null, + options: (ObjectEncodingOptions & ExecFileOptions) | undefined | null, + callback: ((error: ExecFileException | null, stdout: string | Buffer, stderr: string | Buffer) => void) | undefined | null + ): ChildProcess; + namespace execFile { + function __promisify__(file: string): PromiseWithChild<{ + stdout: string; + stderr: string; + }>; + function __promisify__( + file: string, + args: ReadonlyArray | undefined | null + ): PromiseWithChild<{ + stdout: string; + stderr: string; + }>; + function __promisify__( + file: string, + options: ExecFileOptionsWithBufferEncoding + ): PromiseWithChild<{ + stdout: Buffer; + stderr: Buffer; + }>; + function __promisify__( + file: string, + args: ReadonlyArray | undefined | null, + options: ExecFileOptionsWithBufferEncoding + ): PromiseWithChild<{ + stdout: Buffer; + stderr: Buffer; + }>; + function __promisify__( + file: string, + options: ExecFileOptionsWithStringEncoding + ): PromiseWithChild<{ + stdout: string; + stderr: string; + }>; + function __promisify__( + file: string, + args: ReadonlyArray | undefined | null, + options: ExecFileOptionsWithStringEncoding + ): PromiseWithChild<{ + stdout: string; + stderr: string; + }>; + function __promisify__( + file: string, + options: ExecFileOptionsWithOtherEncoding + ): PromiseWithChild<{ + stdout: string | Buffer; + stderr: string | Buffer; + }>; + function __promisify__( + file: string, + args: ReadonlyArray | undefined | null, + options: ExecFileOptionsWithOtherEncoding + ): PromiseWithChild<{ + stdout: string | Buffer; + stderr: string | Buffer; + }>; + function __promisify__( + file: string, + options: ExecFileOptions + ): PromiseWithChild<{ + stdout: string; + stderr: string; + }>; + function __promisify__( + file: string, + args: ReadonlyArray | undefined | null, + options: ExecFileOptions + ): PromiseWithChild<{ + stdout: string; + stderr: string; + }>; + function __promisify__( + file: string, + options: (ObjectEncodingOptions & ExecFileOptions) | undefined | null + ): PromiseWithChild<{ + stdout: string | Buffer; + stderr: string | Buffer; + }>; + function __promisify__( + file: string, + args: ReadonlyArray | undefined | null, + options: (ObjectEncodingOptions & ExecFileOptions) | undefined | null + ): PromiseWithChild<{ + stdout: string | Buffer; + stderr: string | Buffer; + }>; + } + interface ForkOptions extends ProcessEnvOptions, MessagingOptions, Abortable { + execPath?: string | undefined; + execArgv?: string[] | undefined; + silent?: boolean | undefined; + stdio?: StdioOptions | undefined; + detached?: boolean | undefined; + windowsVerbatimArguments?: boolean | undefined; + } + /** + * The `child_process.fork()` method is a special case of {@link spawn} used specifically to spawn new Node.js processes. + * Like {@link spawn}, a `ChildProcess` object is returned. The + * returned `ChildProcess` will have an additional communication channel + * built-in that allows messages to be passed back and forth between the parent and + * child. See `subprocess.send()` for details. + * + * Keep in mind that spawned Node.js child processes are + * independent of the parent with exception of the IPC communication channel + * that is established between the two. Each process has its own memory, with + * their own V8 instances. Because of the additional resource allocations + * required, spawning a large number of child Node.js processes is not + * recommended. + * + * By default, `child_process.fork()` will spawn new Node.js instances using the `process.execPath` of the parent process. The `execPath` property in the`options` object allows for an alternative + * execution path to be used. + * + * Node.js processes launched with a custom `execPath` will communicate with the + * parent process using the file descriptor (fd) identified using the + * environment variable `NODE_CHANNEL_FD` on the child process. + * + * Unlike the [`fork(2)`](http://man7.org/linux/man-pages/man2/fork.2.html) POSIX system call, `child_process.fork()` does not clone the + * current process. + * + * The `shell` option available in {@link spawn} is not supported by`child_process.fork()` and will be ignored if set. + * + * If the `signal` option is enabled, calling `.abort()` on the corresponding`AbortController` is similar to calling `.kill()` on the child process except + * the error passed to the callback will be an `AbortError`: + * + * ```js + * if (process.argv[2] === 'child') { + * setTimeout(() => { + * console.log(`Hello from ${process.argv[2]}!`); + * }, 1_000); + * } else { + * const { fork } = require('child_process'); + * const controller = new AbortController(); + * const { signal } = controller; + * const child = fork(__filename, ['child'], { signal }); + * child.on('error', (err) => { + * // This will be called with err being an AbortError if the controller aborts + * }); + * controller.abort(); // Stops the child process + * } + * ``` + * @since v0.5.0 + * @param modulePath The module to run in the child. + * @param args List of string arguments. + */ + function fork(modulePath: string, options?: ForkOptions): ChildProcess; + function fork(modulePath: string, args?: ReadonlyArray, options?: ForkOptions): ChildProcess; + interface SpawnSyncOptions extends CommonSpawnOptions { + input?: string | NodeJS.ArrayBufferView | undefined; + maxBuffer?: number | undefined; + encoding?: BufferEncoding | 'buffer' | null | undefined; + } + interface SpawnSyncOptionsWithStringEncoding extends SpawnSyncOptions { + encoding: BufferEncoding; + } + interface SpawnSyncOptionsWithBufferEncoding extends SpawnSyncOptions { + encoding?: 'buffer' | null | undefined; + } + interface SpawnSyncReturns { + pid: number; + output: Array; + stdout: T; + stderr: T; + status: number | null; + signal: NodeJS.Signals | null; + error?: Error | undefined; + } + /** + * The `child_process.spawnSync()` method is generally identical to {@link spawn} with the exception that the function will not return + * until the child process has fully closed. When a timeout has been encountered + * and `killSignal` is sent, the method won't return until the process has + * completely exited. If the process intercepts and handles the `SIGTERM` signal + * and doesn't exit, the parent process will wait until the child process has + * exited. + * + * **If the `shell` option is enabled, do not pass unsanitized user input to this** + * **function. Any input containing shell metacharacters may be used to trigger** + * **arbitrary command execution.** + * @since v0.11.12 + * @param command The command to run. + * @param args List of string arguments. + */ + function spawnSync(command: string): SpawnSyncReturns; + function spawnSync(command: string, options: SpawnSyncOptionsWithStringEncoding): SpawnSyncReturns; + function spawnSync(command: string, options: SpawnSyncOptionsWithBufferEncoding): SpawnSyncReturns; + function spawnSync(command: string, options?: SpawnSyncOptions): SpawnSyncReturns; + function spawnSync(command: string, args: ReadonlyArray): SpawnSyncReturns; + function spawnSync(command: string, args: ReadonlyArray, options: SpawnSyncOptionsWithStringEncoding): SpawnSyncReturns; + function spawnSync(command: string, args: ReadonlyArray, options: SpawnSyncOptionsWithBufferEncoding): SpawnSyncReturns; + function spawnSync(command: string, args?: ReadonlyArray, options?: SpawnSyncOptions): SpawnSyncReturns; + interface CommonExecOptions extends CommonOptions { + input?: string | NodeJS.ArrayBufferView | undefined; + stdio?: StdioOptions | undefined; + killSignal?: NodeJS.Signals | number | undefined; + maxBuffer?: number | undefined; + encoding?: BufferEncoding | 'buffer' | null | undefined; + } + interface ExecSyncOptions extends CommonExecOptions { + shell?: string | undefined; + } + interface ExecSyncOptionsWithStringEncoding extends ExecSyncOptions { + encoding: BufferEncoding; + } + interface ExecSyncOptionsWithBufferEncoding extends ExecSyncOptions { + encoding?: 'buffer' | null | undefined; + } + /** + * The `child_process.execSync()` method is generally identical to {@link exec} with the exception that the method will not return + * until the child process has fully closed. When a timeout has been encountered + * and `killSignal` is sent, the method won't return until the process has + * completely exited. If the child process intercepts and handles the `SIGTERM`signal and doesn't exit, the parent process will wait until the child process + * has exited. + * + * If the process times out or has a non-zero exit code, this method will throw. + * The `Error` object will contain the entire result from {@link spawnSync}. + * + * **Never pass unsanitized user input to this function. Any input containing shell** + * **metacharacters may be used to trigger arbitrary command execution.** + * @since v0.11.12 + * @param command The command to run. + * @return The stdout from the command. + */ + function execSync(command: string): Buffer; + function execSync(command: string, options: ExecSyncOptionsWithStringEncoding): string; + function execSync(command: string, options: ExecSyncOptionsWithBufferEncoding): Buffer; + function execSync(command: string, options?: ExecSyncOptions): string | Buffer; + interface ExecFileSyncOptions extends CommonExecOptions { + shell?: boolean | string | undefined; + } + interface ExecFileSyncOptionsWithStringEncoding extends ExecFileSyncOptions { + encoding: BufferEncoding; + } + interface ExecFileSyncOptionsWithBufferEncoding extends ExecFileSyncOptions { + encoding?: 'buffer' | null; // specify `null`. + } + /** + * The `child_process.execFileSync()` method is generally identical to {@link execFile} with the exception that the method will not + * return until the child process has fully closed. When a timeout has been + * encountered and `killSignal` is sent, the method won't return until the process + * has completely exited. + * + * If the child process intercepts and handles the `SIGTERM` signal and + * does not exit, the parent process will still wait until the child process has + * exited. + * + * If the process times out or has a non-zero exit code, this method will throw an `Error` that will include the full result of the underlying {@link spawnSync}. + * + * **If the `shell` option is enabled, do not pass unsanitized user input to this** + * **function. Any input containing shell metacharacters may be used to trigger** + * **arbitrary command execution.** + * @since v0.11.12 + * @param file The name or path of the executable file to run. + * @param args List of string arguments. + * @return The stdout from the command. + */ + function execFileSync(file: string): Buffer; + function execFileSync(file: string, options: ExecFileSyncOptionsWithStringEncoding): string; + function execFileSync(file: string, options: ExecFileSyncOptionsWithBufferEncoding): Buffer; + function execFileSync(file: string, options?: ExecFileSyncOptions): string | Buffer; + function execFileSync(file: string, args: ReadonlyArray): Buffer; + function execFileSync(file: string, args: ReadonlyArray, options: ExecFileSyncOptionsWithStringEncoding): string; + function execFileSync(file: string, args: ReadonlyArray, options: ExecFileSyncOptionsWithBufferEncoding): Buffer; + function execFileSync(file: string, args?: ReadonlyArray, options?: ExecFileSyncOptions): string | Buffer; +} +declare module 'node:child_process' { + export * from 'child_process'; +} diff --git a/ts-ticket-office-service/node_modules/@types/node/cluster.d.ts b/ts-ticket-office-service/node_modules/@types/node/cluster.d.ts new file mode 100755 index 000000000..37dbc5746 --- /dev/null +++ b/ts-ticket-office-service/node_modules/@types/node/cluster.d.ts @@ -0,0 +1,410 @@ +/** + * Clusters of Node.js processes can be used to run multiple instances of Node.js + * that can distribute workloads among their application threads. When process + * isolation is not needed, use the `worker_threads` module instead, which + * allows running multiple application threads within a single Node.js instance. + * + * The cluster module allows easy creation of child processes that all share + * server ports. + * + * ```js + * import cluster from 'cluster'; + * import http from 'http'; + * import { cpus } from 'os'; + * import process from 'process'; + * + * const numCPUs = cpus().length; + * + * if (cluster.isPrimary) { + * console.log(`Primary ${process.pid} is running`); + * + * // Fork workers. + * for (let i = 0; i < numCPUs; i++) { + * cluster.fork(); + * } + * + * cluster.on('exit', (worker, code, signal) => { + * console.log(`worker ${worker.process.pid} died`); + * }); + * } else { + * // Workers can share any TCP connection + * // In this case it is an HTTP server + * http.createServer((req, res) => { + * res.writeHead(200); + * res.end('hello world\n'); + * }).listen(8000); + * + * console.log(`Worker ${process.pid} started`); + * } + * ``` + * + * Running Node.js will now share port 8000 between the workers: + * + * ```console + * $ node server.js + * Primary 3596 is running + * Worker 4324 started + * Worker 4520 started + * Worker 6056 started + * Worker 5644 started + * ``` + * + * On Windows, it is not yet possible to set up a named pipe server in a worker. + * @see [source](https://github.com/nodejs/node/blob/v18.0.0/lib/cluster.js) + */ +declare module 'cluster' { + import * as child from 'node:child_process'; + import EventEmitter = require('node:events'); + import * as net from 'node:net'; + export interface ClusterSettings { + execArgv?: string[] | undefined; // default: process.execArgv + exec?: string | undefined; + args?: string[] | undefined; + silent?: boolean | undefined; + stdio?: any[] | undefined; + uid?: number | undefined; + gid?: number | undefined; + inspectPort?: number | (() => number) | undefined; + } + export interface Address { + address: string; + port: number; + addressType: number | 'udp4' | 'udp6'; // 4, 6, -1, "udp4", "udp6" + } + /** + * A `Worker` object contains all public information and method about a worker. + * In the primary it can be obtained using `cluster.workers`. In a worker + * it can be obtained using `cluster.worker`. + * @since v0.7.0 + */ + export class Worker extends EventEmitter { + /** + * Each new worker is given its own unique id, this id is stored in the`id`. + * + * While a worker is alive, this is the key that indexes it in`cluster.workers`. + * @since v0.8.0 + */ + id: number; + /** + * All workers are created using `child_process.fork()`, the returned object + * from this function is stored as `.process`. In a worker, the global `process`is stored. + * + * See: `Child Process module`. + * + * Workers will call `process.exit(0)` if the `'disconnect'` event occurs + * on `process` and `.exitedAfterDisconnect` is not `true`. This protects against + * accidental disconnection. + * @since v0.7.0 + */ + process: child.ChildProcess; + /** + * Send a message to a worker or primary, optionally with a handle. + * + * In the primary, this sends a message to a specific worker. It is identical to `ChildProcess.send()`. + * + * In a worker, this sends a message to the primary. It is identical to`process.send()`. + * + * This example will echo back all messages from the primary: + * + * ```js + * if (cluster.isPrimary) { + * const worker = cluster.fork(); + * worker.send('hi there'); + * + * } else if (cluster.isWorker) { + * process.on('message', (msg) => { + * process.send(msg); + * }); + * } + * ``` + * @since v0.7.0 + * @param options The `options` argument, if present, is an object used to parameterize the sending of certain types of handles. `options` supports the following properties: + */ + send(message: child.Serializable, callback?: (error: Error | null) => void): boolean; + send(message: child.Serializable, sendHandle: child.SendHandle, callback?: (error: Error | null) => void): boolean; + send(message: child.Serializable, sendHandle: child.SendHandle, options?: child.MessageOptions, callback?: (error: Error | null) => void): boolean; + /** + * This function will kill the worker. In the primary worker, it does this by + * disconnecting the `worker.process`, and once disconnected, killing with`signal`. In the worker, it does it by killing the process with `signal`. + * + * The `kill()` function kills the worker process without waiting for a graceful + * disconnect, it has the same behavior as `worker.process.kill()`. + * + * This method is aliased as `worker.destroy()` for backwards compatibility. + * + * In a worker, `process.kill()` exists, but it is not this function; + * it is `kill()`. + * @since v0.9.12 + * @param [signal='SIGTERM'] Name of the kill signal to send to the worker process. + */ + kill(signal?: string): void; + destroy(signal?: string): void; + /** + * In a worker, this function will close all servers, wait for the `'close'` event + * on those servers, and then disconnect the IPC channel. + * + * In the primary, an internal message is sent to the worker causing it to call`.disconnect()` on itself. + * + * Causes `.exitedAfterDisconnect` to be set. + * + * After a server is closed, it will no longer accept new connections, + * but connections may be accepted by any other listening worker. Existing + * connections will be allowed to close as usual. When no more connections exist, + * see `server.close()`, the IPC channel to the worker will close allowing it + * to die gracefully. + * + * The above applies _only_ to server connections, client connections are not + * automatically closed by workers, and disconnect does not wait for them to close + * before exiting. + * + * In a worker, `process.disconnect` exists, but it is not this function; + * it is `disconnect()`. + * + * Because long living server connections may block workers from disconnecting, it + * may be useful to send a message, so application specific actions may be taken to + * close them. It also may be useful to implement a timeout, killing a worker if + * the `'disconnect'` event has not been emitted after some time. + * + * ```js + * if (cluster.isPrimary) { + * const worker = cluster.fork(); + * let timeout; + * + * worker.on('listening', (address) => { + * worker.send('shutdown'); + * worker.disconnect(); + * timeout = setTimeout(() => { + * worker.kill(); + * }, 2000); + * }); + * + * worker.on('disconnect', () => { + * clearTimeout(timeout); + * }); + * + * } else if (cluster.isWorker) { + * const net = require('net'); + * const server = net.createServer((socket) => { + * // Connections never end + * }); + * + * server.listen(8000); + * + * process.on('message', (msg) => { + * if (msg === 'shutdown') { + * // Initiate graceful close of any connections to server + * } + * }); + * } + * ``` + * @since v0.7.7 + * @return A reference to `worker`. + */ + disconnect(): void; + /** + * This function returns `true` if the worker is connected to its primary via its + * IPC channel, `false` otherwise. A worker is connected to its primary after it + * has been created. It is disconnected after the `'disconnect'` event is emitted. + * @since v0.11.14 + */ + isConnected(): boolean; + /** + * This function returns `true` if the worker's process has terminated (either + * because of exiting or being signaled). Otherwise, it returns `false`. + * + * ```js + * import cluster from 'cluster'; + * import http from 'http'; + * import { cpus } from 'os'; + * import process from 'process'; + * + * const numCPUs = cpus().length; + * + * if (cluster.isPrimary) { + * console.log(`Primary ${process.pid} is running`); + * + * // Fork workers. + * for (let i = 0; i < numCPUs; i++) { + * cluster.fork(); + * } + * + * cluster.on('fork', (worker) => { + * console.log('worker is dead:', worker.isDead()); + * }); + * + * cluster.on('exit', (worker, code, signal) => { + * console.log('worker is dead:', worker.isDead()); + * }); + * } else { + * // Workers can share any TCP connection. In this case, it is an HTTP server. + * http.createServer((req, res) => { + * res.writeHead(200); + * res.end(`Current process\n ${process.pid}`); + * process.kill(process.pid); + * }).listen(8000); + * } + * ``` + * @since v0.11.14 + */ + isDead(): boolean; + /** + * This property is `true` if the worker exited due to `.disconnect()`. + * If the worker exited any other way, it is `false`. If the + * worker has not exited, it is `undefined`. + * + * The boolean `worker.exitedAfterDisconnect` allows distinguishing between + * voluntary and accidental exit, the primary may choose not to respawn a worker + * based on this value. + * + * ```js + * cluster.on('exit', (worker, code, signal) => { + * if (worker.exitedAfterDisconnect === true) { + * console.log('Oh, it was just voluntary – no need to worry'); + * } + * }); + * + * // kill worker + * worker.kill(); + * ``` + * @since v6.0.0 + */ + exitedAfterDisconnect: boolean; + /** + * events.EventEmitter + * 1. disconnect + * 2. error + * 3. exit + * 4. listening + * 5. message + * 6. online + */ + addListener(event: string, listener: (...args: any[]) => void): this; + addListener(event: 'disconnect', listener: () => void): this; + addListener(event: 'error', listener: (error: Error) => void): this; + addListener(event: 'exit', listener: (code: number, signal: string) => void): this; + addListener(event: 'listening', listener: (address: Address) => void): this; + addListener(event: 'message', listener: (message: any, handle: net.Socket | net.Server) => void): this; // the handle is a net.Socket or net.Server object, or undefined. + addListener(event: 'online', listener: () => void): this; + emit(event: string | symbol, ...args: any[]): boolean; + emit(event: 'disconnect'): boolean; + emit(event: 'error', error: Error): boolean; + emit(event: 'exit', code: number, signal: string): boolean; + emit(event: 'listening', address: Address): boolean; + emit(event: 'message', message: any, handle: net.Socket | net.Server): boolean; + emit(event: 'online'): boolean; + on(event: string, listener: (...args: any[]) => void): this; + on(event: 'disconnect', listener: () => void): this; + on(event: 'error', listener: (error: Error) => void): this; + on(event: 'exit', listener: (code: number, signal: string) => void): this; + on(event: 'listening', listener: (address: Address) => void): this; + on(event: 'message', listener: (message: any, handle: net.Socket | net.Server) => void): this; // the handle is a net.Socket or net.Server object, or undefined. + on(event: 'online', listener: () => void): this; + once(event: string, listener: (...args: any[]) => void): this; + once(event: 'disconnect', listener: () => void): this; + once(event: 'error', listener: (error: Error) => void): this; + once(event: 'exit', listener: (code: number, signal: string) => void): this; + once(event: 'listening', listener: (address: Address) => void): this; + once(event: 'message', listener: (message: any, handle: net.Socket | net.Server) => void): this; // the handle is a net.Socket or net.Server object, or undefined. + once(event: 'online', listener: () => void): this; + prependListener(event: string, listener: (...args: any[]) => void): this; + prependListener(event: 'disconnect', listener: () => void): this; + prependListener(event: 'error', listener: (error: Error) => void): this; + prependListener(event: 'exit', listener: (code: number, signal: string) => void): this; + prependListener(event: 'listening', listener: (address: Address) => void): this; + prependListener(event: 'message', listener: (message: any, handle: net.Socket | net.Server) => void): this; // the handle is a net.Socket or net.Server object, or undefined. + prependListener(event: 'online', listener: () => void): this; + prependOnceListener(event: string, listener: (...args: any[]) => void): this; + prependOnceListener(event: 'disconnect', listener: () => void): this; + prependOnceListener(event: 'error', listener: (error: Error) => void): this; + prependOnceListener(event: 'exit', listener: (code: number, signal: string) => void): this; + prependOnceListener(event: 'listening', listener: (address: Address) => void): this; + prependOnceListener(event: 'message', listener: (message: any, handle: net.Socket | net.Server) => void): this; // the handle is a net.Socket or net.Server object, or undefined. + prependOnceListener(event: 'online', listener: () => void): this; + } + export interface Cluster extends EventEmitter { + disconnect(callback?: () => void): void; + fork(env?: any): Worker; + /** @deprecated since v16.0.0 - use isPrimary. */ + readonly isMaster: boolean; + readonly isPrimary: boolean; + readonly isWorker: boolean; + schedulingPolicy: number; + readonly settings: ClusterSettings; + /** @deprecated since v16.0.0 - use setupPrimary. */ + setupMaster(settings?: ClusterSettings): void; + /** + * `setupPrimary` is used to change the default 'fork' behavior. Once called, the settings will be present in cluster.settings. + */ + setupPrimary(settings?: ClusterSettings): void; + readonly worker?: Worker | undefined; + readonly workers?: NodeJS.Dict | undefined; + readonly SCHED_NONE: number; + readonly SCHED_RR: number; + /** + * events.EventEmitter + * 1. disconnect + * 2. exit + * 3. fork + * 4. listening + * 5. message + * 6. online + * 7. setup + */ + addListener(event: string, listener: (...args: any[]) => void): this; + addListener(event: 'disconnect', listener: (worker: Worker) => void): this; + addListener(event: 'exit', listener: (worker: Worker, code: number, signal: string) => void): this; + addListener(event: 'fork', listener: (worker: Worker) => void): this; + addListener(event: 'listening', listener: (worker: Worker, address: Address) => void): this; + addListener(event: 'message', listener: (worker: Worker, message: any, handle: net.Socket | net.Server) => void): this; // the handle is a net.Socket or net.Server object, or undefined. + addListener(event: 'online', listener: (worker: Worker) => void): this; + addListener(event: 'setup', listener: (settings: ClusterSettings) => void): this; + emit(event: string | symbol, ...args: any[]): boolean; + emit(event: 'disconnect', worker: Worker): boolean; + emit(event: 'exit', worker: Worker, code: number, signal: string): boolean; + emit(event: 'fork', worker: Worker): boolean; + emit(event: 'listening', worker: Worker, address: Address): boolean; + emit(event: 'message', worker: Worker, message: any, handle: net.Socket | net.Server): boolean; + emit(event: 'online', worker: Worker): boolean; + emit(event: 'setup', settings: ClusterSettings): boolean; + on(event: string, listener: (...args: any[]) => void): this; + on(event: 'disconnect', listener: (worker: Worker) => void): this; + on(event: 'exit', listener: (worker: Worker, code: number, signal: string) => void): this; + on(event: 'fork', listener: (worker: Worker) => void): this; + on(event: 'listening', listener: (worker: Worker, address: Address) => void): this; + on(event: 'message', listener: (worker: Worker, message: any, handle: net.Socket | net.Server) => void): this; // the handle is a net.Socket or net.Server object, or undefined. + on(event: 'online', listener: (worker: Worker) => void): this; + on(event: 'setup', listener: (settings: ClusterSettings) => void): this; + once(event: string, listener: (...args: any[]) => void): this; + once(event: 'disconnect', listener: (worker: Worker) => void): this; + once(event: 'exit', listener: (worker: Worker, code: number, signal: string) => void): this; + once(event: 'fork', listener: (worker: Worker) => void): this; + once(event: 'listening', listener: (worker: Worker, address: Address) => void): this; + once(event: 'message', listener: (worker: Worker, message: any, handle: net.Socket | net.Server) => void): this; // the handle is a net.Socket or net.Server object, or undefined. + once(event: 'online', listener: (worker: Worker) => void): this; + once(event: 'setup', listener: (settings: ClusterSettings) => void): this; + prependListener(event: string, listener: (...args: any[]) => void): this; + prependListener(event: 'disconnect', listener: (worker: Worker) => void): this; + prependListener(event: 'exit', listener: (worker: Worker, code: number, signal: string) => void): this; + prependListener(event: 'fork', listener: (worker: Worker) => void): this; + prependListener(event: 'listening', listener: (worker: Worker, address: Address) => void): this; + // the handle is a net.Socket or net.Server object, or undefined. + prependListener(event: 'message', listener: (worker: Worker, message: any, handle?: net.Socket | net.Server) => void): this; + prependListener(event: 'online', listener: (worker: Worker) => void): this; + prependListener(event: 'setup', listener: (settings: ClusterSettings) => void): this; + prependOnceListener(event: string, listener: (...args: any[]) => void): this; + prependOnceListener(event: 'disconnect', listener: (worker: Worker) => void): this; + prependOnceListener(event: 'exit', listener: (worker: Worker, code: number, signal: string) => void): this; + prependOnceListener(event: 'fork', listener: (worker: Worker) => void): this; + prependOnceListener(event: 'listening', listener: (worker: Worker, address: Address) => void): this; + // the handle is a net.Socket or net.Server object, or undefined. + prependOnceListener(event: 'message', listener: (worker: Worker, message: any, handle: net.Socket | net.Server) => void): this; + prependOnceListener(event: 'online', listener: (worker: Worker) => void): this; + prependOnceListener(event: 'setup', listener: (settings: ClusterSettings) => void): this; + } + const cluster: Cluster; + export default cluster; +} +declare module 'node:cluster' { + export * from 'cluster'; + export { default as default } from 'cluster'; +} diff --git a/ts-ticket-office-service/node_modules/@types/node/console.d.ts b/ts-ticket-office-service/node_modules/@types/node/console.d.ts new file mode 100755 index 000000000..16c9137ad --- /dev/null +++ b/ts-ticket-office-service/node_modules/@types/node/console.d.ts @@ -0,0 +1,412 @@ +/** + * The `console` module provides a simple debugging console that is similar to the + * JavaScript console mechanism provided by web browsers. + * + * The module exports two specific components: + * + * * A `Console` class with methods such as `console.log()`, `console.error()` and`console.warn()` that can be used to write to any Node.js stream. + * * A global `console` instance configured to write to `process.stdout` and `process.stderr`. The global `console` can be used without calling`require('console')`. + * + * _**Warning**_: The global console object's methods are neither consistently + * synchronous like the browser APIs they resemble, nor are they consistently + * asynchronous like all other Node.js streams. See the `note on process I/O` for + * more information. + * + * Example using the global `console`: + * + * ```js + * console.log('hello world'); + * // Prints: hello world, to stdout + * console.log('hello %s', 'world'); + * // Prints: hello world, to stdout + * console.error(new Error('Whoops, something bad happened')); + * // Prints error message and stack trace to stderr: + * // Error: Whoops, something bad happened + * // at [eval]:5:15 + * // at Script.runInThisContext (node:vm:132:18) + * // at Object.runInThisContext (node:vm:309:38) + * // at node:internal/process/execution:77:19 + * // at [eval]-wrapper:6:22 + * // at evalScript (node:internal/process/execution:76:60) + * // at node:internal/main/eval_string:23:3 + * + * const name = 'Will Robinson'; + * console.warn(`Danger ${name}! Danger!`); + * // Prints: Danger Will Robinson! Danger!, to stderr + * ``` + * + * Example using the `Console` class: + * + * ```js + * const out = getStreamSomehow(); + * const err = getStreamSomehow(); + * const myConsole = new console.Console(out, err); + * + * myConsole.log('hello world'); + * // Prints: hello world, to out + * myConsole.log('hello %s', 'world'); + * // Prints: hello world, to out + * myConsole.error(new Error('Whoops, something bad happened')); + * // Prints: [Error: Whoops, something bad happened], to err + * + * const name = 'Will Robinson'; + * myConsole.warn(`Danger ${name}! Danger!`); + * // Prints: Danger Will Robinson! Danger!, to err + * ``` + * @see [source](https://github.com/nodejs/node/blob/v18.0.0/lib/console.js) + */ +declare module 'console' { + import console = require('node:console'); + export = console; +} +declare module 'node:console' { + import { InspectOptions } from 'node:util'; + global { + // This needs to be global to avoid TS2403 in case lib.dom.d.ts is present in the same build + interface Console { + Console: console.ConsoleConstructor; + /** + * `console.assert()` writes a message if `value` is [falsy](https://developer.mozilla.org/en-US/docs/Glossary/Falsy) or omitted. It only + * writes a message and does not otherwise affect execution. The output always + * starts with `"Assertion failed"`. If provided, `message` is formatted using `util.format()`. + * + * If `value` is [truthy](https://developer.mozilla.org/en-US/docs/Glossary/Truthy), nothing happens. + * + * ```js + * console.assert(true, 'does nothing'); + * + * console.assert(false, 'Whoops %s work', 'didn\'t'); + * // Assertion failed: Whoops didn't work + * + * console.assert(); + * // Assertion failed + * ``` + * @since v0.1.101 + * @param value The value tested for being truthy. + * @param message All arguments besides `value` are used as error message. + */ + assert(value: any, message?: string, ...optionalParams: any[]): void; + /** + * When `stdout` is a TTY, calling `console.clear()` will attempt to clear the + * TTY. When `stdout` is not a TTY, this method does nothing. + * + * The specific operation of `console.clear()` can vary across operating systems + * and terminal types. For most Linux operating systems, `console.clear()`operates similarly to the `clear` shell command. On Windows, `console.clear()`will clear only the output in the + * current terminal viewport for the Node.js + * binary. + * @since v8.3.0 + */ + clear(): void; + /** + * Maintains an internal counter specific to `label` and outputs to `stdout` the + * number of times `console.count()` has been called with the given `label`. + * + * ```js + * > console.count() + * default: 1 + * undefined + * > console.count('default') + * default: 2 + * undefined + * > console.count('abc') + * abc: 1 + * undefined + * > console.count('xyz') + * xyz: 1 + * undefined + * > console.count('abc') + * abc: 2 + * undefined + * > console.count() + * default: 3 + * undefined + * > + * ``` + * @since v8.3.0 + * @param label The display label for the counter. + */ + count(label?: string): void; + /** + * Resets the internal counter specific to `label`. + * + * ```js + * > console.count('abc'); + * abc: 1 + * undefined + * > console.countReset('abc'); + * undefined + * > console.count('abc'); + * abc: 1 + * undefined + * > + * ``` + * @since v8.3.0 + * @param label The display label for the counter. + */ + countReset(label?: string): void; + /** + * The `console.debug()` function is an alias for {@link log}. + * @since v8.0.0 + */ + debug(message?: any, ...optionalParams: any[]): void; + /** + * Uses `util.inspect()` on `obj` and prints the resulting string to `stdout`. + * This function bypasses any custom `inspect()` function defined on `obj`. + * @since v0.1.101 + */ + dir(obj: any, options?: InspectOptions): void; + /** + * This method calls `console.log()` passing it the arguments received. + * This method does not produce any XML formatting. + * @since v8.0.0 + */ + dirxml(...data: any[]): void; + /** + * Prints to `stderr` with newline. Multiple arguments can be passed, with the + * first used as the primary message and all additional used as substitution + * values similar to [`printf(3)`](http://man7.org/linux/man-pages/man3/printf.3.html) (the arguments are all passed to `util.format()`). + * + * ```js + * const code = 5; + * console.error('error #%d', code); + * // Prints: error #5, to stderr + * console.error('error', code); + * // Prints: error 5, to stderr + * ``` + * + * If formatting elements (e.g. `%d`) are not found in the first string then `util.inspect()` is called on each argument and the resulting string + * values are concatenated. See `util.format()` for more information. + * @since v0.1.100 + */ + error(message?: any, ...optionalParams: any[]): void; + /** + * Increases indentation of subsequent lines by spaces for `groupIndentation`length. + * + * If one or more `label`s are provided, those are printed first without the + * additional indentation. + * @since v8.5.0 + */ + group(...label: any[]): void; + /** + * An alias for {@link group}. + * @since v8.5.0 + */ + groupCollapsed(...label: any[]): void; + /** + * Decreases indentation of subsequent lines by spaces for `groupIndentation`length. + * @since v8.5.0 + */ + groupEnd(): void; + /** + * The `console.info()` function is an alias for {@link log}. + * @since v0.1.100 + */ + info(message?: any, ...optionalParams: any[]): void; + /** + * Prints to `stdout` with newline. Multiple arguments can be passed, with the + * first used as the primary message and all additional used as substitution + * values similar to [`printf(3)`](http://man7.org/linux/man-pages/man3/printf.3.html) (the arguments are all passed to `util.format()`). + * + * ```js + * const count = 5; + * console.log('count: %d', count); + * // Prints: count: 5, to stdout + * console.log('count:', count); + * // Prints: count: 5, to stdout + * ``` + * + * See `util.format()` for more information. + * @since v0.1.100 + */ + log(message?: any, ...optionalParams: any[]): void; + /** + * Try to construct a table with the columns of the properties of `tabularData`(or use `properties`) and rows of `tabularData` and log it. Falls back to just + * logging the argument if it can’t be parsed as tabular. + * + * ```js + * // These can't be parsed as tabular data + * console.table(Symbol()); + * // Symbol() + * + * console.table(undefined); + * // undefined + * + * console.table([{ a: 1, b: 'Y' }, { a: 'Z', b: 2 }]); + * // ┌─────────┬─────┬─────┐ + * // │ (index) │ a │ b │ + * // ├─────────┼─────┼─────┤ + * // │ 0 │ 1 │ 'Y' │ + * // │ 1 │ 'Z' │ 2 │ + * // └─────────┴─────┴─────┘ + * + * console.table([{ a: 1, b: 'Y' }, { a: 'Z', b: 2 }], ['a']); + * // ┌─────────┬─────┐ + * // │ (index) │ a │ + * // ├─────────┼─────┤ + * // │ 0 │ 1 │ + * // │ 1 │ 'Z' │ + * // └─────────┴─────┘ + * ``` + * @since v10.0.0 + * @param properties Alternate properties for constructing the table. + */ + table(tabularData: any, properties?: ReadonlyArray): void; + /** + * Starts a timer that can be used to compute the duration of an operation. Timers + * are identified by a unique `label`. Use the same `label` when calling {@link timeEnd} to stop the timer and output the elapsed time in + * suitable time units to `stdout`. For example, if the elapsed + * time is 3869ms, `console.timeEnd()` displays "3.869s". + * @since v0.1.104 + */ + time(label?: string): void; + /** + * Stops a timer that was previously started by calling {@link time} and + * prints the result to `stdout`: + * + * ```js + * console.time('100-elements'); + * for (let i = 0; i < 100; i++) {} + * console.timeEnd('100-elements'); + * // prints 100-elements: 225.438ms + * ``` + * @since v0.1.104 + */ + timeEnd(label?: string): void; + /** + * For a timer that was previously started by calling {@link time}, prints + * the elapsed time and other `data` arguments to `stdout`: + * + * ```js + * console.time('process'); + * const value = expensiveProcess1(); // Returns 42 + * console.timeLog('process', value); + * // Prints "process: 365.227ms 42". + * doExpensiveProcess2(value); + * console.timeEnd('process'); + * ``` + * @since v10.7.0 + */ + timeLog(label?: string, ...data: any[]): void; + /** + * Prints to `stderr` the string `'Trace: '`, followed by the `util.format()` formatted message and stack trace to the current position in the code. + * + * ```js + * console.trace('Show me'); + * // Prints: (stack trace will vary based on where trace is called) + * // Trace: Show me + * // at repl:2:9 + * // at REPLServer.defaultEval (repl.js:248:27) + * // at bound (domain.js:287:14) + * // at REPLServer.runBound [as eval] (domain.js:300:12) + * // at REPLServer. (repl.js:412:12) + * // at emitOne (events.js:82:20) + * // at REPLServer.emit (events.js:169:7) + * // at REPLServer.Interface._onLine (readline.js:210:10) + * // at REPLServer.Interface._line (readline.js:549:8) + * // at REPLServer.Interface._ttyWrite (readline.js:826:14) + * ``` + * @since v0.1.104 + */ + trace(message?: any, ...optionalParams: any[]): void; + /** + * The `console.warn()` function is an alias for {@link error}. + * @since v0.1.100 + */ + warn(message?: any, ...optionalParams: any[]): void; + // --- Inspector mode only --- + /** + * This method does not display anything unless used in the inspector. + * Starts a JavaScript CPU profile with an optional label. + */ + profile(label?: string): void; + /** + * This method does not display anything unless used in the inspector. + * Stops the current JavaScript CPU profiling session if one has been started and prints the report to the Profiles panel of the inspector. + */ + profileEnd(label?: string): void; + /** + * This method does not display anything unless used in the inspector. + * Adds an event with the label `label` to the Timeline panel of the inspector. + */ + timeStamp(label?: string): void; + } + /** + * The `console` module provides a simple debugging console that is similar to the + * JavaScript console mechanism provided by web browsers. + * + * The module exports two specific components: + * + * * A `Console` class with methods such as `console.log()`, `console.error()` and`console.warn()` that can be used to write to any Node.js stream. + * * A global `console` instance configured to write to `process.stdout` and `process.stderr`. The global `console` can be used without calling`require('console')`. + * + * _**Warning**_: The global console object's methods are neither consistently + * synchronous like the browser APIs they resemble, nor are they consistently + * asynchronous like all other Node.js streams. See the `note on process I/O` for + * more information. + * + * Example using the global `console`: + * + * ```js + * console.log('hello world'); + * // Prints: hello world, to stdout + * console.log('hello %s', 'world'); + * // Prints: hello world, to stdout + * console.error(new Error('Whoops, something bad happened')); + * // Prints error message and stack trace to stderr: + * // Error: Whoops, something bad happened + * // at [eval]:5:15 + * // at Script.runInThisContext (node:vm:132:18) + * // at Object.runInThisContext (node:vm:309:38) + * // at node:internal/process/execution:77:19 + * // at [eval]-wrapper:6:22 + * // at evalScript (node:internal/process/execution:76:60) + * // at node:internal/main/eval_string:23:3 + * + * const name = 'Will Robinson'; + * console.warn(`Danger ${name}! Danger!`); + * // Prints: Danger Will Robinson! Danger!, to stderr + * ``` + * + * Example using the `Console` class: + * + * ```js + * const out = getStreamSomehow(); + * const err = getStreamSomehow(); + * const myConsole = new console.Console(out, err); + * + * myConsole.log('hello world'); + * // Prints: hello world, to out + * myConsole.log('hello %s', 'world'); + * // Prints: hello world, to out + * myConsole.error(new Error('Whoops, something bad happened')); + * // Prints: [Error: Whoops, something bad happened], to err + * + * const name = 'Will Robinson'; + * myConsole.warn(`Danger ${name}! Danger!`); + * // Prints: Danger Will Robinson! Danger!, to err + * ``` + * @see [source](https://github.com/nodejs/node/blob/v16.4.2/lib/console.js) + */ + namespace console { + interface ConsoleConstructorOptions { + stdout: NodeJS.WritableStream; + stderr?: NodeJS.WritableStream | undefined; + ignoreErrors?: boolean | undefined; + colorMode?: boolean | 'auto' | undefined; + inspectOptions?: InspectOptions | undefined; + /** + * Set group indentation + * @default 2 + */ + groupIndentation?: number | undefined; + } + interface ConsoleConstructor { + prototype: Console; + new (stdout: NodeJS.WritableStream, stderr?: NodeJS.WritableStream, ignoreErrors?: boolean): Console; + new (options: ConsoleConstructorOptions): Console; + } + } + var console: Console; + } + export = globalThis.console; +} diff --git a/ts-ticket-office-service/node_modules/@types/node/constants.d.ts b/ts-ticket-office-service/node_modules/@types/node/constants.d.ts new file mode 100755 index 000000000..208020dcb --- /dev/null +++ b/ts-ticket-office-service/node_modules/@types/node/constants.d.ts @@ -0,0 +1,18 @@ +/** @deprecated since v6.3.0 - use constants property exposed by the relevant module instead. */ +declare module 'constants' { + import { constants as osConstants, SignalConstants } from 'node:os'; + import { constants as cryptoConstants } from 'node:crypto'; + import { constants as fsConstants } from 'node:fs'; + + const exp: typeof osConstants.errno & + typeof osConstants.priority & + SignalConstants & + typeof cryptoConstants & + typeof fsConstants; + export = exp; +} + +declare module 'node:constants' { + import constants = require('constants'); + export = constants; +} diff --git a/ts-ticket-office-service/node_modules/@types/node/crypto.d.ts b/ts-ticket-office-service/node_modules/@types/node/crypto.d.ts new file mode 100755 index 000000000..e127518d9 --- /dev/null +++ b/ts-ticket-office-service/node_modules/@types/node/crypto.d.ts @@ -0,0 +1,3964 @@ +/** + * The `crypto` module provides cryptographic functionality that includes a set of + * wrappers for OpenSSL's hash, HMAC, cipher, decipher, sign, and verify functions. + * + * ```js + * const { createHmac } = await import('crypto'); + * + * const secret = 'abcdefg'; + * const hash = createHmac('sha256', secret) + * .update('I love cupcakes') + * .digest('hex'); + * console.log(hash); + * // Prints: + * // c0fa1bc00531bd78ef38c628449c5102aeabd49b5dc3a2a516ea6ea959d6658e + * ``` + * @see [source](https://github.com/nodejs/node/blob/v18.0.0/lib/crypto.js) + */ +declare module 'crypto' { + import * as stream from 'node:stream'; + import { PeerCertificate } from 'node:tls'; + /** + * SPKAC is a Certificate Signing Request mechanism originally implemented by + * Netscape and was specified formally as part of [HTML5's `keygen` element](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/keygen). + * + * `` is deprecated since [HTML 5.2](https://www.w3.org/TR/html52/changes.html#features-removed) and new projects + * should not use this element anymore. + * + * The `crypto` module provides the `Certificate` class for working with SPKAC + * data. The most common usage is handling output generated by the HTML5`` element. Node.js uses [OpenSSL's SPKAC + * implementation](https://www.openssl.org/docs/man1.1.0/apps/openssl-spkac.html) internally. + * @since v0.11.8 + */ + class Certificate { + /** + * ```js + * const { Certificate } = await import('crypto'); + * const spkac = getSpkacSomehow(); + * const challenge = Certificate.exportChallenge(spkac); + * console.log(challenge.toString('utf8')); + * // Prints: the challenge as a UTF8 string + * ``` + * @since v9.0.0 + * @param encoding The `encoding` of the `spkac` string. + * @return The challenge component of the `spkac` data structure, which includes a public key and a challenge. + */ + static exportChallenge(spkac: BinaryLike): Buffer; + /** + * ```js + * const { Certificate } = await import('crypto'); + * const spkac = getSpkacSomehow(); + * const publicKey = Certificate.exportPublicKey(spkac); + * console.log(publicKey); + * // Prints: the public key as + * ``` + * @since v9.0.0 + * @param encoding The `encoding` of the `spkac` string. + * @return The public key component of the `spkac` data structure, which includes a public key and a challenge. + */ + static exportPublicKey(spkac: BinaryLike, encoding?: string): Buffer; + /** + * ```js + * import { Buffer } from 'buffer'; + * const { Certificate } = await import('crypto'); + * + * const spkac = getSpkacSomehow(); + * console.log(Certificate.verifySpkac(Buffer.from(spkac))); + * // Prints: true or false + * ``` + * @since v9.0.0 + * @param encoding The `encoding` of the `spkac` string. + * @return `true` if the given `spkac` data structure is valid, `false` otherwise. + */ + static verifySpkac(spkac: NodeJS.ArrayBufferView): boolean; + /** + * @deprecated + * @param spkac + * @returns The challenge component of the `spkac` data structure, + * which includes a public key and a challenge. + */ + exportChallenge(spkac: BinaryLike): Buffer; + /** + * @deprecated + * @param spkac + * @param encoding The encoding of the spkac string. + * @returns The public key component of the `spkac` data structure, + * which includes a public key and a challenge. + */ + exportPublicKey(spkac: BinaryLike, encoding?: string): Buffer; + /** + * @deprecated + * @param spkac + * @returns `true` if the given `spkac` data structure is valid, + * `false` otherwise. + */ + verifySpkac(spkac: NodeJS.ArrayBufferView): boolean; + } + namespace constants { + // https://nodejs.org/dist/latest-v10.x/docs/api/crypto.html#crypto_crypto_constants + const OPENSSL_VERSION_NUMBER: number; + /** Applies multiple bug workarounds within OpenSSL. See https://www.openssl.org/docs/man1.0.2/ssl/SSL_CTX_set_options.html for detail. */ + const SSL_OP_ALL: number; + /** Allows legacy insecure renegotiation between OpenSSL and unpatched clients or servers. See https://www.openssl.org/docs/man1.0.2/ssl/SSL_CTX_set_options.html. */ + const SSL_OP_ALLOW_UNSAFE_LEGACY_RENEGOTIATION: number; + /** Attempts to use the server's preferences instead of the client's when selecting a cipher. See https://www.openssl.org/docs/man1.0.2/ssl/SSL_CTX_set_options.html. */ + const SSL_OP_CIPHER_SERVER_PREFERENCE: number; + /** Instructs OpenSSL to use Cisco's "speshul" version of DTLS_BAD_VER. */ + const SSL_OP_CISCO_ANYCONNECT: number; + /** Instructs OpenSSL to turn on cookie exchange. */ + const SSL_OP_COOKIE_EXCHANGE: number; + /** Instructs OpenSSL to add server-hello extension from an early version of the cryptopro draft. */ + const SSL_OP_CRYPTOPRO_TLSEXT_BUG: number; + /** Instructs OpenSSL to disable a SSL 3.0/TLS 1.0 vulnerability workaround added in OpenSSL 0.9.6d. */ + const SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS: number; + /** Instructs OpenSSL to always use the tmp_rsa key when performing RSA operations. */ + const SSL_OP_EPHEMERAL_RSA: number; + /** Allows initial connection to servers that do not support RI. */ + const SSL_OP_LEGACY_SERVER_CONNECT: number; + const SSL_OP_MICROSOFT_BIG_SSLV3_BUFFER: number; + const SSL_OP_MICROSOFT_SESS_ID_BUG: number; + /** Instructs OpenSSL to disable the workaround for a man-in-the-middle protocol-version vulnerability in the SSL 2.0 server implementation. */ + const SSL_OP_MSIE_SSLV2_RSA_PADDING: number; + const SSL_OP_NETSCAPE_CA_DN_BUG: number; + const SSL_OP_NETSCAPE_CHALLENGE_BUG: number; + const SSL_OP_NETSCAPE_DEMO_CIPHER_CHANGE_BUG: number; + const SSL_OP_NETSCAPE_REUSE_CIPHER_CHANGE_BUG: number; + /** Instructs OpenSSL to disable support for SSL/TLS compression. */ + const SSL_OP_NO_COMPRESSION: number; + const SSL_OP_NO_QUERY_MTU: number; + /** Instructs OpenSSL to always start a new session when performing renegotiation. */ + const SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION: number; + const SSL_OP_NO_SSLv2: number; + const SSL_OP_NO_SSLv3: number; + const SSL_OP_NO_TICKET: number; + const SSL_OP_NO_TLSv1: number; + const SSL_OP_NO_TLSv1_1: number; + const SSL_OP_NO_TLSv1_2: number; + const SSL_OP_PKCS1_CHECK_1: number; + const SSL_OP_PKCS1_CHECK_2: number; + /** Instructs OpenSSL to always create a new key when using temporary/ephemeral DH parameters. */ + const SSL_OP_SINGLE_DH_USE: number; + /** Instructs OpenSSL to always create a new key when using temporary/ephemeral ECDH parameters. */ + const SSL_OP_SINGLE_ECDH_USE: number; + const SSL_OP_SSLEAY_080_CLIENT_DH_BUG: number; + const SSL_OP_SSLREF2_REUSE_CERT_TYPE_BUG: number; + const SSL_OP_TLS_BLOCK_PADDING_BUG: number; + const SSL_OP_TLS_D5_BUG: number; + /** Instructs OpenSSL to disable version rollback attack detection. */ + const SSL_OP_TLS_ROLLBACK_BUG: number; + const ENGINE_METHOD_RSA: number; + const ENGINE_METHOD_DSA: number; + const ENGINE_METHOD_DH: number; + const ENGINE_METHOD_RAND: number; + const ENGINE_METHOD_EC: number; + const ENGINE_METHOD_CIPHERS: number; + const ENGINE_METHOD_DIGESTS: number; + const ENGINE_METHOD_PKEY_METHS: number; + const ENGINE_METHOD_PKEY_ASN1_METHS: number; + const ENGINE_METHOD_ALL: number; + const ENGINE_METHOD_NONE: number; + const DH_CHECK_P_NOT_SAFE_PRIME: number; + const DH_CHECK_P_NOT_PRIME: number; + const DH_UNABLE_TO_CHECK_GENERATOR: number; + const DH_NOT_SUITABLE_GENERATOR: number; + const ALPN_ENABLED: number; + const RSA_PKCS1_PADDING: number; + const RSA_SSLV23_PADDING: number; + const RSA_NO_PADDING: number; + const RSA_PKCS1_OAEP_PADDING: number; + const RSA_X931_PADDING: number; + const RSA_PKCS1_PSS_PADDING: number; + /** Sets the salt length for RSA_PKCS1_PSS_PADDING to the digest size when signing or verifying. */ + const RSA_PSS_SALTLEN_DIGEST: number; + /** Sets the salt length for RSA_PKCS1_PSS_PADDING to the maximum permissible value when signing data. */ + const RSA_PSS_SALTLEN_MAX_SIGN: number; + /** Causes the salt length for RSA_PKCS1_PSS_PADDING to be determined automatically when verifying a signature. */ + const RSA_PSS_SALTLEN_AUTO: number; + const POINT_CONVERSION_COMPRESSED: number; + const POINT_CONVERSION_UNCOMPRESSED: number; + const POINT_CONVERSION_HYBRID: number; + /** Specifies the built-in default cipher list used by Node.js (colon-separated values). */ + const defaultCoreCipherList: string; + /** Specifies the active default cipher list used by the current Node.js process (colon-separated values). */ + const defaultCipherList: string; + } + interface HashOptions extends stream.TransformOptions { + /** + * For XOF hash functions such as `shake256`, the + * outputLength option can be used to specify the desired output length in bytes. + */ + outputLength?: number | undefined; + } + /** @deprecated since v10.0.0 */ + const fips: boolean; + /** + * Creates and returns a `Hash` object that can be used to generate hash digests + * using the given `algorithm`. Optional `options` argument controls stream + * behavior. For XOF hash functions such as `'shake256'`, the `outputLength` option + * can be used to specify the desired output length in bytes. + * + * The `algorithm` is dependent on the available algorithms supported by the + * version of OpenSSL on the platform. Examples are `'sha256'`, `'sha512'`, etc. + * On recent releases of OpenSSL, `openssl list -digest-algorithms` will + * display the available digest algorithms. + * + * Example: generating the sha256 sum of a file + * + * ```js + * import { + * createReadStream + * } from 'fs'; + * import { argv } from 'process'; + * const { + * createHash + * } = await import('crypto'); + * + * const filename = argv[2]; + * + * const hash = createHash('sha256'); + * + * const input = createReadStream(filename); + * input.on('readable', () => { + * // Only one element is going to be produced by the + * // hash stream. + * const data = input.read(); + * if (data) + * hash.update(data); + * else { + * console.log(`${hash.digest('hex')} ${filename}`); + * } + * }); + * ``` + * @since v0.1.92 + * @param options `stream.transform` options + */ + function createHash(algorithm: string, options?: HashOptions): Hash; + /** + * Creates and returns an `Hmac` object that uses the given `algorithm` and `key`. + * Optional `options` argument controls stream behavior. + * + * The `algorithm` is dependent on the available algorithms supported by the + * version of OpenSSL on the platform. Examples are `'sha256'`, `'sha512'`, etc. + * On recent releases of OpenSSL, `openssl list -digest-algorithms` will + * display the available digest algorithms. + * + * The `key` is the HMAC key used to generate the cryptographic HMAC hash. If it is + * a `KeyObject`, its type must be `secret`. + * + * Example: generating the sha256 HMAC of a file + * + * ```js + * import { + * createReadStream + * } from 'fs'; + * import { argv } from 'process'; + * const { + * createHmac + * } = await import('crypto'); + * + * const filename = argv[2]; + * + * const hmac = createHmac('sha256', 'a secret'); + * + * const input = createReadStream(filename); + * input.on('readable', () => { + * // Only one element is going to be produced by the + * // hash stream. + * const data = input.read(); + * if (data) + * hmac.update(data); + * else { + * console.log(`${hmac.digest('hex')} ${filename}`); + * } + * }); + * ``` + * @since v0.1.94 + * @param options `stream.transform` options + */ + function createHmac(algorithm: string, key: BinaryLike | KeyObject, options?: stream.TransformOptions): Hmac; + // https://nodejs.org/api/buffer.html#buffer_buffers_and_character_encodings + type BinaryToTextEncoding = 'base64' | 'base64url' | 'hex' | 'binary'; + type CharacterEncoding = 'utf8' | 'utf-8' | 'utf16le' | 'latin1'; + type LegacyCharacterEncoding = 'ascii' | 'binary' | 'ucs2' | 'ucs-2'; + type Encoding = BinaryToTextEncoding | CharacterEncoding | LegacyCharacterEncoding; + type ECDHKeyFormat = 'compressed' | 'uncompressed' | 'hybrid'; + /** + * The `Hash` class is a utility for creating hash digests of data. It can be + * used in one of two ways: + * + * * As a `stream` that is both readable and writable, where data is written + * to produce a computed hash digest on the readable side, or + * * Using the `hash.update()` and `hash.digest()` methods to produce the + * computed hash. + * + * The {@link createHash} method is used to create `Hash` instances. `Hash`objects are not to be created directly using the `new` keyword. + * + * Example: Using `Hash` objects as streams: + * + * ```js + * const { + * createHash + * } = await import('crypto'); + * + * const hash = createHash('sha256'); + * + * hash.on('readable', () => { + * // Only one element is going to be produced by the + * // hash stream. + * const data = hash.read(); + * if (data) { + * console.log(data.toString('hex')); + * // Prints: + * // 6a2da20943931e9834fc12cfe5bb47bbd9ae43489a30726962b576f4e3993e50 + * } + * }); + * + * hash.write('some data to hash'); + * hash.end(); + * ``` + * + * Example: Using `Hash` and piped streams: + * + * ```js + * import { createReadStream } from 'fs'; + * import { stdout } from 'process'; + * const { createHash } = await import('crypto'); + * + * const hash = createHash('sha256'); + * + * const input = createReadStream('test.js'); + * input.pipe(hash).setEncoding('hex').pipe(stdout); + * ``` + * + * Example: Using the `hash.update()` and `hash.digest()` methods: + * + * ```js + * const { + * createHash + * } = await import('crypto'); + * + * const hash = createHash('sha256'); + * + * hash.update('some data to hash'); + * console.log(hash.digest('hex')); + * // Prints: + * // 6a2da20943931e9834fc12cfe5bb47bbd9ae43489a30726962b576f4e3993e50 + * ``` + * @since v0.1.92 + */ + class Hash extends stream.Transform { + private constructor(); + /** + * Creates a new `Hash` object that contains a deep copy of the internal state + * of the current `Hash` object. + * + * The optional `options` argument controls stream behavior. For XOF hash + * functions such as `'shake256'`, the `outputLength` option can be used to + * specify the desired output length in bytes. + * + * An error is thrown when an attempt is made to copy the `Hash` object after + * its `hash.digest()` method has been called. + * + * ```js + * // Calculate a rolling hash. + * const { + * createHash + * } = await import('crypto'); + * + * const hash = createHash('sha256'); + * + * hash.update('one'); + * console.log(hash.copy().digest('hex')); + * + * hash.update('two'); + * console.log(hash.copy().digest('hex')); + * + * hash.update('three'); + * console.log(hash.copy().digest('hex')); + * + * // Etc. + * ``` + * @since v13.1.0 + * @param options `stream.transform` options + */ + copy(options?: stream.TransformOptions): Hash; + /** + * Updates the hash content with the given `data`, the encoding of which + * is given in `inputEncoding`. + * If `encoding` is not provided, and the `data` is a string, an + * encoding of `'utf8'` is enforced. If `data` is a `Buffer`, `TypedArray`, or`DataView`, then `inputEncoding` is ignored. + * + * This can be called many times with new data as it is streamed. + * @since v0.1.92 + * @param inputEncoding The `encoding` of the `data` string. + */ + update(data: BinaryLike): Hash; + update(data: string, inputEncoding: Encoding): Hash; + /** + * Calculates the digest of all of the data passed to be hashed (using the `hash.update()` method). + * If `encoding` is provided a string will be returned; otherwise + * a `Buffer` is returned. + * + * The `Hash` object can not be used again after `hash.digest()` method has been + * called. Multiple calls will cause an error to be thrown. + * @since v0.1.92 + * @param encoding The `encoding` of the return value. + */ + digest(): Buffer; + digest(encoding: BinaryToTextEncoding): string; + } + /** + * The `Hmac` class is a utility for creating cryptographic HMAC digests. It can + * be used in one of two ways: + * + * * As a `stream` that is both readable and writable, where data is written + * to produce a computed HMAC digest on the readable side, or + * * Using the `hmac.update()` and `hmac.digest()` methods to produce the + * computed HMAC digest. + * + * The {@link createHmac} method is used to create `Hmac` instances. `Hmac`objects are not to be created directly using the `new` keyword. + * + * Example: Using `Hmac` objects as streams: + * + * ```js + * const { + * createHmac + * } = await import('crypto'); + * + * const hmac = createHmac('sha256', 'a secret'); + * + * hmac.on('readable', () => { + * // Only one element is going to be produced by the + * // hash stream. + * const data = hmac.read(); + * if (data) { + * console.log(data.toString('hex')); + * // Prints: + * // 7fd04df92f636fd450bc841c9418e5825c17f33ad9c87c518115a45971f7f77e + * } + * }); + * + * hmac.write('some data to hash'); + * hmac.end(); + * ``` + * + * Example: Using `Hmac` and piped streams: + * + * ```js + * import { createReadStream } from 'fs'; + * import { stdout } from 'process'; + * const { + * createHmac + * } = await import('crypto'); + * + * const hmac = createHmac('sha256', 'a secret'); + * + * const input = createReadStream('test.js'); + * input.pipe(hmac).pipe(stdout); + * ``` + * + * Example: Using the `hmac.update()` and `hmac.digest()` methods: + * + * ```js + * const { + * createHmac + * } = await import('crypto'); + * + * const hmac = createHmac('sha256', 'a secret'); + * + * hmac.update('some data to hash'); + * console.log(hmac.digest('hex')); + * // Prints: + * // 7fd04df92f636fd450bc841c9418e5825c17f33ad9c87c518115a45971f7f77e + * ``` + * @since v0.1.94 + */ + class Hmac extends stream.Transform { + private constructor(); + /** + * Updates the `Hmac` content with the given `data`, the encoding of which + * is given in `inputEncoding`. + * If `encoding` is not provided, and the `data` is a string, an + * encoding of `'utf8'` is enforced. If `data` is a `Buffer`, `TypedArray`, or`DataView`, then `inputEncoding` is ignored. + * + * This can be called many times with new data as it is streamed. + * @since v0.1.94 + * @param inputEncoding The `encoding` of the `data` string. + */ + update(data: BinaryLike): Hmac; + update(data: string, inputEncoding: Encoding): Hmac; + /** + * Calculates the HMAC digest of all of the data passed using `hmac.update()`. + * If `encoding` is + * provided a string is returned; otherwise a `Buffer` is returned; + * + * The `Hmac` object can not be used again after `hmac.digest()` has been + * called. Multiple calls to `hmac.digest()` will result in an error being thrown. + * @since v0.1.94 + * @param encoding The `encoding` of the return value. + */ + digest(): Buffer; + digest(encoding: BinaryToTextEncoding): string; + } + type KeyObjectType = 'secret' | 'public' | 'private'; + interface KeyExportOptions { + type: 'pkcs1' | 'spki' | 'pkcs8' | 'sec1'; + format: T; + cipher?: string | undefined; + passphrase?: string | Buffer | undefined; + } + interface JwkKeyExportOptions { + format: 'jwk'; + } + interface JsonWebKey { + crv?: string | undefined; + d?: string | undefined; + dp?: string | undefined; + dq?: string | undefined; + e?: string | undefined; + k?: string | undefined; + kty?: string | undefined; + n?: string | undefined; + p?: string | undefined; + q?: string | undefined; + qi?: string | undefined; + x?: string | undefined; + y?: string | undefined; + [key: string]: unknown; + } + interface AsymmetricKeyDetails { + /** + * Key size in bits (RSA, DSA). + */ + modulusLength?: number | undefined; + /** + * Public exponent (RSA). + */ + publicExponent?: bigint | undefined; + /** + * Name of the message digest (RSA-PSS). + */ + hashAlgorithm?: string | undefined; + /** + * Name of the message digest used by MGF1 (RSA-PSS). + */ + mgf1HashAlgorithm?: string | undefined; + /** + * Minimal salt length in bytes (RSA-PSS). + */ + saltLength?: number | undefined; + /** + * Size of q in bits (DSA). + */ + divisorLength?: number | undefined; + /** + * Name of the curve (EC). + */ + namedCurve?: string | undefined; + } + interface JwkKeyExportOptions { + format: 'jwk'; + } + /** + * Node.js uses a `KeyObject` class to represent a symmetric or asymmetric key, + * and each kind of key exposes different functions. The {@link createSecretKey}, {@link createPublicKey} and {@link createPrivateKey} methods are used to create `KeyObject`instances. `KeyObject` + * objects are not to be created directly using the `new`keyword. + * + * Most applications should consider using the new `KeyObject` API instead of + * passing keys as strings or `Buffer`s due to improved security features. + * + * `KeyObject` instances can be passed to other threads via `postMessage()`. + * The receiver obtains a cloned `KeyObject`, and the `KeyObject` does not need to + * be listed in the `transferList` argument. + * @since v11.6.0 + */ + class KeyObject { + private constructor(); + /** + * Example: Converting a `CryptoKey` instance to a `KeyObject`: + * + * ```js + * const { webcrypto, KeyObject } = await import('crypto'); + * const { subtle } = webcrypto; + * + * const key = await subtle.generateKey({ + * name: 'HMAC', + * hash: 'SHA-256', + * length: 256 + * }, true, ['sign', 'verify']); + * + * const keyObject = KeyObject.from(key); + * console.log(keyObject.symmetricKeySize); + * // Prints: 32 (symmetric key size in bytes) + * ``` + * @since v15.0.0 + */ + static from(key: webcrypto.CryptoKey): KeyObject; + /** + * For asymmetric keys, this property represents the type of the key. Supported key + * types are: + * + * * `'rsa'` (OID 1.2.840.113549.1.1.1) + * * `'rsa-pss'` (OID 1.2.840.113549.1.1.10) + * * `'dsa'` (OID 1.2.840.10040.4.1) + * * `'ec'` (OID 1.2.840.10045.2.1) + * * `'x25519'` (OID 1.3.101.110) + * * `'x448'` (OID 1.3.101.111) + * * `'ed25519'` (OID 1.3.101.112) + * * `'ed448'` (OID 1.3.101.113) + * * `'dh'` (OID 1.2.840.113549.1.3.1) + * + * This property is `undefined` for unrecognized `KeyObject` types and symmetric + * keys. + * @since v11.6.0 + */ + asymmetricKeyType?: KeyType | undefined; + /** + * For asymmetric keys, this property represents the size of the embedded key in + * bytes. This property is `undefined` for symmetric keys. + */ + asymmetricKeySize?: number | undefined; + /** + * This property exists only on asymmetric keys. Depending on the type of the key, + * this object contains information about the key. None of the information obtained + * through this property can be used to uniquely identify a key or to compromise + * the security of the key. + * + * For RSA-PSS keys, if the key material contains a `RSASSA-PSS-params` sequence, + * the `hashAlgorithm`, `mgf1HashAlgorithm`, and `saltLength` properties will be + * set. + * + * Other key details might be exposed via this API using additional attributes. + * @since v15.7.0 + */ + asymmetricKeyDetails?: AsymmetricKeyDetails | undefined; + /** + * For symmetric keys, the following encoding options can be used: + * + * For public keys, the following encoding options can be used: + * + * For private keys, the following encoding options can be used: + * + * The result type depends on the selected encoding format, when PEM the + * result is a string, when DER it will be a buffer containing the data + * encoded as DER, when [JWK](https://tools.ietf.org/html/rfc7517) it will be an object. + * + * When [JWK](https://tools.ietf.org/html/rfc7517) encoding format was selected, all other encoding options are + * ignored. + * + * PKCS#1, SEC1, and PKCS#8 type keys can be encrypted by using a combination of + * the `cipher` and `format` options. The PKCS#8 `type` can be used with any`format` to encrypt any key algorithm (RSA, EC, or DH) by specifying a`cipher`. PKCS#1 and SEC1 can only be + * encrypted by specifying a `cipher`when the PEM `format` is used. For maximum compatibility, use PKCS#8 for + * encrypted private keys. Since PKCS#8 defines its own + * encryption mechanism, PEM-level encryption is not supported when encrypting + * a PKCS#8 key. See [RFC 5208](https://www.rfc-editor.org/rfc/rfc5208.txt) for PKCS#8 encryption and [RFC 1421](https://www.rfc-editor.org/rfc/rfc1421.txt) for + * PKCS#1 and SEC1 encryption. + * @since v11.6.0 + */ + export(options: KeyExportOptions<'pem'>): string | Buffer; + export(options?: KeyExportOptions<'der'>): Buffer; + export(options?: JwkKeyExportOptions): JsonWebKey; + /** + * For secret keys, this property represents the size of the key in bytes. This + * property is `undefined` for asymmetric keys. + * @since v11.6.0 + */ + symmetricKeySize?: number | undefined; + /** + * Depending on the type of this `KeyObject`, this property is either`'secret'` for secret (symmetric) keys, `'public'` for public (asymmetric) keys + * or `'private'` for private (asymmetric) keys. + * @since v11.6.0 + */ + type: KeyObjectType; + } + type CipherCCMTypes = 'aes-128-ccm' | 'aes-192-ccm' | 'aes-256-ccm' | 'chacha20-poly1305'; + type CipherGCMTypes = 'aes-128-gcm' | 'aes-192-gcm' | 'aes-256-gcm'; + type CipherOCBTypes = 'aes-128-ocb' | 'aes-192-ocb' | 'aes-256-ocb'; + type BinaryLike = string | NodeJS.ArrayBufferView; + type CipherKey = BinaryLike | KeyObject; + interface CipherCCMOptions extends stream.TransformOptions { + authTagLength: number; + } + interface CipherGCMOptions extends stream.TransformOptions { + authTagLength?: number | undefined; + } + interface CipherOCBOptions extends stream.TransformOptions { + authTagLength: number; + } + /** + * Creates and returns a `Cipher` object that uses the given `algorithm` and`password`. + * + * The `options` argument controls stream behavior and is optional except when a + * cipher in CCM or OCB mode (e.g. `'aes-128-ccm'`) is used. In that case, the`authTagLength` option is required and specifies the length of the + * authentication tag in bytes, see `CCM mode`. In GCM mode, the `authTagLength`option is not required but can be used to set the length of the authentication + * tag that will be returned by `getAuthTag()` and defaults to 16 bytes. + * For `chacha20-poly1305`, the `authTagLength` option defaults to 16 bytes. + * + * The `algorithm` is dependent on OpenSSL, examples are `'aes192'`, etc. On + * recent OpenSSL releases, `openssl list -cipher-algorithms` will + * display the available cipher algorithms. + * + * The `password` is used to derive the cipher key and initialization vector (IV). + * The value must be either a `'latin1'` encoded string, a `Buffer`, a`TypedArray`, or a `DataView`. + * + * The implementation of `crypto.createCipher()` derives keys using the OpenSSL + * function [`EVP_BytesToKey`](https://www.openssl.org/docs/man1.1.0/crypto/EVP_BytesToKey.html) with the digest algorithm set to MD5, one + * iteration, and no salt. The lack of salt allows dictionary attacks as the same + * password always creates the same key. The low iteration count and + * non-cryptographically secure hash algorithm allow passwords to be tested very + * rapidly. + * + * In line with OpenSSL's recommendation to use a more modern algorithm instead of [`EVP_BytesToKey`](https://www.openssl.org/docs/man1.1.0/crypto/EVP_BytesToKey.html) it is recommended that + * developers derive a key and IV on + * their own using {@link scrypt} and to use {@link createCipheriv} to create the `Cipher` object. Users should not use ciphers with counter mode + * (e.g. CTR, GCM, or CCM) in `crypto.createCipher()`. A warning is emitted when + * they are used in order to avoid the risk of IV reuse that causes + * vulnerabilities. For the case when IV is reused in GCM, see [Nonce-Disrespecting Adversaries](https://github.com/nonce-disrespect/nonce-disrespect) for details. + * @since v0.1.94 + * @deprecated Since v10.0.0 - Use {@link createCipheriv} instead. + * @param options `stream.transform` options + */ + function createCipher(algorithm: CipherCCMTypes, password: BinaryLike, options: CipherCCMOptions): CipherCCM; + /** @deprecated since v10.0.0 use `createCipheriv()` */ + function createCipher(algorithm: CipherGCMTypes, password: BinaryLike, options?: CipherGCMOptions): CipherGCM; + /** @deprecated since v10.0.0 use `createCipheriv()` */ + function createCipher(algorithm: string, password: BinaryLike, options?: stream.TransformOptions): Cipher; + /** + * Creates and returns a `Cipher` object, with the given `algorithm`, `key` and + * initialization vector (`iv`). + * + * The `options` argument controls stream behavior and is optional except when a + * cipher in CCM or OCB mode (e.g. `'aes-128-ccm'`) is used. In that case, the`authTagLength` option is required and specifies the length of the + * authentication tag in bytes, see `CCM mode`. In GCM mode, the `authTagLength`option is not required but can be used to set the length of the authentication + * tag that will be returned by `getAuthTag()` and defaults to 16 bytes. + * For `chacha20-poly1305`, the `authTagLength` option defaults to 16 bytes. + * + * The `algorithm` is dependent on OpenSSL, examples are `'aes192'`, etc. On + * recent OpenSSL releases, `openssl list -cipher-algorithms` will + * display the available cipher algorithms. + * + * The `key` is the raw key used by the `algorithm` and `iv` is an [initialization vector](https://en.wikipedia.org/wiki/Initialization_vector). Both arguments must be `'utf8'` encoded + * strings,`Buffers`, `TypedArray`, or `DataView`s. The `key` may optionally be + * a `KeyObject` of type `secret`. If the cipher does not need + * an initialization vector, `iv` may be `null`. + * + * When passing strings for `key` or `iv`, please consider `caveats when using strings as inputs to cryptographic APIs`. + * + * Initialization vectors should be unpredictable and unique; ideally, they will be + * cryptographically random. They do not have to be secret: IVs are typically just + * added to ciphertext messages unencrypted. It may sound contradictory that + * something has to be unpredictable and unique, but does not have to be secret; + * remember that an attacker must not be able to predict ahead of time what a + * given IV will be. + * @since v0.1.94 + * @param options `stream.transform` options + */ + function createCipheriv(algorithm: CipherCCMTypes, key: CipherKey, iv: BinaryLike, options: CipherCCMOptions): CipherCCM; + function createCipheriv(algorithm: CipherOCBTypes, key: CipherKey, iv: BinaryLike, options: CipherOCBOptions): CipherOCB; + function createCipheriv(algorithm: CipherGCMTypes, key: CipherKey, iv: BinaryLike, options?: CipherGCMOptions): CipherGCM; + function createCipheriv(algorithm: string, key: CipherKey, iv: BinaryLike | null, options?: stream.TransformOptions): Cipher; + /** + * Instances of the `Cipher` class are used to encrypt data. The class can be + * used in one of two ways: + * + * * As a `stream` that is both readable and writable, where plain unencrypted + * data is written to produce encrypted data on the readable side, or + * * Using the `cipher.update()` and `cipher.final()` methods to produce + * the encrypted data. + * + * The {@link createCipher} or {@link createCipheriv} methods are + * used to create `Cipher` instances. `Cipher` objects are not to be created + * directly using the `new` keyword. + * + * Example: Using `Cipher` objects as streams: + * + * ```js + * const { + * scrypt, + * randomFill, + * createCipheriv + * } = await import('crypto'); + * + * const algorithm = 'aes-192-cbc'; + * const password = 'Password used to generate key'; + * + * // First, we'll generate the key. The key length is dependent on the algorithm. + * // In this case for aes192, it is 24 bytes (192 bits). + * scrypt(password, 'salt', 24, (err, key) => { + * if (err) throw err; + * // Then, we'll generate a random initialization vector + * randomFill(new Uint8Array(16), (err, iv) => { + * if (err) throw err; + * + * // Once we have the key and iv, we can create and use the cipher... + * const cipher = createCipheriv(algorithm, key, iv); + * + * let encrypted = ''; + * cipher.setEncoding('hex'); + * + * cipher.on('data', (chunk) => encrypted += chunk); + * cipher.on('end', () => console.log(encrypted)); + * + * cipher.write('some clear text data'); + * cipher.end(); + * }); + * }); + * ``` + * + * Example: Using `Cipher` and piped streams: + * + * ```js + * import { + * createReadStream, + * createWriteStream, + * } from 'fs'; + * + * import { + * pipeline + * } from 'stream'; + * + * const { + * scrypt, + * randomFill, + * createCipheriv + * } = await import('crypto'); + * + * const algorithm = 'aes-192-cbc'; + * const password = 'Password used to generate key'; + * + * // First, we'll generate the key. The key length is dependent on the algorithm. + * // In this case for aes192, it is 24 bytes (192 bits). + * scrypt(password, 'salt', 24, (err, key) => { + * if (err) throw err; + * // Then, we'll generate a random initialization vector + * randomFill(new Uint8Array(16), (err, iv) => { + * if (err) throw err; + * + * const cipher = createCipheriv(algorithm, key, iv); + * + * const input = createReadStream('test.js'); + * const output = createWriteStream('test.enc'); + * + * pipeline(input, cipher, output, (err) => { + * if (err) throw err; + * }); + * }); + * }); + * ``` + * + * Example: Using the `cipher.update()` and `cipher.final()` methods: + * + * ```js + * const { + * scrypt, + * randomFill, + * createCipheriv + * } = await import('crypto'); + * + * const algorithm = 'aes-192-cbc'; + * const password = 'Password used to generate key'; + * + * // First, we'll generate the key. The key length is dependent on the algorithm. + * // In this case for aes192, it is 24 bytes (192 bits). + * scrypt(password, 'salt', 24, (err, key) => { + * if (err) throw err; + * // Then, we'll generate a random initialization vector + * randomFill(new Uint8Array(16), (err, iv) => { + * if (err) throw err; + * + * const cipher = createCipheriv(algorithm, key, iv); + * + * let encrypted = cipher.update('some clear text data', 'utf8', 'hex'); + * encrypted += cipher.final('hex'); + * console.log(encrypted); + * }); + * }); + * ``` + * @since v0.1.94 + */ + class Cipher extends stream.Transform { + private constructor(); + /** + * Updates the cipher with `data`. If the `inputEncoding` argument is given, + * the `data`argument is a string using the specified encoding. If the `inputEncoding`argument is not given, `data` must be a `Buffer`, `TypedArray`, or`DataView`. If `data` is a `Buffer`, + * `TypedArray`, or `DataView`, then`inputEncoding` is ignored. + * + * The `outputEncoding` specifies the output format of the enciphered + * data. If the `outputEncoding`is specified, a string using the specified encoding is returned. If no`outputEncoding` is provided, a `Buffer` is returned. + * + * The `cipher.update()` method can be called multiple times with new data until `cipher.final()` is called. Calling `cipher.update()` after `cipher.final()` will result in an error being + * thrown. + * @since v0.1.94 + * @param inputEncoding The `encoding` of the data. + * @param outputEncoding The `encoding` of the return value. + */ + update(data: BinaryLike): Buffer; + update(data: string, inputEncoding: Encoding): Buffer; + update(data: NodeJS.ArrayBufferView, inputEncoding: undefined, outputEncoding: Encoding): string; + update(data: string, inputEncoding: Encoding | undefined, outputEncoding: Encoding): string; + /** + * Once the `cipher.final()` method has been called, the `Cipher` object can no + * longer be used to encrypt data. Attempts to call `cipher.final()` more than + * once will result in an error being thrown. + * @since v0.1.94 + * @param outputEncoding The `encoding` of the return value. + * @return Any remaining enciphered contents. If `outputEncoding` is specified, a string is returned. If an `outputEncoding` is not provided, a {@link Buffer} is returned. + */ + final(): Buffer; + final(outputEncoding: BufferEncoding): string; + /** + * When using block encryption algorithms, the `Cipher` class will automatically + * add padding to the input data to the appropriate block size. To disable the + * default padding call `cipher.setAutoPadding(false)`. + * + * When `autoPadding` is `false`, the length of the entire input data must be a + * multiple of the cipher's block size or `cipher.final()` will throw an error. + * Disabling automatic padding is useful for non-standard padding, for instance + * using `0x0` instead of PKCS padding. + * + * The `cipher.setAutoPadding()` method must be called before `cipher.final()`. + * @since v0.7.1 + * @param [autoPadding=true] + * @return for method chaining. + */ + setAutoPadding(autoPadding?: boolean): this; + } + interface CipherCCM extends Cipher { + setAAD( + buffer: NodeJS.ArrayBufferView, + options: { + plaintextLength: number; + } + ): this; + getAuthTag(): Buffer; + } + interface CipherGCM extends Cipher { + setAAD( + buffer: NodeJS.ArrayBufferView, + options?: { + plaintextLength: number; + } + ): this; + getAuthTag(): Buffer; + } + interface CipherOCB extends Cipher { + setAAD( + buffer: NodeJS.ArrayBufferView, + options?: { + plaintextLength: number; + } + ): this; + getAuthTag(): Buffer; + } + /** + * Creates and returns a `Decipher` object that uses the given `algorithm` and`password` (key). + * + * The `options` argument controls stream behavior and is optional except when a + * cipher in CCM or OCB mode (e.g. `'aes-128-ccm'`) is used. In that case, the`authTagLength` option is required and specifies the length of the + * authentication tag in bytes, see `CCM mode`. + * For `chacha20-poly1305`, the `authTagLength` option defaults to 16 bytes. + * + * The implementation of `crypto.createDecipher()` derives keys using the OpenSSL + * function [`EVP_BytesToKey`](https://www.openssl.org/docs/man1.1.0/crypto/EVP_BytesToKey.html) with the digest algorithm set to MD5, one + * iteration, and no salt. The lack of salt allows dictionary attacks as the same + * password always creates the same key. The low iteration count and + * non-cryptographically secure hash algorithm allow passwords to be tested very + * rapidly. + * + * In line with OpenSSL's recommendation to use a more modern algorithm instead of [`EVP_BytesToKey`](https://www.openssl.org/docs/man1.1.0/crypto/EVP_BytesToKey.html) it is recommended that + * developers derive a key and IV on + * their own using {@link scrypt} and to use {@link createDecipheriv} to create the `Decipher` object. + * @since v0.1.94 + * @deprecated Since v10.0.0 - Use {@link createDecipheriv} instead. + * @param options `stream.transform` options + */ + function createDecipher(algorithm: CipherCCMTypes, password: BinaryLike, options: CipherCCMOptions): DecipherCCM; + /** @deprecated since v10.0.0 use `createDecipheriv()` */ + function createDecipher(algorithm: CipherGCMTypes, password: BinaryLike, options?: CipherGCMOptions): DecipherGCM; + /** @deprecated since v10.0.0 use `createDecipheriv()` */ + function createDecipher(algorithm: string, password: BinaryLike, options?: stream.TransformOptions): Decipher; + /** + * Creates and returns a `Decipher` object that uses the given `algorithm`, `key`and initialization vector (`iv`). + * + * The `options` argument controls stream behavior and is optional except when a + * cipher in CCM or OCB mode (e.g. `'aes-128-ccm'`) is used. In that case, the`authTagLength` option is required and specifies the length of the + * authentication tag in bytes, see `CCM mode`. In GCM mode, the `authTagLength`option is not required but can be used to restrict accepted authentication tags + * to those with the specified length. + * For `chacha20-poly1305`, the `authTagLength` option defaults to 16 bytes. + * + * The `algorithm` is dependent on OpenSSL, examples are `'aes192'`, etc. On + * recent OpenSSL releases, `openssl list -cipher-algorithms` will + * display the available cipher algorithms. + * + * The `key` is the raw key used by the `algorithm` and `iv` is an [initialization vector](https://en.wikipedia.org/wiki/Initialization_vector). Both arguments must be `'utf8'` encoded + * strings,`Buffers`, `TypedArray`, or `DataView`s. The `key` may optionally be + * a `KeyObject` of type `secret`. If the cipher does not need + * an initialization vector, `iv` may be `null`. + * + * When passing strings for `key` or `iv`, please consider `caveats when using strings as inputs to cryptographic APIs`. + * + * Initialization vectors should be unpredictable and unique; ideally, they will be + * cryptographically random. They do not have to be secret: IVs are typically just + * added to ciphertext messages unencrypted. It may sound contradictory that + * something has to be unpredictable and unique, but does not have to be secret; + * remember that an attacker must not be able to predict ahead of time what a given + * IV will be. + * @since v0.1.94 + * @param options `stream.transform` options + */ + function createDecipheriv(algorithm: CipherCCMTypes, key: CipherKey, iv: BinaryLike, options: CipherCCMOptions): DecipherCCM; + function createDecipheriv(algorithm: CipherOCBTypes, key: CipherKey, iv: BinaryLike, options: CipherOCBOptions): DecipherOCB; + function createDecipheriv(algorithm: CipherGCMTypes, key: CipherKey, iv: BinaryLike, options?: CipherGCMOptions): DecipherGCM; + function createDecipheriv(algorithm: string, key: CipherKey, iv: BinaryLike | null, options?: stream.TransformOptions): Decipher; + /** + * Instances of the `Decipher` class are used to decrypt data. The class can be + * used in one of two ways: + * + * * As a `stream` that is both readable and writable, where plain encrypted + * data is written to produce unencrypted data on the readable side, or + * * Using the `decipher.update()` and `decipher.final()` methods to + * produce the unencrypted data. + * + * The {@link createDecipher} or {@link createDecipheriv} methods are + * used to create `Decipher` instances. `Decipher` objects are not to be created + * directly using the `new` keyword. + * + * Example: Using `Decipher` objects as streams: + * + * ```js + * import { Buffer } from 'buffer'; + * const { + * scryptSync, + * createDecipheriv + * } = await import('crypto'); + * + * const algorithm = 'aes-192-cbc'; + * const password = 'Password used to generate key'; + * // Key length is dependent on the algorithm. In this case for aes192, it is + * // 24 bytes (192 bits). + * // Use the async `crypto.scrypt()` instead. + * const key = scryptSync(password, 'salt', 24); + * // The IV is usually passed along with the ciphertext. + * const iv = Buffer.alloc(16, 0); // Initialization vector. + * + * const decipher = createDecipheriv(algorithm, key, iv); + * + * let decrypted = ''; + * decipher.on('readable', () => { + * while (null !== (chunk = decipher.read())) { + * decrypted += chunk.toString('utf8'); + * } + * }); + * decipher.on('end', () => { + * console.log(decrypted); + * // Prints: some clear text data + * }); + * + * // Encrypted with same algorithm, key and iv. + * const encrypted = + * 'e5f79c5915c02171eec6b212d5520d44480993d7d622a7c4c2da32f6efda0ffa'; + * decipher.write(encrypted, 'hex'); + * decipher.end(); + * ``` + * + * Example: Using `Decipher` and piped streams: + * + * ```js + * import { + * createReadStream, + * createWriteStream, + * } from 'fs'; + * import { Buffer } from 'buffer'; + * const { + * scryptSync, + * createDecipheriv + * } = await import('crypto'); + * + * const algorithm = 'aes-192-cbc'; + * const password = 'Password used to generate key'; + * // Use the async `crypto.scrypt()` instead. + * const key = scryptSync(password, 'salt', 24); + * // The IV is usually passed along with the ciphertext. + * const iv = Buffer.alloc(16, 0); // Initialization vector. + * + * const decipher = createDecipheriv(algorithm, key, iv); + * + * const input = createReadStream('test.enc'); + * const output = createWriteStream('test.js'); + * + * input.pipe(decipher).pipe(output); + * ``` + * + * Example: Using the `decipher.update()` and `decipher.final()` methods: + * + * ```js + * import { Buffer } from 'buffer'; + * const { + * scryptSync, + * createDecipheriv + * } = await import('crypto'); + * + * const algorithm = 'aes-192-cbc'; + * const password = 'Password used to generate key'; + * // Use the async `crypto.scrypt()` instead. + * const key = scryptSync(password, 'salt', 24); + * // The IV is usually passed along with the ciphertext. + * const iv = Buffer.alloc(16, 0); // Initialization vector. + * + * const decipher = createDecipheriv(algorithm, key, iv); + * + * // Encrypted using same algorithm, key and iv. + * const encrypted = + * 'e5f79c5915c02171eec6b212d5520d44480993d7d622a7c4c2da32f6efda0ffa'; + * let decrypted = decipher.update(encrypted, 'hex', 'utf8'); + * decrypted += decipher.final('utf8'); + * console.log(decrypted); + * // Prints: some clear text data + * ``` + * @since v0.1.94 + */ + class Decipher extends stream.Transform { + private constructor(); + /** + * Updates the decipher with `data`. If the `inputEncoding` argument is given, + * the `data`argument is a string using the specified encoding. If the `inputEncoding`argument is not given, `data` must be a `Buffer`. If `data` is a `Buffer` then `inputEncoding` is + * ignored. + * + * The `outputEncoding` specifies the output format of the enciphered + * data. If the `outputEncoding`is specified, a string using the specified encoding is returned. If no`outputEncoding` is provided, a `Buffer` is returned. + * + * The `decipher.update()` method can be called multiple times with new data until `decipher.final()` is called. Calling `decipher.update()` after `decipher.final()` will result in an error + * being thrown. + * @since v0.1.94 + * @param inputEncoding The `encoding` of the `data` string. + * @param outputEncoding The `encoding` of the return value. + */ + update(data: NodeJS.ArrayBufferView): Buffer; + update(data: string, inputEncoding: Encoding): Buffer; + update(data: NodeJS.ArrayBufferView, inputEncoding: undefined, outputEncoding: Encoding): string; + update(data: string, inputEncoding: Encoding | undefined, outputEncoding: Encoding): string; + /** + * Once the `decipher.final()` method has been called, the `Decipher` object can + * no longer be used to decrypt data. Attempts to call `decipher.final()` more + * than once will result in an error being thrown. + * @since v0.1.94 + * @param outputEncoding The `encoding` of the return value. + * @return Any remaining deciphered contents. If `outputEncoding` is specified, a string is returned. If an `outputEncoding` is not provided, a {@link Buffer} is returned. + */ + final(): Buffer; + final(outputEncoding: BufferEncoding): string; + /** + * When data has been encrypted without standard block padding, calling`decipher.setAutoPadding(false)` will disable automatic padding to prevent `decipher.final()` from checking for and + * removing padding. + * + * Turning auto padding off will only work if the input data's length is a + * multiple of the ciphers block size. + * + * The `decipher.setAutoPadding()` method must be called before `decipher.final()`. + * @since v0.7.1 + * @param [autoPadding=true] + * @return for method chaining. + */ + setAutoPadding(auto_padding?: boolean): this; + } + interface DecipherCCM extends Decipher { + setAuthTag(buffer: NodeJS.ArrayBufferView): this; + setAAD( + buffer: NodeJS.ArrayBufferView, + options: { + plaintextLength: number; + } + ): this; + } + interface DecipherGCM extends Decipher { + setAuthTag(buffer: NodeJS.ArrayBufferView): this; + setAAD( + buffer: NodeJS.ArrayBufferView, + options?: { + plaintextLength: number; + } + ): this; + } + interface DecipherOCB extends Decipher { + setAuthTag(buffer: NodeJS.ArrayBufferView): this; + setAAD( + buffer: NodeJS.ArrayBufferView, + options?: { + plaintextLength: number; + } + ): this; + } + interface PrivateKeyInput { + key: string | Buffer; + format?: KeyFormat | undefined; + type?: 'pkcs1' | 'pkcs8' | 'sec1' | undefined; + passphrase?: string | Buffer | undefined; + } + interface PublicKeyInput { + key: string | Buffer; + format?: KeyFormat | undefined; + type?: 'pkcs1' | 'spki' | undefined; + } + /** + * Asynchronously generates a new random secret key of the given `length`. The`type` will determine which validations will be performed on the `length`. + * + * ```js + * const { + * generateKey + * } = await import('crypto'); + * + * generateKey('hmac', { length: 64 }, (err, key) => { + * if (err) throw err; + * console.log(key.export().toString('hex')); // 46e..........620 + * }); + * ``` + * @since v15.0.0 + * @param type The intended use of the generated secret key. Currently accepted values are `'hmac'` and `'aes'`. + */ + function generateKey( + type: 'hmac' | 'aes', + options: { + length: number; + }, + callback: (err: Error | null, key: KeyObject) => void + ): void; + /** + * Synchronously generates a new random secret key of the given `length`. The`type` will determine which validations will be performed on the `length`. + * + * ```js + * const { + * generateKeySync + * } = await import('crypto'); + * + * const key = generateKeySync('hmac', { length: 64 }); + * console.log(key.export().toString('hex')); // e89..........41e + * ``` + * @since v15.0.0 + * @param type The intended use of the generated secret key. Currently accepted values are `'hmac'` and `'aes'`. + */ + function generateKeySync( + type: 'hmac' | 'aes', + options: { + length: number; + } + ): KeyObject; + interface JsonWebKeyInput { + key: JsonWebKey; + format: 'jwk'; + } + /** + * Creates and returns a new key object containing a private key. If `key` is a + * string or `Buffer`, `format` is assumed to be `'pem'`; otherwise, `key`must be an object with the properties described above. + * + * If the private key is encrypted, a `passphrase` must be specified. The length + * of the passphrase is limited to 1024 bytes. + * @since v11.6.0 + */ + function createPrivateKey(key: PrivateKeyInput | string | Buffer | JsonWebKeyInput): KeyObject; + /** + * Creates and returns a new key object containing a public key. If `key` is a + * string or `Buffer`, `format` is assumed to be `'pem'`; if `key` is a `KeyObject`with type `'private'`, the public key is derived from the given private key; + * otherwise, `key` must be an object with the properties described above. + * + * If the format is `'pem'`, the `'key'` may also be an X.509 certificate. + * + * Because public keys can be derived from private keys, a private key may be + * passed instead of a public key. In that case, this function behaves as if {@link createPrivateKey} had been called, except that the type of the + * returned `KeyObject` will be `'public'` and that the private key cannot be + * extracted from the returned `KeyObject`. Similarly, if a `KeyObject` with type`'private'` is given, a new `KeyObject` with type `'public'` will be returned + * and it will be impossible to extract the private key from the returned object. + * @since v11.6.0 + */ + function createPublicKey(key: PublicKeyInput | string | Buffer | KeyObject | JsonWebKeyInput): KeyObject; + /** + * Creates and returns a new key object containing a secret key for symmetric + * encryption or `Hmac`. + * @since v11.6.0 + * @param encoding The string encoding when `key` is a string. + */ + function createSecretKey(key: NodeJS.ArrayBufferView): KeyObject; + function createSecretKey(key: string, encoding: BufferEncoding): KeyObject; + /** + * Creates and returns a `Sign` object that uses the given `algorithm`. Use {@link getHashes} to obtain the names of the available digest algorithms. + * Optional `options` argument controls the `stream.Writable` behavior. + * + * In some cases, a `Sign` instance can be created using the name of a signature + * algorithm, such as `'RSA-SHA256'`, instead of a digest algorithm. This will use + * the corresponding digest algorithm. This does not work for all signature + * algorithms, such as `'ecdsa-with-SHA256'`, so it is best to always use digest + * algorithm names. + * @since v0.1.92 + * @param options `stream.Writable` options + */ + function createSign(algorithm: string, options?: stream.WritableOptions): Sign; + type DSAEncoding = 'der' | 'ieee-p1363'; + interface SigningOptions { + /** + * @See crypto.constants.RSA_PKCS1_PADDING + */ + padding?: number | undefined; + saltLength?: number | undefined; + dsaEncoding?: DSAEncoding | undefined; + } + interface SignPrivateKeyInput extends PrivateKeyInput, SigningOptions {} + interface SignKeyObjectInput extends SigningOptions { + key: KeyObject; + } + interface VerifyPublicKeyInput extends PublicKeyInput, SigningOptions {} + interface VerifyKeyObjectInput extends SigningOptions { + key: KeyObject; + } + type KeyLike = string | Buffer | KeyObject; + /** + * The `Sign` class is a utility for generating signatures. It can be used in one + * of two ways: + * + * * As a writable `stream`, where data to be signed is written and the `sign.sign()` method is used to generate and return the signature, or + * * Using the `sign.update()` and `sign.sign()` methods to produce the + * signature. + * + * The {@link createSign} method is used to create `Sign` instances. The + * argument is the string name of the hash function to use. `Sign` objects are not + * to be created directly using the `new` keyword. + * + * Example: Using `Sign` and `Verify` objects as streams: + * + * ```js + * const { + * generateKeyPairSync, + * createSign, + * createVerify + * } = await import('crypto'); + * + * const { privateKey, publicKey } = generateKeyPairSync('ec', { + * namedCurve: 'sect239k1' + * }); + * + * const sign = createSign('SHA256'); + * sign.write('some data to sign'); + * sign.end(); + * const signature = sign.sign(privateKey, 'hex'); + * + * const verify = createVerify('SHA256'); + * verify.write('some data to sign'); + * verify.end(); + * console.log(verify.verify(publicKey, signature, 'hex')); + * // Prints: true + * ``` + * + * Example: Using the `sign.update()` and `verify.update()` methods: + * + * ```js + * const { + * generateKeyPairSync, + * createSign, + * createVerify + * } = await import('crypto'); + * + * const { privateKey, publicKey } = generateKeyPairSync('rsa', { + * modulusLength: 2048, + * }); + * + * const sign = createSign('SHA256'); + * sign.update('some data to sign'); + * sign.end(); + * const signature = sign.sign(privateKey); + * + * const verify = createVerify('SHA256'); + * verify.update('some data to sign'); + * verify.end(); + * console.log(verify.verify(publicKey, signature)); + * // Prints: true + * ``` + * @since v0.1.92 + */ + class Sign extends stream.Writable { + private constructor(); + /** + * Updates the `Sign` content with the given `data`, the encoding of which + * is given in `inputEncoding`. + * If `encoding` is not provided, and the `data` is a string, an + * encoding of `'utf8'` is enforced. If `data` is a `Buffer`, `TypedArray`, or`DataView`, then `inputEncoding` is ignored. + * + * This can be called many times with new data as it is streamed. + * @since v0.1.92 + * @param inputEncoding The `encoding` of the `data` string. + */ + update(data: BinaryLike): this; + update(data: string, inputEncoding: Encoding): this; + /** + * Calculates the signature on all the data passed through using either `sign.update()` or `sign.write()`. + * + * If `privateKey` is not a `KeyObject`, this function behaves as if`privateKey` had been passed to {@link createPrivateKey}. If it is an + * object, the following additional properties can be passed: + * + * If `outputEncoding` is provided a string is returned; otherwise a `Buffer` is returned. + * + * The `Sign` object can not be again used after `sign.sign()` method has been + * called. Multiple calls to `sign.sign()` will result in an error being thrown. + * @since v0.1.92 + */ + sign(privateKey: KeyLike | SignKeyObjectInput | SignPrivateKeyInput): Buffer; + sign(privateKey: KeyLike | SignKeyObjectInput | SignPrivateKeyInput, outputFormat: BinaryToTextEncoding): string; + } + /** + * Creates and returns a `Verify` object that uses the given algorithm. + * Use {@link getHashes} to obtain an array of names of the available + * signing algorithms. Optional `options` argument controls the`stream.Writable` behavior. + * + * In some cases, a `Verify` instance can be created using the name of a signature + * algorithm, such as `'RSA-SHA256'`, instead of a digest algorithm. This will use + * the corresponding digest algorithm. This does not work for all signature + * algorithms, such as `'ecdsa-with-SHA256'`, so it is best to always use digest + * algorithm names. + * @since v0.1.92 + * @param options `stream.Writable` options + */ + function createVerify(algorithm: string, options?: stream.WritableOptions): Verify; + /** + * The `Verify` class is a utility for verifying signatures. It can be used in one + * of two ways: + * + * * As a writable `stream` where written data is used to validate against the + * supplied signature, or + * * Using the `verify.update()` and `verify.verify()` methods to verify + * the signature. + * + * The {@link createVerify} method is used to create `Verify` instances.`Verify` objects are not to be created directly using the `new` keyword. + * + * See `Sign` for examples. + * @since v0.1.92 + */ + class Verify extends stream.Writable { + private constructor(); + /** + * Updates the `Verify` content with the given `data`, the encoding of which + * is given in `inputEncoding`. + * If `inputEncoding` is not provided, and the `data` is a string, an + * encoding of `'utf8'` is enforced. If `data` is a `Buffer`, `TypedArray`, or`DataView`, then `inputEncoding` is ignored. + * + * This can be called many times with new data as it is streamed. + * @since v0.1.92 + * @param inputEncoding The `encoding` of the `data` string. + */ + update(data: BinaryLike): Verify; + update(data: string, inputEncoding: Encoding): Verify; + /** + * Verifies the provided data using the given `object` and `signature`. + * + * If `object` is not a `KeyObject`, this function behaves as if`object` had been passed to {@link createPublicKey}. If it is an + * object, the following additional properties can be passed: + * + * The `signature` argument is the previously calculated signature for the data, in + * the `signatureEncoding`. + * If a `signatureEncoding` is specified, the `signature` is expected to be a + * string; otherwise `signature` is expected to be a `Buffer`,`TypedArray`, or `DataView`. + * + * The `verify` object can not be used again after `verify.verify()` has been + * called. Multiple calls to `verify.verify()` will result in an error being + * thrown. + * + * Because public keys can be derived from private keys, a private key may + * be passed instead of a public key. + * @since v0.1.92 + */ + verify(object: KeyLike | VerifyKeyObjectInput | VerifyPublicKeyInput, signature: NodeJS.ArrayBufferView): boolean; + verify(object: KeyLike | VerifyKeyObjectInput | VerifyPublicKeyInput, signature: string, signature_format?: BinaryToTextEncoding): boolean; + } + /** + * Creates a `DiffieHellman` key exchange object using the supplied `prime` and an + * optional specific `generator`. + * + * The `generator` argument can be a number, string, or `Buffer`. If`generator` is not specified, the value `2` is used. + * + * If `primeEncoding` is specified, `prime` is expected to be a string; otherwise + * a `Buffer`, `TypedArray`, or `DataView` is expected. + * + * If `generatorEncoding` is specified, `generator` is expected to be a string; + * otherwise a number, `Buffer`, `TypedArray`, or `DataView` is expected. + * @since v0.11.12 + * @param primeEncoding The `encoding` of the `prime` string. + * @param [generator=2] + * @param generatorEncoding The `encoding` of the `generator` string. + */ + function createDiffieHellman(primeLength: number, generator?: number | NodeJS.ArrayBufferView): DiffieHellman; + function createDiffieHellman(prime: NodeJS.ArrayBufferView): DiffieHellman; + function createDiffieHellman(prime: string, primeEncoding: BinaryToTextEncoding): DiffieHellman; + function createDiffieHellman(prime: string, primeEncoding: BinaryToTextEncoding, generator: number | NodeJS.ArrayBufferView): DiffieHellman; + function createDiffieHellman(prime: string, primeEncoding: BinaryToTextEncoding, generator: string, generatorEncoding: BinaryToTextEncoding): DiffieHellman; + /** + * The `DiffieHellman` class is a utility for creating Diffie-Hellman key + * exchanges. + * + * Instances of the `DiffieHellman` class can be created using the {@link createDiffieHellman} function. + * + * ```js + * import assert from 'assert'; + * + * const { + * createDiffieHellman + * } = await import('crypto'); + * + * // Generate Alice's keys... + * const alice = createDiffieHellman(2048); + * const aliceKey = alice.generateKeys(); + * + * // Generate Bob's keys... + * const bob = createDiffieHellman(alice.getPrime(), alice.getGenerator()); + * const bobKey = bob.generateKeys(); + * + * // Exchange and generate the secret... + * const aliceSecret = alice.computeSecret(bobKey); + * const bobSecret = bob.computeSecret(aliceKey); + * + * // OK + * assert.strictEqual(aliceSecret.toString('hex'), bobSecret.toString('hex')); + * ``` + * @since v0.5.0 + */ + class DiffieHellman { + private constructor(); + /** + * Generates private and public Diffie-Hellman key values, and returns + * the public key in the specified `encoding`. This key should be + * transferred to the other party. + * If `encoding` is provided a string is returned; otherwise a `Buffer` is returned. + * @since v0.5.0 + * @param encoding The `encoding` of the return value. + */ + generateKeys(): Buffer; + generateKeys(encoding: BinaryToTextEncoding): string; + /** + * Computes the shared secret using `otherPublicKey` as the other + * party's public key and returns the computed shared secret. The supplied + * key is interpreted using the specified `inputEncoding`, and secret is + * encoded using specified `outputEncoding`. + * If the `inputEncoding` is not + * provided, `otherPublicKey` is expected to be a `Buffer`,`TypedArray`, or `DataView`. + * + * If `outputEncoding` is given a string is returned; otherwise, a `Buffer` is returned. + * @since v0.5.0 + * @param inputEncoding The `encoding` of an `otherPublicKey` string. + * @param outputEncoding The `encoding` of the return value. + */ + computeSecret(otherPublicKey: NodeJS.ArrayBufferView, inputEncoding?: null, outputEncoding?: null): Buffer; + computeSecret(otherPublicKey: string, inputEncoding: BinaryToTextEncoding, outputEncoding?: null): Buffer; + computeSecret(otherPublicKey: NodeJS.ArrayBufferView, inputEncoding: null, outputEncoding: BinaryToTextEncoding): string; + computeSecret(otherPublicKey: string, inputEncoding: BinaryToTextEncoding, outputEncoding: BinaryToTextEncoding): string; + /** + * Returns the Diffie-Hellman prime in the specified `encoding`. + * If `encoding` is provided a string is + * returned; otherwise a `Buffer` is returned. + * @since v0.5.0 + * @param encoding The `encoding` of the return value. + */ + getPrime(): Buffer; + getPrime(encoding: BinaryToTextEncoding): string; + /** + * Returns the Diffie-Hellman generator in the specified `encoding`. + * If `encoding` is provided a string is + * returned; otherwise a `Buffer` is returned. + * @since v0.5.0 + * @param encoding The `encoding` of the return value. + */ + getGenerator(): Buffer; + getGenerator(encoding: BinaryToTextEncoding): string; + /** + * Returns the Diffie-Hellman public key in the specified `encoding`. + * If `encoding` is provided a + * string is returned; otherwise a `Buffer` is returned. + * @since v0.5.0 + * @param encoding The `encoding` of the return value. + */ + getPublicKey(): Buffer; + getPublicKey(encoding: BinaryToTextEncoding): string; + /** + * Returns the Diffie-Hellman private key in the specified `encoding`. + * If `encoding` is provided a + * string is returned; otherwise a `Buffer` is returned. + * @since v0.5.0 + * @param encoding The `encoding` of the return value. + */ + getPrivateKey(): Buffer; + getPrivateKey(encoding: BinaryToTextEncoding): string; + /** + * Sets the Diffie-Hellman public key. If the `encoding` argument is provided,`publicKey` is expected + * to be a string. If no `encoding` is provided, `publicKey` is expected + * to be a `Buffer`, `TypedArray`, or `DataView`. + * @since v0.5.0 + * @param encoding The `encoding` of the `publicKey` string. + */ + setPublicKey(publicKey: NodeJS.ArrayBufferView): void; + setPublicKey(publicKey: string, encoding: BufferEncoding): void; + /** + * Sets the Diffie-Hellman private key. If the `encoding` argument is provided,`privateKey` is expected + * to be a string. If no `encoding` is provided, `privateKey` is expected + * to be a `Buffer`, `TypedArray`, or `DataView`. + * @since v0.5.0 + * @param encoding The `encoding` of the `privateKey` string. + */ + setPrivateKey(privateKey: NodeJS.ArrayBufferView): void; + setPrivateKey(privateKey: string, encoding: BufferEncoding): void; + /** + * A bit field containing any warnings and/or errors resulting from a check + * performed during initialization of the `DiffieHellman` object. + * + * The following values are valid for this property (as defined in `constants`module): + * + * * `DH_CHECK_P_NOT_SAFE_PRIME` + * * `DH_CHECK_P_NOT_PRIME` + * * `DH_UNABLE_TO_CHECK_GENERATOR` + * * `DH_NOT_SUITABLE_GENERATOR` + * @since v0.11.12 + */ + verifyError: number; + } + /** + * The `DiffieHellmanGroup` class takes a well-known modp group as its argument. + * It works the same as `DiffieHellman`, except that it does not allow changing its keys after creation. + * In other words, it does not implement `setPublicKey()` or `setPrivateKey()` methods. + * + * ```js + * const { createDiffieHellmanGroup } = await import('node:crypto'); + * const dh = createDiffieHellmanGroup('modp1'); + * ``` + * The name (e.g. `'modp1'`) is taken from [RFC 2412](https://www.rfc-editor.org/rfc/rfc2412.txt) (modp1 and 2) and [RFC 3526](https://www.rfc-editor.org/rfc/rfc3526.txt): + * ```bash + * $ perl -ne 'print "$1\n" if /"(modp\d+)"/' src/node_crypto_groups.h + * modp1 # 768 bits + * modp2 # 1024 bits + * modp5 # 1536 bits + * modp14 # 2048 bits + * modp15 # etc. + * modp16 + * modp17 + * modp18 + * ``` + * @since v0.7.5 + */ + const DiffieHellmanGroup: DiffieHellmanGroupConstructor; + interface DiffieHellmanGroupConstructor { + new(name: string): DiffieHellmanGroup; + (name: string): DiffieHellmanGroup; + readonly prototype: DiffieHellmanGroup; + } + type DiffieHellmanGroup = Omit; + /** + * Creates a predefined `DiffieHellmanGroup` key exchange object. The + * supported groups are: `'modp1'`, `'modp2'`, `'modp5'` (defined in [RFC 2412](https://www.rfc-editor.org/rfc/rfc2412.txt), but see `Caveats`) and `'modp14'`, `'modp15'`,`'modp16'`, `'modp17'`, + * `'modp18'` (defined in [RFC 3526](https://www.rfc-editor.org/rfc/rfc3526.txt)). The + * returned object mimics the interface of objects created by {@link createDiffieHellman}, but will not allow changing + * the keys (with `diffieHellman.setPublicKey()`, for example). The + * advantage of using this method is that the parties do not have to + * generate nor exchange a group modulus beforehand, saving both processor + * and communication time. + * + * Example (obtaining a shared secret): + * + * ```js + * const { + * getDiffieHellman + * } = await import('crypto'); + * const alice = getDiffieHellman('modp14'); + * const bob = getDiffieHellman('modp14'); + * + * alice.generateKeys(); + * bob.generateKeys(); + * + * const aliceSecret = alice.computeSecret(bob.getPublicKey(), null, 'hex'); + * const bobSecret = bob.computeSecret(alice.getPublicKey(), null, 'hex'); + * + * // aliceSecret and bobSecret should be the same + * console.log(aliceSecret === bobSecret); + * ``` + * @since v0.7.5 + */ + function getDiffieHellman(groupName: string): DiffieHellmanGroup; + /** + * An alias for {@link getDiffieHellman} + * @since v0.9.3 + */ + function createDiffieHellmanGroup(name: string): DiffieHellmanGroup; + /** + * Provides an asynchronous Password-Based Key Derivation Function 2 (PBKDF2) + * implementation. A selected HMAC digest algorithm specified by `digest` is + * applied to derive a key of the requested byte length (`keylen`) from the`password`, `salt` and `iterations`. + * + * The supplied `callback` function is called with two arguments: `err` and`derivedKey`. If an error occurs while deriving the key, `err` will be set; + * otherwise `err` will be `null`. By default, the successfully generated`derivedKey` will be passed to the callback as a `Buffer`. An error will be + * thrown if any of the input arguments specify invalid values or types. + * + * If `digest` is `null`, `'sha1'` will be used. This behavior is deprecated, + * please specify a `digest` explicitly. + * + * The `iterations` argument must be a number set as high as possible. The + * higher the number of iterations, the more secure the derived key will be, + * but will take a longer amount of time to complete. + * + * The `salt` should be as unique as possible. It is recommended that a salt is + * random and at least 16 bytes long. See [NIST SP 800-132](https://nvlpubs.nist.gov/nistpubs/Legacy/SP/nistspecialpublication800-132.pdf) for details. + * + * When passing strings for `password` or `salt`, please consider `caveats when using strings as inputs to cryptographic APIs`. + * + * ```js + * const { + * pbkdf2 + * } = await import('crypto'); + * + * pbkdf2('secret', 'salt', 100000, 64, 'sha512', (err, derivedKey) => { + * if (err) throw err; + * console.log(derivedKey.toString('hex')); // '3745e48...08d59ae' + * }); + * ``` + * + * The `crypto.DEFAULT_ENCODING` property can be used to change the way the`derivedKey` is passed to the callback. This property, however, has been + * deprecated and use should be avoided. + * + * ```js + * import crypto from 'crypto'; + * crypto.DEFAULT_ENCODING = 'hex'; + * crypto.pbkdf2('secret', 'salt', 100000, 512, 'sha512', (err, derivedKey) => { + * if (err) throw err; + * console.log(derivedKey); // '3745e48...aa39b34' + * }); + * ``` + * + * An array of supported digest functions can be retrieved using {@link getHashes}. + * + * This API uses libuv's threadpool, which can have surprising and + * negative performance implications for some applications; see the `UV_THREADPOOL_SIZE` documentation for more information. + * @since v0.5.5 + */ + function pbkdf2(password: BinaryLike, salt: BinaryLike, iterations: number, keylen: number, digest: string, callback: (err: Error | null, derivedKey: Buffer) => void): void; + /** + * Provides a synchronous Password-Based Key Derivation Function 2 (PBKDF2) + * implementation. A selected HMAC digest algorithm specified by `digest` is + * applied to derive a key of the requested byte length (`keylen`) from the`password`, `salt` and `iterations`. + * + * If an error occurs an `Error` will be thrown, otherwise the derived key will be + * returned as a `Buffer`. + * + * If `digest` is `null`, `'sha1'` will be used. This behavior is deprecated, + * please specify a `digest` explicitly. + * + * The `iterations` argument must be a number set as high as possible. The + * higher the number of iterations, the more secure the derived key will be, + * but will take a longer amount of time to complete. + * + * The `salt` should be as unique as possible. It is recommended that a salt is + * random and at least 16 bytes long. See [NIST SP 800-132](https://nvlpubs.nist.gov/nistpubs/Legacy/SP/nistspecialpublication800-132.pdf) for details. + * + * When passing strings for `password` or `salt`, please consider `caveats when using strings as inputs to cryptographic APIs`. + * + * ```js + * const { + * pbkdf2Sync + * } = await import('crypto'); + * + * const key = pbkdf2Sync('secret', 'salt', 100000, 64, 'sha512'); + * console.log(key.toString('hex')); // '3745e48...08d59ae' + * ``` + * + * The `crypto.DEFAULT_ENCODING` property may be used to change the way the`derivedKey` is returned. This property, however, is deprecated and use + * should be avoided. + * + * ```js + * import crypto from 'crypto'; + * crypto.DEFAULT_ENCODING = 'hex'; + * const key = crypto.pbkdf2Sync('secret', 'salt', 100000, 512, 'sha512'); + * console.log(key); // '3745e48...aa39b34' + * ``` + * + * An array of supported digest functions can be retrieved using {@link getHashes}. + * @since v0.9.3 + */ + function pbkdf2Sync(password: BinaryLike, salt: BinaryLike, iterations: number, keylen: number, digest: string): Buffer; + /** + * Generates cryptographically strong pseudorandom data. The `size` argument + * is a number indicating the number of bytes to generate. + * + * If a `callback` function is provided, the bytes are generated asynchronously + * and the `callback` function is invoked with two arguments: `err` and `buf`. + * If an error occurs, `err` will be an `Error` object; otherwise it is `null`. The`buf` argument is a `Buffer` containing the generated bytes. + * + * ```js + * // Asynchronous + * const { + * randomBytes + * } = await import('crypto'); + * + * randomBytes(256, (err, buf) => { + * if (err) throw err; + * console.log(`${buf.length} bytes of random data: ${buf.toString('hex')}`); + * }); + * ``` + * + * If the `callback` function is not provided, the random bytes are generated + * synchronously and returned as a `Buffer`. An error will be thrown if + * there is a problem generating the bytes. + * + * ```js + * // Synchronous + * const { + * randomBytes + * } = await import('crypto'); + * + * const buf = randomBytes(256); + * console.log( + * `${buf.length} bytes of random data: ${buf.toString('hex')}`); + * ``` + * + * The `crypto.randomBytes()` method will not complete until there is + * sufficient entropy available. + * This should normally never take longer than a few milliseconds. The only time + * when generating the random bytes may conceivably block for a longer period of + * time is right after boot, when the whole system is still low on entropy. + * + * This API uses libuv's threadpool, which can have surprising and + * negative performance implications for some applications; see the `UV_THREADPOOL_SIZE` documentation for more information. + * + * The asynchronous version of `crypto.randomBytes()` is carried out in a single + * threadpool request. To minimize threadpool task length variation, partition + * large `randomBytes` requests when doing so as part of fulfilling a client + * request. + * @since v0.5.8 + * @param size The number of bytes to generate. The `size` must not be larger than `2**31 - 1`. + * @return if the `callback` function is not provided. + */ + function randomBytes(size: number): Buffer; + function randomBytes(size: number, callback: (err: Error | null, buf: Buffer) => void): void; + function pseudoRandomBytes(size: number): Buffer; + function pseudoRandomBytes(size: number, callback: (err: Error | null, buf: Buffer) => void): void; + /** + * Return a random integer `n` such that `min <= n < max`. This + * implementation avoids [modulo bias](https://en.wikipedia.org/wiki/Fisher%E2%80%93Yates_shuffle#Modulo_bias). + * + * The range (`max - min`) must be less than 248. `min` and `max` must + * be [safe integers](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/isSafeInteger). + * + * If the `callback` function is not provided, the random integer is + * generated synchronously. + * + * ```js + * // Asynchronous + * const { + * randomInt + * } = await import('crypto'); + * + * randomInt(3, (err, n) => { + * if (err) throw err; + * console.log(`Random number chosen from (0, 1, 2): ${n}`); + * }); + * ``` + * + * ```js + * // Synchronous + * const { + * randomInt + * } = await import('crypto'); + * + * const n = randomInt(3); + * console.log(`Random number chosen from (0, 1, 2): ${n}`); + * ``` + * + * ```js + * // With `min` argument + * const { + * randomInt + * } = await import('crypto'); + * + * const n = randomInt(1, 7); + * console.log(`The dice rolled: ${n}`); + * ``` + * @since v14.10.0, v12.19.0 + * @param [min=0] Start of random range (inclusive). + * @param max End of random range (exclusive). + * @param callback `function(err, n) {}`. + */ + function randomInt(max: number): number; + function randomInt(min: number, max: number): number; + function randomInt(max: number, callback: (err: Error | null, value: number) => void): void; + function randomInt(min: number, max: number, callback: (err: Error | null, value: number) => void): void; + /** + * Synchronous version of {@link randomFill}. + * + * ```js + * import { Buffer } from 'buffer'; + * const { randomFillSync } = await import('crypto'); + * + * const buf = Buffer.alloc(10); + * console.log(randomFillSync(buf).toString('hex')); + * + * randomFillSync(buf, 5); + * console.log(buf.toString('hex')); + * + * // The above is equivalent to the following: + * randomFillSync(buf, 5, 5); + * console.log(buf.toString('hex')); + * ``` + * + * Any `ArrayBuffer`, `TypedArray` or `DataView` instance may be passed as`buffer`. + * + * ```js + * import { Buffer } from 'buffer'; + * const { randomFillSync } = await import('crypto'); + * + * const a = new Uint32Array(10); + * console.log(Buffer.from(randomFillSync(a).buffer, + * a.byteOffset, a.byteLength).toString('hex')); + * + * const b = new DataView(new ArrayBuffer(10)); + * console.log(Buffer.from(randomFillSync(b).buffer, + * b.byteOffset, b.byteLength).toString('hex')); + * + * const c = new ArrayBuffer(10); + * console.log(Buffer.from(randomFillSync(c)).toString('hex')); + * ``` + * @since v7.10.0, v6.13.0 + * @param buffer Must be supplied. The size of the provided `buffer` must not be larger than `2**31 - 1`. + * @param [offset=0] + * @param [size=buffer.length - offset] + * @return The object passed as `buffer` argument. + */ + function randomFillSync(buffer: T, offset?: number, size?: number): T; + /** + * This function is similar to {@link randomBytes} but requires the first + * argument to be a `Buffer` that will be filled. It also + * requires that a callback is passed in. + * + * If the `callback` function is not provided, an error will be thrown. + * + * ```js + * import { Buffer } from 'buffer'; + * const { randomFill } = await import('crypto'); + * + * const buf = Buffer.alloc(10); + * randomFill(buf, (err, buf) => { + * if (err) throw err; + * console.log(buf.toString('hex')); + * }); + * + * randomFill(buf, 5, (err, buf) => { + * if (err) throw err; + * console.log(buf.toString('hex')); + * }); + * + * // The above is equivalent to the following: + * randomFill(buf, 5, 5, (err, buf) => { + * if (err) throw err; + * console.log(buf.toString('hex')); + * }); + * ``` + * + * Any `ArrayBuffer`, `TypedArray`, or `DataView` instance may be passed as`buffer`. + * + * While this includes instances of `Float32Array` and `Float64Array`, this + * function should not be used to generate random floating-point numbers. The + * result may contain `+Infinity`, `-Infinity`, and `NaN`, and even if the array + * contains finite numbers only, they are not drawn from a uniform random + * distribution and have no meaningful lower or upper bounds. + * + * ```js + * import { Buffer } from 'buffer'; + * const { randomFill } = await import('crypto'); + * + * const a = new Uint32Array(10); + * randomFill(a, (err, buf) => { + * if (err) throw err; + * console.log(Buffer.from(buf.buffer, buf.byteOffset, buf.byteLength) + * .toString('hex')); + * }); + * + * const b = new DataView(new ArrayBuffer(10)); + * randomFill(b, (err, buf) => { + * if (err) throw err; + * console.log(Buffer.from(buf.buffer, buf.byteOffset, buf.byteLength) + * .toString('hex')); + * }); + * + * const c = new ArrayBuffer(10); + * randomFill(c, (err, buf) => { + * if (err) throw err; + * console.log(Buffer.from(buf).toString('hex')); + * }); + * ``` + * + * This API uses libuv's threadpool, which can have surprising and + * negative performance implications for some applications; see the `UV_THREADPOOL_SIZE` documentation for more information. + * + * The asynchronous version of `crypto.randomFill()` is carried out in a single + * threadpool request. To minimize threadpool task length variation, partition + * large `randomFill` requests when doing so as part of fulfilling a client + * request. + * @since v7.10.0, v6.13.0 + * @param buffer Must be supplied. The size of the provided `buffer` must not be larger than `2**31 - 1`. + * @param [offset=0] + * @param [size=buffer.length - offset] + * @param callback `function(err, buf) {}`. + */ + function randomFill(buffer: T, callback: (err: Error | null, buf: T) => void): void; + function randomFill(buffer: T, offset: number, callback: (err: Error | null, buf: T) => void): void; + function randomFill(buffer: T, offset: number, size: number, callback: (err: Error | null, buf: T) => void): void; + interface ScryptOptions { + cost?: number | undefined; + blockSize?: number | undefined; + parallelization?: number | undefined; + N?: number | undefined; + r?: number | undefined; + p?: number | undefined; + maxmem?: number | undefined; + } + /** + * Provides an asynchronous [scrypt](https://en.wikipedia.org/wiki/Scrypt) implementation. Scrypt is a password-based + * key derivation function that is designed to be expensive computationally and + * memory-wise in order to make brute-force attacks unrewarding. + * + * The `salt` should be as unique as possible. It is recommended that a salt is + * random and at least 16 bytes long. See [NIST SP 800-132](https://nvlpubs.nist.gov/nistpubs/Legacy/SP/nistspecialpublication800-132.pdf) for details. + * + * When passing strings for `password` or `salt`, please consider `caveats when using strings as inputs to cryptographic APIs`. + * + * The `callback` function is called with two arguments: `err` and `derivedKey`.`err` is an exception object when key derivation fails, otherwise `err` is`null`. `derivedKey` is passed to the + * callback as a `Buffer`. + * + * An exception is thrown when any of the input arguments specify invalid values + * or types. + * + * ```js + * const { + * scrypt + * } = await import('crypto'); + * + * // Using the factory defaults. + * scrypt('password', 'salt', 64, (err, derivedKey) => { + * if (err) throw err; + * console.log(derivedKey.toString('hex')); // '3745e48...08d59ae' + * }); + * // Using a custom N parameter. Must be a power of two. + * scrypt('password', 'salt', 64, { N: 1024 }, (err, derivedKey) => { + * if (err) throw err; + * console.log(derivedKey.toString('hex')); // '3745e48...aa39b34' + * }); + * ``` + * @since v10.5.0 + */ + function scrypt(password: BinaryLike, salt: BinaryLike, keylen: number, callback: (err: Error | null, derivedKey: Buffer) => void): void; + function scrypt(password: BinaryLike, salt: BinaryLike, keylen: number, options: ScryptOptions, callback: (err: Error | null, derivedKey: Buffer) => void): void; + /** + * Provides a synchronous [scrypt](https://en.wikipedia.org/wiki/Scrypt) implementation. Scrypt is a password-based + * key derivation function that is designed to be expensive computationally and + * memory-wise in order to make brute-force attacks unrewarding. + * + * The `salt` should be as unique as possible. It is recommended that a salt is + * random and at least 16 bytes long. See [NIST SP 800-132](https://nvlpubs.nist.gov/nistpubs/Legacy/SP/nistspecialpublication800-132.pdf) for details. + * + * When passing strings for `password` or `salt`, please consider `caveats when using strings as inputs to cryptographic APIs`. + * + * An exception is thrown when key derivation fails, otherwise the derived key is + * returned as a `Buffer`. + * + * An exception is thrown when any of the input arguments specify invalid values + * or types. + * + * ```js + * const { + * scryptSync + * } = await import('crypto'); + * // Using the factory defaults. + * + * const key1 = scryptSync('password', 'salt', 64); + * console.log(key1.toString('hex')); // '3745e48...08d59ae' + * // Using a custom N parameter. Must be a power of two. + * const key2 = scryptSync('password', 'salt', 64, { N: 1024 }); + * console.log(key2.toString('hex')); // '3745e48...aa39b34' + * ``` + * @since v10.5.0 + */ + function scryptSync(password: BinaryLike, salt: BinaryLike, keylen: number, options?: ScryptOptions): Buffer; + interface RsaPublicKey { + key: KeyLike; + padding?: number | undefined; + } + interface RsaPrivateKey { + key: KeyLike; + passphrase?: string | undefined; + /** + * @default 'sha1' + */ + oaepHash?: string | undefined; + oaepLabel?: NodeJS.TypedArray | undefined; + padding?: number | undefined; + } + /** + * Encrypts the content of `buffer` with `key` and returns a new `Buffer` with encrypted content. The returned data can be decrypted using + * the corresponding private key, for example using {@link privateDecrypt}. + * + * If `key` is not a `KeyObject`, this function behaves as if`key` had been passed to {@link createPublicKey}. If it is an + * object, the `padding` property can be passed. Otherwise, this function uses`RSA_PKCS1_OAEP_PADDING`. + * + * Because RSA public keys can be derived from private keys, a private key may + * be passed instead of a public key. + * @since v0.11.14 + */ + function publicEncrypt(key: RsaPublicKey | RsaPrivateKey | KeyLike, buffer: NodeJS.ArrayBufferView): Buffer; + /** + * Decrypts `buffer` with `key`.`buffer` was previously encrypted using + * the corresponding private key, for example using {@link privateEncrypt}. + * + * If `key` is not a `KeyObject`, this function behaves as if`key` had been passed to {@link createPublicKey}. If it is an + * object, the `padding` property can be passed. Otherwise, this function uses`RSA_PKCS1_PADDING`. + * + * Because RSA public keys can be derived from private keys, a private key may + * be passed instead of a public key. + * @since v1.1.0 + */ + function publicDecrypt(key: RsaPublicKey | RsaPrivateKey | KeyLike, buffer: NodeJS.ArrayBufferView): Buffer; + /** + * Decrypts `buffer` with `privateKey`. `buffer` was previously encrypted using + * the corresponding public key, for example using {@link publicEncrypt}. + * + * If `privateKey` is not a `KeyObject`, this function behaves as if`privateKey` had been passed to {@link createPrivateKey}. If it is an + * object, the `padding` property can be passed. Otherwise, this function uses`RSA_PKCS1_OAEP_PADDING`. + * @since v0.11.14 + */ + function privateDecrypt(privateKey: RsaPrivateKey | KeyLike, buffer: NodeJS.ArrayBufferView): Buffer; + /** + * Encrypts `buffer` with `privateKey`. The returned data can be decrypted using + * the corresponding public key, for example using {@link publicDecrypt}. + * + * If `privateKey` is not a `KeyObject`, this function behaves as if`privateKey` had been passed to {@link createPrivateKey}. If it is an + * object, the `padding` property can be passed. Otherwise, this function uses`RSA_PKCS1_PADDING`. + * @since v1.1.0 + */ + function privateEncrypt(privateKey: RsaPrivateKey | KeyLike, buffer: NodeJS.ArrayBufferView): Buffer; + /** + * ```js + * const { + * getCiphers + * } = await import('crypto'); + * + * console.log(getCiphers()); // ['aes-128-cbc', 'aes-128-ccm', ...] + * ``` + * @since v0.9.3 + * @return An array with the names of the supported cipher algorithms. + */ + function getCiphers(): string[]; + /** + * ```js + * const { + * getCurves + * } = await import('crypto'); + * + * console.log(getCurves()); // ['Oakley-EC2N-3', 'Oakley-EC2N-4', ...] + * ``` + * @since v2.3.0 + * @return An array with the names of the supported elliptic curves. + */ + function getCurves(): string[]; + /** + * @since v10.0.0 + * @return `1` if and only if a FIPS compliant crypto provider is currently in use, `0` otherwise. A future semver-major release may change the return type of this API to a {boolean}. + */ + function getFips(): 1 | 0; + /** + * Enables the FIPS compliant crypto provider in a FIPS-enabled Node.js build. Throws an error if FIPS mode is not available. + * @since v10.0.0 + * @param bool `true` to enable FIPS mode. + */ + function setFips(bool: boolean): void; + /** + * ```js + * const { + * getHashes + * } = await import('crypto'); + * + * console.log(getHashes()); // ['DSA', 'DSA-SHA', 'DSA-SHA1', ...] + * ``` + * @since v0.9.3 + * @return An array of the names of the supported hash algorithms, such as `'RSA-SHA256'`. Hash algorithms are also called "digest" algorithms. + */ + function getHashes(): string[]; + /** + * The `ECDH` class is a utility for creating Elliptic Curve Diffie-Hellman (ECDH) + * key exchanges. + * + * Instances of the `ECDH` class can be created using the {@link createECDH} function. + * + * ```js + * import assert from 'assert'; + * + * const { + * createECDH + * } = await import('crypto'); + * + * // Generate Alice's keys... + * const alice = createECDH('secp521r1'); + * const aliceKey = alice.generateKeys(); + * + * // Generate Bob's keys... + * const bob = createECDH('secp521r1'); + * const bobKey = bob.generateKeys(); + * + * // Exchange and generate the secret... + * const aliceSecret = alice.computeSecret(bobKey); + * const bobSecret = bob.computeSecret(aliceKey); + * + * assert.strictEqual(aliceSecret.toString('hex'), bobSecret.toString('hex')); + * // OK + * ``` + * @since v0.11.14 + */ + class ECDH { + private constructor(); + /** + * Converts the EC Diffie-Hellman public key specified by `key` and `curve` to the + * format specified by `format`. The `format` argument specifies point encoding + * and can be `'compressed'`, `'uncompressed'` or `'hybrid'`. The supplied key is + * interpreted using the specified `inputEncoding`, and the returned key is encoded + * using the specified `outputEncoding`. + * + * Use {@link getCurves} to obtain a list of available curve names. + * On recent OpenSSL releases, `openssl ecparam -list_curves` will also display + * the name and description of each available elliptic curve. + * + * If `format` is not specified the point will be returned in `'uncompressed'`format. + * + * If the `inputEncoding` is not provided, `key` is expected to be a `Buffer`,`TypedArray`, or `DataView`. + * + * Example (uncompressing a key): + * + * ```js + * const { + * createECDH, + * ECDH + * } = await import('crypto'); + * + * const ecdh = createECDH('secp256k1'); + * ecdh.generateKeys(); + * + * const compressedKey = ecdh.getPublicKey('hex', 'compressed'); + * + * const uncompressedKey = ECDH.convertKey(compressedKey, + * 'secp256k1', + * 'hex', + * 'hex', + * 'uncompressed'); + * + * // The converted key and the uncompressed public key should be the same + * console.log(uncompressedKey === ecdh.getPublicKey('hex')); + * ``` + * @since v10.0.0 + * @param inputEncoding The `encoding` of the `key` string. + * @param outputEncoding The `encoding` of the return value. + * @param [format='uncompressed'] + */ + static convertKey( + key: BinaryLike, + curve: string, + inputEncoding?: BinaryToTextEncoding, + outputEncoding?: 'latin1' | 'hex' | 'base64' | 'base64url', + format?: 'uncompressed' | 'compressed' | 'hybrid' + ): Buffer | string; + /** + * Generates private and public EC Diffie-Hellman key values, and returns + * the public key in the specified `format` and `encoding`. This key should be + * transferred to the other party. + * + * The `format` argument specifies point encoding and can be `'compressed'` or`'uncompressed'`. If `format` is not specified, the point will be returned in`'uncompressed'` format. + * + * If `encoding` is provided a string is returned; otherwise a `Buffer` is returned. + * @since v0.11.14 + * @param encoding The `encoding` of the return value. + * @param [format='uncompressed'] + */ + generateKeys(): Buffer; + generateKeys(encoding: BinaryToTextEncoding, format?: ECDHKeyFormat): string; + /** + * Computes the shared secret using `otherPublicKey` as the other + * party's public key and returns the computed shared secret. The supplied + * key is interpreted using specified `inputEncoding`, and the returned secret + * is encoded using the specified `outputEncoding`. + * If the `inputEncoding` is not + * provided, `otherPublicKey` is expected to be a `Buffer`, `TypedArray`, or`DataView`. + * + * If `outputEncoding` is given a string will be returned; otherwise a `Buffer` is returned. + * + * `ecdh.computeSecret` will throw an`ERR_CRYPTO_ECDH_INVALID_PUBLIC_KEY` error when `otherPublicKey`lies outside of the elliptic curve. Since `otherPublicKey` is + * usually supplied from a remote user over an insecure network, + * be sure to handle this exception accordingly. + * @since v0.11.14 + * @param inputEncoding The `encoding` of the `otherPublicKey` string. + * @param outputEncoding The `encoding` of the return value. + */ + computeSecret(otherPublicKey: NodeJS.ArrayBufferView): Buffer; + computeSecret(otherPublicKey: string, inputEncoding: BinaryToTextEncoding): Buffer; + computeSecret(otherPublicKey: NodeJS.ArrayBufferView, outputEncoding: BinaryToTextEncoding): string; + computeSecret(otherPublicKey: string, inputEncoding: BinaryToTextEncoding, outputEncoding: BinaryToTextEncoding): string; + /** + * If `encoding` is specified, a string is returned; otherwise a `Buffer` is + * returned. + * @since v0.11.14 + * @param encoding The `encoding` of the return value. + * @return The EC Diffie-Hellman in the specified `encoding`. + */ + getPrivateKey(): Buffer; + getPrivateKey(encoding: BinaryToTextEncoding): string; + /** + * The `format` argument specifies point encoding and can be `'compressed'` or`'uncompressed'`. If `format` is not specified the point will be returned in`'uncompressed'` format. + * + * If `encoding` is specified, a string is returned; otherwise a `Buffer` is + * returned. + * @since v0.11.14 + * @param encoding The `encoding` of the return value. + * @param [format='uncompressed'] + * @return The EC Diffie-Hellman public key in the specified `encoding` and `format`. + */ + getPublicKey(): Buffer; + getPublicKey(encoding: BinaryToTextEncoding, format?: ECDHKeyFormat): string; + /** + * Sets the EC Diffie-Hellman private key. + * If `encoding` is provided, `privateKey` is expected + * to be a string; otherwise `privateKey` is expected to be a `Buffer`,`TypedArray`, or `DataView`. + * + * If `privateKey` is not valid for the curve specified when the `ECDH` object was + * created, an error is thrown. Upon setting the private key, the associated + * public point (key) is also generated and set in the `ECDH` object. + * @since v0.11.14 + * @param encoding The `encoding` of the `privateKey` string. + */ + setPrivateKey(privateKey: NodeJS.ArrayBufferView): void; + setPrivateKey(privateKey: string, encoding: BinaryToTextEncoding): void; + } + /** + * Creates an Elliptic Curve Diffie-Hellman (`ECDH`) key exchange object using a + * predefined curve specified by the `curveName` string. Use {@link getCurves} to obtain a list of available curve names. On recent + * OpenSSL releases, `openssl ecparam -list_curves` will also display the name + * and description of each available elliptic curve. + * @since v0.11.14 + */ + function createECDH(curveName: string): ECDH; + /** + * This function is based on a constant-time algorithm. + * Returns true if `a` is equal to `b`, without leaking timing information that + * would allow an attacker to guess one of the values. This is suitable for + * comparing HMAC digests or secret values like authentication cookies or [capability urls](https://www.w3.org/TR/capability-urls/). + * + * `a` and `b` must both be `Buffer`s, `TypedArray`s, or `DataView`s, and they + * must have the same byte length. An error is thrown if `a` and `b` have + * different byte lengths. + * + * If at least one of `a` and `b` is a `TypedArray` with more than one byte per + * entry, such as `Uint16Array`, the result will be computed using the platform + * byte order. + * + * Use of `crypto.timingSafeEqual` does not guarantee that the _surrounding_ code + * is timing-safe. Care should be taken to ensure that the surrounding code does + * not introduce timing vulnerabilities. + * @since v6.6.0 + */ + function timingSafeEqual(a: NodeJS.ArrayBufferView, b: NodeJS.ArrayBufferView): boolean; + /** @deprecated since v10.0.0 */ + const DEFAULT_ENCODING: BufferEncoding; + type KeyType = 'rsa' | 'rsa-pss' | 'dsa' | 'ec' | 'ed25519' | 'ed448' | 'x25519' | 'x448'; + type KeyFormat = 'pem' | 'der'; + interface BasePrivateKeyEncodingOptions { + format: T; + cipher?: string | undefined; + passphrase?: string | undefined; + } + interface KeyPairKeyObjectResult { + publicKey: KeyObject; + privateKey: KeyObject; + } + interface ED25519KeyPairKeyObjectOptions {} + interface ED448KeyPairKeyObjectOptions {} + interface X25519KeyPairKeyObjectOptions {} + interface X448KeyPairKeyObjectOptions {} + interface ECKeyPairKeyObjectOptions { + /** + * Name of the curve to use + */ + namedCurve: string; + } + interface RSAKeyPairKeyObjectOptions { + /** + * Key size in bits + */ + modulusLength: number; + /** + * Public exponent + * @default 0x10001 + */ + publicExponent?: number | undefined; + } + interface RSAPSSKeyPairKeyObjectOptions { + /** + * Key size in bits + */ + modulusLength: number; + /** + * Public exponent + * @default 0x10001 + */ + publicExponent?: number | undefined; + /** + * Name of the message digest + */ + hashAlgorithm?: string; + /** + * Name of the message digest used by MGF1 + */ + mgf1HashAlgorithm?: string; + /** + * Minimal salt length in bytes + */ + saltLength?: string; + } + interface DSAKeyPairKeyObjectOptions { + /** + * Key size in bits + */ + modulusLength: number; + /** + * Size of q in bits + */ + divisorLength: number; + } + interface RSAKeyPairOptions { + /** + * Key size in bits + */ + modulusLength: number; + /** + * Public exponent + * @default 0x10001 + */ + publicExponent?: number | undefined; + publicKeyEncoding: { + type: 'pkcs1' | 'spki'; + format: PubF; + }; + privateKeyEncoding: BasePrivateKeyEncodingOptions & { + type: 'pkcs1' | 'pkcs8'; + }; + } + interface RSAPSSKeyPairOptions { + /** + * Key size in bits + */ + modulusLength: number; + /** + * Public exponent + * @default 0x10001 + */ + publicExponent?: number | undefined; + /** + * Name of the message digest + */ + hashAlgorithm?: string; + /** + * Name of the message digest used by MGF1 + */ + mgf1HashAlgorithm?: string; + /** + * Minimal salt length in bytes + */ + saltLength?: string; + publicKeyEncoding: { + type: 'spki'; + format: PubF; + }; + privateKeyEncoding: BasePrivateKeyEncodingOptions & { + type: 'pkcs8'; + }; + } + interface DSAKeyPairOptions { + /** + * Key size in bits + */ + modulusLength: number; + /** + * Size of q in bits + */ + divisorLength: number; + publicKeyEncoding: { + type: 'spki'; + format: PubF; + }; + privateKeyEncoding: BasePrivateKeyEncodingOptions & { + type: 'pkcs8'; + }; + } + interface ECKeyPairOptions { + /** + * Name of the curve to use. + */ + namedCurve: string; + publicKeyEncoding: { + type: 'pkcs1' | 'spki'; + format: PubF; + }; + privateKeyEncoding: BasePrivateKeyEncodingOptions & { + type: 'sec1' | 'pkcs8'; + }; + } + interface ED25519KeyPairOptions { + publicKeyEncoding: { + type: 'spki'; + format: PubF; + }; + privateKeyEncoding: BasePrivateKeyEncodingOptions & { + type: 'pkcs8'; + }; + } + interface ED448KeyPairOptions { + publicKeyEncoding: { + type: 'spki'; + format: PubF; + }; + privateKeyEncoding: BasePrivateKeyEncodingOptions & { + type: 'pkcs8'; + }; + } + interface X25519KeyPairOptions { + publicKeyEncoding: { + type: 'spki'; + format: PubF; + }; + privateKeyEncoding: BasePrivateKeyEncodingOptions & { + type: 'pkcs8'; + }; + } + interface X448KeyPairOptions { + publicKeyEncoding: { + type: 'spki'; + format: PubF; + }; + privateKeyEncoding: BasePrivateKeyEncodingOptions & { + type: 'pkcs8'; + }; + } + interface KeyPairSyncResult { + publicKey: T1; + privateKey: T2; + } + /** + * Generates a new asymmetric key pair of the given `type`. RSA, RSA-PSS, DSA, EC, + * Ed25519, Ed448, X25519, X448, and DH are currently supported. + * + * If a `publicKeyEncoding` or `privateKeyEncoding` was specified, this function + * behaves as if `keyObject.export()` had been called on its result. Otherwise, + * the respective part of the key is returned as a `KeyObject`. + * + * When encoding public keys, it is recommended to use `'spki'`. When encoding + * private keys, it is recommended to use `'pkcs8'` with a strong passphrase, + * and to keep the passphrase confidential. + * + * ```js + * const { + * generateKeyPairSync + * } = await import('crypto'); + * + * const { + * publicKey, + * privateKey, + * } = generateKeyPairSync('rsa', { + * modulusLength: 4096, + * publicKeyEncoding: { + * type: 'spki', + * format: 'pem' + * }, + * privateKeyEncoding: { + * type: 'pkcs8', + * format: 'pem', + * cipher: 'aes-256-cbc', + * passphrase: 'top secret' + * } + * }); + * ``` + * + * The return value `{ publicKey, privateKey }` represents the generated key pair. + * When PEM encoding was selected, the respective key will be a string, otherwise + * it will be a buffer containing the data encoded as DER. + * @since v10.12.0 + * @param type Must be `'rsa'`, `'rsa-pss'`, `'dsa'`, `'ec'`, `'ed25519'`, `'ed448'`, `'x25519'`, `'x448'`, or `'dh'`. + */ + function generateKeyPairSync(type: 'rsa', options: RSAKeyPairOptions<'pem', 'pem'>): KeyPairSyncResult; + function generateKeyPairSync(type: 'rsa', options: RSAKeyPairOptions<'pem', 'der'>): KeyPairSyncResult; + function generateKeyPairSync(type: 'rsa', options: RSAKeyPairOptions<'der', 'pem'>): KeyPairSyncResult; + function generateKeyPairSync(type: 'rsa', options: RSAKeyPairOptions<'der', 'der'>): KeyPairSyncResult; + function generateKeyPairSync(type: 'rsa', options: RSAKeyPairKeyObjectOptions): KeyPairKeyObjectResult; + function generateKeyPairSync(type: 'rsa-pss', options: RSAPSSKeyPairOptions<'pem', 'pem'>): KeyPairSyncResult; + function generateKeyPairSync(type: 'rsa-pss', options: RSAPSSKeyPairOptions<'pem', 'der'>): KeyPairSyncResult; + function generateKeyPairSync(type: 'rsa-pss', options: RSAPSSKeyPairOptions<'der', 'pem'>): KeyPairSyncResult; + function generateKeyPairSync(type: 'rsa-pss', options: RSAPSSKeyPairOptions<'der', 'der'>): KeyPairSyncResult; + function generateKeyPairSync(type: 'rsa-pss', options: RSAPSSKeyPairKeyObjectOptions): KeyPairKeyObjectResult; + function generateKeyPairSync(type: 'dsa', options: DSAKeyPairOptions<'pem', 'pem'>): KeyPairSyncResult; + function generateKeyPairSync(type: 'dsa', options: DSAKeyPairOptions<'pem', 'der'>): KeyPairSyncResult; + function generateKeyPairSync(type: 'dsa', options: DSAKeyPairOptions<'der', 'pem'>): KeyPairSyncResult; + function generateKeyPairSync(type: 'dsa', options: DSAKeyPairOptions<'der', 'der'>): KeyPairSyncResult; + function generateKeyPairSync(type: 'dsa', options: DSAKeyPairKeyObjectOptions): KeyPairKeyObjectResult; + function generateKeyPairSync(type: 'ec', options: ECKeyPairOptions<'pem', 'pem'>): KeyPairSyncResult; + function generateKeyPairSync(type: 'ec', options: ECKeyPairOptions<'pem', 'der'>): KeyPairSyncResult; + function generateKeyPairSync(type: 'ec', options: ECKeyPairOptions<'der', 'pem'>): KeyPairSyncResult; + function generateKeyPairSync(type: 'ec', options: ECKeyPairOptions<'der', 'der'>): KeyPairSyncResult; + function generateKeyPairSync(type: 'ec', options: ECKeyPairKeyObjectOptions): KeyPairKeyObjectResult; + function generateKeyPairSync(type: 'ed25519', options: ED25519KeyPairOptions<'pem', 'pem'>): KeyPairSyncResult; + function generateKeyPairSync(type: 'ed25519', options: ED25519KeyPairOptions<'pem', 'der'>): KeyPairSyncResult; + function generateKeyPairSync(type: 'ed25519', options: ED25519KeyPairOptions<'der', 'pem'>): KeyPairSyncResult; + function generateKeyPairSync(type: 'ed25519', options: ED25519KeyPairOptions<'der', 'der'>): KeyPairSyncResult; + function generateKeyPairSync(type: 'ed25519', options?: ED25519KeyPairKeyObjectOptions): KeyPairKeyObjectResult; + function generateKeyPairSync(type: 'ed448', options: ED448KeyPairOptions<'pem', 'pem'>): KeyPairSyncResult; + function generateKeyPairSync(type: 'ed448', options: ED448KeyPairOptions<'pem', 'der'>): KeyPairSyncResult; + function generateKeyPairSync(type: 'ed448', options: ED448KeyPairOptions<'der', 'pem'>): KeyPairSyncResult; + function generateKeyPairSync(type: 'ed448', options: ED448KeyPairOptions<'der', 'der'>): KeyPairSyncResult; + function generateKeyPairSync(type: 'ed448', options?: ED448KeyPairKeyObjectOptions): KeyPairKeyObjectResult; + function generateKeyPairSync(type: 'x25519', options: X25519KeyPairOptions<'pem', 'pem'>): KeyPairSyncResult; + function generateKeyPairSync(type: 'x25519', options: X25519KeyPairOptions<'pem', 'der'>): KeyPairSyncResult; + function generateKeyPairSync(type: 'x25519', options: X25519KeyPairOptions<'der', 'pem'>): KeyPairSyncResult; + function generateKeyPairSync(type: 'x25519', options: X25519KeyPairOptions<'der', 'der'>): KeyPairSyncResult; + function generateKeyPairSync(type: 'x25519', options?: X25519KeyPairKeyObjectOptions): KeyPairKeyObjectResult; + function generateKeyPairSync(type: 'x448', options: X448KeyPairOptions<'pem', 'pem'>): KeyPairSyncResult; + function generateKeyPairSync(type: 'x448', options: X448KeyPairOptions<'pem', 'der'>): KeyPairSyncResult; + function generateKeyPairSync(type: 'x448', options: X448KeyPairOptions<'der', 'pem'>): KeyPairSyncResult; + function generateKeyPairSync(type: 'x448', options: X448KeyPairOptions<'der', 'der'>): KeyPairSyncResult; + function generateKeyPairSync(type: 'x448', options?: X448KeyPairKeyObjectOptions): KeyPairKeyObjectResult; + /** + * Generates a new asymmetric key pair of the given `type`. RSA, RSA-PSS, DSA, EC, + * Ed25519, Ed448, X25519, X448, and DH are currently supported. + * + * If a `publicKeyEncoding` or `privateKeyEncoding` was specified, this function + * behaves as if `keyObject.export()` had been called on its result. Otherwise, + * the respective part of the key is returned as a `KeyObject`. + * + * It is recommended to encode public keys as `'spki'` and private keys as`'pkcs8'` with encryption for long-term storage: + * + * ```js + * const { + * generateKeyPair + * } = await import('crypto'); + * + * generateKeyPair('rsa', { + * modulusLength: 4096, + * publicKeyEncoding: { + * type: 'spki', + * format: 'pem' + * }, + * privateKeyEncoding: { + * type: 'pkcs8', + * format: 'pem', + * cipher: 'aes-256-cbc', + * passphrase: 'top secret' + * } + * }, (err, publicKey, privateKey) => { + * // Handle errors and use the generated key pair. + * }); + * ``` + * + * On completion, `callback` will be called with `err` set to `undefined` and`publicKey` / `privateKey` representing the generated key pair. + * + * If this method is invoked as its `util.promisify()` ed version, it returns + * a `Promise` for an `Object` with `publicKey` and `privateKey` properties. + * @since v10.12.0 + * @param type Must be `'rsa'`, `'rsa-pss'`, `'dsa'`, `'ec'`, `'ed25519'`, `'ed448'`, `'x25519'`, `'x448'`, or `'dh'`. + */ + function generateKeyPair(type: 'rsa', options: RSAKeyPairOptions<'pem', 'pem'>, callback: (err: Error | null, publicKey: string, privateKey: string) => void): void; + function generateKeyPair(type: 'rsa', options: RSAKeyPairOptions<'pem', 'der'>, callback: (err: Error | null, publicKey: string, privateKey: Buffer) => void): void; + function generateKeyPair(type: 'rsa', options: RSAKeyPairOptions<'der', 'pem'>, callback: (err: Error | null, publicKey: Buffer, privateKey: string) => void): void; + function generateKeyPair(type: 'rsa', options: RSAKeyPairOptions<'der', 'der'>, callback: (err: Error | null, publicKey: Buffer, privateKey: Buffer) => void): void; + function generateKeyPair(type: 'rsa', options: RSAKeyPairKeyObjectOptions, callback: (err: Error | null, publicKey: KeyObject, privateKey: KeyObject) => void): void; + function generateKeyPair(type: 'rsa-pss', options: RSAPSSKeyPairOptions<'pem', 'pem'>, callback: (err: Error | null, publicKey: string, privateKey: string) => void): void; + function generateKeyPair(type: 'rsa-pss', options: RSAPSSKeyPairOptions<'pem', 'der'>, callback: (err: Error | null, publicKey: string, privateKey: Buffer) => void): void; + function generateKeyPair(type: 'rsa-pss', options: RSAPSSKeyPairOptions<'der', 'pem'>, callback: (err: Error | null, publicKey: Buffer, privateKey: string) => void): void; + function generateKeyPair(type: 'rsa-pss', options: RSAPSSKeyPairOptions<'der', 'der'>, callback: (err: Error | null, publicKey: Buffer, privateKey: Buffer) => void): void; + function generateKeyPair(type: 'rsa-pss', options: RSAPSSKeyPairKeyObjectOptions, callback: (err: Error | null, publicKey: KeyObject, privateKey: KeyObject) => void): void; + function generateKeyPair(type: 'dsa', options: DSAKeyPairOptions<'pem', 'pem'>, callback: (err: Error | null, publicKey: string, privateKey: string) => void): void; + function generateKeyPair(type: 'dsa', options: DSAKeyPairOptions<'pem', 'der'>, callback: (err: Error | null, publicKey: string, privateKey: Buffer) => void): void; + function generateKeyPair(type: 'dsa', options: DSAKeyPairOptions<'der', 'pem'>, callback: (err: Error | null, publicKey: Buffer, privateKey: string) => void): void; + function generateKeyPair(type: 'dsa', options: DSAKeyPairOptions<'der', 'der'>, callback: (err: Error | null, publicKey: Buffer, privateKey: Buffer) => void): void; + function generateKeyPair(type: 'dsa', options: DSAKeyPairKeyObjectOptions, callback: (err: Error | null, publicKey: KeyObject, privateKey: KeyObject) => void): void; + function generateKeyPair(type: 'ec', options: ECKeyPairOptions<'pem', 'pem'>, callback: (err: Error | null, publicKey: string, privateKey: string) => void): void; + function generateKeyPair(type: 'ec', options: ECKeyPairOptions<'pem', 'der'>, callback: (err: Error | null, publicKey: string, privateKey: Buffer) => void): void; + function generateKeyPair(type: 'ec', options: ECKeyPairOptions<'der', 'pem'>, callback: (err: Error | null, publicKey: Buffer, privateKey: string) => void): void; + function generateKeyPair(type: 'ec', options: ECKeyPairOptions<'der', 'der'>, callback: (err: Error | null, publicKey: Buffer, privateKey: Buffer) => void): void; + function generateKeyPair(type: 'ec', options: ECKeyPairKeyObjectOptions, callback: (err: Error | null, publicKey: KeyObject, privateKey: KeyObject) => void): void; + function generateKeyPair(type: 'ed25519', options: ED25519KeyPairOptions<'pem', 'pem'>, callback: (err: Error | null, publicKey: string, privateKey: string) => void): void; + function generateKeyPair(type: 'ed25519', options: ED25519KeyPairOptions<'pem', 'der'>, callback: (err: Error | null, publicKey: string, privateKey: Buffer) => void): void; + function generateKeyPair(type: 'ed25519', options: ED25519KeyPairOptions<'der', 'pem'>, callback: (err: Error | null, publicKey: Buffer, privateKey: string) => void): void; + function generateKeyPair(type: 'ed25519', options: ED25519KeyPairOptions<'der', 'der'>, callback: (err: Error | null, publicKey: Buffer, privateKey: Buffer) => void): void; + function generateKeyPair(type: 'ed25519', options: ED25519KeyPairKeyObjectOptions | undefined, callback: (err: Error | null, publicKey: KeyObject, privateKey: KeyObject) => void): void; + function generateKeyPair(type: 'ed448', options: ED448KeyPairOptions<'pem', 'pem'>, callback: (err: Error | null, publicKey: string, privateKey: string) => void): void; + function generateKeyPair(type: 'ed448', options: ED448KeyPairOptions<'pem', 'der'>, callback: (err: Error | null, publicKey: string, privateKey: Buffer) => void): void; + function generateKeyPair(type: 'ed448', options: ED448KeyPairOptions<'der', 'pem'>, callback: (err: Error | null, publicKey: Buffer, privateKey: string) => void): void; + function generateKeyPair(type: 'ed448', options: ED448KeyPairOptions<'der', 'der'>, callback: (err: Error | null, publicKey: Buffer, privateKey: Buffer) => void): void; + function generateKeyPair(type: 'ed448', options: ED448KeyPairKeyObjectOptions | undefined, callback: (err: Error | null, publicKey: KeyObject, privateKey: KeyObject) => void): void; + function generateKeyPair(type: 'x25519', options: X25519KeyPairOptions<'pem', 'pem'>, callback: (err: Error | null, publicKey: string, privateKey: string) => void): void; + function generateKeyPair(type: 'x25519', options: X25519KeyPairOptions<'pem', 'der'>, callback: (err: Error | null, publicKey: string, privateKey: Buffer) => void): void; + function generateKeyPair(type: 'x25519', options: X25519KeyPairOptions<'der', 'pem'>, callback: (err: Error | null, publicKey: Buffer, privateKey: string) => void): void; + function generateKeyPair(type: 'x25519', options: X25519KeyPairOptions<'der', 'der'>, callback: (err: Error | null, publicKey: Buffer, privateKey: Buffer) => void): void; + function generateKeyPair(type: 'x25519', options: X25519KeyPairKeyObjectOptions | undefined, callback: (err: Error | null, publicKey: KeyObject, privateKey: KeyObject) => void): void; + function generateKeyPair(type: 'x448', options: X448KeyPairOptions<'pem', 'pem'>, callback: (err: Error | null, publicKey: string, privateKey: string) => void): void; + function generateKeyPair(type: 'x448', options: X448KeyPairOptions<'pem', 'der'>, callback: (err: Error | null, publicKey: string, privateKey: Buffer) => void): void; + function generateKeyPair(type: 'x448', options: X448KeyPairOptions<'der', 'pem'>, callback: (err: Error | null, publicKey: Buffer, privateKey: string) => void): void; + function generateKeyPair(type: 'x448', options: X448KeyPairOptions<'der', 'der'>, callback: (err: Error | null, publicKey: Buffer, privateKey: Buffer) => void): void; + function generateKeyPair(type: 'x448', options: X448KeyPairKeyObjectOptions | undefined, callback: (err: Error | null, publicKey: KeyObject, privateKey: KeyObject) => void): void; + namespace generateKeyPair { + function __promisify__( + type: 'rsa', + options: RSAKeyPairOptions<'pem', 'pem'> + ): Promise<{ + publicKey: string; + privateKey: string; + }>; + function __promisify__( + type: 'rsa', + options: RSAKeyPairOptions<'pem', 'der'> + ): Promise<{ + publicKey: string; + privateKey: Buffer; + }>; + function __promisify__( + type: 'rsa', + options: RSAKeyPairOptions<'der', 'pem'> + ): Promise<{ + publicKey: Buffer; + privateKey: string; + }>; + function __promisify__( + type: 'rsa', + options: RSAKeyPairOptions<'der', 'der'> + ): Promise<{ + publicKey: Buffer; + privateKey: Buffer; + }>; + function __promisify__(type: 'rsa', options: RSAKeyPairKeyObjectOptions): Promise; + function __promisify__( + type: 'rsa-pss', + options: RSAPSSKeyPairOptions<'pem', 'pem'> + ): Promise<{ + publicKey: string; + privateKey: string; + }>; + function __promisify__( + type: 'rsa-pss', + options: RSAPSSKeyPairOptions<'pem', 'der'> + ): Promise<{ + publicKey: string; + privateKey: Buffer; + }>; + function __promisify__( + type: 'rsa-pss', + options: RSAPSSKeyPairOptions<'der', 'pem'> + ): Promise<{ + publicKey: Buffer; + privateKey: string; + }>; + function __promisify__( + type: 'rsa-pss', + options: RSAPSSKeyPairOptions<'der', 'der'> + ): Promise<{ + publicKey: Buffer; + privateKey: Buffer; + }>; + function __promisify__(type: 'rsa-pss', options: RSAPSSKeyPairKeyObjectOptions): Promise; + function __promisify__( + type: 'dsa', + options: DSAKeyPairOptions<'pem', 'pem'> + ): Promise<{ + publicKey: string; + privateKey: string; + }>; + function __promisify__( + type: 'dsa', + options: DSAKeyPairOptions<'pem', 'der'> + ): Promise<{ + publicKey: string; + privateKey: Buffer; + }>; + function __promisify__( + type: 'dsa', + options: DSAKeyPairOptions<'der', 'pem'> + ): Promise<{ + publicKey: Buffer; + privateKey: string; + }>; + function __promisify__( + type: 'dsa', + options: DSAKeyPairOptions<'der', 'der'> + ): Promise<{ + publicKey: Buffer; + privateKey: Buffer; + }>; + function __promisify__(type: 'dsa', options: DSAKeyPairKeyObjectOptions): Promise; + function __promisify__( + type: 'ec', + options: ECKeyPairOptions<'pem', 'pem'> + ): Promise<{ + publicKey: string; + privateKey: string; + }>; + function __promisify__( + type: 'ec', + options: ECKeyPairOptions<'pem', 'der'> + ): Promise<{ + publicKey: string; + privateKey: Buffer; + }>; + function __promisify__( + type: 'ec', + options: ECKeyPairOptions<'der', 'pem'> + ): Promise<{ + publicKey: Buffer; + privateKey: string; + }>; + function __promisify__( + type: 'ec', + options: ECKeyPairOptions<'der', 'der'> + ): Promise<{ + publicKey: Buffer; + privateKey: Buffer; + }>; + function __promisify__(type: 'ec', options: ECKeyPairKeyObjectOptions): Promise; + function __promisify__( + type: 'ed25519', + options: ED25519KeyPairOptions<'pem', 'pem'> + ): Promise<{ + publicKey: string; + privateKey: string; + }>; + function __promisify__( + type: 'ed25519', + options: ED25519KeyPairOptions<'pem', 'der'> + ): Promise<{ + publicKey: string; + privateKey: Buffer; + }>; + function __promisify__( + type: 'ed25519', + options: ED25519KeyPairOptions<'der', 'pem'> + ): Promise<{ + publicKey: Buffer; + privateKey: string; + }>; + function __promisify__( + type: 'ed25519', + options: ED25519KeyPairOptions<'der', 'der'> + ): Promise<{ + publicKey: Buffer; + privateKey: Buffer; + }>; + function __promisify__(type: 'ed25519', options?: ED25519KeyPairKeyObjectOptions): Promise; + function __promisify__( + type: 'ed448', + options: ED448KeyPairOptions<'pem', 'pem'> + ): Promise<{ + publicKey: string; + privateKey: string; + }>; + function __promisify__( + type: 'ed448', + options: ED448KeyPairOptions<'pem', 'der'> + ): Promise<{ + publicKey: string; + privateKey: Buffer; + }>; + function __promisify__( + type: 'ed448', + options: ED448KeyPairOptions<'der', 'pem'> + ): Promise<{ + publicKey: Buffer; + privateKey: string; + }>; + function __promisify__( + type: 'ed448', + options: ED448KeyPairOptions<'der', 'der'> + ): Promise<{ + publicKey: Buffer; + privateKey: Buffer; + }>; + function __promisify__(type: 'ed448', options?: ED448KeyPairKeyObjectOptions): Promise; + function __promisify__( + type: 'x25519', + options: X25519KeyPairOptions<'pem', 'pem'> + ): Promise<{ + publicKey: string; + privateKey: string; + }>; + function __promisify__( + type: 'x25519', + options: X25519KeyPairOptions<'pem', 'der'> + ): Promise<{ + publicKey: string; + privateKey: Buffer; + }>; + function __promisify__( + type: 'x25519', + options: X25519KeyPairOptions<'der', 'pem'> + ): Promise<{ + publicKey: Buffer; + privateKey: string; + }>; + function __promisify__( + type: 'x25519', + options: X25519KeyPairOptions<'der', 'der'> + ): Promise<{ + publicKey: Buffer; + privateKey: Buffer; + }>; + function __promisify__(type: 'x25519', options?: X25519KeyPairKeyObjectOptions): Promise; + function __promisify__( + type: 'x448', + options: X448KeyPairOptions<'pem', 'pem'> + ): Promise<{ + publicKey: string; + privateKey: string; + }>; + function __promisify__( + type: 'x448', + options: X448KeyPairOptions<'pem', 'der'> + ): Promise<{ + publicKey: string; + privateKey: Buffer; + }>; + function __promisify__( + type: 'x448', + options: X448KeyPairOptions<'der', 'pem'> + ): Promise<{ + publicKey: Buffer; + privateKey: string; + }>; + function __promisify__( + type: 'x448', + options: X448KeyPairOptions<'der', 'der'> + ): Promise<{ + publicKey: Buffer; + privateKey: Buffer; + }>; + function __promisify__(type: 'x448', options?: X448KeyPairKeyObjectOptions): Promise; + } + /** + * Calculates and returns the signature for `data` using the given private key and + * algorithm. If `algorithm` is `null` or `undefined`, then the algorithm is + * dependent upon the key type (especially Ed25519 and Ed448). + * + * If `key` is not a `KeyObject`, this function behaves as if `key` had been + * passed to {@link createPrivateKey}. If it is an object, the following + * additional properties can be passed: + * + * If the `callback` function is provided this function uses libuv's threadpool. + * @since v12.0.0 + */ + function sign(algorithm: string | null | undefined, data: NodeJS.ArrayBufferView, key: KeyLike | SignKeyObjectInput | SignPrivateKeyInput): Buffer; + function sign( + algorithm: string | null | undefined, + data: NodeJS.ArrayBufferView, + key: KeyLike | SignKeyObjectInput | SignPrivateKeyInput, + callback: (error: Error | null, data: Buffer) => void + ): void; + /** + * Verifies the given signature for `data` using the given key and algorithm. If`algorithm` is `null` or `undefined`, then the algorithm is dependent upon the + * key type (especially Ed25519 and Ed448). + * + * If `key` is not a `KeyObject`, this function behaves as if `key` had been + * passed to {@link createPublicKey}. If it is an object, the following + * additional properties can be passed: + * + * The `signature` argument is the previously calculated signature for the `data`. + * + * Because public keys can be derived from private keys, a private key or a public + * key may be passed for `key`. + * + * If the `callback` function is provided this function uses libuv's threadpool. + * @since v12.0.0 + */ + function verify(algorithm: string | null | undefined, data: NodeJS.ArrayBufferView, key: KeyLike | VerifyKeyObjectInput | VerifyPublicKeyInput, signature: NodeJS.ArrayBufferView): boolean; + function verify( + algorithm: string | null | undefined, + data: NodeJS.ArrayBufferView, + key: KeyLike | VerifyKeyObjectInput | VerifyPublicKeyInput, + signature: NodeJS.ArrayBufferView, + callback: (error: Error | null, result: boolean) => void + ): void; + /** + * Computes the Diffie-Hellman secret based on a `privateKey` and a `publicKey`. + * Both keys must have the same `asymmetricKeyType`, which must be one of `'dh'`(for Diffie-Hellman), `'ec'` (for ECDH), `'x448'`, or `'x25519'` (for ECDH-ES). + * @since v13.9.0, v12.17.0 + */ + function diffieHellman(options: { privateKey: KeyObject; publicKey: KeyObject }): Buffer; + type CipherMode = 'cbc' | 'ccm' | 'cfb' | 'ctr' | 'ecb' | 'gcm' | 'ocb' | 'ofb' | 'stream' | 'wrap' | 'xts'; + interface CipherInfoOptions { + /** + * A test key length. + */ + keyLength?: number | undefined; + /** + * A test IV length. + */ + ivLength?: number | undefined; + } + interface CipherInfo { + /** + * The name of the cipher. + */ + name: string; + /** + * The nid of the cipher. + */ + nid: number; + /** + * The block size of the cipher in bytes. + * This property is omitted when mode is 'stream'. + */ + blockSize?: number | undefined; + /** + * The expected or default initialization vector length in bytes. + * This property is omitted if the cipher does not use an initialization vector. + */ + ivLength?: number | undefined; + /** + * The expected or default key length in bytes. + */ + keyLength: number; + /** + * The cipher mode. + */ + mode: CipherMode; + } + /** + * Returns information about a given cipher. + * + * Some ciphers accept variable length keys and initialization vectors. By default, + * the `crypto.getCipherInfo()` method will return the default values for these + * ciphers. To test if a given key length or iv length is acceptable for given + * cipher, use the `keyLength` and `ivLength` options. If the given values are + * unacceptable, `undefined` will be returned. + * @since v15.0.0 + * @param nameOrNid The name or nid of the cipher to query. + */ + function getCipherInfo(nameOrNid: string | number, options?: CipherInfoOptions): CipherInfo | undefined; + /** + * HKDF is a simple key derivation function defined in RFC 5869\. The given `ikm`,`salt` and `info` are used with the `digest` to derive a key of `keylen` bytes. + * + * The supplied `callback` function is called with two arguments: `err` and`derivedKey`. If an errors occurs while deriving the key, `err` will be set; + * otherwise `err` will be `null`. The successfully generated `derivedKey` will + * be passed to the callback as an [ArrayBuffer](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer). An error will be thrown if any + * of the input arguments specify invalid values or types. + * + * ```js + * import { Buffer } from 'buffer'; + * const { + * hkdf + * } = await import('crypto'); + * + * hkdf('sha512', 'key', 'salt', 'info', 64, (err, derivedKey) => { + * if (err) throw err; + * console.log(Buffer.from(derivedKey).toString('hex')); // '24156e2...5391653' + * }); + * ``` + * @since v15.0.0 + * @param digest The digest algorithm to use. + * @param ikm The input keying material. It must be at least one byte in length. + * @param salt The salt value. Must be provided but can be zero-length. + * @param info Additional info value. Must be provided but can be zero-length, and cannot be more than 1024 bytes. + * @param keylen The length of the key to generate. Must be greater than 0. The maximum allowable value is `255` times the number of bytes produced by the selected digest function (e.g. `sha512` + * generates 64-byte hashes, making the maximum HKDF output 16320 bytes). + */ + function hkdf(digest: string, irm: BinaryLike | KeyObject, salt: BinaryLike, info: BinaryLike, keylen: number, callback: (err: Error | null, derivedKey: ArrayBuffer) => void): void; + /** + * Provides a synchronous HKDF key derivation function as defined in RFC 5869\. The + * given `ikm`, `salt` and `info` are used with the `digest` to derive a key of`keylen` bytes. + * + * The successfully generated `derivedKey` will be returned as an [ArrayBuffer](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer). + * + * An error will be thrown if any of the input arguments specify invalid values or + * types, or if the derived key cannot be generated. + * + * ```js + * import { Buffer } from 'buffer'; + * const { + * hkdfSync + * } = await import('crypto'); + * + * const derivedKey = hkdfSync('sha512', 'key', 'salt', 'info', 64); + * console.log(Buffer.from(derivedKey).toString('hex')); // '24156e2...5391653' + * ``` + * @since v15.0.0 + * @param digest The digest algorithm to use. + * @param ikm The input keying material. It must be at least one byte in length. + * @param salt The salt value. Must be provided but can be zero-length. + * @param info Additional info value. Must be provided but can be zero-length, and cannot be more than 1024 bytes. + * @param keylen The length of the key to generate. Must be greater than 0. The maximum allowable value is `255` times the number of bytes produced by the selected digest function (e.g. `sha512` + * generates 64-byte hashes, making the maximum HKDF output 16320 bytes). + */ + function hkdfSync(digest: string, ikm: BinaryLike | KeyObject, salt: BinaryLike, info: BinaryLike, keylen: number): ArrayBuffer; + interface SecureHeapUsage { + /** + * The total allocated secure heap size as specified using the `--secure-heap=n` command-line flag. + */ + total: number; + /** + * The minimum allocation from the secure heap as specified using the `--secure-heap-min` command-line flag. + */ + min: number; + /** + * The total number of bytes currently allocated from the secure heap. + */ + used: number; + /** + * The calculated ratio of `used` to `total` allocated bytes. + */ + utilization: number; + } + /** + * @since v15.6.0 + */ + function secureHeapUsed(): SecureHeapUsage; + interface RandomUUIDOptions { + /** + * By default, to improve performance, + * Node.js will pre-emptively generate and persistently cache enough + * random data to generate up to 128 random UUIDs. To generate a UUID + * without using the cache, set `disableEntropyCache` to `true`. + * + * @default `false` + */ + disableEntropyCache?: boolean | undefined; + } + /** + * Generates a random [RFC 4122](https://www.rfc-editor.org/rfc/rfc4122.txt) version 4 UUID. The UUID is generated using a + * cryptographic pseudorandom number generator. + * @since v15.6.0, v14.17.0 + */ + function randomUUID(options?: RandomUUIDOptions): string; + interface X509CheckOptions { + /** + * @default 'always' + */ + subject: 'always' | 'never'; + /** + * @default true + */ + wildcards: boolean; + /** + * @default true + */ + partialWildcards: boolean; + /** + * @default false + */ + multiLabelWildcards: boolean; + /** + * @default false + */ + singleLabelSubdomains: boolean; + } + /** + * Encapsulates an X509 certificate and provides read-only access to + * its information. + * + * ```js + * const { X509Certificate } = await import('crypto'); + * + * const x509 = new X509Certificate('{... pem encoded cert ...}'); + * + * console.log(x509.subject); + * ``` + * @since v15.6.0 + */ + class X509Certificate { + /** + * Will be \`true\` if this is a Certificate Authority (CA) certificate. + * @since v15.6.0 + */ + readonly ca: boolean; + /** + * The SHA-1 fingerprint of this certificate. + * + * Because SHA-1 is cryptographically broken and because the security of SHA-1 is + * significantly worse than that of algorithms that are commonly used to sign + * certificates, consider using `x509.fingerprint256` instead. + * @since v15.6.0 + */ + readonly fingerprint: string; + /** + * The SHA-256 fingerprint of this certificate. + * @since v15.6.0 + */ + readonly fingerprint256: string; + /** + * The SHA-512 fingerprint of this certificate. + * @since v16.14.0 + */ + readonly fingerprint512: string; + /** + * The complete subject of this certificate. + * @since v15.6.0 + */ + readonly subject: string; + /** + * The subject alternative name specified for this certificate or `undefined` + * if not available. + * @since v15.6.0 + */ + readonly subjectAltName: string | undefined; + /** + * The information access content of this certificate or `undefined` if not + * available. + * @since v15.6.0 + */ + readonly infoAccess: string | undefined; + /** + * An array detailing the key usages for this certificate. + * @since v15.6.0 + */ + readonly keyUsage: string[]; + /** + * The issuer identification included in this certificate. + * @since v15.6.0 + */ + readonly issuer: string; + /** + * The issuer certificate or `undefined` if the issuer certificate is not + * available. + * @since v15.9.0 + */ + readonly issuerCertificate?: X509Certificate | undefined; + /** + * The public key `KeyObject` for this certificate. + * @since v15.6.0 + */ + readonly publicKey: KeyObject; + /** + * A `Buffer` containing the DER encoding of this certificate. + * @since v15.6.0 + */ + readonly raw: Buffer; + /** + * The serial number of this certificate. + * + * Serial numbers are assigned by certificate authorities and do not uniquely + * identify certificates. Consider using `x509.fingerprint256` as a unique + * identifier instead. + * @since v15.6.0 + */ + readonly serialNumber: string; + /** + * The date/time from which this certificate is considered valid. + * @since v15.6.0 + */ + readonly validFrom: string; + /** + * The date/time until which this certificate is considered valid. + * @since v15.6.0 + */ + readonly validTo: string; + constructor(buffer: BinaryLike); + /** + * Checks whether the certificate matches the given email address. + * + * If the `'subject'` option is undefined or set to `'default'`, the certificate + * subject is only considered if the subject alternative name extension either does + * not exist or does not contain any email addresses. + * + * If the `'subject'` option is set to `'always'` and if the subject alternative + * name extension either does not exist or does not contain a matching email + * address, the certificate subject is considered. + * + * If the `'subject'` option is set to `'never'`, the certificate subject is never + * considered, even if the certificate contains no subject alternative names. + * @since v15.6.0 + * @return Returns `email` if the certificate matches, `undefined` if it does not. + */ + checkEmail(email: string, options?: Pick): string | undefined; + /** + * Checks whether the certificate matches the given host name. + * + * If the certificate matches the given host name, the matching subject name is + * returned. The returned name might be an exact match (e.g., `foo.example.com`) + * or it might contain wildcards (e.g., `*.example.com`). Because host name + * comparisons are case-insensitive, the returned subject name might also differ + * from the given `name` in capitalization. + * + * If the `'subject'` option is undefined or set to `'default'`, the certificate + * subject is only considered if the subject alternative name extension either does + * not exist or does not contain any DNS names. This behavior is consistent with [RFC 2818](https://www.rfc-editor.org/rfc/rfc2818.txt) ("HTTP Over TLS"). + * + * If the `'subject'` option is set to `'always'` and if the subject alternative + * name extension either does not exist or does not contain a matching DNS name, + * the certificate subject is considered. + * + * If the `'subject'` option is set to `'never'`, the certificate subject is never + * considered, even if the certificate contains no subject alternative names. + * @since v15.6.0 + * @return Returns a subject name that matches `name`, or `undefined` if no subject name matches `name`. + */ + checkHost(name: string, options?: X509CheckOptions): string | undefined; + /** + * Checks whether the certificate matches the given IP address (IPv4 or IPv6). + * + * Only [RFC 5280](https://www.rfc-editor.org/rfc/rfc5280.txt) `iPAddress` subject alternative names are considered, and they + * must match the given `ip` address exactly. Other subject alternative names as + * well as the subject field of the certificate are ignored. + * @since v15.6.0 + * @return Returns `ip` if the certificate matches, `undefined` if it does not. + */ + checkIP(ip: string): string | undefined; + /** + * Checks whether this certificate was issued by the given `otherCert`. + * @since v15.6.0 + */ + checkIssued(otherCert: X509Certificate): boolean; + /** + * Checks whether the public key for this certificate is consistent with + * the given private key. + * @since v15.6.0 + * @param privateKey A private key. + */ + checkPrivateKey(privateKey: KeyObject): boolean; + /** + * There is no standard JSON encoding for X509 certificates. The`toJSON()` method returns a string containing the PEM encoded + * certificate. + * @since v15.6.0 + */ + toJSON(): string; + /** + * Returns information about this certificate using the legacy `certificate object` encoding. + * @since v15.6.0 + */ + toLegacyObject(): PeerCertificate; + /** + * Returns the PEM-encoded certificate. + * @since v15.6.0 + */ + toString(): string; + /** + * Verifies that this certificate was signed by the given public key. + * Does not perform any other validation checks on the certificate. + * @since v15.6.0 + * @param publicKey A public key. + */ + verify(publicKey: KeyObject): boolean; + } + type LargeNumberLike = NodeJS.ArrayBufferView | SharedArrayBuffer | ArrayBuffer | bigint; + interface GeneratePrimeOptions { + add?: LargeNumberLike | undefined; + rem?: LargeNumberLike | undefined; + /** + * @default false + */ + safe?: boolean | undefined; + bigint?: boolean | undefined; + } + interface GeneratePrimeOptionsBigInt extends GeneratePrimeOptions { + bigint: true; + } + interface GeneratePrimeOptionsArrayBuffer extends GeneratePrimeOptions { + bigint?: false | undefined; + } + /** + * Generates a pseudorandom prime of `size` bits. + * + * If `options.safe` is `true`, the prime will be a safe prime -- that is,`(prime - 1) / 2` will also be a prime. + * + * The `options.add` and `options.rem` parameters can be used to enforce additional + * requirements, e.g., for Diffie-Hellman: + * + * * If `options.add` and `options.rem` are both set, the prime will satisfy the + * condition that `prime % add = rem`. + * * If only `options.add` is set and `options.safe` is not `true`, the prime will + * satisfy the condition that `prime % add = 1`. + * * If only `options.add` is set and `options.safe` is set to `true`, the prime + * will instead satisfy the condition that `prime % add = 3`. This is necessary + * because `prime % add = 1` for `options.add > 2` would contradict the condition + * enforced by `options.safe`. + * * `options.rem` is ignored if `options.add` is not given. + * + * Both `options.add` and `options.rem` must be encoded as big-endian sequences + * if given as an `ArrayBuffer`, `SharedArrayBuffer`, `TypedArray`, `Buffer`, or`DataView`. + * + * By default, the prime is encoded as a big-endian sequence of octets + * in an [ArrayBuffer](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer). If the `bigint` option is `true`, then a + * [bigint](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/BigInt) is provided. + * @since v15.8.0 + * @param size The size (in bits) of the prime to generate. + */ + function generatePrime(size: number, callback: (err: Error | null, prime: ArrayBuffer) => void): void; + function generatePrime(size: number, options: GeneratePrimeOptionsBigInt, callback: (err: Error | null, prime: bigint) => void): void; + function generatePrime(size: number, options: GeneratePrimeOptionsArrayBuffer, callback: (err: Error | null, prime: ArrayBuffer) => void): void; + function generatePrime(size: number, options: GeneratePrimeOptions, callback: (err: Error | null, prime: ArrayBuffer | bigint) => void): void; + /** + * Generates a pseudorandom prime of `size` bits. + * + * If `options.safe` is `true`, the prime will be a safe prime -- that is,`(prime - 1) / 2` will also be a prime. + * + * The `options.add` and `options.rem` parameters can be used to enforce additional + * requirements, e.g., for Diffie-Hellman: + * + * * If `options.add` and `options.rem` are both set, the prime will satisfy the + * condition that `prime % add = rem`. + * * If only `options.add` is set and `options.safe` is not `true`, the prime will + * satisfy the condition that `prime % add = 1`. + * * If only `options.add` is set and `options.safe` is set to `true`, the prime + * will instead satisfy the condition that `prime % add = 3`. This is necessary + * because `prime % add = 1` for `options.add > 2` would contradict the condition + * enforced by `options.safe`. + * * `options.rem` is ignored if `options.add` is not given. + * + * Both `options.add` and `options.rem` must be encoded as big-endian sequences + * if given as an `ArrayBuffer`, `SharedArrayBuffer`, `TypedArray`, `Buffer`, or`DataView`. + * + * By default, the prime is encoded as a big-endian sequence of octets + * in an [ArrayBuffer](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer). If the `bigint` option is `true`, then a + * [bigint](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/BigInt) is provided. + * @since v15.8.0 + * @param size The size (in bits) of the prime to generate. + */ + function generatePrimeSync(size: number): ArrayBuffer; + function generatePrimeSync(size: number, options: GeneratePrimeOptionsBigInt): bigint; + function generatePrimeSync(size: number, options: GeneratePrimeOptionsArrayBuffer): ArrayBuffer; + function generatePrimeSync(size: number, options: GeneratePrimeOptions): ArrayBuffer | bigint; + interface CheckPrimeOptions { + /** + * The number of Miller-Rabin probabilistic primality iterations to perform. + * When the value is 0 (zero), a number of checks is used that yields a false positive rate of at most 2-64 for random input. + * Care must be used when selecting a number of checks. + * Refer to the OpenSSL documentation for the BN_is_prime_ex function nchecks options for more details. + * + * @default 0 + */ + checks?: number | undefined; + } + /** + * Checks the primality of the `candidate`. + * @since v15.8.0 + * @param candidate A possible prime encoded as a sequence of big endian octets of arbitrary length. + */ + function checkPrime(value: LargeNumberLike, callback: (err: Error | null, result: boolean) => void): void; + function checkPrime(value: LargeNumberLike, options: CheckPrimeOptions, callback: (err: Error | null, result: boolean) => void): void; + /** + * Checks the primality of the `candidate`. + * @since v15.8.0 + * @param candidate A possible prime encoded as a sequence of big endian octets of arbitrary length. + * @return `true` if the candidate is a prime with an error probability less than `0.25 ** options.checks`. + */ + function checkPrimeSync(candidate: LargeNumberLike, options?: CheckPrimeOptions): boolean; + /** + * Load and set the `engine` for some or all OpenSSL functions (selected by flags). + * + * `engine` could be either an id or a path to the engine's shared library. + * + * The optional `flags` argument uses `ENGINE_METHOD_ALL` by default. + * The `flags` is a bit field taking one of or a mix of the following flags (defined in `crypto.constants`): + * + * - `crypto.constants.ENGINE_METHOD_RSA` + * - `crypto.constants.ENGINE_METHOD_DSA` + * - `crypto.constants.ENGINE_METHOD_DH` + * - `crypto.constants.ENGINE_METHOD_RAND` + * - `crypto.constants.ENGINE_METHOD_EC` + * - `crypto.constants.ENGINE_METHOD_CIPHERS` + * - `crypto.constants.ENGINE_METHOD_DIGESTS` + * - `crypto.constants.ENGINE_METHOD_PKEY_METHS` + * - `crypto.constants.ENGINE_METHOD_PKEY_ASN1_METHS` + * - `crypto.constants.ENGINE_METHOD_ALL` + * - `crypto.constants.ENGINE_METHOD_NONE` + * + * The flags below are deprecated in OpenSSL-1.1.0. + * + * - `crypto.constants.ENGINE_METHOD_ECDH` + * - `crypto.constants.ENGINE_METHOD_ECDSA` + * - `crypto.constants.ENGINE_METHOD_STORE` + * @since v0.11.11 + * @param [flags=crypto.constants.ENGINE_METHOD_ALL] + */ + function setEngine(engine: string, flags?: number): void; + /** + * A convenient alias for `crypto.webcrypto.getRandomValues()`. + * This implementation is not compliant with the Web Crypto spec, + * to write web-compatible code use `crypto.webcrypto.getRandomValues()` instead. + * @since v17.4.0 + * @returns Returns `typedArray`. + */ + function getRandomValues(typedArray: T): T; + /** + * A convenient alias for `crypto.webcrypto.subtle`. + * @since v17.4.0 + */ + const subtle: webcrypto.SubtleCrypto; + /** + * An implementation of the Web Crypto API standard. + * + * See the {@link https://nodejs.org/docs/latest/api/webcrypto.html Web Crypto API documentation} for details. + * @since v15.0.0 + */ + const webcrypto: webcrypto.Crypto; + namespace webcrypto { + type BufferSource = ArrayBufferView | ArrayBuffer; + type KeyFormat = 'jwk' | 'pkcs8' | 'raw' | 'spki'; + type KeyType = 'private' | 'public' | 'secret'; + type KeyUsage = 'decrypt' | 'deriveBits' | 'deriveKey' | 'encrypt' | 'sign' | 'unwrapKey' | 'verify' | 'wrapKey'; + type AlgorithmIdentifier = Algorithm | string; + type HashAlgorithmIdentifier = AlgorithmIdentifier; + type NamedCurve = string; + type BigInteger = Uint8Array; + interface AesCbcParams extends Algorithm { + iv: BufferSource; + } + interface AesCtrParams extends Algorithm { + counter: BufferSource; + length: number; + } + interface AesDerivedKeyParams extends Algorithm { + length: number; + } + interface AesGcmParams extends Algorithm { + additionalData?: BufferSource; + iv: BufferSource; + tagLength?: number; + } + interface AesKeyAlgorithm extends KeyAlgorithm { + length: number; + } + interface AesKeyGenParams extends Algorithm { + length: number; + } + interface Algorithm { + name: string; + } + interface EcKeyAlgorithm extends KeyAlgorithm { + namedCurve: NamedCurve; + } + interface EcKeyGenParams extends Algorithm { + namedCurve: NamedCurve; + } + interface EcKeyImportParams extends Algorithm { + namedCurve: NamedCurve; + } + interface EcdhKeyDeriveParams extends Algorithm { + public: CryptoKey; + } + interface EcdsaParams extends Algorithm { + hash: HashAlgorithmIdentifier; + } + interface Ed448Params extends Algorithm { + context?: BufferSource; + } + interface HkdfParams extends Algorithm { + hash: HashAlgorithmIdentifier; + info: BufferSource; + salt: BufferSource; + } + interface HmacImportParams extends Algorithm { + hash: HashAlgorithmIdentifier; + length?: number; + } + interface HmacKeyAlgorithm extends KeyAlgorithm { + hash: KeyAlgorithm; + length: number; + } + interface HmacKeyGenParams extends Algorithm { + hash: HashAlgorithmIdentifier; + length?: number; + } + interface JsonWebKey { + alg?: string; + crv?: string; + d?: string; + dp?: string; + dq?: string; + e?: string; + ext?: boolean; + k?: string; + key_ops?: string[]; + kty?: string; + n?: string; + oth?: RsaOtherPrimesInfo[]; + p?: string; + q?: string; + qi?: string; + use?: string; + x?: string; + y?: string; + } + interface KeyAlgorithm { + name: string; + } + interface Pbkdf2Params extends Algorithm { + hash: HashAlgorithmIdentifier; + iterations: number; + salt: BufferSource; + } + interface RsaHashedImportParams extends Algorithm { + hash: HashAlgorithmIdentifier; + } + interface RsaHashedKeyAlgorithm extends RsaKeyAlgorithm { + hash: KeyAlgorithm; + } + interface RsaHashedKeyGenParams extends RsaKeyGenParams { + hash: HashAlgorithmIdentifier; + } + interface RsaKeyAlgorithm extends KeyAlgorithm { + modulusLength: number; + publicExponent: BigInteger; + } + interface RsaKeyGenParams extends Algorithm { + modulusLength: number; + publicExponent: BigInteger; + } + interface RsaOaepParams extends Algorithm { + label?: BufferSource; + } + interface RsaOtherPrimesInfo { + d?: string; + r?: string; + t?: string; + } + interface RsaPssParams extends Algorithm { + saltLength: number; + } + /** + * Calling `require('node:crypto').webcrypto` returns an instance of the `Crypto` class. + * `Crypto` is a singleton that provides access to the remainder of the crypto API. + * @since v15.0.0 + */ + interface Crypto { + /** + * Provides access to the `SubtleCrypto` API. + * @since v15.0.0 + */ + readonly subtle: SubtleCrypto; + /** + * Generates cryptographically strong random values. + * The given `typedArray` is filled with random values, and a reference to `typedArray` is returned. + * + * The given `typedArray` must be an integer-based instance of {@link NodeJS.TypedArray}, i.e. `Float32Array` and `Float64Array` are not accepted. + * + * An error will be thrown if the given `typedArray` is larger than 65,536 bytes. + * @since v15.0.0 + */ + getRandomValues>(typedArray: T): T; + /** + * Generates a random {@link https://www.rfc-editor.org/rfc/rfc4122.txt RFC 4122} version 4 UUID. + * The UUID is generated using a cryptographic pseudorandom number generator. + * @since v16.7.0 + */ + randomUUID(): string; + CryptoKey: CryptoKeyConstructor; + } + // This constructor throws ILLEGAL_CONSTRUCTOR so it should not be newable. + interface CryptoKeyConstructor { + /** Illegal constructor */ + (_: { readonly _: unique symbol }): never; // Allows instanceof to work but not be callable by the user. + readonly length: 0; + readonly name: 'CryptoKey'; + readonly prototype: CryptoKey; + } + /** + * @since v15.0.0 + */ + interface CryptoKey { + /** + * An object detailing the algorithm for which the key can be used along with additional algorithm-specific parameters. + * @since v15.0.0 + */ + readonly algorithm: KeyAlgorithm; + /** + * When `true`, the {@link CryptoKey} can be extracted using either `subtleCrypto.exportKey()` or `subtleCrypto.wrapKey()`. + * @since v15.0.0 + */ + readonly extractable: boolean; + /** + * A string identifying whether the key is a symmetric (`'secret'`) or asymmetric (`'private'` or `'public'`) key. + * @since v15.0.0 + */ + readonly type: KeyType; + /** + * An array of strings identifying the operations for which the key may be used. + * + * The possible usages are: + * - `'encrypt'` - The key may be used to encrypt data. + * - `'decrypt'` - The key may be used to decrypt data. + * - `'sign'` - The key may be used to generate digital signatures. + * - `'verify'` - The key may be used to verify digital signatures. + * - `'deriveKey'` - The key may be used to derive a new key. + * - `'deriveBits'` - The key may be used to derive bits. + * - `'wrapKey'` - The key may be used to wrap another key. + * - `'unwrapKey'` - The key may be used to unwrap another key. + * + * Valid key usages depend on the key algorithm (identified by `cryptokey.algorithm.name`). + * @since v15.0.0 + */ + readonly usages: KeyUsage[]; + } + /** + * The `CryptoKeyPair` is a simple dictionary object with `publicKey` and `privateKey` properties, representing an asymmetric key pair. + * @since v15.0.0 + */ + interface CryptoKeyPair { + /** + * A {@link CryptoKey} whose type will be `'private'`. + * @since v15.0.0 + */ + privateKey: CryptoKey; + /** + * A {@link CryptoKey} whose type will be `'public'`. + * @since v15.0.0 + */ + publicKey: CryptoKey; + } + /** + * @since v15.0.0 + */ + interface SubtleCrypto { + /** + * Using the method and parameters specified in `algorithm` and the keying material provided by `key`, + * `subtle.decrypt()` attempts to decipher the provided `data`. If successful, + * the returned promise will be resolved with an `` containing the plaintext result. + * + * The algorithms currently supported include: + * + * - `'RSA-OAEP'` + * - `'AES-CTR'` + * - `'AES-CBC'` + * - `'AES-GCM'` + * @since v15.0.0 + */ + decrypt(algorithm: AlgorithmIdentifier | RsaOaepParams | AesCtrParams | AesCbcParams | AesGcmParams, key: CryptoKey, data: BufferSource): Promise; + /** + * Using the method and parameters specified in `algorithm` and the keying material provided by `baseKey`, + * `subtle.deriveBits()` attempts to generate `length` bits. + * The Node.js implementation requires that `length` is a multiple of `8`. + * If successful, the returned promise will be resolved with an `` containing the generated data. + * + * The algorithms currently supported include: + * + * - `'ECDH'` + * - `'X25519'` + * - `'X448'` + * - `'HKDF'` + * - `'PBKDF2'` + * @since v15.0.0 + */ + deriveBits(algorithm: AlgorithmIdentifier | EcdhKeyDeriveParams | HkdfParams | Pbkdf2Params, baseKey: CryptoKey, length: number): Promise; + /** + * Using the method and parameters specified in `algorithm`, and the keying material provided by `baseKey`, + * `subtle.deriveKey()` attempts to generate a new ` based on the method and parameters in `derivedKeyAlgorithm`. + * + * Calling `subtle.deriveKey()` is equivalent to calling `subtle.deriveBits()` to generate raw keying material, + * then passing the result into the `subtle.importKey()` method using the `deriveKeyAlgorithm`, `extractable`, and `keyUsages` parameters as input. + * + * The algorithms currently supported include: + * + * - `'ECDH'` + * - `'X25519'` + * - `'X448'` + * - `'HKDF'` + * - `'PBKDF2'` + * @param keyUsages See {@link https://nodejs.org/docs/latest/api/webcrypto.html#cryptokeyusages Key usages}. + * @since v15.0.0 + */ + deriveKey( + algorithm: AlgorithmIdentifier | EcdhKeyDeriveParams | HkdfParams | Pbkdf2Params, + baseKey: CryptoKey, + derivedKeyAlgorithm: AlgorithmIdentifier | AesDerivedKeyParams | HmacImportParams | HkdfParams | Pbkdf2Params, + extractable: boolean, + keyUsages: ReadonlyArray + ): Promise; + /** + * Using the method identified by `algorithm`, `subtle.digest()` attempts to generate a digest of `data`. + * If successful, the returned promise is resolved with an `` containing the computed digest. + * + * If `algorithm` is provided as a ``, it must be one of: + * + * - `'SHA-1'` + * - `'SHA-256'` + * - `'SHA-384'` + * - `'SHA-512'` + * + * If `algorithm` is provided as an ``, it must have a `name` property whose value is one of the above. + * @since v15.0.0 + */ + digest(algorithm: AlgorithmIdentifier, data: BufferSource): Promise; + /** + * Using the method and parameters specified by `algorithm` and the keying material provided by `key`, + * `subtle.encrypt()` attempts to encipher `data`. If successful, + * the returned promise is resolved with an `` containing the encrypted result. + * + * The algorithms currently supported include: + * + * - `'RSA-OAEP'` + * - `'AES-CTR'` + * - `'AES-CBC'` + * - `'AES-GCM'` + * @since v15.0.0 + */ + encrypt(algorithm: AlgorithmIdentifier | RsaOaepParams | AesCtrParams | AesCbcParams | AesGcmParams, key: CryptoKey, data: BufferSource): Promise; + /** + * Exports the given key into the specified format, if supported. + * + * If the `` is not extractable, the returned promise will reject. + * + * When `format` is either `'pkcs8'` or `'spki'` and the export is successful, + * the returned promise will be resolved with an `` containing the exported key data. + * + * When `format` is `'jwk'` and the export is successful, the returned promise will be resolved with a + * JavaScript object conforming to the {@link https://tools.ietf.org/html/rfc7517 JSON Web Key} specification. + * @param format Must be one of `'raw'`, `'pkcs8'`, `'spki'`, or `'jwk'`. + * @returns `` containing ``. + * @since v15.0.0 + */ + exportKey(format: 'jwk', key: CryptoKey): Promise; + exportKey(format: Exclude, key: CryptoKey): Promise; + /** + * Using the method and parameters provided in `algorithm`, + * `subtle.generateKey()` attempts to generate new keying material. + * Depending the method used, the method may generate either a single `` or a ``. + * + * The `` (public and private key) generating algorithms supported include: + * + * - `'RSASSA-PKCS1-v1_5'` + * - `'RSA-PSS'` + * - `'RSA-OAEP'` + * - `'ECDSA'` + * - `'Ed25519'` + * - `'Ed448'` + * - `'ECDH'` + * - `'X25519'` + * - `'X448'` + * The `` (secret key) generating algorithms supported include: + * + * - `'HMAC'` + * - `'AES-CTR'` + * - `'AES-CBC'` + * - `'AES-GCM'` + * - `'AES-KW'` + * @param keyUsages See {@link https://nodejs.org/docs/latest/api/webcrypto.html#cryptokeyusages Key usages}. + * @since v15.0.0 + */ + generateKey(algorithm: RsaHashedKeyGenParams | EcKeyGenParams, extractable: boolean, keyUsages: ReadonlyArray): Promise; + generateKey(algorithm: AesKeyGenParams | HmacKeyGenParams | Pbkdf2Params, extractable: boolean, keyUsages: ReadonlyArray): Promise; + generateKey(algorithm: AlgorithmIdentifier, extractable: boolean, keyUsages: KeyUsage[]): Promise; + /** + * The `subtle.importKey()` method attempts to interpret the provided `keyData` as the given `format` + * to create a `` instance using the provided `algorithm`, `extractable`, and `keyUsages` arguments. + * If the import is successful, the returned promise will be resolved with the created ``. + * + * If importing a `'PBKDF2'` key, `extractable` must be `false`. + * @param format Must be one of `'raw'`, `'pkcs8'`, `'spki'`, or `'jwk'`. + * @param keyUsages See {@link https://nodejs.org/docs/latest/api/webcrypto.html#cryptokeyusages Key usages}. + * @since v15.0.0 + */ + importKey( + format: 'jwk', + keyData: JsonWebKey, + algorithm: AlgorithmIdentifier | RsaHashedImportParams | EcKeyImportParams | HmacImportParams | AesKeyAlgorithm, + extractable: boolean, + keyUsages: ReadonlyArray + ): Promise; + importKey( + format: Exclude, + keyData: BufferSource, + algorithm: AlgorithmIdentifier | RsaHashedImportParams | EcKeyImportParams | HmacImportParams | AesKeyAlgorithm, + extractable: boolean, + keyUsages: KeyUsage[] + ): Promise; + /** + * Using the method and parameters given by `algorithm` and the keying material provided by `key`, + * `subtle.sign()` attempts to generate a cryptographic signature of `data`. If successful, + * the returned promise is resolved with an `` containing the generated signature. + * + * The algorithms currently supported include: + * + * - `'RSASSA-PKCS1-v1_5'` + * - `'RSA-PSS'` + * - `'ECDSA'` + * - `'Ed25519'` + * - `'Ed448'` + * - `'HMAC'` + * @since v15.0.0 + */ + sign(algorithm: AlgorithmIdentifier | RsaPssParams | EcdsaParams | Ed448Params, key: CryptoKey, data: BufferSource): Promise; + /** + * In cryptography, "wrapping a key" refers to exporting and then encrypting the keying material. + * The `subtle.unwrapKey()` method attempts to decrypt a wrapped key and create a `` instance. + * It is equivalent to calling `subtle.decrypt()` first on the encrypted key data (using the `wrappedKey`, `unwrapAlgo`, and `unwrappingKey` arguments as input) + * then passing the results in to the `subtle.importKey()` method using the `unwrappedKeyAlgo`, `extractable`, and `keyUsages` arguments as inputs. + * If successful, the returned promise is resolved with a `` object. + * + * The wrapping algorithms currently supported include: + * + * - `'RSA-OAEP'` + * - `'AES-CTR'` + * - `'AES-CBC'` + * - `'AES-GCM'` + * - `'AES-KW'` + * + * The unwrapped key algorithms supported include: + * + * - `'RSASSA-PKCS1-v1_5'` + * - `'RSA-PSS'` + * - `'RSA-OAEP'` + * - `'ECDSA'` + * - `'Ed25519'` + * - `'Ed448'` + * - `'ECDH'` + * - `'X25519'` + * - `'X448'` + * - `'HMAC'` + * - `'AES-CTR'` + * - `'AES-CBC'` + * - `'AES-GCM'` + * - `'AES-KW'` + * @param format Must be one of `'raw'`, `'pkcs8'`, `'spki'`, or `'jwk'`. + * @param keyUsages See {@link https://nodejs.org/docs/latest/api/webcrypto.html#cryptokeyusages Key usages}. + * @since v15.0.0 + */ + unwrapKey( + format: KeyFormat, + wrappedKey: BufferSource, + unwrappingKey: CryptoKey, + unwrapAlgorithm: AlgorithmIdentifier | RsaOaepParams | AesCtrParams | AesCbcParams | AesGcmParams, + unwrappedKeyAlgorithm: AlgorithmIdentifier | RsaHashedImportParams | EcKeyImportParams | HmacImportParams | AesKeyAlgorithm, + extractable: boolean, + keyUsages: KeyUsage[] + ): Promise; + /** + * Using the method and parameters given in `algorithm` and the keying material provided by `key`, + * `subtle.verify()` attempts to verify that `signature` is a valid cryptographic signature of `data`. + * The returned promise is resolved with either `true` or `false`. + * + * The algorithms currently supported include: + * + * - `'RSASSA-PKCS1-v1_5'` + * - `'RSA-PSS'` + * - `'ECDSA'` + * - `'Ed25519'` + * - `'Ed448'` + * - `'HMAC'` + * @since v15.0.0 + */ + verify(algorithm: AlgorithmIdentifier | RsaPssParams | EcdsaParams | Ed448Params, key: CryptoKey, signature: BufferSource, data: BufferSource): Promise; + /** + * In cryptography, "wrapping a key" refers to exporting and then encrypting the keying material. + * The `subtle.wrapKey()` method exports the keying material into the format identified by `format`, + * then encrypts it using the method and parameters specified by `wrapAlgo` and the keying material provided by `wrappingKey`. + * It is the equivalent to calling `subtle.exportKey()` using `format` and `key` as the arguments, + * then passing the result to the `subtle.encrypt()` method using `wrappingKey` and `wrapAlgo` as inputs. + * If successful, the returned promise will be resolved with an `` containing the encrypted key data. + * + * The wrapping algorithms currently supported include: + * + * - `'RSA-OAEP'` + * - `'AES-CTR'` + * - `'AES-CBC'` + * - `'AES-GCM'` + * - `'AES-KW'` + * @param format Must be one of `'raw'`, `'pkcs8'`, `'spki'`, or `'jwk'`. + * @since v15.0.0 + */ + wrapKey(format: KeyFormat, key: CryptoKey, wrappingKey: CryptoKey, wrapAlgorithm: AlgorithmIdentifier | RsaOaepParams | AesCtrParams | AesCbcParams | AesGcmParams): Promise; + } + } +} +declare module 'node:crypto' { + export * from 'crypto'; +} diff --git a/ts-ticket-office-service/node_modules/@types/node/dgram.d.ts b/ts-ticket-office-service/node_modules/@types/node/dgram.d.ts new file mode 100755 index 000000000..247328d28 --- /dev/null +++ b/ts-ticket-office-service/node_modules/@types/node/dgram.d.ts @@ -0,0 +1,545 @@ +/** + * The `dgram` module provides an implementation of UDP datagram sockets. + * + * ```js + * import dgram from 'dgram'; + * + * const server = dgram.createSocket('udp4'); + * + * server.on('error', (err) => { + * console.log(`server error:\n${err.stack}`); + * server.close(); + * }); + * + * server.on('message', (msg, rinfo) => { + * console.log(`server got: ${msg} from ${rinfo.address}:${rinfo.port}`); + * }); + * + * server.on('listening', () => { + * const address = server.address(); + * console.log(`server listening ${address.address}:${address.port}`); + * }); + * + * server.bind(41234); + * // Prints: server listening 0.0.0.0:41234 + * ``` + * @see [source](https://github.com/nodejs/node/blob/v18.0.0/lib/dgram.js) + */ +declare module 'dgram' { + import { AddressInfo } from 'node:net'; + import * as dns from 'node:dns'; + import { EventEmitter, Abortable } from 'node:events'; + interface RemoteInfo { + address: string; + family: 'IPv4' | 'IPv6'; + port: number; + size: number; + } + interface BindOptions { + port?: number | undefined; + address?: string | undefined; + exclusive?: boolean | undefined; + fd?: number | undefined; + } + type SocketType = 'udp4' | 'udp6'; + interface SocketOptions extends Abortable { + type: SocketType; + reuseAddr?: boolean | undefined; + /** + * @default false + */ + ipv6Only?: boolean | undefined; + recvBufferSize?: number | undefined; + sendBufferSize?: number | undefined; + lookup?: ((hostname: string, options: dns.LookupOneOptions, callback: (err: NodeJS.ErrnoException | null, address: string, family: number) => void) => void) | undefined; + } + /** + * Creates a `dgram.Socket` object. Once the socket is created, calling `socket.bind()` will instruct the socket to begin listening for datagram + * messages. When `address` and `port` are not passed to `socket.bind()` the + * method will bind the socket to the "all interfaces" address on a random port + * (it does the right thing for both `udp4` and `udp6` sockets). The bound address + * and port can be retrieved using `socket.address().address` and `socket.address().port`. + * + * If the `signal` option is enabled, calling `.abort()` on the corresponding`AbortController` is similar to calling `.close()` on the socket: + * + * ```js + * const controller = new AbortController(); + * const { signal } = controller; + * const server = dgram.createSocket({ type: 'udp4', signal }); + * server.on('message', (msg, rinfo) => { + * console.log(`server got: ${msg} from ${rinfo.address}:${rinfo.port}`); + * }); + * // Later, when you want to close the server. + * controller.abort(); + * ``` + * @since v0.11.13 + * @param options Available options are: + * @param callback Attached as a listener for `'message'` events. Optional. + */ + function createSocket(type: SocketType, callback?: (msg: Buffer, rinfo: RemoteInfo) => void): Socket; + function createSocket(options: SocketOptions, callback?: (msg: Buffer, rinfo: RemoteInfo) => void): Socket; + /** + * Encapsulates the datagram functionality. + * + * New instances of `dgram.Socket` are created using {@link createSocket}. + * The `new` keyword is not to be used to create `dgram.Socket` instances. + * @since v0.1.99 + */ + class Socket extends EventEmitter { + /** + * Tells the kernel to join a multicast group at the given `multicastAddress` and`multicastInterface` using the `IP_ADD_MEMBERSHIP` socket option. If the`multicastInterface` argument is not + * specified, the operating system will choose + * one interface and will add membership to it. To add membership to every + * available interface, call `addMembership` multiple times, once per interface. + * + * When called on an unbound socket, this method will implicitly bind to a random + * port, listening on all interfaces. + * + * When sharing a UDP socket across multiple `cluster` workers, the`socket.addMembership()` function must be called only once or an`EADDRINUSE` error will occur: + * + * ```js + * import cluster from 'cluster'; + * import dgram from 'dgram'; + * + * if (cluster.isPrimary) { + * cluster.fork(); // Works ok. + * cluster.fork(); // Fails with EADDRINUSE. + * } else { + * const s = dgram.createSocket('udp4'); + * s.bind(1234, () => { + * s.addMembership('224.0.0.114'); + * }); + * } + * ``` + * @since v0.6.9 + */ + addMembership(multicastAddress: string, multicastInterface?: string): void; + /** + * Returns an object containing the address information for a socket. + * For UDP sockets, this object will contain `address`, `family` and `port`properties. + * + * This method throws `EBADF` if called on an unbound socket. + * @since v0.1.99 + */ + address(): AddressInfo; + /** + * For UDP sockets, causes the `dgram.Socket` to listen for datagram + * messages on a named `port` and optional `address`. If `port` is not + * specified or is `0`, the operating system will attempt to bind to a + * random port. If `address` is not specified, the operating system will + * attempt to listen on all addresses. Once binding is complete, a`'listening'` event is emitted and the optional `callback` function is + * called. + * + * Specifying both a `'listening'` event listener and passing a`callback` to the `socket.bind()` method is not harmful but not very + * useful. + * + * A bound datagram socket keeps the Node.js process running to receive + * datagram messages. + * + * If binding fails, an `'error'` event is generated. In rare case (e.g. + * attempting to bind with a closed socket), an `Error` may be thrown. + * + * Example of a UDP server listening on port 41234: + * + * ```js + * import dgram from 'dgram'; + * + * const server = dgram.createSocket('udp4'); + * + * server.on('error', (err) => { + * console.log(`server error:\n${err.stack}`); + * server.close(); + * }); + * + * server.on('message', (msg, rinfo) => { + * console.log(`server got: ${msg} from ${rinfo.address}:${rinfo.port}`); + * }); + * + * server.on('listening', () => { + * const address = server.address(); + * console.log(`server listening ${address.address}:${address.port}`); + * }); + * + * server.bind(41234); + * // Prints: server listening 0.0.0.0:41234 + * ``` + * @since v0.1.99 + * @param callback with no parameters. Called when binding is complete. + */ + bind(port?: number, address?: string, callback?: () => void): this; + bind(port?: number, callback?: () => void): this; + bind(callback?: () => void): this; + bind(options: BindOptions, callback?: () => void): this; + /** + * Close the underlying socket and stop listening for data on it. If a callback is + * provided, it is added as a listener for the `'close'` event. + * @since v0.1.99 + * @param callback Called when the socket has been closed. + */ + close(callback?: () => void): this; + /** + * Associates the `dgram.Socket` to a remote address and port. Every + * message sent by this handle is automatically sent to that destination. Also, + * the socket will only receive messages from that remote peer. + * Trying to call `connect()` on an already connected socket will result + * in an `ERR_SOCKET_DGRAM_IS_CONNECTED` exception. If `address` is not + * provided, `'127.0.0.1'` (for `udp4` sockets) or `'::1'` (for `udp6` sockets) + * will be used by default. Once the connection is complete, a `'connect'` event + * is emitted and the optional `callback` function is called. In case of failure, + * the `callback` is called or, failing this, an `'error'` event is emitted. + * @since v12.0.0 + * @param callback Called when the connection is completed or on error. + */ + connect(port: number, address?: string, callback?: () => void): void; + connect(port: number, callback: () => void): void; + /** + * A synchronous function that disassociates a connected `dgram.Socket` from + * its remote address. Trying to call `disconnect()` on an unbound or already + * disconnected socket will result in an `ERR_SOCKET_DGRAM_NOT_CONNECTED` exception. + * @since v12.0.0 + */ + disconnect(): void; + /** + * Instructs the kernel to leave a multicast group at `multicastAddress` using the`IP_DROP_MEMBERSHIP` socket option. This method is automatically called by the + * kernel when the socket is closed or the process terminates, so most apps will + * never have reason to call this. + * + * If `multicastInterface` is not specified, the operating system will attempt to + * drop membership on all valid interfaces. + * @since v0.6.9 + */ + dropMembership(multicastAddress: string, multicastInterface?: string): void; + /** + * This method throws `ERR_SOCKET_BUFFER_SIZE` if called on an unbound socket. + * @since v8.7.0 + * @return the `SO_RCVBUF` socket receive buffer size in bytes. + */ + getRecvBufferSize(): number; + /** + * This method throws `ERR_SOCKET_BUFFER_SIZE` if called on an unbound socket. + * @since v8.7.0 + * @return the `SO_SNDBUF` socket send buffer size in bytes. + */ + getSendBufferSize(): number; + /** + * By default, binding a socket will cause it to block the Node.js process from + * exiting as long as the socket is open. The `socket.unref()` method can be used + * to exclude the socket from the reference counting that keeps the Node.js + * process active. The `socket.ref()` method adds the socket back to the reference + * counting and restores the default behavior. + * + * Calling `socket.ref()` multiples times will have no additional effect. + * + * The `socket.ref()` method returns a reference to the socket so calls can be + * chained. + * @since v0.9.1 + */ + ref(): this; + /** + * Returns an object containing the `address`, `family`, and `port` of the remote + * endpoint. This method throws an `ERR_SOCKET_DGRAM_NOT_CONNECTED` exception + * if the socket is not connected. + * @since v12.0.0 + */ + remoteAddress(): AddressInfo; + /** + * Broadcasts a datagram on the socket. + * For connectionless sockets, the destination `port` and `address` must be + * specified. Connected sockets, on the other hand, will use their associated + * remote endpoint, so the `port` and `address` arguments must not be set. + * + * The `msg` argument contains the message to be sent. + * Depending on its type, different behavior can apply. If `msg` is a `Buffer`, + * any `TypedArray` or a `DataView`, + * the `offset` and `length` specify the offset within the `Buffer` where the + * message begins and the number of bytes in the message, respectively. + * If `msg` is a `String`, then it is automatically converted to a `Buffer`with `'utf8'` encoding. With messages that + * contain multi-byte characters, `offset` and `length` will be calculated with + * respect to `byte length` and not the character position. + * If `msg` is an array, `offset` and `length` must not be specified. + * + * The `address` argument is a string. If the value of `address` is a host name, + * DNS will be used to resolve the address of the host. If `address` is not + * provided or otherwise nullish, `'127.0.0.1'` (for `udp4` sockets) or `'::1'`(for `udp6` sockets) will be used by default. + * + * If the socket has not been previously bound with a call to `bind`, the socket + * is assigned a random port number and is bound to the "all interfaces" address + * (`'0.0.0.0'` for `udp4` sockets, `'::0'` for `udp6` sockets.) + * + * An optional `callback` function may be specified to as a way of reporting + * DNS errors or for determining when it is safe to reuse the `buf` object. + * DNS lookups delay the time to send for at least one tick of the + * Node.js event loop. + * + * The only way to know for sure that the datagram has been sent is by using a`callback`. If an error occurs and a `callback` is given, the error will be + * passed as the first argument to the `callback`. If a `callback` is not given, + * the error is emitted as an `'error'` event on the `socket` object. + * + * Offset and length are optional but both _must_ be set if either are used. + * They are supported only when the first argument is a `Buffer`, a `TypedArray`, + * or a `DataView`. + * + * This method throws `ERR_SOCKET_BAD_PORT` if called on an unbound socket. + * + * Example of sending a UDP packet to a port on `localhost`; + * + * ```js + * import dgram from 'dgram'; + * import { Buffer } from 'buffer'; + * + * const message = Buffer.from('Some bytes'); + * const client = dgram.createSocket('udp4'); + * client.send(message, 41234, 'localhost', (err) => { + * client.close(); + * }); + * ``` + * + * Example of sending a UDP packet composed of multiple buffers to a port on`127.0.0.1`; + * + * ```js + * import dgram from 'dgram'; + * import { Buffer } from 'buffer'; + * + * const buf1 = Buffer.from('Some '); + * const buf2 = Buffer.from('bytes'); + * const client = dgram.createSocket('udp4'); + * client.send([buf1, buf2], 41234, (err) => { + * client.close(); + * }); + * ``` + * + * Sending multiple buffers might be faster or slower depending on the + * application and operating system. Run benchmarks to + * determine the optimal strategy on a case-by-case basis. Generally speaking, + * however, sending multiple buffers is faster. + * + * Example of sending a UDP packet using a socket connected to a port on`localhost`: + * + * ```js + * import dgram from 'dgram'; + * import { Buffer } from 'buffer'; + * + * const message = Buffer.from('Some bytes'); + * const client = dgram.createSocket('udp4'); + * client.connect(41234, 'localhost', (err) => { + * client.send(message, (err) => { + * client.close(); + * }); + * }); + * ``` + * @since v0.1.99 + * @param msg Message to be sent. + * @param offset Offset in the buffer where the message starts. + * @param length Number of bytes in the message. + * @param port Destination port. + * @param address Destination host name or IP address. + * @param callback Called when the message has been sent. + */ + send(msg: string | Uint8Array | ReadonlyArray, port?: number, address?: string, callback?: (error: Error | null, bytes: number) => void): void; + send(msg: string | Uint8Array | ReadonlyArray, port?: number, callback?: (error: Error | null, bytes: number) => void): void; + send(msg: string | Uint8Array | ReadonlyArray, callback?: (error: Error | null, bytes: number) => void): void; + send(msg: string | Uint8Array, offset: number, length: number, port?: number, address?: string, callback?: (error: Error | null, bytes: number) => void): void; + send(msg: string | Uint8Array, offset: number, length: number, port?: number, callback?: (error: Error | null, bytes: number) => void): void; + send(msg: string | Uint8Array, offset: number, length: number, callback?: (error: Error | null, bytes: number) => void): void; + /** + * Sets or clears the `SO_BROADCAST` socket option. When set to `true`, UDP + * packets may be sent to a local interface's broadcast address. + * + * This method throws `EBADF` if called on an unbound socket. + * @since v0.6.9 + */ + setBroadcast(flag: boolean): void; + /** + * _All references to scope in this section are referring to [IPv6 Zone Indices](https://en.wikipedia.org/wiki/IPv6_address#Scoped_literal_IPv6_addresses), which are defined by [RFC + * 4007](https://tools.ietf.org/html/rfc4007). In string form, an IP_ + * _with a scope index is written as `'IP%scope'` where scope is an interface name_ + * _or interface number._ + * + * Sets the default outgoing multicast interface of the socket to a chosen + * interface or back to system interface selection. The `multicastInterface` must + * be a valid string representation of an IP from the socket's family. + * + * For IPv4 sockets, this should be the IP configured for the desired physical + * interface. All packets sent to multicast on the socket will be sent on the + * interface determined by the most recent successful use of this call. + * + * For IPv6 sockets, `multicastInterface` should include a scope to indicate the + * interface as in the examples that follow. In IPv6, individual `send` calls can + * also use explicit scope in addresses, so only packets sent to a multicast + * address without specifying an explicit scope are affected by the most recent + * successful use of this call. + * + * This method throws `EBADF` if called on an unbound socket. + * + * #### Example: IPv6 outgoing multicast interface + * + * On most systems, where scope format uses the interface name: + * + * ```js + * const socket = dgram.createSocket('udp6'); + * + * socket.bind(1234, () => { + * socket.setMulticastInterface('::%eth1'); + * }); + * ``` + * + * On Windows, where scope format uses an interface number: + * + * ```js + * const socket = dgram.createSocket('udp6'); + * + * socket.bind(1234, () => { + * socket.setMulticastInterface('::%2'); + * }); + * ``` + * + * #### Example: IPv4 outgoing multicast interface + * + * All systems use an IP of the host on the desired physical interface: + * + * ```js + * const socket = dgram.createSocket('udp4'); + * + * socket.bind(1234, () => { + * socket.setMulticastInterface('10.0.0.2'); + * }); + * ``` + * @since v8.6.0 + */ + setMulticastInterface(multicastInterface: string): void; + /** + * Sets or clears the `IP_MULTICAST_LOOP` socket option. When set to `true`, + * multicast packets will also be received on the local interface. + * + * This method throws `EBADF` if called on an unbound socket. + * @since v0.3.8 + */ + setMulticastLoopback(flag: boolean): boolean; + /** + * Sets the `IP_MULTICAST_TTL` socket option. While TTL generally stands for + * "Time to Live", in this context it specifies the number of IP hops that a + * packet is allowed to travel through, specifically for multicast traffic. Each + * router or gateway that forwards a packet decrements the TTL. If the TTL is + * decremented to 0 by a router, it will not be forwarded. + * + * The `ttl` argument may be between 0 and 255\. The default on most systems is `1`. + * + * This method throws `EBADF` if called on an unbound socket. + * @since v0.3.8 + */ + setMulticastTTL(ttl: number): number; + /** + * Sets the `SO_RCVBUF` socket option. Sets the maximum socket receive buffer + * in bytes. + * + * This method throws `ERR_SOCKET_BUFFER_SIZE` if called on an unbound socket. + * @since v8.7.0 + */ + setRecvBufferSize(size: number): void; + /** + * Sets the `SO_SNDBUF` socket option. Sets the maximum socket send buffer + * in bytes. + * + * This method throws `ERR_SOCKET_BUFFER_SIZE` if called on an unbound socket. + * @since v8.7.0 + */ + setSendBufferSize(size: number): void; + /** + * Sets the `IP_TTL` socket option. While TTL generally stands for "Time to Live", + * in this context it specifies the number of IP hops that a packet is allowed to + * travel through. Each router or gateway that forwards a packet decrements the + * TTL. If the TTL is decremented to 0 by a router, it will not be forwarded. + * Changing TTL values is typically done for network probes or when multicasting. + * + * The `ttl` argument may be between 1 and 255\. The default on most systems + * is 64. + * + * This method throws `EBADF` if called on an unbound socket. + * @since v0.1.101 + */ + setTTL(ttl: number): number; + /** + * By default, binding a socket will cause it to block the Node.js process from + * exiting as long as the socket is open. The `socket.unref()` method can be used + * to exclude the socket from the reference counting that keeps the Node.js + * process active, allowing the process to exit even if the socket is still + * listening. + * + * Calling `socket.unref()` multiple times will have no addition effect. + * + * The `socket.unref()` method returns a reference to the socket so calls can be + * chained. + * @since v0.9.1 + */ + unref(): this; + /** + * Tells the kernel to join a source-specific multicast channel at the given`sourceAddress` and `groupAddress`, using the `multicastInterface` with the`IP_ADD_SOURCE_MEMBERSHIP` socket + * option. If the `multicastInterface` argument + * is not specified, the operating system will choose one interface and will add + * membership to it. To add membership to every available interface, call`socket.addSourceSpecificMembership()` multiple times, once per interface. + * + * When called on an unbound socket, this method will implicitly bind to a random + * port, listening on all interfaces. + * @since v13.1.0, v12.16.0 + */ + addSourceSpecificMembership(sourceAddress: string, groupAddress: string, multicastInterface?: string): void; + /** + * Instructs the kernel to leave a source-specific multicast channel at the given`sourceAddress` and `groupAddress` using the `IP_DROP_SOURCE_MEMBERSHIP`socket option. This method is + * automatically called by the kernel when the + * socket is closed or the process terminates, so most apps will never have + * reason to call this. + * + * If `multicastInterface` is not specified, the operating system will attempt to + * drop membership on all valid interfaces. + * @since v13.1.0, v12.16.0 + */ + dropSourceSpecificMembership(sourceAddress: string, groupAddress: string, multicastInterface?: string): void; + /** + * events.EventEmitter + * 1. close + * 2. connect + * 3. error + * 4. listening + * 5. message + */ + addListener(event: string, listener: (...args: any[]) => void): this; + addListener(event: 'close', listener: () => void): this; + addListener(event: 'connect', listener: () => void): this; + addListener(event: 'error', listener: (err: Error) => void): this; + addListener(event: 'listening', listener: () => void): this; + addListener(event: 'message', listener: (msg: Buffer, rinfo: RemoteInfo) => void): this; + emit(event: string | symbol, ...args: any[]): boolean; + emit(event: 'close'): boolean; + emit(event: 'connect'): boolean; + emit(event: 'error', err: Error): boolean; + emit(event: 'listening'): boolean; + emit(event: 'message', msg: Buffer, rinfo: RemoteInfo): boolean; + on(event: string, listener: (...args: any[]) => void): this; + on(event: 'close', listener: () => void): this; + on(event: 'connect', listener: () => void): this; + on(event: 'error', listener: (err: Error) => void): this; + on(event: 'listening', listener: () => void): this; + on(event: 'message', listener: (msg: Buffer, rinfo: RemoteInfo) => void): this; + once(event: string, listener: (...args: any[]) => void): this; + once(event: 'close', listener: () => void): this; + once(event: 'connect', listener: () => void): this; + once(event: 'error', listener: (err: Error) => void): this; + once(event: 'listening', listener: () => void): this; + once(event: 'message', listener: (msg: Buffer, rinfo: RemoteInfo) => void): this; + prependListener(event: string, listener: (...args: any[]) => void): this; + prependListener(event: 'close', listener: () => void): this; + prependListener(event: 'connect', listener: () => void): this; + prependListener(event: 'error', listener: (err: Error) => void): this; + prependListener(event: 'listening', listener: () => void): this; + prependListener(event: 'message', listener: (msg: Buffer, rinfo: RemoteInfo) => void): this; + prependOnceListener(event: string, listener: (...args: any[]) => void): this; + prependOnceListener(event: 'close', listener: () => void): this; + prependOnceListener(event: 'connect', listener: () => void): this; + prependOnceListener(event: 'error', listener: (err: Error) => void): this; + prependOnceListener(event: 'listening', listener: () => void): this; + prependOnceListener(event: 'message', listener: (msg: Buffer, rinfo: RemoteInfo) => void): this; + } +} +declare module 'node:dgram' { + export * from 'dgram'; +} diff --git a/ts-ticket-office-service/node_modules/@types/node/diagnostics_channel.d.ts b/ts-ticket-office-service/node_modules/@types/node/diagnostics_channel.d.ts new file mode 100755 index 000000000..a87ba8ca9 --- /dev/null +++ b/ts-ticket-office-service/node_modules/@types/node/diagnostics_channel.d.ts @@ -0,0 +1,153 @@ +/** + * The `diagnostics_channel` module provides an API to create named channels + * to report arbitrary message data for diagnostics purposes. + * + * It can be accessed using: + * + * ```js + * import diagnostics_channel from 'diagnostics_channel'; + * ``` + * + * It is intended that a module writer wanting to report diagnostics messages + * will create one or many top-level channels to report messages through. + * Channels may also be acquired at runtime but it is not encouraged + * due to the additional overhead of doing so. Channels may be exported for + * convenience, but as long as the name is known it can be acquired anywhere. + * + * If you intend for your module to produce diagnostics data for others to + * consume it is recommended that you include documentation of what named + * channels are used along with the shape of the message data. Channel names + * should generally include the module name to avoid collisions with data from + * other modules. + * @experimental + * @see [source](https://github.com/nodejs/node/blob/v18.0.0/lib/diagnostics_channel.js) + */ +declare module 'diagnostics_channel' { + /** + * Check if there are active subscribers to the named channel. This is helpful if + * the message you want to send might be expensive to prepare. + * + * This API is optional but helpful when trying to publish messages from very + * performance-sensitive code. + * + * ```js + * import diagnostics_channel from 'diagnostics_channel'; + * + * if (diagnostics_channel.hasSubscribers('my-channel')) { + * // There are subscribers, prepare and publish message + * } + * ``` + * @since v15.1.0, v14.17.0 + * @param name The channel name + * @return If there are active subscribers + */ + function hasSubscribers(name: string): boolean; + /** + * This is the primary entry-point for anyone wanting to interact with a named + * channel. It produces a channel object which is optimized to reduce overhead at + * publish time as much as possible. + * + * ```js + * import diagnostics_channel from 'diagnostics_channel'; + * + * const channel = diagnostics_channel.channel('my-channel'); + * ``` + * @since v15.1.0, v14.17.0 + * @param name The channel name + * @return The named channel object + */ + function channel(name: string): Channel; + type ChannelListener = (message: unknown, name: string) => void; + /** + * The class `Channel` represents an individual named channel within the data + * pipeline. It is use to track subscribers and to publish messages when there + * are subscribers present. It exists as a separate object to avoid channel + * lookups at publish time, enabling very fast publish speeds and allowing + * for heavy use while incurring very minimal cost. Channels are created with {@link channel}, constructing a channel directly + * with `new Channel(name)` is not supported. + * @since v15.1.0, v14.17.0 + */ + class Channel { + readonly name: string; + /** + * Check if there are active subscribers to this channel. This is helpful if + * the message you want to send might be expensive to prepare. + * + * This API is optional but helpful when trying to publish messages from very + * performance-sensitive code. + * + * ```js + * import diagnostics_channel from 'diagnostics_channel'; + * + * const channel = diagnostics_channel.channel('my-channel'); + * + * if (channel.hasSubscribers) { + * // There are subscribers, prepare and publish message + * } + * ``` + * @since v15.1.0, v14.17.0 + */ + readonly hasSubscribers: boolean; + private constructor(name: string); + /** + * Publish a message to any subscribers to the channel. This will + * trigger message handlers synchronously so they will execute within + * the same context. + * + * ```js + * import diagnostics_channel from 'diagnostics_channel'; + * + * const channel = diagnostics_channel.channel('my-channel'); + * + * channel.publish({ + * some: 'message' + * }); + * ``` + * @since v15.1.0, v14.17.0 + * @param message The message to send to the channel subscribers + */ + publish(message: unknown): void; + /** + * Register a message handler to subscribe to this channel. This message handler + * will be run synchronously whenever a message is published to the channel. Any + * errors thrown in the message handler will trigger an `'uncaughtException'`. + * + * ```js + * import diagnostics_channel from 'diagnostics_channel'; + * + * const channel = diagnostics_channel.channel('my-channel'); + * + * channel.subscribe((message, name) => { + * // Received data + * }); + * ``` + * @since v15.1.0, v14.17.0 + * @param onMessage The handler to receive channel messages + */ + subscribe(onMessage: ChannelListener): void; + /** + * Remove a message handler previously registered to this channel with `channel.subscribe(onMessage)`. + * + * ```js + * import diagnostics_channel from 'diagnostics_channel'; + * + * const channel = diagnostics_channel.channel('my-channel'); + * + * function onMessage(message, name) { + * // Received data + * } + * + * channel.subscribe(onMessage); + * + * channel.unsubscribe(onMessage); + * ``` + * @since v15.1.0, v14.17.0 + * @param onMessage The previous subscribed handler to remove + * @return `true` if the handler was found, `false` otherwise. + */ + unsubscribe(onMessage: ChannelListener): void; + } +} +declare module 'node:diagnostics_channel' { + export * from 'diagnostics_channel'; +} diff --git a/ts-ticket-office-service/node_modules/@types/node/dns.d.ts b/ts-ticket-office-service/node_modules/@types/node/dns.d.ts new file mode 100755 index 000000000..305367b81 --- /dev/null +++ b/ts-ticket-office-service/node_modules/@types/node/dns.d.ts @@ -0,0 +1,659 @@ +/** + * The `dns` module enables name resolution. For example, use it to look up IP + * addresses of host names. + * + * Although named for the [Domain Name System (DNS)](https://en.wikipedia.org/wiki/Domain_Name_System), it does not always use the + * DNS protocol for lookups. {@link lookup} uses the operating system + * facilities to perform name resolution. It may not need to perform any network + * communication. To perform name resolution the way other applications on the same + * system do, use {@link lookup}. + * + * ```js + * const dns = require('dns'); + * + * dns.lookup('example.org', (err, address, family) => { + * console.log('address: %j family: IPv%s', address, family); + * }); + * // address: "93.184.216.34" family: IPv4 + * ``` + * + * All other functions in the `dns` module connect to an actual DNS server to + * perform name resolution. They will always use the network to perform DNS + * queries. These functions do not use the same set of configuration files used by {@link lookup} (e.g. `/etc/hosts`). Use these functions to always perform + * DNS queries, bypassing other name-resolution facilities. + * + * ```js + * const dns = require('dns'); + * + * dns.resolve4('archive.org', (err, addresses) => { + * if (err) throw err; + * + * console.log(`addresses: ${JSON.stringify(addresses)}`); + * + * addresses.forEach((a) => { + * dns.reverse(a, (err, hostnames) => { + * if (err) { + * throw err; + * } + * console.log(`reverse for ${a}: ${JSON.stringify(hostnames)}`); + * }); + * }); + * }); + * ``` + * + * See the `Implementation considerations section` for more information. + * @see [source](https://github.com/nodejs/node/blob/v18.0.0/lib/dns.js) + */ +declare module 'dns' { + import * as dnsPromises from 'node:dns/promises'; + // Supported getaddrinfo flags. + export const ADDRCONFIG: number; + export const V4MAPPED: number; + /** + * If `dns.V4MAPPED` is specified, return resolved IPv6 addresses as + * well as IPv4 mapped IPv6 addresses. + */ + export const ALL: number; + export interface LookupOptions { + family?: number | undefined; + hints?: number | undefined; + all?: boolean | undefined; + /** + * @default true + */ + verbatim?: boolean | undefined; + } + export interface LookupOneOptions extends LookupOptions { + all?: false | undefined; + } + export interface LookupAllOptions extends LookupOptions { + all: true; + } + export interface LookupAddress { + address: string; + family: number; + } + /** + * Resolves a host name (e.g. `'nodejs.org'`) into the first found A (IPv4) or + * AAAA (IPv6) record. All `option` properties are optional. If `options` is an + * integer, then it must be `4` or `6` – if `options` is not provided, then IPv4 + * and IPv6 addresses are both returned if found. + * + * With the `all` option set to `true`, the arguments for `callback` change to`(err, addresses)`, with `addresses` being an array of objects with the + * properties `address` and `family`. + * + * On error, `err` is an `Error` object, where `err.code` is the error code. + * Keep in mind that `err.code` will be set to `'ENOTFOUND'` not only when + * the host name does not exist but also when the lookup fails in other ways + * such as no available file descriptors. + * + * `dns.lookup()` does not necessarily have anything to do with the DNS protocol. + * The implementation uses an operating system facility that can associate names + * with addresses, and vice versa. This implementation can have subtle but + * important consequences on the behavior of any Node.js program. Please take some + * time to consult the `Implementation considerations section` before using`dns.lookup()`. + * + * Example usage: + * + * ```js + * const dns = require('dns'); + * const options = { + * family: 6, + * hints: dns.ADDRCONFIG | dns.V4MAPPED, + * }; + * dns.lookup('example.com', options, (err, address, family) => + * console.log('address: %j family: IPv%s', address, family)); + * // address: "2606:2800:220:1:248:1893:25c8:1946" family: IPv6 + * + * // When options.all is true, the result will be an Array. + * options.all = true; + * dns.lookup('example.com', options, (err, addresses) => + * console.log('addresses: %j', addresses)); + * // addresses: [{"address":"2606:2800:220:1:248:1893:25c8:1946","family":6}] + * ``` + * + * If this method is invoked as its `util.promisify()` ed version, and `all`is not set to `true`, it returns a `Promise` for an `Object` with `address` and`family` properties. + * @since v0.1.90 + */ + export function lookup(hostname: string, family: number, callback: (err: NodeJS.ErrnoException | null, address: string, family: number) => void): void; + export function lookup(hostname: string, options: LookupOneOptions, callback: (err: NodeJS.ErrnoException | null, address: string, family: number) => void): void; + export function lookup(hostname: string, options: LookupAllOptions, callback: (err: NodeJS.ErrnoException | null, addresses: LookupAddress[]) => void): void; + export function lookup(hostname: string, options: LookupOptions, callback: (err: NodeJS.ErrnoException | null, address: string | LookupAddress[], family: number) => void): void; + export function lookup(hostname: string, callback: (err: NodeJS.ErrnoException | null, address: string, family: number) => void): void; + export namespace lookup { + function __promisify__(hostname: string, options: LookupAllOptions): Promise; + function __promisify__(hostname: string, options?: LookupOneOptions | number): Promise; + function __promisify__(hostname: string, options: LookupOptions): Promise; + } + /** + * Resolves the given `address` and `port` into a host name and service using + * the operating system's underlying `getnameinfo` implementation. + * + * If `address` is not a valid IP address, a `TypeError` will be thrown. + * The `port` will be coerced to a number. If it is not a legal port, a `TypeError`will be thrown. + * + * On an error, `err` is an `Error` object, where `err.code` is the error code. + * + * ```js + * const dns = require('dns'); + * dns.lookupService('127.0.0.1', 22, (err, hostname, service) => { + * console.log(hostname, service); + * // Prints: localhost ssh + * }); + * ``` + * + * If this method is invoked as its `util.promisify()` ed version, it returns a`Promise` for an `Object` with `hostname` and `service` properties. + * @since v0.11.14 + */ + export function lookupService(address: string, port: number, callback: (err: NodeJS.ErrnoException | null, hostname: string, service: string) => void): void; + export namespace lookupService { + function __promisify__( + address: string, + port: number + ): Promise<{ + hostname: string; + service: string; + }>; + } + export interface ResolveOptions { + ttl: boolean; + } + export interface ResolveWithTtlOptions extends ResolveOptions { + ttl: true; + } + export interface RecordWithTtl { + address: string; + ttl: number; + } + /** @deprecated Use `AnyARecord` or `AnyAaaaRecord` instead. */ + export type AnyRecordWithTtl = AnyARecord | AnyAaaaRecord; + export interface AnyARecord extends RecordWithTtl { + type: 'A'; + } + export interface AnyAaaaRecord extends RecordWithTtl { + type: 'AAAA'; + } + export interface CaaRecord { + critial: number; + issue?: string | undefined; + issuewild?: string | undefined; + iodef?: string | undefined; + contactemail?: string | undefined; + contactphone?: string | undefined; + } + export interface MxRecord { + priority: number; + exchange: string; + } + export interface AnyMxRecord extends MxRecord { + type: 'MX'; + } + export interface NaptrRecord { + flags: string; + service: string; + regexp: string; + replacement: string; + order: number; + preference: number; + } + export interface AnyNaptrRecord extends NaptrRecord { + type: 'NAPTR'; + } + export interface SoaRecord { + nsname: string; + hostmaster: string; + serial: number; + refresh: number; + retry: number; + expire: number; + minttl: number; + } + export interface AnySoaRecord extends SoaRecord { + type: 'SOA'; + } + export interface SrvRecord { + priority: number; + weight: number; + port: number; + name: string; + } + export interface AnySrvRecord extends SrvRecord { + type: 'SRV'; + } + export interface AnyTxtRecord { + type: 'TXT'; + entries: string[]; + } + export interface AnyNsRecord { + type: 'NS'; + value: string; + } + export interface AnyPtrRecord { + type: 'PTR'; + value: string; + } + export interface AnyCnameRecord { + type: 'CNAME'; + value: string; + } + export type AnyRecord = AnyARecord | AnyAaaaRecord | AnyCnameRecord | AnyMxRecord | AnyNaptrRecord | AnyNsRecord | AnyPtrRecord | AnySoaRecord | AnySrvRecord | AnyTxtRecord; + /** + * Uses the DNS protocol to resolve a host name (e.g. `'nodejs.org'`) into an array + * of the resource records. The `callback` function has arguments`(err, records)`. When successful, `records` will be an array of resource + * records. The type and structure of individual results varies based on `rrtype`: + * + * + * + * On error, `err` is an `Error` object, where `err.code` is one of the `DNS error codes`. + * @since v0.1.27 + * @param hostname Host name to resolve. + * @param [rrtype='A'] Resource record type. + */ + export function resolve(hostname: string, callback: (err: NodeJS.ErrnoException | null, addresses: string[]) => void): void; + export function resolve(hostname: string, rrtype: 'A', callback: (err: NodeJS.ErrnoException | null, addresses: string[]) => void): void; + export function resolve(hostname: string, rrtype: 'AAAA', callback: (err: NodeJS.ErrnoException | null, addresses: string[]) => void): void; + export function resolve(hostname: string, rrtype: 'ANY', callback: (err: NodeJS.ErrnoException | null, addresses: AnyRecord[]) => void): void; + export function resolve(hostname: string, rrtype: 'CNAME', callback: (err: NodeJS.ErrnoException | null, addresses: string[]) => void): void; + export function resolve(hostname: string, rrtype: 'MX', callback: (err: NodeJS.ErrnoException | null, addresses: MxRecord[]) => void): void; + export function resolve(hostname: string, rrtype: 'NAPTR', callback: (err: NodeJS.ErrnoException | null, addresses: NaptrRecord[]) => void): void; + export function resolve(hostname: string, rrtype: 'NS', callback: (err: NodeJS.ErrnoException | null, addresses: string[]) => void): void; + export function resolve(hostname: string, rrtype: 'PTR', callback: (err: NodeJS.ErrnoException | null, addresses: string[]) => void): void; + export function resolve(hostname: string, rrtype: 'SOA', callback: (err: NodeJS.ErrnoException | null, addresses: SoaRecord) => void): void; + export function resolve(hostname: string, rrtype: 'SRV', callback: (err: NodeJS.ErrnoException | null, addresses: SrvRecord[]) => void): void; + export function resolve(hostname: string, rrtype: 'TXT', callback: (err: NodeJS.ErrnoException | null, addresses: string[][]) => void): void; + export function resolve( + hostname: string, + rrtype: string, + callback: (err: NodeJS.ErrnoException | null, addresses: string[] | MxRecord[] | NaptrRecord[] | SoaRecord | SrvRecord[] | string[][] | AnyRecord[]) => void + ): void; + export namespace resolve { + function __promisify__(hostname: string, rrtype?: 'A' | 'AAAA' | 'CNAME' | 'NS' | 'PTR'): Promise; + function __promisify__(hostname: string, rrtype: 'ANY'): Promise; + function __promisify__(hostname: string, rrtype: 'MX'): Promise; + function __promisify__(hostname: string, rrtype: 'NAPTR'): Promise; + function __promisify__(hostname: string, rrtype: 'SOA'): Promise; + function __promisify__(hostname: string, rrtype: 'SRV'): Promise; + function __promisify__(hostname: string, rrtype: 'TXT'): Promise; + function __promisify__(hostname: string, rrtype: string): Promise; + } + /** + * Uses the DNS protocol to resolve a IPv4 addresses (`A` records) for the`hostname`. The `addresses` argument passed to the `callback` function + * will contain an array of IPv4 addresses (e.g.`['74.125.79.104', '74.125.79.105', '74.125.79.106']`). + * @since v0.1.16 + * @param hostname Host name to resolve. + */ + export function resolve4(hostname: string, callback: (err: NodeJS.ErrnoException | null, addresses: string[]) => void): void; + export function resolve4(hostname: string, options: ResolveWithTtlOptions, callback: (err: NodeJS.ErrnoException | null, addresses: RecordWithTtl[]) => void): void; + export function resolve4(hostname: string, options: ResolveOptions, callback: (err: NodeJS.ErrnoException | null, addresses: string[] | RecordWithTtl[]) => void): void; + export namespace resolve4 { + function __promisify__(hostname: string): Promise; + function __promisify__(hostname: string, options: ResolveWithTtlOptions): Promise; + function __promisify__(hostname: string, options?: ResolveOptions): Promise; + } + /** + * Uses the DNS protocol to resolve a IPv6 addresses (`AAAA` records) for the`hostname`. The `addresses` argument passed to the `callback` function + * will contain an array of IPv6 addresses. + * @since v0.1.16 + * @param hostname Host name to resolve. + */ + export function resolve6(hostname: string, callback: (err: NodeJS.ErrnoException | null, addresses: string[]) => void): void; + export function resolve6(hostname: string, options: ResolveWithTtlOptions, callback: (err: NodeJS.ErrnoException | null, addresses: RecordWithTtl[]) => void): void; + export function resolve6(hostname: string, options: ResolveOptions, callback: (err: NodeJS.ErrnoException | null, addresses: string[] | RecordWithTtl[]) => void): void; + export namespace resolve6 { + function __promisify__(hostname: string): Promise; + function __promisify__(hostname: string, options: ResolveWithTtlOptions): Promise; + function __promisify__(hostname: string, options?: ResolveOptions): Promise; + } + /** + * Uses the DNS protocol to resolve `CNAME` records for the `hostname`. The`addresses` argument passed to the `callback` function + * will contain an array of canonical name records available for the `hostname`(e.g. `['bar.example.com']`). + * @since v0.3.2 + */ + export function resolveCname(hostname: string, callback: (err: NodeJS.ErrnoException | null, addresses: string[]) => void): void; + export namespace resolveCname { + function __promisify__(hostname: string): Promise; + } + /** + * Uses the DNS protocol to resolve `CAA` records for the `hostname`. The`addresses` argument passed to the `callback` function + * will contain an array of certification authority authorization records + * available for the `hostname` (e.g. `[{critical: 0, iodef: 'mailto:pki@example.com'}, {critical: 128, issue: 'pki.example.com'}]`). + * @since v15.0.0, v14.17.0 + */ + export function resolveCaa(hostname: string, callback: (err: NodeJS.ErrnoException | null, records: CaaRecord[]) => void): void; + export namespace resolveCaa { + function __promisify__(hostname: string): Promise; + } + /** + * Uses the DNS protocol to resolve mail exchange records (`MX` records) for the`hostname`. The `addresses` argument passed to the `callback` function will + * contain an array of objects containing both a `priority` and `exchange`property (e.g. `[{priority: 10, exchange: 'mx.example.com'}, ...]`). + * @since v0.1.27 + */ + export function resolveMx(hostname: string, callback: (err: NodeJS.ErrnoException | null, addresses: MxRecord[]) => void): void; + export namespace resolveMx { + function __promisify__(hostname: string): Promise; + } + /** + * Uses the DNS protocol to resolve regular expression based records (`NAPTR`records) for the `hostname`. The `addresses` argument passed to the `callback`function will contain an array of + * objects with the following properties: + * + * * `flags` + * * `service` + * * `regexp` + * * `replacement` + * * `order` + * * `preference` + * + * ```js + * { + * flags: 's', + * service: 'SIP+D2U', + * regexp: '', + * replacement: '_sip._udp.example.com', + * order: 30, + * preference: 100 + * } + * ``` + * @since v0.9.12 + */ + export function resolveNaptr(hostname: string, callback: (err: NodeJS.ErrnoException | null, addresses: NaptrRecord[]) => void): void; + export namespace resolveNaptr { + function __promisify__(hostname: string): Promise; + } + /** + * Uses the DNS protocol to resolve name server records (`NS` records) for the`hostname`. The `addresses` argument passed to the `callback` function will + * contain an array of name server records available for `hostname`(e.g. `['ns1.example.com', 'ns2.example.com']`). + * @since v0.1.90 + */ + export function resolveNs(hostname: string, callback: (err: NodeJS.ErrnoException | null, addresses: string[]) => void): void; + export namespace resolveNs { + function __promisify__(hostname: string): Promise; + } + /** + * Uses the DNS protocol to resolve pointer records (`PTR` records) for the`hostname`. The `addresses` argument passed to the `callback` function will + * be an array of strings containing the reply records. + * @since v6.0.0 + */ + export function resolvePtr(hostname: string, callback: (err: NodeJS.ErrnoException | null, addresses: string[]) => void): void; + export namespace resolvePtr { + function __promisify__(hostname: string): Promise; + } + /** + * Uses the DNS protocol to resolve a start of authority record (`SOA` record) for + * the `hostname`. The `address` argument passed to the `callback` function will + * be an object with the following properties: + * + * * `nsname` + * * `hostmaster` + * * `serial` + * * `refresh` + * * `retry` + * * `expire` + * * `minttl` + * + * ```js + * { + * nsname: 'ns.example.com', + * hostmaster: 'root.example.com', + * serial: 2013101809, + * refresh: 10000, + * retry: 2400, + * expire: 604800, + * minttl: 3600 + * } + * ``` + * @since v0.11.10 + */ + export function resolveSoa(hostname: string, callback: (err: NodeJS.ErrnoException | null, address: SoaRecord) => void): void; + export namespace resolveSoa { + function __promisify__(hostname: string): Promise; + } + /** + * Uses the DNS protocol to resolve service records (`SRV` records) for the`hostname`. The `addresses` argument passed to the `callback` function will + * be an array of objects with the following properties: + * + * * `priority` + * * `weight` + * * `port` + * * `name` + * + * ```js + * { + * priority: 10, + * weight: 5, + * port: 21223, + * name: 'service.example.com' + * } + * ``` + * @since v0.1.27 + */ + export function resolveSrv(hostname: string, callback: (err: NodeJS.ErrnoException | null, addresses: SrvRecord[]) => void): void; + export namespace resolveSrv { + function __promisify__(hostname: string): Promise; + } + /** + * Uses the DNS protocol to resolve text queries (`TXT` records) for the`hostname`. The `records` argument passed to the `callback` function is a + * two-dimensional array of the text records available for `hostname` (e.g.`[ ['v=spf1 ip4:0.0.0.0 ', '~all' ] ]`). Each sub-array contains TXT chunks of + * one record. Depending on the use case, these could be either joined together or + * treated separately. + * @since v0.1.27 + */ + export function resolveTxt(hostname: string, callback: (err: NodeJS.ErrnoException | null, addresses: string[][]) => void): void; + export namespace resolveTxt { + function __promisify__(hostname: string): Promise; + } + /** + * Uses the DNS protocol to resolve all records (also known as `ANY` or `*` query). + * The `ret` argument passed to the `callback` function will be an array containing + * various types of records. Each object has a property `type` that indicates the + * type of the current record. And depending on the `type`, additional properties + * will be present on the object: + * + * + * + * Here is an example of the `ret` object passed to the callback: + * + * ```js + * [ { type: 'A', address: '127.0.0.1', ttl: 299 }, + * { type: 'CNAME', value: 'example.com' }, + * { type: 'MX', exchange: 'alt4.aspmx.l.example.com', priority: 50 }, + * { type: 'NS', value: 'ns1.example.com' }, + * { type: 'TXT', entries: [ 'v=spf1 include:_spf.example.com ~all' ] }, + * { type: 'SOA', + * nsname: 'ns1.example.com', + * hostmaster: 'admin.example.com', + * serial: 156696742, + * refresh: 900, + * retry: 900, + * expire: 1800, + * minttl: 60 } ] + * ``` + * + * DNS server operators may choose not to respond to `ANY`queries. It may be better to call individual methods like {@link resolve4},{@link resolveMx}, and so on. For more details, see [RFC + * 8482](https://tools.ietf.org/html/rfc8482). + */ + export function resolveAny(hostname: string, callback: (err: NodeJS.ErrnoException | null, addresses: AnyRecord[]) => void): void; + export namespace resolveAny { + function __promisify__(hostname: string): Promise; + } + /** + * Performs a reverse DNS query that resolves an IPv4 or IPv6 address to an + * array of host names. + * + * On error, `err` is an `Error` object, where `err.code` is + * one of the `DNS error codes`. + * @since v0.1.16 + */ + export function reverse(ip: string, callback: (err: NodeJS.ErrnoException | null, hostnames: string[]) => void): void; + /** + * Sets the IP address and port of servers to be used when performing DNS + * resolution. The `servers` argument is an array of [RFC 5952](https://tools.ietf.org/html/rfc5952#section-6) formatted + * addresses. If the port is the IANA default DNS port (53) it can be omitted. + * + * ```js + * dns.setServers([ + * '4.4.4.4', + * '[2001:4860:4860::8888]', + * '4.4.4.4:1053', + * '[2001:4860:4860::8888]:1053', + * ]); + * ``` + * + * An error will be thrown if an invalid address is provided. + * + * The `dns.setServers()` method must not be called while a DNS query is in + * progress. + * + * The {@link setServers} method affects only {@link resolve},`dns.resolve*()` and {@link reverse} (and specifically _not_ {@link lookup}). + * + * This method works much like [resolve.conf](https://man7.org/linux/man-pages/man5/resolv.conf.5.html). + * That is, if attempting to resolve with the first server provided results in a`NOTFOUND` error, the `resolve()` method will _not_ attempt to resolve with + * subsequent servers provided. Fallback DNS servers will only be used if the + * earlier ones time out or result in some other error. + * @since v0.11.3 + * @param servers array of `RFC 5952` formatted addresses + */ + export function setServers(servers: ReadonlyArray): void; + /** + * Returns an array of IP address strings, formatted according to [RFC 5952](https://tools.ietf.org/html/rfc5952#section-6), + * that are currently configured for DNS resolution. A string will include a port + * section if a custom port is used. + * + * ```js + * [ + * '4.4.4.4', + * '2001:4860:4860::8888', + * '4.4.4.4:1053', + * '[2001:4860:4860::8888]:1053', + * ] + * ``` + * @since v0.11.3 + */ + export function getServers(): string[]; + /** + * Set the default value of `verbatim` in {@link lookup} and `dnsPromises.lookup()`. The value could be: + * + * * `ipv4first`: sets default `verbatim` `false`. + * * `verbatim`: sets default `verbatim` `true`. + * + * The default is `ipv4first` and {@link setDefaultResultOrder} have higher + * priority than `--dns-result-order`. When using `worker threads`,{@link setDefaultResultOrder} from the main thread won't affect the default + * dns orders in workers. + * @since v16.4.0, v14.18.0 + * @param order must be `'ipv4first'` or `'verbatim'`. + */ + export function setDefaultResultOrder(order: 'ipv4first' | 'verbatim'): void; + // Error codes + export const NODATA: string; + export const FORMERR: string; + export const SERVFAIL: string; + export const NOTFOUND: string; + export const NOTIMP: string; + export const REFUSED: string; + export const BADQUERY: string; + export const BADNAME: string; + export const BADFAMILY: string; + export const BADRESP: string; + export const CONNREFUSED: string; + export const TIMEOUT: string; + export const EOF: string; + export const FILE: string; + export const NOMEM: string; + export const DESTRUCTION: string; + export const BADSTR: string; + export const BADFLAGS: string; + export const NONAME: string; + export const BADHINTS: string; + export const NOTINITIALIZED: string; + export const LOADIPHLPAPI: string; + export const ADDRGETNETWORKPARAMS: string; + export const CANCELLED: string; + export interface ResolverOptions { + timeout?: number | undefined; + /** + * @default 4 + */ + tries?: number; + } + /** + * An independent resolver for DNS requests. + * + * Creating a new resolver uses the default server settings. Setting + * the servers used for a resolver using `resolver.setServers()` does not affect + * other resolvers: + * + * ```js + * const { Resolver } = require('dns'); + * const resolver = new Resolver(); + * resolver.setServers(['4.4.4.4']); + * + * // This request will use the server at 4.4.4.4, independent of global settings. + * resolver.resolve4('example.org', (err, addresses) => { + * // ... + * }); + * ``` + * + * The following methods from the `dns` module are available: + * + * * `resolver.getServers()` + * * `resolver.resolve()` + * * `resolver.resolve4()` + * * `resolver.resolve6()` + * * `resolver.resolveAny()` + * * `resolver.resolveCaa()` + * * `resolver.resolveCname()` + * * `resolver.resolveMx()` + * * `resolver.resolveNaptr()` + * * `resolver.resolveNs()` + * * `resolver.resolvePtr()` + * * `resolver.resolveSoa()` + * * `resolver.resolveSrv()` + * * `resolver.resolveTxt()` + * * `resolver.reverse()` + * * `resolver.setServers()` + * @since v8.3.0 + */ + export class Resolver { + constructor(options?: ResolverOptions); + /** + * Cancel all outstanding DNS queries made by this resolver. The corresponding + * callbacks will be called with an error with code `ECANCELLED`. + * @since v8.3.0 + */ + cancel(): void; + getServers: typeof getServers; + resolve: typeof resolve; + resolve4: typeof resolve4; + resolve6: typeof resolve6; + resolveAny: typeof resolveAny; + resolveCname: typeof resolveCname; + resolveMx: typeof resolveMx; + resolveNaptr: typeof resolveNaptr; + resolveNs: typeof resolveNs; + resolvePtr: typeof resolvePtr; + resolveSoa: typeof resolveSoa; + resolveSrv: typeof resolveSrv; + resolveTxt: typeof resolveTxt; + reverse: typeof reverse; + /** + * The resolver instance will send its requests from the specified IP address. + * This allows programs to specify outbound interfaces when used on multi-homed + * systems. + * + * If a v4 or v6 address is not specified, it is set to the default, and the + * operating system will choose a local address automatically. + * + * The resolver will use the v4 local address when making requests to IPv4 DNS + * servers, and the v6 local address when making requests to IPv6 DNS servers. + * The `rrtype` of resolution requests has no impact on the local address used. + * @since v15.1.0, v14.17.0 + * @param [ipv4='0.0.0.0'] A string representation of an IPv4 address. + * @param [ipv6='::0'] A string representation of an IPv6 address. + */ + setLocalAddress(ipv4?: string, ipv6?: string): void; + setServers: typeof setServers; + } + export { dnsPromises as promises }; +} +declare module 'node:dns' { + export * from 'dns'; +} diff --git a/ts-ticket-office-service/node_modules/@types/node/dns/promises.d.ts b/ts-ticket-office-service/node_modules/@types/node/dns/promises.d.ts new file mode 100755 index 000000000..77cd807bd --- /dev/null +++ b/ts-ticket-office-service/node_modules/@types/node/dns/promises.d.ts @@ -0,0 +1,370 @@ +/** + * The `dns.promises` API provides an alternative set of asynchronous DNS methods + * that return `Promise` objects rather than using callbacks. The API is accessible + * via `require('dns').promises` or `require('dns/promises')`. + * @since v10.6.0 + */ +declare module 'dns/promises' { + import { + LookupAddress, + LookupOneOptions, + LookupAllOptions, + LookupOptions, + AnyRecord, + CaaRecord, + MxRecord, + NaptrRecord, + SoaRecord, + SrvRecord, + ResolveWithTtlOptions, + RecordWithTtl, + ResolveOptions, + ResolverOptions, + } from 'node:dns'; + /** + * Returns an array of IP address strings, formatted according to [RFC 5952](https://tools.ietf.org/html/rfc5952#section-6), + * that are currently configured for DNS resolution. A string will include a port + * section if a custom port is used. + * + * ```js + * [ + * '4.4.4.4', + * '2001:4860:4860::8888', + * '4.4.4.4:1053', + * '[2001:4860:4860::8888]:1053', + * ] + * ``` + * @since v10.6.0 + */ + function getServers(): string[]; + /** + * Resolves a host name (e.g. `'nodejs.org'`) into the first found A (IPv4) or + * AAAA (IPv6) record. All `option` properties are optional. If `options` is an + * integer, then it must be `4` or `6` – if `options` is not provided, then IPv4 + * and IPv6 addresses are both returned if found. + * + * With the `all` option set to `true`, the `Promise` is resolved with `addresses`being an array of objects with the properties `address` and `family`. + * + * On error, the `Promise` is rejected with an `Error` object, where `err.code`is the error code. + * Keep in mind that `err.code` will be set to `'ENOTFOUND'` not only when + * the host name does not exist but also when the lookup fails in other ways + * such as no available file descriptors. + * + * `dnsPromises.lookup()` does not necessarily have anything to do with the DNS + * protocol. The implementation uses an operating system facility that can + * associate names with addresses, and vice versa. This implementation can have + * subtle but important consequences on the behavior of any Node.js program. Please + * take some time to consult the `Implementation considerations section` before + * using `dnsPromises.lookup()`. + * + * Example usage: + * + * ```js + * const dns = require('dns'); + * const dnsPromises = dns.promises; + * const options = { + * family: 6, + * hints: dns.ADDRCONFIG | dns.V4MAPPED, + * }; + * + * dnsPromises.lookup('example.com', options).then((result) => { + * console.log('address: %j family: IPv%s', result.address, result.family); + * // address: "2606:2800:220:1:248:1893:25c8:1946" family: IPv6 + * }); + * + * // When options.all is true, the result will be an Array. + * options.all = true; + * dnsPromises.lookup('example.com', options).then((result) => { + * console.log('addresses: %j', result); + * // addresses: [{"address":"2606:2800:220:1:248:1893:25c8:1946","family":6}] + * }); + * ``` + * @since v10.6.0 + */ + function lookup(hostname: string, family: number): Promise; + function lookup(hostname: string, options: LookupOneOptions): Promise; + function lookup(hostname: string, options: LookupAllOptions): Promise; + function lookup(hostname: string, options: LookupOptions): Promise; + function lookup(hostname: string): Promise; + /** + * Resolves the given `address` and `port` into a host name and service using + * the operating system's underlying `getnameinfo` implementation. + * + * If `address` is not a valid IP address, a `TypeError` will be thrown. + * The `port` will be coerced to a number. If it is not a legal port, a `TypeError`will be thrown. + * + * On error, the `Promise` is rejected with an `Error` object, where `err.code`is the error code. + * + * ```js + * const dnsPromises = require('dns').promises; + * dnsPromises.lookupService('127.0.0.1', 22).then((result) => { + * console.log(result.hostname, result.service); + * // Prints: localhost ssh + * }); + * ``` + * @since v10.6.0 + */ + function lookupService( + address: string, + port: number + ): Promise<{ + hostname: string; + service: string; + }>; + /** + * Uses the DNS protocol to resolve a host name (e.g. `'nodejs.org'`) into an array + * of the resource records. When successful, the `Promise` is resolved with an + * array of resource records. The type and structure of individual results vary + * based on `rrtype`: + * + * + * + * On error, the `Promise` is rejected with an `Error` object, where `err.code`is one of the `DNS error codes`. + * @since v10.6.0 + * @param hostname Host name to resolve. + * @param [rrtype='A'] Resource record type. + */ + function resolve(hostname: string): Promise; + function resolve(hostname: string, rrtype: 'A'): Promise; + function resolve(hostname: string, rrtype: 'AAAA'): Promise; + function resolve(hostname: string, rrtype: 'ANY'): Promise; + function resolve(hostname: string, rrtype: 'CAA'): Promise; + function resolve(hostname: string, rrtype: 'CNAME'): Promise; + function resolve(hostname: string, rrtype: 'MX'): Promise; + function resolve(hostname: string, rrtype: 'NAPTR'): Promise; + function resolve(hostname: string, rrtype: 'NS'): Promise; + function resolve(hostname: string, rrtype: 'PTR'): Promise; + function resolve(hostname: string, rrtype: 'SOA'): Promise; + function resolve(hostname: string, rrtype: 'SRV'): Promise; + function resolve(hostname: string, rrtype: 'TXT'): Promise; + function resolve(hostname: string, rrtype: string): Promise; + /** + * Uses the DNS protocol to resolve IPv4 addresses (`A` records) for the`hostname`. On success, the `Promise` is resolved with an array of IPv4 + * addresses (e.g. `['74.125.79.104', '74.125.79.105', '74.125.79.106']`). + * @since v10.6.0 + * @param hostname Host name to resolve. + */ + function resolve4(hostname: string): Promise; + function resolve4(hostname: string, options: ResolveWithTtlOptions): Promise; + function resolve4(hostname: string, options: ResolveOptions): Promise; + /** + * Uses the DNS protocol to resolve IPv6 addresses (`AAAA` records) for the`hostname`. On success, the `Promise` is resolved with an array of IPv6 + * addresses. + * @since v10.6.0 + * @param hostname Host name to resolve. + */ + function resolve6(hostname: string): Promise; + function resolve6(hostname: string, options: ResolveWithTtlOptions): Promise; + function resolve6(hostname: string, options: ResolveOptions): Promise; + /** + * Uses the DNS protocol to resolve all records (also known as `ANY` or `*` query). + * On success, the `Promise` is resolved with an array containing various types of + * records. Each object has a property `type` that indicates the type of the + * current record. And depending on the `type`, additional properties will be + * present on the object: + * + * + * + * Here is an example of the result object: + * + * ```js + * [ { type: 'A', address: '127.0.0.1', ttl: 299 }, + * { type: 'CNAME', value: 'example.com' }, + * { type: 'MX', exchange: 'alt4.aspmx.l.example.com', priority: 50 }, + * { type: 'NS', value: 'ns1.example.com' }, + * { type: 'TXT', entries: [ 'v=spf1 include:_spf.example.com ~all' ] }, + * { type: 'SOA', + * nsname: 'ns1.example.com', + * hostmaster: 'admin.example.com', + * serial: 156696742, + * refresh: 900, + * retry: 900, + * expire: 1800, + * minttl: 60 } ] + * ``` + * @since v10.6.0 + */ + function resolveAny(hostname: string): Promise; + /** + * Uses the DNS protocol to resolve `CAA` records for the `hostname`. On success, + * the `Promise` is resolved with an array of objects containing available + * certification authority authorization records available for the `hostname`(e.g. `[{critical: 0, iodef: 'mailto:pki@example.com'},{critical: 128, issue: 'pki.example.com'}]`). + * @since v15.0.0, v14.17.0 + */ + function resolveCaa(hostname: string): Promise; + /** + * Uses the DNS protocol to resolve `CNAME` records for the `hostname`. On success, + * the `Promise` is resolved with an array of canonical name records available for + * the `hostname` (e.g. `['bar.example.com']`). + * @since v10.6.0 + */ + function resolveCname(hostname: string): Promise; + /** + * Uses the DNS protocol to resolve mail exchange records (`MX` records) for the`hostname`. On success, the `Promise` is resolved with an array of objects + * containing both a `priority` and `exchange` property (e.g.`[{priority: 10, exchange: 'mx.example.com'}, ...]`). + * @since v10.6.0 + */ + function resolveMx(hostname: string): Promise; + /** + * Uses the DNS protocol to resolve regular expression based records (`NAPTR`records) for the `hostname`. On success, the `Promise` is resolved with an array + * of objects with the following properties: + * + * * `flags` + * * `service` + * * `regexp` + * * `replacement` + * * `order` + * * `preference` + * + * ```js + * { + * flags: 's', + * service: 'SIP+D2U', + * regexp: '', + * replacement: '_sip._udp.example.com', + * order: 30, + * preference: 100 + * } + * ``` + * @since v10.6.0 + */ + function resolveNaptr(hostname: string): Promise; + /** + * Uses the DNS protocol to resolve name server records (`NS` records) for the`hostname`. On success, the `Promise` is resolved with an array of name server + * records available for `hostname` (e.g.`['ns1.example.com', 'ns2.example.com']`). + * @since v10.6.0 + */ + function resolveNs(hostname: string): Promise; + /** + * Uses the DNS protocol to resolve pointer records (`PTR` records) for the`hostname`. On success, the `Promise` is resolved with an array of strings + * containing the reply records. + * @since v10.6.0 + */ + function resolvePtr(hostname: string): Promise; + /** + * Uses the DNS protocol to resolve a start of authority record (`SOA` record) for + * the `hostname`. On success, the `Promise` is resolved with an object with the + * following properties: + * + * * `nsname` + * * `hostmaster` + * * `serial` + * * `refresh` + * * `retry` + * * `expire` + * * `minttl` + * + * ```js + * { + * nsname: 'ns.example.com', + * hostmaster: 'root.example.com', + * serial: 2013101809, + * refresh: 10000, + * retry: 2400, + * expire: 604800, + * minttl: 3600 + * } + * ``` + * @since v10.6.0 + */ + function resolveSoa(hostname: string): Promise; + /** + * Uses the DNS protocol to resolve service records (`SRV` records) for the`hostname`. On success, the `Promise` is resolved with an array of objects with + * the following properties: + * + * * `priority` + * * `weight` + * * `port` + * * `name` + * + * ```js + * { + * priority: 10, + * weight: 5, + * port: 21223, + * name: 'service.example.com' + * } + * ``` + * @since v10.6.0 + */ + function resolveSrv(hostname: string): Promise; + /** + * Uses the DNS protocol to resolve text queries (`TXT` records) for the`hostname`. On success, the `Promise` is resolved with a two-dimensional array + * of the text records available for `hostname` (e.g.`[ ['v=spf1 ip4:0.0.0.0 ', '~all' ] ]`). Each sub-array contains TXT chunks of + * one record. Depending on the use case, these could be either joined together or + * treated separately. + * @since v10.6.0 + */ + function resolveTxt(hostname: string): Promise; + /** + * Performs a reverse DNS query that resolves an IPv4 or IPv6 address to an + * array of host names. + * + * On error, the `Promise` is rejected with an `Error` object, where `err.code`is one of the `DNS error codes`. + * @since v10.6.0 + */ + function reverse(ip: string): Promise; + /** + * Sets the IP address and port of servers to be used when performing DNS + * resolution. The `servers` argument is an array of [RFC 5952](https://tools.ietf.org/html/rfc5952#section-6) formatted + * addresses. If the port is the IANA default DNS port (53) it can be omitted. + * + * ```js + * dnsPromises.setServers([ + * '4.4.4.4', + * '[2001:4860:4860::8888]', + * '4.4.4.4:1053', + * '[2001:4860:4860::8888]:1053', + * ]); + * ``` + * + * An error will be thrown if an invalid address is provided. + * + * The `dnsPromises.setServers()` method must not be called while a DNS query is in + * progress. + * + * This method works much like [resolve.conf](https://man7.org/linux/man-pages/man5/resolv.conf.5.html). + * That is, if attempting to resolve with the first server provided results in a`NOTFOUND` error, the `resolve()` method will _not_ attempt to resolve with + * subsequent servers provided. Fallback DNS servers will only be used if the + * earlier ones time out or result in some other error. + * @since v10.6.0 + * @param servers array of `RFC 5952` formatted addresses + */ + function setServers(servers: ReadonlyArray): void; + /** + * Set the default value of `verbatim` in `dns.lookup()` and `dnsPromises.lookup()`. The value could be: + * + * * `ipv4first`: sets default `verbatim` `false`. + * * `verbatim`: sets default `verbatim` `true`. + * + * The default is `ipv4first` and `dnsPromises.setDefaultResultOrder()` have + * higher priority than `--dns-result-order`. When using `worker threads`,`dnsPromises.setDefaultResultOrder()` from the main thread won't affect the + * default dns orders in workers. + * @since v16.4.0, v14.18.0 + * @param order must be `'ipv4first'` or `'verbatim'`. + */ + function setDefaultResultOrder(order: 'ipv4first' | 'verbatim'): void; + class Resolver { + constructor(options?: ResolverOptions); + cancel(): void; + getServers: typeof getServers; + resolve: typeof resolve; + resolve4: typeof resolve4; + resolve6: typeof resolve6; + resolveAny: typeof resolveAny; + resolveCname: typeof resolveCname; + resolveMx: typeof resolveMx; + resolveNaptr: typeof resolveNaptr; + resolveNs: typeof resolveNs; + resolvePtr: typeof resolvePtr; + resolveSoa: typeof resolveSoa; + resolveSrv: typeof resolveSrv; + resolveTxt: typeof resolveTxt; + reverse: typeof reverse; + setLocalAddress(ipv4?: string, ipv6?: string): void; + setServers: typeof setServers; + } +} +declare module 'node:dns/promises' { + export * from 'dns/promises'; +} diff --git a/ts-ticket-office-service/node_modules/@types/node/domain.d.ts b/ts-ticket-office-service/node_modules/@types/node/domain.d.ts new file mode 100755 index 000000000..fafe68a5d --- /dev/null +++ b/ts-ticket-office-service/node_modules/@types/node/domain.d.ts @@ -0,0 +1,170 @@ +/** + * **This module is pending deprecation.** Once a replacement API has been + * finalized, this module will be fully deprecated. Most developers should + * **not** have cause to use this module. Users who absolutely must have + * the functionality that domains provide may rely on it for the time being + * but should expect to have to migrate to a different solution + * in the future. + * + * Domains provide a way to handle multiple different IO operations as a + * single group. If any of the event emitters or callbacks registered to a + * domain emit an `'error'` event, or throw an error, then the domain object + * will be notified, rather than losing the context of the error in the`process.on('uncaughtException')` handler, or causing the program to + * exit immediately with an error code. + * @deprecated Since v1.4.2 - Deprecated + * @see [source](https://github.com/nodejs/node/blob/v18.0.0/lib/domain.js) + */ +declare module 'domain' { + import EventEmitter = require('node:events'); + /** + * The `Domain` class encapsulates the functionality of routing errors and + * uncaught exceptions to the active `Domain` object. + * + * To handle the errors that it catches, listen to its `'error'` event. + */ + class Domain extends EventEmitter { + /** + * An array of timers and event emitters that have been explicitly added + * to the domain. + */ + members: Array; + /** + * The `enter()` method is plumbing used by the `run()`, `bind()`, and`intercept()` methods to set the active domain. It sets `domain.active` and`process.domain` to the domain, and implicitly + * pushes the domain onto the domain + * stack managed by the domain module (see {@link exit} for details on the + * domain stack). The call to `enter()` delimits the beginning of a chain of + * asynchronous calls and I/O operations bound to a domain. + * + * Calling `enter()` changes only the active domain, and does not alter the domain + * itself. `enter()` and `exit()` can be called an arbitrary number of times on a + * single domain. + */ + enter(): void; + /** + * The `exit()` method exits the current domain, popping it off the domain stack. + * Any time execution is going to switch to the context of a different chain of + * asynchronous calls, it's important to ensure that the current domain is exited. + * The call to `exit()` delimits either the end of or an interruption to the chain + * of asynchronous calls and I/O operations bound to a domain. + * + * If there are multiple, nested domains bound to the current execution context,`exit()` will exit any domains nested within this domain. + * + * Calling `exit()` changes only the active domain, and does not alter the domain + * itself. `enter()` and `exit()` can be called an arbitrary number of times on a + * single domain. + */ + exit(): void; + /** + * Run the supplied function in the context of the domain, implicitly + * binding all event emitters, timers, and lowlevel requests that are + * created in that context. Optionally, arguments can be passed to + * the function. + * + * This is the most basic way to use a domain. + * + * ```js + * const domain = require('domain'); + * const fs = require('fs'); + * const d = domain.create(); + * d.on('error', (er) => { + * console.error('Caught error!', er); + * }); + * d.run(() => { + * process.nextTick(() => { + * setTimeout(() => { // Simulating some various async stuff + * fs.open('non-existent file', 'r', (er, fd) => { + * if (er) throw er; + * // proceed... + * }); + * }, 100); + * }); + * }); + * ``` + * + * In this example, the `d.on('error')` handler will be triggered, rather + * than crashing the program. + */ + run(fn: (...args: any[]) => T, ...args: any[]): T; + /** + * Explicitly adds an emitter to the domain. If any event handlers called by + * the emitter throw an error, or if the emitter emits an `'error'` event, it + * will be routed to the domain's `'error'` event, just like with implicit + * binding. + * + * This also works with timers that are returned from `setInterval()` and `setTimeout()`. If their callback function throws, it will be caught by + * the domain `'error'` handler. + * + * If the Timer or `EventEmitter` was already bound to a domain, it is removed + * from that one, and bound to this one instead. + * @param emitter emitter or timer to be added to the domain + */ + add(emitter: EventEmitter | NodeJS.Timer): void; + /** + * The opposite of {@link add}. Removes domain handling from the + * specified emitter. + * @param emitter emitter or timer to be removed from the domain + */ + remove(emitter: EventEmitter | NodeJS.Timer): void; + /** + * The returned function will be a wrapper around the supplied callback + * function. When the returned function is called, any errors that are + * thrown will be routed to the domain's `'error'` event. + * + * ```js + * const d = domain.create(); + * + * function readSomeFile(filename, cb) { + * fs.readFile(filename, 'utf8', d.bind((er, data) => { + * // If this throws, it will also be passed to the domain. + * return cb(er, data ? JSON.parse(data) : null); + * })); + * } + * + * d.on('error', (er) => { + * // An error occurred somewhere. If we throw it now, it will crash the program + * // with the normal line number and stack message. + * }); + * ``` + * @param callback The callback function + * @return The bound function + */ + bind(callback: T): T; + /** + * This method is almost identical to {@link bind}. However, in + * addition to catching thrown errors, it will also intercept `Error` objects sent as the first argument to the function. + * + * In this way, the common `if (err) return callback(err);` pattern can be replaced + * with a single error handler in a single place. + * + * ```js + * const d = domain.create(); + * + * function readSomeFile(filename, cb) { + * fs.readFile(filename, 'utf8', d.intercept((data) => { + * // Note, the first argument is never passed to the + * // callback since it is assumed to be the 'Error' argument + * // and thus intercepted by the domain. + * + * // If this throws, it will also be passed to the domain + * // so the error-handling logic can be moved to the 'error' + * // event on the domain instead of being repeated throughout + * // the program. + * return cb(null, JSON.parse(data)); + * })); + * } + * + * d.on('error', (er) => { + * // An error occurred somewhere. If we throw it now, it will crash the program + * // with the normal line number and stack message. + * }); + * ``` + * @param callback The callback function + * @return The intercepted function + */ + intercept(callback: T): T; + } + function create(): Domain; +} +declare module 'node:domain' { + export * from 'domain'; +} diff --git a/ts-ticket-office-service/node_modules/@types/node/events.d.ts b/ts-ticket-office-service/node_modules/@types/node/events.d.ts new file mode 100755 index 000000000..85cbd66ac --- /dev/null +++ b/ts-ticket-office-service/node_modules/@types/node/events.d.ts @@ -0,0 +1,641 @@ +/** + * Much of the Node.js core API is built around an idiomatic asynchronous + * event-driven architecture in which certain kinds of objects (called "emitters") + * emit named events that cause `Function` objects ("listeners") to be called. + * + * For instance: a `net.Server` object emits an event each time a peer + * connects to it; a `fs.ReadStream` emits an event when the file is opened; + * a `stream` emits an event whenever data is available to be read. + * + * All objects that emit events are instances of the `EventEmitter` class. These + * objects expose an `eventEmitter.on()` function that allows one or more + * functions to be attached to named events emitted by the object. Typically, + * event names are camel-cased strings but any valid JavaScript property key + * can be used. + * + * When the `EventEmitter` object emits an event, all of the functions attached + * to that specific event are called _synchronously_. Any values returned by the + * called listeners are _ignored_ and discarded. + * + * The following example shows a simple `EventEmitter` instance with a single + * listener. The `eventEmitter.on()` method is used to register listeners, while + * the `eventEmitter.emit()` method is used to trigger the event. + * + * ```js + * const EventEmitter = require('events'); + * + * class MyEmitter extends EventEmitter {} + * + * const myEmitter = new MyEmitter(); + * myEmitter.on('event', () => { + * console.log('an event occurred!'); + * }); + * myEmitter.emit('event'); + * ``` + * @see [source](https://github.com/nodejs/node/blob/v18.0.0/lib/events.js) + */ +declare module 'events' { + interface EventEmitterOptions { + /** + * Enables automatic capturing of promise rejection. + */ + captureRejections?: boolean | undefined; + } + interface NodeEventTarget { + once(eventName: string | symbol, listener: (...args: any[]) => void): this; + } + interface DOMEventTarget { + addEventListener( + eventName: string, + listener: (...args: any[]) => void, + opts?: { + once: boolean; + } + ): any; + } + interface StaticEventEmitterOptions { + signal?: AbortSignal | undefined; + } + interface EventEmitter extends NodeJS.EventEmitter {} + /** + * The `EventEmitter` class is defined and exposed by the `events` module: + * + * ```js + * const EventEmitter = require('events'); + * ``` + * + * All `EventEmitter`s emit the event `'newListener'` when new listeners are + * added and `'removeListener'` when existing listeners are removed. + * + * It supports the following option: + * @since v0.1.26 + */ + class EventEmitter { + constructor(options?: EventEmitterOptions); + /** + * Creates a `Promise` that is fulfilled when the `EventEmitter` emits the given + * event or that is rejected if the `EventEmitter` emits `'error'` while waiting. + * The `Promise` will resolve with an array of all the arguments emitted to the + * given event. + * + * This method is intentionally generic and works with the web platform [EventTarget](https://dom.spec.whatwg.org/#interface-eventtarget) interface, which has no special`'error'` event + * semantics and does not listen to the `'error'` event. + * + * ```js + * const { once, EventEmitter } = require('events'); + * + * async function run() { + * const ee = new EventEmitter(); + * + * process.nextTick(() => { + * ee.emit('myevent', 42); + * }); + * + * const [value] = await once(ee, 'myevent'); + * console.log(value); + * + * const err = new Error('kaboom'); + * process.nextTick(() => { + * ee.emit('error', err); + * }); + * + * try { + * await once(ee, 'myevent'); + * } catch (err) { + * console.log('error happened', err); + * } + * } + * + * run(); + * ``` + * + * The special handling of the `'error'` event is only used when `events.once()`is used to wait for another event. If `events.once()` is used to wait for the + * '`error'` event itself, then it is treated as any other kind of event without + * special handling: + * + * ```js + * const { EventEmitter, once } = require('events'); + * + * const ee = new EventEmitter(); + * + * once(ee, 'error') + * .then(([err]) => console.log('ok', err.message)) + * .catch((err) => console.log('error', err.message)); + * + * ee.emit('error', new Error('boom')); + * + * // Prints: ok boom + * ``` + * + * An `AbortSignal` can be used to cancel waiting for the event: + * + * ```js + * const { EventEmitter, once } = require('events'); + * + * const ee = new EventEmitter(); + * const ac = new AbortController(); + * + * async function foo(emitter, event, signal) { + * try { + * await once(emitter, event, { signal }); + * console.log('event emitted!'); + * } catch (error) { + * if (error.name === 'AbortError') { + * console.error('Waiting for the event was canceled!'); + * } else { + * console.error('There was an error', error.message); + * } + * } + * } + * + * foo(ee, 'foo', ac.signal); + * ac.abort(); // Abort waiting for the event + * ee.emit('foo'); // Prints: Waiting for the event was canceled! + * ``` + * @since v11.13.0, v10.16.0 + */ + static once(emitter: NodeEventTarget, eventName: string | symbol, options?: StaticEventEmitterOptions): Promise; + static once(emitter: DOMEventTarget, eventName: string, options?: StaticEventEmitterOptions): Promise; + /** + * ```js + * const { on, EventEmitter } = require('events'); + * + * (async () => { + * const ee = new EventEmitter(); + * + * // Emit later on + * process.nextTick(() => { + * ee.emit('foo', 'bar'); + * ee.emit('foo', 42); + * }); + * + * for await (const event of on(ee, 'foo')) { + * // The execution of this inner block is synchronous and it + * // processes one event at a time (even with await). Do not use + * // if concurrent execution is required. + * console.log(event); // prints ['bar'] [42] + * } + * // Unreachable here + * })(); + * ``` + * + * Returns an `AsyncIterator` that iterates `eventName` events. It will throw + * if the `EventEmitter` emits `'error'`. It removes all listeners when + * exiting the loop. The `value` returned by each iteration is an array + * composed of the emitted event arguments. + * + * An `AbortSignal` can be used to cancel waiting on events: + * + * ```js + * const { on, EventEmitter } = require('events'); + * const ac = new AbortController(); + * + * (async () => { + * const ee = new EventEmitter(); + * + * // Emit later on + * process.nextTick(() => { + * ee.emit('foo', 'bar'); + * ee.emit('foo', 42); + * }); + * + * for await (const event of on(ee, 'foo', { signal: ac.signal })) { + * // The execution of this inner block is synchronous and it + * // processes one event at a time (even with await). Do not use + * // if concurrent execution is required. + * console.log(event); // prints ['bar'] [42] + * } + * // Unreachable here + * })(); + * + * process.nextTick(() => ac.abort()); + * ``` + * @since v13.6.0, v12.16.0 + * @param eventName The name of the event being listened for + * @return that iterates `eventName` events emitted by the `emitter` + */ + static on(emitter: NodeJS.EventEmitter, eventName: string, options?: StaticEventEmitterOptions): AsyncIterableIterator; + /** + * A class method that returns the number of listeners for the given `eventName`registered on the given `emitter`. + * + * ```js + * const { EventEmitter, listenerCount } = require('events'); + * const myEmitter = new EventEmitter(); + * myEmitter.on('event', () => {}); + * myEmitter.on('event', () => {}); + * console.log(listenerCount(myEmitter, 'event')); + * // Prints: 2 + * ``` + * @since v0.9.12 + * @deprecated Since v3.2.0 - Use `listenerCount` instead. + * @param emitter The emitter to query + * @param eventName The event name + */ + static listenerCount(emitter: NodeJS.EventEmitter, eventName: string | symbol): number; + /** + * Returns a copy of the array of listeners for the event named `eventName`. + * + * For `EventEmitter`s this behaves exactly the same as calling `.listeners` on + * the emitter. + * + * For `EventTarget`s this is the only way to get the event listeners for the + * event target. This is useful for debugging and diagnostic purposes. + * + * ```js + * const { getEventListeners, EventEmitter } = require('events'); + * + * { + * const ee = new EventEmitter(); + * const listener = () => console.log('Events are fun'); + * ee.on('foo', listener); + * getEventListeners(ee, 'foo'); // [listener] + * } + * { + * const et = new EventTarget(); + * const listener = () => console.log('Events are fun'); + * et.addEventListener('foo', listener); + * getEventListeners(et, 'foo'); // [listener] + * } + * ``` + * @since v15.2.0, v14.17.0 + */ + static getEventListeners(emitter: DOMEventTarget | NodeJS.EventEmitter, name: string | symbol): Function[]; + /** + * ```js + * const { + * setMaxListeners, + * EventEmitter + * } = require('events'); + * + * const target = new EventTarget(); + * const emitter = new EventEmitter(); + * + * setMaxListeners(5, target, emitter); + * ``` + * @since v15.4.0 + * @param n A non-negative number. The maximum number of listeners per `EventTarget` event. + * @param eventsTargets Zero or more {EventTarget} or {EventEmitter} instances. If none are specified, `n` is set as the default max for all newly created {EventTarget} and {EventEmitter} + * objects. + */ + static setMaxListeners(n?: number, ...eventTargets: Array): void; + /** + * This symbol shall be used to install a listener for only monitoring `'error'` + * events. Listeners installed using this symbol are called before the regular + * `'error'` listeners are called. + * + * Installing a listener using this symbol does not change the behavior once an + * `'error'` event is emitted, therefore the process will still crash if no + * regular `'error'` listener is installed. + */ + static readonly errorMonitor: unique symbol; + static readonly captureRejectionSymbol: unique symbol; + /** + * Sets or gets the default captureRejection value for all emitters. + */ + // TODO: These should be described using static getter/setter pairs: + static captureRejections: boolean; + static defaultMaxListeners: number; + } + import internal = require('node:events'); + namespace EventEmitter { + // Should just be `export { EventEmitter }`, but that doesn't work in TypeScript 3.4 + export { internal as EventEmitter }; + export interface Abortable { + /** + * When provided the corresponding `AbortController` can be used to cancel an asynchronous action. + */ + signal?: AbortSignal | undefined; + } + } + global { + namespace NodeJS { + interface EventEmitter { + /** + * Alias for `emitter.on(eventName, listener)`. + * @since v0.1.26 + */ + addListener(eventName: string | symbol, listener: (...args: any[]) => void): this; + /** + * Adds the `listener` function to the end of the listeners array for the + * event named `eventName`. No checks are made to see if the `listener` has + * already been added. Multiple calls passing the same combination of `eventName`and `listener` will result in the `listener` being added, and called, multiple + * times. + * + * ```js + * server.on('connection', (stream) => { + * console.log('someone connected!'); + * }); + * ``` + * + * Returns a reference to the `EventEmitter`, so that calls can be chained. + * + * By default, event listeners are invoked in the order they are added. The`emitter.prependListener()` method can be used as an alternative to add the + * event listener to the beginning of the listeners array. + * + * ```js + * const myEE = new EventEmitter(); + * myEE.on('foo', () => console.log('a')); + * myEE.prependListener('foo', () => console.log('b')); + * myEE.emit('foo'); + * // Prints: + * // b + * // a + * ``` + * @since v0.1.101 + * @param eventName The name of the event. + * @param listener The callback function + */ + on(eventName: string | symbol, listener: (...args: any[]) => void): this; + /** + * Adds a **one-time**`listener` function for the event named `eventName`. The + * next time `eventName` is triggered, this listener is removed and then invoked. + * + * ```js + * server.once('connection', (stream) => { + * console.log('Ah, we have our first user!'); + * }); + * ``` + * + * Returns a reference to the `EventEmitter`, so that calls can be chained. + * + * By default, event listeners are invoked in the order they are added. The`emitter.prependOnceListener()` method can be used as an alternative to add the + * event listener to the beginning of the listeners array. + * + * ```js + * const myEE = new EventEmitter(); + * myEE.once('foo', () => console.log('a')); + * myEE.prependOnceListener('foo', () => console.log('b')); + * myEE.emit('foo'); + * // Prints: + * // b + * // a + * ``` + * @since v0.3.0 + * @param eventName The name of the event. + * @param listener The callback function + */ + once(eventName: string | symbol, listener: (...args: any[]) => void): this; + /** + * Removes the specified `listener` from the listener array for the event named`eventName`. + * + * ```js + * const callback = (stream) => { + * console.log('someone connected!'); + * }; + * server.on('connection', callback); + * // ... + * server.removeListener('connection', callback); + * ``` + * + * `removeListener()` will remove, at most, one instance of a listener from the + * listener array. If any single listener has been added multiple times to the + * listener array for the specified `eventName`, then `removeListener()` must be + * called multiple times to remove each instance. + * + * Once an event is emitted, all listeners attached to it at the + * time of emitting are called in order. This implies that any`removeListener()` or `removeAllListeners()` calls _after_ emitting and_before_ the last listener finishes execution will + * not remove them from`emit()` in progress. Subsequent events behave as expected. + * + * ```js + * const myEmitter = new MyEmitter(); + * + * const callbackA = () => { + * console.log('A'); + * myEmitter.removeListener('event', callbackB); + * }; + * + * const callbackB = () => { + * console.log('B'); + * }; + * + * myEmitter.on('event', callbackA); + * + * myEmitter.on('event', callbackB); + * + * // callbackA removes listener callbackB but it will still be called. + * // Internal listener array at time of emit [callbackA, callbackB] + * myEmitter.emit('event'); + * // Prints: + * // A + * // B + * + * // callbackB is now removed. + * // Internal listener array [callbackA] + * myEmitter.emit('event'); + * // Prints: + * // A + * ``` + * + * Because listeners are managed using an internal array, calling this will + * change the position indices of any listener registered _after_ the listener + * being removed. This will not impact the order in which listeners are called, + * but it means that any copies of the listener array as returned by + * the `emitter.listeners()` method will need to be recreated. + * + * When a single function has been added as a handler multiple times for a single + * event (as in the example below), `removeListener()` will remove the most + * recently added instance. In the example the `once('ping')`listener is removed: + * + * ```js + * const ee = new EventEmitter(); + * + * function pong() { + * console.log('pong'); + * } + * + * ee.on('ping', pong); + * ee.once('ping', pong); + * ee.removeListener('ping', pong); + * + * ee.emit('ping'); + * ee.emit('ping'); + * ``` + * + * Returns a reference to the `EventEmitter`, so that calls can be chained. + * @since v0.1.26 + */ + removeListener(eventName: string | symbol, listener: (...args: any[]) => void): this; + /** + * Alias for `emitter.removeListener()`. + * @since v10.0.0 + */ + off(eventName: string | symbol, listener: (...args: any[]) => void): this; + /** + * Removes all listeners, or those of the specified `eventName`. + * + * It is bad practice to remove listeners added elsewhere in the code, + * particularly when the `EventEmitter` instance was created by some other + * component or module (e.g. sockets or file streams). + * + * Returns a reference to the `EventEmitter`, so that calls can be chained. + * @since v0.1.26 + */ + removeAllListeners(event?: string | symbol): this; + /** + * By default `EventEmitter`s will print a warning if more than `10` listeners are + * added for a particular event. This is a useful default that helps finding + * memory leaks. The `emitter.setMaxListeners()` method allows the limit to be + * modified for this specific `EventEmitter` instance. The value can be set to`Infinity` (or `0`) to indicate an unlimited number of listeners. + * + * Returns a reference to the `EventEmitter`, so that calls can be chained. + * @since v0.3.5 + */ + setMaxListeners(n: number): this; + /** + * Returns the current max listener value for the `EventEmitter` which is either + * set by `emitter.setMaxListeners(n)` or defaults to {@link defaultMaxListeners}. + * @since v1.0.0 + */ + getMaxListeners(): number; + /** + * Returns a copy of the array of listeners for the event named `eventName`. + * + * ```js + * server.on('connection', (stream) => { + * console.log('someone connected!'); + * }); + * console.log(util.inspect(server.listeners('connection'))); + * // Prints: [ [Function] ] + * ``` + * @since v0.1.26 + */ + listeners(eventName: string | symbol): Function[]; + /** + * Returns a copy of the array of listeners for the event named `eventName`, + * including any wrappers (such as those created by `.once()`). + * + * ```js + * const emitter = new EventEmitter(); + * emitter.once('log', () => console.log('log once')); + * + * // Returns a new Array with a function `onceWrapper` which has a property + * // `listener` which contains the original listener bound above + * const listeners = emitter.rawListeners('log'); + * const logFnWrapper = listeners[0]; + * + * // Logs "log once" to the console and does not unbind the `once` event + * logFnWrapper.listener(); + * + * // Logs "log once" to the console and removes the listener + * logFnWrapper(); + * + * emitter.on('log', () => console.log('log persistently')); + * // Will return a new Array with a single function bound by `.on()` above + * const newListeners = emitter.rawListeners('log'); + * + * // Logs "log persistently" twice + * newListeners[0](); + * emitter.emit('log'); + * ``` + * @since v9.4.0 + */ + rawListeners(eventName: string | symbol): Function[]; + /** + * Synchronously calls each of the listeners registered for the event named`eventName`, in the order they were registered, passing the supplied arguments + * to each. + * + * Returns `true` if the event had listeners, `false` otherwise. + * + * ```js + * const EventEmitter = require('events'); + * const myEmitter = new EventEmitter(); + * + * // First listener + * myEmitter.on('event', function firstListener() { + * console.log('Helloooo! first listener'); + * }); + * // Second listener + * myEmitter.on('event', function secondListener(arg1, arg2) { + * console.log(`event with parameters ${arg1}, ${arg2} in second listener`); + * }); + * // Third listener + * myEmitter.on('event', function thirdListener(...args) { + * const parameters = args.join(', '); + * console.log(`event with parameters ${parameters} in third listener`); + * }); + * + * console.log(myEmitter.listeners('event')); + * + * myEmitter.emit('event', 1, 2, 3, 4, 5); + * + * // Prints: + * // [ + * // [Function: firstListener], + * // [Function: secondListener], + * // [Function: thirdListener] + * // ] + * // Helloooo! first listener + * // event with parameters 1, 2 in second listener + * // event with parameters 1, 2, 3, 4, 5 in third listener + * ``` + * @since v0.1.26 + */ + emit(eventName: string | symbol, ...args: any[]): boolean; + /** + * Returns the number of listeners listening to the event named `eventName`. + * @since v3.2.0 + * @param eventName The name of the event being listened for + */ + listenerCount(eventName: string | symbol): number; + /** + * Adds the `listener` function to the _beginning_ of the listeners array for the + * event named `eventName`. No checks are made to see if the `listener` has + * already been added. Multiple calls passing the same combination of `eventName`and `listener` will result in the `listener` being added, and called, multiple + * times. + * + * ```js + * server.prependListener('connection', (stream) => { + * console.log('someone connected!'); + * }); + * ``` + * + * Returns a reference to the `EventEmitter`, so that calls can be chained. + * @since v6.0.0 + * @param eventName The name of the event. + * @param listener The callback function + */ + prependListener(eventName: string | symbol, listener: (...args: any[]) => void): this; + /** + * Adds a **one-time**`listener` function for the event named `eventName` to the_beginning_ of the listeners array. The next time `eventName` is triggered, this + * listener is removed, and then invoked. + * + * ```js + * server.prependOnceListener('connection', (stream) => { + * console.log('Ah, we have our first user!'); + * }); + * ``` + * + * Returns a reference to the `EventEmitter`, so that calls can be chained. + * @since v6.0.0 + * @param eventName The name of the event. + * @param listener The callback function + */ + prependOnceListener(eventName: string | symbol, listener: (...args: any[]) => void): this; + /** + * Returns an array listing the events for which the emitter has registered + * listeners. The values in the array are strings or `Symbol`s. + * + * ```js + * const EventEmitter = require('events'); + * const myEE = new EventEmitter(); + * myEE.on('foo', () => {}); + * myEE.on('bar', () => {}); + * + * const sym = Symbol('symbol'); + * myEE.on(sym, () => {}); + * + * console.log(myEE.eventNames()); + * // Prints: [ 'foo', 'bar', Symbol(symbol) ] + * ``` + * @since v6.0.0 + */ + eventNames(): Array; + } + } + } + export = EventEmitter; +} +declare module 'node:events' { + import events = require('events'); + export = events; +} diff --git a/ts-ticket-office-service/node_modules/@types/node/fs.d.ts b/ts-ticket-office-service/node_modules/@types/node/fs.d.ts new file mode 100755 index 000000000..08515148a --- /dev/null +++ b/ts-ticket-office-service/node_modules/@types/node/fs.d.ts @@ -0,0 +1,3858 @@ +/** + * The `fs` module enables interacting with the file system in a + * way modeled on standard POSIX functions. + * + * To use the promise-based APIs: + * + * ```js + * import * as fs from 'fs/promises'; + * ``` + * + * To use the callback and sync APIs: + * + * ```js + * import * as fs from 'fs'; + * ``` + * + * All file system operations have synchronous, callback, and promise-based + * forms, and are accessible using both CommonJS syntax and ES6 Modules (ESM). + * @see [source](https://github.com/nodejs/node/blob/v18.0.0/lib/fs.js) + */ +declare module 'fs' { + import * as stream from 'node:stream'; + import { Abortable, EventEmitter } from 'node:events'; + import { URL } from 'node:url'; + import * as promises from 'node:fs/promises'; + export { promises }; + /** + * Valid types for path values in "fs". + */ + export type PathLike = string | Buffer | URL; + export type PathOrFileDescriptor = PathLike | number; + export type TimeLike = string | number | Date; + export type NoParamCallback = (err: NodeJS.ErrnoException | null) => void; + export type BufferEncodingOption = + | 'buffer' + | { + encoding: 'buffer'; + }; + export interface ObjectEncodingOptions { + encoding?: BufferEncoding | null | undefined; + } + export type EncodingOption = ObjectEncodingOptions | BufferEncoding | undefined | null; + export type OpenMode = number | string; + export type Mode = number | string; + export interface StatsBase { + isFile(): boolean; + isDirectory(): boolean; + isBlockDevice(): boolean; + isCharacterDevice(): boolean; + isSymbolicLink(): boolean; + isFIFO(): boolean; + isSocket(): boolean; + dev: T; + ino: T; + mode: T; + nlink: T; + uid: T; + gid: T; + rdev: T; + size: T; + blksize: T; + blocks: T; + atimeMs: T; + mtimeMs: T; + ctimeMs: T; + birthtimeMs: T; + atime: Date; + mtime: Date; + ctime: Date; + birthtime: Date; + } + export interface Stats extends StatsBase {} + /** + * A `fs.Stats` object provides information about a file. + * + * Objects returned from {@link stat}, {@link lstat} and {@link fstat} and + * their synchronous counterparts are of this type. + * If `bigint` in the `options` passed to those methods is true, the numeric values + * will be `bigint` instead of `number`, and the object will contain additional + * nanosecond-precision properties suffixed with `Ns`. + * + * ```console + * Stats { + * dev: 2114, + * ino: 48064969, + * mode: 33188, + * nlink: 1, + * uid: 85, + * gid: 100, + * rdev: 0, + * size: 527, + * blksize: 4096, + * blocks: 8, + * atimeMs: 1318289051000.1, + * mtimeMs: 1318289051000.1, + * ctimeMs: 1318289051000.1, + * birthtimeMs: 1318289051000.1, + * atime: Mon, 10 Oct 2011 23:24:11 GMT, + * mtime: Mon, 10 Oct 2011 23:24:11 GMT, + * ctime: Mon, 10 Oct 2011 23:24:11 GMT, + * birthtime: Mon, 10 Oct 2011 23:24:11 GMT } + * ``` + * + * `bigint` version: + * + * ```console + * BigIntStats { + * dev: 2114n, + * ino: 48064969n, + * mode: 33188n, + * nlink: 1n, + * uid: 85n, + * gid: 100n, + * rdev: 0n, + * size: 527n, + * blksize: 4096n, + * blocks: 8n, + * atimeMs: 1318289051000n, + * mtimeMs: 1318289051000n, + * ctimeMs: 1318289051000n, + * birthtimeMs: 1318289051000n, + * atimeNs: 1318289051000000000n, + * mtimeNs: 1318289051000000000n, + * ctimeNs: 1318289051000000000n, + * birthtimeNs: 1318289051000000000n, + * atime: Mon, 10 Oct 2011 23:24:11 GMT, + * mtime: Mon, 10 Oct 2011 23:24:11 GMT, + * ctime: Mon, 10 Oct 2011 23:24:11 GMT, + * birthtime: Mon, 10 Oct 2011 23:24:11 GMT } + * ``` + * @since v0.1.21 + */ + export class Stats {} + /** + * A representation of a directory entry, which can be a file or a subdirectory + * within the directory, as returned by reading from an `fs.Dir`. The + * directory entry is a combination of the file name and file type pairs. + * + * Additionally, when {@link readdir} or {@link readdirSync} is called with + * the `withFileTypes` option set to `true`, the resulting array is filled with `fs.Dirent` objects, rather than strings or `Buffer` s. + * @since v10.10.0 + */ + export class Dirent { + /** + * Returns `true` if the `fs.Dirent` object describes a regular file. + * @since v10.10.0 + */ + isFile(): boolean; + /** + * Returns `true` if the `fs.Dirent` object describes a file system + * directory. + * @since v10.10.0 + */ + isDirectory(): boolean; + /** + * Returns `true` if the `fs.Dirent` object describes a block device. + * @since v10.10.0 + */ + isBlockDevice(): boolean; + /** + * Returns `true` if the `fs.Dirent` object describes a character device. + * @since v10.10.0 + */ + isCharacterDevice(): boolean; + /** + * Returns `true` if the `fs.Dirent` object describes a symbolic link. + * @since v10.10.0 + */ + isSymbolicLink(): boolean; + /** + * Returns `true` if the `fs.Dirent` object describes a first-in-first-out + * (FIFO) pipe. + * @since v10.10.0 + */ + isFIFO(): boolean; + /** + * Returns `true` if the `fs.Dirent` object describes a socket. + * @since v10.10.0 + */ + isSocket(): boolean; + /** + * The file name that this `fs.Dirent` object refers to. The type of this + * value is determined by the `options.encoding` passed to {@link readdir} or {@link readdirSync}. + * @since v10.10.0 + */ + name: string; + } + /** + * A class representing a directory stream. + * + * Created by {@link opendir}, {@link opendirSync}, or `fsPromises.opendir()`. + * + * ```js + * import { opendir } from 'fs/promises'; + * + * try { + * const dir = await opendir('./'); + * for await (const dirent of dir) + * console.log(dirent.name); + * } catch (err) { + * console.error(err); + * } + * ``` + * + * When using the async iterator, the `fs.Dir` object will be automatically + * closed after the iterator exits. + * @since v12.12.0 + */ + export class Dir implements AsyncIterable { + /** + * The read-only path of this directory as was provided to {@link opendir},{@link opendirSync}, or `fsPromises.opendir()`. + * @since v12.12.0 + */ + readonly path: string; + /** + * Asynchronously iterates over the directory via `readdir(3)` until all entries have been read. + */ + [Symbol.asyncIterator](): AsyncIterableIterator; + /** + * Asynchronously close the directory's underlying resource handle. + * Subsequent reads will result in errors. + * + * A promise is returned that will be resolved after the resource has been + * closed. + * @since v12.12.0 + */ + close(): Promise; + close(cb: NoParamCallback): void; + /** + * Synchronously close the directory's underlying resource handle. + * Subsequent reads will result in errors. + * @since v12.12.0 + */ + closeSync(): void; + /** + * Asynchronously read the next directory entry via [`readdir(3)`](http://man7.org/linux/man-pages/man3/readdir.3.html) as an `fs.Dirent`. + * + * A promise is returned that will be resolved with an `fs.Dirent`, or `null`if there are no more directory entries to read. + * + * Directory entries returned by this function are in no particular order as + * provided by the operating system's underlying directory mechanisms. + * Entries added or removed while iterating over the directory might not be + * included in the iteration results. + * @since v12.12.0 + * @return containing {fs.Dirent|null} + */ + read(): Promise; + read(cb: (err: NodeJS.ErrnoException | null, dirEnt: Dirent | null) => void): void; + /** + * Synchronously read the next directory entry as an `fs.Dirent`. See the + * POSIX [`readdir(3)`](http://man7.org/linux/man-pages/man3/readdir.3.html) documentation for more detail. + * + * If there are no more directory entries to read, `null` will be returned. + * + * Directory entries returned by this function are in no particular order as + * provided by the operating system's underlying directory mechanisms. + * Entries added or removed while iterating over the directory might not be + * included in the iteration results. + * @since v12.12.0 + */ + readSync(): Dirent | null; + } + /** + * Class: fs.StatWatcher + * @since v14.3.0, v12.20.0 + * Extends `EventEmitter` + * A successful call to {@link watchFile} method will return a new fs.StatWatcher object. + */ + export interface StatWatcher extends EventEmitter { + /** + * When called, requests that the Node.js event loop _not_ exit so long as the `fs.StatWatcher` is active. Calling `watcher.ref()` multiple times will have + * no effect. + * + * By default, all `fs.StatWatcher` objects are "ref'ed", making it normally + * unnecessary to call `watcher.ref()` unless `watcher.unref()` had been + * called previously. + * @since v14.3.0, v12.20.0 + */ + ref(): this; + /** + * When called, the active `fs.StatWatcher` object will not require the Node.js + * event loop to remain active. If there is no other activity keeping the + * event loop running, the process may exit before the `fs.StatWatcher` object's + * callback is invoked. Calling `watcher.unref()` multiple times will have + * no effect. + * @since v14.3.0, v12.20.0 + */ + unref(): this; + } + export interface FSWatcher extends EventEmitter { + /** + * Stop watching for changes on the given `fs.FSWatcher`. Once stopped, the `fs.FSWatcher` object is no longer usable. + * @since v0.5.8 + */ + close(): void; + /** + * events.EventEmitter + * 1. change + * 2. error + */ + addListener(event: string, listener: (...args: any[]) => void): this; + addListener(event: 'change', listener: (eventType: string, filename: string | Buffer) => void): this; + addListener(event: 'error', listener: (error: Error) => void): this; + addListener(event: 'close', listener: () => void): this; + on(event: string, listener: (...args: any[]) => void): this; + on(event: 'change', listener: (eventType: string, filename: string | Buffer) => void): this; + on(event: 'error', listener: (error: Error) => void): this; + on(event: 'close', listener: () => void): this; + once(event: string, listener: (...args: any[]) => void): this; + once(event: 'change', listener: (eventType: string, filename: string | Buffer) => void): this; + once(event: 'error', listener: (error: Error) => void): this; + once(event: 'close', listener: () => void): this; + prependListener(event: string, listener: (...args: any[]) => void): this; + prependListener(event: 'change', listener: (eventType: string, filename: string | Buffer) => void): this; + prependListener(event: 'error', listener: (error: Error) => void): this; + prependListener(event: 'close', listener: () => void): this; + prependOnceListener(event: string, listener: (...args: any[]) => void): this; + prependOnceListener(event: 'change', listener: (eventType: string, filename: string | Buffer) => void): this; + prependOnceListener(event: 'error', listener: (error: Error) => void): this; + prependOnceListener(event: 'close', listener: () => void): this; + } + /** + * Instances of `fs.ReadStream` are created and returned using the {@link createReadStream} function. + * @since v0.1.93 + */ + export class ReadStream extends stream.Readable { + close(callback?: (err?: NodeJS.ErrnoException | null) => void): void; + /** + * The number of bytes that have been read so far. + * @since v6.4.0 + */ + bytesRead: number; + /** + * The path to the file the stream is reading from as specified in the first + * argument to `fs.createReadStream()`. If `path` is passed as a string, then`readStream.path` will be a string. If `path` is passed as a `Buffer`, then`readStream.path` will be a + * `Buffer`. If `fd` is specified, then`readStream.path` will be `undefined`. + * @since v0.1.93 + */ + path: string | Buffer; + /** + * This property is `true` if the underlying file has not been opened yet, + * i.e. before the `'ready'` event is emitted. + * @since v11.2.0, v10.16.0 + */ + pending: boolean; + /** + * events.EventEmitter + * 1. open + * 2. close + * 3. ready + */ + addListener(event: 'close', listener: () => void): this; + addListener(event: 'data', listener: (chunk: Buffer | string) => void): this; + addListener(event: 'end', listener: () => void): this; + addListener(event: 'error', listener: (err: Error) => void): this; + addListener(event: 'open', listener: (fd: number) => void): this; + addListener(event: 'pause', listener: () => void): this; + addListener(event: 'readable', listener: () => void): this; + addListener(event: 'ready', listener: () => void): this; + addListener(event: 'resume', listener: () => void): this; + addListener(event: string | symbol, listener: (...args: any[]) => void): this; + on(event: 'close', listener: () => void): this; + on(event: 'data', listener: (chunk: Buffer | string) => void): this; + on(event: 'end', listener: () => void): this; + on(event: 'error', listener: (err: Error) => void): this; + on(event: 'open', listener: (fd: number) => void): this; + on(event: 'pause', listener: () => void): this; + on(event: 'readable', listener: () => void): this; + on(event: 'ready', listener: () => void): this; + on(event: 'resume', listener: () => void): this; + on(event: string | symbol, listener: (...args: any[]) => void): this; + once(event: 'close', listener: () => void): this; + once(event: 'data', listener: (chunk: Buffer | string) => void): this; + once(event: 'end', listener: () => void): this; + once(event: 'error', listener: (err: Error) => void): this; + once(event: 'open', listener: (fd: number) => void): this; + once(event: 'pause', listener: () => void): this; + once(event: 'readable', listener: () => void): this; + once(event: 'ready', listener: () => void): this; + once(event: 'resume', listener: () => void): this; + once(event: string | symbol, listener: (...args: any[]) => void): this; + prependListener(event: 'close', listener: () => void): this; + prependListener(event: 'data', listener: (chunk: Buffer | string) => void): this; + prependListener(event: 'end', listener: () => void): this; + prependListener(event: 'error', listener: (err: Error) => void): this; + prependListener(event: 'open', listener: (fd: number) => void): this; + prependListener(event: 'pause', listener: () => void): this; + prependListener(event: 'readable', listener: () => void): this; + prependListener(event: 'ready', listener: () => void): this; + prependListener(event: 'resume', listener: () => void): this; + prependListener(event: string | symbol, listener: (...args: any[]) => void): this; + prependOnceListener(event: 'close', listener: () => void): this; + prependOnceListener(event: 'data', listener: (chunk: Buffer | string) => void): this; + prependOnceListener(event: 'end', listener: () => void): this; + prependOnceListener(event: 'error', listener: (err: Error) => void): this; + prependOnceListener(event: 'open', listener: (fd: number) => void): this; + prependOnceListener(event: 'pause', listener: () => void): this; + prependOnceListener(event: 'readable', listener: () => void): this; + prependOnceListener(event: 'ready', listener: () => void): this; + prependOnceListener(event: 'resume', listener: () => void): this; + prependOnceListener(event: string | symbol, listener: (...args: any[]) => void): this; + } + /** + * * Extends `stream.Writable` + * + * Instances of `fs.WriteStream` are created and returned using the {@link createWriteStream} function. + * @since v0.1.93 + */ + export class WriteStream extends stream.Writable { + /** + * Closes `writeStream`. Optionally accepts a + * callback that will be executed once the `writeStream`is closed. + * @since v0.9.4 + */ + close(callback?: (err?: NodeJS.ErrnoException | null) => void): void; + /** + * The number of bytes written so far. Does not include data that is still queued + * for writing. + * @since v0.4.7 + */ + bytesWritten: number; + /** + * The path to the file the stream is writing to as specified in the first + * argument to {@link createWriteStream}. If `path` is passed as a string, then`writeStream.path` will be a string. If `path` is passed as a `Buffer`, then`writeStream.path` will be a + * `Buffer`. + * @since v0.1.93 + */ + path: string | Buffer; + /** + * This property is `true` if the underlying file has not been opened yet, + * i.e. before the `'ready'` event is emitted. + * @since v11.2.0 + */ + pending: boolean; + /** + * events.EventEmitter + * 1. open + * 2. close + * 3. ready + */ + addListener(event: 'close', listener: () => void): this; + addListener(event: 'drain', listener: () => void): this; + addListener(event: 'error', listener: (err: Error) => void): this; + addListener(event: 'finish', listener: () => void): this; + addListener(event: 'open', listener: (fd: number) => void): this; + addListener(event: 'pipe', listener: (src: stream.Readable) => void): this; + addListener(event: 'ready', listener: () => void): this; + addListener(event: 'unpipe', listener: (src: stream.Readable) => void): this; + addListener(event: string | symbol, listener: (...args: any[]) => void): this; + on(event: 'close', listener: () => void): this; + on(event: 'drain', listener: () => void): this; + on(event: 'error', listener: (err: Error) => void): this; + on(event: 'finish', listener: () => void): this; + on(event: 'open', listener: (fd: number) => void): this; + on(event: 'pipe', listener: (src: stream.Readable) => void): this; + on(event: 'ready', listener: () => void): this; + on(event: 'unpipe', listener: (src: stream.Readable) => void): this; + on(event: string | symbol, listener: (...args: any[]) => void): this; + once(event: 'close', listener: () => void): this; + once(event: 'drain', listener: () => void): this; + once(event: 'error', listener: (err: Error) => void): this; + once(event: 'finish', listener: () => void): this; + once(event: 'open', listener: (fd: number) => void): this; + once(event: 'pipe', listener: (src: stream.Readable) => void): this; + once(event: 'ready', listener: () => void): this; + once(event: 'unpipe', listener: (src: stream.Readable) => void): this; + once(event: string | symbol, listener: (...args: any[]) => void): this; + prependListener(event: 'close', listener: () => void): this; + prependListener(event: 'drain', listener: () => void): this; + prependListener(event: 'error', listener: (err: Error) => void): this; + prependListener(event: 'finish', listener: () => void): this; + prependListener(event: 'open', listener: (fd: number) => void): this; + prependListener(event: 'pipe', listener: (src: stream.Readable) => void): this; + prependListener(event: 'ready', listener: () => void): this; + prependListener(event: 'unpipe', listener: (src: stream.Readable) => void): this; + prependListener(event: string | symbol, listener: (...args: any[]) => void): this; + prependOnceListener(event: 'close', listener: () => void): this; + prependOnceListener(event: 'drain', listener: () => void): this; + prependOnceListener(event: 'error', listener: (err: Error) => void): this; + prependOnceListener(event: 'finish', listener: () => void): this; + prependOnceListener(event: 'open', listener: (fd: number) => void): this; + prependOnceListener(event: 'pipe', listener: (src: stream.Readable) => void): this; + prependOnceListener(event: 'ready', listener: () => void): this; + prependOnceListener(event: 'unpipe', listener: (src: stream.Readable) => void): this; + prependOnceListener(event: string | symbol, listener: (...args: any[]) => void): this; + } + /** + * Asynchronously rename file at `oldPath` to the pathname provided + * as `newPath`. In the case that `newPath` already exists, it will + * be overwritten. If there is a directory at `newPath`, an error will + * be raised instead. No arguments other than a possible exception are + * given to the completion callback. + * + * See also: [`rename(2)`](http://man7.org/linux/man-pages/man2/rename.2.html). + * + * ```js + * import { rename } from 'fs'; + * + * rename('oldFile.txt', 'newFile.txt', (err) => { + * if (err) throw err; + * console.log('Rename complete!'); + * }); + * ``` + * @since v0.0.2 + */ + export function rename(oldPath: PathLike, newPath: PathLike, callback: NoParamCallback): void; + export namespace rename { + /** + * Asynchronous rename(2) - Change the name or location of a file or directory. + * @param oldPath A path to a file. If a URL is provided, it must use the `file:` protocol. + * URL support is _experimental_. + * @param newPath A path to a file. If a URL is provided, it must use the `file:` protocol. + * URL support is _experimental_. + */ + function __promisify__(oldPath: PathLike, newPath: PathLike): Promise; + } + /** + * Renames the file from `oldPath` to `newPath`. Returns `undefined`. + * + * See the POSIX [`rename(2)`](http://man7.org/linux/man-pages/man2/rename.2.html) documentation for more details. + * @since v0.1.21 + */ + export function renameSync(oldPath: PathLike, newPath: PathLike): void; + /** + * Truncates the file. No arguments other than a possible exception are + * given to the completion callback. A file descriptor can also be passed as the + * first argument. In this case, `fs.ftruncate()` is called. + * + * ```js + * import { truncate } from 'fs'; + * // Assuming that 'path/file.txt' is a regular file. + * truncate('path/file.txt', (err) => { + * if (err) throw err; + * console.log('path/file.txt was truncated'); + * }); + * ``` + * + * Passing a file descriptor is deprecated and may result in an error being thrown + * in the future. + * + * See the POSIX [`truncate(2)`](http://man7.org/linux/man-pages/man2/truncate.2.html) documentation for more details. + * @since v0.8.6 + * @param [len=0] + */ + export function truncate(path: PathLike, len: number | undefined | null, callback: NoParamCallback): void; + /** + * Asynchronous truncate(2) - Truncate a file to a specified length. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + */ + export function truncate(path: PathLike, callback: NoParamCallback): void; + export namespace truncate { + /** + * Asynchronous truncate(2) - Truncate a file to a specified length. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param len If not specified, defaults to `0`. + */ + function __promisify__(path: PathLike, len?: number | null): Promise; + } + /** + * Truncates the file. Returns `undefined`. A file descriptor can also be + * passed as the first argument. In this case, `fs.ftruncateSync()` is called. + * + * Passing a file descriptor is deprecated and may result in an error being thrown + * in the future. + * @since v0.8.6 + * @param [len=0] + */ + export function truncateSync(path: PathLike, len?: number | null): void; + /** + * Truncates the file descriptor. No arguments other than a possible exception are + * given to the completion callback. + * + * See the POSIX [`ftruncate(2)`](http://man7.org/linux/man-pages/man2/ftruncate.2.html) documentation for more detail. + * + * If the file referred to by the file descriptor was larger than `len` bytes, only + * the first `len` bytes will be retained in the file. + * + * For example, the following program retains only the first four bytes of the + * file: + * + * ```js + * import { open, close, ftruncate } from 'fs'; + * + * function closeFd(fd) { + * close(fd, (err) => { + * if (err) throw err; + * }); + * } + * + * open('temp.txt', 'r+', (err, fd) => { + * if (err) throw err; + * + * try { + * ftruncate(fd, 4, (err) => { + * closeFd(fd); + * if (err) throw err; + * }); + * } catch (err) { + * closeFd(fd); + * if (err) throw err; + * } + * }); + * ``` + * + * If the file previously was shorter than `len` bytes, it is extended, and the + * extended part is filled with null bytes (`'\0'`): + * + * If `len` is negative then `0` will be used. + * @since v0.8.6 + * @param [len=0] + */ + export function ftruncate(fd: number, len: number | undefined | null, callback: NoParamCallback): void; + /** + * Asynchronous ftruncate(2) - Truncate a file to a specified length. + * @param fd A file descriptor. + */ + export function ftruncate(fd: number, callback: NoParamCallback): void; + export namespace ftruncate { + /** + * Asynchronous ftruncate(2) - Truncate a file to a specified length. + * @param fd A file descriptor. + * @param len If not specified, defaults to `0`. + */ + function __promisify__(fd: number, len?: number | null): Promise; + } + /** + * Truncates the file descriptor. Returns `undefined`. + * + * For detailed information, see the documentation of the asynchronous version of + * this API: {@link ftruncate}. + * @since v0.8.6 + * @param [len=0] + */ + export function ftruncateSync(fd: number, len?: number | null): void; + /** + * Asynchronously changes owner and group of a file. No arguments other than a + * possible exception are given to the completion callback. + * + * See the POSIX [`chown(2)`](http://man7.org/linux/man-pages/man2/chown.2.html) documentation for more detail. + * @since v0.1.97 + */ + export function chown(path: PathLike, uid: number, gid: number, callback: NoParamCallback): void; + export namespace chown { + /** + * Asynchronous chown(2) - Change ownership of a file. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + */ + function __promisify__(path: PathLike, uid: number, gid: number): Promise; + } + /** + * Synchronously changes owner and group of a file. Returns `undefined`. + * This is the synchronous version of {@link chown}. + * + * See the POSIX [`chown(2)`](http://man7.org/linux/man-pages/man2/chown.2.html) documentation for more detail. + * @since v0.1.97 + */ + export function chownSync(path: PathLike, uid: number, gid: number): void; + /** + * Sets the owner of the file. No arguments other than a possible exception are + * given to the completion callback. + * + * See the POSIX [`fchown(2)`](http://man7.org/linux/man-pages/man2/fchown.2.html) documentation for more detail. + * @since v0.4.7 + */ + export function fchown(fd: number, uid: number, gid: number, callback: NoParamCallback): void; + export namespace fchown { + /** + * Asynchronous fchown(2) - Change ownership of a file. + * @param fd A file descriptor. + */ + function __promisify__(fd: number, uid: number, gid: number): Promise; + } + /** + * Sets the owner of the file. Returns `undefined`. + * + * See the POSIX [`fchown(2)`](http://man7.org/linux/man-pages/man2/fchown.2.html) documentation for more detail. + * @since v0.4.7 + * @param uid The file's new owner's user id. + * @param gid The file's new group's group id. + */ + export function fchownSync(fd: number, uid: number, gid: number): void; + /** + * Set the owner of the symbolic link. No arguments other than a possible + * exception are given to the completion callback. + * + * See the POSIX [`lchown(2)`](http://man7.org/linux/man-pages/man2/lchown.2.html) documentation for more detail. + */ + export function lchown(path: PathLike, uid: number, gid: number, callback: NoParamCallback): void; + export namespace lchown { + /** + * Asynchronous lchown(2) - Change ownership of a file. Does not dereference symbolic links. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + */ + function __promisify__(path: PathLike, uid: number, gid: number): Promise; + } + /** + * Set the owner for the path. Returns `undefined`. + * + * See the POSIX [`lchown(2)`](http://man7.org/linux/man-pages/man2/lchown.2.html) documentation for more details. + * @param uid The file's new owner's user id. + * @param gid The file's new group's group id. + */ + export function lchownSync(path: PathLike, uid: number, gid: number): void; + /** + * Changes the access and modification times of a file in the same way as {@link utimes}, with the difference that if the path refers to a symbolic + * link, then the link is not dereferenced: instead, the timestamps of the + * symbolic link itself are changed. + * + * No arguments other than a possible exception are given to the completion + * callback. + * @since v14.5.0, v12.19.0 + */ + export function lutimes(path: PathLike, atime: TimeLike, mtime: TimeLike, callback: NoParamCallback): void; + export namespace lutimes { + /** + * Changes the access and modification times of a file in the same way as `fsPromises.utimes()`, + * with the difference that if the path refers to a symbolic link, then the link is not + * dereferenced: instead, the timestamps of the symbolic link itself are changed. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param atime The last access time. If a string is provided, it will be coerced to number. + * @param mtime The last modified time. If a string is provided, it will be coerced to number. + */ + function __promisify__(path: PathLike, atime: TimeLike, mtime: TimeLike): Promise; + } + /** + * Change the file system timestamps of the symbolic link referenced by `path`. + * Returns `undefined`, or throws an exception when parameters are incorrect or + * the operation fails. This is the synchronous version of {@link lutimes}. + * @since v14.5.0, v12.19.0 + */ + export function lutimesSync(path: PathLike, atime: TimeLike, mtime: TimeLike): void; + /** + * Asynchronously changes the permissions of a file. No arguments other than a + * possible exception are given to the completion callback. + * + * See the POSIX [`chmod(2)`](http://man7.org/linux/man-pages/man2/chmod.2.html) documentation for more detail. + * + * ```js + * import { chmod } from 'fs'; + * + * chmod('my_file.txt', 0o775, (err) => { + * if (err) throw err; + * console.log('The permissions for file "my_file.txt" have been changed!'); + * }); + * ``` + * @since v0.1.30 + */ + export function chmod(path: PathLike, mode: Mode, callback: NoParamCallback): void; + export namespace chmod { + /** + * Asynchronous chmod(2) - Change permissions of a file. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param mode A file mode. If a string is passed, it is parsed as an octal integer. + */ + function __promisify__(path: PathLike, mode: Mode): Promise; + } + /** + * For detailed information, see the documentation of the asynchronous version of + * this API: {@link chmod}. + * + * See the POSIX [`chmod(2)`](http://man7.org/linux/man-pages/man2/chmod.2.html) documentation for more detail. + * @since v0.6.7 + */ + export function chmodSync(path: PathLike, mode: Mode): void; + /** + * Sets the permissions on the file. No arguments other than a possible exception + * are given to the completion callback. + * + * See the POSIX [`fchmod(2)`](http://man7.org/linux/man-pages/man2/fchmod.2.html) documentation for more detail. + * @since v0.4.7 + */ + export function fchmod(fd: number, mode: Mode, callback: NoParamCallback): void; + export namespace fchmod { + /** + * Asynchronous fchmod(2) - Change permissions of a file. + * @param fd A file descriptor. + * @param mode A file mode. If a string is passed, it is parsed as an octal integer. + */ + function __promisify__(fd: number, mode: Mode): Promise; + } + /** + * Sets the permissions on the file. Returns `undefined`. + * + * See the POSIX [`fchmod(2)`](http://man7.org/linux/man-pages/man2/fchmod.2.html) documentation for more detail. + * @since v0.4.7 + */ + export function fchmodSync(fd: number, mode: Mode): void; + /** + * Changes the permissions on a symbolic link. No arguments other than a possible + * exception are given to the completion callback. + * + * This method is only implemented on macOS. + * + * See the POSIX [`lchmod(2)`](https://www.freebsd.org/cgi/man.cgi?query=lchmod&sektion=2) documentation for more detail. + * @deprecated Since v0.4.7 + */ + export function lchmod(path: PathLike, mode: Mode, callback: NoParamCallback): void; + /** @deprecated */ + export namespace lchmod { + /** + * Asynchronous lchmod(2) - Change permissions of a file. Does not dereference symbolic links. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param mode A file mode. If a string is passed, it is parsed as an octal integer. + */ + function __promisify__(path: PathLike, mode: Mode): Promise; + } + /** + * Changes the permissions on a symbolic link. Returns `undefined`. + * + * This method is only implemented on macOS. + * + * See the POSIX [`lchmod(2)`](https://www.freebsd.org/cgi/man.cgi?query=lchmod&sektion=2) documentation for more detail. + * @deprecated Since v0.4.7 + */ + export function lchmodSync(path: PathLike, mode: Mode): void; + /** + * Asynchronous [`stat(2)`](http://man7.org/linux/man-pages/man2/stat.2.html). The callback gets two arguments `(err, stats)` where`stats` is an `fs.Stats` object. + * + * In case of an error, the `err.code` will be one of `Common System Errors`. + * + * Using `fs.stat()` to check for the existence of a file before calling`fs.open()`, `fs.readFile()` or `fs.writeFile()` is not recommended. + * Instead, user code should open/read/write the file directly and handle the + * error raised if the file is not available. + * + * To check if a file exists without manipulating it afterwards, {@link access} is recommended. + * + * For example, given the following directory structure: + * + * ```text + * - txtDir + * -- file.txt + * - app.js + * ``` + * + * The next program will check for the stats of the given paths: + * + * ```js + * import { stat } from 'fs'; + * + * const pathsToCheck = ['./txtDir', './txtDir/file.txt']; + * + * for (let i = 0; i < pathsToCheck.length; i++) { + * stat(pathsToCheck[i], (err, stats) => { + * console.log(stats.isDirectory()); + * console.log(stats); + * }); + * } + * ``` + * + * The resulting output will resemble: + * + * ```console + * true + * Stats { + * dev: 16777220, + * mode: 16877, + * nlink: 3, + * uid: 501, + * gid: 20, + * rdev: 0, + * blksize: 4096, + * ino: 14214262, + * size: 96, + * blocks: 0, + * atimeMs: 1561174653071.963, + * mtimeMs: 1561174614583.3518, + * ctimeMs: 1561174626623.5366, + * birthtimeMs: 1561174126937.2893, + * atime: 2019-06-22T03:37:33.072Z, + * mtime: 2019-06-22T03:36:54.583Z, + * ctime: 2019-06-22T03:37:06.624Z, + * birthtime: 2019-06-22T03:28:46.937Z + * } + * false + * Stats { + * dev: 16777220, + * mode: 33188, + * nlink: 1, + * uid: 501, + * gid: 20, + * rdev: 0, + * blksize: 4096, + * ino: 14214074, + * size: 8, + * blocks: 8, + * atimeMs: 1561174616618.8555, + * mtimeMs: 1561174614584, + * ctimeMs: 1561174614583.8145, + * birthtimeMs: 1561174007710.7478, + * atime: 2019-06-22T03:36:56.619Z, + * mtime: 2019-06-22T03:36:54.584Z, + * ctime: 2019-06-22T03:36:54.584Z, + * birthtime: 2019-06-22T03:26:47.711Z + * } + * ``` + * @since v0.0.2 + */ + export function stat(path: PathLike, callback: (err: NodeJS.ErrnoException | null, stats: Stats) => void): void; + export function stat( + path: PathLike, + options: + | (StatOptions & { + bigint?: false | undefined; + }) + | undefined, + callback: (err: NodeJS.ErrnoException | null, stats: Stats) => void + ): void; + export function stat( + path: PathLike, + options: StatOptions & { + bigint: true; + }, + callback: (err: NodeJS.ErrnoException | null, stats: BigIntStats) => void + ): void; + export function stat(path: PathLike, options: StatOptions | undefined, callback: (err: NodeJS.ErrnoException | null, stats: Stats | BigIntStats) => void): void; + export namespace stat { + /** + * Asynchronous stat(2) - Get file status. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + */ + function __promisify__( + path: PathLike, + options?: StatOptions & { + bigint?: false | undefined; + } + ): Promise; + function __promisify__( + path: PathLike, + options: StatOptions & { + bigint: true; + } + ): Promise; + function __promisify__(path: PathLike, options?: StatOptions): Promise; + } + export interface StatSyncFn extends Function { + (path: PathLike, options?: undefined): Stats; + ( + path: PathLike, + options?: StatSyncOptions & { + bigint?: false | undefined; + throwIfNoEntry: false; + } + ): Stats | undefined; + ( + path: PathLike, + options: StatSyncOptions & { + bigint: true; + throwIfNoEntry: false; + } + ): BigIntStats | undefined; + ( + path: PathLike, + options?: StatSyncOptions & { + bigint?: false | undefined; + } + ): Stats; + ( + path: PathLike, + options: StatSyncOptions & { + bigint: true; + } + ): BigIntStats; + ( + path: PathLike, + options: StatSyncOptions & { + bigint: boolean; + throwIfNoEntry?: false | undefined; + } + ): Stats | BigIntStats; + (path: PathLike, options?: StatSyncOptions): Stats | BigIntStats | undefined; + } + /** + * Synchronous stat(2) - Get file status. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + */ + export const statSync: StatSyncFn; + /** + * Invokes the callback with the `fs.Stats` for the file descriptor. + * + * See the POSIX [`fstat(2)`](http://man7.org/linux/man-pages/man2/fstat.2.html) documentation for more detail. + * @since v0.1.95 + */ + export function fstat(fd: number, callback: (err: NodeJS.ErrnoException | null, stats: Stats) => void): void; + export function fstat( + fd: number, + options: + | (StatOptions & { + bigint?: false | undefined; + }) + | undefined, + callback: (err: NodeJS.ErrnoException | null, stats: Stats) => void + ): void; + export function fstat( + fd: number, + options: StatOptions & { + bigint: true; + }, + callback: (err: NodeJS.ErrnoException | null, stats: BigIntStats) => void + ): void; + export function fstat(fd: number, options: StatOptions | undefined, callback: (err: NodeJS.ErrnoException | null, stats: Stats | BigIntStats) => void): void; + export namespace fstat { + /** + * Asynchronous fstat(2) - Get file status. + * @param fd A file descriptor. + */ + function __promisify__( + fd: number, + options?: StatOptions & { + bigint?: false | undefined; + } + ): Promise; + function __promisify__( + fd: number, + options: StatOptions & { + bigint: true; + } + ): Promise; + function __promisify__(fd: number, options?: StatOptions): Promise; + } + /** + * Retrieves the `fs.Stats` for the file descriptor. + * + * See the POSIX [`fstat(2)`](http://man7.org/linux/man-pages/man2/fstat.2.html) documentation for more detail. + * @since v0.1.95 + */ + export function fstatSync( + fd: number, + options?: StatOptions & { + bigint?: false | undefined; + } + ): Stats; + export function fstatSync( + fd: number, + options: StatOptions & { + bigint: true; + } + ): BigIntStats; + export function fstatSync(fd: number, options?: StatOptions): Stats | BigIntStats; + /** + * Retrieves the `fs.Stats` for the symbolic link referred to by the path. + * The callback gets two arguments `(err, stats)` where `stats` is a `fs.Stats` object. `lstat()` is identical to `stat()`, except that if `path` is a symbolic + * link, then the link itself is stat-ed, not the file that it refers to. + * + * See the POSIX [`lstat(2)`](http://man7.org/linux/man-pages/man2/lstat.2.html) documentation for more details. + * @since v0.1.30 + */ + export function lstat(path: PathLike, callback: (err: NodeJS.ErrnoException | null, stats: Stats) => void): void; + export function lstat( + path: PathLike, + options: + | (StatOptions & { + bigint?: false | undefined; + }) + | undefined, + callback: (err: NodeJS.ErrnoException | null, stats: Stats) => void + ): void; + export function lstat( + path: PathLike, + options: StatOptions & { + bigint: true; + }, + callback: (err: NodeJS.ErrnoException | null, stats: BigIntStats) => void + ): void; + export function lstat(path: PathLike, options: StatOptions | undefined, callback: (err: NodeJS.ErrnoException | null, stats: Stats | BigIntStats) => void): void; + export namespace lstat { + /** + * Asynchronous lstat(2) - Get file status. Does not dereference symbolic links. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + */ + function __promisify__( + path: PathLike, + options?: StatOptions & { + bigint?: false | undefined; + } + ): Promise; + function __promisify__( + path: PathLike, + options: StatOptions & { + bigint: true; + } + ): Promise; + function __promisify__(path: PathLike, options?: StatOptions): Promise; + } + /** + * Synchronous lstat(2) - Get file status. Does not dereference symbolic links. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + */ + export const lstatSync: StatSyncFn; + /** + * Creates a new link from the `existingPath` to the `newPath`. See the POSIX [`link(2)`](http://man7.org/linux/man-pages/man2/link.2.html) documentation for more detail. No arguments other than + * a possible + * exception are given to the completion callback. + * @since v0.1.31 + */ + export function link(existingPath: PathLike, newPath: PathLike, callback: NoParamCallback): void; + export namespace link { + /** + * Asynchronous link(2) - Create a new link (also known as a hard link) to an existing file. + * @param existingPath A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param newPath A path to a file. If a URL is provided, it must use the `file:` protocol. + */ + function __promisify__(existingPath: PathLike, newPath: PathLike): Promise; + } + /** + * Creates a new link from the `existingPath` to the `newPath`. See the POSIX [`link(2)`](http://man7.org/linux/man-pages/man2/link.2.html) documentation for more detail. Returns `undefined`. + * @since v0.1.31 + */ + export function linkSync(existingPath: PathLike, newPath: PathLike): void; + /** + * Creates the link called `path` pointing to `target`. No arguments other than a + * possible exception are given to the completion callback. + * + * See the POSIX [`symlink(2)`](http://man7.org/linux/man-pages/man2/symlink.2.html) documentation for more details. + * + * The `type` argument is only available on Windows and ignored on other platforms. + * It can be set to `'dir'`, `'file'`, or `'junction'`. If the `type` argument is + * not set, Node.js will autodetect `target` type and use `'file'` or `'dir'`. If + * the `target` does not exist, `'file'` will be used. Windows junction points + * require the destination path to be absolute. When using `'junction'`, the`target` argument will automatically be normalized to absolute path. + * + * Relative targets are relative to the link’s parent directory. + * + * ```js + * import { symlink } from 'fs'; + * + * symlink('./mew', './mewtwo', callback); + * ``` + * + * The above example creates a symbolic link `mewtwo` which points to `mew` in the + * same directory: + * + * ```bash + * $ tree . + * . + * ├── mew + * └── mewtwo -> ./mew + * ``` + * @since v0.1.31 + */ + export function symlink(target: PathLike, path: PathLike, type: symlink.Type | undefined | null, callback: NoParamCallback): void; + /** + * Asynchronous symlink(2) - Create a new symbolic link to an existing file. + * @param target A path to an existing file. If a URL is provided, it must use the `file:` protocol. + * @param path A path to the new symlink. If a URL is provided, it must use the `file:` protocol. + */ + export function symlink(target: PathLike, path: PathLike, callback: NoParamCallback): void; + export namespace symlink { + /** + * Asynchronous symlink(2) - Create a new symbolic link to an existing file. + * @param target A path to an existing file. If a URL is provided, it must use the `file:` protocol. + * @param path A path to the new symlink. If a URL is provided, it must use the `file:` protocol. + * @param type May be set to `'dir'`, `'file'`, or `'junction'` (default is `'file'`) and is only available on Windows (ignored on other platforms). + * When using `'junction'`, the `target` argument will automatically be normalized to an absolute path. + */ + function __promisify__(target: PathLike, path: PathLike, type?: string | null): Promise; + type Type = 'dir' | 'file' | 'junction'; + } + /** + * Returns `undefined`. + * + * For detailed information, see the documentation of the asynchronous version of + * this API: {@link symlink}. + * @since v0.1.31 + */ + export function symlinkSync(target: PathLike, path: PathLike, type?: symlink.Type | null): void; + /** + * Reads the contents of the symbolic link referred to by `path`. The callback gets + * two arguments `(err, linkString)`. + * + * See the POSIX [`readlink(2)`](http://man7.org/linux/man-pages/man2/readlink.2.html) documentation for more details. + * + * The optional `options` argument can be a string specifying an encoding, or an + * object with an `encoding` property specifying the character encoding to use for + * the link path passed to the callback. If the `encoding` is set to `'buffer'`, + * the link path returned will be passed as a `Buffer` object. + * @since v0.1.31 + */ + export function readlink(path: PathLike, options: EncodingOption, callback: (err: NodeJS.ErrnoException | null, linkString: string) => void): void; + /** + * Asynchronous readlink(2) - read value of a symbolic link. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + export function readlink(path: PathLike, options: BufferEncodingOption, callback: (err: NodeJS.ErrnoException | null, linkString: Buffer) => void): void; + /** + * Asynchronous readlink(2) - read value of a symbolic link. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + export function readlink(path: PathLike, options: EncodingOption, callback: (err: NodeJS.ErrnoException | null, linkString: string | Buffer) => void): void; + /** + * Asynchronous readlink(2) - read value of a symbolic link. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + */ + export function readlink(path: PathLike, callback: (err: NodeJS.ErrnoException | null, linkString: string) => void): void; + export namespace readlink { + /** + * Asynchronous readlink(2) - read value of a symbolic link. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function __promisify__(path: PathLike, options?: EncodingOption): Promise; + /** + * Asynchronous readlink(2) - read value of a symbolic link. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function __promisify__(path: PathLike, options: BufferEncodingOption): Promise; + /** + * Asynchronous readlink(2) - read value of a symbolic link. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function __promisify__(path: PathLike, options?: EncodingOption): Promise; + } + /** + * Returns the symbolic link's string value. + * + * See the POSIX [`readlink(2)`](http://man7.org/linux/man-pages/man2/readlink.2.html) documentation for more details. + * + * The optional `options` argument can be a string specifying an encoding, or an + * object with an `encoding` property specifying the character encoding to use for + * the link path returned. If the `encoding` is set to `'buffer'`, + * the link path returned will be passed as a `Buffer` object. + * @since v0.1.31 + */ + export function readlinkSync(path: PathLike, options?: EncodingOption): string; + /** + * Synchronous readlink(2) - read value of a symbolic link. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + export function readlinkSync(path: PathLike, options: BufferEncodingOption): Buffer; + /** + * Synchronous readlink(2) - read value of a symbolic link. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + export function readlinkSync(path: PathLike, options?: EncodingOption): string | Buffer; + /** + * Asynchronously computes the canonical pathname by resolving `.`, `..` and + * symbolic links. + * + * A canonical pathname is not necessarily unique. Hard links and bind mounts can + * expose a file system entity through many pathnames. + * + * This function behaves like [`realpath(3)`](http://man7.org/linux/man-pages/man3/realpath.3.html), with some exceptions: + * + * 1. No case conversion is performed on case-insensitive file systems. + * 2. The maximum number of symbolic links is platform-independent and generally + * (much) higher than what the native [`realpath(3)`](http://man7.org/linux/man-pages/man3/realpath.3.html) implementation supports. + * + * The `callback` gets two arguments `(err, resolvedPath)`. May use `process.cwd`to resolve relative paths. + * + * Only paths that can be converted to UTF8 strings are supported. + * + * The optional `options` argument can be a string specifying an encoding, or an + * object with an `encoding` property specifying the character encoding to use for + * the path passed to the callback. If the `encoding` is set to `'buffer'`, + * the path returned will be passed as a `Buffer` object. + * + * If `path` resolves to a socket or a pipe, the function will return a system + * dependent name for that object. + * @since v0.1.31 + */ + export function realpath(path: PathLike, options: EncodingOption, callback: (err: NodeJS.ErrnoException | null, resolvedPath: string) => void): void; + /** + * Asynchronous realpath(3) - return the canonicalized absolute pathname. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + export function realpath(path: PathLike, options: BufferEncodingOption, callback: (err: NodeJS.ErrnoException | null, resolvedPath: Buffer) => void): void; + /** + * Asynchronous realpath(3) - return the canonicalized absolute pathname. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + export function realpath(path: PathLike, options: EncodingOption, callback: (err: NodeJS.ErrnoException | null, resolvedPath: string | Buffer) => void): void; + /** + * Asynchronous realpath(3) - return the canonicalized absolute pathname. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + */ + export function realpath(path: PathLike, callback: (err: NodeJS.ErrnoException | null, resolvedPath: string) => void): void; + export namespace realpath { + /** + * Asynchronous realpath(3) - return the canonicalized absolute pathname. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function __promisify__(path: PathLike, options?: EncodingOption): Promise; + /** + * Asynchronous realpath(3) - return the canonicalized absolute pathname. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function __promisify__(path: PathLike, options: BufferEncodingOption): Promise; + /** + * Asynchronous realpath(3) - return the canonicalized absolute pathname. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function __promisify__(path: PathLike, options?: EncodingOption): Promise; + /** + * Asynchronous [`realpath(3)`](http://man7.org/linux/man-pages/man3/realpath.3.html). + * + * The `callback` gets two arguments `(err, resolvedPath)`. + * + * Only paths that can be converted to UTF8 strings are supported. + * + * The optional `options` argument can be a string specifying an encoding, or an + * object with an `encoding` property specifying the character encoding to use for + * the path passed to the callback. If the `encoding` is set to `'buffer'`, + * the path returned will be passed as a `Buffer` object. + * + * On Linux, when Node.js is linked against musl libc, the procfs file system must + * be mounted on `/proc` in order for this function to work. Glibc does not have + * this restriction. + * @since v9.2.0 + */ + function native(path: PathLike, options: EncodingOption, callback: (err: NodeJS.ErrnoException | null, resolvedPath: string) => void): void; + function native(path: PathLike, options: BufferEncodingOption, callback: (err: NodeJS.ErrnoException | null, resolvedPath: Buffer) => void): void; + function native(path: PathLike, options: EncodingOption, callback: (err: NodeJS.ErrnoException | null, resolvedPath: string | Buffer) => void): void; + function native(path: PathLike, callback: (err: NodeJS.ErrnoException | null, resolvedPath: string) => void): void; + } + /** + * Returns the resolved pathname. + * + * For detailed information, see the documentation of the asynchronous version of + * this API: {@link realpath}. + * @since v0.1.31 + */ + export function realpathSync(path: PathLike, options?: EncodingOption): string; + /** + * Synchronous realpath(3) - return the canonicalized absolute pathname. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + export function realpathSync(path: PathLike, options: BufferEncodingOption): Buffer; + /** + * Synchronous realpath(3) - return the canonicalized absolute pathname. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + export function realpathSync(path: PathLike, options?: EncodingOption): string | Buffer; + export namespace realpathSync { + function native(path: PathLike, options?: EncodingOption): string; + function native(path: PathLike, options: BufferEncodingOption): Buffer; + function native(path: PathLike, options?: EncodingOption): string | Buffer; + } + /** + * Asynchronously removes a file or symbolic link. No arguments other than a + * possible exception are given to the completion callback. + * + * ```js + * import { unlink } from 'fs'; + * // Assuming that 'path/file.txt' is a regular file. + * unlink('path/file.txt', (err) => { + * if (err) throw err; + * console.log('path/file.txt was deleted'); + * }); + * ``` + * + * `fs.unlink()` will not work on a directory, empty or otherwise. To remove a + * directory, use {@link rmdir}. + * + * See the POSIX [`unlink(2)`](http://man7.org/linux/man-pages/man2/unlink.2.html) documentation for more details. + * @since v0.0.2 + */ + export function unlink(path: PathLike, callback: NoParamCallback): void; + export namespace unlink { + /** + * Asynchronous unlink(2) - delete a name and possibly the file it refers to. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + */ + function __promisify__(path: PathLike): Promise; + } + /** + * Synchronous [`unlink(2)`](http://man7.org/linux/man-pages/man2/unlink.2.html). Returns `undefined`. + * @since v0.1.21 + */ + export function unlinkSync(path: PathLike): void; + export interface RmDirOptions { + /** + * If an `EBUSY`, `EMFILE`, `ENFILE`, `ENOTEMPTY`, or + * `EPERM` error is encountered, Node.js will retry the operation with a linear + * backoff wait of `retryDelay` ms longer on each try. This option represents the + * number of retries. This option is ignored if the `recursive` option is not + * `true`. + * @default 0 + */ + maxRetries?: number | undefined; + /** + * @deprecated since v14.14.0 In future versions of Node.js and will trigger a warning + * `fs.rmdir(path, { recursive: true })` will throw if `path` does not exist or is a file. + * Use `fs.rm(path, { recursive: true, force: true })` instead. + * + * If `true`, perform a recursive directory removal. In + * recursive mode soperations are retried on failure. + * @default false + */ + recursive?: boolean | undefined; + /** + * The amount of time in milliseconds to wait between retries. + * This option is ignored if the `recursive` option is not `true`. + * @default 100 + */ + retryDelay?: number | undefined; + } + /** + * Asynchronous [`rmdir(2)`](http://man7.org/linux/man-pages/man2/rmdir.2.html). No arguments other than a possible exception are given + * to the completion callback. + * + * Using `fs.rmdir()` on a file (not a directory) results in an `ENOENT` error on + * Windows and an `ENOTDIR` error on POSIX. + * + * To get a behavior similar to the `rm -rf` Unix command, use {@link rm} with options `{ recursive: true, force: true }`. + * @since v0.0.2 + */ + export function rmdir(path: PathLike, callback: NoParamCallback): void; + export function rmdir(path: PathLike, options: RmDirOptions, callback: NoParamCallback): void; + export namespace rmdir { + /** + * Asynchronous rmdir(2) - delete a directory. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + */ + function __promisify__(path: PathLike, options?: RmDirOptions): Promise; + } + /** + * Synchronous [`rmdir(2)`](http://man7.org/linux/man-pages/man2/rmdir.2.html). Returns `undefined`. + * + * Using `fs.rmdirSync()` on a file (not a directory) results in an `ENOENT` error + * on Windows and an `ENOTDIR` error on POSIX. + * + * To get a behavior similar to the `rm -rf` Unix command, use {@link rmSync} with options `{ recursive: true, force: true }`. + * @since v0.1.21 + */ + export function rmdirSync(path: PathLike, options?: RmDirOptions): void; + export interface RmOptions { + /** + * When `true`, exceptions will be ignored if `path` does not exist. + * @default false + */ + force?: boolean | undefined; + /** + * If an `EBUSY`, `EMFILE`, `ENFILE`, `ENOTEMPTY`, or + * `EPERM` error is encountered, Node.js will retry the operation with a linear + * backoff wait of `retryDelay` ms longer on each try. This option represents the + * number of retries. This option is ignored if the `recursive` option is not + * `true`. + * @default 0 + */ + maxRetries?: number | undefined; + /** + * If `true`, perform a recursive directory removal. In + * recursive mode, operations are retried on failure. + * @default false + */ + recursive?: boolean | undefined; + /** + * The amount of time in milliseconds to wait between retries. + * This option is ignored if the `recursive` option is not `true`. + * @default 100 + */ + retryDelay?: number | undefined; + } + /** + * Asynchronously removes files and directories (modeled on the standard POSIX `rm`utility). No arguments other than a possible exception are given to the + * completion callback. + * @since v14.14.0 + */ + export function rm(path: PathLike, callback: NoParamCallback): void; + export function rm(path: PathLike, options: RmOptions, callback: NoParamCallback): void; + export namespace rm { + /** + * Asynchronously removes files and directories (modeled on the standard POSIX `rm` utility). + */ + function __promisify__(path: PathLike, options?: RmOptions): Promise; + } + /** + * Synchronously removes files and directories (modeled on the standard POSIX `rm`utility). Returns `undefined`. + * @since v14.14.0 + */ + export function rmSync(path: PathLike, options?: RmOptions): void; + export interface MakeDirectoryOptions { + /** + * Indicates whether parent folders should be created. + * If a folder was created, the path to the first created folder will be returned. + * @default false + */ + recursive?: boolean | undefined; + /** + * A file mode. If a string is passed, it is parsed as an octal integer. If not specified + * @default 0o777 + */ + mode?: Mode | undefined; + } + /** + * Asynchronously creates a directory. + * + * The callback is given a possible exception and, if `recursive` is `true`, the + * first directory path created, `(err[, path])`.`path` can still be `undefined` when `recursive` is `true`, if no directory was + * created. + * + * The optional `options` argument can be an integer specifying `mode` (permission + * and sticky bits), or an object with a `mode` property and a `recursive`property indicating whether parent directories should be created. Calling`fs.mkdir()` when `path` is a directory that + * exists results in an error only + * when `recursive` is false. + * + * ```js + * import { mkdir } from 'fs'; + * + * // Creates /tmp/a/apple, regardless of whether `/tmp` and /tmp/a exist. + * mkdir('/tmp/a/apple', { recursive: true }, (err) => { + * if (err) throw err; + * }); + * ``` + * + * On Windows, using `fs.mkdir()` on the root directory even with recursion will + * result in an error: + * + * ```js + * import { mkdir } from 'fs'; + * + * mkdir('/', { recursive: true }, (err) => { + * // => [Error: EPERM: operation not permitted, mkdir 'C:\'] + * }); + * ``` + * + * See the POSIX [`mkdir(2)`](http://man7.org/linux/man-pages/man2/mkdir.2.html) documentation for more details. + * @since v0.1.8 + */ + export function mkdir( + path: PathLike, + options: MakeDirectoryOptions & { + recursive: true; + }, + callback: (err: NodeJS.ErrnoException | null, path?: string) => void + ): void; + /** + * Asynchronous mkdir(2) - create a directory. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options Either the file mode, or an object optionally specifying the file mode and whether parent folders + * should be created. If a string is passed, it is parsed as an octal integer. If not specified, defaults to `0o777`. + */ + export function mkdir( + path: PathLike, + options: + | Mode + | (MakeDirectoryOptions & { + recursive?: false | undefined; + }) + | null + | undefined, + callback: NoParamCallback + ): void; + /** + * Asynchronous mkdir(2) - create a directory. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options Either the file mode, or an object optionally specifying the file mode and whether parent folders + * should be created. If a string is passed, it is parsed as an octal integer. If not specified, defaults to `0o777`. + */ + export function mkdir(path: PathLike, options: Mode | MakeDirectoryOptions | null | undefined, callback: (err: NodeJS.ErrnoException | null, path?: string) => void): void; + /** + * Asynchronous mkdir(2) - create a directory with a mode of `0o777`. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + */ + export function mkdir(path: PathLike, callback: NoParamCallback): void; + export namespace mkdir { + /** + * Asynchronous mkdir(2) - create a directory. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options Either the file mode, or an object optionally specifying the file mode and whether parent folders + * should be created. If a string is passed, it is parsed as an octal integer. If not specified, defaults to `0o777`. + */ + function __promisify__( + path: PathLike, + options: MakeDirectoryOptions & { + recursive: true; + } + ): Promise; + /** + * Asynchronous mkdir(2) - create a directory. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options Either the file mode, or an object optionally specifying the file mode and whether parent folders + * should be created. If a string is passed, it is parsed as an octal integer. If not specified, defaults to `0o777`. + */ + function __promisify__( + path: PathLike, + options?: + | Mode + | (MakeDirectoryOptions & { + recursive?: false | undefined; + }) + | null + ): Promise; + /** + * Asynchronous mkdir(2) - create a directory. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options Either the file mode, or an object optionally specifying the file mode and whether parent folders + * should be created. If a string is passed, it is parsed as an octal integer. If not specified, defaults to `0o777`. + */ + function __promisify__(path: PathLike, options?: Mode | MakeDirectoryOptions | null): Promise; + } + /** + * Synchronously creates a directory. Returns `undefined`, or if `recursive` is`true`, the first directory path created. + * This is the synchronous version of {@link mkdir}. + * + * See the POSIX [`mkdir(2)`](http://man7.org/linux/man-pages/man2/mkdir.2.html) documentation for more details. + * @since v0.1.21 + */ + export function mkdirSync( + path: PathLike, + options: MakeDirectoryOptions & { + recursive: true; + } + ): string | undefined; + /** + * Synchronous mkdir(2) - create a directory. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options Either the file mode, or an object optionally specifying the file mode and whether parent folders + * should be created. If a string is passed, it is parsed as an octal integer. If not specified, defaults to `0o777`. + */ + export function mkdirSync( + path: PathLike, + options?: + | Mode + | (MakeDirectoryOptions & { + recursive?: false | undefined; + }) + | null + ): void; + /** + * Synchronous mkdir(2) - create a directory. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options Either the file mode, or an object optionally specifying the file mode and whether parent folders + * should be created. If a string is passed, it is parsed as an octal integer. If not specified, defaults to `0o777`. + */ + export function mkdirSync(path: PathLike, options?: Mode | MakeDirectoryOptions | null): string | undefined; + /** + * Creates a unique temporary directory. + * + * Generates six random characters to be appended behind a required`prefix` to create a unique temporary directory. Due to platform + * inconsistencies, avoid trailing `X` characters in `prefix`. Some platforms, + * notably the BSDs, can return more than six random characters, and replace + * trailing `X` characters in `prefix` with random characters. + * + * The created directory path is passed as a string to the callback's second + * parameter. + * + * The optional `options` argument can be a string specifying an encoding, or an + * object with an `encoding` property specifying the character encoding to use. + * + * ```js + * import { mkdtemp } from 'fs'; + * + * mkdtemp(path.join(os.tmpdir(), 'foo-'), (err, directory) => { + * if (err) throw err; + * console.log(directory); + * // Prints: /tmp/foo-itXde2 or C:\Users\...\AppData\Local\Temp\foo-itXde2 + * }); + * ``` + * + * The `fs.mkdtemp()` method will append the six randomly selected characters + * directly to the `prefix` string. For instance, given a directory `/tmp`, if the + * intention is to create a temporary directory _within_`/tmp`, the `prefix`must end with a trailing platform-specific path separator + * (`require('path').sep`). + * + * ```js + * import { tmpdir } from 'os'; + * import { mkdtemp } from 'fs'; + * + * // The parent directory for the new temporary directory + * const tmpDir = tmpdir(); + * + * // This method is *INCORRECT*: + * mkdtemp(tmpDir, (err, directory) => { + * if (err) throw err; + * console.log(directory); + * // Will print something similar to `/tmpabc123`. + * // A new temporary directory is created at the file system root + * // rather than *within* the /tmp directory. + * }); + * + * // This method is *CORRECT*: + * import { sep } from 'path'; + * mkdtemp(`${tmpDir}${sep}`, (err, directory) => { + * if (err) throw err; + * console.log(directory); + * // Will print something similar to `/tmp/abc123`. + * // A new temporary directory is created within + * // the /tmp directory. + * }); + * ``` + * @since v5.10.0 + */ + export function mkdtemp(prefix: string, options: EncodingOption, callback: (err: NodeJS.ErrnoException | null, folder: string) => void): void; + /** + * Asynchronously creates a unique temporary directory. + * Generates six random characters to be appended behind a required prefix to create a unique temporary directory. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + export function mkdtemp( + prefix: string, + options: + | 'buffer' + | { + encoding: 'buffer'; + }, + callback: (err: NodeJS.ErrnoException | null, folder: Buffer) => void + ): void; + /** + * Asynchronously creates a unique temporary directory. + * Generates six random characters to be appended behind a required prefix to create a unique temporary directory. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + export function mkdtemp(prefix: string, options: EncodingOption, callback: (err: NodeJS.ErrnoException | null, folder: string | Buffer) => void): void; + /** + * Asynchronously creates a unique temporary directory. + * Generates six random characters to be appended behind a required prefix to create a unique temporary directory. + */ + export function mkdtemp(prefix: string, callback: (err: NodeJS.ErrnoException | null, folder: string) => void): void; + export namespace mkdtemp { + /** + * Asynchronously creates a unique temporary directory. + * Generates six random characters to be appended behind a required prefix to create a unique temporary directory. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function __promisify__(prefix: string, options?: EncodingOption): Promise; + /** + * Asynchronously creates a unique temporary directory. + * Generates six random characters to be appended behind a required prefix to create a unique temporary directory. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function __promisify__(prefix: string, options: BufferEncodingOption): Promise; + /** + * Asynchronously creates a unique temporary directory. + * Generates six random characters to be appended behind a required prefix to create a unique temporary directory. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function __promisify__(prefix: string, options?: EncodingOption): Promise; + } + /** + * Returns the created directory path. + * + * For detailed information, see the documentation of the asynchronous version of + * this API: {@link mkdtemp}. + * + * The optional `options` argument can be a string specifying an encoding, or an + * object with an `encoding` property specifying the character encoding to use. + * @since v5.10.0 + */ + export function mkdtempSync(prefix: string, options?: EncodingOption): string; + /** + * Synchronously creates a unique temporary directory. + * Generates six random characters to be appended behind a required prefix to create a unique temporary directory. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + export function mkdtempSync(prefix: string, options: BufferEncodingOption): Buffer; + /** + * Synchronously creates a unique temporary directory. + * Generates six random characters to be appended behind a required prefix to create a unique temporary directory. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + export function mkdtempSync(prefix: string, options?: EncodingOption): string | Buffer; + /** + * Reads the contents of a directory. The callback gets two arguments `(err, files)`where `files` is an array of the names of the files in the directory excluding`'.'` and `'..'`. + * + * See the POSIX [`readdir(3)`](http://man7.org/linux/man-pages/man3/readdir.3.html) documentation for more details. + * + * The optional `options` argument can be a string specifying an encoding, or an + * object with an `encoding` property specifying the character encoding to use for + * the filenames passed to the callback. If the `encoding` is set to `'buffer'`, + * the filenames returned will be passed as `Buffer` objects. + * + * If `options.withFileTypes` is set to `true`, the `files` array will contain `fs.Dirent` objects. + * @since v0.1.8 + */ + export function readdir( + path: PathLike, + options: + | { + encoding: BufferEncoding | null; + withFileTypes?: false | undefined; + } + | BufferEncoding + | undefined + | null, + callback: (err: NodeJS.ErrnoException | null, files: string[]) => void + ): void; + /** + * Asynchronous readdir(3) - read a directory. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + export function readdir( + path: PathLike, + options: + | { + encoding: 'buffer'; + withFileTypes?: false | undefined; + } + | 'buffer', + callback: (err: NodeJS.ErrnoException | null, files: Buffer[]) => void + ): void; + /** + * Asynchronous readdir(3) - read a directory. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + export function readdir( + path: PathLike, + options: + | (ObjectEncodingOptions & { + withFileTypes?: false | undefined; + }) + | BufferEncoding + | undefined + | null, + callback: (err: NodeJS.ErrnoException | null, files: string[] | Buffer[]) => void + ): void; + /** + * Asynchronous readdir(3) - read a directory. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + */ + export function readdir(path: PathLike, callback: (err: NodeJS.ErrnoException | null, files: string[]) => void): void; + /** + * Asynchronous readdir(3) - read a directory. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options If called with `withFileTypes: true` the result data will be an array of Dirent. + */ + export function readdir( + path: PathLike, + options: ObjectEncodingOptions & { + withFileTypes: true; + }, + callback: (err: NodeJS.ErrnoException | null, files: Dirent[]) => void + ): void; + export namespace readdir { + /** + * Asynchronous readdir(3) - read a directory. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function __promisify__( + path: PathLike, + options?: + | { + encoding: BufferEncoding | null; + withFileTypes?: false | undefined; + } + | BufferEncoding + | null + ): Promise; + /** + * Asynchronous readdir(3) - read a directory. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function __promisify__( + path: PathLike, + options: + | 'buffer' + | { + encoding: 'buffer'; + withFileTypes?: false | undefined; + } + ): Promise; + /** + * Asynchronous readdir(3) - read a directory. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function __promisify__( + path: PathLike, + options?: + | (ObjectEncodingOptions & { + withFileTypes?: false | undefined; + }) + | BufferEncoding + | null + ): Promise; + /** + * Asynchronous readdir(3) - read a directory. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options If called with `withFileTypes: true` the result data will be an array of Dirent + */ + function __promisify__( + path: PathLike, + options: ObjectEncodingOptions & { + withFileTypes: true; + } + ): Promise; + } + /** + * Reads the contents of the directory. + * + * See the POSIX [`readdir(3)`](http://man7.org/linux/man-pages/man3/readdir.3.html) documentation for more details. + * + * The optional `options` argument can be a string specifying an encoding, or an + * object with an `encoding` property specifying the character encoding to use for + * the filenames returned. If the `encoding` is set to `'buffer'`, + * the filenames returned will be passed as `Buffer` objects. + * + * If `options.withFileTypes` is set to `true`, the result will contain `fs.Dirent` objects. + * @since v0.1.21 + */ + export function readdirSync( + path: PathLike, + options?: + | { + encoding: BufferEncoding | null; + withFileTypes?: false | undefined; + } + | BufferEncoding + | null + ): string[]; + /** + * Synchronous readdir(3) - read a directory. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + export function readdirSync( + path: PathLike, + options: + | { + encoding: 'buffer'; + withFileTypes?: false | undefined; + } + | 'buffer' + ): Buffer[]; + /** + * Synchronous readdir(3) - read a directory. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + export function readdirSync( + path: PathLike, + options?: + | (ObjectEncodingOptions & { + withFileTypes?: false | undefined; + }) + | BufferEncoding + | null + ): string[] | Buffer[]; + /** + * Synchronous readdir(3) - read a directory. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options If called with `withFileTypes: true` the result data will be an array of Dirent. + */ + export function readdirSync( + path: PathLike, + options: ObjectEncodingOptions & { + withFileTypes: true; + } + ): Dirent[]; + /** + * Closes the file descriptor. No arguments other than a possible exception are + * given to the completion callback. + * + * Calling `fs.close()` on any file descriptor (`fd`) that is currently in use + * through any other `fs` operation may lead to undefined behavior. + * + * See the POSIX [`close(2)`](http://man7.org/linux/man-pages/man2/close.2.html) documentation for more detail. + * @since v0.0.2 + */ + export function close(fd: number, callback?: NoParamCallback): void; + export namespace close { + /** + * Asynchronous close(2) - close a file descriptor. + * @param fd A file descriptor. + */ + function __promisify__(fd: number): Promise; + } + /** + * Closes the file descriptor. Returns `undefined`. + * + * Calling `fs.closeSync()` on any file descriptor (`fd`) that is currently in use + * through any other `fs` operation may lead to undefined behavior. + * + * See the POSIX [`close(2)`](http://man7.org/linux/man-pages/man2/close.2.html) documentation for more detail. + * @since v0.1.21 + */ + export function closeSync(fd: number): void; + /** + * Asynchronous file open. See the POSIX [`open(2)`](http://man7.org/linux/man-pages/man2/open.2.html) documentation for more details. + * + * `mode` sets the file mode (permission and sticky bits), but only if the file was + * created. On Windows, only the write permission can be manipulated; see {@link chmod}. + * + * The callback gets two arguments `(err, fd)`. + * + * Some characters (`< > : " / \ | ? *`) are reserved under Windows as documented + * by [Naming Files, Paths, and Namespaces](https://docs.microsoft.com/en-us/windows/desktop/FileIO/naming-a-file). Under NTFS, if the filename contains + * a colon, Node.js will open a file system stream, as described by [this MSDN page](https://docs.microsoft.com/en-us/windows/desktop/FileIO/using-streams). + * + * Functions based on `fs.open()` exhibit this behavior as well:`fs.writeFile()`, `fs.readFile()`, etc. + * @since v0.0.2 + * @param [flags='r'] See `support of file system `flags``. + * @param [mode=0o666] + */ + export function open(path: PathLike, flags: OpenMode | undefined, mode: Mode | undefined | null, callback: (err: NodeJS.ErrnoException | null, fd: number) => void): void; + /** + * Asynchronous open(2) - open and possibly create a file. If the file is created, its mode will be `0o666`. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param [flags='r'] See `support of file system `flags``. + */ + export function open(path: PathLike, flags: OpenMode | undefined, callback: (err: NodeJS.ErrnoException | null, fd: number) => void): void; + /** + * Asynchronous open(2) - open and possibly create a file. If the file is created, its mode will be `0o666`. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + */ + export function open(path: PathLike, callback: (err: NodeJS.ErrnoException | null, fd: number) => void): void; + + export namespace open { + /** + * Asynchronous open(2) - open and possibly create a file. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param mode A file mode. If a string is passed, it is parsed as an octal integer. If not supplied, defaults to `0o666`. + */ + function __promisify__(path: PathLike, flags: OpenMode, mode?: Mode | null): Promise; + } + /** + * Returns an integer representing the file descriptor. + * + * For detailed information, see the documentation of the asynchronous version of + * this API: {@link open}. + * @since v0.1.21 + * @param [flags='r'] + * @param [mode=0o666] + */ + export function openSync(path: PathLike, flags: OpenMode, mode?: Mode | null): number; + /** + * Change the file system timestamps of the object referenced by `path`. + * + * The `atime` and `mtime` arguments follow these rules: + * + * * Values can be either numbers representing Unix epoch time in seconds,`Date`s, or a numeric string like `'123456789.0'`. + * * If the value can not be converted to a number, or is `NaN`, `Infinity` or`-Infinity`, an `Error` will be thrown. + * @since v0.4.2 + */ + export function utimes(path: PathLike, atime: TimeLike, mtime: TimeLike, callback: NoParamCallback): void; + export namespace utimes { + /** + * Asynchronously change file timestamps of the file referenced by the supplied path. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param atime The last access time. If a string is provided, it will be coerced to number. + * @param mtime The last modified time. If a string is provided, it will be coerced to number. + */ + function __promisify__(path: PathLike, atime: TimeLike, mtime: TimeLike): Promise; + } + /** + * Returns `undefined`. + * + * For detailed information, see the documentation of the asynchronous version of + * this API: {@link utimes}. + * @since v0.4.2 + */ + export function utimesSync(path: PathLike, atime: TimeLike, mtime: TimeLike): void; + /** + * Change the file system timestamps of the object referenced by the supplied file + * descriptor. See {@link utimes}. + * @since v0.4.2 + */ + export function futimes(fd: number, atime: TimeLike, mtime: TimeLike, callback: NoParamCallback): void; + export namespace futimes { + /** + * Asynchronously change file timestamps of the file referenced by the supplied file descriptor. + * @param fd A file descriptor. + * @param atime The last access time. If a string is provided, it will be coerced to number. + * @param mtime The last modified time. If a string is provided, it will be coerced to number. + */ + function __promisify__(fd: number, atime: TimeLike, mtime: TimeLike): Promise; + } + /** + * Synchronous version of {@link futimes}. Returns `undefined`. + * @since v0.4.2 + */ + export function futimesSync(fd: number, atime: TimeLike, mtime: TimeLike): void; + /** + * Request that all data for the open file descriptor is flushed to the storage + * device. The specific implementation is operating system and device specific. + * Refer to the POSIX [`fsync(2)`](http://man7.org/linux/man-pages/man2/fsync.2.html) documentation for more detail. No arguments other + * than a possible exception are given to the completion callback. + * @since v0.1.96 + */ + export function fsync(fd: number, callback: NoParamCallback): void; + export namespace fsync { + /** + * Asynchronous fsync(2) - synchronize a file's in-core state with the underlying storage device. + * @param fd A file descriptor. + */ + function __promisify__(fd: number): Promise; + } + /** + * Request that all data for the open file descriptor is flushed to the storage + * device. The specific implementation is operating system and device specific. + * Refer to the POSIX [`fsync(2)`](http://man7.org/linux/man-pages/man2/fsync.2.html) documentation for more detail. Returns `undefined`. + * @since v0.1.96 + */ + export function fsyncSync(fd: number): void; + /** + * Write `buffer` to the file specified by `fd`. + * + * `offset` determines the part of the buffer to be written, and `length` is + * an integer specifying the number of bytes to write. + * + * `position` refers to the offset from the beginning of the file where this data + * should be written. If `typeof position !== 'number'`, the data will be written + * at the current position. See [`pwrite(2)`](http://man7.org/linux/man-pages/man2/pwrite.2.html). + * + * The callback will be given three arguments `(err, bytesWritten, buffer)` where`bytesWritten` specifies how many _bytes_ were written from `buffer`. + * + * If this method is invoked as its `util.promisify()` ed version, it returns + * a promise for an `Object` with `bytesWritten` and `buffer` properties. + * + * It is unsafe to use `fs.write()` multiple times on the same file without waiting + * for the callback. For this scenario, {@link createWriteStream} is + * recommended. + * + * On Linux, positional writes don't work when the file is opened in append mode. + * The kernel ignores the position argument and always appends the data to + * the end of the file. + * @since v0.0.2 + */ + export function write( + fd: number, + buffer: TBuffer, + offset: number | undefined | null, + length: number | undefined | null, + position: number | undefined | null, + callback: (err: NodeJS.ErrnoException | null, written: number, buffer: TBuffer) => void + ): void; + /** + * Asynchronously writes `buffer` to the file referenced by the supplied file descriptor. + * @param fd A file descriptor. + * @param offset The part of the buffer to be written. If not supplied, defaults to `0`. + * @param length The number of bytes to write. If not supplied, defaults to `buffer.length - offset`. + */ + export function write( + fd: number, + buffer: TBuffer, + offset: number | undefined | null, + length: number | undefined | null, + callback: (err: NodeJS.ErrnoException | null, written: number, buffer: TBuffer) => void + ): void; + /** + * Asynchronously writes `buffer` to the file referenced by the supplied file descriptor. + * @param fd A file descriptor. + * @param offset The part of the buffer to be written. If not supplied, defaults to `0`. + */ + export function write( + fd: number, + buffer: TBuffer, + offset: number | undefined | null, + callback: (err: NodeJS.ErrnoException | null, written: number, buffer: TBuffer) => void + ): void; + /** + * Asynchronously writes `buffer` to the file referenced by the supplied file descriptor. + * @param fd A file descriptor. + */ + export function write(fd: number, buffer: TBuffer, callback: (err: NodeJS.ErrnoException | null, written: number, buffer: TBuffer) => void): void; + /** + * Asynchronously writes `string` to the file referenced by the supplied file descriptor. + * @param fd A file descriptor. + * @param string A string to write. + * @param position The offset from the beginning of the file where this data should be written. If not supplied, defaults to the current position. + * @param encoding The expected string encoding. + */ + export function write( + fd: number, + string: string, + position: number | undefined | null, + encoding: BufferEncoding | undefined | null, + callback: (err: NodeJS.ErrnoException | null, written: number, str: string) => void + ): void; + /** + * Asynchronously writes `string` to the file referenced by the supplied file descriptor. + * @param fd A file descriptor. + * @param string A string to write. + * @param position The offset from the beginning of the file where this data should be written. If not supplied, defaults to the current position. + */ + export function write(fd: number, string: string, position: number | undefined | null, callback: (err: NodeJS.ErrnoException | null, written: number, str: string) => void): void; + /** + * Asynchronously writes `string` to the file referenced by the supplied file descriptor. + * @param fd A file descriptor. + * @param string A string to write. + */ + export function write(fd: number, string: string, callback: (err: NodeJS.ErrnoException | null, written: number, str: string) => void): void; + export namespace write { + /** + * Asynchronously writes `buffer` to the file referenced by the supplied file descriptor. + * @param fd A file descriptor. + * @param offset The part of the buffer to be written. If not supplied, defaults to `0`. + * @param length The number of bytes to write. If not supplied, defaults to `buffer.length - offset`. + * @param position The offset from the beginning of the file where this data should be written. If not supplied, defaults to the current position. + */ + function __promisify__( + fd: number, + buffer?: TBuffer, + offset?: number, + length?: number, + position?: number | null + ): Promise<{ + bytesWritten: number; + buffer: TBuffer; + }>; + /** + * Asynchronously writes `string` to the file referenced by the supplied file descriptor. + * @param fd A file descriptor. + * @param string A string to write. + * @param position The offset from the beginning of the file where this data should be written. If not supplied, defaults to the current position. + * @param encoding The expected string encoding. + */ + function __promisify__( + fd: number, + string: string, + position?: number | null, + encoding?: BufferEncoding | null + ): Promise<{ + bytesWritten: number; + buffer: string; + }>; + } + /** + * For detailed information, see the documentation of the asynchronous version of + * this API: {@link write}. + * @since v0.1.21 + * @return The number of bytes written. + */ + export function writeSync(fd: number, buffer: NodeJS.ArrayBufferView, offset?: number | null, length?: number | null, position?: number | null): number; + /** + * Synchronously writes `string` to the file referenced by the supplied file descriptor, returning the number of bytes written. + * @param fd A file descriptor. + * @param string A string to write. + * @param position The offset from the beginning of the file where this data should be written. If not supplied, defaults to the current position. + * @param encoding The expected string encoding. + */ + export function writeSync(fd: number, string: string, position?: number | null, encoding?: BufferEncoding | null): number; + export type ReadPosition = number | bigint; + export interface ReadSyncOptions { + /** + * @default 0 + */ + offset?: number | undefined; + /** + * @default `length of buffer` + */ + length?: number | undefined; + /** + * @default null + */ + position?: ReadPosition | null | undefined; + } + export interface ReadAsyncOptions extends ReadSyncOptions { + buffer?: TBuffer; + } + /** + * Read data from the file specified by `fd`. + * + * The callback is given the three arguments, `(err, bytesRead, buffer)`. + * + * If the file is not modified concurrently, the end-of-file is reached when the + * number of bytes read is zero. + * + * If this method is invoked as its `util.promisify()` ed version, it returns + * a promise for an `Object` with `bytesRead` and `buffer` properties. + * @since v0.0.2 + * @param buffer The buffer that the data will be written to. + * @param offset The position in `buffer` to write the data to. + * @param length The number of bytes to read. + * @param position Specifies where to begin reading from in the file. If `position` is `null` or `-1 `, data will be read from the current file position, and the file position will be updated. If + * `position` is an integer, the file position will be unchanged. + */ + export function read( + fd: number, + buffer: TBuffer, + offset: number, + length: number, + position: ReadPosition | null, + callback: (err: NodeJS.ErrnoException | null, bytesRead: number, buffer: TBuffer) => void + ): void; + /** + * Similar to the above `fs.read` function, this version takes an optional `options` object. + * If not otherwise specified in an `options` object, + * `buffer` defaults to `Buffer.alloc(16384)`, + * `offset` defaults to `0`, + * `length` defaults to `buffer.byteLength`, `- offset` as of Node 17.6.0 + * `position` defaults to `null` + * @since v12.17.0, 13.11.0 + */ + export function read( + fd: number, + options: ReadAsyncOptions, + callback: (err: NodeJS.ErrnoException | null, bytesRead: number, buffer: TBuffer) => void + ): void; + export function read(fd: number, callback: (err: NodeJS.ErrnoException | null, bytesRead: number, buffer: NodeJS.ArrayBufferView) => void): void; + export namespace read { + /** + * @param fd A file descriptor. + * @param buffer The buffer that the data will be written to. + * @param offset The offset in the buffer at which to start writing. + * @param length The number of bytes to read. + * @param position The offset from the beginning of the file from which data should be read. If `null`, data will be read from the current position. + */ + function __promisify__( + fd: number, + buffer: TBuffer, + offset: number, + length: number, + position: number | null + ): Promise<{ + bytesRead: number; + buffer: TBuffer; + }>; + function __promisify__( + fd: number, + options: ReadAsyncOptions + ): Promise<{ + bytesRead: number; + buffer: TBuffer; + }>; + function __promisify__(fd: number): Promise<{ + bytesRead: number; + buffer: NodeJS.ArrayBufferView; + }>; + } + /** + * Returns the number of `bytesRead`. + * + * For detailed information, see the documentation of the asynchronous version of + * this API: {@link read}. + * @since v0.1.21 + */ + export function readSync(fd: number, buffer: NodeJS.ArrayBufferView, offset: number, length: number, position: ReadPosition | null): number; + /** + * Similar to the above `fs.readSync` function, this version takes an optional `options` object. + * If no `options` object is specified, it will default with the above values. + */ + export function readSync(fd: number, buffer: NodeJS.ArrayBufferView, opts?: ReadSyncOptions): number; + /** + * Asynchronously reads the entire contents of a file. + * + * ```js + * import { readFile } from 'fs'; + * + * readFile('/etc/passwd', (err, data) => { + * if (err) throw err; + * console.log(data); + * }); + * ``` + * + * The callback is passed two arguments `(err, data)`, where `data` is the + * contents of the file. + * + * If no encoding is specified, then the raw buffer is returned. + * + * If `options` is a string, then it specifies the encoding: + * + * ```js + * import { readFile } from 'fs'; + * + * readFile('/etc/passwd', 'utf8', callback); + * ``` + * + * When the path is a directory, the behavior of `fs.readFile()` and {@link readFileSync} is platform-specific. On macOS, Linux, and Windows, an + * error will be returned. On FreeBSD, a representation of the directory's contents + * will be returned. + * + * ```js + * import { readFile } from 'fs'; + * + * // macOS, Linux, and Windows + * readFile('', (err, data) => { + * // => [Error: EISDIR: illegal operation on a directory, read ] + * }); + * + * // FreeBSD + * readFile('', (err, data) => { + * // => null, + * }); + * ``` + * + * It is possible to abort an ongoing request using an `AbortSignal`. If a + * request is aborted the callback is called with an `AbortError`: + * + * ```js + * import { readFile } from 'fs'; + * + * const controller = new AbortController(); + * const signal = controller.signal; + * readFile(fileInfo[0].name, { signal }, (err, buf) => { + * // ... + * }); + * // When you want to abort the request + * controller.abort(); + * ``` + * + * The `fs.readFile()` function buffers the entire file. To minimize memory costs, + * when possible prefer streaming via `fs.createReadStream()`. + * + * Aborting an ongoing request does not abort individual operating + * system requests but rather the internal buffering `fs.readFile` performs. + * @since v0.1.29 + * @param path filename or file descriptor + */ + export function readFile( + path: PathOrFileDescriptor, + options: + | ({ + encoding?: null | undefined; + flag?: string | undefined; + } & Abortable) + | undefined + | null, + callback: (err: NodeJS.ErrnoException | null, data: Buffer) => void + ): void; + /** + * Asynchronously reads the entire contents of a file. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * If a file descriptor is provided, the underlying file will _not_ be closed automatically. + * @param options Either the encoding for the result, or an object that contains the encoding and an optional flag. + * If a flag is not provided, it defaults to `'r'`. + */ + export function readFile( + path: PathOrFileDescriptor, + options: + | ({ + encoding: BufferEncoding; + flag?: string | undefined; + } & Abortable) + | BufferEncoding, + callback: (err: NodeJS.ErrnoException | null, data: string) => void + ): void; + /** + * Asynchronously reads the entire contents of a file. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * If a file descriptor is provided, the underlying file will _not_ be closed automatically. + * @param options Either the encoding for the result, or an object that contains the encoding and an optional flag. + * If a flag is not provided, it defaults to `'r'`. + */ + export function readFile( + path: PathOrFileDescriptor, + options: + | (ObjectEncodingOptions & { + flag?: string | undefined; + } & Abortable) + | BufferEncoding + | undefined + | null, + callback: (err: NodeJS.ErrnoException | null, data: string | Buffer) => void + ): void; + /** + * Asynchronously reads the entire contents of a file. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * If a file descriptor is provided, the underlying file will _not_ be closed automatically. + */ + export function readFile(path: PathOrFileDescriptor, callback: (err: NodeJS.ErrnoException | null, data: Buffer) => void): void; + export namespace readFile { + /** + * Asynchronously reads the entire contents of a file. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * If a file descriptor is provided, the underlying file will _not_ be closed automatically. + * @param options An object that may contain an optional flag. + * If a flag is not provided, it defaults to `'r'`. + */ + function __promisify__( + path: PathOrFileDescriptor, + options?: { + encoding?: null | undefined; + flag?: string | undefined; + } | null + ): Promise; + /** + * Asynchronously reads the entire contents of a file. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * URL support is _experimental_. + * If a file descriptor is provided, the underlying file will _not_ be closed automatically. + * @param options Either the encoding for the result, or an object that contains the encoding and an optional flag. + * If a flag is not provided, it defaults to `'r'`. + */ + function __promisify__( + path: PathOrFileDescriptor, + options: + | { + encoding: BufferEncoding; + flag?: string | undefined; + } + | BufferEncoding + ): Promise; + /** + * Asynchronously reads the entire contents of a file. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * URL support is _experimental_. + * If a file descriptor is provided, the underlying file will _not_ be closed automatically. + * @param options Either the encoding for the result, or an object that contains the encoding and an optional flag. + * If a flag is not provided, it defaults to `'r'`. + */ + function __promisify__( + path: PathOrFileDescriptor, + options?: + | (ObjectEncodingOptions & { + flag?: string | undefined; + }) + | BufferEncoding + | null + ): Promise; + } + /** + * Returns the contents of the `path`. + * + * For detailed information, see the documentation of the asynchronous version of + * this API: {@link readFile}. + * + * If the `encoding` option is specified then this function returns a + * string. Otherwise it returns a buffer. + * + * Similar to {@link readFile}, when the path is a directory, the behavior of`fs.readFileSync()` is platform-specific. + * + * ```js + * import { readFileSync } from 'fs'; + * + * // macOS, Linux, and Windows + * readFileSync(''); + * // => [Error: EISDIR: illegal operation on a directory, read ] + * + * // FreeBSD + * readFileSync(''); // => + * ``` + * @since v0.1.8 + * @param path filename or file descriptor + */ + export function readFileSync( + path: PathOrFileDescriptor, + options?: { + encoding?: null | undefined; + flag?: string | undefined; + } | null + ): Buffer; + /** + * Synchronously reads the entire contents of a file. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * If a file descriptor is provided, the underlying file will _not_ be closed automatically. + * @param options Either the encoding for the result, or an object that contains the encoding and an optional flag. + * If a flag is not provided, it defaults to `'r'`. + */ + export function readFileSync( + path: PathOrFileDescriptor, + options: + | { + encoding: BufferEncoding; + flag?: string | undefined; + } + | BufferEncoding + ): string; + /** + * Synchronously reads the entire contents of a file. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * If a file descriptor is provided, the underlying file will _not_ be closed automatically. + * @param options Either the encoding for the result, or an object that contains the encoding and an optional flag. + * If a flag is not provided, it defaults to `'r'`. + */ + export function readFileSync( + path: PathOrFileDescriptor, + options?: + | (ObjectEncodingOptions & { + flag?: string | undefined; + }) + | BufferEncoding + | null + ): string | Buffer; + export type WriteFileOptions = + | (ObjectEncodingOptions & + Abortable & { + mode?: Mode | undefined; + flag?: string | undefined; + }) + | BufferEncoding + | null; + /** + * When `file` is a filename, asynchronously writes data to the file, replacing the + * file if it already exists. `data` can be a string or a buffer. + * + * When `file` is a file descriptor, the behavior is similar to calling`fs.write()` directly (which is recommended). See the notes below on using + * a file descriptor. + * + * The `encoding` option is ignored if `data` is a buffer. + * + * The `mode` option only affects the newly created file. See {@link open} for more details. + * + * ```js + * import { writeFile } from 'fs'; + * import { Buffer } from 'buffer'; + * + * const data = new Uint8Array(Buffer.from('Hello Node.js')); + * writeFile('message.txt', data, (err) => { + * if (err) throw err; + * console.log('The file has been saved!'); + * }); + * ``` + * + * If `options` is a string, then it specifies the encoding: + * + * ```js + * import { writeFile } from 'fs'; + * + * writeFile('message.txt', 'Hello Node.js', 'utf8', callback); + * ``` + * + * It is unsafe to use `fs.writeFile()` multiple times on the same file without + * waiting for the callback. For this scenario, {@link createWriteStream} is + * recommended. + * + * Similarly to `fs.readFile` \- `fs.writeFile` is a convenience method that + * performs multiple `write` calls internally to write the buffer passed to it. + * For performance sensitive code consider using {@link createWriteStream}. + * + * It is possible to use an `AbortSignal` to cancel an `fs.writeFile()`. + * Cancelation is "best effort", and some amount of data is likely still + * to be written. + * + * ```js + * import { writeFile } from 'fs'; + * import { Buffer } from 'buffer'; + * + * const controller = new AbortController(); + * const { signal } = controller; + * const data = new Uint8Array(Buffer.from('Hello Node.js')); + * writeFile('message.txt', data, { signal }, (err) => { + * // When a request is aborted - the callback is called with an AbortError + * }); + * // When the request should be aborted + * controller.abort(); + * ``` + * + * Aborting an ongoing request does not abort individual operating + * system requests but rather the internal buffering `fs.writeFile` performs. + * @since v0.1.29 + * @param file filename or file descriptor + */ + export function writeFile(file: PathOrFileDescriptor, data: string | NodeJS.ArrayBufferView, options: WriteFileOptions, callback: NoParamCallback): void; + /** + * Asynchronously writes data to a file, replacing the file if it already exists. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * If a file descriptor is provided, the underlying file will _not_ be closed automatically. + * @param data The data to write. If something other than a Buffer or Uint8Array is provided, the value is coerced to a string. + */ + export function writeFile(path: PathOrFileDescriptor, data: string | NodeJS.ArrayBufferView, callback: NoParamCallback): void; + export namespace writeFile { + /** + * Asynchronously writes data to a file, replacing the file if it already exists. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * URL support is _experimental_. + * If a file descriptor is provided, the underlying file will _not_ be closed automatically. + * @param data The data to write. If something other than a Buffer or Uint8Array is provided, the value is coerced to a string. + * @param options Either the encoding for the file, or an object optionally specifying the encoding, file mode, and flag. + * If `encoding` is not supplied, the default of `'utf8'` is used. + * If `mode` is not supplied, the default of `0o666` is used. + * If `mode` is a string, it is parsed as an octal integer. + * If `flag` is not supplied, the default of `'w'` is used. + */ + function __promisify__(path: PathOrFileDescriptor, data: string | NodeJS.ArrayBufferView, options?: WriteFileOptions): Promise; + } + /** + * Returns `undefined`. + * + * The `mode` option only affects the newly created file. See {@link open} for more details. + * + * For detailed information, see the documentation of the asynchronous version of + * this API: {@link writeFile}. + * @since v0.1.29 + * @param file filename or file descriptor + */ + export function writeFileSync(file: PathOrFileDescriptor, data: string | NodeJS.ArrayBufferView, options?: WriteFileOptions): void; + /** + * Asynchronously append data to a file, creating the file if it does not yet + * exist. `data` can be a string or a `Buffer`. + * + * The `mode` option only affects the newly created file. See {@link open} for more details. + * + * ```js + * import { appendFile } from 'fs'; + * + * appendFile('message.txt', 'data to append', (err) => { + * if (err) throw err; + * console.log('The "data to append" was appended to file!'); + * }); + * ``` + * + * If `options` is a string, then it specifies the encoding: + * + * ```js + * import { appendFile } from 'fs'; + * + * appendFile('message.txt', 'data to append', 'utf8', callback); + * ``` + * + * The `path` may be specified as a numeric file descriptor that has been opened + * for appending (using `fs.open()` or `fs.openSync()`). The file descriptor will + * not be closed automatically. + * + * ```js + * import { open, close, appendFile } from 'fs'; + * + * function closeFd(fd) { + * close(fd, (err) => { + * if (err) throw err; + * }); + * } + * + * open('message.txt', 'a', (err, fd) => { + * if (err) throw err; + * + * try { + * appendFile(fd, 'data to append', 'utf8', (err) => { + * closeFd(fd); + * if (err) throw err; + * }); + * } catch (err) { + * closeFd(fd); + * throw err; + * } + * }); + * ``` + * @since v0.6.7 + * @param path filename or file descriptor + */ + export function appendFile(path: PathOrFileDescriptor, data: string | Uint8Array, options: WriteFileOptions, callback: NoParamCallback): void; + /** + * Asynchronously append data to a file, creating the file if it does not exist. + * @param file A path to a file. If a URL is provided, it must use the `file:` protocol. + * If a file descriptor is provided, the underlying file will _not_ be closed automatically. + * @param data The data to write. If something other than a Buffer or Uint8Array is provided, the value is coerced to a string. + */ + export function appendFile(file: PathOrFileDescriptor, data: string | Uint8Array, callback: NoParamCallback): void; + export namespace appendFile { + /** + * Asynchronously append data to a file, creating the file if it does not exist. + * @param file A path to a file. If a URL is provided, it must use the `file:` protocol. + * URL support is _experimental_. + * If a file descriptor is provided, the underlying file will _not_ be closed automatically. + * @param data The data to write. If something other than a Buffer or Uint8Array is provided, the value is coerced to a string. + * @param options Either the encoding for the file, or an object optionally specifying the encoding, file mode, and flag. + * If `encoding` is not supplied, the default of `'utf8'` is used. + * If `mode` is not supplied, the default of `0o666` is used. + * If `mode` is a string, it is parsed as an octal integer. + * If `flag` is not supplied, the default of `'a'` is used. + */ + function __promisify__(file: PathOrFileDescriptor, data: string | Uint8Array, options?: WriteFileOptions): Promise; + } + /** + * Synchronously append data to a file, creating the file if it does not yet + * exist. `data` can be a string or a `Buffer`. + * + * The `mode` option only affects the newly created file. See {@link open} for more details. + * + * ```js + * import { appendFileSync } from 'fs'; + * + * try { + * appendFileSync('message.txt', 'data to append'); + * console.log('The "data to append" was appended to file!'); + * } catch (err) { + * // Handle the error + * } + * ``` + * + * If `options` is a string, then it specifies the encoding: + * + * ```js + * import { appendFileSync } from 'fs'; + * + * appendFileSync('message.txt', 'data to append', 'utf8'); + * ``` + * + * The `path` may be specified as a numeric file descriptor that has been opened + * for appending (using `fs.open()` or `fs.openSync()`). The file descriptor will + * not be closed automatically. + * + * ```js + * import { openSync, closeSync, appendFileSync } from 'fs'; + * + * let fd; + * + * try { + * fd = openSync('message.txt', 'a'); + * appendFileSync(fd, 'data to append', 'utf8'); + * } catch (err) { + * // Handle the error + * } finally { + * if (fd !== undefined) + * closeSync(fd); + * } + * ``` + * @since v0.6.7 + * @param path filename or file descriptor + */ + export function appendFileSync(path: PathOrFileDescriptor, data: string | Uint8Array, options?: WriteFileOptions): void; + /** + * Watch for changes on `filename`. The callback `listener` will be called each + * time the file is accessed. + * + * The `options` argument may be omitted. If provided, it should be an object. The`options` object may contain a boolean named `persistent` that indicates + * whether the process should continue to run as long as files are being watched. + * The `options` object may specify an `interval` property indicating how often the + * target should be polled in milliseconds. + * + * The `listener` gets two arguments the current stat object and the previous + * stat object: + * + * ```js + * import { watchFile } from 'fs'; + * + * watchFile('message.text', (curr, prev) => { + * console.log(`the current mtime is: ${curr.mtime}`); + * console.log(`the previous mtime was: ${prev.mtime}`); + * }); + * ``` + * + * These stat objects are instances of `fs.Stat`. If the `bigint` option is `true`, + * the numeric values in these objects are specified as `BigInt`s. + * + * To be notified when the file was modified, not just accessed, it is necessary + * to compare `curr.mtimeMs` and `prev.mtimeMs`. + * + * When an `fs.watchFile` operation results in an `ENOENT` error, it + * will invoke the listener once, with all the fields zeroed (or, for dates, the + * Unix Epoch). If the file is created later on, the listener will be called + * again, with the latest stat objects. This is a change in functionality since + * v0.10. + * + * Using {@link watch} is more efficient than `fs.watchFile` and`fs.unwatchFile`. `fs.watch` should be used instead of `fs.watchFile` and`fs.unwatchFile` when possible. + * + * When a file being watched by `fs.watchFile()` disappears and reappears, + * then the contents of `previous` in the second callback event (the file's + * reappearance) will be the same as the contents of `previous` in the first + * callback event (its disappearance). + * + * This happens when: + * + * * the file is deleted, followed by a restore + * * the file is renamed and then renamed a second time back to its original name + * @since v0.1.31 + */ + export interface WatchFileOptions { + bigint?: boolean | undefined; + persistent?: boolean | undefined; + interval?: number | undefined; + } + /** + * Watch for changes on `filename`. The callback `listener` will be called each + * time the file is accessed. + * + * The `options` argument may be omitted. If provided, it should be an object. The`options` object may contain a boolean named `persistent` that indicates + * whether the process should continue to run as long as files are being watched. + * The `options` object may specify an `interval` property indicating how often the + * target should be polled in milliseconds. + * + * The `listener` gets two arguments the current stat object and the previous + * stat object: + * + * ```js + * import { watchFile } from 'fs'; + * + * watchFile('message.text', (curr, prev) => { + * console.log(`the current mtime is: ${curr.mtime}`); + * console.log(`the previous mtime was: ${prev.mtime}`); + * }); + * ``` + * + * These stat objects are instances of `fs.Stat`. If the `bigint` option is `true`, + * the numeric values in these objects are specified as `BigInt`s. + * + * To be notified when the file was modified, not just accessed, it is necessary + * to compare `curr.mtimeMs` and `prev.mtimeMs`. + * + * When an `fs.watchFile` operation results in an `ENOENT` error, it + * will invoke the listener once, with all the fields zeroed (or, for dates, the + * Unix Epoch). If the file is created later on, the listener will be called + * again, with the latest stat objects. This is a change in functionality since + * v0.10. + * + * Using {@link watch} is more efficient than `fs.watchFile` and`fs.unwatchFile`. `fs.watch` should be used instead of `fs.watchFile` and`fs.unwatchFile` when possible. + * + * When a file being watched by `fs.watchFile()` disappears and reappears, + * then the contents of `previous` in the second callback event (the file's + * reappearance) will be the same as the contents of `previous` in the first + * callback event (its disappearance). + * + * This happens when: + * + * * the file is deleted, followed by a restore + * * the file is renamed and then renamed a second time back to its original name + * @since v0.1.31 + */ + export function watchFile( + filename: PathLike, + options: + | (WatchFileOptions & { + bigint?: false | undefined; + }) + | undefined, + listener: (curr: Stats, prev: Stats) => void + ): StatWatcher; + export function watchFile( + filename: PathLike, + options: + | (WatchFileOptions & { + bigint: true; + }) + | undefined, + listener: (curr: BigIntStats, prev: BigIntStats) => void + ): StatWatcher; + /** + * Watch for changes on `filename`. The callback `listener` will be called each time the file is accessed. + * @param filename A path to a file or directory. If a URL is provided, it must use the `file:` protocol. + */ + export function watchFile(filename: PathLike, listener: (curr: Stats, prev: Stats) => void): StatWatcher; + /** + * Stop watching for changes on `filename`. If `listener` is specified, only that + * particular listener is removed. Otherwise, _all_ listeners are removed, + * effectively stopping watching of `filename`. + * + * Calling `fs.unwatchFile()` with a filename that is not being watched is a + * no-op, not an error. + * + * Using {@link watch} is more efficient than `fs.watchFile()` and`fs.unwatchFile()`. `fs.watch()` should be used instead of `fs.watchFile()`and `fs.unwatchFile()` when possible. + * @since v0.1.31 + * @param listener Optional, a listener previously attached using `fs.watchFile()` + */ + export function unwatchFile(filename: PathLike, listener?: (curr: Stats, prev: Stats) => void): void; + export interface WatchOptions extends Abortable { + encoding?: BufferEncoding | 'buffer' | undefined; + persistent?: boolean | undefined; + recursive?: boolean | undefined; + } + export type WatchEventType = 'rename' | 'change'; + export type WatchListener = (event: WatchEventType, filename: T) => void; + /** + * Watch for changes on `filename`, where `filename` is either a file or a + * directory. + * + * The second argument is optional. If `options` is provided as a string, it + * specifies the `encoding`. Otherwise `options` should be passed as an object. + * + * The listener callback gets two arguments `(eventType, filename)`. `eventType`is either `'rename'` or `'change'`, and `filename` is the name of the file + * which triggered the event. + * + * On most platforms, `'rename'` is emitted whenever a filename appears or + * disappears in the directory. + * + * The listener callback is attached to the `'change'` event fired by `fs.FSWatcher`, but it is not the same thing as the `'change'` value of`eventType`. + * + * If a `signal` is passed, aborting the corresponding AbortController will close + * the returned `fs.FSWatcher`. + * @since v0.5.10 + * @param listener + */ + export function watch( + filename: PathLike, + options: + | (WatchOptions & { + encoding: 'buffer'; + }) + | 'buffer', + listener?: WatchListener + ): FSWatcher; + /** + * Watch for changes on `filename`, where `filename` is either a file or a directory, returning an `FSWatcher`. + * @param filename A path to a file or directory. If a URL is provided, it must use the `file:` protocol. + * @param options Either the encoding for the filename provided to the listener, or an object optionally specifying encoding, persistent, and recursive options. + * If `encoding` is not supplied, the default of `'utf8'` is used. + * If `persistent` is not supplied, the default of `true` is used. + * If `recursive` is not supplied, the default of `false` is used. + */ + export function watch(filename: PathLike, options?: WatchOptions | BufferEncoding | null, listener?: WatchListener): FSWatcher; + /** + * Watch for changes on `filename`, where `filename` is either a file or a directory, returning an `FSWatcher`. + * @param filename A path to a file or directory. If a URL is provided, it must use the `file:` protocol. + * @param options Either the encoding for the filename provided to the listener, or an object optionally specifying encoding, persistent, and recursive options. + * If `encoding` is not supplied, the default of `'utf8'` is used. + * If `persistent` is not supplied, the default of `true` is used. + * If `recursive` is not supplied, the default of `false` is used. + */ + export function watch(filename: PathLike, options: WatchOptions | string, listener?: WatchListener): FSWatcher; + /** + * Watch for changes on `filename`, where `filename` is either a file or a directory, returning an `FSWatcher`. + * @param filename A path to a file or directory. If a URL is provided, it must use the `file:` protocol. + */ + export function watch(filename: PathLike, listener?: WatchListener): FSWatcher; + /** + * Test whether or not the given path exists by checking with the file system. + * Then call the `callback` argument with either true or false: + * + * ```js + * import { exists } from 'fs'; + * + * exists('/etc/passwd', (e) => { + * console.log(e ? 'it exists' : 'no passwd!'); + * }); + * ``` + * + * **The parameters for this callback are not consistent with other Node.js** + * **callbacks.** Normally, the first parameter to a Node.js callback is an `err`parameter, optionally followed by other parameters. The `fs.exists()` callback + * has only one boolean parameter. This is one reason `fs.access()` is recommended + * instead of `fs.exists()`. + * + * Using `fs.exists()` to check for the existence of a file before calling`fs.open()`, `fs.readFile()` or `fs.writeFile()` is not recommended. Doing + * so introduces a race condition, since other processes may change the file's + * state between the two calls. Instead, user code should open/read/write the + * file directly and handle the error raised if the file does not exist. + * + * **write (NOT RECOMMENDED)** + * + * ```js + * import { exists, open, close } from 'fs'; + * + * exists('myfile', (e) => { + * if (e) { + * console.error('myfile already exists'); + * } else { + * open('myfile', 'wx', (err, fd) => { + * if (err) throw err; + * + * try { + * writeMyData(fd); + * } finally { + * close(fd, (err) => { + * if (err) throw err; + * }); + * } + * }); + * } + * }); + * ``` + * + * **write (RECOMMENDED)** + * + * ```js + * import { open, close } from 'fs'; + * open('myfile', 'wx', (err, fd) => { + * if (err) { + * if (err.code === 'EEXIST') { + * console.error('myfile already exists'); + * return; + * } + * + * throw err; + * } + * + * try { + * writeMyData(fd); + * } finally { + * close(fd, (err) => { + * if (err) throw err; + * }); + * } + * }); + * ``` + * + * **read (NOT RECOMMENDED)** + * + * ```js + * import { open, close, exists } from 'fs'; + * + * exists('myfile', (e) => { + * if (e) { + * open('myfile', 'r', (err, fd) => { + * if (err) throw err; + * + * try { + * readMyData(fd); + * } finally { + * close(fd, (err) => { + * if (err) throw err; + * }); + * } + * }); + * } else { + * console.error('myfile does not exist'); + * } + * }); + * ``` + * + * **read (RECOMMENDED)** + * + * ```js + * import { open, close } from 'fs'; + * + * open('myfile', 'r', (err, fd) => { + * if (err) { + * if (err.code === 'ENOENT') { + * console.error('myfile does not exist'); + * return; + * } + * + * throw err; + * } + * + * try { + * readMyData(fd); + * } finally { + * close(fd, (err) => { + * if (err) throw err; + * }); + * } + * }); + * ``` + * + * The "not recommended" examples above check for existence and then use the + * file; the "recommended" examples are better because they use the file directly + * and handle the error, if any. + * + * In general, check for the existence of a file only if the file won’t be + * used directly, for example when its existence is a signal from another + * process. + * @since v0.0.2 + * @deprecated Since v1.0.0 - Use {@link stat} or {@link access} instead. + */ + export function exists(path: PathLike, callback: (exists: boolean) => void): void; + /** @deprecated */ + export namespace exists { + /** + * @param path A path to a file or directory. If a URL is provided, it must use the `file:` protocol. + * URL support is _experimental_. + */ + function __promisify__(path: PathLike): Promise; + } + /** + * Returns `true` if the path exists, `false` otherwise. + * + * For detailed information, see the documentation of the asynchronous version of + * this API: {@link exists}. + * + * `fs.exists()` is deprecated, but `fs.existsSync()` is not. The `callback`parameter to `fs.exists()` accepts parameters that are inconsistent with other + * Node.js callbacks. `fs.existsSync()` does not use a callback. + * + * ```js + * import { existsSync } from 'fs'; + * + * if (existsSync('/etc/passwd')) + * console.log('The path exists.'); + * ``` + * @since v0.1.21 + */ + export function existsSync(path: PathLike): boolean; + export namespace constants { + // File Access Constants + /** Constant for fs.access(). File is visible to the calling process. */ + const F_OK: number; + /** Constant for fs.access(). File can be read by the calling process. */ + const R_OK: number; + /** Constant for fs.access(). File can be written by the calling process. */ + const W_OK: number; + /** Constant for fs.access(). File can be executed by the calling process. */ + const X_OK: number; + // File Copy Constants + /** Constant for fs.copyFile. Flag indicating the destination file should not be overwritten if it already exists. */ + const COPYFILE_EXCL: number; + /** + * Constant for fs.copyFile. copy operation will attempt to create a copy-on-write reflink. + * If the underlying platform does not support copy-on-write, then a fallback copy mechanism is used. + */ + const COPYFILE_FICLONE: number; + /** + * Constant for fs.copyFile. Copy operation will attempt to create a copy-on-write reflink. + * If the underlying platform does not support copy-on-write, then the operation will fail with an error. + */ + const COPYFILE_FICLONE_FORCE: number; + // File Open Constants + /** Constant for fs.open(). Flag indicating to open a file for read-only access. */ + const O_RDONLY: number; + /** Constant for fs.open(). Flag indicating to open a file for write-only access. */ + const O_WRONLY: number; + /** Constant for fs.open(). Flag indicating to open a file for read-write access. */ + const O_RDWR: number; + /** Constant for fs.open(). Flag indicating to create the file if it does not already exist. */ + const O_CREAT: number; + /** Constant for fs.open(). Flag indicating that opening a file should fail if the O_CREAT flag is set and the file already exists. */ + const O_EXCL: number; + /** + * Constant for fs.open(). Flag indicating that if path identifies a terminal device, + * opening the path shall not cause that terminal to become the controlling terminal for the process + * (if the process does not already have one). + */ + const O_NOCTTY: number; + /** Constant for fs.open(). Flag indicating that if the file exists and is a regular file, and the file is opened successfully for write access, its length shall be truncated to zero. */ + const O_TRUNC: number; + /** Constant for fs.open(). Flag indicating that data will be appended to the end of the file. */ + const O_APPEND: number; + /** Constant for fs.open(). Flag indicating that the open should fail if the path is not a directory. */ + const O_DIRECTORY: number; + /** + * constant for fs.open(). + * Flag indicating reading accesses to the file system will no longer result in + * an update to the atime information associated with the file. + * This flag is available on Linux operating systems only. + */ + const O_NOATIME: number; + /** Constant for fs.open(). Flag indicating that the open should fail if the path is a symbolic link. */ + const O_NOFOLLOW: number; + /** Constant for fs.open(). Flag indicating that the file is opened for synchronous I/O. */ + const O_SYNC: number; + /** Constant for fs.open(). Flag indicating that the file is opened for synchronous I/O with write operations waiting for data integrity. */ + const O_DSYNC: number; + /** Constant for fs.open(). Flag indicating to open the symbolic link itself rather than the resource it is pointing to. */ + const O_SYMLINK: number; + /** Constant for fs.open(). When set, an attempt will be made to minimize caching effects of file I/O. */ + const O_DIRECT: number; + /** Constant for fs.open(). Flag indicating to open the file in nonblocking mode when possible. */ + const O_NONBLOCK: number; + // File Type Constants + /** Constant for fs.Stats mode property for determining a file's type. Bit mask used to extract the file type code. */ + const S_IFMT: number; + /** Constant for fs.Stats mode property for determining a file's type. File type constant for a regular file. */ + const S_IFREG: number; + /** Constant for fs.Stats mode property for determining a file's type. File type constant for a directory. */ + const S_IFDIR: number; + /** Constant for fs.Stats mode property for determining a file's type. File type constant for a character-oriented device file. */ + const S_IFCHR: number; + /** Constant for fs.Stats mode property for determining a file's type. File type constant for a block-oriented device file. */ + const S_IFBLK: number; + /** Constant for fs.Stats mode property for determining a file's type. File type constant for a FIFO/pipe. */ + const S_IFIFO: number; + /** Constant for fs.Stats mode property for determining a file's type. File type constant for a symbolic link. */ + const S_IFLNK: number; + /** Constant for fs.Stats mode property for determining a file's type. File type constant for a socket. */ + const S_IFSOCK: number; + // File Mode Constants + /** Constant for fs.Stats mode property for determining access permissions for a file. File mode indicating readable, writable and executable by owner. */ + const S_IRWXU: number; + /** Constant for fs.Stats mode property for determining access permissions for a file. File mode indicating readable by owner. */ + const S_IRUSR: number; + /** Constant for fs.Stats mode property for determining access permissions for a file. File mode indicating writable by owner. */ + const S_IWUSR: number; + /** Constant for fs.Stats mode property for determining access permissions for a file. File mode indicating executable by owner. */ + const S_IXUSR: number; + /** Constant for fs.Stats mode property for determining access permissions for a file. File mode indicating readable, writable and executable by group. */ + const S_IRWXG: number; + /** Constant for fs.Stats mode property for determining access permissions for a file. File mode indicating readable by group. */ + const S_IRGRP: number; + /** Constant for fs.Stats mode property for determining access permissions for a file. File mode indicating writable by group. */ + const S_IWGRP: number; + /** Constant for fs.Stats mode property for determining access permissions for a file. File mode indicating executable by group. */ + const S_IXGRP: number; + /** Constant for fs.Stats mode property for determining access permissions for a file. File mode indicating readable, writable and executable by others. */ + const S_IRWXO: number; + /** Constant for fs.Stats mode property for determining access permissions for a file. File mode indicating readable by others. */ + const S_IROTH: number; + /** Constant for fs.Stats mode property for determining access permissions for a file. File mode indicating writable by others. */ + const S_IWOTH: number; + /** Constant for fs.Stats mode property for determining access permissions for a file. File mode indicating executable by others. */ + const S_IXOTH: number; + /** + * When set, a memory file mapping is used to access the file. This flag + * is available on Windows operating systems only. On other operating systems, + * this flag is ignored. + */ + const UV_FS_O_FILEMAP: number; + } + /** + * Tests a user's permissions for the file or directory specified by `path`. + * The `mode` argument is an optional integer that specifies the accessibility + * checks to be performed. `mode` should be either the value `fs.constants.F_OK`or a mask consisting of the bitwise OR of any of `fs.constants.R_OK`,`fs.constants.W_OK`, and `fs.constants.X_OK` + * (e.g.`fs.constants.W_OK | fs.constants.R_OK`). Check `File access constants` for + * possible values of `mode`. + * + * The final argument, `callback`, is a callback function that is invoked with + * a possible error argument. If any of the accessibility checks fail, the error + * argument will be an `Error` object. The following examples check if`package.json` exists, and if it is readable or writable. + * + * ```js + * import { access, constants } from 'fs'; + * + * const file = 'package.json'; + * + * // Check if the file exists in the current directory. + * access(file, constants.F_OK, (err) => { + * console.log(`${file} ${err ? 'does not exist' : 'exists'}`); + * }); + * + * // Check if the file is readable. + * access(file, constants.R_OK, (err) => { + * console.log(`${file} ${err ? 'is not readable' : 'is readable'}`); + * }); + * + * // Check if the file is writable. + * access(file, constants.W_OK, (err) => { + * console.log(`${file} ${err ? 'is not writable' : 'is writable'}`); + * }); + * + * // Check if the file is readable and writable. + * access(file, constants.R_OK | constants.W_OK, (err) => { + * console.log(`${file} ${err ? 'is not' : 'is'} readable and writable`); + * }); + * ``` + * + * Do not use `fs.access()` to check for the accessibility of a file before calling`fs.open()`, `fs.readFile()` or `fs.writeFile()`. Doing + * so introduces a race condition, since other processes may change the file's + * state between the two calls. Instead, user code should open/read/write the + * file directly and handle the error raised if the file is not accessible. + * + * **write (NOT RECOMMENDED)** + * + * ```js + * import { access, open, close } from 'fs'; + * + * access('myfile', (err) => { + * if (!err) { + * console.error('myfile already exists'); + * return; + * } + * + * open('myfile', 'wx', (err, fd) => { + * if (err) throw err; + * + * try { + * writeMyData(fd); + * } finally { + * close(fd, (err) => { + * if (err) throw err; + * }); + * } + * }); + * }); + * ``` + * + * **write (RECOMMENDED)** + * + * ```js + * import { open, close } from 'fs'; + * + * open('myfile', 'wx', (err, fd) => { + * if (err) { + * if (err.code === 'EEXIST') { + * console.error('myfile already exists'); + * return; + * } + * + * throw err; + * } + * + * try { + * writeMyData(fd); + * } finally { + * close(fd, (err) => { + * if (err) throw err; + * }); + * } + * }); + * ``` + * + * **read (NOT RECOMMENDED)** + * + * ```js + * import { access, open, close } from 'fs'; + * access('myfile', (err) => { + * if (err) { + * if (err.code === 'ENOENT') { + * console.error('myfile does not exist'); + * return; + * } + * + * throw err; + * } + * + * open('myfile', 'r', (err, fd) => { + * if (err) throw err; + * + * try { + * readMyData(fd); + * } finally { + * close(fd, (err) => { + * if (err) throw err; + * }); + * } + * }); + * }); + * ``` + * + * **read (RECOMMENDED)** + * + * ```js + * import { open, close } from 'fs'; + * + * open('myfile', 'r', (err, fd) => { + * if (err) { + * if (err.code === 'ENOENT') { + * console.error('myfile does not exist'); + * return; + * } + * + * throw err; + * } + * + * try { + * readMyData(fd); + * } finally { + * close(fd, (err) => { + * if (err) throw err; + * }); + * } + * }); + * ``` + * + * The "not recommended" examples above check for accessibility and then use the + * file; the "recommended" examples are better because they use the file directly + * and handle the error, if any. + * + * In general, check for the accessibility of a file only if the file will not be + * used directly, for example when its accessibility is a signal from another + * process. + * + * On Windows, access-control policies (ACLs) on a directory may limit access to + * a file or directory. The `fs.access()` function, however, does not check the + * ACL and therefore may report that a path is accessible even if the ACL restricts + * the user from reading or writing to it. + * @since v0.11.15 + * @param [mode=fs.constants.F_OK] + */ + export function access(path: PathLike, mode: number | undefined, callback: NoParamCallback): void; + /** + * Asynchronously tests a user's permissions for the file specified by path. + * @param path A path to a file or directory. If a URL is provided, it must use the `file:` protocol. + */ + export function access(path: PathLike, callback: NoParamCallback): void; + export namespace access { + /** + * Asynchronously tests a user's permissions for the file specified by path. + * @param path A path to a file or directory. If a URL is provided, it must use the `file:` protocol. + * URL support is _experimental_. + */ + function __promisify__(path: PathLike, mode?: number): Promise; + } + /** + * Synchronously tests a user's permissions for the file or directory specified + * by `path`. The `mode` argument is an optional integer that specifies the + * accessibility checks to be performed. `mode` should be either the value`fs.constants.F_OK` or a mask consisting of the bitwise OR of any of`fs.constants.R_OK`, `fs.constants.W_OK`, and + * `fs.constants.X_OK` (e.g.`fs.constants.W_OK | fs.constants.R_OK`). Check `File access constants` for + * possible values of `mode`. + * + * If any of the accessibility checks fail, an `Error` will be thrown. Otherwise, + * the method will return `undefined`. + * + * ```js + * import { accessSync, constants } from 'fs'; + * + * try { + * accessSync('etc/passwd', constants.R_OK | constants.W_OK); + * console.log('can read/write'); + * } catch (err) { + * console.error('no access!'); + * } + * ``` + * @since v0.11.15 + * @param [mode=fs.constants.F_OK] + */ + export function accessSync(path: PathLike, mode?: number): void; + interface StreamOptions { + flags?: string | undefined; + encoding?: BufferEncoding | undefined; + fd?: number | promises.FileHandle | undefined; + mode?: number | undefined; + autoClose?: boolean | undefined; + /** + * @default false + */ + emitClose?: boolean | undefined; + start?: number | undefined; + highWaterMark?: number | undefined; + } + interface ReadStreamOptions extends StreamOptions { + end?: number | undefined; + } + /** + * Unlike the 16 kb default `highWaterMark` for a `stream.Readable`, the stream + * returned by this method has a default `highWaterMark` of 64 kb. + * + * `options` can include `start` and `end` values to read a range of bytes from + * the file instead of the entire file. Both `start` and `end` are inclusive and + * start counting at 0, allowed values are in the + * \[0, [`Number.MAX_SAFE_INTEGER`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/MAX_SAFE_INTEGER)\] range. If `fd` is specified and `start` is + * omitted or `undefined`, `fs.createReadStream()` reads sequentially from the + * current file position. The `encoding` can be any one of those accepted by `Buffer`. + * + * If `fd` is specified, `ReadStream` will ignore the `path` argument and will use + * the specified file descriptor. This means that no `'open'` event will be + * emitted. `fd` should be blocking; non-blocking `fd`s should be passed to `net.Socket`. + * + * If `fd` points to a character device that only supports blocking reads + * (such as keyboard or sound card), read operations do not finish until data is + * available. This can prevent the process from exiting and the stream from + * closing naturally. + * + * By default, the stream will emit a `'close'` event after it has been + * destroyed. Set the `emitClose` option to `false` to change this behavior. + * + * By providing the `fs` option, it is possible to override the corresponding `fs`implementations for `open`, `read`, and `close`. When providing the `fs` option, + * an override for `read` is required. If no `fd` is provided, an override for`open` is also required. If `autoClose` is `true`, an override for `close` is + * also required. + * + * ```js + * import { createReadStream } from 'fs'; + * + * // Create a stream from some character device. + * const stream = createReadStream('/dev/input/event0'); + * setTimeout(() => { + * stream.close(); // This may not close the stream. + * // Artificially marking end-of-stream, as if the underlying resource had + * // indicated end-of-file by itself, allows the stream to close. + * // This does not cancel pending read operations, and if there is such an + * // operation, the process may still not be able to exit successfully + * // until it finishes. + * stream.push(null); + * stream.read(0); + * }, 100); + * ``` + * + * If `autoClose` is false, then the file descriptor won't be closed, even if + * there's an error. It is the application's responsibility to close it and make + * sure there's no file descriptor leak. If `autoClose` is set to true (default + * behavior), on `'error'` or `'end'` the file descriptor will be closed + * automatically. + * + * `mode` sets the file mode (permission and sticky bits), but only if the + * file was created. + * + * An example to read the last 10 bytes of a file which is 100 bytes long: + * + * ```js + * import { createReadStream } from 'fs'; + * + * createReadStream('sample.txt', { start: 90, end: 99 }); + * ``` + * + * If `options` is a string, then it specifies the encoding. + * @since v0.1.31 + */ + export function createReadStream(path: PathLike, options?: BufferEncoding | ReadStreamOptions): ReadStream; + /** + * `options` may also include a `start` option to allow writing data at some + * position past the beginning of the file, allowed values are in the + * \[0, [`Number.MAX_SAFE_INTEGER`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/MAX_SAFE_INTEGER)\] range. Modifying a file rather than + * replacing it may require the `flags` option to be set to `r+` rather than the + * default `w`. The `encoding` can be any one of those accepted by `Buffer`. + * + * If `autoClose` is set to true (default behavior) on `'error'` or `'finish'`the file descriptor will be closed automatically. If `autoClose` is false, + * then the file descriptor won't be closed, even if there's an error. + * It is the application's responsibility to close it and make sure there's no + * file descriptor leak. + * + * By default, the stream will emit a `'close'` event after it has been + * destroyed. Set the `emitClose` option to `false` to change this behavior. + * + * By providing the `fs` option it is possible to override the corresponding `fs`implementations for `open`, `write`, `writev` and `close`. Overriding `write()`without `writev()` can reduce + * performance as some optimizations (`_writev()`) + * will be disabled. When providing the `fs` option, overrides for at least one of`write` and `writev` are required. If no `fd` option is supplied, an override + * for `open` is also required. If `autoClose` is `true`, an override for `close`is also required. + * + * Like `fs.ReadStream`, if `fd` is specified, `fs.WriteStream` will ignore the`path` argument and will use the specified file descriptor. This means that no`'open'` event will be + * emitted. `fd` should be blocking; non-blocking `fd`s + * should be passed to `net.Socket`. + * + * If `options` is a string, then it specifies the encoding. + * @since v0.1.31 + */ + export function createWriteStream(path: PathLike, options?: BufferEncoding | StreamOptions): WriteStream; + /** + * Forces all currently queued I/O operations associated with the file to the + * operating system's synchronized I/O completion state. Refer to the POSIX [`fdatasync(2)`](http://man7.org/linux/man-pages/man2/fdatasync.2.html) documentation for details. No arguments other + * than a possible + * exception are given to the completion callback. + * @since v0.1.96 + */ + export function fdatasync(fd: number, callback: NoParamCallback): void; + export namespace fdatasync { + /** + * Asynchronous fdatasync(2) - synchronize a file's in-core state with storage device. + * @param fd A file descriptor. + */ + function __promisify__(fd: number): Promise; + } + /** + * Forces all currently queued I/O operations associated with the file to the + * operating system's synchronized I/O completion state. Refer to the POSIX [`fdatasync(2)`](http://man7.org/linux/man-pages/man2/fdatasync.2.html) documentation for details. Returns `undefined`. + * @since v0.1.96 + */ + export function fdatasyncSync(fd: number): void; + /** + * Asynchronously copies `src` to `dest`. By default, `dest` is overwritten if it + * already exists. No arguments other than a possible exception are given to the + * callback function. Node.js makes no guarantees about the atomicity of the copy + * operation. If an error occurs after the destination file has been opened for + * writing, Node.js will attempt to remove the destination. + * + * `mode` is an optional integer that specifies the behavior + * of the copy operation. It is possible to create a mask consisting of the bitwise + * OR of two or more values (e.g.`fs.constants.COPYFILE_EXCL | fs.constants.COPYFILE_FICLONE`). + * + * * `fs.constants.COPYFILE_EXCL`: The copy operation will fail if `dest` already + * exists. + * * `fs.constants.COPYFILE_FICLONE`: The copy operation will attempt to create a + * copy-on-write reflink. If the platform does not support copy-on-write, then a + * fallback copy mechanism is used. + * * `fs.constants.COPYFILE_FICLONE_FORCE`: The copy operation will attempt to + * create a copy-on-write reflink. If the platform does not support + * copy-on-write, then the operation will fail. + * + * ```js + * import { copyFile, constants } from 'fs'; + * + * function callback(err) { + * if (err) throw err; + * console.log('source.txt was copied to destination.txt'); + * } + * + * // destination.txt will be created or overwritten by default. + * copyFile('source.txt', 'destination.txt', callback); + * + * // By using COPYFILE_EXCL, the operation will fail if destination.txt exists. + * copyFile('source.txt', 'destination.txt', constants.COPYFILE_EXCL, callback); + * ``` + * @since v8.5.0 + * @param src source filename to copy + * @param dest destination filename of the copy operation + * @param [mode=0] modifiers for copy operation. + */ + export function copyFile(src: PathLike, dest: PathLike, callback: NoParamCallback): void; + export function copyFile(src: PathLike, dest: PathLike, mode: number, callback: NoParamCallback): void; + export namespace copyFile { + function __promisify__(src: PathLike, dst: PathLike, mode?: number): Promise; + } + /** + * Synchronously copies `src` to `dest`. By default, `dest` is overwritten if it + * already exists. Returns `undefined`. Node.js makes no guarantees about the + * atomicity of the copy operation. If an error occurs after the destination file + * has been opened for writing, Node.js will attempt to remove the destination. + * + * `mode` is an optional integer that specifies the behavior + * of the copy operation. It is possible to create a mask consisting of the bitwise + * OR of two or more values (e.g.`fs.constants.COPYFILE_EXCL | fs.constants.COPYFILE_FICLONE`). + * + * * `fs.constants.COPYFILE_EXCL`: The copy operation will fail if `dest` already + * exists. + * * `fs.constants.COPYFILE_FICLONE`: The copy operation will attempt to create a + * copy-on-write reflink. If the platform does not support copy-on-write, then a + * fallback copy mechanism is used. + * * `fs.constants.COPYFILE_FICLONE_FORCE`: The copy operation will attempt to + * create a copy-on-write reflink. If the platform does not support + * copy-on-write, then the operation will fail. + * + * ```js + * import { copyFileSync, constants } from 'fs'; + * + * // destination.txt will be created or overwritten by default. + * copyFileSync('source.txt', 'destination.txt'); + * console.log('source.txt was copied to destination.txt'); + * + * // By using COPYFILE_EXCL, the operation will fail if destination.txt exists. + * copyFileSync('source.txt', 'destination.txt', constants.COPYFILE_EXCL); + * ``` + * @since v8.5.0 + * @param src source filename to copy + * @param dest destination filename of the copy operation + * @param [mode=0] modifiers for copy operation. + */ + export function copyFileSync(src: PathLike, dest: PathLike, mode?: number): void; + /** + * Write an array of `ArrayBufferView`s to the file specified by `fd` using`writev()`. + * + * `position` is the offset from the beginning of the file where this data + * should be written. If `typeof position !== 'number'`, the data will be written + * at the current position. + * + * The callback will be given three arguments: `err`, `bytesWritten`, and`buffers`. `bytesWritten` is how many bytes were written from `buffers`. + * + * If this method is `util.promisify()` ed, it returns a promise for an`Object` with `bytesWritten` and `buffers` properties. + * + * It is unsafe to use `fs.writev()` multiple times on the same file without + * waiting for the callback. For this scenario, use {@link createWriteStream}. + * + * On Linux, positional writes don't work when the file is opened in append mode. + * The kernel ignores the position argument and always appends the data to + * the end of the file. + * @since v12.9.0 + */ + export function writev(fd: number, buffers: ReadonlyArray, cb: (err: NodeJS.ErrnoException | null, bytesWritten: number, buffers: NodeJS.ArrayBufferView[]) => void): void; + export function writev( + fd: number, + buffers: ReadonlyArray, + position: number, + cb: (err: NodeJS.ErrnoException | null, bytesWritten: number, buffers: NodeJS.ArrayBufferView[]) => void + ): void; + export interface WriteVResult { + bytesWritten: number; + buffers: NodeJS.ArrayBufferView[]; + } + export namespace writev { + function __promisify__(fd: number, buffers: ReadonlyArray, position?: number): Promise; + } + /** + * For detailed information, see the documentation of the asynchronous version of + * this API: {@link writev}. + * @since v12.9.0 + * @return The number of bytes written. + */ + export function writevSync(fd: number, buffers: ReadonlyArray, position?: number): number; + /** + * Read from a file specified by `fd` and write to an array of `ArrayBufferView`s + * using `readv()`. + * + * `position` is the offset from the beginning of the file from where data + * should be read. If `typeof position !== 'number'`, the data will be read + * from the current position. + * + * The callback will be given three arguments: `err`, `bytesRead`, and`buffers`. `bytesRead` is how many bytes were read from the file. + * + * If this method is invoked as its `util.promisify()` ed version, it returns + * a promise for an `Object` with `bytesRead` and `buffers` properties. + * @since v13.13.0, v12.17.0 + */ + export function readv(fd: number, buffers: ReadonlyArray, cb: (err: NodeJS.ErrnoException | null, bytesRead: number, buffers: NodeJS.ArrayBufferView[]) => void): void; + export function readv( + fd: number, + buffers: ReadonlyArray, + position: number, + cb: (err: NodeJS.ErrnoException | null, bytesRead: number, buffers: NodeJS.ArrayBufferView[]) => void + ): void; + export interface ReadVResult { + bytesRead: number; + buffers: NodeJS.ArrayBufferView[]; + } + export namespace readv { + function __promisify__(fd: number, buffers: ReadonlyArray, position?: number): Promise; + } + /** + * For detailed information, see the documentation of the asynchronous version of + * this API: {@link readv}. + * @since v13.13.0, v12.17.0 + * @return The number of bytes read. + */ + export function readvSync(fd: number, buffers: ReadonlyArray, position?: number): number; + export interface OpenDirOptions { + encoding?: BufferEncoding | undefined; + /** + * Number of directory entries that are buffered + * internally when reading from the directory. Higher values lead to better + * performance but higher memory usage. + * @default 32 + */ + bufferSize?: number | undefined; + } + /** + * Synchronously open a directory. See [`opendir(3)`](http://man7.org/linux/man-pages/man3/opendir.3.html). + * + * Creates an `fs.Dir`, which contains all further functions for reading from + * and cleaning up the directory. + * + * The `encoding` option sets the encoding for the `path` while opening the + * directory and subsequent read operations. + * @since v12.12.0 + */ + export function opendirSync(path: PathLike, options?: OpenDirOptions): Dir; + /** + * Asynchronously open a directory. See the POSIX [`opendir(3)`](http://man7.org/linux/man-pages/man3/opendir.3.html) documentation for + * more details. + * + * Creates an `fs.Dir`, which contains all further functions for reading from + * and cleaning up the directory. + * + * The `encoding` option sets the encoding for the `path` while opening the + * directory and subsequent read operations. + * @since v12.12.0 + */ + export function opendir(path: PathLike, cb: (err: NodeJS.ErrnoException | null, dir: Dir) => void): void; + export function opendir(path: PathLike, options: OpenDirOptions, cb: (err: NodeJS.ErrnoException | null, dir: Dir) => void): void; + export namespace opendir { + function __promisify__(path: PathLike, options?: OpenDirOptions): Promise; + } + export interface BigIntStats extends StatsBase { + atimeNs: bigint; + mtimeNs: bigint; + ctimeNs: bigint; + birthtimeNs: bigint; + } + export interface BigIntOptions { + bigint: true; + } + export interface StatOptions { + bigint?: boolean | undefined; + } + export interface StatSyncOptions extends StatOptions { + throwIfNoEntry?: boolean | undefined; + } + export interface CopyOptions { + /** + * Dereference symlinks + * @default false + */ + dereference?: boolean; + /** + * When `force` is `false`, and the destination + * exists, throw an error. + * @default false + */ + errorOnExist?: boolean; + /** + * Function to filter copied files/directories. Return + * `true` to copy the item, `false` to ignore it. + */ + filter?(source: string, destination: string): boolean; + /** + * Overwrite existing file or directory. _The copy + * operation will ignore errors if you set this to false and the destination + * exists. Use the `errorOnExist` option to change this behavior. + * @default true + */ + force?: boolean; + /** + * When `true` timestamps from `src` will + * be preserved. + * @default false + */ + preserveTimestamps?: boolean; + /** + * Copy directories recursively. + * @default false + */ + recursive?: boolean; + } + /** + * Asynchronously copies the entire directory structure from `src` to `dest`, + * including subdirectories and files. + * + * When copying a directory to another directory, globs are not supported and + * behavior is similar to `cp dir1/ dir2/`. + * @since v16.7.0 + * @experimental + * @param src source path to copy. + * @param dest destination path to copy to. + */ + export function cp(source: string | URL, destination: string | URL, callback: (err: NodeJS.ErrnoException | null) => void): void; + export function cp(source: string | URL, destination: string | URL, opts: CopyOptions, callback: (err: NodeJS.ErrnoException | null) => void): void; + /** + * Synchronously copies the entire directory structure from `src` to `dest`, + * including subdirectories and files. + * + * When copying a directory to another directory, globs are not supported and + * behavior is similar to `cp dir1/ dir2/`. + * @since v16.7.0 + * @experimental + * @param src source path to copy. + * @param dest destination path to copy to. + */ + export function cpSync(source: string | URL, destination: string | URL, opts?: CopyOptions): void; +} +declare module 'node:fs' { + export * from 'fs'; +} diff --git a/ts-ticket-office-service/node_modules/@types/node/fs/promises.d.ts b/ts-ticket-office-service/node_modules/@types/node/fs/promises.d.ts new file mode 100755 index 000000000..2759883e2 --- /dev/null +++ b/ts-ticket-office-service/node_modules/@types/node/fs/promises.d.ts @@ -0,0 +1,1114 @@ +/** + * The `fs/promises` API provides asynchronous file system methods that return + * promises. + * + * The promise APIs use the underlying Node.js threadpool to perform file + * system operations off the event loop thread. These operations are not + * synchronized or threadsafe. Care must be taken when performing multiple + * concurrent modifications on the same file or data corruption may occur. + * @since v10.0.0 + */ +declare module 'fs/promises' { + import { Abortable } from 'node:events'; + import { Stream } from 'node:stream'; + import { ReadableStream } from 'node:stream/web'; + import { + Stats, + BigIntStats, + StatOptions, + WriteVResult, + ReadVResult, + PathLike, + RmDirOptions, + RmOptions, + MakeDirectoryOptions, + Dirent, + OpenDirOptions, + Dir, + ObjectEncodingOptions, + BufferEncodingOption, + OpenMode, + Mode, + WatchOptions, + WatchEventType, + CopyOptions, + ReadStream, + WriteStream, + } from 'node:fs'; + interface FileChangeInfo { + eventType: WatchEventType; + filename: T; + } + interface FlagAndOpenMode { + mode?: Mode | undefined; + flag?: OpenMode | undefined; + } + interface FileReadResult { + bytesRead: number; + buffer: T; + } + interface FileReadOptions { + /** + * @default `Buffer.alloc(0xffff)` + */ + buffer?: T; + /** + * @default 0 + */ + offset?: number | null; + /** + * @default `buffer.byteLength` + */ + length?: number | null; + position?: number | null; + } + interface CreateReadStreamOptions { + encoding?: BufferEncoding | null | undefined; + autoClose?: boolean | undefined; + emitClose?: boolean | undefined; + start?: number | undefined; + end?: number | undefined; + highWaterMark?: number | undefined; + } + interface CreateWriteStreamOptions { + encoding?: BufferEncoding | null | undefined; + autoClose?: boolean | undefined; + emitClose?: boolean | undefined; + start?: number | undefined; + } + // TODO: Add `EventEmitter` close + interface FileHandle { + /** + * The numeric file descriptor managed by the {FileHandle} object. + * @since v10.0.0 + */ + readonly fd: number; + /** + * Alias of `filehandle.writeFile()`. + * + * When operating on file handles, the mode cannot be changed from what it was set + * to with `fsPromises.open()`. Therefore, this is equivalent to `filehandle.writeFile()`. + * @since v10.0.0 + * @return Fulfills with `undefined` upon success. + */ + appendFile(data: string | Uint8Array, options?: (ObjectEncodingOptions & FlagAndOpenMode) | BufferEncoding | null): Promise; + /** + * Changes the ownership of the file. A wrapper for [`chown(2)`](http://man7.org/linux/man-pages/man2/chown.2.html). + * @since v10.0.0 + * @param uid The file's new owner's user id. + * @param gid The file's new group's group id. + * @return Fulfills with `undefined` upon success. + */ + chown(uid: number, gid: number): Promise; + /** + * Modifies the permissions on the file. See [`chmod(2)`](http://man7.org/linux/man-pages/man2/chmod.2.html). + * @since v10.0.0 + * @param mode the file mode bit mask. + * @return Fulfills with `undefined` upon success. + */ + chmod(mode: Mode): Promise; + /** + * Unlike the 16 kb default `highWaterMark` for a `stream.Readable`, the stream + * returned by this method has a default `highWaterMark` of 64 kb. + * + * `options` can include `start` and `end` values to read a range of bytes from + * the file instead of the entire file. Both `start` and `end` are inclusive and + * start counting at 0, allowed values are in the + * \[0, [`Number.MAX_SAFE_INTEGER`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/MAX_SAFE_INTEGER)\] range. If `start` is + * omitted or `undefined`, `filehandle.createReadStream()` reads sequentially from + * the current file position. The `encoding` can be any one of those accepted by `Buffer`. + * + * If the `FileHandle` points to a character device that only supports blocking + * reads (such as keyboard or sound card), read operations do not finish until data + * is available. This can prevent the process from exiting and the stream from + * closing naturally. + * + * By default, the stream will emit a `'close'` event after it has been + * destroyed. Set the `emitClose` option to `false` to change this behavior. + * + * ```js + * import { open } from 'fs/promises'; + * + * const fd = await open('/dev/input/event0'); + * // Create a stream from some character device. + * const stream = fd.createReadStream(); + * setTimeout(() => { + * stream.close(); // This may not close the stream. + * // Artificially marking end-of-stream, as if the underlying resource had + * // indicated end-of-file by itself, allows the stream to close. + * // This does not cancel pending read operations, and if there is such an + * // operation, the process may still not be able to exit successfully + * // until it finishes. + * stream.push(null); + * stream.read(0); + * }, 100); + * ``` + * + * If `autoClose` is false, then the file descriptor won't be closed, even if + * there's an error. It is the application's responsibility to close it and make + * sure there's no file descriptor leak. If `autoClose` is set to true (default + * behavior), on `'error'` or `'end'` the file descriptor will be closed + * automatically. + * + * An example to read the last 10 bytes of a file which is 100 bytes long: + * + * ```js + * import { open } from 'fs/promises'; + * + * const fd = await open('sample.txt'); + * fd.createReadStream({ start: 90, end: 99 }); + * ``` + * @since v16.11.0 + */ + createReadStream(options?: CreateReadStreamOptions): ReadStream; + /** + * `options` may also include a `start` option to allow writing data at some + * position past the beginning of the file, allowed values are in the + * \[0, [`Number.MAX_SAFE_INTEGER`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/MAX_SAFE_INTEGER)\] range. Modifying a file rather than + * replacing it may require the `flags` `open` option to be set to `r+` rather than + * the default `r`. The `encoding` can be any one of those accepted by `Buffer`. + * + * If `autoClose` is set to true (default behavior) on `'error'` or `'finish'`the file descriptor will be closed automatically. If `autoClose` is false, + * then the file descriptor won't be closed, even if there's an error. + * It is the application's responsibility to close it and make sure there's no + * file descriptor leak. + * + * By default, the stream will emit a `'close'` event after it has been + * destroyed. Set the `emitClose` option to `false` to change this behavior. + * @since v16.11.0 + */ + createWriteStream(options?: CreateWriteStreamOptions): WriteStream; + /** + * Forces all currently queued I/O operations associated with the file to the + * operating system's synchronized I/O completion state. Refer to the POSIX [`fdatasync(2)`](http://man7.org/linux/man-pages/man2/fdatasync.2.html) documentation for details. + * + * Unlike `filehandle.sync` this method does not flush modified metadata. + * @since v10.0.0 + * @return Fulfills with `undefined` upon success. + */ + datasync(): Promise; + /** + * Request that all data for the open file descriptor is flushed to the storage + * device. The specific implementation is operating system and device specific. + * Refer to the POSIX [`fsync(2)`](http://man7.org/linux/man-pages/man2/fsync.2.html) documentation for more detail. + * @since v10.0.0 + * @return Fufills with `undefined` upon success. + */ + sync(): Promise; + /** + * Reads data from the file and stores that in the given buffer. + * + * If the file is not modified concurrently, the end-of-file is reached when the + * number of bytes read is zero. + * @since v10.0.0 + * @param buffer A buffer that will be filled with the file data read. + * @param offset The location in the buffer at which to start filling. + * @param length The number of bytes to read. + * @param position The location where to begin reading data from the file. If `null`, data will be read from the current file position, and the position will be updated. If `position` is an + * integer, the current file position will remain unchanged. + * @return Fulfills upon success with an object with two properties: + */ + read(buffer: T, offset?: number | null, length?: number | null, position?: number | null): Promise>; + read(options?: FileReadOptions): Promise>; + /** + * Returns a `ReadableStream` that may be used to read the files data. + * + * An error will be thrown if this method is called more than once or is called after the `FileHandle` is closed + * or closing. + * + * ```js + * import { open } from 'node:fs/promises'; + * + * const file = await open('./some/file/to/read'); + * + * for await (const chunk of file.readableWebStream()) + * console.log(chunk); + * + * await file.close(); + * ``` + * + * While the `ReadableStream` will read the file to completion, it will not close the `FileHandle` automatically. User code must still call the `fileHandle.close()` method. + * + * @since v17.0.0 + * @experimental + */ + readableWebStream(): ReadableStream; + /** + * Asynchronously reads the entire contents of a file. + * + * If `options` is a string, then it specifies the `encoding`. + * + * The `FileHandle` has to support reading. + * + * If one or more `filehandle.read()` calls are made on a file handle and then a`filehandle.readFile()` call is made, the data will be read from the current + * position till the end of the file. It doesn't always read from the beginning + * of the file. + * @since v10.0.0 + * @return Fulfills upon a successful read with the contents of the file. If no encoding is specified (using `options.encoding`), the data is returned as a {Buffer} object. Otherwise, the + * data will be a string. + */ + readFile( + options?: { + encoding?: null | undefined; + flag?: OpenMode | undefined; + } | null + ): Promise; + /** + * Asynchronously reads the entire contents of a file. The underlying file will _not_ be closed automatically. + * The `FileHandle` must have been opened for reading. + * @param options An object that may contain an optional flag. + * If a flag is not provided, it defaults to `'r'`. + */ + readFile( + options: + | { + encoding: BufferEncoding; + flag?: OpenMode | undefined; + } + | BufferEncoding + ): Promise; + /** + * Asynchronously reads the entire contents of a file. The underlying file will _not_ be closed automatically. + * The `FileHandle` must have been opened for reading. + * @param options An object that may contain an optional flag. + * If a flag is not provided, it defaults to `'r'`. + */ + readFile( + options?: + | (ObjectEncodingOptions & { + flag?: OpenMode | undefined; + }) + | BufferEncoding + | null + ): Promise; + /** + * @since v10.0.0 + * @return Fulfills with an {fs.Stats} for the file. + */ + stat( + opts?: StatOptions & { + bigint?: false | undefined; + } + ): Promise; + stat( + opts: StatOptions & { + bigint: true; + } + ): Promise; + stat(opts?: StatOptions): Promise; + /** + * Truncates the file. + * + * If the file was larger than `len` bytes, only the first `len` bytes will be + * retained in the file. + * + * The following example retains only the first four bytes of the file: + * + * ```js + * import { open } from 'fs/promises'; + * + * let filehandle = null; + * try { + * filehandle = await open('temp.txt', 'r+'); + * await filehandle.truncate(4); + * } finally { + * await filehandle?.close(); + * } + * ``` + * + * If the file previously was shorter than `len` bytes, it is extended, and the + * extended part is filled with null bytes (`'\0'`): + * + * If `len` is negative then `0` will be used. + * @since v10.0.0 + * @param [len=0] + * @return Fulfills with `undefined` upon success. + */ + truncate(len?: number): Promise; + /** + * Change the file system timestamps of the object referenced by the `FileHandle` then resolves the promise with no arguments upon success. + * @since v10.0.0 + */ + utimes(atime: string | number | Date, mtime: string | number | Date): Promise; + /** + * Asynchronously writes data to a file, replacing the file if it already exists.`data` can be a string, a buffer, an + * [AsyncIterable](https://tc39.github.io/ecma262/#sec-asynciterable-interface) or + * [Iterable](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols#The_iterable_protocol) object. + * The promise is resolved with no arguments upon success. + * + * If `options` is a string, then it specifies the `encoding`. + * + * The `FileHandle` has to support writing. + * + * It is unsafe to use `filehandle.writeFile()` multiple times on the same file + * without waiting for the promise to be resolved (or rejected). + * + * If one or more `filehandle.write()` calls are made on a file handle and then a`filehandle.writeFile()` call is made, the data will be written from the + * current position till the end of the file. It doesn't always write from the + * beginning of the file. + * @since v10.0.0 + */ + writeFile(data: string | Uint8Array, options?: (ObjectEncodingOptions & FlagAndOpenMode & Abortable) | BufferEncoding | null): Promise; + /** + * Write `buffer` to the file. + * + * The promise is resolved with an object containing two properties: + * + * It is unsafe to use `filehandle.write()` multiple times on the same file + * without waiting for the promise to be resolved (or rejected). For this + * scenario, use `filehandle.createWriteStream()`. + * + * On Linux, positional writes do not work when the file is opened in append mode. + * The kernel ignores the position argument and always appends the data to + * the end of the file. + * @since v10.0.0 + * @param [offset=0] The start position from within `buffer` where the data to write begins. + * @param [length=buffer.byteLength - offset] The number of bytes from `buffer` to write. + * @param position The offset from the beginning of the file where the data from `buffer` should be written. If `position` is not a `number`, the data will be written at the current position. + * See the POSIX pwrite(2) documentation for more detail. + */ + write( + buffer: TBuffer, + offset?: number | null, + length?: number | null, + position?: number | null + ): Promise<{ + bytesWritten: number; + buffer: TBuffer; + }>; + write( + data: string, + position?: number | null, + encoding?: BufferEncoding | null + ): Promise<{ + bytesWritten: number; + buffer: string; + }>; + /** + * Write an array of [ArrayBufferView](https://developer.mozilla.org/en-US/docs/Web/API/ArrayBufferView) s to the file. + * + * The promise is resolved with an object containing a two properties: + * + * It is unsafe to call `writev()` multiple times on the same file without waiting + * for the promise to be resolved (or rejected). + * + * On Linux, positional writes don't work when the file is opened in append mode. + * The kernel ignores the position argument and always appends the data to + * the end of the file. + * @since v12.9.0 + * @param position The offset from the beginning of the file where the data from `buffers` should be written. If `position` is not a `number`, the data will be written at the current + * position. + */ + writev(buffers: ReadonlyArray, position?: number): Promise; + /** + * Read from a file and write to an array of [ArrayBufferView](https://developer.mozilla.org/en-US/docs/Web/API/ArrayBufferView) s + * @since v13.13.0, v12.17.0 + * @param position The offset from the beginning of the file where the data should be read from. If `position` is not a `number`, the data will be read from the current position. + * @return Fulfills upon success an object containing two properties: + */ + readv(buffers: ReadonlyArray, position?: number): Promise; + /** + * Closes the file handle after waiting for any pending operation on the handle to + * complete. + * + * ```js + * import { open } from 'fs/promises'; + * + * let filehandle; + * try { + * filehandle = await open('thefile.txt', 'r'); + * } finally { + * await filehandle?.close(); + * } + * ``` + * @since v10.0.0 + * @return Fulfills with `undefined` upon success. + */ + close(): Promise; + } + /** + * Tests a user's permissions for the file or directory specified by `path`. + * The `mode` argument is an optional integer that specifies the accessibility + * checks to be performed. `mode` should be either the value `fs.constants.F_OK`or a mask consisting of the bitwise OR of any of `fs.constants.R_OK`,`fs.constants.W_OK`, and `fs.constants.X_OK` + * (e.g.`fs.constants.W_OK | fs.constants.R_OK`). Check `File access constants` for + * possible values of `mode`. + * + * If the accessibility check is successful, the promise is resolved with no + * value. If any of the accessibility checks fail, the promise is rejected + * with an [Error](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error) object. The following example checks if the file`/etc/passwd` can be read and + * written by the current process. + * + * ```js + * import { access } from 'fs/promises'; + * import { constants } from 'fs'; + * + * try { + * await access('/etc/passwd', constants.R_OK | constants.W_OK); + * console.log('can access'); + * } catch { + * console.error('cannot access'); + * } + * ``` + * + * Using `fsPromises.access()` to check for the accessibility of a file before + * calling `fsPromises.open()` is not recommended. Doing so introduces a race + * condition, since other processes may change the file's state between the two + * calls. Instead, user code should open/read/write the file directly and handle + * the error raised if the file is not accessible. + * @since v10.0.0 + * @param [mode=fs.constants.F_OK] + * @return Fulfills with `undefined` upon success. + */ + function access(path: PathLike, mode?: number): Promise; + /** + * Asynchronously copies `src` to `dest`. By default, `dest` is overwritten if it + * already exists. + * + * No guarantees are made about the atomicity of the copy operation. If an + * error occurs after the destination file has been opened for writing, an attempt + * will be made to remove the destination. + * + * ```js + * import { constants } from 'fs'; + * import { copyFile } from 'fs/promises'; + * + * try { + * await copyFile('source.txt', 'destination.txt'); + * console.log('source.txt was copied to destination.txt'); + * } catch { + * console.log('The file could not be copied'); + * } + * + * // By using COPYFILE_EXCL, the operation will fail if destination.txt exists. + * try { + * await copyFile('source.txt', 'destination.txt', constants.COPYFILE_EXCL); + * console.log('source.txt was copied to destination.txt'); + * } catch { + * console.log('The file could not be copied'); + * } + * ``` + * @since v10.0.0 + * @param src source filename to copy + * @param dest destination filename of the copy operation + * @param [mode=0] Optional modifiers that specify the behavior of the copy operation. It is possible to create a mask consisting of the bitwise OR of two or more values (e.g. + * `fs.constants.COPYFILE_EXCL | fs.constants.COPYFILE_FICLONE`) + * @return Fulfills with `undefined` upon success. + */ + function copyFile(src: PathLike, dest: PathLike, mode?: number): Promise; + /** + * Opens a `FileHandle`. + * + * Refer to the POSIX [`open(2)`](http://man7.org/linux/man-pages/man2/open.2.html) documentation for more detail. + * + * Some characters (`< > : " / \ | ? *`) are reserved under Windows as documented + * by [Naming Files, Paths, and Namespaces](https://docs.microsoft.com/en-us/windows/desktop/FileIO/naming-a-file). Under NTFS, if the filename contains + * a colon, Node.js will open a file system stream, as described by [this MSDN page](https://docs.microsoft.com/en-us/windows/desktop/FileIO/using-streams). + * @since v10.0.0 + * @param [flags='r'] See `support of file system `flags``. + * @param [mode=0o666] Sets the file mode (permission and sticky bits) if the file is created. + * @return Fulfills with a {FileHandle} object. + */ + function open(path: PathLike, flags?: string | number, mode?: Mode): Promise; + /** + * Renames `oldPath` to `newPath`. + * @since v10.0.0 + * @return Fulfills with `undefined` upon success. + */ + function rename(oldPath: PathLike, newPath: PathLike): Promise; + /** + * Truncates (shortens or extends the length) of the content at `path` to `len`bytes. + * @since v10.0.0 + * @param [len=0] + * @return Fulfills with `undefined` upon success. + */ + function truncate(path: PathLike, len?: number): Promise; + /** + * Removes the directory identified by `path`. + * + * Using `fsPromises.rmdir()` on a file (not a directory) results in the + * promise being rejected with an `ENOENT` error on Windows and an `ENOTDIR`error on POSIX. + * + * To get a behavior similar to the `rm -rf` Unix command, use `fsPromises.rm()` with options `{ recursive: true, force: true }`. + * @since v10.0.0 + * @return Fulfills with `undefined` upon success. + */ + function rmdir(path: PathLike, options?: RmDirOptions): Promise; + /** + * Removes files and directories (modeled on the standard POSIX `rm` utility). + * @since v14.14.0 + * @return Fulfills with `undefined` upon success. + */ + function rm(path: PathLike, options?: RmOptions): Promise; + /** + * Asynchronously creates a directory. + * + * The optional `options` argument can be an integer specifying `mode` (permission + * and sticky bits), or an object with a `mode` property and a `recursive`property indicating whether parent directories should be created. Calling`fsPromises.mkdir()` when `path` is a directory + * that exists results in a + * rejection only when `recursive` is false. + * @since v10.0.0 + * @return Upon success, fulfills with `undefined` if `recursive` is `false`, or the first directory path created if `recursive` is `true`. + */ + function mkdir( + path: PathLike, + options: MakeDirectoryOptions & { + recursive: true; + } + ): Promise; + /** + * Asynchronous mkdir(2) - create a directory. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options Either the file mode, or an object optionally specifying the file mode and whether parent folders + * should be created. If a string is passed, it is parsed as an octal integer. If not specified, defaults to `0o777`. + */ + function mkdir( + path: PathLike, + options?: + | Mode + | (MakeDirectoryOptions & { + recursive?: false | undefined; + }) + | null + ): Promise; + /** + * Asynchronous mkdir(2) - create a directory. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options Either the file mode, or an object optionally specifying the file mode and whether parent folders + * should be created. If a string is passed, it is parsed as an octal integer. If not specified, defaults to `0o777`. + */ + function mkdir(path: PathLike, options?: Mode | MakeDirectoryOptions | null): Promise; + /** + * Reads the contents of a directory. + * + * The optional `options` argument can be a string specifying an encoding, or an + * object with an `encoding` property specifying the character encoding to use for + * the filenames. If the `encoding` is set to `'buffer'`, the filenames returned + * will be passed as `Buffer` objects. + * + * If `options.withFileTypes` is set to `true`, the resolved array will contain `fs.Dirent` objects. + * + * ```js + * import { readdir } from 'fs/promises'; + * + * try { + * const files = await readdir(path); + * for (const file of files) + * console.log(file); + * } catch (err) { + * console.error(err); + * } + * ``` + * @since v10.0.0 + * @return Fulfills with an array of the names of the files in the directory excluding `'.'` and `'..'`. + */ + function readdir( + path: PathLike, + options?: + | (ObjectEncodingOptions & { + withFileTypes?: false | undefined; + }) + | BufferEncoding + | null + ): Promise; + /** + * Asynchronous readdir(3) - read a directory. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function readdir( + path: PathLike, + options: + | { + encoding: 'buffer'; + withFileTypes?: false | undefined; + } + | 'buffer' + ): Promise; + /** + * Asynchronous readdir(3) - read a directory. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function readdir( + path: PathLike, + options?: + | (ObjectEncodingOptions & { + withFileTypes?: false | undefined; + }) + | BufferEncoding + | null + ): Promise; + /** + * Asynchronous readdir(3) - read a directory. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options If called with `withFileTypes: true` the result data will be an array of Dirent. + */ + function readdir( + path: PathLike, + options: ObjectEncodingOptions & { + withFileTypes: true; + } + ): Promise; + /** + * Reads the contents of the symbolic link referred to by `path`. See the POSIX [`readlink(2)`](http://man7.org/linux/man-pages/man2/readlink.2.html) documentation for more detail. The promise is + * resolved with the`linkString` upon success. + * + * The optional `options` argument can be a string specifying an encoding, or an + * object with an `encoding` property specifying the character encoding to use for + * the link path returned. If the `encoding` is set to `'buffer'`, the link path + * returned will be passed as a `Buffer` object. + * @since v10.0.0 + * @return Fulfills with the `linkString` upon success. + */ + function readlink(path: PathLike, options?: ObjectEncodingOptions | BufferEncoding | null): Promise; + /** + * Asynchronous readlink(2) - read value of a symbolic link. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function readlink(path: PathLike, options: BufferEncodingOption): Promise; + /** + * Asynchronous readlink(2) - read value of a symbolic link. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function readlink(path: PathLike, options?: ObjectEncodingOptions | string | null): Promise; + /** + * Creates a symbolic link. + * + * The `type` argument is only used on Windows platforms and can be one of `'dir'`,`'file'`, or `'junction'`. Windows junction points require the destination path + * to be absolute. When using `'junction'`, the `target` argument will + * automatically be normalized to absolute path. + * @since v10.0.0 + * @param [type='file'] + * @return Fulfills with `undefined` upon success. + */ + function symlink(target: PathLike, path: PathLike, type?: string | null): Promise; + /** + * Equivalent to `fsPromises.stat()` unless `path` refers to a symbolic link, + * in which case the link itself is stat-ed, not the file that it refers to. + * Refer to the POSIX [`lstat(2)`](http://man7.org/linux/man-pages/man2/lstat.2.html) document for more detail. + * @since v10.0.0 + * @return Fulfills with the {fs.Stats} object for the given symbolic link `path`. + */ + function lstat( + path: PathLike, + opts?: StatOptions & { + bigint?: false | undefined; + } + ): Promise; + function lstat( + path: PathLike, + opts: StatOptions & { + bigint: true; + } + ): Promise; + function lstat(path: PathLike, opts?: StatOptions): Promise; + /** + * @since v10.0.0 + * @return Fulfills with the {fs.Stats} object for the given `path`. + */ + function stat( + path: PathLike, + opts?: StatOptions & { + bigint?: false | undefined; + } + ): Promise; + function stat( + path: PathLike, + opts: StatOptions & { + bigint: true; + } + ): Promise; + function stat(path: PathLike, opts?: StatOptions): Promise; + /** + * Creates a new link from the `existingPath` to the `newPath`. See the POSIX [`link(2)`](http://man7.org/linux/man-pages/man2/link.2.html) documentation for more detail. + * @since v10.0.0 + * @return Fulfills with `undefined` upon success. + */ + function link(existingPath: PathLike, newPath: PathLike): Promise; + /** + * If `path` refers to a symbolic link, then the link is removed without affecting + * the file or directory to which that link refers. If the `path` refers to a file + * path that is not a symbolic link, the file is deleted. See the POSIX [`unlink(2)`](http://man7.org/linux/man-pages/man2/unlink.2.html) documentation for more detail. + * @since v10.0.0 + * @return Fulfills with `undefined` upon success. + */ + function unlink(path: PathLike): Promise; + /** + * Changes the permissions of a file. + * @since v10.0.0 + * @return Fulfills with `undefined` upon success. + */ + function chmod(path: PathLike, mode: Mode): Promise; + /** + * Changes the permissions on a symbolic link. + * + * This method is only implemented on macOS. + * @deprecated Since v10.0.0 + * @return Fulfills with `undefined` upon success. + */ + function lchmod(path: PathLike, mode: Mode): Promise; + /** + * Changes the ownership on a symbolic link. + * @since v10.0.0 + * @return Fulfills with `undefined` upon success. + */ + function lchown(path: PathLike, uid: number, gid: number): Promise; + /** + * Changes the access and modification times of a file in the same way as `fsPromises.utimes()`, with the difference that if the path refers to a + * symbolic link, then the link is not dereferenced: instead, the timestamps of + * the symbolic link itself are changed. + * @since v14.5.0, v12.19.0 + * @return Fulfills with `undefined` upon success. + */ + function lutimes(path: PathLike, atime: string | number | Date, mtime: string | number | Date): Promise; + /** + * Changes the ownership of a file. + * @since v10.0.0 + * @return Fulfills with `undefined` upon success. + */ + function chown(path: PathLike, uid: number, gid: number): Promise; + /** + * Change the file system timestamps of the object referenced by `path`. + * + * The `atime` and `mtime` arguments follow these rules: + * + * * Values can be either numbers representing Unix epoch time, `Date`s, or a + * numeric string like `'123456789.0'`. + * * If the value can not be converted to a number, or is `NaN`, `Infinity` or`-Infinity`, an `Error` will be thrown. + * @since v10.0.0 + * @return Fulfills with `undefined` upon success. + */ + function utimes(path: PathLike, atime: string | number | Date, mtime: string | number | Date): Promise; + /** + * Determines the actual location of `path` using the same semantics as the`fs.realpath.native()` function. + * + * Only paths that can be converted to UTF8 strings are supported. + * + * The optional `options` argument can be a string specifying an encoding, or an + * object with an `encoding` property specifying the character encoding to use for + * the path. If the `encoding` is set to `'buffer'`, the path returned will be + * passed as a `Buffer` object. + * + * On Linux, when Node.js is linked against musl libc, the procfs file system must + * be mounted on `/proc` in order for this function to work. Glibc does not have + * this restriction. + * @since v10.0.0 + * @return Fulfills with the resolved path upon success. + */ + function realpath(path: PathLike, options?: ObjectEncodingOptions | BufferEncoding | null): Promise; + /** + * Asynchronous realpath(3) - return the canonicalized absolute pathname. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function realpath(path: PathLike, options: BufferEncodingOption): Promise; + /** + * Asynchronous realpath(3) - return the canonicalized absolute pathname. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function realpath(path: PathLike, options?: ObjectEncodingOptions | BufferEncoding | null): Promise; + /** + * Creates a unique temporary directory. A unique directory name is generated by + * appending six random characters to the end of the provided `prefix`. Due to + * platform inconsistencies, avoid trailing `X` characters in `prefix`. Some + * platforms, notably the BSDs, can return more than six random characters, and + * replace trailing `X` characters in `prefix` with random characters. + * + * The optional `options` argument can be a string specifying an encoding, or an + * object with an `encoding` property specifying the character encoding to use. + * + * ```js + * import { mkdtemp } from 'fs/promises'; + * + * try { + * await mkdtemp(path.join(os.tmpdir(), 'foo-')); + * } catch (err) { + * console.error(err); + * } + * ``` + * + * The `fsPromises.mkdtemp()` method will append the six randomly selected + * characters directly to the `prefix` string. For instance, given a directory`/tmp`, if the intention is to create a temporary directory _within_`/tmp`, the`prefix` must end with a trailing + * platform-specific path separator + * (`require('path').sep`). + * @since v10.0.0 + * @return Fulfills with a string containing the filesystem path of the newly created temporary directory. + */ + function mkdtemp(prefix: string, options?: ObjectEncodingOptions | BufferEncoding | null): Promise; + /** + * Asynchronously creates a unique temporary directory. + * Generates six random characters to be appended behind a required `prefix` to create a unique temporary directory. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function mkdtemp(prefix: string, options: BufferEncodingOption): Promise; + /** + * Asynchronously creates a unique temporary directory. + * Generates six random characters to be appended behind a required `prefix` to create a unique temporary directory. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function mkdtemp(prefix: string, options?: ObjectEncodingOptions | BufferEncoding | null): Promise; + /** + * Asynchronously writes data to a file, replacing the file if it already exists.`data` can be a string, a buffer, an + * [AsyncIterable](https://tc39.github.io/ecma262/#sec-asynciterable-interface) or + * [Iterable](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols#The_iterable_protocol) object. + * + * The `encoding` option is ignored if `data` is a buffer. + * + * If `options` is a string, then it specifies the encoding. + * + * The `mode` option only affects the newly created file. See `fs.open()` for more details. + * + * Any specified `FileHandle` has to support writing. + * + * It is unsafe to use `fsPromises.writeFile()` multiple times on the same file + * without waiting for the promise to be settled. + * + * Similarly to `fsPromises.readFile` \- `fsPromises.writeFile` is a convenience + * method that performs multiple `write` calls internally to write the buffer + * passed to it. For performance sensitive code consider using `fs.createWriteStream()` or `filehandle.createWriteStream()`. + * + * It is possible to use an `AbortSignal` to cancel an `fsPromises.writeFile()`. + * Cancelation is "best effort", and some amount of data is likely still + * to be written. + * + * ```js + * import { writeFile } from 'fs/promises'; + * import { Buffer } from 'buffer'; + * + * try { + * const controller = new AbortController(); + * const { signal } = controller; + * const data = new Uint8Array(Buffer.from('Hello Node.js')); + * const promise = writeFile('message.txt', data, { signal }); + * + * // Abort the request before the promise settles. + * controller.abort(); + * + * await promise; + * } catch (err) { + * // When a request is aborted - err is an AbortError + * console.error(err); + * } + * ``` + * + * Aborting an ongoing request does not abort individual operating + * system requests but rather the internal buffering `fs.writeFile` performs. + * @since v10.0.0 + * @param file filename or `FileHandle` + * @return Fulfills with `undefined` upon success. + */ + function writeFile( + file: PathLike | FileHandle, + data: string | NodeJS.ArrayBufferView | Iterable | AsyncIterable | Stream, + options?: + | (ObjectEncodingOptions & { + mode?: Mode | undefined; + flag?: OpenMode | undefined; + } & Abortable) + | BufferEncoding + | null + ): Promise; + /** + * Asynchronously append data to a file, creating the file if it does not yet + * exist. `data` can be a string or a `Buffer`. + * + * If `options` is a string, then it specifies the `encoding`. + * + * The `mode` option only affects the newly created file. See `fs.open()` for more details. + * + * The `path` may be specified as a `FileHandle` that has been opened + * for appending (using `fsPromises.open()`). + * @since v10.0.0 + * @param path filename or {FileHandle} + * @return Fulfills with `undefined` upon success. + */ + function appendFile(path: PathLike | FileHandle, data: string | Uint8Array, options?: (ObjectEncodingOptions & FlagAndOpenMode) | BufferEncoding | null): Promise; + /** + * Asynchronously reads the entire contents of a file. + * + * If no encoding is specified (using `options.encoding`), the data is returned + * as a `Buffer` object. Otherwise, the data will be a string. + * + * If `options` is a string, then it specifies the encoding. + * + * When the `path` is a directory, the behavior of `fsPromises.readFile()` is + * platform-specific. On macOS, Linux, and Windows, the promise will be rejected + * with an error. On FreeBSD, a representation of the directory's contents will be + * returned. + * + * It is possible to abort an ongoing `readFile` using an `AbortSignal`. If a + * request is aborted the promise returned is rejected with an `AbortError`: + * + * ```js + * import { readFile } from 'fs/promises'; + * + * try { + * const controller = new AbortController(); + * const { signal } = controller; + * const promise = readFile(fileName, { signal }); + * + * // Abort the request before the promise settles. + * controller.abort(); + * + * await promise; + * } catch (err) { + * // When a request is aborted - err is an AbortError + * console.error(err); + * } + * ``` + * + * Aborting an ongoing request does not abort individual operating + * system requests but rather the internal buffering `fs.readFile` performs. + * + * Any specified `FileHandle` has to support reading. + * @since v10.0.0 + * @param path filename or `FileHandle` + * @return Fulfills with the contents of the file. + */ + function readFile( + path: PathLike | FileHandle, + options?: + | ({ + encoding?: null | undefined; + flag?: OpenMode | undefined; + } & Abortable) + | null + ): Promise; + /** + * Asynchronously reads the entire contents of a file. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * If a `FileHandle` is provided, the underlying file will _not_ be closed automatically. + * @param options An object that may contain an optional flag. + * If a flag is not provided, it defaults to `'r'`. + */ + function readFile( + path: PathLike | FileHandle, + options: + | ({ + encoding: BufferEncoding; + flag?: OpenMode | undefined; + } & Abortable) + | BufferEncoding + ): Promise; + /** + * Asynchronously reads the entire contents of a file. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * If a `FileHandle` is provided, the underlying file will _not_ be closed automatically. + * @param options An object that may contain an optional flag. + * If a flag is not provided, it defaults to `'r'`. + */ + function readFile( + path: PathLike | FileHandle, + options?: + | (ObjectEncodingOptions & + Abortable & { + flag?: OpenMode | undefined; + }) + | BufferEncoding + | null + ): Promise; + /** + * Asynchronously open a directory for iterative scanning. See the POSIX [`opendir(3)`](http://man7.org/linux/man-pages/man3/opendir.3.html) documentation for more detail. + * + * Creates an `fs.Dir`, which contains all further functions for reading from + * and cleaning up the directory. + * + * The `encoding` option sets the encoding for the `path` while opening the + * directory and subsequent read operations. + * + * Example using async iteration: + * + * ```js + * import { opendir } from 'fs/promises'; + * + * try { + * const dir = await opendir('./'); + * for await (const dirent of dir) + * console.log(dirent.name); + * } catch (err) { + * console.error(err); + * } + * ``` + * + * When using the async iterator, the `fs.Dir` object will be automatically + * closed after the iterator exits. + * @since v12.12.0 + * @return Fulfills with an {fs.Dir}. + */ + function opendir(path: PathLike, options?: OpenDirOptions): Promise; + /** + * Returns an async iterator that watches for changes on `filename`, where `filename`is either a file or a directory. + * + * ```js + * const { watch } = require('fs/promises'); + * + * const ac = new AbortController(); + * const { signal } = ac; + * setTimeout(() => ac.abort(), 10000); + * + * (async () => { + * try { + * const watcher = watch(__filename, { signal }); + * for await (const event of watcher) + * console.log(event); + * } catch (err) { + * if (err.name === 'AbortError') + * return; + * throw err; + * } + * })(); + * ``` + * + * On most platforms, `'rename'` is emitted whenever a filename appears or + * disappears in the directory. + * + * All the `caveats` for `fs.watch()` also apply to `fsPromises.watch()`. + * @since v15.9.0, v14.18.0 + * @return of objects with the properties: + */ + function watch( + filename: PathLike, + options: + | (WatchOptions & { + encoding: 'buffer'; + }) + | 'buffer' + ): AsyncIterable>; + /** + * Watch for changes on `filename`, where `filename` is either a file or a directory, returning an `FSWatcher`. + * @param filename A path to a file or directory. If a URL is provided, it must use the `file:` protocol. + * @param options Either the encoding for the filename provided to the listener, or an object optionally specifying encoding, persistent, and recursive options. + * If `encoding` is not supplied, the default of `'utf8'` is used. + * If `persistent` is not supplied, the default of `true` is used. + * If `recursive` is not supplied, the default of `false` is used. + */ + function watch(filename: PathLike, options?: WatchOptions | BufferEncoding): AsyncIterable>; + /** + * Watch for changes on `filename`, where `filename` is either a file or a directory, returning an `FSWatcher`. + * @param filename A path to a file or directory. If a URL is provided, it must use the `file:` protocol. + * @param options Either the encoding for the filename provided to the listener, or an object optionally specifying encoding, persistent, and recursive options. + * If `encoding` is not supplied, the default of `'utf8'` is used. + * If `persistent` is not supplied, the default of `true` is used. + * If `recursive` is not supplied, the default of `false` is used. + */ + function watch(filename: PathLike, options: WatchOptions | string): AsyncIterable> | AsyncIterable>; + /** + * Asynchronously copies the entire directory structure from `src` to `dest`, + * including subdirectories and files. + * + * When copying a directory to another directory, globs are not supported and + * behavior is similar to `cp dir1/ dir2/`. + * @since v16.7.0 + * @experimental + * @param src source path to copy. + * @param dest destination path to copy to. + * @return Fulfills with `undefined` upon success. + */ + function cp(source: string | URL, destination: string | URL, opts?: CopyOptions): Promise; +} +declare module 'node:fs/promises' { + export * from 'fs/promises'; +} diff --git a/ts-ticket-office-service/node_modules/@types/node/globals.d.ts b/ts-ticket-office-service/node_modules/@types/node/globals.d.ts new file mode 100755 index 000000000..da499940e --- /dev/null +++ b/ts-ticket-office-service/node_modules/@types/node/globals.d.ts @@ -0,0 +1,294 @@ +// Declare "static" methods in Error +interface ErrorConstructor { + /** Create .stack property on a target object */ + captureStackTrace(targetObject: object, constructorOpt?: Function): void; + + /** + * Optional override for formatting stack traces + * + * @see https://v8.dev/docs/stack-trace-api#customizing-stack-traces + */ + prepareStackTrace?: ((err: Error, stackTraces: NodeJS.CallSite[]) => any) | undefined; + + stackTraceLimit: number; +} + +/*-----------------------------------------------* + * * + * GLOBAL * + * * + ------------------------------------------------*/ + +// For backwards compability +interface NodeRequire extends NodeJS.Require { } +interface RequireResolve extends NodeJS.RequireResolve { } +interface NodeModule extends NodeJS.Module { } + +declare var process: NodeJS.Process; +declare var console: Console; + +declare var __filename: string; +declare var __dirname: string; + +declare var require: NodeRequire; +declare var module: NodeModule; + +// Same as module.exports +declare var exports: any; + +/** + * Only available if `--expose-gc` is passed to the process. + */ +declare var gc: undefined | (() => void); + +//#region borrowed +// from https://github.com/microsoft/TypeScript/blob/38da7c600c83e7b31193a62495239a0fe478cb67/lib/lib.webworker.d.ts#L633 until moved to separate lib +/** A controller object that allows you to abort one or more DOM requests as and when desired. */ +interface AbortController { + /** + * Returns the AbortSignal object associated with this object. + */ + + readonly signal: AbortSignal; + /** + * Invoking this method will set this object's AbortSignal's aborted flag and signal to any observers that the associated activity is to be aborted. + */ + abort(): void; +} + +/** A signal object that allows you to communicate with a DOM request (such as a Fetch) and abort it if required via an AbortController object. */ +interface AbortSignal { + /** + * Returns true if this AbortSignal's AbortController has signaled to abort, and false otherwise. + */ + readonly aborted: boolean; +} + +declare var AbortController: { + prototype: AbortController; + new(): AbortController; +}; + +declare var AbortSignal: { + prototype: AbortSignal; + new(): AbortSignal; + // TODO: Add abort() static +}; +//#endregion borrowed + +//#region ArrayLike.at() +interface RelativeIndexable { + /** + * Takes an integer value and returns the item at that index, + * allowing for positive and negative integers. + * Negative integers count back from the last item in the array. + */ + at(index: number): T | undefined; +} +interface String extends RelativeIndexable {} +interface Array extends RelativeIndexable {} +interface Int8Array extends RelativeIndexable {} +interface Uint8Array extends RelativeIndexable {} +interface Uint8ClampedArray extends RelativeIndexable {} +interface Int16Array extends RelativeIndexable {} +interface Uint16Array extends RelativeIndexable {} +interface Int32Array extends RelativeIndexable {} +interface Uint32Array extends RelativeIndexable {} +interface Float32Array extends RelativeIndexable {} +interface Float64Array extends RelativeIndexable {} +interface BigInt64Array extends RelativeIndexable {} +interface BigUint64Array extends RelativeIndexable {} +//#endregion ArrayLike.at() end + +/** + * @since v17.0.0 + * + * Creates a deep clone of an object. + */ +declare function structuredClone( + value: T, + transfer?: { transfer: ReadonlyArray }, +): T; + +/*----------------------------------------------* +* * +* GLOBAL INTERFACES * +* * +*-----------------------------------------------*/ +declare namespace NodeJS { + interface CallSite { + /** + * Value of "this" + */ + getThis(): unknown; + + /** + * Type of "this" as a string. + * This is the name of the function stored in the constructor field of + * "this", if available. Otherwise the object's [[Class]] internal + * property. + */ + getTypeName(): string | null; + + /** + * Current function + */ + getFunction(): Function | undefined; + + /** + * Name of the current function, typically its name property. + * If a name property is not available an attempt will be made to try + * to infer a name from the function's context. + */ + getFunctionName(): string | null; + + /** + * Name of the property [of "this" or one of its prototypes] that holds + * the current function + */ + getMethodName(): string | null; + + /** + * Name of the script [if this function was defined in a script] + */ + getFileName(): string | null; + + /** + * Current line number [if this function was defined in a script] + */ + getLineNumber(): number | null; + + /** + * Current column number [if this function was defined in a script] + */ + getColumnNumber(): number | null; + + /** + * A call site object representing the location where eval was called + * [if this function was created using a call to eval] + */ + getEvalOrigin(): string | undefined; + + /** + * Is this a toplevel invocation, that is, is "this" the global object? + */ + isToplevel(): boolean; + + /** + * Does this call take place in code defined by a call to eval? + */ + isEval(): boolean; + + /** + * Is this call in native V8 code? + */ + isNative(): boolean; + + /** + * Is this a constructor call? + */ + isConstructor(): boolean; + } + + interface ErrnoException extends Error { + errno?: number | undefined; + code?: string | undefined; + path?: string | undefined; + syscall?: string | undefined; + } + + interface ReadableStream extends EventEmitter { + readable: boolean; + read(size?: number): string | Buffer; + setEncoding(encoding: BufferEncoding): this; + pause(): this; + resume(): this; + isPaused(): boolean; + pipe(destination: T, options?: { end?: boolean | undefined; }): T; + unpipe(destination?: WritableStream): this; + unshift(chunk: string | Uint8Array, encoding?: BufferEncoding): void; + wrap(oldStream: ReadableStream): this; + [Symbol.asyncIterator](): AsyncIterableIterator; + } + + interface WritableStream extends EventEmitter { + writable: boolean; + write(buffer: Uint8Array | string, cb?: (err?: Error | null) => void): boolean; + write(str: string, encoding?: BufferEncoding, cb?: (err?: Error | null) => void): boolean; + end(cb?: () => void): this; + end(data: string | Uint8Array, cb?: () => void): this; + end(str: string, encoding?: BufferEncoding, cb?: () => void): this; + } + + interface ReadWriteStream extends ReadableStream, WritableStream { } + + interface RefCounted { + ref(): this; + unref(): this; + } + + type TypedArray = + | Uint8Array + | Uint8ClampedArray + | Uint16Array + | Uint32Array + | Int8Array + | Int16Array + | Int32Array + | BigUint64Array + | BigInt64Array + | Float32Array + | Float64Array; + type ArrayBufferView = TypedArray | DataView; + + interface Require { + (id: string): any; + resolve: RequireResolve; + cache: Dict; + /** + * @deprecated + */ + extensions: RequireExtensions; + main: Module | undefined; + } + + interface RequireResolve { + (id: string, options?: { paths?: string[] | undefined; }): string; + paths(request: string): string[] | null; + } + + interface RequireExtensions extends Dict<(m: Module, filename: string) => any> { + '.js': (m: Module, filename: string) => any; + '.json': (m: Module, filename: string) => any; + '.node': (m: Module, filename: string) => any; + } + interface Module { + /** + * `true` if the module is running during the Node.js preload + */ + isPreloading: boolean; + exports: any; + require: Require; + id: string; + filename: string; + loaded: boolean; + /** @deprecated since v14.6.0 Please use `require.main` and `module.children` instead. */ + parent: Module | null | undefined; + children: Module[]; + /** + * @since v11.14.0 + * + * The directory name of the module. This is usually the same as the path.dirname() of the module.id. + */ + path: string; + paths: string[]; + } + + interface Dict { + [key: string]: T | undefined; + } + + interface ReadOnlyDict { + readonly [key: string]: T | undefined; + } +} diff --git a/ts-ticket-office-service/node_modules/@types/node/globals.global.d.ts b/ts-ticket-office-service/node_modules/@types/node/globals.global.d.ts new file mode 100755 index 000000000..ef1198c05 --- /dev/null +++ b/ts-ticket-office-service/node_modules/@types/node/globals.global.d.ts @@ -0,0 +1 @@ +declare var global: typeof globalThis; diff --git a/ts-ticket-office-service/node_modules/@types/node/http.d.ts b/ts-ticket-office-service/node_modules/@types/node/http.d.ts new file mode 100755 index 000000000..cced16dcd --- /dev/null +++ b/ts-ticket-office-service/node_modules/@types/node/http.d.ts @@ -0,0 +1,1452 @@ +/** + * To use the HTTP server and client one must `require('http')`. + * + * The HTTP interfaces in Node.js are designed to support many features + * of the protocol which have been traditionally difficult to use. + * In particular, large, possibly chunk-encoded, messages. The interface is + * careful to never buffer entire requests or responses, so the + * user is able to stream data. + * + * HTTP message headers are represented by an object like this: + * + * ```js + * { 'content-length': '123', + * 'content-type': 'text/plain', + * 'connection': 'keep-alive', + * 'host': 'example.com', + * 'accept': '*' } + * ``` + * + * Keys are lowercased. Values are not modified. + * + * In order to support the full spectrum of possible HTTP applications, the Node.js + * HTTP API is very low-level. It deals with stream handling and message + * parsing only. It parses a message into headers and body but it does not + * parse the actual headers or the body. + * + * See `message.headers` for details on how duplicate headers are handled. + * + * The raw headers as they were received are retained in the `rawHeaders`property, which is an array of `[key, value, key2, value2, ...]`. For + * example, the previous message header object might have a `rawHeaders`list like the following: + * + * ```js + * [ 'ConTent-Length', '123456', + * 'content-LENGTH', '123', + * 'content-type', 'text/plain', + * 'CONNECTION', 'keep-alive', + * 'Host', 'example.com', + * 'accepT', '*' ] + * ``` + * @see [source](https://github.com/nodejs/node/blob/v18.0.0/lib/http.js) + */ +declare module 'http' { + import * as stream from 'node:stream'; + import { URL } from 'node:url'; + import { TcpSocketConnectOpts, Socket, Server as NetServer, LookupFunction } from 'node:net'; + // incoming headers will never contain number + interface IncomingHttpHeaders extends NodeJS.Dict { + accept?: string | undefined; + 'accept-language'?: string | undefined; + 'accept-patch'?: string | undefined; + 'accept-ranges'?: string | undefined; + 'access-control-allow-credentials'?: string | undefined; + 'access-control-allow-headers'?: string | undefined; + 'access-control-allow-methods'?: string | undefined; + 'access-control-allow-origin'?: string | undefined; + 'access-control-expose-headers'?: string | undefined; + 'access-control-max-age'?: string | undefined; + 'access-control-request-headers'?: string | undefined; + 'access-control-request-method'?: string | undefined; + age?: string | undefined; + allow?: string | undefined; + 'alt-svc'?: string | undefined; + authorization?: string | undefined; + 'cache-control'?: string | undefined; + connection?: string | undefined; + 'content-disposition'?: string | undefined; + 'content-encoding'?: string | undefined; + 'content-language'?: string | undefined; + 'content-length'?: string | undefined; + 'content-location'?: string | undefined; + 'content-range'?: string | undefined; + 'content-type'?: string | undefined; + cookie?: string | undefined; + date?: string | undefined; + etag?: string | undefined; + expect?: string | undefined; + expires?: string | undefined; + forwarded?: string | undefined; + from?: string | undefined; + host?: string | undefined; + 'if-match'?: string | undefined; + 'if-modified-since'?: string | undefined; + 'if-none-match'?: string | undefined; + 'if-unmodified-since'?: string | undefined; + 'last-modified'?: string | undefined; + location?: string | undefined; + origin?: string | undefined; + pragma?: string | undefined; + 'proxy-authenticate'?: string | undefined; + 'proxy-authorization'?: string | undefined; + 'public-key-pins'?: string | undefined; + range?: string | undefined; + referer?: string | undefined; + 'retry-after'?: string | undefined; + 'sec-websocket-accept'?: string | undefined; + 'sec-websocket-extensions'?: string | undefined; + 'sec-websocket-key'?: string | undefined; + 'sec-websocket-protocol'?: string | undefined; + 'sec-websocket-version'?: string | undefined; + 'set-cookie'?: string[] | undefined; + 'strict-transport-security'?: string | undefined; + tk?: string | undefined; + trailer?: string | undefined; + 'transfer-encoding'?: string | undefined; + upgrade?: string | undefined; + 'user-agent'?: string | undefined; + vary?: string | undefined; + via?: string | undefined; + warning?: string | undefined; + 'www-authenticate'?: string | undefined; + } + // outgoing headers allows numbers (as they are converted internally to strings) + type OutgoingHttpHeader = number | string | string[]; + interface OutgoingHttpHeaders extends NodeJS.Dict {} + interface ClientRequestArgs { + signal?: AbortSignal | undefined; + protocol?: string | null | undefined; + host?: string | null | undefined; + hostname?: string | null | undefined; + family?: number | undefined; + port?: number | string | null | undefined; + defaultPort?: number | string | undefined; + localAddress?: string | undefined; + socketPath?: string | undefined; + /** + * @default 8192 + */ + maxHeaderSize?: number | undefined; + method?: string | undefined; + path?: string | null | undefined; + headers?: OutgoingHttpHeaders | undefined; + auth?: string | null | undefined; + agent?: Agent | boolean | undefined; + _defaultAgent?: Agent | undefined; + timeout?: number | undefined; + setHost?: boolean | undefined; + // https://github.com/nodejs/node/blob/master/lib/_http_client.js#L278 + createConnection?: ((options: ClientRequestArgs, oncreate: (err: Error, socket: Socket) => void) => Socket) | undefined; + lookup?: LookupFunction | undefined; + } + interface ServerOptions { + IncomingMessage?: typeof IncomingMessage | undefined; + ServerResponse?: typeof ServerResponse | undefined; + /** + * Optionally overrides the value of + * `--max-http-header-size` for requests received by this server, i.e. + * the maximum length of request headers in bytes. + * @default 8192 + */ + maxHeaderSize?: number | undefined; + /** + * Use an insecure HTTP parser that accepts invalid HTTP headers when true. + * Using the insecure parser should be avoided. + * See --insecure-http-parser for more information. + * @default false + */ + insecureHTTPParser?: boolean | undefined; + } + type RequestListener = (req: IncomingMessage, res: ServerResponse) => void; + /** + * @since v0.1.17 + */ + class Server extends NetServer { + constructor(requestListener?: RequestListener); + constructor(options: ServerOptions, requestListener?: RequestListener); + /** + * Sets the timeout value for sockets, and emits a `'timeout'` event on + * the Server object, passing the socket as an argument, if a timeout + * occurs. + * + * If there is a `'timeout'` event listener on the Server object, then it + * will be called with the timed-out socket as an argument. + * + * By default, the Server does not timeout sockets. However, if a callback + * is assigned to the Server's `'timeout'` event, timeouts must be handled + * explicitly. + * @since v0.9.12 + * @param [msecs=0 (no timeout)] + */ + setTimeout(msecs?: number, callback?: () => void): this; + setTimeout(callback: () => void): this; + /** + * Limits maximum incoming headers count. If set to 0, no limit will be applied. + * @since v0.7.0 + */ + maxHeadersCount: number | null; + /** + * The maximum number of requests socket can handle + * before closing keep alive connection. + * + * A value of `0` will disable the limit. + * + * When the limit is reached it will set the `Connection` header value to `close`, + * but will not actually close the connection, subsequent requests sent + * after the limit is reached will get `503 Service Unavailable` as a response. + * @since v16.10.0 + */ + maxRequestsPerSocket: number | null; + /** + * The number of milliseconds of inactivity before a socket is presumed + * to have timed out. + * + * A value of `0` will disable the timeout behavior on incoming connections. + * + * The socket timeout logic is set up on connection, so changing this + * value only affects new connections to the server, not any existing connections. + * @since v0.9.12 + */ + timeout: number; + /** + * Limit the amount of time the parser will wait to receive the complete HTTP + * headers. + * + * If the timeout expires, the server responds with status 408 without + * forwarding the request to the request listener and then closes the connection. + * + * It must be set to a non-zero value (e.g. 120 seconds) to protect against + * potential Denial-of-Service attacks in case the server is deployed without a + * reverse proxy in front. + * @since v11.3.0, v10.14.0 + */ + headersTimeout: number; + /** + * The number of milliseconds of inactivity a server needs to wait for additional + * incoming data, after it has finished writing the last response, before a socket + * will be destroyed. If the server receives new data before the keep-alive + * timeout has fired, it will reset the regular inactivity timeout, i.e.,`server.timeout`. + * + * A value of `0` will disable the keep-alive timeout behavior on incoming + * connections. + * A value of `0` makes the http server behave similarly to Node.js versions prior + * to 8.0.0, which did not have a keep-alive timeout. + * + * The socket timeout logic is set up on connection, so changing this value only + * affects new connections to the server, not any existing connections. + * @since v8.0.0 + */ + keepAliveTimeout: number; + /** + * Sets the timeout value in milliseconds for receiving the entire request from + * the client. + * + * If the timeout expires, the server responds with status 408 without + * forwarding the request to the request listener and then closes the connection. + * + * It must be set to a non-zero value (e.g. 120 seconds) to protect against + * potential Denial-of-Service attacks in case the server is deployed without a + * reverse proxy in front. + * @since v14.11.0 + */ + requestTimeout: number; + /** + * Closes all connections connected to this server. + * @since v18.2.0 + */ + closeAllConnections(): void; + /** + * Closes all connections connected to this server which are not sending a request or waiting for a response. + * @since v18.2.0 + */ + closeIdleConnections(): void; + addListener(event: string, listener: (...args: any[]) => void): this; + addListener(event: 'close', listener: () => void): this; + addListener(event: 'connection', listener: (socket: Socket) => void): this; + addListener(event: 'error', listener: (err: Error) => void): this; + addListener(event: 'listening', listener: () => void): this; + addListener(event: 'checkContinue', listener: RequestListener): this; + addListener(event: 'checkExpectation', listener: RequestListener): this; + addListener(event: 'clientError', listener: (err: Error, socket: stream.Duplex) => void): this; + addListener(event: 'connect', listener: (req: IncomingMessage, socket: stream.Duplex, head: Buffer) => void): this; + addListener(event: 'request', listener: RequestListener): this; + addListener(event: 'upgrade', listener: (req: IncomingMessage, socket: stream.Duplex, head: Buffer) => void): this; + emit(event: string, ...args: any[]): boolean; + emit(event: 'close'): boolean; + emit(event: 'connection', socket: Socket): boolean; + emit(event: 'error', err: Error): boolean; + emit(event: 'listening'): boolean; + emit(event: 'checkContinue', req: IncomingMessage, res: ServerResponse): boolean; + emit(event: 'checkExpectation', req: IncomingMessage, res: ServerResponse): boolean; + emit(event: 'clientError', err: Error, socket: stream.Duplex): boolean; + emit(event: 'connect', req: IncomingMessage, socket: stream.Duplex, head: Buffer): boolean; + emit(event: 'request', req: IncomingMessage, res: ServerResponse): boolean; + emit(event: 'upgrade', req: IncomingMessage, socket: stream.Duplex, head: Buffer): boolean; + on(event: string, listener: (...args: any[]) => void): this; + on(event: 'close', listener: () => void): this; + on(event: 'connection', listener: (socket: Socket) => void): this; + on(event: 'error', listener: (err: Error) => void): this; + on(event: 'listening', listener: () => void): this; + on(event: 'checkContinue', listener: RequestListener): this; + on(event: 'checkExpectation', listener: RequestListener): this; + on(event: 'clientError', listener: (err: Error, socket: stream.Duplex) => void): this; + on(event: 'connect', listener: (req: IncomingMessage, socket: stream.Duplex, head: Buffer) => void): this; + on(event: 'request', listener: RequestListener): this; + on(event: 'upgrade', listener: (req: IncomingMessage, socket: stream.Duplex, head: Buffer) => void): this; + once(event: string, listener: (...args: any[]) => void): this; + once(event: 'close', listener: () => void): this; + once(event: 'connection', listener: (socket: Socket) => void): this; + once(event: 'error', listener: (err: Error) => void): this; + once(event: 'listening', listener: () => void): this; + once(event: 'checkContinue', listener: RequestListener): this; + once(event: 'checkExpectation', listener: RequestListener): this; + once(event: 'clientError', listener: (err: Error, socket: stream.Duplex) => void): this; + once(event: 'connect', listener: (req: IncomingMessage, socket: stream.Duplex, head: Buffer) => void): this; + once(event: 'request', listener: RequestListener): this; + once(event: 'upgrade', listener: (req: IncomingMessage, socket: stream.Duplex, head: Buffer) => void): this; + prependListener(event: string, listener: (...args: any[]) => void): this; + prependListener(event: 'close', listener: () => void): this; + prependListener(event: 'connection', listener: (socket: Socket) => void): this; + prependListener(event: 'error', listener: (err: Error) => void): this; + prependListener(event: 'listening', listener: () => void): this; + prependListener(event: 'checkContinue', listener: RequestListener): this; + prependListener(event: 'checkExpectation', listener: RequestListener): this; + prependListener(event: 'clientError', listener: (err: Error, socket: stream.Duplex) => void): this; + prependListener(event: 'connect', listener: (req: IncomingMessage, socket: stream.Duplex, head: Buffer) => void): this; + prependListener(event: 'request', listener: RequestListener): this; + prependListener(event: 'upgrade', listener: (req: IncomingMessage, socket: stream.Duplex, head: Buffer) => void): this; + prependOnceListener(event: string, listener: (...args: any[]) => void): this; + prependOnceListener(event: 'close', listener: () => void): this; + prependOnceListener(event: 'connection', listener: (socket: Socket) => void): this; + prependOnceListener(event: 'error', listener: (err: Error) => void): this; + prependOnceListener(event: 'listening', listener: () => void): this; + prependOnceListener(event: 'checkContinue', listener: RequestListener): this; + prependOnceListener(event: 'checkExpectation', listener: RequestListener): this; + prependOnceListener(event: 'clientError', listener: (err: Error, socket: stream.Duplex) => void): this; + prependOnceListener(event: 'connect', listener: (req: IncomingMessage, socket: stream.Duplex, head: Buffer) => void): this; + prependOnceListener(event: 'request', listener: RequestListener): this; + prependOnceListener(event: 'upgrade', listener: (req: IncomingMessage, socket: stream.Duplex, head: Buffer) => void): this; + } + /** + * This class serves as the parent class of {@link ClientRequest} and {@link ServerResponse}. It is an abstract of outgoing message from + * the perspective of the participants of HTTP transaction. + * @since v0.1.17 + */ + class OutgoingMessage extends stream.Writable { + readonly req: IncomingMessage; + chunkedEncoding: boolean; + shouldKeepAlive: boolean; + useChunkedEncodingByDefault: boolean; + sendDate: boolean; + /** + * @deprecated Use `writableEnded` instead. + */ + finished: boolean; + /** + * Read-only. `true` if the headers were sent, otherwise `false`. + * @since v0.9.3 + */ + readonly headersSent: boolean; + /** + * Aliases of `outgoingMessage.socket` + * @since v0.3.0 + * @deprecated Since v15.12.0,v14.17.1 - Use `socket` instead. + */ + readonly connection: Socket | null; + /** + * Reference to the underlying socket. Usually, users will not want to access + * this property. + * + * After calling `outgoingMessage.end()`, this property will be nulled. + * @since v0.3.0 + */ + readonly socket: Socket | null; + constructor(); + /** + * Once a socket is associated with the message and is connected,`socket.setTimeout()` will be called with `msecs` as the first parameter. + * @since v0.9.12 + * @param callback Optional function to be called when a timeout occurs. Same as binding to the `timeout` event. + */ + setTimeout(msecs: number, callback?: () => void): this; + /** + * Sets a single header value for the header object. + * @since v0.4.0 + * @param name Header name + * @param value Header value + */ + setHeader(name: string, value: number | string | ReadonlyArray): this; + /** + * Gets the value of HTTP header with the given name. If such a name doesn't + * exist in message, it will be `undefined`. + * @since v0.4.0 + * @param name Name of header + */ + getHeader(name: string): number | string | string[] | undefined; + /** + * Returns a shallow copy of the current outgoing headers. Since a shallow + * copy is used, array values may be mutated without additional calls to + * various header-related HTTP module methods. The keys of the returned + * object are the header names and the values are the respective header + * values. All header names are lowercase. + * + * The object returned by the `outgoingMessage.getHeaders()` method does + * not prototypically inherit from the JavaScript Object. This means that + * typical Object methods such as `obj.toString()`, `obj.hasOwnProperty()`, + * and others are not defined and will not work. + * + * ```js + * outgoingMessage.setHeader('Foo', 'bar'); + * outgoingMessage.setHeader('Set-Cookie', ['foo=bar', 'bar=baz']); + * + * const headers = outgoingMessage.getHeaders(); + * // headers === { foo: 'bar', 'set-cookie': ['foo=bar', 'bar=baz'] } + * ``` + * @since v7.7.0 + */ + getHeaders(): OutgoingHttpHeaders; + /** + * Returns an array of names of headers of the outgoing outgoingMessage. All + * names are lowercase. + * @since v7.7.0 + */ + getHeaderNames(): string[]; + /** + * Returns `true` if the header identified by `name` is currently set in the + * outgoing headers. The header name is case-insensitive. + * + * ```js + * const hasContentType = outgoingMessage.hasHeader('content-type'); + * ``` + * @since v7.7.0 + */ + hasHeader(name: string): boolean; + /** + * Removes a header that is queued for implicit sending. + * + * ```js + * outgoingMessage.removeHeader('Content-Encoding'); + * ``` + * @since v0.4.0 + * @param name Header name + */ + removeHeader(name: string): void; + /** + * Adds HTTP trailers (headers but at the end of the message) to the message. + * + * Trailers are **only** be emitted if the message is chunked encoded. If not, + * the trailer will be silently discarded. + * + * HTTP requires the `Trailer` header to be sent to emit trailers, + * with a list of header fields in its value, e.g. + * + * ```js + * message.writeHead(200, { 'Content-Type': 'text/plain', + * 'Trailer': 'Content-MD5' }); + * message.write(fileData); + * message.addTrailers({ 'Content-MD5': '7895bf4b8828b55ceaf47747b4bca667' }); + * message.end(); + * ``` + * + * Attempting to set a header field name or value that contains invalid characters + * will result in a `TypeError` being thrown. + * @since v0.3.0 + */ + addTrailers(headers: OutgoingHttpHeaders | ReadonlyArray<[string, string]>): void; + /** + * Compulsorily flushes the message headers + * + * For efficiency reason, Node.js normally buffers the message headers + * until `outgoingMessage.end()` is called or the first chunk of message data + * is written. It then tries to pack the headers and data into a single TCP + * packet. + * + * It is usually desired (it saves a TCP round-trip), but not when the first + * data is not sent until possibly much later. `outgoingMessage.flushHeaders()`bypasses the optimization and kickstarts the request. + * @since v1.6.0 + */ + flushHeaders(): void; + } + /** + * This object is created internally by an HTTP server, not by the user. It is + * passed as the second parameter to the `'request'` event. + * @since v0.1.17 + */ + class ServerResponse extends OutgoingMessage { + /** + * When using implicit headers (not calling `response.writeHead()` explicitly), + * this property controls the status code that will be sent to the client when + * the headers get flushed. + * + * ```js + * response.statusCode = 404; + * ``` + * + * After response header was sent to the client, this property indicates the + * status code which was sent out. + * @since v0.4.0 + */ + statusCode: number; + /** + * When using implicit headers (not calling `response.writeHead()` explicitly), + * this property controls the status message that will be sent to the client when + * the headers get flushed. If this is left as `undefined` then the standard + * message for the status code will be used. + * + * ```js + * response.statusMessage = 'Not found'; + * ``` + * + * After response header was sent to the client, this property indicates the + * status message which was sent out. + * @since v0.11.8 + */ + statusMessage: string; + constructor(req: IncomingMessage); + assignSocket(socket: Socket): void; + detachSocket(socket: Socket): void; + /** + * Sends a HTTP/1.1 100 Continue message to the client, indicating that + * the request body should be sent. See the `'checkContinue'` event on`Server`. + * @since v0.3.0 + */ + writeContinue(callback?: () => void): void; + /** + * Sends a response header to the request. The status code is a 3-digit HTTP + * status code, like `404`. The last argument, `headers`, are the response headers. + * Optionally one can give a human-readable `statusMessage` as the second + * argument. + * + * `headers` may be an `Array` where the keys and values are in the same list. + * It is _not_ a list of tuples. So, the even-numbered offsets are key values, + * and the odd-numbered offsets are the associated values. The array is in the same + * format as `request.rawHeaders`. + * + * Returns a reference to the `ServerResponse`, so that calls can be chained. + * + * ```js + * const body = 'hello world'; + * response + * .writeHead(200, { + * 'Content-Length': Buffer.byteLength(body), + * 'Content-Type': 'text/plain' + * }) + * .end(body); + * ``` + * + * This method must only be called once on a message and it must + * be called before `response.end()` is called. + * + * If `response.write()` or `response.end()` are called before calling + * this, the implicit/mutable headers will be calculated and call this function. + * + * When headers have been set with `response.setHeader()`, they will be merged + * with any headers passed to `response.writeHead()`, with the headers passed + * to `response.writeHead()` given precedence. + * + * If this method is called and `response.setHeader()` has not been called, + * it will directly write the supplied header values onto the network channel + * without caching internally, and the `response.getHeader()` on the header + * will not yield the expected result. If progressive population of headers is + * desired with potential future retrieval and modification, use `response.setHeader()` instead. + * + * ```js + * // Returns content-type = text/plain + * const server = http.createServer((req, res) => { + * res.setHeader('Content-Type', 'text/html'); + * res.setHeader('X-Foo', 'bar'); + * res.writeHead(200, { 'Content-Type': 'text/plain' }); + * res.end('ok'); + * }); + * ``` + * + * `Content-Length` is given in bytes, not characters. Use `Buffer.byteLength()` to determine the length of the body in bytes. Node.js + * does not check whether `Content-Length` and the length of the body which has + * been transmitted are equal or not. + * + * Attempting to set a header field name or value that contains invalid characters + * will result in a `TypeError` being thrown. + * @since v0.1.30 + */ + writeHead(statusCode: number, statusMessage?: string, headers?: OutgoingHttpHeaders | OutgoingHttpHeader[]): this; + writeHead(statusCode: number, headers?: OutgoingHttpHeaders | OutgoingHttpHeader[]): this; + /** + * Sends a HTTP/1.1 102 Processing message to the client, indicating that + * the request body should be sent. + * @since v10.0.0 + */ + writeProcessing(): void; + } + interface InformationEvent { + statusCode: number; + statusMessage: string; + httpVersion: string; + httpVersionMajor: number; + httpVersionMinor: number; + headers: IncomingHttpHeaders; + rawHeaders: string[]; + } + /** + * This object is created internally and returned from {@link request}. It + * represents an _in-progress_ request whose header has already been queued. The + * header is still mutable using the `setHeader(name, value)`,`getHeader(name)`, `removeHeader(name)` API. The actual header will + * be sent along with the first data chunk or when calling `request.end()`. + * + * To get the response, add a listener for `'response'` to the request object.`'response'` will be emitted from the request object when the response + * headers have been received. The `'response'` event is executed with one + * argument which is an instance of {@link IncomingMessage}. + * + * During the `'response'` event, one can add listeners to the + * response object; particularly to listen for the `'data'` event. + * + * If no `'response'` handler is added, then the response will be + * entirely discarded. However, if a `'response'` event handler is added, + * then the data from the response object **must** be consumed, either by + * calling `response.read()` whenever there is a `'readable'` event, or + * by adding a `'data'` handler, or by calling the `.resume()` method. + * Until the data is consumed, the `'end'` event will not fire. Also, until + * the data is read it will consume memory that can eventually lead to a + * 'process out of memory' error. + * + * For backward compatibility, `res` will only emit `'error'` if there is an`'error'` listener registered. + * + * Node.js does not check whether Content-Length and the length of the + * body which has been transmitted are equal or not. + * @since v0.1.17 + */ + class ClientRequest extends OutgoingMessage { + /** + * The `request.aborted` property will be `true` if the request has + * been aborted. + * @since v0.11.14 + * @deprecated Since v17.0.0,v16.12.0 - Check `destroyed` instead. + */ + aborted: boolean; + /** + * The request host. + * @since v14.5.0, v12.19.0 + */ + host: string; + /** + * The request protocol. + * @since v14.5.0, v12.19.0 + */ + protocol: string; + /** + * When sending request through a keep-alive enabled agent, the underlying socket + * might be reused. But if server closes connection at unfortunate time, client + * may run into a 'ECONNRESET' error. + * + * ```js + * const http = require('http'); + * + * // Server has a 5 seconds keep-alive timeout by default + * http + * .createServer((req, res) => { + * res.write('hello\n'); + * res.end(); + * }) + * .listen(3000); + * + * setInterval(() => { + * // Adapting a keep-alive agent + * http.get('http://localhost:3000', { agent }, (res) => { + * res.on('data', (data) => { + * // Do nothing + * }); + * }); + * }, 5000); // Sending request on 5s interval so it's easy to hit idle timeout + * ``` + * + * By marking a request whether it reused socket or not, we can do + * automatic error retry base on it. + * + * ```js + * const http = require('http'); + * const agent = new http.Agent({ keepAlive: true }); + * + * function retriableRequest() { + * const req = http + * .get('http://localhost:3000', { agent }, (res) => { + * // ... + * }) + * .on('error', (err) => { + * // Check if retry is needed + * if (req.reusedSocket && err.code === 'ECONNRESET') { + * retriableRequest(); + * } + * }); + * } + * + * retriableRequest(); + * ``` + * @since v13.0.0, v12.16.0 + */ + reusedSocket: boolean; + /** + * Limits maximum response headers count. If set to 0, no limit will be applied. + */ + maxHeadersCount: number; + constructor(url: string | URL | ClientRequestArgs, cb?: (res: IncomingMessage) => void); + /** + * The request method. + * @since v0.1.97 + */ + method: string; + /** + * The request path. + * @since v0.4.0 + */ + path: string; + /** + * Marks the request as aborting. Calling this will cause remaining data + * in the response to be dropped and the socket to be destroyed. + * @since v0.3.8 + * @deprecated Since v14.1.0,v13.14.0 - Use `destroy` instead. + */ + abort(): void; + onSocket(socket: Socket): void; + /** + * Once a socket is assigned to this request and is connected `socket.setTimeout()` will be called. + * @since v0.5.9 + * @param timeout Milliseconds before a request times out. + * @param callback Optional function to be called when a timeout occurs. Same as binding to the `'timeout'` event. + */ + setTimeout(timeout: number, callback?: () => void): this; + /** + * Once a socket is assigned to this request and is connected `socket.setNoDelay()` will be called. + * @since v0.5.9 + */ + setNoDelay(noDelay?: boolean): void; + /** + * Once a socket is assigned to this request and is connected `socket.setKeepAlive()` will be called. + * @since v0.5.9 + */ + setSocketKeepAlive(enable?: boolean, initialDelay?: number): void; + /** + * Returns an array containing the unique names of the current outgoing raw + * headers. Header names are returned with their exact casing being set. + * + * ```js + * request.setHeader('Foo', 'bar'); + * request.setHeader('Set-Cookie', ['foo=bar', 'bar=baz']); + * + * const headerNames = request.getRawHeaderNames(); + * // headerNames === ['Foo', 'Set-Cookie'] + * ``` + * @since v15.13.0, v14.17.0 + */ + getRawHeaderNames(): string[]; + /** + * @deprecated + */ + addListener(event: 'abort', listener: () => void): this; + addListener(event: 'connect', listener: (response: IncomingMessage, socket: Socket, head: Buffer) => void): this; + addListener(event: 'continue', listener: () => void): this; + addListener(event: 'information', listener: (info: InformationEvent) => void): this; + addListener(event: 'response', listener: (response: IncomingMessage) => void): this; + addListener(event: 'socket', listener: (socket: Socket) => void): this; + addListener(event: 'timeout', listener: () => void): this; + addListener(event: 'upgrade', listener: (response: IncomingMessage, socket: Socket, head: Buffer) => void): this; + addListener(event: 'close', listener: () => void): this; + addListener(event: 'drain', listener: () => void): this; + addListener(event: 'error', listener: (err: Error) => void): this; + addListener(event: 'finish', listener: () => void): this; + addListener(event: 'pipe', listener: (src: stream.Readable) => void): this; + addListener(event: 'unpipe', listener: (src: stream.Readable) => void): this; + addListener(event: string | symbol, listener: (...args: any[]) => void): this; + /** + * @deprecated + */ + on(event: 'abort', listener: () => void): this; + on(event: 'connect', listener: (response: IncomingMessage, socket: Socket, head: Buffer) => void): this; + on(event: 'continue', listener: () => void): this; + on(event: 'information', listener: (info: InformationEvent) => void): this; + on(event: 'response', listener: (response: IncomingMessage) => void): this; + on(event: 'socket', listener: (socket: Socket) => void): this; + on(event: 'timeout', listener: () => void): this; + on(event: 'upgrade', listener: (response: IncomingMessage, socket: Socket, head: Buffer) => void): this; + on(event: 'close', listener: () => void): this; + on(event: 'drain', listener: () => void): this; + on(event: 'error', listener: (err: Error) => void): this; + on(event: 'finish', listener: () => void): this; + on(event: 'pipe', listener: (src: stream.Readable) => void): this; + on(event: 'unpipe', listener: (src: stream.Readable) => void): this; + on(event: string | symbol, listener: (...args: any[]) => void): this; + /** + * @deprecated + */ + once(event: 'abort', listener: () => void): this; + once(event: 'connect', listener: (response: IncomingMessage, socket: Socket, head: Buffer) => void): this; + once(event: 'continue', listener: () => void): this; + once(event: 'information', listener: (info: InformationEvent) => void): this; + once(event: 'response', listener: (response: IncomingMessage) => void): this; + once(event: 'socket', listener: (socket: Socket) => void): this; + once(event: 'timeout', listener: () => void): this; + once(event: 'upgrade', listener: (response: IncomingMessage, socket: Socket, head: Buffer) => void): this; + once(event: 'close', listener: () => void): this; + once(event: 'drain', listener: () => void): this; + once(event: 'error', listener: (err: Error) => void): this; + once(event: 'finish', listener: () => void): this; + once(event: 'pipe', listener: (src: stream.Readable) => void): this; + once(event: 'unpipe', listener: (src: stream.Readable) => void): this; + once(event: string | symbol, listener: (...args: any[]) => void): this; + /** + * @deprecated + */ + prependListener(event: 'abort', listener: () => void): this; + prependListener(event: 'connect', listener: (response: IncomingMessage, socket: Socket, head: Buffer) => void): this; + prependListener(event: 'continue', listener: () => void): this; + prependListener(event: 'information', listener: (info: InformationEvent) => void): this; + prependListener(event: 'response', listener: (response: IncomingMessage) => void): this; + prependListener(event: 'socket', listener: (socket: Socket) => void): this; + prependListener(event: 'timeout', listener: () => void): this; + prependListener(event: 'upgrade', listener: (response: IncomingMessage, socket: Socket, head: Buffer) => void): this; + prependListener(event: 'close', listener: () => void): this; + prependListener(event: 'drain', listener: () => void): this; + prependListener(event: 'error', listener: (err: Error) => void): this; + prependListener(event: 'finish', listener: () => void): this; + prependListener(event: 'pipe', listener: (src: stream.Readable) => void): this; + prependListener(event: 'unpipe', listener: (src: stream.Readable) => void): this; + prependListener(event: string | symbol, listener: (...args: any[]) => void): this; + /** + * @deprecated + */ + prependOnceListener(event: 'abort', listener: () => void): this; + prependOnceListener(event: 'connect', listener: (response: IncomingMessage, socket: Socket, head: Buffer) => void): this; + prependOnceListener(event: 'continue', listener: () => void): this; + prependOnceListener(event: 'information', listener: (info: InformationEvent) => void): this; + prependOnceListener(event: 'response', listener: (response: IncomingMessage) => void): this; + prependOnceListener(event: 'socket', listener: (socket: Socket) => void): this; + prependOnceListener(event: 'timeout', listener: () => void): this; + prependOnceListener(event: 'upgrade', listener: (response: IncomingMessage, socket: Socket, head: Buffer) => void): this; + prependOnceListener(event: 'close', listener: () => void): this; + prependOnceListener(event: 'drain', listener: () => void): this; + prependOnceListener(event: 'error', listener: (err: Error) => void): this; + prependOnceListener(event: 'finish', listener: () => void): this; + prependOnceListener(event: 'pipe', listener: (src: stream.Readable) => void): this; + prependOnceListener(event: 'unpipe', listener: (src: stream.Readable) => void): this; + prependOnceListener(event: string | symbol, listener: (...args: any[]) => void): this; + } + /** + * An `IncomingMessage` object is created by {@link Server} or {@link ClientRequest} and passed as the first argument to the `'request'` and `'response'` event respectively. It may be used to + * access response + * status, headers and data. + * + * Different from its `socket` value which is a subclass of `stream.Duplex`, the`IncomingMessage` itself extends `stream.Readable` and is created separately to + * parse and emit the incoming HTTP headers and payload, as the underlying socket + * may be reused multiple times in case of keep-alive. + * @since v0.1.17 + */ + class IncomingMessage extends stream.Readable { + constructor(socket: Socket); + /** + * The `message.aborted` property will be `true` if the request has + * been aborted. + * @since v10.1.0 + * @deprecated Since v17.0.0,v16.12.0 - Check `message.destroyed` from stream.Readable. + */ + aborted: boolean; + /** + * In case of server request, the HTTP version sent by the client. In the case of + * client response, the HTTP version of the connected-to server. + * Probably either `'1.1'` or `'1.0'`. + * + * Also `message.httpVersionMajor` is the first integer and`message.httpVersionMinor` is the second. + * @since v0.1.1 + */ + httpVersion: string; + httpVersionMajor: number; + httpVersionMinor: number; + /** + * The `message.complete` property will be `true` if a complete HTTP message has + * been received and successfully parsed. + * + * This property is particularly useful as a means of determining if a client or + * server fully transmitted a message before a connection was terminated: + * + * ```js + * const req = http.request({ + * host: '127.0.0.1', + * port: 8080, + * method: 'POST' + * }, (res) => { + * res.resume(); + * res.on('end', () => { + * if (!res.complete) + * console.error( + * 'The connection was terminated while the message was still being sent'); + * }); + * }); + * ``` + * @since v0.3.0 + */ + complete: boolean; + /** + * Alias for `message.socket`. + * @since v0.1.90 + * @deprecated Since v16.0.0 - Use `socket`. + */ + connection: Socket; + /** + * The `net.Socket` object associated with the connection. + * + * With HTTPS support, use `request.socket.getPeerCertificate()` to obtain the + * client's authentication details. + * + * This property is guaranteed to be an instance of the `net.Socket` class, + * a subclass of `stream.Duplex`, unless the user specified a socket + * type other than `net.Socket` or internally nulled. + * @since v0.3.0 + */ + socket: Socket; + /** + * The request/response headers object. + * + * Key-value pairs of header names and values. Header names are lower-cased. + * + * ```js + * // Prints something like: + * // + * // { 'user-agent': 'curl/7.22.0', + * // host: '127.0.0.1:8000', + * // accept: '*' } + * console.log(request.getHeaders()); + * ``` + * + * Duplicates in raw headers are handled in the following ways, depending on the + * header name: + * + * * Duplicates of `age`, `authorization`, `content-length`, `content-type`,`etag`, `expires`, `from`, `host`, `if-modified-since`, `if-unmodified-since`,`last-modified`, `location`, + * `max-forwards`, `proxy-authorization`, `referer`,`retry-after`, `server`, or `user-agent` are discarded. + * * `set-cookie` is always an array. Duplicates are added to the array. + * * For duplicate `cookie` headers, the values are joined together with '; '. + * * For all other headers, the values are joined together with ', '. + * @since v0.1.5 + */ + headers: IncomingHttpHeaders; + /** + * The raw request/response headers list exactly as they were received. + * + * The keys and values are in the same list. It is _not_ a + * list of tuples. So, the even-numbered offsets are key values, and the + * odd-numbered offsets are the associated values. + * + * Header names are not lowercased, and duplicates are not merged. + * + * ```js + * // Prints something like: + * // + * // [ 'user-agent', + * // 'this is invalid because there can be only one', + * // 'User-Agent', + * // 'curl/7.22.0', + * // 'Host', + * // '127.0.0.1:8000', + * // 'ACCEPT', + * // '*' ] + * console.log(request.rawHeaders); + * ``` + * @since v0.11.6 + */ + rawHeaders: string[]; + /** + * The request/response trailers object. Only populated at the `'end'` event. + * @since v0.3.0 + */ + trailers: NodeJS.Dict; + /** + * The raw request/response trailer keys and values exactly as they were + * received. Only populated at the `'end'` event. + * @since v0.11.6 + */ + rawTrailers: string[]; + /** + * Calls `message.socket.setTimeout(msecs, callback)`. + * @since v0.5.9 + */ + setTimeout(msecs: number, callback?: () => void): this; + /** + * **Only valid for request obtained from {@link Server}.** + * + * The request method as a string. Read only. Examples: `'GET'`, `'DELETE'`. + * @since v0.1.1 + */ + method?: string | undefined; + /** + * **Only valid for request obtained from {@link Server}.** + * + * Request URL string. This contains only the URL that is present in the actual + * HTTP request. Take the following request: + * + * ```http + * GET /status?name=ryan HTTP/1.1 + * Accept: text/plain + * ``` + * + * To parse the URL into its parts: + * + * ```js + * new URL(request.url, `http://${request.getHeaders().host}`); + * ``` + * + * When `request.url` is `'/status?name=ryan'` and`request.getHeaders().host` is `'localhost:3000'`: + * + * ```console + * $ node + * > new URL(request.url, `http://${request.getHeaders().host}`) + * URL { + * href: 'http://localhost:3000/status?name=ryan', + * origin: 'http://localhost:3000', + * protocol: 'http:', + * username: '', + * password: '', + * host: 'localhost:3000', + * hostname: 'localhost', + * port: '3000', + * pathname: '/status', + * search: '?name=ryan', + * searchParams: URLSearchParams { 'name' => 'ryan' }, + * hash: '' + * } + * ``` + * @since v0.1.90 + */ + url?: string | undefined; + /** + * **Only valid for response obtained from {@link ClientRequest}.** + * + * The 3-digit HTTP response status code. E.G. `404`. + * @since v0.1.1 + */ + statusCode?: number | undefined; + /** + * **Only valid for response obtained from {@link ClientRequest}.** + * + * The HTTP response status message (reason phrase). E.G. `OK` or `Internal Server Error`. + * @since v0.11.10 + */ + statusMessage?: string | undefined; + /** + * Calls `destroy()` on the socket that received the `IncomingMessage`. If `error`is provided, an `'error'` event is emitted on the socket and `error` is passed + * as an argument to any listeners on the event. + * @since v0.3.0 + */ + destroy(error?: Error): this; + } + interface AgentOptions extends Partial { + /** + * Keep sockets around in a pool to be used by other requests in the future. Default = false + */ + keepAlive?: boolean | undefined; + /** + * When using HTTP KeepAlive, how often to send TCP KeepAlive packets over sockets being kept alive. Default = 1000. + * Only relevant if keepAlive is set to true. + */ + keepAliveMsecs?: number | undefined; + /** + * Maximum number of sockets to allow per host. Default for Node 0.10 is 5, default for Node 0.12 is Infinity + */ + maxSockets?: number | undefined; + /** + * Maximum number of sockets allowed for all hosts in total. Each request will use a new socket until the maximum is reached. Default: Infinity. + */ + maxTotalSockets?: number | undefined; + /** + * Maximum number of sockets to leave open in a free state. Only relevant if keepAlive is set to true. Default = 256. + */ + maxFreeSockets?: number | undefined; + /** + * Socket timeout in milliseconds. This will set the timeout after the socket is connected. + */ + timeout?: number | undefined; + /** + * Scheduling strategy to apply when picking the next free socket to use. + * @default `lifo` + */ + scheduling?: 'fifo' | 'lifo' | undefined; + } + /** + * An `Agent` is responsible for managing connection persistence + * and reuse for HTTP clients. It maintains a queue of pending requests + * for a given host and port, reusing a single socket connection for each + * until the queue is empty, at which time the socket is either destroyed + * or put into a pool where it is kept to be used again for requests to the + * same host and port. Whether it is destroyed or pooled depends on the`keepAlive` `option`. + * + * Pooled connections have TCP Keep-Alive enabled for them, but servers may + * still close idle connections, in which case they will be removed from the + * pool and a new connection will be made when a new HTTP request is made for + * that host and port. Servers may also refuse to allow multiple requests + * over the same connection, in which case the connection will have to be + * remade for every request and cannot be pooled. The `Agent` will still make + * the requests to that server, but each one will occur over a new connection. + * + * When a connection is closed by the client or the server, it is removed + * from the pool. Any unused sockets in the pool will be unrefed so as not + * to keep the Node.js process running when there are no outstanding requests. + * (see `socket.unref()`). + * + * It is good practice, to `destroy()` an `Agent` instance when it is no + * longer in use, because unused sockets consume OS resources. + * + * Sockets are removed from an agent when the socket emits either + * a `'close'` event or an `'agentRemove'` event. When intending to keep one + * HTTP request open for a long time without keeping it in the agent, something + * like the following may be done: + * + * ```js + * http.get(options, (res) => { + * // Do stuff + * }).on('socket', (socket) => { + * socket.emit('agentRemove'); + * }); + * ``` + * + * An agent may also be used for an individual request. By providing`{agent: false}` as an option to the `http.get()` or `http.request()`functions, a one-time use `Agent` with default options + * will be used + * for the client connection. + * + * `agent:false`: + * + * ```js + * http.get({ + * hostname: 'localhost', + * port: 80, + * path: '/', + * agent: false // Create a new agent just for this one request + * }, (res) => { + * // Do stuff with response + * }); + * ``` + * @since v0.3.4 + */ + class Agent { + /** + * By default set to 256\. For agents with `keepAlive` enabled, this + * sets the maximum number of sockets that will be left open in the free + * state. + * @since v0.11.7 + */ + maxFreeSockets: number; + /** + * By default set to `Infinity`. Determines how many concurrent sockets the agent + * can have open per origin. Origin is the returned value of `agent.getName()`. + * @since v0.3.6 + */ + maxSockets: number; + /** + * By default set to `Infinity`. Determines how many concurrent sockets the agent + * can have open. Unlike `maxSockets`, this parameter applies across all origins. + * @since v14.5.0, v12.19.0 + */ + maxTotalSockets: number; + /** + * An object which contains arrays of sockets currently awaiting use by + * the agent when `keepAlive` is enabled. Do not modify. + * + * Sockets in the `freeSockets` list will be automatically destroyed and + * removed from the array on `'timeout'`. + * @since v0.11.4 + */ + readonly freeSockets: NodeJS.ReadOnlyDict; + /** + * An object which contains arrays of sockets currently in use by the + * agent. Do not modify. + * @since v0.3.6 + */ + readonly sockets: NodeJS.ReadOnlyDict; + /** + * An object which contains queues of requests that have not yet been assigned to + * sockets. Do not modify. + * @since v0.5.9 + */ + readonly requests: NodeJS.ReadOnlyDict; + constructor(opts?: AgentOptions); + /** + * Destroy any sockets that are currently in use by the agent. + * + * It is usually not necessary to do this. However, if using an + * agent with `keepAlive` enabled, then it is best to explicitly shut down + * the agent when it is no longer needed. Otherwise, + * sockets might stay open for quite a long time before the server + * terminates them. + * @since v0.11.4 + */ + destroy(): void; + } + const METHODS: string[]; + const STATUS_CODES: { + [errorCode: number]: string | undefined; + [errorCode: string]: string | undefined; + }; + /** + * Returns a new instance of {@link Server}. + * + * The `requestListener` is a function which is automatically + * added to the `'request'` event. + * @since v0.1.13 + */ + function createServer(requestListener?: RequestListener): Server; + function createServer(options: ServerOptions, requestListener?: RequestListener): Server; + // although RequestOptions are passed as ClientRequestArgs to ClientRequest directly, + // create interface RequestOptions would make the naming more clear to developers + interface RequestOptions extends ClientRequestArgs {} + /** + * `options` in `socket.connect()` are also supported. + * + * Node.js maintains several connections per server to make HTTP requests. + * This function allows one to transparently issue requests. + * + * `url` can be a string or a `URL` object. If `url` is a + * string, it is automatically parsed with `new URL()`. If it is a `URL` object, it will be automatically converted to an ordinary `options` object. + * + * If both `url` and `options` are specified, the objects are merged, with the`options` properties taking precedence. + * + * The optional `callback` parameter will be added as a one-time listener for + * the `'response'` event. + * + * `http.request()` returns an instance of the {@link ClientRequest} class. The `ClientRequest` instance is a writable stream. If one needs to + * upload a file with a POST request, then write to the `ClientRequest` object. + * + * ```js + * const http = require('http'); + * + * const postData = JSON.stringify({ + * 'msg': 'Hello World!' + * }); + * + * const options = { + * hostname: 'www.google.com', + * port: 80, + * path: '/upload', + * method: 'POST', + * headers: { + * 'Content-Type': 'application/json', + * 'Content-Length': Buffer.byteLength(postData) + * } + * }; + * + * const req = http.request(options, (res) => { + * console.log(`STATUS: ${res.statusCode}`); + * console.log(`HEADERS: ${JSON.stringify(res.headers)}`); + * res.setEncoding('utf8'); + * res.on('data', (chunk) => { + * console.log(`BODY: ${chunk}`); + * }); + * res.on('end', () => { + * console.log('No more data in response.'); + * }); + * }); + * + * req.on('error', (e) => { + * console.error(`problem with request: ${e.message}`); + * }); + * + * // Write data to request body + * req.write(postData); + * req.end(); + * ``` + * + * In the example `req.end()` was called. With `http.request()` one + * must always call `req.end()` to signify the end of the request - + * even if there is no data being written to the request body. + * + * If any error is encountered during the request (be that with DNS resolution, + * TCP level errors, or actual HTTP parse errors) an `'error'` event is emitted + * on the returned request object. As with all `'error'` events, if no listeners + * are registered the error will be thrown. + * + * There are a few special headers that should be noted. + * + * * Sending a 'Connection: keep-alive' will notify Node.js that the connection to + * the server should be persisted until the next request. + * * Sending a 'Content-Length' header will disable the default chunked encoding. + * * Sending an 'Expect' header will immediately send the request headers. + * Usually, when sending 'Expect: 100-continue', both a timeout and a listener + * for the `'continue'` event should be set. See RFC 2616 Section 8.2.3 for more + * information. + * * Sending an Authorization header will override using the `auth` option + * to compute basic authentication. + * + * Example using a `URL` as `options`: + * + * ```js + * const options = new URL('http://abc:xyz@example.com'); + * + * const req = http.request(options, (res) => { + * // ... + * }); + * ``` + * + * In a successful request, the following events will be emitted in the following + * order: + * + * * `'socket'` + * * `'response'` + * * `'data'` any number of times, on the `res` object + * (`'data'` will not be emitted at all if the response body is empty, for + * instance, in most redirects) + * * `'end'` on the `res` object + * * `'close'` + * + * In the case of a connection error, the following events will be emitted: + * + * * `'socket'` + * * `'error'` + * * `'close'` + * + * In the case of a premature connection close before the response is received, + * the following events will be emitted in the following order: + * + * * `'socket'` + * * `'error'` with an error with message `'Error: socket hang up'` and code`'ECONNRESET'` + * * `'close'` + * + * In the case of a premature connection close after the response is received, + * the following events will be emitted in the following order: + * + * * `'socket'` + * * `'response'` + * * `'data'` any number of times, on the `res` object + * * (connection closed here) + * * `'aborted'` on the `res` object + * * `'error'` on the `res` object with an error with message`'Error: aborted'` and code `'ECONNRESET'`. + * * `'close'` + * * `'close'` on the `res` object + * + * If `req.destroy()` is called before a socket is assigned, the following + * events will be emitted in the following order: + * + * * (`req.destroy()` called here) + * * `'error'` with an error with message `'Error: socket hang up'` and code`'ECONNRESET'` + * * `'close'` + * + * If `req.destroy()` is called before the connection succeeds, the following + * events will be emitted in the following order: + * + * * `'socket'` + * * (`req.destroy()` called here) + * * `'error'` with an error with message `'Error: socket hang up'` and code`'ECONNRESET'` + * * `'close'` + * + * If `req.destroy()` is called after the response is received, the following + * events will be emitted in the following order: + * + * * `'socket'` + * * `'response'` + * * `'data'` any number of times, on the `res` object + * * (`req.destroy()` called here) + * * `'aborted'` on the `res` object + * * `'error'` on the `res` object with an error with message`'Error: aborted'` and code `'ECONNRESET'`. + * * `'close'` + * * `'close'` on the `res` object + * + * If `req.abort()` is called before a socket is assigned, the following + * events will be emitted in the following order: + * + * * (`req.abort()` called here) + * * `'abort'` + * * `'close'` + * + * If `req.abort()` is called before the connection succeeds, the following + * events will be emitted in the following order: + * + * * `'socket'` + * * (`req.abort()` called here) + * * `'abort'` + * * `'error'` with an error with message `'Error: socket hang up'` and code`'ECONNRESET'` + * * `'close'` + * + * If `req.abort()` is called after the response is received, the following + * events will be emitted in the following order: + * + * * `'socket'` + * * `'response'` + * * `'data'` any number of times, on the `res` object + * * (`req.abort()` called here) + * * `'abort'` + * * `'aborted'` on the `res` object + * * `'error'` on the `res` object with an error with message`'Error: aborted'` and code `'ECONNRESET'`. + * * `'close'` + * * `'close'` on the `res` object + * + * Setting the `timeout` option or using the `setTimeout()` function will + * not abort the request or do anything besides add a `'timeout'` event. + * + * Passing an `AbortSignal` and then calling `abort` on the corresponding`AbortController` will behave the same way as calling `.destroy()` on the + * request itself. + * @since v0.3.6 + */ + function request(options: RequestOptions | string | URL, callback?: (res: IncomingMessage) => void): ClientRequest; + function request(url: string | URL, options: RequestOptions, callback?: (res: IncomingMessage) => void): ClientRequest; + /** + * Since most requests are GET requests without bodies, Node.js provides this + * convenience method. The only difference between this method and {@link request} is that it sets the method to GET and calls `req.end()`automatically. The callback must take care to consume the + * response + * data for reasons stated in {@link ClientRequest} section. + * + * The `callback` is invoked with a single argument that is an instance of {@link IncomingMessage}. + * + * JSON fetching example: + * + * ```js + * http.get('http://localhost:8000/', (res) => { + * const { statusCode } = res; + * const contentType = res.headers['content-type']; + * + * let error; + * // Any 2xx status code signals a successful response but + * // here we're only checking for 200. + * if (statusCode !== 200) { + * error = new Error('Request Failed.\n' + + * `Status Code: ${statusCode}`); + * } else if (!/^application\/json/.test(contentType)) { + * error = new Error('Invalid content-type.\n' + + * `Expected application/json but received ${contentType}`); + * } + * if (error) { + * console.error(error.message); + * // Consume response data to free up memory + * res.resume(); + * return; + * } + * + * res.setEncoding('utf8'); + * let rawData = ''; + * res.on('data', (chunk) => { rawData += chunk; }); + * res.on('end', () => { + * try { + * const parsedData = JSON.parse(rawData); + * console.log(parsedData); + * } catch (e) { + * console.error(e.message); + * } + * }); + * }).on('error', (e) => { + * console.error(`Got error: ${e.message}`); + * }); + * + * // Create a local server to receive data from + * const server = http.createServer((req, res) => { + * res.writeHead(200, { 'Content-Type': 'application/json' }); + * res.end(JSON.stringify({ + * data: 'Hello World!' + * })); + * }); + * + * server.listen(8000); + * ``` + * @since v0.3.6 + * @param options Accepts the same `options` as {@link request}, with the `method` always set to `GET`. Properties that are inherited from the prototype are ignored. + */ + function get(options: RequestOptions | string | URL, callback?: (res: IncomingMessage) => void): ClientRequest; + function get(url: string | URL, options: RequestOptions, callback?: (res: IncomingMessage) => void): ClientRequest; + let globalAgent: Agent; + /** + * Read-only property specifying the maximum allowed size of HTTP headers in bytes. + * Defaults to 16KB. Configurable using the `--max-http-header-size` CLI option. + */ + const maxHeaderSize: number; +} +declare module 'node:http' { + export * from 'http'; +} diff --git a/ts-ticket-office-service/node_modules/@types/node/http2.d.ts b/ts-ticket-office-service/node_modules/@types/node/http2.d.ts new file mode 100755 index 000000000..6dd174ac0 --- /dev/null +++ b/ts-ticket-office-service/node_modules/@types/node/http2.d.ts @@ -0,0 +1,2106 @@ +/** + * The `http2` module provides an implementation of the [HTTP/2](https://tools.ietf.org/html/rfc7540) protocol. It + * can be accessed using: + * + * ```js + * const http2 = require('http2'); + * ``` + * @since v8.4.0 + * @see [source](https://github.com/nodejs/node/blob/v18.0.0/lib/http2.js) + */ +declare module 'http2' { + import EventEmitter = require('node:events'); + import * as fs from 'node:fs'; + import * as net from 'node:net'; + import * as stream from 'node:stream'; + import * as tls from 'node:tls'; + import * as url from 'node:url'; + import { IncomingHttpHeaders as Http1IncomingHttpHeaders, OutgoingHttpHeaders, IncomingMessage, ServerResponse } from 'node:http'; + export { OutgoingHttpHeaders } from 'node:http'; + export interface IncomingHttpStatusHeader { + ':status'?: number | undefined; + } + export interface IncomingHttpHeaders extends Http1IncomingHttpHeaders { + ':path'?: string | undefined; + ':method'?: string | undefined; + ':authority'?: string | undefined; + ':scheme'?: string | undefined; + } + // Http2Stream + export interface StreamPriorityOptions { + exclusive?: boolean | undefined; + parent?: number | undefined; + weight?: number | undefined; + silent?: boolean | undefined; + } + export interface StreamState { + localWindowSize?: number | undefined; + state?: number | undefined; + localClose?: number | undefined; + remoteClose?: number | undefined; + sumDependencyWeight?: number | undefined; + weight?: number | undefined; + } + export interface ServerStreamResponseOptions { + endStream?: boolean | undefined; + waitForTrailers?: boolean | undefined; + } + export interface StatOptions { + offset: number; + length: number; + } + export interface ServerStreamFileResponseOptions { + statCheck?(stats: fs.Stats, headers: OutgoingHttpHeaders, statOptions: StatOptions): void | boolean; + waitForTrailers?: boolean | undefined; + offset?: number | undefined; + length?: number | undefined; + } + export interface ServerStreamFileResponseOptionsWithError extends ServerStreamFileResponseOptions { + onError?(err: NodeJS.ErrnoException): void; + } + export interface Http2Stream extends stream.Duplex { + /** + * Set to `true` if the `Http2Stream` instance was aborted abnormally. When set, + * the `'aborted'` event will have been emitted. + * @since v8.4.0 + */ + readonly aborted: boolean; + /** + * This property shows the number of characters currently buffered to be written. + * See `net.Socket.bufferSize` for details. + * @since v11.2.0, v10.16.0 + */ + readonly bufferSize: number; + /** + * Set to `true` if the `Http2Stream` instance has been closed. + * @since v9.4.0 + */ + readonly closed: boolean; + /** + * Set to `true` if the `Http2Stream` instance has been destroyed and is no longer + * usable. + * @since v8.4.0 + */ + readonly destroyed: boolean; + /** + * Set to `true` if the `END_STREAM` flag was set in the request or response + * HEADERS frame received, indicating that no additional data should be received + * and the readable side of the `Http2Stream` will be closed. + * @since v10.11.0 + */ + readonly endAfterHeaders: boolean; + /** + * The numeric stream identifier of this `Http2Stream` instance. Set to `undefined`if the stream identifier has not yet been assigned. + * @since v8.4.0 + */ + readonly id?: number | undefined; + /** + * Set to `true` if the `Http2Stream` instance has not yet been assigned a + * numeric stream identifier. + * @since v9.4.0 + */ + readonly pending: boolean; + /** + * Set to the `RST_STREAM` `error code` reported when the `Http2Stream` is + * destroyed after either receiving an `RST_STREAM` frame from the connected peer, + * calling `http2stream.close()`, or `http2stream.destroy()`. Will be`undefined` if the `Http2Stream` has not been closed. + * @since v8.4.0 + */ + readonly rstCode: number; + /** + * An object containing the outbound headers sent for this `Http2Stream`. + * @since v9.5.0 + */ + readonly sentHeaders: OutgoingHttpHeaders; + /** + * An array of objects containing the outbound informational (additional) headers + * sent for this `Http2Stream`. + * @since v9.5.0 + */ + readonly sentInfoHeaders?: OutgoingHttpHeaders[] | undefined; + /** + * An object containing the outbound trailers sent for this `HttpStream`. + * @since v9.5.0 + */ + readonly sentTrailers?: OutgoingHttpHeaders | undefined; + /** + * A reference to the `Http2Session` instance that owns this `Http2Stream`. The + * value will be `undefined` after the `Http2Stream` instance is destroyed. + * @since v8.4.0 + */ + readonly session: Http2Session; + /** + * Provides miscellaneous information about the current state of the`Http2Stream`. + * + * A current state of this `Http2Stream`. + * @since v8.4.0 + */ + readonly state: StreamState; + /** + * Closes the `Http2Stream` instance by sending an `RST_STREAM` frame to the + * connected HTTP/2 peer. + * @since v8.4.0 + * @param [code=http2.constants.NGHTTP2_NO_ERROR] Unsigned 32-bit integer identifying the error code. + * @param callback An optional function registered to listen for the `'close'` event. + */ + close(code?: number, callback?: () => void): void; + /** + * Updates the priority for this `Http2Stream` instance. + * @since v8.4.0 + */ + priority(options: StreamPriorityOptions): void; + /** + * ```js + * const http2 = require('http2'); + * const client = http2.connect('http://example.org:8000'); + * const { NGHTTP2_CANCEL } = http2.constants; + * const req = client.request({ ':path': '/' }); + * + * // Cancel the stream if there's no activity after 5 seconds + * req.setTimeout(5000, () => req.close(NGHTTP2_CANCEL)); + * ``` + * @since v8.4.0 + */ + setTimeout(msecs: number, callback?: () => void): void; + /** + * Sends a trailing `HEADERS` frame to the connected HTTP/2 peer. This method + * will cause the `Http2Stream` to be immediately closed and must only be + * called after the `'wantTrailers'` event has been emitted. When sending a + * request or sending a response, the `options.waitForTrailers` option must be set + * in order to keep the `Http2Stream` open after the final `DATA` frame so that + * trailers can be sent. + * + * ```js + * const http2 = require('http2'); + * const server = http2.createServer(); + * server.on('stream', (stream) => { + * stream.respond(undefined, { waitForTrailers: true }); + * stream.on('wantTrailers', () => { + * stream.sendTrailers({ xyz: 'abc' }); + * }); + * stream.end('Hello World'); + * }); + * ``` + * + * The HTTP/1 specification forbids trailers from containing HTTP/2 pseudo-header + * fields (e.g. `':method'`, `':path'`, etc). + * @since v10.0.0 + */ + sendTrailers(headers: OutgoingHttpHeaders): void; + addListener(event: 'aborted', listener: () => void): this; + addListener(event: 'close', listener: () => void): this; + addListener(event: 'data', listener: (chunk: Buffer | string) => void): this; + addListener(event: 'drain', listener: () => void): this; + addListener(event: 'end', listener: () => void): this; + addListener(event: 'error', listener: (err: Error) => void): this; + addListener(event: 'finish', listener: () => void): this; + addListener(event: 'frameError', listener: (frameType: number, errorCode: number) => void): this; + addListener(event: 'pipe', listener: (src: stream.Readable) => void): this; + addListener(event: 'unpipe', listener: (src: stream.Readable) => void): this; + addListener(event: 'streamClosed', listener: (code: number) => void): this; + addListener(event: 'timeout', listener: () => void): this; + addListener(event: 'trailers', listener: (trailers: IncomingHttpHeaders, flags: number) => void): this; + addListener(event: 'wantTrailers', listener: () => void): this; + addListener(event: string | symbol, listener: (...args: any[]) => void): this; + emit(event: 'aborted'): boolean; + emit(event: 'close'): boolean; + emit(event: 'data', chunk: Buffer | string): boolean; + emit(event: 'drain'): boolean; + emit(event: 'end'): boolean; + emit(event: 'error', err: Error): boolean; + emit(event: 'finish'): boolean; + emit(event: 'frameError', frameType: number, errorCode: number): boolean; + emit(event: 'pipe', src: stream.Readable): boolean; + emit(event: 'unpipe', src: stream.Readable): boolean; + emit(event: 'streamClosed', code: number): boolean; + emit(event: 'timeout'): boolean; + emit(event: 'trailers', trailers: IncomingHttpHeaders, flags: number): boolean; + emit(event: 'wantTrailers'): boolean; + emit(event: string | symbol, ...args: any[]): boolean; + on(event: 'aborted', listener: () => void): this; + on(event: 'close', listener: () => void): this; + on(event: 'data', listener: (chunk: Buffer | string) => void): this; + on(event: 'drain', listener: () => void): this; + on(event: 'end', listener: () => void): this; + on(event: 'error', listener: (err: Error) => void): this; + on(event: 'finish', listener: () => void): this; + on(event: 'frameError', listener: (frameType: number, errorCode: number) => void): this; + on(event: 'pipe', listener: (src: stream.Readable) => void): this; + on(event: 'unpipe', listener: (src: stream.Readable) => void): this; + on(event: 'streamClosed', listener: (code: number) => void): this; + on(event: 'timeout', listener: () => void): this; + on(event: 'trailers', listener: (trailers: IncomingHttpHeaders, flags: number) => void): this; + on(event: 'wantTrailers', listener: () => void): this; + on(event: string | symbol, listener: (...args: any[]) => void): this; + once(event: 'aborted', listener: () => void): this; + once(event: 'close', listener: () => void): this; + once(event: 'data', listener: (chunk: Buffer | string) => void): this; + once(event: 'drain', listener: () => void): this; + once(event: 'end', listener: () => void): this; + once(event: 'error', listener: (err: Error) => void): this; + once(event: 'finish', listener: () => void): this; + once(event: 'frameError', listener: (frameType: number, errorCode: number) => void): this; + once(event: 'pipe', listener: (src: stream.Readable) => void): this; + once(event: 'unpipe', listener: (src: stream.Readable) => void): this; + once(event: 'streamClosed', listener: (code: number) => void): this; + once(event: 'timeout', listener: () => void): this; + once(event: 'trailers', listener: (trailers: IncomingHttpHeaders, flags: number) => void): this; + once(event: 'wantTrailers', listener: () => void): this; + once(event: string | symbol, listener: (...args: any[]) => void): this; + prependListener(event: 'aborted', listener: () => void): this; + prependListener(event: 'close', listener: () => void): this; + prependListener(event: 'data', listener: (chunk: Buffer | string) => void): this; + prependListener(event: 'drain', listener: () => void): this; + prependListener(event: 'end', listener: () => void): this; + prependListener(event: 'error', listener: (err: Error) => void): this; + prependListener(event: 'finish', listener: () => void): this; + prependListener(event: 'frameError', listener: (frameType: number, errorCode: number) => void): this; + prependListener(event: 'pipe', listener: (src: stream.Readable) => void): this; + prependListener(event: 'unpipe', listener: (src: stream.Readable) => void): this; + prependListener(event: 'streamClosed', listener: (code: number) => void): this; + prependListener(event: 'timeout', listener: () => void): this; + prependListener(event: 'trailers', listener: (trailers: IncomingHttpHeaders, flags: number) => void): this; + prependListener(event: 'wantTrailers', listener: () => void): this; + prependListener(event: string | symbol, listener: (...args: any[]) => void): this; + prependOnceListener(event: 'aborted', listener: () => void): this; + prependOnceListener(event: 'close', listener: () => void): this; + prependOnceListener(event: 'data', listener: (chunk: Buffer | string) => void): this; + prependOnceListener(event: 'drain', listener: () => void): this; + prependOnceListener(event: 'end', listener: () => void): this; + prependOnceListener(event: 'error', listener: (err: Error) => void): this; + prependOnceListener(event: 'finish', listener: () => void): this; + prependOnceListener(event: 'frameError', listener: (frameType: number, errorCode: number) => void): this; + prependOnceListener(event: 'pipe', listener: (src: stream.Readable) => void): this; + prependOnceListener(event: 'unpipe', listener: (src: stream.Readable) => void): this; + prependOnceListener(event: 'streamClosed', listener: (code: number) => void): this; + prependOnceListener(event: 'timeout', listener: () => void): this; + prependOnceListener(event: 'trailers', listener: (trailers: IncomingHttpHeaders, flags: number) => void): this; + prependOnceListener(event: 'wantTrailers', listener: () => void): this; + prependOnceListener(event: string | symbol, listener: (...args: any[]) => void): this; + } + export interface ClientHttp2Stream extends Http2Stream { + addListener(event: 'continue', listener: () => {}): this; + addListener(event: 'headers', listener: (headers: IncomingHttpHeaders & IncomingHttpStatusHeader, flags: number) => void): this; + addListener(event: 'push', listener: (headers: IncomingHttpHeaders, flags: number) => void): this; + addListener(event: 'response', listener: (headers: IncomingHttpHeaders & IncomingHttpStatusHeader, flags: number) => void): this; + addListener(event: string | symbol, listener: (...args: any[]) => void): this; + emit(event: 'continue'): boolean; + emit(event: 'headers', headers: IncomingHttpHeaders & IncomingHttpStatusHeader, flags: number): boolean; + emit(event: 'push', headers: IncomingHttpHeaders, flags: number): boolean; + emit(event: 'response', headers: IncomingHttpHeaders & IncomingHttpStatusHeader, flags: number): boolean; + emit(event: string | symbol, ...args: any[]): boolean; + on(event: 'continue', listener: () => {}): this; + on(event: 'headers', listener: (headers: IncomingHttpHeaders & IncomingHttpStatusHeader, flags: number) => void): this; + on(event: 'push', listener: (headers: IncomingHttpHeaders, flags: number) => void): this; + on(event: 'response', listener: (headers: IncomingHttpHeaders & IncomingHttpStatusHeader, flags: number) => void): this; + on(event: string | symbol, listener: (...args: any[]) => void): this; + once(event: 'continue', listener: () => {}): this; + once(event: 'headers', listener: (headers: IncomingHttpHeaders & IncomingHttpStatusHeader, flags: number) => void): this; + once(event: 'push', listener: (headers: IncomingHttpHeaders, flags: number) => void): this; + once(event: 'response', listener: (headers: IncomingHttpHeaders & IncomingHttpStatusHeader, flags: number) => void): this; + once(event: string | symbol, listener: (...args: any[]) => void): this; + prependListener(event: 'continue', listener: () => {}): this; + prependListener(event: 'headers', listener: (headers: IncomingHttpHeaders & IncomingHttpStatusHeader, flags: number) => void): this; + prependListener(event: 'push', listener: (headers: IncomingHttpHeaders, flags: number) => void): this; + prependListener(event: 'response', listener: (headers: IncomingHttpHeaders & IncomingHttpStatusHeader, flags: number) => void): this; + prependListener(event: string | symbol, listener: (...args: any[]) => void): this; + prependOnceListener(event: 'continue', listener: () => {}): this; + prependOnceListener(event: 'headers', listener: (headers: IncomingHttpHeaders & IncomingHttpStatusHeader, flags: number) => void): this; + prependOnceListener(event: 'push', listener: (headers: IncomingHttpHeaders, flags: number) => void): this; + prependOnceListener(event: 'response', listener: (headers: IncomingHttpHeaders & IncomingHttpStatusHeader, flags: number) => void): this; + prependOnceListener(event: string | symbol, listener: (...args: any[]) => void): this; + } + export interface ServerHttp2Stream extends Http2Stream { + /** + * True if headers were sent, false otherwise (read-only). + * @since v8.4.0 + */ + readonly headersSent: boolean; + /** + * Read-only property mapped to the `SETTINGS_ENABLE_PUSH` flag of the remote + * client's most recent `SETTINGS` frame. Will be `true` if the remote peer + * accepts push streams, `false` otherwise. Settings are the same for every`Http2Stream` in the same `Http2Session`. + * @since v8.4.0 + */ + readonly pushAllowed: boolean; + /** + * Sends an additional informational `HEADERS` frame to the connected HTTP/2 peer. + * @since v8.4.0 + */ + additionalHeaders(headers: OutgoingHttpHeaders): void; + /** + * Initiates a push stream. The callback is invoked with the new `Http2Stream`instance created for the push stream passed as the second argument, or an`Error` passed as the first argument. + * + * ```js + * const http2 = require('http2'); + * const server = http2.createServer(); + * server.on('stream', (stream) => { + * stream.respond({ ':status': 200 }); + * stream.pushStream({ ':path': '/' }, (err, pushStream, headers) => { + * if (err) throw err; + * pushStream.respond({ ':status': 200 }); + * pushStream.end('some pushed data'); + * }); + * stream.end('some data'); + * }); + * ``` + * + * Setting the weight of a push stream is not allowed in the `HEADERS` frame. Pass + * a `weight` value to `http2stream.priority` with the `silent` option set to`true` to enable server-side bandwidth balancing between concurrent streams. + * + * Calling `http2stream.pushStream()` from within a pushed stream is not permitted + * and will throw an error. + * @since v8.4.0 + * @param callback Callback that is called once the push stream has been initiated. + */ + pushStream(headers: OutgoingHttpHeaders, callback?: (err: Error | null, pushStream: ServerHttp2Stream, headers: OutgoingHttpHeaders) => void): void; + pushStream(headers: OutgoingHttpHeaders, options?: StreamPriorityOptions, callback?: (err: Error | null, pushStream: ServerHttp2Stream, headers: OutgoingHttpHeaders) => void): void; + /** + * ```js + * const http2 = require('http2'); + * const server = http2.createServer(); + * server.on('stream', (stream) => { + * stream.respond({ ':status': 200 }); + * stream.end('some data'); + * }); + * ``` + * + * When the `options.waitForTrailers` option is set, the `'wantTrailers'` event + * will be emitted immediately after queuing the last chunk of payload data to be + * sent. The `http2stream.sendTrailers()` method can then be used to sent trailing + * header fields to the peer. + * + * When `options.waitForTrailers` is set, the `Http2Stream` will not automatically + * close when the final `DATA` frame is transmitted. User code must call either`http2stream.sendTrailers()` or `http2stream.close()` to close the`Http2Stream`. + * + * ```js + * const http2 = require('http2'); + * const server = http2.createServer(); + * server.on('stream', (stream) => { + * stream.respond({ ':status': 200 }, { waitForTrailers: true }); + * stream.on('wantTrailers', () => { + * stream.sendTrailers({ ABC: 'some value to send' }); + * }); + * stream.end('some data'); + * }); + * ``` + * @since v8.4.0 + */ + respond(headers?: OutgoingHttpHeaders, options?: ServerStreamResponseOptions): void; + /** + * Initiates a response whose data is read from the given file descriptor. No + * validation is performed on the given file descriptor. If an error occurs while + * attempting to read data using the file descriptor, the `Http2Stream` will be + * closed using an `RST_STREAM` frame using the standard `INTERNAL_ERROR` code. + * + * When used, the `Http2Stream` object's `Duplex` interface will be closed + * automatically. + * + * ```js + * const http2 = require('http2'); + * const fs = require('fs'); + * + * const server = http2.createServer(); + * server.on('stream', (stream) => { + * const fd = fs.openSync('/some/file', 'r'); + * + * const stat = fs.fstatSync(fd); + * const headers = { + * 'content-length': stat.size, + * 'last-modified': stat.mtime.toUTCString(), + * 'content-type': 'text/plain; charset=utf-8' + * }; + * stream.respondWithFD(fd, headers); + * stream.on('close', () => fs.closeSync(fd)); + * }); + * ``` + * + * The optional `options.statCheck` function may be specified to give user code + * an opportunity to set additional content headers based on the `fs.Stat` details + * of the given fd. If the `statCheck` function is provided, the`http2stream.respondWithFD()` method will perform an `fs.fstat()` call to + * collect details on the provided file descriptor. + * + * The `offset` and `length` options may be used to limit the response to a + * specific range subset. This can be used, for instance, to support HTTP Range + * requests. + * + * The file descriptor or `FileHandle` is not closed when the stream is closed, + * so it will need to be closed manually once it is no longer needed. + * Using the same file descriptor concurrently for multiple streams + * is not supported and may result in data loss. Re-using a file descriptor + * after a stream has finished is supported. + * + * When the `options.waitForTrailers` option is set, the `'wantTrailers'` event + * will be emitted immediately after queuing the last chunk of payload data to be + * sent. The `http2stream.sendTrailers()` method can then be used to sent trailing + * header fields to the peer. + * + * When `options.waitForTrailers` is set, the `Http2Stream` will not automatically + * close when the final `DATA` frame is transmitted. User code _must_ call either`http2stream.sendTrailers()` or `http2stream.close()` to close the`Http2Stream`. + * + * ```js + * const http2 = require('http2'); + * const fs = require('fs'); + * + * const server = http2.createServer(); + * server.on('stream', (stream) => { + * const fd = fs.openSync('/some/file', 'r'); + * + * const stat = fs.fstatSync(fd); + * const headers = { + * 'content-length': stat.size, + * 'last-modified': stat.mtime.toUTCString(), + * 'content-type': 'text/plain; charset=utf-8' + * }; + * stream.respondWithFD(fd, headers, { waitForTrailers: true }); + * stream.on('wantTrailers', () => { + * stream.sendTrailers({ ABC: 'some value to send' }); + * }); + * + * stream.on('close', () => fs.closeSync(fd)); + * }); + * ``` + * @since v8.4.0 + * @param fd A readable file descriptor. + */ + respondWithFD(fd: number | fs.promises.FileHandle, headers?: OutgoingHttpHeaders, options?: ServerStreamFileResponseOptions): void; + /** + * Sends a regular file as the response. The `path` must specify a regular file + * or an `'error'` event will be emitted on the `Http2Stream` object. + * + * When used, the `Http2Stream` object's `Duplex` interface will be closed + * automatically. + * + * The optional `options.statCheck` function may be specified to give user code + * an opportunity to set additional content headers based on the `fs.Stat` details + * of the given file: + * + * If an error occurs while attempting to read the file data, the `Http2Stream`will be closed using an `RST_STREAM` frame using the standard `INTERNAL_ERROR`code. If the `onError` callback is + * defined, then it will be called. Otherwise + * the stream will be destroyed. + * + * Example using a file path: + * + * ```js + * const http2 = require('http2'); + * const server = http2.createServer(); + * server.on('stream', (stream) => { + * function statCheck(stat, headers) { + * headers['last-modified'] = stat.mtime.toUTCString(); + * } + * + * function onError(err) { + * // stream.respond() can throw if the stream has been destroyed by + * // the other side. + * try { + * if (err.code === 'ENOENT') { + * stream.respond({ ':status': 404 }); + * } else { + * stream.respond({ ':status': 500 }); + * } + * } catch (err) { + * // Perform actual error handling. + * console.log(err); + * } + * stream.end(); + * } + * + * stream.respondWithFile('/some/file', + * { 'content-type': 'text/plain; charset=utf-8' }, + * { statCheck, onError }); + * }); + * ``` + * + * The `options.statCheck` function may also be used to cancel the send operation + * by returning `false`. For instance, a conditional request may check the stat + * results to determine if the file has been modified to return an appropriate`304` response: + * + * ```js + * const http2 = require('http2'); + * const server = http2.createServer(); + * server.on('stream', (stream) => { + * function statCheck(stat, headers) { + * // Check the stat here... + * stream.respond({ ':status': 304 }); + * return false; // Cancel the send operation + * } + * stream.respondWithFile('/some/file', + * { 'content-type': 'text/plain; charset=utf-8' }, + * { statCheck }); + * }); + * ``` + * + * The `content-length` header field will be automatically set. + * + * The `offset` and `length` options may be used to limit the response to a + * specific range subset. This can be used, for instance, to support HTTP Range + * requests. + * + * The `options.onError` function may also be used to handle all the errors + * that could happen before the delivery of the file is initiated. The + * default behavior is to destroy the stream. + * + * When the `options.waitForTrailers` option is set, the `'wantTrailers'` event + * will be emitted immediately after queuing the last chunk of payload data to be + * sent. The `http2stream.sendTrailers()` method can then be used to sent trailing + * header fields to the peer. + * + * When `options.waitForTrailers` is set, the `Http2Stream` will not automatically + * close when the final `DATA` frame is transmitted. User code must call either`http2stream.sendTrailers()` or `http2stream.close()` to close the`Http2Stream`. + * + * ```js + * const http2 = require('http2'); + * const server = http2.createServer(); + * server.on('stream', (stream) => { + * stream.respondWithFile('/some/file', + * { 'content-type': 'text/plain; charset=utf-8' }, + * { waitForTrailers: true }); + * stream.on('wantTrailers', () => { + * stream.sendTrailers({ ABC: 'some value to send' }); + * }); + * }); + * ``` + * @since v8.4.0 + */ + respondWithFile(path: string, headers?: OutgoingHttpHeaders, options?: ServerStreamFileResponseOptionsWithError): void; + } + // Http2Session + export interface Settings { + headerTableSize?: number | undefined; + enablePush?: boolean | undefined; + initialWindowSize?: number | undefined; + maxFrameSize?: number | undefined; + maxConcurrentStreams?: number | undefined; + maxHeaderListSize?: number | undefined; + enableConnectProtocol?: boolean | undefined; + } + export interface ClientSessionRequestOptions { + endStream?: boolean | undefined; + exclusive?: boolean | undefined; + parent?: number | undefined; + weight?: number | undefined; + waitForTrailers?: boolean | undefined; + signal?: AbortSignal | undefined; + } + export interface SessionState { + effectiveLocalWindowSize?: number | undefined; + effectiveRecvDataLength?: number | undefined; + nextStreamID?: number | undefined; + localWindowSize?: number | undefined; + lastProcStreamID?: number | undefined; + remoteWindowSize?: number | undefined; + outboundQueueSize?: number | undefined; + deflateDynamicTableSize?: number | undefined; + inflateDynamicTableSize?: number | undefined; + } + export interface Http2Session extends EventEmitter { + /** + * Value will be `undefined` if the `Http2Session` is not yet connected to a + * socket, `h2c` if the `Http2Session` is not connected to a `TLSSocket`, or + * will return the value of the connected `TLSSocket`'s own `alpnProtocol`property. + * @since v9.4.0 + */ + readonly alpnProtocol?: string | undefined; + /** + * Will be `true` if this `Http2Session` instance has been closed, otherwise`false`. + * @since v9.4.0 + */ + readonly closed: boolean; + /** + * Will be `true` if this `Http2Session` instance is still connecting, will be set + * to `false` before emitting `connect` event and/or calling the `http2.connect`callback. + * @since v10.0.0 + */ + readonly connecting: boolean; + /** + * Will be `true` if this `Http2Session` instance has been destroyed and must no + * longer be used, otherwise `false`. + * @since v8.4.0 + */ + readonly destroyed: boolean; + /** + * Value is `undefined` if the `Http2Session` session socket has not yet been + * connected, `true` if the `Http2Session` is connected with a `TLSSocket`, + * and `false` if the `Http2Session` is connected to any other kind of socket + * or stream. + * @since v9.4.0 + */ + readonly encrypted?: boolean | undefined; + /** + * A prototype-less object describing the current local settings of this`Http2Session`. The local settings are local to _this_`Http2Session` instance. + * @since v8.4.0 + */ + readonly localSettings: Settings; + /** + * If the `Http2Session` is connected to a `TLSSocket`, the `originSet` property + * will return an `Array` of origins for which the `Http2Session` may be + * considered authoritative. + * + * The `originSet` property is only available when using a secure TLS connection. + * @since v9.4.0 + */ + readonly originSet?: string[] | undefined; + /** + * Indicates whether the `Http2Session` is currently waiting for acknowledgment of + * a sent `SETTINGS` frame. Will be `true` after calling the`http2session.settings()` method. Will be `false` once all sent `SETTINGS`frames have been acknowledged. + * @since v8.4.0 + */ + readonly pendingSettingsAck: boolean; + /** + * A prototype-less object describing the current remote settings of this`Http2Session`. The remote settings are set by the _connected_ HTTP/2 peer. + * @since v8.4.0 + */ + readonly remoteSettings: Settings; + /** + * Returns a `Proxy` object that acts as a `net.Socket` (or `tls.TLSSocket`) but + * limits available methods to ones safe to use with HTTP/2. + * + * `destroy`, `emit`, `end`, `pause`, `read`, `resume`, and `write` will throw + * an error with code `ERR_HTTP2_NO_SOCKET_MANIPULATION`. See `Http2Session and Sockets` for more information. + * + * `setTimeout` method will be called on this `Http2Session`. + * + * All other interactions will be routed directly to the socket. + * @since v8.4.0 + */ + readonly socket: net.Socket | tls.TLSSocket; + /** + * Provides miscellaneous information about the current state of the`Http2Session`. + * + * An object describing the current status of this `Http2Session`. + * @since v8.4.0 + */ + readonly state: SessionState; + /** + * The `http2session.type` will be equal to`http2.constants.NGHTTP2_SESSION_SERVER` if this `Http2Session` instance is a + * server, and `http2.constants.NGHTTP2_SESSION_CLIENT` if the instance is a + * client. + * @since v8.4.0 + */ + readonly type: number; + /** + * Gracefully closes the `Http2Session`, allowing any existing streams to + * complete on their own and preventing new `Http2Stream` instances from being + * created. Once closed, `http2session.destroy()`_might_ be called if there + * are no open `Http2Stream` instances. + * + * If specified, the `callback` function is registered as a handler for the`'close'` event. + * @since v9.4.0 + */ + close(callback?: () => void): void; + /** + * Immediately terminates the `Http2Session` and the associated `net.Socket` or`tls.TLSSocket`. + * + * Once destroyed, the `Http2Session` will emit the `'close'` event. If `error`is not undefined, an `'error'` event will be emitted immediately before the`'close'` event. + * + * If there are any remaining open `Http2Streams` associated with the`Http2Session`, those will also be destroyed. + * @since v8.4.0 + * @param error An `Error` object if the `Http2Session` is being destroyed due to an error. + * @param code The HTTP/2 error code to send in the final `GOAWAY` frame. If unspecified, and `error` is not undefined, the default is `INTERNAL_ERROR`, otherwise defaults to `NO_ERROR`. + */ + destroy(error?: Error, code?: number): void; + /** + * Transmits a `GOAWAY` frame to the connected peer _without_ shutting down the`Http2Session`. + * @since v9.4.0 + * @param code An HTTP/2 error code + * @param lastStreamID The numeric ID of the last processed `Http2Stream` + * @param opaqueData A `TypedArray` or `DataView` instance containing additional data to be carried within the `GOAWAY` frame. + */ + goaway(code?: number, lastStreamID?: number, opaqueData?: NodeJS.ArrayBufferView): void; + /** + * Sends a `PING` frame to the connected HTTP/2 peer. A `callback` function must + * be provided. The method will return `true` if the `PING` was sent, `false`otherwise. + * + * The maximum number of outstanding (unacknowledged) pings is determined by the`maxOutstandingPings` configuration option. The default maximum is 10. + * + * If provided, the `payload` must be a `Buffer`, `TypedArray`, or `DataView`containing 8 bytes of data that will be transmitted with the `PING` and + * returned with the ping acknowledgment. + * + * The callback will be invoked with three arguments: an error argument that will + * be `null` if the `PING` was successfully acknowledged, a `duration` argument + * that reports the number of milliseconds elapsed since the ping was sent and the + * acknowledgment was received, and a `Buffer` containing the 8-byte `PING`payload. + * + * ```js + * session.ping(Buffer.from('abcdefgh'), (err, duration, payload) => { + * if (!err) { + * console.log(`Ping acknowledged in ${duration} milliseconds`); + * console.log(`With payload '${payload.toString()}'`); + * } + * }); + * ``` + * + * If the `payload` argument is not specified, the default payload will be the + * 64-bit timestamp (little endian) marking the start of the `PING` duration. + * @since v8.9.3 + * @param payload Optional ping payload. + */ + ping(callback: (err: Error | null, duration: number, payload: Buffer) => void): boolean; + ping(payload: NodeJS.ArrayBufferView, callback: (err: Error | null, duration: number, payload: Buffer) => void): boolean; + /** + * Calls `ref()` on this `Http2Session`instance's underlying `net.Socket`. + * @since v9.4.0 + */ + ref(): void; + /** + * Sets the local endpoint's window size. + * The `windowSize` is the total window size to set, not + * the delta. + * + * ```js + * const http2 = require('http2'); + * + * const server = http2.createServer(); + * const expectedWindowSize = 2 ** 20; + * server.on('connect', (session) => { + * + * // Set local window size to be 2 ** 20 + * session.setLocalWindowSize(expectedWindowSize); + * }); + * ``` + * @since v15.3.0, v14.18.0 + */ + setLocalWindowSize(windowSize: number): void; + /** + * Used to set a callback function that is called when there is no activity on + * the `Http2Session` after `msecs` milliseconds. The given `callback` is + * registered as a listener on the `'timeout'` event. + * @since v8.4.0 + */ + setTimeout(msecs: number, callback?: () => void): void; + /** + * Updates the current local settings for this `Http2Session` and sends a new`SETTINGS` frame to the connected HTTP/2 peer. + * + * Once called, the `http2session.pendingSettingsAck` property will be `true`while the session is waiting for the remote peer to acknowledge the new + * settings. + * + * The new settings will not become effective until the `SETTINGS` acknowledgment + * is received and the `'localSettings'` event is emitted. It is possible to send + * multiple `SETTINGS` frames while acknowledgment is still pending. + * @since v8.4.0 + * @param callback Callback that is called once the session is connected or right away if the session is already connected. + */ + settings(settings: Settings): void; + /** + * Calls `unref()` on this `Http2Session`instance's underlying `net.Socket`. + * @since v9.4.0 + */ + unref(): void; + addListener(event: 'close', listener: () => void): this; + addListener(event: 'error', listener: (err: Error) => void): this; + addListener(event: 'frameError', listener: (frameType: number, errorCode: number, streamID: number) => void): this; + addListener(event: 'goaway', listener: (errorCode: number, lastStreamID: number, opaqueData: Buffer) => void): this; + addListener(event: 'localSettings', listener: (settings: Settings) => void): this; + addListener(event: 'ping', listener: () => void): this; + addListener(event: 'remoteSettings', listener: (settings: Settings) => void): this; + addListener(event: 'timeout', listener: () => void): this; + addListener(event: string | symbol, listener: (...args: any[]) => void): this; + emit(event: 'close'): boolean; + emit(event: 'error', err: Error): boolean; + emit(event: 'frameError', frameType: number, errorCode: number, streamID: number): boolean; + emit(event: 'goaway', errorCode: number, lastStreamID: number, opaqueData: Buffer): boolean; + emit(event: 'localSettings', settings: Settings): boolean; + emit(event: 'ping'): boolean; + emit(event: 'remoteSettings', settings: Settings): boolean; + emit(event: 'timeout'): boolean; + emit(event: string | symbol, ...args: any[]): boolean; + on(event: 'close', listener: () => void): this; + on(event: 'error', listener: (err: Error) => void): this; + on(event: 'frameError', listener: (frameType: number, errorCode: number, streamID: number) => void): this; + on(event: 'goaway', listener: (errorCode: number, lastStreamID: number, opaqueData: Buffer) => void): this; + on(event: 'localSettings', listener: (settings: Settings) => void): this; + on(event: 'ping', listener: () => void): this; + on(event: 'remoteSettings', listener: (settings: Settings) => void): this; + on(event: 'timeout', listener: () => void): this; + on(event: string | symbol, listener: (...args: any[]) => void): this; + once(event: 'close', listener: () => void): this; + once(event: 'error', listener: (err: Error) => void): this; + once(event: 'frameError', listener: (frameType: number, errorCode: number, streamID: number) => void): this; + once(event: 'goaway', listener: (errorCode: number, lastStreamID: number, opaqueData: Buffer) => void): this; + once(event: 'localSettings', listener: (settings: Settings) => void): this; + once(event: 'ping', listener: () => void): this; + once(event: 'remoteSettings', listener: (settings: Settings) => void): this; + once(event: 'timeout', listener: () => void): this; + once(event: string | symbol, listener: (...args: any[]) => void): this; + prependListener(event: 'close', listener: () => void): this; + prependListener(event: 'error', listener: (err: Error) => void): this; + prependListener(event: 'frameError', listener: (frameType: number, errorCode: number, streamID: number) => void): this; + prependListener(event: 'goaway', listener: (errorCode: number, lastStreamID: number, opaqueData: Buffer) => void): this; + prependListener(event: 'localSettings', listener: (settings: Settings) => void): this; + prependListener(event: 'ping', listener: () => void): this; + prependListener(event: 'remoteSettings', listener: (settings: Settings) => void): this; + prependListener(event: 'timeout', listener: () => void): this; + prependListener(event: string | symbol, listener: (...args: any[]) => void): this; + prependOnceListener(event: 'close', listener: () => void): this; + prependOnceListener(event: 'error', listener: (err: Error) => void): this; + prependOnceListener(event: 'frameError', listener: (frameType: number, errorCode: number, streamID: number) => void): this; + prependOnceListener(event: 'goaway', listener: (errorCode: number, lastStreamID: number, opaqueData: Buffer) => void): this; + prependOnceListener(event: 'localSettings', listener: (settings: Settings) => void): this; + prependOnceListener(event: 'ping', listener: () => void): this; + prependOnceListener(event: 'remoteSettings', listener: (settings: Settings) => void): this; + prependOnceListener(event: 'timeout', listener: () => void): this; + prependOnceListener(event: string | symbol, listener: (...args: any[]) => void): this; + } + export interface ClientHttp2Session extends Http2Session { + /** + * For HTTP/2 Client `Http2Session` instances only, the `http2session.request()`creates and returns an `Http2Stream` instance that can be used to send an + * HTTP/2 request to the connected server. + * + * When a `ClientHttp2Session` is first created, the socket may not yet be + * connected. if `clienthttp2session.request()` is called during this time, the + * actual request will be deferred until the socket is ready to go. + * If the `session` is closed before the actual request be executed, an`ERR_HTTP2_GOAWAY_SESSION` is thrown. + * + * This method is only available if `http2session.type` is equal to`http2.constants.NGHTTP2_SESSION_CLIENT`. + * + * ```js + * const http2 = require('http2'); + * const clientSession = http2.connect('https://localhost:1234'); + * const { + * HTTP2_HEADER_PATH, + * HTTP2_HEADER_STATUS + * } = http2.constants; + * + * const req = clientSession.request({ [HTTP2_HEADER_PATH]: '/' }); + * req.on('response', (headers) => { + * console.log(headers[HTTP2_HEADER_STATUS]); + * req.on('data', (chunk) => { // .. }); + * req.on('end', () => { // .. }); + * }); + * ``` + * + * When the `options.waitForTrailers` option is set, the `'wantTrailers'` event + * is emitted immediately after queuing the last chunk of payload data to be sent. + * The `http2stream.sendTrailers()` method can then be called to send trailing + * headers to the peer. + * + * When `options.waitForTrailers` is set, the `Http2Stream` will not automatically + * close when the final `DATA` frame is transmitted. User code must call either`http2stream.sendTrailers()` or `http2stream.close()` to close the`Http2Stream`. + * + * When `options.signal` is set with an `AbortSignal` and then `abort` on the + * corresponding `AbortController` is called, the request will emit an `'error'`event with an `AbortError` error. + * + * The `:method` and `:path` pseudo-headers are not specified within `headers`, + * they respectively default to: + * + * * `:method` \= `'GET'` + * * `:path` \= `/` + * @since v8.4.0 + */ + request(headers?: OutgoingHttpHeaders, options?: ClientSessionRequestOptions): ClientHttp2Stream; + addListener(event: 'altsvc', listener: (alt: string, origin: string, stream: number) => void): this; + addListener(event: 'origin', listener: (origins: string[]) => void): this; + addListener(event: 'connect', listener: (session: ClientHttp2Session, socket: net.Socket | tls.TLSSocket) => void): this; + addListener(event: 'stream', listener: (stream: ClientHttp2Stream, headers: IncomingHttpHeaders & IncomingHttpStatusHeader, flags: number) => void): this; + addListener(event: string | symbol, listener: (...args: any[]) => void): this; + emit(event: 'altsvc', alt: string, origin: string, stream: number): boolean; + emit(event: 'origin', origins: ReadonlyArray): boolean; + emit(event: 'connect', session: ClientHttp2Session, socket: net.Socket | tls.TLSSocket): boolean; + emit(event: 'stream', stream: ClientHttp2Stream, headers: IncomingHttpHeaders & IncomingHttpStatusHeader, flags: number): boolean; + emit(event: string | symbol, ...args: any[]): boolean; + on(event: 'altsvc', listener: (alt: string, origin: string, stream: number) => void): this; + on(event: 'origin', listener: (origins: string[]) => void): this; + on(event: 'connect', listener: (session: ClientHttp2Session, socket: net.Socket | tls.TLSSocket) => void): this; + on(event: 'stream', listener: (stream: ClientHttp2Stream, headers: IncomingHttpHeaders & IncomingHttpStatusHeader, flags: number) => void): this; + on(event: string | symbol, listener: (...args: any[]) => void): this; + once(event: 'altsvc', listener: (alt: string, origin: string, stream: number) => void): this; + once(event: 'origin', listener: (origins: string[]) => void): this; + once(event: 'connect', listener: (session: ClientHttp2Session, socket: net.Socket | tls.TLSSocket) => void): this; + once(event: 'stream', listener: (stream: ClientHttp2Stream, headers: IncomingHttpHeaders & IncomingHttpStatusHeader, flags: number) => void): this; + once(event: string | symbol, listener: (...args: any[]) => void): this; + prependListener(event: 'altsvc', listener: (alt: string, origin: string, stream: number) => void): this; + prependListener(event: 'origin', listener: (origins: string[]) => void): this; + prependListener(event: 'connect', listener: (session: ClientHttp2Session, socket: net.Socket | tls.TLSSocket) => void): this; + prependListener(event: 'stream', listener: (stream: ClientHttp2Stream, headers: IncomingHttpHeaders & IncomingHttpStatusHeader, flags: number) => void): this; + prependListener(event: string | symbol, listener: (...args: any[]) => void): this; + prependOnceListener(event: 'altsvc', listener: (alt: string, origin: string, stream: number) => void): this; + prependOnceListener(event: 'origin', listener: (origins: string[]) => void): this; + prependOnceListener(event: 'connect', listener: (session: ClientHttp2Session, socket: net.Socket | tls.TLSSocket) => void): this; + prependOnceListener(event: 'stream', listener: (stream: ClientHttp2Stream, headers: IncomingHttpHeaders & IncomingHttpStatusHeader, flags: number) => void): this; + prependOnceListener(event: string | symbol, listener: (...args: any[]) => void): this; + } + export interface AlternativeServiceOptions { + origin: number | string | url.URL; + } + export interface ServerHttp2Session extends Http2Session { + readonly server: Http2Server | Http2SecureServer; + /** + * Submits an `ALTSVC` frame (as defined by [RFC 7838](https://tools.ietf.org/html/rfc7838)) to the connected client. + * + * ```js + * const http2 = require('http2'); + * + * const server = http2.createServer(); + * server.on('session', (session) => { + * // Set altsvc for origin https://example.org:80 + * session.altsvc('h2=":8000"', 'https://example.org:80'); + * }); + * + * server.on('stream', (stream) => { + * // Set altsvc for a specific stream + * stream.session.altsvc('h2=":8000"', stream.id); + * }); + * ``` + * + * Sending an `ALTSVC` frame with a specific stream ID indicates that the alternate + * service is associated with the origin of the given `Http2Stream`. + * + * The `alt` and origin string _must_ contain only ASCII bytes and are + * strictly interpreted as a sequence of ASCII bytes. The special value `'clear'`may be passed to clear any previously set alternative service for a given + * domain. + * + * When a string is passed for the `originOrStream` argument, it will be parsed as + * a URL and the origin will be derived. For instance, the origin for the + * HTTP URL `'https://example.org/foo/bar'` is the ASCII string`'https://example.org'`. An error will be thrown if either the given string + * cannot be parsed as a URL or if a valid origin cannot be derived. + * + * A `URL` object, or any object with an `origin` property, may be passed as`originOrStream`, in which case the value of the `origin` property will be + * used. The value of the `origin` property _must_ be a properly serialized + * ASCII origin. + * @since v9.4.0 + * @param alt A description of the alternative service configuration as defined by `RFC 7838`. + * @param originOrStream Either a URL string specifying the origin (or an `Object` with an `origin` property) or the numeric identifier of an active `Http2Stream` as given by the + * `http2stream.id` property. + */ + altsvc(alt: string, originOrStream: number | string | url.URL | AlternativeServiceOptions): void; + /** + * Submits an `ORIGIN` frame (as defined by [RFC 8336](https://tools.ietf.org/html/rfc8336)) to the connected client + * to advertise the set of origins for which the server is capable of providing + * authoritative responses. + * + * ```js + * const http2 = require('http2'); + * const options = getSecureOptionsSomehow(); + * const server = http2.createSecureServer(options); + * server.on('stream', (stream) => { + * stream.respond(); + * stream.end('ok'); + * }); + * server.on('session', (session) => { + * session.origin('https://example.com', 'https://example.org'); + * }); + * ``` + * + * When a string is passed as an `origin`, it will be parsed as a URL and the + * origin will be derived. For instance, the origin for the HTTP URL`'https://example.org/foo/bar'` is the ASCII string`'https://example.org'`. An error will be thrown if either the given + * string + * cannot be parsed as a URL or if a valid origin cannot be derived. + * + * A `URL` object, or any object with an `origin` property, may be passed as + * an `origin`, in which case the value of the `origin` property will be + * used. The value of the `origin` property _must_ be a properly serialized + * ASCII origin. + * + * Alternatively, the `origins` option may be used when creating a new HTTP/2 + * server using the `http2.createSecureServer()` method: + * + * ```js + * const http2 = require('http2'); + * const options = getSecureOptionsSomehow(); + * options.origins = ['https://example.com', 'https://example.org']; + * const server = http2.createSecureServer(options); + * server.on('stream', (stream) => { + * stream.respond(); + * stream.end('ok'); + * }); + * ``` + * @since v10.12.0 + * @param origins One or more URL Strings passed as separate arguments. + */ + origin( + ...origins: Array< + | string + | url.URL + | { + origin: string; + } + > + ): void; + addListener(event: 'connect', listener: (session: ServerHttp2Session, socket: net.Socket | tls.TLSSocket) => void): this; + addListener(event: 'stream', listener: (stream: ServerHttp2Stream, headers: IncomingHttpHeaders, flags: number) => void): this; + addListener(event: string | symbol, listener: (...args: any[]) => void): this; + emit(event: 'connect', session: ServerHttp2Session, socket: net.Socket | tls.TLSSocket): boolean; + emit(event: 'stream', stream: ServerHttp2Stream, headers: IncomingHttpHeaders, flags: number): boolean; + emit(event: string | symbol, ...args: any[]): boolean; + on(event: 'connect', listener: (session: ServerHttp2Session, socket: net.Socket | tls.TLSSocket) => void): this; + on(event: 'stream', listener: (stream: ServerHttp2Stream, headers: IncomingHttpHeaders, flags: number) => void): this; + on(event: string | symbol, listener: (...args: any[]) => void): this; + once(event: 'connect', listener: (session: ServerHttp2Session, socket: net.Socket | tls.TLSSocket) => void): this; + once(event: 'stream', listener: (stream: ServerHttp2Stream, headers: IncomingHttpHeaders, flags: number) => void): this; + once(event: string | symbol, listener: (...args: any[]) => void): this; + prependListener(event: 'connect', listener: (session: ServerHttp2Session, socket: net.Socket | tls.TLSSocket) => void): this; + prependListener(event: 'stream', listener: (stream: ServerHttp2Stream, headers: IncomingHttpHeaders, flags: number) => void): this; + prependListener(event: string | symbol, listener: (...args: any[]) => void): this; + prependOnceListener(event: 'connect', listener: (session: ServerHttp2Session, socket: net.Socket | tls.TLSSocket) => void): this; + prependOnceListener(event: 'stream', listener: (stream: ServerHttp2Stream, headers: IncomingHttpHeaders, flags: number) => void): this; + prependOnceListener(event: string | symbol, listener: (...args: any[]) => void): this; + } + // Http2Server + export interface SessionOptions { + maxDeflateDynamicTableSize?: number | undefined; + maxSessionMemory?: number | undefined; + maxHeaderListPairs?: number | undefined; + maxOutstandingPings?: number | undefined; + maxSendHeaderBlockLength?: number | undefined; + paddingStrategy?: number | undefined; + peerMaxConcurrentStreams?: number | undefined; + settings?: Settings | undefined; + /** + * Specifies a timeout in milliseconds that + * a server should wait when an [`'unknownProtocol'`][] is emitted. If the + * socket has not been destroyed by that time the server will destroy it. + * @default 100000 + */ + unknownProtocolTimeout?: number | undefined; + selectPadding?(frameLen: number, maxFrameLen: number): number; + createConnection?(authority: url.URL, option: SessionOptions): stream.Duplex; + } + export interface ClientSessionOptions extends SessionOptions { + maxReservedRemoteStreams?: number | undefined; + createConnection?: ((authority: url.URL, option: SessionOptions) => stream.Duplex) | undefined; + protocol?: 'http:' | 'https:' | undefined; + } + export interface ServerSessionOptions extends SessionOptions { + Http1IncomingMessage?: typeof IncomingMessage | undefined; + Http1ServerResponse?: typeof ServerResponse | undefined; + Http2ServerRequest?: typeof Http2ServerRequest | undefined; + Http2ServerResponse?: typeof Http2ServerResponse | undefined; + } + export interface SecureClientSessionOptions extends ClientSessionOptions, tls.ConnectionOptions {} + export interface SecureServerSessionOptions extends ServerSessionOptions, tls.TlsOptions {} + export interface ServerOptions extends ServerSessionOptions {} + export interface SecureServerOptions extends SecureServerSessionOptions { + allowHTTP1?: boolean | undefined; + origins?: string[] | undefined; + } + interface HTTP2ServerCommon { + setTimeout(msec?: number, callback?: () => void): this; + /** + * Throws ERR_HTTP2_INVALID_SETTING_VALUE for invalid settings values. + * Throws ERR_INVALID_ARG_TYPE for invalid settings argument. + */ + updateSettings(settings: Settings): void; + } + export interface Http2Server extends net.Server, HTTP2ServerCommon { + addListener(event: 'checkContinue', listener: (request: Http2ServerRequest, response: Http2ServerResponse) => void): this; + addListener(event: 'request', listener: (request: Http2ServerRequest, response: Http2ServerResponse) => void): this; + addListener(event: 'session', listener: (session: ServerHttp2Session) => void): this; + addListener(event: 'sessionError', listener: (err: Error) => void): this; + addListener(event: 'stream', listener: (stream: ServerHttp2Stream, headers: IncomingHttpHeaders, flags: number) => void): this; + addListener(event: 'timeout', listener: () => void): this; + addListener(event: string | symbol, listener: (...args: any[]) => void): this; + emit(event: 'checkContinue', request: Http2ServerRequest, response: Http2ServerResponse): boolean; + emit(event: 'request', request: Http2ServerRequest, response: Http2ServerResponse): boolean; + emit(event: 'session', session: ServerHttp2Session): boolean; + emit(event: 'sessionError', err: Error): boolean; + emit(event: 'stream', stream: ServerHttp2Stream, headers: IncomingHttpHeaders, flags: number): boolean; + emit(event: 'timeout'): boolean; + emit(event: string | symbol, ...args: any[]): boolean; + on(event: 'checkContinue', listener: (request: Http2ServerRequest, response: Http2ServerResponse) => void): this; + on(event: 'request', listener: (request: Http2ServerRequest, response: Http2ServerResponse) => void): this; + on(event: 'session', listener: (session: ServerHttp2Session) => void): this; + on(event: 'sessionError', listener: (err: Error) => void): this; + on(event: 'stream', listener: (stream: ServerHttp2Stream, headers: IncomingHttpHeaders, flags: number) => void): this; + on(event: 'timeout', listener: () => void): this; + on(event: string | symbol, listener: (...args: any[]) => void): this; + once(event: 'checkContinue', listener: (request: Http2ServerRequest, response: Http2ServerResponse) => void): this; + once(event: 'request', listener: (request: Http2ServerRequest, response: Http2ServerResponse) => void): this; + once(event: 'session', listener: (session: ServerHttp2Session) => void): this; + once(event: 'sessionError', listener: (err: Error) => void): this; + once(event: 'stream', listener: (stream: ServerHttp2Stream, headers: IncomingHttpHeaders, flags: number) => void): this; + once(event: 'timeout', listener: () => void): this; + once(event: string | symbol, listener: (...args: any[]) => void): this; + prependListener(event: 'checkContinue', listener: (request: Http2ServerRequest, response: Http2ServerResponse) => void): this; + prependListener(event: 'request', listener: (request: Http2ServerRequest, response: Http2ServerResponse) => void): this; + prependListener(event: 'session', listener: (session: ServerHttp2Session) => void): this; + prependListener(event: 'sessionError', listener: (err: Error) => void): this; + prependListener(event: 'stream', listener: (stream: ServerHttp2Stream, headers: IncomingHttpHeaders, flags: number) => void): this; + prependListener(event: 'timeout', listener: () => void): this; + prependListener(event: string | symbol, listener: (...args: any[]) => void): this; + prependOnceListener(event: 'checkContinue', listener: (request: Http2ServerRequest, response: Http2ServerResponse) => void): this; + prependOnceListener(event: 'request', listener: (request: Http2ServerRequest, response: Http2ServerResponse) => void): this; + prependOnceListener(event: 'session', listener: (session: ServerHttp2Session) => void): this; + prependOnceListener(event: 'sessionError', listener: (err: Error) => void): this; + prependOnceListener(event: 'stream', listener: (stream: ServerHttp2Stream, headers: IncomingHttpHeaders, flags: number) => void): this; + prependOnceListener(event: 'timeout', listener: () => void): this; + prependOnceListener(event: string | symbol, listener: (...args: any[]) => void): this; + } + export interface Http2SecureServer extends tls.Server, HTTP2ServerCommon { + addListener(event: 'checkContinue', listener: (request: Http2ServerRequest, response: Http2ServerResponse) => void): this; + addListener(event: 'request', listener: (request: Http2ServerRequest, response: Http2ServerResponse) => void): this; + addListener(event: 'session', listener: (session: ServerHttp2Session) => void): this; + addListener(event: 'sessionError', listener: (err: Error) => void): this; + addListener(event: 'stream', listener: (stream: ServerHttp2Stream, headers: IncomingHttpHeaders, flags: number) => void): this; + addListener(event: 'timeout', listener: () => void): this; + addListener(event: 'unknownProtocol', listener: (socket: tls.TLSSocket) => void): this; + addListener(event: string | symbol, listener: (...args: any[]) => void): this; + emit(event: 'checkContinue', request: Http2ServerRequest, response: Http2ServerResponse): boolean; + emit(event: 'request', request: Http2ServerRequest, response: Http2ServerResponse): boolean; + emit(event: 'session', session: ServerHttp2Session): boolean; + emit(event: 'sessionError', err: Error): boolean; + emit(event: 'stream', stream: ServerHttp2Stream, headers: IncomingHttpHeaders, flags: number): boolean; + emit(event: 'timeout'): boolean; + emit(event: 'unknownProtocol', socket: tls.TLSSocket): boolean; + emit(event: string | symbol, ...args: any[]): boolean; + on(event: 'checkContinue', listener: (request: Http2ServerRequest, response: Http2ServerResponse) => void): this; + on(event: 'request', listener: (request: Http2ServerRequest, response: Http2ServerResponse) => void): this; + on(event: 'session', listener: (session: ServerHttp2Session) => void): this; + on(event: 'sessionError', listener: (err: Error) => void): this; + on(event: 'stream', listener: (stream: ServerHttp2Stream, headers: IncomingHttpHeaders, flags: number) => void): this; + on(event: 'timeout', listener: () => void): this; + on(event: 'unknownProtocol', listener: (socket: tls.TLSSocket) => void): this; + on(event: string | symbol, listener: (...args: any[]) => void): this; + once(event: 'checkContinue', listener: (request: Http2ServerRequest, response: Http2ServerResponse) => void): this; + once(event: 'request', listener: (request: Http2ServerRequest, response: Http2ServerResponse) => void): this; + once(event: 'session', listener: (session: ServerHttp2Session) => void): this; + once(event: 'sessionError', listener: (err: Error) => void): this; + once(event: 'stream', listener: (stream: ServerHttp2Stream, headers: IncomingHttpHeaders, flags: number) => void): this; + once(event: 'timeout', listener: () => void): this; + once(event: 'unknownProtocol', listener: (socket: tls.TLSSocket) => void): this; + once(event: string | symbol, listener: (...args: any[]) => void): this; + prependListener(event: 'checkContinue', listener: (request: Http2ServerRequest, response: Http2ServerResponse) => void): this; + prependListener(event: 'request', listener: (request: Http2ServerRequest, response: Http2ServerResponse) => void): this; + prependListener(event: 'session', listener: (session: ServerHttp2Session) => void): this; + prependListener(event: 'sessionError', listener: (err: Error) => void): this; + prependListener(event: 'stream', listener: (stream: ServerHttp2Stream, headers: IncomingHttpHeaders, flags: number) => void): this; + prependListener(event: 'timeout', listener: () => void): this; + prependListener(event: 'unknownProtocol', listener: (socket: tls.TLSSocket) => void): this; + prependListener(event: string | symbol, listener: (...args: any[]) => void): this; + prependOnceListener(event: 'checkContinue', listener: (request: Http2ServerRequest, response: Http2ServerResponse) => void): this; + prependOnceListener(event: 'request', listener: (request: Http2ServerRequest, response: Http2ServerResponse) => void): this; + prependOnceListener(event: 'session', listener: (session: ServerHttp2Session) => void): this; + prependOnceListener(event: 'sessionError', listener: (err: Error) => void): this; + prependOnceListener(event: 'stream', listener: (stream: ServerHttp2Stream, headers: IncomingHttpHeaders, flags: number) => void): this; + prependOnceListener(event: 'timeout', listener: () => void): this; + prependOnceListener(event: 'unknownProtocol', listener: (socket: tls.TLSSocket) => void): this; + prependOnceListener(event: string | symbol, listener: (...args: any[]) => void): this; + } + /** + * A `Http2ServerRequest` object is created by {@link Server} or {@link SecureServer} and passed as the first argument to the `'request'` event. It may be used to access a request status, + * headers, and + * data. + * @since v8.4.0 + */ + export class Http2ServerRequest extends stream.Readable { + constructor(stream: ServerHttp2Stream, headers: IncomingHttpHeaders, options: stream.ReadableOptions, rawHeaders: ReadonlyArray); + /** + * The `request.aborted` property will be `true` if the request has + * been aborted. + * @since v10.1.0 + */ + readonly aborted: boolean; + /** + * The request authority pseudo header field. Because HTTP/2 allows requests + * to set either `:authority` or `host`, this value is derived from`req.headers[':authority']` if present. Otherwise, it is derived from`req.headers['host']`. + * @since v8.4.0 + */ + readonly authority: string; + /** + * See `request.socket`. + * @since v8.4.0 + * @deprecated Since v13.0.0 - Use `socket`. + */ + readonly connection: net.Socket | tls.TLSSocket; + /** + * The `request.complete` property will be `true` if the request has + * been completed, aborted, or destroyed. + * @since v12.10.0 + */ + readonly complete: boolean; + /** + * The request/response headers object. + * + * Key-value pairs of header names and values. Header names are lower-cased. + * + * ```js + * // Prints something like: + * // + * // { 'user-agent': 'curl/7.22.0', + * // host: '127.0.0.1:8000', + * // accept: '*' } + * console.log(request.headers); + * ``` + * + * See `HTTP/2 Headers Object`. + * + * In HTTP/2, the request path, host name, protocol, and method are represented as + * special headers prefixed with the `:` character (e.g. `':path'`). These special + * headers will be included in the `request.headers` object. Care must be taken not + * to inadvertently modify these special headers or errors may occur. For instance, + * removing all headers from the request will cause errors to occur: + * + * ```js + * removeAllHeaders(request.headers); + * assert(request.url); // Fails because the :path header has been removed + * ``` + * @since v8.4.0 + */ + readonly headers: IncomingHttpHeaders; + /** + * In case of server request, the HTTP version sent by the client. In the case of + * client response, the HTTP version of the connected-to server. Returns`'2.0'`. + * + * Also `message.httpVersionMajor` is the first integer and`message.httpVersionMinor` is the second. + * @since v8.4.0 + */ + readonly httpVersion: string; + readonly httpVersionMinor: number; + readonly httpVersionMajor: number; + /** + * The request method as a string. Read-only. Examples: `'GET'`, `'DELETE'`. + * @since v8.4.0 + */ + readonly method: string; + /** + * The raw request/response headers list exactly as they were received. + * + * The keys and values are in the same list. It is _not_ a + * list of tuples. So, the even-numbered offsets are key values, and the + * odd-numbered offsets are the associated values. + * + * Header names are not lowercased, and duplicates are not merged. + * + * ```js + * // Prints something like: + * // + * // [ 'user-agent', + * // 'this is invalid because there can be only one', + * // 'User-Agent', + * // 'curl/7.22.0', + * // 'Host', + * // '127.0.0.1:8000', + * // 'ACCEPT', + * // '*' ] + * console.log(request.rawHeaders); + * ``` + * @since v8.4.0 + */ + readonly rawHeaders: string[]; + /** + * The raw request/response trailer keys and values exactly as they were + * received. Only populated at the `'end'` event. + * @since v8.4.0 + */ + readonly rawTrailers: string[]; + /** + * The request scheme pseudo header field indicating the scheme + * portion of the target URL. + * @since v8.4.0 + */ + readonly scheme: string; + /** + * Returns a `Proxy` object that acts as a `net.Socket` (or `tls.TLSSocket`) but + * applies getters, setters, and methods based on HTTP/2 logic. + * + * `destroyed`, `readable`, and `writable` properties will be retrieved from and + * set on `request.stream`. + * + * `destroy`, `emit`, `end`, `on` and `once` methods will be called on`request.stream`. + * + * `setTimeout` method will be called on `request.stream.session`. + * + * `pause`, `read`, `resume`, and `write` will throw an error with code`ERR_HTTP2_NO_SOCKET_MANIPULATION`. See `Http2Session and Sockets` for + * more information. + * + * All other interactions will be routed directly to the socket. With TLS support, + * use `request.socket.getPeerCertificate()` to obtain the client's + * authentication details. + * @since v8.4.0 + */ + readonly socket: net.Socket | tls.TLSSocket; + /** + * The `Http2Stream` object backing the request. + * @since v8.4.0 + */ + readonly stream: ServerHttp2Stream; + /** + * The request/response trailers object. Only populated at the `'end'` event. + * @since v8.4.0 + */ + readonly trailers: IncomingHttpHeaders; + /** + * Request URL string. This contains only the URL that is present in the actual + * HTTP request. If the request is: + * + * ```http + * GET /status?name=ryan HTTP/1.1 + * Accept: text/plain + * ``` + * + * Then `request.url` will be: + * + * ```js + * '/status?name=ryan' + * ``` + * + * To parse the url into its parts, `new URL()` can be used: + * + * ```console + * $ node + * > new URL('/status?name=ryan', 'http://example.com') + * URL { + * href: 'http://example.com/status?name=ryan', + * origin: 'http://example.com', + * protocol: 'http:', + * username: '', + * password: '', + * host: 'example.com', + * hostname: 'example.com', + * port: '', + * pathname: '/status', + * search: '?name=ryan', + * searchParams: URLSearchParams { 'name' => 'ryan' }, + * hash: '' + * } + * ``` + * @since v8.4.0 + */ + url: string; + /** + * Sets the `Http2Stream`'s timeout value to `msecs`. If a callback is + * provided, then it is added as a listener on the `'timeout'` event on + * the response object. + * + * If no `'timeout'` listener is added to the request, the response, or + * the server, then `Http2Stream` s are destroyed when they time out. If a + * handler is assigned to the request, the response, or the server's `'timeout'`events, timed out sockets must be handled explicitly. + * @since v8.4.0 + */ + setTimeout(msecs: number, callback?: () => void): void; + read(size?: number): Buffer | string | null; + addListener(event: 'aborted', listener: (hadError: boolean, code: number) => void): this; + addListener(event: 'close', listener: () => void): this; + addListener(event: 'data', listener: (chunk: Buffer | string) => void): this; + addListener(event: 'end', listener: () => void): this; + addListener(event: 'readable', listener: () => void): this; + addListener(event: 'error', listener: (err: Error) => void): this; + addListener(event: string | symbol, listener: (...args: any[]) => void): this; + emit(event: 'aborted', hadError: boolean, code: number): boolean; + emit(event: 'close'): boolean; + emit(event: 'data', chunk: Buffer | string): boolean; + emit(event: 'end'): boolean; + emit(event: 'readable'): boolean; + emit(event: 'error', err: Error): boolean; + emit(event: string | symbol, ...args: any[]): boolean; + on(event: 'aborted', listener: (hadError: boolean, code: number) => void): this; + on(event: 'close', listener: () => void): this; + on(event: 'data', listener: (chunk: Buffer | string) => void): this; + on(event: 'end', listener: () => void): this; + on(event: 'readable', listener: () => void): this; + on(event: 'error', listener: (err: Error) => void): this; + on(event: string | symbol, listener: (...args: any[]) => void): this; + once(event: 'aborted', listener: (hadError: boolean, code: number) => void): this; + once(event: 'close', listener: () => void): this; + once(event: 'data', listener: (chunk: Buffer | string) => void): this; + once(event: 'end', listener: () => void): this; + once(event: 'readable', listener: () => void): this; + once(event: 'error', listener: (err: Error) => void): this; + once(event: string | symbol, listener: (...args: any[]) => void): this; + prependListener(event: 'aborted', listener: (hadError: boolean, code: number) => void): this; + prependListener(event: 'close', listener: () => void): this; + prependListener(event: 'data', listener: (chunk: Buffer | string) => void): this; + prependListener(event: 'end', listener: () => void): this; + prependListener(event: 'readable', listener: () => void): this; + prependListener(event: 'error', listener: (err: Error) => void): this; + prependListener(event: string | symbol, listener: (...args: any[]) => void): this; + prependOnceListener(event: 'aborted', listener: (hadError: boolean, code: number) => void): this; + prependOnceListener(event: 'close', listener: () => void): this; + prependOnceListener(event: 'data', listener: (chunk: Buffer | string) => void): this; + prependOnceListener(event: 'end', listener: () => void): this; + prependOnceListener(event: 'readable', listener: () => void): this; + prependOnceListener(event: 'error', listener: (err: Error) => void): this; + prependOnceListener(event: string | symbol, listener: (...args: any[]) => void): this; + } + /** + * This object is created internally by an HTTP server, not by the user. It is + * passed as the second parameter to the `'request'` event. + * @since v8.4.0 + */ + export class Http2ServerResponse extends stream.Writable { + constructor(stream: ServerHttp2Stream); + /** + * See `response.socket`. + * @since v8.4.0 + * @deprecated Since v13.0.0 - Use `socket`. + */ + readonly connection: net.Socket | tls.TLSSocket; + /** + * Boolean value that indicates whether the response has completed. Starts + * as `false`. After `response.end()` executes, the value will be `true`. + * @since v8.4.0 + * @deprecated Since v13.4.0,v12.16.0 - Use `writableEnded`. + */ + readonly finished: boolean; + /** + * True if headers were sent, false otherwise (read-only). + * @since v8.4.0 + */ + readonly headersSent: boolean; + /** + * A reference to the original HTTP2 request object. + * @since v15.7.0 + */ + readonly req: Http2ServerRequest; + /** + * Returns a `Proxy` object that acts as a `net.Socket` (or `tls.TLSSocket`) but + * applies getters, setters, and methods based on HTTP/2 logic. + * + * `destroyed`, `readable`, and `writable` properties will be retrieved from and + * set on `response.stream`. + * + * `destroy`, `emit`, `end`, `on` and `once` methods will be called on`response.stream`. + * + * `setTimeout` method will be called on `response.stream.session`. + * + * `pause`, `read`, `resume`, and `write` will throw an error with code`ERR_HTTP2_NO_SOCKET_MANIPULATION`. See `Http2Session and Sockets` for + * more information. + * + * All other interactions will be routed directly to the socket. + * + * ```js + * const http2 = require('http2'); + * const server = http2.createServer((req, res) => { + * const ip = req.socket.remoteAddress; + * const port = req.socket.remotePort; + * res.end(`Your IP address is ${ip} and your source port is ${port}.`); + * }).listen(3000); + * ``` + * @since v8.4.0 + */ + readonly socket: net.Socket | tls.TLSSocket; + /** + * The `Http2Stream` object backing the response. + * @since v8.4.0 + */ + readonly stream: ServerHttp2Stream; + /** + * When true, the Date header will be automatically generated and sent in + * the response if it is not already present in the headers. Defaults to true. + * + * This should only be disabled for testing; HTTP requires the Date header + * in responses. + * @since v8.4.0 + */ + sendDate: boolean; + /** + * When using implicit headers (not calling `response.writeHead()` explicitly), + * this property controls the status code that will be sent to the client when + * the headers get flushed. + * + * ```js + * response.statusCode = 404; + * ``` + * + * After response header was sent to the client, this property indicates the + * status code which was sent out. + * @since v8.4.0 + */ + statusCode: number; + /** + * Status message is not supported by HTTP/2 (RFC 7540 8.1.2.4). It returns + * an empty string. + * @since v8.4.0 + */ + statusMessage: ''; + /** + * This method adds HTTP trailing headers (a header but at the end of the + * message) to the response. + * + * Attempting to set a header field name or value that contains invalid characters + * will result in a `TypeError` being thrown. + * @since v8.4.0 + */ + addTrailers(trailers: OutgoingHttpHeaders): void; + /** + * This method signals to the server that all of the response headers and body + * have been sent; that server should consider this message complete. + * The method, `response.end()`, MUST be called on each response. + * + * If `data` is specified, it is equivalent to calling `response.write(data, encoding)` followed by `response.end(callback)`. + * + * If `callback` is specified, it will be called when the response stream + * is finished. + * @since v8.4.0 + */ + end(callback?: () => void): this; + end(data: string | Uint8Array, callback?: () => void): this; + end(data: string | Uint8Array, encoding: BufferEncoding, callback?: () => void): this; + /** + * Reads out a header that has already been queued but not sent to the client. + * The name is case-insensitive. + * + * ```js + * const contentType = response.getHeader('content-type'); + * ``` + * @since v8.4.0 + */ + getHeader(name: string): string; + /** + * Returns an array containing the unique names of the current outgoing headers. + * All header names are lowercase. + * + * ```js + * response.setHeader('Foo', 'bar'); + * response.setHeader('Set-Cookie', ['foo=bar', 'bar=baz']); + * + * const headerNames = response.getHeaderNames(); + * // headerNames === ['foo', 'set-cookie'] + * ``` + * @since v8.4.0 + */ + getHeaderNames(): string[]; + /** + * Returns a shallow copy of the current outgoing headers. Since a shallow copy + * is used, array values may be mutated without additional calls to various + * header-related http module methods. The keys of the returned object are the + * header names and the values are the respective header values. All header names + * are lowercase. + * + * The object returned by the `response.getHeaders()` method _does not_prototypically inherit from the JavaScript `Object`. This means that typical`Object` methods such as `obj.toString()`, + * `obj.hasOwnProperty()`, and others + * are not defined and _will not work_. + * + * ```js + * response.setHeader('Foo', 'bar'); + * response.setHeader('Set-Cookie', ['foo=bar', 'bar=baz']); + * + * const headers = response.getHeaders(); + * // headers === { foo: 'bar', 'set-cookie': ['foo=bar', 'bar=baz'] } + * ``` + * @since v8.4.0 + */ + getHeaders(): OutgoingHttpHeaders; + /** + * Returns `true` if the header identified by `name` is currently set in the + * outgoing headers. The header name matching is case-insensitive. + * + * ```js + * const hasContentType = response.hasHeader('content-type'); + * ``` + * @since v8.4.0 + */ + hasHeader(name: string): boolean; + /** + * Removes a header that has been queued for implicit sending. + * + * ```js + * response.removeHeader('Content-Encoding'); + * ``` + * @since v8.4.0 + */ + removeHeader(name: string): void; + /** + * Sets a single header value for implicit headers. If this header already exists + * in the to-be-sent headers, its value will be replaced. Use an array of strings + * here to send multiple headers with the same name. + * + * ```js + * response.setHeader('Content-Type', 'text/html; charset=utf-8'); + * ``` + * + * or + * + * ```js + * response.setHeader('Set-Cookie', ['type=ninja', 'language=javascript']); + * ``` + * + * Attempting to set a header field name or value that contains invalid characters + * will result in a `TypeError` being thrown. + * + * When headers have been set with `response.setHeader()`, they will be merged + * with any headers passed to `response.writeHead()`, with the headers passed + * to `response.writeHead()` given precedence. + * + * ```js + * // Returns content-type = text/plain + * const server = http2.createServer((req, res) => { + * res.setHeader('Content-Type', 'text/html; charset=utf-8'); + * res.setHeader('X-Foo', 'bar'); + * res.writeHead(200, { 'Content-Type': 'text/plain; charset=utf-8' }); + * res.end('ok'); + * }); + * ``` + * @since v8.4.0 + */ + setHeader(name: string, value: number | string | ReadonlyArray): void; + /** + * Sets the `Http2Stream`'s timeout value to `msecs`. If a callback is + * provided, then it is added as a listener on the `'timeout'` event on + * the response object. + * + * If no `'timeout'` listener is added to the request, the response, or + * the server, then `Http2Stream` s are destroyed when they time out. If a + * handler is assigned to the request, the response, or the server's `'timeout'`events, timed out sockets must be handled explicitly. + * @since v8.4.0 + */ + setTimeout(msecs: number, callback?: () => void): void; + /** + * If this method is called and `response.writeHead()` has not been called, + * it will switch to implicit header mode and flush the implicit headers. + * + * This sends a chunk of the response body. This method may + * be called multiple times to provide successive parts of the body. + * + * In the `http` module, the response body is omitted when the + * request is a HEAD request. Similarly, the `204` and `304` responses_must not_ include a message body. + * + * `chunk` can be a string or a buffer. If `chunk` is a string, + * the second parameter specifies how to encode it into a byte stream. + * By default the `encoding` is `'utf8'`. `callback` will be called when this chunk + * of data is flushed. + * + * This is the raw HTTP body and has nothing to do with higher-level multi-part + * body encodings that may be used. + * + * The first time `response.write()` is called, it will send the buffered + * header information and the first chunk of the body to the client. The second + * time `response.write()` is called, Node.js assumes data will be streamed, + * and sends the new data separately. That is, the response is buffered up to the + * first chunk of the body. + * + * Returns `true` if the entire data was flushed successfully to the kernel + * buffer. Returns `false` if all or part of the data was queued in user memory.`'drain'` will be emitted when the buffer is free again. + * @since v8.4.0 + */ + write(chunk: string | Uint8Array, callback?: (err: Error) => void): boolean; + write(chunk: string | Uint8Array, encoding: BufferEncoding, callback?: (err: Error) => void): boolean; + /** + * Sends a status `100 Continue` to the client, indicating that the request body + * should be sent. See the `'checkContinue'` event on `Http2Server` and`Http2SecureServer`. + * @since v8.4.0 + */ + writeContinue(): void; + /** + * Sends a response header to the request. The status code is a 3-digit HTTP + * status code, like `404`. The last argument, `headers`, are the response headers. + * + * Returns a reference to the `Http2ServerResponse`, so that calls can be chained. + * + * For compatibility with `HTTP/1`, a human-readable `statusMessage` may be + * passed as the second argument. However, because the `statusMessage` has no + * meaning within HTTP/2, the argument will have no effect and a process warning + * will be emitted. + * + * ```js + * const body = 'hello world'; + * response.writeHead(200, { + * 'Content-Length': Buffer.byteLength(body), + * 'Content-Type': 'text/plain; charset=utf-8', + * }); + * ``` + * + * `Content-Length` is given in bytes not characters. The`Buffer.byteLength()` API may be used to determine the number of bytes in a + * given encoding. On outbound messages, Node.js does not check if Content-Length + * and the length of the body being transmitted are equal or not. However, when + * receiving messages, Node.js will automatically reject messages when the`Content-Length` does not match the actual payload size. + * + * This method may be called at most one time on a message before `response.end()` is called. + * + * If `response.write()` or `response.end()` are called before calling + * this, the implicit/mutable headers will be calculated and call this function. + * + * When headers have been set with `response.setHeader()`, they will be merged + * with any headers passed to `response.writeHead()`, with the headers passed + * to `response.writeHead()` given precedence. + * + * ```js + * // Returns content-type = text/plain + * const server = http2.createServer((req, res) => { + * res.setHeader('Content-Type', 'text/html; charset=utf-8'); + * res.setHeader('X-Foo', 'bar'); + * res.writeHead(200, { 'Content-Type': 'text/plain; charset=utf-8' }); + * res.end('ok'); + * }); + * ``` + * + * Attempting to set a header field name or value that contains invalid characters + * will result in a `TypeError` being thrown. + * @since v8.4.0 + */ + writeHead(statusCode: number, headers?: OutgoingHttpHeaders): this; + writeHead(statusCode: number, statusMessage: string, headers?: OutgoingHttpHeaders): this; + /** + * Call `http2stream.pushStream()` with the given headers, and wrap the + * given `Http2Stream` on a newly created `Http2ServerResponse` as the callback + * parameter if successful. When `Http2ServerRequest` is closed, the callback is + * called with an error `ERR_HTTP2_INVALID_STREAM`. + * @since v8.4.0 + * @param headers An object describing the headers + * @param callback Called once `http2stream.pushStream()` is finished, or either when the attempt to create the pushed `Http2Stream` has failed or has been rejected, or the state of + * `Http2ServerRequest` is closed prior to calling the `http2stream.pushStream()` method + */ + createPushResponse(headers: OutgoingHttpHeaders, callback: (err: Error | null, res: Http2ServerResponse) => void): void; + addListener(event: 'close', listener: () => void): this; + addListener(event: 'drain', listener: () => void): this; + addListener(event: 'error', listener: (error: Error) => void): this; + addListener(event: 'finish', listener: () => void): this; + addListener(event: 'pipe', listener: (src: stream.Readable) => void): this; + addListener(event: 'unpipe', listener: (src: stream.Readable) => void): this; + addListener(event: string | symbol, listener: (...args: any[]) => void): this; + emit(event: 'close'): boolean; + emit(event: 'drain'): boolean; + emit(event: 'error', error: Error): boolean; + emit(event: 'finish'): boolean; + emit(event: 'pipe', src: stream.Readable): boolean; + emit(event: 'unpipe', src: stream.Readable): boolean; + emit(event: string | symbol, ...args: any[]): boolean; + on(event: 'close', listener: () => void): this; + on(event: 'drain', listener: () => void): this; + on(event: 'error', listener: (error: Error) => void): this; + on(event: 'finish', listener: () => void): this; + on(event: 'pipe', listener: (src: stream.Readable) => void): this; + on(event: 'unpipe', listener: (src: stream.Readable) => void): this; + on(event: string | symbol, listener: (...args: any[]) => void): this; + once(event: 'close', listener: () => void): this; + once(event: 'drain', listener: () => void): this; + once(event: 'error', listener: (error: Error) => void): this; + once(event: 'finish', listener: () => void): this; + once(event: 'pipe', listener: (src: stream.Readable) => void): this; + once(event: 'unpipe', listener: (src: stream.Readable) => void): this; + once(event: string | symbol, listener: (...args: any[]) => void): this; + prependListener(event: 'close', listener: () => void): this; + prependListener(event: 'drain', listener: () => void): this; + prependListener(event: 'error', listener: (error: Error) => void): this; + prependListener(event: 'finish', listener: () => void): this; + prependListener(event: 'pipe', listener: (src: stream.Readable) => void): this; + prependListener(event: 'unpipe', listener: (src: stream.Readable) => void): this; + prependListener(event: string | symbol, listener: (...args: any[]) => void): this; + prependOnceListener(event: 'close', listener: () => void): this; + prependOnceListener(event: 'drain', listener: () => void): this; + prependOnceListener(event: 'error', listener: (error: Error) => void): this; + prependOnceListener(event: 'finish', listener: () => void): this; + prependOnceListener(event: 'pipe', listener: (src: stream.Readable) => void): this; + prependOnceListener(event: 'unpipe', listener: (src: stream.Readable) => void): this; + prependOnceListener(event: string | symbol, listener: (...args: any[]) => void): this; + } + export namespace constants { + const NGHTTP2_SESSION_SERVER: number; + const NGHTTP2_SESSION_CLIENT: number; + const NGHTTP2_STREAM_STATE_IDLE: number; + const NGHTTP2_STREAM_STATE_OPEN: number; + const NGHTTP2_STREAM_STATE_RESERVED_LOCAL: number; + const NGHTTP2_STREAM_STATE_RESERVED_REMOTE: number; + const NGHTTP2_STREAM_STATE_HALF_CLOSED_LOCAL: number; + const NGHTTP2_STREAM_STATE_HALF_CLOSED_REMOTE: number; + const NGHTTP2_STREAM_STATE_CLOSED: number; + const NGHTTP2_NO_ERROR: number; + const NGHTTP2_PROTOCOL_ERROR: number; + const NGHTTP2_INTERNAL_ERROR: number; + const NGHTTP2_FLOW_CONTROL_ERROR: number; + const NGHTTP2_SETTINGS_TIMEOUT: number; + const NGHTTP2_STREAM_CLOSED: number; + const NGHTTP2_FRAME_SIZE_ERROR: number; + const NGHTTP2_REFUSED_STREAM: number; + const NGHTTP2_CANCEL: number; + const NGHTTP2_COMPRESSION_ERROR: number; + const NGHTTP2_CONNECT_ERROR: number; + const NGHTTP2_ENHANCE_YOUR_CALM: number; + const NGHTTP2_INADEQUATE_SECURITY: number; + const NGHTTP2_HTTP_1_1_REQUIRED: number; + const NGHTTP2_ERR_FRAME_SIZE_ERROR: number; + const NGHTTP2_FLAG_NONE: number; + const NGHTTP2_FLAG_END_STREAM: number; + const NGHTTP2_FLAG_END_HEADERS: number; + const NGHTTP2_FLAG_ACK: number; + const NGHTTP2_FLAG_PADDED: number; + const NGHTTP2_FLAG_PRIORITY: number; + const DEFAULT_SETTINGS_HEADER_TABLE_SIZE: number; + const DEFAULT_SETTINGS_ENABLE_PUSH: number; + const DEFAULT_SETTINGS_INITIAL_WINDOW_SIZE: number; + const DEFAULT_SETTINGS_MAX_FRAME_SIZE: number; + const MAX_MAX_FRAME_SIZE: number; + const MIN_MAX_FRAME_SIZE: number; + const MAX_INITIAL_WINDOW_SIZE: number; + const NGHTTP2_DEFAULT_WEIGHT: number; + const NGHTTP2_SETTINGS_HEADER_TABLE_SIZE: number; + const NGHTTP2_SETTINGS_ENABLE_PUSH: number; + const NGHTTP2_SETTINGS_MAX_CONCURRENT_STREAMS: number; + const NGHTTP2_SETTINGS_INITIAL_WINDOW_SIZE: number; + const NGHTTP2_SETTINGS_MAX_FRAME_SIZE: number; + const NGHTTP2_SETTINGS_MAX_HEADER_LIST_SIZE: number; + const PADDING_STRATEGY_NONE: number; + const PADDING_STRATEGY_MAX: number; + const PADDING_STRATEGY_CALLBACK: number; + const HTTP2_HEADER_STATUS: string; + const HTTP2_HEADER_METHOD: string; + const HTTP2_HEADER_AUTHORITY: string; + const HTTP2_HEADER_SCHEME: string; + const HTTP2_HEADER_PATH: string; + const HTTP2_HEADER_ACCEPT_CHARSET: string; + const HTTP2_HEADER_ACCEPT_ENCODING: string; + const HTTP2_HEADER_ACCEPT_LANGUAGE: string; + const HTTP2_HEADER_ACCEPT_RANGES: string; + const HTTP2_HEADER_ACCEPT: string; + const HTTP2_HEADER_ACCESS_CONTROL_ALLOW_ORIGIN: string; + const HTTP2_HEADER_AGE: string; + const HTTP2_HEADER_ALLOW: string; + const HTTP2_HEADER_AUTHORIZATION: string; + const HTTP2_HEADER_CACHE_CONTROL: string; + const HTTP2_HEADER_CONNECTION: string; + const HTTP2_HEADER_CONTENT_DISPOSITION: string; + const HTTP2_HEADER_CONTENT_ENCODING: string; + const HTTP2_HEADER_CONTENT_LANGUAGE: string; + const HTTP2_HEADER_CONTENT_LENGTH: string; + const HTTP2_HEADER_CONTENT_LOCATION: string; + const HTTP2_HEADER_CONTENT_MD5: string; + const HTTP2_HEADER_CONTENT_RANGE: string; + const HTTP2_HEADER_CONTENT_TYPE: string; + const HTTP2_HEADER_COOKIE: string; + const HTTP2_HEADER_DATE: string; + const HTTP2_HEADER_ETAG: string; + const HTTP2_HEADER_EXPECT: string; + const HTTP2_HEADER_EXPIRES: string; + const HTTP2_HEADER_FROM: string; + const HTTP2_HEADER_HOST: string; + const HTTP2_HEADER_IF_MATCH: string; + const HTTP2_HEADER_IF_MODIFIED_SINCE: string; + const HTTP2_HEADER_IF_NONE_MATCH: string; + const HTTP2_HEADER_IF_RANGE: string; + const HTTP2_HEADER_IF_UNMODIFIED_SINCE: string; + const HTTP2_HEADER_LAST_MODIFIED: string; + const HTTP2_HEADER_LINK: string; + const HTTP2_HEADER_LOCATION: string; + const HTTP2_HEADER_MAX_FORWARDS: string; + const HTTP2_HEADER_PREFER: string; + const HTTP2_HEADER_PROXY_AUTHENTICATE: string; + const HTTP2_HEADER_PROXY_AUTHORIZATION: string; + const HTTP2_HEADER_RANGE: string; + const HTTP2_HEADER_REFERER: string; + const HTTP2_HEADER_REFRESH: string; + const HTTP2_HEADER_RETRY_AFTER: string; + const HTTP2_HEADER_SERVER: string; + const HTTP2_HEADER_SET_COOKIE: string; + const HTTP2_HEADER_STRICT_TRANSPORT_SECURITY: string; + const HTTP2_HEADER_TRANSFER_ENCODING: string; + const HTTP2_HEADER_TE: string; + const HTTP2_HEADER_UPGRADE: string; + const HTTP2_HEADER_USER_AGENT: string; + const HTTP2_HEADER_VARY: string; + const HTTP2_HEADER_VIA: string; + const HTTP2_HEADER_WWW_AUTHENTICATE: string; + const HTTP2_HEADER_HTTP2_SETTINGS: string; + const HTTP2_HEADER_KEEP_ALIVE: string; + const HTTP2_HEADER_PROXY_CONNECTION: string; + const HTTP2_METHOD_ACL: string; + const HTTP2_METHOD_BASELINE_CONTROL: string; + const HTTP2_METHOD_BIND: string; + const HTTP2_METHOD_CHECKIN: string; + const HTTP2_METHOD_CHECKOUT: string; + const HTTP2_METHOD_CONNECT: string; + const HTTP2_METHOD_COPY: string; + const HTTP2_METHOD_DELETE: string; + const HTTP2_METHOD_GET: string; + const HTTP2_METHOD_HEAD: string; + const HTTP2_METHOD_LABEL: string; + const HTTP2_METHOD_LINK: string; + const HTTP2_METHOD_LOCK: string; + const HTTP2_METHOD_MERGE: string; + const HTTP2_METHOD_MKACTIVITY: string; + const HTTP2_METHOD_MKCALENDAR: string; + const HTTP2_METHOD_MKCOL: string; + const HTTP2_METHOD_MKREDIRECTREF: string; + const HTTP2_METHOD_MKWORKSPACE: string; + const HTTP2_METHOD_MOVE: string; + const HTTP2_METHOD_OPTIONS: string; + const HTTP2_METHOD_ORDERPATCH: string; + const HTTP2_METHOD_PATCH: string; + const HTTP2_METHOD_POST: string; + const HTTP2_METHOD_PRI: string; + const HTTP2_METHOD_PROPFIND: string; + const HTTP2_METHOD_PROPPATCH: string; + const HTTP2_METHOD_PUT: string; + const HTTP2_METHOD_REBIND: string; + const HTTP2_METHOD_REPORT: string; + const HTTP2_METHOD_SEARCH: string; + const HTTP2_METHOD_TRACE: string; + const HTTP2_METHOD_UNBIND: string; + const HTTP2_METHOD_UNCHECKOUT: string; + const HTTP2_METHOD_UNLINK: string; + const HTTP2_METHOD_UNLOCK: string; + const HTTP2_METHOD_UPDATE: string; + const HTTP2_METHOD_UPDATEREDIRECTREF: string; + const HTTP2_METHOD_VERSION_CONTROL: string; + const HTTP_STATUS_CONTINUE: number; + const HTTP_STATUS_SWITCHING_PROTOCOLS: number; + const HTTP_STATUS_PROCESSING: number; + const HTTP_STATUS_OK: number; + const HTTP_STATUS_CREATED: number; + const HTTP_STATUS_ACCEPTED: number; + const HTTP_STATUS_NON_AUTHORITATIVE_INFORMATION: number; + const HTTP_STATUS_NO_CONTENT: number; + const HTTP_STATUS_RESET_CONTENT: number; + const HTTP_STATUS_PARTIAL_CONTENT: number; + const HTTP_STATUS_MULTI_STATUS: number; + const HTTP_STATUS_ALREADY_REPORTED: number; + const HTTP_STATUS_IM_USED: number; + const HTTP_STATUS_MULTIPLE_CHOICES: number; + const HTTP_STATUS_MOVED_PERMANENTLY: number; + const HTTP_STATUS_FOUND: number; + const HTTP_STATUS_SEE_OTHER: number; + const HTTP_STATUS_NOT_MODIFIED: number; + const HTTP_STATUS_USE_PROXY: number; + const HTTP_STATUS_TEMPORARY_REDIRECT: number; + const HTTP_STATUS_PERMANENT_REDIRECT: number; + const HTTP_STATUS_BAD_REQUEST: number; + const HTTP_STATUS_UNAUTHORIZED: number; + const HTTP_STATUS_PAYMENT_REQUIRED: number; + const HTTP_STATUS_FORBIDDEN: number; + const HTTP_STATUS_NOT_FOUND: number; + const HTTP_STATUS_METHOD_NOT_ALLOWED: number; + const HTTP_STATUS_NOT_ACCEPTABLE: number; + const HTTP_STATUS_PROXY_AUTHENTICATION_REQUIRED: number; + const HTTP_STATUS_REQUEST_TIMEOUT: number; + const HTTP_STATUS_CONFLICT: number; + const HTTP_STATUS_GONE: number; + const HTTP_STATUS_LENGTH_REQUIRED: number; + const HTTP_STATUS_PRECONDITION_FAILED: number; + const HTTP_STATUS_PAYLOAD_TOO_LARGE: number; + const HTTP_STATUS_URI_TOO_LONG: number; + const HTTP_STATUS_UNSUPPORTED_MEDIA_TYPE: number; + const HTTP_STATUS_RANGE_NOT_SATISFIABLE: number; + const HTTP_STATUS_EXPECTATION_FAILED: number; + const HTTP_STATUS_TEAPOT: number; + const HTTP_STATUS_MISDIRECTED_REQUEST: number; + const HTTP_STATUS_UNPROCESSABLE_ENTITY: number; + const HTTP_STATUS_LOCKED: number; + const HTTP_STATUS_FAILED_DEPENDENCY: number; + const HTTP_STATUS_UNORDERED_COLLECTION: number; + const HTTP_STATUS_UPGRADE_REQUIRED: number; + const HTTP_STATUS_PRECONDITION_REQUIRED: number; + const HTTP_STATUS_TOO_MANY_REQUESTS: number; + const HTTP_STATUS_REQUEST_HEADER_FIELDS_TOO_LARGE: number; + const HTTP_STATUS_UNAVAILABLE_FOR_LEGAL_REASONS: number; + const HTTP_STATUS_INTERNAL_SERVER_ERROR: number; + const HTTP_STATUS_NOT_IMPLEMENTED: number; + const HTTP_STATUS_BAD_GATEWAY: number; + const HTTP_STATUS_SERVICE_UNAVAILABLE: number; + const HTTP_STATUS_GATEWAY_TIMEOUT: number; + const HTTP_STATUS_HTTP_VERSION_NOT_SUPPORTED: number; + const HTTP_STATUS_VARIANT_ALSO_NEGOTIATES: number; + const HTTP_STATUS_INSUFFICIENT_STORAGE: number; + const HTTP_STATUS_LOOP_DETECTED: number; + const HTTP_STATUS_BANDWIDTH_LIMIT_EXCEEDED: number; + const HTTP_STATUS_NOT_EXTENDED: number; + const HTTP_STATUS_NETWORK_AUTHENTICATION_REQUIRED: number; + } + /** + * This symbol can be set as a property on the HTTP/2 headers object with + * an array value in order to provide a list of headers considered sensitive. + */ + export const sensitiveHeaders: symbol; + /** + * Returns an object containing the default settings for an `Http2Session`instance. This method returns a new object instance every time it is called + * so instances returned may be safely modified for use. + * @since v8.4.0 + */ + export function getDefaultSettings(): Settings; + /** + * Returns a `Buffer` instance containing serialized representation of the given + * HTTP/2 settings as specified in the [HTTP/2](https://tools.ietf.org/html/rfc7540) specification. This is intended + * for use with the `HTTP2-Settings` header field. + * + * ```js + * const http2 = require('http2'); + * + * const packed = http2.getPackedSettings({ enablePush: false }); + * + * console.log(packed.toString('base64')); + * // Prints: AAIAAAAA + * ``` + * @since v8.4.0 + */ + export function getPackedSettings(settings: Settings): Buffer; + /** + * Returns a `HTTP/2 Settings Object` containing the deserialized settings from + * the given `Buffer` as generated by `http2.getPackedSettings()`. + * @since v8.4.0 + * @param buf The packed settings. + */ + export function getUnpackedSettings(buf: Uint8Array): Settings; + /** + * Returns a `net.Server` instance that creates and manages `Http2Session`instances. + * + * Since there are no browsers known that support [unencrypted HTTP/2](https://http2.github.io/faq/#does-http2-require-encryption), the use of {@link createSecureServer} is necessary when + * communicating + * with browser clients. + * + * ```js + * const http2 = require('http2'); + * + * // Create an unencrypted HTTP/2 server. + * // Since there are no browsers known that support + * // unencrypted HTTP/2, the use of `http2.createSecureServer()` + * // is necessary when communicating with browser clients. + * const server = http2.createServer(); + * + * server.on('stream', (stream, headers) => { + * stream.respond({ + * 'content-type': 'text/html; charset=utf-8', + * ':status': 200 + * }); + * stream.end('

Hello World

'); + * }); + * + * server.listen(80); + * ``` + * @since v8.4.0 + * @param onRequestHandler See `Compatibility API` + */ + export function createServer(onRequestHandler?: (request: Http2ServerRequest, response: Http2ServerResponse) => void): Http2Server; + export function createServer(options: ServerOptions, onRequestHandler?: (request: Http2ServerRequest, response: Http2ServerResponse) => void): Http2Server; + /** + * Returns a `tls.Server` instance that creates and manages `Http2Session`instances. + * + * ```js + * const http2 = require('http2'); + * const fs = require('fs'); + * + * const options = { + * key: fs.readFileSync('server-key.pem'), + * cert: fs.readFileSync('server-cert.pem') + * }; + * + * // Create a secure HTTP/2 server + * const server = http2.createSecureServer(options); + * + * server.on('stream', (stream, headers) => { + * stream.respond({ + * 'content-type': 'text/html; charset=utf-8', + * ':status': 200 + * }); + * stream.end('

Hello World

'); + * }); + * + * server.listen(80); + * ``` + * @since v8.4.0 + * @param onRequestHandler See `Compatibility API` + */ + export function createSecureServer(onRequestHandler?: (request: Http2ServerRequest, response: Http2ServerResponse) => void): Http2SecureServer; + export function createSecureServer(options: SecureServerOptions, onRequestHandler?: (request: Http2ServerRequest, response: Http2ServerResponse) => void): Http2SecureServer; + /** + * Returns a `ClientHttp2Session` instance. + * + * ```js + * const http2 = require('http2'); + * const client = http2.connect('https://localhost:1234'); + * + * // Use the client + * + * client.close(); + * ``` + * @since v8.4.0 + * @param authority The remote HTTP/2 server to connect to. This must be in the form of a minimal, valid URL with the `http://` or `https://` prefix, host name, and IP port (if a non-default port + * is used). Userinfo (user ID and password), path, querystring, and fragment details in the URL will be ignored. + * @param listener Will be registered as a one-time listener of the {@link 'connect'} event. + */ + export function connect(authority: string | url.URL, listener: (session: ClientHttp2Session, socket: net.Socket | tls.TLSSocket) => void): ClientHttp2Session; + export function connect( + authority: string | url.URL, + options?: ClientSessionOptions | SecureClientSessionOptions, + listener?: (session: ClientHttp2Session, socket: net.Socket | tls.TLSSocket) => void + ): ClientHttp2Session; +} +declare module 'node:http2' { + export * from 'http2'; +} diff --git a/ts-ticket-office-service/node_modules/@types/node/https.d.ts b/ts-ticket-office-service/node_modules/@types/node/https.d.ts new file mode 100755 index 000000000..5b78a3f28 --- /dev/null +++ b/ts-ticket-office-service/node_modules/@types/node/https.d.ts @@ -0,0 +1,401 @@ +/** + * HTTPS is the HTTP protocol over TLS/SSL. In Node.js this is implemented as a + * separate module. + * @see [source](https://github.com/nodejs/node/blob/v18.0.0/lib/https.js) + */ +declare module 'https' { + import { Duplex } from 'node:stream'; + import * as tls from 'node:tls'; + import * as http from 'node:http'; + import { URL } from 'node:url'; + type ServerOptions = tls.SecureContextOptions & tls.TlsOptions & http.ServerOptions; + type RequestOptions = http.RequestOptions & + tls.SecureContextOptions & { + rejectUnauthorized?: boolean | undefined; // Defaults to true + servername?: string | undefined; // SNI TLS Extension + }; + interface AgentOptions extends http.AgentOptions, tls.ConnectionOptions { + rejectUnauthorized?: boolean | undefined; + maxCachedSessions?: number | undefined; + } + /** + * An `Agent` object for HTTPS similar to `http.Agent`. See {@link request} for more information. + * @since v0.4.5 + */ + class Agent extends http.Agent { + constructor(options?: AgentOptions); + options: AgentOptions; + } + interface Server extends http.Server {} + /** + * See `http.Server` for more information. + * @since v0.3.4 + */ + class Server extends tls.Server { + constructor(requestListener?: http.RequestListener); + constructor(options: ServerOptions, requestListener?: http.RequestListener); + /** + * Closes all connections connected to this server. + * @since v18.2.0 + */ + closeAllConnections(): void; + /** + * Closes all connections connected to this server which are not sending a request or waiting for a response. + * @since v18.2.0 + */ + closeIdleConnections(): void; + addListener(event: string, listener: (...args: any[]) => void): this; + addListener(event: 'keylog', listener: (line: Buffer, tlsSocket: tls.TLSSocket) => void): this; + addListener(event: 'newSession', listener: (sessionId: Buffer, sessionData: Buffer, callback: (err: Error, resp: Buffer) => void) => void): this; + addListener(event: 'OCSPRequest', listener: (certificate: Buffer, issuer: Buffer, callback: (err: Error | null, resp: Buffer) => void) => void): this; + addListener(event: 'resumeSession', listener: (sessionId: Buffer, callback: (err: Error, sessionData: Buffer) => void) => void): this; + addListener(event: 'secureConnection', listener: (tlsSocket: tls.TLSSocket) => void): this; + addListener(event: 'tlsClientError', listener: (err: Error, tlsSocket: tls.TLSSocket) => void): this; + addListener(event: 'close', listener: () => void): this; + addListener(event: 'connection', listener: (socket: Duplex) => void): this; + addListener(event: 'error', listener: (err: Error) => void): this; + addListener(event: 'listening', listener: () => void): this; + addListener(event: 'checkContinue', listener: http.RequestListener): this; + addListener(event: 'checkExpectation', listener: http.RequestListener): this; + addListener(event: 'clientError', listener: (err: Error, socket: Duplex) => void): this; + addListener(event: 'connect', listener: (req: http.IncomingMessage, socket: Duplex, head: Buffer) => void): this; + addListener(event: 'request', listener: http.RequestListener): this; + addListener(event: 'upgrade', listener: (req: http.IncomingMessage, socket: Duplex, head: Buffer) => void): this; + emit(event: string, ...args: any[]): boolean; + emit(event: 'keylog', line: Buffer, tlsSocket: tls.TLSSocket): boolean; + emit(event: 'newSession', sessionId: Buffer, sessionData: Buffer, callback: (err: Error, resp: Buffer) => void): boolean; + emit(event: 'OCSPRequest', certificate: Buffer, issuer: Buffer, callback: (err: Error | null, resp: Buffer) => void): boolean; + emit(event: 'resumeSession', sessionId: Buffer, callback: (err: Error, sessionData: Buffer) => void): boolean; + emit(event: 'secureConnection', tlsSocket: tls.TLSSocket): boolean; + emit(event: 'tlsClientError', err: Error, tlsSocket: tls.TLSSocket): boolean; + emit(event: 'close'): boolean; + emit(event: 'connection', socket: Duplex): boolean; + emit(event: 'error', err: Error): boolean; + emit(event: 'listening'): boolean; + emit(event: 'checkContinue', req: http.IncomingMessage, res: http.ServerResponse): boolean; + emit(event: 'checkExpectation', req: http.IncomingMessage, res: http.ServerResponse): boolean; + emit(event: 'clientError', err: Error, socket: Duplex): boolean; + emit(event: 'connect', req: http.IncomingMessage, socket: Duplex, head: Buffer): boolean; + emit(event: 'request', req: http.IncomingMessage, res: http.ServerResponse): boolean; + emit(event: 'upgrade', req: http.IncomingMessage, socket: Duplex, head: Buffer): boolean; + on(event: string, listener: (...args: any[]) => void): this; + on(event: 'keylog', listener: (line: Buffer, tlsSocket: tls.TLSSocket) => void): this; + on(event: 'newSession', listener: (sessionId: Buffer, sessionData: Buffer, callback: (err: Error, resp: Buffer) => void) => void): this; + on(event: 'OCSPRequest', listener: (certificate: Buffer, issuer: Buffer, callback: (err: Error | null, resp: Buffer) => void) => void): this; + on(event: 'resumeSession', listener: (sessionId: Buffer, callback: (err: Error, sessionData: Buffer) => void) => void): this; + on(event: 'secureConnection', listener: (tlsSocket: tls.TLSSocket) => void): this; + on(event: 'tlsClientError', listener: (err: Error, tlsSocket: tls.TLSSocket) => void): this; + on(event: 'close', listener: () => void): this; + on(event: 'connection', listener: (socket: Duplex) => void): this; + on(event: 'error', listener: (err: Error) => void): this; + on(event: 'listening', listener: () => void): this; + on(event: 'checkContinue', listener: http.RequestListener): this; + on(event: 'checkExpectation', listener: http.RequestListener): this; + on(event: 'clientError', listener: (err: Error, socket: Duplex) => void): this; + on(event: 'connect', listener: (req: http.IncomingMessage, socket: Duplex, head: Buffer) => void): this; + on(event: 'request', listener: http.RequestListener): this; + on(event: 'upgrade', listener: (req: http.IncomingMessage, socket: Duplex, head: Buffer) => void): this; + once(event: string, listener: (...args: any[]) => void): this; + once(event: 'keylog', listener: (line: Buffer, tlsSocket: tls.TLSSocket) => void): this; + once(event: 'newSession', listener: (sessionId: Buffer, sessionData: Buffer, callback: (err: Error, resp: Buffer) => void) => void): this; + once(event: 'OCSPRequest', listener: (certificate: Buffer, issuer: Buffer, callback: (err: Error | null, resp: Buffer) => void) => void): this; + once(event: 'resumeSession', listener: (sessionId: Buffer, callback: (err: Error, sessionData: Buffer) => void) => void): this; + once(event: 'secureConnection', listener: (tlsSocket: tls.TLSSocket) => void): this; + once(event: 'tlsClientError', listener: (err: Error, tlsSocket: tls.TLSSocket) => void): this; + once(event: 'close', listener: () => void): this; + once(event: 'connection', listener: (socket: Duplex) => void): this; + once(event: 'error', listener: (err: Error) => void): this; + once(event: 'listening', listener: () => void): this; + once(event: 'checkContinue', listener: http.RequestListener): this; + once(event: 'checkExpectation', listener: http.RequestListener): this; + once(event: 'clientError', listener: (err: Error, socket: Duplex) => void): this; + once(event: 'connect', listener: (req: http.IncomingMessage, socket: Duplex, head: Buffer) => void): this; + once(event: 'request', listener: http.RequestListener): this; + once(event: 'upgrade', listener: (req: http.IncomingMessage, socket: Duplex, head: Buffer) => void): this; + prependListener(event: string, listener: (...args: any[]) => void): this; + prependListener(event: 'keylog', listener: (line: Buffer, tlsSocket: tls.TLSSocket) => void): this; + prependListener(event: 'newSession', listener: (sessionId: Buffer, sessionData: Buffer, callback: (err: Error, resp: Buffer) => void) => void): this; + prependListener(event: 'OCSPRequest', listener: (certificate: Buffer, issuer: Buffer, callback: (err: Error | null, resp: Buffer) => void) => void): this; + prependListener(event: 'resumeSession', listener: (sessionId: Buffer, callback: (err: Error, sessionData: Buffer) => void) => void): this; + prependListener(event: 'secureConnection', listener: (tlsSocket: tls.TLSSocket) => void): this; + prependListener(event: 'tlsClientError', listener: (err: Error, tlsSocket: tls.TLSSocket) => void): this; + prependListener(event: 'close', listener: () => void): this; + prependListener(event: 'connection', listener: (socket: Duplex) => void): this; + prependListener(event: 'error', listener: (err: Error) => void): this; + prependListener(event: 'listening', listener: () => void): this; + prependListener(event: 'checkContinue', listener: http.RequestListener): this; + prependListener(event: 'checkExpectation', listener: http.RequestListener): this; + prependListener(event: 'clientError', listener: (err: Error, socket: Duplex) => void): this; + prependListener(event: 'connect', listener: (req: http.IncomingMessage, socket: Duplex, head: Buffer) => void): this; + prependListener(event: 'request', listener: http.RequestListener): this; + prependListener(event: 'upgrade', listener: (req: http.IncomingMessage, socket: Duplex, head: Buffer) => void): this; + prependOnceListener(event: string, listener: (...args: any[]) => void): this; + prependOnceListener(event: 'keylog', listener: (line: Buffer, tlsSocket: tls.TLSSocket) => void): this; + prependOnceListener(event: 'newSession', listener: (sessionId: Buffer, sessionData: Buffer, callback: (err: Error, resp: Buffer) => void) => void): this; + prependOnceListener(event: 'OCSPRequest', listener: (certificate: Buffer, issuer: Buffer, callback: (err: Error | null, resp: Buffer) => void) => void): this; + prependOnceListener(event: 'resumeSession', listener: (sessionId: Buffer, callback: (err: Error, sessionData: Buffer) => void) => void): this; + prependOnceListener(event: 'secureConnection', listener: (tlsSocket: tls.TLSSocket) => void): this; + prependOnceListener(event: 'tlsClientError', listener: (err: Error, tlsSocket: tls.TLSSocket) => void): this; + prependOnceListener(event: 'close', listener: () => void): this; + prependOnceListener(event: 'connection', listener: (socket: Duplex) => void): this; + prependOnceListener(event: 'error', listener: (err: Error) => void): this; + prependOnceListener(event: 'listening', listener: () => void): this; + prependOnceListener(event: 'checkContinue', listener: http.RequestListener): this; + prependOnceListener(event: 'checkExpectation', listener: http.RequestListener): this; + prependOnceListener(event: 'clientError', listener: (err: Error, socket: Duplex) => void): this; + prependOnceListener(event: 'connect', listener: (req: http.IncomingMessage, socket: Duplex, head: Buffer) => void): this; + prependOnceListener(event: 'request', listener: http.RequestListener): this; + prependOnceListener(event: 'upgrade', listener: (req: http.IncomingMessage, socket: Duplex, head: Buffer) => void): this; + } + /** + * ```js + * // curl -k https://localhost:8000/ + * const https = require('https'); + * const fs = require('fs'); + * + * const options = { + * key: fs.readFileSync('test/fixtures/keys/agent2-key.pem'), + * cert: fs.readFileSync('test/fixtures/keys/agent2-cert.pem') + * }; + * + * https.createServer(options, (req, res) => { + * res.writeHead(200); + * res.end('hello world\n'); + * }).listen(8000); + * ``` + * + * Or + * + * ```js + * const https = require('https'); + * const fs = require('fs'); + * + * const options = { + * pfx: fs.readFileSync('test/fixtures/test_cert.pfx'), + * passphrase: 'sample' + * }; + * + * https.createServer(options, (req, res) => { + * res.writeHead(200); + * res.end('hello world\n'); + * }).listen(8000); + * ``` + * @since v0.3.4 + * @param options Accepts `options` from `createServer`, `createSecureContext` and `createServer`. + * @param requestListener A listener to be added to the `'request'` event. + */ + function createServer(requestListener?: http.RequestListener): Server; + function createServer(options: ServerOptions, requestListener?: http.RequestListener): Server; + /** + * Makes a request to a secure web server. + * + * The following additional `options` from `tls.connect()` are also accepted:`ca`, `cert`, `ciphers`, `clientCertEngine`, `crl`, `dhparam`, `ecdhCurve`,`honorCipherOrder`, `key`, `passphrase`, + * `pfx`, `rejectUnauthorized`,`secureOptions`, `secureProtocol`, `servername`, `sessionIdContext`,`highWaterMark`. + * + * `options` can be an object, a string, or a `URL` object. If `options` is a + * string, it is automatically parsed with `new URL()`. If it is a `URL` object, it will be automatically converted to an ordinary `options` object. + * + * `https.request()` returns an instance of the `http.ClientRequest` class. The `ClientRequest` instance is a writable stream. If one needs to + * upload a file with a POST request, then write to the `ClientRequest` object. + * + * ```js + * const https = require('https'); + * + * const options = { + * hostname: 'encrypted.google.com', + * port: 443, + * path: '/', + * method: 'GET' + * }; + * + * const req = https.request(options, (res) => { + * console.log('statusCode:', res.statusCode); + * console.log('headers:', res.headers); + * + * res.on('data', (d) => { + * process.stdout.write(d); + * }); + * }); + * + * req.on('error', (e) => { + * console.error(e); + * }); + * req.end(); + * ``` + * + * Example using options from `tls.connect()`: + * + * ```js + * const options = { + * hostname: 'encrypted.google.com', + * port: 443, + * path: '/', + * method: 'GET', + * key: fs.readFileSync('test/fixtures/keys/agent2-key.pem'), + * cert: fs.readFileSync('test/fixtures/keys/agent2-cert.pem') + * }; + * options.agent = new https.Agent(options); + * + * const req = https.request(options, (res) => { + * // ... + * }); + * ``` + * + * Alternatively, opt out of connection pooling by not using an `Agent`. + * + * ```js + * const options = { + * hostname: 'encrypted.google.com', + * port: 443, + * path: '/', + * method: 'GET', + * key: fs.readFileSync('test/fixtures/keys/agent2-key.pem'), + * cert: fs.readFileSync('test/fixtures/keys/agent2-cert.pem'), + * agent: false + * }; + * + * const req = https.request(options, (res) => { + * // ... + * }); + * ``` + * + * Example using a `URL` as `options`: + * + * ```js + * const options = new URL('https://abc:xyz@example.com'); + * + * const req = https.request(options, (res) => { + * // ... + * }); + * ``` + * + * Example pinning on certificate fingerprint, or the public key (similar to`pin-sha256`): + * + * ```js + * const tls = require('tls'); + * const https = require('https'); + * const crypto = require('crypto'); + * + * function sha256(s) { + * return crypto.createHash('sha256').update(s).digest('base64'); + * } + * const options = { + * hostname: 'github.com', + * port: 443, + * path: '/', + * method: 'GET', + * checkServerIdentity: function(host, cert) { + * // Make sure the certificate is issued to the host we are connected to + * const err = tls.checkServerIdentity(host, cert); + * if (err) { + * return err; + * } + * + * // Pin the public key, similar to HPKP pin-sha25 pinning + * const pubkey256 = 'pL1+qb9HTMRZJmuC/bB/ZI9d302BYrrqiVuRyW+DGrU='; + * if (sha256(cert.pubkey) !== pubkey256) { + * const msg = 'Certificate verification error: ' + + * `The public key of '${cert.subject.CN}' ` + + * 'does not match our pinned fingerprint'; + * return new Error(msg); + * } + * + * // Pin the exact certificate, rather than the pub key + * const cert256 = '25:FE:39:32:D9:63:8C:8A:FC:A1:9A:29:87:' + + * 'D8:3E:4C:1D:98:DB:71:E4:1A:48:03:98:EA:22:6A:BD:8B:93:16'; + * if (cert.fingerprint256 !== cert256) { + * const msg = 'Certificate verification error: ' + + * `The certificate of '${cert.subject.CN}' ` + + * 'does not match our pinned fingerprint'; + * return new Error(msg); + * } + * + * // This loop is informational only. + * // Print the certificate and public key fingerprints of all certs in the + * // chain. Its common to pin the public key of the issuer on the public + * // internet, while pinning the public key of the service in sensitive + * // environments. + * do { + * console.log('Subject Common Name:', cert.subject.CN); + * console.log(' Certificate SHA256 fingerprint:', cert.fingerprint256); + * + * hash = crypto.createHash('sha256'); + * console.log(' Public key ping-sha256:', sha256(cert.pubkey)); + * + * lastprint256 = cert.fingerprint256; + * cert = cert.issuerCertificate; + * } while (cert.fingerprint256 !== lastprint256); + * + * }, + * }; + * + * options.agent = new https.Agent(options); + * const req = https.request(options, (res) => { + * console.log('All OK. Server matched our pinned cert or public key'); + * console.log('statusCode:', res.statusCode); + * // Print the HPKP values + * console.log('headers:', res.headers['public-key-pins']); + * + * res.on('data', (d) => {}); + * }); + * + * req.on('error', (e) => { + * console.error(e.message); + * }); + * req.end(); + * ``` + * + * Outputs for example: + * + * ```text + * Subject Common Name: github.com + * Certificate SHA256 fingerprint: 25:FE:39:32:D9:63:8C:8A:FC:A1:9A:29:87:D8:3E:4C:1D:98:DB:71:E4:1A:48:03:98:EA:22:6A:BD:8B:93:16 + * Public key ping-sha256: pL1+qb9HTMRZJmuC/bB/ZI9d302BYrrqiVuRyW+DGrU= + * Subject Common Name: DigiCert SHA2 Extended Validation Server CA + * Certificate SHA256 fingerprint: 40:3E:06:2A:26:53:05:91:13:28:5B:AF:80:A0:D4:AE:42:2C:84:8C:9F:78:FA:D0:1F:C9:4B:C5:B8:7F:EF:1A + * Public key ping-sha256: RRM1dGqnDFsCJXBTHky16vi1obOlCgFFn/yOhI/y+ho= + * Subject Common Name: DigiCert High Assurance EV Root CA + * Certificate SHA256 fingerprint: 74:31:E5:F4:C3:C1:CE:46:90:77:4F:0B:61:E0:54:40:88:3B:A9:A0:1E:D0:0B:A6:AB:D7:80:6E:D3:B1:18:CF + * Public key ping-sha256: WoiWRyIOVNa9ihaBciRSC7XHjliYS9VwUGOIud4PB18= + * All OK. Server matched our pinned cert or public key + * statusCode: 200 + * headers: max-age=0; pin-sha256="WoiWRyIOVNa9ihaBciRSC7XHjliYS9VwUGOIud4PB18="; pin-sha256="RRM1dGqnDFsCJXBTHky16vi1obOlCgFFn/yOhI/y+ho="; + * pin-sha256="k2v657xBsOVe1PQRwOsHsw3bsGT2VzIqz5K+59sNQws="; pin-sha256="K87oWBWM9UZfyddvDfoxL+8lpNyoUB2ptGtn0fv6G2Q="; pin-sha256="IQBnNBEiFuhj+8x6X8XLgh01V9Ic5/V3IRQLNFFc7v4="; + * pin-sha256="iie1VXtL7HzAMF+/PVPR9xzT80kQxdZeJ+zduCB3uj0="; pin-sha256="LvRiGEjRqfzurezaWuj8Wie2gyHMrW5Q06LspMnox7A="; includeSubDomains + * ``` + * @since v0.3.6 + * @param options Accepts all `options` from `request`, with some differences in default values: + */ + function request(options: RequestOptions | string | URL, callback?: (res: http.IncomingMessage) => void): http.ClientRequest; + function request(url: string | URL, options: RequestOptions, callback?: (res: http.IncomingMessage) => void): http.ClientRequest; + /** + * Like `http.get()` but for HTTPS. + * + * `options` can be an object, a string, or a `URL` object. If `options` is a + * string, it is automatically parsed with `new URL()`. If it is a `URL` object, it will be automatically converted to an ordinary `options` object. + * + * ```js + * const https = require('https'); + * + * https.get('https://encrypted.google.com/', (res) => { + * console.log('statusCode:', res.statusCode); + * console.log('headers:', res.headers); + * + * res.on('data', (d) => { + * process.stdout.write(d); + * }); + * + * }).on('error', (e) => { + * console.error(e); + * }); + * ``` + * @since v0.3.6 + * @param options Accepts the same `options` as {@link request}, with the `method` always set to `GET`. + */ + function get(options: RequestOptions | string | URL, callback?: (res: http.IncomingMessage) => void): http.ClientRequest; + function get(url: string | URL, options: RequestOptions, callback?: (res: http.IncomingMessage) => void): http.ClientRequest; + let globalAgent: Agent; +} +declare module 'node:https' { + export * from 'https'; +} diff --git a/ts-ticket-office-service/node_modules/@types/node/index.d.ts b/ts-ticket-office-service/node_modules/@types/node/index.d.ts new file mode 100755 index 000000000..a6346aaf8 --- /dev/null +++ b/ts-ticket-office-service/node_modules/@types/node/index.d.ts @@ -0,0 +1,131 @@ +// Type definitions for non-npm package Node.js 18.6 +// Project: https://nodejs.org/ +// Definitions by: Microsoft TypeScript +// DefinitelyTyped +// Alberto Schiabel +// Alvis HT Tang +// Andrew Makarov +// Benjamin Toueg +// Chigozirim C. +// David Junger +// Deividas Bakanas +// Eugene Y. Q. Shen +// Hannes Magnusson +// Huw +// Kelvin Jin +// Klaus Meinhardt +// Lishude +// Mariusz Wiktorczyk +// Mohsen Azimi +// Nicolas Even +// Nikita Galkin +// Parambir Singh +// Sebastian Silbermann +// Simon Schick +// Thomas den Hollander +// Wilco Bakker +// wwwy3y3 +// Samuel Ainsworth +// Kyle Uehlein +// Thanik Bhongbhibhat +// Marcin Kopacz +// Trivikram Kamat +// Junxiao Shi +// Ilia Baryshnikov +// ExE Boss +// Piotr Błażejewicz +// Anna Henningsen +// Victor Perin +// Yongsheng Zhang +// NodeJS Contributors +// Linus Unnebäck +// wafuwafu13 +// Matteo Collina +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/** + * License for programmatically and manually incorporated + * documentation aka. `JSDoc` from https://github.com/nodejs/node/tree/master/doc + * + * Copyright Node.js contributors. All rights reserved. + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to + * deal in the Software without restriction, including without limitation the + * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or + * sell copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING + * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS + * IN THE SOFTWARE. + */ + +// NOTE: These definitions support NodeJS and TypeScript 3.7+. + +// Reference required types from the default lib: +/// +/// +/// +/// + +// Base definitions for all NodeJS modules that are not specific to any version of TypeScript: +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// + +/// diff --git a/ts-ticket-office-service/node_modules/@types/node/inspector.d.ts b/ts-ticket-office-service/node_modules/@types/node/inspector.d.ts new file mode 100755 index 000000000..a64ab6b78 --- /dev/null +++ b/ts-ticket-office-service/node_modules/@types/node/inspector.d.ts @@ -0,0 +1,2741 @@ +// tslint:disable-next-line:dt-header +// Type definitions for inspector + +// These definitions are auto-generated. +// Please see https://github.com/DefinitelyTyped/DefinitelyTyped/pull/19330 +// for more information. + +// tslint:disable:max-line-length + +/** + * The `inspector` module provides an API for interacting with the V8 inspector. + * + * It can be accessed using: + * + * ```js + * const inspector = require('inspector'); + * ``` + * @see [source](https://github.com/nodejs/node/blob/v18.0.0/lib/inspector.js) + */ +declare module 'inspector' { + import EventEmitter = require('node:events'); + interface InspectorNotification { + method: string; + params: T; + } + namespace Schema { + /** + * Description of the protocol domain. + */ + interface Domain { + /** + * Domain name. + */ + name: string; + /** + * Domain version. + */ + version: string; + } + interface GetDomainsReturnType { + /** + * List of supported domains. + */ + domains: Domain[]; + } + } + namespace Runtime { + /** + * Unique script identifier. + */ + type ScriptId = string; + /** + * Unique object identifier. + */ + type RemoteObjectId = string; + /** + * Primitive value which cannot be JSON-stringified. + */ + type UnserializableValue = string; + /** + * Mirror object referencing original JavaScript object. + */ + interface RemoteObject { + /** + * Object type. + */ + type: string; + /** + * Object subtype hint. Specified for object type values only. + */ + subtype?: string | undefined; + /** + * Object class (constructor) name. Specified for object type values only. + */ + className?: string | undefined; + /** + * Remote object value in case of primitive values or JSON values (if it was requested). + */ + value?: any; + /** + * Primitive value which can not be JSON-stringified does not have value, but gets this property. + */ + unserializableValue?: UnserializableValue | undefined; + /** + * String representation of the object. + */ + description?: string | undefined; + /** + * Unique object identifier (for non-primitive values). + */ + objectId?: RemoteObjectId | undefined; + /** + * Preview containing abbreviated property values. Specified for object type values only. + * @experimental + */ + preview?: ObjectPreview | undefined; + /** + * @experimental + */ + customPreview?: CustomPreview | undefined; + } + /** + * @experimental + */ + interface CustomPreview { + header: string; + hasBody: boolean; + formatterObjectId: RemoteObjectId; + bindRemoteObjectFunctionId: RemoteObjectId; + configObjectId?: RemoteObjectId | undefined; + } + /** + * Object containing abbreviated remote object value. + * @experimental + */ + interface ObjectPreview { + /** + * Object type. + */ + type: string; + /** + * Object subtype hint. Specified for object type values only. + */ + subtype?: string | undefined; + /** + * String representation of the object. + */ + description?: string | undefined; + /** + * True iff some of the properties or entries of the original object did not fit. + */ + overflow: boolean; + /** + * List of the properties. + */ + properties: PropertyPreview[]; + /** + * List of the entries. Specified for map and set subtype values only. + */ + entries?: EntryPreview[] | undefined; + } + /** + * @experimental + */ + interface PropertyPreview { + /** + * Property name. + */ + name: string; + /** + * Object type. Accessor means that the property itself is an accessor property. + */ + type: string; + /** + * User-friendly property value string. + */ + value?: string | undefined; + /** + * Nested value preview. + */ + valuePreview?: ObjectPreview | undefined; + /** + * Object subtype hint. Specified for object type values only. + */ + subtype?: string | undefined; + } + /** + * @experimental + */ + interface EntryPreview { + /** + * Preview of the key. Specified for map-like collection entries. + */ + key?: ObjectPreview | undefined; + /** + * Preview of the value. + */ + value: ObjectPreview; + } + /** + * Object property descriptor. + */ + interface PropertyDescriptor { + /** + * Property name or symbol description. + */ + name: string; + /** + * The value associated with the property. + */ + value?: RemoteObject | undefined; + /** + * True if the value associated with the property may be changed (data descriptors only). + */ + writable?: boolean | undefined; + /** + * A function which serves as a getter for the property, or undefined if there is no getter (accessor descriptors only). + */ + get?: RemoteObject | undefined; + /** + * A function which serves as a setter for the property, or undefined if there is no setter (accessor descriptors only). + */ + set?: RemoteObject | undefined; + /** + * True if the type of this property descriptor may be changed and if the property may be deleted from the corresponding object. + */ + configurable: boolean; + /** + * True if this property shows up during enumeration of the properties on the corresponding object. + */ + enumerable: boolean; + /** + * True if the result was thrown during the evaluation. + */ + wasThrown?: boolean | undefined; + /** + * True if the property is owned for the object. + */ + isOwn?: boolean | undefined; + /** + * Property symbol object, if the property is of the symbol type. + */ + symbol?: RemoteObject | undefined; + } + /** + * Object internal property descriptor. This property isn't normally visible in JavaScript code. + */ + interface InternalPropertyDescriptor { + /** + * Conventional property name. + */ + name: string; + /** + * The value associated with the property. + */ + value?: RemoteObject | undefined; + } + /** + * Represents function call argument. Either remote object id objectId, primitive value, unserializable primitive value or neither of (for undefined) them should be specified. + */ + interface CallArgument { + /** + * Primitive value or serializable javascript object. + */ + value?: any; + /** + * Primitive value which can not be JSON-stringified. + */ + unserializableValue?: UnserializableValue | undefined; + /** + * Remote object handle. + */ + objectId?: RemoteObjectId | undefined; + } + /** + * Id of an execution context. + */ + type ExecutionContextId = number; + /** + * Description of an isolated world. + */ + interface ExecutionContextDescription { + /** + * Unique id of the execution context. It can be used to specify in which execution context script evaluation should be performed. + */ + id: ExecutionContextId; + /** + * Execution context origin. + */ + origin: string; + /** + * Human readable name describing given context. + */ + name: string; + /** + * Embedder-specific auxiliary data. + */ + auxData?: {} | undefined; + } + /** + * Detailed information about exception (or error) that was thrown during script compilation or execution. + */ + interface ExceptionDetails { + /** + * Exception id. + */ + exceptionId: number; + /** + * Exception text, which should be used together with exception object when available. + */ + text: string; + /** + * Line number of the exception location (0-based). + */ + lineNumber: number; + /** + * Column number of the exception location (0-based). + */ + columnNumber: number; + /** + * Script ID of the exception location. + */ + scriptId?: ScriptId | undefined; + /** + * URL of the exception location, to be used when the script was not reported. + */ + url?: string | undefined; + /** + * JavaScript stack trace if available. + */ + stackTrace?: StackTrace | undefined; + /** + * Exception object if available. + */ + exception?: RemoteObject | undefined; + /** + * Identifier of the context where exception happened. + */ + executionContextId?: ExecutionContextId | undefined; + } + /** + * Number of milliseconds since epoch. + */ + type Timestamp = number; + /** + * Stack entry for runtime errors and assertions. + */ + interface CallFrame { + /** + * JavaScript function name. + */ + functionName: string; + /** + * JavaScript script id. + */ + scriptId: ScriptId; + /** + * JavaScript script name or url. + */ + url: string; + /** + * JavaScript script line number (0-based). + */ + lineNumber: number; + /** + * JavaScript script column number (0-based). + */ + columnNumber: number; + } + /** + * Call frames for assertions or error messages. + */ + interface StackTrace { + /** + * String label of this stack trace. For async traces this may be a name of the function that initiated the async call. + */ + description?: string | undefined; + /** + * JavaScript function name. + */ + callFrames: CallFrame[]; + /** + * Asynchronous JavaScript stack trace that preceded this stack, if available. + */ + parent?: StackTrace | undefined; + /** + * Asynchronous JavaScript stack trace that preceded this stack, if available. + * @experimental + */ + parentId?: StackTraceId | undefined; + } + /** + * Unique identifier of current debugger. + * @experimental + */ + type UniqueDebuggerId = string; + /** + * If debuggerId is set stack trace comes from another debugger and can be resolved there. This allows to track cross-debugger calls. See Runtime.StackTrace and Debugger.paused for usages. + * @experimental + */ + interface StackTraceId { + id: string; + debuggerId?: UniqueDebuggerId | undefined; + } + interface EvaluateParameterType { + /** + * Expression to evaluate. + */ + expression: string; + /** + * Symbolic group name that can be used to release multiple objects. + */ + objectGroup?: string | undefined; + /** + * Determines whether Command Line API should be available during the evaluation. + */ + includeCommandLineAPI?: boolean | undefined; + /** + * In silent mode exceptions thrown during evaluation are not reported and do not pause execution. Overrides setPauseOnException state. + */ + silent?: boolean | undefined; + /** + * Specifies in which execution context to perform evaluation. If the parameter is omitted the evaluation will be performed in the context of the inspected page. + */ + contextId?: ExecutionContextId | undefined; + /** + * Whether the result is expected to be a JSON object that should be sent by value. + */ + returnByValue?: boolean | undefined; + /** + * Whether preview should be generated for the result. + * @experimental + */ + generatePreview?: boolean | undefined; + /** + * Whether execution should be treated as initiated by user in the UI. + */ + userGesture?: boolean | undefined; + /** + * Whether execution should await for resulting value and return once awaited promise is resolved. + */ + awaitPromise?: boolean | undefined; + } + interface AwaitPromiseParameterType { + /** + * Identifier of the promise. + */ + promiseObjectId: RemoteObjectId; + /** + * Whether the result is expected to be a JSON object that should be sent by value. + */ + returnByValue?: boolean | undefined; + /** + * Whether preview should be generated for the result. + */ + generatePreview?: boolean | undefined; + } + interface CallFunctionOnParameterType { + /** + * Declaration of the function to call. + */ + functionDeclaration: string; + /** + * Identifier of the object to call function on. Either objectId or executionContextId should be specified. + */ + objectId?: RemoteObjectId | undefined; + /** + * Call arguments. All call arguments must belong to the same JavaScript world as the target object. + */ + arguments?: CallArgument[] | undefined; + /** + * In silent mode exceptions thrown during evaluation are not reported and do not pause execution. Overrides setPauseOnException state. + */ + silent?: boolean | undefined; + /** + * Whether the result is expected to be a JSON object which should be sent by value. + */ + returnByValue?: boolean | undefined; + /** + * Whether preview should be generated for the result. + * @experimental + */ + generatePreview?: boolean | undefined; + /** + * Whether execution should be treated as initiated by user in the UI. + */ + userGesture?: boolean | undefined; + /** + * Whether execution should await for resulting value and return once awaited promise is resolved. + */ + awaitPromise?: boolean | undefined; + /** + * Specifies execution context which global object will be used to call function on. Either executionContextId or objectId should be specified. + */ + executionContextId?: ExecutionContextId | undefined; + /** + * Symbolic group name that can be used to release multiple objects. If objectGroup is not specified and objectId is, objectGroup will be inherited from object. + */ + objectGroup?: string | undefined; + } + interface GetPropertiesParameterType { + /** + * Identifier of the object to return properties for. + */ + objectId: RemoteObjectId; + /** + * If true, returns properties belonging only to the element itself, not to its prototype chain. + */ + ownProperties?: boolean | undefined; + /** + * If true, returns accessor properties (with getter/setter) only; internal properties are not returned either. + * @experimental + */ + accessorPropertiesOnly?: boolean | undefined; + /** + * Whether preview should be generated for the results. + * @experimental + */ + generatePreview?: boolean | undefined; + } + interface ReleaseObjectParameterType { + /** + * Identifier of the object to release. + */ + objectId: RemoteObjectId; + } + interface ReleaseObjectGroupParameterType { + /** + * Symbolic object group name. + */ + objectGroup: string; + } + interface SetCustomObjectFormatterEnabledParameterType { + enabled: boolean; + } + interface CompileScriptParameterType { + /** + * Expression to compile. + */ + expression: string; + /** + * Source url to be set for the script. + */ + sourceURL: string; + /** + * Specifies whether the compiled script should be persisted. + */ + persistScript: boolean; + /** + * Specifies in which execution context to perform script run. If the parameter is omitted the evaluation will be performed in the context of the inspected page. + */ + executionContextId?: ExecutionContextId | undefined; + } + interface RunScriptParameterType { + /** + * Id of the script to run. + */ + scriptId: ScriptId; + /** + * Specifies in which execution context to perform script run. If the parameter is omitted the evaluation will be performed in the context of the inspected page. + */ + executionContextId?: ExecutionContextId | undefined; + /** + * Symbolic group name that can be used to release multiple objects. + */ + objectGroup?: string | undefined; + /** + * In silent mode exceptions thrown during evaluation are not reported and do not pause execution. Overrides setPauseOnException state. + */ + silent?: boolean | undefined; + /** + * Determines whether Command Line API should be available during the evaluation. + */ + includeCommandLineAPI?: boolean | undefined; + /** + * Whether the result is expected to be a JSON object which should be sent by value. + */ + returnByValue?: boolean | undefined; + /** + * Whether preview should be generated for the result. + */ + generatePreview?: boolean | undefined; + /** + * Whether execution should await for resulting value and return once awaited promise is resolved. + */ + awaitPromise?: boolean | undefined; + } + interface QueryObjectsParameterType { + /** + * Identifier of the prototype to return objects for. + */ + prototypeObjectId: RemoteObjectId; + } + interface GlobalLexicalScopeNamesParameterType { + /** + * Specifies in which execution context to lookup global scope variables. + */ + executionContextId?: ExecutionContextId | undefined; + } + interface EvaluateReturnType { + /** + * Evaluation result. + */ + result: RemoteObject; + /** + * Exception details. + */ + exceptionDetails?: ExceptionDetails | undefined; + } + interface AwaitPromiseReturnType { + /** + * Promise result. Will contain rejected value if promise was rejected. + */ + result: RemoteObject; + /** + * Exception details if stack strace is available. + */ + exceptionDetails?: ExceptionDetails | undefined; + } + interface CallFunctionOnReturnType { + /** + * Call result. + */ + result: RemoteObject; + /** + * Exception details. + */ + exceptionDetails?: ExceptionDetails | undefined; + } + interface GetPropertiesReturnType { + /** + * Object properties. + */ + result: PropertyDescriptor[]; + /** + * Internal object properties (only of the element itself). + */ + internalProperties?: InternalPropertyDescriptor[] | undefined; + /** + * Exception details. + */ + exceptionDetails?: ExceptionDetails | undefined; + } + interface CompileScriptReturnType { + /** + * Id of the script. + */ + scriptId?: ScriptId | undefined; + /** + * Exception details. + */ + exceptionDetails?: ExceptionDetails | undefined; + } + interface RunScriptReturnType { + /** + * Run result. + */ + result: RemoteObject; + /** + * Exception details. + */ + exceptionDetails?: ExceptionDetails | undefined; + } + interface QueryObjectsReturnType { + /** + * Array with objects. + */ + objects: RemoteObject; + } + interface GlobalLexicalScopeNamesReturnType { + names: string[]; + } + interface ExecutionContextCreatedEventDataType { + /** + * A newly created execution context. + */ + context: ExecutionContextDescription; + } + interface ExecutionContextDestroyedEventDataType { + /** + * Id of the destroyed context + */ + executionContextId: ExecutionContextId; + } + interface ExceptionThrownEventDataType { + /** + * Timestamp of the exception. + */ + timestamp: Timestamp; + exceptionDetails: ExceptionDetails; + } + interface ExceptionRevokedEventDataType { + /** + * Reason describing why exception was revoked. + */ + reason: string; + /** + * The id of revoked exception, as reported in exceptionThrown. + */ + exceptionId: number; + } + interface ConsoleAPICalledEventDataType { + /** + * Type of the call. + */ + type: string; + /** + * Call arguments. + */ + args: RemoteObject[]; + /** + * Identifier of the context where the call was made. + */ + executionContextId: ExecutionContextId; + /** + * Call timestamp. + */ + timestamp: Timestamp; + /** + * Stack trace captured when the call was made. + */ + stackTrace?: StackTrace | undefined; + /** + * Console context descriptor for calls on non-default console context (not console.*): 'anonymous#unique-logger-id' for call on unnamed context, 'name#unique-logger-id' for call on named context. + * @experimental + */ + context?: string | undefined; + } + interface InspectRequestedEventDataType { + object: RemoteObject; + hints: {}; + } + } + namespace Debugger { + /** + * Breakpoint identifier. + */ + type BreakpointId = string; + /** + * Call frame identifier. + */ + type CallFrameId = string; + /** + * Location in the source code. + */ + interface Location { + /** + * Script identifier as reported in the Debugger.scriptParsed. + */ + scriptId: Runtime.ScriptId; + /** + * Line number in the script (0-based). + */ + lineNumber: number; + /** + * Column number in the script (0-based). + */ + columnNumber?: number | undefined; + } + /** + * Location in the source code. + * @experimental + */ + interface ScriptPosition { + lineNumber: number; + columnNumber: number; + } + /** + * JavaScript call frame. Array of call frames form the call stack. + */ + interface CallFrame { + /** + * Call frame identifier. This identifier is only valid while the virtual machine is paused. + */ + callFrameId: CallFrameId; + /** + * Name of the JavaScript function called on this call frame. + */ + functionName: string; + /** + * Location in the source code. + */ + functionLocation?: Location | undefined; + /** + * Location in the source code. + */ + location: Location; + /** + * JavaScript script name or url. + */ + url: string; + /** + * Scope chain for this call frame. + */ + scopeChain: Scope[]; + /** + * this object for this call frame. + */ + this: Runtime.RemoteObject; + /** + * The value being returned, if the function is at return point. + */ + returnValue?: Runtime.RemoteObject | undefined; + } + /** + * Scope description. + */ + interface Scope { + /** + * Scope type. + */ + type: string; + /** + * Object representing the scope. For global and with scopes it represents the actual object; for the rest of the scopes, it is artificial transient object enumerating scope variables as its properties. + */ + object: Runtime.RemoteObject; + name?: string | undefined; + /** + * Location in the source code where scope starts + */ + startLocation?: Location | undefined; + /** + * Location in the source code where scope ends + */ + endLocation?: Location | undefined; + } + /** + * Search match for resource. + */ + interface SearchMatch { + /** + * Line number in resource content. + */ + lineNumber: number; + /** + * Line with match content. + */ + lineContent: string; + } + interface BreakLocation { + /** + * Script identifier as reported in the Debugger.scriptParsed. + */ + scriptId: Runtime.ScriptId; + /** + * Line number in the script (0-based). + */ + lineNumber: number; + /** + * Column number in the script (0-based). + */ + columnNumber?: number | undefined; + type?: string | undefined; + } + interface SetBreakpointsActiveParameterType { + /** + * New value for breakpoints active state. + */ + active: boolean; + } + interface SetSkipAllPausesParameterType { + /** + * New value for skip pauses state. + */ + skip: boolean; + } + interface SetBreakpointByUrlParameterType { + /** + * Line number to set breakpoint at. + */ + lineNumber: number; + /** + * URL of the resources to set breakpoint on. + */ + url?: string | undefined; + /** + * Regex pattern for the URLs of the resources to set breakpoints on. Either url or urlRegex must be specified. + */ + urlRegex?: string | undefined; + /** + * Script hash of the resources to set breakpoint on. + */ + scriptHash?: string | undefined; + /** + * Offset in the line to set breakpoint at. + */ + columnNumber?: number | undefined; + /** + * Expression to use as a breakpoint condition. When specified, debugger will only stop on the breakpoint if this expression evaluates to true. + */ + condition?: string | undefined; + } + interface SetBreakpointParameterType { + /** + * Location to set breakpoint in. + */ + location: Location; + /** + * Expression to use as a breakpoint condition. When specified, debugger will only stop on the breakpoint if this expression evaluates to true. + */ + condition?: string | undefined; + } + interface RemoveBreakpointParameterType { + breakpointId: BreakpointId; + } + interface GetPossibleBreakpointsParameterType { + /** + * Start of range to search possible breakpoint locations in. + */ + start: Location; + /** + * End of range to search possible breakpoint locations in (excluding). When not specified, end of scripts is used as end of range. + */ + end?: Location | undefined; + /** + * Only consider locations which are in the same (non-nested) function as start. + */ + restrictToFunction?: boolean | undefined; + } + interface ContinueToLocationParameterType { + /** + * Location to continue to. + */ + location: Location; + targetCallFrames?: string | undefined; + } + interface PauseOnAsyncCallParameterType { + /** + * Debugger will pause when async call with given stack trace is started. + */ + parentStackTraceId: Runtime.StackTraceId; + } + interface StepIntoParameterType { + /** + * Debugger will issue additional Debugger.paused notification if any async task is scheduled before next pause. + * @experimental + */ + breakOnAsyncCall?: boolean | undefined; + } + interface GetStackTraceParameterType { + stackTraceId: Runtime.StackTraceId; + } + interface SearchInContentParameterType { + /** + * Id of the script to search in. + */ + scriptId: Runtime.ScriptId; + /** + * String to search for. + */ + query: string; + /** + * If true, search is case sensitive. + */ + caseSensitive?: boolean | undefined; + /** + * If true, treats string parameter as regex. + */ + isRegex?: boolean | undefined; + } + interface SetScriptSourceParameterType { + /** + * Id of the script to edit. + */ + scriptId: Runtime.ScriptId; + /** + * New content of the script. + */ + scriptSource: string; + /** + * If true the change will not actually be applied. Dry run may be used to get result description without actually modifying the code. + */ + dryRun?: boolean | undefined; + } + interface RestartFrameParameterType { + /** + * Call frame identifier to evaluate on. + */ + callFrameId: CallFrameId; + } + interface GetScriptSourceParameterType { + /** + * Id of the script to get source for. + */ + scriptId: Runtime.ScriptId; + } + interface SetPauseOnExceptionsParameterType { + /** + * Pause on exceptions mode. + */ + state: string; + } + interface EvaluateOnCallFrameParameterType { + /** + * Call frame identifier to evaluate on. + */ + callFrameId: CallFrameId; + /** + * Expression to evaluate. + */ + expression: string; + /** + * String object group name to put result into (allows rapid releasing resulting object handles using releaseObjectGroup). + */ + objectGroup?: string | undefined; + /** + * Specifies whether command line API should be available to the evaluated expression, defaults to false. + */ + includeCommandLineAPI?: boolean | undefined; + /** + * In silent mode exceptions thrown during evaluation are not reported and do not pause execution. Overrides setPauseOnException state. + */ + silent?: boolean | undefined; + /** + * Whether the result is expected to be a JSON object that should be sent by value. + */ + returnByValue?: boolean | undefined; + /** + * Whether preview should be generated for the result. + * @experimental + */ + generatePreview?: boolean | undefined; + /** + * Whether to throw an exception if side effect cannot be ruled out during evaluation. + */ + throwOnSideEffect?: boolean | undefined; + } + interface SetVariableValueParameterType { + /** + * 0-based number of scope as was listed in scope chain. Only 'local', 'closure' and 'catch' scope types are allowed. Other scopes could be manipulated manually. + */ + scopeNumber: number; + /** + * Variable name. + */ + variableName: string; + /** + * New variable value. + */ + newValue: Runtime.CallArgument; + /** + * Id of callframe that holds variable. + */ + callFrameId: CallFrameId; + } + interface SetReturnValueParameterType { + /** + * New return value. + */ + newValue: Runtime.CallArgument; + } + interface SetAsyncCallStackDepthParameterType { + /** + * Maximum depth of async call stacks. Setting to 0 will effectively disable collecting async call stacks (default). + */ + maxDepth: number; + } + interface SetBlackboxPatternsParameterType { + /** + * Array of regexps that will be used to check script url for blackbox state. + */ + patterns: string[]; + } + interface SetBlackboxedRangesParameterType { + /** + * Id of the script. + */ + scriptId: Runtime.ScriptId; + positions: ScriptPosition[]; + } + interface EnableReturnType { + /** + * Unique identifier of the debugger. + * @experimental + */ + debuggerId: Runtime.UniqueDebuggerId; + } + interface SetBreakpointByUrlReturnType { + /** + * Id of the created breakpoint for further reference. + */ + breakpointId: BreakpointId; + /** + * List of the locations this breakpoint resolved into upon addition. + */ + locations: Location[]; + } + interface SetBreakpointReturnType { + /** + * Id of the created breakpoint for further reference. + */ + breakpointId: BreakpointId; + /** + * Location this breakpoint resolved into. + */ + actualLocation: Location; + } + interface GetPossibleBreakpointsReturnType { + /** + * List of the possible breakpoint locations. + */ + locations: BreakLocation[]; + } + interface GetStackTraceReturnType { + stackTrace: Runtime.StackTrace; + } + interface SearchInContentReturnType { + /** + * List of search matches. + */ + result: SearchMatch[]; + } + interface SetScriptSourceReturnType { + /** + * New stack trace in case editing has happened while VM was stopped. + */ + callFrames?: CallFrame[] | undefined; + /** + * Whether current call stack was modified after applying the changes. + */ + stackChanged?: boolean | undefined; + /** + * Async stack trace, if any. + */ + asyncStackTrace?: Runtime.StackTrace | undefined; + /** + * Async stack trace, if any. + * @experimental + */ + asyncStackTraceId?: Runtime.StackTraceId | undefined; + /** + * Exception details if any. + */ + exceptionDetails?: Runtime.ExceptionDetails | undefined; + } + interface RestartFrameReturnType { + /** + * New stack trace. + */ + callFrames: CallFrame[]; + /** + * Async stack trace, if any. + */ + asyncStackTrace?: Runtime.StackTrace | undefined; + /** + * Async stack trace, if any. + * @experimental + */ + asyncStackTraceId?: Runtime.StackTraceId | undefined; + } + interface GetScriptSourceReturnType { + /** + * Script source. + */ + scriptSource: string; + } + interface EvaluateOnCallFrameReturnType { + /** + * Object wrapper for the evaluation result. + */ + result: Runtime.RemoteObject; + /** + * Exception details. + */ + exceptionDetails?: Runtime.ExceptionDetails | undefined; + } + interface ScriptParsedEventDataType { + /** + * Identifier of the script parsed. + */ + scriptId: Runtime.ScriptId; + /** + * URL or name of the script parsed (if any). + */ + url: string; + /** + * Line offset of the script within the resource with given URL (for script tags). + */ + startLine: number; + /** + * Column offset of the script within the resource with given URL. + */ + startColumn: number; + /** + * Last line of the script. + */ + endLine: number; + /** + * Length of the last line of the script. + */ + endColumn: number; + /** + * Specifies script creation context. + */ + executionContextId: Runtime.ExecutionContextId; + /** + * Content hash of the script. + */ + hash: string; + /** + * Embedder-specific auxiliary data. + */ + executionContextAuxData?: {} | undefined; + /** + * True, if this script is generated as a result of the live edit operation. + * @experimental + */ + isLiveEdit?: boolean | undefined; + /** + * URL of source map associated with script (if any). + */ + sourceMapURL?: string | undefined; + /** + * True, if this script has sourceURL. + */ + hasSourceURL?: boolean | undefined; + /** + * True, if this script is ES6 module. + */ + isModule?: boolean | undefined; + /** + * This script length. + */ + length?: number | undefined; + /** + * JavaScript top stack frame of where the script parsed event was triggered if available. + * @experimental + */ + stackTrace?: Runtime.StackTrace | undefined; + } + interface ScriptFailedToParseEventDataType { + /** + * Identifier of the script parsed. + */ + scriptId: Runtime.ScriptId; + /** + * URL or name of the script parsed (if any). + */ + url: string; + /** + * Line offset of the script within the resource with given URL (for script tags). + */ + startLine: number; + /** + * Column offset of the script within the resource with given URL. + */ + startColumn: number; + /** + * Last line of the script. + */ + endLine: number; + /** + * Length of the last line of the script. + */ + endColumn: number; + /** + * Specifies script creation context. + */ + executionContextId: Runtime.ExecutionContextId; + /** + * Content hash of the script. + */ + hash: string; + /** + * Embedder-specific auxiliary data. + */ + executionContextAuxData?: {} | undefined; + /** + * URL of source map associated with script (if any). + */ + sourceMapURL?: string | undefined; + /** + * True, if this script has sourceURL. + */ + hasSourceURL?: boolean | undefined; + /** + * True, if this script is ES6 module. + */ + isModule?: boolean | undefined; + /** + * This script length. + */ + length?: number | undefined; + /** + * JavaScript top stack frame of where the script parsed event was triggered if available. + * @experimental + */ + stackTrace?: Runtime.StackTrace | undefined; + } + interface BreakpointResolvedEventDataType { + /** + * Breakpoint unique identifier. + */ + breakpointId: BreakpointId; + /** + * Actual breakpoint location. + */ + location: Location; + } + interface PausedEventDataType { + /** + * Call stack the virtual machine stopped on. + */ + callFrames: CallFrame[]; + /** + * Pause reason. + */ + reason: string; + /** + * Object containing break-specific auxiliary properties. + */ + data?: {} | undefined; + /** + * Hit breakpoints IDs + */ + hitBreakpoints?: string[] | undefined; + /** + * Async stack trace, if any. + */ + asyncStackTrace?: Runtime.StackTrace | undefined; + /** + * Async stack trace, if any. + * @experimental + */ + asyncStackTraceId?: Runtime.StackTraceId | undefined; + /** + * Just scheduled async call will have this stack trace as parent stack during async execution. This field is available only after Debugger.stepInto call with breakOnAsynCall flag. + * @experimental + */ + asyncCallStackTraceId?: Runtime.StackTraceId | undefined; + } + } + namespace Console { + /** + * Console message. + */ + interface ConsoleMessage { + /** + * Message source. + */ + source: string; + /** + * Message severity. + */ + level: string; + /** + * Message text. + */ + text: string; + /** + * URL of the message origin. + */ + url?: string | undefined; + /** + * Line number in the resource that generated this message (1-based). + */ + line?: number | undefined; + /** + * Column number in the resource that generated this message (1-based). + */ + column?: number | undefined; + } + interface MessageAddedEventDataType { + /** + * Console message that has been added. + */ + message: ConsoleMessage; + } + } + namespace Profiler { + /** + * Profile node. Holds callsite information, execution statistics and child nodes. + */ + interface ProfileNode { + /** + * Unique id of the node. + */ + id: number; + /** + * Function location. + */ + callFrame: Runtime.CallFrame; + /** + * Number of samples where this node was on top of the call stack. + */ + hitCount?: number | undefined; + /** + * Child node ids. + */ + children?: number[] | undefined; + /** + * The reason of being not optimized. The function may be deoptimized or marked as don't optimize. + */ + deoptReason?: string | undefined; + /** + * An array of source position ticks. + */ + positionTicks?: PositionTickInfo[] | undefined; + } + /** + * Profile. + */ + interface Profile { + /** + * The list of profile nodes. First item is the root node. + */ + nodes: ProfileNode[]; + /** + * Profiling start timestamp in microseconds. + */ + startTime: number; + /** + * Profiling end timestamp in microseconds. + */ + endTime: number; + /** + * Ids of samples top nodes. + */ + samples?: number[] | undefined; + /** + * Time intervals between adjacent samples in microseconds. The first delta is relative to the profile startTime. + */ + timeDeltas?: number[] | undefined; + } + /** + * Specifies a number of samples attributed to a certain source position. + */ + interface PositionTickInfo { + /** + * Source line number (1-based). + */ + line: number; + /** + * Number of samples attributed to the source line. + */ + ticks: number; + } + /** + * Coverage data for a source range. + */ + interface CoverageRange { + /** + * JavaScript script source offset for the range start. + */ + startOffset: number; + /** + * JavaScript script source offset for the range end. + */ + endOffset: number; + /** + * Collected execution count of the source range. + */ + count: number; + } + /** + * Coverage data for a JavaScript function. + */ + interface FunctionCoverage { + /** + * JavaScript function name. + */ + functionName: string; + /** + * Source ranges inside the function with coverage data. + */ + ranges: CoverageRange[]; + /** + * Whether coverage data for this function has block granularity. + */ + isBlockCoverage: boolean; + } + /** + * Coverage data for a JavaScript script. + */ + interface ScriptCoverage { + /** + * JavaScript script id. + */ + scriptId: Runtime.ScriptId; + /** + * JavaScript script name or url. + */ + url: string; + /** + * Functions contained in the script that has coverage data. + */ + functions: FunctionCoverage[]; + } + /** + * Describes a type collected during runtime. + * @experimental + */ + interface TypeObject { + /** + * Name of a type collected with type profiling. + */ + name: string; + } + /** + * Source offset and types for a parameter or return value. + * @experimental + */ + interface TypeProfileEntry { + /** + * Source offset of the parameter or end of function for return values. + */ + offset: number; + /** + * The types for this parameter or return value. + */ + types: TypeObject[]; + } + /** + * Type profile data collected during runtime for a JavaScript script. + * @experimental + */ + interface ScriptTypeProfile { + /** + * JavaScript script id. + */ + scriptId: Runtime.ScriptId; + /** + * JavaScript script name or url. + */ + url: string; + /** + * Type profile entries for parameters and return values of the functions in the script. + */ + entries: TypeProfileEntry[]; + } + interface SetSamplingIntervalParameterType { + /** + * New sampling interval in microseconds. + */ + interval: number; + } + interface StartPreciseCoverageParameterType { + /** + * Collect accurate call counts beyond simple 'covered' or 'not covered'. + */ + callCount?: boolean | undefined; + /** + * Collect block-based coverage. + */ + detailed?: boolean | undefined; + } + interface StopReturnType { + /** + * Recorded profile. + */ + profile: Profile; + } + interface TakePreciseCoverageReturnType { + /** + * Coverage data for the current isolate. + */ + result: ScriptCoverage[]; + } + interface GetBestEffortCoverageReturnType { + /** + * Coverage data for the current isolate. + */ + result: ScriptCoverage[]; + } + interface TakeTypeProfileReturnType { + /** + * Type profile for all scripts since startTypeProfile() was turned on. + */ + result: ScriptTypeProfile[]; + } + interface ConsoleProfileStartedEventDataType { + id: string; + /** + * Location of console.profile(). + */ + location: Debugger.Location; + /** + * Profile title passed as an argument to console.profile(). + */ + title?: string | undefined; + } + interface ConsoleProfileFinishedEventDataType { + id: string; + /** + * Location of console.profileEnd(). + */ + location: Debugger.Location; + profile: Profile; + /** + * Profile title passed as an argument to console.profile(). + */ + title?: string | undefined; + } + } + namespace HeapProfiler { + /** + * Heap snapshot object id. + */ + type HeapSnapshotObjectId = string; + /** + * Sampling Heap Profile node. Holds callsite information, allocation statistics and child nodes. + */ + interface SamplingHeapProfileNode { + /** + * Function location. + */ + callFrame: Runtime.CallFrame; + /** + * Allocations size in bytes for the node excluding children. + */ + selfSize: number; + /** + * Child nodes. + */ + children: SamplingHeapProfileNode[]; + } + /** + * Profile. + */ + interface SamplingHeapProfile { + head: SamplingHeapProfileNode; + } + interface StartTrackingHeapObjectsParameterType { + trackAllocations?: boolean | undefined; + } + interface StopTrackingHeapObjectsParameterType { + /** + * If true 'reportHeapSnapshotProgress' events will be generated while snapshot is being taken when the tracking is stopped. + */ + reportProgress?: boolean | undefined; + } + interface TakeHeapSnapshotParameterType { + /** + * If true 'reportHeapSnapshotProgress' events will be generated while snapshot is being taken. + */ + reportProgress?: boolean | undefined; + } + interface GetObjectByHeapObjectIdParameterType { + objectId: HeapSnapshotObjectId; + /** + * Symbolic group name that can be used to release multiple objects. + */ + objectGroup?: string | undefined; + } + interface AddInspectedHeapObjectParameterType { + /** + * Heap snapshot object id to be accessible by means of $x command line API. + */ + heapObjectId: HeapSnapshotObjectId; + } + interface GetHeapObjectIdParameterType { + /** + * Identifier of the object to get heap object id for. + */ + objectId: Runtime.RemoteObjectId; + } + interface StartSamplingParameterType { + /** + * Average sample interval in bytes. Poisson distribution is used for the intervals. The default value is 32768 bytes. + */ + samplingInterval?: number | undefined; + } + interface GetObjectByHeapObjectIdReturnType { + /** + * Evaluation result. + */ + result: Runtime.RemoteObject; + } + interface GetHeapObjectIdReturnType { + /** + * Id of the heap snapshot object corresponding to the passed remote object id. + */ + heapSnapshotObjectId: HeapSnapshotObjectId; + } + interface StopSamplingReturnType { + /** + * Recorded sampling heap profile. + */ + profile: SamplingHeapProfile; + } + interface GetSamplingProfileReturnType { + /** + * Return the sampling profile being collected. + */ + profile: SamplingHeapProfile; + } + interface AddHeapSnapshotChunkEventDataType { + chunk: string; + } + interface ReportHeapSnapshotProgressEventDataType { + done: number; + total: number; + finished?: boolean | undefined; + } + interface LastSeenObjectIdEventDataType { + lastSeenObjectId: number; + timestamp: number; + } + interface HeapStatsUpdateEventDataType { + /** + * An array of triplets. Each triplet describes a fragment. The first integer is the fragment index, the second integer is a total count of objects for the fragment, the third integer is a total size of the objects for the fragment. + */ + statsUpdate: number[]; + } + } + namespace NodeTracing { + interface TraceConfig { + /** + * Controls how the trace buffer stores data. + */ + recordMode?: string | undefined; + /** + * Included category filters. + */ + includedCategories: string[]; + } + interface StartParameterType { + traceConfig: TraceConfig; + } + interface GetCategoriesReturnType { + /** + * A list of supported tracing categories. + */ + categories: string[]; + } + interface DataCollectedEventDataType { + value: Array<{}>; + } + } + namespace NodeWorker { + type WorkerID = string; + /** + * Unique identifier of attached debugging session. + */ + type SessionID = string; + interface WorkerInfo { + workerId: WorkerID; + type: string; + title: string; + url: string; + } + interface SendMessageToWorkerParameterType { + message: string; + /** + * Identifier of the session. + */ + sessionId: SessionID; + } + interface EnableParameterType { + /** + * Whether to new workers should be paused until the frontend sends `Runtime.runIfWaitingForDebugger` + * message to run them. + */ + waitForDebuggerOnStart: boolean; + } + interface DetachParameterType { + sessionId: SessionID; + } + interface AttachedToWorkerEventDataType { + /** + * Identifier assigned to the session used to send/receive messages. + */ + sessionId: SessionID; + workerInfo: WorkerInfo; + waitingForDebugger: boolean; + } + interface DetachedFromWorkerEventDataType { + /** + * Detached session identifier. + */ + sessionId: SessionID; + } + interface ReceivedMessageFromWorkerEventDataType { + /** + * Identifier of a session which sends a message. + */ + sessionId: SessionID; + message: string; + } + } + namespace NodeRuntime { + interface NotifyWhenWaitingForDisconnectParameterType { + enabled: boolean; + } + } + /** + * The `inspector.Session` is used for dispatching messages to the V8 inspector + * back-end and receiving message responses and notifications. + */ + class Session extends EventEmitter { + /** + * Create a new instance of the inspector.Session class. + * The inspector session needs to be connected through session.connect() before the messages can be dispatched to the inspector backend. + */ + constructor(); + /** + * Connects a session to the inspector back-end. + * @since v8.0.0 + */ + connect(): void; + /** + * Immediately close the session. All pending message callbacks will be called + * with an error. `session.connect()` will need to be called to be able to send + * messages again. Reconnected session will lose all inspector state, such as + * enabled agents or configured breakpoints. + * @since v8.0.0 + */ + disconnect(): void; + /** + * Posts a message to the inspector back-end. `callback` will be notified when + * a response is received. `callback` is a function that accepts two optional + * arguments: error and message-specific result. + * + * ```js + * session.post('Runtime.evaluate', { expression: '2 + 2' }, + * (error, { result }) => console.log(result)); + * // Output: { type: 'number', value: 4, description: '4' } + * ``` + * + * The latest version of the V8 inspector protocol is published on the [Chrome DevTools Protocol Viewer](https://chromedevtools.github.io/devtools-protocol/v8/). + * + * Node.js inspector supports all the Chrome DevTools Protocol domains declared + * by V8\. Chrome DevTools Protocol domain provides an interface for interacting + * with one of the runtime agents used to inspect the application state and listen + * to the run-time events. + * + * ## Example usage + * + * Apart from the debugger, various V8 Profilers are available through the DevTools + * protocol. + * @since v8.0.0 + */ + post(method: string, params?: {}, callback?: (err: Error | null, params?: {}) => void): void; + post(method: string, callback?: (err: Error | null, params?: {}) => void): void; + /** + * Returns supported domains. + */ + post(method: 'Schema.getDomains', callback?: (err: Error | null, params: Schema.GetDomainsReturnType) => void): void; + /** + * Evaluates expression on global object. + */ + post(method: 'Runtime.evaluate', params?: Runtime.EvaluateParameterType, callback?: (err: Error | null, params: Runtime.EvaluateReturnType) => void): void; + post(method: 'Runtime.evaluate', callback?: (err: Error | null, params: Runtime.EvaluateReturnType) => void): void; + /** + * Add handler to promise with given promise object id. + */ + post(method: 'Runtime.awaitPromise', params?: Runtime.AwaitPromiseParameterType, callback?: (err: Error | null, params: Runtime.AwaitPromiseReturnType) => void): void; + post(method: 'Runtime.awaitPromise', callback?: (err: Error | null, params: Runtime.AwaitPromiseReturnType) => void): void; + /** + * Calls function with given declaration on the given object. Object group of the result is inherited from the target object. + */ + post(method: 'Runtime.callFunctionOn', params?: Runtime.CallFunctionOnParameterType, callback?: (err: Error | null, params: Runtime.CallFunctionOnReturnType) => void): void; + post(method: 'Runtime.callFunctionOn', callback?: (err: Error | null, params: Runtime.CallFunctionOnReturnType) => void): void; + /** + * Returns properties of a given object. Object group of the result is inherited from the target object. + */ + post(method: 'Runtime.getProperties', params?: Runtime.GetPropertiesParameterType, callback?: (err: Error | null, params: Runtime.GetPropertiesReturnType) => void): void; + post(method: 'Runtime.getProperties', callback?: (err: Error | null, params: Runtime.GetPropertiesReturnType) => void): void; + /** + * Releases remote object with given id. + */ + post(method: 'Runtime.releaseObject', params?: Runtime.ReleaseObjectParameterType, callback?: (err: Error | null) => void): void; + post(method: 'Runtime.releaseObject', callback?: (err: Error | null) => void): void; + /** + * Releases all remote objects that belong to a given group. + */ + post(method: 'Runtime.releaseObjectGroup', params?: Runtime.ReleaseObjectGroupParameterType, callback?: (err: Error | null) => void): void; + post(method: 'Runtime.releaseObjectGroup', callback?: (err: Error | null) => void): void; + /** + * Tells inspected instance to run if it was waiting for debugger to attach. + */ + post(method: 'Runtime.runIfWaitingForDebugger', callback?: (err: Error | null) => void): void; + /** + * Enables reporting of execution contexts creation by means of executionContextCreated event. When the reporting gets enabled the event will be sent immediately for each existing execution context. + */ + post(method: 'Runtime.enable', callback?: (err: Error | null) => void): void; + /** + * Disables reporting of execution contexts creation. + */ + post(method: 'Runtime.disable', callback?: (err: Error | null) => void): void; + /** + * Discards collected exceptions and console API calls. + */ + post(method: 'Runtime.discardConsoleEntries', callback?: (err: Error | null) => void): void; + /** + * @experimental + */ + post(method: 'Runtime.setCustomObjectFormatterEnabled', params?: Runtime.SetCustomObjectFormatterEnabledParameterType, callback?: (err: Error | null) => void): void; + post(method: 'Runtime.setCustomObjectFormatterEnabled', callback?: (err: Error | null) => void): void; + /** + * Compiles expression. + */ + post(method: 'Runtime.compileScript', params?: Runtime.CompileScriptParameterType, callback?: (err: Error | null, params: Runtime.CompileScriptReturnType) => void): void; + post(method: 'Runtime.compileScript', callback?: (err: Error | null, params: Runtime.CompileScriptReturnType) => void): void; + /** + * Runs script with given id in a given context. + */ + post(method: 'Runtime.runScript', params?: Runtime.RunScriptParameterType, callback?: (err: Error | null, params: Runtime.RunScriptReturnType) => void): void; + post(method: 'Runtime.runScript', callback?: (err: Error | null, params: Runtime.RunScriptReturnType) => void): void; + post(method: 'Runtime.queryObjects', params?: Runtime.QueryObjectsParameterType, callback?: (err: Error | null, params: Runtime.QueryObjectsReturnType) => void): void; + post(method: 'Runtime.queryObjects', callback?: (err: Error | null, params: Runtime.QueryObjectsReturnType) => void): void; + /** + * Returns all let, const and class variables from global scope. + */ + post( + method: 'Runtime.globalLexicalScopeNames', + params?: Runtime.GlobalLexicalScopeNamesParameterType, + callback?: (err: Error | null, params: Runtime.GlobalLexicalScopeNamesReturnType) => void + ): void; + post(method: 'Runtime.globalLexicalScopeNames', callback?: (err: Error | null, params: Runtime.GlobalLexicalScopeNamesReturnType) => void): void; + /** + * Enables debugger for the given page. Clients should not assume that the debugging has been enabled until the result for this command is received. + */ + post(method: 'Debugger.enable', callback?: (err: Error | null, params: Debugger.EnableReturnType) => void): void; + /** + * Disables debugger for given page. + */ + post(method: 'Debugger.disable', callback?: (err: Error | null) => void): void; + /** + * Activates / deactivates all breakpoints on the page. + */ + post(method: 'Debugger.setBreakpointsActive', params?: Debugger.SetBreakpointsActiveParameterType, callback?: (err: Error | null) => void): void; + post(method: 'Debugger.setBreakpointsActive', callback?: (err: Error | null) => void): void; + /** + * Makes page not interrupt on any pauses (breakpoint, exception, dom exception etc). + */ + post(method: 'Debugger.setSkipAllPauses', params?: Debugger.SetSkipAllPausesParameterType, callback?: (err: Error | null) => void): void; + post(method: 'Debugger.setSkipAllPauses', callback?: (err: Error | null) => void): void; + /** + * Sets JavaScript breakpoint at given location specified either by URL or URL regex. Once this command is issued, all existing parsed scripts will have breakpoints resolved and returned in locations property. Further matching script parsing will result in subsequent breakpointResolved events issued. This logical breakpoint will survive page reloads. + */ + post(method: 'Debugger.setBreakpointByUrl', params?: Debugger.SetBreakpointByUrlParameterType, callback?: (err: Error | null, params: Debugger.SetBreakpointByUrlReturnType) => void): void; + post(method: 'Debugger.setBreakpointByUrl', callback?: (err: Error | null, params: Debugger.SetBreakpointByUrlReturnType) => void): void; + /** + * Sets JavaScript breakpoint at a given location. + */ + post(method: 'Debugger.setBreakpoint', params?: Debugger.SetBreakpointParameterType, callback?: (err: Error | null, params: Debugger.SetBreakpointReturnType) => void): void; + post(method: 'Debugger.setBreakpoint', callback?: (err: Error | null, params: Debugger.SetBreakpointReturnType) => void): void; + /** + * Removes JavaScript breakpoint. + */ + post(method: 'Debugger.removeBreakpoint', params?: Debugger.RemoveBreakpointParameterType, callback?: (err: Error | null) => void): void; + post(method: 'Debugger.removeBreakpoint', callback?: (err: Error | null) => void): void; + /** + * Returns possible locations for breakpoint. scriptId in start and end range locations should be the same. + */ + post( + method: 'Debugger.getPossibleBreakpoints', + params?: Debugger.GetPossibleBreakpointsParameterType, + callback?: (err: Error | null, params: Debugger.GetPossibleBreakpointsReturnType) => void + ): void; + post(method: 'Debugger.getPossibleBreakpoints', callback?: (err: Error | null, params: Debugger.GetPossibleBreakpointsReturnType) => void): void; + /** + * Continues execution until specific location is reached. + */ + post(method: 'Debugger.continueToLocation', params?: Debugger.ContinueToLocationParameterType, callback?: (err: Error | null) => void): void; + post(method: 'Debugger.continueToLocation', callback?: (err: Error | null) => void): void; + /** + * @experimental + */ + post(method: 'Debugger.pauseOnAsyncCall', params?: Debugger.PauseOnAsyncCallParameterType, callback?: (err: Error | null) => void): void; + post(method: 'Debugger.pauseOnAsyncCall', callback?: (err: Error | null) => void): void; + /** + * Steps over the statement. + */ + post(method: 'Debugger.stepOver', callback?: (err: Error | null) => void): void; + /** + * Steps into the function call. + */ + post(method: 'Debugger.stepInto', params?: Debugger.StepIntoParameterType, callback?: (err: Error | null) => void): void; + post(method: 'Debugger.stepInto', callback?: (err: Error | null) => void): void; + /** + * Steps out of the function call. + */ + post(method: 'Debugger.stepOut', callback?: (err: Error | null) => void): void; + /** + * Stops on the next JavaScript statement. + */ + post(method: 'Debugger.pause', callback?: (err: Error | null) => void): void; + /** + * This method is deprecated - use Debugger.stepInto with breakOnAsyncCall and Debugger.pauseOnAsyncTask instead. Steps into next scheduled async task if any is scheduled before next pause. Returns success when async task is actually scheduled, returns error if no task were scheduled or another scheduleStepIntoAsync was called. + * @experimental + */ + post(method: 'Debugger.scheduleStepIntoAsync', callback?: (err: Error | null) => void): void; + /** + * Resumes JavaScript execution. + */ + post(method: 'Debugger.resume', callback?: (err: Error | null) => void): void; + /** + * Returns stack trace with given stackTraceId. + * @experimental + */ + post(method: 'Debugger.getStackTrace', params?: Debugger.GetStackTraceParameterType, callback?: (err: Error | null, params: Debugger.GetStackTraceReturnType) => void): void; + post(method: 'Debugger.getStackTrace', callback?: (err: Error | null, params: Debugger.GetStackTraceReturnType) => void): void; + /** + * Searches for given string in script content. + */ + post(method: 'Debugger.searchInContent', params?: Debugger.SearchInContentParameterType, callback?: (err: Error | null, params: Debugger.SearchInContentReturnType) => void): void; + post(method: 'Debugger.searchInContent', callback?: (err: Error | null, params: Debugger.SearchInContentReturnType) => void): void; + /** + * Edits JavaScript source live. + */ + post(method: 'Debugger.setScriptSource', params?: Debugger.SetScriptSourceParameterType, callback?: (err: Error | null, params: Debugger.SetScriptSourceReturnType) => void): void; + post(method: 'Debugger.setScriptSource', callback?: (err: Error | null, params: Debugger.SetScriptSourceReturnType) => void): void; + /** + * Restarts particular call frame from the beginning. + */ + post(method: 'Debugger.restartFrame', params?: Debugger.RestartFrameParameterType, callback?: (err: Error | null, params: Debugger.RestartFrameReturnType) => void): void; + post(method: 'Debugger.restartFrame', callback?: (err: Error | null, params: Debugger.RestartFrameReturnType) => void): void; + /** + * Returns source for the script with given id. + */ + post(method: 'Debugger.getScriptSource', params?: Debugger.GetScriptSourceParameterType, callback?: (err: Error | null, params: Debugger.GetScriptSourceReturnType) => void): void; + post(method: 'Debugger.getScriptSource', callback?: (err: Error | null, params: Debugger.GetScriptSourceReturnType) => void): void; + /** + * Defines pause on exceptions state. Can be set to stop on all exceptions, uncaught exceptions or no exceptions. Initial pause on exceptions state is none. + */ + post(method: 'Debugger.setPauseOnExceptions', params?: Debugger.SetPauseOnExceptionsParameterType, callback?: (err: Error | null) => void): void; + post(method: 'Debugger.setPauseOnExceptions', callback?: (err: Error | null) => void): void; + /** + * Evaluates expression on a given call frame. + */ + post(method: 'Debugger.evaluateOnCallFrame', params?: Debugger.EvaluateOnCallFrameParameterType, callback?: (err: Error | null, params: Debugger.EvaluateOnCallFrameReturnType) => void): void; + post(method: 'Debugger.evaluateOnCallFrame', callback?: (err: Error | null, params: Debugger.EvaluateOnCallFrameReturnType) => void): void; + /** + * Changes value of variable in a callframe. Object-based scopes are not supported and must be mutated manually. + */ + post(method: 'Debugger.setVariableValue', params?: Debugger.SetVariableValueParameterType, callback?: (err: Error | null) => void): void; + post(method: 'Debugger.setVariableValue', callback?: (err: Error | null) => void): void; + /** + * Changes return value in top frame. Available only at return break position. + * @experimental + */ + post(method: 'Debugger.setReturnValue', params?: Debugger.SetReturnValueParameterType, callback?: (err: Error | null) => void): void; + post(method: 'Debugger.setReturnValue', callback?: (err: Error | null) => void): void; + /** + * Enables or disables async call stacks tracking. + */ + post(method: 'Debugger.setAsyncCallStackDepth', params?: Debugger.SetAsyncCallStackDepthParameterType, callback?: (err: Error | null) => void): void; + post(method: 'Debugger.setAsyncCallStackDepth', callback?: (err: Error | null) => void): void; + /** + * Replace previous blackbox patterns with passed ones. Forces backend to skip stepping/pausing in scripts with url matching one of the patterns. VM will try to leave blackboxed script by performing 'step in' several times, finally resorting to 'step out' if unsuccessful. + * @experimental + */ + post(method: 'Debugger.setBlackboxPatterns', params?: Debugger.SetBlackboxPatternsParameterType, callback?: (err: Error | null) => void): void; + post(method: 'Debugger.setBlackboxPatterns', callback?: (err: Error | null) => void): void; + /** + * Makes backend skip steps in the script in blackboxed ranges. VM will try leave blacklisted scripts by performing 'step in' several times, finally resorting to 'step out' if unsuccessful. Positions array contains positions where blackbox state is changed. First interval isn't blackboxed. Array should be sorted. + * @experimental + */ + post(method: 'Debugger.setBlackboxedRanges', params?: Debugger.SetBlackboxedRangesParameterType, callback?: (err: Error | null) => void): void; + post(method: 'Debugger.setBlackboxedRanges', callback?: (err: Error | null) => void): void; + /** + * Enables console domain, sends the messages collected so far to the client by means of the messageAdded notification. + */ + post(method: 'Console.enable', callback?: (err: Error | null) => void): void; + /** + * Disables console domain, prevents further console messages from being reported to the client. + */ + post(method: 'Console.disable', callback?: (err: Error | null) => void): void; + /** + * Does nothing. + */ + post(method: 'Console.clearMessages', callback?: (err: Error | null) => void): void; + post(method: 'Profiler.enable', callback?: (err: Error | null) => void): void; + post(method: 'Profiler.disable', callback?: (err: Error | null) => void): void; + /** + * Changes CPU profiler sampling interval. Must be called before CPU profiles recording started. + */ + post(method: 'Profiler.setSamplingInterval', params?: Profiler.SetSamplingIntervalParameterType, callback?: (err: Error | null) => void): void; + post(method: 'Profiler.setSamplingInterval', callback?: (err: Error | null) => void): void; + post(method: 'Profiler.start', callback?: (err: Error | null) => void): void; + post(method: 'Profiler.stop', callback?: (err: Error | null, params: Profiler.StopReturnType) => void): void; + /** + * Enable precise code coverage. Coverage data for JavaScript executed before enabling precise code coverage may be incomplete. Enabling prevents running optimized code and resets execution counters. + */ + post(method: 'Profiler.startPreciseCoverage', params?: Profiler.StartPreciseCoverageParameterType, callback?: (err: Error | null) => void): void; + post(method: 'Profiler.startPreciseCoverage', callback?: (err: Error | null) => void): void; + /** + * Disable precise code coverage. Disabling releases unnecessary execution count records and allows executing optimized code. + */ + post(method: 'Profiler.stopPreciseCoverage', callback?: (err: Error | null) => void): void; + /** + * Collect coverage data for the current isolate, and resets execution counters. Precise code coverage needs to have started. + */ + post(method: 'Profiler.takePreciseCoverage', callback?: (err: Error | null, params: Profiler.TakePreciseCoverageReturnType) => void): void; + /** + * Collect coverage data for the current isolate. The coverage data may be incomplete due to garbage collection. + */ + post(method: 'Profiler.getBestEffortCoverage', callback?: (err: Error | null, params: Profiler.GetBestEffortCoverageReturnType) => void): void; + /** + * Enable type profile. + * @experimental + */ + post(method: 'Profiler.startTypeProfile', callback?: (err: Error | null) => void): void; + /** + * Disable type profile. Disabling releases type profile data collected so far. + * @experimental + */ + post(method: 'Profiler.stopTypeProfile', callback?: (err: Error | null) => void): void; + /** + * Collect type profile. + * @experimental + */ + post(method: 'Profiler.takeTypeProfile', callback?: (err: Error | null, params: Profiler.TakeTypeProfileReturnType) => void): void; + post(method: 'HeapProfiler.enable', callback?: (err: Error | null) => void): void; + post(method: 'HeapProfiler.disable', callback?: (err: Error | null) => void): void; + post(method: 'HeapProfiler.startTrackingHeapObjects', params?: HeapProfiler.StartTrackingHeapObjectsParameterType, callback?: (err: Error | null) => void): void; + post(method: 'HeapProfiler.startTrackingHeapObjects', callback?: (err: Error | null) => void): void; + post(method: 'HeapProfiler.stopTrackingHeapObjects', params?: HeapProfiler.StopTrackingHeapObjectsParameterType, callback?: (err: Error | null) => void): void; + post(method: 'HeapProfiler.stopTrackingHeapObjects', callback?: (err: Error | null) => void): void; + post(method: 'HeapProfiler.takeHeapSnapshot', params?: HeapProfiler.TakeHeapSnapshotParameterType, callback?: (err: Error | null) => void): void; + post(method: 'HeapProfiler.takeHeapSnapshot', callback?: (err: Error | null) => void): void; + post(method: 'HeapProfiler.collectGarbage', callback?: (err: Error | null) => void): void; + post( + method: 'HeapProfiler.getObjectByHeapObjectId', + params?: HeapProfiler.GetObjectByHeapObjectIdParameterType, + callback?: (err: Error | null, params: HeapProfiler.GetObjectByHeapObjectIdReturnType) => void + ): void; + post(method: 'HeapProfiler.getObjectByHeapObjectId', callback?: (err: Error | null, params: HeapProfiler.GetObjectByHeapObjectIdReturnType) => void): void; + /** + * Enables console to refer to the node with given id via $x (see Command Line API for more details $x functions). + */ + post(method: 'HeapProfiler.addInspectedHeapObject', params?: HeapProfiler.AddInspectedHeapObjectParameterType, callback?: (err: Error | null) => void): void; + post(method: 'HeapProfiler.addInspectedHeapObject', callback?: (err: Error | null) => void): void; + post(method: 'HeapProfiler.getHeapObjectId', params?: HeapProfiler.GetHeapObjectIdParameterType, callback?: (err: Error | null, params: HeapProfiler.GetHeapObjectIdReturnType) => void): void; + post(method: 'HeapProfiler.getHeapObjectId', callback?: (err: Error | null, params: HeapProfiler.GetHeapObjectIdReturnType) => void): void; + post(method: 'HeapProfiler.startSampling', params?: HeapProfiler.StartSamplingParameterType, callback?: (err: Error | null) => void): void; + post(method: 'HeapProfiler.startSampling', callback?: (err: Error | null) => void): void; + post(method: 'HeapProfiler.stopSampling', callback?: (err: Error | null, params: HeapProfiler.StopSamplingReturnType) => void): void; + post(method: 'HeapProfiler.getSamplingProfile', callback?: (err: Error | null, params: HeapProfiler.GetSamplingProfileReturnType) => void): void; + /** + * Gets supported tracing categories. + */ + post(method: 'NodeTracing.getCategories', callback?: (err: Error | null, params: NodeTracing.GetCategoriesReturnType) => void): void; + /** + * Start trace events collection. + */ + post(method: 'NodeTracing.start', params?: NodeTracing.StartParameterType, callback?: (err: Error | null) => void): void; + post(method: 'NodeTracing.start', callback?: (err: Error | null) => void): void; + /** + * Stop trace events collection. Remaining collected events will be sent as a sequence of + * dataCollected events followed by tracingComplete event. + */ + post(method: 'NodeTracing.stop', callback?: (err: Error | null) => void): void; + /** + * Sends protocol message over session with given id. + */ + post(method: 'NodeWorker.sendMessageToWorker', params?: NodeWorker.SendMessageToWorkerParameterType, callback?: (err: Error | null) => void): void; + post(method: 'NodeWorker.sendMessageToWorker', callback?: (err: Error | null) => void): void; + /** + * Instructs the inspector to attach to running workers. Will also attach to new workers + * as they start + */ + post(method: 'NodeWorker.enable', params?: NodeWorker.EnableParameterType, callback?: (err: Error | null) => void): void; + post(method: 'NodeWorker.enable', callback?: (err: Error | null) => void): void; + /** + * Detaches from all running workers and disables attaching to new workers as they are started. + */ + post(method: 'NodeWorker.disable', callback?: (err: Error | null) => void): void; + /** + * Detached from the worker with given sessionId. + */ + post(method: 'NodeWorker.detach', params?: NodeWorker.DetachParameterType, callback?: (err: Error | null) => void): void; + post(method: 'NodeWorker.detach', callback?: (err: Error | null) => void): void; + /** + * Enable the `NodeRuntime.waitingForDisconnect`. + */ + post(method: 'NodeRuntime.notifyWhenWaitingForDisconnect', params?: NodeRuntime.NotifyWhenWaitingForDisconnectParameterType, callback?: (err: Error | null) => void): void; + post(method: 'NodeRuntime.notifyWhenWaitingForDisconnect', callback?: (err: Error | null) => void): void; + // Events + addListener(event: string, listener: (...args: any[]) => void): this; + /** + * Emitted when any notification from the V8 Inspector is received. + */ + addListener(event: 'inspectorNotification', listener: (message: InspectorNotification<{}>) => void): this; + /** + * Issued when new execution context is created. + */ + addListener(event: 'Runtime.executionContextCreated', listener: (message: InspectorNotification) => void): this; + /** + * Issued when execution context is destroyed. + */ + addListener(event: 'Runtime.executionContextDestroyed', listener: (message: InspectorNotification) => void): this; + /** + * Issued when all executionContexts were cleared in browser + */ + addListener(event: 'Runtime.executionContextsCleared', listener: () => void): this; + /** + * Issued when exception was thrown and unhandled. + */ + addListener(event: 'Runtime.exceptionThrown', listener: (message: InspectorNotification) => void): this; + /** + * Issued when unhandled exception was revoked. + */ + addListener(event: 'Runtime.exceptionRevoked', listener: (message: InspectorNotification) => void): this; + /** + * Issued when console API was called. + */ + addListener(event: 'Runtime.consoleAPICalled', listener: (message: InspectorNotification) => void): this; + /** + * Issued when object should be inspected (for example, as a result of inspect() command line API call). + */ + addListener(event: 'Runtime.inspectRequested', listener: (message: InspectorNotification) => void): this; + /** + * Fired when virtual machine parses script. This event is also fired for all known and uncollected scripts upon enabling debugger. + */ + addListener(event: 'Debugger.scriptParsed', listener: (message: InspectorNotification) => void): this; + /** + * Fired when virtual machine fails to parse the script. + */ + addListener(event: 'Debugger.scriptFailedToParse', listener: (message: InspectorNotification) => void): this; + /** + * Fired when breakpoint is resolved to an actual script and location. + */ + addListener(event: 'Debugger.breakpointResolved', listener: (message: InspectorNotification) => void): this; + /** + * Fired when the virtual machine stopped on breakpoint or exception or any other stop criteria. + */ + addListener(event: 'Debugger.paused', listener: (message: InspectorNotification) => void): this; + /** + * Fired when the virtual machine resumed execution. + */ + addListener(event: 'Debugger.resumed', listener: () => void): this; + /** + * Issued when new console message is added. + */ + addListener(event: 'Console.messageAdded', listener: (message: InspectorNotification) => void): this; + /** + * Sent when new profile recording is started using console.profile() call. + */ + addListener(event: 'Profiler.consoleProfileStarted', listener: (message: InspectorNotification) => void): this; + addListener(event: 'Profiler.consoleProfileFinished', listener: (message: InspectorNotification) => void): this; + addListener(event: 'HeapProfiler.addHeapSnapshotChunk', listener: (message: InspectorNotification) => void): this; + addListener(event: 'HeapProfiler.resetProfiles', listener: () => void): this; + addListener(event: 'HeapProfiler.reportHeapSnapshotProgress', listener: (message: InspectorNotification) => void): this; + /** + * If heap objects tracking has been started then backend regularly sends a current value for last seen object id and corresponding timestamp. If the were changes in the heap since last event then one or more heapStatsUpdate events will be sent before a new lastSeenObjectId event. + */ + addListener(event: 'HeapProfiler.lastSeenObjectId', listener: (message: InspectorNotification) => void): this; + /** + * If heap objects tracking has been started then backend may send update for one or more fragments + */ + addListener(event: 'HeapProfiler.heapStatsUpdate', listener: (message: InspectorNotification) => void): this; + /** + * Contains an bucket of collected trace events. + */ + addListener(event: 'NodeTracing.dataCollected', listener: (message: InspectorNotification) => void): this; + /** + * Signals that tracing is stopped and there is no trace buffers pending flush, all data were + * delivered via dataCollected events. + */ + addListener(event: 'NodeTracing.tracingComplete', listener: () => void): this; + /** + * Issued when attached to a worker. + */ + addListener(event: 'NodeWorker.attachedToWorker', listener: (message: InspectorNotification) => void): this; + /** + * Issued when detached from the worker. + */ + addListener(event: 'NodeWorker.detachedFromWorker', listener: (message: InspectorNotification) => void): this; + /** + * Notifies about a new protocol message received from the session + * (session ID is provided in attachedToWorker notification). + */ + addListener(event: 'NodeWorker.receivedMessageFromWorker', listener: (message: InspectorNotification) => void): this; + /** + * This event is fired instead of `Runtime.executionContextDestroyed` when + * enabled. + * It is fired when the Node process finished all code execution and is + * waiting for all frontends to disconnect. + */ + addListener(event: 'NodeRuntime.waitingForDisconnect', listener: () => void): this; + emit(event: string | symbol, ...args: any[]): boolean; + emit(event: 'inspectorNotification', message: InspectorNotification<{}>): boolean; + emit(event: 'Runtime.executionContextCreated', message: InspectorNotification): boolean; + emit(event: 'Runtime.executionContextDestroyed', message: InspectorNotification): boolean; + emit(event: 'Runtime.executionContextsCleared'): boolean; + emit(event: 'Runtime.exceptionThrown', message: InspectorNotification): boolean; + emit(event: 'Runtime.exceptionRevoked', message: InspectorNotification): boolean; + emit(event: 'Runtime.consoleAPICalled', message: InspectorNotification): boolean; + emit(event: 'Runtime.inspectRequested', message: InspectorNotification): boolean; + emit(event: 'Debugger.scriptParsed', message: InspectorNotification): boolean; + emit(event: 'Debugger.scriptFailedToParse', message: InspectorNotification): boolean; + emit(event: 'Debugger.breakpointResolved', message: InspectorNotification): boolean; + emit(event: 'Debugger.paused', message: InspectorNotification): boolean; + emit(event: 'Debugger.resumed'): boolean; + emit(event: 'Console.messageAdded', message: InspectorNotification): boolean; + emit(event: 'Profiler.consoleProfileStarted', message: InspectorNotification): boolean; + emit(event: 'Profiler.consoleProfileFinished', message: InspectorNotification): boolean; + emit(event: 'HeapProfiler.addHeapSnapshotChunk', message: InspectorNotification): boolean; + emit(event: 'HeapProfiler.resetProfiles'): boolean; + emit(event: 'HeapProfiler.reportHeapSnapshotProgress', message: InspectorNotification): boolean; + emit(event: 'HeapProfiler.lastSeenObjectId', message: InspectorNotification): boolean; + emit(event: 'HeapProfiler.heapStatsUpdate', message: InspectorNotification): boolean; + emit(event: 'NodeTracing.dataCollected', message: InspectorNotification): boolean; + emit(event: 'NodeTracing.tracingComplete'): boolean; + emit(event: 'NodeWorker.attachedToWorker', message: InspectorNotification): boolean; + emit(event: 'NodeWorker.detachedFromWorker', message: InspectorNotification): boolean; + emit(event: 'NodeWorker.receivedMessageFromWorker', message: InspectorNotification): boolean; + emit(event: 'NodeRuntime.waitingForDisconnect'): boolean; + on(event: string, listener: (...args: any[]) => void): this; + /** + * Emitted when any notification from the V8 Inspector is received. + */ + on(event: 'inspectorNotification', listener: (message: InspectorNotification<{}>) => void): this; + /** + * Issued when new execution context is created. + */ + on(event: 'Runtime.executionContextCreated', listener: (message: InspectorNotification) => void): this; + /** + * Issued when execution context is destroyed. + */ + on(event: 'Runtime.executionContextDestroyed', listener: (message: InspectorNotification) => void): this; + /** + * Issued when all executionContexts were cleared in browser + */ + on(event: 'Runtime.executionContextsCleared', listener: () => void): this; + /** + * Issued when exception was thrown and unhandled. + */ + on(event: 'Runtime.exceptionThrown', listener: (message: InspectorNotification) => void): this; + /** + * Issued when unhandled exception was revoked. + */ + on(event: 'Runtime.exceptionRevoked', listener: (message: InspectorNotification) => void): this; + /** + * Issued when console API was called. + */ + on(event: 'Runtime.consoleAPICalled', listener: (message: InspectorNotification) => void): this; + /** + * Issued when object should be inspected (for example, as a result of inspect() command line API call). + */ + on(event: 'Runtime.inspectRequested', listener: (message: InspectorNotification) => void): this; + /** + * Fired when virtual machine parses script. This event is also fired for all known and uncollected scripts upon enabling debugger. + */ + on(event: 'Debugger.scriptParsed', listener: (message: InspectorNotification) => void): this; + /** + * Fired when virtual machine fails to parse the script. + */ + on(event: 'Debugger.scriptFailedToParse', listener: (message: InspectorNotification) => void): this; + /** + * Fired when breakpoint is resolved to an actual script and location. + */ + on(event: 'Debugger.breakpointResolved', listener: (message: InspectorNotification) => void): this; + /** + * Fired when the virtual machine stopped on breakpoint or exception or any other stop criteria. + */ + on(event: 'Debugger.paused', listener: (message: InspectorNotification) => void): this; + /** + * Fired when the virtual machine resumed execution. + */ + on(event: 'Debugger.resumed', listener: () => void): this; + /** + * Issued when new console message is added. + */ + on(event: 'Console.messageAdded', listener: (message: InspectorNotification) => void): this; + /** + * Sent when new profile recording is started using console.profile() call. + */ + on(event: 'Profiler.consoleProfileStarted', listener: (message: InspectorNotification) => void): this; + on(event: 'Profiler.consoleProfileFinished', listener: (message: InspectorNotification) => void): this; + on(event: 'HeapProfiler.addHeapSnapshotChunk', listener: (message: InspectorNotification) => void): this; + on(event: 'HeapProfiler.resetProfiles', listener: () => void): this; + on(event: 'HeapProfiler.reportHeapSnapshotProgress', listener: (message: InspectorNotification) => void): this; + /** + * If heap objects tracking has been started then backend regularly sends a current value for last seen object id and corresponding timestamp. If the were changes in the heap since last event then one or more heapStatsUpdate events will be sent before a new lastSeenObjectId event. + */ + on(event: 'HeapProfiler.lastSeenObjectId', listener: (message: InspectorNotification) => void): this; + /** + * If heap objects tracking has been started then backend may send update for one or more fragments + */ + on(event: 'HeapProfiler.heapStatsUpdate', listener: (message: InspectorNotification) => void): this; + /** + * Contains an bucket of collected trace events. + */ + on(event: 'NodeTracing.dataCollected', listener: (message: InspectorNotification) => void): this; + /** + * Signals that tracing is stopped and there is no trace buffers pending flush, all data were + * delivered via dataCollected events. + */ + on(event: 'NodeTracing.tracingComplete', listener: () => void): this; + /** + * Issued when attached to a worker. + */ + on(event: 'NodeWorker.attachedToWorker', listener: (message: InspectorNotification) => void): this; + /** + * Issued when detached from the worker. + */ + on(event: 'NodeWorker.detachedFromWorker', listener: (message: InspectorNotification) => void): this; + /** + * Notifies about a new protocol message received from the session + * (session ID is provided in attachedToWorker notification). + */ + on(event: 'NodeWorker.receivedMessageFromWorker', listener: (message: InspectorNotification) => void): this; + /** + * This event is fired instead of `Runtime.executionContextDestroyed` when + * enabled. + * It is fired when the Node process finished all code execution and is + * waiting for all frontends to disconnect. + */ + on(event: 'NodeRuntime.waitingForDisconnect', listener: () => void): this; + once(event: string, listener: (...args: any[]) => void): this; + /** + * Emitted when any notification from the V8 Inspector is received. + */ + once(event: 'inspectorNotification', listener: (message: InspectorNotification<{}>) => void): this; + /** + * Issued when new execution context is created. + */ + once(event: 'Runtime.executionContextCreated', listener: (message: InspectorNotification) => void): this; + /** + * Issued when execution context is destroyed. + */ + once(event: 'Runtime.executionContextDestroyed', listener: (message: InspectorNotification) => void): this; + /** + * Issued when all executionContexts were cleared in browser + */ + once(event: 'Runtime.executionContextsCleared', listener: () => void): this; + /** + * Issued when exception was thrown and unhandled. + */ + once(event: 'Runtime.exceptionThrown', listener: (message: InspectorNotification) => void): this; + /** + * Issued when unhandled exception was revoked. + */ + once(event: 'Runtime.exceptionRevoked', listener: (message: InspectorNotification) => void): this; + /** + * Issued when console API was called. + */ + once(event: 'Runtime.consoleAPICalled', listener: (message: InspectorNotification) => void): this; + /** + * Issued when object should be inspected (for example, as a result of inspect() command line API call). + */ + once(event: 'Runtime.inspectRequested', listener: (message: InspectorNotification) => void): this; + /** + * Fired when virtual machine parses script. This event is also fired for all known and uncollected scripts upon enabling debugger. + */ + once(event: 'Debugger.scriptParsed', listener: (message: InspectorNotification) => void): this; + /** + * Fired when virtual machine fails to parse the script. + */ + once(event: 'Debugger.scriptFailedToParse', listener: (message: InspectorNotification) => void): this; + /** + * Fired when breakpoint is resolved to an actual script and location. + */ + once(event: 'Debugger.breakpointResolved', listener: (message: InspectorNotification) => void): this; + /** + * Fired when the virtual machine stopped on breakpoint or exception or any other stop criteria. + */ + once(event: 'Debugger.paused', listener: (message: InspectorNotification) => void): this; + /** + * Fired when the virtual machine resumed execution. + */ + once(event: 'Debugger.resumed', listener: () => void): this; + /** + * Issued when new console message is added. + */ + once(event: 'Console.messageAdded', listener: (message: InspectorNotification) => void): this; + /** + * Sent when new profile recording is started using console.profile() call. + */ + once(event: 'Profiler.consoleProfileStarted', listener: (message: InspectorNotification) => void): this; + once(event: 'Profiler.consoleProfileFinished', listener: (message: InspectorNotification) => void): this; + once(event: 'HeapProfiler.addHeapSnapshotChunk', listener: (message: InspectorNotification) => void): this; + once(event: 'HeapProfiler.resetProfiles', listener: () => void): this; + once(event: 'HeapProfiler.reportHeapSnapshotProgress', listener: (message: InspectorNotification) => void): this; + /** + * If heap objects tracking has been started then backend regularly sends a current value for last seen object id and corresponding timestamp. If the were changes in the heap since last event then one or more heapStatsUpdate events will be sent before a new lastSeenObjectId event. + */ + once(event: 'HeapProfiler.lastSeenObjectId', listener: (message: InspectorNotification) => void): this; + /** + * If heap objects tracking has been started then backend may send update for one or more fragments + */ + once(event: 'HeapProfiler.heapStatsUpdate', listener: (message: InspectorNotification) => void): this; + /** + * Contains an bucket of collected trace events. + */ + once(event: 'NodeTracing.dataCollected', listener: (message: InspectorNotification) => void): this; + /** + * Signals that tracing is stopped and there is no trace buffers pending flush, all data were + * delivered via dataCollected events. + */ + once(event: 'NodeTracing.tracingComplete', listener: () => void): this; + /** + * Issued when attached to a worker. + */ + once(event: 'NodeWorker.attachedToWorker', listener: (message: InspectorNotification) => void): this; + /** + * Issued when detached from the worker. + */ + once(event: 'NodeWorker.detachedFromWorker', listener: (message: InspectorNotification) => void): this; + /** + * Notifies about a new protocol message received from the session + * (session ID is provided in attachedToWorker notification). + */ + once(event: 'NodeWorker.receivedMessageFromWorker', listener: (message: InspectorNotification) => void): this; + /** + * This event is fired instead of `Runtime.executionContextDestroyed` when + * enabled. + * It is fired when the Node process finished all code execution and is + * waiting for all frontends to disconnect. + */ + once(event: 'NodeRuntime.waitingForDisconnect', listener: () => void): this; + prependListener(event: string, listener: (...args: any[]) => void): this; + /** + * Emitted when any notification from the V8 Inspector is received. + */ + prependListener(event: 'inspectorNotification', listener: (message: InspectorNotification<{}>) => void): this; + /** + * Issued when new execution context is created. + */ + prependListener(event: 'Runtime.executionContextCreated', listener: (message: InspectorNotification) => void): this; + /** + * Issued when execution context is destroyed. + */ + prependListener(event: 'Runtime.executionContextDestroyed', listener: (message: InspectorNotification) => void): this; + /** + * Issued when all executionContexts were cleared in browser + */ + prependListener(event: 'Runtime.executionContextsCleared', listener: () => void): this; + /** + * Issued when exception was thrown and unhandled. + */ + prependListener(event: 'Runtime.exceptionThrown', listener: (message: InspectorNotification) => void): this; + /** + * Issued when unhandled exception was revoked. + */ + prependListener(event: 'Runtime.exceptionRevoked', listener: (message: InspectorNotification) => void): this; + /** + * Issued when console API was called. + */ + prependListener(event: 'Runtime.consoleAPICalled', listener: (message: InspectorNotification) => void): this; + /** + * Issued when object should be inspected (for example, as a result of inspect() command line API call). + */ + prependListener(event: 'Runtime.inspectRequested', listener: (message: InspectorNotification) => void): this; + /** + * Fired when virtual machine parses script. This event is also fired for all known and uncollected scripts upon enabling debugger. + */ + prependListener(event: 'Debugger.scriptParsed', listener: (message: InspectorNotification) => void): this; + /** + * Fired when virtual machine fails to parse the script. + */ + prependListener(event: 'Debugger.scriptFailedToParse', listener: (message: InspectorNotification) => void): this; + /** + * Fired when breakpoint is resolved to an actual script and location. + */ + prependListener(event: 'Debugger.breakpointResolved', listener: (message: InspectorNotification) => void): this; + /** + * Fired when the virtual machine stopped on breakpoint or exception or any other stop criteria. + */ + prependListener(event: 'Debugger.paused', listener: (message: InspectorNotification) => void): this; + /** + * Fired when the virtual machine resumed execution. + */ + prependListener(event: 'Debugger.resumed', listener: () => void): this; + /** + * Issued when new console message is added. + */ + prependListener(event: 'Console.messageAdded', listener: (message: InspectorNotification) => void): this; + /** + * Sent when new profile recording is started using console.profile() call. + */ + prependListener(event: 'Profiler.consoleProfileStarted', listener: (message: InspectorNotification) => void): this; + prependListener(event: 'Profiler.consoleProfileFinished', listener: (message: InspectorNotification) => void): this; + prependListener(event: 'HeapProfiler.addHeapSnapshotChunk', listener: (message: InspectorNotification) => void): this; + prependListener(event: 'HeapProfiler.resetProfiles', listener: () => void): this; + prependListener(event: 'HeapProfiler.reportHeapSnapshotProgress', listener: (message: InspectorNotification) => void): this; + /** + * If heap objects tracking has been started then backend regularly sends a current value for last seen object id and corresponding timestamp. If the were changes in the heap since last event then one or more heapStatsUpdate events will be sent before a new lastSeenObjectId event. + */ + prependListener(event: 'HeapProfiler.lastSeenObjectId', listener: (message: InspectorNotification) => void): this; + /** + * If heap objects tracking has been started then backend may send update for one or more fragments + */ + prependListener(event: 'HeapProfiler.heapStatsUpdate', listener: (message: InspectorNotification) => void): this; + /** + * Contains an bucket of collected trace events. + */ + prependListener(event: 'NodeTracing.dataCollected', listener: (message: InspectorNotification) => void): this; + /** + * Signals that tracing is stopped and there is no trace buffers pending flush, all data were + * delivered via dataCollected events. + */ + prependListener(event: 'NodeTracing.tracingComplete', listener: () => void): this; + /** + * Issued when attached to a worker. + */ + prependListener(event: 'NodeWorker.attachedToWorker', listener: (message: InspectorNotification) => void): this; + /** + * Issued when detached from the worker. + */ + prependListener(event: 'NodeWorker.detachedFromWorker', listener: (message: InspectorNotification) => void): this; + /** + * Notifies about a new protocol message received from the session + * (session ID is provided in attachedToWorker notification). + */ + prependListener(event: 'NodeWorker.receivedMessageFromWorker', listener: (message: InspectorNotification) => void): this; + /** + * This event is fired instead of `Runtime.executionContextDestroyed` when + * enabled. + * It is fired when the Node process finished all code execution and is + * waiting for all frontends to disconnect. + */ + prependListener(event: 'NodeRuntime.waitingForDisconnect', listener: () => void): this; + prependOnceListener(event: string, listener: (...args: any[]) => void): this; + /** + * Emitted when any notification from the V8 Inspector is received. + */ + prependOnceListener(event: 'inspectorNotification', listener: (message: InspectorNotification<{}>) => void): this; + /** + * Issued when new execution context is created. + */ + prependOnceListener(event: 'Runtime.executionContextCreated', listener: (message: InspectorNotification) => void): this; + /** + * Issued when execution context is destroyed. + */ + prependOnceListener(event: 'Runtime.executionContextDestroyed', listener: (message: InspectorNotification) => void): this; + /** + * Issued when all executionContexts were cleared in browser + */ + prependOnceListener(event: 'Runtime.executionContextsCleared', listener: () => void): this; + /** + * Issued when exception was thrown and unhandled. + */ + prependOnceListener(event: 'Runtime.exceptionThrown', listener: (message: InspectorNotification) => void): this; + /** + * Issued when unhandled exception was revoked. + */ + prependOnceListener(event: 'Runtime.exceptionRevoked', listener: (message: InspectorNotification) => void): this; + /** + * Issued when console API was called. + */ + prependOnceListener(event: 'Runtime.consoleAPICalled', listener: (message: InspectorNotification) => void): this; + /** + * Issued when object should be inspected (for example, as a result of inspect() command line API call). + */ + prependOnceListener(event: 'Runtime.inspectRequested', listener: (message: InspectorNotification) => void): this; + /** + * Fired when virtual machine parses script. This event is also fired for all known and uncollected scripts upon enabling debugger. + */ + prependOnceListener(event: 'Debugger.scriptParsed', listener: (message: InspectorNotification) => void): this; + /** + * Fired when virtual machine fails to parse the script. + */ + prependOnceListener(event: 'Debugger.scriptFailedToParse', listener: (message: InspectorNotification) => void): this; + /** + * Fired when breakpoint is resolved to an actual script and location. + */ + prependOnceListener(event: 'Debugger.breakpointResolved', listener: (message: InspectorNotification) => void): this; + /** + * Fired when the virtual machine stopped on breakpoint or exception or any other stop criteria. + */ + prependOnceListener(event: 'Debugger.paused', listener: (message: InspectorNotification) => void): this; + /** + * Fired when the virtual machine resumed execution. + */ + prependOnceListener(event: 'Debugger.resumed', listener: () => void): this; + /** + * Issued when new console message is added. + */ + prependOnceListener(event: 'Console.messageAdded', listener: (message: InspectorNotification) => void): this; + /** + * Sent when new profile recording is started using console.profile() call. + */ + prependOnceListener(event: 'Profiler.consoleProfileStarted', listener: (message: InspectorNotification) => void): this; + prependOnceListener(event: 'Profiler.consoleProfileFinished', listener: (message: InspectorNotification) => void): this; + prependOnceListener(event: 'HeapProfiler.addHeapSnapshotChunk', listener: (message: InspectorNotification) => void): this; + prependOnceListener(event: 'HeapProfiler.resetProfiles', listener: () => void): this; + prependOnceListener(event: 'HeapProfiler.reportHeapSnapshotProgress', listener: (message: InspectorNotification) => void): this; + /** + * If heap objects tracking has been started then backend regularly sends a current value for last seen object id and corresponding timestamp. If the were changes in the heap since last event then one or more heapStatsUpdate events will be sent before a new lastSeenObjectId event. + */ + prependOnceListener(event: 'HeapProfiler.lastSeenObjectId', listener: (message: InspectorNotification) => void): this; + /** + * If heap objects tracking has been started then backend may send update for one or more fragments + */ + prependOnceListener(event: 'HeapProfiler.heapStatsUpdate', listener: (message: InspectorNotification) => void): this; + /** + * Contains an bucket of collected trace events. + */ + prependOnceListener(event: 'NodeTracing.dataCollected', listener: (message: InspectorNotification) => void): this; + /** + * Signals that tracing is stopped and there is no trace buffers pending flush, all data were + * delivered via dataCollected events. + */ + prependOnceListener(event: 'NodeTracing.tracingComplete', listener: () => void): this; + /** + * Issued when attached to a worker. + */ + prependOnceListener(event: 'NodeWorker.attachedToWorker', listener: (message: InspectorNotification) => void): this; + /** + * Issued when detached from the worker. + */ + prependOnceListener(event: 'NodeWorker.detachedFromWorker', listener: (message: InspectorNotification) => void): this; + /** + * Notifies about a new protocol message received from the session + * (session ID is provided in attachedToWorker notification). + */ + prependOnceListener(event: 'NodeWorker.receivedMessageFromWorker', listener: (message: InspectorNotification) => void): this; + /** + * This event is fired instead of `Runtime.executionContextDestroyed` when + * enabled. + * It is fired when the Node process finished all code execution and is + * waiting for all frontends to disconnect. + */ + prependOnceListener(event: 'NodeRuntime.waitingForDisconnect', listener: () => void): this; + } + /** + * Activate inspector on host and port. Equivalent to`node --inspect=[[host:]port]`, but can be done programmatically after node has + * started. + * + * If wait is `true`, will block until a client has connected to the inspect port + * and flow control has been passed to the debugger client. + * + * See the `security warning` regarding the `host`parameter usage. + * @param [port='what was specified on the CLI'] Port to listen on for inspector connections. Optional. + * @param [host='what was specified on the CLI'] Host to listen on for inspector connections. Optional. + * @param [wait=false] Block until a client has connected. Optional. + */ + function open(port?: number, host?: string, wait?: boolean): void; + /** + * Deactivate the inspector. Blocks until there are no active connections. + */ + function close(): void; + /** + * Return the URL of the active inspector, or `undefined` if there is none. + * + * ```console + * $ node --inspect -p 'inspector.url()' + * Debugger listening on ws://127.0.0.1:9229/166e272e-7a30-4d09-97ce-f1c012b43c34 + * For help, see: https://nodejs.org/en/docs/inspector + * ws://127.0.0.1:9229/166e272e-7a30-4d09-97ce-f1c012b43c34 + * + * $ node --inspect=localhost:3000 -p 'inspector.url()' + * Debugger listening on ws://localhost:3000/51cf8d0e-3c36-4c59-8efd-54519839e56a + * For help, see: https://nodejs.org/en/docs/inspector + * ws://localhost:3000/51cf8d0e-3c36-4c59-8efd-54519839e56a + * + * $ node -p 'inspector.url()' + * undefined + * ``` + */ + function url(): string | undefined; + /** + * Blocks until a client (existing or connected later) has sent`Runtime.runIfWaitingForDebugger` command. + * + * An exception will be thrown if there is no active inspector. + * @since v12.7.0 + */ + function waitForDebugger(): void; +} +/** + * The inspector module provides an API for interacting with the V8 inspector. + */ +declare module 'node:inspector' { + import inspector = require('inspector'); + export = inspector; +} diff --git a/ts-ticket-office-service/node_modules/@types/node/module.d.ts b/ts-ticket-office-service/node_modules/@types/node/module.d.ts new file mode 100755 index 000000000..d83aec94a --- /dev/null +++ b/ts-ticket-office-service/node_modules/@types/node/module.d.ts @@ -0,0 +1,114 @@ +/** + * @since v0.3.7 + */ +declare module 'module' { + import { URL } from 'node:url'; + namespace Module { + /** + * The `module.syncBuiltinESMExports()` method updates all the live bindings for + * builtin `ES Modules` to match the properties of the `CommonJS` exports. It + * does not add or remove exported names from the `ES Modules`. + * + * ```js + * const fs = require('fs'); + * const assert = require('assert'); + * const { syncBuiltinESMExports } = require('module'); + * + * fs.readFile = newAPI; + * + * delete fs.readFileSync; + * + * function newAPI() { + * // ... + * } + * + * fs.newAPI = newAPI; + * + * syncBuiltinESMExports(); + * + * import('fs').then((esmFS) => { + * // It syncs the existing readFile property with the new value + * assert.strictEqual(esmFS.readFile, newAPI); + * // readFileSync has been deleted from the required fs + * assert.strictEqual('readFileSync' in fs, false); + * // syncBuiltinESMExports() does not remove readFileSync from esmFS + * assert.strictEqual('readFileSync' in esmFS, true); + * // syncBuiltinESMExports() does not add names + * assert.strictEqual(esmFS.newAPI, undefined); + * }); + * ``` + * @since v12.12.0 + */ + function syncBuiltinESMExports(): void; + /** + * `path` is the resolved path for the file for which a corresponding source map + * should be fetched. + * @since v13.7.0, v12.17.0 + */ + function findSourceMap(path: string, error?: Error): SourceMap; + interface SourceMapPayload { + file: string; + version: number; + sources: string[]; + sourcesContent: string[]; + names: string[]; + mappings: string; + sourceRoot: string; + } + interface SourceMapping { + generatedLine: number; + generatedColumn: number; + originalSource: string; + originalLine: number; + originalColumn: number; + } + /** + * @since v13.7.0, v12.17.0 + */ + class SourceMap { + /** + * Getter for the payload used to construct the `SourceMap` instance. + */ + readonly payload: SourceMapPayload; + constructor(payload: SourceMapPayload); + /** + * Given a line number and column number in the generated source file, returns + * an object representing the position in the original file. The object returned + * consists of the following keys: + */ + findEntry(line: number, column: number): SourceMapping; + } + } + interface Module extends NodeModule {} + class Module { + static runMain(): void; + static wrap(code: string): string; + static createRequire(path: string | URL): NodeRequire; + static builtinModules: string[]; + static Module: typeof Module; + constructor(id: string, parent?: Module); + } + global { + interface ImportMeta { + url: string; + /** + * @experimental + * This feature is only available with the `--experimental-import-meta-resolve` + * command flag enabled. + * + * Provides a module-relative resolution function scoped to each module, returning + * the URL string. + * + * @param specified The module specifier to resolve relative to `parent`. + * @param parent The absolute parent module URL to resolve from. If none + * is specified, the value of `import.meta.url` is used as the default. + */ + resolve?(specified: string, parent?: string | URL): Promise; + } + } + export = Module; +} +declare module 'node:module' { + import module = require('module'); + export = module; +} diff --git a/ts-ticket-office-service/node_modules/@types/node/net.d.ts b/ts-ticket-office-service/node_modules/@types/node/net.d.ts new file mode 100755 index 000000000..f0ae5b803 --- /dev/null +++ b/ts-ticket-office-service/node_modules/@types/node/net.d.ts @@ -0,0 +1,816 @@ +/** + * > Stability: 2 - Stable + * + * The `net` module provides an asynchronous network API for creating stream-based + * TCP or `IPC` servers ({@link createServer}) and clients + * ({@link createConnection}). + * + * It can be accessed using: + * + * ```js + * const net = require('net'); + * ``` + * @see [source](https://github.com/nodejs/node/blob/v18.0.0/lib/net.js) + */ +declare module 'net' { + import * as stream from 'node:stream'; + import { Abortable, EventEmitter } from 'node:events'; + import * as dns from 'node:dns'; + type LookupFunction = (hostname: string, options: dns.LookupOneOptions, callback: (err: NodeJS.ErrnoException | null, address: string, family: number) => void) => void; + interface AddressInfo { + address: string; + family: string; + port: number; + } + interface SocketConstructorOpts { + fd?: number | undefined; + allowHalfOpen?: boolean | undefined; + readable?: boolean | undefined; + writable?: boolean | undefined; + signal?: AbortSignal; + } + interface OnReadOpts { + buffer: Uint8Array | (() => Uint8Array); + /** + * This function is called for every chunk of incoming data. + * Two arguments are passed to it: the number of bytes written to buffer and a reference to buffer. + * Return false from this function to implicitly pause() the socket. + */ + callback(bytesWritten: number, buf: Uint8Array): boolean; + } + interface ConnectOpts { + /** + * If specified, incoming data is stored in a single buffer and passed to the supplied callback when data arrives on the socket. + * Note: this will cause the streaming functionality to not provide any data, however events like 'error', 'end', and 'close' will + * still be emitted as normal and methods like pause() and resume() will also behave as expected. + */ + onread?: OnReadOpts | undefined; + } + interface TcpSocketConnectOpts extends ConnectOpts { + port: number; + host?: string | undefined; + localAddress?: string | undefined; + localPort?: number | undefined; + hints?: number | undefined; + family?: number | undefined; + lookup?: LookupFunction | undefined; + } + interface IpcSocketConnectOpts extends ConnectOpts { + path: string; + } + type SocketConnectOpts = TcpSocketConnectOpts | IpcSocketConnectOpts; + type SocketReadyState = 'opening' | 'open' | 'readOnly' | 'writeOnly' | 'closed'; + /** + * This class is an abstraction of a TCP socket or a streaming `IPC` endpoint + * (uses named pipes on Windows, and Unix domain sockets otherwise). It is also + * an `EventEmitter`. + * + * A `net.Socket` can be created by the user and used directly to interact with + * a server. For example, it is returned by {@link createConnection}, + * so the user can use it to talk to the server. + * + * It can also be created by Node.js and passed to the user when a connection + * is received. For example, it is passed to the listeners of a `'connection'` event emitted on a {@link Server}, so the user can use + * it to interact with the client. + * @since v0.3.4 + */ + class Socket extends stream.Duplex { + constructor(options?: SocketConstructorOpts); + /** + * Sends data on the socket. The second parameter specifies the encoding in the + * case of a string. It defaults to UTF8 encoding. + * + * Returns `true` if the entire data was flushed successfully to the kernel + * buffer. Returns `false` if all or part of the data was queued in user memory.`'drain'` will be emitted when the buffer is again free. + * + * The optional `callback` parameter will be executed when the data is finally + * written out, which may not be immediately. + * + * See `Writable` stream `write()` method for more + * information. + * @since v0.1.90 + * @param [encoding='utf8'] Only used when data is `string`. + */ + write(buffer: Uint8Array | string, cb?: (err?: Error) => void): boolean; + write(str: Uint8Array | string, encoding?: BufferEncoding, cb?: (err?: Error) => void): boolean; + /** + * Initiate a connection on a given socket. + * + * Possible signatures: + * + * * `socket.connect(options[, connectListener])` + * * `socket.connect(path[, connectListener])` for `IPC` connections. + * * `socket.connect(port[, host][, connectListener])` for TCP connections. + * * Returns: `net.Socket` The socket itself. + * + * This function is asynchronous. When the connection is established, the `'connect'` event will be emitted. If there is a problem connecting, + * instead of a `'connect'` event, an `'error'` event will be emitted with + * the error passed to the `'error'` listener. + * The last parameter `connectListener`, if supplied, will be added as a listener + * for the `'connect'` event **once**. + * + * This function should only be used for reconnecting a socket after`'close'` has been emitted or otherwise it may lead to undefined + * behavior. + */ + connect(options: SocketConnectOpts, connectionListener?: () => void): this; + connect(port: number, host: string, connectionListener?: () => void): this; + connect(port: number, connectionListener?: () => void): this; + connect(path: string, connectionListener?: () => void): this; + /** + * Set the encoding for the socket as a `Readable Stream`. See `readable.setEncoding()` for more information. + * @since v0.1.90 + * @return The socket itself. + */ + setEncoding(encoding?: BufferEncoding): this; + /** + * Pauses the reading of data. That is, `'data'` events will not be emitted. + * Useful to throttle back an upload. + * @return The socket itself. + */ + pause(): this; + /** + * Resumes reading after a call to `socket.pause()`. + * @return The socket itself. + */ + resume(): this; + /** + * Sets the socket to timeout after `timeout` milliseconds of inactivity on + * the socket. By default `net.Socket` do not have a timeout. + * + * When an idle timeout is triggered the socket will receive a `'timeout'` event but the connection will not be severed. The user must manually call `socket.end()` or `socket.destroy()` to + * end the connection. + * + * ```js + * socket.setTimeout(3000); + * socket.on('timeout', () => { + * console.log('socket timeout'); + * socket.end(); + * }); + * ``` + * + * If `timeout` is 0, then the existing idle timeout is disabled. + * + * The optional `callback` parameter will be added as a one-time listener for the `'timeout'` event. + * @since v0.1.90 + * @return The socket itself. + */ + setTimeout(timeout: number, callback?: () => void): this; + /** + * Enable/disable the use of Nagle's algorithm. + * + * When a TCP connection is created, it will have Nagle's algorithm enabled. + * + * Nagle's algorithm delays data before it is sent via the network. It attempts + * to optimize throughput at the expense of latency. + * + * Passing `true` for `noDelay` or not passing an argument will disable Nagle's + * algorithm for the socket. Passing `false` for `noDelay` will enable Nagle's + * algorithm. + * @since v0.1.90 + * @param [noDelay=true] + * @return The socket itself. + */ + setNoDelay(noDelay?: boolean): this; + /** + * Enable/disable keep-alive functionality, and optionally set the initial + * delay before the first keepalive probe is sent on an idle socket. + * + * Set `initialDelay` (in milliseconds) to set the delay between the last + * data packet received and the first keepalive probe. Setting `0` for`initialDelay` will leave the value unchanged from the default + * (or previous) setting. + * + * Enabling the keep-alive functionality will set the following socket options: + * + * * `SO_KEEPALIVE=1` + * * `TCP_KEEPIDLE=initialDelay` + * * `TCP_KEEPCNT=10` + * * `TCP_KEEPINTVL=1` + * @since v0.1.92 + * @param [enable=false] + * @param [initialDelay=0] + * @return The socket itself. + */ + setKeepAlive(enable?: boolean, initialDelay?: number): this; + /** + * Returns the bound `address`, the address `family` name and `port` of the + * socket as reported by the operating system:`{ port: 12346, family: 'IPv4', address: '127.0.0.1' }` + * @since v0.1.90 + */ + address(): AddressInfo | {}; + /** + * Calling `unref()` on a socket will allow the program to exit if this is the only + * active socket in the event system. If the socket is already `unref`ed calling`unref()` again will have no effect. + * @since v0.9.1 + * @return The socket itself. + */ + unref(): this; + /** + * Opposite of `unref()`, calling `ref()` on a previously `unref`ed socket will_not_ let the program exit if it's the only socket left (the default behavior). + * If the socket is `ref`ed calling `ref` again will have no effect. + * @since v0.9.1 + * @return The socket itself. + */ + ref(): this; + /** + * This property shows the number of characters buffered for writing. The buffer + * may contain strings whose length after encoding is not yet known. So this number + * is only an approximation of the number of bytes in the buffer. + * + * `net.Socket` has the property that `socket.write()` always works. This is to + * help users get up and running quickly. The computer cannot always keep up + * with the amount of data that is written to a socket. The network connection + * simply might be too slow. Node.js will internally queue up the data written to a + * socket and send it out over the wire when it is possible. + * + * The consequence of this internal buffering is that memory may grow. + * Users who experience large or growing `bufferSize` should attempt to + * "throttle" the data flows in their program with `socket.pause()` and `socket.resume()`. + * @since v0.3.8 + * @deprecated Since v14.6.0 - Use `writableLength` instead. + */ + readonly bufferSize: number; + /** + * The amount of received bytes. + * @since v0.5.3 + */ + readonly bytesRead: number; + /** + * The amount of bytes sent. + * @since v0.5.3 + */ + readonly bytesWritten: number; + /** + * If `true`,`socket.connect(options[, connectListener])` was + * called and has not yet finished. It will stay `true` until the socket becomes + * connected, then it is set to `false` and the `'connect'` event is emitted. Note + * that the `socket.connect(options[, connectListener])` callback is a listener for the `'connect'` event. + * @since v6.1.0 + */ + readonly connecting: boolean; + /** + * See `writable.destroyed` for further details. + */ + readonly destroyed: boolean; + /** + * The string representation of the local IP address the remote client is + * connecting on. For example, in a server listening on `'0.0.0.0'`, if a client + * connects on `'192.168.1.1'`, the value of `socket.localAddress` would be`'192.168.1.1'`. + * @since v0.9.6 + */ + readonly localAddress?: string; + /** + * The numeric representation of the local port. For example, `80` or `21`. + * @since v0.9.6 + */ + readonly localPort?: number; + /** + * This property represents the state of the connection as a string. + * @see {https://nodejs.org/api/net.html#socketreadystate} + * @since v0.5.0 + */ + readonly readyState: SocketReadyState; + /** + * The string representation of the remote IP address. For example,`'74.125.127.100'` or `'2001:4860:a005::68'`. Value may be `undefined` if + * the socket is destroyed (for example, if the client disconnected). + * @since v0.5.10 + */ + readonly remoteAddress?: string | undefined; + /** + * The string representation of the remote IP family. `'IPv4'` or `'IPv6'`. + * @since v0.11.14 + */ + readonly remoteFamily?: string | undefined; + /** + * The numeric representation of the remote port. For example, `80` or `21`. + * @since v0.5.10 + */ + readonly remotePort?: number | undefined; + /** + * The socket timeout in milliseconds as set by socket.setTimeout(). It is undefined if a timeout has not been set. + * @since v10.7.0 + */ + readonly timeout?: number | undefined; + /** + * Half-closes the socket. i.e., it sends a FIN packet. It is possible the + * server will still send some data. + * + * See `writable.end()` for further details. + * @since v0.1.90 + * @param [encoding='utf8'] Only used when data is `string`. + * @param callback Optional callback for when the socket is finished. + * @return The socket itself. + */ + end(callback?: () => void): this; + end(buffer: Uint8Array | string, callback?: () => void): this; + end(str: Uint8Array | string, encoding?: BufferEncoding, callback?: () => void): this; + /** + * events.EventEmitter + * 1. close + * 2. connect + * 3. data + * 4. drain + * 5. end + * 6. error + * 7. lookup + * 8. timeout + */ + addListener(event: string, listener: (...args: any[]) => void): this; + addListener(event: 'close', listener: (hadError: boolean) => void): this; + addListener(event: 'connect', listener: () => void): this; + addListener(event: 'data', listener: (data: Buffer) => void): this; + addListener(event: 'drain', listener: () => void): this; + addListener(event: 'end', listener: () => void): this; + addListener(event: 'error', listener: (err: Error) => void): this; + addListener(event: 'lookup', listener: (err: Error, address: string, family: string | number, host: string) => void): this; + addListener(event: 'ready', listener: () => void): this; + addListener(event: 'timeout', listener: () => void): this; + emit(event: string | symbol, ...args: any[]): boolean; + emit(event: 'close', hadError: boolean): boolean; + emit(event: 'connect'): boolean; + emit(event: 'data', data: Buffer): boolean; + emit(event: 'drain'): boolean; + emit(event: 'end'): boolean; + emit(event: 'error', err: Error): boolean; + emit(event: 'lookup', err: Error, address: string, family: string | number, host: string): boolean; + emit(event: 'ready'): boolean; + emit(event: 'timeout'): boolean; + on(event: string, listener: (...args: any[]) => void): this; + on(event: 'close', listener: (hadError: boolean) => void): this; + on(event: 'connect', listener: () => void): this; + on(event: 'data', listener: (data: Buffer) => void): this; + on(event: 'drain', listener: () => void): this; + on(event: 'end', listener: () => void): this; + on(event: 'error', listener: (err: Error) => void): this; + on(event: 'lookup', listener: (err: Error, address: string, family: string | number, host: string) => void): this; + on(event: 'ready', listener: () => void): this; + on(event: 'timeout', listener: () => void): this; + once(event: string, listener: (...args: any[]) => void): this; + once(event: 'close', listener: (hadError: boolean) => void): this; + once(event: 'connect', listener: () => void): this; + once(event: 'data', listener: (data: Buffer) => void): this; + once(event: 'drain', listener: () => void): this; + once(event: 'end', listener: () => void): this; + once(event: 'error', listener: (err: Error) => void): this; + once(event: 'lookup', listener: (err: Error, address: string, family: string | number, host: string) => void): this; + once(event: 'ready', listener: () => void): this; + once(event: 'timeout', listener: () => void): this; + prependListener(event: string, listener: (...args: any[]) => void): this; + prependListener(event: 'close', listener: (hadError: boolean) => void): this; + prependListener(event: 'connect', listener: () => void): this; + prependListener(event: 'data', listener: (data: Buffer) => void): this; + prependListener(event: 'drain', listener: () => void): this; + prependListener(event: 'end', listener: () => void): this; + prependListener(event: 'error', listener: (err: Error) => void): this; + prependListener(event: 'lookup', listener: (err: Error, address: string, family: string | number, host: string) => void): this; + prependListener(event: 'ready', listener: () => void): this; + prependListener(event: 'timeout', listener: () => void): this; + prependOnceListener(event: string, listener: (...args: any[]) => void): this; + prependOnceListener(event: 'close', listener: (hadError: boolean) => void): this; + prependOnceListener(event: 'connect', listener: () => void): this; + prependOnceListener(event: 'data', listener: (data: Buffer) => void): this; + prependOnceListener(event: 'drain', listener: () => void): this; + prependOnceListener(event: 'end', listener: () => void): this; + prependOnceListener(event: 'error', listener: (err: Error) => void): this; + prependOnceListener(event: 'lookup', listener: (err: Error, address: string, family: string | number, host: string) => void): this; + prependOnceListener(event: 'ready', listener: () => void): this; + prependOnceListener(event: 'timeout', listener: () => void): this; + } + interface ListenOptions extends Abortable { + port?: number | undefined; + host?: string | undefined; + backlog?: number | undefined; + path?: string | undefined; + exclusive?: boolean | undefined; + readableAll?: boolean | undefined; + writableAll?: boolean | undefined; + /** + * @default false + */ + ipv6Only?: boolean | undefined; + } + interface ServerOpts { + /** + * Indicates whether half-opened TCP connections are allowed. + * @default false + */ + allowHalfOpen?: boolean | undefined; + /** + * Indicates whether the socket should be paused on incoming connections. + * @default false + */ + pauseOnConnect?: boolean | undefined; + } + /** + * This class is used to create a TCP or `IPC` server. + * @since v0.1.90 + */ + class Server extends EventEmitter { + constructor(connectionListener?: (socket: Socket) => void); + constructor(options?: ServerOpts, connectionListener?: (socket: Socket) => void); + /** + * Start a server listening for connections. A `net.Server` can be a TCP or + * an `IPC` server depending on what it listens to. + * + * Possible signatures: + * + * * `server.listen(handle[, backlog][, callback])` + * * `server.listen(options[, callback])` + * * `server.listen(path[, backlog][, callback])` for `IPC` servers + * * `server.listen([port[, host[, backlog]]][, callback])` for TCP servers + * + * This function is asynchronous. When the server starts listening, the `'listening'` event will be emitted. The last parameter `callback`will be added as a listener for the `'listening'` + * event. + * + * All `listen()` methods can take a `backlog` parameter to specify the maximum + * length of the queue of pending connections. The actual length will be determined + * by the OS through sysctl settings such as `tcp_max_syn_backlog` and `somaxconn`on Linux. The default value of this parameter is 511 (not 512). + * + * All {@link Socket} are set to `SO_REUSEADDR` (see [`socket(7)`](https://man7.org/linux/man-pages/man7/socket.7.html) for + * details). + * + * The `server.listen()` method can be called again if and only if there was an + * error during the first `server.listen()` call or `server.close()` has been + * called. Otherwise, an `ERR_SERVER_ALREADY_LISTEN` error will be thrown. + * + * One of the most common errors raised when listening is `EADDRINUSE`. + * This happens when another server is already listening on the requested`port`/`path`/`handle`. One way to handle this would be to retry + * after a certain amount of time: + * + * ```js + * server.on('error', (e) => { + * if (e.code === 'EADDRINUSE') { + * console.log('Address in use, retrying...'); + * setTimeout(() => { + * server.close(); + * server.listen(PORT, HOST); + * }, 1000); + * } + * }); + * ``` + */ + listen(port?: number, hostname?: string, backlog?: number, listeningListener?: () => void): this; + listen(port?: number, hostname?: string, listeningListener?: () => void): this; + listen(port?: number, backlog?: number, listeningListener?: () => void): this; + listen(port?: number, listeningListener?: () => void): this; + listen(path: string, backlog?: number, listeningListener?: () => void): this; + listen(path: string, listeningListener?: () => void): this; + listen(options: ListenOptions, listeningListener?: () => void): this; + listen(handle: any, backlog?: number, listeningListener?: () => void): this; + listen(handle: any, listeningListener?: () => void): this; + /** + * Stops the server from accepting new connections and keeps existing + * connections. This function is asynchronous, the server is finally closed + * when all connections are ended and the server emits a `'close'` event. + * The optional `callback` will be called once the `'close'` event occurs. Unlike + * that event, it will be called with an `Error` as its only argument if the server + * was not open when it was closed. + * @since v0.1.90 + * @param callback Called when the server is closed. + */ + close(callback?: (err?: Error) => void): this; + /** + * Returns the bound `address`, the address `family` name, and `port` of the server + * as reported by the operating system if listening on an IP socket + * (useful to find which port was assigned when getting an OS-assigned address):`{ port: 12346, family: 'IPv4', address: '127.0.0.1' }`. + * + * For a server listening on a pipe or Unix domain socket, the name is returned + * as a string. + * + * ```js + * const server = net.createServer((socket) => { + * socket.end('goodbye\n'); + * }).on('error', (err) => { + * // Handle errors here. + * throw err; + * }); + * + * // Grab an arbitrary unused port. + * server.listen(() => { + * console.log('opened server on', server.address()); + * }); + * ``` + * + * `server.address()` returns `null` before the `'listening'` event has been + * emitted or after calling `server.close()`. + * @since v0.1.90 + */ + address(): AddressInfo | string | null; + /** + * Asynchronously get the number of concurrent connections on the server. Works + * when sockets were sent to forks. + * + * Callback should take two arguments `err` and `count`. + * @since v0.9.7 + */ + getConnections(cb: (error: Error | null, count: number) => void): void; + /** + * Opposite of `unref()`, calling `ref()` on a previously `unref`ed server will_not_ let the program exit if it's the only server left (the default behavior). + * If the server is `ref`ed calling `ref()` again will have no effect. + * @since v0.9.1 + */ + ref(): this; + /** + * Calling `unref()` on a server will allow the program to exit if this is the only + * active server in the event system. If the server is already `unref`ed calling`unref()` again will have no effect. + * @since v0.9.1 + */ + unref(): this; + /** + * Set this property to reject connections when the server's connection count gets + * high. + * + * It is not recommended to use this option once a socket has been sent to a child + * with `child_process.fork()`. + * @since v0.2.0 + */ + maxConnections: number; + connections: number; + /** + * Indicates whether or not the server is listening for connections. + * @since v5.7.0 + */ + listening: boolean; + /** + * events.EventEmitter + * 1. close + * 2. connection + * 3. error + * 4. listening + */ + addListener(event: string, listener: (...args: any[]) => void): this; + addListener(event: 'close', listener: () => void): this; + addListener(event: 'connection', listener: (socket: Socket) => void): this; + addListener(event: 'error', listener: (err: Error) => void): this; + addListener(event: 'listening', listener: () => void): this; + emit(event: string | symbol, ...args: any[]): boolean; + emit(event: 'close'): boolean; + emit(event: 'connection', socket: Socket): boolean; + emit(event: 'error', err: Error): boolean; + emit(event: 'listening'): boolean; + on(event: string, listener: (...args: any[]) => void): this; + on(event: 'close', listener: () => void): this; + on(event: 'connection', listener: (socket: Socket) => void): this; + on(event: 'error', listener: (err: Error) => void): this; + on(event: 'listening', listener: () => void): this; + once(event: string, listener: (...args: any[]) => void): this; + once(event: 'close', listener: () => void): this; + once(event: 'connection', listener: (socket: Socket) => void): this; + once(event: 'error', listener: (err: Error) => void): this; + once(event: 'listening', listener: () => void): this; + prependListener(event: string, listener: (...args: any[]) => void): this; + prependListener(event: 'close', listener: () => void): this; + prependListener(event: 'connection', listener: (socket: Socket) => void): this; + prependListener(event: 'error', listener: (err: Error) => void): this; + prependListener(event: 'listening', listener: () => void): this; + prependOnceListener(event: string, listener: (...args: any[]) => void): this; + prependOnceListener(event: 'close', listener: () => void): this; + prependOnceListener(event: 'connection', listener: (socket: Socket) => void): this; + prependOnceListener(event: 'error', listener: (err: Error) => void): this; + prependOnceListener(event: 'listening', listener: () => void): this; + } + type IPVersion = 'ipv4' | 'ipv6'; + /** + * The `BlockList` object can be used with some network APIs to specify rules for + * disabling inbound or outbound access to specific IP addresses, IP ranges, or + * IP subnets. + * @since v15.0.0, v14.18.0 + */ + class BlockList { + /** + * Adds a rule to block the given IP address. + * @since v15.0.0, v14.18.0 + * @param address An IPv4 or IPv6 address. + * @param [type='ipv4'] Either `'ipv4'` or `'ipv6'`. + */ + addAddress(address: string, type?: IPVersion): void; + addAddress(address: SocketAddress): void; + /** + * Adds a rule to block a range of IP addresses from `start` (inclusive) to`end` (inclusive). + * @since v15.0.0, v14.18.0 + * @param start The starting IPv4 or IPv6 address in the range. + * @param end The ending IPv4 or IPv6 address in the range. + * @param [type='ipv4'] Either `'ipv4'` or `'ipv6'`. + */ + addRange(start: string, end: string, type?: IPVersion): void; + addRange(start: SocketAddress, end: SocketAddress): void; + /** + * Adds a rule to block a range of IP addresses specified as a subnet mask. + * @since v15.0.0, v14.18.0 + * @param net The network IPv4 or IPv6 address. + * @param prefix The number of CIDR prefix bits. For IPv4, this must be a value between `0` and `32`. For IPv6, this must be between `0` and `128`. + * @param [type='ipv4'] Either `'ipv4'` or `'ipv6'`. + */ + addSubnet(net: SocketAddress, prefix: number): void; + addSubnet(net: string, prefix: number, type?: IPVersion): void; + /** + * Returns `true` if the given IP address matches any of the rules added to the`BlockList`. + * + * ```js + * const blockList = new net.BlockList(); + * blockList.addAddress('123.123.123.123'); + * blockList.addRange('10.0.0.1', '10.0.0.10'); + * blockList.addSubnet('8592:757c:efae:4e45::', 64, 'ipv6'); + * + * console.log(blockList.check('123.123.123.123')); // Prints: true + * console.log(blockList.check('10.0.0.3')); // Prints: true + * console.log(blockList.check('222.111.111.222')); // Prints: false + * + * // IPv6 notation for IPv4 addresses works: + * console.log(blockList.check('::ffff:7b7b:7b7b', 'ipv6')); // Prints: true + * console.log(blockList.check('::ffff:123.123.123.123', 'ipv6')); // Prints: true + * ``` + * @since v15.0.0, v14.18.0 + * @param address The IP address to check + * @param [type='ipv4'] Either `'ipv4'` or `'ipv6'`. + */ + check(address: SocketAddress): boolean; + check(address: string, type?: IPVersion): boolean; + } + interface TcpNetConnectOpts extends TcpSocketConnectOpts, SocketConstructorOpts { + timeout?: number | undefined; + } + interface IpcNetConnectOpts extends IpcSocketConnectOpts, SocketConstructorOpts { + timeout?: number | undefined; + } + type NetConnectOpts = TcpNetConnectOpts | IpcNetConnectOpts; + /** + * Creates a new TCP or `IPC` server. + * + * If `allowHalfOpen` is set to `true`, when the other end of the socket + * signals the end of transmission, the server will only send back the end of + * transmission when `socket.end()` is explicitly called. For example, in the + * context of TCP, when a FIN packed is received, a FIN packed is sent + * back only when `socket.end()` is explicitly called. Until then the + * connection is half-closed (non-readable but still writable). See `'end'` event and [RFC 1122](https://tools.ietf.org/html/rfc1122) (section 4.2.2.13) for more information. + * + * If `pauseOnConnect` is set to `true`, then the socket associated with each + * incoming connection will be paused, and no data will be read from its handle. + * This allows connections to be passed between processes without any data being + * read by the original process. To begin reading data from a paused socket, call `socket.resume()`. + * + * The server can be a TCP server or an `IPC` server, depending on what it `listen()` to. + * + * Here is an example of a TCP echo server which listens for connections + * on port 8124: + * + * ```js + * const net = require('net'); + * const server = net.createServer((c) => { + * // 'connection' listener. + * console.log('client connected'); + * c.on('end', () => { + * console.log('client disconnected'); + * }); + * c.write('hello\r\n'); + * c.pipe(c); + * }); + * server.on('error', (err) => { + * throw err; + * }); + * server.listen(8124, () => { + * console.log('server bound'); + * }); + * ``` + * + * Test this by using `telnet`: + * + * ```console + * $ telnet localhost 8124 + * ``` + * + * To listen on the socket `/tmp/echo.sock`: + * + * ```js + * server.listen('/tmp/echo.sock', () => { + * console.log('server bound'); + * }); + * ``` + * + * Use `nc` to connect to a Unix domain socket server: + * + * ```console + * $ nc -U /tmp/echo.sock + * ``` + * @since v0.5.0 + * @param connectionListener Automatically set as a listener for the {@link 'connection'} event. + */ + function createServer(connectionListener?: (socket: Socket) => void): Server; + function createServer(options?: ServerOpts, connectionListener?: (socket: Socket) => void): Server; + /** + * Aliases to {@link createConnection}. + * + * Possible signatures: + * + * * {@link connect} + * * {@link connect} for `IPC` connections. + * * {@link connect} for TCP connections. + */ + function connect(options: NetConnectOpts, connectionListener?: () => void): Socket; + function connect(port: number, host?: string, connectionListener?: () => void): Socket; + function connect(path: string, connectionListener?: () => void): Socket; + /** + * A factory function, which creates a new {@link Socket}, + * immediately initiates connection with `socket.connect()`, + * then returns the `net.Socket` that starts the connection. + * + * When the connection is established, a `'connect'` event will be emitted + * on the returned socket. The last parameter `connectListener`, if supplied, + * will be added as a listener for the `'connect'` event **once**. + * + * Possible signatures: + * + * * {@link createConnection} + * * {@link createConnection} for `IPC` connections. + * * {@link createConnection} for TCP connections. + * + * The {@link connect} function is an alias to this function. + */ + function createConnection(options: NetConnectOpts, connectionListener?: () => void): Socket; + function createConnection(port: number, host?: string, connectionListener?: () => void): Socket; + function createConnection(path: string, connectionListener?: () => void): Socket; + /** + * Returns `6` if `input` is an IPv6 address. Returns `4` if `input` is an IPv4 + * address in [dot-decimal notation](https://en.wikipedia.org/wiki/Dot-decimal_notation) with no leading zeroes. Otherwise, returns`0`. + * + * ```js + * net.isIP('::1'); // returns 6 + * net.isIP('127.0.0.1'); // returns 4 + * net.isIP('127.000.000.001'); // returns 0 + * net.isIP('127.0.0.1/24'); // returns 0 + * net.isIP('fhqwhgads'); // returns 0 + * ``` + * @since v0.3.0 + */ + function isIP(input: string): number; + /** + * Returns `true` if `input` is an IPv4 address in [dot-decimal notation](https://en.wikipedia.org/wiki/Dot-decimal_notation) with no + * leading zeroes. Otherwise, returns `false`. + * + * ```js + * net.isIPv4('127.0.0.1'); // returns true + * net.isIPv4('127.000.000.001'); // returns false + * net.isIPv4('127.0.0.1/24'); // returns false + * net.isIPv4('fhqwhgads'); // returns false + * ``` + * @since v0.3.0 + */ + function isIPv4(input: string): boolean; + /** + * Returns `true` if `input` is an IPv6 address. Otherwise, returns `false`. + * + * ```js + * net.isIPv6('::1'); // returns true + * net.isIPv6('fhqwhgads'); // returns false + * ``` + * @since v0.3.0 + */ + function isIPv6(input: string): boolean; + interface SocketAddressInitOptions { + /** + * The network address as either an IPv4 or IPv6 string. + * @default 127.0.0.1 + */ + address?: string | undefined; + /** + * @default `'ipv4'` + */ + family?: IPVersion | undefined; + /** + * An IPv6 flow-label used only if `family` is `'ipv6'`. + * @default 0 + */ + flowlabel?: number | undefined; + /** + * An IP port. + * @default 0 + */ + port?: number | undefined; + } + /** + * @since v15.14.0, v14.18.0 + */ + class SocketAddress { + constructor(options: SocketAddressInitOptions); + /** + * Either \`'ipv4'\` or \`'ipv6'\`. + * @since v15.14.0, v14.18.0 + */ + readonly address: string; + /** + * Either \`'ipv4'\` or \`'ipv6'\`. + * @since v15.14.0, v14.18.0 + */ + readonly family: IPVersion; + /** + * @since v15.14.0, v14.18.0 + */ + readonly port: number; + /** + * @since v15.14.0, v14.18.0 + */ + readonly flowlabel: number; + } +} +declare module 'node:net' { + export * from 'net'; +} diff --git a/ts-ticket-office-service/node_modules/@types/node/os.d.ts b/ts-ticket-office-service/node_modules/@types/node/os.d.ts new file mode 100755 index 000000000..cad5eccb4 --- /dev/null +++ b/ts-ticket-office-service/node_modules/@types/node/os.d.ts @@ -0,0 +1,456 @@ +/** + * The `os` module provides operating system-related utility methods and + * properties. It can be accessed using: + * + * ```js + * const os = require('os'); + * ``` + * @see [source](https://github.com/nodejs/node/blob/v18.0.0/lib/os.js) + */ +declare module 'os' { + interface CpuInfo { + model: string; + speed: number; + times: { + user: number; + nice: number; + sys: number; + idle: number; + irq: number; + }; + } + interface NetworkInterfaceBase { + address: string; + netmask: string; + mac: string; + internal: boolean; + cidr: string | null; + } + interface NetworkInterfaceInfoIPv4 extends NetworkInterfaceBase { + family: 'IPv4'; + } + interface NetworkInterfaceInfoIPv6 extends NetworkInterfaceBase { + family: 'IPv6'; + scopeid: number; + } + interface UserInfo { + username: T; + uid: number; + gid: number; + shell: T; + homedir: T; + } + type NetworkInterfaceInfo = NetworkInterfaceInfoIPv4 | NetworkInterfaceInfoIPv6; + /** + * Returns the host name of the operating system as a string. + * @since v0.3.3 + */ + function hostname(): string; + /** + * Returns an array containing the 1, 5, and 15 minute load averages. + * + * The load average is a measure of system activity calculated by the operating + * system and expressed as a fractional number. + * + * The load average is a Unix-specific concept. On Windows, the return value is + * always `[0, 0, 0]`. + * @since v0.3.3 + */ + function loadavg(): number[]; + /** + * Returns the system uptime in number of seconds. + * @since v0.3.3 + */ + function uptime(): number; + /** + * Returns the amount of free system memory in bytes as an integer. + * @since v0.3.3 + */ + function freemem(): number; + /** + * Returns the total amount of system memory in bytes as an integer. + * @since v0.3.3 + */ + function totalmem(): number; + /** + * Returns an array of objects containing information about each logical CPU core. + * + * The properties included on each object include: + * + * ```js + * [ + * { + * model: 'Intel(R) Core(TM) i7 CPU 860 @ 2.80GHz', + * speed: 2926, + * times: { + * user: 252020, + * nice: 0, + * sys: 30340, + * idle: 1070356870, + * irq: 0 + * } + * }, + * { + * model: 'Intel(R) Core(TM) i7 CPU 860 @ 2.80GHz', + * speed: 2926, + * times: { + * user: 306960, + * nice: 0, + * sys: 26980, + * idle: 1071569080, + * irq: 0 + * } + * }, + * { + * model: 'Intel(R) Core(TM) i7 CPU 860 @ 2.80GHz', + * speed: 2926, + * times: { + * user: 248450, + * nice: 0, + * sys: 21750, + * idle: 1070919370, + * irq: 0 + * } + * }, + * { + * model: 'Intel(R) Core(TM) i7 CPU 860 @ 2.80GHz', + * speed: 2926, + * times: { + * user: 256880, + * nice: 0, + * sys: 19430, + * idle: 1070905480, + * irq: 20 + * } + * }, + * ] + * ``` + * + * `nice` values are POSIX-only. On Windows, the `nice` values of all processors + * are always 0. + * @since v0.3.3 + */ + function cpus(): CpuInfo[]; + /** + * Returns the operating system name as returned by [`uname(3)`](https://linux.die.net/man/3/uname). For example, it + * returns `'Linux'` on Linux, `'Darwin'` on macOS, and `'Windows_NT'` on Windows. + * + * See [https://en.wikipedia.org/wiki/Uname#Examples](https://en.wikipedia.org/wiki/Uname#Examples) for additional information + * about the output of running [`uname(3)`](https://linux.die.net/man/3/uname) on various operating systems. + * @since v0.3.3 + */ + function type(): string; + /** + * Returns the operating system as a string. + * + * On POSIX systems, the operating system release is determined by calling [`uname(3)`](https://linux.die.net/man/3/uname). On Windows, `GetVersionExW()` is used. See + * [https://en.wikipedia.org/wiki/Uname#Examples](https://en.wikipedia.org/wiki/Uname#Examples) for more information. + * @since v0.3.3 + */ + function release(): string; + /** + * Returns an object containing network interfaces that have been assigned a + * network address. + * + * Each key on the returned object identifies a network interface. The associated + * value is an array of objects that each describe an assigned network address. + * + * The properties available on the assigned network address object include: + * + * ```js + * { + * lo: [ + * { + * address: '127.0.0.1', + * netmask: '255.0.0.0', + * family: 'IPv4', + * mac: '00:00:00:00:00:00', + * internal: true, + * cidr: '127.0.0.1/8' + * }, + * { + * address: '::1', + * netmask: 'ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff', + * family: 'IPv6', + * mac: '00:00:00:00:00:00', + * scopeid: 0, + * internal: true, + * cidr: '::1/128' + * } + * ], + * eth0: [ + * { + * address: '192.168.1.108', + * netmask: '255.255.255.0', + * family: 'IPv4', + * mac: '01:02:03:0a:0b:0c', + * internal: false, + * cidr: '192.168.1.108/24' + * }, + * { + * address: 'fe80::a00:27ff:fe4e:66a1', + * netmask: 'ffff:ffff:ffff:ffff::', + * family: 'IPv6', + * mac: '01:02:03:0a:0b:0c', + * scopeid: 1, + * internal: false, + * cidr: 'fe80::a00:27ff:fe4e:66a1/64' + * } + * ] + * } + * ``` + * @since v0.6.0 + */ + function networkInterfaces(): NodeJS.Dict; + /** + * Returns the string path of the current user's home directory. + * + * On POSIX, it uses the `$HOME` environment variable if defined. Otherwise it + * uses the [effective UID](https://en.wikipedia.org/wiki/User_identifier#Effective_user_ID) to look up the user's home directory. + * + * On Windows, it uses the `USERPROFILE` environment variable if defined. + * Otherwise it uses the path to the profile directory of the current user. + * @since v2.3.0 + */ + function homedir(): string; + /** + * Returns information about the currently effective user. On POSIX platforms, + * this is typically a subset of the password file. The returned object includes + * the `username`, `uid`, `gid`, `shell`, and `homedir`. On Windows, the `uid` and`gid` fields are `-1`, and `shell` is `null`. + * + * The value of `homedir` returned by `os.userInfo()` is provided by the operating + * system. This differs from the result of `os.homedir()`, which queries + * environment variables for the home directory before falling back to the + * operating system response. + * + * Throws a `SystemError` if a user has no `username` or `homedir`. + * @since v6.0.0 + */ + function userInfo(options: { encoding: 'buffer' }): UserInfo; + function userInfo(options?: { encoding: BufferEncoding }): UserInfo; + type SignalConstants = { + [key in NodeJS.Signals]: number; + }; + namespace constants { + const UV_UDP_REUSEADDR: number; + namespace signals {} + const signals: SignalConstants; + namespace errno { + const E2BIG: number; + const EACCES: number; + const EADDRINUSE: number; + const EADDRNOTAVAIL: number; + const EAFNOSUPPORT: number; + const EAGAIN: number; + const EALREADY: number; + const EBADF: number; + const EBADMSG: number; + const EBUSY: number; + const ECANCELED: number; + const ECHILD: number; + const ECONNABORTED: number; + const ECONNREFUSED: number; + const ECONNRESET: number; + const EDEADLK: number; + const EDESTADDRREQ: number; + const EDOM: number; + const EDQUOT: number; + const EEXIST: number; + const EFAULT: number; + const EFBIG: number; + const EHOSTUNREACH: number; + const EIDRM: number; + const EILSEQ: number; + const EINPROGRESS: number; + const EINTR: number; + const EINVAL: number; + const EIO: number; + const EISCONN: number; + const EISDIR: number; + const ELOOP: number; + const EMFILE: number; + const EMLINK: number; + const EMSGSIZE: number; + const EMULTIHOP: number; + const ENAMETOOLONG: number; + const ENETDOWN: number; + const ENETRESET: number; + const ENETUNREACH: number; + const ENFILE: number; + const ENOBUFS: number; + const ENODATA: number; + const ENODEV: number; + const ENOENT: number; + const ENOEXEC: number; + const ENOLCK: number; + const ENOLINK: number; + const ENOMEM: number; + const ENOMSG: number; + const ENOPROTOOPT: number; + const ENOSPC: number; + const ENOSR: number; + const ENOSTR: number; + const ENOSYS: number; + const ENOTCONN: number; + const ENOTDIR: number; + const ENOTEMPTY: number; + const ENOTSOCK: number; + const ENOTSUP: number; + const ENOTTY: number; + const ENXIO: number; + const EOPNOTSUPP: number; + const EOVERFLOW: number; + const EPERM: number; + const EPIPE: number; + const EPROTO: number; + const EPROTONOSUPPORT: number; + const EPROTOTYPE: number; + const ERANGE: number; + const EROFS: number; + const ESPIPE: number; + const ESRCH: number; + const ESTALE: number; + const ETIME: number; + const ETIMEDOUT: number; + const ETXTBSY: number; + const EWOULDBLOCK: number; + const EXDEV: number; + const WSAEINTR: number; + const WSAEBADF: number; + const WSAEACCES: number; + const WSAEFAULT: number; + const WSAEINVAL: number; + const WSAEMFILE: number; + const WSAEWOULDBLOCK: number; + const WSAEINPROGRESS: number; + const WSAEALREADY: number; + const WSAENOTSOCK: number; + const WSAEDESTADDRREQ: number; + const WSAEMSGSIZE: number; + const WSAEPROTOTYPE: number; + const WSAENOPROTOOPT: number; + const WSAEPROTONOSUPPORT: number; + const WSAESOCKTNOSUPPORT: number; + const WSAEOPNOTSUPP: number; + const WSAEPFNOSUPPORT: number; + const WSAEAFNOSUPPORT: number; + const WSAEADDRINUSE: number; + const WSAEADDRNOTAVAIL: number; + const WSAENETDOWN: number; + const WSAENETUNREACH: number; + const WSAENETRESET: number; + const WSAECONNABORTED: number; + const WSAECONNRESET: number; + const WSAENOBUFS: number; + const WSAEISCONN: number; + const WSAENOTCONN: number; + const WSAESHUTDOWN: number; + const WSAETOOMANYREFS: number; + const WSAETIMEDOUT: number; + const WSAECONNREFUSED: number; + const WSAELOOP: number; + const WSAENAMETOOLONG: number; + const WSAEHOSTDOWN: number; + const WSAEHOSTUNREACH: number; + const WSAENOTEMPTY: number; + const WSAEPROCLIM: number; + const WSAEUSERS: number; + const WSAEDQUOT: number; + const WSAESTALE: number; + const WSAEREMOTE: number; + const WSASYSNOTREADY: number; + const WSAVERNOTSUPPORTED: number; + const WSANOTINITIALISED: number; + const WSAEDISCON: number; + const WSAENOMORE: number; + const WSAECANCELLED: number; + const WSAEINVALIDPROCTABLE: number; + const WSAEINVALIDPROVIDER: number; + const WSAEPROVIDERFAILEDINIT: number; + const WSASYSCALLFAILURE: number; + const WSASERVICE_NOT_FOUND: number; + const WSATYPE_NOT_FOUND: number; + const WSA_E_NO_MORE: number; + const WSA_E_CANCELLED: number; + const WSAEREFUSED: number; + } + namespace priority { + const PRIORITY_LOW: number; + const PRIORITY_BELOW_NORMAL: number; + const PRIORITY_NORMAL: number; + const PRIORITY_ABOVE_NORMAL: number; + const PRIORITY_HIGH: number; + const PRIORITY_HIGHEST: number; + } + } + const devNull: string; + const EOL: string; + /** + * Returns the operating system CPU architecture for which the Node.js binary was + * compiled. Possible values are `'arm'`, `'arm64'`, `'ia32'`, `'mips'`,`'mipsel'`, `'ppc'`, `'ppc64'`, `'s390'`, `'s390x'`, and `'x64'`. + * + * The return value is equivalent to `process.arch`. + * @since v0.5.0 + */ + function arch(): string; + /** + * Returns a string identifying the kernel version. + * + * On POSIX systems, the operating system release is determined by calling [`uname(3)`](https://linux.die.net/man/3/uname). On Windows, `RtlGetVersion()` is used, and if it is not + * available, `GetVersionExW()` will be used. See [https://en.wikipedia.org/wiki/Uname#Examples](https://en.wikipedia.org/wiki/Uname#Examples) for more information. + * @since v13.11.0, v12.17.0 + */ + function version(): string; + /** + * Returns a string identifying the operating system platform for which + * the Node.js binary was compiled. The value is set at compile time. + * Possible values are `'aix'`, `'darwin'`, `'freebsd'`,`'linux'`,`'openbsd'`, `'sunos'`, and `'win32'`. + * + * The return value is equivalent to `process.platform`. + * + * The value `'android'` may also be returned if Node.js is built on the Android + * operating system. [Android support is experimental](https://github.com/nodejs/node/blob/HEAD/BUILDING.md#androidandroid-based-devices-eg-firefox-os). + * @since v0.5.0 + */ + function platform(): NodeJS.Platform; + /** + * Returns the operating system's default directory for temporary files as a + * string. + * @since v0.9.9 + */ + function tmpdir(): string; + /** + * Returns a string identifying the endianness of the CPU for which the Node.js + * binary was compiled. + * + * Possible values are `'BE'` for big endian and `'LE'` for little endian. + * @since v0.9.4 + */ + function endianness(): 'BE' | 'LE'; + /** + * Returns the scheduling priority for the process specified by `pid`. If `pid` is + * not provided or is `0`, the priority of the current process is returned. + * @since v10.10.0 + * @param [pid=0] The process ID to retrieve scheduling priority for. + */ + function getPriority(pid?: number): number; + /** + * Attempts to set the scheduling priority for the process specified by `pid`. If`pid` is not provided or is `0`, the process ID of the current process is used. + * + * The `priority` input must be an integer between `-20` (high priority) and `19`(low priority). Due to differences between Unix priority levels and Windows + * priority classes, `priority` is mapped to one of six priority constants in`os.constants.priority`. When retrieving a process priority level, this range + * mapping may cause the return value to be slightly different on Windows. To avoid + * confusion, set `priority` to one of the priority constants. + * + * On Windows, setting priority to `PRIORITY_HIGHEST` requires elevated user + * privileges. Otherwise the set priority will be silently reduced to`PRIORITY_HIGH`. + * @since v10.10.0 + * @param [pid=0] The process ID to set scheduling priority for. + * @param priority The scheduling priority to assign to the process. + */ + function setPriority(priority: number): void; + function setPriority(pid: number, priority: number): void; +} +declare module 'node:os' { + export * from 'os'; +} diff --git a/ts-ticket-office-service/node_modules/@types/node/package.json b/ts-ticket-office-service/node_modules/@types/node/package.json new file mode 100755 index 000000000..76a4b968a --- /dev/null +++ b/ts-ticket-office-service/node_modules/@types/node/package.json @@ -0,0 +1,225 @@ +{ + "name": "@types/node", + "version": "18.6.1", + "description": "TypeScript definitions for Node.js", + "homepage": "https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/node", + "license": "MIT", + "contributors": [ + { + "name": "Microsoft TypeScript", + "url": "https://github.com/Microsoft", + "githubUsername": "Microsoft" + }, + { + "name": "DefinitelyTyped", + "url": "https://github.com/DefinitelyTyped", + "githubUsername": "DefinitelyTyped" + }, + { + "name": "Alberto Schiabel", + "url": "https://github.com/jkomyno", + "githubUsername": "jkomyno" + }, + { + "name": "Alvis HT Tang", + "url": "https://github.com/alvis", + "githubUsername": "alvis" + }, + { + "name": "Andrew Makarov", + "url": "https://github.com/r3nya", + "githubUsername": "r3nya" + }, + { + "name": "Benjamin Toueg", + "url": "https://github.com/btoueg", + "githubUsername": "btoueg" + }, + { + "name": "Chigozirim C.", + "url": "https://github.com/smac89", + "githubUsername": "smac89" + }, + { + "name": "David Junger", + "url": "https://github.com/touffy", + "githubUsername": "touffy" + }, + { + "name": "Deividas Bakanas", + "url": "https://github.com/DeividasBakanas", + "githubUsername": "DeividasBakanas" + }, + { + "name": "Eugene Y. Q. Shen", + "url": "https://github.com/eyqs", + "githubUsername": "eyqs" + }, + { + "name": "Hannes Magnusson", + "url": "https://github.com/Hannes-Magnusson-CK", + "githubUsername": "Hannes-Magnusson-CK" + }, + { + "name": "Huw", + "url": "https://github.com/hoo29", + "githubUsername": "hoo29" + }, + { + "name": "Kelvin Jin", + "url": "https://github.com/kjin", + "githubUsername": "kjin" + }, + { + "name": "Klaus Meinhardt", + "url": "https://github.com/ajafff", + "githubUsername": "ajafff" + }, + { + "name": "Lishude", + "url": "https://github.com/islishude", + "githubUsername": "islishude" + }, + { + "name": "Mariusz Wiktorczyk", + "url": "https://github.com/mwiktorczyk", + "githubUsername": "mwiktorczyk" + }, + { + "name": "Mohsen Azimi", + "url": "https://github.com/mohsen1", + "githubUsername": "mohsen1" + }, + { + "name": "Nicolas Even", + "url": "https://github.com/n-e", + "githubUsername": "n-e" + }, + { + "name": "Nikita Galkin", + "url": "https://github.com/galkin", + "githubUsername": "galkin" + }, + { + "name": "Parambir Singh", + "url": "https://github.com/parambirs", + "githubUsername": "parambirs" + }, + { + "name": "Sebastian Silbermann", + "url": "https://github.com/eps1lon", + "githubUsername": "eps1lon" + }, + { + "name": "Simon Schick", + "url": "https://github.com/SimonSchick", + "githubUsername": "SimonSchick" + }, + { + "name": "Thomas den Hollander", + "url": "https://github.com/ThomasdenH", + "githubUsername": "ThomasdenH" + }, + { + "name": "Wilco Bakker", + "url": "https://github.com/WilcoBakker", + "githubUsername": "WilcoBakker" + }, + { + "name": "wwwy3y3", + "url": "https://github.com/wwwy3y3", + "githubUsername": "wwwy3y3" + }, + { + "name": "Samuel Ainsworth", + "url": "https://github.com/samuela", + "githubUsername": "samuela" + }, + { + "name": "Kyle Uehlein", + "url": "https://github.com/kuehlein", + "githubUsername": "kuehlein" + }, + { + "name": "Thanik Bhongbhibhat", + "url": "https://github.com/bhongy", + "githubUsername": "bhongy" + }, + { + "name": "Marcin Kopacz", + "url": "https://github.com/chyzwar", + "githubUsername": "chyzwar" + }, + { + "name": "Trivikram Kamat", + "url": "https://github.com/trivikr", + "githubUsername": "trivikr" + }, + { + "name": "Junxiao Shi", + "url": "https://github.com/yoursunny", + "githubUsername": "yoursunny" + }, + { + "name": "Ilia Baryshnikov", + "url": "https://github.com/qwelias", + "githubUsername": "qwelias" + }, + { + "name": "ExE Boss", + "url": "https://github.com/ExE-Boss", + "githubUsername": "ExE-Boss" + }, + { + "name": "Piotr Błażejewicz", + "url": "https://github.com/peterblazejewicz", + "githubUsername": "peterblazejewicz" + }, + { + "name": "Anna Henningsen", + "url": "https://github.com/addaleax", + "githubUsername": "addaleax" + }, + { + "name": "Victor Perin", + "url": "https://github.com/victorperin", + "githubUsername": "victorperin" + }, + { + "name": "Yongsheng Zhang", + "url": "https://github.com/ZYSzys", + "githubUsername": "ZYSzys" + }, + { + "name": "NodeJS Contributors", + "url": "https://github.com/NodeJS", + "githubUsername": "NodeJS" + }, + { + "name": "Linus Unnebäck", + "url": "https://github.com/LinusU", + "githubUsername": "LinusU" + }, + { + "name": "wafuwafu13", + "url": "https://github.com/wafuwafu13", + "githubUsername": "wafuwafu13" + }, + { + "name": "Matteo Collina", + "url": "https://github.com/mcollina", + "githubUsername": "mcollina" + } + ], + "main": "", + "types": "index.d.ts", + "repository": { + "type": "git", + "url": "https://github.com/DefinitelyTyped/DefinitelyTyped.git", + "directory": "types/node" + }, + "scripts": {}, + "dependencies": {}, + "typesPublisherContentHash": "44e628c188a3b958cbf3478d419ce6106d591da55cf4b80f1d8dffa1caae8bf2", + "typeScriptVersion": "4.0" +} \ No newline at end of file diff --git a/ts-ticket-office-service/node_modules/@types/node/path.d.ts b/ts-ticket-office-service/node_modules/@types/node/path.d.ts new file mode 100755 index 000000000..db6c27a6a --- /dev/null +++ b/ts-ticket-office-service/node_modules/@types/node/path.d.ts @@ -0,0 +1,180 @@ +declare module 'path/posix' { + import path = require('path'); + export = path; +} +declare module 'path/win32' { + import path = require('path'); + export = path; +} +/** + * The `path` module provides utilities for working with file and directory paths. + * It can be accessed using: + * + * ```js + * const path = require('path'); + * ``` + * @see [source](https://github.com/nodejs/node/blob/v18.0.0/lib/path.js) + */ +declare module 'path' { + namespace path { + /** + * A parsed path object generated by path.parse() or consumed by path.format(). + */ + interface ParsedPath { + /** + * The root of the path such as '/' or 'c:\' + */ + root: string; + /** + * The full directory path such as '/home/user/dir' or 'c:\path\dir' + */ + dir: string; + /** + * The file name including extension (if any) such as 'index.html' + */ + base: string; + /** + * The file extension (if any) such as '.html' + */ + ext: string; + /** + * The file name without extension (if any) such as 'index' + */ + name: string; + } + interface FormatInputPathObject { + /** + * The root of the path such as '/' or 'c:\' + */ + root?: string | undefined; + /** + * The full directory path such as '/home/user/dir' or 'c:\path\dir' + */ + dir?: string | undefined; + /** + * The file name including extension (if any) such as 'index.html' + */ + base?: string | undefined; + /** + * The file extension (if any) such as '.html' + */ + ext?: string | undefined; + /** + * The file name without extension (if any) such as 'index' + */ + name?: string | undefined; + } + interface PlatformPath { + /** + * Normalize a string path, reducing '..' and '.' parts. + * When multiple slashes are found, they're replaced by a single one; when the path contains a trailing slash, it is preserved. On Windows backslashes are used. + * + * @param p string path to normalize. + */ + normalize(p: string): string; + /** + * Join all arguments together and normalize the resulting path. + * Arguments must be strings. In v0.8, non-string arguments were silently ignored. In v0.10 and up, an exception is thrown. + * + * @param paths paths to join. + */ + join(...paths: string[]): string; + /** + * The right-most parameter is considered {to}. Other parameters are considered an array of {from}. + * + * Starting from leftmost {from} parameter, resolves {to} to an absolute path. + * + * If {to} isn't already absolute, {from} arguments are prepended in right to left order, + * until an absolute path is found. If after using all {from} paths still no absolute path is found, + * the current working directory is used as well. The resulting path is normalized, + * and trailing slashes are removed unless the path gets resolved to the root directory. + * + * @param pathSegments string paths to join. Non-string arguments are ignored. + */ + resolve(...pathSegments: string[]): string; + /** + * Determines whether {path} is an absolute path. An absolute path will always resolve to the same location, regardless of the working directory. + * + * @param path path to test. + */ + isAbsolute(p: string): boolean; + /** + * Solve the relative path from {from} to {to}. + * At times we have two absolute paths, and we need to derive the relative path from one to the other. This is actually the reverse transform of path.resolve. + */ + relative(from: string, to: string): string; + /** + * Return the directory name of a path. Similar to the Unix dirname command. + * + * @param p the path to evaluate. + */ + dirname(p: string): string; + /** + * Return the last portion of a path. Similar to the Unix basename command. + * Often used to extract the file name from a fully qualified path. + * + * @param p the path to evaluate. + * @param ext optionally, an extension to remove from the result. + */ + basename(p: string, ext?: string): string; + /** + * Return the extension of the path, from the last '.' to end of string in the last portion of the path. + * If there is no '.' in the last portion of the path or the first character of it is '.', then it returns an empty string + * + * @param p the path to evaluate. + */ + extname(p: string): string; + /** + * The platform-specific file separator. '\\' or '/'. + */ + readonly sep: string; + /** + * The platform-specific file delimiter. ';' or ':'. + */ + readonly delimiter: string; + /** + * Returns an object from a path string - the opposite of format(). + * + * @param pathString path to evaluate. + */ + parse(p: string): ParsedPath; + /** + * Returns a path string from an object - the opposite of parse(). + * + * @param pathString path to evaluate. + */ + format(pP: FormatInputPathObject): string; + /** + * On Windows systems only, returns an equivalent namespace-prefixed path for the given path. + * If path is not a string, path will be returned without modifications. + * This method is meaningful only on Windows system. + * On POSIX systems, the method is non-operational and always returns path without modifications. + */ + toNamespacedPath(path: string): string; + /** + * Posix specific pathing. + * Same as parent object on posix. + */ + readonly posix: PlatformPath; + /** + * Windows specific pathing. + * Same as parent object on windows + */ + readonly win32: PlatformPath; + } + } + const path: path.PlatformPath; + export = path; +} +declare module 'node:path' { + import path = require('path'); + export = path; +} +declare module 'node:path/posix' { + import path = require('path/posix'); + export = path; +} +declare module 'node:path/win32' { + import path = require('path/win32'); + export = path; +} diff --git a/ts-ticket-office-service/node_modules/@types/node/perf_hooks.d.ts b/ts-ticket-office-service/node_modules/@types/node/perf_hooks.d.ts new file mode 100755 index 000000000..6c956c1eb --- /dev/null +++ b/ts-ticket-office-service/node_modules/@types/node/perf_hooks.d.ts @@ -0,0 +1,571 @@ +/** + * This module provides an implementation of a subset of the W3C [Web Performance APIs](https://w3c.github.io/perf-timing-primer/) as well as additional APIs for + * Node.js-specific performance measurements. + * + * Node.js supports the following [Web Performance APIs](https://w3c.github.io/perf-timing-primer/): + * + * * [High Resolution Time](https://www.w3.org/TR/hr-time-2) + * * [Performance Timeline](https://w3c.github.io/performance-timeline/) + * * [User Timing](https://www.w3.org/TR/user-timing/) + * + * ```js + * const { PerformanceObserver, performance } = require('perf_hooks'); + * + * const obs = new PerformanceObserver((items) => { + * console.log(items.getEntries()[0].duration); + * performance.clearMarks(); + * }); + * obs.observe({ type: 'measure' }); + * performance.measure('Start to Now'); + * + * performance.mark('A'); + * doSomeLongRunningProcess(() => { + * performance.measure('A to Now', 'A'); + * + * performance.mark('B'); + * performance.measure('A to B', 'A', 'B'); + * }); + * ``` + * @see [source](https://github.com/nodejs/node/blob/v18.0.0/lib/perf_hooks.js) + */ +declare module 'perf_hooks' { + import { AsyncResource } from 'node:async_hooks'; + type EntryType = 'node' | 'mark' | 'measure' | 'gc' | 'function' | 'http2' | 'http'; + interface NodeGCPerformanceDetail { + /** + * When `performanceEntry.entryType` is equal to 'gc', `the performance.kind` property identifies + * the type of garbage collection operation that occurred. + * See perf_hooks.constants for valid values. + */ + readonly kind?: number | undefined; + /** + * When `performanceEntry.entryType` is equal to 'gc', the `performance.flags` + * property contains additional information about garbage collection operation. + * See perf_hooks.constants for valid values. + */ + readonly flags?: number | undefined; + } + /** + * @since v8.5.0 + */ + class PerformanceEntry { + protected constructor(); + /** + * The total number of milliseconds elapsed for this entry. This value will not + * be meaningful for all Performance Entry types. + * @since v8.5.0 + */ + readonly duration: number; + /** + * The name of the performance entry. + * @since v8.5.0 + */ + readonly name: string; + /** + * The high resolution millisecond timestamp marking the starting time of the + * Performance Entry. + * @since v8.5.0 + */ + readonly startTime: number; + /** + * The type of the performance entry. It may be one of: + * + * * `'node'` (Node.js only) + * * `'mark'` (available on the Web) + * * `'measure'` (available on the Web) + * * `'gc'` (Node.js only) + * * `'function'` (Node.js only) + * * `'http2'` (Node.js only) + * * `'http'` (Node.js only) + * @since v8.5.0 + */ + readonly entryType: EntryType; + /** + * Additional detail specific to the `entryType`. + * @since v16.0.0 + */ + readonly detail?: NodeGCPerformanceDetail | unknown | undefined; // TODO: Narrow this based on entry type. + } + /** + * _This property is an extension by Node.js. It is not available in Web browsers._ + * + * Provides timing details for Node.js itself. The constructor of this class + * is not exposed to users. + * @since v8.5.0 + */ + class PerformanceNodeTiming extends PerformanceEntry { + /** + * The high resolution millisecond timestamp at which the Node.js process + * completed bootstrapping. If bootstrapping has not yet finished, the property + * has the value of -1. + * @since v8.5.0 + */ + readonly bootstrapComplete: number; + /** + * The high resolution millisecond timestamp at which the Node.js environment was + * initialized. + * @since v8.5.0 + */ + readonly environment: number; + /** + * The high resolution millisecond timestamp of the amount of time the event loop + * has been idle within the event loop's event provider (e.g. `epoll_wait`). This + * does not take CPU usage into consideration. If the event loop has not yet + * started (e.g., in the first tick of the main script), the property has the + * value of 0. + * @since v14.10.0, v12.19.0 + */ + readonly idleTime: number; + /** + * The high resolution millisecond timestamp at which the Node.js event loop + * exited. If the event loop has not yet exited, the property has the value of -1\. + * It can only have a value of not -1 in a handler of the `'exit'` event. + * @since v8.5.0 + */ + readonly loopExit: number; + /** + * The high resolution millisecond timestamp at which the Node.js event loop + * started. If the event loop has not yet started (e.g., in the first tick of the + * main script), the property has the value of -1. + * @since v8.5.0 + */ + readonly loopStart: number; + /** + * The high resolution millisecond timestamp at which the V8 platform was + * initialized. + * @since v8.5.0 + */ + readonly v8Start: number; + } + interface EventLoopUtilization { + idle: number; + active: number; + utilization: number; + } + /** + * @param util1 The result of a previous call to eventLoopUtilization() + * @param util2 The result of a previous call to eventLoopUtilization() prior to util1 + */ + type EventLoopUtilityFunction = (util1?: EventLoopUtilization, util2?: EventLoopUtilization) => EventLoopUtilization; + interface MarkOptions { + /** + * Additional optional detail to include with the mark. + */ + detail?: unknown | undefined; + /** + * An optional timestamp to be used as the mark time. + * @default `performance.now()`. + */ + startTime?: number | undefined; + } + interface MeasureOptions { + /** + * Additional optional detail to include with the mark. + */ + detail?: unknown | undefined; + /** + * Duration between start and end times. + */ + duration?: number | undefined; + /** + * Timestamp to be used as the end time, or a string identifying a previously recorded mark. + */ + end?: number | string | undefined; + /** + * Timestamp to be used as the start time, or a string identifying a previously recorded mark. + */ + start?: number | string | undefined; + } + interface TimerifyOptions { + /** + * A histogram object created using + * `perf_hooks.createHistogram()` that will record runtime durations in + * nanoseconds. + */ + histogram?: RecordableHistogram | undefined; + } + interface Performance { + /** + * If name is not provided, removes all PerformanceMark objects from the Performance Timeline. + * If name is provided, removes only the named mark. + * @param name + */ + clearMarks(name?: string): void; + /** + * Creates a new PerformanceMark entry in the Performance Timeline. + * A PerformanceMark is a subclass of PerformanceEntry whose performanceEntry.entryType is always 'mark', + * and whose performanceEntry.duration is always 0. + * Performance marks are used to mark specific significant moments in the Performance Timeline. + * @param name + */ + mark(name?: string, options?: MarkOptions): void; + /** + * Creates a new PerformanceMeasure entry in the Performance Timeline. + * A PerformanceMeasure is a subclass of PerformanceEntry whose performanceEntry.entryType is always 'measure', + * and whose performanceEntry.duration measures the number of milliseconds elapsed since startMark and endMark. + * + * The startMark argument may identify any existing PerformanceMark in the the Performance Timeline, or may identify + * any of the timestamp properties provided by the PerformanceNodeTiming class. If the named startMark does not exist, + * then startMark is set to timeOrigin by default. + * + * The endMark argument must identify any existing PerformanceMark in the the Performance Timeline or any of the timestamp + * properties provided by the PerformanceNodeTiming class. If the named endMark does not exist, an error will be thrown. + * @param name + * @param startMark + * @param endMark + */ + measure(name: string, startMark?: string, endMark?: string): void; + measure(name: string, options: MeasureOptions): void; + /** + * An instance of the PerformanceNodeTiming class that provides performance metrics for specific Node.js operational milestones. + */ + readonly nodeTiming: PerformanceNodeTiming; + /** + * @return the current high resolution millisecond timestamp + */ + now(): number; + /** + * The timeOrigin specifies the high resolution millisecond timestamp from which all performance metric durations are measured. + */ + readonly timeOrigin: number; + /** + * Wraps a function within a new function that measures the running time of the wrapped function. + * A PerformanceObserver must be subscribed to the 'function' event type in order for the timing details to be accessed. + * @param fn + */ + timerify any>(fn: T, options?: TimerifyOptions): T; + /** + * eventLoopUtilization is similar to CPU utilization except that it is calculated using high precision wall-clock time. + * It represents the percentage of time the event loop has spent outside the event loop's event provider (e.g. epoll_wait). + * No other CPU idle time is taken into consideration. + */ + eventLoopUtilization: EventLoopUtilityFunction; + } + interface PerformanceObserverEntryList { + /** + * Returns a list of `PerformanceEntry` objects in chronological order + * with respect to `performanceEntry.startTime`. + * + * ```js + * const { + * performance, + * PerformanceObserver + * } = require('perf_hooks'); + * + * const obs = new PerformanceObserver((perfObserverList, observer) => { + * console.log(perfObserverList.getEntries()); + * + * * [ + * * PerformanceEntry { + * * name: 'test', + * * entryType: 'mark', + * * startTime: 81.465639, + * * duration: 0 + * * }, + * * PerformanceEntry { + * * name: 'meow', + * * entryType: 'mark', + * * startTime: 81.860064, + * * duration: 0 + * * } + * * ] + * + * + * performance.clearMarks(); + * performance.clearMeasures(); + * observer.disconnect(); + * }); + * obs.observe({ type: 'mark' }); + * + * performance.mark('test'); + * performance.mark('meow'); + * ``` + * @since v8.5.0 + */ + getEntries(): PerformanceEntry[]; + /** + * Returns a list of `PerformanceEntry` objects in chronological order + * with respect to `performanceEntry.startTime` whose `performanceEntry.name` is + * equal to `name`, and optionally, whose `performanceEntry.entryType` is equal to`type`. + * + * ```js + * const { + * performance, + * PerformanceObserver + * } = require('perf_hooks'); + * + * const obs = new PerformanceObserver((perfObserverList, observer) => { + * console.log(perfObserverList.getEntriesByName('meow')); + * + * * [ + * * PerformanceEntry { + * * name: 'meow', + * * entryType: 'mark', + * * startTime: 98.545991, + * * duration: 0 + * * } + * * ] + * + * console.log(perfObserverList.getEntriesByName('nope')); // [] + * + * console.log(perfObserverList.getEntriesByName('test', 'mark')); + * + * * [ + * * PerformanceEntry { + * * name: 'test', + * * entryType: 'mark', + * * startTime: 63.518931, + * * duration: 0 + * * } + * * ] + * + * console.log(perfObserverList.getEntriesByName('test', 'measure')); // [] + * + * performance.clearMarks(); + * performance.clearMeasures(); + * observer.disconnect(); + * }); + * obs.observe({ entryTypes: ['mark', 'measure'] }); + * + * performance.mark('test'); + * performance.mark('meow'); + * ``` + * @since v8.5.0 + */ + getEntriesByName(name: string, type?: EntryType): PerformanceEntry[]; + /** + * Returns a list of `PerformanceEntry` objects in chronological order + * with respect to `performanceEntry.startTime` whose `performanceEntry.entryType`is equal to `type`. + * + * ```js + * const { + * performance, + * PerformanceObserver + * } = require('perf_hooks'); + * + * const obs = new PerformanceObserver((perfObserverList, observer) => { + * console.log(perfObserverList.getEntriesByType('mark')); + * + * * [ + * * PerformanceEntry { + * * name: 'test', + * * entryType: 'mark', + * * startTime: 55.897834, + * * duration: 0 + * * }, + * * PerformanceEntry { + * * name: 'meow', + * * entryType: 'mark', + * * startTime: 56.350146, + * * duration: 0 + * * } + * * ] + * + * performance.clearMarks(); + * performance.clearMeasures(); + * observer.disconnect(); + * }); + * obs.observe({ type: 'mark' }); + * + * performance.mark('test'); + * performance.mark('meow'); + * ``` + * @since v8.5.0 + */ + getEntriesByType(type: EntryType): PerformanceEntry[]; + } + type PerformanceObserverCallback = (list: PerformanceObserverEntryList, observer: PerformanceObserver) => void; + class PerformanceObserver extends AsyncResource { + constructor(callback: PerformanceObserverCallback); + /** + * Disconnects the `PerformanceObserver` instance from all notifications. + * @since v8.5.0 + */ + disconnect(): void; + /** + * Subscribes the `PerformanceObserver` instance to notifications of new `PerformanceEntry` instances identified either by `options.entryTypes`or `options.type`: + * + * ```js + * const { + * performance, + * PerformanceObserver + * } = require('perf_hooks'); + * + * const obs = new PerformanceObserver((list, observer) => { + * // Called once asynchronously. `list` contains three items. + * }); + * obs.observe({ type: 'mark' }); + * + * for (let n = 0; n < 3; n++) + * performance.mark(`test${n}`); + * ``` + * @since v8.5.0 + */ + observe( + options: + | { + entryTypes: ReadonlyArray; + buffered?: boolean | undefined; + } + | { + type: EntryType; + buffered?: boolean | undefined; + } + ): void; + } + namespace constants { + const NODE_PERFORMANCE_GC_MAJOR: number; + const NODE_PERFORMANCE_GC_MINOR: number; + const NODE_PERFORMANCE_GC_INCREMENTAL: number; + const NODE_PERFORMANCE_GC_WEAKCB: number; + const NODE_PERFORMANCE_GC_FLAGS_NO: number; + const NODE_PERFORMANCE_GC_FLAGS_CONSTRUCT_RETAINED: number; + const NODE_PERFORMANCE_GC_FLAGS_FORCED: number; + const NODE_PERFORMANCE_GC_FLAGS_SYNCHRONOUS_PHANTOM_PROCESSING: number; + const NODE_PERFORMANCE_GC_FLAGS_ALL_AVAILABLE_GARBAGE: number; + const NODE_PERFORMANCE_GC_FLAGS_ALL_EXTERNAL_MEMORY: number; + const NODE_PERFORMANCE_GC_FLAGS_SCHEDULE_IDLE: number; + } + const performance: Performance; + interface EventLoopMonitorOptions { + /** + * The sampling rate in milliseconds. + * Must be greater than zero. + * @default 10 + */ + resolution?: number | undefined; + } + interface Histogram { + /** + * Returns a `Map` object detailing the accumulated percentile distribution. + * @since v11.10.0 + */ + readonly percentiles: Map; + /** + * The number of times the event loop delay exceeded the maximum 1 hour event + * loop delay threshold. + * @since v11.10.0 + */ + readonly exceeds: number; + /** + * The minimum recorded event loop delay. + * @since v11.10.0 + */ + readonly min: number; + /** + * The maximum recorded event loop delay. + * @since v11.10.0 + */ + readonly max: number; + /** + * The mean of the recorded event loop delays. + * @since v11.10.0 + */ + readonly mean: number; + /** + * The standard deviation of the recorded event loop delays. + * @since v11.10.0 + */ + readonly stddev: number; + /** + * Resets the collected histogram data. + * @since v11.10.0 + */ + reset(): void; + /** + * Returns the value at the given percentile. + * @since v11.10.0 + * @param percentile A percentile value in the range (0, 100]. + */ + percentile(percentile: number): number; + } + interface IntervalHistogram extends Histogram { + /** + * Enables the update interval timer. Returns `true` if the timer was + * started, `false` if it was already started. + * @since v11.10.0 + */ + enable(): boolean; + /** + * Disables the update interval timer. Returns `true` if the timer was + * stopped, `false` if it was already stopped. + * @since v11.10.0 + */ + disable(): boolean; + } + interface RecordableHistogram extends Histogram { + /** + * @since v15.9.0, v14.18.0 + * @param val The amount to record in the histogram. + */ + record(val: number | bigint): void; + /** + * Calculates the amount of time (in nanoseconds) that has passed since the + * previous call to `recordDelta()` and records that amount in the histogram. + * + * ## Examples + * @since v15.9.0, v14.18.0 + */ + recordDelta(): void; + /** + * Adds the values from other to this histogram. + * @since v17.4.0, v16.14.0 + * @param other Recordable Histogram to combine with + */ + add(other: RecordableHistogram): void; + } + /** + * _This property is an extension by Node.js. It is not available in Web browsers._ + * + * Creates an `IntervalHistogram` object that samples and reports the event loop + * delay over time. The delays will be reported in nanoseconds. + * + * Using a timer to detect approximate event loop delay works because the + * execution of timers is tied specifically to the lifecycle of the libuv + * event loop. That is, a delay in the loop will cause a delay in the execution + * of the timer, and those delays are specifically what this API is intended to + * detect. + * + * ```js + * const { monitorEventLoopDelay } = require('perf_hooks'); + * const h = monitorEventLoopDelay({ resolution: 20 }); + * h.enable(); + * // Do something. + * h.disable(); + * console.log(h.min); + * console.log(h.max); + * console.log(h.mean); + * console.log(h.stddev); + * console.log(h.percentiles); + * console.log(h.percentile(50)); + * console.log(h.percentile(99)); + * ``` + * @since v11.10.0 + */ + function monitorEventLoopDelay(options?: EventLoopMonitorOptions): IntervalHistogram; + interface CreateHistogramOptions { + /** + * The minimum recordable value. Must be an integer value greater than 0. + * @default 1 + */ + min?: number | bigint | undefined; + /** + * The maximum recordable value. Must be an integer value greater than min. + * @default Number.MAX_SAFE_INTEGER + */ + max?: number | bigint | undefined; + /** + * The number of accuracy digits. Must be a number between 1 and 5. + * @default 3 + */ + figures?: number | undefined; + } + /** + * Returns a `RecordableHistogram`. + * @since v15.9.0, v14.18.0 + */ + function createHistogram(options?: CreateHistogramOptions): RecordableHistogram; +} +declare module 'node:perf_hooks' { + export * from 'perf_hooks'; +} diff --git a/ts-ticket-office-service/node_modules/@types/node/process.d.ts b/ts-ticket-office-service/node_modules/@types/node/process.d.ts new file mode 100755 index 000000000..7f6e66bc9 --- /dev/null +++ b/ts-ticket-office-service/node_modules/@types/node/process.d.ts @@ -0,0 +1,1482 @@ +declare module 'process' { + import * as tty from 'node:tty'; + import { Worker } from 'node:worker_threads'; + global { + var process: NodeJS.Process; + namespace NodeJS { + // this namespace merge is here because these are specifically used + // as the type for process.stdin, process.stdout, and process.stderr. + // they can't live in tty.d.ts because we need to disambiguate the imported name. + interface ReadStream extends tty.ReadStream {} + interface WriteStream extends tty.WriteStream {} + interface MemoryUsageFn { + /** + * The `process.memoryUsage()` method iterate over each page to gather informations about memory + * usage which can be slow depending on the program memory allocations. + */ + (): MemoryUsage; + /** + * method returns an integer representing the Resident Set Size (RSS) in bytes. + */ + rss(): number; + } + interface MemoryUsage { + rss: number; + heapTotal: number; + heapUsed: number; + external: number; + arrayBuffers: number; + } + interface CpuUsage { + user: number; + system: number; + } + interface ProcessRelease { + name: string; + sourceUrl?: string | undefined; + headersUrl?: string | undefined; + libUrl?: string | undefined; + lts?: string | undefined; + } + interface ProcessVersions extends Dict { + http_parser: string; + node: string; + v8: string; + ares: string; + uv: string; + zlib: string; + modules: string; + openssl: string; + } + type Platform = 'aix' | 'android' | 'darwin' | 'freebsd' | 'haiku' | 'linux' | 'openbsd' | 'sunos' | 'win32' | 'cygwin' | 'netbsd'; + type Architecture = 'arm' | 'arm64' | 'ia32' | 'mips' | 'mipsel' | 'ppc' | 'ppc64' | 's390' | 's390x' | 'x64'; + type Signals = + | 'SIGABRT' + | 'SIGALRM' + | 'SIGBUS' + | 'SIGCHLD' + | 'SIGCONT' + | 'SIGFPE' + | 'SIGHUP' + | 'SIGILL' + | 'SIGINT' + | 'SIGIO' + | 'SIGIOT' + | 'SIGKILL' + | 'SIGPIPE' + | 'SIGPOLL' + | 'SIGPROF' + | 'SIGPWR' + | 'SIGQUIT' + | 'SIGSEGV' + | 'SIGSTKFLT' + | 'SIGSTOP' + | 'SIGSYS' + | 'SIGTERM' + | 'SIGTRAP' + | 'SIGTSTP' + | 'SIGTTIN' + | 'SIGTTOU' + | 'SIGUNUSED' + | 'SIGURG' + | 'SIGUSR1' + | 'SIGUSR2' + | 'SIGVTALRM' + | 'SIGWINCH' + | 'SIGXCPU' + | 'SIGXFSZ' + | 'SIGBREAK' + | 'SIGLOST' + | 'SIGINFO'; + type UncaughtExceptionOrigin = 'uncaughtException' | 'unhandledRejection'; + type MultipleResolveType = 'resolve' | 'reject'; + type BeforeExitListener = (code: number) => void; + type DisconnectListener = () => void; + type ExitListener = (code: number) => void; + type RejectionHandledListener = (promise: Promise) => void; + type UncaughtExceptionListener = (error: Error, origin: UncaughtExceptionOrigin) => void; + /** + * Most of the time the unhandledRejection will be an Error, but this should not be relied upon + * as *anything* can be thrown/rejected, it is therefore unsafe to assume the the value is an Error. + */ + type UnhandledRejectionListener = (reason: unknown, promise: Promise) => void; + type WarningListener = (warning: Error) => void; + type MessageListener = (message: unknown, sendHandle: unknown) => void; + type SignalsListener = (signal: Signals) => void; + type MultipleResolveListener = (type: MultipleResolveType, promise: Promise, value: unknown) => void; + type WorkerListener = (worker: Worker) => void; + interface Socket extends ReadWriteStream { + isTTY?: true | undefined; + } + // Alias for compatibility + interface ProcessEnv extends Dict { + /** + * Can be used to change the default timezone at runtime + */ + TZ?: string; + } + interface HRTime { + (time?: [number, number]): [number, number]; + bigint(): bigint; + } + interface ProcessReport { + /** + * Directory where the report is written. + * working directory of the Node.js process. + * @default '' indicating that reports are written to the current + */ + directory: string; + /** + * Filename where the report is written. + * The default value is the empty string. + * @default '' the output filename will be comprised of a timestamp, + * PID, and sequence number. + */ + filename: string; + /** + * Returns a JSON-formatted diagnostic report for the running process. + * The report's JavaScript stack trace is taken from err, if present. + */ + getReport(err?: Error): string; + /** + * If true, a diagnostic report is generated on fatal errors, + * such as out of memory errors or failed C++ assertions. + * @default false + */ + reportOnFatalError: boolean; + /** + * If true, a diagnostic report is generated when the process + * receives the signal specified by process.report.signal. + * @default false + */ + reportOnSignal: boolean; + /** + * If true, a diagnostic report is generated on uncaught exception. + * @default false + */ + reportOnUncaughtException: boolean; + /** + * The signal used to trigger the creation of a diagnostic report. + * @default 'SIGUSR2' + */ + signal: Signals; + /** + * Writes a diagnostic report to a file. If filename is not provided, the default filename + * includes the date, time, PID, and a sequence number. + * The report's JavaScript stack trace is taken from err, if present. + * + * @param fileName Name of the file where the report is written. + * This should be a relative path, that will be appended to the directory specified in + * `process.report.directory`, or the current working directory of the Node.js process, + * if unspecified. + * @param error A custom error used for reporting the JavaScript stack. + * @return Filename of the generated report. + */ + writeReport(fileName?: string): string; + writeReport(error?: Error): string; + writeReport(fileName?: string, err?: Error): string; + } + interface ResourceUsage { + fsRead: number; + fsWrite: number; + involuntaryContextSwitches: number; + ipcReceived: number; + ipcSent: number; + majorPageFault: number; + maxRSS: number; + minorPageFault: number; + sharedMemorySize: number; + signalsCount: number; + swappedOut: number; + systemCPUTime: number; + unsharedDataSize: number; + unsharedStackSize: number; + userCPUTime: number; + voluntaryContextSwitches: number; + } + interface EmitWarningOptions { + /** + * When `warning` is a `string`, `type` is the name to use for the _type_ of warning being emitted. + * + * @default 'Warning' + */ + type?: string | undefined; + /** + * A unique identifier for the warning instance being emitted. + */ + code?: string | undefined; + /** + * When `warning` is a `string`, `ctor` is an optional function used to limit the generated stack trace. + * + * @default process.emitWarning + */ + ctor?: Function | undefined; + /** + * Additional text to include with the error. + */ + detail?: string | undefined; + } + interface ProcessConfig { + readonly target_defaults: { + readonly cflags: any[]; + readonly default_configuration: string; + readonly defines: string[]; + readonly include_dirs: string[]; + readonly libraries: string[]; + }; + readonly variables: { + readonly clang: number; + readonly host_arch: string; + readonly node_install_npm: boolean; + readonly node_install_waf: boolean; + readonly node_prefix: string; + readonly node_shared_openssl: boolean; + readonly node_shared_v8: boolean; + readonly node_shared_zlib: boolean; + readonly node_use_dtrace: boolean; + readonly node_use_etw: boolean; + readonly node_use_openssl: boolean; + readonly target_arch: string; + readonly v8_no_strict_aliasing: number; + readonly v8_use_snapshot: boolean; + readonly visibility: string; + }; + } + interface Process extends EventEmitter { + /** + * The `process.stdout` property returns a stream connected to`stdout` (fd `1`). It is a `net.Socket` (which is a `Duplex` stream) unless fd `1` refers to a file, in which case it is + * a `Writable` stream. + * + * For example, to copy `process.stdin` to `process.stdout`: + * + * ```js + * import { stdin, stdout } from 'process'; + * + * stdin.pipe(stdout); + * ``` + * + * `process.stdout` differs from other Node.js streams in important ways. See `note on process I/O` for more information. + */ + stdout: WriteStream & { + fd: 1; + }; + /** + * The `process.stderr` property returns a stream connected to`stderr` (fd `2`). It is a `net.Socket` (which is a `Duplex` stream) unless fd `2` refers to a file, in which case it is + * a `Writable` stream. + * + * `process.stderr` differs from other Node.js streams in important ways. See `note on process I/O` for more information. + */ + stderr: WriteStream & { + fd: 2; + }; + /** + * The `process.stdin` property returns a stream connected to`stdin` (fd `0`). It is a `net.Socket` (which is a `Duplex` stream) unless fd `0` refers to a file, in which case it is + * a `Readable` stream. + * + * For details of how to read from `stdin` see `readable.read()`. + * + * As a `Duplex` stream, `process.stdin` can also be used in "old" mode that + * is compatible with scripts written for Node.js prior to v0.10\. + * For more information see `Stream compatibility`. + * + * In "old" streams mode the `stdin` stream is paused by default, so one + * must call `process.stdin.resume()` to read from it. Note also that calling`process.stdin.resume()` itself would switch stream to "old" mode. + */ + stdin: ReadStream & { + fd: 0; + }; + openStdin(): Socket; + /** + * The `process.argv` property returns an array containing the command-line + * arguments passed when the Node.js process was launched. The first element will + * be {@link execPath}. See `process.argv0` if access to the original value + * of `argv[0]` is needed. The second element will be the path to the JavaScript + * file being executed. The remaining elements will be any additional command-line + * arguments. + * + * For example, assuming the following script for `process-args.js`: + * + * ```js + * import { argv } from 'process'; + * + * // print process.argv + * argv.forEach((val, index) => { + * console.log(`${index}: ${val}`); + * }); + * ``` + * + * Launching the Node.js process as: + * + * ```console + * $ node process-args.js one two=three four + * ``` + * + * Would generate the output: + * + * ```text + * 0: /usr/local/bin/node + * 1: /Users/mjr/work/node/process-args.js + * 2: one + * 3: two=three + * 4: four + * ``` + * @since v0.1.27 + */ + argv: string[]; + /** + * The `process.argv0` property stores a read-only copy of the original value of`argv[0]` passed when Node.js starts. + * + * ```console + * $ bash -c 'exec -a customArgv0 ./node' + * > process.argv[0] + * '/Volumes/code/external/node/out/Release/node' + * > process.argv0 + * 'customArgv0' + * ``` + * @since v6.4.0 + */ + argv0: string; + /** + * The `process.execArgv` property returns the set of Node.js-specific command-line + * options passed when the Node.js process was launched. These options do not + * appear in the array returned by the {@link argv} property, and do not + * include the Node.js executable, the name of the script, or any options following + * the script name. These options are useful in order to spawn child processes with + * the same execution environment as the parent. + * + * ```console + * $ node --harmony script.js --version + * ``` + * + * Results in `process.execArgv`: + * + * ```js + * ['--harmony'] + * ``` + * + * And `process.argv`: + * + * ```js + * ['/usr/local/bin/node', 'script.js', '--version'] + * ``` + * + * Refer to `Worker constructor` for the detailed behavior of worker + * threads with this property. + * @since v0.7.7 + */ + execArgv: string[]; + /** + * The `process.execPath` property returns the absolute pathname of the executable + * that started the Node.js process. Symbolic links, if any, are resolved. + * + * ```js + * '/usr/local/bin/node' + * ``` + * @since v0.1.100 + */ + execPath: string; + /** + * The `process.abort()` method causes the Node.js process to exit immediately and + * generate a core file. + * + * This feature is not available in `Worker` threads. + * @since v0.7.0 + */ + abort(): never; + /** + * The `process.chdir()` method changes the current working directory of the + * Node.js process or throws an exception if doing so fails (for instance, if + * the specified `directory` does not exist). + * + * ```js + * import { chdir, cwd } from 'process'; + * + * console.log(`Starting directory: ${cwd()}`); + * try { + * chdir('/tmp'); + * console.log(`New directory: ${cwd()}`); + * } catch (err) { + * console.error(`chdir: ${err}`); + * } + * ``` + * + * This feature is not available in `Worker` threads. + * @since v0.1.17 + */ + chdir(directory: string): void; + /** + * The `process.cwd()` method returns the current working directory of the Node.js + * process. + * + * ```js + * import { cwd } from 'process'; + * + * console.log(`Current directory: ${cwd()}`); + * ``` + * @since v0.1.8 + */ + cwd(): string; + /** + * The port used by the Node.js debugger when enabled. + * + * ```js + * import process from 'process'; + * + * process.debugPort = 5858; + * ``` + * @since v0.7.2 + */ + debugPort: number; + /** + * The `process.emitWarning()` method can be used to emit custom or application + * specific process warnings. These can be listened for by adding a handler to the `'warning'` event. + * + * ```js + * import { emitWarning } from 'process'; + * + * // Emit a warning with a code and additional detail. + * emitWarning('Something happened!', { + * code: 'MY_WARNING', + * detail: 'This is some additional information' + * }); + * // Emits: + * // (node:56338) [MY_WARNING] Warning: Something happened! + * // This is some additional information + * ``` + * + * In this example, an `Error` object is generated internally by`process.emitWarning()` and passed through to the `'warning'` handler. + * + * ```js + * import process from 'process'; + * + * process.on('warning', (warning) => { + * console.warn(warning.name); // 'Warning' + * console.warn(warning.message); // 'Something happened!' + * console.warn(warning.code); // 'MY_WARNING' + * console.warn(warning.stack); // Stack trace + * console.warn(warning.detail); // 'This is some additional information' + * }); + * ``` + * + * If `warning` is passed as an `Error` object, the `options` argument is ignored. + * @since v8.0.0 + * @param warning The warning to emit. + */ + emitWarning(warning: string | Error, ctor?: Function): void; + emitWarning(warning: string | Error, type?: string, ctor?: Function): void; + emitWarning(warning: string | Error, type?: string, code?: string, ctor?: Function): void; + emitWarning(warning: string | Error, options?: EmitWarningOptions): void; + /** + * The `process.env` property returns an object containing the user environment. + * See [`environ(7)`](http://man7.org/linux/man-pages/man7/environ.7.html). + * + * An example of this object looks like: + * + * ```js + * { + * TERM: 'xterm-256color', + * SHELL: '/usr/local/bin/bash', + * USER: 'maciej', + * PATH: '~/.bin/:/usr/bin:/bin:/usr/sbin:/sbin:/usr/local/bin', + * PWD: '/Users/maciej', + * EDITOR: 'vim', + * SHLVL: '1', + * HOME: '/Users/maciej', + * LOGNAME: 'maciej', + * _: '/usr/local/bin/node' + * } + * ``` + * + * It is possible to modify this object, but such modifications will not be + * reflected outside the Node.js process, or (unless explicitly requested) + * to other `Worker` threads. + * In other words, the following example would not work: + * + * ```console + * $ node -e 'process.env.foo = "bar"' && echo $foo + * ``` + * + * While the following will: + * + * ```js + * import { env } from 'process'; + * + * env.foo = 'bar'; + * console.log(env.foo); + * ``` + * + * Assigning a property on `process.env` will implicitly convert the value + * to a string. **This behavior is deprecated.** Future versions of Node.js may + * throw an error when the value is not a string, number, or boolean. + * + * ```js + * import { env } from 'process'; + * + * env.test = null; + * console.log(env.test); + * // => 'null' + * env.test = undefined; + * console.log(env.test); + * // => 'undefined' + * ``` + * + * Use `delete` to delete a property from `process.env`. + * + * ```js + * import { env } from 'process'; + * + * env.TEST = 1; + * delete env.TEST; + * console.log(env.TEST); + * // => undefined + * ``` + * + * On Windows operating systems, environment variables are case-insensitive. + * + * ```js + * import { env } from 'process'; + * + * env.TEST = 1; + * console.log(env.test); + * // => 1 + * ``` + * + * Unless explicitly specified when creating a `Worker` instance, + * each `Worker` thread has its own copy of `process.env`, based on its + * parent thread’s `process.env`, or whatever was specified as the `env` option + * to the `Worker` constructor. Changes to `process.env` will not be visible + * across `Worker` threads, and only the main thread can make changes that + * are visible to the operating system or to native add-ons. + * @since v0.1.27 + */ + env: ProcessEnv; + /** + * The `process.exit()` method instructs Node.js to terminate the process + * synchronously with an exit status of `code`. If `code` is omitted, exit uses + * either the 'success' code `0` or the value of `process.exitCode` if it has been + * set. Node.js will not terminate until all the `'exit'` event listeners are + * called. + * + * To exit with a 'failure' code: + * + * ```js + * import { exit } from 'process'; + * + * exit(1); + * ``` + * + * The shell that executed Node.js should see the exit code as `1`. + * + * Calling `process.exit()` will force the process to exit as quickly as possible + * even if there are still asynchronous operations pending that have not yet + * completed fully, including I/O operations to `process.stdout` and`process.stderr`. + * + * In most situations, it is not actually necessary to call `process.exit()`explicitly. The Node.js process will exit on its own _if there is no additional_ + * _work pending_ in the event loop. The `process.exitCode` property can be set to + * tell the process which exit code to use when the process exits gracefully. + * + * For instance, the following example illustrates a _misuse_ of the`process.exit()` method that could lead to data printed to stdout being + * truncated and lost: + * + * ```js + * import { exit } from 'process'; + * + * // This is an example of what *not* to do: + * if (someConditionNotMet()) { + * printUsageToStdout(); + * exit(1); + * } + * ``` + * + * The reason this is problematic is because writes to `process.stdout` in Node.js + * are sometimes _asynchronous_ and may occur over multiple ticks of the Node.js + * event loop. Calling `process.exit()`, however, forces the process to exit_before_ those additional writes to `stdout` can be performed. + * + * Rather than calling `process.exit()` directly, the code _should_ set the`process.exitCode` and allow the process to exit naturally by avoiding + * scheduling any additional work for the event loop: + * + * ```js + * import process from 'process'; + * + * // How to properly set the exit code while letting + * // the process exit gracefully. + * if (someConditionNotMet()) { + * printUsageToStdout(); + * process.exitCode = 1; + * } + * ``` + * + * If it is necessary to terminate the Node.js process due to an error condition, + * throwing an _uncaught_ error and allowing the process to terminate accordingly + * is safer than calling `process.exit()`. + * + * In `Worker` threads, this function stops the current thread rather + * than the current process. + * @since v0.1.13 + * @param [code=0] The exit code. + */ + exit(code?: number): never; + /** + * A number which will be the process exit code, when the process either + * exits gracefully, or is exited via {@link exit} without specifying + * a code. + * + * Specifying a code to {@link exit} will override any + * previous setting of `process.exitCode`. + * @since v0.11.8 + */ + exitCode?: number | undefined; + /** + * The `process.getgid()` method returns the numerical group identity of the + * process. (See [`getgid(2)`](http://man7.org/linux/man-pages/man2/getgid.2.html).) + * + * ```js + * import process from 'process'; + * + * if (process.getgid) { + * console.log(`Current gid: ${process.getgid()}`); + * } + * ``` + * + * This function is only available on POSIX platforms (i.e. not Windows or + * Android). + * @since v0.1.31 + */ + getgid?: () => number; + /** + * The `process.setgid()` method sets the group identity of the process. (See [`setgid(2)`](http://man7.org/linux/man-pages/man2/setgid.2.html).) The `id` can be passed as either a + * numeric ID or a group name + * string. If a group name is specified, this method blocks while resolving the + * associated numeric ID. + * + * ```js + * import process from 'process'; + * + * if (process.getgid && process.setgid) { + * console.log(`Current gid: ${process.getgid()}`); + * try { + * process.setgid(501); + * console.log(`New gid: ${process.getgid()}`); + * } catch (err) { + * console.log(`Failed to set gid: ${err}`); + * } + * } + * ``` + * + * This function is only available on POSIX platforms (i.e. not Windows or + * Android). + * This feature is not available in `Worker` threads. + * @since v0.1.31 + * @param id The group name or ID + */ + setgid?: (id: number | string) => void; + /** + * The `process.getuid()` method returns the numeric user identity of the process. + * (See [`getuid(2)`](http://man7.org/linux/man-pages/man2/getuid.2.html).) + * + * ```js + * import process from 'process'; + * + * if (process.getuid) { + * console.log(`Current uid: ${process.getuid()}`); + * } + * ``` + * + * This function is only available on POSIX platforms (i.e. not Windows or + * Android). + * @since v0.1.28 + */ + getuid?: () => number; + /** + * The `process.setuid(id)` method sets the user identity of the process. (See [`setuid(2)`](http://man7.org/linux/man-pages/man2/setuid.2.html).) The `id` can be passed as either a + * numeric ID or a username string. + * If a username is specified, the method blocks while resolving the associated + * numeric ID. + * + * ```js + * import process from 'process'; + * + * if (process.getuid && process.setuid) { + * console.log(`Current uid: ${process.getuid()}`); + * try { + * process.setuid(501); + * console.log(`New uid: ${process.getuid()}`); + * } catch (err) { + * console.log(`Failed to set uid: ${err}`); + * } + * } + * ``` + * + * This function is only available on POSIX platforms (i.e. not Windows or + * Android). + * This feature is not available in `Worker` threads. + * @since v0.1.28 + */ + setuid?: (id: number | string) => void; + /** + * The `process.geteuid()` method returns the numerical effective user identity of + * the process. (See [`geteuid(2)`](http://man7.org/linux/man-pages/man2/geteuid.2.html).) + * + * ```js + * import process from 'process'; + * + * if (process.geteuid) { + * console.log(`Current uid: ${process.geteuid()}`); + * } + * ``` + * + * This function is only available on POSIX platforms (i.e. not Windows or + * Android). + * @since v2.0.0 + */ + geteuid?: () => number; + /** + * The `process.seteuid()` method sets the effective user identity of the process. + * (See [`seteuid(2)`](http://man7.org/linux/man-pages/man2/seteuid.2.html).) The `id` can be passed as either a numeric ID or a username + * string. If a username is specified, the method blocks while resolving the + * associated numeric ID. + * + * ```js + * import process from 'process'; + * + * if (process.geteuid && process.seteuid) { + * console.log(`Current uid: ${process.geteuid()}`); + * try { + * process.seteuid(501); + * console.log(`New uid: ${process.geteuid()}`); + * } catch (err) { + * console.log(`Failed to set uid: ${err}`); + * } + * } + * ``` + * + * This function is only available on POSIX platforms (i.e. not Windows or + * Android). + * This feature is not available in `Worker` threads. + * @since v2.0.0 + * @param id A user name or ID + */ + seteuid?: (id: number | string) => void; + /** + * The `process.getegid()` method returns the numerical effective group identity + * of the Node.js process. (See [`getegid(2)`](http://man7.org/linux/man-pages/man2/getegid.2.html).) + * + * ```js + * import process from 'process'; + * + * if (process.getegid) { + * console.log(`Current gid: ${process.getegid()}`); + * } + * ``` + * + * This function is only available on POSIX platforms (i.e. not Windows or + * Android). + * @since v2.0.0 + */ + getegid?: () => number; + /** + * The `process.setegid()` method sets the effective group identity of the process. + * (See [`setegid(2)`](http://man7.org/linux/man-pages/man2/setegid.2.html).) The `id` can be passed as either a numeric ID or a group + * name string. If a group name is specified, this method blocks while resolving + * the associated a numeric ID. + * + * ```js + * import process from 'process'; + * + * if (process.getegid && process.setegid) { + * console.log(`Current gid: ${process.getegid()}`); + * try { + * process.setegid(501); + * console.log(`New gid: ${process.getegid()}`); + * } catch (err) { + * console.log(`Failed to set gid: ${err}`); + * } + * } + * ``` + * + * This function is only available on POSIX platforms (i.e. not Windows or + * Android). + * This feature is not available in `Worker` threads. + * @since v2.0.0 + * @param id A group name or ID + */ + setegid?: (id: number | string) => void; + /** + * The `process.getgroups()` method returns an array with the supplementary group + * IDs. POSIX leaves it unspecified if the effective group ID is included but + * Node.js ensures it always is. + * + * ```js + * import process from 'process'; + * + * if (process.getgroups) { + * console.log(process.getgroups()); // [ 16, 21, 297 ] + * } + * ``` + * + * This function is only available on POSIX platforms (i.e. not Windows or + * Android). + * @since v0.9.4 + */ + getgroups?: () => number[]; + /** + * The `process.setgroups()` method sets the supplementary group IDs for the + * Node.js process. This is a privileged operation that requires the Node.js + * process to have `root` or the `CAP_SETGID` capability. + * + * The `groups` array can contain numeric group IDs, group names, or both. + * + * ```js + * import process from 'process'; + * + * if (process.getgroups && process.setgroups) { + * try { + * process.setgroups([501]); + * console.log(process.getgroups()); // new groups + * } catch (err) { + * console.log(`Failed to set groups: ${err}`); + * } + * } + * ``` + * + * This function is only available on POSIX platforms (i.e. not Windows or + * Android). + * This feature is not available in `Worker` threads. + * @since v0.9.4 + */ + setgroups?: (groups: ReadonlyArray) => void; + /** + * The `process.setUncaughtExceptionCaptureCallback()` function sets a function + * that will be invoked when an uncaught exception occurs, which will receive the + * exception value itself as its first argument. + * + * If such a function is set, the `'uncaughtException'` event will + * not be emitted. If `--abort-on-uncaught-exception` was passed from the + * command line or set through `v8.setFlagsFromString()`, the process will + * not abort. Actions configured to take place on exceptions such as report + * generations will be affected too + * + * To unset the capture function,`process.setUncaughtExceptionCaptureCallback(null)` may be used. Calling this + * method with a non-`null` argument while another capture function is set will + * throw an error. + * + * Using this function is mutually exclusive with using the deprecated `domain` built-in module. + * @since v9.3.0 + */ + setUncaughtExceptionCaptureCallback(cb: ((err: Error) => void) | null): void; + /** + * Indicates whether a callback has been set using {@link setUncaughtExceptionCaptureCallback}. + * @since v9.3.0 + */ + hasUncaughtExceptionCaptureCallback(): boolean; + /** + * The `process.version` property contains the Node.js version string. + * + * ```js + * import { version } from 'process'; + * + * console.log(`Version: ${version}`); + * // Version: v14.8.0 + * ``` + * + * To get the version string without the prepended _v_, use`process.versions.node`. + * @since v0.1.3 + */ + readonly version: string; + /** + * The `process.versions` property returns an object listing the version strings of + * Node.js and its dependencies. `process.versions.modules` indicates the current + * ABI version, which is increased whenever a C++ API changes. Node.js will refuse + * to load modules that were compiled against a different module ABI version. + * + * ```js + * import { versions } from 'process'; + * + * console.log(versions); + * ``` + * + * Will generate an object similar to: + * + * ```console + * { node: '11.13.0', + * v8: '7.0.276.38-node.18', + * uv: '1.27.0', + * zlib: '1.2.11', + * brotli: '1.0.7', + * ares: '1.15.0', + * modules: '67', + * nghttp2: '1.34.0', + * napi: '4', + * llhttp: '1.1.1', + * openssl: '1.1.1b', + * cldr: '34.0', + * icu: '63.1', + * tz: '2018e', + * unicode: '11.0' } + * ``` + * @since v0.2.0 + */ + readonly versions: ProcessVersions; + /** + * The `process.config` property returns an `Object` containing the JavaScript + * representation of the configure options used to compile the current Node.js + * executable. This is the same as the `config.gypi` file that was produced when + * running the `./configure` script. + * + * An example of the possible output looks like: + * + * ```js + * { + * target_defaults: + * { cflags: [], + * default_configuration: 'Release', + * defines: [], + * include_dirs: [], + * libraries: [] }, + * variables: + * { + * host_arch: 'x64', + * napi_build_version: 5, + * node_install_npm: 'true', + * node_prefix: '', + * node_shared_cares: 'false', + * node_shared_http_parser: 'false', + * node_shared_libuv: 'false', + * node_shared_zlib: 'false', + * node_use_dtrace: 'false', + * node_use_openssl: 'true', + * node_shared_openssl: 'false', + * strict_aliasing: 'true', + * target_arch: 'x64', + * v8_use_snapshot: 1 + * } + * } + * ``` + * + * The `process.config` property is **not** read-only and there are existing + * modules in the ecosystem that are known to extend, modify, or entirely replace + * the value of `process.config`. + * + * Modifying the `process.config` property, or any child-property of the`process.config` object has been deprecated. The `process.config` will be made + * read-only in a future release. + * @since v0.7.7 + */ + readonly config: ProcessConfig; + /** + * The `process.kill()` method sends the `signal` to the process identified by`pid`. + * + * Signal names are strings such as `'SIGINT'` or `'SIGHUP'`. See `Signal Events` and [`kill(2)`](http://man7.org/linux/man-pages/man2/kill.2.html) for more information. + * + * This method will throw an error if the target `pid` does not exist. As a special + * case, a signal of `0` can be used to test for the existence of a process. + * Windows platforms will throw an error if the `pid` is used to kill a process + * group. + * + * Even though the name of this function is `process.kill()`, it is really just a + * signal sender, like the `kill` system call. The signal sent may do something + * other than kill the target process. + * + * ```js + * import process, { kill } from 'process'; + * + * process.on('SIGHUP', () => { + * console.log('Got SIGHUP signal.'); + * }); + * + * setTimeout(() => { + * console.log('Exiting.'); + * process.exit(0); + * }, 100); + * + * kill(process.pid, 'SIGHUP'); + * ``` + * + * When `SIGUSR1` is received by a Node.js process, Node.js will start the + * debugger. See `Signal Events`. + * @since v0.0.6 + * @param pid A process ID + * @param [signal='SIGTERM'] The signal to send, either as a string or number. + */ + kill(pid: number, signal?: string | number): true; + /** + * The `process.pid` property returns the PID of the process. + * + * ```js + * import { pid } from 'process'; + * + * console.log(`This process is pid ${pid}`); + * ``` + * @since v0.1.15 + */ + readonly pid: number; + /** + * The `process.ppid` property returns the PID of the parent of the + * current process. + * + * ```js + * import { ppid } from 'process'; + * + * console.log(`The parent process is pid ${ppid}`); + * ``` + * @since v9.2.0, v8.10.0, v6.13.0 + */ + readonly ppid: number; + /** + * The `process.title` property returns the current process title (i.e. returns + * the current value of `ps`). Assigning a new value to `process.title` modifies + * the current value of `ps`. + * + * When a new value is assigned, different platforms will impose different maximum + * length restrictions on the title. Usually such restrictions are quite limited. + * For instance, on Linux and macOS, `process.title` is limited to the size of the + * binary name plus the length of the command-line arguments because setting the`process.title` overwrites the `argv` memory of the process. Node.js v0.8 + * allowed for longer process title strings by also overwriting the `environ`memory but that was potentially insecure and confusing in some (rather obscure) + * cases. + * + * Assigning a value to `process.title` might not result in an accurate label + * within process manager applications such as macOS Activity Monitor or Windows + * Services Manager. + * @since v0.1.104 + */ + title: string; + /** + * The operating system CPU architecture for which the Node.js binary was compiled. + * Possible values are: `'arm'`, `'arm64'`, `'ia32'`, `'mips'`,`'mipsel'`, `'ppc'`,`'ppc64'`, `'s390'`, `'s390x'`, and `'x64'`. + * + * ```js + * import { arch } from 'process'; + * + * console.log(`This processor architecture is ${arch}`); + * ``` + * @since v0.5.0 + */ + readonly arch: Architecture; + /** + * The `process.platform` property returns a string identifying the operating + * system platform for which the Node.js binary was compiled. + * + * Currently possible values are: + * + * * `'aix'` + * * `'darwin'` + * * `'freebsd'` + * * `'linux'` + * * `'openbsd'` + * * `'sunos'` + * * `'win32'` + * + * ```js + * import { platform } from 'process'; + * + * console.log(`This platform is ${platform}`); + * ``` + * + * The value `'android'` may also be returned if the Node.js is built on the + * Android operating system. However, Android support in Node.js [is experimental](https://github.com/nodejs/node/blob/HEAD/BUILDING.md#androidandroid-based-devices-eg-firefox-os). + * @since v0.1.16 + */ + readonly platform: Platform; + /** + * The `process.mainModule` property provides an alternative way of retrieving `require.main`. The difference is that if the main module changes at + * runtime, `require.main` may still refer to the original main module in + * modules that were required before the change occurred. Generally, it's + * safe to assume that the two refer to the same module. + * + * As with `require.main`, `process.mainModule` will be `undefined` if there + * is no entry script. + * @since v0.1.17 + * @deprecated Since v14.0.0 - Use `main` instead. + */ + mainModule?: Module | undefined; + memoryUsage: MemoryUsageFn; + /** + * The `process.cpuUsage()` method returns the user and system CPU time usage of + * the current process, in an object with properties `user` and `system`, whose + * values are microsecond values (millionth of a second). These values measure time + * spent in user and system code respectively, and may end up being greater than + * actual elapsed time if multiple CPU cores are performing work for this process. + * + * The result of a previous call to `process.cpuUsage()` can be passed as the + * argument to the function, to get a diff reading. + * + * ```js + * import { cpuUsage } from 'process'; + * + * const startUsage = cpuUsage(); + * // { user: 38579, system: 6986 } + * + * // spin the CPU for 500 milliseconds + * const now = Date.now(); + * while (Date.now() - now < 500); + * + * console.log(cpuUsage(startUsage)); + * // { user: 514883, system: 11226 } + * ``` + * @since v6.1.0 + * @param previousValue A previous return value from calling `process.cpuUsage()` + */ + cpuUsage(previousValue?: CpuUsage): CpuUsage; + /** + * `process.nextTick()` adds `callback` to the "next tick queue". This queue is + * fully drained after the current operation on the JavaScript stack runs to + * completion and before the event loop is allowed to continue. It's possible to + * create an infinite loop if one were to recursively call `process.nextTick()`. + * See the [Event Loop](https://nodejs.org/en/docs/guides/event-loop-timers-and-nexttick/#process-nexttick) guide for more background. + * + * ```js + * import { nextTick } from 'process'; + * + * console.log('start'); + * nextTick(() => { + * console.log('nextTick callback'); + * }); + * console.log('scheduled'); + * // Output: + * // start + * // scheduled + * // nextTick callback + * ``` + * + * This is important when developing APIs in order to give users the opportunity + * to assign event handlers _after_ an object has been constructed but before any + * I/O has occurred: + * + * ```js + * import { nextTick } from 'process'; + * + * function MyThing(options) { + * this.setupOptions(options); + * + * nextTick(() => { + * this.startDoingStuff(); + * }); + * } + * + * const thing = new MyThing(); + * thing.getReadyForStuff(); + * + * // thing.startDoingStuff() gets called now, not before. + * ``` + * + * It is very important for APIs to be either 100% synchronous or 100% + * asynchronous. Consider this example: + * + * ```js + * // WARNING! DO NOT USE! BAD UNSAFE HAZARD! + * function maybeSync(arg, cb) { + * if (arg) { + * cb(); + * return; + * } + * + * fs.stat('file', cb); + * } + * ``` + * + * This API is hazardous because in the following case: + * + * ```js + * const maybeTrue = Math.random() > 0.5; + * + * maybeSync(maybeTrue, () => { + * foo(); + * }); + * + * bar(); + * ``` + * + * It is not clear whether `foo()` or `bar()` will be called first. + * + * The following approach is much better: + * + * ```js + * import { nextTick } from 'process'; + * + * function definitelyAsync(arg, cb) { + * if (arg) { + * nextTick(cb); + * return; + * } + * + * fs.stat('file', cb); + * } + * ``` + * @since v0.1.26 + * @param args Additional arguments to pass when invoking the `callback` + */ + nextTick(callback: Function, ...args: any[]): void; + /** + * The `process.release` property returns an `Object` containing metadata related + * to the current release, including URLs for the source tarball and headers-only + * tarball. + * + * `process.release` contains the following properties: + * + * ```js + * { + * name: 'node', + * lts: 'Erbium', + * sourceUrl: 'https://nodejs.org/download/release/v12.18.1/node-v12.18.1.tar.gz', + * headersUrl: 'https://nodejs.org/download/release/v12.18.1/node-v12.18.1-headers.tar.gz', + * libUrl: 'https://nodejs.org/download/release/v12.18.1/win-x64/node.lib' + * } + * ``` + * + * In custom builds from non-release versions of the source tree, only the`name` property may be present. The additional properties should not be + * relied upon to exist. + * @since v3.0.0 + */ + readonly release: ProcessRelease; + features: { + inspector: boolean; + debug: boolean; + uv: boolean; + ipv6: boolean; + tls_alpn: boolean; + tls_sni: boolean; + tls_ocsp: boolean; + tls: boolean; + }; + /** + * `process.umask()` returns the Node.js process's file mode creation mask. Child + * processes inherit the mask from the parent process. + * @since v0.1.19 + * @deprecated Calling `process.umask()` with no argument causes the process-wide umask to be written twice. This introduces a race condition between threads, and is a potential * + * security vulnerability. There is no safe, cross-platform alternative API. + */ + umask(): number; + /** + * Can only be set if not in worker thread. + */ + umask(mask: string | number): number; + /** + * The `process.uptime()` method returns the number of seconds the current Node.js + * process has been running. + * + * The return value includes fractions of a second. Use `Math.floor()` to get whole + * seconds. + * @since v0.5.0 + */ + uptime(): number; + hrtime: HRTime; + /** + * If Node.js is spawned with an IPC channel, the `process.send()` method can be + * used to send messages to the parent process. Messages will be received as a `'message'` event on the parent's `ChildProcess` object. + * + * If Node.js was not spawned with an IPC channel, `process.send` will be`undefined`. + * + * The message goes through serialization and parsing. The resulting message might + * not be the same as what is originally sent. + * @since v0.5.9 + * @param options used to parameterize the sending of certain types of handles.`options` supports the following properties: + */ + send?( + message: any, + sendHandle?: any, + options?: { + swallowErrors?: boolean | undefined; + }, + callback?: (error: Error | null) => void + ): boolean; + /** + * If the Node.js process is spawned with an IPC channel (see the `Child Process` and `Cluster` documentation), the `process.disconnect()` method will close the + * IPC channel to the parent process, allowing the child process to exit gracefully + * once there are no other connections keeping it alive. + * + * The effect of calling `process.disconnect()` is the same as calling `ChildProcess.disconnect()` from the parent process. + * + * If the Node.js process was not spawned with an IPC channel,`process.disconnect()` will be `undefined`. + * @since v0.7.2 + */ + disconnect(): void; + /** + * If the Node.js process is spawned with an IPC channel (see the `Child Process` and `Cluster` documentation), the `process.connected` property will return`true` so long as the IPC + * channel is connected and will return `false` after`process.disconnect()` is called. + * + * Once `process.connected` is `false`, it is no longer possible to send messages + * over the IPC channel using `process.send()`. + * @since v0.7.2 + */ + connected: boolean; + /** + * The `process.allowedNodeEnvironmentFlags` property is a special, + * read-only `Set` of flags allowable within the `NODE_OPTIONS` environment variable. + * + * `process.allowedNodeEnvironmentFlags` extends `Set`, but overrides`Set.prototype.has` to recognize several different possible flag + * representations. `process.allowedNodeEnvironmentFlags.has()` will + * return `true` in the following cases: + * + * * Flags may omit leading single (`-`) or double (`--`) dashes; e.g.,`inspect-brk` for `--inspect-brk`, or `r` for `-r`. + * * Flags passed through to V8 (as listed in `--v8-options`) may replace + * one or more _non-leading_ dashes for an underscore, or vice-versa; + * e.g., `--perf_basic_prof`, `--perf-basic-prof`, `--perf_basic-prof`, + * etc. + * * Flags may contain one or more equals (`=`) characters; all + * characters after and including the first equals will be ignored; + * e.g., `--stack-trace-limit=100`. + * * Flags _must_ be allowable within `NODE_OPTIONS`. + * + * When iterating over `process.allowedNodeEnvironmentFlags`, flags will + * appear only _once_; each will begin with one or more dashes. Flags + * passed through to V8 will contain underscores instead of non-leading + * dashes: + * + * ```js + * import { allowedNodeEnvironmentFlags } from 'process'; + * + * allowedNodeEnvironmentFlags.forEach((flag) => { + * // -r + * // --inspect-brk + * // --abort_on_uncaught_exception + * // ... + * }); + * ``` + * + * The methods `add()`, `clear()`, and `delete()` of`process.allowedNodeEnvironmentFlags` do nothing, and will fail + * silently. + * + * If Node.js was compiled _without_ `NODE_OPTIONS` support (shown in {@link config}), `process.allowedNodeEnvironmentFlags` will + * contain what _would have_ been allowable. + * @since v10.10.0 + */ + allowedNodeEnvironmentFlags: ReadonlySet; + /** + * `process.report` is an object whose methods are used to generate diagnostic + * reports for the current process. Additional documentation is available in the `report documentation`. + * @since v11.8.0 + */ + report?: ProcessReport | undefined; + /** + * ```js + * import { resourceUsage } from 'process'; + * + * console.log(resourceUsage()); + * /* + * Will output: + * { + * userCPUTime: 82872, + * systemCPUTime: 4143, + * maxRSS: 33164, + * sharedMemorySize: 0, + * unsharedDataSize: 0, + * unsharedStackSize: 0, + * minorPageFault: 2469, + * majorPageFault: 0, + * swappedOut: 0, + * fsRead: 0, + * fsWrite: 8, + * ipcSent: 0, + * ipcReceived: 0, + * signalsCount: 0, + * voluntaryContextSwitches: 79, + * involuntaryContextSwitches: 1 + * } + * + * ``` + * @since v12.6.0 + * @return the resource usage for the current process. All of these values come from the `uv_getrusage` call which returns a [`uv_rusage_t` struct][uv_rusage_t]. + */ + resourceUsage(): ResourceUsage; + /** + * The `process.traceDeprecation` property indicates whether the`--trace-deprecation` flag is set on the current Node.js process. See the + * documentation for the `'warning' event` and the `emitWarning() method` for more information about this + * flag's behavior. + * @since v0.8.0 + */ + traceDeprecation: boolean; + /* EventEmitter */ + addListener(event: 'beforeExit', listener: BeforeExitListener): this; + addListener(event: 'disconnect', listener: DisconnectListener): this; + addListener(event: 'exit', listener: ExitListener): this; + addListener(event: 'rejectionHandled', listener: RejectionHandledListener): this; + addListener(event: 'uncaughtException', listener: UncaughtExceptionListener): this; + addListener(event: 'uncaughtExceptionMonitor', listener: UncaughtExceptionListener): this; + addListener(event: 'unhandledRejection', listener: UnhandledRejectionListener): this; + addListener(event: 'warning', listener: WarningListener): this; + addListener(event: 'message', listener: MessageListener): this; + addListener(event: Signals, listener: SignalsListener): this; + addListener(event: 'multipleResolves', listener: MultipleResolveListener): this; + addListener(event: 'worker', listener: WorkerListener): this; + emit(event: 'beforeExit', code: number): boolean; + emit(event: 'disconnect'): boolean; + emit(event: 'exit', code: number): boolean; + emit(event: 'rejectionHandled', promise: Promise): boolean; + emit(event: 'uncaughtException', error: Error): boolean; + emit(event: 'uncaughtExceptionMonitor', error: Error): boolean; + emit(event: 'unhandledRejection', reason: unknown, promise: Promise): boolean; + emit(event: 'warning', warning: Error): boolean; + emit(event: 'message', message: unknown, sendHandle: unknown): this; + emit(event: Signals, signal?: Signals): boolean; + emit(event: 'multipleResolves', type: MultipleResolveType, promise: Promise, value: unknown): this; + emit(event: 'worker', listener: WorkerListener): this; + on(event: 'beforeExit', listener: BeforeExitListener): this; + on(event: 'disconnect', listener: DisconnectListener): this; + on(event: 'exit', listener: ExitListener): this; + on(event: 'rejectionHandled', listener: RejectionHandledListener): this; + on(event: 'uncaughtException', listener: UncaughtExceptionListener): this; + on(event: 'uncaughtExceptionMonitor', listener: UncaughtExceptionListener): this; + on(event: 'unhandledRejection', listener: UnhandledRejectionListener): this; + on(event: 'warning', listener: WarningListener): this; + on(event: 'message', listener: MessageListener): this; + on(event: Signals, listener: SignalsListener): this; + on(event: 'multipleResolves', listener: MultipleResolveListener): this; + on(event: 'worker', listener: WorkerListener): this; + on(event: string | symbol, listener: (...args: any[]) => void): this; + once(event: 'beforeExit', listener: BeforeExitListener): this; + once(event: 'disconnect', listener: DisconnectListener): this; + once(event: 'exit', listener: ExitListener): this; + once(event: 'rejectionHandled', listener: RejectionHandledListener): this; + once(event: 'uncaughtException', listener: UncaughtExceptionListener): this; + once(event: 'uncaughtExceptionMonitor', listener: UncaughtExceptionListener): this; + once(event: 'unhandledRejection', listener: UnhandledRejectionListener): this; + once(event: 'warning', listener: WarningListener): this; + once(event: 'message', listener: MessageListener): this; + once(event: Signals, listener: SignalsListener): this; + once(event: 'multipleResolves', listener: MultipleResolveListener): this; + once(event: 'worker', listener: WorkerListener): this; + once(event: string | symbol, listener: (...args: any[]) => void): this; + prependListener(event: 'beforeExit', listener: BeforeExitListener): this; + prependListener(event: 'disconnect', listener: DisconnectListener): this; + prependListener(event: 'exit', listener: ExitListener): this; + prependListener(event: 'rejectionHandled', listener: RejectionHandledListener): this; + prependListener(event: 'uncaughtException', listener: UncaughtExceptionListener): this; + prependListener(event: 'uncaughtExceptionMonitor', listener: UncaughtExceptionListener): this; + prependListener(event: 'unhandledRejection', listener: UnhandledRejectionListener): this; + prependListener(event: 'warning', listener: WarningListener): this; + prependListener(event: 'message', listener: MessageListener): this; + prependListener(event: Signals, listener: SignalsListener): this; + prependListener(event: 'multipleResolves', listener: MultipleResolveListener): this; + prependListener(event: 'worker', listener: WorkerListener): this; + prependOnceListener(event: 'beforeExit', listener: BeforeExitListener): this; + prependOnceListener(event: 'disconnect', listener: DisconnectListener): this; + prependOnceListener(event: 'exit', listener: ExitListener): this; + prependOnceListener(event: 'rejectionHandled', listener: RejectionHandledListener): this; + prependOnceListener(event: 'uncaughtException', listener: UncaughtExceptionListener): this; + prependOnceListener(event: 'uncaughtExceptionMonitor', listener: UncaughtExceptionListener): this; + prependOnceListener(event: 'unhandledRejection', listener: UnhandledRejectionListener): this; + prependOnceListener(event: 'warning', listener: WarningListener): this; + prependOnceListener(event: 'message', listener: MessageListener): this; + prependOnceListener(event: Signals, listener: SignalsListener): this; + prependOnceListener(event: 'multipleResolves', listener: MultipleResolveListener): this; + prependOnceListener(event: 'worker', listener: WorkerListener): this; + listeners(event: 'beforeExit'): BeforeExitListener[]; + listeners(event: 'disconnect'): DisconnectListener[]; + listeners(event: 'exit'): ExitListener[]; + listeners(event: 'rejectionHandled'): RejectionHandledListener[]; + listeners(event: 'uncaughtException'): UncaughtExceptionListener[]; + listeners(event: 'uncaughtExceptionMonitor'): UncaughtExceptionListener[]; + listeners(event: 'unhandledRejection'): UnhandledRejectionListener[]; + listeners(event: 'warning'): WarningListener[]; + listeners(event: 'message'): MessageListener[]; + listeners(event: Signals): SignalsListener[]; + listeners(event: 'multipleResolves'): MultipleResolveListener[]; + listeners(event: 'worker'): WorkerListener[]; + } + } + } + export = process; +} +declare module 'node:process' { + import process = require('process'); + export = process; +} diff --git a/ts-ticket-office-service/node_modules/@types/node/punycode.d.ts b/ts-ticket-office-service/node_modules/@types/node/punycode.d.ts new file mode 100755 index 000000000..87ebbb904 --- /dev/null +++ b/ts-ticket-office-service/node_modules/@types/node/punycode.d.ts @@ -0,0 +1,117 @@ +/** + * **The version of the punycode module bundled in Node.js is being deprecated.**In a future major version of Node.js this module will be removed. Users + * currently depending on the `punycode` module should switch to using the + * userland-provided [Punycode.js](https://github.com/bestiejs/punycode.js) module instead. For punycode-based URL + * encoding, see `url.domainToASCII` or, more generally, the `WHATWG URL API`. + * + * The `punycode` module is a bundled version of the [Punycode.js](https://github.com/bestiejs/punycode.js) module. It + * can be accessed using: + * + * ```js + * const punycode = require('punycode'); + * ``` + * + * [Punycode](https://tools.ietf.org/html/rfc3492) is a character encoding scheme defined by RFC 3492 that is + * primarily intended for use in Internationalized Domain Names. Because host + * names in URLs are limited to ASCII characters only, Domain Names that contain + * non-ASCII characters must be converted into ASCII using the Punycode scheme. + * For instance, the Japanese character that translates into the English word,`'example'` is `'例'`. The Internationalized Domain Name, `'例.com'` (equivalent + * to `'example.com'`) is represented by Punycode as the ASCII string`'xn--fsq.com'`. + * + * The `punycode` module provides a simple implementation of the Punycode standard. + * + * The `punycode` module is a third-party dependency used by Node.js and + * made available to developers as a convenience. Fixes or other modifications to + * the module must be directed to the [Punycode.js](https://github.com/bestiejs/punycode.js) project. + * @deprecated Since v7.0.0 - Deprecated + * @see [source](https://github.com/nodejs/node/blob/v18.0.0/lib/punycode.js) + */ +declare module 'punycode' { + /** + * The `punycode.decode()` method converts a [Punycode](https://tools.ietf.org/html/rfc3492) string of ASCII-only + * characters to the equivalent string of Unicode codepoints. + * + * ```js + * punycode.decode('maana-pta'); // 'mañana' + * punycode.decode('--dqo34k'); // '☃-⌘' + * ``` + * @since v0.5.1 + */ + function decode(string: string): string; + /** + * The `punycode.encode()` method converts a string of Unicode codepoints to a [Punycode](https://tools.ietf.org/html/rfc3492) string of ASCII-only characters. + * + * ```js + * punycode.encode('mañana'); // 'maana-pta' + * punycode.encode('☃-⌘'); // '--dqo34k' + * ``` + * @since v0.5.1 + */ + function encode(string: string): string; + /** + * The `punycode.toUnicode()` method converts a string representing a domain name + * containing [Punycode](https://tools.ietf.org/html/rfc3492) encoded characters into Unicode. Only the [Punycode](https://tools.ietf.org/html/rfc3492) encoded parts of the domain name are be + * converted. + * + * ```js + * // decode domain names + * punycode.toUnicode('xn--maana-pta.com'); // 'mañana.com' + * punycode.toUnicode('xn----dqo34k.com'); // '☃-⌘.com' + * punycode.toUnicode('example.com'); // 'example.com' + * ``` + * @since v0.6.1 + */ + function toUnicode(domain: string): string; + /** + * The `punycode.toASCII()` method converts a Unicode string representing an + * Internationalized Domain Name to [Punycode](https://tools.ietf.org/html/rfc3492). Only the non-ASCII parts of the + * domain name will be converted. Calling `punycode.toASCII()` on a string that + * already only contains ASCII characters will have no effect. + * + * ```js + * // encode domain names + * punycode.toASCII('mañana.com'); // 'xn--maana-pta.com' + * punycode.toASCII('☃-⌘.com'); // 'xn----dqo34k.com' + * punycode.toASCII('example.com'); // 'example.com' + * ``` + * @since v0.6.1 + */ + function toASCII(domain: string): string; + /** + * @deprecated since v7.0.0 + * The version of the punycode module bundled in Node.js is being deprecated. + * In a future major version of Node.js this module will be removed. + * Users currently depending on the punycode module should switch to using + * the userland-provided Punycode.js module instead. + */ + const ucs2: ucs2; + interface ucs2 { + /** + * @deprecated since v7.0.0 + * The version of the punycode module bundled in Node.js is being deprecated. + * In a future major version of Node.js this module will be removed. + * Users currently depending on the punycode module should switch to using + * the userland-provided Punycode.js module instead. + */ + decode(string: string): number[]; + /** + * @deprecated since v7.0.0 + * The version of the punycode module bundled in Node.js is being deprecated. + * In a future major version of Node.js this module will be removed. + * Users currently depending on the punycode module should switch to using + * the userland-provided Punycode.js module instead. + */ + encode(codePoints: ReadonlyArray): string; + } + /** + * @deprecated since v7.0.0 + * The version of the punycode module bundled in Node.js is being deprecated. + * In a future major version of Node.js this module will be removed. + * Users currently depending on the punycode module should switch to using + * the userland-provided Punycode.js module instead. + */ + const version: string; +} +declare module 'node:punycode' { + export * from 'punycode'; +} diff --git a/ts-ticket-office-service/node_modules/@types/node/querystring.d.ts b/ts-ticket-office-service/node_modules/@types/node/querystring.d.ts new file mode 100755 index 000000000..e694d8c84 --- /dev/null +++ b/ts-ticket-office-service/node_modules/@types/node/querystring.d.ts @@ -0,0 +1,131 @@ +/** + * The `querystring` module provides utilities for parsing and formatting URL + * query strings. It can be accessed using: + * + * ```js + * const querystring = require('querystring'); + * ``` + * + * The `querystring` API is considered Legacy. While it is still maintained, + * new code should use the `URLSearchParams` API instead. + * @deprecated Legacy + * @see [source](https://github.com/nodejs/node/blob/v18.0.0/lib/querystring.js) + */ +declare module 'querystring' { + interface StringifyOptions { + encodeURIComponent?: ((str: string) => string) | undefined; + } + interface ParseOptions { + maxKeys?: number | undefined; + decodeURIComponent?: ((str: string) => string) | undefined; + } + interface ParsedUrlQuery extends NodeJS.Dict {} + interface ParsedUrlQueryInput extends NodeJS.Dict | ReadonlyArray | ReadonlyArray | null> {} + /** + * The `querystring.stringify()` method produces a URL query string from a + * given `obj` by iterating through the object's "own properties". + * + * It serializes the following types of values passed in `obj`:[string](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | + * [number](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) | + * [bigint](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/BigInt) | + * [boolean](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type) | + * [string\[\]](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | + * [number\[\]](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) | + * [bigint\[\]](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/BigInt) | + * [boolean\[\]](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type) The numeric values must be finite. Any other input values will be coerced to + * empty strings. + * + * ```js + * querystring.stringify({ foo: 'bar', baz: ['qux', 'quux'], corge: '' }); + * // Returns 'foo=bar&baz=qux&baz=quux&corge=' + * + * querystring.stringify({ foo: 'bar', baz: 'qux' }, ';', ':'); + * // Returns 'foo:bar;baz:qux' + * ``` + * + * By default, characters requiring percent-encoding within the query string will + * be encoded as UTF-8\. If an alternative encoding is required, then an alternative`encodeURIComponent` option will need to be specified: + * + * ```js + * // Assuming gbkEncodeURIComponent function already exists, + * + * querystring.stringify({ w: '中文', foo: 'bar' }, null, null, + * { encodeURIComponent: gbkEncodeURIComponent }); + * ``` + * @since v0.1.25 + * @param obj The object to serialize into a URL query string + * @param [sep='&'] The substring used to delimit key and value pairs in the query string. + * @param [eq='='] . The substring used to delimit keys and values in the query string. + */ + function stringify(obj?: ParsedUrlQueryInput, sep?: string, eq?: string, options?: StringifyOptions): string; + /** + * The `querystring.parse()` method parses a URL query string (`str`) into a + * collection of key and value pairs. + * + * For example, the query string `'foo=bar&abc=xyz&abc=123'` is parsed into: + * + * ```js + * { + * foo: 'bar', + * abc: ['xyz', '123'] + * } + * ``` + * + * The object returned by the `querystring.parse()` method _does not_prototypically inherit from the JavaScript `Object`. This means that typical`Object` methods such as `obj.toString()`, + * `obj.hasOwnProperty()`, and others + * are not defined and _will not work_. + * + * By default, percent-encoded characters within the query string will be assumed + * to use UTF-8 encoding. If an alternative character encoding is used, then an + * alternative `decodeURIComponent` option will need to be specified: + * + * ```js + * // Assuming gbkDecodeURIComponent function already exists... + * + * querystring.parse('w=%D6%D0%CE%C4&foo=bar', null, null, + * { decodeURIComponent: gbkDecodeURIComponent }); + * ``` + * @since v0.1.25 + * @param str The URL query string to parse + * @param [sep='&'] The substring used to delimit key and value pairs in the query string. + * @param [eq='='] . The substring used to delimit keys and values in the query string. + */ + function parse(str: string, sep?: string, eq?: string, options?: ParseOptions): ParsedUrlQuery; + /** + * The querystring.encode() function is an alias for querystring.stringify(). + */ + const encode: typeof stringify; + /** + * The querystring.decode() function is an alias for querystring.parse(). + */ + const decode: typeof parse; + /** + * The `querystring.escape()` method performs URL percent-encoding on the given`str` in a manner that is optimized for the specific requirements of URL + * query strings. + * + * The `querystring.escape()` method is used by `querystring.stringify()` and is + * generally not expected to be used directly. It is exported primarily to allow + * application code to provide a replacement percent-encoding implementation if + * necessary by assigning `querystring.escape` to an alternative function. + * @since v0.1.25 + */ + function escape(str: string): string; + /** + * The `querystring.unescape()` method performs decoding of URL percent-encoded + * characters on the given `str`. + * + * The `querystring.unescape()` method is used by `querystring.parse()` and is + * generally not expected to be used directly. It is exported primarily to allow + * application code to provide a replacement decoding implementation if + * necessary by assigning `querystring.unescape` to an alternative function. + * + * By default, the `querystring.unescape()` method will attempt to use the + * JavaScript built-in `decodeURIComponent()` method to decode. If that fails, + * a safer equivalent that does not throw on malformed URLs will be used. + * @since v0.1.25 + */ + function unescape(str: string): string; +} +declare module 'node:querystring' { + export * from 'querystring'; +} diff --git a/ts-ticket-office-service/node_modules/@types/node/readline.d.ts b/ts-ticket-office-service/node_modules/@types/node/readline.d.ts new file mode 100755 index 000000000..ac8b81ab7 --- /dev/null +++ b/ts-ticket-office-service/node_modules/@types/node/readline.d.ts @@ -0,0 +1,650 @@ +/** + * The `readline` module provides an interface for reading data from a `Readable` stream (such as `process.stdin`) one line at a time. + * + * To use the promise-based APIs: + * + * ```js + * import * as readline from 'node:readline/promises'; + * ``` + * + * To use the callback and sync APIs: + * + * ```js + * import * as readline from 'node:readline'; + * ``` + * + * The following simple example illustrates the basic use of the `readline` module. + * + * ```js + * import * as readline from 'node:readline/promises'; + * import { stdin as input, stdout as output } from 'node:process'; + * + * const rl = readline.createInterface({ input, output }); + * + * const answer = await rl.question('What do you think of Node.js? '); + * + * console.log(`Thank you for your valuable feedback: ${answer}`); + * + * rl.close(); + * ``` + * + * Once this code is invoked, the Node.js application will not terminate until the`readline.Interface` is closed because the interface waits for data to be + * received on the `input` stream. + * @see [source](https://github.com/nodejs/node/blob/v18.0.0/lib/readline.js) + */ +declare module 'readline' { + import { Abortable, EventEmitter } from 'node:events'; + interface Key { + sequence?: string | undefined; + name?: string | undefined; + ctrl?: boolean | undefined; + meta?: boolean | undefined; + shift?: boolean | undefined; + } + /** + * Instances of the `readline.Interface` class are constructed using the`readline.createInterface()` method. Every instance is associated with a + * single `input` `Readable` stream and a single `output` `Writable` stream. + * The `output` stream is used to print prompts for user input that arrives on, + * and is read from, the `input` stream. + * @since v0.1.104 + */ + class Interface extends EventEmitter { + readonly terminal: boolean; + /** + * The current input data being processed by node. + * + * This can be used when collecting input from a TTY stream to retrieve the + * current value that has been processed thus far, prior to the `line` event + * being emitted. Once the `line` event has been emitted, this property will + * be an empty string. + * + * Be aware that modifying the value during the instance runtime may have + * unintended consequences if `rl.cursor` is not also controlled. + * + * **If not using a TTY stream for input, use the `'line'` event.** + * + * One possible use case would be as follows: + * + * ```js + * const values = ['lorem ipsum', 'dolor sit amet']; + * const rl = readline.createInterface(process.stdin); + * const showResults = debounce(() => { + * console.log( + * '\n', + * values.filter((val) => val.startsWith(rl.line)).join(' ') + * ); + * }, 300); + * process.stdin.on('keypress', (c, k) => { + * showResults(); + * }); + * ``` + * @since v0.1.98 + */ + readonly line: string; + /** + * The cursor position relative to `rl.line`. + * + * This will track where the current cursor lands in the input string, when + * reading input from a TTY stream. The position of cursor determines the + * portion of the input string that will be modified as input is processed, + * as well as the column where the terminal caret will be rendered. + * @since v0.1.98 + */ + readonly cursor: number; + /** + * NOTE: According to the documentation: + * + * > Instances of the `readline.Interface` class are constructed using the + * > `readline.createInterface()` method. + * + * @see https://nodejs.org/dist/latest-v10.x/docs/api/readline.html#readline_class_interface + */ + protected constructor(input: NodeJS.ReadableStream, output?: NodeJS.WritableStream, completer?: Completer | AsyncCompleter, terminal?: boolean); + /** + * NOTE: According to the documentation: + * + * > Instances of the `readline.Interface` class are constructed using the + * > `readline.createInterface()` method. + * + * @see https://nodejs.org/dist/latest-v10.x/docs/api/readline.html#readline_class_interface + */ + protected constructor(options: ReadLineOptions); + /** + * The `rl.getPrompt()` method returns the current prompt used by `rl.prompt()`. + * @since v15.3.0 + * @return the current prompt string + */ + getPrompt(): string; + /** + * The `rl.setPrompt()` method sets the prompt that will be written to `output`whenever `rl.prompt()` is called. + * @since v0.1.98 + */ + setPrompt(prompt: string): void; + /** + * The `rl.prompt()` method writes the `readline.Interface` instances configured`prompt` to a new line in `output` in order to provide a user with a new + * location at which to provide input. + * + * When called, `rl.prompt()` will resume the `input` stream if it has been + * paused. + * + * If the `readline.Interface` was created with `output` set to `null` or`undefined` the prompt is not written. + * @since v0.1.98 + * @param preserveCursor If `true`, prevents the cursor placement from being reset to `0`. + */ + prompt(preserveCursor?: boolean): void; + /** + * The `rl.question()` method displays the `query` by writing it to the `output`, + * waits for user input to be provided on `input`, then invokes the `callback`function passing the provided input as the first argument. + * + * When called, `rl.question()` will resume the `input` stream if it has been + * paused. + * + * If the `readline.Interface` was created with `output` set to `null` or`undefined` the `query` is not written. + * + * The `callback` function passed to `rl.question()` does not follow the typical + * pattern of accepting an `Error` object or `null` as the first argument. + * The `callback` is called with the provided answer as the only argument. + * + * Example usage: + * + * ```js + * rl.question('What is your favorite food? ', (answer) => { + * console.log(`Oh, so your favorite food is ${answer}`); + * }); + * ``` + * + * Using an `AbortController` to cancel a question. + * + * ```js + * const ac = new AbortController(); + * const signal = ac.signal; + * + * rl.question('What is your favorite food? ', { signal }, (answer) => { + * console.log(`Oh, so your favorite food is ${answer}`); + * }); + * + * signal.addEventListener('abort', () => { + * console.log('The food question timed out'); + * }, { once: true }); + * + * setTimeout(() => ac.abort(), 10000); + * ``` + * + * If this method is invoked as it's util.promisify()ed version, it returns a + * Promise that fulfills with the answer. If the question is canceled using + * an `AbortController` it will reject with an `AbortError`. + * + * ```js + * const util = require('util'); + * const question = util.promisify(rl.question).bind(rl); + * + * async function questionExample() { + * try { + * const answer = await question('What is you favorite food? '); + * console.log(`Oh, so your favorite food is ${answer}`); + * } catch (err) { + * console.error('Question rejected', err); + * } + * } + * questionExample(); + * ``` + * @since v0.3.3 + * @param query A statement or query to write to `output`, prepended to the prompt. + * @param callback A callback function that is invoked with the user's input in response to the `query`. + */ + question(query: string, callback: (answer: string) => void): void; + question(query: string, options: Abortable, callback: (answer: string) => void): void; + /** + * The `rl.pause()` method pauses the `input` stream, allowing it to be resumed + * later if necessary. + * + * Calling `rl.pause()` does not immediately pause other events (including`'line'`) from being emitted by the `readline.Interface` instance. + * @since v0.3.4 + */ + pause(): this; + /** + * The `rl.resume()` method resumes the `input` stream if it has been paused. + * @since v0.3.4 + */ + resume(): this; + /** + * The `rl.close()` method closes the `readline.Interface` instance and + * relinquishes control over the `input` and `output` streams. When called, + * the `'close'` event will be emitted. + * + * Calling `rl.close()` does not immediately stop other events (including `'line'`) + * from being emitted by the `readline.Interface` instance. + * @since v0.1.98 + */ + close(): void; + /** + * The `rl.write()` method will write either `data` or a key sequence identified + * by `key` to the `output`. The `key` argument is supported only if `output` is + * a `TTY` text terminal. See `TTY keybindings` for a list of key + * combinations. + * + * If `key` is specified, `data` is ignored. + * + * When called, `rl.write()` will resume the `input` stream if it has been + * paused. + * + * If the `readline.Interface` was created with `output` set to `null` or`undefined` the `data` and `key` are not written. + * + * ```js + * rl.write('Delete this!'); + * // Simulate Ctrl+U to delete the line written previously + * rl.write(null, { ctrl: true, name: 'u' }); + * ``` + * + * The `rl.write()` method will write the data to the `readline` `Interface`'s`input`_as if it were provided by the user_. + * @since v0.1.98 + */ + write(data: string | Buffer, key?: Key): void; + write(data: undefined | null | string | Buffer, key: Key): void; + /** + * Returns the real position of the cursor in relation to the input + * prompt + string. Long input (wrapping) strings, as well as multiple + * line prompts are included in the calculations. + * @since v13.5.0, v12.16.0 + */ + getCursorPos(): CursorPos; + /** + * events.EventEmitter + * 1. close + * 2. line + * 3. pause + * 4. resume + * 5. SIGCONT + * 6. SIGINT + * 7. SIGTSTP + * 8. history + */ + addListener(event: string, listener: (...args: any[]) => void): this; + addListener(event: 'close', listener: () => void): this; + addListener(event: 'line', listener: (input: string) => void): this; + addListener(event: 'pause', listener: () => void): this; + addListener(event: 'resume', listener: () => void): this; + addListener(event: 'SIGCONT', listener: () => void): this; + addListener(event: 'SIGINT', listener: () => void): this; + addListener(event: 'SIGTSTP', listener: () => void): this; + addListener(event: 'history', listener: (history: string[]) => void): this; + emit(event: string | symbol, ...args: any[]): boolean; + emit(event: 'close'): boolean; + emit(event: 'line', input: string): boolean; + emit(event: 'pause'): boolean; + emit(event: 'resume'): boolean; + emit(event: 'SIGCONT'): boolean; + emit(event: 'SIGINT'): boolean; + emit(event: 'SIGTSTP'): boolean; + emit(event: 'history', history: string[]): boolean; + on(event: string, listener: (...args: any[]) => void): this; + on(event: 'close', listener: () => void): this; + on(event: 'line', listener: (input: string) => void): this; + on(event: 'pause', listener: () => void): this; + on(event: 'resume', listener: () => void): this; + on(event: 'SIGCONT', listener: () => void): this; + on(event: 'SIGINT', listener: () => void): this; + on(event: 'SIGTSTP', listener: () => void): this; + on(event: 'history', listener: (history: string[]) => void): this; + once(event: string, listener: (...args: any[]) => void): this; + once(event: 'close', listener: () => void): this; + once(event: 'line', listener: (input: string) => void): this; + once(event: 'pause', listener: () => void): this; + once(event: 'resume', listener: () => void): this; + once(event: 'SIGCONT', listener: () => void): this; + once(event: 'SIGINT', listener: () => void): this; + once(event: 'SIGTSTP', listener: () => void): this; + once(event: 'history', listener: (history: string[]) => void): this; + prependListener(event: string, listener: (...args: any[]) => void): this; + prependListener(event: 'close', listener: () => void): this; + prependListener(event: 'line', listener: (input: string) => void): this; + prependListener(event: 'pause', listener: () => void): this; + prependListener(event: 'resume', listener: () => void): this; + prependListener(event: 'SIGCONT', listener: () => void): this; + prependListener(event: 'SIGINT', listener: () => void): this; + prependListener(event: 'SIGTSTP', listener: () => void): this; + prependListener(event: 'history', listener: (history: string[]) => void): this; + prependOnceListener(event: string, listener: (...args: any[]) => void): this; + prependOnceListener(event: 'close', listener: () => void): this; + prependOnceListener(event: 'line', listener: (input: string) => void): this; + prependOnceListener(event: 'pause', listener: () => void): this; + prependOnceListener(event: 'resume', listener: () => void): this; + prependOnceListener(event: 'SIGCONT', listener: () => void): this; + prependOnceListener(event: 'SIGINT', listener: () => void): this; + prependOnceListener(event: 'SIGTSTP', listener: () => void): this; + prependOnceListener(event: 'history', listener: (history: string[]) => void): this; + [Symbol.asyncIterator](): AsyncIterableIterator; + } + type ReadLine = Interface; // type forwarded for backwards compatibility + type Completer = (line: string) => CompleterResult; + type AsyncCompleter = (line: string, callback: (err?: null | Error, result?: CompleterResult) => void) => void; + type CompleterResult = [string[], string]; + interface ReadLineOptions { + input: NodeJS.ReadableStream; + output?: NodeJS.WritableStream | undefined; + completer?: Completer | AsyncCompleter | undefined; + terminal?: boolean | undefined; + /** + * Initial list of history lines. This option makes sense + * only if `terminal` is set to `true` by the user or by an internal `output` + * check, otherwise the history caching mechanism is not initialized at all. + * @default [] + */ + history?: string[] | undefined; + historySize?: number | undefined; + prompt?: string | undefined; + crlfDelay?: number | undefined; + /** + * If `true`, when a new input line added + * to the history list duplicates an older one, this removes the older line + * from the list. + * @default false + */ + removeHistoryDuplicates?: boolean | undefined; + escapeCodeTimeout?: number | undefined; + tabSize?: number | undefined; + } + /** + * The `readline.createInterface()` method creates a new `readline.Interface`instance. + * + * ```js + * const readline = require('readline'); + * const rl = readline.createInterface({ + * input: process.stdin, + * output: process.stdout + * }); + * ``` + * + * Once the `readline.Interface` instance is created, the most common case is to + * listen for the `'line'` event: + * + * ```js + * rl.on('line', (line) => { + * console.log(`Received: ${line}`); + * }); + * ``` + * + * If `terminal` is `true` for this instance then the `output` stream will get + * the best compatibility if it defines an `output.columns` property and emits + * a `'resize'` event on the `output` if or when the columns ever change + * (`process.stdout` does this automatically when it is a TTY). + * + * When creating a `readline.Interface` using `stdin` as input, the program + * will not terminate until it receives `EOF` (Ctrl+D on + * Linux/macOS, Ctrl+Z followed by Return on + * Windows). + * If you want your application to exit without waiting for user input, you can `unref()` the standard input stream: + * + * ```js + * process.stdin.unref(); + * ``` + * @since v0.1.98 + */ + function createInterface(input: NodeJS.ReadableStream, output?: NodeJS.WritableStream, completer?: Completer | AsyncCompleter, terminal?: boolean): Interface; + function createInterface(options: ReadLineOptions): Interface; + /** + * The `readline.emitKeypressEvents()` method causes the given `Readable` stream to begin emitting `'keypress'` events corresponding to received input. + * + * Optionally, `interface` specifies a `readline.Interface` instance for which + * autocompletion is disabled when copy-pasted input is detected. + * + * If the `stream` is a `TTY`, then it must be in raw mode. + * + * This is automatically called by any readline instance on its `input` if the`input` is a terminal. Closing the `readline` instance does not stop + * the `input` from emitting `'keypress'` events. + * + * ```js + * readline.emitKeypressEvents(process.stdin); + * if (process.stdin.isTTY) + * process.stdin.setRawMode(true); + * ``` + * + * ## Example: Tiny CLI + * + * The following example illustrates the use of `readline.Interface` class to + * implement a small command-line interface: + * + * ```js + * const readline = require('readline'); + * const rl = readline.createInterface({ + * input: process.stdin, + * output: process.stdout, + * prompt: 'OHAI> ' + * }); + * + * rl.prompt(); + * + * rl.on('line', (line) => { + * switch (line.trim()) { + * case 'hello': + * console.log('world!'); + * break; + * default: + * console.log(`Say what? I might have heard '${line.trim()}'`); + * break; + * } + * rl.prompt(); + * }).on('close', () => { + * console.log('Have a great day!'); + * process.exit(0); + * }); + * ``` + * + * ## Example: Read file stream line-by-Line + * + * A common use case for `readline` is to consume an input file one line at a + * time. The easiest way to do so is leveraging the `fs.ReadStream` API as + * well as a `for await...of` loop: + * + * ```js + * const fs = require('fs'); + * const readline = require('readline'); + * + * async function processLineByLine() { + * const fileStream = fs.createReadStream('input.txt'); + * + * const rl = readline.createInterface({ + * input: fileStream, + * crlfDelay: Infinity + * }); + * // Note: we use the crlfDelay option to recognize all instances of CR LF + * // ('\r\n') in input.txt as a single line break. + * + * for await (const line of rl) { + * // Each line in input.txt will be successively available here as `line`. + * console.log(`Line from file: ${line}`); + * } + * } + * + * processLineByLine(); + * ``` + * + * Alternatively, one could use the `'line'` event: + * + * ```js + * const fs = require('fs'); + * const readline = require('readline'); + * + * const rl = readline.createInterface({ + * input: fs.createReadStream('sample.txt'), + * crlfDelay: Infinity + * }); + * + * rl.on('line', (line) => { + * console.log(`Line from file: ${line}`); + * }); + * ``` + * + * Currently, `for await...of` loop can be a bit slower. If `async` / `await`flow and speed are both essential, a mixed approach can be applied: + * + * ```js + * const { once } = require('events'); + * const { createReadStream } = require('fs'); + * const { createInterface } = require('readline'); + * + * (async function processLineByLine() { + * try { + * const rl = createInterface({ + * input: createReadStream('big-file.txt'), + * crlfDelay: Infinity + * }); + * + * rl.on('line', (line) => { + * // Process the line. + * }); + * + * await once(rl, 'close'); + * + * console.log('File processed.'); + * } catch (err) { + * console.error(err); + * } + * })(); + * ``` + * @since v0.7.7 + */ + function emitKeypressEvents(stream: NodeJS.ReadableStream, readlineInterface?: Interface): void; + type Direction = -1 | 0 | 1; + interface CursorPos { + rows: number; + cols: number; + } + /** + * The `readline.clearLine()` method clears current line of given `TTY` stream + * in a specified direction identified by `dir`. + * @since v0.7.7 + * @param callback Invoked once the operation completes. + * @return `false` if `stream` wishes for the calling code to wait for the `'drain'` event to be emitted before continuing to write additional data; otherwise `true`. + */ + function clearLine(stream: NodeJS.WritableStream, dir: Direction, callback?: () => void): boolean; + /** + * The `readline.clearScreenDown()` method clears the given `TTY` stream from + * the current position of the cursor down. + * @since v0.7.7 + * @param callback Invoked once the operation completes. + * @return `false` if `stream` wishes for the calling code to wait for the `'drain'` event to be emitted before continuing to write additional data; otherwise `true`. + */ + function clearScreenDown(stream: NodeJS.WritableStream, callback?: () => void): boolean; + /** + * The `readline.cursorTo()` method moves cursor to the specified position in a + * given `TTY` `stream`. + * @since v0.7.7 + * @param callback Invoked once the operation completes. + * @return `false` if `stream` wishes for the calling code to wait for the `'drain'` event to be emitted before continuing to write additional data; otherwise `true`. + */ + function cursorTo(stream: NodeJS.WritableStream, x: number, y?: number, callback?: () => void): boolean; + /** + * The `readline.moveCursor()` method moves the cursor _relative_ to its current + * position in a given `TTY` `stream`. + * + * ## Example: Tiny CLI + * + * The following example illustrates the use of `readline.Interface` class to + * implement a small command-line interface: + * + * ```js + * const readline = require('readline'); + * const rl = readline.createInterface({ + * input: process.stdin, + * output: process.stdout, + * prompt: 'OHAI> ' + * }); + * + * rl.prompt(); + * + * rl.on('line', (line) => { + * switch (line.trim()) { + * case 'hello': + * console.log('world!'); + * break; + * default: + * console.log(`Say what? I might have heard '${line.trim()}'`); + * break; + * } + * rl.prompt(); + * }).on('close', () => { + * console.log('Have a great day!'); + * process.exit(0); + * }); + * ``` + * + * ## Example: Read file stream line-by-Line + * + * A common use case for `readline` is to consume an input file one line at a + * time. The easiest way to do so is leveraging the `fs.ReadStream` API as + * well as a `for await...of` loop: + * + * ```js + * const fs = require('fs'); + * const readline = require('readline'); + * + * async function processLineByLine() { + * const fileStream = fs.createReadStream('input.txt'); + * + * const rl = readline.createInterface({ + * input: fileStream, + * crlfDelay: Infinity + * }); + * // Note: we use the crlfDelay option to recognize all instances of CR LF + * // ('\r\n') in input.txt as a single line break. + * + * for await (const line of rl) { + * // Each line in input.txt will be successively available here as `line`. + * console.log(`Line from file: ${line}`); + * } + * } + * + * processLineByLine(); + * ``` + * + * Alternatively, one could use the `'line'` event: + * + * ```js + * const fs = require('fs'); + * const readline = require('readline'); + * + * const rl = readline.createInterface({ + * input: fs.createReadStream('sample.txt'), + * crlfDelay: Infinity + * }); + * + * rl.on('line', (line) => { + * console.log(`Line from file: ${line}`); + * }); + * ``` + * + * Currently, `for await...of` loop can be a bit slower. If `async` / `await`flow and speed are both essential, a mixed approach can be applied: + * + * ```js + * const { once } = require('events'); + * const { createReadStream } = require('fs'); + * const { createInterface } = require('readline'); + * + * (async function processLineByLine() { + * try { + * const rl = createInterface({ + * input: createReadStream('big-file.txt'), + * crlfDelay: Infinity + * }); + * + * rl.on('line', (line) => { + * // Process the line. + * }); + * + * await once(rl, 'close'); + * + * console.log('File processed.'); + * } catch (err) { + * console.error(err); + * } + * })(); + * ``` + * @since v0.7.7 + * @param callback Invoked once the operation completes. + * @return `false` if `stream` wishes for the calling code to wait for the `'drain'` event to be emitted before continuing to write additional data; otherwise `true`. + */ + function moveCursor(stream: NodeJS.WritableStream, dx: number, dy: number, callback?: () => void): boolean; +} +declare module 'node:readline' { + export * from 'readline'; +} diff --git a/ts-ticket-office-service/node_modules/@types/node/repl.d.ts b/ts-ticket-office-service/node_modules/@types/node/repl.d.ts new file mode 100755 index 000000000..be42ccc4a --- /dev/null +++ b/ts-ticket-office-service/node_modules/@types/node/repl.d.ts @@ -0,0 +1,424 @@ +/** + * The `repl` module provides a Read-Eval-Print-Loop (REPL) implementation that + * is available both as a standalone program or includible in other applications. + * It can be accessed using: + * + * ```js + * const repl = require('repl'); + * ``` + * @see [source](https://github.com/nodejs/node/blob/v18.0.0/lib/repl.js) + */ +declare module 'repl' { + import { Interface, Completer, AsyncCompleter } from 'node:readline'; + import { Context } from 'node:vm'; + import { InspectOptions } from 'node:util'; + interface ReplOptions { + /** + * The input prompt to display. + * @default "> " + */ + prompt?: string | undefined; + /** + * The `Readable` stream from which REPL input will be read. + * @default process.stdin + */ + input?: NodeJS.ReadableStream | undefined; + /** + * The `Writable` stream to which REPL output will be written. + * @default process.stdout + */ + output?: NodeJS.WritableStream | undefined; + /** + * If `true`, specifies that the output should be treated as a TTY terminal, and have + * ANSI/VT100 escape codes written to it. + * Default: checking the value of the `isTTY` property on the output stream upon + * instantiation. + */ + terminal?: boolean | undefined; + /** + * The function to be used when evaluating each given line of input. + * Default: an async wrapper for the JavaScript `eval()` function. An `eval` function can + * error with `repl.Recoverable` to indicate the input was incomplete and prompt for + * additional lines. + * + * @see https://nodejs.org/dist/latest-v10.x/docs/api/repl.html#repl_default_evaluation + * @see https://nodejs.org/dist/latest-v10.x/docs/api/repl.html#repl_custom_evaluation_functions + */ + eval?: REPLEval | undefined; + /** + * Defines if the repl prints output previews or not. + * @default `true` Always `false` in case `terminal` is falsy. + */ + preview?: boolean | undefined; + /** + * If `true`, specifies that the default `writer` function should include ANSI color + * styling to REPL output. If a custom `writer` function is provided then this has no + * effect. + * Default: the REPL instance's `terminal` value. + */ + useColors?: boolean | undefined; + /** + * If `true`, specifies that the default evaluation function will use the JavaScript + * `global` as the context as opposed to creating a new separate context for the REPL + * instance. The node CLI REPL sets this value to `true`. + * Default: `false`. + */ + useGlobal?: boolean | undefined; + /** + * If `true`, specifies that the default writer will not output the return value of a + * command if it evaluates to `undefined`. + * Default: `false`. + */ + ignoreUndefined?: boolean | undefined; + /** + * The function to invoke to format the output of each command before writing to `output`. + * Default: a wrapper for `util.inspect`. + * + * @see https://nodejs.org/dist/latest-v10.x/docs/api/repl.html#repl_customizing_repl_output + */ + writer?: REPLWriter | undefined; + /** + * An optional function used for custom Tab auto completion. + * + * @see https://nodejs.org/dist/latest-v11.x/docs/api/readline.html#readline_use_of_the_completer_function + */ + completer?: Completer | AsyncCompleter | undefined; + /** + * A flag that specifies whether the default evaluator executes all JavaScript commands in + * strict mode or default (sloppy) mode. + * Accepted values are: + * - `repl.REPL_MODE_SLOPPY` - evaluates expressions in sloppy mode. + * - `repl.REPL_MODE_STRICT` - evaluates expressions in strict mode. This is equivalent to + * prefacing every repl statement with `'use strict'`. + */ + replMode?: typeof REPL_MODE_SLOPPY | typeof REPL_MODE_STRICT | undefined; + /** + * Stop evaluating the current piece of code when `SIGINT` is received, i.e. `Ctrl+C` is + * pressed. This cannot be used together with a custom `eval` function. + * Default: `false`. + */ + breakEvalOnSigint?: boolean | undefined; + } + type REPLEval = (this: REPLServer, evalCmd: string, context: Context, file: string, cb: (err: Error | null, result: any) => void) => void; + type REPLWriter = (this: REPLServer, obj: any) => string; + /** + * This is the default "writer" value, if none is passed in the REPL options, + * and it can be overridden by custom print functions. + */ + const writer: REPLWriter & { + options: InspectOptions; + }; + type REPLCommandAction = (this: REPLServer, text: string) => void; + interface REPLCommand { + /** + * Help text to be displayed when `.help` is entered. + */ + help?: string | undefined; + /** + * The function to execute, optionally accepting a single string argument. + */ + action: REPLCommandAction; + } + /** + * Instances of `repl.REPLServer` are created using the {@link start} method + * or directly using the JavaScript `new` keyword. + * + * ```js + * const repl = require('repl'); + * + * const options = { useColors: true }; + * + * const firstInstance = repl.start(options); + * const secondInstance = new repl.REPLServer(options); + * ``` + * @since v0.1.91 + */ + class REPLServer extends Interface { + /** + * The `vm.Context` provided to the `eval` function to be used for JavaScript + * evaluation. + */ + readonly context: Context; + /** + * @deprecated since v14.3.0 - Use `input` instead. + */ + readonly inputStream: NodeJS.ReadableStream; + /** + * @deprecated since v14.3.0 - Use `output` instead. + */ + readonly outputStream: NodeJS.WritableStream; + /** + * The `Readable` stream from which REPL input will be read. + */ + readonly input: NodeJS.ReadableStream; + /** + * The `Writable` stream to which REPL output will be written. + */ + readonly output: NodeJS.WritableStream; + /** + * The commands registered via `replServer.defineCommand()`. + */ + readonly commands: NodeJS.ReadOnlyDict; + /** + * A value indicating whether the REPL is currently in "editor mode". + * + * @see https://nodejs.org/dist/latest-v10.x/docs/api/repl.html#repl_commands_and_special_keys + */ + readonly editorMode: boolean; + /** + * A value indicating whether the `_` variable has been assigned. + * + * @see https://nodejs.org/dist/latest-v10.x/docs/api/repl.html#repl_assignment_of_the_underscore_variable + */ + readonly underscoreAssigned: boolean; + /** + * The last evaluation result from the REPL (assigned to the `_` variable inside of the REPL). + * + * @see https://nodejs.org/dist/latest-v10.x/docs/api/repl.html#repl_assignment_of_the_underscore_variable + */ + readonly last: any; + /** + * A value indicating whether the `_error` variable has been assigned. + * + * @since v9.8.0 + * @see https://nodejs.org/dist/latest-v10.x/docs/api/repl.html#repl_assignment_of_the_underscore_variable + */ + readonly underscoreErrAssigned: boolean; + /** + * The last error raised inside the REPL (assigned to the `_error` variable inside of the REPL). + * + * @since v9.8.0 + * @see https://nodejs.org/dist/latest-v10.x/docs/api/repl.html#repl_assignment_of_the_underscore_variable + */ + readonly lastError: any; + /** + * Specified in the REPL options, this is the function to be used when evaluating each + * given line of input. If not specified in the REPL options, this is an async wrapper + * for the JavaScript `eval()` function. + */ + readonly eval: REPLEval; + /** + * Specified in the REPL options, this is a value indicating whether the default + * `writer` function should include ANSI color styling to REPL output. + */ + readonly useColors: boolean; + /** + * Specified in the REPL options, this is a value indicating whether the default `eval` + * function will use the JavaScript `global` as the context as opposed to creating a new + * separate context for the REPL instance. + */ + readonly useGlobal: boolean; + /** + * Specified in the REPL options, this is a value indicating whether the default `writer` + * function should output the result of a command if it evaluates to `undefined`. + */ + readonly ignoreUndefined: boolean; + /** + * Specified in the REPL options, this is the function to invoke to format the output of + * each command before writing to `outputStream`. If not specified in the REPL options, + * this will be a wrapper for `util.inspect`. + */ + readonly writer: REPLWriter; + /** + * Specified in the REPL options, this is the function to use for custom Tab auto-completion. + */ + readonly completer: Completer | AsyncCompleter; + /** + * Specified in the REPL options, this is a flag that specifies whether the default `eval` + * function should execute all JavaScript commands in strict mode or default (sloppy) mode. + * Possible values are: + * - `repl.REPL_MODE_SLOPPY` - evaluates expressions in sloppy mode. + * - `repl.REPL_MODE_STRICT` - evaluates expressions in strict mode. This is equivalent to + * prefacing every repl statement with `'use strict'`. + */ + readonly replMode: typeof REPL_MODE_SLOPPY | typeof REPL_MODE_STRICT; + /** + * NOTE: According to the documentation: + * + * > Instances of `repl.REPLServer` are created using the `repl.start()` method and + * > _should not_ be created directly using the JavaScript `new` keyword. + * + * `REPLServer` cannot be subclassed due to implementation specifics in NodeJS. + * + * @see https://nodejs.org/dist/latest-v10.x/docs/api/repl.html#repl_class_replserver + */ + private constructor(); + /** + * The `replServer.defineCommand()` method is used to add new `.`\-prefixed commands + * to the REPL instance. Such commands are invoked by typing a `.` followed by the`keyword`. The `cmd` is either a `Function` or an `Object` with the following + * properties: + * + * The following example shows two new commands added to the REPL instance: + * + * ```js + * const repl = require('repl'); + * + * const replServer = repl.start({ prompt: '> ' }); + * replServer.defineCommand('sayhello', { + * help: 'Say hello', + * action(name) { + * this.clearBufferedCommand(); + * console.log(`Hello, ${name}!`); + * this.displayPrompt(); + * } + * }); + * replServer.defineCommand('saybye', function saybye() { + * console.log('Goodbye!'); + * this.close(); + * }); + * ``` + * + * The new commands can then be used from within the REPL instance: + * + * ```console + * > .sayhello Node.js User + * Hello, Node.js User! + * > .saybye + * Goodbye! + * ``` + * @since v0.3.0 + * @param keyword The command keyword (_without_ a leading `.` character). + * @param cmd The function to invoke when the command is processed. + */ + defineCommand(keyword: string, cmd: REPLCommandAction | REPLCommand): void; + /** + * The `replServer.displayPrompt()` method readies the REPL instance for input + * from the user, printing the configured `prompt` to a new line in the `output`and resuming the `input` to accept new input. + * + * When multi-line input is being entered, an ellipsis is printed rather than the + * 'prompt'. + * + * When `preserveCursor` is `true`, the cursor placement will not be reset to `0`. + * + * The `replServer.displayPrompt` method is primarily intended to be called from + * within the action function for commands registered using the`replServer.defineCommand()` method. + * @since v0.1.91 + */ + displayPrompt(preserveCursor?: boolean): void; + /** + * The `replServer.clearBufferedCommand()` method clears any command that has been + * buffered but not yet executed. This method is primarily intended to be + * called from within the action function for commands registered using the`replServer.defineCommand()` method. + * @since v9.0.0 + */ + clearBufferedCommand(): void; + /** + * Initializes a history log file for the REPL instance. When executing the + * Node.js binary and using the command-line REPL, a history file is initialized + * by default. However, this is not the case when creating a REPL + * programmatically. Use this method to initialize a history log file when working + * with REPL instances programmatically. + * @since v11.10.0 + * @param historyPath the path to the history file + * @param callback called when history writes are ready or upon error + */ + setupHistory(path: string, callback: (err: Error | null, repl: this) => void): void; + /** + * events.EventEmitter + * 1. close - inherited from `readline.Interface` + * 2. line - inherited from `readline.Interface` + * 3. pause - inherited from `readline.Interface` + * 4. resume - inherited from `readline.Interface` + * 5. SIGCONT - inherited from `readline.Interface` + * 6. SIGINT - inherited from `readline.Interface` + * 7. SIGTSTP - inherited from `readline.Interface` + * 8. exit + * 9. reset + */ + addListener(event: string, listener: (...args: any[]) => void): this; + addListener(event: 'close', listener: () => void): this; + addListener(event: 'line', listener: (input: string) => void): this; + addListener(event: 'pause', listener: () => void): this; + addListener(event: 'resume', listener: () => void): this; + addListener(event: 'SIGCONT', listener: () => void): this; + addListener(event: 'SIGINT', listener: () => void): this; + addListener(event: 'SIGTSTP', listener: () => void): this; + addListener(event: 'exit', listener: () => void): this; + addListener(event: 'reset', listener: (context: Context) => void): this; + emit(event: string | symbol, ...args: any[]): boolean; + emit(event: 'close'): boolean; + emit(event: 'line', input: string): boolean; + emit(event: 'pause'): boolean; + emit(event: 'resume'): boolean; + emit(event: 'SIGCONT'): boolean; + emit(event: 'SIGINT'): boolean; + emit(event: 'SIGTSTP'): boolean; + emit(event: 'exit'): boolean; + emit(event: 'reset', context: Context): boolean; + on(event: string, listener: (...args: any[]) => void): this; + on(event: 'close', listener: () => void): this; + on(event: 'line', listener: (input: string) => void): this; + on(event: 'pause', listener: () => void): this; + on(event: 'resume', listener: () => void): this; + on(event: 'SIGCONT', listener: () => void): this; + on(event: 'SIGINT', listener: () => void): this; + on(event: 'SIGTSTP', listener: () => void): this; + on(event: 'exit', listener: () => void): this; + on(event: 'reset', listener: (context: Context) => void): this; + once(event: string, listener: (...args: any[]) => void): this; + once(event: 'close', listener: () => void): this; + once(event: 'line', listener: (input: string) => void): this; + once(event: 'pause', listener: () => void): this; + once(event: 'resume', listener: () => void): this; + once(event: 'SIGCONT', listener: () => void): this; + once(event: 'SIGINT', listener: () => void): this; + once(event: 'SIGTSTP', listener: () => void): this; + once(event: 'exit', listener: () => void): this; + once(event: 'reset', listener: (context: Context) => void): this; + prependListener(event: string, listener: (...args: any[]) => void): this; + prependListener(event: 'close', listener: () => void): this; + prependListener(event: 'line', listener: (input: string) => void): this; + prependListener(event: 'pause', listener: () => void): this; + prependListener(event: 'resume', listener: () => void): this; + prependListener(event: 'SIGCONT', listener: () => void): this; + prependListener(event: 'SIGINT', listener: () => void): this; + prependListener(event: 'SIGTSTP', listener: () => void): this; + prependListener(event: 'exit', listener: () => void): this; + prependListener(event: 'reset', listener: (context: Context) => void): this; + prependOnceListener(event: string, listener: (...args: any[]) => void): this; + prependOnceListener(event: 'close', listener: () => void): this; + prependOnceListener(event: 'line', listener: (input: string) => void): this; + prependOnceListener(event: 'pause', listener: () => void): this; + prependOnceListener(event: 'resume', listener: () => void): this; + prependOnceListener(event: 'SIGCONT', listener: () => void): this; + prependOnceListener(event: 'SIGINT', listener: () => void): this; + prependOnceListener(event: 'SIGTSTP', listener: () => void): this; + prependOnceListener(event: 'exit', listener: () => void): this; + prependOnceListener(event: 'reset', listener: (context: Context) => void): this; + } + /** + * A flag passed in the REPL options. Evaluates expressions in sloppy mode. + */ + const REPL_MODE_SLOPPY: unique symbol; + /** + * A flag passed in the REPL options. Evaluates expressions in strict mode. + * This is equivalent to prefacing every repl statement with `'use strict'`. + */ + const REPL_MODE_STRICT: unique symbol; + /** + * The `repl.start()` method creates and starts a {@link REPLServer} instance. + * + * If `options` is a string, then it specifies the input prompt: + * + * ```js + * const repl = require('repl'); + * + * // a Unix style prompt + * repl.start('$ '); + * ``` + * @since v0.1.91 + */ + function start(options?: string | ReplOptions): REPLServer; + /** + * Indicates a recoverable error that a `REPLServer` can use to support multi-line input. + * + * @see https://nodejs.org/dist/latest-v10.x/docs/api/repl.html#repl_recoverable_errors + */ + class Recoverable extends SyntaxError { + err: Error; + constructor(err: Error); + } +} +declare module 'node:repl' { + export * from 'repl'; +} diff --git a/ts-ticket-office-service/node_modules/@types/node/stream.d.ts b/ts-ticket-office-service/node_modules/@types/node/stream.d.ts new file mode 100755 index 000000000..d478f335c --- /dev/null +++ b/ts-ticket-office-service/node_modules/@types/node/stream.d.ts @@ -0,0 +1,1339 @@ +/** + * A stream is an abstract interface for working with streaming data in Node.js. + * The `stream` module provides an API for implementing the stream interface. + * + * There are many stream objects provided by Node.js. For instance, a `request to an HTTP server` and `process.stdout` are both stream instances. + * + * Streams can be readable, writable, or both. All streams are instances of `EventEmitter`. + * + * To access the `stream` module: + * + * ```js + * const stream = require('stream'); + * ``` + * + * The `stream` module is useful for creating new types of stream instances. It is + * usually not necessary to use the `stream` module to consume streams. + * @see [source](https://github.com/nodejs/node/blob/v18.0.0/lib/stream.js) + */ +declare module 'stream' { + import { EventEmitter, Abortable } from 'node:events'; + import * as streamPromises from 'node:stream/promises'; + import * as streamConsumers from 'node:stream/consumers'; + import * as streamWeb from 'node:stream/web'; + class internal extends EventEmitter { + pipe( + destination: T, + options?: { + end?: boolean | undefined; + } + ): T; + } + namespace internal { + class Stream extends internal { + constructor(opts?: ReadableOptions); + } + interface StreamOptions extends Abortable { + emitClose?: boolean | undefined; + highWaterMark?: number | undefined; + objectMode?: boolean | undefined; + construct?(this: T, callback: (error?: Error | null) => void): void; + destroy?(this: T, error: Error | null, callback: (error: Error | null) => void): void; + autoDestroy?: boolean | undefined; + } + interface ReadableOptions extends StreamOptions { + encoding?: BufferEncoding | undefined; + read?(this: Readable, size: number): void; + } + /** + * @since v0.9.4 + */ + class Readable extends Stream implements NodeJS.ReadableStream { + /** + * A utility method for creating Readable Streams out of iterators. + */ + static from(iterable: Iterable | AsyncIterable, options?: ReadableOptions): Readable; + /** + * A utility method for creating a `Readable` from a web `ReadableStream`. + * @since v17.0.0 + * @experimental + */ + static fromWeb(readableStream: streamWeb.ReadableStream, options?: Pick): Readable; + /** + * Returns whether the stream has been read from or cancelled. + * @since v16.8.0 + */ + static isDisturbed(stream: Readable | NodeJS.ReadableStream): boolean; + /** + * A utility method for creating a web `ReadableStream` from a `Readable`. + * @since v17.0.0 + * @experimental + */ + static toWeb(streamReadable: Readable): streamWeb.ReadableStream; + /** + * Returns whether the stream was destroyed or errored before emitting `'end'`. + * @since v16.8.0 + * @experimental + */ + readonly readableAborted: boolean; + /** + * Is `true` if it is safe to call `readable.read()`, which means + * the stream has not been destroyed or emitted `'error'` or `'end'`. + * @since v11.4.0 + */ + readable: boolean; + /** + * Returns whether `'data'` has been emitted. + * @since v16.7.0, v14.18.0 + * @experimental + */ + readonly readableDidRead: boolean; + /** + * Getter for the property `encoding` of a given `Readable` stream. The `encoding`property can be set using the `readable.setEncoding()` method. + * @since v12.7.0 + */ + readonly readableEncoding: BufferEncoding | null; + /** + * Becomes `true` when `'end'` event is emitted. + * @since v12.9.0 + */ + readonly readableEnded: boolean; + /** + * This property reflects the current state of a `Readable` stream as described + * in the `Three states` section. + * @since v9.4.0 + */ + readonly readableFlowing: boolean | null; + /** + * Returns the value of `highWaterMark` passed when creating this `Readable`. + * @since v9.3.0 + */ + readonly readableHighWaterMark: number; + /** + * This property contains the number of bytes (or objects) in the queue + * ready to be read. The value provides introspection data regarding + * the status of the `highWaterMark`. + * @since v9.4.0 + */ + readonly readableLength: number; + /** + * Getter for the property `objectMode` of a given `Readable` stream. + * @since v12.3.0 + */ + readonly readableObjectMode: boolean; + /** + * Is `true` after `readable.destroy()` has been called. + * @since v18.0.0 + */ + destroyed: boolean; + /** + * Is true after 'close' has been emitted. + * @since v8.0.0 + */ + readonly closed: boolean; + /** + * Returns error if the stream has been destroyed with an error. + * @since v18.0.0 + */ + readonly errored: Error | null; + constructor(opts?: ReadableOptions); + _construct?(callback: (error?: Error | null) => void): void; + _read(size: number): void; + /** + * The `readable.read()` method reads data out of the internal buffer and + * returns it. If no data is available to be read, `null` is returned. By default, + * the data is returned as a `Buffer` object unless an encoding has been + * specified using the `readable.setEncoding()` method or the stream is operating + * in object mode. + * + * The optional `size` argument specifies a specific number of bytes to read. If`size` bytes are not available to be read, `null` will be returned _unless_the stream has ended, in which + * case all of the data remaining in the internal + * buffer will be returned. + * + * If the `size` argument is not specified, all of the data contained in the + * internal buffer will be returned. + * + * The `size` argument must be less than or equal to 1 GiB. + * + * The `readable.read()` method should only be called on `Readable` streams + * operating in paused mode. In flowing mode, `readable.read()` is called + * automatically until the internal buffer is fully drained. + * + * ```js + * const readable = getReadableStreamSomehow(); + * + * // 'readable' may be triggered multiple times as data is buffered in + * readable.on('readable', () => { + * let chunk; + * console.log('Stream is readable (new data received in buffer)'); + * // Use a loop to make sure we read all currently available data + * while (null !== (chunk = readable.read())) { + * console.log(`Read ${chunk.length} bytes of data...`); + * } + * }); + * + * // 'end' will be triggered once when there is no more data available + * readable.on('end', () => { + * console.log('Reached end of stream.'); + * }); + * ``` + * + * Each call to `readable.read()` returns a chunk of data, or `null`. The chunks + * are not concatenated. A `while` loop is necessary to consume all data + * currently in the buffer. When reading a large file `.read()` may return `null`, + * having consumed all buffered content so far, but there is still more data to + * come not yet buffered. In this case a new `'readable'` event will be emitted + * when there is more data in the buffer. Finally the `'end'` event will be + * emitted when there is no more data to come. + * + * Therefore to read a file's whole contents from a `readable`, it is necessary + * to collect chunks across multiple `'readable'` events: + * + * ```js + * const chunks = []; + * + * readable.on('readable', () => { + * let chunk; + * while (null !== (chunk = readable.read())) { + * chunks.push(chunk); + * } + * }); + * + * readable.on('end', () => { + * const content = chunks.join(''); + * }); + * ``` + * + * A `Readable` stream in object mode will always return a single item from + * a call to `readable.read(size)`, regardless of the value of the`size` argument. + * + * If the `readable.read()` method returns a chunk of data, a `'data'` event will + * also be emitted. + * + * Calling {@link read} after the `'end'` event has + * been emitted will return `null`. No runtime error will be raised. + * @since v0.9.4 + * @param size Optional argument to specify how much data to read. + */ + read(size?: number): any; + /** + * The `readable.setEncoding()` method sets the character encoding for + * data read from the `Readable` stream. + * + * By default, no encoding is assigned and stream data will be returned as`Buffer` objects. Setting an encoding causes the stream data + * to be returned as strings of the specified encoding rather than as `Buffer`objects. For instance, calling `readable.setEncoding('utf8')` will cause the + * output data to be interpreted as UTF-8 data, and passed as strings. Calling`readable.setEncoding('hex')` will cause the data to be encoded in hexadecimal + * string format. + * + * The `Readable` stream will properly handle multi-byte characters delivered + * through the stream that would otherwise become improperly decoded if simply + * pulled from the stream as `Buffer` objects. + * + * ```js + * const readable = getReadableStreamSomehow(); + * readable.setEncoding('utf8'); + * readable.on('data', (chunk) => { + * assert.equal(typeof chunk, 'string'); + * console.log('Got %d characters of string data:', chunk.length); + * }); + * ``` + * @since v0.9.4 + * @param encoding The encoding to use. + */ + setEncoding(encoding: BufferEncoding): this; + /** + * The `readable.pause()` method will cause a stream in flowing mode to stop + * emitting `'data'` events, switching out of flowing mode. Any data that + * becomes available will remain in the internal buffer. + * + * ```js + * const readable = getReadableStreamSomehow(); + * readable.on('data', (chunk) => { + * console.log(`Received ${chunk.length} bytes of data.`); + * readable.pause(); + * console.log('There will be no additional data for 1 second.'); + * setTimeout(() => { + * console.log('Now data will start flowing again.'); + * readable.resume(); + * }, 1000); + * }); + * ``` + * + * The `readable.pause()` method has no effect if there is a `'readable'`event listener. + * @since v0.9.4 + */ + pause(): this; + /** + * The `readable.resume()` method causes an explicitly paused `Readable` stream to + * resume emitting `'data'` events, switching the stream into flowing mode. + * + * The `readable.resume()` method can be used to fully consume the data from a + * stream without actually processing any of that data: + * + * ```js + * getReadableStreamSomehow() + * .resume() + * .on('end', () => { + * console.log('Reached the end, but did not read anything.'); + * }); + * ``` + * + * The `readable.resume()` method has no effect if there is a `'readable'`event listener. + * @since v0.9.4 + */ + resume(): this; + /** + * The `readable.isPaused()` method returns the current operating state of the`Readable`. This is used primarily by the mechanism that underlies the`readable.pipe()` method. In most + * typical cases, there will be no reason to + * use this method directly. + * + * ```js + * const readable = new stream.Readable(); + * + * readable.isPaused(); // === false + * readable.pause(); + * readable.isPaused(); // === true + * readable.resume(); + * readable.isPaused(); // === false + * ``` + * @since v0.11.14 + */ + isPaused(): boolean; + /** + * The `readable.unpipe()` method detaches a `Writable` stream previously attached + * using the {@link pipe} method. + * + * If the `destination` is not specified, then _all_ pipes are detached. + * + * If the `destination` is specified, but no pipe is set up for it, then + * the method does nothing. + * + * ```js + * const fs = require('fs'); + * const readable = getReadableStreamSomehow(); + * const writable = fs.createWriteStream('file.txt'); + * // All the data from readable goes into 'file.txt', + * // but only for the first second. + * readable.pipe(writable); + * setTimeout(() => { + * console.log('Stop writing to file.txt.'); + * readable.unpipe(writable); + * console.log('Manually close the file stream.'); + * writable.end(); + * }, 1000); + * ``` + * @since v0.9.4 + * @param destination Optional specific stream to unpipe + */ + unpipe(destination?: NodeJS.WritableStream): this; + /** + * Passing `chunk` as `null` signals the end of the stream (EOF) and behaves the + * same as `readable.push(null)`, after which no more data can be written. The EOF + * signal is put at the end of the buffer and any buffered data will still be + * flushed. + * + * The `readable.unshift()` method pushes a chunk of data back into the internal + * buffer. This is useful in certain situations where a stream is being consumed by + * code that needs to "un-consume" some amount of data that it has optimistically + * pulled out of the source, so that the data can be passed on to some other party. + * + * The `stream.unshift(chunk)` method cannot be called after the `'end'` event + * has been emitted or a runtime error will be thrown. + * + * Developers using `stream.unshift()` often should consider switching to + * use of a `Transform` stream instead. See the `API for stream implementers` section for more information. + * + * ```js + * // Pull off a header delimited by \n\n. + * // Use unshift() if we get too much. + * // Call the callback with (error, header, stream). + * const { StringDecoder } = require('string_decoder'); + * function parseHeader(stream, callback) { + * stream.on('error', callback); + * stream.on('readable', onReadable); + * const decoder = new StringDecoder('utf8'); + * let header = ''; + * function onReadable() { + * let chunk; + * while (null !== (chunk = stream.read())) { + * const str = decoder.write(chunk); + * if (str.includes('\n\n')) { + * // Found the header boundary. + * const split = str.split(/\n\n/); + * header += split.shift(); + * const remaining = split.join('\n\n'); + * const buf = Buffer.from(remaining, 'utf8'); + * stream.removeListener('error', callback); + * // Remove the 'readable' listener before unshifting. + * stream.removeListener('readable', onReadable); + * if (buf.length) + * stream.unshift(buf); + * // Now the body of the message can be read from the stream. + * callback(null, header, stream); + * return; + * } + * // Still reading the header. + * header += str; + * } + * } + * } + * ``` + * + * Unlike {@link push}, `stream.unshift(chunk)` will not + * end the reading process by resetting the internal reading state of the stream. + * This can cause unexpected results if `readable.unshift()` is called during a + * read (i.e. from within a {@link _read} implementation on a + * custom stream). Following the call to `readable.unshift()` with an immediate {@link push} will reset the reading state appropriately, + * however it is best to simply avoid calling `readable.unshift()` while in the + * process of performing a read. + * @since v0.9.11 + * @param chunk Chunk of data to unshift onto the read queue. For streams not operating in object mode, `chunk` must be a string, `Buffer`, `Uint8Array` or `null`. For object mode + * streams, `chunk` may be any JavaScript value. + * @param encoding Encoding of string chunks. Must be a valid `Buffer` encoding, such as `'utf8'` or `'ascii'`. + */ + unshift(chunk: any, encoding?: BufferEncoding): void; + /** + * Prior to Node.js 0.10, streams did not implement the entire `stream` module API + * as it is currently defined. (See `Compatibility` for more information.) + * + * When using an older Node.js library that emits `'data'` events and has a {@link pause} method that is advisory only, the`readable.wrap()` method can be used to create a `Readable` + * stream that uses + * the old stream as its data source. + * + * It will rarely be necessary to use `readable.wrap()` but the method has been + * provided as a convenience for interacting with older Node.js applications and + * libraries. + * + * ```js + * const { OldReader } = require('./old-api-module.js'); + * const { Readable } = require('stream'); + * const oreader = new OldReader(); + * const myReader = new Readable().wrap(oreader); + * + * myReader.on('readable', () => { + * myReader.read(); // etc. + * }); + * ``` + * @since v0.9.4 + * @param stream An "old style" readable stream + */ + wrap(stream: NodeJS.ReadableStream): this; + push(chunk: any, encoding?: BufferEncoding): boolean; + _destroy(error: Error | null, callback: (error?: Error | null) => void): void; + /** + * Destroy the stream. Optionally emit an `'error'` event, and emit a `'close'`event (unless `emitClose` is set to `false`). After this call, the readable + * stream will release any internal resources and subsequent calls to `push()`will be ignored. + * + * Once `destroy()` has been called any further calls will be a no-op and no + * further errors except from `_destroy()` may be emitted as `'error'`. + * + * Implementors should not override this method, but instead implement `readable._destroy()`. + * @since v8.0.0 + * @param error Error which will be passed as payload in `'error'` event + */ + destroy(error?: Error): this; + /** + * Event emitter + * The defined events on documents including: + * 1. close + * 2. data + * 3. end + * 4. error + * 5. pause + * 6. readable + * 7. resume + */ + addListener(event: 'close', listener: () => void): this; + addListener(event: 'data', listener: (chunk: any) => void): this; + addListener(event: 'end', listener: () => void): this; + addListener(event: 'error', listener: (err: Error) => void): this; + addListener(event: 'pause', listener: () => void): this; + addListener(event: 'readable', listener: () => void): this; + addListener(event: 'resume', listener: () => void): this; + addListener(event: string | symbol, listener: (...args: any[]) => void): this; + emit(event: 'close'): boolean; + emit(event: 'data', chunk: any): boolean; + emit(event: 'end'): boolean; + emit(event: 'error', err: Error): boolean; + emit(event: 'pause'): boolean; + emit(event: 'readable'): boolean; + emit(event: 'resume'): boolean; + emit(event: string | symbol, ...args: any[]): boolean; + on(event: 'close', listener: () => void): this; + on(event: 'data', listener: (chunk: any) => void): this; + on(event: 'end', listener: () => void): this; + on(event: 'error', listener: (err: Error) => void): this; + on(event: 'pause', listener: () => void): this; + on(event: 'readable', listener: () => void): this; + on(event: 'resume', listener: () => void): this; + on(event: string | symbol, listener: (...args: any[]) => void): this; + once(event: 'close', listener: () => void): this; + once(event: 'data', listener: (chunk: any) => void): this; + once(event: 'end', listener: () => void): this; + once(event: 'error', listener: (err: Error) => void): this; + once(event: 'pause', listener: () => void): this; + once(event: 'readable', listener: () => void): this; + once(event: 'resume', listener: () => void): this; + once(event: string | symbol, listener: (...args: any[]) => void): this; + prependListener(event: 'close', listener: () => void): this; + prependListener(event: 'data', listener: (chunk: any) => void): this; + prependListener(event: 'end', listener: () => void): this; + prependListener(event: 'error', listener: (err: Error) => void): this; + prependListener(event: 'pause', listener: () => void): this; + prependListener(event: 'readable', listener: () => void): this; + prependListener(event: 'resume', listener: () => void): this; + prependListener(event: string | symbol, listener: (...args: any[]) => void): this; + prependOnceListener(event: 'close', listener: () => void): this; + prependOnceListener(event: 'data', listener: (chunk: any) => void): this; + prependOnceListener(event: 'end', listener: () => void): this; + prependOnceListener(event: 'error', listener: (err: Error) => void): this; + prependOnceListener(event: 'pause', listener: () => void): this; + prependOnceListener(event: 'readable', listener: () => void): this; + prependOnceListener(event: 'resume', listener: () => void): this; + prependOnceListener(event: string | symbol, listener: (...args: any[]) => void): this; + removeListener(event: 'close', listener: () => void): this; + removeListener(event: 'data', listener: (chunk: any) => void): this; + removeListener(event: 'end', listener: () => void): this; + removeListener(event: 'error', listener: (err: Error) => void): this; + removeListener(event: 'pause', listener: () => void): this; + removeListener(event: 'readable', listener: () => void): this; + removeListener(event: 'resume', listener: () => void): this; + removeListener(event: string | symbol, listener: (...args: any[]) => void): this; + [Symbol.asyncIterator](): AsyncIterableIterator; + } + interface WritableOptions extends StreamOptions { + decodeStrings?: boolean | undefined; + defaultEncoding?: BufferEncoding | undefined; + write?(this: Writable, chunk: any, encoding: BufferEncoding, callback: (error?: Error | null) => void): void; + writev?( + this: Writable, + chunks: Array<{ + chunk: any; + encoding: BufferEncoding; + }>, + callback: (error?: Error | null) => void + ): void; + final?(this: Writable, callback: (error?: Error | null) => void): void; + } + /** + * @since v0.9.4 + */ + class Writable extends Stream implements NodeJS.WritableStream { + /** + * A utility method for creating a `Writable` from a web `WritableStream`. + * @since v17.0.0 + * @experimental + */ + static fromWeb(writableStream: streamWeb.WritableStream, options?: Pick): Writable; + /** + * A utility method for creating a web `WritableStream` from a `Writable`. + * @since v17.0.0 + * @experimental + */ + static toWeb(streamWritable: Writable): streamWeb.WritableStream; + /** + * Is `true` if it is safe to call `writable.write()`, which means + * the stream has not been destroyed, errored or ended. + * @since v11.4.0 + */ + readonly writable: boolean; + /** + * Is `true` after `writable.end()` has been called. This property + * does not indicate whether the data has been flushed, for this use `writable.writableFinished` instead. + * @since v12.9.0 + */ + readonly writableEnded: boolean; + /** + * Is set to `true` immediately before the `'finish'` event is emitted. + * @since v12.6.0 + */ + readonly writableFinished: boolean; + /** + * Return the value of `highWaterMark` passed when creating this `Writable`. + * @since v9.3.0 + */ + readonly writableHighWaterMark: number; + /** + * This property contains the number of bytes (or objects) in the queue + * ready to be written. The value provides introspection data regarding + * the status of the `highWaterMark`. + * @since v9.4.0 + */ + readonly writableLength: number; + /** + * Getter for the property `objectMode` of a given `Writable` stream. + * @since v12.3.0 + */ + readonly writableObjectMode: boolean; + /** + * Number of times `writable.uncork()` needs to be + * called in order to fully uncork the stream. + * @since v13.2.0, v12.16.0 + */ + readonly writableCorked: number; + /** + * Is `true` after `writable.destroy()` has been called. + * @since v8.0.0 + */ + destroyed: boolean; + /** + * Is true after 'close' has been emitted. + * @since v8.0.0 + */ + readonly closed: boolean; + /** + * Returns error if the stream has been destroyed with an error. + * @since v18.0.0 + */ + readonly errored: Error | null; + /** + * Is `true` if the stream's buffer has been full and stream will emit 'drain'. + * @since v15.2.0, v14.17.0 + */ + readonly writableNeedDrain: boolean; + constructor(opts?: WritableOptions); + _write(chunk: any, encoding: BufferEncoding, callback: (error?: Error | null) => void): void; + _writev?( + chunks: Array<{ + chunk: any; + encoding: BufferEncoding; + }>, + callback: (error?: Error | null) => void + ): void; + _construct?(callback: (error?: Error | null) => void): void; + _destroy(error: Error | null, callback: (error?: Error | null) => void): void; + _final(callback: (error?: Error | null) => void): void; + /** + * The `writable.write()` method writes some data to the stream, and calls the + * supplied `callback` once the data has been fully handled. If an error + * occurs, the `callback` will be called with the error as its + * first argument. The `callback` is called asynchronously and before `'error'` is + * emitted. + * + * The return value is `true` if the internal buffer is less than the`highWaterMark` configured when the stream was created after admitting `chunk`. + * If `false` is returned, further attempts to write data to the stream should + * stop until the `'drain'` event is emitted. + * + * While a stream is not draining, calls to `write()` will buffer `chunk`, and + * return false. Once all currently buffered chunks are drained (accepted for + * delivery by the operating system), the `'drain'` event will be emitted. + * Once `write()` returns false, do not write more chunks + * until the `'drain'` event is emitted. While calling `write()` on a stream that + * is not draining is allowed, Node.js will buffer all written chunks until + * maximum memory usage occurs, at which point it will abort unconditionally. + * Even before it aborts, high memory usage will cause poor garbage collector + * performance and high RSS (which is not typically released back to the system, + * even after the memory is no longer required). Since TCP sockets may never + * drain if the remote peer does not read the data, writing a socket that is + * not draining may lead to a remotely exploitable vulnerability. + * + * Writing data while the stream is not draining is particularly + * problematic for a `Transform`, because the `Transform` streams are paused + * by default until they are piped or a `'data'` or `'readable'` event handler + * is added. + * + * If the data to be written can be generated or fetched on demand, it is + * recommended to encapsulate the logic into a `Readable` and use {@link pipe}. However, if calling `write()` is preferred, it is + * possible to respect backpressure and avoid memory issues using the `'drain'` event: + * + * ```js + * function write(data, cb) { + * if (!stream.write(data)) { + * stream.once('drain', cb); + * } else { + * process.nextTick(cb); + * } + * } + * + * // Wait for cb to be called before doing any other write. + * write('hello', () => { + * console.log('Write completed, do more writes now.'); + * }); + * ``` + * + * A `Writable` stream in object mode will always ignore the `encoding` argument. + * @since v0.9.4 + * @param chunk Optional data to write. For streams not operating in object mode, `chunk` must be a string, `Buffer` or `Uint8Array`. For object mode streams, `chunk` may be any + * JavaScript value other than `null`. + * @param [encoding='utf8'] The encoding, if `chunk` is a string. + * @param callback Callback for when this chunk of data is flushed. + * @return `false` if the stream wishes for the calling code to wait for the `'drain'` event to be emitted before continuing to write additional data; otherwise `true`. + */ + write(chunk: any, callback?: (error: Error | null | undefined) => void): boolean; + write(chunk: any, encoding: BufferEncoding, callback?: (error: Error | null | undefined) => void): boolean; + /** + * The `writable.setDefaultEncoding()` method sets the default `encoding` for a `Writable` stream. + * @since v0.11.15 + * @param encoding The new default encoding + */ + setDefaultEncoding(encoding: BufferEncoding): this; + /** + * Calling the `writable.end()` method signals that no more data will be written + * to the `Writable`. The optional `chunk` and `encoding` arguments allow one + * final additional chunk of data to be written immediately before closing the + * stream. + * + * Calling the {@link write} method after calling {@link end} will raise an error. + * + * ```js + * // Write 'hello, ' and then end with 'world!'. + * const fs = require('fs'); + * const file = fs.createWriteStream('example.txt'); + * file.write('hello, '); + * file.end('world!'); + * // Writing more now is not allowed! + * ``` + * @since v0.9.4 + * @param chunk Optional data to write. For streams not operating in object mode, `chunk` must be a string, `Buffer` or `Uint8Array`. For object mode streams, `chunk` may be any + * JavaScript value other than `null`. + * @param encoding The encoding if `chunk` is a string + * @param callback Callback for when the stream is finished. + */ + end(cb?: () => void): this; + end(chunk: any, cb?: () => void): this; + end(chunk: any, encoding: BufferEncoding, cb?: () => void): this; + /** + * The `writable.cork()` method forces all written data to be buffered in memory. + * The buffered data will be flushed when either the {@link uncork} or {@link end} methods are called. + * + * The primary intent of `writable.cork()` is to accommodate a situation in which + * several small chunks are written to the stream in rapid succession. Instead of + * immediately forwarding them to the underlying destination, `writable.cork()`buffers all the chunks until `writable.uncork()` is called, which will pass them + * all to `writable._writev()`, if present. This prevents a head-of-line blocking + * situation where data is being buffered while waiting for the first small chunk + * to be processed. However, use of `writable.cork()` without implementing`writable._writev()` may have an adverse effect on throughput. + * + * See also: `writable.uncork()`, `writable._writev()`. + * @since v0.11.2 + */ + cork(): void; + /** + * The `writable.uncork()` method flushes all data buffered since {@link cork} was called. + * + * When using `writable.cork()` and `writable.uncork()` to manage the buffering + * of writes to a stream, defer calls to `writable.uncork()` using`process.nextTick()`. Doing so allows batching of all`writable.write()` calls that occur within a given Node.js event + * loop phase. + * + * ```js + * stream.cork(); + * stream.write('some '); + * stream.write('data '); + * process.nextTick(() => stream.uncork()); + * ``` + * + * If the `writable.cork()` method is called multiple times on a stream, the + * same number of calls to `writable.uncork()` must be called to flush the buffered + * data. + * + * ```js + * stream.cork(); + * stream.write('some '); + * stream.cork(); + * stream.write('data '); + * process.nextTick(() => { + * stream.uncork(); + * // The data will not be flushed until uncork() is called a second time. + * stream.uncork(); + * }); + * ``` + * + * See also: `writable.cork()`. + * @since v0.11.2 + */ + uncork(): void; + /** + * Destroy the stream. Optionally emit an `'error'` event, and emit a `'close'`event (unless `emitClose` is set to `false`). After this call, the writable + * stream has ended and subsequent calls to `write()` or `end()` will result in + * an `ERR_STREAM_DESTROYED` error. + * This is a destructive and immediate way to destroy a stream. Previous calls to`write()` may not have drained, and may trigger an `ERR_STREAM_DESTROYED` error. + * Use `end()` instead of destroy if data should flush before close, or wait for + * the `'drain'` event before destroying the stream. + * + * Once `destroy()` has been called any further calls will be a no-op and no + * further errors except from `_destroy()` may be emitted as `'error'`. + * + * Implementors should not override this method, + * but instead implement `writable._destroy()`. + * @since v8.0.0 + * @param error Optional, an error to emit with `'error'` event. + */ + destroy(error?: Error): this; + /** + * Event emitter + * The defined events on documents including: + * 1. close + * 2. drain + * 3. error + * 4. finish + * 5. pipe + * 6. unpipe + */ + addListener(event: 'close', listener: () => void): this; + addListener(event: 'drain', listener: () => void): this; + addListener(event: 'error', listener: (err: Error) => void): this; + addListener(event: 'finish', listener: () => void): this; + addListener(event: 'pipe', listener: (src: Readable) => void): this; + addListener(event: 'unpipe', listener: (src: Readable) => void): this; + addListener(event: string | symbol, listener: (...args: any[]) => void): this; + emit(event: 'close'): boolean; + emit(event: 'drain'): boolean; + emit(event: 'error', err: Error): boolean; + emit(event: 'finish'): boolean; + emit(event: 'pipe', src: Readable): boolean; + emit(event: 'unpipe', src: Readable): boolean; + emit(event: string | symbol, ...args: any[]): boolean; + on(event: 'close', listener: () => void): this; + on(event: 'drain', listener: () => void): this; + on(event: 'error', listener: (err: Error) => void): this; + on(event: 'finish', listener: () => void): this; + on(event: 'pipe', listener: (src: Readable) => void): this; + on(event: 'unpipe', listener: (src: Readable) => void): this; + on(event: string | symbol, listener: (...args: any[]) => void): this; + once(event: 'close', listener: () => void): this; + once(event: 'drain', listener: () => void): this; + once(event: 'error', listener: (err: Error) => void): this; + once(event: 'finish', listener: () => void): this; + once(event: 'pipe', listener: (src: Readable) => void): this; + once(event: 'unpipe', listener: (src: Readable) => void): this; + once(event: string | symbol, listener: (...args: any[]) => void): this; + prependListener(event: 'close', listener: () => void): this; + prependListener(event: 'drain', listener: () => void): this; + prependListener(event: 'error', listener: (err: Error) => void): this; + prependListener(event: 'finish', listener: () => void): this; + prependListener(event: 'pipe', listener: (src: Readable) => void): this; + prependListener(event: 'unpipe', listener: (src: Readable) => void): this; + prependListener(event: string | symbol, listener: (...args: any[]) => void): this; + prependOnceListener(event: 'close', listener: () => void): this; + prependOnceListener(event: 'drain', listener: () => void): this; + prependOnceListener(event: 'error', listener: (err: Error) => void): this; + prependOnceListener(event: 'finish', listener: () => void): this; + prependOnceListener(event: 'pipe', listener: (src: Readable) => void): this; + prependOnceListener(event: 'unpipe', listener: (src: Readable) => void): this; + prependOnceListener(event: string | symbol, listener: (...args: any[]) => void): this; + removeListener(event: 'close', listener: () => void): this; + removeListener(event: 'drain', listener: () => void): this; + removeListener(event: 'error', listener: (err: Error) => void): this; + removeListener(event: 'finish', listener: () => void): this; + removeListener(event: 'pipe', listener: (src: Readable) => void): this; + removeListener(event: 'unpipe', listener: (src: Readable) => void): this; + removeListener(event: string | symbol, listener: (...args: any[]) => void): this; + } + interface DuplexOptions extends ReadableOptions, WritableOptions { + allowHalfOpen?: boolean | undefined; + readableObjectMode?: boolean | undefined; + writableObjectMode?: boolean | undefined; + readableHighWaterMark?: number | undefined; + writableHighWaterMark?: number | undefined; + writableCorked?: number | undefined; + construct?(this: Duplex, callback: (error?: Error | null) => void): void; + read?(this: Duplex, size: number): void; + write?(this: Duplex, chunk: any, encoding: BufferEncoding, callback: (error?: Error | null) => void): void; + writev?( + this: Duplex, + chunks: Array<{ + chunk: any; + encoding: BufferEncoding; + }>, + callback: (error?: Error | null) => void + ): void; + final?(this: Duplex, callback: (error?: Error | null) => void): void; + destroy?(this: Duplex, error: Error | null, callback: (error: Error | null) => void): void; + } + /** + * Duplex streams are streams that implement both the `Readable` and `Writable` interfaces. + * + * Examples of `Duplex` streams include: + * + * * `TCP sockets` + * * `zlib streams` + * * `crypto streams` + * @since v0.9.4 + */ + class Duplex extends Readable implements Writable { + readonly writable: boolean; + readonly writableEnded: boolean; + readonly writableFinished: boolean; + readonly writableHighWaterMark: number; + readonly writableLength: number; + readonly writableObjectMode: boolean; + readonly writableCorked: number; + readonly writableNeedDrain: boolean; + readonly closed: boolean; + readonly errored: Error | null; + /** + * If `false` then the stream will automatically end the writable side when the + * readable side ends. Set initially by the `allowHalfOpen` constructor option, + * which defaults to `false`. + * + * This can be changed manually to change the half-open behavior of an existing`Duplex` stream instance, but must be changed before the `'end'` event is + * emitted. + * @since v0.9.4 + */ + allowHalfOpen: boolean; + constructor(opts?: DuplexOptions); + /** + * A utility method for creating duplex streams. + * + * - `Stream` converts writable stream into writable `Duplex` and readable stream + * to `Duplex`. + * - `Blob` converts into readable `Duplex`. + * - `string` converts into readable `Duplex`. + * - `ArrayBuffer` converts into readable `Duplex`. + * - `AsyncIterable` converts into a readable `Duplex`. Cannot yield `null`. + * - `AsyncGeneratorFunction` converts into a readable/writable transform + * `Duplex`. Must take a source `AsyncIterable` as first parameter. Cannot yield + * `null`. + * - `AsyncFunction` converts into a writable `Duplex`. Must return + * either `null` or `undefined` + * - `Object ({ writable, readable })` converts `readable` and + * `writable` into `Stream` and then combines them into `Duplex` where the + * `Duplex` will write to the `writable` and read from the `readable`. + * - `Promise` converts into readable `Duplex`. Value `null` is ignored. + * + * @since v16.8.0 + */ + static from(src: Stream | Blob | ArrayBuffer | string | Iterable | AsyncIterable | AsyncGeneratorFunction | Promise | Object): Duplex; + _write(chunk: any, encoding: BufferEncoding, callback: (error?: Error | null) => void): void; + _writev?( + chunks: Array<{ + chunk: any; + encoding: BufferEncoding; + }>, + callback: (error?: Error | null) => void + ): void; + _destroy(error: Error | null, callback: (error: Error | null) => void): void; + _final(callback: (error?: Error | null) => void): void; + write(chunk: any, encoding?: BufferEncoding, cb?: (error: Error | null | undefined) => void): boolean; + write(chunk: any, cb?: (error: Error | null | undefined) => void): boolean; + setDefaultEncoding(encoding: BufferEncoding): this; + end(cb?: () => void): this; + end(chunk: any, cb?: () => void): this; + end(chunk: any, encoding?: BufferEncoding, cb?: () => void): this; + cork(): void; + uncork(): void; + } + type TransformCallback = (error?: Error | null, data?: any) => void; + interface TransformOptions extends DuplexOptions { + construct?(this: Transform, callback: (error?: Error | null) => void): void; + read?(this: Transform, size: number): void; + write?(this: Transform, chunk: any, encoding: BufferEncoding, callback: (error?: Error | null) => void): void; + writev?( + this: Transform, + chunks: Array<{ + chunk: any; + encoding: BufferEncoding; + }>, + callback: (error?: Error | null) => void + ): void; + final?(this: Transform, callback: (error?: Error | null) => void): void; + destroy?(this: Transform, error: Error | null, callback: (error: Error | null) => void): void; + transform?(this: Transform, chunk: any, encoding: BufferEncoding, callback: TransformCallback): void; + flush?(this: Transform, callback: TransformCallback): void; + } + /** + * Transform streams are `Duplex` streams where the output is in some way + * related to the input. Like all `Duplex` streams, `Transform` streams + * implement both the `Readable` and `Writable` interfaces. + * + * Examples of `Transform` streams include: + * + * * `zlib streams` + * * `crypto streams` + * @since v0.9.4 + */ + class Transform extends Duplex { + constructor(opts?: TransformOptions); + _transform(chunk: any, encoding: BufferEncoding, callback: TransformCallback): void; + _flush(callback: TransformCallback): void; + } + /** + * The `stream.PassThrough` class is a trivial implementation of a `Transform` stream that simply passes the input bytes across to the output. Its purpose is + * primarily for examples and testing, but there are some use cases where`stream.PassThrough` is useful as a building block for novel sorts of streams. + */ + class PassThrough extends Transform {} + /** + * Attaches an AbortSignal to a readable or writeable stream. This lets code + * control stream destruction using an `AbortController`. + * + * Calling `abort` on the `AbortController` corresponding to the passed`AbortSignal` will behave the same way as calling `.destroy(new AbortError())`on the stream. + * + * ```js + * const fs = require('fs'); + * + * const controller = new AbortController(); + * const read = addAbortSignal( + * controller.signal, + * fs.createReadStream(('object.json')) + * ); + * // Later, abort the operation closing the stream + * controller.abort(); + * ``` + * + * Or using an `AbortSignal` with a readable stream as an async iterable: + * + * ```js + * const controller = new AbortController(); + * setTimeout(() => controller.abort(), 10_000); // set a timeout + * const stream = addAbortSignal( + * controller.signal, + * fs.createReadStream(('object.json')) + * ); + * (async () => { + * try { + * for await (const chunk of stream) { + * await process(chunk); + * } + * } catch (e) { + * if (e.name === 'AbortError') { + * // The operation was cancelled + * } else { + * throw e; + * } + * } + * })(); + * ``` + * @since v15.4.0 + * @param signal A signal representing possible cancellation + * @param stream a stream to attach a signal to + */ + function addAbortSignal(signal: AbortSignal, stream: T): T; + interface FinishedOptions extends Abortable { + error?: boolean | undefined; + readable?: boolean | undefined; + writable?: boolean | undefined; + } + /** + * A function to get notified when a stream is no longer readable, writable + * or has experienced an error or a premature close event. + * + * ```js + * const { finished } = require('stream'); + * + * const rs = fs.createReadStream('archive.tar'); + * + * finished(rs, (err) => { + * if (err) { + * console.error('Stream failed.', err); + * } else { + * console.log('Stream is done reading.'); + * } + * }); + * + * rs.resume(); // Drain the stream. + * ``` + * + * Especially useful in error handling scenarios where a stream is destroyed + * prematurely (like an aborted HTTP request), and will not emit `'end'`or `'finish'`. + * + * The `finished` API provides promise version: + * + * ```js + * const { finished } = require('stream/promises'); + * + * const rs = fs.createReadStream('archive.tar'); + * + * async function run() { + * await finished(rs); + * console.log('Stream is done reading.'); + * } + * + * run().catch(console.error); + * rs.resume(); // Drain the stream. + * ``` + * + * `stream.finished()` leaves dangling event listeners (in particular`'error'`, `'end'`, `'finish'` and `'close'`) after `callback` has been + * invoked. The reason for this is so that unexpected `'error'` events (due to + * incorrect stream implementations) do not cause unexpected crashes. + * If this is unwanted behavior then the returned cleanup function needs to be + * invoked in the callback: + * + * ```js + * const cleanup = finished(rs, (err) => { + * cleanup(); + * // ... + * }); + * ``` + * @since v10.0.0 + * @param stream A readable and/or writable stream. + * @param callback A callback function that takes an optional error argument. + * @return A cleanup function which removes all registered listeners. + */ + function finished(stream: NodeJS.ReadableStream | NodeJS.WritableStream | NodeJS.ReadWriteStream, options: FinishedOptions, callback: (err?: NodeJS.ErrnoException | null) => void): () => void; + function finished(stream: NodeJS.ReadableStream | NodeJS.WritableStream | NodeJS.ReadWriteStream, callback: (err?: NodeJS.ErrnoException | null) => void): () => void; + namespace finished { + function __promisify__(stream: NodeJS.ReadableStream | NodeJS.WritableStream | NodeJS.ReadWriteStream, options?: FinishedOptions): Promise; + } + type PipelineSourceFunction = () => Iterable | AsyncIterable; + type PipelineSource = Iterable | AsyncIterable | NodeJS.ReadableStream | PipelineSourceFunction; + type PipelineTransform, U> = + | NodeJS.ReadWriteStream + | ((source: S extends (...args: any[]) => Iterable | AsyncIterable ? AsyncIterable : S) => AsyncIterable); + type PipelineTransformSource = PipelineSource | PipelineTransform; + type PipelineDestinationIterableFunction = (source: AsyncIterable) => AsyncIterable; + type PipelineDestinationPromiseFunction = (source: AsyncIterable) => Promise

; + type PipelineDestination, P> = S extends PipelineTransformSource + ? NodeJS.WritableStream | PipelineDestinationIterableFunction | PipelineDestinationPromiseFunction + : never; + type PipelineCallback> = S extends PipelineDestinationPromiseFunction + ? (err: NodeJS.ErrnoException | null, value: P) => void + : (err: NodeJS.ErrnoException | null) => void; + type PipelinePromise> = S extends PipelineDestinationPromiseFunction ? Promise

: Promise; + interface PipelineOptions { + signal: AbortSignal; + } + /** + * A module method to pipe between streams and generators forwarding errors and + * properly cleaning up and provide a callback when the pipeline is complete. + * + * ```js + * const { pipeline } = require('stream'); + * const fs = require('fs'); + * const zlib = require('zlib'); + * + * // Use the pipeline API to easily pipe a series of streams + * // together and get notified when the pipeline is fully done. + * + * // A pipeline to gzip a potentially huge tar file efficiently: + * + * pipeline( + * fs.createReadStream('archive.tar'), + * zlib.createGzip(), + * fs.createWriteStream('archive.tar.gz'), + * (err) => { + * if (err) { + * console.error('Pipeline failed.', err); + * } else { + * console.log('Pipeline succeeded.'); + * } + * } + * ); + * ``` + * + * The `pipeline` API provides a promise version, which can also + * receive an options argument as the last parameter with a`signal` `AbortSignal` property. When the signal is aborted,`destroy` will be called on the underlying pipeline, with + * an`AbortError`. + * + * ```js + * const { pipeline } = require('stream/promises'); + * + * async function run() { + * await pipeline( + * fs.createReadStream('archive.tar'), + * zlib.createGzip(), + * fs.createWriteStream('archive.tar.gz') + * ); + * console.log('Pipeline succeeded.'); + * } + * + * run().catch(console.error); + * ``` + * + * To use an `AbortSignal`, pass it inside an options object, + * as the last argument: + * + * ```js + * const { pipeline } = require('stream/promises'); + * + * async function run() { + * const ac = new AbortController(); + * const signal = ac.signal; + * + * setTimeout(() => ac.abort(), 1); + * await pipeline( + * fs.createReadStream('archive.tar'), + * zlib.createGzip(), + * fs.createWriteStream('archive.tar.gz'), + * { signal }, + * ); + * } + * + * run().catch(console.error); // AbortError + * ``` + * + * The `pipeline` API also supports async generators: + * + * ```js + * const { pipeline } = require('stream/promises'); + * const fs = require('fs'); + * + * async function run() { + * await pipeline( + * fs.createReadStream('lowercase.txt'), + * async function* (source, { signal }) { + * source.setEncoding('utf8'); // Work with strings rather than `Buffer`s. + * for await (const chunk of source) { + * yield await processChunk(chunk, { signal }); + * } + * }, + * fs.createWriteStream('uppercase.txt') + * ); + * console.log('Pipeline succeeded.'); + * } + * + * run().catch(console.error); + * ``` + * + * Remember to handle the `signal` argument passed into the async generator. + * Especially in the case where the async generator is the source for the + * pipeline (i.e. first argument) or the pipeline will never complete. + * + * ```js + * const { pipeline } = require('stream/promises'); + * const fs = require('fs'); + * + * async function run() { + * await pipeline( + * async function* ({ signal }) { + * await someLongRunningfn({ signal }); + * yield 'asd'; + * }, + * fs.createWriteStream('uppercase.txt') + * ); + * console.log('Pipeline succeeded.'); + * } + * + * run().catch(console.error); + * ``` + * + * `stream.pipeline()` will call `stream.destroy(err)` on all streams except: + * + * * `Readable` streams which have emitted `'end'` or `'close'`. + * * `Writable` streams which have emitted `'finish'` or `'close'`. + * + * `stream.pipeline()` leaves dangling event listeners on the streams + * after the `callback` has been invoked. In the case of reuse of streams after + * failure, this can cause event listener leaks and swallowed errors. If the last + * stream is readable, dangling event listeners will be removed so that the last + * stream can be consumed later. + * + * `stream.pipeline()` closes all the streams when an error is raised. + * The `IncomingRequest` usage with `pipeline` could lead to an unexpected behavior + * once it would destroy the socket without sending the expected response. + * See the example below: + * + * ```js + * const fs = require('fs'); + * const http = require('http'); + * const { pipeline } = require('stream'); + * + * const server = http.createServer((req, res) => { + * const fileStream = fs.createReadStream('./fileNotExist.txt'); + * pipeline(fileStream, res, (err) => { + * if (err) { + * console.log(err); // No such file + * // this message can't be sent once `pipeline` already destroyed the socket + * return res.end('error!!!'); + * } + * }); + * }); + * ``` + * @since v10.0.0 + * @param callback Called when the pipeline is fully done. + */ + function pipeline, B extends PipelineDestination>( + source: A, + destination: B, + callback?: PipelineCallback + ): B extends NodeJS.WritableStream ? B : NodeJS.WritableStream; + function pipeline, T1 extends PipelineTransform, B extends PipelineDestination>( + source: A, + transform1: T1, + destination: B, + callback?: PipelineCallback + ): B extends NodeJS.WritableStream ? B : NodeJS.WritableStream; + function pipeline, T1 extends PipelineTransform, T2 extends PipelineTransform, B extends PipelineDestination>( + source: A, + transform1: T1, + transform2: T2, + destination: B, + callback?: PipelineCallback + ): B extends NodeJS.WritableStream ? B : NodeJS.WritableStream; + function pipeline< + A extends PipelineSource, + T1 extends PipelineTransform, + T2 extends PipelineTransform, + T3 extends PipelineTransform, + B extends PipelineDestination + >(source: A, transform1: T1, transform2: T2, transform3: T3, destination: B, callback?: PipelineCallback): B extends NodeJS.WritableStream ? B : NodeJS.WritableStream; + function pipeline< + A extends PipelineSource, + T1 extends PipelineTransform, + T2 extends PipelineTransform, + T3 extends PipelineTransform, + T4 extends PipelineTransform, + B extends PipelineDestination + >(source: A, transform1: T1, transform2: T2, transform3: T3, transform4: T4, destination: B, callback?: PipelineCallback): B extends NodeJS.WritableStream ? B : NodeJS.WritableStream; + function pipeline( + streams: ReadonlyArray, + callback?: (err: NodeJS.ErrnoException | null) => void + ): NodeJS.WritableStream; + function pipeline( + stream1: NodeJS.ReadableStream, + stream2: NodeJS.ReadWriteStream | NodeJS.WritableStream, + ...streams: Array void)> + ): NodeJS.WritableStream; + namespace pipeline { + function __promisify__, B extends PipelineDestination>(source: A, destination: B, options?: PipelineOptions): PipelinePromise; + function __promisify__, T1 extends PipelineTransform, B extends PipelineDestination>( + source: A, + transform1: T1, + destination: B, + options?: PipelineOptions + ): PipelinePromise; + function __promisify__, T1 extends PipelineTransform, T2 extends PipelineTransform, B extends PipelineDestination>( + source: A, + transform1: T1, + transform2: T2, + destination: B, + options?: PipelineOptions + ): PipelinePromise; + function __promisify__< + A extends PipelineSource, + T1 extends PipelineTransform, + T2 extends PipelineTransform, + T3 extends PipelineTransform, + B extends PipelineDestination + >(source: A, transform1: T1, transform2: T2, transform3: T3, destination: B, options?: PipelineOptions): PipelinePromise; + function __promisify__< + A extends PipelineSource, + T1 extends PipelineTransform, + T2 extends PipelineTransform, + T3 extends PipelineTransform, + T4 extends PipelineTransform, + B extends PipelineDestination + >(source: A, transform1: T1, transform2: T2, transform3: T3, transform4: T4, destination: B, options?: PipelineOptions): PipelinePromise; + function __promisify__(streams: ReadonlyArray, options?: PipelineOptions): Promise; + function __promisify__( + stream1: NodeJS.ReadableStream, + stream2: NodeJS.ReadWriteStream | NodeJS.WritableStream, + ...streams: Array + ): Promise; + } + interface Pipe { + close(): void; + hasRef(): boolean; + ref(): void; + unref(): void; + } + + /** + * Returns whether the stream has encountered an error. + * @since v17.3.0 + */ + function isErrored(stream: Readable | Writable | NodeJS.ReadableStream | NodeJS.WritableStream): boolean; + + /** + * Returns whether the stream is readable. + * @since v17.4.0 + */ + function isReadable(stream: Readable | NodeJS.ReadableStream): boolean; + + const promises: typeof streamPromises; + const consumers: typeof streamConsumers; + } + export = internal; +} +declare module 'node:stream' { + import stream = require('stream'); + export = stream; +} diff --git a/ts-ticket-office-service/node_modules/@types/node/stream/consumers.d.ts b/ts-ticket-office-service/node_modules/@types/node/stream/consumers.d.ts new file mode 100755 index 000000000..ce6c9bb78 --- /dev/null +++ b/ts-ticket-office-service/node_modules/@types/node/stream/consumers.d.ts @@ -0,0 +1,24 @@ +// Duplicates of interface in lib.dom.ts. +// Duplicated here rather than referencing lib.dom.ts because doing so causes lib.dom.ts to be loaded for "test-all" +// Which in turn causes tests to pass that shouldn't pass. +// +// This interface is not, and should not be, exported. +interface Blob { + readonly size: number; + readonly type: string; + arrayBuffer(): Promise; + slice(start?: number, end?: number, contentType?: string): Blob; + stream(): NodeJS.ReadableStream; + text(): Promise; +} +declare module 'stream/consumers' { + import { Readable } from 'node:stream'; + function buffer(stream: NodeJS.ReadableStream | Readable | AsyncIterator): Promise; + function text(stream: NodeJS.ReadableStream | Readable | AsyncIterator): Promise; + function arrayBuffer(stream: NodeJS.ReadableStream | Readable | AsyncIterator): Promise; + function blob(stream: NodeJS.ReadableStream | Readable | AsyncIterator): Promise; + function json(stream: NodeJS.ReadableStream | Readable | AsyncIterator): Promise; +} +declare module 'node:stream/consumers' { + export * from 'stream/consumers'; +} diff --git a/ts-ticket-office-service/node_modules/@types/node/stream/promises.d.ts b/ts-ticket-office-service/node_modules/@types/node/stream/promises.d.ts new file mode 100755 index 000000000..b427073de --- /dev/null +++ b/ts-ticket-office-service/node_modules/@types/node/stream/promises.d.ts @@ -0,0 +1,42 @@ +declare module 'stream/promises' { + import { FinishedOptions, PipelineSource, PipelineTransform, PipelineDestination, PipelinePromise, PipelineOptions } from 'node:stream'; + function finished(stream: NodeJS.ReadableStream | NodeJS.WritableStream | NodeJS.ReadWriteStream, options?: FinishedOptions): Promise; + function pipeline, B extends PipelineDestination>(source: A, destination: B, options?: PipelineOptions): PipelinePromise; + function pipeline, T1 extends PipelineTransform, B extends PipelineDestination>( + source: A, + transform1: T1, + destination: B, + options?: PipelineOptions + ): PipelinePromise; + function pipeline, T1 extends PipelineTransform, T2 extends PipelineTransform, B extends PipelineDestination>( + source: A, + transform1: T1, + transform2: T2, + destination: B, + options?: PipelineOptions + ): PipelinePromise; + function pipeline< + A extends PipelineSource, + T1 extends PipelineTransform, + T2 extends PipelineTransform, + T3 extends PipelineTransform, + B extends PipelineDestination + >(source: A, transform1: T1, transform2: T2, transform3: T3, destination: B, options?: PipelineOptions): PipelinePromise; + function pipeline< + A extends PipelineSource, + T1 extends PipelineTransform, + T2 extends PipelineTransform, + T3 extends PipelineTransform, + T4 extends PipelineTransform, + B extends PipelineDestination + >(source: A, transform1: T1, transform2: T2, transform3: T3, transform4: T4, destination: B, options?: PipelineOptions): PipelinePromise; + function pipeline(streams: ReadonlyArray, options?: PipelineOptions): Promise; + function pipeline( + stream1: NodeJS.ReadableStream, + stream2: NodeJS.ReadWriteStream | NodeJS.WritableStream, + ...streams: Array + ): Promise; +} +declare module 'node:stream/promises' { + export * from 'stream/promises'; +} diff --git a/ts-ticket-office-service/node_modules/@types/node/stream/web.d.ts b/ts-ticket-office-service/node_modules/@types/node/stream/web.d.ts new file mode 100755 index 000000000..f9ef0570d --- /dev/null +++ b/ts-ticket-office-service/node_modules/@types/node/stream/web.d.ts @@ -0,0 +1,330 @@ +declare module 'stream/web' { + // stub module, pending copy&paste from .d.ts or manual impl + // copy from lib.dom.d.ts + interface ReadableWritablePair { + readable: ReadableStream; + /** + * Provides a convenient, chainable way of piping this readable stream + * through a transform stream (or any other { writable, readable } + * pair). It simply pipes the stream into the writable side of the + * supplied pair, and returns the readable side for further use. + * + * Piping a stream will lock it for the duration of the pipe, preventing + * any other consumer from acquiring a reader. + */ + writable: WritableStream; + } + interface StreamPipeOptions { + preventAbort?: boolean; + preventCancel?: boolean; + /** + * Pipes this readable stream to a given writable stream destination. + * The way in which the piping process behaves under various error + * conditions can be customized with a number of passed options. It + * returns a promise that fulfills when the piping process completes + * successfully, or rejects if any errors were encountered. + * + * Piping a stream will lock it for the duration of the pipe, preventing + * any other consumer from acquiring a reader. + * + * Errors and closures of the source and destination streams propagate + * as follows: + * + * An error in this source readable stream will abort destination, + * unless preventAbort is truthy. The returned promise will be rejected + * with the source's error, or with any error that occurs during + * aborting the destination. + * + * An error in destination will cancel this source readable stream, + * unless preventCancel is truthy. The returned promise will be rejected + * with the destination's error, or with any error that occurs during + * canceling the source. + * + * When this source readable stream closes, destination will be closed, + * unless preventClose is truthy. The returned promise will be fulfilled + * once this process completes, unless an error is encountered while + * closing the destination, in which case it will be rejected with that + * error. + * + * If destination starts out closed or closing, this source readable + * stream will be canceled, unless preventCancel is true. The returned + * promise will be rejected with an error indicating piping to a closed + * stream failed, or with any error that occurs during canceling the + * source. + * + * The signal option can be set to an AbortSignal to allow aborting an + * ongoing pipe operation via the corresponding AbortController. In this + * case, this source readable stream will be canceled, and destination + * aborted, unless the respective options preventCancel or preventAbort + * are set. + */ + preventClose?: boolean; + signal?: AbortSignal; + } + interface ReadableStreamGenericReader { + readonly closed: Promise; + cancel(reason?: any): Promise; + } + interface ReadableStreamDefaultReadValueResult { + done: false; + value: T; + } + interface ReadableStreamDefaultReadDoneResult { + done: true; + value?: undefined; + } + type ReadableStreamController = ReadableStreamDefaultController; + type ReadableStreamDefaultReadResult = ReadableStreamDefaultReadValueResult | ReadableStreamDefaultReadDoneResult; + interface ReadableByteStreamControllerCallback { + (controller: ReadableByteStreamController): void | PromiseLike; + } + interface UnderlyingSinkAbortCallback { + (reason?: any): void | PromiseLike; + } + interface UnderlyingSinkCloseCallback { + (): void | PromiseLike; + } + interface UnderlyingSinkStartCallback { + (controller: WritableStreamDefaultController): any; + } + interface UnderlyingSinkWriteCallback { + (chunk: W, controller: WritableStreamDefaultController): void | PromiseLike; + } + interface UnderlyingSourceCancelCallback { + (reason?: any): void | PromiseLike; + } + interface UnderlyingSourcePullCallback { + (controller: ReadableStreamController): void | PromiseLike; + } + interface UnderlyingSourceStartCallback { + (controller: ReadableStreamController): any; + } + interface TransformerFlushCallback { + (controller: TransformStreamDefaultController): void | PromiseLike; + } + interface TransformerStartCallback { + (controller: TransformStreamDefaultController): any; + } + interface TransformerTransformCallback { + (chunk: I, controller: TransformStreamDefaultController): void | PromiseLike; + } + interface UnderlyingByteSource { + autoAllocateChunkSize?: number; + cancel?: ReadableStreamErrorCallback; + pull?: ReadableByteStreamControllerCallback; + start?: ReadableByteStreamControllerCallback; + type: 'bytes'; + } + interface UnderlyingSource { + cancel?: UnderlyingSourceCancelCallback; + pull?: UnderlyingSourcePullCallback; + start?: UnderlyingSourceStartCallback; + type?: undefined; + } + interface UnderlyingSink { + abort?: UnderlyingSinkAbortCallback; + close?: UnderlyingSinkCloseCallback; + start?: UnderlyingSinkStartCallback; + type?: undefined; + write?: UnderlyingSinkWriteCallback; + } + interface ReadableStreamErrorCallback { + (reason: any): void | PromiseLike; + } + /** This Streams API interface represents a readable stream of byte data. */ + interface ReadableStream { + readonly locked: boolean; + cancel(reason?: any): Promise; + getReader(): ReadableStreamDefaultReader; + pipeThrough(transform: ReadableWritablePair, options?: StreamPipeOptions): ReadableStream; + pipeTo(destination: WritableStream, options?: StreamPipeOptions): Promise; + tee(): [ReadableStream, ReadableStream]; + values(options?: { preventCancel?: boolean }): AsyncIterableIterator; + [Symbol.asyncIterator](): AsyncIterableIterator; + } + const ReadableStream: { + prototype: ReadableStream; + new (underlyingSource: UnderlyingByteSource, strategy?: QueuingStrategy): ReadableStream; + new (underlyingSource?: UnderlyingSource, strategy?: QueuingStrategy): ReadableStream; + }; + interface ReadableStreamDefaultReader extends ReadableStreamGenericReader { + read(): Promise>; + releaseLock(): void; + } + const ReadableStreamDefaultReader: { + prototype: ReadableStreamDefaultReader; + new (stream: ReadableStream): ReadableStreamDefaultReader; + }; + const ReadableStreamBYOBReader: any; + const ReadableStreamBYOBRequest: any; + interface ReadableByteStreamController { + readonly byobRequest: undefined; + readonly desiredSize: number | null; + close(): void; + enqueue(chunk: ArrayBufferView): void; + error(error?: any): void; + } + const ReadableByteStreamController: { + prototype: ReadableByteStreamController; + new (): ReadableByteStreamController; + }; + interface ReadableStreamDefaultController { + readonly desiredSize: number | null; + close(): void; + enqueue(chunk?: R): void; + error(e?: any): void; + } + const ReadableStreamDefaultController: { + prototype: ReadableStreamDefaultController; + new (): ReadableStreamDefaultController; + }; + interface Transformer { + flush?: TransformerFlushCallback; + readableType?: undefined; + start?: TransformerStartCallback; + transform?: TransformerTransformCallback; + writableType?: undefined; + } + interface TransformStream { + readonly readable: ReadableStream; + readonly writable: WritableStream; + } + const TransformStream: { + prototype: TransformStream; + new (transformer?: Transformer, writableStrategy?: QueuingStrategy, readableStrategy?: QueuingStrategy): TransformStream; + }; + interface TransformStreamDefaultController { + readonly desiredSize: number | null; + enqueue(chunk?: O): void; + error(reason?: any): void; + terminate(): void; + } + const TransformStreamDefaultController: { + prototype: TransformStreamDefaultController; + new (): TransformStreamDefaultController; + }; + /** + * This Streams API interface provides a standard abstraction for writing + * streaming data to a destination, known as a sink. This object comes with + * built-in back pressure and queuing. + */ + interface WritableStream { + readonly locked: boolean; + abort(reason?: any): Promise; + close(): Promise; + getWriter(): WritableStreamDefaultWriter; + } + const WritableStream: { + prototype: WritableStream; + new (underlyingSink?: UnderlyingSink, strategy?: QueuingStrategy): WritableStream; + }; + /** + * This Streams API interface is the object returned by + * WritableStream.getWriter() and once created locks the < writer to the + * WritableStream ensuring that no other streams can write to the underlying + * sink. + */ + interface WritableStreamDefaultWriter { + readonly closed: Promise; + readonly desiredSize: number | null; + readonly ready: Promise; + abort(reason?: any): Promise; + close(): Promise; + releaseLock(): void; + write(chunk?: W): Promise; + } + const WritableStreamDefaultWriter: { + prototype: WritableStreamDefaultWriter; + new (stream: WritableStream): WritableStreamDefaultWriter; + }; + /** + * This Streams API interface represents a controller allowing control of a + * WritableStream's state. When constructing a WritableStream, the + * underlying sink is given a corresponding WritableStreamDefaultController + * instance to manipulate. + */ + interface WritableStreamDefaultController { + error(e?: any): void; + } + const WritableStreamDefaultController: { + prototype: WritableStreamDefaultController; + new (): WritableStreamDefaultController; + }; + interface QueuingStrategy { + highWaterMark?: number; + size?: QueuingStrategySize; + } + interface QueuingStrategySize { + (chunk?: T): number; + } + interface QueuingStrategyInit { + /** + * Creates a new ByteLengthQueuingStrategy with the provided high water + * mark. + * + * Note that the provided high water mark will not be validated ahead of + * time. Instead, if it is negative, NaN, or not a number, the resulting + * ByteLengthQueuingStrategy will cause the corresponding stream + * constructor to throw. + */ + highWaterMark: number; + } + /** + * This Streams API interface provides a built-in byte length queuing + * strategy that can be used when constructing streams. + */ + interface ByteLengthQueuingStrategy extends QueuingStrategy { + readonly highWaterMark: number; + readonly size: QueuingStrategySize; + } + const ByteLengthQueuingStrategy: { + prototype: ByteLengthQueuingStrategy; + new (init: QueuingStrategyInit): ByteLengthQueuingStrategy; + }; + /** + * This Streams API interface provides a built-in byte length queuing + * strategy that can be used when constructing streams. + */ + interface CountQueuingStrategy extends QueuingStrategy { + readonly highWaterMark: number; + readonly size: QueuingStrategySize; + } + const CountQueuingStrategy: { + prototype: CountQueuingStrategy; + new (init: QueuingStrategyInit): CountQueuingStrategy; + }; + interface TextEncoderStream { + /** Returns "utf-8". */ + readonly encoding: 'utf-8'; + readonly readable: ReadableStream; + readonly writable: WritableStream; + readonly [Symbol.toStringTag]: string; + } + const TextEncoderStream: { + prototype: TextEncoderStream; + new (): TextEncoderStream; + }; + interface TextDecoderOptions { + fatal?: boolean; + ignoreBOM?: boolean; + } + type BufferSource = ArrayBufferView | ArrayBuffer; + interface TextDecoderStream { + /** Returns encoding's name, lower cased. */ + readonly encoding: string; + /** Returns `true` if error mode is "fatal", and `false` otherwise. */ + readonly fatal: boolean; + /** Returns `true` if ignore BOM flag is set, and `false` otherwise. */ + readonly ignoreBOM: boolean; + readonly readable: ReadableStream; + readonly writable: WritableStream; + readonly [Symbol.toStringTag]: string; + } + const TextDecoderStream: { + prototype: TextDecoderStream; + new (label?: string, options?: TextDecoderOptions): TextDecoderStream; + }; +} +declare module 'node:stream/web' { + export * from 'stream/web'; +} diff --git a/ts-ticket-office-service/node_modules/@types/node/string_decoder.d.ts b/ts-ticket-office-service/node_modules/@types/node/string_decoder.d.ts new file mode 100755 index 000000000..a58580411 --- /dev/null +++ b/ts-ticket-office-service/node_modules/@types/node/string_decoder.d.ts @@ -0,0 +1,67 @@ +/** + * The `string_decoder` module provides an API for decoding `Buffer` objects into + * strings in a manner that preserves encoded multi-byte UTF-8 and UTF-16 + * characters. It can be accessed using: + * + * ```js + * const { StringDecoder } = require('string_decoder'); + * ``` + * + * The following example shows the basic use of the `StringDecoder` class. + * + * ```js + * const { StringDecoder } = require('string_decoder'); + * const decoder = new StringDecoder('utf8'); + * + * const cent = Buffer.from([0xC2, 0xA2]); + * console.log(decoder.write(cent)); + * + * const euro = Buffer.from([0xE2, 0x82, 0xAC]); + * console.log(decoder.write(euro)); + * ``` + * + * When a `Buffer` instance is written to the `StringDecoder` instance, an + * internal buffer is used to ensure that the decoded string does not contain + * any incomplete multibyte characters. These are held in the buffer until the + * next call to `stringDecoder.write()` or until `stringDecoder.end()` is called. + * + * In the following example, the three UTF-8 encoded bytes of the European Euro + * symbol (`€`) are written over three separate operations: + * + * ```js + * const { StringDecoder } = require('string_decoder'); + * const decoder = new StringDecoder('utf8'); + * + * decoder.write(Buffer.from([0xE2])); + * decoder.write(Buffer.from([0x82])); + * console.log(decoder.end(Buffer.from([0xAC]))); + * ``` + * @see [source](https://github.com/nodejs/node/blob/v18.0.0/lib/string_decoder.js) + */ +declare module 'string_decoder' { + class StringDecoder { + constructor(encoding?: BufferEncoding); + /** + * Returns a decoded string, ensuring that any incomplete multibyte characters at + * the end of the `Buffer`, or `TypedArray`, or `DataView` are omitted from the + * returned string and stored in an internal buffer for the next call to`stringDecoder.write()` or `stringDecoder.end()`. + * @since v0.1.99 + * @param buffer A `Buffer`, or `TypedArray`, or `DataView` containing the bytes to decode. + */ + write(buffer: Buffer): string; + /** + * Returns any remaining input stored in the internal buffer as a string. Bytes + * representing incomplete UTF-8 and UTF-16 characters will be replaced with + * substitution characters appropriate for the character encoding. + * + * If the `buffer` argument is provided, one final call to `stringDecoder.write()`is performed before returning the remaining input. + * After `end()` is called, the `stringDecoder` object can be reused for new input. + * @since v0.9.3 + * @param buffer A `Buffer`, or `TypedArray`, or `DataView` containing the bytes to decode. + */ + end(buffer?: Buffer): string; + } +} +declare module 'node:string_decoder' { + export * from 'string_decoder'; +} diff --git a/ts-ticket-office-service/node_modules/@types/node/test.d.ts b/ts-ticket-office-service/node_modules/@types/node/test.d.ts new file mode 100755 index 000000000..9ba9512e9 --- /dev/null +++ b/ts-ticket-office-service/node_modules/@types/node/test.d.ts @@ -0,0 +1,176 @@ +/** + * The `node:test` module provides a standalone testing module. + * @see [source](https://github.com/nodejs/node/blob/v18.0.0/lib/test.js) + */ +declare module 'node:test' { + /** + * The `test()` function is the value imported from the test module. Each invocation of this + * function results in the creation of a test point in the TAP output. + * + * The {@link TestContext} object passed to the fn argument can be used to perform actions + * related to the current test. Examples include skipping the test, adding additional TAP + * diagnostic information, or creating subtests. + * + * `test()` returns a {@link Promise} that resolves once the test completes. The return value + * can usually be discarded for top level tests. However, the return value from subtests should + * be used to prevent the parent test from finishing first and cancelling the subtest as shown + * in the following example. + * + * ```js + * test('top level test', async (t) => { + * // The setTimeout() in the following subtest would cause it to outlive its + * // parent test if 'await' is removed on the next line. Once the parent test + * // completes, it will cancel any outstanding subtests. + * await t.test('longer running subtest', async (t) => { + * return new Promise((resolve, reject) => { + * setTimeout(resolve, 1000); + * }); + * }); + * }); + * ``` + * @since v18.0.0 + * @param name The name of the test, which is displayed when reporting test results. + * Default: The `name` property of fn, or `''` if `fn` does not have a name. + * @param options Configuration options for the test + * @param fn The function under test. The first argument to this function is a + * {@link TestContext} object. If the test uses callbacks, the callback function is + * passed as the second argument. Default: A no-op function. + * @returns A {@link Promise} resolved with `undefined` once the test completes. + */ + function test(name?: string, fn?: TestFn): Promise; + function test(name?: string, options?: TestOptions, fn?: TestFn): Promise; + function test(options?: TestOptions, fn?: TestFn): Promise; + function test(fn?: TestFn): Promise; + + /* + * @since v18.6.0 + * @param name The name of the suite, which is displayed when reporting suite results. + * Default: The `name` property of fn, or `''` if `fn` does not have a name. + * @param options Configuration options for the suite + * @param fn The function under suite. Default: A no-op function. + */ + function describe(name?: string, options?: TestOptions, fn?: SuiteFn): void; + function describe(name?: string, fn?: SuiteFn): void; + function describe(options?: TestOptions, fn?: SuiteFn): void; + function describe(fn?: SuiteFn): void; + + /* + * @since v18.6.0 + * @param name The name of the test, which is displayed when reporting test results. + * Default: The `name` property of fn, or `''` if `fn` does not have a name. + * @param options Configuration options for the test + * @param fn The function under test. If the test uses callbacks, the callback function is + * passed as the second argument. Default: A no-op function. + */ + function it(name?: string, options?: TestOptions, fn?: ItFn): void; + function it(name?: string, fn?: ItFn): void; + function it(options?: TestOptions, fn?: ItFn): void; + function it(fn?: ItFn): void; + + /** + * The type of a function under test. The first argument to this function is a + * {@link TestContext} object. If the test uses callbacks, the callback function is passed as + * the second argument. + */ + type TestFn = (t: TestContext, done: (result?: any) => void) => any; + + /** + * The type of a function under Suite. + * If the test uses callbacks, the callback function is passed as an argument + */ + type SuiteFn = (done: (result?: any) => void) => void; + + /** + * The type of a function under test. + * If the test uses callbacks, the callback function is passed as an argument + */ + type ItFn = (done: (result?: any) => void) => any; + + /** + * An instance of `TestContext` is passed to each test function in order to interact with the + * test runner. However, the `TestContext` constructor is not exposed as part of the API. + * @since v18.0.0 + */ + interface TestContext { + /** + * This function is used to write TAP diagnostics to the output. Any diagnostic information is + * included at the end of the test's results. This function does not return a value. + * @param message Message to be displayed as a TAP diagnostic. + * @since v18.0.0 + */ + diagnostic(message: string): void; + + /** + * If `shouldRunOnlyTests` is truthy, the test context will only run tests that have the `only` + * option set. Otherwise, all tests are run. If Node.js was not started with the `--test-only` + * command-line option, this function is a no-op. + * @param shouldRunOnlyTests Whether or not to run `only` tests. + * @since v18.0.0 + */ + runOnly(shouldRunOnlyTests: boolean): void; + + /** + * This function causes the test's output to indicate the test as skipped. If `message` is + * provided, it is included in the TAP output. Calling `skip()` does not terminate execution of + * the test function. This function does not return a value. + * @param message Optional skip message to be displayed in TAP output. + * @since v18.0.0 + */ + skip(message?: string): void; + + /** + * This function adds a `TODO` directive to the test's output. If `message` is provided, it is + * included in the TAP output. Calling `todo()` does not terminate execution of the test + * function. This function does not return a value. + * @param message Optional `TODO` message to be displayed in TAP output. + * @since v18.0.0 + */ + todo(message?: string): void; + + /** + * This function is used to create subtests under the current test. This function behaves in + * the same fashion as the top level {@link test} function. + * @since v18.0.0 + * @param name The name of the test, which is displayed when reporting test results. + * Default: The `name` property of fn, or `''` if `fn` does not have a name. + * @param options Configuration options for the test + * @param fn The function under test. This first argument to this function is a + * {@link TestContext} object. If the test uses callbacks, the callback function is + * passed as the second argument. Default: A no-op function. + * @returns A {@link Promise} resolved with `undefined` once the test completes. + */ + test: typeof test; + } + + interface TestOptions { + /** + * The number of tests that can be run at the same time. If unspecified, subtests inherit this + * value from their parent. + * @default 1 + */ + concurrency?: number; + + /** + * If truthy, and the test context is configured to run `only` tests, then this test will be + * run. Otherwise, the test is skipped. + * @default false + */ + only?: boolean; + + /** + * If truthy, the test is skipped. If a string is provided, that string is displayed in the + * test results as the reason for skipping the test. + * @default false + */ + skip?: boolean | string; + + /** + * If truthy, the test marked as `TODO`. If a string is provided, that string is displayed in + * the test results as the reason why the test is `TODO`. + * @default false + */ + todo?: boolean | string; + } + + export { test as default, test, describe, it }; +} diff --git a/ts-ticket-office-service/node_modules/@types/node/timers.d.ts b/ts-ticket-office-service/node_modules/@types/node/timers.d.ts new file mode 100755 index 000000000..b26f3ceda --- /dev/null +++ b/ts-ticket-office-service/node_modules/@types/node/timers.d.ts @@ -0,0 +1,94 @@ +/** + * The `timer` module exposes a global API for scheduling functions to + * be called at some future period of time. Because the timer functions are + * globals, there is no need to call `require('timers')` to use the API. + * + * The timer functions within Node.js implement a similar API as the timers API + * provided by Web Browsers but use a different internal implementation that is + * built around the Node.js [Event Loop](https://nodejs.org/en/docs/guides/event-loop-timers-and-nexttick/#setimmediate-vs-settimeout). + * @see [source](https://github.com/nodejs/node/blob/v18.0.0/lib/timers.js) + */ +declare module 'timers' { + import { Abortable } from 'node:events'; + import { setTimeout as setTimeoutPromise, setImmediate as setImmediatePromise, setInterval as setIntervalPromise } from 'node:timers/promises'; + interface TimerOptions extends Abortable { + /** + * Set to `false` to indicate that the scheduled `Timeout` + * should not require the Node.js event loop to remain active. + * @default true + */ + ref?: boolean | undefined; + } + let setTimeout: typeof global.setTimeout; + let clearTimeout: typeof global.clearTimeout; + let setInterval: typeof global.setInterval; + let clearInterval: typeof global.clearInterval; + let setImmediate: typeof global.setImmediate; + let clearImmediate: typeof global.clearImmediate; + global { + namespace NodeJS { + // compatibility with older typings + interface Timer extends RefCounted { + hasRef(): boolean; + refresh(): this; + [Symbol.toPrimitive](): number; + } + interface Immediate extends RefCounted { + /** + * If true, the `Immediate` object will keep the Node.js event loop active. + * @since v11.0.0 + */ + hasRef(): boolean; + _onImmediate: Function; // to distinguish it from the Timeout class + } + interface Timeout extends Timer { + /** + * If true, the `Timeout` object will keep the Node.js event loop active. + * @since v11.0.0 + */ + hasRef(): boolean; + /** + * Sets the timer's start time to the current time, and reschedules the timer to + * call its callback at the previously specified duration adjusted to the current + * time. This is useful for refreshing a timer without allocating a new + * JavaScript object. + * + * Using this on a timer that has already called its callback will reactivate the + * timer. + * @since v10.2.0 + * @return a reference to `timeout` + */ + refresh(): this; + [Symbol.toPrimitive](): number; + } + } + function setTimeout(callback: (...args: TArgs) => void, ms?: number, ...args: TArgs): NodeJS.Timeout; + // util.promisify no rest args compability + // tslint:disable-next-line void-return + function setTimeout(callback: (args: void) => void, ms?: number): NodeJS.Timeout; + namespace setTimeout { + const __promisify__: typeof setTimeoutPromise; + } + function clearTimeout(timeoutId: NodeJS.Timeout | string | number | undefined): void; + function setInterval(callback: (...args: TArgs) => void, ms?: number, ...args: TArgs): NodeJS.Timer; + // util.promisify no rest args compability + // tslint:disable-next-line void-return + function setInterval(callback: (args: void) => void, ms?: number): NodeJS.Timer; + namespace setInterval { + const __promisify__: typeof setIntervalPromise; + } + function clearInterval(intervalId: NodeJS.Timeout | string | number | undefined): void; + function setImmediate(callback: (...args: TArgs) => void, ...args: TArgs): NodeJS.Immediate; + // util.promisify no rest args compability + // tslint:disable-next-line void-return + function setImmediate(callback: (args: void) => void): NodeJS.Immediate; + namespace setImmediate { + const __promisify__: typeof setImmediatePromise; + } + function clearImmediate(immediateId: NodeJS.Immediate | undefined): void; + function queueMicrotask(callback: () => void): void; + } +} +declare module 'node:timers' { + export * from 'timers'; +} diff --git a/ts-ticket-office-service/node_modules/@types/node/timers/promises.d.ts b/ts-ticket-office-service/node_modules/@types/node/timers/promises.d.ts new file mode 100755 index 000000000..fd778880e --- /dev/null +++ b/ts-ticket-office-service/node_modules/@types/node/timers/promises.d.ts @@ -0,0 +1,68 @@ +/** + * The `timers/promises` API provides an alternative set of timer functions + * that return `Promise` objects. The API is accessible via`require('timers/promises')`. + * + * ```js + * import { + * setTimeout, + * setImmediate, + * setInterval, + * } from 'timers/promises'; + * ``` + * @since v15.0.0 + */ +declare module 'timers/promises' { + import { TimerOptions } from 'node:timers'; + /** + * ```js + * import { + * setTimeout, + * } from 'timers/promises'; + * + * const res = await setTimeout(100, 'result'); + * + * console.log(res); // Prints 'result' + * ``` + * @since v15.0.0 + * @param [delay=1] The number of milliseconds to wait before fulfilling the promise. + * @param value A value with which the promise is fulfilled. + */ + function setTimeout(delay?: number, value?: T, options?: TimerOptions): Promise; + /** + * ```js + * import { + * setImmediate, + * } from 'timers/promises'; + * + * const res = await setImmediate('result'); + * + * console.log(res); // Prints 'result' + * ``` + * @since v15.0.0 + * @param value A value with which the promise is fulfilled. + */ + function setImmediate(value?: T, options?: TimerOptions): Promise; + /** + * Returns an async iterator that generates values in an interval of `delay` ms. + * + * ```js + * import { + * setInterval, + * } from 'timers/promises'; + * + * const interval = 100; + * for await (const startTime of setInterval(interval, Date.now())) { + * const now = Date.now(); + * console.log(now); + * if ((now - startTime) > 1000) + * break; + * } + * console.log(Date.now()); + * ``` + * @since v15.9.0 + */ + function setInterval(delay?: number, value?: T, options?: TimerOptions): AsyncIterable; +} +declare module 'node:timers/promises' { + export * from 'timers/promises'; +} diff --git a/ts-ticket-office-service/node_modules/@types/node/tls.d.ts b/ts-ticket-office-service/node_modules/@types/node/tls.d.ts new file mode 100755 index 000000000..816766e47 --- /dev/null +++ b/ts-ticket-office-service/node_modules/@types/node/tls.d.ts @@ -0,0 +1,1028 @@ +/** + * The `tls` module provides an implementation of the Transport Layer Security + * (TLS) and Secure Socket Layer (SSL) protocols that is built on top of OpenSSL. + * The module can be accessed using: + * + * ```js + * const tls = require('tls'); + * ``` + * @see [source](https://github.com/nodejs/node/blob/v18.0.0/lib/tls.js) + */ +declare module 'tls' { + import { X509Certificate } from 'node:crypto'; + import * as net from 'node:net'; + import * as stream from 'stream'; + const CLIENT_RENEG_LIMIT: number; + const CLIENT_RENEG_WINDOW: number; + interface Certificate { + /** + * Country code. + */ + C: string; + /** + * Street. + */ + ST: string; + /** + * Locality. + */ + L: string; + /** + * Organization. + */ + O: string; + /** + * Organizational unit. + */ + OU: string; + /** + * Common name. + */ + CN: string; + } + interface PeerCertificate { + subject: Certificate; + issuer: Certificate; + subjectaltname: string; + infoAccess: NodeJS.Dict; + modulus: string; + exponent: string; + valid_from: string; + valid_to: string; + fingerprint: string; + fingerprint256: string; + ext_key_usage: string[]; + serialNumber: string; + raw: Buffer; + } + interface DetailedPeerCertificate extends PeerCertificate { + issuerCertificate: DetailedPeerCertificate; + } + interface CipherNameAndProtocol { + /** + * The cipher name. + */ + name: string; + /** + * SSL/TLS protocol version. + */ + version: string; + /** + * IETF name for the cipher suite. + */ + standardName: string; + } + interface EphemeralKeyInfo { + /** + * The supported types are 'DH' and 'ECDH'. + */ + type: string; + /** + * The name property is available only when type is 'ECDH'. + */ + name?: string | undefined; + /** + * The size of parameter of an ephemeral key exchange. + */ + size: number; + } + interface KeyObject { + /** + * Private keys in PEM format. + */ + pem: string | Buffer; + /** + * Optional passphrase. + */ + passphrase?: string | undefined; + } + interface PxfObject { + /** + * PFX or PKCS12 encoded private key and certificate chain. + */ + buf: string | Buffer; + /** + * Optional passphrase. + */ + passphrase?: string | undefined; + } + interface TLSSocketOptions extends SecureContextOptions, CommonConnectionOptions { + /** + * If true the TLS socket will be instantiated in server-mode. + * Defaults to false. + */ + isServer?: boolean | undefined; + /** + * An optional net.Server instance. + */ + server?: net.Server | undefined; + /** + * An optional Buffer instance containing a TLS session. + */ + session?: Buffer | undefined; + /** + * If true, specifies that the OCSP status request extension will be + * added to the client hello and an 'OCSPResponse' event will be + * emitted on the socket before establishing a secure communication + */ + requestOCSP?: boolean | undefined; + } + /** + * Performs transparent encryption of written data and all required TLS + * negotiation. + * + * Instances of `tls.TLSSocket` implement the duplex `Stream` interface. + * + * Methods that return TLS connection metadata (e.g.{@link TLSSocket.getPeerCertificate} will only return data while the + * connection is open. + * @since v0.11.4 + */ + class TLSSocket extends net.Socket { + /** + * Construct a new tls.TLSSocket object from an existing TCP socket. + */ + constructor(socket: net.Socket, options?: TLSSocketOptions); + /** + * This property is `true` if the peer certificate was signed by one of the CAs + * specified when creating the `tls.TLSSocket` instance, otherwise `false`. + * @since v0.11.4 + */ + authorized: boolean; + /** + * Returns the reason why the peer's certificate was not been verified. This + * property is set only when `tlsSocket.authorized === false`. + * @since v0.11.4 + */ + authorizationError: Error; + /** + * Always returns `true`. This may be used to distinguish TLS sockets from regular`net.Socket` instances. + * @since v0.11.4 + */ + encrypted: true; + /** + * String containing the selected ALPN protocol. + * Before a handshake has completed, this value is always null. + * When a handshake is completed but not ALPN protocol was selected, tlsSocket.alpnProtocol equals false. + */ + alpnProtocol: string | false | null; + /** + * Returns an object representing the local certificate. The returned object has + * some properties corresponding to the fields of the certificate. + * + * See {@link TLSSocket.getPeerCertificate} for an example of the certificate + * structure. + * + * If there is no local certificate, an empty object will be returned. If the + * socket has been destroyed, `null` will be returned. + * @since v11.2.0 + */ + getCertificate(): PeerCertificate | object | null; + /** + * Returns an object containing information on the negotiated cipher suite. + * + * For example: + * + * ```json + * { + * "name": "AES128-SHA256", + * "standardName": "TLS_RSA_WITH_AES_128_CBC_SHA256", + * "version": "TLSv1.2" + * } + * ``` + * + * See [SSL\_CIPHER\_get\_name](https://www.openssl.org/docs/man1.1.1/man3/SSL_CIPHER_get_name.html) for more information. + * @since v0.11.4 + */ + getCipher(): CipherNameAndProtocol; + /** + * Returns an object representing the type, name, and size of parameter of + * an ephemeral key exchange in `perfect forward secrecy` on a client + * connection. It returns an empty object when the key exchange is not + * ephemeral. As this is only supported on a client socket; `null` is returned + * if called on a server socket. The supported types are `'DH'` and `'ECDH'`. The`name` property is available only when type is `'ECDH'`. + * + * For example: `{ type: 'ECDH', name: 'prime256v1', size: 256 }`. + * @since v5.0.0 + */ + getEphemeralKeyInfo(): EphemeralKeyInfo | object | null; + /** + * As the `Finished` messages are message digests of the complete handshake + * (with a total of 192 bits for TLS 1.0 and more for SSL 3.0), they can + * be used for external authentication procedures when the authentication + * provided by SSL/TLS is not desired or is not enough. + * + * Corresponds to the `SSL_get_finished` routine in OpenSSL and may be used + * to implement the `tls-unique` channel binding from [RFC 5929](https://tools.ietf.org/html/rfc5929). + * @since v9.9.0 + * @return The latest `Finished` message that has been sent to the socket as part of a SSL/TLS handshake, or `undefined` if no `Finished` message has been sent yet. + */ + getFinished(): Buffer | undefined; + /** + * Returns an object representing the peer's certificate. If the peer does not + * provide a certificate, an empty object will be returned. If the socket has been + * destroyed, `null` will be returned. + * + * If the full certificate chain was requested, each certificate will include an`issuerCertificate` property containing an object representing its issuer's + * certificate. + * @since v0.11.4 + * @param detailed Include the full certificate chain if `true`, otherwise include just the peer's certificate. + * @return A certificate object. + */ + getPeerCertificate(detailed: true): DetailedPeerCertificate; + getPeerCertificate(detailed?: false): PeerCertificate; + getPeerCertificate(detailed?: boolean): PeerCertificate | DetailedPeerCertificate; + /** + * As the `Finished` messages are message digests of the complete handshake + * (with a total of 192 bits for TLS 1.0 and more for SSL 3.0), they can + * be used for external authentication procedures when the authentication + * provided by SSL/TLS is not desired or is not enough. + * + * Corresponds to the `SSL_get_peer_finished` routine in OpenSSL and may be used + * to implement the `tls-unique` channel binding from [RFC 5929](https://tools.ietf.org/html/rfc5929). + * @since v9.9.0 + * @return The latest `Finished` message that is expected or has actually been received from the socket as part of a SSL/TLS handshake, or `undefined` if there is no `Finished` message so + * far. + */ + getPeerFinished(): Buffer | undefined; + /** + * Returns a string containing the negotiated SSL/TLS protocol version of the + * current connection. The value `'unknown'` will be returned for connected + * sockets that have not completed the handshaking process. The value `null` will + * be returned for server sockets or disconnected client sockets. + * + * Protocol versions are: + * + * * `'SSLv3'` + * * `'TLSv1'` + * * `'TLSv1.1'` + * * `'TLSv1.2'` + * * `'TLSv1.3'` + * + * See the OpenSSL [`SSL_get_version`](https://www.openssl.org/docs/man1.1.1/man3/SSL_get_version.html) documentation for more information. + * @since v5.7.0 + */ + getProtocol(): string | null; + /** + * Returns the TLS session data or `undefined` if no session was + * negotiated. On the client, the data can be provided to the `session` option of {@link connect} to resume the connection. On the server, it may be useful + * for debugging. + * + * See `Session Resumption` for more information. + * + * Note: `getSession()` works only for TLSv1.2 and below. For TLSv1.3, applications + * must use the `'session'` event (it also works for TLSv1.2 and below). + * @since v0.11.4 + */ + getSession(): Buffer | undefined; + /** + * See [SSL\_get\_shared\_sigalgs](https://www.openssl.org/docs/man1.1.1/man3/SSL_get_shared_sigalgs.html) for more information. + * @since v12.11.0 + * @return List of signature algorithms shared between the server and the client in the order of decreasing preference. + */ + getSharedSigalgs(): string[]; + /** + * For a client, returns the TLS session ticket if one is available, or`undefined`. For a server, always returns `undefined`. + * + * It may be useful for debugging. + * + * See `Session Resumption` for more information. + * @since v0.11.4 + */ + getTLSTicket(): Buffer | undefined; + /** + * See `Session Resumption` for more information. + * @since v0.5.6 + * @return `true` if the session was reused, `false` otherwise. + */ + isSessionReused(): boolean; + /** + * The `tlsSocket.renegotiate()` method initiates a TLS renegotiation process. + * Upon completion, the `callback` function will be passed a single argument + * that is either an `Error` (if the request failed) or `null`. + * + * This method can be used to request a peer's certificate after the secure + * connection has been established. + * + * When running as the server, the socket will be destroyed with an error after`handshakeTimeout` timeout. + * + * For TLSv1.3, renegotiation cannot be initiated, it is not supported by the + * protocol. + * @since v0.11.8 + * @param callback If `renegotiate()` returned `true`, callback is attached once to the `'secure'` event. If `renegotiate()` returned `false`, `callback` will be called in the next tick with + * an error, unless the `tlsSocket` has been destroyed, in which case `callback` will not be called at all. + * @return `true` if renegotiation was initiated, `false` otherwise. + */ + renegotiate( + options: { + rejectUnauthorized?: boolean | undefined; + requestCert?: boolean | undefined; + }, + callback: (err: Error | null) => void + ): undefined | boolean; + /** + * The `tlsSocket.setMaxSendFragment()` method sets the maximum TLS fragment size. + * Returns `true` if setting the limit succeeded; `false` otherwise. + * + * Smaller fragment sizes decrease the buffering latency on the client: larger + * fragments are buffered by the TLS layer until the entire fragment is received + * and its integrity is verified; large fragments can span multiple roundtrips + * and their processing can be delayed due to packet loss or reordering. However, + * smaller fragments add extra TLS framing bytes and CPU overhead, which may + * decrease overall server throughput. + * @since v0.11.11 + * @param [size=16384] The maximum TLS fragment size. The maximum value is `16384`. + */ + setMaxSendFragment(size: number): boolean; + /** + * Disables TLS renegotiation for this `TLSSocket` instance. Once called, attempts + * to renegotiate will trigger an `'error'` event on the `TLSSocket`. + * @since v8.4.0 + */ + disableRenegotiation(): void; + /** + * When enabled, TLS packet trace information is written to `stderr`. This can be + * used to debug TLS connection problems. + * + * The format of the output is identical to the output of`openssl s_client -trace` or `openssl s_server -trace`. While it is produced by + * OpenSSL's `SSL_trace()` function, the format is undocumented, can change + * without notice, and should not be relied on. + * @since v12.2.0 + */ + enableTrace(): void; + /** + * Returns the peer certificate as an `X509Certificate` object. + * + * If there is no peer certificate, or the socket has been destroyed,`undefined` will be returned. + * @since v15.9.0 + */ + getPeerX509Certificate(): X509Certificate | undefined; + /** + * Returns the local certificate as an `X509Certificate` object. + * + * If there is no local certificate, or the socket has been destroyed,`undefined` will be returned. + * @since v15.9.0 + */ + getX509Certificate(): X509Certificate | undefined; + /** + * Keying material is used for validations to prevent different kind of attacks in + * network protocols, for example in the specifications of IEEE 802.1X. + * + * Example + * + * ```js + * const keyingMaterial = tlsSocket.exportKeyingMaterial( + * 128, + * 'client finished'); + * + * /* + * Example return value of keyingMaterial: + * + * + * ``` + * + * See the OpenSSL [`SSL_export_keying_material`](https://www.openssl.org/docs/man1.1.1/man3/SSL_export_keying_material.html) documentation for more + * information. + * @since v13.10.0, v12.17.0 + * @param length number of bytes to retrieve from keying material + * @param label an application specific label, typically this will be a value from the [IANA Exporter Label + * Registry](https://www.iana.org/assignments/tls-parameters/tls-parameters.xhtml#exporter-labels). + * @param context Optionally provide a context. + * @return requested bytes of the keying material + */ + exportKeyingMaterial(length: number, label: string, context: Buffer): Buffer; + addListener(event: string, listener: (...args: any[]) => void): this; + addListener(event: 'OCSPResponse', listener: (response: Buffer) => void): this; + addListener(event: 'secureConnect', listener: () => void): this; + addListener(event: 'session', listener: (session: Buffer) => void): this; + addListener(event: 'keylog', listener: (line: Buffer) => void): this; + emit(event: string | symbol, ...args: any[]): boolean; + emit(event: 'OCSPResponse', response: Buffer): boolean; + emit(event: 'secureConnect'): boolean; + emit(event: 'session', session: Buffer): boolean; + emit(event: 'keylog', line: Buffer): boolean; + on(event: string, listener: (...args: any[]) => void): this; + on(event: 'OCSPResponse', listener: (response: Buffer) => void): this; + on(event: 'secureConnect', listener: () => void): this; + on(event: 'session', listener: (session: Buffer) => void): this; + on(event: 'keylog', listener: (line: Buffer) => void): this; + once(event: string, listener: (...args: any[]) => void): this; + once(event: 'OCSPResponse', listener: (response: Buffer) => void): this; + once(event: 'secureConnect', listener: () => void): this; + once(event: 'session', listener: (session: Buffer) => void): this; + once(event: 'keylog', listener: (line: Buffer) => void): this; + prependListener(event: string, listener: (...args: any[]) => void): this; + prependListener(event: 'OCSPResponse', listener: (response: Buffer) => void): this; + prependListener(event: 'secureConnect', listener: () => void): this; + prependListener(event: 'session', listener: (session: Buffer) => void): this; + prependListener(event: 'keylog', listener: (line: Buffer) => void): this; + prependOnceListener(event: string, listener: (...args: any[]) => void): this; + prependOnceListener(event: 'OCSPResponse', listener: (response: Buffer) => void): this; + prependOnceListener(event: 'secureConnect', listener: () => void): this; + prependOnceListener(event: 'session', listener: (session: Buffer) => void): this; + prependOnceListener(event: 'keylog', listener: (line: Buffer) => void): this; + } + interface CommonConnectionOptions { + /** + * An optional TLS context object from tls.createSecureContext() + */ + secureContext?: SecureContext | undefined; + /** + * When enabled, TLS packet trace information is written to `stderr`. This can be + * used to debug TLS connection problems. + * @default false + */ + enableTrace?: boolean | undefined; + /** + * If true the server will request a certificate from clients that + * connect and attempt to verify that certificate. Defaults to + * false. + */ + requestCert?: boolean | undefined; + /** + * An array of strings or a Buffer naming possible ALPN protocols. + * (Protocols should be ordered by their priority.) + */ + ALPNProtocols?: string[] | Uint8Array[] | Uint8Array | undefined; + /** + * SNICallback(servername, cb) A function that will be + * called if the client supports SNI TLS extension. Two arguments + * will be passed when called: servername and cb. SNICallback should + * invoke cb(null, ctx), where ctx is a SecureContext instance. + * (tls.createSecureContext(...) can be used to get a proper + * SecureContext.) If SNICallback wasn't provided the default callback + * with high-level API will be used (see below). + */ + SNICallback?: ((servername: string, cb: (err: Error | null, ctx?: SecureContext) => void) => void) | undefined; + /** + * If true the server will reject any connection which is not + * authorized with the list of supplied CAs. This option only has an + * effect if requestCert is true. + * @default true + */ + rejectUnauthorized?: boolean | undefined; + } + interface TlsOptions extends SecureContextOptions, CommonConnectionOptions, net.ServerOpts { + /** + * Abort the connection if the SSL/TLS handshake does not finish in the + * specified number of milliseconds. A 'tlsClientError' is emitted on + * the tls.Server object whenever a handshake times out. Default: + * 120000 (120 seconds). + */ + handshakeTimeout?: number | undefined; + /** + * The number of seconds after which a TLS session created by the + * server will no longer be resumable. See Session Resumption for more + * information. Default: 300. + */ + sessionTimeout?: number | undefined; + /** + * 48-bytes of cryptographically strong pseudo-random data. + */ + ticketKeys?: Buffer | undefined; + /** + * + * @param socket + * @param identity identity parameter sent from the client. + * @return pre-shared key that must either be + * a buffer or `null` to stop the negotiation process. Returned PSK must be + * compatible with the selected cipher's digest. + * + * When negotiating TLS-PSK (pre-shared keys), this function is called + * with the identity provided by the client. + * If the return value is `null` the negotiation process will stop and an + * "unknown_psk_identity" alert message will be sent to the other party. + * If the server wishes to hide the fact that the PSK identity was not known, + * the callback must provide some random data as `psk` to make the connection + * fail with "decrypt_error" before negotiation is finished. + * PSK ciphers are disabled by default, and using TLS-PSK thus + * requires explicitly specifying a cipher suite with the `ciphers` option. + * More information can be found in the RFC 4279. + */ + pskCallback?(socket: TLSSocket, identity: string): DataView | NodeJS.TypedArray | null; + /** + * hint to send to a client to help + * with selecting the identity during TLS-PSK negotiation. Will be ignored + * in TLS 1.3. Upon failing to set pskIdentityHint `tlsClientError` will be + * emitted with `ERR_TLS_PSK_SET_IDENTIY_HINT_FAILED` code. + */ + pskIdentityHint?: string | undefined; + } + interface PSKCallbackNegotation { + psk: DataView | NodeJS.TypedArray; + identity: string; + } + interface ConnectionOptions extends SecureContextOptions, CommonConnectionOptions { + host?: string | undefined; + port?: number | undefined; + path?: string | undefined; // Creates unix socket connection to path. If this option is specified, `host` and `port` are ignored. + socket?: stream.Duplex | undefined; // Establish secure connection on a given socket rather than creating a new socket + checkServerIdentity?: typeof checkServerIdentity | undefined; + servername?: string | undefined; // SNI TLS Extension + session?: Buffer | undefined; + minDHSize?: number | undefined; + lookup?: net.LookupFunction | undefined; + timeout?: number | undefined; + /** + * When negotiating TLS-PSK (pre-shared keys), this function is called + * with optional identity `hint` provided by the server or `null` + * in case of TLS 1.3 where `hint` was removed. + * It will be necessary to provide a custom `tls.checkServerIdentity()` + * for the connection as the default one will try to check hostname/IP + * of the server against the certificate but that's not applicable for PSK + * because there won't be a certificate present. + * More information can be found in the RFC 4279. + * + * @param hint message sent from the server to help client + * decide which identity to use during negotiation. + * Always `null` if TLS 1.3 is used. + * @returns Return `null` to stop the negotiation process. `psk` must be + * compatible with the selected cipher's digest. + * `identity` must use UTF-8 encoding. + */ + pskCallback?(hint: string | null): PSKCallbackNegotation | null; + } + /** + * Accepts encrypted connections using TLS or SSL. + * @since v0.3.2 + */ + class Server extends net.Server { + constructor(secureConnectionListener?: (socket: TLSSocket) => void); + constructor(options: TlsOptions, secureConnectionListener?: (socket: TLSSocket) => void); + /** + * The `server.addContext()` method adds a secure context that will be used if + * the client request's SNI name matches the supplied `hostname` (or wildcard). + * + * When there are multiple matching contexts, the most recently added one is + * used. + * @since v0.5.3 + * @param hostname A SNI host name or wildcard (e.g. `'*'`) + * @param context An object containing any of the possible properties from the {@link createSecureContext} `options` arguments (e.g. `key`, `cert`, `ca`, etc). + */ + addContext(hostname: string, context: SecureContextOptions): void; + /** + * Returns the session ticket keys. + * + * See `Session Resumption` for more information. + * @since v3.0.0 + * @return A 48-byte buffer containing the session ticket keys. + */ + getTicketKeys(): Buffer; + /** + * The `server.setSecureContext()` method replaces the secure context of an + * existing server. Existing connections to the server are not interrupted. + * @since v11.0.0 + * @param options An object containing any of the possible properties from the {@link createSecureContext} `options` arguments (e.g. `key`, `cert`, `ca`, etc). + */ + setSecureContext(options: SecureContextOptions): void; + /** + * Sets the session ticket keys. + * + * Changes to the ticket keys are effective only for future server connections. + * Existing or currently pending server connections will use the previous keys. + * + * See `Session Resumption` for more information. + * @since v3.0.0 + * @param keys A 48-byte buffer containing the session ticket keys. + */ + setTicketKeys(keys: Buffer): void; + /** + * events.EventEmitter + * 1. tlsClientError + * 2. newSession + * 3. OCSPRequest + * 4. resumeSession + * 5. secureConnection + * 6. keylog + */ + addListener(event: string, listener: (...args: any[]) => void): this; + addListener(event: 'tlsClientError', listener: (err: Error, tlsSocket: TLSSocket) => void): this; + addListener(event: 'newSession', listener: (sessionId: Buffer, sessionData: Buffer, callback: (err: Error, resp: Buffer) => void) => void): this; + addListener(event: 'OCSPRequest', listener: (certificate: Buffer, issuer: Buffer, callback: (err: Error | null, resp: Buffer) => void) => void): this; + addListener(event: 'resumeSession', listener: (sessionId: Buffer, callback: (err: Error, sessionData: Buffer) => void) => void): this; + addListener(event: 'secureConnection', listener: (tlsSocket: TLSSocket) => void): this; + addListener(event: 'keylog', listener: (line: Buffer, tlsSocket: TLSSocket) => void): this; + emit(event: string | symbol, ...args: any[]): boolean; + emit(event: 'tlsClientError', err: Error, tlsSocket: TLSSocket): boolean; + emit(event: 'newSession', sessionId: Buffer, sessionData: Buffer, callback: (err: Error, resp: Buffer) => void): boolean; + emit(event: 'OCSPRequest', certificate: Buffer, issuer: Buffer, callback: (err: Error | null, resp: Buffer) => void): boolean; + emit(event: 'resumeSession', sessionId: Buffer, callback: (err: Error, sessionData: Buffer) => void): boolean; + emit(event: 'secureConnection', tlsSocket: TLSSocket): boolean; + emit(event: 'keylog', line: Buffer, tlsSocket: TLSSocket): boolean; + on(event: string, listener: (...args: any[]) => void): this; + on(event: 'tlsClientError', listener: (err: Error, tlsSocket: TLSSocket) => void): this; + on(event: 'newSession', listener: (sessionId: Buffer, sessionData: Buffer, callback: (err: Error, resp: Buffer) => void) => void): this; + on(event: 'OCSPRequest', listener: (certificate: Buffer, issuer: Buffer, callback: (err: Error | null, resp: Buffer) => void) => void): this; + on(event: 'resumeSession', listener: (sessionId: Buffer, callback: (err: Error, sessionData: Buffer) => void) => void): this; + on(event: 'secureConnection', listener: (tlsSocket: TLSSocket) => void): this; + on(event: 'keylog', listener: (line: Buffer, tlsSocket: TLSSocket) => void): this; + once(event: string, listener: (...args: any[]) => void): this; + once(event: 'tlsClientError', listener: (err: Error, tlsSocket: TLSSocket) => void): this; + once(event: 'newSession', listener: (sessionId: Buffer, sessionData: Buffer, callback: (err: Error, resp: Buffer) => void) => void): this; + once(event: 'OCSPRequest', listener: (certificate: Buffer, issuer: Buffer, callback: (err: Error | null, resp: Buffer) => void) => void): this; + once(event: 'resumeSession', listener: (sessionId: Buffer, callback: (err: Error, sessionData: Buffer) => void) => void): this; + once(event: 'secureConnection', listener: (tlsSocket: TLSSocket) => void): this; + once(event: 'keylog', listener: (line: Buffer, tlsSocket: TLSSocket) => void): this; + prependListener(event: string, listener: (...args: any[]) => void): this; + prependListener(event: 'tlsClientError', listener: (err: Error, tlsSocket: TLSSocket) => void): this; + prependListener(event: 'newSession', listener: (sessionId: Buffer, sessionData: Buffer, callback: (err: Error, resp: Buffer) => void) => void): this; + prependListener(event: 'OCSPRequest', listener: (certificate: Buffer, issuer: Buffer, callback: (err: Error | null, resp: Buffer) => void) => void): this; + prependListener(event: 'resumeSession', listener: (sessionId: Buffer, callback: (err: Error, sessionData: Buffer) => void) => void): this; + prependListener(event: 'secureConnection', listener: (tlsSocket: TLSSocket) => void): this; + prependListener(event: 'keylog', listener: (line: Buffer, tlsSocket: TLSSocket) => void): this; + prependOnceListener(event: string, listener: (...args: any[]) => void): this; + prependOnceListener(event: 'tlsClientError', listener: (err: Error, tlsSocket: TLSSocket) => void): this; + prependOnceListener(event: 'newSession', listener: (sessionId: Buffer, sessionData: Buffer, callback: (err: Error, resp: Buffer) => void) => void): this; + prependOnceListener(event: 'OCSPRequest', listener: (certificate: Buffer, issuer: Buffer, callback: (err: Error | null, resp: Buffer) => void) => void): this; + prependOnceListener(event: 'resumeSession', listener: (sessionId: Buffer, callback: (err: Error, sessionData: Buffer) => void) => void): this; + prependOnceListener(event: 'secureConnection', listener: (tlsSocket: TLSSocket) => void): this; + prependOnceListener(event: 'keylog', listener: (line: Buffer, tlsSocket: TLSSocket) => void): this; + } + /** + * @deprecated since v0.11.3 Use `tls.TLSSocket` instead. + */ + interface SecurePair { + encrypted: TLSSocket; + cleartext: TLSSocket; + } + type SecureVersion = 'TLSv1.3' | 'TLSv1.2' | 'TLSv1.1' | 'TLSv1'; + interface SecureContextOptions { + /** + * Optionally override the trusted CA certificates. Default is to trust + * the well-known CAs curated by Mozilla. Mozilla's CAs are completely + * replaced when CAs are explicitly specified using this option. + */ + ca?: string | Buffer | Array | undefined; + /** + * Cert chains in PEM format. One cert chain should be provided per + * private key. Each cert chain should consist of the PEM formatted + * certificate for a provided private key, followed by the PEM + * formatted intermediate certificates (if any), in order, and not + * including the root CA (the root CA must be pre-known to the peer, + * see ca). When providing multiple cert chains, they do not have to + * be in the same order as their private keys in key. If the + * intermediate certificates are not provided, the peer will not be + * able to validate the certificate, and the handshake will fail. + */ + cert?: string | Buffer | Array | undefined; + /** + * Colon-separated list of supported signature algorithms. The list + * can contain digest algorithms (SHA256, MD5 etc.), public key + * algorithms (RSA-PSS, ECDSA etc.), combination of both (e.g + * 'RSA+SHA384') or TLS v1.3 scheme names (e.g. rsa_pss_pss_sha512). + */ + sigalgs?: string | undefined; + /** + * Cipher suite specification, replacing the default. For more + * information, see modifying the default cipher suite. Permitted + * ciphers can be obtained via tls.getCiphers(). Cipher names must be + * uppercased in order for OpenSSL to accept them. + */ + ciphers?: string | undefined; + /** + * Name of an OpenSSL engine which can provide the client certificate. + */ + clientCertEngine?: string | undefined; + /** + * PEM formatted CRLs (Certificate Revocation Lists). + */ + crl?: string | Buffer | Array | undefined; + /** + * Diffie Hellman parameters, required for Perfect Forward Secrecy. Use + * openssl dhparam to create the parameters. The key length must be + * greater than or equal to 1024 bits or else an error will be thrown. + * Although 1024 bits is permissible, use 2048 bits or larger for + * stronger security. If omitted or invalid, the parameters are + * silently discarded and DHE ciphers will not be available. + */ + dhparam?: string | Buffer | undefined; + /** + * A string describing a named curve or a colon separated list of curve + * NIDs or names, for example P-521:P-384:P-256, to use for ECDH key + * agreement. Set to auto to select the curve automatically. Use + * crypto.getCurves() to obtain a list of available curve names. On + * recent releases, openssl ecparam -list_curves will also display the + * name and description of each available elliptic curve. Default: + * tls.DEFAULT_ECDH_CURVE. + */ + ecdhCurve?: string | undefined; + /** + * Attempt to use the server's cipher suite preferences instead of the + * client's. When true, causes SSL_OP_CIPHER_SERVER_PREFERENCE to be + * set in secureOptions + */ + honorCipherOrder?: boolean | undefined; + /** + * Private keys in PEM format. PEM allows the option of private keys + * being encrypted. Encrypted keys will be decrypted with + * options.passphrase. Multiple keys using different algorithms can be + * provided either as an array of unencrypted key strings or buffers, + * or an array of objects in the form {pem: [, + * passphrase: ]}. The object form can only occur in an array. + * object.passphrase is optional. Encrypted keys will be decrypted with + * object.passphrase if provided, or options.passphrase if it is not. + */ + key?: string | Buffer | Array | undefined; + /** + * Name of an OpenSSL engine to get private key from. Should be used + * together with privateKeyIdentifier. + */ + privateKeyEngine?: string | undefined; + /** + * Identifier of a private key managed by an OpenSSL engine. Should be + * used together with privateKeyEngine. Should not be set together with + * key, because both options define a private key in different ways. + */ + privateKeyIdentifier?: string | undefined; + /** + * Optionally set the maximum TLS version to allow. One + * of `'TLSv1.3'`, `'TLSv1.2'`, `'TLSv1.1'`, or `'TLSv1'`. Cannot be specified along with the + * `secureProtocol` option, use one or the other. + * **Default:** `'TLSv1.3'`, unless changed using CLI options. Using + * `--tls-max-v1.2` sets the default to `'TLSv1.2'`. Using `--tls-max-v1.3` sets the default to + * `'TLSv1.3'`. If multiple of the options are provided, the highest maximum is used. + */ + maxVersion?: SecureVersion | undefined; + /** + * Optionally set the minimum TLS version to allow. One + * of `'TLSv1.3'`, `'TLSv1.2'`, `'TLSv1.1'`, or `'TLSv1'`. Cannot be specified along with the + * `secureProtocol` option, use one or the other. It is not recommended to use + * less than TLSv1.2, but it may be required for interoperability. + * **Default:** `'TLSv1.2'`, unless changed using CLI options. Using + * `--tls-v1.0` sets the default to `'TLSv1'`. Using `--tls-v1.1` sets the default to + * `'TLSv1.1'`. Using `--tls-min-v1.3` sets the default to + * 'TLSv1.3'. If multiple of the options are provided, the lowest minimum is used. + */ + minVersion?: SecureVersion | undefined; + /** + * Shared passphrase used for a single private key and/or a PFX. + */ + passphrase?: string | undefined; + /** + * PFX or PKCS12 encoded private key and certificate chain. pfx is an + * alternative to providing key and cert individually. PFX is usually + * encrypted, if it is, passphrase will be used to decrypt it. Multiple + * PFX can be provided either as an array of unencrypted PFX buffers, + * or an array of objects in the form {buf: [, + * passphrase: ]}. The object form can only occur in an array. + * object.passphrase is optional. Encrypted PFX will be decrypted with + * object.passphrase if provided, or options.passphrase if it is not. + */ + pfx?: string | Buffer | Array | undefined; + /** + * Optionally affect the OpenSSL protocol behavior, which is not + * usually necessary. This should be used carefully if at all! Value is + * a numeric bitmask of the SSL_OP_* options from OpenSSL Options + */ + secureOptions?: number | undefined; // Value is a numeric bitmask of the `SSL_OP_*` options + /** + * Legacy mechanism to select the TLS protocol version to use, it does + * not support independent control of the minimum and maximum version, + * and does not support limiting the protocol to TLSv1.3. Use + * minVersion and maxVersion instead. The possible values are listed as + * SSL_METHODS, use the function names as strings. For example, use + * 'TLSv1_1_method' to force TLS version 1.1, or 'TLS_method' to allow + * any TLS protocol version up to TLSv1.3. It is not recommended to use + * TLS versions less than 1.2, but it may be required for + * interoperability. Default: none, see minVersion. + */ + secureProtocol?: string | undefined; + /** + * Opaque identifier used by servers to ensure session state is not + * shared between applications. Unused by clients. + */ + sessionIdContext?: string | undefined; + /** + * 48-bytes of cryptographically strong pseudo-random data. + * See Session Resumption for more information. + */ + ticketKeys?: Buffer | undefined; + /** + * The number of seconds after which a TLS session created by the + * server will no longer be resumable. See Session Resumption for more + * information. Default: 300. + */ + sessionTimeout?: number | undefined; + } + interface SecureContext { + context: any; + } + /** + * Verifies the certificate `cert` is issued to `hostname`. + * + * Returns [Error](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error) object, populating it with `reason`, `host`, and `cert` on + * failure. On success, returns [undefined](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Undefined_type). + * + * This function is intended to be used in combination with the`checkServerIdentity` option that can be passed to {@link connect} and as + * such operates on a `certificate object`. For other purposes, consider using `x509.checkHost()` instead. + * + * This function can be overwritten by providing an alternative function as the`options.checkServerIdentity` option that is passed to `tls.connect()`. The + * overwriting function can call `tls.checkServerIdentity()` of course, to augment + * the checks done with additional verification. + * + * This function is only called if the certificate passed all other checks, such as + * being issued by trusted CA (`options.ca`). + * + * Earlier versions of Node.js incorrectly accepted certificates for a given`hostname` if a matching `uniformResourceIdentifier` subject alternative name + * was present (see [CVE-2021-44531](https://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2021-44531)). Applications that wish to accept`uniformResourceIdentifier` subject alternative names can use + * a custom`options.checkServerIdentity` function that implements the desired behavior. + * @since v0.8.4 + * @param hostname The host name or IP address to verify the certificate against. + * @param cert A `certificate object` representing the peer's certificate. + */ + function checkServerIdentity(hostname: string, cert: PeerCertificate): Error | undefined; + /** + * Creates a new {@link Server}. The `secureConnectionListener`, if provided, is + * automatically set as a listener for the `'secureConnection'` event. + * + * The `ticketKeys` options is automatically shared between `cluster` module + * workers. + * + * The following illustrates a simple echo server: + * + * ```js + * const tls = require('tls'); + * const fs = require('fs'); + * + * const options = { + * key: fs.readFileSync('server-key.pem'), + * cert: fs.readFileSync('server-cert.pem'), + * + * // This is necessary only if using client certificate authentication. + * requestCert: true, + * + * // This is necessary only if the client uses a self-signed certificate. + * ca: [ fs.readFileSync('client-cert.pem') ] + * }; + * + * const server = tls.createServer(options, (socket) => { + * console.log('server connected', + * socket.authorized ? 'authorized' : 'unauthorized'); + * socket.write('welcome!\n'); + * socket.setEncoding('utf8'); + * socket.pipe(socket); + * }); + * server.listen(8000, () => { + * console.log('server bound'); + * }); + * ``` + * + * The server can be tested by connecting to it using the example client from {@link connect}. + * @since v0.3.2 + */ + function createServer(secureConnectionListener?: (socket: TLSSocket) => void): Server; + function createServer(options: TlsOptions, secureConnectionListener?: (socket: TLSSocket) => void): Server; + /** + * The `callback` function, if specified, will be added as a listener for the `'secureConnect'` event. + * + * `tls.connect()` returns a {@link TLSSocket} object. + * + * Unlike the `https` API, `tls.connect()` does not enable the + * SNI (Server Name Indication) extension by default, which may cause some + * servers to return an incorrect certificate or reject the connection + * altogether. To enable SNI, set the `servername` option in addition + * to `host`. + * + * The following illustrates a client for the echo server example from {@link createServer}: + * + * ```js + * // Assumes an echo server that is listening on port 8000. + * const tls = require('tls'); + * const fs = require('fs'); + * + * const options = { + * // Necessary only if the server requires client certificate authentication. + * key: fs.readFileSync('client-key.pem'), + * cert: fs.readFileSync('client-cert.pem'), + * + * // Necessary only if the server uses a self-signed certificate. + * ca: [ fs.readFileSync('server-cert.pem') ], + * + * // Necessary only if the server's cert isn't for "localhost". + * checkServerIdentity: () => { return null; }, + * }; + * + * const socket = tls.connect(8000, options, () => { + * console.log('client connected', + * socket.authorized ? 'authorized' : 'unauthorized'); + * process.stdin.pipe(socket); + * process.stdin.resume(); + * }); + * socket.setEncoding('utf8'); + * socket.on('data', (data) => { + * console.log(data); + * }); + * socket.on('end', () => { + * console.log('server ends connection'); + * }); + * ``` + * @since v0.11.3 + */ + function connect(options: ConnectionOptions, secureConnectListener?: () => void): TLSSocket; + function connect(port: number, host?: string, options?: ConnectionOptions, secureConnectListener?: () => void): TLSSocket; + function connect(port: number, options?: ConnectionOptions, secureConnectListener?: () => void): TLSSocket; + /** + * Creates a new secure pair object with two streams, one of which reads and writes + * the encrypted data and the other of which reads and writes the cleartext data. + * Generally, the encrypted stream is piped to/from an incoming encrypted data + * stream and the cleartext one is used as a replacement for the initial encrypted + * stream. + * + * `tls.createSecurePair()` returns a `tls.SecurePair` object with `cleartext` and`encrypted` stream properties. + * + * Using `cleartext` has the same API as {@link TLSSocket}. + * + * The `tls.createSecurePair()` method is now deprecated in favor of`tls.TLSSocket()`. For example, the code: + * + * ```js + * pair = tls.createSecurePair(// ... ); + * pair.encrypted.pipe(socket); + * socket.pipe(pair.encrypted); + * ``` + * + * can be replaced by: + * + * ```js + * secureSocket = tls.TLSSocket(socket, options); + * ``` + * + * where `secureSocket` has the same API as `pair.cleartext`. + * @since v0.3.2 + * @deprecated Since v0.11.3 - Use {@link TLSSocket} instead. + * @param context A secure context object as returned by `tls.createSecureContext()` + * @param isServer `true` to specify that this TLS connection should be opened as a server. + * @param requestCert `true` to specify whether a server should request a certificate from a connecting client. Only applies when `isServer` is `true`. + * @param rejectUnauthorized If not `false` a server automatically reject clients with invalid certificates. Only applies when `isServer` is `true`. + */ + function createSecurePair(context?: SecureContext, isServer?: boolean, requestCert?: boolean, rejectUnauthorized?: boolean): SecurePair; + /** + * {@link createServer} sets the default value of the `honorCipherOrder` option + * to `true`, other APIs that create secure contexts leave it unset. + * + * {@link createServer} uses a 128 bit truncated SHA1 hash value generated + * from `process.argv` as the default value of the `sessionIdContext` option, other + * APIs that create secure contexts have no default value. + * + * The `tls.createSecureContext()` method creates a `SecureContext` object. It is + * usable as an argument to several `tls` APIs, such as {@link createServer} and `server.addContext()`, but has no public methods. + * + * A key is _required_ for ciphers that use certificates. Either `key` or`pfx` can be used to provide it. + * + * If the `ca` option is not given, then Node.js will default to using [Mozilla's publicly trusted list of + * CAs](https://hg.mozilla.org/mozilla-central/raw-file/tip/security/nss/lib/ckfw/builtins/certdata.txt). + * @since v0.11.13 + */ + function createSecureContext(options?: SecureContextOptions): SecureContext; + /** + * Returns an array with the names of the supported TLS ciphers. The names are + * lower-case for historical reasons, but must be uppercased to be used in + * the `ciphers` option of {@link createSecureContext}. + * + * Not all supported ciphers are enabled by default. See `Modifying the default TLS cipher suite`. + * + * Cipher names that start with `'tls_'` are for TLSv1.3, all the others are for + * TLSv1.2 and below. + * + * ```js + * console.log(tls.getCiphers()); // ['aes128-gcm-sha256', 'aes128-sha', ...] + * ``` + * @since v0.10.2 + */ + function getCiphers(): string[]; + /** + * The default curve name to use for ECDH key agreement in a tls server. + * The default value is 'auto'. See tls.createSecureContext() for further + * information. + */ + let DEFAULT_ECDH_CURVE: string; + /** + * The default value of the maxVersion option of + * tls.createSecureContext(). It can be assigned any of the supported TLS + * protocol versions, 'TLSv1.3', 'TLSv1.2', 'TLSv1.1', or 'TLSv1'. Default: + * 'TLSv1.3', unless changed using CLI options. Using --tls-max-v1.2 sets + * the default to 'TLSv1.2'. Using --tls-max-v1.3 sets the default to + * 'TLSv1.3'. If multiple of the options are provided, the highest maximum + * is used. + */ + let DEFAULT_MAX_VERSION: SecureVersion; + /** + * The default value of the minVersion option of tls.createSecureContext(). + * It can be assigned any of the supported TLS protocol versions, + * 'TLSv1.3', 'TLSv1.2', 'TLSv1.1', or 'TLSv1'. Default: 'TLSv1.2', unless + * changed using CLI options. Using --tls-min-v1.0 sets the default to + * 'TLSv1'. Using --tls-min-v1.1 sets the default to 'TLSv1.1'. Using + * --tls-min-v1.3 sets the default to 'TLSv1.3'. If multiple of the options + * are provided, the lowest minimum is used. + */ + let DEFAULT_MIN_VERSION: SecureVersion; + /** + * An immutable array of strings representing the root certificates (in PEM + * format) used for verifying peer certificates. This is the default value + * of the ca option to tls.createSecureContext(). + */ + const rootCertificates: ReadonlyArray; +} +declare module 'node:tls' { + export * from 'tls'; +} diff --git a/ts-ticket-office-service/node_modules/@types/node/trace_events.d.ts b/ts-ticket-office-service/node_modules/@types/node/trace_events.d.ts new file mode 100755 index 000000000..d47aa9311 --- /dev/null +++ b/ts-ticket-office-service/node_modules/@types/node/trace_events.d.ts @@ -0,0 +1,171 @@ +/** + * The `trace_events` module provides a mechanism to centralize tracing information + * generated by V8, Node.js core, and userspace code. + * + * Tracing can be enabled with the `--trace-event-categories` command-line flag + * or by using the `trace_events` module. The `--trace-event-categories` flag + * accepts a list of comma-separated category names. + * + * The available categories are: + * + * * `node`: An empty placeholder. + * * `node.async_hooks`: Enables capture of detailed `async_hooks` trace data. + * The `async_hooks` events have a unique `asyncId` and a special `triggerId` `triggerAsyncId` property. + * * `node.bootstrap`: Enables capture of Node.js bootstrap milestones. + * * `node.console`: Enables capture of `console.time()` and `console.count()`output. + * * `node.dns.native`: Enables capture of trace data for DNS queries. + * * `node.environment`: Enables capture of Node.js Environment milestones. + * * `node.fs.sync`: Enables capture of trace data for file system sync methods. + * * `node.perf`: Enables capture of `Performance API` measurements. + * * `node.perf.usertiming`: Enables capture of only Performance API User Timing + * measures and marks. + * * `node.perf.timerify`: Enables capture of only Performance API timerify + * measurements. + * * `node.promises.rejections`: Enables capture of trace data tracking the number + * of unhandled Promise rejections and handled-after-rejections. + * * `node.vm.script`: Enables capture of trace data for the `vm` module's`runInNewContext()`, `runInContext()`, and `runInThisContext()` methods. + * * `v8`: The `V8` events are GC, compiling, and execution related. + * + * By default the `node`, `node.async_hooks`, and `v8` categories are enabled. + * + * ```bash + * node --trace-event-categories v8,node,node.async_hooks server.js + * ``` + * + * Prior versions of Node.js required the use of the `--trace-events-enabled`flag to enable trace events. This requirement has been removed. However, the`--trace-events-enabled` flag _may_ still be + * used and will enable the`node`, `node.async_hooks`, and `v8` trace event categories by default. + * + * ```bash + * node --trace-events-enabled + * + * # is equivalent to + * + * node --trace-event-categories v8,node,node.async_hooks + * ``` + * + * Alternatively, trace events may be enabled using the `trace_events` module: + * + * ```js + * const trace_events = require('trace_events'); + * const tracing = trace_events.createTracing({ categories: ['node.perf'] }); + * tracing.enable(); // Enable trace event capture for the 'node.perf' category + * + * // do work + * + * tracing.disable(); // Disable trace event capture for the 'node.perf' category + * ``` + * + * Running Node.js with tracing enabled will produce log files that can be opened + * in the [`chrome://tracing`](https://www.chromium.org/developers/how-tos/trace-event-profiling-tool) tab of Chrome. + * + * The logging file is by default called `node_trace.${rotation}.log`, where`${rotation}` is an incrementing log-rotation id. The filepath pattern can + * be specified with `--trace-event-file-pattern` that accepts a template + * string that supports `${rotation}` and `${pid}`: + * + * ```bash + * node --trace-event-categories v8 --trace-event-file-pattern '${pid}-${rotation}.log' server.js + * ``` + * + * To guarantee that the log file is properly generated after signal events like`SIGINT`, `SIGTERM`, or `SIGBREAK`, make sure to have the appropriate handlers + * in your code, such as: + * + * ```js + * process.on('SIGINT', function onSigint() { + * console.info('Received SIGINT.'); + * process.exit(130); // Or applicable exit code depending on OS and signal + * }); + * ``` + * + * The tracing system uses the same time source + * as the one used by `process.hrtime()`. + * However the trace-event timestamps are expressed in microseconds, + * unlike `process.hrtime()` which returns nanoseconds. + * + * The features from this module are not available in `Worker` threads. + * @experimental + * @see [source](https://github.com/nodejs/node/blob/v18.0.0/lib/trace_events.js) + */ +declare module 'trace_events' { + /** + * The `Tracing` object is used to enable or disable tracing for sets of + * categories. Instances are created using the + * `trace_events.createTracing()` method. + * + * When created, the `Tracing` object is disabled. Calling the + * `tracing.enable()` method adds the categories to the set of enabled trace + * event categories. Calling `tracing.disable()` will remove the categories + * from the set of enabled trace event categories. + */ + interface Tracing { + /** + * A comma-separated list of the trace event categories covered by this + * `Tracing` object. + */ + readonly categories: string; + /** + * Disables this `Tracing` object. + * + * Only trace event categories _not_ covered by other enabled `Tracing` + * objects and _not_ specified by the `--trace-event-categories` flag + * will be disabled. + */ + disable(): void; + /** + * Enables this `Tracing` object for the set of categories covered by + * the `Tracing` object. + */ + enable(): void; + /** + * `true` only if the `Tracing` object has been enabled. + */ + readonly enabled: boolean; + } + interface CreateTracingOptions { + /** + * An array of trace category names. Values included in the array are + * coerced to a string when possible. An error will be thrown if the + * value cannot be coerced. + */ + categories: string[]; + } + /** + * Creates and returns a `Tracing` object for the given set of `categories`. + * + * ```js + * const trace_events = require('trace_events'); + * const categories = ['node.perf', 'node.async_hooks']; + * const tracing = trace_events.createTracing({ categories }); + * tracing.enable(); + * // do stuff + * tracing.disable(); + * ``` + * @since v10.0.0 + * @return . + */ + function createTracing(options: CreateTracingOptions): Tracing; + /** + * Returns a comma-separated list of all currently-enabled trace event + * categories. The current set of enabled trace event categories is determined + * by the _union_ of all currently-enabled `Tracing` objects and any categories + * enabled using the `--trace-event-categories` flag. + * + * Given the file `test.js` below, the command`node --trace-event-categories node.perf test.js` will print`'node.async_hooks,node.perf'` to the console. + * + * ```js + * const trace_events = require('trace_events'); + * const t1 = trace_events.createTracing({ categories: ['node.async_hooks'] }); + * const t2 = trace_events.createTracing({ categories: ['node.perf'] }); + * const t3 = trace_events.createTracing({ categories: ['v8'] }); + * + * t1.enable(); + * t2.enable(); + * + * console.log(trace_events.getEnabledCategories()); + * ``` + * @since v10.0.0 + */ + function getEnabledCategories(): string | undefined; +} +declare module 'node:trace_events' { + export * from 'trace_events'; +} diff --git a/ts-ticket-office-service/node_modules/@types/node/tty.d.ts b/ts-ticket-office-service/node_modules/@types/node/tty.d.ts new file mode 100755 index 000000000..6473f8db7 --- /dev/null +++ b/ts-ticket-office-service/node_modules/@types/node/tty.d.ts @@ -0,0 +1,206 @@ +/** + * The `tty` module provides the `tty.ReadStream` and `tty.WriteStream` classes. + * In most cases, it will not be necessary or possible to use this module directly. + * However, it can be accessed using: + * + * ```js + * const tty = require('tty'); + * ``` + * + * When Node.js detects that it is being run with a text terminal ("TTY") + * attached, `process.stdin` will, by default, be initialized as an instance of`tty.ReadStream` and both `process.stdout` and `process.stderr` will, by + * default, be instances of `tty.WriteStream`. The preferred method of determining + * whether Node.js is being run within a TTY context is to check that the value of + * the `process.stdout.isTTY` property is `true`: + * + * ```console + * $ node -p -e "Boolean(process.stdout.isTTY)" + * true + * $ node -p -e "Boolean(process.stdout.isTTY)" | cat + * false + * ``` + * + * In most cases, there should be little to no reason for an application to + * manually create instances of the `tty.ReadStream` and `tty.WriteStream`classes. + * @see [source](https://github.com/nodejs/node/blob/v18.0.0/lib/tty.js) + */ +declare module 'tty' { + import * as net from 'node:net'; + /** + * The `tty.isatty()` method returns `true` if the given `fd` is associated with + * a TTY and `false` if it is not, including whenever `fd` is not a non-negative + * integer. + * @since v0.5.8 + * @param fd A numeric file descriptor + */ + function isatty(fd: number): boolean; + /** + * Represents the readable side of a TTY. In normal circumstances `process.stdin` will be the only `tty.ReadStream` instance in a Node.js + * process and there should be no reason to create additional instances. + * @since v0.5.8 + */ + class ReadStream extends net.Socket { + constructor(fd: number, options?: net.SocketConstructorOpts); + /** + * A `boolean` that is `true` if the TTY is currently configured to operate as a + * raw device. Defaults to `false`. + * @since v0.7.7 + */ + isRaw: boolean; + /** + * Allows configuration of `tty.ReadStream` so that it operates as a raw device. + * + * When in raw mode, input is always available character-by-character, not + * including modifiers. Additionally, all special processing of characters by the + * terminal is disabled, including echoing input + * characters. Ctrl+C will no longer cause a `SIGINT` when + * in this mode. + * @since v0.7.7 + * @param mode If `true`, configures the `tty.ReadStream` to operate as a raw device. If `false`, configures the `tty.ReadStream` to operate in its default mode. The `readStream.isRaw` + * property will be set to the resulting mode. + * @return The read stream instance. + */ + setRawMode(mode: boolean): this; + /** + * A `boolean` that is always `true` for `tty.ReadStream` instances. + * @since v0.5.8 + */ + isTTY: boolean; + } + /** + * -1 - to the left from cursor + * 0 - the entire line + * 1 - to the right from cursor + */ + type Direction = -1 | 0 | 1; + /** + * Represents the writable side of a TTY. In normal circumstances,`process.stdout` and `process.stderr` will be the only`tty.WriteStream` instances created for a Node.js process and there + * should be no reason to create additional instances. + * @since v0.5.8 + */ + class WriteStream extends net.Socket { + constructor(fd: number); + addListener(event: string, listener: (...args: any[]) => void): this; + addListener(event: 'resize', listener: () => void): this; + emit(event: string | symbol, ...args: any[]): boolean; + emit(event: 'resize'): boolean; + on(event: string, listener: (...args: any[]) => void): this; + on(event: 'resize', listener: () => void): this; + once(event: string, listener: (...args: any[]) => void): this; + once(event: 'resize', listener: () => void): this; + prependListener(event: string, listener: (...args: any[]) => void): this; + prependListener(event: 'resize', listener: () => void): this; + prependOnceListener(event: string, listener: (...args: any[]) => void): this; + prependOnceListener(event: 'resize', listener: () => void): this; + /** + * `writeStream.clearLine()` clears the current line of this `WriteStream` in a + * direction identified by `dir`. + * @since v0.7.7 + * @param callback Invoked once the operation completes. + * @return `false` if the stream wishes for the calling code to wait for the `'drain'` event to be emitted before continuing to write additional data; otherwise `true`. + */ + clearLine(dir: Direction, callback?: () => void): boolean; + /** + * `writeStream.clearScreenDown()` clears this `WriteStream` from the current + * cursor down. + * @since v0.7.7 + * @param callback Invoked once the operation completes. + * @return `false` if the stream wishes for the calling code to wait for the `'drain'` event to be emitted before continuing to write additional data; otherwise `true`. + */ + clearScreenDown(callback?: () => void): boolean; + /** + * `writeStream.cursorTo()` moves this `WriteStream`'s cursor to the specified + * position. + * @since v0.7.7 + * @param callback Invoked once the operation completes. + * @return `false` if the stream wishes for the calling code to wait for the `'drain'` event to be emitted before continuing to write additional data; otherwise `true`. + */ + cursorTo(x: number, y?: number, callback?: () => void): boolean; + cursorTo(x: number, callback: () => void): boolean; + /** + * `writeStream.moveCursor()` moves this `WriteStream`'s cursor _relative_ to its + * current position. + * @since v0.7.7 + * @param callback Invoked once the operation completes. + * @return `false` if the stream wishes for the calling code to wait for the `'drain'` event to be emitted before continuing to write additional data; otherwise `true`. + */ + moveCursor(dx: number, dy: number, callback?: () => void): boolean; + /** + * Returns: + * + * * `1` for 2, + * * `4` for 16, + * * `8` for 256, + * * `24` for 16,777,216 colors supported. + * + * Use this to determine what colors the terminal supports. Due to the nature of + * colors in terminals it is possible to either have false positives or false + * negatives. It depends on process information and the environment variables that + * may lie about what terminal is used. + * It is possible to pass in an `env` object to simulate the usage of a specific + * terminal. This can be useful to check how specific environment settings behave. + * + * To enforce a specific color support, use one of the below environment settings. + * + * * 2 colors: `FORCE_COLOR = 0` (Disables colors) + * * 16 colors: `FORCE_COLOR = 1` + * * 256 colors: `FORCE_COLOR = 2` + * * 16,777,216 colors: `FORCE_COLOR = 3` + * + * Disabling color support is also possible by using the `NO_COLOR` and`NODE_DISABLE_COLORS` environment variables. + * @since v9.9.0 + * @param [env=process.env] An object containing the environment variables to check. This enables simulating the usage of a specific terminal. + */ + getColorDepth(env?: object): number; + /** + * Returns `true` if the `writeStream` supports at least as many colors as provided + * in `count`. Minimum support is 2 (black and white). + * + * This has the same false positives and negatives as described in `writeStream.getColorDepth()`. + * + * ```js + * process.stdout.hasColors(); + * // Returns true or false depending on if `stdout` supports at least 16 colors. + * process.stdout.hasColors(256); + * // Returns true or false depending on if `stdout` supports at least 256 colors. + * process.stdout.hasColors({ TMUX: '1' }); + * // Returns true. + * process.stdout.hasColors(2 ** 24, { TMUX: '1' }); + * // Returns false (the environment setting pretends to support 2 ** 8 colors). + * ``` + * @since v11.13.0, v10.16.0 + * @param [count=16] The number of colors that are requested (minimum 2). + * @param [env=process.env] An object containing the environment variables to check. This enables simulating the usage of a specific terminal. + */ + hasColors(count?: number): boolean; + hasColors(env?: object): boolean; + hasColors(count: number, env?: object): boolean; + /** + * `writeStream.getWindowSize()` returns the size of the TTY + * corresponding to this `WriteStream`. The array is of the type`[numColumns, numRows]` where `numColumns` and `numRows` represent the number + * of columns and rows in the corresponding TTY. + * @since v0.7.7 + */ + getWindowSize(): [number, number]; + /** + * A `number` specifying the number of columns the TTY currently has. This property + * is updated whenever the `'resize'` event is emitted. + * @since v0.7.7 + */ + columns: number; + /** + * A `number` specifying the number of rows the TTY currently has. This property + * is updated whenever the `'resize'` event is emitted. + * @since v0.7.7 + */ + rows: number; + /** + * A `boolean` that is always `true`. + * @since v0.5.8 + */ + isTTY: boolean; + } +} +declare module 'node:tty' { + export * from 'tty'; +} diff --git a/ts-ticket-office-service/node_modules/@types/node/url.d.ts b/ts-ticket-office-service/node_modules/@types/node/url.d.ts new file mode 100755 index 000000000..18362c8aa --- /dev/null +++ b/ts-ticket-office-service/node_modules/@types/node/url.d.ts @@ -0,0 +1,897 @@ +/** + * The `url` module provides utilities for URL resolution and parsing. It can be + * accessed using: + * + * ```js + * import url from 'url'; + * ``` + * @see [source](https://github.com/nodejs/node/blob/v18.0.0/lib/url.js) + */ +declare module 'url' { + import { Blob } from 'node:buffer'; + import { ClientRequestArgs } from 'node:http'; + import { ParsedUrlQuery, ParsedUrlQueryInput } from 'node:querystring'; + // Input to `url.format` + interface UrlObject { + auth?: string | null | undefined; + hash?: string | null | undefined; + host?: string | null | undefined; + hostname?: string | null | undefined; + href?: string | null | undefined; + pathname?: string | null | undefined; + protocol?: string | null | undefined; + search?: string | null | undefined; + slashes?: boolean | null | undefined; + port?: string | number | null | undefined; + query?: string | null | ParsedUrlQueryInput | undefined; + } + // Output of `url.parse` + interface Url { + auth: string | null; + hash: string | null; + host: string | null; + hostname: string | null; + href: string; + path: string | null; + pathname: string | null; + protocol: string | null; + search: string | null; + slashes: boolean | null; + port: string | null; + query: string | null | ParsedUrlQuery; + } + interface UrlWithParsedQuery extends Url { + query: ParsedUrlQuery; + } + interface UrlWithStringQuery extends Url { + query: string | null; + } + /** + * The `url.parse()` method takes a URL string, parses it, and returns a URL + * object. + * + * A `TypeError` is thrown if `urlString` is not a string. + * + * A `URIError` is thrown if the `auth` property is present but cannot be decoded. + * + * Use of the legacy `url.parse()` method is discouraged. Users should + * use the WHATWG `URL` API. Because the `url.parse()` method uses a + * lenient, non-standard algorithm for parsing URL strings, security + * issues can be introduced. Specifically, issues with [host name spoofing](https://hackerone.com/reports/678487) and + * incorrect handling of usernames and passwords have been identified. + * + * Deprecation of this API has been shelved for now primarily due to the the + * inability of the [WHATWG API to parse relative URLs](https://github.com/nodejs/node/issues/12682#issuecomment-1154492373). + * [Discussions are ongoing](https://github.com/whatwg/url/issues/531) for the best way to resolve this. + * + * @since v0.1.25 + * @param urlString The URL string to parse. + * @param [parseQueryString=false] If `true`, the `query` property will always be set to an object returned by the {@link querystring} module's `parse()` method. If `false`, the `query` property + * on the returned URL object will be an unparsed, undecoded string. + * @param [slashesDenoteHost=false] If `true`, the first token after the literal string `//` and preceding the next `/` will be interpreted as the `host`. For instance, given `//foo/bar`, the + * result would be `{host: 'foo', pathname: '/bar'}` rather than `{pathname: '//foo/bar'}`. + */ + function parse(urlString: string): UrlWithStringQuery; + function parse(urlString: string, parseQueryString: false | undefined, slashesDenoteHost?: boolean): UrlWithStringQuery; + function parse(urlString: string, parseQueryString: true, slashesDenoteHost?: boolean): UrlWithParsedQuery; + function parse(urlString: string, parseQueryString: boolean, slashesDenoteHost?: boolean): Url; + /** + * The `url.format()` method returns a formatted URL string derived from`urlObject`. + * + * ```js + * const url = require('url'); + * url.format({ + * protocol: 'https', + * hostname: 'example.com', + * pathname: '/some/path', + * query: { + * page: 1, + * format: 'json' + * } + * }); + * + * // => 'https://example.com/some/path?page=1&format=json' + * ``` + * + * If `urlObject` is not an object or a string, `url.format()` will throw a `TypeError`. + * + * The formatting process operates as follows: + * + * * A new empty string `result` is created. + * * If `urlObject.protocol` is a string, it is appended as-is to `result`. + * * Otherwise, if `urlObject.protocol` is not `undefined` and is not a string, an `Error` is thrown. + * * For all string values of `urlObject.protocol` that _do not end_ with an ASCII + * colon (`:`) character, the literal string `:` will be appended to `result`. + * * If either of the following conditions is true, then the literal string `//`will be appended to `result`: + * * `urlObject.slashes` property is true; + * * `urlObject.protocol` begins with `http`, `https`, `ftp`, `gopher`, or`file`; + * * If the value of the `urlObject.auth` property is truthy, and either`urlObject.host` or `urlObject.hostname` are not `undefined`, the value of`urlObject.auth` will be coerced into a string + * and appended to `result`followed by the literal string `@`. + * * If the `urlObject.host` property is `undefined` then: + * * If the `urlObject.hostname` is a string, it is appended to `result`. + * * Otherwise, if `urlObject.hostname` is not `undefined` and is not a string, + * an `Error` is thrown. + * * If the `urlObject.port` property value is truthy, and `urlObject.hostname`is not `undefined`: + * * The literal string `:` is appended to `result`, and + * * The value of `urlObject.port` is coerced to a string and appended to`result`. + * * Otherwise, if the `urlObject.host` property value is truthy, the value of`urlObject.host` is coerced to a string and appended to `result`. + * * If the `urlObject.pathname` property is a string that is not an empty string: + * * If the `urlObject.pathname`_does not start_ with an ASCII forward slash + * (`/`), then the literal string `'/'` is appended to `result`. + * * The value of `urlObject.pathname` is appended to `result`. + * * Otherwise, if `urlObject.pathname` is not `undefined` and is not a string, an `Error` is thrown. + * * If the `urlObject.search` property is `undefined` and if the `urlObject.query`property is an `Object`, the literal string `?` is appended to `result`followed by the output of calling the + * `querystring` module's `stringify()`method passing the value of `urlObject.query`. + * * Otherwise, if `urlObject.search` is a string: + * * If the value of `urlObject.search`_does not start_ with the ASCII question + * mark (`?`) character, the literal string `?` is appended to `result`. + * * The value of `urlObject.search` is appended to `result`. + * * Otherwise, if `urlObject.search` is not `undefined` and is not a string, an `Error` is thrown. + * * If the `urlObject.hash` property is a string: + * * If the value of `urlObject.hash`_does not start_ with the ASCII hash (`#`) + * character, the literal string `#` is appended to `result`. + * * The value of `urlObject.hash` is appended to `result`. + * * Otherwise, if the `urlObject.hash` property is not `undefined` and is not a + * string, an `Error` is thrown. + * * `result` is returned. + * @since v0.1.25 + * @deprecated Legacy: Use the WHATWG URL API instead. + * @param urlObject A URL object (as returned by `url.parse()` or constructed otherwise). If a string, it is converted to an object by passing it to `url.parse()`. + */ + function format(urlObject: URL, options?: URLFormatOptions): string; + /** + * The `url.format()` method returns a formatted URL string derived from`urlObject`. + * + * ```js + * const url = require('url'); + * url.format({ + * protocol: 'https', + * hostname: 'example.com', + * pathname: '/some/path', + * query: { + * page: 1, + * format: 'json' + * } + * }); + * + * // => 'https://example.com/some/path?page=1&format=json' + * ``` + * + * If `urlObject` is not an object or a string, `url.format()` will throw a `TypeError`. + * + * The formatting process operates as follows: + * + * * A new empty string `result` is created. + * * If `urlObject.protocol` is a string, it is appended as-is to `result`. + * * Otherwise, if `urlObject.protocol` is not `undefined` and is not a string, an `Error` is thrown. + * * For all string values of `urlObject.protocol` that _do not end_ with an ASCII + * colon (`:`) character, the literal string `:` will be appended to `result`. + * * If either of the following conditions is true, then the literal string `//`will be appended to `result`: + * * `urlObject.slashes` property is true; + * * `urlObject.protocol` begins with `http`, `https`, `ftp`, `gopher`, or`file`; + * * If the value of the `urlObject.auth` property is truthy, and either`urlObject.host` or `urlObject.hostname` are not `undefined`, the value of`urlObject.auth` will be coerced into a string + * and appended to `result`followed by the literal string `@`. + * * If the `urlObject.host` property is `undefined` then: + * * If the `urlObject.hostname` is a string, it is appended to `result`. + * * Otherwise, if `urlObject.hostname` is not `undefined` and is not a string, + * an `Error` is thrown. + * * If the `urlObject.port` property value is truthy, and `urlObject.hostname`is not `undefined`: + * * The literal string `:` is appended to `result`, and + * * The value of `urlObject.port` is coerced to a string and appended to`result`. + * * Otherwise, if the `urlObject.host` property value is truthy, the value of`urlObject.host` is coerced to a string and appended to `result`. + * * If the `urlObject.pathname` property is a string that is not an empty string: + * * If the `urlObject.pathname`_does not start_ with an ASCII forward slash + * (`/`), then the literal string `'/'` is appended to `result`. + * * The value of `urlObject.pathname` is appended to `result`. + * * Otherwise, if `urlObject.pathname` is not `undefined` and is not a string, an `Error` is thrown. + * * If the `urlObject.search` property is `undefined` and if the `urlObject.query`property is an `Object`, the literal string `?` is appended to `result`followed by the output of calling the + * `querystring` module's `stringify()`method passing the value of `urlObject.query`. + * * Otherwise, if `urlObject.search` is a string: + * * If the value of `urlObject.search`_does not start_ with the ASCII question + * mark (`?`) character, the literal string `?` is appended to `result`. + * * The value of `urlObject.search` is appended to `result`. + * * Otherwise, if `urlObject.search` is not `undefined` and is not a string, an `Error` is thrown. + * * If the `urlObject.hash` property is a string: + * * If the value of `urlObject.hash`_does not start_ with the ASCII hash (`#`) + * character, the literal string `#` is appended to `result`. + * * The value of `urlObject.hash` is appended to `result`. + * * Otherwise, if the `urlObject.hash` property is not `undefined` and is not a + * string, an `Error` is thrown. + * * `result` is returned. + * @since v0.1.25 + * @deprecated Legacy: Use the WHATWG URL API instead. + * @param urlObject A URL object (as returned by `url.parse()` or constructed otherwise). If a string, it is converted to an object by passing it to `url.parse()`. + */ + function format(urlObject: UrlObject | string): string; + /** + * The `url.resolve()` method resolves a target URL relative to a base URL in a + * manner similar to that of a web browser resolving an anchor tag. + * + * ```js + * const url = require('url'); + * url.resolve('/one/two/three', 'four'); // '/one/two/four' + * url.resolve('http://example.com/', '/one'); // 'http://example.com/one' + * url.resolve('http://example.com/one', '/two'); // 'http://example.com/two' + * ``` + * + * To achieve the same result using the WHATWG URL API: + * + * ```js + * function resolve(from, to) { + * const resolvedUrl = new URL(to, new URL(from, 'resolve://')); + * if (resolvedUrl.protocol === 'resolve:') { + * // `from` is a relative URL. + * const { pathname, search, hash } = resolvedUrl; + * return pathname + search + hash; + * } + * return resolvedUrl.toString(); + * } + * + * resolve('/one/two/three', 'four'); // '/one/two/four' + * resolve('http://example.com/', '/one'); // 'http://example.com/one' + * resolve('http://example.com/one', '/two'); // 'http://example.com/two' + * ``` + * @since v0.1.25 + * @deprecated Legacy: Use the WHATWG URL API instead. + * @param from The base URL to use if `to` is a relative URL. + * @param to The target URL to resolve. + */ + function resolve(from: string, to: string): string; + /** + * Returns the [Punycode](https://tools.ietf.org/html/rfc5891#section-4.4) ASCII serialization of the `domain`. If `domain` is an + * invalid domain, the empty string is returned. + * + * It performs the inverse operation to {@link domainToUnicode}. + * + * This feature is only available if the `node` executable was compiled with `ICU` enabled. If not, the domain names are passed through unchanged. + * + * ```js + * import url from 'url'; + * + * console.log(url.domainToASCII('español.com')); + * // Prints xn--espaol-zwa.com + * console.log(url.domainToASCII('中文.com')); + * // Prints xn--fiq228c.com + * console.log(url.domainToASCII('xn--iñvalid.com')); + * // Prints an empty string + * ``` + * @since v7.4.0, v6.13.0 + */ + function domainToASCII(domain: string): string; + /** + * Returns the Unicode serialization of the `domain`. If `domain` is an invalid + * domain, the empty string is returned. + * + * It performs the inverse operation to {@link domainToASCII}. + * + * This feature is only available if the `node` executable was compiled with `ICU` enabled. If not, the domain names are passed through unchanged. + * + * ```js + * import url from 'url'; + * + * console.log(url.domainToUnicode('xn--espaol-zwa.com')); + * // Prints español.com + * console.log(url.domainToUnicode('xn--fiq228c.com')); + * // Prints 中文.com + * console.log(url.domainToUnicode('xn--iñvalid.com')); + * // Prints an empty string + * ``` + * @since v7.4.0, v6.13.0 + */ + function domainToUnicode(domain: string): string; + /** + * This function ensures the correct decodings of percent-encoded characters as + * well as ensuring a cross-platform valid absolute path string. + * + * ```js + * import { fileURLToPath } from 'url'; + * + * const __filename = fileURLToPath(import.meta.url); + * + * new URL('file:///C:/path/').pathname; // Incorrect: /C:/path/ + * fileURLToPath('file:///C:/path/'); // Correct: C:\path\ (Windows) + * + * new URL('file://nas/foo.txt').pathname; // Incorrect: /foo.txt + * fileURLToPath('file://nas/foo.txt'); // Correct: \\nas\foo.txt (Windows) + * + * new URL('file:///你好.txt').pathname; // Incorrect: /%E4%BD%A0%E5%A5%BD.txt + * fileURLToPath('file:///你好.txt'); // Correct: /你好.txt (POSIX) + * + * new URL('file:///hello world').pathname; // Incorrect: /hello%20world + * fileURLToPath('file:///hello world'); // Correct: /hello world (POSIX) + * ``` + * @since v10.12.0 + * @param url The file URL string or URL object to convert to a path. + * @return The fully-resolved platform-specific Node.js file path. + */ + function fileURLToPath(url: string | URL): string; + /** + * This function ensures that `path` is resolved absolutely, and that the URL + * control characters are correctly encoded when converting into a File URL. + * + * ```js + * import { pathToFileURL } from 'url'; + * + * new URL('/foo#1', 'file:'); // Incorrect: file:///foo#1 + * pathToFileURL('/foo#1'); // Correct: file:///foo%231 (POSIX) + * + * new URL('/some/path%.c', 'file:'); // Incorrect: file:///some/path%.c + * pathToFileURL('/some/path%.c'); // Correct: file:///some/path%25.c (POSIX) + * ``` + * @since v10.12.0 + * @param path The path to convert to a File URL. + * @return The file URL object. + */ + function pathToFileURL(path: string): URL; + /** + * This utility function converts a URL object into an ordinary options object as + * expected by the `http.request()` and `https.request()` APIs. + * + * ```js + * import { urlToHttpOptions } from 'url'; + * const myURL = new URL('https://a:b@測試?abc#foo'); + * + * console.log(urlToHttpOptions(myURL)); + * /* + * { + * protocol: 'https:', + * hostname: 'xn--g6w251d', + * hash: '#foo', + * search: '?abc', + * pathname: '/', + * path: '/?abc', + * href: 'https://a:b@xn--g6w251d/?abc#foo', + * auth: 'a:b' + * } + * + * ``` + * @since v15.7.0, v14.18.0 + * @param url The `WHATWG URL` object to convert to an options object. + * @return Options object + */ + function urlToHttpOptions(url: URL): ClientRequestArgs; + interface URLFormatOptions { + auth?: boolean | undefined; + fragment?: boolean | undefined; + search?: boolean | undefined; + unicode?: boolean | undefined; + } + /** + * Browser-compatible `URL` class, implemented by following the WHATWG URL + * Standard. [Examples of parsed URLs](https://url.spec.whatwg.org/#example-url-parsing) may be found in the Standard itself. + * The `URL` class is also available on the global object. + * + * In accordance with browser conventions, all properties of `URL` objects + * are implemented as getters and setters on the class prototype, rather than as + * data properties on the object itself. Thus, unlike `legacy urlObject` s, + * using the `delete` keyword on any properties of `URL` objects (e.g. `delete myURL.protocol`, `delete myURL.pathname`, etc) has no effect but will still + * return `true`. + * @since v7.0.0, v6.13.0 + */ + class URL { + /** + * Creates a `'blob:nodedata:...'` URL string that represents the given `Blob` object and can be used to retrieve the `Blob` later. + * + * ```js + * const { + * Blob, + * resolveObjectURL, + * } = require('buffer'); + * + * const blob = new Blob(['hello']); + * const id = URL.createObjectURL(blob); + * + * // later... + * + * const otherBlob = resolveObjectURL(id); + * console.log(otherBlob.size); + * ``` + * + * The data stored by the registered `Blob` will be retained in memory until`URL.revokeObjectURL()` is called to remove it. + * + * `Blob` objects are registered within the current thread. If using Worker + * Threads, `Blob` objects registered within one Worker will not be available + * to other workers or the main thread. + * @since v16.7.0 + * @experimental + */ + static createObjectURL(blob: Blob): string; + /** + * Removes the stored `Blob` identified by the given ID. Attempting to revoke a + * ID that isn’t registered will silently fail. + * @since v16.7.0 + * @experimental + * @param id A `'blob:nodedata:...` URL string returned by a prior call to `URL.createObjectURL()`. + */ + static revokeObjectURL(objectUrl: string): void; + constructor(input: string, base?: string | URL); + /** + * Gets and sets the fragment portion of the URL. + * + * ```js + * const myURL = new URL('https://example.org/foo#bar'); + * console.log(myURL.hash); + * // Prints #bar + * + * myURL.hash = 'baz'; + * console.log(myURL.href); + * // Prints https://example.org/foo#baz + * ``` + * + * Invalid URL characters included in the value assigned to the `hash` property + * are `percent-encoded`. The selection of which characters to + * percent-encode may vary somewhat from what the {@link parse} and {@link format} methods would produce. + */ + hash: string; + /** + * Gets and sets the host portion of the URL. + * + * ```js + * const myURL = new URL('https://example.org:81/foo'); + * console.log(myURL.host); + * // Prints example.org:81 + * + * myURL.host = 'example.com:82'; + * console.log(myURL.href); + * // Prints https://example.com:82/foo + * ``` + * + * Invalid host values assigned to the `host` property are ignored. + */ + host: string; + /** + * Gets and sets the host name portion of the URL. The key difference between`url.host` and `url.hostname` is that `url.hostname` does _not_ include the + * port. + * + * ```js + * const myURL = new URL('https://example.org:81/foo'); + * console.log(myURL.hostname); + * // Prints example.org + * + * // Setting the hostname does not change the port + * myURL.hostname = 'example.com:82'; + * console.log(myURL.href); + * // Prints https://example.com:81/foo + * + * // Use myURL.host to change the hostname and port + * myURL.host = 'example.org:82'; + * console.log(myURL.href); + * // Prints https://example.org:82/foo + * ``` + * + * Invalid host name values assigned to the `hostname` property are ignored. + */ + hostname: string; + /** + * Gets and sets the serialized URL. + * + * ```js + * const myURL = new URL('https://example.org/foo'); + * console.log(myURL.href); + * // Prints https://example.org/foo + * + * myURL.href = 'https://example.com/bar'; + * console.log(myURL.href); + * // Prints https://example.com/bar + * ``` + * + * Getting the value of the `href` property is equivalent to calling {@link toString}. + * + * Setting the value of this property to a new value is equivalent to creating a + * new `URL` object using `new URL(value)`. Each of the `URL`object's properties will be modified. + * + * If the value assigned to the `href` property is not a valid URL, a `TypeError`will be thrown. + */ + href: string; + /** + * Gets the read-only serialization of the URL's origin. + * + * ```js + * const myURL = new URL('https://example.org/foo/bar?baz'); + * console.log(myURL.origin); + * // Prints https://example.org + * ``` + * + * ```js + * const idnURL = new URL('https://測試'); + * console.log(idnURL.origin); + * // Prints https://xn--g6w251d + * + * console.log(idnURL.hostname); + * // Prints xn--g6w251d + * ``` + */ + readonly origin: string; + /** + * Gets and sets the password portion of the URL. + * + * ```js + * const myURL = new URL('https://abc:xyz@example.com'); + * console.log(myURL.password); + * // Prints xyz + * + * myURL.password = '123'; + * console.log(myURL.href); + * // Prints https://abc:123@example.com + * ``` + * + * Invalid URL characters included in the value assigned to the `password` property + * are `percent-encoded`. The selection of which characters to + * percent-encode may vary somewhat from what the {@link parse} and {@link format} methods would produce. + */ + password: string; + /** + * Gets and sets the path portion of the URL. + * + * ```js + * const myURL = new URL('https://example.org/abc/xyz?123'); + * console.log(myURL.pathname); + * // Prints /abc/xyz + * + * myURL.pathname = '/abcdef'; + * console.log(myURL.href); + * // Prints https://example.org/abcdef?123 + * ``` + * + * Invalid URL characters included in the value assigned to the `pathname`property are `percent-encoded`. The selection of which characters + * to percent-encode may vary somewhat from what the {@link parse} and {@link format} methods would produce. + */ + pathname: string; + /** + * Gets and sets the port portion of the URL. + * + * The port value may be a number or a string containing a number in the range`0` to `65535` (inclusive). Setting the value to the default port of the`URL` objects given `protocol` will + * result in the `port` value becoming + * the empty string (`''`). + * + * The port value can be an empty string in which case the port depends on + * the protocol/scheme: + * + * + * + * Upon assigning a value to the port, the value will first be converted to a + * string using `.toString()`. + * + * If that string is invalid but it begins with a number, the leading number is + * assigned to `port`. + * If the number lies outside the range denoted above, it is ignored. + * + * ```js + * const myURL = new URL('https://example.org:8888'); + * console.log(myURL.port); + * // Prints 8888 + * + * // Default ports are automatically transformed to the empty string + * // (HTTPS protocol's default port is 443) + * myURL.port = '443'; + * console.log(myURL.port); + * // Prints the empty string + * console.log(myURL.href); + * // Prints https://example.org/ + * + * myURL.port = 1234; + * console.log(myURL.port); + * // Prints 1234 + * console.log(myURL.href); + * // Prints https://example.org:1234/ + * + * // Completely invalid port strings are ignored + * myURL.port = 'abcd'; + * console.log(myURL.port); + * // Prints 1234 + * + * // Leading numbers are treated as a port number + * myURL.port = '5678abcd'; + * console.log(myURL.port); + * // Prints 5678 + * + * // Non-integers are truncated + * myURL.port = 1234.5678; + * console.log(myURL.port); + * // Prints 1234 + * + * // Out-of-range numbers which are not represented in scientific notation + * // will be ignored. + * myURL.port = 1e10; // 10000000000, will be range-checked as described below + * console.log(myURL.port); + * // Prints 1234 + * ``` + * + * Numbers which contain a decimal point, + * such as floating-point numbers or numbers in scientific notation, + * are not an exception to this rule. + * Leading numbers up to the decimal point will be set as the URL's port, + * assuming they are valid: + * + * ```js + * myURL.port = 4.567e21; + * console.log(myURL.port); + * // Prints 4 (because it is the leading number in the string '4.567e21') + * ``` + */ + port: string; + /** + * Gets and sets the protocol portion of the URL. + * + * ```js + * const myURL = new URL('https://example.org'); + * console.log(myURL.protocol); + * // Prints https: + * + * myURL.protocol = 'ftp'; + * console.log(myURL.href); + * // Prints ftp://example.org/ + * ``` + * + * Invalid URL protocol values assigned to the `protocol` property are ignored. + */ + protocol: string; + /** + * Gets and sets the serialized query portion of the URL. + * + * ```js + * const myURL = new URL('https://example.org/abc?123'); + * console.log(myURL.search); + * // Prints ?123 + * + * myURL.search = 'abc=xyz'; + * console.log(myURL.href); + * // Prints https://example.org/abc?abc=xyz + * ``` + * + * Any invalid URL characters appearing in the value assigned the `search`property will be `percent-encoded`. The selection of which + * characters to percent-encode may vary somewhat from what the {@link parse} and {@link format} methods would produce. + */ + search: string; + /** + * Gets the `URLSearchParams` object representing the query parameters of the + * URL. This property is read-only but the `URLSearchParams` object it provides + * can be used to mutate the URL instance; to replace the entirety of query + * parameters of the URL, use the {@link search} setter. See `URLSearchParams` documentation for details. + * + * Use care when using `.searchParams` to modify the `URL` because, + * per the WHATWG specification, the `URLSearchParams` object uses + * different rules to determine which characters to percent-encode. For + * instance, the `URL` object will not percent encode the ASCII tilde (`~`) + * character, while `URLSearchParams` will always encode it: + * + * ```js + * const myUrl = new URL('https://example.org/abc?foo=~bar'); + * + * console.log(myUrl.search); // prints ?foo=~bar + * + * // Modify the URL via searchParams... + * myUrl.searchParams.sort(); + * + * console.log(myUrl.search); // prints ?foo=%7Ebar + * ``` + */ + readonly searchParams: URLSearchParams; + /** + * Gets and sets the username portion of the URL. + * + * ```js + * const myURL = new URL('https://abc:xyz@example.com'); + * console.log(myURL.username); + * // Prints abc + * + * myURL.username = '123'; + * console.log(myURL.href); + * // Prints https://123:xyz@example.com/ + * ``` + * + * Any invalid URL characters appearing in the value assigned the `username`property will be `percent-encoded`. The selection of which + * characters to percent-encode may vary somewhat from what the {@link parse} and {@link format} methods would produce. + */ + username: string; + /** + * The `toString()` method on the `URL` object returns the serialized URL. The + * value returned is equivalent to that of {@link href} and {@link toJSON}. + */ + toString(): string; + /** + * The `toJSON()` method on the `URL` object returns the serialized URL. The + * value returned is equivalent to that of {@link href} and {@link toString}. + * + * This method is automatically called when an `URL` object is serialized + * with [`JSON.stringify()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify). + * + * ```js + * const myURLs = [ + * new URL('https://www.example.com'), + * new URL('https://test.example.org'), + * ]; + * console.log(JSON.stringify(myURLs)); + * // Prints ["https://www.example.com/","https://test.example.org/"] + * ``` + */ + toJSON(): string; + } + /** + * The `URLSearchParams` API provides read and write access to the query of a`URL`. The `URLSearchParams` class can also be used standalone with one of the + * four following constructors. + * The `URLSearchParams` class is also available on the global object. + * + * The WHATWG `URLSearchParams` interface and the `querystring` module have + * similar purpose, but the purpose of the `querystring` module is more + * general, as it allows the customization of delimiter characters (`&` and `=`). + * On the other hand, this API is designed purely for URL query strings. + * + * ```js + * const myURL = new URL('https://example.org/?abc=123'); + * console.log(myURL.searchParams.get('abc')); + * // Prints 123 + * + * myURL.searchParams.append('abc', 'xyz'); + * console.log(myURL.href); + * // Prints https://example.org/?abc=123&abc=xyz + * + * myURL.searchParams.delete('abc'); + * myURL.searchParams.set('a', 'b'); + * console.log(myURL.href); + * // Prints https://example.org/?a=b + * + * const newSearchParams = new URLSearchParams(myURL.searchParams); + * // The above is equivalent to + * // const newSearchParams = new URLSearchParams(myURL.search); + * + * newSearchParams.append('a', 'c'); + * console.log(myURL.href); + * // Prints https://example.org/?a=b + * console.log(newSearchParams.toString()); + * // Prints a=b&a=c + * + * // newSearchParams.toString() is implicitly called + * myURL.search = newSearchParams; + * console.log(myURL.href); + * // Prints https://example.org/?a=b&a=c + * newSearchParams.delete('a'); + * console.log(myURL.href); + * // Prints https://example.org/?a=b&a=c + * ``` + * @since v7.5.0, v6.13.0 + */ + class URLSearchParams implements Iterable<[string, string]> { + constructor(init?: URLSearchParams | string | Record> | Iterable<[string, string]> | ReadonlyArray<[string, string]>); + /** + * Append a new name-value pair to the query string. + */ + append(name: string, value: string): void; + /** + * Remove all name-value pairs whose name is `name`. + */ + delete(name: string): void; + /** + * Returns an ES6 `Iterator` over each of the name-value pairs in the query. + * Each item of the iterator is a JavaScript `Array`. The first item of the `Array`is the `name`, the second item of the `Array` is the `value`. + * + * Alias for `urlSearchParams[@@iterator]()`. + */ + entries(): IterableIterator<[string, string]>; + /** + * Iterates over each name-value pair in the query and invokes the given function. + * + * ```js + * const myURL = new URL('https://example.org/?a=b&c=d'); + * myURL.searchParams.forEach((value, name, searchParams) => { + * console.log(name, value, myURL.searchParams === searchParams); + * }); + * // Prints: + * // a b true + * // c d true + * ``` + * @param fn Invoked for each name-value pair in the query + * @param thisArg To be used as `this` value for when `fn` is called + */ + forEach(callback: (this: TThis, value: string, name: string, searchParams: URLSearchParams) => void, thisArg?: TThis): void; + /** + * Returns the value of the first name-value pair whose name is `name`. If there + * are no such pairs, `null` is returned. + * @return or `null` if there is no name-value pair with the given `name`. + */ + get(name: string): string | null; + /** + * Returns the values of all name-value pairs whose name is `name`. If there are + * no such pairs, an empty array is returned. + */ + getAll(name: string): string[]; + /** + * Returns `true` if there is at least one name-value pair whose name is `name`. + */ + has(name: string): boolean; + /** + * Returns an ES6 `Iterator` over the names of each name-value pair. + * + * ```js + * const params = new URLSearchParams('foo=bar&foo=baz'); + * for (const name of params.keys()) { + * console.log(name); + * } + * // Prints: + * // foo + * // foo + * ``` + */ + keys(): IterableIterator; + /** + * Sets the value in the `URLSearchParams` object associated with `name` to`value`. If there are any pre-existing name-value pairs whose names are `name`, + * set the first such pair's value to `value` and remove all others. If not, + * append the name-value pair to the query string. + * + * ```js + * const params = new URLSearchParams(); + * params.append('foo', 'bar'); + * params.append('foo', 'baz'); + * params.append('abc', 'def'); + * console.log(params.toString()); + * // Prints foo=bar&foo=baz&abc=def + * + * params.set('foo', 'def'); + * params.set('xyz', 'opq'); + * console.log(params.toString()); + * // Prints foo=def&abc=def&xyz=opq + * ``` + */ + set(name: string, value: string): void; + /** + * Sort all existing name-value pairs in-place by their names. Sorting is done + * with a [stable sorting algorithm](https://en.wikipedia.org/wiki/Sorting_algorithm#Stability), so relative order between name-value pairs + * with the same name is preserved. + * + * This method can be used, in particular, to increase cache hits. + * + * ```js + * const params = new URLSearchParams('query[]=abc&type=search&query[]=123'); + * params.sort(); + * console.log(params.toString()); + * // Prints query%5B%5D=abc&query%5B%5D=123&type=search + * ``` + * @since v7.7.0, v6.13.0 + */ + sort(): void; + /** + * Returns the search parameters serialized as a string, with characters + * percent-encoded where necessary. + */ + toString(): string; + /** + * Returns an ES6 `Iterator` over the values of each name-value pair. + */ + values(): IterableIterator; + [Symbol.iterator](): IterableIterator<[string, string]>; + } + import { URL as _URL, URLSearchParams as _URLSearchParams } from 'url'; + global { + interface URLSearchParams extends _URLSearchParams {} + interface URL extends _URL {} + interface Global { + URL: typeof _URL; + URLSearchParams: typeof _URLSearchParams; + } + /** + * `URL` class is a global reference for `require('url').URL` + * https://nodejs.org/api/url.html#the-whatwg-url-api + * @since v10.0.0 + */ + var URL: typeof globalThis extends { + onmessage: any; + URL: infer URL; + } + ? URL + : typeof _URL; + /** + * `URLSearchParams` class is a global reference for `require('url').URLSearchParams` + * https://nodejs.org/api/url.html#class-urlsearchparams + * @since v10.0.0 + */ + var URLSearchParams: typeof globalThis extends { + onmessage: any; + URLSearchParams: infer URLSearchParams; + } + ? URLSearchParams + : typeof _URLSearchParams; + } +} +declare module 'node:url' { + export * from 'url'; +} diff --git a/ts-ticket-office-service/node_modules/@types/node/util.d.ts b/ts-ticket-office-service/node_modules/@types/node/util.d.ts new file mode 100755 index 000000000..88f2a5415 --- /dev/null +++ b/ts-ticket-office-service/node_modules/@types/node/util.d.ts @@ -0,0 +1,1605 @@ +/** + * The `util` module supports the needs of Node.js internal APIs. Many of the + * utilities are useful for application and module developers as well. To access + * it: + * + * ```js + * const util = require('util'); + * ``` + * @see [source](https://github.com/nodejs/node/blob/v18.0.0/lib/util.js) + */ +declare module 'util' { + import * as types from 'node:util/types'; + export interface InspectOptions { + /** + * If set to `true`, getters are going to be + * inspected as well. If set to `'get'` only getters without setter are going + * to be inspected. If set to `'set'` only getters having a corresponding + * setter are going to be inspected. This might cause side effects depending on + * the getter function. + * @default `false` + */ + getters?: 'get' | 'set' | boolean | undefined; + showHidden?: boolean | undefined; + /** + * @default 2 + */ + depth?: number | null | undefined; + colors?: boolean | undefined; + customInspect?: boolean | undefined; + showProxy?: boolean | undefined; + maxArrayLength?: number | null | undefined; + /** + * Specifies the maximum number of characters to + * include when formatting. Set to `null` or `Infinity` to show all elements. + * Set to `0` or negative to show no characters. + * @default 10000 + */ + maxStringLength?: number | null | undefined; + breakLength?: number | undefined; + /** + * Setting this to `false` causes each object key + * to be displayed on a new line. It will also add new lines to text that is + * longer than `breakLength`. If set to a number, the most `n` inner elements + * are united on a single line as long as all properties fit into + * `breakLength`. Short array elements are also grouped together. Note that no + * text will be reduced below 16 characters, no matter the `breakLength` size. + * For more information, see the example below. + * @default `true` + */ + compact?: boolean | number | undefined; + sorted?: boolean | ((a: string, b: string) => number) | undefined; + } + export type Style = 'special' | 'number' | 'bigint' | 'boolean' | 'undefined' | 'null' | 'string' | 'symbol' | 'date' | 'regexp' | 'module'; + export type CustomInspectFunction = (depth: number, options: InspectOptionsStylized) => string; + export interface InspectOptionsStylized extends InspectOptions { + stylize(text: string, styleType: Style): string; + } + /** + * The `util.format()` method returns a formatted string using the first argument + * as a `printf`\-like format string which can contain zero or more format + * specifiers. Each specifier is replaced with the converted value from the + * corresponding argument. Supported specifiers are: + * + * If a specifier does not have a corresponding argument, it is not replaced: + * + * ```js + * util.format('%s:%s', 'foo'); + * // Returns: 'foo:%s' + * ``` + * + * Values that are not part of the format string are formatted using`util.inspect()` if their type is not `string`. + * + * If there are more arguments passed to the `util.format()` method than the + * number of specifiers, the extra arguments are concatenated to the returned + * string, separated by spaces: + * + * ```js + * util.format('%s:%s', 'foo', 'bar', 'baz'); + * // Returns: 'foo:bar baz' + * ``` + * + * If the first argument does not contain a valid format specifier, `util.format()`returns a string that is the concatenation of all arguments separated by spaces: + * + * ```js + * util.format(1, 2, 3); + * // Returns: '1 2 3' + * ``` + * + * If only one argument is passed to `util.format()`, it is returned as it is + * without any formatting: + * + * ```js + * util.format('%% %s'); + * // Returns: '%% %s' + * ``` + * + * `util.format()` is a synchronous method that is intended as a debugging tool. + * Some input values can have a significant performance overhead that can block the + * event loop. Use this function with care and never in a hot code path. + * @since v0.5.3 + * @param format A `printf`-like format string. + */ + export function format(format?: any, ...param: any[]): string; + /** + * This function is identical to {@link format}, except in that it takes + * an `inspectOptions` argument which specifies options that are passed along to {@link inspect}. + * + * ```js + * util.formatWithOptions({ colors: true }, 'See object %O', { foo: 42 }); + * // Returns 'See object { foo: 42 }', where `42` is colored as a number + * // when printed to a terminal. + * ``` + * @since v10.0.0 + */ + export function formatWithOptions(inspectOptions: InspectOptions, format?: any, ...param: any[]): string; + /** + * Returns the string name for a numeric error code that comes from a Node.js API. + * The mapping between error codes and error names is platform-dependent. + * See `Common System Errors` for the names of common errors. + * + * ```js + * fs.access('file/that/does/not/exist', (err) => { + * const name = util.getSystemErrorName(err.errno); + * console.error(name); // ENOENT + * }); + * ``` + * @since v9.7.0 + */ + export function getSystemErrorName(err: number): string; + /** + * Returns a Map of all system error codes available from the Node.js API. + * The mapping between error codes and error names is platform-dependent. + * See `Common System Errors` for the names of common errors. + * + * ```js + * fs.access('file/that/does/not/exist', (err) => { + * const errorMap = util.getSystemErrorMap(); + * const name = errorMap.get(err.errno); + * console.error(name); // ENOENT + * }); + * ``` + * @since v16.0.0, v14.17.0 + */ + export function getSystemErrorMap(): Map; + /** + * The `util.log()` method prints the given `string` to `stdout` with an included + * timestamp. + * + * ```js + * const util = require('util'); + * + * util.log('Timestamped message.'); + * ``` + * @since v0.3.0 + * @deprecated Since v6.0.0 - Use a third party module instead. + */ + export function log(string: string): void; + /** + * Returns the `string` after replacing any surrogate code points + * (or equivalently, any unpaired surrogate code units) with the + * Unicode "replacement character" U+FFFD. + * @since v16.8.0, v14.18.0 + */ + export function toUSVString(string: string): string; + /** + * The `util.inspect()` method returns a string representation of `object` that is + * intended for debugging. The output of `util.inspect` may change at any time + * and should not be depended upon programmatically. Additional `options` may be + * passed that alter the result.`util.inspect()` will use the constructor's name and/or `@@toStringTag` to make + * an identifiable tag for an inspected value. + * + * ```js + * class Foo { + * get [Symbol.toStringTag]() { + * return 'bar'; + * } + * } + * + * class Bar {} + * + * const baz = Object.create(null, { [Symbol.toStringTag]: { value: 'foo' } }); + * + * util.inspect(new Foo()); // 'Foo [bar] {}' + * util.inspect(new Bar()); // 'Bar {}' + * util.inspect(baz); // '[foo] {}' + * ``` + * + * Circular references point to their anchor by using a reference index: + * + * ```js + * const { inspect } = require('util'); + * + * const obj = {}; + * obj.a = [obj]; + * obj.b = {}; + * obj.b.inner = obj.b; + * obj.b.obj = obj; + * + * console.log(inspect(obj)); + * // { + * // a: [ [Circular *1] ], + * // b: { inner: [Circular *2], obj: [Circular *1] } + * // } + * ``` + * + * The following example inspects all properties of the `util` object: + * + * ```js + * const util = require('util'); + * + * console.log(util.inspect(util, { showHidden: true, depth: null })); + * ``` + * + * The following example highlights the effect of the `compact` option: + * + * ```js + * const util = require('util'); + * + * const o = { + * a: [1, 2, [[ + * 'Lorem ipsum dolor sit amet,\nconsectetur adipiscing elit, sed do ' + + * 'eiusmod \ntempor incididunt ut labore et dolore magna aliqua.', + * 'test', + * 'foo']], 4], + * b: new Map([['za', 1], ['zb', 'test']]) + * }; + * console.log(util.inspect(o, { compact: true, depth: 5, breakLength: 80 })); + * + * // { a: + * // [ 1, + * // 2, + * // [ [ 'Lorem ipsum dolor sit amet,\nconsectetur [...]', // A long line + * // 'test', + * // 'foo' ] ], + * // 4 ], + * // b: Map(2) { 'za' => 1, 'zb' => 'test' } } + * + * // Setting `compact` to false or an integer creates more reader friendly output. + * console.log(util.inspect(o, { compact: false, depth: 5, breakLength: 80 })); + * + * // { + * // a: [ + * // 1, + * // 2, + * // [ + * // [ + * // 'Lorem ipsum dolor sit amet,\n' + + * // 'consectetur adipiscing elit, sed do eiusmod \n' + + * // 'tempor incididunt ut labore et dolore magna aliqua.', + * // 'test', + * // 'foo' + * // ] + * // ], + * // 4 + * // ], + * // b: Map(2) { + * // 'za' => 1, + * // 'zb' => 'test' + * // } + * // } + * + * // Setting `breakLength` to e.g. 150 will print the "Lorem ipsum" text in a + * // single line. + * ``` + * + * The `showHidden` option allows [`WeakMap`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/WeakMap) and + * [`WeakSet`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/WeakSet) entries to be + * inspected. If there are more entries than `maxArrayLength`, there is no + * guarantee which entries are displayed. That means retrieving the same [`WeakSet`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/WeakSet) entries twice may + * result in different output. Furthermore, entries + * with no remaining strong references may be garbage collected at any time. + * + * ```js + * const { inspect } = require('util'); + * + * const obj = { a: 1 }; + * const obj2 = { b: 2 }; + * const weakSet = new WeakSet([obj, obj2]); + * + * console.log(inspect(weakSet, { showHidden: true })); + * // WeakSet { { a: 1 }, { b: 2 } } + * ``` + * + * The `sorted` option ensures that an object's property insertion order does not + * impact the result of `util.inspect()`. + * + * ```js + * const { inspect } = require('util'); + * const assert = require('assert'); + * + * const o1 = { + * b: [2, 3, 1], + * a: '`a` comes before `b`', + * c: new Set([2, 3, 1]) + * }; + * console.log(inspect(o1, { sorted: true })); + * // { a: '`a` comes before `b`', b: [ 2, 3, 1 ], c: Set(3) { 1, 2, 3 } } + * console.log(inspect(o1, { sorted: (a, b) => b.localeCompare(a) })); + * // { c: Set(3) { 3, 2, 1 }, b: [ 2, 3, 1 ], a: '`a` comes before `b`' } + * + * const o2 = { + * c: new Set([2, 1, 3]), + * a: '`a` comes before `b`', + * b: [2, 3, 1] + * }; + * assert.strict.equal( + * inspect(o1, { sorted: true }), + * inspect(o2, { sorted: true }) + * ); + * ``` + * + * The `numericSeparator` option adds an underscore every three digits to all + * numbers. + * + * ```js + * const { inspect } = require('util'); + * + * const thousand = 1_000; + * const million = 1_000_000; + * const bigNumber = 123_456_789n; + * const bigDecimal = 1_234.123_45; + * + * console.log(thousand, million, bigNumber, bigDecimal); + * // 1_000 1_000_000 123_456_789n 1_234.123_45 + * ``` + * + * `util.inspect()` is a synchronous method intended for debugging. Its maximum + * output length is approximately 128 MB. Inputs that result in longer output will + * be truncated. + * @since v0.3.0 + * @param object Any JavaScript primitive or `Object`. + * @return The representation of `object`. + */ + export function inspect(object: any, showHidden?: boolean, depth?: number | null, color?: boolean): string; + export function inspect(object: any, options?: InspectOptions): string; + export namespace inspect { + let colors: NodeJS.Dict<[number, number]>; + let styles: { + [K in Style]: string; + }; + let defaultOptions: InspectOptions; + /** + * Allows changing inspect settings from the repl. + */ + let replDefaults: InspectOptions; + /** + * That can be used to declare custom inspect functions. + */ + const custom: unique symbol; + } + /** + * Alias for [`Array.isArray()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/isArray). + * + * Returns `true` if the given `object` is an `Array`. Otherwise, returns `false`. + * + * ```js + * const util = require('util'); + * + * util.isArray([]); + * // Returns: true + * util.isArray(new Array()); + * // Returns: true + * util.isArray({}); + * // Returns: false + * ``` + * @since v0.6.0 + * @deprecated Since v4.0.0 - Use `isArray` instead. + */ + export function isArray(object: unknown): object is unknown[]; + /** + * Returns `true` if the given `object` is a `RegExp`. Otherwise, returns `false`. + * + * ```js + * const util = require('util'); + * + * util.isRegExp(/some regexp/); + * // Returns: true + * util.isRegExp(new RegExp('another regexp')); + * // Returns: true + * util.isRegExp({}); + * // Returns: false + * ``` + * @since v0.6.0 + * @deprecated Since v4.0.0 - Deprecated + */ + export function isRegExp(object: unknown): object is RegExp; + /** + * Returns `true` if the given `object` is a `Date`. Otherwise, returns `false`. + * + * ```js + * const util = require('util'); + * + * util.isDate(new Date()); + * // Returns: true + * util.isDate(Date()); + * // false (without 'new' returns a String) + * util.isDate({}); + * // Returns: false + * ``` + * @since v0.6.0 + * @deprecated Since v4.0.0 - Use {@link types.isDate} instead. + */ + export function isDate(object: unknown): object is Date; + /** + * Returns `true` if the given `object` is an `Error`. Otherwise, returns`false`. + * + * ```js + * const util = require('util'); + * + * util.isError(new Error()); + * // Returns: true + * util.isError(new TypeError()); + * // Returns: true + * util.isError({ name: 'Error', message: 'an error occurred' }); + * // Returns: false + * ``` + * + * This method relies on `Object.prototype.toString()` behavior. It is + * possible to obtain an incorrect result when the `object` argument manipulates`@@toStringTag`. + * + * ```js + * const util = require('util'); + * const obj = { name: 'Error', message: 'an error occurred' }; + * + * util.isError(obj); + * // Returns: false + * obj[Symbol.toStringTag] = 'Error'; + * util.isError(obj); + * // Returns: true + * ``` + * @since v0.6.0 + * @deprecated Since v4.0.0 - Use {@link types.isNativeError} instead. + */ + export function isError(object: unknown): object is Error; + /** + * Usage of `util.inherits()` is discouraged. Please use the ES6 `class` and`extends` keywords to get language level inheritance support. Also note + * that the two styles are [semantically incompatible](https://github.com/nodejs/node/issues/4179). + * + * Inherit the prototype methods from one [constructor](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/constructor) into another. The + * prototype of `constructor` will be set to a new object created from`superConstructor`. + * + * This mainly adds some input validation on top of`Object.setPrototypeOf(constructor.prototype, superConstructor.prototype)`. + * As an additional convenience, `superConstructor` will be accessible + * through the `constructor.super_` property. + * + * ```js + * const util = require('util'); + * const EventEmitter = require('events'); + * + * function MyStream() { + * EventEmitter.call(this); + * } + * + * util.inherits(MyStream, EventEmitter); + * + * MyStream.prototype.write = function(data) { + * this.emit('data', data); + * }; + * + * const stream = new MyStream(); + * + * console.log(stream instanceof EventEmitter); // true + * console.log(MyStream.super_ === EventEmitter); // true + * + * stream.on('data', (data) => { + * console.log(`Received data: "${data}"`); + * }); + * stream.write('It works!'); // Received data: "It works!" + * ``` + * + * ES6 example using `class` and `extends`: + * + * ```js + * const EventEmitter = require('events'); + * + * class MyStream extends EventEmitter { + * write(data) { + * this.emit('data', data); + * } + * } + * + * const stream = new MyStream(); + * + * stream.on('data', (data) => { + * console.log(`Received data: "${data}"`); + * }); + * stream.write('With ES6'); + * ``` + * @since v0.3.0 + * @deprecated Legacy: Use ES2015 class syntax and `extends` keyword instead. + */ + export function inherits(constructor: unknown, superConstructor: unknown): void; + export type DebugLoggerFunction = (msg: string, ...param: unknown[]) => void; + export interface DebugLogger extends DebugLoggerFunction { + enabled: boolean; + } + /** + * The `util.debuglog()` method is used to create a function that conditionally + * writes debug messages to `stderr` based on the existence of the `NODE_DEBUG`environment variable. If the `section` name appears within the value of that + * environment variable, then the returned function operates similar to `console.error()`. If not, then the returned function is a no-op. + * + * ```js + * const util = require('util'); + * const debuglog = util.debuglog('foo'); + * + * debuglog('hello from foo [%d]', 123); + * ``` + * + * If this program is run with `NODE_DEBUG=foo` in the environment, then + * it will output something like: + * + * ```console + * FOO 3245: hello from foo [123] + * ``` + * + * where `3245` is the process id. If it is not run with that + * environment variable set, then it will not print anything. + * + * The `section` supports wildcard also: + * + * ```js + * const util = require('util'); + * const debuglog = util.debuglog('foo-bar'); + * + * debuglog('hi there, it\'s foo-bar [%d]', 2333); + * ``` + * + * if it is run with `NODE_DEBUG=foo*` in the environment, then it will output + * something like: + * + * ```console + * FOO-BAR 3257: hi there, it's foo-bar [2333] + * ``` + * + * Multiple comma-separated `section` names may be specified in the `NODE_DEBUG`environment variable: `NODE_DEBUG=fs,net,tls`. + * + * The optional `callback` argument can be used to replace the logging function + * with a different function that doesn't have any initialization or + * unnecessary wrapping. + * + * ```js + * const util = require('util'); + * let debuglog = util.debuglog('internals', (debug) => { + * // Replace with a logging function that optimizes out + * // testing if the section is enabled + * debuglog = debug; + * }); + * ``` + * @since v0.11.3 + * @param section A string identifying the portion of the application for which the `debuglog` function is being created. + * @param callback A callback invoked the first time the logging function is called with a function argument that is a more optimized logging function. + * @return The logging function + */ + export function debuglog(section: string, callback?: (fn: DebugLoggerFunction) => void): DebugLogger; + export const debug: typeof debuglog; + /** + * Returns `true` if the given `object` is a `Boolean`. Otherwise, returns `false`. + * + * ```js + * const util = require('util'); + * + * util.isBoolean(1); + * // Returns: false + * util.isBoolean(0); + * // Returns: false + * util.isBoolean(false); + * // Returns: true + * ``` + * @since v0.11.5 + * @deprecated Since v4.0.0 - Use `typeof value === 'boolean'` instead. + */ + export function isBoolean(object: unknown): object is boolean; + /** + * Returns `true` if the given `object` is a `Buffer`. Otherwise, returns `false`. + * + * ```js + * const util = require('util'); + * + * util.isBuffer({ length: 0 }); + * // Returns: false + * util.isBuffer([]); + * // Returns: false + * util.isBuffer(Buffer.from('hello world')); + * // Returns: true + * ``` + * @since v0.11.5 + * @deprecated Since v4.0.0 - Use `isBuffer` instead. + */ + export function isBuffer(object: unknown): object is Buffer; + /** + * Returns `true` if the given `object` is a `Function`. Otherwise, returns`false`. + * + * ```js + * const util = require('util'); + * + * function Foo() {} + * const Bar = () => {}; + * + * util.isFunction({}); + * // Returns: false + * util.isFunction(Foo); + * // Returns: true + * util.isFunction(Bar); + * // Returns: true + * ``` + * @since v0.11.5 + * @deprecated Since v4.0.0 - Use `typeof value === 'function'` instead. + */ + export function isFunction(object: unknown): boolean; + /** + * Returns `true` if the given `object` is strictly `null`. Otherwise, returns`false`. + * + * ```js + * const util = require('util'); + * + * util.isNull(0); + * // Returns: false + * util.isNull(undefined); + * // Returns: false + * util.isNull(null); + * // Returns: true + * ``` + * @since v0.11.5 + * @deprecated Since v4.0.0 - Use `value === null` instead. + */ + export function isNull(object: unknown): object is null; + /** + * Returns `true` if the given `object` is `null` or `undefined`. Otherwise, + * returns `false`. + * + * ```js + * const util = require('util'); + * + * util.isNullOrUndefined(0); + * // Returns: false + * util.isNullOrUndefined(undefined); + * // Returns: true + * util.isNullOrUndefined(null); + * // Returns: true + * ``` + * @since v0.11.5 + * @deprecated Since v4.0.0 - Use `value === undefined || value === null` instead. + */ + export function isNullOrUndefined(object: unknown): object is null | undefined; + /** + * Returns `true` if the given `object` is a `Number`. Otherwise, returns `false`. + * + * ```js + * const util = require('util'); + * + * util.isNumber(false); + * // Returns: false + * util.isNumber(Infinity); + * // Returns: true + * util.isNumber(0); + * // Returns: true + * util.isNumber(NaN); + * // Returns: true + * ``` + * @since v0.11.5 + * @deprecated Since v4.0.0 - Use `typeof value === 'number'` instead. + */ + export function isNumber(object: unknown): object is number; + /** + * Returns `true` if the given `object` is strictly an `Object`**and** not a`Function` (even though functions are objects in JavaScript). + * Otherwise, returns `false`. + * + * ```js + * const util = require('util'); + * + * util.isObject(5); + * // Returns: false + * util.isObject(null); + * // Returns: false + * util.isObject({}); + * // Returns: true + * util.isObject(() => {}); + * // Returns: false + * ``` + * @since v0.11.5 + * @deprecated Since v4.0.0 - Deprecated: Use `value !== null && typeof value === 'object'` instead. + */ + export function isObject(object: unknown): boolean; + /** + * Returns `true` if the given `object` is a primitive type. Otherwise, returns`false`. + * + * ```js + * const util = require('util'); + * + * util.isPrimitive(5); + * // Returns: true + * util.isPrimitive('foo'); + * // Returns: true + * util.isPrimitive(false); + * // Returns: true + * util.isPrimitive(null); + * // Returns: true + * util.isPrimitive(undefined); + * // Returns: true + * util.isPrimitive({}); + * // Returns: false + * util.isPrimitive(() => {}); + * // Returns: false + * util.isPrimitive(/^$/); + * // Returns: false + * util.isPrimitive(new Date()); + * // Returns: false + * ``` + * @since v0.11.5 + * @deprecated Since v4.0.0 - Use `(typeof value !== 'object' && typeof value !== 'function') || value === null` instead. + */ + export function isPrimitive(object: unknown): boolean; + /** + * Returns `true` if the given `object` is a `string`. Otherwise, returns `false`. + * + * ```js + * const util = require('util'); + * + * util.isString(''); + * // Returns: true + * util.isString('foo'); + * // Returns: true + * util.isString(String('foo')); + * // Returns: true + * util.isString(5); + * // Returns: false + * ``` + * @since v0.11.5 + * @deprecated Since v4.0.0 - Use `typeof value === 'string'` instead. + */ + export function isString(object: unknown): object is string; + /** + * Returns `true` if the given `object` is a `Symbol`. Otherwise, returns `false`. + * + * ```js + * const util = require('util'); + * + * util.isSymbol(5); + * // Returns: false + * util.isSymbol('foo'); + * // Returns: false + * util.isSymbol(Symbol('foo')); + * // Returns: true + * ``` + * @since v0.11.5 + * @deprecated Since v4.0.0 - Use `typeof value === 'symbol'` instead. + */ + export function isSymbol(object: unknown): object is symbol; + /** + * Returns `true` if the given `object` is `undefined`. Otherwise, returns `false`. + * + * ```js + * const util = require('util'); + * + * const foo = undefined; + * util.isUndefined(5); + * // Returns: false + * util.isUndefined(foo); + * // Returns: true + * util.isUndefined(null); + * // Returns: false + * ``` + * @since v0.11.5 + * @deprecated Since v4.0.0 - Use `value === undefined` instead. + */ + export function isUndefined(object: unknown): object is undefined; + /** + * The `util.deprecate()` method wraps `fn` (which may be a function or class) in + * such a way that it is marked as deprecated. + * + * ```js + * const util = require('util'); + * + * exports.obsoleteFunction = util.deprecate(() => { + * // Do something here. + * }, 'obsoleteFunction() is deprecated. Use newShinyFunction() instead.'); + * ``` + * + * When called, `util.deprecate()` will return a function that will emit a`DeprecationWarning` using the `'warning'` event. The warning will + * be emitted and printed to `stderr` the first time the returned function is + * called. After the warning is emitted, the wrapped function is called without + * emitting a warning. + * + * If the same optional `code` is supplied in multiple calls to `util.deprecate()`, + * the warning will be emitted only once for that `code`. + * + * ```js + * const util = require('util'); + * + * const fn1 = util.deprecate(someFunction, someMessage, 'DEP0001'); + * const fn2 = util.deprecate(someOtherFunction, someOtherMessage, 'DEP0001'); + * fn1(); // Emits a deprecation warning with code DEP0001 + * fn2(); // Does not emit a deprecation warning because it has the same code + * ``` + * + * If either the `--no-deprecation` or `--no-warnings` command-line flags are + * used, or if the `process.noDeprecation` property is set to `true`_prior_ to + * the first deprecation warning, the `util.deprecate()` method does nothing. + * + * If the `--trace-deprecation` or `--trace-warnings` command-line flags are set, + * or the `process.traceDeprecation` property is set to `true`, a warning and a + * stack trace are printed to `stderr` the first time the deprecated function is + * called. + * + * If the `--throw-deprecation` command-line flag is set, or the`process.throwDeprecation` property is set to `true`, then an exception will be + * thrown when the deprecated function is called. + * + * The `--throw-deprecation` command-line flag and `process.throwDeprecation`property take precedence over `--trace-deprecation` and`process.traceDeprecation`. + * @since v0.8.0 + * @param fn The function that is being deprecated. + * @param msg A warning message to display when the deprecated function is invoked. + * @param code A deprecation code. See the `list of deprecated APIs` for a list of codes. + * @return The deprecated function wrapped to emit a warning. + */ + export function deprecate(fn: T, msg: string, code?: string): T; + /** + * Returns `true` if there is deep strict equality between `val1` and `val2`. + * Otherwise, returns `false`. + * + * See `assert.deepStrictEqual()` for more information about deep strict + * equality. + * @since v9.0.0 + */ + export function isDeepStrictEqual(val1: unknown, val2: unknown): boolean; + /** + * Returns `str` with any ANSI escape codes removed. + * + * ```js + * console.log(util.stripVTControlCharacters('\u001B[4mvalue\u001B[0m')); + * // Prints "value" + * ``` + * @since v16.11.0 + */ + export function stripVTControlCharacters(str: string): string; + /** + * Takes an `async` function (or a function that returns a `Promise`) and returns a + * function following the error-first callback style, i.e. taking + * an `(err, value) => ...` callback as the last argument. In the callback, the + * first argument will be the rejection reason (or `null` if the `Promise`resolved), and the second argument will be the resolved value. + * + * ```js + * const util = require('util'); + * + * async function fn() { + * return 'hello world'; + * } + * const callbackFunction = util.callbackify(fn); + * + * callbackFunction((err, ret) => { + * if (err) throw err; + * console.log(ret); + * }); + * ``` + * + * Will print: + * + * ```text + * hello world + * ``` + * + * The callback is executed asynchronously, and will have a limited stack trace. + * If the callback throws, the process will emit an `'uncaughtException'` event, and if not handled will exit. + * + * Since `null` has a special meaning as the first argument to a callback, if a + * wrapped function rejects a `Promise` with a falsy value as a reason, the value + * is wrapped in an `Error` with the original value stored in a field named`reason`. + * + * ```js + * function fn() { + * return Promise.reject(null); + * } + * const callbackFunction = util.callbackify(fn); + * + * callbackFunction((err, ret) => { + * // When the Promise was rejected with `null` it is wrapped with an Error and + * // the original value is stored in `reason`. + * err && Object.hasOwn(err, 'reason') && err.reason === null; // true + * }); + * ``` + * @since v8.2.0 + * @param original An `async` function + * @return a callback style function + */ + export function callbackify(fn: () => Promise): (callback: (err: NodeJS.ErrnoException) => void) => void; + export function callbackify(fn: () => Promise): (callback: (err: NodeJS.ErrnoException, result: TResult) => void) => void; + export function callbackify(fn: (arg1: T1) => Promise): (arg1: T1, callback: (err: NodeJS.ErrnoException) => void) => void; + export function callbackify(fn: (arg1: T1) => Promise): (arg1: T1, callback: (err: NodeJS.ErrnoException, result: TResult) => void) => void; + export function callbackify(fn: (arg1: T1, arg2: T2) => Promise): (arg1: T1, arg2: T2, callback: (err: NodeJS.ErrnoException) => void) => void; + export function callbackify(fn: (arg1: T1, arg2: T2) => Promise): (arg1: T1, arg2: T2, callback: (err: NodeJS.ErrnoException | null, result: TResult) => void) => void; + export function callbackify(fn: (arg1: T1, arg2: T2, arg3: T3) => Promise): (arg1: T1, arg2: T2, arg3: T3, callback: (err: NodeJS.ErrnoException) => void) => void; + export function callbackify( + fn: (arg1: T1, arg2: T2, arg3: T3) => Promise + ): (arg1: T1, arg2: T2, arg3: T3, callback: (err: NodeJS.ErrnoException | null, result: TResult) => void) => void; + export function callbackify( + fn: (arg1: T1, arg2: T2, arg3: T3, arg4: T4) => Promise + ): (arg1: T1, arg2: T2, arg3: T3, arg4: T4, callback: (err: NodeJS.ErrnoException) => void) => void; + export function callbackify( + fn: (arg1: T1, arg2: T2, arg3: T3, arg4: T4) => Promise + ): (arg1: T1, arg2: T2, arg3: T3, arg4: T4, callback: (err: NodeJS.ErrnoException | null, result: TResult) => void) => void; + export function callbackify( + fn: (arg1: T1, arg2: T2, arg3: T3, arg4: T4, arg5: T5) => Promise + ): (arg1: T1, arg2: T2, arg3: T3, arg4: T4, arg5: T5, callback: (err: NodeJS.ErrnoException) => void) => void; + export function callbackify( + fn: (arg1: T1, arg2: T2, arg3: T3, arg4: T4, arg5: T5) => Promise + ): (arg1: T1, arg2: T2, arg3: T3, arg4: T4, arg5: T5, callback: (err: NodeJS.ErrnoException | null, result: TResult) => void) => void; + export function callbackify( + fn: (arg1: T1, arg2: T2, arg3: T3, arg4: T4, arg5: T5, arg6: T6) => Promise + ): (arg1: T1, arg2: T2, arg3: T3, arg4: T4, arg5: T5, arg6: T6, callback: (err: NodeJS.ErrnoException) => void) => void; + export function callbackify( + fn: (arg1: T1, arg2: T2, arg3: T3, arg4: T4, arg5: T5, arg6: T6) => Promise + ): (arg1: T1, arg2: T2, arg3: T3, arg4: T4, arg5: T5, arg6: T6, callback: (err: NodeJS.ErrnoException | null, result: TResult) => void) => void; + export interface CustomPromisifyLegacy extends Function { + __promisify__: TCustom; + } + export interface CustomPromisifySymbol extends Function { + [promisify.custom]: TCustom; + } + export type CustomPromisify = CustomPromisifySymbol | CustomPromisifyLegacy; + /** + * Takes a function following the common error-first callback style, i.e. taking + * an `(err, value) => ...` callback as the last argument, and returns a version + * that returns promises. + * + * ```js + * const util = require('util'); + * const fs = require('fs'); + * + * const stat = util.promisify(fs.stat); + * stat('.').then((stats) => { + * // Do something with `stats` + * }).catch((error) => { + * // Handle the error. + * }); + * ``` + * + * Or, equivalently using `async function`s: + * + * ```js + * const util = require('util'); + * const fs = require('fs'); + * + * const stat = util.promisify(fs.stat); + * + * async function callStat() { + * const stats = await stat('.'); + * console.log(`This directory is owned by ${stats.uid}`); + * } + * ``` + * + * If there is an `original[util.promisify.custom]` property present, `promisify`will return its value, see `Custom promisified functions`. + * + * `promisify()` assumes that `original` is a function taking a callback as its + * final argument in all cases. If `original` is not a function, `promisify()`will throw an error. If `original` is a function but its last argument is not + * an error-first callback, it will still be passed an error-first + * callback as its last argument. + * + * Using `promisify()` on class methods or other methods that use `this` may not + * work as expected unless handled specially: + * + * ```js + * const util = require('util'); + * + * class Foo { + * constructor() { + * this.a = 42; + * } + * + * bar(callback) { + * callback(null, this.a); + * } + * } + * + * const foo = new Foo(); + * + * const naiveBar = util.promisify(foo.bar); + * // TypeError: Cannot read property 'a' of undefined + * // naiveBar().then(a => console.log(a)); + * + * naiveBar.call(foo).then((a) => console.log(a)); // '42' + * + * const bindBar = naiveBar.bind(foo); + * bindBar().then((a) => console.log(a)); // '42' + * ``` + * @since v8.0.0 + */ + export function promisify(fn: CustomPromisify): TCustom; + export function promisify(fn: (callback: (err: any, result: TResult) => void) => void): () => Promise; + export function promisify(fn: (callback: (err?: any) => void) => void): () => Promise; + export function promisify(fn: (arg1: T1, callback: (err: any, result: TResult) => void) => void): (arg1: T1) => Promise; + export function promisify(fn: (arg1: T1, callback: (err?: any) => void) => void): (arg1: T1) => Promise; + export function promisify(fn: (arg1: T1, arg2: T2, callback: (err: any, result: TResult) => void) => void): (arg1: T1, arg2: T2) => Promise; + export function promisify(fn: (arg1: T1, arg2: T2, callback: (err?: any) => void) => void): (arg1: T1, arg2: T2) => Promise; + export function promisify(fn: (arg1: T1, arg2: T2, arg3: T3, callback: (err: any, result: TResult) => void) => void): (arg1: T1, arg2: T2, arg3: T3) => Promise; + export function promisify(fn: (arg1: T1, arg2: T2, arg3: T3, callback: (err?: any) => void) => void): (arg1: T1, arg2: T2, arg3: T3) => Promise; + export function promisify( + fn: (arg1: T1, arg2: T2, arg3: T3, arg4: T4, callback: (err: any, result: TResult) => void) => void + ): (arg1: T1, arg2: T2, arg3: T3, arg4: T4) => Promise; + export function promisify(fn: (arg1: T1, arg2: T2, arg3: T3, arg4: T4, callback: (err?: any) => void) => void): (arg1: T1, arg2: T2, arg3: T3, arg4: T4) => Promise; + export function promisify( + fn: (arg1: T1, arg2: T2, arg3: T3, arg4: T4, arg5: T5, callback: (err: any, result: TResult) => void) => void + ): (arg1: T1, arg2: T2, arg3: T3, arg4: T4, arg5: T5) => Promise; + export function promisify( + fn: (arg1: T1, arg2: T2, arg3: T3, arg4: T4, arg5: T5, callback: (err?: any) => void) => void + ): (arg1: T1, arg2: T2, arg3: T3, arg4: T4, arg5: T5) => Promise; + export function promisify(fn: Function): Function; + export namespace promisify { + /** + * That can be used to declare custom promisified variants of functions. + */ + const custom: unique symbol; + } + /** + * An implementation of the [WHATWG Encoding Standard](https://encoding.spec.whatwg.org/) `TextDecoder` API. + * + * ```js + * const decoder = new TextDecoder(); + * const u8arr = new Uint8Array([72, 101, 108, 108, 111]); + * console.log(decoder.decode(u8arr)); // Hello + * ``` + * @since v8.3.0 + */ + export class TextDecoder { + /** + * The encoding supported by the `TextDecoder` instance. + */ + readonly encoding: string; + /** + * The value will be `true` if decoding errors result in a `TypeError` being + * thrown. + */ + readonly fatal: boolean; + /** + * The value will be `true` if the decoding result will include the byte order + * mark. + */ + readonly ignoreBOM: boolean; + constructor( + encoding?: string, + options?: { + fatal?: boolean | undefined; + ignoreBOM?: boolean | undefined; + } + ); + /** + * Decodes the `input` and returns a string. If `options.stream` is `true`, any + * incomplete byte sequences occurring at the end of the `input` are buffered + * internally and emitted after the next call to `textDecoder.decode()`. + * + * If `textDecoder.fatal` is `true`, decoding errors that occur will result in a`TypeError` being thrown. + * @param input An `ArrayBuffer`, `DataView` or `TypedArray` instance containing the encoded data. + */ + decode( + input?: NodeJS.ArrayBufferView | ArrayBuffer | null, + options?: { + stream?: boolean | undefined; + } + ): string; + } + export interface EncodeIntoResult { + /** + * The read Unicode code units of input. + */ + read: number; + /** + * The written UTF-8 bytes of output. + */ + written: number; + } + export { types }; + /** + * An implementation of the [WHATWG Encoding Standard](https://encoding.spec.whatwg.org/) `TextEncoder` API. All + * instances of `TextEncoder` only support UTF-8 encoding. + * + * ```js + * const encoder = new TextEncoder(); + * const uint8array = encoder.encode('this is some data'); + * ``` + * + * The `TextEncoder` class is also available on the global object. + * @since v8.3.0 + */ + export class TextEncoder { + /** + * The encoding supported by the `TextEncoder` instance. Always set to `'utf-8'`. + */ + readonly encoding: string; + /** + * UTF-8 encodes the `input` string and returns a `Uint8Array` containing the + * encoded bytes. + * @param [input='an empty string'] The text to encode. + */ + encode(input?: string): Uint8Array; + /** + * UTF-8 encodes the `src` string to the `dest` Uint8Array and returns an object + * containing the read Unicode code units and written UTF-8 bytes. + * + * ```js + * const encoder = new TextEncoder(); + * const src = 'this is some data'; + * const dest = new Uint8Array(10); + * const { read, written } = encoder.encodeInto(src, dest); + * ``` + * @param src The text to encode. + * @param dest The array to hold the encode result. + */ + encodeInto(src: string, dest: Uint8Array): EncodeIntoResult; + } +} +declare module 'util/types' { + export * from 'util/types'; +} +declare module 'util/types' { + import { KeyObject, webcrypto } from 'node:crypto'; + /** + * Returns `true` if the value is a built-in [`ArrayBuffer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer) or + * [`SharedArrayBuffer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/SharedArrayBuffer) instance. + * + * See also `util.types.isArrayBuffer()` and `util.types.isSharedArrayBuffer()`. + * + * ```js + * util.types.isAnyArrayBuffer(new ArrayBuffer()); // Returns true + * util.types.isAnyArrayBuffer(new SharedArrayBuffer()); // Returns true + * ``` + * @since v10.0.0 + */ + function isAnyArrayBuffer(object: unknown): object is ArrayBufferLike; + /** + * Returns `true` if the value is an `arguments` object. + * + * ```js + * function foo() { + * util.types.isArgumentsObject(arguments); // Returns true + * } + * ``` + * @since v10.0.0 + */ + function isArgumentsObject(object: unknown): object is IArguments; + /** + * Returns `true` if the value is a built-in [`ArrayBuffer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer) instance. + * This does _not_ include [`SharedArrayBuffer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/SharedArrayBuffer) instances. Usually, it is + * desirable to test for both; See `util.types.isAnyArrayBuffer()` for that. + * + * ```js + * util.types.isArrayBuffer(new ArrayBuffer()); // Returns true + * util.types.isArrayBuffer(new SharedArrayBuffer()); // Returns false + * ``` + * @since v10.0.0 + */ + function isArrayBuffer(object: unknown): object is ArrayBuffer; + /** + * Returns `true` if the value is an instance of one of the [`ArrayBuffer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer) views, such as typed + * array objects or [`DataView`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView). Equivalent to + * [`ArrayBuffer.isView()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer/isView). + * + * ```js + * util.types.isArrayBufferView(new Int8Array()); // true + * util.types.isArrayBufferView(Buffer.from('hello world')); // true + * util.types.isArrayBufferView(new DataView(new ArrayBuffer(16))); // true + * util.types.isArrayBufferView(new ArrayBuffer()); // false + * ``` + * @since v10.0.0 + */ + function isArrayBufferView(object: unknown): object is NodeJS.ArrayBufferView; + /** + * Returns `true` if the value is an [async function](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/async_function). + * This only reports back what the JavaScript engine is seeing; + * in particular, the return value may not match the original source code if + * a transpilation tool was used. + * + * ```js + * util.types.isAsyncFunction(function foo() {}); // Returns false + * util.types.isAsyncFunction(async function foo() {}); // Returns true + * ``` + * @since v10.0.0 + */ + function isAsyncFunction(object: unknown): boolean; + /** + * Returns `true` if the value is a `BigInt64Array` instance. + * + * ```js + * util.types.isBigInt64Array(new BigInt64Array()); // Returns true + * util.types.isBigInt64Array(new BigUint64Array()); // Returns false + * ``` + * @since v10.0.0 + */ + function isBigInt64Array(value: unknown): value is BigInt64Array; + /** + * Returns `true` if the value is a `BigUint64Array` instance. + * + * ```js + * util.types.isBigUint64Array(new BigInt64Array()); // Returns false + * util.types.isBigUint64Array(new BigUint64Array()); // Returns true + * ``` + * @since v10.0.0 + */ + function isBigUint64Array(value: unknown): value is BigUint64Array; + /** + * Returns `true` if the value is a boolean object, e.g. created + * by `new Boolean()`. + * + * ```js + * util.types.isBooleanObject(false); // Returns false + * util.types.isBooleanObject(true); // Returns false + * util.types.isBooleanObject(new Boolean(false)); // Returns true + * util.types.isBooleanObject(new Boolean(true)); // Returns true + * util.types.isBooleanObject(Boolean(false)); // Returns false + * util.types.isBooleanObject(Boolean(true)); // Returns false + * ``` + * @since v10.0.0 + */ + function isBooleanObject(object: unknown): object is Boolean; + /** + * Returns `true` if the value is any boxed primitive object, e.g. created + * by `new Boolean()`, `new String()` or `Object(Symbol())`. + * + * For example: + * + * ```js + * util.types.isBoxedPrimitive(false); // Returns false + * util.types.isBoxedPrimitive(new Boolean(false)); // Returns true + * util.types.isBoxedPrimitive(Symbol('foo')); // Returns false + * util.types.isBoxedPrimitive(Object(Symbol('foo'))); // Returns true + * util.types.isBoxedPrimitive(Object(BigInt(5))); // Returns true + * ``` + * @since v10.11.0 + */ + function isBoxedPrimitive(object: unknown): object is String | Number | BigInt | Boolean | Symbol; + /** + * Returns `true` if the value is a built-in [`DataView`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView) instance. + * + * ```js + * const ab = new ArrayBuffer(20); + * util.types.isDataView(new DataView(ab)); // Returns true + * util.types.isDataView(new Float64Array()); // Returns false + * ``` + * + * See also [`ArrayBuffer.isView()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer/isView). + * @since v10.0.0 + */ + function isDataView(object: unknown): object is DataView; + /** + * Returns `true` if the value is a built-in [`Date`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date) instance. + * + * ```js + * util.types.isDate(new Date()); // Returns true + * ``` + * @since v10.0.0 + */ + function isDate(object: unknown): object is Date; + /** + * Returns `true` if the value is a native `External` value. + * + * A native `External` value is a special type of object that contains a + * raw C++ pointer (`void*`) for access from native code, and has no other + * properties. Such objects are created either by Node.js internals or native + * addons. In JavaScript, they are [frozen](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/freeze) objects with a`null` prototype. + * + * ```c + * #include + * #include + * napi_value result; + * static napi_value MyNapi(napi_env env, napi_callback_info info) { + * int* raw = (int*) malloc(1024); + * napi_status status = napi_create_external(env, (void*) raw, NULL, NULL, &result); + * if (status != napi_ok) { + * napi_throw_error(env, NULL, "napi_create_external failed"); + * return NULL; + * } + * return result; + * } + * ... + * DECLARE_NAPI_PROPERTY("myNapi", MyNapi) + * ... + * ``` + * + * ```js + * const native = require('napi_addon.node'); + * const data = native.myNapi(); + * util.types.isExternal(data); // returns true + * util.types.isExternal(0); // returns false + * util.types.isExternal(new String('foo')); // returns false + * ``` + * + * For further information on `napi_create_external`, refer to `napi_create_external()`. + * @since v10.0.0 + */ + function isExternal(object: unknown): boolean; + /** + * Returns `true` if the value is a built-in [`Float32Array`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Float32Array) instance. + * + * ```js + * util.types.isFloat32Array(new ArrayBuffer()); // Returns false + * util.types.isFloat32Array(new Float32Array()); // Returns true + * util.types.isFloat32Array(new Float64Array()); // Returns false + * ``` + * @since v10.0.0 + */ + function isFloat32Array(object: unknown): object is Float32Array; + /** + * Returns `true` if the value is a built-in [`Float64Array`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Float64Array) instance. + * + * ```js + * util.types.isFloat64Array(new ArrayBuffer()); // Returns false + * util.types.isFloat64Array(new Uint8Array()); // Returns false + * util.types.isFloat64Array(new Float64Array()); // Returns true + * ``` + * @since v10.0.0 + */ + function isFloat64Array(object: unknown): object is Float64Array; + /** + * Returns `true` if the value is a generator function. + * This only reports back what the JavaScript engine is seeing; + * in particular, the return value may not match the original source code if + * a transpilation tool was used. + * + * ```js + * util.types.isGeneratorFunction(function foo() {}); // Returns false + * util.types.isGeneratorFunction(function* foo() {}); // Returns true + * ``` + * @since v10.0.0 + */ + function isGeneratorFunction(object: unknown): object is GeneratorFunction; + /** + * Returns `true` if the value is a generator object as returned from a + * built-in generator function. + * This only reports back what the JavaScript engine is seeing; + * in particular, the return value may not match the original source code if + * a transpilation tool was used. + * + * ```js + * function* foo() {} + * const generator = foo(); + * util.types.isGeneratorObject(generator); // Returns true + * ``` + * @since v10.0.0 + */ + function isGeneratorObject(object: unknown): object is Generator; + /** + * Returns `true` if the value is a built-in [`Int8Array`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Int8Array) instance. + * + * ```js + * util.types.isInt8Array(new ArrayBuffer()); // Returns false + * util.types.isInt8Array(new Int8Array()); // Returns true + * util.types.isInt8Array(new Float64Array()); // Returns false + * ``` + * @since v10.0.0 + */ + function isInt8Array(object: unknown): object is Int8Array; + /** + * Returns `true` if the value is a built-in [`Int16Array`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Int16Array) instance. + * + * ```js + * util.types.isInt16Array(new ArrayBuffer()); // Returns false + * util.types.isInt16Array(new Int16Array()); // Returns true + * util.types.isInt16Array(new Float64Array()); // Returns false + * ``` + * @since v10.0.0 + */ + function isInt16Array(object: unknown): object is Int16Array; + /** + * Returns `true` if the value is a built-in [`Int32Array`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Int32Array) instance. + * + * ```js + * util.types.isInt32Array(new ArrayBuffer()); // Returns false + * util.types.isInt32Array(new Int32Array()); // Returns true + * util.types.isInt32Array(new Float64Array()); // Returns false + * ``` + * @since v10.0.0 + */ + function isInt32Array(object: unknown): object is Int32Array; + /** + * Returns `true` if the value is a built-in [`Map`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map) instance. + * + * ```js + * util.types.isMap(new Map()); // Returns true + * ``` + * @since v10.0.0 + */ + function isMap(object: T | {}): object is T extends ReadonlyMap ? (unknown extends T ? never : ReadonlyMap) : Map; + /** + * Returns `true` if the value is an iterator returned for a built-in [`Map`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map) instance. + * + * ```js + * const map = new Map(); + * util.types.isMapIterator(map.keys()); // Returns true + * util.types.isMapIterator(map.values()); // Returns true + * util.types.isMapIterator(map.entries()); // Returns true + * util.types.isMapIterator(map[Symbol.iterator]()); // Returns true + * ``` + * @since v10.0.0 + */ + function isMapIterator(object: unknown): boolean; + /** + * Returns `true` if the value is an instance of a [Module Namespace Object](https://tc39.github.io/ecma262/#sec-module-namespace-exotic-objects). + * + * ```js + * import * as ns from './a.js'; + * + * util.types.isModuleNamespaceObject(ns); // Returns true + * ``` + * @since v10.0.0 + */ + function isModuleNamespaceObject(value: unknown): boolean; + /** + * Returns `true` if the value is an instance of a built-in `Error` type. + * + * ```js + * util.types.isNativeError(new Error()); // Returns true + * util.types.isNativeError(new TypeError()); // Returns true + * util.types.isNativeError(new RangeError()); // Returns true + * ``` + * @since v10.0.0 + */ + function isNativeError(object: unknown): object is Error; + /** + * Returns `true` if the value is a number object, e.g. created + * by `new Number()`. + * + * ```js + * util.types.isNumberObject(0); // Returns false + * util.types.isNumberObject(new Number(0)); // Returns true + * ``` + * @since v10.0.0 + */ + function isNumberObject(object: unknown): object is Number; + /** + * Returns `true` if the value is a built-in [`Promise`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise). + * + * ```js + * util.types.isPromise(Promise.resolve(42)); // Returns true + * ``` + * @since v10.0.0 + */ + function isPromise(object: unknown): object is Promise; + /** + * Returns `true` if the value is a [`Proxy`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Proxy) instance. + * + * ```js + * const target = {}; + * const proxy = new Proxy(target, {}); + * util.types.isProxy(target); // Returns false + * util.types.isProxy(proxy); // Returns true + * ``` + * @since v10.0.0 + */ + function isProxy(object: unknown): boolean; + /** + * Returns `true` if the value is a regular expression object. + * + * ```js + * util.types.isRegExp(/abc/); // Returns true + * util.types.isRegExp(new RegExp('abc')); // Returns true + * ``` + * @since v10.0.0 + */ + function isRegExp(object: unknown): object is RegExp; + /** + * Returns `true` if the value is a built-in [`Set`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Set) instance. + * + * ```js + * util.types.isSet(new Set()); // Returns true + * ``` + * @since v10.0.0 + */ + function isSet(object: T | {}): object is T extends ReadonlySet ? (unknown extends T ? never : ReadonlySet) : Set; + /** + * Returns `true` if the value is an iterator returned for a built-in [`Set`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Set) instance. + * + * ```js + * const set = new Set(); + * util.types.isSetIterator(set.keys()); // Returns true + * util.types.isSetIterator(set.values()); // Returns true + * util.types.isSetIterator(set.entries()); // Returns true + * util.types.isSetIterator(set[Symbol.iterator]()); // Returns true + * ``` + * @since v10.0.0 + */ + function isSetIterator(object: unknown): boolean; + /** + * Returns `true` if the value is a built-in [`SharedArrayBuffer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/SharedArrayBuffer) instance. + * This does _not_ include [`ArrayBuffer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer) instances. Usually, it is + * desirable to test for both; See `util.types.isAnyArrayBuffer()` for that. + * + * ```js + * util.types.isSharedArrayBuffer(new ArrayBuffer()); // Returns false + * util.types.isSharedArrayBuffer(new SharedArrayBuffer()); // Returns true + * ``` + * @since v10.0.0 + */ + function isSharedArrayBuffer(object: unknown): object is SharedArrayBuffer; + /** + * Returns `true` if the value is a string object, e.g. created + * by `new String()`. + * + * ```js + * util.types.isStringObject('foo'); // Returns false + * util.types.isStringObject(new String('foo')); // Returns true + * ``` + * @since v10.0.0 + */ + function isStringObject(object: unknown): object is String; + /** + * Returns `true` if the value is a symbol object, created + * by calling `Object()` on a `Symbol` primitive. + * + * ```js + * const symbol = Symbol('foo'); + * util.types.isSymbolObject(symbol); // Returns false + * util.types.isSymbolObject(Object(symbol)); // Returns true + * ``` + * @since v10.0.0 + */ + function isSymbolObject(object: unknown): object is Symbol; + /** + * Returns `true` if the value is a built-in [`TypedArray`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray) instance. + * + * ```js + * util.types.isTypedArray(new ArrayBuffer()); // Returns false + * util.types.isTypedArray(new Uint8Array()); // Returns true + * util.types.isTypedArray(new Float64Array()); // Returns true + * ``` + * + * See also [`ArrayBuffer.isView()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer/isView). + * @since v10.0.0 + */ + function isTypedArray(object: unknown): object is NodeJS.TypedArray; + /** + * Returns `true` if the value is a built-in [`Uint8Array`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Uint8Array) instance. + * + * ```js + * util.types.isUint8Array(new ArrayBuffer()); // Returns false + * util.types.isUint8Array(new Uint8Array()); // Returns true + * util.types.isUint8Array(new Float64Array()); // Returns false + * ``` + * @since v10.0.0 + */ + function isUint8Array(object: unknown): object is Uint8Array; + /** + * Returns `true` if the value is a built-in [`Uint8ClampedArray`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Uint8ClampedArray) instance. + * + * ```js + * util.types.isUint8ClampedArray(new ArrayBuffer()); // Returns false + * util.types.isUint8ClampedArray(new Uint8ClampedArray()); // Returns true + * util.types.isUint8ClampedArray(new Float64Array()); // Returns false + * ``` + * @since v10.0.0 + */ + function isUint8ClampedArray(object: unknown): object is Uint8ClampedArray; + /** + * Returns `true` if the value is a built-in [`Uint16Array`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Uint16Array) instance. + * + * ```js + * util.types.isUint16Array(new ArrayBuffer()); // Returns false + * util.types.isUint16Array(new Uint16Array()); // Returns true + * util.types.isUint16Array(new Float64Array()); // Returns false + * ``` + * @since v10.0.0 + */ + function isUint16Array(object: unknown): object is Uint16Array; + /** + * Returns `true` if the value is a built-in [`Uint32Array`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Uint32Array) instance. + * + * ```js + * util.types.isUint32Array(new ArrayBuffer()); // Returns false + * util.types.isUint32Array(new Uint32Array()); // Returns true + * util.types.isUint32Array(new Float64Array()); // Returns false + * ``` + * @since v10.0.0 + */ + function isUint32Array(object: unknown): object is Uint32Array; + /** + * Returns `true` if the value is a built-in [`WeakMap`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/WeakMap) instance. + * + * ```js + * util.types.isWeakMap(new WeakMap()); // Returns true + * ``` + * @since v10.0.0 + */ + function isWeakMap(object: unknown): object is WeakMap; + /** + * Returns `true` if the value is a built-in [`WeakSet`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/WeakSet) instance. + * + * ```js + * util.types.isWeakSet(new WeakSet()); // Returns true + * ``` + * @since v10.0.0 + */ + function isWeakSet(object: unknown): object is WeakSet; + /** + * Returns `true` if `value` is a `KeyObject`, `false` otherwise. + * @since v16.2.0 + */ + function isKeyObject(object: unknown): object is KeyObject; + /** + * Returns `true` if `value` is a `CryptoKey`, `false` otherwise. + * @since v16.2.0 + */ + function isCryptoKey(object: unknown): object is webcrypto.CryptoKey; +} +declare module 'node:util' { + export * from 'util'; +} +declare module 'node:util/types' { + export * from 'util/types'; +} diff --git a/ts-ticket-office-service/node_modules/@types/node/v8.d.ts b/ts-ticket-office-service/node_modules/@types/node/v8.d.ts new file mode 100755 index 000000000..6685dc253 --- /dev/null +++ b/ts-ticket-office-service/node_modules/@types/node/v8.d.ts @@ -0,0 +1,396 @@ +/** + * The `v8` module exposes APIs that are specific to the version of [V8](https://developers.google.com/v8/) built into the Node.js binary. It can be accessed using: + * + * ```js + * const v8 = require('v8'); + * ``` + * @see [source](https://github.com/nodejs/node/blob/v18.0.0/lib/v8.js) + */ +declare module 'v8' { + import { Readable } from 'node:stream'; + interface HeapSpaceInfo { + space_name: string; + space_size: number; + space_used_size: number; + space_available_size: number; + physical_space_size: number; + } + // ** Signifies if the --zap_code_space option is enabled or not. 1 == enabled, 0 == disabled. */ + type DoesZapCodeSpaceFlag = 0 | 1; + interface HeapInfo { + total_heap_size: number; + total_heap_size_executable: number; + total_physical_size: number; + total_available_size: number; + used_heap_size: number; + heap_size_limit: number; + malloced_memory: number; + peak_malloced_memory: number; + does_zap_garbage: DoesZapCodeSpaceFlag; + number_of_native_contexts: number; + number_of_detached_contexts: number; + } + interface HeapCodeStatistics { + code_and_metadata_size: number; + bytecode_and_metadata_size: number; + external_script_source_size: number; + } + /** + * Returns an integer representing a version tag derived from the V8 version, + * command-line flags, and detected CPU features. This is useful for determining + * whether a `vm.Script` `cachedData` buffer is compatible with this instance + * of V8. + * + * ```js + * console.log(v8.cachedDataVersionTag()); // 3947234607 + * // The value returned by v8.cachedDataVersionTag() is derived from the V8 + * // version, command-line flags, and detected CPU features. Test that the value + * // does indeed update when flags are toggled. + * v8.setFlagsFromString('--allow_natives_syntax'); + * console.log(v8.cachedDataVersionTag()); // 183726201 + * ``` + * @since v8.0.0 + */ + function cachedDataVersionTag(): number; + /** + * Returns an object with the following properties: + * + * `does_zap_garbage` is a 0/1 boolean, which signifies whether the`--zap_code_space` option is enabled or not. This makes V8 overwrite heap + * garbage with a bit pattern. The RSS footprint (resident set size) gets bigger + * because it continuously touches all heap pages and that makes them less likely + * to get swapped out by the operating system. + * + * `number_of_native_contexts` The value of native\_context is the number of the + * top-level contexts currently active. Increase of this number over time indicates + * a memory leak. + * + * `number_of_detached_contexts` The value of detached\_context is the number + * of contexts that were detached and not yet garbage collected. This number + * being non-zero indicates a potential memory leak. + * + * ```js + * { + * total_heap_size: 7326976, + * total_heap_size_executable: 4194304, + * total_physical_size: 7326976, + * total_available_size: 1152656, + * used_heap_size: 3476208, + * heap_size_limit: 1535115264, + * malloced_memory: 16384, + * peak_malloced_memory: 1127496, + * does_zap_garbage: 0, + * number_of_native_contexts: 1, + * number_of_detached_contexts: 0 + * } + * ``` + * @since v1.0.0 + */ + function getHeapStatistics(): HeapInfo; + /** + * Returns statistics about the V8 heap spaces, i.e. the segments which make up + * the V8 heap. Neither the ordering of heap spaces, nor the availability of a + * heap space can be guaranteed as the statistics are provided via the + * V8[`GetHeapSpaceStatistics`](https://v8docs.nodesource.com/node-13.2/d5/dda/classv8_1_1_isolate.html#ac673576f24fdc7a33378f8f57e1d13a4) function and may change from one V8 version to the + * next. + * + * The value returned is an array of objects containing the following properties: + * + * ```json + * [ + * { + * "space_name": "new_space", + * "space_size": 2063872, + * "space_used_size": 951112, + * "space_available_size": 80824, + * "physical_space_size": 2063872 + * }, + * { + * "space_name": "old_space", + * "space_size": 3090560, + * "space_used_size": 2493792, + * "space_available_size": 0, + * "physical_space_size": 3090560 + * }, + * { + * "space_name": "code_space", + * "space_size": 1260160, + * "space_used_size": 644256, + * "space_available_size": 960, + * "physical_space_size": 1260160 + * }, + * { + * "space_name": "map_space", + * "space_size": 1094160, + * "space_used_size": 201608, + * "space_available_size": 0, + * "physical_space_size": 1094160 + * }, + * { + * "space_name": "large_object_space", + * "space_size": 0, + * "space_used_size": 0, + * "space_available_size": 1490980608, + * "physical_space_size": 0 + * } + * ] + * ``` + * @since v6.0.0 + */ + function getHeapSpaceStatistics(): HeapSpaceInfo[]; + /** + * The `v8.setFlagsFromString()` method can be used to programmatically set + * V8 command-line flags. This method should be used with care. Changing settings + * after the VM has started may result in unpredictable behavior, including + * crashes and data loss; or it may simply do nothing. + * + * The V8 options available for a version of Node.js may be determined by running`node --v8-options`. + * + * Usage: + * + * ```js + * // Print GC events to stdout for one minute. + * const v8 = require('v8'); + * v8.setFlagsFromString('--trace_gc'); + * setTimeout(() => { v8.setFlagsFromString('--notrace_gc'); }, 60e3); + * ``` + * @since v1.0.0 + */ + function setFlagsFromString(flags: string): void; + /** + * Generates a snapshot of the current V8 heap and returns a Readable + * Stream that may be used to read the JSON serialized representation. + * This JSON stream format is intended to be used with tools such as + * Chrome DevTools. The JSON schema is undocumented and specific to the + * V8 engine. Therefore, the schema may change from one version of V8 to the next. + * + * Creating a heap snapshot requires memory about twice the size of the heap at + * the time the snapshot is created. This results in the risk of OOM killers + * terminating the process. + * + * Generating a snapshot is a synchronous operation which blocks the event loop + * for a duration depending on the heap size. + * + * ```js + * // Print heap snapshot to the console + * const v8 = require('v8'); + * const stream = v8.getHeapSnapshot(); + * stream.pipe(process.stdout); + * ``` + * @since v11.13.0 + * @return A Readable Stream containing the V8 heap snapshot + */ + function getHeapSnapshot(): Readable; + /** + * Generates a snapshot of the current V8 heap and writes it to a JSON + * file. This file is intended to be used with tools such as Chrome + * DevTools. The JSON schema is undocumented and specific to the V8 + * engine, and may change from one version of V8 to the next. + * + * A heap snapshot is specific to a single V8 isolate. When using `worker threads`, a heap snapshot generated from the main thread will + * not contain any information about the workers, and vice versa. + * + * Creating a heap snapshot requires memory about twice the size of the heap at + * the time the snapshot is created. This results in the risk of OOM killers + * terminating the process. + * + * Generating a snapshot is a synchronous operation which blocks the event loop + * for a duration depending on the heap size. + * + * ```js + * const { writeHeapSnapshot } = require('v8'); + * const { + * Worker, + * isMainThread, + * parentPort + * } = require('worker_threads'); + * + * if (isMainThread) { + * const worker = new Worker(__filename); + * + * worker.once('message', (filename) => { + * console.log(`worker heapdump: ${filename}`); + * // Now get a heapdump for the main thread. + * console.log(`main thread heapdump: ${writeHeapSnapshot()}`); + * }); + * + * // Tell the worker to create a heapdump. + * worker.postMessage('heapdump'); + * } else { + * parentPort.once('message', (message) => { + * if (message === 'heapdump') { + * // Generate a heapdump for the worker + * // and return the filename to the parent. + * parentPort.postMessage(writeHeapSnapshot()); + * } + * }); + * } + * ``` + * @since v11.13.0 + * @param filename The file path where the V8 heap snapshot is to be saved. If not specified, a file name with the pattern `'Heap-${yyyymmdd}-${hhmmss}-${pid}-${thread_id}.heapsnapshot'` will be + * generated, where `{pid}` will be the PID of the Node.js process, `{thread_id}` will be `0` when `writeHeapSnapshot()` is called from the main Node.js thread or the id of a + * worker thread. + * @return The filename where the snapshot was saved. + */ + function writeHeapSnapshot(filename?: string): string; + /** + * Returns an object with the following properties: + * + * ```js + * { + * code_and_metadata_size: 212208, + * bytecode_and_metadata_size: 161368, + * external_script_source_size: 1410794 + * } + * ``` + * @since v12.8.0 + */ + function getHeapCodeStatistics(): HeapCodeStatistics; + /** + * @since v8.0.0 + */ + class Serializer { + /** + * Writes out a header, which includes the serialization format version. + */ + writeHeader(): void; + /** + * Serializes a JavaScript value and adds the serialized representation to the + * internal buffer. + * + * This throws an error if `value` cannot be serialized. + */ + writeValue(val: any): boolean; + /** + * Returns the stored internal buffer. This serializer should not be used once + * the buffer is released. Calling this method results in undefined behavior + * if a previous write has failed. + */ + releaseBuffer(): Buffer; + /** + * Marks an `ArrayBuffer` as having its contents transferred out of band. + * Pass the corresponding `ArrayBuffer` in the deserializing context to `deserializer.transferArrayBuffer()`. + * @param id A 32-bit unsigned integer. + * @param arrayBuffer An `ArrayBuffer` instance. + */ + transferArrayBuffer(id: number, arrayBuffer: ArrayBuffer): void; + /** + * Write a raw 32-bit unsigned integer. + * For use inside of a custom `serializer._writeHostObject()`. + */ + writeUint32(value: number): void; + /** + * Write a raw 64-bit unsigned integer, split into high and low 32-bit parts. + * For use inside of a custom `serializer._writeHostObject()`. + */ + writeUint64(hi: number, lo: number): void; + /** + * Write a JS `number` value. + * For use inside of a custom `serializer._writeHostObject()`. + */ + writeDouble(value: number): void; + /** + * Write raw bytes into the serializer’s internal buffer. The deserializer + * will require a way to compute the length of the buffer. + * For use inside of a custom `serializer._writeHostObject()`. + */ + writeRawBytes(buffer: NodeJS.TypedArray): void; + } + /** + * A subclass of `Serializer` that serializes `TypedArray`(in particular `Buffer`) and `DataView` objects as host objects, and only + * stores the part of their underlying `ArrayBuffer`s that they are referring to. + * @since v8.0.0 + */ + class DefaultSerializer extends Serializer {} + /** + * @since v8.0.0 + */ + class Deserializer { + constructor(data: NodeJS.TypedArray); + /** + * Reads and validates a header (including the format version). + * May, for example, reject an invalid or unsupported wire format. In that case, + * an `Error` is thrown. + */ + readHeader(): boolean; + /** + * Deserializes a JavaScript value from the buffer and returns it. + */ + readValue(): any; + /** + * Marks an `ArrayBuffer` as having its contents transferred out of band. + * Pass the corresponding `ArrayBuffer` in the serializing context to `serializer.transferArrayBuffer()` (or return the `id` from `serializer._getSharedArrayBufferId()` in the case of + * `SharedArrayBuffer`s). + * @param id A 32-bit unsigned integer. + * @param arrayBuffer An `ArrayBuffer` instance. + */ + transferArrayBuffer(id: number, arrayBuffer: ArrayBuffer): void; + /** + * Reads the underlying wire format version. Likely mostly to be useful to + * legacy code reading old wire format versions. May not be called before`.readHeader()`. + */ + getWireFormatVersion(): number; + /** + * Read a raw 32-bit unsigned integer and return it. + * For use inside of a custom `deserializer._readHostObject()`. + */ + readUint32(): number; + /** + * Read a raw 64-bit unsigned integer and return it as an array `[hi, lo]`with two 32-bit unsigned integer entries. + * For use inside of a custom `deserializer._readHostObject()`. + */ + readUint64(): [number, number]; + /** + * Read a JS `number` value. + * For use inside of a custom `deserializer._readHostObject()`. + */ + readDouble(): number; + /** + * Read raw bytes from the deserializer’s internal buffer. The `length` parameter + * must correspond to the length of the buffer that was passed to `serializer.writeRawBytes()`. + * For use inside of a custom `deserializer._readHostObject()`. + */ + readRawBytes(length: number): Buffer; + } + /** + * A subclass of `Deserializer` corresponding to the format written by `DefaultSerializer`. + * @since v8.0.0 + */ + class DefaultDeserializer extends Deserializer {} + /** + * Uses a `DefaultSerializer` to serialize `value` into a buffer. + * + * `ERR_BUFFER_TOO_LARGE` will be thrown when trying to + * serialize a huge object which requires buffer + * larger than `buffer.constants.MAX_LENGTH`. + * @since v8.0.0 + */ + function serialize(value: any): Buffer; + /** + * Uses a `DefaultDeserializer` with default options to read a JS value + * from a buffer. + * @since v8.0.0 + * @param buffer A buffer returned by {@link serialize}. + */ + function deserialize(buffer: NodeJS.TypedArray): any; + /** + * The `v8.takeCoverage()` method allows the user to write the coverage started by `NODE_V8_COVERAGE` to disk on demand. This method can be invoked multiple + * times during the lifetime of the process. Each time the execution counter will + * be reset and a new coverage report will be written to the directory specified + * by `NODE_V8_COVERAGE`. + * + * When the process is about to exit, one last coverage will still be written to + * disk unless {@link stopCoverage} is invoked before the process exits. + * @since v15.1.0, v14.18.0, v12.22.0 + */ + function takeCoverage(): void; + /** + * The `v8.stopCoverage()` method allows the user to stop the coverage collection + * started by `NODE_V8_COVERAGE`, so that V8 can release the execution count + * records and optimize code. This can be used in conjunction with {@link takeCoverage} if the user wants to collect the coverage on demand. + * @since v15.1.0, v14.18.0, v12.22.0 + */ + function stopCoverage(): void; +} +declare module 'node:v8' { + export * from 'v8'; +} diff --git a/ts-ticket-office-service/node_modules/@types/node/vm.d.ts b/ts-ticket-office-service/node_modules/@types/node/vm.d.ts new file mode 100755 index 000000000..eee4e40bf --- /dev/null +++ b/ts-ticket-office-service/node_modules/@types/node/vm.d.ts @@ -0,0 +1,509 @@ +/** + * The `vm` module enables compiling and running code within V8 Virtual + * Machine contexts. + * + * **The `vm` module is not a security** + * **mechanism. Do not use it to run untrusted code.** + * + * JavaScript code can be compiled and run immediately or + * compiled, saved, and run later. + * + * A common use case is to run the code in a different V8 Context. This means + * invoked code has a different global object than the invoking code. + * + * One can provide the context by `contextifying` an + * object. The invoked code treats any property in the context like a + * global variable. Any changes to global variables caused by the invoked + * code are reflected in the context object. + * + * ```js + * const vm = require('vm'); + * + * const x = 1; + * + * const context = { x: 2 }; + * vm.createContext(context); // Contextify the object. + * + * const code = 'x += 40; var y = 17;'; + * // `x` and `y` are global variables in the context. + * // Initially, x has the value 2 because that is the value of context.x. + * vm.runInContext(code, context); + * + * console.log(context.x); // 42 + * console.log(context.y); // 17 + * + * console.log(x); // 1; y is not defined. + * ``` + * @see [source](https://github.com/nodejs/node/blob/v18.0.0/lib/vm.js) + */ +declare module 'vm' { + interface Context extends NodeJS.Dict {} + interface BaseOptions { + /** + * Specifies the filename used in stack traces produced by this script. + * Default: `''`. + */ + filename?: string | undefined; + /** + * Specifies the line number offset that is displayed in stack traces produced by this script. + * Default: `0`. + */ + lineOffset?: number | undefined; + /** + * Specifies the column number offset that is displayed in stack traces produced by this script. + * @default 0 + */ + columnOffset?: number | undefined; + } + interface ScriptOptions extends BaseOptions { + displayErrors?: boolean | undefined; + timeout?: number | undefined; + cachedData?: Buffer | undefined; + /** @deprecated in favor of `script.createCachedData()` */ + produceCachedData?: boolean | undefined; + } + interface RunningScriptOptions extends BaseOptions { + /** + * When `true`, if an `Error` occurs while compiling the `code`, the line of code causing the error is attached to the stack trace. + * Default: `true`. + */ + displayErrors?: boolean | undefined; + /** + * Specifies the number of milliseconds to execute code before terminating execution. + * If execution is terminated, an `Error` will be thrown. This value must be a strictly positive integer. + */ + timeout?: number | undefined; + /** + * If `true`, the execution will be terminated when `SIGINT` (Ctrl+C) is received. + * Existing handlers for the event that have been attached via `process.on('SIGINT')` will be disabled during script execution, but will continue to work after that. + * If execution is terminated, an `Error` will be thrown. + * Default: `false`. + */ + breakOnSigint?: boolean | undefined; + /** + * If set to `afterEvaluate`, microtasks will be run immediately after the script has run. + */ + microtaskMode?: 'afterEvaluate' | undefined; + } + interface CompileFunctionOptions extends BaseOptions { + /** + * Provides an optional data with V8's code cache data for the supplied source. + */ + cachedData?: Buffer | undefined; + /** + * Specifies whether to produce new cache data. + * Default: `false`, + */ + produceCachedData?: boolean | undefined; + /** + * The sandbox/context in which the said function should be compiled in. + */ + parsingContext?: Context | undefined; + /** + * An array containing a collection of context extensions (objects wrapping the current scope) to be applied while compiling + */ + contextExtensions?: Object[] | undefined; + } + interface CreateContextOptions { + /** + * Human-readable name of the newly created context. + * @default 'VM Context i' Where i is an ascending numerical index of the created context. + */ + name?: string | undefined; + /** + * Corresponds to the newly created context for display purposes. + * The origin should be formatted like a `URL`, but with only the scheme, host, and port (if necessary), + * like the value of the `url.origin` property of a URL object. + * Most notably, this string should omit the trailing slash, as that denotes a path. + * @default '' + */ + origin?: string | undefined; + codeGeneration?: + | { + /** + * If set to false any calls to eval or function constructors (Function, GeneratorFunction, etc) + * will throw an EvalError. + * @default true + */ + strings?: boolean | undefined; + /** + * If set to false any attempt to compile a WebAssembly module will throw a WebAssembly.CompileError. + * @default true + */ + wasm?: boolean | undefined; + } + | undefined; + /** + * If set to `afterEvaluate`, microtasks will be run immediately after the script has run. + */ + microtaskMode?: 'afterEvaluate' | undefined; + } + type MeasureMemoryMode = 'summary' | 'detailed'; + interface MeasureMemoryOptions { + /** + * @default 'summary' + */ + mode?: MeasureMemoryMode | undefined; + context?: Context | undefined; + } + interface MemoryMeasurement { + total: { + jsMemoryEstimate: number; + jsMemoryRange: [number, number]; + }; + } + /** + * Instances of the `vm.Script` class contain precompiled scripts that can be + * executed in specific contexts. + * @since v0.3.1 + */ + class Script { + constructor(code: string, options?: ScriptOptions); + /** + * Runs the compiled code contained by the `vm.Script` object within the given`contextifiedObject` and returns the result. Running code does not have access + * to local scope. + * + * The following example compiles code that increments a global variable, sets + * the value of another global variable, then execute the code multiple times. + * The globals are contained in the `context` object. + * + * ```js + * const vm = require('vm'); + * + * const context = { + * animal: 'cat', + * count: 2 + * }; + * + * const script = new vm.Script('count += 1; name = "kitty";'); + * + * vm.createContext(context); + * for (let i = 0; i < 10; ++i) { + * script.runInContext(context); + * } + * + * console.log(context); + * // Prints: { animal: 'cat', count: 12, name: 'kitty' } + * ``` + * + * Using the `timeout` or `breakOnSigint` options will result in new event loops + * and corresponding threads being started, which have a non-zero performance + * overhead. + * @since v0.3.1 + * @param contextifiedObject A `contextified` object as returned by the `vm.createContext()` method. + * @return the result of the very last statement executed in the script. + */ + runInContext(contextifiedObject: Context, options?: RunningScriptOptions): any; + /** + * First contextifies the given `contextObject`, runs the compiled code contained + * by the `vm.Script` object within the created context, and returns the result. + * Running code does not have access to local scope. + * + * The following example compiles code that sets a global variable, then executes + * the code multiple times in different contexts. The globals are set on and + * contained within each individual `context`. + * + * ```js + * const vm = require('vm'); + * + * const script = new vm.Script('globalVar = "set"'); + * + * const contexts = [{}, {}, {}]; + * contexts.forEach((context) => { + * script.runInNewContext(context); + * }); + * + * console.log(contexts); + * // Prints: [{ globalVar: 'set' }, { globalVar: 'set' }, { globalVar: 'set' }] + * ``` + * @since v0.3.1 + * @param contextObject An object that will be `contextified`. If `undefined`, a new object will be created. + * @return the result of the very last statement executed in the script. + */ + runInNewContext(contextObject?: Context, options?: RunningScriptOptions): any; + /** + * Runs the compiled code contained by the `vm.Script` within the context of the + * current `global` object. Running code does not have access to local scope, but_does_ have access to the current `global` object. + * + * The following example compiles code that increments a `global` variable then + * executes that code multiple times: + * + * ```js + * const vm = require('vm'); + * + * global.globalVar = 0; + * + * const script = new vm.Script('globalVar += 1', { filename: 'myfile.vm' }); + * + * for (let i = 0; i < 1000; ++i) { + * script.runInThisContext(); + * } + * + * console.log(globalVar); + * + * // 1000 + * ``` + * @since v0.3.1 + * @return the result of the very last statement executed in the script. + */ + runInThisContext(options?: RunningScriptOptions): any; + /** + * Creates a code cache that can be used with the `Script` constructor's`cachedData` option. Returns a `Buffer`. This method may be called at any + * time and any number of times. + * + * ```js + * const script = new vm.Script(` + * function add(a, b) { + * return a + b; + * } + * + * const x = add(1, 2); + * `); + * + * const cacheWithoutX = script.createCachedData(); + * + * script.runInThisContext(); + * + * const cacheWithX = script.createCachedData(); + * ``` + * @since v10.6.0 + */ + createCachedData(): Buffer; + /** @deprecated in favor of `script.createCachedData()` */ + cachedDataProduced?: boolean | undefined; + cachedDataRejected?: boolean | undefined; + cachedData?: Buffer | undefined; + } + /** + * If given a `contextObject`, the `vm.createContext()` method will `prepare + * that object` so that it can be used in calls to {@link runInContext} or `script.runInContext()`. Inside such scripts, + * the `contextObject` will be the global object, retaining all of its existing + * properties but also having the built-in objects and functions any standard [global object](https://es5.github.io/#x15.1) has. Outside of scripts run by the vm module, global variables + * will remain unchanged. + * + * ```js + * const vm = require('vm'); + * + * global.globalVar = 3; + * + * const context = { globalVar: 1 }; + * vm.createContext(context); + * + * vm.runInContext('globalVar *= 2;', context); + * + * console.log(context); + * // Prints: { globalVar: 2 } + * + * console.log(global.globalVar); + * // Prints: 3 + * ``` + * + * If `contextObject` is omitted (or passed explicitly as `undefined`), a new, + * empty `contextified` object will be returned. + * + * The `vm.createContext()` method is primarily useful for creating a single + * context that can be used to run multiple scripts. For instance, if emulating a + * web browser, the method can be used to create a single context representing a + * window's global object, then run all `` + +[Get supported base64-js with the Tidelift Subscription](https://tidelift.com/subscription/pkg/npm-base64-js?utm_source=npm-base64-js&utm_medium=referral&utm_campaign=readme) + +## methods + +`base64js` has three exposed functions, `byteLength`, `toByteArray` and `fromByteArray`, which both take a single argument. + +* `byteLength` - Takes a base64 string and returns length of byte array +* `toByteArray` - Takes a base64 string and returns a byte array +* `fromByteArray` - Takes a byte array and returns a base64 string + +## license + +MIT diff --git a/ts-ticket-office-service/node_modules/base64-js/base64js.min.js b/ts-ticket-office-service/node_modules/base64-js/base64js.min.js new file mode 100644 index 000000000..908ac83fd --- /dev/null +++ b/ts-ticket-office-service/node_modules/base64-js/base64js.min.js @@ -0,0 +1 @@ +(function(a){if("object"==typeof exports&&"undefined"!=typeof module)module.exports=a();else if("function"==typeof define&&define.amd)define([],a);else{var b;b="undefined"==typeof window?"undefined"==typeof global?"undefined"==typeof self?this:self:global:window,b.base64js=a()}})(function(){return function(){function b(d,e,g){function a(j,i){if(!e[j]){if(!d[j]){var f="function"==typeof require&&require;if(!i&&f)return f(j,!0);if(h)return h(j,!0);var c=new Error("Cannot find module '"+j+"'");throw c.code="MODULE_NOT_FOUND",c}var k=e[j]={exports:{}};d[j][0].call(k.exports,function(b){var c=d[j][1][b];return a(c||b)},k,k.exports,b,d,e,g)}return e[j].exports}for(var h="function"==typeof require&&require,c=0;c>16,j[k++]=255&b>>8,j[k++]=255&b;return 2===h&&(b=l[a.charCodeAt(c)]<<2|l[a.charCodeAt(c+1)]>>4,j[k++]=255&b),1===h&&(b=l[a.charCodeAt(c)]<<10|l[a.charCodeAt(c+1)]<<4|l[a.charCodeAt(c+2)]>>2,j[k++]=255&b>>8,j[k++]=255&b),j}function g(a){return k[63&a>>18]+k[63&a>>12]+k[63&a>>6]+k[63&a]}function h(a,b,c){for(var d,e=[],f=b;fj?j:g+f));return 1===d?(b=a[c-1],e.push(k[b>>2]+k[63&b<<4]+"==")):2===d&&(b=(a[c-2]<<8)+a[c-1],e.push(k[b>>10]+k[63&b>>4]+k[63&b<<2]+"=")),e.join("")}c.byteLength=function(a){var b=d(a),c=b[0],e=b[1];return 3*(c+e)/4-e},c.toByteArray=f,c.fromByteArray=j;for(var k=[],l=[],m="undefined"==typeof Uint8Array?Array:Uint8Array,n="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",o=0,p=n.length;o 0) { + throw new Error('Invalid string. Length must be a multiple of 4') + } + + // Trim off extra bytes after placeholder bytes are found + // See: https://github.com/beatgammit/base64-js/issues/42 + var validLen = b64.indexOf('=') + if (validLen === -1) validLen = len + + var placeHoldersLen = validLen === len + ? 0 + : 4 - (validLen % 4) + + return [validLen, placeHoldersLen] +} + +// base64 is 4/3 + up to two characters of the original data +function byteLength (b64) { + var lens = getLens(b64) + var validLen = lens[0] + var placeHoldersLen = lens[1] + return ((validLen + placeHoldersLen) * 3 / 4) - placeHoldersLen +} + +function _byteLength (b64, validLen, placeHoldersLen) { + return ((validLen + placeHoldersLen) * 3 / 4) - placeHoldersLen +} + +function toByteArray (b64) { + var tmp + var lens = getLens(b64) + var validLen = lens[0] + var placeHoldersLen = lens[1] + + var arr = new Arr(_byteLength(b64, validLen, placeHoldersLen)) + + var curByte = 0 + + // if there are placeholders, only get up to the last complete 4 chars + var len = placeHoldersLen > 0 + ? validLen - 4 + : validLen + + var i + for (i = 0; i < len; i += 4) { + tmp = + (revLookup[b64.charCodeAt(i)] << 18) | + (revLookup[b64.charCodeAt(i + 1)] << 12) | + (revLookup[b64.charCodeAt(i + 2)] << 6) | + revLookup[b64.charCodeAt(i + 3)] + arr[curByte++] = (tmp >> 16) & 0xFF + arr[curByte++] = (tmp >> 8) & 0xFF + arr[curByte++] = tmp & 0xFF + } + + if (placeHoldersLen === 2) { + tmp = + (revLookup[b64.charCodeAt(i)] << 2) | + (revLookup[b64.charCodeAt(i + 1)] >> 4) + arr[curByte++] = tmp & 0xFF + } + + if (placeHoldersLen === 1) { + tmp = + (revLookup[b64.charCodeAt(i)] << 10) | + (revLookup[b64.charCodeAt(i + 1)] << 4) | + (revLookup[b64.charCodeAt(i + 2)] >> 2) + arr[curByte++] = (tmp >> 8) & 0xFF + arr[curByte++] = tmp & 0xFF + } + + return arr +} + +function tripletToBase64 (num) { + return lookup[num >> 18 & 0x3F] + + lookup[num >> 12 & 0x3F] + + lookup[num >> 6 & 0x3F] + + lookup[num & 0x3F] +} + +function encodeChunk (uint8, start, end) { + var tmp + var output = [] + for (var i = start; i < end; i += 3) { + tmp = + ((uint8[i] << 16) & 0xFF0000) + + ((uint8[i + 1] << 8) & 0xFF00) + + (uint8[i + 2] & 0xFF) + output.push(tripletToBase64(tmp)) + } + return output.join('') +} + +function fromByteArray (uint8) { + var tmp + var len = uint8.length + var extraBytes = len % 3 // if we have 1 byte left, pad 2 bytes + var parts = [] + var maxChunkLength = 16383 // must be multiple of 3 + + // go through the array every three bytes, we'll deal with trailing stuff later + for (var i = 0, len2 = len - extraBytes; i < len2; i += maxChunkLength) { + parts.push(encodeChunk(uint8, i, (i + maxChunkLength) > len2 ? len2 : (i + maxChunkLength))) + } + + // pad the end with zeros, but make sure to not forget the extra bytes + if (extraBytes === 1) { + tmp = uint8[len - 1] + parts.push( + lookup[tmp >> 2] + + lookup[(tmp << 4) & 0x3F] + + '==' + ) + } else if (extraBytes === 2) { + tmp = (uint8[len - 2] << 8) + uint8[len - 1] + parts.push( + lookup[tmp >> 10] + + lookup[(tmp >> 4) & 0x3F] + + lookup[(tmp << 2) & 0x3F] + + '=' + ) + } + + return parts.join('') +} diff --git a/ts-ticket-office-service/node_modules/base64-js/package.json b/ts-ticket-office-service/node_modules/base64-js/package.json new file mode 100644 index 000000000..c3972e39f --- /dev/null +++ b/ts-ticket-office-service/node_modules/base64-js/package.json @@ -0,0 +1,47 @@ +{ + "name": "base64-js", + "description": "Base64 encoding/decoding in pure JS", + "version": "1.5.1", + "author": "T. Jameson Little ", + "typings": "index.d.ts", + "bugs": { + "url": "https://github.com/beatgammit/base64-js/issues" + }, + "devDependencies": { + "babel-minify": "^0.5.1", + "benchmark": "^2.1.4", + "browserify": "^16.3.0", + "standard": "*", + "tape": "4.x" + }, + "homepage": "https://github.com/beatgammit/base64-js", + "keywords": [ + "base64" + ], + "license": "MIT", + "main": "index.js", + "repository": { + "type": "git", + "url": "git://github.com/beatgammit/base64-js.git" + }, + "scripts": { + "build": "browserify -s base64js -r ./ | minify > base64js.min.js", + "lint": "standard", + "test": "npm run lint && npm run unit", + "unit": "tape test/*.js" + }, + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/feross" + }, + { + "type": "patreon", + "url": "https://www.patreon.com/feross" + }, + { + "type": "consulting", + "url": "https://feross.org/support" + } + ] +} diff --git a/ts-ticket-office-service/node_modules/bignumber.js/CHANGELOG.md b/ts-ticket-office-service/node_modules/bignumber.js/CHANGELOG.md new file mode 100644 index 000000000..e288a9329 --- /dev/null +++ b/ts-ticket-office-service/node_modules/bignumber.js/CHANGELOG.md @@ -0,0 +1,266 @@ +#### 9.0.0 +* 27/05/2019 +* For compatibility with legacy browsers, remove `Symbol` references. + +#### 8.1.1 +* 24/02/2019 +* [BUGFIX] #222 Restore missing `var` to `export BigNumber`. +* Allow any key in BigNumber.Instance in *bignumber.d.ts*. + +#### 8.1.0 +* 23/02/2019 +* [NEW FEATURE] #220 Create a BigNumber using `{s, e, c}`. +* [NEW FEATURE] `isBigNumber`: if `BigNumber.DEBUG` is `true`, also check that the BigNumber instance is well-formed. +* Remove `instanceof` checks; just use `_isBigNumber` to identify a BigNumber instance. +* Add `_isBigNumber` to prototype in *bignumber.mjs*. +* Add tests for BigNumber creation from object. +* Update *API.html*. + +#### 8.0.2 +* 13/01/2019 +* #209 `toPrecision` without argument should follow `toString`. +* Improve *Use* section of *README*. +* Optimise `toString(10)`. +* Add verson number to API doc. + +#### 8.0.1 +* 01/11/2018 +* Rest parameter must be array type in *bignumber.d.ts*. + +#### 8.0.0 +* 01/11/2018 +* [NEW FEATURE] Add `BigNumber.sum` method. +* [NEW FEATURE]`toFormat`: add `prefix` and `suffix` options. +* [NEW FEATURE] #178 Pass custom formatting to `toFormat`. +* [BREAKING CHANGE] #184 `toFraction`: return array of BigNumbers not strings. +* [NEW FEATURE] #185 Enable overwrite of `valueOf` to prevent accidental addition to string. +* #183 Add Node.js `crypto` requirement to documentation. +* [BREAKING CHANGE] #198 Disallow signs and whitespace in custom alphabet. +* [NEW FEATURE] #188 Implement `util.inspect.custom` for Node.js REPL. +* #170 Make `isBigNumber` a type guard in *bignumber.d.ts*. +* [BREAKING CHANGE] `BigNumber.min` and `BigNumber.max`: don't accept an array. +* Update *.travis.yml*. +* Remove *bower.json*. + +#### 7.2.1 +* 24/05/2018 +* Add `browser` field to *package.json*. + +#### 7.2.0 +* 22/05/2018 +* #166 Correct *.mjs* file. Remove extension from `main` field in *package.json*. + +#### 7.1.0 +* 18/05/2018 +* Add `module` field to *package.json* for *bignumber.mjs*. + +#### 7.0.2 +* 17/05/2018 +* #165 Bugfix: upper-case letters for bases 11-36 in a custom alphabet. +* Add note to *README* regarding creating BigNumbers from Number values. + +#### 7.0.1 +* 26/04/2018 +* #158 Fix global object variable name typo. + +#### 7.0.0 +* 26/04/2018 +* #143 Remove global BigNumber from typings. +* #144 Enable compatibility with `Object.freeze(Object.prototype)`. +* #148 #123 #11 Only throw on a number primitive with more than 15 significant digits if `BigNumber.DEBUG` is `true`. +* Only throw on an invalid BigNumber value if `BigNumber.DEBUG` is `true`. Return BigNumber `NaN` instead. +* #154 `exponentiatedBy`: allow BigNumber exponent. +* #156 Prevent Content Security Policy *unsafe-eval* issue. +* `toFraction`: allow `Infinity` maximum denominator. +* Comment-out some excess tests to reduce test time. +* Amend indentation and other spacing. + +#### 6.0.0 +* 26/01/2018 +* #137 Implement `APLHABET` configuration option. +* Remove `ERRORS` configuration option. +* Remove `toDigits` method; extend `precision` method accordingly. +* Remove s`round` method; extend `decimalPlaces` method accordingly. +* Remove methods: `ceil`, `floor`, and `truncated`. +* Remove method aliases: `add`, `cmp`, `isInt`, `isNeg`, `trunc`, `mul`, `neg` and `sub`. +* Rename methods: `shift` to `shiftedBy`, `another` to `clone`, `toPower` to `exponentiatedBy`, and `equals` to `isEqualTo`. +* Rename methods: add `is` prefix to `greaterThan`, `greaterThanOrEqualTo`, `lessThan` and `lessThanOrEqualTo`. +* Add methods: `multipliedBy`, `isBigNumber`, `isPositive`, `integerValue`, `maximum` and `minimum`. +* Refactor test suite. +* Add *CHANGELOG.md*. +* Rewrite *bignumber.d.ts*. +* Redo API image. + +#### 5.0.0 +* 27/11/2017 +* #81 Don't throw on constructor call without `new`. + +#### 4.1.0 +* 26/09/2017 +* Remove node 0.6 from *.travis.yml*. +* Add *bignumber.mjs*. + +#### 4.0.4 +* 03/09/2017 +* Add missing aliases to *bignumber.d.ts*. + +#### 4.0.3 +* 30/08/2017 +* Add types: *bignumber.d.ts*. + +#### 4.0.2 +* 03/05/2017 +* #120 Workaround Safari/Webkit bug. + +#### 4.0.1 +* 05/04/2017 +* #121 BigNumber.default to BigNumber['default']. + +#### 4.0.0 +* 09/01/2017 +* Replace BigNumber.isBigNumber method with isBigNumber prototype property. + +#### 3.1.2 +* 08/01/2017 +* Minor documentation edit. + +#### 3.1.1 +* 08/01/2017 +* Uncomment `isBigNumber` tests. +* Ignore dot files. + +#### 3.1.0 +* 08/01/2017 +* Add `isBigNumber` method. + +#### 3.0.2 +* 08/01/2017 +* Bugfix: Possible incorrect value of `ERRORS` after a `BigNumber.another` call (due to `parseNumeric` declaration in outer scope). + +#### 3.0.1 +* 23/11/2016 +* Apply fix for old ipads with `%` issue, see #57 and #102. +* Correct error message. + +#### 3.0.0 +* 09/11/2016 +* Remove `require('crypto')` - leave it to the user. +* Add `BigNumber.set` as `BigNumber.config` alias. +* Default `POW_PRECISION` to `0`. + +#### 2.4.0 +* 14/07/2016 +* #97 Add exports to support ES6 imports. + +#### 2.3.0 +* 07/03/2016 +* #86 Add modulus parameter to `toPower`. + +#### 2.2.0 +* 03/03/2016 +* #91 Permit larger JS integers. + +#### 2.1.4 +* 15/12/2015 +* Correct UMD. + +#### 2.1.3 +* 13/12/2015 +* Refactor re global object and crypto availability when bundling. + +#### 2.1.2 +* 10/12/2015 +* Bugfix: `window.crypto` not assigned to `crypto`. + +#### 2.1.1 +* 09/12/2015 +* Prevent code bundler from adding `crypto` shim. + +#### 2.1.0 +* 26/10/2015 +* For `valueOf` and `toJSON`, include the minus sign with negative zero. + +#### 2.0.8 +* 2/10/2015 +* Internal round function bugfix. + +#### 2.0.6 +* 31/03/2015 +* Add bower.json. Tweak division after in-depth review. + +#### 2.0.5 +* 25/03/2015 +* Amend README. Remove bitcoin address. + +#### 2.0.4 +* 25/03/2015 +* Critical bugfix #58: division. + +#### 2.0.3 +* 18/02/2015 +* Amend README. Add source map. + +#### 2.0.2 +* 18/02/2015 +* Correct links. + +#### 2.0.1 +* 18/02/2015 +* Add `max`, `min`, `precision`, `random`, `shiftedBy`, `toDigits` and `truncated` methods. +* Add the short-forms: `add`, `mul`, `sd`, `sub` and `trunc`. +* Add an `another` method to enable multiple independent constructors to be created. +* Add support for the base 2, 8 and 16 prefixes `0b`, `0o` and `0x`. +* Enable a rounding mode to be specified as a second parameter to `toExponential`, `toFixed`, `toFormat` and `toPrecision`. +* Add a `CRYPTO` configuration property so cryptographically-secure pseudo-random number generation can be specified. +* Add a `MODULO_MODE` configuration property to enable the rounding mode used by the `modulo` operation to be specified. +* Add a `POW_PRECISION` configuration property to enable the number of significant digits calculated by the power operation to be limited. +* Improve code quality. +* Improve documentation. + +#### 2.0.0 +* 29/12/2014 +* Add `dividedToIntegerBy`, `isInteger` and `toFormat` methods. +* Remove the following short-forms: `isF`, `isZ`, `toE`, `toF`, `toFr`, `toN`, `toP`, `toS`. +* Store a BigNumber's coefficient in base 1e14, rather than base 10. +* Add fast path for integers to BigNumber constructor. +* Incorporate the library into the online documentation. + +#### 1.5.0 +* 13/11/2014 +* Add `toJSON` and `decimalPlaces` methods. + +#### 1.4.1 +* 08/06/2014 +* Amend README. + +#### 1.4.0 +* 08/05/2014 +* Add `toNumber`. + +#### 1.3.0 +* 08/11/2013 +* Ensure correct rounding of `sqrt` in all, rather than almost all, cases. +* Maximum radix to 64. + +#### 1.2.1 +* 17/10/2013 +* Sign of zero when x < 0 and x + (-x) = 0. + +#### 1.2.0 +* 19/9/2013 +* Throw Error objects for stack. + +#### 1.1.1 +* 22/8/2013 +* Show original value in constructor error message. + +#### 1.1.0 +* 1/8/2013 +* Allow numbers with trailing radix point. + +#### 1.0.1 +* Bugfix: error messages with incorrect method name + +#### 1.0.0 +* 8/11/2012 +* Initial release diff --git a/ts-ticket-office-service/node_modules/bignumber.js/LICENCE b/ts-ticket-office-service/node_modules/bignumber.js/LICENCE new file mode 100644 index 000000000..87a9b15e3 --- /dev/null +++ b/ts-ticket-office-service/node_modules/bignumber.js/LICENCE @@ -0,0 +1,23 @@ +The MIT Licence. + +Copyright (c) 2019 Michael Mclaughlin + +Permission is hereby granted, free of charge, to any person obtaining +a copy of this software and associated documentation files (the +'Software'), to deal in the Software without restriction, including +without limitation the rights to use, copy, modify, merge, publish, +distribute, sublicense, and/or sell copies of the Software, and to +permit persons to whom the Software is furnished to do so, subject to +the following conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. +IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY +CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, +TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE +SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + diff --git a/ts-ticket-office-service/node_modules/bignumber.js/README.md b/ts-ticket-office-service/node_modules/bignumber.js/README.md new file mode 100644 index 000000000..fc3c84cde --- /dev/null +++ b/ts-ticket-office-service/node_modules/bignumber.js/README.md @@ -0,0 +1,268 @@ +![bignumber.js](https://raw.githubusercontent.com/MikeMcl/bignumber.js/gh-pages/bignumberjs.png) + +A JavaScript library for arbitrary-precision decimal and non-decimal arithmetic. + +[![Build Status](https://travis-ci.org/MikeMcl/bignumber.js.svg)](https://travis-ci.org/MikeMcl/bignumber.js) + +
+ +## Features + + - Integers and decimals + - Simple API but full-featured + - Faster, smaller, and perhaps easier to use than JavaScript versions of Java's BigDecimal + - 8 KB minified and gzipped + - Replicates the `toExponential`, `toFixed`, `toPrecision` and `toString` methods of JavaScript's Number type + - Includes a `toFraction` and a correctly-rounded `squareRoot` method + - Supports cryptographically-secure pseudo-random number generation + - No dependencies + - Wide platform compatibility: uses JavaScript 1.5 (ECMAScript 3) features only + - Comprehensive [documentation](http://mikemcl.github.io/bignumber.js/) and test set + +![API](https://raw.githubusercontent.com/MikeMcl/bignumber.js/gh-pages/API.png) + +If a smaller and simpler library is required see [big.js](https://github.com/MikeMcl/big.js/). +It's less than half the size but only works with decimal numbers and only has half the methods. +It also does not allow `NaN` or `Infinity`, or have the configuration options of this library. + +See also [decimal.js](https://github.com/MikeMcl/decimal.js/), which among other things adds support for non-integer powers, and performs all operations to a specified number of significant digits. + +## Load + +The library is the single JavaScript file *bignumber.js* (or minified, *bignumber.min.js*). + +Browser: + +```html + +``` + +[Node.js](http://nodejs.org): + +```bash +$ npm install bignumber.js +``` + +```javascript +const BigNumber = require('bignumber.js'); +``` + +ES6 module: + +```javascript +import BigNumber from "./bignumber.mjs" +``` + +AMD loader libraries such as [requireJS](http://requirejs.org/): + +```javascript +require(['bignumber'], function(BigNumber) { + // Use BigNumber here in local scope. No global BigNumber. +}); +``` + +## Use + +The library exports a single constructor function, [`BigNumber`](http://mikemcl.github.io/bignumber.js/#bignumber), which accepts a value of type Number, String or BigNumber, + +```javascript +let x = new BigNumber(123.4567); +let y = BigNumber('123456.7e-3'); +let z = new BigNumber(x); +x.isEqualTo(y) && y.isEqualTo(z) && x.isEqualTo(z); // true +``` + +To get the string value of a BigNumber use [`toString()`](http://mikemcl.github.io/bignumber.js/#toS) or [`toFixed()`](http://mikemcl.github.io/bignumber.js/#toFix). Using `toFixed()` prevents exponential notation being returned, no matter how large or small the value. + +```javascript +let x = new BigNumber('1111222233334444555566'); +x.toString(); // "1.111222233334444555566e+21" +x.toFixed(); // "1111222233334444555566" +``` + +If the limited precision of Number values is not well understood, it is recommended to create BigNumbers from String values rather than Number values to avoid a potential loss of precision. + +*In all further examples below, `let`, semicolons and `toString` calls are not shown. If a commented-out value is in quotes it means `toString` has been called on the preceding expression.* + +```javascript +// Precision loss from using numeric literals with more than 15 significant digits. +new BigNumber(1.0000000000000001) // '1' +new BigNumber(88259496234518.57) // '88259496234518.56' +new BigNumber(99999999999999999999) // '100000000000000000000' + +// Precision loss from using numeric literals outside the range of Number values. +new BigNumber(2e+308) // 'Infinity' +new BigNumber(1e-324) // '0' + +// Precision loss from the unexpected result of arithmetic with Number values. +new BigNumber(0.7 + 0.1) // '0.7999999999999999' +``` + +When creating a BigNumber from a Number, note that a BigNumber is created from a Number's decimal `toString()` value not from its underlying binary value. If the latter is required, then pass the Number's `toString(2)` value and specify base 2. + +```javascript +new BigNumber(Number.MAX_VALUE.toString(2), 2) +``` + +BigNumbers can be created from values in bases from 2 to 36. See [`ALPHABET`](http://mikemcl.github.io/bignumber.js/#alphabet) to extend this range. + +```javascript +a = new BigNumber(1011, 2) // "11" +b = new BigNumber('zz.9', 36) // "1295.25" +c = a.plus(b) // "1306.25" +``` + +Performance is better if base 10 is NOT specified for decimal values. Only specify base 10 when it is desired that the number of decimal places of the input value be limited to the current [`DECIMAL_PLACES`](http://mikemcl.github.io/bignumber.js/#decimal-places) setting. + +A BigNumber is immutable in the sense that it is not changed by its methods. + +```javascript +0.3 - 0.1 // 0.19999999999999998 +x = new BigNumber(0.3) +x.minus(0.1) // "0.2" +x // "0.3" +``` + +The methods that return a BigNumber can be chained. + +```javascript +x.dividedBy(y).plus(z).times(9) +x.times('1.23456780123456789e+9').plus(9876.5432321).dividedBy('4444562598.111772').integerValue() +``` + +Some of the longer method names have a shorter alias. + +```javascript +x.squareRoot().dividedBy(y).exponentiatedBy(3).isEqualTo(x.sqrt().div(y).pow(3)) // true +x.modulo(y).multipliedBy(z).eq(x.mod(y).times(z)) // true +``` + +As with JavaScript's Number type, there are [`toExponential`](http://mikemcl.github.io/bignumber.js/#toE), [`toFixed`](http://mikemcl.github.io/bignumber.js/#toFix) and [`toPrecision`](http://mikemcl.github.io/bignumber.js/#toP) methods. + +```javascript +x = new BigNumber(255.5) +x.toExponential(5) // "2.55500e+2" +x.toFixed(5) // "255.50000" +x.toPrecision(5) // "255.50" +x.toNumber() // 255.5 +``` + + A base can be specified for [`toString`](http://mikemcl.github.io/bignumber.js/#toS). Performance is better if base 10 is NOT specified, i.e. use `toString()` not `toString(10)`. Only specify base 10 when it is desired that the number of decimal places be limited to the current [`DECIMAL_PLACES`](http://mikemcl.github.io/bignumber.js/#decimal-places) setting. + + ```javascript + x.toString(16) // "ff.8" + ``` + +There is a [`toFormat`](http://mikemcl.github.io/bignumber.js/#toFor) method which may be useful for internationalisation. + +```javascript +y = new BigNumber('1234567.898765') +y.toFormat(2) // "1,234,567.90" +``` + +The maximum number of decimal places of the result of an operation involving division (i.e. a division, square root, base conversion or negative power operation) is set using the `set` or `config` method of the `BigNumber` constructor. + +The other arithmetic operations always give the exact result. + +```javascript +BigNumber.set({ DECIMAL_PLACES: 10, ROUNDING_MODE: 4 }) + +x = new BigNumber(2) +y = new BigNumber(3) +z = x.dividedBy(y) // "0.6666666667" +z.squareRoot() // "0.8164965809" +z.exponentiatedBy(-3) // "3.3749999995" +z.toString(2) // "0.1010101011" +z.multipliedBy(z) // "0.44444444448888888889" +z.multipliedBy(z).decimalPlaces(10) // "0.4444444445" +``` + +There is a [`toFraction`](http://mikemcl.github.io/bignumber.js/#toFr) method with an optional *maximum denominator* argument + +```javascript +y = new BigNumber(355) +pi = y.dividedBy(113) // "3.1415929204" +pi.toFraction() // [ "7853982301", "2500000000" ] +pi.toFraction(1000) // [ "355", "113" ] +``` + +and [`isNaN`](http://mikemcl.github.io/bignumber.js/#isNaN) and [`isFinite`](http://mikemcl.github.io/bignumber.js/#isF) methods, as `NaN` and `Infinity` are valid `BigNumber` values. + +```javascript +x = new BigNumber(NaN) // "NaN" +y = new BigNumber(Infinity) // "Infinity" +x.isNaN() && !y.isNaN() && !x.isFinite() && !y.isFinite() // true +``` + +The value of a BigNumber is stored in a decimal floating point format in terms of a coefficient, exponent and sign. + +```javascript +x = new BigNumber(-123.456); +x.c // [ 123, 45600000000000 ] coefficient (i.e. significand) +x.e // 2 exponent +x.s // -1 sign +``` + +For advanced usage, multiple BigNumber constructors can be created, each with their own independent configuration. + +```javascript +// Set DECIMAL_PLACES for the original BigNumber constructor +BigNumber.set({ DECIMAL_PLACES: 10 }) + +// Create another BigNumber constructor, optionally passing in a configuration object +BN = BigNumber.clone({ DECIMAL_PLACES: 5 }) + +x = new BigNumber(1) +y = new BN(1) + +x.div(3) // '0.3333333333' +y.div(3) // '0.33333' +``` + +For further information see the [API](http://mikemcl.github.io/bignumber.js/) reference in the *doc* directory. + +## Test + +The *test/modules* directory contains the test scripts for each method. + +The tests can be run with Node.js or a browser. For Node.js use + + $ npm test + +or + + $ node test/test + +To test a single method, use, for example + + $ node test/methods/toFraction + +For the browser, open *test/test.html*. + +## Build + +For Node, if [uglify-js](https://github.com/mishoo/UglifyJS2) is installed + + npm install uglify-js -g + +then + + npm run build + +will create *bignumber.min.js*. + +A source map will also be created in the root directory. + +## Feedback + +Open an issue, or email + +Michael + +M8ch88l@gmail.com + +## Licence + +The MIT Licence. + +See [LICENCE](https://github.com/MikeMcl/bignumber.js/blob/master/LICENCE). diff --git a/ts-ticket-office-service/node_modules/bignumber.js/bignumber.d.ts b/ts-ticket-office-service/node_modules/bignumber.js/bignumber.d.ts new file mode 100644 index 000000000..ac6a3e43a --- /dev/null +++ b/ts-ticket-office-service/node_modules/bignumber.js/bignumber.d.ts @@ -0,0 +1,1829 @@ +// Type definitions for bignumber.js >=8.1.0 +// Project: https://github.com/MikeMcl/bignumber.js +// Definitions by: Michael Mclaughlin +// Definitions: https://github.com/MikeMcl/bignumber.js + +// Documentation: http://mikemcl.github.io/bignumber.js/ +// +// Exports: +// +// class BigNumber (default export) +// type BigNumber.Constructor +// type BigNumber.ModuloMode +// type BigNumber.RoundingMOde +// type BigNumber.Value +// interface BigNumber.Config +// interface BigNumber.Format +// interface BigNumber.Instance +// +// Example: +// +// import {BigNumber} from "bignumber.js" +// //import BigNumber from "bignumber.js" +// +// let rm: BigNumber.RoundingMode = BigNumber.ROUND_UP; +// let f: BigNumber.Format = { decimalSeparator: ',' }; +// let c: BigNumber.Config = { DECIMAL_PLACES: 4, ROUNDING_MODE: rm, FORMAT: f }; +// BigNumber.config(c); +// +// let v: BigNumber.Value = '12345.6789'; +// let b: BigNumber = new BigNumber(v); +// +// The use of compiler option `--strictNullChecks` is recommended. + +export default BigNumber; + +export namespace BigNumber { + + /** See `BigNumber.config` (alias `BigNumber.set`) and `BigNumber.clone`. */ + interface Config { + + /** + * An integer, 0 to 1e+9. Default value: 20. + * + * The maximum number of decimal places of the result of operations involving division, i.e. + * division, square root and base conversion operations, and exponentiation when the exponent is + * negative. + * + * ```ts + * BigNumber.config({ DECIMAL_PLACES: 5 }) + * BigNumber.set({ DECIMAL_PLACES: 5 }) + * ``` + */ + DECIMAL_PLACES?: number; + + /** + * An integer, 0 to 8. Default value: `BigNumber.ROUND_HALF_UP` (4). + * + * The rounding mode used in operations that involve division (see `DECIMAL_PLACES`) and the + * default rounding mode of the `decimalPlaces`, `precision`, `toExponential`, `toFixed`, + * `toFormat` and `toPrecision` methods. + * + * The modes are available as enumerated properties of the BigNumber constructor. + * + * ```ts + * BigNumber.config({ ROUNDING_MODE: 0 }) + * BigNumber.set({ ROUNDING_MODE: BigNumber.ROUND_UP }) + * ``` + */ + ROUNDING_MODE?: BigNumber.RoundingMode; + + /** + * An integer, 0 to 1e+9, or an array, [-1e+9 to 0, 0 to 1e+9]. + * Default value: `[-7, 20]`. + * + * The exponent value(s) at which `toString` returns exponential notation. + * + * If a single number is assigned, the value is the exponent magnitude. + * + * If an array of two numbers is assigned then the first number is the negative exponent value at + * and beneath which exponential notation is used, and the second number is the positive exponent + * value at and above which exponential notation is used. + * + * For example, to emulate JavaScript numbers in terms of the exponent values at which they begin + * to use exponential notation, use `[-7, 20]`. + * + * ```ts + * BigNumber.config({ EXPONENTIAL_AT: 2 }) + * new BigNumber(12.3) // '12.3' e is only 1 + * new BigNumber(123) // '1.23e+2' + * new BigNumber(0.123) // '0.123' e is only -1 + * new BigNumber(0.0123) // '1.23e-2' + * + * BigNumber.config({ EXPONENTIAL_AT: [-7, 20] }) + * new BigNumber(123456789) // '123456789' e is only 8 + * new BigNumber(0.000000123) // '1.23e-7' + * + * // Almost never return exponential notation: + * BigNumber.config({ EXPONENTIAL_AT: 1e+9 }) + * + * // Always return exponential notation: + * BigNumber.config({ EXPONENTIAL_AT: 0 }) + * ``` + * + * Regardless of the value of `EXPONENTIAL_AT`, the `toFixed` method will always return a value in + * normal notation and the `toExponential` method will always return a value in exponential form. + * Calling `toString` with a base argument, e.g. `toString(10)`, will also always return normal + * notation. + */ + EXPONENTIAL_AT?: number | [number, number]; + + /** + * An integer, magnitude 1 to 1e+9, or an array, [-1e+9 to -1, 1 to 1e+9]. + * Default value: `[-1e+9, 1e+9]`. + * + * The exponent value(s) beyond which overflow to Infinity and underflow to zero occurs. + * + * If a single number is assigned, it is the maximum exponent magnitude: values wth a positive + * exponent of greater magnitude become Infinity and those with a negative exponent of greater + * magnitude become zero. + * + * If an array of two numbers is assigned then the first number is the negative exponent limit and + * the second number is the positive exponent limit. + * + * For example, to emulate JavaScript numbers in terms of the exponent values at which they + * become zero and Infinity, use [-324, 308]. + * + * ```ts + * BigNumber.config({ RANGE: 500 }) + * BigNumber.config().RANGE // [ -500, 500 ] + * new BigNumber('9.999e499') // '9.999e+499' + * new BigNumber('1e500') // 'Infinity' + * new BigNumber('1e-499') // '1e-499' + * new BigNumber('1e-500') // '0' + * + * BigNumber.config({ RANGE: [-3, 4] }) + * new BigNumber(99999) // '99999' e is only 4 + * new BigNumber(100000) // 'Infinity' e is 5 + * new BigNumber(0.001) // '0.01' e is only -3 + * new BigNumber(0.0001) // '0' e is -4 + * ``` + * The largest possible magnitude of a finite BigNumber is 9.999...e+1000000000. + * The smallest possible magnitude of a non-zero BigNumber is 1e-1000000000. + */ + RANGE?: number | [number, number]; + + /** + * A boolean: `true` or `false`. Default value: `false`. + * + * The value that determines whether cryptographically-secure pseudo-random number generation is + * used. If `CRYPTO` is set to true then the random method will generate random digits using + * `crypto.getRandomValues` in browsers that support it, or `crypto.randomBytes` if using a + * version of Node.js that supports it. + * + * If neither function is supported by the host environment then attempting to set `CRYPTO` to + * `true` will fail and an exception will be thrown. + * + * If `CRYPTO` is `false` then the source of randomness used will be `Math.random` (which is + * assumed to generate at least 30 bits of randomness). + * + * See `BigNumber.random`. + * + * ```ts + * // Node.js + * global.crypto = require('crypto') + * + * BigNumber.config({ CRYPTO: true }) + * BigNumber.config().CRYPTO // true + * BigNumber.random() // 0.54340758610486147524 + * ``` + */ + CRYPTO?: boolean; + + /** + * An integer, 0, 1, 3, 6 or 9. Default value: `BigNumber.ROUND_DOWN` (1). + * + * The modulo mode used when calculating the modulus: `a mod n`. + * The quotient, `q = a / n`, is calculated according to the `ROUNDING_MODE` that corresponds to + * the chosen `MODULO_MODE`. + * The remainder, `r`, is calculated as: `r = a - n * q`. + * + * The modes that are most commonly used for the modulus/remainder operation are shown in the + * following table. Although the other rounding modes can be used, they may not give useful + * results. + * + * Property | Value | Description + * :------------------|:------|:------------------------------------------------------------------ + * `ROUND_UP` | 0 | The remainder is positive if the dividend is negative. + * `ROUND_DOWN` | 1 | The remainder has the same sign as the dividend. + * | | Uses 'truncating division' and matches JavaScript's `%` operator . + * `ROUND_FLOOR` | 3 | The remainder has the same sign as the divisor. + * | | This matches Python's `%` operator. + * `ROUND_HALF_EVEN` | 6 | The IEEE 754 remainder function. + * `EUCLID` | 9 | The remainder is always positive. + * | | Euclidian division: `q = sign(n) * floor(a / abs(n))` + * + * The rounding/modulo modes are available as enumerated properties of the BigNumber constructor. + * + * See `modulo`. + * + * ```ts + * BigNumber.config({ MODULO_MODE: BigNumber.EUCLID }) + * BigNumber.set({ MODULO_MODE: 9 }) // equivalent + * ``` + */ + MODULO_MODE?: BigNumber.ModuloMode; + + /** + * An integer, 0 to 1e+9. Default value: 0. + * + * The maximum precision, i.e. number of significant digits, of the result of the power operation + * - unless a modulus is specified. + * + * If set to 0, the number of significant digits will not be limited. + * + * See `exponentiatedBy`. + * + * ```ts + * BigNumber.config({ POW_PRECISION: 100 }) + * ``` + */ + POW_PRECISION?: number; + + /** + * An object including any number of the properties shown below. + * + * The object configures the format of the string returned by the `toFormat` method. + * The example below shows the properties of the object that are recognised, and + * their default values. + * + * Unlike the other configuration properties, the values of the properties of the `FORMAT` object + * will not be checked for validity - the existing object will simply be replaced by the object + * that is passed in. + * + * See `toFormat`. + * + * ```ts + * BigNumber.config({ + * FORMAT: { + * // string to prepend + * prefix: '', + * // the decimal separator + * decimalSeparator: '.', + * // the grouping separator of the integer part + * groupSeparator: ',', + * // the primary grouping size of the integer part + * groupSize: 3, + * // the secondary grouping size of the integer part + * secondaryGroupSize: 0, + * // the grouping separator of the fraction part + * fractionGroupSeparator: ' ', + * // the grouping size of the fraction part + * fractionGroupSize: 0, + * // string to append + * suffix: '' + * } + * }) + * ``` + */ + FORMAT?: BigNumber.Format; + + /** + * The alphabet used for base conversion. The length of the alphabet corresponds to the maximum + * value of the base argument that can be passed to the BigNumber constructor or `toString`. + * + * Default value: `'0123456789abcdefghijklmnopqrstuvwxyz'`. + * + * There is no maximum length for the alphabet, but it must be at least 2 characters long, + * and it must not contain whitespace or a repeated character, or the sign indicators '+' and + * '-', or the decimal separator '.'. + * + * ```ts + * // duodecimal (base 12) + * BigNumber.config({ ALPHABET: '0123456789TE' }) + * x = new BigNumber('T', 12) + * x.toString() // '10' + * x.toString(12) // 'T' + * ``` + */ + ALPHABET?: string; + } + + /** See `FORMAT` and `toFormat`. */ + interface Format { + + /** The string to prepend. */ + prefix?: string; + + /** The decimal separator. */ + decimalSeparator?: string; + + /** The grouping separator of the integer part. */ + groupSeparator?: string; + + /** The primary grouping size of the integer part. */ + groupSize?: number; + + /** The secondary grouping size of the integer part. */ + secondaryGroupSize?: number; + + /** The grouping separator of the fraction part. */ + fractionGroupSeparator?: string; + + /** The grouping size of the fraction part. */ + fractionGroupSize?: number; + + /** The string to append. */ + suffix?: string; + } + + interface Instance { + + /** The coefficient of the value of this BigNumber, an array of base 1e14 integer numbers, or null. */ + readonly c: number[] | null; + + /** The exponent of the value of this BigNumber, an integer number, -1000000000 to 1000000000, or null. */ + readonly e: number | null; + + /** The sign of the value of this BigNumber, -1, 1, or null. */ + readonly s: number | null; + + [key: string]: any; + } + + type Constructor = typeof BigNumber; + type ModuloMode = 0 | 1 | 3 | 6 | 9; + type RoundingMode = 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8; + type Value = string | number | Instance; +} + +export declare class BigNumber implements BigNumber.Instance { + + /** Used internally to identify a BigNumber instance. */ + private readonly _isBigNumber: true; + + /** The coefficient of the value of this BigNumber, an array of base 1e14 integer numbers, or null. */ + readonly c: number[] | null; + + /** The exponent of the value of this BigNumber, an integer number, -1000000000 to 1000000000, or null. */ + readonly e: number | null; + + /** The sign of the value of this BigNumber, -1, 1, or null. */ + readonly s: number | null; + + /** + * Returns a new instance of a BigNumber object with value `n`, where `n` is a numeric value in + * the specified `base`, or base 10 if `base` is omitted or is `null` or `undefined`. + * + * ```ts + * x = new BigNumber(123.4567) // '123.4567' + * // 'new' is optional + * y = BigNumber(x) // '123.4567' + * ``` + * + * If `n` is a base 10 value it can be in normal (fixed-point) or exponential notation. + * Values in other bases must be in normal notation. Values in any base can have fraction digits, + * i.e. digits after the decimal point. + * + * ```ts + * new BigNumber(43210) // '43210' + * new BigNumber('4.321e+4') // '43210' + * new BigNumber('-735.0918e-430') // '-7.350918e-428' + * new BigNumber('123412421.234324', 5) // '607236.557696' + * ``` + * + * Signed `0`, signed `Infinity` and `NaN` are supported. + * + * ```ts + * new BigNumber('-Infinity') // '-Infinity' + * new BigNumber(NaN) // 'NaN' + * new BigNumber(-0) // '0' + * new BigNumber('.5') // '0.5' + * new BigNumber('+2') // '2' + * ``` + * + * String values in hexadecimal literal form, e.g. `'0xff'`, are valid, as are string values with + * the octal and binary prefixs `'0o'` and `'0b'`. String values in octal literal form without the + * prefix will be interpreted as decimals, e.g. `'011'` is interpreted as 11, not 9. + * + * ```ts + * new BigNumber(-10110100.1, 2) // '-180.5' + * new BigNumber('-0b10110100.1') // '-180.5' + * new BigNumber('ff.8', 16) // '255.5' + * new BigNumber('0xff.8') // '255.5' + * ``` + * + * If a base is specified, `n` is rounded according to the current `DECIMAL_PLACES` and + * `ROUNDING_MODE` settings. This includes base 10, so don't include a `base` parameter for decimal + * values unless this behaviour is desired. + * + * ```ts + * BigNumber.config({ DECIMAL_PLACES: 5 }) + * new BigNumber(1.23456789) // '1.23456789' + * new BigNumber(1.23456789, 10) // '1.23457' + * ``` + * + * An error is thrown if `base` is invalid. + * + * There is no limit to the number of digits of a value of type string (other than that of + * JavaScript's maximum array size). See `RANGE` to set the maximum and minimum possible exponent + * value of a BigNumber. + * + * ```ts + * new BigNumber('5032485723458348569331745.33434346346912144534543') + * new BigNumber('4.321e10000000') + * ``` + * + * BigNumber `NaN` is returned if `n` is invalid (unless `BigNumber.DEBUG` is `true`, see below). + * + * ```ts + * new BigNumber('.1*') // 'NaN' + * new BigNumber('blurgh') // 'NaN' + * new BigNumber(9, 2) // 'NaN' + * ``` + * + * To aid in debugging, if `BigNumber.DEBUG` is `true` then an error will be thrown on an + * invalid `n`. An error will also be thrown if `n` is of type number with more than 15 + * significant digits, as calling `toString` or `valueOf` on these numbers may not result in the + * intended value. + * + * ```ts + * console.log(823456789123456.3) // 823456789123456.2 + * new BigNumber(823456789123456.3) // '823456789123456.2' + * BigNumber.DEBUG = true + * // 'Error: Number has more than 15 significant digits' + * new BigNumber(823456789123456.3) + * // 'Error: Not a base 2 number' + * new BigNumber(9, 2) + * ``` + * + * A BigNumber can also be created from an object literal. + * Use `isBigNumber` to check that it is well-formed. + * + * ```ts + * new BigNumber({ s: 1, e: 2, c: [ 777, 12300000000000 ], _isBigNumber: true }) // '777.123' + * ``` + * + * @param n A numeric value. + * @param base The base of `n`, integer, 2 to 36 (or `ALPHABET.length`, see `ALPHABET`). + */ + constructor(n: BigNumber.Value, base?: number); + + /** + * Returns a BigNumber whose value is the absolute value, i.e. the magnitude, of the value of this + * BigNumber. + * + * The return value is always exact and unrounded. + * + * ```ts + * x = new BigNumber(-0.8) + * x.absoluteValue() // '0.8' + * ``` + */ + absoluteValue(): BigNumber; + + /** + * Returns a BigNumber whose value is the absolute value, i.e. the magnitude, of the value of this + * BigNumber. + * + * The return value is always exact and unrounded. + * + * ```ts + * x = new BigNumber(-0.8) + * x.abs() // '0.8' + * ``` + */ + abs(): BigNumber; + + /** + * Returns | | + * :-------:|:--------------------------------------------------------------| + * 1 | If the value of this BigNumber is greater than the value of `n` + * -1 | If the value of this BigNumber is less than the value of `n` + * 0 | If this BigNumber and `n` have the same value + * `null` | If the value of either this BigNumber or `n` is `NaN` + * + * ```ts + * + * x = new BigNumber(Infinity) + * y = new BigNumber(5) + * x.comparedTo(y) // 1 + * x.comparedTo(x.minus(1)) // 0 + * y.comparedTo(NaN) // null + * y.comparedTo('110', 2) // -1 + * ``` + * @param n A numeric value. + * @param [base] The base of n. + */ + comparedTo(n: BigNumber.Value, base?: number): number; + + /** + * Returns a BigNumber whose value is the value of this BigNumber rounded by rounding mode + * `roundingMode` to a maximum of `decimalPlaces` decimal places. + * + * If `decimalPlaces` is omitted, or is `null` or `undefined`, the return value is the number of + * decimal places of the value of this BigNumber, or `null` if the value of this BigNumber is + * ±`Infinity` or `NaN`. + * + * If `roundingMode` is omitted, or is `null` or `undefined`, `ROUNDING_MODE` is used. + * + * Throws if `decimalPlaces` or `roundingMode` is invalid. + * + * ```ts + * x = new BigNumber(1234.56) + * x.decimalPlaces() // 2 + * x.decimalPlaces(1) // '1234.6' + * x.decimalPlaces(2) // '1234.56' + * x.decimalPlaces(10) // '1234.56' + * x.decimalPlaces(0, 1) // '1234' + * x.decimalPlaces(0, 6) // '1235' + * x.decimalPlaces(1, 1) // '1234.5' + * x.decimalPlaces(1, BigNumber.ROUND_HALF_EVEN) // '1234.6' + * x // '1234.56' + * y = new BigNumber('9.9e-101') + * y.decimalPlaces() // 102 + * ``` + * + * @param [decimalPlaces] Decimal places, integer, 0 to 1e+9. + * @param [roundingMode] Rounding mode, integer, 0 to 8. + */ + decimalPlaces(): number; + decimalPlaces(decimalPlaces: number, roundingMode?: BigNumber.RoundingMode): BigNumber; + + /** + * Returns a BigNumber whose value is the value of this BigNumber rounded by rounding mode + * `roundingMode` to a maximum of `decimalPlaces` decimal places. + * + * If `decimalPlaces` is omitted, or is `null` or `undefined`, the return value is the number of + * decimal places of the value of this BigNumber, or `null` if the value of this BigNumber is + * ±`Infinity` or `NaN`. + * + * If `roundingMode` is omitted, or is `null` or `undefined`, `ROUNDING_MODE` is used. + * + * Throws if `decimalPlaces` or `roundingMode` is invalid. + * + * ```ts + * x = new BigNumber(1234.56) + * x.dp() // 2 + * x.dp(1) // '1234.6' + * x.dp(2) // '1234.56' + * x.dp(10) // '1234.56' + * x.dp(0, 1) // '1234' + * x.dp(0, 6) // '1235' + * x.dp(1, 1) // '1234.5' + * x.dp(1, BigNumber.ROUND_HALF_EVEN) // '1234.6' + * x // '1234.56' + * y = new BigNumber('9.9e-101') + * y.dp() // 102 + * ``` + * + * @param [decimalPlaces] Decimal places, integer, 0 to 1e+9. + * @param [roundingMode] Rounding mode, integer, 0 to 8. + */ + dp(): number; + dp(decimalPlaces: number, roundingMode?: BigNumber.RoundingMode): BigNumber; + + /** + * Returns a BigNumber whose value is the value of this BigNumber divided by `n`, rounded + * according to the current `DECIMAL_PLACES` and `ROUNDING_MODE` settings. + * + * ```ts + * x = new BigNumber(355) + * y = new BigNumber(113) + * x.dividedBy(y) // '3.14159292035398230088' + * x.dividedBy(5) // '71' + * x.dividedBy(47, 16) // '5' + * ``` + * + * @param n A numeric value. + * @param [base] The base of n. + */ + dividedBy(n: BigNumber.Value, base?: number): BigNumber; + + /** + * Returns a BigNumber whose value is the value of this BigNumber divided by `n`, rounded + * according to the current `DECIMAL_PLACES` and `ROUNDING_MODE` settings. + * + * ```ts + * x = new BigNumber(355) + * y = new BigNumber(113) + * x.div(y) // '3.14159292035398230088' + * x.div(5) // '71' + * x.div(47, 16) // '5' + * ``` + * + * @param n A numeric value. + * @param [base] The base of n. + */ + div(n: BigNumber.Value, base?: number): BigNumber; + + /** + * Returns a BigNumber whose value is the integer part of dividing the value of this BigNumber by + * `n`. + * + * ```ts + * x = new BigNumber(5) + * y = new BigNumber(3) + * x.dividedToIntegerBy(y) // '1' + * x.dividedToIntegerBy(0.7) // '7' + * x.dividedToIntegerBy('0.f', 16) // '5' + * ``` + * + * @param n A numeric value. + * @param [base] The base of n. + */ + dividedToIntegerBy(n: BigNumber.Value, base?: number): BigNumber; + + /** + * Returns a BigNumber whose value is the integer part of dividing the value of this BigNumber by + * `n`. + * + * ```ts + * x = new BigNumber(5) + * y = new BigNumber(3) + * x.idiv(y) // '1' + * x.idiv(0.7) // '7' + * x.idiv('0.f', 16) // '5' + * ``` + * + * @param n A numeric value. + * @param [base] The base of n. + */ + idiv(n: BigNumber.Value, base?: number): BigNumber; + + /** + * Returns a BigNumber whose value is the value of this BigNumber exponentiated by `n`, i.e. + * raised to the power `n`, and optionally modulo a modulus `m`. + * + * If `n` is negative the result is rounded according to the current `DECIMAL_PLACES` and + * `ROUNDING_MODE` settings. + * + * As the number of digits of the result of the power operation can grow so large so quickly, + * e.g. 123.456**10000 has over 50000 digits, the number of significant digits calculated is + * limited to the value of the `POW_PRECISION` setting (unless a modulus `m` is specified). + * + * By default `POW_PRECISION` is set to 0. This means that an unlimited number of significant + * digits will be calculated, and that the method's performance will decrease dramatically for + * larger exponents. + * + * If `m` is specified and the value of `m`, `n` and this BigNumber are integers and `n` is + * positive, then a fast modular exponentiation algorithm is used, otherwise the operation will + * be performed as `x.exponentiatedBy(n).modulo(m)` with a `POW_PRECISION` of 0. + * + * Throws if `n` is not an integer. + * + * ```ts + * Math.pow(0.7, 2) // 0.48999999999999994 + * x = new BigNumber(0.7) + * x.exponentiatedBy(2) // '0.49' + * BigNumber(3).exponentiatedBy(-2) // '0.11111111111111111111' + * ``` + * + * @param n The exponent, an integer. + * @param [m] The modulus. + */ + exponentiatedBy(n: BigNumber.Value, m?: BigNumber.Value): BigNumber; + exponentiatedBy(n: number, m?: BigNumber.Value): BigNumber; + + /** + * Returns a BigNumber whose value is the value of this BigNumber exponentiated by `n`, i.e. + * raised to the power `n`, and optionally modulo a modulus `m`. + * + * If `n` is negative the result is rounded according to the current `DECIMAL_PLACES` and + * `ROUNDING_MODE` settings. + * + * As the number of digits of the result of the power operation can grow so large so quickly, + * e.g. 123.456**10000 has over 50000 digits, the number of significant digits calculated is + * limited to the value of the `POW_PRECISION` setting (unless a modulus `m` is specified). + * + * By default `POW_PRECISION` is set to 0. This means that an unlimited number of significant + * digits will be calculated, and that the method's performance will decrease dramatically for + * larger exponents. + * + * If `m` is specified and the value of `m`, `n` and this BigNumber are integers and `n` is + * positive, then a fast modular exponentiation algorithm is used, otherwise the operation will + * be performed as `x.pow(n).modulo(m)` with a `POW_PRECISION` of 0. + * + * Throws if `n` is not an integer. + * + * ```ts + * Math.pow(0.7, 2) // 0.48999999999999994 + * x = new BigNumber(0.7) + * x.pow(2) // '0.49' + * BigNumber(3).pow(-2) // '0.11111111111111111111' + * ``` + * + * @param n The exponent, an integer. + * @param [m] The modulus. + */ + pow(n: BigNumber.Value, m?: BigNumber.Value): BigNumber; + pow(n: number, m?: BigNumber.Value): BigNumber; + + /** + * Returns a BigNumber whose value is the value of this BigNumber rounded to an integer using + * rounding mode `rm`. + * + * If `rm` is omitted, or is `null` or `undefined`, `ROUNDING_MODE` is used. + * + * Throws if `rm` is invalid. + * + * ```ts + * x = new BigNumber(123.456) + * x.integerValue() // '123' + * x.integerValue(BigNumber.ROUND_CEIL) // '124' + * y = new BigNumber(-12.7) + * y.integerValue() // '-13' + * x.integerValue(BigNumber.ROUND_DOWN) // '-12' + * ``` + * + * @param {BigNumber.RoundingMode} [rm] The roundng mode, an integer, 0 to 8. + */ + integerValue(rm?: BigNumber.RoundingMode): BigNumber; + + /** + * Returns `true` if the value of this BigNumber is equal to the value of `n`, otherwise returns + * `false`. + * + * As with JavaScript, `NaN` does not equal `NaN`. + * + * ```ts + * 0 === 1e-324 // true + * x = new BigNumber(0) + * x.isEqualTo('1e-324') // false + * BigNumber(-0).isEqualTo(x) // true ( -0 === 0 ) + * BigNumber(255).isEqualTo('ff', 16) // true + * + * y = new BigNumber(NaN) + * y.isEqualTo(NaN) // false + * ``` + * + * @param n A numeric value. + * @param [base] The base of n. + */ + isEqualTo(n: BigNumber.Value, base?: number): boolean; + + /** + * Returns `true` if the value of this BigNumber is equal to the value of `n`, otherwise returns + * `false`. + * + * As with JavaScript, `NaN` does not equal `NaN`. + * + * ```ts + * 0 === 1e-324 // true + * x = new BigNumber(0) + * x.eq('1e-324') // false + * BigNumber(-0).eq(x) // true ( -0 === 0 ) + * BigNumber(255).eq('ff', 16) // true + * + * y = new BigNumber(NaN) + * y.eq(NaN) // false + * ``` + * + * @param n A numeric value. + * @param [base] The base of n. + */ + eq(n: BigNumber.Value, base?: number): boolean; + + /** + * Returns `true` if the value of this BigNumber is a finite number, otherwise returns `false`. + * + * The only possible non-finite values of a BigNumber are `NaN`, `Infinity` and `-Infinity`. + * + * ```ts + * x = new BigNumber(1) + * x.isFinite() // true + * y = new BigNumber(Infinity) + * y.isFinite() // false + * ``` + */ + isFinite(): boolean; + + /** + * Returns `true` if the value of this BigNumber is greater than the value of `n`, otherwise + * returns `false`. + * + * ```ts + * 0.1 > (0.3 - 0.2) // true + * x = new BigNumber(0.1) + * x.isGreaterThan(BigNumber(0.3).minus(0.2)) // false + * BigNumber(0).isGreaterThan(x) // false + * BigNumber(11, 3).isGreaterThan(11.1, 2) // true + * ``` + * + * @param n A numeric value. + * @param [base] The base of n. + */ + isGreaterThan(n: BigNumber.Value, base?: number): boolean; + + /** + * Returns `true` if the value of this BigNumber is greater than the value of `n`, otherwise + * returns `false`. + * + * ```ts + * 0.1 > (0.3 - 0 // true + * x = new BigNumber(0.1) + * x.gt(BigNumber(0.3).minus(0.2)) // false + * BigNumber(0).gt(x) // false + * BigNumber(11, 3).gt(11.1, 2) // true + * ``` + * + * @param n A numeric value. + * @param [base] The base of n. + */ + gt(n: BigNumber.Value, base?: number): boolean; + + /** + * Returns `true` if the value of this BigNumber is greater than or equal to the value of `n`, + * otherwise returns `false`. + * + * ```ts + * (0.3 - 0.2) >= 0.1 // false + * x = new BigNumber(0.3).minus(0.2) + * x.isGreaterThanOrEqualTo(0.1) // true + * BigNumber(1).isGreaterThanOrEqualTo(x) // true + * BigNumber(10, 18).isGreaterThanOrEqualTo('i', 36) // true + * ``` + * + * @param n A numeric value. + * @param [base] The base of n. + */ + isGreaterThanOrEqualTo(n: BigNumber.Value, base?: number): boolean; + + /** + * Returns `true` if the value of this BigNumber is greater than or equal to the value of `n`, + * otherwise returns `false`. + * + * ```ts + * (0.3 - 0.2) >= 0.1 // false + * x = new BigNumber(0.3).minus(0.2) + * x.gte(0.1) // true + * BigNumber(1).gte(x) // true + * BigNumber(10, 18).gte('i', 36) // true + * ``` + * + * @param n A numeric value. + * @param [base] The base of n. + */ + gte(n: BigNumber.Value, base?: number): boolean; + + /** + * Returns `true` if the value of this BigNumber is an integer, otherwise returns `false`. + * + * ```ts + * x = new BigNumber(1) + * x.isInteger() // true + * y = new BigNumber(123.456) + * y.isInteger() // false + * ``` + */ + isInteger(): boolean; + + /** + * Returns `true` if the value of this BigNumber is less than the value of `n`, otherwise returns + * `false`. + * + * ```ts + * (0.3 - 0.2) < 0.1 // true + * x = new BigNumber(0.3).minus(0.2) + * x.isLessThan(0.1) // false + * BigNumber(0).isLessThan(x) // true + * BigNumber(11.1, 2).isLessThan(11, 3) // true + * ``` + * + * @param n A numeric value. + * @param [base] The base of n. + */ + isLessThan(n: BigNumber.Value, base?: number): boolean; + + /** + * Returns `true` if the value of this BigNumber is less than the value of `n`, otherwise returns + * `false`. + * + * ```ts + * (0.3 - 0.2) < 0.1 // true + * x = new BigNumber(0.3).minus(0.2) + * x.lt(0.1) // false + * BigNumber(0).lt(x) // true + * BigNumber(11.1, 2).lt(11, 3) // true + * ``` + * + * @param n A numeric value. + * @param [base] The base of n. + */ + lt(n: BigNumber.Value, base?: number): boolean; + + /** + * Returns `true` if the value of this BigNumber is less than or equal to the value of `n`, + * otherwise returns `false`. + * + * ```ts + * 0.1 <= (0.3 - 0.2) // false + * x = new BigNumber(0.1) + * x.isLessThanOrEqualTo(BigNumber(0.3).minus(0.2)) // true + * BigNumber(-1).isLessThanOrEqualTo(x) // true + * BigNumber(10, 18).isLessThanOrEqualTo('i', 36) // true + * ``` + * + * @param n A numeric value. + * @param [base] The base of n. + */ + isLessThanOrEqualTo(n: BigNumber.Value, base?: number): boolean; + + /** + * Returns `true` if the value of this BigNumber is less than or equal to the value of `n`, + * otherwise returns `false`. + * + * ```ts + * 0.1 <= (0.3 - 0.2) // false + * x = new BigNumber(0.1) + * x.lte(BigNumber(0.3).minus(0.2)) // true + * BigNumber(-1).lte(x) // true + * BigNumber(10, 18).lte('i', 36) // true + * ``` + * + * @param n A numeric value. + * @param [base] The base of n. + */ + lte(n: BigNumber.Value, base?: number): boolean; + + /** + * Returns `true` if the value of this BigNumber is `NaN`, otherwise returns `false`. + * + * ```ts + * x = new BigNumber(NaN) + * x.isNaN() // true + * y = new BigNumber('Infinity') + * y.isNaN() // false + * ``` + */ + isNaN(): boolean; + + /** + * Returns `true` if the value of this BigNumber is negative, otherwise returns `false`. + * + * ```ts + * x = new BigNumber(-0) + * x.isNegative() // true + * y = new BigNumber(2) + * y.isNegative() // false + * ``` + */ + isNegative(): boolean; + + /** + * Returns `true` if the value of this BigNumber is positive, otherwise returns `false`. + * + * ```ts + * x = new BigNumber(-0) + * x.isPositive() // false + * y = new BigNumber(2) + * y.isPositive() // true + * ``` + */ + isPositive(): boolean; + + /** + * Returns `true` if the value of this BigNumber is zero or minus zero, otherwise returns `false`. + * + * ```ts + * x = new BigNumber(-0) + * x.isZero() // true + * ``` + */ + isZero(): boolean; + + /** + * Returns a BigNumber whose value is the value of this BigNumber minus `n`. + * + * The return value is always exact and unrounded. + * + * ```ts + * 0.3 - 0.1 // 0.19999999999999998 + * x = new BigNumber(0.3) + * x.minus(0.1) // '0.2' + * x.minus(0.6, 20) // '0' + * ``` + * + * @param n A numeric value. + * @param [base] The base of n. + */ + minus(n: BigNumber.Value, base?: number): BigNumber; + + /** + * Returns a BigNumber whose value is the value of this BigNumber modulo `n`, i.e. the integer + * remainder of dividing this BigNumber by `n`. + * + * The value returned, and in particular its sign, is dependent on the value of the `MODULO_MODE` + * setting of this BigNumber constructor. If it is 1 (default value), the result will have the + * same sign as this BigNumber, and it will match that of Javascript's `%` operator (within the + * limits of double precision) and BigDecimal's `remainder` method. + * + * The return value is always exact and unrounded. + * + * See `MODULO_MODE` for a description of the other modulo modes. + * + * ```ts + * 1 % 0.9 // 0.09999999999999998 + * x = new BigNumber(1) + * x.modulo(0.9) // '0.1' + * y = new BigNumber(33) + * y.modulo('a', 33) // '3' + * ``` + * + * @param n A numeric value. + * @param [base] The base of n. + */ + modulo(n: BigNumber.Value, base?: number): BigNumber; + + /** + * Returns a BigNumber whose value is the value of this BigNumber modulo `n`, i.e. the integer + * remainder of dividing this BigNumber by `n`. + * + * The value returned, and in particular its sign, is dependent on the value of the `MODULO_MODE` + * setting of this BigNumber constructor. If it is 1 (default value), the result will have the + * same sign as this BigNumber, and it will match that of Javascript's `%` operator (within the + * limits of double precision) and BigDecimal's `remainder` method. + * + * The return value is always exact and unrounded. + * + * See `MODULO_MODE` for a description of the other modulo modes. + * + * ```ts + * 1 % 0.9 // 0.09999999999999998 + * x = new BigNumber(1) + * x.mod(0.9) // '0.1' + * y = new BigNumber(33) + * y.mod('a', 33) // '3' + * ``` + * + * @param n A numeric value. + * @param [base] The base of n. + */ + mod(n: BigNumber.Value, base?: number): BigNumber; + + /** + * Returns a BigNumber whose value is the value of this BigNumber multiplied by `n`. + * + * The return value is always exact and unrounded. + * + * ```ts + * 0.6 * 3 // 1.7999999999999998 + * x = new BigNumber(0.6) + * y = x.multipliedBy(3) // '1.8' + * BigNumber('7e+500').multipliedBy(y) // '1.26e+501' + * x.multipliedBy('-a', 16) // '-6' + * ``` + * + * @param n A numeric value. + * @param [base] The base of n. + */ + multipliedBy(n: BigNumber.Value, base?: number): BigNumber; + + /** + * Returns a BigNumber whose value is the value of this BigNumber multiplied by `n`. + * + * The return value is always exact and unrounded. + * + * ```ts + * 0.6 * 3 // 1.7999999999999998 + * x = new BigNumber(0.6) + * y = x.times(3) // '1.8' + * BigNumber('7e+500').times(y) // '1.26e+501' + * x.times('-a', 16) // '-6' + * ``` + * + * @param n A numeric value. + * @param [base] The base of n. + */ + times(n: BigNumber.Value, base?: number): BigNumber; + + /** + * Returns a BigNumber whose value is the value of this BigNumber negated, i.e. multiplied by -1. + * + * ```ts + * x = new BigNumber(1.8) + * x.negated() // '-1.8' + * y = new BigNumber(-1.3) + * y.negated() // '1.3' + * ``` + */ + negated(): BigNumber; + + /** + * Returns a BigNumber whose value is the value of this BigNumber plus `n`. + * + * The return value is always exact and unrounded. + * + * ```ts + * 0.1 + 0.2 // 0.30000000000000004 + * x = new BigNumber(0.1) + * y = x.plus(0.2) // '0.3' + * BigNumber(0.7).plus(x).plus(y) // '1' + * x.plus('0.1', 8) // '0.225' + * ``` + * + * @param n A numeric value. + * @param [base] The base of n. + */ + plus(n: BigNumber.Value, base?: number): BigNumber; + + /** + * Returns the number of significant digits of the value of this BigNumber, or `null` if the value + * of this BigNumber is ±`Infinity` or `NaN`. + * + * If `includeZeros` is true then any trailing zeros of the integer part of the value of this + * BigNumber are counted as significant digits, otherwise they are not. + * + * Throws if `includeZeros` is invalid. + * + * ```ts + * x = new BigNumber(9876.54321) + * x.precision() // 9 + * y = new BigNumber(987000) + * y.precision(false) // 3 + * y.precision(true) // 6 + * ``` + * + * @param [includeZeros] Whether to include integer trailing zeros in the significant digit count. + */ + precision(includeZeros?: boolean): number; + + /** + * Returns a BigNumber whose value is the value of this BigNumber rounded to a precision of + * `significantDigits` significant digits using rounding mode `roundingMode`. + * + * If `roundingMode` is omitted or is `null` or `undefined`, `ROUNDING_MODE` will be used. + * + * Throws if `significantDigits` or `roundingMode` is invalid. + * + * ```ts + * x = new BigNumber(9876.54321) + * x.precision(6) // '9876.54' + * x.precision(6, BigNumber.ROUND_UP) // '9876.55' + * x.precision(2) // '9900' + * x.precision(2, 1) // '9800' + * x // '9876.54321' + * ``` + * + * @param significantDigits Significant digits, integer, 1 to 1e+9. + * @param [roundingMode] Rounding mode, integer, 0 to 8. + */ + precision(significantDigits: number, roundingMode?: BigNumber.RoundingMode): BigNumber; + + /** + * Returns the number of significant digits of the value of this BigNumber, + * or `null` if the value of this BigNumber is ±`Infinity` or `NaN`. + * + * If `includeZeros` is true then any trailing zeros of the integer part of + * the value of this BigNumber are counted as significant digits, otherwise + * they are not. + * + * Throws if `includeZeros` is invalid. + * + * ```ts + * x = new BigNumber(9876.54321) + * x.sd() // 9 + * y = new BigNumber(987000) + * y.sd(false) // 3 + * y.sd(true) // 6 + * ``` + * + * @param [includeZeros] Whether to include integer trailing zeros in the significant digit count. + */ + sd(includeZeros?: boolean): number; + + /** + * Returns a BigNumber whose value is the value of this BigNumber rounded to a precision of + * `significantDigits` significant digits using rounding mode `roundingMode`. + * + * If `roundingMode` is omitted or is `null` or `undefined`, `ROUNDING_MODE` will be used. + * + * Throws if `significantDigits` or `roundingMode` is invalid. + * + * ```ts + * x = new BigNumber(9876.54321) + * x.sd(6) // '9876.54' + * x.sd(6, BigNumber.ROUND_UP) // '9876.55' + * x.sd(2) // '9900' + * x.sd(2, 1) // '9800' + * x // '9876.54321' + * ``` + * + * @param significantDigits Significant digits, integer, 1 to 1e+9. + * @param [roundingMode] Rounding mode, integer, 0 to 8. + */ + sd(significantDigits: number, roundingMode?: BigNumber.RoundingMode): BigNumber; + + /** + * Returns a BigNumber whose value is the value of this BigNumber shifted by `n` places. + * + * The shift is of the decimal point, i.e. of powers of ten, and is to the left if `n` is negative + * or to the right if `n` is positive. + * + * The return value is always exact and unrounded. + * + * Throws if `n` is invalid. + * + * ```ts + * x = new BigNumber(1.23) + * x.shiftedBy(3) // '1230' + * x.shiftedBy(-3) // '0.00123' + * ``` + * + * @param n The shift value, integer, -9007199254740991 to 9007199254740991. + */ + shiftedBy(n: number): BigNumber; + + /** + * Returns a BigNumber whose value is the square root of the value of this BigNumber, rounded + * according to the current `DECIMAL_PLACES` and `ROUNDING_MODE` settings. + * + * The return value will be correctly rounded, i.e. rounded as if the result was first calculated + * to an infinite number of correct digits before rounding. + * + * ```ts + * x = new BigNumber(16) + * x.squareRoot() // '4' + * y = new BigNumber(3) + * y.squareRoot() // '1.73205080756887729353' + * ``` + */ + squareRoot(): BigNumber; + + /** + * Returns a BigNumber whose value is the square root of the value of this BigNumber, rounded + * according to the current `DECIMAL_PLACES` and `ROUNDING_MODE` settings. + * + * The return value will be correctly rounded, i.e. rounded as if the result was first calculated + * to an infinite number of correct digits before rounding. + * + * ```ts + * x = new BigNumber(16) + * x.sqrt() // '4' + * y = new BigNumber(3) + * y.sqrt() // '1.73205080756887729353' + * ``` + */ + sqrt(): BigNumber; + + /** + * Returns a string representing the value of this BigNumber in exponential notation rounded using + * rounding mode `roundingMode` to `decimalPlaces` decimal places, i.e with one digit before the + * decimal point and `decimalPlaces` digits after it. + * + * If the value of this BigNumber in exponential notation has fewer than `decimalPlaces` fraction + * digits, the return value will be appended with zeros accordingly. + * + * If `decimalPlaces` is omitted, or is `null` or `undefined`, the number of digits after the + * decimal point defaults to the minimum number of digits necessary to represent the value + * exactly. + * + * If `roundingMode` is omitted or is `null` or `undefined`, `ROUNDING_MODE` is used. + * + * Throws if `decimalPlaces` or `roundingMode` is invalid. + * + * ```ts + * x = 45.6 + * y = new BigNumber(x) + * x.toExponential() // '4.56e+1' + * y.toExponential() // '4.56e+1' + * x.toExponential(0) // '5e+1' + * y.toExponential(0) // '5e+1' + * x.toExponential(1) // '4.6e+1' + * y.toExponential(1) // '4.6e+1' + * y.toExponential(1, 1) // '4.5e+1' (ROUND_DOWN) + * x.toExponential(3) // '4.560e+1' + * y.toExponential(3) // '4.560e+1' + * ``` + * + * @param [decimalPlaces] Decimal places, integer, 0 to 1e+9. + * @param [roundingMode] Rounding mode, integer, 0 to 8. + */ + toExponential(decimalPlaces: number, roundingMode?: BigNumber.RoundingMode): string; + toExponential(): string; + + /** + * Returns a string representing the value of this BigNumber in normal (fixed-point) notation + * rounded to `decimalPlaces` decimal places using rounding mode `roundingMode`. + * + * If the value of this BigNumber in normal notation has fewer than `decimalPlaces` fraction + * digits, the return value will be appended with zeros accordingly. + * + * Unlike `Number.prototype.toFixed`, which returns exponential notation if a number is greater or + * equal to 10**21, this method will always return normal notation. + * + * If `decimalPlaces` is omitted or is `null` or `undefined`, the return value will be unrounded + * and in normal notation. This is also unlike `Number.prototype.toFixed`, which returns the value + * to zero decimal places. It is useful when normal notation is required and the current + * `EXPONENTIAL_AT` setting causes `toString` to return exponential notation. + * + * If `roundingMode` is omitted or is `null` or `undefined`, `ROUNDING_MODE` is used. + * + * Throws if `decimalPlaces` or `roundingMode` is invalid. + * + * ```ts + * x = 3.456 + * y = new BigNumber(x) + * x.toFixed() // '3' + * y.toFixed() // '3.456' + * y.toFixed(0) // '3' + * x.toFixed(2) // '3.46' + * y.toFixed(2) // '3.46' + * y.toFixed(2, 1) // '3.45' (ROUND_DOWN) + * x.toFixed(5) // '3.45600' + * y.toFixed(5) // '3.45600' + * ``` + * + * @param [decimalPlaces] Decimal places, integer, 0 to 1e+9. + * @param [roundingMode] Rounding mode, integer, 0 to 8. + */ + toFixed(decimalPlaces: number, roundingMode?: BigNumber.RoundingMode): string; + toFixed(): string; + + /** + * Returns a string representing the value of this BigNumber in normal (fixed-point) notation + * rounded to `decimalPlaces` decimal places using rounding mode `roundingMode`, and formatted + * according to the properties of the `format` or `FORMAT` object. + * + * The formatting object may contain some or all of the properties shown in the examples below. + * + * If `decimalPlaces` is omitted or is `null` or `undefined`, then the return value is not + * rounded to a fixed number of decimal places. + * + * If `roundingMode` is omitted or is `null` or `undefined`, `ROUNDING_MODE` is used. + * + * If `format` is omitted or is `null` or `undefined`, `FORMAT` is used. + * + * Throws if `decimalPlaces`, `roundingMode`, or `format` is invalid. + * + * ```ts + * fmt = { + * decimalSeparator: '.', + * groupSeparator: ',', + * groupSize: 3, + * secondaryGroupSize: 0, + * fractionGroupSeparator: ' ', + * fractionGroupSize: 0 + * } + * + * x = new BigNumber('123456789.123456789') + * + * // Set the global formatting options + * BigNumber.config({ FORMAT: fmt }) + * + * x.toFormat() // '123,456,789.123456789' + * x.toFormat(3) // '123,456,789.123' + * + * // If a reference to the object assigned to FORMAT has been retained, + * // the format properties can be changed directly + * fmt.groupSeparator = ' ' + * fmt.fractionGroupSize = 5 + * x.toFormat() // '123 456 789.12345 6789' + * + * // Alternatively, pass the formatting options as an argument + * fmt = { + * decimalSeparator: ',', + * groupSeparator: '.', + * groupSize: 3, + * secondaryGroupSize: 2 + * } + * + * x.toFormat() // '123 456 789.12345 6789' + * x.toFormat(fmt) // '12.34.56.789,123456789' + * x.toFormat(2, fmt) // '12.34.56.789,12' + * x.toFormat(3, BigNumber.ROUND_UP, fmt) // '12.34.56.789,124' + * ``` + * + * @param [decimalPlaces] Decimal places, integer, 0 to 1e+9. + * @param [roundingMode] Rounding mode, integer, 0 to 8. + * @param [format] Formatting options object. See `BigNumber.Format`. + */ + toFormat(decimalPlaces: number, roundingMode: BigNumber.RoundingMode, format?: BigNumber.Format): string; + toFormat(decimalPlaces: number, roundingMode?: BigNumber.RoundingMode): string; + toFormat(decimalPlaces?: number): string; + toFormat(decimalPlaces: number, format: BigNumber.Format): string; + toFormat(format: BigNumber.Format): string; + + /** + * Returns an array of two BigNumbers representing the value of this BigNumber as a simple + * fraction with an integer numerator and an integer denominator. + * The denominator will be a positive non-zero value less than or equal to `max_denominator`. + * If a maximum denominator, `max_denominator`, is not specified, or is `null` or `undefined`, the + * denominator will be the lowest value necessary to represent the number exactly. + * + * Throws if `max_denominator` is invalid. + * + * ```ts + * x = new BigNumber(1.75) + * x.toFraction() // '7, 4' + * + * pi = new BigNumber('3.14159265358') + * pi.toFraction() // '157079632679,50000000000' + * pi.toFraction(100000) // '312689, 99532' + * pi.toFraction(10000) // '355, 113' + * pi.toFraction(100) // '311, 99' + * pi.toFraction(10) // '22, 7' + * pi.toFraction(1) // '3, 1' + * ``` + * + * @param [max_denominator] The maximum denominator, integer > 0, or Infinity. + */ + toFraction(max_denominator?: BigNumber.Value): [BigNumber, BigNumber]; + + /** As `valueOf`. */ + toJSON(): string; + + /** + * Returns the value of this BigNumber as a JavaScript primitive number. + * + * Using the unary plus operator gives the same result. + * + * ```ts + * x = new BigNumber(456.789) + * x.toNumber() // 456.789 + * +x // 456.789 + * + * y = new BigNumber('45987349857634085409857349856430985') + * y.toNumber() // 4.598734985763409e+34 + * + * z = new BigNumber(-0) + * 1 / z.toNumber() // -Infinity + * 1 / +z // -Infinity + * ``` + */ + toNumber(): number; + + /** + * Returns a string representing the value of this BigNumber rounded to `significantDigits` + * significant digits using rounding mode `roundingMode`. + * + * If `significantDigits` is less than the number of digits necessary to represent the integer + * part of the value in normal (fixed-point) notation, then exponential notation is used. + * + * If `significantDigits` is omitted, or is `null` or `undefined`, then the return value is the + * same as `n.toString()`. + * + * If `roundingMode` is omitted or is `null` or `undefined`, `ROUNDING_MODE` is used. + * + * Throws if `significantDigits` or `roundingMode` is invalid. + * + * ```ts + * x = 45.6 + * y = new BigNumber(x) + * x.toPrecision() // '45.6' + * y.toPrecision() // '45.6' + * x.toPrecision(1) // '5e+1' + * y.toPrecision(1) // '5e+1' + * y.toPrecision(2, 0) // '4.6e+1' (ROUND_UP) + * y.toPrecision(2, 1) // '4.5e+1' (ROUND_DOWN) + * x.toPrecision(5) // '45.600' + * y.toPrecision(5) // '45.600' + * ``` + * + * @param [significantDigits] Significant digits, integer, 1 to 1e+9. + * @param [roundingMode] Rounding mode, integer 0 to 8. + */ + toPrecision(significantDigits: number, roundingMode?: BigNumber.RoundingMode): string; + toPrecision(): string; + + /** + * Returns a string representing the value of this BigNumber in base `base`, or base 10 if `base` + * is omitted or is `null` or `undefined`. + * + * For bases above 10, and using the default base conversion alphabet (see `ALPHABET`), values + * from 10 to 35 are represented by a-z (the same as `Number.prototype.toString`). + * + * If a base is specified the value is rounded according to the current `DECIMAL_PLACES` and + * `ROUNDING_MODE` settings, otherwise it is not. + * + * If a base is not specified, and this BigNumber has a positive exponent that is equal to or + * greater than the positive component of the current `EXPONENTIAL_AT` setting, or a negative + * exponent equal to or less than the negative component of the setting, then exponential notation + * is returned. + * + * If `base` is `null` or `undefined` it is ignored. + * + * Throws if `base` is invalid. + * + * ```ts + * x = new BigNumber(750000) + * x.toString() // '750000' + * BigNumber.config({ EXPONENTIAL_AT: 5 }) + * x.toString() // '7.5e+5' + * + * y = new BigNumber(362.875) + * y.toString(2) // '101101010.111' + * y.toString(9) // '442.77777777777777777778' + * y.toString(32) // 'ba.s' + * + * BigNumber.config({ DECIMAL_PLACES: 4 }); + * z = new BigNumber('1.23456789') + * z.toString() // '1.23456789' + * z.toString(10) // '1.2346' + * ``` + * + * @param [base] The base, integer, 2 to 36 (or `ALPHABET.length`, see `ALPHABET`). + */ + toString(base?: number): string; + + /** + * As `toString`, but does not accept a base argument and includes the minus sign for negative + * zero. + * + * ``ts + * x = new BigNumber('-0') + * x.toString() // '0' + * x.valueOf() // '-0' + * y = new BigNumber('1.777e+457') + * y.valueOf() // '1.777e+457' + * ``` + */ + valueOf(): string; + + /** Helps ES6 import. */ + private static readonly default?: BigNumber.Constructor; + + /** Helps ES6 import. */ + private static readonly BigNumber?: BigNumber.Constructor; + + /** Rounds away from zero. */ + static readonly ROUND_UP: 0; + + /** Rounds towards zero. */ + static readonly ROUND_DOWN: 1; + + /** Rounds towards Infinity. */ + static readonly ROUND_CEIL: 2; + + /** Rounds towards -Infinity. */ + static readonly ROUND_FLOOR: 3; + + /** Rounds towards nearest neighbour. If equidistant, rounds away from zero . */ + static readonly ROUND_HALF_UP: 4; + + /** Rounds towards nearest neighbour. If equidistant, rounds towards zero. */ + static readonly ROUND_HALF_DOWN: 5; + + /** Rounds towards nearest neighbour. If equidistant, rounds towards even neighbour. */ + static readonly ROUND_HALF_EVEN: 6; + + /** Rounds towards nearest neighbour. If equidistant, rounds towards Infinity. */ + static readonly ROUND_HALF_CEIL: 7; + + /** Rounds towards nearest neighbour. If equidistant, rounds towards -Infinity. */ + static readonly ROUND_HALF_FLOOR: 8; + + /** See `MODULO_MODE`. */ + static readonly EUCLID: 9; + + /** + * To aid in debugging, if a `BigNumber.DEBUG` property is `true` then an error will be thrown + * if the BigNumber constructor receives an invalid `BigNumber.Value`, or if `BigNumber.isBigNumber` + * receives a BigNumber instance that is malformed. + * + * ```ts + * // No error, and BigNumber NaN is returned. + * new BigNumber('blurgh') // 'NaN' + * new BigNumber(9, 2) // 'NaN' + * BigNumber.DEBUG = true + * new BigNumber('blurgh') // '[BigNumber Error] Not a number' + * new BigNumber(9, 2) // '[BigNumber Error] Not a base 2 number' + * ``` + * + * An error will also be thrown if a `BigNumber.Value` is of type number with more than 15 + * significant digits, as calling `toString` or `valueOf` on such numbers may not result + * in the intended value. + * + * ```ts + * console.log(823456789123456.3) // 823456789123456.2 + * // No error, and the returned BigNumber does not have the same value as the number literal. + * new BigNumber(823456789123456.3) // '823456789123456.2' + * BigNumber.DEBUG = true + * new BigNumber(823456789123456.3) + * // '[BigNumber Error] Number primitive has more than 15 significant digits' + * ``` + * + * Check that a BigNumber instance is well-formed: + * + * ```ts + * x = new BigNumber(10) + * + * BigNumber.DEBUG = false + * // Change x.c to an illegitimate value. + * x.c = NaN + * // No error, as BigNumber.DEBUG is false. + * BigNumber.isBigNumber(x) // true + * + * BigNumber.DEBUG = true + * BigNumber.isBigNumber(x) // '[BigNumber Error] Invalid BigNumber' + * ``` + */ + static DEBUG?: boolean; + + /** + * Returns a new independent BigNumber constructor with configuration as described by `object`, or + * with the default configuration if object is `null` or `undefined`. + * + * Throws if `object` is not an object. + * + * ```ts + * BigNumber.config({ DECIMAL_PLACES: 5 }) + * BN = BigNumber.clone({ DECIMAL_PLACES: 9 }) + * + * x = new BigNumber(1) + * y = new BN(1) + * + * x.div(3) // 0.33333 + * y.div(3) // 0.333333333 + * + * // BN = BigNumber.clone({ DECIMAL_PLACES: 9 }) is equivalent to: + * BN = BigNumber.clone() + * BN.config({ DECIMAL_PLACES: 9 }) + * ``` + * + * @param [object] The configuration object. + */ + static clone(object?: BigNumber.Config): BigNumber.Constructor; + + /** + * Configures the settings that apply to this BigNumber constructor. + * + * The configuration object, `object`, contains any number of the properties shown in the example + * below. + * + * Returns an object with the above properties and their current values. + * + * Throws if `object` is not an object, or if an invalid value is assigned to one or more of the + * properties. + * + * ```ts + * BigNumber.config({ + * DECIMAL_PLACES: 40, + * ROUNDING_MODE: BigNumber.ROUND_HALF_CEIL, + * EXPONENTIAL_AT: [-10, 20], + * RANGE: [-500, 500], + * CRYPTO: true, + * MODULO_MODE: BigNumber.ROUND_FLOOR, + * POW_PRECISION: 80, + * FORMAT: { + * groupSize: 3, + * groupSeparator: ' ', + * decimalSeparator: ',' + * }, + * ALPHABET: '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ$_' + * }); + * + * BigNumber.config().DECIMAL_PLACES // 40 + * ``` + * + * @param object The configuration object. + */ + static config(object: BigNumber.Config): BigNumber.Config; + + /** + * Returns `true` if `value` is a BigNumber instance, otherwise returns `false`. + * + * If `BigNumber.DEBUG` is `true`, throws if a BigNumber instance is not well-formed. + * + * ```ts + * x = 42 + * y = new BigNumber(x) + * + * BigNumber.isBigNumber(x) // false + * y instanceof BigNumber // true + * BigNumber.isBigNumber(y) // true + * + * BN = BigNumber.clone(); + * z = new BN(x) + * z instanceof BigNumber // false + * BigNumber.isBigNumber(z) // true + * ``` + * + * @param value The value to test. + */ + static isBigNumber(value: any): value is BigNumber; + + /** + * Returns a BigNumber whose value is the maximum of the arguments. + * + * The return value is always exact and unrounded. + * + * ```ts + * x = new BigNumber('3257869345.0378653') + * BigNumber.maximum(4e9, x, '123456789.9') // '4000000000' + * + * arr = [12, '13', new BigNumber(14)] + * BigNumber.maximum.apply(null, arr) // '14' + * ``` + * + * @param n A numeric value. + */ + static maximum(...n: BigNumber.Value[]): BigNumber; + + /** + * Returns a BigNumber whose value is the maximum of the arguments. + * + * The return value is always exact and unrounded. + * + * ```ts + * x = new BigNumber('3257869345.0378653') + * BigNumber.max(4e9, x, '123456789.9') // '4000000000' + * + * arr = [12, '13', new BigNumber(14)] + * BigNumber.max.apply(null, arr) // '14' + * ``` + * + * @param n A numeric value. + */ + static max(...n: BigNumber.Value[]): BigNumber; + + /** + * Returns a BigNumber whose value is the minimum of the arguments. + * + * The return value is always exact and unrounded. + * + * ```ts + * x = new BigNumber('3257869345.0378653') + * BigNumber.minimum(4e9, x, '123456789.9') // '123456789.9' + * + * arr = [2, new BigNumber(-14), '-15.9999', -12] + * BigNumber.minimum.apply(null, arr) // '-15.9999' + * ``` + * + * @param n A numeric value. + */ + static minimum(...n: BigNumber.Value[]): BigNumber; + + /** + * Returns a BigNumber whose value is the minimum of the arguments. + * + * The return value is always exact and unrounded. + * + * ```ts + * x = new BigNumber('3257869345.0378653') + * BigNumber.min(4e9, x, '123456789.9') // '123456789.9' + * + * arr = [2, new BigNumber(-14), '-15.9999', -12] + * BigNumber.min.apply(null, arr) // '-15.9999' + * ``` + * + * @param n A numeric value. + */ + static min(...n: BigNumber.Value[]): BigNumber; + + /** + * Returns a new BigNumber with a pseudo-random value equal to or greater than 0 and less than 1. + * + * The return value will have `decimalPlaces` decimal places, or less if trailing zeros are + * produced. If `decimalPlaces` is omitted, the current `DECIMAL_PLACES` setting will be used. + * + * Depending on the value of this BigNumber constructor's `CRYPTO` setting and the support for the + * `crypto` object in the host environment, the random digits of the return value are generated by + * either `Math.random` (fastest), `crypto.getRandomValues` (Web Cryptography API in recent + * browsers) or `crypto.randomBytes` (Node.js). + * + * To be able to set `CRYPTO` to true when using Node.js, the `crypto` object must be available + * globally: + * + * ```ts + * global.crypto = require('crypto') + * ``` + * + * If `CRYPTO` is true, i.e. one of the `crypto` methods is to be used, the value of a returned + * BigNumber should be cryptographically secure and statistically indistinguishable from a random + * value. + * + * Throws if `decimalPlaces` is invalid. + * + * ```ts + * BigNumber.config({ DECIMAL_PLACES: 10 }) + * BigNumber.random() // '0.4117936847' + * BigNumber.random(20) // '0.78193327636914089009' + * ``` + * + * @param [decimalPlaces] Decimal places, integer, 0 to 1e+9. + */ + static random(decimalPlaces?: number): BigNumber; + + /** + * Returns a BigNumber whose value is the sum of the arguments. + * + * The return value is always exact and unrounded. + * + * ```ts + * x = new BigNumber('3257869345.0378653') + * BigNumber.sum(4e9, x, '123456789.9') // '7381326134.9378653' + * + * arr = [2, new BigNumber(14), '15.9999', 12] + * BigNumber.sum.apply(null, arr) // '43.9999' + * ``` + * + * @param n A numeric value. + */ + static sum(...n: BigNumber.Value[]): BigNumber; + + /** + * Configures the settings that apply to this BigNumber constructor. + * + * The configuration object, `object`, contains any number of the properties shown in the example + * below. + * + * Returns an object with the above properties and their current values. + * + * Throws if `object` is not an object, or if an invalid value is assigned to one or more of the + * properties. + * + * ```ts + * BigNumber.set({ + * DECIMAL_PLACES: 40, + * ROUNDING_MODE: BigNumber.ROUND_HALF_CEIL, + * EXPONENTIAL_AT: [-10, 20], + * RANGE: [-500, 500], + * CRYPTO: true, + * MODULO_MODE: BigNumber.ROUND_FLOOR, + * POW_PRECISION: 80, + * FORMAT: { + * groupSize: 3, + * groupSeparator: ' ', + * decimalSeparator: ',' + * }, + * ALPHABET: '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ$_' + * }); + * + * BigNumber.set().DECIMAL_PLACES // 40 + * ``` + * + * @param object The configuration object. + */ + static set(object: BigNumber.Config): BigNumber.Config; +} diff --git a/ts-ticket-office-service/node_modules/bignumber.js/bignumber.js b/ts-ticket-office-service/node_modules/bignumber.js/bignumber.js new file mode 100644 index 000000000..f2ea883f3 --- /dev/null +++ b/ts-ticket-office-service/node_modules/bignumber.js/bignumber.js @@ -0,0 +1,2902 @@ +;(function (globalObject) { + 'use strict'; + +/* + * bignumber.js v9.0.0 + * A JavaScript library for arbitrary-precision arithmetic. + * https://github.com/MikeMcl/bignumber.js + * Copyright (c) 2019 Michael Mclaughlin + * MIT Licensed. + * + * BigNumber.prototype methods | BigNumber methods + * | + * absoluteValue abs | clone + * comparedTo | config set + * decimalPlaces dp | DECIMAL_PLACES + * dividedBy div | ROUNDING_MODE + * dividedToIntegerBy idiv | EXPONENTIAL_AT + * exponentiatedBy pow | RANGE + * integerValue | CRYPTO + * isEqualTo eq | MODULO_MODE + * isFinite | POW_PRECISION + * isGreaterThan gt | FORMAT + * isGreaterThanOrEqualTo gte | ALPHABET + * isInteger | isBigNumber + * isLessThan lt | maximum max + * isLessThanOrEqualTo lte | minimum min + * isNaN | random + * isNegative | sum + * isPositive | + * isZero | + * minus | + * modulo mod | + * multipliedBy times | + * negated | + * plus | + * precision sd | + * shiftedBy | + * squareRoot sqrt | + * toExponential | + * toFixed | + * toFormat | + * toFraction | + * toJSON | + * toNumber | + * toPrecision | + * toString | + * valueOf | + * + */ + + + var BigNumber, + isNumeric = /^-?(?:\d+(?:\.\d*)?|\.\d+)(?:e[+-]?\d+)?$/i, + mathceil = Math.ceil, + mathfloor = Math.floor, + + bignumberError = '[BigNumber Error] ', + tooManyDigits = bignumberError + 'Number primitive has more than 15 significant digits: ', + + BASE = 1e14, + LOG_BASE = 14, + MAX_SAFE_INTEGER = 0x1fffffffffffff, // 2^53 - 1 + // MAX_INT32 = 0x7fffffff, // 2^31 - 1 + POWS_TEN = [1, 10, 100, 1e3, 1e4, 1e5, 1e6, 1e7, 1e8, 1e9, 1e10, 1e11, 1e12, 1e13], + SQRT_BASE = 1e7, + + // EDITABLE + // The limit on the value of DECIMAL_PLACES, TO_EXP_NEG, TO_EXP_POS, MIN_EXP, MAX_EXP, and + // the arguments to toExponential, toFixed, toFormat, and toPrecision. + MAX = 1E9; // 0 to MAX_INT32 + + + /* + * Create and return a BigNumber constructor. + */ + function clone(configObject) { + var div, convertBase, parseNumeric, + P = BigNumber.prototype = { constructor: BigNumber, toString: null, valueOf: null }, + ONE = new BigNumber(1), + + + //----------------------------- EDITABLE CONFIG DEFAULTS ------------------------------- + + + // The default values below must be integers within the inclusive ranges stated. + // The values can also be changed at run-time using BigNumber.set. + + // The maximum number of decimal places for operations involving division. + DECIMAL_PLACES = 20, // 0 to MAX + + // The rounding mode used when rounding to the above decimal places, and when using + // toExponential, toFixed, toFormat and toPrecision, and round (default value). + // UP 0 Away from zero. + // DOWN 1 Towards zero. + // CEIL 2 Towards +Infinity. + // FLOOR 3 Towards -Infinity. + // HALF_UP 4 Towards nearest neighbour. If equidistant, up. + // HALF_DOWN 5 Towards nearest neighbour. If equidistant, down. + // HALF_EVEN 6 Towards nearest neighbour. If equidistant, towards even neighbour. + // HALF_CEIL 7 Towards nearest neighbour. If equidistant, towards +Infinity. + // HALF_FLOOR 8 Towards nearest neighbour. If equidistant, towards -Infinity. + ROUNDING_MODE = 4, // 0 to 8 + + // EXPONENTIAL_AT : [TO_EXP_NEG , TO_EXP_POS] + + // The exponent value at and beneath which toString returns exponential notation. + // Number type: -7 + TO_EXP_NEG = -7, // 0 to -MAX + + // The exponent value at and above which toString returns exponential notation. + // Number type: 21 + TO_EXP_POS = 21, // 0 to MAX + + // RANGE : [MIN_EXP, MAX_EXP] + + // The minimum exponent value, beneath which underflow to zero occurs. + // Number type: -324 (5e-324) + MIN_EXP = -1e7, // -1 to -MAX + + // The maximum exponent value, above which overflow to Infinity occurs. + // Number type: 308 (1.7976931348623157e+308) + // For MAX_EXP > 1e7, e.g. new BigNumber('1e100000000').plus(1) may be slow. + MAX_EXP = 1e7, // 1 to MAX + + // Whether to use cryptographically-secure random number generation, if available. + CRYPTO = false, // true or false + + // The modulo mode used when calculating the modulus: a mod n. + // The quotient (q = a / n) is calculated according to the corresponding rounding mode. + // The remainder (r) is calculated as: r = a - n * q. + // + // UP 0 The remainder is positive if the dividend is negative, else is negative. + // DOWN 1 The remainder has the same sign as the dividend. + // This modulo mode is commonly known as 'truncated division' and is + // equivalent to (a % n) in JavaScript. + // FLOOR 3 The remainder has the same sign as the divisor (Python %). + // HALF_EVEN 6 This modulo mode implements the IEEE 754 remainder function. + // EUCLID 9 Euclidian division. q = sign(n) * floor(a / abs(n)). + // The remainder is always positive. + // + // The truncated division, floored division, Euclidian division and IEEE 754 remainder + // modes are commonly used for the modulus operation. + // Although the other rounding modes can also be used, they may not give useful results. + MODULO_MODE = 1, // 0 to 9 + + // The maximum number of significant digits of the result of the exponentiatedBy operation. + // If POW_PRECISION is 0, there will be unlimited significant digits. + POW_PRECISION = 0, // 0 to MAX + + // The format specification used by the BigNumber.prototype.toFormat method. + FORMAT = { + prefix: '', + groupSize: 3, + secondaryGroupSize: 0, + groupSeparator: ',', + decimalSeparator: '.', + fractionGroupSize: 0, + fractionGroupSeparator: '\xA0', // non-breaking space + suffix: '' + }, + + // The alphabet used for base conversion. It must be at least 2 characters long, with no '+', + // '-', '.', whitespace, or repeated character. + // '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ$_' + ALPHABET = '0123456789abcdefghijklmnopqrstuvwxyz'; + + + //------------------------------------------------------------------------------------------ + + + // CONSTRUCTOR + + + /* + * The BigNumber constructor and exported function. + * Create and return a new instance of a BigNumber object. + * + * v {number|string|BigNumber} A numeric value. + * [b] {number} The base of v. Integer, 2 to ALPHABET.length inclusive. + */ + function BigNumber(v, b) { + var alphabet, c, caseChanged, e, i, isNum, len, str, + x = this; + + // Enable constructor call without `new`. + if (!(x instanceof BigNumber)) return new BigNumber(v, b); + + if (b == null) { + + if (v && v._isBigNumber === true) { + x.s = v.s; + + if (!v.c || v.e > MAX_EXP) { + x.c = x.e = null; + } else if (v.e < MIN_EXP) { + x.c = [x.e = 0]; + } else { + x.e = v.e; + x.c = v.c.slice(); + } + + return; + } + + if ((isNum = typeof v == 'number') && v * 0 == 0) { + + // Use `1 / n` to handle minus zero also. + x.s = 1 / v < 0 ? (v = -v, -1) : 1; + + // Fast path for integers, where n < 2147483648 (2**31). + if (v === ~~v) { + for (e = 0, i = v; i >= 10; i /= 10, e++); + + if (e > MAX_EXP) { + x.c = x.e = null; + } else { + x.e = e; + x.c = [v]; + } + + return; + } + + str = String(v); + } else { + + if (!isNumeric.test(str = String(v))) return parseNumeric(x, str, isNum); + + x.s = str.charCodeAt(0) == 45 ? (str = str.slice(1), -1) : 1; + } + + // Decimal point? + if ((e = str.indexOf('.')) > -1) str = str.replace('.', ''); + + // Exponential form? + if ((i = str.search(/e/i)) > 0) { + + // Determine exponent. + if (e < 0) e = i; + e += +str.slice(i + 1); + str = str.substring(0, i); + } else if (e < 0) { + + // Integer. + e = str.length; + } + + } else { + + // '[BigNumber Error] Base {not a primitive number|not an integer|out of range}: {b}' + intCheck(b, 2, ALPHABET.length, 'Base'); + + // Allow exponential notation to be used with base 10 argument, while + // also rounding to DECIMAL_PLACES as with other bases. + if (b == 10) { + x = new BigNumber(v); + return round(x, DECIMAL_PLACES + x.e + 1, ROUNDING_MODE); + } + + str = String(v); + + if (isNum = typeof v == 'number') { + + // Avoid potential interpretation of Infinity and NaN as base 44+ values. + if (v * 0 != 0) return parseNumeric(x, str, isNum, b); + + x.s = 1 / v < 0 ? (str = str.slice(1), -1) : 1; + + // '[BigNumber Error] Number primitive has more than 15 significant digits: {n}' + if (BigNumber.DEBUG && str.replace(/^0\.0*|\./, '').length > 15) { + throw Error + (tooManyDigits + v); + } + } else { + x.s = str.charCodeAt(0) === 45 ? (str = str.slice(1), -1) : 1; + } + + alphabet = ALPHABET.slice(0, b); + e = i = 0; + + // Check that str is a valid base b number. + // Don't use RegExp, so alphabet can contain special characters. + for (len = str.length; i < len; i++) { + if (alphabet.indexOf(c = str.charAt(i)) < 0) { + if (c == '.') { + + // If '.' is not the first character and it has not be found before. + if (i > e) { + e = len; + continue; + } + } else if (!caseChanged) { + + // Allow e.g. hexadecimal 'FF' as well as 'ff'. + if (str == str.toUpperCase() && (str = str.toLowerCase()) || + str == str.toLowerCase() && (str = str.toUpperCase())) { + caseChanged = true; + i = -1; + e = 0; + continue; + } + } + + return parseNumeric(x, String(v), isNum, b); + } + } + + // Prevent later check for length on converted number. + isNum = false; + str = convertBase(str, b, 10, x.s); + + // Decimal point? + if ((e = str.indexOf('.')) > -1) str = str.replace('.', ''); + else e = str.length; + } + + // Determine leading zeros. + for (i = 0; str.charCodeAt(i) === 48; i++); + + // Determine trailing zeros. + for (len = str.length; str.charCodeAt(--len) === 48;); + + if (str = str.slice(i, ++len)) { + len -= i; + + // '[BigNumber Error] Number primitive has more than 15 significant digits: {n}' + if (isNum && BigNumber.DEBUG && + len > 15 && (v > MAX_SAFE_INTEGER || v !== mathfloor(v))) { + throw Error + (tooManyDigits + (x.s * v)); + } + + // Overflow? + if ((e = e - i - 1) > MAX_EXP) { + + // Infinity. + x.c = x.e = null; + + // Underflow? + } else if (e < MIN_EXP) { + + // Zero. + x.c = [x.e = 0]; + } else { + x.e = e; + x.c = []; + + // Transform base + + // e is the base 10 exponent. + // i is where to slice str to get the first element of the coefficient array. + i = (e + 1) % LOG_BASE; + if (e < 0) i += LOG_BASE; // i < 1 + + if (i < len) { + if (i) x.c.push(+str.slice(0, i)); + + for (len -= LOG_BASE; i < len;) { + x.c.push(+str.slice(i, i += LOG_BASE)); + } + + i = LOG_BASE - (str = str.slice(i)).length; + } else { + i -= len; + } + + for (; i--; str += '0'); + x.c.push(+str); + } + } else { + + // Zero. + x.c = [x.e = 0]; + } + } + + + // CONSTRUCTOR PROPERTIES + + + BigNumber.clone = clone; + + BigNumber.ROUND_UP = 0; + BigNumber.ROUND_DOWN = 1; + BigNumber.ROUND_CEIL = 2; + BigNumber.ROUND_FLOOR = 3; + BigNumber.ROUND_HALF_UP = 4; + BigNumber.ROUND_HALF_DOWN = 5; + BigNumber.ROUND_HALF_EVEN = 6; + BigNumber.ROUND_HALF_CEIL = 7; + BigNumber.ROUND_HALF_FLOOR = 8; + BigNumber.EUCLID = 9; + + + /* + * Configure infrequently-changing library-wide settings. + * + * Accept an object with the following optional properties (if the value of a property is + * a number, it must be an integer within the inclusive range stated): + * + * DECIMAL_PLACES {number} 0 to MAX + * ROUNDING_MODE {number} 0 to 8 + * EXPONENTIAL_AT {number|number[]} -MAX to MAX or [-MAX to 0, 0 to MAX] + * RANGE {number|number[]} -MAX to MAX (not zero) or [-MAX to -1, 1 to MAX] + * CRYPTO {boolean} true or false + * MODULO_MODE {number} 0 to 9 + * POW_PRECISION {number} 0 to MAX + * ALPHABET {string} A string of two or more unique characters which does + * not contain '.'. + * FORMAT {object} An object with some of the following properties: + * prefix {string} + * groupSize {number} + * secondaryGroupSize {number} + * groupSeparator {string} + * decimalSeparator {string} + * fractionGroupSize {number} + * fractionGroupSeparator {string} + * suffix {string} + * + * (The values assigned to the above FORMAT object properties are not checked for validity.) + * + * E.g. + * BigNumber.config({ DECIMAL_PLACES : 20, ROUNDING_MODE : 4 }) + * + * Ignore properties/parameters set to null or undefined, except for ALPHABET. + * + * Return an object with the properties current values. + */ + BigNumber.config = BigNumber.set = function (obj) { + var p, v; + + if (obj != null) { + + if (typeof obj == 'object') { + + // DECIMAL_PLACES {number} Integer, 0 to MAX inclusive. + // '[BigNumber Error] DECIMAL_PLACES {not a primitive number|not an integer|out of range}: {v}' + if (obj.hasOwnProperty(p = 'DECIMAL_PLACES')) { + v = obj[p]; + intCheck(v, 0, MAX, p); + DECIMAL_PLACES = v; + } + + // ROUNDING_MODE {number} Integer, 0 to 8 inclusive. + // '[BigNumber Error] ROUNDING_MODE {not a primitive number|not an integer|out of range}: {v}' + if (obj.hasOwnProperty(p = 'ROUNDING_MODE')) { + v = obj[p]; + intCheck(v, 0, 8, p); + ROUNDING_MODE = v; + } + + // EXPONENTIAL_AT {number|number[]} + // Integer, -MAX to MAX inclusive or + // [integer -MAX to 0 inclusive, 0 to MAX inclusive]. + // '[BigNumber Error] EXPONENTIAL_AT {not a primitive number|not an integer|out of range}: {v}' + if (obj.hasOwnProperty(p = 'EXPONENTIAL_AT')) { + v = obj[p]; + if (v && v.pop) { + intCheck(v[0], -MAX, 0, p); + intCheck(v[1], 0, MAX, p); + TO_EXP_NEG = v[0]; + TO_EXP_POS = v[1]; + } else { + intCheck(v, -MAX, MAX, p); + TO_EXP_NEG = -(TO_EXP_POS = v < 0 ? -v : v); + } + } + + // RANGE {number|number[]} Non-zero integer, -MAX to MAX inclusive or + // [integer -MAX to -1 inclusive, integer 1 to MAX inclusive]. + // '[BigNumber Error] RANGE {not a primitive number|not an integer|out of range|cannot be zero}: {v}' + if (obj.hasOwnProperty(p = 'RANGE')) { + v = obj[p]; + if (v && v.pop) { + intCheck(v[0], -MAX, -1, p); + intCheck(v[1], 1, MAX, p); + MIN_EXP = v[0]; + MAX_EXP = v[1]; + } else { + intCheck(v, -MAX, MAX, p); + if (v) { + MIN_EXP = -(MAX_EXP = v < 0 ? -v : v); + } else { + throw Error + (bignumberError + p + ' cannot be zero: ' + v); + } + } + } + + // CRYPTO {boolean} true or false. + // '[BigNumber Error] CRYPTO not true or false: {v}' + // '[BigNumber Error] crypto unavailable' + if (obj.hasOwnProperty(p = 'CRYPTO')) { + v = obj[p]; + if (v === !!v) { + if (v) { + if (typeof crypto != 'undefined' && crypto && + (crypto.getRandomValues || crypto.randomBytes)) { + CRYPTO = v; + } else { + CRYPTO = !v; + throw Error + (bignumberError + 'crypto unavailable'); + } + } else { + CRYPTO = v; + } + } else { + throw Error + (bignumberError + p + ' not true or false: ' + v); + } + } + + // MODULO_MODE {number} Integer, 0 to 9 inclusive. + // '[BigNumber Error] MODULO_MODE {not a primitive number|not an integer|out of range}: {v}' + if (obj.hasOwnProperty(p = 'MODULO_MODE')) { + v = obj[p]; + intCheck(v, 0, 9, p); + MODULO_MODE = v; + } + + // POW_PRECISION {number} Integer, 0 to MAX inclusive. + // '[BigNumber Error] POW_PRECISION {not a primitive number|not an integer|out of range}: {v}' + if (obj.hasOwnProperty(p = 'POW_PRECISION')) { + v = obj[p]; + intCheck(v, 0, MAX, p); + POW_PRECISION = v; + } + + // FORMAT {object} + // '[BigNumber Error] FORMAT not an object: {v}' + if (obj.hasOwnProperty(p = 'FORMAT')) { + v = obj[p]; + if (typeof v == 'object') FORMAT = v; + else throw Error + (bignumberError + p + ' not an object: ' + v); + } + + // ALPHABET {string} + // '[BigNumber Error] ALPHABET invalid: {v}' + if (obj.hasOwnProperty(p = 'ALPHABET')) { + v = obj[p]; + + // Disallow if only one character, + // or if it contains '+', '-', '.', whitespace, or a repeated character. + if (typeof v == 'string' && !/^.$|[+-.\s]|(.).*\1/.test(v)) { + ALPHABET = v; + } else { + throw Error + (bignumberError + p + ' invalid: ' + v); + } + } + + } else { + + // '[BigNumber Error] Object expected: {v}' + throw Error + (bignumberError + 'Object expected: ' + obj); + } + } + + return { + DECIMAL_PLACES: DECIMAL_PLACES, + ROUNDING_MODE: ROUNDING_MODE, + EXPONENTIAL_AT: [TO_EXP_NEG, TO_EXP_POS], + RANGE: [MIN_EXP, MAX_EXP], + CRYPTO: CRYPTO, + MODULO_MODE: MODULO_MODE, + POW_PRECISION: POW_PRECISION, + FORMAT: FORMAT, + ALPHABET: ALPHABET + }; + }; + + + /* + * Return true if v is a BigNumber instance, otherwise return false. + * + * If BigNumber.DEBUG is true, throw if a BigNumber instance is not well-formed. + * + * v {any} + * + * '[BigNumber Error] Invalid BigNumber: {v}' + */ + BigNumber.isBigNumber = function (v) { + if (!v || v._isBigNumber !== true) return false; + if (!BigNumber.DEBUG) return true; + + var i, n, + c = v.c, + e = v.e, + s = v.s; + + out: if ({}.toString.call(c) == '[object Array]') { + + if ((s === 1 || s === -1) && e >= -MAX && e <= MAX && e === mathfloor(e)) { + + // If the first element is zero, the BigNumber value must be zero. + if (c[0] === 0) { + if (e === 0 && c.length === 1) return true; + break out; + } + + // Calculate number of digits that c[0] should have, based on the exponent. + i = (e + 1) % LOG_BASE; + if (i < 1) i += LOG_BASE; + + // Calculate number of digits of c[0]. + //if (Math.ceil(Math.log(c[0] + 1) / Math.LN10) == i) { + if (String(c[0]).length == i) { + + for (i = 0; i < c.length; i++) { + n = c[i]; + if (n < 0 || n >= BASE || n !== mathfloor(n)) break out; + } + + // Last element cannot be zero, unless it is the only element. + if (n !== 0) return true; + } + } + + // Infinity/NaN + } else if (c === null && e === null && (s === null || s === 1 || s === -1)) { + return true; + } + + throw Error + (bignumberError + 'Invalid BigNumber: ' + v); + }; + + + /* + * Return a new BigNumber whose value is the maximum of the arguments. + * + * arguments {number|string|BigNumber} + */ + BigNumber.maximum = BigNumber.max = function () { + return maxOrMin(arguments, P.lt); + }; + + + /* + * Return a new BigNumber whose value is the minimum of the arguments. + * + * arguments {number|string|BigNumber} + */ + BigNumber.minimum = BigNumber.min = function () { + return maxOrMin(arguments, P.gt); + }; + + + /* + * Return a new BigNumber with a random value equal to or greater than 0 and less than 1, + * and with dp, or DECIMAL_PLACES if dp is omitted, decimal places (or less if trailing + * zeros are produced). + * + * [dp] {number} Decimal places. Integer, 0 to MAX inclusive. + * + * '[BigNumber Error] Argument {not a primitive number|not an integer|out of range}: {dp}' + * '[BigNumber Error] crypto unavailable' + */ + BigNumber.random = (function () { + var pow2_53 = 0x20000000000000; + + // Return a 53 bit integer n, where 0 <= n < 9007199254740992. + // Check if Math.random() produces more than 32 bits of randomness. + // If it does, assume at least 53 bits are produced, otherwise assume at least 30 bits. + // 0x40000000 is 2^30, 0x800000 is 2^23, 0x1fffff is 2^21 - 1. + var random53bitInt = (Math.random() * pow2_53) & 0x1fffff + ? function () { return mathfloor(Math.random() * pow2_53); } + : function () { return ((Math.random() * 0x40000000 | 0) * 0x800000) + + (Math.random() * 0x800000 | 0); }; + + return function (dp) { + var a, b, e, k, v, + i = 0, + c = [], + rand = new BigNumber(ONE); + + if (dp == null) dp = DECIMAL_PLACES; + else intCheck(dp, 0, MAX); + + k = mathceil(dp / LOG_BASE); + + if (CRYPTO) { + + // Browsers supporting crypto.getRandomValues. + if (crypto.getRandomValues) { + + a = crypto.getRandomValues(new Uint32Array(k *= 2)); + + for (; i < k;) { + + // 53 bits: + // ((Math.pow(2, 32) - 1) * Math.pow(2, 21)).toString(2) + // 11111 11111111 11111111 11111111 11100000 00000000 00000000 + // ((Math.pow(2, 32) - 1) >>> 11).toString(2) + // 11111 11111111 11111111 + // 0x20000 is 2^21. + v = a[i] * 0x20000 + (a[i + 1] >>> 11); + + // Rejection sampling: + // 0 <= v < 9007199254740992 + // Probability that v >= 9e15, is + // 7199254740992 / 9007199254740992 ~= 0.0008, i.e. 1 in 1251 + if (v >= 9e15) { + b = crypto.getRandomValues(new Uint32Array(2)); + a[i] = b[0]; + a[i + 1] = b[1]; + } else { + + // 0 <= v <= 8999999999999999 + // 0 <= (v % 1e14) <= 99999999999999 + c.push(v % 1e14); + i += 2; + } + } + i = k / 2; + + // Node.js supporting crypto.randomBytes. + } else if (crypto.randomBytes) { + + // buffer + a = crypto.randomBytes(k *= 7); + + for (; i < k;) { + + // 0x1000000000000 is 2^48, 0x10000000000 is 2^40 + // 0x100000000 is 2^32, 0x1000000 is 2^24 + // 11111 11111111 11111111 11111111 11111111 11111111 11111111 + // 0 <= v < 9007199254740992 + v = ((a[i] & 31) * 0x1000000000000) + (a[i + 1] * 0x10000000000) + + (a[i + 2] * 0x100000000) + (a[i + 3] * 0x1000000) + + (a[i + 4] << 16) + (a[i + 5] << 8) + a[i + 6]; + + if (v >= 9e15) { + crypto.randomBytes(7).copy(a, i); + } else { + + // 0 <= (v % 1e14) <= 99999999999999 + c.push(v % 1e14); + i += 7; + } + } + i = k / 7; + } else { + CRYPTO = false; + throw Error + (bignumberError + 'crypto unavailable'); + } + } + + // Use Math.random. + if (!CRYPTO) { + + for (; i < k;) { + v = random53bitInt(); + if (v < 9e15) c[i++] = v % 1e14; + } + } + + k = c[--i]; + dp %= LOG_BASE; + + // Convert trailing digits to zeros according to dp. + if (k && dp) { + v = POWS_TEN[LOG_BASE - dp]; + c[i] = mathfloor(k / v) * v; + } + + // Remove trailing elements which are zero. + for (; c[i] === 0; c.pop(), i--); + + // Zero? + if (i < 0) { + c = [e = 0]; + } else { + + // Remove leading elements which are zero and adjust exponent accordingly. + for (e = -1 ; c[0] === 0; c.splice(0, 1), e -= LOG_BASE); + + // Count the digits of the first element of c to determine leading zeros, and... + for (i = 1, v = c[0]; v >= 10; v /= 10, i++); + + // adjust the exponent accordingly. + if (i < LOG_BASE) e -= LOG_BASE - i; + } + + rand.e = e; + rand.c = c; + return rand; + }; + })(); + + + /* + * Return a BigNumber whose value is the sum of the arguments. + * + * arguments {number|string|BigNumber} + */ + BigNumber.sum = function () { + var i = 1, + args = arguments, + sum = new BigNumber(args[0]); + for (; i < args.length;) sum = sum.plus(args[i++]); + return sum; + }; + + + // PRIVATE FUNCTIONS + + + // Called by BigNumber and BigNumber.prototype.toString. + convertBase = (function () { + var decimal = '0123456789'; + + /* + * Convert string of baseIn to an array of numbers of baseOut. + * Eg. toBaseOut('255', 10, 16) returns [15, 15]. + * Eg. toBaseOut('ff', 16, 10) returns [2, 5, 5]. + */ + function toBaseOut(str, baseIn, baseOut, alphabet) { + var j, + arr = [0], + arrL, + i = 0, + len = str.length; + + for (; i < len;) { + for (arrL = arr.length; arrL--; arr[arrL] *= baseIn); + + arr[0] += alphabet.indexOf(str.charAt(i++)); + + for (j = 0; j < arr.length; j++) { + + if (arr[j] > baseOut - 1) { + if (arr[j + 1] == null) arr[j + 1] = 0; + arr[j + 1] += arr[j] / baseOut | 0; + arr[j] %= baseOut; + } + } + } + + return arr.reverse(); + } + + // Convert a numeric string of baseIn to a numeric string of baseOut. + // If the caller is toString, we are converting from base 10 to baseOut. + // If the caller is BigNumber, we are converting from baseIn to base 10. + return function (str, baseIn, baseOut, sign, callerIsToString) { + var alphabet, d, e, k, r, x, xc, y, + i = str.indexOf('.'), + dp = DECIMAL_PLACES, + rm = ROUNDING_MODE; + + // Non-integer. + if (i >= 0) { + k = POW_PRECISION; + + // Unlimited precision. + POW_PRECISION = 0; + str = str.replace('.', ''); + y = new BigNumber(baseIn); + x = y.pow(str.length - i); + POW_PRECISION = k; + + // Convert str as if an integer, then restore the fraction part by dividing the + // result by its base raised to a power. + + y.c = toBaseOut(toFixedPoint(coeffToString(x.c), x.e, '0'), + 10, baseOut, decimal); + y.e = y.c.length; + } + + // Convert the number as integer. + + xc = toBaseOut(str, baseIn, baseOut, callerIsToString + ? (alphabet = ALPHABET, decimal) + : (alphabet = decimal, ALPHABET)); + + // xc now represents str as an integer and converted to baseOut. e is the exponent. + e = k = xc.length; + + // Remove trailing zeros. + for (; xc[--k] == 0; xc.pop()); + + // Zero? + if (!xc[0]) return alphabet.charAt(0); + + // Does str represent an integer? If so, no need for the division. + if (i < 0) { + --e; + } else { + x.c = xc; + x.e = e; + + // The sign is needed for correct rounding. + x.s = sign; + x = div(x, y, dp, rm, baseOut); + xc = x.c; + r = x.r; + e = x.e; + } + + // xc now represents str converted to baseOut. + + // THe index of the rounding digit. + d = e + dp + 1; + + // The rounding digit: the digit to the right of the digit that may be rounded up. + i = xc[d]; + + // Look at the rounding digits and mode to determine whether to round up. + + k = baseOut / 2; + r = r || d < 0 || xc[d + 1] != null; + + r = rm < 4 ? (i != null || r) && (rm == 0 || rm == (x.s < 0 ? 3 : 2)) + : i > k || i == k &&(rm == 4 || r || rm == 6 && xc[d - 1] & 1 || + rm == (x.s < 0 ? 8 : 7)); + + // If the index of the rounding digit is not greater than zero, or xc represents + // zero, then the result of the base conversion is zero or, if rounding up, a value + // such as 0.00001. + if (d < 1 || !xc[0]) { + + // 1^-dp or 0 + str = r ? toFixedPoint(alphabet.charAt(1), -dp, alphabet.charAt(0)) : alphabet.charAt(0); + } else { + + // Truncate xc to the required number of decimal places. + xc.length = d; + + // Round up? + if (r) { + + // Rounding up may mean the previous digit has to be rounded up and so on. + for (--baseOut; ++xc[--d] > baseOut;) { + xc[d] = 0; + + if (!d) { + ++e; + xc = [1].concat(xc); + } + } + } + + // Determine trailing zeros. + for (k = xc.length; !xc[--k];); + + // E.g. [4, 11, 15] becomes 4bf. + for (i = 0, str = ''; i <= k; str += alphabet.charAt(xc[i++])); + + // Add leading zeros, decimal point and trailing zeros as required. + str = toFixedPoint(str, e, alphabet.charAt(0)); + } + + // The caller will add the sign. + return str; + }; + })(); + + + // Perform division in the specified base. Called by div and convertBase. + div = (function () { + + // Assume non-zero x and k. + function multiply(x, k, base) { + var m, temp, xlo, xhi, + carry = 0, + i = x.length, + klo = k % SQRT_BASE, + khi = k / SQRT_BASE | 0; + + for (x = x.slice(); i--;) { + xlo = x[i] % SQRT_BASE; + xhi = x[i] / SQRT_BASE | 0; + m = khi * xlo + xhi * klo; + temp = klo * xlo + ((m % SQRT_BASE) * SQRT_BASE) + carry; + carry = (temp / base | 0) + (m / SQRT_BASE | 0) + khi * xhi; + x[i] = temp % base; + } + + if (carry) x = [carry].concat(x); + + return x; + } + + function compare(a, b, aL, bL) { + var i, cmp; + + if (aL != bL) { + cmp = aL > bL ? 1 : -1; + } else { + + for (i = cmp = 0; i < aL; i++) { + + if (a[i] != b[i]) { + cmp = a[i] > b[i] ? 1 : -1; + break; + } + } + } + + return cmp; + } + + function subtract(a, b, aL, base) { + var i = 0; + + // Subtract b from a. + for (; aL--;) { + a[aL] -= i; + i = a[aL] < b[aL] ? 1 : 0; + a[aL] = i * base + a[aL] - b[aL]; + } + + // Remove leading zeros. + for (; !a[0] && a.length > 1; a.splice(0, 1)); + } + + // x: dividend, y: divisor. + return function (x, y, dp, rm, base) { + var cmp, e, i, more, n, prod, prodL, q, qc, rem, remL, rem0, xi, xL, yc0, + yL, yz, + s = x.s == y.s ? 1 : -1, + xc = x.c, + yc = y.c; + + // Either NaN, Infinity or 0? + if (!xc || !xc[0] || !yc || !yc[0]) { + + return new BigNumber( + + // Return NaN if either NaN, or both Infinity or 0. + !x.s || !y.s || (xc ? yc && xc[0] == yc[0] : !yc) ? NaN : + + // Return ±0 if x is ±0 or y is ±Infinity, or return ±Infinity as y is ±0. + xc && xc[0] == 0 || !yc ? s * 0 : s / 0 + ); + } + + q = new BigNumber(s); + qc = q.c = []; + e = x.e - y.e; + s = dp + e + 1; + + if (!base) { + base = BASE; + e = bitFloor(x.e / LOG_BASE) - bitFloor(y.e / LOG_BASE); + s = s / LOG_BASE | 0; + } + + // Result exponent may be one less then the current value of e. + // The coefficients of the BigNumbers from convertBase may have trailing zeros. + for (i = 0; yc[i] == (xc[i] || 0); i++); + + if (yc[i] > (xc[i] || 0)) e--; + + if (s < 0) { + qc.push(1); + more = true; + } else { + xL = xc.length; + yL = yc.length; + i = 0; + s += 2; + + // Normalise xc and yc so highest order digit of yc is >= base / 2. + + n = mathfloor(base / (yc[0] + 1)); + + // Not necessary, but to handle odd bases where yc[0] == (base / 2) - 1. + // if (n > 1 || n++ == 1 && yc[0] < base / 2) { + if (n > 1) { + yc = multiply(yc, n, base); + xc = multiply(xc, n, base); + yL = yc.length; + xL = xc.length; + } + + xi = yL; + rem = xc.slice(0, yL); + remL = rem.length; + + // Add zeros to make remainder as long as divisor. + for (; remL < yL; rem[remL++] = 0); + yz = yc.slice(); + yz = [0].concat(yz); + yc0 = yc[0]; + if (yc[1] >= base / 2) yc0++; + // Not necessary, but to prevent trial digit n > base, when using base 3. + // else if (base == 3 && yc0 == 1) yc0 = 1 + 1e-15; + + do { + n = 0; + + // Compare divisor and remainder. + cmp = compare(yc, rem, yL, remL); + + // If divisor < remainder. + if (cmp < 0) { + + // Calculate trial digit, n. + + rem0 = rem[0]; + if (yL != remL) rem0 = rem0 * base + (rem[1] || 0); + + // n is how many times the divisor goes into the current remainder. + n = mathfloor(rem0 / yc0); + + // Algorithm: + // product = divisor multiplied by trial digit (n). + // Compare product and remainder. + // If product is greater than remainder: + // Subtract divisor from product, decrement trial digit. + // Subtract product from remainder. + // If product was less than remainder at the last compare: + // Compare new remainder and divisor. + // If remainder is greater than divisor: + // Subtract divisor from remainder, increment trial digit. + + if (n > 1) { + + // n may be > base only when base is 3. + if (n >= base) n = base - 1; + + // product = divisor * trial digit. + prod = multiply(yc, n, base); + prodL = prod.length; + remL = rem.length; + + // Compare product and remainder. + // If product > remainder then trial digit n too high. + // n is 1 too high about 5% of the time, and is not known to have + // ever been more than 1 too high. + while (compare(prod, rem, prodL, remL) == 1) { + n--; + + // Subtract divisor from product. + subtract(prod, yL < prodL ? yz : yc, prodL, base); + prodL = prod.length; + cmp = 1; + } + } else { + + // n is 0 or 1, cmp is -1. + // If n is 0, there is no need to compare yc and rem again below, + // so change cmp to 1 to avoid it. + // If n is 1, leave cmp as -1, so yc and rem are compared again. + if (n == 0) { + + // divisor < remainder, so n must be at least 1. + cmp = n = 1; + } + + // product = divisor + prod = yc.slice(); + prodL = prod.length; + } + + if (prodL < remL) prod = [0].concat(prod); + + // Subtract product from remainder. + subtract(rem, prod, remL, base); + remL = rem.length; + + // If product was < remainder. + if (cmp == -1) { + + // Compare divisor and new remainder. + // If divisor < new remainder, subtract divisor from remainder. + // Trial digit n too low. + // n is 1 too low about 5% of the time, and very rarely 2 too low. + while (compare(yc, rem, yL, remL) < 1) { + n++; + + // Subtract divisor from remainder. + subtract(rem, yL < remL ? yz : yc, remL, base); + remL = rem.length; + } + } + } else if (cmp === 0) { + n++; + rem = [0]; + } // else cmp === 1 and n will be 0 + + // Add the next digit, n, to the result array. + qc[i++] = n; + + // Update the remainder. + if (rem[0]) { + rem[remL++] = xc[xi] || 0; + } else { + rem = [xc[xi]]; + remL = 1; + } + } while ((xi++ < xL || rem[0] != null) && s--); + + more = rem[0] != null; + + // Leading zero? + if (!qc[0]) qc.splice(0, 1); + } + + if (base == BASE) { + + // To calculate q.e, first get the number of digits of qc[0]. + for (i = 1, s = qc[0]; s >= 10; s /= 10, i++); + + round(q, dp + (q.e = i + e * LOG_BASE - 1) + 1, rm, more); + + // Caller is convertBase. + } else { + q.e = e; + q.r = +more; + } + + return q; + }; + })(); + + + /* + * Return a string representing the value of BigNumber n in fixed-point or exponential + * notation rounded to the specified decimal places or significant digits. + * + * n: a BigNumber. + * i: the index of the last digit required (i.e. the digit that may be rounded up). + * rm: the rounding mode. + * id: 1 (toExponential) or 2 (toPrecision). + */ + function format(n, i, rm, id) { + var c0, e, ne, len, str; + + if (rm == null) rm = ROUNDING_MODE; + else intCheck(rm, 0, 8); + + if (!n.c) return n.toString(); + + c0 = n.c[0]; + ne = n.e; + + if (i == null) { + str = coeffToString(n.c); + str = id == 1 || id == 2 && (ne <= TO_EXP_NEG || ne >= TO_EXP_POS) + ? toExponential(str, ne) + : toFixedPoint(str, ne, '0'); + } else { + n = round(new BigNumber(n), i, rm); + + // n.e may have changed if the value was rounded up. + e = n.e; + + str = coeffToString(n.c); + len = str.length; + + // toPrecision returns exponential notation if the number of significant digits + // specified is less than the number of digits necessary to represent the integer + // part of the value in fixed-point notation. + + // Exponential notation. + if (id == 1 || id == 2 && (i <= e || e <= TO_EXP_NEG)) { + + // Append zeros? + for (; len < i; str += '0', len++); + str = toExponential(str, e); + + // Fixed-point notation. + } else { + i -= ne; + str = toFixedPoint(str, e, '0'); + + // Append zeros? + if (e + 1 > len) { + if (--i > 0) for (str += '.'; i--; str += '0'); + } else { + i += e - len; + if (i > 0) { + if (e + 1 == len) str += '.'; + for (; i--; str += '0'); + } + } + } + } + + return n.s < 0 && c0 ? '-' + str : str; + } + + + // Handle BigNumber.max and BigNumber.min. + function maxOrMin(args, method) { + var n, + i = 1, + m = new BigNumber(args[0]); + + for (; i < args.length; i++) { + n = new BigNumber(args[i]); + + // If any number is NaN, return NaN. + if (!n.s) { + m = n; + break; + } else if (method.call(m, n)) { + m = n; + } + } + + return m; + } + + + /* + * Strip trailing zeros, calculate base 10 exponent and check against MIN_EXP and MAX_EXP. + * Called by minus, plus and times. + */ + function normalise(n, c, e) { + var i = 1, + j = c.length; + + // Remove trailing zeros. + for (; !c[--j]; c.pop()); + + // Calculate the base 10 exponent. First get the number of digits of c[0]. + for (j = c[0]; j >= 10; j /= 10, i++); + + // Overflow? + if ((e = i + e * LOG_BASE - 1) > MAX_EXP) { + + // Infinity. + n.c = n.e = null; + + // Underflow? + } else if (e < MIN_EXP) { + + // Zero. + n.c = [n.e = 0]; + } else { + n.e = e; + n.c = c; + } + + return n; + } + + + // Handle values that fail the validity test in BigNumber. + parseNumeric = (function () { + var basePrefix = /^(-?)0([xbo])(?=\w[\w.]*$)/i, + dotAfter = /^([^.]+)\.$/, + dotBefore = /^\.([^.]+)$/, + isInfinityOrNaN = /^-?(Infinity|NaN)$/, + whitespaceOrPlus = /^\s*\+(?=[\w.])|^\s+|\s+$/g; + + return function (x, str, isNum, b) { + var base, + s = isNum ? str : str.replace(whitespaceOrPlus, ''); + + // No exception on ±Infinity or NaN. + if (isInfinityOrNaN.test(s)) { + x.s = isNaN(s) ? null : s < 0 ? -1 : 1; + } else { + if (!isNum) { + + // basePrefix = /^(-?)0([xbo])(?=\w[\w.]*$)/i + s = s.replace(basePrefix, function (m, p1, p2) { + base = (p2 = p2.toLowerCase()) == 'x' ? 16 : p2 == 'b' ? 2 : 8; + return !b || b == base ? p1 : m; + }); + + if (b) { + base = b; + + // E.g. '1.' to '1', '.1' to '0.1' + s = s.replace(dotAfter, '$1').replace(dotBefore, '0.$1'); + } + + if (str != s) return new BigNumber(s, base); + } + + // '[BigNumber Error] Not a number: {n}' + // '[BigNumber Error] Not a base {b} number: {n}' + if (BigNumber.DEBUG) { + throw Error + (bignumberError + 'Not a' + (b ? ' base ' + b : '') + ' number: ' + str); + } + + // NaN + x.s = null; + } + + x.c = x.e = null; + } + })(); + + + /* + * Round x to sd significant digits using rounding mode rm. Check for over/under-flow. + * If r is truthy, it is known that there are more digits after the rounding digit. + */ + function round(x, sd, rm, r) { + var d, i, j, k, n, ni, rd, + xc = x.c, + pows10 = POWS_TEN; + + // if x is not Infinity or NaN... + if (xc) { + + // rd is the rounding digit, i.e. the digit after the digit that may be rounded up. + // n is a base 1e14 number, the value of the element of array x.c containing rd. + // ni is the index of n within x.c. + // d is the number of digits of n. + // i is the index of rd within n including leading zeros. + // j is the actual index of rd within n (if < 0, rd is a leading zero). + out: { + + // Get the number of digits of the first element of xc. + for (d = 1, k = xc[0]; k >= 10; k /= 10, d++); + i = sd - d; + + // If the rounding digit is in the first element of xc... + if (i < 0) { + i += LOG_BASE; + j = sd; + n = xc[ni = 0]; + + // Get the rounding digit at index j of n. + rd = n / pows10[d - j - 1] % 10 | 0; + } else { + ni = mathceil((i + 1) / LOG_BASE); + + if (ni >= xc.length) { + + if (r) { + + // Needed by sqrt. + for (; xc.length <= ni; xc.push(0)); + n = rd = 0; + d = 1; + i %= LOG_BASE; + j = i - LOG_BASE + 1; + } else { + break out; + } + } else { + n = k = xc[ni]; + + // Get the number of digits of n. + for (d = 1; k >= 10; k /= 10, d++); + + // Get the index of rd within n. + i %= LOG_BASE; + + // Get the index of rd within n, adjusted for leading zeros. + // The number of leading zeros of n is given by LOG_BASE - d. + j = i - LOG_BASE + d; + + // Get the rounding digit at index j of n. + rd = j < 0 ? 0 : n / pows10[d - j - 1] % 10 | 0; + } + } + + r = r || sd < 0 || + + // Are there any non-zero digits after the rounding digit? + // The expression n % pows10[d - j - 1] returns all digits of n to the right + // of the digit at j, e.g. if n is 908714 and j is 2, the expression gives 714. + xc[ni + 1] != null || (j < 0 ? n : n % pows10[d - j - 1]); + + r = rm < 4 + ? (rd || r) && (rm == 0 || rm == (x.s < 0 ? 3 : 2)) + : rd > 5 || rd == 5 && (rm == 4 || r || rm == 6 && + + // Check whether the digit to the left of the rounding digit is odd. + ((i > 0 ? j > 0 ? n / pows10[d - j] : 0 : xc[ni - 1]) % 10) & 1 || + rm == (x.s < 0 ? 8 : 7)); + + if (sd < 1 || !xc[0]) { + xc.length = 0; + + if (r) { + + // Convert sd to decimal places. + sd -= x.e + 1; + + // 1, 0.1, 0.01, 0.001, 0.0001 etc. + xc[0] = pows10[(LOG_BASE - sd % LOG_BASE) % LOG_BASE]; + x.e = -sd || 0; + } else { + + // Zero. + xc[0] = x.e = 0; + } + + return x; + } + + // Remove excess digits. + if (i == 0) { + xc.length = ni; + k = 1; + ni--; + } else { + xc.length = ni + 1; + k = pows10[LOG_BASE - i]; + + // E.g. 56700 becomes 56000 if 7 is the rounding digit. + // j > 0 means i > number of leading zeros of n. + xc[ni] = j > 0 ? mathfloor(n / pows10[d - j] % pows10[j]) * k : 0; + } + + // Round up? + if (r) { + + for (; ;) { + + // If the digit to be rounded up is in the first element of xc... + if (ni == 0) { + + // i will be the length of xc[0] before k is added. + for (i = 1, j = xc[0]; j >= 10; j /= 10, i++); + j = xc[0] += k; + for (k = 1; j >= 10; j /= 10, k++); + + // if i != k the length has increased. + if (i != k) { + x.e++; + if (xc[0] == BASE) xc[0] = 1; + } + + break; + } else { + xc[ni] += k; + if (xc[ni] != BASE) break; + xc[ni--] = 0; + k = 1; + } + } + } + + // Remove trailing zeros. + for (i = xc.length; xc[--i] === 0; xc.pop()); + } + + // Overflow? Infinity. + if (x.e > MAX_EXP) { + x.c = x.e = null; + + // Underflow? Zero. + } else if (x.e < MIN_EXP) { + x.c = [x.e = 0]; + } + } + + return x; + } + + + function valueOf(n) { + var str, + e = n.e; + + if (e === null) return n.toString(); + + str = coeffToString(n.c); + + str = e <= TO_EXP_NEG || e >= TO_EXP_POS + ? toExponential(str, e) + : toFixedPoint(str, e, '0'); + + return n.s < 0 ? '-' + str : str; + } + + + // PROTOTYPE/INSTANCE METHODS + + + /* + * Return a new BigNumber whose value is the absolute value of this BigNumber. + */ + P.absoluteValue = P.abs = function () { + var x = new BigNumber(this); + if (x.s < 0) x.s = 1; + return x; + }; + + + /* + * Return + * 1 if the value of this BigNumber is greater than the value of BigNumber(y, b), + * -1 if the value of this BigNumber is less than the value of BigNumber(y, b), + * 0 if they have the same value, + * or null if the value of either is NaN. + */ + P.comparedTo = function (y, b) { + return compare(this, new BigNumber(y, b)); + }; + + + /* + * If dp is undefined or null or true or false, return the number of decimal places of the + * value of this BigNumber, or null if the value of this BigNumber is ±Infinity or NaN. + * + * Otherwise, if dp is a number, return a new BigNumber whose value is the value of this + * BigNumber rounded to a maximum of dp decimal places using rounding mode rm, or + * ROUNDING_MODE if rm is omitted. + * + * [dp] {number} Decimal places: integer, 0 to MAX inclusive. + * [rm] {number} Rounding mode. Integer, 0 to 8 inclusive. + * + * '[BigNumber Error] Argument {not a primitive number|not an integer|out of range}: {dp|rm}' + */ + P.decimalPlaces = P.dp = function (dp, rm) { + var c, n, v, + x = this; + + if (dp != null) { + intCheck(dp, 0, MAX); + if (rm == null) rm = ROUNDING_MODE; + else intCheck(rm, 0, 8); + + return round(new BigNumber(x), dp + x.e + 1, rm); + } + + if (!(c = x.c)) return null; + n = ((v = c.length - 1) - bitFloor(this.e / LOG_BASE)) * LOG_BASE; + + // Subtract the number of trailing zeros of the last number. + if (v = c[v]) for (; v % 10 == 0; v /= 10, n--); + if (n < 0) n = 0; + + return n; + }; + + + /* + * n / 0 = I + * n / N = N + * n / I = 0 + * 0 / n = 0 + * 0 / 0 = N + * 0 / N = N + * 0 / I = 0 + * N / n = N + * N / 0 = N + * N / N = N + * N / I = N + * I / n = I + * I / 0 = I + * I / N = N + * I / I = N + * + * Return a new BigNumber whose value is the value of this BigNumber divided by the value of + * BigNumber(y, b), rounded according to DECIMAL_PLACES and ROUNDING_MODE. + */ + P.dividedBy = P.div = function (y, b) { + return div(this, new BigNumber(y, b), DECIMAL_PLACES, ROUNDING_MODE); + }; + + + /* + * Return a new BigNumber whose value is the integer part of dividing the value of this + * BigNumber by the value of BigNumber(y, b). + */ + P.dividedToIntegerBy = P.idiv = function (y, b) { + return div(this, new BigNumber(y, b), 0, 1); + }; + + + /* + * Return a BigNumber whose value is the value of this BigNumber exponentiated by n. + * + * If m is present, return the result modulo m. + * If n is negative round according to DECIMAL_PLACES and ROUNDING_MODE. + * If POW_PRECISION is non-zero and m is not present, round to POW_PRECISION using ROUNDING_MODE. + * + * The modular power operation works efficiently when x, n, and m are integers, otherwise it + * is equivalent to calculating x.exponentiatedBy(n).modulo(m) with a POW_PRECISION of 0. + * + * n {number|string|BigNumber} The exponent. An integer. + * [m] {number|string|BigNumber} The modulus. + * + * '[BigNumber Error] Exponent not an integer: {n}' + */ + P.exponentiatedBy = P.pow = function (n, m) { + var half, isModExp, i, k, more, nIsBig, nIsNeg, nIsOdd, y, + x = this; + + n = new BigNumber(n); + + // Allow NaN and ±Infinity, but not other non-integers. + if (n.c && !n.isInteger()) { + throw Error + (bignumberError + 'Exponent not an integer: ' + valueOf(n)); + } + + if (m != null) m = new BigNumber(m); + + // Exponent of MAX_SAFE_INTEGER is 15. + nIsBig = n.e > 14; + + // If x is NaN, ±Infinity, ±0 or ±1, or n is ±Infinity, NaN or ±0. + if (!x.c || !x.c[0] || x.c[0] == 1 && !x.e && x.c.length == 1 || !n.c || !n.c[0]) { + + // The sign of the result of pow when x is negative depends on the evenness of n. + // If +n overflows to ±Infinity, the evenness of n would be not be known. + y = new BigNumber(Math.pow(+valueOf(x), nIsBig ? 2 - isOdd(n) : +valueOf(n))); + return m ? y.mod(m) : y; + } + + nIsNeg = n.s < 0; + + if (m) { + + // x % m returns NaN if abs(m) is zero, or m is NaN. + if (m.c ? !m.c[0] : !m.s) return new BigNumber(NaN); + + isModExp = !nIsNeg && x.isInteger() && m.isInteger(); + + if (isModExp) x = x.mod(m); + + // Overflow to ±Infinity: >=2**1e10 or >=1.0000024**1e15. + // Underflow to ±0: <=0.79**1e10 or <=0.9999975**1e15. + } else if (n.e > 9 && (x.e > 0 || x.e < -1 || (x.e == 0 + // [1, 240000000] + ? x.c[0] > 1 || nIsBig && x.c[1] >= 24e7 + // [80000000000000] [99999750000000] + : x.c[0] < 8e13 || nIsBig && x.c[0] <= 9999975e7))) { + + // If x is negative and n is odd, k = -0, else k = 0. + k = x.s < 0 && isOdd(n) ? -0 : 0; + + // If x >= 1, k = ±Infinity. + if (x.e > -1) k = 1 / k; + + // If n is negative return ±0, else return ±Infinity. + return new BigNumber(nIsNeg ? 1 / k : k); + + } else if (POW_PRECISION) { + + // Truncating each coefficient array to a length of k after each multiplication + // equates to truncating significant digits to POW_PRECISION + [28, 41], + // i.e. there will be a minimum of 28 guard digits retained. + k = mathceil(POW_PRECISION / LOG_BASE + 2); + } + + if (nIsBig) { + half = new BigNumber(0.5); + if (nIsNeg) n.s = 1; + nIsOdd = isOdd(n); + } else { + i = Math.abs(+valueOf(n)); + nIsOdd = i % 2; + } + + y = new BigNumber(ONE); + + // Performs 54 loop iterations for n of 9007199254740991. + for (; ;) { + + if (nIsOdd) { + y = y.times(x); + if (!y.c) break; + + if (k) { + if (y.c.length > k) y.c.length = k; + } else if (isModExp) { + y = y.mod(m); //y = y.minus(div(y, m, 0, MODULO_MODE).times(m)); + } + } + + if (i) { + i = mathfloor(i / 2); + if (i === 0) break; + nIsOdd = i % 2; + } else { + n = n.times(half); + round(n, n.e + 1, 1); + + if (n.e > 14) { + nIsOdd = isOdd(n); + } else { + i = +valueOf(n); + if (i === 0) break; + nIsOdd = i % 2; + } + } + + x = x.times(x); + + if (k) { + if (x.c && x.c.length > k) x.c.length = k; + } else if (isModExp) { + x = x.mod(m); //x = x.minus(div(x, m, 0, MODULO_MODE).times(m)); + } + } + + if (isModExp) return y; + if (nIsNeg) y = ONE.div(y); + + return m ? y.mod(m) : k ? round(y, POW_PRECISION, ROUNDING_MODE, more) : y; + }; + + + /* + * Return a new BigNumber whose value is the value of this BigNumber rounded to an integer + * using rounding mode rm, or ROUNDING_MODE if rm is omitted. + * + * [rm] {number} Rounding mode. Integer, 0 to 8 inclusive. + * + * '[BigNumber Error] Argument {not a primitive number|not an integer|out of range}: {rm}' + */ + P.integerValue = function (rm) { + var n = new BigNumber(this); + if (rm == null) rm = ROUNDING_MODE; + else intCheck(rm, 0, 8); + return round(n, n.e + 1, rm); + }; + + + /* + * Return true if the value of this BigNumber is equal to the value of BigNumber(y, b), + * otherwise return false. + */ + P.isEqualTo = P.eq = function (y, b) { + return compare(this, new BigNumber(y, b)) === 0; + }; + + + /* + * Return true if the value of this BigNumber is a finite number, otherwise return false. + */ + P.isFinite = function () { + return !!this.c; + }; + + + /* + * Return true if the value of this BigNumber is greater than the value of BigNumber(y, b), + * otherwise return false. + */ + P.isGreaterThan = P.gt = function (y, b) { + return compare(this, new BigNumber(y, b)) > 0; + }; + + + /* + * Return true if the value of this BigNumber is greater than or equal to the value of + * BigNumber(y, b), otherwise return false. + */ + P.isGreaterThanOrEqualTo = P.gte = function (y, b) { + return (b = compare(this, new BigNumber(y, b))) === 1 || b === 0; + + }; + + + /* + * Return true if the value of this BigNumber is an integer, otherwise return false. + */ + P.isInteger = function () { + return !!this.c && bitFloor(this.e / LOG_BASE) > this.c.length - 2; + }; + + + /* + * Return true if the value of this BigNumber is less than the value of BigNumber(y, b), + * otherwise return false. + */ + P.isLessThan = P.lt = function (y, b) { + return compare(this, new BigNumber(y, b)) < 0; + }; + + + /* + * Return true if the value of this BigNumber is less than or equal to the value of + * BigNumber(y, b), otherwise return false. + */ + P.isLessThanOrEqualTo = P.lte = function (y, b) { + return (b = compare(this, new BigNumber(y, b))) === -1 || b === 0; + }; + + + /* + * Return true if the value of this BigNumber is NaN, otherwise return false. + */ + P.isNaN = function () { + return !this.s; + }; + + + /* + * Return true if the value of this BigNumber is negative, otherwise return false. + */ + P.isNegative = function () { + return this.s < 0; + }; + + + /* + * Return true if the value of this BigNumber is positive, otherwise return false. + */ + P.isPositive = function () { + return this.s > 0; + }; + + + /* + * Return true if the value of this BigNumber is 0 or -0, otherwise return false. + */ + P.isZero = function () { + return !!this.c && this.c[0] == 0; + }; + + + /* + * n - 0 = n + * n - N = N + * n - I = -I + * 0 - n = -n + * 0 - 0 = 0 + * 0 - N = N + * 0 - I = -I + * N - n = N + * N - 0 = N + * N - N = N + * N - I = N + * I - n = I + * I - 0 = I + * I - N = N + * I - I = N + * + * Return a new BigNumber whose value is the value of this BigNumber minus the value of + * BigNumber(y, b). + */ + P.minus = function (y, b) { + var i, j, t, xLTy, + x = this, + a = x.s; + + y = new BigNumber(y, b); + b = y.s; + + // Either NaN? + if (!a || !b) return new BigNumber(NaN); + + // Signs differ? + if (a != b) { + y.s = -b; + return x.plus(y); + } + + var xe = x.e / LOG_BASE, + ye = y.e / LOG_BASE, + xc = x.c, + yc = y.c; + + if (!xe || !ye) { + + // Either Infinity? + if (!xc || !yc) return xc ? (y.s = -b, y) : new BigNumber(yc ? x : NaN); + + // Either zero? + if (!xc[0] || !yc[0]) { + + // Return y if y is non-zero, x if x is non-zero, or zero if both are zero. + return yc[0] ? (y.s = -b, y) : new BigNumber(xc[0] ? x : + + // IEEE 754 (2008) 6.3: n - n = -0 when rounding to -Infinity + ROUNDING_MODE == 3 ? -0 : 0); + } + } + + xe = bitFloor(xe); + ye = bitFloor(ye); + xc = xc.slice(); + + // Determine which is the bigger number. + if (a = xe - ye) { + + if (xLTy = a < 0) { + a = -a; + t = xc; + } else { + ye = xe; + t = yc; + } + + t.reverse(); + + // Prepend zeros to equalise exponents. + for (b = a; b--; t.push(0)); + t.reverse(); + } else { + + // Exponents equal. Check digit by digit. + j = (xLTy = (a = xc.length) < (b = yc.length)) ? a : b; + + for (a = b = 0; b < j; b++) { + + if (xc[b] != yc[b]) { + xLTy = xc[b] < yc[b]; + break; + } + } + } + + // x < y? Point xc to the array of the bigger number. + if (xLTy) t = xc, xc = yc, yc = t, y.s = -y.s; + + b = (j = yc.length) - (i = xc.length); + + // Append zeros to xc if shorter. + // No need to add zeros to yc if shorter as subtract only needs to start at yc.length. + if (b > 0) for (; b--; xc[i++] = 0); + b = BASE - 1; + + // Subtract yc from xc. + for (; j > a;) { + + if (xc[--j] < yc[j]) { + for (i = j; i && !xc[--i]; xc[i] = b); + --xc[i]; + xc[j] += BASE; + } + + xc[j] -= yc[j]; + } + + // Remove leading zeros and adjust exponent accordingly. + for (; xc[0] == 0; xc.splice(0, 1), --ye); + + // Zero? + if (!xc[0]) { + + // Following IEEE 754 (2008) 6.3, + // n - n = +0 but n - n = -0 when rounding towards -Infinity. + y.s = ROUNDING_MODE == 3 ? -1 : 1; + y.c = [y.e = 0]; + return y; + } + + // No need to check for Infinity as +x - +y != Infinity && -x - -y != Infinity + // for finite x and y. + return normalise(y, xc, ye); + }; + + + /* + * n % 0 = N + * n % N = N + * n % I = n + * 0 % n = 0 + * -0 % n = -0 + * 0 % 0 = N + * 0 % N = N + * 0 % I = 0 + * N % n = N + * N % 0 = N + * N % N = N + * N % I = N + * I % n = N + * I % 0 = N + * I % N = N + * I % I = N + * + * Return a new BigNumber whose value is the value of this BigNumber modulo the value of + * BigNumber(y, b). The result depends on the value of MODULO_MODE. + */ + P.modulo = P.mod = function (y, b) { + var q, s, + x = this; + + y = new BigNumber(y, b); + + // Return NaN if x is Infinity or NaN, or y is NaN or zero. + if (!x.c || !y.s || y.c && !y.c[0]) { + return new BigNumber(NaN); + + // Return x if y is Infinity or x is zero. + } else if (!y.c || x.c && !x.c[0]) { + return new BigNumber(x); + } + + if (MODULO_MODE == 9) { + + // Euclidian division: q = sign(y) * floor(x / abs(y)) + // r = x - qy where 0 <= r < abs(y) + s = y.s; + y.s = 1; + q = div(x, y, 0, 3); + y.s = s; + q.s *= s; + } else { + q = div(x, y, 0, MODULO_MODE); + } + + y = x.minus(q.times(y)); + + // To match JavaScript %, ensure sign of zero is sign of dividend. + if (!y.c[0] && MODULO_MODE == 1) y.s = x.s; + + return y; + }; + + + /* + * n * 0 = 0 + * n * N = N + * n * I = I + * 0 * n = 0 + * 0 * 0 = 0 + * 0 * N = N + * 0 * I = N + * N * n = N + * N * 0 = N + * N * N = N + * N * I = N + * I * n = I + * I * 0 = N + * I * N = N + * I * I = I + * + * Return a new BigNumber whose value is the value of this BigNumber multiplied by the value + * of BigNumber(y, b). + */ + P.multipliedBy = P.times = function (y, b) { + var c, e, i, j, k, m, xcL, xlo, xhi, ycL, ylo, yhi, zc, + base, sqrtBase, + x = this, + xc = x.c, + yc = (y = new BigNumber(y, b)).c; + + // Either NaN, ±Infinity or ±0? + if (!xc || !yc || !xc[0] || !yc[0]) { + + // Return NaN if either is NaN, or one is 0 and the other is Infinity. + if (!x.s || !y.s || xc && !xc[0] && !yc || yc && !yc[0] && !xc) { + y.c = y.e = y.s = null; + } else { + y.s *= x.s; + + // Return ±Infinity if either is ±Infinity. + if (!xc || !yc) { + y.c = y.e = null; + + // Return ±0 if either is ±0. + } else { + y.c = [0]; + y.e = 0; + } + } + + return y; + } + + e = bitFloor(x.e / LOG_BASE) + bitFloor(y.e / LOG_BASE); + y.s *= x.s; + xcL = xc.length; + ycL = yc.length; + + // Ensure xc points to longer array and xcL to its length. + if (xcL < ycL) zc = xc, xc = yc, yc = zc, i = xcL, xcL = ycL, ycL = i; + + // Initialise the result array with zeros. + for (i = xcL + ycL, zc = []; i--; zc.push(0)); + + base = BASE; + sqrtBase = SQRT_BASE; + + for (i = ycL; --i >= 0;) { + c = 0; + ylo = yc[i] % sqrtBase; + yhi = yc[i] / sqrtBase | 0; + + for (k = xcL, j = i + k; j > i;) { + xlo = xc[--k] % sqrtBase; + xhi = xc[k] / sqrtBase | 0; + m = yhi * xlo + xhi * ylo; + xlo = ylo * xlo + ((m % sqrtBase) * sqrtBase) + zc[j] + c; + c = (xlo / base | 0) + (m / sqrtBase | 0) + yhi * xhi; + zc[j--] = xlo % base; + } + + zc[j] = c; + } + + if (c) { + ++e; + } else { + zc.splice(0, 1); + } + + return normalise(y, zc, e); + }; + + + /* + * Return a new BigNumber whose value is the value of this BigNumber negated, + * i.e. multiplied by -1. + */ + P.negated = function () { + var x = new BigNumber(this); + x.s = -x.s || null; + return x; + }; + + + /* + * n + 0 = n + * n + N = N + * n + I = I + * 0 + n = n + * 0 + 0 = 0 + * 0 + N = N + * 0 + I = I + * N + n = N + * N + 0 = N + * N + N = N + * N + I = N + * I + n = I + * I + 0 = I + * I + N = N + * I + I = I + * + * Return a new BigNumber whose value is the value of this BigNumber plus the value of + * BigNumber(y, b). + */ + P.plus = function (y, b) { + var t, + x = this, + a = x.s; + + y = new BigNumber(y, b); + b = y.s; + + // Either NaN? + if (!a || !b) return new BigNumber(NaN); + + // Signs differ? + if (a != b) { + y.s = -b; + return x.minus(y); + } + + var xe = x.e / LOG_BASE, + ye = y.e / LOG_BASE, + xc = x.c, + yc = y.c; + + if (!xe || !ye) { + + // Return ±Infinity if either ±Infinity. + if (!xc || !yc) return new BigNumber(a / 0); + + // Either zero? + // Return y if y is non-zero, x if x is non-zero, or zero if both are zero. + if (!xc[0] || !yc[0]) return yc[0] ? y : new BigNumber(xc[0] ? x : a * 0); + } + + xe = bitFloor(xe); + ye = bitFloor(ye); + xc = xc.slice(); + + // Prepend zeros to equalise exponents. Faster to use reverse then do unshifts. + if (a = xe - ye) { + if (a > 0) { + ye = xe; + t = yc; + } else { + a = -a; + t = xc; + } + + t.reverse(); + for (; a--; t.push(0)); + t.reverse(); + } + + a = xc.length; + b = yc.length; + + // Point xc to the longer array, and b to the shorter length. + if (a - b < 0) t = yc, yc = xc, xc = t, b = a; + + // Only start adding at yc.length - 1 as the further digits of xc can be ignored. + for (a = 0; b;) { + a = (xc[--b] = xc[b] + yc[b] + a) / BASE | 0; + xc[b] = BASE === xc[b] ? 0 : xc[b] % BASE; + } + + if (a) { + xc = [a].concat(xc); + ++ye; + } + + // No need to check for zero, as +x + +y != 0 && -x + -y != 0 + // ye = MAX_EXP + 1 possible + return normalise(y, xc, ye); + }; + + + /* + * If sd is undefined or null or true or false, return the number of significant digits of + * the value of this BigNumber, or null if the value of this BigNumber is ±Infinity or NaN. + * If sd is true include integer-part trailing zeros in the count. + * + * Otherwise, if sd is a number, return a new BigNumber whose value is the value of this + * BigNumber rounded to a maximum of sd significant digits using rounding mode rm, or + * ROUNDING_MODE if rm is omitted. + * + * sd {number|boolean} number: significant digits: integer, 1 to MAX inclusive. + * boolean: whether to count integer-part trailing zeros: true or false. + * [rm] {number} Rounding mode. Integer, 0 to 8 inclusive. + * + * '[BigNumber Error] Argument {not a primitive number|not an integer|out of range}: {sd|rm}' + */ + P.precision = P.sd = function (sd, rm) { + var c, n, v, + x = this; + + if (sd != null && sd !== !!sd) { + intCheck(sd, 1, MAX); + if (rm == null) rm = ROUNDING_MODE; + else intCheck(rm, 0, 8); + + return round(new BigNumber(x), sd, rm); + } + + if (!(c = x.c)) return null; + v = c.length - 1; + n = v * LOG_BASE + 1; + + if (v = c[v]) { + + // Subtract the number of trailing zeros of the last element. + for (; v % 10 == 0; v /= 10, n--); + + // Add the number of digits of the first element. + for (v = c[0]; v >= 10; v /= 10, n++); + } + + if (sd && x.e + 1 > n) n = x.e + 1; + + return n; + }; + + + /* + * Return a new BigNumber whose value is the value of this BigNumber shifted by k places + * (powers of 10). Shift to the right if n > 0, and to the left if n < 0. + * + * k {number} Integer, -MAX_SAFE_INTEGER to MAX_SAFE_INTEGER inclusive. + * + * '[BigNumber Error] Argument {not a primitive number|not an integer|out of range}: {k}' + */ + P.shiftedBy = function (k) { + intCheck(k, -MAX_SAFE_INTEGER, MAX_SAFE_INTEGER); + return this.times('1e' + k); + }; + + + /* + * sqrt(-n) = N + * sqrt(N) = N + * sqrt(-I) = N + * sqrt(I) = I + * sqrt(0) = 0 + * sqrt(-0) = -0 + * + * Return a new BigNumber whose value is the square root of the value of this BigNumber, + * rounded according to DECIMAL_PLACES and ROUNDING_MODE. + */ + P.squareRoot = P.sqrt = function () { + var m, n, r, rep, t, + x = this, + c = x.c, + s = x.s, + e = x.e, + dp = DECIMAL_PLACES + 4, + half = new BigNumber('0.5'); + + // Negative/NaN/Infinity/zero? + if (s !== 1 || !c || !c[0]) { + return new BigNumber(!s || s < 0 && (!c || c[0]) ? NaN : c ? x : 1 / 0); + } + + // Initial estimate. + s = Math.sqrt(+valueOf(x)); + + // Math.sqrt underflow/overflow? + // Pass x to Math.sqrt as integer, then adjust the exponent of the result. + if (s == 0 || s == 1 / 0) { + n = coeffToString(c); + if ((n.length + e) % 2 == 0) n += '0'; + s = Math.sqrt(+n); + e = bitFloor((e + 1) / 2) - (e < 0 || e % 2); + + if (s == 1 / 0) { + n = '1e' + e; + } else { + n = s.toExponential(); + n = n.slice(0, n.indexOf('e') + 1) + e; + } + + r = new BigNumber(n); + } else { + r = new BigNumber(s + ''); + } + + // Check for zero. + // r could be zero if MIN_EXP is changed after the this value was created. + // This would cause a division by zero (x/t) and hence Infinity below, which would cause + // coeffToString to throw. + if (r.c[0]) { + e = r.e; + s = e + dp; + if (s < 3) s = 0; + + // Newton-Raphson iteration. + for (; ;) { + t = r; + r = half.times(t.plus(div(x, t, dp, 1))); + + if (coeffToString(t.c).slice(0, s) === (n = coeffToString(r.c)).slice(0, s)) { + + // The exponent of r may here be one less than the final result exponent, + // e.g 0.0009999 (e-4) --> 0.001 (e-3), so adjust s so the rounding digits + // are indexed correctly. + if (r.e < e) --s; + n = n.slice(s - 3, s + 1); + + // The 4th rounding digit may be in error by -1 so if the 4 rounding digits + // are 9999 or 4999 (i.e. approaching a rounding boundary) continue the + // iteration. + if (n == '9999' || !rep && n == '4999') { + + // On the first iteration only, check to see if rounding up gives the + // exact result as the nines may infinitely repeat. + if (!rep) { + round(t, t.e + DECIMAL_PLACES + 2, 0); + + if (t.times(t).eq(x)) { + r = t; + break; + } + } + + dp += 4; + s += 4; + rep = 1; + } else { + + // If rounding digits are null, 0{0,4} or 50{0,3}, check for exact + // result. If not, then there are further digits and m will be truthy. + if (!+n || !+n.slice(1) && n.charAt(0) == '5') { + + // Truncate to the first rounding digit. + round(r, r.e + DECIMAL_PLACES + 2, 1); + m = !r.times(r).eq(x); + } + + break; + } + } + } + } + + return round(r, r.e + DECIMAL_PLACES + 1, ROUNDING_MODE, m); + }; + + + /* + * Return a string representing the value of this BigNumber in exponential notation and + * rounded using ROUNDING_MODE to dp fixed decimal places. + * + * [dp] {number} Decimal places. Integer, 0 to MAX inclusive. + * [rm] {number} Rounding mode. Integer, 0 to 8 inclusive. + * + * '[BigNumber Error] Argument {not a primitive number|not an integer|out of range}: {dp|rm}' + */ + P.toExponential = function (dp, rm) { + if (dp != null) { + intCheck(dp, 0, MAX); + dp++; + } + return format(this, dp, rm, 1); + }; + + + /* + * Return a string representing the value of this BigNumber in fixed-point notation rounding + * to dp fixed decimal places using rounding mode rm, or ROUNDING_MODE if rm is omitted. + * + * Note: as with JavaScript's number type, (-0).toFixed(0) is '0', + * but e.g. (-0.00001).toFixed(0) is '-0'. + * + * [dp] {number} Decimal places. Integer, 0 to MAX inclusive. + * [rm] {number} Rounding mode. Integer, 0 to 8 inclusive. + * + * '[BigNumber Error] Argument {not a primitive number|not an integer|out of range}: {dp|rm}' + */ + P.toFixed = function (dp, rm) { + if (dp != null) { + intCheck(dp, 0, MAX); + dp = dp + this.e + 1; + } + return format(this, dp, rm); + }; + + + /* + * Return a string representing the value of this BigNumber in fixed-point notation rounded + * using rm or ROUNDING_MODE to dp decimal places, and formatted according to the properties + * of the format or FORMAT object (see BigNumber.set). + * + * The formatting object may contain some or all of the properties shown below. + * + * FORMAT = { + * prefix: '', + * groupSize: 3, + * secondaryGroupSize: 0, + * groupSeparator: ',', + * decimalSeparator: '.', + * fractionGroupSize: 0, + * fractionGroupSeparator: '\xA0', // non-breaking space + * suffix: '' + * }; + * + * [dp] {number} Decimal places. Integer, 0 to MAX inclusive. + * [rm] {number} Rounding mode. Integer, 0 to 8 inclusive. + * [format] {object} Formatting options. See FORMAT pbject above. + * + * '[BigNumber Error] Argument {not a primitive number|not an integer|out of range}: {dp|rm}' + * '[BigNumber Error] Argument not an object: {format}' + */ + P.toFormat = function (dp, rm, format) { + var str, + x = this; + + if (format == null) { + if (dp != null && rm && typeof rm == 'object') { + format = rm; + rm = null; + } else if (dp && typeof dp == 'object') { + format = dp; + dp = rm = null; + } else { + format = FORMAT; + } + } else if (typeof format != 'object') { + throw Error + (bignumberError + 'Argument not an object: ' + format); + } + + str = x.toFixed(dp, rm); + + if (x.c) { + var i, + arr = str.split('.'), + g1 = +format.groupSize, + g2 = +format.secondaryGroupSize, + groupSeparator = format.groupSeparator || '', + intPart = arr[0], + fractionPart = arr[1], + isNeg = x.s < 0, + intDigits = isNeg ? intPart.slice(1) : intPart, + len = intDigits.length; + + if (g2) i = g1, g1 = g2, g2 = i, len -= i; + + if (g1 > 0 && len > 0) { + i = len % g1 || g1; + intPart = intDigits.substr(0, i); + for (; i < len; i += g1) intPart += groupSeparator + intDigits.substr(i, g1); + if (g2 > 0) intPart += groupSeparator + intDigits.slice(i); + if (isNeg) intPart = '-' + intPart; + } + + str = fractionPart + ? intPart + (format.decimalSeparator || '') + ((g2 = +format.fractionGroupSize) + ? fractionPart.replace(new RegExp('\\d{' + g2 + '}\\B', 'g'), + '$&' + (format.fractionGroupSeparator || '')) + : fractionPart) + : intPart; + } + + return (format.prefix || '') + str + (format.suffix || ''); + }; + + + /* + * Return an array of two BigNumbers representing the value of this BigNumber as a simple + * fraction with an integer numerator and an integer denominator. + * The denominator will be a positive non-zero value less than or equal to the specified + * maximum denominator. If a maximum denominator is not specified, the denominator will be + * the lowest value necessary to represent the number exactly. + * + * [md] {number|string|BigNumber} Integer >= 1, or Infinity. The maximum denominator. + * + * '[BigNumber Error] Argument {not an integer|out of range} : {md}' + */ + P.toFraction = function (md) { + var d, d0, d1, d2, e, exp, n, n0, n1, q, r, s, + x = this, + xc = x.c; + + if (md != null) { + n = new BigNumber(md); + + // Throw if md is less than one or is not an integer, unless it is Infinity. + if (!n.isInteger() && (n.c || n.s !== 1) || n.lt(ONE)) { + throw Error + (bignumberError + 'Argument ' + + (n.isInteger() ? 'out of range: ' : 'not an integer: ') + valueOf(n)); + } + } + + if (!xc) return new BigNumber(x); + + d = new BigNumber(ONE); + n1 = d0 = new BigNumber(ONE); + d1 = n0 = new BigNumber(ONE); + s = coeffToString(xc); + + // Determine initial denominator. + // d is a power of 10 and the minimum max denominator that specifies the value exactly. + e = d.e = s.length - x.e - 1; + d.c[0] = POWS_TEN[(exp = e % LOG_BASE) < 0 ? LOG_BASE + exp : exp]; + md = !md || n.comparedTo(d) > 0 ? (e > 0 ? d : n1) : n; + + exp = MAX_EXP; + MAX_EXP = 1 / 0; + n = new BigNumber(s); + + // n0 = d1 = 0 + n0.c[0] = 0; + + for (; ;) { + q = div(n, d, 0, 1); + d2 = d0.plus(q.times(d1)); + if (d2.comparedTo(md) == 1) break; + d0 = d1; + d1 = d2; + n1 = n0.plus(q.times(d2 = n1)); + n0 = d2; + d = n.minus(q.times(d2 = d)); + n = d2; + } + + d2 = div(md.minus(d0), d1, 0, 1); + n0 = n0.plus(d2.times(n1)); + d0 = d0.plus(d2.times(d1)); + n0.s = n1.s = x.s; + e = e * 2; + + // Determine which fraction is closer to x, n0/d0 or n1/d1 + r = div(n1, d1, e, ROUNDING_MODE).minus(x).abs().comparedTo( + div(n0, d0, e, ROUNDING_MODE).minus(x).abs()) < 1 ? [n1, d1] : [n0, d0]; + + MAX_EXP = exp; + + return r; + }; + + + /* + * Return the value of this BigNumber converted to a number primitive. + */ + P.toNumber = function () { + return +valueOf(this); + }; + + + /* + * Return a string representing the value of this BigNumber rounded to sd significant digits + * using rounding mode rm or ROUNDING_MODE. If sd is less than the number of digits + * necessary to represent the integer part of the value in fixed-point notation, then use + * exponential notation. + * + * [sd] {number} Significant digits. Integer, 1 to MAX inclusive. + * [rm] {number} Rounding mode. Integer, 0 to 8 inclusive. + * + * '[BigNumber Error] Argument {not a primitive number|not an integer|out of range}: {sd|rm}' + */ + P.toPrecision = function (sd, rm) { + if (sd != null) intCheck(sd, 1, MAX); + return format(this, sd, rm, 2); + }; + + + /* + * Return a string representing the value of this BigNumber in base b, or base 10 if b is + * omitted. If a base is specified, including base 10, round according to DECIMAL_PLACES and + * ROUNDING_MODE. If a base is not specified, and this BigNumber has a positive exponent + * that is equal to or greater than TO_EXP_POS, or a negative exponent equal to or less than + * TO_EXP_NEG, return exponential notation. + * + * [b] {number} Integer, 2 to ALPHABET.length inclusive. + * + * '[BigNumber Error] Base {not a primitive number|not an integer|out of range}: {b}' + */ + P.toString = function (b) { + var str, + n = this, + s = n.s, + e = n.e; + + // Infinity or NaN? + if (e === null) { + if (s) { + str = 'Infinity'; + if (s < 0) str = '-' + str; + } else { + str = 'NaN'; + } + } else { + if (b == null) { + str = e <= TO_EXP_NEG || e >= TO_EXP_POS + ? toExponential(coeffToString(n.c), e) + : toFixedPoint(coeffToString(n.c), e, '0'); + } else if (b === 10) { + n = round(new BigNumber(n), DECIMAL_PLACES + e + 1, ROUNDING_MODE); + str = toFixedPoint(coeffToString(n.c), n.e, '0'); + } else { + intCheck(b, 2, ALPHABET.length, 'Base'); + str = convertBase(toFixedPoint(coeffToString(n.c), e, '0'), 10, b, s, true); + } + + if (s < 0 && n.c[0]) str = '-' + str; + } + + return str; + }; + + + /* + * Return as toString, but do not accept a base argument, and include the minus sign for + * negative zero. + */ + P.valueOf = P.toJSON = function () { + return valueOf(this); + }; + + + P._isBigNumber = true; + + if (configObject != null) BigNumber.set(configObject); + + return BigNumber; + } + + + // PRIVATE HELPER FUNCTIONS + + // These functions don't need access to variables, + // e.g. DECIMAL_PLACES, in the scope of the `clone` function above. + + + function bitFloor(n) { + var i = n | 0; + return n > 0 || n === i ? i : i - 1; + } + + + // Return a coefficient array as a string of base 10 digits. + function coeffToString(a) { + var s, z, + i = 1, + j = a.length, + r = a[0] + ''; + + for (; i < j;) { + s = a[i++] + ''; + z = LOG_BASE - s.length; + for (; z--; s = '0' + s); + r += s; + } + + // Determine trailing zeros. + for (j = r.length; r.charCodeAt(--j) === 48;); + + return r.slice(0, j + 1 || 1); + } + + + // Compare the value of BigNumbers x and y. + function compare(x, y) { + var a, b, + xc = x.c, + yc = y.c, + i = x.s, + j = y.s, + k = x.e, + l = y.e; + + // Either NaN? + if (!i || !j) return null; + + a = xc && !xc[0]; + b = yc && !yc[0]; + + // Either zero? + if (a || b) return a ? b ? 0 : -j : i; + + // Signs differ? + if (i != j) return i; + + a = i < 0; + b = k == l; + + // Either Infinity? + if (!xc || !yc) return b ? 0 : !xc ^ a ? 1 : -1; + + // Compare exponents. + if (!b) return k > l ^ a ? 1 : -1; + + j = (k = xc.length) < (l = yc.length) ? k : l; + + // Compare digit by digit. + for (i = 0; i < j; i++) if (xc[i] != yc[i]) return xc[i] > yc[i] ^ a ? 1 : -1; + + // Compare lengths. + return k == l ? 0 : k > l ^ a ? 1 : -1; + } + + + /* + * Check that n is a primitive number, an integer, and in range, otherwise throw. + */ + function intCheck(n, min, max, name) { + if (n < min || n > max || n !== mathfloor(n)) { + throw Error + (bignumberError + (name || 'Argument') + (typeof n == 'number' + ? n < min || n > max ? ' out of range: ' : ' not an integer: ' + : ' not a primitive number: ') + String(n)); + } + } + + + // Assumes finite n. + function isOdd(n) { + var k = n.c.length - 1; + return bitFloor(n.e / LOG_BASE) == k && n.c[k] % 2 != 0; + } + + + function toExponential(str, e) { + return (str.length > 1 ? str.charAt(0) + '.' + str.slice(1) : str) + + (e < 0 ? 'e' : 'e+') + e; + } + + + function toFixedPoint(str, e, z) { + var len, zs; + + // Negative exponent? + if (e < 0) { + + // Prepend zeros. + for (zs = z + '.'; ++e; zs += z); + str = zs + str; + + // Positive exponent + } else { + len = str.length; + + // Append zeros. + if (++e > len) { + for (zs = z, e -= len; --e; zs += z); + str += zs; + } else if (e < len) { + str = str.slice(0, e) + '.' + str.slice(e); + } + } + + return str; + } + + + // EXPORT + + + BigNumber = clone(); + BigNumber['default'] = BigNumber.BigNumber = BigNumber; + + // AMD. + if (typeof define == 'function' && define.amd) { + define(function () { return BigNumber; }); + + // Node.js and other environments that support module.exports. + } else if (typeof module != 'undefined' && module.exports) { + module.exports = BigNumber; + + // Browser. + } else { + if (!globalObject) { + globalObject = typeof self != 'undefined' && self ? self : window; + } + + globalObject.BigNumber = BigNumber; + } +})(this); diff --git a/ts-ticket-office-service/node_modules/bignumber.js/bignumber.min.js b/ts-ticket-office-service/node_modules/bignumber.js/bignumber.min.js new file mode 100644 index 000000000..2610072fd --- /dev/null +++ b/ts-ticket-office-service/node_modules/bignumber.js/bignumber.min.js @@ -0,0 +1 @@ +/* bignumber.js v9.0.0 https://github.com/MikeMcl/bignumber.js/LICENCE */!function(e){"use strict";var r,x=/^-?(?:\d+(?:\.\d*)?|\.\d+)(?:e[+-]?\d+)?$/i,L=Math.ceil,U=Math.floor,I="[BigNumber Error] ",T=I+"Number primitive has more than 15 significant digits: ",C=1e14,M=14,G=9007199254740991,k=[1,10,100,1e3,1e4,1e5,1e6,1e7,1e8,1e9,1e10,1e11,1e12,1e13],F=1e7,q=1e9;function j(e){var r=0|e;return 0o[s]^n?1:-1;return u==l?0:l(t=e.length)){for(i=n,r-=t;--r;i+=n);e+=i}else ry?c.c=c.e=null:e.ey)c.c=c.e=null;else if(oy?e.c=e.e=null:e.c=n=a.length){if(!t)break e;for(;a.length<=l;a.push(0));u=c=0,s=(o%=M)-M+(i=1)}else{for(u=f=a[l],i=1;10<=f;f/=10,i++);c=(s=(o%=M)-M+i)<0?0:u/h[i-s-1]%10|0}if(t=t||r<0||null!=a[l+1]||(s<0?u:u%h[i-s-1]),t=n<4?(c||t)&&(0==n||n==(e.s<0?3:2)):5y?e.c=e.e=null:e.e>>11))?(n=crypto.getRandomValues(new Uint32Array(2)),r[s]=n[0],r[s+1]=n[1]):(f.push(o%1e14),s+=2);s=i/2}else{if(!crypto.randomBytes)throw b=!1,Error(I+"crypto unavailable");for(r=crypto.randomBytes(i*=7);sn-1&&(null==s[i+1]&&(s[i+1]=0),s[i+1]+=s[i]/n|0,s[i]%=n)}return s.reverse()}return function(e,r,n,t,i){var o,s,f,u,l,c,a,h,g=e.indexOf("."),p=N,w=O;for(0<=g&&(u=E,E=0,e=e.replace(".",""),c=(h=new B(r)).pow(e.length-g),E=u,h.c=m(X($(c.c),c.e,"0"),10,n,d),h.e=h.c.length),f=u=(a=m(e,r,n,i?(o=S,d):(o=d,S))).length;0==a[--u];a.pop());if(!a[0])return o.charAt(0);if(g<0?--f:(c.c=a,c.e=f,c.s=t,a=(c=v(c,h,p,w,n)).c,l=c.r,f=c.e),g=a[s=f+p+1],u=n/2,l=l||s<0||null!=a[s+1],l=w<4?(null!=g||l)&&(0==w||w==(c.s<0?3:2)):un;)a[s]=0,s||(++f,a=[1].concat(a));for(u=a.length;!a[--u];);for(g=0,e="";g<=u;e+=o.charAt(a[g++]));e=X(e,f,o.charAt(0))}return e}}(),v=function(){function S(e,r,n){var t,i,o,s,f=0,u=e.length,l=r%F,c=r/F|0;for(e=e.slice();u--;)f=((i=l*(o=e[u]%F)+(t=c*o+(s=e[u]/F|0)*l)%F*F+f)/n|0)+(t/F|0)+c*s,e[u]=i%n;return f&&(e=[f].concat(e)),e}function R(e,r,n,t){var i,o;if(n!=t)o=tr[i]?1:-1;break}return o}function _(e,r,n,t){for(var i=0;n--;)e[n]-=i,i=e[n](E[f]||0)&&s--,b<0)g.push(1),u=!0;else{for(v=E.length,O=A.length,b+=2,1<(l=U(i/(A[f=0]+1)))&&(A=S(A,l,i),E=S(E,l,i),O=A.length,v=E.length),m=O,w=(p=E.slice(0,O)).length;w=i/2&&N++;do{if(l=0,(o=R(A,p,O,w))<0){if(d=p[0],O!=w&&(d=d*i+(p[1]||0)),1<(l=U(d/N)))for(i<=l&&(l=i-1),a=(c=S(A,l,i)).length,w=p.length;1==R(c,p,a,w);)l--,_(c,Oo&&(l.c.length=o):t&&(l=l.mod(r))}if(i){if(0===(i=U(i/2)))break;u=i%2}else if(D(e=e.times(n),e.e+1,1),14o&&(c.c.length=o):t&&(c=c.mod(r))}return t?l:(f&&(l=w.div(l)),r?l.mod(r):o?D(l,E,O,void 0):l)},t.integerValue=function(e){var r=new B(this);return null==e?e=O:H(e,0,8),D(r,r.e+1,e)},t.isEqualTo=t.eq=function(e,r){return 0===z(this,new B(e,r))},t.isFinite=function(){return!!this.c},t.isGreaterThan=t.gt=function(e,r){return 0this.c.length-2},t.isLessThan=t.lt=function(e,r){return z(this,new B(e,r))<0},t.isLessThanOrEqualTo=t.lte=function(e,r){return-1===(r=z(this,new B(e,r)))||0===r},t.isNaN=function(){return!this.s},t.isNegative=function(){return this.s<0},t.isPositive=function(){return 0t&&(t=this.e+1),t},t.shiftedBy=function(e){return H(e,-G,G),this.times("1e"+e)},t.squareRoot=t.sqrt=function(){var e,r,n,t,i,o=this,s=o.c,f=o.s,u=o.e,l=N+4,c=new B("0.5");if(1!==f||!s||!s[0])return new B(!f||f<0&&(!s||s[0])?NaN:s?o:1/0);if((n=0==(f=Math.sqrt(+P(o)))||f==1/0?(((r=$(s)).length+u)%2==0&&(r+="0"),f=Math.sqrt(+r),u=j((u+1)/2)-(u<0||u%2),new B(r=f==1/0?"1e"+u:(r=f.toExponential()).slice(0,r.indexOf("e")+1)+u)):new B(f+"")).c[0])for((f=(u=n.e)+l)<3&&(f=0);;)if(i=n,n=c.times(i.plus(v(o,i,l,1))),$(i.c).slice(0,f)===(r=$(n.c)).slice(0,f)){if(n.e + * MIT Licensed. + * + * BigNumber.prototype methods | BigNumber methods + * | + * absoluteValue abs | clone + * comparedTo | config set + * decimalPlaces dp | DECIMAL_PLACES + * dividedBy div | ROUNDING_MODE + * dividedToIntegerBy idiv | EXPONENTIAL_AT + * exponentiatedBy pow | RANGE + * integerValue | CRYPTO + * isEqualTo eq | MODULO_MODE + * isFinite | POW_PRECISION + * isGreaterThan gt | FORMAT + * isGreaterThanOrEqualTo gte | ALPHABET + * isInteger | isBigNumber + * isLessThan lt | maximum max + * isLessThanOrEqualTo lte | minimum min + * isNaN | random + * isNegative | sum + * isPositive | + * isZero | + * minus | + * modulo mod | + * multipliedBy times | + * negated | + * plus | + * precision sd | + * shiftedBy | + * squareRoot sqrt | + * toExponential | + * toFixed | + * toFormat | + * toFraction | + * toJSON | + * toNumber | + * toPrecision | + * toString | + * valueOf | + * + */ + + +var + isNumeric = /^-?(?:\d+(?:\.\d*)?|\.\d+)(?:e[+-]?\d+)?$/i, + + mathceil = Math.ceil, + mathfloor = Math.floor, + + bignumberError = '[BigNumber Error] ', + tooManyDigits = bignumberError + 'Number primitive has more than 15 significant digits: ', + + BASE = 1e14, + LOG_BASE = 14, + MAX_SAFE_INTEGER = 0x1fffffffffffff, // 2^53 - 1 + // MAX_INT32 = 0x7fffffff, // 2^31 - 1 + POWS_TEN = [1, 10, 100, 1e3, 1e4, 1e5, 1e6, 1e7, 1e8, 1e9, 1e10, 1e11, 1e12, 1e13], + SQRT_BASE = 1e7, + + // EDITABLE + // The limit on the value of DECIMAL_PLACES, TO_EXP_NEG, TO_EXP_POS, MIN_EXP, MAX_EXP, and + // the arguments to toExponential, toFixed, toFormat, and toPrecision. + MAX = 1E9; // 0 to MAX_INT32 + + +/* + * Create and return a BigNumber constructor. + */ +function clone(configObject) { + var div, convertBase, parseNumeric, + P = BigNumber.prototype = { constructor: BigNumber, toString: null, valueOf: null }, + ONE = new BigNumber(1), + + + //----------------------------- EDITABLE CONFIG DEFAULTS ------------------------------- + + + // The default values below must be integers within the inclusive ranges stated. + // The values can also be changed at run-time using BigNumber.set. + + // The maximum number of decimal places for operations involving division. + DECIMAL_PLACES = 20, // 0 to MAX + + // The rounding mode used when rounding to the above decimal places, and when using + // toExponential, toFixed, toFormat and toPrecision, and round (default value). + // UP 0 Away from zero. + // DOWN 1 Towards zero. + // CEIL 2 Towards +Infinity. + // FLOOR 3 Towards -Infinity. + // HALF_UP 4 Towards nearest neighbour. If equidistant, up. + // HALF_DOWN 5 Towards nearest neighbour. If equidistant, down. + // HALF_EVEN 6 Towards nearest neighbour. If equidistant, towards even neighbour. + // HALF_CEIL 7 Towards nearest neighbour. If equidistant, towards +Infinity. + // HALF_FLOOR 8 Towards nearest neighbour. If equidistant, towards -Infinity. + ROUNDING_MODE = 4, // 0 to 8 + + // EXPONENTIAL_AT : [TO_EXP_NEG , TO_EXP_POS] + + // The exponent value at and beneath which toString returns exponential notation. + // Number type: -7 + TO_EXP_NEG = -7, // 0 to -MAX + + // The exponent value at and above which toString returns exponential notation. + // Number type: 21 + TO_EXP_POS = 21, // 0 to MAX + + // RANGE : [MIN_EXP, MAX_EXP] + + // The minimum exponent value, beneath which underflow to zero occurs. + // Number type: -324 (5e-324) + MIN_EXP = -1e7, // -1 to -MAX + + // The maximum exponent value, above which overflow to Infinity occurs. + // Number type: 308 (1.7976931348623157e+308) + // For MAX_EXP > 1e7, e.g. new BigNumber('1e100000000').plus(1) may be slow. + MAX_EXP = 1e7, // 1 to MAX + + // Whether to use cryptographically-secure random number generation, if available. + CRYPTO = false, // true or false + + // The modulo mode used when calculating the modulus: a mod n. + // The quotient (q = a / n) is calculated according to the corresponding rounding mode. + // The remainder (r) is calculated as: r = a - n * q. + // + // UP 0 The remainder is positive if the dividend is negative, else is negative. + // DOWN 1 The remainder has the same sign as the dividend. + // This modulo mode is commonly known as 'truncated division' and is + // equivalent to (a % n) in JavaScript. + // FLOOR 3 The remainder has the same sign as the divisor (Python %). + // HALF_EVEN 6 This modulo mode implements the IEEE 754 remainder function. + // EUCLID 9 Euclidian division. q = sign(n) * floor(a / abs(n)). + // The remainder is always positive. + // + // The truncated division, floored division, Euclidian division and IEEE 754 remainder + // modes are commonly used for the modulus operation. + // Although the other rounding modes can also be used, they may not give useful results. + MODULO_MODE = 1, // 0 to 9 + + // The maximum number of significant digits of the result of the exponentiatedBy operation. + // If POW_PRECISION is 0, there will be unlimited significant digits. + POW_PRECISION = 0, // 0 to MAX + + // The format specification used by the BigNumber.prototype.toFormat method. + FORMAT = { + prefix: '', + groupSize: 3, + secondaryGroupSize: 0, + groupSeparator: ',', + decimalSeparator: '.', + fractionGroupSize: 0, + fractionGroupSeparator: '\xA0', // non-breaking space + suffix: '' + }, + + // The alphabet used for base conversion. It must be at least 2 characters long, with no '+', + // '-', '.', whitespace, or repeated character. + // '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ$_' + ALPHABET = '0123456789abcdefghijklmnopqrstuvwxyz'; + + + //------------------------------------------------------------------------------------------ + + + // CONSTRUCTOR + + + /* + * The BigNumber constructor and exported function. + * Create and return a new instance of a BigNumber object. + * + * v {number|string|BigNumber} A numeric value. + * [b] {number} The base of v. Integer, 2 to ALPHABET.length inclusive. + */ + function BigNumber(v, b) { + var alphabet, c, caseChanged, e, i, isNum, len, str, + x = this; + + // Enable constructor call without `new`. + if (!(x instanceof BigNumber)) return new BigNumber(v, b); + + if (b == null) { + + if (v && v._isBigNumber === true) { + x.s = v.s; + + if (!v.c || v.e > MAX_EXP) { + x.c = x.e = null; + } else if (v.e < MIN_EXP) { + x.c = [x.e = 0]; + } else { + x.e = v.e; + x.c = v.c.slice(); + } + + return; + } + + if ((isNum = typeof v == 'number') && v * 0 == 0) { + + // Use `1 / n` to handle minus zero also. + x.s = 1 / v < 0 ? (v = -v, -1) : 1; + + // Fast path for integers, where n < 2147483648 (2**31). + if (v === ~~v) { + for (e = 0, i = v; i >= 10; i /= 10, e++); + + if (e > MAX_EXP) { + x.c = x.e = null; + } else { + x.e = e; + x.c = [v]; + } + + return; + } + + str = String(v); + } else { + + if (!isNumeric.test(str = String(v))) return parseNumeric(x, str, isNum); + + x.s = str.charCodeAt(0) == 45 ? (str = str.slice(1), -1) : 1; + } + + // Decimal point? + if ((e = str.indexOf('.')) > -1) str = str.replace('.', ''); + + // Exponential form? + if ((i = str.search(/e/i)) > 0) { + + // Determine exponent. + if (e < 0) e = i; + e += +str.slice(i + 1); + str = str.substring(0, i); + } else if (e < 0) { + + // Integer. + e = str.length; + } + + } else { + + // '[BigNumber Error] Base {not a primitive number|not an integer|out of range}: {b}' + intCheck(b, 2, ALPHABET.length, 'Base'); + + // Allow exponential notation to be used with base 10 argument, while + // also rounding to DECIMAL_PLACES as with other bases. + if (b == 10) { + x = new BigNumber(v); + return round(x, DECIMAL_PLACES + x.e + 1, ROUNDING_MODE); + } + + str = String(v); + + if (isNum = typeof v == 'number') { + + // Avoid potential interpretation of Infinity and NaN as base 44+ values. + if (v * 0 != 0) return parseNumeric(x, str, isNum, b); + + x.s = 1 / v < 0 ? (str = str.slice(1), -1) : 1; + + // '[BigNumber Error] Number primitive has more than 15 significant digits: {n}' + if (BigNumber.DEBUG && str.replace(/^0\.0*|\./, '').length > 15) { + throw Error + (tooManyDigits + v); + } + } else { + x.s = str.charCodeAt(0) === 45 ? (str = str.slice(1), -1) : 1; + } + + alphabet = ALPHABET.slice(0, b); + e = i = 0; + + // Check that str is a valid base b number. + // Don't use RegExp, so alphabet can contain special characters. + for (len = str.length; i < len; i++) { + if (alphabet.indexOf(c = str.charAt(i)) < 0) { + if (c == '.') { + + // If '.' is not the first character and it has not be found before. + if (i > e) { + e = len; + continue; + } + } else if (!caseChanged) { + + // Allow e.g. hexadecimal 'FF' as well as 'ff'. + if (str == str.toUpperCase() && (str = str.toLowerCase()) || + str == str.toLowerCase() && (str = str.toUpperCase())) { + caseChanged = true; + i = -1; + e = 0; + continue; + } + } + + return parseNumeric(x, String(v), isNum, b); + } + } + + // Prevent later check for length on converted number. + isNum = false; + str = convertBase(str, b, 10, x.s); + + // Decimal point? + if ((e = str.indexOf('.')) > -1) str = str.replace('.', ''); + else e = str.length; + } + + // Determine leading zeros. + for (i = 0; str.charCodeAt(i) === 48; i++); + + // Determine trailing zeros. + for (len = str.length; str.charCodeAt(--len) === 48;); + + if (str = str.slice(i, ++len)) { + len -= i; + + // '[BigNumber Error] Number primitive has more than 15 significant digits: {n}' + if (isNum && BigNumber.DEBUG && + len > 15 && (v > MAX_SAFE_INTEGER || v !== mathfloor(v))) { + throw Error + (tooManyDigits + (x.s * v)); + } + + // Overflow? + if ((e = e - i - 1) > MAX_EXP) { + + // Infinity. + x.c = x.e = null; + + // Underflow? + } else if (e < MIN_EXP) { + + // Zero. + x.c = [x.e = 0]; + } else { + x.e = e; + x.c = []; + + // Transform base + + // e is the base 10 exponent. + // i is where to slice str to get the first element of the coefficient array. + i = (e + 1) % LOG_BASE; + if (e < 0) i += LOG_BASE; // i < 1 + + if (i < len) { + if (i) x.c.push(+str.slice(0, i)); + + for (len -= LOG_BASE; i < len;) { + x.c.push(+str.slice(i, i += LOG_BASE)); + } + + i = LOG_BASE - (str = str.slice(i)).length; + } else { + i -= len; + } + + for (; i--; str += '0'); + x.c.push(+str); + } + } else { + + // Zero. + x.c = [x.e = 0]; + } + } + + + // CONSTRUCTOR PROPERTIES + + + BigNumber.clone = clone; + + BigNumber.ROUND_UP = 0; + BigNumber.ROUND_DOWN = 1; + BigNumber.ROUND_CEIL = 2; + BigNumber.ROUND_FLOOR = 3; + BigNumber.ROUND_HALF_UP = 4; + BigNumber.ROUND_HALF_DOWN = 5; + BigNumber.ROUND_HALF_EVEN = 6; + BigNumber.ROUND_HALF_CEIL = 7; + BigNumber.ROUND_HALF_FLOOR = 8; + BigNumber.EUCLID = 9; + + + /* + * Configure infrequently-changing library-wide settings. + * + * Accept an object with the following optional properties (if the value of a property is + * a number, it must be an integer within the inclusive range stated): + * + * DECIMAL_PLACES {number} 0 to MAX + * ROUNDING_MODE {number} 0 to 8 + * EXPONENTIAL_AT {number|number[]} -MAX to MAX or [-MAX to 0, 0 to MAX] + * RANGE {number|number[]} -MAX to MAX (not zero) or [-MAX to -1, 1 to MAX] + * CRYPTO {boolean} true or false + * MODULO_MODE {number} 0 to 9 + * POW_PRECISION {number} 0 to MAX + * ALPHABET {string} A string of two or more unique characters which does + * not contain '.'. + * FORMAT {object} An object with some of the following properties: + * prefix {string} + * groupSize {number} + * secondaryGroupSize {number} + * groupSeparator {string} + * decimalSeparator {string} + * fractionGroupSize {number} + * fractionGroupSeparator {string} + * suffix {string} + * + * (The values assigned to the above FORMAT object properties are not checked for validity.) + * + * E.g. + * BigNumber.config({ DECIMAL_PLACES : 20, ROUNDING_MODE : 4 }) + * + * Ignore properties/parameters set to null or undefined, except for ALPHABET. + * + * Return an object with the properties current values. + */ + BigNumber.config = BigNumber.set = function (obj) { + var p, v; + + if (obj != null) { + + if (typeof obj == 'object') { + + // DECIMAL_PLACES {number} Integer, 0 to MAX inclusive. + // '[BigNumber Error] DECIMAL_PLACES {not a primitive number|not an integer|out of range}: {v}' + if (obj.hasOwnProperty(p = 'DECIMAL_PLACES')) { + v = obj[p]; + intCheck(v, 0, MAX, p); + DECIMAL_PLACES = v; + } + + // ROUNDING_MODE {number} Integer, 0 to 8 inclusive. + // '[BigNumber Error] ROUNDING_MODE {not a primitive number|not an integer|out of range}: {v}' + if (obj.hasOwnProperty(p = 'ROUNDING_MODE')) { + v = obj[p]; + intCheck(v, 0, 8, p); + ROUNDING_MODE = v; + } + + // EXPONENTIAL_AT {number|number[]} + // Integer, -MAX to MAX inclusive or + // [integer -MAX to 0 inclusive, 0 to MAX inclusive]. + // '[BigNumber Error] EXPONENTIAL_AT {not a primitive number|not an integer|out of range}: {v}' + if (obj.hasOwnProperty(p = 'EXPONENTIAL_AT')) { + v = obj[p]; + if (v && v.pop) { + intCheck(v[0], -MAX, 0, p); + intCheck(v[1], 0, MAX, p); + TO_EXP_NEG = v[0]; + TO_EXP_POS = v[1]; + } else { + intCheck(v, -MAX, MAX, p); + TO_EXP_NEG = -(TO_EXP_POS = v < 0 ? -v : v); + } + } + + // RANGE {number|number[]} Non-zero integer, -MAX to MAX inclusive or + // [integer -MAX to -1 inclusive, integer 1 to MAX inclusive]. + // '[BigNumber Error] RANGE {not a primitive number|not an integer|out of range|cannot be zero}: {v}' + if (obj.hasOwnProperty(p = 'RANGE')) { + v = obj[p]; + if (v && v.pop) { + intCheck(v[0], -MAX, -1, p); + intCheck(v[1], 1, MAX, p); + MIN_EXP = v[0]; + MAX_EXP = v[1]; + } else { + intCheck(v, -MAX, MAX, p); + if (v) { + MIN_EXP = -(MAX_EXP = v < 0 ? -v : v); + } else { + throw Error + (bignumberError + p + ' cannot be zero: ' + v); + } + } + } + + // CRYPTO {boolean} true or false. + // '[BigNumber Error] CRYPTO not true or false: {v}' + // '[BigNumber Error] crypto unavailable' + if (obj.hasOwnProperty(p = 'CRYPTO')) { + v = obj[p]; + if (v === !!v) { + if (v) { + if (typeof crypto != 'undefined' && crypto && + (crypto.getRandomValues || crypto.randomBytes)) { + CRYPTO = v; + } else { + CRYPTO = !v; + throw Error + (bignumberError + 'crypto unavailable'); + } + } else { + CRYPTO = v; + } + } else { + throw Error + (bignumberError + p + ' not true or false: ' + v); + } + } + + // MODULO_MODE {number} Integer, 0 to 9 inclusive. + // '[BigNumber Error] MODULO_MODE {not a primitive number|not an integer|out of range}: {v}' + if (obj.hasOwnProperty(p = 'MODULO_MODE')) { + v = obj[p]; + intCheck(v, 0, 9, p); + MODULO_MODE = v; + } + + // POW_PRECISION {number} Integer, 0 to MAX inclusive. + // '[BigNumber Error] POW_PRECISION {not a primitive number|not an integer|out of range}: {v}' + if (obj.hasOwnProperty(p = 'POW_PRECISION')) { + v = obj[p]; + intCheck(v, 0, MAX, p); + POW_PRECISION = v; + } + + // FORMAT {object} + // '[BigNumber Error] FORMAT not an object: {v}' + if (obj.hasOwnProperty(p = 'FORMAT')) { + v = obj[p]; + if (typeof v == 'object') FORMAT = v; + else throw Error + (bignumberError + p + ' not an object: ' + v); + } + + // ALPHABET {string} + // '[BigNumber Error] ALPHABET invalid: {v}' + if (obj.hasOwnProperty(p = 'ALPHABET')) { + v = obj[p]; + + // Disallow if only one character, + // or if it contains '+', '-', '.', whitespace, or a repeated character. + if (typeof v == 'string' && !/^.$|[+-.\s]|(.).*\1/.test(v)) { + ALPHABET = v; + } else { + throw Error + (bignumberError + p + ' invalid: ' + v); + } + } + + } else { + + // '[BigNumber Error] Object expected: {v}' + throw Error + (bignumberError + 'Object expected: ' + obj); + } + } + + return { + DECIMAL_PLACES: DECIMAL_PLACES, + ROUNDING_MODE: ROUNDING_MODE, + EXPONENTIAL_AT: [TO_EXP_NEG, TO_EXP_POS], + RANGE: [MIN_EXP, MAX_EXP], + CRYPTO: CRYPTO, + MODULO_MODE: MODULO_MODE, + POW_PRECISION: POW_PRECISION, + FORMAT: FORMAT, + ALPHABET: ALPHABET + }; + }; + + + /* + * Return true if v is a BigNumber instance, otherwise return false. + * + * If BigNumber.DEBUG is true, throw if a BigNumber instance is not well-formed. + * + * v {any} + * + * '[BigNumber Error] Invalid BigNumber: {v}' + */ + BigNumber.isBigNumber = function (v) { + if (!v || v._isBigNumber !== true) return false; + if (!BigNumber.DEBUG) return true; + + var i, n, + c = v.c, + e = v.e, + s = v.s; + + out: if ({}.toString.call(c) == '[object Array]') { + + if ((s === 1 || s === -1) && e >= -MAX && e <= MAX && e === mathfloor(e)) { + + // If the first element is zero, the BigNumber value must be zero. + if (c[0] === 0) { + if (e === 0 && c.length === 1) return true; + break out; + } + + // Calculate number of digits that c[0] should have, based on the exponent. + i = (e + 1) % LOG_BASE; + if (i < 1) i += LOG_BASE; + + // Calculate number of digits of c[0]. + //if (Math.ceil(Math.log(c[0] + 1) / Math.LN10) == i) { + if (String(c[0]).length == i) { + + for (i = 0; i < c.length; i++) { + n = c[i]; + if (n < 0 || n >= BASE || n !== mathfloor(n)) break out; + } + + // Last element cannot be zero, unless it is the only element. + if (n !== 0) return true; + } + } + + // Infinity/NaN + } else if (c === null && e === null && (s === null || s === 1 || s === -1)) { + return true; + } + + throw Error + (bignumberError + 'Invalid BigNumber: ' + v); + }; + + + /* + * Return a new BigNumber whose value is the maximum of the arguments. + * + * arguments {number|string|BigNumber} + */ + BigNumber.maximum = BigNumber.max = function () { + return maxOrMin(arguments, P.lt); + }; + + + /* + * Return a new BigNumber whose value is the minimum of the arguments. + * + * arguments {number|string|BigNumber} + */ + BigNumber.minimum = BigNumber.min = function () { + return maxOrMin(arguments, P.gt); + }; + + + /* + * Return a new BigNumber with a random value equal to or greater than 0 and less than 1, + * and with dp, or DECIMAL_PLACES if dp is omitted, decimal places (or less if trailing + * zeros are produced). + * + * [dp] {number} Decimal places. Integer, 0 to MAX inclusive. + * + * '[BigNumber Error] Argument {not a primitive number|not an integer|out of range}: {dp}' + * '[BigNumber Error] crypto unavailable' + */ + BigNumber.random = (function () { + var pow2_53 = 0x20000000000000; + + // Return a 53 bit integer n, where 0 <= n < 9007199254740992. + // Check if Math.random() produces more than 32 bits of randomness. + // If it does, assume at least 53 bits are produced, otherwise assume at least 30 bits. + // 0x40000000 is 2^30, 0x800000 is 2^23, 0x1fffff is 2^21 - 1. + var random53bitInt = (Math.random() * pow2_53) & 0x1fffff + ? function () { return mathfloor(Math.random() * pow2_53); } + : function () { return ((Math.random() * 0x40000000 | 0) * 0x800000) + + (Math.random() * 0x800000 | 0); }; + + return function (dp) { + var a, b, e, k, v, + i = 0, + c = [], + rand = new BigNumber(ONE); + + if (dp == null) dp = DECIMAL_PLACES; + else intCheck(dp, 0, MAX); + + k = mathceil(dp / LOG_BASE); + + if (CRYPTO) { + + // Browsers supporting crypto.getRandomValues. + if (crypto.getRandomValues) { + + a = crypto.getRandomValues(new Uint32Array(k *= 2)); + + for (; i < k;) { + + // 53 bits: + // ((Math.pow(2, 32) - 1) * Math.pow(2, 21)).toString(2) + // 11111 11111111 11111111 11111111 11100000 00000000 00000000 + // ((Math.pow(2, 32) - 1) >>> 11).toString(2) + // 11111 11111111 11111111 + // 0x20000 is 2^21. + v = a[i] * 0x20000 + (a[i + 1] >>> 11); + + // Rejection sampling: + // 0 <= v < 9007199254740992 + // Probability that v >= 9e15, is + // 7199254740992 / 9007199254740992 ~= 0.0008, i.e. 1 in 1251 + if (v >= 9e15) { + b = crypto.getRandomValues(new Uint32Array(2)); + a[i] = b[0]; + a[i + 1] = b[1]; + } else { + + // 0 <= v <= 8999999999999999 + // 0 <= (v % 1e14) <= 99999999999999 + c.push(v % 1e14); + i += 2; + } + } + i = k / 2; + + // Node.js supporting crypto.randomBytes. + } else if (crypto.randomBytes) { + + // buffer + a = crypto.randomBytes(k *= 7); + + for (; i < k;) { + + // 0x1000000000000 is 2^48, 0x10000000000 is 2^40 + // 0x100000000 is 2^32, 0x1000000 is 2^24 + // 11111 11111111 11111111 11111111 11111111 11111111 11111111 + // 0 <= v < 9007199254740992 + v = ((a[i] & 31) * 0x1000000000000) + (a[i + 1] * 0x10000000000) + + (a[i + 2] * 0x100000000) + (a[i + 3] * 0x1000000) + + (a[i + 4] << 16) + (a[i + 5] << 8) + a[i + 6]; + + if (v >= 9e15) { + crypto.randomBytes(7).copy(a, i); + } else { + + // 0 <= (v % 1e14) <= 99999999999999 + c.push(v % 1e14); + i += 7; + } + } + i = k / 7; + } else { + CRYPTO = false; + throw Error + (bignumberError + 'crypto unavailable'); + } + } + + // Use Math.random. + if (!CRYPTO) { + + for (; i < k;) { + v = random53bitInt(); + if (v < 9e15) c[i++] = v % 1e14; + } + } + + k = c[--i]; + dp %= LOG_BASE; + + // Convert trailing digits to zeros according to dp. + if (k && dp) { + v = POWS_TEN[LOG_BASE - dp]; + c[i] = mathfloor(k / v) * v; + } + + // Remove trailing elements which are zero. + for (; c[i] === 0; c.pop(), i--); + + // Zero? + if (i < 0) { + c = [e = 0]; + } else { + + // Remove leading elements which are zero and adjust exponent accordingly. + for (e = -1 ; c[0] === 0; c.splice(0, 1), e -= LOG_BASE); + + // Count the digits of the first element of c to determine leading zeros, and... + for (i = 1, v = c[0]; v >= 10; v /= 10, i++); + + // adjust the exponent accordingly. + if (i < LOG_BASE) e -= LOG_BASE - i; + } + + rand.e = e; + rand.c = c; + return rand; + }; + })(); + + + /* + * Return a BigNumber whose value is the sum of the arguments. + * + * arguments {number|string|BigNumber} + */ + BigNumber.sum = function () { + var i = 1, + args = arguments, + sum = new BigNumber(args[0]); + for (; i < args.length;) sum = sum.plus(args[i++]); + return sum; + }; + + + // PRIVATE FUNCTIONS + + + // Called by BigNumber and BigNumber.prototype.toString. + convertBase = (function () { + var decimal = '0123456789'; + + /* + * Convert string of baseIn to an array of numbers of baseOut. + * Eg. toBaseOut('255', 10, 16) returns [15, 15]. + * Eg. toBaseOut('ff', 16, 10) returns [2, 5, 5]. + */ + function toBaseOut(str, baseIn, baseOut, alphabet) { + var j, + arr = [0], + arrL, + i = 0, + len = str.length; + + for (; i < len;) { + for (arrL = arr.length; arrL--; arr[arrL] *= baseIn); + + arr[0] += alphabet.indexOf(str.charAt(i++)); + + for (j = 0; j < arr.length; j++) { + + if (arr[j] > baseOut - 1) { + if (arr[j + 1] == null) arr[j + 1] = 0; + arr[j + 1] += arr[j] / baseOut | 0; + arr[j] %= baseOut; + } + } + } + + return arr.reverse(); + } + + // Convert a numeric string of baseIn to a numeric string of baseOut. + // If the caller is toString, we are converting from base 10 to baseOut. + // If the caller is BigNumber, we are converting from baseIn to base 10. + return function (str, baseIn, baseOut, sign, callerIsToString) { + var alphabet, d, e, k, r, x, xc, y, + i = str.indexOf('.'), + dp = DECIMAL_PLACES, + rm = ROUNDING_MODE; + + // Non-integer. + if (i >= 0) { + k = POW_PRECISION; + + // Unlimited precision. + POW_PRECISION = 0; + str = str.replace('.', ''); + y = new BigNumber(baseIn); + x = y.pow(str.length - i); + POW_PRECISION = k; + + // Convert str as if an integer, then restore the fraction part by dividing the + // result by its base raised to a power. + + y.c = toBaseOut(toFixedPoint(coeffToString(x.c), x.e, '0'), + 10, baseOut, decimal); + y.e = y.c.length; + } + + // Convert the number as integer. + + xc = toBaseOut(str, baseIn, baseOut, callerIsToString + ? (alphabet = ALPHABET, decimal) + : (alphabet = decimal, ALPHABET)); + + // xc now represents str as an integer and converted to baseOut. e is the exponent. + e = k = xc.length; + + // Remove trailing zeros. + for (; xc[--k] == 0; xc.pop()); + + // Zero? + if (!xc[0]) return alphabet.charAt(0); + + // Does str represent an integer? If so, no need for the division. + if (i < 0) { + --e; + } else { + x.c = xc; + x.e = e; + + // The sign is needed for correct rounding. + x.s = sign; + x = div(x, y, dp, rm, baseOut); + xc = x.c; + r = x.r; + e = x.e; + } + + // xc now represents str converted to baseOut. + + // THe index of the rounding digit. + d = e + dp + 1; + + // The rounding digit: the digit to the right of the digit that may be rounded up. + i = xc[d]; + + // Look at the rounding digits and mode to determine whether to round up. + + k = baseOut / 2; + r = r || d < 0 || xc[d + 1] != null; + + r = rm < 4 ? (i != null || r) && (rm == 0 || rm == (x.s < 0 ? 3 : 2)) + : i > k || i == k &&(rm == 4 || r || rm == 6 && xc[d - 1] & 1 || + rm == (x.s < 0 ? 8 : 7)); + + // If the index of the rounding digit is not greater than zero, or xc represents + // zero, then the result of the base conversion is zero or, if rounding up, a value + // such as 0.00001. + if (d < 1 || !xc[0]) { + + // 1^-dp or 0 + str = r ? toFixedPoint(alphabet.charAt(1), -dp, alphabet.charAt(0)) : alphabet.charAt(0); + } else { + + // Truncate xc to the required number of decimal places. + xc.length = d; + + // Round up? + if (r) { + + // Rounding up may mean the previous digit has to be rounded up and so on. + for (--baseOut; ++xc[--d] > baseOut;) { + xc[d] = 0; + + if (!d) { + ++e; + xc = [1].concat(xc); + } + } + } + + // Determine trailing zeros. + for (k = xc.length; !xc[--k];); + + // E.g. [4, 11, 15] becomes 4bf. + for (i = 0, str = ''; i <= k; str += alphabet.charAt(xc[i++])); + + // Add leading zeros, decimal point and trailing zeros as required. + str = toFixedPoint(str, e, alphabet.charAt(0)); + } + + // The caller will add the sign. + return str; + }; + })(); + + + // Perform division in the specified base. Called by div and convertBase. + div = (function () { + + // Assume non-zero x and k. + function multiply(x, k, base) { + var m, temp, xlo, xhi, + carry = 0, + i = x.length, + klo = k % SQRT_BASE, + khi = k / SQRT_BASE | 0; + + for (x = x.slice(); i--;) { + xlo = x[i] % SQRT_BASE; + xhi = x[i] / SQRT_BASE | 0; + m = khi * xlo + xhi * klo; + temp = klo * xlo + ((m % SQRT_BASE) * SQRT_BASE) + carry; + carry = (temp / base | 0) + (m / SQRT_BASE | 0) + khi * xhi; + x[i] = temp % base; + } + + if (carry) x = [carry].concat(x); + + return x; + } + + function compare(a, b, aL, bL) { + var i, cmp; + + if (aL != bL) { + cmp = aL > bL ? 1 : -1; + } else { + + for (i = cmp = 0; i < aL; i++) { + + if (a[i] != b[i]) { + cmp = a[i] > b[i] ? 1 : -1; + break; + } + } + } + + return cmp; + } + + function subtract(a, b, aL, base) { + var i = 0; + + // Subtract b from a. + for (; aL--;) { + a[aL] -= i; + i = a[aL] < b[aL] ? 1 : 0; + a[aL] = i * base + a[aL] - b[aL]; + } + + // Remove leading zeros. + for (; !a[0] && a.length > 1; a.splice(0, 1)); + } + + // x: dividend, y: divisor. + return function (x, y, dp, rm, base) { + var cmp, e, i, more, n, prod, prodL, q, qc, rem, remL, rem0, xi, xL, yc0, + yL, yz, + s = x.s == y.s ? 1 : -1, + xc = x.c, + yc = y.c; + + // Either NaN, Infinity or 0? + if (!xc || !xc[0] || !yc || !yc[0]) { + + return new BigNumber( + + // Return NaN if either NaN, or both Infinity or 0. + !x.s || !y.s || (xc ? yc && xc[0] == yc[0] : !yc) ? NaN : + + // Return ±0 if x is ±0 or y is ±Infinity, or return ±Infinity as y is ±0. + xc && xc[0] == 0 || !yc ? s * 0 : s / 0 + ); + } + + q = new BigNumber(s); + qc = q.c = []; + e = x.e - y.e; + s = dp + e + 1; + + if (!base) { + base = BASE; + e = bitFloor(x.e / LOG_BASE) - bitFloor(y.e / LOG_BASE); + s = s / LOG_BASE | 0; + } + + // Result exponent may be one less then the current value of e. + // The coefficients of the BigNumbers from convertBase may have trailing zeros. + for (i = 0; yc[i] == (xc[i] || 0); i++); + + if (yc[i] > (xc[i] || 0)) e--; + + if (s < 0) { + qc.push(1); + more = true; + } else { + xL = xc.length; + yL = yc.length; + i = 0; + s += 2; + + // Normalise xc and yc so highest order digit of yc is >= base / 2. + + n = mathfloor(base / (yc[0] + 1)); + + // Not necessary, but to handle odd bases where yc[0] == (base / 2) - 1. + // if (n > 1 || n++ == 1 && yc[0] < base / 2) { + if (n > 1) { + yc = multiply(yc, n, base); + xc = multiply(xc, n, base); + yL = yc.length; + xL = xc.length; + } + + xi = yL; + rem = xc.slice(0, yL); + remL = rem.length; + + // Add zeros to make remainder as long as divisor. + for (; remL < yL; rem[remL++] = 0); + yz = yc.slice(); + yz = [0].concat(yz); + yc0 = yc[0]; + if (yc[1] >= base / 2) yc0++; + // Not necessary, but to prevent trial digit n > base, when using base 3. + // else if (base == 3 && yc0 == 1) yc0 = 1 + 1e-15; + + do { + n = 0; + + // Compare divisor and remainder. + cmp = compare(yc, rem, yL, remL); + + // If divisor < remainder. + if (cmp < 0) { + + // Calculate trial digit, n. + + rem0 = rem[0]; + if (yL != remL) rem0 = rem0 * base + (rem[1] || 0); + + // n is how many times the divisor goes into the current remainder. + n = mathfloor(rem0 / yc0); + + // Algorithm: + // product = divisor multiplied by trial digit (n). + // Compare product and remainder. + // If product is greater than remainder: + // Subtract divisor from product, decrement trial digit. + // Subtract product from remainder. + // If product was less than remainder at the last compare: + // Compare new remainder and divisor. + // If remainder is greater than divisor: + // Subtract divisor from remainder, increment trial digit. + + if (n > 1) { + + // n may be > base only when base is 3. + if (n >= base) n = base - 1; + + // product = divisor * trial digit. + prod = multiply(yc, n, base); + prodL = prod.length; + remL = rem.length; + + // Compare product and remainder. + // If product > remainder then trial digit n too high. + // n is 1 too high about 5% of the time, and is not known to have + // ever been more than 1 too high. + while (compare(prod, rem, prodL, remL) == 1) { + n--; + + // Subtract divisor from product. + subtract(prod, yL < prodL ? yz : yc, prodL, base); + prodL = prod.length; + cmp = 1; + } + } else { + + // n is 0 or 1, cmp is -1. + // If n is 0, there is no need to compare yc and rem again below, + // so change cmp to 1 to avoid it. + // If n is 1, leave cmp as -1, so yc and rem are compared again. + if (n == 0) { + + // divisor < remainder, so n must be at least 1. + cmp = n = 1; + } + + // product = divisor + prod = yc.slice(); + prodL = prod.length; + } + + if (prodL < remL) prod = [0].concat(prod); + + // Subtract product from remainder. + subtract(rem, prod, remL, base); + remL = rem.length; + + // If product was < remainder. + if (cmp == -1) { + + // Compare divisor and new remainder. + // If divisor < new remainder, subtract divisor from remainder. + // Trial digit n too low. + // n is 1 too low about 5% of the time, and very rarely 2 too low. + while (compare(yc, rem, yL, remL) < 1) { + n++; + + // Subtract divisor from remainder. + subtract(rem, yL < remL ? yz : yc, remL, base); + remL = rem.length; + } + } + } else if (cmp === 0) { + n++; + rem = [0]; + } // else cmp === 1 and n will be 0 + + // Add the next digit, n, to the result array. + qc[i++] = n; + + // Update the remainder. + if (rem[0]) { + rem[remL++] = xc[xi] || 0; + } else { + rem = [xc[xi]]; + remL = 1; + } + } while ((xi++ < xL || rem[0] != null) && s--); + + more = rem[0] != null; + + // Leading zero? + if (!qc[0]) qc.splice(0, 1); + } + + if (base == BASE) { + + // To calculate q.e, first get the number of digits of qc[0]. + for (i = 1, s = qc[0]; s >= 10; s /= 10, i++); + + round(q, dp + (q.e = i + e * LOG_BASE - 1) + 1, rm, more); + + // Caller is convertBase. + } else { + q.e = e; + q.r = +more; + } + + return q; + }; + })(); + + + /* + * Return a string representing the value of BigNumber n in fixed-point or exponential + * notation rounded to the specified decimal places or significant digits. + * + * n: a BigNumber. + * i: the index of the last digit required (i.e. the digit that may be rounded up). + * rm: the rounding mode. + * id: 1 (toExponential) or 2 (toPrecision). + */ + function format(n, i, rm, id) { + var c0, e, ne, len, str; + + if (rm == null) rm = ROUNDING_MODE; + else intCheck(rm, 0, 8); + + if (!n.c) return n.toString(); + + c0 = n.c[0]; + ne = n.e; + + if (i == null) { + str = coeffToString(n.c); + str = id == 1 || id == 2 && (ne <= TO_EXP_NEG || ne >= TO_EXP_POS) + ? toExponential(str, ne) + : toFixedPoint(str, ne, '0'); + } else { + n = round(new BigNumber(n), i, rm); + + // n.e may have changed if the value was rounded up. + e = n.e; + + str = coeffToString(n.c); + len = str.length; + + // toPrecision returns exponential notation if the number of significant digits + // specified is less than the number of digits necessary to represent the integer + // part of the value in fixed-point notation. + + // Exponential notation. + if (id == 1 || id == 2 && (i <= e || e <= TO_EXP_NEG)) { + + // Append zeros? + for (; len < i; str += '0', len++); + str = toExponential(str, e); + + // Fixed-point notation. + } else { + i -= ne; + str = toFixedPoint(str, e, '0'); + + // Append zeros? + if (e + 1 > len) { + if (--i > 0) for (str += '.'; i--; str += '0'); + } else { + i += e - len; + if (i > 0) { + if (e + 1 == len) str += '.'; + for (; i--; str += '0'); + } + } + } + } + + return n.s < 0 && c0 ? '-' + str : str; + } + + + // Handle BigNumber.max and BigNumber.min. + function maxOrMin(args, method) { + var n, + i = 1, + m = new BigNumber(args[0]); + + for (; i < args.length; i++) { + n = new BigNumber(args[i]); + + // If any number is NaN, return NaN. + if (!n.s) { + m = n; + break; + } else if (method.call(m, n)) { + m = n; + } + } + + return m; + } + + + /* + * Strip trailing zeros, calculate base 10 exponent and check against MIN_EXP and MAX_EXP. + * Called by minus, plus and times. + */ + function normalise(n, c, e) { + var i = 1, + j = c.length; + + // Remove trailing zeros. + for (; !c[--j]; c.pop()); + + // Calculate the base 10 exponent. First get the number of digits of c[0]. + for (j = c[0]; j >= 10; j /= 10, i++); + + // Overflow? + if ((e = i + e * LOG_BASE - 1) > MAX_EXP) { + + // Infinity. + n.c = n.e = null; + + // Underflow? + } else if (e < MIN_EXP) { + + // Zero. + n.c = [n.e = 0]; + } else { + n.e = e; + n.c = c; + } + + return n; + } + + + // Handle values that fail the validity test in BigNumber. + parseNumeric = (function () { + var basePrefix = /^(-?)0([xbo])(?=\w[\w.]*$)/i, + dotAfter = /^([^.]+)\.$/, + dotBefore = /^\.([^.]+)$/, + isInfinityOrNaN = /^-?(Infinity|NaN)$/, + whitespaceOrPlus = /^\s*\+(?=[\w.])|^\s+|\s+$/g; + + return function (x, str, isNum, b) { + var base, + s = isNum ? str : str.replace(whitespaceOrPlus, ''); + + // No exception on ±Infinity or NaN. + if (isInfinityOrNaN.test(s)) { + x.s = isNaN(s) ? null : s < 0 ? -1 : 1; + } else { + if (!isNum) { + + // basePrefix = /^(-?)0([xbo])(?=\w[\w.]*$)/i + s = s.replace(basePrefix, function (m, p1, p2) { + base = (p2 = p2.toLowerCase()) == 'x' ? 16 : p2 == 'b' ? 2 : 8; + return !b || b == base ? p1 : m; + }); + + if (b) { + base = b; + + // E.g. '1.' to '1', '.1' to '0.1' + s = s.replace(dotAfter, '$1').replace(dotBefore, '0.$1'); + } + + if (str != s) return new BigNumber(s, base); + } + + // '[BigNumber Error] Not a number: {n}' + // '[BigNumber Error] Not a base {b} number: {n}' + if (BigNumber.DEBUG) { + throw Error + (bignumberError + 'Not a' + (b ? ' base ' + b : '') + ' number: ' + str); + } + + // NaN + x.s = null; + } + + x.c = x.e = null; + } + })(); + + + /* + * Round x to sd significant digits using rounding mode rm. Check for over/under-flow. + * If r is truthy, it is known that there are more digits after the rounding digit. + */ + function round(x, sd, rm, r) { + var d, i, j, k, n, ni, rd, + xc = x.c, + pows10 = POWS_TEN; + + // if x is not Infinity or NaN... + if (xc) { + + // rd is the rounding digit, i.e. the digit after the digit that may be rounded up. + // n is a base 1e14 number, the value of the element of array x.c containing rd. + // ni is the index of n within x.c. + // d is the number of digits of n. + // i is the index of rd within n including leading zeros. + // j is the actual index of rd within n (if < 0, rd is a leading zero). + out: { + + // Get the number of digits of the first element of xc. + for (d = 1, k = xc[0]; k >= 10; k /= 10, d++); + i = sd - d; + + // If the rounding digit is in the first element of xc... + if (i < 0) { + i += LOG_BASE; + j = sd; + n = xc[ni = 0]; + + // Get the rounding digit at index j of n. + rd = n / pows10[d - j - 1] % 10 | 0; + } else { + ni = mathceil((i + 1) / LOG_BASE); + + if (ni >= xc.length) { + + if (r) { + + // Needed by sqrt. + for (; xc.length <= ni; xc.push(0)); + n = rd = 0; + d = 1; + i %= LOG_BASE; + j = i - LOG_BASE + 1; + } else { + break out; + } + } else { + n = k = xc[ni]; + + // Get the number of digits of n. + for (d = 1; k >= 10; k /= 10, d++); + + // Get the index of rd within n. + i %= LOG_BASE; + + // Get the index of rd within n, adjusted for leading zeros. + // The number of leading zeros of n is given by LOG_BASE - d. + j = i - LOG_BASE + d; + + // Get the rounding digit at index j of n. + rd = j < 0 ? 0 : n / pows10[d - j - 1] % 10 | 0; + } + } + + r = r || sd < 0 || + + // Are there any non-zero digits after the rounding digit? + // The expression n % pows10[d - j - 1] returns all digits of n to the right + // of the digit at j, e.g. if n is 908714 and j is 2, the expression gives 714. + xc[ni + 1] != null || (j < 0 ? n : n % pows10[d - j - 1]); + + r = rm < 4 + ? (rd || r) && (rm == 0 || rm == (x.s < 0 ? 3 : 2)) + : rd > 5 || rd == 5 && (rm == 4 || r || rm == 6 && + + // Check whether the digit to the left of the rounding digit is odd. + ((i > 0 ? j > 0 ? n / pows10[d - j] : 0 : xc[ni - 1]) % 10) & 1 || + rm == (x.s < 0 ? 8 : 7)); + + if (sd < 1 || !xc[0]) { + xc.length = 0; + + if (r) { + + // Convert sd to decimal places. + sd -= x.e + 1; + + // 1, 0.1, 0.01, 0.001, 0.0001 etc. + xc[0] = pows10[(LOG_BASE - sd % LOG_BASE) % LOG_BASE]; + x.e = -sd || 0; + } else { + + // Zero. + xc[0] = x.e = 0; + } + + return x; + } + + // Remove excess digits. + if (i == 0) { + xc.length = ni; + k = 1; + ni--; + } else { + xc.length = ni + 1; + k = pows10[LOG_BASE - i]; + + // E.g. 56700 becomes 56000 if 7 is the rounding digit. + // j > 0 means i > number of leading zeros of n. + xc[ni] = j > 0 ? mathfloor(n / pows10[d - j] % pows10[j]) * k : 0; + } + + // Round up? + if (r) { + + for (; ;) { + + // If the digit to be rounded up is in the first element of xc... + if (ni == 0) { + + // i will be the length of xc[0] before k is added. + for (i = 1, j = xc[0]; j >= 10; j /= 10, i++); + j = xc[0] += k; + for (k = 1; j >= 10; j /= 10, k++); + + // if i != k the length has increased. + if (i != k) { + x.e++; + if (xc[0] == BASE) xc[0] = 1; + } + + break; + } else { + xc[ni] += k; + if (xc[ni] != BASE) break; + xc[ni--] = 0; + k = 1; + } + } + } + + // Remove trailing zeros. + for (i = xc.length; xc[--i] === 0; xc.pop()); + } + + // Overflow? Infinity. + if (x.e > MAX_EXP) { + x.c = x.e = null; + + // Underflow? Zero. + } else if (x.e < MIN_EXP) { + x.c = [x.e = 0]; + } + } + + return x; + } + + + function valueOf(n) { + var str, + e = n.e; + + if (e === null) return n.toString(); + + str = coeffToString(n.c); + + str = e <= TO_EXP_NEG || e >= TO_EXP_POS + ? toExponential(str, e) + : toFixedPoint(str, e, '0'); + + return n.s < 0 ? '-' + str : str; + } + + + // PROTOTYPE/INSTANCE METHODS + + + /* + * Return a new BigNumber whose value is the absolute value of this BigNumber. + */ + P.absoluteValue = P.abs = function () { + var x = new BigNumber(this); + if (x.s < 0) x.s = 1; + return x; + }; + + + /* + * Return + * 1 if the value of this BigNumber is greater than the value of BigNumber(y, b), + * -1 if the value of this BigNumber is less than the value of BigNumber(y, b), + * 0 if they have the same value, + * or null if the value of either is NaN. + */ + P.comparedTo = function (y, b) { + return compare(this, new BigNumber(y, b)); + }; + + + /* + * If dp is undefined or null or true or false, return the number of decimal places of the + * value of this BigNumber, or null if the value of this BigNumber is ±Infinity or NaN. + * + * Otherwise, if dp is a number, return a new BigNumber whose value is the value of this + * BigNumber rounded to a maximum of dp decimal places using rounding mode rm, or + * ROUNDING_MODE if rm is omitted. + * + * [dp] {number} Decimal places: integer, 0 to MAX inclusive. + * [rm] {number} Rounding mode. Integer, 0 to 8 inclusive. + * + * '[BigNumber Error] Argument {not a primitive number|not an integer|out of range}: {dp|rm}' + */ + P.decimalPlaces = P.dp = function (dp, rm) { + var c, n, v, + x = this; + + if (dp != null) { + intCheck(dp, 0, MAX); + if (rm == null) rm = ROUNDING_MODE; + else intCheck(rm, 0, 8); + + return round(new BigNumber(x), dp + x.e + 1, rm); + } + + if (!(c = x.c)) return null; + n = ((v = c.length - 1) - bitFloor(this.e / LOG_BASE)) * LOG_BASE; + + // Subtract the number of trailing zeros of the last number. + if (v = c[v]) for (; v % 10 == 0; v /= 10, n--); + if (n < 0) n = 0; + + return n; + }; + + + /* + * n / 0 = I + * n / N = N + * n / I = 0 + * 0 / n = 0 + * 0 / 0 = N + * 0 / N = N + * 0 / I = 0 + * N / n = N + * N / 0 = N + * N / N = N + * N / I = N + * I / n = I + * I / 0 = I + * I / N = N + * I / I = N + * + * Return a new BigNumber whose value is the value of this BigNumber divided by the value of + * BigNumber(y, b), rounded according to DECIMAL_PLACES and ROUNDING_MODE. + */ + P.dividedBy = P.div = function (y, b) { + return div(this, new BigNumber(y, b), DECIMAL_PLACES, ROUNDING_MODE); + }; + + + /* + * Return a new BigNumber whose value is the integer part of dividing the value of this + * BigNumber by the value of BigNumber(y, b). + */ + P.dividedToIntegerBy = P.idiv = function (y, b) { + return div(this, new BigNumber(y, b), 0, 1); + }; + + + /* + * Return a BigNumber whose value is the value of this BigNumber exponentiated by n. + * + * If m is present, return the result modulo m. + * If n is negative round according to DECIMAL_PLACES and ROUNDING_MODE. + * If POW_PRECISION is non-zero and m is not present, round to POW_PRECISION using ROUNDING_MODE. + * + * The modular power operation works efficiently when x, n, and m are integers, otherwise it + * is equivalent to calculating x.exponentiatedBy(n).modulo(m) with a POW_PRECISION of 0. + * + * n {number|string|BigNumber} The exponent. An integer. + * [m] {number|string|BigNumber} The modulus. + * + * '[BigNumber Error] Exponent not an integer: {n}' + */ + P.exponentiatedBy = P.pow = function (n, m) { + var half, isModExp, i, k, more, nIsBig, nIsNeg, nIsOdd, y, + x = this; + + n = new BigNumber(n); + + // Allow NaN and ±Infinity, but not other non-integers. + if (n.c && !n.isInteger()) { + throw Error + (bignumberError + 'Exponent not an integer: ' + valueOf(n)); + } + + if (m != null) m = new BigNumber(m); + + // Exponent of MAX_SAFE_INTEGER is 15. + nIsBig = n.e > 14; + + // If x is NaN, ±Infinity, ±0 or ±1, or n is ±Infinity, NaN or ±0. + if (!x.c || !x.c[0] || x.c[0] == 1 && !x.e && x.c.length == 1 || !n.c || !n.c[0]) { + + // The sign of the result of pow when x is negative depends on the evenness of n. + // If +n overflows to ±Infinity, the evenness of n would be not be known. + y = new BigNumber(Math.pow(+valueOf(x), nIsBig ? 2 - isOdd(n) : +valueOf(n))); + return m ? y.mod(m) : y; + } + + nIsNeg = n.s < 0; + + if (m) { + + // x % m returns NaN if abs(m) is zero, or m is NaN. + if (m.c ? !m.c[0] : !m.s) return new BigNumber(NaN); + + isModExp = !nIsNeg && x.isInteger() && m.isInteger(); + + if (isModExp) x = x.mod(m); + + // Overflow to ±Infinity: >=2**1e10 or >=1.0000024**1e15. + // Underflow to ±0: <=0.79**1e10 or <=0.9999975**1e15. + } else if (n.e > 9 && (x.e > 0 || x.e < -1 || (x.e == 0 + // [1, 240000000] + ? x.c[0] > 1 || nIsBig && x.c[1] >= 24e7 + // [80000000000000] [99999750000000] + : x.c[0] < 8e13 || nIsBig && x.c[0] <= 9999975e7))) { + + // If x is negative and n is odd, k = -0, else k = 0. + k = x.s < 0 && isOdd(n) ? -0 : 0; + + // If x >= 1, k = ±Infinity. + if (x.e > -1) k = 1 / k; + + // If n is negative return ±0, else return ±Infinity. + return new BigNumber(nIsNeg ? 1 / k : k); + + } else if (POW_PRECISION) { + + // Truncating each coefficient array to a length of k after each multiplication + // equates to truncating significant digits to POW_PRECISION + [28, 41], + // i.e. there will be a minimum of 28 guard digits retained. + k = mathceil(POW_PRECISION / LOG_BASE + 2); + } + + if (nIsBig) { + half = new BigNumber(0.5); + if (nIsNeg) n.s = 1; + nIsOdd = isOdd(n); + } else { + i = Math.abs(+valueOf(n)); + nIsOdd = i % 2; + } + + y = new BigNumber(ONE); + + // Performs 54 loop iterations for n of 9007199254740991. + for (; ;) { + + if (nIsOdd) { + y = y.times(x); + if (!y.c) break; + + if (k) { + if (y.c.length > k) y.c.length = k; + } else if (isModExp) { + y = y.mod(m); //y = y.minus(div(y, m, 0, MODULO_MODE).times(m)); + } + } + + if (i) { + i = mathfloor(i / 2); + if (i === 0) break; + nIsOdd = i % 2; + } else { + n = n.times(half); + round(n, n.e + 1, 1); + + if (n.e > 14) { + nIsOdd = isOdd(n); + } else { + i = +valueOf(n); + if (i === 0) break; + nIsOdd = i % 2; + } + } + + x = x.times(x); + + if (k) { + if (x.c && x.c.length > k) x.c.length = k; + } else if (isModExp) { + x = x.mod(m); //x = x.minus(div(x, m, 0, MODULO_MODE).times(m)); + } + } + + if (isModExp) return y; + if (nIsNeg) y = ONE.div(y); + + return m ? y.mod(m) : k ? round(y, POW_PRECISION, ROUNDING_MODE, more) : y; + }; + + + /* + * Return a new BigNumber whose value is the value of this BigNumber rounded to an integer + * using rounding mode rm, or ROUNDING_MODE if rm is omitted. + * + * [rm] {number} Rounding mode. Integer, 0 to 8 inclusive. + * + * '[BigNumber Error] Argument {not a primitive number|not an integer|out of range}: {rm}' + */ + P.integerValue = function (rm) { + var n = new BigNumber(this); + if (rm == null) rm = ROUNDING_MODE; + else intCheck(rm, 0, 8); + return round(n, n.e + 1, rm); + }; + + + /* + * Return true if the value of this BigNumber is equal to the value of BigNumber(y, b), + * otherwise return false. + */ + P.isEqualTo = P.eq = function (y, b) { + return compare(this, new BigNumber(y, b)) === 0; + }; + + + /* + * Return true if the value of this BigNumber is a finite number, otherwise return false. + */ + P.isFinite = function () { + return !!this.c; + }; + + + /* + * Return true if the value of this BigNumber is greater than the value of BigNumber(y, b), + * otherwise return false. + */ + P.isGreaterThan = P.gt = function (y, b) { + return compare(this, new BigNumber(y, b)) > 0; + }; + + + /* + * Return true if the value of this BigNumber is greater than or equal to the value of + * BigNumber(y, b), otherwise return false. + */ + P.isGreaterThanOrEqualTo = P.gte = function (y, b) { + return (b = compare(this, new BigNumber(y, b))) === 1 || b === 0; + + }; + + + /* + * Return true if the value of this BigNumber is an integer, otherwise return false. + */ + P.isInteger = function () { + return !!this.c && bitFloor(this.e / LOG_BASE) > this.c.length - 2; + }; + + + /* + * Return true if the value of this BigNumber is less than the value of BigNumber(y, b), + * otherwise return false. + */ + P.isLessThan = P.lt = function (y, b) { + return compare(this, new BigNumber(y, b)) < 0; + }; + + + /* + * Return true if the value of this BigNumber is less than or equal to the value of + * BigNumber(y, b), otherwise return false. + */ + P.isLessThanOrEqualTo = P.lte = function (y, b) { + return (b = compare(this, new BigNumber(y, b))) === -1 || b === 0; + }; + + + /* + * Return true if the value of this BigNumber is NaN, otherwise return false. + */ + P.isNaN = function () { + return !this.s; + }; + + + /* + * Return true if the value of this BigNumber is negative, otherwise return false. + */ + P.isNegative = function () { + return this.s < 0; + }; + + + /* + * Return true if the value of this BigNumber is positive, otherwise return false. + */ + P.isPositive = function () { + return this.s > 0; + }; + + + /* + * Return true if the value of this BigNumber is 0 or -0, otherwise return false. + */ + P.isZero = function () { + return !!this.c && this.c[0] == 0; + }; + + + /* + * n - 0 = n + * n - N = N + * n - I = -I + * 0 - n = -n + * 0 - 0 = 0 + * 0 - N = N + * 0 - I = -I + * N - n = N + * N - 0 = N + * N - N = N + * N - I = N + * I - n = I + * I - 0 = I + * I - N = N + * I - I = N + * + * Return a new BigNumber whose value is the value of this BigNumber minus the value of + * BigNumber(y, b). + */ + P.minus = function (y, b) { + var i, j, t, xLTy, + x = this, + a = x.s; + + y = new BigNumber(y, b); + b = y.s; + + // Either NaN? + if (!a || !b) return new BigNumber(NaN); + + // Signs differ? + if (a != b) { + y.s = -b; + return x.plus(y); + } + + var xe = x.e / LOG_BASE, + ye = y.e / LOG_BASE, + xc = x.c, + yc = y.c; + + if (!xe || !ye) { + + // Either Infinity? + if (!xc || !yc) return xc ? (y.s = -b, y) : new BigNumber(yc ? x : NaN); + + // Either zero? + if (!xc[0] || !yc[0]) { + + // Return y if y is non-zero, x if x is non-zero, or zero if both are zero. + return yc[0] ? (y.s = -b, y) : new BigNumber(xc[0] ? x : + + // IEEE 754 (2008) 6.3: n - n = -0 when rounding to -Infinity + ROUNDING_MODE == 3 ? -0 : 0); + } + } + + xe = bitFloor(xe); + ye = bitFloor(ye); + xc = xc.slice(); + + // Determine which is the bigger number. + if (a = xe - ye) { + + if (xLTy = a < 0) { + a = -a; + t = xc; + } else { + ye = xe; + t = yc; + } + + t.reverse(); + + // Prepend zeros to equalise exponents. + for (b = a; b--; t.push(0)); + t.reverse(); + } else { + + // Exponents equal. Check digit by digit. + j = (xLTy = (a = xc.length) < (b = yc.length)) ? a : b; + + for (a = b = 0; b < j; b++) { + + if (xc[b] != yc[b]) { + xLTy = xc[b] < yc[b]; + break; + } + } + } + + // x < y? Point xc to the array of the bigger number. + if (xLTy) t = xc, xc = yc, yc = t, y.s = -y.s; + + b = (j = yc.length) - (i = xc.length); + + // Append zeros to xc if shorter. + // No need to add zeros to yc if shorter as subtract only needs to start at yc.length. + if (b > 0) for (; b--; xc[i++] = 0); + b = BASE - 1; + + // Subtract yc from xc. + for (; j > a;) { + + if (xc[--j] < yc[j]) { + for (i = j; i && !xc[--i]; xc[i] = b); + --xc[i]; + xc[j] += BASE; + } + + xc[j] -= yc[j]; + } + + // Remove leading zeros and adjust exponent accordingly. + for (; xc[0] == 0; xc.splice(0, 1), --ye); + + // Zero? + if (!xc[0]) { + + // Following IEEE 754 (2008) 6.3, + // n - n = +0 but n - n = -0 when rounding towards -Infinity. + y.s = ROUNDING_MODE == 3 ? -1 : 1; + y.c = [y.e = 0]; + return y; + } + + // No need to check for Infinity as +x - +y != Infinity && -x - -y != Infinity + // for finite x and y. + return normalise(y, xc, ye); + }; + + + /* + * n % 0 = N + * n % N = N + * n % I = n + * 0 % n = 0 + * -0 % n = -0 + * 0 % 0 = N + * 0 % N = N + * 0 % I = 0 + * N % n = N + * N % 0 = N + * N % N = N + * N % I = N + * I % n = N + * I % 0 = N + * I % N = N + * I % I = N + * + * Return a new BigNumber whose value is the value of this BigNumber modulo the value of + * BigNumber(y, b). The result depends on the value of MODULO_MODE. + */ + P.modulo = P.mod = function (y, b) { + var q, s, + x = this; + + y = new BigNumber(y, b); + + // Return NaN if x is Infinity or NaN, or y is NaN or zero. + if (!x.c || !y.s || y.c && !y.c[0]) { + return new BigNumber(NaN); + + // Return x if y is Infinity or x is zero. + } else if (!y.c || x.c && !x.c[0]) { + return new BigNumber(x); + } + + if (MODULO_MODE == 9) { + + // Euclidian division: q = sign(y) * floor(x / abs(y)) + // r = x - qy where 0 <= r < abs(y) + s = y.s; + y.s = 1; + q = div(x, y, 0, 3); + y.s = s; + q.s *= s; + } else { + q = div(x, y, 0, MODULO_MODE); + } + + y = x.minus(q.times(y)); + + // To match JavaScript %, ensure sign of zero is sign of dividend. + if (!y.c[0] && MODULO_MODE == 1) y.s = x.s; + + return y; + }; + + + /* + * n * 0 = 0 + * n * N = N + * n * I = I + * 0 * n = 0 + * 0 * 0 = 0 + * 0 * N = N + * 0 * I = N + * N * n = N + * N * 0 = N + * N * N = N + * N * I = N + * I * n = I + * I * 0 = N + * I * N = N + * I * I = I + * + * Return a new BigNumber whose value is the value of this BigNumber multiplied by the value + * of BigNumber(y, b). + */ + P.multipliedBy = P.times = function (y, b) { + var c, e, i, j, k, m, xcL, xlo, xhi, ycL, ylo, yhi, zc, + base, sqrtBase, + x = this, + xc = x.c, + yc = (y = new BigNumber(y, b)).c; + + // Either NaN, ±Infinity or ±0? + if (!xc || !yc || !xc[0] || !yc[0]) { + + // Return NaN if either is NaN, or one is 0 and the other is Infinity. + if (!x.s || !y.s || xc && !xc[0] && !yc || yc && !yc[0] && !xc) { + y.c = y.e = y.s = null; + } else { + y.s *= x.s; + + // Return ±Infinity if either is ±Infinity. + if (!xc || !yc) { + y.c = y.e = null; + + // Return ±0 if either is ±0. + } else { + y.c = [0]; + y.e = 0; + } + } + + return y; + } + + e = bitFloor(x.e / LOG_BASE) + bitFloor(y.e / LOG_BASE); + y.s *= x.s; + xcL = xc.length; + ycL = yc.length; + + // Ensure xc points to longer array and xcL to its length. + if (xcL < ycL) zc = xc, xc = yc, yc = zc, i = xcL, xcL = ycL, ycL = i; + + // Initialise the result array with zeros. + for (i = xcL + ycL, zc = []; i--; zc.push(0)); + + base = BASE; + sqrtBase = SQRT_BASE; + + for (i = ycL; --i >= 0;) { + c = 0; + ylo = yc[i] % sqrtBase; + yhi = yc[i] / sqrtBase | 0; + + for (k = xcL, j = i + k; j > i;) { + xlo = xc[--k] % sqrtBase; + xhi = xc[k] / sqrtBase | 0; + m = yhi * xlo + xhi * ylo; + xlo = ylo * xlo + ((m % sqrtBase) * sqrtBase) + zc[j] + c; + c = (xlo / base | 0) + (m / sqrtBase | 0) + yhi * xhi; + zc[j--] = xlo % base; + } + + zc[j] = c; + } + + if (c) { + ++e; + } else { + zc.splice(0, 1); + } + + return normalise(y, zc, e); + }; + + + /* + * Return a new BigNumber whose value is the value of this BigNumber negated, + * i.e. multiplied by -1. + */ + P.negated = function () { + var x = new BigNumber(this); + x.s = -x.s || null; + return x; + }; + + + /* + * n + 0 = n + * n + N = N + * n + I = I + * 0 + n = n + * 0 + 0 = 0 + * 0 + N = N + * 0 + I = I + * N + n = N + * N + 0 = N + * N + N = N + * N + I = N + * I + n = I + * I + 0 = I + * I + N = N + * I + I = I + * + * Return a new BigNumber whose value is the value of this BigNumber plus the value of + * BigNumber(y, b). + */ + P.plus = function (y, b) { + var t, + x = this, + a = x.s; + + y = new BigNumber(y, b); + b = y.s; + + // Either NaN? + if (!a || !b) return new BigNumber(NaN); + + // Signs differ? + if (a != b) { + y.s = -b; + return x.minus(y); + } + + var xe = x.e / LOG_BASE, + ye = y.e / LOG_BASE, + xc = x.c, + yc = y.c; + + if (!xe || !ye) { + + // Return ±Infinity if either ±Infinity. + if (!xc || !yc) return new BigNumber(a / 0); + + // Either zero? + // Return y if y is non-zero, x if x is non-zero, or zero if both are zero. + if (!xc[0] || !yc[0]) return yc[0] ? y : new BigNumber(xc[0] ? x : a * 0); + } + + xe = bitFloor(xe); + ye = bitFloor(ye); + xc = xc.slice(); + + // Prepend zeros to equalise exponents. Faster to use reverse then do unshifts. + if (a = xe - ye) { + if (a > 0) { + ye = xe; + t = yc; + } else { + a = -a; + t = xc; + } + + t.reverse(); + for (; a--; t.push(0)); + t.reverse(); + } + + a = xc.length; + b = yc.length; + + // Point xc to the longer array, and b to the shorter length. + if (a - b < 0) t = yc, yc = xc, xc = t, b = a; + + // Only start adding at yc.length - 1 as the further digits of xc can be ignored. + for (a = 0; b;) { + a = (xc[--b] = xc[b] + yc[b] + a) / BASE | 0; + xc[b] = BASE === xc[b] ? 0 : xc[b] % BASE; + } + + if (a) { + xc = [a].concat(xc); + ++ye; + } + + // No need to check for zero, as +x + +y != 0 && -x + -y != 0 + // ye = MAX_EXP + 1 possible + return normalise(y, xc, ye); + }; + + + /* + * If sd is undefined or null or true or false, return the number of significant digits of + * the value of this BigNumber, or null if the value of this BigNumber is ±Infinity or NaN. + * If sd is true include integer-part trailing zeros in the count. + * + * Otherwise, if sd is a number, return a new BigNumber whose value is the value of this + * BigNumber rounded to a maximum of sd significant digits using rounding mode rm, or + * ROUNDING_MODE if rm is omitted. + * + * sd {number|boolean} number: significant digits: integer, 1 to MAX inclusive. + * boolean: whether to count integer-part trailing zeros: true or false. + * [rm] {number} Rounding mode. Integer, 0 to 8 inclusive. + * + * '[BigNumber Error] Argument {not a primitive number|not an integer|out of range}: {sd|rm}' + */ + P.precision = P.sd = function (sd, rm) { + var c, n, v, + x = this; + + if (sd != null && sd !== !!sd) { + intCheck(sd, 1, MAX); + if (rm == null) rm = ROUNDING_MODE; + else intCheck(rm, 0, 8); + + return round(new BigNumber(x), sd, rm); + } + + if (!(c = x.c)) return null; + v = c.length - 1; + n = v * LOG_BASE + 1; + + if (v = c[v]) { + + // Subtract the number of trailing zeros of the last element. + for (; v % 10 == 0; v /= 10, n--); + + // Add the number of digits of the first element. + for (v = c[0]; v >= 10; v /= 10, n++); + } + + if (sd && x.e + 1 > n) n = x.e + 1; + + return n; + }; + + + /* + * Return a new BigNumber whose value is the value of this BigNumber shifted by k places + * (powers of 10). Shift to the right if n > 0, and to the left if n < 0. + * + * k {number} Integer, -MAX_SAFE_INTEGER to MAX_SAFE_INTEGER inclusive. + * + * '[BigNumber Error] Argument {not a primitive number|not an integer|out of range}: {k}' + */ + P.shiftedBy = function (k) { + intCheck(k, -MAX_SAFE_INTEGER, MAX_SAFE_INTEGER); + return this.times('1e' + k); + }; + + + /* + * sqrt(-n) = N + * sqrt(N) = N + * sqrt(-I) = N + * sqrt(I) = I + * sqrt(0) = 0 + * sqrt(-0) = -0 + * + * Return a new BigNumber whose value is the square root of the value of this BigNumber, + * rounded according to DECIMAL_PLACES and ROUNDING_MODE. + */ + P.squareRoot = P.sqrt = function () { + var m, n, r, rep, t, + x = this, + c = x.c, + s = x.s, + e = x.e, + dp = DECIMAL_PLACES + 4, + half = new BigNumber('0.5'); + + // Negative/NaN/Infinity/zero? + if (s !== 1 || !c || !c[0]) { + return new BigNumber(!s || s < 0 && (!c || c[0]) ? NaN : c ? x : 1 / 0); + } + + // Initial estimate. + s = Math.sqrt(+valueOf(x)); + + // Math.sqrt underflow/overflow? + // Pass x to Math.sqrt as integer, then adjust the exponent of the result. + if (s == 0 || s == 1 / 0) { + n = coeffToString(c); + if ((n.length + e) % 2 == 0) n += '0'; + s = Math.sqrt(+n); + e = bitFloor((e + 1) / 2) - (e < 0 || e % 2); + + if (s == 1 / 0) { + n = '1e' + e; + } else { + n = s.toExponential(); + n = n.slice(0, n.indexOf('e') + 1) + e; + } + + r = new BigNumber(n); + } else { + r = new BigNumber(s + ''); + } + + // Check for zero. + // r could be zero if MIN_EXP is changed after the this value was created. + // This would cause a division by zero (x/t) and hence Infinity below, which would cause + // coeffToString to throw. + if (r.c[0]) { + e = r.e; + s = e + dp; + if (s < 3) s = 0; + + // Newton-Raphson iteration. + for (; ;) { + t = r; + r = half.times(t.plus(div(x, t, dp, 1))); + + if (coeffToString(t.c).slice(0, s) === (n = coeffToString(r.c)).slice(0, s)) { + + // The exponent of r may here be one less than the final result exponent, + // e.g 0.0009999 (e-4) --> 0.001 (e-3), so adjust s so the rounding digits + // are indexed correctly. + if (r.e < e) --s; + n = n.slice(s - 3, s + 1); + + // The 4th rounding digit may be in error by -1 so if the 4 rounding digits + // are 9999 or 4999 (i.e. approaching a rounding boundary) continue the + // iteration. + if (n == '9999' || !rep && n == '4999') { + + // On the first iteration only, check to see if rounding up gives the + // exact result as the nines may infinitely repeat. + if (!rep) { + round(t, t.e + DECIMAL_PLACES + 2, 0); + + if (t.times(t).eq(x)) { + r = t; + break; + } + } + + dp += 4; + s += 4; + rep = 1; + } else { + + // If rounding digits are null, 0{0,4} or 50{0,3}, check for exact + // result. If not, then there are further digits and m will be truthy. + if (!+n || !+n.slice(1) && n.charAt(0) == '5') { + + // Truncate to the first rounding digit. + round(r, r.e + DECIMAL_PLACES + 2, 1); + m = !r.times(r).eq(x); + } + + break; + } + } + } + } + + return round(r, r.e + DECIMAL_PLACES + 1, ROUNDING_MODE, m); + }; + + + /* + * Return a string representing the value of this BigNumber in exponential notation and + * rounded using ROUNDING_MODE to dp fixed decimal places. + * + * [dp] {number} Decimal places. Integer, 0 to MAX inclusive. + * [rm] {number} Rounding mode. Integer, 0 to 8 inclusive. + * + * '[BigNumber Error] Argument {not a primitive number|not an integer|out of range}: {dp|rm}' + */ + P.toExponential = function (dp, rm) { + if (dp != null) { + intCheck(dp, 0, MAX); + dp++; + } + return format(this, dp, rm, 1); + }; + + + /* + * Return a string representing the value of this BigNumber in fixed-point notation rounding + * to dp fixed decimal places using rounding mode rm, or ROUNDING_MODE if rm is omitted. + * + * Note: as with JavaScript's number type, (-0).toFixed(0) is '0', + * but e.g. (-0.00001).toFixed(0) is '-0'. + * + * [dp] {number} Decimal places. Integer, 0 to MAX inclusive. + * [rm] {number} Rounding mode. Integer, 0 to 8 inclusive. + * + * '[BigNumber Error] Argument {not a primitive number|not an integer|out of range}: {dp|rm}' + */ + P.toFixed = function (dp, rm) { + if (dp != null) { + intCheck(dp, 0, MAX); + dp = dp + this.e + 1; + } + return format(this, dp, rm); + }; + + + /* + * Return a string representing the value of this BigNumber in fixed-point notation rounded + * using rm or ROUNDING_MODE to dp decimal places, and formatted according to the properties + * of the format or FORMAT object (see BigNumber.set). + * + * The formatting object may contain some or all of the properties shown below. + * + * FORMAT = { + * prefix: '', + * groupSize: 3, + * secondaryGroupSize: 0, + * groupSeparator: ',', + * decimalSeparator: '.', + * fractionGroupSize: 0, + * fractionGroupSeparator: '\xA0', // non-breaking space + * suffix: '' + * }; + * + * [dp] {number} Decimal places. Integer, 0 to MAX inclusive. + * [rm] {number} Rounding mode. Integer, 0 to 8 inclusive. + * [format] {object} Formatting options. See FORMAT pbject above. + * + * '[BigNumber Error] Argument {not a primitive number|not an integer|out of range}: {dp|rm}' + * '[BigNumber Error] Argument not an object: {format}' + */ + P.toFormat = function (dp, rm, format) { + var str, + x = this; + + if (format == null) { + if (dp != null && rm && typeof rm == 'object') { + format = rm; + rm = null; + } else if (dp && typeof dp == 'object') { + format = dp; + dp = rm = null; + } else { + format = FORMAT; + } + } else if (typeof format != 'object') { + throw Error + (bignumberError + 'Argument not an object: ' + format); + } + + str = x.toFixed(dp, rm); + + if (x.c) { + var i, + arr = str.split('.'), + g1 = +format.groupSize, + g2 = +format.secondaryGroupSize, + groupSeparator = format.groupSeparator || '', + intPart = arr[0], + fractionPart = arr[1], + isNeg = x.s < 0, + intDigits = isNeg ? intPart.slice(1) : intPart, + len = intDigits.length; + + if (g2) i = g1, g1 = g2, g2 = i, len -= i; + + if (g1 > 0 && len > 0) { + i = len % g1 || g1; + intPart = intDigits.substr(0, i); + for (; i < len; i += g1) intPart += groupSeparator + intDigits.substr(i, g1); + if (g2 > 0) intPart += groupSeparator + intDigits.slice(i); + if (isNeg) intPart = '-' + intPart; + } + + str = fractionPart + ? intPart + (format.decimalSeparator || '') + ((g2 = +format.fractionGroupSize) + ? fractionPart.replace(new RegExp('\\d{' + g2 + '}\\B', 'g'), + '$&' + (format.fractionGroupSeparator || '')) + : fractionPart) + : intPart; + } + + return (format.prefix || '') + str + (format.suffix || ''); + }; + + + /* + * Return an array of two BigNumbers representing the value of this BigNumber as a simple + * fraction with an integer numerator and an integer denominator. + * The denominator will be a positive non-zero value less than or equal to the specified + * maximum denominator. If a maximum denominator is not specified, the denominator will be + * the lowest value necessary to represent the number exactly. + * + * [md] {number|string|BigNumber} Integer >= 1, or Infinity. The maximum denominator. + * + * '[BigNumber Error] Argument {not an integer|out of range} : {md}' + */ + P.toFraction = function (md) { + var d, d0, d1, d2, e, exp, n, n0, n1, q, r, s, + x = this, + xc = x.c; + + if (md != null) { + n = new BigNumber(md); + + // Throw if md is less than one or is not an integer, unless it is Infinity. + if (!n.isInteger() && (n.c || n.s !== 1) || n.lt(ONE)) { + throw Error + (bignumberError + 'Argument ' + + (n.isInteger() ? 'out of range: ' : 'not an integer: ') + valueOf(n)); + } + } + + if (!xc) return new BigNumber(x); + + d = new BigNumber(ONE); + n1 = d0 = new BigNumber(ONE); + d1 = n0 = new BigNumber(ONE); + s = coeffToString(xc); + + // Determine initial denominator. + // d is a power of 10 and the minimum max denominator that specifies the value exactly. + e = d.e = s.length - x.e - 1; + d.c[0] = POWS_TEN[(exp = e % LOG_BASE) < 0 ? LOG_BASE + exp : exp]; + md = !md || n.comparedTo(d) > 0 ? (e > 0 ? d : n1) : n; + + exp = MAX_EXP; + MAX_EXP = 1 / 0; + n = new BigNumber(s); + + // n0 = d1 = 0 + n0.c[0] = 0; + + for (; ;) { + q = div(n, d, 0, 1); + d2 = d0.plus(q.times(d1)); + if (d2.comparedTo(md) == 1) break; + d0 = d1; + d1 = d2; + n1 = n0.plus(q.times(d2 = n1)); + n0 = d2; + d = n.minus(q.times(d2 = d)); + n = d2; + } + + d2 = div(md.minus(d0), d1, 0, 1); + n0 = n0.plus(d2.times(n1)); + d0 = d0.plus(d2.times(d1)); + n0.s = n1.s = x.s; + e = e * 2; + + // Determine which fraction is closer to x, n0/d0 or n1/d1 + r = div(n1, d1, e, ROUNDING_MODE).minus(x).abs().comparedTo( + div(n0, d0, e, ROUNDING_MODE).minus(x).abs()) < 1 ? [n1, d1] : [n0, d0]; + + MAX_EXP = exp; + + return r; + }; + + + /* + * Return the value of this BigNumber converted to a number primitive. + */ + P.toNumber = function () { + return +valueOf(this); + }; + + + /* + * Return a string representing the value of this BigNumber rounded to sd significant digits + * using rounding mode rm or ROUNDING_MODE. If sd is less than the number of digits + * necessary to represent the integer part of the value in fixed-point notation, then use + * exponential notation. + * + * [sd] {number} Significant digits. Integer, 1 to MAX inclusive. + * [rm] {number} Rounding mode. Integer, 0 to 8 inclusive. + * + * '[BigNumber Error] Argument {not a primitive number|not an integer|out of range}: {sd|rm}' + */ + P.toPrecision = function (sd, rm) { + if (sd != null) intCheck(sd, 1, MAX); + return format(this, sd, rm, 2); + }; + + + /* + * Return a string representing the value of this BigNumber in base b, or base 10 if b is + * omitted. If a base is specified, including base 10, round according to DECIMAL_PLACES and + * ROUNDING_MODE. If a base is not specified, and this BigNumber has a positive exponent + * that is equal to or greater than TO_EXP_POS, or a negative exponent equal to or less than + * TO_EXP_NEG, return exponential notation. + * + * [b] {number} Integer, 2 to ALPHABET.length inclusive. + * + * '[BigNumber Error] Base {not a primitive number|not an integer|out of range}: {b}' + */ + P.toString = function (b) { + var str, + n = this, + s = n.s, + e = n.e; + + // Infinity or NaN? + if (e === null) { + if (s) { + str = 'Infinity'; + if (s < 0) str = '-' + str; + } else { + str = 'NaN'; + } + } else { + if (b == null) { + str = e <= TO_EXP_NEG || e >= TO_EXP_POS + ? toExponential(coeffToString(n.c), e) + : toFixedPoint(coeffToString(n.c), e, '0'); + } else if (b === 10) { + n = round(new BigNumber(n), DECIMAL_PLACES + e + 1, ROUNDING_MODE); + str = toFixedPoint(coeffToString(n.c), n.e, '0'); + } else { + intCheck(b, 2, ALPHABET.length, 'Base'); + str = convertBase(toFixedPoint(coeffToString(n.c), e, '0'), 10, b, s, true); + } + + if (s < 0 && n.c[0]) str = '-' + str; + } + + return str; + }; + + + /* + * Return as toString, but do not accept a base argument, and include the minus sign for + * negative zero. + */ + P.valueOf = P.toJSON = function () { + return valueOf(this); + }; + + + P._isBigNumber = true; + + P[Symbol.toStringTag] = 'BigNumber'; + + // Node.js v10.12.0+ + P[Symbol.for('nodejs.util.inspect.custom')] = P.valueOf; + + if (configObject != null) BigNumber.set(configObject); + + return BigNumber; +} + + +// PRIVATE HELPER FUNCTIONS + +// These functions don't need access to variables, +// e.g. DECIMAL_PLACES, in the scope of the `clone` function above. + + +function bitFloor(n) { + var i = n | 0; + return n > 0 || n === i ? i : i - 1; +} + + +// Return a coefficient array as a string of base 10 digits. +function coeffToString(a) { + var s, z, + i = 1, + j = a.length, + r = a[0] + ''; + + for (; i < j;) { + s = a[i++] + ''; + z = LOG_BASE - s.length; + for (; z--; s = '0' + s); + r += s; + } + + // Determine trailing zeros. + for (j = r.length; r.charCodeAt(--j) === 48;); + + return r.slice(0, j + 1 || 1); +} + + +// Compare the value of BigNumbers x and y. +function compare(x, y) { + var a, b, + xc = x.c, + yc = y.c, + i = x.s, + j = y.s, + k = x.e, + l = y.e; + + // Either NaN? + if (!i || !j) return null; + + a = xc && !xc[0]; + b = yc && !yc[0]; + + // Either zero? + if (a || b) return a ? b ? 0 : -j : i; + + // Signs differ? + if (i != j) return i; + + a = i < 0; + b = k == l; + + // Either Infinity? + if (!xc || !yc) return b ? 0 : !xc ^ a ? 1 : -1; + + // Compare exponents. + if (!b) return k > l ^ a ? 1 : -1; + + j = (k = xc.length) < (l = yc.length) ? k : l; + + // Compare digit by digit. + for (i = 0; i < j; i++) if (xc[i] != yc[i]) return xc[i] > yc[i] ^ a ? 1 : -1; + + // Compare lengths. + return k == l ? 0 : k > l ^ a ? 1 : -1; +} + + +/* + * Check that n is a primitive number, an integer, and in range, otherwise throw. + */ +function intCheck(n, min, max, name) { + if (n < min || n > max || n !== mathfloor(n)) { + throw Error + (bignumberError + (name || 'Argument') + (typeof n == 'number' + ? n < min || n > max ? ' out of range: ' : ' not an integer: ' + : ' not a primitive number: ') + String(n)); + } +} + + +// Assumes finite n. +function isOdd(n) { + var k = n.c.length - 1; + return bitFloor(n.e / LOG_BASE) == k && n.c[k] % 2 != 0; +} + + +function toExponential(str, e) { + return (str.length > 1 ? str.charAt(0) + '.' + str.slice(1) : str) + + (e < 0 ? 'e' : 'e+') + e; +} + + +function toFixedPoint(str, e, z) { + var len, zs; + + // Negative exponent? + if (e < 0) { + + // Prepend zeros. + for (zs = z + '.'; ++e; zs += z); + str = zs + str; + + // Positive exponent + } else { + len = str.length; + + // Append zeros. + if (++e > len) { + for (zs = z, e -= len; --e; zs += z); + str += zs; + } else if (e < len) { + str = str.slice(0, e) + '.' + str.slice(e); + } + } + + return str; +} + + +// EXPORT + + +export var BigNumber = clone(); + +export default BigNumber; diff --git a/ts-ticket-office-service/node_modules/bignumber.js/doc/API.html b/ts-ticket-office-service/node_modules/bignumber.js/doc/API.html new file mode 100644 index 000000000..1ed4a8747 --- /dev/null +++ b/ts-ticket-office-service/node_modules/bignumber.js/doc/API.html @@ -0,0 +1,2237 @@ + + + + + + +bignumber.js API + + + + + + +
+ +

bignumber.js

+ +

A JavaScript library for arbitrary-precision arithmetic.

+

Hosted on GitHub.

+ +

API

+ +

+ See the README on GitHub for a + quick-start introduction. +

+

+ In all examples below, var and semicolons are not shown, and if a commented-out + value is in quotes it means toString has been called on the preceding expression. +

+ + +

CONSTRUCTOR

+ + +
+ BigNumberBigNumber(n [, base]) ⇒ BigNumber +
+

+ n: number|string|BigNumber
+ base: number: integer, 2 to 36 inclusive. (See + ALPHABET to extend this range). +

+

+ Returns a new instance of a BigNumber object with value n, where n + is a numeric value in the specified base, or base 10 if + base is omitted or is null or undefined. +

+
+x = new BigNumber(123.4567)                // '123.4567'
+// 'new' is optional
+y = BigNumber(x)                           // '123.4567'
+

+ If n is a base 10 value it can be in normal (fixed-point) or + exponential notation. Values in other bases must be in normal notation. Values in any base can + have fraction digits, i.e. digits after the decimal point. +

+
+new BigNumber(43210)                       // '43210'
+new BigNumber('4.321e+4')                  // '43210'
+new BigNumber('-735.0918e-430')            // '-7.350918e-428'
+new BigNumber('123412421.234324', 5)       // '607236.557696'
+

+ Signed 0, signed Infinity and NaN are supported. +

+
+new BigNumber('-Infinity')                 // '-Infinity'
+new BigNumber(NaN)                         // 'NaN'
+new BigNumber(-0)                          // '0'
+new BigNumber('.5')                        // '0.5'
+new BigNumber('+2')                        // '2'
+

+ String values in hexadecimal literal form, e.g. '0xff', are valid, as are + string values with the octal and binary prefixs '0o' and '0b'. + String values in octal literal form without the prefix will be interpreted as + decimals, e.g. '011' is interpreted as 11, not 9. +

+
+new BigNumber(-10110100.1, 2)              // '-180.5'
+new BigNumber('-0b10110100.1')             // '-180.5'
+new BigNumber('ff.8', 16)                  // '255.5'
+new BigNumber('0xff.8')                    // '255.5'
+

+ If a base is specified, n is rounded according to the current + DECIMAL_PLACES and + ROUNDING_MODE settings. This includes base + 10 so don't include a base parameter for decimal values unless + this behaviour is wanted. +

+
BigNumber.config({ DECIMAL_PLACES: 5 })
+new BigNumber(1.23456789)                  // '1.23456789'
+new BigNumber(1.23456789, 10)              // '1.23457'
+

An error is thrown if base is invalid. See Errors.

+

+ There is no limit to the number of digits of a value of type string (other than + that of JavaScript's maximum array size). See RANGE to set + the maximum and minimum possible exponent value of a BigNumber. +

+
+new BigNumber('5032485723458348569331745.33434346346912144534543')
+new BigNumber('4.321e10000000')
+

BigNumber NaN is returned if n is invalid + (unless BigNumber.DEBUG is true, see below).

+
+new BigNumber('.1*')                       // 'NaN'
+new BigNumber('blurgh')                    // 'NaN'
+new BigNumber(9, 2)                        // 'NaN'
+

+ To aid in debugging, if BigNumber.DEBUG is true then an error will + be thrown on an invalid n. An error will also be thrown if n is of + type number with more than 15 significant digits, as calling + toString or valueOf on + these numbers may not result in the intended value. +

+
+console.log(823456789123456.3)            //  823456789123456.2
+new BigNumber(823456789123456.3)          // '823456789123456.2'
+BigNumber.DEBUG = true
+// '[BigNumber Error] Number primitive has more than 15 significant digits'
+new BigNumber(823456789123456.3)
+// '[BigNumber Error] Not a base 2 number'
+new BigNumber(9, 2)
+

+ A BigNumber can also be created from an object literal. + Use isBigNumber to check that it is well-formed. +

+
new BigNumber({ s: 1, e: 2, c: [ 777, 12300000000000 ], _isBigNumber: true })    // '777.123'
+ + + + +

Methods

+

The static methods of a BigNumber constructor.

+ + + + +
clone + .clone([object]) ⇒ BigNumber constructor +
+

object: object

+

+ Returns a new independent BigNumber constructor with configuration as described by + object (see config), or with the default + configuration if object is null or undefined. +

+

+ Throws if object is not an object. See Errors. +

+
BigNumber.config({ DECIMAL_PLACES: 5 })
+BN = BigNumber.clone({ DECIMAL_PLACES: 9 })
+
+x = new BigNumber(1)
+y = new BN(1)
+
+x.div(3)                        // 0.33333
+y.div(3)                        // 0.333333333
+
+// BN = BigNumber.clone({ DECIMAL_PLACES: 9 }) is equivalent to:
+BN = BigNumber.clone()
+BN.config({ DECIMAL_PLACES: 9 })
+ + + +
configset([object]) ⇒ object
+

+ object: object: an object that contains some or all of the following + properties. +

+

Configures the settings for this particular BigNumber constructor.

+ +
+
DECIMAL_PLACES
+
+ number: integer, 0 to 1e+9 inclusive
+ Default value: 20 +
+
+ The maximum number of decimal places of the results of operations involving + division, i.e. division, square root and base conversion operations, and power + operations with negative exponents.
+
+
+
BigNumber.config({ DECIMAL_PLACES: 5 })
+BigNumber.set({ DECIMAL_PLACES: 5 })    // equivalent
+
+ + + +
ROUNDING_MODE
+
+ number: integer, 0 to 8 inclusive
+ Default value: 4 (ROUND_HALF_UP) +
+
+ The rounding mode used in the above operations and the default rounding mode of + decimalPlaces, + precision, + toExponential, + toFixed, + toFormat and + toPrecision. +
+
The modes are available as enumerated properties of the BigNumber constructor.
+
+
BigNumber.config({ ROUNDING_MODE: 0 })
+BigNumber.set({ ROUNDING_MODE: BigNumber.ROUND_UP })    // equivalent
+
+ + + +
EXPONENTIAL_AT
+
+ number: integer, magnitude 0 to 1e+9 inclusive, or +
+ number[]: [ integer -1e+9 to 0 inclusive, integer + 0 to 1e+9 inclusive ]
+ Default value: [-7, 20] +
+
+ The exponent value(s) at which toString returns exponential notation. +
+
+ If a single number is assigned, the value is the exponent magnitude.
+ If an array of two numbers is assigned then the first number is the negative exponent + value at and beneath which exponential notation is used, and the second number is the + positive exponent value at and above which the same. +
+
+ For example, to emulate JavaScript numbers in terms of the exponent values at which they + begin to use exponential notation, use [-7, 20]. +
+
+
BigNumber.config({ EXPONENTIAL_AT: 2 })
+new BigNumber(12.3)         // '12.3'        e is only 1
+new BigNumber(123)          // '1.23e+2'
+new BigNumber(0.123)        // '0.123'       e is only -1
+new BigNumber(0.0123)       // '1.23e-2'
+
+BigNumber.config({ EXPONENTIAL_AT: [-7, 20] })
+new BigNumber(123456789)    // '123456789'   e is only 8
+new BigNumber(0.000000123)  // '1.23e-7'
+
+// Almost never return exponential notation:
+BigNumber.config({ EXPONENTIAL_AT: 1e+9 })
+
+// Always return exponential notation:
+BigNumber.config({ EXPONENTIAL_AT: 0 })
+
+
+ Regardless of the value of EXPONENTIAL_AT, the toFixed method + will always return a value in normal notation and the toExponential method + will always return a value in exponential form. +
+
+ Calling toString with a base argument, e.g. toString(10), will + also always return normal notation. +
+ + + +
RANGE
+
+ number: integer, magnitude 1 to 1e+9 inclusive, or +
+ number[]: [ integer -1e+9 to -1 inclusive, integer + 1 to 1e+9 inclusive ]
+ Default value: [-1e+9, 1e+9] +
+
+ The exponent value(s) beyond which overflow to Infinity and underflow to + zero occurs. +
+
+ If a single number is assigned, it is the maximum exponent magnitude: values wth a + positive exponent of greater magnitude become Infinity and those with a + negative exponent of greater magnitude become zero. +
+ If an array of two numbers is assigned then the first number is the negative exponent + limit and the second number is the positive exponent limit. +
+
+ For example, to emulate JavaScript numbers in terms of the exponent values at which they + become zero and Infinity, use [-324, 308]. +
+
+
BigNumber.config({ RANGE: 500 })
+BigNumber.config().RANGE     // [ -500, 500 ]
+new BigNumber('9.999e499')   // '9.999e+499'
+new BigNumber('1e500')       // 'Infinity'
+new BigNumber('1e-499')      // '1e-499'
+new BigNumber('1e-500')      // '0'
+
+BigNumber.config({ RANGE: [-3, 4] })
+new BigNumber(99999)         // '99999'      e is only 4
+new BigNumber(100000)        // 'Infinity'   e is 5
+new BigNumber(0.001)         // '0.01'       e is only -3
+new BigNumber(0.0001)        // '0'          e is -4
+
+
+ The largest possible magnitude of a finite BigNumber is + 9.999...e+1000000000.
+ The smallest possible magnitude of a non-zero BigNumber is 1e-1000000000. +
+ + + +
CRYPTO
+
+ boolean: true or false.
+ Default value: false +
+
+ The value that determines whether cryptographically-secure pseudo-random number + generation is used. +
+
+ If CRYPTO is set to true then the + random method will generate random digits using + crypto.getRandomValues in browsers that support it, or + crypto.randomBytes if using Node.js. +
+
+ If neither function is supported by the host environment then attempting to set + CRYPTO to true will fail and an exception will be thrown. +
+
+ If CRYPTO is false then the source of randomness used will be + Math.random (which is assumed to generate at least 30 bits of + randomness). +
+
See random.
+
+
+// Node.js
+global.crypto = require('crypto')
+
+BigNumber.config({ CRYPTO: true })
+BigNumber.config().CRYPTO       // true
+BigNumber.random()              // 0.54340758610486147524
+
+ + + +
MODULO_MODE
+
+ number: integer, 0 to 9 inclusive
+ Default value: 1 (ROUND_DOWN) +
+
The modulo mode used when calculating the modulus: a mod n.
+
+ The quotient, q = a / n, is calculated according to the + ROUNDING_MODE that corresponds to the chosen + MODULO_MODE. +
+
The remainder, r, is calculated as: r = a - n * q.
+
+ The modes that are most commonly used for the modulus/remainder operation are shown in + the following table. Although the other rounding modes can be used, they may not give + useful results. +
+
+ + + + + + + + + + + + + + + + + + + + + + +
PropertyValueDescription
ROUND_UP0 + The remainder is positive if the dividend is negative, otherwise it is negative. +
ROUND_DOWN1 + The remainder has the same sign as the dividend.
+ This uses 'truncating division' and matches the behaviour of JavaScript's + remainder operator %. +
ROUND_FLOOR3 + The remainder has the same sign as the divisor.
+ This matches Python's % operator. +
ROUND_HALF_EVEN6The IEEE 754 remainder function.
EUCLID9 + The remainder is always positive. Euclidian division:
+ q = sign(n) * floor(a / abs(n)) +
+
+
+ The rounding/modulo modes are available as enumerated properties of the BigNumber + constructor. +
+
See modulo.
+
+
BigNumber.config({ MODULO_MODE: BigNumber.EUCLID })
+BigNumber.config({ MODULO_MODE: 9 })          // equivalent
+
+ + + +
POW_PRECISION
+
+ number: integer, 0 to 1e+9 inclusive.
+ Default value: 0 +
+
+ The maximum precision, i.e. number of significant digits, of the result of the power + operation (unless a modulus is specified). +
+
If set to 0, the number of significant digits will not be limited.
+
See exponentiatedBy.
+
BigNumber.config({ POW_PRECISION: 100 })
+ + + +
FORMAT
+
object
+
+ The FORMAT object configures the format of the string returned by the + toFormat method. +
+
+ The example below shows the properties of the FORMAT object that are + recognised, and their default values. +
+
+ Unlike the other configuration properties, the values of the properties of the + FORMAT object will not be checked for validity. The existing + FORMAT object will simply be replaced by the object that is passed in. + The object can include any number of the properties shown below. +
+
See toFormat for examples of usage.
+
+
+BigNumber.config({
+  FORMAT: {
+    // string to prepend
+    prefix: '',
+    // decimal separator
+    decimalSeparator: '.',
+    // grouping separator of the integer part
+    groupSeparator: ',',
+    // primary grouping size of the integer part
+    groupSize: 3,
+    // secondary grouping size of the integer part
+    secondaryGroupSize: 0,
+    // grouping separator of the fraction part
+    fractionGroupSeparator: ' ',
+    // grouping size of the fraction part
+    fractionGroupSize: 0,
+    // string to append
+    suffix: ''
+  }
+});
+
+ + + +
ALPHABET
+
+ string
+ Default value: '0123456789abcdefghijklmnopqrstuvwxyz' +
+
+ The alphabet used for base conversion. The length of the alphabet corresponds to the + maximum value of the base argument that can be passed to the + BigNumber constructor or + toString. +
+
+ There is no maximum length for the alphabet, but it must be at least 2 characters long, and + it must not contain whitespace or a repeated character, or the sign indicators + '+' and '-', or the decimal separator '.'. +
+
+
// duodecimal (base 12)
+BigNumber.config({ ALPHABET: '0123456789TE' })
+x = new BigNumber('T', 12)
+x.toString()                // '10'
+x.toString(12)              // 'T'
+
+ + + +
+

+

Returns an object with the above properties and their current values.

+

+ Throws if object is not an object, or if an invalid value is assigned to + one or more of the above properties. See Errors. +

+
+BigNumber.config({
+  DECIMAL_PLACES: 40,
+  ROUNDING_MODE: BigNumber.ROUND_HALF_CEIL,
+  EXPONENTIAL_AT: [-10, 20],
+  RANGE: [-500, 500],
+  CRYPTO: true,
+  MODULO_MODE: BigNumber.ROUND_FLOOR,
+  POW_PRECISION: 80,
+  FORMAT: {
+    groupSize: 3,
+    groupSeparator: ' ',
+    decimalSeparator: ','
+  },
+  ALPHABET: '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ$_'
+});
+
+obj = BigNumber.config();
+obj.DECIMAL_PLACES        // 40
+obj.RANGE                 // [-500, 500]
+ + + +
+ isBigNumber.isBigNumber(value) ⇒ boolean +
+

value: any

+

+ Returns true if value is a BigNumber instance, otherwise returns + false. +

+
x = 42
+y = new BigNumber(x)
+
+BigNumber.isBigNumber(x)             // false
+y instanceof BigNumber               // true
+BigNumber.isBigNumber(y)             // true
+
+BN = BigNumber.clone();
+z = new BN(x)
+z instanceof BigNumber               // false
+BigNumber.isBigNumber(z)             // true
+

+ If value is a BigNumber instance and BigNumber.DEBUG is true, + then this method will also check if value is well-formed, and throw if it is not. + See Errors. +

+

+ The check can be useful if creating a BigNumber from an object literal. + See BigNumber. +

+
+x = new BigNumber(10)
+
+// Change x.c to an illegitimate value.
+x.c = NaN
+
+BigNumber.DEBUG = false
+
+// No error.
+BigNumber.isBigNumber(x)    // true
+
+BigNumber.DEBUG = true
+
+// Error.
+BigNumber.isBigNumber(x)    // '[BigNumber Error] Invalid BigNumber'
+ + + +
maximum.max(n...) ⇒ BigNumber
+

+ n: number|string|BigNumber
+ See BigNumber for further parameter details. +

+

+ Returns a BigNumber whose value is the maximum of the arguments. +

+

The return value is always exact and unrounded.

+
x = new BigNumber('3257869345.0378653')
+BigNumber.maximum(4e9, x, '123456789.9')      // '4000000000'
+
+arr = [12, '13', new BigNumber(14)]
+BigNumber.max.apply(null, arr)                // '14'
+ + + +
minimum.min(n...) ⇒ BigNumber
+

+ n: number|string|BigNumber
+ See BigNumber for further parameter details. +

+

+ Returns a BigNumber whose value is the minimum of the arguments. +

+

The return value is always exact and unrounded.

+
x = new BigNumber('3257869345.0378653')
+BigNumber.minimum(4e9, x, '123456789.9')      // '123456789.9'
+
+arr = [2, new BigNumber(-14), '-15.9999', -12]
+BigNumber.min.apply(null, arr)                // '-15.9999'
+ + + +
+ random.random([dp]) ⇒ BigNumber +
+

dp: number: integer, 0 to 1e+9 inclusive

+

+ Returns a new BigNumber with a pseudo-random value equal to or greater than 0 and + less than 1. +

+

+ The return value will have dp decimal places (or less if trailing zeros are + produced).
+ If dp is omitted then the number of decimal places will default to the current + DECIMAL_PLACES setting. +

+

+ Depending on the value of this BigNumber constructor's + CRYPTO setting and the support for the + crypto object in the host environment, the random digits of the return value are + generated by either Math.random (fastest), crypto.getRandomValues + (Web Cryptography API in recent browsers) or crypto.randomBytes (Node.js). +

+

+ To be able to set CRYPTO to true when using + Node.js, the crypto object must be available globally: +

+
global.crypto = require('crypto')
+

+ If CRYPTO is true, i.e. one of the + crypto methods is to be used, the value of a returned BigNumber should be + cryptographically-secure and statistically indistinguishable from a random value. +

+

+ Throws if dp is invalid. See Errors. +

+
BigNumber.config({ DECIMAL_PLACES: 10 })
+BigNumber.random()              // '0.4117936847'
+BigNumber.random(20)            // '0.78193327636914089009'
+ + + +
sum.sum(n...) ⇒ BigNumber
+

+ n: number|string|BigNumber
+ See BigNumber for further parameter details. +

+

Returns a BigNumber whose value is the sum of the arguments.

+

The return value is always exact and unrounded.

+
x = new BigNumber('3257869345.0378653')
+BigNumber.sum(4e9, x, '123456789.9')      // '7381326134.9378653'
+
+arr = [2, new BigNumber(14), '15.9999', 12]
+BigNumber.sum.apply(null, arr)            // '43.9999'
+ + + +

Properties

+

+ The library's enumerated rounding modes are stored as properties of the constructor.
+ (They are not referenced internally by the library itself.) +

+

+ Rounding modes 0 to 6 (inclusive) are the same as those of Java's + BigDecimal class. +

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
PropertyValueDescription
ROUND_UP0Rounds away from zero
ROUND_DOWN1Rounds towards zero
ROUND_CEIL2Rounds towards Infinity
ROUND_FLOOR3Rounds towards -Infinity
ROUND_HALF_UP4 + Rounds towards nearest neighbour.
+ If equidistant, rounds away from zero +
ROUND_HALF_DOWN5 + Rounds towards nearest neighbour.
+ If equidistant, rounds towards zero +
ROUND_HALF_EVEN6 + Rounds towards nearest neighbour.
+ If equidistant, rounds towards even neighbour +
ROUND_HALF_CEIL7 + Rounds towards nearest neighbour.
+ If equidistant, rounds towards Infinity +
ROUND_HALF_FLOOR8 + Rounds towards nearest neighbour.
+ If equidistant, rounds towards -Infinity +
+
+BigNumber.config({ ROUNDING_MODE: BigNumber.ROUND_CEIL })
+BigNumber.config({ ROUNDING_MODE: 2 })     // equivalent
+ +
DEBUG
+

undefined|false|true

+

+ If BigNumber.DEBUG is set true then an error will be thrown + if this BigNumber constructor receives an invalid value, such as + a value of type number with more than 15 significant digits. + See BigNumber. +

+

+ An error will also be thrown if the isBigNumber + method receives a BigNumber that is not well-formed. + See isBigNumber. +

+
BigNumber.DEBUG = true
+ + +

INSTANCE

+ + +

Methods

+

The methods inherited by a BigNumber instance from its constructor's prototype object.

+

A BigNumber is immutable in the sense that it is not changed by its methods.

+

+ The treatment of ±0, ±Infinity and NaN is + consistent with how JavaScript treats these values. +

+

Many method names have a shorter alias.

+ + + +
absoluteValue.abs() ⇒ BigNumber
+

+ Returns a BigNumber whose value is the absolute value, i.e. the magnitude, of the value of + this BigNumber. +

+

The return value is always exact and unrounded.

+
+x = new BigNumber(-0.8)
+y = x.absoluteValue()           // '0.8'
+z = y.abs()                     // '0.8'
+ + + +
+ comparedTo.comparedTo(n [, base]) ⇒ number +
+

+ n: number|string|BigNumber
+ base: number
+ See BigNumber for further parameter details. +

+ + + + + + + + + + + + + + + + + + +
Returns 
1If the value of this BigNumber is greater than the value of n
-1If the value of this BigNumber is less than the value of n
0If this BigNumber and n have the same value
nullIf the value of either this BigNumber or n is NaN
+
+x = new BigNumber(Infinity)
+y = new BigNumber(5)
+x.comparedTo(y)                 // 1
+x.comparedTo(x.minus(1))        // 0
+y.comparedTo(NaN)               // null
+y.comparedTo('110', 2)          // -1
+ + + +
+ decimalPlaces.dp([dp [, rm]]) ⇒ BigNumber|number +
+

+ dp: number: integer, 0 to 1e+9 inclusive
+ rm: number: integer, 0 to 8 inclusive +

+

+ If dp is a number, returns a BigNumber whose value is the value of this BigNumber + rounded by rounding mode rm to a maximum of dp decimal places. +

+

+ If dp is omitted, or is null or undefined, the return + value is the number of decimal places of the value of this BigNumber, or null if + the value of this BigNumber is ±Infinity or NaN. +

+

+ If rm is omitted, or is null or undefined, + ROUNDING_MODE is used. +

+

+ Throws if dp or rm is invalid. See Errors. +

+
+x = new BigNumber(1234.56)
+x.decimalPlaces(1)                     // '1234.6'
+x.dp()                                 // 2
+x.decimalPlaces(2)                     // '1234.56'
+x.dp(10)                               // '1234.56'
+x.decimalPlaces(0, 1)                  // '1234'
+x.dp(0, 6)                             // '1235'
+x.decimalPlaces(1, 1)                  // '1234.5'
+x.dp(1, BigNumber.ROUND_HALF_EVEN)     // '1234.6'
+x                                      // '1234.56'
+y = new BigNumber('9.9e-101')
+y.dp()                                 // 102
+ + + +
dividedBy.div(n [, base]) ⇒ BigNumber +
+

+ n: number|string|BigNumber
+ base: number
+ See BigNumber for further parameter details. +

+

+ Returns a BigNumber whose value is the value of this BigNumber divided by + n, rounded according to the current + DECIMAL_PLACES and + ROUNDING_MODE settings. +

+
+x = new BigNumber(355)
+y = new BigNumber(113)
+x.dividedBy(y)                  // '3.14159292035398230088'
+x.div(5)                        // '71'
+x.div(47, 16)                   // '5'
+ + + +
+ dividedToIntegerBy.idiv(n [, base]) ⇒ + BigNumber +
+

+ n: number|string|BigNumber
+ base: number
+ See BigNumber for further parameter details. +

+

+ Returns a BigNumber whose value is the integer part of dividing the value of this BigNumber by + n. +

+
+x = new BigNumber(5)
+y = new BigNumber(3)
+x.dividedToIntegerBy(y)         // '1'
+x.idiv(0.7)                     // '7'
+x.idiv('0.f', 16)               // '5'
+ + + +
+ exponentiatedBy.pow(n [, m]) ⇒ BigNumber +
+

+ n: number|string|BigNumber: integer
+ m: number|string|BigNumber +

+

+ Returns a BigNumber whose value is the value of this BigNumber exponentiated by + n, i.e. raised to the power n, and optionally modulo a modulus + m. +

+

+ Throws if n is not an integer. See Errors. +

+

+ If n is negative the result is rounded according to the current + DECIMAL_PLACES and + ROUNDING_MODE settings. +

+

+ As the number of digits of the result of the power operation can grow so large so quickly, + e.g. 123.45610000 has over 50000 digits, the number of significant + digits calculated is limited to the value of the + POW_PRECISION setting (unless a modulus + m is specified). +

+

+ By default POW_PRECISION is set to 0. + This means that an unlimited number of significant digits will be calculated, and that the + method's performance will decrease dramatically for larger exponents. +

+

+ If m is specified and the value of m, n and this + BigNumber are integers, and n is positive, then a fast modular exponentiation + algorithm is used, otherwise the operation will be performed as + x.exponentiatedBy(n).modulo(m) with a + POW_PRECISION of 0. +

+
+Math.pow(0.7, 2)                // 0.48999999999999994
+x = new BigNumber(0.7)
+x.exponentiatedBy(2)            // '0.49'
+BigNumber(3).pow(-2)            // '0.11111111111111111111'
+ + + +
+ integerValue.integerValue([rm]) ⇒ BigNumber +
+

+ rm: number: integer, 0 to 8 inclusive +

+

+ Returns a BigNumber whose value is the value of this BigNumber rounded to an integer using + rounding mode rm. +

+

+ If rm is omitted, or is null or undefined, + ROUNDING_MODE is used. +

+

+ Throws if rm is invalid. See Errors. +

+
+x = new BigNumber(123.456)
+x.integerValue()                        // '123'
+x.integerValue(BigNumber.ROUND_CEIL)    // '124'
+y = new BigNumber(-12.7)
+y.integerValue()                        // '-13'
+y.integerValue(BigNumber.ROUND_DOWN)    // '-12'
+

+ The following is an example of how to add a prototype method that emulates JavaScript's + Math.round function. Math.ceil, Math.floor and + Math.trunc can be emulated in the same way with + BigNumber.ROUND_CEIL, BigNumber.ROUND_FLOOR and + BigNumber.ROUND_DOWN respectively. +

+
+BigNumber.prototype.round = function (n) {
+  return n.integerValue(BigNumber.ROUND_HALF_CEIL);
+};
+x.round()                               // '123'
+ + + +
isEqualTo.eq(n [, base]) ⇒ boolean
+

+ n: number|string|BigNumber
+ base: number
+ See BigNumber for further parameter details. +

+

+ Returns true if the value of this BigNumber is equal to the value of + n, otherwise returns false.
+ As with JavaScript, NaN does not equal NaN. +

+

Note: This method uses the comparedTo method internally.

+
+0 === 1e-324                    // true
+x = new BigNumber(0)
+x.isEqualTo('1e-324')           // false
+BigNumber(-0).eq(x)             // true  ( -0 === 0 )
+BigNumber(255).eq('ff', 16)     // true
+
+y = new BigNumber(NaN)
+y.isEqualTo(NaN)                // false
+ + + +
isFinite.isFinite() ⇒ boolean
+

+ Returns true if the value of this BigNumber is a finite number, otherwise + returns false. +

+

+ The only possible non-finite values of a BigNumber are NaN, Infinity + and -Infinity. +

+
+x = new BigNumber(1)
+x.isFinite()                    // true
+y = new BigNumber(Infinity)
+y.isFinite()                    // false
+

+ Note: The native method isFinite() can be used if + n <= Number.MAX_VALUE. +

+ + + +
isGreaterThan.gt(n [, base]) ⇒ boolean
+

+ n: number|string|BigNumber
+ base: number
+ See BigNumber for further parameter details. +

+

+ Returns true if the value of this BigNumber is greater than the value of + n, otherwise returns false. +

+

Note: This method uses the comparedTo method internally.

+
+0.1 > (0.3 - 0.2)                             // true
+x = new BigNumber(0.1)
+x.isGreaterThan(BigNumber(0.3).minus(0.2))    // false
+BigNumber(0).gt(x)                            // false
+BigNumber(11, 3).gt(11.1, 2)                  // true
+ + + +
+ isGreaterThanOrEqualTo.gte(n [, base]) ⇒ boolean +
+

+ n: number|string|BigNumber
+ base: number
+ See BigNumber for further parameter details. +

+

+ Returns true if the value of this BigNumber is greater than or equal to the value + of n, otherwise returns false. +

+

Note: This method uses the comparedTo method internally.

+
+(0.3 - 0.2) >= 0.1                     // false
+x = new BigNumber(0.3).minus(0.2)
+x.isGreaterThanOrEqualTo(0.1)          // true
+BigNumber(1).gte(x)                    // true
+BigNumber(10, 18).gte('i', 36)         // true
+ + + +
isInteger.isInteger() ⇒ boolean
+

+ Returns true if the value of this BigNumber is an integer, otherwise returns + false. +

+
+x = new BigNumber(1)
+x.isInteger()                   // true
+y = new BigNumber(123.456)
+y.isInteger()                   // false
+ + + +
isLessThan.lt(n [, base]) ⇒ boolean
+

+ n: number|string|BigNumber
+ base: number
+ See BigNumber for further parameter details. +

+

+ Returns true if the value of this BigNumber is less than the value of + n, otherwise returns false. +

+

Note: This method uses the comparedTo method internally.

+
+(0.3 - 0.2) < 0.1                       // true
+x = new BigNumber(0.3).minus(0.2)
+x.isLessThan(0.1)                       // false
+BigNumber(0).lt(x)                      // true
+BigNumber(11.1, 2).lt(11, 3)            // true
+ + + +
+ isLessThanOrEqualTo.lte(n [, base]) ⇒ boolean +
+

+ n: number|string|BigNumber
+ base: number
+ See BigNumber for further parameter details. +

+

+ Returns true if the value of this BigNumber is less than or equal to the value of + n, otherwise returns false. +

+

Note: This method uses the comparedTo method internally.

+
+0.1 <= (0.3 - 0.2)                                // false
+x = new BigNumber(0.1)
+x.isLessThanOrEqualTo(BigNumber(0.3).minus(0.2))  // true
+BigNumber(-1).lte(x)                              // true
+BigNumber(10, 18).lte('i', 36)                    // true
+ + + +
isNaN.isNaN() ⇒ boolean
+

+ Returns true if the value of this BigNumber is NaN, otherwise + returns false. +

+
+x = new BigNumber(NaN)
+x.isNaN()                       // true
+y = new BigNumber('Infinity')
+y.isNaN()                       // false
+

Note: The native method isNaN() can also be used.

+ + + +
isNegative.isNegative() ⇒ boolean
+

+ Returns true if the sign of this BigNumber is negative, otherwise returns + false. +

+
+x = new BigNumber(-0)
+x.isNegative()                  // true
+y = new BigNumber(2)
+y.isNegative()                  // false
+

Note: n < 0 can be used if n <= -Number.MIN_VALUE.

+ + + +
isPositive.isPositive() ⇒ boolean
+

+ Returns true if the sign of this BigNumber is positive, otherwise returns + false. +

+
+x = new BigNumber(-0)
+x.isPositive()                  // false
+y = new BigNumber(2)
+y.isPositive()                  // true
+ + + +
isZero.isZero() ⇒ boolean
+

+ Returns true if the value of this BigNumber is zero or minus zero, otherwise + returns false. +

+
+x = new BigNumber(-0)
+x.isZero() && x.isNegative()         // true
+y = new BigNumber(Infinity)
+y.isZero()                      // false
+

Note: n == 0 can be used if n >= Number.MIN_VALUE.

+ + + +
+ minus.minus(n [, base]) ⇒ BigNumber +
+

+ n: number|string|BigNumber
+ base: number
+ See BigNumber for further parameter details. +

+

Returns a BigNumber whose value is the value of this BigNumber minus n.

+

The return value is always exact and unrounded.

+
+0.3 - 0.1                       // 0.19999999999999998
+x = new BigNumber(0.3)
+x.minus(0.1)                    // '0.2'
+x.minus(0.6, 20)                // '0'
+ + + +
modulo.mod(n [, base]) ⇒ BigNumber
+

+ n: number|string|BigNumber
+ base: number
+ See BigNumber for further parameter details. +

+

+ Returns a BigNumber whose value is the value of this BigNumber modulo n, i.e. + the integer remainder of dividing this BigNumber by n. +

+

+ The value returned, and in particular its sign, is dependent on the value of the + MODULO_MODE setting of this BigNumber constructor. + If it is 1 (default value), the result will have the same sign as this BigNumber, + and it will match that of Javascript's % operator (within the limits of double + precision) and BigDecimal's remainder method. +

+

The return value is always exact and unrounded.

+

+ See MODULO_MODE for a description of the other + modulo modes. +

+
+1 % 0.9                         // 0.09999999999999998
+x = new BigNumber(1)
+x.modulo(0.9)                   // '0.1'
+y = new BigNumber(33)
+y.mod('a', 33)                  // '3'
+ + + +
+ multipliedBy.times(n [, base]) ⇒ BigNumber +
+

+ n: number|string|BigNumber
+ base: number
+ See BigNumber for further parameter details. +

+

+ Returns a BigNumber whose value is the value of this BigNumber multiplied by n. +

+

The return value is always exact and unrounded.

+
+0.6 * 3                         // 1.7999999999999998
+x = new BigNumber(0.6)
+y = x.multipliedBy(3)           // '1.8'
+BigNumber('7e+500').times(y)    // '1.26e+501'
+x.multipliedBy('-a', 16)        // '-6'
+ + + +
negated.negated() ⇒ BigNumber
+

+ Returns a BigNumber whose value is the value of this BigNumber negated, i.e. multiplied by + -1. +

+
+x = new BigNumber(1.8)
+x.negated()                     // '-1.8'
+y = new BigNumber(-1.3)
+y.negated()                     // '1.3'
+ + + +
plus.plus(n [, base]) ⇒ BigNumber
+

+ n: number|string|BigNumber
+ base: number
+ See BigNumber for further parameter details. +

+

Returns a BigNumber whose value is the value of this BigNumber plus n.

+

The return value is always exact and unrounded.

+
+0.1 + 0.2                       // 0.30000000000000004
+x = new BigNumber(0.1)
+y = x.plus(0.2)                 // '0.3'
+BigNumber(0.7).plus(x).plus(y)  // '1'
+x.plus('0.1', 8)                // '0.225'
+ + + +
+ precision.sd([d [, rm]]) ⇒ BigNumber|number +
+

+ d: number|boolean: integer, 1 to 1e+9 + inclusive, or true or false
+ rm: number: integer, 0 to 8 inclusive. +

+

+ If d is a number, returns a BigNumber whose value is the value of this BigNumber + rounded to a precision of d significant digits using rounding mode + rm. +

+

+ If d is omitted or is null or undefined, the return + value is the number of significant digits of the value of this BigNumber, or null + if the value of this BigNumber is ±Infinity or NaN.

+

+

+ If d is true then any trailing zeros of the integer + part of a number are counted as significant digits, otherwise they are not. +

+

+ If rm is omitted or is null or undefined, + ROUNDING_MODE will be used. +

+

+ Throws if d or rm is invalid. See Errors. +

+
+x = new BigNumber(9876.54321)
+x.precision(6)                         // '9876.54'
+x.sd()                                 // 9
+x.precision(6, BigNumber.ROUND_UP)     // '9876.55'
+x.sd(2)                                // '9900'
+x.precision(2, 1)                      // '9800'
+x                                      // '9876.54321'
+y = new BigNumber(987000)
+y.precision()                          // 3
+y.sd(true)                             // 6
+ + + +
shiftedBy.shiftedBy(n) ⇒ BigNumber
+

+ n: number: integer, + -9007199254740991 to 9007199254740991 inclusive +

+

+ Returns a BigNumber whose value is the value of this BigNumber shifted by n + places. +

+ The shift is of the decimal point, i.e. of powers of ten, and is to the left if n + is negative or to the right if n is positive. +

+

The return value is always exact and unrounded.

+

+ Throws if n is invalid. See Errors. +

+
+x = new BigNumber(1.23)
+x.shiftedBy(3)                      // '1230'
+x.shiftedBy(-3)                     // '0.00123'
+ + + +
squareRoot.sqrt() ⇒ BigNumber
+

+ Returns a BigNumber whose value is the square root of the value of this BigNumber, + rounded according to the current + DECIMAL_PLACES and + ROUNDING_MODE settings. +

+

+ The return value will be correctly rounded, i.e. rounded as if the result was first calculated + to an infinite number of correct digits before rounding. +

+
+x = new BigNumber(16)
+x.squareRoot()                  // '4'
+y = new BigNumber(3)
+y.sqrt()                        // '1.73205080756887729353'
+ + + +
+ toExponential.toExponential([dp [, rm]]) ⇒ string +
+

+ dp: number: integer, 0 to 1e+9 inclusive
+ rm: number: integer, 0 to 8 inclusive +

+

+ Returns a string representing the value of this BigNumber in exponential notation rounded + using rounding mode rm to dp decimal places, i.e with one digit + before the decimal point and dp digits after it. +

+

+ If the value of this BigNumber in exponential notation has fewer than dp fraction + digits, the return value will be appended with zeros accordingly. +

+

+ If dp is omitted, or is null or undefined, the number + of digits after the decimal point defaults to the minimum number of digits necessary to + represent the value exactly.
+ If rm is omitted or is null or undefined, + ROUNDING_MODE is used. +

+

+ Throws if dp or rm is invalid. See Errors. +

+
+x = 45.6
+y = new BigNumber(x)
+x.toExponential()               // '4.56e+1'
+y.toExponential()               // '4.56e+1'
+x.toExponential(0)              // '5e+1'
+y.toExponential(0)              // '5e+1'
+x.toExponential(1)              // '4.6e+1'
+y.toExponential(1)              // '4.6e+1'
+y.toExponential(1, 1)           // '4.5e+1'  (ROUND_DOWN)
+x.toExponential(3)              // '4.560e+1'
+y.toExponential(3)              // '4.560e+1'
+ + + +
+ toFixed.toFixed([dp [, rm]]) ⇒ string +
+

+ dp: number: integer, 0 to 1e+9 inclusive
+ rm: number: integer, 0 to 8 inclusive +

+

+ Returns a string representing the value of this BigNumber in normal (fixed-point) notation + rounded to dp decimal places using rounding mode rm. +

+

+ If the value of this BigNumber in normal notation has fewer than dp fraction + digits, the return value will be appended with zeros accordingly. +

+

+ Unlike Number.prototype.toFixed, which returns exponential notation if a number + is greater or equal to 1021, this method will always return normal + notation. +

+

+ If dp is omitted or is null or undefined, the return + value will be unrounded and in normal notation. This is also unlike + Number.prototype.toFixed, which returns the value to zero decimal places.
+ It is useful when fixed-point notation is required and the current + EXPONENTIAL_AT setting causes + toString to return exponential notation.
+ If rm is omitted or is null or undefined, + ROUNDING_MODE is used. +

+

+ Throws if dp or rm is invalid. See Errors. +

+
+x = 3.456
+y = new BigNumber(x)
+x.toFixed()                     // '3'
+y.toFixed()                     // '3.456'
+y.toFixed(0)                    // '3'
+x.toFixed(2)                    // '3.46'
+y.toFixed(2)                    // '3.46'
+y.toFixed(2, 1)                 // '3.45'  (ROUND_DOWN)
+x.toFixed(5)                    // '3.45600'
+y.toFixed(5)                    // '3.45600'
+ + + +
+ toFormat.toFormat([dp [, rm[, format]]]) ⇒ string +
+

+ dp: number: integer, 0 to 1e+9 inclusive
+ rm: number: integer, 0 to 8 inclusive
+ format: object: see FORMAT +

+

+

+ Returns a string representing the value of this BigNumber in normal (fixed-point) notation + rounded to dp decimal places using rounding mode rm, and formatted + according to the properties of the format object. +

+

+ See FORMAT and the examples below for the properties of the + format object, their types, and their usage. A formatting object may contain + some or all of the recognised properties. +

+

+ If dp is omitted or is null or undefined, then the + return value is not rounded to a fixed number of decimal places.
+ If rm is omitted or is null or undefined, + ROUNDING_MODE is used.
+ If format is omitted or is null or undefined, the + FORMAT object is used. +

+

+ Throws if dp, rm or format is invalid. See + Errors. +

+
+fmt = {
+  prefix = '',
+  decimalSeparator: '.',
+  groupSeparator: ',',
+  groupSize: 3,
+  secondaryGroupSize: 0,
+  fractionGroupSeparator: ' ',
+  fractionGroupSize: 0,
+  suffix = ''
+}
+
+x = new BigNumber('123456789.123456789')
+
+// Set the global formatting options
+BigNumber.config({ FORMAT: fmt })
+
+x.toFormat()                              // '123,456,789.123456789'
+x.toFormat(3)                             // '123,456,789.123'
+
+// If a reference to the object assigned to FORMAT has been retained,
+// the format properties can be changed directly
+fmt.groupSeparator = ' '
+fmt.fractionGroupSize = 5
+x.toFormat()                              // '123 456 789.12345 6789'
+
+// Alternatively, pass the formatting options as an argument
+fmt = {
+  prefix: '=> ',
+  decimalSeparator: ',',
+  groupSeparator: '.',
+  groupSize: 3,
+  secondaryGroupSize: 2
+}
+
+x.toFormat()                              // '123 456 789.12345 6789'
+x.toFormat(fmt)                           // '=> 12.34.56.789,123456789'
+x.toFormat(2, fmt)                        // '=> 12.34.56.789,12'
+x.toFormat(3, BigNumber.ROUND_UP, fmt)    // '=> 12.34.56.789,124'
+ + + +
+ toFraction.toFraction([maximum_denominator]) + ⇒ [BigNumber, BigNumber] +
+

+ maximum_denominator: + number|string|BigNumber: integer >= 1 and <= + Infinity +

+

+ Returns an array of two BigNumbers representing the value of this BigNumber as a simple + fraction with an integer numerator and an integer denominator. The denominator will be a + positive non-zero value less than or equal to maximum_denominator. +

+

+ If a maximum_denominator is not specified, or is null or + undefined, the denominator will be the lowest value necessary to represent the + number exactly. +

+

+ Throws if maximum_denominator is invalid. See Errors. +

+
+x = new BigNumber(1.75)
+x.toFraction()                  // '7, 4'
+
+pi = new BigNumber('3.14159265358')
+pi.toFraction()                 // '157079632679,50000000000'
+pi.toFraction(100000)           // '312689, 99532'
+pi.toFraction(10000)            // '355, 113'
+pi.toFraction(100)              // '311, 99'
+pi.toFraction(10)               // '22, 7'
+pi.toFraction(1)                // '3, 1'
+ + + +
toJSON.toJSON() ⇒ string
+

As valueOf.

+
+x = new BigNumber('177.7e+457')
+y = new BigNumber(235.4325)
+z = new BigNumber('0.0098074')
+
+// Serialize an array of three BigNumbers
+str = JSON.stringify( [x, y, z] )
+// "["1.777e+459","235.4325","0.0098074"]"
+
+// Return an array of three BigNumbers
+JSON.parse(str, function (key, val) {
+    return key === '' ? val : new BigNumber(val)
+})
+ + + +
toNumber.toNumber() ⇒ number
+

Returns the value of this BigNumber as a JavaScript number primitive.

+

+ This method is identical to using type coercion with the unary plus operator. +

+
+x = new BigNumber(456.789)
+x.toNumber()                    // 456.789
++x                              // 456.789
+
+y = new BigNumber('45987349857634085409857349856430985')
+y.toNumber()                    // 4.598734985763409e+34
+
+z = new BigNumber(-0)
+1 / z.toNumber()                // -Infinity
+1 / +z                          // -Infinity
+ + + +
+ toPrecision.toPrecision([sd [, rm]]) ⇒ string +
+

+ sd: number: integer, 1 to 1e+9 inclusive
+ rm: number: integer, 0 to 8 inclusive +

+

+ Returns a string representing the value of this BigNumber rounded to sd + significant digits using rounding mode rm. +

+

+ If sd is less than the number of digits necessary to represent the integer part + of the value in normal (fixed-point) notation, then exponential notation is used. +

+

+ If sd is omitted, or is null or undefined, then the + return value is the same as n.toString().
+ If rm is omitted or is null or undefined, + ROUNDING_MODE is used. +

+

+ Throws if sd or rm is invalid. See Errors. +

+
+x = 45.6
+y = new BigNumber(x)
+x.toPrecision()                 // '45.6'
+y.toPrecision()                 // '45.6'
+x.toPrecision(1)                // '5e+1'
+y.toPrecision(1)                // '5e+1'
+y.toPrecision(2, 0)             // '4.6e+1'  (ROUND_UP)
+y.toPrecision(2, 1)             // '4.5e+1'  (ROUND_DOWN)
+x.toPrecision(5)                // '45.600'
+y.toPrecision(5)                // '45.600'
+ + + +
toString.toString([base]) ⇒ string
+

+ base: number: integer, 2 to ALPHABET.length + inclusive (see ALPHABET). +

+

+ Returns a string representing the value of this BigNumber in the specified base, or base + 10 if base is omitted or is null or + undefined. +

+

+ For bases above 10, and using the default base conversion alphabet + (see ALPHABET), values from 10 to + 35 are represented by a-z + (as with Number.prototype.toString). +

+

+ If a base is specified the value is rounded according to the current + DECIMAL_PLACES + and ROUNDING_MODE settings. +

+

+ If a base is not specified, and this BigNumber has a positive + exponent that is equal to or greater than the positive component of the + current EXPONENTIAL_AT setting, + or a negative exponent equal to or less than the negative component of the + setting, then exponential notation is returned. +

+

If base is null or undefined it is ignored.

+

+ Throws if base is invalid. See Errors. +

+
+x = new BigNumber(750000)
+x.toString()                    // '750000'
+BigNumber.config({ EXPONENTIAL_AT: 5 })
+x.toString()                    // '7.5e+5'
+
+y = new BigNumber(362.875)
+y.toString(2)                   // '101101010.111'
+y.toString(9)                   // '442.77777777777777777778'
+y.toString(32)                  // 'ba.s'
+
+BigNumber.config({ DECIMAL_PLACES: 4 });
+z = new BigNumber('1.23456789')
+z.toString()                    // '1.23456789'
+z.toString(10)                  // '1.2346'
+ + + +
valueOf.valueOf() ⇒ string
+

+ As toString, but does not accept a base argument and includes + the minus sign for negative zero. +

+
+x = new BigNumber('-0')
+x.toString()                    // '0'
+x.valueOf()                     // '-0'
+y = new BigNumber('1.777e+457')
+y.valueOf()                     // '1.777e+457'
+ + + +

Properties

+

The properties of a BigNumber instance:

+ + + + + + + + + + + + + + + + + + + + + + + + + +
PropertyDescriptionTypeValue
ccoefficient*number[] Array of base 1e14 numbers
eexponentnumberInteger, -1000000000 to 1000000000 inclusive
ssignnumber-1 or 1
+

*significand

+

+ The value of any of the c, e and s properties may also + be null. +

+

+ The above properties are best considered to be read-only. In early versions of this library it + was okay to change the exponent of a BigNumber by writing to its exponent property directly, + but this is no longer reliable as the value of the first element of the coefficient array is + now dependent on the exponent. +

+

+ Note that, as with JavaScript numbers, the original exponent and fractional trailing zeros are + not necessarily preserved. +

+
x = new BigNumber(0.123)              // '0.123'
+x.toExponential()                     // '1.23e-1'
+x.c                                   // '1,2,3'
+x.e                                   // -1
+x.s                                   // 1
+
+y = new Number(-123.4567000e+2)       // '-12345.67'
+y.toExponential()                     // '-1.234567e+4'
+z = new BigNumber('-123.4567000e+2')  // '-12345.67'
+z.toExponential()                     // '-1.234567e+4'
+z.c                                   // '1,2,3,4,5,6,7'
+z.e                                   // 4
+z.s                                   // -1
+ + + +

Zero, NaN and Infinity

+

+ The table below shows how ±0, NaN and + ±Infinity are stored. +

+ + + + + + + + + + + + + + + + + + + + + + + + + +
ces
±0[0]0±1
NaNnullnullnull
±Infinitynullnull±1
+
+x = new Number(-0)              // 0
+1 / x == -Infinity              // true
+
+y = new BigNumber(-0)           // '0'
+y.c                             // '0' ( [0].toString() )
+y.e                             // 0
+y.s                             // -1
+ + + +

Errors

+

The table below shows the errors that are thrown.

+

+ The errors are generic Error objects whose message begins + '[BigNumber Error]'. +

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
MethodThrows
+ BigNumber
+ comparedTo
+ dividedBy
+ dividedToIntegerBy
+ isEqualTo
+ isGreaterThan
+ isGreaterThanOrEqualTo
+ isLessThan
+ isLessThanOrEqualTo
+ minus
+ modulo
+ plus
+ multipliedBy +
Base not a primitive number
Base not an integer
Base out of range
Number primitive has more than 15 significant digits*
Not a base... number*
Not a number*
cloneObject expected
configObject expected
DECIMAL_PLACES not a primitive number
DECIMAL_PLACES not an integer
DECIMAL_PLACES out of range
ROUNDING_MODE not a primitive number
ROUNDING_MODE not an integer
ROUNDING_MODE out of range
EXPONENTIAL_AT not a primitive number
EXPONENTIAL_AT not an integer
EXPONENTIAL_AT out of range
RANGE not a primitive number
RANGE not an integer
RANGE cannot be zero
RANGE cannot be zero
CRYPTO not true or false
crypto unavailable
MODULO_MODE not a primitive number
MODULO_MODE not an integer
MODULO_MODE out of range
POW_PRECISION not a primitive number
POW_PRECISION not an integer
POW_PRECISION out of range
FORMAT not an object
ALPHABET invalid
+ decimalPlaces
+ precision
+ random
+ shiftedBy
+ toExponential
+ toFixed
+ toFormat
+ toPrecision +
Argument not a primitive number
Argument not an integer
Argument out of range
+ decimalPlaces
+ precision +
Argument not true or false
exponentiatedByArgument not an integer
isBigNumberInvalid BigNumber*
+ minimum
+ maximum +
Not a number*
+ random + crypto unavailable
+ toFormat + Argument not an object
toFractionArgument not an integer
Argument out of range
toStringBase not a primitive number
Base not an integer
Base out of range
+

*Only thrown if BigNumber.DEBUG is true.

+

To determine if an exception is a BigNumber Error:

+
+try {
+  // ...
+} catch (e) {
+  if (e instanceof Error && e.message.indexOf('[BigNumber Error]') === 0) {
+      // ...
+  }
+}
+ + + +

Type coercion

+

+ To prevent the accidental use of a BigNumber in primitive number operations, or the + accidental addition of a BigNumber to a string, the valueOf method can be safely + overwritten as shown below. +

+

+ The valueOf method is the same as the + toJSON method, and both are the same as the + toString method except they do not take a base + argument and they include the minus sign for negative zero. +

+
+BigNumber.prototype.valueOf = function () {
+  throw Error('valueOf called!')
+}
+
+x = new BigNumber(1)
+x / 2                    // '[BigNumber Error] valueOf called!'
+x + 'abc'                // '[BigNumber Error] valueOf called!'
+
+ + + +

FAQ

+ +
Why are trailing fractional zeros removed from BigNumbers?
+

+ Some arbitrary-precision libraries retain trailing fractional zeros as they can indicate the + precision of a value. This can be useful but the results of arithmetic operations can be + misleading. +

+
+x = new BigDecimal("1.0")
+y = new BigDecimal("1.1000")
+z = x.add(y)                      // 2.1000
+
+x = new BigDecimal("1.20")
+y = new BigDecimal("3.45000")
+z = x.multiply(y)                 // 4.1400000
+

+ To specify the precision of a value is to specify that the value lies + within a certain range. +

+

+ In the first example, x has a value of 1.0. The trailing zero shows + the precision of the value, implying that it is in the range 0.95 to + 1.05. Similarly, the precision indicated by the trailing zeros of y + indicates that the value is in the range 1.09995 to 1.10005. +

+

+ If we add the two lowest values in the ranges we have, 0.95 + 1.09995 = 2.04995, + and if we add the two highest values we have, 1.05 + 1.10005 = 2.15005, so the + range of the result of the addition implied by the precision of its operands is + 2.04995 to 2.15005. +

+

+ The result given by BigDecimal of 2.1000 however, indicates that the value is in + the range 2.09995 to 2.10005 and therefore the precision implied by + its trailing zeros may be misleading. +

+

+ In the second example, the true range is 4.122744 to 4.157256 yet + the BigDecimal answer of 4.1400000 indicates a range of 4.13999995 + to 4.14000005. Again, the precision implied by the trailing zeros may be + misleading. +

+

+ This library, like binary floating point and most calculators, does not retain trailing + fractional zeros. Instead, the toExponential, toFixed and + toPrecision methods enable trailing zeros to be added if and when required.
+

+
+ + + diff --git a/ts-ticket-office-service/node_modules/bignumber.js/package.json b/ts-ticket-office-service/node_modules/bignumber.js/package.json new file mode 100644 index 000000000..885136c6d --- /dev/null +++ b/ts-ticket-office-service/node_modules/bignumber.js/package.json @@ -0,0 +1,40 @@ +{ + "name": "bignumber.js", + "description": "A library for arbitrary-precision decimal and non-decimal arithmetic", + "version": "9.0.0", + "keywords": [ + "arbitrary", + "precision", + "arithmetic", + "big", + "number", + "decimal", + "float", + "biginteger", + "bigdecimal", + "bignumber", + "bigint", + "bignum" + ], + "repository": { + "type": "git", + "url": "https://github.com/MikeMcl/bignumber.js.git" + }, + "main": "bignumber", + "module": "bignumber.mjs", + "browser": "bignumber.js", + "types": "bignumber.d.ts", + "author": { + "name": "Michael Mclaughlin", + "email": "M8ch88l@gmail.com" + }, + "engines": { + "node": "*" + }, + "license": "MIT", + "scripts": { + "test": "node test/test", + "build": "uglifyjs bignumber.js --source-map -c -m -o bignumber.min.js" + }, + "dependencies": {} +} diff --git a/ts-ticket-office-service/node_modules/bson/HISTORY.md b/ts-ticket-office-service/node_modules/bson/HISTORY.md deleted file mode 100644 index 30f0f5fbb..000000000 --- a/ts-ticket-office-service/node_modules/bson/HISTORY.md +++ /dev/null @@ -1,199 +0,0 @@ -1.0.4 2016-01-11 ----------------- -- #204 remove Buffer.from as it's partially broken in early 4.x.x. series of node releases. - -1.0.3 2016-01-03 ----------------- -- Fixed toString for ObjectId so it will work with inspect. - -1.0.2 2016-01-02 ----------------- -- Minor optimizations for ObjectID to use Buffer.from where available. - -1.0.1 2016-12-06 ----------------- -- Reverse behavior for undefined to be serialized as NULL. MongoDB 3.4 does not allow for undefined comparisons. - -1.0.0 2016-12-06 ----------------- -- Introduced new BSON API and documentation. - -0.5.7 2016-11-18 ------------------ -- NODE-848 BSON Regex flags must be alphabetically ordered. - -0.5.6 2016-10-19 ------------------ -- NODE-833, Detects cyclic dependencies in documents and throws error if one is found. -- Fix(deserializer): corrected the check for (size + index) comparison… (Issue #195, https://github.com/JoelParke). - -0.5.5 2016-09-15 ------------------ -- Added DBPointer up conversion to DBRef - -0.5.4 2016-08-23 ------------------ -- Added promoteValues flag (default to true) allowing user to specify if deserialization should be into wrapper classes only. - -0.5.3 2016-07-11 ------------------ -- Throw error if ObjectId is not a string or a buffer. - -0.5.2 2016-07-11 ------------------ -- All values encoded big-endian style for ObjectId. - -0.5.1 2016-07-11 ------------------ -- Fixed encoding/decoding issue in ObjectId timestamp generation. -- Removed BinaryParser dependency from the serializer/deserializer. - -0.5.0 2016-07-05 ------------------ -- Added Decimal128 type and extended test suite to include entire bson corpus. - -0.4.23 2016-04-08 ------------------ -- Allow for proper detection of ObjectId or objects that look like ObjectId, improving compatibility across third party libraries. -- Remove one package from dependency due to having been pulled from NPM. - -0.4.22 2016-03-04 ------------------ -- Fix "TypeError: data.copy is not a function" in Electron (Issue #170, https://github.com/kangas). -- Fixed issue with undefined type on deserializing. - -0.4.21 2016-01-12 ------------------ -- Minor optimizations to avoid non needed object creation. - -0.4.20 2015-10-15 ------------------ -- Added bower file to repository. -- Fixed browser pid sometimes set greater than 0xFFFF on browsers (Issue #155, https://github.com/rahatarmanahmed) - -0.4.19 2015-10-15 ------------------ -- Remove all support for bson-ext. - -0.4.18 2015-10-15 ------------------ -- ObjectID equality check should return boolean instead of throwing exception for invalid oid string #139 -- add option for deserializing binary into Buffer object #116 - -0.4.17 2015-10-15 ------------------ -- Validate regexp string for null bytes and throw if there is one. - -0.4.16 2015-10-07 ------------------ -- Fixed issue with return statement in Map.js. - -0.4.15 2015-10-06 ------------------ -- Exposed Map correctly via index.js file. - -0.4.14 2015-10-06 ------------------ -- Exposed Map correctly via bson.js file. - -0.4.13 2015-10-06 ------------------ -- Added ES6 Map type serialization as well as a polyfill for ES5. - -0.4.12 2015-09-18 ------------------ -- Made ignore undefined an optional parameter. - -0.4.11 2015-08-06 ------------------ -- Minor fix for invalid key checking. - -0.4.10 2015-08-06 ------------------ -- NODE-38 Added new BSONRegExp type to allow direct serialization to MongoDB type. -- Some performance improvements by in lining code. - -0.4.9 2015-08-06 ----------------- -- Undefined fields are omitted from serialization in objects. - -0.4.8 2015-07-14 ----------------- -- Fixed size validation to ensure we can deserialize from dumped files. - -0.4.7 2015-06-26 ----------------- -- Added ability to instruct deserializer to return raw BSON buffers for named array fields. -- Minor deserialization optimization by moving inlined function out. - -0.4.6 2015-06-17 ----------------- -- Fixed serializeWithBufferAndIndex bug. - -0.4.5 2015-06-17 ----------------- -- Removed any references to the shared buffer to avoid non GC collectible bson instances. - -0.4.4 2015-06-17 ----------------- -- Fixed rethrowing of error when not RangeError. - -0.4.3 2015-06-17 ----------------- -- Start buffer at 64K and double as needed, meaning we keep a low memory profile until needed. - -0.4.2 2015-06-16 ----------------- -- More fixes for corrupt Bson - -0.4.1 2015-06-16 ----------------- -- More fixes for corrupt Bson - -0.4.0 2015-06-16 ----------------- -- New JS serializer serializing into a single buffer then copying out the new buffer. Performance is similar to current C++ parser. -- Removed bson-ext extension dependency for now. - -0.3.2 2015-03-27 ----------------- -- Removed node-gyp from install script in package.json. - -0.3.1 2015-03-27 ----------------- -- Return pure js version on native() call if failed to initialize. - -0.3.0 2015-03-26 ----------------- -- Pulled out all C++ code into bson-ext and made it an optional dependency. - -0.2.21 2015-03-21 ------------------ -- Updated Nan to 1.7.0 to support io.js and node 0.12.0 - -0.2.19 2015-02-16 ------------------ -- Updated Nan to 1.6.2 to support io.js and node 0.12.0 - -0.2.18 2015-01-20 ------------------ -- Updated Nan to 1.5.1 to support io.js - -0.2.16 2014-12-17 ------------------ -- Made pid cycle on 0xffff to avoid weird overflows on creation of ObjectID's - -0.2.12 2014-08-24 ------------------ -- Fixes for fortify review of c++ extension -- toBSON correctly allows returns of non objects - -0.2.3 2013-10-01 ----------------- -- Drying of ObjectId code for generation of id (Issue #54, https://github.com/moredip) -- Fixed issue where corrupt CString's could cause endless loop -- Support for Node 0.11.X > (Issue #49, https://github.com/kkoopa) - -0.1.4 2012-09-25 ----------------- -- Added precompiled c++ native extensions for win32 ia32 and x64 diff --git a/ts-ticket-office-service/node_modules/bson/README.md b/ts-ticket-office-service/node_modules/bson/README.md index af25c3c07..cd7242fdf 100644 --- a/ts-ticket-office-service/node_modules/bson/README.md +++ b/ts-ticket-office-service/node_modules/bson/README.md @@ -1,141 +1,376 @@ # BSON parser -If you don't yet know what BSON actually is, read [the spec](http://bsonspec.org). +BSON is short for "Binary JSON," and is the binary-encoded serialization of JSON-like documents. You can learn more about it in [the specification](http://bsonspec.org). -The browser version of the BSON parser is compiled using webpack and the current -version is pre-compiled in the browser_build directory. To build a new version perform the following operation. +This browser version of the BSON parser is compiled using [rollup](https://rollupjs.org/) and the current version is pre-compiled in the `dist` directory. + +This is the default BSON parser, however, there is a C++ Node.js addon version as well that does not support the browser. It can be found at [mongod-js/bson-ext](https://github.com/mongodb-js/bson-ext). + +### Table of Contents +- [Usage](#usage) +- [Bugs/Feature Requests](#bugs--feature-requests) +- [Installation](#installation) +- [Documentation](#documentation) +- [FAQ](#faq) + +## Bugs / Feature Requests + +Think you've found a bug? Want to see a new feature in `bson`? Please open a case in our issue management tool, JIRA: + +1. Create an account and login: [jira.mongodb.org](https://jira.mongodb.org) +2. Navigate to the NODE project: [jira.mongodb.org/browse/NODE](https://jira.mongodb.org/browse/NODE) +3. Click **Create Issue** - Please provide as much information as possible about the issue and how to reproduce it. + +Bug reports in JIRA for all driver projects (i.e. NODE, PYTHON, CSHARP, JAVA) and the Core Server (i.e. SERVER) project are **public**. + +## Usage + +To build a new version perform the following operations: ``` npm install npm run build ``` -A simple example of how to use BSON in the browser: +### Node (no bundling) +A simple example of how to use BSON in `Node.js`: + +```js +const BSON = require('bson'); +const Long = BSON.Long; + +// Serialize a document +const doc = { long: Long.fromNumber(100) }; +const data = BSON.serialize(doc); +console.log('data:', data); + +// Deserialize the resulting Buffer +const doc_2 = BSON.deserialize(data); +console.log('doc_2:', doc_2); +``` + +### Browser (no bundling) + +If you are not using a bundler like webpack, you can include `dist/bson.bundle.js` using a script tag. It includes polyfills for built-in node types like `Buffer`. ```html - + ``` -A simple example of how to use BSON in `node.js`: +### Using webpack + +If using webpack, you can use your normal import/require syntax of your project to pull in the `bson` library. + +ES6 Example: ```js -// Get BSON parser class -var BSON = require('bson') -// Get the Long type -var Long = BSON.Long; -// Create a bson parser instance -var bson = new BSON(); +import { Long, serialize, deserialize } from 'bson'; + +// Serialize a document +const doc = { long: Long.fromNumber(100) }; +const data = serialize(doc); +console.log('data:', data); + +// De serialize it again +const doc_2 = deserialize(data); +console.log('doc_2:', doc_2); +``` -// Serialize document -var doc = { long: Long.fromNumber(100) } +ES5 Example: + +```js +const BSON = require('bson'); +const Long = BSON.Long; // Serialize a document -var data = bson.serialize(doc) -console.log('data:', data) +const doc = { long: Long.fromNumber(100) }; +const data = BSON.serialize(doc); +console.log('data:', data); // Deserialize the resulting Buffer -var doc_2 = bson.deserialize(data) -console.log('doc_2:', doc_2) +const doc_2 = BSON.deserialize(data); +console.log('doc_2:', doc_2); +``` + +Depending on your settings, webpack will under the hood resolve to one of the following: + +- `dist/bson.browser.esm.js` If your project is in the browser and using ES6 modules (Default for `webworker` and `web` targets) +- `dist/bson.browser.umd.js` If your project is in the browser and not using ES6 modules +- `dist/bson.esm.js` If your project is in Node.js and using ES6 modules (Default for `node` targets) +- `lib/bson.js` (the normal include path) If your project is in Node.js and not using ES6 modules + +For more information, see [this page on webpack's `resolve.mainFields`](https://webpack.js.org/configuration/resolve/#resolvemainfields) and [the `package.json` for this project](./package.json#L52) + +### Usage with Angular + +Starting with Angular 6, Angular CLI removed the shim for `global` and other node built-in variables (original comment [here](https://github.com/angular/angular-cli/issues/9827#issuecomment-386154063)). If you are using BSON with Angular, you may need to add the following shim to your `polyfills.ts` file: + +```js +// In polyfills.ts +(window as any).global = window; ``` +- [Original Comment by Angular CLI](https://github.com/angular/angular-cli/issues/9827#issuecomment-386154063) +- [Original Source for Solution](https://stackoverflow.com/a/50488337/4930088) + ## Installation `npm install bson` -## API +## Documentation -### BSON types +### Objects -For all BSON types documentation, please refer to the documentation for the mongodb driver. +
+
EJSON : object
+
+
-https://github.com/mongodb/node-mongodb-native +### Functions -### BSON serialization and deserialiation +
+
setInternalBufferSize(size)
+

Sets the size of the internal serialization buffer.

+
+
serialize(object)Buffer
+

Serialize a Javascript object.

+
+
serializeWithBufferAndIndex(object, buffer)Number
+

Serialize a Javascript object using a predefined Buffer and index into the buffer, useful when pre-allocating the space for serialization.

+
+
deserialize(buffer)Object
+

Deserialize data as BSON.

+
+
calculateObjectSize(object)Number
+

Calculate the bson size for a passed in Javascript object.

+
+
deserializeStream(data, startIndex, numberOfDocuments, documents, docStartIndex, [options])Number
+

Deserialize stream data as BSON documents.

+
+
-**`new BSON()`** - Creates a new BSON seralizer/deserializer you can use to serialize and deserialize BSON. + -#### BSON.serialize +### EJSON -The BSON serialize method takes a javascript object and an optional options object and returns a Node.js Buffer. +* [EJSON](#EJSON) - * BSON.serialize(object, options) - * @param {Object} object the Javascript object to serialize. - * @param {Boolean} [options.checkKeys=false] the serializer will check if keys are valid. - * @param {Boolean} [options.serializeFunctions=false] serialize the javascript. functions. - * @param {Boolean} [options.ignoreUndefined=true] - * @return {Buffer} returns a Buffer instance. + * [.parse(text, [options])](#EJSON.parse) -#### BSON.serializeWithBufferAndIndex + * [.stringify(value, [replacer], [space], [options])](#EJSON.stringify) -The BSON serializeWithBufferAndIndex method takes an object, a target buffer instance and an optional options object and returns the end serialization index in the final buffer. + * [.serialize(bson, [options])](#EJSON.serialize) - * BSON.serializeWithBufferAndIndex(object, buffer, options) - * @param {Object} object the Javascript object to serialize. - * @param {Buffer} buffer the Buffer you pre-allocated to store the serialized BSON object. - * @param {Boolean} [options.checkKeys=false] the serializer will check if keys are valid. - * @param {Boolean} [options.serializeFunctions=false] serialize the javascript functions. - * @param {Boolean} [options.ignoreUndefined=true] ignore undefined fields. - * @param {Number} [options.index=0] the index in the buffer where we wish to start serializing into. - * @return {Number} returns the index pointing to the last written byte in the buffer. + * [.deserialize(ejson, [options])](#EJSON.deserialize) -#### BSON.calculateObjectSize -The BSON calculateObjectSize method takes a javascript object and an optional options object and returns the size of the BSON object. + - * BSON.calculateObjectSize(object, options) - * @param {Object} object the Javascript object to serialize. - * @param {Boolean} [options.serializeFunctions=false] serialize the javascript. functions. - * @param {Boolean} [options.ignoreUndefined=true] - * @return {Buffer} returns a Buffer instance. +#### *EJSON*.parse(text, [options]) -#### BSON.deserialize +| Param | Type | Default | Description | +| --- | --- | --- | --- | +| text | string | | | +| [options] | object | | Optional settings | +| [options.relaxed] | boolean | true | Attempt to return native JS types where possible, rather than BSON types (if true) | -The BSON deserialize method takes a node.js Buffer and an optional options object and returns a deserialized Javascript object. +Parse an Extended JSON string, constructing the JavaScript value or object described by that +string. - * BSON.deserialize(buffer, options) - * @param {Object} [options.evalFunctions=false] evaluate functions in the BSON document scoped to the object deserialized. - * @param {Object} [options.cacheFunctions=false] cache evaluated functions for reuse. - * @param {Object} [options.cacheFunctionsCrc32=false] use a crc32 code for caching, otherwise use the string of the function. - * @param {Object} [options.promoteLongs=true] when deserializing a Long will fit it into a Number if it's smaller than 53 bits - * @param {Object} [options.promoteBuffers=false] when deserializing a Binary will return it as a node.js Buffer instance. - * @param {Object} [options.promoteValues=false] when deserializing will promote BSON values to their Node.js closest equivalent types. - * @param {Object} [options.fieldsAsRaw=null] allow to specify if there what fields we wish to return as unserialized raw buffer. - * @param {Object} [options.bsonRegExp=false] return BSON regular expressions as BSONRegExp instances. - * @return {Number} returns the next index in the buffer after deserialization **x** numbers of documents. +**Example** +```js +const { EJSON } = require('bson'); +const text = '{ "int32": { "$numberInt": "10" } }'; + +// prints { int32: { [String: '10'] _bsontype: 'Int32', value: '10' } } +console.log(EJSON.parse(text, { relaxed: false })); -#### BSON.deserializeStream +// prints { int32: 10 } +console.log(EJSON.parse(text)); +``` + + +#### *EJSON*.stringify(value, [replacer], [space], [options]) + +| Param | Type | Default | Description | +| --- | --- | --- | --- | +| value | object | | The value to convert to extended JSON | +| [replacer] | function \| array | | A function that alters the behavior of the stringification process, or an array of String and Number objects that serve as a whitelist for selecting/filtering the properties of the value object to be included in the JSON string. If this value is null or not provided, all properties of the object are included in the resulting JSON string | +| [space] | string \| number | | A String or Number object that's used to insert white space into the output JSON string for readability purposes. | +| [options] | object | | Optional settings | +| [options.relaxed] | boolean | true | Enabled Extended JSON's `relaxed` mode | +| [options.legacy] | boolean | true | Output in Extended JSON v1 | + +Converts a BSON document to an Extended JSON string, optionally replacing values if a replacer +function is specified or optionally including only the specified properties if a replacer array +is specified. + +**Example** +```js +const { EJSON } = require('bson'); +const Int32 = require('mongodb').Int32; +const doc = { int32: new Int32(10) }; -The BSON deserializeStream method takes a node.js Buffer, startIndex and allow more control over deserialization of a Buffer containing concatenated BSON documents. +// prints '{"int32":{"$numberInt":"10"}}' +console.log(EJSON.stringify(doc, { relaxed: false })); - * BSON.deserializeStream(buffer, startIndex, numberOfDocuments, documents, docStartIndex, options) - * @param {Buffer} buffer the buffer containing the serialized set of BSON documents. - * @param {Number} startIndex the start index in the data Buffer where the deserialization is to start. - * @param {Number} numberOfDocuments number of documents to deserialize. - * @param {Array} documents an array where to store the deserialized documents. - * @param {Number} docStartIndex the index in the documents array from where to start inserting documents. - * @param {Object} [options.evalFunctions=false] evaluate functions in the BSON document scoped to the object deserialized. - * @param {Object} [options.cacheFunctions=false] cache evaluated functions for reuse. - * @param {Object} [options.cacheFunctionsCrc32=false] use a crc32 code for caching, otherwise use the string of the function. - * @param {Object} [options.promoteLongs=true] when deserializing a Long will fit it into a Number if it's smaller than 53 bits - * @param {Object} [options.promoteBuffers=false] when deserializing a Binary will return it as a node.js Buffer instance. - * @param {Object} [options.promoteValues=false] when deserializing will promote BSON values to their Node.js closest equivalent types. - * @param {Object} [options.fieldsAsRaw=null] allow to specify if there what fields we wish to return as unserialized raw buffer. - * @param {Object} [options.bsonRegExp=false] return BSON regular expressions as BSONRegExp instances. - * @return {Object} returns the deserialized Javascript Object. +// prints '{"int32":10}' +console.log(EJSON.stringify(doc)); +``` + + +#### *EJSON*.serialize(bson, [options]) + +| Param | Type | Description | +| --- | --- | --- | +| bson | object | The object to serialize | +| [options] | object | Optional settings passed to the `stringify` function | + +Serializes an object to an Extended JSON string, and reparse it as a JavaScript object. + + + +#### *EJSON*.deserialize(ejson, [options]) + +| Param | Type | Description | +| --- | --- | --- | +| ejson | object | The Extended JSON object to deserialize | +| [options] | object | Optional settings passed to the parse method | + +Deserializes an Extended JSON object into a plain JavaScript object with native/BSON types + + + +### setInternalBufferSize(size) + +| Param | Type | Description | +| --- | --- | --- | +| size | number | The desired size for the internal serialization buffer | + +Sets the size of the internal serialization buffer. + + + +### serialize(object) + +| Param | Type | Default | Description | +| --- | --- | --- | --- | +| object | Object | | the Javascript object to serialize. | +| [options.checkKeys] | Boolean | | the serializer will check if keys are valid. | +| [options.serializeFunctions] | Boolean | false | serialize the javascript functions **(default:false)**. | +| [options.ignoreUndefined] | Boolean | true | ignore undefined fields **(default:true)**. | + +Serialize a Javascript object. + +**Returns**: Buffer - returns the Buffer object containing the serialized object. + + +### serializeWithBufferAndIndex(object, buffer) + +| Param | Type | Default | Description | +| --- | --- | --- | --- | +| object | Object | | the Javascript object to serialize. | +| buffer | Buffer | | the Buffer you pre-allocated to store the serialized BSON object. | +| [options.checkKeys] | Boolean | | the serializer will check if keys are valid. | +| [options.serializeFunctions] | Boolean | false | serialize the javascript functions **(default:false)**. | +| [options.ignoreUndefined] | Boolean | true | ignore undefined fields **(default:true)**. | +| [options.index] | Number | | the index in the buffer where we wish to start serializing into. | + +Serialize a Javascript object using a predefined Buffer and index into the buffer, useful when pre-allocating the space for serialization. + +**Returns**: Number - returns the index pointing to the last written byte in the buffer. + + +### deserialize(buffer) + +| Param | Type | Default | Description | +| --- | --- | --- | --- | +| buffer | Buffer | | the buffer containing the serialized set of BSON documents. | +| [options.evalFunctions] | Object | false | evaluate functions in the BSON document scoped to the object deserialized. | +| [options.cacheFunctions] | Object | false | cache evaluated functions for reuse. | +| [options.promoteLongs] | Object | true | when deserializing a Long will fit it into a Number if it's smaller than 53 bits | +| [options.promoteBuffers] | Object | false | when deserializing a Binary will return it as a node.js Buffer instance. | +| [options.promoteValues] | Object | false | when deserializing will promote BSON values to their Node.js closest equivalent types. | +| [options.fieldsAsRaw] | Object | | allow to specify if there what fields we wish to return as unserialized raw buffer. | +| [options.bsonRegExp] | Object | false | return BSON regular expressions as BSONRegExp instances. | +| [options.allowObjectSmallerThanBufferSize] | boolean | false | allows the buffer to be larger than the parsed BSON object | + +Deserialize data as BSON. + +**Returns**: Object - returns the deserialized Javascript Object. + + +### calculateObjectSize(object) + +| Param | Type | Default | Description | +| --- | --- | --- | --- | +| object | Object | | the Javascript object to calculate the BSON byte size for. | +| [options.serializeFunctions] | Boolean | false | serialize the javascript functions **(default:false)**. | +| [options.ignoreUndefined] | Boolean | true | ignore undefined fields **(default:true)**. | + +Calculate the bson size for a passed in Javascript object. + +**Returns**: Number - returns the number of bytes the BSON object will take up. + + +### deserializeStream(data, startIndex, numberOfDocuments, documents, docStartIndex, [options]) + +| Param | Type | Default | Description | +| --- | --- | --- | --- | +| data | Buffer | | the buffer containing the serialized set of BSON documents. | +| startIndex | Number | | the start index in the data Buffer where the deserialization is to start. | +| numberOfDocuments | Number | | number of documents to deserialize. | +| documents | Array | | an array where to store the deserialized documents. | +| docStartIndex | Number | | the index in the documents array from where to start inserting documents. | +| [options] | Object | | additional options used for the deserialization. | +| [options.evalFunctions] | Object | false | evaluate functions in the BSON document scoped to the object deserialized. | +| [options.cacheFunctions] | Object | false | cache evaluated functions for reuse. | +| [options.promoteLongs] | Object | true | when deserializing a Long will fit it into a Number if it's smaller than 53 bits | +| [options.promoteBuffers] | Object | false | when deserializing a Binary will return it as a node.js Buffer instance. | +| [options.promoteValues] | Object | false | when deserializing will promote BSON values to their Node.js closest equivalent types. | +| [options.fieldsAsRaw] | Object | | allow to specify if there what fields we wish to return as unserialized raw buffer. | +| [options.bsonRegExp] | Object | false | return BSON regular expressions as BSONRegExp instances. | + +Deserialize stream data as BSON documents. + +**Returns**: Number - returns the next index in the buffer after deserialization **x** numbers of documents. + +## FAQ + +#### Why does `undefined` get converted to `null`? + +The `undefined` BSON type has been [deprecated for many years](http://bsonspec.org/spec.html), so this library has dropped support for it. Use the `ignoreUndefined` option (for example, from the [driver](http://mongodb.github.io/node-mongodb-native/2.2/api/MongoClient.html#connect) ) to instead remove `undefined` keys. + +#### How do I add custom serialization logic? + +This library looks for `toBSON()` functions on every path, and calls the `toBSON()` function to get the value to serialize. + +```javascript +const BSON = require('bson'); + +class CustomSerialize { + toBSON() { + return 42; + } +} + +const obj = { answer: new CustomSerialize() }; +// "{ answer: 42 }" +console.log(BSON.deserialize(BSON.serialize(obj))); +``` diff --git a/ts-ticket-office-service/node_modules/bson/bower.json b/ts-ticket-office-service/node_modules/bson/bower.json index b32140ead..d5fc054ee 100644 --- a/ts-ticket-office-service/node_modules/bson/bower.json +++ b/ts-ticket-office-service/node_modules/bson/bower.json @@ -7,7 +7,7 @@ "parser" ], "author": "Christian Amor Kvalheim ", - "main": "./browser_build/bson.js", + "main": "./dist/bson.js", "license": "Apache-2.0", "moduleType": [ "globals", @@ -21,5 +21,6 @@ "node_modules", "test", "tools" - ] + ], + "version": "4.6.5" } diff --git a/ts-ticket-office-service/node_modules/bson/browser_build/bson.js b/ts-ticket-office-service/node_modules/bson/browser_build/bson.js deleted file mode 100644 index 6021fcadb..000000000 --- a/ts-ticket-office-service/node_modules/bson/browser_build/bson.js +++ /dev/null @@ -1,16734 +0,0 @@ -(function webpackUniversalModuleDefinition(root, factory) { - if(typeof exports === 'object' && typeof module === 'object') - module.exports = factory(); - else if(typeof define === 'function' && define.amd) - define([], factory); - else { - var a = factory(); - for(var i in a) (typeof exports === 'object' ? exports : root)[i] = a[i]; - } -})(this, function() { -return /******/ (function(modules) { // webpackBootstrap -/******/ // The module cache -/******/ var installedModules = {}; - -/******/ // The require function -/******/ function __webpack_require__(moduleId) { - -/******/ // Check if module is in cache -/******/ if(installedModules[moduleId]) -/******/ return installedModules[moduleId].exports; - -/******/ // Create a new module (and put it into the cache) -/******/ var module = installedModules[moduleId] = { -/******/ exports: {}, -/******/ id: moduleId, -/******/ loaded: false -/******/ }; - -/******/ // Execute the module function -/******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__); - -/******/ // Flag the module as loaded -/******/ module.loaded = true; - -/******/ // Return the exports of the module -/******/ return module.exports; -/******/ } - - -/******/ // expose the modules object (__webpack_modules__) -/******/ __webpack_require__.m = modules; - -/******/ // expose the module cache -/******/ __webpack_require__.c = installedModules; - -/******/ // __webpack_public_path__ -/******/ __webpack_require__.p = "/"; - -/******/ // Load entry module and return exports -/******/ return __webpack_require__(0); -/******/ }) -/************************************************************************/ -/******/ ([ -/* 0 */ -/***/ function(module, exports, __webpack_require__) { - - __webpack_require__(1); - module.exports = __webpack_require__(298); - - -/***/ }, -/* 1 */ -/***/ function(module, exports, __webpack_require__) { - - /* WEBPACK VAR INJECTION */(function(global) {"use strict"; - - __webpack_require__(2); - - __webpack_require__(293); - - __webpack_require__(295); - - if (global._babelPolyfill) { - throw new Error("only one instance of babel-polyfill is allowed"); - } - global._babelPolyfill = true; - - var DEFINE_PROPERTY = "defineProperty"; - function define(O, key, value) { - O[key] || Object[DEFINE_PROPERTY](O, key, { - writable: true, - configurable: true, - value: value - }); - } - - define(String.prototype, "padLeft", "".padStart); - define(String.prototype, "padRight", "".padEnd); - - "pop,reverse,shift,keys,values,entries,indexOf,every,some,forEach,map,filter,find,findIndex,includes,join,slice,concat,push,splice,unshift,sort,lastIndexOf,reduce,reduceRight,copyWithin,fill".split(",").forEach(function (key) { - [][key] && define(Array, key, Function.call.bind([][key])); - }); - /* WEBPACK VAR INJECTION */}.call(exports, (function() { return this; }()))) - -/***/ }, -/* 2 */ -/***/ function(module, exports, __webpack_require__) { - - __webpack_require__(3); - __webpack_require__(52); - __webpack_require__(53); - __webpack_require__(54); - __webpack_require__(55); - __webpack_require__(57); - __webpack_require__(60); - __webpack_require__(61); - __webpack_require__(62); - __webpack_require__(63); - __webpack_require__(64); - __webpack_require__(65); - __webpack_require__(66); - __webpack_require__(67); - __webpack_require__(68); - __webpack_require__(70); - __webpack_require__(72); - __webpack_require__(74); - __webpack_require__(76); - __webpack_require__(79); - __webpack_require__(80); - __webpack_require__(81); - __webpack_require__(85); - __webpack_require__(87); - __webpack_require__(89); - __webpack_require__(92); - __webpack_require__(93); - __webpack_require__(94); - __webpack_require__(95); - __webpack_require__(97); - __webpack_require__(98); - __webpack_require__(99); - __webpack_require__(100); - __webpack_require__(101); - __webpack_require__(102); - __webpack_require__(103); - __webpack_require__(105); - __webpack_require__(106); - __webpack_require__(107); - __webpack_require__(109); - __webpack_require__(110); - __webpack_require__(111); - __webpack_require__(113); - __webpack_require__(114); - __webpack_require__(115); - __webpack_require__(116); - __webpack_require__(117); - __webpack_require__(118); - __webpack_require__(119); - __webpack_require__(120); - __webpack_require__(121); - __webpack_require__(122); - __webpack_require__(123); - __webpack_require__(124); - __webpack_require__(125); - __webpack_require__(126); - __webpack_require__(131); - __webpack_require__(132); - __webpack_require__(136); - __webpack_require__(137); - __webpack_require__(138); - __webpack_require__(139); - __webpack_require__(141); - __webpack_require__(142); - __webpack_require__(143); - __webpack_require__(144); - __webpack_require__(145); - __webpack_require__(146); - __webpack_require__(147); - __webpack_require__(148); - __webpack_require__(149); - __webpack_require__(150); - __webpack_require__(151); - __webpack_require__(152); - __webpack_require__(153); - __webpack_require__(154); - __webpack_require__(155); - __webpack_require__(156); - __webpack_require__(157); - __webpack_require__(159); - __webpack_require__(160); - __webpack_require__(166); - __webpack_require__(167); - __webpack_require__(169); - __webpack_require__(170); - __webpack_require__(171); - __webpack_require__(175); - __webpack_require__(176); - __webpack_require__(177); - __webpack_require__(178); - __webpack_require__(179); - __webpack_require__(181); - __webpack_require__(182); - __webpack_require__(183); - __webpack_require__(184); - __webpack_require__(187); - __webpack_require__(189); - __webpack_require__(190); - __webpack_require__(191); - __webpack_require__(193); - __webpack_require__(195); - __webpack_require__(197); - __webpack_require__(198); - __webpack_require__(199); - __webpack_require__(201); - __webpack_require__(202); - __webpack_require__(203); - __webpack_require__(204); - __webpack_require__(211); - __webpack_require__(214); - __webpack_require__(215); - __webpack_require__(217); - __webpack_require__(218); - __webpack_require__(221); - __webpack_require__(222); - __webpack_require__(224); - __webpack_require__(225); - __webpack_require__(226); - __webpack_require__(227); - __webpack_require__(228); - __webpack_require__(229); - __webpack_require__(230); - __webpack_require__(231); - __webpack_require__(232); - __webpack_require__(233); - __webpack_require__(234); - __webpack_require__(235); - __webpack_require__(236); - __webpack_require__(237); - __webpack_require__(238); - __webpack_require__(239); - __webpack_require__(240); - __webpack_require__(241); - __webpack_require__(242); - __webpack_require__(244); - __webpack_require__(245); - __webpack_require__(246); - __webpack_require__(247); - __webpack_require__(248); - __webpack_require__(249); - __webpack_require__(251); - __webpack_require__(252); - __webpack_require__(253); - __webpack_require__(254); - __webpack_require__(255); - __webpack_require__(256); - __webpack_require__(257); - __webpack_require__(258); - __webpack_require__(260); - __webpack_require__(261); - __webpack_require__(263); - __webpack_require__(264); - __webpack_require__(265); - __webpack_require__(266); - __webpack_require__(269); - __webpack_require__(270); - __webpack_require__(271); - __webpack_require__(272); - __webpack_require__(273); - __webpack_require__(274); - __webpack_require__(275); - __webpack_require__(276); - __webpack_require__(278); - __webpack_require__(279); - __webpack_require__(280); - __webpack_require__(281); - __webpack_require__(282); - __webpack_require__(283); - __webpack_require__(284); - __webpack_require__(285); - __webpack_require__(286); - __webpack_require__(287); - __webpack_require__(288); - __webpack_require__(291); - __webpack_require__(292); - module.exports = __webpack_require__(9); - -/***/ }, -/* 3 */ -/***/ function(module, exports, __webpack_require__) { - - 'use strict'; - // ECMAScript 6 symbols shim - var global = __webpack_require__(4) - , has = __webpack_require__(5) - , DESCRIPTORS = __webpack_require__(6) - , $export = __webpack_require__(8) - , redefine = __webpack_require__(18) - , META = __webpack_require__(22).KEY - , $fails = __webpack_require__(7) - , shared = __webpack_require__(23) - , setToStringTag = __webpack_require__(24) - , uid = __webpack_require__(19) - , wks = __webpack_require__(25) - , wksExt = __webpack_require__(26) - , wksDefine = __webpack_require__(27) - , keyOf = __webpack_require__(29) - , enumKeys = __webpack_require__(42) - , isArray = __webpack_require__(45) - , anObject = __webpack_require__(12) - , toIObject = __webpack_require__(32) - , toPrimitive = __webpack_require__(16) - , createDesc = __webpack_require__(17) - , _create = __webpack_require__(46) - , gOPNExt = __webpack_require__(49) - , $GOPD = __webpack_require__(51) - , $DP = __webpack_require__(11) - , $keys = __webpack_require__(30) - , gOPD = $GOPD.f - , dP = $DP.f - , gOPN = gOPNExt.f - , $Symbol = global.Symbol - , $JSON = global.JSON - , _stringify = $JSON && $JSON.stringify - , PROTOTYPE = 'prototype' - , HIDDEN = wks('_hidden') - , TO_PRIMITIVE = wks('toPrimitive') - , isEnum = {}.propertyIsEnumerable - , SymbolRegistry = shared('symbol-registry') - , AllSymbols = shared('symbols') - , OPSymbols = shared('op-symbols') - , ObjectProto = Object[PROTOTYPE] - , USE_NATIVE = typeof $Symbol == 'function' - , QObject = global.QObject; - // Don't use setters in Qt Script, https://github.com/zloirock/core-js/issues/173 - var setter = !QObject || !QObject[PROTOTYPE] || !QObject[PROTOTYPE].findChild; - - // fallback for old Android, https://code.google.com/p/v8/issues/detail?id=687 - var setSymbolDesc = DESCRIPTORS && $fails(function(){ - return _create(dP({}, 'a', { - get: function(){ return dP(this, 'a', {value: 7}).a; } - })).a != 7; - }) ? function(it, key, D){ - var protoDesc = gOPD(ObjectProto, key); - if(protoDesc)delete ObjectProto[key]; - dP(it, key, D); - if(protoDesc && it !== ObjectProto)dP(ObjectProto, key, protoDesc); - } : dP; - - var wrap = function(tag){ - var sym = AllSymbols[tag] = _create($Symbol[PROTOTYPE]); - sym._k = tag; - return sym; - }; - - var isSymbol = USE_NATIVE && typeof $Symbol.iterator == 'symbol' ? function(it){ - return typeof it == 'symbol'; - } : function(it){ - return it instanceof $Symbol; - }; - - var $defineProperty = function defineProperty(it, key, D){ - if(it === ObjectProto)$defineProperty(OPSymbols, key, D); - anObject(it); - key = toPrimitive(key, true); - anObject(D); - if(has(AllSymbols, key)){ - if(!D.enumerable){ - if(!has(it, HIDDEN))dP(it, HIDDEN, createDesc(1, {})); - it[HIDDEN][key] = true; - } else { - if(has(it, HIDDEN) && it[HIDDEN][key])it[HIDDEN][key] = false; - D = _create(D, {enumerable: createDesc(0, false)}); - } return setSymbolDesc(it, key, D); - } return dP(it, key, D); - }; - var $defineProperties = function defineProperties(it, P){ - anObject(it); - var keys = enumKeys(P = toIObject(P)) - , i = 0 - , l = keys.length - , key; - while(l > i)$defineProperty(it, key = keys[i++], P[key]); - return it; - }; - var $create = function create(it, P){ - return P === undefined ? _create(it) : $defineProperties(_create(it), P); - }; - var $propertyIsEnumerable = function propertyIsEnumerable(key){ - var E = isEnum.call(this, key = toPrimitive(key, true)); - if(this === ObjectProto && has(AllSymbols, key) && !has(OPSymbols, key))return false; - return E || !has(this, key) || !has(AllSymbols, key) || has(this, HIDDEN) && this[HIDDEN][key] ? E : true; - }; - var $getOwnPropertyDescriptor = function getOwnPropertyDescriptor(it, key){ - it = toIObject(it); - key = toPrimitive(key, true); - if(it === ObjectProto && has(AllSymbols, key) && !has(OPSymbols, key))return; - var D = gOPD(it, key); - if(D && has(AllSymbols, key) && !(has(it, HIDDEN) && it[HIDDEN][key]))D.enumerable = true; - return D; - }; - var $getOwnPropertyNames = function getOwnPropertyNames(it){ - var names = gOPN(toIObject(it)) - , result = [] - , i = 0 - , key; - while(names.length > i){ - if(!has(AllSymbols, key = names[i++]) && key != HIDDEN && key != META)result.push(key); - } return result; - }; - var $getOwnPropertySymbols = function getOwnPropertySymbols(it){ - var IS_OP = it === ObjectProto - , names = gOPN(IS_OP ? OPSymbols : toIObject(it)) - , result = [] - , i = 0 - , key; - while(names.length > i){ - if(has(AllSymbols, key = names[i++]) && (IS_OP ? has(ObjectProto, key) : true))result.push(AllSymbols[key]); - } return result; - }; - - // 19.4.1.1 Symbol([description]) - if(!USE_NATIVE){ - $Symbol = function Symbol(){ - if(this instanceof $Symbol)throw TypeError('Symbol is not a constructor!'); - var tag = uid(arguments.length > 0 ? arguments[0] : undefined); - var $set = function(value){ - if(this === ObjectProto)$set.call(OPSymbols, value); - if(has(this, HIDDEN) && has(this[HIDDEN], tag))this[HIDDEN][tag] = false; - setSymbolDesc(this, tag, createDesc(1, value)); - }; - if(DESCRIPTORS && setter)setSymbolDesc(ObjectProto, tag, {configurable: true, set: $set}); - return wrap(tag); - }; - redefine($Symbol[PROTOTYPE], 'toString', function toString(){ - return this._k; - }); - - $GOPD.f = $getOwnPropertyDescriptor; - $DP.f = $defineProperty; - __webpack_require__(50).f = gOPNExt.f = $getOwnPropertyNames; - __webpack_require__(44).f = $propertyIsEnumerable; - __webpack_require__(43).f = $getOwnPropertySymbols; - - if(DESCRIPTORS && !__webpack_require__(28)){ - redefine(ObjectProto, 'propertyIsEnumerable', $propertyIsEnumerable, true); - } - - wksExt.f = function(name){ - return wrap(wks(name)); - } - } - - $export($export.G + $export.W + $export.F * !USE_NATIVE, {Symbol: $Symbol}); - - for(var symbols = ( - // 19.4.2.2, 19.4.2.3, 19.4.2.4, 19.4.2.6, 19.4.2.8, 19.4.2.9, 19.4.2.10, 19.4.2.11, 19.4.2.12, 19.4.2.13, 19.4.2.14 - 'hasInstance,isConcatSpreadable,iterator,match,replace,search,species,split,toPrimitive,toStringTag,unscopables' - ).split(','), i = 0; symbols.length > i; )wks(symbols[i++]); - - for(var symbols = $keys(wks.store), i = 0; symbols.length > i; )wksDefine(symbols[i++]); - - $export($export.S + $export.F * !USE_NATIVE, 'Symbol', { - // 19.4.2.1 Symbol.for(key) - 'for': function(key){ - return has(SymbolRegistry, key += '') - ? SymbolRegistry[key] - : SymbolRegistry[key] = $Symbol(key); - }, - // 19.4.2.5 Symbol.keyFor(sym) - keyFor: function keyFor(key){ - if(isSymbol(key))return keyOf(SymbolRegistry, key); - throw TypeError(key + ' is not a symbol!'); - }, - useSetter: function(){ setter = true; }, - useSimple: function(){ setter = false; } - }); - - $export($export.S + $export.F * !USE_NATIVE, 'Object', { - // 19.1.2.2 Object.create(O [, Properties]) - create: $create, - // 19.1.2.4 Object.defineProperty(O, P, Attributes) - defineProperty: $defineProperty, - // 19.1.2.3 Object.defineProperties(O, Properties) - defineProperties: $defineProperties, - // 19.1.2.6 Object.getOwnPropertyDescriptor(O, P) - getOwnPropertyDescriptor: $getOwnPropertyDescriptor, - // 19.1.2.7 Object.getOwnPropertyNames(O) - getOwnPropertyNames: $getOwnPropertyNames, - // 19.1.2.8 Object.getOwnPropertySymbols(O) - getOwnPropertySymbols: $getOwnPropertySymbols - }); - - // 24.3.2 JSON.stringify(value [, replacer [, space]]) - $JSON && $export($export.S + $export.F * (!USE_NATIVE || $fails(function(){ - var S = $Symbol(); - // MS Edge converts symbol values to JSON as {} - // WebKit converts symbol values to JSON as null - // V8 throws on boxed symbols - return _stringify([S]) != '[null]' || _stringify({a: S}) != '{}' || _stringify(Object(S)) != '{}'; - })), 'JSON', { - stringify: function stringify(it){ - if(it === undefined || isSymbol(it))return; // IE8 returns string on undefined - var args = [it] - , i = 1 - , replacer, $replacer; - while(arguments.length > i)args.push(arguments[i++]); - replacer = args[1]; - if(typeof replacer == 'function')$replacer = replacer; - if($replacer || !isArray(replacer))replacer = function(key, value){ - if($replacer)value = $replacer.call(this, key, value); - if(!isSymbol(value))return value; - }; - args[1] = replacer; - return _stringify.apply($JSON, args); - } - }); - - // 19.4.3.4 Symbol.prototype[@@toPrimitive](hint) - $Symbol[PROTOTYPE][TO_PRIMITIVE] || __webpack_require__(10)($Symbol[PROTOTYPE], TO_PRIMITIVE, $Symbol[PROTOTYPE].valueOf); - // 19.4.3.5 Symbol.prototype[@@toStringTag] - setToStringTag($Symbol, 'Symbol'); - // 20.2.1.9 Math[@@toStringTag] - setToStringTag(Math, 'Math', true); - // 24.3.3 JSON[@@toStringTag] - setToStringTag(global.JSON, 'JSON', true); - -/***/ }, -/* 4 */ -/***/ function(module, exports) { - - // https://github.com/zloirock/core-js/issues/86#issuecomment-115759028 - var global = module.exports = typeof window != 'undefined' && window.Math == Math - ? window : typeof self != 'undefined' && self.Math == Math ? self : Function('return this')(); - if(typeof __g == 'number')__g = global; // eslint-disable-line no-undef - -/***/ }, -/* 5 */ -/***/ function(module, exports) { - - var hasOwnProperty = {}.hasOwnProperty; - module.exports = function(it, key){ - return hasOwnProperty.call(it, key); - }; - -/***/ }, -/* 6 */ -/***/ function(module, exports, __webpack_require__) { - - // Thank's IE8 for his funny defineProperty - module.exports = !__webpack_require__(7)(function(){ - return Object.defineProperty({}, 'a', {get: function(){ return 7; }}).a != 7; - }); - -/***/ }, -/* 7 */ -/***/ function(module, exports) { - - module.exports = function(exec){ - try { - return !!exec(); - } catch(e){ - return true; - } - }; - -/***/ }, -/* 8 */ -/***/ function(module, exports, __webpack_require__) { - - var global = __webpack_require__(4) - , core = __webpack_require__(9) - , hide = __webpack_require__(10) - , redefine = __webpack_require__(18) - , ctx = __webpack_require__(20) - , PROTOTYPE = 'prototype'; - - var $export = function(type, name, source){ - var IS_FORCED = type & $export.F - , IS_GLOBAL = type & $export.G - , IS_STATIC = type & $export.S - , IS_PROTO = type & $export.P - , IS_BIND = type & $export.B - , target = IS_GLOBAL ? global : IS_STATIC ? global[name] || (global[name] = {}) : (global[name] || {})[PROTOTYPE] - , exports = IS_GLOBAL ? core : core[name] || (core[name] = {}) - , expProto = exports[PROTOTYPE] || (exports[PROTOTYPE] = {}) - , key, own, out, exp; - if(IS_GLOBAL)source = name; - for(key in source){ - // contains in native - own = !IS_FORCED && target && target[key] !== undefined; - // export native or passed - out = (own ? target : source)[key]; - // bind timers to global for call from export context - exp = IS_BIND && own ? ctx(out, global) : IS_PROTO && typeof out == 'function' ? ctx(Function.call, out) : out; - // extend global - if(target)redefine(target, key, out, type & $export.U); - // export - if(exports[key] != out)hide(exports, key, exp); - if(IS_PROTO && expProto[key] != out)expProto[key] = out; - } - }; - global.core = core; - // type bitmap - $export.F = 1; // forced - $export.G = 2; // global - $export.S = 4; // static - $export.P = 8; // proto - $export.B = 16; // bind - $export.W = 32; // wrap - $export.U = 64; // safe - $export.R = 128; // real proto method for `library` - module.exports = $export; - -/***/ }, -/* 9 */ -/***/ function(module, exports) { - - var core = module.exports = {version: '2.4.0'}; - if(typeof __e == 'number')__e = core; // eslint-disable-line no-undef - -/***/ }, -/* 10 */ -/***/ function(module, exports, __webpack_require__) { - - var dP = __webpack_require__(11) - , createDesc = __webpack_require__(17); - module.exports = __webpack_require__(6) ? function(object, key, value){ - return dP.f(object, key, createDesc(1, value)); - } : function(object, key, value){ - object[key] = value; - return object; - }; - -/***/ }, -/* 11 */ -/***/ function(module, exports, __webpack_require__) { - - var anObject = __webpack_require__(12) - , IE8_DOM_DEFINE = __webpack_require__(14) - , toPrimitive = __webpack_require__(16) - , dP = Object.defineProperty; - - exports.f = __webpack_require__(6) ? Object.defineProperty : function defineProperty(O, P, Attributes){ - anObject(O); - P = toPrimitive(P, true); - anObject(Attributes); - if(IE8_DOM_DEFINE)try { - return dP(O, P, Attributes); - } catch(e){ /* empty */ } - if('get' in Attributes || 'set' in Attributes)throw TypeError('Accessors not supported!'); - if('value' in Attributes)O[P] = Attributes.value; - return O; - }; - -/***/ }, -/* 12 */ -/***/ function(module, exports, __webpack_require__) { - - var isObject = __webpack_require__(13); - module.exports = function(it){ - if(!isObject(it))throw TypeError(it + ' is not an object!'); - return it; - }; - -/***/ }, -/* 13 */ -/***/ function(module, exports) { - - module.exports = function(it){ - return typeof it === 'object' ? it !== null : typeof it === 'function'; - }; - -/***/ }, -/* 14 */ -/***/ function(module, exports, __webpack_require__) { - - module.exports = !__webpack_require__(6) && !__webpack_require__(7)(function(){ - return Object.defineProperty(__webpack_require__(15)('div'), 'a', {get: function(){ return 7; }}).a != 7; - }); - -/***/ }, -/* 15 */ -/***/ function(module, exports, __webpack_require__) { - - var isObject = __webpack_require__(13) - , document = __webpack_require__(4).document - // in old IE typeof document.createElement is 'object' - , is = isObject(document) && isObject(document.createElement); - module.exports = function(it){ - return is ? document.createElement(it) : {}; - }; - -/***/ }, -/* 16 */ -/***/ function(module, exports, __webpack_require__) { - - // 7.1.1 ToPrimitive(input [, PreferredType]) - var isObject = __webpack_require__(13); - // instead of the ES6 spec version, we didn't implement @@toPrimitive case - // and the second argument - flag - preferred type is a string - module.exports = function(it, S){ - if(!isObject(it))return it; - var fn, val; - if(S && typeof (fn = it.toString) == 'function' && !isObject(val = fn.call(it)))return val; - if(typeof (fn = it.valueOf) == 'function' && !isObject(val = fn.call(it)))return val; - if(!S && typeof (fn = it.toString) == 'function' && !isObject(val = fn.call(it)))return val; - throw TypeError("Can't convert object to primitive value"); - }; - -/***/ }, -/* 17 */ -/***/ function(module, exports) { - - module.exports = function(bitmap, value){ - return { - enumerable : !(bitmap & 1), - configurable: !(bitmap & 2), - writable : !(bitmap & 4), - value : value - }; - }; - -/***/ }, -/* 18 */ -/***/ function(module, exports, __webpack_require__) { - - var global = __webpack_require__(4) - , hide = __webpack_require__(10) - , has = __webpack_require__(5) - , SRC = __webpack_require__(19)('src') - , TO_STRING = 'toString' - , $toString = Function[TO_STRING] - , TPL = ('' + $toString).split(TO_STRING); - - __webpack_require__(9).inspectSource = function(it){ - return $toString.call(it); - }; - - (module.exports = function(O, key, val, safe){ - var isFunction = typeof val == 'function'; - if(isFunction)has(val, 'name') || hide(val, 'name', key); - if(O[key] === val)return; - if(isFunction)has(val, SRC) || hide(val, SRC, O[key] ? '' + O[key] : TPL.join(String(key))); - if(O === global){ - O[key] = val; - } else { - if(!safe){ - delete O[key]; - hide(O, key, val); - } else { - if(O[key])O[key] = val; - else hide(O, key, val); - } - } - // add fake Function#toString for correct work wrapped methods / constructors with methods like LoDash isNative - })(Function.prototype, TO_STRING, function toString(){ - return typeof this == 'function' && this[SRC] || $toString.call(this); - }); - -/***/ }, -/* 19 */ -/***/ function(module, exports) { - - var id = 0 - , px = Math.random(); - module.exports = function(key){ - return 'Symbol('.concat(key === undefined ? '' : key, ')_', (++id + px).toString(36)); - }; - -/***/ }, -/* 20 */ -/***/ function(module, exports, __webpack_require__) { - - // optional / simple context binding - var aFunction = __webpack_require__(21); - module.exports = function(fn, that, length){ - aFunction(fn); - if(that === undefined)return fn; - switch(length){ - case 1: return function(a){ - return fn.call(that, a); - }; - case 2: return function(a, b){ - return fn.call(that, a, b); - }; - case 3: return function(a, b, c){ - return fn.call(that, a, b, c); - }; - } - return function(/* ...args */){ - return fn.apply(that, arguments); - }; - }; - -/***/ }, -/* 21 */ -/***/ function(module, exports) { - - module.exports = function(it){ - if(typeof it != 'function')throw TypeError(it + ' is not a function!'); - return it; - }; - -/***/ }, -/* 22 */ -/***/ function(module, exports, __webpack_require__) { - - var META = __webpack_require__(19)('meta') - , isObject = __webpack_require__(13) - , has = __webpack_require__(5) - , setDesc = __webpack_require__(11).f - , id = 0; - var isExtensible = Object.isExtensible || function(){ - return true; - }; - var FREEZE = !__webpack_require__(7)(function(){ - return isExtensible(Object.preventExtensions({})); - }); - var setMeta = function(it){ - setDesc(it, META, {value: { - i: 'O' + ++id, // object ID - w: {} // weak collections IDs - }}); - }; - var fastKey = function(it, create){ - // return primitive with prefix - if(!isObject(it))return typeof it == 'symbol' ? it : (typeof it == 'string' ? 'S' : 'P') + it; - if(!has(it, META)){ - // can't set metadata to uncaught frozen object - if(!isExtensible(it))return 'F'; - // not necessary to add metadata - if(!create)return 'E'; - // add missing metadata - setMeta(it); - // return object ID - } return it[META].i; - }; - var getWeak = function(it, create){ - if(!has(it, META)){ - // can't set metadata to uncaught frozen object - if(!isExtensible(it))return true; - // not necessary to add metadata - if(!create)return false; - // add missing metadata - setMeta(it); - // return hash weak collections IDs - } return it[META].w; - }; - // add metadata on freeze-family methods calling - var onFreeze = function(it){ - if(FREEZE && meta.NEED && isExtensible(it) && !has(it, META))setMeta(it); - return it; - }; - var meta = module.exports = { - KEY: META, - NEED: false, - fastKey: fastKey, - getWeak: getWeak, - onFreeze: onFreeze - }; - -/***/ }, -/* 23 */ -/***/ function(module, exports, __webpack_require__) { - - var global = __webpack_require__(4) - , SHARED = '__core-js_shared__' - , store = global[SHARED] || (global[SHARED] = {}); - module.exports = function(key){ - return store[key] || (store[key] = {}); - }; - -/***/ }, -/* 24 */ -/***/ function(module, exports, __webpack_require__) { - - var def = __webpack_require__(11).f - , has = __webpack_require__(5) - , TAG = __webpack_require__(25)('toStringTag'); - - module.exports = function(it, tag, stat){ - if(it && !has(it = stat ? it : it.prototype, TAG))def(it, TAG, {configurable: true, value: tag}); - }; - -/***/ }, -/* 25 */ -/***/ function(module, exports, __webpack_require__) { - - var store = __webpack_require__(23)('wks') - , uid = __webpack_require__(19) - , Symbol = __webpack_require__(4).Symbol - , USE_SYMBOL = typeof Symbol == 'function'; - - var $exports = module.exports = function(name){ - return store[name] || (store[name] = - USE_SYMBOL && Symbol[name] || (USE_SYMBOL ? Symbol : uid)('Symbol.' + name)); - }; - - $exports.store = store; - -/***/ }, -/* 26 */ -/***/ function(module, exports, __webpack_require__) { - - exports.f = __webpack_require__(25); - -/***/ }, -/* 27 */ -/***/ function(module, exports, __webpack_require__) { - - var global = __webpack_require__(4) - , core = __webpack_require__(9) - , LIBRARY = __webpack_require__(28) - , wksExt = __webpack_require__(26) - , defineProperty = __webpack_require__(11).f; - module.exports = function(name){ - var $Symbol = core.Symbol || (core.Symbol = LIBRARY ? {} : global.Symbol || {}); - if(name.charAt(0) != '_' && !(name in $Symbol))defineProperty($Symbol, name, {value: wksExt.f(name)}); - }; - -/***/ }, -/* 28 */ -/***/ function(module, exports) { - - module.exports = false; - -/***/ }, -/* 29 */ -/***/ function(module, exports, __webpack_require__) { - - var getKeys = __webpack_require__(30) - , toIObject = __webpack_require__(32); - module.exports = function(object, el){ - var O = toIObject(object) - , keys = getKeys(O) - , length = keys.length - , index = 0 - , key; - while(length > index)if(O[key = keys[index++]] === el)return key; - }; - -/***/ }, -/* 30 */ -/***/ function(module, exports, __webpack_require__) { - - // 19.1.2.14 / 15.2.3.14 Object.keys(O) - var $keys = __webpack_require__(31) - , enumBugKeys = __webpack_require__(41); - - module.exports = Object.keys || function keys(O){ - return $keys(O, enumBugKeys); - }; - -/***/ }, -/* 31 */ -/***/ function(module, exports, __webpack_require__) { - - var has = __webpack_require__(5) - , toIObject = __webpack_require__(32) - , arrayIndexOf = __webpack_require__(36)(false) - , IE_PROTO = __webpack_require__(40)('IE_PROTO'); - - module.exports = function(object, names){ - var O = toIObject(object) - , i = 0 - , result = [] - , key; - for(key in O)if(key != IE_PROTO)has(O, key) && result.push(key); - // Don't enum bug & hidden keys - while(names.length > i)if(has(O, key = names[i++])){ - ~arrayIndexOf(result, key) || result.push(key); - } - return result; - }; - -/***/ }, -/* 32 */ -/***/ function(module, exports, __webpack_require__) { - - // to indexed object, toObject with fallback for non-array-like ES3 strings - var IObject = __webpack_require__(33) - , defined = __webpack_require__(35); - module.exports = function(it){ - return IObject(defined(it)); - }; - -/***/ }, -/* 33 */ -/***/ function(module, exports, __webpack_require__) { - - // fallback for non-array-like ES3 and non-enumerable old V8 strings - var cof = __webpack_require__(34); - module.exports = Object('z').propertyIsEnumerable(0) ? Object : function(it){ - return cof(it) == 'String' ? it.split('') : Object(it); - }; - -/***/ }, -/* 34 */ -/***/ function(module, exports) { - - var toString = {}.toString; - - module.exports = function(it){ - return toString.call(it).slice(8, -1); - }; - -/***/ }, -/* 35 */ -/***/ function(module, exports) { - - // 7.2.1 RequireObjectCoercible(argument) - module.exports = function(it){ - if(it == undefined)throw TypeError("Can't call method on " + it); - return it; - }; - -/***/ }, -/* 36 */ -/***/ function(module, exports, __webpack_require__) { - - // false -> Array#indexOf - // true -> Array#includes - var toIObject = __webpack_require__(32) - , toLength = __webpack_require__(37) - , toIndex = __webpack_require__(39); - module.exports = function(IS_INCLUDES){ - return function($this, el, fromIndex){ - var O = toIObject($this) - , length = toLength(O.length) - , index = toIndex(fromIndex, length) - , value; - // Array#includes uses SameValueZero equality algorithm - if(IS_INCLUDES && el != el)while(length > index){ - value = O[index++]; - if(value != value)return true; - // Array#toIndex ignores holes, Array#includes - not - } else for(;length > index; index++)if(IS_INCLUDES || index in O){ - if(O[index] === el)return IS_INCLUDES || index || 0; - } return !IS_INCLUDES && -1; - }; - }; - -/***/ }, -/* 37 */ -/***/ function(module, exports, __webpack_require__) { - - // 7.1.15 ToLength - var toInteger = __webpack_require__(38) - , min = Math.min; - module.exports = function(it){ - return it > 0 ? min(toInteger(it), 0x1fffffffffffff) : 0; // pow(2, 53) - 1 == 9007199254740991 - }; - -/***/ }, -/* 38 */ -/***/ function(module, exports) { - - // 7.1.4 ToInteger - var ceil = Math.ceil - , floor = Math.floor; - module.exports = function(it){ - return isNaN(it = +it) ? 0 : (it > 0 ? floor : ceil)(it); - }; - -/***/ }, -/* 39 */ -/***/ function(module, exports, __webpack_require__) { - - var toInteger = __webpack_require__(38) - , max = Math.max - , min = Math.min; - module.exports = function(index, length){ - index = toInteger(index); - return index < 0 ? max(index + length, 0) : min(index, length); - }; - -/***/ }, -/* 40 */ -/***/ function(module, exports, __webpack_require__) { - - var shared = __webpack_require__(23)('keys') - , uid = __webpack_require__(19); - module.exports = function(key){ - return shared[key] || (shared[key] = uid(key)); - }; - -/***/ }, -/* 41 */ -/***/ function(module, exports) { - - // IE 8- don't enum bug keys - module.exports = ( - 'constructor,hasOwnProperty,isPrototypeOf,propertyIsEnumerable,toLocaleString,toString,valueOf' - ).split(','); - -/***/ }, -/* 42 */ -/***/ function(module, exports, __webpack_require__) { - - // all enumerable object keys, includes symbols - var getKeys = __webpack_require__(30) - , gOPS = __webpack_require__(43) - , pIE = __webpack_require__(44); - module.exports = function(it){ - var result = getKeys(it) - , getSymbols = gOPS.f; - if(getSymbols){ - var symbols = getSymbols(it) - , isEnum = pIE.f - , i = 0 - , key; - while(symbols.length > i)if(isEnum.call(it, key = symbols[i++]))result.push(key); - } return result; - }; - -/***/ }, -/* 43 */ -/***/ function(module, exports) { - - exports.f = Object.getOwnPropertySymbols; - -/***/ }, -/* 44 */ -/***/ function(module, exports) { - - exports.f = {}.propertyIsEnumerable; - -/***/ }, -/* 45 */ -/***/ function(module, exports, __webpack_require__) { - - // 7.2.2 IsArray(argument) - var cof = __webpack_require__(34); - module.exports = Array.isArray || function isArray(arg){ - return cof(arg) == 'Array'; - }; - -/***/ }, -/* 46 */ -/***/ function(module, exports, __webpack_require__) { - - // 19.1.2.2 / 15.2.3.5 Object.create(O [, Properties]) - var anObject = __webpack_require__(12) - , dPs = __webpack_require__(47) - , enumBugKeys = __webpack_require__(41) - , IE_PROTO = __webpack_require__(40)('IE_PROTO') - , Empty = function(){ /* empty */ } - , PROTOTYPE = 'prototype'; - - // Create object with fake `null` prototype: use iframe Object with cleared prototype - var createDict = function(){ - // Thrash, waste and sodomy: IE GC bug - var iframe = __webpack_require__(15)('iframe') - , i = enumBugKeys.length - , lt = '<' - , gt = '>' - , iframeDocument; - iframe.style.display = 'none'; - __webpack_require__(48).appendChild(iframe); - iframe.src = 'javascript:'; // eslint-disable-line no-script-url - // createDict = iframe.contentWindow.Object; - // html.removeChild(iframe); - iframeDocument = iframe.contentWindow.document; - iframeDocument.open(); - iframeDocument.write(lt + 'script' + gt + 'document.F=Object' + lt + '/script' + gt); - iframeDocument.close(); - createDict = iframeDocument.F; - while(i--)delete createDict[PROTOTYPE][enumBugKeys[i]]; - return createDict(); - }; - - module.exports = Object.create || function create(O, Properties){ - var result; - if(O !== null){ - Empty[PROTOTYPE] = anObject(O); - result = new Empty; - Empty[PROTOTYPE] = null; - // add "__proto__" for Object.getPrototypeOf polyfill - result[IE_PROTO] = O; - } else result = createDict(); - return Properties === undefined ? result : dPs(result, Properties); - }; - - -/***/ }, -/* 47 */ -/***/ function(module, exports, __webpack_require__) { - - var dP = __webpack_require__(11) - , anObject = __webpack_require__(12) - , getKeys = __webpack_require__(30); - - module.exports = __webpack_require__(6) ? Object.defineProperties : function defineProperties(O, Properties){ - anObject(O); - var keys = getKeys(Properties) - , length = keys.length - , i = 0 - , P; - while(length > i)dP.f(O, P = keys[i++], Properties[P]); - return O; - }; - -/***/ }, -/* 48 */ -/***/ function(module, exports, __webpack_require__) { - - module.exports = __webpack_require__(4).document && document.documentElement; - -/***/ }, -/* 49 */ -/***/ function(module, exports, __webpack_require__) { - - // fallback for IE11 buggy Object.getOwnPropertyNames with iframe and window - var toIObject = __webpack_require__(32) - , gOPN = __webpack_require__(50).f - , toString = {}.toString; - - var windowNames = typeof window == 'object' && window && Object.getOwnPropertyNames - ? Object.getOwnPropertyNames(window) : []; - - var getWindowNames = function(it){ - try { - return gOPN(it); - } catch(e){ - return windowNames.slice(); - } - }; - - module.exports.f = function getOwnPropertyNames(it){ - return windowNames && toString.call(it) == '[object Window]' ? getWindowNames(it) : gOPN(toIObject(it)); - }; - - -/***/ }, -/* 50 */ -/***/ function(module, exports, __webpack_require__) { - - // 19.1.2.7 / 15.2.3.4 Object.getOwnPropertyNames(O) - var $keys = __webpack_require__(31) - , hiddenKeys = __webpack_require__(41).concat('length', 'prototype'); - - exports.f = Object.getOwnPropertyNames || function getOwnPropertyNames(O){ - return $keys(O, hiddenKeys); - }; - -/***/ }, -/* 51 */ -/***/ function(module, exports, __webpack_require__) { - - var pIE = __webpack_require__(44) - , createDesc = __webpack_require__(17) - , toIObject = __webpack_require__(32) - , toPrimitive = __webpack_require__(16) - , has = __webpack_require__(5) - , IE8_DOM_DEFINE = __webpack_require__(14) - , gOPD = Object.getOwnPropertyDescriptor; - - exports.f = __webpack_require__(6) ? gOPD : function getOwnPropertyDescriptor(O, P){ - O = toIObject(O); - P = toPrimitive(P, true); - if(IE8_DOM_DEFINE)try { - return gOPD(O, P); - } catch(e){ /* empty */ } - if(has(O, P))return createDesc(!pIE.f.call(O, P), O[P]); - }; - -/***/ }, -/* 52 */ -/***/ function(module, exports, __webpack_require__) { - - var $export = __webpack_require__(8) - // 19.1.2.2 / 15.2.3.5 Object.create(O [, Properties]) - $export($export.S, 'Object', {create: __webpack_require__(46)}); - -/***/ }, -/* 53 */ -/***/ function(module, exports, __webpack_require__) { - - var $export = __webpack_require__(8); - // 19.1.2.4 / 15.2.3.6 Object.defineProperty(O, P, Attributes) - $export($export.S + $export.F * !__webpack_require__(6), 'Object', {defineProperty: __webpack_require__(11).f}); - -/***/ }, -/* 54 */ -/***/ function(module, exports, __webpack_require__) { - - var $export = __webpack_require__(8); - // 19.1.2.3 / 15.2.3.7 Object.defineProperties(O, Properties) - $export($export.S + $export.F * !__webpack_require__(6), 'Object', {defineProperties: __webpack_require__(47)}); - -/***/ }, -/* 55 */ -/***/ function(module, exports, __webpack_require__) { - - // 19.1.2.6 Object.getOwnPropertyDescriptor(O, P) - var toIObject = __webpack_require__(32) - , $getOwnPropertyDescriptor = __webpack_require__(51).f; - - __webpack_require__(56)('getOwnPropertyDescriptor', function(){ - return function getOwnPropertyDescriptor(it, key){ - return $getOwnPropertyDescriptor(toIObject(it), key); - }; - }); - -/***/ }, -/* 56 */ -/***/ function(module, exports, __webpack_require__) { - - // most Object methods by ES6 should accept primitives - var $export = __webpack_require__(8) - , core = __webpack_require__(9) - , fails = __webpack_require__(7); - module.exports = function(KEY, exec){ - var fn = (core.Object || {})[KEY] || Object[KEY] - , exp = {}; - exp[KEY] = exec(fn); - $export($export.S + $export.F * fails(function(){ fn(1); }), 'Object', exp); - }; - -/***/ }, -/* 57 */ -/***/ function(module, exports, __webpack_require__) { - - // 19.1.2.9 Object.getPrototypeOf(O) - var toObject = __webpack_require__(58) - , $getPrototypeOf = __webpack_require__(59); - - __webpack_require__(56)('getPrototypeOf', function(){ - return function getPrototypeOf(it){ - return $getPrototypeOf(toObject(it)); - }; - }); - -/***/ }, -/* 58 */ -/***/ function(module, exports, __webpack_require__) { - - // 7.1.13 ToObject(argument) - var defined = __webpack_require__(35); - module.exports = function(it){ - return Object(defined(it)); - }; - -/***/ }, -/* 59 */ -/***/ function(module, exports, __webpack_require__) { - - // 19.1.2.9 / 15.2.3.2 Object.getPrototypeOf(O) - var has = __webpack_require__(5) - , toObject = __webpack_require__(58) - , IE_PROTO = __webpack_require__(40)('IE_PROTO') - , ObjectProto = Object.prototype; - - module.exports = Object.getPrototypeOf || function(O){ - O = toObject(O); - if(has(O, IE_PROTO))return O[IE_PROTO]; - if(typeof O.constructor == 'function' && O instanceof O.constructor){ - return O.constructor.prototype; - } return O instanceof Object ? ObjectProto : null; - }; - -/***/ }, -/* 60 */ -/***/ function(module, exports, __webpack_require__) { - - // 19.1.2.14 Object.keys(O) - var toObject = __webpack_require__(58) - , $keys = __webpack_require__(30); - - __webpack_require__(56)('keys', function(){ - return function keys(it){ - return $keys(toObject(it)); - }; - }); - -/***/ }, -/* 61 */ -/***/ function(module, exports, __webpack_require__) { - - // 19.1.2.7 Object.getOwnPropertyNames(O) - __webpack_require__(56)('getOwnPropertyNames', function(){ - return __webpack_require__(49).f; - }); - -/***/ }, -/* 62 */ -/***/ function(module, exports, __webpack_require__) { - - // 19.1.2.5 Object.freeze(O) - var isObject = __webpack_require__(13) - , meta = __webpack_require__(22).onFreeze; - - __webpack_require__(56)('freeze', function($freeze){ - return function freeze(it){ - return $freeze && isObject(it) ? $freeze(meta(it)) : it; - }; - }); - -/***/ }, -/* 63 */ -/***/ function(module, exports, __webpack_require__) { - - // 19.1.2.17 Object.seal(O) - var isObject = __webpack_require__(13) - , meta = __webpack_require__(22).onFreeze; - - __webpack_require__(56)('seal', function($seal){ - return function seal(it){ - return $seal && isObject(it) ? $seal(meta(it)) : it; - }; - }); - -/***/ }, -/* 64 */ -/***/ function(module, exports, __webpack_require__) { - - // 19.1.2.15 Object.preventExtensions(O) - var isObject = __webpack_require__(13) - , meta = __webpack_require__(22).onFreeze; - - __webpack_require__(56)('preventExtensions', function($preventExtensions){ - return function preventExtensions(it){ - return $preventExtensions && isObject(it) ? $preventExtensions(meta(it)) : it; - }; - }); - -/***/ }, -/* 65 */ -/***/ function(module, exports, __webpack_require__) { - - // 19.1.2.12 Object.isFrozen(O) - var isObject = __webpack_require__(13); - - __webpack_require__(56)('isFrozen', function($isFrozen){ - return function isFrozen(it){ - return isObject(it) ? $isFrozen ? $isFrozen(it) : false : true; - }; - }); - -/***/ }, -/* 66 */ -/***/ function(module, exports, __webpack_require__) { - - // 19.1.2.13 Object.isSealed(O) - var isObject = __webpack_require__(13); - - __webpack_require__(56)('isSealed', function($isSealed){ - return function isSealed(it){ - return isObject(it) ? $isSealed ? $isSealed(it) : false : true; - }; - }); - -/***/ }, -/* 67 */ -/***/ function(module, exports, __webpack_require__) { - - // 19.1.2.11 Object.isExtensible(O) - var isObject = __webpack_require__(13); - - __webpack_require__(56)('isExtensible', function($isExtensible){ - return function isExtensible(it){ - return isObject(it) ? $isExtensible ? $isExtensible(it) : true : false; - }; - }); - -/***/ }, -/* 68 */ -/***/ function(module, exports, __webpack_require__) { - - // 19.1.3.1 Object.assign(target, source) - var $export = __webpack_require__(8); - - $export($export.S + $export.F, 'Object', {assign: __webpack_require__(69)}); - -/***/ }, -/* 69 */ -/***/ function(module, exports, __webpack_require__) { - - 'use strict'; - // 19.1.2.1 Object.assign(target, source, ...) - var getKeys = __webpack_require__(30) - , gOPS = __webpack_require__(43) - , pIE = __webpack_require__(44) - , toObject = __webpack_require__(58) - , IObject = __webpack_require__(33) - , $assign = Object.assign; - - // should work with symbols and should have deterministic property order (V8 bug) - module.exports = !$assign || __webpack_require__(7)(function(){ - var A = {} - , B = {} - , S = Symbol() - , K = 'abcdefghijklmnopqrst'; - A[S] = 7; - K.split('').forEach(function(k){ B[k] = k; }); - return $assign({}, A)[S] != 7 || Object.keys($assign({}, B)).join('') != K; - }) ? function assign(target, source){ // eslint-disable-line no-unused-vars - var T = toObject(target) - , aLen = arguments.length - , index = 1 - , getSymbols = gOPS.f - , isEnum = pIE.f; - while(aLen > index){ - var S = IObject(arguments[index++]) - , keys = getSymbols ? getKeys(S).concat(getSymbols(S)) : getKeys(S) - , length = keys.length - , j = 0 - , key; - while(length > j)if(isEnum.call(S, key = keys[j++]))T[key] = S[key]; - } return T; - } : $assign; - -/***/ }, -/* 70 */ -/***/ function(module, exports, __webpack_require__) { - - // 19.1.3.10 Object.is(value1, value2) - var $export = __webpack_require__(8); - $export($export.S, 'Object', {is: __webpack_require__(71)}); - -/***/ }, -/* 71 */ -/***/ function(module, exports) { - - // 7.2.9 SameValue(x, y) - module.exports = Object.is || function is(x, y){ - return x === y ? x !== 0 || 1 / x === 1 / y : x != x && y != y; - }; - -/***/ }, -/* 72 */ -/***/ function(module, exports, __webpack_require__) { - - // 19.1.3.19 Object.setPrototypeOf(O, proto) - var $export = __webpack_require__(8); - $export($export.S, 'Object', {setPrototypeOf: __webpack_require__(73).set}); - -/***/ }, -/* 73 */ -/***/ function(module, exports, __webpack_require__) { - - // Works with __proto__ only. Old v8 can't work with null proto objects. - /* eslint-disable no-proto */ - var isObject = __webpack_require__(13) - , anObject = __webpack_require__(12); - var check = function(O, proto){ - anObject(O); - if(!isObject(proto) && proto !== null)throw TypeError(proto + ": can't set as prototype!"); - }; - module.exports = { - set: Object.setPrototypeOf || ('__proto__' in {} ? // eslint-disable-line - function(test, buggy, set){ - try { - set = __webpack_require__(20)(Function.call, __webpack_require__(51).f(Object.prototype, '__proto__').set, 2); - set(test, []); - buggy = !(test instanceof Array); - } catch(e){ buggy = true; } - return function setPrototypeOf(O, proto){ - check(O, proto); - if(buggy)O.__proto__ = proto; - else set(O, proto); - return O; - }; - }({}, false) : undefined), - check: check - }; - -/***/ }, -/* 74 */ -/***/ function(module, exports, __webpack_require__) { - - 'use strict'; - // 19.1.3.6 Object.prototype.toString() - var classof = __webpack_require__(75) - , test = {}; - test[__webpack_require__(25)('toStringTag')] = 'z'; - if(test + '' != '[object z]'){ - __webpack_require__(18)(Object.prototype, 'toString', function toString(){ - return '[object ' + classof(this) + ']'; - }, true); - } - -/***/ }, -/* 75 */ -/***/ function(module, exports, __webpack_require__) { - - // getting tag from 19.1.3.6 Object.prototype.toString() - var cof = __webpack_require__(34) - , TAG = __webpack_require__(25)('toStringTag') - // ES3 wrong here - , ARG = cof(function(){ return arguments; }()) == 'Arguments'; - - // fallback for IE11 Script Access Denied error - var tryGet = function(it, key){ - try { - return it[key]; - } catch(e){ /* empty */ } - }; - - module.exports = function(it){ - var O, T, B; - return it === undefined ? 'Undefined' : it === null ? 'Null' - // @@toStringTag case - : typeof (T = tryGet(O = Object(it), TAG)) == 'string' ? T - // builtinTag case - : ARG ? cof(O) - // ES3 arguments fallback - : (B = cof(O)) == 'Object' && typeof O.callee == 'function' ? 'Arguments' : B; - }; - -/***/ }, -/* 76 */ -/***/ function(module, exports, __webpack_require__) { - - // 19.2.3.2 / 15.3.4.5 Function.prototype.bind(thisArg, args...) - var $export = __webpack_require__(8); - - $export($export.P, 'Function', {bind: __webpack_require__(77)}); - -/***/ }, -/* 77 */ -/***/ function(module, exports, __webpack_require__) { - - 'use strict'; - var aFunction = __webpack_require__(21) - , isObject = __webpack_require__(13) - , invoke = __webpack_require__(78) - , arraySlice = [].slice - , factories = {}; - - var construct = function(F, len, args){ - if(!(len in factories)){ - for(var n = [], i = 0; i < len; i++)n[i] = 'a[' + i + ']'; - factories[len] = Function('F,a', 'return new F(' + n.join(',') + ')'); - } return factories[len](F, args); - }; - - module.exports = Function.bind || function bind(that /*, args... */){ - var fn = aFunction(this) - , partArgs = arraySlice.call(arguments, 1); - var bound = function(/* args... */){ - var args = partArgs.concat(arraySlice.call(arguments)); - return this instanceof bound ? construct(fn, args.length, args) : invoke(fn, args, that); - }; - if(isObject(fn.prototype))bound.prototype = fn.prototype; - return bound; - }; - -/***/ }, -/* 78 */ -/***/ function(module, exports) { - - // fast apply, http://jsperf.lnkit.com/fast-apply/5 - module.exports = function(fn, args, that){ - var un = that === undefined; - switch(args.length){ - case 0: return un ? fn() - : fn.call(that); - case 1: return un ? fn(args[0]) - : fn.call(that, args[0]); - case 2: return un ? fn(args[0], args[1]) - : fn.call(that, args[0], args[1]); - case 3: return un ? fn(args[0], args[1], args[2]) - : fn.call(that, args[0], args[1], args[2]); - case 4: return un ? fn(args[0], args[1], args[2], args[3]) - : fn.call(that, args[0], args[1], args[2], args[3]); - } return fn.apply(that, args); - }; - -/***/ }, -/* 79 */ -/***/ function(module, exports, __webpack_require__) { - - var dP = __webpack_require__(11).f - , createDesc = __webpack_require__(17) - , has = __webpack_require__(5) - , FProto = Function.prototype - , nameRE = /^\s*function ([^ (]*)/ - , NAME = 'name'; - - var isExtensible = Object.isExtensible || function(){ - return true; - }; - - // 19.2.4.2 name - NAME in FProto || __webpack_require__(6) && dP(FProto, NAME, { - configurable: true, - get: function(){ - try { - var that = this - , name = ('' + that).match(nameRE)[1]; - has(that, NAME) || !isExtensible(that) || dP(that, NAME, createDesc(5, name)); - return name; - } catch(e){ - return ''; - } - } - }); - -/***/ }, -/* 80 */ -/***/ function(module, exports, __webpack_require__) { - - 'use strict'; - var isObject = __webpack_require__(13) - , getPrototypeOf = __webpack_require__(59) - , HAS_INSTANCE = __webpack_require__(25)('hasInstance') - , FunctionProto = Function.prototype; - // 19.2.3.6 Function.prototype[@@hasInstance](V) - if(!(HAS_INSTANCE in FunctionProto))__webpack_require__(11).f(FunctionProto, HAS_INSTANCE, {value: function(O){ - if(typeof this != 'function' || !isObject(O))return false; - if(!isObject(this.prototype))return O instanceof this; - // for environment w/o native `@@hasInstance` logic enough `instanceof`, but add this: - while(O = getPrototypeOf(O))if(this.prototype === O)return true; - return false; - }}); - -/***/ }, -/* 81 */ -/***/ function(module, exports, __webpack_require__) { - - var $export = __webpack_require__(8) - , $parseInt = __webpack_require__(82); - // 18.2.5 parseInt(string, radix) - $export($export.G + $export.F * (parseInt != $parseInt), {parseInt: $parseInt}); - -/***/ }, -/* 82 */ -/***/ function(module, exports, __webpack_require__) { - - var $parseInt = __webpack_require__(4).parseInt - , $trim = __webpack_require__(83).trim - , ws = __webpack_require__(84) - , hex = /^[\-+]?0[xX]/; - - module.exports = $parseInt(ws + '08') !== 8 || $parseInt(ws + '0x16') !== 22 ? function parseInt(str, radix){ - var string = $trim(String(str), 3); - return $parseInt(string, (radix >>> 0) || (hex.test(string) ? 16 : 10)); - } : $parseInt; - -/***/ }, -/* 83 */ -/***/ function(module, exports, __webpack_require__) { - - var $export = __webpack_require__(8) - , defined = __webpack_require__(35) - , fails = __webpack_require__(7) - , spaces = __webpack_require__(84) - , space = '[' + spaces + ']' - , non = '\u200b\u0085' - , ltrim = RegExp('^' + space + space + '*') - , rtrim = RegExp(space + space + '*$'); - - var exporter = function(KEY, exec, ALIAS){ - var exp = {}; - var FORCE = fails(function(){ - return !!spaces[KEY]() || non[KEY]() != non; - }); - var fn = exp[KEY] = FORCE ? exec(trim) : spaces[KEY]; - if(ALIAS)exp[ALIAS] = fn; - $export($export.P + $export.F * FORCE, 'String', exp); - }; - - // 1 -> String#trimLeft - // 2 -> String#trimRight - // 3 -> String#trim - var trim = exporter.trim = function(string, TYPE){ - string = String(defined(string)); - if(TYPE & 1)string = string.replace(ltrim, ''); - if(TYPE & 2)string = string.replace(rtrim, ''); - return string; - }; - - module.exports = exporter; - -/***/ }, -/* 84 */ -/***/ function(module, exports) { - - module.exports = '\x09\x0A\x0B\x0C\x0D\x20\xA0\u1680\u180E\u2000\u2001\u2002\u2003' + - '\u2004\u2005\u2006\u2007\u2008\u2009\u200A\u202F\u205F\u3000\u2028\u2029\uFEFF'; - -/***/ }, -/* 85 */ -/***/ function(module, exports, __webpack_require__) { - - var $export = __webpack_require__(8) - , $parseFloat = __webpack_require__(86); - // 18.2.4 parseFloat(string) - $export($export.G + $export.F * (parseFloat != $parseFloat), {parseFloat: $parseFloat}); - -/***/ }, -/* 86 */ -/***/ function(module, exports, __webpack_require__) { - - var $parseFloat = __webpack_require__(4).parseFloat - , $trim = __webpack_require__(83).trim; - - module.exports = 1 / $parseFloat(__webpack_require__(84) + '-0') !== -Infinity ? function parseFloat(str){ - var string = $trim(String(str), 3) - , result = $parseFloat(string); - return result === 0 && string.charAt(0) == '-' ? -0 : result; - } : $parseFloat; - -/***/ }, -/* 87 */ -/***/ function(module, exports, __webpack_require__) { - - 'use strict'; - var global = __webpack_require__(4) - , has = __webpack_require__(5) - , cof = __webpack_require__(34) - , inheritIfRequired = __webpack_require__(88) - , toPrimitive = __webpack_require__(16) - , fails = __webpack_require__(7) - , gOPN = __webpack_require__(50).f - , gOPD = __webpack_require__(51).f - , dP = __webpack_require__(11).f - , $trim = __webpack_require__(83).trim - , NUMBER = 'Number' - , $Number = global[NUMBER] - , Base = $Number - , proto = $Number.prototype - // Opera ~12 has broken Object#toString - , BROKEN_COF = cof(__webpack_require__(46)(proto)) == NUMBER - , TRIM = 'trim' in String.prototype; - - // 7.1.3 ToNumber(argument) - var toNumber = function(argument){ - var it = toPrimitive(argument, false); - if(typeof it == 'string' && it.length > 2){ - it = TRIM ? it.trim() : $trim(it, 3); - var first = it.charCodeAt(0) - , third, radix, maxCode; - if(first === 43 || first === 45){ - third = it.charCodeAt(2); - if(third === 88 || third === 120)return NaN; // Number('+0x1') should be NaN, old V8 fix - } else if(first === 48){ - switch(it.charCodeAt(1)){ - case 66 : case 98 : radix = 2; maxCode = 49; break; // fast equal /^0b[01]+$/i - case 79 : case 111 : radix = 8; maxCode = 55; break; // fast equal /^0o[0-7]+$/i - default : return +it; - } - for(var digits = it.slice(2), i = 0, l = digits.length, code; i < l; i++){ - code = digits.charCodeAt(i); - // parseInt parses a string to a first unavailable symbol - // but ToNumber should return NaN if a string contains unavailable symbols - if(code < 48 || code > maxCode)return NaN; - } return parseInt(digits, radix); - } - } return +it; - }; - - if(!$Number(' 0o1') || !$Number('0b1') || $Number('+0x1')){ - $Number = function Number(value){ - var it = arguments.length < 1 ? 0 : value - , that = this; - return that instanceof $Number - // check on 1..constructor(foo) case - && (BROKEN_COF ? fails(function(){ proto.valueOf.call(that); }) : cof(that) != NUMBER) - ? inheritIfRequired(new Base(toNumber(it)), that, $Number) : toNumber(it); - }; - for(var keys = __webpack_require__(6) ? gOPN(Base) : ( - // ES3: - 'MAX_VALUE,MIN_VALUE,NaN,NEGATIVE_INFINITY,POSITIVE_INFINITY,' + - // ES6 (in case, if modules with ES6 Number statics required before): - 'EPSILON,isFinite,isInteger,isNaN,isSafeInteger,MAX_SAFE_INTEGER,' + - 'MIN_SAFE_INTEGER,parseFloat,parseInt,isInteger' - ).split(','), j = 0, key; keys.length > j; j++){ - if(has(Base, key = keys[j]) && !has($Number, key)){ - dP($Number, key, gOPD(Base, key)); - } - } - $Number.prototype = proto; - proto.constructor = $Number; - __webpack_require__(18)(global, NUMBER, $Number); - } - -/***/ }, -/* 88 */ -/***/ function(module, exports, __webpack_require__) { - - var isObject = __webpack_require__(13) - , setPrototypeOf = __webpack_require__(73).set; - module.exports = function(that, target, C){ - var P, S = target.constructor; - if(S !== C && typeof S == 'function' && (P = S.prototype) !== C.prototype && isObject(P) && setPrototypeOf){ - setPrototypeOf(that, P); - } return that; - }; - -/***/ }, -/* 89 */ -/***/ function(module, exports, __webpack_require__) { - - 'use strict'; - var $export = __webpack_require__(8) - , toInteger = __webpack_require__(38) - , aNumberValue = __webpack_require__(90) - , repeat = __webpack_require__(91) - , $toFixed = 1..toFixed - , floor = Math.floor - , data = [0, 0, 0, 0, 0, 0] - , ERROR = 'Number.toFixed: incorrect invocation!' - , ZERO = '0'; - - var multiply = function(n, c){ - var i = -1 - , c2 = c; - while(++i < 6){ - c2 += n * data[i]; - data[i] = c2 % 1e7; - c2 = floor(c2 / 1e7); - } - }; - var divide = function(n){ - var i = 6 - , c = 0; - while(--i >= 0){ - c += data[i]; - data[i] = floor(c / n); - c = (c % n) * 1e7; - } - }; - var numToString = function(){ - var i = 6 - , s = ''; - while(--i >= 0){ - if(s !== '' || i === 0 || data[i] !== 0){ - var t = String(data[i]); - s = s === '' ? t : s + repeat.call(ZERO, 7 - t.length) + t; - } - } return s; - }; - var pow = function(x, n, acc){ - return n === 0 ? acc : n % 2 === 1 ? pow(x, n - 1, acc * x) : pow(x * x, n / 2, acc); - }; - var log = function(x){ - var n = 0 - , x2 = x; - while(x2 >= 4096){ - n += 12; - x2 /= 4096; - } - while(x2 >= 2){ - n += 1; - x2 /= 2; - } return n; - }; - - $export($export.P + $export.F * (!!$toFixed && ( - 0.00008.toFixed(3) !== '0.000' || - 0.9.toFixed(0) !== '1' || - 1.255.toFixed(2) !== '1.25' || - 1000000000000000128..toFixed(0) !== '1000000000000000128' - ) || !__webpack_require__(7)(function(){ - // V8 ~ Android 4.3- - $toFixed.call({}); - })), 'Number', { - toFixed: function toFixed(fractionDigits){ - var x = aNumberValue(this, ERROR) - , f = toInteger(fractionDigits) - , s = '' - , m = ZERO - , e, z, j, k; - if(f < 0 || f > 20)throw RangeError(ERROR); - if(x != x)return 'NaN'; - if(x <= -1e21 || x >= 1e21)return String(x); - if(x < 0){ - s = '-'; - x = -x; - } - if(x > 1e-21){ - e = log(x * pow(2, 69, 1)) - 69; - z = e < 0 ? x * pow(2, -e, 1) : x / pow(2, e, 1); - z *= 0x10000000000000; - e = 52 - e; - if(e > 0){ - multiply(0, z); - j = f; - while(j >= 7){ - multiply(1e7, 0); - j -= 7; - } - multiply(pow(10, j, 1), 0); - j = e - 1; - while(j >= 23){ - divide(1 << 23); - j -= 23; - } - divide(1 << j); - multiply(1, 1); - divide(2); - m = numToString(); - } else { - multiply(0, z); - multiply(1 << -e, 0); - m = numToString() + repeat.call(ZERO, f); - } - } - if(f > 0){ - k = m.length; - m = s + (k <= f ? '0.' + repeat.call(ZERO, f - k) + m : m.slice(0, k - f) + '.' + m.slice(k - f)); - } else { - m = s + m; - } return m; - } - }); - -/***/ }, -/* 90 */ -/***/ function(module, exports, __webpack_require__) { - - var cof = __webpack_require__(34); - module.exports = function(it, msg){ - if(typeof it != 'number' && cof(it) != 'Number')throw TypeError(msg); - return +it; - }; - -/***/ }, -/* 91 */ -/***/ function(module, exports, __webpack_require__) { - - 'use strict'; - var toInteger = __webpack_require__(38) - , defined = __webpack_require__(35); - - module.exports = function repeat(count){ - var str = String(defined(this)) - , res = '' - , n = toInteger(count); - if(n < 0 || n == Infinity)throw RangeError("Count can't be negative"); - for(;n > 0; (n >>>= 1) && (str += str))if(n & 1)res += str; - return res; - }; - -/***/ }, -/* 92 */ -/***/ function(module, exports, __webpack_require__) { - - 'use strict'; - var $export = __webpack_require__(8) - , $fails = __webpack_require__(7) - , aNumberValue = __webpack_require__(90) - , $toPrecision = 1..toPrecision; - - $export($export.P + $export.F * ($fails(function(){ - // IE7- - return $toPrecision.call(1, undefined) !== '1'; - }) || !$fails(function(){ - // V8 ~ Android 4.3- - $toPrecision.call({}); - })), 'Number', { - toPrecision: function toPrecision(precision){ - var that = aNumberValue(this, 'Number#toPrecision: incorrect invocation!'); - return precision === undefined ? $toPrecision.call(that) : $toPrecision.call(that, precision); - } - }); - -/***/ }, -/* 93 */ -/***/ function(module, exports, __webpack_require__) { - - // 20.1.2.1 Number.EPSILON - var $export = __webpack_require__(8); - - $export($export.S, 'Number', {EPSILON: Math.pow(2, -52)}); - -/***/ }, -/* 94 */ -/***/ function(module, exports, __webpack_require__) { - - // 20.1.2.2 Number.isFinite(number) - var $export = __webpack_require__(8) - , _isFinite = __webpack_require__(4).isFinite; - - $export($export.S, 'Number', { - isFinite: function isFinite(it){ - return typeof it == 'number' && _isFinite(it); - } - }); - -/***/ }, -/* 95 */ -/***/ function(module, exports, __webpack_require__) { - - // 20.1.2.3 Number.isInteger(number) - var $export = __webpack_require__(8); - - $export($export.S, 'Number', {isInteger: __webpack_require__(96)}); - -/***/ }, -/* 96 */ -/***/ function(module, exports, __webpack_require__) { - - // 20.1.2.3 Number.isInteger(number) - var isObject = __webpack_require__(13) - , floor = Math.floor; - module.exports = function isInteger(it){ - return !isObject(it) && isFinite(it) && floor(it) === it; - }; - -/***/ }, -/* 97 */ -/***/ function(module, exports, __webpack_require__) { - - // 20.1.2.4 Number.isNaN(number) - var $export = __webpack_require__(8); - - $export($export.S, 'Number', { - isNaN: function isNaN(number){ - return number != number; - } - }); - -/***/ }, -/* 98 */ -/***/ function(module, exports, __webpack_require__) { - - // 20.1.2.5 Number.isSafeInteger(number) - var $export = __webpack_require__(8) - , isInteger = __webpack_require__(96) - , abs = Math.abs; - - $export($export.S, 'Number', { - isSafeInteger: function isSafeInteger(number){ - return isInteger(number) && abs(number) <= 0x1fffffffffffff; - } - }); - -/***/ }, -/* 99 */ -/***/ function(module, exports, __webpack_require__) { - - // 20.1.2.6 Number.MAX_SAFE_INTEGER - var $export = __webpack_require__(8); - - $export($export.S, 'Number', {MAX_SAFE_INTEGER: 0x1fffffffffffff}); - -/***/ }, -/* 100 */ -/***/ function(module, exports, __webpack_require__) { - - // 20.1.2.10 Number.MIN_SAFE_INTEGER - var $export = __webpack_require__(8); - - $export($export.S, 'Number', {MIN_SAFE_INTEGER: -0x1fffffffffffff}); - -/***/ }, -/* 101 */ -/***/ function(module, exports, __webpack_require__) { - - var $export = __webpack_require__(8) - , $parseFloat = __webpack_require__(86); - // 20.1.2.12 Number.parseFloat(string) - $export($export.S + $export.F * (Number.parseFloat != $parseFloat), 'Number', {parseFloat: $parseFloat}); - -/***/ }, -/* 102 */ -/***/ function(module, exports, __webpack_require__) { - - var $export = __webpack_require__(8) - , $parseInt = __webpack_require__(82); - // 20.1.2.13 Number.parseInt(string, radix) - $export($export.S + $export.F * (Number.parseInt != $parseInt), 'Number', {parseInt: $parseInt}); - -/***/ }, -/* 103 */ -/***/ function(module, exports, __webpack_require__) { - - // 20.2.2.3 Math.acosh(x) - var $export = __webpack_require__(8) - , log1p = __webpack_require__(104) - , sqrt = Math.sqrt - , $acosh = Math.acosh; - - $export($export.S + $export.F * !($acosh - // V8 bug: https://code.google.com/p/v8/issues/detail?id=3509 - && Math.floor($acosh(Number.MAX_VALUE)) == 710 - // Tor Browser bug: Math.acosh(Infinity) -> NaN - && $acosh(Infinity) == Infinity - ), 'Math', { - acosh: function acosh(x){ - return (x = +x) < 1 ? NaN : x > 94906265.62425156 - ? Math.log(x) + Math.LN2 - : log1p(x - 1 + sqrt(x - 1) * sqrt(x + 1)); - } - }); - -/***/ }, -/* 104 */ -/***/ function(module, exports) { - - // 20.2.2.20 Math.log1p(x) - module.exports = Math.log1p || function log1p(x){ - return (x = +x) > -1e-8 && x < 1e-8 ? x - x * x / 2 : Math.log(1 + x); - }; - -/***/ }, -/* 105 */ -/***/ function(module, exports, __webpack_require__) { - - // 20.2.2.5 Math.asinh(x) - var $export = __webpack_require__(8) - , $asinh = Math.asinh; - - function asinh(x){ - return !isFinite(x = +x) || x == 0 ? x : x < 0 ? -asinh(-x) : Math.log(x + Math.sqrt(x * x + 1)); - } - - // Tor Browser bug: Math.asinh(0) -> -0 - $export($export.S + $export.F * !($asinh && 1 / $asinh(0) > 0), 'Math', {asinh: asinh}); - -/***/ }, -/* 106 */ -/***/ function(module, exports, __webpack_require__) { - - // 20.2.2.7 Math.atanh(x) - var $export = __webpack_require__(8) - , $atanh = Math.atanh; - - // Tor Browser bug: Math.atanh(-0) -> 0 - $export($export.S + $export.F * !($atanh && 1 / $atanh(-0) < 0), 'Math', { - atanh: function atanh(x){ - return (x = +x) == 0 ? x : Math.log((1 + x) / (1 - x)) / 2; - } - }); - -/***/ }, -/* 107 */ -/***/ function(module, exports, __webpack_require__) { - - // 20.2.2.9 Math.cbrt(x) - var $export = __webpack_require__(8) - , sign = __webpack_require__(108); - - $export($export.S, 'Math', { - cbrt: function cbrt(x){ - return sign(x = +x) * Math.pow(Math.abs(x), 1 / 3); - } - }); - -/***/ }, -/* 108 */ -/***/ function(module, exports) { - - // 20.2.2.28 Math.sign(x) - module.exports = Math.sign || function sign(x){ - return (x = +x) == 0 || x != x ? x : x < 0 ? -1 : 1; - }; - -/***/ }, -/* 109 */ -/***/ function(module, exports, __webpack_require__) { - - // 20.2.2.11 Math.clz32(x) - var $export = __webpack_require__(8); - - $export($export.S, 'Math', { - clz32: function clz32(x){ - return (x >>>= 0) ? 31 - Math.floor(Math.log(x + 0.5) * Math.LOG2E) : 32; - } - }); - -/***/ }, -/* 110 */ -/***/ function(module, exports, __webpack_require__) { - - // 20.2.2.12 Math.cosh(x) - var $export = __webpack_require__(8) - , exp = Math.exp; - - $export($export.S, 'Math', { - cosh: function cosh(x){ - return (exp(x = +x) + exp(-x)) / 2; - } - }); - -/***/ }, -/* 111 */ -/***/ function(module, exports, __webpack_require__) { - - // 20.2.2.14 Math.expm1(x) - var $export = __webpack_require__(8) - , $expm1 = __webpack_require__(112); - - $export($export.S + $export.F * ($expm1 != Math.expm1), 'Math', {expm1: $expm1}); - -/***/ }, -/* 112 */ -/***/ function(module, exports) { - - // 20.2.2.14 Math.expm1(x) - var $expm1 = Math.expm1; - module.exports = (!$expm1 - // Old FF bug - || $expm1(10) > 22025.465794806719 || $expm1(10) < 22025.4657948067165168 - // Tor Browser bug - || $expm1(-2e-17) != -2e-17 - ) ? function expm1(x){ - return (x = +x) == 0 ? x : x > -1e-6 && x < 1e-6 ? x + x * x / 2 : Math.exp(x) - 1; - } : $expm1; - -/***/ }, -/* 113 */ -/***/ function(module, exports, __webpack_require__) { - - // 20.2.2.16 Math.fround(x) - var $export = __webpack_require__(8) - , sign = __webpack_require__(108) - , pow = Math.pow - , EPSILON = pow(2, -52) - , EPSILON32 = pow(2, -23) - , MAX32 = pow(2, 127) * (2 - EPSILON32) - , MIN32 = pow(2, -126); - - var roundTiesToEven = function(n){ - return n + 1 / EPSILON - 1 / EPSILON; - }; - - - $export($export.S, 'Math', { - fround: function fround(x){ - var $abs = Math.abs(x) - , $sign = sign(x) - , a, result; - if($abs < MIN32)return $sign * roundTiesToEven($abs / MIN32 / EPSILON32) * MIN32 * EPSILON32; - a = (1 + EPSILON32 / EPSILON) * $abs; - result = a - (a - $abs); - if(result > MAX32 || result != result)return $sign * Infinity; - return $sign * result; - } - }); - -/***/ }, -/* 114 */ -/***/ function(module, exports, __webpack_require__) { - - // 20.2.2.17 Math.hypot([value1[, value2[, … ]]]) - var $export = __webpack_require__(8) - , abs = Math.abs; - - $export($export.S, 'Math', { - hypot: function hypot(value1, value2){ // eslint-disable-line no-unused-vars - var sum = 0 - , i = 0 - , aLen = arguments.length - , larg = 0 - , arg, div; - while(i < aLen){ - arg = abs(arguments[i++]); - if(larg < arg){ - div = larg / arg; - sum = sum * div * div + 1; - larg = arg; - } else if(arg > 0){ - div = arg / larg; - sum += div * div; - } else sum += arg; - } - return larg === Infinity ? Infinity : larg * Math.sqrt(sum); - } - }); - -/***/ }, -/* 115 */ -/***/ function(module, exports, __webpack_require__) { - - // 20.2.2.18 Math.imul(x, y) - var $export = __webpack_require__(8) - , $imul = Math.imul; - - // some WebKit versions fails with big numbers, some has wrong arity - $export($export.S + $export.F * __webpack_require__(7)(function(){ - return $imul(0xffffffff, 5) != -5 || $imul.length != 2; - }), 'Math', { - imul: function imul(x, y){ - var UINT16 = 0xffff - , xn = +x - , yn = +y - , xl = UINT16 & xn - , yl = UINT16 & yn; - return 0 | xl * yl + ((UINT16 & xn >>> 16) * yl + xl * (UINT16 & yn >>> 16) << 16 >>> 0); - } - }); - -/***/ }, -/* 116 */ -/***/ function(module, exports, __webpack_require__) { - - // 20.2.2.21 Math.log10(x) - var $export = __webpack_require__(8); - - $export($export.S, 'Math', { - log10: function log10(x){ - return Math.log(x) / Math.LN10; - } - }); - -/***/ }, -/* 117 */ -/***/ function(module, exports, __webpack_require__) { - - // 20.2.2.20 Math.log1p(x) - var $export = __webpack_require__(8); - - $export($export.S, 'Math', {log1p: __webpack_require__(104)}); - -/***/ }, -/* 118 */ -/***/ function(module, exports, __webpack_require__) { - - // 20.2.2.22 Math.log2(x) - var $export = __webpack_require__(8); - - $export($export.S, 'Math', { - log2: function log2(x){ - return Math.log(x) / Math.LN2; - } - }); - -/***/ }, -/* 119 */ -/***/ function(module, exports, __webpack_require__) { - - // 20.2.2.28 Math.sign(x) - var $export = __webpack_require__(8); - - $export($export.S, 'Math', {sign: __webpack_require__(108)}); - -/***/ }, -/* 120 */ -/***/ function(module, exports, __webpack_require__) { - - // 20.2.2.30 Math.sinh(x) - var $export = __webpack_require__(8) - , expm1 = __webpack_require__(112) - , exp = Math.exp; - - // V8 near Chromium 38 has a problem with very small numbers - $export($export.S + $export.F * __webpack_require__(7)(function(){ - return !Math.sinh(-2e-17) != -2e-17; - }), 'Math', { - sinh: function sinh(x){ - return Math.abs(x = +x) < 1 - ? (expm1(x) - expm1(-x)) / 2 - : (exp(x - 1) - exp(-x - 1)) * (Math.E / 2); - } - }); - -/***/ }, -/* 121 */ -/***/ function(module, exports, __webpack_require__) { - - // 20.2.2.33 Math.tanh(x) - var $export = __webpack_require__(8) - , expm1 = __webpack_require__(112) - , exp = Math.exp; - - $export($export.S, 'Math', { - tanh: function tanh(x){ - var a = expm1(x = +x) - , b = expm1(-x); - return a == Infinity ? 1 : b == Infinity ? -1 : (a - b) / (exp(x) + exp(-x)); - } - }); - -/***/ }, -/* 122 */ -/***/ function(module, exports, __webpack_require__) { - - // 20.2.2.34 Math.trunc(x) - var $export = __webpack_require__(8); - - $export($export.S, 'Math', { - trunc: function trunc(it){ - return (it > 0 ? Math.floor : Math.ceil)(it); - } - }); - -/***/ }, -/* 123 */ -/***/ function(module, exports, __webpack_require__) { - - var $export = __webpack_require__(8) - , toIndex = __webpack_require__(39) - , fromCharCode = String.fromCharCode - , $fromCodePoint = String.fromCodePoint; - - // length should be 1, old FF problem - $export($export.S + $export.F * (!!$fromCodePoint && $fromCodePoint.length != 1), 'String', { - // 21.1.2.2 String.fromCodePoint(...codePoints) - fromCodePoint: function fromCodePoint(x){ // eslint-disable-line no-unused-vars - var res = [] - , aLen = arguments.length - , i = 0 - , code; - while(aLen > i){ - code = +arguments[i++]; - if(toIndex(code, 0x10ffff) !== code)throw RangeError(code + ' is not a valid code point'); - res.push(code < 0x10000 - ? fromCharCode(code) - : fromCharCode(((code -= 0x10000) >> 10) + 0xd800, code % 0x400 + 0xdc00) - ); - } return res.join(''); - } - }); - -/***/ }, -/* 124 */ -/***/ function(module, exports, __webpack_require__) { - - var $export = __webpack_require__(8) - , toIObject = __webpack_require__(32) - , toLength = __webpack_require__(37); - - $export($export.S, 'String', { - // 21.1.2.4 String.raw(callSite, ...substitutions) - raw: function raw(callSite){ - var tpl = toIObject(callSite.raw) - , len = toLength(tpl.length) - , aLen = arguments.length - , res = [] - , i = 0; - while(len > i){ - res.push(String(tpl[i++])); - if(i < aLen)res.push(String(arguments[i])); - } return res.join(''); - } - }); - -/***/ }, -/* 125 */ -/***/ function(module, exports, __webpack_require__) { - - 'use strict'; - // 21.1.3.25 String.prototype.trim() - __webpack_require__(83)('trim', function($trim){ - return function trim(){ - return $trim(this, 3); - }; - }); - -/***/ }, -/* 126 */ -/***/ function(module, exports, __webpack_require__) { - - 'use strict'; - var $at = __webpack_require__(127)(true); - - // 21.1.3.27 String.prototype[@@iterator]() - __webpack_require__(128)(String, 'String', function(iterated){ - this._t = String(iterated); // target - this._i = 0; // next index - // 21.1.5.2.1 %StringIteratorPrototype%.next() - }, function(){ - var O = this._t - , index = this._i - , point; - if(index >= O.length)return {value: undefined, done: true}; - point = $at(O, index); - this._i += point.length; - return {value: point, done: false}; - }); - -/***/ }, -/* 127 */ -/***/ function(module, exports, __webpack_require__) { - - var toInteger = __webpack_require__(38) - , defined = __webpack_require__(35); - // true -> String#at - // false -> String#codePointAt - module.exports = function(TO_STRING){ - return function(that, pos){ - var s = String(defined(that)) - , i = toInteger(pos) - , l = s.length - , a, b; - if(i < 0 || i >= l)return TO_STRING ? '' : undefined; - a = s.charCodeAt(i); - return a < 0xd800 || a > 0xdbff || i + 1 === l || (b = s.charCodeAt(i + 1)) < 0xdc00 || b > 0xdfff - ? TO_STRING ? s.charAt(i) : a - : TO_STRING ? s.slice(i, i + 2) : (a - 0xd800 << 10) + (b - 0xdc00) + 0x10000; - }; - }; - -/***/ }, -/* 128 */ -/***/ function(module, exports, __webpack_require__) { - - 'use strict'; - var LIBRARY = __webpack_require__(28) - , $export = __webpack_require__(8) - , redefine = __webpack_require__(18) - , hide = __webpack_require__(10) - , has = __webpack_require__(5) - , Iterators = __webpack_require__(129) - , $iterCreate = __webpack_require__(130) - , setToStringTag = __webpack_require__(24) - , getPrototypeOf = __webpack_require__(59) - , ITERATOR = __webpack_require__(25)('iterator') - , BUGGY = !([].keys && 'next' in [].keys()) // Safari has buggy iterators w/o `next` - , FF_ITERATOR = '@@iterator' - , KEYS = 'keys' - , VALUES = 'values'; - - var returnThis = function(){ return this; }; - - module.exports = function(Base, NAME, Constructor, next, DEFAULT, IS_SET, FORCED){ - $iterCreate(Constructor, NAME, next); - var getMethod = function(kind){ - if(!BUGGY && kind in proto)return proto[kind]; - switch(kind){ - case KEYS: return function keys(){ return new Constructor(this, kind); }; - case VALUES: return function values(){ return new Constructor(this, kind); }; - } return function entries(){ return new Constructor(this, kind); }; - }; - var TAG = NAME + ' Iterator' - , DEF_VALUES = DEFAULT == VALUES - , VALUES_BUG = false - , proto = Base.prototype - , $native = proto[ITERATOR] || proto[FF_ITERATOR] || DEFAULT && proto[DEFAULT] - , $default = $native || getMethod(DEFAULT) - , $entries = DEFAULT ? !DEF_VALUES ? $default : getMethod('entries') : undefined - , $anyNative = NAME == 'Array' ? proto.entries || $native : $native - , methods, key, IteratorPrototype; - // Fix native - if($anyNative){ - IteratorPrototype = getPrototypeOf($anyNative.call(new Base)); - if(IteratorPrototype !== Object.prototype){ - // Set @@toStringTag to native iterators - setToStringTag(IteratorPrototype, TAG, true); - // fix for some old engines - if(!LIBRARY && !has(IteratorPrototype, ITERATOR))hide(IteratorPrototype, ITERATOR, returnThis); - } - } - // fix Array#{values, @@iterator}.name in V8 / FF - if(DEF_VALUES && $native && $native.name !== VALUES){ - VALUES_BUG = true; - $default = function values(){ return $native.call(this); }; - } - // Define iterator - if((!LIBRARY || FORCED) && (BUGGY || VALUES_BUG || !proto[ITERATOR])){ - hide(proto, ITERATOR, $default); - } - // Plug for library - Iterators[NAME] = $default; - Iterators[TAG] = returnThis; - if(DEFAULT){ - methods = { - values: DEF_VALUES ? $default : getMethod(VALUES), - keys: IS_SET ? $default : getMethod(KEYS), - entries: $entries - }; - if(FORCED)for(key in methods){ - if(!(key in proto))redefine(proto, key, methods[key]); - } else $export($export.P + $export.F * (BUGGY || VALUES_BUG), NAME, methods); - } - return methods; - }; - -/***/ }, -/* 129 */ -/***/ function(module, exports) { - - module.exports = {}; - -/***/ }, -/* 130 */ -/***/ function(module, exports, __webpack_require__) { - - 'use strict'; - var create = __webpack_require__(46) - , descriptor = __webpack_require__(17) - , setToStringTag = __webpack_require__(24) - , IteratorPrototype = {}; - - // 25.1.2.1.1 %IteratorPrototype%[@@iterator]() - __webpack_require__(10)(IteratorPrototype, __webpack_require__(25)('iterator'), function(){ return this; }); - - module.exports = function(Constructor, NAME, next){ - Constructor.prototype = create(IteratorPrototype, {next: descriptor(1, next)}); - setToStringTag(Constructor, NAME + ' Iterator'); - }; - -/***/ }, -/* 131 */ -/***/ function(module, exports, __webpack_require__) { - - 'use strict'; - var $export = __webpack_require__(8) - , $at = __webpack_require__(127)(false); - $export($export.P, 'String', { - // 21.1.3.3 String.prototype.codePointAt(pos) - codePointAt: function codePointAt(pos){ - return $at(this, pos); - } - }); - -/***/ }, -/* 132 */ -/***/ function(module, exports, __webpack_require__) { - - // 21.1.3.6 String.prototype.endsWith(searchString [, endPosition]) - 'use strict'; - var $export = __webpack_require__(8) - , toLength = __webpack_require__(37) - , context = __webpack_require__(133) - , ENDS_WITH = 'endsWith' - , $endsWith = ''[ENDS_WITH]; - - $export($export.P + $export.F * __webpack_require__(135)(ENDS_WITH), 'String', { - endsWith: function endsWith(searchString /*, endPosition = @length */){ - var that = context(this, searchString, ENDS_WITH) - , endPosition = arguments.length > 1 ? arguments[1] : undefined - , len = toLength(that.length) - , end = endPosition === undefined ? len : Math.min(toLength(endPosition), len) - , search = String(searchString); - return $endsWith - ? $endsWith.call(that, search, end) - : that.slice(end - search.length, end) === search; - } - }); - -/***/ }, -/* 133 */ -/***/ function(module, exports, __webpack_require__) { - - // helper for String#{startsWith, endsWith, includes} - var isRegExp = __webpack_require__(134) - , defined = __webpack_require__(35); - - module.exports = function(that, searchString, NAME){ - if(isRegExp(searchString))throw TypeError('String#' + NAME + " doesn't accept regex!"); - return String(defined(that)); - }; - -/***/ }, -/* 134 */ -/***/ function(module, exports, __webpack_require__) { - - // 7.2.8 IsRegExp(argument) - var isObject = __webpack_require__(13) - , cof = __webpack_require__(34) - , MATCH = __webpack_require__(25)('match'); - module.exports = function(it){ - var isRegExp; - return isObject(it) && ((isRegExp = it[MATCH]) !== undefined ? !!isRegExp : cof(it) == 'RegExp'); - }; - -/***/ }, -/* 135 */ -/***/ function(module, exports, __webpack_require__) { - - var MATCH = __webpack_require__(25)('match'); - module.exports = function(KEY){ - var re = /./; - try { - '/./'[KEY](re); - } catch(e){ - try { - re[MATCH] = false; - return !'/./'[KEY](re); - } catch(f){ /* empty */ } - } return true; - }; - -/***/ }, -/* 136 */ -/***/ function(module, exports, __webpack_require__) { - - // 21.1.3.7 String.prototype.includes(searchString, position = 0) - 'use strict'; - var $export = __webpack_require__(8) - , context = __webpack_require__(133) - , INCLUDES = 'includes'; - - $export($export.P + $export.F * __webpack_require__(135)(INCLUDES), 'String', { - includes: function includes(searchString /*, position = 0 */){ - return !!~context(this, searchString, INCLUDES) - .indexOf(searchString, arguments.length > 1 ? arguments[1] : undefined); - } - }); - -/***/ }, -/* 137 */ -/***/ function(module, exports, __webpack_require__) { - - var $export = __webpack_require__(8); - - $export($export.P, 'String', { - // 21.1.3.13 String.prototype.repeat(count) - repeat: __webpack_require__(91) - }); - -/***/ }, -/* 138 */ -/***/ function(module, exports, __webpack_require__) { - - // 21.1.3.18 String.prototype.startsWith(searchString [, position ]) - 'use strict'; - var $export = __webpack_require__(8) - , toLength = __webpack_require__(37) - , context = __webpack_require__(133) - , STARTS_WITH = 'startsWith' - , $startsWith = ''[STARTS_WITH]; - - $export($export.P + $export.F * __webpack_require__(135)(STARTS_WITH), 'String', { - startsWith: function startsWith(searchString /*, position = 0 */){ - var that = context(this, searchString, STARTS_WITH) - , index = toLength(Math.min(arguments.length > 1 ? arguments[1] : undefined, that.length)) - , search = String(searchString); - return $startsWith - ? $startsWith.call(that, search, index) - : that.slice(index, index + search.length) === search; - } - }); - -/***/ }, -/* 139 */ -/***/ function(module, exports, __webpack_require__) { - - 'use strict'; - // B.2.3.2 String.prototype.anchor(name) - __webpack_require__(140)('anchor', function(createHTML){ - return function anchor(name){ - return createHTML(this, 'a', 'name', name); - } - }); - -/***/ }, -/* 140 */ -/***/ function(module, exports, __webpack_require__) { - - var $export = __webpack_require__(8) - , fails = __webpack_require__(7) - , defined = __webpack_require__(35) - , quot = /"/g; - // B.2.3.2.1 CreateHTML(string, tag, attribute, value) - var createHTML = function(string, tag, attribute, value) { - var S = String(defined(string)) - , p1 = '<' + tag; - if(attribute !== '')p1 += ' ' + attribute + '="' + String(value).replace(quot, '"') + '"'; - return p1 + '>' + S + ''; - }; - module.exports = function(NAME, exec){ - var O = {}; - O[NAME] = exec(createHTML); - $export($export.P + $export.F * fails(function(){ - var test = ''[NAME]('"'); - return test !== test.toLowerCase() || test.split('"').length > 3; - }), 'String', O); - }; - -/***/ }, -/* 141 */ -/***/ function(module, exports, __webpack_require__) { - - 'use strict'; - // B.2.3.3 String.prototype.big() - __webpack_require__(140)('big', function(createHTML){ - return function big(){ - return createHTML(this, 'big', '', ''); - } - }); - -/***/ }, -/* 142 */ -/***/ function(module, exports, __webpack_require__) { - - 'use strict'; - // B.2.3.4 String.prototype.blink() - __webpack_require__(140)('blink', function(createHTML){ - return function blink(){ - return createHTML(this, 'blink', '', ''); - } - }); - -/***/ }, -/* 143 */ -/***/ function(module, exports, __webpack_require__) { - - 'use strict'; - // B.2.3.5 String.prototype.bold() - __webpack_require__(140)('bold', function(createHTML){ - return function bold(){ - return createHTML(this, 'b', '', ''); - } - }); - -/***/ }, -/* 144 */ -/***/ function(module, exports, __webpack_require__) { - - 'use strict'; - // B.2.3.6 String.prototype.fixed() - __webpack_require__(140)('fixed', function(createHTML){ - return function fixed(){ - return createHTML(this, 'tt', '', ''); - } - }); - -/***/ }, -/* 145 */ -/***/ function(module, exports, __webpack_require__) { - - 'use strict'; - // B.2.3.7 String.prototype.fontcolor(color) - __webpack_require__(140)('fontcolor', function(createHTML){ - return function fontcolor(color){ - return createHTML(this, 'font', 'color', color); - } - }); - -/***/ }, -/* 146 */ -/***/ function(module, exports, __webpack_require__) { - - 'use strict'; - // B.2.3.8 String.prototype.fontsize(size) - __webpack_require__(140)('fontsize', function(createHTML){ - return function fontsize(size){ - return createHTML(this, 'font', 'size', size); - } - }); - -/***/ }, -/* 147 */ -/***/ function(module, exports, __webpack_require__) { - - 'use strict'; - // B.2.3.9 String.prototype.italics() - __webpack_require__(140)('italics', function(createHTML){ - return function italics(){ - return createHTML(this, 'i', '', ''); - } - }); - -/***/ }, -/* 148 */ -/***/ function(module, exports, __webpack_require__) { - - 'use strict'; - // B.2.3.10 String.prototype.link(url) - __webpack_require__(140)('link', function(createHTML){ - return function link(url){ - return createHTML(this, 'a', 'href', url); - } - }); - -/***/ }, -/* 149 */ -/***/ function(module, exports, __webpack_require__) { - - 'use strict'; - // B.2.3.11 String.prototype.small() - __webpack_require__(140)('small', function(createHTML){ - return function small(){ - return createHTML(this, 'small', '', ''); - } - }); - -/***/ }, -/* 150 */ -/***/ function(module, exports, __webpack_require__) { - - 'use strict'; - // B.2.3.12 String.prototype.strike() - __webpack_require__(140)('strike', function(createHTML){ - return function strike(){ - return createHTML(this, 'strike', '', ''); - } - }); - -/***/ }, -/* 151 */ -/***/ function(module, exports, __webpack_require__) { - - 'use strict'; - // B.2.3.13 String.prototype.sub() - __webpack_require__(140)('sub', function(createHTML){ - return function sub(){ - return createHTML(this, 'sub', '', ''); - } - }); - -/***/ }, -/* 152 */ -/***/ function(module, exports, __webpack_require__) { - - 'use strict'; - // B.2.3.14 String.prototype.sup() - __webpack_require__(140)('sup', function(createHTML){ - return function sup(){ - return createHTML(this, 'sup', '', ''); - } - }); - -/***/ }, -/* 153 */ -/***/ function(module, exports, __webpack_require__) { - - // 20.3.3.1 / 15.9.4.4 Date.now() - var $export = __webpack_require__(8); - - $export($export.S, 'Date', {now: function(){ return new Date().getTime(); }}); - -/***/ }, -/* 154 */ -/***/ function(module, exports, __webpack_require__) { - - 'use strict'; - var $export = __webpack_require__(8) - , toObject = __webpack_require__(58) - , toPrimitive = __webpack_require__(16); - - $export($export.P + $export.F * __webpack_require__(7)(function(){ - return new Date(NaN).toJSON() !== null || Date.prototype.toJSON.call({toISOString: function(){ return 1; }}) !== 1; - }), 'Date', { - toJSON: function toJSON(key){ - var O = toObject(this) - , pv = toPrimitive(O); - return typeof pv == 'number' && !isFinite(pv) ? null : O.toISOString(); - } - }); - -/***/ }, -/* 155 */ -/***/ function(module, exports, __webpack_require__) { - - 'use strict'; - // 20.3.4.36 / 15.9.5.43 Date.prototype.toISOString() - var $export = __webpack_require__(8) - , fails = __webpack_require__(7) - , getTime = Date.prototype.getTime; - - var lz = function(num){ - return num > 9 ? num : '0' + num; - }; - - // PhantomJS / old WebKit has a broken implementations - $export($export.P + $export.F * (fails(function(){ - return new Date(-5e13 - 1).toISOString() != '0385-07-25T07:06:39.999Z'; - }) || !fails(function(){ - new Date(NaN).toISOString(); - })), 'Date', { - toISOString: function toISOString(){ - if(!isFinite(getTime.call(this)))throw RangeError('Invalid time value'); - var d = this - , y = d.getUTCFullYear() - , m = d.getUTCMilliseconds() - , s = y < 0 ? '-' : y > 9999 ? '+' : ''; - return s + ('00000' + Math.abs(y)).slice(s ? -6 : -4) + - '-' + lz(d.getUTCMonth() + 1) + '-' + lz(d.getUTCDate()) + - 'T' + lz(d.getUTCHours()) + ':' + lz(d.getUTCMinutes()) + - ':' + lz(d.getUTCSeconds()) + '.' + (m > 99 ? m : '0' + lz(m)) + 'Z'; - } - }); - -/***/ }, -/* 156 */ -/***/ function(module, exports, __webpack_require__) { - - var DateProto = Date.prototype - , INVALID_DATE = 'Invalid Date' - , TO_STRING = 'toString' - , $toString = DateProto[TO_STRING] - , getTime = DateProto.getTime; - if(new Date(NaN) + '' != INVALID_DATE){ - __webpack_require__(18)(DateProto, TO_STRING, function toString(){ - var value = getTime.call(this); - return value === value ? $toString.call(this) : INVALID_DATE; - }); - } - -/***/ }, -/* 157 */ -/***/ function(module, exports, __webpack_require__) { - - var TO_PRIMITIVE = __webpack_require__(25)('toPrimitive') - , proto = Date.prototype; - - if(!(TO_PRIMITIVE in proto))__webpack_require__(10)(proto, TO_PRIMITIVE, __webpack_require__(158)); - -/***/ }, -/* 158 */ -/***/ function(module, exports, __webpack_require__) { - - 'use strict'; - var anObject = __webpack_require__(12) - , toPrimitive = __webpack_require__(16) - , NUMBER = 'number'; - - module.exports = function(hint){ - if(hint !== 'string' && hint !== NUMBER && hint !== 'default')throw TypeError('Incorrect hint'); - return toPrimitive(anObject(this), hint != NUMBER); - }; - -/***/ }, -/* 159 */ -/***/ function(module, exports, __webpack_require__) { - - // 22.1.2.2 / 15.4.3.2 Array.isArray(arg) - var $export = __webpack_require__(8); - - $export($export.S, 'Array', {isArray: __webpack_require__(45)}); - -/***/ }, -/* 160 */ -/***/ function(module, exports, __webpack_require__) { - - 'use strict'; - var ctx = __webpack_require__(20) - , $export = __webpack_require__(8) - , toObject = __webpack_require__(58) - , call = __webpack_require__(161) - , isArrayIter = __webpack_require__(162) - , toLength = __webpack_require__(37) - , createProperty = __webpack_require__(163) - , getIterFn = __webpack_require__(164); - - $export($export.S + $export.F * !__webpack_require__(165)(function(iter){ Array.from(iter); }), 'Array', { - // 22.1.2.1 Array.from(arrayLike, mapfn = undefined, thisArg = undefined) - from: function from(arrayLike/*, mapfn = undefined, thisArg = undefined*/){ - var O = toObject(arrayLike) - , C = typeof this == 'function' ? this : Array - , aLen = arguments.length - , mapfn = aLen > 1 ? arguments[1] : undefined - , mapping = mapfn !== undefined - , index = 0 - , iterFn = getIterFn(O) - , length, result, step, iterator; - if(mapping)mapfn = ctx(mapfn, aLen > 2 ? arguments[2] : undefined, 2); - // if object isn't iterable or it's array with default iterator - use simple case - if(iterFn != undefined && !(C == Array && isArrayIter(iterFn))){ - for(iterator = iterFn.call(O), result = new C; !(step = iterator.next()).done; index++){ - createProperty(result, index, mapping ? call(iterator, mapfn, [step.value, index], true) : step.value); - } - } else { - length = toLength(O.length); - for(result = new C(length); length > index; index++){ - createProperty(result, index, mapping ? mapfn(O[index], index) : O[index]); - } - } - result.length = index; - return result; - } - }); - - -/***/ }, -/* 161 */ -/***/ function(module, exports, __webpack_require__) { - - // call something on iterator step with safe closing on error - var anObject = __webpack_require__(12); - module.exports = function(iterator, fn, value, entries){ - try { - return entries ? fn(anObject(value)[0], value[1]) : fn(value); - // 7.4.6 IteratorClose(iterator, completion) - } catch(e){ - var ret = iterator['return']; - if(ret !== undefined)anObject(ret.call(iterator)); - throw e; - } - }; - -/***/ }, -/* 162 */ -/***/ function(module, exports, __webpack_require__) { - - // check on default Array iterator - var Iterators = __webpack_require__(129) - , ITERATOR = __webpack_require__(25)('iterator') - , ArrayProto = Array.prototype; - - module.exports = function(it){ - return it !== undefined && (Iterators.Array === it || ArrayProto[ITERATOR] === it); - }; - -/***/ }, -/* 163 */ -/***/ function(module, exports, __webpack_require__) { - - 'use strict'; - var $defineProperty = __webpack_require__(11) - , createDesc = __webpack_require__(17); - - module.exports = function(object, index, value){ - if(index in object)$defineProperty.f(object, index, createDesc(0, value)); - else object[index] = value; - }; - -/***/ }, -/* 164 */ -/***/ function(module, exports, __webpack_require__) { - - var classof = __webpack_require__(75) - , ITERATOR = __webpack_require__(25)('iterator') - , Iterators = __webpack_require__(129); - module.exports = __webpack_require__(9).getIteratorMethod = function(it){ - if(it != undefined)return it[ITERATOR] - || it['@@iterator'] - || Iterators[classof(it)]; - }; - -/***/ }, -/* 165 */ -/***/ function(module, exports, __webpack_require__) { - - var ITERATOR = __webpack_require__(25)('iterator') - , SAFE_CLOSING = false; - - try { - var riter = [7][ITERATOR](); - riter['return'] = function(){ SAFE_CLOSING = true; }; - Array.from(riter, function(){ throw 2; }); - } catch(e){ /* empty */ } - - module.exports = function(exec, skipClosing){ - if(!skipClosing && !SAFE_CLOSING)return false; - var safe = false; - try { - var arr = [7] - , iter = arr[ITERATOR](); - iter.next = function(){ return {done: safe = true}; }; - arr[ITERATOR] = function(){ return iter; }; - exec(arr); - } catch(e){ /* empty */ } - return safe; - }; - -/***/ }, -/* 166 */ -/***/ function(module, exports, __webpack_require__) { - - 'use strict'; - var $export = __webpack_require__(8) - , createProperty = __webpack_require__(163); - - // WebKit Array.of isn't generic - $export($export.S + $export.F * __webpack_require__(7)(function(){ - function F(){} - return !(Array.of.call(F) instanceof F); - }), 'Array', { - // 22.1.2.3 Array.of( ...items) - of: function of(/* ...args */){ - var index = 0 - , aLen = arguments.length - , result = new (typeof this == 'function' ? this : Array)(aLen); - while(aLen > index)createProperty(result, index, arguments[index++]); - result.length = aLen; - return result; - } - }); - -/***/ }, -/* 167 */ -/***/ function(module, exports, __webpack_require__) { - - 'use strict'; - // 22.1.3.13 Array.prototype.join(separator) - var $export = __webpack_require__(8) - , toIObject = __webpack_require__(32) - , arrayJoin = [].join; - - // fallback for not array-like strings - $export($export.P + $export.F * (__webpack_require__(33) != Object || !__webpack_require__(168)(arrayJoin)), 'Array', { - join: function join(separator){ - return arrayJoin.call(toIObject(this), separator === undefined ? ',' : separator); - } - }); - -/***/ }, -/* 168 */ -/***/ function(module, exports, __webpack_require__) { - - var fails = __webpack_require__(7); - - module.exports = function(method, arg){ - return !!method && fails(function(){ - arg ? method.call(null, function(){}, 1) : method.call(null); - }); - }; - -/***/ }, -/* 169 */ -/***/ function(module, exports, __webpack_require__) { - - 'use strict'; - var $export = __webpack_require__(8) - , html = __webpack_require__(48) - , cof = __webpack_require__(34) - , toIndex = __webpack_require__(39) - , toLength = __webpack_require__(37) - , arraySlice = [].slice; - - // fallback for not array-like ES3 strings and DOM objects - $export($export.P + $export.F * __webpack_require__(7)(function(){ - if(html)arraySlice.call(html); - }), 'Array', { - slice: function slice(begin, end){ - var len = toLength(this.length) - , klass = cof(this); - end = end === undefined ? len : end; - if(klass == 'Array')return arraySlice.call(this, begin, end); - var start = toIndex(begin, len) - , upTo = toIndex(end, len) - , size = toLength(upTo - start) - , cloned = Array(size) - , i = 0; - for(; i < size; i++)cloned[i] = klass == 'String' - ? this.charAt(start + i) - : this[start + i]; - return cloned; - } - }); - -/***/ }, -/* 170 */ -/***/ function(module, exports, __webpack_require__) { - - 'use strict'; - var $export = __webpack_require__(8) - , aFunction = __webpack_require__(21) - , toObject = __webpack_require__(58) - , fails = __webpack_require__(7) - , $sort = [].sort - , test = [1, 2, 3]; - - $export($export.P + $export.F * (fails(function(){ - // IE8- - test.sort(undefined); - }) || !fails(function(){ - // V8 bug - test.sort(null); - // Old WebKit - }) || !__webpack_require__(168)($sort)), 'Array', { - // 22.1.3.25 Array.prototype.sort(comparefn) - sort: function sort(comparefn){ - return comparefn === undefined - ? $sort.call(toObject(this)) - : $sort.call(toObject(this), aFunction(comparefn)); - } - }); - -/***/ }, -/* 171 */ -/***/ function(module, exports, __webpack_require__) { - - 'use strict'; - var $export = __webpack_require__(8) - , $forEach = __webpack_require__(172)(0) - , STRICT = __webpack_require__(168)([].forEach, true); - - $export($export.P + $export.F * !STRICT, 'Array', { - // 22.1.3.10 / 15.4.4.18 Array.prototype.forEach(callbackfn [, thisArg]) - forEach: function forEach(callbackfn /* , thisArg */){ - return $forEach(this, callbackfn, arguments[1]); - } - }); - -/***/ }, -/* 172 */ -/***/ function(module, exports, __webpack_require__) { - - // 0 -> Array#forEach - // 1 -> Array#map - // 2 -> Array#filter - // 3 -> Array#some - // 4 -> Array#every - // 5 -> Array#find - // 6 -> Array#findIndex - var ctx = __webpack_require__(20) - , IObject = __webpack_require__(33) - , toObject = __webpack_require__(58) - , toLength = __webpack_require__(37) - , asc = __webpack_require__(173); - module.exports = function(TYPE, $create){ - var IS_MAP = TYPE == 1 - , IS_FILTER = TYPE == 2 - , IS_SOME = TYPE == 3 - , IS_EVERY = TYPE == 4 - , IS_FIND_INDEX = TYPE == 6 - , NO_HOLES = TYPE == 5 || IS_FIND_INDEX - , create = $create || asc; - return function($this, callbackfn, that){ - var O = toObject($this) - , self = IObject(O) - , f = ctx(callbackfn, that, 3) - , length = toLength(self.length) - , index = 0 - , result = IS_MAP ? create($this, length) : IS_FILTER ? create($this, 0) : undefined - , val, res; - for(;length > index; index++)if(NO_HOLES || index in self){ - val = self[index]; - res = f(val, index, O); - if(TYPE){ - if(IS_MAP)result[index] = res; // map - else if(res)switch(TYPE){ - case 3: return true; // some - case 5: return val; // find - case 6: return index; // findIndex - case 2: result.push(val); // filter - } else if(IS_EVERY)return false; // every - } - } - return IS_FIND_INDEX ? -1 : IS_SOME || IS_EVERY ? IS_EVERY : result; - }; - }; - -/***/ }, -/* 173 */ -/***/ function(module, exports, __webpack_require__) { - - // 9.4.2.3 ArraySpeciesCreate(originalArray, length) - var speciesConstructor = __webpack_require__(174); - - module.exports = function(original, length){ - return new (speciesConstructor(original))(length); - }; - -/***/ }, -/* 174 */ -/***/ function(module, exports, __webpack_require__) { - - var isObject = __webpack_require__(13) - , isArray = __webpack_require__(45) - , SPECIES = __webpack_require__(25)('species'); - - module.exports = function(original){ - var C; - if(isArray(original)){ - C = original.constructor; - // cross-realm fallback - if(typeof C == 'function' && (C === Array || isArray(C.prototype)))C = undefined; - if(isObject(C)){ - C = C[SPECIES]; - if(C === null)C = undefined; - } - } return C === undefined ? Array : C; - }; - -/***/ }, -/* 175 */ -/***/ function(module, exports, __webpack_require__) { - - 'use strict'; - var $export = __webpack_require__(8) - , $map = __webpack_require__(172)(1); - - $export($export.P + $export.F * !__webpack_require__(168)([].map, true), 'Array', { - // 22.1.3.15 / 15.4.4.19 Array.prototype.map(callbackfn [, thisArg]) - map: function map(callbackfn /* , thisArg */){ - return $map(this, callbackfn, arguments[1]); - } - }); - -/***/ }, -/* 176 */ -/***/ function(module, exports, __webpack_require__) { - - 'use strict'; - var $export = __webpack_require__(8) - , $filter = __webpack_require__(172)(2); - - $export($export.P + $export.F * !__webpack_require__(168)([].filter, true), 'Array', { - // 22.1.3.7 / 15.4.4.20 Array.prototype.filter(callbackfn [, thisArg]) - filter: function filter(callbackfn /* , thisArg */){ - return $filter(this, callbackfn, arguments[1]); - } - }); - -/***/ }, -/* 177 */ -/***/ function(module, exports, __webpack_require__) { - - 'use strict'; - var $export = __webpack_require__(8) - , $some = __webpack_require__(172)(3); - - $export($export.P + $export.F * !__webpack_require__(168)([].some, true), 'Array', { - // 22.1.3.23 / 15.4.4.17 Array.prototype.some(callbackfn [, thisArg]) - some: function some(callbackfn /* , thisArg */){ - return $some(this, callbackfn, arguments[1]); - } - }); - -/***/ }, -/* 178 */ -/***/ function(module, exports, __webpack_require__) { - - 'use strict'; - var $export = __webpack_require__(8) - , $every = __webpack_require__(172)(4); - - $export($export.P + $export.F * !__webpack_require__(168)([].every, true), 'Array', { - // 22.1.3.5 / 15.4.4.16 Array.prototype.every(callbackfn [, thisArg]) - every: function every(callbackfn /* , thisArg */){ - return $every(this, callbackfn, arguments[1]); - } - }); - -/***/ }, -/* 179 */ -/***/ function(module, exports, __webpack_require__) { - - 'use strict'; - var $export = __webpack_require__(8) - , $reduce = __webpack_require__(180); - - $export($export.P + $export.F * !__webpack_require__(168)([].reduce, true), 'Array', { - // 22.1.3.18 / 15.4.4.21 Array.prototype.reduce(callbackfn [, initialValue]) - reduce: function reduce(callbackfn /* , initialValue */){ - return $reduce(this, callbackfn, arguments.length, arguments[1], false); - } - }); - -/***/ }, -/* 180 */ -/***/ function(module, exports, __webpack_require__) { - - var aFunction = __webpack_require__(21) - , toObject = __webpack_require__(58) - , IObject = __webpack_require__(33) - , toLength = __webpack_require__(37); - - module.exports = function(that, callbackfn, aLen, memo, isRight){ - aFunction(callbackfn); - var O = toObject(that) - , self = IObject(O) - , length = toLength(O.length) - , index = isRight ? length - 1 : 0 - , i = isRight ? -1 : 1; - if(aLen < 2)for(;;){ - if(index in self){ - memo = self[index]; - index += i; - break; - } - index += i; - if(isRight ? index < 0 : length <= index){ - throw TypeError('Reduce of empty array with no initial value'); - } - } - for(;isRight ? index >= 0 : length > index; index += i)if(index in self){ - memo = callbackfn(memo, self[index], index, O); - } - return memo; - }; - -/***/ }, -/* 181 */ -/***/ function(module, exports, __webpack_require__) { - - 'use strict'; - var $export = __webpack_require__(8) - , $reduce = __webpack_require__(180); - - $export($export.P + $export.F * !__webpack_require__(168)([].reduceRight, true), 'Array', { - // 22.1.3.19 / 15.4.4.22 Array.prototype.reduceRight(callbackfn [, initialValue]) - reduceRight: function reduceRight(callbackfn /* , initialValue */){ - return $reduce(this, callbackfn, arguments.length, arguments[1], true); - } - }); - -/***/ }, -/* 182 */ -/***/ function(module, exports, __webpack_require__) { - - 'use strict'; - var $export = __webpack_require__(8) - , $indexOf = __webpack_require__(36)(false) - , $native = [].indexOf - , NEGATIVE_ZERO = !!$native && 1 / [1].indexOf(1, -0) < 0; - - $export($export.P + $export.F * (NEGATIVE_ZERO || !__webpack_require__(168)($native)), 'Array', { - // 22.1.3.11 / 15.4.4.14 Array.prototype.indexOf(searchElement [, fromIndex]) - indexOf: function indexOf(searchElement /*, fromIndex = 0 */){ - return NEGATIVE_ZERO - // convert -0 to +0 - ? $native.apply(this, arguments) || 0 - : $indexOf(this, searchElement, arguments[1]); - } - }); - -/***/ }, -/* 183 */ -/***/ function(module, exports, __webpack_require__) { - - 'use strict'; - var $export = __webpack_require__(8) - , toIObject = __webpack_require__(32) - , toInteger = __webpack_require__(38) - , toLength = __webpack_require__(37) - , $native = [].lastIndexOf - , NEGATIVE_ZERO = !!$native && 1 / [1].lastIndexOf(1, -0) < 0; - - $export($export.P + $export.F * (NEGATIVE_ZERO || !__webpack_require__(168)($native)), 'Array', { - // 22.1.3.14 / 15.4.4.15 Array.prototype.lastIndexOf(searchElement [, fromIndex]) - lastIndexOf: function lastIndexOf(searchElement /*, fromIndex = @[*-1] */){ - // convert -0 to +0 - if(NEGATIVE_ZERO)return $native.apply(this, arguments) || 0; - var O = toIObject(this) - , length = toLength(O.length) - , index = length - 1; - if(arguments.length > 1)index = Math.min(index, toInteger(arguments[1])); - if(index < 0)index = length + index; - for(;index >= 0; index--)if(index in O)if(O[index] === searchElement)return index || 0; - return -1; - } - }); - -/***/ }, -/* 184 */ -/***/ function(module, exports, __webpack_require__) { - - // 22.1.3.3 Array.prototype.copyWithin(target, start, end = this.length) - var $export = __webpack_require__(8); - - $export($export.P, 'Array', {copyWithin: __webpack_require__(185)}); - - __webpack_require__(186)('copyWithin'); - -/***/ }, -/* 185 */ -/***/ function(module, exports, __webpack_require__) { - - // 22.1.3.3 Array.prototype.copyWithin(target, start, end = this.length) - 'use strict'; - var toObject = __webpack_require__(58) - , toIndex = __webpack_require__(39) - , toLength = __webpack_require__(37); - - module.exports = [].copyWithin || function copyWithin(target/*= 0*/, start/*= 0, end = @length*/){ - var O = toObject(this) - , len = toLength(O.length) - , to = toIndex(target, len) - , from = toIndex(start, len) - , end = arguments.length > 2 ? arguments[2] : undefined - , count = Math.min((end === undefined ? len : toIndex(end, len)) - from, len - to) - , inc = 1; - if(from < to && to < from + count){ - inc = -1; - from += count - 1; - to += count - 1; - } - while(count-- > 0){ - if(from in O)O[to] = O[from]; - else delete O[to]; - to += inc; - from += inc; - } return O; - }; - -/***/ }, -/* 186 */ -/***/ function(module, exports, __webpack_require__) { - - // 22.1.3.31 Array.prototype[@@unscopables] - var UNSCOPABLES = __webpack_require__(25)('unscopables') - , ArrayProto = Array.prototype; - if(ArrayProto[UNSCOPABLES] == undefined)__webpack_require__(10)(ArrayProto, UNSCOPABLES, {}); - module.exports = function(key){ - ArrayProto[UNSCOPABLES][key] = true; - }; - -/***/ }, -/* 187 */ -/***/ function(module, exports, __webpack_require__) { - - // 22.1.3.6 Array.prototype.fill(value, start = 0, end = this.length) - var $export = __webpack_require__(8); - - $export($export.P, 'Array', {fill: __webpack_require__(188)}); - - __webpack_require__(186)('fill'); - -/***/ }, -/* 188 */ -/***/ function(module, exports, __webpack_require__) { - - // 22.1.3.6 Array.prototype.fill(value, start = 0, end = this.length) - 'use strict'; - var toObject = __webpack_require__(58) - , toIndex = __webpack_require__(39) - , toLength = __webpack_require__(37); - module.exports = function fill(value /*, start = 0, end = @length */){ - var O = toObject(this) - , length = toLength(O.length) - , aLen = arguments.length - , index = toIndex(aLen > 1 ? arguments[1] : undefined, length) - , end = aLen > 2 ? arguments[2] : undefined - , endPos = end === undefined ? length : toIndex(end, length); - while(endPos > index)O[index++] = value; - return O; - }; - -/***/ }, -/* 189 */ -/***/ function(module, exports, __webpack_require__) { - - 'use strict'; - // 22.1.3.8 Array.prototype.find(predicate, thisArg = undefined) - var $export = __webpack_require__(8) - , $find = __webpack_require__(172)(5) - , KEY = 'find' - , forced = true; - // Shouldn't skip holes - if(KEY in [])Array(1)[KEY](function(){ forced = false; }); - $export($export.P + $export.F * forced, 'Array', { - find: function find(callbackfn/*, that = undefined */){ - return $find(this, callbackfn, arguments.length > 1 ? arguments[1] : undefined); - } - }); - __webpack_require__(186)(KEY); - -/***/ }, -/* 190 */ -/***/ function(module, exports, __webpack_require__) { - - 'use strict'; - // 22.1.3.9 Array.prototype.findIndex(predicate, thisArg = undefined) - var $export = __webpack_require__(8) - , $find = __webpack_require__(172)(6) - , KEY = 'findIndex' - , forced = true; - // Shouldn't skip holes - if(KEY in [])Array(1)[KEY](function(){ forced = false; }); - $export($export.P + $export.F * forced, 'Array', { - findIndex: function findIndex(callbackfn/*, that = undefined */){ - return $find(this, callbackfn, arguments.length > 1 ? arguments[1] : undefined); - } - }); - __webpack_require__(186)(KEY); - -/***/ }, -/* 191 */ -/***/ function(module, exports, __webpack_require__) { - - __webpack_require__(192)('Array'); - -/***/ }, -/* 192 */ -/***/ function(module, exports, __webpack_require__) { - - 'use strict'; - var global = __webpack_require__(4) - , dP = __webpack_require__(11) - , DESCRIPTORS = __webpack_require__(6) - , SPECIES = __webpack_require__(25)('species'); - - module.exports = function(KEY){ - var C = global[KEY]; - if(DESCRIPTORS && C && !C[SPECIES])dP.f(C, SPECIES, { - configurable: true, - get: function(){ return this; } - }); - }; - -/***/ }, -/* 193 */ -/***/ function(module, exports, __webpack_require__) { - - 'use strict'; - var addToUnscopables = __webpack_require__(186) - , step = __webpack_require__(194) - , Iterators = __webpack_require__(129) - , toIObject = __webpack_require__(32); - - // 22.1.3.4 Array.prototype.entries() - // 22.1.3.13 Array.prototype.keys() - // 22.1.3.29 Array.prototype.values() - // 22.1.3.30 Array.prototype[@@iterator]() - module.exports = __webpack_require__(128)(Array, 'Array', function(iterated, kind){ - this._t = toIObject(iterated); // target - this._i = 0; // next index - this._k = kind; // kind - // 22.1.5.2.1 %ArrayIteratorPrototype%.next() - }, function(){ - var O = this._t - , kind = this._k - , index = this._i++; - if(!O || index >= O.length){ - this._t = undefined; - return step(1); - } - if(kind == 'keys' )return step(0, index); - if(kind == 'values')return step(0, O[index]); - return step(0, [index, O[index]]); - }, 'values'); - - // argumentsList[@@iterator] is %ArrayProto_values% (9.4.4.6, 9.4.4.7) - Iterators.Arguments = Iterators.Array; - - addToUnscopables('keys'); - addToUnscopables('values'); - addToUnscopables('entries'); - -/***/ }, -/* 194 */ -/***/ function(module, exports) { - - module.exports = function(done, value){ - return {value: value, done: !!done}; - }; - -/***/ }, -/* 195 */ -/***/ function(module, exports, __webpack_require__) { - - var global = __webpack_require__(4) - , inheritIfRequired = __webpack_require__(88) - , dP = __webpack_require__(11).f - , gOPN = __webpack_require__(50).f - , isRegExp = __webpack_require__(134) - , $flags = __webpack_require__(196) - , $RegExp = global.RegExp - , Base = $RegExp - , proto = $RegExp.prototype - , re1 = /a/g - , re2 = /a/g - // "new" creates a new object, old webkit buggy here - , CORRECT_NEW = new $RegExp(re1) !== re1; - - if(__webpack_require__(6) && (!CORRECT_NEW || __webpack_require__(7)(function(){ - re2[__webpack_require__(25)('match')] = false; - // RegExp constructor can alter flags and IsRegExp works correct with @@match - return $RegExp(re1) != re1 || $RegExp(re2) == re2 || $RegExp(re1, 'i') != '/a/i'; - }))){ - $RegExp = function RegExp(p, f){ - var tiRE = this instanceof $RegExp - , piRE = isRegExp(p) - , fiU = f === undefined; - return !tiRE && piRE && p.constructor === $RegExp && fiU ? p - : inheritIfRequired(CORRECT_NEW - ? new Base(piRE && !fiU ? p.source : p, f) - : Base((piRE = p instanceof $RegExp) ? p.source : p, piRE && fiU ? $flags.call(p) : f) - , tiRE ? this : proto, $RegExp); - }; - var proxy = function(key){ - key in $RegExp || dP($RegExp, key, { - configurable: true, - get: function(){ return Base[key]; }, - set: function(it){ Base[key] = it; } - }); - }; - for(var keys = gOPN(Base), i = 0; keys.length > i; )proxy(keys[i++]); - proto.constructor = $RegExp; - $RegExp.prototype = proto; - __webpack_require__(18)(global, 'RegExp', $RegExp); - } - - __webpack_require__(192)('RegExp'); - -/***/ }, -/* 196 */ -/***/ function(module, exports, __webpack_require__) { - - 'use strict'; - // 21.2.5.3 get RegExp.prototype.flags - var anObject = __webpack_require__(12); - module.exports = function(){ - var that = anObject(this) - , result = ''; - if(that.global) result += 'g'; - if(that.ignoreCase) result += 'i'; - if(that.multiline) result += 'm'; - if(that.unicode) result += 'u'; - if(that.sticky) result += 'y'; - return result; - }; - -/***/ }, -/* 197 */ -/***/ function(module, exports, __webpack_require__) { - - 'use strict'; - __webpack_require__(198); - var anObject = __webpack_require__(12) - , $flags = __webpack_require__(196) - , DESCRIPTORS = __webpack_require__(6) - , TO_STRING = 'toString' - , $toString = /./[TO_STRING]; - - var define = function(fn){ - __webpack_require__(18)(RegExp.prototype, TO_STRING, fn, true); - }; - - // 21.2.5.14 RegExp.prototype.toString() - if(__webpack_require__(7)(function(){ return $toString.call({source: 'a', flags: 'b'}) != '/a/b'; })){ - define(function toString(){ - var R = anObject(this); - return '/'.concat(R.source, '/', - 'flags' in R ? R.flags : !DESCRIPTORS && R instanceof RegExp ? $flags.call(R) : undefined); - }); - // FF44- RegExp#toString has a wrong name - } else if($toString.name != TO_STRING){ - define(function toString(){ - return $toString.call(this); - }); - } - -/***/ }, -/* 198 */ -/***/ function(module, exports, __webpack_require__) { - - // 21.2.5.3 get RegExp.prototype.flags() - if(__webpack_require__(6) && /./g.flags != 'g')__webpack_require__(11).f(RegExp.prototype, 'flags', { - configurable: true, - get: __webpack_require__(196) - }); - -/***/ }, -/* 199 */ -/***/ function(module, exports, __webpack_require__) { - - // @@match logic - __webpack_require__(200)('match', 1, function(defined, MATCH, $match){ - // 21.1.3.11 String.prototype.match(regexp) - return [function match(regexp){ - 'use strict'; - var O = defined(this) - , fn = regexp == undefined ? undefined : regexp[MATCH]; - return fn !== undefined ? fn.call(regexp, O) : new RegExp(regexp)[MATCH](String(O)); - }, $match]; - }); - -/***/ }, -/* 200 */ -/***/ function(module, exports, __webpack_require__) { - - 'use strict'; - var hide = __webpack_require__(10) - , redefine = __webpack_require__(18) - , fails = __webpack_require__(7) - , defined = __webpack_require__(35) - , wks = __webpack_require__(25); - - module.exports = function(KEY, length, exec){ - var SYMBOL = wks(KEY) - , fns = exec(defined, SYMBOL, ''[KEY]) - , strfn = fns[0] - , rxfn = fns[1]; - if(fails(function(){ - var O = {}; - O[SYMBOL] = function(){ return 7; }; - return ''[KEY](O) != 7; - })){ - redefine(String.prototype, KEY, strfn); - hide(RegExp.prototype, SYMBOL, length == 2 - // 21.2.5.8 RegExp.prototype[@@replace](string, replaceValue) - // 21.2.5.11 RegExp.prototype[@@split](string, limit) - ? function(string, arg){ return rxfn.call(string, this, arg); } - // 21.2.5.6 RegExp.prototype[@@match](string) - // 21.2.5.9 RegExp.prototype[@@search](string) - : function(string){ return rxfn.call(string, this); } - ); - } - }; - -/***/ }, -/* 201 */ -/***/ function(module, exports, __webpack_require__) { - - // @@replace logic - __webpack_require__(200)('replace', 2, function(defined, REPLACE, $replace){ - // 21.1.3.14 String.prototype.replace(searchValue, replaceValue) - return [function replace(searchValue, replaceValue){ - 'use strict'; - var O = defined(this) - , fn = searchValue == undefined ? undefined : searchValue[REPLACE]; - return fn !== undefined - ? fn.call(searchValue, O, replaceValue) - : $replace.call(String(O), searchValue, replaceValue); - }, $replace]; - }); - -/***/ }, -/* 202 */ -/***/ function(module, exports, __webpack_require__) { - - // @@search logic - __webpack_require__(200)('search', 1, function(defined, SEARCH, $search){ - // 21.1.3.15 String.prototype.search(regexp) - return [function search(regexp){ - 'use strict'; - var O = defined(this) - , fn = regexp == undefined ? undefined : regexp[SEARCH]; - return fn !== undefined ? fn.call(regexp, O) : new RegExp(regexp)[SEARCH](String(O)); - }, $search]; - }); - -/***/ }, -/* 203 */ -/***/ function(module, exports, __webpack_require__) { - - // @@split logic - __webpack_require__(200)('split', 2, function(defined, SPLIT, $split){ - 'use strict'; - var isRegExp = __webpack_require__(134) - , _split = $split - , $push = [].push - , $SPLIT = 'split' - , LENGTH = 'length' - , LAST_INDEX = 'lastIndex'; - if( - 'abbc'[$SPLIT](/(b)*/)[1] == 'c' || - 'test'[$SPLIT](/(?:)/, -1)[LENGTH] != 4 || - 'ab'[$SPLIT](/(?:ab)*/)[LENGTH] != 2 || - '.'[$SPLIT](/(.?)(.?)/)[LENGTH] != 4 || - '.'[$SPLIT](/()()/)[LENGTH] > 1 || - ''[$SPLIT](/.?/)[LENGTH] - ){ - var NPCG = /()??/.exec('')[1] === undefined; // nonparticipating capturing group - // based on es5-shim implementation, need to rework it - $split = function(separator, limit){ - var string = String(this); - if(separator === undefined && limit === 0)return []; - // If `separator` is not a regex, use native split - if(!isRegExp(separator))return _split.call(string, separator, limit); - var output = []; - var flags = (separator.ignoreCase ? 'i' : '') + - (separator.multiline ? 'm' : '') + - (separator.unicode ? 'u' : '') + - (separator.sticky ? 'y' : ''); - var lastLastIndex = 0; - var splitLimit = limit === undefined ? 4294967295 : limit >>> 0; - // Make `global` and avoid `lastIndex` issues by working with a copy - var separatorCopy = new RegExp(separator.source, flags + 'g'); - var separator2, match, lastIndex, lastLength, i; - // Doesn't need flags gy, but they don't hurt - if(!NPCG)separator2 = new RegExp('^' + separatorCopy.source + '$(?!\\s)', flags); - while(match = separatorCopy.exec(string)){ - // `separatorCopy.lastIndex` is not reliable cross-browser - lastIndex = match.index + match[0][LENGTH]; - if(lastIndex > lastLastIndex){ - output.push(string.slice(lastLastIndex, match.index)); - // Fix browsers whose `exec` methods don't consistently return `undefined` for NPCG - if(!NPCG && match[LENGTH] > 1)match[0].replace(separator2, function(){ - for(i = 1; i < arguments[LENGTH] - 2; i++)if(arguments[i] === undefined)match[i] = undefined; - }); - if(match[LENGTH] > 1 && match.index < string[LENGTH])$push.apply(output, match.slice(1)); - lastLength = match[0][LENGTH]; - lastLastIndex = lastIndex; - if(output[LENGTH] >= splitLimit)break; - } - if(separatorCopy[LAST_INDEX] === match.index)separatorCopy[LAST_INDEX]++; // Avoid an infinite loop - } - if(lastLastIndex === string[LENGTH]){ - if(lastLength || !separatorCopy.test(''))output.push(''); - } else output.push(string.slice(lastLastIndex)); - return output[LENGTH] > splitLimit ? output.slice(0, splitLimit) : output; - }; - // Chakra, V8 - } else if('0'[$SPLIT](undefined, 0)[LENGTH]){ - $split = function(separator, limit){ - return separator === undefined && limit === 0 ? [] : _split.call(this, separator, limit); - }; - } - // 21.1.3.17 String.prototype.split(separator, limit) - return [function split(separator, limit){ - var O = defined(this) - , fn = separator == undefined ? undefined : separator[SPLIT]; - return fn !== undefined ? fn.call(separator, O, limit) : $split.call(String(O), separator, limit); - }, $split]; - }); - -/***/ }, -/* 204 */ -/***/ function(module, exports, __webpack_require__) { - - 'use strict'; - var LIBRARY = __webpack_require__(28) - , global = __webpack_require__(4) - , ctx = __webpack_require__(20) - , classof = __webpack_require__(75) - , $export = __webpack_require__(8) - , isObject = __webpack_require__(13) - , aFunction = __webpack_require__(21) - , anInstance = __webpack_require__(205) - , forOf = __webpack_require__(206) - , speciesConstructor = __webpack_require__(207) - , task = __webpack_require__(208).set - , microtask = __webpack_require__(209)() - , PROMISE = 'Promise' - , TypeError = global.TypeError - , process = global.process - , $Promise = global[PROMISE] - , process = global.process - , isNode = classof(process) == 'process' - , empty = function(){ /* empty */ } - , Internal, GenericPromiseCapability, Wrapper; - - var USE_NATIVE = !!function(){ - try { - // correct subclassing with @@species support - var promise = $Promise.resolve(1) - , FakePromise = (promise.constructor = {})[__webpack_require__(25)('species')] = function(exec){ exec(empty, empty); }; - // unhandled rejections tracking support, NodeJS Promise without it fails @@species test - return (isNode || typeof PromiseRejectionEvent == 'function') && promise.then(empty) instanceof FakePromise; - } catch(e){ /* empty */ } - }(); - - // helpers - var sameConstructor = function(a, b){ - // with library wrapper special case - return a === b || a === $Promise && b === Wrapper; - }; - var isThenable = function(it){ - var then; - return isObject(it) && typeof (then = it.then) == 'function' ? then : false; - }; - var newPromiseCapability = function(C){ - return sameConstructor($Promise, C) - ? new PromiseCapability(C) - : new GenericPromiseCapability(C); - }; - var PromiseCapability = GenericPromiseCapability = function(C){ - var resolve, reject; - this.promise = new C(function($$resolve, $$reject){ - if(resolve !== undefined || reject !== undefined)throw TypeError('Bad Promise constructor'); - resolve = $$resolve; - reject = $$reject; - }); - this.resolve = aFunction(resolve); - this.reject = aFunction(reject); - }; - var perform = function(exec){ - try { - exec(); - } catch(e){ - return {error: e}; - } - }; - var notify = function(promise, isReject){ - if(promise._n)return; - promise._n = true; - var chain = promise._c; - microtask(function(){ - var value = promise._v - , ok = promise._s == 1 - , i = 0; - var run = function(reaction){ - var handler = ok ? reaction.ok : reaction.fail - , resolve = reaction.resolve - , reject = reaction.reject - , domain = reaction.domain - , result, then; - try { - if(handler){ - if(!ok){ - if(promise._h == 2)onHandleUnhandled(promise); - promise._h = 1; - } - if(handler === true)result = value; - else { - if(domain)domain.enter(); - result = handler(value); - if(domain)domain.exit(); - } - if(result === reaction.promise){ - reject(TypeError('Promise-chain cycle')); - } else if(then = isThenable(result)){ - then.call(result, resolve, reject); - } else resolve(result); - } else reject(value); - } catch(e){ - reject(e); - } - }; - while(chain.length > i)run(chain[i++]); // variable length - can't use forEach - promise._c = []; - promise._n = false; - if(isReject && !promise._h)onUnhandled(promise); - }); - }; - var onUnhandled = function(promise){ - task.call(global, function(){ - var value = promise._v - , abrupt, handler, console; - if(isUnhandled(promise)){ - abrupt = perform(function(){ - if(isNode){ - process.emit('unhandledRejection', value, promise); - } else if(handler = global.onunhandledrejection){ - handler({promise: promise, reason: value}); - } else if((console = global.console) && console.error){ - console.error('Unhandled promise rejection', value); - } - }); - // Browsers should not trigger `rejectionHandled` event if it was handled here, NodeJS - should - promise._h = isNode || isUnhandled(promise) ? 2 : 1; - } promise._a = undefined; - if(abrupt)throw abrupt.error; - }); - }; - var isUnhandled = function(promise){ - if(promise._h == 1)return false; - var chain = promise._a || promise._c - , i = 0 - , reaction; - while(chain.length > i){ - reaction = chain[i++]; - if(reaction.fail || !isUnhandled(reaction.promise))return false; - } return true; - }; - var onHandleUnhandled = function(promise){ - task.call(global, function(){ - var handler; - if(isNode){ - process.emit('rejectionHandled', promise); - } else if(handler = global.onrejectionhandled){ - handler({promise: promise, reason: promise._v}); - } - }); - }; - var $reject = function(value){ - var promise = this; - if(promise._d)return; - promise._d = true; - promise = promise._w || promise; // unwrap - promise._v = value; - promise._s = 2; - if(!promise._a)promise._a = promise._c.slice(); - notify(promise, true); - }; - var $resolve = function(value){ - var promise = this - , then; - if(promise._d)return; - promise._d = true; - promise = promise._w || promise; // unwrap - try { - if(promise === value)throw TypeError("Promise can't be resolved itself"); - if(then = isThenable(value)){ - microtask(function(){ - var wrapper = {_w: promise, _d: false}; // wrap - try { - then.call(value, ctx($resolve, wrapper, 1), ctx($reject, wrapper, 1)); - } catch(e){ - $reject.call(wrapper, e); - } - }); - } else { - promise._v = value; - promise._s = 1; - notify(promise, false); - } - } catch(e){ - $reject.call({_w: promise, _d: false}, e); // wrap - } - }; - - // constructor polyfill - if(!USE_NATIVE){ - // 25.4.3.1 Promise(executor) - $Promise = function Promise(executor){ - anInstance(this, $Promise, PROMISE, '_h'); - aFunction(executor); - Internal.call(this); - try { - executor(ctx($resolve, this, 1), ctx($reject, this, 1)); - } catch(err){ - $reject.call(this, err); - } - }; - Internal = function Promise(executor){ - this._c = []; // <- awaiting reactions - this._a = undefined; // <- checked in isUnhandled reactions - this._s = 0; // <- state - this._d = false; // <- done - this._v = undefined; // <- value - this._h = 0; // <- rejection state, 0 - default, 1 - handled, 2 - unhandled - this._n = false; // <- notify - }; - Internal.prototype = __webpack_require__(210)($Promise.prototype, { - // 25.4.5.3 Promise.prototype.then(onFulfilled, onRejected) - then: function then(onFulfilled, onRejected){ - var reaction = newPromiseCapability(speciesConstructor(this, $Promise)); - reaction.ok = typeof onFulfilled == 'function' ? onFulfilled : true; - reaction.fail = typeof onRejected == 'function' && onRejected; - reaction.domain = isNode ? process.domain : undefined; - this._c.push(reaction); - if(this._a)this._a.push(reaction); - if(this._s)notify(this, false); - return reaction.promise; - }, - // 25.4.5.1 Promise.prototype.catch(onRejected) - 'catch': function(onRejected){ - return this.then(undefined, onRejected); - } - }); - PromiseCapability = function(){ - var promise = new Internal; - this.promise = promise; - this.resolve = ctx($resolve, promise, 1); - this.reject = ctx($reject, promise, 1); - }; - } - - $export($export.G + $export.W + $export.F * !USE_NATIVE, {Promise: $Promise}); - __webpack_require__(24)($Promise, PROMISE); - __webpack_require__(192)(PROMISE); - Wrapper = __webpack_require__(9)[PROMISE]; - - // statics - $export($export.S + $export.F * !USE_NATIVE, PROMISE, { - // 25.4.4.5 Promise.reject(r) - reject: function reject(r){ - var capability = newPromiseCapability(this) - , $$reject = capability.reject; - $$reject(r); - return capability.promise; - } - }); - $export($export.S + $export.F * (LIBRARY || !USE_NATIVE), PROMISE, { - // 25.4.4.6 Promise.resolve(x) - resolve: function resolve(x){ - // instanceof instead of internal slot check because we should fix it without replacement native Promise core - if(x instanceof $Promise && sameConstructor(x.constructor, this))return x; - var capability = newPromiseCapability(this) - , $$resolve = capability.resolve; - $$resolve(x); - return capability.promise; - } - }); - $export($export.S + $export.F * !(USE_NATIVE && __webpack_require__(165)(function(iter){ - $Promise.all(iter)['catch'](empty); - })), PROMISE, { - // 25.4.4.1 Promise.all(iterable) - all: function all(iterable){ - var C = this - , capability = newPromiseCapability(C) - , resolve = capability.resolve - , reject = capability.reject; - var abrupt = perform(function(){ - var values = [] - , index = 0 - , remaining = 1; - forOf(iterable, false, function(promise){ - var $index = index++ - , alreadyCalled = false; - values.push(undefined); - remaining++; - C.resolve(promise).then(function(value){ - if(alreadyCalled)return; - alreadyCalled = true; - values[$index] = value; - --remaining || resolve(values); - }, reject); - }); - --remaining || resolve(values); - }); - if(abrupt)reject(abrupt.error); - return capability.promise; - }, - // 25.4.4.4 Promise.race(iterable) - race: function race(iterable){ - var C = this - , capability = newPromiseCapability(C) - , reject = capability.reject; - var abrupt = perform(function(){ - forOf(iterable, false, function(promise){ - C.resolve(promise).then(capability.resolve, reject); - }); - }); - if(abrupt)reject(abrupt.error); - return capability.promise; - } - }); - -/***/ }, -/* 205 */ -/***/ function(module, exports) { - - module.exports = function(it, Constructor, name, forbiddenField){ - if(!(it instanceof Constructor) || (forbiddenField !== undefined && forbiddenField in it)){ - throw TypeError(name + ': incorrect invocation!'); - } return it; - }; - -/***/ }, -/* 206 */ -/***/ function(module, exports, __webpack_require__) { - - var ctx = __webpack_require__(20) - , call = __webpack_require__(161) - , isArrayIter = __webpack_require__(162) - , anObject = __webpack_require__(12) - , toLength = __webpack_require__(37) - , getIterFn = __webpack_require__(164) - , BREAK = {} - , RETURN = {}; - var exports = module.exports = function(iterable, entries, fn, that, ITERATOR){ - var iterFn = ITERATOR ? function(){ return iterable; } : getIterFn(iterable) - , f = ctx(fn, that, entries ? 2 : 1) - , index = 0 - , length, step, iterator, result; - if(typeof iterFn != 'function')throw TypeError(iterable + ' is not iterable!'); - // fast case for arrays with default iterator - if(isArrayIter(iterFn))for(length = toLength(iterable.length); length > index; index++){ - result = entries ? f(anObject(step = iterable[index])[0], step[1]) : f(iterable[index]); - if(result === BREAK || result === RETURN)return result; - } else for(iterator = iterFn.call(iterable); !(step = iterator.next()).done; ){ - result = call(iterator, f, step.value, entries); - if(result === BREAK || result === RETURN)return result; - } - }; - exports.BREAK = BREAK; - exports.RETURN = RETURN; - -/***/ }, -/* 207 */ -/***/ function(module, exports, __webpack_require__) { - - // 7.3.20 SpeciesConstructor(O, defaultConstructor) - var anObject = __webpack_require__(12) - , aFunction = __webpack_require__(21) - , SPECIES = __webpack_require__(25)('species'); - module.exports = function(O, D){ - var C = anObject(O).constructor, S; - return C === undefined || (S = anObject(C)[SPECIES]) == undefined ? D : aFunction(S); - }; - -/***/ }, -/* 208 */ -/***/ function(module, exports, __webpack_require__) { - - var ctx = __webpack_require__(20) - , invoke = __webpack_require__(78) - , html = __webpack_require__(48) - , cel = __webpack_require__(15) - , global = __webpack_require__(4) - , process = global.process - , setTask = global.setImmediate - , clearTask = global.clearImmediate - , MessageChannel = global.MessageChannel - , counter = 0 - , queue = {} - , ONREADYSTATECHANGE = 'onreadystatechange' - , defer, channel, port; - var run = function(){ - var id = +this; - if(queue.hasOwnProperty(id)){ - var fn = queue[id]; - delete queue[id]; - fn(); - } - }; - var listener = function(event){ - run.call(event.data); - }; - // Node.js 0.9+ & IE10+ has setImmediate, otherwise: - if(!setTask || !clearTask){ - setTask = function setImmediate(fn){ - var args = [], i = 1; - while(arguments.length > i)args.push(arguments[i++]); - queue[++counter] = function(){ - invoke(typeof fn == 'function' ? fn : Function(fn), args); - }; - defer(counter); - return counter; - }; - clearTask = function clearImmediate(id){ - delete queue[id]; - }; - // Node.js 0.8- - if(__webpack_require__(34)(process) == 'process'){ - defer = function(id){ - process.nextTick(ctx(run, id, 1)); - }; - // Browsers with MessageChannel, includes WebWorkers - } else if(MessageChannel){ - channel = new MessageChannel; - port = channel.port2; - channel.port1.onmessage = listener; - defer = ctx(port.postMessage, port, 1); - // Browsers with postMessage, skip WebWorkers - // IE8 has postMessage, but it's sync & typeof its postMessage is 'object' - } else if(global.addEventListener && typeof postMessage == 'function' && !global.importScripts){ - defer = function(id){ - global.postMessage(id + '', '*'); - }; - global.addEventListener('message', listener, false); - // IE8- - } else if(ONREADYSTATECHANGE in cel('script')){ - defer = function(id){ - html.appendChild(cel('script'))[ONREADYSTATECHANGE] = function(){ - html.removeChild(this); - run.call(id); - }; - }; - // Rest old browsers - } else { - defer = function(id){ - setTimeout(ctx(run, id, 1), 0); - }; - } - } - module.exports = { - set: setTask, - clear: clearTask - }; - -/***/ }, -/* 209 */ -/***/ function(module, exports, __webpack_require__) { - - var global = __webpack_require__(4) - , macrotask = __webpack_require__(208).set - , Observer = global.MutationObserver || global.WebKitMutationObserver - , process = global.process - , Promise = global.Promise - , isNode = __webpack_require__(34)(process) == 'process'; - - module.exports = function(){ - var head, last, notify; - - var flush = function(){ - var parent, fn; - if(isNode && (parent = process.domain))parent.exit(); - while(head){ - fn = head.fn; - head = head.next; - try { - fn(); - } catch(e){ - if(head)notify(); - else last = undefined; - throw e; - } - } last = undefined; - if(parent)parent.enter(); - }; - - // Node.js - if(isNode){ - notify = function(){ - process.nextTick(flush); - }; - // browsers with MutationObserver - } else if(Observer){ - var toggle = true - , node = document.createTextNode(''); - new Observer(flush).observe(node, {characterData: true}); // eslint-disable-line no-new - notify = function(){ - node.data = toggle = !toggle; - }; - // environments with maybe non-completely correct, but existent Promise - } else if(Promise && Promise.resolve){ - var promise = Promise.resolve(); - notify = function(){ - promise.then(flush); - }; - // for other environments - macrotask based on: - // - setImmediate - // - MessageChannel - // - window.postMessag - // - onreadystatechange - // - setTimeout - } else { - notify = function(){ - // strange IE + webpack dev server bug - use .call(global) - macrotask.call(global, flush); - }; - } - - return function(fn){ - var task = {fn: fn, next: undefined}; - if(last)last.next = task; - if(!head){ - head = task; - notify(); - } last = task; - }; - }; - -/***/ }, -/* 210 */ -/***/ function(module, exports, __webpack_require__) { - - var redefine = __webpack_require__(18); - module.exports = function(target, src, safe){ - for(var key in src)redefine(target, key, src[key], safe); - return target; - }; - -/***/ }, -/* 211 */ -/***/ function(module, exports, __webpack_require__) { - - 'use strict'; - var strong = __webpack_require__(212); - - // 23.1 Map Objects - module.exports = __webpack_require__(213)('Map', function(get){ - return function Map(){ return get(this, arguments.length > 0 ? arguments[0] : undefined); }; - }, { - // 23.1.3.6 Map.prototype.get(key) - get: function get(key){ - var entry = strong.getEntry(this, key); - return entry && entry.v; - }, - // 23.1.3.9 Map.prototype.set(key, value) - set: function set(key, value){ - return strong.def(this, key === 0 ? 0 : key, value); - } - }, strong, true); - -/***/ }, -/* 212 */ -/***/ function(module, exports, __webpack_require__) { - - 'use strict'; - var dP = __webpack_require__(11).f - , create = __webpack_require__(46) - , redefineAll = __webpack_require__(210) - , ctx = __webpack_require__(20) - , anInstance = __webpack_require__(205) - , defined = __webpack_require__(35) - , forOf = __webpack_require__(206) - , $iterDefine = __webpack_require__(128) - , step = __webpack_require__(194) - , setSpecies = __webpack_require__(192) - , DESCRIPTORS = __webpack_require__(6) - , fastKey = __webpack_require__(22).fastKey - , SIZE = DESCRIPTORS ? '_s' : 'size'; - - var getEntry = function(that, key){ - // fast case - var index = fastKey(key), entry; - if(index !== 'F')return that._i[index]; - // frozen object case - for(entry = that._f; entry; entry = entry.n){ - if(entry.k == key)return entry; - } - }; - - module.exports = { - getConstructor: function(wrapper, NAME, IS_MAP, ADDER){ - var C = wrapper(function(that, iterable){ - anInstance(that, C, NAME, '_i'); - that._i = create(null); // index - that._f = undefined; // first entry - that._l = undefined; // last entry - that[SIZE] = 0; // size - if(iterable != undefined)forOf(iterable, IS_MAP, that[ADDER], that); - }); - redefineAll(C.prototype, { - // 23.1.3.1 Map.prototype.clear() - // 23.2.3.2 Set.prototype.clear() - clear: function clear(){ - for(var that = this, data = that._i, entry = that._f; entry; entry = entry.n){ - entry.r = true; - if(entry.p)entry.p = entry.p.n = undefined; - delete data[entry.i]; - } - that._f = that._l = undefined; - that[SIZE] = 0; - }, - // 23.1.3.3 Map.prototype.delete(key) - // 23.2.3.4 Set.prototype.delete(value) - 'delete': function(key){ - var that = this - , entry = getEntry(that, key); - if(entry){ - var next = entry.n - , prev = entry.p; - delete that._i[entry.i]; - entry.r = true; - if(prev)prev.n = next; - if(next)next.p = prev; - if(that._f == entry)that._f = next; - if(that._l == entry)that._l = prev; - that[SIZE]--; - } return !!entry; - }, - // 23.2.3.6 Set.prototype.forEach(callbackfn, thisArg = undefined) - // 23.1.3.5 Map.prototype.forEach(callbackfn, thisArg = undefined) - forEach: function forEach(callbackfn /*, that = undefined */){ - anInstance(this, C, 'forEach'); - var f = ctx(callbackfn, arguments.length > 1 ? arguments[1] : undefined, 3) - , entry; - while(entry = entry ? entry.n : this._f){ - f(entry.v, entry.k, this); - // revert to the last existing entry - while(entry && entry.r)entry = entry.p; - } - }, - // 23.1.3.7 Map.prototype.has(key) - // 23.2.3.7 Set.prototype.has(value) - has: function has(key){ - return !!getEntry(this, key); - } - }); - if(DESCRIPTORS)dP(C.prototype, 'size', { - get: function(){ - return defined(this[SIZE]); - } - }); - return C; - }, - def: function(that, key, value){ - var entry = getEntry(that, key) - , prev, index; - // change existing entry - if(entry){ - entry.v = value; - // create new entry - } else { - that._l = entry = { - i: index = fastKey(key, true), // <- index - k: key, // <- key - v: value, // <- value - p: prev = that._l, // <- previous entry - n: undefined, // <- next entry - r: false // <- removed - }; - if(!that._f)that._f = entry; - if(prev)prev.n = entry; - that[SIZE]++; - // add to index - if(index !== 'F')that._i[index] = entry; - } return that; - }, - getEntry: getEntry, - setStrong: function(C, NAME, IS_MAP){ - // add .keys, .values, .entries, [@@iterator] - // 23.1.3.4, 23.1.3.8, 23.1.3.11, 23.1.3.12, 23.2.3.5, 23.2.3.8, 23.2.3.10, 23.2.3.11 - $iterDefine(C, NAME, function(iterated, kind){ - this._t = iterated; // target - this._k = kind; // kind - this._l = undefined; // previous - }, function(){ - var that = this - , kind = that._k - , entry = that._l; - // revert to the last existing entry - while(entry && entry.r)entry = entry.p; - // get next entry - if(!that._t || !(that._l = entry = entry ? entry.n : that._t._f)){ - // or finish the iteration - that._t = undefined; - return step(1); - } - // return step by kind - if(kind == 'keys' )return step(0, entry.k); - if(kind == 'values')return step(0, entry.v); - return step(0, [entry.k, entry.v]); - }, IS_MAP ? 'entries' : 'values' , !IS_MAP, true); - - // add [@@species], 23.1.2.2, 23.2.2.2 - setSpecies(NAME); - } - }; - -/***/ }, -/* 213 */ -/***/ function(module, exports, __webpack_require__) { - - 'use strict'; - var global = __webpack_require__(4) - , $export = __webpack_require__(8) - , redefine = __webpack_require__(18) - , redefineAll = __webpack_require__(210) - , meta = __webpack_require__(22) - , forOf = __webpack_require__(206) - , anInstance = __webpack_require__(205) - , isObject = __webpack_require__(13) - , fails = __webpack_require__(7) - , $iterDetect = __webpack_require__(165) - , setToStringTag = __webpack_require__(24) - , inheritIfRequired = __webpack_require__(88); - - module.exports = function(NAME, wrapper, methods, common, IS_MAP, IS_WEAK){ - var Base = global[NAME] - , C = Base - , ADDER = IS_MAP ? 'set' : 'add' - , proto = C && C.prototype - , O = {}; - var fixMethod = function(KEY){ - var fn = proto[KEY]; - redefine(proto, KEY, - KEY == 'delete' ? function(a){ - return IS_WEAK && !isObject(a) ? false : fn.call(this, a === 0 ? 0 : a); - } : KEY == 'has' ? function has(a){ - return IS_WEAK && !isObject(a) ? false : fn.call(this, a === 0 ? 0 : a); - } : KEY == 'get' ? function get(a){ - return IS_WEAK && !isObject(a) ? undefined : fn.call(this, a === 0 ? 0 : a); - } : KEY == 'add' ? function add(a){ fn.call(this, a === 0 ? 0 : a); return this; } - : function set(a, b){ fn.call(this, a === 0 ? 0 : a, b); return this; } - ); - }; - if(typeof C != 'function' || !(IS_WEAK || proto.forEach && !fails(function(){ - new C().entries().next(); - }))){ - // create collection constructor - C = common.getConstructor(wrapper, NAME, IS_MAP, ADDER); - redefineAll(C.prototype, methods); - meta.NEED = true; - } else { - var instance = new C - // early implementations not supports chaining - , HASNT_CHAINING = instance[ADDER](IS_WEAK ? {} : -0, 1) != instance - // V8 ~ Chromium 40- weak-collections throws on primitives, but should return false - , THROWS_ON_PRIMITIVES = fails(function(){ instance.has(1); }) - // most early implementations doesn't supports iterables, most modern - not close it correctly - , ACCEPT_ITERABLES = $iterDetect(function(iter){ new C(iter); }) // eslint-disable-line no-new - // for early implementations -0 and +0 not the same - , BUGGY_ZERO = !IS_WEAK && fails(function(){ - // V8 ~ Chromium 42- fails only with 5+ elements - var $instance = new C() - , index = 5; - while(index--)$instance[ADDER](index, index); - return !$instance.has(-0); - }); - if(!ACCEPT_ITERABLES){ - C = wrapper(function(target, iterable){ - anInstance(target, C, NAME); - var that = inheritIfRequired(new Base, target, C); - if(iterable != undefined)forOf(iterable, IS_MAP, that[ADDER], that); - return that; - }); - C.prototype = proto; - proto.constructor = C; - } - if(THROWS_ON_PRIMITIVES || BUGGY_ZERO){ - fixMethod('delete'); - fixMethod('has'); - IS_MAP && fixMethod('get'); - } - if(BUGGY_ZERO || HASNT_CHAINING)fixMethod(ADDER); - // weak collections should not contains .clear method - if(IS_WEAK && proto.clear)delete proto.clear; - } - - setToStringTag(C, NAME); - - O[NAME] = C; - $export($export.G + $export.W + $export.F * (C != Base), O); - - if(!IS_WEAK)common.setStrong(C, NAME, IS_MAP); - - return C; - }; - -/***/ }, -/* 214 */ -/***/ function(module, exports, __webpack_require__) { - - 'use strict'; - var strong = __webpack_require__(212); - - // 23.2 Set Objects - module.exports = __webpack_require__(213)('Set', function(get){ - return function Set(){ return get(this, arguments.length > 0 ? arguments[0] : undefined); }; - }, { - // 23.2.3.1 Set.prototype.add(value) - add: function add(value){ - return strong.def(this, value = value === 0 ? 0 : value, value); - } - }, strong); - -/***/ }, -/* 215 */ -/***/ function(module, exports, __webpack_require__) { - - 'use strict'; - var each = __webpack_require__(172)(0) - , redefine = __webpack_require__(18) - , meta = __webpack_require__(22) - , assign = __webpack_require__(69) - , weak = __webpack_require__(216) - , isObject = __webpack_require__(13) - , getWeak = meta.getWeak - , isExtensible = Object.isExtensible - , uncaughtFrozenStore = weak.ufstore - , tmp = {} - , InternalMap; - - var wrapper = function(get){ - return function WeakMap(){ - return get(this, arguments.length > 0 ? arguments[0] : undefined); - }; - }; - - var methods = { - // 23.3.3.3 WeakMap.prototype.get(key) - get: function get(key){ - if(isObject(key)){ - var data = getWeak(key); - if(data === true)return uncaughtFrozenStore(this).get(key); - return data ? data[this._i] : undefined; - } - }, - // 23.3.3.5 WeakMap.prototype.set(key, value) - set: function set(key, value){ - return weak.def(this, key, value); - } - }; - - // 23.3 WeakMap Objects - var $WeakMap = module.exports = __webpack_require__(213)('WeakMap', wrapper, methods, weak, true, true); - - // IE11 WeakMap frozen keys fix - if(new $WeakMap().set((Object.freeze || Object)(tmp), 7).get(tmp) != 7){ - InternalMap = weak.getConstructor(wrapper); - assign(InternalMap.prototype, methods); - meta.NEED = true; - each(['delete', 'has', 'get', 'set'], function(key){ - var proto = $WeakMap.prototype - , method = proto[key]; - redefine(proto, key, function(a, b){ - // store frozen objects on internal weakmap shim - if(isObject(a) && !isExtensible(a)){ - if(!this._f)this._f = new InternalMap; - var result = this._f[key](a, b); - return key == 'set' ? this : result; - // store all the rest on native weakmap - } return method.call(this, a, b); - }); - }); - } - -/***/ }, -/* 216 */ -/***/ function(module, exports, __webpack_require__) { - - 'use strict'; - var redefineAll = __webpack_require__(210) - , getWeak = __webpack_require__(22).getWeak - , anObject = __webpack_require__(12) - , isObject = __webpack_require__(13) - , anInstance = __webpack_require__(205) - , forOf = __webpack_require__(206) - , createArrayMethod = __webpack_require__(172) - , $has = __webpack_require__(5) - , arrayFind = createArrayMethod(5) - , arrayFindIndex = createArrayMethod(6) - , id = 0; - - // fallback for uncaught frozen keys - var uncaughtFrozenStore = function(that){ - return that._l || (that._l = new UncaughtFrozenStore); - }; - var UncaughtFrozenStore = function(){ - this.a = []; - }; - var findUncaughtFrozen = function(store, key){ - return arrayFind(store.a, function(it){ - return it[0] === key; - }); - }; - UncaughtFrozenStore.prototype = { - get: function(key){ - var entry = findUncaughtFrozen(this, key); - if(entry)return entry[1]; - }, - has: function(key){ - return !!findUncaughtFrozen(this, key); - }, - set: function(key, value){ - var entry = findUncaughtFrozen(this, key); - if(entry)entry[1] = value; - else this.a.push([key, value]); - }, - 'delete': function(key){ - var index = arrayFindIndex(this.a, function(it){ - return it[0] === key; - }); - if(~index)this.a.splice(index, 1); - return !!~index; - } - }; - - module.exports = { - getConstructor: function(wrapper, NAME, IS_MAP, ADDER){ - var C = wrapper(function(that, iterable){ - anInstance(that, C, NAME, '_i'); - that._i = id++; // collection id - that._l = undefined; // leak store for uncaught frozen objects - if(iterable != undefined)forOf(iterable, IS_MAP, that[ADDER], that); - }); - redefineAll(C.prototype, { - // 23.3.3.2 WeakMap.prototype.delete(key) - // 23.4.3.3 WeakSet.prototype.delete(value) - 'delete': function(key){ - if(!isObject(key))return false; - var data = getWeak(key); - if(data === true)return uncaughtFrozenStore(this)['delete'](key); - return data && $has(data, this._i) && delete data[this._i]; - }, - // 23.3.3.4 WeakMap.prototype.has(key) - // 23.4.3.4 WeakSet.prototype.has(value) - has: function has(key){ - if(!isObject(key))return false; - var data = getWeak(key); - if(data === true)return uncaughtFrozenStore(this).has(key); - return data && $has(data, this._i); - } - }); - return C; - }, - def: function(that, key, value){ - var data = getWeak(anObject(key), true); - if(data === true)uncaughtFrozenStore(that).set(key, value); - else data[that._i] = value; - return that; - }, - ufstore: uncaughtFrozenStore - }; - -/***/ }, -/* 217 */ -/***/ function(module, exports, __webpack_require__) { - - 'use strict'; - var weak = __webpack_require__(216); - - // 23.4 WeakSet Objects - __webpack_require__(213)('WeakSet', function(get){ - return function WeakSet(){ return get(this, arguments.length > 0 ? arguments[0] : undefined); }; - }, { - // 23.4.3.1 WeakSet.prototype.add(value) - add: function add(value){ - return weak.def(this, value, true); - } - }, weak, false, true); - -/***/ }, -/* 218 */ -/***/ function(module, exports, __webpack_require__) { - - 'use strict'; - var $export = __webpack_require__(8) - , $typed = __webpack_require__(219) - , buffer = __webpack_require__(220) - , anObject = __webpack_require__(12) - , toIndex = __webpack_require__(39) - , toLength = __webpack_require__(37) - , isObject = __webpack_require__(13) - , ArrayBuffer = __webpack_require__(4).ArrayBuffer - , speciesConstructor = __webpack_require__(207) - , $ArrayBuffer = buffer.ArrayBuffer - , $DataView = buffer.DataView - , $isView = $typed.ABV && ArrayBuffer.isView - , $slice = $ArrayBuffer.prototype.slice - , VIEW = $typed.VIEW - , ARRAY_BUFFER = 'ArrayBuffer'; - - $export($export.G + $export.W + $export.F * (ArrayBuffer !== $ArrayBuffer), {ArrayBuffer: $ArrayBuffer}); - - $export($export.S + $export.F * !$typed.CONSTR, ARRAY_BUFFER, { - // 24.1.3.1 ArrayBuffer.isView(arg) - isView: function isView(it){ - return $isView && $isView(it) || isObject(it) && VIEW in it; - } - }); - - $export($export.P + $export.U + $export.F * __webpack_require__(7)(function(){ - return !new $ArrayBuffer(2).slice(1, undefined).byteLength; - }), ARRAY_BUFFER, { - // 24.1.4.3 ArrayBuffer.prototype.slice(start, end) - slice: function slice(start, end){ - if($slice !== undefined && end === undefined)return $slice.call(anObject(this), start); // FF fix - var len = anObject(this).byteLength - , first = toIndex(start, len) - , final = toIndex(end === undefined ? len : end, len) - , result = new (speciesConstructor(this, $ArrayBuffer))(toLength(final - first)) - , viewS = new $DataView(this) - , viewT = new $DataView(result) - , index = 0; - while(first < final){ - viewT.setUint8(index++, viewS.getUint8(first++)); - } return result; - } - }); - - __webpack_require__(192)(ARRAY_BUFFER); - -/***/ }, -/* 219 */ -/***/ function(module, exports, __webpack_require__) { - - var global = __webpack_require__(4) - , hide = __webpack_require__(10) - , uid = __webpack_require__(19) - , TYPED = uid('typed_array') - , VIEW = uid('view') - , ABV = !!(global.ArrayBuffer && global.DataView) - , CONSTR = ABV - , i = 0, l = 9, Typed; - - var TypedArrayConstructors = ( - 'Int8Array,Uint8Array,Uint8ClampedArray,Int16Array,Uint16Array,Int32Array,Uint32Array,Float32Array,Float64Array' - ).split(','); - - while(i < l){ - if(Typed = global[TypedArrayConstructors[i++]]){ - hide(Typed.prototype, TYPED, true); - hide(Typed.prototype, VIEW, true); - } else CONSTR = false; - } - - module.exports = { - ABV: ABV, - CONSTR: CONSTR, - TYPED: TYPED, - VIEW: VIEW - }; - -/***/ }, -/* 220 */ -/***/ function(module, exports, __webpack_require__) { - - 'use strict'; - var global = __webpack_require__(4) - , DESCRIPTORS = __webpack_require__(6) - , LIBRARY = __webpack_require__(28) - , $typed = __webpack_require__(219) - , hide = __webpack_require__(10) - , redefineAll = __webpack_require__(210) - , fails = __webpack_require__(7) - , anInstance = __webpack_require__(205) - , toInteger = __webpack_require__(38) - , toLength = __webpack_require__(37) - , gOPN = __webpack_require__(50).f - , dP = __webpack_require__(11).f - , arrayFill = __webpack_require__(188) - , setToStringTag = __webpack_require__(24) - , ARRAY_BUFFER = 'ArrayBuffer' - , DATA_VIEW = 'DataView' - , PROTOTYPE = 'prototype' - , WRONG_LENGTH = 'Wrong length!' - , WRONG_INDEX = 'Wrong index!' - , $ArrayBuffer = global[ARRAY_BUFFER] - , $DataView = global[DATA_VIEW] - , Math = global.Math - , RangeError = global.RangeError - , Infinity = global.Infinity - , BaseBuffer = $ArrayBuffer - , abs = Math.abs - , pow = Math.pow - , floor = Math.floor - , log = Math.log - , LN2 = Math.LN2 - , BUFFER = 'buffer' - , BYTE_LENGTH = 'byteLength' - , BYTE_OFFSET = 'byteOffset' - , $BUFFER = DESCRIPTORS ? '_b' : BUFFER - , $LENGTH = DESCRIPTORS ? '_l' : BYTE_LENGTH - , $OFFSET = DESCRIPTORS ? '_o' : BYTE_OFFSET; - - // IEEE754 conversions based on https://github.com/feross/ieee754 - var packIEEE754 = function(value, mLen, nBytes){ - var buffer = Array(nBytes) - , eLen = nBytes * 8 - mLen - 1 - , eMax = (1 << eLen) - 1 - , eBias = eMax >> 1 - , rt = mLen === 23 ? pow(2, -24) - pow(2, -77) : 0 - , i = 0 - , s = value < 0 || value === 0 && 1 / value < 0 ? 1 : 0 - , e, m, c; - value = abs(value) - if(value != value || value === Infinity){ - m = value != value ? 1 : 0; - e = eMax; - } else { - e = floor(log(value) / LN2); - if(value * (c = pow(2, -e)) < 1){ - e--; - c *= 2; - } - if(e + eBias >= 1){ - value += rt / c; - } else { - value += rt * pow(2, 1 - eBias); - } - if(value * c >= 2){ - e++; - c /= 2; - } - if(e + eBias >= eMax){ - m = 0; - e = eMax; - } else if(e + eBias >= 1){ - m = (value * c - 1) * pow(2, mLen); - e = e + eBias; - } else { - m = value * pow(2, eBias - 1) * pow(2, mLen); - e = 0; - } - } - for(; mLen >= 8; buffer[i++] = m & 255, m /= 256, mLen -= 8); - e = e << mLen | m; - eLen += mLen; - for(; eLen > 0; buffer[i++] = e & 255, e /= 256, eLen -= 8); - buffer[--i] |= s * 128; - return buffer; - }; - var unpackIEEE754 = function(buffer, mLen, nBytes){ - var eLen = nBytes * 8 - mLen - 1 - , eMax = (1 << eLen) - 1 - , eBias = eMax >> 1 - , nBits = eLen - 7 - , i = nBytes - 1 - , s = buffer[i--] - , e = s & 127 - , m; - s >>= 7; - for(; nBits > 0; e = e * 256 + buffer[i], i--, nBits -= 8); - m = e & (1 << -nBits) - 1; - e >>= -nBits; - nBits += mLen; - for(; nBits > 0; m = m * 256 + buffer[i], i--, nBits -= 8); - if(e === 0){ - e = 1 - eBias; - } else if(e === eMax){ - return m ? NaN : s ? -Infinity : Infinity; - } else { - m = m + pow(2, mLen); - e = e - eBias; - } return (s ? -1 : 1) * m * pow(2, e - mLen); - }; - - var unpackI32 = function(bytes){ - return bytes[3] << 24 | bytes[2] << 16 | bytes[1] << 8 | bytes[0]; - }; - var packI8 = function(it){ - return [it & 0xff]; - }; - var packI16 = function(it){ - return [it & 0xff, it >> 8 & 0xff]; - }; - var packI32 = function(it){ - return [it & 0xff, it >> 8 & 0xff, it >> 16 & 0xff, it >> 24 & 0xff]; - }; - var packF64 = function(it){ - return packIEEE754(it, 52, 8); - }; - var packF32 = function(it){ - return packIEEE754(it, 23, 4); - }; - - var addGetter = function(C, key, internal){ - dP(C[PROTOTYPE], key, {get: function(){ return this[internal]; }}); - }; - - var get = function(view, bytes, index, isLittleEndian){ - var numIndex = +index - , intIndex = toInteger(numIndex); - if(numIndex != intIndex || intIndex < 0 || intIndex + bytes > view[$LENGTH])throw RangeError(WRONG_INDEX); - var store = view[$BUFFER]._b - , start = intIndex + view[$OFFSET] - , pack = store.slice(start, start + bytes); - return isLittleEndian ? pack : pack.reverse(); - }; - var set = function(view, bytes, index, conversion, value, isLittleEndian){ - var numIndex = +index - , intIndex = toInteger(numIndex); - if(numIndex != intIndex || intIndex < 0 || intIndex + bytes > view[$LENGTH])throw RangeError(WRONG_INDEX); - var store = view[$BUFFER]._b - , start = intIndex + view[$OFFSET] - , pack = conversion(+value); - for(var i = 0; i < bytes; i++)store[start + i] = pack[isLittleEndian ? i : bytes - i - 1]; - }; - - var validateArrayBufferArguments = function(that, length){ - anInstance(that, $ArrayBuffer, ARRAY_BUFFER); - var numberLength = +length - , byteLength = toLength(numberLength); - if(numberLength != byteLength)throw RangeError(WRONG_LENGTH); - return byteLength; - }; - - if(!$typed.ABV){ - $ArrayBuffer = function ArrayBuffer(length){ - var byteLength = validateArrayBufferArguments(this, length); - this._b = arrayFill.call(Array(byteLength), 0); - this[$LENGTH] = byteLength; - }; - - $DataView = function DataView(buffer, byteOffset, byteLength){ - anInstance(this, $DataView, DATA_VIEW); - anInstance(buffer, $ArrayBuffer, DATA_VIEW); - var bufferLength = buffer[$LENGTH] - , offset = toInteger(byteOffset); - if(offset < 0 || offset > bufferLength)throw RangeError('Wrong offset!'); - byteLength = byteLength === undefined ? bufferLength - offset : toLength(byteLength); - if(offset + byteLength > bufferLength)throw RangeError(WRONG_LENGTH); - this[$BUFFER] = buffer; - this[$OFFSET] = offset; - this[$LENGTH] = byteLength; - }; - - if(DESCRIPTORS){ - addGetter($ArrayBuffer, BYTE_LENGTH, '_l'); - addGetter($DataView, BUFFER, '_b'); - addGetter($DataView, BYTE_LENGTH, '_l'); - addGetter($DataView, BYTE_OFFSET, '_o'); - } - - redefineAll($DataView[PROTOTYPE], { - getInt8: function getInt8(byteOffset){ - return get(this, 1, byteOffset)[0] << 24 >> 24; - }, - getUint8: function getUint8(byteOffset){ - return get(this, 1, byteOffset)[0]; - }, - getInt16: function getInt16(byteOffset /*, littleEndian */){ - var bytes = get(this, 2, byteOffset, arguments[1]); - return (bytes[1] << 8 | bytes[0]) << 16 >> 16; - }, - getUint16: function getUint16(byteOffset /*, littleEndian */){ - var bytes = get(this, 2, byteOffset, arguments[1]); - return bytes[1] << 8 | bytes[0]; - }, - getInt32: function getInt32(byteOffset /*, littleEndian */){ - return unpackI32(get(this, 4, byteOffset, arguments[1])); - }, - getUint32: function getUint32(byteOffset /*, littleEndian */){ - return unpackI32(get(this, 4, byteOffset, arguments[1])) >>> 0; - }, - getFloat32: function getFloat32(byteOffset /*, littleEndian */){ - return unpackIEEE754(get(this, 4, byteOffset, arguments[1]), 23, 4); - }, - getFloat64: function getFloat64(byteOffset /*, littleEndian */){ - return unpackIEEE754(get(this, 8, byteOffset, arguments[1]), 52, 8); - }, - setInt8: function setInt8(byteOffset, value){ - set(this, 1, byteOffset, packI8, value); - }, - setUint8: function setUint8(byteOffset, value){ - set(this, 1, byteOffset, packI8, value); - }, - setInt16: function setInt16(byteOffset, value /*, littleEndian */){ - set(this, 2, byteOffset, packI16, value, arguments[2]); - }, - setUint16: function setUint16(byteOffset, value /*, littleEndian */){ - set(this, 2, byteOffset, packI16, value, arguments[2]); - }, - setInt32: function setInt32(byteOffset, value /*, littleEndian */){ - set(this, 4, byteOffset, packI32, value, arguments[2]); - }, - setUint32: function setUint32(byteOffset, value /*, littleEndian */){ - set(this, 4, byteOffset, packI32, value, arguments[2]); - }, - setFloat32: function setFloat32(byteOffset, value /*, littleEndian */){ - set(this, 4, byteOffset, packF32, value, arguments[2]); - }, - setFloat64: function setFloat64(byteOffset, value /*, littleEndian */){ - set(this, 8, byteOffset, packF64, value, arguments[2]); - } - }); - } else { - if(!fails(function(){ - new $ArrayBuffer; // eslint-disable-line no-new - }) || !fails(function(){ - new $ArrayBuffer(.5); // eslint-disable-line no-new - })){ - $ArrayBuffer = function ArrayBuffer(length){ - return new BaseBuffer(validateArrayBufferArguments(this, length)); - }; - var ArrayBufferProto = $ArrayBuffer[PROTOTYPE] = BaseBuffer[PROTOTYPE]; - for(var keys = gOPN(BaseBuffer), j = 0, key; keys.length > j; ){ - if(!((key = keys[j++]) in $ArrayBuffer))hide($ArrayBuffer, key, BaseBuffer[key]); - }; - if(!LIBRARY)ArrayBufferProto.constructor = $ArrayBuffer; - } - // iOS Safari 7.x bug - var view = new $DataView(new $ArrayBuffer(2)) - , $setInt8 = $DataView[PROTOTYPE].setInt8; - view.setInt8(0, 2147483648); - view.setInt8(1, 2147483649); - if(view.getInt8(0) || !view.getInt8(1))redefineAll($DataView[PROTOTYPE], { - setInt8: function setInt8(byteOffset, value){ - $setInt8.call(this, byteOffset, value << 24 >> 24); - }, - setUint8: function setUint8(byteOffset, value){ - $setInt8.call(this, byteOffset, value << 24 >> 24); - } - }, true); - } - setToStringTag($ArrayBuffer, ARRAY_BUFFER); - setToStringTag($DataView, DATA_VIEW); - hide($DataView[PROTOTYPE], $typed.VIEW, true); - exports[ARRAY_BUFFER] = $ArrayBuffer; - exports[DATA_VIEW] = $DataView; - -/***/ }, -/* 221 */ -/***/ function(module, exports, __webpack_require__) { - - var $export = __webpack_require__(8); - $export($export.G + $export.W + $export.F * !__webpack_require__(219).ABV, { - DataView: __webpack_require__(220).DataView - }); - -/***/ }, -/* 222 */ -/***/ function(module, exports, __webpack_require__) { - - __webpack_require__(223)('Int8', 1, function(init){ - return function Int8Array(data, byteOffset, length){ - return init(this, data, byteOffset, length); - }; - }); - -/***/ }, -/* 223 */ -/***/ function(module, exports, __webpack_require__) { - - 'use strict'; - if(__webpack_require__(6)){ - var LIBRARY = __webpack_require__(28) - , global = __webpack_require__(4) - , fails = __webpack_require__(7) - , $export = __webpack_require__(8) - , $typed = __webpack_require__(219) - , $buffer = __webpack_require__(220) - , ctx = __webpack_require__(20) - , anInstance = __webpack_require__(205) - , propertyDesc = __webpack_require__(17) - , hide = __webpack_require__(10) - , redefineAll = __webpack_require__(210) - , toInteger = __webpack_require__(38) - , toLength = __webpack_require__(37) - , toIndex = __webpack_require__(39) - , toPrimitive = __webpack_require__(16) - , has = __webpack_require__(5) - , same = __webpack_require__(71) - , classof = __webpack_require__(75) - , isObject = __webpack_require__(13) - , toObject = __webpack_require__(58) - , isArrayIter = __webpack_require__(162) - , create = __webpack_require__(46) - , getPrototypeOf = __webpack_require__(59) - , gOPN = __webpack_require__(50).f - , getIterFn = __webpack_require__(164) - , uid = __webpack_require__(19) - , wks = __webpack_require__(25) - , createArrayMethod = __webpack_require__(172) - , createArrayIncludes = __webpack_require__(36) - , speciesConstructor = __webpack_require__(207) - , ArrayIterators = __webpack_require__(193) - , Iterators = __webpack_require__(129) - , $iterDetect = __webpack_require__(165) - , setSpecies = __webpack_require__(192) - , arrayFill = __webpack_require__(188) - , arrayCopyWithin = __webpack_require__(185) - , $DP = __webpack_require__(11) - , $GOPD = __webpack_require__(51) - , dP = $DP.f - , gOPD = $GOPD.f - , RangeError = global.RangeError - , TypeError = global.TypeError - , Uint8Array = global.Uint8Array - , ARRAY_BUFFER = 'ArrayBuffer' - , SHARED_BUFFER = 'Shared' + ARRAY_BUFFER - , BYTES_PER_ELEMENT = 'BYTES_PER_ELEMENT' - , PROTOTYPE = 'prototype' - , ArrayProto = Array[PROTOTYPE] - , $ArrayBuffer = $buffer.ArrayBuffer - , $DataView = $buffer.DataView - , arrayForEach = createArrayMethod(0) - , arrayFilter = createArrayMethod(2) - , arraySome = createArrayMethod(3) - , arrayEvery = createArrayMethod(4) - , arrayFind = createArrayMethod(5) - , arrayFindIndex = createArrayMethod(6) - , arrayIncludes = createArrayIncludes(true) - , arrayIndexOf = createArrayIncludes(false) - , arrayValues = ArrayIterators.values - , arrayKeys = ArrayIterators.keys - , arrayEntries = ArrayIterators.entries - , arrayLastIndexOf = ArrayProto.lastIndexOf - , arrayReduce = ArrayProto.reduce - , arrayReduceRight = ArrayProto.reduceRight - , arrayJoin = ArrayProto.join - , arraySort = ArrayProto.sort - , arraySlice = ArrayProto.slice - , arrayToString = ArrayProto.toString - , arrayToLocaleString = ArrayProto.toLocaleString - , ITERATOR = wks('iterator') - , TAG = wks('toStringTag') - , TYPED_CONSTRUCTOR = uid('typed_constructor') - , DEF_CONSTRUCTOR = uid('def_constructor') - , ALL_CONSTRUCTORS = $typed.CONSTR - , TYPED_ARRAY = $typed.TYPED - , VIEW = $typed.VIEW - , WRONG_LENGTH = 'Wrong length!'; - - var $map = createArrayMethod(1, function(O, length){ - return allocate(speciesConstructor(O, O[DEF_CONSTRUCTOR]), length); - }); - - var LITTLE_ENDIAN = fails(function(){ - return new Uint8Array(new Uint16Array([1]).buffer)[0] === 1; - }); - - var FORCED_SET = !!Uint8Array && !!Uint8Array[PROTOTYPE].set && fails(function(){ - new Uint8Array(1).set({}); - }); - - var strictToLength = function(it, SAME){ - if(it === undefined)throw TypeError(WRONG_LENGTH); - var number = +it - , length = toLength(it); - if(SAME && !same(number, length))throw RangeError(WRONG_LENGTH); - return length; - }; - - var toOffset = function(it, BYTES){ - var offset = toInteger(it); - if(offset < 0 || offset % BYTES)throw RangeError('Wrong offset!'); - return offset; - }; - - var validate = function(it){ - if(isObject(it) && TYPED_ARRAY in it)return it; - throw TypeError(it + ' is not a typed array!'); - }; - - var allocate = function(C, length){ - if(!(isObject(C) && TYPED_CONSTRUCTOR in C)){ - throw TypeError('It is not a typed array constructor!'); - } return new C(length); - }; - - var speciesFromList = function(O, list){ - return fromList(speciesConstructor(O, O[DEF_CONSTRUCTOR]), list); - }; - - var fromList = function(C, list){ - var index = 0 - , length = list.length - , result = allocate(C, length); - while(length > index)result[index] = list[index++]; - return result; - }; - - var addGetter = function(it, key, internal){ - dP(it, key, {get: function(){ return this._d[internal]; }}); - }; - - var $from = function from(source /*, mapfn, thisArg */){ - var O = toObject(source) - , aLen = arguments.length - , mapfn = aLen > 1 ? arguments[1] : undefined - , mapping = mapfn !== undefined - , iterFn = getIterFn(O) - , i, length, values, result, step, iterator; - if(iterFn != undefined && !isArrayIter(iterFn)){ - for(iterator = iterFn.call(O), values = [], i = 0; !(step = iterator.next()).done; i++){ - values.push(step.value); - } O = values; - } - if(mapping && aLen > 2)mapfn = ctx(mapfn, arguments[2], 2); - for(i = 0, length = toLength(O.length), result = allocate(this, length); length > i; i++){ - result[i] = mapping ? mapfn(O[i], i) : O[i]; - } - return result; - }; - - var $of = function of(/*...items*/){ - var index = 0 - , length = arguments.length - , result = allocate(this, length); - while(length > index)result[index] = arguments[index++]; - return result; - }; - - // iOS Safari 6.x fails here - var TO_LOCALE_BUG = !!Uint8Array && fails(function(){ arrayToLocaleString.call(new Uint8Array(1)); }); - - var $toLocaleString = function toLocaleString(){ - return arrayToLocaleString.apply(TO_LOCALE_BUG ? arraySlice.call(validate(this)) : validate(this), arguments); - }; - - var proto = { - copyWithin: function copyWithin(target, start /*, end */){ - return arrayCopyWithin.call(validate(this), target, start, arguments.length > 2 ? arguments[2] : undefined); - }, - every: function every(callbackfn /*, thisArg */){ - return arrayEvery(validate(this), callbackfn, arguments.length > 1 ? arguments[1] : undefined); - }, - fill: function fill(value /*, start, end */){ // eslint-disable-line no-unused-vars - return arrayFill.apply(validate(this), arguments); - }, - filter: function filter(callbackfn /*, thisArg */){ - return speciesFromList(this, arrayFilter(validate(this), callbackfn, - arguments.length > 1 ? arguments[1] : undefined)); - }, - find: function find(predicate /*, thisArg */){ - return arrayFind(validate(this), predicate, arguments.length > 1 ? arguments[1] : undefined); - }, - findIndex: function findIndex(predicate /*, thisArg */){ - return arrayFindIndex(validate(this), predicate, arguments.length > 1 ? arguments[1] : undefined); - }, - forEach: function forEach(callbackfn /*, thisArg */){ - arrayForEach(validate(this), callbackfn, arguments.length > 1 ? arguments[1] : undefined); - }, - indexOf: function indexOf(searchElement /*, fromIndex */){ - return arrayIndexOf(validate(this), searchElement, arguments.length > 1 ? arguments[1] : undefined); - }, - includes: function includes(searchElement /*, fromIndex */){ - return arrayIncludes(validate(this), searchElement, arguments.length > 1 ? arguments[1] : undefined); - }, - join: function join(separator){ // eslint-disable-line no-unused-vars - return arrayJoin.apply(validate(this), arguments); - }, - lastIndexOf: function lastIndexOf(searchElement /*, fromIndex */){ // eslint-disable-line no-unused-vars - return arrayLastIndexOf.apply(validate(this), arguments); - }, - map: function map(mapfn /*, thisArg */){ - return $map(validate(this), mapfn, arguments.length > 1 ? arguments[1] : undefined); - }, - reduce: function reduce(callbackfn /*, initialValue */){ // eslint-disable-line no-unused-vars - return arrayReduce.apply(validate(this), arguments); - }, - reduceRight: function reduceRight(callbackfn /*, initialValue */){ // eslint-disable-line no-unused-vars - return arrayReduceRight.apply(validate(this), arguments); - }, - reverse: function reverse(){ - var that = this - , length = validate(that).length - , middle = Math.floor(length / 2) - , index = 0 - , value; - while(index < middle){ - value = that[index]; - that[index++] = that[--length]; - that[length] = value; - } return that; - }, - some: function some(callbackfn /*, thisArg */){ - return arraySome(validate(this), callbackfn, arguments.length > 1 ? arguments[1] : undefined); - }, - sort: function sort(comparefn){ - return arraySort.call(validate(this), comparefn); - }, - subarray: function subarray(begin, end){ - var O = validate(this) - , length = O.length - , $begin = toIndex(begin, length); - return new (speciesConstructor(O, O[DEF_CONSTRUCTOR]))( - O.buffer, - O.byteOffset + $begin * O.BYTES_PER_ELEMENT, - toLength((end === undefined ? length : toIndex(end, length)) - $begin) - ); - } - }; - - var $slice = function slice(start, end){ - return speciesFromList(this, arraySlice.call(validate(this), start, end)); - }; - - var $set = function set(arrayLike /*, offset */){ - validate(this); - var offset = toOffset(arguments[1], 1) - , length = this.length - , src = toObject(arrayLike) - , len = toLength(src.length) - , index = 0; - if(len + offset > length)throw RangeError(WRONG_LENGTH); - while(index < len)this[offset + index] = src[index++]; - }; - - var $iterators = { - entries: function entries(){ - return arrayEntries.call(validate(this)); - }, - keys: function keys(){ - return arrayKeys.call(validate(this)); - }, - values: function values(){ - return arrayValues.call(validate(this)); - } - }; - - var isTAIndex = function(target, key){ - return isObject(target) - && target[TYPED_ARRAY] - && typeof key != 'symbol' - && key in target - && String(+key) == String(key); - }; - var $getDesc = function getOwnPropertyDescriptor(target, key){ - return isTAIndex(target, key = toPrimitive(key, true)) - ? propertyDesc(2, target[key]) - : gOPD(target, key); - }; - var $setDesc = function defineProperty(target, key, desc){ - if(isTAIndex(target, key = toPrimitive(key, true)) - && isObject(desc) - && has(desc, 'value') - && !has(desc, 'get') - && !has(desc, 'set') - // TODO: add validation descriptor w/o calling accessors - && !desc.configurable - && (!has(desc, 'writable') || desc.writable) - && (!has(desc, 'enumerable') || desc.enumerable) - ){ - target[key] = desc.value; - return target; - } else return dP(target, key, desc); - }; - - if(!ALL_CONSTRUCTORS){ - $GOPD.f = $getDesc; - $DP.f = $setDesc; - } - - $export($export.S + $export.F * !ALL_CONSTRUCTORS, 'Object', { - getOwnPropertyDescriptor: $getDesc, - defineProperty: $setDesc - }); - - if(fails(function(){ arrayToString.call({}); })){ - arrayToString = arrayToLocaleString = function toString(){ - return arrayJoin.call(this); - } - } - - var $TypedArrayPrototype$ = redefineAll({}, proto); - redefineAll($TypedArrayPrototype$, $iterators); - hide($TypedArrayPrototype$, ITERATOR, $iterators.values); - redefineAll($TypedArrayPrototype$, { - slice: $slice, - set: $set, - constructor: function(){ /* noop */ }, - toString: arrayToString, - toLocaleString: $toLocaleString - }); - addGetter($TypedArrayPrototype$, 'buffer', 'b'); - addGetter($TypedArrayPrototype$, 'byteOffset', 'o'); - addGetter($TypedArrayPrototype$, 'byteLength', 'l'); - addGetter($TypedArrayPrototype$, 'length', 'e'); - dP($TypedArrayPrototype$, TAG, { - get: function(){ return this[TYPED_ARRAY]; } - }); - - module.exports = function(KEY, BYTES, wrapper, CLAMPED){ - CLAMPED = !!CLAMPED; - var NAME = KEY + (CLAMPED ? 'Clamped' : '') + 'Array' - , ISNT_UINT8 = NAME != 'Uint8Array' - , GETTER = 'get' + KEY - , SETTER = 'set' + KEY - , TypedArray = global[NAME] - , Base = TypedArray || {} - , TAC = TypedArray && getPrototypeOf(TypedArray) - , FORCED = !TypedArray || !$typed.ABV - , O = {} - , TypedArrayPrototype = TypedArray && TypedArray[PROTOTYPE]; - var getter = function(that, index){ - var data = that._d; - return data.v[GETTER](index * BYTES + data.o, LITTLE_ENDIAN); - }; - var setter = function(that, index, value){ - var data = that._d; - if(CLAMPED)value = (value = Math.round(value)) < 0 ? 0 : value > 0xff ? 0xff : value & 0xff; - data.v[SETTER](index * BYTES + data.o, value, LITTLE_ENDIAN); - }; - var addElement = function(that, index){ - dP(that, index, { - get: function(){ - return getter(this, index); - }, - set: function(value){ - return setter(this, index, value); - }, - enumerable: true - }); - }; - if(FORCED){ - TypedArray = wrapper(function(that, data, $offset, $length){ - anInstance(that, TypedArray, NAME, '_d'); - var index = 0 - , offset = 0 - , buffer, byteLength, length, klass; - if(!isObject(data)){ - length = strictToLength(data, true) - byteLength = length * BYTES; - buffer = new $ArrayBuffer(byteLength); - } else if(data instanceof $ArrayBuffer || (klass = classof(data)) == ARRAY_BUFFER || klass == SHARED_BUFFER){ - buffer = data; - offset = toOffset($offset, BYTES); - var $len = data.byteLength; - if($length === undefined){ - if($len % BYTES)throw RangeError(WRONG_LENGTH); - byteLength = $len - offset; - if(byteLength < 0)throw RangeError(WRONG_LENGTH); - } else { - byteLength = toLength($length) * BYTES; - if(byteLength + offset > $len)throw RangeError(WRONG_LENGTH); - } - length = byteLength / BYTES; - } else if(TYPED_ARRAY in data){ - return fromList(TypedArray, data); - } else { - return $from.call(TypedArray, data); - } - hide(that, '_d', { - b: buffer, - o: offset, - l: byteLength, - e: length, - v: new $DataView(buffer) - }); - while(index < length)addElement(that, index++); - }); - TypedArrayPrototype = TypedArray[PROTOTYPE] = create($TypedArrayPrototype$); - hide(TypedArrayPrototype, 'constructor', TypedArray); - } else if(!$iterDetect(function(iter){ - // V8 works with iterators, but fails in many other cases - // https://code.google.com/p/v8/issues/detail?id=4552 - new TypedArray(null); // eslint-disable-line no-new - new TypedArray(iter); // eslint-disable-line no-new - }, true)){ - TypedArray = wrapper(function(that, data, $offset, $length){ - anInstance(that, TypedArray, NAME); - var klass; - // `ws` module bug, temporarily remove validation length for Uint8Array - // https://github.com/websockets/ws/pull/645 - if(!isObject(data))return new Base(strictToLength(data, ISNT_UINT8)); - if(data instanceof $ArrayBuffer || (klass = classof(data)) == ARRAY_BUFFER || klass == SHARED_BUFFER){ - return $length !== undefined - ? new Base(data, toOffset($offset, BYTES), $length) - : $offset !== undefined - ? new Base(data, toOffset($offset, BYTES)) - : new Base(data); - } - if(TYPED_ARRAY in data)return fromList(TypedArray, data); - return $from.call(TypedArray, data); - }); - arrayForEach(TAC !== Function.prototype ? gOPN(Base).concat(gOPN(TAC)) : gOPN(Base), function(key){ - if(!(key in TypedArray))hide(TypedArray, key, Base[key]); - }); - TypedArray[PROTOTYPE] = TypedArrayPrototype; - if(!LIBRARY)TypedArrayPrototype.constructor = TypedArray; - } - var $nativeIterator = TypedArrayPrototype[ITERATOR] - , CORRECT_ITER_NAME = !!$nativeIterator && ($nativeIterator.name == 'values' || $nativeIterator.name == undefined) - , $iterator = $iterators.values; - hide(TypedArray, TYPED_CONSTRUCTOR, true); - hide(TypedArrayPrototype, TYPED_ARRAY, NAME); - hide(TypedArrayPrototype, VIEW, true); - hide(TypedArrayPrototype, DEF_CONSTRUCTOR, TypedArray); - - if(CLAMPED ? new TypedArray(1)[TAG] != NAME : !(TAG in TypedArrayPrototype)){ - dP(TypedArrayPrototype, TAG, { - get: function(){ return NAME; } - }); - } - - O[NAME] = TypedArray; - - $export($export.G + $export.W + $export.F * (TypedArray != Base), O); - - $export($export.S, NAME, { - BYTES_PER_ELEMENT: BYTES, - from: $from, - of: $of - }); - - if(!(BYTES_PER_ELEMENT in TypedArrayPrototype))hide(TypedArrayPrototype, BYTES_PER_ELEMENT, BYTES); - - $export($export.P, NAME, proto); - - setSpecies(NAME); - - $export($export.P + $export.F * FORCED_SET, NAME, {set: $set}); - - $export($export.P + $export.F * !CORRECT_ITER_NAME, NAME, $iterators); - - $export($export.P + $export.F * (TypedArrayPrototype.toString != arrayToString), NAME, {toString: arrayToString}); - - $export($export.P + $export.F * fails(function(){ - new TypedArray(1).slice(); - }), NAME, {slice: $slice}); - - $export($export.P + $export.F * (fails(function(){ - return [1, 2].toLocaleString() != new TypedArray([1, 2]).toLocaleString() - }) || !fails(function(){ - TypedArrayPrototype.toLocaleString.call([1, 2]); - })), NAME, {toLocaleString: $toLocaleString}); - - Iterators[NAME] = CORRECT_ITER_NAME ? $nativeIterator : $iterator; - if(!LIBRARY && !CORRECT_ITER_NAME)hide(TypedArrayPrototype, ITERATOR, $iterator); - }; - } else module.exports = function(){ /* empty */ }; - -/***/ }, -/* 224 */ -/***/ function(module, exports, __webpack_require__) { - - __webpack_require__(223)('Uint8', 1, function(init){ - return function Uint8Array(data, byteOffset, length){ - return init(this, data, byteOffset, length); - }; - }); - -/***/ }, -/* 225 */ -/***/ function(module, exports, __webpack_require__) { - - __webpack_require__(223)('Uint8', 1, function(init){ - return function Uint8ClampedArray(data, byteOffset, length){ - return init(this, data, byteOffset, length); - }; - }, true); - -/***/ }, -/* 226 */ -/***/ function(module, exports, __webpack_require__) { - - __webpack_require__(223)('Int16', 2, function(init){ - return function Int16Array(data, byteOffset, length){ - return init(this, data, byteOffset, length); - }; - }); - -/***/ }, -/* 227 */ -/***/ function(module, exports, __webpack_require__) { - - __webpack_require__(223)('Uint16', 2, function(init){ - return function Uint16Array(data, byteOffset, length){ - return init(this, data, byteOffset, length); - }; - }); - -/***/ }, -/* 228 */ -/***/ function(module, exports, __webpack_require__) { - - __webpack_require__(223)('Int32', 4, function(init){ - return function Int32Array(data, byteOffset, length){ - return init(this, data, byteOffset, length); - }; - }); - -/***/ }, -/* 229 */ -/***/ function(module, exports, __webpack_require__) { - - __webpack_require__(223)('Uint32', 4, function(init){ - return function Uint32Array(data, byteOffset, length){ - return init(this, data, byteOffset, length); - }; - }); - -/***/ }, -/* 230 */ -/***/ function(module, exports, __webpack_require__) { - - __webpack_require__(223)('Float32', 4, function(init){ - return function Float32Array(data, byteOffset, length){ - return init(this, data, byteOffset, length); - }; - }); - -/***/ }, -/* 231 */ -/***/ function(module, exports, __webpack_require__) { - - __webpack_require__(223)('Float64', 8, function(init){ - return function Float64Array(data, byteOffset, length){ - return init(this, data, byteOffset, length); - }; - }); - -/***/ }, -/* 232 */ -/***/ function(module, exports, __webpack_require__) { - - // 26.1.1 Reflect.apply(target, thisArgument, argumentsList) - var $export = __webpack_require__(8) - , aFunction = __webpack_require__(21) - , anObject = __webpack_require__(12) - , rApply = (__webpack_require__(4).Reflect || {}).apply - , fApply = Function.apply; - // MS Edge argumentsList argument is optional - $export($export.S + $export.F * !__webpack_require__(7)(function(){ - rApply(function(){}); - }), 'Reflect', { - apply: function apply(target, thisArgument, argumentsList){ - var T = aFunction(target) - , L = anObject(argumentsList); - return rApply ? rApply(T, thisArgument, L) : fApply.call(T, thisArgument, L); - } - }); - -/***/ }, -/* 233 */ -/***/ function(module, exports, __webpack_require__) { - - // 26.1.2 Reflect.construct(target, argumentsList [, newTarget]) - var $export = __webpack_require__(8) - , create = __webpack_require__(46) - , aFunction = __webpack_require__(21) - , anObject = __webpack_require__(12) - , isObject = __webpack_require__(13) - , fails = __webpack_require__(7) - , bind = __webpack_require__(77) - , rConstruct = (__webpack_require__(4).Reflect || {}).construct; - - // MS Edge supports only 2 arguments and argumentsList argument is optional - // FF Nightly sets third argument as `new.target`, but does not create `this` from it - var NEW_TARGET_BUG = fails(function(){ - function F(){} - return !(rConstruct(function(){}, [], F) instanceof F); - }); - var ARGS_BUG = !fails(function(){ - rConstruct(function(){}); - }); - - $export($export.S + $export.F * (NEW_TARGET_BUG || ARGS_BUG), 'Reflect', { - construct: function construct(Target, args /*, newTarget*/){ - aFunction(Target); - anObject(args); - var newTarget = arguments.length < 3 ? Target : aFunction(arguments[2]); - if(ARGS_BUG && !NEW_TARGET_BUG)return rConstruct(Target, args, newTarget); - if(Target == newTarget){ - // w/o altered newTarget, optimization for 0-4 arguments - switch(args.length){ - case 0: return new Target; - case 1: return new Target(args[0]); - case 2: return new Target(args[0], args[1]); - case 3: return new Target(args[0], args[1], args[2]); - case 4: return new Target(args[0], args[1], args[2], args[3]); - } - // w/o altered newTarget, lot of arguments case - var $args = [null]; - $args.push.apply($args, args); - return new (bind.apply(Target, $args)); - } - // with altered newTarget, not support built-in constructors - var proto = newTarget.prototype - , instance = create(isObject(proto) ? proto : Object.prototype) - , result = Function.apply.call(Target, instance, args); - return isObject(result) ? result : instance; - } - }); - -/***/ }, -/* 234 */ -/***/ function(module, exports, __webpack_require__) { - - // 26.1.3 Reflect.defineProperty(target, propertyKey, attributes) - var dP = __webpack_require__(11) - , $export = __webpack_require__(8) - , anObject = __webpack_require__(12) - , toPrimitive = __webpack_require__(16); - - // MS Edge has broken Reflect.defineProperty - throwing instead of returning false - $export($export.S + $export.F * __webpack_require__(7)(function(){ - Reflect.defineProperty(dP.f({}, 1, {value: 1}), 1, {value: 2}); - }), 'Reflect', { - defineProperty: function defineProperty(target, propertyKey, attributes){ - anObject(target); - propertyKey = toPrimitive(propertyKey, true); - anObject(attributes); - try { - dP.f(target, propertyKey, attributes); - return true; - } catch(e){ - return false; - } - } - }); - -/***/ }, -/* 235 */ -/***/ function(module, exports, __webpack_require__) { - - // 26.1.4 Reflect.deleteProperty(target, propertyKey) - var $export = __webpack_require__(8) - , gOPD = __webpack_require__(51).f - , anObject = __webpack_require__(12); - - $export($export.S, 'Reflect', { - deleteProperty: function deleteProperty(target, propertyKey){ - var desc = gOPD(anObject(target), propertyKey); - return desc && !desc.configurable ? false : delete target[propertyKey]; - } - }); - -/***/ }, -/* 236 */ -/***/ function(module, exports, __webpack_require__) { - - 'use strict'; - // 26.1.5 Reflect.enumerate(target) - var $export = __webpack_require__(8) - , anObject = __webpack_require__(12); - var Enumerate = function(iterated){ - this._t = anObject(iterated); // target - this._i = 0; // next index - var keys = this._k = [] // keys - , key; - for(key in iterated)keys.push(key); - }; - __webpack_require__(130)(Enumerate, 'Object', function(){ - var that = this - , keys = that._k - , key; - do { - if(that._i >= keys.length)return {value: undefined, done: true}; - } while(!((key = keys[that._i++]) in that._t)); - return {value: key, done: false}; - }); - - $export($export.S, 'Reflect', { - enumerate: function enumerate(target){ - return new Enumerate(target); - } - }); - -/***/ }, -/* 237 */ -/***/ function(module, exports, __webpack_require__) { - - // 26.1.6 Reflect.get(target, propertyKey [, receiver]) - var gOPD = __webpack_require__(51) - , getPrototypeOf = __webpack_require__(59) - , has = __webpack_require__(5) - , $export = __webpack_require__(8) - , isObject = __webpack_require__(13) - , anObject = __webpack_require__(12); - - function get(target, propertyKey/*, receiver*/){ - var receiver = arguments.length < 3 ? target : arguments[2] - , desc, proto; - if(anObject(target) === receiver)return target[propertyKey]; - if(desc = gOPD.f(target, propertyKey))return has(desc, 'value') - ? desc.value - : desc.get !== undefined - ? desc.get.call(receiver) - : undefined; - if(isObject(proto = getPrototypeOf(target)))return get(proto, propertyKey, receiver); - } - - $export($export.S, 'Reflect', {get: get}); - -/***/ }, -/* 238 */ -/***/ function(module, exports, __webpack_require__) { - - // 26.1.7 Reflect.getOwnPropertyDescriptor(target, propertyKey) - var gOPD = __webpack_require__(51) - , $export = __webpack_require__(8) - , anObject = __webpack_require__(12); - - $export($export.S, 'Reflect', { - getOwnPropertyDescriptor: function getOwnPropertyDescriptor(target, propertyKey){ - return gOPD.f(anObject(target), propertyKey); - } - }); - -/***/ }, -/* 239 */ -/***/ function(module, exports, __webpack_require__) { - - // 26.1.8 Reflect.getPrototypeOf(target) - var $export = __webpack_require__(8) - , getProto = __webpack_require__(59) - , anObject = __webpack_require__(12); - - $export($export.S, 'Reflect', { - getPrototypeOf: function getPrototypeOf(target){ - return getProto(anObject(target)); - } - }); - -/***/ }, -/* 240 */ -/***/ function(module, exports, __webpack_require__) { - - // 26.1.9 Reflect.has(target, propertyKey) - var $export = __webpack_require__(8); - - $export($export.S, 'Reflect', { - has: function has(target, propertyKey){ - return propertyKey in target; - } - }); - -/***/ }, -/* 241 */ -/***/ function(module, exports, __webpack_require__) { - - // 26.1.10 Reflect.isExtensible(target) - var $export = __webpack_require__(8) - , anObject = __webpack_require__(12) - , $isExtensible = Object.isExtensible; - - $export($export.S, 'Reflect', { - isExtensible: function isExtensible(target){ - anObject(target); - return $isExtensible ? $isExtensible(target) : true; - } - }); - -/***/ }, -/* 242 */ -/***/ function(module, exports, __webpack_require__) { - - // 26.1.11 Reflect.ownKeys(target) - var $export = __webpack_require__(8); - - $export($export.S, 'Reflect', {ownKeys: __webpack_require__(243)}); - -/***/ }, -/* 243 */ -/***/ function(module, exports, __webpack_require__) { - - // all object keys, includes non-enumerable and symbols - var gOPN = __webpack_require__(50) - , gOPS = __webpack_require__(43) - , anObject = __webpack_require__(12) - , Reflect = __webpack_require__(4).Reflect; - module.exports = Reflect && Reflect.ownKeys || function ownKeys(it){ - var keys = gOPN.f(anObject(it)) - , getSymbols = gOPS.f; - return getSymbols ? keys.concat(getSymbols(it)) : keys; - }; - -/***/ }, -/* 244 */ -/***/ function(module, exports, __webpack_require__) { - - // 26.1.12 Reflect.preventExtensions(target) - var $export = __webpack_require__(8) - , anObject = __webpack_require__(12) - , $preventExtensions = Object.preventExtensions; - - $export($export.S, 'Reflect', { - preventExtensions: function preventExtensions(target){ - anObject(target); - try { - if($preventExtensions)$preventExtensions(target); - return true; - } catch(e){ - return false; - } - } - }); - -/***/ }, -/* 245 */ -/***/ function(module, exports, __webpack_require__) { - - // 26.1.13 Reflect.set(target, propertyKey, V [, receiver]) - var dP = __webpack_require__(11) - , gOPD = __webpack_require__(51) - , getPrototypeOf = __webpack_require__(59) - , has = __webpack_require__(5) - , $export = __webpack_require__(8) - , createDesc = __webpack_require__(17) - , anObject = __webpack_require__(12) - , isObject = __webpack_require__(13); - - function set(target, propertyKey, V/*, receiver*/){ - var receiver = arguments.length < 4 ? target : arguments[3] - , ownDesc = gOPD.f(anObject(target), propertyKey) - , existingDescriptor, proto; - if(!ownDesc){ - if(isObject(proto = getPrototypeOf(target))){ - return set(proto, propertyKey, V, receiver); - } - ownDesc = createDesc(0); - } - if(has(ownDesc, 'value')){ - if(ownDesc.writable === false || !isObject(receiver))return false; - existingDescriptor = gOPD.f(receiver, propertyKey) || createDesc(0); - existingDescriptor.value = V; - dP.f(receiver, propertyKey, existingDescriptor); - return true; - } - return ownDesc.set === undefined ? false : (ownDesc.set.call(receiver, V), true); - } - - $export($export.S, 'Reflect', {set: set}); - -/***/ }, -/* 246 */ -/***/ function(module, exports, __webpack_require__) { - - // 26.1.14 Reflect.setPrototypeOf(target, proto) - var $export = __webpack_require__(8) - , setProto = __webpack_require__(73); - - if(setProto)$export($export.S, 'Reflect', { - setPrototypeOf: function setPrototypeOf(target, proto){ - setProto.check(target, proto); - try { - setProto.set(target, proto); - return true; - } catch(e){ - return false; - } - } - }); - -/***/ }, -/* 247 */ -/***/ function(module, exports, __webpack_require__) { - - 'use strict'; - // https://github.com/tc39/Array.prototype.includes - var $export = __webpack_require__(8) - , $includes = __webpack_require__(36)(true); - - $export($export.P, 'Array', { - includes: function includes(el /*, fromIndex = 0 */){ - return $includes(this, el, arguments.length > 1 ? arguments[1] : undefined); - } - }); - - __webpack_require__(186)('includes'); - -/***/ }, -/* 248 */ -/***/ function(module, exports, __webpack_require__) { - - 'use strict'; - // https://github.com/mathiasbynens/String.prototype.at - var $export = __webpack_require__(8) - , $at = __webpack_require__(127)(true); - - $export($export.P, 'String', { - at: function at(pos){ - return $at(this, pos); - } - }); - -/***/ }, -/* 249 */ -/***/ function(module, exports, __webpack_require__) { - - 'use strict'; - // https://github.com/tc39/proposal-string-pad-start-end - var $export = __webpack_require__(8) - , $pad = __webpack_require__(250); - - $export($export.P, 'String', { - padStart: function padStart(maxLength /*, fillString = ' ' */){ - return $pad(this, maxLength, arguments.length > 1 ? arguments[1] : undefined, true); - } - }); - -/***/ }, -/* 250 */ -/***/ function(module, exports, __webpack_require__) { - - // https://github.com/tc39/proposal-string-pad-start-end - var toLength = __webpack_require__(37) - , repeat = __webpack_require__(91) - , defined = __webpack_require__(35); - - module.exports = function(that, maxLength, fillString, left){ - var S = String(defined(that)) - , stringLength = S.length - , fillStr = fillString === undefined ? ' ' : String(fillString) - , intMaxLength = toLength(maxLength); - if(intMaxLength <= stringLength || fillStr == '')return S; - var fillLen = intMaxLength - stringLength - , stringFiller = repeat.call(fillStr, Math.ceil(fillLen / fillStr.length)); - if(stringFiller.length > fillLen)stringFiller = stringFiller.slice(0, fillLen); - return left ? stringFiller + S : S + stringFiller; - }; - - -/***/ }, -/* 251 */ -/***/ function(module, exports, __webpack_require__) { - - 'use strict'; - // https://github.com/tc39/proposal-string-pad-start-end - var $export = __webpack_require__(8) - , $pad = __webpack_require__(250); - - $export($export.P, 'String', { - padEnd: function padEnd(maxLength /*, fillString = ' ' */){ - return $pad(this, maxLength, arguments.length > 1 ? arguments[1] : undefined, false); - } - }); - -/***/ }, -/* 252 */ -/***/ function(module, exports, __webpack_require__) { - - 'use strict'; - // https://github.com/sebmarkbage/ecmascript-string-left-right-trim - __webpack_require__(83)('trimLeft', function($trim){ - return function trimLeft(){ - return $trim(this, 1); - }; - }, 'trimStart'); - -/***/ }, -/* 253 */ -/***/ function(module, exports, __webpack_require__) { - - 'use strict'; - // https://github.com/sebmarkbage/ecmascript-string-left-right-trim - __webpack_require__(83)('trimRight', function($trim){ - return function trimRight(){ - return $trim(this, 2); - }; - }, 'trimEnd'); - -/***/ }, -/* 254 */ -/***/ function(module, exports, __webpack_require__) { - - 'use strict'; - // https://tc39.github.io/String.prototype.matchAll/ - var $export = __webpack_require__(8) - , defined = __webpack_require__(35) - , toLength = __webpack_require__(37) - , isRegExp = __webpack_require__(134) - , getFlags = __webpack_require__(196) - , RegExpProto = RegExp.prototype; - - var $RegExpStringIterator = function(regexp, string){ - this._r = regexp; - this._s = string; - }; - - __webpack_require__(130)($RegExpStringIterator, 'RegExp String', function next(){ - var match = this._r.exec(this._s); - return {value: match, done: match === null}; - }); - - $export($export.P, 'String', { - matchAll: function matchAll(regexp){ - defined(this); - if(!isRegExp(regexp))throw TypeError(regexp + ' is not a regexp!'); - var S = String(this) - , flags = 'flags' in RegExpProto ? String(regexp.flags) : getFlags.call(regexp) - , rx = new RegExp(regexp.source, ~flags.indexOf('g') ? flags : 'g' + flags); - rx.lastIndex = toLength(regexp.lastIndex); - return new $RegExpStringIterator(rx, S); - } - }); - -/***/ }, -/* 255 */ -/***/ function(module, exports, __webpack_require__) { - - __webpack_require__(27)('asyncIterator'); - -/***/ }, -/* 256 */ -/***/ function(module, exports, __webpack_require__) { - - __webpack_require__(27)('observable'); - -/***/ }, -/* 257 */ -/***/ function(module, exports, __webpack_require__) { - - // https://github.com/tc39/proposal-object-getownpropertydescriptors - var $export = __webpack_require__(8) - , ownKeys = __webpack_require__(243) - , toIObject = __webpack_require__(32) - , gOPD = __webpack_require__(51) - , createProperty = __webpack_require__(163); - - $export($export.S, 'Object', { - getOwnPropertyDescriptors: function getOwnPropertyDescriptors(object){ - var O = toIObject(object) - , getDesc = gOPD.f - , keys = ownKeys(O) - , result = {} - , i = 0 - , key; - while(keys.length > i)createProperty(result, key = keys[i++], getDesc(O, key)); - return result; - } - }); - -/***/ }, -/* 258 */ -/***/ function(module, exports, __webpack_require__) { - - // https://github.com/tc39/proposal-object-values-entries - var $export = __webpack_require__(8) - , $values = __webpack_require__(259)(false); - - $export($export.S, 'Object', { - values: function values(it){ - return $values(it); - } - }); - -/***/ }, -/* 259 */ -/***/ function(module, exports, __webpack_require__) { - - var getKeys = __webpack_require__(30) - , toIObject = __webpack_require__(32) - , isEnum = __webpack_require__(44).f; - module.exports = function(isEntries){ - return function(it){ - var O = toIObject(it) - , keys = getKeys(O) - , length = keys.length - , i = 0 - , result = [] - , key; - while(length > i)if(isEnum.call(O, key = keys[i++])){ - result.push(isEntries ? [key, O[key]] : O[key]); - } return result; - }; - }; - -/***/ }, -/* 260 */ -/***/ function(module, exports, __webpack_require__) { - - // https://github.com/tc39/proposal-object-values-entries - var $export = __webpack_require__(8) - , $entries = __webpack_require__(259)(true); - - $export($export.S, 'Object', { - entries: function entries(it){ - return $entries(it); - } - }); - -/***/ }, -/* 261 */ -/***/ function(module, exports, __webpack_require__) { - - 'use strict'; - var $export = __webpack_require__(8) - , toObject = __webpack_require__(58) - , aFunction = __webpack_require__(21) - , $defineProperty = __webpack_require__(11); - - // B.2.2.2 Object.prototype.__defineGetter__(P, getter) - __webpack_require__(6) && $export($export.P + __webpack_require__(262), 'Object', { - __defineGetter__: function __defineGetter__(P, getter){ - $defineProperty.f(toObject(this), P, {get: aFunction(getter), enumerable: true, configurable: true}); - } - }); - -/***/ }, -/* 262 */ -/***/ function(module, exports, __webpack_require__) { - - // Forced replacement prototype accessors methods - module.exports = __webpack_require__(28)|| !__webpack_require__(7)(function(){ - var K = Math.random(); - // In FF throws only define methods - __defineSetter__.call(null, K, function(){ /* empty */}); - delete __webpack_require__(4)[K]; - }); - -/***/ }, -/* 263 */ -/***/ function(module, exports, __webpack_require__) { - - 'use strict'; - var $export = __webpack_require__(8) - , toObject = __webpack_require__(58) - , aFunction = __webpack_require__(21) - , $defineProperty = __webpack_require__(11); - - // B.2.2.3 Object.prototype.__defineSetter__(P, setter) - __webpack_require__(6) && $export($export.P + __webpack_require__(262), 'Object', { - __defineSetter__: function __defineSetter__(P, setter){ - $defineProperty.f(toObject(this), P, {set: aFunction(setter), enumerable: true, configurable: true}); - } - }); - -/***/ }, -/* 264 */ -/***/ function(module, exports, __webpack_require__) { - - 'use strict'; - var $export = __webpack_require__(8) - , toObject = __webpack_require__(58) - , toPrimitive = __webpack_require__(16) - , getPrototypeOf = __webpack_require__(59) - , getOwnPropertyDescriptor = __webpack_require__(51).f; - - // B.2.2.4 Object.prototype.__lookupGetter__(P) - __webpack_require__(6) && $export($export.P + __webpack_require__(262), 'Object', { - __lookupGetter__: function __lookupGetter__(P){ - var O = toObject(this) - , K = toPrimitive(P, true) - , D; - do { - if(D = getOwnPropertyDescriptor(O, K))return D.get; - } while(O = getPrototypeOf(O)); - } - }); - -/***/ }, -/* 265 */ -/***/ function(module, exports, __webpack_require__) { - - 'use strict'; - var $export = __webpack_require__(8) - , toObject = __webpack_require__(58) - , toPrimitive = __webpack_require__(16) - , getPrototypeOf = __webpack_require__(59) - , getOwnPropertyDescriptor = __webpack_require__(51).f; - - // B.2.2.5 Object.prototype.__lookupSetter__(P) - __webpack_require__(6) && $export($export.P + __webpack_require__(262), 'Object', { - __lookupSetter__: function __lookupSetter__(P){ - var O = toObject(this) - , K = toPrimitive(P, true) - , D; - do { - if(D = getOwnPropertyDescriptor(O, K))return D.set; - } while(O = getPrototypeOf(O)); - } - }); - -/***/ }, -/* 266 */ -/***/ function(module, exports, __webpack_require__) { - - // https://github.com/DavidBruant/Map-Set.prototype.toJSON - var $export = __webpack_require__(8); - - $export($export.P + $export.R, 'Map', {toJSON: __webpack_require__(267)('Map')}); - -/***/ }, -/* 267 */ -/***/ function(module, exports, __webpack_require__) { - - // https://github.com/DavidBruant/Map-Set.prototype.toJSON - var classof = __webpack_require__(75) - , from = __webpack_require__(268); - module.exports = function(NAME){ - return function toJSON(){ - if(classof(this) != NAME)throw TypeError(NAME + "#toJSON isn't generic"); - return from(this); - }; - }; - -/***/ }, -/* 268 */ -/***/ function(module, exports, __webpack_require__) { - - var forOf = __webpack_require__(206); - - module.exports = function(iter, ITERATOR){ - var result = []; - forOf(iter, false, result.push, result, ITERATOR); - return result; - }; - - -/***/ }, -/* 269 */ -/***/ function(module, exports, __webpack_require__) { - - // https://github.com/DavidBruant/Map-Set.prototype.toJSON - var $export = __webpack_require__(8); - - $export($export.P + $export.R, 'Set', {toJSON: __webpack_require__(267)('Set')}); - -/***/ }, -/* 270 */ -/***/ function(module, exports, __webpack_require__) { - - // https://github.com/ljharb/proposal-global - var $export = __webpack_require__(8); - - $export($export.S, 'System', {global: __webpack_require__(4)}); - -/***/ }, -/* 271 */ -/***/ function(module, exports, __webpack_require__) { - - // https://github.com/ljharb/proposal-is-error - var $export = __webpack_require__(8) - , cof = __webpack_require__(34); - - $export($export.S, 'Error', { - isError: function isError(it){ - return cof(it) === 'Error'; - } - }); - -/***/ }, -/* 272 */ -/***/ function(module, exports, __webpack_require__) { - - // https://gist.github.com/BrendanEich/4294d5c212a6d2254703 - var $export = __webpack_require__(8); - - $export($export.S, 'Math', { - iaddh: function iaddh(x0, x1, y0, y1){ - var $x0 = x0 >>> 0 - , $x1 = x1 >>> 0 - , $y0 = y0 >>> 0; - return $x1 + (y1 >>> 0) + (($x0 & $y0 | ($x0 | $y0) & ~($x0 + $y0 >>> 0)) >>> 31) | 0; - } - }); - -/***/ }, -/* 273 */ -/***/ function(module, exports, __webpack_require__) { - - // https://gist.github.com/BrendanEich/4294d5c212a6d2254703 - var $export = __webpack_require__(8); - - $export($export.S, 'Math', { - isubh: function isubh(x0, x1, y0, y1){ - var $x0 = x0 >>> 0 - , $x1 = x1 >>> 0 - , $y0 = y0 >>> 0; - return $x1 - (y1 >>> 0) - ((~$x0 & $y0 | ~($x0 ^ $y0) & $x0 - $y0 >>> 0) >>> 31) | 0; - } - }); - -/***/ }, -/* 274 */ -/***/ function(module, exports, __webpack_require__) { - - // https://gist.github.com/BrendanEich/4294d5c212a6d2254703 - var $export = __webpack_require__(8); - - $export($export.S, 'Math', { - imulh: function imulh(u, v){ - var UINT16 = 0xffff - , $u = +u - , $v = +v - , u0 = $u & UINT16 - , v0 = $v & UINT16 - , u1 = $u >> 16 - , v1 = $v >> 16 - , t = (u1 * v0 >>> 0) + (u0 * v0 >>> 16); - return u1 * v1 + (t >> 16) + ((u0 * v1 >>> 0) + (t & UINT16) >> 16); - } - }); - -/***/ }, -/* 275 */ -/***/ function(module, exports, __webpack_require__) { - - // https://gist.github.com/BrendanEich/4294d5c212a6d2254703 - var $export = __webpack_require__(8); - - $export($export.S, 'Math', { - umulh: function umulh(u, v){ - var UINT16 = 0xffff - , $u = +u - , $v = +v - , u0 = $u & UINT16 - , v0 = $v & UINT16 - , u1 = $u >>> 16 - , v1 = $v >>> 16 - , t = (u1 * v0 >>> 0) + (u0 * v0 >>> 16); - return u1 * v1 + (t >>> 16) + ((u0 * v1 >>> 0) + (t & UINT16) >>> 16); - } - }); - -/***/ }, -/* 276 */ -/***/ function(module, exports, __webpack_require__) { - - var metadata = __webpack_require__(277) - , anObject = __webpack_require__(12) - , toMetaKey = metadata.key - , ordinaryDefineOwnMetadata = metadata.set; - - metadata.exp({defineMetadata: function defineMetadata(metadataKey, metadataValue, target, targetKey){ - ordinaryDefineOwnMetadata(metadataKey, metadataValue, anObject(target), toMetaKey(targetKey)); - }}); - -/***/ }, -/* 277 */ -/***/ function(module, exports, __webpack_require__) { - - var Map = __webpack_require__(211) - , $export = __webpack_require__(8) - , shared = __webpack_require__(23)('metadata') - , store = shared.store || (shared.store = new (__webpack_require__(215))); - - var getOrCreateMetadataMap = function(target, targetKey, create){ - var targetMetadata = store.get(target); - if(!targetMetadata){ - if(!create)return undefined; - store.set(target, targetMetadata = new Map); - } - var keyMetadata = targetMetadata.get(targetKey); - if(!keyMetadata){ - if(!create)return undefined; - targetMetadata.set(targetKey, keyMetadata = new Map); - } return keyMetadata; - }; - var ordinaryHasOwnMetadata = function(MetadataKey, O, P){ - var metadataMap = getOrCreateMetadataMap(O, P, false); - return metadataMap === undefined ? false : metadataMap.has(MetadataKey); - }; - var ordinaryGetOwnMetadata = function(MetadataKey, O, P){ - var metadataMap = getOrCreateMetadataMap(O, P, false); - return metadataMap === undefined ? undefined : metadataMap.get(MetadataKey); - }; - var ordinaryDefineOwnMetadata = function(MetadataKey, MetadataValue, O, P){ - getOrCreateMetadataMap(O, P, true).set(MetadataKey, MetadataValue); - }; - var ordinaryOwnMetadataKeys = function(target, targetKey){ - var metadataMap = getOrCreateMetadataMap(target, targetKey, false) - , keys = []; - if(metadataMap)metadataMap.forEach(function(_, key){ keys.push(key); }); - return keys; - }; - var toMetaKey = function(it){ - return it === undefined || typeof it == 'symbol' ? it : String(it); - }; - var exp = function(O){ - $export($export.S, 'Reflect', O); - }; - - module.exports = { - store: store, - map: getOrCreateMetadataMap, - has: ordinaryHasOwnMetadata, - get: ordinaryGetOwnMetadata, - set: ordinaryDefineOwnMetadata, - keys: ordinaryOwnMetadataKeys, - key: toMetaKey, - exp: exp - }; - -/***/ }, -/* 278 */ -/***/ function(module, exports, __webpack_require__) { - - var metadata = __webpack_require__(277) - , anObject = __webpack_require__(12) - , toMetaKey = metadata.key - , getOrCreateMetadataMap = metadata.map - , store = metadata.store; - - metadata.exp({deleteMetadata: function deleteMetadata(metadataKey, target /*, targetKey */){ - var targetKey = arguments.length < 3 ? undefined : toMetaKey(arguments[2]) - , metadataMap = getOrCreateMetadataMap(anObject(target), targetKey, false); - if(metadataMap === undefined || !metadataMap['delete'](metadataKey))return false; - if(metadataMap.size)return true; - var targetMetadata = store.get(target); - targetMetadata['delete'](targetKey); - return !!targetMetadata.size || store['delete'](target); - }}); - -/***/ }, -/* 279 */ -/***/ function(module, exports, __webpack_require__) { - - var metadata = __webpack_require__(277) - , anObject = __webpack_require__(12) - , getPrototypeOf = __webpack_require__(59) - , ordinaryHasOwnMetadata = metadata.has - , ordinaryGetOwnMetadata = metadata.get - , toMetaKey = metadata.key; - - var ordinaryGetMetadata = function(MetadataKey, O, P){ - var hasOwn = ordinaryHasOwnMetadata(MetadataKey, O, P); - if(hasOwn)return ordinaryGetOwnMetadata(MetadataKey, O, P); - var parent = getPrototypeOf(O); - return parent !== null ? ordinaryGetMetadata(MetadataKey, parent, P) : undefined; - }; - - metadata.exp({getMetadata: function getMetadata(metadataKey, target /*, targetKey */){ - return ordinaryGetMetadata(metadataKey, anObject(target), arguments.length < 3 ? undefined : toMetaKey(arguments[2])); - }}); - -/***/ }, -/* 280 */ -/***/ function(module, exports, __webpack_require__) { - - var Set = __webpack_require__(214) - , from = __webpack_require__(268) - , metadata = __webpack_require__(277) - , anObject = __webpack_require__(12) - , getPrototypeOf = __webpack_require__(59) - , ordinaryOwnMetadataKeys = metadata.keys - , toMetaKey = metadata.key; - - var ordinaryMetadataKeys = function(O, P){ - var oKeys = ordinaryOwnMetadataKeys(O, P) - , parent = getPrototypeOf(O); - if(parent === null)return oKeys; - var pKeys = ordinaryMetadataKeys(parent, P); - return pKeys.length ? oKeys.length ? from(new Set(oKeys.concat(pKeys))) : pKeys : oKeys; - }; - - metadata.exp({getMetadataKeys: function getMetadataKeys(target /*, targetKey */){ - return ordinaryMetadataKeys(anObject(target), arguments.length < 2 ? undefined : toMetaKey(arguments[1])); - }}); - -/***/ }, -/* 281 */ -/***/ function(module, exports, __webpack_require__) { - - var metadata = __webpack_require__(277) - , anObject = __webpack_require__(12) - , ordinaryGetOwnMetadata = metadata.get - , toMetaKey = metadata.key; - - metadata.exp({getOwnMetadata: function getOwnMetadata(metadataKey, target /*, targetKey */){ - return ordinaryGetOwnMetadata(metadataKey, anObject(target) - , arguments.length < 3 ? undefined : toMetaKey(arguments[2])); - }}); - -/***/ }, -/* 282 */ -/***/ function(module, exports, __webpack_require__) { - - var metadata = __webpack_require__(277) - , anObject = __webpack_require__(12) - , ordinaryOwnMetadataKeys = metadata.keys - , toMetaKey = metadata.key; - - metadata.exp({getOwnMetadataKeys: function getOwnMetadataKeys(target /*, targetKey */){ - return ordinaryOwnMetadataKeys(anObject(target), arguments.length < 2 ? undefined : toMetaKey(arguments[1])); - }}); - -/***/ }, -/* 283 */ -/***/ function(module, exports, __webpack_require__) { - - var metadata = __webpack_require__(277) - , anObject = __webpack_require__(12) - , getPrototypeOf = __webpack_require__(59) - , ordinaryHasOwnMetadata = metadata.has - , toMetaKey = metadata.key; - - var ordinaryHasMetadata = function(MetadataKey, O, P){ - var hasOwn = ordinaryHasOwnMetadata(MetadataKey, O, P); - if(hasOwn)return true; - var parent = getPrototypeOf(O); - return parent !== null ? ordinaryHasMetadata(MetadataKey, parent, P) : false; - }; - - metadata.exp({hasMetadata: function hasMetadata(metadataKey, target /*, targetKey */){ - return ordinaryHasMetadata(metadataKey, anObject(target), arguments.length < 3 ? undefined : toMetaKey(arguments[2])); - }}); - -/***/ }, -/* 284 */ -/***/ function(module, exports, __webpack_require__) { - - var metadata = __webpack_require__(277) - , anObject = __webpack_require__(12) - , ordinaryHasOwnMetadata = metadata.has - , toMetaKey = metadata.key; - - metadata.exp({hasOwnMetadata: function hasOwnMetadata(metadataKey, target /*, targetKey */){ - return ordinaryHasOwnMetadata(metadataKey, anObject(target) - , arguments.length < 3 ? undefined : toMetaKey(arguments[2])); - }}); - -/***/ }, -/* 285 */ -/***/ function(module, exports, __webpack_require__) { - - var metadata = __webpack_require__(277) - , anObject = __webpack_require__(12) - , aFunction = __webpack_require__(21) - , toMetaKey = metadata.key - , ordinaryDefineOwnMetadata = metadata.set; - - metadata.exp({metadata: function metadata(metadataKey, metadataValue){ - return function decorator(target, targetKey){ - ordinaryDefineOwnMetadata( - metadataKey, metadataValue, - (targetKey !== undefined ? anObject : aFunction)(target), - toMetaKey(targetKey) - ); - }; - }}); - -/***/ }, -/* 286 */ -/***/ function(module, exports, __webpack_require__) { - - // https://github.com/rwaldron/tc39-notes/blob/master/es6/2014-09/sept-25.md#510-globalasap-for-enqueuing-a-microtask - var $export = __webpack_require__(8) - , microtask = __webpack_require__(209)() - , process = __webpack_require__(4).process - , isNode = __webpack_require__(34)(process) == 'process'; - - $export($export.G, { - asap: function asap(fn){ - var domain = isNode && process.domain; - microtask(domain ? domain.bind(fn) : fn); - } - }); - -/***/ }, -/* 287 */ -/***/ function(module, exports, __webpack_require__) { - - 'use strict'; - // https://github.com/zenparsing/es-observable - var $export = __webpack_require__(8) - , global = __webpack_require__(4) - , core = __webpack_require__(9) - , microtask = __webpack_require__(209)() - , OBSERVABLE = __webpack_require__(25)('observable') - , aFunction = __webpack_require__(21) - , anObject = __webpack_require__(12) - , anInstance = __webpack_require__(205) - , redefineAll = __webpack_require__(210) - , hide = __webpack_require__(10) - , forOf = __webpack_require__(206) - , RETURN = forOf.RETURN; - - var getMethod = function(fn){ - return fn == null ? undefined : aFunction(fn); - }; - - var cleanupSubscription = function(subscription){ - var cleanup = subscription._c; - if(cleanup){ - subscription._c = undefined; - cleanup(); - } - }; - - var subscriptionClosed = function(subscription){ - return subscription._o === undefined; - }; - - var closeSubscription = function(subscription){ - if(!subscriptionClosed(subscription)){ - subscription._o = undefined; - cleanupSubscription(subscription); - } - }; - - var Subscription = function(observer, subscriber){ - anObject(observer); - this._c = undefined; - this._o = observer; - observer = new SubscriptionObserver(this); - try { - var cleanup = subscriber(observer) - , subscription = cleanup; - if(cleanup != null){ - if(typeof cleanup.unsubscribe === 'function')cleanup = function(){ subscription.unsubscribe(); }; - else aFunction(cleanup); - this._c = cleanup; - } - } catch(e){ - observer.error(e); - return; - } if(subscriptionClosed(this))cleanupSubscription(this); - }; - - Subscription.prototype = redefineAll({}, { - unsubscribe: function unsubscribe(){ closeSubscription(this); } - }); - - var SubscriptionObserver = function(subscription){ - this._s = subscription; - }; - - SubscriptionObserver.prototype = redefineAll({}, { - next: function next(value){ - var subscription = this._s; - if(!subscriptionClosed(subscription)){ - var observer = subscription._o; - try { - var m = getMethod(observer.next); - if(m)return m.call(observer, value); - } catch(e){ - try { - closeSubscription(subscription); - } finally { - throw e; - } - } - } - }, - error: function error(value){ - var subscription = this._s; - if(subscriptionClosed(subscription))throw value; - var observer = subscription._o; - subscription._o = undefined; - try { - var m = getMethod(observer.error); - if(!m)throw value; - value = m.call(observer, value); - } catch(e){ - try { - cleanupSubscription(subscription); - } finally { - throw e; - } - } cleanupSubscription(subscription); - return value; - }, - complete: function complete(value){ - var subscription = this._s; - if(!subscriptionClosed(subscription)){ - var observer = subscription._o; - subscription._o = undefined; - try { - var m = getMethod(observer.complete); - value = m ? m.call(observer, value) : undefined; - } catch(e){ - try { - cleanupSubscription(subscription); - } finally { - throw e; - } - } cleanupSubscription(subscription); - return value; - } - } - }); - - var $Observable = function Observable(subscriber){ - anInstance(this, $Observable, 'Observable', '_f')._f = aFunction(subscriber); - }; - - redefineAll($Observable.prototype, { - subscribe: function subscribe(observer){ - return new Subscription(observer, this._f); - }, - forEach: function forEach(fn){ - var that = this; - return new (core.Promise || global.Promise)(function(resolve, reject){ - aFunction(fn); - var subscription = that.subscribe({ - next : function(value){ - try { - return fn(value); - } catch(e){ - reject(e); - subscription.unsubscribe(); - } - }, - error: reject, - complete: resolve - }); - }); - } - }); - - redefineAll($Observable, { - from: function from(x){ - var C = typeof this === 'function' ? this : $Observable; - var method = getMethod(anObject(x)[OBSERVABLE]); - if(method){ - var observable = anObject(method.call(x)); - return observable.constructor === C ? observable : new C(function(observer){ - return observable.subscribe(observer); - }); - } - return new C(function(observer){ - var done = false; - microtask(function(){ - if(!done){ - try { - if(forOf(x, false, function(it){ - observer.next(it); - if(done)return RETURN; - }) === RETURN)return; - } catch(e){ - if(done)throw e; - observer.error(e); - return; - } observer.complete(); - } - }); - return function(){ done = true; }; - }); - }, - of: function of(){ - for(var i = 0, l = arguments.length, items = Array(l); i < l;)items[i] = arguments[i++]; - return new (typeof this === 'function' ? this : $Observable)(function(observer){ - var done = false; - microtask(function(){ - if(!done){ - for(var i = 0; i < items.length; ++i){ - observer.next(items[i]); - if(done)return; - } observer.complete(); - } - }); - return function(){ done = true; }; - }); - } - }); - - hide($Observable.prototype, OBSERVABLE, function(){ return this; }); - - $export($export.G, {Observable: $Observable}); - - __webpack_require__(192)('Observable'); - -/***/ }, -/* 288 */ -/***/ function(module, exports, __webpack_require__) { - - // ie9- setTimeout & setInterval additional parameters fix - var global = __webpack_require__(4) - , $export = __webpack_require__(8) - , invoke = __webpack_require__(78) - , partial = __webpack_require__(289) - , navigator = global.navigator - , MSIE = !!navigator && /MSIE .\./.test(navigator.userAgent); // <- dirty ie9- check - var wrap = function(set){ - return MSIE ? function(fn, time /*, ...args */){ - return set(invoke( - partial, - [].slice.call(arguments, 2), - typeof fn == 'function' ? fn : Function(fn) - ), time); - } : set; - }; - $export($export.G + $export.B + $export.F * MSIE, { - setTimeout: wrap(global.setTimeout), - setInterval: wrap(global.setInterval) - }); - -/***/ }, -/* 289 */ -/***/ function(module, exports, __webpack_require__) { - - 'use strict'; - var path = __webpack_require__(290) - , invoke = __webpack_require__(78) - , aFunction = __webpack_require__(21); - module.exports = function(/* ...pargs */){ - var fn = aFunction(this) - , length = arguments.length - , pargs = Array(length) - , i = 0 - , _ = path._ - , holder = false; - while(length > i)if((pargs[i] = arguments[i++]) === _)holder = true; - return function(/* ...args */){ - var that = this - , aLen = arguments.length - , j = 0, k = 0, args; - if(!holder && !aLen)return invoke(fn, pargs, that); - args = pargs.slice(); - if(holder)for(;length > j; j++)if(args[j] === _)args[j] = arguments[k++]; - while(aLen > k)args.push(arguments[k++]); - return invoke(fn, args, that); - }; - }; - -/***/ }, -/* 290 */ -/***/ function(module, exports, __webpack_require__) { - - module.exports = __webpack_require__(4); - -/***/ }, -/* 291 */ -/***/ function(module, exports, __webpack_require__) { - - var $export = __webpack_require__(8) - , $task = __webpack_require__(208); - $export($export.G + $export.B, { - setImmediate: $task.set, - clearImmediate: $task.clear - }); - -/***/ }, -/* 292 */ -/***/ function(module, exports, __webpack_require__) { - - var $iterators = __webpack_require__(193) - , redefine = __webpack_require__(18) - , global = __webpack_require__(4) - , hide = __webpack_require__(10) - , Iterators = __webpack_require__(129) - , wks = __webpack_require__(25) - , ITERATOR = wks('iterator') - , TO_STRING_TAG = wks('toStringTag') - , ArrayValues = Iterators.Array; - - for(var collections = ['NodeList', 'DOMTokenList', 'MediaList', 'StyleSheetList', 'CSSRuleList'], i = 0; i < 5; i++){ - var NAME = collections[i] - , Collection = global[NAME] - , proto = Collection && Collection.prototype - , key; - if(proto){ - if(!proto[ITERATOR])hide(proto, ITERATOR, ArrayValues); - if(!proto[TO_STRING_TAG])hide(proto, TO_STRING_TAG, NAME); - Iterators[NAME] = ArrayValues; - for(key in $iterators)if(!proto[key])redefine(proto, key, $iterators[key], true); - } - } - -/***/ }, -/* 293 */ -/***/ function(module, exports, __webpack_require__) { - - /* WEBPACK VAR INJECTION */(function(global, process) {/** - * Copyright (c) 2014, Facebook, Inc. - * All rights reserved. - * - * This source code is licensed under the BSD-style license found in the - * https://raw.github.com/facebook/regenerator/master/LICENSE file. An - * additional grant of patent rights can be found in the PATENTS file in - * the same directory. - */ - - !(function(global) { - "use strict"; - - var hasOwn = Object.prototype.hasOwnProperty; - var undefined; // More compressible than void 0. - var $Symbol = typeof Symbol === "function" ? Symbol : {}; - var iteratorSymbol = $Symbol.iterator || "@@iterator"; - var toStringTagSymbol = $Symbol.toStringTag || "@@toStringTag"; - - var inModule = typeof module === "object"; - var runtime = global.regeneratorRuntime; - if (runtime) { - if (inModule) { - // If regeneratorRuntime is defined globally and we're in a module, - // make the exports object identical to regeneratorRuntime. - module.exports = runtime; - } - // Don't bother evaluating the rest of this file if the runtime was - // already defined globally. - return; - } - - // Define the runtime globally (as expected by generated code) as either - // module.exports (if we're in a module) or a new, empty object. - runtime = global.regeneratorRuntime = inModule ? module.exports : {}; - - function wrap(innerFn, outerFn, self, tryLocsList) { - // If outerFn provided and outerFn.prototype is a Generator, then outerFn.prototype instanceof Generator. - var protoGenerator = outerFn && outerFn.prototype instanceof Generator ? outerFn : Generator; - var generator = Object.create(protoGenerator.prototype); - var context = new Context(tryLocsList || []); - - // The ._invoke method unifies the implementations of the .next, - // .throw, and .return methods. - generator._invoke = makeInvokeMethod(innerFn, self, context); - - return generator; - } - runtime.wrap = wrap; - - // Try/catch helper to minimize deoptimizations. Returns a completion - // record like context.tryEntries[i].completion. This interface could - // have been (and was previously) designed to take a closure to be - // invoked without arguments, but in all the cases we care about we - // already have an existing method we want to call, so there's no need - // to create a new function object. We can even get away with assuming - // the method takes exactly one argument, since that happens to be true - // in every case, so we don't have to touch the arguments object. The - // only additional allocation required is the completion record, which - // has a stable shape and so hopefully should be cheap to allocate. - function tryCatch(fn, obj, arg) { - try { - return { type: "normal", arg: fn.call(obj, arg) }; - } catch (err) { - return { type: "throw", arg: err }; - } - } - - var GenStateSuspendedStart = "suspendedStart"; - var GenStateSuspendedYield = "suspendedYield"; - var GenStateExecuting = "executing"; - var GenStateCompleted = "completed"; - - // Returning this object from the innerFn has the same effect as - // breaking out of the dispatch switch statement. - var ContinueSentinel = {}; - - // Dummy constructor functions that we use as the .constructor and - // .constructor.prototype properties for functions that return Generator - // objects. For full spec compliance, you may wish to configure your - // minifier not to mangle the names of these two functions. - function Generator() {} - function GeneratorFunction() {} - function GeneratorFunctionPrototype() {} - - var Gp = GeneratorFunctionPrototype.prototype = Generator.prototype; - GeneratorFunction.prototype = Gp.constructor = GeneratorFunctionPrototype; - GeneratorFunctionPrototype.constructor = GeneratorFunction; - GeneratorFunctionPrototype[toStringTagSymbol] = GeneratorFunction.displayName = "GeneratorFunction"; - - // Helper for defining the .next, .throw, and .return methods of the - // Iterator interface in terms of a single ._invoke method. - function defineIteratorMethods(prototype) { - ["next", "throw", "return"].forEach(function(method) { - prototype[method] = function(arg) { - return this._invoke(method, arg); - }; - }); - } - - runtime.isGeneratorFunction = function(genFun) { - var ctor = typeof genFun === "function" && genFun.constructor; - return ctor - ? ctor === GeneratorFunction || - // For the native GeneratorFunction constructor, the best we can - // do is to check its .name property. - (ctor.displayName || ctor.name) === "GeneratorFunction" - : false; - }; - - runtime.mark = function(genFun) { - if (Object.setPrototypeOf) { - Object.setPrototypeOf(genFun, GeneratorFunctionPrototype); - } else { - genFun.__proto__ = GeneratorFunctionPrototype; - if (!(toStringTagSymbol in genFun)) { - genFun[toStringTagSymbol] = "GeneratorFunction"; - } - } - genFun.prototype = Object.create(Gp); - return genFun; - }; - - // Within the body of any async function, `await x` is transformed to - // `yield regeneratorRuntime.awrap(x)`, so that the runtime can test - // `value instanceof AwaitArgument` to determine if the yielded value is - // meant to be awaited. Some may consider the name of this method too - // cutesy, but they are curmudgeons. - runtime.awrap = function(arg) { - return new AwaitArgument(arg); - }; - - function AwaitArgument(arg) { - this.arg = arg; - } - - function AsyncIterator(generator) { - function invoke(method, arg, resolve, reject) { - var record = tryCatch(generator[method], generator, arg); - if (record.type === "throw") { - reject(record.arg); - } else { - var result = record.arg; - var value = result.value; - if (value instanceof AwaitArgument) { - return Promise.resolve(value.arg).then(function(value) { - invoke("next", value, resolve, reject); - }, function(err) { - invoke("throw", err, resolve, reject); - }); - } - - return Promise.resolve(value).then(function(unwrapped) { - // When a yielded Promise is resolved, its final value becomes - // the .value of the Promise<{value,done}> result for the - // current iteration. If the Promise is rejected, however, the - // result for this iteration will be rejected with the same - // reason. Note that rejections of yielded Promises are not - // thrown back into the generator function, as is the case - // when an awaited Promise is rejected. This difference in - // behavior between yield and await is important, because it - // allows the consumer to decide what to do with the yielded - // rejection (swallow it and continue, manually .throw it back - // into the generator, abandon iteration, whatever). With - // await, by contrast, there is no opportunity to examine the - // rejection reason outside the generator function, so the - // only option is to throw it from the await expression, and - // let the generator function handle the exception. - result.value = unwrapped; - resolve(result); - }, reject); - } - } - - if (typeof process === "object" && process.domain) { - invoke = process.domain.bind(invoke); - } - - var previousPromise; - - function enqueue(method, arg) { - function callInvokeWithMethodAndArg() { - return new Promise(function(resolve, reject) { - invoke(method, arg, resolve, reject); - }); - } - - return previousPromise = - // If enqueue has been called before, then we want to wait until - // all previous Promises have been resolved before calling invoke, - // so that results are always delivered in the correct order. If - // enqueue has not been called before, then it is important to - // call invoke immediately, without waiting on a callback to fire, - // so that the async generator function has the opportunity to do - // any necessary setup in a predictable way. This predictability - // is why the Promise constructor synchronously invokes its - // executor callback, and why async functions synchronously - // execute code before the first await. Since we implement simple - // async functions in terms of async generators, it is especially - // important to get this right, even though it requires care. - previousPromise ? previousPromise.then( - callInvokeWithMethodAndArg, - // Avoid propagating failures to Promises returned by later - // invocations of the iterator. - callInvokeWithMethodAndArg - ) : callInvokeWithMethodAndArg(); - } - - // Define the unified helper method that is used to implement .next, - // .throw, and .return (see defineIteratorMethods). - this._invoke = enqueue; - } - - defineIteratorMethods(AsyncIterator.prototype); - - // Note that simple async functions are implemented on top of - // AsyncIterator objects; they just return a Promise for the value of - // the final result produced by the iterator. - runtime.async = function(innerFn, outerFn, self, tryLocsList) { - var iter = new AsyncIterator( - wrap(innerFn, outerFn, self, tryLocsList) - ); - - return runtime.isGeneratorFunction(outerFn) - ? iter // If outerFn is a generator, return the full iterator. - : iter.next().then(function(result) { - return result.done ? result.value : iter.next(); - }); - }; - - function makeInvokeMethod(innerFn, self, context) { - var state = GenStateSuspendedStart; - - return function invoke(method, arg) { - if (state === GenStateExecuting) { - throw new Error("Generator is already running"); - } - - if (state === GenStateCompleted) { - if (method === "throw") { - throw arg; - } - - // Be forgiving, per 25.3.3.3.3 of the spec: - // https://people.mozilla.org/~jorendorff/es6-draft.html#sec-generatorresume - return doneResult(); - } - - while (true) { - var delegate = context.delegate; - if (delegate) { - if (method === "return" || - (method === "throw" && delegate.iterator[method] === undefined)) { - // A return or throw (when the delegate iterator has no throw - // method) always terminates the yield* loop. - context.delegate = null; - - // If the delegate iterator has a return method, give it a - // chance to clean up. - var returnMethod = delegate.iterator["return"]; - if (returnMethod) { - var record = tryCatch(returnMethod, delegate.iterator, arg); - if (record.type === "throw") { - // If the return method threw an exception, let that - // exception prevail over the original return or throw. - method = "throw"; - arg = record.arg; - continue; - } - } - - if (method === "return") { - // Continue with the outer return, now that the delegate - // iterator has been terminated. - continue; - } - } - - var record = tryCatch( - delegate.iterator[method], - delegate.iterator, - arg - ); - - if (record.type === "throw") { - context.delegate = null; - - // Like returning generator.throw(uncaught), but without the - // overhead of an extra function call. - method = "throw"; - arg = record.arg; - continue; - } - - // Delegate generator ran and handled its own exceptions so - // regardless of what the method was, we continue as if it is - // "next" with an undefined arg. - method = "next"; - arg = undefined; - - var info = record.arg; - if (info.done) { - context[delegate.resultName] = info.value; - context.next = delegate.nextLoc; - } else { - state = GenStateSuspendedYield; - return info; - } - - context.delegate = null; - } - - if (method === "next") { - // Setting context._sent for legacy support of Babel's - // function.sent implementation. - context.sent = context._sent = arg; - - } else if (method === "throw") { - if (state === GenStateSuspendedStart) { - state = GenStateCompleted; - throw arg; - } - - if (context.dispatchException(arg)) { - // If the dispatched exception was caught by a catch block, - // then let that catch block handle the exception normally. - method = "next"; - arg = undefined; - } - - } else if (method === "return") { - context.abrupt("return", arg); - } - - state = GenStateExecuting; - - var record = tryCatch(innerFn, self, context); - if (record.type === "normal") { - // If an exception is thrown from innerFn, we leave state === - // GenStateExecuting and loop back for another invocation. - state = context.done - ? GenStateCompleted - : GenStateSuspendedYield; - - var info = { - value: record.arg, - done: context.done - }; - - if (record.arg === ContinueSentinel) { - if (context.delegate && method === "next") { - // Deliberately forget the last sent value so that we don't - // accidentally pass it on to the delegate. - arg = undefined; - } - } else { - return info; - } - - } else if (record.type === "throw") { - state = GenStateCompleted; - // Dispatch the exception by looping back around to the - // context.dispatchException(arg) call above. - method = "throw"; - arg = record.arg; - } - } - }; - } - - // Define Generator.prototype.{next,throw,return} in terms of the - // unified ._invoke helper method. - defineIteratorMethods(Gp); - - Gp[iteratorSymbol] = function() { - return this; - }; - - Gp[toStringTagSymbol] = "Generator"; - - Gp.toString = function() { - return "[object Generator]"; - }; - - function pushTryEntry(locs) { - var entry = { tryLoc: locs[0] }; - - if (1 in locs) { - entry.catchLoc = locs[1]; - } - - if (2 in locs) { - entry.finallyLoc = locs[2]; - entry.afterLoc = locs[3]; - } - - this.tryEntries.push(entry); - } - - function resetTryEntry(entry) { - var record = entry.completion || {}; - record.type = "normal"; - delete record.arg; - entry.completion = record; - } - - function Context(tryLocsList) { - // The root entry object (effectively a try statement without a catch - // or a finally block) gives us a place to store values thrown from - // locations where there is no enclosing try statement. - this.tryEntries = [{ tryLoc: "root" }]; - tryLocsList.forEach(pushTryEntry, this); - this.reset(true); - } - - runtime.keys = function(object) { - var keys = []; - for (var key in object) { - keys.push(key); - } - keys.reverse(); - - // Rather than returning an object with a next method, we keep - // things simple and return the next function itself. - return function next() { - while (keys.length) { - var key = keys.pop(); - if (key in object) { - next.value = key; - next.done = false; - return next; - } - } - - // To avoid creating an additional object, we just hang the .value - // and .done properties off the next function object itself. This - // also ensures that the minifier will not anonymize the function. - next.done = true; - return next; - }; - }; - - function values(iterable) { - if (iterable) { - var iteratorMethod = iterable[iteratorSymbol]; - if (iteratorMethod) { - return iteratorMethod.call(iterable); - } - - if (typeof iterable.next === "function") { - return iterable; - } - - if (!isNaN(iterable.length)) { - var i = -1, next = function next() { - while (++i < iterable.length) { - if (hasOwn.call(iterable, i)) { - next.value = iterable[i]; - next.done = false; - return next; - } - } - - next.value = undefined; - next.done = true; - - return next; - }; - - return next.next = next; - } - } - - // Return an iterator with no values. - return { next: doneResult }; - } - runtime.values = values; - - function doneResult() { - return { value: undefined, done: true }; - } - - Context.prototype = { - constructor: Context, - - reset: function(skipTempReset) { - this.prev = 0; - this.next = 0; - // Resetting context._sent for legacy support of Babel's - // function.sent implementation. - this.sent = this._sent = undefined; - this.done = false; - this.delegate = null; - - this.tryEntries.forEach(resetTryEntry); - - if (!skipTempReset) { - for (var name in this) { - // Not sure about the optimal order of these conditions: - if (name.charAt(0) === "t" && - hasOwn.call(this, name) && - !isNaN(+name.slice(1))) { - this[name] = undefined; - } - } - } - }, - - stop: function() { - this.done = true; - - var rootEntry = this.tryEntries[0]; - var rootRecord = rootEntry.completion; - if (rootRecord.type === "throw") { - throw rootRecord.arg; - } - - return this.rval; - }, - - dispatchException: function(exception) { - if (this.done) { - throw exception; - } - - var context = this; - function handle(loc, caught) { - record.type = "throw"; - record.arg = exception; - context.next = loc; - return !!caught; - } - - for (var i = this.tryEntries.length - 1; i >= 0; --i) { - var entry = this.tryEntries[i]; - var record = entry.completion; - - if (entry.tryLoc === "root") { - // Exception thrown outside of any try block that could handle - // it, so set the completion value of the entire function to - // throw the exception. - return handle("end"); - } - - if (entry.tryLoc <= this.prev) { - var hasCatch = hasOwn.call(entry, "catchLoc"); - var hasFinally = hasOwn.call(entry, "finallyLoc"); - - if (hasCatch && hasFinally) { - if (this.prev < entry.catchLoc) { - return handle(entry.catchLoc, true); - } else if (this.prev < entry.finallyLoc) { - return handle(entry.finallyLoc); - } - - } else if (hasCatch) { - if (this.prev < entry.catchLoc) { - return handle(entry.catchLoc, true); - } - - } else if (hasFinally) { - if (this.prev < entry.finallyLoc) { - return handle(entry.finallyLoc); - } - - } else { - throw new Error("try statement without catch or finally"); - } - } - } - }, - - abrupt: function(type, arg) { - for (var i = this.tryEntries.length - 1; i >= 0; --i) { - var entry = this.tryEntries[i]; - if (entry.tryLoc <= this.prev && - hasOwn.call(entry, "finallyLoc") && - this.prev < entry.finallyLoc) { - var finallyEntry = entry; - break; - } - } - - if (finallyEntry && - (type === "break" || - type === "continue") && - finallyEntry.tryLoc <= arg && - arg <= finallyEntry.finallyLoc) { - // Ignore the finally entry if control is not jumping to a - // location outside the try/catch block. - finallyEntry = null; - } - - var record = finallyEntry ? finallyEntry.completion : {}; - record.type = type; - record.arg = arg; - - if (finallyEntry) { - this.next = finallyEntry.finallyLoc; - } else { - this.complete(record); - } - - return ContinueSentinel; - }, - - complete: function(record, afterLoc) { - if (record.type === "throw") { - throw record.arg; - } - - if (record.type === "break" || - record.type === "continue") { - this.next = record.arg; - } else if (record.type === "return") { - this.rval = record.arg; - this.next = "end"; - } else if (record.type === "normal" && afterLoc) { - this.next = afterLoc; - } - }, - - finish: function(finallyLoc) { - for (var i = this.tryEntries.length - 1; i >= 0; --i) { - var entry = this.tryEntries[i]; - if (entry.finallyLoc === finallyLoc) { - this.complete(entry.completion, entry.afterLoc); - resetTryEntry(entry); - return ContinueSentinel; - } - } - }, - - "catch": function(tryLoc) { - for (var i = this.tryEntries.length - 1; i >= 0; --i) { - var entry = this.tryEntries[i]; - if (entry.tryLoc === tryLoc) { - var record = entry.completion; - if (record.type === "throw") { - var thrown = record.arg; - resetTryEntry(entry); - } - return thrown; - } - } - - // The context.catch method must only be called with a location - // argument that corresponds to a known catch block. - throw new Error("illegal catch attempt"); - }, - - delegateYield: function(iterable, resultName, nextLoc) { - this.delegate = { - iterator: values(iterable), - resultName: resultName, - nextLoc: nextLoc - }; - - return ContinueSentinel; - } - }; - })( - // Among the various tricks for obtaining a reference to the global - // object, this seems to be the most reliable technique that does not - // use indirect eval (which violates Content Security Policy). - typeof global === "object" ? global : - typeof window === "object" ? window : - typeof self === "object" ? self : this - ); - - /* WEBPACK VAR INJECTION */}.call(exports, (function() { return this; }()), __webpack_require__(294))) - -/***/ }, -/* 294 */ -/***/ function(module, exports) { - - // shim for using process in browser - var process = module.exports = {}; - - // cached from whatever global is present so that test runners that stub it - // don't break things. But we need to wrap it in a try catch in case it is - // wrapped in strict mode code which doesn't define any globals. It's inside a - // function because try/catches deoptimize in certain engines. - - var cachedSetTimeout; - var cachedClearTimeout; - - function defaultSetTimout() { - throw new Error('setTimeout has not been defined'); - } - function defaultClearTimeout () { - throw new Error('clearTimeout has not been defined'); - } - (function () { - try { - if (typeof setTimeout === 'function') { - cachedSetTimeout = setTimeout; - } else { - cachedSetTimeout = defaultSetTimout; - } - } catch (e) { - cachedSetTimeout = defaultSetTimout; - } - try { - if (typeof clearTimeout === 'function') { - cachedClearTimeout = clearTimeout; - } else { - cachedClearTimeout = defaultClearTimeout; - } - } catch (e) { - cachedClearTimeout = defaultClearTimeout; - } - } ()) - function runTimeout(fun) { - if (cachedSetTimeout === setTimeout) { - //normal enviroments in sane situations - return setTimeout(fun, 0); - } - // if setTimeout wasn't available but was latter defined - if ((cachedSetTimeout === defaultSetTimout || !cachedSetTimeout) && setTimeout) { - cachedSetTimeout = setTimeout; - return setTimeout(fun, 0); - } - try { - // when when somebody has screwed with setTimeout but no I.E. maddness - return cachedSetTimeout(fun, 0); - } catch(e){ - try { - // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally - return cachedSetTimeout.call(null, fun, 0); - } catch(e){ - // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error - return cachedSetTimeout.call(this, fun, 0); - } - } - - - } - function runClearTimeout(marker) { - if (cachedClearTimeout === clearTimeout) { - //normal enviroments in sane situations - return clearTimeout(marker); - } - // if clearTimeout wasn't available but was latter defined - if ((cachedClearTimeout === defaultClearTimeout || !cachedClearTimeout) && clearTimeout) { - cachedClearTimeout = clearTimeout; - return clearTimeout(marker); - } - try { - // when when somebody has screwed with setTimeout but no I.E. maddness - return cachedClearTimeout(marker); - } catch (e){ - try { - // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally - return cachedClearTimeout.call(null, marker); - } catch (e){ - // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error. - // Some versions of I.E. have different rules for clearTimeout vs setTimeout - return cachedClearTimeout.call(this, marker); - } - } - - - - } - var queue = []; - var draining = false; - var currentQueue; - var queueIndex = -1; - - function cleanUpNextTick() { - if (!draining || !currentQueue) { - return; - } - draining = false; - if (currentQueue.length) { - queue = currentQueue.concat(queue); - } else { - queueIndex = -1; - } - if (queue.length) { - drainQueue(); - } - } - - function drainQueue() { - if (draining) { - return; - } - var timeout = runTimeout(cleanUpNextTick); - draining = true; - - var len = queue.length; - while(len) { - currentQueue = queue; - queue = []; - while (++queueIndex < len) { - if (currentQueue) { - currentQueue[queueIndex].run(); - } - } - queueIndex = -1; - len = queue.length; - } - currentQueue = null; - draining = false; - runClearTimeout(timeout); - } - - process.nextTick = function (fun) { - var args = new Array(arguments.length - 1); - if (arguments.length > 1) { - for (var i = 1; i < arguments.length; i++) { - args[i - 1] = arguments[i]; - } - } - queue.push(new Item(fun, args)); - if (queue.length === 1 && !draining) { - runTimeout(drainQueue); - } - }; - - // v8 likes predictible objects - function Item(fun, array) { - this.fun = fun; - this.array = array; - } - Item.prototype.run = function () { - this.fun.apply(null, this.array); - }; - process.title = 'browser'; - process.browser = true; - process.env = {}; - process.argv = []; - process.version = ''; // empty string to avoid regexp issues - process.versions = {}; - - function noop() {} - - process.on = noop; - process.addListener = noop; - process.once = noop; - process.off = noop; - process.removeListener = noop; - process.removeAllListeners = noop; - process.emit = noop; - - process.binding = function (name) { - throw new Error('process.binding is not supported'); - }; - - process.cwd = function () { return '/' }; - process.chdir = function (dir) { - throw new Error('process.chdir is not supported'); - }; - process.umask = function() { return 0; }; - - -/***/ }, -/* 295 */ -/***/ function(module, exports, __webpack_require__) { - - __webpack_require__(296); - module.exports = __webpack_require__(9).RegExp.escape; - -/***/ }, -/* 296 */ -/***/ function(module, exports, __webpack_require__) { - - // https://github.com/benjamingr/RexExp.escape - var $export = __webpack_require__(8) - , $re = __webpack_require__(297)(/[\\^$*+?.()|[\]{}]/g, '\\$&'); - - $export($export.S, 'RegExp', {escape: function escape(it){ return $re(it); }}); - - -/***/ }, -/* 297 */ -/***/ function(module, exports) { - - module.exports = function(regExp, replace){ - var replacer = replace === Object(replace) ? function(part){ - return replace[part]; - } : replace; - return function(it){ - return String(it).replace(regExp, replacer); - }; - }; - -/***/ }, -/* 298 */ -/***/ function(module, exports, __webpack_require__) { - - var BSON = __webpack_require__(299), - Binary = __webpack_require__(318), - Code = __webpack_require__(313), - DBRef = __webpack_require__(317), - Decimal128 = __webpack_require__(314), - Double = __webpack_require__(307), - Int32 = __webpack_require__(312), - Long = __webpack_require__(306), - Map = __webpack_require__(305), - MaxKey = __webpack_require__(316), - MinKey = __webpack_require__(315), - ObjectId = __webpack_require__(309), - BSONRegExp = __webpack_require__(310), - Symbol = __webpack_require__(311), - Timestamp = __webpack_require__(308); - - // BSON MAX VALUES - BSON.BSON_INT32_MAX = 0x7FFFFFFF; - BSON.BSON_INT32_MIN = -0x80000000; - - BSON.BSON_INT64_MAX = Math.pow(2, 63) - 1; - BSON.BSON_INT64_MIN = -Math.pow(2, 63); - - // JS MAX PRECISE VALUES - BSON.JS_INT_MAX = 0x20000000000000; // Any integer up to 2^53 can be precisely represented by a double. - BSON.JS_INT_MIN = -0x20000000000000; // Any integer down to -2^53 can be precisely represented by a double. - - // Add BSON types to function creation - BSON.Binary = Binary; - BSON.Code = Code; - BSON.DBRef = DBRef; - BSON.Decimal128 = Decimal128; - BSON.Double = Double; - BSON.Int32 = Int32; - BSON.Long = Long; - BSON.Map = Map; - BSON.MaxKey = MaxKey; - BSON.MinKey = MinKey; - BSON.ObjectId = ObjectId; - BSON.ObjectID = ObjectId; - BSON.BSONRegExp = BSONRegExp; - BSON.Symbol = Symbol; - BSON.Timestamp = Timestamp; - - // Return the BSON - module.exports = BSON; - -/***/ }, -/* 299 */ -/***/ function(module, exports, __webpack_require__) { - - /* WEBPACK VAR INJECTION */(function(Buffer) {"use strict"; - - var writeIEEE754 = __webpack_require__(304).writeIEEE754, - readIEEE754 = __webpack_require__(304).readIEEE754, - Map = __webpack_require__(305), - Long = __webpack_require__(306), - Double = __webpack_require__(307), - Timestamp = __webpack_require__(308), - ObjectID = __webpack_require__(309), - BSONRegExp = __webpack_require__(310), - Symbol = __webpack_require__(311), - Int32 = __webpack_require__(312), - Code = __webpack_require__(313), - Decimal128 = __webpack_require__(314), - MinKey = __webpack_require__(315), - MaxKey = __webpack_require__(316), - DBRef = __webpack_require__(317), - Binary = __webpack_require__(318); - - // Parts of the parser - var deserialize = __webpack_require__(319), - serializer = __webpack_require__(323), - calculateObjectSize = __webpack_require__(324); - - /** - * @ignore - * @api private - */ - // Max Size - var MAXSIZE = 1024 * 1024 * 17; - // Max Document Buffer size - var buffer = new Buffer(MAXSIZE); - - var BSON = function () {}; - - /** - * Serialize a Javascript object. - * - * @param {Object} object the Javascript object to serialize. - * @param {Boolean} [options.checkKeys] the serializer will check if keys are valid. - * @param {Boolean} [options.serializeFunctions=false] serialize the javascript functions **(default:false)**. - * @param {Boolean} [options.ignoreUndefined=true] ignore undefined fields **(default:true)**. - * @return {Buffer} returns the Buffer object containing the serialized object. - * @api public - */ - BSON.prototype.serialize = function serialize(object, options) { - options = options || {}; - // Unpack the options - var checkKeys = typeof options.checkKeys == 'boolean' ? options.checkKeys : false; - var serializeFunctions = typeof options.serializeFunctions == 'boolean' ? options.serializeFunctions : false; - var ignoreUndefined = typeof options.ignoreUndefined == 'boolean' ? options.ignoreUndefined : true; - - // console.log("===================================== serialize") - // console.log("checkKeys = " + checkKeys) - // console.log("serializeFunctions = " + serializeFunctions) - // console.log("ignoreUndefined = " + ignoreUndefined) - - // Attempt to serialize - var serializationIndex = serializer(buffer, object, checkKeys, 0, 0, serializeFunctions, ignoreUndefined, []); - // Create the final buffer - var finishedBuffer = new Buffer(serializationIndex); - // Copy into the finished buffer - buffer.copy(finishedBuffer, 0, 0, finishedBuffer.length); - // Return the buffer - return finishedBuffer; - }; - - /** - * Serialize a Javascript object using a predefined Buffer and index into the buffer, useful when pre-allocating the space for serialization. - * - * @param {Object} object the Javascript object to serialize. - * @param {Buffer} buffer the Buffer you pre-allocated to store the serialized BSON object. - * @param {Boolean} [options.checkKeys] the serializer will check if keys are valid. - * @param {Boolean} [options.serializeFunctions=false] serialize the javascript functions **(default:false)**. - * @param {Boolean} [options.ignoreUndefined=true] ignore undefined fields **(default:true)**. - * @param {Number} [options.index] the index in the buffer where we wish to start serializing into. - * @return {Number} returns the index pointing to the last written byte in the buffer. - * @api public - */ - BSON.prototype.serializeWithBufferAndIndex = function (object, finalBuffer, options) { - options = options || {}; - // Unpack the options - var checkKeys = typeof options.checkKeys == 'boolean' ? options.checkKeys : false; - var serializeFunctions = typeof options.serializeFunctions == 'boolean' ? options.serializeFunctions : false; - var ignoreUndefined = typeof options.ignoreUndefined == 'boolean' ? options.ignoreUndefined : true; - var startIndex = typeof options.index == 'number' ? options.index : 0; - - // console.log("===================================== serializeWithBufferAndIndex") - // console.log("checkKeys = " + checkKeys) - // console.log("serializeFunctions = " + serializeFunctions) - // console.log("ignoreUndefined = " + ignoreUndefined) - // console.log("startIndex = " + startIndex) - - // Attempt to serialize - var serializationIndex = serializer(buffer, object, checkKeys, startIndex || 0, 0, serializeFunctions, ignoreUndefined); - buffer.copy(finalBuffer, startIndex, 0, serializationIndex); - - // Return the index - return serializationIndex - 1; - }; - - /** - * Deserialize data as BSON. - * - * Options - * - **evalFunctions** {Boolean, default:false}, evaluate functions in the BSON document scoped to the object deserialized. - * - **cacheFunctions** {Boolean, default:false}, cache evaluated functions for reuse. - * - **cacheFunctionsCrc32** {Boolean, default:false}, use a crc32 code for caching, otherwise use the string of the function. - * - **promoteLongs** {Boolean, default:true}, when deserializing a Long will fit it into a Number if it's smaller than 53 bits - * - * @param {Buffer} buffer the buffer containing the serialized set of BSON documents. - * @param {Object} [options] additional options used for the deserialization. - * @param {Boolean} [isArray] ignore used for recursive parsing. - * @return {Object} returns the deserialized Javascript Object. - * @api public - */ - BSON.prototype.deserialize = function (data, options) { - return deserialize(data, options); - }; - - /** - * Calculate the bson size for a passed in Javascript object. - * - * @param {Object} object the Javascript object to calculate the BSON byte size for. - * @param {Boolean} [options.serializeFunctions=false] serialize the javascript functions **(default:false)**. - * @param {Boolean} [options.ignoreUndefined=true] ignore undefined fields **(default:true)**. - * @return {Number} returns the number of bytes the BSON object will take up. - * @api public - */ - BSON.prototype.calculateObjectSize = function (object, options) { - options = options || {}; - - var serializeFunctions = typeof options.serializeFunctions == 'boolean' ? options.serializeFunctions : false; - var ignoreUndefined = typeof options.ignoreUndefined == 'boolean' ? options.ignoreUndefined : true; - - return calculateObjectSize(object, serializeFunctions, ignoreUndefined); - }; - - /** - * Deserialize stream data as BSON documents. - * - * Options - * - **evalFunctions** {Boolean, default:false}, evaluate functions in the BSON document scoped to the object deserialized. - * - **cacheFunctions** {Boolean, default:false}, cache evaluated functions for reuse. - * - **cacheFunctionsCrc32** {Boolean, default:false}, use a crc32 code for caching, otherwise use the string of the function. - * - **promoteLongs** {Boolean, default:true}, when deserializing a Long will fit it into a Number if it's smaller than 53 bits - * - * @param {Buffer} data the buffer containing the serialized set of BSON documents. - * @param {Number} startIndex the start index in the data Buffer where the deserialization is to start. - * @param {Number} numberOfDocuments number of documents to deserialize. - * @param {Array} documents an array where to store the deserialized documents. - * @param {Number} docStartIndex the index in the documents array from where to start inserting documents. - * @param {Object} [options] additional options used for the deserialization. - * @return {Number} returns the next index in the buffer after deserialization **x** numbers of documents. - * @api public - */ - BSON.prototype.deserializeStream = function (data, startIndex, numberOfDocuments, documents, docStartIndex, options) { - // if(numberOfDocuments !== documents.length) throw new Error("Number of expected results back is less than the number of documents"); - options = options != null ? options : {}; - var index = startIndex; - // Loop over all documents - for (var i = 0; i < numberOfDocuments; i++) { - // Find size of the document - var size = data[index] | data[index + 1] << 8 | data[index + 2] << 16 | data[index + 3] << 24; - // Update options with index - options['index'] = index; - // Parse the document at this point - documents[docStartIndex + i] = this.deserialize(data, options); - // Adjust index by the document size - index = index + size; - } - - // Return object containing end index of parsing and list of documents - return index; - }; - - /** - * @ignore - * @api private - */ - // BSON MAX VALUES - BSON.BSON_INT32_MAX = 0x7FFFFFFF; - BSON.BSON_INT32_MIN = -0x80000000; - - BSON.BSON_INT64_MAX = Math.pow(2, 63) - 1; - BSON.BSON_INT64_MIN = -Math.pow(2, 63); - - // JS MAX PRECISE VALUES - BSON.JS_INT_MAX = 0x20000000000000; // Any integer up to 2^53 can be precisely represented by a double. - BSON.JS_INT_MIN = -0x20000000000000; // Any integer down to -2^53 can be precisely represented by a double. - - // Internal long versions - var JS_INT_MAX_LONG = Long.fromNumber(0x20000000000000); // Any integer up to 2^53 can be precisely represented by a double. - var JS_INT_MIN_LONG = Long.fromNumber(-0x20000000000000); // Any integer down to -2^53 can be precisely represented by a double. - - /** - * Number BSON Type - * - * @classconstant BSON_DATA_NUMBER - **/ - BSON.BSON_DATA_NUMBER = 1; - /** - * String BSON Type - * - * @classconstant BSON_DATA_STRING - **/ - BSON.BSON_DATA_STRING = 2; - /** - * Object BSON Type - * - * @classconstant BSON_DATA_OBJECT - **/ - BSON.BSON_DATA_OBJECT = 3; - /** - * Array BSON Type - * - * @classconstant BSON_DATA_ARRAY - **/ - BSON.BSON_DATA_ARRAY = 4; - /** - * Binary BSON Type - * - * @classconstant BSON_DATA_BINARY - **/ - BSON.BSON_DATA_BINARY = 5; - /** - * ObjectID BSON Type - * - * @classconstant BSON_DATA_OID - **/ - BSON.BSON_DATA_OID = 7; - /** - * Boolean BSON Type - * - * @classconstant BSON_DATA_BOOLEAN - **/ - BSON.BSON_DATA_BOOLEAN = 8; - /** - * Date BSON Type - * - * @classconstant BSON_DATA_DATE - **/ - BSON.BSON_DATA_DATE = 9; - /** - * null BSON Type - * - * @classconstant BSON_DATA_NULL - **/ - BSON.BSON_DATA_NULL = 10; - /** - * RegExp BSON Type - * - * @classconstant BSON_DATA_REGEXP - **/ - BSON.BSON_DATA_REGEXP = 11; - /** - * Code BSON Type - * - * @classconstant BSON_DATA_CODE - **/ - BSON.BSON_DATA_CODE = 13; - /** - * Symbol BSON Type - * - * @classconstant BSON_DATA_SYMBOL - **/ - BSON.BSON_DATA_SYMBOL = 14; - /** - * Code with Scope BSON Type - * - * @classconstant BSON_DATA_CODE_W_SCOPE - **/ - BSON.BSON_DATA_CODE_W_SCOPE = 15; - /** - * 32 bit Integer BSON Type - * - * @classconstant BSON_DATA_INT - **/ - BSON.BSON_DATA_INT = 16; - /** - * Timestamp BSON Type - * - * @classconstant BSON_DATA_TIMESTAMP - **/ - BSON.BSON_DATA_TIMESTAMP = 17; - /** - * Long BSON Type - * - * @classconstant BSON_DATA_LONG - **/ - BSON.BSON_DATA_LONG = 18; - /** - * MinKey BSON Type - * - * @classconstant BSON_DATA_MIN_KEY - **/ - BSON.BSON_DATA_MIN_KEY = 0xff; - /** - * MaxKey BSON Type - * - * @classconstant BSON_DATA_MAX_KEY - **/ - BSON.BSON_DATA_MAX_KEY = 0x7f; - - /** - * Binary Default Type - * - * @classconstant BSON_BINARY_SUBTYPE_DEFAULT - **/ - BSON.BSON_BINARY_SUBTYPE_DEFAULT = 0; - /** - * Binary Function Type - * - * @classconstant BSON_BINARY_SUBTYPE_FUNCTION - **/ - BSON.BSON_BINARY_SUBTYPE_FUNCTION = 1; - /** - * Binary Byte Array Type - * - * @classconstant BSON_BINARY_SUBTYPE_BYTE_ARRAY - **/ - BSON.BSON_BINARY_SUBTYPE_BYTE_ARRAY = 2; - /** - * Binary UUID Type - * - * @classconstant BSON_BINARY_SUBTYPE_UUID - **/ - BSON.BSON_BINARY_SUBTYPE_UUID = 3; - /** - * Binary MD5 Type - * - * @classconstant BSON_BINARY_SUBTYPE_MD5 - **/ - BSON.BSON_BINARY_SUBTYPE_MD5 = 4; - /** - * Binary User Defined Type - * - * @classconstant BSON_BINARY_SUBTYPE_USER_DEFINED - **/ - BSON.BSON_BINARY_SUBTYPE_USER_DEFINED = 128; - - // Return BSON - module.exports = BSON; - module.exports.Code = Code; - module.exports.Map = Map; - module.exports.Symbol = Symbol; - module.exports.BSON = BSON; - module.exports.DBRef = DBRef; - module.exports.Binary = Binary; - module.exports.ObjectID = ObjectID; - module.exports.Long = Long; - module.exports.Timestamp = Timestamp; - module.exports.Double = Double; - module.exports.Int32 = Int32; - module.exports.MinKey = MinKey; - module.exports.MaxKey = MaxKey; - module.exports.BSONRegExp = BSONRegExp; - module.exports.Decimal128 = Decimal128; - /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(300).Buffer)) - -/***/ }, -/* 300 */ -/***/ function(module, exports, __webpack_require__) { - - /* WEBPACK VAR INJECTION */(function(Buffer, global) {/*! - * The buffer module from node.js, for the browser. - * - * @author Feross Aboukhadijeh - * @license MIT - */ - /* eslint-disable no-proto */ - - 'use strict' - - var base64 = __webpack_require__(301) - var ieee754 = __webpack_require__(302) - var isArray = __webpack_require__(303) - - exports.Buffer = Buffer - exports.SlowBuffer = SlowBuffer - exports.INSPECT_MAX_BYTES = 50 - - /** - * If `Buffer.TYPED_ARRAY_SUPPORT`: - * === true Use Uint8Array implementation (fastest) - * === false Use Object implementation (most compatible, even IE6) - * - * Browsers that support typed arrays are IE 10+, Firefox 4+, Chrome 7+, Safari 5.1+, - * Opera 11.6+, iOS 4.2+. - * - * Due to various browser bugs, sometimes the Object implementation will be used even - * when the browser supports typed arrays. - * - * Note: - * - * - Firefox 4-29 lacks support for adding new properties to `Uint8Array` instances, - * See: https://bugzilla.mozilla.org/show_bug.cgi?id=695438. - * - * - Chrome 9-10 is missing the `TypedArray.prototype.subarray` function. - * - * - IE10 has a broken `TypedArray.prototype.subarray` function which returns arrays of - * incorrect length in some situations. - - * We detect these buggy browsers and set `Buffer.TYPED_ARRAY_SUPPORT` to `false` so they - * get the Object implementation, which is slower but behaves correctly. - */ - Buffer.TYPED_ARRAY_SUPPORT = global.TYPED_ARRAY_SUPPORT !== undefined - ? global.TYPED_ARRAY_SUPPORT - : typedArraySupport() - - /* - * Export kMaxLength after typed array support is determined. - */ - exports.kMaxLength = kMaxLength() - - function typedArraySupport () { - try { - var arr = new Uint8Array(1) - arr.__proto__ = {__proto__: Uint8Array.prototype, foo: function () { return 42 }} - return arr.foo() === 42 && // typed array instances can be augmented - typeof arr.subarray === 'function' && // chrome 9-10 lack `subarray` - arr.subarray(1, 1).byteLength === 0 // ie10 has broken `subarray` - } catch (e) { - return false - } - } - - function kMaxLength () { - return Buffer.TYPED_ARRAY_SUPPORT - ? 0x7fffffff - : 0x3fffffff - } - - function createBuffer (that, length) { - if (kMaxLength() < length) { - throw new RangeError('Invalid typed array length') - } - if (Buffer.TYPED_ARRAY_SUPPORT) { - // Return an augmented `Uint8Array` instance, for best performance - that = new Uint8Array(length) - that.__proto__ = Buffer.prototype - } else { - // Fallback: Return an object instance of the Buffer class - if (that === null) { - that = new Buffer(length) - } - that.length = length - } - - return that - } - - /** - * The Buffer constructor returns instances of `Uint8Array` that have their - * prototype changed to `Buffer.prototype`. Furthermore, `Buffer` is a subclass of - * `Uint8Array`, so the returned instances will have all the node `Buffer` methods - * and the `Uint8Array` methods. Square bracket notation works as expected -- it - * returns a single octet. - * - * The `Uint8Array` prototype remains unmodified. - */ - - function Buffer (arg, encodingOrOffset, length) { - if (!Buffer.TYPED_ARRAY_SUPPORT && !(this instanceof Buffer)) { - return new Buffer(arg, encodingOrOffset, length) - } - - // Common case. - if (typeof arg === 'number') { - if (typeof encodingOrOffset === 'string') { - throw new Error( - 'If encoding is specified then the first argument must be a string' - ) - } - return allocUnsafe(this, arg) - } - return from(this, arg, encodingOrOffset, length) - } - - Buffer.poolSize = 8192 // not used by this implementation - - // TODO: Legacy, not needed anymore. Remove in next major version. - Buffer._augment = function (arr) { - arr.__proto__ = Buffer.prototype - return arr - } - - function from (that, value, encodingOrOffset, length) { - if (typeof value === 'number') { - throw new TypeError('"value" argument must not be a number') - } - - if (typeof ArrayBuffer !== 'undefined' && value instanceof ArrayBuffer) { - return fromArrayBuffer(that, value, encodingOrOffset, length) - } - - if (typeof value === 'string') { - return fromString(that, value, encodingOrOffset) - } - - return fromObject(that, value) - } - - /** - * Functionally equivalent to Buffer(arg, encoding) but throws a TypeError - * if value is a number. - * Buffer.from(str[, encoding]) - * Buffer.from(array) - * Buffer.from(buffer) - * Buffer.from(arrayBuffer[, byteOffset[, length]]) - **/ - Buffer.from = function (value, encodingOrOffset, length) { - return from(null, value, encodingOrOffset, length) - } - - if (Buffer.TYPED_ARRAY_SUPPORT) { - Buffer.prototype.__proto__ = Uint8Array.prototype - Buffer.__proto__ = Uint8Array - if (typeof Symbol !== 'undefined' && Symbol.species && - Buffer[Symbol.species] === Buffer) { - // Fix subarray() in ES2016. See: https://github.com/feross/buffer/pull/97 - Object.defineProperty(Buffer, Symbol.species, { - value: null, - configurable: true - }) - } - } - - function assertSize (size) { - if (typeof size !== 'number') { - throw new TypeError('"size" argument must be a number') - } else if (size < 0) { - throw new RangeError('"size" argument must not be negative') - } - } - - function alloc (that, size, fill, encoding) { - assertSize(size) - if (size <= 0) { - return createBuffer(that, size) - } - if (fill !== undefined) { - // Only pay attention to encoding if it's a string. This - // prevents accidentally sending in a number that would - // be interpretted as a start offset. - return typeof encoding === 'string' - ? createBuffer(that, size).fill(fill, encoding) - : createBuffer(that, size).fill(fill) - } - return createBuffer(that, size) - } - - /** - * Creates a new filled Buffer instance. - * alloc(size[, fill[, encoding]]) - **/ - Buffer.alloc = function (size, fill, encoding) { - return alloc(null, size, fill, encoding) - } - - function allocUnsafe (that, size) { - assertSize(size) - that = createBuffer(that, size < 0 ? 0 : checked(size) | 0) - if (!Buffer.TYPED_ARRAY_SUPPORT) { - for (var i = 0; i < size; ++i) { - that[i] = 0 - } - } - return that - } - - /** - * Equivalent to Buffer(num), by default creates a non-zero-filled Buffer instance. - * */ - Buffer.allocUnsafe = function (size) { - return allocUnsafe(null, size) - } - /** - * Equivalent to SlowBuffer(num), by default creates a non-zero-filled Buffer instance. - */ - Buffer.allocUnsafeSlow = function (size) { - return allocUnsafe(null, size) - } - - function fromString (that, string, encoding) { - if (typeof encoding !== 'string' || encoding === '') { - encoding = 'utf8' - } - - if (!Buffer.isEncoding(encoding)) { - throw new TypeError('"encoding" must be a valid string encoding') - } - - var length = byteLength(string, encoding) | 0 - that = createBuffer(that, length) - - var actual = that.write(string, encoding) - - if (actual !== length) { - // Writing a hex string, for example, that contains invalid characters will - // cause everything after the first invalid character to be ignored. (e.g. - // 'abxxcd' will be treated as 'ab') - that = that.slice(0, actual) - } - - return that - } - - function fromArrayLike (that, array) { - var length = array.length < 0 ? 0 : checked(array.length) | 0 - that = createBuffer(that, length) - for (var i = 0; i < length; i += 1) { - that[i] = array[i] & 255 - } - return that - } - - function fromArrayBuffer (that, array, byteOffset, length) { - array.byteLength // this throws if `array` is not a valid ArrayBuffer - - if (byteOffset < 0 || array.byteLength < byteOffset) { - throw new RangeError('\'offset\' is out of bounds') - } - - if (array.byteLength < byteOffset + (length || 0)) { - throw new RangeError('\'length\' is out of bounds') - } - - if (byteOffset === undefined && length === undefined) { - array = new Uint8Array(array) - } else if (length === undefined) { - array = new Uint8Array(array, byteOffset) - } else { - array = new Uint8Array(array, byteOffset, length) - } - - if (Buffer.TYPED_ARRAY_SUPPORT) { - // Return an augmented `Uint8Array` instance, for best performance - that = array - that.__proto__ = Buffer.prototype - } else { - // Fallback: Return an object instance of the Buffer class - that = fromArrayLike(that, array) - } - return that - } - - function fromObject (that, obj) { - if (Buffer.isBuffer(obj)) { - var len = checked(obj.length) | 0 - that = createBuffer(that, len) - - if (that.length === 0) { - return that - } - - obj.copy(that, 0, 0, len) - return that - } - - if (obj) { - if ((typeof ArrayBuffer !== 'undefined' && - obj.buffer instanceof ArrayBuffer) || 'length' in obj) { - if (typeof obj.length !== 'number' || isnan(obj.length)) { - return createBuffer(that, 0) - } - return fromArrayLike(that, obj) - } - - if (obj.type === 'Buffer' && isArray(obj.data)) { - return fromArrayLike(that, obj.data) - } - } - - throw new TypeError('First argument must be a string, Buffer, ArrayBuffer, Array, or array-like object.') - } - - function checked (length) { - // Note: cannot use `length < kMaxLength()` here because that fails when - // length is NaN (which is otherwise coerced to zero.) - if (length >= kMaxLength()) { - throw new RangeError('Attempt to allocate Buffer larger than maximum ' + - 'size: 0x' + kMaxLength().toString(16) + ' bytes') - } - return length | 0 - } - - function SlowBuffer (length) { - if (+length != length) { // eslint-disable-line eqeqeq - length = 0 - } - return Buffer.alloc(+length) - } - - Buffer.isBuffer = function isBuffer (b) { - return !!(b != null && b._isBuffer) - } - - Buffer.compare = function compare (a, b) { - if (!Buffer.isBuffer(a) || !Buffer.isBuffer(b)) { - throw new TypeError('Arguments must be Buffers') - } - - if (a === b) return 0 - - var x = a.length - var y = b.length - - for (var i = 0, len = Math.min(x, y); i < len; ++i) { - if (a[i] !== b[i]) { - x = a[i] - y = b[i] - break - } - } - - if (x < y) return -1 - if (y < x) return 1 - return 0 - } - - Buffer.isEncoding = function isEncoding (encoding) { - switch (String(encoding).toLowerCase()) { - case 'hex': - case 'utf8': - case 'utf-8': - case 'ascii': - case 'latin1': - case 'binary': - case 'base64': - case 'ucs2': - case 'ucs-2': - case 'utf16le': - case 'utf-16le': - return true - default: - return false - } - } - - Buffer.concat = function concat (list, length) { - if (!isArray(list)) { - throw new TypeError('"list" argument must be an Array of Buffers') - } - - if (list.length === 0) { - return Buffer.alloc(0) - } - - var i - if (length === undefined) { - length = 0 - for (i = 0; i < list.length; ++i) { - length += list[i].length - } - } - - var buffer = Buffer.allocUnsafe(length) - var pos = 0 - for (i = 0; i < list.length; ++i) { - var buf = list[i] - if (!Buffer.isBuffer(buf)) { - throw new TypeError('"list" argument must be an Array of Buffers') - } - buf.copy(buffer, pos) - pos += buf.length - } - return buffer - } - - function byteLength (string, encoding) { - if (Buffer.isBuffer(string)) { - return string.length - } - if (typeof ArrayBuffer !== 'undefined' && typeof ArrayBuffer.isView === 'function' && - (ArrayBuffer.isView(string) || string instanceof ArrayBuffer)) { - return string.byteLength - } - if (typeof string !== 'string') { - string = '' + string - } - - var len = string.length - if (len === 0) return 0 - - // Use a for loop to avoid recursion - var loweredCase = false - for (;;) { - switch (encoding) { - case 'ascii': - case 'latin1': - case 'binary': - return len - case 'utf8': - case 'utf-8': - case undefined: - return utf8ToBytes(string).length - case 'ucs2': - case 'ucs-2': - case 'utf16le': - case 'utf-16le': - return len * 2 - case 'hex': - return len >>> 1 - case 'base64': - return base64ToBytes(string).length - default: - if (loweredCase) return utf8ToBytes(string).length // assume utf8 - encoding = ('' + encoding).toLowerCase() - loweredCase = true - } - } - } - Buffer.byteLength = byteLength - - function slowToString (encoding, start, end) { - var loweredCase = false - - // No need to verify that "this.length <= MAX_UINT32" since it's a read-only - // property of a typed array. - - // This behaves neither like String nor Uint8Array in that we set start/end - // to their upper/lower bounds if the value passed is out of range. - // undefined is handled specially as per ECMA-262 6th Edition, - // Section 13.3.3.7 Runtime Semantics: KeyedBindingInitialization. - if (start === undefined || start < 0) { - start = 0 - } - // Return early if start > this.length. Done here to prevent potential uint32 - // coercion fail below. - if (start > this.length) { - return '' - } - - if (end === undefined || end > this.length) { - end = this.length - } - - if (end <= 0) { - return '' - } - - // Force coersion to uint32. This will also coerce falsey/NaN values to 0. - end >>>= 0 - start >>>= 0 - - if (end <= start) { - return '' - } - - if (!encoding) encoding = 'utf8' - - while (true) { - switch (encoding) { - case 'hex': - return hexSlice(this, start, end) - - case 'utf8': - case 'utf-8': - return utf8Slice(this, start, end) - - case 'ascii': - return asciiSlice(this, start, end) - - case 'latin1': - case 'binary': - return latin1Slice(this, start, end) - - case 'base64': - return base64Slice(this, start, end) - - case 'ucs2': - case 'ucs-2': - case 'utf16le': - case 'utf-16le': - return utf16leSlice(this, start, end) - - default: - if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding) - encoding = (encoding + '').toLowerCase() - loweredCase = true - } - } - } - - // The property is used by `Buffer.isBuffer` and `is-buffer` (in Safari 5-7) to detect - // Buffer instances. - Buffer.prototype._isBuffer = true - - function swap (b, n, m) { - var i = b[n] - b[n] = b[m] - b[m] = i - } - - Buffer.prototype.swap16 = function swap16 () { - var len = this.length - if (len % 2 !== 0) { - throw new RangeError('Buffer size must be a multiple of 16-bits') - } - for (var i = 0; i < len; i += 2) { - swap(this, i, i + 1) - } - return this - } - - Buffer.prototype.swap32 = function swap32 () { - var len = this.length - if (len % 4 !== 0) { - throw new RangeError('Buffer size must be a multiple of 32-bits') - } - for (var i = 0; i < len; i += 4) { - swap(this, i, i + 3) - swap(this, i + 1, i + 2) - } - return this - } - - Buffer.prototype.swap64 = function swap64 () { - var len = this.length - if (len % 8 !== 0) { - throw new RangeError('Buffer size must be a multiple of 64-bits') - } - for (var i = 0; i < len; i += 8) { - swap(this, i, i + 7) - swap(this, i + 1, i + 6) - swap(this, i + 2, i + 5) - swap(this, i + 3, i + 4) - } - return this - } - - Buffer.prototype.toString = function toString () { - var length = this.length | 0 - if (length === 0) return '' - if (arguments.length === 0) return utf8Slice(this, 0, length) - return slowToString.apply(this, arguments) - } - - Buffer.prototype.equals = function equals (b) { - if (!Buffer.isBuffer(b)) throw new TypeError('Argument must be a Buffer') - if (this === b) return true - return Buffer.compare(this, b) === 0 - } - - Buffer.prototype.inspect = function inspect () { - var str = '' - var max = exports.INSPECT_MAX_BYTES - if (this.length > 0) { - str = this.toString('hex', 0, max).match(/.{2}/g).join(' ') - if (this.length > max) str += ' ... ' - } - return '' - } - - Buffer.prototype.compare = function compare (target, start, end, thisStart, thisEnd) { - if (!Buffer.isBuffer(target)) { - throw new TypeError('Argument must be a Buffer') - } - - if (start === undefined) { - start = 0 - } - if (end === undefined) { - end = target ? target.length : 0 - } - if (thisStart === undefined) { - thisStart = 0 - } - if (thisEnd === undefined) { - thisEnd = this.length - } - - if (start < 0 || end > target.length || thisStart < 0 || thisEnd > this.length) { - throw new RangeError('out of range index') - } - - if (thisStart >= thisEnd && start >= end) { - return 0 - } - if (thisStart >= thisEnd) { - return -1 - } - if (start >= end) { - return 1 - } - - start >>>= 0 - end >>>= 0 - thisStart >>>= 0 - thisEnd >>>= 0 - - if (this === target) return 0 - - var x = thisEnd - thisStart - var y = end - start - var len = Math.min(x, y) - - var thisCopy = this.slice(thisStart, thisEnd) - var targetCopy = target.slice(start, end) - - for (var i = 0; i < len; ++i) { - if (thisCopy[i] !== targetCopy[i]) { - x = thisCopy[i] - y = targetCopy[i] - break - } - } - - if (x < y) return -1 - if (y < x) return 1 - return 0 - } - - // Finds either the first index of `val` in `buffer` at offset >= `byteOffset`, - // OR the last index of `val` in `buffer` at offset <= `byteOffset`. - // - // Arguments: - // - buffer - a Buffer to search - // - val - a string, Buffer, or number - // - byteOffset - an index into `buffer`; will be clamped to an int32 - // - encoding - an optional encoding, relevant is val is a string - // - dir - true for indexOf, false for lastIndexOf - function bidirectionalIndexOf (buffer, val, byteOffset, encoding, dir) { - // Empty buffer means no match - if (buffer.length === 0) return -1 - - // Normalize byteOffset - if (typeof byteOffset === 'string') { - encoding = byteOffset - byteOffset = 0 - } else if (byteOffset > 0x7fffffff) { - byteOffset = 0x7fffffff - } else if (byteOffset < -0x80000000) { - byteOffset = -0x80000000 - } - byteOffset = +byteOffset // Coerce to Number. - if (isNaN(byteOffset)) { - // byteOffset: it it's undefined, null, NaN, "foo", etc, search whole buffer - byteOffset = dir ? 0 : (buffer.length - 1) - } - - // Normalize byteOffset: negative offsets start from the end of the buffer - if (byteOffset < 0) byteOffset = buffer.length + byteOffset - if (byteOffset >= buffer.length) { - if (dir) return -1 - else byteOffset = buffer.length - 1 - } else if (byteOffset < 0) { - if (dir) byteOffset = 0 - else return -1 - } - - // Normalize val - if (typeof val === 'string') { - val = Buffer.from(val, encoding) - } - - // Finally, search either indexOf (if dir is true) or lastIndexOf - if (Buffer.isBuffer(val)) { - // Special case: looking for empty string/buffer always fails - if (val.length === 0) { - return -1 - } - return arrayIndexOf(buffer, val, byteOffset, encoding, dir) - } else if (typeof val === 'number') { - val = val & 0xFF // Search for a byte value [0-255] - if (Buffer.TYPED_ARRAY_SUPPORT && - typeof Uint8Array.prototype.indexOf === 'function') { - if (dir) { - return Uint8Array.prototype.indexOf.call(buffer, val, byteOffset) - } else { - return Uint8Array.prototype.lastIndexOf.call(buffer, val, byteOffset) - } - } - return arrayIndexOf(buffer, [ val ], byteOffset, encoding, dir) - } - - throw new TypeError('val must be string, number or Buffer') - } - - function arrayIndexOf (arr, val, byteOffset, encoding, dir) { - var indexSize = 1 - var arrLength = arr.length - var valLength = val.length - - if (encoding !== undefined) { - encoding = String(encoding).toLowerCase() - if (encoding === 'ucs2' || encoding === 'ucs-2' || - encoding === 'utf16le' || encoding === 'utf-16le') { - if (arr.length < 2 || val.length < 2) { - return -1 - } - indexSize = 2 - arrLength /= 2 - valLength /= 2 - byteOffset /= 2 - } - } - - function read (buf, i) { - if (indexSize === 1) { - return buf[i] - } else { - return buf.readUInt16BE(i * indexSize) - } - } - - var i - if (dir) { - var foundIndex = -1 - for (i = byteOffset; i < arrLength; i++) { - if (read(arr, i) === read(val, foundIndex === -1 ? 0 : i - foundIndex)) { - if (foundIndex === -1) foundIndex = i - if (i - foundIndex + 1 === valLength) return foundIndex * indexSize - } else { - if (foundIndex !== -1) i -= i - foundIndex - foundIndex = -1 - } - } - } else { - if (byteOffset + valLength > arrLength) byteOffset = arrLength - valLength - for (i = byteOffset; i >= 0; i--) { - var found = true - for (var j = 0; j < valLength; j++) { - if (read(arr, i + j) !== read(val, j)) { - found = false - break - } - } - if (found) return i - } - } - - return -1 - } - - Buffer.prototype.includes = function includes (val, byteOffset, encoding) { - return this.indexOf(val, byteOffset, encoding) !== -1 - } - - Buffer.prototype.indexOf = function indexOf (val, byteOffset, encoding) { - return bidirectionalIndexOf(this, val, byteOffset, encoding, true) - } - - Buffer.prototype.lastIndexOf = function lastIndexOf (val, byteOffset, encoding) { - return bidirectionalIndexOf(this, val, byteOffset, encoding, false) - } - - function hexWrite (buf, string, offset, length) { - offset = Number(offset) || 0 - var remaining = buf.length - offset - if (!length) { - length = remaining - } else { - length = Number(length) - if (length > remaining) { - length = remaining - } - } - - // must be an even number of digits - var strLen = string.length - if (strLen % 2 !== 0) throw new TypeError('Invalid hex string') - - if (length > strLen / 2) { - length = strLen / 2 - } - for (var i = 0; i < length; ++i) { - var parsed = parseInt(string.substr(i * 2, 2), 16) - if (isNaN(parsed)) return i - buf[offset + i] = parsed - } - return i - } - - function utf8Write (buf, string, offset, length) { - return blitBuffer(utf8ToBytes(string, buf.length - offset), buf, offset, length) - } - - function asciiWrite (buf, string, offset, length) { - return blitBuffer(asciiToBytes(string), buf, offset, length) - } - - function latin1Write (buf, string, offset, length) { - return asciiWrite(buf, string, offset, length) - } - - function base64Write (buf, string, offset, length) { - return blitBuffer(base64ToBytes(string), buf, offset, length) - } - - function ucs2Write (buf, string, offset, length) { - return blitBuffer(utf16leToBytes(string, buf.length - offset), buf, offset, length) - } - - Buffer.prototype.write = function write (string, offset, length, encoding) { - // Buffer#write(string) - if (offset === undefined) { - encoding = 'utf8' - length = this.length - offset = 0 - // Buffer#write(string, encoding) - } else if (length === undefined && typeof offset === 'string') { - encoding = offset - length = this.length - offset = 0 - // Buffer#write(string, offset[, length][, encoding]) - } else if (isFinite(offset)) { - offset = offset | 0 - if (isFinite(length)) { - length = length | 0 - if (encoding === undefined) encoding = 'utf8' - } else { - encoding = length - length = undefined - } - // legacy write(string, encoding, offset, length) - remove in v0.13 - } else { - throw new Error( - 'Buffer.write(string, encoding, offset[, length]) is no longer supported' - ) - } - - var remaining = this.length - offset - if (length === undefined || length > remaining) length = remaining - - if ((string.length > 0 && (length < 0 || offset < 0)) || offset > this.length) { - throw new RangeError('Attempt to write outside buffer bounds') - } - - if (!encoding) encoding = 'utf8' - - var loweredCase = false - for (;;) { - switch (encoding) { - case 'hex': - return hexWrite(this, string, offset, length) - - case 'utf8': - case 'utf-8': - return utf8Write(this, string, offset, length) - - case 'ascii': - return asciiWrite(this, string, offset, length) - - case 'latin1': - case 'binary': - return latin1Write(this, string, offset, length) - - case 'base64': - // Warning: maxLength not taken into account in base64Write - return base64Write(this, string, offset, length) - - case 'ucs2': - case 'ucs-2': - case 'utf16le': - case 'utf-16le': - return ucs2Write(this, string, offset, length) - - default: - if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding) - encoding = ('' + encoding).toLowerCase() - loweredCase = true - } - } - } - - Buffer.prototype.toJSON = function toJSON () { - return { - type: 'Buffer', - data: Array.prototype.slice.call(this._arr || this, 0) - } - } - - function base64Slice (buf, start, end) { - if (start === 0 && end === buf.length) { - return base64.fromByteArray(buf) - } else { - return base64.fromByteArray(buf.slice(start, end)) - } - } - - function utf8Slice (buf, start, end) { - end = Math.min(buf.length, end) - var res = [] - - var i = start - while (i < end) { - var firstByte = buf[i] - var codePoint = null - var bytesPerSequence = (firstByte > 0xEF) ? 4 - : (firstByte > 0xDF) ? 3 - : (firstByte > 0xBF) ? 2 - : 1 - - if (i + bytesPerSequence <= end) { - var secondByte, thirdByte, fourthByte, tempCodePoint - - switch (bytesPerSequence) { - case 1: - if (firstByte < 0x80) { - codePoint = firstByte - } - break - case 2: - secondByte = buf[i + 1] - if ((secondByte & 0xC0) === 0x80) { - tempCodePoint = (firstByte & 0x1F) << 0x6 | (secondByte & 0x3F) - if (tempCodePoint > 0x7F) { - codePoint = tempCodePoint - } - } - break - case 3: - secondByte = buf[i + 1] - thirdByte = buf[i + 2] - if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80) { - tempCodePoint = (firstByte & 0xF) << 0xC | (secondByte & 0x3F) << 0x6 | (thirdByte & 0x3F) - if (tempCodePoint > 0x7FF && (tempCodePoint < 0xD800 || tempCodePoint > 0xDFFF)) { - codePoint = tempCodePoint - } - } - break - case 4: - secondByte = buf[i + 1] - thirdByte = buf[i + 2] - fourthByte = buf[i + 3] - if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80 && (fourthByte & 0xC0) === 0x80) { - tempCodePoint = (firstByte & 0xF) << 0x12 | (secondByte & 0x3F) << 0xC | (thirdByte & 0x3F) << 0x6 | (fourthByte & 0x3F) - if (tempCodePoint > 0xFFFF && tempCodePoint < 0x110000) { - codePoint = tempCodePoint - } - } - } - } - - if (codePoint === null) { - // we did not generate a valid codePoint so insert a - // replacement char (U+FFFD) and advance only 1 byte - codePoint = 0xFFFD - bytesPerSequence = 1 - } else if (codePoint > 0xFFFF) { - // encode to utf16 (surrogate pair dance) - codePoint -= 0x10000 - res.push(codePoint >>> 10 & 0x3FF | 0xD800) - codePoint = 0xDC00 | codePoint & 0x3FF - } - - res.push(codePoint) - i += bytesPerSequence - } - - return decodeCodePointsArray(res) - } - - // Based on http://stackoverflow.com/a/22747272/680742, the browser with - // the lowest limit is Chrome, with 0x10000 args. - // We go 1 magnitude less, for safety - var MAX_ARGUMENTS_LENGTH = 0x1000 - - function decodeCodePointsArray (codePoints) { - var len = codePoints.length - if (len <= MAX_ARGUMENTS_LENGTH) { - return String.fromCharCode.apply(String, codePoints) // avoid extra slice() - } - - // Decode in chunks to avoid "call stack size exceeded". - var res = '' - var i = 0 - while (i < len) { - res += String.fromCharCode.apply( - String, - codePoints.slice(i, i += MAX_ARGUMENTS_LENGTH) - ) - } - return res - } - - function asciiSlice (buf, start, end) { - var ret = '' - end = Math.min(buf.length, end) - - for (var i = start; i < end; ++i) { - ret += String.fromCharCode(buf[i] & 0x7F) - } - return ret - } - - function latin1Slice (buf, start, end) { - var ret = '' - end = Math.min(buf.length, end) - - for (var i = start; i < end; ++i) { - ret += String.fromCharCode(buf[i]) - } - return ret - } - - function hexSlice (buf, start, end) { - var len = buf.length - - if (!start || start < 0) start = 0 - if (!end || end < 0 || end > len) end = len - - var out = '' - for (var i = start; i < end; ++i) { - out += toHex(buf[i]) - } - return out - } - - function utf16leSlice (buf, start, end) { - var bytes = buf.slice(start, end) - var res = '' - for (var i = 0; i < bytes.length; i += 2) { - res += String.fromCharCode(bytes[i] + bytes[i + 1] * 256) - } - return res - } - - Buffer.prototype.slice = function slice (start, end) { - var len = this.length - start = ~~start - end = end === undefined ? len : ~~end - - if (start < 0) { - start += len - if (start < 0) start = 0 - } else if (start > len) { - start = len - } - - if (end < 0) { - end += len - if (end < 0) end = 0 - } else if (end > len) { - end = len - } - - if (end < start) end = start - - var newBuf - if (Buffer.TYPED_ARRAY_SUPPORT) { - newBuf = this.subarray(start, end) - newBuf.__proto__ = Buffer.prototype - } else { - var sliceLen = end - start - newBuf = new Buffer(sliceLen, undefined) - for (var i = 0; i < sliceLen; ++i) { - newBuf[i] = this[i + start] - } - } - - return newBuf - } - - /* - * Need to make sure that buffer isn't trying to write out of bounds. - */ - function checkOffset (offset, ext, length) { - if ((offset % 1) !== 0 || offset < 0) throw new RangeError('offset is not uint') - if (offset + ext > length) throw new RangeError('Trying to access beyond buffer length') - } - - Buffer.prototype.readUIntLE = function readUIntLE (offset, byteLength, noAssert) { - offset = offset | 0 - byteLength = byteLength | 0 - if (!noAssert) checkOffset(offset, byteLength, this.length) - - var val = this[offset] - var mul = 1 - var i = 0 - while (++i < byteLength && (mul *= 0x100)) { - val += this[offset + i] * mul - } - - return val - } - - Buffer.prototype.readUIntBE = function readUIntBE (offset, byteLength, noAssert) { - offset = offset | 0 - byteLength = byteLength | 0 - if (!noAssert) { - checkOffset(offset, byteLength, this.length) - } - - var val = this[offset + --byteLength] - var mul = 1 - while (byteLength > 0 && (mul *= 0x100)) { - val += this[offset + --byteLength] * mul - } - - return val - } - - Buffer.prototype.readUInt8 = function readUInt8 (offset, noAssert) { - if (!noAssert) checkOffset(offset, 1, this.length) - return this[offset] - } - - Buffer.prototype.readUInt16LE = function readUInt16LE (offset, noAssert) { - if (!noAssert) checkOffset(offset, 2, this.length) - return this[offset] | (this[offset + 1] << 8) - } - - Buffer.prototype.readUInt16BE = function readUInt16BE (offset, noAssert) { - if (!noAssert) checkOffset(offset, 2, this.length) - return (this[offset] << 8) | this[offset + 1] - } - - Buffer.prototype.readUInt32LE = function readUInt32LE (offset, noAssert) { - if (!noAssert) checkOffset(offset, 4, this.length) - - return ((this[offset]) | - (this[offset + 1] << 8) | - (this[offset + 2] << 16)) + - (this[offset + 3] * 0x1000000) - } - - Buffer.prototype.readUInt32BE = function readUInt32BE (offset, noAssert) { - if (!noAssert) checkOffset(offset, 4, this.length) - - return (this[offset] * 0x1000000) + - ((this[offset + 1] << 16) | - (this[offset + 2] << 8) | - this[offset + 3]) - } - - Buffer.prototype.readIntLE = function readIntLE (offset, byteLength, noAssert) { - offset = offset | 0 - byteLength = byteLength | 0 - if (!noAssert) checkOffset(offset, byteLength, this.length) - - var val = this[offset] - var mul = 1 - var i = 0 - while (++i < byteLength && (mul *= 0x100)) { - val += this[offset + i] * mul - } - mul *= 0x80 - - if (val >= mul) val -= Math.pow(2, 8 * byteLength) - - return val - } - - Buffer.prototype.readIntBE = function readIntBE (offset, byteLength, noAssert) { - offset = offset | 0 - byteLength = byteLength | 0 - if (!noAssert) checkOffset(offset, byteLength, this.length) - - var i = byteLength - var mul = 1 - var val = this[offset + --i] - while (i > 0 && (mul *= 0x100)) { - val += this[offset + --i] * mul - } - mul *= 0x80 - - if (val >= mul) val -= Math.pow(2, 8 * byteLength) - - return val - } - - Buffer.prototype.readInt8 = function readInt8 (offset, noAssert) { - if (!noAssert) checkOffset(offset, 1, this.length) - if (!(this[offset] & 0x80)) return (this[offset]) - return ((0xff - this[offset] + 1) * -1) - } - - Buffer.prototype.readInt16LE = function readInt16LE (offset, noAssert) { - if (!noAssert) checkOffset(offset, 2, this.length) - var val = this[offset] | (this[offset + 1] << 8) - return (val & 0x8000) ? val | 0xFFFF0000 : val - } - - Buffer.prototype.readInt16BE = function readInt16BE (offset, noAssert) { - if (!noAssert) checkOffset(offset, 2, this.length) - var val = this[offset + 1] | (this[offset] << 8) - return (val & 0x8000) ? val | 0xFFFF0000 : val - } - - Buffer.prototype.readInt32LE = function readInt32LE (offset, noAssert) { - if (!noAssert) checkOffset(offset, 4, this.length) - - return (this[offset]) | - (this[offset + 1] << 8) | - (this[offset + 2] << 16) | - (this[offset + 3] << 24) - } - - Buffer.prototype.readInt32BE = function readInt32BE (offset, noAssert) { - if (!noAssert) checkOffset(offset, 4, this.length) - - return (this[offset] << 24) | - (this[offset + 1] << 16) | - (this[offset + 2] << 8) | - (this[offset + 3]) - } - - Buffer.prototype.readFloatLE = function readFloatLE (offset, noAssert) { - if (!noAssert) checkOffset(offset, 4, this.length) - return ieee754.read(this, offset, true, 23, 4) - } - - Buffer.prototype.readFloatBE = function readFloatBE (offset, noAssert) { - if (!noAssert) checkOffset(offset, 4, this.length) - return ieee754.read(this, offset, false, 23, 4) - } - - Buffer.prototype.readDoubleLE = function readDoubleLE (offset, noAssert) { - if (!noAssert) checkOffset(offset, 8, this.length) - return ieee754.read(this, offset, true, 52, 8) - } - - Buffer.prototype.readDoubleBE = function readDoubleBE (offset, noAssert) { - if (!noAssert) checkOffset(offset, 8, this.length) - return ieee754.read(this, offset, false, 52, 8) - } - - function checkInt (buf, value, offset, ext, max, min) { - if (!Buffer.isBuffer(buf)) throw new TypeError('"buffer" argument must be a Buffer instance') - if (value > max || value < min) throw new RangeError('"value" argument is out of bounds') - if (offset + ext > buf.length) throw new RangeError('Index out of range') - } - - Buffer.prototype.writeUIntLE = function writeUIntLE (value, offset, byteLength, noAssert) { - value = +value - offset = offset | 0 - byteLength = byteLength | 0 - if (!noAssert) { - var maxBytes = Math.pow(2, 8 * byteLength) - 1 - checkInt(this, value, offset, byteLength, maxBytes, 0) - } - - var mul = 1 - var i = 0 - this[offset] = value & 0xFF - while (++i < byteLength && (mul *= 0x100)) { - this[offset + i] = (value / mul) & 0xFF - } - - return offset + byteLength - } - - Buffer.prototype.writeUIntBE = function writeUIntBE (value, offset, byteLength, noAssert) { - value = +value - offset = offset | 0 - byteLength = byteLength | 0 - if (!noAssert) { - var maxBytes = Math.pow(2, 8 * byteLength) - 1 - checkInt(this, value, offset, byteLength, maxBytes, 0) - } - - var i = byteLength - 1 - var mul = 1 - this[offset + i] = value & 0xFF - while (--i >= 0 && (mul *= 0x100)) { - this[offset + i] = (value / mul) & 0xFF - } - - return offset + byteLength - } - - Buffer.prototype.writeUInt8 = function writeUInt8 (value, offset, noAssert) { - value = +value - offset = offset | 0 - if (!noAssert) checkInt(this, value, offset, 1, 0xff, 0) - if (!Buffer.TYPED_ARRAY_SUPPORT) value = Math.floor(value) - this[offset] = (value & 0xff) - return offset + 1 - } - - function objectWriteUInt16 (buf, value, offset, littleEndian) { - if (value < 0) value = 0xffff + value + 1 - for (var i = 0, j = Math.min(buf.length - offset, 2); i < j; ++i) { - buf[offset + i] = (value & (0xff << (8 * (littleEndian ? i : 1 - i)))) >>> - (littleEndian ? i : 1 - i) * 8 - } - } - - Buffer.prototype.writeUInt16LE = function writeUInt16LE (value, offset, noAssert) { - value = +value - offset = offset | 0 - if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0) - if (Buffer.TYPED_ARRAY_SUPPORT) { - this[offset] = (value & 0xff) - this[offset + 1] = (value >>> 8) - } else { - objectWriteUInt16(this, value, offset, true) - } - return offset + 2 - } - - Buffer.prototype.writeUInt16BE = function writeUInt16BE (value, offset, noAssert) { - value = +value - offset = offset | 0 - if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0) - if (Buffer.TYPED_ARRAY_SUPPORT) { - this[offset] = (value >>> 8) - this[offset + 1] = (value & 0xff) - } else { - objectWriteUInt16(this, value, offset, false) - } - return offset + 2 - } - - function objectWriteUInt32 (buf, value, offset, littleEndian) { - if (value < 0) value = 0xffffffff + value + 1 - for (var i = 0, j = Math.min(buf.length - offset, 4); i < j; ++i) { - buf[offset + i] = (value >>> (littleEndian ? i : 3 - i) * 8) & 0xff - } - } - - Buffer.prototype.writeUInt32LE = function writeUInt32LE (value, offset, noAssert) { - value = +value - offset = offset | 0 - if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0) - if (Buffer.TYPED_ARRAY_SUPPORT) { - this[offset + 3] = (value >>> 24) - this[offset + 2] = (value >>> 16) - this[offset + 1] = (value >>> 8) - this[offset] = (value & 0xff) - } else { - objectWriteUInt32(this, value, offset, true) - } - return offset + 4 - } - - Buffer.prototype.writeUInt32BE = function writeUInt32BE (value, offset, noAssert) { - value = +value - offset = offset | 0 - if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0) - if (Buffer.TYPED_ARRAY_SUPPORT) { - this[offset] = (value >>> 24) - this[offset + 1] = (value >>> 16) - this[offset + 2] = (value >>> 8) - this[offset + 3] = (value & 0xff) - } else { - objectWriteUInt32(this, value, offset, false) - } - return offset + 4 - } - - Buffer.prototype.writeIntLE = function writeIntLE (value, offset, byteLength, noAssert) { - value = +value - offset = offset | 0 - if (!noAssert) { - var limit = Math.pow(2, 8 * byteLength - 1) - - checkInt(this, value, offset, byteLength, limit - 1, -limit) - } - - var i = 0 - var mul = 1 - var sub = 0 - this[offset] = value & 0xFF - while (++i < byteLength && (mul *= 0x100)) { - if (value < 0 && sub === 0 && this[offset + i - 1] !== 0) { - sub = 1 - } - this[offset + i] = ((value / mul) >> 0) - sub & 0xFF - } - - return offset + byteLength - } - - Buffer.prototype.writeIntBE = function writeIntBE (value, offset, byteLength, noAssert) { - value = +value - offset = offset | 0 - if (!noAssert) { - var limit = Math.pow(2, 8 * byteLength - 1) - - checkInt(this, value, offset, byteLength, limit - 1, -limit) - } - - var i = byteLength - 1 - var mul = 1 - var sub = 0 - this[offset + i] = value & 0xFF - while (--i >= 0 && (mul *= 0x100)) { - if (value < 0 && sub === 0 && this[offset + i + 1] !== 0) { - sub = 1 - } - this[offset + i] = ((value / mul) >> 0) - sub & 0xFF - } - - return offset + byteLength - } - - Buffer.prototype.writeInt8 = function writeInt8 (value, offset, noAssert) { - value = +value - offset = offset | 0 - if (!noAssert) checkInt(this, value, offset, 1, 0x7f, -0x80) - if (!Buffer.TYPED_ARRAY_SUPPORT) value = Math.floor(value) - if (value < 0) value = 0xff + value + 1 - this[offset] = (value & 0xff) - return offset + 1 - } - - Buffer.prototype.writeInt16LE = function writeInt16LE (value, offset, noAssert) { - value = +value - offset = offset | 0 - if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000) - if (Buffer.TYPED_ARRAY_SUPPORT) { - this[offset] = (value & 0xff) - this[offset + 1] = (value >>> 8) - } else { - objectWriteUInt16(this, value, offset, true) - } - return offset + 2 - } - - Buffer.prototype.writeInt16BE = function writeInt16BE (value, offset, noAssert) { - value = +value - offset = offset | 0 - if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000) - if (Buffer.TYPED_ARRAY_SUPPORT) { - this[offset] = (value >>> 8) - this[offset + 1] = (value & 0xff) - } else { - objectWriteUInt16(this, value, offset, false) - } - return offset + 2 - } - - Buffer.prototype.writeInt32LE = function writeInt32LE (value, offset, noAssert) { - value = +value - offset = offset | 0 - if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000) - if (Buffer.TYPED_ARRAY_SUPPORT) { - this[offset] = (value & 0xff) - this[offset + 1] = (value >>> 8) - this[offset + 2] = (value >>> 16) - this[offset + 3] = (value >>> 24) - } else { - objectWriteUInt32(this, value, offset, true) - } - return offset + 4 - } - - Buffer.prototype.writeInt32BE = function writeInt32BE (value, offset, noAssert) { - value = +value - offset = offset | 0 - if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000) - if (value < 0) value = 0xffffffff + value + 1 - if (Buffer.TYPED_ARRAY_SUPPORT) { - this[offset] = (value >>> 24) - this[offset + 1] = (value >>> 16) - this[offset + 2] = (value >>> 8) - this[offset + 3] = (value & 0xff) - } else { - objectWriteUInt32(this, value, offset, false) - } - return offset + 4 - } - - function checkIEEE754 (buf, value, offset, ext, max, min) { - if (offset + ext > buf.length) throw new RangeError('Index out of range') - if (offset < 0) throw new RangeError('Index out of range') - } - - function writeFloat (buf, value, offset, littleEndian, noAssert) { - if (!noAssert) { - checkIEEE754(buf, value, offset, 4, 3.4028234663852886e+38, -3.4028234663852886e+38) - } - ieee754.write(buf, value, offset, littleEndian, 23, 4) - return offset + 4 - } - - Buffer.prototype.writeFloatLE = function writeFloatLE (value, offset, noAssert) { - return writeFloat(this, value, offset, true, noAssert) - } - - Buffer.prototype.writeFloatBE = function writeFloatBE (value, offset, noAssert) { - return writeFloat(this, value, offset, false, noAssert) - } - - function writeDouble (buf, value, offset, littleEndian, noAssert) { - if (!noAssert) { - checkIEEE754(buf, value, offset, 8, 1.7976931348623157E+308, -1.7976931348623157E+308) - } - ieee754.write(buf, value, offset, littleEndian, 52, 8) - return offset + 8 - } - - Buffer.prototype.writeDoubleLE = function writeDoubleLE (value, offset, noAssert) { - return writeDouble(this, value, offset, true, noAssert) - } - - Buffer.prototype.writeDoubleBE = function writeDoubleBE (value, offset, noAssert) { - return writeDouble(this, value, offset, false, noAssert) - } - - // copy(targetBuffer, targetStart=0, sourceStart=0, sourceEnd=buffer.length) - Buffer.prototype.copy = function copy (target, targetStart, start, end) { - if (!start) start = 0 - if (!end && end !== 0) end = this.length - if (targetStart >= target.length) targetStart = target.length - if (!targetStart) targetStart = 0 - if (end > 0 && end < start) end = start - - // Copy 0 bytes; we're done - if (end === start) return 0 - if (target.length === 0 || this.length === 0) return 0 - - // Fatal error conditions - if (targetStart < 0) { - throw new RangeError('targetStart out of bounds') - } - if (start < 0 || start >= this.length) throw new RangeError('sourceStart out of bounds') - if (end < 0) throw new RangeError('sourceEnd out of bounds') - - // Are we oob? - if (end > this.length) end = this.length - if (target.length - targetStart < end - start) { - end = target.length - targetStart + start - } - - var len = end - start - var i - - if (this === target && start < targetStart && targetStart < end) { - // descending copy from end - for (i = len - 1; i >= 0; --i) { - target[i + targetStart] = this[i + start] - } - } else if (len < 1000 || !Buffer.TYPED_ARRAY_SUPPORT) { - // ascending copy from start - for (i = 0; i < len; ++i) { - target[i + targetStart] = this[i + start] - } - } else { - Uint8Array.prototype.set.call( - target, - this.subarray(start, start + len), - targetStart - ) - } - - return len - } - - // Usage: - // buffer.fill(number[, offset[, end]]) - // buffer.fill(buffer[, offset[, end]]) - // buffer.fill(string[, offset[, end]][, encoding]) - Buffer.prototype.fill = function fill (val, start, end, encoding) { - // Handle string cases: - if (typeof val === 'string') { - if (typeof start === 'string') { - encoding = start - start = 0 - end = this.length - } else if (typeof end === 'string') { - encoding = end - end = this.length - } - if (val.length === 1) { - var code = val.charCodeAt(0) - if (code < 256) { - val = code - } - } - if (encoding !== undefined && typeof encoding !== 'string') { - throw new TypeError('encoding must be a string') - } - if (typeof encoding === 'string' && !Buffer.isEncoding(encoding)) { - throw new TypeError('Unknown encoding: ' + encoding) - } - } else if (typeof val === 'number') { - val = val & 255 - } - - // Invalid ranges are not set to a default, so can range check early. - if (start < 0 || this.length < start || this.length < end) { - throw new RangeError('Out of range index') - } - - if (end <= start) { - return this - } - - start = start >>> 0 - end = end === undefined ? this.length : end >>> 0 - - if (!val) val = 0 - - var i - if (typeof val === 'number') { - for (i = start; i < end; ++i) { - this[i] = val - } - } else { - var bytes = Buffer.isBuffer(val) - ? val - : utf8ToBytes(new Buffer(val, encoding).toString()) - var len = bytes.length - for (i = 0; i < end - start; ++i) { - this[i + start] = bytes[i % len] - } - } - - return this - } - - // HELPER FUNCTIONS - // ================ - - var INVALID_BASE64_RE = /[^+\/0-9A-Za-z-_]/g - - function base64clean (str) { - // Node strips out invalid characters like \n and \t from the string, base64-js does not - str = stringtrim(str).replace(INVALID_BASE64_RE, '') - // Node converts strings with length < 2 to '' - if (str.length < 2) return '' - // Node allows for non-padded base64 strings (missing trailing ===), base64-js does not - while (str.length % 4 !== 0) { - str = str + '=' - } - return str - } - - function stringtrim (str) { - if (str.trim) return str.trim() - return str.replace(/^\s+|\s+$/g, '') - } - - function toHex (n) { - if (n < 16) return '0' + n.toString(16) - return n.toString(16) - } - - function utf8ToBytes (string, units) { - units = units || Infinity - var codePoint - var length = string.length - var leadSurrogate = null - var bytes = [] - - for (var i = 0; i < length; ++i) { - codePoint = string.charCodeAt(i) - - // is surrogate component - if (codePoint > 0xD7FF && codePoint < 0xE000) { - // last char was a lead - if (!leadSurrogate) { - // no lead yet - if (codePoint > 0xDBFF) { - // unexpected trail - if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD) - continue - } else if (i + 1 === length) { - // unpaired lead - if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD) - continue - } - - // valid lead - leadSurrogate = codePoint - - continue - } - - // 2 leads in a row - if (codePoint < 0xDC00) { - if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD) - leadSurrogate = codePoint - continue - } - - // valid surrogate pair - codePoint = (leadSurrogate - 0xD800 << 10 | codePoint - 0xDC00) + 0x10000 - } else if (leadSurrogate) { - // valid bmp char, but last char was a lead - if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD) - } - - leadSurrogate = null - - // encode utf8 - if (codePoint < 0x80) { - if ((units -= 1) < 0) break - bytes.push(codePoint) - } else if (codePoint < 0x800) { - if ((units -= 2) < 0) break - bytes.push( - codePoint >> 0x6 | 0xC0, - codePoint & 0x3F | 0x80 - ) - } else if (codePoint < 0x10000) { - if ((units -= 3) < 0) break - bytes.push( - codePoint >> 0xC | 0xE0, - codePoint >> 0x6 & 0x3F | 0x80, - codePoint & 0x3F | 0x80 - ) - } else if (codePoint < 0x110000) { - if ((units -= 4) < 0) break - bytes.push( - codePoint >> 0x12 | 0xF0, - codePoint >> 0xC & 0x3F | 0x80, - codePoint >> 0x6 & 0x3F | 0x80, - codePoint & 0x3F | 0x80 - ) - } else { - throw new Error('Invalid code point') - } - } - - return bytes - } - - function asciiToBytes (str) { - var byteArray = [] - for (var i = 0; i < str.length; ++i) { - // Node's code seems to be doing this and not & 0x7F.. - byteArray.push(str.charCodeAt(i) & 0xFF) - } - return byteArray - } - - function utf16leToBytes (str, units) { - var c, hi, lo - var byteArray = [] - for (var i = 0; i < str.length; ++i) { - if ((units -= 2) < 0) break - - c = str.charCodeAt(i) - hi = c >> 8 - lo = c % 256 - byteArray.push(lo) - byteArray.push(hi) - } - - return byteArray - } - - function base64ToBytes (str) { - return base64.toByteArray(base64clean(str)) - } - - function blitBuffer (src, dst, offset, length) { - for (var i = 0; i < length; ++i) { - if ((i + offset >= dst.length) || (i >= src.length)) break - dst[i + offset] = src[i] - } - return i - } - - function isnan (val) { - return val !== val // eslint-disable-line no-self-compare - } - - /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(300).Buffer, (function() { return this; }()))) - -/***/ }, -/* 301 */ -/***/ function(module, exports) { - - 'use strict' - - exports.byteLength = byteLength - exports.toByteArray = toByteArray - exports.fromByteArray = fromByteArray - - var lookup = [] - var revLookup = [] - var Arr = typeof Uint8Array !== 'undefined' ? Uint8Array : Array - - var code = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/' - for (var i = 0, len = code.length; i < len; ++i) { - lookup[i] = code[i] - revLookup[code.charCodeAt(i)] = i - } - - revLookup['-'.charCodeAt(0)] = 62 - revLookup['_'.charCodeAt(0)] = 63 - - function placeHoldersCount (b64) { - var len = b64.length - if (len % 4 > 0) { - throw new Error('Invalid string. Length must be a multiple of 4') - } - - // the number of equal signs (place holders) - // if there are two placeholders, than the two characters before it - // represent one byte - // if there is only one, then the three characters before it represent 2 bytes - // this is just a cheap hack to not do indexOf twice - return b64[len - 2] === '=' ? 2 : b64[len - 1] === '=' ? 1 : 0 - } - - function byteLength (b64) { - // base64 is 4/3 + up to two characters of the original data - return b64.length * 3 / 4 - placeHoldersCount(b64) - } - - function toByteArray (b64) { - var i, j, l, tmp, placeHolders, arr - var len = b64.length - placeHolders = placeHoldersCount(b64) - - arr = new Arr(len * 3 / 4 - placeHolders) - - // if there are placeholders, only get up to the last complete 4 chars - l = placeHolders > 0 ? len - 4 : len - - var L = 0 - - for (i = 0, j = 0; i < l; i += 4, j += 3) { - tmp = (revLookup[b64.charCodeAt(i)] << 18) | (revLookup[b64.charCodeAt(i + 1)] << 12) | (revLookup[b64.charCodeAt(i + 2)] << 6) | revLookup[b64.charCodeAt(i + 3)] - arr[L++] = (tmp >> 16) & 0xFF - arr[L++] = (tmp >> 8) & 0xFF - arr[L++] = tmp & 0xFF - } - - if (placeHolders === 2) { - tmp = (revLookup[b64.charCodeAt(i)] << 2) | (revLookup[b64.charCodeAt(i + 1)] >> 4) - arr[L++] = tmp & 0xFF - } else if (placeHolders === 1) { - tmp = (revLookup[b64.charCodeAt(i)] << 10) | (revLookup[b64.charCodeAt(i + 1)] << 4) | (revLookup[b64.charCodeAt(i + 2)] >> 2) - arr[L++] = (tmp >> 8) & 0xFF - arr[L++] = tmp & 0xFF - } - - return arr - } - - function tripletToBase64 (num) { - return lookup[num >> 18 & 0x3F] + lookup[num >> 12 & 0x3F] + lookup[num >> 6 & 0x3F] + lookup[num & 0x3F] - } - - function encodeChunk (uint8, start, end) { - var tmp - var output = [] - for (var i = start; i < end; i += 3) { - tmp = (uint8[i] << 16) + (uint8[i + 1] << 8) + (uint8[i + 2]) - output.push(tripletToBase64(tmp)) - } - return output.join('') - } - - function fromByteArray (uint8) { - var tmp - var len = uint8.length - var extraBytes = len % 3 // if we have 1 byte left, pad 2 bytes - var output = '' - var parts = [] - var maxChunkLength = 16383 // must be multiple of 3 - - // go through the array every three bytes, we'll deal with trailing stuff later - for (var i = 0, len2 = len - extraBytes; i < len2; i += maxChunkLength) { - parts.push(encodeChunk(uint8, i, (i + maxChunkLength) > len2 ? len2 : (i + maxChunkLength))) - } - - // pad the end with zeros, but make sure to not forget the extra bytes - if (extraBytes === 1) { - tmp = uint8[len - 1] - output += lookup[tmp >> 2] - output += lookup[(tmp << 4) & 0x3F] - output += '==' - } else if (extraBytes === 2) { - tmp = (uint8[len - 2] << 8) + (uint8[len - 1]) - output += lookup[tmp >> 10] - output += lookup[(tmp >> 4) & 0x3F] - output += lookup[(tmp << 2) & 0x3F] - output += '=' - } - - parts.push(output) - - return parts.join('') - } - - -/***/ }, -/* 302 */ -/***/ function(module, exports) { - - exports.read = function (buffer, offset, isLE, mLen, nBytes) { - var e, m - var eLen = nBytes * 8 - mLen - 1 - var eMax = (1 << eLen) - 1 - var eBias = eMax >> 1 - var nBits = -7 - var i = isLE ? (nBytes - 1) : 0 - var d = isLE ? -1 : 1 - var s = buffer[offset + i] - - i += d - - e = s & ((1 << (-nBits)) - 1) - s >>= (-nBits) - nBits += eLen - for (; nBits > 0; e = e * 256 + buffer[offset + i], i += d, nBits -= 8) {} - - m = e & ((1 << (-nBits)) - 1) - e >>= (-nBits) - nBits += mLen - for (; nBits > 0; m = m * 256 + buffer[offset + i], i += d, nBits -= 8) {} - - if (e === 0) { - e = 1 - eBias - } else if (e === eMax) { - return m ? NaN : ((s ? -1 : 1) * Infinity) - } else { - m = m + Math.pow(2, mLen) - e = e - eBias - } - return (s ? -1 : 1) * m * Math.pow(2, e - mLen) - } - - exports.write = function (buffer, value, offset, isLE, mLen, nBytes) { - var e, m, c - var eLen = nBytes * 8 - mLen - 1 - var eMax = (1 << eLen) - 1 - var eBias = eMax >> 1 - var rt = (mLen === 23 ? Math.pow(2, -24) - Math.pow(2, -77) : 0) - var i = isLE ? 0 : (nBytes - 1) - var d = isLE ? 1 : -1 - var s = value < 0 || (value === 0 && 1 / value < 0) ? 1 : 0 - - value = Math.abs(value) - - if (isNaN(value) || value === Infinity) { - m = isNaN(value) ? 1 : 0 - e = eMax - } else { - e = Math.floor(Math.log(value) / Math.LN2) - if (value * (c = Math.pow(2, -e)) < 1) { - e-- - c *= 2 - } - if (e + eBias >= 1) { - value += rt / c - } else { - value += rt * Math.pow(2, 1 - eBias) - } - if (value * c >= 2) { - e++ - c /= 2 - } - - if (e + eBias >= eMax) { - m = 0 - e = eMax - } else if (e + eBias >= 1) { - m = (value * c - 1) * Math.pow(2, mLen) - e = e + eBias - } else { - m = value * Math.pow(2, eBias - 1) * Math.pow(2, mLen) - e = 0 - } - } - - for (; mLen >= 8; buffer[offset + i] = m & 0xff, i += d, m /= 256, mLen -= 8) {} - - e = (e << mLen) | m - eLen += mLen - for (; eLen > 0; buffer[offset + i] = e & 0xff, i += d, e /= 256, eLen -= 8) {} - - buffer[offset + i - d] |= s * 128 - } - - -/***/ }, -/* 303 */ -/***/ function(module, exports) { - - var toString = {}.toString; - - module.exports = Array.isArray || function (arr) { - return toString.call(arr) == '[object Array]'; - }; - - -/***/ }, -/* 304 */ -/***/ function(module, exports) { - - // Copyright (c) 2008, Fair Oaks Labs, Inc. - // All rights reserved. - // - // Redistribution and use in source and binary forms, with or without - // modification, are permitted provided that the following conditions are met: - // - // * Redistributions of source code must retain the above copyright notice, - // this list of conditions and the following disclaimer. - // - // * Redistributions in binary form must reproduce the above copyright notice, - // this list of conditions and the following disclaimer in the documentation - // and/or other materials provided with the distribution. - // - // * Neither the name of Fair Oaks Labs, Inc. nor the names of its contributors - // may be used to endorse or promote products derived from this software - // without specific prior written permission. - // - // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE - // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE - // POSSIBILITY OF SUCH DAMAGE. - // - // - // Modifications to writeIEEE754 to support negative zeroes made by Brian White - - var readIEEE754 = function (buffer, offset, endian, mLen, nBytes) { - var e, - m, - bBE = endian === 'big', - eLen = nBytes * 8 - mLen - 1, - eMax = (1 << eLen) - 1, - eBias = eMax >> 1, - nBits = -7, - i = bBE ? 0 : nBytes - 1, - d = bBE ? 1 : -1, - s = buffer[offset + i]; - - i += d; - - e = s & (1 << -nBits) - 1; - s >>= -nBits; - nBits += eLen; - for (; nBits > 0; e = e * 256 + buffer[offset + i], i += d, nBits -= 8); - - m = e & (1 << -nBits) - 1; - e >>= -nBits; - nBits += mLen; - for (; nBits > 0; m = m * 256 + buffer[offset + i], i += d, nBits -= 8); - - if (e === 0) { - e = 1 - eBias; - } else if (e === eMax) { - return m ? NaN : (s ? -1 : 1) * Infinity; - } else { - m = m + Math.pow(2, mLen); - e = e - eBias; - } - return (s ? -1 : 1) * m * Math.pow(2, e - mLen); - }; - - var writeIEEE754 = function (buffer, value, offset, endian, mLen, nBytes) { - var e, - m, - c, - bBE = endian === 'big', - eLen = nBytes * 8 - mLen - 1, - eMax = (1 << eLen) - 1, - eBias = eMax >> 1, - rt = mLen === 23 ? Math.pow(2, -24) - Math.pow(2, -77) : 0, - i = bBE ? nBytes - 1 : 0, - d = bBE ? -1 : 1, - s = value < 0 || value === 0 && 1 / value < 0 ? 1 : 0; - - value = Math.abs(value); - - if (isNaN(value) || value === Infinity) { - m = isNaN(value) ? 1 : 0; - e = eMax; - } else { - e = Math.floor(Math.log(value) / Math.LN2); - if (value * (c = Math.pow(2, -e)) < 1) { - e--; - c *= 2; - } - if (e + eBias >= 1) { - value += rt / c; - } else { - value += rt * Math.pow(2, 1 - eBias); - } - if (value * c >= 2) { - e++; - c /= 2; - } - - if (e + eBias >= eMax) { - m = 0; - e = eMax; - } else if (e + eBias >= 1) { - m = (value * c - 1) * Math.pow(2, mLen); - e = e + eBias; - } else { - m = value * Math.pow(2, eBias - 1) * Math.pow(2, mLen); - e = 0; - } - } - - for (; mLen >= 8; buffer[offset + i] = m & 0xff, i += d, m /= 256, mLen -= 8); - - e = e << mLen | m; - eLen += mLen; - for (; eLen > 0; buffer[offset + i] = e & 0xff, i += d, e /= 256, eLen -= 8); - - buffer[offset + i - d] |= s * 128; - }; - - exports.readIEEE754 = readIEEE754; - exports.writeIEEE754 = writeIEEE754; - -/***/ }, -/* 305 */ -/***/ function(module, exports) { - - /* WEBPACK VAR INJECTION */(function(global) {"use strict"; - - // We have an ES6 Map available, return the native instance - - if (typeof global.Map !== 'undefined') { - module.exports = global.Map; - module.exports.Map = global.Map; - } else { - // We will return a polyfill - var Map = function (array) { - this._keys = []; - this._values = {}; - - for (var i = 0; i < array.length; i++) { - if (array[i] == null) continue; // skip null and undefined - var entry = array[i]; - var key = entry[0]; - var value = entry[1]; - // Add the key to the list of keys in order - this._keys.push(key); - // Add the key and value to the values dictionary with a point - // to the location in the ordered keys list - this._values[key] = { v: value, i: this._keys.length - 1 }; - } - }; - - Map.prototype.clear = function () { - this._keys = []; - this._values = {}; - }; - - Map.prototype.delete = function (key) { - var value = this._values[key]; - if (value == null) return false; - // Delete entry - delete this._values[key]; - // Remove the key from the ordered keys list - this._keys.splice(value.i, 1); - return true; - }; - - Map.prototype.entries = function () { - var self = this; - var index = 0; - - return { - next: function () { - var key = self._keys[index++]; - return { - value: key !== undefined ? [key, self._values[key].v] : undefined, - done: key !== undefined ? false : true - }; - } - }; - }; - - Map.prototype.forEach = function (callback, self) { - self = self || this; - - for (var i = 0; i < this._keys.length; i++) { - var key = this._keys[i]; - // Call the forEach callback - callback.call(self, this._values[key].v, key, self); - } - }; - - Map.prototype.get = function (key) { - return this._values[key] ? this._values[key].v : undefined; - }; - - Map.prototype.has = function (key) { - return this._values[key] != null; - }; - - Map.prototype.keys = function (key) { - var self = this; - var index = 0; - - return { - next: function () { - var key = self._keys[index++]; - return { - value: key !== undefined ? key : undefined, - done: key !== undefined ? false : true - }; - } - }; - }; - - Map.prototype.set = function (key, value) { - if (this._values[key]) { - this._values[key].v = value; - return this; - } - - // Add the key to the list of keys in order - this._keys.push(key); - // Add the key and value to the values dictionary with a point - // to the location in the ordered keys list - this._values[key] = { v: value, i: this._keys.length - 1 }; - return this; - }; - - Map.prototype.values = function (key, value) { - var self = this; - var index = 0; - - return { - next: function () { - var key = self._keys[index++]; - return { - value: key !== undefined ? self._values[key].v : undefined, - done: key !== undefined ? false : true - }; - } - }; - }; - - // Last ismaster - Object.defineProperty(Map.prototype, 'size', { - enumerable: true, - get: function () { - return this._keys.length; - } - }); - - module.exports = Map; - module.exports.Map = Map; - } - /* WEBPACK VAR INJECTION */}.call(exports, (function() { return this; }()))) - -/***/ }, -/* 306 */ -/***/ function(module, exports) { - - // Licensed under the Apache License, Version 2.0 (the "License"); - // you may not use this file except in compliance with the License. - // You may obtain a copy of the License at - // - // http://www.apache.org/licenses/LICENSE-2.0 - // - // Unless required by applicable law or agreed to in writing, software - // distributed under the License is distributed on an "AS IS" BASIS, - // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - // See the License for the specific language governing permissions and - // limitations under the License. - // - // Copyright 2009 Google Inc. All Rights Reserved - - /** - * Defines a Long class for representing a 64-bit two's-complement - * integer value, which faithfully simulates the behavior of a Java "Long". This - * implementation is derived from LongLib in GWT. - * - * Constructs a 64-bit two's-complement integer, given its low and high 32-bit - * values as *signed* integers. See the from* functions below for more - * convenient ways of constructing Longs. - * - * The internal representation of a Long is the two given signed, 32-bit values. - * We use 32-bit pieces because these are the size of integers on which - * Javascript performs bit-operations. For operations like addition and - * multiplication, we split each number into 16-bit pieces, which can easily be - * multiplied within Javascript's floating-point representation without overflow - * or change in sign. - * - * In the algorithms below, we frequently reduce the negative case to the - * positive case by negating the input(s) and then post-processing the result. - * Note that we must ALWAYS check specially whether those values are MIN_VALUE - * (-2^63) because -MIN_VALUE == MIN_VALUE (since 2^63 cannot be represented as - * a positive number, it overflows back into a negative). Not handling this - * case would often result in infinite recursion. - * - * @class - * @param {number} low the low (signed) 32 bits of the Long. - * @param {number} high the high (signed) 32 bits of the Long. - * @return {Long} - */ - function Long(low, high) { - if (!(this instanceof Long)) return new Long(low, high); - - this._bsontype = 'Long'; - /** - * @type {number} - * @ignore - */ - this.low_ = low | 0; // force into 32 signed bits. - - /** - * @type {number} - * @ignore - */ - this.high_ = high | 0; // force into 32 signed bits. - }; - - /** - * Return the int value. - * - * @method - * @return {number} the value, assuming it is a 32-bit integer. - */ - Long.prototype.toInt = function () { - return this.low_; - }; - - /** - * Return the Number value. - * - * @method - * @return {number} the closest floating-point representation to this value. - */ - Long.prototype.toNumber = function () { - return this.high_ * Long.TWO_PWR_32_DBL_ + this.getLowBitsUnsigned(); - }; - - /** - * Return the JSON value. - * - * @method - * @return {string} the JSON representation. - */ - Long.prototype.toJSON = function () { - return this.toString(); - }; - - /** - * Return the String value. - * - * @method - * @param {number} [opt_radix] the radix in which the text should be written. - * @return {string} the textual representation of this value. - */ - Long.prototype.toString = function (opt_radix) { - var radix = opt_radix || 10; - if (radix < 2 || 36 < radix) { - throw Error('radix out of range: ' + radix); - } - - if (this.isZero()) { - return '0'; - } - - if (this.isNegative()) { - if (this.equals(Long.MIN_VALUE)) { - // We need to change the Long value before it can be negated, so we remove - // the bottom-most digit in this base and then recurse to do the rest. - var radixLong = Long.fromNumber(radix); - var div = this.div(radixLong); - var rem = div.multiply(radixLong).subtract(this); - return div.toString(radix) + rem.toInt().toString(radix); - } else { - return '-' + this.negate().toString(radix); - } - } - - // Do several (6) digits each time through the loop, so as to - // minimize the calls to the very expensive emulated div. - var radixToPower = Long.fromNumber(Math.pow(radix, 6)); - - var rem = this; - var result = ''; - while (true) { - var remDiv = rem.div(radixToPower); - var intval = rem.subtract(remDiv.multiply(radixToPower)).toInt(); - var digits = intval.toString(radix); - - rem = remDiv; - if (rem.isZero()) { - return digits + result; - } else { - while (digits.length < 6) { - digits = '0' + digits; - } - result = '' + digits + result; - } - } - }; - - /** - * Return the high 32-bits value. - * - * @method - * @return {number} the high 32-bits as a signed value. - */ - Long.prototype.getHighBits = function () { - return this.high_; - }; - - /** - * Return the low 32-bits value. - * - * @method - * @return {number} the low 32-bits as a signed value. - */ - Long.prototype.getLowBits = function () { - return this.low_; - }; - - /** - * Return the low unsigned 32-bits value. - * - * @method - * @return {number} the low 32-bits as an unsigned value. - */ - Long.prototype.getLowBitsUnsigned = function () { - return this.low_ >= 0 ? this.low_ : Long.TWO_PWR_32_DBL_ + this.low_; - }; - - /** - * Returns the number of bits needed to represent the absolute value of this Long. - * - * @method - * @return {number} Returns the number of bits needed to represent the absolute value of this Long. - */ - Long.prototype.getNumBitsAbs = function () { - if (this.isNegative()) { - if (this.equals(Long.MIN_VALUE)) { - return 64; - } else { - return this.negate().getNumBitsAbs(); - } - } else { - var val = this.high_ != 0 ? this.high_ : this.low_; - for (var bit = 31; bit > 0; bit--) { - if ((val & 1 << bit) != 0) { - break; - } - } - return this.high_ != 0 ? bit + 33 : bit + 1; - } - }; - - /** - * Return whether this value is zero. - * - * @method - * @return {boolean} whether this value is zero. - */ - Long.prototype.isZero = function () { - return this.high_ == 0 && this.low_ == 0; - }; - - /** - * Return whether this value is negative. - * - * @method - * @return {boolean} whether this value is negative. - */ - Long.prototype.isNegative = function () { - return this.high_ < 0; - }; - - /** - * Return whether this value is odd. - * - * @method - * @return {boolean} whether this value is odd. - */ - Long.prototype.isOdd = function () { - return (this.low_ & 1) == 1; - }; - - /** - * Return whether this Long equals the other - * - * @method - * @param {Long} other Long to compare against. - * @return {boolean} whether this Long equals the other - */ - Long.prototype.equals = function (other) { - return this.high_ == other.high_ && this.low_ == other.low_; - }; - - /** - * Return whether this Long does not equal the other. - * - * @method - * @param {Long} other Long to compare against. - * @return {boolean} whether this Long does not equal the other. - */ - Long.prototype.notEquals = function (other) { - return this.high_ != other.high_ || this.low_ != other.low_; - }; - - /** - * Return whether this Long is less than the other. - * - * @method - * @param {Long} other Long to compare against. - * @return {boolean} whether this Long is less than the other. - */ - Long.prototype.lessThan = function (other) { - return this.compare(other) < 0; - }; - - /** - * Return whether this Long is less than or equal to the other. - * - * @method - * @param {Long} other Long to compare against. - * @return {boolean} whether this Long is less than or equal to the other. - */ - Long.prototype.lessThanOrEqual = function (other) { - return this.compare(other) <= 0; - }; - - /** - * Return whether this Long is greater than the other. - * - * @method - * @param {Long} other Long to compare against. - * @return {boolean} whether this Long is greater than the other. - */ - Long.prototype.greaterThan = function (other) { - return this.compare(other) > 0; - }; - - /** - * Return whether this Long is greater than or equal to the other. - * - * @method - * @param {Long} other Long to compare against. - * @return {boolean} whether this Long is greater than or equal to the other. - */ - Long.prototype.greaterThanOrEqual = function (other) { - return this.compare(other) >= 0; - }; - - /** - * Compares this Long with the given one. - * - * @method - * @param {Long} other Long to compare against. - * @return {boolean} 0 if they are the same, 1 if the this is greater, and -1 if the given one is greater. - */ - Long.prototype.compare = function (other) { - if (this.equals(other)) { - return 0; - } - - var thisNeg = this.isNegative(); - var otherNeg = other.isNegative(); - if (thisNeg && !otherNeg) { - return -1; - } - if (!thisNeg && otherNeg) { - return 1; - } - - // at this point, the signs are the same, so subtraction will not overflow - if (this.subtract(other).isNegative()) { - return -1; - } else { - return 1; - } - }; - - /** - * The negation of this value. - * - * @method - * @return {Long} the negation of this value. - */ - Long.prototype.negate = function () { - if (this.equals(Long.MIN_VALUE)) { - return Long.MIN_VALUE; - } else { - return this.not().add(Long.ONE); - } - }; - - /** - * Returns the sum of this and the given Long. - * - * @method - * @param {Long} other Long to add to this one. - * @return {Long} the sum of this and the given Long. - */ - Long.prototype.add = function (other) { - // Divide each number into 4 chunks of 16 bits, and then sum the chunks. - - var a48 = this.high_ >>> 16; - var a32 = this.high_ & 0xFFFF; - var a16 = this.low_ >>> 16; - var a00 = this.low_ & 0xFFFF; - - var b48 = other.high_ >>> 16; - var b32 = other.high_ & 0xFFFF; - var b16 = other.low_ >>> 16; - var b00 = other.low_ & 0xFFFF; - - var c48 = 0, - c32 = 0, - c16 = 0, - c00 = 0; - c00 += a00 + b00; - c16 += c00 >>> 16; - c00 &= 0xFFFF; - c16 += a16 + b16; - c32 += c16 >>> 16; - c16 &= 0xFFFF; - c32 += a32 + b32; - c48 += c32 >>> 16; - c32 &= 0xFFFF; - c48 += a48 + b48; - c48 &= 0xFFFF; - return Long.fromBits(c16 << 16 | c00, c48 << 16 | c32); - }; - - /** - * Returns the difference of this and the given Long. - * - * @method - * @param {Long} other Long to subtract from this. - * @return {Long} the difference of this and the given Long. - */ - Long.prototype.subtract = function (other) { - return this.add(other.negate()); - }; - - /** - * Returns the product of this and the given Long. - * - * @method - * @param {Long} other Long to multiply with this. - * @return {Long} the product of this and the other. - */ - Long.prototype.multiply = function (other) { - if (this.isZero()) { - return Long.ZERO; - } else if (other.isZero()) { - return Long.ZERO; - } - - if (this.equals(Long.MIN_VALUE)) { - return other.isOdd() ? Long.MIN_VALUE : Long.ZERO; - } else if (other.equals(Long.MIN_VALUE)) { - return this.isOdd() ? Long.MIN_VALUE : Long.ZERO; - } - - if (this.isNegative()) { - if (other.isNegative()) { - return this.negate().multiply(other.negate()); - } else { - return this.negate().multiply(other).negate(); - } - } else if (other.isNegative()) { - return this.multiply(other.negate()).negate(); - } - - // If both Longs are small, use float multiplication - if (this.lessThan(Long.TWO_PWR_24_) && other.lessThan(Long.TWO_PWR_24_)) { - return Long.fromNumber(this.toNumber() * other.toNumber()); - } - - // Divide each Long into 4 chunks of 16 bits, and then add up 4x4 products. - // We can skip products that would overflow. - - var a48 = this.high_ >>> 16; - var a32 = this.high_ & 0xFFFF; - var a16 = this.low_ >>> 16; - var a00 = this.low_ & 0xFFFF; - - var b48 = other.high_ >>> 16; - var b32 = other.high_ & 0xFFFF; - var b16 = other.low_ >>> 16; - var b00 = other.low_ & 0xFFFF; - - var c48 = 0, - c32 = 0, - c16 = 0, - c00 = 0; - c00 += a00 * b00; - c16 += c00 >>> 16; - c00 &= 0xFFFF; - c16 += a16 * b00; - c32 += c16 >>> 16; - c16 &= 0xFFFF; - c16 += a00 * b16; - c32 += c16 >>> 16; - c16 &= 0xFFFF; - c32 += a32 * b00; - c48 += c32 >>> 16; - c32 &= 0xFFFF; - c32 += a16 * b16; - c48 += c32 >>> 16; - c32 &= 0xFFFF; - c32 += a00 * b32; - c48 += c32 >>> 16; - c32 &= 0xFFFF; - c48 += a48 * b00 + a32 * b16 + a16 * b32 + a00 * b48; - c48 &= 0xFFFF; - return Long.fromBits(c16 << 16 | c00, c48 << 16 | c32); - }; - - /** - * Returns this Long divided by the given one. - * - * @method - * @param {Long} other Long by which to divide. - * @return {Long} this Long divided by the given one. - */ - Long.prototype.div = function (other) { - if (other.isZero()) { - throw Error('division by zero'); - } else if (this.isZero()) { - return Long.ZERO; - } - - if (this.equals(Long.MIN_VALUE)) { - if (other.equals(Long.ONE) || other.equals(Long.NEG_ONE)) { - return Long.MIN_VALUE; // recall that -MIN_VALUE == MIN_VALUE - } else if (other.equals(Long.MIN_VALUE)) { - return Long.ONE; - } else { - // At this point, we have |other| >= 2, so |this/other| < |MIN_VALUE|. - var halfThis = this.shiftRight(1); - var approx = halfThis.div(other).shiftLeft(1); - if (approx.equals(Long.ZERO)) { - return other.isNegative() ? Long.ONE : Long.NEG_ONE; - } else { - var rem = this.subtract(other.multiply(approx)); - var result = approx.add(rem.div(other)); - return result; - } - } - } else if (other.equals(Long.MIN_VALUE)) { - return Long.ZERO; - } - - if (this.isNegative()) { - if (other.isNegative()) { - return this.negate().div(other.negate()); - } else { - return this.negate().div(other).negate(); - } - } else if (other.isNegative()) { - return this.div(other.negate()).negate(); - } - - // Repeat the following until the remainder is less than other: find a - // floating-point that approximates remainder / other *from below*, add this - // into the result, and subtract it from the remainder. It is critical that - // the approximate value is less than or equal to the real value so that the - // remainder never becomes negative. - var res = Long.ZERO; - var rem = this; - while (rem.greaterThanOrEqual(other)) { - // Approximate the result of division. This may be a little greater or - // smaller than the actual value. - var approx = Math.max(1, Math.floor(rem.toNumber() / other.toNumber())); - - // We will tweak the approximate result by changing it in the 48-th digit or - // the smallest non-fractional digit, whichever is larger. - var log2 = Math.ceil(Math.log(approx) / Math.LN2); - var delta = log2 <= 48 ? 1 : Math.pow(2, log2 - 48); - - // Decrease the approximation until it is smaller than the remainder. Note - // that if it is too large, the product overflows and is negative. - var approxRes = Long.fromNumber(approx); - var approxRem = approxRes.multiply(other); - while (approxRem.isNegative() || approxRem.greaterThan(rem)) { - approx -= delta; - approxRes = Long.fromNumber(approx); - approxRem = approxRes.multiply(other); - } - - // We know the answer can't be zero... and actually, zero would cause - // infinite recursion since we would make no progress. - if (approxRes.isZero()) { - approxRes = Long.ONE; - } - - res = res.add(approxRes); - rem = rem.subtract(approxRem); - } - return res; - }; - - /** - * Returns this Long modulo the given one. - * - * @method - * @param {Long} other Long by which to mod. - * @return {Long} this Long modulo the given one. - */ - Long.prototype.modulo = function (other) { - return this.subtract(this.div(other).multiply(other)); - }; - - /** - * The bitwise-NOT of this value. - * - * @method - * @return {Long} the bitwise-NOT of this value. - */ - Long.prototype.not = function () { - return Long.fromBits(~this.low_, ~this.high_); - }; - - /** - * Returns the bitwise-AND of this Long and the given one. - * - * @method - * @param {Long} other the Long with which to AND. - * @return {Long} the bitwise-AND of this and the other. - */ - Long.prototype.and = function (other) { - return Long.fromBits(this.low_ & other.low_, this.high_ & other.high_); - }; - - /** - * Returns the bitwise-OR of this Long and the given one. - * - * @method - * @param {Long} other the Long with which to OR. - * @return {Long} the bitwise-OR of this and the other. - */ - Long.prototype.or = function (other) { - return Long.fromBits(this.low_ | other.low_, this.high_ | other.high_); - }; - - /** - * Returns the bitwise-XOR of this Long and the given one. - * - * @method - * @param {Long} other the Long with which to XOR. - * @return {Long} the bitwise-XOR of this and the other. - */ - Long.prototype.xor = function (other) { - return Long.fromBits(this.low_ ^ other.low_, this.high_ ^ other.high_); - }; - - /** - * Returns this Long with bits shifted to the left by the given amount. - * - * @method - * @param {number} numBits the number of bits by which to shift. - * @return {Long} this shifted to the left by the given amount. - */ - Long.prototype.shiftLeft = function (numBits) { - numBits &= 63; - if (numBits == 0) { - return this; - } else { - var low = this.low_; - if (numBits < 32) { - var high = this.high_; - return Long.fromBits(low << numBits, high << numBits | low >>> 32 - numBits); - } else { - return Long.fromBits(0, low << numBits - 32); - } - } - }; - - /** - * Returns this Long with bits shifted to the right by the given amount. - * - * @method - * @param {number} numBits the number of bits by which to shift. - * @return {Long} this shifted to the right by the given amount. - */ - Long.prototype.shiftRight = function (numBits) { - numBits &= 63; - if (numBits == 0) { - return this; - } else { - var high = this.high_; - if (numBits < 32) { - var low = this.low_; - return Long.fromBits(low >>> numBits | high << 32 - numBits, high >> numBits); - } else { - return Long.fromBits(high >> numBits - 32, high >= 0 ? 0 : -1); - } - } - }; - - /** - * Returns this Long with bits shifted to the right by the given amount, with the new top bits matching the current sign bit. - * - * @method - * @param {number} numBits the number of bits by which to shift. - * @return {Long} this shifted to the right by the given amount, with zeros placed into the new leading bits. - */ - Long.prototype.shiftRightUnsigned = function (numBits) { - numBits &= 63; - if (numBits == 0) { - return this; - } else { - var high = this.high_; - if (numBits < 32) { - var low = this.low_; - return Long.fromBits(low >>> numBits | high << 32 - numBits, high >>> numBits); - } else if (numBits == 32) { - return Long.fromBits(high, 0); - } else { - return Long.fromBits(high >>> numBits - 32, 0); - } - } - }; - - /** - * Returns a Long representing the given (32-bit) integer value. - * - * @method - * @param {number} value the 32-bit integer in question. - * @return {Long} the corresponding Long value. - */ - Long.fromInt = function (value) { - if (-128 <= value && value < 128) { - var cachedObj = Long.INT_CACHE_[value]; - if (cachedObj) { - return cachedObj; - } - } - - var obj = new Long(value | 0, value < 0 ? -1 : 0); - if (-128 <= value && value < 128) { - Long.INT_CACHE_[value] = obj; - } - return obj; - }; - - /** - * Returns a Long representing the given value, provided that it is a finite number. Otherwise, zero is returned. - * - * @method - * @param {number} value the number in question. - * @return {Long} the corresponding Long value. - */ - Long.fromNumber = function (value) { - if (isNaN(value) || !isFinite(value)) { - return Long.ZERO; - } else if (value <= -Long.TWO_PWR_63_DBL_) { - return Long.MIN_VALUE; - } else if (value + 1 >= Long.TWO_PWR_63_DBL_) { - return Long.MAX_VALUE; - } else if (value < 0) { - return Long.fromNumber(-value).negate(); - } else { - return new Long(value % Long.TWO_PWR_32_DBL_ | 0, value / Long.TWO_PWR_32_DBL_ | 0); - } - }; - - /** - * Returns a Long representing the 64-bit integer that comes by concatenating the given high and low bits. Each is assumed to use 32 bits. - * - * @method - * @param {number} lowBits the low 32-bits. - * @param {number} highBits the high 32-bits. - * @return {Long} the corresponding Long value. - */ - Long.fromBits = function (lowBits, highBits) { - return new Long(lowBits, highBits); - }; - - /** - * Returns a Long representation of the given string, written using the given radix. - * - * @method - * @param {string} str the textual representation of the Long. - * @param {number} opt_radix the radix in which the text is written. - * @return {Long} the corresponding Long value. - */ - Long.fromString = function (str, opt_radix) { - if (str.length == 0) { - throw Error('number format error: empty string'); - } - - var radix = opt_radix || 10; - if (radix < 2 || 36 < radix) { - throw Error('radix out of range: ' + radix); - } - - if (str.charAt(0) == '-') { - return Long.fromString(str.substring(1), radix).negate(); - } else if (str.indexOf('-') >= 0) { - throw Error('number format error: interior "-" character: ' + str); - } - - // Do several (8) digits each time through the loop, so as to - // minimize the calls to the very expensive emulated div. - var radixToPower = Long.fromNumber(Math.pow(radix, 8)); - - var result = Long.ZERO; - for (var i = 0; i < str.length; i += 8) { - var size = Math.min(8, str.length - i); - var value = parseInt(str.substring(i, i + size), radix); - if (size < 8) { - var power = Long.fromNumber(Math.pow(radix, size)); - result = result.multiply(power).add(Long.fromNumber(value)); - } else { - result = result.multiply(radixToPower); - result = result.add(Long.fromNumber(value)); - } - } - return result; - }; - - // NOTE: Common constant values ZERO, ONE, NEG_ONE, etc. are defined below the - // from* methods on which they depend. - - - /** - * A cache of the Long representations of small integer values. - * @type {Object} - * @ignore - */ - Long.INT_CACHE_ = {}; - - // NOTE: the compiler should inline these constant values below and then remove - // these variables, so there should be no runtime penalty for these. - - /** - * Number used repeated below in calculations. This must appear before the - * first call to any from* function below. - * @type {number} - * @ignore - */ - Long.TWO_PWR_16_DBL_ = 1 << 16; - - /** - * @type {number} - * @ignore - */ - Long.TWO_PWR_24_DBL_ = 1 << 24; - - /** - * @type {number} - * @ignore - */ - Long.TWO_PWR_32_DBL_ = Long.TWO_PWR_16_DBL_ * Long.TWO_PWR_16_DBL_; - - /** - * @type {number} - * @ignore - */ - Long.TWO_PWR_31_DBL_ = Long.TWO_PWR_32_DBL_ / 2; - - /** - * @type {number} - * @ignore - */ - Long.TWO_PWR_48_DBL_ = Long.TWO_PWR_32_DBL_ * Long.TWO_PWR_16_DBL_; - - /** - * @type {number} - * @ignore - */ - Long.TWO_PWR_64_DBL_ = Long.TWO_PWR_32_DBL_ * Long.TWO_PWR_32_DBL_; - - /** - * @type {number} - * @ignore - */ - Long.TWO_PWR_63_DBL_ = Long.TWO_PWR_64_DBL_ / 2; - - /** @type {Long} */ - Long.ZERO = Long.fromInt(0); - - /** @type {Long} */ - Long.ONE = Long.fromInt(1); - - /** @type {Long} */ - Long.NEG_ONE = Long.fromInt(-1); - - /** @type {Long} */ - Long.MAX_VALUE = Long.fromBits(0xFFFFFFFF | 0, 0x7FFFFFFF | 0); - - /** @type {Long} */ - Long.MIN_VALUE = Long.fromBits(0, 0x80000000 | 0); - - /** - * @type {Long} - * @ignore - */ - Long.TWO_PWR_24_ = Long.fromInt(1 << 24); - - /** - * Expose. - */ - module.exports = Long; - module.exports.Long = Long; - -/***/ }, -/* 307 */ -/***/ function(module, exports) { - - /** - * A class representation of the BSON Double type. - * - * @class - * @param {number} value the number we want to represent as a double. - * @return {Double} - */ - function Double(value) { - if (!(this instanceof Double)) return new Double(value); - - this._bsontype = 'Double'; - this.value = value; - } - - /** - * Access the number value. - * - * @method - * @return {number} returns the wrapped double number. - */ - Double.prototype.valueOf = function () { - return this.value; - }; - - /** - * @ignore - */ - Double.prototype.toJSON = function () { - return this.value; - }; - - module.exports = Double; - module.exports.Double = Double; - -/***/ }, -/* 308 */ -/***/ function(module, exports) { - - // Licensed under the Apache License, Version 2.0 (the "License"); - // you may not use this file except in compliance with the License. - // You may obtain a copy of the License at - // - // http://www.apache.org/licenses/LICENSE-2.0 - // - // Unless required by applicable law or agreed to in writing, software - // distributed under the License is distributed on an "AS IS" BASIS, - // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - // See the License for the specific language governing permissions and - // limitations under the License. - // - // Copyright 2009 Google Inc. All Rights Reserved - - /** - * This type is for INTERNAL use in MongoDB only and should not be used in applications. - * The appropriate corresponding type is the JavaScript Date type. - * - * Defines a Timestamp class for representing a 64-bit two's-complement - * integer value, which faithfully simulates the behavior of a Java "Timestamp". This - * implementation is derived from TimestampLib in GWT. - * - * Constructs a 64-bit two's-complement integer, given its low and high 32-bit - * values as *signed* integers. See the from* functions below for more - * convenient ways of constructing Timestamps. - * - * The internal representation of a Timestamp is the two given signed, 32-bit values. - * We use 32-bit pieces because these are the size of integers on which - * Javascript performs bit-operations. For operations like addition and - * multiplication, we split each number into 16-bit pieces, which can easily be - * multiplied within Javascript's floating-point representation without overflow - * or change in sign. - * - * In the algorithms below, we frequently reduce the negative case to the - * positive case by negating the input(s) and then post-processing the result. - * Note that we must ALWAYS check specially whether those values are MIN_VALUE - * (-2^63) because -MIN_VALUE == MIN_VALUE (since 2^63 cannot be represented as - * a positive number, it overflows back into a negative). Not handling this - * case would often result in infinite recursion. - * - * @class - * @param {number} low the low (signed) 32 bits of the Timestamp. - * @param {number} high the high (signed) 32 bits of the Timestamp. - */ - function Timestamp(low, high) { - if (!(this instanceof Timestamp)) return new Timestamp(low, high); - this._bsontype = 'Timestamp'; - /** - * @type {number} - * @ignore - */ - this.low_ = low | 0; // force into 32 signed bits. - - /** - * @type {number} - * @ignore - */ - this.high_ = high | 0; // force into 32 signed bits. - }; - - /** - * Return the int value. - * - * @return {number} the value, assuming it is a 32-bit integer. - */ - Timestamp.prototype.toInt = function () { - return this.low_; - }; - - /** - * Return the Number value. - * - * @method - * @return {number} the closest floating-point representation to this value. - */ - Timestamp.prototype.toNumber = function () { - return this.high_ * Timestamp.TWO_PWR_32_DBL_ + this.getLowBitsUnsigned(); - }; - - /** - * Return the JSON value. - * - * @method - * @return {string} the JSON representation. - */ - Timestamp.prototype.toJSON = function () { - return this.toString(); - }; - - /** - * Return the String value. - * - * @method - * @param {number} [opt_radix] the radix in which the text should be written. - * @return {string} the textual representation of this value. - */ - Timestamp.prototype.toString = function (opt_radix) { - var radix = opt_radix || 10; - if (radix < 2 || 36 < radix) { - throw Error('radix out of range: ' + radix); - } - - if (this.isZero()) { - return '0'; - } - - if (this.isNegative()) { - if (this.equals(Timestamp.MIN_VALUE)) { - // We need to change the Timestamp value before it can be negated, so we remove - // the bottom-most digit in this base and then recurse to do the rest. - var radixTimestamp = Timestamp.fromNumber(radix); - var div = this.div(radixTimestamp); - var rem = div.multiply(radixTimestamp).subtract(this); - return div.toString(radix) + rem.toInt().toString(radix); - } else { - return '-' + this.negate().toString(radix); - } - } - - // Do several (6) digits each time through the loop, so as to - // minimize the calls to the very expensive emulated div. - var radixToPower = Timestamp.fromNumber(Math.pow(radix, 6)); - - var rem = this; - var result = ''; - while (true) { - var remDiv = rem.div(radixToPower); - var intval = rem.subtract(remDiv.multiply(radixToPower)).toInt(); - var digits = intval.toString(radix); - - rem = remDiv; - if (rem.isZero()) { - return digits + result; - } else { - while (digits.length < 6) { - digits = '0' + digits; - } - result = '' + digits + result; - } - } - }; - - /** - * Return the high 32-bits value. - * - * @method - * @return {number} the high 32-bits as a signed value. - */ - Timestamp.prototype.getHighBits = function () { - return this.high_; - }; - - /** - * Return the low 32-bits value. - * - * @method - * @return {number} the low 32-bits as a signed value. - */ - Timestamp.prototype.getLowBits = function () { - return this.low_; - }; - - /** - * Return the low unsigned 32-bits value. - * - * @method - * @return {number} the low 32-bits as an unsigned value. - */ - Timestamp.prototype.getLowBitsUnsigned = function () { - return this.low_ >= 0 ? this.low_ : Timestamp.TWO_PWR_32_DBL_ + this.low_; - }; - - /** - * Returns the number of bits needed to represent the absolute value of this Timestamp. - * - * @method - * @return {number} Returns the number of bits needed to represent the absolute value of this Timestamp. - */ - Timestamp.prototype.getNumBitsAbs = function () { - if (this.isNegative()) { - if (this.equals(Timestamp.MIN_VALUE)) { - return 64; - } else { - return this.negate().getNumBitsAbs(); - } - } else { - var val = this.high_ != 0 ? this.high_ : this.low_; - for (var bit = 31; bit > 0; bit--) { - if ((val & 1 << bit) != 0) { - break; - } - } - return this.high_ != 0 ? bit + 33 : bit + 1; - } - }; - - /** - * Return whether this value is zero. - * - * @method - * @return {boolean} whether this value is zero. - */ - Timestamp.prototype.isZero = function () { - return this.high_ == 0 && this.low_ == 0; - }; - - /** - * Return whether this value is negative. - * - * @method - * @return {boolean} whether this value is negative. - */ - Timestamp.prototype.isNegative = function () { - return this.high_ < 0; - }; - - /** - * Return whether this value is odd. - * - * @method - * @return {boolean} whether this value is odd. - */ - Timestamp.prototype.isOdd = function () { - return (this.low_ & 1) == 1; - }; - - /** - * Return whether this Timestamp equals the other - * - * @method - * @param {Timestamp} other Timestamp to compare against. - * @return {boolean} whether this Timestamp equals the other - */ - Timestamp.prototype.equals = function (other) { - return this.high_ == other.high_ && this.low_ == other.low_; - }; - - /** - * Return whether this Timestamp does not equal the other. - * - * @method - * @param {Timestamp} other Timestamp to compare against. - * @return {boolean} whether this Timestamp does not equal the other. - */ - Timestamp.prototype.notEquals = function (other) { - return this.high_ != other.high_ || this.low_ != other.low_; - }; - - /** - * Return whether this Timestamp is less than the other. - * - * @method - * @param {Timestamp} other Timestamp to compare against. - * @return {boolean} whether this Timestamp is less than the other. - */ - Timestamp.prototype.lessThan = function (other) { - return this.compare(other) < 0; - }; - - /** - * Return whether this Timestamp is less than or equal to the other. - * - * @method - * @param {Timestamp} other Timestamp to compare against. - * @return {boolean} whether this Timestamp is less than or equal to the other. - */ - Timestamp.prototype.lessThanOrEqual = function (other) { - return this.compare(other) <= 0; - }; - - /** - * Return whether this Timestamp is greater than the other. - * - * @method - * @param {Timestamp} other Timestamp to compare against. - * @return {boolean} whether this Timestamp is greater than the other. - */ - Timestamp.prototype.greaterThan = function (other) { - return this.compare(other) > 0; - }; - - /** - * Return whether this Timestamp is greater than or equal to the other. - * - * @method - * @param {Timestamp} other Timestamp to compare against. - * @return {boolean} whether this Timestamp is greater than or equal to the other. - */ - Timestamp.prototype.greaterThanOrEqual = function (other) { - return this.compare(other) >= 0; - }; - - /** - * Compares this Timestamp with the given one. - * - * @method - * @param {Timestamp} other Timestamp to compare against. - * @return {boolean} 0 if they are the same, 1 if the this is greater, and -1 if the given one is greater. - */ - Timestamp.prototype.compare = function (other) { - if (this.equals(other)) { - return 0; - } - - var thisNeg = this.isNegative(); - var otherNeg = other.isNegative(); - if (thisNeg && !otherNeg) { - return -1; - } - if (!thisNeg && otherNeg) { - return 1; - } - - // at this point, the signs are the same, so subtraction will not overflow - if (this.subtract(other).isNegative()) { - return -1; - } else { - return 1; - } - }; - - /** - * The negation of this value. - * - * @method - * @return {Timestamp} the negation of this value. - */ - Timestamp.prototype.negate = function () { - if (this.equals(Timestamp.MIN_VALUE)) { - return Timestamp.MIN_VALUE; - } else { - return this.not().add(Timestamp.ONE); - } - }; - - /** - * Returns the sum of this and the given Timestamp. - * - * @method - * @param {Timestamp} other Timestamp to add to this one. - * @return {Timestamp} the sum of this and the given Timestamp. - */ - Timestamp.prototype.add = function (other) { - // Divide each number into 4 chunks of 16 bits, and then sum the chunks. - - var a48 = this.high_ >>> 16; - var a32 = this.high_ & 0xFFFF; - var a16 = this.low_ >>> 16; - var a00 = this.low_ & 0xFFFF; - - var b48 = other.high_ >>> 16; - var b32 = other.high_ & 0xFFFF; - var b16 = other.low_ >>> 16; - var b00 = other.low_ & 0xFFFF; - - var c48 = 0, - c32 = 0, - c16 = 0, - c00 = 0; - c00 += a00 + b00; - c16 += c00 >>> 16; - c00 &= 0xFFFF; - c16 += a16 + b16; - c32 += c16 >>> 16; - c16 &= 0xFFFF; - c32 += a32 + b32; - c48 += c32 >>> 16; - c32 &= 0xFFFF; - c48 += a48 + b48; - c48 &= 0xFFFF; - return Timestamp.fromBits(c16 << 16 | c00, c48 << 16 | c32); - }; - - /** - * Returns the difference of this and the given Timestamp. - * - * @method - * @param {Timestamp} other Timestamp to subtract from this. - * @return {Timestamp} the difference of this and the given Timestamp. - */ - Timestamp.prototype.subtract = function (other) { - return this.add(other.negate()); - }; - - /** - * Returns the product of this and the given Timestamp. - * - * @method - * @param {Timestamp} other Timestamp to multiply with this. - * @return {Timestamp} the product of this and the other. - */ - Timestamp.prototype.multiply = function (other) { - if (this.isZero()) { - return Timestamp.ZERO; - } else if (other.isZero()) { - return Timestamp.ZERO; - } - - if (this.equals(Timestamp.MIN_VALUE)) { - return other.isOdd() ? Timestamp.MIN_VALUE : Timestamp.ZERO; - } else if (other.equals(Timestamp.MIN_VALUE)) { - return this.isOdd() ? Timestamp.MIN_VALUE : Timestamp.ZERO; - } - - if (this.isNegative()) { - if (other.isNegative()) { - return this.negate().multiply(other.negate()); - } else { - return this.negate().multiply(other).negate(); - } - } else if (other.isNegative()) { - return this.multiply(other.negate()).negate(); - } - - // If both Timestamps are small, use float multiplication - if (this.lessThan(Timestamp.TWO_PWR_24_) && other.lessThan(Timestamp.TWO_PWR_24_)) { - return Timestamp.fromNumber(this.toNumber() * other.toNumber()); - } - - // Divide each Timestamp into 4 chunks of 16 bits, and then add up 4x4 products. - // We can skip products that would overflow. - - var a48 = this.high_ >>> 16; - var a32 = this.high_ & 0xFFFF; - var a16 = this.low_ >>> 16; - var a00 = this.low_ & 0xFFFF; - - var b48 = other.high_ >>> 16; - var b32 = other.high_ & 0xFFFF; - var b16 = other.low_ >>> 16; - var b00 = other.low_ & 0xFFFF; - - var c48 = 0, - c32 = 0, - c16 = 0, - c00 = 0; - c00 += a00 * b00; - c16 += c00 >>> 16; - c00 &= 0xFFFF; - c16 += a16 * b00; - c32 += c16 >>> 16; - c16 &= 0xFFFF; - c16 += a00 * b16; - c32 += c16 >>> 16; - c16 &= 0xFFFF; - c32 += a32 * b00; - c48 += c32 >>> 16; - c32 &= 0xFFFF; - c32 += a16 * b16; - c48 += c32 >>> 16; - c32 &= 0xFFFF; - c32 += a00 * b32; - c48 += c32 >>> 16; - c32 &= 0xFFFF; - c48 += a48 * b00 + a32 * b16 + a16 * b32 + a00 * b48; - c48 &= 0xFFFF; - return Timestamp.fromBits(c16 << 16 | c00, c48 << 16 | c32); - }; - - /** - * Returns this Timestamp divided by the given one. - * - * @method - * @param {Timestamp} other Timestamp by which to divide. - * @return {Timestamp} this Timestamp divided by the given one. - */ - Timestamp.prototype.div = function (other) { - if (other.isZero()) { - throw Error('division by zero'); - } else if (this.isZero()) { - return Timestamp.ZERO; - } - - if (this.equals(Timestamp.MIN_VALUE)) { - if (other.equals(Timestamp.ONE) || other.equals(Timestamp.NEG_ONE)) { - return Timestamp.MIN_VALUE; // recall that -MIN_VALUE == MIN_VALUE - } else if (other.equals(Timestamp.MIN_VALUE)) { - return Timestamp.ONE; - } else { - // At this point, we have |other| >= 2, so |this/other| < |MIN_VALUE|. - var halfThis = this.shiftRight(1); - var approx = halfThis.div(other).shiftLeft(1); - if (approx.equals(Timestamp.ZERO)) { - return other.isNegative() ? Timestamp.ONE : Timestamp.NEG_ONE; - } else { - var rem = this.subtract(other.multiply(approx)); - var result = approx.add(rem.div(other)); - return result; - } - } - } else if (other.equals(Timestamp.MIN_VALUE)) { - return Timestamp.ZERO; - } - - if (this.isNegative()) { - if (other.isNegative()) { - return this.negate().div(other.negate()); - } else { - return this.negate().div(other).negate(); - } - } else if (other.isNegative()) { - return this.div(other.negate()).negate(); - } - - // Repeat the following until the remainder is less than other: find a - // floating-point that approximates remainder / other *from below*, add this - // into the result, and subtract it from the remainder. It is critical that - // the approximate value is less than or equal to the real value so that the - // remainder never becomes negative. - var res = Timestamp.ZERO; - var rem = this; - while (rem.greaterThanOrEqual(other)) { - // Approximate the result of division. This may be a little greater or - // smaller than the actual value. - var approx = Math.max(1, Math.floor(rem.toNumber() / other.toNumber())); - - // We will tweak the approximate result by changing it in the 48-th digit or - // the smallest non-fractional digit, whichever is larger. - var log2 = Math.ceil(Math.log(approx) / Math.LN2); - var delta = log2 <= 48 ? 1 : Math.pow(2, log2 - 48); - - // Decrease the approximation until it is smaller than the remainder. Note - // that if it is too large, the product overflows and is negative. - var approxRes = Timestamp.fromNumber(approx); - var approxRem = approxRes.multiply(other); - while (approxRem.isNegative() || approxRem.greaterThan(rem)) { - approx -= delta; - approxRes = Timestamp.fromNumber(approx); - approxRem = approxRes.multiply(other); - } - - // We know the answer can't be zero... and actually, zero would cause - // infinite recursion since we would make no progress. - if (approxRes.isZero()) { - approxRes = Timestamp.ONE; - } - - res = res.add(approxRes); - rem = rem.subtract(approxRem); - } - return res; - }; - - /** - * Returns this Timestamp modulo the given one. - * - * @method - * @param {Timestamp} other Timestamp by which to mod. - * @return {Timestamp} this Timestamp modulo the given one. - */ - Timestamp.prototype.modulo = function (other) { - return this.subtract(this.div(other).multiply(other)); - }; - - /** - * The bitwise-NOT of this value. - * - * @method - * @return {Timestamp} the bitwise-NOT of this value. - */ - Timestamp.prototype.not = function () { - return Timestamp.fromBits(~this.low_, ~this.high_); - }; - - /** - * Returns the bitwise-AND of this Timestamp and the given one. - * - * @method - * @param {Timestamp} other the Timestamp with which to AND. - * @return {Timestamp} the bitwise-AND of this and the other. - */ - Timestamp.prototype.and = function (other) { - return Timestamp.fromBits(this.low_ & other.low_, this.high_ & other.high_); - }; - - /** - * Returns the bitwise-OR of this Timestamp and the given one. - * - * @method - * @param {Timestamp} other the Timestamp with which to OR. - * @return {Timestamp} the bitwise-OR of this and the other. - */ - Timestamp.prototype.or = function (other) { - return Timestamp.fromBits(this.low_ | other.low_, this.high_ | other.high_); - }; - - /** - * Returns the bitwise-XOR of this Timestamp and the given one. - * - * @method - * @param {Timestamp} other the Timestamp with which to XOR. - * @return {Timestamp} the bitwise-XOR of this and the other. - */ - Timestamp.prototype.xor = function (other) { - return Timestamp.fromBits(this.low_ ^ other.low_, this.high_ ^ other.high_); - }; - - /** - * Returns this Timestamp with bits shifted to the left by the given amount. - * - * @method - * @param {number} numBits the number of bits by which to shift. - * @return {Timestamp} this shifted to the left by the given amount. - */ - Timestamp.prototype.shiftLeft = function (numBits) { - numBits &= 63; - if (numBits == 0) { - return this; - } else { - var low = this.low_; - if (numBits < 32) { - var high = this.high_; - return Timestamp.fromBits(low << numBits, high << numBits | low >>> 32 - numBits); - } else { - return Timestamp.fromBits(0, low << numBits - 32); - } - } - }; - - /** - * Returns this Timestamp with bits shifted to the right by the given amount. - * - * @method - * @param {number} numBits the number of bits by which to shift. - * @return {Timestamp} this shifted to the right by the given amount. - */ - Timestamp.prototype.shiftRight = function (numBits) { - numBits &= 63; - if (numBits == 0) { - return this; - } else { - var high = this.high_; - if (numBits < 32) { - var low = this.low_; - return Timestamp.fromBits(low >>> numBits | high << 32 - numBits, high >> numBits); - } else { - return Timestamp.fromBits(high >> numBits - 32, high >= 0 ? 0 : -1); - } - } - }; - - /** - * Returns this Timestamp with bits shifted to the right by the given amount, with the new top bits matching the current sign bit. - * - * @method - * @param {number} numBits the number of bits by which to shift. - * @return {Timestamp} this shifted to the right by the given amount, with zeros placed into the new leading bits. - */ - Timestamp.prototype.shiftRightUnsigned = function (numBits) { - numBits &= 63; - if (numBits == 0) { - return this; - } else { - var high = this.high_; - if (numBits < 32) { - var low = this.low_; - return Timestamp.fromBits(low >>> numBits | high << 32 - numBits, high >>> numBits); - } else if (numBits == 32) { - return Timestamp.fromBits(high, 0); - } else { - return Timestamp.fromBits(high >>> numBits - 32, 0); - } - } - }; - - /** - * Returns a Timestamp representing the given (32-bit) integer value. - * - * @method - * @param {number} value the 32-bit integer in question. - * @return {Timestamp} the corresponding Timestamp value. - */ - Timestamp.fromInt = function (value) { - if (-128 <= value && value < 128) { - var cachedObj = Timestamp.INT_CACHE_[value]; - if (cachedObj) { - return cachedObj; - } - } - - var obj = new Timestamp(value | 0, value < 0 ? -1 : 0); - if (-128 <= value && value < 128) { - Timestamp.INT_CACHE_[value] = obj; - } - return obj; - }; - - /** - * Returns a Timestamp representing the given value, provided that it is a finite number. Otherwise, zero is returned. - * - * @method - * @param {number} value the number in question. - * @return {Timestamp} the corresponding Timestamp value. - */ - Timestamp.fromNumber = function (value) { - if (isNaN(value) || !isFinite(value)) { - return Timestamp.ZERO; - } else if (value <= -Timestamp.TWO_PWR_63_DBL_) { - return Timestamp.MIN_VALUE; - } else if (value + 1 >= Timestamp.TWO_PWR_63_DBL_) { - return Timestamp.MAX_VALUE; - } else if (value < 0) { - return Timestamp.fromNumber(-value).negate(); - } else { - return new Timestamp(value % Timestamp.TWO_PWR_32_DBL_ | 0, value / Timestamp.TWO_PWR_32_DBL_ | 0); - } - }; - - /** - * Returns a Timestamp representing the 64-bit integer that comes by concatenating the given high and low bits. Each is assumed to use 32 bits. - * - * @method - * @param {number} lowBits the low 32-bits. - * @param {number} highBits the high 32-bits. - * @return {Timestamp} the corresponding Timestamp value. - */ - Timestamp.fromBits = function (lowBits, highBits) { - return new Timestamp(lowBits, highBits); - }; - - /** - * Returns a Timestamp representation of the given string, written using the given radix. - * - * @method - * @param {string} str the textual representation of the Timestamp. - * @param {number} opt_radix the radix in which the text is written. - * @return {Timestamp} the corresponding Timestamp value. - */ - Timestamp.fromString = function (str, opt_radix) { - if (str.length == 0) { - throw Error('number format error: empty string'); - } - - var radix = opt_radix || 10; - if (radix < 2 || 36 < radix) { - throw Error('radix out of range: ' + radix); - } - - if (str.charAt(0) == '-') { - return Timestamp.fromString(str.substring(1), radix).negate(); - } else if (str.indexOf('-') >= 0) { - throw Error('number format error: interior "-" character: ' + str); - } - - // Do several (8) digits each time through the loop, so as to - // minimize the calls to the very expensive emulated div. - var radixToPower = Timestamp.fromNumber(Math.pow(radix, 8)); - - var result = Timestamp.ZERO; - for (var i = 0; i < str.length; i += 8) { - var size = Math.min(8, str.length - i); - var value = parseInt(str.substring(i, i + size), radix); - if (size < 8) { - var power = Timestamp.fromNumber(Math.pow(radix, size)); - result = result.multiply(power).add(Timestamp.fromNumber(value)); - } else { - result = result.multiply(radixToPower); - result = result.add(Timestamp.fromNumber(value)); - } - } - return result; - }; - - // NOTE: Common constant values ZERO, ONE, NEG_ONE, etc. are defined below the - // from* methods on which they depend. - - - /** - * A cache of the Timestamp representations of small integer values. - * @type {Object} - * @ignore - */ - Timestamp.INT_CACHE_ = {}; - - // NOTE: the compiler should inline these constant values below and then remove - // these variables, so there should be no runtime penalty for these. - - /** - * Number used repeated below in calculations. This must appear before the - * first call to any from* function below. - * @type {number} - * @ignore - */ - Timestamp.TWO_PWR_16_DBL_ = 1 << 16; - - /** - * @type {number} - * @ignore - */ - Timestamp.TWO_PWR_24_DBL_ = 1 << 24; - - /** - * @type {number} - * @ignore - */ - Timestamp.TWO_PWR_32_DBL_ = Timestamp.TWO_PWR_16_DBL_ * Timestamp.TWO_PWR_16_DBL_; - - /** - * @type {number} - * @ignore - */ - Timestamp.TWO_PWR_31_DBL_ = Timestamp.TWO_PWR_32_DBL_ / 2; - - /** - * @type {number} - * @ignore - */ - Timestamp.TWO_PWR_48_DBL_ = Timestamp.TWO_PWR_32_DBL_ * Timestamp.TWO_PWR_16_DBL_; - - /** - * @type {number} - * @ignore - */ - Timestamp.TWO_PWR_64_DBL_ = Timestamp.TWO_PWR_32_DBL_ * Timestamp.TWO_PWR_32_DBL_; - - /** - * @type {number} - * @ignore - */ - Timestamp.TWO_PWR_63_DBL_ = Timestamp.TWO_PWR_64_DBL_ / 2; - - /** @type {Timestamp} */ - Timestamp.ZERO = Timestamp.fromInt(0); - - /** @type {Timestamp} */ - Timestamp.ONE = Timestamp.fromInt(1); - - /** @type {Timestamp} */ - Timestamp.NEG_ONE = Timestamp.fromInt(-1); - - /** @type {Timestamp} */ - Timestamp.MAX_VALUE = Timestamp.fromBits(0xFFFFFFFF | 0, 0x7FFFFFFF | 0); - - /** @type {Timestamp} */ - Timestamp.MIN_VALUE = Timestamp.fromBits(0, 0x80000000 | 0); - - /** - * @type {Timestamp} - * @ignore - */ - Timestamp.TWO_PWR_24_ = Timestamp.fromInt(1 << 24); - - /** - * Expose. - */ - module.exports = Timestamp; - module.exports.Timestamp = Timestamp; - -/***/ }, -/* 309 */ -/***/ function(module, exports, __webpack_require__) { - - /* WEBPACK VAR INJECTION */(function(process, Buffer) {/** - * Machine id. - * - * Create a random 3-byte value (i.e. unique for this - * process). Other drivers use a md5 of the machine id here, but - * that would mean an asyc call to gethostname, so we don't bother. - * @ignore - */ - var MACHINE_ID = parseInt(Math.random() * 0xFFFFFF, 10); - - // Regular expression that checks for hex value - var checkForHexRegExp = new RegExp("^[0-9a-fA-F]{24}$"); - - /** - * Create a new ObjectID instance - * - * @class - * @param {(string|number)} id Can be a 24 byte hex string, 12 byte binary string or a Number. - * @property {number} generationTime The generation time of this ObjectId instance - * @return {ObjectID} instance of ObjectID. - */ - var ObjectID = function ObjectID(id) { - // Duck-typing to support ObjectId from different npm packages - if (id instanceof ObjectID) return id; - if (!(this instanceof ObjectID)) return new ObjectID(id); - - this._bsontype = 'ObjectID'; - - var __id = null; - var valid = ObjectID.isValid(id); - - // Throw an error if it's not a valid setup - if (!valid && id != null) { - throw new Error("Argument passed in must be a single String of 12 bytes or a string of 24 hex characters"); - } else if (valid && typeof id == 'string' && id.length == 24) { - return ObjectID.createFromHexString(id); - } else if (id == null || typeof id == 'number') { - // convert to 12 byte binary string - this.id = this.generate(id); - } else if (id != null && id.length === 12) { - // assume 12 byte string - this.id = id; - } else if (id != null && id.toHexString) { - // Duck-typing to support ObjectId from different npm packages - return id; - } else { - throw new Error("Argument passed in must be a single String of 12 bytes or a string of 24 hex characters"); - } - - if (ObjectID.cacheHexString) this.__id = this.toHexString(); - }; - - // Allow usage of ObjectId as well as ObjectID - var ObjectId = ObjectID; - - // Precomputed hex table enables speedy hex string conversion - var hexTable = []; - for (var i = 0; i < 256; i++) { - hexTable[i] = (i <= 15 ? '0' : '') + i.toString(16); - } - - /** - * Return the ObjectID id as a 24 byte hex string representation - * - * @method - * @return {string} return the 24 byte hex string representation. - */ - ObjectID.prototype.toHexString = function () { - if (ObjectID.cacheHexString && this.__id) return this.__id; - - var hexString = ''; - if (!this.id || !this.id.length) { - throw new Error('invalid ObjectId, ObjectId.id must be either a string or a Buffer, but is [' + JSON.stringify(this.id) + ']'); - } - - if (this.id instanceof _Buffer) { - hexString = convertToHex(this.id); - if (ObjectID.cacheHexString) this.__id = hexString; - return hexString; - } - - for (var i = 0; i < this.id.length; i++) { - hexString += hexTable[this.id.charCodeAt(i)]; - } - - if (ObjectID.cacheHexString) this.__id = hexString; - return hexString; - }; - - /** - * Update the ObjectID index used in generating new ObjectID's on the driver - * - * @method - * @return {number} returns next index value. - * @ignore - */ - ObjectID.prototype.get_inc = function () { - return ObjectID.index = (ObjectID.index + 1) % 0xFFFFFF; - }; - - /** - * Update the ObjectID index used in generating new ObjectID's on the driver - * - * @method - * @return {number} returns next index value. - * @ignore - */ - ObjectID.prototype.getInc = function () { - return this.get_inc(); - }; - - /** - * Generate a 12 byte id buffer used in ObjectID's - * - * @method - * @param {number} [time] optional parameter allowing to pass in a second based timestamp. - * @return {Buffer} return the 12 byte id buffer string. - */ - ObjectID.prototype.generate = function (time) { - if ('number' != typeof time) { - time = ~~(Date.now() / 1000); - } - - // Use pid - var pid = (typeof process === 'undefined' ? Math.floor(Math.random() * 100000) : process.pid) % 0xFFFF; - var inc = this.get_inc(); - // Buffer used - var buffer = new Buffer(12); - // Encode time - buffer[3] = time & 0xff; - buffer[2] = time >> 8 & 0xff; - buffer[1] = time >> 16 & 0xff; - buffer[0] = time >> 24 & 0xff; - // Encode machine - buffer[6] = MACHINE_ID & 0xff; - buffer[5] = MACHINE_ID >> 8 & 0xff; - buffer[4] = MACHINE_ID >> 16 & 0xff; - // Encode pid - buffer[8] = pid & 0xff; - buffer[7] = pid >> 8 & 0xff; - // Encode index - buffer[11] = inc & 0xff; - buffer[10] = inc >> 8 & 0xff; - buffer[9] = inc >> 16 & 0xff; - // Return the buffer - return buffer; - }; - - /** - * Converts the id into a 24 byte hex string for printing - * - * @return {String} return the 24 byte hex string representation. - * @ignore - */ - ObjectID.prototype.toString = function () { - return this.toHexString(); - }; - - /** - * Converts to a string representation of this Id. - * - * @return {String} return the 24 byte hex string representation. - * @ignore - */ - ObjectID.prototype.inspect = ObjectID.prototype.toString; - - /** - * Converts to its JSON representation. - * - * @return {String} return the 24 byte hex string representation. - * @ignore - */ - ObjectID.prototype.toJSON = function () { - return this.toHexString(); - }; - - /** - * Compares the equality of this ObjectID with `otherID`. - * - * @method - * @param {object} otherID ObjectID instance to compare against. - * @return {boolean} the result of comparing two ObjectID's - */ - ObjectID.prototype.equals = function equals(otherId) { - var id; - - if (otherId instanceof ObjectID) { - return this.toString() == otherId.toString(); - } else if (typeof otherId == 'string' && ObjectID.isValid(otherId) && otherId.length == 12 && this.id instanceof _Buffer) { - return otherId === this.id.toString('binary'); - } else if (typeof otherId == 'string' && ObjectID.isValid(otherId) && otherId.length == 24) { - return otherId.toLowerCase() === this.toHexString(); - } else if (typeof otherId == 'string' && ObjectID.isValid(otherId) && otherId.length == 12) { - return otherId === this.id; - } else if (otherId != null && (otherId instanceof ObjectID || otherId.toHexString)) { - return otherId.toHexString() === this.toHexString(); - } else { - return false; - } - }; - - /** - * Returns the generation date (accurate up to the second) that this ID was generated. - * - * @method - * @return {date} the generation date - */ - ObjectID.prototype.getTimestamp = function () { - var timestamp = new Date(); - var time = this.id[3] | this.id[2] << 8 | this.id[1] << 16 | this.id[0] << 24; - timestamp.setTime(Math.floor(time) * 1000); - return timestamp; - }; - - /** - * @ignore - */ - ObjectID.index = ~~(Math.random() * 0xFFFFFF); - - /** - * @ignore - */ - ObjectID.createPk = function createPk() { - return new ObjectID(); - }; - - /** - * Creates an ObjectID from a second based number, with the rest of the ObjectID zeroed out. Used for comparisons or sorting the ObjectID. - * - * @method - * @param {number} time an integer number representing a number of seconds. - * @return {ObjectID} return the created ObjectID - */ - ObjectID.createFromTime = function createFromTime(time) { - var buffer = new Buffer([0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]); - // Encode time into first 4 bytes - buffer[3] = time & 0xff; - buffer[2] = time >> 8 & 0xff; - buffer[1] = time >> 16 & 0xff; - buffer[0] = time >> 24 & 0xff; - // Return the new objectId - return new ObjectID(buffer); - }; - - // Lookup tables - var encodeLookup = '0123456789abcdef'.split(''); - var decodeLookup = []; - var i = 0; - while (i < 10) decodeLookup[0x30 + i] = i++; - while (i < 16) decodeLookup[0x41 - 10 + i] = decodeLookup[0x61 - 10 + i] = i++; - - var _Buffer = Buffer; - var convertToHex = function (bytes) { - return bytes.toString('hex'); - }; - - /** - * Creates an ObjectID from a hex string representation of an ObjectID. - * - * @method - * @param {string} hexString create a ObjectID from a passed in 24 byte hexstring. - * @return {ObjectID} return the created ObjectID - */ - ObjectID.createFromHexString = function createFromHexString(string) { - // Throw an error if it's not a valid setup - if (typeof string === 'undefined' || string != null && string.length != 24) throw new Error("Argument passed in must be a single String of 12 bytes or a string of 24 hex characters"); - - var length = string.length; - - if (length > 12 * 2) { - throw new Error('Id cannot be longer than 12 bytes'); - } - - // Calculate lengths - var sizeof = length >> 1; - var array = new _Buffer(sizeof); - var n = 0; - var i = 0; - - while (i < length) { - array[n++] = decodeLookup[string.charCodeAt(i++)] << 4 | decodeLookup[string.charCodeAt(i++)]; - } - - return new ObjectID(array); - }; - - /** - * Checks if a value is a valid bson ObjectId - * - * @method - * @return {boolean} return true if the value is a valid bson ObjectId, return false otherwise. - */ - ObjectID.isValid = function isValid(id) { - if (id == null) return false; - - if (typeof id == 'number') { - return true; - } - - if (typeof id == 'string') { - return id.length == 12 || id.length == 24 && checkForHexRegExp.test(id); - } - - if (id instanceof ObjectID) { - return true; - } - - if (id instanceof _Buffer) { - return true; - } - - // Duck-Typing detection of ObjectId like objects - if (id.toHexString) { - return id.id.length == 12 || id.id.length == 24 && checkForHexRegExp.test(id.id); - } - - return false; - }; - - /** - * @ignore - */ - Object.defineProperty(ObjectID.prototype, "generationTime", { - enumerable: true, - get: function () { - return this.id[3] | this.id[2] << 8 | this.id[1] << 16 | this.id[0] << 24; - }, - set: function (value) { - // Encode time into first 4 bytes - this.id[3] = value & 0xff; - this.id[2] = value >> 8 & 0xff; - this.id[1] = value >> 16 & 0xff; - this.id[0] = value >> 24 & 0xff; - } - }); - - /** - * Expose. - */ - module.exports = ObjectID; - module.exports.ObjectID = ObjectID; - module.exports.ObjectId = ObjectID; - /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(294), __webpack_require__(300).Buffer)) - -/***/ }, -/* 310 */ -/***/ function(module, exports) { - - /** - * A class representation of the BSON RegExp type. - * - * @class - * @return {BSONRegExp} A MinKey instance - */ - function BSONRegExp(pattern, options) { - if (!(this instanceof BSONRegExp)) return new BSONRegExp(); - - // Execute - this._bsontype = 'BSONRegExp'; - this.pattern = pattern || ''; - this.options = options || ''; - - // Validate options - for (var i = 0; i < this.options.length; i++) { - if (!(this.options[i] == 'i' || this.options[i] == 'm' || this.options[i] == 'x' || this.options[i] == 'l' || this.options[i] == 's' || this.options[i] == 'u')) { - throw new Error('the regular expression options [' + this.options[i] + "] is not supported"); - } - } - } - - module.exports = BSONRegExp; - module.exports.BSONRegExp = BSONRegExp; - -/***/ }, -/* 311 */ -/***/ function(module, exports) { - - /** - * A class representation of the BSON Symbol type. - * - * @class - * @deprecated - * @param {string} value the string representing the symbol. - * @return {Symbol} - */ - function Symbol(value) { - if (!(this instanceof Symbol)) return new Symbol(value); - this._bsontype = 'Symbol'; - this.value = value; - } - - /** - * Access the wrapped string value. - * - * @method - * @return {String} returns the wrapped string. - */ - Symbol.prototype.valueOf = function () { - return this.value; - }; - - /** - * @ignore - */ - Symbol.prototype.toString = function () { - return this.value; - }; - - /** - * @ignore - */ - Symbol.prototype.inspect = function () { - return this.value; - }; - - /** - * @ignore - */ - Symbol.prototype.toJSON = function () { - return this.value; - }; - - module.exports = Symbol; - module.exports.Symbol = Symbol; - -/***/ }, -/* 312 */ -/***/ function(module, exports) { - - var Int32 = function (value) { - if (!(this instanceof Int32)) return new Int32(value); - - this._bsontype = 'Int32'; - this.value = value; - }; - - /** - * Access the number value. - * - * @method - * @return {number} returns the wrapped int32 number. - */ - Int32.prototype.valueOf = function () { - return this.value; - }; - - /** - * @ignore - */ - Int32.prototype.toJSON = function () { - return this.value; - }; - - module.exports = Int32; - module.exports.Int32 = Int32; - -/***/ }, -/* 313 */ -/***/ function(module, exports) { - - /** - * A class representation of the BSON Code type. - * - * @class - * @param {(string|function)} code a string or function. - * @param {Object} [scope] an optional scope for the function. - * @return {Code} - */ - var Code = function Code(code, scope) { - if (!(this instanceof Code)) return new Code(code, scope); - this._bsontype = 'Code'; - this.code = code; - this.scope = scope; - }; - - /** - * @ignore - */ - Code.prototype.toJSON = function () { - return { scope: this.scope, code: this.code }; - }; - - module.exports = Code; - module.exports.Code = Code; - -/***/ }, -/* 314 */ -/***/ function(module, exports, __webpack_require__) { - - /* WEBPACK VAR INJECTION */(function(Buffer) {"use strict"; - - var Long = __webpack_require__(306); - - var PARSE_STRING_REGEXP = /^(\+|\-)?(\d+|(\d*\.\d*))?(E|e)?([\-\+])?(\d+)?$/; - var PARSE_INF_REGEXP = /^(\+|\-)?(Infinity|inf)$/i; - var PARSE_NAN_REGEXP = /^(\+|\-)?NaN$/i; - - var EXPONENT_MAX = 6111; - var EXPONENT_MIN = -6176; - var EXPONENT_BIAS = 6176; - var MAX_DIGITS = 34; - - // Nan value bits as 32 bit values (due to lack of longs) - var NAN_BUFFER = [0x7c, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00].reverse(); - // Infinity value bits 32 bit values (due to lack of longs) - var INF_NEGATIVE_BUFFER = [0xf8, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00].reverse(); - var INF_POSITIVE_BUFFER = [0x78, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00].reverse(); - - var EXPONENT_REGEX = /^([\-\+])?(\d+)?$/; - - // Detect if the value is a digit - var isDigit = function (value) { - return !isNaN(parseInt(value, 10)); - }; - - // Divide two uint128 values - var divideu128 = function (value) { - var DIVISOR = Long.fromNumber(1000 * 1000 * 1000); - var _rem = Long.fromNumber(0); - var i = 0; - - if (!value.parts[0] && !value.parts[1] && !value.parts[2] && !value.parts[3]) { - return { quotient: value, rem: _rem }; - } - - for (var i = 0; i <= 3; i++) { - // Adjust remainder to match value of next dividend - _rem = _rem.shiftLeft(32); - // Add the divided to _rem - _rem = _rem.add(new Long(value.parts[i], 0)); - value.parts[i] = _rem.div(DIVISOR).low_; - _rem = _rem.modulo(DIVISOR); - } - - return { quotient: value, rem: _rem }; - }; - - // Multiply two Long values and return the 128 bit value - var multiply64x2 = function (left, right) { - if (!left && !right) { - return { high: Long.fromNumber(0), low: Long.fromNumber(0) }; - } - - var leftHigh = left.shiftRightUnsigned(32); - var leftLow = new Long(left.getLowBits(), 0); - var rightHigh = right.shiftRightUnsigned(32); - var rightLow = new Long(right.getLowBits(), 0); - - var productHigh = leftHigh.multiply(rightHigh); - var productMid = leftHigh.multiply(rightLow); - var productMid2 = leftLow.multiply(rightHigh); - var productLow = leftLow.multiply(rightLow); - - productHigh = productHigh.add(productMid.shiftRightUnsigned(32)); - productMid = new Long(productMid.getLowBits(), 0).add(productMid2).add(productLow.shiftRightUnsigned(32)); - - productHigh = productHigh.add(productMid.shiftRightUnsigned(32)); - productLow = productMid.shiftLeft(32).add(new Long(productLow.getLowBits(), 0)); - - // Return the 128 bit result - return { high: productHigh, low: productLow }; - }; - - var lessThan = function (left, right) { - // Make values unsigned - var uhleft = left.high_ >>> 0; - var uhright = right.high_ >>> 0; - - // Compare high bits first - if (uhleft < uhright) { - return true; - } else if (uhleft == uhright) { - var ulleft = left.low_ >>> 0; - var ulright = right.low_ >>> 0; - if (ulleft < ulright) return true; - } - - return false; - }; - - var longtoHex = function (value) { - var buffer = new Buffer(8); - var index = 0; - // Encode the low 64 bits of the decimal - // Encode low bits - buffer[index++] = value.low_ & 0xff; - buffer[index++] = value.low_ >> 8 & 0xff; - buffer[index++] = value.low_ >> 16 & 0xff; - buffer[index++] = value.low_ >> 24 & 0xff; - // Encode high bits - buffer[index++] = value.high_ & 0xff; - buffer[index++] = value.high_ >> 8 & 0xff; - buffer[index++] = value.high_ >> 16 & 0xff; - buffer[index++] = value.high_ >> 24 & 0xff; - return buffer.reverse().toString('hex'); - }; - - var int32toHex = function (value) { - var buffer = new Buffer(4); - var index = 0; - // Encode the low 64 bits of the decimal - // Encode low bits - buffer[index++] = value & 0xff; - buffer[index++] = value >> 8 & 0xff; - buffer[index++] = value >> 16 & 0xff; - buffer[index++] = value >> 24 & 0xff; - return buffer.reverse().toString('hex'); - }; - - var Decimal128 = function (bytes) { - this._bsontype = 'Decimal128'; - this.bytes = bytes; - }; - - Decimal128.fromString = function (string) { - // Parse state tracking - var isNegative = false; - var sawRadix = false; - var foundNonZero = false; - - // Total number of significant digits (no leading or trailing zero) - var significantDigits = 0; - // Total number of significand digits read - var nDigitsRead = 0; - // Total number of digits (no leading zeros) - var nDigits = 0; - // The number of the digits after radix - var radixPosition = 0; - // The index of the first non-zero in *str* - var firstNonZero = 0; - - // Digits Array - var digits = [0]; - // The number of digits in digits - var nDigitsStored = 0; - // Insertion pointer for digits - var digitsInsert = 0; - // The index of the first non-zero digit - var firstDigit = 0; - // The index of the last digit - var lastDigit = 0; - - // Exponent - var exponent = 0; - // loop index over array - var i = 0; - // The high 17 digits of the significand - var significandHigh = [0, 0]; - // The low 17 digits of the significand - var significandLow = [0, 0]; - // The biased exponent - var biasedExponent = 0; - - // Read index - var index = 0; - - // Trim the string - string = string.trim(); - - // Results - var stringMatch = string.match(PARSE_STRING_REGEXP); - var infMatch = string.match(PARSE_INF_REGEXP); - var nanMatch = string.match(PARSE_NAN_REGEXP); - - // Validate the string - if (!stringMatch && !infMatch && !nanMatch || string.length == 0) { - throw new Error("" + string + " not a valid Decimal128 string"); - } - - // Check if we have an illegal exponent format - if (stringMatch && stringMatch[4] && stringMatch[2] === undefined) { - throw new Error("" + string + " not a valid Decimal128 string"); - } - - // Get the negative or positive sign - if (string[index] == '+' || string[index] == '-') { - isNegative = string[index++] == '-'; - } - - // Check if user passed Infinity or NaN - if (!isDigit(string[index]) && string[index] != '.') { - if (string[index] == 'i' || string[index] == 'I') { - return new Decimal128(new Buffer(isNegative ? INF_NEGATIVE_BUFFER : INF_POSITIVE_BUFFER)); - } else if (string[index] == 'N') { - return new Decimal128(new Buffer(NAN_BUFFER)); - } - } - - // Read all the digits - while (isDigit(string[index]) || string[index] == '.') { - if (string[index] == '.') { - if (sawRadix) { - return new Decimal128(new Buffer(NAN_BUFFER)); - } - - sawRadix = true; - index = index + 1; - continue; - } - - if (nDigitsStored < 34) { - if (string[index] != '0' || foundNonZero) { - if (!foundNonZero) { - firstNonZero = nDigitsRead; - } - - foundNonZero = true; - - // Only store 34 digits - digits[digitsInsert++] = parseInt(string[index], 10); - nDigitsStored = nDigitsStored + 1; - } - } - - if (foundNonZero) { - nDigits = nDigits + 1; - } - - if (sawRadix) { - radixPosition = radixPosition + 1; - } - - nDigitsRead = nDigitsRead + 1; - index = index + 1; - } - - if (sawRadix && !nDigitsRead) { - throw new Error("" + string + " not a valid Decimal128 string"); - } - - // Read exponent if exists - if (string[index] == 'e' || string[index] == 'E') { - // Read exponent digits - var match = string.substr(++index).match(EXPONENT_REGEX); - - // No digits read - if (!match || !match[2]) { - return new Decimal128(new Buffer(NAN_BUFFER)); - } - - // Get exponent - exponent = parseInt(match[0], 10); - - // Adjust the index - index = index + match[0].length; - } - - // Return not a number - if (string[index]) { - return new Decimal128(new Buffer(NAN_BUFFER)); - } - - // Done reading input - // Find first non-zero digit in digits - firstDigit = 0; - - if (!nDigitsStored) { - firstDigit = 0; - lastDigit = 0; - digits[0] = 0; - nDigits = 1; - nDigitsStored = 1; - significantDigits = 0; - } else { - lastDigit = nDigitsStored - 1; - significantDigits = nDigits; - - if (exponent != 0 && significantDigits != 1) { - while (string[firstNonZero + significantDigits - 1] == '0') { - significantDigits = significantDigits - 1; - } - } - } - - // Normalization of exponent - // Correct exponent based on radix position, and shift significand as needed - // to represent user input - - // Overflow prevention - if (exponent <= radixPosition && radixPosition - exponent > 1 << 14) { - exponent = EXPONENT_MIN; - } else { - exponent = exponent - radixPosition; - } - - // Attempt to normalize the exponent - while (exponent > EXPONENT_MAX) { - // Shift exponent to significand and decrease - lastDigit = lastDigit + 1; - - if (lastDigit - firstDigit > MAX_DIGITS) { - // Check if we have a zero then just hard clamp, otherwise fail - var digitsString = digits.join(''); - if (digitsString.match(/^0+$/)) { - exponent = EXPONENT_MAX; - break; - } else { - return new Decimal128(new Buffer(isNegative ? INF_NEGATIVE_BUFFER : INF_POSITIVE_BUFFER)); - } - } - - exponent = exponent - 1; - } - - while (exponent < EXPONENT_MIN || nDigitsStored < nDigits) { - // Shift last digit - if (lastDigit == 0) { - exponent = EXPONENT_MIN; - significantDigits = 0; - break; - } - - if (nDigitsStored < nDigits) { - // adjust to match digits not stored - nDigits = nDigits - 1; - } else { - // adjust to round - lastDigit = lastDigit - 1; - } - - if (exponent < EXPONENT_MAX) { - exponent = exponent + 1; - } else { - // Check if we have a zero then just hard clamp, otherwise fail - var digitsString = digits.join(''); - if (digitsString.match(/^0+$/)) { - exponent = EXPONENT_MAX; - break; - } else { - return new Decimal128(new Buffer(isNegative ? INF_NEGATIVE_BUFFER : INF_POSITIVE_BUFFER)); - } - } - } - - // Round - // We've normalized the exponent, but might still need to round. - if (lastDigit - firstDigit + 1 < significantDigits && string[significantDigits] != '0') { - var endOfString = nDigitsRead; - - // If we have seen a radix point, 'string' is 1 longer than we have - // documented with ndigits_read, so inc the position of the first nonzero - // digit and the position that digits are read to. - if (sawRadix && exponent == EXPONENT_MIN) { - firstNonZero = firstNonZero + 1; - endOfString = endOfString + 1; - } - - var roundDigit = parseInt(string[firstNonZero + lastDigit + 1], 10); - var roundBit = 0; - - if (roundDigit >= 5) { - roundBit = 1; - - if (roundDigit == 5) { - roundBit = digits[lastDigit] % 2 == 1; - - for (var i = firstNonZero + lastDigit + 2; i < endOfString; i++) { - if (parseInt(string[i], 10)) { - roundBit = 1; - break; - } - } - } - } - - if (roundBit) { - var dIdx = lastDigit; - - for (; dIdx >= 0; dIdx--) { - if (++digits[dIdx] > 9) { - digits[dIdx] = 0; - - // overflowed most significant digit - if (dIdx == 0) { - if (exponent < EXPONENT_MAX) { - exponent = exponent + 1; - digits[dIdx] = 1; - } else { - return new Decimal128(new Buffer(isNegative ? INF_NEGATIVE_BUFFER : INF_POSITIVE_BUFFER)); - } - } - } else { - break; - } - } - } - } - - // Encode significand - // The high 17 digits of the significand - significandHigh = Long.fromNumber(0); - // The low 17 digits of the significand - significandLow = Long.fromNumber(0); - - // read a zero - if (significantDigits == 0) { - significandHigh = Long.fromNumber(0); - significandLow = Long.fromNumber(0); - } else if (lastDigit - firstDigit < 17) { - var dIdx = firstDigit; - significandLow = Long.fromNumber(digits[dIdx++]); - significandHigh = new Long(0, 0); - - for (; dIdx <= lastDigit; dIdx++) { - significandLow = significandLow.multiply(Long.fromNumber(10)); - significandLow = significandLow.add(Long.fromNumber(digits[dIdx])); - } - } else { - var dIdx = firstDigit; - significandHigh = Long.fromNumber(digits[dIdx++]); - - for (; dIdx <= lastDigit - 17; dIdx++) { - significandHigh = significandHigh.multiply(Long.fromNumber(10)); - significandHigh = significandHigh.add(Long.fromNumber(digits[dIdx])); - } - - significandLow = Long.fromNumber(digits[dIdx++]); - - for (; dIdx <= lastDigit; dIdx++) { - significandLow = significandLow.multiply(Long.fromNumber(10)); - significandLow = significandLow.add(Long.fromNumber(digits[dIdx])); - } - } - - var significand = multiply64x2(significandHigh, Long.fromString("100000000000000000")); - - significand.low = significand.low.add(significandLow); - - if (lessThan(significand.low, significandLow)) { - significand.high = significand.high.add(Long.fromNumber(1)); - } - - // Biased exponent - var biasedExponent = exponent + EXPONENT_BIAS; - var dec = { low: Long.fromNumber(0), high: Long.fromNumber(0) }; - - // Encode combination, exponent, and significand. - if (significand.high.shiftRightUnsigned(49).and(Long.fromNumber(1)).equals(Long.fromNumber)) { - // Encode '11' into bits 1 to 3 - dec.high = dec.high.or(Long.fromNumber(0x3).shiftLeft(61)); - dec.high = dec.high.or(Long.fromNumber(biasedExponent).and(Long.fromNumber(0x3fff).shiftLeft(47))); - dec.high = dec.high.or(significand.high.and(Long.fromNumber(0x7fffffffffff))); - } else { - dec.high = dec.high.or(Long.fromNumber(biasedExponent & 0x3fff).shiftLeft(49)); - dec.high = dec.high.or(significand.high.and(Long.fromNumber(0x1ffffffffffff))); - } - - dec.low = significand.low; - - // Encode sign - if (isNegative) { - dec.high = dec.high.or(Long.fromString('9223372036854775808')); - } - - // Encode into a buffer - var buffer = new Buffer(16); - var index = 0; - - // Encode the low 64 bits of the decimal - // Encode low bits - buffer[index++] = dec.low.low_ & 0xff; - buffer[index++] = dec.low.low_ >> 8 & 0xff; - buffer[index++] = dec.low.low_ >> 16 & 0xff; - buffer[index++] = dec.low.low_ >> 24 & 0xff; - // Encode high bits - buffer[index++] = dec.low.high_ & 0xff; - buffer[index++] = dec.low.high_ >> 8 & 0xff; - buffer[index++] = dec.low.high_ >> 16 & 0xff; - buffer[index++] = dec.low.high_ >> 24 & 0xff; - - // Encode the high 64 bits of the decimal - // Encode low bits - buffer[index++] = dec.high.low_ & 0xff; - buffer[index++] = dec.high.low_ >> 8 & 0xff; - buffer[index++] = dec.high.low_ >> 16 & 0xff; - buffer[index++] = dec.high.low_ >> 24 & 0xff; - // Encode high bits - buffer[index++] = dec.high.high_ & 0xff; - buffer[index++] = dec.high.high_ >> 8 & 0xff; - buffer[index++] = dec.high.high_ >> 16 & 0xff; - buffer[index++] = dec.high.high_ >> 24 & 0xff; - - // Return the new Decimal128 - return new Decimal128(buffer); - }; - - // Extract least significant 5 bits - var COMBINATION_MASK = 0x1f; - // Extract least significant 14 bits - var EXPONENT_MASK = 0x3fff; - // Value of combination field for Inf - var COMBINATION_INFINITY = 30; - // Value of combination field for NaN - var COMBINATION_NAN = 31; - // Value of combination field for NaN - var COMBINATION_SNAN = 32; - // decimal128 exponent bias - var EXPONENT_BIAS = 6176; - - Decimal128.prototype.toString = function () { - // Note: bits in this routine are referred to starting at 0, - // from the sign bit, towards the coefficient. - - // bits 0 - 31 - var high; - // bits 32 - 63 - var midh; - // bits 64 - 95 - var midl; - // bits 96 - 127 - var low; - // bits 1 - 5 - var combination; - // decoded biased exponent (14 bits) - var biased_exponent; - // the number of significand digits - var significand_digits = 0; - // the base-10 digits in the significand - var significand = new Array(36); - for (var i = 0; i < significand.length; i++) significand[i] = 0; - // read pointer into significand - var index = 0; - - // unbiased exponent - var exponent; - // the exponent if scientific notation is used - var scientific_exponent; - - // true if the number is zero - var is_zero = false; - - // the most signifcant significand bits (50-46) - var significand_msb; - // temporary storage for significand decoding - var significand128 = { parts: new Array(4) }; - // indexing variables - var i; - var j, k; - - // Output string - var string = []; - - // Unpack index - var index = 0; - - // Buffer reference - var buffer = this.bytes; - - // Unpack the low 64bits into a long - low = buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24; - midl = buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24; - - // Unpack the high 64bits into a long - midh = buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24; - high = buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24; - - // Unpack index - var index = 0; - - // Create the state of the decimal - var dec = { - low: new Long(low, midl), - high: new Long(midh, high) }; - - if (dec.high.lessThan(Long.ZERO)) { - string.push('-'); - } - - // Decode combination field and exponent - combination = high >> 26 & COMBINATION_MASK; - - if (combination >> 3 == 3) { - // Check for 'special' values - if (combination == COMBINATION_INFINITY) { - return string.join('') + "Infinity"; - } else if (combination == COMBINATION_NAN) { - return "NaN"; - } else { - biased_exponent = high >> 15 & EXPONENT_MASK; - significand_msb = 0x08 + (high >> 14 & 0x01); - } - } else { - significand_msb = high >> 14 & 0x07; - biased_exponent = high >> 17 & EXPONENT_MASK; - } - - exponent = biased_exponent - EXPONENT_BIAS; - - // Create string of significand digits - - // Convert the 114-bit binary number represented by - // (significand_high, significand_low) to at most 34 decimal - // digits through modulo and division. - significand128.parts[0] = (high & 0x3fff) + ((significand_msb & 0xf) << 14); - significand128.parts[1] = midh; - significand128.parts[2] = midl; - significand128.parts[3] = low; - - if (significand128.parts[0] == 0 && significand128.parts[1] == 0 && significand128.parts[2] == 0 && significand128.parts[3] == 0) { - is_zero = true; - } else { - for (var k = 3; k >= 0; k--) { - var least_digits = 0; - // Peform the divide - var result = divideu128(significand128); - significand128 = result.quotient; - least_digits = result.rem.low_; - - // We now have the 9 least significant digits (in base 2). - // Convert and output to string. - if (!least_digits) continue; - - for (var j = 8; j >= 0; j--) { - // significand[k * 9 + j] = Math.round(least_digits % 10); - significand[k * 9 + j] = least_digits % 10; - // least_digits = Math.round(least_digits / 10); - least_digits = Math.floor(least_digits / 10); - } - } - } - - // Output format options: - // Scientific - [-]d.dddE(+/-)dd or [-]dE(+/-)dd - // Regular - ddd.ddd - - if (is_zero) { - significand_digits = 1; - significand[index] = 0; - } else { - significand_digits = 36; - var i = 0; - - while (!significand[index]) { - i++; - significand_digits = significand_digits - 1; - index = index + 1; - } - } - - scientific_exponent = significand_digits - 1 + exponent; - - // The scientific exponent checks are dictated by the string conversion - // specification and are somewhat arbitrary cutoffs. - // - // We must check exponent > 0, because if this is the case, the number - // has trailing zeros. However, we *cannot* output these trailing zeros, - // because doing so would change the precision of the value, and would - // change stored data if the string converted number is round tripped. - - if (scientific_exponent >= 34 || scientific_exponent <= -7 || exponent > 0) { - // Scientific format - string.push(significand[index++]); - significand_digits = significand_digits - 1; - - if (significand_digits) { - string.push('.'); - } - - for (var i = 0; i < significand_digits; i++) { - string.push(significand[index++]); - } - - // Exponent - string.push('E'); - if (scientific_exponent > 0) { - string.push('+' + scientific_exponent); - } else { - string.push(scientific_exponent); - } - } else { - // Regular format with no decimal place - if (exponent >= 0) { - for (var i = 0; i < significand_digits; i++) { - string.push(significand[index++]); - } - } else { - var radix_position = significand_digits + exponent; - - // non-zero digits before radix - if (radix_position > 0) { - for (var i = 0; i < radix_position; i++) { - string.push(significand[index++]); - } - } else { - string.push('0'); - } - - string.push('.'); - // add leading zeros after radix - while (radix_position++ < 0) { - string.push('0'); - } - - for (var i = 0; i < significand_digits - Math.max(radix_position - 1, 0); i++) { - string.push(significand[index++]); - } - } - } - - return string.join(''); - }; - - Decimal128.prototype.toJSON = function () { - return { "$numberDecimal": this.toString() }; - }; - - module.exports = Decimal128; - module.exports.Decimal128 = Decimal128; - /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(300).Buffer)) - -/***/ }, -/* 315 */ -/***/ function(module, exports) { - - /** - * A class representation of the BSON MinKey type. - * - * @class - * @return {MinKey} A MinKey instance - */ - function MinKey() { - if (!(this instanceof MinKey)) return new MinKey(); - - this._bsontype = 'MinKey'; - } - - module.exports = MinKey; - module.exports.MinKey = MinKey; - -/***/ }, -/* 316 */ -/***/ function(module, exports) { - - /** - * A class representation of the BSON MaxKey type. - * - * @class - * @return {MaxKey} A MaxKey instance - */ - function MaxKey() { - if (!(this instanceof MaxKey)) return new MaxKey(); - - this._bsontype = 'MaxKey'; - } - - module.exports = MaxKey; - module.exports.MaxKey = MaxKey; - -/***/ }, -/* 317 */ -/***/ function(module, exports) { - - /** - * A class representation of the BSON DBRef type. - * - * @class - * @param {string} namespace the collection name. - * @param {ObjectID} oid the reference ObjectID. - * @param {string} [db] optional db name, if omitted the reference is local to the current db. - * @return {DBRef} - */ - function DBRef(namespace, oid, db) { - if (!(this instanceof DBRef)) return new DBRef(namespace, oid, db); - - this._bsontype = 'DBRef'; - this.namespace = namespace; - this.oid = oid; - this.db = db; - }; - - /** - * @ignore - * @api private - */ - DBRef.prototype.toJSON = function () { - return { - '$ref': this.namespace, - '$id': this.oid, - '$db': this.db == null ? '' : this.db - }; - }; - - module.exports = DBRef; - module.exports.DBRef = DBRef; - -/***/ }, -/* 318 */ -/***/ function(module, exports, __webpack_require__) { - - /* WEBPACK VAR INJECTION */(function(global) {/** - * Module dependencies. - * @ignore - */ - - // Test if we're in Node via presence of "global" not absence of "window" - // to support hybrid environments like Electron - if (typeof global !== 'undefined') { - var Buffer = __webpack_require__(300).Buffer; // TODO just use global Buffer - } - - /** - * A class representation of the BSON Binary type. - * - * Sub types - * - **BSON.BSON_BINARY_SUBTYPE_DEFAULT**, default BSON type. - * - **BSON.BSON_BINARY_SUBTYPE_FUNCTION**, BSON function type. - * - **BSON.BSON_BINARY_SUBTYPE_BYTE_ARRAY**, BSON byte array type. - * - **BSON.BSON_BINARY_SUBTYPE_UUID**, BSON uuid type. - * - **BSON.BSON_BINARY_SUBTYPE_MD5**, BSON md5 type. - * - **BSON.BSON_BINARY_SUBTYPE_USER_DEFINED**, BSON user defined type. - * - * @class - * @param {Buffer} buffer a buffer object containing the binary data. - * @param {Number} [subType] the option binary type. - * @return {Binary} - */ - function Binary(buffer, subType) { - if (!(this instanceof Binary)) return new Binary(buffer, subType); - - this._bsontype = 'Binary'; - - if (buffer instanceof Number) { - this.sub_type = buffer; - this.position = 0; - } else { - this.sub_type = subType == null ? BSON_BINARY_SUBTYPE_DEFAULT : subType; - this.position = 0; - } - - if (buffer != null && !(buffer instanceof Number)) { - // Only accept Buffer, Uint8Array or Arrays - if (typeof buffer == 'string') { - // Different ways of writing the length of the string for the different types - if (typeof Buffer != 'undefined') { - this.buffer = new Buffer(buffer); - } else if (typeof Uint8Array != 'undefined' || Object.prototype.toString.call(buffer) == '[object Array]') { - this.buffer = writeStringToArray(buffer); - } else { - throw new Error("only String, Buffer, Uint8Array or Array accepted"); - } - } else { - this.buffer = buffer; - } - this.position = buffer.length; - } else { - if (typeof Buffer != 'undefined') { - this.buffer = new Buffer(Binary.BUFFER_SIZE); - } else if (typeof Uint8Array != 'undefined') { - this.buffer = new Uint8Array(new ArrayBuffer(Binary.BUFFER_SIZE)); - } else { - this.buffer = new Array(Binary.BUFFER_SIZE); - } - // Set position to start of buffer - this.position = 0; - } - }; - - /** - * Updates this binary with byte_value. - * - * @method - * @param {string} byte_value a single byte we wish to write. - */ - Binary.prototype.put = function put(byte_value) { - // If it's a string and a has more than one character throw an error - if (byte_value['length'] != null && typeof byte_value != 'number' && byte_value.length != 1) throw new Error("only accepts single character String, Uint8Array or Array"); - if (typeof byte_value != 'number' && byte_value < 0 || byte_value > 255) throw new Error("only accepts number in a valid unsigned byte range 0-255"); - - // Decode the byte value once - var decoded_byte = null; - if (typeof byte_value == 'string') { - decoded_byte = byte_value.charCodeAt(0); - } else if (byte_value['length'] != null) { - decoded_byte = byte_value[0]; - } else { - decoded_byte = byte_value; - } - - if (this.buffer.length > this.position) { - this.buffer[this.position++] = decoded_byte; - } else { - if (typeof Buffer != 'undefined' && Buffer.isBuffer(this.buffer)) { - // Create additional overflow buffer - var buffer = new Buffer(Binary.BUFFER_SIZE + this.buffer.length); - // Combine the two buffers together - this.buffer.copy(buffer, 0, 0, this.buffer.length); - this.buffer = buffer; - this.buffer[this.position++] = decoded_byte; - } else { - var buffer = null; - // Create a new buffer (typed or normal array) - if (Object.prototype.toString.call(this.buffer) == '[object Uint8Array]') { - buffer = new Uint8Array(new ArrayBuffer(Binary.BUFFER_SIZE + this.buffer.length)); - } else { - buffer = new Array(Binary.BUFFER_SIZE + this.buffer.length); - } - - // We need to copy all the content to the new array - for (var i = 0; i < this.buffer.length; i++) { - buffer[i] = this.buffer[i]; - } - - // Reassign the buffer - this.buffer = buffer; - // Write the byte - this.buffer[this.position++] = decoded_byte; - } - } - }; - - /** - * Writes a buffer or string to the binary. - * - * @method - * @param {(Buffer|string)} string a string or buffer to be written to the Binary BSON object. - * @param {number} offset specify the binary of where to write the content. - * @return {null} - */ - Binary.prototype.write = function write(string, offset) { - offset = typeof offset == 'number' ? offset : this.position; - - // If the buffer is to small let's extend the buffer - if (this.buffer.length < offset + string.length) { - var buffer = null; - // If we are in node.js - if (typeof Buffer != 'undefined' && Buffer.isBuffer(this.buffer)) { - buffer = new Buffer(this.buffer.length + string.length); - this.buffer.copy(buffer, 0, 0, this.buffer.length); - } else if (Object.prototype.toString.call(this.buffer) == '[object Uint8Array]') { - // Create a new buffer - buffer = new Uint8Array(new ArrayBuffer(this.buffer.length + string.length)); - // Copy the content - for (var i = 0; i < this.position; i++) { - buffer[i] = this.buffer[i]; - } - } - - // Assign the new buffer - this.buffer = buffer; - } - - if (typeof Buffer != 'undefined' && Buffer.isBuffer(string) && Buffer.isBuffer(this.buffer)) { - string.copy(this.buffer, offset, 0, string.length); - this.position = offset + string.length > this.position ? offset + string.length : this.position; - // offset = string.length - } else if (typeof Buffer != 'undefined' && typeof string == 'string' && Buffer.isBuffer(this.buffer)) { - this.buffer.write(string, offset, 'binary'); - this.position = offset + string.length > this.position ? offset + string.length : this.position; - // offset = string.length; - } else if (Object.prototype.toString.call(string) == '[object Uint8Array]' || Object.prototype.toString.call(string) == '[object Array]' && typeof string != 'string') { - for (var i = 0; i < string.length; i++) { - this.buffer[offset++] = string[i]; - } - - this.position = offset > this.position ? offset : this.position; - } else if (typeof string == 'string') { - for (var i = 0; i < string.length; i++) { - this.buffer[offset++] = string.charCodeAt(i); - } - - this.position = offset > this.position ? offset : this.position; - } - }; - - /** - * Reads **length** bytes starting at **position**. - * - * @method - * @param {number} position read from the given position in the Binary. - * @param {number} length the number of bytes to read. - * @return {Buffer} - */ - Binary.prototype.read = function read(position, length) { - length = length && length > 0 ? length : this.position; - - // Let's return the data based on the type we have - if (this.buffer['slice']) { - return this.buffer.slice(position, position + length); - } else { - // Create a buffer to keep the result - var buffer = typeof Uint8Array != 'undefined' ? new Uint8Array(new ArrayBuffer(length)) : new Array(length); - for (var i = 0; i < length; i++) { - buffer[i] = this.buffer[position++]; - } - } - // Return the buffer - return buffer; - }; - - /** - * Returns the value of this binary as a string. - * - * @method - * @return {string} - */ - Binary.prototype.value = function value(asRaw) { - asRaw = asRaw == null ? false : asRaw; - - // Optimize to serialize for the situation where the data == size of buffer - if (asRaw && typeof Buffer != 'undefined' && Buffer.isBuffer(this.buffer) && this.buffer.length == this.position) return this.buffer; - - // If it's a node.js buffer object - if (typeof Buffer != 'undefined' && Buffer.isBuffer(this.buffer)) { - return asRaw ? this.buffer.slice(0, this.position) : this.buffer.toString('binary', 0, this.position); - } else { - if (asRaw) { - // we support the slice command use it - if (this.buffer['slice'] != null) { - return this.buffer.slice(0, this.position); - } else { - // Create a new buffer to copy content to - var newBuffer = Object.prototype.toString.call(this.buffer) == '[object Uint8Array]' ? new Uint8Array(new ArrayBuffer(this.position)) : new Array(this.position); - // Copy content - for (var i = 0; i < this.position; i++) { - newBuffer[i] = this.buffer[i]; - } - // Return the buffer - return newBuffer; - } - } else { - return convertArraytoUtf8BinaryString(this.buffer, 0, this.position); - } - } - }; - - /** - * Length. - * - * @method - * @return {number} the length of the binary. - */ - Binary.prototype.length = function length() { - return this.position; - }; - - /** - * @ignore - */ - Binary.prototype.toJSON = function () { - return this.buffer != null ? this.buffer.toString('base64') : ''; - }; - - /** - * @ignore - */ - Binary.prototype.toString = function (format) { - return this.buffer != null ? this.buffer.slice(0, this.position).toString(format) : ''; - }; - - /** - * Binary default subtype - * @ignore - */ - var BSON_BINARY_SUBTYPE_DEFAULT = 0; - - /** - * @ignore - */ - var writeStringToArray = function (data) { - // Create a buffer - var buffer = typeof Uint8Array != 'undefined' ? new Uint8Array(new ArrayBuffer(data.length)) : new Array(data.length); - // Write the content to the buffer - for (var i = 0; i < data.length; i++) { - buffer[i] = data.charCodeAt(i); - } - // Write the string to the buffer - return buffer; - }; - - /** - * Convert Array ot Uint8Array to Binary String - * - * @ignore - */ - var convertArraytoUtf8BinaryString = function (byteArray, startIndex, endIndex) { - var result = ""; - for (var i = startIndex; i < endIndex; i++) { - result = result + String.fromCharCode(byteArray[i]); - } - return result; - }; - - Binary.BUFFER_SIZE = 256; - - /** - * Default BSON type - * - * @classconstant SUBTYPE_DEFAULT - **/ - Binary.SUBTYPE_DEFAULT = 0; - /** - * Function BSON type - * - * @classconstant SUBTYPE_DEFAULT - **/ - Binary.SUBTYPE_FUNCTION = 1; - /** - * Byte Array BSON type - * - * @classconstant SUBTYPE_DEFAULT - **/ - Binary.SUBTYPE_BYTE_ARRAY = 2; - /** - * OLD UUID BSON type - * - * @classconstant SUBTYPE_DEFAULT - **/ - Binary.SUBTYPE_UUID_OLD = 3; - /** - * UUID BSON type - * - * @classconstant SUBTYPE_DEFAULT - **/ - Binary.SUBTYPE_UUID = 4; - /** - * MD5 BSON type - * - * @classconstant SUBTYPE_DEFAULT - **/ - Binary.SUBTYPE_MD5 = 5; - /** - * User BSON type - * - * @classconstant SUBTYPE_DEFAULT - **/ - Binary.SUBTYPE_USER_DEFINED = 128; - - /** - * Expose. - */ - module.exports = Binary; - module.exports.Binary = Binary; - /* WEBPACK VAR INJECTION */}.call(exports, (function() { return this; }()))) - -/***/ }, -/* 319 */ -/***/ function(module, exports, __webpack_require__) { - - /* WEBPACK VAR INJECTION */(function(Buffer) {"use strict"; - - var readIEEE754 = __webpack_require__(304).readIEEE754, - f = __webpack_require__(320).format, - Long = __webpack_require__(306).Long, - Double = __webpack_require__(307).Double, - Timestamp = __webpack_require__(308).Timestamp, - ObjectID = __webpack_require__(309).ObjectID, - Symbol = __webpack_require__(311).Symbol, - Code = __webpack_require__(313).Code, - MinKey = __webpack_require__(315).MinKey, - MaxKey = __webpack_require__(316).MaxKey, - Decimal128 = __webpack_require__(314), - Int32 = __webpack_require__(312), - DBRef = __webpack_require__(317).DBRef, - BSONRegExp = __webpack_require__(310).BSONRegExp, - Binary = __webpack_require__(318).Binary; - - var deserialize = function (buffer, options, isArray) { - options = options == null ? {} : options; - var index = options && options.index ? options.index : 0; - // Read the document size - var size = buffer[index] | buffer[index + 1] << 8 | buffer[index + 2] << 16 | buffer[index + 3] << 24; - - // Ensure buffer is valid size - if (size < 5 || buffer.length < size || size + index > buffer.length) { - throw new Error("corrupt bson message"); - } - - // Illegal end value - if (buffer[index + size - 1] != 0) { - throw new Error("One object, sized correctly, with a spot for an EOO, but the EOO isn't 0x00"); - } - - // Start deserializtion - return deserializeObject(buffer, index, options, isArray); - }; - - var deserializeObject = function (buffer, index, options, isArray) { - var evalFunctions = options['evalFunctions'] == null ? false : options['evalFunctions']; - var cacheFunctions = options['cacheFunctions'] == null ? false : options['cacheFunctions']; - var cacheFunctionsCrc32 = options['cacheFunctionsCrc32'] == null ? false : options['cacheFunctionsCrc32']; - var fieldsAsRaw = options['fieldsAsRaw'] == null ? null : options['fieldsAsRaw']; - - // Return raw bson buffer instead of parsing it - var raw = options['raw'] == null ? false : options['raw']; - - // Return BSONRegExp objects instead of native regular expressions - var bsonRegExp = typeof options['bsonRegExp'] == 'boolean' ? options['bsonRegExp'] : false; - - // Controls the promotion of values vs wrapper classes - var promoteBuffers = options['promoteBuffers'] == null ? false : options['promoteBuffers']; - var promoteLongs = options['promoteLongs'] == null ? true : options['promoteLongs']; - var promoteValues = options['promoteValues'] == null ? true : options['promoteValues']; - - // Set the start index - var startIndex = index; - - // Validate that we have at least 4 bytes of buffer - if (buffer.length < 5) throw new Error("corrupt bson message < 5 bytes long"); - - // Read the document size - var size = buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24; - - // Ensure buffer is valid size - if (size < 5 || size > buffer.length) throw new Error("corrupt bson message"); - - // Create holding object - var object = isArray ? [] : {}; - // Used for arrays to skip having to perform utf8 decoding - var arrayIndex = 0; - - // While we have more left data left keep parsing - while (true) { - // Read the type - var elementType = buffer[index++]; - // If we get a zero it's the last byte, exit - if (elementType == 0) { - break; - } - - // Get the start search index - var i = index; - // Locate the end of the c string - while (buffer[i] !== 0x00 && i < buffer.length) { - i++; - } - - // If are at the end of the buffer there is a problem with the document - if (i >= buffer.length) throw new Error("Bad BSON Document: illegal CString"); - var name = isArray ? arrayIndex++ : buffer.toString('utf8', index, i); - - index = i + 1; - - if (elementType == BSON.BSON_DATA_STRING) { - var stringSize = buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24; - if (stringSize <= 0 || stringSize > buffer.length - index || buffer[index + stringSize - 1] != 0) throw new Error("bad string length in bson"); - object[name] = buffer.toString('utf8', index, index + stringSize - 1); - index = index + stringSize; - } else if (elementType == BSON.BSON_DATA_OID) { - var oid = new Buffer(12); - buffer.copy(oid, 0, index, index + 12); - object[name] = new ObjectID(oid); - index = index + 12; - } else if (elementType == BSON.BSON_DATA_INT && promoteValues == false) { - object[name] = new Int32(buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24); - } else if (elementType == BSON.BSON_DATA_INT) { - object[name] = buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24; - } else if (elementType == BSON.BSON_DATA_NUMBER && promoteValues == false) { - object[name] = new Double(buffer.readDoubleLE(index)); - index = index + 8; - } else if (elementType == BSON.BSON_DATA_NUMBER) { - object[name] = buffer.readDoubleLE(index); - index = index + 8; - } else if (elementType == BSON.BSON_DATA_DATE) { - var lowBits = buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24; - var highBits = buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24; - object[name] = new Date(new Long(lowBits, highBits).toNumber()); - } else if (elementType == BSON.BSON_DATA_BOOLEAN) { - if (buffer[index] != 0 && buffer[index] != 1) throw new Error('illegal boolean type value'); - object[name] = buffer[index++] == 1; - } else if (elementType == BSON.BSON_DATA_OBJECT) { - var _index = index; - var objectSize = buffer[index] | buffer[index + 1] << 8 | buffer[index + 2] << 16 | buffer[index + 3] << 24; - if (objectSize <= 0 || objectSize > buffer.length - index) throw new Error("bad embedded document length in bson"); - - // We have a raw value - if (raw) { - object[name] = buffer.slice(index, index + objectSize); - } else { - object[name] = deserializeObject(buffer, _index, options, false); - } - - index = index + objectSize; - } else if (elementType == BSON.BSON_DATA_ARRAY) { - var _index = index; - var objectSize = buffer[index] | buffer[index + 1] << 8 | buffer[index + 2] << 16 | buffer[index + 3] << 24; - var arrayOptions = options; - - // Stop index - var stopIndex = index + objectSize; - - // All elements of array to be returned as raw bson - if (fieldsAsRaw && fieldsAsRaw[name]) { - arrayOptions = {}; - for (var n in options) arrayOptions[n] = options[n]; - arrayOptions['raw'] = true; - } - - object[name] = deserializeObject(buffer, _index, arrayOptions, true); - index = index + objectSize; - - if (buffer[index - 1] != 0) throw new Error('invalid array terminator byte'); - if (index != stopIndex) throw new Error('corrupted array bson'); - } else if (elementType == BSON.BSON_DATA_UNDEFINED) { - object[name] = undefined; - } else if (elementType == BSON.BSON_DATA_NULL) { - object[name] = null; - } else if (elementType == BSON.BSON_DATA_LONG) { - // Unpack the low and high bits - var lowBits = buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24; - var highBits = buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24; - var long = new Long(lowBits, highBits); - // Promote the long if possible - if (promoteLongs && promoteValues == true) { - object[name] = long.lessThanOrEqual(JS_INT_MAX_LONG) && long.greaterThanOrEqual(JS_INT_MIN_LONG) ? long.toNumber() : long; - } else { - object[name] = long; - } - } else if (elementType == BSON.BSON_DATA_DECIMAL128) { - // Buffer to contain the decimal bytes - var bytes = new Buffer(16); - // Copy the next 16 bytes into the bytes buffer - buffer.copy(bytes, 0, index, index + 16); - // Update index - index = index + 16; - // Assign the new Decimal128 value - var decimal128 = new Decimal128(bytes); - // If we have an alternative mapper use that - object[name] = decimal128.toObject ? decimal128.toObject() : decimal128; - } else if (elementType == BSON.BSON_DATA_BINARY) { - var binarySize = buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24; - var totalBinarySize = binarySize; - var subType = buffer[index++]; - - // Did we have a negative binary size, throw - if (binarySize < 0) throw new Error('Negative binary type element size found'); - - // Is the length longer than the document - if (binarySize > buffer.length) throw new Error('Binary type size larger than document size'); - - // Decode as raw Buffer object if options specifies it - if (buffer['slice'] != null) { - // If we have subtype 2 skip the 4 bytes for the size - if (subType == Binary.SUBTYPE_BYTE_ARRAY) { - binarySize = buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24; - if (binarySize < 0) throw new Error('Negative binary type element size found for subtype 0x02'); - if (binarySize > totalBinarySize - 4) throw new Error('Binary type with subtype 0x02 contains to long binary size'); - if (binarySize < totalBinarySize - 4) throw new Error('Binary type with subtype 0x02 contains to short binary size'); - } - - if (promoteBuffers && promoteValues) { - object[name] = buffer.slice(index, index + binarySize); - } else { - object[name] = new Binary(buffer.slice(index, index + binarySize), subType); - } - } else { - var _buffer = typeof Uint8Array != 'undefined' ? new Uint8Array(new ArrayBuffer(binarySize)) : new Array(binarySize); - // If we have subtype 2 skip the 4 bytes for the size - if (subType == Binary.SUBTYPE_BYTE_ARRAY) { - binarySize = buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24; - if (binarySize < 0) throw new Error('Negative binary type element size found for subtype 0x02'); - if (binarySize > totalBinarySize - 4) throw new Error('Binary type with subtype 0x02 contains to long binary size'); - if (binarySize < totalBinarySize - 4) throw new Error('Binary type with subtype 0x02 contains to short binary size'); - } - - // Copy the data - for (var i = 0; i < binarySize; i++) { - _buffer[i] = buffer[index + i]; - } - - if (promoteBuffers && promoteValues) { - object[name] = _buffer; - } else { - object[name] = new Binary(_buffer, subType); - } - } - - // Update the index - index = index + binarySize; - } else if (elementType == BSON.BSON_DATA_REGEXP && bsonRegExp == false) { - // Get the start search index - var i = index; - // Locate the end of the c string - while (buffer[i] !== 0x00 && i < buffer.length) { - i++; - } - // If are at the end of the buffer there is a problem with the document - if (i >= buffer.length) throw new Error("Bad BSON Document: illegal CString"); - // Return the C string - var source = buffer.toString('utf8', index, i); - // Create the regexp - index = i + 1; - - // Get the start search index - var i = index; - // Locate the end of the c string - while (buffer[i] !== 0x00 && i < buffer.length) { - i++; - } - // If are at the end of the buffer there is a problem with the document - if (i >= buffer.length) throw new Error("Bad BSON Document: illegal CString"); - // Return the C string - var regExpOptions = buffer.toString('utf8', index, i); - index = i + 1; - - // For each option add the corresponding one for javascript - var optionsArray = new Array(regExpOptions.length); - - // Parse options - for (var i = 0; i < regExpOptions.length; i++) { - switch (regExpOptions[i]) { - case 'm': - optionsArray[i] = 'm'; - break; - case 's': - optionsArray[i] = 'g'; - break; - case 'i': - optionsArray[i] = 'i'; - break; - } - } - - object[name] = new RegExp(source, optionsArray.join('')); - } else if (elementType == BSON.BSON_DATA_REGEXP && bsonRegExp == true) { - // Get the start search index - var i = index; - // Locate the end of the c string - while (buffer[i] !== 0x00 && i < buffer.length) { - i++; - } - // If are at the end of the buffer there is a problem with the document - if (i >= buffer.length) throw new Error("Bad BSON Document: illegal CString"); - // Return the C string - var source = buffer.toString('utf8', index, i); - index = i + 1; - - // Get the start search index - var i = index; - // Locate the end of the c string - while (buffer[i] !== 0x00 && i < buffer.length) { - i++; - } - // If are at the end of the buffer there is a problem with the document - if (i >= buffer.length) throw new Error("Bad BSON Document: illegal CString"); - // Return the C string - var regExpOptions = buffer.toString('utf8', index, i); - index = i + 1; - - // Set the object - object[name] = new BSONRegExp(source, regExpOptions); - } else if (elementType == BSON.BSON_DATA_SYMBOL) { - var stringSize = buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24; - if (stringSize <= 0 || stringSize > buffer.length - index || buffer[index + stringSize - 1] != 0) throw new Error("bad string length in bson"); - object[name] = new Symbol(buffer.toString('utf8', index, index + stringSize - 1)); - index = index + stringSize; - } else if (elementType == BSON.BSON_DATA_TIMESTAMP) { - var lowBits = buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24; - var highBits = buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24; - object[name] = new Timestamp(lowBits, highBits); - } else if (elementType == BSON.BSON_DATA_MIN_KEY) { - object[name] = new MinKey(); - } else if (elementType == BSON.BSON_DATA_MAX_KEY) { - object[name] = new MaxKey(); - } else if (elementType == BSON.BSON_DATA_CODE) { - var stringSize = buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24; - if (stringSize <= 0 || stringSize > buffer.length - index || buffer[index + stringSize - 1] != 0) throw new Error("bad string length in bson"); - var functionString = buffer.toString('utf8', index, index + stringSize - 1); - - // If we are evaluating the functions - if (evalFunctions) { - var value = null; - // If we have cache enabled let's look for the md5 of the function in the cache - if (cacheFunctions) { - var hash = cacheFunctionsCrc32 ? crc32(functionString) : functionString; - // Got to do this to avoid V8 deoptimizing the call due to finding eval - object[name] = isolateEvalWithHash(functionCache, hash, functionString, object); - } else { - object[name] = isolateEval(functionString); - } - } else { - object[name] = new Code(functionString); - } - - // Update parse index position - index = index + stringSize; - } else if (elementType == BSON.BSON_DATA_CODE_W_SCOPE) { - var totalSize = buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24; - - // Element cannot be shorter than totalSize + stringSize + documentSize + terminator - if (totalSize < 4 + 4 + 4 + 1) { - throw new Error("code_w_scope total size shorter minimum expected length"); - } - - // Get the code string size - var stringSize = buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24; - // Check if we have a valid string - if (stringSize <= 0 || stringSize > buffer.length - index || buffer[index + stringSize - 1] != 0) throw new Error("bad string length in bson"); - - // Javascript function - var functionString = buffer.toString('utf8', index, index + stringSize - 1); - // Update parse index position - index = index + stringSize; - // Parse the element - var _index = index; - // Decode the size of the object document - var objectSize = buffer[index] | buffer[index + 1] << 8 | buffer[index + 2] << 16 | buffer[index + 3] << 24; - // Decode the scope object - var scopeObject = deserializeObject(buffer, _index, options, false); - // Adjust the index - index = index + objectSize; - - // Check if field length is to short - if (totalSize < 4 + 4 + objectSize + stringSize) { - throw new Error('code_w_scope total size is to short, truncating scope'); - } - - // Check if totalSize field is to long - if (totalSize > 4 + 4 + objectSize + stringSize) { - throw new Error('code_w_scope total size is to long, clips outer document'); - } - - // If we are evaluating the functions - if (evalFunctions) { - // Contains the value we are going to set - var value = null; - // If we have cache enabled let's look for the md5 of the function in the cache - if (cacheFunctions) { - var hash = cacheFunctionsCrc32 ? crc32(functionString) : functionString; - // Got to do this to avoid V8 deoptimizing the call due to finding eval - object[name] = isolateEvalWithHash(functionCache, hash, functionString, object); - } else { - object[name] = isolateEval(functionString); - } - - object[name].scope = scopeObject; - } else { - object[name] = new Code(functionString, scopeObject); - } - } else if (elementType == BSON.BSON_DATA_DBPOINTER) { - // Get the code string size - var stringSize = buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24; - // Check if we have a valid string - if (stringSize <= 0 || stringSize > buffer.length - index || buffer[index + stringSize - 1] != 0) throw new Error("bad string length in bson"); - // Namespace - var namespace = buffer.toString('utf8', index, index + stringSize - 1); - // Update parse index position - index = index + stringSize; - - // Read the oid - var oidBuffer = new Buffer(12); - buffer.copy(oidBuffer, 0, index, index + 12); - var oid = new ObjectID(oidBuffer); - - // Update the index - index = index + 12; - - // Split the namespace - var parts = namespace.split('.'); - var db = parts.shift(); - var collection = parts.join('.'); - // Upgrade to DBRef type - object[name] = new DBRef(collection, oid, db); - } else { - throw new Error("Detected unknown BSON type " + elementType.toString(16) + " for fieldname \"" + name + "\", are you using the latest BSON parser"); - } - } - - // Check if the deserialization was against a valid array/object - if (size != index - startIndex) { - if (isArray) throw new Error('corrupt array bson'); - throw new Error('corrupt object bson'); - } - - // Check if we have a db ref object - if (object['$id'] != null) object = new DBRef(object['$ref'], object['$id'], object['$db']); - return object; - }; - - /** - * Ensure eval is isolated. - * - * @ignore - * @api private - */ - var isolateEvalWithHash = function (functionCache, hash, functionString, object) { - // Contains the value we are going to set - var value = null; - - // Check for cache hit, eval if missing and return cached function - if (functionCache[hash] == null) { - eval("value = " + functionString); - functionCache[hash] = value; - } - // Set the object - return functionCache[hash].bind(object); - }; - - /** - * Ensure eval is isolated. - * - * @ignore - * @api private - */ - var isolateEval = function (functionString) { - // Contains the value we are going to set - var value = null; - // Eval the function - eval("value = " + functionString); - return value; - }; - - var BSON = {}; - - /** - * Contains the function cache if we have that enable to allow for avoiding the eval step on each deserialization, comparison is by md5 - * - * @ignore - * @api private - */ - var functionCache = BSON.functionCache = {}; - - /** - * Number BSON Type - * - * @classconstant BSON_DATA_NUMBER - **/ - BSON.BSON_DATA_NUMBER = 1; - /** - * String BSON Type - * - * @classconstant BSON_DATA_STRING - **/ - BSON.BSON_DATA_STRING = 2; - /** - * Object BSON Type - * - * @classconstant BSON_DATA_OBJECT - **/ - BSON.BSON_DATA_OBJECT = 3; - /** - * Array BSON Type - * - * @classconstant BSON_DATA_ARRAY - **/ - BSON.BSON_DATA_ARRAY = 4; - /** - * Binary BSON Type - * - * @classconstant BSON_DATA_BINARY - **/ - BSON.BSON_DATA_BINARY = 5; - /** - * Binary BSON Type - * - * @classconstant BSON_DATA_UNDEFINED - **/ - BSON.BSON_DATA_UNDEFINED = 6; - /** - * ObjectID BSON Type - * - * @classconstant BSON_DATA_OID - **/ - BSON.BSON_DATA_OID = 7; - /** - * Boolean BSON Type - * - * @classconstant BSON_DATA_BOOLEAN - **/ - BSON.BSON_DATA_BOOLEAN = 8; - /** - * Date BSON Type - * - * @classconstant BSON_DATA_DATE - **/ - BSON.BSON_DATA_DATE = 9; - /** - * null BSON Type - * - * @classconstant BSON_DATA_NULL - **/ - BSON.BSON_DATA_NULL = 10; - /** - * RegExp BSON Type - * - * @classconstant BSON_DATA_REGEXP - **/ - BSON.BSON_DATA_REGEXP = 11; - /** - * Code BSON Type - * - * @classconstant BSON_DATA_DBPOINTER - **/ - BSON.BSON_DATA_DBPOINTER = 12; - /** - * Code BSON Type - * - * @classconstant BSON_DATA_CODE - **/ - BSON.BSON_DATA_CODE = 13; - /** - * Symbol BSON Type - * - * @classconstant BSON_DATA_SYMBOL - **/ - BSON.BSON_DATA_SYMBOL = 14; - /** - * Code with Scope BSON Type - * - * @classconstant BSON_DATA_CODE_W_SCOPE - **/ - BSON.BSON_DATA_CODE_W_SCOPE = 15; - /** - * 32 bit Integer BSON Type - * - * @classconstant BSON_DATA_INT - **/ - BSON.BSON_DATA_INT = 16; - /** - * Timestamp BSON Type - * - * @classconstant BSON_DATA_TIMESTAMP - **/ - BSON.BSON_DATA_TIMESTAMP = 17; - /** - * Long BSON Type - * - * @classconstant BSON_DATA_LONG - **/ - BSON.BSON_DATA_LONG = 18; - /** - * Long BSON Type - * - * @classconstant BSON_DATA_DECIMAL128 - **/ - BSON.BSON_DATA_DECIMAL128 = 19; - /** - * MinKey BSON Type - * - * @classconstant BSON_DATA_MIN_KEY - **/ - BSON.BSON_DATA_MIN_KEY = 0xff; - /** - * MaxKey BSON Type - * - * @classconstant BSON_DATA_MAX_KEY - **/ - BSON.BSON_DATA_MAX_KEY = 0x7f; - - /** - * Binary Default Type - * - * @classconstant BSON_BINARY_SUBTYPE_DEFAULT - **/ - BSON.BSON_BINARY_SUBTYPE_DEFAULT = 0; - /** - * Binary Function Type - * - * @classconstant BSON_BINARY_SUBTYPE_FUNCTION - **/ - BSON.BSON_BINARY_SUBTYPE_FUNCTION = 1; - /** - * Binary Byte Array Type - * - * @classconstant BSON_BINARY_SUBTYPE_BYTE_ARRAY - **/ - BSON.BSON_BINARY_SUBTYPE_BYTE_ARRAY = 2; - /** - * Binary UUID Type - * - * @classconstant BSON_BINARY_SUBTYPE_UUID - **/ - BSON.BSON_BINARY_SUBTYPE_UUID = 3; - /** - * Binary MD5 Type - * - * @classconstant BSON_BINARY_SUBTYPE_MD5 - **/ - BSON.BSON_BINARY_SUBTYPE_MD5 = 4; - /** - * Binary User Defined Type - * - * @classconstant BSON_BINARY_SUBTYPE_USER_DEFINED - **/ - BSON.BSON_BINARY_SUBTYPE_USER_DEFINED = 128; - - // BSON MAX VALUES - BSON.BSON_INT32_MAX = 0x7FFFFFFF; - BSON.BSON_INT32_MIN = -0x80000000; - - BSON.BSON_INT64_MAX = Math.pow(2, 63) - 1; - BSON.BSON_INT64_MIN = -Math.pow(2, 63); - - // JS MAX PRECISE VALUES - BSON.JS_INT_MAX = 0x20000000000000; // Any integer up to 2^53 can be precisely represented by a double. - BSON.JS_INT_MIN = -0x20000000000000; // Any integer down to -2^53 can be precisely represented by a double. - - // Internal long versions - var JS_INT_MAX_LONG = Long.fromNumber(0x20000000000000); // Any integer up to 2^53 can be precisely represented by a double. - var JS_INT_MIN_LONG = Long.fromNumber(-0x20000000000000); // Any integer down to -2^53 can be precisely represented by a double. - - module.exports = deserialize; - /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(300).Buffer)) - -/***/ }, -/* 320 */ -/***/ function(module, exports, __webpack_require__) { - - /* WEBPACK VAR INJECTION */(function(global, process) {// Copyright Joyent, Inc. and other Node contributors. - // - // Permission is hereby granted, free of charge, to any person obtaining a - // copy of this software and associated documentation files (the - // "Software"), to deal in the Software without restriction, including - // without limitation the rights to use, copy, modify, merge, publish, - // distribute, sublicense, and/or sell copies of the Software, and to permit - // persons to whom the Software is furnished to do so, subject to the - // following conditions: - // - // The above copyright notice and this permission notice shall be included - // in all copies or substantial portions of the Software. - // - // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS - // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN - // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, - // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR - // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE - // USE OR OTHER DEALINGS IN THE SOFTWARE. - - var formatRegExp = /%[sdj%]/g; - exports.format = function(f) { - if (!isString(f)) { - var objects = []; - for (var i = 0; i < arguments.length; i++) { - objects.push(inspect(arguments[i])); - } - return objects.join(' '); - } - - var i = 1; - var args = arguments; - var len = args.length; - var str = String(f).replace(formatRegExp, function(x) { - if (x === '%%') return '%'; - if (i >= len) return x; - switch (x) { - case '%s': return String(args[i++]); - case '%d': return Number(args[i++]); - case '%j': - try { - return JSON.stringify(args[i++]); - } catch (_) { - return '[Circular]'; - } - default: - return x; - } - }); - for (var x = args[i]; i < len; x = args[++i]) { - if (isNull(x) || !isObject(x)) { - str += ' ' + x; - } else { - str += ' ' + inspect(x); - } - } - return str; - }; - - - // Mark that a method should not be used. - // Returns a modified function which warns once by default. - // If --no-deprecation is set, then it is a no-op. - exports.deprecate = function(fn, msg) { - // Allow for deprecating things in the process of starting up. - if (isUndefined(global.process)) { - return function() { - return exports.deprecate(fn, msg).apply(this, arguments); - }; - } - - if (process.noDeprecation === true) { - return fn; - } - - var warned = false; - function deprecated() { - if (!warned) { - if (process.throwDeprecation) { - throw new Error(msg); - } else if (process.traceDeprecation) { - console.trace(msg); - } else { - console.error(msg); - } - warned = true; - } - return fn.apply(this, arguments); - } - - return deprecated; - }; - - - var debugs = {}; - var debugEnviron; - exports.debuglog = function(set) { - if (isUndefined(debugEnviron)) - debugEnviron = process.env.NODE_DEBUG || ''; - set = set.toUpperCase(); - if (!debugs[set]) { - if (new RegExp('\\b' + set + '\\b', 'i').test(debugEnviron)) { - var pid = process.pid; - debugs[set] = function() { - var msg = exports.format.apply(exports, arguments); - console.error('%s %d: %s', set, pid, msg); - }; - } else { - debugs[set] = function() {}; - } - } - return debugs[set]; - }; - - - /** - * Echos the value of a value. Trys to print the value out - * in the best way possible given the different types. - * - * @param {Object} obj The object to print out. - * @param {Object} opts Optional options object that alters the output. - */ - /* legacy: obj, showHidden, depth, colors*/ - function inspect(obj, opts) { - // default options - var ctx = { - seen: [], - stylize: stylizeNoColor - }; - // legacy... - if (arguments.length >= 3) ctx.depth = arguments[2]; - if (arguments.length >= 4) ctx.colors = arguments[3]; - if (isBoolean(opts)) { - // legacy... - ctx.showHidden = opts; - } else if (opts) { - // got an "options" object - exports._extend(ctx, opts); - } - // set default options - if (isUndefined(ctx.showHidden)) ctx.showHidden = false; - if (isUndefined(ctx.depth)) ctx.depth = 2; - if (isUndefined(ctx.colors)) ctx.colors = false; - if (isUndefined(ctx.customInspect)) ctx.customInspect = true; - if (ctx.colors) ctx.stylize = stylizeWithColor; - return formatValue(ctx, obj, ctx.depth); - } - exports.inspect = inspect; - - - // http://en.wikipedia.org/wiki/ANSI_escape_code#graphics - inspect.colors = { - 'bold' : [1, 22], - 'italic' : [3, 23], - 'underline' : [4, 24], - 'inverse' : [7, 27], - 'white' : [37, 39], - 'grey' : [90, 39], - 'black' : [30, 39], - 'blue' : [34, 39], - 'cyan' : [36, 39], - 'green' : [32, 39], - 'magenta' : [35, 39], - 'red' : [31, 39], - 'yellow' : [33, 39] - }; - - // Don't use 'blue' not visible on cmd.exe - inspect.styles = { - 'special': 'cyan', - 'number': 'yellow', - 'boolean': 'yellow', - 'undefined': 'grey', - 'null': 'bold', - 'string': 'green', - 'date': 'magenta', - // "name": intentionally not styling - 'regexp': 'red' - }; - - - function stylizeWithColor(str, styleType) { - var style = inspect.styles[styleType]; - - if (style) { - return '\u001b[' + inspect.colors[style][0] + 'm' + str + - '\u001b[' + inspect.colors[style][1] + 'm'; - } else { - return str; - } - } - - - function stylizeNoColor(str, styleType) { - return str; - } - - - function arrayToHash(array) { - var hash = {}; - - array.forEach(function(val, idx) { - hash[val] = true; - }); - - return hash; - } - - - function formatValue(ctx, value, recurseTimes) { - // Provide a hook for user-specified inspect functions. - // Check that value is an object with an inspect function on it - if (ctx.customInspect && - value && - isFunction(value.inspect) && - // Filter out the util module, it's inspect function is special - value.inspect !== exports.inspect && - // Also filter out any prototype objects using the circular check. - !(value.constructor && value.constructor.prototype === value)) { - var ret = value.inspect(recurseTimes, ctx); - if (!isString(ret)) { - ret = formatValue(ctx, ret, recurseTimes); - } - return ret; - } - - // Primitive types cannot have properties - var primitive = formatPrimitive(ctx, value); - if (primitive) { - return primitive; - } - - // Look up the keys of the object. - var keys = Object.keys(value); - var visibleKeys = arrayToHash(keys); - - if (ctx.showHidden) { - keys = Object.getOwnPropertyNames(value); - } - - // IE doesn't make error fields non-enumerable - // http://msdn.microsoft.com/en-us/library/ie/dww52sbt(v=vs.94).aspx - if (isError(value) - && (keys.indexOf('message') >= 0 || keys.indexOf('description') >= 0)) { - return formatError(value); - } - - // Some type of object without properties can be shortcutted. - if (keys.length === 0) { - if (isFunction(value)) { - var name = value.name ? ': ' + value.name : ''; - return ctx.stylize('[Function' + name + ']', 'special'); - } - if (isRegExp(value)) { - return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp'); - } - if (isDate(value)) { - return ctx.stylize(Date.prototype.toString.call(value), 'date'); - } - if (isError(value)) { - return formatError(value); - } - } - - var base = '', array = false, braces = ['{', '}']; - - // Make Array say that they are Array - if (isArray(value)) { - array = true; - braces = ['[', ']']; - } - - // Make functions say that they are functions - if (isFunction(value)) { - var n = value.name ? ': ' + value.name : ''; - base = ' [Function' + n + ']'; - } - - // Make RegExps say that they are RegExps - if (isRegExp(value)) { - base = ' ' + RegExp.prototype.toString.call(value); - } - - // Make dates with properties first say the date - if (isDate(value)) { - base = ' ' + Date.prototype.toUTCString.call(value); - } - - // Make error with message first say the error - if (isError(value)) { - base = ' ' + formatError(value); - } - - if (keys.length === 0 && (!array || value.length == 0)) { - return braces[0] + base + braces[1]; - } - - if (recurseTimes < 0) { - if (isRegExp(value)) { - return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp'); - } else { - return ctx.stylize('[Object]', 'special'); - } - } - - ctx.seen.push(value); - - var output; - if (array) { - output = formatArray(ctx, value, recurseTimes, visibleKeys, keys); - } else { - output = keys.map(function(key) { - return formatProperty(ctx, value, recurseTimes, visibleKeys, key, array); - }); - } - - ctx.seen.pop(); - - return reduceToSingleString(output, base, braces); - } - - - function formatPrimitive(ctx, value) { - if (isUndefined(value)) - return ctx.stylize('undefined', 'undefined'); - if (isString(value)) { - var simple = '\'' + JSON.stringify(value).replace(/^"|"$/g, '') - .replace(/'/g, "\\'") - .replace(/\\"/g, '"') + '\''; - return ctx.stylize(simple, 'string'); - } - if (isNumber(value)) - return ctx.stylize('' + value, 'number'); - if (isBoolean(value)) - return ctx.stylize('' + value, 'boolean'); - // For some reason typeof null is "object", so special case here. - if (isNull(value)) - return ctx.stylize('null', 'null'); - } - - - function formatError(value) { - return '[' + Error.prototype.toString.call(value) + ']'; - } - - - function formatArray(ctx, value, recurseTimes, visibleKeys, keys) { - var output = []; - for (var i = 0, l = value.length; i < l; ++i) { - if (hasOwnProperty(value, String(i))) { - output.push(formatProperty(ctx, value, recurseTimes, visibleKeys, - String(i), true)); - } else { - output.push(''); - } - } - keys.forEach(function(key) { - if (!key.match(/^\d+$/)) { - output.push(formatProperty(ctx, value, recurseTimes, visibleKeys, - key, true)); - } - }); - return output; - } - - - function formatProperty(ctx, value, recurseTimes, visibleKeys, key, array) { - var name, str, desc; - desc = Object.getOwnPropertyDescriptor(value, key) || { value: value[key] }; - if (desc.get) { - if (desc.set) { - str = ctx.stylize('[Getter/Setter]', 'special'); - } else { - str = ctx.stylize('[Getter]', 'special'); - } - } else { - if (desc.set) { - str = ctx.stylize('[Setter]', 'special'); - } - } - if (!hasOwnProperty(visibleKeys, key)) { - name = '[' + key + ']'; - } - if (!str) { - if (ctx.seen.indexOf(desc.value) < 0) { - if (isNull(recurseTimes)) { - str = formatValue(ctx, desc.value, null); - } else { - str = formatValue(ctx, desc.value, recurseTimes - 1); - } - if (str.indexOf('\n') > -1) { - if (array) { - str = str.split('\n').map(function(line) { - return ' ' + line; - }).join('\n').substr(2); - } else { - str = '\n' + str.split('\n').map(function(line) { - return ' ' + line; - }).join('\n'); - } - } - } else { - str = ctx.stylize('[Circular]', 'special'); - } - } - if (isUndefined(name)) { - if (array && key.match(/^\d+$/)) { - return str; - } - name = JSON.stringify('' + key); - if (name.match(/^"([a-zA-Z_][a-zA-Z_0-9]*)"$/)) { - name = name.substr(1, name.length - 2); - name = ctx.stylize(name, 'name'); - } else { - name = name.replace(/'/g, "\\'") - .replace(/\\"/g, '"') - .replace(/(^"|"$)/g, "'"); - name = ctx.stylize(name, 'string'); - } - } - - return name + ': ' + str; - } - - - function reduceToSingleString(output, base, braces) { - var numLinesEst = 0; - var length = output.reduce(function(prev, cur) { - numLinesEst++; - if (cur.indexOf('\n') >= 0) numLinesEst++; - return prev + cur.replace(/\u001b\[\d\d?m/g, '').length + 1; - }, 0); - - if (length > 60) { - return braces[0] + - (base === '' ? '' : base + '\n ') + - ' ' + - output.join(',\n ') + - ' ' + - braces[1]; - } - - return braces[0] + base + ' ' + output.join(', ') + ' ' + braces[1]; - } - - - // NOTE: These type checking functions intentionally don't use `instanceof` - // because it is fragile and can be easily faked with `Object.create()`. - function isArray(ar) { - return Array.isArray(ar); - } - exports.isArray = isArray; - - function isBoolean(arg) { - return typeof arg === 'boolean'; - } - exports.isBoolean = isBoolean; - - function isNull(arg) { - return arg === null; - } - exports.isNull = isNull; - - function isNullOrUndefined(arg) { - return arg == null; - } - exports.isNullOrUndefined = isNullOrUndefined; - - function isNumber(arg) { - return typeof arg === 'number'; - } - exports.isNumber = isNumber; - - function isString(arg) { - return typeof arg === 'string'; - } - exports.isString = isString; - - function isSymbol(arg) { - return typeof arg === 'symbol'; - } - exports.isSymbol = isSymbol; - - function isUndefined(arg) { - return arg === void 0; - } - exports.isUndefined = isUndefined; - - function isRegExp(re) { - return isObject(re) && objectToString(re) === '[object RegExp]'; - } - exports.isRegExp = isRegExp; - - function isObject(arg) { - return typeof arg === 'object' && arg !== null; - } - exports.isObject = isObject; - - function isDate(d) { - return isObject(d) && objectToString(d) === '[object Date]'; - } - exports.isDate = isDate; - - function isError(e) { - return isObject(e) && - (objectToString(e) === '[object Error]' || e instanceof Error); - } - exports.isError = isError; - - function isFunction(arg) { - return typeof arg === 'function'; - } - exports.isFunction = isFunction; - - function isPrimitive(arg) { - return arg === null || - typeof arg === 'boolean' || - typeof arg === 'number' || - typeof arg === 'string' || - typeof arg === 'symbol' || // ES6 symbol - typeof arg === 'undefined'; - } - exports.isPrimitive = isPrimitive; - - exports.isBuffer = __webpack_require__(321); - - function objectToString(o) { - return Object.prototype.toString.call(o); - } - - - function pad(n) { - return n < 10 ? '0' + n.toString(10) : n.toString(10); - } - - - var months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', - 'Oct', 'Nov', 'Dec']; - - // 26 Feb 16:19:34 - function timestamp() { - var d = new Date(); - var time = [pad(d.getHours()), - pad(d.getMinutes()), - pad(d.getSeconds())].join(':'); - return [d.getDate(), months[d.getMonth()], time].join(' '); - } - - - // log is just a thin wrapper to console.log that prepends a timestamp - exports.log = function() { - console.log('%s - %s', timestamp(), exports.format.apply(exports, arguments)); - }; - - - /** - * Inherit the prototype methods from one constructor into another. - * - * The Function.prototype.inherits from lang.js rewritten as a standalone - * function (not on Function.prototype). NOTE: If this file is to be loaded - * during bootstrapping this function needs to be rewritten using some native - * functions as prototype setup using normal JavaScript does not work as - * expected during bootstrapping (see mirror.js in r114903). - * - * @param {function} ctor Constructor function which needs to inherit the - * prototype. - * @param {function} superCtor Constructor function to inherit prototype from. - */ - exports.inherits = __webpack_require__(322); - - exports._extend = function(origin, add) { - // Don't do anything if add isn't an object - if (!add || !isObject(add)) return origin; - - var keys = Object.keys(add); - var i = keys.length; - while (i--) { - origin[keys[i]] = add[keys[i]]; - } - return origin; - }; - - function hasOwnProperty(obj, prop) { - return Object.prototype.hasOwnProperty.call(obj, prop); - } - - /* WEBPACK VAR INJECTION */}.call(exports, (function() { return this; }()), __webpack_require__(294))) - -/***/ }, -/* 321 */ -/***/ function(module, exports) { - - module.exports = function isBuffer(arg) { - return arg && typeof arg === 'object' - && typeof arg.copy === 'function' - && typeof arg.fill === 'function' - && typeof arg.readUInt8 === 'function'; - } - -/***/ }, -/* 322 */ -/***/ function(module, exports) { - - if (typeof Object.create === 'function') { - // implementation from standard node.js 'util' module - module.exports = function inherits(ctor, superCtor) { - ctor.super_ = superCtor - ctor.prototype = Object.create(superCtor.prototype, { - constructor: { - value: ctor, - enumerable: false, - writable: true, - configurable: true - } - }); - }; - } else { - // old school shim for old browsers - module.exports = function inherits(ctor, superCtor) { - ctor.super_ = superCtor - var TempCtor = function () {} - TempCtor.prototype = superCtor.prototype - ctor.prototype = new TempCtor() - ctor.prototype.constructor = ctor - } - } - - -/***/ }, -/* 323 */ -/***/ function(module, exports, __webpack_require__) { - - /* WEBPACK VAR INJECTION */(function(Buffer) {"use strict"; - - var writeIEEE754 = __webpack_require__(304).writeIEEE754, - readIEEE754 = __webpack_require__(304).readIEEE754, - Long = __webpack_require__(306).Long, - Map = __webpack_require__(305), - Double = __webpack_require__(307).Double, - Timestamp = __webpack_require__(308).Timestamp, - ObjectID = __webpack_require__(309).ObjectID, - Symbol = __webpack_require__(311).Symbol, - Code = __webpack_require__(313).Code, - BSONRegExp = __webpack_require__(310).BSONRegExp, - Int32 = __webpack_require__(312).Int32, - MinKey = __webpack_require__(315).MinKey, - MaxKey = __webpack_require__(316).MaxKey, - Decimal128 = __webpack_require__(314), - DBRef = __webpack_require__(317).DBRef, - Binary = __webpack_require__(318).Binary; - - try { - var _Buffer = Uint8Array; - } catch (e) { - var _Buffer = Buffer; - } - - var regexp = /\x00/; - - // To ensure that 0.4 of node works correctly - var isDate = function isDate(d) { - return typeof d === 'object' && Object.prototype.toString.call(d) === '[object Date]'; - }; - - var isRegExp = function isRegExp(d) { - return Object.prototype.toString.call(d) === '[object RegExp]'; - }; - - var serializeString = function (buffer, key, value, index, isArray) { - // Encode String type - buffer[index++] = BSON.BSON_DATA_STRING; - // Number of written bytes - var numberOfWrittenBytes = !isArray ? buffer.write(key, index, 'utf8') : buffer.write(key, index, 'ascii'); - // Encode the name - index = index + numberOfWrittenBytes + 1; - buffer[index - 1] = 0; - // Write the string - var size = buffer.write(value, index + 4, 'utf8'); - // Write the size of the string to buffer - buffer[index + 3] = size + 1 >> 24 & 0xff; - buffer[index + 2] = size + 1 >> 16 & 0xff; - buffer[index + 1] = size + 1 >> 8 & 0xff; - buffer[index] = size + 1 & 0xff; - // Update index - index = index + 4 + size; - // Write zero - buffer[index++] = 0; - return index; - }; - - var serializeNumber = function (buffer, key, value, index, isArray) { - // We have an integer value - if (Math.floor(value) === value && value >= BSON.JS_INT_MIN && value <= BSON.JS_INT_MAX) { - // If the value fits in 32 bits encode as int, if it fits in a double - // encode it as a double, otherwise long - if (value >= BSON.BSON_INT32_MIN && value <= BSON.BSON_INT32_MAX) { - // Set int type 32 bits or less - buffer[index++] = BSON.BSON_DATA_INT; - // Number of written bytes - var numberOfWrittenBytes = !isArray ? buffer.write(key, index, 'utf8') : buffer.write(key, index, 'ascii'); - // Encode the name - index = index + numberOfWrittenBytes; - buffer[index++] = 0; - // Write the int value - buffer[index++] = value & 0xff; - buffer[index++] = value >> 8 & 0xff; - buffer[index++] = value >> 16 & 0xff; - buffer[index++] = value >> 24 & 0xff; - } else if (value >= BSON.JS_INT_MIN && value <= BSON.JS_INT_MAX) { - // Encode as double - buffer[index++] = BSON.BSON_DATA_NUMBER; - // Number of written bytes - var numberOfWrittenBytes = !isArray ? buffer.write(key, index, 'utf8') : buffer.write(key, index, 'ascii'); - // Encode the name - index = index + numberOfWrittenBytes; - buffer[index++] = 0; - // Write float - writeIEEE754(buffer, value, index, 'little', 52, 8); - // Ajust index - index = index + 8; - } else { - // Set long type - buffer[index++] = BSON.BSON_DATA_LONG; - // Number of written bytes - var numberOfWrittenBytes = !isArray ? buffer.write(key, index, 'utf8') : buffer.write(key, index, 'ascii'); - // Encode the name - index = index + numberOfWrittenBytes; - buffer[index++] = 0; - var longVal = Long.fromNumber(value); - var lowBits = longVal.getLowBits(); - var highBits = longVal.getHighBits(); - // Encode low bits - buffer[index++] = lowBits & 0xff; - buffer[index++] = lowBits >> 8 & 0xff; - buffer[index++] = lowBits >> 16 & 0xff; - buffer[index++] = lowBits >> 24 & 0xff; - // Encode high bits - buffer[index++] = highBits & 0xff; - buffer[index++] = highBits >> 8 & 0xff; - buffer[index++] = highBits >> 16 & 0xff; - buffer[index++] = highBits >> 24 & 0xff; - } - } else { - // Encode as double - buffer[index++] = BSON.BSON_DATA_NUMBER; - // Number of written bytes - var numberOfWrittenBytes = !isArray ? buffer.write(key, index, 'utf8') : buffer.write(key, index, 'ascii'); - // Encode the name - index = index + numberOfWrittenBytes; - buffer[index++] = 0; - // Write float - writeIEEE754(buffer, value, index, 'little', 52, 8); - // Ajust index - index = index + 8; - } - - return index; - }; - - var serializeUndefined = function (buffer, key, value, index, isArray) { - // Set long type - buffer[index++] = BSON.BSON_DATA_UNDEFINED; - // Number of written bytes - var numberOfWrittenBytes = !isArray ? buffer.write(key, index, 'utf8') : buffer.write(key, index, 'ascii'); - // Encode the name - index = index + numberOfWrittenBytes; - buffer[index++] = 0; - return index; - }; - - var serializeNull = function (buffer, key, value, index, isArray) { - // Set long type - buffer[index++] = BSON.BSON_DATA_NULL; - // Number of written bytes - var numberOfWrittenBytes = !isArray ? buffer.write(key, index, 'utf8') : buffer.write(key, index, 'ascii'); - // Encode the name - index = index + numberOfWrittenBytes; - buffer[index++] = 0; - return index; - }; - - var serializeBoolean = function (buffer, key, value, index, isArray) { - // Write the type - buffer[index++] = BSON.BSON_DATA_BOOLEAN; - // Number of written bytes - var numberOfWrittenBytes = !isArray ? buffer.write(key, index, 'utf8') : buffer.write(key, index, 'ascii'); - // Encode the name - index = index + numberOfWrittenBytes; - buffer[index++] = 0; - // Encode the boolean value - buffer[index++] = value ? 1 : 0; - return index; - }; - - var serializeDate = function (buffer, key, value, index, isArray) { - // Write the type - buffer[index++] = BSON.BSON_DATA_DATE; - // Number of written bytes - var numberOfWrittenBytes = !isArray ? buffer.write(key, index, 'utf8') : buffer.write(key, index, 'ascii'); - // Encode the name - index = index + numberOfWrittenBytes; - buffer[index++] = 0; - - // Write the date - var dateInMilis = Long.fromNumber(value.getTime()); - var lowBits = dateInMilis.getLowBits(); - var highBits = dateInMilis.getHighBits(); - // Encode low bits - buffer[index++] = lowBits & 0xff; - buffer[index++] = lowBits >> 8 & 0xff; - buffer[index++] = lowBits >> 16 & 0xff; - buffer[index++] = lowBits >> 24 & 0xff; - // Encode high bits - buffer[index++] = highBits & 0xff; - buffer[index++] = highBits >> 8 & 0xff; - buffer[index++] = highBits >> 16 & 0xff; - buffer[index++] = highBits >> 24 & 0xff; - return index; - }; - - var serializeRegExp = function (buffer, key, value, index, isArray) { - // Write the type - buffer[index++] = BSON.BSON_DATA_REGEXP; - // Number of written bytes - var numberOfWrittenBytes = !isArray ? buffer.write(key, index, 'utf8') : buffer.write(key, index, 'ascii'); - // Encode the name - index = index + numberOfWrittenBytes; - buffer[index++] = 0; - if (value.source && value.source.match(regexp) != null) { - throw Error("value " + value.source + " must not contain null bytes"); - } - // Adjust the index - index = index + buffer.write(value.source, index, 'utf8'); - // Write zero - buffer[index++] = 0x00; - // Write the parameters - if (value.global) buffer[index++] = 0x73; // s - if (value.ignoreCase) buffer[index++] = 0x69; // i - if (value.multiline) buffer[index++] = 0x6d; // m - // Add ending zero - buffer[index++] = 0x00; - return index; - }; - - var serializeBSONRegExp = function (buffer, key, value, index, isArray) { - // Write the type - buffer[index++] = BSON.BSON_DATA_REGEXP; - // Number of written bytes - var numberOfWrittenBytes = !isArray ? buffer.write(key, index, 'utf8') : buffer.write(key, index, 'ascii'); - // Encode the name - index = index + numberOfWrittenBytes; - buffer[index++] = 0; - - // Check the pattern for 0 bytes - if (value.pattern.match(regexp) != null) { - // The BSON spec doesn't allow keys with null bytes because keys are - // null-terminated. - throw Error("pattern " + value.pattern + " must not contain null bytes"); - } - - // Adjust the index - index = index + buffer.write(value.pattern, index, 'utf8'); - // Write zero - buffer[index++] = 0x00; - // Write the options - index = index + buffer.write(value.options.split('').sort().join(''), index, 'utf8'); - // Add ending zero - buffer[index++] = 0x00; - return index; - }; - - var serializeMinMax = function (buffer, key, value, index, isArray) { - // Write the type of either min or max key - if (value === null) { - buffer[index++] = BSON.BSON_DATA_NULL; - } else if (value instanceof MinKey) { - buffer[index++] = BSON.BSON_DATA_MIN_KEY; - } else { - buffer[index++] = BSON.BSON_DATA_MAX_KEY; - } - - // Number of written bytes - var numberOfWrittenBytes = !isArray ? buffer.write(key, index, 'utf8') : buffer.write(key, index, 'ascii'); - // Encode the name - index = index + numberOfWrittenBytes; - buffer[index++] = 0; - return index; - }; - - var serializeObjectId = function (buffer, key, value, index, isArray) { - // Write the type - buffer[index++] = BSON.BSON_DATA_OID; - // Number of written bytes - var numberOfWrittenBytes = !isArray ? buffer.write(key, index, 'utf8') : buffer.write(key, index, 'ascii'); - - // Encode the name - index = index + numberOfWrittenBytes; - buffer[index++] = 0; - - // Write the objectId into the shared buffer - if (typeof value.id == 'string') { - buffer.write(value.id, index, 'binary'); - } else if (value.id && value.id.copy) { - value.id.copy(buffer, index, 0, 12); - } else { - throw new Error('object [' + JSON.stringify(value) + "] is not a valid ObjectId"); - } - - // Ajust index - return index + 12; - }; - - var serializeBuffer = function (buffer, key, value, index, isArray) { - // Write the type - buffer[index++] = BSON.BSON_DATA_BINARY; - // Number of written bytes - var numberOfWrittenBytes = !isArray ? buffer.write(key, index, 'utf8') : buffer.write(key, index, 'ascii'); - // Encode the name - index = index + numberOfWrittenBytes; - buffer[index++] = 0; - // Get size of the buffer (current write point) - var size = value.length; - // Write the size of the string to buffer - buffer[index++] = size & 0xff; - buffer[index++] = size >> 8 & 0xff; - buffer[index++] = size >> 16 & 0xff; - buffer[index++] = size >> 24 & 0xff; - // Write the default subtype - buffer[index++] = BSON.BSON_BINARY_SUBTYPE_DEFAULT; - // Copy the content form the binary field to the buffer - value.copy(buffer, index, 0, size); - // Adjust the index - index = index + size; - return index; - }; - - var serializeObject = function (buffer, key, value, index, checkKeys, depth, serializeFunctions, ignoreUndefined, isArray, path) { - for (var i = 0; i < path.length; i++) { - if (path[i] === value) throw new Error('cyclic dependency detected'); - } - - // Push value to stack - path.push(value); - // Write the type - buffer[index++] = Array.isArray(value) ? BSON.BSON_DATA_ARRAY : BSON.BSON_DATA_OBJECT; - // Number of written bytes - var numberOfWrittenBytes = !isArray ? buffer.write(key, index, 'utf8') : buffer.write(key, index, 'ascii'); - // Encode the name - index = index + numberOfWrittenBytes; - buffer[index++] = 0; - var endIndex = serializeInto(buffer, value, checkKeys, index, depth + 1, serializeFunctions, ignoreUndefined, path); - // Pop stack - path.pop(); - // Write size - var size = endIndex - index; - return endIndex; - }; - - var serializeDecimal128 = function (buffer, key, value, index, isArray) { - buffer[index++] = BSON.BSON_DATA_DECIMAL128; - // Number of written bytes - var numberOfWrittenBytes = !isArray ? buffer.write(key, index, 'utf8') : buffer.write(key, index, 'ascii'); - // Encode the name - index = index + numberOfWrittenBytes; - buffer[index++] = 0; - // Write the data from the value - value.bytes.copy(buffer, index, 0, 16); - return index + 16; - }; - - var serializeLong = function (buffer, key, value, index, isArray) { - // Write the type - buffer[index++] = value._bsontype == 'Long' ? BSON.BSON_DATA_LONG : BSON.BSON_DATA_TIMESTAMP; - // Number of written bytes - var numberOfWrittenBytes = !isArray ? buffer.write(key, index, 'utf8') : buffer.write(key, index, 'ascii'); - // Encode the name - index = index + numberOfWrittenBytes; - buffer[index++] = 0; - // Write the date - var lowBits = value.getLowBits(); - var highBits = value.getHighBits(); - // Encode low bits - buffer[index++] = lowBits & 0xff; - buffer[index++] = lowBits >> 8 & 0xff; - buffer[index++] = lowBits >> 16 & 0xff; - buffer[index++] = lowBits >> 24 & 0xff; - // Encode high bits - buffer[index++] = highBits & 0xff; - buffer[index++] = highBits >> 8 & 0xff; - buffer[index++] = highBits >> 16 & 0xff; - buffer[index++] = highBits >> 24 & 0xff; - return index; - }; - - var serializeInt32 = function (buffer, key, value, index, isArray) { - // Set int type 32 bits or less - buffer[index++] = BSON.BSON_DATA_INT; - // Number of written bytes - var numberOfWrittenBytes = !isArray ? buffer.write(key, index, 'utf8') : buffer.write(key, index, 'ascii'); - // Encode the name - index = index + numberOfWrittenBytes; - buffer[index++] = 0; - // Write the int value - buffer[index++] = value & 0xff; - buffer[index++] = value >> 8 & 0xff; - buffer[index++] = value >> 16 & 0xff; - buffer[index++] = value >> 24 & 0xff; - return index; - }; - - var serializeDouble = function (buffer, key, value, index, isArray) { - // Encode as double - buffer[index++] = BSON.BSON_DATA_NUMBER; - // Number of written bytes - var numberOfWrittenBytes = !isArray ? buffer.write(key, index, 'utf8') : buffer.write(key, index, 'ascii'); - // Encode the name - index = index + numberOfWrittenBytes; - buffer[index++] = 0; - // Write float - writeIEEE754(buffer, value, index, 'little', 52, 8); - // Ajust index - index = index + 8; - return index; - }; - - var serializeFunction = function (buffer, key, value, index, checkKeys, depth, isArray) { - buffer[index++] = BSON.BSON_DATA_CODE; - // Number of written bytes - var numberOfWrittenBytes = !isArray ? buffer.write(key, index, 'utf8') : buffer.write(key, index, 'ascii'); - // Encode the name - index = index + numberOfWrittenBytes; - buffer[index++] = 0; - // Function string - var functionString = value.toString(); - // Write the string - var size = buffer.write(functionString, index + 4, 'utf8') + 1; - // Write the size of the string to buffer - buffer[index] = size & 0xff; - buffer[index + 1] = size >> 8 & 0xff; - buffer[index + 2] = size >> 16 & 0xff; - buffer[index + 3] = size >> 24 & 0xff; - // Update index - index = index + 4 + size - 1; - // Write zero - buffer[index++] = 0; - return index; - }; - - var serializeCode = function (buffer, key, value, index, checkKeys, depth, serializeFunctions, ignoreUndefined, isArray) { - if (value.scope && typeof value.scope == 'object') { - // Write the type - buffer[index++] = BSON.BSON_DATA_CODE_W_SCOPE; - // Number of written bytes - var numberOfWrittenBytes = !isArray ? buffer.write(key, index, 'utf8') : buffer.write(key, index, 'ascii'); - // Encode the name - index = index + numberOfWrittenBytes; - buffer[index++] = 0; - - // Starting index - var startIndex = index; - - // Serialize the function - // Get the function string - var functionString = typeof value.code == 'string' ? value.code : value.code.toString(); - // Index adjustment - index = index + 4; - // Write string into buffer - var codeSize = buffer.write(functionString, index + 4, 'utf8') + 1; - // Write the size of the string to buffer - buffer[index] = codeSize & 0xff; - buffer[index + 1] = codeSize >> 8 & 0xff; - buffer[index + 2] = codeSize >> 16 & 0xff; - buffer[index + 3] = codeSize >> 24 & 0xff; - // Write end 0 - buffer[index + 4 + codeSize - 1] = 0; - // Write the - index = index + codeSize + 4; - - // - // Serialize the scope value - var endIndex = serializeInto(buffer, value.scope, checkKeys, index, depth + 1, serializeFunctions, ignoreUndefined); - index = endIndex - 1; - - // Writ the total - var totalSize = endIndex - startIndex; - - // Write the total size of the object - buffer[startIndex++] = totalSize & 0xff; - buffer[startIndex++] = totalSize >> 8 & 0xff; - buffer[startIndex++] = totalSize >> 16 & 0xff; - buffer[startIndex++] = totalSize >> 24 & 0xff; - // Write trailing zero - buffer[index++] = 0; - } else { - buffer[index++] = BSON.BSON_DATA_CODE; - // Number of written bytes - var numberOfWrittenBytes = !isArray ? buffer.write(key, index, 'utf8') : buffer.write(key, index, 'ascii'); - // Encode the name - index = index + numberOfWrittenBytes; - buffer[index++] = 0; - // Function string - var functionString = value.code.toString(); - // Write the string - var size = buffer.write(functionString, index + 4, 'utf8') + 1; - // Write the size of the string to buffer - buffer[index] = size & 0xff; - buffer[index + 1] = size >> 8 & 0xff; - buffer[index + 2] = size >> 16 & 0xff; - buffer[index + 3] = size >> 24 & 0xff; - // Update index - index = index + 4 + size - 1; - // Write zero - buffer[index++] = 0; - } - - return index; - }; - - var serializeBinary = function (buffer, key, value, index, isArray) { - // Write the type - buffer[index++] = BSON.BSON_DATA_BINARY; - // Number of written bytes - var numberOfWrittenBytes = !isArray ? buffer.write(key, index, 'utf8') : buffer.write(key, index, 'ascii'); - // Encode the name - index = index + numberOfWrittenBytes; - buffer[index++] = 0; - // Extract the buffer - var data = value.value(true); - // Calculate size - var size = value.position; - // Add the deprecated 02 type 4 bytes of size to total - if (value.sub_type == Binary.SUBTYPE_BYTE_ARRAY) size = size + 4; - // Write the size of the string to buffer - buffer[index++] = size & 0xff; - buffer[index++] = size >> 8 & 0xff; - buffer[index++] = size >> 16 & 0xff; - buffer[index++] = size >> 24 & 0xff; - // Write the subtype to the buffer - buffer[index++] = value.sub_type; - - // If we have binary type 2 the 4 first bytes are the size - if (value.sub_type == Binary.SUBTYPE_BYTE_ARRAY) { - size = size - 4; - buffer[index++] = size & 0xff; - buffer[index++] = size >> 8 & 0xff; - buffer[index++] = size >> 16 & 0xff; - buffer[index++] = size >> 24 & 0xff; - } - - // Write the data to the object - data.copy(buffer, index, 0, value.position); - // Adjust the index - index = index + value.position; - return index; - }; - - var serializeSymbol = function (buffer, key, value, index, isArray) { - // Write the type - buffer[index++] = BSON.BSON_DATA_SYMBOL; - // Number of written bytes - var numberOfWrittenBytes = !isArray ? buffer.write(key, index, 'utf8') : buffer.write(key, index, 'ascii'); - // Encode the name - index = index + numberOfWrittenBytes; - buffer[index++] = 0; - // Write the string - var size = buffer.write(value.value, index + 4, 'utf8') + 1; - // Write the size of the string to buffer - buffer[index] = size & 0xff; - buffer[index + 1] = size >> 8 & 0xff; - buffer[index + 2] = size >> 16 & 0xff; - buffer[index + 3] = size >> 24 & 0xff; - // Update index - index = index + 4 + size - 1; - // Write zero - buffer[index++] = 0x00; - return index; - }; - - var serializeDBRef = function (buffer, key, value, index, depth, serializeFunctions, isArray) { - // Write the type - buffer[index++] = BSON.BSON_DATA_OBJECT; - // Number of written bytes - var numberOfWrittenBytes = !isArray ? buffer.write(key, index, 'utf8') : buffer.write(key, index, 'ascii'); - - // Encode the name - index = index + numberOfWrittenBytes; - buffer[index++] = 0; - - var startIndex = index; - var endIndex; - - // Serialize object - if (null != value.db) { - endIndex = serializeInto(buffer, { - '$ref': value.namespace, - '$id': value.oid, - '$db': value.db - }, false, index, depth + 1, serializeFunctions); - } else { - endIndex = serializeInto(buffer, { - '$ref': value.namespace, - '$id': value.oid - }, false, index, depth + 1, serializeFunctions); - } - - // Calculate object size - var size = endIndex - startIndex; - // Write the size - buffer[startIndex++] = size & 0xff; - buffer[startIndex++] = size >> 8 & 0xff; - buffer[startIndex++] = size >> 16 & 0xff; - buffer[startIndex++] = size >> 24 & 0xff; - // Set index - return endIndex; - }; - - var serializeInto = function serializeInto(buffer, object, checkKeys, startingIndex, depth, serializeFunctions, ignoreUndefined, path) { - startingIndex = startingIndex || 0; - path = path || []; - - // Push the object to the path - path.push(object); - - // Start place to serialize into - var index = startingIndex + 4; - var self = this; - - // Special case isArray - if (Array.isArray(object)) { - // Get object keys - for (var i = 0; i < object.length; i++) { - var key = "" + i; - var value = object[i]; - - // Is there an override value - if (value && value.toBSON) { - if (typeof value.toBSON != 'function') throw new Error("toBSON is not a function"); - value = value.toBSON(); - } - - var type = typeof value; - if (type == 'string') { - index = serializeString(buffer, key, value, index, true); - } else if (type == 'number') { - index = serializeNumber(buffer, key, value, index, true); - } else if (type == 'boolean') { - index = serializeBoolean(buffer, key, value, index, true); - } else if (value instanceof Date || isDate(value)) { - index = serializeDate(buffer, key, value, index, true); - } else if (value === undefined) { - index = serializeNull(buffer, key, value, index, true); - } else if (value === null) { - index = serializeNull(buffer, key, value, index, true); - } else if (value['_bsontype'] == 'ObjectID') { - index = serializeObjectId(buffer, key, value, index, true); - } else if (Buffer.isBuffer(value)) { - index = serializeBuffer(buffer, key, value, index, true); - } else if (value instanceof RegExp || isRegExp(value)) { - index = serializeRegExp(buffer, key, value, index, true); - } else if (type == 'object' && value['_bsontype'] == null) { - index = serializeObject(buffer, key, value, index, checkKeys, depth, serializeFunctions, ignoreUndefined, true, path); - } else if (type == 'object' && value['_bsontype'] == 'Decimal128') { - index = serializeDecimal128(buffer, key, value, index, true); - } else if (value['_bsontype'] == 'Long' || value['_bsontype'] == 'Timestamp') { - index = serializeLong(buffer, key, value, index, true); - } else if (value['_bsontype'] == 'Double') { - index = serializeDouble(buffer, key, value, index, true); - } else if (typeof value == 'function' && serializeFunctions) { - index = serializeFunction(buffer, key, value, index, checkKeys, depth, serializeFunctions, true); - } else if (value['_bsontype'] == 'Code') { - index = serializeCode(buffer, key, value, index, checkKeys, depth, serializeFunctions, ignoreUndefined, true); - } else if (value['_bsontype'] == 'Binary') { - index = serializeBinary(buffer, key, value, index, true); - } else if (value['_bsontype'] == 'Symbol') { - index = serializeSymbol(buffer, key, value, index, true); - } else if (value['_bsontype'] == 'DBRef') { - index = serializeDBRef(buffer, key, value, index, depth, serializeFunctions, true); - } else if (value['_bsontype'] == 'BSONRegExp') { - index = serializeBSONRegExp(buffer, key, value, index, true); - } else if (value['_bsontype'] == 'Int32') { - index = serializeInt32(buffer, key, value, index, true); - } else if (value['_bsontype'] == 'MinKey' || value['_bsontype'] == 'MaxKey') { - index = serializeMinMax(buffer, key, value, index, true); - } - } - } else if (object instanceof Map) { - var iterator = object.entries(); - var done = false; - - while (!done) { - // Unpack the next entry - var entry = iterator.next(); - done = entry.done; - // Are we done, then skip and terminate - if (done) continue; - - // Get the entry values - var key = entry.value[0]; - var value = entry.value[1]; - - // Check the type of the value - var type = typeof value; - - // Check the key and throw error if it's illegal - if (key != '$db' && key != '$ref' && key != '$id') { - if (key.match(regexp) != null) { - // The BSON spec doesn't allow keys with null bytes because keys are - // null-terminated. - throw Error("key " + key + " must not contain null bytes"); - } - - if (checkKeys) { - if ('$' == key[0]) { - throw Error("key " + key + " must not start with '$'"); - } else if (!!~key.indexOf('.')) { - throw Error("key " + key + " must not contain '.'"); - } - } - } - - if (type == 'string') { - index = serializeString(buffer, key, value, index); - } else if (type == 'number') { - index = serializeNumber(buffer, key, value, index); - } else if (type == 'boolean') { - index = serializeBoolean(buffer, key, value, index); - } else if (value instanceof Date || isDate(value)) { - index = serializeDate(buffer, key, value, index); - } else if (value === undefined && ignoreUndefined == true) {} else if (value === undefined) { - index = serializeUndefined(buffer, key, value, index); - } else if (value === null) { - index = serializeNull(buffer, key, value, index); - } else if (value['_bsontype'] == 'ObjectID') { - index = serializeObjectId(buffer, key, value, index); - } else if (Buffer.isBuffer(value)) { - index = serializeBuffer(buffer, key, value, index); - } else if (value instanceof RegExp || isRegExp(value)) { - index = serializeRegExp(buffer, key, value, index); - } else if (type == 'object' && value['_bsontype'] == null) { - index = serializeObject(buffer, key, value, index, checkKeys, depth, serializeFunctions, ignoreUndefined, false, path); - } else if (type == 'object' && value['_bsontype'] == 'Decimal128') { - index = serializeDecimal128(buffer, key, value, index); - } else if (value['_bsontype'] == 'Long' || value['_bsontype'] == 'Timestamp') { - index = serializeLong(buffer, key, value, index); - } else if (value['_bsontype'] == 'Double') { - index = serializeDouble(buffer, key, value, index); - } else if (value['_bsontype'] == 'Code') { - index = serializeCode(buffer, key, value, index, checkKeys, depth, serializeFunctions, ignoreUndefined); - } else if (typeof value == 'function' && serializeFunctions) { - index = serializeFunction(buffer, key, value, index, checkKeys, depth, serializeFunctions); - } else if (value['_bsontype'] == 'Binary') { - index = serializeBinary(buffer, key, value, index); - } else if (value['_bsontype'] == 'Symbol') { - index = serializeSymbol(buffer, key, value, index); - } else if (value['_bsontype'] == 'DBRef') { - index = serializeDBRef(buffer, key, value, index, depth, serializeFunctions); - } else if (value['_bsontype'] == 'BSONRegExp') { - index = serializeBSONRegExp(buffer, key, value, index); - } else if (value['_bsontype'] == 'Int32') { - index = serializeInt32(buffer, key, value, index); - } else if (value['_bsontype'] == 'MinKey' || value['_bsontype'] == 'MaxKey') { - index = serializeMinMax(buffer, key, value, index); - } - } - } else { - // Did we provide a custom serialization method - if (object.toBSON) { - if (typeof object.toBSON != 'function') throw new Error("toBSON is not a function"); - object = object.toBSON(); - if (object != null && typeof object != 'object') throw new Error("toBSON function did not return an object"); - } - - // Iterate over all the keys - for (var key in object) { - var value = object[key]; - // Is there an override value - if (value && value.toBSON) { - if (typeof value.toBSON != 'function') throw new Error("toBSON is not a function"); - value = value.toBSON(); - } - - // Check the type of the value - var type = typeof value; - - // Check the key and throw error if it's illegal - if (key != '$db' && key != '$ref' && key != '$id') { - if (key.match(regexp) != null) { - // The BSON spec doesn't allow keys with null bytes because keys are - // null-terminated. - throw Error("key " + key + " must not contain null bytes"); - } - - if (checkKeys) { - if ('$' == key[0]) { - throw Error("key " + key + " must not start with '$'"); - } else if (!!~key.indexOf('.')) { - throw Error("key " + key + " must not contain '.'"); - } - } - } - - if (type == 'string') { - index = serializeString(buffer, key, value, index); - } else if (type == 'number') { - index = serializeNumber(buffer, key, value, index); - } else if (type == 'boolean') { - index = serializeBoolean(buffer, key, value, index); - } else if (value instanceof Date || isDate(value)) { - index = serializeDate(buffer, key, value, index); - } else if (value === undefined && ignoreUndefined == true) {} else if (value === undefined) { - index = serializeUndefined(buffer, key, value, index); - } else if (value === null) { - index = serializeNull(buffer, key, value, index); - } else if (value['_bsontype'] == 'ObjectID') { - index = serializeObjectId(buffer, key, value, index); - } else if (Buffer.isBuffer(value)) { - index = serializeBuffer(buffer, key, value, index); - } else if (value instanceof RegExp || isRegExp(value)) { - index = serializeRegExp(buffer, key, value, index); - } else if (type == 'object' && value['_bsontype'] == null) { - index = serializeObject(buffer, key, value, index, checkKeys, depth, serializeFunctions, ignoreUndefined, false, path); - } else if (type == 'object' && value['_bsontype'] == 'Decimal128') { - index = serializeDecimal128(buffer, key, value, index); - } else if (value['_bsontype'] == 'Long' || value['_bsontype'] == 'Timestamp') { - index = serializeLong(buffer, key, value, index); - } else if (value['_bsontype'] == 'Double') { - index = serializeDouble(buffer, key, value, index); - } else if (value['_bsontype'] == 'Code') { - index = serializeCode(buffer, key, value, index, checkKeys, depth, serializeFunctions, ignoreUndefined); - } else if (typeof value == 'function' && serializeFunctions) { - index = serializeFunction(buffer, key, value, index, checkKeys, depth, serializeFunctions); - } else if (value['_bsontype'] == 'Binary') { - index = serializeBinary(buffer, key, value, index); - } else if (value['_bsontype'] == 'Symbol') { - index = serializeSymbol(buffer, key, value, index); - } else if (value['_bsontype'] == 'DBRef') { - index = serializeDBRef(buffer, key, value, index, depth, serializeFunctions); - } else if (value['_bsontype'] == 'BSONRegExp') { - index = serializeBSONRegExp(buffer, key, value, index); - } else if (value['_bsontype'] == 'Int32') { - index = serializeInt32(buffer, key, value, index); - } else if (value['_bsontype'] == 'MinKey' || value['_bsontype'] == 'MaxKey') { - index = serializeMinMax(buffer, key, value, index); - } - } - } - - // Remove the path - path.pop(); - - // Final padding byte for object - buffer[index++] = 0x00; - - // Final size - var size = index - startingIndex; - // Write the size of the object - buffer[startingIndex++] = size & 0xff; - buffer[startingIndex++] = size >> 8 & 0xff; - buffer[startingIndex++] = size >> 16 & 0xff; - buffer[startingIndex++] = size >> 24 & 0xff; - return index; - }; - - var BSON = {}; - - /** - * Contains the function cache if we have that enable to allow for avoiding the eval step on each deserialization, comparison is by md5 - * - * @ignore - * @api private - */ - var functionCache = BSON.functionCache = {}; - - /** - * Number BSON Type - * - * @classconstant BSON_DATA_NUMBER - **/ - BSON.BSON_DATA_NUMBER = 1; - /** - * String BSON Type - * - * @classconstant BSON_DATA_STRING - **/ - BSON.BSON_DATA_STRING = 2; - /** - * Object BSON Type - * - * @classconstant BSON_DATA_OBJECT - **/ - BSON.BSON_DATA_OBJECT = 3; - /** - * Array BSON Type - * - * @classconstant BSON_DATA_ARRAY - **/ - BSON.BSON_DATA_ARRAY = 4; - /** - * Binary BSON Type - * - * @classconstant BSON_DATA_BINARY - **/ - BSON.BSON_DATA_BINARY = 5; - /** - * ObjectID BSON Type, deprecated - * - * @classconstant BSON_DATA_UNDEFINED - **/ - BSON.BSON_DATA_UNDEFINED = 6; - /** - * ObjectID BSON Type - * - * @classconstant BSON_DATA_OID - **/ - BSON.BSON_DATA_OID = 7; - /** - * Boolean BSON Type - * - * @classconstant BSON_DATA_BOOLEAN - **/ - BSON.BSON_DATA_BOOLEAN = 8; - /** - * Date BSON Type - * - * @classconstant BSON_DATA_DATE - **/ - BSON.BSON_DATA_DATE = 9; - /** - * null BSON Type - * - * @classconstant BSON_DATA_NULL - **/ - BSON.BSON_DATA_NULL = 10; - /** - * RegExp BSON Type - * - * @classconstant BSON_DATA_REGEXP - **/ - BSON.BSON_DATA_REGEXP = 11; - /** - * Code BSON Type - * - * @classconstant BSON_DATA_CODE - **/ - BSON.BSON_DATA_CODE = 13; - /** - * Symbol BSON Type - * - * @classconstant BSON_DATA_SYMBOL - **/ - BSON.BSON_DATA_SYMBOL = 14; - /** - * Code with Scope BSON Type - * - * @classconstant BSON_DATA_CODE_W_SCOPE - **/ - BSON.BSON_DATA_CODE_W_SCOPE = 15; - /** - * 32 bit Integer BSON Type - * - * @classconstant BSON_DATA_INT - **/ - BSON.BSON_DATA_INT = 16; - /** - * Timestamp BSON Type - * - * @classconstant BSON_DATA_TIMESTAMP - **/ - BSON.BSON_DATA_TIMESTAMP = 17; - /** - * Long BSON Type - * - * @classconstant BSON_DATA_LONG - **/ - BSON.BSON_DATA_LONG = 18; - /** - * Long BSON Type - * - * @classconstant BSON_DATA_DECIMAL128 - **/ - BSON.BSON_DATA_DECIMAL128 = 19; - /** - * MinKey BSON Type - * - * @classconstant BSON_DATA_MIN_KEY - **/ - BSON.BSON_DATA_MIN_KEY = 0xff; - /** - * MaxKey BSON Type - * - * @classconstant BSON_DATA_MAX_KEY - **/ - BSON.BSON_DATA_MAX_KEY = 0x7f; - /** - * Binary Default Type - * - * @classconstant BSON_BINARY_SUBTYPE_DEFAULT - **/ - BSON.BSON_BINARY_SUBTYPE_DEFAULT = 0; - /** - * Binary Function Type - * - * @classconstant BSON_BINARY_SUBTYPE_FUNCTION - **/ - BSON.BSON_BINARY_SUBTYPE_FUNCTION = 1; - /** - * Binary Byte Array Type - * - * @classconstant BSON_BINARY_SUBTYPE_BYTE_ARRAY - **/ - BSON.BSON_BINARY_SUBTYPE_BYTE_ARRAY = 2; - /** - * Binary UUID Type - * - * @classconstant BSON_BINARY_SUBTYPE_UUID - **/ - BSON.BSON_BINARY_SUBTYPE_UUID = 3; - /** - * Binary MD5 Type - * - * @classconstant BSON_BINARY_SUBTYPE_MD5 - **/ - BSON.BSON_BINARY_SUBTYPE_MD5 = 4; - /** - * Binary User Defined Type - * - * @classconstant BSON_BINARY_SUBTYPE_USER_DEFINED - **/ - BSON.BSON_BINARY_SUBTYPE_USER_DEFINED = 128; - - // BSON MAX VALUES - BSON.BSON_INT32_MAX = 0x7FFFFFFF; - BSON.BSON_INT32_MIN = -0x80000000; - - BSON.BSON_INT64_MAX = Math.pow(2, 63) - 1; - BSON.BSON_INT64_MIN = -Math.pow(2, 63); - - // JS MAX PRECISE VALUES - BSON.JS_INT_MAX = 0x20000000000000; // Any integer up to 2^53 can be precisely represented by a double. - BSON.JS_INT_MIN = -0x20000000000000; // Any integer down to -2^53 can be precisely represented by a double. - - // Internal long versions - var JS_INT_MAX_LONG = Long.fromNumber(0x20000000000000); // Any integer up to 2^53 can be precisely represented by a double. - var JS_INT_MIN_LONG = Long.fromNumber(-0x20000000000000); // Any integer down to -2^53 can be precisely represented by a double. - - module.exports = serializeInto; - /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(300).Buffer)) - -/***/ }, -/* 324 */ -/***/ function(module, exports, __webpack_require__) { - - /* WEBPACK VAR INJECTION */(function(Buffer) {"use strict"; - - var writeIEEE754 = __webpack_require__(304).writeIEEE754, - readIEEE754 = __webpack_require__(304).readIEEE754, - Long = __webpack_require__(306).Long, - Double = __webpack_require__(307).Double, - Timestamp = __webpack_require__(308).Timestamp, - ObjectID = __webpack_require__(309).ObjectID, - Symbol = __webpack_require__(311).Symbol, - BSONRegExp = __webpack_require__(310).BSONRegExp, - Code = __webpack_require__(313).Code, - Decimal128 = __webpack_require__(314), - MinKey = __webpack_require__(315).MinKey, - MaxKey = __webpack_require__(316).MaxKey, - DBRef = __webpack_require__(317).DBRef, - Binary = __webpack_require__(318).Binary; - - // To ensure that 0.4 of node works correctly - var isDate = function isDate(d) { - return typeof d === 'object' && Object.prototype.toString.call(d) === '[object Date]'; - }; - - var calculateObjectSize = function calculateObjectSize(object, serializeFunctions, ignoreUndefined) { - var totalLength = 4 + 1; - - if (Array.isArray(object)) { - for (var i = 0; i < object.length; i++) { - totalLength += calculateElement(i.toString(), object[i], serializeFunctions, true, ignoreUndefined); - } - } else { - // If we have toBSON defined, override the current object - if (object.toBSON) { - object = object.toBSON(); - } - - // Calculate size - for (var key in object) { - totalLength += calculateElement(key, object[key], serializeFunctions, false, ignoreUndefined); - } - } - - return totalLength; - }; - - /** - * @ignore - * @api private - */ - function calculateElement(name, value, serializeFunctions, isArray, ignoreUndefined) { - // If we have toBSON defined, override the current object - if (value && value.toBSON) { - value = value.toBSON(); - } - - switch (typeof value) { - case 'string': - return 1 + Buffer.byteLength(name, 'utf8') + 1 + 4 + Buffer.byteLength(value, 'utf8') + 1; - case 'number': - if (Math.floor(value) === value && value >= BSON.JS_INT_MIN && value <= BSON.JS_INT_MAX) { - if (value >= BSON.BSON_INT32_MIN && value <= BSON.BSON_INT32_MAX) { - // 32 bit - return (name != null ? Buffer.byteLength(name, 'utf8') + 1 : 0) + (4 + 1); - } else { - return (name != null ? Buffer.byteLength(name, 'utf8') + 1 : 0) + (8 + 1); - } - } else { - // 64 bit - return (name != null ? Buffer.byteLength(name, 'utf8') + 1 : 0) + (8 + 1); - } - case 'undefined': - if (isArray || !ignoreUndefined) return (name != null ? Buffer.byteLength(name, 'utf8') + 1 : 0) + 1; - return 0; - case 'boolean': - return (name != null ? Buffer.byteLength(name, 'utf8') + 1 : 0) + (1 + 1); - case 'object': - if (value == null || value instanceof MinKey || value instanceof MaxKey || value['_bsontype'] == 'MinKey' || value['_bsontype'] == 'MaxKey') { - return (name != null ? Buffer.byteLength(name, 'utf8') + 1 : 0) + 1; - } else if (value instanceof ObjectID || value['_bsontype'] == 'ObjectID') { - return (name != null ? Buffer.byteLength(name, 'utf8') + 1 : 0) + (12 + 1); - } else if (value instanceof Date || isDate(value)) { - return (name != null ? Buffer.byteLength(name, 'utf8') + 1 : 0) + (8 + 1); - } else if (typeof Buffer !== 'undefined' && Buffer.isBuffer(value)) { - return (name != null ? Buffer.byteLength(name, 'utf8') + 1 : 0) + (1 + 4 + 1) + value.length; - } else if (value instanceof Long || value instanceof Double || value instanceof Timestamp || value['_bsontype'] == 'Long' || value['_bsontype'] == 'Double' || value['_bsontype'] == 'Timestamp') { - return (name != null ? Buffer.byteLength(name, 'utf8') + 1 : 0) + (8 + 1); - } else if (value instanceof Decimal128 || value['_bsontype'] == 'Decimal128') { - return (name != null ? Buffer.byteLength(name, 'utf8') + 1 : 0) + (16 + 1); - } else if (value instanceof Code || value['_bsontype'] == 'Code') { - // Calculate size depending on the availability of a scope - if (value.scope != null && Object.keys(value.scope).length > 0) { - return (name != null ? Buffer.byteLength(name, 'utf8') + 1 : 0) + 1 + 4 + 4 + Buffer.byteLength(value.code.toString(), 'utf8') + 1 + calculateObjectSize(value.scope, serializeFunctions, ignoreUndefined); - } else { - return (name != null ? Buffer.byteLength(name, 'utf8') + 1 : 0) + 1 + 4 + Buffer.byteLength(value.code.toString(), 'utf8') + 1; - } - } else if (value instanceof Binary || value['_bsontype'] == 'Binary') { - // Check what kind of subtype we have - if (value.sub_type == Binary.SUBTYPE_BYTE_ARRAY) { - return (name != null ? Buffer.byteLength(name, 'utf8') + 1 : 0) + (value.position + 1 + 4 + 1 + 4); - } else { - return (name != null ? Buffer.byteLength(name, 'utf8') + 1 : 0) + (value.position + 1 + 4 + 1); - } - } else if (value instanceof Symbol || value['_bsontype'] == 'Symbol') { - return (name != null ? Buffer.byteLength(name, 'utf8') + 1 : 0) + Buffer.byteLength(value.value, 'utf8') + 4 + 1 + 1; - } else if (value instanceof DBRef || value['_bsontype'] == 'DBRef') { - // Set up correct object for serialization - var ordered_values = { - '$ref': value.namespace, - '$id': value.oid - }; - - // Add db reference if it exists - if (null != value.db) { - ordered_values['$db'] = value.db; - } - - return (name != null ? Buffer.byteLength(name, 'utf8') + 1 : 0) + 1 + calculateObjectSize(ordered_values, serializeFunctions, ignoreUndefined); - } else if (value instanceof RegExp || Object.prototype.toString.call(value) === '[object RegExp]') { - return (name != null ? Buffer.byteLength(name, 'utf8') + 1 : 0) + 1 + Buffer.byteLength(value.source, 'utf8') + 1 + (value.global ? 1 : 0) + (value.ignoreCase ? 1 : 0) + (value.multiline ? 1 : 0) + 1; - } else if (value instanceof BSONRegExp || value['_bsontype'] == 'BSONRegExp') { - return (name != null ? Buffer.byteLength(name, 'utf8') + 1 : 0) + 1 + Buffer.byteLength(value.pattern, 'utf8') + 1 + Buffer.byteLength(value.options, 'utf8') + 1; - } else { - return (name != null ? Buffer.byteLength(name, 'utf8') + 1 : 0) + calculateObjectSize(value, serializeFunctions, ignoreUndefined) + 1; - } - case 'function': - // WTF for 0.4.X where typeof /someregexp/ === 'function' - if (value instanceof RegExp || Object.prototype.toString.call(value) === '[object RegExp]' || String.call(value) == '[object RegExp]') { - return (name != null ? Buffer.byteLength(name, 'utf8') + 1 : 0) + 1 + Buffer.byteLength(value.source, 'utf8') + 1 + (value.global ? 1 : 0) + (value.ignoreCase ? 1 : 0) + (value.multiline ? 1 : 0) + 1; - } else { - if (serializeFunctions && value.scope != null && Object.keys(value.scope).length > 0) { - return (name != null ? Buffer.byteLength(name, 'utf8') + 1 : 0) + 1 + 4 + 4 + Buffer.byteLength(value.toString(), 'utf8') + 1 + calculateObjectSize(value.scope, serializeFunctions, ignoreUndefined); - } else if (serializeFunctions) { - return (name != null ? Buffer.byteLength(name, 'utf8') + 1 : 0) + 1 + 4 + Buffer.byteLength(value.toString(), 'utf8') + 1; - } - } - } - - return 0; - } - - var BSON = {}; - - // BSON MAX VALUES - BSON.BSON_INT32_MAX = 0x7FFFFFFF; - BSON.BSON_INT32_MIN = -0x80000000; - - // JS MAX PRECISE VALUES - BSON.JS_INT_MAX = 0x20000000000000; // Any integer up to 2^53 can be precisely represented by a double. - BSON.JS_INT_MIN = -0x20000000000000; // Any integer down to -2^53 can be precisely represented by a double. - - module.exports = calculateObjectSize; - /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(300).Buffer)) - -/***/ } -/******/ ]) -}); -; \ No newline at end of file diff --git a/ts-ticket-office-service/node_modules/bson/browser_build/package.json b/ts-ticket-office-service/node_modules/bson/browser_build/package.json deleted file mode 100644 index 980db7f95..000000000 --- a/ts-ticket-office-service/node_modules/bson/browser_build/package.json +++ /dev/null @@ -1,8 +0,0 @@ -{ "name" : "bson" -, "description" : "A bson parser for node.js and the browser" -, "main": "../" -, "directories" : { "lib" : "../lib/bson" } -, "engines" : { "node" : ">=0.6.0" } -, "licenses" : [ { "type" : "Apache License, Version 2.0" - , "url" : "http://www.apache.org/licenses/LICENSE-2.0" } ] -} diff --git a/ts-ticket-office-service/node_modules/bson/bson.d.ts b/ts-ticket-office-service/node_modules/bson/bson.d.ts new file mode 100644 index 000000000..8417d143b --- /dev/null +++ b/ts-ticket-office-service/node_modules/bson/bson.d.ts @@ -0,0 +1,1235 @@ +import { Buffer } from 'buffer'; + +/** + * A class representation of the BSON Binary type. + * @public + * @category BSONType + */ +export declare class Binary { + _bsontype: 'Binary'; + /* Excluded from this release type: BSON_BINARY_SUBTYPE_DEFAULT */ + /** Initial buffer default size */ + static readonly BUFFER_SIZE = 256; + /** Default BSON type */ + static readonly SUBTYPE_DEFAULT = 0; + /** Function BSON type */ + static readonly SUBTYPE_FUNCTION = 1; + /** Byte Array BSON type */ + static readonly SUBTYPE_BYTE_ARRAY = 2; + /** Deprecated UUID BSON type @deprecated Please use SUBTYPE_UUID */ + static readonly SUBTYPE_UUID_OLD = 3; + /** UUID BSON type */ + static readonly SUBTYPE_UUID = 4; + /** MD5 BSON type */ + static readonly SUBTYPE_MD5 = 5; + /** Encrypted BSON type */ + static readonly SUBTYPE_ENCRYPTED = 6; + /** Column BSON type */ + static readonly SUBTYPE_COLUMN = 7; + /** User BSON type */ + static readonly SUBTYPE_USER_DEFINED = 128; + buffer: Buffer; + sub_type: number; + position: number; + /** + * Create a new Binary instance. + * + * This constructor can accept a string as its first argument. In this case, + * this string will be encoded using ISO-8859-1, **not** using UTF-8. + * This is almost certainly not what you want. Use `new Binary(Buffer.from(string))` + * instead to convert the string to a Buffer using UTF-8 first. + * + * @param buffer - a buffer object containing the binary data. + * @param subType - the option binary type. + */ + constructor(buffer?: string | BinarySequence, subType?: number); + /** + * Updates this binary with byte_value. + * + * @param byteValue - a single byte we wish to write. + */ + put(byteValue: string | number | Uint8Array | Buffer | number[]): void; + /** + * Writes a buffer or string to the binary. + * + * @param sequence - a string or buffer to be written to the Binary BSON object. + * @param offset - specify the binary of where to write the content. + */ + write(sequence: string | BinarySequence, offset: number): void; + /** + * Reads **length** bytes starting at **position**. + * + * @param position - read from the given position in the Binary. + * @param length - the number of bytes to read. + */ + read(position: number, length: number): BinarySequence; + /** + * Returns the value of this binary as a string. + * @param asRaw - Will skip converting to a string + * @remarks + * This is handy when calling this function conditionally for some key value pairs and not others + */ + value(asRaw?: boolean): string | BinarySequence; + /** the length of the binary sequence */ + length(): number; + toJSON(): string; + toString(format?: string): string; + /* Excluded from this release type: toExtendedJSON */ + toUUID(): UUID; + /* Excluded from this release type: fromExtendedJSON */ + inspect(): string; +} + +/** @public */ +export declare interface BinaryExtended { + $binary: { + subType: string; + base64: string; + }; +} + +/** @public */ +export declare interface BinaryExtendedLegacy { + $type: string; + $binary: string; +} + +/** @public */ +export declare type BinarySequence = Uint8Array | Buffer | number[]; + +/** + * BSON default export + * @deprecated Please use named exports + * @privateRemarks + * We want to someday deprecate the default export, + * so none of the new TS types are being exported on the default + * @public + */ +declare const BSON: { + Binary: typeof Binary; + Code: typeof Code; + DBRef: typeof DBRef; + Decimal128: typeof Decimal128; + Double: typeof Double; + Int32: typeof Int32; + Long: typeof Long; + UUID: typeof UUID; + Map: MapConstructor; + MaxKey: typeof MaxKey; + MinKey: typeof MinKey; + ObjectId: typeof ObjectId; + ObjectID: typeof ObjectId; + BSONRegExp: typeof BSONRegExp; + BSONSymbol: typeof BSONSymbol; + Timestamp: typeof Timestamp; + EJSON: typeof EJSON; + setInternalBufferSize: typeof setInternalBufferSize; + serialize: typeof serialize; + serializeWithBufferAndIndex: typeof serializeWithBufferAndIndex; + deserialize: typeof deserialize; + calculateObjectSize: typeof calculateObjectSize; + deserializeStream: typeof deserializeStream; + BSONError: typeof BSONError; + BSONTypeError: typeof BSONTypeError; +}; +export default BSON; + +/* Excluded from this release type: BSON_BINARY_SUBTYPE_BYTE_ARRAY */ + +/* Excluded from this release type: BSON_BINARY_SUBTYPE_COLUMN */ + +/* Excluded from this release type: BSON_BINARY_SUBTYPE_DEFAULT */ + +/* Excluded from this release type: BSON_BINARY_SUBTYPE_ENCRYPTED */ + +/* Excluded from this release type: BSON_BINARY_SUBTYPE_FUNCTION */ + +/* Excluded from this release type: BSON_BINARY_SUBTYPE_MD5 */ + +/* Excluded from this release type: BSON_BINARY_SUBTYPE_USER_DEFINED */ + +/* Excluded from this release type: BSON_BINARY_SUBTYPE_UUID */ + +/* Excluded from this release type: BSON_BINARY_SUBTYPE_UUID_NEW */ + +/* Excluded from this release type: BSON_DATA_ARRAY */ + +/* Excluded from this release type: BSON_DATA_BINARY */ + +/* Excluded from this release type: BSON_DATA_BOOLEAN */ + +/* Excluded from this release type: BSON_DATA_CODE */ + +/* Excluded from this release type: BSON_DATA_CODE_W_SCOPE */ + +/* Excluded from this release type: BSON_DATA_DATE */ + +/* Excluded from this release type: BSON_DATA_DBPOINTER */ + +/* Excluded from this release type: BSON_DATA_DECIMAL128 */ + +/* Excluded from this release type: BSON_DATA_INT */ + +/* Excluded from this release type: BSON_DATA_LONG */ + +/* Excluded from this release type: BSON_DATA_MAX_KEY */ + +/* Excluded from this release type: BSON_DATA_MIN_KEY */ + +/* Excluded from this release type: BSON_DATA_NULL */ + +/* Excluded from this release type: BSON_DATA_NUMBER */ + +/* Excluded from this release type: BSON_DATA_OBJECT */ + +/* Excluded from this release type: BSON_DATA_OID */ + +/* Excluded from this release type: BSON_DATA_REGEXP */ + +/* Excluded from this release type: BSON_DATA_STRING */ + +/* Excluded from this release type: BSON_DATA_SYMBOL */ + +/* Excluded from this release type: BSON_DATA_TIMESTAMP */ + +/* Excluded from this release type: BSON_DATA_UNDEFINED */ + +/* Excluded from this release type: BSON_INT32_MAX */ + +/* Excluded from this release type: BSON_INT32_MIN */ + +/* Excluded from this release type: BSON_INT64_MAX */ + +/* Excluded from this release type: BSON_INT64_MIN */ + +/** @public */ +export declare class BSONError extends Error { + constructor(message: string); + get name(): string; +} + +/** + * A class representation of the BSON RegExp type. + * @public + * @category BSONType + */ +export declare class BSONRegExp { + _bsontype: 'BSONRegExp'; + pattern: string; + options: string; + /** + * @param pattern - The regular expression pattern to match + * @param options - The regular expression options + */ + constructor(pattern: string, options?: string); + static parseOptions(options?: string): string; + /* Excluded from this release type: toExtendedJSON */ + /* Excluded from this release type: fromExtendedJSON */ +} + +/** @public */ +export declare interface BSONRegExpExtended { + $regularExpression: { + pattern: string; + options: string; + }; +} + +/** @public */ +export declare interface BSONRegExpExtendedLegacy { + $regex: string | BSONRegExp; + $options: string; +} + +/** + * A class representation of the BSON Symbol type. + * @public + * @category BSONType + */ +export declare class BSONSymbol { + _bsontype: 'Symbol'; + value: string; + /** + * @param value - the string representing the symbol. + */ + constructor(value: string); + /** Access the wrapped string value. */ + valueOf(): string; + toString(): string; + /* Excluded from this release type: inspect */ + toJSON(): string; + /* Excluded from this release type: toExtendedJSON */ + /* Excluded from this release type: fromExtendedJSON */ +} + +/** @public */ +export declare interface BSONSymbolExtended { + $symbol: string; +} + +/** @public */ +export declare class BSONTypeError extends TypeError { + constructor(message: string); + get name(): string; +} + +/** + * Calculate the bson size for a passed in Javascript object. + * + * @param object - the Javascript object to calculate the BSON byte size for + * @returns size of BSON object in bytes + * @public + */ +export declare function calculateObjectSize(object: Document, options?: CalculateObjectSizeOptions): number; + +/** @public */ +export declare type CalculateObjectSizeOptions = Pick; + +/** + * A class representation of the BSON Code type. + * @public + * @category BSONType + */ +export declare class Code { + _bsontype: 'Code'; + code: string | Function; + scope?: Document; + /** + * @param code - a string or function. + * @param scope - an optional scope for the function. + */ + constructor(code: string | Function, scope?: Document); + toJSON(): { + code: string | Function; + scope?: Document; + }; + /* Excluded from this release type: toExtendedJSON */ + /* Excluded from this release type: fromExtendedJSON */ + inspect(): string; +} + +/** @public */ +export declare interface CodeExtended { + $code: string | Function; + $scope?: Document; +} + +/** + * A class representation of the BSON DBRef type. + * @public + * @category BSONType + */ +export declare class DBRef { + _bsontype: 'DBRef'; + collection: string; + oid: ObjectId; + db?: string; + fields: Document; + /** + * @param collection - the collection name. + * @param oid - the reference ObjectId. + * @param db - optional db name, if omitted the reference is local to the current db. + */ + constructor(collection: string, oid: ObjectId, db?: string, fields?: Document); + /* Excluded from this release type: namespace */ + /* Excluded from this release type: namespace */ + toJSON(): DBRefLike & Document; + /* Excluded from this release type: toExtendedJSON */ + /* Excluded from this release type: fromExtendedJSON */ + inspect(): string; +} + +/** @public */ +export declare interface DBRefLike { + $ref: string; + $id: ObjectId; + $db?: string; +} + +/** + * A class representation of the BSON Decimal128 type. + * @public + * @category BSONType + */ +export declare class Decimal128 { + _bsontype: 'Decimal128'; + readonly bytes: Buffer; + /** + * @param bytes - a buffer containing the raw Decimal128 bytes in little endian order, + * or a string representation as returned by .toString() + */ + constructor(bytes: Buffer | string); + /** + * Create a Decimal128 instance from a string representation + * + * @param representation - a numeric string representation. + */ + static fromString(representation: string): Decimal128; + /** Create a string representation of the raw Decimal128 value */ + toString(): string; + toJSON(): Decimal128Extended; + /* Excluded from this release type: toExtendedJSON */ + /* Excluded from this release type: fromExtendedJSON */ + inspect(): string; +} + +/** @public */ +export declare interface Decimal128Extended { + $numberDecimal: string; +} + +/** + * Deserialize data as BSON. + * + * @param buffer - the buffer containing the serialized set of BSON documents. + * @returns returns the deserialized Javascript Object. + * @public + */ +export declare function deserialize(buffer: Buffer | ArrayBufferView | ArrayBuffer, options?: DeserializeOptions): Document; + +/** @public */ +export declare interface DeserializeOptions { + /** evaluate functions in the BSON document scoped to the object deserialized. */ + evalFunctions?: boolean; + /** cache evaluated functions for reuse. */ + cacheFunctions?: boolean; + /** + * use a crc32 code for caching, otherwise use the string of the function. + * @deprecated this option to use the crc32 function never worked as intended + * due to the fact that the crc32 function itself was never implemented. + * */ + cacheFunctionsCrc32?: boolean; + /** when deserializing a Long will fit it into a Number if it's smaller than 53 bits */ + promoteLongs?: boolean; + /** when deserializing a Binary will return it as a node.js Buffer instance. */ + promoteBuffers?: boolean; + /** when deserializing will promote BSON values to their Node.js closest equivalent types. */ + promoteValues?: boolean; + /** allow to specify if there what fields we wish to return as unserialized raw buffer. */ + fieldsAsRaw?: Document; + /** return BSON regular expressions as BSONRegExp instances. */ + bsonRegExp?: boolean; + /** allows the buffer to be larger than the parsed BSON object */ + allowObjectSmallerThanBufferSize?: boolean; + /** Offset into buffer to begin reading document from */ + index?: number; + raw?: boolean; + /** Allows for opt-out utf-8 validation for all keys or + * specified keys. Must be all true or all false. + * + * @example + * ```js + * // disables validation on all keys + * validation: { utf8: false } + * + * // enables validation only on specified keys a, b, and c + * validation: { utf8: { a: true, b: true, c: true } } + * + * // disables validation only on specified keys a, b + * validation: { utf8: { a: false, b: false } } + * ``` + */ + validation?: { + utf8: boolean | Record | Record; + }; +} + +/** + * Deserialize stream data as BSON documents. + * + * @param data - the buffer containing the serialized set of BSON documents. + * @param startIndex - the start index in the data Buffer where the deserialization is to start. + * @param numberOfDocuments - number of documents to deserialize. + * @param documents - an array where to store the deserialized documents. + * @param docStartIndex - the index in the documents array from where to start inserting documents. + * @param options - additional options used for the deserialization. + * @returns next index in the buffer after deserialization **x** numbers of documents. + * @public + */ +export declare function deserializeStream(data: Buffer | ArrayBufferView | ArrayBuffer, startIndex: number, numberOfDocuments: number, documents: Document[], docStartIndex: number, options: DeserializeOptions): number; + +/** @public */ +export declare interface Document { + [key: string]: any; +} + +/** + * A class representation of the BSON Double type. + * @public + * @category BSONType + */ +export declare class Double { + _bsontype: 'Double'; + value: number; + /** + * Create a Double type + * + * @param value - the number we want to represent as a double. + */ + constructor(value: number); + /** + * Access the number value. + * + * @returns returns the wrapped double number. + */ + valueOf(): number; + toJSON(): number; + toString(radix?: number): string; + /* Excluded from this release type: toExtendedJSON */ + /* Excluded from this release type: fromExtendedJSON */ + inspect(): string; +} + +/** @public */ +export declare interface DoubleExtended { + $numberDouble: string; +} + +/** + * EJSON parse / stringify API + * @public + */ +export declare namespace EJSON { + export interface Options { + /** Output using the Extended JSON v1 spec */ + legacy?: boolean; + /** Enable Extended JSON's `relaxed` mode, which attempts to return native JS types where possible, rather than BSON types */ + relaxed?: boolean; + /** + * Disable Extended JSON's `relaxed` mode, which attempts to return BSON types where possible, rather than native JS types + * @deprecated Please use the relaxed property instead + */ + strict?: boolean; + } + /** + * Parse an Extended JSON string, constructing the JavaScript value or object described by that + * string. + * + * @example + * ```js + * const { EJSON } = require('bson'); + * const text = '{ "int32": { "$numberInt": "10" } }'; + * + * // prints { int32: { [String: '10'] _bsontype: 'Int32', value: '10' } } + * console.log(EJSON.parse(text, { relaxed: false })); + * + * // prints { int32: 10 } + * console.log(EJSON.parse(text)); + * ``` + */ + export function parse(text: string, options?: EJSON.Options): SerializableTypes; + export type JSONPrimitive = string | number | boolean | null; + export type SerializableTypes = Document | Array | JSONPrimitive; + /** + * Converts a BSON document to an Extended JSON string, optionally replacing values if a replacer + * function is specified or optionally including only the specified properties if a replacer array + * is specified. + * + * @param value - The value to convert to extended JSON + * @param replacer - A function that alters the behavior of the stringification process, or an array of String and Number objects that serve as a whitelist for selecting/filtering the properties of the value object to be included in the JSON string. If this value is null or not provided, all properties of the object are included in the resulting JSON string + * @param space - A String or Number object that's used to insert white space into the output JSON string for readability purposes. + * @param options - Optional settings + * + * @example + * ```js + * const { EJSON } = require('bson'); + * const Int32 = require('mongodb').Int32; + * const doc = { int32: new Int32(10) }; + * + * // prints '{"int32":{"$numberInt":"10"}}' + * console.log(EJSON.stringify(doc, { relaxed: false })); + * + * // prints '{"int32":10}' + * console.log(EJSON.stringify(doc)); + * ``` + */ + export function stringify(value: SerializableTypes, replacer?: (number | string)[] | ((this: any, key: string, value: any) => any) | EJSON.Options, space?: string | number, options?: EJSON.Options): string; + /** + * Serializes an object to an Extended JSON string, and reparse it as a JavaScript object. + * + * @param value - The object to serialize + * @param options - Optional settings passed to the `stringify` function + */ + export function serialize(value: SerializableTypes, options?: EJSON.Options): Document; + /** + * Deserializes an Extended JSON object into a plain JavaScript object with native/BSON types + * + * @param ejson - The Extended JSON object to deserialize + * @param options - Optional settings passed to the parse method + */ + export function deserialize(ejson: Document, options?: EJSON.Options): SerializableTypes; +} + +/** @public */ +export declare type EJSONOptions = EJSON.Options; + +/** + * A class representation of a BSON Int32 type. + * @public + * @category BSONType + */ +export declare class Int32 { + _bsontype: 'Int32'; + value: number; + /** + * Create an Int32 type + * + * @param value - the number we want to represent as an int32. + */ + constructor(value: number | string); + /** + * Access the number value. + * + * @returns returns the wrapped int32 number. + */ + valueOf(): number; + toString(radix?: number): string; + toJSON(): number; + /* Excluded from this release type: toExtendedJSON */ + /* Excluded from this release type: fromExtendedJSON */ + inspect(): string; +} + +/** @public */ +export declare interface Int32Extended { + $numberInt: string; +} + +declare const kId: unique symbol; + +declare const kId_2: unique symbol; + +/** + * A class representing a 64-bit integer + * @public + * @category BSONType + * @remarks + * The internal representation of a long is the two given signed, 32-bit values. + * We use 32-bit pieces because these are the size of integers on which + * Javascript performs bit-operations. For operations like addition and + * multiplication, we split each number into 16 bit pieces, which can easily be + * multiplied within Javascript's floating-point representation without overflow + * or change in sign. + * In the algorithms below, we frequently reduce the negative case to the + * positive case by negating the input(s) and then post-processing the result. + * Note that we must ALWAYS check specially whether those values are MIN_VALUE + * (-2^63) because -MIN_VALUE == MIN_VALUE (since 2^63 cannot be represented as + * a positive number, it overflows back into a negative). Not handling this + * case would often result in infinite recursion. + * Common constant values ZERO, ONE, NEG_ONE, etc. are found as static properties on this class. + */ +export declare class Long { + _bsontype: 'Long'; + /** An indicator used to reliably determine if an object is a Long or not. */ + __isLong__: true; + /** + * The high 32 bits as a signed value. + */ + high: number; + /** + * The low 32 bits as a signed value. + */ + low: number; + /** + * Whether unsigned or not. + */ + unsigned: boolean; + /** + * Constructs a 64 bit two's-complement integer, given its low and high 32 bit values as *signed* integers. + * See the from* functions below for more convenient ways of constructing Longs. + * + * Acceptable signatures are: + * - Long(low, high, unsigned?) + * - Long(bigint, unsigned?) + * - Long(string, unsigned?) + * + * @param low - The low (signed) 32 bits of the long + * @param high - The high (signed) 32 bits of the long + * @param unsigned - Whether unsigned or not, defaults to signed + */ + constructor(low?: number | bigint | string, high?: number | boolean, unsigned?: boolean); + static TWO_PWR_24: Long; + /** Maximum unsigned value. */ + static MAX_UNSIGNED_VALUE: Long; + /** Signed zero */ + static ZERO: Long; + /** Unsigned zero. */ + static UZERO: Long; + /** Signed one. */ + static ONE: Long; + /** Unsigned one. */ + static UONE: Long; + /** Signed negative one. */ + static NEG_ONE: Long; + /** Maximum signed value. */ + static MAX_VALUE: Long; + /** Minimum signed value. */ + static MIN_VALUE: Long; + /** + * Returns a Long representing the 64 bit integer that comes by concatenating the given low and high bits. + * Each is assumed to use 32 bits. + * @param lowBits - The low 32 bits + * @param highBits - The high 32 bits + * @param unsigned - Whether unsigned or not, defaults to signed + * @returns The corresponding Long value + */ + static fromBits(lowBits: number, highBits: number, unsigned?: boolean): Long; + /** + * Returns a Long representing the given 32 bit integer value. + * @param value - The 32 bit integer in question + * @param unsigned - Whether unsigned or not, defaults to signed + * @returns The corresponding Long value + */ + static fromInt(value: number, unsigned?: boolean): Long; + /** + * Returns a Long representing the given value, provided that it is a finite number. Otherwise, zero is returned. + * @param value - The number in question + * @param unsigned - Whether unsigned or not, defaults to signed + * @returns The corresponding Long value + */ + static fromNumber(value: number, unsigned?: boolean): Long; + /** + * Returns a Long representing the given value, provided that it is a finite number. Otherwise, zero is returned. + * @param value - The number in question + * @param unsigned - Whether unsigned or not, defaults to signed + * @returns The corresponding Long value + */ + static fromBigInt(value: bigint, unsigned?: boolean): Long; + /** + * Returns a Long representation of the given string, written using the specified radix. + * @param str - The textual representation of the Long + * @param unsigned - Whether unsigned or not, defaults to signed + * @param radix - The radix in which the text is written (2-36), defaults to 10 + * @returns The corresponding Long value + */ + static fromString(str: string, unsigned?: boolean, radix?: number): Long; + /** + * Creates a Long from its byte representation. + * @param bytes - Byte representation + * @param unsigned - Whether unsigned or not, defaults to signed + * @param le - Whether little or big endian, defaults to big endian + * @returns The corresponding Long value + */ + static fromBytes(bytes: number[], unsigned?: boolean, le?: boolean): Long; + /** + * Creates a Long from its little endian byte representation. + * @param bytes - Little endian byte representation + * @param unsigned - Whether unsigned or not, defaults to signed + * @returns The corresponding Long value + */ + static fromBytesLE(bytes: number[], unsigned?: boolean): Long; + /** + * Creates a Long from its big endian byte representation. + * @param bytes - Big endian byte representation + * @param unsigned - Whether unsigned or not, defaults to signed + * @returns The corresponding Long value + */ + static fromBytesBE(bytes: number[], unsigned?: boolean): Long; + /** + * Tests if the specified object is a Long. + */ + static isLong(value: unknown): value is Long; + /** + * Converts the specified value to a Long. + * @param unsigned - Whether unsigned or not, defaults to signed + */ + static fromValue(val: number | string | { + low: number; + high: number; + unsigned?: boolean; + }, unsigned?: boolean): Long; + /** Returns the sum of this and the specified Long. */ + add(addend: string | number | Long | Timestamp): Long; + /** + * Returns the sum of this and the specified Long. + * @returns Sum + */ + and(other: string | number | Long | Timestamp): Long; + /** + * Compares this Long's value with the specified's. + * @returns 0 if they are the same, 1 if the this is greater and -1 if the given one is greater + */ + compare(other: string | number | Long | Timestamp): 0 | 1 | -1; + /** This is an alias of {@link Long.compare} */ + comp(other: string | number | Long | Timestamp): 0 | 1 | -1; + /** + * Returns this Long divided by the specified. The result is signed if this Long is signed or unsigned if this Long is unsigned. + * @returns Quotient + */ + divide(divisor: string | number | Long | Timestamp): Long; + /**This is an alias of {@link Long.divide} */ + div(divisor: string | number | Long | Timestamp): Long; + /** + * Tests if this Long's value equals the specified's. + * @param other - Other value + */ + equals(other: string | number | Long | Timestamp): boolean; + /** This is an alias of {@link Long.equals} */ + eq(other: string | number | Long | Timestamp): boolean; + /** Gets the high 32 bits as a signed integer. */ + getHighBits(): number; + /** Gets the high 32 bits as an unsigned integer. */ + getHighBitsUnsigned(): number; + /** Gets the low 32 bits as a signed integer. */ + getLowBits(): number; + /** Gets the low 32 bits as an unsigned integer. */ + getLowBitsUnsigned(): number; + /** Gets the number of bits needed to represent the absolute value of this Long. */ + getNumBitsAbs(): number; + /** Tests if this Long's value is greater than the specified's. */ + greaterThan(other: string | number | Long | Timestamp): boolean; + /** This is an alias of {@link Long.greaterThan} */ + gt(other: string | number | Long | Timestamp): boolean; + /** Tests if this Long's value is greater than or equal the specified's. */ + greaterThanOrEqual(other: string | number | Long | Timestamp): boolean; + /** This is an alias of {@link Long.greaterThanOrEqual} */ + gte(other: string | number | Long | Timestamp): boolean; + /** This is an alias of {@link Long.greaterThanOrEqual} */ + ge(other: string | number | Long | Timestamp): boolean; + /** Tests if this Long's value is even. */ + isEven(): boolean; + /** Tests if this Long's value is negative. */ + isNegative(): boolean; + /** Tests if this Long's value is odd. */ + isOdd(): boolean; + /** Tests if this Long's value is positive. */ + isPositive(): boolean; + /** Tests if this Long's value equals zero. */ + isZero(): boolean; + /** Tests if this Long's value is less than the specified's. */ + lessThan(other: string | number | Long | Timestamp): boolean; + /** This is an alias of {@link Long#lessThan}. */ + lt(other: string | number | Long | Timestamp): boolean; + /** Tests if this Long's value is less than or equal the specified's. */ + lessThanOrEqual(other: string | number | Long | Timestamp): boolean; + /** This is an alias of {@link Long.lessThanOrEqual} */ + lte(other: string | number | Long | Timestamp): boolean; + /** Returns this Long modulo the specified. */ + modulo(divisor: string | number | Long | Timestamp): Long; + /** This is an alias of {@link Long.modulo} */ + mod(divisor: string | number | Long | Timestamp): Long; + /** This is an alias of {@link Long.modulo} */ + rem(divisor: string | number | Long | Timestamp): Long; + /** + * Returns the product of this and the specified Long. + * @param multiplier - Multiplier + * @returns Product + */ + multiply(multiplier: string | number | Long | Timestamp): Long; + /** This is an alias of {@link Long.multiply} */ + mul(multiplier: string | number | Long | Timestamp): Long; + /** Returns the Negation of this Long's value. */ + negate(): Long; + /** This is an alias of {@link Long.negate} */ + neg(): Long; + /** Returns the bitwise NOT of this Long. */ + not(): Long; + /** Tests if this Long's value differs from the specified's. */ + notEquals(other: string | number | Long | Timestamp): boolean; + /** This is an alias of {@link Long.notEquals} */ + neq(other: string | number | Long | Timestamp): boolean; + /** This is an alias of {@link Long.notEquals} */ + ne(other: string | number | Long | Timestamp): boolean; + /** + * Returns the bitwise OR of this Long and the specified. + */ + or(other: number | string | Long): Long; + /** + * Returns this Long with bits shifted to the left by the given amount. + * @param numBits - Number of bits + * @returns Shifted Long + */ + shiftLeft(numBits: number | Long): Long; + /** This is an alias of {@link Long.shiftLeft} */ + shl(numBits: number | Long): Long; + /** + * Returns this Long with bits arithmetically shifted to the right by the given amount. + * @param numBits - Number of bits + * @returns Shifted Long + */ + shiftRight(numBits: number | Long): Long; + /** This is an alias of {@link Long.shiftRight} */ + shr(numBits: number | Long): Long; + /** + * Returns this Long with bits logically shifted to the right by the given amount. + * @param numBits - Number of bits + * @returns Shifted Long + */ + shiftRightUnsigned(numBits: Long | number): Long; + /** This is an alias of {@link Long.shiftRightUnsigned} */ + shr_u(numBits: number | Long): Long; + /** This is an alias of {@link Long.shiftRightUnsigned} */ + shru(numBits: number | Long): Long; + /** + * Returns the difference of this and the specified Long. + * @param subtrahend - Subtrahend + * @returns Difference + */ + subtract(subtrahend: string | number | Long | Timestamp): Long; + /** This is an alias of {@link Long.subtract} */ + sub(subtrahend: string | number | Long | Timestamp): Long; + /** Converts the Long to a 32 bit integer, assuming it is a 32 bit integer. */ + toInt(): number; + /** Converts the Long to a the nearest floating-point representation of this value (double, 53 bit mantissa). */ + toNumber(): number; + /** Converts the Long to a BigInt (arbitrary precision). */ + toBigInt(): bigint; + /** + * Converts this Long to its byte representation. + * @param le - Whether little or big endian, defaults to big endian + * @returns Byte representation + */ + toBytes(le?: boolean): number[]; + /** + * Converts this Long to its little endian byte representation. + * @returns Little endian byte representation + */ + toBytesLE(): number[]; + /** + * Converts this Long to its big endian byte representation. + * @returns Big endian byte representation + */ + toBytesBE(): number[]; + /** + * Converts this Long to signed. + */ + toSigned(): Long; + /** + * Converts the Long to a string written in the specified radix. + * @param radix - Radix (2-36), defaults to 10 + * @throws RangeError If `radix` is out of range + */ + toString(radix?: number): string; + /** Converts this Long to unsigned. */ + toUnsigned(): Long; + /** Returns the bitwise XOR of this Long and the given one. */ + xor(other: Long | number | string): Long; + /** This is an alias of {@link Long.isZero} */ + eqz(): boolean; + /** This is an alias of {@link Long.lessThanOrEqual} */ + le(other: string | number | Long | Timestamp): boolean; + toExtendedJSON(options?: EJSONOptions): number | LongExtended; + static fromExtendedJSON(doc: { + $numberLong: string; + }, options?: EJSONOptions): number | Long; + inspect(): string; +} + +/** @public */ +export declare interface LongExtended { + $numberLong: string; +} + +/** @public */ +export declare type LongWithoutOverrides = new (low: unknown, high?: number, unsigned?: boolean) => { + [P in Exclude]: Long[P]; +}; + +/** @public */ +export declare const LongWithoutOverridesClass: LongWithoutOverrides; + +/** @public */ +declare let Map_2: MapConstructor; +export { Map_2 as Map } + +/** + * A class representation of the BSON MaxKey type. + * @public + * @category BSONType + */ +export declare class MaxKey { + _bsontype: 'MaxKey'; + constructor(); + /* Excluded from this release type: toExtendedJSON */ + /* Excluded from this release type: fromExtendedJSON */ + inspect(): string; +} + +/** @public */ +export declare interface MaxKeyExtended { + $maxKey: 1; +} + +/** + * A class representation of the BSON MinKey type. + * @public + * @category BSONType + */ +export declare class MinKey { + _bsontype: 'MinKey'; + constructor(); + /* Excluded from this release type: toExtendedJSON */ + /* Excluded from this release type: fromExtendedJSON */ + inspect(): string; +} + +/** @public */ +export declare interface MinKeyExtended { + $minKey: 1; +} + +/** + * A class representation of the BSON ObjectId type. + * @public + * @category BSONType + */ +declare class ObjectId { + _bsontype: 'ObjectID'; + /* Excluded from this release type: index */ + static cacheHexString: boolean; + /* Excluded from this release type: [kId] */ + /* Excluded from this release type: __id */ + /** + * Create an ObjectId type + * + * @param inputId - Can be a 24 character hex string, 12 byte binary Buffer, or a number. + */ + constructor(inputId?: string | number | ObjectId | ObjectIdLike | Buffer | Uint8Array); + /** + * The ObjectId bytes + * @readonly + */ + get id(): Buffer; + set id(value: Buffer); + /** + * The generation time of this ObjectId instance + * @deprecated Please use getTimestamp / createFromTime which returns an int32 epoch + */ + get generationTime(): number; + set generationTime(value: number); + /** Returns the ObjectId id as a 24 character hex string representation */ + toHexString(): string; + /* Excluded from this release type: getInc */ + /** + * Generate a 12 byte id buffer used in ObjectId's + * + * @param time - pass in a second based timestamp. + */ + static generate(time?: number): Buffer; + /** + * Converts the id into a 24 character hex string for printing + * + * @param format - The Buffer toString format parameter. + */ + toString(format?: string): string; + /** Converts to its JSON the 24 character hex string representation. */ + toJSON(): string; + /** + * Compares the equality of this ObjectId with `otherID`. + * + * @param otherId - ObjectId instance to compare against. + */ + equals(otherId: string | ObjectId | ObjectIdLike): boolean; + /** Returns the generation date (accurate up to the second) that this ID was generated. */ + getTimestamp(): Date; + /* Excluded from this release type: createPk */ + /** + * Creates an ObjectId from a second based number, with the rest of the ObjectId zeroed out. Used for comparisons or sorting the ObjectId. + * + * @param time - an integer number representing a number of seconds. + */ + static createFromTime(time: number): ObjectId; + /** + * Creates an ObjectId from a hex string representation of an ObjectId. + * + * @param hexString - create a ObjectId from a passed in 24 character hexstring. + */ + static createFromHexString(hexString: string): ObjectId; + /** + * Checks if a value is a valid bson ObjectId + * + * @param id - ObjectId instance to validate. + */ + static isValid(id: string | number | ObjectId | ObjectIdLike | Buffer | Uint8Array): boolean; + /* Excluded from this release type: toExtendedJSON */ + /* Excluded from this release type: fromExtendedJSON */ + inspect(): string; +} +export { ObjectId as ObjectID } +export { ObjectId } + +/** @public */ +export declare interface ObjectIdExtended { + $oid: string; +} + +/** @public */ +export declare interface ObjectIdLike { + id: string | Buffer; + __id?: string; + toHexString(): string; +} + +/** + * Serialize a Javascript object. + * + * @param object - the Javascript object to serialize. + * @returns Buffer object containing the serialized object. + * @public + */ +export declare function serialize(object: Document, options?: SerializeOptions): Buffer; + +/** @public */ +export declare interface SerializeOptions { + /** the serializer will check if keys are valid. */ + checkKeys?: boolean; + /** serialize the javascript functions **(default:false)**. */ + serializeFunctions?: boolean; + /** serialize will not emit undefined fields **(default:true)** */ + ignoreUndefined?: boolean; + /* Excluded from this release type: minInternalBufferSize */ + /** the index in the buffer where we wish to start serializing into */ + index?: number; +} + +/** + * Serialize a Javascript object using a predefined Buffer and index into the buffer, + * useful when pre-allocating the space for serialization. + * + * @param object - the Javascript object to serialize. + * @param finalBuffer - the Buffer you pre-allocated to store the serialized BSON object. + * @returns the index pointing to the last written byte in the buffer. + * @public + */ +export declare function serializeWithBufferAndIndex(object: Document, finalBuffer: Buffer, options?: SerializeOptions): number; + +/** + * Sets the size of the internal serialization buffer. + * + * @param size - The desired size for the internal serialization buffer + * @public + */ +export declare function setInternalBufferSize(size: number): void; + +/** + * @public + * @category BSONType + * */ +export declare class Timestamp extends LongWithoutOverridesClass { + _bsontype: 'Timestamp'; + static readonly MAX_VALUE: Long; + /** + * @param low - A 64-bit Long representing the Timestamp. + */ + constructor(long: Long); + /** + * @param value - A pair of two values indicating timestamp and increment. + */ + constructor(value: { + t: number; + i: number; + }); + /** + * @param low - the low (signed) 32 bits of the Timestamp. + * @param high - the high (signed) 32 bits of the Timestamp. + * @deprecated Please use `Timestamp({ t: high, i: low })` or `Timestamp(Long(low, high))` instead. + */ + constructor(low: number, high: number); + toJSON(): { + $timestamp: string; + }; + /** Returns a Timestamp represented by the given (32-bit) integer value. */ + static fromInt(value: number): Timestamp; + /** Returns a Timestamp representing the given number value, provided that it is a finite number. Otherwise, zero is returned. */ + static fromNumber(value: number): Timestamp; + /** + * Returns a Timestamp for the given high and low bits. Each is assumed to use 32 bits. + * + * @param lowBits - the low 32-bits. + * @param highBits - the high 32-bits. + */ + static fromBits(lowBits: number, highBits: number): Timestamp; + /** + * Returns a Timestamp from the given string, optionally using the given radix. + * + * @param str - the textual representation of the Timestamp. + * @param optRadix - the radix in which the text is written. + */ + static fromString(str: string, optRadix: number): Timestamp; + /* Excluded from this release type: toExtendedJSON */ + /* Excluded from this release type: fromExtendedJSON */ + inspect(): string; +} + +/** @public */ +export declare interface TimestampExtended { + $timestamp: { + t: number; + i: number; + }; +} + +/** @public */ +export declare type TimestampOverrides = '_bsontype' | 'toExtendedJSON' | 'fromExtendedJSON' | 'inspect'; + +/** + * A class representation of the BSON UUID type. + * @public + */ +export declare class UUID { + _bsontype: 'UUID'; + static cacheHexString: boolean; + /* Excluded from this release type: [kId] */ + /* Excluded from this release type: __id */ + /** + * Create an UUID type + * + * @param input - Can be a 32 or 36 character hex string (dashes excluded/included) or a 16 byte binary Buffer. + */ + constructor(input?: string | Buffer | UUID); + /** + * The UUID bytes + * @readonly + */ + get id(): Buffer; + set id(value: Buffer); + /** + * Generate a 16 byte uuid v4 buffer used in UUIDs + */ + /** + * Returns the UUID id as a 32 or 36 character hex string representation, excluding/including dashes (defaults to 36 character dash separated) + * @param includeDashes - should the string exclude dash-separators. + * */ + toHexString(includeDashes?: boolean): string; + /** + * Converts the id into a 36 character (dashes included) hex string, unless a encoding is specified. + */ + toString(encoding?: string): string; + /** + * Converts the id into its JSON string representation. + * A 36 character (dashes included) hex string in the format: xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx + */ + toJSON(): string; + /** + * Compares the equality of this UUID with `otherID`. + * + * @param otherId - UUID instance to compare against. + */ + equals(otherId: string | Buffer | UUID): boolean; + /** + * Creates a Binary instance from the current UUID. + */ + toBinary(): Binary; + /** + * Generates a populated buffer containing a v4 uuid + */ + static generate(): Buffer; + /** + * Checks if a value is a valid bson UUID + * @param input - UUID, string or Buffer to validate. + */ + static isValid(input: string | Buffer | UUID): boolean; + /** + * Creates an UUID from a hex string representation of an UUID. + * @param hexString - 32 or 36 character hex string (dashes excluded/included). + */ + static createFromHexString(hexString: string): UUID; + inspect(): string; +} + +/** @public */ +export declare type UUIDExtended = { + $uuid: string; +}; + +export { } diff --git a/ts-ticket-office-service/node_modules/bson/etc/prepare.js b/ts-ticket-office-service/node_modules/bson/etc/prepare.js new file mode 100755 index 000000000..91e6f3a97 --- /dev/null +++ b/ts-ticket-office-service/node_modules/bson/etc/prepare.js @@ -0,0 +1,19 @@ +#! /usr/bin/env node +var cp = require('child_process'); +var fs = require('fs'); + +var nodeMajorVersion = +process.version.match(/^v(\d+)\.\d+/)[1]; + +if (fs.existsSync('src') && nodeMajorVersion >= 10) { + cp.spawnSync('npm', ['run', 'build'], { stdio: 'inherit', shell: true }); +} else { + if (!fs.existsSync('lib')) { + console.warn('BSON: No compiled javascript present, the library is not installed correctly.'); + if (nodeMajorVersion < 10) { + console.warn( + 'This library can only be compiled in nodejs version 10 or later, currently running: ' + + nodeMajorVersion + ); + } + } +} diff --git a/ts-ticket-office-service/node_modules/bson/index.js b/ts-ticket-office-service/node_modules/bson/index.js deleted file mode 100644 index caed12b74..000000000 --- a/ts-ticket-office-service/node_modules/bson/index.js +++ /dev/null @@ -1,46 +0,0 @@ -var BSON = require('./lib/bson/bson'), - Binary = require('./lib/bson/binary'), - Code = require('./lib/bson/code'), - DBRef = require('./lib/bson/db_ref'), - Decimal128 = require('./lib/bson/decimal128'), - Double = require('./lib/bson/double'), - Int32 = require('./lib/bson/int_32'), - Long = require('./lib/bson/long'), - Map = require('./lib/bson/map'), - MaxKey = require('./lib/bson/max_key'), - MinKey = require('./lib/bson/min_key'), - ObjectId = require('./lib/bson/objectid'), - BSONRegExp = require('./lib/bson/regexp'), - Symbol = require('./lib/bson/symbol'), - Timestamp = require('./lib/bson/timestamp'); - -// BSON MAX VALUES -BSON.BSON_INT32_MAX = 0x7FFFFFFF; -BSON.BSON_INT32_MIN = -0x80000000; - -BSON.BSON_INT64_MAX = Math.pow(2, 63) - 1; -BSON.BSON_INT64_MIN = -Math.pow(2, 63); - -// JS MAX PRECISE VALUES -BSON.JS_INT_MAX = 0x20000000000000; // Any integer up to 2^53 can be precisely represented by a double. -BSON.JS_INT_MIN = -0x20000000000000; // Any integer down to -2^53 can be precisely represented by a double. - -// Add BSON types to function creation -BSON.Binary = Binary; -BSON.Code = Code; -BSON.DBRef = DBRef; -BSON.Decimal128 = Decimal128; -BSON.Double = Double; -BSON.Int32 = Int32; -BSON.Long = Long; -BSON.Map = Map; -BSON.MaxKey = MaxKey; -BSON.MinKey = MinKey; -BSON.ObjectId = ObjectId; -BSON.ObjectID = ObjectId; -BSON.BSONRegExp = BSONRegExp; -BSON.Symbol = Symbol; -BSON.Timestamp = Timestamp; - -// Return the BSON -module.exports = BSON; diff --git a/ts-ticket-office-service/node_modules/bson/lib/binary.js b/ts-ticket-office-service/node_modules/bson/lib/binary.js new file mode 100644 index 000000000..925c1fcfc --- /dev/null +++ b/ts-ticket-office-service/node_modules/bson/lib/binary.js @@ -0,0 +1,247 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.Binary = void 0; +var buffer_1 = require("buffer"); +var ensure_buffer_1 = require("./ensure_buffer"); +var uuid_utils_1 = require("./uuid_utils"); +var uuid_1 = require("./uuid"); +var error_1 = require("./error"); +/** + * A class representation of the BSON Binary type. + * @public + * @category BSONType + */ +var Binary = /** @class */ (function () { + /** + * Create a new Binary instance. + * + * This constructor can accept a string as its first argument. In this case, + * this string will be encoded using ISO-8859-1, **not** using UTF-8. + * This is almost certainly not what you want. Use `new Binary(Buffer.from(string))` + * instead to convert the string to a Buffer using UTF-8 first. + * + * @param buffer - a buffer object containing the binary data. + * @param subType - the option binary type. + */ + function Binary(buffer, subType) { + if (!(this instanceof Binary)) + return new Binary(buffer, subType); + if (!(buffer == null) && + !(typeof buffer === 'string') && + !ArrayBuffer.isView(buffer) && + !(buffer instanceof ArrayBuffer) && + !Array.isArray(buffer)) { + throw new error_1.BSONTypeError('Binary can only be constructed from string, Buffer, TypedArray, or Array'); + } + this.sub_type = subType !== null && subType !== void 0 ? subType : Binary.BSON_BINARY_SUBTYPE_DEFAULT; + if (buffer == null) { + // create an empty binary buffer + this.buffer = buffer_1.Buffer.alloc(Binary.BUFFER_SIZE); + this.position = 0; + } + else { + if (typeof buffer === 'string') { + // string + this.buffer = buffer_1.Buffer.from(buffer, 'binary'); + } + else if (Array.isArray(buffer)) { + // number[] + this.buffer = buffer_1.Buffer.from(buffer); + } + else { + // Buffer | TypedArray | ArrayBuffer + this.buffer = (0, ensure_buffer_1.ensureBuffer)(buffer); + } + this.position = this.buffer.byteLength; + } + } + /** + * Updates this binary with byte_value. + * + * @param byteValue - a single byte we wish to write. + */ + Binary.prototype.put = function (byteValue) { + // If it's a string and a has more than one character throw an error + if (typeof byteValue === 'string' && byteValue.length !== 1) { + throw new error_1.BSONTypeError('only accepts single character String'); + } + else if (typeof byteValue !== 'number' && byteValue.length !== 1) + throw new error_1.BSONTypeError('only accepts single character Uint8Array or Array'); + // Decode the byte value once + var decodedByte; + if (typeof byteValue === 'string') { + decodedByte = byteValue.charCodeAt(0); + } + else if (typeof byteValue === 'number') { + decodedByte = byteValue; + } + else { + decodedByte = byteValue[0]; + } + if (decodedByte < 0 || decodedByte > 255) { + throw new error_1.BSONTypeError('only accepts number in a valid unsigned byte range 0-255'); + } + if (this.buffer.length > this.position) { + this.buffer[this.position++] = decodedByte; + } + else { + var buffer = buffer_1.Buffer.alloc(Binary.BUFFER_SIZE + this.buffer.length); + // Combine the two buffers together + this.buffer.copy(buffer, 0, 0, this.buffer.length); + this.buffer = buffer; + this.buffer[this.position++] = decodedByte; + } + }; + /** + * Writes a buffer or string to the binary. + * + * @param sequence - a string or buffer to be written to the Binary BSON object. + * @param offset - specify the binary of where to write the content. + */ + Binary.prototype.write = function (sequence, offset) { + offset = typeof offset === 'number' ? offset : this.position; + // If the buffer is to small let's extend the buffer + if (this.buffer.length < offset + sequence.length) { + var buffer = buffer_1.Buffer.alloc(this.buffer.length + sequence.length); + this.buffer.copy(buffer, 0, 0, this.buffer.length); + // Assign the new buffer + this.buffer = buffer; + } + if (ArrayBuffer.isView(sequence)) { + this.buffer.set((0, ensure_buffer_1.ensureBuffer)(sequence), offset); + this.position = + offset + sequence.byteLength > this.position ? offset + sequence.length : this.position; + } + else if (typeof sequence === 'string') { + this.buffer.write(sequence, offset, sequence.length, 'binary'); + this.position = + offset + sequence.length > this.position ? offset + sequence.length : this.position; + } + }; + /** + * Reads **length** bytes starting at **position**. + * + * @param position - read from the given position in the Binary. + * @param length - the number of bytes to read. + */ + Binary.prototype.read = function (position, length) { + length = length && length > 0 ? length : this.position; + // Let's return the data based on the type we have + return this.buffer.slice(position, position + length); + }; + /** + * Returns the value of this binary as a string. + * @param asRaw - Will skip converting to a string + * @remarks + * This is handy when calling this function conditionally for some key value pairs and not others + */ + Binary.prototype.value = function (asRaw) { + asRaw = !!asRaw; + // Optimize to serialize for the situation where the data == size of buffer + if (asRaw && this.buffer.length === this.position) { + return this.buffer; + } + // If it's a node.js buffer object + if (asRaw) { + return this.buffer.slice(0, this.position); + } + return this.buffer.toString('binary', 0, this.position); + }; + /** the length of the binary sequence */ + Binary.prototype.length = function () { + return this.position; + }; + Binary.prototype.toJSON = function () { + return this.buffer.toString('base64'); + }; + Binary.prototype.toString = function (format) { + return this.buffer.toString(format); + }; + /** @internal */ + Binary.prototype.toExtendedJSON = function (options) { + options = options || {}; + var base64String = this.buffer.toString('base64'); + var subType = Number(this.sub_type).toString(16); + if (options.legacy) { + return { + $binary: base64String, + $type: subType.length === 1 ? '0' + subType : subType + }; + } + return { + $binary: { + base64: base64String, + subType: subType.length === 1 ? '0' + subType : subType + } + }; + }; + Binary.prototype.toUUID = function () { + if (this.sub_type === Binary.SUBTYPE_UUID) { + return new uuid_1.UUID(this.buffer.slice(0, this.position)); + } + throw new error_1.BSONError("Binary sub_type \"".concat(this.sub_type, "\" is not supported for converting to UUID. Only \"").concat(Binary.SUBTYPE_UUID, "\" is currently supported.")); + }; + /** @internal */ + Binary.fromExtendedJSON = function (doc, options) { + options = options || {}; + var data; + var type; + if ('$binary' in doc) { + if (options.legacy && typeof doc.$binary === 'string' && '$type' in doc) { + type = doc.$type ? parseInt(doc.$type, 16) : 0; + data = buffer_1.Buffer.from(doc.$binary, 'base64'); + } + else { + if (typeof doc.$binary !== 'string') { + type = doc.$binary.subType ? parseInt(doc.$binary.subType, 16) : 0; + data = buffer_1.Buffer.from(doc.$binary.base64, 'base64'); + } + } + } + else if ('$uuid' in doc) { + type = 4; + data = (0, uuid_utils_1.uuidHexStringToBuffer)(doc.$uuid); + } + if (!data) { + throw new error_1.BSONTypeError("Unexpected Binary Extended JSON format ".concat(JSON.stringify(doc))); + } + return new Binary(data, type); + }; + /** @internal */ + Binary.prototype[Symbol.for('nodejs.util.inspect.custom')] = function () { + return this.inspect(); + }; + Binary.prototype.inspect = function () { + var asBuffer = this.value(true); + return "new Binary(Buffer.from(\"".concat(asBuffer.toString('hex'), "\", \"hex\"), ").concat(this.sub_type, ")"); + }; + /** + * Binary default subtype + * @internal + */ + Binary.BSON_BINARY_SUBTYPE_DEFAULT = 0; + /** Initial buffer default size */ + Binary.BUFFER_SIZE = 256; + /** Default BSON type */ + Binary.SUBTYPE_DEFAULT = 0; + /** Function BSON type */ + Binary.SUBTYPE_FUNCTION = 1; + /** Byte Array BSON type */ + Binary.SUBTYPE_BYTE_ARRAY = 2; + /** Deprecated UUID BSON type @deprecated Please use SUBTYPE_UUID */ + Binary.SUBTYPE_UUID_OLD = 3; + /** UUID BSON type */ + Binary.SUBTYPE_UUID = 4; + /** MD5 BSON type */ + Binary.SUBTYPE_MD5 = 5; + /** Encrypted BSON type */ + Binary.SUBTYPE_ENCRYPTED = 6; + /** Column BSON type */ + Binary.SUBTYPE_COLUMN = 7; + /** User BSON type */ + Binary.SUBTYPE_USER_DEFINED = 128; + return Binary; +}()); +exports.Binary = Binary; +Object.defineProperty(Binary.prototype, '_bsontype', { value: 'Binary' }); +//# sourceMappingURL=binary.js.map \ No newline at end of file diff --git a/ts-ticket-office-service/node_modules/bson/lib/binary.js.map b/ts-ticket-office-service/node_modules/bson/lib/binary.js.map new file mode 100644 index 000000000..d01093009 --- /dev/null +++ b/ts-ticket-office-service/node_modules/bson/lib/binary.js.map @@ -0,0 +1 @@ +{"version":3,"file":"binary.js","sourceRoot":"","sources":["../src/binary.ts"],"names":[],"mappings":";;;AAAA,iCAAgC;AAChC,iDAA+C;AAC/C,2CAAqD;AACrD,+BAA4C;AAE5C,iCAAmD;AAmBnD;;;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AC,CAAC;IAExD,kCAAkC;IAClB,kBAAW,GAAG,GAAG,CAAC;IAClC,wBAAwB;IACR,sBAAe,GAAG,CAAC,CAAC;IACpC,yBAAyB;IACT,uBAAgB,GAAG,CAAC,CAAC;IACrC,2BAA2B;IACX,yBAAkB,GAAG,CAAC,CAAC;IACvC,oEAAoE;IACpD,uBAAgB,GAAG,CAAC,CAAC;IACrC,qBAAqB;IACL,mBAAY,GAAG,CAAC,CAAC;IACjC,oBAAoB;IACJ,kBAAW,GAAG,CAAC,CAAC;IAChC,0BAA0B;IACV,wBAAiB,GAAG,CAAC,CAAC;IACtC,uBAAuB;IACP,qBAAc,GAAG,CAAC,CAAC;IACnC,qBAAqB;IACL,2BAAoB,GAAG,GAAG,CAAC;IA0O7C,aAAC;CAAA,AAtQD,IAsQC;AAtQY,wBAAM;AAwQnB,MAAM,CAAC,cAAc,CAAC,MAAM,CAAC,SAAS,EAAE,WAAW,EAAE,EAAE,KAAK,EAAE,QAAQ,EAAE,CAAC,CAAC"} \ No newline at end of file diff --git a/ts-ticket-office-service/node_modules/bson/lib/bson.js b/ts-ticket-office-service/node_modules/bson/lib/bson.js new file mode 100644 index 000000000..21da67a6d --- /dev/null +++ b/ts-ticket-office-service/node_modules/bson/lib/bson.js @@ -0,0 +1,265 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.BSONRegExp = exports.MaxKey = exports.MinKey = exports.Int32 = exports.Double = exports.Timestamp = exports.Long = exports.UUID = exports.ObjectId = exports.Binary = exports.DBRef = exports.BSONSymbol = exports.Map = exports.Code = exports.LongWithoutOverridesClass = exports.EJSON = exports.BSON_INT64_MIN = exports.BSON_INT64_MAX = exports.BSON_INT32_MIN = exports.BSON_INT32_MAX = exports.BSON_DATA_UNDEFINED = exports.BSON_DATA_TIMESTAMP = exports.BSON_DATA_SYMBOL = exports.BSON_DATA_STRING = exports.BSON_DATA_REGEXP = exports.BSON_DATA_OID = exports.BSON_DATA_OBJECT = exports.BSON_DATA_NUMBER = exports.BSON_DATA_NULL = exports.BSON_DATA_MIN_KEY = exports.BSON_DATA_MAX_KEY = exports.BSON_DATA_LONG = exports.BSON_DATA_INT = exports.BSON_DATA_DECIMAL128 = exports.BSON_DATA_DBPOINTER = exports.BSON_DATA_DATE = exports.BSON_DATA_CODE_W_SCOPE = exports.BSON_DATA_CODE = exports.BSON_DATA_BOOLEAN = exports.BSON_DATA_BINARY = exports.BSON_DATA_ARRAY = exports.BSON_BINARY_SUBTYPE_COLUMN = exports.BSON_BINARY_SUBTYPE_ENCRYPTED = exports.BSON_BINARY_SUBTYPE_UUID_NEW = exports.BSON_BINARY_SUBTYPE_UUID = exports.BSON_BINARY_SUBTYPE_USER_DEFINED = exports.BSON_BINARY_SUBTYPE_MD5 = exports.BSON_BINARY_SUBTYPE_FUNCTION = exports.BSON_BINARY_SUBTYPE_DEFAULT = exports.BSON_BINARY_SUBTYPE_BYTE_ARRAY = void 0; +exports.deserializeStream = exports.calculateObjectSize = exports.deserialize = exports.serializeWithBufferAndIndex = exports.serialize = exports.setInternalBufferSize = exports.BSONTypeError = exports.BSONError = exports.ObjectID = exports.Decimal128 = void 0; +var buffer_1 = require("buffer"); +var binary_1 = require("./binary"); +Object.defineProperty(exports, "Binary", { enumerable: true, get: function () { return binary_1.Binary; } }); +var code_1 = require("./code"); +Object.defineProperty(exports, "Code", { enumerable: true, get: function () { return code_1.Code; } }); +var db_ref_1 = require("./db_ref"); +Object.defineProperty(exports, "DBRef", { enumerable: true, get: function () { return db_ref_1.DBRef; } }); +var decimal128_1 = require("./decimal128"); +Object.defineProperty(exports, "Decimal128", { enumerable: true, get: function () { return decimal128_1.Decimal128; } }); +var double_1 = require("./double"); +Object.defineProperty(exports, "Double", { enumerable: true, get: function () { return double_1.Double; } }); +var ensure_buffer_1 = require("./ensure_buffer"); +var extended_json_1 = require("./extended_json"); +var int_32_1 = require("./int_32"); +Object.defineProperty(exports, "Int32", { enumerable: true, get: function () { return int_32_1.Int32; } }); +var long_1 = require("./long"); +Object.defineProperty(exports, "Long", { enumerable: true, get: function () { return long_1.Long; } }); +var map_1 = require("./map"); +Object.defineProperty(exports, "Map", { enumerable: true, get: function () { return map_1.Map; } }); +var max_key_1 = require("./max_key"); +Object.defineProperty(exports, "MaxKey", { enumerable: true, get: function () { return max_key_1.MaxKey; } }); +var min_key_1 = require("./min_key"); +Object.defineProperty(exports, "MinKey", { enumerable: true, get: function () { return min_key_1.MinKey; } }); +var objectid_1 = require("./objectid"); +Object.defineProperty(exports, "ObjectId", { enumerable: true, get: function () { return objectid_1.ObjectId; } }); +Object.defineProperty(exports, "ObjectID", { enumerable: true, get: function () { return objectid_1.ObjectId; } }); +var error_1 = require("./error"); +var calculate_size_1 = require("./parser/calculate_size"); +// Parts of the parser +var deserializer_1 = require("./parser/deserializer"); +var serializer_1 = require("./parser/serializer"); +var regexp_1 = require("./regexp"); +Object.defineProperty(exports, "BSONRegExp", { enumerable: true, get: function () { return regexp_1.BSONRegExp; } }); +var symbol_1 = require("./symbol"); +Object.defineProperty(exports, "BSONSymbol", { enumerable: true, get: function () { return symbol_1.BSONSymbol; } }); +var timestamp_1 = require("./timestamp"); +Object.defineProperty(exports, "Timestamp", { enumerable: true, get: function () { return timestamp_1.Timestamp; } }); +var uuid_1 = require("./uuid"); +Object.defineProperty(exports, "UUID", { enumerable: true, get: function () { return uuid_1.UUID; } }); +var binary_2 = require("./binary"); +var code_2 = require("./code"); +var constants_1 = require("./constants"); +Object.defineProperty(exports, "BSON_BINARY_SUBTYPE_BYTE_ARRAY", { enumerable: true, get: function () { return constants_1.BSON_BINARY_SUBTYPE_BYTE_ARRAY; } }); +Object.defineProperty(exports, "BSON_BINARY_SUBTYPE_DEFAULT", { enumerable: true, get: function () { return constants_1.BSON_BINARY_SUBTYPE_DEFAULT; } }); +Object.defineProperty(exports, "BSON_BINARY_SUBTYPE_FUNCTION", { enumerable: true, get: function () { return constants_1.BSON_BINARY_SUBTYPE_FUNCTION; } }); +Object.defineProperty(exports, "BSON_BINARY_SUBTYPE_MD5", { enumerable: true, get: function () { return constants_1.BSON_BINARY_SUBTYPE_MD5; } }); +Object.defineProperty(exports, "BSON_BINARY_SUBTYPE_USER_DEFINED", { enumerable: true, get: function () { return constants_1.BSON_BINARY_SUBTYPE_USER_DEFINED; } }); +Object.defineProperty(exports, "BSON_BINARY_SUBTYPE_UUID", { enumerable: true, get: function () { return constants_1.BSON_BINARY_SUBTYPE_UUID; } }); +Object.defineProperty(exports, "BSON_BINARY_SUBTYPE_UUID_NEW", { enumerable: true, get: function () { return constants_1.BSON_BINARY_SUBTYPE_UUID_NEW; } }); +Object.defineProperty(exports, "BSON_BINARY_SUBTYPE_ENCRYPTED", { enumerable: true, get: function () { return constants_1.BSON_BINARY_SUBTYPE_ENCRYPTED; } }); +Object.defineProperty(exports, "BSON_BINARY_SUBTYPE_COLUMN", { enumerable: true, get: function () { return constants_1.BSON_BINARY_SUBTYPE_COLUMN; } }); +Object.defineProperty(exports, "BSON_DATA_ARRAY", { enumerable: true, get: function () { return constants_1.BSON_DATA_ARRAY; } }); +Object.defineProperty(exports, "BSON_DATA_BINARY", { enumerable: true, get: function () { return constants_1.BSON_DATA_BINARY; } }); +Object.defineProperty(exports, "BSON_DATA_BOOLEAN", { enumerable: true, get: function () { return constants_1.BSON_DATA_BOOLEAN; } }); +Object.defineProperty(exports, "BSON_DATA_CODE", { enumerable: true, get: function () { return constants_1.BSON_DATA_CODE; } }); +Object.defineProperty(exports, "BSON_DATA_CODE_W_SCOPE", { enumerable: true, get: function () { return constants_1.BSON_DATA_CODE_W_SCOPE; } }); +Object.defineProperty(exports, "BSON_DATA_DATE", { enumerable: true, get: function () { return constants_1.BSON_DATA_DATE; } }); +Object.defineProperty(exports, "BSON_DATA_DBPOINTER", { enumerable: true, get: function () { return constants_1.BSON_DATA_DBPOINTER; } }); +Object.defineProperty(exports, "BSON_DATA_DECIMAL128", { enumerable: true, get: function () { return constants_1.BSON_DATA_DECIMAL128; } }); +Object.defineProperty(exports, "BSON_DATA_INT", { enumerable: true, get: function () { return constants_1.BSON_DATA_INT; } }); +Object.defineProperty(exports, "BSON_DATA_LONG", { enumerable: true, get: function () { return constants_1.BSON_DATA_LONG; } }); +Object.defineProperty(exports, "BSON_DATA_MAX_KEY", { enumerable: true, get: function () { return constants_1.BSON_DATA_MAX_KEY; } }); +Object.defineProperty(exports, "BSON_DATA_MIN_KEY", { enumerable: true, get: function () { return constants_1.BSON_DATA_MIN_KEY; } }); +Object.defineProperty(exports, "BSON_DATA_NULL", { enumerable: true, get: function () { return constants_1.BSON_DATA_NULL; } }); +Object.defineProperty(exports, "BSON_DATA_NUMBER", { enumerable: true, get: function () { return constants_1.BSON_DATA_NUMBER; } }); +Object.defineProperty(exports, "BSON_DATA_OBJECT", { enumerable: true, get: function () { return constants_1.BSON_DATA_OBJECT; } }); +Object.defineProperty(exports, "BSON_DATA_OID", { enumerable: true, get: function () { return constants_1.BSON_DATA_OID; } }); +Object.defineProperty(exports, "BSON_DATA_REGEXP", { enumerable: true, get: function () { return constants_1.BSON_DATA_REGEXP; } }); +Object.defineProperty(exports, "BSON_DATA_STRING", { enumerable: true, get: function () { return constants_1.BSON_DATA_STRING; } }); +Object.defineProperty(exports, "BSON_DATA_SYMBOL", { enumerable: true, get: function () { return constants_1.BSON_DATA_SYMBOL; } }); +Object.defineProperty(exports, "BSON_DATA_TIMESTAMP", { enumerable: true, get: function () { return constants_1.BSON_DATA_TIMESTAMP; } }); +Object.defineProperty(exports, "BSON_DATA_UNDEFINED", { enumerable: true, get: function () { return constants_1.BSON_DATA_UNDEFINED; } }); +Object.defineProperty(exports, "BSON_INT32_MAX", { enumerable: true, get: function () { return constants_1.BSON_INT32_MAX; } }); +Object.defineProperty(exports, "BSON_INT32_MIN", { enumerable: true, get: function () { return constants_1.BSON_INT32_MIN; } }); +Object.defineProperty(exports, "BSON_INT64_MAX", { enumerable: true, get: function () { return constants_1.BSON_INT64_MAX; } }); +Object.defineProperty(exports, "BSON_INT64_MIN", { enumerable: true, get: function () { return constants_1.BSON_INT64_MIN; } }); +var db_ref_2 = require("./db_ref"); +var decimal128_2 = require("./decimal128"); +var double_2 = require("./double"); +var extended_json_2 = require("./extended_json"); +Object.defineProperty(exports, "EJSON", { enumerable: true, get: function () { return extended_json_2.EJSON; } }); +var int_32_2 = require("./int_32"); +var long_2 = require("./long"); +var max_key_2 = require("./max_key"); +var min_key_2 = require("./min_key"); +var objectid_2 = require("./objectid"); +var regexp_2 = require("./regexp"); +var symbol_2 = require("./symbol"); +var timestamp_2 = require("./timestamp"); +Object.defineProperty(exports, "LongWithoutOverridesClass", { enumerable: true, get: function () { return timestamp_2.LongWithoutOverridesClass; } }); +var uuid_2 = require("./uuid"); +var error_2 = require("./error"); +Object.defineProperty(exports, "BSONError", { enumerable: true, get: function () { return error_2.BSONError; } }); +Object.defineProperty(exports, "BSONTypeError", { enumerable: true, get: function () { return error_2.BSONTypeError; } }); +/** @internal */ +// Default Max Size +var MAXSIZE = 1024 * 1024 * 17; +// Current Internal Temporary Serialization Buffer +var buffer = buffer_1.Buffer.alloc(MAXSIZE); +/** + * Sets the size of the internal serialization buffer. + * + * @param size - The desired size for the internal serialization buffer + * @public + */ +function setInternalBufferSize(size) { + // Resize the internal serialization buffer if needed + if (buffer.length < size) { + buffer = buffer_1.Buffer.alloc(size); + } +} +exports.setInternalBufferSize = setInternalBufferSize; +/** + * Serialize a Javascript object. + * + * @param object - the Javascript object to serialize. + * @returns Buffer object containing the serialized object. + * @public + */ +function serialize(object, options) { + if (options === void 0) { options = {}; } + // Unpack the options + var checkKeys = typeof options.checkKeys === 'boolean' ? options.checkKeys : false; + var serializeFunctions = typeof options.serializeFunctions === 'boolean' ? options.serializeFunctions : false; + var ignoreUndefined = typeof options.ignoreUndefined === 'boolean' ? options.ignoreUndefined : true; + var minInternalBufferSize = typeof options.minInternalBufferSize === 'number' ? options.minInternalBufferSize : MAXSIZE; + // Resize the internal serialization buffer if needed + if (buffer.length < minInternalBufferSize) { + buffer = buffer_1.Buffer.alloc(minInternalBufferSize); + } + // Attempt to serialize + var serializationIndex = (0, serializer_1.serializeInto)(buffer, object, checkKeys, 0, 0, serializeFunctions, ignoreUndefined, []); + // Create the final buffer + var finishedBuffer = buffer_1.Buffer.alloc(serializationIndex); + // Copy into the finished buffer + buffer.copy(finishedBuffer, 0, 0, finishedBuffer.length); + // Return the buffer + return finishedBuffer; +} +exports.serialize = serialize; +/** + * Serialize a Javascript object using a predefined Buffer and index into the buffer, + * useful when pre-allocating the space for serialization. + * + * @param object - the Javascript object to serialize. + * @param finalBuffer - the Buffer you pre-allocated to store the serialized BSON object. + * @returns the index pointing to the last written byte in the buffer. + * @public + */ +function serializeWithBufferAndIndex(object, finalBuffer, options) { + if (options === void 0) { options = {}; } + // Unpack the options + var checkKeys = typeof options.checkKeys === 'boolean' ? options.checkKeys : false; + var serializeFunctions = typeof options.serializeFunctions === 'boolean' ? options.serializeFunctions : false; + var ignoreUndefined = typeof options.ignoreUndefined === 'boolean' ? options.ignoreUndefined : true; + var startIndex = typeof options.index === 'number' ? options.index : 0; + // Attempt to serialize + var serializationIndex = (0, serializer_1.serializeInto)(buffer, object, checkKeys, 0, 0, serializeFunctions, ignoreUndefined); + buffer.copy(finalBuffer, startIndex, 0, serializationIndex); + // Return the index + return startIndex + serializationIndex - 1; +} +exports.serializeWithBufferAndIndex = serializeWithBufferAndIndex; +/** + * Deserialize data as BSON. + * + * @param buffer - the buffer containing the serialized set of BSON documents. + * @returns returns the deserialized Javascript Object. + * @public + */ +function deserialize(buffer, options) { + if (options === void 0) { options = {}; } + return (0, deserializer_1.deserialize)(buffer instanceof buffer_1.Buffer ? buffer : (0, ensure_buffer_1.ensureBuffer)(buffer), options); +} +exports.deserialize = deserialize; +/** + * Calculate the bson size for a passed in Javascript object. + * + * @param object - the Javascript object to calculate the BSON byte size for + * @returns size of BSON object in bytes + * @public + */ +function calculateObjectSize(object, options) { + if (options === void 0) { options = {}; } + options = options || {}; + var serializeFunctions = typeof options.serializeFunctions === 'boolean' ? options.serializeFunctions : false; + var ignoreUndefined = typeof options.ignoreUndefined === 'boolean' ? options.ignoreUndefined : true; + return (0, calculate_size_1.calculateObjectSize)(object, serializeFunctions, ignoreUndefined); +} +exports.calculateObjectSize = calculateObjectSize; +/** + * Deserialize stream data as BSON documents. + * + * @param data - the buffer containing the serialized set of BSON documents. + * @param startIndex - the start index in the data Buffer where the deserialization is to start. + * @param numberOfDocuments - number of documents to deserialize. + * @param documents - an array where to store the deserialized documents. + * @param docStartIndex - the index in the documents array from where to start inserting documents. + * @param options - additional options used for the deserialization. + * @returns next index in the buffer after deserialization **x** numbers of documents. + * @public + */ +function deserializeStream(data, startIndex, numberOfDocuments, documents, docStartIndex, options) { + var internalOptions = Object.assign({ allowObjectSmallerThanBufferSize: true, index: 0 }, options); + var bufferData = (0, ensure_buffer_1.ensureBuffer)(data); + var index = startIndex; + // Loop over all documents + for (var i = 0; i < numberOfDocuments; i++) { + // Find size of the document + var size = bufferData[index] | + (bufferData[index + 1] << 8) | + (bufferData[index + 2] << 16) | + (bufferData[index + 3] << 24); + // Update options with index + internalOptions.index = index; + // Parse the document at this point + documents[docStartIndex + i] = (0, deserializer_1.deserialize)(bufferData, internalOptions); + // Adjust index by the document size + index = index + size; + } + // Return object containing end index of parsing and list of documents + return index; +} +exports.deserializeStream = deserializeStream; +/** + * BSON default export + * @deprecated Please use named exports + * @privateRemarks + * We want to someday deprecate the default export, + * so none of the new TS types are being exported on the default + * @public + */ +var BSON = { + Binary: binary_1.Binary, + Code: code_1.Code, + DBRef: db_ref_1.DBRef, + Decimal128: decimal128_1.Decimal128, + Double: double_1.Double, + Int32: int_32_1.Int32, + Long: long_1.Long, + UUID: uuid_1.UUID, + Map: map_1.Map, + MaxKey: max_key_1.MaxKey, + MinKey: min_key_1.MinKey, + ObjectId: objectid_1.ObjectId, + ObjectID: objectid_1.ObjectId, + BSONRegExp: regexp_1.BSONRegExp, + BSONSymbol: symbol_1.BSONSymbol, + Timestamp: timestamp_1.Timestamp, + EJSON: extended_json_1.EJSON, + setInternalBufferSize: setInternalBufferSize, + serialize: serialize, + serializeWithBufferAndIndex: serializeWithBufferAndIndex, + deserialize: deserialize, + calculateObjectSize: calculateObjectSize, + deserializeStream: deserializeStream, + BSONError: error_1.BSONError, + BSONTypeError: error_1.BSONTypeError +}; +exports.default = BSON; +//# sourceMappingURL=bson.js.map \ No newline at end of file diff --git a/ts-ticket-office-service/node_modules/bson/lib/bson.js.map b/ts-ticket-office-service/node_modules/bson/lib/bson.js.map new file mode 100644 index 000000000..742d1ce54 --- /dev/null +++ b/ts-ticket-office-service/node_modules/bson/lib/bson.js.map @@ -0,0 +1 @@ +{"version":3,"file":"bson.js","sourceRoot":"","sources":["../src/bson.ts"],"names":[],"mappings":";;;;AAAA,iCAAgC;AAChC,mCAAkC;AAoFhC,uFApFO,eAAM,OAoFP;AAnFR,+BAA8B;AA+E5B,qFA/EO,WAAI,OA+EP;AA9EN,mCAAiC;AAiF/B,sFAjFO,cAAK,OAiFP;AAhFP,2CAA0C;AA2FxC,2FA3FO,uBAAU,OA2FP;AA1FZ,mCAAkC;AAqFhC,uFArFO,eAAM,OAqFP;AApFR,iDAA+C;AAC/C,iDAAwC;AACxC,mCAAiC;AAmF/B,sFAnFO,cAAK,OAmFP;AAlFP,+BAA8B;AA+E5B,qFA/EO,WAAI,OA+EP;AA9EN,6BAA4B;AAwE1B,oFAxEO,SAAG,OAwEP;AAvEL,qCAAmC;AAkFjC,uFAlFO,gBAAM,OAkFP;AAjFR,qCAAmC;AAgFjC,uFAhFO,gBAAM,OAgFP;AA/ER,uCAAsC;AAyEpC,yFAzEO,mBAAQ,OAyEP;AAaI,yFAtFL,mBAAQ,OAsFK;AArFtB,iCAAmD;AACnD,0DAA6F;AAC7F,sBAAsB;AACtB,sDAA+F;AAC/F,kDAA2F;AAC3F,mCAAsC;AA2EpC,2FA3EO,mBAAU,OA2EP;AA1EZ,mCAAsC;AA+DpC,2FA/DO,mBAAU,OA+DP;AA9DZ,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BAAA;IACT,aAAa,uBAAA;CACd,CAAC;AACF,kBAAe,IAAI,CAAC"} \ No newline at end of file diff --git a/ts-ticket-office-service/node_modules/bson/lib/bson/binary.js b/ts-ticket-office-service/node_modules/bson/lib/bson/binary.js deleted file mode 100644 index 793b56f92..000000000 --- a/ts-ticket-office-service/node_modules/bson/lib/bson/binary.js +++ /dev/null @@ -1,347 +0,0 @@ -/** - * Module dependencies. - * @ignore - */ - -// Test if we're in Node via presence of "global" not absence of "window" -// to support hybrid environments like Electron -if(typeof global !== 'undefined') { - var Buffer = require('buffer').Buffer; // TODO just use global Buffer -} - -/** - * A class representation of the BSON Binary type. - * - * Sub types - * - **BSON.BSON_BINARY_SUBTYPE_DEFAULT**, default BSON type. - * - **BSON.BSON_BINARY_SUBTYPE_FUNCTION**, BSON function type. - * - **BSON.BSON_BINARY_SUBTYPE_BYTE_ARRAY**, BSON byte array type. - * - **BSON.BSON_BINARY_SUBTYPE_UUID**, BSON uuid type. - * - **BSON.BSON_BINARY_SUBTYPE_MD5**, BSON md5 type. - * - **BSON.BSON_BINARY_SUBTYPE_USER_DEFINED**, BSON user defined type. - * - * @class - * @param {Buffer} buffer a buffer object containing the binary data. - * @param {Number} [subType] the option binary type. - * @return {Binary} - */ -function Binary(buffer, subType) { - if(!(this instanceof Binary)) return new Binary(buffer, subType); - - this._bsontype = 'Binary'; - - if(buffer instanceof Number) { - this.sub_type = buffer; - this.position = 0; - } else { - this.sub_type = subType == null ? BSON_BINARY_SUBTYPE_DEFAULT : subType; - this.position = 0; - } - - if(buffer != null && !(buffer instanceof Number)) { - // Only accept Buffer, Uint8Array or Arrays - if(typeof buffer == 'string') { - // Different ways of writing the length of the string for the different types - if(typeof Buffer != 'undefined') { - this.buffer = new Buffer(buffer); - } else if(typeof Uint8Array != 'undefined' || (Object.prototype.toString.call(buffer) == '[object Array]')) { - this.buffer = writeStringToArray(buffer); - } else { - throw new Error("only String, Buffer, Uint8Array or Array accepted"); - } - } else { - this.buffer = buffer; - } - this.position = buffer.length; - } else { - if(typeof Buffer != 'undefined') { - this.buffer = new Buffer(Binary.BUFFER_SIZE); - } else if(typeof Uint8Array != 'undefined'){ - this.buffer = new Uint8Array(new ArrayBuffer(Binary.BUFFER_SIZE)); - } else { - this.buffer = new Array(Binary.BUFFER_SIZE); - } - // Set position to start of buffer - this.position = 0; - } -}; - -/** - * Updates this binary with byte_value. - * - * @method - * @param {string} byte_value a single byte we wish to write. - */ -Binary.prototype.put = function put(byte_value) { - // If it's a string and a has more than one character throw an error - if(byte_value['length'] != null && typeof byte_value != 'number' && byte_value.length != 1) throw new Error("only accepts single character String, Uint8Array or Array"); - if(typeof byte_value != 'number' && byte_value < 0 || byte_value > 255) throw new Error("only accepts number in a valid unsigned byte range 0-255"); - - // Decode the byte value once - var decoded_byte = null; - if(typeof byte_value == 'string') { - decoded_byte = byte_value.charCodeAt(0); - } else if(byte_value['length'] != null) { - decoded_byte = byte_value[0]; - } else { - decoded_byte = byte_value; - } - - if(this.buffer.length > this.position) { - this.buffer[this.position++] = decoded_byte; - } else { - if(typeof Buffer != 'undefined' && Buffer.isBuffer(this.buffer)) { - // Create additional overflow buffer - var buffer = new Buffer(Binary.BUFFER_SIZE + this.buffer.length); - // Combine the two buffers together - this.buffer.copy(buffer, 0, 0, this.buffer.length); - this.buffer = buffer; - this.buffer[this.position++] = decoded_byte; - } else { - var buffer = null; - // Create a new buffer (typed or normal array) - if(Object.prototype.toString.call(this.buffer) == '[object Uint8Array]') { - buffer = new Uint8Array(new ArrayBuffer(Binary.BUFFER_SIZE + this.buffer.length)); - } else { - buffer = new Array(Binary.BUFFER_SIZE + this.buffer.length); - } - - // We need to copy all the content to the new array - for(var i = 0; i < this.buffer.length; i++) { - buffer[i] = this.buffer[i]; - } - - // Reassign the buffer - this.buffer = buffer; - // Write the byte - this.buffer[this.position++] = decoded_byte; - } - } -}; - -/** - * Writes a buffer or string to the binary. - * - * @method - * @param {(Buffer|string)} string a string or buffer to be written to the Binary BSON object. - * @param {number} offset specify the binary of where to write the content. - * @return {null} - */ -Binary.prototype.write = function write(string, offset) { - offset = typeof offset == 'number' ? offset : this.position; - - // If the buffer is to small let's extend the buffer - if(this.buffer.length < offset + string.length) { - var buffer = null; - // If we are in node.js - if(typeof Buffer != 'undefined' && Buffer.isBuffer(this.buffer)) { - buffer = new Buffer(this.buffer.length + string.length); - this.buffer.copy(buffer, 0, 0, this.buffer.length); - } else if(Object.prototype.toString.call(this.buffer) == '[object Uint8Array]') { - // Create a new buffer - buffer = new Uint8Array(new ArrayBuffer(this.buffer.length + string.length)) - // Copy the content - for(var i = 0; i < this.position; i++) { - buffer[i] = this.buffer[i]; - } - } - - // Assign the new buffer - this.buffer = buffer; - } - - if(typeof Buffer != 'undefined' && Buffer.isBuffer(string) && Buffer.isBuffer(this.buffer)) { - string.copy(this.buffer, offset, 0, string.length); - this.position = (offset + string.length) > this.position ? (offset + string.length) : this.position; - // offset = string.length - } else if(typeof Buffer != 'undefined' && typeof string == 'string' && Buffer.isBuffer(this.buffer)) { - this.buffer.write(string, offset, 'binary'); - this.position = (offset + string.length) > this.position ? (offset + string.length) : this.position; - // offset = string.length; - } else if(Object.prototype.toString.call(string) == '[object Uint8Array]' - || Object.prototype.toString.call(string) == '[object Array]' && typeof string != 'string') { - for(var i = 0; i < string.length; i++) { - this.buffer[offset++] = string[i]; - } - - this.position = offset > this.position ? offset : this.position; - } else if(typeof string == 'string') { - for(var i = 0; i < string.length; i++) { - this.buffer[offset++] = string.charCodeAt(i); - } - - this.position = offset > this.position ? offset : this.position; - } -}; - -/** - * Reads **length** bytes starting at **position**. - * - * @method - * @param {number} position read from the given position in the Binary. - * @param {number} length the number of bytes to read. - * @return {Buffer} - */ -Binary.prototype.read = function read(position, length) { - length = length && length > 0 - ? length - : this.position; - - // Let's return the data based on the type we have - if(this.buffer['slice']) { - return this.buffer.slice(position, position + length); - } else { - // Create a buffer to keep the result - var buffer = typeof Uint8Array != 'undefined' ? new Uint8Array(new ArrayBuffer(length)) : new Array(length); - for(var i = 0; i < length; i++) { - buffer[i] = this.buffer[position++]; - } - } - // Return the buffer - return buffer; -}; - -/** - * Returns the value of this binary as a string. - * - * @method - * @return {string} - */ -Binary.prototype.value = function value(asRaw) { - asRaw = asRaw == null ? false : asRaw; - - // Optimize to serialize for the situation where the data == size of buffer - if(asRaw && typeof Buffer != 'undefined' && Buffer.isBuffer(this.buffer) && this.buffer.length == this.position) - return this.buffer; - - // If it's a node.js buffer object - if(typeof Buffer != 'undefined' && Buffer.isBuffer(this.buffer)) { - return asRaw ? this.buffer.slice(0, this.position) : this.buffer.toString('binary', 0, this.position); - } else { - if(asRaw) { - // we support the slice command use it - if(this.buffer['slice'] != null) { - return this.buffer.slice(0, this.position); - } else { - // Create a new buffer to copy content to - var newBuffer = Object.prototype.toString.call(this.buffer) == '[object Uint8Array]' ? new Uint8Array(new ArrayBuffer(this.position)) : new Array(this.position); - // Copy content - for(var i = 0; i < this.position; i++) { - newBuffer[i] = this.buffer[i]; - } - // Return the buffer - return newBuffer; - } - } else { - return convertArraytoUtf8BinaryString(this.buffer, 0, this.position); - } - } -}; - -/** - * Length. - * - * @method - * @return {number} the length of the binary. - */ -Binary.prototype.length = function length() { - return this.position; -}; - -/** - * @ignore - */ -Binary.prototype.toJSON = function() { - return this.buffer != null ? this.buffer.toString('base64') : ''; -} - -/** - * @ignore - */ -Binary.prototype.toString = function(format) { - return this.buffer != null ? this.buffer.slice(0, this.position).toString(format) : ''; -} - -/** - * Binary default subtype - * @ignore - */ -var BSON_BINARY_SUBTYPE_DEFAULT = 0; - -/** - * @ignore - */ -var writeStringToArray = function(data) { - // Create a buffer - var buffer = typeof Uint8Array != 'undefined' ? new Uint8Array(new ArrayBuffer(data.length)) : new Array(data.length); - // Write the content to the buffer - for(var i = 0; i < data.length; i++) { - buffer[i] = data.charCodeAt(i); - } - // Write the string to the buffer - return buffer; -} - -/** - * Convert Array ot Uint8Array to Binary String - * - * @ignore - */ -var convertArraytoUtf8BinaryString = function(byteArray, startIndex, endIndex) { - var result = ""; - for(var i = startIndex; i < endIndex; i++) { - result = result + String.fromCharCode(byteArray[i]); - } - return result; -}; - -Binary.BUFFER_SIZE = 256; - -/** - * Default BSON type - * - * @classconstant SUBTYPE_DEFAULT - **/ -Binary.SUBTYPE_DEFAULT = 0; -/** - * Function BSON type - * - * @classconstant SUBTYPE_DEFAULT - **/ -Binary.SUBTYPE_FUNCTION = 1; -/** - * Byte Array BSON type - * - * @classconstant SUBTYPE_DEFAULT - **/ -Binary.SUBTYPE_BYTE_ARRAY = 2; -/** - * OLD UUID BSON type - * - * @classconstant SUBTYPE_DEFAULT - **/ -Binary.SUBTYPE_UUID_OLD = 3; -/** - * UUID BSON type - * - * @classconstant SUBTYPE_DEFAULT - **/ -Binary.SUBTYPE_UUID = 4; -/** - * MD5 BSON type - * - * @classconstant SUBTYPE_DEFAULT - **/ -Binary.SUBTYPE_MD5 = 5; -/** - * User BSON type - * - * @classconstant SUBTYPE_DEFAULT - **/ -Binary.SUBTYPE_USER_DEFINED = 128; - -/** - * Expose. - */ -module.exports = Binary; -module.exports.Binary = Binary; diff --git a/ts-ticket-office-service/node_modules/bson/lib/bson/bson.js b/ts-ticket-office-service/node_modules/bson/lib/bson/bson.js deleted file mode 100644 index b98887eaa..000000000 --- a/ts-ticket-office-service/node_modules/bson/lib/bson/bson.js +++ /dev/null @@ -1,358 +0,0 @@ -"use strict" - -var writeIEEE754 = require('./float_parser').writeIEEE754, - readIEEE754 = require('./float_parser').readIEEE754, - Map = require('./map'), - Long = require('./long'), - Double = require('./double'), - Timestamp = require('./timestamp'), - ObjectID = require('./objectid'), - BSONRegExp = require('./regexp'), - Symbol = require('./symbol'), - Int32 = require('./int_32'), - Code = require('./code'), - Decimal128 = require('./decimal128'), - MinKey = require('./min_key'), - MaxKey = require('./max_key'), - DBRef = require('./db_ref'), - Binary = require('./binary'); - -// Parts of the parser -var deserialize = require('./parser/deserializer'), - serializer = require('./parser/serializer'), - calculateObjectSize = require('./parser/calculate_size'); - -/** - * @ignore - * @api private - */ -// Max Size -var MAXSIZE = (1024*1024*17); -// Max Document Buffer size -var buffer = new Buffer(MAXSIZE); - -var BSON = function() { -} - -/** - * Serialize a Javascript object. - * - * @param {Object} object the Javascript object to serialize. - * @param {Boolean} [options.checkKeys] the serializer will check if keys are valid. - * @param {Boolean} [options.serializeFunctions=false] serialize the javascript functions **(default:false)**. - * @param {Boolean} [options.ignoreUndefined=true] ignore undefined fields **(default:true)**. - * @return {Buffer} returns the Buffer object containing the serialized object. - * @api public - */ -BSON.prototype.serialize = function serialize(object, options) { - options = options || {}; - // Unpack the options - var checkKeys = typeof options.checkKeys == 'boolean' - ? options.checkKeys : false; - var serializeFunctions = typeof options.serializeFunctions == 'boolean' - ? options.serializeFunctions : false; - var ignoreUndefined = typeof options.ignoreUndefined == 'boolean' - ? options.ignoreUndefined : true; - - // Attempt to serialize - var serializationIndex = serializer(buffer, object, checkKeys, 0, 0, serializeFunctions, ignoreUndefined, []); - // Create the final buffer - var finishedBuffer = new Buffer(serializationIndex); - // Copy into the finished buffer - buffer.copy(finishedBuffer, 0, 0, finishedBuffer.length); - // Return the buffer - return finishedBuffer; -} - -/** - * Serialize a Javascript object using a predefined Buffer and index into the buffer, useful when pre-allocating the space for serialization. - * - * @param {Object} object the Javascript object to serialize. - * @param {Buffer} buffer the Buffer you pre-allocated to store the serialized BSON object. - * @param {Boolean} [options.checkKeys] the serializer will check if keys are valid. - * @param {Boolean} [options.serializeFunctions=false] serialize the javascript functions **(default:false)**. - * @param {Boolean} [options.ignoreUndefined=true] ignore undefined fields **(default:true)**. - * @param {Number} [options.index] the index in the buffer where we wish to start serializing into. - * @return {Number} returns the index pointing to the last written byte in the buffer. - * @api public - */ -BSON.prototype.serializeWithBufferAndIndex = function(object, finalBuffer, options) { - options = options || {}; - // Unpack the options - var checkKeys = typeof options.checkKeys == 'boolean' - ? options.checkKeys : false; - var serializeFunctions = typeof options.serializeFunctions == 'boolean' - ? options.serializeFunctions : false; - var ignoreUndefined = typeof options.ignoreUndefined == 'boolean' - ? options.ignoreUndefined : true; - var startIndex = typeof options.index == 'number' - ? options.index : 0; - - // Attempt to serialize - var serializationIndex = serializer(buffer, object, checkKeys, startIndex || 0, 0, serializeFunctions, ignoreUndefined); - buffer.copy(finalBuffer, startIndex, 0, serializationIndex); - - // Return the index - return serializationIndex - 1; -} - -/** - * Deserialize data as BSON. - * - * @param {Buffer} buffer the buffer containing the serialized set of BSON documents. - * @param {Object} [options.evalFunctions=false] evaluate functions in the BSON document scoped to the object deserialized. - * @param {Object} [options.cacheFunctions=false] cache evaluated functions for reuse. - * @param {Object} [options.cacheFunctionsCrc32=false] use a crc32 code for caching, otherwise use the string of the function. - * @param {Object} [options.promoteLongs=true] when deserializing a Long will fit it into a Number if it's smaller than 53 bits - * @param {Object} [options.promoteBuffers=false] when deserializing a Binary will return it as a node.js Buffer instance. - * @param {Object} [options.promoteValues=false] when deserializing will promote BSON values to their Node.js closest equivalent types. - * @param {Object} [options.fieldsAsRaw=null] allow to specify if there what fields we wish to return as unserialized raw buffer. - * @param {Object} [options.bsonRegExp=false] return BSON regular expressions as BSONRegExp instances. - * @return {Object} returns the deserialized Javascript Object. - * @api public - */ -BSON.prototype.deserialize = function(buffer, options) { - return deserialize(buffer, options); -} - -/** - * Calculate the bson size for a passed in Javascript object. - * - * @param {Object} object the Javascript object to calculate the BSON byte size for. - * @param {Boolean} [options.serializeFunctions=false] serialize the javascript functions **(default:false)**. - * @param {Boolean} [options.ignoreUndefined=true] ignore undefined fields **(default:true)**. - * @return {Number} returns the number of bytes the BSON object will take up. - * @api public - */ -BSON.prototype.calculateObjectSize = function(object, options) { - options = options || {}; - - var serializeFunctions = typeof options.serializeFunctions == 'boolean' - ? options.serializeFunctions : false; - var ignoreUndefined = typeof options.ignoreUndefined == 'boolean' - ? options.ignoreUndefined : true; - - return calculateObjectSize(object, serializeFunctions, ignoreUndefined); -} - -/** - * Deserialize stream data as BSON documents. - * - * @param {Buffer} data the buffer containing the serialized set of BSON documents. - * @param {Number} startIndex the start index in the data Buffer where the deserialization is to start. - * @param {Number} numberOfDocuments number of documents to deserialize. - * @param {Array} documents an array where to store the deserialized documents. - * @param {Number} docStartIndex the index in the documents array from where to start inserting documents. - * @param {Object} [options] additional options used for the deserialization. - * @param {Object} [options.evalFunctions=false] evaluate functions in the BSON document scoped to the object deserialized. - * @param {Object} [options.cacheFunctions=false] cache evaluated functions for reuse. - * @param {Object} [options.cacheFunctionsCrc32=false] use a crc32 code for caching, otherwise use the string of the function. - * @param {Object} [options.promoteLongs=true] when deserializing a Long will fit it into a Number if it's smaller than 53 bits - * @param {Object} [options.promoteBuffers=false] when deserializing a Binary will return it as a node.js Buffer instance. - * @param {Object} [options.promoteValues=false] when deserializing will promote BSON values to their Node.js closest equivalent types. - * @param {Object} [options.fieldsAsRaw=null] allow to specify if there what fields we wish to return as unserialized raw buffer. - * @param {Object} [options.bsonRegExp=false] return BSON regular expressions as BSONRegExp instances. - * @return {Number} returns the next index in the buffer after deserialization **x** numbers of documents. - * @api public - */ -BSON.prototype.deserializeStream = function(data, startIndex, numberOfDocuments, documents, docStartIndex, options) { - options = options != null ? options : {}; - var index = startIndex; - // Loop over all documents - for(var i = 0; i < numberOfDocuments; i++) { - // Find size of the document - var size = data[index] | data[index + 1] << 8 | data[index + 2] << 16 | data[index + 3] << 24; - // Update options with index - options['index'] = index; - // Parse the document at this point - documents[docStartIndex + i] = this.deserialize(data, options); - // Adjust index by the document size - index = index + size; - } - - // Return object containing end index of parsing and list of documents - return index; -} - -/** - * @ignore - * @api private - */ -// BSON MAX VALUES -BSON.BSON_INT32_MAX = 0x7FFFFFFF; -BSON.BSON_INT32_MIN = -0x80000000; - -BSON.BSON_INT64_MAX = Math.pow(2, 63) - 1; -BSON.BSON_INT64_MIN = -Math.pow(2, 63); - -// JS MAX PRECISE VALUES -BSON.JS_INT_MAX = 0x20000000000000; // Any integer up to 2^53 can be precisely represented by a double. -BSON.JS_INT_MIN = -0x20000000000000; // Any integer down to -2^53 can be precisely represented by a double. - -// Internal long versions -var JS_INT_MAX_LONG = Long.fromNumber(0x20000000000000); // Any integer up to 2^53 can be precisely represented by a double. -var JS_INT_MIN_LONG = Long.fromNumber(-0x20000000000000); // Any integer down to -2^53 can be precisely represented by a double. - -/** - * Number BSON Type - * - * @classconstant BSON_DATA_NUMBER - **/ -BSON.BSON_DATA_NUMBER = 1; -/** - * String BSON Type - * - * @classconstant BSON_DATA_STRING - **/ -BSON.BSON_DATA_STRING = 2; -/** - * Object BSON Type - * - * @classconstant BSON_DATA_OBJECT - **/ -BSON.BSON_DATA_OBJECT = 3; -/** - * Array BSON Type - * - * @classconstant BSON_DATA_ARRAY - **/ -BSON.BSON_DATA_ARRAY = 4; -/** - * Binary BSON Type - * - * @classconstant BSON_DATA_BINARY - **/ -BSON.BSON_DATA_BINARY = 5; -/** - * ObjectID BSON Type - * - * @classconstant BSON_DATA_OID - **/ -BSON.BSON_DATA_OID = 7; -/** - * Boolean BSON Type - * - * @classconstant BSON_DATA_BOOLEAN - **/ -BSON.BSON_DATA_BOOLEAN = 8; -/** - * Date BSON Type - * - * @classconstant BSON_DATA_DATE - **/ -BSON.BSON_DATA_DATE = 9; -/** - * null BSON Type - * - * @classconstant BSON_DATA_NULL - **/ -BSON.BSON_DATA_NULL = 10; -/** - * RegExp BSON Type - * - * @classconstant BSON_DATA_REGEXP - **/ -BSON.BSON_DATA_REGEXP = 11; -/** - * Code BSON Type - * - * @classconstant BSON_DATA_CODE - **/ -BSON.BSON_DATA_CODE = 13; -/** - * Symbol BSON Type - * - * @classconstant BSON_DATA_SYMBOL - **/ -BSON.BSON_DATA_SYMBOL = 14; -/** - * Code with Scope BSON Type - * - * @classconstant BSON_DATA_CODE_W_SCOPE - **/ -BSON.BSON_DATA_CODE_W_SCOPE = 15; -/** - * 32 bit Integer BSON Type - * - * @classconstant BSON_DATA_INT - **/ -BSON.BSON_DATA_INT = 16; -/** - * Timestamp BSON Type - * - * @classconstant BSON_DATA_TIMESTAMP - **/ -BSON.BSON_DATA_TIMESTAMP = 17; -/** - * Long BSON Type - * - * @classconstant BSON_DATA_LONG - **/ -BSON.BSON_DATA_LONG = 18; -/** - * MinKey BSON Type - * - * @classconstant BSON_DATA_MIN_KEY - **/ -BSON.BSON_DATA_MIN_KEY = 0xff; -/** - * MaxKey BSON Type - * - * @classconstant BSON_DATA_MAX_KEY - **/ -BSON.BSON_DATA_MAX_KEY = 0x7f; - -/** - * Binary Default Type - * - * @classconstant BSON_BINARY_SUBTYPE_DEFAULT - **/ -BSON.BSON_BINARY_SUBTYPE_DEFAULT = 0; -/** - * Binary Function Type - * - * @classconstant BSON_BINARY_SUBTYPE_FUNCTION - **/ -BSON.BSON_BINARY_SUBTYPE_FUNCTION = 1; -/** - * Binary Byte Array Type - * - * @classconstant BSON_BINARY_SUBTYPE_BYTE_ARRAY - **/ -BSON.BSON_BINARY_SUBTYPE_BYTE_ARRAY = 2; -/** - * Binary UUID Type - * - * @classconstant BSON_BINARY_SUBTYPE_UUID - **/ -BSON.BSON_BINARY_SUBTYPE_UUID = 3; -/** - * Binary MD5 Type - * - * @classconstant BSON_BINARY_SUBTYPE_MD5 - **/ -BSON.BSON_BINARY_SUBTYPE_MD5 = 4; -/** - * Binary User Defined Type - * - * @classconstant BSON_BINARY_SUBTYPE_USER_DEFINED - **/ -BSON.BSON_BINARY_SUBTYPE_USER_DEFINED = 128; - -// Return BSON -module.exports = BSON; -module.exports.Code = Code; -module.exports.Map = Map; -module.exports.Symbol = Symbol; -module.exports.BSON = BSON; -module.exports.DBRef = DBRef; -module.exports.Binary = Binary; -module.exports.ObjectID = ObjectID; -module.exports.Long = Long; -module.exports.Timestamp = Timestamp; -module.exports.Double = Double; -module.exports.Int32 = Int32; -module.exports.MinKey = MinKey; -module.exports.MaxKey = MaxKey; -module.exports.BSONRegExp = BSONRegExp; -module.exports.Decimal128 = Decimal128; diff --git a/ts-ticket-office-service/node_modules/bson/lib/bson/code.js b/ts-ticket-office-service/node_modules/bson/lib/bson/code.js deleted file mode 100644 index bc80ce5f4..000000000 --- a/ts-ticket-office-service/node_modules/bson/lib/bson/code.js +++ /dev/null @@ -1,24 +0,0 @@ -/** - * A class representation of the BSON Code type. - * - * @class - * @param {(string|function)} code a string or function. - * @param {Object} [scope] an optional scope for the function. - * @return {Code} - */ -var Code = function Code(code, scope) { - if(!(this instanceof Code)) return new Code(code, scope); - this._bsontype = 'Code'; - this.code = code; - this.scope = scope; -}; - -/** - * @ignore - */ -Code.prototype.toJSON = function() { - return {scope:this.scope, code:this.code}; -} - -module.exports = Code; -module.exports.Code = Code; diff --git a/ts-ticket-office-service/node_modules/bson/lib/bson/db_ref.js b/ts-ticket-office-service/node_modules/bson/lib/bson/db_ref.js deleted file mode 100644 index 06789a6cb..000000000 --- a/ts-ticket-office-service/node_modules/bson/lib/bson/db_ref.js +++ /dev/null @@ -1,32 +0,0 @@ -/** - * A class representation of the BSON DBRef type. - * - * @class - * @param {string} namespace the collection name. - * @param {ObjectID} oid the reference ObjectID. - * @param {string} [db] optional db name, if omitted the reference is local to the current db. - * @return {DBRef} - */ -function DBRef(namespace, oid, db) { - if(!(this instanceof DBRef)) return new DBRef(namespace, oid, db); - - this._bsontype = 'DBRef'; - this.namespace = namespace; - this.oid = oid; - this.db = db; -}; - -/** - * @ignore - * @api private - */ -DBRef.prototype.toJSON = function() { - return { - '$ref':this.namespace, - '$id':this.oid, - '$db':this.db == null ? '' : this.db - }; -} - -module.exports = DBRef; -module.exports.DBRef = DBRef; \ No newline at end of file diff --git a/ts-ticket-office-service/node_modules/bson/lib/bson/decimal128.js b/ts-ticket-office-service/node_modules/bson/lib/bson/decimal128.js deleted file mode 100644 index 23ae082e7..000000000 --- a/ts-ticket-office-service/node_modules/bson/lib/bson/decimal128.js +++ /dev/null @@ -1,728 +0,0 @@ -"use strict" - -var Long = require('./long'); - -var PARSE_STRING_REGEXP = /^(\+|\-)?(\d+|(\d*\.\d*))?(E|e)?([\-\+])?(\d+)?$/; -var PARSE_INF_REGEXP = /^(\+|\-)?(Infinity|inf)$/i; -var PARSE_NAN_REGEXP = /^(\+|\-)?NaN$/i; - -var EXPONENT_MAX = 6111; -var EXPONENT_MIN = -6176; -var EXPONENT_BIAS = 6176; -var MAX_DIGITS = 34; - -// Nan value bits as 32 bit values (due to lack of longs) -var NAN_BUFFER = [0x7c, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00].reverse(); -// Infinity value bits 32 bit values (due to lack of longs) -var INF_NEGATIVE_BUFFER = [0xf8, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00].reverse(); -var INF_POSITIVE_BUFFER = [0x78, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00].reverse(); - -var EXPONENT_REGEX = /^([\-\+])?(\d+)?$/; - - -// Detect if the value is a digit -var isDigit = function(value) { - return !isNaN(parseInt(value, 10)); -} - -// Divide two uint128 values -var divideu128 = function(value) { - var DIVISOR = Long.fromNumber(1000 * 1000 * 1000); - var _rem = Long.fromNumber(0); - var i = 0; - - if(!value.parts[0] && !value.parts[1] && - !value.parts[2] && !value.parts[3]) { - return { quotient: value, rem: _rem }; - } - - for(var i = 0; i <= 3; i++) { - // Adjust remainder to match value of next dividend - _rem = _rem.shiftLeft(32); - // Add the divided to _rem - _rem = _rem.add(new Long(value.parts[i], 0)); - value.parts[i] = _rem.div(DIVISOR).low_; - _rem = _rem.modulo(DIVISOR); - } - - return { quotient: value, rem: _rem }; -} - -// Multiply two Long values and return the 128 bit value -var multiply64x2 = function(left, right) { - if(!left && !right) { - return {high: Long.fromNumber(0), low: Long.fromNumber(0)}; - } - - var leftHigh = left.shiftRightUnsigned(32); - var leftLow = new Long(left.getLowBits(), 0); - var rightHigh = right.shiftRightUnsigned(32); - var rightLow = new Long(right.getLowBits(), 0); - - var productHigh = leftHigh.multiply(rightHigh); - var productMid = leftHigh.multiply(rightLow); - var productMid2 = leftLow.multiply(rightHigh); - var productLow = leftLow.multiply(rightLow); - - productHigh = productHigh.add(productMid.shiftRightUnsigned(32)); - productMid = new Long(productMid.getLowBits(), 0) - .add(productMid2) - .add(productLow.shiftRightUnsigned(32)); - - productHigh = productHigh.add(productMid.shiftRightUnsigned(32)); - productLow = productMid.shiftLeft(32).add(new Long(productLow.getLowBits(), 0)); - - // Return the 128 bit result - return {high: productHigh, low: productLow}; -} - -var lessThan = function(left, right) { - // Make values unsigned - var uhleft = left.high_ >>> 0; - var uhright = right.high_ >>> 0; - - // Compare high bits first - if(uhleft < uhright) { - return true - } else if(uhleft == uhright) { - var ulleft = left.low_ >>> 0; - var ulright = right.low_ >>> 0; - if(ulleft < ulright) return true; - } - - return false; -} - -var longtoHex = function(value) { - var buffer = new Buffer(8); - var index = 0; - // Encode the low 64 bits of the decimal - // Encode low bits - buffer[index++] = value.low_ & 0xff; - buffer[index++] = (value.low_ >> 8) & 0xff; - buffer[index++] = (value.low_ >> 16) & 0xff; - buffer[index++] = (value.low_ >> 24) & 0xff; - // Encode high bits - buffer[index++] = value.high_ & 0xff; - buffer[index++] = (value.high_ >> 8) & 0xff; - buffer[index++] = (value.high_ >> 16) & 0xff; - buffer[index++] = (value.high_ >> 24) & 0xff; - return buffer.reverse().toString('hex'); -} - -var int32toHex = function(value) { - var buffer = new Buffer(4); - var index = 0; - // Encode the low 64 bits of the decimal - // Encode low bits - buffer[index++] = value & 0xff; - buffer[index++] = (value >> 8) & 0xff; - buffer[index++] = (value >> 16) & 0xff; - buffer[index++] = (value >> 24) & 0xff; - return buffer.reverse().toString('hex'); -} - -var Decimal128 = function(bytes) { - this._bsontype = 'Decimal128'; - this.bytes = bytes; -} - -Decimal128.fromString = function(string) { - // Parse state tracking - var isNegative = false; - var sawRadix = false; - var foundNonZero = false; - - // Total number of significant digits (no leading or trailing zero) - var significantDigits = 0; - // Total number of significand digits read - var nDigitsRead = 0; - // Total number of digits (no leading zeros) - var nDigits = 0; - // The number of the digits after radix - var radixPosition = 0; - // The index of the first non-zero in *str* - var firstNonZero = 0; - - // Digits Array - var digits = [0]; - // The number of digits in digits - var nDigitsStored = 0; - // Insertion pointer for digits - var digitsInsert = 0; - // The index of the first non-zero digit - var firstDigit = 0; - // The index of the last digit - var lastDigit = 0; - - // Exponent - var exponent = 0; - // loop index over array - var i = 0; - // The high 17 digits of the significand - var significandHigh = [0, 0]; - // The low 17 digits of the significand - var significandLow = [0, 0]; - // The biased exponent - var biasedExponent = 0; - - // Read index - var index = 0; - - // Trim the string - string = string.trim(); - - // Results - var stringMatch = string.match(PARSE_STRING_REGEXP); - var infMatch = string.match(PARSE_INF_REGEXP); - var nanMatch = string.match(PARSE_NAN_REGEXP); - - // Validate the string - if(!stringMatch - && ! infMatch - && ! nanMatch || string.length == 0) { - throw new Error("" + string + " not a valid Decimal128 string"); - } - - // Check if we have an illegal exponent format - if(stringMatch && stringMatch[4] && stringMatch[2] === undefined) { - throw new Error("" + string + " not a valid Decimal128 string"); - } - - // Get the negative or positive sign - if(string[index] == '+' || string[index] == '-') { - isNegative = string[index++] == '-'; - } - - // Check if user passed Infinity or NaN - if(!isDigit(string[index]) && string[index] != '.') { - if(string[index] == 'i' || string[index] == 'I') { - return new Decimal128(new Buffer(isNegative ? INF_NEGATIVE_BUFFER : INF_POSITIVE_BUFFER)); - } else if(string[index] == 'N') { - return new Decimal128(new Buffer(NAN_BUFFER)); - } - } - - // Read all the digits - while(isDigit(string[index]) || string[index] == '.') { - if(string[index] == '.') { - if(sawRadix) { - return new Decimal128(new Buffer(NAN_BUFFER)); - } - - sawRadix = true; - index = index + 1; - continue; - } - - if(nDigitsStored < 34) { - if(string[index] != '0' || foundNonZero) { - if(!foundNonZero) { - firstNonZero = nDigitsRead; - } - - foundNonZero = true; - - // Only store 34 digits - digits[digitsInsert++] = parseInt(string[index], 10); - nDigitsStored = nDigitsStored + 1; - } - } - - if(foundNonZero) { - nDigits = nDigits + 1; - } - - if(sawRadix) { - radixPosition = radixPosition + 1; - } - - nDigitsRead = nDigitsRead + 1; - index = index + 1; - } - - if(sawRadix && !nDigitsRead) { - throw new Error("" + string + " not a valid Decimal128 string"); - } - - // Read exponent if exists - if(string[index] == 'e' || string[index] == 'E') { - // Read exponent digits - var match = string.substr(++index).match(EXPONENT_REGEX); - - // No digits read - if(!match || !match[2]) { - return new Decimal128(new Buffer(NAN_BUFFER)); - } - - // Get exponent - exponent = parseInt(match[0], 10); - - // Adjust the index - index = index + match[0].length; - } - - // Return not a number - if(string[index]) { - return new Decimal128(new Buffer(NAN_BUFFER)); - } - - // Done reading input - // Find first non-zero digit in digits - firstDigit = 0; - - if(!nDigitsStored) { - firstDigit = 0; - lastDigit = 0; - digits[0] = 0; - nDigits = 1; - nDigitsStored = 1; - significantDigits = 0; - } else { - lastDigit = nDigitsStored - 1; - significantDigits = nDigits; - - if(exponent != 0 && significantDigits != 1) { - while(string[firstNonZero + significantDigits - 1] == '0') { - significantDigits = significantDigits - 1; - } - } - } - - // Normalization of exponent - // Correct exponent based on radix position, and shift significand as needed - // to represent user input - - // Overflow prevention - if(exponent <= radixPosition && radixPosition - exponent > (1 << 14)) { - exponent = EXPONENT_MIN; - } else { - exponent = exponent - radixPosition; - } - - // Attempt to normalize the exponent - while(exponent > EXPONENT_MAX) { - // Shift exponent to significand and decrease - lastDigit = lastDigit + 1; - - if(lastDigit - firstDigit > MAX_DIGITS) { - // Check if we have a zero then just hard clamp, otherwise fail - var digitsString = digits.join(''); - if(digitsString.match(/^0+$/)) { - exponent = EXPONENT_MAX; - break; - } else { - return new Decimal128(new Buffer(isNegative ? INF_NEGATIVE_BUFFER : INF_POSITIVE_BUFFER)); - } - } - - exponent = exponent - 1; - } - - while(exponent < EXPONENT_MIN || nDigitsStored < nDigits) { - // Shift last digit - if(lastDigit == 0) { - exponent = EXPONENT_MIN; - significantDigits = 0; - break; - } - - if(nDigitsStored < nDigits) { - // adjust to match digits not stored - nDigits = nDigits - 1; - } else { - // adjust to round - lastDigit = lastDigit - 1; - } - - if(exponent < EXPONENT_MAX) { - exponent = exponent + 1; - } else { - // Check if we have a zero then just hard clamp, otherwise fail - var digitsString = digits.join(''); - if(digitsString.match(/^0+$/)) { - exponent = EXPONENT_MAX; - break; - } else { - return new Decimal128(new Buffer(isNegative ? INF_NEGATIVE_BUFFER : INF_POSITIVE_BUFFER)) - } - } - } - - - // Round - // We've normalized the exponent, but might still need to round. - if((lastDigit - firstDigit + 1 < significantDigits) && string[significantDigits] != '0') { - var endOfString = nDigitsRead; - - // If we have seen a radix point, 'string' is 1 longer than we have - // documented with ndigits_read, so inc the position of the first nonzero - // digit and the position that digits are read to. - if(sawRadix && exponent == EXPONENT_MIN) { - firstNonZero = firstNonZero + 1; - endOfString = endOfString + 1; - } - - var roundDigit = parseInt(string[firstNonZero + lastDigit + 1], 10); - var roundBit = 0; - - if(roundDigit >= 5) { - roundBit = 1; - - if(roundDigit == 5) { - roundBit = digits[lastDigit] % 2 == 1; - - for(var i = firstNonZero + lastDigit + 2; i < endOfString; i++) { - if(parseInt(string[i], 10)) { - roundBit = 1; - break; - } - } - } - } - - if(roundBit) { - var dIdx = lastDigit; - - for(; dIdx >= 0; dIdx--) { - if(++digits[dIdx] > 9) { - digits[dIdx] = 0; - - // overflowed most significant digit - if(dIdx == 0) { - if(exponent < EXPONENT_MAX) { - exponent = exponent + 1; - digits[dIdx] = 1; - } else { - return new Decimal128(new Buffer(isNegative ? INF_NEGATIVE_BUFFER : INF_POSITIVE_BUFFER)) - } - } - } else { - break; - } - } - } - } - - // Encode significand - // The high 17 digits of the significand - significandHigh = Long.fromNumber(0); - // The low 17 digits of the significand - significandLow = Long.fromNumber(0); - - // read a zero - if(significantDigits == 0) { - significandHigh = Long.fromNumber(0); - significandLow = Long.fromNumber(0); - } else if(lastDigit - firstDigit < 17) { - var dIdx = firstDigit; - significandLow = Long.fromNumber(digits[dIdx++]); - significandHigh = new Long(0, 0); - - for(; dIdx <= lastDigit; dIdx++) { - significandLow = significandLow.multiply(Long.fromNumber(10)); - significandLow = significandLow.add(Long.fromNumber(digits[dIdx])); - } - } else { - var dIdx = firstDigit; - significandHigh = Long.fromNumber(digits[dIdx++]); - - for(; dIdx <= lastDigit - 17; dIdx++) { - significandHigh = significandHigh.multiply(Long.fromNumber(10)); - significandHigh = significandHigh.add(Long.fromNumber(digits[dIdx])); - } - - significandLow = Long.fromNumber(digits[dIdx++]); - - for(; dIdx <= lastDigit; dIdx++) { - significandLow = significandLow.multiply(Long.fromNumber(10)); - significandLow = significandLow.add(Long.fromNumber(digits[dIdx])); - } - } - - var significand = multiply64x2(significandHigh, Long.fromString("100000000000000000")); - - significand.low = significand.low.add(significandLow); - - if(lessThan(significand.low, significandLow)) { - significand.high = significand.high.add(Long.fromNumber(1)); - } - - // Biased exponent - var biasedExponent = (exponent + EXPONENT_BIAS); - var dec = { low: Long.fromNumber(0), high: Long.fromNumber(0) }; - - // Encode combination, exponent, and significand. - if(significand.high.shiftRightUnsigned(49).and(Long.fromNumber(1)).equals(Long.fromNumber)) { - // Encode '11' into bits 1 to 3 - dec.high = dec.high.or(Long.fromNumber(0x3).shiftLeft(61)); - dec.high = dec.high.or(Long.fromNumber(biasedExponent).and(Long.fromNumber(0x3fff).shiftLeft(47))); - dec.high = dec.high.or(significand.high.and(Long.fromNumber(0x7fffffffffff))); - } else { - dec.high = dec.high.or(Long.fromNumber(biasedExponent & 0x3fff).shiftLeft(49)); - dec.high = dec.high.or(significand.high.and(Long.fromNumber(0x1ffffffffffff))); - } - - dec.low = significand.low; - - // Encode sign - if(isNegative) { - dec.high = dec.high.or(Long.fromString('9223372036854775808')); - } - - // Encode into a buffer - var buffer = new Buffer(16); - var index = 0; - - // Encode the low 64 bits of the decimal - // Encode low bits - buffer[index++] = dec.low.low_ & 0xff; - buffer[index++] = (dec.low.low_ >> 8) & 0xff; - buffer[index++] = (dec.low.low_ >> 16) & 0xff; - buffer[index++] = (dec.low.low_ >> 24) & 0xff; - // Encode high bits - buffer[index++] = dec.low.high_ & 0xff; - buffer[index++] = (dec.low.high_ >> 8) & 0xff; - buffer[index++] = (dec.low.high_ >> 16) & 0xff; - buffer[index++] = (dec.low.high_ >> 24) & 0xff; - - // Encode the high 64 bits of the decimal - // Encode low bits - buffer[index++] = dec.high.low_ & 0xff; - buffer[index++] = (dec.high.low_ >> 8) & 0xff; - buffer[index++] = (dec.high.low_ >> 16) & 0xff; - buffer[index++] = (dec.high.low_ >> 24) & 0xff; - // Encode high bits - buffer[index++] = dec.high.high_ & 0xff; - buffer[index++] = (dec.high.high_ >> 8) & 0xff; - buffer[index++] = (dec.high.high_ >> 16) & 0xff; - buffer[index++] = (dec.high.high_ >> 24) & 0xff; - - // Return the new Decimal128 - return new Decimal128(buffer); -} - -// Extract least significant 5 bits -var COMBINATION_MASK = 0x1f; -// Extract least significant 14 bits -var EXPONENT_MASK = 0x3fff; -// Value of combination field for Inf -var COMBINATION_INFINITY = 30; -// Value of combination field for NaN -var COMBINATION_NAN = 31; -// Value of combination field for NaN -var COMBINATION_SNAN = 32; -// decimal128 exponent bias -var EXPONENT_BIAS = 6176; - -Decimal128.prototype.toString = function() { - // Note: bits in this routine are referred to starting at 0, - // from the sign bit, towards the coefficient. - - // bits 0 - 31 - var high; - // bits 32 - 63 - var midh; - // bits 64 - 95 - var midl; - // bits 96 - 127 - var low; - // bits 1 - 5 - var combination; - // decoded biased exponent (14 bits) - var biased_exponent; - // the number of significand digits - var significand_digits = 0; - // the base-10 digits in the significand - var significand = new Array(36); - for(var i = 0; i < significand.length; i++) significand[i] = 0; - // read pointer into significand - var index = 0; - - // unbiased exponent - var exponent; - // the exponent if scientific notation is used - var scientific_exponent; - - // true if the number is zero - var is_zero = false; - - // the most signifcant significand bits (50-46) - var significand_msb; - // temporary storage for significand decoding - var significand128 = {parts: new Array(4)}; - // indexing variables - var i; - var j, k; - - // Output string - var string = []; - - // Unpack index - var index = 0; - - // Buffer reference - var buffer = this.bytes; - - // Unpack the low 64bits into a long - low = buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24; - midl = buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24; - - // Unpack the high 64bits into a long - midh = buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24; - high = buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24; - - // Unpack index - var index = 0; - - // Create the state of the decimal - var dec = { - low: new Long(low, midl), - high: new Long(midh, high) }; - - if(dec.high.lessThan(Long.ZERO)) { - string.push('-'); - } - - // Decode combination field and exponent - combination = (high >> 26) & COMBINATION_MASK; - - if((combination >> 3) == 3) { - // Check for 'special' values - if(combination == COMBINATION_INFINITY) { - return string.join('') + "Infinity"; - } else if(combination == COMBINATION_NAN) { - return "NaN"; - } else { - biased_exponent = (high >> 15) & EXPONENT_MASK; - significand_msb = 0x08 + ((high >> 14) & 0x01); - } - } else { - significand_msb = (high >> 14) & 0x07; - biased_exponent = (high >> 17) & EXPONENT_MASK; - } - - exponent = biased_exponent - EXPONENT_BIAS; - - // Create string of significand digits - - // Convert the 114-bit binary number represented by - // (significand_high, significand_low) to at most 34 decimal - // digits through modulo and division. - significand128.parts[0] = (high & 0x3fff) + ((significand_msb & 0xf) << 14); - significand128.parts[1] = midh; - significand128.parts[2] = midl; - significand128.parts[3] = low; - - if(significand128.parts[0] == 0 && significand128.parts[1] == 0 - && significand128.parts[2] == 0 && significand128.parts[3] == 0) { - is_zero = true; - } else { - for(var k = 3; k >= 0; k--) { - var least_digits = 0; - // Peform the divide - var result = divideu128(significand128); - significand128 = result.quotient; - least_digits = result.rem.low_; - - // We now have the 9 least significant digits (in base 2). - // Convert and output to string. - if(!least_digits) continue; - - for(var j = 8; j >= 0; j--) { - // significand[k * 9 + j] = Math.round(least_digits % 10); - significand[k * 9 + j] = least_digits % 10; - // least_digits = Math.round(least_digits / 10); - least_digits = Math.floor(least_digits / 10); - } - } - } - - // Output format options: - // Scientific - [-]d.dddE(+/-)dd or [-]dE(+/-)dd - // Regular - ddd.ddd - - if(is_zero) { - significand_digits = 1; - significand[index] = 0; - } else { - significand_digits = 36; - var i = 0; - - while(!significand[index]) { - i++; - significand_digits = significand_digits - 1; - index = index + 1; - } - } - - scientific_exponent = significand_digits - 1 + exponent; - - // The scientific exponent checks are dictated by the string conversion - // specification and are somewhat arbitrary cutoffs. - // - // We must check exponent > 0, because if this is the case, the number - // has trailing zeros. However, we *cannot* output these trailing zeros, - // because doing so would change the precision of the value, and would - // change stored data if the string converted number is round tripped. - - if(scientific_exponent >= 34 || scientific_exponent <= -7 || - exponent > 0) { - // Scientific format - string.push(significand[index++]); - significand_digits = significand_digits - 1; - - if(significand_digits) { - string.push('.'); - } - - for(var i = 0; i < significand_digits; i++) { - string.push(significand[index++]); - } - - // Exponent - string.push('E'); - if(scientific_exponent > 0) { - string.push('+' + scientific_exponent); - } else { - string.push(scientific_exponent); - } - } else { - // Regular format with no decimal place - if(exponent >= 0) { - for(var i = 0; i < significand_digits; i++) { - string.push(significand[index++]); - } - } else { - var radix_position = significand_digits + exponent; - - // non-zero digits before radix - if(radix_position > 0) { - for(var i = 0; i < radix_position; i++) { - string.push(significand[index++]); - } - } else { - string.push('0'); - } - - string.push('.'); - // add leading zeros after radix - while(radix_position++ < 0) { - string.push('0'); - } - - for(var i = 0; i < significand_digits - Math.max(radix_position - 1, 0); i++) { - string.push(significand[index++]); - } - } - } - - return string.join(''); -} - -Decimal128.prototype.toJSON = function() { - return { "$numberDecimal": this.toString() }; -} - -module.exports = Decimal128; -module.exports.Decimal128 = Decimal128; diff --git a/ts-ticket-office-service/node_modules/bson/lib/bson/double.js b/ts-ticket-office-service/node_modules/bson/lib/bson/double.js deleted file mode 100644 index 82c5bd600..000000000 --- a/ts-ticket-office-service/node_modules/bson/lib/bson/double.js +++ /dev/null @@ -1,33 +0,0 @@ -/** - * A class representation of the BSON Double type. - * - * @class - * @param {number} value the number we want to represent as a double. - * @return {Double} - */ -function Double(value) { - if(!(this instanceof Double)) return new Double(value); - - this._bsontype = 'Double'; - this.value = value; -} - -/** - * Access the number value. - * - * @method - * @return {number} returns the wrapped double number. - */ -Double.prototype.valueOf = function() { - return this.value; -}; - -/** - * @ignore - */ -Double.prototype.toJSON = function() { - return this.value; -} - -module.exports = Double; -module.exports.Double = Double; diff --git a/ts-ticket-office-service/node_modules/bson/lib/bson/float_parser.js b/ts-ticket-office-service/node_modules/bson/lib/bson/float_parser.js deleted file mode 100644 index 6fca3924f..000000000 --- a/ts-ticket-office-service/node_modules/bson/lib/bson/float_parser.js +++ /dev/null @@ -1,121 +0,0 @@ -// Copyright (c) 2008, Fair Oaks Labs, Inc. -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// * Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// * Redistributions in binary form must reproduce the above copyright notice, -// this list of conditions and the following disclaimer in the documentation -// and/or other materials provided with the distribution. -// -// * Neither the name of Fair Oaks Labs, Inc. nor the names of its contributors -// may be used to endorse or promote products derived from this software -// without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. -// -// -// Modifications to writeIEEE754 to support negative zeroes made by Brian White - -var readIEEE754 = function(buffer, offset, endian, mLen, nBytes) { - var e, m, - bBE = (endian === 'big'), - eLen = nBytes * 8 - mLen - 1, - eMax = (1 << eLen) - 1, - eBias = eMax >> 1, - nBits = -7, - i = bBE ? 0 : (nBytes - 1), - d = bBE ? 1 : -1, - s = buffer[offset + i]; - - i += d; - - e = s & ((1 << (-nBits)) - 1); - s >>= (-nBits); - nBits += eLen; - for (; nBits > 0; e = e * 256 + buffer[offset + i], i += d, nBits -= 8); - - m = e & ((1 << (-nBits)) - 1); - e >>= (-nBits); - nBits += mLen; - for (; nBits > 0; m = m * 256 + buffer[offset + i], i += d, nBits -= 8); - - if (e === 0) { - e = 1 - eBias; - } else if (e === eMax) { - return m ? NaN : ((s ? -1 : 1) * Infinity); - } else { - m = m + Math.pow(2, mLen); - e = e - eBias; - } - return (s ? -1 : 1) * m * Math.pow(2, e - mLen); -}; - -var writeIEEE754 = function(buffer, value, offset, endian, mLen, nBytes) { - var e, m, c, - bBE = (endian === 'big'), - eLen = nBytes * 8 - mLen - 1, - eMax = (1 << eLen) - 1, - eBias = eMax >> 1, - rt = (mLen === 23 ? Math.pow(2, -24) - Math.pow(2, -77) : 0), - i = bBE ? (nBytes-1) : 0, - d = bBE ? -1 : 1, - s = value < 0 || (value === 0 && 1 / value < 0) ? 1 : 0; - - value = Math.abs(value); - - if (isNaN(value) || value === Infinity) { - m = isNaN(value) ? 1 : 0; - e = eMax; - } else { - e = Math.floor(Math.log(value) / Math.LN2); - if (value * (c = Math.pow(2, -e)) < 1) { - e--; - c *= 2; - } - if (e+eBias >= 1) { - value += rt / c; - } else { - value += rt * Math.pow(2, 1 - eBias); - } - if (value * c >= 2) { - e++; - c /= 2; - } - - if (e + eBias >= eMax) { - m = 0; - e = eMax; - } else if (e + eBias >= 1) { - m = (value * c - 1) * Math.pow(2, mLen); - e = e + eBias; - } else { - m = value * Math.pow(2, eBias - 1) * Math.pow(2, mLen); - e = 0; - } - } - - for (; mLen >= 8; buffer[offset + i] = m & 0xff, i += d, m /= 256, mLen -= 8); - - e = (e << mLen) | m; - eLen += mLen; - for (; eLen > 0; buffer[offset + i] = e & 0xff, i += d, e /= 256, eLen -= 8); - - buffer[offset + i - d] |= s * 128; -}; - -exports.readIEEE754 = readIEEE754; -exports.writeIEEE754 = writeIEEE754; \ No newline at end of file diff --git a/ts-ticket-office-service/node_modules/bson/lib/bson/int_32.js b/ts-ticket-office-service/node_modules/bson/lib/bson/int_32.js deleted file mode 100644 index 6c729f6b7..000000000 --- a/ts-ticket-office-service/node_modules/bson/lib/bson/int_32.js +++ /dev/null @@ -1,26 +0,0 @@ -var Int32 = function(value) { - if(!(this instanceof Int32)) return new Int32(value); - - this._bsontype = 'Int32'; - this.value = value; -} - -/** - * Access the number value. - * - * @method - * @return {number} returns the wrapped int32 number. - */ -Int32.prototype.valueOf = function() { - return this.value; -}; - -/** - * @ignore - */ -Int32.prototype.toJSON = function() { - return this.value; -} - -module.exports = Int32; -module.exports.Int32 = Int32; diff --git a/ts-ticket-office-service/node_modules/bson/lib/bson/long.js b/ts-ticket-office-service/node_modules/bson/lib/bson/long.js deleted file mode 100644 index 6f188850d..000000000 --- a/ts-ticket-office-service/node_modules/bson/lib/bson/long.js +++ /dev/null @@ -1,856 +0,0 @@ -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// -// Copyright 2009 Google Inc. All Rights Reserved - -/** - * Defines a Long class for representing a 64-bit two's-complement - * integer value, which faithfully simulates the behavior of a Java "Long". This - * implementation is derived from LongLib in GWT. - * - * Constructs a 64-bit two's-complement integer, given its low and high 32-bit - * values as *signed* integers. See the from* functions below for more - * convenient ways of constructing Longs. - * - * The internal representation of a Long is the two given signed, 32-bit values. - * We use 32-bit pieces because these are the size of integers on which - * Javascript performs bit-operations. For operations like addition and - * multiplication, we split each number into 16-bit pieces, which can easily be - * multiplied within Javascript's floating-point representation without overflow - * or change in sign. - * - * In the algorithms below, we frequently reduce the negative case to the - * positive case by negating the input(s) and then post-processing the result. - * Note that we must ALWAYS check specially whether those values are MIN_VALUE - * (-2^63) because -MIN_VALUE == MIN_VALUE (since 2^63 cannot be represented as - * a positive number, it overflows back into a negative). Not handling this - * case would often result in infinite recursion. - * - * @class - * @param {number} low the low (signed) 32 bits of the Long. - * @param {number} high the high (signed) 32 bits of the Long. - * @return {Long} - */ -function Long(low, high) { - if(!(this instanceof Long)) return new Long(low, high); - - this._bsontype = 'Long'; - /** - * @type {number} - * @ignore - */ - this.low_ = low | 0; // force into 32 signed bits. - - /** - * @type {number} - * @ignore - */ - this.high_ = high | 0; // force into 32 signed bits. -}; - -/** - * Return the int value. - * - * @method - * @return {number} the value, assuming it is a 32-bit integer. - */ -Long.prototype.toInt = function() { - return this.low_; -}; - -/** - * Return the Number value. - * - * @method - * @return {number} the closest floating-point representation to this value. - */ -Long.prototype.toNumber = function() { - return this.high_ * Long.TWO_PWR_32_DBL_ + - this.getLowBitsUnsigned(); -}; - -/** - * Return the JSON value. - * - * @method - * @return {string} the JSON representation. - */ -Long.prototype.toJSON = function() { - return this.toString(); -} - -/** - * Return the String value. - * - * @method - * @param {number} [opt_radix] the radix in which the text should be written. - * @return {string} the textual representation of this value. - */ -Long.prototype.toString = function(opt_radix) { - var radix = opt_radix || 10; - if (radix < 2 || 36 < radix) { - throw Error('radix out of range: ' + radix); - } - - if (this.isZero()) { - return '0'; - } - - if (this.isNegative()) { - if (this.equals(Long.MIN_VALUE)) { - // We need to change the Long value before it can be negated, so we remove - // the bottom-most digit in this base and then recurse to do the rest. - var radixLong = Long.fromNumber(radix); - var div = this.div(radixLong); - var rem = div.multiply(radixLong).subtract(this); - return div.toString(radix) + rem.toInt().toString(radix); - } else { - return '-' + this.negate().toString(radix); - } - } - - // Do several (6) digits each time through the loop, so as to - // minimize the calls to the very expensive emulated div. - var radixToPower = Long.fromNumber(Math.pow(radix, 6)); - - var rem = this; - var result = ''; - while (true) { - var remDiv = rem.div(radixToPower); - var intval = rem.subtract(remDiv.multiply(radixToPower)).toInt(); - var digits = intval.toString(radix); - - rem = remDiv; - if (rem.isZero()) { - return digits + result; - } else { - while (digits.length < 6) { - digits = '0' + digits; - } - result = '' + digits + result; - } - } -}; - -/** - * Return the high 32-bits value. - * - * @method - * @return {number} the high 32-bits as a signed value. - */ -Long.prototype.getHighBits = function() { - return this.high_; -}; - -/** - * Return the low 32-bits value. - * - * @method - * @return {number} the low 32-bits as a signed value. - */ -Long.prototype.getLowBits = function() { - return this.low_; -}; - -/** - * Return the low unsigned 32-bits value. - * - * @method - * @return {number} the low 32-bits as an unsigned value. - */ -Long.prototype.getLowBitsUnsigned = function() { - return (this.low_ >= 0) ? - this.low_ : Long.TWO_PWR_32_DBL_ + this.low_; -}; - -/** - * Returns the number of bits needed to represent the absolute value of this Long. - * - * @method - * @return {number} Returns the number of bits needed to represent the absolute value of this Long. - */ -Long.prototype.getNumBitsAbs = function() { - if (this.isNegative()) { - if (this.equals(Long.MIN_VALUE)) { - return 64; - } else { - return this.negate().getNumBitsAbs(); - } - } else { - var val = this.high_ != 0 ? this.high_ : this.low_; - for (var bit = 31; bit > 0; bit--) { - if ((val & (1 << bit)) != 0) { - break; - } - } - return this.high_ != 0 ? bit + 33 : bit + 1; - } -}; - -/** - * Return whether this value is zero. - * - * @method - * @return {boolean} whether this value is zero. - */ -Long.prototype.isZero = function() { - return this.high_ == 0 && this.low_ == 0; -}; - -/** - * Return whether this value is negative. - * - * @method - * @return {boolean} whether this value is negative. - */ -Long.prototype.isNegative = function() { - return this.high_ < 0; -}; - -/** - * Return whether this value is odd. - * - * @method - * @return {boolean} whether this value is odd. - */ -Long.prototype.isOdd = function() { - return (this.low_ & 1) == 1; -}; - -/** - * Return whether this Long equals the other - * - * @method - * @param {Long} other Long to compare against. - * @return {boolean} whether this Long equals the other - */ -Long.prototype.equals = function(other) { - return (this.high_ == other.high_) && (this.low_ == other.low_); -}; - -/** - * Return whether this Long does not equal the other. - * - * @method - * @param {Long} other Long to compare against. - * @return {boolean} whether this Long does not equal the other. - */ -Long.prototype.notEquals = function(other) { - return (this.high_ != other.high_) || (this.low_ != other.low_); -}; - -/** - * Return whether this Long is less than the other. - * - * @method - * @param {Long} other Long to compare against. - * @return {boolean} whether this Long is less than the other. - */ -Long.prototype.lessThan = function(other) { - return this.compare(other) < 0; -}; - -/** - * Return whether this Long is less than or equal to the other. - * - * @method - * @param {Long} other Long to compare against. - * @return {boolean} whether this Long is less than or equal to the other. - */ -Long.prototype.lessThanOrEqual = function(other) { - return this.compare(other) <= 0; -}; - -/** - * Return whether this Long is greater than the other. - * - * @method - * @param {Long} other Long to compare against. - * @return {boolean} whether this Long is greater than the other. - */ -Long.prototype.greaterThan = function(other) { - return this.compare(other) > 0; -}; - -/** - * Return whether this Long is greater than or equal to the other. - * - * @method - * @param {Long} other Long to compare against. - * @return {boolean} whether this Long is greater than or equal to the other. - */ -Long.prototype.greaterThanOrEqual = function(other) { - return this.compare(other) >= 0; -}; - -/** - * Compares this Long with the given one. - * - * @method - * @param {Long} other Long to compare against. - * @return {boolean} 0 if they are the same, 1 if the this is greater, and -1 if the given one is greater. - */ -Long.prototype.compare = function(other) { - if (this.equals(other)) { - return 0; - } - - var thisNeg = this.isNegative(); - var otherNeg = other.isNegative(); - if (thisNeg && !otherNeg) { - return -1; - } - if (!thisNeg && otherNeg) { - return 1; - } - - // at this point, the signs are the same, so subtraction will not overflow - if (this.subtract(other).isNegative()) { - return -1; - } else { - return 1; - } -}; - -/** - * The negation of this value. - * - * @method - * @return {Long} the negation of this value. - */ -Long.prototype.negate = function() { - if (this.equals(Long.MIN_VALUE)) { - return Long.MIN_VALUE; - } else { - return this.not().add(Long.ONE); - } -}; - -/** - * Returns the sum of this and the given Long. - * - * @method - * @param {Long} other Long to add to this one. - * @return {Long} the sum of this and the given Long. - */ -Long.prototype.add = function(other) { - // Divide each number into 4 chunks of 16 bits, and then sum the chunks. - - var a48 = this.high_ >>> 16; - var a32 = this.high_ & 0xFFFF; - var a16 = this.low_ >>> 16; - var a00 = this.low_ & 0xFFFF; - - var b48 = other.high_ >>> 16; - var b32 = other.high_ & 0xFFFF; - var b16 = other.low_ >>> 16; - var b00 = other.low_ & 0xFFFF; - - var c48 = 0, c32 = 0, c16 = 0, c00 = 0; - c00 += a00 + b00; - c16 += c00 >>> 16; - c00 &= 0xFFFF; - c16 += a16 + b16; - c32 += c16 >>> 16; - c16 &= 0xFFFF; - c32 += a32 + b32; - c48 += c32 >>> 16; - c32 &= 0xFFFF; - c48 += a48 + b48; - c48 &= 0xFFFF; - return Long.fromBits((c16 << 16) | c00, (c48 << 16) | c32); -}; - -/** - * Returns the difference of this and the given Long. - * - * @method - * @param {Long} other Long to subtract from this. - * @return {Long} the difference of this and the given Long. - */ -Long.prototype.subtract = function(other) { - return this.add(other.negate()); -}; - -/** - * Returns the product of this and the given Long. - * - * @method - * @param {Long} other Long to multiply with this. - * @return {Long} the product of this and the other. - */ -Long.prototype.multiply = function(other) { - if (this.isZero()) { - return Long.ZERO; - } else if (other.isZero()) { - return Long.ZERO; - } - - if (this.equals(Long.MIN_VALUE)) { - return other.isOdd() ? Long.MIN_VALUE : Long.ZERO; - } else if (other.equals(Long.MIN_VALUE)) { - return this.isOdd() ? Long.MIN_VALUE : Long.ZERO; - } - - if (this.isNegative()) { - if (other.isNegative()) { - return this.negate().multiply(other.negate()); - } else { - return this.negate().multiply(other).negate(); - } - } else if (other.isNegative()) { - return this.multiply(other.negate()).negate(); - } - - // If both Longs are small, use float multiplication - if (this.lessThan(Long.TWO_PWR_24_) && - other.lessThan(Long.TWO_PWR_24_)) { - return Long.fromNumber(this.toNumber() * other.toNumber()); - } - - // Divide each Long into 4 chunks of 16 bits, and then add up 4x4 products. - // We can skip products that would overflow. - - var a48 = this.high_ >>> 16; - var a32 = this.high_ & 0xFFFF; - var a16 = this.low_ >>> 16; - var a00 = this.low_ & 0xFFFF; - - var b48 = other.high_ >>> 16; - var b32 = other.high_ & 0xFFFF; - var b16 = other.low_ >>> 16; - var b00 = other.low_ & 0xFFFF; - - var c48 = 0, c32 = 0, c16 = 0, c00 = 0; - c00 += a00 * b00; - c16 += c00 >>> 16; - c00 &= 0xFFFF; - c16 += a16 * b00; - c32 += c16 >>> 16; - c16 &= 0xFFFF; - c16 += a00 * b16; - c32 += c16 >>> 16; - c16 &= 0xFFFF; - c32 += a32 * b00; - c48 += c32 >>> 16; - c32 &= 0xFFFF; - c32 += a16 * b16; - c48 += c32 >>> 16; - c32 &= 0xFFFF; - c32 += a00 * b32; - c48 += c32 >>> 16; - c32 &= 0xFFFF; - c48 += a48 * b00 + a32 * b16 + a16 * b32 + a00 * b48; - c48 &= 0xFFFF; - return Long.fromBits((c16 << 16) | c00, (c48 << 16) | c32); -}; - -/** - * Returns this Long divided by the given one. - * - * @method - * @param {Long} other Long by which to divide. - * @return {Long} this Long divided by the given one. - */ -Long.prototype.div = function(other) { - if (other.isZero()) { - throw Error('division by zero'); - } else if (this.isZero()) { - return Long.ZERO; - } - - if (this.equals(Long.MIN_VALUE)) { - if (other.equals(Long.ONE) || - other.equals(Long.NEG_ONE)) { - return Long.MIN_VALUE; // recall that -MIN_VALUE == MIN_VALUE - } else if (other.equals(Long.MIN_VALUE)) { - return Long.ONE; - } else { - // At this point, we have |other| >= 2, so |this/other| < |MIN_VALUE|. - var halfThis = this.shiftRight(1); - var approx = halfThis.div(other).shiftLeft(1); - if (approx.equals(Long.ZERO)) { - return other.isNegative() ? Long.ONE : Long.NEG_ONE; - } else { - var rem = this.subtract(other.multiply(approx)); - var result = approx.add(rem.div(other)); - return result; - } - } - } else if (other.equals(Long.MIN_VALUE)) { - return Long.ZERO; - } - - if (this.isNegative()) { - if (other.isNegative()) { - return this.negate().div(other.negate()); - } else { - return this.negate().div(other).negate(); - } - } else if (other.isNegative()) { - return this.div(other.negate()).negate(); - } - - // Repeat the following until the remainder is less than other: find a - // floating-point that approximates remainder / other *from below*, add this - // into the result, and subtract it from the remainder. It is critical that - // the approximate value is less than or equal to the real value so that the - // remainder never becomes negative. - var res = Long.ZERO; - var rem = this; - while (rem.greaterThanOrEqual(other)) { - // Approximate the result of division. This may be a little greater or - // smaller than the actual value. - var approx = Math.max(1, Math.floor(rem.toNumber() / other.toNumber())); - - // We will tweak the approximate result by changing it in the 48-th digit or - // the smallest non-fractional digit, whichever is larger. - var log2 = Math.ceil(Math.log(approx) / Math.LN2); - var delta = (log2 <= 48) ? 1 : Math.pow(2, log2 - 48); - - // Decrease the approximation until it is smaller than the remainder. Note - // that if it is too large, the product overflows and is negative. - var approxRes = Long.fromNumber(approx); - var approxRem = approxRes.multiply(other); - while (approxRem.isNegative() || approxRem.greaterThan(rem)) { - approx -= delta; - approxRes = Long.fromNumber(approx); - approxRem = approxRes.multiply(other); - } - - // We know the answer can't be zero... and actually, zero would cause - // infinite recursion since we would make no progress. - if (approxRes.isZero()) { - approxRes = Long.ONE; - } - - res = res.add(approxRes); - rem = rem.subtract(approxRem); - } - return res; -}; - -/** - * Returns this Long modulo the given one. - * - * @method - * @param {Long} other Long by which to mod. - * @return {Long} this Long modulo the given one. - */ -Long.prototype.modulo = function(other) { - return this.subtract(this.div(other).multiply(other)); -}; - -/** - * The bitwise-NOT of this value. - * - * @method - * @return {Long} the bitwise-NOT of this value. - */ -Long.prototype.not = function() { - return Long.fromBits(~this.low_, ~this.high_); -}; - -/** - * Returns the bitwise-AND of this Long and the given one. - * - * @method - * @param {Long} other the Long with which to AND. - * @return {Long} the bitwise-AND of this and the other. - */ -Long.prototype.and = function(other) { - return Long.fromBits(this.low_ & other.low_, this.high_ & other.high_); -}; - -/** - * Returns the bitwise-OR of this Long and the given one. - * - * @method - * @param {Long} other the Long with which to OR. - * @return {Long} the bitwise-OR of this and the other. - */ -Long.prototype.or = function(other) { - return Long.fromBits(this.low_ | other.low_, this.high_ | other.high_); -}; - -/** - * Returns the bitwise-XOR of this Long and the given one. - * - * @method - * @param {Long} other the Long with which to XOR. - * @return {Long} the bitwise-XOR of this and the other. - */ -Long.prototype.xor = function(other) { - return Long.fromBits(this.low_ ^ other.low_, this.high_ ^ other.high_); -}; - -/** - * Returns this Long with bits shifted to the left by the given amount. - * - * @method - * @param {number} numBits the number of bits by which to shift. - * @return {Long} this shifted to the left by the given amount. - */ -Long.prototype.shiftLeft = function(numBits) { - numBits &= 63; - if (numBits == 0) { - return this; - } else { - var low = this.low_; - if (numBits < 32) { - var high = this.high_; - return Long.fromBits( - low << numBits, - (high << numBits) | (low >>> (32 - numBits))); - } else { - return Long.fromBits(0, low << (numBits - 32)); - } - } -}; - -/** - * Returns this Long with bits shifted to the right by the given amount. - * - * @method - * @param {number} numBits the number of bits by which to shift. - * @return {Long} this shifted to the right by the given amount. - */ -Long.prototype.shiftRight = function(numBits) { - numBits &= 63; - if (numBits == 0) { - return this; - } else { - var high = this.high_; - if (numBits < 32) { - var low = this.low_; - return Long.fromBits( - (low >>> numBits) | (high << (32 - numBits)), - high >> numBits); - } else { - return Long.fromBits( - high >> (numBits - 32), - high >= 0 ? 0 : -1); - } - } -}; - -/** - * Returns this Long with bits shifted to the right by the given amount, with the new top bits matching the current sign bit. - * - * @method - * @param {number} numBits the number of bits by which to shift. - * @return {Long} this shifted to the right by the given amount, with zeros placed into the new leading bits. - */ -Long.prototype.shiftRightUnsigned = function(numBits) { - numBits &= 63; - if (numBits == 0) { - return this; - } else { - var high = this.high_; - if (numBits < 32) { - var low = this.low_; - return Long.fromBits( - (low >>> numBits) | (high << (32 - numBits)), - high >>> numBits); - } else if (numBits == 32) { - return Long.fromBits(high, 0); - } else { - return Long.fromBits(high >>> (numBits - 32), 0); - } - } -}; - -/** - * Returns a Long representing the given (32-bit) integer value. - * - * @method - * @param {number} value the 32-bit integer in question. - * @return {Long} the corresponding Long value. - */ -Long.fromInt = function(value) { - if (-128 <= value && value < 128) { - var cachedObj = Long.INT_CACHE_[value]; - if (cachedObj) { - return cachedObj; - } - } - - var obj = new Long(value | 0, value < 0 ? -1 : 0); - if (-128 <= value && value < 128) { - Long.INT_CACHE_[value] = obj; - } - return obj; -}; - -/** - * Returns a Long representing the given value, provided that it is a finite number. Otherwise, zero is returned. - * - * @method - * @param {number} value the number in question. - * @return {Long} the corresponding Long value. - */ -Long.fromNumber = function(value) { - if (isNaN(value) || !isFinite(value)) { - return Long.ZERO; - } else if (value <= -Long.TWO_PWR_63_DBL_) { - return Long.MIN_VALUE; - } else if (value + 1 >= Long.TWO_PWR_63_DBL_) { - return Long.MAX_VALUE; - } else if (value < 0) { - return Long.fromNumber(-value).negate(); - } else { - return new Long( - (value % Long.TWO_PWR_32_DBL_) | 0, - (value / Long.TWO_PWR_32_DBL_) | 0); - } -}; - -/** - * Returns a Long representing the 64-bit integer that comes by concatenating the given high and low bits. Each is assumed to use 32 bits. - * - * @method - * @param {number} lowBits the low 32-bits. - * @param {number} highBits the high 32-bits. - * @return {Long} the corresponding Long value. - */ -Long.fromBits = function(lowBits, highBits) { - return new Long(lowBits, highBits); -}; - -/** - * Returns a Long representation of the given string, written using the given radix. - * - * @method - * @param {string} str the textual representation of the Long. - * @param {number} opt_radix the radix in which the text is written. - * @return {Long} the corresponding Long value. - */ -Long.fromString = function(str, opt_radix) { - if (str.length == 0) { - throw Error('number format error: empty string'); - } - - var radix = opt_radix || 10; - if (radix < 2 || 36 < radix) { - throw Error('radix out of range: ' + radix); - } - - if (str.charAt(0) == '-') { - return Long.fromString(str.substring(1), radix).negate(); - } else if (str.indexOf('-') >= 0) { - throw Error('number format error: interior "-" character: ' + str); - } - - // Do several (8) digits each time through the loop, so as to - // minimize the calls to the very expensive emulated div. - var radixToPower = Long.fromNumber(Math.pow(radix, 8)); - - var result = Long.ZERO; - for (var i = 0; i < str.length; i += 8) { - var size = Math.min(8, str.length - i); - var value = parseInt(str.substring(i, i + size), radix); - if (size < 8) { - var power = Long.fromNumber(Math.pow(radix, size)); - result = result.multiply(power).add(Long.fromNumber(value)); - } else { - result = result.multiply(radixToPower); - result = result.add(Long.fromNumber(value)); - } - } - return result; -}; - -// NOTE: Common constant values ZERO, ONE, NEG_ONE, etc. are defined below the -// from* methods on which they depend. - - -/** - * A cache of the Long representations of small integer values. - * @type {Object} - * @ignore - */ -Long.INT_CACHE_ = {}; - -// NOTE: the compiler should inline these constant values below and then remove -// these variables, so there should be no runtime penalty for these. - -/** - * Number used repeated below in calculations. This must appear before the - * first call to any from* function below. - * @type {number} - * @ignore - */ -Long.TWO_PWR_16_DBL_ = 1 << 16; - -/** - * @type {number} - * @ignore - */ -Long.TWO_PWR_24_DBL_ = 1 << 24; - -/** - * @type {number} - * @ignore - */ -Long.TWO_PWR_32_DBL_ = Long.TWO_PWR_16_DBL_ * Long.TWO_PWR_16_DBL_; - -/** - * @type {number} - * @ignore - */ -Long.TWO_PWR_31_DBL_ = Long.TWO_PWR_32_DBL_ / 2; - -/** - * @type {number} - * @ignore - */ -Long.TWO_PWR_48_DBL_ = Long.TWO_PWR_32_DBL_ * Long.TWO_PWR_16_DBL_; - -/** - * @type {number} - * @ignore - */ -Long.TWO_PWR_64_DBL_ = Long.TWO_PWR_32_DBL_ * Long.TWO_PWR_32_DBL_; - -/** - * @type {number} - * @ignore - */ -Long.TWO_PWR_63_DBL_ = Long.TWO_PWR_64_DBL_ / 2; - -/** @type {Long} */ -Long.ZERO = Long.fromInt(0); - -/** @type {Long} */ -Long.ONE = Long.fromInt(1); - -/** @type {Long} */ -Long.NEG_ONE = Long.fromInt(-1); - -/** @type {Long} */ -Long.MAX_VALUE = - Long.fromBits(0xFFFFFFFF | 0, 0x7FFFFFFF | 0); - -/** @type {Long} */ -Long.MIN_VALUE = Long.fromBits(0, 0x80000000 | 0); - -/** - * @type {Long} - * @ignore - */ -Long.TWO_PWR_24_ = Long.fromInt(1 << 24); - -/** - * Expose. - */ -module.exports = Long; -module.exports.Long = Long; \ No newline at end of file diff --git a/ts-ticket-office-service/node_modules/bson/lib/bson/map.js b/ts-ticket-office-service/node_modules/bson/lib/bson/map.js deleted file mode 100644 index f53c8c162..000000000 --- a/ts-ticket-office-service/node_modules/bson/lib/bson/map.js +++ /dev/null @@ -1,126 +0,0 @@ -"use strict" - -// We have an ES6 Map available, return the native instance -if(typeof global.Map !== 'undefined') { - module.exports = global.Map; - module.exports.Map = global.Map; -} else { - // We will return a polyfill - var Map = function(array) { - this._keys = []; - this._values = {}; - - for(var i = 0; i < array.length; i++) { - if(array[i] == null) continue; // skip null and undefined - var entry = array[i]; - var key = entry[0]; - var value = entry[1]; - // Add the key to the list of keys in order - this._keys.push(key); - // Add the key and value to the values dictionary with a point - // to the location in the ordered keys list - this._values[key] = {v: value, i: this._keys.length - 1}; - } - } - - Map.prototype.clear = function() { - this._keys = []; - this._values = {}; - } - - Map.prototype.delete = function(key) { - var value = this._values[key]; - if(value == null) return false; - // Delete entry - delete this._values[key]; - // Remove the key from the ordered keys list - this._keys.splice(value.i, 1); - return true; - } - - Map.prototype.entries = function() { - var self = this; - var index = 0; - - return { - next: function() { - var key = self._keys[index++]; - return { - value: key !== undefined ? [key, self._values[key].v] : undefined, - done: key !== undefined ? false : true - } - } - }; - } - - Map.prototype.forEach = function(callback, self) { - self = self || this; - - for(var i = 0; i < this._keys.length; i++) { - var key = this._keys[i]; - // Call the forEach callback - callback.call(self, this._values[key].v, key, self); - } - } - - Map.prototype.get = function(key) { - return this._values[key] ? this._values[key].v : undefined; - } - - Map.prototype.has = function(key) { - return this._values[key] != null; - } - - Map.prototype.keys = function(key) { - var self = this; - var index = 0; - - return { - next: function() { - var key = self._keys[index++]; - return { - value: key !== undefined ? key : undefined, - done: key !== undefined ? false : true - } - } - }; - } - - Map.prototype.set = function(key, value) { - if(this._values[key]) { - this._values[key].v = value; - return this; - } - - // Add the key to the list of keys in order - this._keys.push(key); - // Add the key and value to the values dictionary with a point - // to the location in the ordered keys list - this._values[key] = {v: value, i: this._keys.length - 1}; - return this; - } - - Map.prototype.values = function(key, value) { - var self = this; - var index = 0; - - return { - next: function() { - var key = self._keys[index++]; - return { - value: key !== undefined ? self._values[key].v : undefined, - done: key !== undefined ? false : true - } - } - }; - } - - // Last ismaster - Object.defineProperty(Map.prototype, 'size', { - enumerable:true, - get: function() { return this._keys.length; } - }); - - module.exports = Map; - module.exports.Map = Map; -} \ No newline at end of file diff --git a/ts-ticket-office-service/node_modules/bson/lib/bson/max_key.js b/ts-ticket-office-service/node_modules/bson/lib/bson/max_key.js deleted file mode 100644 index 03ee9cdd1..000000000 --- a/ts-ticket-office-service/node_modules/bson/lib/bson/max_key.js +++ /dev/null @@ -1,14 +0,0 @@ -/** - * A class representation of the BSON MaxKey type. - * - * @class - * @return {MaxKey} A MaxKey instance - */ -function MaxKey() { - if(!(this instanceof MaxKey)) return new MaxKey(); - - this._bsontype = 'MaxKey'; -} - -module.exports = MaxKey; -module.exports.MaxKey = MaxKey; \ No newline at end of file diff --git a/ts-ticket-office-service/node_modules/bson/lib/bson/min_key.js b/ts-ticket-office-service/node_modules/bson/lib/bson/min_key.js deleted file mode 100644 index 5e120fbef..000000000 --- a/ts-ticket-office-service/node_modules/bson/lib/bson/min_key.js +++ /dev/null @@ -1,14 +0,0 @@ -/** - * A class representation of the BSON MinKey type. - * - * @class - * @return {MinKey} A MinKey instance - */ -function MinKey() { - if(!(this instanceof MinKey)) return new MinKey(); - - this._bsontype = 'MinKey'; -} - -module.exports = MinKey; -module.exports.MinKey = MinKey; \ No newline at end of file diff --git a/ts-ticket-office-service/node_modules/bson/lib/bson/objectid.js b/ts-ticket-office-service/node_modules/bson/lib/bson/objectid.js deleted file mode 100644 index 4a52ab660..000000000 --- a/ts-ticket-office-service/node_modules/bson/lib/bson/objectid.js +++ /dev/null @@ -1,362 +0,0 @@ -/** - * Machine id. - * - * Create a random 3-byte value (i.e. unique for this - * process). Other drivers use a md5 of the machine id here, but - * that would mean an asyc call to gethostname, so we don't bother. - * @ignore - */ -var MACHINE_ID = parseInt(Math.random() * 0xFFFFFF, 10); - -// Regular expression that checks for hex value -var checkForHexRegExp = new RegExp("^[0-9a-fA-F]{24}$"); -var hasBufferType = false; - -// Check if buffer exists -try { - if(Buffer && Buffer.from) hasBufferType = true; -} catch(err) {}; - -/** -* Create a new ObjectID instance -* -* @class -* @param {(string|number)} id Can be a 24 byte hex string, 12 byte binary string or a Number. -* @property {number} generationTime The generation time of this ObjectId instance -* @return {ObjectID} instance of ObjectID. -*/ -var ObjectID = function ObjectID(id) { - // Duck-typing to support ObjectId from different npm packages - if(id instanceof ObjectID) return id; - if(!(this instanceof ObjectID)) return new ObjectID(id); - - this._bsontype = 'ObjectID'; - - // The most common usecase (blank id, new objectId instance) - if(id == null || typeof id == 'number') { - // Generate a new id - this.id = this.generate(id); - // If we are caching the hex string - if(ObjectID.cacheHexString) this.__id = this.toString('hex'); - // Return the object - return; - } - - // Check if the passed in id is valid - var valid = ObjectID.isValid(id); - - // Throw an error if it's not a valid setup - if(!valid && id != null){ - throw new Error("Argument passed in must be a single String of 12 bytes or a string of 24 hex characters"); - } else if(valid && typeof id == 'string' && id.length == 24 && hasBufferType) { - return new ObjectID(new Buffer(id, 'hex')); - } else if(valid && typeof id == 'string' && id.length == 24) { - return ObjectID.createFromHexString(id); - } else if(id != null && id.length === 12) { - // assume 12 byte string - this.id = id; - } else if(id != null && id.toHexString) { - // Duck-typing to support ObjectId from different npm packages - return id; - } else { - throw new Error("Argument passed in must be a single String of 12 bytes or a string of 24 hex characters"); - } - - if(ObjectID.cacheHexString) this.__id = this.toString('hex'); -}; - -// Allow usage of ObjectId as well as ObjectID -var ObjectId = ObjectID; - -// Precomputed hex table enables speedy hex string conversion -var hexTable = []; -for (var i = 0; i < 256; i++) { - hexTable[i] = (i <= 15 ? '0' : '') + i.toString(16); -} - -/** -* Return the ObjectID id as a 24 byte hex string representation -* -* @method -* @return {string} return the 24 byte hex string representation. -*/ -ObjectID.prototype.toHexString = function() { - if(ObjectID.cacheHexString && this.__id) return this.__id; - - var hexString = ''; - if(!this.id || !this.id.length) { - throw new Error('invalid ObjectId, ObjectId.id must be either a string or a Buffer, but is [' + JSON.stringify(this.id) + ']'); - } - - if(this.id instanceof _Buffer) { - hexString = convertToHex(this.id); - if(ObjectID.cacheHexString) this.__id = hexString; - return hexString; - } - - for (var i = 0; i < this.id.length; i++) { - hexString += hexTable[this.id.charCodeAt(i)]; - } - - if(ObjectID.cacheHexString) this.__id = hexString; - return hexString; -}; - -/** -* Update the ObjectID index used in generating new ObjectID's on the driver -* -* @method -* @return {number} returns next index value. -* @ignore -*/ -ObjectID.prototype.get_inc = function() { - return ObjectID.index = (ObjectID.index + 1) % 0xFFFFFF; -}; - -/** -* Update the ObjectID index used in generating new ObjectID's on the driver -* -* @method -* @return {number} returns next index value. -* @ignore -*/ -ObjectID.prototype.getInc = function() { - return this.get_inc(); -}; - -/** -* Generate a 12 byte id buffer used in ObjectID's -* -* @method -* @param {number} [time] optional parameter allowing to pass in a second based timestamp. -* @return {Buffer} return the 12 byte id buffer string. -*/ -ObjectID.prototype.generate = function(time) { - if ('number' != typeof time) { - time = ~~(Date.now()/1000); - } - - // Use pid - var pid = (typeof process === 'undefined' ? Math.floor(Math.random() * 100000) : process.pid) % 0xFFFF; - var inc = this.get_inc(); - // Buffer used - var buffer = new Buffer(12); - // Encode time - buffer[3] = time & 0xff; - buffer[2] = (time >> 8) & 0xff; - buffer[1] = (time >> 16) & 0xff; - buffer[0] = (time >> 24) & 0xff; - // Encode machine - buffer[6] = MACHINE_ID & 0xff; - buffer[5] = (MACHINE_ID >> 8) & 0xff; - buffer[4] = (MACHINE_ID >> 16) & 0xff; - // Encode pid - buffer[8] = pid & 0xff; - buffer[7] = (pid >> 8) & 0xff; - // Encode index - buffer[11] = inc & 0xff; - buffer[10] = (inc >> 8) & 0xff; - buffer[9] = (inc >> 16) & 0xff; - // Return the buffer - return buffer; -}; - -/** -* Converts the id into a 24 byte hex string for printing -* -* @param {String} format The Buffer toString format parameter. -* @return {String} return the 24 byte hex string representation. -* @ignore -*/ -ObjectID.prototype.toString = function(format) { - // Is the id a buffer then use the buffer toString method to return the format - if(this.id && this.id.copy) { - return this.id.toString(typeof format === 'string' ? format : 'hex'); - } - - // if(this.buffer ) - return this.toHexString(); -}; - -/** -* Converts to a string representation of this Id. -* -* @return {String} return the 24 byte hex string representation. -* @ignore -*/ -ObjectID.prototype.inspect = ObjectID.prototype.toString; - -/** -* Converts to its JSON representation. -* -* @return {String} return the 24 byte hex string representation. -* @ignore -*/ -ObjectID.prototype.toJSON = function() { - return this.toHexString(); -}; - -/** -* Compares the equality of this ObjectID with `otherID`. -* -* @method -* @param {object} otherID ObjectID instance to compare against. -* @return {boolean} the result of comparing two ObjectID's -*/ -ObjectID.prototype.equals = function equals (otherId) { - var id; - - if(otherId instanceof ObjectID) { - return this.toString() == otherId.toString(); - } else if(typeof otherId == 'string' && ObjectID.isValid(otherId) && otherId.length == 12 && this.id instanceof _Buffer) { - return otherId === this.id.toString('binary'); - } else if(typeof otherId == 'string' && ObjectID.isValid(otherId) && otherId.length == 24) { - return otherId.toLowerCase() === this.toHexString(); - } else if(typeof otherId == 'string' && ObjectID.isValid(otherId) && otherId.length == 12) { - return otherId === this.id; - } else if(otherId != null && (otherId instanceof ObjectID || otherId.toHexString)) { - return otherId.toHexString() === this.toHexString(); - } else { - return false; - } -} - -/** -* Returns the generation date (accurate up to the second) that this ID was generated. -* -* @method -* @return {date} the generation date -*/ -ObjectID.prototype.getTimestamp = function() { - var timestamp = new Date(); - var time = this.id[3] | this.id[2] << 8 | this.id[1] << 16 | this.id[0] << 24; - timestamp.setTime(Math.floor(time) * 1000); - return timestamp; -} - -/** -* @ignore -*/ -ObjectID.index = ~~(Math.random() * 0xFFFFFF); - -/** -* @ignore -*/ -ObjectID.createPk = function createPk () { - return new ObjectID(); -}; - -/** -* Creates an ObjectID from a second based number, with the rest of the ObjectID zeroed out. Used for comparisons or sorting the ObjectID. -* -* @method -* @param {number} time an integer number representing a number of seconds. -* @return {ObjectID} return the created ObjectID -*/ -ObjectID.createFromTime = function createFromTime (time) { - var buffer = new Buffer([0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]); - // Encode time into first 4 bytes - buffer[3] = time & 0xff; - buffer[2] = (time >> 8) & 0xff; - buffer[1] = (time >> 16) & 0xff; - buffer[0] = (time >> 24) & 0xff; - // Return the new objectId - return new ObjectID(buffer); -}; - -// Lookup tables -var encodeLookup = '0123456789abcdef'.split('') -var decodeLookup = [] -var i = 0 -while (i < 10) decodeLookup[0x30 + i] = i++ -while (i < 16) decodeLookup[0x41 - 10 + i] = decodeLookup[0x61 - 10 + i] = i++ - -var _Buffer = Buffer; -var convertToHex = function(bytes) { - return bytes.toString('hex'); -} - -/** -* Creates an ObjectID from a hex string representation of an ObjectID. -* -* @method -* @param {string} hexString create a ObjectID from a passed in 24 byte hexstring. -* @return {ObjectID} return the created ObjectID -*/ -ObjectID.createFromHexString = function createFromHexString (string) { - // Throw an error if it's not a valid setup - if(typeof string === 'undefined' || string != null && string.length != 24) { - throw new Error("Argument passed in must be a single String of 12 bytes or a string of 24 hex characters"); - } - - // Use Buffer.from method if available - if(hasBufferType) return new ObjectID(new Buffer(string, 'hex')); - - // Calculate lengths - var array = new _Buffer(12); - var n = 0; - var i = 0; - - while (i < 24) { - array[n++] = decodeLookup[string.charCodeAt(i++)] << 4 | decodeLookup[string.charCodeAt(i++)] - } - - return new ObjectID(array); -}; - -/** -* Checks if a value is a valid bson ObjectId -* -* @method -* @return {boolean} return true if the value is a valid bson ObjectId, return false otherwise. -*/ -ObjectID.isValid = function isValid(id) { - if(id == null) return false; - - if(typeof id == 'number') { - return true; - } - - if(typeof id == 'string') { - return id.length == 12 || (id.length == 24 && checkForHexRegExp.test(id)); - } - - if(id instanceof ObjectID) { - return true; - } - - if(id instanceof _Buffer) { - return true; - } - - // Duck-Typing detection of ObjectId like objects - if(id.toHexString) { - return id.id.length == 12 || (id.id.length == 24 && checkForHexRegExp.test(id.id)); - } - - return false; -}; - -/** -* @ignore -*/ -Object.defineProperty(ObjectID.prototype, "generationTime", { - enumerable: true - , get: function () { - return this.id[3] | this.id[2] << 8 | this.id[1] << 16 | this.id[0] << 24; - } - , set: function (value) { - // Encode time into first 4 bytes - this.id[3] = value & 0xff; - this.id[2] = (value >> 8) & 0xff; - this.id[1] = (value >> 16) & 0xff; - this.id[0] = (value >> 24) & 0xff; - } -}); - -/** - * Expose. - */ -module.exports = ObjectID; -module.exports.ObjectID = ObjectID; -module.exports.ObjectId = ObjectID; diff --git a/ts-ticket-office-service/node_modules/bson/lib/bson/parser/calculate_size.js b/ts-ticket-office-service/node_modules/bson/lib/bson/parser/calculate_size.js deleted file mode 100644 index 53d338f58..000000000 --- a/ts-ticket-office-service/node_modules/bson/lib/bson/parser/calculate_size.js +++ /dev/null @@ -1,152 +0,0 @@ -"use strict" - -var writeIEEE754 = require('../float_parser').writeIEEE754 - , readIEEE754 = require('../float_parser').readIEEE754 - , Long = require('../long').Long - , Double = require('../double').Double - , Timestamp = require('../timestamp').Timestamp - , ObjectID = require('../objectid').ObjectID - , Symbol = require('../symbol').Symbol - , BSONRegExp = require('../regexp').BSONRegExp - , Code = require('../code').Code - , Decimal128 = require('../decimal128') - , MinKey = require('../min_key').MinKey - , MaxKey = require('../max_key').MaxKey - , DBRef = require('../db_ref').DBRef - , Binary = require('../binary').Binary; - -// To ensure that 0.4 of node works correctly -var isDate = function isDate(d) { - return typeof d === 'object' && Object.prototype.toString.call(d) === '[object Date]'; -} - -var calculateObjectSize = function calculateObjectSize(object, serializeFunctions, ignoreUndefined) { - var totalLength = (4 + 1); - - if(Array.isArray(object)) { - for(var i = 0; i < object.length; i++) { - totalLength += calculateElement(i.toString(), object[i], serializeFunctions, true, ignoreUndefined) - } - } else { - // If we have toBSON defined, override the current object - if(object.toBSON) { - object = object.toBSON(); - } - - // Calculate size - for(var key in object) { - totalLength += calculateElement(key, object[key], serializeFunctions, false, ignoreUndefined) - } - } - - return totalLength; -} - -/** - * @ignore - * @api private - */ -function calculateElement(name, value, serializeFunctions, isArray, ignoreUndefined) { - // If we have toBSON defined, override the current object - if(value && value.toBSON){ - value = value.toBSON(); - } - - switch(typeof value) { - case 'string': - return 1 + Buffer.byteLength(name, 'utf8') + 1 + 4 + Buffer.byteLength(value, 'utf8') + 1; - case 'number': - if(Math.floor(value) === value && value >= BSON.JS_INT_MIN && value <= BSON.JS_INT_MAX) { - if(value >= BSON.BSON_INT32_MIN && value <= BSON.BSON_INT32_MAX) { // 32 bit - return (name != null ? (Buffer.byteLength(name, 'utf8') + 1) : 0) + (4 + 1); - } else { - return (name != null ? (Buffer.byteLength(name, 'utf8') + 1) : 0) + (8 + 1); - } - } else { // 64 bit - return (name != null ? (Buffer.byteLength(name, 'utf8') + 1) : 0) + (8 + 1); - } - case 'undefined': - if(isArray || !ignoreUndefined) return (name != null ? (Buffer.byteLength(name, 'utf8') + 1) : 0) + (1); - return 0; - case 'boolean': - return (name != null ? (Buffer.byteLength(name, 'utf8') + 1) : 0) + (1 + 1); - case 'object': - if(value == null || value instanceof MinKey || value instanceof MaxKey || value['_bsontype'] == 'MinKey' || value['_bsontype'] == 'MaxKey') { - return (name != null ? (Buffer.byteLength(name, 'utf8') + 1) : 0) + (1); - } else if(value instanceof ObjectID || value['_bsontype'] == 'ObjectID') { - return (name != null ? (Buffer.byteLength(name, 'utf8') + 1) : 0) + (12 + 1); - } else if(value instanceof Date || isDate(value)) { - return (name != null ? (Buffer.byteLength(name, 'utf8') + 1) : 0) + (8 + 1); - } else if(typeof Buffer !== 'undefined' && Buffer.isBuffer(value)) { - return (name != null ? (Buffer.byteLength(name, 'utf8') + 1) : 0) + (1 + 4 + 1) + value.length; - } else if(value instanceof Long || value instanceof Double || value instanceof Timestamp - || value['_bsontype'] == 'Long' || value['_bsontype'] == 'Double' || value['_bsontype'] == 'Timestamp') { - return (name != null ? (Buffer.byteLength(name, 'utf8') + 1) : 0) + (8 + 1); - } else if(value instanceof Decimal128 || value['_bsontype'] == 'Decimal128') { - return (name != null ? (Buffer.byteLength(name, 'utf8') + 1) : 0) + (16 + 1); - } else if(value instanceof Code || value['_bsontype'] == 'Code') { - // Calculate size depending on the availability of a scope - if(value.scope != null && Object.keys(value.scope).length > 0) { - return (name != null ? (Buffer.byteLength(name, 'utf8') + 1) : 0) + 1 + 4 + 4 + Buffer.byteLength(value.code.toString(), 'utf8') + 1 + calculateObjectSize(value.scope, serializeFunctions, ignoreUndefined); - } else { - return (name != null ? (Buffer.byteLength(name, 'utf8') + 1) : 0) + 1 + 4 + Buffer.byteLength(value.code.toString(), 'utf8') + 1; - } - } else if(value instanceof Binary || value['_bsontype'] == 'Binary') { - // Check what kind of subtype we have - if(value.sub_type == Binary.SUBTYPE_BYTE_ARRAY) { - return (name != null ? (Buffer.byteLength(name, 'utf8') + 1) : 0) + (value.position + 1 + 4 + 1 + 4); - } else { - return (name != null ? (Buffer.byteLength(name, 'utf8') + 1) : 0) + (value.position + 1 + 4 + 1); - } - } else if(value instanceof Symbol || value['_bsontype'] == 'Symbol') { - return (name != null ? (Buffer.byteLength(name, 'utf8') + 1) : 0) + Buffer.byteLength(value.value, 'utf8') + 4 + 1 + 1; - } else if(value instanceof DBRef || value['_bsontype'] == 'DBRef') { - // Set up correct object for serialization - var ordered_values = { - '$ref': value.namespace - , '$id' : value.oid - }; - - // Add db reference if it exists - if(null != value.db) { - ordered_values['$db'] = value.db; - } - - return (name != null ? (Buffer.byteLength(name, 'utf8') + 1) : 0) + 1 + calculateObjectSize(ordered_values, serializeFunctions, ignoreUndefined); - } else if(value instanceof RegExp || Object.prototype.toString.call(value) === '[object RegExp]') { - return (name != null ? (Buffer.byteLength(name, 'utf8') + 1) : 0) + 1 + Buffer.byteLength(value.source, 'utf8') + 1 - + (value.global ? 1 : 0) + (value.ignoreCase ? 1 : 0) + (value.multiline ? 1 : 0) + 1 - } else if(value instanceof BSONRegExp || value['_bsontype'] == 'BSONRegExp') { - return (name != null ? (Buffer.byteLength(name, 'utf8') + 1) : 0) + 1 + Buffer.byteLength(value.pattern, 'utf8') + 1 - + Buffer.byteLength(value.options, 'utf8') + 1 - } else { - return (name != null ? (Buffer.byteLength(name, 'utf8') + 1) : 0) + calculateObjectSize(value, serializeFunctions, ignoreUndefined) + 1; - } - case 'function': - // WTF for 0.4.X where typeof /someregexp/ === 'function' - if(value instanceof RegExp || Object.prototype.toString.call(value) === '[object RegExp]' || String.call(value) == '[object RegExp]') { - return (name != null ? (Buffer.byteLength(name, 'utf8') + 1) : 0) + 1 + Buffer.byteLength(value.source, 'utf8') + 1 - + (value.global ? 1 : 0) + (value.ignoreCase ? 1 : 0) + (value.multiline ? 1 : 0) + 1 - } else { - if(serializeFunctions && value.scope != null && Object.keys(value.scope).length > 0) { - return (name != null ? (Buffer.byteLength(name, 'utf8') + 1) : 0) + 1 + 4 + 4 + Buffer.byteLength(value.toString(), 'utf8') + 1 + calculateObjectSize(value.scope, serializeFunctions, ignoreUndefined); - } else if(serializeFunctions) { - return (name != null ? (Buffer.byteLength(name, 'utf8') + 1) : 0) + 1 + 4 + Buffer.byteLength(value.toString(), 'utf8') + 1; - } - } - } - - return 0; -} - -var BSON = {}; - -// BSON MAX VALUES -BSON.BSON_INT32_MAX = 0x7FFFFFFF; -BSON.BSON_INT32_MIN = -0x80000000; - -// JS MAX PRECISE VALUES -BSON.JS_INT_MAX = 0x20000000000000; // Any integer up to 2^53 can be precisely represented by a double. -BSON.JS_INT_MIN = -0x20000000000000; // Any integer down to -2^53 can be precisely represented by a double. - -module.exports = calculateObjectSize; diff --git a/ts-ticket-office-service/node_modules/bson/lib/bson/parser/deserializer.js b/ts-ticket-office-service/node_modules/bson/lib/bson/parser/deserializer.js deleted file mode 100644 index 35818a3c2..000000000 --- a/ts-ticket-office-service/node_modules/bson/lib/bson/parser/deserializer.js +++ /dev/null @@ -1,653 +0,0 @@ -"use strict" - -var readIEEE754 = require('../float_parser').readIEEE754, - f = require('util').format, - Long = require('../long').Long, - Double = require('../double').Double, - Timestamp = require('../timestamp').Timestamp, - ObjectID = require('../objectid').ObjectID, - Symbol = require('../symbol').Symbol, - Code = require('../code').Code, - MinKey = require('../min_key').MinKey, - MaxKey = require('../max_key').MaxKey, - Decimal128 = require('../decimal128'), - Int32 = require('../int_32'), - DBRef = require('../db_ref').DBRef, - BSONRegExp = require('../regexp').BSONRegExp, - Binary = require('../binary').Binary; - -var deserialize = function(buffer, options, isArray) { - options = options == null ? {} : options; - var index = options && options.index ? options.index : 0; - // Read the document size - var size = buffer[index] | buffer[index+1] << 8 | buffer[index+2] << 16 | buffer[index+3] << 24; - - // Ensure buffer is valid size - if(size < 5 || buffer.length < size || (size + index) > buffer.length) { - throw new Error("corrupt bson message"); - } - - // Illegal end value - if(buffer[index + size - 1] != 0) { - throw new Error("One object, sized correctly, with a spot for an EOO, but the EOO isn't 0x00"); - } - - // Start deserializtion - return deserializeObject(buffer, index, options, isArray); -} - -var deserializeObject = function(buffer, index, options, isArray) { - var evalFunctions = options['evalFunctions'] == null ? false : options['evalFunctions']; - var cacheFunctions = options['cacheFunctions'] == null ? false : options['cacheFunctions']; - var cacheFunctionsCrc32 = options['cacheFunctionsCrc32'] == null ? false : options['cacheFunctionsCrc32']; - var fieldsAsRaw = options['fieldsAsRaw'] == null ? null : options['fieldsAsRaw']; - - // Return raw bson buffer instead of parsing it - var raw = options['raw'] == null ? false : options['raw']; - - // Return BSONRegExp objects instead of native regular expressions - var bsonRegExp = typeof options['bsonRegExp'] == 'boolean' ? options['bsonRegExp'] : false; - - // Controls the promotion of values vs wrapper classes - var promoteBuffers = options['promoteBuffers'] == null ? false : options['promoteBuffers']; - var promoteLongs = options['promoteLongs'] == null ? true : options['promoteLongs']; - var promoteValues = options['promoteValues'] == null ? true : options['promoteValues']; - - // Set the start index - var startIndex = index; - - // Validate that we have at least 4 bytes of buffer - if(buffer.length < 5) throw new Error("corrupt bson message < 5 bytes long"); - - // Read the document size - var size = buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24; - - // Ensure buffer is valid size - if(size < 5 || size > buffer.length) throw new Error("corrupt bson message"); - - // Create holding object - var object = isArray ? [] : {}; - // Used for arrays to skip having to perform utf8 decoding - var arrayIndex = 0; - - // While we have more left data left keep parsing - while(true) { - // Read the type - var elementType = buffer[index++]; - // If we get a zero it's the last byte, exit - if(elementType == 0) { - break; - } - - // Get the start search index - var i = index; - // Locate the end of the c string - while(buffer[i] !== 0x00 && i < buffer.length) { - i++ - } - - // If are at the end of the buffer there is a problem with the document - if(i >= buffer.length) throw new Error("Bad BSON Document: illegal CString") - var name = isArray ? arrayIndex++ : buffer.toString('utf8', index, i); - - index = i + 1; - - if(elementType == BSON.BSON_DATA_STRING) { - var stringSize = buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24; - if(stringSize <= 0 || stringSize > (buffer.length - index) || buffer[index + stringSize - 1] != 0) throw new Error("bad string length in bson"); - object[name] = buffer.toString('utf8', index, index + stringSize - 1); - index = index + stringSize; - } else if(elementType == BSON.BSON_DATA_OID) { - var oid = new Buffer(12); - buffer.copy(oid, 0, index, index + 12); - object[name] = new ObjectID(oid); - index = index + 12; - } else if(elementType == BSON.BSON_DATA_INT && promoteValues == false) { - object[name] = new Int32(buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24); - } else if(elementType == BSON.BSON_DATA_INT) { - object[name] = buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24; - } else if(elementType == BSON.BSON_DATA_NUMBER && promoteValues == false) { - object[name] = new Double(buffer.readDoubleLE(index)); - index = index + 8; - } else if(elementType == BSON.BSON_DATA_NUMBER) { - object[name] = buffer.readDoubleLE(index); - index = index + 8; - } else if(elementType == BSON.BSON_DATA_DATE) { - var lowBits = buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24; - var highBits = buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24; - object[name] = new Date(new Long(lowBits, highBits).toNumber()); - } else if(elementType == BSON.BSON_DATA_BOOLEAN) { - if(buffer[index] != 0 && buffer[index] != 1) throw new Error('illegal boolean type value'); - object[name] = buffer[index++] == 1; - } else if(elementType == BSON.BSON_DATA_OBJECT) { - var _index = index; - var objectSize = buffer[index] | buffer[index + 1] << 8 | buffer[index + 2] << 16 | buffer[index + 3] << 24; - if(objectSize <= 0 || objectSize > (buffer.length - index)) throw new Error("bad embedded document length in bson"); - - // We have a raw value - if(raw) { - object[name] = buffer.slice(index, index + objectSize); - } else { - object[name] = deserializeObject(buffer, _index, options, false); - } - - index = index + objectSize; - } else if(elementType == BSON.BSON_DATA_ARRAY) { - var _index = index; - var objectSize = buffer[index] | buffer[index + 1] << 8 | buffer[index + 2] << 16 | buffer[index + 3] << 24; - var arrayOptions = options; - - // Stop index - var stopIndex = index + objectSize; - - // All elements of array to be returned as raw bson - if(fieldsAsRaw && fieldsAsRaw[name]) { - arrayOptions = {}; - for(var n in options) arrayOptions[n] = options[n]; - arrayOptions['raw'] = true; - } - - object[name] = deserializeObject(buffer, _index, arrayOptions, true); - index = index + objectSize; - - if(buffer[index - 1] != 0) throw new Error('invalid array terminator byte'); - if(index != stopIndex) throw new Error('corrupted array bson'); - } else if(elementType == BSON.BSON_DATA_UNDEFINED) { - object[name] = undefined; - } else if(elementType == BSON.BSON_DATA_NULL) { - object[name] = null; - } else if(elementType == BSON.BSON_DATA_LONG) { - // Unpack the low and high bits - var lowBits = buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24; - var highBits = buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24; - var long = new Long(lowBits, highBits); - // Promote the long if possible - if(promoteLongs && promoteValues == true) { - object[name] = long.lessThanOrEqual(JS_INT_MAX_LONG) && long.greaterThanOrEqual(JS_INT_MIN_LONG) ? long.toNumber() : long; - } else { - object[name] = long; - } - } else if(elementType == BSON.BSON_DATA_DECIMAL128) { - // Buffer to contain the decimal bytes - var bytes = new Buffer(16); - // Copy the next 16 bytes into the bytes buffer - buffer.copy(bytes, 0, index, index + 16); - // Update index - index = index + 16; - // Assign the new Decimal128 value - var decimal128 = new Decimal128(bytes); - // If we have an alternative mapper use that - object[name] = decimal128.toObject ? decimal128.toObject() : decimal128; - } else if(elementType == BSON.BSON_DATA_BINARY) { - var binarySize = buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24; - var totalBinarySize = binarySize; - var subType = buffer[index++]; - - // Did we have a negative binary size, throw - if(binarySize < 0) throw new Error('Negative binary type element size found'); - - // Is the length longer than the document - if(binarySize > buffer.length) throw new Error('Binary type size larger than document size'); - - // Decode as raw Buffer object if options specifies it - if(buffer['slice'] != null) { - // If we have subtype 2 skip the 4 bytes for the size - if(subType == Binary.SUBTYPE_BYTE_ARRAY) { - binarySize = buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24; - if(binarySize < 0) throw new Error('Negative binary type element size found for subtype 0x02'); - if(binarySize > (totalBinarySize - 4)) throw new Error('Binary type with subtype 0x02 contains to long binary size'); - if(binarySize < (totalBinarySize - 4)) throw new Error('Binary type with subtype 0x02 contains to short binary size'); - } - - if(promoteBuffers && promoteValues) { - object[name] = buffer.slice(index, index + binarySize); - } else { - object[name] = new Binary(buffer.slice(index, index + binarySize), subType); - } - } else { - var _buffer = typeof Uint8Array != 'undefined' ? new Uint8Array(new ArrayBuffer(binarySize)) : new Array(binarySize); - // If we have subtype 2 skip the 4 bytes for the size - if(subType == Binary.SUBTYPE_BYTE_ARRAY) { - binarySize = buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24; - if(binarySize < 0) throw new Error('Negative binary type element size found for subtype 0x02'); - if(binarySize > (totalBinarySize - 4)) throw new Error('Binary type with subtype 0x02 contains to long binary size'); - if(binarySize < (totalBinarySize - 4)) throw new Error('Binary type with subtype 0x02 contains to short binary size'); - } - - // Copy the data - for(var i = 0; i < binarySize; i++) { - _buffer[i] = buffer[index + i]; - } - - if(promoteBuffers && promoteValues) { - object[name] = _buffer; - } else { - object[name] = new Binary(_buffer, subType); - } - } - - // Update the index - index = index + binarySize; - } else if(elementType == BSON.BSON_DATA_REGEXP && bsonRegExp == false) { - // Get the start search index - var i = index; - // Locate the end of the c string - while(buffer[i] !== 0x00 && i < buffer.length) { - i++ - } - // If are at the end of the buffer there is a problem with the document - if(i >= buffer.length) throw new Error("Bad BSON Document: illegal CString") - // Return the C string - var source = buffer.toString('utf8', index, i); - // Create the regexp - index = i + 1; - - // Get the start search index - var i = index; - // Locate the end of the c string - while(buffer[i] !== 0x00 && i < buffer.length) { - i++ - } - // If are at the end of the buffer there is a problem with the document - if(i >= buffer.length) throw new Error("Bad BSON Document: illegal CString") - // Return the C string - var regExpOptions = buffer.toString('utf8', index, i); - index = i + 1; - - // For each option add the corresponding one for javascript - var optionsArray = new Array(regExpOptions.length); - - // Parse options - for(var i = 0; i < regExpOptions.length; i++) { - switch(regExpOptions[i]) { - case 'm': - optionsArray[i] = 'm'; - break; - case 's': - optionsArray[i] = 'g'; - break; - case 'i': - optionsArray[i] = 'i'; - break; - } - } - - object[name] = new RegExp(source, optionsArray.join('')); - } else if(elementType == BSON.BSON_DATA_REGEXP && bsonRegExp == true) { - // Get the start search index - var i = index; - // Locate the end of the c string - while(buffer[i] !== 0x00 && i < buffer.length) { - i++ - } - // If are at the end of the buffer there is a problem with the document - if(i >= buffer.length) throw new Error("Bad BSON Document: illegal CString") - // Return the C string - var source = buffer.toString('utf8', index, i); - index = i + 1; - - // Get the start search index - var i = index; - // Locate the end of the c string - while(buffer[i] !== 0x00 && i < buffer.length) { - i++ - } - // If are at the end of the buffer there is a problem with the document - if(i >= buffer.length) throw new Error("Bad BSON Document: illegal CString") - // Return the C string - var regExpOptions = buffer.toString('utf8', index, i); - index = i + 1; - - // Set the object - object[name] = new BSONRegExp(source, regExpOptions); - } else if(elementType == BSON.BSON_DATA_SYMBOL) { - var stringSize = buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24; - if(stringSize <= 0 || stringSize > (buffer.length - index) || buffer[index + stringSize - 1] != 0) throw new Error("bad string length in bson"); - object[name] = new Symbol(buffer.toString('utf8', index, index + stringSize - 1)); - index = index + stringSize; - } else if(elementType == BSON.BSON_DATA_TIMESTAMP) { - var lowBits = buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24; - var highBits = buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24; - object[name] = new Timestamp(lowBits, highBits); - } else if(elementType == BSON.BSON_DATA_MIN_KEY) { - object[name] = new MinKey(); - } else if(elementType == BSON.BSON_DATA_MAX_KEY) { - object[name] = new MaxKey(); - } else if(elementType == BSON.BSON_DATA_CODE) { - var stringSize = buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24; - if(stringSize <= 0 || stringSize > (buffer.length - index) || buffer[index + stringSize - 1] != 0) throw new Error("bad string length in bson"); - var functionString = buffer.toString('utf8', index, index + stringSize - 1); - - // If we are evaluating the functions - if(evalFunctions) { - var value = null; - // If we have cache enabled let's look for the md5 of the function in the cache - if(cacheFunctions) { - var hash = cacheFunctionsCrc32 ? crc32(functionString) : functionString; - // Got to do this to avoid V8 deoptimizing the call due to finding eval - object[name] = isolateEvalWithHash(functionCache, hash, functionString, object); - } else { - object[name] = isolateEval(functionString); - } - } else { - object[name] = new Code(functionString); - } - - // Update parse index position - index = index + stringSize; - } else if(elementType == BSON.BSON_DATA_CODE_W_SCOPE) { - var totalSize = buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24; - - // Element cannot be shorter than totalSize + stringSize + documentSize + terminator - if(totalSize < (4 + 4 + 4 + 1)) { - throw new Error("code_w_scope total size shorter minimum expected length"); - } - - // Get the code string size - var stringSize = buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24; - // Check if we have a valid string - if(stringSize <= 0 || stringSize > (buffer.length - index) || buffer[index + stringSize - 1] != 0) throw new Error("bad string length in bson"); - - // Javascript function - var functionString = buffer.toString('utf8', index, index + stringSize - 1); - // Update parse index position - index = index + stringSize; - // Parse the element - var _index = index; - // Decode the size of the object document - var objectSize = buffer[index] | buffer[index + 1] << 8 | buffer[index + 2] << 16 | buffer[index + 3] << 24; - // Decode the scope object - var scopeObject = deserializeObject(buffer, _index, options, false); - // Adjust the index - index = index + objectSize; - - // Check if field length is to short - if(totalSize < (4 + 4 + objectSize + stringSize)) { - throw new Error('code_w_scope total size is to short, truncating scope'); - } - - // Check if totalSize field is to long - if(totalSize > (4 + 4 + objectSize + stringSize)) { - throw new Error('code_w_scope total size is to long, clips outer document'); - } - - // If we are evaluating the functions - if(evalFunctions) { - // Contains the value we are going to set - var value = null; - // If we have cache enabled let's look for the md5 of the function in the cache - if(cacheFunctions) { - var hash = cacheFunctionsCrc32 ? crc32(functionString) : functionString; - // Got to do this to avoid V8 deoptimizing the call due to finding eval - object[name] = isolateEvalWithHash(functionCache, hash, functionString, object); - } else { - object[name] = isolateEval(functionString); - } - - object[name].scope = scopeObject; - } else { - object[name] = new Code(functionString, scopeObject); - } - } else if(elementType == BSON.BSON_DATA_DBPOINTER) { - // Get the code string size - var stringSize = buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24; - // Check if we have a valid string - if(stringSize <= 0 || stringSize > (buffer.length - index) || buffer[index + stringSize - 1] != 0) throw new Error("bad string length in bson"); - // Namespace - var namespace = buffer.toString('utf8', index, index + stringSize - 1); - // Update parse index position - index = index + stringSize; - - // Read the oid - var oidBuffer = new Buffer(12); - buffer.copy(oidBuffer, 0, index, index + 12); - var oid = new ObjectID(oidBuffer); - - // Update the index - index = index + 12; - - // Split the namespace - var parts = namespace.split('.'); - var db = parts.shift(); - var collection = parts.join('.'); - // Upgrade to DBRef type - object[name] = new DBRef(collection, oid, db); - } else { - throw new Error("Detected unknown BSON type " + elementType.toString(16) + " for fieldname \"" + name + "\", are you using the latest BSON parser"); - } - } - - // Check if the deserialization was against a valid array/object - if(size != (index - startIndex)) { - if(isArray) throw new Error('corrupt array bson'); - throw new Error('corrupt object bson'); - } - - // Check if we have a db ref object - if(object['$id'] != null) object = new DBRef(object['$ref'], object['$id'], object['$db']); - return object; -} - -/** - * Ensure eval is isolated. - * - * @ignore - * @api private - */ -var isolateEvalWithHash = function(functionCache, hash, functionString, object) { - // Contains the value we are going to set - var value = null; - - // Check for cache hit, eval if missing and return cached function - if(functionCache[hash] == null) { - eval("value = " + functionString); - functionCache[hash] = value; - } - // Set the object - return functionCache[hash].bind(object); -} - -/** - * Ensure eval is isolated. - * - * @ignore - * @api private - */ -var isolateEval = function(functionString) { - // Contains the value we are going to set - var value = null; - // Eval the function - eval("value = " + functionString); - return value; -} - -var BSON = {}; - -/** - * Contains the function cache if we have that enable to allow for avoiding the eval step on each deserialization, comparison is by md5 - * - * @ignore - * @api private - */ -var functionCache = BSON.functionCache = {}; - -/** - * Number BSON Type - * - * @classconstant BSON_DATA_NUMBER - **/ -BSON.BSON_DATA_NUMBER = 1; -/** - * String BSON Type - * - * @classconstant BSON_DATA_STRING - **/ -BSON.BSON_DATA_STRING = 2; -/** - * Object BSON Type - * - * @classconstant BSON_DATA_OBJECT - **/ -BSON.BSON_DATA_OBJECT = 3; -/** - * Array BSON Type - * - * @classconstant BSON_DATA_ARRAY - **/ -BSON.BSON_DATA_ARRAY = 4; -/** - * Binary BSON Type - * - * @classconstant BSON_DATA_BINARY - **/ -BSON.BSON_DATA_BINARY = 5; -/** - * Binary BSON Type - * - * @classconstant BSON_DATA_UNDEFINED - **/ -BSON.BSON_DATA_UNDEFINED = 6; -/** - * ObjectID BSON Type - * - * @classconstant BSON_DATA_OID - **/ -BSON.BSON_DATA_OID = 7; -/** - * Boolean BSON Type - * - * @classconstant BSON_DATA_BOOLEAN - **/ -BSON.BSON_DATA_BOOLEAN = 8; -/** - * Date BSON Type - * - * @classconstant BSON_DATA_DATE - **/ -BSON.BSON_DATA_DATE = 9; -/** - * null BSON Type - * - * @classconstant BSON_DATA_NULL - **/ -BSON.BSON_DATA_NULL = 10; -/** - * RegExp BSON Type - * - * @classconstant BSON_DATA_REGEXP - **/ -BSON.BSON_DATA_REGEXP = 11; -/** - * Code BSON Type - * - * @classconstant BSON_DATA_DBPOINTER - **/ -BSON.BSON_DATA_DBPOINTER = 12; -/** - * Code BSON Type - * - * @classconstant BSON_DATA_CODE - **/ -BSON.BSON_DATA_CODE = 13; -/** - * Symbol BSON Type - * - * @classconstant BSON_DATA_SYMBOL - **/ -BSON.BSON_DATA_SYMBOL = 14; -/** - * Code with Scope BSON Type - * - * @classconstant BSON_DATA_CODE_W_SCOPE - **/ -BSON.BSON_DATA_CODE_W_SCOPE = 15; -/** - * 32 bit Integer BSON Type - * - * @classconstant BSON_DATA_INT - **/ -BSON.BSON_DATA_INT = 16; -/** - * Timestamp BSON Type - * - * @classconstant BSON_DATA_TIMESTAMP - **/ -BSON.BSON_DATA_TIMESTAMP = 17; -/** - * Long BSON Type - * - * @classconstant BSON_DATA_LONG - **/ -BSON.BSON_DATA_LONG = 18; -/** - * Long BSON Type - * - * @classconstant BSON_DATA_DECIMAL128 - **/ -BSON.BSON_DATA_DECIMAL128 = 19; -/** - * MinKey BSON Type - * - * @classconstant BSON_DATA_MIN_KEY - **/ -BSON.BSON_DATA_MIN_KEY = 0xff; -/** - * MaxKey BSON Type - * - * @classconstant BSON_DATA_MAX_KEY - **/ -BSON.BSON_DATA_MAX_KEY = 0x7f; - -/** - * Binary Default Type - * - * @classconstant BSON_BINARY_SUBTYPE_DEFAULT - **/ -BSON.BSON_BINARY_SUBTYPE_DEFAULT = 0; -/** - * Binary Function Type - * - * @classconstant BSON_BINARY_SUBTYPE_FUNCTION - **/ -BSON.BSON_BINARY_SUBTYPE_FUNCTION = 1; -/** - * Binary Byte Array Type - * - * @classconstant BSON_BINARY_SUBTYPE_BYTE_ARRAY - **/ -BSON.BSON_BINARY_SUBTYPE_BYTE_ARRAY = 2; -/** - * Binary UUID Type - * - * @classconstant BSON_BINARY_SUBTYPE_UUID - **/ -BSON.BSON_BINARY_SUBTYPE_UUID = 3; -/** - * Binary MD5 Type - * - * @classconstant BSON_BINARY_SUBTYPE_MD5 - **/ -BSON.BSON_BINARY_SUBTYPE_MD5 = 4; -/** - * Binary User Defined Type - * - * @classconstant BSON_BINARY_SUBTYPE_USER_DEFINED - **/ -BSON.BSON_BINARY_SUBTYPE_USER_DEFINED = 128; - -// BSON MAX VALUES -BSON.BSON_INT32_MAX = 0x7FFFFFFF; -BSON.BSON_INT32_MIN = -0x80000000; - -BSON.BSON_INT64_MAX = Math.pow(2, 63) - 1; -BSON.BSON_INT64_MIN = -Math.pow(2, 63); - -// JS MAX PRECISE VALUES -BSON.JS_INT_MAX = 0x20000000000000; // Any integer up to 2^53 can be precisely represented by a double. -BSON.JS_INT_MIN = -0x20000000000000; // Any integer down to -2^53 can be precisely represented by a double. - -// Internal long versions -var JS_INT_MAX_LONG = Long.fromNumber(0x20000000000000); // Any integer up to 2^53 can be precisely represented by a double. -var JS_INT_MIN_LONG = Long.fromNumber(-0x20000000000000); // Any integer down to -2^53 can be precisely represented by a double. - -module.exports = deserialize diff --git a/ts-ticket-office-service/node_modules/bson/lib/bson/parser/serializer.js b/ts-ticket-office-service/node_modules/bson/lib/bson/parser/serializer.js deleted file mode 100644 index 4fdb0cfba..000000000 --- a/ts-ticket-office-service/node_modules/bson/lib/bson/parser/serializer.js +++ /dev/null @@ -1,1001 +0,0 @@ -"use strict" - -var writeIEEE754 = require('../float_parser').writeIEEE754, - readIEEE754 = require('../float_parser').readIEEE754, - Long = require('../long').Long, - Map = require('../map'), - Double = require('../double').Double, - Timestamp = require('../timestamp').Timestamp, - ObjectID = require('../objectid').ObjectID, - Symbol = require('../symbol').Symbol, - Code = require('../code').Code, - BSONRegExp = require('../regexp').BSONRegExp, - Int32 = require('../int_32').Int32, - MinKey = require('../min_key').MinKey, - MaxKey = require('../max_key').MaxKey, - Decimal128 = require('../decimal128'), - DBRef = require('../db_ref').DBRef, - Binary = require('../binary').Binary; - -try { - var _Buffer = Uint8Array; -} catch(e) { - var _Buffer = Buffer; -} - -var regexp = /\x00/ - -// To ensure that 0.4 of node works correctly -var isDate = function isDate(d) { - return typeof d === 'object' && Object.prototype.toString.call(d) === '[object Date]'; -} - -var isRegExp = function isRegExp(d) { - return Object.prototype.toString.call(d) === '[object RegExp]'; -} - -var serializeString = function(buffer, key, value, index, isArray) { - // Encode String type - buffer[index++] = BSON.BSON_DATA_STRING; - // Number of written bytes - var numberOfWrittenBytes = !isArray ? buffer.write(key, index, 'utf8') : buffer.write(key, index, 'ascii'); - // Encode the name - index = index + numberOfWrittenBytes + 1; - buffer[index - 1] = 0; - // Write the string - var size = buffer.write(value, index + 4, 'utf8'); - // Write the size of the string to buffer - buffer[index + 3] = (size + 1 >> 24) & 0xff; - buffer[index + 2] = (size + 1 >> 16) & 0xff; - buffer[index + 1] = (size + 1 >> 8) & 0xff; - buffer[index] = size + 1 & 0xff; - // Update index - index = index + 4 + size; - // Write zero - buffer[index++] = 0; - return index; -} - -var serializeNumber = function(buffer, key, value, index, isArray) { - // We have an integer value - if(Math.floor(value) === value && value >= BSON.JS_INT_MIN && value <= BSON.JS_INT_MAX) { - // If the value fits in 32 bits encode as int, if it fits in a double - // encode it as a double, otherwise long - if(value >= BSON.BSON_INT32_MIN && value <= BSON.BSON_INT32_MAX) { - // Set int type 32 bits or less - buffer[index++] = BSON.BSON_DATA_INT; - // Number of written bytes - var numberOfWrittenBytes = !isArray ? buffer.write(key, index, 'utf8') : buffer.write(key, index, 'ascii'); - // Encode the name - index = index + numberOfWrittenBytes; - buffer[index++] = 0; - // Write the int value - buffer[index++] = value & 0xff; - buffer[index++] = (value >> 8) & 0xff; - buffer[index++] = (value >> 16) & 0xff; - buffer[index++] = (value >> 24) & 0xff; - } else if(value >= BSON.JS_INT_MIN && value <= BSON.JS_INT_MAX) { - // Encode as double - buffer[index++] = BSON.BSON_DATA_NUMBER; - // Number of written bytes - var numberOfWrittenBytes = !isArray ? buffer.write(key, index, 'utf8') : buffer.write(key, index, 'ascii'); - // Encode the name - index = index + numberOfWrittenBytes; - buffer[index++] = 0; - // Write float - writeIEEE754(buffer, value, index, 'little', 52, 8); - // Ajust index - index = index + 8; - } else { - // Set long type - buffer[index++] = BSON.BSON_DATA_LONG; - // Number of written bytes - var numberOfWrittenBytes = !isArray ? buffer.write(key, index, 'utf8') : buffer.write(key, index, 'ascii'); - // Encode the name - index = index + numberOfWrittenBytes; - buffer[index++] = 0; - var longVal = Long.fromNumber(value); - var lowBits = longVal.getLowBits(); - var highBits = longVal.getHighBits(); - // Encode low bits - buffer[index++] = lowBits & 0xff; - buffer[index++] = (lowBits >> 8) & 0xff; - buffer[index++] = (lowBits >> 16) & 0xff; - buffer[index++] = (lowBits >> 24) & 0xff; - // Encode high bits - buffer[index++] = highBits & 0xff; - buffer[index++] = (highBits >> 8) & 0xff; - buffer[index++] = (highBits >> 16) & 0xff; - buffer[index++] = (highBits >> 24) & 0xff; - } - } else { - // Encode as double - buffer[index++] = BSON.BSON_DATA_NUMBER; - // Number of written bytes - var numberOfWrittenBytes = !isArray ? buffer.write(key, index, 'utf8') : buffer.write(key, index, 'ascii'); - // Encode the name - index = index + numberOfWrittenBytes; - buffer[index++] = 0; - // Write float - writeIEEE754(buffer, value, index, 'little', 52, 8); - // Ajust index - index = index + 8; - } - - return index; -} - -var serializeNull = function(buffer, key, value, index, isArray) { - // Set long type - buffer[index++] = BSON.BSON_DATA_NULL; - // Number of written bytes - var numberOfWrittenBytes = !isArray ? buffer.write(key, index, 'utf8') : buffer.write(key, index, 'ascii'); - // Encode the name - index = index + numberOfWrittenBytes; - buffer[index++] = 0; - return index; -} - -var serializeBoolean = function(buffer, key, value, index, isArray) { - // Write the type - buffer[index++] = BSON.BSON_DATA_BOOLEAN; - // Number of written bytes - var numberOfWrittenBytes = !isArray ? buffer.write(key, index, 'utf8') : buffer.write(key, index, 'ascii'); - // Encode the name - index = index + numberOfWrittenBytes; - buffer[index++] = 0; - // Encode the boolean value - buffer[index++] = value ? 1 : 0; - return index; -} - -var serializeDate = function(buffer, key, value, index, isArray) { - // Write the type - buffer[index++] = BSON.BSON_DATA_DATE; - // Number of written bytes - var numberOfWrittenBytes = !isArray ? buffer.write(key, index, 'utf8') : buffer.write(key, index, 'ascii'); - // Encode the name - index = index + numberOfWrittenBytes; - buffer[index++] = 0; - - // Write the date - var dateInMilis = Long.fromNumber(value.getTime()); - var lowBits = dateInMilis.getLowBits(); - var highBits = dateInMilis.getHighBits(); - // Encode low bits - buffer[index++] = lowBits & 0xff; - buffer[index++] = (lowBits >> 8) & 0xff; - buffer[index++] = (lowBits >> 16) & 0xff; - buffer[index++] = (lowBits >> 24) & 0xff; - // Encode high bits - buffer[index++] = highBits & 0xff; - buffer[index++] = (highBits >> 8) & 0xff; - buffer[index++] = (highBits >> 16) & 0xff; - buffer[index++] = (highBits >> 24) & 0xff; - return index; -} - -var serializeRegExp = function(buffer, key, value, index, isArray) { - // Write the type - buffer[index++] = BSON.BSON_DATA_REGEXP; - // Number of written bytes - var numberOfWrittenBytes = !isArray ? buffer.write(key, index, 'utf8') : buffer.write(key, index, 'ascii'); - // Encode the name - index = index + numberOfWrittenBytes; - buffer[index++] = 0; - if (value.source && value.source.match(regexp) != null) { - throw Error("value " + value.source + " must not contain null bytes"); - } - // Adjust the index - index = index + buffer.write(value.source, index, 'utf8'); - // Write zero - buffer[index++] = 0x00; - // Write the parameters - if(value.global) buffer[index++] = 0x73; // s - if(value.ignoreCase) buffer[index++] = 0x69; // i - if(value.multiline) buffer[index++] = 0x6d; // m - // Add ending zero - buffer[index++] = 0x00; - return index; -} - -var serializeBSONRegExp = function(buffer, key, value, index, isArray) { - // Write the type - buffer[index++] = BSON.BSON_DATA_REGEXP; - // Number of written bytes - var numberOfWrittenBytes = !isArray ? buffer.write(key, index, 'utf8') : buffer.write(key, index, 'ascii'); - // Encode the name - index = index + numberOfWrittenBytes; - buffer[index++] = 0; - - // Check the pattern for 0 bytes - if (value.pattern.match(regexp) != null) { - // The BSON spec doesn't allow keys with null bytes because keys are - // null-terminated. - throw Error("pattern " + value.pattern + " must not contain null bytes"); - } - - // Adjust the index - index = index + buffer.write(value.pattern, index, 'utf8'); - // Write zero - buffer[index++] = 0x00; - // Write the options - index = index + buffer.write(value.options.split('').sort().join(''), index, 'utf8'); - // Add ending zero - buffer[index++] = 0x00; - return index; -} - -var serializeMinMax = function(buffer, key, value, index, isArray) { - // Write the type of either min or max key - if(value === null) { - buffer[index++] = BSON.BSON_DATA_NULL; - } else if(value instanceof MinKey) { - buffer[index++] = BSON.BSON_DATA_MIN_KEY; - } else { - buffer[index++] = BSON.BSON_DATA_MAX_KEY; - } - - // Number of written bytes - var numberOfWrittenBytes = !isArray ? buffer.write(key, index, 'utf8') : buffer.write(key, index, 'ascii'); - // Encode the name - index = index + numberOfWrittenBytes; - buffer[index++] = 0; - return index; -} - -var serializeObjectId = function(buffer, key, value, index, isArray) { - // Write the type - buffer[index++] = BSON.BSON_DATA_OID; - // Number of written bytes - var numberOfWrittenBytes = !isArray ? buffer.write(key, index, 'utf8') : buffer.write(key, index, 'ascii'); - - // Encode the name - index = index + numberOfWrittenBytes; - buffer[index++] = 0; - - // Write the objectId into the shared buffer - if(typeof value.id == 'string') { - buffer.write(value.id, index, 'binary') - } else if(value.id && value.id.copy){ - value.id.copy(buffer, index, 0, 12); - } else { - throw new Error('object [' + JSON.stringify(value) + "] is not a valid ObjectId"); - } - - // Ajust index - return index + 12; -} - -var serializeBuffer = function(buffer, key, value, index, isArray) { - // Write the type - buffer[index++] = BSON.BSON_DATA_BINARY; - // Number of written bytes - var numberOfWrittenBytes = !isArray ? buffer.write(key, index, 'utf8') : buffer.write(key, index, 'ascii'); - // Encode the name - index = index + numberOfWrittenBytes; - buffer[index++] = 0; - // Get size of the buffer (current write point) - var size = value.length; - // Write the size of the string to buffer - buffer[index++] = size & 0xff; - buffer[index++] = (size >> 8) & 0xff; - buffer[index++] = (size >> 16) & 0xff; - buffer[index++] = (size >> 24) & 0xff; - // Write the default subtype - buffer[index++] = BSON.BSON_BINARY_SUBTYPE_DEFAULT; - // Copy the content form the binary field to the buffer - value.copy(buffer, index, 0, size); - // Adjust the index - index = index + size; - return index; -} - -var serializeObject = function(buffer, key, value, index, checkKeys, depth, serializeFunctions, ignoreUndefined, isArray, path) { - for(var i = 0; i < path.length; i++) { - if(path[i] === value) throw new Error('cyclic dependency detected'); - } - - // Push value to stack - path.push(value); - // Write the type - buffer[index++] = Array.isArray(value) ? BSON.BSON_DATA_ARRAY : BSON.BSON_DATA_OBJECT; - // Number of written bytes - var numberOfWrittenBytes = !isArray ? buffer.write(key, index, 'utf8') : buffer.write(key, index, 'ascii'); - // Encode the name - index = index + numberOfWrittenBytes; - buffer[index++] = 0; - var endIndex = serializeInto(buffer, value, checkKeys, index, depth + 1, serializeFunctions, ignoreUndefined, path); - // Pop stack - path.pop(); - // Write size - var size = endIndex - index; - return endIndex; -} - -var serializeDecimal128 = function(buffer, key, value, index, isArray) { - buffer[index++] = BSON.BSON_DATA_DECIMAL128; - // Number of written bytes - var numberOfWrittenBytes = !isArray ? buffer.write(key, index, 'utf8') : buffer.write(key, index, 'ascii'); - // Encode the name - index = index + numberOfWrittenBytes; - buffer[index++] = 0; - // Write the data from the value - value.bytes.copy(buffer, index, 0, 16); - return index + 16; -} - -var serializeLong = function(buffer, key, value, index, isArray) { - // Write the type - buffer[index++] = value._bsontype == 'Long' ? BSON.BSON_DATA_LONG : BSON.BSON_DATA_TIMESTAMP; - // Number of written bytes - var numberOfWrittenBytes = !isArray ? buffer.write(key, index, 'utf8') : buffer.write(key, index, 'ascii'); - // Encode the name - index = index + numberOfWrittenBytes; - buffer[index++] = 0; - // Write the date - var lowBits = value.getLowBits(); - var highBits = value.getHighBits(); - // Encode low bits - buffer[index++] = lowBits & 0xff; - buffer[index++] = (lowBits >> 8) & 0xff; - buffer[index++] = (lowBits >> 16) & 0xff; - buffer[index++] = (lowBits >> 24) & 0xff; - // Encode high bits - buffer[index++] = highBits & 0xff; - buffer[index++] = (highBits >> 8) & 0xff; - buffer[index++] = (highBits >> 16) & 0xff; - buffer[index++] = (highBits >> 24) & 0xff; - return index; -} - -var serializeInt32 = function(buffer, key, value, index, isArray) { - // Set int type 32 bits or less - buffer[index++] = BSON.BSON_DATA_INT; - // Number of written bytes - var numberOfWrittenBytes = !isArray ? buffer.write(key, index, 'utf8') : buffer.write(key, index, 'ascii'); - // Encode the name - index = index + numberOfWrittenBytes; - buffer[index++] = 0; - // Write the int value - buffer[index++] = value & 0xff; - buffer[index++] = (value >> 8) & 0xff; - buffer[index++] = (value >> 16) & 0xff; - buffer[index++] = (value >> 24) & 0xff; - return index; -} - -var serializeDouble = function(buffer, key, value, index, isArray) { - // Encode as double - buffer[index++] = BSON.BSON_DATA_NUMBER; - // Number of written bytes - var numberOfWrittenBytes = !isArray ? buffer.write(key, index, 'utf8') : buffer.write(key, index, 'ascii'); - // Encode the name - index = index + numberOfWrittenBytes; - buffer[index++] = 0; - // Write float - writeIEEE754(buffer, value, index, 'little', 52, 8); - // Ajust index - index = index + 8; - return index; -} - -var serializeFunction = function(buffer, key, value, index, checkKeys, depth, isArray) { - buffer[index++] = BSON.BSON_DATA_CODE; - // Number of written bytes - var numberOfWrittenBytes = !isArray ? buffer.write(key, index, 'utf8') : buffer.write(key, index, 'ascii'); - // Encode the name - index = index + numberOfWrittenBytes; - buffer[index++] = 0; - // Function string - var functionString = value.toString(); - // Write the string - var size = buffer.write(functionString, index + 4, 'utf8') + 1; - // Write the size of the string to buffer - buffer[index] = size & 0xff; - buffer[index + 1] = (size >> 8) & 0xff; - buffer[index + 2] = (size >> 16) & 0xff; - buffer[index + 3] = (size >> 24) & 0xff; - // Update index - index = index + 4 + size - 1; - // Write zero - buffer[index++] = 0; - return index; -} - -var serializeCode = function(buffer, key, value, index, checkKeys, depth, serializeFunctions, ignoreUndefined, isArray) { - if(value.scope && typeof value.scope == 'object') { - // Write the type - buffer[index++] = BSON.BSON_DATA_CODE_W_SCOPE; - // Number of written bytes - var numberOfWrittenBytes = !isArray ? buffer.write(key, index, 'utf8') : buffer.write(key, index, 'ascii'); - // Encode the name - index = index + numberOfWrittenBytes; - buffer[index++] = 0; - - // Starting index - var startIndex = index; - - // Serialize the function - // Get the function string - var functionString = typeof value.code == 'string' ? value.code : value.code.toString(); - // Index adjustment - index = index + 4; - // Write string into buffer - var codeSize = buffer.write(functionString, index + 4, 'utf8') + 1; - // Write the size of the string to buffer - buffer[index] = codeSize & 0xff; - buffer[index + 1] = (codeSize >> 8) & 0xff; - buffer[index + 2] = (codeSize >> 16) & 0xff; - buffer[index + 3] = (codeSize >> 24) & 0xff; - // Write end 0 - buffer[index + 4 + codeSize - 1] = 0; - // Write the - index = index + codeSize + 4; - - // - // Serialize the scope value - var endIndex = serializeInto(buffer, value.scope, checkKeys, index, depth + 1, serializeFunctions, ignoreUndefined) - index = endIndex - 1; - - // Writ the total - var totalSize = endIndex - startIndex; - - // Write the total size of the object - buffer[startIndex++] = totalSize & 0xff; - buffer[startIndex++] = (totalSize >> 8) & 0xff; - buffer[startIndex++] = (totalSize >> 16) & 0xff; - buffer[startIndex++] = (totalSize >> 24) & 0xff; - // Write trailing zero - buffer[index++] = 0; - } else { - buffer[index++] = BSON.BSON_DATA_CODE; - // Number of written bytes - var numberOfWrittenBytes = !isArray ? buffer.write(key, index, 'utf8') : buffer.write(key, index, 'ascii'); - // Encode the name - index = index + numberOfWrittenBytes; - buffer[index++] = 0; - // Function string - var functionString = value.code.toString(); - // Write the string - var size = buffer.write(functionString, index + 4, 'utf8') + 1; - // Write the size of the string to buffer - buffer[index] = size & 0xff; - buffer[index + 1] = (size >> 8) & 0xff; - buffer[index + 2] = (size >> 16) & 0xff; - buffer[index + 3] = (size >> 24) & 0xff; - // Update index - index = index + 4 + size - 1; - // Write zero - buffer[index++] = 0; - } - - return index; -} - -var serializeBinary = function(buffer, key, value, index, isArray) { - // Write the type - buffer[index++] = BSON.BSON_DATA_BINARY; - // Number of written bytes - var numberOfWrittenBytes = !isArray ? buffer.write(key, index, 'utf8') : buffer.write(key, index, 'ascii'); - // Encode the name - index = index + numberOfWrittenBytes; - buffer[index++] = 0; - // Extract the buffer - var data = value.value(true); - // Calculate size - var size = value.position; - // Add the deprecated 02 type 4 bytes of size to total - if(value.sub_type == Binary.SUBTYPE_BYTE_ARRAY) size = size + 4; - // Write the size of the string to buffer - buffer[index++] = size & 0xff; - buffer[index++] = (size >> 8) & 0xff; - buffer[index++] = (size >> 16) & 0xff; - buffer[index++] = (size >> 24) & 0xff; - // Write the subtype to the buffer - buffer[index++] = value.sub_type; - - // If we have binary type 2 the 4 first bytes are the size - if(value.sub_type == Binary.SUBTYPE_BYTE_ARRAY) { - size = size - 4; - buffer[index++] = size & 0xff; - buffer[index++] = (size >> 8) & 0xff; - buffer[index++] = (size >> 16) & 0xff; - buffer[index++] = (size >> 24) & 0xff; - } - - // Write the data to the object - data.copy(buffer, index, 0, value.position); - // Adjust the index - index = index + value.position; - return index; -} - -var serializeSymbol = function(buffer, key, value, index, isArray) { - // Write the type - buffer[index++] = BSON.BSON_DATA_SYMBOL; - // Number of written bytes - var numberOfWrittenBytes = !isArray ? buffer.write(key, index, 'utf8') : buffer.write(key, index, 'ascii'); - // Encode the name - index = index + numberOfWrittenBytes; - buffer[index++] = 0; - // Write the string - var size = buffer.write(value.value, index + 4, 'utf8') + 1; - // Write the size of the string to buffer - buffer[index] = size & 0xff; - buffer[index + 1] = (size >> 8) & 0xff; - buffer[index + 2] = (size >> 16) & 0xff; - buffer[index + 3] = (size >> 24) & 0xff; - // Update index - index = index + 4 + size - 1; - // Write zero - buffer[index++] = 0x00; - return index; -} - -var serializeDBRef = function(buffer, key, value, index, depth, serializeFunctions, isArray) { - // Write the type - buffer[index++] = BSON.BSON_DATA_OBJECT; - // Number of written bytes - var numberOfWrittenBytes = !isArray ? buffer.write(key, index, 'utf8') : buffer.write(key, index, 'ascii'); - - // Encode the name - index = index + numberOfWrittenBytes; - buffer[index++] = 0; - - var startIndex = index; - var endIndex; - - // Serialize object - if(null != value.db) { - endIndex = serializeInto(buffer, { - '$ref': value.namespace - , '$id' : value.oid - , '$db' : value.db - }, false, index, depth + 1, serializeFunctions); - } else { - endIndex = serializeInto(buffer, { - '$ref': value.namespace - , '$id' : value.oid - }, false, index, depth + 1, serializeFunctions); - } - - // Calculate object size - var size = endIndex - startIndex; - // Write the size - buffer[startIndex++] = size & 0xff; - buffer[startIndex++] = (size >> 8) & 0xff; - buffer[startIndex++] = (size >> 16) & 0xff; - buffer[startIndex++] = (size >> 24) & 0xff; - // Set index - return endIndex; -} - -var serializeInto = function serializeInto(buffer, object, checkKeys, startingIndex, depth, serializeFunctions, ignoreUndefined, path) { - startingIndex = startingIndex || 0; - path = path || []; - - // Push the object to the path - path.push(object); - - // Start place to serialize into - var index = startingIndex + 4; - var self = this; - - // Special case isArray - if(Array.isArray(object)) { - // Get object keys - for(var i = 0; i < object.length; i++) { - var key = "" + i; - var value = object[i]; - - // Is there an override value - if(value && value.toBSON) { - if(typeof value.toBSON != 'function') throw new Error("toBSON is not a function"); - value = value.toBSON(); - } - - var type = typeof value; - if(type == 'string') { - index = serializeString(buffer, key, value, index, true); - } else if(type == 'number') { - index = serializeNumber(buffer, key, value, index, true); - } else if(type == 'boolean') { - index = serializeBoolean(buffer, key, value, index, true); - } else if(value instanceof Date || isDate(value)) { - index = serializeDate(buffer, key, value, index, true); - } else if(value === undefined) { - index = serializeNull(buffer, key, value, index, true); - } else if(value === null) { - index = serializeNull(buffer, key, value, index, true); - } else if(value['_bsontype'] == 'ObjectID') { - index = serializeObjectId(buffer, key, value, index, true); - } else if(Buffer.isBuffer(value)) { - index = serializeBuffer(buffer, key, value, index, true); - } else if(value instanceof RegExp || isRegExp(value)) { - index = serializeRegExp(buffer, key, value, index, true); - } else if(type == 'object' && value['_bsontype'] == null) { - index = serializeObject(buffer, key, value, index, checkKeys, depth, serializeFunctions, ignoreUndefined, true, path); - } else if(type == 'object' && value['_bsontype'] == 'Decimal128') { - index = serializeDecimal128(buffer, key, value, index, true); - } else if(value['_bsontype'] == 'Long' || value['_bsontype'] == 'Timestamp') { - index = serializeLong(buffer, key, value, index, true); - } else if(value['_bsontype'] == 'Double') { - index = serializeDouble(buffer, key, value, index, true); - } else if(typeof value == 'function' && serializeFunctions) { - index = serializeFunction(buffer, key, value, index, checkKeys, depth, serializeFunctions, true); - } else if(value['_bsontype'] == 'Code') { - index = serializeCode(buffer, key, value, index, checkKeys, depth, serializeFunctions, ignoreUndefined, true); - } else if(value['_bsontype'] == 'Binary') { - index = serializeBinary(buffer, key, value, index, true); - } else if(value['_bsontype'] == 'Symbol') { - index = serializeSymbol(buffer, key, value, index, true); - } else if(value['_bsontype'] == 'DBRef') { - index = serializeDBRef(buffer, key, value, index, depth, serializeFunctions, true); - } else if(value['_bsontype'] == 'BSONRegExp') { - index = serializeBSONRegExp(buffer, key, value, index, true); - } else if(value['_bsontype'] == 'Int32') { - index = serializeInt32(buffer, key, value, index, true); - } else if(value['_bsontype'] == 'MinKey' || value['_bsontype'] == 'MaxKey') { - index = serializeMinMax(buffer, key, value, index, true); - } - } - } else if(object instanceof Map) { - var iterator = object.entries(); - var done = false; - - while(!done) { - // Unpack the next entry - var entry = iterator.next(); - done = entry.done; - // Are we done, then skip and terminate - if(done) continue; - - // Get the entry values - var key = entry.value[0]; - var value = entry.value[1]; - - // Check the type of the value - var type = typeof value; - - // Check the key and throw error if it's illegal - if(key != '$db' && key != '$ref' && key != '$id') { - if (key.match(regexp) != null) { - // The BSON spec doesn't allow keys with null bytes because keys are - // null-terminated. - throw Error("key " + key + " must not contain null bytes"); - } - - if (checkKeys) { - if('$' == key[0]) { - throw Error("key " + key + " must not start with '$'"); - } else if (!!~key.indexOf('.')) { - throw Error("key " + key + " must not contain '.'"); - } - } - } - - if(type == 'string') { - index = serializeString(buffer, key, value, index); - } else if(type == 'number') { - index = serializeNumber(buffer, key, value, index); - } else if(type == 'boolean') { - index = serializeBoolean(buffer, key, value, index); - } else if(value instanceof Date || isDate(value)) { - index = serializeDate(buffer, key, value, index); - } else if(value === undefined && ignoreUndefined == true) { - } else if(value === null || value === undefined) { - index = serializeNull(buffer, key, value, index); - } else if(value['_bsontype'] == 'ObjectID') { - index = serializeObjectId(buffer, key, value, index); - } else if(Buffer.isBuffer(value)) { - index = serializeBuffer(buffer, key, value, index); - } else if(value instanceof RegExp || isRegExp(value)) { - index = serializeRegExp(buffer, key, value, index); - } else if(type == 'object' && value['_bsontype'] == null) { - index = serializeObject(buffer, key, value, index, checkKeys, depth, serializeFunctions, ignoreUndefined, false, path); - } else if(type == 'object' && value['_bsontype'] == 'Decimal128') { - index = serializeDecimal128(buffer, key, value, index); - } else if(value['_bsontype'] == 'Long' || value['_bsontype'] == 'Timestamp') { - index = serializeLong(buffer, key, value, index); - } else if(value['_bsontype'] == 'Double') { - index = serializeDouble(buffer, key, value, index); - } else if(value['_bsontype'] == 'Code') { - index = serializeCode(buffer, key, value, index, checkKeys, depth, serializeFunctions, ignoreUndefined); - } else if(typeof value == 'function' && serializeFunctions) { - index = serializeFunction(buffer, key, value, index, checkKeys, depth, serializeFunctions); - } else if(value['_bsontype'] == 'Binary') { - index = serializeBinary(buffer, key, value, index); - } else if(value['_bsontype'] == 'Symbol') { - index = serializeSymbol(buffer, key, value, index); - } else if(value['_bsontype'] == 'DBRef') { - index = serializeDBRef(buffer, key, value, index, depth, serializeFunctions); - } else if(value['_bsontype'] == 'BSONRegExp') { - index = serializeBSONRegExp(buffer, key, value, index); - } else if(value['_bsontype'] == 'Int32') { - index = serializeInt32(buffer, key, value, index); - } else if(value['_bsontype'] == 'MinKey' || value['_bsontype'] == 'MaxKey') { - index = serializeMinMax(buffer, key, value, index); - } - } - } else { - // Did we provide a custom serialization method - if(object.toBSON) { - if(typeof object.toBSON != 'function') throw new Error("toBSON is not a function"); - object = object.toBSON(); - if(object != null && typeof object != 'object') throw new Error("toBSON function did not return an object"); - } - - // Iterate over all the keys - for(var key in object) { - var value = object[key]; - // Is there an override value - if(value && value.toBSON) { - if(typeof value.toBSON != 'function') throw new Error("toBSON is not a function"); - value = value.toBSON(); - } - - // Check the type of the value - var type = typeof value; - - // Check the key and throw error if it's illegal - if(key != '$db' && key != '$ref' && key != '$id') { - if (key.match(regexp) != null) { - // The BSON spec doesn't allow keys with null bytes because keys are - // null-terminated. - throw Error("key " + key + " must not contain null bytes"); - } - - if (checkKeys) { - if('$' == key[0]) { - throw Error("key " + key + " must not start with '$'"); - } else if (!!~key.indexOf('.')) { - throw Error("key " + key + " must not contain '.'"); - } - } - } - - if(type == 'string') { - index = serializeString(buffer, key, value, index); - } else if(type == 'number') { - index = serializeNumber(buffer, key, value, index); - } else if(type == 'boolean') { - index = serializeBoolean(buffer, key, value, index); - } else if(value instanceof Date || isDate(value)) { - index = serializeDate(buffer, key, value, index); - } else if(value === undefined && ignoreUndefined == true) { - } else if(value === null || value === undefined) { - index = serializeNull(buffer, key, value, index); - } else if(value['_bsontype'] == 'ObjectID') { - index = serializeObjectId(buffer, key, value, index); - } else if(Buffer.isBuffer(value)) { - index = serializeBuffer(buffer, key, value, index); - } else if(value instanceof RegExp || isRegExp(value)) { - index = serializeRegExp(buffer, key, value, index); - } else if(type == 'object' && value['_bsontype'] == null) { - index = serializeObject(buffer, key, value, index, checkKeys, depth, serializeFunctions, ignoreUndefined, false, path); - } else if(type == 'object' && value['_bsontype'] == 'Decimal128') { - index = serializeDecimal128(buffer, key, value, index); - } else if(value['_bsontype'] == 'Long' || value['_bsontype'] == 'Timestamp') { - index = serializeLong(buffer, key, value, index); - } else if(value['_bsontype'] == 'Double') { - index = serializeDouble(buffer, key, value, index); - } else if(value['_bsontype'] == 'Code') { - index = serializeCode(buffer, key, value, index, checkKeys, depth, serializeFunctions, ignoreUndefined); - } else if(typeof value == 'function' && serializeFunctions) { - index = serializeFunction(buffer, key, value, index, checkKeys, depth, serializeFunctions); - } else if(value['_bsontype'] == 'Binary') { - index = serializeBinary(buffer, key, value, index); - } else if(value['_bsontype'] == 'Symbol') { - index = serializeSymbol(buffer, key, value, index); - } else if(value['_bsontype'] == 'DBRef') { - index = serializeDBRef(buffer, key, value, index, depth, serializeFunctions); - } else if(value['_bsontype'] == 'BSONRegExp') { - index = serializeBSONRegExp(buffer, key, value, index); - } else if(value['_bsontype'] == 'Int32') { - index = serializeInt32(buffer, key, value, index); - } else if(value['_bsontype'] == 'MinKey' || value['_bsontype'] == 'MaxKey') { - index = serializeMinMax(buffer, key, value, index); - } - } - } - - // Remove the path - path.pop(); - - // Final padding byte for object - buffer[index++] = 0x00; - - // Final size - var size = index - startingIndex; - // Write the size of the object - buffer[startingIndex++] = size & 0xff; - buffer[startingIndex++] = (size >> 8) & 0xff; - buffer[startingIndex++] = (size >> 16) & 0xff; - buffer[startingIndex++] = (size >> 24) & 0xff; - return index; -} - -var BSON = {}; - -/** - * Contains the function cache if we have that enable to allow for avoiding the eval step on each deserialization, comparison is by md5 - * - * @ignore - * @api private - */ -var functionCache = BSON.functionCache = {}; - -/** - * Number BSON Type - * - * @classconstant BSON_DATA_NUMBER - **/ -BSON.BSON_DATA_NUMBER = 1; -/** - * String BSON Type - * - * @classconstant BSON_DATA_STRING - **/ -BSON.BSON_DATA_STRING = 2; -/** - * Object BSON Type - * - * @classconstant BSON_DATA_OBJECT - **/ -BSON.BSON_DATA_OBJECT = 3; -/** - * Array BSON Type - * - * @classconstant BSON_DATA_ARRAY - **/ -BSON.BSON_DATA_ARRAY = 4; -/** - * Binary BSON Type - * - * @classconstant BSON_DATA_BINARY - **/ -BSON.BSON_DATA_BINARY = 5; -/** - * ObjectID BSON Type, deprecated - * - * @classconstant BSON_DATA_UNDEFINED - **/ -BSON.BSON_DATA_UNDEFINED = 6; -/** - * ObjectID BSON Type - * - * @classconstant BSON_DATA_OID - **/ -BSON.BSON_DATA_OID = 7; -/** - * Boolean BSON Type - * - * @classconstant BSON_DATA_BOOLEAN - **/ -BSON.BSON_DATA_BOOLEAN = 8; -/** - * Date BSON Type - * - * @classconstant BSON_DATA_DATE - **/ -BSON.BSON_DATA_DATE = 9; -/** - * null BSON Type - * - * @classconstant BSON_DATA_NULL - **/ -BSON.BSON_DATA_NULL = 10; -/** - * RegExp BSON Type - * - * @classconstant BSON_DATA_REGEXP - **/ -BSON.BSON_DATA_REGEXP = 11; -/** - * Code BSON Type - * - * @classconstant BSON_DATA_CODE - **/ -BSON.BSON_DATA_CODE = 13; -/** - * Symbol BSON Type - * - * @classconstant BSON_DATA_SYMBOL - **/ -BSON.BSON_DATA_SYMBOL = 14; -/** - * Code with Scope BSON Type - * - * @classconstant BSON_DATA_CODE_W_SCOPE - **/ -BSON.BSON_DATA_CODE_W_SCOPE = 15; -/** - * 32 bit Integer BSON Type - * - * @classconstant BSON_DATA_INT - **/ -BSON.BSON_DATA_INT = 16; -/** - * Timestamp BSON Type - * - * @classconstant BSON_DATA_TIMESTAMP - **/ -BSON.BSON_DATA_TIMESTAMP = 17; -/** - * Long BSON Type - * - * @classconstant BSON_DATA_LONG - **/ -BSON.BSON_DATA_LONG = 18; -/** - * Long BSON Type - * - * @classconstant BSON_DATA_DECIMAL128 - **/ -BSON.BSON_DATA_DECIMAL128 = 19; -/** - * MinKey BSON Type - * - * @classconstant BSON_DATA_MIN_KEY - **/ -BSON.BSON_DATA_MIN_KEY = 0xff; -/** - * MaxKey BSON Type - * - * @classconstant BSON_DATA_MAX_KEY - **/ -BSON.BSON_DATA_MAX_KEY = 0x7f; -/** - * Binary Default Type - * - * @classconstant BSON_BINARY_SUBTYPE_DEFAULT - **/ -BSON.BSON_BINARY_SUBTYPE_DEFAULT = 0; -/** - * Binary Function Type - * - * @classconstant BSON_BINARY_SUBTYPE_FUNCTION - **/ -BSON.BSON_BINARY_SUBTYPE_FUNCTION = 1; -/** - * Binary Byte Array Type - * - * @classconstant BSON_BINARY_SUBTYPE_BYTE_ARRAY - **/ -BSON.BSON_BINARY_SUBTYPE_BYTE_ARRAY = 2; -/** - * Binary UUID Type - * - * @classconstant BSON_BINARY_SUBTYPE_UUID - **/ -BSON.BSON_BINARY_SUBTYPE_UUID = 3; -/** - * Binary MD5 Type - * - * @classconstant BSON_BINARY_SUBTYPE_MD5 - **/ -BSON.BSON_BINARY_SUBTYPE_MD5 = 4; -/** - * Binary User Defined Type - * - * @classconstant BSON_BINARY_SUBTYPE_USER_DEFINED - **/ -BSON.BSON_BINARY_SUBTYPE_USER_DEFINED = 128; - -// BSON MAX VALUES -BSON.BSON_INT32_MAX = 0x7FFFFFFF; -BSON.BSON_INT32_MIN = -0x80000000; - -BSON.BSON_INT64_MAX = Math.pow(2, 63) - 1; -BSON.BSON_INT64_MIN = -Math.pow(2, 63); - -// JS MAX PRECISE VALUES -BSON.JS_INT_MAX = 0x20000000000000; // Any integer up to 2^53 can be precisely represented by a double. -BSON.JS_INT_MIN = -0x20000000000000; // Any integer down to -2^53 can be precisely represented by a double. - -// Internal long versions -var JS_INT_MAX_LONG = Long.fromNumber(0x20000000000000); // Any integer up to 2^53 can be precisely represented by a double. -var JS_INT_MIN_LONG = Long.fromNumber(-0x20000000000000); // Any integer down to -2^53 can be precisely represented by a double. - -module.exports = serializeInto; diff --git a/ts-ticket-office-service/node_modules/bson/lib/bson/regexp.js b/ts-ticket-office-service/node_modules/bson/lib/bson/regexp.js deleted file mode 100644 index 9dd006624..000000000 --- a/ts-ticket-office-service/node_modules/bson/lib/bson/regexp.js +++ /dev/null @@ -1,30 +0,0 @@ -/** - * A class representation of the BSON RegExp type. - * - * @class - * @return {BSONRegExp} A MinKey instance - */ -function BSONRegExp(pattern, options) { - if(!(this instanceof BSONRegExp)) return new BSONRegExp(); - - // Execute - this._bsontype = 'BSONRegExp'; - this.pattern = pattern || ''; - this.options = options || ''; - - // Validate options - for(var i = 0; i < this.options.length; i++) { - if(!(this.options[i] == 'i' - || this.options[i] == 'm' - || this.options[i] == 'x' - || this.options[i] == 'l' - || this.options[i] == 's' - || this.options[i] == 'u' - )) { - throw new Error('the regular expression options [' + this.options[i] + "] is not supported"); - } - } -} - -module.exports = BSONRegExp; -module.exports.BSONRegExp = BSONRegExp; diff --git a/ts-ticket-office-service/node_modules/bson/lib/bson/symbol.js b/ts-ticket-office-service/node_modules/bson/lib/bson/symbol.js deleted file mode 100644 index 7681a4de6..000000000 --- a/ts-ticket-office-service/node_modules/bson/lib/bson/symbol.js +++ /dev/null @@ -1,47 +0,0 @@ -/** - * A class representation of the BSON Symbol type. - * - * @class - * @deprecated - * @param {string} value the string representing the symbol. - * @return {Symbol} - */ -function Symbol(value) { - if(!(this instanceof Symbol)) return new Symbol(value); - this._bsontype = 'Symbol'; - this.value = value; -} - -/** - * Access the wrapped string value. - * - * @method - * @return {String} returns the wrapped string. - */ -Symbol.prototype.valueOf = function() { - return this.value; -}; - -/** - * @ignore - */ -Symbol.prototype.toString = function() { - return this.value; -} - -/** - * @ignore - */ -Symbol.prototype.inspect = function() { - return this.value; -} - -/** - * @ignore - */ -Symbol.prototype.toJSON = function() { - return this.value; -} - -module.exports = Symbol; -module.exports.Symbol = Symbol; \ No newline at end of file diff --git a/ts-ticket-office-service/node_modules/bson/lib/bson/timestamp.js b/ts-ticket-office-service/node_modules/bson/lib/bson/timestamp.js deleted file mode 100644 index 7718cafc4..000000000 --- a/ts-ticket-office-service/node_modules/bson/lib/bson/timestamp.js +++ /dev/null @@ -1,856 +0,0 @@ -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// -// Copyright 2009 Google Inc. All Rights Reserved - -/** - * This type is for INTERNAL use in MongoDB only and should not be used in applications. - * The appropriate corresponding type is the JavaScript Date type. - * - * Defines a Timestamp class for representing a 64-bit two's-complement - * integer value, which faithfully simulates the behavior of a Java "Timestamp". This - * implementation is derived from TimestampLib in GWT. - * - * Constructs a 64-bit two's-complement integer, given its low and high 32-bit - * values as *signed* integers. See the from* functions below for more - * convenient ways of constructing Timestamps. - * - * The internal representation of a Timestamp is the two given signed, 32-bit values. - * We use 32-bit pieces because these are the size of integers on which - * Javascript performs bit-operations. For operations like addition and - * multiplication, we split each number into 16-bit pieces, which can easily be - * multiplied within Javascript's floating-point representation without overflow - * or change in sign. - * - * In the algorithms below, we frequently reduce the negative case to the - * positive case by negating the input(s) and then post-processing the result. - * Note that we must ALWAYS check specially whether those values are MIN_VALUE - * (-2^63) because -MIN_VALUE == MIN_VALUE (since 2^63 cannot be represented as - * a positive number, it overflows back into a negative). Not handling this - * case would often result in infinite recursion. - * - * @class - * @param {number} low the low (signed) 32 bits of the Timestamp. - * @param {number} high the high (signed) 32 bits of the Timestamp. - */ -function Timestamp(low, high) { - if(!(this instanceof Timestamp)) return new Timestamp(low, high); - this._bsontype = 'Timestamp'; - /** - * @type {number} - * @ignore - */ - this.low_ = low | 0; // force into 32 signed bits. - - /** - * @type {number} - * @ignore - */ - this.high_ = high | 0; // force into 32 signed bits. -}; - -/** - * Return the int value. - * - * @return {number} the value, assuming it is a 32-bit integer. - */ -Timestamp.prototype.toInt = function() { - return this.low_; -}; - -/** - * Return the Number value. - * - * @method - * @return {number} the closest floating-point representation to this value. - */ -Timestamp.prototype.toNumber = function() { - return this.high_ * Timestamp.TWO_PWR_32_DBL_ + - this.getLowBitsUnsigned(); -}; - -/** - * Return the JSON value. - * - * @method - * @return {string} the JSON representation. - */ -Timestamp.prototype.toJSON = function() { - return this.toString(); -} - -/** - * Return the String value. - * - * @method - * @param {number} [opt_radix] the radix in which the text should be written. - * @return {string} the textual representation of this value. - */ -Timestamp.prototype.toString = function(opt_radix) { - var radix = opt_radix || 10; - if (radix < 2 || 36 < radix) { - throw Error('radix out of range: ' + radix); - } - - if (this.isZero()) { - return '0'; - } - - if (this.isNegative()) { - if (this.equals(Timestamp.MIN_VALUE)) { - // We need to change the Timestamp value before it can be negated, so we remove - // the bottom-most digit in this base and then recurse to do the rest. - var radixTimestamp = Timestamp.fromNumber(radix); - var div = this.div(radixTimestamp); - var rem = div.multiply(radixTimestamp).subtract(this); - return div.toString(radix) + rem.toInt().toString(radix); - } else { - return '-' + this.negate().toString(radix); - } - } - - // Do several (6) digits each time through the loop, so as to - // minimize the calls to the very expensive emulated div. - var radixToPower = Timestamp.fromNumber(Math.pow(radix, 6)); - - var rem = this; - var result = ''; - while (true) { - var remDiv = rem.div(radixToPower); - var intval = rem.subtract(remDiv.multiply(radixToPower)).toInt(); - var digits = intval.toString(radix); - - rem = remDiv; - if (rem.isZero()) { - return digits + result; - } else { - while (digits.length < 6) { - digits = '0' + digits; - } - result = '' + digits + result; - } - } -}; - -/** - * Return the high 32-bits value. - * - * @method - * @return {number} the high 32-bits as a signed value. - */ -Timestamp.prototype.getHighBits = function() { - return this.high_; -}; - -/** - * Return the low 32-bits value. - * - * @method - * @return {number} the low 32-bits as a signed value. - */ -Timestamp.prototype.getLowBits = function() { - return this.low_; -}; - -/** - * Return the low unsigned 32-bits value. - * - * @method - * @return {number} the low 32-bits as an unsigned value. - */ -Timestamp.prototype.getLowBitsUnsigned = function() { - return (this.low_ >= 0) ? - this.low_ : Timestamp.TWO_PWR_32_DBL_ + this.low_; -}; - -/** - * Returns the number of bits needed to represent the absolute value of this Timestamp. - * - * @method - * @return {number} Returns the number of bits needed to represent the absolute value of this Timestamp. - */ -Timestamp.prototype.getNumBitsAbs = function() { - if (this.isNegative()) { - if (this.equals(Timestamp.MIN_VALUE)) { - return 64; - } else { - return this.negate().getNumBitsAbs(); - } - } else { - var val = this.high_ != 0 ? this.high_ : this.low_; - for (var bit = 31; bit > 0; bit--) { - if ((val & (1 << bit)) != 0) { - break; - } - } - return this.high_ != 0 ? bit + 33 : bit + 1; - } -}; - -/** - * Return whether this value is zero. - * - * @method - * @return {boolean} whether this value is zero. - */ -Timestamp.prototype.isZero = function() { - return this.high_ == 0 && this.low_ == 0; -}; - -/** - * Return whether this value is negative. - * - * @method - * @return {boolean} whether this value is negative. - */ -Timestamp.prototype.isNegative = function() { - return this.high_ < 0; -}; - -/** - * Return whether this value is odd. - * - * @method - * @return {boolean} whether this value is odd. - */ -Timestamp.prototype.isOdd = function() { - return (this.low_ & 1) == 1; -}; - -/** - * Return whether this Timestamp equals the other - * - * @method - * @param {Timestamp} other Timestamp to compare against. - * @return {boolean} whether this Timestamp equals the other - */ -Timestamp.prototype.equals = function(other) { - return (this.high_ == other.high_) && (this.low_ == other.low_); -}; - -/** - * Return whether this Timestamp does not equal the other. - * - * @method - * @param {Timestamp} other Timestamp to compare against. - * @return {boolean} whether this Timestamp does not equal the other. - */ -Timestamp.prototype.notEquals = function(other) { - return (this.high_ != other.high_) || (this.low_ != other.low_); -}; - -/** - * Return whether this Timestamp is less than the other. - * - * @method - * @param {Timestamp} other Timestamp to compare against. - * @return {boolean} whether this Timestamp is less than the other. - */ -Timestamp.prototype.lessThan = function(other) { - return this.compare(other) < 0; -}; - -/** - * Return whether this Timestamp is less than or equal to the other. - * - * @method - * @param {Timestamp} other Timestamp to compare against. - * @return {boolean} whether this Timestamp is less than or equal to the other. - */ -Timestamp.prototype.lessThanOrEqual = function(other) { - return this.compare(other) <= 0; -}; - -/** - * Return whether this Timestamp is greater than the other. - * - * @method - * @param {Timestamp} other Timestamp to compare against. - * @return {boolean} whether this Timestamp is greater than the other. - */ -Timestamp.prototype.greaterThan = function(other) { - return this.compare(other) > 0; -}; - -/** - * Return whether this Timestamp is greater than or equal to the other. - * - * @method - * @param {Timestamp} other Timestamp to compare against. - * @return {boolean} whether this Timestamp is greater than or equal to the other. - */ -Timestamp.prototype.greaterThanOrEqual = function(other) { - return this.compare(other) >= 0; -}; - -/** - * Compares this Timestamp with the given one. - * - * @method - * @param {Timestamp} other Timestamp to compare against. - * @return {boolean} 0 if they are the same, 1 if the this is greater, and -1 if the given one is greater. - */ -Timestamp.prototype.compare = function(other) { - if (this.equals(other)) { - return 0; - } - - var thisNeg = this.isNegative(); - var otherNeg = other.isNegative(); - if (thisNeg && !otherNeg) { - return -1; - } - if (!thisNeg && otherNeg) { - return 1; - } - - // at this point, the signs are the same, so subtraction will not overflow - if (this.subtract(other).isNegative()) { - return -1; - } else { - return 1; - } -}; - -/** - * The negation of this value. - * - * @method - * @return {Timestamp} the negation of this value. - */ -Timestamp.prototype.negate = function() { - if (this.equals(Timestamp.MIN_VALUE)) { - return Timestamp.MIN_VALUE; - } else { - return this.not().add(Timestamp.ONE); - } -}; - -/** - * Returns the sum of this and the given Timestamp. - * - * @method - * @param {Timestamp} other Timestamp to add to this one. - * @return {Timestamp} the sum of this and the given Timestamp. - */ -Timestamp.prototype.add = function(other) { - // Divide each number into 4 chunks of 16 bits, and then sum the chunks. - - var a48 = this.high_ >>> 16; - var a32 = this.high_ & 0xFFFF; - var a16 = this.low_ >>> 16; - var a00 = this.low_ & 0xFFFF; - - var b48 = other.high_ >>> 16; - var b32 = other.high_ & 0xFFFF; - var b16 = other.low_ >>> 16; - var b00 = other.low_ & 0xFFFF; - - var c48 = 0, c32 = 0, c16 = 0, c00 = 0; - c00 += a00 + b00; - c16 += c00 >>> 16; - c00 &= 0xFFFF; - c16 += a16 + b16; - c32 += c16 >>> 16; - c16 &= 0xFFFF; - c32 += a32 + b32; - c48 += c32 >>> 16; - c32 &= 0xFFFF; - c48 += a48 + b48; - c48 &= 0xFFFF; - return Timestamp.fromBits((c16 << 16) | c00, (c48 << 16) | c32); -}; - -/** - * Returns the difference of this and the given Timestamp. - * - * @method - * @param {Timestamp} other Timestamp to subtract from this. - * @return {Timestamp} the difference of this and the given Timestamp. - */ -Timestamp.prototype.subtract = function(other) { - return this.add(other.negate()); -}; - -/** - * Returns the product of this and the given Timestamp. - * - * @method - * @param {Timestamp} other Timestamp to multiply with this. - * @return {Timestamp} the product of this and the other. - */ -Timestamp.prototype.multiply = function(other) { - if (this.isZero()) { - return Timestamp.ZERO; - } else if (other.isZero()) { - return Timestamp.ZERO; - } - - if (this.equals(Timestamp.MIN_VALUE)) { - return other.isOdd() ? Timestamp.MIN_VALUE : Timestamp.ZERO; - } else if (other.equals(Timestamp.MIN_VALUE)) { - return this.isOdd() ? Timestamp.MIN_VALUE : Timestamp.ZERO; - } - - if (this.isNegative()) { - if (other.isNegative()) { - return this.negate().multiply(other.negate()); - } else { - return this.negate().multiply(other).negate(); - } - } else if (other.isNegative()) { - return this.multiply(other.negate()).negate(); - } - - // If both Timestamps are small, use float multiplication - if (this.lessThan(Timestamp.TWO_PWR_24_) && - other.lessThan(Timestamp.TWO_PWR_24_)) { - return Timestamp.fromNumber(this.toNumber() * other.toNumber()); - } - - // Divide each Timestamp into 4 chunks of 16 bits, and then add up 4x4 products. - // We can skip products that would overflow. - - var a48 = this.high_ >>> 16; - var a32 = this.high_ & 0xFFFF; - var a16 = this.low_ >>> 16; - var a00 = this.low_ & 0xFFFF; - - var b48 = other.high_ >>> 16; - var b32 = other.high_ & 0xFFFF; - var b16 = other.low_ >>> 16; - var b00 = other.low_ & 0xFFFF; - - var c48 = 0, c32 = 0, c16 = 0, c00 = 0; - c00 += a00 * b00; - c16 += c00 >>> 16; - c00 &= 0xFFFF; - c16 += a16 * b00; - c32 += c16 >>> 16; - c16 &= 0xFFFF; - c16 += a00 * b16; - c32 += c16 >>> 16; - c16 &= 0xFFFF; - c32 += a32 * b00; - c48 += c32 >>> 16; - c32 &= 0xFFFF; - c32 += a16 * b16; - c48 += c32 >>> 16; - c32 &= 0xFFFF; - c32 += a00 * b32; - c48 += c32 >>> 16; - c32 &= 0xFFFF; - c48 += a48 * b00 + a32 * b16 + a16 * b32 + a00 * b48; - c48 &= 0xFFFF; - return Timestamp.fromBits((c16 << 16) | c00, (c48 << 16) | c32); -}; - -/** - * Returns this Timestamp divided by the given one. - * - * @method - * @param {Timestamp} other Timestamp by which to divide. - * @return {Timestamp} this Timestamp divided by the given one. - */ -Timestamp.prototype.div = function(other) { - if (other.isZero()) { - throw Error('division by zero'); - } else if (this.isZero()) { - return Timestamp.ZERO; - } - - if (this.equals(Timestamp.MIN_VALUE)) { - if (other.equals(Timestamp.ONE) || - other.equals(Timestamp.NEG_ONE)) { - return Timestamp.MIN_VALUE; // recall that -MIN_VALUE == MIN_VALUE - } else if (other.equals(Timestamp.MIN_VALUE)) { - return Timestamp.ONE; - } else { - // At this point, we have |other| >= 2, so |this/other| < |MIN_VALUE|. - var halfThis = this.shiftRight(1); - var approx = halfThis.div(other).shiftLeft(1); - if (approx.equals(Timestamp.ZERO)) { - return other.isNegative() ? Timestamp.ONE : Timestamp.NEG_ONE; - } else { - var rem = this.subtract(other.multiply(approx)); - var result = approx.add(rem.div(other)); - return result; - } - } - } else if (other.equals(Timestamp.MIN_VALUE)) { - return Timestamp.ZERO; - } - - if (this.isNegative()) { - if (other.isNegative()) { - return this.negate().div(other.negate()); - } else { - return this.negate().div(other).negate(); - } - } else if (other.isNegative()) { - return this.div(other.negate()).negate(); - } - - // Repeat the following until the remainder is less than other: find a - // floating-point that approximates remainder / other *from below*, add this - // into the result, and subtract it from the remainder. It is critical that - // the approximate value is less than or equal to the real value so that the - // remainder never becomes negative. - var res = Timestamp.ZERO; - var rem = this; - while (rem.greaterThanOrEqual(other)) { - // Approximate the result of division. This may be a little greater or - // smaller than the actual value. - var approx = Math.max(1, Math.floor(rem.toNumber() / other.toNumber())); - - // We will tweak the approximate result by changing it in the 48-th digit or - // the smallest non-fractional digit, whichever is larger. - var log2 = Math.ceil(Math.log(approx) / Math.LN2); - var delta = (log2 <= 48) ? 1 : Math.pow(2, log2 - 48); - - // Decrease the approximation until it is smaller than the remainder. Note - // that if it is too large, the product overflows and is negative. - var approxRes = Timestamp.fromNumber(approx); - var approxRem = approxRes.multiply(other); - while (approxRem.isNegative() || approxRem.greaterThan(rem)) { - approx -= delta; - approxRes = Timestamp.fromNumber(approx); - approxRem = approxRes.multiply(other); - } - - // We know the answer can't be zero... and actually, zero would cause - // infinite recursion since we would make no progress. - if (approxRes.isZero()) { - approxRes = Timestamp.ONE; - } - - res = res.add(approxRes); - rem = rem.subtract(approxRem); - } - return res; -}; - -/** - * Returns this Timestamp modulo the given one. - * - * @method - * @param {Timestamp} other Timestamp by which to mod. - * @return {Timestamp} this Timestamp modulo the given one. - */ -Timestamp.prototype.modulo = function(other) { - return this.subtract(this.div(other).multiply(other)); -}; - -/** - * The bitwise-NOT of this value. - * - * @method - * @return {Timestamp} the bitwise-NOT of this value. - */ -Timestamp.prototype.not = function() { - return Timestamp.fromBits(~this.low_, ~this.high_); -}; - -/** - * Returns the bitwise-AND of this Timestamp and the given one. - * - * @method - * @param {Timestamp} other the Timestamp with which to AND. - * @return {Timestamp} the bitwise-AND of this and the other. - */ -Timestamp.prototype.and = function(other) { - return Timestamp.fromBits(this.low_ & other.low_, this.high_ & other.high_); -}; - -/** - * Returns the bitwise-OR of this Timestamp and the given one. - * - * @method - * @param {Timestamp} other the Timestamp with which to OR. - * @return {Timestamp} the bitwise-OR of this and the other. - */ -Timestamp.prototype.or = function(other) { - return Timestamp.fromBits(this.low_ | other.low_, this.high_ | other.high_); -}; - -/** - * Returns the bitwise-XOR of this Timestamp and the given one. - * - * @method - * @param {Timestamp} other the Timestamp with which to XOR. - * @return {Timestamp} the bitwise-XOR of this and the other. - */ -Timestamp.prototype.xor = function(other) { - return Timestamp.fromBits(this.low_ ^ other.low_, this.high_ ^ other.high_); -}; - -/** - * Returns this Timestamp with bits shifted to the left by the given amount. - * - * @method - * @param {number} numBits the number of bits by which to shift. - * @return {Timestamp} this shifted to the left by the given amount. - */ -Timestamp.prototype.shiftLeft = function(numBits) { - numBits &= 63; - if (numBits == 0) { - return this; - } else { - var low = this.low_; - if (numBits < 32) { - var high = this.high_; - return Timestamp.fromBits( - low << numBits, - (high << numBits) | (low >>> (32 - numBits))); - } else { - return Timestamp.fromBits(0, low << (numBits - 32)); - } - } -}; - -/** - * Returns this Timestamp with bits shifted to the right by the given amount. - * - * @method - * @param {number} numBits the number of bits by which to shift. - * @return {Timestamp} this shifted to the right by the given amount. - */ -Timestamp.prototype.shiftRight = function(numBits) { - numBits &= 63; - if (numBits == 0) { - return this; - } else { - var high = this.high_; - if (numBits < 32) { - var low = this.low_; - return Timestamp.fromBits( - (low >>> numBits) | (high << (32 - numBits)), - high >> numBits); - } else { - return Timestamp.fromBits( - high >> (numBits - 32), - high >= 0 ? 0 : -1); - } - } -}; - -/** - * Returns this Timestamp with bits shifted to the right by the given amount, with the new top bits matching the current sign bit. - * - * @method - * @param {number} numBits the number of bits by which to shift. - * @return {Timestamp} this shifted to the right by the given amount, with zeros placed into the new leading bits. - */ -Timestamp.prototype.shiftRightUnsigned = function(numBits) { - numBits &= 63; - if (numBits == 0) { - return this; - } else { - var high = this.high_; - if (numBits < 32) { - var low = this.low_; - return Timestamp.fromBits( - (low >>> numBits) | (high << (32 - numBits)), - high >>> numBits); - } else if (numBits == 32) { - return Timestamp.fromBits(high, 0); - } else { - return Timestamp.fromBits(high >>> (numBits - 32), 0); - } - } -}; - -/** - * Returns a Timestamp representing the given (32-bit) integer value. - * - * @method - * @param {number} value the 32-bit integer in question. - * @return {Timestamp} the corresponding Timestamp value. - */ -Timestamp.fromInt = function(value) { - if (-128 <= value && value < 128) { - var cachedObj = Timestamp.INT_CACHE_[value]; - if (cachedObj) { - return cachedObj; - } - } - - var obj = new Timestamp(value | 0, value < 0 ? -1 : 0); - if (-128 <= value && value < 128) { - Timestamp.INT_CACHE_[value] = obj; - } - return obj; -}; - -/** - * Returns a Timestamp representing the given value, provided that it is a finite number. Otherwise, zero is returned. - * - * @method - * @param {number} value the number in question. - * @return {Timestamp} the corresponding Timestamp value. - */ -Timestamp.fromNumber = function(value) { - if (isNaN(value) || !isFinite(value)) { - return Timestamp.ZERO; - } else if (value <= -Timestamp.TWO_PWR_63_DBL_) { - return Timestamp.MIN_VALUE; - } else if (value + 1 >= Timestamp.TWO_PWR_63_DBL_) { - return Timestamp.MAX_VALUE; - } else if (value < 0) { - return Timestamp.fromNumber(-value).negate(); - } else { - return new Timestamp( - (value % Timestamp.TWO_PWR_32_DBL_) | 0, - (value / Timestamp.TWO_PWR_32_DBL_) | 0); - } -}; - -/** - * Returns a Timestamp representing the 64-bit integer that comes by concatenating the given high and low bits. Each is assumed to use 32 bits. - * - * @method - * @param {number} lowBits the low 32-bits. - * @param {number} highBits the high 32-bits. - * @return {Timestamp} the corresponding Timestamp value. - */ -Timestamp.fromBits = function(lowBits, highBits) { - return new Timestamp(lowBits, highBits); -}; - -/** - * Returns a Timestamp representation of the given string, written using the given radix. - * - * @method - * @param {string} str the textual representation of the Timestamp. - * @param {number} opt_radix the radix in which the text is written. - * @return {Timestamp} the corresponding Timestamp value. - */ -Timestamp.fromString = function(str, opt_radix) { - if (str.length == 0) { - throw Error('number format error: empty string'); - } - - var radix = opt_radix || 10; - if (radix < 2 || 36 < radix) { - throw Error('radix out of range: ' + radix); - } - - if (str.charAt(0) == '-') { - return Timestamp.fromString(str.substring(1), radix).negate(); - } else if (str.indexOf('-') >= 0) { - throw Error('number format error: interior "-" character: ' + str); - } - - // Do several (8) digits each time through the loop, so as to - // minimize the calls to the very expensive emulated div. - var radixToPower = Timestamp.fromNumber(Math.pow(radix, 8)); - - var result = Timestamp.ZERO; - for (var i = 0; i < str.length; i += 8) { - var size = Math.min(8, str.length - i); - var value = parseInt(str.substring(i, i + size), radix); - if (size < 8) { - var power = Timestamp.fromNumber(Math.pow(radix, size)); - result = result.multiply(power).add(Timestamp.fromNumber(value)); - } else { - result = result.multiply(radixToPower); - result = result.add(Timestamp.fromNumber(value)); - } - } - return result; -}; - -// NOTE: Common constant values ZERO, ONE, NEG_ONE, etc. are defined below the -// from* methods on which they depend. - - -/** - * A cache of the Timestamp representations of small integer values. - * @type {Object} - * @ignore - */ -Timestamp.INT_CACHE_ = {}; - -// NOTE: the compiler should inline these constant values below and then remove -// these variables, so there should be no runtime penalty for these. - -/** - * Number used repeated below in calculations. This must appear before the - * first call to any from* function below. - * @type {number} - * @ignore - */ -Timestamp.TWO_PWR_16_DBL_ = 1 << 16; - -/** - * @type {number} - * @ignore - */ -Timestamp.TWO_PWR_24_DBL_ = 1 << 24; - -/** - * @type {number} - * @ignore - */ -Timestamp.TWO_PWR_32_DBL_ = Timestamp.TWO_PWR_16_DBL_ * Timestamp.TWO_PWR_16_DBL_; - -/** - * @type {number} - * @ignore - */ -Timestamp.TWO_PWR_31_DBL_ = Timestamp.TWO_PWR_32_DBL_ / 2; - -/** - * @type {number} - * @ignore - */ -Timestamp.TWO_PWR_48_DBL_ = Timestamp.TWO_PWR_32_DBL_ * Timestamp.TWO_PWR_16_DBL_; - -/** - * @type {number} - * @ignore - */ -Timestamp.TWO_PWR_64_DBL_ = Timestamp.TWO_PWR_32_DBL_ * Timestamp.TWO_PWR_32_DBL_; - -/** - * @type {number} - * @ignore - */ -Timestamp.TWO_PWR_63_DBL_ = Timestamp.TWO_PWR_64_DBL_ / 2; - -/** @type {Timestamp} */ -Timestamp.ZERO = Timestamp.fromInt(0); - -/** @type {Timestamp} */ -Timestamp.ONE = Timestamp.fromInt(1); - -/** @type {Timestamp} */ -Timestamp.NEG_ONE = Timestamp.fromInt(-1); - -/** @type {Timestamp} */ -Timestamp.MAX_VALUE = - Timestamp.fromBits(0xFFFFFFFF | 0, 0x7FFFFFFF | 0); - -/** @type {Timestamp} */ -Timestamp.MIN_VALUE = Timestamp.fromBits(0, 0x80000000 | 0); - -/** - * @type {Timestamp} - * @ignore - */ -Timestamp.TWO_PWR_24_ = Timestamp.fromInt(1 << 24); - -/** - * Expose. - */ -module.exports = Timestamp; -module.exports.Timestamp = Timestamp; \ No newline at end of file diff --git a/ts-ticket-office-service/node_modules/bson/lib/code.js b/ts-ticket-office-service/node_modules/bson/lib/code.js new file mode 100644 index 000000000..585539378 --- /dev/null +++ b/ts-ticket-office-service/node_modules/bson/lib/code.js @@ -0,0 +1,46 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.Code = void 0; +/** + * A class representation of the BSON Code type. + * @public + * @category BSONType + */ +var Code = /** @class */ (function () { + /** + * @param code - a string or function. + * @param scope - an optional scope for the function. + */ + function Code(code, scope) { + if (!(this instanceof Code)) + return new Code(code, scope); + this.code = code; + this.scope = scope; + } + Code.prototype.toJSON = function () { + return { code: this.code, scope: this.scope }; + }; + /** @internal */ + Code.prototype.toExtendedJSON = function () { + if (this.scope) { + return { $code: this.code, $scope: this.scope }; + } + return { $code: this.code }; + }; + /** @internal */ + Code.fromExtendedJSON = function (doc) { + return new Code(doc.$code, doc.$scope); + }; + /** @internal */ + Code.prototype[Symbol.for('nodejs.util.inspect.custom')] = function () { + return this.inspect(); + }; + Code.prototype.inspect = function () { + var codeJson = this.toJSON(); + return "new Code(\"".concat(String(codeJson.code), "\"").concat(codeJson.scope ? ", ".concat(JSON.stringify(codeJson.scope)) : '', ")"); + }; + return Code; +}()); +exports.Code = Code; +Object.defineProperty(Code.prototype, '_bsontype', { value: 'Code' }); +//# sourceMappingURL=code.js.map \ No newline at end of file diff --git a/ts-ticket-office-service/node_modules/bson/lib/code.js.map b/ts-ticket-office-service/node_modules/bson/lib/code.js.map new file mode 100644 index 000000000..2291a6b93 --- /dev/null +++ b/ts-ticket-office-service/node_modules/bson/lib/code.js.map @@ -0,0 +1 @@ +{"version":3,"file":"code.js","sourceRoot":"","sources":["../src/code.ts"],"names":[],"mappings":";;;AAQA;;;;GAIG;AACH;IAKE;;;OAGG;IACH,cAAY,IAAuB,EAAE,KAAgB;QACnD,IAAI,CAAC,CAAC,IAAI,YAAY,IAAI,CAAC;YAAE,OAAO,IAAI,IAAI,CAAC,IAAI,EAAE,KAAK,CAAC,CAAC;QAE1D,IAAI,CAAC,IAAI,GAAG,IAAI,CAAC;QACjB,IAAI,CAAC,KAAK,GAAG,KAAK,CAAC;IACrB,CAAC;IAED,qBAAM,GAAN;QACE,OAAO,EAAE,IAAI,EAAE,IAAI,CAAC,IAAI,EAAE,KAAK,EAAE,IAAI,CAAC,KAAK,EAAE,CAAC;IAChD,CAAC;IAED,gBAAgB;IAChB,6BAAc,GAAd;QACE,IAAI,IAAI,CAAC,KAAK,EAAE;YACd,OAAO,EAAE,KAAK,EAAE,IAAI,CAAC,IAAI,EAAE,MAAM,EAAE,IAAI,CAAC,KAAK,EAAE,CAAC;SACjD;QAED,OAAO,EAAE,KAAK,EAAE,IAAI,CAAC,IAAI,EAAE,CAAC;IAC9B,CAAC;IAED,gBAAgB;IACT,qBAAgB,GAAvB,UAAwB,GAAiB;QACvC,OAAO,IAAI,IAAI,CAAC,GAAG,CAAC,KAAK,EAAE,GAAG,CAAC,MAAM,CAAC,CAAC;IACzC,CAAC;IAED,gBAAgB;IAChB,eAAC,MAAM,CAAC,GAAG,CAAC,4BAA4B,CAAC,CAAC,GAA1C;QACE,OAAO,IAAI,CAAC,OAAO,EAAE,CAAC;IACxB,CAAC;IAED,sBAAO,GAAP;QACE,IAAM,QAAQ,GAAG,IAAI,CAAC,MAAM,EAAE,CAAC;QAC/B,OAAO,qBAAa,MAAM,CAAC,QAAQ,CAAC,IAAI,CAAC,eACvC,QAAQ,CAAC,KAAK,CAAC,CAAC,CAAC,YAAK,IAAI,CAAC,SAAS,CAAC,QAAQ,CAAC,KAAK,CAAC,CAAE,CAAC,CAAC,CAAC,EAAE,MAC1D,CAAC;IACN,CAAC;IACH,WAAC;AAAD,CAAC,AA7CD,IA6CC;AA7CY,oBAAI;AA+CjB,MAAM,CAAC,cAAc,CAAC,IAAI,CAAC,SAAS,EAAE,WAAW,EAAE,EAAE,KAAK,EAAE,MAAM,EAAE,CAAC,CAAC"} \ No newline at end of file diff --git a/ts-ticket-office-service/node_modules/bson/lib/constants.js b/ts-ticket-office-service/node_modules/bson/lib/constants.js new file mode 100644 index 000000000..ff8b68d3d --- /dev/null +++ b/ts-ticket-office-service/node_modules/bson/lib/constants.js @@ -0,0 +1,82 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.BSON_BINARY_SUBTYPE_USER_DEFINED = exports.BSON_BINARY_SUBTYPE_COLUMN = exports.BSON_BINARY_SUBTYPE_ENCRYPTED = exports.BSON_BINARY_SUBTYPE_MD5 = exports.BSON_BINARY_SUBTYPE_UUID_NEW = exports.BSON_BINARY_SUBTYPE_UUID = exports.BSON_BINARY_SUBTYPE_BYTE_ARRAY = exports.BSON_BINARY_SUBTYPE_FUNCTION = exports.BSON_BINARY_SUBTYPE_DEFAULT = exports.BSON_DATA_MAX_KEY = exports.BSON_DATA_MIN_KEY = exports.BSON_DATA_DECIMAL128 = exports.BSON_DATA_LONG = exports.BSON_DATA_TIMESTAMP = exports.BSON_DATA_INT = exports.BSON_DATA_CODE_W_SCOPE = exports.BSON_DATA_SYMBOL = exports.BSON_DATA_CODE = exports.BSON_DATA_DBPOINTER = exports.BSON_DATA_REGEXP = exports.BSON_DATA_NULL = exports.BSON_DATA_DATE = exports.BSON_DATA_BOOLEAN = exports.BSON_DATA_OID = exports.BSON_DATA_UNDEFINED = exports.BSON_DATA_BINARY = exports.BSON_DATA_ARRAY = exports.BSON_DATA_OBJECT = exports.BSON_DATA_STRING = exports.BSON_DATA_NUMBER = exports.JS_INT_MIN = exports.JS_INT_MAX = exports.BSON_INT64_MIN = exports.BSON_INT64_MAX = exports.BSON_INT32_MIN = exports.BSON_INT32_MAX = void 0; +/** @internal */ +exports.BSON_INT32_MAX = 0x7fffffff; +/** @internal */ +exports.BSON_INT32_MIN = -0x80000000; +/** @internal */ +exports.BSON_INT64_MAX = Math.pow(2, 63) - 1; +/** @internal */ +exports.BSON_INT64_MIN = -Math.pow(2, 63); +/** + * Any integer up to 2^53 can be precisely represented by a double. + * @internal + */ +exports.JS_INT_MAX = Math.pow(2, 53); +/** + * Any integer down to -2^53 can be precisely represented by a double. + * @internal + */ +exports.JS_INT_MIN = -Math.pow(2, 53); +/** Number BSON Type @internal */ +exports.BSON_DATA_NUMBER = 1; +/** String BSON Type @internal */ +exports.BSON_DATA_STRING = 2; +/** Object BSON Type @internal */ +exports.BSON_DATA_OBJECT = 3; +/** Array BSON Type @internal */ +exports.BSON_DATA_ARRAY = 4; +/** Binary BSON Type @internal */ +exports.BSON_DATA_BINARY = 5; +/** Binary BSON Type @internal */ +exports.BSON_DATA_UNDEFINED = 6; +/** ObjectId BSON Type @internal */ +exports.BSON_DATA_OID = 7; +/** Boolean BSON Type @internal */ +exports.BSON_DATA_BOOLEAN = 8; +/** Date BSON Type @internal */ +exports.BSON_DATA_DATE = 9; +/** null BSON Type @internal */ +exports.BSON_DATA_NULL = 10; +/** RegExp BSON Type @internal */ +exports.BSON_DATA_REGEXP = 11; +/** Code BSON Type @internal */ +exports.BSON_DATA_DBPOINTER = 12; +/** Code BSON Type @internal */ +exports.BSON_DATA_CODE = 13; +/** Symbol BSON Type @internal */ +exports.BSON_DATA_SYMBOL = 14; +/** Code with Scope BSON Type @internal */ +exports.BSON_DATA_CODE_W_SCOPE = 15; +/** 32 bit Integer BSON Type @internal */ +exports.BSON_DATA_INT = 16; +/** Timestamp BSON Type @internal */ +exports.BSON_DATA_TIMESTAMP = 17; +/** Long BSON Type @internal */ +exports.BSON_DATA_LONG = 18; +/** Decimal128 BSON Type @internal */ +exports.BSON_DATA_DECIMAL128 = 19; +/** MinKey BSON Type @internal */ +exports.BSON_DATA_MIN_KEY = 0xff; +/** MaxKey BSON Type @internal */ +exports.BSON_DATA_MAX_KEY = 0x7f; +/** Binary Default Type @internal */ +exports.BSON_BINARY_SUBTYPE_DEFAULT = 0; +/** Binary Function Type @internal */ +exports.BSON_BINARY_SUBTYPE_FUNCTION = 1; +/** Binary Byte Array Type @internal */ +exports.BSON_BINARY_SUBTYPE_BYTE_ARRAY = 2; +/** Binary Deprecated UUID Type @deprecated Please use BSON_BINARY_SUBTYPE_UUID_NEW @internal */ +exports.BSON_BINARY_SUBTYPE_UUID = 3; +/** Binary UUID Type @internal */ +exports.BSON_BINARY_SUBTYPE_UUID_NEW = 4; +/** Binary MD5 Type @internal */ +exports.BSON_BINARY_SUBTYPE_MD5 = 5; +/** Encrypted BSON type @internal */ +exports.BSON_BINARY_SUBTYPE_ENCRYPTED = 6; +/** Column BSON type @internal */ +exports.BSON_BINARY_SUBTYPE_COLUMN = 7; +/** Binary User Defined Type @internal */ +exports.BSON_BINARY_SUBTYPE_USER_DEFINED = 128; +//# sourceMappingURL=constants.js.map \ No newline at end of file diff --git a/ts-ticket-office-service/node_modules/bson/lib/constants.js.map b/ts-ticket-office-service/node_modules/bson/lib/constants.js.map new file mode 100644 index 000000000..3b9c0ca6c --- /dev/null +++ b/ts-ticket-office-service/node_modules/bson/lib/constants.js.map @@ -0,0 +1 @@ +{"version":3,"file":"constants.js","sourceRoot":"","sources":["../src/constants.ts"],"names":[],"mappings":";;;AAAA,gBAAgB;AACH,QAAA,cAAc,GAAG,UAAU,CAAC;AACzC,gBAAgB;AACH,QAAA,cAAc,GAAG,CAAC,UAAU,CAAC;AAC1C,gBAAgB;AACH,QAAA,cAAc,GAAG,IAAI,CAAC,GAAG,CAAC,CAAC,EAAE,EAAE,CAAC,GAAG,CAAC,CAAC;AAClD,gBAAgB;AACH,QAAA,cAAc,GAAG,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC;AAE/C;;;GAGG;AACU,QAAA,UAAU,GAAG,IAAI,CAAC,GAAG,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC;AAE1C;;;GAGG;AACU,QAAA,UAAU,GAAG,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC;AAE3C,iCAAiC;AACpB,QAAA,gBAAgB,GAAG,CAAC,CAAC;AAElC,iCAAiC;AACpB,QAAA,gBAAgB,GAAG,CAAC,CAAC;AAElC,iCAAiC;AACpB,QAA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BAA4B,GAAG,CAAC,CAAC;AAE9C,gCAAgC;AACnB,QAAA,uBAAuB,GAAG,CAAC,CAAC;AAEzC,oCAAoC;AACvB,QAAA,6BAA6B,GAAG,CAAC,CAAC;AAE/C,iCAAiC;AACpB,QAAA,0BAA0B,GAAG,CAAC,CAAC;AAE5C,yCAAyC;AAC5B,QAAA,gCAAgC,GAAG,GAAG,CAAC"} \ No newline at end of file diff --git a/ts-ticket-office-service/node_modules/bson/lib/db_ref.js b/ts-ticket-office-service/node_modules/bson/lib/db_ref.js new file mode 100644 index 000000000..d18bd965e --- /dev/null +++ b/ts-ticket-office-service/node_modules/bson/lib/db_ref.js @@ -0,0 +1,97 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.DBRef = exports.isDBRefLike = void 0; +var utils_1 = require("./parser/utils"); +/** @internal */ +function isDBRefLike(value) { + return ((0, utils_1.isObjectLike)(value) && + value.$id != null && + typeof value.$ref === 'string' && + (value.$db == null || typeof value.$db === 'string')); +} +exports.isDBRefLike = isDBRefLike; +/** + * A class representation of the BSON DBRef type. + * @public + * @category BSONType + */ +var DBRef = /** @class */ (function () { + /** + * @param collection - the collection name. + * @param oid - the reference ObjectId. + * @param db - optional db name, if omitted the reference is local to the current db. + */ + function DBRef(collection, oid, db, fields) { + if (!(this instanceof DBRef)) + return new DBRef(collection, oid, db, fields); + // check if namespace has been provided + var parts = collection.split('.'); + if (parts.length === 2) { + db = parts.shift(); + // eslint-disable-next-line @typescript-eslint/no-non-null-assertion + collection = parts.shift(); + } + this.collection = collection; + this.oid = oid; + this.db = db; + this.fields = fields || {}; + } + Object.defineProperty(DBRef.prototype, "namespace", { + // Property provided for compatibility with the 1.x parser + // the 1.x parser used a "namespace" property, while 4.x uses "collection" + /** @internal */ + get: function () { + return this.collection; + }, + set: function (value) { + this.collection = value; + }, + enumerable: false, + configurable: true + }); + DBRef.prototype.toJSON = function () { + var o = Object.assign({ + $ref: this.collection, + $id: this.oid + }, this.fields); + if (this.db != null) + o.$db = this.db; + return o; + }; + /** @internal */ + DBRef.prototype.toExtendedJSON = function (options) { + options = options || {}; + var o = { + $ref: this.collection, + $id: this.oid + }; + if (options.legacy) { + return o; + } + if (this.db) + o.$db = this.db; + o = Object.assign(o, this.fields); + return o; + }; + /** @internal */ + DBRef.fromExtendedJSON = function (doc) { + var copy = Object.assign({}, doc); + delete copy.$ref; + delete copy.$id; + delete copy.$db; + return new DBRef(doc.$ref, doc.$id, doc.$db, copy); + }; + /** @internal */ + DBRef.prototype[Symbol.for('nodejs.util.inspect.custom')] = function () { + return this.inspect(); + }; + DBRef.prototype.inspect = function () { + // NOTE: if OID is an ObjectId class it will just print the oid string. + var oid = this.oid === undefined || this.oid.toString === undefined ? this.oid : this.oid.toString(); + return "new DBRef(\"".concat(this.namespace, "\", new ObjectId(\"").concat(String(oid), "\")").concat(this.db ? ", \"".concat(this.db, "\"") : '', ")"); + }; + return DBRef; +}()); +exports.DBRef = DBRef; +Object.defineProperty(DBRef.prototype, '_bsontype', { value: 'DBRef' }); +//# sourceMappingURL=db_ref.js.map \ No newline at end of file diff --git a/ts-ticket-office-service/node_modules/bson/lib/db_ref.js.map b/ts-ticket-office-service/node_modules/bson/lib/db_ref.js.map new file mode 100644 index 000000000..74e49aac7 --- /dev/null +++ b/ts-ticket-office-service/node_modules/bson/lib/db_ref.js.map @@ -0,0 +1 @@ +{"version":3,"file":"db_ref.js","sourceRoot":"","sources":["../src/db_ref.ts"],"names":[],"mappings":";;;AAGA,wCAA8C;AAS9C,gBAAgB;AAChB,SAAgB,WAAW,CAAC,KAAc;IACxC,OAAO,CACL,IAAA,oBAAY,EAAC,KAAK,CAAC;QACnB,KAAK,CAAC,GAAG,IAAI,IAAI;QACjB,OAAO,KAAK,CAAC,IAAI,KAAK,QAAQ;QAC9B,CAAC,KAAK,CAAC,GAAG,IAAI,IAAI,IAAI,OAAO,KAAK,CAAC,GAAG,KAAK,QAAQ,CAAC,CACrD,CAAC;AACJ,CAAC;AAPD,kCA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CAAC,CAAC,CAAC,cAAM,IAAI,CAAC,EAAE,OAAG,CAAC,CAAC,CAAC,EAAE,MAC9B,CAAC;IACN,CAAC;IACH,YAAC;AAAD,CAAC,AA9FD,IA8FC;AA9FY,sBAAK;AAgGlB,MAAM,CAAC,cAAc,CAAC,KAAK,CAAC,SAAS,EAAE,WAAW,EAAE,EAAE,KAAK,EAAE,OAAO,EAAE,CAAC,CAAC"} \ No newline at end of file diff --git a/ts-ticket-office-service/node_modules/bson/lib/decimal128.js b/ts-ticket-office-service/node_modules/bson/lib/decimal128.js new file mode 100644 index 000000000..2fd7efa84 --- /dev/null +++ b/ts-ticket-office-service/node_modules/bson/lib/decimal128.js @@ -0,0 +1,669 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.Decimal128 = void 0; +var buffer_1 = require("buffer"); +var error_1 = require("./error"); +var long_1 = require("./long"); +var utils_1 = require("./parser/utils"); +var PARSE_STRING_REGEXP = /^(\+|-)?(\d+|(\d*\.\d*))?(E|e)?([-+])?(\d+)?$/; +var PARSE_INF_REGEXP = /^(\+|-)?(Infinity|inf)$/i; +var PARSE_NAN_REGEXP = /^(\+|-)?NaN$/i; +var EXPONENT_MAX = 6111; +var EXPONENT_MIN = -6176; +var EXPONENT_BIAS = 6176; +var MAX_DIGITS = 34; +// Nan value bits as 32 bit values (due to lack of longs) +var NAN_BUFFER = [ + 0x7c, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 +].reverse(); +// Infinity value bits 32 bit values (due to lack of longs) +var INF_NEGATIVE_BUFFER = [ + 0xf8, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 +].reverse(); +var INF_POSITIVE_BUFFER = [ + 0x78, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 +].reverse(); +var EXPONENT_REGEX = /^([-+])?(\d+)?$/; +// Extract least significant 5 bits +var COMBINATION_MASK = 0x1f; +// Extract least significant 14 bits +var EXPONENT_MASK = 0x3fff; +// Value of combination field for Inf +var COMBINATION_INFINITY = 30; +// Value of combination field for NaN +var COMBINATION_NAN = 31; +// Detect if the value is a digit +function isDigit(value) { + return !isNaN(parseInt(value, 10)); +} +// Divide two uint128 values +function divideu128(value) { + var DIVISOR = long_1.Long.fromNumber(1000 * 1000 * 1000); + var _rem = long_1.Long.fromNumber(0); + if (!value.parts[0] && !value.parts[1] && !value.parts[2] && !value.parts[3]) { + return { quotient: value, rem: _rem }; + } + for (var i = 0; i <= 3; i++) { + // Adjust remainder to match value of next dividend + _rem = _rem.shiftLeft(32); + // Add the divided to _rem + _rem = _rem.add(new long_1.Long(value.parts[i], 0)); + value.parts[i] = _rem.div(DIVISOR).low; + _rem = _rem.modulo(DIVISOR); + } + return { quotient: value, rem: _rem }; +} +// Multiply two Long values and return the 128 bit value +function multiply64x2(left, right) { + if (!left && !right) { + return { high: long_1.Long.fromNumber(0), low: long_1.Long.fromNumber(0) }; + } + var leftHigh = left.shiftRightUnsigned(32); + var leftLow = new long_1.Long(left.getLowBits(), 0); + var rightHigh = right.shiftRightUnsigned(32); + var rightLow = new long_1.Long(right.getLowBits(), 0); + var productHigh = leftHigh.multiply(rightHigh); + var productMid = leftHigh.multiply(rightLow); + var productMid2 = leftLow.multiply(rightHigh); + var productLow = leftLow.multiply(rightLow); + productHigh = productHigh.add(productMid.shiftRightUnsigned(32)); + productMid = new long_1.Long(productMid.getLowBits(), 0) + .add(productMid2) + .add(productLow.shiftRightUnsigned(32)); + productHigh = productHigh.add(productMid.shiftRightUnsigned(32)); + productLow = productMid.shiftLeft(32).add(new long_1.Long(productLow.getLowBits(), 0)); + // Return the 128 bit result + return { high: productHigh, low: productLow }; +} +function lessThan(left, right) { + // Make values unsigned + var uhleft = left.high >>> 0; + var uhright = right.high >>> 0; + // Compare high bits first + if (uhleft < uhright) { + return true; + } + else if (uhleft === uhright) { + var ulleft = left.low >>> 0; + var ulright = right.low >>> 0; + if (ulleft < ulright) + return true; + } + return false; +} +function invalidErr(string, message) { + throw new error_1.BSONTypeError("\"".concat(string, "\" is not a valid Decimal128 string - ").concat(message)); +} +/** + * A class representation of the BSON Decimal128 type. + * @public + * @category BSONType + */ +var Decimal128 = /** @class */ (function () { + /** + * @param bytes - a buffer containing the raw Decimal128 bytes in little endian order, + * or a string representation as returned by .toString() + */ + function Decimal128(bytes) { + if (!(this instanceof Decimal128)) + return new Decimal128(bytes); + if (typeof bytes === 'string') { + this.bytes = Decimal128.fromString(bytes).bytes; + } + else if ((0, utils_1.isUint8Array)(bytes)) { + if (bytes.byteLength !== 16) { + throw new error_1.BSONTypeError('Decimal128 must take a Buffer of 16 bytes'); + } + this.bytes = bytes; + } + else { + throw new error_1.BSONTypeError('Decimal128 must take a Buffer or string'); + } + } + /** + * Create a Decimal128 instance from a string representation + * + * @param representation - a numeric string representation. + */ + Decimal128.fromString = function (representation) { + // Parse state tracking + var isNegative = false; + var sawRadix = false; + var foundNonZero = false; + // Total number of significant digits (no leading or trailing zero) + var significantDigits = 0; + // Total number of significand digits read + var nDigitsRead = 0; + // Total number of digits (no leading zeros) + var nDigits = 0; + // The number of the digits after radix + var radixPosition = 0; + // The index of the first non-zero in *str* + var firstNonZero = 0; + // Digits Array + var digits = [0]; + // The number of digits in digits + var nDigitsStored = 0; + // Insertion pointer for digits + var digitsInsert = 0; + // The index of the first non-zero digit + var firstDigit = 0; + // The index of the last digit + var lastDigit = 0; + // Exponent + var exponent = 0; + // loop index over array + var i = 0; + // The high 17 digits of the significand + var significandHigh = new long_1.Long(0, 0); + // The low 17 digits of the significand + var significandLow = new long_1.Long(0, 0); + // The biased exponent + var biasedExponent = 0; + // Read index + var index = 0; + // Naively prevent against REDOS attacks. + // TODO: implementing a custom parsing for this, or refactoring the regex would yield + // further gains. + if (representation.length >= 7000) { + throw new error_1.BSONTypeError('' + representation + ' not a valid Decimal128 string'); + } + // Results + var stringMatch = representation.match(PARSE_STRING_REGEXP); + var infMatch = representation.match(PARSE_INF_REGEXP); + var nanMatch = representation.match(PARSE_NAN_REGEXP); + // Validate the string + if ((!stringMatch && !infMatch && !nanMatch) || representation.length === 0) { + throw new error_1.BSONTypeError('' + representation + ' not a valid Decimal128 string'); + } + if (stringMatch) { + // full_match = stringMatch[0] + // sign = stringMatch[1] + var unsignedNumber = stringMatch[2]; + // stringMatch[3] is undefined if a whole number (ex "1", 12") + // but defined if a number w/ decimal in it (ex "1.0, 12.2") + var e = stringMatch[4]; + var expSign = stringMatch[5]; + var expNumber = stringMatch[6]; + // they provided e, but didn't give an exponent number. for ex "1e" + if (e && expNumber === undefined) + invalidErr(representation, 'missing exponent power'); + // they provided e, but didn't give a number before it. for ex "e1" + if (e && unsignedNumber === undefined) + invalidErr(representation, 'missing exponent base'); + if (e === undefined && (expSign || expNumber)) { + invalidErr(representation, 'missing e before exponent'); + } + } + // Get the negative or positive sign + if (representation[index] === '+' || representation[index] === '-') { + isNegative = representation[index++] === '-'; + } + // Check if user passed Infinity or NaN + if (!isDigit(representation[index]) && representation[index] !== '.') { + if (representation[index] === 'i' || representation[index] === 'I') { + return new Decimal128(buffer_1.Buffer.from(isNegative ? INF_NEGATIVE_BUFFER : INF_POSITIVE_BUFFER)); + } + else if (representation[index] === 'N') { + return new Decimal128(buffer_1.Buffer.from(NAN_BUFFER)); + } + } + // Read all the digits + while (isDigit(representation[index]) || representation[index] === '.') { + if (representation[index] === '.') { + if (sawRadix) + invalidErr(representation, 'contains multiple periods'); + sawRadix = true; + index = index + 1; + continue; + } + if (nDigitsStored < 34) { + if (representation[index] !== '0' || foundNonZero) { + if (!foundNonZero) { + firstNonZero = nDigitsRead; + } + foundNonZero = true; + // Only store 34 digits + digits[digitsInsert++] = parseInt(representation[index], 10); + nDigitsStored = nDigitsStored + 1; + } + } + if (foundNonZero) + nDigits = nDigits + 1; + if (sawRadix) + radixPosition = radixPosition + 1; + nDigitsRead = nDigitsRead + 1; + index = index + 1; + } + if (sawRadix && !nDigitsRead) + throw new error_1.BSONTypeError('' + representation + ' not a valid Decimal128 string'); + // Read exponent if exists + if (representation[index] === 'e' || representation[index] === 'E') { + // Read exponent digits + var match = representation.substr(++index).match(EXPONENT_REGEX); + // No digits read + if (!match || !match[2]) + return new Decimal128(buffer_1.Buffer.from(NAN_BUFFER)); + // Get exponent + exponent = parseInt(match[0], 10); + // Adjust the index + index = index + match[0].length; + } + // Return not a number + if (representation[index]) + return new Decimal128(buffer_1.Buffer.from(NAN_BUFFER)); + // Done reading input + // Find first non-zero digit in digits + firstDigit = 0; + if (!nDigitsStored) { + firstDigit = 0; + lastDigit = 0; + digits[0] = 0; + nDigits = 1; + nDigitsStored = 1; + significantDigits = 0; + } + else { + lastDigit = nDigitsStored - 1; + significantDigits = nDigits; + if (significantDigits !== 1) { + while (digits[firstNonZero + significantDigits - 1] === 0) { + significantDigits = significantDigits - 1; + } + } + } + // Normalization of exponent + // Correct exponent based on radix position, and shift significand as needed + // to represent user input + // Overflow prevention + if (exponent <= radixPosition && radixPosition - exponent > 1 << 14) { + exponent = EXPONENT_MIN; + } + else { + exponent = exponent - radixPosition; + } + // Attempt to normalize the exponent + while (exponent > EXPONENT_MAX) { + // Shift exponent to significand and decrease + lastDigit = lastDigit + 1; + if (lastDigit - firstDigit > MAX_DIGITS) { + // Check if we have a zero then just hard clamp, otherwise fail + var digitsString = digits.join(''); + if (digitsString.match(/^0+$/)) { + exponent = EXPONENT_MAX; + break; + } + invalidErr(representation, 'overflow'); + } + exponent = exponent - 1; + } + while (exponent < EXPONENT_MIN || nDigitsStored < nDigits) { + // Shift last digit. can only do this if < significant digits than # stored. + if (lastDigit === 0 && significantDigits < nDigitsStored) { + exponent = EXPONENT_MIN; + significantDigits = 0; + break; + } + if (nDigitsStored < nDigits) { + // adjust to match digits not stored + nDigits = nDigits - 1; + } + else { + // adjust to round + lastDigit = lastDigit - 1; + } + if (exponent < EXPONENT_MAX) { + exponent = exponent + 1; + } + else { + // Check if we have a zero then just hard clamp, otherwise fail + var digitsString = digits.join(''); + if (digitsString.match(/^0+$/)) { + exponent = EXPONENT_MAX; + break; + } + invalidErr(representation, 'overflow'); + } + } + // Round + // We've normalized the exponent, but might still need to round. + if (lastDigit - firstDigit + 1 < significantDigits) { + var endOfString = nDigitsRead; + // If we have seen a radix point, 'string' is 1 longer than we have + // documented with ndigits_read, so inc the position of the first nonzero + // digit and the position that digits are read to. + if (sawRadix) { + firstNonZero = firstNonZero + 1; + endOfString = endOfString + 1; + } + // if negative, we need to increment again to account for - sign at start. + if (isNegative) { + firstNonZero = firstNonZero + 1; + endOfString = endOfString + 1; + } + var roundDigit = parseInt(representation[firstNonZero + lastDigit + 1], 10); + var roundBit = 0; + if (roundDigit >= 5) { + roundBit = 1; + if (roundDigit === 5) { + roundBit = digits[lastDigit] % 2 === 1 ? 1 : 0; + for (i = firstNonZero + lastDigit + 2; i < endOfString; i++) { + if (parseInt(representation[i], 10)) { + roundBit = 1; + break; + } + } + } + } + if (roundBit) { + var dIdx = lastDigit; + for (; dIdx >= 0; dIdx--) { + if (++digits[dIdx] > 9) { + digits[dIdx] = 0; + // overflowed most significant digit + if (dIdx === 0) { + if (exponent < EXPONENT_MAX) { + exponent = exponent + 1; + digits[dIdx] = 1; + } + else { + return new Decimal128(buffer_1.Buffer.from(isNegative ? INF_NEGATIVE_BUFFER : INF_POSITIVE_BUFFER)); + } + } + } + } + } + } + // Encode significand + // The high 17 digits of the significand + significandHigh = long_1.Long.fromNumber(0); + // The low 17 digits of the significand + significandLow = long_1.Long.fromNumber(0); + // read a zero + if (significantDigits === 0) { + significandHigh = long_1.Long.fromNumber(0); + significandLow = long_1.Long.fromNumber(0); + } + else if (lastDigit - firstDigit < 17) { + var dIdx = firstDigit; + significandLow = long_1.Long.fromNumber(digits[dIdx++]); + significandHigh = new long_1.Long(0, 0); + for (; dIdx <= lastDigit; dIdx++) { + significandLow = significandLow.multiply(long_1.Long.fromNumber(10)); + significandLow = significandLow.add(long_1.Long.fromNumber(digits[dIdx])); + } + } + else { + var dIdx = firstDigit; + significandHigh = long_1.Long.fromNumber(digits[dIdx++]); + for (; dIdx <= lastDigit - 17; dIdx++) { + significandHigh = significandHigh.multiply(long_1.Long.fromNumber(10)); + significandHigh = significandHigh.add(long_1.Long.fromNumber(digits[dIdx])); + } + significandLow = long_1.Long.fromNumber(digits[dIdx++]); + for (; dIdx <= lastDigit; dIdx++) { + significandLow = significandLow.multiply(long_1.Long.fromNumber(10)); + significandLow = significandLow.add(long_1.Long.fromNumber(digits[dIdx])); + } + } + var significand = multiply64x2(significandHigh, long_1.Long.fromString('100000000000000000')); + significand.low = significand.low.add(significandLow); + if (lessThan(significand.low, significandLow)) { + significand.high = significand.high.add(long_1.Long.fromNumber(1)); + } + // Biased exponent + biasedExponent = exponent + EXPONENT_BIAS; + var dec = { low: long_1.Long.fromNumber(0), high: long_1.Long.fromNumber(0) }; + // Encode combination, exponent, and significand. + if (significand.high.shiftRightUnsigned(49).and(long_1.Long.fromNumber(1)).equals(long_1.Long.fromNumber(1))) { + // Encode '11' into bits 1 to 3 + dec.high = dec.high.or(long_1.Long.fromNumber(0x3).shiftLeft(61)); + dec.high = dec.high.or(long_1.Long.fromNumber(biasedExponent).and(long_1.Long.fromNumber(0x3fff).shiftLeft(47))); + dec.high = dec.high.or(significand.high.and(long_1.Long.fromNumber(0x7fffffffffff))); + } + else { + dec.high = dec.high.or(long_1.Long.fromNumber(biasedExponent & 0x3fff).shiftLeft(49)); + dec.high = dec.high.or(significand.high.and(long_1.Long.fromNumber(0x1ffffffffffff))); + } + dec.low = significand.low; + // Encode sign + if (isNegative) { + dec.high = dec.high.or(long_1.Long.fromString('9223372036854775808')); + } + // Encode into a buffer + var buffer = buffer_1.Buffer.alloc(16); + index = 0; + // Encode the low 64 bits of the decimal + // Encode low bits + buffer[index++] = dec.low.low & 0xff; + buffer[index++] = (dec.low.low >> 8) & 0xff; + buffer[index++] = (dec.low.low >> 16) & 0xff; + buffer[index++] = (dec.low.low >> 24) & 0xff; + // Encode high bits + buffer[index++] = dec.low.high & 0xff; + buffer[index++] = (dec.low.high >> 8) & 0xff; + buffer[index++] = (dec.low.high >> 16) & 0xff; + buffer[index++] = (dec.low.high >> 24) & 0xff; + // Encode the high 64 bits of the decimal + // Encode low bits + buffer[index++] = dec.high.low & 0xff; + buffer[index++] = (dec.high.low >> 8) & 0xff; + buffer[index++] = (dec.high.low >> 16) & 0xff; + buffer[index++] = (dec.high.low >> 24) & 0xff; + // Encode high bits + buffer[index++] = dec.high.high & 0xff; + buffer[index++] = (dec.high.high >> 8) & 0xff; + buffer[index++] = (dec.high.high >> 16) & 0xff; + buffer[index++] = (dec.high.high >> 24) & 0xff; + // Return the new Decimal128 + return new Decimal128(buffer); + }; + /** Create a string representation of the raw Decimal128 value */ + Decimal128.prototype.toString = function () { + // Note: bits in this routine are referred to starting at 0, + // from the sign bit, towards the coefficient. + // decoded biased exponent (14 bits) + var biased_exponent; + // the number of significand digits + var significand_digits = 0; + // the base-10 digits in the significand + var significand = new Array(36); + for (var i = 0; i < significand.length; i++) + significand[i] = 0; + // read pointer into significand + var index = 0; + // true if the number is zero + var is_zero = false; + // the most significant significand bits (50-46) + var significand_msb; + // temporary storage for significand decoding + var significand128 = { parts: [0, 0, 0, 0] }; + // indexing variables + var j, k; + // Output string + var string = []; + // Unpack index + index = 0; + // Buffer reference + var buffer = this.bytes; + // Unpack the low 64bits into a long + // bits 96 - 127 + var low = buffer[index++] | (buffer[index++] << 8) | (buffer[index++] << 16) | (buffer[index++] << 24); + // bits 64 - 95 + var midl = buffer[index++] | (buffer[index++] << 8) | (buffer[index++] << 16) | (buffer[index++] << 24); + // Unpack the high 64bits into a long + // bits 32 - 63 + var midh = buffer[index++] | (buffer[index++] << 8) | (buffer[index++] << 16) | (buffer[index++] << 24); + // bits 0 - 31 + var high = buffer[index++] | (buffer[index++] << 8) | (buffer[index++] << 16) | (buffer[index++] << 24); + // Unpack index + index = 0; + // Create the state of the decimal + var dec = { + low: new long_1.Long(low, midl), + high: new long_1.Long(midh, high) + }; + if (dec.high.lessThan(long_1.Long.ZERO)) { + string.push('-'); + } + // Decode combination field and exponent + // bits 1 - 5 + var combination = (high >> 26) & COMBINATION_MASK; + if (combination >> 3 === 3) { + // Check for 'special' values + if (combination === COMBINATION_INFINITY) { + return string.join('') + 'Infinity'; + } + else if (combination === COMBINATION_NAN) { + return 'NaN'; + } + else { + biased_exponent = (high >> 15) & EXPONENT_MASK; + significand_msb = 0x08 + ((high >> 14) & 0x01); + } + } + else { + significand_msb = (high >> 14) & 0x07; + biased_exponent = (high >> 17) & EXPONENT_MASK; + } + // unbiased exponent + var exponent = biased_exponent - EXPONENT_BIAS; + // Create string of significand digits + // Convert the 114-bit binary number represented by + // (significand_high, significand_low) to at most 34 decimal + // digits through modulo and division. + significand128.parts[0] = (high & 0x3fff) + ((significand_msb & 0xf) << 14); + significand128.parts[1] = midh; + significand128.parts[2] = midl; + significand128.parts[3] = low; + if (significand128.parts[0] === 0 && + significand128.parts[1] === 0 && + significand128.parts[2] === 0 && + significand128.parts[3] === 0) { + is_zero = true; + } + else { + for (k = 3; k >= 0; k--) { + var least_digits = 0; + // Perform the divide + var result = divideu128(significand128); + significand128 = result.quotient; + least_digits = result.rem.low; + // We now have the 9 least significant digits (in base 2). + // Convert and output to string. + if (!least_digits) + continue; + for (j = 8; j >= 0; j--) { + // significand[k * 9 + j] = Math.round(least_digits % 10); + significand[k * 9 + j] = least_digits % 10; + // least_digits = Math.round(least_digits / 10); + least_digits = Math.floor(least_digits / 10); + } + } + } + // Output format options: + // Scientific - [-]d.dddE(+/-)dd or [-]dE(+/-)dd + // Regular - ddd.ddd + if (is_zero) { + significand_digits = 1; + significand[index] = 0; + } + else { + significand_digits = 36; + while (!significand[index]) { + significand_digits = significand_digits - 1; + index = index + 1; + } + } + // the exponent if scientific notation is used + var scientific_exponent = significand_digits - 1 + exponent; + // The scientific exponent checks are dictated by the string conversion + // specification and are somewhat arbitrary cutoffs. + // + // We must check exponent > 0, because if this is the case, the number + // has trailing zeros. However, we *cannot* output these trailing zeros, + // because doing so would change the precision of the value, and would + // change stored data if the string converted number is round tripped. + if (scientific_exponent >= 34 || scientific_exponent <= -7 || exponent > 0) { + // Scientific format + // if there are too many significant digits, we should just be treating numbers + // as + or - 0 and using the non-scientific exponent (this is for the "invalid + // representation should be treated as 0/-0" spec cases in decimal128-1.json) + if (significand_digits > 34) { + string.push("".concat(0)); + if (exponent > 0) + string.push("E+".concat(exponent)); + else if (exponent < 0) + string.push("E".concat(exponent)); + return string.join(''); + } + string.push("".concat(significand[index++])); + significand_digits = significand_digits - 1; + if (significand_digits) { + string.push('.'); + } + for (var i = 0; i < significand_digits; i++) { + string.push("".concat(significand[index++])); + } + // Exponent + string.push('E'); + if (scientific_exponent > 0) { + string.push("+".concat(scientific_exponent)); + } + else { + string.push("".concat(scientific_exponent)); + } + } + else { + // Regular format with no decimal place + if (exponent >= 0) { + for (var i = 0; i < significand_digits; i++) { + string.push("".concat(significand[index++])); + } + } + else { + var radix_position = significand_digits + exponent; + // non-zero digits before radix + if (radix_position > 0) { + for (var i = 0; i < radix_position; i++) { + string.push("".concat(significand[index++])); + } + } + else { + string.push('0'); + } + string.push('.'); + // add leading zeros after radix + while (radix_position++ < 0) { + string.push('0'); + } + for (var i = 0; i < significand_digits - Math.max(radix_position - 1, 0); i++) { + string.push("".concat(significand[index++])); + } + } + } + return string.join(''); + }; + Decimal128.prototype.toJSON = function () { + return { $numberDecimal: this.toString() }; + }; + /** @internal */ + Decimal128.prototype.toExtendedJSON = function () { + return { $numberDecimal: this.toString() }; + }; + /** @internal */ + Decimal128.fromExtendedJSON = function (doc) { + return Decimal128.fromString(doc.$numberDecimal); + }; + /** @internal */ + Decimal128.prototype[Symbol.for('nodejs.util.inspect.custom')] = function () { + return this.inspect(); + }; + Decimal128.prototype.inspect = function () { + return "new Decimal128(\"".concat(this.toString(), "\")"); + }; + return Decimal128; +}()); +exports.Decimal128 = Decimal128; +Object.defineProperty(Decimal128.prototype, '_bsontype', { value: 'Decimal128' }); +//# sourceMappingURL=decimal128.js.map \ No newline at end of file diff --git a/ts-ticket-office-service/node_modules/bson/lib/decimal128.js.map b/ts-ticket-office-service/node_modules/bson/lib/decimal128.js.map new file mode 100644 index 000000000..31f0ee87d --- /dev/null +++ b/ts-ticket-office-service/node_modules/bson/lib/decimal128.js.map @@ -0,0 +1 @@ +{"version":3,"file":"decimal128.js","sourceRoot":"","sources":["../src/decimal128.ts"],"names":[],"mappings":";;;AAAA,iCAAgC;AAChC,iCAAwC;AACxC,+BAA8B;AAC9B,wCAA8C;AAE9C,IAAM,mBAAmB,GAAG,+CAA+C,CAAC;AAC5E,IAAM,gBAAgB,GAAG,0BAA0B,CAAC;AACpD,IAAM,gBAAgB,GAAG,eAAe,CAAC;AAEzC,IAAM,YAAY,GAAG,IAAI,CAAC;AAC1B,IAAM,YAAY,GAAG,CAAC,IAAI,CAAC;AAC3B,IAAM,aAAa,GAAG,IAAI,CAAC;AAC3B,IAAM,UAAU,GAAG,EAAE,CAAC;AAEtB,yDAAyD;AACzD,IAAM,UAAU,GAAG;IACjB,IAAI,EAAE,IAAI,EAAE,IAAI,EAAE,IAAI,EAAE,IAAI,EAAE,IAAI,EAAE,IAAI,EAAE,IAAI,EAAE,IAAI,EAAE,IAAI,EAAE,IAAI,EAAE,IAAI,EAAE,IAAI,EAAE,IAAI,EAAE,IAAI,EAAE,IAAI;CAC/F,CAAC,OAAO,EAAE,CAAC;AACZ,2DAA2D;AAC3D,IAAM,mBAAmB,GAAG;IAC1B,IAAI,EAAE,IAAI,EAAE,IAAI,EAAE,IAAI,EAAE,IAAI,EAAE,IAAI,EAAE,IAAI,EAAE,IAAI,EAAE,IAAI,EAAE,IAAI,EAAE,IAAI,EAAE,IAAI,EAAE,IAAI,EAAE,IAAI,EAAE,IAAI,EAAE,IAAI;CAC/F,CAAC,OAAO,E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AAC,cAAc,CAAC,UAAU,CAAC,SAAS,EAAE,WAAW,EAAE,EAAE,KAAK,EAAE,YAAY,EAAE,CAAC,CAAC"} \ No newline at end of file diff --git a/ts-ticket-office-service/node_modules/bson/lib/double.js b/ts-ticket-office-service/node_modules/bson/lib/double.js new file mode 100644 index 000000000..39c488f32 --- /dev/null +++ b/ts-ticket-office-service/node_modules/bson/lib/double.js @@ -0,0 +1,76 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.Double = void 0; +/** + * A class representation of the BSON Double type. + * @public + * @category BSONType + */ +var Double = /** @class */ (function () { + /** + * Create a Double type + * + * @param value - the number we want to represent as a double. + */ + function Double(value) { + if (!(this instanceof Double)) + return new Double(value); + if (value instanceof Number) { + value = value.valueOf(); + } + this.value = +value; + } + /** + * Access the number value. + * + * @returns returns the wrapped double number. + */ + Double.prototype.valueOf = function () { + return this.value; + }; + Double.prototype.toJSON = function () { + return this.value; + }; + Double.prototype.toString = function (radix) { + return this.value.toString(radix); + }; + /** @internal */ + Double.prototype.toExtendedJSON = function (options) { + if (options && (options.legacy || (options.relaxed && isFinite(this.value)))) { + return this.value; + } + // NOTE: JavaScript has +0 and -0, apparently to model limit calculations. If a user + // explicitly provided `-0` then we need to ensure the sign makes it into the output + if (Object.is(Math.sign(this.value), -0)) { + return { $numberDouble: "-".concat(this.value.toFixed(1)) }; + } + var $numberDouble; + if (Number.isInteger(this.value)) { + $numberDouble = this.value.toFixed(1); + if ($numberDouble.length >= 13) { + $numberDouble = this.value.toExponential(13).toUpperCase(); + } + } + else { + $numberDouble = this.value.toString(); + } + return { $numberDouble: $numberDouble }; + }; + /** @internal */ + Double.fromExtendedJSON = function (doc, options) { + var doubleValue = parseFloat(doc.$numberDouble); + return options && options.relaxed ? doubleValue : new Double(doubleValue); + }; + /** @internal */ + Double.prototype[Symbol.for('nodejs.util.inspect.custom')] = function () { + return this.inspect(); + }; + Double.prototype.inspect = function () { + var eJSON = this.toExtendedJSON(); + return "new Double(".concat(eJSON.$numberDouble, ")"); + }; + return Double; +}()); +exports.Double = Double; +Object.defineProperty(Double.prototype, '_bsontype', { value: 'Double' }); +//# sourceMappingURL=double.js.map \ No newline at end of file diff --git a/ts-ticket-office-service/node_modules/bson/lib/double.js.map b/ts-ticket-office-service/node_modules/bson/lib/double.js.map new file mode 100644 index 000000000..31201e109 --- /dev/null +++ b/ts-ticket-office-service/node_modules/bson/lib/double.js.map @@ -0,0 +1 @@ +{"version":3,"file":"double.js","sourceRoot":"","sources":["../src/double.ts"],"names":[],"mappings":";;;AAOA;;;;GAIG;AACH;IAIE;;;;OAIG;IACH,gBAAY,KAAa;QACvB,IAAI,CAAC,CAAC,IAAI,YAAY,MAAM,CAAC;YAAE,OAAO,IAAI,MAAM,CAAC,KAAK,CAAC,CAAC;QAExD,IAAK,KAAiB,YAAY,MAAM,EAAE;YACxC,KAAK,GAAG,KAAK,CAAC,OAAO,EAAE,CAAC;SACzB;QAED,IAAI,CAAC,KAAK,GAAG,CAAC,KAAK,CAAC;IACtB,CAAC;IAED;;;;OAIG;IACH,wBAAO,GAAP;QACE,OAAO,IAAI,CAAC,KAAK,CAAC;IACpB,CAAC;IAED,uBAAM,GAAN;QACE,OAAO,IAAI,CAAC,KAAK,CAAC;IACpB,CAAC;IAED,yBAAQ,GAAR,UAAS,KAAc;QACrB,OAAO,IAAI,CAAC,KAAK,CAAC,QAAQ,CAAC,KAAK,CAAC,CAAC;IACpC,CAAC;IAED,gBAAgB;IAChB,+BAAc,GAAd,UAAe,OAAsB;QACnC,IAAI,OAAO,IAAI,CAAC,OAAO,CAAC,MAAM,IAAI,CAAC,OAAO,CAAC,OAAO,IAAI,QAAQ,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC,CAAC,EAAE;YAC5E,OAAO,IAAI,CAAC,KAAK,CAAC;SACnB;QAED,oFAAoF;QACpF,oFAAoF;QACpF,IAAI,MAAM,CAAC,EAAE,CAAC,IAAI,CAAC,IAAI,CAAC,IAAI,CAAC,KAA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AAE,EAAE,KAAK,EAAE,QAAQ,EAAE,CAAC,CAAC"} \ No newline at end of file diff --git a/ts-ticket-office-service/node_modules/bson/lib/ensure_buffer.js b/ts-ticket-office-service/node_modules/bson/lib/ensure_buffer.js new file mode 100644 index 000000000..d8298ea4a --- /dev/null +++ b/ts-ticket-office-service/node_modules/bson/lib/ensure_buffer.js @@ -0,0 +1,25 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.ensureBuffer = void 0; +var buffer_1 = require("buffer"); +var error_1 = require("./error"); +var utils_1 = require("./parser/utils"); +/** + * Makes sure that, if a Uint8Array is passed in, it is wrapped in a Buffer. + * + * @param potentialBuffer - The potential buffer + * @returns Buffer the input if potentialBuffer is a buffer, or a buffer that + * wraps a passed in Uint8Array + * @throws BSONTypeError If anything other than a Buffer or Uint8Array is passed in + */ +function ensureBuffer(potentialBuffer) { + if (ArrayBuffer.isView(potentialBuffer)) { + return buffer_1.Buffer.from(potentialBuffer.buffer, potentialBuffer.byteOffset, potentialBuffer.byteLength); + } + if ((0, utils_1.isAnyArrayBuffer)(potentialBuffer)) { + return buffer_1.Buffer.from(potentialBuffer); + } + throw new error_1.BSONTypeError('Must use either Buffer or TypedArray'); +} +exports.ensureBuffer = ensureBuffer; +//# sourceMappingURL=ensure_buffer.js.map \ No newline at end of file diff --git a/ts-ticket-office-service/node_modules/bson/lib/ensure_buffer.js.map b/ts-ticket-office-service/node_modules/bson/lib/ensure_buffer.js.map new file mode 100644 index 000000000..f39d86a6c --- /dev/null +++ b/ts-ticket-office-service/node_modules/bson/lib/ensure_buffer.js.map @@ -0,0 +1 @@ +{"version":3,"file":"ensure_buffer.js","sourceRoot":"","sources":["../src/ensure_buffer.ts"],"names":[],"mappings":";;;AAAA,iCAAgC;AAChC,iCAAwC;AACxC,wCAAkD;AAElD;;;;;;;GAOG;AACH,SAAgB,YAAY,CAAC,eAAuD;IAClF,IAAI,WAAW,CAAC,MAAM,CAAC,eAAe,CAAC,EAAE;QACvC,OAAO,eAAM,CAAC,IAAI,CAChB,eAAe,CAAC,MAAM,EACtB,eAAe,CAAC,UAAU,EAC1B,eAAe,CAAC,UAAU,CAC3B,CAAC;KACH;IAED,IAAI,IAAA,wBAAgB,EAAC,eAAe,CAAC,EAAE;QACrC,OAAO,eAAM,CAAC,IAAI,CAAC,eAAe,CAAC,CAAC;KACrC;IAED,MAAM,IAAI,qBAAa,CAAC,sCAAsC,CAAC,CAAC;AAClE,CAAC;AAdD,oCAcC"} \ No newline at end of file diff --git a/ts-ticket-office-service/node_modules/bson/lib/error.js b/ts-ticket-office-service/node_modules/bson/lib/error.js new file mode 100644 index 000000000..035ce86f1 --- /dev/null +++ b/ts-ticket-office-service/node_modules/bson/lib/error.js @@ -0,0 +1,55 @@ +"use strict"; +var __extends = (this && this.__extends) || (function () { + var extendStatics = function (d, b) { + extendStatics = Object.setPrototypeOf || + ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || + function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; }; + return extendStatics(d, b); + }; + return function (d, b) { + if (typeof b !== "function" && b !== null) + throw new TypeError("Class extends value " + String(b) + " is not a constructor or null"); + extendStatics(d, b); + function __() { this.constructor = d; } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); + }; +})(); +Object.defineProperty(exports, "__esModule", { value: true }); +exports.BSONTypeError = exports.BSONError = void 0; +/** @public */ +var BSONError = /** @class */ (function (_super) { + __extends(BSONError, _super); + function BSONError(message) { + var _this = _super.call(this, message) || this; + Object.setPrototypeOf(_this, BSONError.prototype); + return _this; + } + Object.defineProperty(BSONError.prototype, "name", { + get: function () { + return 'BSONError'; + }, + enumerable: false, + configurable: true + }); + return BSONError; +}(Error)); +exports.BSONError = BSONError; +/** @public */ +var BSONTypeError = /** @class */ (function (_super) { + __extends(BSONTypeError, _super); + function BSONTypeError(message) { + var _this = _super.call(this, message) || this; + Object.setPrototypeOf(_this, BSONTypeError.prototype); + return _this; + } + Object.defineProperty(BSONTypeError.prototype, "name", { + get: function () { + return 'BSONTypeError'; + }, + enumerable: false, + configurable: true + }); + return BSONTypeError; +}(TypeError)); +exports.BSONTypeError = BSONTypeError; +//# sourceMappingURL=error.js.map \ No newline at end of file diff --git a/ts-ticket-office-service/node_modules/bson/lib/error.js.map b/ts-ticket-office-service/node_modules/bson/lib/error.js.map new file mode 100644 index 000000000..2acd4ef3f --- /dev/null +++ b/ts-ticket-office-service/node_modules/bson/lib/error.js.map @@ -0,0 +1 @@ +{"version":3,"file":"error.js","sourceRoot":"","sources":["../src/error.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;AAAA,cAAc;AACd;IAA+B,6BAAK;IAClC,mBAAY,OAAe;QAA3B,YACE,kBAAM,OAAO,CAAC,SAEf;QADC,MAAM,CAAC,cAAc,CAAC,KAAI,EAAE,SAAS,CAAC,SAAS,CAAC,CAAC;;IACnD,CAAC;IAED,sBAAI,2BAAI;aAAR;YACE,OAAO,WAAW,CAAC;QACrB,CAAC;;;OAAA;IACH,gBAAC;AAAD,CAAC,AATD,CAA+B,KAAK,GASnC;AATY,8BAAS;AAWtB,cAAc;AACd;IAAmC,iCAAS;IAC1C,uBAAY,OAAe;QAA3B,YACE,kBAAM,OAAO,CAAC,SAEf;QADC,MAAM,CAAC,cAAc,CAAC,KAAI,EAAE,aAAa,CAAC,SAAS,CAAC,CAAC;;IACvD,CAAC;IAED,sBAAI,+BAAI;aAAR;YACE,OAAO,eAAe,CAAC;QACzB,CAAC;;;OAAA;IACH,oBAAC;AAAD,CAAC,AATD,CAAmC,SAAS,GAS3C;AATY,sCAAa"} \ No newline at end of file diff --git a/ts-ticket-office-service/node_modules/bson/lib/extended_json.js b/ts-ticket-office-service/node_modules/bson/lib/extended_json.js new file mode 100644 index 000000000..980e4db74 --- /dev/null +++ b/ts-ticket-office-service/node_modules/bson/lib/extended_json.js @@ -0,0 +1,390 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.EJSON = exports.isBSONType = void 0; +var binary_1 = require("./binary"); +var code_1 = require("./code"); +var db_ref_1 = require("./db_ref"); +var decimal128_1 = require("./decimal128"); +var double_1 = require("./double"); +var error_1 = require("./error"); +var int_32_1 = require("./int_32"); +var long_1 = require("./long"); +var max_key_1 = require("./max_key"); +var min_key_1 = require("./min_key"); +var objectid_1 = require("./objectid"); +var utils_1 = require("./parser/utils"); +var regexp_1 = require("./regexp"); +var symbol_1 = require("./symbol"); +var timestamp_1 = require("./timestamp"); +function isBSONType(value) { + return ((0, utils_1.isObjectLike)(value) && Reflect.has(value, '_bsontype') && typeof value._bsontype === 'string'); +} +exports.isBSONType = isBSONType; +// INT32 boundaries +var BSON_INT32_MAX = 0x7fffffff; +var BSON_INT32_MIN = -0x80000000; +// INT64 boundaries +// const BSON_INT64_MAX = 0x7fffffffffffffff; // TODO(NODE-4377): This number cannot be precisely represented in JS +var BSON_INT64_MAX = 0x8000000000000000; +var BSON_INT64_MIN = -0x8000000000000000; +// all the types where we don't need to do any special processing and can just pass the EJSON +//straight to type.fromExtendedJSON +var keysToCodecs = { + $oid: objectid_1.ObjectId, + $binary: binary_1.Binary, + $uuid: binary_1.Binary, + $symbol: symbol_1.BSONSymbol, + $numberInt: int_32_1.Int32, + $numberDecimal: decimal128_1.Decimal128, + $numberDouble: double_1.Double, + $numberLong: long_1.Long, + $minKey: min_key_1.MinKey, + $maxKey: max_key_1.MaxKey, + $regex: regexp_1.BSONRegExp, + $regularExpression: regexp_1.BSONRegExp, + $timestamp: timestamp_1.Timestamp +}; +// eslint-disable-next-line @typescript-eslint/no-explicit-any +function deserializeValue(value, options) { + if (options === void 0) { options = {}; } + if (typeof value === 'number') { + if (options.relaxed || options.legacy) { + return value; + } + // if it's an integer, should interpret as smallest BSON integer + // that can represent it exactly. (if out of range, interpret as double.) + if (Math.floor(value) === value) { + if (value >= BSON_INT32_MIN && value <= BSON_INT32_MAX) + return new int_32_1.Int32(value); + if (value >= BSON_INT64_MIN && value <= BSON_INT64_MAX) + return long_1.Long.fromNumber(value); + } + // If the number is a non-integer or out of integer range, should interpret as BSON Double. + return new double_1.Double(value); + } + // from here on out we're looking for bson types, so bail if its not an object + if (value == null || typeof value !== 'object') + return value; + // upgrade deprecated undefined to null + if (value.$undefined) + return null; + var keys = Object.keys(value).filter(function (k) { return k.startsWith('$') && value[k] != null; }); + for (var i = 0; i < keys.length; i++) { + var c = keysToCodecs[keys[i]]; + if (c) + return c.fromExtendedJSON(value, options); + } + if (value.$date != null) { + var d = value.$date; + var date = new Date(); + if (options.legacy) { + if (typeof d === 'number') + date.setTime(d); + else if (typeof d === 'string') + date.setTime(Date.parse(d)); + } + else { + if (typeof d === 'string') + date.setTime(Date.parse(d)); + else if (long_1.Long.isLong(d)) + date.setTime(d.toNumber()); + else if (typeof d === 'number' && options.relaxed) + date.setTime(d); + } + return date; + } + if (value.$code != null) { + var copy = Object.assign({}, value); + if (value.$scope) { + copy.$scope = deserializeValue(value.$scope); + } + return code_1.Code.fromExtendedJSON(value); + } + if ((0, db_ref_1.isDBRefLike)(value) || value.$dbPointer) { + var v = value.$ref ? value : value.$dbPointer; + // we run into this in a "degenerate EJSON" case (with $id and $ref order flipped) + // because of the order JSON.parse goes through the document + if (v instanceof db_ref_1.DBRef) + return v; + var dollarKeys = Object.keys(v).filter(function (k) { return k.startsWith('$'); }); + var valid_1 = true; + dollarKeys.forEach(function (k) { + if (['$ref', '$id', '$db'].indexOf(k) === -1) + valid_1 = false; + }); + // only make DBRef if $ keys are all valid + if (valid_1) + return db_ref_1.DBRef.fromExtendedJSON(v); + } + return value; +} +// eslint-disable-next-line @typescript-eslint/no-explicit-any +function serializeArray(array, options) { + return array.map(function (v, index) { + options.seenObjects.push({ propertyName: "index ".concat(index), obj: null }); + try { + return serializeValue(v, options); + } + finally { + options.seenObjects.pop(); + } + }); +} +function getISOString(date) { + var isoStr = date.toISOString(); + // we should only show milliseconds in timestamp if they're non-zero + return date.getUTCMilliseconds() !== 0 ? isoStr : isoStr.slice(0, -5) + 'Z'; +} +// eslint-disable-next-line @typescript-eslint/no-explicit-any +function serializeValue(value, options) { + if ((typeof value === 'object' || typeof value === 'function') && value !== null) { + var index = options.seenObjects.findIndex(function (entry) { return entry.obj === value; }); + if (index !== -1) { + var props = options.seenObjects.map(function (entry) { return entry.propertyName; }); + var leadingPart = props + .slice(0, index) + .map(function (prop) { return "".concat(prop, " -> "); }) + .join(''); + var alreadySeen = props[index]; + var circularPart = ' -> ' + + props + .slice(index + 1, props.length - 1) + .map(function (prop) { return "".concat(prop, " -> "); }) + .join(''); + var current = props[props.length - 1]; + var leadingSpace = ' '.repeat(leadingPart.length + alreadySeen.length / 2); + var dashes = '-'.repeat(circularPart.length + (alreadySeen.length + current.length) / 2 - 1); + throw new error_1.BSONTypeError('Converting circular structure to EJSON:\n' + + " ".concat(leadingPart).concat(alreadySeen).concat(circularPart).concat(current, "\n") + + " ".concat(leadingSpace, "\\").concat(dashes, "/")); + } + options.seenObjects[options.seenObjects.length - 1].obj = value; + } + if (Array.isArray(value)) + return serializeArray(value, options); + if (value === undefined) + return null; + if (value instanceof Date || (0, utils_1.isDate)(value)) { + var dateNum = value.getTime(), + // is it in year range 1970-9999? + inRange = dateNum > -1 && dateNum < 253402318800000; + if (options.legacy) { + return options.relaxed && inRange + ? { $date: value.getTime() } + : { $date: getISOString(value) }; + } + return options.relaxed && inRange + ? { $date: getISOString(value) } + : { $date: { $numberLong: value.getTime().toString() } }; + } + if (typeof value === 'number' && (!options.relaxed || !isFinite(value))) { + // it's an integer + if (Math.floor(value) === value) { + var int32Range = value >= BSON_INT32_MIN && value <= BSON_INT32_MAX, int64Range = value >= BSON_INT64_MIN && value <= BSON_INT64_MAX; + // interpret as being of the smallest BSON integer type that can represent the number exactly + if (int32Range) + return { $numberInt: value.toString() }; + if (int64Range) + return { $numberLong: value.toString() }; + } + return { $numberDouble: value.toString() }; + } + if (value instanceof RegExp || (0, utils_1.isRegExp)(value)) { + var flags = value.flags; + if (flags === undefined) { + var match = value.toString().match(/[gimuy]*$/); + if (match) { + flags = match[0]; + } + } + var rx = new regexp_1.BSONRegExp(value.source, flags); + return rx.toExtendedJSON(options); + } + if (value != null && typeof value === 'object') + return serializeDocument(value, options); + return value; +} +var BSON_TYPE_MAPPINGS = { + Binary: function (o) { return new binary_1.Binary(o.value(), o.sub_type); }, + Code: function (o) { return new code_1.Code(o.code, o.scope); }, + DBRef: function (o) { return new db_ref_1.DBRef(o.collection || o.namespace, o.oid, o.db, o.fields); }, + Decimal128: function (o) { return new decimal128_1.Decimal128(o.bytes); }, + Double: function (o) { return new double_1.Double(o.value); }, + Int32: function (o) { return new int_32_1.Int32(o.value); }, + Long: function (o) { + return long_1.Long.fromBits( + // underscore variants for 1.x backwards compatibility + o.low != null ? o.low : o.low_, o.low != null ? o.high : o.high_, o.low != null ? o.unsigned : o.unsigned_); + }, + MaxKey: function () { return new max_key_1.MaxKey(); }, + MinKey: function () { return new min_key_1.MinKey(); }, + ObjectID: function (o) { return new objectid_1.ObjectId(o); }, + ObjectId: function (o) { return new objectid_1.ObjectId(o); }, + BSONRegExp: function (o) { return new regexp_1.BSONRegExp(o.pattern, o.options); }, + Symbol: function (o) { return new symbol_1.BSONSymbol(o.value); }, + Timestamp: function (o) { return timestamp_1.Timestamp.fromBits(o.low, o.high); } +}; +// eslint-disable-next-line @typescript-eslint/no-explicit-any +function serializeDocument(doc, options) { + if (doc == null || typeof doc !== 'object') + throw new error_1.BSONError('not an object instance'); + var bsontype = doc._bsontype; + if (typeof bsontype === 'undefined') { + // It's a regular object. Recursively serialize its property values. + var _doc = {}; + for (var name in doc) { + options.seenObjects.push({ propertyName: name, obj: null }); + try { + var value = serializeValue(doc[name], options); + if (name === '__proto__') { + Object.defineProperty(_doc, name, { + value: value, + writable: true, + enumerable: true, + configurable: true + }); + } + else { + _doc[name] = value; + } + } + finally { + options.seenObjects.pop(); + } + } + return _doc; + } + else if (isBSONType(doc)) { + // the "document" is really just a BSON type object + // eslint-disable-next-line @typescript-eslint/no-explicit-any + var outDoc = doc; + if (typeof outDoc.toExtendedJSON !== 'function') { + // There's no EJSON serialization function on the object. It's probably an + // object created by a previous version of this library (or another library) + // that's duck-typing objects to look like they were generated by this library). + // Copy the object into this library's version of that type. + var mapper = BSON_TYPE_MAPPINGS[doc._bsontype]; + if (!mapper) { + throw new error_1.BSONTypeError('Unrecognized or invalid _bsontype: ' + doc._bsontype); + } + outDoc = mapper(outDoc); + } + // Two BSON types may have nested objects that may need to be serialized too + if (bsontype === 'Code' && outDoc.scope) { + outDoc = new code_1.Code(outDoc.code, serializeValue(outDoc.scope, options)); + } + else if (bsontype === 'DBRef' && outDoc.oid) { + outDoc = new db_ref_1.DBRef(serializeValue(outDoc.collection, options), serializeValue(outDoc.oid, options), serializeValue(outDoc.db, options), serializeValue(outDoc.fields, options)); + } + return outDoc.toExtendedJSON(options); + } + else { + throw new error_1.BSONError('_bsontype must be a string, but was: ' + typeof bsontype); + } +} +/** + * EJSON parse / stringify API + * @public + */ +// the namespace here is used to emulate `export * as EJSON from '...'` +// which as of now (sept 2020) api-extractor does not support +// eslint-disable-next-line @typescript-eslint/no-namespace +var EJSON; +(function (EJSON) { + /** + * Parse an Extended JSON string, constructing the JavaScript value or object described by that + * string. + * + * @example + * ```js + * const { EJSON } = require('bson'); + * const text = '{ "int32": { "$numberInt": "10" } }'; + * + * // prints { int32: { [String: '10'] _bsontype: 'Int32', value: '10' } } + * console.log(EJSON.parse(text, { relaxed: false })); + * + * // prints { int32: 10 } + * console.log(EJSON.parse(text)); + * ``` + */ + function parse(text, options) { + var finalOptions = Object.assign({}, { relaxed: true, legacy: false }, options); + // relaxed implies not strict + if (typeof finalOptions.relaxed === 'boolean') + finalOptions.strict = !finalOptions.relaxed; + if (typeof finalOptions.strict === 'boolean') + finalOptions.relaxed = !finalOptions.strict; + return JSON.parse(text, function (key, value) { + if (key.indexOf('\x00') !== -1) { + throw new error_1.BSONError("BSON Document field names cannot contain null bytes, found: ".concat(JSON.stringify(key))); + } + return deserializeValue(value, finalOptions); + }); + } + EJSON.parse = parse; + /** + * Converts a BSON document to an Extended JSON string, optionally replacing values if a replacer + * function is specified or optionally including only the specified properties if a replacer array + * is specified. + * + * @param value - The value to convert to extended JSON + * @param replacer - A function that alters the behavior of the stringification process, or an array of String and Number objects that serve as a whitelist for selecting/filtering the properties of the value object to be included in the JSON string. If this value is null or not provided, all properties of the object are included in the resulting JSON string + * @param space - A String or Number object that's used to insert white space into the output JSON string for readability purposes. + * @param options - Optional settings + * + * @example + * ```js + * const { EJSON } = require('bson'); + * const Int32 = require('mongodb').Int32; + * const doc = { int32: new Int32(10) }; + * + * // prints '{"int32":{"$numberInt":"10"}}' + * console.log(EJSON.stringify(doc, { relaxed: false })); + * + * // prints '{"int32":10}' + * console.log(EJSON.stringify(doc)); + * ``` + */ + function stringify(value, + // eslint-disable-next-line @typescript-eslint/no-explicit-any + replacer, space, options) { + if (space != null && typeof space === 'object') { + options = space; + space = 0; + } + if (replacer != null && typeof replacer === 'object' && !Array.isArray(replacer)) { + options = replacer; + replacer = undefined; + space = 0; + } + var serializeOptions = Object.assign({ relaxed: true, legacy: false }, options, { + seenObjects: [{ propertyName: '(root)', obj: null }] + }); + var doc = serializeValue(value, serializeOptions); + return JSON.stringify(doc, replacer, space); + } + EJSON.stringify = stringify; + /** + * Serializes an object to an Extended JSON string, and reparse it as a JavaScript object. + * + * @param value - The object to serialize + * @param options - Optional settings passed to the `stringify` function + */ + function serialize(value, options) { + options = options || {}; + return JSON.parse(stringify(value, options)); + } + EJSON.serialize = serialize; + /** + * Deserializes an Extended JSON object into a plain JavaScript object with native/BSON types + * + * @param ejson - The Extended JSON object to deserialize + * @param options - Optional settings passed to the parse method + */ + function deserialize(ejson, options) { + options = options || {}; + return parse(JSON.stringify(ejson), options); + } + EJSON.deserialize = deserialize; +})(EJSON = exports.EJSON || (exports.EJSON = {})); +//# sourceMappingURL=extended_json.js.map \ No newline at end of file diff --git a/ts-ticket-office-service/node_modules/bson/lib/extended_json.js.map b/ts-ticket-office-service/node_modules/bson/lib/extended_json.js.map new file mode 100644 index 000000000..d123c0ebb --- /dev/null +++ b/ts-ticket-office-service/node_modules/bson/lib/extended_json.js.map @@ -0,0 +1 @@ +{"version":3,"file":"extended_json.js","sourceRoot":"","sources":["../src/extended_json.ts"],"names":[],"mappings":";;;AAAA,mCAAkC;AAElC,+BAA8B;AAC9B,mCAA8C;AAC9C,2CAA0C;AAC1C,mCAAkC;AAClC,iCAAmD;AACnD,mCAAiC;AACjC,+BAA8B;AAC9B,qCAAmC;AACnC,qCAAmC;AACnC,uCAAsC;AACtC,wCAAgE;AAChE,mCAAsC;AACtC,mCAAsC;AACtC,yCAAwC;AAqBxC,SAAgB,UAAU,CAAC,KAAc;IACvC,OAAO,CACL,IAAA,oBAAY,EAAC,KAAK,CAAC,IAAI,OAAO,CAAC,GAAG,CAAC,KAAK,EAAE,WAAW,CAAC,IAAI,OAAO,KAAK,CAAC,SAAS,KAAK,QAAQ,CAC9F,CAAC;AACJ,CAAC;AAJD,gCAIC;AAED,mBAAmB;AACnB,IAAM,cAAc,GAAG,UAAU,CAAC;AAClC,IAAM,cAAc,GAAG,CAAC,UAAU,CAAC;AACnC,mBAAmB;AACnB,mHAAmH;AACnH,IAAM,cAAc,GAAG,kBAAkB,CAAC;AAC1C,IAAM,cAAc,GAAG,CAAC,kBAAkB,CAAC;AAE3C,6FAA6F;AAC7F,mCAAmC;AACnC,IAAM,YAAY,GAAG;IACnB,IAAI,EAAE,mBAAQ;IACd,OAAO,EAAE,eAAM;IACf,KAAK,EAAE,eAAM;IACb,OAAO,EAAE,mBAAU;IACnB,UAAU,EAAE,cAAK;IACjB,cAAc,EAAE,uBAAU;IAC1B,aAAa,EAAE,eAAM;IACrB,WAAW,EAAE,WAAI;IACjB,OAAO,EAAE,gBAAM;IACf,OAAO,EAAE,gBAAM;IACf,MAAM,EAAE,mBAAU;IAClB,kBAAkB,EAAE,mBAAU;IAC9B,UAAU,EAAE,qBAAS;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AK,CAAC,IAAI,CAAC,SAAS,CAAC,KAAK,CAAC,EAAE,OAAO,CAAC,CAAC;IAC/C,CAAC;IAHe,iBAAW,cAG1B,CAAA;AACH,CAAC,EArHgB,KAAK,GAAL,aAAK,KAAL,aAAK,QAqHrB"} \ No newline at end of file diff --git a/ts-ticket-office-service/node_modules/bson/lib/int_32.js b/ts-ticket-office-service/node_modules/bson/lib/int_32.js new file mode 100644 index 000000000..e862255df --- /dev/null +++ b/ts-ticket-office-service/node_modules/bson/lib/int_32.js @@ -0,0 +1,58 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.Int32 = void 0; +/** + * A class representation of a BSON Int32 type. + * @public + * @category BSONType + */ +var Int32 = /** @class */ (function () { + /** + * Create an Int32 type + * + * @param value - the number we want to represent as an int32. + */ + function Int32(value) { + if (!(this instanceof Int32)) + return new Int32(value); + if (value instanceof Number) { + value = value.valueOf(); + } + this.value = +value | 0; + } + /** + * Access the number value. + * + * @returns returns the wrapped int32 number. + */ + Int32.prototype.valueOf = function () { + return this.value; + }; + Int32.prototype.toString = function (radix) { + return this.value.toString(radix); + }; + Int32.prototype.toJSON = function () { + return this.value; + }; + /** @internal */ + Int32.prototype.toExtendedJSON = function (options) { + if (options && (options.relaxed || options.legacy)) + return this.value; + return { $numberInt: this.value.toString() }; + }; + /** @internal */ + Int32.fromExtendedJSON = function (doc, options) { + return options && options.relaxed ? parseInt(doc.$numberInt, 10) : new Int32(doc.$numberInt); + }; + /** @internal */ + Int32.prototype[Symbol.for('nodejs.util.inspect.custom')] = function () { + return this.inspect(); + }; + Int32.prototype.inspect = function () { + return "new Int32(".concat(this.valueOf(), ")"); + }; + return Int32; +}()); +exports.Int32 = Int32; +Object.defineProperty(Int32.prototype, '_bsontype', { value: 'Int32' }); +//# sourceMappingURL=int_32.js.map \ No newline at end of file diff --git a/ts-ticket-office-service/node_modules/bson/lib/int_32.js.map b/ts-ticket-office-service/node_modules/bson/lib/int_32.js.map new file mode 100644 index 000000000..f55ab8596 --- /dev/null +++ b/ts-ticket-office-service/node_modules/bson/lib/int_32.js.map @@ -0,0 +1 @@ +{"version":3,"file":"int_32.js","sourceRoot":"","sources":["../src/int_32.ts"],"names":[],"mappings":";;;AAOA;;;;GAIG;AACH;IAIE;;;;OAIG;IACH,eAAY,KAAsB;QAChC,IAAI,CAAC,CAAC,IAAI,YAAY,KAAK,CAAC;YAAE,OAAO,IAAI,KAAK,CAAC,KAAK,CAAC,CAAC;QAEtD,IAAK,KAAiB,YAAY,MAAM,EAAE;YACxC,KAAK,GAAG,KAAK,CAAC,OAAO,EAAE,CAAC;SACzB;QAED,IAAI,CAAC,KAAK,GAAG,CAAC,KAAK,GAAG,CAAC,CAAC;IAC1B,CAAC;IAED;;;;OAIG;IACH,uBAAO,GAAP;QACE,OAAO,IAAI,CAAC,KAAK,CAAC;IACpB,CAAC;IAED,wBAAQ,GAAR,UAAS,KAAc;QACrB,OAAO,IAAI,CAAC,KAAK,CAAC,QAAQ,CAAC,KAAK,CAAC,CAAC;IACpC,CAAC;IAED,sBAAM,GAAN;QACE,OAAO,IAAI,CAAC,KAAK,CAAC;IACpB,CAAC;IAED,gBAAgB;IAChB,8BAAc,GAAd,UAAe,OAAsB;QACnC,IAAI,OAAO,IAAI,CAAC,OAAO,CAAC,OAAO,IAAI,OAAO,CAAC,MAAM,CAAC;YAAE,OAAO,IAAI,CAAC,KAAK,CAAC;QACtE,OAAO,EAAE,UAAU,EAAE,IAAI,CAAC,KAAK,CAAC,QAAQ,EAAE,EAAE,CAAC;IAC/C,CAAC;IAED,gBAAgB;IACT,sBAAgB,GAAvB,UAAwB,GAAkB,EAAE,OAAsB;QAChE,OAAO,OAAO,IAAI,OAAO,CAAC,OAAO,CAAC,CAAC,CAAC,QAAQ,CAAC,GAAG,CAAC,UAAU,EAAE,EAAE,CAAC,CAAC,CAAC,CAAC,IAAI,KAAK,CAAC,GAAG,CAAC,UAAU,CAAC,CAAC;IAC/F,CAAC;IAED,gBAAgB;IAChB,gBAAC,MAAM,CAAC,GAAG,CAAC,4BAA4B,CAAC,CAAC,GAA1C;QACE,OAAO,IAAI,CAAC,OAAO,EAAE,CAAC;IACxB,CAAC;IAED,uBAAO,GAAP;QACE,OAAO,oBAAa,IAAI,CAAC,OAAO,EAAE,MAAG,CAAC;IACxC,CAAC;IACH,YAAC;AAAD,CAAC,AAvDD,IAuDC;AAvDY,sBAAK;AAyDlB,MAAM,CAAC,cAAc,CAAC,KAAK,CAAC,SAAS,EAAE,WAAW,EAAE,EAAE,KAAK,EAAE,OAAO,EAAE,CAAC,CAAC"} \ No newline at end of file diff --git a/ts-ticket-office-service/node_modules/bson/lib/long.js b/ts-ticket-office-service/node_modules/bson/lib/long.js new file mode 100644 index 000000000..ec7aaec56 --- /dev/null +++ b/ts-ticket-office-service/node_modules/bson/lib/long.js @@ -0,0 +1,900 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.Long = void 0; +var utils_1 = require("./parser/utils"); +/** + * wasm optimizations, to do native i64 multiplication and divide + */ +var wasm = undefined; +try { + wasm = new WebAssembly.Instance(new WebAssembly.Module( + // prettier-ignore + new Uint8Array([0, 97, 115, 109, 1, 0, 0, 0, 1, 13, 2, 96, 0, 1, 127, 96, 4, 127, 127, 127, 127, 1, 127, 3, 7, 6, 0, 1, 1, 1, 1, 1, 6, 6, 1, 127, 1, 65, 0, 11, 7, 50, 6, 3, 109, 117, 108, 0, 1, 5, 100, 105, 118, 95, 115, 0, 2, 5, 100, 105, 118, 95, 117, 0, 3, 5, 114, 101, 109, 95, 115, 0, 4, 5, 114, 101, 109, 95, 117, 0, 5, 8, 103, 101, 116, 95, 104, 105, 103, 104, 0, 0, 10, 191, 1, 6, 4, 0, 35, 0, 11, 36, 1, 1, 126, 32, 0, 173, 32, 1, 173, 66, 32, 134, 132, 32, 2, 173, 32, 3, 173, 66, 32, 134, 132, 126, 34, 4, 66, 32, 135, 167, 36, 0, 32, 4, 167, 11, 36, 1, 1, 126, 32, 0, 173, 32, 1, 173, 66, 32, 134, 132, 32, 2, 173, 32, 3, 173, 66, 32, 134, 132, 127, 34, 4, 66, 32, 135, 167, 36, 0, 32, 4, 167, 11, 36, 1, 1, 126, 32, 0, 173, 32, 1, 173, 66, 32, 134, 132, 32, 2, 173, 32, 3, 173, 66, 32, 134, 132, 128, 34, 4, 66, 32, 135, 167, 36, 0, 32, 4, 167, 11, 36, 1, 1, 126, 32, 0, 173, 32, 1, 173, 66, 32, 134, 132, 32, 2, 173, 32, 3, 173, 66, 32, 134, 132, 129, 34, 4, 66, 32, 135, 167, 36, 0, 32, 4, 167, 11, 36, 1, 1, 126, 32, 0, 173, 32, 1, 173, 66, 32, 134, 132, 32, 2, 173, 32, 3, 173, 66, 32, 134, 132, 130, 34, 4, 66, 32, 135, 167, 36, 0, 32, 4, 167, 11])), {}).exports; +} +catch (_a) { + // no wasm support +} +var TWO_PWR_16_DBL = 1 << 16; +var TWO_PWR_24_DBL = 1 << 24; +var TWO_PWR_32_DBL = TWO_PWR_16_DBL * TWO_PWR_16_DBL; +var TWO_PWR_64_DBL = TWO_PWR_32_DBL * TWO_PWR_32_DBL; +var TWO_PWR_63_DBL = TWO_PWR_64_DBL / 2; +/** A cache of the Long representations of small integer values. */ +var INT_CACHE = {}; +/** A cache of the Long representations of small unsigned integer values. */ +var UINT_CACHE = {}; +/** + * A class representing a 64-bit integer + * @public + * @category BSONType + * @remarks + * The internal representation of a long is the two given signed, 32-bit values. + * We use 32-bit pieces because these are the size of integers on which + * Javascript performs bit-operations. For operations like addition and + * multiplication, we split each number into 16 bit pieces, which can easily be + * multiplied within Javascript's floating-point representation without overflow + * or change in sign. + * In the algorithms below, we frequently reduce the negative case to the + * positive case by negating the input(s) and then post-processing the result. + * Note that we must ALWAYS check specially whether those values are MIN_VALUE + * (-2^63) because -MIN_VALUE == MIN_VALUE (since 2^63 cannot be represented as + * a positive number, it overflows back into a negative). Not handling this + * case would often result in infinite recursion. + * Common constant values ZERO, ONE, NEG_ONE, etc. are found as static properties on this class. + */ +var Long = /** @class */ (function () { + /** + * Constructs a 64 bit two's-complement integer, given its low and high 32 bit values as *signed* integers. + * See the from* functions below for more convenient ways of constructing Longs. + * + * Acceptable signatures are: + * - Long(low, high, unsigned?) + * - Long(bigint, unsigned?) + * - Long(string, unsigned?) + * + * @param low - The low (signed) 32 bits of the long + * @param high - The high (signed) 32 bits of the long + * @param unsigned - Whether unsigned or not, defaults to signed + */ + function Long(low, high, unsigned) { + if (low === void 0) { low = 0; } + if (!(this instanceof Long)) + return new Long(low, high, unsigned); + if (typeof low === 'bigint') { + Object.assign(this, Long.fromBigInt(low, !!high)); + } + else if (typeof low === 'string') { + Object.assign(this, Long.fromString(low, !!high)); + } + else { + this.low = low | 0; + this.high = high | 0; + this.unsigned = !!unsigned; + } + Object.defineProperty(this, '__isLong__', { + value: true, + configurable: false, + writable: false, + enumerable: false + }); + } + /** + * Returns a Long representing the 64 bit integer that comes by concatenating the given low and high bits. + * Each is assumed to use 32 bits. + * @param lowBits - The low 32 bits + * @param highBits - The high 32 bits + * @param unsigned - Whether unsigned or not, defaults to signed + * @returns The corresponding Long value + */ + Long.fromBits = function (lowBits, highBits, unsigned) { + return new Long(lowBits, highBits, unsigned); + }; + /** + * Returns a Long representing the given 32 bit integer value. + * @param value - The 32 bit integer in question + * @param unsigned - Whether unsigned or not, defaults to signed + * @returns The corresponding Long value + */ + Long.fromInt = function (value, unsigned) { + var obj, cachedObj, cache; + if (unsigned) { + value >>>= 0; + if ((cache = 0 <= value && value < 256)) { + cachedObj = UINT_CACHE[value]; + if (cachedObj) + return cachedObj; + } + obj = Long.fromBits(value, (value | 0) < 0 ? -1 : 0, true); + if (cache) + UINT_CACHE[value] = obj; + return obj; + } + else { + value |= 0; + if ((cache = -128 <= value && value < 128)) { + cachedObj = INT_CACHE[value]; + if (cachedObj) + return cachedObj; + } + obj = Long.fromBits(value, value < 0 ? -1 : 0, false); + if (cache) + INT_CACHE[value] = obj; + return obj; + } + }; + /** + * Returns a Long representing the given value, provided that it is a finite number. Otherwise, zero is returned. + * @param value - The number in question + * @param unsigned - Whether unsigned or not, defaults to signed + * @returns The corresponding Long value + */ + Long.fromNumber = function (value, unsigned) { + if (isNaN(value)) + return unsigned ? Long.UZERO : Long.ZERO; + if (unsigned) { + if (value < 0) + return Long.UZERO; + if (value >= TWO_PWR_64_DBL) + return Long.MAX_UNSIGNED_VALUE; + } + else { + if (value <= -TWO_PWR_63_DBL) + return Long.MIN_VALUE; + if (value + 1 >= TWO_PWR_63_DBL) + return Long.MAX_VALUE; + } + if (value < 0) + return Long.fromNumber(-value, unsigned).neg(); + return Long.fromBits(value % TWO_PWR_32_DBL | 0, (value / TWO_PWR_32_DBL) | 0, unsigned); + }; + /** + * Returns a Long representing the given value, provided that it is a finite number. Otherwise, zero is returned. + * @param value - The number in question + * @param unsigned - Whether unsigned or not, defaults to signed + * @returns The corresponding Long value + */ + Long.fromBigInt = function (value, unsigned) { + return Long.fromString(value.toString(), unsigned); + }; + /** + * Returns a Long representation of the given string, written using the specified radix. + * @param str - The textual representation of the Long + * @param unsigned - Whether unsigned or not, defaults to signed + * @param radix - The radix in which the text is written (2-36), defaults to 10 + * @returns The corresponding Long value + */ + Long.fromString = function (str, unsigned, radix) { + if (str.length === 0) + throw Error('empty string'); + if (str === 'NaN' || str === 'Infinity' || str === '+Infinity' || str === '-Infinity') + return Long.ZERO; + if (typeof unsigned === 'number') { + // For goog.math.long compatibility + (radix = unsigned), (unsigned = false); + } + else { + unsigned = !!unsigned; + } + radix = radix || 10; + if (radix < 2 || 36 < radix) + throw RangeError('radix'); + var p; + if ((p = str.indexOf('-')) > 0) + throw Error('interior hyphen'); + else if (p === 0) { + return Long.fromString(str.substring(1), unsigned, radix).neg(); + } + // Do several (8) digits each time through the loop, so as to + // minimize the calls to the very expensive emulated div. + var radixToPower = Long.fromNumber(Math.pow(radix, 8)); + var result = Long.ZERO; + for (var i = 0; i < str.length; i += 8) { + var size = Math.min(8, str.length - i), value = parseInt(str.substring(i, i + size), radix); + if (size < 8) { + var power = Long.fromNumber(Math.pow(radix, size)); + result = result.mul(power).add(Long.fromNumber(value)); + } + else { + result = result.mul(radixToPower); + result = result.add(Long.fromNumber(value)); + } + } + result.unsigned = unsigned; + return result; + }; + /** + * Creates a Long from its byte representation. + * @param bytes - Byte representation + * @param unsigned - Whether unsigned or not, defaults to signed + * @param le - Whether little or big endian, defaults to big endian + * @returns The corresponding Long value + */ + Long.fromBytes = function (bytes, unsigned, le) { + return le ? Long.fromBytesLE(bytes, unsigned) : Long.fromBytesBE(bytes, unsigned); + }; + /** + * Creates a Long from its little endian byte representation. + * @param bytes - Little endian byte representation + * @param unsigned - Whether unsigned or not, defaults to signed + * @returns The corresponding Long value + */ + Long.fromBytesLE = function (bytes, unsigned) { + return new Long(bytes[0] | (bytes[1] << 8) | (bytes[2] << 16) | (bytes[3] << 24), bytes[4] | (bytes[5] << 8) | (bytes[6] << 16) | (bytes[7] << 24), unsigned); + }; + /** + * Creates a Long from its big endian byte representation. + * @param bytes - Big endian byte representation + * @param unsigned - Whether unsigned or not, defaults to signed + * @returns The corresponding Long value + */ + Long.fromBytesBE = function (bytes, unsigned) { + return new Long((bytes[4] << 24) | (bytes[5] << 16) | (bytes[6] << 8) | bytes[7], (bytes[0] << 24) | (bytes[1] << 16) | (bytes[2] << 8) | bytes[3], unsigned); + }; + /** + * Tests if the specified object is a Long. + */ + Long.isLong = function (value) { + return (0, utils_1.isObjectLike)(value) && value['__isLong__'] === true; + }; + /** + * Converts the specified value to a Long. + * @param unsigned - Whether unsigned or not, defaults to signed + */ + Long.fromValue = function (val, unsigned) { + if (typeof val === 'number') + return Long.fromNumber(val, unsigned); + if (typeof val === 'string') + return Long.fromString(val, unsigned); + // Throws for non-objects, converts non-instanceof Long: + return Long.fromBits(val.low, val.high, typeof unsigned === 'boolean' ? unsigned : val.unsigned); + }; + /** Returns the sum of this and the specified Long. */ + Long.prototype.add = function (addend) { + if (!Long.isLong(addend)) + addend = Long.fromValue(addend); + // Divide each number into 4 chunks of 16 bits, and then sum the chunks. + var a48 = this.high >>> 16; + var a32 = this.high & 0xffff; + var a16 = this.low >>> 16; + var a00 = this.low & 0xffff; + var b48 = addend.high >>> 16; + var b32 = addend.high & 0xffff; + var b16 = addend.low >>> 16; + var b00 = addend.low & 0xffff; + var c48 = 0, c32 = 0, c16 = 0, c00 = 0; + c00 += a00 + b00; + c16 += c00 >>> 16; + c00 &= 0xffff; + c16 += a16 + b16; + c32 += c16 >>> 16; + c16 &= 0xffff; + c32 += a32 + b32; + c48 += c32 >>> 16; + c32 &= 0xffff; + c48 += a48 + b48; + c48 &= 0xffff; + return Long.fromBits((c16 << 16) | c00, (c48 << 16) | c32, this.unsigned); + }; + /** + * Returns the sum of this and the specified Long. + * @returns Sum + */ + Long.prototype.and = function (other) { + if (!Long.isLong(other)) + other = Long.fromValue(other); + return Long.fromBits(this.low & other.low, this.high & other.high, this.unsigned); + }; + /** + * Compares this Long's value with the specified's. + * @returns 0 if they are the same, 1 if the this is greater and -1 if the given one is greater + */ + Long.prototype.compare = function (other) { + if (!Long.isLong(other)) + other = Long.fromValue(other); + if (this.eq(other)) + return 0; + var thisNeg = this.isNegative(), otherNeg = other.isNegative(); + if (thisNeg && !otherNeg) + return -1; + if (!thisNeg && otherNeg) + return 1; + // At this point the sign bits are the same + if (!this.unsigned) + return this.sub(other).isNegative() ? -1 : 1; + // Both are positive if at least one is unsigned + return other.high >>> 0 > this.high >>> 0 || + (other.high === this.high && other.low >>> 0 > this.low >>> 0) + ? -1 + : 1; + }; + /** This is an alias of {@link Long.compare} */ + Long.prototype.comp = function (other) { + return this.compare(other); + }; + /** + * Returns this Long divided by the specified. The result is signed if this Long is signed or unsigned if this Long is unsigned. + * @returns Quotient + */ + Long.prototype.divide = function (divisor) { + if (!Long.isLong(divisor)) + divisor = Long.fromValue(divisor); + if (divisor.isZero()) + throw Error('division by zero'); + // use wasm support if present + if (wasm) { + // guard against signed division overflow: the largest + // negative number / -1 would be 1 larger than the largest + // positive number, due to two's complement. + if (!this.unsigned && + this.high === -0x80000000 && + divisor.low === -1 && + divisor.high === -1) { + // be consistent with non-wasm code path + return this; + } + var low = (this.unsigned ? wasm.div_u : wasm.div_s)(this.low, this.high, divisor.low, divisor.high); + return Long.fromBits(low, wasm.get_high(), this.unsigned); + } + if (this.isZero()) + return this.unsigned ? Long.UZERO : Long.ZERO; + var approx, rem, res; + if (!this.unsigned) { + // This section is only relevant for signed longs and is derived from the + // closure library as a whole. + if (this.eq(Long.MIN_VALUE)) { + if (divisor.eq(Long.ONE) || divisor.eq(Long.NEG_ONE)) + return Long.MIN_VALUE; + // recall that -MIN_VALUE == MIN_VALUE + else if (divisor.eq(Long.MIN_VALUE)) + return Long.ONE; + else { + // At this point, we have |other| >= 2, so |this/other| < |MIN_VALUE|. + var halfThis = this.shr(1); + approx = halfThis.div(divisor).shl(1); + if (approx.eq(Long.ZERO)) { + return divisor.isNegative() ? Long.ONE : Long.NEG_ONE; + } + else { + rem = this.sub(divisor.mul(approx)); + res = approx.add(rem.div(divisor)); + return res; + } + } + } + else if (divisor.eq(Long.MIN_VALUE)) + return this.unsigned ? Long.UZERO : Long.ZERO; + if (this.isNegative()) { + if (divisor.isNegative()) + return this.neg().div(divisor.neg()); + return this.neg().div(divisor).neg(); + } + else if (divisor.isNegative()) + return this.div(divisor.neg()).neg(); + res = Long.ZERO; + } + else { + // The algorithm below has not been made for unsigned longs. It's therefore + // required to take special care of the MSB prior to running it. + if (!divisor.unsigned) + divisor = divisor.toUnsigned(); + if (divisor.gt(this)) + return Long.UZERO; + if (divisor.gt(this.shru(1))) + // 15 >>> 1 = 7 ; with divisor = 8 ; true + return Long.UONE; + res = Long.UZERO; + } + // Repeat the following until the remainder is less than other: find a + // floating-point that approximates remainder / other *from below*, add this + // into the result, and subtract it from the remainder. It is critical that + // the approximate value is less than or equal to the real value so that the + // remainder never becomes negative. + // eslint-disable-next-line @typescript-eslint/no-this-alias + rem = this; + while (rem.gte(divisor)) { + // Approximate the result of division. This may be a little greater or + // smaller than the actual value. + approx = Math.max(1, Math.floor(rem.toNumber() / divisor.toNumber())); + // We will tweak the approximate result by changing it in the 48-th digit or + // the smallest non-fractional digit, whichever is larger. + var log2 = Math.ceil(Math.log(approx) / Math.LN2); + var delta = log2 <= 48 ? 1 : Math.pow(2, log2 - 48); + // Decrease the approximation until it is smaller than the remainder. Note + // that if it is too large, the product overflows and is negative. + var approxRes = Long.fromNumber(approx); + var approxRem = approxRes.mul(divisor); + while (approxRem.isNegative() || approxRem.gt(rem)) { + approx -= delta; + approxRes = Long.fromNumber(approx, this.unsigned); + approxRem = approxRes.mul(divisor); + } + // We know the answer can't be zero... and actually, zero would cause + // infinite recursion since we would make no progress. + if (approxRes.isZero()) + approxRes = Long.ONE; + res = res.add(approxRes); + rem = rem.sub(approxRem); + } + return res; + }; + /**This is an alias of {@link Long.divide} */ + Long.prototype.div = function (divisor) { + return this.divide(divisor); + }; + /** + * Tests if this Long's value equals the specified's. + * @param other - Other value + */ + Long.prototype.equals = function (other) { + if (!Long.isLong(other)) + other = Long.fromValue(other); + if (this.unsigned !== other.unsigned && this.high >>> 31 === 1 && other.high >>> 31 === 1) + return false; + return this.high === other.high && this.low === other.low; + }; + /** This is an alias of {@link Long.equals} */ + Long.prototype.eq = function (other) { + return this.equals(other); + }; + /** Gets the high 32 bits as a signed integer. */ + Long.prototype.getHighBits = function () { + return this.high; + }; + /** Gets the high 32 bits as an unsigned integer. */ + Long.prototype.getHighBitsUnsigned = function () { + return this.high >>> 0; + }; + /** Gets the low 32 bits as a signed integer. */ + Long.prototype.getLowBits = function () { + return this.low; + }; + /** Gets the low 32 bits as an unsigned integer. */ + Long.prototype.getLowBitsUnsigned = function () { + return this.low >>> 0; + }; + /** Gets the number of bits needed to represent the absolute value of this Long. */ + Long.prototype.getNumBitsAbs = function () { + if (this.isNegative()) { + // Unsigned Longs are never negative + return this.eq(Long.MIN_VALUE) ? 64 : this.neg().getNumBitsAbs(); + } + var val = this.high !== 0 ? this.high : this.low; + var bit; + for (bit = 31; bit > 0; bit--) + if ((val & (1 << bit)) !== 0) + break; + return this.high !== 0 ? bit + 33 : bit + 1; + }; + /** Tests if this Long's value is greater than the specified's. */ + Long.prototype.greaterThan = function (other) { + return this.comp(other) > 0; + }; + /** This is an alias of {@link Long.greaterThan} */ + Long.prototype.gt = function (other) { + return this.greaterThan(other); + }; + /** Tests if this Long's value is greater than or equal the specified's. */ + Long.prototype.greaterThanOrEqual = function (other) { + return this.comp(other) >= 0; + }; + /** This is an alias of {@link Long.greaterThanOrEqual} */ + Long.prototype.gte = function (other) { + return this.greaterThanOrEqual(other); + }; + /** This is an alias of {@link Long.greaterThanOrEqual} */ + Long.prototype.ge = function (other) { + return this.greaterThanOrEqual(other); + }; + /** Tests if this Long's value is even. */ + Long.prototype.isEven = function () { + return (this.low & 1) === 0; + }; + /** Tests if this Long's value is negative. */ + Long.prototype.isNegative = function () { + return !this.unsigned && this.high < 0; + }; + /** Tests if this Long's value is odd. */ + Long.prototype.isOdd = function () { + return (this.low & 1) === 1; + }; + /** Tests if this Long's value is positive. */ + Long.prototype.isPositive = function () { + return this.unsigned || this.high >= 0; + }; + /** Tests if this Long's value equals zero. */ + Long.prototype.isZero = function () { + return this.high === 0 && this.low === 0; + }; + /** Tests if this Long's value is less than the specified's. */ + Long.prototype.lessThan = function (other) { + return this.comp(other) < 0; + }; + /** This is an alias of {@link Long#lessThan}. */ + Long.prototype.lt = function (other) { + return this.lessThan(other); + }; + /** Tests if this Long's value is less than or equal the specified's. */ + Long.prototype.lessThanOrEqual = function (other) { + return this.comp(other) <= 0; + }; + /** This is an alias of {@link Long.lessThanOrEqual} */ + Long.prototype.lte = function (other) { + return this.lessThanOrEqual(other); + }; + /** Returns this Long modulo the specified. */ + Long.prototype.modulo = function (divisor) { + if (!Long.isLong(divisor)) + divisor = Long.fromValue(divisor); + // use wasm support if present + if (wasm) { + var low = (this.unsigned ? wasm.rem_u : wasm.rem_s)(this.low, this.high, divisor.low, divisor.high); + return Long.fromBits(low, wasm.get_high(), this.unsigned); + } + return this.sub(this.div(divisor).mul(divisor)); + }; + /** This is an alias of {@link Long.modulo} */ + Long.prototype.mod = function (divisor) { + return this.modulo(divisor); + }; + /** This is an alias of {@link Long.modulo} */ + Long.prototype.rem = function (divisor) { + return this.modulo(divisor); + }; + /** + * Returns the product of this and the specified Long. + * @param multiplier - Multiplier + * @returns Product + */ + Long.prototype.multiply = function (multiplier) { + if (this.isZero()) + return Long.ZERO; + if (!Long.isLong(multiplier)) + multiplier = Long.fromValue(multiplier); + // use wasm support if present + if (wasm) { + var low = wasm.mul(this.low, this.high, multiplier.low, multiplier.high); + return Long.fromBits(low, wasm.get_high(), this.unsigned); + } + if (multiplier.isZero()) + return Long.ZERO; + if (this.eq(Long.MIN_VALUE)) + return multiplier.isOdd() ? Long.MIN_VALUE : Long.ZERO; + if (multiplier.eq(Long.MIN_VALUE)) + return this.isOdd() ? Long.MIN_VALUE : Long.ZERO; + if (this.isNegative()) { + if (multiplier.isNegative()) + return this.neg().mul(multiplier.neg()); + else + return this.neg().mul(multiplier).neg(); + } + else if (multiplier.isNegative()) + return this.mul(multiplier.neg()).neg(); + // If both longs are small, use float multiplication + if (this.lt(Long.TWO_PWR_24) && multiplier.lt(Long.TWO_PWR_24)) + return Long.fromNumber(this.toNumber() * multiplier.toNumber(), this.unsigned); + // Divide each long into 4 chunks of 16 bits, and then add up 4x4 products. + // We can skip products that would overflow. + var a48 = this.high >>> 16; + var a32 = this.high & 0xffff; + var a16 = this.low >>> 16; + var a00 = this.low & 0xffff; + var b48 = multiplier.high >>> 16; + var b32 = multiplier.high & 0xffff; + var b16 = multiplier.low >>> 16; + var b00 = multiplier.low & 0xffff; + var c48 = 0, c32 = 0, c16 = 0, c00 = 0; + c00 += a00 * b00; + c16 += c00 >>> 16; + c00 &= 0xffff; + c16 += a16 * b00; + c32 += c16 >>> 16; + c16 &= 0xffff; + c16 += a00 * b16; + c32 += c16 >>> 16; + c16 &= 0xffff; + c32 += a32 * b00; + c48 += c32 >>> 16; + c32 &= 0xffff; + c32 += a16 * b16; + c48 += c32 >>> 16; + c32 &= 0xffff; + c32 += a00 * b32; + c48 += c32 >>> 16; + c32 &= 0xffff; + c48 += a48 * b00 + a32 * b16 + a16 * b32 + a00 * b48; + c48 &= 0xffff; + return Long.fromBits((c16 << 16) | c00, (c48 << 16) | c32, this.unsigned); + }; + /** This is an alias of {@link Long.multiply} */ + Long.prototype.mul = function (multiplier) { + return this.multiply(multiplier); + }; + /** Returns the Negation of this Long's value. */ + Long.prototype.negate = function () { + if (!this.unsigned && this.eq(Long.MIN_VALUE)) + return Long.MIN_VALUE; + return this.not().add(Long.ONE); + }; + /** This is an alias of {@link Long.negate} */ + Long.prototype.neg = function () { + return this.negate(); + }; + /** Returns the bitwise NOT of this Long. */ + Long.prototype.not = function () { + return Long.fromBits(~this.low, ~this.high, this.unsigned); + }; + /** Tests if this Long's value differs from the specified's. */ + Long.prototype.notEquals = function (other) { + return !this.equals(other); + }; + /** This is an alias of {@link Long.notEquals} */ + Long.prototype.neq = function (other) { + return this.notEquals(other); + }; + /** This is an alias of {@link Long.notEquals} */ + Long.prototype.ne = function (other) { + return this.notEquals(other); + }; + /** + * Returns the bitwise OR of this Long and the specified. + */ + Long.prototype.or = function (other) { + if (!Long.isLong(other)) + other = Long.fromValue(other); + return Long.fromBits(this.low | other.low, this.high | other.high, this.unsigned); + }; + /** + * Returns this Long with bits shifted to the left by the given amount. + * @param numBits - Number of bits + * @returns Shifted Long + */ + Long.prototype.shiftLeft = function (numBits) { + if (Long.isLong(numBits)) + numBits = numBits.toInt(); + if ((numBits &= 63) === 0) + return this; + else if (numBits < 32) + return Long.fromBits(this.low << numBits, (this.high << numBits) | (this.low >>> (32 - numBits)), this.unsigned); + else + return Long.fromBits(0, this.low << (numBits - 32), this.unsigned); + }; + /** This is an alias of {@link Long.shiftLeft} */ + Long.prototype.shl = function (numBits) { + return this.shiftLeft(numBits); + }; + /** + * Returns this Long with bits arithmetically shifted to the right by the given amount. + * @param numBits - Number of bits + * @returns Shifted Long + */ + Long.prototype.shiftRight = function (numBits) { + if (Long.isLong(numBits)) + numBits = numBits.toInt(); + if ((numBits &= 63) === 0) + return this; + else if (numBits < 32) + return Long.fromBits((this.low >>> numBits) | (this.high << (32 - numBits)), this.high >> numBits, this.unsigned); + else + return Long.fromBits(this.high >> (numBits - 32), this.high >= 0 ? 0 : -1, this.unsigned); + }; + /** This is an alias of {@link Long.shiftRight} */ + Long.prototype.shr = function (numBits) { + return this.shiftRight(numBits); + }; + /** + * Returns this Long with bits logically shifted to the right by the given amount. + * @param numBits - Number of bits + * @returns Shifted Long + */ + Long.prototype.shiftRightUnsigned = function (numBits) { + if (Long.isLong(numBits)) + numBits = numBits.toInt(); + numBits &= 63; + if (numBits === 0) + return this; + else { + var high = this.high; + if (numBits < 32) { + var low = this.low; + return Long.fromBits((low >>> numBits) | (high << (32 - numBits)), high >>> numBits, this.unsigned); + } + else if (numBits === 32) + return Long.fromBits(high, 0, this.unsigned); + else + return Long.fromBits(high >>> (numBits - 32), 0, this.unsigned); + } + }; + /** This is an alias of {@link Long.shiftRightUnsigned} */ + Long.prototype.shr_u = function (numBits) { + return this.shiftRightUnsigned(numBits); + }; + /** This is an alias of {@link Long.shiftRightUnsigned} */ + Long.prototype.shru = function (numBits) { + return this.shiftRightUnsigned(numBits); + }; + /** + * Returns the difference of this and the specified Long. + * @param subtrahend - Subtrahend + * @returns Difference + */ + Long.prototype.subtract = function (subtrahend) { + if (!Long.isLong(subtrahend)) + subtrahend = Long.fromValue(subtrahend); + return this.add(subtrahend.neg()); + }; + /** This is an alias of {@link Long.subtract} */ + Long.prototype.sub = function (subtrahend) { + return this.subtract(subtrahend); + }; + /** Converts the Long to a 32 bit integer, assuming it is a 32 bit integer. */ + Long.prototype.toInt = function () { + return this.unsigned ? this.low >>> 0 : this.low; + }; + /** Converts the Long to a the nearest floating-point representation of this value (double, 53 bit mantissa). */ + Long.prototype.toNumber = function () { + if (this.unsigned) + return (this.high >>> 0) * TWO_PWR_32_DBL + (this.low >>> 0); + return this.high * TWO_PWR_32_DBL + (this.low >>> 0); + }; + /** Converts the Long to a BigInt (arbitrary precision). */ + Long.prototype.toBigInt = function () { + return BigInt(this.toString()); + }; + /** + * Converts this Long to its byte representation. + * @param le - Whether little or big endian, defaults to big endian + * @returns Byte representation + */ + Long.prototype.toBytes = function (le) { + return le ? this.toBytesLE() : this.toBytesBE(); + }; + /** + * Converts this Long to its little endian byte representation. + * @returns Little endian byte representation + */ + Long.prototype.toBytesLE = function () { + var hi = this.high, lo = this.low; + return [ + lo & 0xff, + (lo >>> 8) & 0xff, + (lo >>> 16) & 0xff, + lo >>> 24, + hi & 0xff, + (hi >>> 8) & 0xff, + (hi >>> 16) & 0xff, + hi >>> 24 + ]; + }; + /** + * Converts this Long to its big endian byte representation. + * @returns Big endian byte representation + */ + Long.prototype.toBytesBE = function () { + var hi = this.high, lo = this.low; + return [ + hi >>> 24, + (hi >>> 16) & 0xff, + (hi >>> 8) & 0xff, + hi & 0xff, + lo >>> 24, + (lo >>> 16) & 0xff, + (lo >>> 8) & 0xff, + lo & 0xff + ]; + }; + /** + * Converts this Long to signed. + */ + Long.prototype.toSigned = function () { + if (!this.unsigned) + return this; + return Long.fromBits(this.low, this.high, false); + }; + /** + * Converts the Long to a string written in the specified radix. + * @param radix - Radix (2-36), defaults to 10 + * @throws RangeError If `radix` is out of range + */ + Long.prototype.toString = function (radix) { + radix = radix || 10; + if (radix < 2 || 36 < radix) + throw RangeError('radix'); + if (this.isZero()) + return '0'; + if (this.isNegative()) { + // Unsigned Longs are never negative + if (this.eq(Long.MIN_VALUE)) { + // We need to change the Long value before it can be negated, so we remove + // the bottom-most digit in this base and then recurse to do the rest. + var radixLong = Long.fromNumber(radix), div = this.div(radixLong), rem1 = div.mul(radixLong).sub(this); + return div.toString(radix) + rem1.toInt().toString(radix); + } + else + return '-' + this.neg().toString(radix); + } + // Do several (6) digits each time through the loop, so as to + // minimize the calls to the very expensive emulated div. + var radixToPower = Long.fromNumber(Math.pow(radix, 6), this.unsigned); + // eslint-disable-next-line @typescript-eslint/no-this-alias + var rem = this; + var result = ''; + // eslint-disable-next-line no-constant-condition + while (true) { + var remDiv = rem.div(radixToPower); + var intval = rem.sub(remDiv.mul(radixToPower)).toInt() >>> 0; + var digits = intval.toString(radix); + rem = remDiv; + if (rem.isZero()) { + return digits + result; + } + else { + while (digits.length < 6) + digits = '0' + digits; + result = '' + digits + result; + } + } + }; + /** Converts this Long to unsigned. */ + Long.prototype.toUnsigned = function () { + if (this.unsigned) + return this; + return Long.fromBits(this.low, this.high, true); + }; + /** Returns the bitwise XOR of this Long and the given one. */ + Long.prototype.xor = function (other) { + if (!Long.isLong(other)) + other = Long.fromValue(other); + return Long.fromBits(this.low ^ other.low, this.high ^ other.high, this.unsigned); + }; + /** This is an alias of {@link Long.isZero} */ + Long.prototype.eqz = function () { + return this.isZero(); + }; + /** This is an alias of {@link Long.lessThanOrEqual} */ + Long.prototype.le = function (other) { + return this.lessThanOrEqual(other); + }; + /* + **************************************************************** + * BSON SPECIFIC ADDITIONS * + **************************************************************** + */ + Long.prototype.toExtendedJSON = function (options) { + if (options && options.relaxed) + return this.toNumber(); + return { $numberLong: this.toString() }; + }; + Long.fromExtendedJSON = function (doc, options) { + var result = Long.fromString(doc.$numberLong); + return options && options.relaxed ? result.toNumber() : result; + }; + /** @internal */ + Long.prototype[Symbol.for('nodejs.util.inspect.custom')] = function () { + return this.inspect(); + }; + Long.prototype.inspect = function () { + return "new Long(\"".concat(this.toString(), "\"").concat(this.unsigned ? ', true' : '', ")"); + }; + Long.TWO_PWR_24 = Long.fromInt(TWO_PWR_24_DBL); + /** Maximum unsigned value. */ + Long.MAX_UNSIGNED_VALUE = Long.fromBits(0xffffffff | 0, 0xffffffff | 0, true); + /** Signed zero */ + Long.ZERO = Long.fromInt(0); + /** Unsigned zero. */ + Long.UZERO = Long.fromInt(0, true); + /** Signed one. */ + Long.ONE = Long.fromInt(1); + /** Unsigned one. */ + Long.UONE = Long.fromInt(1, true); + /** Signed negative one. */ + Long.NEG_ONE = Long.fromInt(-1); + /** Maximum signed value. */ + Long.MAX_VALUE = Long.fromBits(0xffffffff | 0, 0x7fffffff | 0, false); + /** Minimum signed value. */ + Long.MIN_VALUE = Long.fromBits(0, 0x80000000 | 0, false); + return Long; +}()); +exports.Long = Long; +Object.defineProperty(Long.prototype, '__isLong__', { value: true }); +Object.defineProperty(Long.prototype, '_bsontype', { value: 'Long' }); +//# sourceMappingURL=long.js.map \ No newline at end of file diff --git a/ts-ticket-office-service/node_modules/bson/lib/long.js.map b/ts-ticket-office-service/node_modules/bson/lib/long.js.map new file mode 100644 index 000000000..c191742c1 --- /dev/null +++ b/ts-ticket-office-service/node_modules/bson/lib/long.js.map @@ -0,0 +1 @@ +{"version":3,"file":"long.js","sourceRoot":"","sources":["../src/long.ts"],"names":[],"mappings":";;;AACA,wCAA8C;AA2C9C;;GAEG;AACH,IAAI,IAAI,GAAgC,SAAS,CAAC;AAMlD,IAAI;IACF,IAAI,GAAG,IAAI,WAAW,CAAC,QAAQ,CAC7B,IAAI,WAAW,CAAC,MAAM;IACpB,kBAAkB;IAClB,IAAI,UAAU,CAAC,CAAC,CAAC,EAAE,EAAE,EAAE,GAAG,EAAE,GAAG,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,EAAE,EAAE,CAAC,EAAE,EAAE,EAAE,CAAC,EAAE,CAAC,EAAE,GAAG,EAAE,EAAE,EAAE,CAAC,EAAE,GAAG,EAAE,GAAG,EAAE,GAAG,EAAE,GAAG,EAAE,CAAC,EAAE,GAAG,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,GAAG,EAAE,CAAC,EAAE,EAAE,EAAE,CAAC,E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C1E,CAAC;IA/2BM,eAAU,GAAG,IAAI,CAAC,OAAO,CAAC,cAAc,CAAC,CAAC;IAEjD,8BAA8B;IACvB,uBAAkB,GAAG,IAAI,CAAC,QAAQ,CAAC,UAAU,GAAG,CAAC,EAAE,UAAU,GAAG,CAAC,EAAE,IAAI,CAAC,CAAC;IAChF,kBAAkB;IACX,SAAI,GAAG,IAAI,CAAC,OAAO,CAAC,CAAC,CAAC,CAAC;IAC9B,qBAAqB;IACd,UAAK,GAAG,IAAI,CAAC,OAAO,CAAC,CAAC,EAAE,IAAI,CAAC,CAAC;IACrC,kBAAkB;IACX,QAAG,GAAG,IAAI,CAAC,OAAO,CAAC,CAAC,CAAC,CAAC;IAC7B,oBAAoB;IACb,SAAI,GAAG,IAAI,CAAC,OAAO,CAAC,CAAC,EAAE,IAAI,CAAC,CAAC;IACpC,2BAA2B;IACpB,YAAO,GAAG,IAAI,CAAC,OAAO,CAAC,CAAC,CAAC,CAAC,CAAC;IAClC,4BAA4B;IACrB,cAAS,GAAG,IAAI,CAAC,QAAQ,CAAC,UAAU,GAAG,CAAC,EAAE,UAAU,GAAG,CAAC,EAAE,KAAK,CAAC,CAAC;IACxE,4BAA4B;IACrB,cAAS,GAAG,IAAI,CAAC,QAAQ,CAAC,CAAC,EAAE,UAAU,GAAG,CAAC,EAAE,KAAK,CAAC,CAAC;IA+1B7D,WAAC;CAAA,AAv6BD,IAu6BC;AAv6BY,oBAAI;AAy6BjB,MAAM,CAAC,cAAc,CAAC,IAAI,CAAC,SAAS,EAAE,YAAY,EAAE,EAAE,KAAK,EAAE,IAAI,EAAE,CAAC,CAAC;AACrE,MAAM,CAAC,cAAc,CAAC,IAAI,CAAC,SAAS,EAAE,WAAW,EAAE,EAAE,KAAK,EAAE,MAAM,EAAE,CAAC,CAAC"} \ No newline at end of file diff --git a/ts-ticket-office-service/node_modules/bson/lib/map.js b/ts-ticket-office-service/node_modules/bson/lib/map.js new file mode 100644 index 000000000..32334f590 --- /dev/null +++ b/ts-ticket-office-service/node_modules/bson/lib/map.js @@ -0,0 +1,123 @@ +"use strict"; +/* eslint-disable @typescript-eslint/no-explicit-any */ +// We have an ES6 Map available, return the native instance +Object.defineProperty(exports, "__esModule", { value: true }); +exports.Map = void 0; +var global_1 = require("./utils/global"); +/** @public */ +var bsonMap; +exports.Map = bsonMap; +var bsonGlobal = (0, global_1.getGlobal)(); +if (bsonGlobal.Map) { + exports.Map = bsonMap = bsonGlobal.Map; +} +else { + // We will return a polyfill + exports.Map = bsonMap = /** @class */ (function () { + function Map(array) { + if (array === void 0) { array = []; } + this._keys = []; + this._values = {}; + for (var i = 0; i < array.length; i++) { + if (array[i] == null) + continue; // skip null and undefined + var entry = array[i]; + var key = entry[0]; + var value = entry[1]; + // Add the key to the list of keys in order + this._keys.push(key); + // Add the key and value to the values dictionary with a point + // to the location in the ordered keys list + this._values[key] = { v: value, i: this._keys.length - 1 }; + } + } + Map.prototype.clear = function () { + this._keys = []; + this._values = {}; + }; + Map.prototype.delete = function (key) { + var value = this._values[key]; + if (value == null) + return false; + // Delete entry + delete this._values[key]; + // Remove the key from the ordered keys list + this._keys.splice(value.i, 1); + return true; + }; + Map.prototype.entries = function () { + var _this = this; + var index = 0; + return { + next: function () { + var key = _this._keys[index++]; + return { + value: key !== undefined ? [key, _this._values[key].v] : undefined, + done: key !== undefined ? false : true + }; + } + }; + }; + Map.prototype.forEach = function (callback, self) { + self = self || this; + for (var i = 0; i < this._keys.length; i++) { + var key = this._keys[i]; + // Call the forEach callback + callback.call(self, this._values[key].v, key, self); + } + }; + Map.prototype.get = function (key) { + return this._values[key] ? this._values[key].v : undefined; + }; + Map.prototype.has = function (key) { + return this._values[key] != null; + }; + Map.prototype.keys = function () { + var _this = this; + var index = 0; + return { + next: function () { + var key = _this._keys[index++]; + return { + value: key !== undefined ? key : undefined, + done: key !== undefined ? false : true + }; + } + }; + }; + Map.prototype.set = function (key, value) { + if (this._values[key]) { + this._values[key].v = value; + return this; + } + // Add the key to the list of keys in order + this._keys.push(key); + // Add the key and value to the values dictionary with a point + // to the location in the ordered keys list + this._values[key] = { v: value, i: this._keys.length - 1 }; + return this; + }; + Map.prototype.values = function () { + var _this = this; + var index = 0; + return { + next: function () { + var key = _this._keys[index++]; + return { + value: key !== undefined ? _this._values[key].v : undefined, + done: key !== undefined ? false : true + }; + } + }; + }; + Object.defineProperty(Map.prototype, "size", { + get: function () { + return this._keys.length; + }, + enumerable: false, + configurable: true + }); + return Map; + }()); +} +//# sourceMappingURL=map.js.map \ No newline at end of file diff --git a/ts-ticket-office-service/node_modules/bson/lib/map.js.map b/ts-ticket-office-service/node_modules/bson/lib/map.js.map new file mode 100644 index 000000000..944dcf6df --- /dev/null +++ b/ts-ticket-office-service/node_modules/bson/lib/map.js.map @@ -0,0 +1 @@ +{"version":3,"file":"map.js","sourceRoot":"","sources":["../src/map.ts"],"names":[],"mappings":";AAAA,uDAAuD;AACvD,2DAA2D;;;AAE3D,yCAA2C;AAE3C,cAAc;AACd,IAAI,OAAuB,CAAC;AAgHR,sBAAG;AA9GvB,IAAM,UAAU,GAAG,IAAA,kBAAS,GAA4B,CAAC;AACzD,IAAI,UAAU,CAAC,GAAG,EAAE;IAClB,cAAA,OAAO,GAAG,UAAU,CAAC,GAAG,CAAC;CAC1B;KAAM;IACL,4BAA4B;IAC5B,cAAA,OAAO,GAAG;QAGR,aAAY,KAA2B;YAA3B,sBAAA,EAAA,UAA2B;YACrC,IAAI,CAAC,KAAK,GAAG,EAAE,CAAC;YAChB,IAAI,CAAC,OAAO,GAAG,EAAE,CAAC;YAElB,KAAK,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC,GAAG,KAAK,CAAC,MAAM,EAAE,CAAC,EAAE,EAAE;gBACrC,IAAI,KAAK,CAAC,CAAC,CAAC,IAAI,IAAI;oBAAE,SAAS,CAAC,0BAA0B;gBAC1D,IAAM,KAAK,GAAG,KAAK,CAAC,CAAC,CAAC,CAAC;gBACvB,IAAM,GAAG,GAAG,KAAK,CAAC,CA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AAI,CAAC,OAAO,CAAC,GAAG,CAAC,EAAE;gBACrB,IAAI,CAAC,OAAO,CAAC,GAAG,CAAC,CAAC,CAAC,GAAG,KAAK,CAAC;gBAC5B,OAAO,IAAI,CAAC;aACb;YAED,2CAA2C;YAC3C,IAAI,CAAC,KAAK,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC;YACrB,8DAA8D;YAC9D,2CAA2C;YAC3C,IAAI,CAAC,OAAO,CAAC,GAAG,CAAC,GAAG,EAAE,CAAC,EAAE,KAAK,EAAE,CAAC,EAAE,IAAI,CAAC,KAAK,CAAC,MAAM,GAAG,CAAC,EAAE,CAAC;YAC3D,OAAO,IAAI,CAAC;QACd,CAAC;QACD,oBAAM,GAAN;YAAA,iBAYC;YAXC,IAAI,KAAK,GAAG,CAAC,CAAC;YAEd,OAAO;gBACL,IAAI,EAAE;oBACJ,IAAM,GAAG,GAAG,KAAI,CAAC,KAAK,CAAC,KAAK,EAAE,CAAC,CAAC;oBAChC,OAAO;wBACL,KAAK,EAAE,GAAG,KAAK,SAAS,CAAC,CAAC,CAAC,KAAI,CAAC,OAAO,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,SAAS;wBAC1D,IAAI,EAAE,GAAG,KAAK,SAAS,CAAC,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC,IAAI;qBACvC,CAAC;gBACJ,CAAC;aACF,CAAC;QACJ,CAAC;QACD,sBAAI,qBAAI;iBAAR;gBACE,OAAO,IAAI,CAAC,KAAK,CAAC,MAAM,CAAC;YAC3B,CAAC;;;WAAA;QACH,UAAC;IAAD,CAAC,AAtGS,GAsGoB,CAAC;CAChC"} \ No newline at end of file diff --git a/ts-ticket-office-service/node_modules/bson/lib/max_key.js b/ts-ticket-office-service/node_modules/bson/lib/max_key.js new file mode 100644 index 000000000..f9fd37603 --- /dev/null +++ b/ts-ticket-office-service/node_modules/bson/lib/max_key.js @@ -0,0 +1,33 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.MaxKey = void 0; +/** + * A class representation of the BSON MaxKey type. + * @public + * @category BSONType + */ +var MaxKey = /** @class */ (function () { + function MaxKey() { + if (!(this instanceof MaxKey)) + return new MaxKey(); + } + /** @internal */ + MaxKey.prototype.toExtendedJSON = function () { + return { $maxKey: 1 }; + }; + /** @internal */ + MaxKey.fromExtendedJSON = function () { + return new MaxKey(); + }; + /** @internal */ + MaxKey.prototype[Symbol.for('nodejs.util.inspect.custom')] = function () { + return this.inspect(); + }; + MaxKey.prototype.inspect = function () { + return 'new MaxKey()'; + }; + return MaxKey; +}()); +exports.MaxKey = MaxKey; +Object.defineProperty(MaxKey.prototype, '_bsontype', { value: 'MaxKey' }); +//# sourceMappingURL=max_key.js.map \ No newline at end of file diff --git a/ts-ticket-office-service/node_modules/bson/lib/max_key.js.map b/ts-ticket-office-service/node_modules/bson/lib/max_key.js.map new file mode 100644 index 000000000..f85a5900f --- /dev/null +++ b/ts-ticket-office-service/node_modules/bson/lib/max_key.js.map @@ -0,0 +1 @@ +{"version":3,"file":"max_key.js","sourceRoot":"","sources":["../src/max_key.ts"],"names":[],"mappings":";;;AAKA;;;;GAIG;AACH;IAGE;QACE,IAAI,CAAC,CAAC,IAAI,YAAY,MAAM,CAAC;YAAE,OAAO,IAAI,MAAM,EAAE,CAAC;IACrD,CAAC;IAED,gBAAgB;IAChB,+BAAc,GAAd;QACE,OAAO,EAAE,OAAO,EAAE,CAAC,EAAE,CAAC;IACxB,CAAC;IAED,gBAAgB;IACT,uBAAgB,GAAvB;QACE,OAAO,IAAI,MAAM,EAAE,CAAC;IACtB,CAAC;IAED,gBAAgB;IAChB,iBAAC,MAAM,CAAC,GAAG,CAAC,4BAA4B,CAAC,CAAC,GAA1C;QACE,OAAO,IAAI,CAAC,OAAO,EAAE,CAAC;IACxB,CAAC;IAED,wBAAO,GAAP;QACE,OAAO,cAAc,CAAC;IACxB,CAAC;IACH,aAAC;AAAD,CAAC,AAzBD,IAyBC;AAzBY,wBAAM;AA2BnB,MAAM,CAAC,cAAc,CAAC,MAAM,CAAC,SAAS,EAAE,WAAW,EAAE,EAAE,KAAK,EAAE,QAAQ,EAAE,CAAC,CAAC"} \ No newline at end of file diff --git a/ts-ticket-office-service/node_modules/bson/lib/min_key.js b/ts-ticket-office-service/node_modules/bson/lib/min_key.js new file mode 100644 index 000000000..c67b3df0b --- /dev/null +++ b/ts-ticket-office-service/node_modules/bson/lib/min_key.js @@ -0,0 +1,33 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.MinKey = void 0; +/** + * A class representation of the BSON MinKey type. + * @public + * @category BSONType + */ +var MinKey = /** @class */ (function () { + function MinKey() { + if (!(this instanceof MinKey)) + return new MinKey(); + } + /** @internal */ + MinKey.prototype.toExtendedJSON = function () { + return { $minKey: 1 }; + }; + /** @internal */ + MinKey.fromExtendedJSON = function () { + return new MinKey(); + }; + /** @internal */ + MinKey.prototype[Symbol.for('nodejs.util.inspect.custom')] = function () { + return this.inspect(); + }; + MinKey.prototype.inspect = function () { + return 'new MinKey()'; + }; + return MinKey; +}()); +exports.MinKey = MinKey; +Object.defineProperty(MinKey.prototype, '_bsontype', { value: 'MinKey' }); +//# sourceMappingURL=min_key.js.map \ No newline at end of file diff --git a/ts-ticket-office-service/node_modules/bson/lib/min_key.js.map b/ts-ticket-office-service/node_modules/bson/lib/min_key.js.map new file mode 100644 index 000000000..2d642d17d --- /dev/null +++ b/ts-ticket-office-service/node_modules/bson/lib/min_key.js.map @@ -0,0 +1 @@ +{"version":3,"file":"min_key.js","sourceRoot":"","sources":["../src/min_key.ts"],"names":[],"mappings":";;;AAKA;;;;GAIG;AACH;IAGE;QACE,IAAI,CAAC,CAAC,IAAI,YAAY,MAAM,CAAC;YAAE,OAAO,IAAI,MAAM,EAAE,CAAC;IACrD,CAAC;IAED,gBAAgB;IAChB,+BAAc,GAAd;QACE,OAAO,EAAE,OAAO,EAAE,CAAC,EAAE,CAAC;IACxB,CAAC;IAED,gBAAgB;IACT,uBAAgB,GAAvB;QACE,OAAO,IAAI,MAAM,EAAE,CAAC;IACtB,CAAC;IAED,gBAAgB;IAChB,iBAAC,MAAM,CAAC,GAAG,CAAC,4BAA4B,CAAC,CAAC,GAA1C;QACE,OAAO,IAAI,CAAC,OAAO,EAAE,CAAC;IACxB,CAAC;IAED,wBAAO,GAAP;QACE,OAAO,cAAc,CAAC;IACxB,CAAC;IACH,aAAC;AAAD,CAAC,AAzBD,IAyBC;AAzBY,wBAAM;AA2BnB,MAAM,CAAC,cAAc,CAAC,MAAM,CAAC,SAAS,EAAE,WAAW,EAAE,EAAE,KAAK,EAAE,QAAQ,EAAE,CAAC,CAAC"} \ No newline at end of file diff --git a/ts-ticket-office-service/node_modules/bson/lib/objectid.js b/ts-ticket-office-service/node_modules/bson/lib/objectid.js new file mode 100644 index 000000000..287de6e61 --- /dev/null +++ b/ts-ticket-office-service/node_modules/bson/lib/objectid.js @@ -0,0 +1,299 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.ObjectId = void 0; +var buffer_1 = require("buffer"); +var ensure_buffer_1 = require("./ensure_buffer"); +var error_1 = require("./error"); +var utils_1 = require("./parser/utils"); +// Regular expression that checks for hex value +var checkForHexRegExp = new RegExp('^[0-9a-fA-F]{24}$'); +// Unique sequence for the current process (initialized on first use) +var PROCESS_UNIQUE = null; +var kId = Symbol('id'); +/** + * A class representation of the BSON ObjectId type. + * @public + * @category BSONType + */ +var ObjectId = /** @class */ (function () { + /** + * Create an ObjectId type + * + * @param inputId - Can be a 24 character hex string, 12 byte binary Buffer, or a number. + */ + function ObjectId(inputId) { + if (!(this instanceof ObjectId)) + return new ObjectId(inputId); + // workingId is set based on type of input and whether valid id exists for the input + var workingId; + if (typeof inputId === 'object' && inputId && 'id' in inputId) { + if (typeof inputId.id !== 'string' && !ArrayBuffer.isView(inputId.id)) { + throw new error_1.BSONTypeError('Argument passed in must have an id that is of type string or Buffer'); + } + if ('toHexString' in inputId && typeof inputId.toHexString === 'function') { + workingId = buffer_1.Buffer.from(inputId.toHexString(), 'hex'); + } + else { + workingId = inputId.id; + } + } + else { + workingId = inputId; + } + // the following cases use workingId to construct an ObjectId + if (workingId == null || typeof workingId === 'number') { + // The most common use case (blank id, new objectId instance) + // Generate a new id + this[kId] = ObjectId.generate(typeof workingId === 'number' ? workingId : undefined); + } + else if (ArrayBuffer.isView(workingId) && workingId.byteLength === 12) { + // If intstanceof matches we can escape calling ensure buffer in Node.js environments + this[kId] = workingId instanceof buffer_1.Buffer ? workingId : (0, ensure_buffer_1.ensureBuffer)(workingId); + } + else if (typeof workingId === 'string') { + if (workingId.length === 12) { + var bytes = buffer_1.Buffer.from(workingId); + if (bytes.byteLength === 12) { + this[kId] = bytes; + } + else { + throw new error_1.BSONTypeError('Argument passed in must be a string of 12 bytes'); + } + } + else if (workingId.length === 24 && checkForHexRegExp.test(workingId)) { + this[kId] = buffer_1.Buffer.from(workingId, 'hex'); + } + else { + throw new error_1.BSONTypeError('Argument passed in must be a string of 12 bytes or a string of 24 hex characters or an integer'); + } + } + else { + throw new error_1.BSONTypeError('Argument passed in does not match the accepted types'); + } + // If we are caching the hex string + if (ObjectId.cacheHexString) { + this.__id = this.id.toString('hex'); + } + } + Object.defineProperty(ObjectId.prototype, "id", { + /** + * The ObjectId bytes + * @readonly + */ + get: function () { + return this[kId]; + }, + set: function (value) { + this[kId] = value; + if (ObjectId.cacheHexString) { + this.__id = value.toString('hex'); + } + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(ObjectId.prototype, "generationTime", { + /** + * The generation time of this ObjectId instance + * @deprecated Please use getTimestamp / createFromTime which returns an int32 epoch + */ + get: function () { + return this.id.readInt32BE(0); + }, + set: function (value) { + // Encode time into first 4 bytes + this.id.writeUInt32BE(value, 0); + }, + enumerable: false, + configurable: true + }); + /** Returns the ObjectId id as a 24 character hex string representation */ + ObjectId.prototype.toHexString = function () { + if (ObjectId.cacheHexString && this.__id) { + return this.__id; + } + var hexString = this.id.toString('hex'); + if (ObjectId.cacheHexString && !this.__id) { + this.__id = hexString; + } + return hexString; + }; + /** + * Update the ObjectId index + * @privateRemarks + * Used in generating new ObjectId's on the driver + * @internal + */ + ObjectId.getInc = function () { + return (ObjectId.index = (ObjectId.index + 1) % 0xffffff); + }; + /** + * Generate a 12 byte id buffer used in ObjectId's + * + * @param time - pass in a second based timestamp. + */ + ObjectId.generate = function (time) { + if ('number' !== typeof time) { + time = Math.floor(Date.now() / 1000); + } + var inc = ObjectId.getInc(); + var buffer = buffer_1.Buffer.alloc(12); + // 4-byte timestamp + buffer.writeUInt32BE(time, 0); + // set PROCESS_UNIQUE if yet not initialized + if (PROCESS_UNIQUE === null) { + PROCESS_UNIQUE = (0, utils_1.randomBytes)(5); + } + // 5-byte process unique + buffer[4] = PROCESS_UNIQUE[0]; + buffer[5] = PROCESS_UNIQUE[1]; + buffer[6] = PROCESS_UNIQUE[2]; + buffer[7] = PROCESS_UNIQUE[3]; + buffer[8] = PROCESS_UNIQUE[4]; + // 3-byte counter + buffer[11] = inc & 0xff; + buffer[10] = (inc >> 8) & 0xff; + buffer[9] = (inc >> 16) & 0xff; + return buffer; + }; + /** + * Converts the id into a 24 character hex string for printing + * + * @param format - The Buffer toString format parameter. + */ + ObjectId.prototype.toString = function (format) { + // Is the id a buffer then use the buffer toString method to return the format + if (format) + return this.id.toString(format); + return this.toHexString(); + }; + /** Converts to its JSON the 24 character hex string representation. */ + ObjectId.prototype.toJSON = function () { + return this.toHexString(); + }; + /** + * Compares the equality of this ObjectId with `otherID`. + * + * @param otherId - ObjectId instance to compare against. + */ + ObjectId.prototype.equals = function (otherId) { + if (otherId === undefined || otherId === null) { + return false; + } + if (otherId instanceof ObjectId) { + return this[kId][11] === otherId[kId][11] && this[kId].equals(otherId[kId]); + } + if (typeof otherId === 'string' && + ObjectId.isValid(otherId) && + otherId.length === 12 && + (0, utils_1.isUint8Array)(this.id)) { + return otherId === buffer_1.Buffer.prototype.toString.call(this.id, 'latin1'); + } + if (typeof otherId === 'string' && ObjectId.isValid(otherId) && otherId.length === 24) { + return otherId.toLowerCase() === this.toHexString(); + } + if (typeof otherId === 'string' && ObjectId.isValid(otherId) && otherId.length === 12) { + return buffer_1.Buffer.from(otherId).equals(this.id); + } + if (typeof otherId === 'object' && + 'toHexString' in otherId && + typeof otherId.toHexString === 'function') { + var otherIdString = otherId.toHexString(); + var thisIdString = this.toHexString().toLowerCase(); + return typeof otherIdString === 'string' && otherIdString.toLowerCase() === thisIdString; + } + return false; + }; + /** Returns the generation date (accurate up to the second) that this ID was generated. */ + ObjectId.prototype.getTimestamp = function () { + var timestamp = new Date(); + var time = this.id.readUInt32BE(0); + timestamp.setTime(Math.floor(time) * 1000); + return timestamp; + }; + /** @internal */ + ObjectId.createPk = function () { + return new ObjectId(); + }; + /** + * Creates an ObjectId from a second based number, with the rest of the ObjectId zeroed out. Used for comparisons or sorting the ObjectId. + * + * @param time - an integer number representing a number of seconds. + */ + ObjectId.createFromTime = function (time) { + var buffer = buffer_1.Buffer.from([0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]); + // Encode time into first 4 bytes + buffer.writeUInt32BE(time, 0); + // Return the new objectId + return new ObjectId(buffer); + }; + /** + * Creates an ObjectId from a hex string representation of an ObjectId. + * + * @param hexString - create a ObjectId from a passed in 24 character hexstring. + */ + ObjectId.createFromHexString = function (hexString) { + // Throw an error if it's not a valid setup + if (typeof hexString === 'undefined' || (hexString != null && hexString.length !== 24)) { + throw new error_1.BSONTypeError('Argument passed in must be a single String of 12 bytes or a string of 24 hex characters'); + } + return new ObjectId(buffer_1.Buffer.from(hexString, 'hex')); + }; + /** + * Checks if a value is a valid bson ObjectId + * + * @param id - ObjectId instance to validate. + */ + ObjectId.isValid = function (id) { + if (id == null) + return false; + try { + new ObjectId(id); + return true; + } + catch (_a) { + return false; + } + }; + /** @internal */ + ObjectId.prototype.toExtendedJSON = function () { + if (this.toHexString) + return { $oid: this.toHexString() }; + return { $oid: this.toString('hex') }; + }; + /** @internal */ + ObjectId.fromExtendedJSON = function (doc) { + return new ObjectId(doc.$oid); + }; + /** + * Converts to a string representation of this Id. + * + * @returns return the 24 character hex string representation. + * @internal + */ + ObjectId.prototype[Symbol.for('nodejs.util.inspect.custom')] = function () { + return this.inspect(); + }; + ObjectId.prototype.inspect = function () { + return "new ObjectId(\"".concat(this.toHexString(), "\")"); + }; + /** @internal */ + ObjectId.index = Math.floor(Math.random() * 0xffffff); + return ObjectId; +}()); +exports.ObjectId = ObjectId; +// Deprecated methods +Object.defineProperty(ObjectId.prototype, 'generate', { + value: (0, utils_1.deprecate)(function (time) { return ObjectId.generate(time); }, 'Please use the static `ObjectId.generate(time)` instead') +}); +Object.defineProperty(ObjectId.prototype, 'getInc', { + value: (0, utils_1.deprecate)(function () { return ObjectId.getInc(); }, 'Please use the static `ObjectId.getInc()` instead') +}); +Object.defineProperty(ObjectId.prototype, 'get_inc', { + value: (0, utils_1.deprecate)(function () { return ObjectId.getInc(); }, 'Please use the static `ObjectId.getInc()` instead') +}); +Object.defineProperty(ObjectId, 'get_inc', { + value: (0, utils_1.deprecate)(function () { return ObjectId.getInc(); }, 'Please use the static `ObjectId.getInc()` instead') +}); +Object.defineProperty(ObjectId.prototype, '_bsontype', { value: 'ObjectID' }); +//# sourceMappingURL=objectid.js.map \ No newline at end of file diff --git a/ts-ticket-office-service/node_modules/bson/lib/objectid.js.map b/ts-ticket-office-service/node_modules/bson/lib/objectid.js.map new file mode 100644 index 000000000..3238ada04 --- /dev/null +++ b/ts-ticket-office-service/node_modules/bson/lib/objectid.js.map @@ -0,0 +1 @@ +{"version":3,"file":"objectid.js","sourceRoot":"","sources":["../src/objectid.ts"],"names":[],"mappings":";;;AAAA,iCAAgC;AAChC,iDAA+C;AAC/C,iCAAwC;AACxC,wCAAsE;AAEtE,+CAA+C;AAC/C,IAAM,iBAAiB,GAAG,IAAI,MAAM,CAAC,mBAAmB,CAAC,CAAC;AAE1D,qEAAqE;AACrE,IAAI,cAAc,GAAsB,IAAI,CAA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EAAE,IAAA,iBAAS,EAAC,cAAM,OAAA,QAAQ,CAAC,MAAM,EAAE,EAAjB,CAAiB,EAAE,mDAAmD,CAAC;CAC/F,CAAC,CAAC;AAEH,MAAM,CAAC,cAAc,CAAC,QAAQ,EAAE,SAAS,EAAE;IACzC,KAAK,EAAE,IAAA,iBAAS,EAAC,cAAM,OAAA,QAAQ,CAAC,MAAM,EAAE,EAAjB,CAAiB,EAAE,mDAAmD,CAAC;CAC/F,CAAC,CAAC;AAEH,MAAM,CAAC,cAAc,CAAC,QAAQ,CAAC,SAAS,EAAE,WAAW,EAAE,EAAE,KAAK,EAAE,UAAU,EAAE,CAAC,CAAC"} \ No newline at end of file diff --git a/ts-ticket-office-service/node_modules/bson/lib/parser/calculate_size.js b/ts-ticket-office-service/node_modules/bson/lib/parser/calculate_size.js new file mode 100644 index 000000000..3d11612b6 --- /dev/null +++ b/ts-ticket-office-service/node_modules/bson/lib/parser/calculate_size.js @@ -0,0 +1,194 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.calculateObjectSize = void 0; +var buffer_1 = require("buffer"); +var binary_1 = require("../binary"); +var constants = require("../constants"); +var utils_1 = require("./utils"); +function calculateObjectSize(object, serializeFunctions, ignoreUndefined) { + var totalLength = 4 + 1; + if (Array.isArray(object)) { + for (var i = 0; i < object.length; i++) { + totalLength += calculateElement(i.toString(), object[i], serializeFunctions, true, ignoreUndefined); + } + } + else { + // If we have toBSON defined, override the current object + if (typeof (object === null || object === void 0 ? void 0 : object.toBSON) === 'function') { + object = object.toBSON(); + } + // Calculate size + for (var key in object) { + totalLength += calculateElement(key, object[key], serializeFunctions, false, ignoreUndefined); + } + } + return totalLength; +} +exports.calculateObjectSize = calculateObjectSize; +/** @internal */ +function calculateElement(name, +// eslint-disable-next-line @typescript-eslint/no-explicit-any +value, serializeFunctions, isArray, ignoreUndefined) { + if (serializeFunctions === void 0) { serializeFunctions = false; } + if (isArray === void 0) { isArray = false; } + if (ignoreUndefined === void 0) { ignoreUndefined = false; } + // If we have toBSON defined, override the current object + if (typeof (value === null || value === void 0 ? void 0 : value.toBSON) === 'function') { + value = value.toBSON(); + } + switch (typeof value) { + case 'string': + return 1 + buffer_1.Buffer.byteLength(name, 'utf8') + 1 + 4 + buffer_1.Buffer.byteLength(value, 'utf8') + 1; + case 'number': + if (Math.floor(value) === value && + value >= constants.JS_INT_MIN && + value <= constants.JS_INT_MAX) { + if (value >= constants.BSON_INT32_MIN && value <= constants.BSON_INT32_MAX) { + // 32 bit + return (name != null ? buffer_1.Buffer.byteLength(name, 'utf8') + 1 : 0) + (4 + 1); + } + else { + return (name != null ? buffer_1.Buffer.byteLength(name, 'utf8') + 1 : 0) + (8 + 1); + } + } + else { + // 64 bit + return (name != null ? buffer_1.Buffer.byteLength(name, 'utf8') + 1 : 0) + (8 + 1); + } + case 'undefined': + if (isArray || !ignoreUndefined) + return (name != null ? buffer_1.Buffer.byteLength(name, 'utf8') + 1 : 0) + 1; + return 0; + case 'boolean': + return (name != null ? buffer_1.Buffer.byteLength(name, 'utf8') + 1 : 0) + (1 + 1); + case 'object': + if (value == null || value['_bsontype'] === 'MinKey' || value['_bsontype'] === 'MaxKey') { + return (name != null ? buffer_1.Buffer.byteLength(name, 'utf8') + 1 : 0) + 1; + } + else if (value['_bsontype'] === 'ObjectId' || value['_bsontype'] === 'ObjectID') { + return (name != null ? buffer_1.Buffer.byteLength(name, 'utf8') + 1 : 0) + (12 + 1); + } + else if (value instanceof Date || (0, utils_1.isDate)(value)) { + return (name != null ? buffer_1.Buffer.byteLength(name, 'utf8') + 1 : 0) + (8 + 1); + } + else if (ArrayBuffer.isView(value) || + value instanceof ArrayBuffer || + (0, utils_1.isAnyArrayBuffer)(value)) { + return ((name != null ? buffer_1.Buffer.byteLength(name, 'utf8') + 1 : 0) + (1 + 4 + 1) + value.byteLength); + } + else if (value['_bsontype'] === 'Long' || + value['_bsontype'] === 'Double' || + value['_bsontype'] === 'Timestamp') { + return (name != null ? buffer_1.Buffer.byteLength(name, 'utf8') + 1 : 0) + (8 + 1); + } + else if (value['_bsontype'] === 'Decimal128') { + return (name != null ? buffer_1.Buffer.byteLength(name, 'utf8') + 1 : 0) + (16 + 1); + } + else if (value['_bsontype'] === 'Code') { + // Calculate size depending on the availability of a scope + if (value.scope != null && Object.keys(value.scope).length > 0) { + return ((name != null ? buffer_1.Buffer.byteLength(name, 'utf8') + 1 : 0) + + 1 + + 4 + + 4 + + buffer_1.Buffer.byteLength(value.code.toString(), 'utf8') + + 1 + + calculateObjectSize(value.scope, serializeFunctions, ignoreUndefined)); + } + else { + return ((name != null ? buffer_1.Buffer.byteLength(name, 'utf8') + 1 : 0) + + 1 + + 4 + + buffer_1.Buffer.byteLength(value.code.toString(), 'utf8') + + 1); + } + } + else if (value['_bsontype'] === 'Binary') { + var binary = value; + // Check what kind of subtype we have + if (binary.sub_type === binary_1.Binary.SUBTYPE_BYTE_ARRAY) { + return ((name != null ? buffer_1.Buffer.byteLength(name, 'utf8') + 1 : 0) + + (binary.position + 1 + 4 + 1 + 4)); + } + else { + return ((name != null ? buffer_1.Buffer.byteLength(name, 'utf8') + 1 : 0) + (binary.position + 1 + 4 + 1)); + } + } + else if (value['_bsontype'] === 'Symbol') { + return ((name != null ? buffer_1.Buffer.byteLength(name, 'utf8') + 1 : 0) + + buffer_1.Buffer.byteLength(value.value, 'utf8') + + 4 + + 1 + + 1); + } + else if (value['_bsontype'] === 'DBRef') { + // Set up correct object for serialization + var ordered_values = Object.assign({ + $ref: value.collection, + $id: value.oid + }, value.fields); + // Add db reference if it exists + if (value.db != null) { + ordered_values['$db'] = value.db; + } + return ((name != null ? buffer_1.Buffer.byteLength(name, 'utf8') + 1 : 0) + + 1 + + calculateObjectSize(ordered_values, serializeFunctions, ignoreUndefined)); + } + else if (value instanceof RegExp || (0, utils_1.isRegExp)(value)) { + return ((name != null ? buffer_1.Buffer.byteLength(name, 'utf8') + 1 : 0) + + 1 + + buffer_1.Buffer.byteLength(value.source, 'utf8') + + 1 + + (value.global ? 1 : 0) + + (value.ignoreCase ? 1 : 0) + + (value.multiline ? 1 : 0) + + 1); + } + else if (value['_bsontype'] === 'BSONRegExp') { + return ((name != null ? buffer_1.Buffer.byteLength(name, 'utf8') + 1 : 0) + + 1 + + buffer_1.Buffer.byteLength(value.pattern, 'utf8') + + 1 + + buffer_1.Buffer.byteLength(value.options, 'utf8') + + 1); + } + else { + return ((name != null ? buffer_1.Buffer.byteLength(name, 'utf8') + 1 : 0) + + calculateObjectSize(value, serializeFunctions, ignoreUndefined) + + 1); + } + case 'function': + // WTF for 0.4.X where typeof /someregexp/ === 'function' + if (value instanceof RegExp || (0, utils_1.isRegExp)(value) || String.call(value) === '[object RegExp]') { + return ((name != null ? buffer_1.Buffer.byteLength(name, 'utf8') + 1 : 0) + + 1 + + buffer_1.Buffer.byteLength(value.source, 'utf8') + + 1 + + (value.global ? 1 : 0) + + (value.ignoreCase ? 1 : 0) + + (value.multiline ? 1 : 0) + + 1); + } + else { + if (serializeFunctions && value.scope != null && Object.keys(value.scope).length > 0) { + return ((name != null ? buffer_1.Buffer.byteLength(name, 'utf8') + 1 : 0) + + 1 + + 4 + + 4 + + buffer_1.Buffer.byteLength((0, utils_1.normalizedFunctionString)(value), 'utf8') + + 1 + + calculateObjectSize(value.scope, serializeFunctions, ignoreUndefined)); + } + else if (serializeFunctions) { + return ((name != null ? buffer_1.Buffer.byteLength(name, 'utf8') + 1 : 0) + + 1 + + 4 + + buffer_1.Buffer.byteLength((0, utils_1.normalizedFunctionString)(value), 'utf8') + + 1); + } + } + } + return 0; +} +//# sourceMappingURL=calculate_size.js.map \ No newline at end of file diff --git a/ts-ticket-office-service/node_modules/bson/lib/parser/calculate_size.js.map b/ts-ticket-office-service/node_modules/bson/lib/parser/calculate_size.js.map new file mode 100644 index 000000000..f24906c17 --- /dev/null +++ b/ts-ticket-office-service/node_modules/bson/lib/parser/calculate_size.js.map @@ -0,0 +1 @@ +{"version":3,"file":"calculate_size.js","sourceRoot":"","sources":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AM,CAAC;wBAC1D,CAAC,CACF,CAAC;iBACH;aACF;KACJ;IAED,OAAO,CAAC,CAAC;AACX,CAAC"} \ No newline at end of file diff --git a/ts-ticket-office-service/node_modules/bson/lib/parser/deserializer.js b/ts-ticket-office-service/node_modules/bson/lib/parser/deserializer.js new file mode 100644 index 000000000..a011a1d2b --- /dev/null +++ b/ts-ticket-office-service/node_modules/bson/lib/parser/deserializer.js @@ -0,0 +1,659 @@ +"use strict"; +var __assign = (this && this.__assign) || function () { + __assign = Object.assign || function(t) { + for (var s, i = 1, n = arguments.length; i < n; i++) { + s = arguments[i]; + for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) + t[p] = s[p]; + } + return t; + }; + return __assign.apply(this, arguments); +}; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.deserialize = void 0; +var buffer_1 = require("buffer"); +var binary_1 = require("../binary"); +var code_1 = require("../code"); +var constants = require("../constants"); +var db_ref_1 = require("../db_ref"); +var decimal128_1 = require("../decimal128"); +var double_1 = require("../double"); +var error_1 = require("../error"); +var int_32_1 = require("../int_32"); +var long_1 = require("../long"); +var max_key_1 = require("../max_key"); +var min_key_1 = require("../min_key"); +var objectid_1 = require("../objectid"); +var regexp_1 = require("../regexp"); +var symbol_1 = require("../symbol"); +var timestamp_1 = require("../timestamp"); +var validate_utf8_1 = require("../validate_utf8"); +// Internal long versions +var JS_INT_MAX_LONG = long_1.Long.fromNumber(constants.JS_INT_MAX); +var JS_INT_MIN_LONG = long_1.Long.fromNumber(constants.JS_INT_MIN); +var functionCache = {}; +function deserialize(buffer, options, isArray) { + options = options == null ? {} : options; + var index = options && options.index ? options.index : 0; + // Read the document size + var size = buffer[index] | + (buffer[index + 1] << 8) | + (buffer[index + 2] << 16) | + (buffer[index + 3] << 24); + if (size < 5) { + throw new error_1.BSONError("bson size must be >= 5, is ".concat(size)); + } + if (options.allowObjectSmallerThanBufferSize && buffer.length < size) { + throw new error_1.BSONError("buffer length ".concat(buffer.length, " must be >= bson size ").concat(size)); + } + if (!options.allowObjectSmallerThanBufferSize && buffer.length !== size) { + throw new error_1.BSONError("buffer length ".concat(buffer.length, " must === bson size ").concat(size)); + } + if (size + index > buffer.byteLength) { + throw new error_1.BSONError("(bson size ".concat(size, " + options.index ").concat(index, " must be <= buffer length ").concat(buffer.byteLength, ")")); + } + // Illegal end value + if (buffer[index + size - 1] !== 0) { + throw new error_1.BSONError("One object, sized correctly, with a spot for an EOO, but the EOO isn't 0x00"); + } + // Start deserializtion + return deserializeObject(buffer, index, options, isArray); +} +exports.deserialize = deserialize; +var allowedDBRefKeys = /^\$ref$|^\$id$|^\$db$/; +function deserializeObject(buffer, index, options, isArray) { + if (isArray === void 0) { isArray = false; } + var evalFunctions = options['evalFunctions'] == null ? false : options['evalFunctions']; + var cacheFunctions = options['cacheFunctions'] == null ? false : options['cacheFunctions']; + var fieldsAsRaw = options['fieldsAsRaw'] == null ? null : options['fieldsAsRaw']; + // Return raw bson buffer instead of parsing it + var raw = options['raw'] == null ? false : options['raw']; + // Return BSONRegExp objects instead of native regular expressions + var bsonRegExp = typeof options['bsonRegExp'] === 'boolean' ? options['bsonRegExp'] : false; + // Controls the promotion of values vs wrapper classes + var promoteBuffers = options['promoteBuffers'] == null ? false : options['promoteBuffers']; + var promoteLongs = options['promoteLongs'] == null ? true : options['promoteLongs']; + var promoteValues = options['promoteValues'] == null ? true : options['promoteValues']; + // Ensures default validation option if none given + var validation = options.validation == null ? { utf8: true } : options.validation; + // Shows if global utf-8 validation is enabled or disabled + var globalUTFValidation = true; + // Reflects utf-8 validation setting regardless of global or specific key validation + var validationSetting; + // Set of keys either to enable or disable validation on + var utf8KeysSet = new Set(); + // Check for boolean uniformity and empty validation option + var utf8ValidatedKeys = validation.utf8; + if (typeof utf8ValidatedKeys === 'boolean') { + validationSetting = utf8ValidatedKeys; + } + else { + globalUTFValidation = false; + var utf8ValidationValues = Object.keys(utf8ValidatedKeys).map(function (key) { + return utf8ValidatedKeys[key]; + }); + if (utf8ValidationValues.length === 0) { + throw new error_1.BSONError('UTF-8 validation setting cannot be empty'); + } + if (typeof utf8ValidationValues[0] !== 'boolean') { + throw new error_1.BSONError('Invalid UTF-8 validation option, must specify boolean values'); + } + validationSetting = utf8ValidationValues[0]; + // Ensures boolean uniformity in utf-8 validation (all true or all false) + if (!utf8ValidationValues.every(function (item) { return item === validationSetting; })) { + throw new error_1.BSONError('Invalid UTF-8 validation option - keys must be all true or all false'); + } + } + // Add keys to set that will either be validated or not based on validationSetting + if (!globalUTFValidation) { + for (var _i = 0, _a = Object.keys(utf8ValidatedKeys); _i < _a.length; _i++) { + var key = _a[_i]; + utf8KeysSet.add(key); + } + } + // Set the start index + var startIndex = index; + // Validate that we have at least 4 bytes of buffer + if (buffer.length < 5) + throw new error_1.BSONError('corrupt bson message < 5 bytes long'); + // Read the document size + var size = buffer[index++] | (buffer[index++] << 8) | (buffer[index++] << 16) | (buffer[index++] << 24); + // Ensure buffer is valid size + if (size < 5 || size > buffer.length) + throw new error_1.BSONError('corrupt bson message'); + // Create holding object + var object = isArray ? [] : {}; + // Used for arrays to skip having to perform utf8 decoding + var arrayIndex = 0; + var done = false; + var isPossibleDBRef = isArray ? false : null; + // While we have more left data left keep parsing + var dataview = new DataView(buffer.buffer, buffer.byteOffset, buffer.byteLength); + while (!done) { + // Read the type + var elementType = buffer[index++]; + // If we get a zero it's the last byte, exit + if (elementType === 0) + break; + // Get the start search index + var i = index; + // Locate the end of the c string + while (buffer[i] !== 0x00 && i < buffer.length) { + i++; + } + // If are at the end of the buffer there is a problem with the document + if (i >= buffer.byteLength) + throw new error_1.BSONError('Bad BSON Document: illegal CString'); + // Represents the key + var name = isArray ? arrayIndex++ : buffer.toString('utf8', index, i); + // shouldValidateKey is true if the key should be validated, false otherwise + var shouldValidateKey = true; + if (globalUTFValidation || utf8KeysSet.has(name)) { + shouldValidateKey = validationSetting; + } + else { + shouldValidateKey = !validationSetting; + } + if (isPossibleDBRef !== false && name[0] === '$') { + isPossibleDBRef = allowedDBRefKeys.test(name); + } + var value = void 0; + index = i + 1; + if (elementType === constants.BSON_DATA_STRING) { + var stringSize = buffer[index++] | + (buffer[index++] << 8) | + (buffer[index++] << 16) | + (buffer[index++] << 24); + if (stringSize <= 0 || + stringSize > buffer.length - index || + buffer[index + stringSize - 1] !== 0) { + throw new error_1.BSONError('bad string length in bson'); + } + value = getValidatedString(buffer, index, index + stringSize - 1, shouldValidateKey); + index = index + stringSize; + } + else if (elementType === constants.BSON_DATA_OID) { + var oid = buffer_1.Buffer.alloc(12); + buffer.copy(oid, 0, index, index + 12); + value = new objectid_1.ObjectId(oid); + index = index + 12; + } + else if (elementType === constants.BSON_DATA_INT && promoteValues === false) { + value = new int_32_1.Int32(buffer[index++] | (buffer[index++] << 8) | (buffer[index++] << 16) | (buffer[index++] << 24)); + } + else if (elementType === constants.BSON_DATA_INT) { + value = + buffer[index++] | + (buffer[index++] << 8) | + (buffer[index++] << 16) | + (buffer[index++] << 24); + } + else if (elementType === constants.BSON_DATA_NUMBER && promoteValues === false) { + value = new double_1.Double(dataview.getFloat64(index, true)); + index = index + 8; + } + else if (elementType === constants.BSON_DATA_NUMBER) { + value = dataview.getFloat64(index, true); + index = index + 8; + } + else if (elementType === constants.BSON_DATA_DATE) { + var lowBits = buffer[index++] | + (buffer[index++] << 8) | + (buffer[index++] << 16) | + (buffer[index++] << 24); + var highBits = buffer[index++] | + (buffer[index++] << 8) | + (buffer[index++] << 16) | + (buffer[index++] << 24); + value = new Date(new long_1.Long(lowBits, highBits).toNumber()); + } + else if (elementType === constants.BSON_DATA_BOOLEAN) { + if (buffer[index] !== 0 && buffer[index] !== 1) + throw new error_1.BSONError('illegal boolean type value'); + value = buffer[index++] === 1; + } + else if (elementType === constants.BSON_DATA_OBJECT) { + var _index = index; + var objectSize = buffer[index] | + (buffer[index + 1] << 8) | + (buffer[index + 2] << 16) | + (buffer[index + 3] << 24); + if (objectSize <= 0 || objectSize > buffer.length - index) + throw new error_1.BSONError('bad embedded document length in bson'); + // We have a raw value + if (raw) { + value = buffer.slice(index, index + objectSize); + } + else { + var objectOptions = options; + if (!globalUTFValidation) { + objectOptions = __assign(__assign({}, options), { validation: { utf8: shouldValidateKey } }); + } + value = deserializeObject(buffer, _index, objectOptions, false); + } + index = index + objectSize; + } + else if (elementType === constants.BSON_DATA_ARRAY) { + var _index = index; + var objectSize = buffer[index] | + (buffer[index + 1] << 8) | + (buffer[index + 2] << 16) | + (buffer[index + 3] << 24); + var arrayOptions = options; + // Stop index + var stopIndex = index + objectSize; + // All elements of array to be returned as raw bson + if (fieldsAsRaw && fieldsAsRaw[name]) { + arrayOptions = {}; + for (var n in options) { + arrayOptions[n] = options[n]; + } + arrayOptions['raw'] = true; + } + if (!globalUTFValidation) { + arrayOptions = __assign(__assign({}, arrayOptions), { validation: { utf8: shouldValidateKey } }); + } + value = deserializeObject(buffer, _index, arrayOptions, true); + index = index + objectSize; + if (buffer[index - 1] !== 0) + throw new error_1.BSONError('invalid array terminator byte'); + if (index !== stopIndex) + throw new error_1.BSONError('corrupted array bson'); + } + else if (elementType === constants.BSON_DATA_UNDEFINED) { + value = undefined; + } + else if (elementType === constants.BSON_DATA_NULL) { + value = null; + } + else if (elementType === constants.BSON_DATA_LONG) { + // Unpack the low and high bits + var lowBits = buffer[index++] | + (buffer[index++] << 8) | + (buffer[index++] << 16) | + (buffer[index++] << 24); + var highBits = buffer[index++] | + (buffer[index++] << 8) | + (buffer[index++] << 16) | + (buffer[index++] << 24); + var long = new long_1.Long(lowBits, highBits); + // Promote the long if possible + if (promoteLongs && promoteValues === true) { + value = + long.lessThanOrEqual(JS_INT_MAX_LONG) && long.greaterThanOrEqual(JS_INT_MIN_LONG) + ? long.toNumber() + : long; + } + else { + value = long; + } + } + else if (elementType === constants.BSON_DATA_DECIMAL128) { + // Buffer to contain the decimal bytes + var bytes = buffer_1.Buffer.alloc(16); + // Copy the next 16 bytes into the bytes buffer + buffer.copy(bytes, 0, index, index + 16); + // Update index + index = index + 16; + // Assign the new Decimal128 value + var decimal128 = new decimal128_1.Decimal128(bytes); + // If we have an alternative mapper use that + if ('toObject' in decimal128 && typeof decimal128.toObject === 'function') { + value = decimal128.toObject(); + } + else { + value = decimal128; + } + } + else if (elementType === constants.BSON_DATA_BINARY) { + var binarySize = buffer[index++] | + (buffer[index++] << 8) | + (buffer[index++] << 16) | + (buffer[index++] << 24); + var totalBinarySize = binarySize; + var subType = buffer[index++]; + // Did we have a negative binary size, throw + if (binarySize < 0) + throw new error_1.BSONError('Negative binary type element size found'); + // Is the length longer than the document + if (binarySize > buffer.byteLength) + throw new error_1.BSONError('Binary type size larger than document size'); + // Decode as raw Buffer object if options specifies it + if (buffer['slice'] != null) { + // If we have subtype 2 skip the 4 bytes for the size + if (subType === binary_1.Binary.SUBTYPE_BYTE_ARRAY) { + binarySize = + buffer[index++] | + (buffer[index++] << 8) | + (buffer[index++] << 16) | + (buffer[index++] << 24); + if (binarySize < 0) + throw new error_1.BSONError('Negative binary type element size found for subtype 0x02'); + if (binarySize > totalBinarySize - 4) + throw new error_1.BSONError('Binary type with subtype 0x02 contains too long binary size'); + if (binarySize < totalBinarySize - 4) + throw new error_1.BSONError('Binary type with subtype 0x02 contains too short binary size'); + } + if (promoteBuffers && promoteValues) { + value = buffer.slice(index, index + binarySize); + } + else { + value = new binary_1.Binary(buffer.slice(index, index + binarySize), subType); + } + } + else { + var _buffer = buffer_1.Buffer.alloc(binarySize); + // If we have subtype 2 skip the 4 bytes for the size + if (subType === binary_1.Binary.SUBTYPE_BYTE_ARRAY) { + binarySize = + buffer[index++] | + (buffer[index++] << 8) | + (buffer[index++] << 16) | + (buffer[index++] << 24); + if (binarySize < 0) + throw new error_1.BSONError('Negative binary type element size found for subtype 0x02'); + if (binarySize > totalBinarySize - 4) + throw new error_1.BSONError('Binary type with subtype 0x02 contains too long binary size'); + if (binarySize < totalBinarySize - 4) + throw new error_1.BSONError('Binary type with subtype 0x02 contains too short binary size'); + } + // Copy the data + for (i = 0; i < binarySize; i++) { + _buffer[i] = buffer[index + i]; + } + if (promoteBuffers && promoteValues) { + value = _buffer; + } + else { + value = new binary_1.Binary(_buffer, subType); + } + } + // Update the index + index = index + binarySize; + } + else if (elementType === constants.BSON_DATA_REGEXP && bsonRegExp === false) { + // Get the start search index + i = index; + // Locate the end of the c string + while (buffer[i] !== 0x00 && i < buffer.length) { + i++; + } + // If are at the end of the buffer there is a problem with the document + if (i >= buffer.length) + throw new error_1.BSONError('Bad BSON Document: illegal CString'); + // Return the C string + var source = buffer.toString('utf8', index, i); + // Create the regexp + index = i + 1; + // Get the start search index + i = index; + // Locate the end of the c string + while (buffer[i] !== 0x00 && i < buffer.length) { + i++; + } + // If are at the end of the buffer there is a problem with the document + if (i >= buffer.length) + throw new error_1.BSONError('Bad BSON Document: illegal CString'); + // Return the C string + var regExpOptions = buffer.toString('utf8', index, i); + index = i + 1; + // For each option add the corresponding one for javascript + var optionsArray = new Array(regExpOptions.length); + // Parse options + for (i = 0; i < regExpOptions.length; i++) { + switch (regExpOptions[i]) { + case 'm': + optionsArray[i] = 'm'; + break; + case 's': + optionsArray[i] = 'g'; + break; + case 'i': + optionsArray[i] = 'i'; + break; + } + } + value = new RegExp(source, optionsArray.join('')); + } + else if (elementType === constants.BSON_DATA_REGEXP && bsonRegExp === true) { + // Get the start search index + i = index; + // Locate the end of the c string + while (buffer[i] !== 0x00 && i < buffer.length) { + i++; + } + // If are at the end of the buffer there is a problem with the document + if (i >= buffer.length) + throw new error_1.BSONError('Bad BSON Document: illegal CString'); + // Return the C string + var source = buffer.toString('utf8', index, i); + index = i + 1; + // Get the start search index + i = index; + // Locate the end of the c string + while (buffer[i] !== 0x00 && i < buffer.length) { + i++; + } + // If are at the end of the buffer there is a problem with the document + if (i >= buffer.length) + throw new error_1.BSONError('Bad BSON Document: illegal CString'); + // Return the C string + var regExpOptions = buffer.toString('utf8', index, i); + index = i + 1; + // Set the object + value = new regexp_1.BSONRegExp(source, regExpOptions); + } + else if (elementType === constants.BSON_DATA_SYMBOL) { + var stringSize = buffer[index++] | + (buffer[index++] << 8) | + (buffer[index++] << 16) | + (buffer[index++] << 24); + if (stringSize <= 0 || + stringSize > buffer.length - index || + buffer[index + stringSize - 1] !== 0) { + throw new error_1.BSONError('bad string length in bson'); + } + var symbol = getValidatedString(buffer, index, index + stringSize - 1, shouldValidateKey); + value = promoteValues ? symbol : new symbol_1.BSONSymbol(symbol); + index = index + stringSize; + } + else if (elementType === constants.BSON_DATA_TIMESTAMP) { + var lowBits = buffer[index++] | + (buffer[index++] << 8) | + (buffer[index++] << 16) | + (buffer[index++] << 24); + var highBits = buffer[index++] | + (buffer[index++] << 8) | + (buffer[index++] << 16) | + (buffer[index++] << 24); + value = new timestamp_1.Timestamp(lowBits, highBits); + } + else if (elementType === constants.BSON_DATA_MIN_KEY) { + value = new min_key_1.MinKey(); + } + else if (elementType === constants.BSON_DATA_MAX_KEY) { + value = new max_key_1.MaxKey(); + } + else if (elementType === constants.BSON_DATA_CODE) { + var stringSize = buffer[index++] | + (buffer[index++] << 8) | + (buffer[index++] << 16) | + (buffer[index++] << 24); + if (stringSize <= 0 || + stringSize > buffer.length - index || + buffer[index + stringSize - 1] !== 0) { + throw new error_1.BSONError('bad string length in bson'); + } + var functionString = getValidatedString(buffer, index, index + stringSize - 1, shouldValidateKey); + // If we are evaluating the functions + if (evalFunctions) { + // If we have cache enabled let's look for the md5 of the function in the cache + if (cacheFunctions) { + // Got to do this to avoid V8 deoptimizing the call due to finding eval + value = isolateEval(functionString, functionCache, object); + } + else { + value = isolateEval(functionString); + } + } + else { + value = new code_1.Code(functionString); + } + // Update parse index position + index = index + stringSize; + } + else if (elementType === constants.BSON_DATA_CODE_W_SCOPE) { + var totalSize = buffer[index++] | + (buffer[index++] << 8) | + (buffer[index++] << 16) | + (buffer[index++] << 24); + // Element cannot be shorter than totalSize + stringSize + documentSize + terminator + if (totalSize < 4 + 4 + 4 + 1) { + throw new error_1.BSONError('code_w_scope total size shorter minimum expected length'); + } + // Get the code string size + var stringSize = buffer[index++] | + (buffer[index++] << 8) | + (buffer[index++] << 16) | + (buffer[index++] << 24); + // Check if we have a valid string + if (stringSize <= 0 || + stringSize > buffer.length - index || + buffer[index + stringSize - 1] !== 0) { + throw new error_1.BSONError('bad string length in bson'); + } + // Javascript function + var functionString = getValidatedString(buffer, index, index + stringSize - 1, shouldValidateKey); + // Update parse index position + index = index + stringSize; + // Parse the element + var _index = index; + // Decode the size of the object document + var objectSize = buffer[index] | + (buffer[index + 1] << 8) | + (buffer[index + 2] << 16) | + (buffer[index + 3] << 24); + // Decode the scope object + var scopeObject = deserializeObject(buffer, _index, options, false); + // Adjust the index + index = index + objectSize; + // Check if field length is too short + if (totalSize < 4 + 4 + objectSize + stringSize) { + throw new error_1.BSONError('code_w_scope total size is too short, truncating scope'); + } + // Check if totalSize field is too long + if (totalSize > 4 + 4 + objectSize + stringSize) { + throw new error_1.BSONError('code_w_scope total size is too long, clips outer document'); + } + // If we are evaluating the functions + if (evalFunctions) { + // If we have cache enabled let's look for the md5 of the function in the cache + if (cacheFunctions) { + // Got to do this to avoid V8 deoptimizing the call due to finding eval + value = isolateEval(functionString, functionCache, object); + } + else { + value = isolateEval(functionString); + } + value.scope = scopeObject; + } + else { + value = new code_1.Code(functionString, scopeObject); + } + } + else if (elementType === constants.BSON_DATA_DBPOINTER) { + // Get the code string size + var stringSize = buffer[index++] | + (buffer[index++] << 8) | + (buffer[index++] << 16) | + (buffer[index++] << 24); + // Check if we have a valid string + if (stringSize <= 0 || + stringSize > buffer.length - index || + buffer[index + stringSize - 1] !== 0) + throw new error_1.BSONError('bad string length in bson'); + // Namespace + if (validation != null && validation.utf8) { + if (!(0, validate_utf8_1.validateUtf8)(buffer, index, index + stringSize - 1)) { + throw new error_1.BSONError('Invalid UTF-8 string in BSON document'); + } + } + var namespace = buffer.toString('utf8', index, index + stringSize - 1); + // Update parse index position + index = index + stringSize; + // Read the oid + var oidBuffer = buffer_1.Buffer.alloc(12); + buffer.copy(oidBuffer, 0, index, index + 12); + var oid = new objectid_1.ObjectId(oidBuffer); + // Update the index + index = index + 12; + // Upgrade to DBRef type + value = new db_ref_1.DBRef(namespace, oid); + } + else { + throw new error_1.BSONError("Detected unknown BSON type ".concat(elementType.toString(16), " for fieldname \"").concat(name, "\"")); + } + if (name === '__proto__') { + Object.defineProperty(object, name, { + value: value, + writable: true, + enumerable: true, + configurable: true + }); + } + else { + object[name] = value; + } + } + // Check if the deserialization was against a valid array/object + if (size !== index - startIndex) { + if (isArray) + throw new error_1.BSONError('corrupt array bson'); + throw new error_1.BSONError('corrupt object bson'); + } + // if we did not find "$ref", "$id", "$db", or found an extraneous $key, don't make a DBRef + if (!isPossibleDBRef) + return object; + if ((0, db_ref_1.isDBRefLike)(object)) { + var copy = Object.assign({}, object); + delete copy.$ref; + delete copy.$id; + delete copy.$db; + return new db_ref_1.DBRef(object.$ref, object.$id, object.$db, copy); + } + return object; +} +/** + * Ensure eval is isolated, store the result in functionCache. + * + * @internal + */ +function isolateEval(functionString, functionCache, object) { + // eslint-disable-next-line @typescript-eslint/no-implied-eval + if (!functionCache) + return new Function(functionString); + // Check for cache hit, eval if missing and return cached function + if (functionCache[functionString] == null) { + // eslint-disable-next-line @typescript-eslint/no-implied-eval + functionCache[functionString] = new Function(functionString); + } + // Set the object + return functionCache[functionString].bind(object); +} +function getValidatedString(buffer, start, end, shouldValidateUtf8) { + var value = buffer.toString('utf8', start, end); + // if utf8 validation is on, do the check + if (shouldValidateUtf8) { + for (var i = 0; i < value.length; i++) { + if (value.charCodeAt(i) === 0xfffd) { + if (!(0, validate_utf8_1.validateUtf8)(buffer, start, end)) { + throw new error_1.BSONError('Invalid UTF-8 string in BSON document'); + } + break; + } + } + } + return value; +} +//# sourceMappingURL=deserializer.js.map \ No newline at end of file diff --git a/ts-ticket-office-service/node_modules/bson/lib/parser/deserializer.js.map b/ts-ticket-office-service/node_modules/bson/lib/parser/deserializer.js.map new file mode 100644 index 000000000..322854706 --- /dev/null +++ b/ts-ticket-office-service/node_modules/bson/lib/parser/deserializer.js.map @@ -0,0 +1 @@ +{"version":3,"file":"deserializer.js","sourceRoot":"","sources":["../../src/parser/deserializer.ts"],"names":[],"mappings":";;;;;;;;;;;;;;AAAA,iCAAgC;AAChC,oCAAmC;AAEnC,gCAA+B;AAC/B,wCAA0C;AAC1C,oCAA0D;AAC1D,4CAA2C;AAC3C,oCAAmC;AACnC,kCAAqC;AACrC,oCAAkC;AAClC,gCAA+B;AAC/B,sCAAoC;AACpC,sCAAoC;AACpC,wCAAuC;AACvC,oCAAuC;AACvC,oCAAuC;AACvC,0CAAyC;AACzC,kDAAgD;AAgDhD,yBAAyB;AACzB,IAAM,eAAe,GAAG,WAAI,CAAC,UAAU,CAAC,SAAS,CAAC,UAAU,CAAC,CAAC;AAC9D,IAAM,eAAe,GAAG,WAAI,CAAC,UAAU,CAAC,SAAS,CAAC,UAAU,CAAC,CAAC;AAE9D,IAAM,aAAa,GAAiC,EAAE,CAAC;AAEvD,SAAgB,WAAW,CACzB,MAAc,EACd,OAA2B,EAC3B,OAAiB;IAEjB,OAAO,GAAG,OAAO,IAAI,IAAI,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,OAAO,CAAC;IACzC,IAAM,KAAK,GAAG,OAAO,IAAI,OAAO,CAAC,KAAK,CAAC,CAAC,CAAC,OAAO,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,CAAC;IAC3D,yBAAyB;IACzB,IAAM,IAAI,GACR,MAAM,CAAC,KAAK,CAAC;QACb,CAAC,MAAM,CAAC,KAAK,GAAG,CAAC,CAAC,IAAI,CAAC,CAAC;QACxB,CAAC,MAAM,CAAC,KAAK,GAAG,CAAC,CAAC,IAAI,EAAE,CAAC;QACzB,CAAC,MAAM,CAAC,KAAK,GAAG,CAAC,CAAC,IAAI,EAAE,CAAC,CAAC;IAE5B,IAAI,IAAI,GAAG,CAAC,EAAE;QACZ,MAAM,IAAI,iBAAS,CAAC,qCAA8B,IAAI,CAAE,CAAC,CAAC;KAC3D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Aa;QAAE,OAAO,IAAI,QAAQ,CAAC,cAAc,CAAC,CAAC;IACxD,kEAAkE;IAClE,IAAI,aAAa,CAAC,cAAc,CAAC,IAAI,IAAI,EAAE;QACzC,8DAA8D;QAC9D,aAAa,CAAC,cAAc,CAAC,GAAG,IAAI,QAAQ,CAAC,cAAc,CAAC,CAAC;KAC9D;IAED,iBAAiB;IACjB,OAAO,aAAa,CAAC,cAAc,CAAC,CAAC,IAAI,CAAC,MAAM,CAAC,CAAC;AACpD,CAAC;AAED,SAAS,kBAAkB,CACzB,MAAc,EACd,KAAa,EACb,GAAW,EACX,kBAA2B;IAE3B,IAAM,KAAK,GAAG,MAAM,CAAC,QAAQ,CAAC,MAAM,EAAE,KAAK,EAAE,GAAG,CAAC,CAAC;IAClD,yCAAyC;IACzC,IAAI,kBAAkB,EAAE;QACtB,KAAK,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC,GAAG,KAAK,CAAC,MAAM,EAAE,CAAC,EAAE,EAAE;YACrC,IAAI,KAAK,CAAC,UAAU,CAAC,CAAC,CAAC,KAAK,MAAM,EAAE;gBAClC,IAAI,CAAC,IAAA,4BAAY,EAAC,MAAM,EAAE,KAAK,EAAE,GAAG,CAAC,EAAE;oBACrC,MAAM,IAAI,iBAAS,CAAC,uCAAuC,CAAC,CAAC;iBAC9D;gBACD,MAAM;aACP;SACF;KACF;IACD,OAAO,KAAK,CAAC;AACf,CAAC"} \ No newline at end of file diff --git a/ts-ticket-office-service/node_modules/bson/lib/parser/serializer.js b/ts-ticket-office-service/node_modules/bson/lib/parser/serializer.js new file mode 100644 index 000000000..d99ca9611 --- /dev/null +++ b/ts-ticket-office-service/node_modules/bson/lib/parser/serializer.js @@ -0,0 +1,867 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.serializeInto = void 0; +var binary_1 = require("../binary"); +var constants = require("../constants"); +var ensure_buffer_1 = require("../ensure_buffer"); +var error_1 = require("../error"); +var extended_json_1 = require("../extended_json"); +var long_1 = require("../long"); +var map_1 = require("../map"); +var utils_1 = require("./utils"); +var regexp = /\x00/; // eslint-disable-line no-control-regex +var ignoreKeys = new Set(['$db', '$ref', '$id', '$clusterTime']); +/* + * isArray indicates if we are writing to a BSON array (type 0x04) + * which forces the "key" which really an array index as a string to be written as ascii + * This will catch any errors in index as a string generation + */ +function serializeString(buffer, key, value, index, isArray) { + // Encode String type + buffer[index++] = constants.BSON_DATA_STRING; + // Number of written bytes + var numberOfWrittenBytes = !isArray + ? buffer.write(key, index, undefined, 'utf8') + : buffer.write(key, index, undefined, 'ascii'); + // Encode the name + index = index + numberOfWrittenBytes + 1; + buffer[index - 1] = 0; + // Write the string + var size = buffer.write(value, index + 4, undefined, 'utf8'); + // Write the size of the string to buffer + buffer[index + 3] = ((size + 1) >> 24) & 0xff; + buffer[index + 2] = ((size + 1) >> 16) & 0xff; + buffer[index + 1] = ((size + 1) >> 8) & 0xff; + buffer[index] = (size + 1) & 0xff; + // Update index + index = index + 4 + size; + // Write zero + buffer[index++] = 0; + return index; +} +var SPACE_FOR_FLOAT64 = new Uint8Array(8); +var DV_FOR_FLOAT64 = new DataView(SPACE_FOR_FLOAT64.buffer, SPACE_FOR_FLOAT64.byteOffset, SPACE_FOR_FLOAT64.byteLength); +function serializeNumber(buffer, key, value, index, isArray) { + // We have an integer value + // TODO(NODE-2529): Add support for big int + if (Number.isInteger(value) && + value >= constants.BSON_INT32_MIN && + value <= constants.BSON_INT32_MAX) { + // If the value fits in 32 bits encode as int32 + // Set int type 32 bits or less + buffer[index++] = constants.BSON_DATA_INT; + // Number of written bytes + var numberOfWrittenBytes = !isArray + ? buffer.write(key, index, undefined, 'utf8') + : buffer.write(key, index, undefined, 'ascii'); + // Encode the name + index = index + numberOfWrittenBytes; + buffer[index++] = 0; + // Write the int value + buffer[index++] = value & 0xff; + buffer[index++] = (value >> 8) & 0xff; + buffer[index++] = (value >> 16) & 0xff; + buffer[index++] = (value >> 24) & 0xff; + } + else { + // Encode as double + buffer[index++] = constants.BSON_DATA_NUMBER; + // Number of written bytes + var numberOfWrittenBytes = !isArray + ? buffer.write(key, index, undefined, 'utf8') + : buffer.write(key, index, undefined, 'ascii'); + // Encode the name + index = index + numberOfWrittenBytes; + buffer[index++] = 0; + // Write float + DV_FOR_FLOAT64.setFloat64(0, value, true); + buffer.set(SPACE_FOR_FLOAT64, index); + // Adjust index + index = index + 8; + } + return index; +} +function serializeNull(buffer, key, _, index, isArray) { + // Set long type + buffer[index++] = constants.BSON_DATA_NULL; + // Number of written bytes + var numberOfWrittenBytes = !isArray + ? buffer.write(key, index, undefined, 'utf8') + : buffer.write(key, index, undefined, 'ascii'); + // Encode the name + index = index + numberOfWrittenBytes; + buffer[index++] = 0; + return index; +} +function serializeBoolean(buffer, key, value, index, isArray) { + // Write the type + buffer[index++] = constants.BSON_DATA_BOOLEAN; + // Number of written bytes + var numberOfWrittenBytes = !isArray + ? buffer.write(key, index, undefined, 'utf8') + : buffer.write(key, index, undefined, 'ascii'); + // Encode the name + index = index + numberOfWrittenBytes; + buffer[index++] = 0; + // Encode the boolean value + buffer[index++] = value ? 1 : 0; + return index; +} +function serializeDate(buffer, key, value, index, isArray) { + // Write the type + buffer[index++] = constants.BSON_DATA_DATE; + // Number of written bytes + var numberOfWrittenBytes = !isArray + ? buffer.write(key, index, undefined, 'utf8') + : buffer.write(key, index, undefined, 'ascii'); + // Encode the name + index = index + numberOfWrittenBytes; + buffer[index++] = 0; + // Write the date + var dateInMilis = long_1.Long.fromNumber(value.getTime()); + var lowBits = dateInMilis.getLowBits(); + var highBits = dateInMilis.getHighBits(); + // Encode low bits + buffer[index++] = lowBits & 0xff; + buffer[index++] = (lowBits >> 8) & 0xff; + buffer[index++] = (lowBits >> 16) & 0xff; + buffer[index++] = (lowBits >> 24) & 0xff; + // Encode high bits + buffer[index++] = highBits & 0xff; + buffer[index++] = (highBits >> 8) & 0xff; + buffer[index++] = (highBits >> 16) & 0xff; + buffer[index++] = (highBits >> 24) & 0xff; + return index; +} +function serializeRegExp(buffer, key, value, index, isArray) { + // Write the type + buffer[index++] = constants.BSON_DATA_REGEXP; + // Number of written bytes + var numberOfWrittenBytes = !isArray + ? buffer.write(key, index, undefined, 'utf8') + : buffer.write(key, index, undefined, 'ascii'); + // Encode the name + index = index + numberOfWrittenBytes; + buffer[index++] = 0; + if (value.source && value.source.match(regexp) != null) { + throw Error('value ' + value.source + ' must not contain null bytes'); + } + // Adjust the index + index = index + buffer.write(value.source, index, undefined, 'utf8'); + // Write zero + buffer[index++] = 0x00; + // Write the parameters + if (value.ignoreCase) + buffer[index++] = 0x69; // i + if (value.global) + buffer[index++] = 0x73; // s + if (value.multiline) + buffer[index++] = 0x6d; // m + // Add ending zero + buffer[index++] = 0x00; + return index; +} +function serializeBSONRegExp(buffer, key, value, index, isArray) { + // Write the type + buffer[index++] = constants.BSON_DATA_REGEXP; + // Number of written bytes + var numberOfWrittenBytes = !isArray + ? buffer.write(key, index, undefined, 'utf8') + : buffer.write(key, index, undefined, 'ascii'); + // Encode the name + index = index + numberOfWrittenBytes; + buffer[index++] = 0; + // Check the pattern for 0 bytes + if (value.pattern.match(regexp) != null) { + // The BSON spec doesn't allow keys with null bytes because keys are + // null-terminated. + throw Error('pattern ' + value.pattern + ' must not contain null bytes'); + } + // Adjust the index + index = index + buffer.write(value.pattern, index, undefined, 'utf8'); + // Write zero + buffer[index++] = 0x00; + // Write the options + index = index + buffer.write(value.options.split('').sort().join(''), index, undefined, 'utf8'); + // Add ending zero + buffer[index++] = 0x00; + return index; +} +function serializeMinMax(buffer, key, value, index, isArray) { + // Write the type of either min or max key + if (value === null) { + buffer[index++] = constants.BSON_DATA_NULL; + } + else if (value._bsontype === 'MinKey') { + buffer[index++] = constants.BSON_DATA_MIN_KEY; + } + else { + buffer[index++] = constants.BSON_DATA_MAX_KEY; + } + // Number of written bytes + var numberOfWrittenBytes = !isArray + ? buffer.write(key, index, undefined, 'utf8') + : buffer.write(key, index, undefined, 'ascii'); + // Encode the name + index = index + numberOfWrittenBytes; + buffer[index++] = 0; + return index; +} +function serializeObjectId(buffer, key, value, index, isArray) { + // Write the type + buffer[index++] = constants.BSON_DATA_OID; + // Number of written bytes + var numberOfWrittenBytes = !isArray + ? buffer.write(key, index, undefined, 'utf8') + : buffer.write(key, index, undefined, 'ascii'); + // Encode the name + index = index + numberOfWrittenBytes; + buffer[index++] = 0; + // Write the objectId into the shared buffer + if (typeof value.id === 'string') { + buffer.write(value.id, index, undefined, 'binary'); + } + else if ((0, utils_1.isUint8Array)(value.id)) { + // Use the standard JS methods here because buffer.copy() is buggy with the + // browser polyfill + buffer.set(value.id.subarray(0, 12), index); + } + else { + throw new error_1.BSONTypeError('object [' + JSON.stringify(value) + '] is not a valid ObjectId'); + } + // Adjust index + return index + 12; +} +function serializeBuffer(buffer, key, value, index, isArray) { + // Write the type + buffer[index++] = constants.BSON_DATA_BINARY; + // Number of written bytes + var numberOfWrittenBytes = !isArray + ? buffer.write(key, index, undefined, 'utf8') + : buffer.write(key, index, undefined, 'ascii'); + // Encode the name + index = index + numberOfWrittenBytes; + buffer[index++] = 0; + // Get size of the buffer (current write point) + var size = value.length; + // Write the size of the string to buffer + buffer[index++] = size & 0xff; + buffer[index++] = (size >> 8) & 0xff; + buffer[index++] = (size >> 16) & 0xff; + buffer[index++] = (size >> 24) & 0xff; + // Write the default subtype + buffer[index++] = constants.BSON_BINARY_SUBTYPE_DEFAULT; + // Copy the content form the binary field to the buffer + buffer.set((0, ensure_buffer_1.ensureBuffer)(value), index); + // Adjust the index + index = index + size; + return index; +} +function serializeObject(buffer, key, value, index, checkKeys, depth, serializeFunctions, ignoreUndefined, isArray, path) { + if (checkKeys === void 0) { checkKeys = false; } + if (depth === void 0) { depth = 0; } + if (serializeFunctions === void 0) { serializeFunctions = false; } + if (ignoreUndefined === void 0) { ignoreUndefined = true; } + if (isArray === void 0) { isArray = false; } + if (path === void 0) { path = []; } + for (var i = 0; i < path.length; i++) { + if (path[i] === value) + throw new error_1.BSONError('cyclic dependency detected'); + } + // Push value to stack + path.push(value); + // Write the type + buffer[index++] = Array.isArray(value) ? constants.BSON_DATA_ARRAY : constants.BSON_DATA_OBJECT; + // Number of written bytes + var numberOfWrittenBytes = !isArray + ? buffer.write(key, index, undefined, 'utf8') + : buffer.write(key, index, undefined, 'ascii'); + // Encode the name + index = index + numberOfWrittenBytes; + buffer[index++] = 0; + var endIndex = serializeInto(buffer, value, checkKeys, index, depth + 1, serializeFunctions, ignoreUndefined, path); + // Pop stack + path.pop(); + return endIndex; +} +function serializeDecimal128(buffer, key, value, index, isArray) { + buffer[index++] = constants.BSON_DATA_DECIMAL128; + // Number of written bytes + var numberOfWrittenBytes = !isArray + ? buffer.write(key, index, undefined, 'utf8') + : buffer.write(key, index, undefined, 'ascii'); + // Encode the name + index = index + numberOfWrittenBytes; + buffer[index++] = 0; + // Write the data from the value + // Prefer the standard JS methods because their typechecking is not buggy, + // unlike the `buffer` polyfill's. + buffer.set(value.bytes.subarray(0, 16), index); + return index + 16; +} +function serializeLong(buffer, key, value, index, isArray) { + // Write the type + buffer[index++] = + value._bsontype === 'Long' ? constants.BSON_DATA_LONG : constants.BSON_DATA_TIMESTAMP; + // Number of written bytes + var numberOfWrittenBytes = !isArray + ? buffer.write(key, index, undefined, 'utf8') + : buffer.write(key, index, undefined, 'ascii'); + // Encode the name + index = index + numberOfWrittenBytes; + buffer[index++] = 0; + // Write the date + var lowBits = value.getLowBits(); + var highBits = value.getHighBits(); + // Encode low bits + buffer[index++] = lowBits & 0xff; + buffer[index++] = (lowBits >> 8) & 0xff; + buffer[index++] = (lowBits >> 16) & 0xff; + buffer[index++] = (lowBits >> 24) & 0xff; + // Encode high bits + buffer[index++] = highBits & 0xff; + buffer[index++] = (highBits >> 8) & 0xff; + buffer[index++] = (highBits >> 16) & 0xff; + buffer[index++] = (highBits >> 24) & 0xff; + return index; +} +function serializeInt32(buffer, key, value, index, isArray) { + value = value.valueOf(); + // Set int type 32 bits or less + buffer[index++] = constants.BSON_DATA_INT; + // Number of written bytes + var numberOfWrittenBytes = !isArray + ? buffer.write(key, index, undefined, 'utf8') + : buffer.write(key, index, undefined, 'ascii'); + // Encode the name + index = index + numberOfWrittenBytes; + buffer[index++] = 0; + // Write the int value + buffer[index++] = value & 0xff; + buffer[index++] = (value >> 8) & 0xff; + buffer[index++] = (value >> 16) & 0xff; + buffer[index++] = (value >> 24) & 0xff; + return index; +} +function serializeDouble(buffer, key, value, index, isArray) { + // Encode as double + buffer[index++] = constants.BSON_DATA_NUMBER; + // Number of written bytes + var numberOfWrittenBytes = !isArray + ? buffer.write(key, index, undefined, 'utf8') + : buffer.write(key, index, undefined, 'ascii'); + // Encode the name + index = index + numberOfWrittenBytes; + buffer[index++] = 0; + // Write float + DV_FOR_FLOAT64.setFloat64(0, value.value, true); + buffer.set(SPACE_FOR_FLOAT64, index); + // Adjust index + index = index + 8; + return index; +} +function serializeFunction(buffer, key, value, index, _checkKeys, _depth, isArray) { + if (_checkKeys === void 0) { _checkKeys = false; } + if (_depth === void 0) { _depth = 0; } + buffer[index++] = constants.BSON_DATA_CODE; + // Number of written bytes + var numberOfWrittenBytes = !isArray + ? buffer.write(key, index, undefined, 'utf8') + : buffer.write(key, index, undefined, 'ascii'); + // Encode the name + index = index + numberOfWrittenBytes; + buffer[index++] = 0; + // Function string + var functionString = (0, utils_1.normalizedFunctionString)(value); + // Write the string + var size = buffer.write(functionString, index + 4, undefined, 'utf8') + 1; + // Write the size of the string to buffer + buffer[index] = size & 0xff; + buffer[index + 1] = (size >> 8) & 0xff; + buffer[index + 2] = (size >> 16) & 0xff; + buffer[index + 3] = (size >> 24) & 0xff; + // Update index + index = index + 4 + size - 1; + // Write zero + buffer[index++] = 0; + return index; +} +function serializeCode(buffer, key, value, index, checkKeys, depth, serializeFunctions, ignoreUndefined, isArray) { + if (checkKeys === void 0) { checkKeys = false; } + if (depth === void 0) { depth = 0; } + if (serializeFunctions === void 0) { serializeFunctions = false; } + if (ignoreUndefined === void 0) { ignoreUndefined = true; } + if (isArray === void 0) { isArray = false; } + if (value.scope && typeof value.scope === 'object') { + // Write the type + buffer[index++] = constants.BSON_DATA_CODE_W_SCOPE; + // Number of written bytes + var numberOfWrittenBytes = !isArray + ? buffer.write(key, index, undefined, 'utf8') + : buffer.write(key, index, undefined, 'ascii'); + // Encode the name + index = index + numberOfWrittenBytes; + buffer[index++] = 0; + // Starting index + var startIndex = index; + // Serialize the function + // Get the function string + var functionString = typeof value.code === 'string' ? value.code : value.code.toString(); + // Index adjustment + index = index + 4; + // Write string into buffer + var codeSize = buffer.write(functionString, index + 4, undefined, 'utf8') + 1; + // Write the size of the string to buffer + buffer[index] = codeSize & 0xff; + buffer[index + 1] = (codeSize >> 8) & 0xff; + buffer[index + 2] = (codeSize >> 16) & 0xff; + buffer[index + 3] = (codeSize >> 24) & 0xff; + // Write end 0 + buffer[index + 4 + codeSize - 1] = 0; + // Write the + index = index + codeSize + 4; + // + // Serialize the scope value + var endIndex = serializeInto(buffer, value.scope, checkKeys, index, depth + 1, serializeFunctions, ignoreUndefined); + index = endIndex - 1; + // Writ the total + var totalSize = endIndex - startIndex; + // Write the total size of the object + buffer[startIndex++] = totalSize & 0xff; + buffer[startIndex++] = (totalSize >> 8) & 0xff; + buffer[startIndex++] = (totalSize >> 16) & 0xff; + buffer[startIndex++] = (totalSize >> 24) & 0xff; + // Write trailing zero + buffer[index++] = 0; + } + else { + buffer[index++] = constants.BSON_DATA_CODE; + // Number of written bytes + var numberOfWrittenBytes = !isArray + ? buffer.write(key, index, undefined, 'utf8') + : buffer.write(key, index, undefined, 'ascii'); + // Encode the name + index = index + numberOfWrittenBytes; + buffer[index++] = 0; + // Function string + var functionString = value.code.toString(); + // Write the string + var size = buffer.write(functionString, index + 4, undefined, 'utf8') + 1; + // Write the size of the string to buffer + buffer[index] = size & 0xff; + buffer[index + 1] = (size >> 8) & 0xff; + buffer[index + 2] = (size >> 16) & 0xff; + buffer[index + 3] = (size >> 24) & 0xff; + // Update index + index = index + 4 + size - 1; + // Write zero + buffer[index++] = 0; + } + return index; +} +function serializeBinary(buffer, key, value, index, isArray) { + // Write the type + buffer[index++] = constants.BSON_DATA_BINARY; + // Number of written bytes + var numberOfWrittenBytes = !isArray + ? buffer.write(key, index, undefined, 'utf8') + : buffer.write(key, index, undefined, 'ascii'); + // Encode the name + index = index + numberOfWrittenBytes; + buffer[index++] = 0; + // Extract the buffer + var data = value.value(true); + // Calculate size + var size = value.position; + // Add the deprecated 02 type 4 bytes of size to total + if (value.sub_type === binary_1.Binary.SUBTYPE_BYTE_ARRAY) + size = size + 4; + // Write the size of the string to buffer + buffer[index++] = size & 0xff; + buffer[index++] = (size >> 8) & 0xff; + buffer[index++] = (size >> 16) & 0xff; + buffer[index++] = (size >> 24) & 0xff; + // Write the subtype to the buffer + buffer[index++] = value.sub_type; + // If we have binary type 2 the 4 first bytes are the size + if (value.sub_type === binary_1.Binary.SUBTYPE_BYTE_ARRAY) { + size = size - 4; + buffer[index++] = size & 0xff; + buffer[index++] = (size >> 8) & 0xff; + buffer[index++] = (size >> 16) & 0xff; + buffer[index++] = (size >> 24) & 0xff; + } + // Write the data to the object + buffer.set(data, index); + // Adjust the index + index = index + value.position; + return index; +} +function serializeSymbol(buffer, key, value, index, isArray) { + // Write the type + buffer[index++] = constants.BSON_DATA_SYMBOL; + // Number of written bytes + var numberOfWrittenBytes = !isArray + ? buffer.write(key, index, undefined, 'utf8') + : buffer.write(key, index, undefined, 'ascii'); + // Encode the name + index = index + numberOfWrittenBytes; + buffer[index++] = 0; + // Write the string + var size = buffer.write(value.value, index + 4, undefined, 'utf8') + 1; + // Write the size of the string to buffer + buffer[index] = size & 0xff; + buffer[index + 1] = (size >> 8) & 0xff; + buffer[index + 2] = (size >> 16) & 0xff; + buffer[index + 3] = (size >> 24) & 0xff; + // Update index + index = index + 4 + size - 1; + // Write zero + buffer[index++] = 0x00; + return index; +} +function serializeDBRef(buffer, key, value, index, depth, serializeFunctions, isArray) { + // Write the type + buffer[index++] = constants.BSON_DATA_OBJECT; + // Number of written bytes + var numberOfWrittenBytes = !isArray + ? buffer.write(key, index, undefined, 'utf8') + : buffer.write(key, index, undefined, 'ascii'); + // Encode the name + index = index + numberOfWrittenBytes; + buffer[index++] = 0; + var startIndex = index; + var output = { + $ref: value.collection || value.namespace, + $id: value.oid + }; + if (value.db != null) { + output.$db = value.db; + } + output = Object.assign(output, value.fields); + var endIndex = serializeInto(buffer, output, false, index, depth + 1, serializeFunctions); + // Calculate object size + var size = endIndex - startIndex; + // Write the size + buffer[startIndex++] = size & 0xff; + buffer[startIndex++] = (size >> 8) & 0xff; + buffer[startIndex++] = (size >> 16) & 0xff; + buffer[startIndex++] = (size >> 24) & 0xff; + // Set index + return endIndex; +} +function serializeInto(buffer, object, checkKeys, startingIndex, depth, serializeFunctions, ignoreUndefined, path) { + if (checkKeys === void 0) { checkKeys = false; } + if (startingIndex === void 0) { startingIndex = 0; } + if (depth === void 0) { depth = 0; } + if (serializeFunctions === void 0) { serializeFunctions = false; } + if (ignoreUndefined === void 0) { ignoreUndefined = true; } + if (path === void 0) { path = []; } + startingIndex = startingIndex || 0; + path = path || []; + // Push the object to the path + path.push(object); + // Start place to serialize into + var index = startingIndex + 4; + // Special case isArray + if (Array.isArray(object)) { + // Get object keys + for (var i = 0; i < object.length; i++) { + var key = "".concat(i); + var value = object[i]; + // Is there an override value + if (typeof (value === null || value === void 0 ? void 0 : value.toBSON) === 'function') { + value = value.toBSON(); + } + if (typeof value === 'string') { + index = serializeString(buffer, key, value, index, true); + } + else if (typeof value === 'number') { + index = serializeNumber(buffer, key, value, index, true); + } + else if (typeof value === 'bigint') { + throw new error_1.BSONTypeError('Unsupported type BigInt, please use Decimal128'); + } + else if (typeof value === 'boolean') { + index = serializeBoolean(buffer, key, value, index, true); + } + else if (value instanceof Date || (0, utils_1.isDate)(value)) { + index = serializeDate(buffer, key, value, index, true); + } + else if (value === undefined) { + index = serializeNull(buffer, key, value, index, true); + } + else if (value === null) { + index = serializeNull(buffer, key, value, index, true); + } + else if (value['_bsontype'] === 'ObjectId' || value['_bsontype'] === 'ObjectID') { + index = serializeObjectId(buffer, key, value, index, true); + } + else if ((0, utils_1.isUint8Array)(value)) { + index = serializeBuffer(buffer, key, value, index, true); + } + else if (value instanceof RegExp || (0, utils_1.isRegExp)(value)) { + index = serializeRegExp(buffer, key, value, index, true); + } + else if (typeof value === 'object' && value['_bsontype'] == null) { + index = serializeObject(buffer, key, value, index, checkKeys, depth, serializeFunctions, ignoreUndefined, true, path); + } + else if (typeof value === 'object' && + (0, extended_json_1.isBSONType)(value) && + value._bsontype === 'Decimal128') { + index = serializeDecimal128(buffer, key, value, index, true); + } + else if (value['_bsontype'] === 'Long' || value['_bsontype'] === 'Timestamp') { + index = serializeLong(buffer, key, value, index, true); + } + else if (value['_bsontype'] === 'Double') { + index = serializeDouble(buffer, key, value, index, true); + } + else if (typeof value === 'function' && serializeFunctions) { + index = serializeFunction(buffer, key, value, index, checkKeys, depth, true); + } + else if (value['_bsontype'] === 'Code') { + index = serializeCode(buffer, key, value, index, checkKeys, depth, serializeFunctions, ignoreUndefined, true); + } + else if (value['_bsontype'] === 'Binary') { + index = serializeBinary(buffer, key, value, index, true); + } + else if (value['_bsontype'] === 'Symbol') { + index = serializeSymbol(buffer, key, value, index, true); + } + else if (value['_bsontype'] === 'DBRef') { + index = serializeDBRef(buffer, key, value, index, depth, serializeFunctions, true); + } + else if (value['_bsontype'] === 'BSONRegExp') { + index = serializeBSONRegExp(buffer, key, value, index, true); + } + else if (value['_bsontype'] === 'Int32') { + index = serializeInt32(buffer, key, value, index, true); + } + else if (value['_bsontype'] === 'MinKey' || value['_bsontype'] === 'MaxKey') { + index = serializeMinMax(buffer, key, value, index, true); + } + else if (typeof value['_bsontype'] !== 'undefined') { + throw new error_1.BSONTypeError("Unrecognized or invalid _bsontype: ".concat(String(value['_bsontype']))); + } + } + } + else if (object instanceof map_1.Map || (0, utils_1.isMap)(object)) { + var iterator = object.entries(); + var done = false; + while (!done) { + // Unpack the next entry + var entry = iterator.next(); + done = !!entry.done; + // Are we done, then skip and terminate + if (done) + continue; + // Get the entry values + var key = entry.value[0]; + var value = entry.value[1]; + // Check the type of the value + var type = typeof value; + // Check the key and throw error if it's illegal + if (typeof key === 'string' && !ignoreKeys.has(key)) { + if (key.match(regexp) != null) { + // The BSON spec doesn't allow keys with null bytes because keys are + // null-terminated. + throw Error('key ' + key + ' must not contain null bytes'); + } + if (checkKeys) { + if ('$' === key[0]) { + throw Error('key ' + key + " must not start with '$'"); + } + else if (~key.indexOf('.')) { + throw Error('key ' + key + " must not contain '.'"); + } + } + } + if (type === 'string') { + index = serializeString(buffer, key, value, index); + } + else if (type === 'number') { + index = serializeNumber(buffer, key, value, index); + } + else if (type === 'bigint' || (0, utils_1.isBigInt64Array)(value) || (0, utils_1.isBigUInt64Array)(value)) { + throw new error_1.BSONTypeError('Unsupported type BigInt, please use Decimal128'); + } + else if (type === 'boolean') { + index = serializeBoolean(buffer, key, value, index); + } + else if (value instanceof Date || (0, utils_1.isDate)(value)) { + index = serializeDate(buffer, key, value, index); + } + else if (value === null || (value === undefined && ignoreUndefined === false)) { + index = serializeNull(buffer, key, value, index); + } + else if (value['_bsontype'] === 'ObjectId' || value['_bsontype'] === 'ObjectID') { + index = serializeObjectId(buffer, key, value, index); + } + else if ((0, utils_1.isUint8Array)(value)) { + index = serializeBuffer(buffer, key, value, index); + } + else if (value instanceof RegExp || (0, utils_1.isRegExp)(value)) { + index = serializeRegExp(buffer, key, value, index); + } + else if (type === 'object' && value['_bsontype'] == null) { + index = serializeObject(buffer, key, value, index, checkKeys, depth, serializeFunctions, ignoreUndefined, false, path); + } + else if (type === 'object' && value['_bsontype'] === 'Decimal128') { + index = serializeDecimal128(buffer, key, value, index); + } + else if (value['_bsontype'] === 'Long' || value['_bsontype'] === 'Timestamp') { + index = serializeLong(buffer, key, value, index); + } + else if (value['_bsontype'] === 'Double') { + index = serializeDouble(buffer, key, value, index); + } + else if (value['_bsontype'] === 'Code') { + index = serializeCode(buffer, key, value, index, checkKeys, depth, serializeFunctions, ignoreUndefined); + } + else if (typeof value === 'function' && serializeFunctions) { + index = serializeFunction(buffer, key, value, index, checkKeys, depth, serializeFunctions); + } + else if (value['_bsontype'] === 'Binary') { + index = serializeBinary(buffer, key, value, index); + } + else if (value['_bsontype'] === 'Symbol') { + index = serializeSymbol(buffer, key, value, index); + } + else if (value['_bsontype'] === 'DBRef') { + index = serializeDBRef(buffer, key, value, index, depth, serializeFunctions); + } + else if (value['_bsontype'] === 'BSONRegExp') { + index = serializeBSONRegExp(buffer, key, value, index); + } + else if (value['_bsontype'] === 'Int32') { + index = serializeInt32(buffer, key, value, index); + } + else if (value['_bsontype'] === 'MinKey' || value['_bsontype'] === 'MaxKey') { + index = serializeMinMax(buffer, key, value, index); + } + else if (typeof value['_bsontype'] !== 'undefined') { + throw new error_1.BSONTypeError("Unrecognized or invalid _bsontype: ".concat(String(value['_bsontype']))); + } + } + } + else { + if (typeof (object === null || object === void 0 ? void 0 : object.toBSON) === 'function') { + // Provided a custom serialization method + object = object.toBSON(); + if (object != null && typeof object !== 'object') { + throw new error_1.BSONTypeError('toBSON function did not return an object'); + } + } + // Iterate over all the keys + for (var key in object) { + var value = object[key]; + // Is there an override value + if (typeof (value === null || value === void 0 ? void 0 : value.toBSON) === 'function') { + value = value.toBSON(); + } + // Check the type of the value + var type = typeof value; + // Check the key and throw error if it's illegal + if (typeof key === 'string' && !ignoreKeys.has(key)) { + if (key.match(regexp) != null) { + // The BSON spec doesn't allow keys with null bytes because keys are + // null-terminated. + throw Error('key ' + key + ' must not contain null bytes'); + } + if (checkKeys) { + if ('$' === key[0]) { + throw Error('key ' + key + " must not start with '$'"); + } + else if (~key.indexOf('.')) { + throw Error('key ' + key + " must not contain '.'"); + } + } + } + if (type === 'string') { + index = serializeString(buffer, key, value, index); + } + else if (type === 'number') { + index = serializeNumber(buffer, key, value, index); + } + else if (type === 'bigint') { + throw new error_1.BSONTypeError('Unsupported type BigInt, please use Decimal128'); + } + else if (type === 'boolean') { + index = serializeBoolean(buffer, key, value, index); + } + else if (value instanceof Date || (0, utils_1.isDate)(value)) { + index = serializeDate(buffer, key, value, index); + } + else if (value === undefined) { + if (ignoreUndefined === false) + index = serializeNull(buffer, key, value, index); + } + else if (value === null) { + index = serializeNull(buffer, key, value, index); + } + else if (value['_bsontype'] === 'ObjectId' || value['_bsontype'] === 'ObjectID') { + index = serializeObjectId(buffer, key, value, index); + } + else if ((0, utils_1.isUint8Array)(value)) { + index = serializeBuffer(buffer, key, value, index); + } + else if (value instanceof RegExp || (0, utils_1.isRegExp)(value)) { + index = serializeRegExp(buffer, key, value, index); + } + else if (type === 'object' && value['_bsontype'] == null) { + index = serializeObject(buffer, key, value, index, checkKeys, depth, serializeFunctions, ignoreUndefined, false, path); + } + else if (type === 'object' && value['_bsontype'] === 'Decimal128') { + index = serializeDecimal128(buffer, key, value, index); + } + else if (value['_bsontype'] === 'Long' || value['_bsontype'] === 'Timestamp') { + index = serializeLong(buffer, key, value, index); + } + else if (value['_bsontype'] === 'Double') { + index = serializeDouble(buffer, key, value, index); + } + else if (value['_bsontype'] === 'Code') { + index = serializeCode(buffer, key, value, index, checkKeys, depth, serializeFunctions, ignoreUndefined); + } + else if (typeof value === 'function' && serializeFunctions) { + index = serializeFunction(buffer, key, value, index, checkKeys, depth, serializeFunctions); + } + else if (value['_bsontype'] === 'Binary') { + index = serializeBinary(buffer, key, value, index); + } + else if (value['_bsontype'] === 'Symbol') { + index = serializeSymbol(buffer, key, value, index); + } + else if (value['_bsontype'] === 'DBRef') { + index = serializeDBRef(buffer, key, value, index, depth, serializeFunctions); + } + else if (value['_bsontype'] === 'BSONRegExp') { + index = serializeBSONRegExp(buffer, key, value, index); + } + else if (value['_bsontype'] === 'Int32') { + index = serializeInt32(buffer, key, value, index); + } + else if (value['_bsontype'] === 'MinKey' || value['_bsontype'] === 'MaxKey') { + index = serializeMinMax(buffer, key, value, index); + } + else if (typeof value['_bsontype'] !== 'undefined') { + throw new error_1.BSONTypeError("Unrecognized or invalid _bsontype: ".concat(String(value['_bsontype']))); + } + } + } + // Remove the path + path.pop(); + // Final padding byte for object + buffer[index++] = 0x00; + // Final size + var size = index - startingIndex; + // Write the size of the object + buffer[startingIndex++] = size & 0xff; + buffer[startingIndex++] = (size >> 8) & 0xff; + buffer[startingIndex++] = (size >> 16) & 0xff; + buffer[startingIndex++] = (size >> 24) & 0xff; + return index; +} +exports.serializeInto = serializeInto; +//# sourceMappingURL=serializer.js.map \ No newline at end of file diff --git a/ts-ticket-office-service/node_modules/bson/lib/parser/serializer.js.map b/ts-ticket-office-service/node_modules/bson/lib/parser/serializer.js.map new file mode 100644 index 000000000..3261fd40f --- /dev/null +++ b/ts-ticket-office-service/node_modules/bson/lib/parser/serializer.js.map @@ -0,0 +1 @@ +{"version":3,"file":"serializer.js","sourceRoot":"","sources":["../../src/parser/serializer.ts"],"names":[],"mappings":";;;AACA,oCAAmC;AAGnC,wCAA0C;AAI1C,kDAAgD;AAChD,kCAAoD;AACpD,kDAA8C;AAE9C,gCAA+B;AAC/B,8BAA6B;AAI7B,iCAQiB;AAgBjB,IAAM,MAAM,GAAG,MAAM,CAAC,CAAC,uCAAuC;AAC9D,IAAM,UAAU,GAAG,IAAI,GAAG,CAAC,CAAC,KAAK,EAAE,MAAM,EAAE,KAAK,EAAE,cAAc,CAAC,CAAC,CAAC;AAEnE;;;;GAIG;AAEH,SAAS,eAAe,CACtB,MAAc,EACd,GAAW,EACX,KAAa,EACb,KAAa,EACb,OAAiB;IAEjB,qBAAqB;IACrB,MAAM,CAAC,KAAK,EAAE,CAAC,GAAG,SAAS,CAAC,gBAAgB,CAAC;IAC7C,0BAA0B;IAC1B,IAAM,oBAAoB,GAAG,CAAC,OAAO;QACnC,CAAC,CAAC,MAAM,CAAC,KAAK,CAAC,GAAG,EAAE,KAAK,EAAE,SAAS,EAAE,MAAM,CAAC;QAC7C,CAAC,CAAC,MAAM,CAAC,KAAK,CAAC,GAAG,EAAE,KAAK,EAAE,SAAS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,CAAC;aAC7F;SACF;KACF;IAED,kBAAkB;IAClB,IAAI,CAAC,GAAG,EAAE,CAAC;IAEX,gCAAgC;IAChC,MAAM,CAAC,KAAK,EAAE,CAAC,GAAG,IAAI,CAAC;IAEvB,aAAa;IACb,IAAM,IAAI,GAAG,KAAK,GAAG,aAAa,CAAC;IACnC,+BAA+B;IAC/B,MAAM,CAAC,aAAa,EAAE,CAAC,GAAG,IAAI,GAAG,IAAI,CAAC;IACtC,MAAM,CAAC,aAAa,EAAE,CAAC,GAAG,CAAC,IAAI,IAAI,CAAC,CAAC,GAAG,IAAI,CAAC;IAC7C,MAAM,CAAC,aAAa,EAAE,CAAC,GAAG,CAAC,IAAI,IAAI,EAAE,CAAC,GAAG,IAAI,CAAC;IAC9C,MAAM,CAAC,aAAa,EAAE,CAAC,GAAG,CAAC,IAAI,IAAI,EAAE,CAAC,GAAG,IAAI,CAAC;IAC9C,OAAO,KAAK,CAAC;AACf,CAAC;AAtUD,sCAsUC"} \ No newline at end of file diff --git a/ts-ticket-office-service/node_modules/bson/lib/parser/utils.js b/ts-ticket-office-service/node_modules/bson/lib/parser/utils.js new file mode 100644 index 000000000..94e8b5fc5 --- /dev/null +++ b/ts-ticket-office-service/node_modules/bson/lib/parser/utils.js @@ -0,0 +1,115 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.deprecate = exports.isObjectLike = exports.isDate = exports.haveBuffer = exports.isMap = exports.isRegExp = exports.isBigUInt64Array = exports.isBigInt64Array = exports.isUint8Array = exports.isAnyArrayBuffer = exports.randomBytes = exports.normalizedFunctionString = void 0; +var buffer_1 = require("buffer"); +var global_1 = require("../utils/global"); +/** + * Normalizes our expected stringified form of a function across versions of node + * @param fn - The function to stringify + */ +function normalizedFunctionString(fn) { + return fn.toString().replace('function(', 'function ('); +} +exports.normalizedFunctionString = normalizedFunctionString; +function isReactNative() { + var g = (0, global_1.getGlobal)(); + return typeof g.navigator === 'object' && g.navigator.product === 'ReactNative'; +} +var insecureRandomBytes = function insecureRandomBytes(size) { + var insecureWarning = isReactNative() + ? 'BSON: For React Native please polyfill crypto.getRandomValues, e.g. using: https://www.npmjs.com/package/react-native-get-random-values.' + : 'BSON: No cryptographic implementation for random bytes present, falling back to a less secure implementation.'; + console.warn(insecureWarning); + var result = buffer_1.Buffer.alloc(size); + for (var i = 0; i < size; ++i) + result[i] = Math.floor(Math.random() * 256); + return result; +}; +var detectRandomBytes = function () { + if (process.browser) { + if (typeof window !== 'undefined') { + // browser crypto implementation(s) + var target_1 = window.crypto || window.msCrypto; // allow for IE11 + if (target_1 && target_1.getRandomValues) { + return function (size) { return target_1.getRandomValues(buffer_1.Buffer.alloc(size)); }; + } + } + if (typeof global !== 'undefined' && global.crypto && global.crypto.getRandomValues) { + // allow for RN packages such as https://www.npmjs.com/package/react-native-get-random-values to populate global + return function (size) { return global.crypto.getRandomValues(buffer_1.Buffer.alloc(size)); }; + } + return insecureRandomBytes; + } + else { + var requiredRandomBytes = void 0; + try { + requiredRandomBytes = require('crypto').randomBytes; + } + catch (e) { + // keep the fallback + } + // NOTE: in transpiled cases the above require might return null/undefined + return requiredRandomBytes || insecureRandomBytes; + } +}; +exports.randomBytes = detectRandomBytes(); +function isAnyArrayBuffer(value) { + return ['[object ArrayBuffer]', '[object SharedArrayBuffer]'].includes(Object.prototype.toString.call(value)); +} +exports.isAnyArrayBuffer = isAnyArrayBuffer; +function isUint8Array(value) { + return Object.prototype.toString.call(value) === '[object Uint8Array]'; +} +exports.isUint8Array = isUint8Array; +function isBigInt64Array(value) { + return Object.prototype.toString.call(value) === '[object BigInt64Array]'; +} +exports.isBigInt64Array = isBigInt64Array; +function isBigUInt64Array(value) { + return Object.prototype.toString.call(value) === '[object BigUint64Array]'; +} +exports.isBigUInt64Array = isBigUInt64Array; +function isRegExp(d) { + return Object.prototype.toString.call(d) === '[object RegExp]'; +} +exports.isRegExp = isRegExp; +function isMap(d) { + return Object.prototype.toString.call(d) === '[object Map]'; +} +exports.isMap = isMap; +/** Call to check if your environment has `Buffer` */ +function haveBuffer() { + return typeof global !== 'undefined' && typeof global.Buffer !== 'undefined'; +} +exports.haveBuffer = haveBuffer; +// To ensure that 0.4 of node works correctly +function isDate(d) { + return isObjectLike(d) && Object.prototype.toString.call(d) === '[object Date]'; +} +exports.isDate = isDate; +/** + * @internal + * this is to solve the `'someKey' in x` problem where x is unknown. + * https://github.com/typescript-eslint/typescript-eslint/issues/1071#issuecomment-541955753 + */ +function isObjectLike(candidate) { + return typeof candidate === 'object' && candidate !== null; +} +exports.isObjectLike = isObjectLike; +function deprecate(fn, message) { + var warned = false; + function deprecated() { + var args = []; + for (var _i = 0; _i < arguments.length; _i++) { + args[_i] = arguments[_i]; + } + if (!warned) { + console.warn(message); + warned = true; + } + return fn.apply(this, args); + } + return deprecated; +} +exports.deprecate = deprecate; +//# sourceMappingURL=utils.js.map \ No newline at end of file diff --git a/ts-ticket-office-service/node_modules/bson/lib/parser/utils.js.map b/ts-ticket-office-service/node_modules/bson/lib/parser/utils.js.map new file mode 100644 index 000000000..6eba4a9bd --- /dev/null +++ b/ts-ticket-office-service/node_modules/bson/lib/parser/utils.js.map @@ -0,0 +1 @@ +{"version":3,"file":"utils.js","sourceRoot":"","sources":["../../src/parser/utils.ts"],"names":[],"mappings":";;;AAAA,iCAAgC;AAChC,0CAA4C;AAI5C;;;GAGG;AACH,SAAgB,wBAAwB,CAAC,EAAY;IACnD,OAAO,EAAE,CAAC,QAAQ,EAAE,CAAC,OAAO,CAAC,WAAW,EAAE,YAAY,CAAC,CAAC;AAC1D,CAAC;AAFD,4DAEC;AAED,SAAS,aAAa;IACpB,IAAM,CAAC,GAAG,IAAA,kBAAS,GAAwC,CAAC;IAC5D,OAAO,OAAO,CAAC,CAAC,SAAS,KAAK,QAAQ,IAAI,CAAC,CAAC,SAAS,CAAC,OAAO,KAAK,aAAa,CAAC;AAClF,CAAC;AAED,IAAM,mBAAmB,GAAwB,SAAS,mBAAmB,CAAC,IAAY;IACxF,IAAM,eA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AAC/E,CAAC;AAFD,gCAEC;AAED,6CAA6C;AAC7C,SAAgB,MAAM,CAAC,CAAU;IAC/B,OAAO,YAAY,CAAC,CAAC,CAAC,IAAI,MAAM,CAAC,SAAS,CAAC,QAAQ,CAAC,IAAI,CAAC,CAAC,CAAC,KAAK,eAAe,CAAC;AAClF,CAAC;AAFD,wBAEC;AAED;;;;GAIG;AACH,SAAgB,YAAY,CAAC,SAAkB;IAC7C,OAAO,OAAO,SAAS,KAAK,QAAQ,IAAI,SAAS,KAAK,IAAI,CAAC;AAC7D,CAAC;AAFD,oCAEC;AAGD,SAAgB,SAAS,CAAqB,EAAK,EAAE,OAAe;IAClE,IAAI,MAAM,GAAG,KAAK,CAAC;IACnB,SAAS,UAAU;QAAgB,cAAkB;aAAlB,UAAkB,EAAlB,qBAAkB,EAAlB,IAAkB;YAAlB,yBAAkB;;QACnD,IAAI,CAAC,MAAM,EAAE;YACX,OAAO,CAAC,IAAI,CAAC,OAAO,CAAC,CAAC;YACtB,MAAM,GAAG,IAAI,CAAC;SACf;QACD,OAAO,EAAE,CAAC,KAAK,CAAC,IAAI,EAAE,IAAI,CAAC,CAAC;IAC9B,CAAC;IACD,OAAO,UAA0B,CAAC;AACpC,CAAC;AAVD,8BAUC"} \ No newline at end of file diff --git a/ts-ticket-office-service/node_modules/bson/lib/regexp.js b/ts-ticket-office-service/node_modules/bson/lib/regexp.js new file mode 100644 index 000000000..bc1f230cc --- /dev/null +++ b/ts-ticket-office-service/node_modules/bson/lib/regexp.js @@ -0,0 +1,74 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.BSONRegExp = void 0; +var error_1 = require("./error"); +function alphabetize(str) { + return str.split('').sort().join(''); +} +/** + * A class representation of the BSON RegExp type. + * @public + * @category BSONType + */ +var BSONRegExp = /** @class */ (function () { + /** + * @param pattern - The regular expression pattern to match + * @param options - The regular expression options + */ + function BSONRegExp(pattern, options) { + if (!(this instanceof BSONRegExp)) + return new BSONRegExp(pattern, options); + this.pattern = pattern; + this.options = alphabetize(options !== null && options !== void 0 ? options : ''); + if (this.pattern.indexOf('\x00') !== -1) { + throw new error_1.BSONError("BSON Regex patterns cannot contain null bytes, found: ".concat(JSON.stringify(this.pattern))); + } + if (this.options.indexOf('\x00') !== -1) { + throw new error_1.BSONError("BSON Regex options cannot contain null bytes, found: ".concat(JSON.stringify(this.options))); + } + // Validate options + for (var i = 0; i < this.options.length; i++) { + if (!(this.options[i] === 'i' || + this.options[i] === 'm' || + this.options[i] === 'x' || + this.options[i] === 'l' || + this.options[i] === 's' || + this.options[i] === 'u')) { + throw new error_1.BSONError("The regular expression option [".concat(this.options[i], "] is not supported")); + } + } + } + BSONRegExp.parseOptions = function (options) { + return options ? options.split('').sort().join('') : ''; + }; + /** @internal */ + BSONRegExp.prototype.toExtendedJSON = function (options) { + options = options || {}; + if (options.legacy) { + return { $regex: this.pattern, $options: this.options }; + } + return { $regularExpression: { pattern: this.pattern, options: this.options } }; + }; + /** @internal */ + BSONRegExp.fromExtendedJSON = function (doc) { + if ('$regex' in doc) { + if (typeof doc.$regex !== 'string') { + // This is for $regex query operators that have extended json values. + if (doc.$regex._bsontype === 'BSONRegExp') { + return doc; + } + } + else { + return new BSONRegExp(doc.$regex, BSONRegExp.parseOptions(doc.$options)); + } + } + if ('$regularExpression' in doc) { + return new BSONRegExp(doc.$regularExpression.pattern, BSONRegExp.parseOptions(doc.$regularExpression.options)); + } + throw new error_1.BSONTypeError("Unexpected BSONRegExp EJSON object form: ".concat(JSON.stringify(doc))); + }; + return BSONRegExp; +}()); +exports.BSONRegExp = BSONRegExp; +Object.defineProperty(BSONRegExp.prototype, '_bsontype', { value: 'BSONRegExp' }); +//# sourceMappingURL=regexp.js.map \ No newline at end of file diff --git a/ts-ticket-office-service/node_modules/bson/lib/regexp.js.map b/ts-ticket-office-service/node_modules/bson/lib/regexp.js.map new file mode 100644 index 000000000..134381759 --- /dev/null +++ b/ts-ticket-office-service/node_modules/bson/lib/regexp.js.map @@ -0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AAC,CAAC,CAAC;aAC1E;SACF;QACD,IAAI,oBAAoB,IAAI,GAAG,EAAE;YAC/B,OAAO,IAAI,UAAU,CACnB,GAAG,CAAC,kBAAkB,CAAC,OAAO,EAC9B,UAAU,CAAC,YAAY,CAAC,GAAG,CAAC,kBAAkB,CAAC,OAAO,CAAC,CACxD,CAAC;SACH;QACD,MAAM,IAAI,qBAAa,CAAC,mDAA4C,IAAI,CAAC,SAAS,CAAC,GAAG,CAAC,CAAE,CAAC,CAAC;IAC7F,CAAC;IACH,iBAAC;AAAD,CAAC,AA5ED,IA4EC;AA5EY,gCAAU;AA8EvB,MAAM,CAAC,cAAc,CAAC,UAAU,CAAC,SAAS,EAAE,WAAW,EAAE,EAAE,KAAK,EAAE,YAAY,EAAE,CAAC,CAAC"} \ No newline at end of file diff --git a/ts-ticket-office-service/node_modules/bson/lib/symbol.js b/ts-ticket-office-service/node_modules/bson/lib/symbol.js new file mode 100644 index 000000000..cad93173f --- /dev/null +++ b/ts-ticket-office-service/node_modules/bson/lib/symbol.js @@ -0,0 +1,48 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.BSONSymbol = void 0; +/** + * A class representation of the BSON Symbol type. + * @public + * @category BSONType + */ +var BSONSymbol = /** @class */ (function () { + /** + * @param value - the string representing the symbol. + */ + function BSONSymbol(value) { + if (!(this instanceof BSONSymbol)) + return new BSONSymbol(value); + this.value = value; + } + /** Access the wrapped string value. */ + BSONSymbol.prototype.valueOf = function () { + return this.value; + }; + BSONSymbol.prototype.toString = function () { + return this.value; + }; + /** @internal */ + BSONSymbol.prototype.inspect = function () { + return "new BSONSymbol(\"".concat(this.value, "\")"); + }; + BSONSymbol.prototype.toJSON = function () { + return this.value; + }; + /** @internal */ + BSONSymbol.prototype.toExtendedJSON = function () { + return { $symbol: this.value }; + }; + /** @internal */ + BSONSymbol.fromExtendedJSON = function (doc) { + return new BSONSymbol(doc.$symbol); + }; + /** @internal */ + BSONSymbol.prototype[Symbol.for('nodejs.util.inspect.custom')] = function () { + return this.inspect(); + }; + return BSONSymbol; +}()); +exports.BSONSymbol = BSONSymbol; +Object.defineProperty(BSONSymbol.prototype, '_bsontype', { value: 'Symbol' }); +//# sourceMappingURL=symbol.js.map \ No newline at end of file diff --git a/ts-ticket-office-service/node_modules/bson/lib/symbol.js.map b/ts-ticket-office-service/node_modules/bson/lib/symbol.js.map new file mode 100644 index 000000000..3662444d7 --- /dev/null +++ b/ts-ticket-office-service/node_modules/bson/lib/symbol.js.map @@ -0,0 +1 @@ +{"version":3,"file":"symbol.js","sourceRoot":"","sources":["../src/symbol.ts"],"names":[],"mappings":";;;AAKA;;;;GAIG;AACH;IAIE;;OAEG;IACH,oBAAY,KAAa;QACvB,IAAI,CAAC,CAAC,IAAI,YAAY,UAAU,CAAC;YAAE,OAAO,IAAI,UAAU,CAAC,KAAK,CAAC,CAAC;QAEhE,IAAI,CAAC,KAAK,GAAG,KAAK,CAAC;IACrB,CAAC;IAED,uCAAuC;IACvC,4BAAO,GAAP;QACE,OAAO,IAAI,CAAC,KAAK,CAAC;IACpB,CAAC;IAED,6BAAQ,GAAR;QACE,OAAO,IAAI,CAAC,KAAK,CAAC;IACpB,CAAC;IAED,gBAAgB;IAChB,4BAAO,GAAP;QACE,OAAO,2BAAmB,IAAI,CAAC,KAAK,QAAI,CAAC;IAC3C,CAAC;IAED,2BAAM,GAAN;QACE,OAAO,IAAI,CAAC,KAAK,CAAC;IACpB,CAAC;IAED,gBAAgB;IAChB,mCAAc,GAAd;QACE,OAAO,EAAE,OAAO,EAAE,IAAI,CAAC,KAAK,EAAE,CAAC;IACjC,CAAC;IAED,gBAAgB;IACT,2BAAgB,GAAvB,UAAwB,GAAuB;QAC7C,OAAO,IAAI,UAAU,CAAC,GAAG,CAAC,OAAO,CAAC,CAAC;IACrC,CAAC;IAED,gBAAgB;IAChB,qBAAC,MAAM,CAAC,GAAG,CAAC,4BAA4B,CAAC,CAAC,GAA1C;QACE,OAAO,IAAI,CAAC,OAAO,EAAE,CAAC;IACxB,CAAC;IACH,iBAAC;AAAD,CAAC,AA7CD,IA6CC;AA7CY,gCAAU;AA+CvB,MAAM,CAAC,cAAc,CAAC,UAAU,CAAC,SAAS,EAAE,WAAW,EAAE,EAAE,KAAK,EAAE,QAAQ,EAAE,CAAC,CAAC"} \ No newline at end of file diff --git a/ts-ticket-office-service/node_modules/bson/lib/timestamp.js b/ts-ticket-office-service/node_modules/bson/lib/timestamp.js new file mode 100644 index 000000000..a3a8417c2 --- /dev/null +++ b/ts-ticket-office-service/node_modules/bson/lib/timestamp.js @@ -0,0 +1,102 @@ +"use strict"; +var __extends = (this && this.__extends) || (function () { + var extendStatics = function (d, b) { + extendStatics = Object.setPrototypeOf || + ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || + function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; }; + return extendStatics(d, b); + }; + return function (d, b) { + if (typeof b !== "function" && b !== null) + throw new TypeError("Class extends value " + String(b) + " is not a constructor or null"); + extendStatics(d, b); + function __() { this.constructor = d; } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); + }; +})(); +Object.defineProperty(exports, "__esModule", { value: true }); +exports.Timestamp = exports.LongWithoutOverridesClass = void 0; +var long_1 = require("./long"); +var utils_1 = require("./parser/utils"); +/** @public */ +exports.LongWithoutOverridesClass = long_1.Long; +/** + * @public + * @category BSONType + * */ +var Timestamp = /** @class */ (function (_super) { + __extends(Timestamp, _super); + function Timestamp(low, high) { + var _this = this; + // eslint-disable-next-line @typescript-eslint/ban-ts-comment + // @ts-expect-error + if (!(_this instanceof Timestamp)) + return new Timestamp(low, high); + if (long_1.Long.isLong(low)) { + _this = _super.call(this, low.low, low.high, true) || this; + } + else if ((0, utils_1.isObjectLike)(low) && typeof low.t !== 'undefined' && typeof low.i !== 'undefined') { + _this = _super.call(this, low.i, low.t, true) || this; + } + else { + _this = _super.call(this, low, high, true) || this; + } + Object.defineProperty(_this, '_bsontype', { + value: 'Timestamp', + writable: false, + configurable: false, + enumerable: false + }); + return _this; + } + Timestamp.prototype.toJSON = function () { + return { + $timestamp: this.toString() + }; + }; + /** Returns a Timestamp represented by the given (32-bit) integer value. */ + Timestamp.fromInt = function (value) { + return new Timestamp(long_1.Long.fromInt(value, true)); + }; + /** Returns a Timestamp representing the given number value, provided that it is a finite number. Otherwise, zero is returned. */ + Timestamp.fromNumber = function (value) { + return new Timestamp(long_1.Long.fromNumber(value, true)); + }; + /** + * Returns a Timestamp for the given high and low bits. Each is assumed to use 32 bits. + * + * @param lowBits - the low 32-bits. + * @param highBits - the high 32-bits. + */ + Timestamp.fromBits = function (lowBits, highBits) { + return new Timestamp(lowBits, highBits); + }; + /** + * Returns a Timestamp from the given string, optionally using the given radix. + * + * @param str - the textual representation of the Timestamp. + * @param optRadix - the radix in which the text is written. + */ + Timestamp.fromString = function (str, optRadix) { + return new Timestamp(long_1.Long.fromString(str, true, optRadix)); + }; + /** @internal */ + Timestamp.prototype.toExtendedJSON = function () { + return { $timestamp: { t: this.high >>> 0, i: this.low >>> 0 } }; + }; + /** @internal */ + Timestamp.fromExtendedJSON = function (doc) { + return new Timestamp(doc.$timestamp); + }; + /** @internal */ + Timestamp.prototype[Symbol.for('nodejs.util.inspect.custom')] = function () { + return this.inspect(); + }; + Timestamp.prototype.inspect = function () { + return "new Timestamp({ t: ".concat(this.getHighBits(), ", i: ").concat(this.getLowBits(), " })"); + }; + Timestamp.MAX_VALUE = long_1.Long.MAX_UNSIGNED_VALUE; + return Timestamp; +}(exports.LongWithoutOverridesClass)); +exports.Timestamp = Timestamp; +//# sourceMappingURL=timestamp.js.map \ No newline at end of file diff --git a/ts-ticket-office-service/node_modules/bson/lib/timestamp.js.map b/ts-ticket-office-service/node_modules/bson/lib/timestamp.js.map new file mode 100644 index 000000000..e1a8bef95 --- /dev/null +++ b/ts-ticket-office-service/node_modules/bson/lib/timestamp.js.map @@ -0,0 +1 @@ +{"version":3,"file":"timestam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C;IAClD,CAAC;IAED,iIAAiI;IAC1H,oBAAU,GAAjB,UAAkB,KAAa;QAC7B,OAAO,IAAI,SAAS,CAAC,WAAI,CAAC,UAAU,CAAC,KAAK,EAAE,IAAI,CAAC,CAAC,CAAC;IACrD,CAAC;IAED;;;;;OAKG;IACI,kBAAQ,GAAf,UAAgB,OAAe,EAAE,QAAgB;QAC/C,OAAO,IAAI,SAAS,CAAC,OAAO,EAAE,QAAQ,CAAC,CAAC;IAC1C,CAAC;IAED;;;;;OAKG;IACI,oBAAU,GAAjB,UAAkB,GAAW,EAAE,QAAgB;QAC7C,OAAO,IAAI,SAAS,CAAC,WAAI,CAAC,UAAU,CAAC,GAAG,EAAE,IAAI,EAAE,QAAQ,CAAC,CAAC,CAAC;IAC7D,CAAC;IAED,gBAAgB;IAChB,kCAAc,GAAd;QACE,OAAO,EAAE,UAAU,EAAE,EAAE,CAAC,EAAE,IAAI,CAAC,IAAI,KAAK,CAAC,EAAE,CAAC,EAAE,IAAI,CAAC,GAAG,KAAK,CAAC,EAAE,EAAE,CAAC;IACnE,CAAC;IAED,gBAAgB;IACT,0BAAgB,GAAvB,UAAwB,GAAsB;QAC5C,OAAO,IAAI,SAAS,CAAC,GAAG,CAAC,UAAU,CAAC,CAAC;IACvC,CAAC;IAED,gBAAgB;IAChB,oBAAC,MAAM,CAAC,GAAG,CAAC,4BAA4B,CAAC,CAAC,GAA1C;QACE,OAAO,IAAI,CAAC,OAAO,EAAE,CAAC;IACxB,CAAC;IAED,2BAAO,GAAP;QACE,OAAO,6BAAsB,IAAI,CAAC,WAAW,EAAE,kBAAQ,IAAI,CAAC,UAAU,EAAE,QAAK,CAAC;IAChF,CAAC;IAzFe,mBAAS,GAAG,WAAI,CAAC,kBAAkB,CAAC;IA0FtD,gBAAC;CAAA,AA7FD,CAA+B,iCAAyB,GA6FvD;AA7FY,8BAAS"} \ No newline at end of file diff --git a/ts-ticket-office-service/node_modules/bson/lib/utils/global.js b/ts-ticket-office-service/node_modules/bson/lib/utils/global.js new file mode 100644 index 000000000..f4bf44405 --- /dev/null +++ b/ts-ticket-office-service/node_modules/bson/lib/utils/global.js @@ -0,0 +1,18 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.getGlobal = void 0; +function checkForMath(potentialGlobal) { + // eslint-disable-next-line eqeqeq + return potentialGlobal && potentialGlobal.Math == Math && potentialGlobal; +} +// https://github.com/zloirock/core-js/issues/86#issuecomment-115759028 +function getGlobal() { + return (checkForMath(typeof globalThis === 'object' && globalThis) || + checkForMath(typeof window === 'object' && window) || + checkForMath(typeof self === 'object' && self) || + checkForMath(typeof global === 'object' && global) || + // eslint-disable-next-line @typescript-eslint/no-implied-eval + Function('return this')()); +} +exports.getGlobal = getGlobal; +//# sourceMappingURL=global.js.map \ No newline at end of file diff --git a/ts-ticket-office-service/node_modules/bson/lib/utils/global.js.map b/ts-ticket-office-service/node_modules/bson/lib/utils/global.js.map new file mode 100644 index 000000000..9d4ad7995 --- /dev/null +++ b/ts-ticket-office-service/node_modules/bson/lib/utils/global.js.map @@ -0,0 +1 @@ +{"version":3,"file":"global.js","sourceRoot":"","sources":["../../src/utils/global.ts"],"names":[],"mappings":";;;AAMA,SAAS,YAAY,CAAC,eAAoB;IACxC,kCAAkC;IAClC,OAAO,eAAe,IAAI,eAAe,CAAC,IAAI,IAAI,IAAI,IAAI,eAAe,CAAC;AAC5E,CAAC;AAED,uEAAuE;AACvE,SAAgB,SAAS;IACvB,OAAO,CACL,YAAY,CAAC,OAAO,UAAU,KAAK,QAAQ,IAAI,UAAU,CAAC;QAC1D,YAAY,CAAC,OAAO,MAAM,KAAK,QAAQ,IAAI,MAAM,CAAC;QAClD,YAAY,CAAC,OAAO,IAAI,KAAK,QAAQ,IAAI,IAAI,CAAC;QAC9C,YAAY,CAAC,OAAO,MAAM,KAAK,QAAQ,IAAI,MAAM,CAAC;QAClD,8DAA8D;QAC9D,QAAQ,CAAC,aAAa,CAAC,EAAE,CAC1B,CAAC;AACJ,CAAC;AATD,8BASC"} \ No newline at end of file diff --git a/ts-ticket-office-service/node_modules/bson/lib/uuid.js b/ts-ticket-office-service/node_modules/bson/lib/uuid.js new file mode 100644 index 000000000..481b1da0c --- /dev/null +++ b/ts-ticket-office-service/node_modules/bson/lib/uuid.js @@ -0,0 +1,179 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.UUID = void 0; +var buffer_1 = require("buffer"); +var ensure_buffer_1 = require("./ensure_buffer"); +var binary_1 = require("./binary"); +var uuid_utils_1 = require("./uuid_utils"); +var utils_1 = require("./parser/utils"); +var error_1 = require("./error"); +var BYTE_LENGTH = 16; +var kId = Symbol('id'); +/** + * A class representation of the BSON UUID type. + * @public + */ +var UUID = /** @class */ (function () { + /** + * Create an UUID type + * + * @param input - Can be a 32 or 36 character hex string (dashes excluded/included) or a 16 byte binary Buffer. + */ + function UUID(input) { + if (typeof input === 'undefined') { + // The most common use case (blank id, new UUID() instance) + this.id = UUID.generate(); + } + else if (input instanceof UUID) { + this[kId] = buffer_1.Buffer.from(input.id); + this.__id = input.__id; + } + else if (ArrayBuffer.isView(input) && input.byteLength === BYTE_LENGTH) { + this.id = (0, ensure_buffer_1.ensureBuffer)(input); + } + else if (typeof input === 'string') { + this.id = (0, uuid_utils_1.uuidHexStringToBuffer)(input); + } + else { + throw new error_1.BSONTypeError('Argument passed in UUID constructor must be a UUID, a 16 byte Buffer or a 32/36 character hex string (dashes excluded/included, format: xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx).'); + } + } + Object.defineProperty(UUID.prototype, "id", { + /** + * The UUID bytes + * @readonly + */ + get: function () { + return this[kId]; + }, + set: function (value) { + this[kId] = value; + if (UUID.cacheHexString) { + this.__id = (0, uuid_utils_1.bufferToUuidHexString)(value); + } + }, + enumerable: false, + configurable: true + }); + /** + * Generate a 16 byte uuid v4 buffer used in UUIDs + */ + /** + * Returns the UUID id as a 32 or 36 character hex string representation, excluding/including dashes (defaults to 36 character dash separated) + * @param includeDashes - should the string exclude dash-separators. + * */ + UUID.prototype.toHexString = function (includeDashes) { + if (includeDashes === void 0) { includeDashes = true; } + if (UUID.cacheHexString && this.__id) { + return this.__id; + } + var uuidHexString = (0, uuid_utils_1.bufferToUuidHexString)(this.id, includeDashes); + if (UUID.cacheHexString) { + this.__id = uuidHexString; + } + return uuidHexString; + }; + /** + * Converts the id into a 36 character (dashes included) hex string, unless a encoding is specified. + */ + UUID.prototype.toString = function (encoding) { + return encoding ? this.id.toString(encoding) : this.toHexString(); + }; + /** + * Converts the id into its JSON string representation. + * A 36 character (dashes included) hex string in the format: xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx + */ + UUID.prototype.toJSON = function () { + return this.toHexString(); + }; + /** + * Compares the equality of this UUID with `otherID`. + * + * @param otherId - UUID instance to compare against. + */ + UUID.prototype.equals = function (otherId) { + if (!otherId) { + return false; + } + if (otherId instanceof UUID) { + return otherId.id.equals(this.id); + } + try { + return new UUID(otherId).id.equals(this.id); + } + catch (_a) { + return false; + } + }; + /** + * Creates a Binary instance from the current UUID. + */ + UUID.prototype.toBinary = function () { + return new binary_1.Binary(this.id, binary_1.Binary.SUBTYPE_UUID); + }; + /** + * Generates a populated buffer containing a v4 uuid + */ + UUID.generate = function () { + var bytes = (0, utils_1.randomBytes)(BYTE_LENGTH); + // Per 4.4, set bits for version and `clock_seq_hi_and_reserved` + // Kindly borrowed from https://github.com/uuidjs/uuid/blob/master/src/v4.js + bytes[6] = (bytes[6] & 0x0f) | 0x40; + bytes[8] = (bytes[8] & 0x3f) | 0x80; + return buffer_1.Buffer.from(bytes); + }; + /** + * Checks if a value is a valid bson UUID + * @param input - UUID, string or Buffer to validate. + */ + UUID.isValid = function (input) { + if (!input) { + return false; + } + if (input instanceof UUID) { + return true; + } + if (typeof input === 'string') { + return (0, uuid_utils_1.uuidValidateString)(input); + } + if ((0, utils_1.isUint8Array)(input)) { + // check for length & uuid version (https://tools.ietf.org/html/rfc4122#section-4.1.3) + if (input.length !== BYTE_LENGTH) { + return false; + } + try { + // get this byte as hex: xxxxxxxx-xxxx-XXxx-xxxx-xxxxxxxxxxxx + // check first part as uuid version: xxxxxxxx-xxxx-Xxxx-xxxx-xxxxxxxxxxxx + return parseInt(input[6].toString(16)[0], 10) === binary_1.Binary.SUBTYPE_UUID; + } + catch (_a) { + return false; + } + } + return false; + }; + /** + * Creates an UUID from a hex string representation of an UUID. + * @param hexString - 32 or 36 character hex string (dashes excluded/included). + */ + UUID.createFromHexString = function (hexString) { + var buffer = (0, uuid_utils_1.uuidHexStringToBuffer)(hexString); + return new UUID(buffer); + }; + /** + * Converts to a string representation of this Id. + * + * @returns return the 36 character hex string representation. + * @internal + */ + UUID.prototype[Symbol.for('nodejs.util.inspect.custom')] = function () { + return this.inspect(); + }; + UUID.prototype.inspect = function () { + return "new UUID(\"".concat(this.toHexString(), "\")"); + }; + return UUID; +}()); +exports.UUID = UUID; +Object.defineProperty(UUID.prototype, '_bsontype', { value: 'UUID' }); +//# sourceMappingURL=uuid.js.map \ No newline at end of file diff --git a/ts-ticket-office-service/node_modules/bson/lib/uuid.js.map b/ts-ticket-office-service/node_modules/bson/lib/uuid.js.map new file mode 100644 index 000000000..046e51d18 --- /dev/null +++ b/ts-ticket-office-service/node_modules/bson/lib/uuid.js.map @@ -0,0 +1 @@ +{"version":3,"file":"uuid.js","sourceRoot":"","sources":["../src/uuid.ts"],"names":[],"mappings":";;;AAAA,iCAAgC;AAChC,iDAA+C;AAC/C,mCAAkC;AAClC,2CAAgG;AAChG,wCAA2D;AAC3D,iCAAwC;AAOxC,IAAM,WAAW,GAAG,EAAE,CAAC;AAEvB,IAAM,GAAG,GAAG,MAAM,CAAC,IAAI,CAAC,CAAC;AAEzB;;;GAGG;AACH;IAWE;;;;OAIG;IACH,cAAY,KAA8B;QACxC,IAAI,OAAO,KAAK,KAAK,WAAW,EAAE;YAChC,2DAA2D;YAC3D,IAAI,CAAC,EAAE,GAAG,IAAI,CAAC,QAAQ,EAAE,CAA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node_modules/bson/lib/uuid_utils.js b/ts-ticket-office-service/node_modules/bson/lib/uuid_utils.js new file mode 100644 index 000000000..bb1f8b7e6 --- /dev/null +++ b/ts-ticket-office-service/node_modules/bson/lib/uuid_utils.js @@ -0,0 +1,35 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.bufferToUuidHexString = exports.uuidHexStringToBuffer = exports.uuidValidateString = void 0; +var buffer_1 = require("buffer"); +var error_1 = require("./error"); +// Validation regex for v4 uuid (validates with or without dashes) +var VALIDATION_REGEX = /^(?:[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}|[0-9a-f]{12}4[0-9a-f]{3}[89ab][0-9a-f]{15})$/i; +var uuidValidateString = function (str) { + return typeof str === 'string' && VALIDATION_REGEX.test(str); +}; +exports.uuidValidateString = uuidValidateString; +var uuidHexStringToBuffer = function (hexString) { + if (!(0, exports.uuidValidateString)(hexString)) { + throw new error_1.BSONTypeError('UUID string representations must be a 32 or 36 character hex string (dashes excluded/included). Format: "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" or "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx".'); + } + var sanitizedHexString = hexString.replace(/-/g, ''); + return buffer_1.Buffer.from(sanitizedHexString, 'hex'); +}; +exports.uuidHexStringToBuffer = uuidHexStringToBuffer; +var bufferToUuidHexString = function (buffer, includeDashes) { + if (includeDashes === void 0) { includeDashes = true; } + return includeDashes + ? buffer.toString('hex', 0, 4) + + '-' + + buffer.toString('hex', 4, 6) + + '-' + + buffer.toString('hex', 6, 8) + + '-' + + buffer.toString('hex', 8, 10) + + '-' + + buffer.toString('hex', 10, 16) + : buffer.toString('hex'); +}; +exports.bufferToUuidHexString = bufferToUuidHexString; +//# sourceMappingURL=uuid_utils.js.map \ No newline at end of file diff --git a/ts-ticket-office-service/node_modules/bson/lib/uuid_utils.js.map b/ts-ticket-office-service/node_modules/bson/lib/uuid_utils.js.map new file mode 100644 index 000000000..f388ec318 --- /dev/null +++ b/ts-ticket-office-service/node_modules/bson/lib/uuid_utils.js.map @@ -0,0 +1 @@ +{"version":3,"file":"uuid_utils.js","sourceRoot":"","sources":["../src/uuid_utils.ts"],"names":[],"mappings":";;;AAAA,iCAAgC;AAChC,iCAAwC;AAExC,kEAAkE;AAClE,IAAM,gBAAgB,GACpB,uHAAuH,CAAC;AAEnH,IAAM,kBAAkB,GAAG,UAAC,GAAW;IAC5C,OAAA,OAAO,GAAG,KAAK,QAAQ,IAAI,gBAAgB,CAAC,IAAI,CAAC,GAAG,CAAC;AAArD,CAAqD,CAAC;AAD3C,QAAA,kBAAkB,sBACyB;AAEjD,IAAM,qBAAqB,GAAG,UAAC,SAAiB;IACrD,IAAI,CAAC,IAAA,0BAAkB,EAAC,SAAS,CAAC,EAAE;QAClC,MAAM,IAAI,qBAAa,CACrB,uLAAuL,CACxL,CAAC;KACH;IAED,IAAM,kBAAkB,GAAG,SAAS,CAAC,OAAO,CAAC,IAAI,EAAE,EAAE,CAAC,CAAC;IACvD,OAAO,eAAM,CAAC,IAAI,CAAC,kBAAkB,EAAE,KAAK,CAAC,CAAC;AAChD,CAAC,CAAC;AATW,QAAA,qBAAqB,yBAShC;AAEK,IAAM,qBAAqB,GAAG,UAAC,MAAc,EAAE,aAAoB;IAApB,8BAAA,EAAA,oBAAoB;IACxE,OAAA,aAAa;QACX,CAAC,CAAC,MAAM,CAAC,QAAQ,CAAC,KAAK,EAAE,CAAC,EAAE,CAAC,CAAC;YAC5B,GAAG;YACH,MAAM,CAAC,QAAQ,CAAC,KAAK,EAAE,CAAC,EAAE,CAAC,CAAC;YAC5B,GAAG;YACH,MAAM,CAAC,QAAQ,CAAC,KAAK,EAAE,CAAC,EAAE,CAAC,CAAC;YAC5B,GAAG;YACH,MAAM,CAAC,QAAQ,CAAC,KAAK,EAAE,CAAC,EAAE,EAAE,CAAC;YAC7B,GAAG;YACH,MAAM,CAAC,QAAQ,CAAC,KAAK,EAAE,EAAE,EAAE,EAAE,CAAC;QAChC,CAAC,CAAC,MAAM,CAAC,QAAQ,CAAC,KAAK,CAAC;AAV1B,CAU0B,CAAC;AAXhB,QAAA,qBAAqB,yBAWL"} \ No newline at end of file diff --git a/ts-ticket-office-service/node_modules/bson/lib/validate_utf8.js b/ts-ticket-office-service/node_modules/bson/lib/validate_utf8.js new file mode 100644 index 000000000..ec7801603 --- /dev/null +++ b/ts-ticket-office-service/node_modules/bson/lib/validate_utf8.js @@ -0,0 +1,47 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.validateUtf8 = void 0; +var FIRST_BIT = 0x80; +var FIRST_TWO_BITS = 0xc0; +var FIRST_THREE_BITS = 0xe0; +var FIRST_FOUR_BITS = 0xf0; +var FIRST_FIVE_BITS = 0xf8; +var TWO_BIT_CHAR = 0xc0; +var THREE_BIT_CHAR = 0xe0; +var FOUR_BIT_CHAR = 0xf0; +var CONTINUING_CHAR = 0x80; +/** + * Determines if the passed in bytes are valid utf8 + * @param bytes - An array of 8-bit bytes. Must be indexable and have length property + * @param start - The index to start validating + * @param end - The index to end validating + */ +function validateUtf8(bytes, start, end) { + var continuation = 0; + for (var i = start; i < end; i += 1) { + var byte = bytes[i]; + if (continuation) { + if ((byte & FIRST_TWO_BITS) !== CONTINUING_CHAR) { + return false; + } + continuation -= 1; + } + else if (byte & FIRST_BIT) { + if ((byte & FIRST_THREE_BITS) === TWO_BIT_CHAR) { + continuation = 1; + } + else if ((byte & FIRST_FOUR_BITS) === THREE_BIT_CHAR) { + continuation = 2; + } + else if ((byte & FIRST_FIVE_BITS) === FOUR_BIT_CHAR) { + continuation = 3; + } + else { + return false; + } + } + } + return !continuation; +} +exports.validateUtf8 = validateUtf8; +//# sourceMappingURL=validate_utf8.js.map \ No newline at end of file diff --git a/ts-ticket-office-service/node_modules/bson/lib/validate_utf8.js.map b/ts-ticket-office-service/node_modules/bson/lib/validate_utf8.js.map new file mode 100644 index 000000000..f1e975be0 --- /dev/null +++ b/ts-ticket-office-service/node_modules/bson/lib/validate_utf8.js.map @@ -0,0 +1 @@ +{"version":3,"file":"validate_utf8.js","sourceRoot":"","sources":["../src/validate_utf8.ts"],"names":[],"mappings":";;;AAAA,IAAM,SAAS,GAAG,IAAI,CAAC;AACvB,IAAM,cAAc,GAAG,IAAI,CAAC;AAC5B,IAAM,gBAAgB,GAAG,IAAI,CAAC;AAC9B,IAAM,eAAe,GAAG,IAAI,CAAC;AAC7B,IAAM,eAAe,GAAG,IAAI,CAAC;AAE7B,IAAM,YAAY,GAAG,IAAI,CAAC;AAC1B,IAAM,cAAc,GAAG,IAAI,CAAC;AAC5B,IAAM,aAAa,GAAG,IAAI,CAAC;AAC3B,IAAM,eAAe,GAAG,IAAI,CAAC;AAE7B;;;;;GAKG;AACH,SAAgB,YAAY,CAC1B,KAAkC,EAClC,KAAa,EACb,GAAW;IAEX,IAAI,YAAY,GAAG,CAAC,CAAC;IAErB,KAAK,IAAI,CAAC,GAAG,KAAK,EAAE,CAAC,GAAG,GAAG,EAAE,CAAC,IAAI,CAAC,EAAE;QACnC,IAAM,IAAI,GAAG,KAAK,CAAC,CAAC,CAAC,CAAC;QAEtB,IAAI,YAAY,EAAE;YAChB,IAAI,CAAC,IAAI,GAAG,cAAc,CAAC,KAAK,eAAe,EAAE;gBAC/C,OAAO,KAAK,CAAC;aACd;YACD,YAAY,IAAI,CAAC,CAAC;SACnB;aAAM,IAAI,IAAI,GAAG,SAAS,EAAE;YAC3B,IAAI,CAAC,IAAI,GAAG,gBAAgB,CAAC,KAAK,YAAY,EAAE;gBAC9C,YAAY,GAAG,CAAC,CAAC;aAClB;iBAAM,IAAI,CAAC,IAAI,GAAG,eAAe,CAAC,KAAK,cAAc,EAAE;gBACtD,YAAY,GAAG,CAAC,CAAC;aAClB;iBAAM,IAAI,CAAC,IAAI,GAAG,eAAe,CAAC,KAAK,aAAa,EAAE;gBACrD,YAAY,GAAG,CAAC,CAAC;aAClB;iBAAM;gBACL,OAAO,KAAK,CAAC;aACd;SACF;KACF;IAED,OAAO,CAAC,YAAY,CAAC;AACvB,CAAC;AA7BD,oCA6BC"} \ No newline at end of file diff --git a/ts-ticket-office-service/node_modules/bson/package.json b/ts-ticket-office-service/node_modules/bson/package.json index fae49675a..a070c00bc 100644 --- a/ts-ticket-office-service/node_modules/bson/package.json +++ b/ts-ticket-office-service/node_modules/bson/package.json @@ -1,122 +1,115 @@ { - "_args": [ - [ - { - "raw": "bson@~1.0.4", - "scope": null, - "escapedName": "bson", - "name": "bson", - "rawSpec": "~1.0.4", - "spec": ">=1.0.4 <1.1.0", - "type": "range" - }, - "F:\\gitwork\\workspace_microservices\\ts-ticket-office-service\\node_modules\\mongodb-core" - ] + "name": "bson", + "description": "A bson parser for node.js and the browser", + "keywords": [ + "mongodb", + "bson", + "parser" ], - "_from": "bson@>=1.0.4 <1.1.0", - "_id": "bson@1.0.4", - "_inCache": true, - "_location": "/bson", - "_nodeVersion": "4.4.0", - "_npmOperationalInternal": { - "host": "packages-12-west.internal.npmjs.com", - "tmp": "tmp/bson-1.0.4.tgz_1484130635725_0.12069115601480007" - }, - "_npmUser": { - "name": "christkv", - "email": "christkv@gmail.com" - }, - "_npmVersion": "2.14.20", - "_phantomChildren": {}, - "_requested": { - "raw": "bson@~1.0.4", - "scope": null, - "escapedName": "bson", - "name": "bson", - "rawSpec": "~1.0.4", - "spec": ">=1.0.4 <1.1.0", - "type": "range" - }, - "_requiredBy": [ - "/mongodb-core" + "files": [ + "lib", + "src", + "dist", + "bson.d.ts", + "etc/prepare.js", + "bower.json" ], - "_resolved": "https://registry.npmjs.org/bson/-/bson-1.0.4.tgz", - "_shasum": "93c10d39eaa5b58415cbc4052f3e53e562b0b72c", - "_shrinkwrap": null, - "_spec": "bson@~1.0.4", - "_where": "F:\\gitwork\\workspace_microservices\\ts-ticket-office-service\\node_modules\\mongodb-core", + "types": "bson.d.ts", + "version": "4.6.5", "author": { - "name": "Christian Amor Kvalheim", - "email": "christkv@gmail.com" + "name": "The MongoDB NodeJS Team", + "email": "dbx-node@mongodb.com" }, - "browser": "lib/bson/bson.js", + "license": "Apache-2.0", + "contributors": [], + "repository": "mongodb/js-bson", "bugs": { - "url": "https://github.com/mongodb/js-bson/issues" + "url": "https://jira.mongodb.org/projects/NODE/issues/" }, - "config": { - "native": false - }, - "contributors": [], - "dependencies": {}, - "description": "A bson parser for node.js and the browser", "devDependencies": { - "babel-core": "^6.14.0", - "babel-loader": "^6.2.5", - "babel-polyfill": "^6.13.0", - "babel-preset-es2015": "^6.14.0", - "babel-preset-stage-0": "^6.5.0", - "babel-register": "^6.14.0", - "benchmark": "1.0.0", - "colors": "1.1.0", - "nodeunit": "0.9.0", - "webpack": "^1.13.2", - "webpack-polyfills-plugin": "0.0.9" + "@babel/plugin-external-helpers": "^7.10.4", + "@babel/preset-env": "^7.11.0", + "@istanbuljs/nyc-config-typescript": "^1.0.1", + "@microsoft/api-extractor": "^7.28.0", + "@rollup/plugin-babel": "^5.2.0", + "@rollup/plugin-commonjs": "^15.0.0", + "@rollup/plugin-json": "^4.1.0", + "@rollup/plugin-node-resolve": "^9.0.0", + "@rollup/plugin-replace": "^4.0.0", + "@rollup/plugin-typescript": "^6.0.0", + "@types/node": "^18.0.0", + "@typescript-eslint/eslint-plugin": "^5.30.0", + "@typescript-eslint/parser": "^5.30.0", + "array-includes": "^3.1.3", + "benchmark": "^2.1.4", + "chai": "^4.2.0", + "eslint": "^8.18.0", + "eslint-config-prettier": "^8.5.0", + "eslint-plugin-prettier": "^4.1.0", + "eslint-plugin-tsdoc": "^0.2.16", + "karma": "^6.3.4", + "karma-chai": "^0.1.0", + "karma-chrome-launcher": "^3.1.0", + "karma-mocha": "^2.0.1", + "karma-mocha-reporter": "^2.2.5", + "karma-rollup-preprocessor": "^7.0.5", + "mocha": "5.2.0", + "node-fetch": "^2.6.1", + "nyc": "^15.1.0", + "object.entries": "^1.1.5", + "prettier": "^2.7.1", + "rimraf": "^3.0.2", + "rollup": "^2.26.5", + "rollup-plugin-commonjs": "^10.1.0", + "rollup-plugin-node-globals": "^1.4.0", + "rollup-plugin-node-polyfills": "^0.2.1", + "rollup-plugin-polyfill-node": "^0.7.0", + "standard-version": "^9.5.0", + "ts-node": "^9.0.0", + "tsd": "^0.21.0", + "typescript": "^4.7.4", + "typescript-cached-transpile": "0.0.6", + "uuid": "^8.3.2" }, - "directories": { - "lib": "./lib/bson" + "tsd": { + "directory": "test/types", + "compilerOptions": { + "strict": true, + "target": "esnext", + "module": "commonjs", + "moduleResolution": "node" + } }, - "dist": { - "shasum": "93c10d39eaa5b58415cbc4052f3e53e562b0b72c", - "tarball": "https://registry.npmjs.org/bson/-/bson-1.0.4.tgz" + "config": { + "native": false }, - "engines": { - "node": ">=0.6.19" + "main": "lib/bson.js", + "module": "dist/bson.esm.js", + "browser": { + "./lib/bson.js": "./dist/bson.browser.umd.js", + "./dist/bson.esm.js": "./dist/bson.browser.esm.js" }, - "files": [ - "lib", - "index.js", - "browser_build", - "bower.json" - ], - "gitHead": "8dd35ca73c30a2bcab61615ccc5edd053aeb868b", - "homepage": "https://github.com/mongodb/js-bson#readme", - "keywords": [ - "mongodb", - "bson", - "parser" - ], - "license": "Apache-2.0", - "main": "./index", - "maintainers": [ - { - "name": "octave", - "email": "chinsay@gmail.com" - }, - { - "name": "christkv", - "email": "christkv@gmail.com" - } - ], - "name": "bson", - "optionalDependencies": {}, - "readme": "ERROR: No README data found!", - "repository": { - "type": "git", - "url": "git+https://github.com/mongodb/js-bson.git" + "engines": { + "node": ">=6.9.0" }, "scripts": { - "build": "webpack --config ./webpack.dist.config.js", - "test": "nodeunit ./test/node" + "docs": "typedoc", + "test": "npm run build && npm run test-node && npm run test-browser", + "test-node": "mocha test/node test/*_tests.js", + "test-tsd": "npm run build:dts && tsd", + "test-browser": "node --max-old-space-size=4096 ./node_modules/.bin/karma start karma.conf.js", + "build:ts": "tsc", + "build:dts": "npm run build:ts && api-extractor run --typescript-compiler-folder node_modules/typescript --local && rimraf 'lib/**/*.d.ts*'", + "build:bundle": "rollup -c rollup.config.js", + "build": "npm run build:dts && npm run build:bundle", + "lint": "eslint -v && eslint --ext '.js,.ts' --max-warnings=0 src test && tsc -v && tsc --noEmit && npm run test-tsd", + "format": "eslint --ext '.js,.ts' src test --fix", + "coverage": "nyc npm run test-node", + "coverage:html": "npm run coverage && open ./coverage/index.html", + "prepare": "node etc/prepare.js", + "release": "standard-version -i HISTORY.md" }, - "version": "1.0.4" + "dependencies": { + "buffer": "^5.6.0" + } } diff --git a/ts-ticket-office-service/node_modules/bson/src/binary.ts b/ts-ticket-office-service/node_modules/bson/src/binary.ts new file mode 100644 index 000000000..f424a547e --- /dev/null +++ b/ts-ticket-office-service/node_modules/bson/src/binary.ts @@ -0,0 +1,294 @@ +import { Buffer } from 'buffer'; +import { ensureBuffer } from './ensure_buffer'; +import { uuidHexStringToBuffer } from './uuid_utils'; +import { UUID, UUIDExtended } from './uuid'; +import type { EJSONOptions } from './extended_json'; +import { BSONError, BSONTypeError } from './error'; + +/** @public */ +export type BinarySequence = Uint8Array | Buffer | number[]; + +/** @public */ +export interface BinaryExtendedLegacy { + $type: string; + $binary: string; +} + +/** @public */ +export interface BinaryExtended { + $binary: { + subType: string; + base64: string; + }; +} + +/** + * A class representation of the BSON Binary type. + * @public + * @category BSONType + */ +export class Binary { + _bsontype!: 'Binary'; + + /** + * Binary default subtype + * @internal + */ + private static readonly BSON_BINARY_SUBTYPE_DEFAULT = 0; + + /** Initial buffer default size */ + static readonly BUFFER_SIZE = 256; + /** Default BSON type */ + static readonly SUBTYPE_DEFAULT = 0; + /** Function BSON type */ + static readonly SUBTYPE_FUNCTION = 1; + /** Byte Array BSON type */ + static readonly SUBTYPE_BYTE_ARRAY = 2; + /** Deprecated UUID BSON type @deprecated Please use SUBTYPE_UUID */ + static readonly SUBTYPE_UUID_OLD = 3; + /** UUID BSON type */ + static readonly SUBTYPE_UUID = 4; + /** MD5 BSON type */ + static readonly SUBTYPE_MD5 = 5; + /** Encrypted BSON type */ + static readonly SUBTYPE_ENCRYPTED = 6; + /** Column BSON type */ + static readonly SUBTYPE_COLUMN = 7; + /** User BSON type */ + static readonly SUBTYPE_USER_DEFINED = 128; + + buffer!: Buffer; + sub_type!: number; + position!: number; + + /** + * Create a new Binary instance. + * + * This constructor can accept a string as its first argument. In this case, + * this string will be encoded using ISO-8859-1, **not** using UTF-8. + * This is almost certainly not what you want. Use `new Binary(Buffer.from(string))` + * instead to convert the string to a Buffer using UTF-8 first. + * + * @param buffer - a buffer object containing the binary data. + * @param subType - the option binary type. + */ + constructor(buffer?: string | BinarySequence, subType?: number) { + if (!(this instanceof Binary)) return new Binary(buffer, subType); + + if ( + !(buffer == null) && + !(typeof buffer === 'string') && + !ArrayBuffer.isView(buffer) && + !(buffer instanceof ArrayBuffer) && + !Array.isArray(buffer) + ) { + throw new BSONTypeError( + 'Binary can only be constructed from string, Buffer, TypedArray, or Array' + ); + } + + this.sub_type = subType ?? Binary.BSON_BINARY_SUBTYPE_DEFAULT; + + if (buffer == null) { + // create an empty binary buffer + this.buffer = Buffer.alloc(Binary.BUFFER_SIZE); + this.position = 0; + } else { + if (typeof buffer === 'string') { + // string + this.buffer = Buffer.from(buffer, 'binary'); + } else if (Array.isArray(buffer)) { + // number[] + this.buffer = Buffer.from(buffer); + } else { + // Buffer | TypedArray | ArrayBuffer + this.buffer = ensureBuffer(buffer); + } + + this.position = this.buffer.byteLength; + } + } + + /** + * Updates this binary with byte_value. + * + * @param byteValue - a single byte we wish to write. + */ + put(byteValue: string | number | Uint8Array | Buffer | number[]): void { + // If it's a string and a has more than one character throw an error + if (typeof byteValue === 'string' && byteValue.length !== 1) { + throw new BSONTypeError('only accepts single character String'); + } else if (typeof byteValue !== 'number' && byteValue.length !== 1) + throw new BSONTypeError('only accepts single character Uint8Array or Array'); + + // Decode the byte value once + let decodedByte: number; + if (typeof byteValue === 'string') { + decodedByte = byteValue.charCodeAt(0); + } else if (typeof byteValue === 'number') { + decodedByte = byteValue; + } else { + decodedByte = byteValue[0]; + } + + if (decodedByte < 0 || decodedByte > 255) { + throw new BSONTypeError('only accepts number in a valid unsigned byte range 0-255'); + } + + if (this.buffer.length > this.position) { + this.buffer[this.position++] = decodedByte; + } else { + const buffer = Buffer.alloc(Binary.BUFFER_SIZE + this.buffer.length); + // Combine the two buffers together + this.buffer.copy(buffer, 0, 0, this.buffer.length); + this.buffer = buffer; + this.buffer[this.position++] = decodedByte; + } + } + + /** + * Writes a buffer or string to the binary. + * + * @param sequence - a string or buffer to be written to the Binary BSON object. + * @param offset - specify the binary of where to write the content. + */ + write(sequence: string | BinarySequence, offset: number): void { + offset = typeof offset === 'number' ? offset : this.position; + + // If the buffer is to small let's extend the buffer + if (this.buffer.length < offset + sequence.length) { + const buffer = Buffer.alloc(this.buffer.length + sequence.length); + this.buffer.copy(buffer, 0, 0, this.buffer.length); + + // Assign the new buffer + this.buffer = buffer; + } + + if (ArrayBuffer.isView(sequence)) { + this.buffer.set(ensureBuffer(sequence), offset); + this.position = + offset + sequence.byteLength > this.position ? offset + sequence.length : this.position; + } else if (typeof sequence === 'string') { + this.buffer.write(sequence, offset, sequence.length, 'binary'); + this.position = + offset + sequence.length > this.position ? offset + sequence.length : this.position; + } + } + + /** + * Reads **length** bytes starting at **position**. + * + * @param position - read from the given position in the Binary. + * @param length - the number of bytes to read. + */ + read(position: number, length: number): BinarySequence { + length = length && length > 0 ? length : this.position; + + // Let's return the data based on the type we have + return this.buffer.slice(position, position + length); + } + + /** + * Returns the value of this binary as a string. + * @param asRaw - Will skip converting to a string + * @remarks + * This is handy when calling this function conditionally for some key value pairs and not others + */ + value(asRaw?: boolean): string | BinarySequence { + asRaw = !!asRaw; + + // Optimize to serialize for the situation where the data == size of buffer + if (asRaw && this.buffer.length === this.position) { + return this.buffer; + } + + // If it's a node.js buffer object + if (asRaw) { + return this.buffer.slice(0, this.position); + } + return this.buffer.toString('binary', 0, this.position); + } + + /** the length of the binary sequence */ + length(): number { + return this.position; + } + + toJSON(): string { + return this.buffer.toString('base64'); + } + + toString(format?: string): string { + return this.buffer.toString(format); + } + + /** @internal */ + toExtendedJSON(options?: EJSONOptions): BinaryExtendedLegacy | BinaryExtended { + options = options || {}; + const base64String = this.buffer.toString('base64'); + + const subType = Number(this.sub_type).toString(16); + if (options.legacy) { + return { + $binary: base64String, + $type: subType.length === 1 ? '0' + subType : subType + }; + } + return { + $binary: { + base64: base64String, + subType: subType.length === 1 ? '0' + subType : subType + } + }; + } + + toUUID(): UUID { + if (this.sub_type === Binary.SUBTYPE_UUID) { + return new UUID(this.buffer.slice(0, this.position)); + } + + throw new BSONError( + `Binary sub_type "${this.sub_type}" is not supported for converting to UUID. Only "${Binary.SUBTYPE_UUID}" is currently supported.` + ); + } + + /** @internal */ + static fromExtendedJSON( + doc: BinaryExtendedLegacy | BinaryExtended | UUIDExtended, + options?: EJSONOptions + ): Binary { + options = options || {}; + let data: Buffer | undefined; + let type; + if ('$binary' in doc) { + if (options.legacy && typeof doc.$binary === 'string' && '$type' in doc) { + type = doc.$type ? parseInt(doc.$type, 16) : 0; + data = Buffer.from(doc.$binary, 'base64'); + } else { + if (typeof doc.$binary !== 'string') { + type = doc.$binary.subType ? parseInt(doc.$binary.subType, 16) : 0; + data = Buffer.from(doc.$binary.base64, 'base64'); + } + } + } else if ('$uuid' in doc) { + type = 4; + data = uuidHexStringToBuffer(doc.$uuid); + } + if (!data) { + throw new BSONTypeError(`Unexpected Binary Extended JSON format ${JSON.stringify(doc)}`); + } + return new Binary(data, type); + } + + /** @internal */ + [Symbol.for('nodejs.util.inspect.custom')](): string { + return this.inspect(); + } + + inspect(): string { + const asBuffer = this.value(true); + return `new Binary(Buffer.from("${asBuffer.toString('hex')}", "hex"), ${this.sub_type})`; + } +} + +Object.defineProperty(Binary.prototype, '_bsontype', { value: 'Binary' }); diff --git a/ts-ticket-office-service/node_modules/bson/src/bson.ts b/ts-ticket-office-service/node_modules/bson/src/bson.ts new file mode 100644 index 000000000..924235aab --- /dev/null +++ b/ts-ticket-office-service/node_modules/bson/src/bson.ts @@ -0,0 +1,335 @@ +import { Buffer } from 'buffer'; +import { Binary } from './binary'; +import { Code } from './code'; +import { DBRef } from './db_ref'; +import { Decimal128 } from './decimal128'; +import { Double } from './double'; +import { ensureBuffer } from './ensure_buffer'; +import { EJSON } from './extended_json'; +import { Int32 } from './int_32'; +import { Long } from './long'; +import { Map } from './map'; +import { MaxKey } from './max_key'; +import { MinKey } from './min_key'; +import { ObjectId } from './objectid'; +import { BSONError, BSONTypeError } from './error'; +import { calculateObjectSize as internalCalculateObjectSize } from './parser/calculate_size'; +// Parts of the parser +import { deserialize as internalDeserialize, DeserializeOptions } from './parser/deserializer'; +import { serializeInto as internalSerialize, SerializeOptions } from './parser/serializer'; +import { BSONRegExp } from './regexp'; +import { BSONSymbol } from './symbol'; +import { Timestamp } from './timestamp'; +import { UUID } from './uuid'; +export { BinaryExtended, BinaryExtendedLegacy, BinarySequence } from './binary'; +export { CodeExtended } from './code'; +export { + BSON_BINARY_SUBTYPE_BYTE_ARRAY, + BSON_BINARY_SUBTYPE_DEFAULT, + BSON_BINARY_SUBTYPE_FUNCTION, + BSON_BINARY_SUBTYPE_MD5, + BSON_BINARY_SUBTYPE_USER_DEFINED, + BSON_BINARY_SUBTYPE_UUID, + BSON_BINARY_SUBTYPE_UUID_NEW, + BSON_BINARY_SUBTYPE_ENCRYPTED, + BSON_BINARY_SUBTYPE_COLUMN, + BSON_DATA_ARRAY, + BSON_DATA_BINARY, + BSON_DATA_BOOLEAN, + BSON_DATA_CODE, + BSON_DATA_CODE_W_SCOPE, + BSON_DATA_DATE, + BSON_DATA_DBPOINTER, + BSON_DATA_DECIMAL128, + BSON_DATA_INT, + BSON_DATA_LONG, + BSON_DATA_MAX_KEY, + BSON_DATA_MIN_KEY, + BSON_DATA_NULL, + BSON_DATA_NUMBER, + BSON_DATA_OBJECT, + BSON_DATA_OID, + BSON_DATA_REGEXP, + BSON_DATA_STRING, + BSON_DATA_SYMBOL, + BSON_DATA_TIMESTAMP, + BSON_DATA_UNDEFINED, + BSON_INT32_MAX, + BSON_INT32_MIN, + BSON_INT64_MAX, + BSON_INT64_MIN +} from './constants'; +export { DBRefLike } from './db_ref'; +export { Decimal128Extended } from './decimal128'; +export { DoubleExtended } from './double'; +export { EJSON, EJSONOptions } from './extended_json'; +export { Int32Extended } from './int_32'; +export { LongExtended } from './long'; +export { MaxKeyExtended } from './max_key'; +export { MinKeyExtended } from './min_key'; +export { ObjectIdExtended, ObjectIdLike } from './objectid'; +export { BSONRegExpExtended, BSONRegExpExtendedLegacy } from './regexp'; +export { BSONSymbolExtended } from './symbol'; +export { + LongWithoutOverrides, + LongWithoutOverridesClass, + TimestampExtended, + TimestampOverrides +} from './timestamp'; +export { UUIDExtended } from './uuid'; +export { SerializeOptions, DeserializeOptions }; +export { + Code, + Map, + BSONSymbol, + DBRef, + Binary, + ObjectId, + UUID, + Long, + Timestamp, + Double, + Int32, + MinKey, + MaxKey, + BSONRegExp, + Decimal128, + // In 4.0.0 and 4.0.1, this property name was changed to ObjectId to match the class name. + // This caused interoperability problems with previous versions of the library, so in + // later builds we changed it back to ObjectID (capital D) to match legacy implementations. + ObjectId as ObjectID +}; +export { BSONError, BSONTypeError } from './error'; + +/** @public */ +export interface Document { + // eslint-disable-next-line @typescript-eslint/no-explicit-any + [key: string]: any; +} + +/** @internal */ +// Default Max Size +const MAXSIZE = 1024 * 1024 * 17; + +// Current Internal Temporary Serialization Buffer +let buffer = Buffer.alloc(MAXSIZE); + +/** + * Sets the size of the internal serialization buffer. + * + * @param size - The desired size for the internal serialization buffer + * @public + */ +export function setInternalBufferSize(size: number): void { + // Resize the internal serialization buffer if needed + if (buffer.length < size) { + buffer = Buffer.alloc(size); + } +} + +/** + * Serialize a Javascript object. + * + * @param object - the Javascript object to serialize. + * @returns Buffer object containing the serialized object. + * @public + */ +export function serialize(object: Document, options: SerializeOptions = {}): Buffer { + // Unpack the options + const checkKeys = typeof options.checkKeys === 'boolean' ? options.checkKeys : false; + const serializeFunctions = + typeof options.serializeFunctions === 'boolean' ? options.serializeFunctions : false; + const ignoreUndefined = + typeof options.ignoreUndefined === 'boolean' ? options.ignoreUndefined : true; + const minInternalBufferSize = + typeof options.minInternalBufferSize === 'number' ? options.minInternalBufferSize : MAXSIZE; + + // Resize the internal serialization buffer if needed + if (buffer.length < minInternalBufferSize) { + buffer = Buffer.alloc(minInternalBufferSize); + } + + // Attempt to serialize + const serializationIndex = internalSerialize( + buffer, + object, + checkKeys, + 0, + 0, + serializeFunctions, + ignoreUndefined, + [] + ); + + // Create the final buffer + const finishedBuffer = Buffer.alloc(serializationIndex); + + // Copy into the finished buffer + buffer.copy(finishedBuffer, 0, 0, finishedBuffer.length); + + // Return the buffer + return finishedBuffer; +} + +/** + * Serialize a Javascript object using a predefined Buffer and index into the buffer, + * useful when pre-allocating the space for serialization. + * + * @param object - the Javascript object to serialize. + * @param finalBuffer - the Buffer you pre-allocated to store the serialized BSON object. + * @returns the index pointing to the last written byte in the buffer. + * @public + */ +export function serializeWithBufferAndIndex( + object: Document, + finalBuffer: Buffer, + options: SerializeOptions = {} +): number { + // Unpack the options + const checkKeys = typeof options.checkKeys === 'boolean' ? options.checkKeys : false; + const serializeFunctions = + typeof options.serializeFunctions === 'boolean' ? options.serializeFunctions : false; + const ignoreUndefined = + typeof options.ignoreUndefined === 'boolean' ? options.ignoreUndefined : true; + const startIndex = typeof options.index === 'number' ? options.index : 0; + + // Attempt to serialize + const serializationIndex = internalSerialize( + buffer, + object, + checkKeys, + 0, + 0, + serializeFunctions, + ignoreUndefined + ); + buffer.copy(finalBuffer, startIndex, 0, serializationIndex); + + // Return the index + return startIndex + serializationIndex - 1; +} + +/** + * Deserialize data as BSON. + * + * @param buffer - the buffer containing the serialized set of BSON documents. + * @returns returns the deserialized Javascript Object. + * @public + */ +export function deserialize( + buffer: Buffer | ArrayBufferView | ArrayBuffer, + options: DeserializeOptions = {} +): Document { + return internalDeserialize(buffer instanceof Buffer ? buffer : ensureBuffer(buffer), options); +} + +/** @public */ +export type CalculateObjectSizeOptions = Pick< + SerializeOptions, + 'serializeFunctions' | 'ignoreUndefined' +>; + +/** + * Calculate the bson size for a passed in Javascript object. + * + * @param object - the Javascript object to calculate the BSON byte size for + * @returns size of BSON object in bytes + * @public + */ +export function calculateObjectSize( + object: Document, + options: CalculateObjectSizeOptions = {} +): number { + options = options || {}; + + const serializeFunctions = + typeof options.serializeFunctions === 'boolean' ? options.serializeFunctions : false; + const ignoreUndefined = + typeof options.ignoreUndefined === 'boolean' ? options.ignoreUndefined : true; + + return internalCalculateObjectSize(object, serializeFunctions, ignoreUndefined); +} + +/** + * Deserialize stream data as BSON documents. + * + * @param data - the buffer containing the serialized set of BSON documents. + * @param startIndex - the start index in the data Buffer where the deserialization is to start. + * @param numberOfDocuments - number of documents to deserialize. + * @param documents - an array where to store the deserialized documents. + * @param docStartIndex - the index in the documents array from where to start inserting documents. + * @param options - additional options used for the deserialization. + * @returns next index in the buffer after deserialization **x** numbers of documents. + * @public + */ +export function deserializeStream( + data: Buffer | ArrayBufferView | ArrayBuffer, + startIndex: number, + numberOfDocuments: number, + documents: Document[], + docStartIndex: number, + options: DeserializeOptions +): number { + const internalOptions = Object.assign( + { allowObjectSmallerThanBufferSize: true, index: 0 }, + options + ); + const bufferData = ensureBuffer(data); + + let index = startIndex; + // Loop over all documents + for (let i = 0; i < numberOfDocuments; i++) { + // Find size of the document + const size = + bufferData[index] | + (bufferData[index + 1] << 8) | + (bufferData[index + 2] << 16) | + (bufferData[index + 3] << 24); + // Update options with index + internalOptions.index = index; + // Parse the document at this point + documents[docStartIndex + i] = internalDeserialize(bufferData, internalOptions); + // Adjust index by the document size + index = index + size; + } + + // Return object containing end index of parsing and list of documents + return index; +} + +/** + * BSON default export + * @deprecated Please use named exports + * @privateRemarks + * We want to someday deprecate the default export, + * so none of the new TS types are being exported on the default + * @public + */ +const BSON = { + Binary, + Code, + DBRef, + Decimal128, + Double, + Int32, + Long, + UUID, + Map, + MaxKey, + MinKey, + ObjectId, + ObjectID: ObjectId, + BSONRegExp, + BSONSymbol, + Timestamp, + EJSON, + setInternalBufferSize, + serialize, + serializeWithBufferAndIndex, + deserialize, + calculateObjectSize, + deserializeStream, + BSONError, + BSONTypeError +}; +export default BSON; diff --git a/ts-ticket-office-service/node_modules/bson/src/code.ts b/ts-ticket-office-service/node_modules/bson/src/code.ts new file mode 100644 index 000000000..86a4fb19c --- /dev/null +++ b/ts-ticket-office-service/node_modules/bson/src/code.ts @@ -0,0 +1,61 @@ +import type { Document } from './bson'; + +/** @public */ +export interface CodeExtended { + $code: string | Function; + $scope?: Document; +} + +/** + * A class representation of the BSON Code type. + * @public + * @category BSONType + */ +export class Code { + _bsontype!: 'Code'; + + code!: string | Function; + scope?: Document; + /** + * @param code - a string or function. + * @param scope - an optional scope for the function. + */ + constructor(code: string | Function, scope?: Document) { + if (!(this instanceof Code)) return new Code(code, scope); + + this.code = code; + this.scope = scope; + } + + toJSON(): { code: string | Function; scope?: Document } { + return { code: this.code, scope: this.scope }; + } + + /** @internal */ + toExtendedJSON(): CodeExtended { + if (this.scope) { + return { $code: this.code, $scope: this.scope }; + } + + return { $code: this.code }; + } + + /** @internal */ + static fromExtendedJSON(doc: CodeExtended): Code { + return new Code(doc.$code, doc.$scope); + } + + /** @internal */ + [Symbol.for('nodejs.util.inspect.custom')](): string { + return this.inspect(); + } + + inspect(): string { + const codeJson = this.toJSON(); + return `new Code("${String(codeJson.code)}"${ + codeJson.scope ? `, ${JSON.stringify(codeJson.scope)}` : '' + })`; + } +} + +Object.defineProperty(Code.prototype, '_bsontype', { value: 'Code' }); diff --git a/ts-ticket-office-service/node_modules/bson/src/constants.ts b/ts-ticket-office-service/node_modules/bson/src/constants.ts new file mode 100644 index 000000000..6af63e694 --- /dev/null +++ b/ts-ticket-office-service/node_modules/bson/src/constants.ts @@ -0,0 +1,110 @@ +/** @internal */ +export const BSON_INT32_MAX = 0x7fffffff; +/** @internal */ +export const BSON_INT32_MIN = -0x80000000; +/** @internal */ +export const BSON_INT64_MAX = Math.pow(2, 63) - 1; +/** @internal */ +export const BSON_INT64_MIN = -Math.pow(2, 63); + +/** + * Any integer up to 2^53 can be precisely represented by a double. + * @internal + */ +export const JS_INT_MAX = Math.pow(2, 53); + +/** + * Any integer down to -2^53 can be precisely represented by a double. + * @internal + */ +export const JS_INT_MIN = -Math.pow(2, 53); + +/** Number BSON Type @internal */ +export const BSON_DATA_NUMBER = 1; + +/** String BSON Type @internal */ +export const BSON_DATA_STRING = 2; + +/** Object BSON Type @internal */ +export const BSON_DATA_OBJECT = 3; + +/** Array BSON Type @internal */ +export const BSON_DATA_ARRAY = 4; + +/** Binary BSON Type @internal */ +export const BSON_DATA_BINARY = 5; + +/** Binary BSON Type @internal */ +export const BSON_DATA_UNDEFINED = 6; + +/** ObjectId BSON Type @internal */ +export const BSON_DATA_OID = 7; + +/** Boolean BSON Type @internal */ +export const BSON_DATA_BOOLEAN = 8; + +/** Date BSON Type @internal */ +export const BSON_DATA_DATE = 9; + +/** null BSON Type @internal */ +export const BSON_DATA_NULL = 10; + +/** RegExp BSON Type @internal */ +export const BSON_DATA_REGEXP = 11; + +/** Code BSON Type @internal */ +export const BSON_DATA_DBPOINTER = 12; + +/** Code BSON Type @internal */ +export const BSON_DATA_CODE = 13; + +/** Symbol BSON Type @internal */ +export const BSON_DATA_SYMBOL = 14; + +/** Code with Scope BSON Type @internal */ +export const BSON_DATA_CODE_W_SCOPE = 15; + +/** 32 bit Integer BSON Type @internal */ +export const BSON_DATA_INT = 16; + +/** Timestamp BSON Type @internal */ +export const BSON_DATA_TIMESTAMP = 17; + +/** Long BSON Type @internal */ +export const BSON_DATA_LONG = 18; + +/** Decimal128 BSON Type @internal */ +export const BSON_DATA_DECIMAL128 = 19; + +/** MinKey BSON Type @internal */ +export const BSON_DATA_MIN_KEY = 0xff; + +/** MaxKey BSON Type @internal */ +export const BSON_DATA_MAX_KEY = 0x7f; + +/** Binary Default Type @internal */ +export const BSON_BINARY_SUBTYPE_DEFAULT = 0; + +/** Binary Function Type @internal */ +export const BSON_BINARY_SUBTYPE_FUNCTION = 1; + +/** Binary Byte Array Type @internal */ +export const BSON_BINARY_SUBTYPE_BYTE_ARRAY = 2; + +/** Binary Deprecated UUID Type @deprecated Please use BSON_BINARY_SUBTYPE_UUID_NEW @internal */ +export const BSON_BINARY_SUBTYPE_UUID = 3; + +/** Binary UUID Type @internal */ +export const BSON_BINARY_SUBTYPE_UUID_NEW = 4; + +/** Binary MD5 Type @internal */ +export const BSON_BINARY_SUBTYPE_MD5 = 5; + +/** Encrypted BSON type @internal */ +export const BSON_BINARY_SUBTYPE_ENCRYPTED = 6; + +/** Column BSON type @internal */ +export const BSON_BINARY_SUBTYPE_COLUMN = 7; + +/** Binary User Defined Type @internal */ +export const BSON_BINARY_SUBTYPE_USER_DEFINED = 128; diff --git a/ts-ticket-office-service/node_modules/bson/src/db_ref.ts b/ts-ticket-office-service/node_modules/bson/src/db_ref.ts new file mode 100644 index 000000000..750c5be93 --- /dev/null +++ b/ts-ticket-office-service/node_modules/bson/src/db_ref.ts @@ -0,0 +1,124 @@ +import type { Document } from './bson'; +import type { EJSONOptions } from './extended_json'; +import type { ObjectId } from './objectid'; +import { isObjectLike } from './parser/utils'; + +/** @public */ +export interface DBRefLike { + $ref: string; + $id: ObjectId; + $db?: string; +} + +/** @internal */ +export function isDBRefLike(value: unknown): value is DBRefLike { + return ( + isObjectLike(value) && + value.$id != null && + typeof value.$ref === 'string' && + (value.$db == null || typeof value.$db === 'string') + ); +} + +/** + * A class representation of the BSON DBRef type. + * @public + * @category BSONType + */ +export class DBRef { + _bsontype!: 'DBRef'; + + collection!: string; + oid!: ObjectId; + db?: string; + fields!: Document; + + /** + * @param collection - the collection name. + * @param oid - the reference ObjectId. + * @param db - optional db name, if omitted the reference is local to the current db. + */ + constructor(collection: string, oid: ObjectId, db?: string, fields?: Document) { + if (!(this instanceof DBRef)) return new DBRef(collection, oid, db, fields); + + // check if namespace has been provided + const parts = collection.split('.'); + if (parts.length === 2) { + db = parts.shift(); + // eslint-disable-next-line @typescript-eslint/no-non-null-assertion + collection = parts.shift()!; + } + + this.collection = collection; + this.oid = oid; + this.db = db; + this.fields = fields || {}; + } + + // Property provided for compatibility with the 1.x parser + // the 1.x parser used a "namespace" property, while 4.x uses "collection" + + /** @internal */ + get namespace(): string { + return this.collection; + } + + set namespace(value: string) { + this.collection = value; + } + + toJSON(): DBRefLike & Document { + const o = Object.assign( + { + $ref: this.collection, + $id: this.oid + }, + this.fields + ); + + if (this.db != null) o.$db = this.db; + return o; + } + + /** @internal */ + toExtendedJSON(options?: EJSONOptions): DBRefLike { + options = options || {}; + let o: DBRefLike = { + $ref: this.collection, + $id: this.oid + }; + + if (options.legacy) { + return o; + } + + if (this.db) o.$db = this.db; + o = Object.assign(o, this.fields); + return o; + } + + /** @internal */ + static fromExtendedJSON(doc: DBRefLike): DBRef { + const copy = Object.assign({}, doc) as Partial; + delete copy.$ref; + delete copy.$id; + delete copy.$db; + return new DBRef(doc.$ref, doc.$id, doc.$db, copy); + } + + /** @internal */ + [Symbol.for('nodejs.util.inspect.custom')](): string { + return this.inspect(); + } + + inspect(): string { + // NOTE: if OID is an ObjectId class it will just print the oid string. + const oid = + this.oid === undefined || this.oid.toString === undefined ? this.oid : this.oid.toString(); + return `new DBRef("${this.namespace}", new ObjectId("${String(oid)}")${ + this.db ? `, "${this.db}"` : '' + })`; + } +} + +Object.defineProperty(DBRef.prototype, '_bsontype', { value: 'DBRef' }); diff --git a/ts-ticket-office-service/node_modules/bson/src/decimal128.ts b/ts-ticket-office-service/node_modules/bson/src/decimal128.ts new file mode 100644 index 000000000..875998648 --- /dev/null +++ b/ts-ticket-office-service/node_modules/bson/src/decimal128.ts @@ -0,0 +1,773 @@ +import { Buffer } from 'buffer'; +import { BSONTypeError } from './error'; +import { Long } from './long'; +import { isUint8Array } from './parser/utils'; + +const PARSE_STRING_REGEXP = /^(\+|-)?(\d+|(\d*\.\d*))?(E|e)?([-+])?(\d+)?$/; +const PARSE_INF_REGEXP = /^(\+|-)?(Infinity|inf)$/i; +const PARSE_NAN_REGEXP = /^(\+|-)?NaN$/i; + +const EXPONENT_MAX = 6111; +const EXPONENT_MIN = -6176; +const EXPONENT_BIAS = 6176; +const MAX_DIGITS = 34; + +// Nan value bits as 32 bit values (due to lack of longs) +const NAN_BUFFER = [ + 0x7c, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 +].reverse(); +// Infinity value bits 32 bit values (due to lack of longs) +const INF_NEGATIVE_BUFFER = [ + 0xf8, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 +].reverse(); +const INF_POSITIVE_BUFFER = [ + 0x78, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 +].reverse(); + +const EXPONENT_REGEX = /^([-+])?(\d+)?$/; + +// Extract least significant 5 bits +const COMBINATION_MASK = 0x1f; +// Extract least significant 14 bits +const EXPONENT_MASK = 0x3fff; +// Value of combination field for Inf +const COMBINATION_INFINITY = 30; +// Value of combination field for NaN +const COMBINATION_NAN = 31; + +// Detect if the value is a digit +function isDigit(value: string): boolean { + return !isNaN(parseInt(value, 10)); +} + +// Divide two uint128 values +function divideu128(value: { parts: [number, number, number, number] }) { + const DIVISOR = Long.fromNumber(1000 * 1000 * 1000); + let _rem = Long.fromNumber(0); + + if (!value.parts[0] && !value.parts[1] && !value.parts[2] && !value.parts[3]) { + return { quotient: value, rem: _rem }; + } + + for (let i = 0; i <= 3; i++) { + // Adjust remainder to match value of next dividend + _rem = _rem.shiftLeft(32); + // Add the divided to _rem + _rem = _rem.add(new Long(value.parts[i], 0)); + value.parts[i] = _rem.div(DIVISOR).low; + _rem = _rem.modulo(DIVISOR); + } + + return { quotient: value, rem: _rem }; +} + +// Multiply two Long values and return the 128 bit value +function multiply64x2(left: Long, right: Long): { high: Long; low: Long } { + if (!left && !right) { + return { high: Long.fromNumber(0), low: Long.fromNumber(0) }; + } + + const leftHigh = left.shiftRightUnsigned(32); + const leftLow = new Long(left.getLowBits(), 0); + const rightHigh = right.shiftRightUnsigned(32); + const rightLow = new Long(right.getLowBits(), 0); + + let productHigh = leftHigh.multiply(rightHigh); + let productMid = leftHigh.multiply(rightLow); + const productMid2 = leftLow.multiply(rightHigh); + let productLow = leftLow.multiply(rightLow); + + productHigh = productHigh.add(productMid.shiftRightUnsigned(32)); + productMid = new Long(productMid.getLowBits(), 0) + .add(productMid2) + .add(productLow.shiftRightUnsigned(32)); + + productHigh = productHigh.add(productMid.shiftRightUnsigned(32)); + productLow = productMid.shiftLeft(32).add(new Long(productLow.getLowBits(), 0)); + + // Return the 128 bit result + return { high: productHigh, low: productLow }; +} + +function lessThan(left: Long, right: Long): boolean { + // Make values unsigned + const uhleft = left.high >>> 0; + const uhright = right.high >>> 0; + + // Compare high bits first + if (uhleft < uhright) { + return true; + } else if (uhleft === uhright) { + const ulleft = left.low >>> 0; + const ulright = right.low >>> 0; + if (ulleft < ulright) return true; + } + + return false; +} + +function invalidErr(string: string, message: string) { + throw new BSONTypeError(`"${string}" is not a valid Decimal128 string - ${message}`); +} + +/** @public */ +export interface Decimal128Extended { + $numberDecimal: string; +} + +/** + * A class representation of the BSON Decimal128 type. + * @public + * @category BSONType + */ +export class Decimal128 { + _bsontype!: 'Decimal128'; + + readonly bytes!: Buffer; + + /** + * @param bytes - a buffer containing the raw Decimal128 bytes in little endian order, + * or a string representation as returned by .toString() + */ + constructor(bytes: Buffer | string) { + if (!(this instanceof Decimal128)) return new Decimal128(bytes); + + if (typeof bytes === 'string') { + this.bytes = Decimal128.fromString(bytes).bytes; + } else if (isUint8Array(bytes)) { + if (bytes.byteLength !== 16) { + throw new BSONTypeError('Decimal128 must take a Buffer of 16 bytes'); + } + this.bytes = bytes; + } else { + throw new BSONTypeError('Decimal128 must take a Buffer or string'); + } + } + + /** + * Create a Decimal128 instance from a string representation + * + * @param representation - a numeric string representation. + */ + static fromString(representation: string): Decimal128 { + // Parse state tracking + let isNegative = false; + let sawRadix = false; + let foundNonZero = false; + + // Total number of significant digits (no leading or trailing zero) + let significantDigits = 0; + // Total number of significand digits read + let nDigitsRead = 0; + // Total number of digits (no leading zeros) + let nDigits = 0; + // The number of the digits after radix + let radixPosition = 0; + // The index of the first non-zero in *str* + let firstNonZero = 0; + + // Digits Array + const digits = [0]; + // The number of digits in digits + let nDigitsStored = 0; + // Insertion pointer for digits + let digitsInsert = 0; + // The index of the first non-zero digit + let firstDigit = 0; + // The index of the last digit + let lastDigit = 0; + + // Exponent + let exponent = 0; + // loop index over array + let i = 0; + // The high 17 digits of the significand + let significandHigh = new Long(0, 0); + // The low 17 digits of the significand + let significandLow = new Long(0, 0); + // The biased exponent + let biasedExponent = 0; + + // Read index + let index = 0; + + // Naively prevent against REDOS attacks. + // TODO: implementing a custom parsing for this, or refactoring the regex would yield + // further gains. + if (representation.length >= 7000) { + throw new BSONTypeError('' + representation + ' not a valid Decimal128 string'); + } + + // Results + const stringMatch = representation.match(PARSE_STRING_REGEXP); + const infMatch = representation.match(PARSE_INF_REGEXP); + const nanMatch = representation.match(PARSE_NAN_REGEXP); + + // Validate the string + if ((!stringMatch && !infMatch && !nanMatch) || representation.length === 0) { + throw new BSONTypeError('' + representation + ' not a valid Decimal128 string'); + } + + if (stringMatch) { + // full_match = stringMatch[0] + // sign = stringMatch[1] + + const unsignedNumber = stringMatch[2]; + // stringMatch[3] is undefined if a whole number (ex "1", 12") + // but defined if a number w/ decimal in it (ex "1.0, 12.2") + + const e = stringMatch[4]; + const expSign = stringMatch[5]; + const expNumber = stringMatch[6]; + + // they provided e, but didn't give an exponent number. for ex "1e" + if (e && expNumber === undefined) invalidErr(representation, 'missing exponent power'); + + // they provided e, but didn't give a number before it. for ex "e1" + if (e && unsignedNumber === undefined) invalidErr(representation, 'missing exponent base'); + + if (e === undefined && (expSign || expNumber)) { + invalidErr(representation, 'missing e before exponent'); + } + } + + // Get the negative or positive sign + if (representation[index] === '+' || representation[index] === '-') { + isNegative = representation[index++] === '-'; + } + + // Check if user passed Infinity or NaN + if (!isDigit(representation[index]) && representation[index] !== '.') { + if (representation[index] === 'i' || representation[index] === 'I') { + return new Decimal128(Buffer.from(isNegative ? INF_NEGATIVE_BUFFER : INF_POSITIVE_BUFFER)); + } else if (representation[index] === 'N') { + return new Decimal128(Buffer.from(NAN_BUFFER)); + } + } + + // Read all the digits + while (isDigit(representation[index]) || representation[index] === '.') { + if (representation[index] === '.') { + if (sawRadix) invalidErr(representation, 'contains multiple periods'); + + sawRadix = true; + index = index + 1; + continue; + } + + if (nDigitsStored < 34) { + if (representation[index] !== '0' || foundNonZero) { + if (!foundNonZero) { + firstNonZero = nDigitsRead; + } + + foundNonZero = true; + + // Only store 34 digits + digits[digitsInsert++] = parseInt(representation[index], 10); + nDigitsStored = nDigitsStored + 1; + } + } + + if (foundNonZero) nDigits = nDigits + 1; + if (sawRadix) radixPosition = radixPosition + 1; + + nDigitsRead = nDigitsRead + 1; + index = index + 1; + } + + if (sawRadix && !nDigitsRead) + throw new BSONTypeError('' + representation + ' not a valid Decimal128 string'); + + // Read exponent if exists + if (representation[index] === 'e' || representation[index] === 'E') { + // Read exponent digits + const match = representation.substr(++index).match(EXPONENT_REGEX); + + // No digits read + if (!match || !match[2]) return new Decimal128(Buffer.from(NAN_BUFFER)); + + // Get exponent + exponent = parseInt(match[0], 10); + + // Adjust the index + index = index + match[0].length; + } + + // Return not a number + if (representation[index]) return new Decimal128(Buffer.from(NAN_BUFFER)); + + // Done reading input + // Find first non-zero digit in digits + firstDigit = 0; + + if (!nDigitsStored) { + firstDigit = 0; + lastDigit = 0; + digits[0] = 0; + nDigits = 1; + nDigitsStored = 1; + significantDigits = 0; + } else { + lastDigit = nDigitsStored - 1; + significantDigits = nDigits; + if (significantDigits !== 1) { + while (digits[firstNonZero + significantDigits - 1] === 0) { + significantDigits = significantDigits - 1; + } + } + } + + // Normalization of exponent + // Correct exponent based on radix position, and shift significand as needed + // to represent user input + + // Overflow prevention + if (exponent <= radixPosition && radixPosition - exponent > 1 << 14) { + exponent = EXPONENT_MIN; + } else { + exponent = exponent - radixPosition; + } + + // Attempt to normalize the exponent + while (exponent > EXPONENT_MAX) { + // Shift exponent to significand and decrease + lastDigit = lastDigit + 1; + + if (lastDigit - firstDigit > MAX_DIGITS) { + // Check if we have a zero then just hard clamp, otherwise fail + const digitsString = digits.join(''); + if (digitsString.match(/^0+$/)) { + exponent = EXPONENT_MAX; + break; + } + + invalidErr(representation, 'overflow'); + } + exponent = exponent - 1; + } + + while (exponent < EXPONENT_MIN || nDigitsStored < nDigits) { + // Shift last digit. can only do this if < significant digits than # stored. + if (lastDigit === 0 && significantDigits < nDigitsStored) { + exponent = EXPONENT_MIN; + significantDigits = 0; + break; + } + + if (nDigitsStored < nDigits) { + // adjust to match digits not stored + nDigits = nDigits - 1; + } else { + // adjust to round + lastDigit = lastDigit - 1; + } + + if (exponent < EXPONENT_MAX) { + exponent = exponent + 1; + } else { + // Check if we have a zero then just hard clamp, otherwise fail + const digitsString = digits.join(''); + if (digitsString.match(/^0+$/)) { + exponent = EXPONENT_MAX; + break; + } + invalidErr(representation, 'overflow'); + } + } + + // Round + // We've normalized the exponent, but might still need to round. + if (lastDigit - firstDigit + 1 < significantDigits) { + let endOfString = nDigitsRead; + + // If we have seen a radix point, 'string' is 1 longer than we have + // documented with ndigits_read, so inc the position of the first nonzero + // digit and the position that digits are read to. + if (sawRadix) { + firstNonZero = firstNonZero + 1; + endOfString = endOfString + 1; + } + // if negative, we need to increment again to account for - sign at start. + if (isNegative) { + firstNonZero = firstNonZero + 1; + endOfString = endOfString + 1; + } + + const roundDigit = parseInt(representation[firstNonZero + lastDigit + 1], 10); + let roundBit = 0; + + if (roundDigit >= 5) { + roundBit = 1; + if (roundDigit === 5) { + roundBit = digits[lastDigit] % 2 === 1 ? 1 : 0; + for (i = firstNonZero + lastDigit + 2; i < endOfString; i++) { + if (parseInt(representation[i], 10)) { + roundBit = 1; + break; + } + } + } + } + + if (roundBit) { + let dIdx = lastDigit; + + for (; dIdx >= 0; dIdx--) { + if (++digits[dIdx] > 9) { + digits[dIdx] = 0; + + // overflowed most significant digit + if (dIdx === 0) { + if (exponent < EXPONENT_MAX) { + exponent = exponent + 1; + digits[dIdx] = 1; + } else { + return new Decimal128( + Buffer.from(isNegative ? INF_NEGATIVE_BUFFER : INF_POSITIVE_BUFFER) + ); + } + } + } + } + } + } + + // Encode significand + // The high 17 digits of the significand + significandHigh = Long.fromNumber(0); + // The low 17 digits of the significand + significandLow = Long.fromNumber(0); + + // read a zero + if (significantDigits === 0) { + significandHigh = Long.fromNumber(0); + significandLow = Long.fromNumber(0); + } else if (lastDigit - firstDigit < 17) { + let dIdx = firstDigit; + significandLow = Long.fromNumber(digits[dIdx++]); + significandHigh = new Long(0, 0); + + for (; dIdx <= lastDigit; dIdx++) { + significandLow = significandLow.multiply(Long.fromNumber(10)); + significandLow = significandLow.add(Long.fromNumber(digits[dIdx])); + } + } else { + let dIdx = firstDigit; + significandHigh = Long.fromNumber(digits[dIdx++]); + + for (; dIdx <= lastDigit - 17; dIdx++) { + significandHigh = significandHigh.multiply(Long.fromNumber(10)); + significandHigh = significandHigh.add(Long.fromNumber(digits[dIdx])); + } + + significandLow = Long.fromNumber(digits[dIdx++]); + + for (; dIdx <= lastDigit; dIdx++) { + significandLow = significandLow.multiply(Long.fromNumber(10)); + significandLow = significandLow.add(Long.fromNumber(digits[dIdx])); + } + } + + const significand = multiply64x2(significandHigh, Long.fromString('100000000000000000')); + significand.low = significand.low.add(significandLow); + + if (lessThan(significand.low, significandLow)) { + significand.high = significand.high.add(Long.fromNumber(1)); + } + + // Biased exponent + biasedExponent = exponent + EXPONENT_BIAS; + const dec = { low: Long.fromNumber(0), high: Long.fromNumber(0) }; + + // Encode combination, exponent, and significand. + if ( + significand.high.shiftRightUnsigned(49).and(Long.fromNumber(1)).equals(Long.fromNumber(1)) + ) { + // Encode '11' into bits 1 to 3 + dec.high = dec.high.or(Long.fromNumber(0x3).shiftLeft(61)); + dec.high = dec.high.or( + Long.fromNumber(biasedExponent).and(Long.fromNumber(0x3fff).shiftLeft(47)) + ); + dec.high = dec.high.or(significand.high.and(Long.fromNumber(0x7fffffffffff))); + } else { + dec.high = dec.high.or(Long.fromNumber(biasedExponent & 0x3fff).shiftLeft(49)); + dec.high = dec.high.or(significand.high.and(Long.fromNumber(0x1ffffffffffff))); + } + + dec.low = significand.low; + + // Encode sign + if (isNegative) { + dec.high = dec.high.or(Long.fromString('9223372036854775808')); + } + + // Encode into a buffer + const buffer = Buffer.alloc(16); + index = 0; + + // Encode the low 64 bits of the decimal + // Encode low bits + buffer[index++] = dec.low.low & 0xff; + buffer[index++] = (dec.low.low >> 8) & 0xff; + buffer[index++] = (dec.low.low >> 16) & 0xff; + buffer[index++] = (dec.low.low >> 24) & 0xff; + // Encode high bits + buffer[index++] = dec.low.high & 0xff; + buffer[index++] = (dec.low.high >> 8) & 0xff; + buffer[index++] = (dec.low.high >> 16) & 0xff; + buffer[index++] = (dec.low.high >> 24) & 0xff; + + // Encode the high 64 bits of the decimal + // Encode low bits + buffer[index++] = dec.high.low & 0xff; + buffer[index++] = (dec.high.low >> 8) & 0xff; + buffer[index++] = (dec.high.low >> 16) & 0xff; + buffer[index++] = (dec.high.low >> 24) & 0xff; + // Encode high bits + buffer[index++] = dec.high.high & 0xff; + buffer[index++] = (dec.high.high >> 8) & 0xff; + buffer[index++] = (dec.high.high >> 16) & 0xff; + buffer[index++] = (dec.high.high >> 24) & 0xff; + + // Return the new Decimal128 + return new Decimal128(buffer); + } + + /** Create a string representation of the raw Decimal128 value */ + toString(): string { + // Note: bits in this routine are referred to starting at 0, + // from the sign bit, towards the coefficient. + + // decoded biased exponent (14 bits) + let biased_exponent; + // the number of significand digits + let significand_digits = 0; + // the base-10 digits in the significand + const significand = new Array(36); + for (let i = 0; i < significand.length; i++) significand[i] = 0; + // read pointer into significand + let index = 0; + + // true if the number is zero + let is_zero = false; + + // the most significant significand bits (50-46) + let significand_msb; + // temporary storage for significand decoding + let significand128: { parts: [number, number, number, number] } = { parts: [0, 0, 0, 0] }; + // indexing variables + let j, k; + + // Output string + const string: string[] = []; + + // Unpack index + index = 0; + + // Buffer reference + const buffer = this.bytes; + + // Unpack the low 64bits into a long + // bits 96 - 127 + const low = + buffer[index++] | (buffer[index++] << 8) | (buffer[index++] << 16) | (buffer[index++] << 24); + // bits 64 - 95 + const midl = + buffer[index++] | (buffer[index++] << 8) | (buffer[index++] << 16) | (buffer[index++] << 24); + + // Unpack the high 64bits into a long + // bits 32 - 63 + const midh = + buffer[index++] | (buffer[index++] << 8) | (buffer[index++] << 16) | (buffer[index++] << 24); + // bits 0 - 31 + const high = + buffer[index++] | (buffer[index++] << 8) | (buffer[index++] << 16) | (buffer[index++] << 24); + + // Unpack index + index = 0; + + // Create the state of the decimal + const dec = { + low: new Long(low, midl), + high: new Long(midh, high) + }; + + if (dec.high.lessThan(Long.ZERO)) { + string.push('-'); + } + + // Decode combination field and exponent + // bits 1 - 5 + const combination = (high >> 26) & COMBINATION_MASK; + + if (combination >> 3 === 3) { + // Check for 'special' values + if (combination === COMBINATION_INFINITY) { + return string.join('') + 'Infinity'; + } else if (combination === COMBINATION_NAN) { + return 'NaN'; + } else { + biased_exponent = (high >> 15) & EXPONENT_MASK; + significand_msb = 0x08 + ((high >> 14) & 0x01); + } + } else { + significand_msb = (high >> 14) & 0x07; + biased_exponent = (high >> 17) & EXPONENT_MASK; + } + + // unbiased exponent + const exponent = biased_exponent - EXPONENT_BIAS; + + // Create string of significand digits + + // Convert the 114-bit binary number represented by + // (significand_high, significand_low) to at most 34 decimal + // digits through modulo and division. + significand128.parts[0] = (high & 0x3fff) + ((significand_msb & 0xf) << 14); + significand128.parts[1] = midh; + significand128.parts[2] = midl; + significand128.parts[3] = low; + + if ( + significand128.parts[0] === 0 && + significand128.parts[1] === 0 && + significand128.parts[2] === 0 && + significand128.parts[3] === 0 + ) { + is_zero = true; + } else { + for (k = 3; k >= 0; k--) { + let least_digits = 0; + // Perform the divide + const result = divideu128(significand128); + significand128 = result.quotient; + least_digits = result.rem.low; + + // We now have the 9 least significant digits (in base 2). + // Convert and output to string. + if (!least_digits) continue; + + for (j = 8; j >= 0; j--) { + // significand[k * 9 + j] = Math.round(least_digits % 10); + significand[k * 9 + j] = least_digits % 10; + // least_digits = Math.round(least_digits / 10); + least_digits = Math.floor(least_digits / 10); + } + } + } + + // Output format options: + // Scientific - [-]d.dddE(+/-)dd or [-]dE(+/-)dd + // Regular - ddd.ddd + + if (is_zero) { + significand_digits = 1; + significand[index] = 0; + } else { + significand_digits = 36; + while (!significand[index]) { + significand_digits = significand_digits - 1; + index = index + 1; + } + } + + // the exponent if scientific notation is used + const scientific_exponent = significand_digits - 1 + exponent; + + // The scientific exponent checks are dictated by the string conversion + // specification and are somewhat arbitrary cutoffs. + // + // We must check exponent > 0, because if this is the case, the number + // has trailing zeros. However, we *cannot* output these trailing zeros, + // because doing so would change the precision of the value, and would + // change stored data if the string converted number is round tripped. + if (scientific_exponent >= 34 || scientific_exponent <= -7 || exponent > 0) { + // Scientific format + + // if there are too many significant digits, we should just be treating numbers + // as + or - 0 and using the non-scientific exponent (this is for the "invalid + // representation should be treated as 0/-0" spec cases in decimal128-1.json) + if (significand_digits > 34) { + string.push(`${0}`); + if (exponent > 0) string.push(`E+${exponent}`); + else if (exponent < 0) string.push(`E${exponent}`); + return string.join(''); + } + + string.push(`${significand[index++]}`); + significand_digits = significand_digits - 1; + + if (significand_digits) { + string.push('.'); + } + + for (let i = 0; i < significand_digits; i++) { + string.push(`${significand[index++]}`); + } + + // Exponent + string.push('E'); + if (scientific_exponent > 0) { + string.push(`+${scientific_exponent}`); + } else { + string.push(`${scientific_exponent}`); + } + } else { + // Regular format with no decimal place + if (exponent >= 0) { + for (let i = 0; i < significand_digits; i++) { + string.push(`${significand[index++]}`); + } + } else { + let radix_position = significand_digits + exponent; + + // non-zero digits before radix + if (radix_position > 0) { + for (let i = 0; i < radix_position; i++) { + string.push(`${significand[index++]}`); + } + } else { + string.push('0'); + } + + string.push('.'); + // add leading zeros after radix + while (radix_position++ < 0) { + string.push('0'); + } + + for (let i = 0; i < significand_digits - Math.max(radix_position - 1, 0); i++) { + string.push(`${significand[index++]}`); + } + } + } + + return string.join(''); + } + + toJSON(): Decimal128Extended { + return { $numberDecimal: this.toString() }; + } + + /** @internal */ + toExtendedJSON(): Decimal128Extended { + return { $numberDecimal: this.toString() }; + } + + /** @internal */ + static fromExtendedJSON(doc: Decimal128Extended): Decimal128 { + return Decimal128.fromString(doc.$numberDecimal); + } + + /** @internal */ + [Symbol.for('nodejs.util.inspect.custom')](): string { + return this.inspect(); + } + + inspect(): string { + return `new Decimal128("${this.toString()}")`; + } +} + +Object.defineProperty(Decimal128.prototype, '_bsontype', { value: 'Decimal128' }); diff --git a/ts-ticket-office-service/node_modules/bson/src/double.ts b/ts-ticket-office-service/node_modules/bson/src/double.ts new file mode 100644 index 000000000..51bbf22d7 --- /dev/null +++ b/ts-ticket-office-service/node_modules/bson/src/double.ts @@ -0,0 +1,91 @@ +import type { EJSONOptions } from './extended_json'; + +/** @public */ +export interface DoubleExtended { + $numberDouble: string; +} + +/** + * A class representation of the BSON Double type. + * @public + * @category BSONType + */ +export class Double { + _bsontype!: 'Double'; + + value!: number; + /** + * Create a Double type + * + * @param value - the number we want to represent as a double. + */ + constructor(value: number) { + if (!(this instanceof Double)) return new Double(value); + + if ((value as unknown) instanceof Number) { + value = value.valueOf(); + } + + this.value = +value; + } + + /** + * Access the number value. + * + * @returns returns the wrapped double number. + */ + valueOf(): number { + return this.value; + } + + toJSON(): number { + return this.value; + } + + toString(radix?: number): string { + return this.value.toString(radix); + } + + /** @internal */ + toExtendedJSON(options?: EJSONOptions): number | DoubleExtended { + if (options && (options.legacy || (options.relaxed && isFinite(this.value)))) { + return this.value; + } + + // NOTE: JavaScript has +0 and -0, apparently to model limit calculations. If a user + // explicitly provided `-0` then we need to ensure the sign makes it into the output + if (Object.is(Math.sign(this.value), -0)) { + return { $numberDouble: `-${this.value.toFixed(1)}` }; + } + + let $numberDouble: string; + if (Number.isInteger(this.value)) { + $numberDouble = this.value.toFixed(1); + if ($numberDouble.length >= 13) { + $numberDouble = this.value.toExponential(13).toUpperCase(); + } + } else { + $numberDouble = this.value.toString(); + } + + return { $numberDouble }; + } + + /** @internal */ + static fromExtendedJSON(doc: DoubleExtended, options?: EJSONOptions): number | Double { + const doubleValue = parseFloat(doc.$numberDouble); + return options && options.relaxed ? doubleValue : new Double(doubleValue); + } + + /** @internal */ + [Symbol.for('nodejs.util.inspect.custom')](): string { + return this.inspect(); + } + + inspect(): string { + const eJSON = this.toExtendedJSON() as DoubleExtended; + return `new Double(${eJSON.$numberDouble})`; + } +} + +Object.defineProperty(Double.prototype, '_bsontype', { value: 'Double' }); diff --git a/ts-ticket-office-service/node_modules/bson/src/ensure_buffer.ts b/ts-ticket-office-service/node_modules/bson/src/ensure_buffer.ts new file mode 100644 index 000000000..8b82a085e --- /dev/null +++ b/ts-ticket-office-service/node_modules/bson/src/ensure_buffer.ts @@ -0,0 +1,27 @@ +import { Buffer } from 'buffer'; +import { BSONTypeError } from './error'; +import { isAnyArrayBuffer } from './parser/utils'; + +/** + * Makes sure that, if a Uint8Array is passed in, it is wrapped in a Buffer. + * + * @param potentialBuffer - The potential buffer + * @returns Buffer the input if potentialBuffer is a buffer, or a buffer that + * wraps a passed in Uint8Array + * @throws BSONTypeError If anything other than a Buffer or Uint8Array is passed in + */ +export function ensureBuffer(potentialBuffer: Buffer | ArrayBufferView | ArrayBuffer): Buffer { + if (ArrayBuffer.isView(potentialBuffer)) { + return Buffer.from( + potentialBuffer.buffer, + potentialBuffer.byteOffset, + potentialBuffer.byteLength + ); + } + + if (isAnyArrayBuffer(potentialBuffer)) { + return Buffer.from(potentialBuffer); + } + + throw new BSONTypeError('Must use either Buffer or TypedArray'); +} diff --git a/ts-ticket-office-service/node_modules/bson/src/error.ts b/ts-ticket-office-service/node_modules/bson/src/error.ts new file mode 100644 index 000000000..8f1a41736 --- /dev/null +++ b/ts-ticket-office-service/node_modules/bson/src/error.ts @@ -0,0 +1,23 @@ +/** @public */ +export class BSONError extends Error { + constructor(message: string) { + super(message); + Object.setPrototypeOf(this, BSONError.prototype); + } + + get name(): string { + return 'BSONError'; + } +} + +/** @public */ +export class BSONTypeError extends TypeError { + constructor(message: string) { + super(message); + Object.setPrototypeOf(this, BSONTypeError.prototype); + } + + get name(): string { + return 'BSONTypeError'; + } +} diff --git a/ts-ticket-office-service/node_modules/bson/src/extended_json.ts b/ts-ticket-office-service/node_modules/bson/src/extended_json.ts new file mode 100644 index 000000000..90269623b --- /dev/null +++ b/ts-ticket-office-service/node_modules/bson/src/extended_json.ts @@ -0,0 +1,462 @@ +import { Binary } from './binary'; +import type { Document } from './bson'; +import { Code } from './code'; +import { DBRef, isDBRefLike } from './db_ref'; +import { Decimal128 } from './decimal128'; +import { Double } from './double'; +import { BSONError, BSONTypeError } from './error'; +import { Int32 } from './int_32'; +import { Long } from './long'; +import { MaxKey } from './max_key'; +import { MinKey } from './min_key'; +import { ObjectId } from './objectid'; +import { isDate, isObjectLike, isRegExp } from './parser/utils'; +import { BSONRegExp } from './regexp'; +import { BSONSymbol } from './symbol'; +import { Timestamp } from './timestamp'; + +/** @public */ +export type EJSONOptions = EJSON.Options; + +/** @internal */ +type BSONType = + | Binary + | Code + | DBRef + | Decimal128 + | Double + | Int32 + | Long + | MaxKey + | MinKey + | ObjectId + | BSONRegExp + | BSONSymbol + | Timestamp; + +export function isBSONType(value: unknown): value is BSONType { + return ( + isObjectLike(value) && Reflect.has(value, '_bsontype') && typeof value._bsontype === 'string' + ); +} + +// INT32 boundaries +const BSON_INT32_MAX = 0x7fffffff; +const BSON_INT32_MIN = -0x80000000; +// INT64 boundaries +// const BSON_INT64_MAX = 0x7fffffffffffffff; // TODO(NODE-4377): This number cannot be precisely represented in JS +const BSON_INT64_MAX = 0x8000000000000000; +const BSON_INT64_MIN = -0x8000000000000000; + +// all the types where we don't need to do any special processing and can just pass the EJSON +//straight to type.fromExtendedJSON +const keysToCodecs = { + $oid: ObjectId, + $binary: Binary, + $uuid: Binary, + $symbol: BSONSymbol, + $numberInt: Int32, + $numberDecimal: Decimal128, + $numberDouble: Double, + $numberLong: Long, + $minKey: MinKey, + $maxKey: MaxKey, + $regex: BSONRegExp, + $regularExpression: BSONRegExp, + $timestamp: Timestamp +} as const; + +// eslint-disable-next-line @typescript-eslint/no-explicit-any +function deserializeValue(value: any, options: EJSON.Options = {}) { + if (typeof value === 'number') { + if (options.relaxed || options.legacy) { + return value; + } + + // if it's an integer, should interpret as smallest BSON integer + // that can represent it exactly. (if out of range, interpret as double.) + if (Math.floor(value) === value) { + if (value >= BSON_INT32_MIN && value <= BSON_INT32_MAX) return new Int32(value); + if (value >= BSON_INT64_MIN && value <= BSON_INT64_MAX) return Long.fromNumber(value); + } + + // If the number is a non-integer or out of integer range, should interpret as BSON Double. + return new Double(value); + } + + // from here on out we're looking for bson types, so bail if its not an object + if (value == null || typeof value !== 'object') return value; + + // upgrade deprecated undefined to null + if (value.$undefined) return null; + + const keys = Object.keys(value).filter( + k => k.startsWith('$') && value[k] != null + ) as (keyof typeof keysToCodecs)[]; + for (let i = 0; i < keys.length; i++) { + const c = keysToCodecs[keys[i]]; + if (c) return c.fromExtendedJSON(value, options); + } + + if (value.$date != null) { + const d = value.$date; + const date = new Date(); + + if (options.legacy) { + if (typeof d === 'number') date.setTime(d); + else if (typeof d === 'string') date.setTime(Date.parse(d)); + } else { + if (typeof d === 'string') date.setTime(Date.parse(d)); + else if (Long.isLong(d)) date.setTime(d.toNumber()); + else if (typeof d === 'number' && options.relaxed) date.setTime(d); + } + return date; + } + + if (value.$code != null) { + const copy = Object.assign({}, value); + if (value.$scope) { + copy.$scope = deserializeValue(value.$scope); + } + + return Code.fromExtendedJSON(value); + } + + if (isDBRefLike(value) || value.$dbPointer) { + const v = value.$ref ? value : value.$dbPointer; + + // we run into this in a "degenerate EJSON" case (with $id and $ref order flipped) + // because of the order JSON.parse goes through the document + if (v instanceof DBRef) return v; + + const dollarKeys = Object.keys(v).filter(k => k.startsWith('$')); + let valid = true; + dollarKeys.forEach(k => { + if (['$ref', '$id', '$db'].indexOf(k) === -1) valid = false; + }); + + // only make DBRef if $ keys are all valid + if (valid) return DBRef.fromExtendedJSON(v); + } + + return value; +} + +type EJSONSerializeOptions = EJSON.Options & { + seenObjects: { obj: unknown; propertyName: string }[]; +}; + +// eslint-disable-next-line @typescript-eslint/no-explicit-any +function serializeArray(array: any[], options: EJSONSerializeOptions): any[] { + return array.map((v: unknown, index: number) => { + options.seenObjects.push({ propertyName: `index ${index}`, obj: null }); + try { + return serializeValue(v, options); + } finally { + options.seenObjects.pop(); + } + }); +} + +function getISOString(date: Date) { + const isoStr = date.toISOString(); + // we should only show milliseconds in timestamp if they're non-zero + return date.getUTCMilliseconds() !== 0 ? isoStr : isoStr.slice(0, -5) + 'Z'; +} + +// eslint-disable-next-line @typescript-eslint/no-explicit-any +function serializeValue(value: any, options: EJSONSerializeOptions): any { + if ((typeof value === 'object' || typeof value === 'function') && value !== null) { + const index = options.seenObjects.findIndex(entry => entry.obj === value); + if (index !== -1) { + const props = options.seenObjects.map(entry => entry.propertyName); + const leadingPart = props + .slice(0, index) + .map(prop => `${prop} -> `) + .join(''); + const alreadySeen = props[index]; + const circularPart = + ' -> ' + + props + .slice(index + 1, props.length - 1) + .map(prop => `${prop} -> `) + .join(''); + const current = props[props.length - 1]; + const leadingSpace = ' '.repeat(leadingPart.length + alreadySeen.length / 2); + const dashes = '-'.repeat( + circularPart.length + (alreadySeen.length + current.length) / 2 - 1 + ); + + throw new BSONTypeError( + 'Converting circular structure to EJSON:\n' + + ` ${leadingPart}${alreadySeen}${circularPart}${current}\n` + + ` ${leadingSpace}\\${dashes}/` + ); + } + options.seenObjects[options.seenObjects.length - 1].obj = value; + } + + if (Array.isArray(value)) return serializeArray(value, options); + + if (value === undefined) return null; + + if (value instanceof Date || isDate(value)) { + const dateNum = value.getTime(), + // is it in year range 1970-9999? + inRange = dateNum > -1 && dateNum < 253402318800000; + + if (options.legacy) { + return options.relaxed && inRange + ? { $date: value.getTime() } + : { $date: getISOString(value) }; + } + return options.relaxed && inRange + ? { $date: getISOString(value) } + : { $date: { $numberLong: value.getTime().toString() } }; + } + + if (typeof value === 'number' && (!options.relaxed || !isFinite(value))) { + // it's an integer + if (Math.floor(value) === value) { + const int32Range = value >= BSON_INT32_MIN && value <= BSON_INT32_MAX, + int64Range = value >= BSON_INT64_MIN && value <= BSON_INT64_MAX; + + // interpret as being of the smallest BSON integer type that can represent the number exactly + if (int32Range) return { $numberInt: value.toString() }; + if (int64Range) return { $numberLong: value.toString() }; + } + return { $numberDouble: value.toString() }; + } + + if (value instanceof RegExp || isRegExp(value)) { + let flags = value.flags; + if (flags === undefined) { + const match = value.toString().match(/[gimuy]*$/); + if (match) { + flags = match[0]; + } + } + + const rx = new BSONRegExp(value.source, flags); + return rx.toExtendedJSON(options); + } + + if (value != null && typeof value === 'object') return serializeDocument(value, options); + return value; +} + +const BSON_TYPE_MAPPINGS = { + Binary: (o: Binary) => new Binary(o.value(), o.sub_type), + Code: (o: Code) => new Code(o.code, o.scope), + DBRef: (o: DBRef) => new DBRef(o.collection || o.namespace, o.oid, o.db, o.fields), // "namespace" for 1.x library backwards compat + Decimal128: (o: Decimal128) => new Decimal128(o.bytes), + Double: (o: Double) => new Double(o.value), + Int32: (o: Int32) => new Int32(o.value), + Long: ( + o: Long & { + low_: number; + high_: number; + unsigned_: boolean | undefined; + } + ) => + Long.fromBits( + // underscore variants for 1.x backwards compatibility + o.low != null ? o.low : o.low_, + o.low != null ? o.high : o.high_, + o.low != null ? o.unsigned : o.unsigned_ + ), + MaxKey: () => new MaxKey(), + MinKey: () => new MinKey(), + ObjectID: (o: ObjectId) => new ObjectId(o), + ObjectId: (o: ObjectId) => new ObjectId(o), // support 4.0.0/4.0.1 before _bsontype was reverted back to ObjectID + BSONRegExp: (o: BSONRegExp) => new BSONRegExp(o.pattern, o.options), + Symbol: (o: BSONSymbol) => new BSONSymbol(o.value), + Timestamp: (o: Timestamp) => Timestamp.fromBits(o.low, o.high) +} as const; + +// eslint-disable-next-line @typescript-eslint/no-explicit-any +function serializeDocument(doc: any, options: EJSONSerializeOptions) { + if (doc == null || typeof doc !== 'object') throw new BSONError('not an object instance'); + + const bsontype: BSONType['_bsontype'] = doc._bsontype; + if (typeof bsontype === 'undefined') { + // It's a regular object. Recursively serialize its property values. + const _doc: Document = {}; + for (const name in doc) { + options.seenObjects.push({ propertyName: name, obj: null }); + try { + const value = serializeValue(doc[name], options); + if (name === '__proto__') { + Object.defineProperty(_doc, name, { + value, + writable: true, + enumerable: true, + configurable: true + }); + } else { + _doc[name] = value; + } + } finally { + options.seenObjects.pop(); + } + } + return _doc; + } else if (isBSONType(doc)) { + // the "document" is really just a BSON type object + // eslint-disable-next-line @typescript-eslint/no-explicit-any + let outDoc: any = doc; + if (typeof outDoc.toExtendedJSON !== 'function') { + // There's no EJSON serialization function on the object. It's probably an + // object created by a previous version of this library (or another library) + // that's duck-typing objects to look like they were generated by this library). + // Copy the object into this library's version of that type. + const mapper = BSON_TYPE_MAPPINGS[doc._bsontype]; + if (!mapper) { + throw new BSONTypeError('Unrecognized or invalid _bsontype: ' + doc._bsontype); + } + outDoc = mapper(outDoc); + } + + // Two BSON types may have nested objects that may need to be serialized too + if (bsontype === 'Code' && outDoc.scope) { + outDoc = new Code(outDoc.code, serializeValue(outDoc.scope, options)); + } else if (bsontype === 'DBRef' && outDoc.oid) { + outDoc = new DBRef( + serializeValue(outDoc.collection, options), + serializeValue(outDoc.oid, options), + serializeValue(outDoc.db, options), + serializeValue(outDoc.fields, options) + ); + } + + return outDoc.toExtendedJSON(options); + } else { + throw new BSONError('_bsontype must be a string, but was: ' + typeof bsontype); + } +} + +/** + * EJSON parse / stringify API + * @public + */ +// the namespace here is used to emulate `export * as EJSON from '...'` +// which as of now (sept 2020) api-extractor does not support +// eslint-disable-next-line @typescript-eslint/no-namespace +export namespace EJSON { + export interface Options { + /** Output using the Extended JSON v1 spec */ + legacy?: boolean; + /** Enable Extended JSON's `relaxed` mode, which attempts to return native JS types where possible, rather than BSON types */ + relaxed?: boolean; + /** + * Disable Extended JSON's `relaxed` mode, which attempts to return BSON types where possible, rather than native JS types + * @deprecated Please use the relaxed property instead + */ + strict?: boolean; + } + + /** + * Parse an Extended JSON string, constructing the JavaScript value or object described by that + * string. + * + * @example + * ```js + * const { EJSON } = require('bson'); + * const text = '{ "int32": { "$numberInt": "10" } }'; + * + * // prints { int32: { [String: '10'] _bsontype: 'Int32', value: '10' } } + * console.log(EJSON.parse(text, { relaxed: false })); + * + * // prints { int32: 10 } + * console.log(EJSON.parse(text)); + * ``` + */ + export function parse(text: string, options?: EJSON.Options): SerializableTypes { + const finalOptions = Object.assign({}, { relaxed: true, legacy: false }, options); + + // relaxed implies not strict + if (typeof finalOptions.relaxed === 'boolean') finalOptions.strict = !finalOptions.relaxed; + if (typeof finalOptions.strict === 'boolean') finalOptions.relaxed = !finalOptions.strict; + + return JSON.parse(text, (key, value) => { + if (key.indexOf('\x00') !== -1) { + throw new BSONError( + `BSON Document field names cannot contain null bytes, found: ${JSON.stringify(key)}` + ); + } + return deserializeValue(value, finalOptions); + }); + } + + export type JSONPrimitive = string | number | boolean | null; + export type SerializableTypes = Document | Array | JSONPrimitive; + + /** + * Converts a BSON document to an Extended JSON string, optionally replacing values if a replacer + * function is specified or optionally including only the specified properties if a replacer array + * is specified. + * + * @param value - The value to convert to extended JSON + * @param replacer - A function that alters the behavior of the stringification process, or an array of String and Number objects that serve as a whitelist for selecting/filtering the properties of the value object to be included in the JSON string. If this value is null or not provided, all properties of the object are included in the resulting JSON string + * @param space - A String or Number object that's used to insert white space into the output JSON string for readability purposes. + * @param options - Optional settings + * + * @example + * ```js + * const { EJSON } = require('bson'); + * const Int32 = require('mongodb').Int32; + * const doc = { int32: new Int32(10) }; + * + * // prints '{"int32":{"$numberInt":"10"}}' + * console.log(EJSON.stringify(doc, { relaxed: false })); + * + * // prints '{"int32":10}' + * console.log(EJSON.stringify(doc)); + * ``` + */ + export function stringify( + value: SerializableTypes, + // eslint-disable-next-line @typescript-eslint/no-explicit-any + replacer?: (number | string)[] | ((this: any, key: string, value: any) => any) | EJSON.Options, + space?: string | number, + options?: EJSON.Options + ): string { + if (space != null && typeof space === 'object') { + options = space; + space = 0; + } + if (replacer != null && typeof replacer === 'object' && !Array.isArray(replacer)) { + options = replacer; + replacer = undefined; + space = 0; + } + const serializeOptions = Object.assign({ relaxed: true, legacy: false }, options, { + seenObjects: [{ propertyName: '(root)', obj: null }] + }); + + const doc = serializeValue(value, serializeOptions); + return JSON.stringify(doc, replacer as Parameters[1], space); + } + + /** + * Serializes an object to an Extended JSON string, and reparse it as a JavaScript object. + * + * @param value - The object to serialize + * @param options - Optional settings passed to the `stringify` function + */ + export function serialize(value: SerializableTypes, options?: EJSON.Options): Document { + options = options || {}; + return JSON.parse(stringify(value, options)); + } + + /** + * Deserializes an Extended JSON object into a plain JavaScript object with native/BSON types + * + * @param ejson - The Extended JSON object to deserialize + * @param options - Optional settings passed to the parse method + */ + export function deserialize(ejson: Document, options?: EJSON.Options): SerializableTypes { + options = options || {}; + return parse(JSON.stringify(ejson), options); + } +} diff --git a/ts-ticket-office-service/node_modules/bson/src/int_32.ts b/ts-ticket-office-service/node_modules/bson/src/int_32.ts new file mode 100644 index 000000000..b3b5760cc --- /dev/null +++ b/ts-ticket-office-service/node_modules/bson/src/int_32.ts @@ -0,0 +1,70 @@ +import type { EJSONOptions } from './extended_json'; + +/** @public */ +export interface Int32Extended { + $numberInt: string; +} + +/** + * A class representation of a BSON Int32 type. + * @public + * @category BSONType + */ +export class Int32 { + _bsontype!: 'Int32'; + + value!: number; + /** + * Create an Int32 type + * + * @param value - the number we want to represent as an int32. + */ + constructor(value: number | string) { + if (!(this instanceof Int32)) return new Int32(value); + + if ((value as unknown) instanceof Number) { + value = value.valueOf(); + } + + this.value = +value | 0; + } + + /** + * Access the number value. + * + * @returns returns the wrapped int32 number. + */ + valueOf(): number { + return this.value; + } + + toString(radix?: number): string { + return this.value.toString(radix); + } + + toJSON(): number { + return this.value; + } + + /** @internal */ + toExtendedJSON(options?: EJSONOptions): number | Int32Extended { + if (options && (options.relaxed || options.legacy)) return this.value; + return { $numberInt: this.value.toString() }; + } + + /** @internal */ + static fromExtendedJSON(doc: Int32Extended, options?: EJSONOptions): number | Int32 { + return options && options.relaxed ? parseInt(doc.$numberInt, 10) : new Int32(doc.$numberInt); + } + + /** @internal */ + [Symbol.for('nodejs.util.inspect.custom')](): string { + return this.inspect(); + } + + inspect(): string { + return `new Int32(${this.valueOf()})`; + } +} + +Object.defineProperty(Int32.prototype, '_bsontype', { value: 'Int32' }); diff --git a/ts-ticket-office-service/node_modules/bson/src/long.ts b/ts-ticket-office-service/node_modules/bson/src/long.ts new file mode 100644 index 000000000..ed3f6e1b7 --- /dev/null +++ b/ts-ticket-office-service/node_modules/bson/src/long.ts @@ -0,0 +1,1040 @@ +import type { EJSONOptions } from './extended_json'; +import { isObjectLike } from './parser/utils'; +import type { Timestamp } from './timestamp'; + +interface LongWASMHelpers { + /** Gets the high bits of the last operation performed */ + get_high(this: void): number; + div_u( + this: void, + lowBits: number, + highBits: number, + lowBitsDivisor: number, + highBitsDivisor: number + ): number; + div_s( + this: void, + lowBits: number, + highBits: number, + lowBitsDivisor: number, + highBitsDivisor: number + ): number; + rem_u( + this: void, + lowBits: number, + highBits: number, + lowBitsDivisor: number, + highBitsDivisor: number + ): number; + rem_s( + this: void, + lowBits: number, + highBits: number, + lowBitsDivisor: number, + highBitsDivisor: number + ): number; + mul( + this: void, + lowBits: number, + highBits: number, + lowBitsMultiplier: number, + highBitsMultiplier: number + ): number; +} + +/** + * wasm optimizations, to do native i64 multiplication and divide + */ +let wasm: LongWASMHelpers | undefined = undefined; + +/* We do not want to have to include DOM types just for this check */ +// eslint-disable-next-line @typescript-eslint/no-explicit-any +declare const WebAssembly: any; + +try { + wasm = new WebAssembly.Instance( + new WebAssembly.Module( + // prettier-ignore + new Uint8Array([0, 97, 115, 109, 1, 0, 0, 0, 1, 13, 2, 96, 0, 1, 127, 96, 4, 127, 127, 127, 127, 1, 127, 3, 7, 6, 0, 1, 1, 1, 1, 1, 6, 6, 1, 127, 1, 65, 0, 11, 7, 50, 6, 3, 109, 117, 108, 0, 1, 5, 100, 105, 118, 95, 115, 0, 2, 5, 100, 105, 118, 95, 117, 0, 3, 5, 114, 101, 109, 95, 115, 0, 4, 5, 114, 101, 109, 95, 117, 0, 5, 8, 103, 101, 116, 95, 104, 105, 103, 104, 0, 0, 10, 191, 1, 6, 4, 0, 35, 0, 11, 36, 1, 1, 126, 32, 0, 173, 32, 1, 173, 66, 32, 134, 132, 32, 2, 173, 32, 3, 173, 66, 32, 134, 132, 126, 34, 4, 66, 32, 135, 167, 36, 0, 32, 4, 167, 11, 36, 1, 1, 126, 32, 0, 173, 32, 1, 173, 66, 32, 134, 132, 32, 2, 173, 32, 3, 173, 66, 32, 134, 132, 127, 34, 4, 66, 32, 135, 167, 36, 0, 32, 4, 167, 11, 36, 1, 1, 126, 32, 0, 173, 32, 1, 173, 66, 32, 134, 132, 32, 2, 173, 32, 3, 173, 66, 32, 134, 132, 128, 34, 4, 66, 32, 135, 167, 36, 0, 32, 4, 167, 11, 36, 1, 1, 126, 32, 0, 173, 32, 1, 173, 66, 32, 134, 132, 32, 2, 173, 32, 3, 173, 66, 32, 134, 132, 129, 34, 4, 66, 32, 135, 167, 36, 0, 32, 4, 167, 11, 36, 1, 1, 126, 32, 0, 173, 32, 1, 173, 66, 32, 134, 132, 32, 2, 173, 32, 3, 173, 66, 32, 134, 132, 130, 34, 4, 66, 32, 135, 167, 36, 0, 32, 4, 167, 11]) + ), + {} + ).exports as unknown as LongWASMHelpers; +} catch { + // no wasm support +} + +const TWO_PWR_16_DBL = 1 << 16; +const TWO_PWR_24_DBL = 1 << 24; +const TWO_PWR_32_DBL = TWO_PWR_16_DBL * TWO_PWR_16_DBL; +const TWO_PWR_64_DBL = TWO_PWR_32_DBL * TWO_PWR_32_DBL; +const TWO_PWR_63_DBL = TWO_PWR_64_DBL / 2; + +/** A cache of the Long representations of small integer values. */ +const INT_CACHE: { [key: number]: Long } = {}; + +/** A cache of the Long representations of small unsigned integer values. */ +const UINT_CACHE: { [key: number]: Long } = {}; + +/** @public */ +export interface LongExtended { + $numberLong: string; +} + +/** + * A class representing a 64-bit integer + * @public + * @category BSONType + * @remarks + * The internal representation of a long is the two given signed, 32-bit values. + * We use 32-bit pieces because these are the size of integers on which + * Javascript performs bit-operations. For operations like addition and + * multiplication, we split each number into 16 bit pieces, which can easily be + * multiplied within Javascript's floating-point representation without overflow + * or change in sign. + * In the algorithms below, we frequently reduce the negative case to the + * positive case by negating the input(s) and then post-processing the result. + * Note that we must ALWAYS check specially whether those values are MIN_VALUE + * (-2^63) because -MIN_VALUE == MIN_VALUE (since 2^63 cannot be represented as + * a positive number, it overflows back into a negative). Not handling this + * case would often result in infinite recursion. + * Common constant values ZERO, ONE, NEG_ONE, etc. are found as static properties on this class. + */ +export class Long { + _bsontype!: 'Long'; + + /** An indicator used to reliably determine if an object is a Long or not. */ + __isLong__!: true; + + /** + * The high 32 bits as a signed value. + */ + high!: number; + + /** + * The low 32 bits as a signed value. + */ + low!: number; + + /** + * Whether unsigned or not. + */ + unsigned!: boolean; + + /** + * Constructs a 64 bit two's-complement integer, given its low and high 32 bit values as *signed* integers. + * See the from* functions below for more convenient ways of constructing Longs. + * + * Acceptable signatures are: + * - Long(low, high, unsigned?) + * - Long(bigint, unsigned?) + * - Long(string, unsigned?) + * + * @param low - The low (signed) 32 bits of the long + * @param high - The high (signed) 32 bits of the long + * @param unsigned - Whether unsigned or not, defaults to signed + */ + constructor(low: number | bigint | string = 0, high?: number | boolean, unsigned?: boolean) { + if (!(this instanceof Long)) return new Long(low, high, unsigned); + + if (typeof low === 'bigint') { + Object.assign(this, Long.fromBigInt(low, !!high)); + } else if (typeof low === 'string') { + Object.assign(this, Long.fromString(low, !!high)); + } else { + this.low = low | 0; + this.high = (high as number) | 0; + this.unsigned = !!unsigned; + } + + Object.defineProperty(this, '__isLong__', { + value: true, + configurable: false, + writable: false, + enumerable: false + }); + } + + static TWO_PWR_24 = Long.fromInt(TWO_PWR_24_DBL); + + /** Maximum unsigned value. */ + static MAX_UNSIGNED_VALUE = Long.fromBits(0xffffffff | 0, 0xffffffff | 0, true); + /** Signed zero */ + static ZERO = Long.fromInt(0); + /** Unsigned zero. */ + static UZERO = Long.fromInt(0, true); + /** Signed one. */ + static ONE = Long.fromInt(1); + /** Unsigned one. */ + static UONE = Long.fromInt(1, true); + /** Signed negative one. */ + static NEG_ONE = Long.fromInt(-1); + /** Maximum signed value. */ + static MAX_VALUE = Long.fromBits(0xffffffff | 0, 0x7fffffff | 0, false); + /** Minimum signed value. */ + static MIN_VALUE = Long.fromBits(0, 0x80000000 | 0, false); + + /** + * Returns a Long representing the 64 bit integer that comes by concatenating the given low and high bits. + * Each is assumed to use 32 bits. + * @param lowBits - The low 32 bits + * @param highBits - The high 32 bits + * @param unsigned - Whether unsigned or not, defaults to signed + * @returns The corresponding Long value + */ + static fromBits(lowBits: number, highBits: number, unsigned?: boolean): Long { + return new Long(lowBits, highBits, unsigned); + } + + /** + * Returns a Long representing the given 32 bit integer value. + * @param value - The 32 bit integer in question + * @param unsigned - Whether unsigned or not, defaults to signed + * @returns The corresponding Long value + */ + static fromInt(value: number, unsigned?: boolean): Long { + let obj, cachedObj, cache; + if (unsigned) { + value >>>= 0; + if ((cache = 0 <= value && value < 256)) { + cachedObj = UINT_CACHE[value]; + if (cachedObj) return cachedObj; + } + obj = Long.fromBits(value, (value | 0) < 0 ? -1 : 0, true); + if (cache) UINT_CACHE[value] = obj; + return obj; + } else { + value |= 0; + if ((cache = -128 <= value && value < 128)) { + cachedObj = INT_CACHE[value]; + if (cachedObj) return cachedObj; + } + obj = Long.fromBits(value, value < 0 ? -1 : 0, false); + if (cache) INT_CACHE[value] = obj; + return obj; + } + } + + /** + * Returns a Long representing the given value, provided that it is a finite number. Otherwise, zero is returned. + * @param value - The number in question + * @param unsigned - Whether unsigned or not, defaults to signed + * @returns The corresponding Long value + */ + static fromNumber(value: number, unsigned?: boolean): Long { + if (isNaN(value)) return unsigned ? Long.UZERO : Long.ZERO; + if (unsigned) { + if (value < 0) return Long.UZERO; + if (value >= TWO_PWR_64_DBL) return Long.MAX_UNSIGNED_VALUE; + } else { + if (value <= -TWO_PWR_63_DBL) return Long.MIN_VALUE; + if (value + 1 >= TWO_PWR_63_DBL) return Long.MAX_VALUE; + } + if (value < 0) return Long.fromNumber(-value, unsigned).neg(); + return Long.fromBits(value % TWO_PWR_32_DBL | 0, (value / TWO_PWR_32_DBL) | 0, unsigned); + } + + /** + * Returns a Long representing the given value, provided that it is a finite number. Otherwise, zero is returned. + * @param value - The number in question + * @param unsigned - Whether unsigned or not, defaults to signed + * @returns The corresponding Long value + */ + static fromBigInt(value: bigint, unsigned?: boolean): Long { + return Long.fromString(value.toString(), unsigned); + } + + /** + * Returns a Long representation of the given string, written using the specified radix. + * @param str - The textual representation of the Long + * @param unsigned - Whether unsigned or not, defaults to signed + * @param radix - The radix in which the text is written (2-36), defaults to 10 + * @returns The corresponding Long value + */ + static fromString(str: string, unsigned?: boolean, radix?: number): Long { + if (str.length === 0) throw Error('empty string'); + if (str === 'NaN' || str === 'Infinity' || str === '+Infinity' || str === '-Infinity') + return Long.ZERO; + if (typeof unsigned === 'number') { + // For goog.math.long compatibility + (radix = unsigned), (unsigned = false); + } else { + unsigned = !!unsigned; + } + radix = radix || 10; + if (radix < 2 || 36 < radix) throw RangeError('radix'); + + let p; + if ((p = str.indexOf('-')) > 0) throw Error('interior hyphen'); + else if (p === 0) { + return Long.fromString(str.substring(1), unsigned, radix).neg(); + } + + // Do several (8) digits each time through the loop, so as to + // minimize the calls to the very expensive emulated div. + const radixToPower = Long.fromNumber(Math.pow(radix, 8)); + + let result = Long.ZERO; + for (let i = 0; i < str.length; i += 8) { + const size = Math.min(8, str.length - i), + value = parseInt(str.substring(i, i + size), radix); + if (size < 8) { + const power = Long.fromNumber(Math.pow(radix, size)); + result = result.mul(power).add(Long.fromNumber(value)); + } else { + result = result.mul(radixToPower); + result = result.add(Long.fromNumber(value)); + } + } + result.unsigned = unsigned; + return result; + } + + /** + * Creates a Long from its byte representation. + * @param bytes - Byte representation + * @param unsigned - Whether unsigned or not, defaults to signed + * @param le - Whether little or big endian, defaults to big endian + * @returns The corresponding Long value + */ + static fromBytes(bytes: number[], unsigned?: boolean, le?: boolean): Long { + return le ? Long.fromBytesLE(bytes, unsigned) : Long.fromBytesBE(bytes, unsigned); + } + + /** + * Creates a Long from its little endian byte representation. + * @param bytes - Little endian byte representation + * @param unsigned - Whether unsigned or not, defaults to signed + * @returns The corresponding Long value + */ + static fromBytesLE(bytes: number[], unsigned?: boolean): Long { + return new Long( + bytes[0] | (bytes[1] << 8) | (bytes[2] << 16) | (bytes[3] << 24), + bytes[4] | (bytes[5] << 8) | (bytes[6] << 16) | (bytes[7] << 24), + unsigned + ); + } + + /** + * Creates a Long from its big endian byte representation. + * @param bytes - Big endian byte representation + * @param unsigned - Whether unsigned or not, defaults to signed + * @returns The corresponding Long value + */ + static fromBytesBE(bytes: number[], unsigned?: boolean): Long { + return new Long( + (bytes[4] << 24) | (bytes[5] << 16) | (bytes[6] << 8) | bytes[7], + (bytes[0] << 24) | (bytes[1] << 16) | (bytes[2] << 8) | bytes[3], + unsigned + ); + } + + /** + * Tests if the specified object is a Long. + */ + static isLong(value: unknown): value is Long { + return isObjectLike(value) && value['__isLong__'] === true; + } + + /** + * Converts the specified value to a Long. + * @param unsigned - Whether unsigned or not, defaults to signed + */ + static fromValue( + val: number | string | { low: number; high: number; unsigned?: boolean }, + unsigned?: boolean + ): Long { + if (typeof val === 'number') return Long.fromNumber(val, unsigned); + if (typeof val === 'string') return Long.fromString(val, unsigned); + // Throws for non-objects, converts non-instanceof Long: + return Long.fromBits( + val.low, + val.high, + typeof unsigned === 'boolean' ? unsigned : val.unsigned + ); + } + + /** Returns the sum of this and the specified Long. */ + add(addend: string | number | Long | Timestamp): Long { + if (!Long.isLong(addend)) addend = Long.fromValue(addend); + + // Divide each number into 4 chunks of 16 bits, and then sum the chunks. + + const a48 = this.high >>> 16; + const a32 = this.high & 0xffff; + const a16 = this.low >>> 16; + const a00 = this.low & 0xffff; + + const b48 = addend.high >>> 16; + const b32 = addend.high & 0xffff; + const b16 = addend.low >>> 16; + const b00 = addend.low & 0xffff; + + let c48 = 0, + c32 = 0, + c16 = 0, + c00 = 0; + c00 += a00 + b00; + c16 += c00 >>> 16; + c00 &= 0xffff; + c16 += a16 + b16; + c32 += c16 >>> 16; + c16 &= 0xffff; + c32 += a32 + b32; + c48 += c32 >>> 16; + c32 &= 0xffff; + c48 += a48 + b48; + c48 &= 0xffff; + return Long.fromBits((c16 << 16) | c00, (c48 << 16) | c32, this.unsigned); + } + + /** + * Returns the sum of this and the specified Long. + * @returns Sum + */ + and(other: string | number | Long | Timestamp): Long { + if (!Long.isLong(other)) other = Long.fromValue(other); + return Long.fromBits(this.low & other.low, this.high & other.high, this.unsigned); + } + + /** + * Compares this Long's value with the specified's. + * @returns 0 if they are the same, 1 if the this is greater and -1 if the given one is greater + */ + compare(other: string | number | Long | Timestamp): 0 | 1 | -1 { + if (!Long.isLong(other)) other = Long.fromValue(other); + if (this.eq(other)) return 0; + const thisNeg = this.isNegative(), + otherNeg = other.isNegative(); + if (thisNeg && !otherNeg) return -1; + if (!thisNeg && otherNeg) return 1; + // At this point the sign bits are the same + if (!this.unsigned) return this.sub(other).isNegative() ? -1 : 1; + // Both are positive if at least one is unsigned + return other.high >>> 0 > this.high >>> 0 || + (other.high === this.high && other.low >>> 0 > this.low >>> 0) + ? -1 + : 1; + } + + /** This is an alias of {@link Long.compare} */ + comp(other: string | number | Long | Timestamp): 0 | 1 | -1 { + return this.compare(other); + } + + /** + * Returns this Long divided by the specified. The result is signed if this Long is signed or unsigned if this Long is unsigned. + * @returns Quotient + */ + divide(divisor: string | number | Long | Timestamp): Long { + if (!Long.isLong(divisor)) divisor = Long.fromValue(divisor); + if (divisor.isZero()) throw Error('division by zero'); + + // use wasm support if present + if (wasm) { + // guard against signed division overflow: the largest + // negative number / -1 would be 1 larger than the largest + // positive number, due to two's complement. + if ( + !this.unsigned && + this.high === -0x80000000 && + divisor.low === -1 && + divisor.high === -1 + ) { + // be consistent with non-wasm code path + return this; + } + const low = (this.unsigned ? wasm.div_u : wasm.div_s)( + this.low, + this.high, + divisor.low, + divisor.high + ); + return Long.fromBits(low, wasm.get_high(), this.unsigned); + } + + if (this.isZero()) return this.unsigned ? Long.UZERO : Long.ZERO; + let approx, rem, res; + if (!this.unsigned) { + // This section is only relevant for signed longs and is derived from the + // closure library as a whole. + if (this.eq(Long.MIN_VALUE)) { + if (divisor.eq(Long.ONE) || divisor.eq(Long.NEG_ONE)) return Long.MIN_VALUE; + // recall that -MIN_VALUE == MIN_VALUE + else if (divisor.eq(Long.MIN_VALUE)) return Long.ONE; + else { + // At this point, we have |other| >= 2, so |this/other| < |MIN_VALUE|. + const halfThis = this.shr(1); + approx = halfThis.div(divisor).shl(1); + if (approx.eq(Long.ZERO)) { + return divisor.isNegative() ? Long.ONE : Long.NEG_ONE; + } else { + rem = this.sub(divisor.mul(approx)); + res = approx.add(rem.div(divisor)); + return res; + } + } + } else if (divisor.eq(Long.MIN_VALUE)) return this.unsigned ? Long.UZERO : Long.ZERO; + if (this.isNegative()) { + if (divisor.isNegative()) return this.neg().div(divisor.neg()); + return this.neg().div(divisor).neg(); + } else if (divisor.isNegative()) return this.div(divisor.neg()).neg(); + res = Long.ZERO; + } else { + // The algorithm below has not been made for unsigned longs. It's therefore + // required to take special care of the MSB prior to running it. + if (!divisor.unsigned) divisor = divisor.toUnsigned(); + if (divisor.gt(this)) return Long.UZERO; + if (divisor.gt(this.shru(1))) + // 15 >>> 1 = 7 ; with divisor = 8 ; true + return Long.UONE; + res = Long.UZERO; + } + + // Repeat the following until the remainder is less than other: find a + // floating-point that approximates remainder / other *from below*, add this + // into the result, and subtract it from the remainder. It is critical that + // the approximate value is less than or equal to the real value so that the + // remainder never becomes negative. + // eslint-disable-next-line @typescript-eslint/no-this-alias + rem = this; + while (rem.gte(divisor)) { + // Approximate the result of division. This may be a little greater or + // smaller than the actual value. + approx = Math.max(1, Math.floor(rem.toNumber() / divisor.toNumber())); + + // We will tweak the approximate result by changing it in the 48-th digit or + // the smallest non-fractional digit, whichever is larger. + const log2 = Math.ceil(Math.log(approx) / Math.LN2); + const delta = log2 <= 48 ? 1 : Math.pow(2, log2 - 48); + // Decrease the approximation until it is smaller than the remainder. Note + // that if it is too large, the product overflows and is negative. + let approxRes = Long.fromNumber(approx); + let approxRem = approxRes.mul(divisor); + while (approxRem.isNegative() || approxRem.gt(rem)) { + approx -= delta; + approxRes = Long.fromNumber(approx, this.unsigned); + approxRem = approxRes.mul(divisor); + } + + // We know the answer can't be zero... and actually, zero would cause + // infinite recursion since we would make no progress. + if (approxRes.isZero()) approxRes = Long.ONE; + + res = res.add(approxRes); + rem = rem.sub(approxRem); + } + return res; + } + + /**This is an alias of {@link Long.divide} */ + div(divisor: string | number | Long | Timestamp): Long { + return this.divide(divisor); + } + + /** + * Tests if this Long's value equals the specified's. + * @param other - Other value + */ + equals(other: string | number | Long | Timestamp): boolean { + if (!Long.isLong(other)) other = Long.fromValue(other); + if (this.unsigned !== other.unsigned && this.high >>> 31 === 1 && other.high >>> 31 === 1) + return false; + return this.high === other.high && this.low === other.low; + } + + /** This is an alias of {@link Long.equals} */ + eq(other: string | number | Long | Timestamp): boolean { + return this.equals(other); + } + + /** Gets the high 32 bits as a signed integer. */ + getHighBits(): number { + return this.high; + } + + /** Gets the high 32 bits as an unsigned integer. */ + getHighBitsUnsigned(): number { + return this.high >>> 0; + } + + /** Gets the low 32 bits as a signed integer. */ + getLowBits(): number { + return this.low; + } + + /** Gets the low 32 bits as an unsigned integer. */ + getLowBitsUnsigned(): number { + return this.low >>> 0; + } + + /** Gets the number of bits needed to represent the absolute value of this Long. */ + getNumBitsAbs(): number { + if (this.isNegative()) { + // Unsigned Longs are never negative + return this.eq(Long.MIN_VALUE) ? 64 : this.neg().getNumBitsAbs(); + } + const val = this.high !== 0 ? this.high : this.low; + let bit: number; + for (bit = 31; bit > 0; bit--) if ((val & (1 << bit)) !== 0) break; + return this.high !== 0 ? bit + 33 : bit + 1; + } + + /** Tests if this Long's value is greater than the specified's. */ + greaterThan(other: string | number | Long | Timestamp): boolean { + return this.comp(other) > 0; + } + + /** This is an alias of {@link Long.greaterThan} */ + gt(other: string | number | Long | Timestamp): boolean { + return this.greaterThan(other); + } + + /** Tests if this Long's value is greater than or equal the specified's. */ + greaterThanOrEqual(other: string | number | Long | Timestamp): boolean { + return this.comp(other) >= 0; + } + + /** This is an alias of {@link Long.greaterThanOrEqual} */ + gte(other: string | number | Long | Timestamp): boolean { + return this.greaterThanOrEqual(other); + } + /** This is an alias of {@link Long.greaterThanOrEqual} */ + ge(other: string | number | Long | Timestamp): boolean { + return this.greaterThanOrEqual(other); + } + + /** Tests if this Long's value is even. */ + isEven(): boolean { + return (this.low & 1) === 0; + } + + /** Tests if this Long's value is negative. */ + isNegative(): boolean { + return !this.unsigned && this.high < 0; + } + + /** Tests if this Long's value is odd. */ + isOdd(): boolean { + return (this.low & 1) === 1; + } + + /** Tests if this Long's value is positive. */ + isPositive(): boolean { + return this.unsigned || this.high >= 0; + } + + /** Tests if this Long's value equals zero. */ + isZero(): boolean { + return this.high === 0 && this.low === 0; + } + + /** Tests if this Long's value is less than the specified's. */ + lessThan(other: string | number | Long | Timestamp): boolean { + return this.comp(other) < 0; + } + + /** This is an alias of {@link Long#lessThan}. */ + lt(other: string | number | Long | Timestamp): boolean { + return this.lessThan(other); + } + + /** Tests if this Long's value is less than or equal the specified's. */ + lessThanOrEqual(other: string | number | Long | Timestamp): boolean { + return this.comp(other) <= 0; + } + + /** This is an alias of {@link Long.lessThanOrEqual} */ + lte(other: string | number | Long | Timestamp): boolean { + return this.lessThanOrEqual(other); + } + + /** Returns this Long modulo the specified. */ + modulo(divisor: string | number | Long | Timestamp): Long { + if (!Long.isLong(divisor)) divisor = Long.fromValue(divisor); + + // use wasm support if present + if (wasm) { + const low = (this.unsigned ? wasm.rem_u : wasm.rem_s)( + this.low, + this.high, + divisor.low, + divisor.high + ); + return Long.fromBits(low, wasm.get_high(), this.unsigned); + } + + return this.sub(this.div(divisor).mul(divisor)); + } + + /** This is an alias of {@link Long.modulo} */ + mod(divisor: string | number | Long | Timestamp): Long { + return this.modulo(divisor); + } + /** This is an alias of {@link Long.modulo} */ + rem(divisor: string | number | Long | Timestamp): Long { + return this.modulo(divisor); + } + + /** + * Returns the product of this and the specified Long. + * @param multiplier - Multiplier + * @returns Product + */ + multiply(multiplier: string | number | Long | Timestamp): Long { + if (this.isZero()) return Long.ZERO; + if (!Long.isLong(multiplier)) multiplier = Long.fromValue(multiplier); + + // use wasm support if present + if (wasm) { + const low = wasm.mul(this.low, this.high, multiplier.low, multiplier.high); + return Long.fromBits(low, wasm.get_high(), this.unsigned); + } + + if (multiplier.isZero()) return Long.ZERO; + if (this.eq(Long.MIN_VALUE)) return multiplier.isOdd() ? Long.MIN_VALUE : Long.ZERO; + if (multiplier.eq(Long.MIN_VALUE)) return this.isOdd() ? Long.MIN_VALUE : Long.ZERO; + + if (this.isNegative()) { + if (multiplier.isNegative()) return this.neg().mul(multiplier.neg()); + else return this.neg().mul(multiplier).neg(); + } else if (multiplier.isNegative()) return this.mul(multiplier.neg()).neg(); + + // If both longs are small, use float multiplication + if (this.lt(Long.TWO_PWR_24) && multiplier.lt(Long.TWO_PWR_24)) + return Long.fromNumber(this.toNumber() * multiplier.toNumber(), this.unsigned); + + // Divide each long into 4 chunks of 16 bits, and then add up 4x4 products. + // We can skip products that would overflow. + + const a48 = this.high >>> 16; + const a32 = this.high & 0xffff; + const a16 = this.low >>> 16; + const a00 = this.low & 0xffff; + + const b48 = multiplier.high >>> 16; + const b32 = multiplier.high & 0xffff; + const b16 = multiplier.low >>> 16; + const b00 = multiplier.low & 0xffff; + + let c48 = 0, + c32 = 0, + c16 = 0, + c00 = 0; + c00 += a00 * b00; + c16 += c00 >>> 16; + c00 &= 0xffff; + c16 += a16 * b00; + c32 += c16 >>> 16; + c16 &= 0xffff; + c16 += a00 * b16; + c32 += c16 >>> 16; + c16 &= 0xffff; + c32 += a32 * b00; + c48 += c32 >>> 16; + c32 &= 0xffff; + c32 += a16 * b16; + c48 += c32 >>> 16; + c32 &= 0xffff; + c32 += a00 * b32; + c48 += c32 >>> 16; + c32 &= 0xffff; + c48 += a48 * b00 + a32 * b16 + a16 * b32 + a00 * b48; + c48 &= 0xffff; + return Long.fromBits((c16 << 16) | c00, (c48 << 16) | c32, this.unsigned); + } + + /** This is an alias of {@link Long.multiply} */ + mul(multiplier: string | number | Long | Timestamp): Long { + return this.multiply(multiplier); + } + + /** Returns the Negation of this Long's value. */ + negate(): Long { + if (!this.unsigned && this.eq(Long.MIN_VALUE)) return Long.MIN_VALUE; + return this.not().add(Long.ONE); + } + + /** This is an alias of {@link Long.negate} */ + neg(): Long { + return this.negate(); + } + + /** Returns the bitwise NOT of this Long. */ + not(): Long { + return Long.fromBits(~this.low, ~this.high, this.unsigned); + } + + /** Tests if this Long's value differs from the specified's. */ + notEquals(other: string | number | Long | Timestamp): boolean { + return !this.equals(other); + } + + /** This is an alias of {@link Long.notEquals} */ + neq(other: string | number | Long | Timestamp): boolean { + return this.notEquals(other); + } + /** This is an alias of {@link Long.notEquals} */ + ne(other: string | number | Long | Timestamp): boolean { + return this.notEquals(other); + } + + /** + * Returns the bitwise OR of this Long and the specified. + */ + or(other: number | string | Long): Long { + if (!Long.isLong(other)) other = Long.fromValue(other); + return Long.fromBits(this.low | other.low, this.high | other.high, this.unsigned); + } + + /** + * Returns this Long with bits shifted to the left by the given amount. + * @param numBits - Number of bits + * @returns Shifted Long + */ + shiftLeft(numBits: number | Long): Long { + if (Long.isLong(numBits)) numBits = numBits.toInt(); + if ((numBits &= 63) === 0) return this; + else if (numBits < 32) + return Long.fromBits( + this.low << numBits, + (this.high << numBits) | (this.low >>> (32 - numBits)), + this.unsigned + ); + else return Long.fromBits(0, this.low << (numBits - 32), this.unsigned); + } + + /** This is an alias of {@link Long.shiftLeft} */ + shl(numBits: number | Long): Long { + return this.shiftLeft(numBits); + } + + /** + * Returns this Long with bits arithmetically shifted to the right by the given amount. + * @param numBits - Number of bits + * @returns Shifted Long + */ + shiftRight(numBits: number | Long): Long { + if (Long.isLong(numBits)) numBits = numBits.toInt(); + if ((numBits &= 63) === 0) return this; + else if (numBits < 32) + return Long.fromBits( + (this.low >>> numBits) | (this.high << (32 - numBits)), + this.high >> numBits, + this.unsigned + ); + else return Long.fromBits(this.high >> (numBits - 32), this.high >= 0 ? 0 : -1, this.unsigned); + } + + /** This is an alias of {@link Long.shiftRight} */ + shr(numBits: number | Long): Long { + return this.shiftRight(numBits); + } + + /** + * Returns this Long with bits logically shifted to the right by the given amount. + * @param numBits - Number of bits + * @returns Shifted Long + */ + shiftRightUnsigned(numBits: Long | number): Long { + if (Long.isLong(numBits)) numBits = numBits.toInt(); + numBits &= 63; + if (numBits === 0) return this; + else { + const high = this.high; + if (numBits < 32) { + const low = this.low; + return Long.fromBits( + (low >>> numBits) | (high << (32 - numBits)), + high >>> numBits, + this.unsigned + ); + } else if (numBits === 32) return Long.fromBits(high, 0, this.unsigned); + else return Long.fromBits(high >>> (numBits - 32), 0, this.unsigned); + } + } + + /** This is an alias of {@link Long.shiftRightUnsigned} */ + shr_u(numBits: number | Long): Long { + return this.shiftRightUnsigned(numBits); + } + /** This is an alias of {@link Long.shiftRightUnsigned} */ + shru(numBits: number | Long): Long { + return this.shiftRightUnsigned(numBits); + } + + /** + * Returns the difference of this and the specified Long. + * @param subtrahend - Subtrahend + * @returns Difference + */ + subtract(subtrahend: string | number | Long | Timestamp): Long { + if (!Long.isLong(subtrahend)) subtrahend = Long.fromValue(subtrahend); + return this.add(subtrahend.neg()); + } + + /** This is an alias of {@link Long.subtract} */ + sub(subtrahend: string | number | Long | Timestamp): Long { + return this.subtract(subtrahend); + } + + /** Converts the Long to a 32 bit integer, assuming it is a 32 bit integer. */ + toInt(): number { + return this.unsigned ? this.low >>> 0 : this.low; + } + + /** Converts the Long to a the nearest floating-point representation of this value (double, 53 bit mantissa). */ + toNumber(): number { + if (this.unsigned) return (this.high >>> 0) * TWO_PWR_32_DBL + (this.low >>> 0); + return this.high * TWO_PWR_32_DBL + (this.low >>> 0); + } + + /** Converts the Long to a BigInt (arbitrary precision). */ + toBigInt(): bigint { + return BigInt(this.toString()); + } + + /** + * Converts this Long to its byte representation. + * @param le - Whether little or big endian, defaults to big endian + * @returns Byte representation + */ + toBytes(le?: boolean): number[] { + return le ? this.toBytesLE() : this.toBytesBE(); + } + + /** + * Converts this Long to its little endian byte representation. + * @returns Little endian byte representation + */ + toBytesLE(): number[] { + const hi = this.high, + lo = this.low; + return [ + lo & 0xff, + (lo >>> 8) & 0xff, + (lo >>> 16) & 0xff, + lo >>> 24, + hi & 0xff, + (hi >>> 8) & 0xff, + (hi >>> 16) & 0xff, + hi >>> 24 + ]; + } + + /** + * Converts this Long to its big endian byte representation. + * @returns Big endian byte representation + */ + toBytesBE(): number[] { + const hi = this.high, + lo = this.low; + return [ + hi >>> 24, + (hi >>> 16) & 0xff, + (hi >>> 8) & 0xff, + hi & 0xff, + lo >>> 24, + (lo >>> 16) & 0xff, + (lo >>> 8) & 0xff, + lo & 0xff + ]; + } + + /** + * Converts this Long to signed. + */ + toSigned(): Long { + if (!this.unsigned) return this; + return Long.fromBits(this.low, this.high, false); + } + + /** + * Converts the Long to a string written in the specified radix. + * @param radix - Radix (2-36), defaults to 10 + * @throws RangeError If `radix` is out of range + */ + toString(radix?: number): string { + radix = radix || 10; + if (radix < 2 || 36 < radix) throw RangeError('radix'); + if (this.isZero()) return '0'; + if (this.isNegative()) { + // Unsigned Longs are never negative + if (this.eq(Long.MIN_VALUE)) { + // We need to change the Long value before it can be negated, so we remove + // the bottom-most digit in this base and then recurse to do the rest. + const radixLong = Long.fromNumber(radix), + div = this.div(radixLong), + rem1 = div.mul(radixLong).sub(this); + return div.toString(radix) + rem1.toInt().toString(radix); + } else return '-' + this.neg().toString(radix); + } + + // Do several (6) digits each time through the loop, so as to + // minimize the calls to the very expensive emulated div. + const radixToPower = Long.fromNumber(Math.pow(radix, 6), this.unsigned); + // eslint-disable-next-line @typescript-eslint/no-this-alias + let rem: Long = this; + let result = ''; + // eslint-disable-next-line no-constant-condition + while (true) { + const remDiv = rem.div(radixToPower); + const intval = rem.sub(remDiv.mul(radixToPower)).toInt() >>> 0; + let digits = intval.toString(radix); + rem = remDiv; + if (rem.isZero()) { + return digits + result; + } else { + while (digits.length < 6) digits = '0' + digits; + result = '' + digits + result; + } + } + } + + /** Converts this Long to unsigned. */ + toUnsigned(): Long { + if (this.unsigned) return this; + return Long.fromBits(this.low, this.high, true); + } + + /** Returns the bitwise XOR of this Long and the given one. */ + xor(other: Long | number | string): Long { + if (!Long.isLong(other)) other = Long.fromValue(other); + return Long.fromBits(this.low ^ other.low, this.high ^ other.high, this.unsigned); + } + + /** This is an alias of {@link Long.isZero} */ + eqz(): boolean { + return this.isZero(); + } + + /** This is an alias of {@link Long.lessThanOrEqual} */ + le(other: string | number | Long | Timestamp): boolean { + return this.lessThanOrEqual(other); + } + + /* + **************************************************************** + * BSON SPECIFIC ADDITIONS * + **************************************************************** + */ + toExtendedJSON(options?: EJSONOptions): number | LongExtended { + if (options && options.relaxed) return this.toNumber(); + return { $numberLong: this.toString() }; + } + static fromExtendedJSON(doc: { $numberLong: string }, options?: EJSONOptions): number | Long { + const result = Long.fromString(doc.$numberLong); + return options && options.relaxed ? result.toNumber() : result; + } + + /** @internal */ + [Symbol.for('nodejs.util.inspect.custom')](): string { + return this.inspect(); + } + + inspect(): string { + return `new Long("${this.toString()}"${this.unsigned ? ', true' : ''})`; + } +} + +Object.defineProperty(Long.prototype, '__isLong__', { value: true }); +Object.defineProperty(Long.prototype, '_bsontype', { value: 'Long' }); diff --git a/ts-ticket-office-service/node_modules/bson/src/map.ts b/ts-ticket-office-service/node_modules/bson/src/map.ts new file mode 100644 index 000000000..ba0032968 --- /dev/null +++ b/ts-ticket-office-service/node_modules/bson/src/map.ts @@ -0,0 +1,119 @@ +/* eslint-disable @typescript-eslint/no-explicit-any */ +// We have an ES6 Map available, return the native instance + +import { getGlobal } from './utils/global'; + +/** @public */ +let bsonMap: MapConstructor; + +const bsonGlobal = getGlobal<{ Map?: MapConstructor }>(); +if (bsonGlobal.Map) { + bsonMap = bsonGlobal.Map; +} else { + // We will return a polyfill + bsonMap = class Map { + private _keys: string[]; + private _values: Record; + constructor(array: [string, any][] = []) { + this._keys = []; + this._values = {}; + + for (let i = 0; i < array.length; i++) { + if (array[i] == null) continue; // skip null and undefined + const entry = array[i]; + const key = entry[0]; + const value = entry[1]; + // Add the key to the list of keys in order + this._keys.push(key); + // Add the key and value to the values dictionary with a point + // to the location in the ordered keys list + this._values[key] = { v: value, i: this._keys.length - 1 }; + } + } + clear() { + this._keys = []; + this._values = {}; + } + delete(key: string) { + const value = this._values[key]; + if (value == null) return false; + // Delete entry + delete this._values[key]; + // Remove the key from the ordered keys list + this._keys.splice(value.i, 1); + return true; + } + entries() { + let index = 0; + + return { + next: () => { + const key = this._keys[index++]; + return { + value: key !== undefined ? [key, this._values[key].v] : undefined, + done: key !== undefined ? false : true + }; + } + }; + } + forEach(callback: (this: this, value: any, key: string, self: this) => void, self?: this) { + self = self || this; + + for (let i = 0; i < this._keys.length; i++) { + const key = this._keys[i]; + // Call the forEach callback + callback.call(self, this._values[key].v, key, self); + } + } + get(key: string) { + return this._values[key] ? this._values[key].v : undefined; + } + has(key: string) { + return this._values[key] != null; + } + keys() { + let index = 0; + + return { + next: () => { + const key = this._keys[index++]; + return { + value: key !== undefined ? key : undefined, + done: key !== undefined ? false : true + }; + } + }; + } + set(key: string, value: any) { + if (this._values[key]) { + this._values[key].v = value; + return this; + } + + // Add the key to the list of keys in order + this._keys.push(key); + // Add the key and value to the values dictionary with a point + // to the location in the ordered keys list + this._values[key] = { v: value, i: this._keys.length - 1 }; + return this; + } + values() { + let index = 0; + + return { + next: () => { + const key = this._keys[index++]; + return { + value: key !== undefined ? this._values[key].v : undefined, + done: key !== undefined ? false : true + }; + } + }; + } + get size() { + return this._keys.length; + } + } as unknown as MapConstructor; +} + +export { bsonMap as Map }; diff --git a/ts-ticket-office-service/node_modules/bson/src/max_key.ts b/ts-ticket-office-service/node_modules/bson/src/max_key.ts new file mode 100644 index 000000000..0ff3d3633 --- /dev/null +++ b/ts-ticket-office-service/node_modules/bson/src/max_key.ts @@ -0,0 +1,38 @@ +/** @public */ +export interface MaxKeyExtended { + $maxKey: 1; +} + +/** + * A class representation of the BSON MaxKey type. + * @public + * @category BSONType + */ +export class MaxKey { + _bsontype!: 'MaxKey'; + + constructor() { + if (!(this instanceof MaxKey)) return new MaxKey(); + } + + /** @internal */ + toExtendedJSON(): MaxKeyExtended { + return { $maxKey: 1 }; + } + + /** @internal */ + static fromExtendedJSON(): MaxKey { + return new MaxKey(); + } + + /** @internal */ + [Symbol.for('nodejs.util.inspect.custom')](): string { + return this.inspect(); + } + + inspect(): string { + return 'new MaxKey()'; + } +} + +Object.defineProperty(MaxKey.prototype, '_bsontype', { value: 'MaxKey' }); diff --git a/ts-ticket-office-service/node_modules/bson/src/min_key.ts b/ts-ticket-office-service/node_modules/bson/src/min_key.ts new file mode 100644 index 000000000..f872b1eb1 --- /dev/null +++ b/ts-ticket-office-service/node_modules/bson/src/min_key.ts @@ -0,0 +1,38 @@ +/** @public */ +export interface MinKeyExtended { + $minKey: 1; +} + +/** + * A class representation of the BSON MinKey type. + * @public + * @category BSONType + */ +export class MinKey { + _bsontype!: 'MinKey'; + + constructor() { + if (!(this instanceof MinKey)) return new MinKey(); + } + + /** @internal */ + toExtendedJSON(): MinKeyExtended { + return { $minKey: 1 }; + } + + /** @internal */ + static fromExtendedJSON(): MinKey { + return new MinKey(); + } + + /** @internal */ + [Symbol.for('nodejs.util.inspect.custom')](): string { + return this.inspect(); + } + + inspect(): string { + return 'new MinKey()'; + } +} + +Object.defineProperty(MinKey.prototype, '_bsontype', { value: 'MinKey' }); diff --git a/ts-ticket-office-service/node_modules/bson/src/objectid.ts b/ts-ticket-office-service/node_modules/bson/src/objectid.ts new file mode 100644 index 000000000..7bf012d7b --- /dev/null +++ b/ts-ticket-office-service/node_modules/bson/src/objectid.ts @@ -0,0 +1,354 @@ +import { Buffer } from 'buffer'; +import { ensureBuffer } from './ensure_buffer'; +import { BSONTypeError } from './error'; +import { deprecate, isUint8Array, randomBytes } from './parser/utils'; + +// Regular expression that checks for hex value +const checkForHexRegExp = new RegExp('^[0-9a-fA-F]{24}$'); + +// Unique sequence for the current process (initialized on first use) +let PROCESS_UNIQUE: Uint8Array | null = null; + +/** @public */ +export interface ObjectIdLike { + id: string | Buffer; + __id?: string; + toHexString(): string; +} + +/** @public */ +export interface ObjectIdExtended { + $oid: string; +} + +const kId = Symbol('id'); + +/** + * A class representation of the BSON ObjectId type. + * @public + * @category BSONType + */ +export class ObjectId { + _bsontype!: 'ObjectID'; + + /** @internal */ + static index = Math.floor(Math.random() * 0xffffff); + + static cacheHexString: boolean; + + /** ObjectId Bytes @internal */ + private [kId]!: Buffer; + /** ObjectId hexString cache @internal */ + private __id?: string; + + /** + * Create an ObjectId type + * + * @param inputId - Can be a 24 character hex string, 12 byte binary Buffer, or a number. + */ + constructor(inputId?: string | number | ObjectId | ObjectIdLike | Buffer | Uint8Array) { + if (!(this instanceof ObjectId)) return new ObjectId(inputId); + + // workingId is set based on type of input and whether valid id exists for the input + let workingId; + if (typeof inputId === 'object' && inputId && 'id' in inputId) { + if (typeof inputId.id !== 'string' && !ArrayBuffer.isView(inputId.id)) { + throw new BSONTypeError( + 'Argument passed in must have an id that is of type string or Buffer' + ); + } + if ('toHexString' in inputId && typeof inputId.toHexString === 'function') { + workingId = Buffer.from(inputId.toHexString(), 'hex'); + } else { + workingId = inputId.id; + } + } else { + workingId = inputId; + } + + // the following cases use workingId to construct an ObjectId + if (workingId == null || typeof workingId === 'number') { + // The most common use case (blank id, new objectId instance) + // Generate a new id + this[kId] = ObjectId.generate(typeof workingId === 'number' ? workingId : undefined); + } else if (ArrayBuffer.isView(workingId) && workingId.byteLength === 12) { + // If intstanceof matches we can escape calling ensure buffer in Node.js environments + this[kId] = workingId instanceof Buffer ? workingId : ensureBuffer(workingId); + } else if (typeof workingId === 'string') { + if (workingId.length === 12) { + const bytes = Buffer.from(workingId); + if (bytes.byteLength === 12) { + this[kId] = bytes; + } else { + throw new BSONTypeError('Argument passed in must be a string of 12 bytes'); + } + } else if (workingId.length === 24 && checkForHexRegExp.test(workingId)) { + this[kId] = Buffer.from(workingId, 'hex'); + } else { + throw new BSONTypeError( + 'Argument passed in must be a string of 12 bytes or a string of 24 hex characters or an integer' + ); + } + } else { + throw new BSONTypeError('Argument passed in does not match the accepted types'); + } + // If we are caching the hex string + if (ObjectId.cacheHexString) { + this.__id = this.id.toString('hex'); + } + } + + /** + * The ObjectId bytes + * @readonly + */ + get id(): Buffer { + return this[kId]; + } + + set id(value: Buffer) { + this[kId] = value; + if (ObjectId.cacheHexString) { + this.__id = value.toString('hex'); + } + } + + /** + * The generation time of this ObjectId instance + * @deprecated Please use getTimestamp / createFromTime which returns an int32 epoch + */ + get generationTime(): number { + return this.id.readInt32BE(0); + } + + set generationTime(value: number) { + // Encode time into first 4 bytes + this.id.writeUInt32BE(value, 0); + } + + /** Returns the ObjectId id as a 24 character hex string representation */ + toHexString(): string { + if (ObjectId.cacheHexString && this.__id) { + return this.__id; + } + + const hexString = this.id.toString('hex'); + + if (ObjectId.cacheHexString && !this.__id) { + this.__id = hexString; + } + + return hexString; + } + + /** + * Update the ObjectId index + * @privateRemarks + * Used in generating new ObjectId's on the driver + * @internal + */ + static getInc(): number { + return (ObjectId.index = (ObjectId.index + 1) % 0xffffff); + } + + /** + * Generate a 12 byte id buffer used in ObjectId's + * + * @param time - pass in a second based timestamp. + */ + static generate(time?: number): Buffer { + if ('number' !== typeof time) { + time = Math.floor(Date.now() / 1000); + } + + const inc = ObjectId.getInc(); + const buffer = Buffer.alloc(12); + + // 4-byte timestamp + buffer.writeUInt32BE(time, 0); + + // set PROCESS_UNIQUE if yet not initialized + if (PROCESS_UNIQUE === null) { + PROCESS_UNIQUE = randomBytes(5); + } + + // 5-byte process unique + buffer[4] = PROCESS_UNIQUE[0]; + buffer[5] = PROCESS_UNIQUE[1]; + buffer[6] = PROCESS_UNIQUE[2]; + buffer[7] = PROCESS_UNIQUE[3]; + buffer[8] = PROCESS_UNIQUE[4]; + + // 3-byte counter + buffer[11] = inc & 0xff; + buffer[10] = (inc >> 8) & 0xff; + buffer[9] = (inc >> 16) & 0xff; + + return buffer; + } + + /** + * Converts the id into a 24 character hex string for printing + * + * @param format - The Buffer toString format parameter. + */ + toString(format?: string): string { + // Is the id a buffer then use the buffer toString method to return the format + if (format) return this.id.toString(format); + return this.toHexString(); + } + + /** Converts to its JSON the 24 character hex string representation. */ + toJSON(): string { + return this.toHexString(); + } + + /** + * Compares the equality of this ObjectId with `otherID`. + * + * @param otherId - ObjectId instance to compare against. + */ + equals(otherId: string | ObjectId | ObjectIdLike): boolean { + if (otherId === undefined || otherId === null) { + return false; + } + + if (otherId instanceof ObjectId) { + return this[kId][11] === otherId[kId][11] && this[kId].equals(otherId[kId]); + } + + if ( + typeof otherId === 'string' && + ObjectId.isValid(otherId) && + otherId.length === 12 && + isUint8Array(this.id) + ) { + return otherId === Buffer.prototype.toString.call(this.id, 'latin1'); + } + + if (typeof otherId === 'string' && ObjectId.isValid(otherId) && otherId.length === 24) { + return otherId.toLowerCase() === this.toHexString(); + } + + if (typeof otherId === 'string' && ObjectId.isValid(otherId) && otherId.length === 12) { + return Buffer.from(otherId).equals(this.id); + } + + if ( + typeof otherId === 'object' && + 'toHexString' in otherId && + typeof otherId.toHexString === 'function' + ) { + const otherIdString = otherId.toHexString(); + const thisIdString = this.toHexString().toLowerCase(); + return typeof otherIdString === 'string' && otherIdString.toLowerCase() === thisIdString; + } + + return false; + } + + /** Returns the generation date (accurate up to the second) that this ID was generated. */ + getTimestamp(): Date { + const timestamp = new Date(); + const time = this.id.readUInt32BE(0); + timestamp.setTime(Math.floor(time) * 1000); + return timestamp; + } + + /** @internal */ + static createPk(): ObjectId { + return new ObjectId(); + } + + /** + * Creates an ObjectId from a second based number, with the rest of the ObjectId zeroed out. Used for comparisons or sorting the ObjectId. + * + * @param time - an integer number representing a number of seconds. + */ + static createFromTime(time: number): ObjectId { + const buffer = Buffer.from([0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]); + // Encode time into first 4 bytes + buffer.writeUInt32BE(time, 0); + // Return the new objectId + return new ObjectId(buffer); + } + + /** + * Creates an ObjectId from a hex string representation of an ObjectId. + * + * @param hexString - create a ObjectId from a passed in 24 character hexstring. + */ + static createFromHexString(hexString: string): ObjectId { + // Throw an error if it's not a valid setup + if (typeof hexString === 'undefined' || (hexString != null && hexString.length !== 24)) { + throw new BSONTypeError( + 'Argument passed in must be a single String of 12 bytes or a string of 24 hex characters' + ); + } + + return new ObjectId(Buffer.from(hexString, 'hex')); + } + + /** + * Checks if a value is a valid bson ObjectId + * + * @param id - ObjectId instance to validate. + */ + static isValid(id: string | number | ObjectId | ObjectIdLike | Buffer | Uint8Array): boolean { + if (id == null) return false; + + try { + new ObjectId(id); + return true; + } catch { + return false; + } + } + + /** @internal */ + toExtendedJSON(): ObjectIdExtended { + if (this.toHexString) return { $oid: this.toHexString() }; + return { $oid: this.toString('hex') }; + } + + /** @internal */ + static fromExtendedJSON(doc: ObjectIdExtended): ObjectId { + return new ObjectId(doc.$oid); + } + + /** + * Converts to a string representation of this Id. + * + * @returns return the 24 character hex string representation. + * @internal + */ + [Symbol.for('nodejs.util.inspect.custom')](): string { + return this.inspect(); + } + + inspect(): string { + return `new ObjectId("${this.toHexString()}")`; + } +} + +// Deprecated methods +Object.defineProperty(ObjectId.prototype, 'generate', { + value: deprecate( + (time: number) => ObjectId.generate(time), + 'Please use the static `ObjectId.generate(time)` instead' + ) +}); + +Object.defineProperty(ObjectId.prototype, 'getInc', { + value: deprecate(() => ObjectId.getInc(), 'Please use the static `ObjectId.getInc()` instead') +}); + +Object.defineProperty(ObjectId.prototype, 'get_inc', { + value: deprecate(() => ObjectId.getInc(), 'Please use the static `ObjectId.getInc()` instead') +}); + +Object.defineProperty(ObjectId, 'get_inc', { + value: deprecate(() => ObjectId.getInc(), 'Please use the static `ObjectId.getInc()` instead') +}); + +Object.defineProperty(ObjectId.prototype, '_bsontype', { value: 'ObjectID' }); diff --git a/ts-ticket-office-service/node_modules/bson/src/parser/calculate_size.ts b/ts-ticket-office-service/node_modules/bson/src/parser/calculate_size.ts new file mode 100644 index 000000000..cc7f431e6 --- /dev/null +++ b/ts-ticket-office-service/node_modules/bson/src/parser/calculate_size.ts @@ -0,0 +1,228 @@ +import { Buffer } from 'buffer'; +import { Binary } from '../binary'; +import type { Document } from '../bson'; +import * as constants from '../constants'; +import { isAnyArrayBuffer, isDate, isRegExp, normalizedFunctionString } from './utils'; + +export function calculateObjectSize( + object: Document, + serializeFunctions?: boolean, + ignoreUndefined?: boolean +): number { + let totalLength = 4 + 1; + + if (Array.isArray(object)) { + for (let i = 0; i < object.length; i++) { + totalLength += calculateElement( + i.toString(), + object[i], + serializeFunctions, + true, + ignoreUndefined + ); + } + } else { + // If we have toBSON defined, override the current object + + if (typeof object?.toBSON === 'function') { + object = object.toBSON(); + } + + // Calculate size + for (const key in object) { + totalLength += calculateElement(key, object[key], serializeFunctions, false, ignoreUndefined); + } + } + + return totalLength; +} + +/** @internal */ +function calculateElement( + name: string, + // eslint-disable-next-line @typescript-eslint/no-explicit-any + value: any, + serializeFunctions = false, + isArray = false, + ignoreUndefined = false +) { + // If we have toBSON defined, override the current object + if (typeof value?.toBSON === 'function') { + value = value.toBSON(); + } + + switch (typeof value) { + case 'string': + return 1 + Buffer.byteLength(name, 'utf8') + 1 + 4 + Buffer.byteLength(value, 'utf8') + 1; + case 'number': + if ( + Math.floor(value) === value && + value >= constants.JS_INT_MIN && + value <= constants.JS_INT_MAX + ) { + if (value >= constants.BSON_INT32_MIN && value <= constants.BSON_INT32_MAX) { + // 32 bit + return (name != null ? Buffer.byteLength(name, 'utf8') + 1 : 0) + (4 + 1); + } else { + return (name != null ? Buffer.byteLength(name, 'utf8') + 1 : 0) + (8 + 1); + } + } else { + // 64 bit + return (name != null ? Buffer.byteLength(name, 'utf8') + 1 : 0) + (8 + 1); + } + case 'undefined': + if (isArray || !ignoreUndefined) + return (name != null ? Buffer.byteLength(name, 'utf8') + 1 : 0) + 1; + return 0; + case 'boolean': + return (name != null ? Buffer.byteLength(name, 'utf8') + 1 : 0) + (1 + 1); + case 'object': + if (value == null || value['_bsontype'] === 'MinKey' || value['_bsontype'] === 'MaxKey') { + return (name != null ? Buffer.byteLength(name, 'utf8') + 1 : 0) + 1; + } else if (value['_bsontype'] === 'ObjectId' || value['_bsontype'] === 'ObjectID') { + return (name != null ? Buffer.byteLength(name, 'utf8') + 1 : 0) + (12 + 1); + } else if (value instanceof Date || isDate(value)) { + return (name != null ? Buffer.byteLength(name, 'utf8') + 1 : 0) + (8 + 1); + } else if ( + ArrayBuffer.isView(value) || + value instanceof ArrayBuffer || + isAnyArrayBuffer(value) + ) { + return ( + (name != null ? Buffer.byteLength(name, 'utf8') + 1 : 0) + (1 + 4 + 1) + value.byteLength + ); + } else if ( + value['_bsontype'] === 'Long' || + value['_bsontype'] === 'Double' || + value['_bsontype'] === 'Timestamp' + ) { + return (name != null ? Buffer.byteLength(name, 'utf8') + 1 : 0) + (8 + 1); + } else if (value['_bsontype'] === 'Decimal128') { + return (name != null ? Buffer.byteLength(name, 'utf8') + 1 : 0) + (16 + 1); + } else if (value['_bsontype'] === 'Code') { + // Calculate size depending on the availability of a scope + if (value.scope != null && Object.keys(value.scope).length > 0) { + return ( + (name != null ? Buffer.byteLength(name, 'utf8') + 1 : 0) + + 1 + + 4 + + 4 + + Buffer.byteLength(value.code.toString(), 'utf8') + + 1 + + calculateObjectSize(value.scope, serializeFunctions, ignoreUndefined) + ); + } else { + return ( + (name != null ? Buffer.byteLength(name, 'utf8') + 1 : 0) + + 1 + + 4 + + Buffer.byteLength(value.code.toString(), 'utf8') + + 1 + ); + } + } else if (value['_bsontype'] === 'Binary') { + const binary: Binary = value; + // Check what kind of subtype we have + if (binary.sub_type === Binary.SUBTYPE_BYTE_ARRAY) { + return ( + (name != null ? Buffer.byteLength(name, 'utf8') + 1 : 0) + + (binary.position + 1 + 4 + 1 + 4) + ); + } else { + return ( + (name != null ? Buffer.byteLength(name, 'utf8') + 1 : 0) + (binary.position + 1 + 4 + 1) + ); + } + } else if (value['_bsontype'] === 'Symbol') { + return ( + (name != null ? Buffer.byteLength(name, 'utf8') + 1 : 0) + + Buffer.byteLength(value.value, 'utf8') + + 4 + + 1 + + 1 + ); + } else if (value['_bsontype'] === 'DBRef') { + // Set up correct object for serialization + const ordered_values = Object.assign( + { + $ref: value.collection, + $id: value.oid + }, + value.fields + ); + + // Add db reference if it exists + if (value.db != null) { + ordered_values['$db'] = value.db; + } + + return ( + (name != null ? Buffer.byteLength(name, 'utf8') + 1 : 0) + + 1 + + calculateObjectSize(ordered_values, serializeFunctions, ignoreUndefined) + ); + } else if (value instanceof RegExp || isRegExp(value)) { + return ( + (name != null ? Buffer.byteLength(name, 'utf8') + 1 : 0) + + 1 + + Buffer.byteLength(value.source, 'utf8') + + 1 + + (value.global ? 1 : 0) + + (value.ignoreCase ? 1 : 0) + + (value.multiline ? 1 : 0) + + 1 + ); + } else if (value['_bsontype'] === 'BSONRegExp') { + return ( + (name != null ? Buffer.byteLength(name, 'utf8') + 1 : 0) + + 1 + + Buffer.byteLength(value.pattern, 'utf8') + + 1 + + Buffer.byteLength(value.options, 'utf8') + + 1 + ); + } else { + return ( + (name != null ? Buffer.byteLength(name, 'utf8') + 1 : 0) + + calculateObjectSize(value, serializeFunctions, ignoreUndefined) + + 1 + ); + } + case 'function': + // WTF for 0.4.X where typeof /someregexp/ === 'function' + if (value instanceof RegExp || isRegExp(value) || String.call(value) === '[object RegExp]') { + return ( + (name != null ? Buffer.byteLength(name, 'utf8') + 1 : 0) + + 1 + + Buffer.byteLength(value.source, 'utf8') + + 1 + + (value.global ? 1 : 0) + + (value.ignoreCase ? 1 : 0) + + (value.multiline ? 1 : 0) + + 1 + ); + } else { + if (serializeFunctions && value.scope != null && Object.keys(value.scope).length > 0) { + return ( + (name != null ? Buffer.byteLength(name, 'utf8') + 1 : 0) + + 1 + + 4 + + 4 + + Buffer.byteLength(normalizedFunctionString(value), 'utf8') + + 1 + + calculateObjectSize(value.scope, serializeFunctions, ignoreUndefined) + ); + } else if (serializeFunctions) { + return ( + (name != null ? Buffer.byteLength(name, 'utf8') + 1 : 0) + + 1 + + 4 + + Buffer.byteLength(normalizedFunctionString(value), 'utf8') + + 1 + ); + } + } + } + + return 0; +} diff --git a/ts-ticket-office-service/node_modules/bson/src/parser/deserializer.ts b/ts-ticket-office-service/node_modules/bson/src/parser/deserializer.ts new file mode 100644 index 000000000..bd306c95c --- /dev/null +++ b/ts-ticket-office-service/node_modules/bson/src/parser/deserializer.ts @@ -0,0 +1,777 @@ +import { Buffer } from 'buffer'; +import { Binary } from '../binary'; +import type { Document } from '../bson'; +import { Code } from '../code'; +import * as constants from '../constants'; +import { DBRef, DBRefLike, isDBRefLike } from '../db_ref'; +import { Decimal128 } from '../decimal128'; +import { Double } from '../double'; +import { BSONError } from '../error'; +import { Int32 } from '../int_32'; +import { Long } from '../long'; +import { MaxKey } from '../max_key'; +import { MinKey } from '../min_key'; +import { ObjectId } from '../objectid'; +import { BSONRegExp } from '../regexp'; +import { BSONSymbol } from '../symbol'; +import { Timestamp } from '../timestamp'; +import { validateUtf8 } from '../validate_utf8'; + +/** @public */ +export interface DeserializeOptions { + /** evaluate functions in the BSON document scoped to the object deserialized. */ + evalFunctions?: boolean; + /** cache evaluated functions for reuse. */ + cacheFunctions?: boolean; + /** + * use a crc32 code for caching, otherwise use the string of the function. + * @deprecated this option to use the crc32 function never worked as intended + * due to the fact that the crc32 function itself was never implemented. + * */ + cacheFunctionsCrc32?: boolean; + /** when deserializing a Long will fit it into a Number if it's smaller than 53 bits */ + promoteLongs?: boolean; + /** when deserializing a Binary will return it as a node.js Buffer instance. */ + promoteBuffers?: boolean; + /** when deserializing will promote BSON values to their Node.js closest equivalent types. */ + promoteValues?: boolean; + /** allow to specify if there what fields we wish to return as unserialized raw buffer. */ + fieldsAsRaw?: Document; + /** return BSON regular expressions as BSONRegExp instances. */ + bsonRegExp?: boolean; + /** allows the buffer to be larger than the parsed BSON object */ + allowObjectSmallerThanBufferSize?: boolean; + /** Offset into buffer to begin reading document from */ + index?: number; + + raw?: boolean; + /** Allows for opt-out utf-8 validation for all keys or + * specified keys. Must be all true or all false. + * + * @example + * ```js + * // disables validation on all keys + * validation: { utf8: false } + * + * // enables validation only on specified keys a, b, and c + * validation: { utf8: { a: true, b: true, c: true } } + * + * // disables validation only on specified keys a, b + * validation: { utf8: { a: false, b: false } } + * ``` + */ + validation?: { utf8: boolean | Record | Record }; +} + +// Internal long versions +const JS_INT_MAX_LONG = Long.fromNumber(constants.JS_INT_MAX); +const JS_INT_MIN_LONG = Long.fromNumber(constants.JS_INT_MIN); + +const functionCache: { [hash: string]: Function } = {}; + +export function deserialize( + buffer: Buffer, + options: DeserializeOptions, + isArray?: boolean +): Document { + options = options == null ? {} : options; + const index = options && options.index ? options.index : 0; + // Read the document size + const size = + buffer[index] | + (buffer[index + 1] << 8) | + (buffer[index + 2] << 16) | + (buffer[index + 3] << 24); + + if (size < 5) { + throw new BSONError(`bson size must be >= 5, is ${size}`); + } + + if (options.allowObjectSmallerThanBufferSize && buffer.length < size) { + throw new BSONError(`buffer length ${buffer.length} must be >= bson size ${size}`); + } + + if (!options.allowObjectSmallerThanBufferSize && buffer.length !== size) { + throw new BSONError(`buffer length ${buffer.length} must === bson size ${size}`); + } + + if (size + index > buffer.byteLength) { + throw new BSONError( + `(bson size ${size} + options.index ${index} must be <= buffer length ${buffer.byteLength})` + ); + } + + // Illegal end value + if (buffer[index + size - 1] !== 0) { + throw new BSONError( + "One object, sized correctly, with a spot for an EOO, but the EOO isn't 0x00" + ); + } + + // Start deserializtion + return deserializeObject(buffer, index, options, isArray); +} + +const allowedDBRefKeys = /^\$ref$|^\$id$|^\$db$/; + +function deserializeObject( + buffer: Buffer, + index: number, + options: DeserializeOptions, + isArray = false +) { + const evalFunctions = options['evalFunctions'] == null ? false : options['evalFunctions']; + const cacheFunctions = options['cacheFunctions'] == null ? false : options['cacheFunctions']; + + const fieldsAsRaw = options['fieldsAsRaw'] == null ? null : options['fieldsAsRaw']; + + // Return raw bson buffer instead of parsing it + const raw = options['raw'] == null ? false : options['raw']; + + // Return BSONRegExp objects instead of native regular expressions + const bsonRegExp = typeof options['bsonRegExp'] === 'boolean' ? options['bsonRegExp'] : false; + + // Controls the promotion of values vs wrapper classes + const promoteBuffers = options['promoteBuffers'] == null ? false : options['promoteBuffers']; + const promoteLongs = options['promoteLongs'] == null ? true : options['promoteLongs']; + const promoteValues = options['promoteValues'] == null ? true : options['promoteValues']; + + // Ensures default validation option if none given + const validation = options.validation == null ? { utf8: true } : options.validation; + + // Shows if global utf-8 validation is enabled or disabled + let globalUTFValidation = true; + // Reflects utf-8 validation setting regardless of global or specific key validation + let validationSetting: boolean; + // Set of keys either to enable or disable validation on + const utf8KeysSet = new Set(); + + // Check for boolean uniformity and empty validation option + const utf8ValidatedKeys = validation.utf8; + if (typeof utf8ValidatedKeys === 'boolean') { + validationSetting = utf8ValidatedKeys; + } else { + globalUTFValidation = false; + const utf8ValidationValues = Object.keys(utf8ValidatedKeys).map(function (key) { + return utf8ValidatedKeys[key]; + }); + if (utf8ValidationValues.length === 0) { + throw new BSONError('UTF-8 validation setting cannot be empty'); + } + if (typeof utf8ValidationValues[0] !== 'boolean') { + throw new BSONError('Invalid UTF-8 validation option, must specify boolean values'); + } + validationSetting = utf8ValidationValues[0]; + // Ensures boolean uniformity in utf-8 validation (all true or all false) + if (!utf8ValidationValues.every(item => item === validationSetting)) { + throw new BSONError('Invalid UTF-8 validation option - keys must be all true or all false'); + } + } + + // Add keys to set that will either be validated or not based on validationSetting + if (!globalUTFValidation) { + for (const key of Object.keys(utf8ValidatedKeys)) { + utf8KeysSet.add(key); + } + } + + // Set the start index + const startIndex = index; + + // Validate that we have at least 4 bytes of buffer + if (buffer.length < 5) throw new BSONError('corrupt bson message < 5 bytes long'); + + // Read the document size + const size = + buffer[index++] | (buffer[index++] << 8) | (buffer[index++] << 16) | (buffer[index++] << 24); + + // Ensure buffer is valid size + if (size < 5 || size > buffer.length) throw new BSONError('corrupt bson message'); + + // Create holding object + const object: Document = isArray ? [] : {}; + // Used for arrays to skip having to perform utf8 decoding + let arrayIndex = 0; + const done = false; + + let isPossibleDBRef = isArray ? false : null; + + // While we have more left data left keep parsing + const dataview = new DataView(buffer.buffer, buffer.byteOffset, buffer.byteLength); + while (!done) { + // Read the type + const elementType = buffer[index++]; + + // If we get a zero it's the last byte, exit + if (elementType === 0) break; + + // Get the start search index + let i = index; + // Locate the end of the c string + while (buffer[i] !== 0x00 && i < buffer.length) { + i++; + } + + // If are at the end of the buffer there is a problem with the document + if (i >= buffer.byteLength) throw new BSONError('Bad BSON Document: illegal CString'); + + // Represents the key + const name = isArray ? arrayIndex++ : buffer.toString('utf8', index, i); + + // shouldValidateKey is true if the key should be validated, false otherwise + let shouldValidateKey = true; + if (globalUTFValidation || utf8KeysSet.has(name)) { + shouldValidateKey = validationSetting; + } else { + shouldValidateKey = !validationSetting; + } + + if (isPossibleDBRef !== false && (name as string)[0] === '$') { + isPossibleDBRef = allowedDBRefKeys.test(name as string); + } + let value; + + index = i + 1; + + if (elementType === constants.BSON_DATA_STRING) { + const stringSize = + buffer[index++] | + (buffer[index++] << 8) | + (buffer[index++] << 16) | + (buffer[index++] << 24); + if ( + stringSize <= 0 || + stringSize > buffer.length - index || + buffer[index + stringSize - 1] !== 0 + ) { + throw new BSONError('bad string length in bson'); + } + value = getValidatedString(buffer, index, index + stringSize - 1, shouldValidateKey); + index = index + stringSize; + } else if (elementType === constants.BSON_DATA_OID) { + const oid = Buffer.alloc(12); + buffer.copy(oid, 0, index, index + 12); + value = new ObjectId(oid); + index = index + 12; + } else if (elementType === constants.BSON_DATA_INT && promoteValues === false) { + value = new Int32( + buffer[index++] | (buffer[index++] << 8) | (buffer[index++] << 16) | (buffer[index++] << 24) + ); + } else if (elementType === constants.BSON_DATA_INT) { + value = + buffer[index++] | + (buffer[index++] << 8) | + (buffer[index++] << 16) | + (buffer[index++] << 24); + } else if (elementType === constants.BSON_DATA_NUMBER && promoteValues === false) { + value = new Double(dataview.getFloat64(index, true)); + index = index + 8; + } else if (elementType === constants.BSON_DATA_NUMBER) { + value = dataview.getFloat64(index, true); + index = index + 8; + } else if (elementType === constants.BSON_DATA_DATE) { + const lowBits = + buffer[index++] | + (buffer[index++] << 8) | + (buffer[index++] << 16) | + (buffer[index++] << 24); + const highBits = + buffer[index++] | + (buffer[index++] << 8) | + (buffer[index++] << 16) | + (buffer[index++] << 24); + value = new Date(new Long(lowBits, highBits).toNumber()); + } else if (elementType === constants.BSON_DATA_BOOLEAN) { + if (buffer[index] !== 0 && buffer[index] !== 1) + throw new BSONError('illegal boolean type value'); + value = buffer[index++] === 1; + } else if (elementType === constants.BSON_DATA_OBJECT) { + const _index = index; + const objectSize = + buffer[index] | + (buffer[index + 1] << 8) | + (buffer[index + 2] << 16) | + (buffer[index + 3] << 24); + if (objectSize <= 0 || objectSize > buffer.length - index) + throw new BSONError('bad embedded document length in bson'); + + // We have a raw value + if (raw) { + value = buffer.slice(index, index + objectSize); + } else { + let objectOptions = options; + if (!globalUTFValidation) { + objectOptions = { ...options, validation: { utf8: shouldValidateKey } }; + } + value = deserializeObject(buffer, _index, objectOptions, false); + } + + index = index + objectSize; + } else if (elementType === constants.BSON_DATA_ARRAY) { + const _index = index; + const objectSize = + buffer[index] | + (buffer[index + 1] << 8) | + (buffer[index + 2] << 16) | + (buffer[index + 3] << 24); + let arrayOptions = options; + + // Stop index + const stopIndex = index + objectSize; + + // All elements of array to be returned as raw bson + if (fieldsAsRaw && fieldsAsRaw[name]) { + arrayOptions = {}; + for (const n in options) { + ( + arrayOptions as { + [key: string]: DeserializeOptions[keyof DeserializeOptions]; + } + )[n] = options[n as keyof DeserializeOptions]; + } + arrayOptions['raw'] = true; + } + if (!globalUTFValidation) { + arrayOptions = { ...arrayOptions, validation: { utf8: shouldValidateKey } }; + } + value = deserializeObject(buffer, _index, arrayOptions, true); + index = index + objectSize; + + if (buffer[index - 1] !== 0) throw new BSONError('invalid array terminator byte'); + if (index !== stopIndex) throw new BSONError('corrupted array bson'); + } else if (elementType === constants.BSON_DATA_UNDEFINED) { + value = undefined; + } else if (elementType === constants.BSON_DATA_NULL) { + value = null; + } else if (elementType === constants.BSON_DATA_LONG) { + // Unpack the low and high bits + const lowBits = + buffer[index++] | + (buffer[index++] << 8) | + (buffer[index++] << 16) | + (buffer[index++] << 24); + const highBits = + buffer[index++] | + (buffer[index++] << 8) | + (buffer[index++] << 16) | + (buffer[index++] << 24); + const long = new Long(lowBits, highBits); + // Promote the long if possible + if (promoteLongs && promoteValues === true) { + value = + long.lessThanOrEqual(JS_INT_MAX_LONG) && long.greaterThanOrEqual(JS_INT_MIN_LONG) + ? long.toNumber() + : long; + } else { + value = long; + } + } else if (elementType === constants.BSON_DATA_DECIMAL128) { + // Buffer to contain the decimal bytes + const bytes = Buffer.alloc(16); + // Copy the next 16 bytes into the bytes buffer + buffer.copy(bytes, 0, index, index + 16); + // Update index + index = index + 16; + // Assign the new Decimal128 value + const decimal128 = new Decimal128(bytes) as Decimal128 | { toObject(): unknown }; + // If we have an alternative mapper use that + if ('toObject' in decimal128 && typeof decimal128.toObject === 'function') { + value = decimal128.toObject(); + } else { + value = decimal128; + } + } else if (elementType === constants.BSON_DATA_BINARY) { + let binarySize = + buffer[index++] | + (buffer[index++] << 8) | + (buffer[index++] << 16) | + (buffer[index++] << 24); + const totalBinarySize = binarySize; + const subType = buffer[index++]; + + // Did we have a negative binary size, throw + if (binarySize < 0) throw new BSONError('Negative binary type element size found'); + + // Is the length longer than the document + if (binarySize > buffer.byteLength) + throw new BSONError('Binary type size larger than document size'); + + // Decode as raw Buffer object if options specifies it + if (buffer['slice'] != null) { + // If we have subtype 2 skip the 4 bytes for the size + if (subType === Binary.SUBTYPE_BYTE_ARRAY) { + binarySize = + buffer[index++] | + (buffer[index++] << 8) | + (buffer[index++] << 16) | + (buffer[index++] << 24); + if (binarySize < 0) + throw new BSONError('Negative binary type element size found for subtype 0x02'); + if (binarySize > totalBinarySize - 4) + throw new BSONError('Binary type with subtype 0x02 contains too long binary size'); + if (binarySize < totalBinarySize - 4) + throw new BSONError('Binary type with subtype 0x02 contains too short binary size'); + } + + if (promoteBuffers && promoteValues) { + value = buffer.slice(index, index + binarySize); + } else { + value = new Binary(buffer.slice(index, index + binarySize), subType); + } + } else { + const _buffer = Buffer.alloc(binarySize); + // If we have subtype 2 skip the 4 bytes for the size + if (subType === Binary.SUBTYPE_BYTE_ARRAY) { + binarySize = + buffer[index++] | + (buffer[index++] << 8) | + (buffer[index++] << 16) | + (buffer[index++] << 24); + if (binarySize < 0) + throw new BSONError('Negative binary type element size found for subtype 0x02'); + if (binarySize > totalBinarySize - 4) + throw new BSONError('Binary type with subtype 0x02 contains too long binary size'); + if (binarySize < totalBinarySize - 4) + throw new BSONError('Binary type with subtype 0x02 contains too short binary size'); + } + + // Copy the data + for (i = 0; i < binarySize; i++) { + _buffer[i] = buffer[index + i]; + } + + if (promoteBuffers && promoteValues) { + value = _buffer; + } else { + value = new Binary(_buffer, subType); + } + } + + // Update the index + index = index + binarySize; + } else if (elementType === constants.BSON_DATA_REGEXP && bsonRegExp === false) { + // Get the start search index + i = index; + // Locate the end of the c string + while (buffer[i] !== 0x00 && i < buffer.length) { + i++; + } + // If are at the end of the buffer there is a problem with the document + if (i >= buffer.length) throw new BSONError('Bad BSON Document: illegal CString'); + // Return the C string + const source = buffer.toString('utf8', index, i); + // Create the regexp + index = i + 1; + + // Get the start search index + i = index; + // Locate the end of the c string + while (buffer[i] !== 0x00 && i < buffer.length) { + i++; + } + // If are at the end of the buffer there is a problem with the document + if (i >= buffer.length) throw new BSONError('Bad BSON Document: illegal CString'); + // Return the C string + const regExpOptions = buffer.toString('utf8', index, i); + index = i + 1; + + // For each option add the corresponding one for javascript + const optionsArray = new Array(regExpOptions.length); + + // Parse options + for (i = 0; i < regExpOptions.length; i++) { + switch (regExpOptions[i]) { + case 'm': + optionsArray[i] = 'm'; + break; + case 's': + optionsArray[i] = 'g'; + break; + case 'i': + optionsArray[i] = 'i'; + break; + } + } + + value = new RegExp(source, optionsArray.join('')); + } else if (elementType === constants.BSON_DATA_REGEXP && bsonRegExp === true) { + // Get the start search index + i = index; + // Locate the end of the c string + while (buffer[i] !== 0x00 && i < buffer.length) { + i++; + } + // If are at the end of the buffer there is a problem with the document + if (i >= buffer.length) throw new BSONError('Bad BSON Document: illegal CString'); + // Return the C string + const source = buffer.toString('utf8', index, i); + index = i + 1; + + // Get the start search index + i = index; + // Locate the end of the c string + while (buffer[i] !== 0x00 && i < buffer.length) { + i++; + } + // If are at the end of the buffer there is a problem with the document + if (i >= buffer.length) throw new BSONError('Bad BSON Document: illegal CString'); + // Return the C string + const regExpOptions = buffer.toString('utf8', index, i); + index = i + 1; + + // Set the object + value = new BSONRegExp(source, regExpOptions); + } else if (elementType === constants.BSON_DATA_SYMBOL) { + const stringSize = + buffer[index++] | + (buffer[index++] << 8) | + (buffer[index++] << 16) | + (buffer[index++] << 24); + if ( + stringSize <= 0 || + stringSize > buffer.length - index || + buffer[index + stringSize - 1] !== 0 + ) { + throw new BSONError('bad string length in bson'); + } + const symbol = getValidatedString(buffer, index, index + stringSize - 1, shouldValidateKey); + value = promoteValues ? symbol : new BSONSymbol(symbol); + index = index + stringSize; + } else if (elementType === constants.BSON_DATA_TIMESTAMP) { + const lowBits = + buffer[index++] | + (buffer[index++] << 8) | + (buffer[index++] << 16) | + (buffer[index++] << 24); + const highBits = + buffer[index++] | + (buffer[index++] << 8) | + (buffer[index++] << 16) | + (buffer[index++] << 24); + + value = new Timestamp(lowBits, highBits); + } else if (elementType === constants.BSON_DATA_MIN_KEY) { + value = new MinKey(); + } else if (elementType === constants.BSON_DATA_MAX_KEY) { + value = new MaxKey(); + } else if (elementType === constants.BSON_DATA_CODE) { + const stringSize = + buffer[index++] | + (buffer[index++] << 8) | + (buffer[index++] << 16) | + (buffer[index++] << 24); + if ( + stringSize <= 0 || + stringSize > buffer.length - index || + buffer[index + stringSize - 1] !== 0 + ) { + throw new BSONError('bad string length in bson'); + } + const functionString = getValidatedString( + buffer, + index, + index + stringSize - 1, + shouldValidateKey + ); + + // If we are evaluating the functions + if (evalFunctions) { + // If we have cache enabled let's look for the md5 of the function in the cache + if (cacheFunctions) { + // Got to do this to avoid V8 deoptimizing the call due to finding eval + value = isolateEval(functionString, functionCache, object); + } else { + value = isolateEval(functionString); + } + } else { + value = new Code(functionString); + } + + // Update parse index position + index = index + stringSize; + } else if (elementType === constants.BSON_DATA_CODE_W_SCOPE) { + const totalSize = + buffer[index++] | + (buffer[index++] << 8) | + (buffer[index++] << 16) | + (buffer[index++] << 24); + + // Element cannot be shorter than totalSize + stringSize + documentSize + terminator + if (totalSize < 4 + 4 + 4 + 1) { + throw new BSONError('code_w_scope total size shorter minimum expected length'); + } + + // Get the code string size + const stringSize = + buffer[index++] | + (buffer[index++] << 8) | + (buffer[index++] << 16) | + (buffer[index++] << 24); + // Check if we have a valid string + if ( + stringSize <= 0 || + stringSize > buffer.length - index || + buffer[index + stringSize - 1] !== 0 + ) { + throw new BSONError('bad string length in bson'); + } + + // Javascript function + const functionString = getValidatedString( + buffer, + index, + index + stringSize - 1, + shouldValidateKey + ); + // Update parse index position + index = index + stringSize; + // Parse the element + const _index = index; + // Decode the size of the object document + const objectSize = + buffer[index] | + (buffer[index + 1] << 8) | + (buffer[index + 2] << 16) | + (buffer[index + 3] << 24); + // Decode the scope object + const scopeObject = deserializeObject(buffer, _index, options, false); + // Adjust the index + index = index + objectSize; + + // Check if field length is too short + if (totalSize < 4 + 4 + objectSize + stringSize) { + throw new BSONError('code_w_scope total size is too short, truncating scope'); + } + + // Check if totalSize field is too long + if (totalSize > 4 + 4 + objectSize + stringSize) { + throw new BSONError('code_w_scope total size is too long, clips outer document'); + } + + // If we are evaluating the functions + if (evalFunctions) { + // If we have cache enabled let's look for the md5 of the function in the cache + if (cacheFunctions) { + // Got to do this to avoid V8 deoptimizing the call due to finding eval + value = isolateEval(functionString, functionCache, object); + } else { + value = isolateEval(functionString); + } + + value.scope = scopeObject; + } else { + value = new Code(functionString, scopeObject); + } + } else if (elementType === constants.BSON_DATA_DBPOINTER) { + // Get the code string size + const stringSize = + buffer[index++] | + (buffer[index++] << 8) | + (buffer[index++] << 16) | + (buffer[index++] << 24); + // Check if we have a valid string + if ( + stringSize <= 0 || + stringSize > buffer.length - index || + buffer[index + stringSize - 1] !== 0 + ) + throw new BSONError('bad string length in bson'); + // Namespace + if (validation != null && validation.utf8) { + if (!validateUtf8(buffer, index, index + stringSize - 1)) { + throw new BSONError('Invalid UTF-8 string in BSON document'); + } + } + const namespace = buffer.toString('utf8', index, index + stringSize - 1); + // Update parse index position + index = index + stringSize; + + // Read the oid + const oidBuffer = Buffer.alloc(12); + buffer.copy(oidBuffer, 0, index, index + 12); + const oid = new ObjectId(oidBuffer); + + // Update the index + index = index + 12; + + // Upgrade to DBRef type + value = new DBRef(namespace, oid); + } else { + throw new BSONError( + `Detected unknown BSON type ${elementType.toString(16)} for fieldname "${name}"` + ); + } + if (name === '__proto__') { + Object.defineProperty(object, name, { + value, + writable: true, + enumerable: true, + configurable: true + }); + } else { + object[name] = value; + } + } + + // Check if the deserialization was against a valid array/object + if (size !== index - startIndex) { + if (isArray) throw new BSONError('corrupt array bson'); + throw new BSONError('corrupt object bson'); + } + + // if we did not find "$ref", "$id", "$db", or found an extraneous $key, don't make a DBRef + if (!isPossibleDBRef) return object; + + if (isDBRefLike(object)) { + const copy = Object.assign({}, object) as Partial; + delete copy.$ref; + delete copy.$id; + delete copy.$db; + return new DBRef(object.$ref, object.$id, object.$db, copy); + } + + return object; +} + +/** + * Ensure eval is isolated, store the result in functionCache. + * + * @internal + */ +function isolateEval( + functionString: string, + functionCache?: { [hash: string]: Function }, + object?: Document +) { + // eslint-disable-next-line @typescript-eslint/no-implied-eval + if (!functionCache) return new Function(functionString); + // Check for cache hit, eval if missing and return cached function + if (functionCache[functionString] == null) { + // eslint-disable-next-line @typescript-eslint/no-implied-eval + functionCache[functionString] = new Function(functionString); + } + + // Set the object + return functionCache[functionString].bind(object); +} + +function getValidatedString( + buffer: Buffer, + start: number, + end: number, + shouldValidateUtf8: boolean +) { + const value = buffer.toString('utf8', start, end); + // if utf8 validation is on, do the check + if (shouldValidateUtf8) { + for (let i = 0; i < value.length; i++) { + if (value.charCodeAt(i) === 0xfffd) { + if (!validateUtf8(buffer, start, end)) { + throw new BSONError('Invalid UTF-8 string in BSON document'); + } + break; + } + } + } + return value; +} diff --git a/ts-ticket-office-service/node_modules/bson/src/parser/serializer.ts b/ts-ticket-office-service/node_modules/bson/src/parser/serializer.ts new file mode 100644 index 000000000..e76402aa3 --- /dev/null +++ b/ts-ticket-office-service/node_modules/bson/src/parser/serializer.ts @@ -0,0 +1,1076 @@ +import type { Buffer } from 'buffer'; +import { Binary } from '../binary'; +import type { BSONSymbol, DBRef, Document, MaxKey } from '../bson'; +import type { Code } from '../code'; +import * as constants from '../constants'; +import type { DBRefLike } from '../db_ref'; +import type { Decimal128 } from '../decimal128'; +import type { Double } from '../double'; +import { ensureBuffer } from '../ensure_buffer'; +import { BSONError, BSONTypeError } from '../error'; +import { isBSONType } from '../extended_json'; +import type { Int32 } from '../int_32'; +import { Long } from '../long'; +import { Map } from '../map'; +import type { MinKey } from '../min_key'; +import type { ObjectId } from '../objectid'; +import type { BSONRegExp } from '../regexp'; +import { + isBigInt64Array, + isBigUInt64Array, + isDate, + isMap, + isRegExp, + isUint8Array, + normalizedFunctionString +} from './utils'; + +/** @public */ +export interface SerializeOptions { + /** the serializer will check if keys are valid. */ + checkKeys?: boolean; + /** serialize the javascript functions **(default:false)**. */ + serializeFunctions?: boolean; + /** serialize will not emit undefined fields **(default:true)** */ + ignoreUndefined?: boolean; + /** @internal Resize internal buffer */ + minInternalBufferSize?: number; + /** the index in the buffer where we wish to start serializing into */ + index?: number; +} + +const regexp = /\x00/; // eslint-disable-line no-control-regex +const ignoreKeys = new Set(['$db', '$ref', '$id', '$clusterTime']); + +/* + * isArray indicates if we are writing to a BSON array (type 0x04) + * which forces the "key" which really an array index as a string to be written as ascii + * This will catch any errors in index as a string generation + */ + +function serializeString( + buffer: Buffer, + key: string, + value: string, + index: number, + isArray?: boolean +) { + // Encode String type + buffer[index++] = constants.BSON_DATA_STRING; + // Number of written bytes + const numberOfWrittenBytes = !isArray + ? buffer.write(key, index, undefined, 'utf8') + : buffer.write(key, index, undefined, 'ascii'); + // Encode the name + index = index + numberOfWrittenBytes + 1; + buffer[index - 1] = 0; + // Write the string + const size = buffer.write(value, index + 4, undefined, 'utf8'); + // Write the size of the string to buffer + buffer[index + 3] = ((size + 1) >> 24) & 0xff; + buffer[index + 2] = ((size + 1) >> 16) & 0xff; + buffer[index + 1] = ((size + 1) >> 8) & 0xff; + buffer[index] = (size + 1) & 0xff; + // Update index + index = index + 4 + size; + // Write zero + buffer[index++] = 0; + return index; +} + +const SPACE_FOR_FLOAT64 = new Uint8Array(8); +const DV_FOR_FLOAT64 = new DataView( + SPACE_FOR_FLOAT64.buffer, + SPACE_FOR_FLOAT64.byteOffset, + SPACE_FOR_FLOAT64.byteLength +); +function serializeNumber( + buffer: Buffer, + key: string, + value: number, + index: number, + isArray?: boolean +) { + // We have an integer value + // TODO(NODE-2529): Add support for big int + if ( + Number.isInteger(value) && + value >= constants.BSON_INT32_MIN && + value <= constants.BSON_INT32_MAX + ) { + // If the value fits in 32 bits encode as int32 + // Set int type 32 bits or less + buffer[index++] = constants.BSON_DATA_INT; + // Number of written bytes + const numberOfWrittenBytes = !isArray + ? buffer.write(key, index, undefined, 'utf8') + : buffer.write(key, index, undefined, 'ascii'); + // Encode the name + index = index + numberOfWrittenBytes; + buffer[index++] = 0; + // Write the int value + buffer[index++] = value & 0xff; + buffer[index++] = (value >> 8) & 0xff; + buffer[index++] = (value >> 16) & 0xff; + buffer[index++] = (value >> 24) & 0xff; + } else { + // Encode as double + buffer[index++] = constants.BSON_DATA_NUMBER; + // Number of written bytes + const numberOfWrittenBytes = !isArray + ? buffer.write(key, index, undefined, 'utf8') + : buffer.write(key, index, undefined, 'ascii'); + // Encode the name + index = index + numberOfWrittenBytes; + buffer[index++] = 0; + // Write float + DV_FOR_FLOAT64.setFloat64(0, value, true); + buffer.set(SPACE_FOR_FLOAT64, index); + // Adjust index + index = index + 8; + } + + return index; +} + +function serializeNull(buffer: Buffer, key: string, _: unknown, index: number, isArray?: boolean) { + // Set long type + buffer[index++] = constants.BSON_DATA_NULL; + + // Number of written bytes + const numberOfWrittenBytes = !isArray + ? buffer.write(key, index, undefined, 'utf8') + : buffer.write(key, index, undefined, 'ascii'); + + // Encode the name + index = index + numberOfWrittenBytes; + buffer[index++] = 0; + return index; +} + +function serializeBoolean( + buffer: Buffer, + key: string, + value: boolean, + index: number, + isArray?: boolean +) { + // Write the type + buffer[index++] = constants.BSON_DATA_BOOLEAN; + // Number of written bytes + const numberOfWrittenBytes = !isArray + ? buffer.write(key, index, undefined, 'utf8') + : buffer.write(key, index, undefined, 'ascii'); + // Encode the name + index = index + numberOfWrittenBytes; + buffer[index++] = 0; + // Encode the boolean value + buffer[index++] = value ? 1 : 0; + return index; +} + +function serializeDate(buffer: Buffer, key: string, value: Date, index: number, isArray?: boolean) { + // Write the type + buffer[index++] = constants.BSON_DATA_DATE; + // Number of written bytes + const numberOfWrittenBytes = !isArray + ? buffer.write(key, index, undefined, 'utf8') + : buffer.write(key, index, undefined, 'ascii'); + // Encode the name + index = index + numberOfWrittenBytes; + buffer[index++] = 0; + + // Write the date + const dateInMilis = Long.fromNumber(value.getTime()); + const lowBits = dateInMilis.getLowBits(); + const highBits = dateInMilis.getHighBits(); + // Encode low bits + buffer[index++] = lowBits & 0xff; + buffer[index++] = (lowBits >> 8) & 0xff; + buffer[index++] = (lowBits >> 16) & 0xff; + buffer[index++] = (lowBits >> 24) & 0xff; + // Encode high bits + buffer[index++] = highBits & 0xff; + buffer[index++] = (highBits >> 8) & 0xff; + buffer[index++] = (highBits >> 16) & 0xff; + buffer[index++] = (highBits >> 24) & 0xff; + return index; +} + +function serializeRegExp( + buffer: Buffer, + key: string, + value: RegExp, + index: number, + isArray?: boolean +) { + // Write the type + buffer[index++] = constants.BSON_DATA_REGEXP; + // Number of written bytes + const numberOfWrittenBytes = !isArray + ? buffer.write(key, index, undefined, 'utf8') + : buffer.write(key, index, undefined, 'ascii'); + + // Encode the name + index = index + numberOfWrittenBytes; + buffer[index++] = 0; + if (value.source && value.source.match(regexp) != null) { + throw Error('value ' + value.source + ' must not contain null bytes'); + } + // Adjust the index + index = index + buffer.write(value.source, index, undefined, 'utf8'); + // Write zero + buffer[index++] = 0x00; + // Write the parameters + if (value.ignoreCase) buffer[index++] = 0x69; // i + if (value.global) buffer[index++] = 0x73; // s + if (value.multiline) buffer[index++] = 0x6d; // m + + // Add ending zero + buffer[index++] = 0x00; + return index; +} + +function serializeBSONRegExp( + buffer: Buffer, + key: string, + value: BSONRegExp, + index: number, + isArray?: boolean +) { + // Write the type + buffer[index++] = constants.BSON_DATA_REGEXP; + // Number of written bytes + const numberOfWrittenBytes = !isArray + ? buffer.write(key, index, undefined, 'utf8') + : buffer.write(key, index, undefined, 'ascii'); + // Encode the name + index = index + numberOfWrittenBytes; + buffer[index++] = 0; + + // Check the pattern for 0 bytes + if (value.pattern.match(regexp) != null) { + // The BSON spec doesn't allow keys with null bytes because keys are + // null-terminated. + throw Error('pattern ' + value.pattern + ' must not contain null bytes'); + } + + // Adjust the index + index = index + buffer.write(value.pattern, index, undefined, 'utf8'); + // Write zero + buffer[index++] = 0x00; + // Write the options + index = index + buffer.write(value.options.split('').sort().join(''), index, undefined, 'utf8'); + // Add ending zero + buffer[index++] = 0x00; + return index; +} + +function serializeMinMax( + buffer: Buffer, + key: string, + value: MinKey | MaxKey, + index: number, + isArray?: boolean +) { + // Write the type of either min or max key + if (value === null) { + buffer[index++] = constants.BSON_DATA_NULL; + } else if (value._bsontype === 'MinKey') { + buffer[index++] = constants.BSON_DATA_MIN_KEY; + } else { + buffer[index++] = constants.BSON_DATA_MAX_KEY; + } + + // Number of written bytes + const numberOfWrittenBytes = !isArray + ? buffer.write(key, index, undefined, 'utf8') + : buffer.write(key, index, undefined, 'ascii'); + // Encode the name + index = index + numberOfWrittenBytes; + buffer[index++] = 0; + return index; +} + +function serializeObjectId( + buffer: Buffer, + key: string, + value: ObjectId, + index: number, + isArray?: boolean +) { + // Write the type + buffer[index++] = constants.BSON_DATA_OID; + // Number of written bytes + const numberOfWrittenBytes = !isArray + ? buffer.write(key, index, undefined, 'utf8') + : buffer.write(key, index, undefined, 'ascii'); + + // Encode the name + index = index + numberOfWrittenBytes; + buffer[index++] = 0; + + // Write the objectId into the shared buffer + if (typeof value.id === 'string') { + buffer.write(value.id, index, undefined, 'binary'); + } else if (isUint8Array(value.id)) { + // Use the standard JS methods here because buffer.copy() is buggy with the + // browser polyfill + buffer.set(value.id.subarray(0, 12), index); + } else { + throw new BSONTypeError('object [' + JSON.stringify(value) + '] is not a valid ObjectId'); + } + + // Adjust index + return index + 12; +} + +function serializeBuffer( + buffer: Buffer, + key: string, + value: Buffer | Uint8Array, + index: number, + isArray?: boolean +) { + // Write the type + buffer[index++] = constants.BSON_DATA_BINARY; + // Number of written bytes + const numberOfWrittenBytes = !isArray + ? buffer.write(key, index, undefined, 'utf8') + : buffer.write(key, index, undefined, 'ascii'); + // Encode the name + index = index + numberOfWrittenBytes; + buffer[index++] = 0; + // Get size of the buffer (current write point) + const size = value.length; + // Write the size of the string to buffer + buffer[index++] = size & 0xff; + buffer[index++] = (size >> 8) & 0xff; + buffer[index++] = (size >> 16) & 0xff; + buffer[index++] = (size >> 24) & 0xff; + // Write the default subtype + buffer[index++] = constants.BSON_BINARY_SUBTYPE_DEFAULT; + // Copy the content form the binary field to the buffer + buffer.set(ensureBuffer(value), index); + // Adjust the index + index = index + size; + return index; +} + +function serializeObject( + buffer: Buffer, + key: string, + value: Document, + index: number, + checkKeys = false, + depth = 0, + serializeFunctions = false, + ignoreUndefined = true, + isArray = false, + path: Document[] = [] +) { + for (let i = 0; i < path.length; i++) { + if (path[i] === value) throw new BSONError('cyclic dependency detected'); + } + + // Push value to stack + path.push(value); + // Write the type + buffer[index++] = Array.isArray(value) ? constants.BSON_DATA_ARRAY : constants.BSON_DATA_OBJECT; + // Number of written bytes + const numberOfWrittenBytes = !isArray + ? buffer.write(key, index, undefined, 'utf8') + : buffer.write(key, index, undefined, 'ascii'); + // Encode the name + index = index + numberOfWrittenBytes; + buffer[index++] = 0; + const endIndex = serializeInto( + buffer, + value, + checkKeys, + index, + depth + 1, + serializeFunctions, + ignoreUndefined, + path + ); + // Pop stack + path.pop(); + return endIndex; +} + +function serializeDecimal128( + buffer: Buffer, + key: string, + value: Decimal128, + index: number, + isArray?: boolean +) { + buffer[index++] = constants.BSON_DATA_DECIMAL128; + // Number of written bytes + const numberOfWrittenBytes = !isArray + ? buffer.write(key, index, undefined, 'utf8') + : buffer.write(key, index, undefined, 'ascii'); + // Encode the name + index = index + numberOfWrittenBytes; + buffer[index++] = 0; + // Write the data from the value + // Prefer the standard JS methods because their typechecking is not buggy, + // unlike the `buffer` polyfill's. + buffer.set(value.bytes.subarray(0, 16), index); + return index + 16; +} + +function serializeLong(buffer: Buffer, key: string, value: Long, index: number, isArray?: boolean) { + // Write the type + buffer[index++] = + value._bsontype === 'Long' ? constants.BSON_DATA_LONG : constants.BSON_DATA_TIMESTAMP; + // Number of written bytes + const numberOfWrittenBytes = !isArray + ? buffer.write(key, index, undefined, 'utf8') + : buffer.write(key, index, undefined, 'ascii'); + // Encode the name + index = index + numberOfWrittenBytes; + buffer[index++] = 0; + // Write the date + const lowBits = value.getLowBits(); + const highBits = value.getHighBits(); + // Encode low bits + buffer[index++] = lowBits & 0xff; + buffer[index++] = (lowBits >> 8) & 0xff; + buffer[index++] = (lowBits >> 16) & 0xff; + buffer[index++] = (lowBits >> 24) & 0xff; + // Encode high bits + buffer[index++] = highBits & 0xff; + buffer[index++] = (highBits >> 8) & 0xff; + buffer[index++] = (highBits >> 16) & 0xff; + buffer[index++] = (highBits >> 24) & 0xff; + return index; +} + +function serializeInt32( + buffer: Buffer, + key: string, + value: Int32 | number, + index: number, + isArray?: boolean +) { + value = value.valueOf(); + // Set int type 32 bits or less + buffer[index++] = constants.BSON_DATA_INT; + // Number of written bytes + const numberOfWrittenBytes = !isArray + ? buffer.write(key, index, undefined, 'utf8') + : buffer.write(key, index, undefined, 'ascii'); + // Encode the name + index = index + numberOfWrittenBytes; + buffer[index++] = 0; + // Write the int value + buffer[index++] = value & 0xff; + buffer[index++] = (value >> 8) & 0xff; + buffer[index++] = (value >> 16) & 0xff; + buffer[index++] = (value >> 24) & 0xff; + return index; +} + +function serializeDouble( + buffer: Buffer, + key: string, + value: Double, + index: number, + isArray?: boolean +) { + // Encode as double + buffer[index++] = constants.BSON_DATA_NUMBER; + + // Number of written bytes + const numberOfWrittenBytes = !isArray + ? buffer.write(key, index, undefined, 'utf8') + : buffer.write(key, index, undefined, 'ascii'); + + // Encode the name + index = index + numberOfWrittenBytes; + buffer[index++] = 0; + + // Write float + DV_FOR_FLOAT64.setFloat64(0, value.value, true); + buffer.set(SPACE_FOR_FLOAT64, index); + + // Adjust index + index = index + 8; + return index; +} + +function serializeFunction( + buffer: Buffer, + key: string, + value: Function, + index: number, + _checkKeys = false, + _depth = 0, + isArray?: boolean +) { + buffer[index++] = constants.BSON_DATA_CODE; + // Number of written bytes + const numberOfWrittenBytes = !isArray + ? buffer.write(key, index, undefined, 'utf8') + : buffer.write(key, index, undefined, 'ascii'); + // Encode the name + index = index + numberOfWrittenBytes; + buffer[index++] = 0; + // Function string + const functionString = normalizedFunctionString(value); + + // Write the string + const size = buffer.write(functionString, index + 4, undefined, 'utf8') + 1; + // Write the size of the string to buffer + buffer[index] = size & 0xff; + buffer[index + 1] = (size >> 8) & 0xff; + buffer[index + 2] = (size >> 16) & 0xff; + buffer[index + 3] = (size >> 24) & 0xff; + // Update index + index = index + 4 + size - 1; + // Write zero + buffer[index++] = 0; + return index; +} + +function serializeCode( + buffer: Buffer, + key: string, + value: Code, + index: number, + checkKeys = false, + depth = 0, + serializeFunctions = false, + ignoreUndefined = true, + isArray = false +) { + if (value.scope && typeof value.scope === 'object') { + // Write the type + buffer[index++] = constants.BSON_DATA_CODE_W_SCOPE; + // Number of written bytes + const numberOfWrittenBytes = !isArray + ? buffer.write(key, index, undefined, 'utf8') + : buffer.write(key, index, undefined, 'ascii'); + // Encode the name + index = index + numberOfWrittenBytes; + buffer[index++] = 0; + + // Starting index + let startIndex = index; + + // Serialize the function + // Get the function string + const functionString = typeof value.code === 'string' ? value.code : value.code.toString(); + // Index adjustment + index = index + 4; + // Write string into buffer + const codeSize = buffer.write(functionString, index + 4, undefined, 'utf8') + 1; + // Write the size of the string to buffer + buffer[index] = codeSize & 0xff; + buffer[index + 1] = (codeSize >> 8) & 0xff; + buffer[index + 2] = (codeSize >> 16) & 0xff; + buffer[index + 3] = (codeSize >> 24) & 0xff; + // Write end 0 + buffer[index + 4 + codeSize - 1] = 0; + // Write the + index = index + codeSize + 4; + + // + // Serialize the scope value + const endIndex = serializeInto( + buffer, + value.scope, + checkKeys, + index, + depth + 1, + serializeFunctions, + ignoreUndefined + ); + index = endIndex - 1; + + // Writ the total + const totalSize = endIndex - startIndex; + + // Write the total size of the object + buffer[startIndex++] = totalSize & 0xff; + buffer[startIndex++] = (totalSize >> 8) & 0xff; + buffer[startIndex++] = (totalSize >> 16) & 0xff; + buffer[startIndex++] = (totalSize >> 24) & 0xff; + // Write trailing zero + buffer[index++] = 0; + } else { + buffer[index++] = constants.BSON_DATA_CODE; + // Number of written bytes + const numberOfWrittenBytes = !isArray + ? buffer.write(key, index, undefined, 'utf8') + : buffer.write(key, index, undefined, 'ascii'); + // Encode the name + index = index + numberOfWrittenBytes; + buffer[index++] = 0; + // Function string + const functionString = value.code.toString(); + // Write the string + const size = buffer.write(functionString, index + 4, undefined, 'utf8') + 1; + // Write the size of the string to buffer + buffer[index] = size & 0xff; + buffer[index + 1] = (size >> 8) & 0xff; + buffer[index + 2] = (size >> 16) & 0xff; + buffer[index + 3] = (size >> 24) & 0xff; + // Update index + index = index + 4 + size - 1; + // Write zero + buffer[index++] = 0; + } + + return index; +} + +function serializeBinary( + buffer: Buffer, + key: string, + value: Binary, + index: number, + isArray?: boolean +) { + // Write the type + buffer[index++] = constants.BSON_DATA_BINARY; + // Number of written bytes + const numberOfWrittenBytes = !isArray + ? buffer.write(key, index, undefined, 'utf8') + : buffer.write(key, index, undefined, 'ascii'); + // Encode the name + index = index + numberOfWrittenBytes; + buffer[index++] = 0; + // Extract the buffer + const data = value.value(true) as Buffer | Uint8Array; + // Calculate size + let size = value.position; + // Add the deprecated 02 type 4 bytes of size to total + if (value.sub_type === Binary.SUBTYPE_BYTE_ARRAY) size = size + 4; + // Write the size of the string to buffer + buffer[index++] = size & 0xff; + buffer[index++] = (size >> 8) & 0xff; + buffer[index++] = (size >> 16) & 0xff; + buffer[index++] = (size >> 24) & 0xff; + // Write the subtype to the buffer + buffer[index++] = value.sub_type; + + // If we have binary type 2 the 4 first bytes are the size + if (value.sub_type === Binary.SUBTYPE_BYTE_ARRAY) { + size = size - 4; + buffer[index++] = size & 0xff; + buffer[index++] = (size >> 8) & 0xff; + buffer[index++] = (size >> 16) & 0xff; + buffer[index++] = (size >> 24) & 0xff; + } + + // Write the data to the object + buffer.set(data, index); + // Adjust the index + index = index + value.position; + return index; +} + +function serializeSymbol( + buffer: Buffer, + key: string, + value: BSONSymbol, + index: number, + isArray?: boolean +) { + // Write the type + buffer[index++] = constants.BSON_DATA_SYMBOL; + // Number of written bytes + const numberOfWrittenBytes = !isArray + ? buffer.write(key, index, undefined, 'utf8') + : buffer.write(key, index, undefined, 'ascii'); + // Encode the name + index = index + numberOfWrittenBytes; + buffer[index++] = 0; + // Write the string + const size = buffer.write(value.value, index + 4, undefined, 'utf8') + 1; + // Write the size of the string to buffer + buffer[index] = size & 0xff; + buffer[index + 1] = (size >> 8) & 0xff; + buffer[index + 2] = (size >> 16) & 0xff; + buffer[index + 3] = (size >> 24) & 0xff; + // Update index + index = index + 4 + size - 1; + // Write zero + buffer[index++] = 0x00; + return index; +} + +function serializeDBRef( + buffer: Buffer, + key: string, + value: DBRef, + index: number, + depth: number, + serializeFunctions: boolean, + isArray?: boolean +) { + // Write the type + buffer[index++] = constants.BSON_DATA_OBJECT; + // Number of written bytes + const numberOfWrittenBytes = !isArray + ? buffer.write(key, index, undefined, 'utf8') + : buffer.write(key, index, undefined, 'ascii'); + + // Encode the name + index = index + numberOfWrittenBytes; + buffer[index++] = 0; + + let startIndex = index; + let output: DBRefLike = { + $ref: value.collection || value.namespace, // "namespace" was what library 1.x called "collection" + $id: value.oid + }; + + if (value.db != null) { + output.$db = value.db; + } + + output = Object.assign(output, value.fields); + const endIndex = serializeInto(buffer, output, false, index, depth + 1, serializeFunctions); + + // Calculate object size + const size = endIndex - startIndex; + // Write the size + buffer[startIndex++] = size & 0xff; + buffer[startIndex++] = (size >> 8) & 0xff; + buffer[startIndex++] = (size >> 16) & 0xff; + buffer[startIndex++] = (size >> 24) & 0xff; + // Set index + return endIndex; +} + +export function serializeInto( + buffer: Buffer, + object: Document, + checkKeys = false, + startingIndex = 0, + depth = 0, + serializeFunctions = false, + ignoreUndefined = true, + path: Document[] = [] +): number { + startingIndex = startingIndex || 0; + path = path || []; + + // Push the object to the path + path.push(object); + + // Start place to serialize into + let index = startingIndex + 4; + + // Special case isArray + if (Array.isArray(object)) { + // Get object keys + for (let i = 0; i < object.length; i++) { + const key = `${i}`; + let value = object[i]; + + // Is there an override value + if (typeof value?.toBSON === 'function') { + value = value.toBSON(); + } + + if (typeof value === 'string') { + index = serializeString(buffer, key, value, index, true); + } else if (typeof value === 'number') { + index = serializeNumber(buffer, key, value, index, true); + } else if (typeof value === 'bigint') { + throw new BSONTypeError('Unsupported type BigInt, please use Decimal128'); + } else if (typeof value === 'boolean') { + index = serializeBoolean(buffer, key, value, index, true); + } else if (value instanceof Date || isDate(value)) { + index = serializeDate(buffer, key, value, index, true); + } else if (value === undefined) { + index = serializeNull(buffer, key, value, index, true); + } else if (value === null) { + index = serializeNull(buffer, key, value, index, true); + } else if (value['_bsontype'] === 'ObjectId' || value['_bsontype'] === 'ObjectID') { + index = serializeObjectId(buffer, key, value, index, true); + } else if (isUint8Array(value)) { + index = serializeBuffer(buffer, key, value, index, true); + } else if (value instanceof RegExp || isRegExp(value)) { + index = serializeRegExp(buffer, key, value, index, true); + } else if (typeof value === 'object' && value['_bsontype'] == null) { + index = serializeObject( + buffer, + key, + value, + index, + checkKeys, + depth, + serializeFunctions, + ignoreUndefined, + true, + path + ); + } else if ( + typeof value === 'object' && + isBSONType(value) && + value._bsontype === 'Decimal128' + ) { + index = serializeDecimal128(buffer, key, value, index, true); + } else if (value['_bsontype'] === 'Long' || value['_bsontype'] === 'Timestamp') { + index = serializeLong(buffer, key, value, index, true); + } else if (value['_bsontype'] === 'Double') { + index = serializeDouble(buffer, key, value, index, true); + } else if (typeof value === 'function' && serializeFunctions) { + index = serializeFunction(buffer, key, value, index, checkKeys, depth, true); + } else if (value['_bsontype'] === 'Code') { + index = serializeCode( + buffer, + key, + value, + index, + checkKeys, + depth, + serializeFunctions, + ignoreUndefined, + true + ); + } else if (value['_bsontype'] === 'Binary') { + index = serializeBinary(buffer, key, value, index, true); + } else if (value['_bsontype'] === 'Symbol') { + index = serializeSymbol(buffer, key, value, index, true); + } else if (value['_bsontype'] === 'DBRef') { + index = serializeDBRef(buffer, key, value, index, depth, serializeFunctions, true); + } else if (value['_bsontype'] === 'BSONRegExp') { + index = serializeBSONRegExp(buffer, key, value, index, true); + } else if (value['_bsontype'] === 'Int32') { + index = serializeInt32(buffer, key, value, index, true); + } else if (value['_bsontype'] === 'MinKey' || value['_bsontype'] === 'MaxKey') { + index = serializeMinMax(buffer, key, value, index, true); + } else if (typeof value['_bsontype'] !== 'undefined') { + throw new BSONTypeError(`Unrecognized or invalid _bsontype: ${String(value['_bsontype'])}`); + } + } + } else if (object instanceof Map || isMap(object)) { + const iterator = object.entries(); + let done = false; + + while (!done) { + // Unpack the next entry + const entry = iterator.next(); + done = !!entry.done; + // Are we done, then skip and terminate + if (done) continue; + + // Get the entry values + const key = entry.value[0]; + const value = entry.value[1]; + + // Check the type of the value + const type = typeof value; + + // Check the key and throw error if it's illegal + if (typeof key === 'string' && !ignoreKeys.has(key)) { + if (key.match(regexp) != null) { + // The BSON spec doesn't allow keys with null bytes because keys are + // null-terminated. + throw Error('key ' + key + ' must not contain null bytes'); + } + + if (checkKeys) { + if ('$' === key[0]) { + throw Error('key ' + key + " must not start with '$'"); + } else if (~key.indexOf('.')) { + throw Error('key ' + key + " must not contain '.'"); + } + } + } + + if (type === 'string') { + index = serializeString(buffer, key, value, index); + } else if (type === 'number') { + index = serializeNumber(buffer, key, value, index); + } else if (type === 'bigint' || isBigInt64Array(value) || isBigUInt64Array(value)) { + throw new BSONTypeError('Unsupported type BigInt, please use Decimal128'); + } else if (type === 'boolean') { + index = serializeBoolean(buffer, key, value, index); + } else if (value instanceof Date || isDate(value)) { + index = serializeDate(buffer, key, value, index); + } else if (value === null || (value === undefined && ignoreUndefined === false)) { + index = serializeNull(buffer, key, value, index); + } else if (value['_bsontype'] === 'ObjectId' || value['_bsontype'] === 'ObjectID') { + index = serializeObjectId(buffer, key, value, index); + } else if (isUint8Array(value)) { + index = serializeBuffer(buffer, key, value, index); + } else if (value instanceof RegExp || isRegExp(value)) { + index = serializeRegExp(buffer, key, value, index); + } else if (type === 'object' && value['_bsontype'] == null) { + index = serializeObject( + buffer, + key, + value, + index, + checkKeys, + depth, + serializeFunctions, + ignoreUndefined, + false, + path + ); + } else if (type === 'object' && value['_bsontype'] === 'Decimal128') { + index = serializeDecimal128(buffer, key, value, index); + } else if (value['_bsontype'] === 'Long' || value['_bsontype'] === 'Timestamp') { + index = serializeLong(buffer, key, value, index); + } else if (value['_bsontype'] === 'Double') { + index = serializeDouble(buffer, key, value, index); + } else if (value['_bsontype'] === 'Code') { + index = serializeCode( + buffer, + key, + value, + index, + checkKeys, + depth, + serializeFunctions, + ignoreUndefined + ); + } else if (typeof value === 'function' && serializeFunctions) { + index = serializeFunction(buffer, key, value, index, checkKeys, depth, serializeFunctions); + } else if (value['_bsontype'] === 'Binary') { + index = serializeBinary(buffer, key, value, index); + } else if (value['_bsontype'] === 'Symbol') { + index = serializeSymbol(buffer, key, value, index); + } else if (value['_bsontype'] === 'DBRef') { + index = serializeDBRef(buffer, key, value, index, depth, serializeFunctions); + } else if (value['_bsontype'] === 'BSONRegExp') { + index = serializeBSONRegExp(buffer, key, value, index); + } else if (value['_bsontype'] === 'Int32') { + index = serializeInt32(buffer, key, value, index); + } else if (value['_bsontype'] === 'MinKey' || value['_bsontype'] === 'MaxKey') { + index = serializeMinMax(buffer, key, value, index); + } else if (typeof value['_bsontype'] !== 'undefined') { + throw new BSONTypeError(`Unrecognized or invalid _bsontype: ${String(value['_bsontype'])}`); + } + } + } else { + if (typeof object?.toBSON === 'function') { + // Provided a custom serialization method + object = object.toBSON(); + if (object != null && typeof object !== 'object') { + throw new BSONTypeError('toBSON function did not return an object'); + } + } + + // Iterate over all the keys + for (const key in object) { + let value = object[key]; + // Is there an override value + if (typeof value?.toBSON === 'function') { + value = value.toBSON(); + } + + // Check the type of the value + const type = typeof value; + + // Check the key and throw error if it's illegal + if (typeof key === 'string' && !ignoreKeys.has(key)) { + if (key.match(regexp) != null) { + // The BSON spec doesn't allow keys with null bytes because keys are + // null-terminated. + throw Error('key ' + key + ' must not contain null bytes'); + } + + if (checkKeys) { + if ('$' === key[0]) { + throw Error('key ' + key + " must not start with '$'"); + } else if (~key.indexOf('.')) { + throw Error('key ' + key + " must not contain '.'"); + } + } + } + + if (type === 'string') { + index = serializeString(buffer, key, value, index); + } else if (type === 'number') { + index = serializeNumber(buffer, key, value, index); + } else if (type === 'bigint') { + throw new BSONTypeError('Unsupported type BigInt, please use Decimal128'); + } else if (type === 'boolean') { + index = serializeBoolean(buffer, key, value, index); + } else if (value instanceof Date || isDate(value)) { + index = serializeDate(buffer, key, value, index); + } else if (value === undefined) { + if (ignoreUndefined === false) index = serializeNull(buffer, key, value, index); + } else if (value === null) { + index = serializeNull(buffer, key, value, index); + } else if (value['_bsontype'] === 'ObjectId' || value['_bsontype'] === 'ObjectID') { + index = serializeObjectId(buffer, key, value, index); + } else if (isUint8Array(value)) { + index = serializeBuffer(buffer, key, value, index); + } else if (value instanceof RegExp || isRegExp(value)) { + index = serializeRegExp(buffer, key, value, index); + } else if (type === 'object' && value['_bsontype'] == null) { + index = serializeObject( + buffer, + key, + value, + index, + checkKeys, + depth, + serializeFunctions, + ignoreUndefined, + false, + path + ); + } else if (type === 'object' && value['_bsontype'] === 'Decimal128') { + index = serializeDecimal128(buffer, key, value, index); + } else if (value['_bsontype'] === 'Long' || value['_bsontype'] === 'Timestamp') { + index = serializeLong(buffer, key, value, index); + } else if (value['_bsontype'] === 'Double') { + index = serializeDouble(buffer, key, value, index); + } else if (value['_bsontype'] === 'Code') { + index = serializeCode( + buffer, + key, + value, + index, + checkKeys, + depth, + serializeFunctions, + ignoreUndefined + ); + } else if (typeof value === 'function' && serializeFunctions) { + index = serializeFunction(buffer, key, value, index, checkKeys, depth, serializeFunctions); + } else if (value['_bsontype'] === 'Binary') { + index = serializeBinary(buffer, key, value, index); + } else if (value['_bsontype'] === 'Symbol') { + index = serializeSymbol(buffer, key, value, index); + } else if (value['_bsontype'] === 'DBRef') { + index = serializeDBRef(buffer, key, value, index, depth, serializeFunctions); + } else if (value['_bsontype'] === 'BSONRegExp') { + index = serializeBSONRegExp(buffer, key, value, index); + } else if (value['_bsontype'] === 'Int32') { + index = serializeInt32(buffer, key, value, index); + } else if (value['_bsontype'] === 'MinKey' || value['_bsontype'] === 'MaxKey') { + index = serializeMinMax(buffer, key, value, index); + } else if (typeof value['_bsontype'] !== 'undefined') { + throw new BSONTypeError(`Unrecognized or invalid _bsontype: ${String(value['_bsontype'])}`); + } + } + } + + // Remove the path + path.pop(); + + // Final padding byte for object + buffer[index++] = 0x00; + + // Final size + const size = index - startingIndex; + // Write the size of the object + buffer[startingIndex++] = size & 0xff; + buffer[startingIndex++] = (size >> 8) & 0xff; + buffer[startingIndex++] = (size >> 16) & 0xff; + buffer[startingIndex++] = (size >> 24) & 0xff; + return index; +} diff --git a/ts-ticket-office-service/node_modules/bson/src/parser/utils.ts b/ts-ticket-office-service/node_modules/bson/src/parser/utils.ts new file mode 100644 index 000000000..abf935df5 --- /dev/null +++ b/ts-ticket-office-service/node_modules/bson/src/parser/utils.ts @@ -0,0 +1,127 @@ +import { Buffer } from 'buffer'; +import { getGlobal } from '../utils/global'; + +type RandomBytesFunction = (size: number) => Uint8Array; + +/** + * Normalizes our expected stringified form of a function across versions of node + * @param fn - The function to stringify + */ +export function normalizedFunctionString(fn: Function): string { + return fn.toString().replace('function(', 'function ('); +} + +function isReactNative() { + const g = getGlobal<{ navigator?: { product?: string } }>(); + return typeof g.navigator === 'object' && g.navigator.product === 'ReactNative'; +} + +const insecureRandomBytes: RandomBytesFunction = function insecureRandomBytes(size: number) { + const insecureWarning = isReactNative() + ? 'BSON: For React Native please polyfill crypto.getRandomValues, e.g. using: https://www.npmjs.com/package/react-native-get-random-values.' + : 'BSON: No cryptographic implementation for random bytes present, falling back to a less secure implementation.'; + console.warn(insecureWarning); + + const result = Buffer.alloc(size); + for (let i = 0; i < size; ++i) result[i] = Math.floor(Math.random() * 256); + return result; +}; + +/* We do not want to have to include DOM types just for this check */ +// eslint-disable-next-line @typescript-eslint/no-explicit-any +declare let window: any; +declare let require: Function; +// eslint-disable-next-line @typescript-eslint/no-explicit-any +declare let global: any; +// eslint-disable-next-line @typescript-eslint/no-explicit-any +declare let process: any; // Used by @rollup/plugin-replace + +const detectRandomBytes = (): RandomBytesFunction => { + if (process.browser) { + if (typeof window !== 'undefined') { + // browser crypto implementation(s) + const target = window.crypto || window.msCrypto; // allow for IE11 + if (target && target.getRandomValues) { + return size => target.getRandomValues(Buffer.alloc(size)); + } + } + + if (typeof global !== 'undefined' && global.crypto && global.crypto.getRandomValues) { + // allow for RN packages such as https://www.npmjs.com/package/react-native-get-random-values to populate global + return size => global.crypto.getRandomValues(Buffer.alloc(size)); + } + + return insecureRandomBytes; + } else { + let requiredRandomBytes: RandomBytesFunction | null | undefined; + try { + requiredRandomBytes = require('crypto').randomBytes; + } catch (e) { + // keep the fallback + } + + // NOTE: in transpiled cases the above require might return null/undefined + + return requiredRandomBytes || insecureRandomBytes; + } +}; + +export const randomBytes = detectRandomBytes(); + +export function isAnyArrayBuffer(value: unknown): value is ArrayBuffer { + return ['[object ArrayBuffer]', '[object SharedArrayBuffer]'].includes( + Object.prototype.toString.call(value) + ); +} + +export function isUint8Array(value: unknown): value is Uint8Array { + return Object.prototype.toString.call(value) === '[object Uint8Array]'; +} + +export function isBigInt64Array(value: unknown): value is BigInt64Array { + return Object.prototype.toString.call(value) === '[object BigInt64Array]'; +} + +export function isBigUInt64Array(value: unknown): value is BigUint64Array { + return Object.prototype.toString.call(value) === '[object BigUint64Array]'; +} + +export function isRegExp(d: unknown): d is RegExp { + return Object.prototype.toString.call(d) === '[object RegExp]'; +} + +export function isMap(d: unknown): d is Map { + return Object.prototype.toString.call(d) === '[object Map]'; +} + +/** Call to check if your environment has `Buffer` */ +export function haveBuffer(): boolean { + return typeof global !== 'undefined' && typeof global.Buffer !== 'undefined'; +} + +// To ensure that 0.4 of node works correctly +export function isDate(d: unknown): d is Date { + return isObjectLike(d) && Object.prototype.toString.call(d) === '[object Date]'; +} + +/** + * @internal + * this is to solve the `'someKey' in x` problem where x is unknown. + * https://github.com/typescript-eslint/typescript-eslint/issues/1071#issuecomment-541955753 + */ +export function isObjectLike(candidate: unknown): candidate is Record { + return typeof candidate === 'object' && candidate !== null; +} + +declare let console: { warn(...message: unknown[]): void }; +export function deprecate(fn: T, message: string): T { + let warned = false; + function deprecated(this: unknown, ...args: unknown[]) { + if (!warned) { + console.warn(message); + warned = true; + } + return fn.apply(this, args); + } + return deprecated as unknown as T; +} diff --git a/ts-ticket-office-service/node_modules/bson/src/regexp.ts b/ts-ticket-office-service/node_modules/bson/src/regexp.ts new file mode 100644 index 000000000..efd56280a --- /dev/null +++ b/ts-ticket-office-service/node_modules/bson/src/regexp.ts @@ -0,0 +1,105 @@ +import { BSONError, BSONTypeError } from './error'; +import type { EJSONOptions } from './extended_json'; + +function alphabetize(str: string): string { + return str.split('').sort().join(''); +} + +/** @public */ +export interface BSONRegExpExtendedLegacy { + $regex: string | BSONRegExp; + $options: string; +} + +/** @public */ +export interface BSONRegExpExtended { + $regularExpression: { + pattern: string; + options: string; + }; +} + +/** + * A class representation of the BSON RegExp type. + * @public + * @category BSONType + */ +export class BSONRegExp { + _bsontype!: 'BSONRegExp'; + + pattern!: string; + options!: string; + /** + * @param pattern - The regular expression pattern to match + * @param options - The regular expression options + */ + constructor(pattern: string, options?: string) { + if (!(this instanceof BSONRegExp)) return new BSONRegExp(pattern, options); + + this.pattern = pattern; + this.options = alphabetize(options ?? ''); + + if (this.pattern.indexOf('\x00') !== -1) { + throw new BSONError( + `BSON Regex patterns cannot contain null bytes, found: ${JSON.stringify(this.pattern)}` + ); + } + if (this.options.indexOf('\x00') !== -1) { + throw new BSONError( + `BSON Regex options cannot contain null bytes, found: ${JSON.stringify(this.options)}` + ); + } + + // Validate options + for (let i = 0; i < this.options.length; i++) { + if ( + !( + this.options[i] === 'i' || + this.options[i] === 'm' || + this.options[i] === 'x' || + this.options[i] === 'l' || + this.options[i] === 's' || + this.options[i] === 'u' + ) + ) { + throw new BSONError(`The regular expression option [${this.options[i]}] is not supported`); + } + } + } + + static parseOptions(options?: string): string { + return options ? options.split('').sort().join('') : ''; + } + + /** @internal */ + toExtendedJSON(options?: EJSONOptions): BSONRegExpExtendedLegacy | BSONRegExpExtended { + options = options || {}; + if (options.legacy) { + return { $regex: this.pattern, $options: this.options }; + } + return { $regularExpression: { pattern: this.pattern, options: this.options } }; + } + + /** @internal */ + static fromExtendedJSON(doc: BSONRegExpExtendedLegacy | BSONRegExpExtended): BSONRegExp { + if ('$regex' in doc) { + if (typeof doc.$regex !== 'string') { + // This is for $regex query operators that have extended json values. + if (doc.$regex._bsontype === 'BSONRegExp') { + return doc as unknown as BSONRegExp; + } + } else { + return new BSONRegExp(doc.$regex, BSONRegExp.parseOptions(doc.$options)); + } + } + if ('$regularExpression' in doc) { + return new BSONRegExp( + doc.$regularExpression.pattern, + BSONRegExp.parseOptions(doc.$regularExpression.options) + ); + } + throw new BSONTypeError(`Unexpected BSONRegExp EJSON object form: ${JSON.stringify(doc)}`); + } +} + +Object.defineProperty(BSONRegExp.prototype, '_bsontype', { value: 'BSONRegExp' }); diff --git a/ts-ticket-office-service/node_modules/bson/src/symbol.ts b/ts-ticket-office-service/node_modules/bson/src/symbol.ts new file mode 100644 index 000000000..1e82fc1c3 --- /dev/null +++ b/ts-ticket-office-service/node_modules/bson/src/symbol.ts @@ -0,0 +1,58 @@ +/** @public */ +export interface BSONSymbolExtended { + $symbol: string; +} + +/** + * A class representation of the BSON Symbol type. + * @public + * @category BSONType + */ +export class BSONSymbol { + _bsontype!: 'Symbol'; + + value!: string; + /** + * @param value - the string representing the symbol. + */ + constructor(value: string) { + if (!(this instanceof BSONSymbol)) return new BSONSymbol(value); + + this.value = value; + } + + /** Access the wrapped string value. */ + valueOf(): string { + return this.value; + } + + toString(): string { + return this.value; + } + + /** @internal */ + inspect(): string { + return `new BSONSymbol("${this.value}")`; + } + + toJSON(): string { + return this.value; + } + + /** @internal */ + toExtendedJSON(): BSONSymbolExtended { + return { $symbol: this.value }; + } + + /** @internal */ + static fromExtendedJSON(doc: BSONSymbolExtended): BSONSymbol { + return new BSONSymbol(doc.$symbol); + } + + /** @internal */ + [Symbol.for('nodejs.util.inspect.custom')](): string { + return this.inspect(); + } +} + +Object.defineProperty(BSONSymbol.prototype, '_bsontype', { value: 'Symbol' }); diff --git a/ts-ticket-office-service/node_modules/bson/src/timestamp.ts b/ts-ticket-office-service/node_modules/bson/src/timestamp.ts new file mode 100644 index 000000000..4c4b7e74c --- /dev/null +++ b/ts-ticket-office-service/node_modules/bson/src/timestamp.ts @@ -0,0 +1,119 @@ +import { Long } from './long'; +import { isObjectLike } from './parser/utils'; + +/** @public */ +export type TimestampOverrides = '_bsontype' | 'toExtendedJSON' | 'fromExtendedJSON' | 'inspect'; +/** @public */ +export type LongWithoutOverrides = new (low: unknown, high?: number, unsigned?: boolean) => { + [P in Exclude]: Long[P]; +}; +/** @public */ +export const LongWithoutOverridesClass: LongWithoutOverrides = + Long as unknown as LongWithoutOverrides; + +/** @public */ +export interface TimestampExtended { + $timestamp: { + t: number; + i: number; + }; +} + +/** + * @public + * @category BSONType + * */ +export class Timestamp extends LongWithoutOverridesClass { + _bsontype!: 'Timestamp'; + + static readonly MAX_VALUE = Long.MAX_UNSIGNED_VALUE; + + /** + * @param low - A 64-bit Long representing the Timestamp. + */ + constructor(long: Long); + /** + * @param value - A pair of two values indicating timestamp and increment. + */ + constructor(value: { t: number; i: number }); + /** + * @param low - the low (signed) 32 bits of the Timestamp. + * @param high - the high (signed) 32 bits of the Timestamp. + * @deprecated Please use `Timestamp({ t: high, i: low })` or `Timestamp(Long(low, high))` instead. + */ + constructor(low: number, high: number); + constructor(low: number | Long | { t: number; i: number }, high?: number) { + // eslint-disable-next-line @typescript-eslint/ban-ts-comment + // @ts-expect-error + if (!(this instanceof Timestamp)) return new Timestamp(low, high); + + if (Long.isLong(low)) { + super(low.low, low.high, true); + } else if (isObjectLike(low) && typeof low.t !== 'undefined' && typeof low.i !== 'undefined') { + super(low.i, low.t, true); + } else { + super(low, high, true); + } + Object.defineProperty(this, '_bsontype', { + value: 'Timestamp', + writable: false, + configurable: false, + enumerable: false + }); + } + + toJSON(): { $timestamp: string } { + return { + $timestamp: this.toString() + }; + } + + /** Returns a Timestamp represented by the given (32-bit) integer value. */ + static fromInt(value: number): Timestamp { + return new Timestamp(Long.fromInt(value, true)); + } + + /** Returns a Timestamp representing the given number value, provided that it is a finite number. Otherwise, zero is returned. */ + static fromNumber(value: number): Timestamp { + return new Timestamp(Long.fromNumber(value, true)); + } + + /** + * Returns a Timestamp for the given high and low bits. Each is assumed to use 32 bits. + * + * @param lowBits - the low 32-bits. + * @param highBits - the high 32-bits. + */ + static fromBits(lowBits: number, highBits: number): Timestamp { + return new Timestamp(lowBits, highBits); + } + + /** + * Returns a Timestamp from the given string, optionally using the given radix. + * + * @param str - the textual representation of the Timestamp. + * @param optRadix - the radix in which the text is written. + */ + static fromString(str: string, optRadix: number): Timestamp { + return new Timestamp(Long.fromString(str, true, optRadix)); + } + + /** @internal */ + toExtendedJSON(): TimestampExtended { + return { $timestamp: { t: this.high >>> 0, i: this.low >>> 0 } }; + } + + /** @internal */ + static fromExtendedJSON(doc: TimestampExtended): Timestamp { + return new Timestamp(doc.$timestamp); + } + + /** @internal */ + [Symbol.for('nodejs.util.inspect.custom')](): string { + return this.inspect(); + } + + inspect(): string { + return `new Timestamp({ t: ${this.getHighBits()}, i: ${this.getLowBits()} })`; + } +} diff --git a/ts-ticket-office-service/node_modules/bson/src/utils/global.ts b/ts-ticket-office-service/node_modules/bson/src/utils/global.ts new file mode 100644 index 000000000..3e45ffb8b --- /dev/null +++ b/ts-ticket-office-service/node_modules/bson/src/utils/global.ts @@ -0,0 +1,22 @@ +/* eslint-disable @typescript-eslint/no-explicit-any */ +/* We do not want to have to include DOM types just for this check */ +declare const window: unknown; +declare const self: unknown; +declare const global: unknown; + +function checkForMath(potentialGlobal: any) { + // eslint-disable-next-line eqeqeq + return potentialGlobal && potentialGlobal.Math == Math && potentialGlobal; +} + +// https://github.com/zloirock/core-js/issues/86#issuecomment-115759028 +export function getGlobal>(): T { + return ( + checkForMath(typeof globalThis === 'object' && globalThis) || + checkForMath(typeof window === 'object' && window) || + checkForMath(typeof self === 'object' && self) || + checkForMath(typeof global === 'object' && global) || + // eslint-disable-next-line @typescript-eslint/no-implied-eval + Function('return this')() + ); +} diff --git a/ts-ticket-office-service/node_modules/bson/src/uuid.ts b/ts-ticket-office-service/node_modules/bson/src/uuid.ts new file mode 100644 index 000000000..625e57dea --- /dev/null +++ b/ts-ticket-office-service/node_modules/bson/src/uuid.ts @@ -0,0 +1,209 @@ +import { Buffer } from 'buffer'; +import { ensureBuffer } from './ensure_buffer'; +import { Binary } from './binary'; +import { bufferToUuidHexString, uuidHexStringToBuffer, uuidValidateString } from './uuid_utils'; +import { isUint8Array, randomBytes } from './parser/utils'; +import { BSONTypeError } from './error'; + +/** @public */ +export type UUIDExtended = { + $uuid: string; +}; + +const BYTE_LENGTH = 16; + +const kId = Symbol('id'); + +/** + * A class representation of the BSON UUID type. + * @public + */ +export class UUID { + // This property is not meant for direct serialization, but simply an indication that this type originates from this package. + _bsontype!: 'UUID'; + + static cacheHexString: boolean; + + /** UUID Bytes @internal */ + private [kId]!: Buffer; + /** UUID hexString cache @internal */ + private __id?: string; + + /** + * Create an UUID type + * + * @param input - Can be a 32 or 36 character hex string (dashes excluded/included) or a 16 byte binary Buffer. + */ + constructor(input?: string | Buffer | UUID) { + if (typeof input === 'undefined') { + // The most common use case (blank id, new UUID() instance) + this.id = UUID.generate(); + } else if (input instanceof UUID) { + this[kId] = Buffer.from(input.id); + this.__id = input.__id; + } else if (ArrayBuffer.isView(input) && input.byteLength === BYTE_LENGTH) { + this.id = ensureBuffer(input); + } else if (typeof input === 'string') { + this.id = uuidHexStringToBuffer(input); + } else { + throw new BSONTypeError( + 'Argument passed in UUID constructor must be a UUID, a 16 byte Buffer or a 32/36 character hex string (dashes excluded/included, format: xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx).' + ); + } + } + + /** + * The UUID bytes + * @readonly + */ + get id(): Buffer { + return this[kId]; + } + + set id(value: Buffer) { + this[kId] = value; + + if (UUID.cacheHexString) { + this.__id = bufferToUuidHexString(value); + } + } + + /** + * Generate a 16 byte uuid v4 buffer used in UUIDs + */ + + /** + * Returns the UUID id as a 32 or 36 character hex string representation, excluding/including dashes (defaults to 36 character dash separated) + * @param includeDashes - should the string exclude dash-separators. + * */ + toHexString(includeDashes = true): string { + if (UUID.cacheHexString && this.__id) { + return this.__id; + } + + const uuidHexString = bufferToUuidHexString(this.id, includeDashes); + + if (UUID.cacheHexString) { + this.__id = uuidHexString; + } + + return uuidHexString; + } + + /** + * Converts the id into a 36 character (dashes included) hex string, unless a encoding is specified. + */ + toString(encoding?: string): string { + return encoding ? this.id.toString(encoding) : this.toHexString(); + } + + /** + * Converts the id into its JSON string representation. + * A 36 character (dashes included) hex string in the format: xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx + */ + toJSON(): string { + return this.toHexString(); + } + + /** + * Compares the equality of this UUID with `otherID`. + * + * @param otherId - UUID instance to compare against. + */ + equals(otherId: string | Buffer | UUID): boolean { + if (!otherId) { + return false; + } + + if (otherId instanceof UUID) { + return otherId.id.equals(this.id); + } + + try { + return new UUID(otherId).id.equals(this.id); + } catch { + return false; + } + } + + /** + * Creates a Binary instance from the current UUID. + */ + toBinary(): Binary { + return new Binary(this.id, Binary.SUBTYPE_UUID); + } + + /** + * Generates a populated buffer containing a v4 uuid + */ + static generate(): Buffer { + const bytes = randomBytes(BYTE_LENGTH); + + // Per 4.4, set bits for version and `clock_seq_hi_and_reserved` + // Kindly borrowed from https://github.com/uuidjs/uuid/blob/master/src/v4.js + bytes[6] = (bytes[6] & 0x0f) | 0x40; + bytes[8] = (bytes[8] & 0x3f) | 0x80; + + return Buffer.from(bytes); + } + + /** + * Checks if a value is a valid bson UUID + * @param input - UUID, string or Buffer to validate. + */ + static isValid(input: string | Buffer | UUID): boolean { + if (!input) { + return false; + } + + if (input instanceof UUID) { + return true; + } + + if (typeof input === 'string') { + return uuidValidateString(input); + } + + if (isUint8Array(input)) { + // check for length & uuid version (https://tools.ietf.org/html/rfc4122#section-4.1.3) + if (input.length !== BYTE_LENGTH) { + return false; + } + + try { + // get this byte as hex: xxxxxxxx-xxxx-XXxx-xxxx-xxxxxxxxxxxx + // check first part as uuid version: xxxxxxxx-xxxx-Xxxx-xxxx-xxxxxxxxxxxx + return parseInt(input[6].toString(16)[0], 10) === Binary.SUBTYPE_UUID; + } catch { + return false; + } + } + + return false; + } + + /** + * Creates an UUID from a hex string representation of an UUID. + * @param hexString - 32 or 36 character hex string (dashes excluded/included). + */ + static createFromHexString(hexString: string): UUID { + const buffer = uuidHexStringToBuffer(hexString); + return new UUID(buffer); + } + + /** + * Converts to a string representation of this Id. + * + * @returns return the 36 character hex string representation. + * @internal + */ + [Symbol.for('nodejs.util.inspect.custom')](): string { + return this.inspect(); + } + + inspect(): string { + return `new UUID("${this.toHexString()}")`; + } +} + +Object.defineProperty(UUID.prototype, '_bsontype', { value: 'UUID' }); diff --git a/ts-ticket-office-service/node_modules/bson/src/uuid_utils.ts b/ts-ticket-office-service/node_modules/bson/src/uuid_utils.ts new file mode 100644 index 000000000..f37b06592 --- /dev/null +++ b/ts-ticket-office-service/node_modules/bson/src/uuid_utils.ts @@ -0,0 +1,33 @@ +import { Buffer } from 'buffer'; +import { BSONTypeError } from './error'; + +// Validation regex for v4 uuid (validates with or without dashes) +const VALIDATION_REGEX = + /^(?:[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}|[0-9a-f]{12}4[0-9a-f]{3}[89ab][0-9a-f]{15})$/i; + +export const uuidValidateString = (str: string): boolean => + typeof str === 'string' && VALIDATION_REGEX.test(str); + +export const uuidHexStringToBuffer = (hexString: string): Buffer => { + if (!uuidValidateString(hexString)) { + throw new BSONTypeError( + 'UUID string representations must be a 32 or 36 character hex string (dashes excluded/included). Format: "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" or "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx".' + ); + } + + const sanitizedHexString = hexString.replace(/-/g, ''); + return Buffer.from(sanitizedHexString, 'hex'); +}; + +export const bufferToUuidHexString = (buffer: Buffer, includeDashes = true): string => + includeDashes + ? buffer.toString('hex', 0, 4) + + '-' + + buffer.toString('hex', 4, 6) + + '-' + + buffer.toString('hex', 6, 8) + + '-' + + buffer.toString('hex', 8, 10) + + '-' + + buffer.toString('hex', 10, 16) + : buffer.toString('hex'); diff --git a/ts-ticket-office-service/node_modules/bson/src/validate_utf8.ts b/ts-ticket-office-service/node_modules/bson/src/validate_utf8.ts new file mode 100644 index 000000000..e1da934c6 --- /dev/null +++ b/ts-ticket-office-service/node_modules/bson/src/validate_utf8.ts @@ -0,0 +1,47 @@ +const FIRST_BIT = 0x80; +const FIRST_TWO_BITS = 0xc0; +const FIRST_THREE_BITS = 0xe0; +const FIRST_FOUR_BITS = 0xf0; +const FIRST_FIVE_BITS = 0xf8; + +const TWO_BIT_CHAR = 0xc0; +const THREE_BIT_CHAR = 0xe0; +const FOUR_BIT_CHAR = 0xf0; +const CONTINUING_CHAR = 0x80; + +/** + * Determines if the passed in bytes are valid utf8 + * @param bytes - An array of 8-bit bytes. Must be indexable and have length property + * @param start - The index to start validating + * @param end - The index to end validating + */ +export function validateUtf8( + bytes: { [index: number]: number }, + start: number, + end: number +): boolean { + let continuation = 0; + + for (let i = start; i < end; i += 1) { + const byte = bytes[i]; + + if (continuation) { + if ((byte & FIRST_TWO_BITS) !== CONTINUING_CHAR) { + return false; + } + continuation -= 1; + } else if (byte & FIRST_BIT) { + if ((byte & FIRST_THREE_BITS) === TWO_BIT_CHAR) { + continuation = 1; + } else if ((byte & FIRST_FOUR_BITS) === THREE_BIT_CHAR) { + continuation = 2; + } else if ((byte & FIRST_FIVE_BITS) === FOUR_BIT_CHAR) { + continuation = 3; + } else { + return false; + } + } + } + + return !continuation; +} diff --git a/ts-ticket-office-service/node_modules/buffer-shims/index.js b/ts-ticket-office-service/node_modules/buffer-shims/index.js deleted file mode 100644 index 1cab4c05e..000000000 --- a/ts-ticket-office-service/node_modules/buffer-shims/index.js +++ /dev/null @@ -1,108 +0,0 @@ -'use strict'; - -var buffer = require('buffer'); -var Buffer = buffer.Buffer; -var SlowBuffer = buffer.SlowBuffer; -var MAX_LEN = buffer.kMaxLength || 2147483647; -exports.alloc = function alloc(size, fill, encoding) { - if (typeof Buffer.alloc === 'function') { - return Buffer.alloc(size, fill, encoding); - } - if (typeof encoding === 'number') { - throw new TypeError('encoding must not be number'); - } - if (typeof size !== 'number') { - throw new TypeError('size must be a number'); - } - if (size > MAX_LEN) { - throw new RangeError('size is too large'); - } - var enc = encoding; - var _fill = fill; - if (_fill === undefined) { - enc = undefined; - _fill = 0; - } - var buf = new Buffer(size); - if (typeof _fill === 'string') { - var fillBuf = new Buffer(_fill, enc); - var flen = fillBuf.length; - var i = -1; - while (++i < size) { - buf[i] = fillBuf[i % flen]; - } - } else { - buf.fill(_fill); - } - return buf; -} -exports.allocUnsafe = function allocUnsafe(size) { - if (typeof Buffer.allocUnsafe === 'function') { - return Buffer.allocUnsafe(size); - } - if (typeof size !== 'number') { - throw new TypeError('size must be a number'); - } - if (size > MAX_LEN) { - throw new RangeError('size is too large'); - } - return new Buffer(size); -} -exports.from = function from(value, encodingOrOffset, length) { - if (typeof Buffer.from === 'function' && (!global.Uint8Array || Uint8Array.from !== Buffer.from)) { - return Buffer.from(value, encodingOrOffset, length); - } - if (typeof value === 'number') { - throw new TypeError('"value" argument must not be a number'); - } - if (typeof value === 'string') { - return new Buffer(value, encodingOrOffset); - } - if (typeof ArrayBuffer !== 'undefined' && value instanceof ArrayBuffer) { - var offset = encodingOrOffset; - if (arguments.length === 1) { - return new Buffer(value); - } - if (typeof offset === 'undefined') { - offset = 0; - } - var len = length; - if (typeof len === 'undefined') { - len = value.byteLength - offset; - } - if (offset >= value.byteLength) { - throw new RangeError('\'offset\' is out of bounds'); - } - if (len > value.byteLength - offset) { - throw new RangeError('\'length\' is out of bounds'); - } - return new Buffer(value.slice(offset, offset + len)); - } - if (Buffer.isBuffer(value)) { - var out = new Buffer(value.length); - value.copy(out, 0, 0, value.length); - return out; - } - if (value) { - if (Array.isArray(value) || (typeof ArrayBuffer !== 'undefined' && value.buffer instanceof ArrayBuffer) || 'length' in value) { - return new Buffer(value); - } - if (value.type === 'Buffer' && Array.isArray(value.data)) { - return new Buffer(value.data); - } - } - - throw new TypeError('First argument must be a string, Buffer, ' + 'ArrayBuffer, Array, or array-like object.'); -} -exports.allocUnsafeSlow = function allocUnsafeSlow(size) { - if (typeof Buffer.allocUnsafeSlow === 'function') { - return Buffer.allocUnsafeSlow(size); - } - if (typeof size !== 'number') { - throw new TypeError('size must be a number'); - } - if (size >= MAX_LEN) { - throw new RangeError('size is too large'); - } - return new SlowBuffer(size); -} diff --git a/ts-ticket-office-service/node_modules/buffer-shims/package.json b/ts-ticket-office-service/node_modules/buffer-shims/package.json deleted file mode 100644 index 8869c82b6..000000000 --- a/ts-ticket-office-service/node_modules/buffer-shims/package.json +++ /dev/null @@ -1,85 +0,0 @@ -{ - "_args": [ - [ - { - "raw": "buffer-shims@~1.0.0", - "scope": null, - "escapedName": "buffer-shims", - "name": "buffer-shims", - "rawSpec": "~1.0.0", - "spec": ">=1.0.0 <1.1.0", - "type": "range" - }, - "F:\\gitwork\\workspace_microservices\\ts-ticket-office-service\\node_modules\\readable-stream" - ] - ], - "_from": "buffer-shims@>=1.0.0 <1.1.0", - "_id": "buffer-shims@1.0.0", - "_inCache": true, - "_location": "/buffer-shims", - "_nodeVersion": "5.11.0", - "_npmOperationalInternal": { - "host": "packages-16-east.internal.npmjs.com", - "tmp": "tmp/buffer-shims-1.0.0.tgz_1462560889323_0.8640750856138766" - }, - "_npmUser": { - "name": "cwmma", - "email": "calvin.metcalf@gmail.com" - }, - "_npmVersion": "3.8.6", - "_phantomChildren": {}, - "_requested": { - "raw": "buffer-shims@~1.0.0", - "scope": null, - "escapedName": "buffer-shims", - "name": "buffer-shims", - "rawSpec": "~1.0.0", - "spec": ">=1.0.0 <1.1.0", - "type": "range" - }, - "_requiredBy": [ - "/readable-stream" - ], - "_resolved": "https://registry.npmjs.org/buffer-shims/-/buffer-shims-1.0.0.tgz", - "_shasum": "9978ce317388c649ad8793028c3477ef044a8b51", - "_shrinkwrap": null, - "_spec": "buffer-shims@~1.0.0", - "_where": "F:\\gitwork\\workspace_microservices\\ts-ticket-office-service\\node_modules\\readable-stream", - "bugs": { - "url": "https://github.com/calvinmetcalf/buffer-shims/issues" - }, - "dependencies": {}, - "description": "some shims for node buffers", - "devDependencies": { - "tape": "^4.5.1" - }, - "directories": {}, - "dist": { - "shasum": "9978ce317388c649ad8793028c3477ef044a8b51", - "tarball": "https://registry.npmjs.org/buffer-shims/-/buffer-shims-1.0.0.tgz" - }, - "files": [ - "index.js" - ], - "gitHead": "ea89b3857ab5b8203957922a84e9a48cf4c47e0a", - "homepage": "https://github.com/calvinmetcalf/buffer-shims#readme", - "license": "MIT", - "main": "index.js", - "maintainers": [ - { - "name": "cwmma", - "email": "calvin.metcalf@gmail.com" - } - ], - "name": "buffer-shims", - "optionalDependencies": {}, - "readme": "ERROR: No README data found!", - "repository": { - "type": "git", - "url": "git+ssh://git@github.com/calvinmetcalf/buffer-shims.git" - }, - "scripts": { - "test": "tape test/*.js" - }, - "version": "1.0.0" -} diff --git a/ts-ticket-office-service/node_modules/buffer-shims/readme.md b/ts-ticket-office-service/node_modules/buffer-shims/readme.md deleted file mode 100644 index 7ea6475e2..000000000 --- a/ts-ticket-office-service/node_modules/buffer-shims/readme.md +++ /dev/null @@ -1,21 +0,0 @@ -buffer-shims -=== - -functions to make sure the new buffer methods work in older browsers. - -```js -var bufferShim = require('buffer-shims'); -bufferShim.from('foo'); -bufferShim.alloc(9, 'cafeface', 'hex'); -bufferShim.allocUnsafe(15); -bufferShim.allocUnsafeSlow(21); -``` - -should just use the original in newer nodes and on older nodes uses fallbacks. - -Known Issues -=== -- this does not patch the buffer object, only the constructor stuff -- it's actually a polyfill - -![](https://i.imgur.com/zxII3jJ.gif) diff --git a/ts-ticket-office-service/node_modules/buffer/AUTHORS.md b/ts-ticket-office-service/node_modules/buffer/AUTHORS.md new file mode 100644 index 000000000..22eb17129 --- /dev/null +++ b/ts-ticket-office-service/node_modules/buffer/AUTHORS.md @@ -0,0 +1,70 @@ +# Authors + +#### Ordered by first contribution. + +- Romain Beauxis (toots@rastageeks.org) +- Tobias Koppers (tobias.koppers@googlemail.com) +- Janus (ysangkok@gmail.com) +- Rainer Dreyer (rdrey1@gmail.com) +- Tõnis Tiigi (tonistiigi@gmail.com) +- James Halliday (mail@substack.net) +- Michael Williamson (mike@zwobble.org) +- elliottcable (github@elliottcable.name) +- rafael (rvalle@livelens.net) +- Andrew Kelley (superjoe30@gmail.com) +- Andreas Madsen (amwebdk@gmail.com) +- Mike Brevoort (mike.brevoort@pearson.com) +- Brian White (mscdex@mscdex.net) +- Feross Aboukhadijeh (feross@feross.org) +- Ruben Verborgh (ruben@verborgh.org) +- eliang (eliang.cs@gmail.com) +- Jesse Tane (jesse.tane@gmail.com) +- Alfonso Boza (alfonso@cloud.com) +- Mathias Buus (mathiasbuus@gmail.com) +- Devon Govett (devongovett@gmail.com) +- Daniel Cousens (github@dcousens.com) +- Joseph Dykstra (josephdykstra@gmail.com) +- Parsha Pourkhomami (parshap+git@gmail.com) +- Damjan Košir (damjan.kosir@gmail.com) +- daverayment (dave.rayment@gmail.com) +- kawanet (u-suke@kawa.net) +- Linus Unnebäck (linus@folkdatorn.se) +- Nolan Lawson (nolan.lawson@gmail.com) +- Calvin Metcalf (calvin.metcalf@gmail.com) +- Koki Takahashi (hakatasiloving@gmail.com) +- Guy Bedford (guybedford@gmail.com) +- Jan Schär (jscissr@gmail.com) +- RaulTsc (tomescu.raul@gmail.com) +- Matthieu Monsch (monsch@alum.mit.edu) +- Dan Ehrenberg (littledan@chromium.org) +- Kirill Fomichev (fanatid@ya.ru) +- Yusuke Kawasaki (u-suke@kawa.net) +- DC (dcposch@dcpos.ch) +- John-David Dalton (john.david.dalton@gmail.com) +- adventure-yunfei (adventure030@gmail.com) +- Emil Bay (github@tixz.dk) +- Sam Sudar (sudar.sam@gmail.com) +- Volker Mische (volker.mische@gmail.com) +- David Walton (support@geekstocks.com) +- Сковорода Никита Андреевич (chalkerx@gmail.com) +- greenkeeper[bot] (greenkeeper[bot]@users.noreply.github.com) +- ukstv (sergey.ukustov@machinomy.com) +- Renée Kooi (renee@kooi.me) +- ranbochen (ranbochen@qq.com) +- Vladimir Borovik (bobahbdb@gmail.com) +- greenkeeper[bot] (23040076+greenkeeper[bot]@users.noreply.github.com) +- kumavis (aaron@kumavis.me) +- Sergey Ukustov (sergey.ukustov@machinomy.com) +- Fei Liu (liu.feiwood@gmail.com) +- Blaine Bublitz (blaine.bublitz@gmail.com) +- clement (clement@seald.io) +- Koushik Dutta (koushd@gmail.com) +- Jordan Harband (ljharb@gmail.com) +- Niklas Mischkulnig (mischnic@users.noreply.github.com) +- Nikolai Vavilov (vvnicholas@gmail.com) +- Fedor Nezhivoi (gyzerok@users.noreply.github.com) +- Peter Newman (peternewman@users.noreply.github.com) +- mathmakgakpak (44949126+mathmakgakpak@users.noreply.github.com) +- jkkang (jkkang@smartauth.kr) + +#### Generated by bin/update-authors.sh. diff --git a/ts-ticket-office-service/node_modules/buffer/LICENSE b/ts-ticket-office-service/node_modules/buffer/LICENSE new file mode 100644 index 000000000..d6bf75dcf --- /dev/null +++ b/ts-ticket-office-service/node_modules/buffer/LICENSE @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) Feross Aboukhadijeh, and other contributors. + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. diff --git a/ts-ticket-office-service/node_modules/buffer/README.md b/ts-ticket-office-service/node_modules/buffer/README.md new file mode 100644 index 000000000..9a23d7cfa --- /dev/null +++ b/ts-ticket-office-service/node_modules/buffer/README.md @@ -0,0 +1,410 @@ +# buffer [![travis][travis-image]][travis-url] [![npm][npm-image]][npm-url] [![downloads][downloads-image]][downloads-url] [![javascript style guide][standard-image]][standard-url] + +[travis-image]: https://img.shields.io/travis/feross/buffer/master.svg +[travis-url]: https://travis-ci.org/feross/buffer +[npm-image]: https://img.shields.io/npm/v/buffer.svg +[npm-url]: https://npmjs.org/package/buffer +[downloads-image]: https://img.shields.io/npm/dm/buffer.svg +[downloads-url]: https://npmjs.org/package/buffer +[standard-image]: https://img.shields.io/badge/code_style-standard-brightgreen.svg +[standard-url]: https://standardjs.com + +#### The buffer module from [node.js](https://nodejs.org/), for the browser. + +[![saucelabs][saucelabs-image]][saucelabs-url] + +[saucelabs-image]: https://saucelabs.com/browser-matrix/buffer.svg +[saucelabs-url]: https://saucelabs.com/u/buffer + +With [browserify](http://browserify.org), simply `require('buffer')` or use the `Buffer` global and you will get this module. + +The goal is to provide an API that is 100% identical to +[node's Buffer API](https://nodejs.org/api/buffer.html). Read the +[official docs](https://nodejs.org/api/buffer.html) for the full list of properties, +instance methods, and class methods that are supported. + +## features + +- Manipulate binary data like a boss, in all browsers! +- Super fast. Backed by Typed Arrays (`Uint8Array`/`ArrayBuffer`, not `Object`) +- Extremely small bundle size (**6.75KB minified + gzipped**, 51.9KB with comments) +- Excellent browser support (Chrome, Firefox, Edge, Safari 9+, IE 11, iOS 9+, Android, etc.) +- Preserves Node API exactly, with one minor difference (see below) +- Square-bracket `buf[4]` notation works! +- Does not modify any browser prototypes or put anything on `window` +- Comprehensive test suite (including all buffer tests from node.js core) + +## install + +To use this module directly (without browserify), install it: + +```bash +npm install buffer +``` + +This module was previously called **native-buffer-browserify**, but please use **buffer** +from now on. + +If you do not use a bundler, you can use the [standalone script](https://bundle.run/buffer). + +## usage + +The module's API is identical to node's `Buffer` API. Read the +[official docs](https://nodejs.org/api/buffer.html) for the full list of properties, +instance methods, and class methods that are supported. + +As mentioned above, `require('buffer')` or use the `Buffer` global with +[browserify](http://browserify.org) and this module will automatically be included +in your bundle. Almost any npm module will work in the browser, even if it assumes that +the node `Buffer` API will be available. + +To depend on this module explicitly (without browserify), require it like this: + +```js +var Buffer = require('buffer/').Buffer // note: the trailing slash is important! +``` + +To require this module explicitly, use `require('buffer/')` which tells the node.js module +lookup algorithm (also used by browserify) to use the **npm module** named `buffer` +instead of the **node.js core** module named `buffer`! + + +## how does it work? + +The Buffer constructor returns instances of `Uint8Array` that have their prototype +changed to `Buffer.prototype`. Furthermore, `Buffer` is a subclass of `Uint8Array`, +so the returned instances will have all the node `Buffer` methods and the +`Uint8Array` methods. Square bracket notation works as expected -- it returns a +single octet. + +The `Uint8Array` prototype remains unmodified. + + +## tracking the latest node api + +This module tracks the Buffer API in the latest (unstable) version of node.js. The Buffer +API is considered **stable** in the +[node stability index](https://nodejs.org/docs/latest/api/documentation.html#documentation_stability_index), +so it is unlikely that there will ever be breaking changes. +Nonetheless, when/if the Buffer API changes in node, this module's API will change +accordingly. + +## related packages + +- [`buffer-reverse`](https://www.npmjs.com/package/buffer-reverse) - Reverse a buffer +- [`buffer-xor`](https://www.npmjs.com/package/buffer-xor) - Bitwise xor a buffer +- [`is-buffer`](https://www.npmjs.com/package/is-buffer) - Determine if an object is a Buffer without including the whole `Buffer` package + +## conversion packages + +### convert typed array to buffer + +Use [`typedarray-to-buffer`](https://www.npmjs.com/package/typedarray-to-buffer) to convert any kind of typed array to a `Buffer`. Does not perform a copy, so it's super fast. + +### convert buffer to typed array + +`Buffer` is a subclass of `Uint8Array` (which is a typed array). So there is no need to explicitly convert to typed array. Just use the buffer as a `Uint8Array`. + +### convert blob to buffer + +Use [`blob-to-buffer`](https://www.npmjs.com/package/blob-to-buffer) to convert a `Blob` to a `Buffer`. + +### convert buffer to blob + +To convert a `Buffer` to a `Blob`, use the `Blob` constructor: + +```js +var blob = new Blob([ buffer ]) +``` + +Optionally, specify a mimetype: + +```js +var blob = new Blob([ buffer ], { type: 'text/html' }) +``` + +### convert arraybuffer to buffer + +To convert an `ArrayBuffer` to a `Buffer`, use the `Buffer.from` function. Does not perform a copy, so it's super fast. + +```js +var buffer = Buffer.from(arrayBuffer) +``` + +### convert buffer to arraybuffer + +To convert a `Buffer` to an `ArrayBuffer`, use the `.buffer` property (which is present on all `Uint8Array` objects): + +```js +var arrayBuffer = buffer.buffer.slice( + buffer.byteOffset, buffer.byteOffset + buffer.byteLength +) +``` + +Alternatively, use the [`to-arraybuffer`](https://www.npmjs.com/package/to-arraybuffer) module. + +## performance + +See perf tests in `/perf`. + +`BrowserBuffer` is the browser `buffer` module (this repo). `Uint8Array` is included as a +sanity check (since `BrowserBuffer` uses `Uint8Array` under the hood, `Uint8Array` will +always be at least a bit faster). Finally, `NodeBuffer` is the node.js buffer module, +which is included to compare against. + +NOTE: Performance has improved since these benchmarks were taken. PR welcome to update the README. + +### Chrome 38 + +| Method | Operations | Accuracy | Sampled | Fastest | +|:-------|:-----------|:---------|:--------|:-------:| +| BrowserBuffer#bracket-notation | 11,457,464 ops/sec | ±0.86% | 66 | ✓ | +| Uint8Array#bracket-notation | 10,824,332 ops/sec | ±0.74% | 65 | | +| | | | | +| BrowserBuffer#concat | 450,532 ops/sec | ±0.76% | 68 | | +| Uint8Array#concat | 1,368,911 ops/sec | ±1.50% | 62 | ✓ | +| | | | | +| BrowserBuffer#copy(16000) | 903,001 ops/sec | ±0.96% | 67 | | +| Uint8Array#copy(16000) | 1,422,441 ops/sec | ±1.04% | 66 | ✓ | +| | | | | +| BrowserBuffer#copy(16) | 11,431,358 ops/sec | ±0.46% | 69 | | +| Uint8Array#copy(16) | 13,944,163 ops/sec | ±1.12% | 68 | ✓ | +| | | | | +| BrowserBuffer#new(16000) | 106,329 ops/sec | ±6.70% | 44 | | +| Uint8Array#new(16000) | 131,001 ops/sec | ±2.85% | 31 | ✓ | +| | | | | +| BrowserBuffer#new(16) | 1,554,491 ops/sec | ±1.60% | 65 | | +| Uint8Array#new(16) | 6,623,930 ops/sec | ±1.66% | 65 | ✓ | +| | | | | +| BrowserBuffer#readDoubleBE | 112,830 ops/sec | ±0.51% | 69 | ✓ | +| DataView#getFloat64 | 93,500 ops/sec | ±0.57% | 68 | | +| | | | | +| BrowserBuffer#readFloatBE | 146,678 ops/sec | ±0.95% | 68 | ✓ | +| DataView#getFloat32 | 99,311 ops/sec | ±0.41% | 67 | | +| | | | | +| BrowserBuffer#readUInt32LE | 843,214 ops/sec | ±0.70% | 69 | ✓ | +| DataView#getUint32 | 103,024 ops/sec | ±0.64% | 67 | | +| | | | | +| BrowserBuffer#slice | 1,013,941 ops/sec | ±0.75% | 67 | | +| Uint8Array#subarray | 1,903,928 ops/sec | ±0.53% | 67 | ✓ | +| | | | | +| BrowserBuffer#writeFloatBE | 61,387 ops/sec | ±0.90% | 67 | | +| DataView#setFloat32 | 141,249 ops/sec | ±0.40% | 66 | ✓ | + + +### Firefox 33 + +| Method | Operations | Accuracy | Sampled | Fastest | +|:-------|:-----------|:---------|:--------|:-------:| +| BrowserBuffer#bracket-notation | 20,800,421 ops/sec | ±1.84% | 60 | | +| Uint8Array#bracket-notation | 20,826,235 ops/sec | ±2.02% | 61 | ✓ | +| | | | | +| BrowserBuffer#concat | 153,076 ops/sec | ±2.32% | 61 | | +| Uint8Array#concat | 1,255,674 ops/sec | ±8.65% | 52 | ✓ | +| | | | | +| BrowserBuffer#copy(16000) | 1,105,312 ops/sec | ±1.16% | 63 | | +| Uint8Array#copy(16000) | 1,615,911 ops/sec | ±0.55% | 66 | ✓ | +| | | | | +| BrowserBuffer#copy(16) | 16,357,599 ops/sec | ±0.73% | 68 | | +| Uint8Array#copy(16) | 31,436,281 ops/sec | ±1.05% | 68 | ✓ | +| | | | | +| BrowserBuffer#new(16000) | 52,995 ops/sec | ±6.01% | 35 | | +| Uint8Array#new(16000) | 87,686 ops/sec | ±5.68% | 45 | ✓ | +| | | | | +| BrowserBuffer#new(16) | 252,031 ops/sec | ±1.61% | 66 | | +| Uint8Array#new(16) | 8,477,026 ops/sec | ±0.49% | 68 | ✓ | +| | | | | +| BrowserBuffer#readDoubleBE | 99,871 ops/sec | ±0.41% | 69 | | +| DataView#getFloat64 | 285,663 ops/sec | ±0.70% | 68 | ✓ | +| | | | | +| BrowserBuffer#readFloatBE | 115,540 ops/sec | ±0.42% | 69 | | +| DataView#getFloat32 | 288,722 ops/sec | ±0.82% | 68 | ✓ | +| | | | | +| BrowserBuffer#readUInt32LE | 633,926 ops/sec | ±1.08% | 67 | ✓ | +| DataView#getUint32 | 294,808 ops/sec | ±0.79% | 64 | | +| | | | | +| BrowserBuffer#slice | 349,425 ops/sec | ±0.46% | 69 | | +| Uint8Array#subarray | 5,965,819 ops/sec | ±0.60% | 65 | ✓ | +| | | | | +| BrowserBuffer#writeFloatBE | 59,980 ops/sec | ±0.41% | 67 | | +| DataView#setFloat32 | 317,634 ops/sec | ±0.63% | 68 | ✓ | + +### Safari 8 + +| Method | Operations | Accuracy | Sampled | Fastest | +|:-------|:-----------|:---------|:--------|:-------:| +| BrowserBuffer#bracket-notation | 10,279,729 ops/sec | ±2.25% | 56 | ✓ | +| Uint8Array#bracket-notation | 10,030,767 ops/sec | ±2.23% | 59 | | +| | | | | +| BrowserBuffer#concat | 144,138 ops/sec | ±1.38% | 65 | | +| Uint8Array#concat | 4,950,764 ops/sec | ±1.70% | 63 | ✓ | +| | | | | +| BrowserBuffer#copy(16000) | 1,058,548 ops/sec | ±1.51% | 64 | | +| Uint8Array#copy(16000) | 1,409,666 ops/sec | ±1.17% | 65 | ✓ | +| | | | | +| BrowserBuffer#copy(16) | 6,282,529 ops/sec | ±1.88% | 58 | | +| Uint8Array#copy(16) | 11,907,128 ops/sec | ±2.87% | 58 | ✓ | +| | | | | +| BrowserBuffer#new(16000) | 101,663 ops/sec | ±3.89% | 57 | | +| Uint8Array#new(16000) | 22,050,818 ops/sec | ±6.51% | 46 | ✓ | +| | | | | +| BrowserBuffer#new(16) | 176,072 ops/sec | ±2.13% | 64 | | +| Uint8Array#new(16) | 24,385,731 ops/sec | ±5.01% | 51 | ✓ | +| | | | | +| BrowserBuffer#readDoubleBE | 41,341 ops/sec | ±1.06% | 67 | | +| DataView#getFloat64 | 322,280 ops/sec | ±0.84% | 68 | ✓ | +| | | | | +| BrowserBuffer#readFloatBE | 46,141 ops/sec | ±1.06% | 65 | | +| DataView#getFloat32 | 337,025 ops/sec | ±0.43% | 69 | ✓ | +| | | | | +| BrowserBuffer#readUInt32LE | 151,551 ops/sec | ±1.02% | 66 | | +| DataView#getUint32 | 308,278 ops/sec | ±0.94% | 67 | ✓ | +| | | | | +| BrowserBuffer#slice | 197,365 ops/sec | ±0.95% | 66 | | +| Uint8Array#subarray | 9,558,024 ops/sec | ±3.08% | 58 | ✓ | +| | | | | +| BrowserBuffer#writeFloatBE | 17,518 ops/sec | ±1.03% | 63 | | +| DataView#setFloat32 | 319,751 ops/sec | ±0.48% | 68 | ✓ | + + +### Node 0.11.14 + +| Method | Operations | Accuracy | Sampled | Fastest | +|:-------|:-----------|:---------|:--------|:-------:| +| BrowserBuffer#bracket-notation | 10,489,828 ops/sec | ±3.25% | 90 | | +| Uint8Array#bracket-notation | 10,534,884 ops/sec | ±0.81% | 92 | ✓ | +| NodeBuffer#bracket-notation | 10,389,910 ops/sec | ±0.97% | 87 | | +| | | | | +| BrowserBuffer#concat | 487,830 ops/sec | ±2.58% | 88 | | +| Uint8Array#concat | 1,814,327 ops/sec | ±1.28% | 88 | ✓ | +| NodeBuffer#concat | 1,636,523 ops/sec | ±1.88% | 73 | | +| | | | | +| BrowserBuffer#copy(16000) | 1,073,665 ops/sec | ±0.77% | 90 | | +| Uint8Array#copy(16000) | 1,348,517 ops/sec | ±0.84% | 89 | ✓ | +| NodeBuffer#copy(16000) | 1,289,533 ops/sec | ±0.82% | 93 | | +| | | | | +| BrowserBuffer#copy(16) | 12,782,706 ops/sec | ±0.74% | 85 | | +| Uint8Array#copy(16) | 14,180,427 ops/sec | ±0.93% | 92 | ✓ | +| NodeBuffer#copy(16) | 11,083,134 ops/sec | ±1.06% | 89 | | +| | | | | +| BrowserBuffer#new(16000) | 141,678 ops/sec | ±3.30% | 67 | | +| Uint8Array#new(16000) | 161,491 ops/sec | ±2.96% | 60 | | +| NodeBuffer#new(16000) | 292,699 ops/sec | ±3.20% | 55 | ✓ | +| | | | | +| BrowserBuffer#new(16) | 1,655,466 ops/sec | ±2.41% | 82 | | +| Uint8Array#new(16) | 14,399,926 ops/sec | ±0.91% | 94 | ✓ | +| NodeBuffer#new(16) | 3,894,696 ops/sec | ±0.88% | 92 | | +| | | | | +| BrowserBuffer#readDoubleBE | 109,582 ops/sec | ±0.75% | 93 | ✓ | +| DataView#getFloat64 | 91,235 ops/sec | ±0.81% | 90 | | +| NodeBuffer#readDoubleBE | 88,593 ops/sec | ±0.96% | 81 | | +| | | | | +| BrowserBuffer#readFloatBE | 139,854 ops/sec | ±1.03% | 85 | ✓ | +| DataView#getFloat32 | 98,744 ops/sec | ±0.80% | 89 | | +| NodeBuffer#readFloatBE | 92,769 ops/sec | ±0.94% | 93 | | +| | | | | +| BrowserBuffer#readUInt32LE | 710,861 ops/sec | ±0.82% | 92 | | +| DataView#getUint32 | 117,893 ops/sec | ±0.84% | 91 | | +| NodeBuffer#readUInt32LE | 851,412 ops/sec | ±0.72% | 93 | ✓ | +| | | | | +| BrowserBuffer#slice | 1,673,877 ops/sec | ±0.73% | 94 | | +| Uint8Array#subarray | 6,919,243 ops/sec | ±0.67% | 90 | ✓ | +| NodeBuffer#slice | 4,617,604 ops/sec | ±0.79% | 93 | | +| | | | | +| BrowserBuffer#writeFloatBE | 66,011 ops/sec | ±0.75% | 93 | | +| DataView#setFloat32 | 127,760 ops/sec | ±0.72% | 93 | ✓ | +| NodeBuffer#writeFloatBE | 103,352 ops/sec | ±0.83% | 93 | | + +### iojs 1.8.1 + +| Method | Operations | Accuracy | Sampled | Fastest | +|:-------|:-----------|:---------|:--------|:-------:| +| BrowserBuffer#bracket-notation | 10,990,488 ops/sec | ±1.11% | 91 | | +| Uint8Array#bracket-notation | 11,268,757 ops/sec | ±0.65% | 97 | | +| NodeBuffer#bracket-notation | 11,353,260 ops/sec | ±0.83% | 94 | ✓ | +| | | | | +| BrowserBuffer#concat | 378,954 ops/sec | ±0.74% | 94 | | +| Uint8Array#concat | 1,358,288 ops/sec | ±0.97% | 87 | | +| NodeBuffer#concat | 1,934,050 ops/sec | ±1.11% | 78 | ✓ | +| | | | | +| BrowserBuffer#copy(16000) | 894,538 ops/sec | ±0.56% | 84 | | +| Uint8Array#copy(16000) | 1,442,656 ops/sec | ±0.71% | 96 | | +| NodeBuffer#copy(16000) | 1,457,898 ops/sec | ±0.53% | 92 | ✓ | +| | | | | +| BrowserBuffer#copy(16) | 12,870,457 ops/sec | ±0.67% | 95 | | +| Uint8Array#copy(16) | 16,643,989 ops/sec | ±0.61% | 93 | ✓ | +| NodeBuffer#copy(16) | 14,885,848 ops/sec | ±0.74% | 94 | | +| | | | | +| BrowserBuffer#new(16000) | 109,264 ops/sec | ±4.21% | 63 | | +| Uint8Array#new(16000) | 138,916 ops/sec | ±1.87% | 61 | | +| NodeBuffer#new(16000) | 281,449 ops/sec | ±3.58% | 51 | ✓ | +| | | | | +| BrowserBuffer#new(16) | 1,362,935 ops/sec | ±0.56% | 99 | | +| Uint8Array#new(16) | 6,193,090 ops/sec | ±0.64% | 95 | ✓ | +| NodeBuffer#new(16) | 4,745,425 ops/sec | ±1.56% | 90 | | +| | | | | +| BrowserBuffer#readDoubleBE | 118,127 ops/sec | ±0.59% | 93 | ✓ | +| DataView#getFloat64 | 107,332 ops/sec | ±0.65% | 91 | | +| NodeBuffer#readDoubleBE | 116,274 ops/sec | ±0.94% | 95 | | +| | | | | +| BrowserBuffer#readFloatBE | 150,326 ops/sec | ±0.58% | 95 | ✓ | +| DataView#getFloat32 | 110,541 ops/sec | ±0.57% | 98 | | +| NodeBuffer#readFloatBE | 121,599 ops/sec | ±0.60% | 87 | | +| | | | | +| BrowserBuffer#readUInt32LE | 814,147 ops/sec | ±0.62% | 93 | | +| DataView#getUint32 | 137,592 ops/sec | ±0.64% | 90 | | +| NodeBuffer#readUInt32LE | 931,650 ops/sec | ±0.71% | 96 | ✓ | +| | | | | +| BrowserBuffer#slice | 878,590 ops/sec | ±0.68% | 93 | | +| Uint8Array#subarray | 2,843,308 ops/sec | ±1.02% | 90 | | +| NodeBuffer#slice | 4,998,316 ops/sec | ±0.68% | 90 | ✓ | +| | | | | +| BrowserBuffer#writeFloatBE | 65,927 ops/sec | ±0.74% | 93 | | +| DataView#setFloat32 | 139,823 ops/sec | ±0.97% | 89 | ✓ | +| NodeBuffer#writeFloatBE | 135,763 ops/sec | ±0.65% | 96 | | +| | | | | + +## Testing the project + +First, install the project: + + npm install + +Then, to run tests in Node.js, run: + + npm run test-node + +To test locally in a browser, you can run: + + npm run test-browser-es5-local # For ES5 browsers that don't support ES6 + npm run test-browser-es6-local # For ES6 compliant browsers + +This will print out a URL that you can then open in a browser to run the tests, using [airtap](https://www.npmjs.com/package/airtap). + +To run automated browser tests using Saucelabs, ensure that your `SAUCE_USERNAME` and `SAUCE_ACCESS_KEY` environment variables are set, then run: + + npm test + +This is what's run in Travis, to check against various browsers. The list of browsers is kept in the `bin/airtap-es5.yml` and `bin/airtap-es6.yml` files. + +## JavaScript Standard Style + +This module uses [JavaScript Standard Style](https://github.com/feross/standard). + +[![JavaScript Style Guide](https://cdn.rawgit.com/feross/standard/master/badge.svg)](https://github.com/feross/standard) + +To test that the code conforms to the style, `npm install` and run: + + ./node_modules/.bin/standard + +## credit + +This was originally forked from [buffer-browserify](https://github.com/toots/buffer-browserify). + +## Security Policies and Procedures + +The `buffer` team and community take all security bugs in `buffer` seriously. Please see our [security policies and procedures](https://github.com/feross/security) document to learn how to report issues. + +## license + +MIT. Copyright (C) [Feross Aboukhadijeh](http://feross.org), and other contributors. Originally forked from an MIT-licensed module by Romain Beauxis. diff --git a/ts-ticket-office-service/node_modules/buffer/index.d.ts b/ts-ticket-office-service/node_modules/buffer/index.d.ts new file mode 100644 index 000000000..5d1a804e5 --- /dev/null +++ b/ts-ticket-office-service/node_modules/buffer/index.d.ts @@ -0,0 +1,186 @@ +export class Buffer extends Uint8Array { + length: number + write(string: string, offset?: number, length?: number, encoding?: string): number; + toString(encoding?: string, start?: number, end?: number): string; + toJSON(): { type: 'Buffer', data: any[] }; + equals(otherBuffer: Buffer): boolean; + compare(otherBuffer: Buffer, targetStart?: number, targetEnd?: number, sourceStart?: number, sourceEnd?: number): number; + copy(targetBuffer: Buffer, targetStart?: number, sourceStart?: number, sourceEnd?: number): number; + slice(start?: number, end?: number): Buffer; + writeUIntLE(value: number, offset: number, byteLength: number, noAssert?: boolean): number; + writeUIntBE(value: number, offset: number, byteLength: number, noAssert?: boolean): number; + writeIntLE(value: number, offset: number, byteLength: number, noAssert?: boolean): number; + writeIntBE(value: number, offset: number, byteLength: number, noAssert?: boolean): number; + readUIntLE(offset: number, byteLength: number, noAssert?: boolean): number; + readUIntBE(offset: number, byteLength: number, noAssert?: boolean): number; + readIntLE(offset: number, byteLength: number, noAssert?: boolean): number; + readIntBE(offset: number, byteLength: number, noAssert?: boolean): number; + readUInt8(offset: number, noAssert?: boolean): number; + readUInt16LE(offset: number, noAssert?: boolean): number; + readUInt16BE(offset: number, noAssert?: boolean): number; + readUInt32LE(offset: number, noAssert?: boolean): number; + readUInt32BE(offset: number, noAssert?: boolean): number; + readInt8(offset: number, noAssert?: boolean): number; + readInt16LE(offset: number, noAssert?: boolean): number; + readInt16BE(offset: number, noAssert?: boolean): number; + readInt32LE(offset: number, noAssert?: boolean): number; + readInt32BE(offset: number, noAssert?: boolean): number; + readFloatLE(offset: number, noAssert?: boolean): number; + readFloatBE(offset: number, noAssert?: boolean): number; + readDoubleLE(offset: number, noAssert?: boolean): number; + readDoubleBE(offset: number, noAssert?: boolean): number; + reverse(): this; + swap16(): Buffer; + swap32(): Buffer; + swap64(): Buffer; + writeUInt8(value: number, offset: number, noAssert?: boolean): number; + writeUInt16LE(value: number, offset: number, noAssert?: boolean): number; + writeUInt16BE(value: number, offset: number, noAssert?: boolean): number; + writeUInt32LE(value: number, offset: number, noAssert?: boolean): number; + writeUInt32BE(value: number, offset: number, noAssert?: boolean): number; + writeInt8(value: number, offset: number, noAssert?: boolean): number; + writeInt16LE(value: number, offset: number, noAssert?: boolean): number; + writeInt16BE(value: number, offset: number, noAssert?: boolean): number; + writeInt32LE(value: number, offset: number, noAssert?: boolean): number; + writeInt32BE(value: number, offset: number, noAssert?: boolean): number; + writeFloatLE(value: number, offset: number, noAssert?: boolean): number; + writeFloatBE(value: number, offset: number, noAssert?: boolean): number; + writeDoubleLE(value: number, offset: number, noAssert?: boolean): number; + writeDoubleBE(value: number, offset: number, noAssert?: boolean): number; + fill(value: any, offset?: number, end?: number): this; + indexOf(value: string | number | Buffer, byteOffset?: number, encoding?: string): number; + lastIndexOf(value: string | number | Buffer, byteOffset?: number, encoding?: string): number; + includes(value: string | number | Buffer, byteOffset?: number, encoding?: string): boolean; + + /** + * Allocates a new buffer containing the given {str}. + * + * @param str String to store in buffer. + * @param encoding encoding to use, optional. Default is 'utf8' + */ + constructor (str: string, encoding?: string); + /** + * Allocates a new buffer of {size} octets. + * + * @param size count of octets to allocate. + */ + constructor (size: number); + /** + * Allocates a new buffer containing the given {array} of octets. + * + * @param array The octets to store. + */ + constructor (array: Uint8Array); + /** + * Produces a Buffer backed by the same allocated memory as + * the given {ArrayBuffer}. + * + * + * @param arrayBuffer The ArrayBuffer with which to share memory. + */ + constructor (arrayBuffer: ArrayBuffer); + /** + * Allocates a new buffer containing the given {array} of octets. + * + * @param array The octets to store. + */ + constructor (array: any[]); + /** + * Copies the passed {buffer} data onto a new {Buffer} instance. + * + * @param buffer The buffer to copy. + */ + constructor (buffer: Buffer); + prototype: Buffer; + /** + * Allocates a new Buffer using an {array} of octets. + * + * @param array + */ + static from(array: any[]): Buffer; + /** + * When passed a reference to the .buffer property of a TypedArray instance, + * the newly created Buffer will share the same allocated memory as the TypedArray. + * The optional {byteOffset} and {length} arguments specify a memory range + * within the {arrayBuffer} that will be shared by the Buffer. + * + * @param arrayBuffer The .buffer property of a TypedArray or a new ArrayBuffer() + * @param byteOffset + * @param length + */ + static from(arrayBuffer: ArrayBuffer, byteOffset?: number, length?: number): Buffer; + /** + * Copies the passed {buffer} data onto a new Buffer instance. + * + * @param buffer + */ + static from(buffer: Buffer | Uint8Array): Buffer; + /** + * Creates a new Buffer containing the given JavaScript string {str}. + * If provided, the {encoding} parameter identifies the character encoding. + * If not provided, {encoding} defaults to 'utf8'. + * + * @param str + */ + static from(str: string, encoding?: string): Buffer; + /** + * Returns true if {obj} is a Buffer + * + * @param obj object to test. + */ + static isBuffer(obj: any): obj is Buffer; + /** + * Returns true if {encoding} is a valid encoding argument. + * Valid string encodings in Node 0.12: 'ascii'|'utf8'|'utf16le'|'ucs2'(alias of 'utf16le')|'base64'|'binary'(deprecated)|'hex' + * + * @param encoding string to test. + */ + static isEncoding(encoding: string): boolean; + /** + * Gives the actual byte length of a string. encoding defaults to 'utf8'. + * This is not the same as String.prototype.length since that returns the number of characters in a string. + * + * @param string string to test. + * @param encoding encoding used to evaluate (defaults to 'utf8') + */ + static byteLength(string: string, encoding?: string): number; + /** + * Returns a buffer which is the result of concatenating all the buffers in the list together. + * + * If the list has no items, or if the totalLength is 0, then it returns a zero-length buffer. + * If the list has exactly one item, then the first item of the list is returned. + * If the list has more than one item, then a new Buffer is created. + * + * @param list An array of Buffer objects to concatenate + * @param totalLength Total length of the buffers when concatenated. + * If totalLength is not provided, it is read from the buffers in the list. However, this adds an additional loop to the function, so it is faster to provide the length explicitly. + */ + static concat(list: Buffer[], totalLength?: number): Buffer; + /** + * The same as buf1.compare(buf2). + */ + static compare(buf1: Buffer, buf2: Buffer): number; + /** + * Allocates a new buffer of {size} octets. + * + * @param size count of octets to allocate. + * @param fill if specified, buffer will be initialized by calling buf.fill(fill). + * If parameter is omitted, buffer will be filled with zeros. + * @param encoding encoding used for call to buf.fill while initializing + */ + static alloc(size: number, fill?: string | Buffer | number, encoding?: string): Buffer; + /** + * Allocates a new buffer of {size} octets, leaving memory not initialized, so the contents + * of the newly created Buffer are unknown and may contain sensitive data. + * + * @param size count of octets to allocate + */ + static allocUnsafe(size: number): Buffer; + /** + * Allocates a new non-pooled buffer of {size} octets, leaving memory not initialized, so the contents + * of the newly created Buffer are unknown and may contain sensitive data. + * + * @param size count of octets to allocate + */ + static allocUnsafeSlow(size: number): Buffer; +} diff --git a/ts-ticket-office-service/node_modules/buffer/index.js b/ts-ticket-office-service/node_modules/buffer/index.js new file mode 100644 index 000000000..609cf3113 --- /dev/null +++ b/ts-ticket-office-service/node_modules/buffer/index.js @@ -0,0 +1,1817 @@ +/*! + * The buffer module from node.js, for the browser. + * + * @author Feross Aboukhadijeh + * @license MIT + */ +/* eslint-disable no-proto */ + +'use strict' + +var base64 = require('base64-js') +var ieee754 = require('ieee754') +var customInspectSymbol = + (typeof Symbol === 'function' && typeof Symbol['for'] === 'function') // eslint-disable-line dot-notation + ? Symbol['for']('nodejs.util.inspect.custom') // eslint-disable-line dot-notation + : null + +exports.Buffer = Buffer +exports.SlowBuffer = SlowBuffer +exports.INSPECT_MAX_BYTES = 50 + +var K_MAX_LENGTH = 0x7fffffff +exports.kMaxLength = K_MAX_LENGTH + +/** + * If `Buffer.TYPED_ARRAY_SUPPORT`: + * === true Use Uint8Array implementation (fastest) + * === false Print warning and recommend using `buffer` v4.x which has an Object + * implementation (most compatible, even IE6) + * + * Browsers that support typed arrays are IE 10+, Firefox 4+, Chrome 7+, Safari 5.1+, + * Opera 11.6+, iOS 4.2+. + * + * We report that the browser does not support typed arrays if the are not subclassable + * using __proto__. Firefox 4-29 lacks support for adding new properties to `Uint8Array` + * (See: https://bugzilla.mozilla.org/show_bug.cgi?id=695438). IE 10 lacks support + * for __proto__ and has a buggy typed array implementation. + */ +Buffer.TYPED_ARRAY_SUPPORT = typedArraySupport() + +if (!Buffer.TYPED_ARRAY_SUPPORT && typeof console !== 'undefined' && + typeof console.error === 'function') { + console.error( + 'This browser lacks typed array (Uint8Array) support which is required by ' + + '`buffer` v5.x. Use `buffer` v4.x if you require old browser support.' + ) +} + +function typedArraySupport () { + // Can typed array instances can be augmented? + try { + var arr = new Uint8Array(1) + var proto = { foo: function () { return 42 } } + Object.setPrototypeOf(proto, Uint8Array.prototype) + Object.setPrototypeOf(arr, proto) + return arr.foo() === 42 + } catch (e) { + return false + } +} + +Object.defineProperty(Buffer.prototype, 'parent', { + enumerable: true, + get: function () { + if (!Buffer.isBuffer(this)) return undefined + return this.buffer + } +}) + +Object.defineProperty(Buffer.prototype, 'offset', { + enumerable: true, + get: function () { + if (!Buffer.isBuffer(this)) return undefined + return this.byteOffset + } +}) + +function createBuffer (length) { + if (length > K_MAX_LENGTH) { + throw new RangeError('The value "' + length + '" is invalid for option "size"') + } + // Return an augmented `Uint8Array` instance + var buf = new Uint8Array(length) + Object.setPrototypeOf(buf, Buffer.prototype) + return buf +} + +/** + * The Buffer constructor returns instances of `Uint8Array` that have their + * prototype changed to `Buffer.prototype`. Furthermore, `Buffer` is a subclass of + * `Uint8Array`, so the returned instances will have all the node `Buffer` methods + * and the `Uint8Array` methods. Square bracket notation works as expected -- it + * returns a single octet. + * + * The `Uint8Array` prototype remains unmodified. + */ + +function Buffer (arg, encodingOrOffset, length) { + // Common case. + if (typeof arg === 'number') { + if (typeof encodingOrOffset === 'string') { + throw new TypeError( + 'The "string" argument must be of type string. Received type number' + ) + } + return allocUnsafe(arg) + } + return from(arg, encodingOrOffset, length) +} + +Buffer.poolSize = 8192 // not used by this implementation + +function from (value, encodingOrOffset, length) { + if (typeof value === 'string') { + return fromString(value, encodingOrOffset) + } + + if (ArrayBuffer.isView(value)) { + return fromArrayView(value) + } + + if (value == null) { + throw new TypeError( + 'The first argument must be one of type string, Buffer, ArrayBuffer, Array, ' + + 'or Array-like Object. Received type ' + (typeof value) + ) + } + + if (isInstance(value, ArrayBuffer) || + (value && isInstance(value.buffer, ArrayBuffer))) { + return fromArrayBuffer(value, encodingOrOffset, length) + } + + if (typeof SharedArrayBuffer !== 'undefined' && + (isInstance(value, SharedArrayBuffer) || + (value && isInstance(value.buffer, SharedArrayBuffer)))) { + return fromArrayBuffer(value, encodingOrOffset, length) + } + + if (typeof value === 'number') { + throw new TypeError( + 'The "value" argument must not be of type number. Received type number' + ) + } + + var valueOf = value.valueOf && value.valueOf() + if (valueOf != null && valueOf !== value) { + return Buffer.from(valueOf, encodingOrOffset, length) + } + + var b = fromObject(value) + if (b) return b + + if (typeof Symbol !== 'undefined' && Symbol.toPrimitive != null && + typeof value[Symbol.toPrimitive] === 'function') { + return Buffer.from( + value[Symbol.toPrimitive]('string'), encodingOrOffset, length + ) + } + + throw new TypeError( + 'The first argument must be one of type string, Buffer, ArrayBuffer, Array, ' + + 'or Array-like Object. Received type ' + (typeof value) + ) +} + +/** + * Functionally equivalent to Buffer(arg, encoding) but throws a TypeError + * if value is a number. + * Buffer.from(str[, encoding]) + * Buffer.from(array) + * Buffer.from(buffer) + * Buffer.from(arrayBuffer[, byteOffset[, length]]) + **/ +Buffer.from = function (value, encodingOrOffset, length) { + return from(value, encodingOrOffset, length) +} + +// Note: Change prototype *after* Buffer.from is defined to workaround Chrome bug: +// https://github.com/feross/buffer/pull/148 +Object.setPrototypeOf(Buffer.prototype, Uint8Array.prototype) +Object.setPrototypeOf(Buffer, Uint8Array) + +function assertSize (size) { + if (typeof size !== 'number') { + throw new TypeError('"size" argument must be of type number') + } else if (size < 0) { + throw new RangeError('The value "' + size + '" is invalid for option "size"') + } +} + +function alloc (size, fill, encoding) { + assertSize(size) + if (size <= 0) { + return createBuffer(size) + } + if (fill !== undefined) { + // Only pay attention to encoding if it's a string. This + // prevents accidentally sending in a number that would + // be interpreted as a start offset. + return typeof encoding === 'string' + ? createBuffer(size).fill(fill, encoding) + : createBuffer(size).fill(fill) + } + return createBuffer(size) +} + +/** + * Creates a new filled Buffer instance. + * alloc(size[, fill[, encoding]]) + **/ +Buffer.alloc = function (size, fill, encoding) { + return alloc(size, fill, encoding) +} + +function allocUnsafe (size) { + assertSize(size) + return createBuffer(size < 0 ? 0 : checked(size) | 0) +} + +/** + * Equivalent to Buffer(num), by default creates a non-zero-filled Buffer instance. + * */ +Buffer.allocUnsafe = function (size) { + return allocUnsafe(size) +} +/** + * Equivalent to SlowBuffer(num), by default creates a non-zero-filled Buffer instance. + */ +Buffer.allocUnsafeSlow = function (size) { + return allocUnsafe(size) +} + +function fromString (string, encoding) { + if (typeof encoding !== 'string' || encoding === '') { + encoding = 'utf8' + } + + if (!Buffer.isEncoding(encoding)) { + throw new TypeError('Unknown encoding: ' + encoding) + } + + var length = byteLength(string, encoding) | 0 + var buf = createBuffer(length) + + var actual = buf.write(string, encoding) + + if (actual !== length) { + // Writing a hex string, for example, that contains invalid characters will + // cause everything after the first invalid character to be ignored. (e.g. + // 'abxxcd' will be treated as 'ab') + buf = buf.slice(0, actual) + } + + return buf +} + +function fromArrayLike (array) { + var length = array.length < 0 ? 0 : checked(array.length) | 0 + var buf = createBuffer(length) + for (var i = 0; i < length; i += 1) { + buf[i] = array[i] & 255 + } + return buf +} + +function fromArrayView (arrayView) { + if (isInstance(arrayView, Uint8Array)) { + var copy = new Uint8Array(arrayView) + return fromArrayBuffer(copy.buffer, copy.byteOffset, copy.byteLength) + } + return fromArrayLike(arrayView) +} + +function fromArrayBuffer (array, byteOffset, length) { + if (byteOffset < 0 || array.byteLength < byteOffset) { + throw new RangeError('"offset" is outside of buffer bounds') + } + + if (array.byteLength < byteOffset + (length || 0)) { + throw new RangeError('"length" is outside of buffer bounds') + } + + var buf + if (byteOffset === undefined && length === undefined) { + buf = new Uint8Array(array) + } else if (length === undefined) { + buf = new Uint8Array(array, byteOffset) + } else { + buf = new Uint8Array(array, byteOffset, length) + } + + // Return an augmented `Uint8Array` instance + Object.setPrototypeOf(buf, Buffer.prototype) + + return buf +} + +function fromObject (obj) { + if (Buffer.isBuffer(obj)) { + var len = checked(obj.length) | 0 + var buf = createBuffer(len) + + if (buf.length === 0) { + return buf + } + + obj.copy(buf, 0, 0, len) + return buf + } + + if (obj.length !== undefined) { + if (typeof obj.length !== 'number' || numberIsNaN(obj.length)) { + return createBuffer(0) + } + return fromArrayLike(obj) + } + + if (obj.type === 'Buffer' && Array.isArray(obj.data)) { + return fromArrayLike(obj.data) + } +} + +function checked (length) { + // Note: cannot use `length < K_MAX_LENGTH` here because that fails when + // length is NaN (which is otherwise coerced to zero.) + if (length >= K_MAX_LENGTH) { + throw new RangeError('Attempt to allocate Buffer larger than maximum ' + + 'size: 0x' + K_MAX_LENGTH.toString(16) + ' bytes') + } + return length | 0 +} + +function SlowBuffer (length) { + if (+length != length) { // eslint-disable-line eqeqeq + length = 0 + } + return Buffer.alloc(+length) +} + +Buffer.isBuffer = function isBuffer (b) { + return b != null && b._isBuffer === true && + b !== Buffer.prototype // so Buffer.isBuffer(Buffer.prototype) will be false +} + +Buffer.compare = function compare (a, b) { + if (isInstance(a, Uint8Array)) a = Buffer.from(a, a.offset, a.byteLength) + if (isInstance(b, Uint8Array)) b = Buffer.from(b, b.offset, b.byteLength) + if (!Buffer.isBuffer(a) || !Buffer.isBuffer(b)) { + throw new TypeError( + 'The "buf1", "buf2" arguments must be one of type Buffer or Uint8Array' + ) + } + + if (a === b) return 0 + + var x = a.length + var y = b.length + + for (var i = 0, len = Math.min(x, y); i < len; ++i) { + if (a[i] !== b[i]) { + x = a[i] + y = b[i] + break + } + } + + if (x < y) return -1 + if (y < x) return 1 + return 0 +} + +Buffer.isEncoding = function isEncoding (encoding) { + switch (String(encoding).toLowerCase()) { + case 'hex': + case 'utf8': + case 'utf-8': + case 'ascii': + case 'latin1': + case 'binary': + case 'base64': + case 'ucs2': + case 'ucs-2': + case 'utf16le': + case 'utf-16le': + return true + default: + return false + } +} + +Buffer.concat = function concat (list, length) { + if (!Array.isArray(list)) { + throw new TypeError('"list" argument must be an Array of Buffers') + } + + if (list.length === 0) { + return Buffer.alloc(0) + } + + var i + if (length === undefined) { + length = 0 + for (i = 0; i < list.length; ++i) { + length += list[i].length + } + } + + var buffer = Buffer.allocUnsafe(length) + var pos = 0 + for (i = 0; i < list.length; ++i) { + var buf = list[i] + if (isInstance(buf, Uint8Array)) { + if (pos + buf.length > buffer.length) { + Buffer.from(buf).copy(buffer, pos) + } else { + Uint8Array.prototype.set.call( + buffer, + buf, + pos + ) + } + } else if (!Buffer.isBuffer(buf)) { + throw new TypeError('"list" argument must be an Array of Buffers') + } else { + buf.copy(buffer, pos) + } + pos += buf.length + } + return buffer +} + +function byteLength (string, encoding) { + if (Buffer.isBuffer(string)) { + return string.length + } + if (ArrayBuffer.isView(string) || isInstance(string, ArrayBuffer)) { + return string.byteLength + } + if (typeof string !== 'string') { + throw new TypeError( + 'The "string" argument must be one of type string, Buffer, or ArrayBuffer. ' + + 'Received type ' + typeof string + ) + } + + var len = string.length + var mustMatch = (arguments.length > 2 && arguments[2] === true) + if (!mustMatch && len === 0) return 0 + + // Use a for loop to avoid recursion + var loweredCase = false + for (;;) { + switch (encoding) { + case 'ascii': + case 'latin1': + case 'binary': + return len + case 'utf8': + case 'utf-8': + return utf8ToBytes(string).length + case 'ucs2': + case 'ucs-2': + case 'utf16le': + case 'utf-16le': + return len * 2 + case 'hex': + return len >>> 1 + case 'base64': + return base64ToBytes(string).length + default: + if (loweredCase) { + return mustMatch ? -1 : utf8ToBytes(string).length // assume utf8 + } + encoding = ('' + encoding).toLowerCase() + loweredCase = true + } + } +} +Buffer.byteLength = byteLength + +function slowToString (encoding, start, end) { + var loweredCase = false + + // No need to verify that "this.length <= MAX_UINT32" since it's a read-only + // property of a typed array. + + // This behaves neither like String nor Uint8Array in that we set start/end + // to their upper/lower bounds if the value passed is out of range. + // undefined is handled specially as per ECMA-262 6th Edition, + // Section 13.3.3.7 Runtime Semantics: KeyedBindingInitialization. + if (start === undefined || start < 0) { + start = 0 + } + // Return early if start > this.length. Done here to prevent potential uint32 + // coercion fail below. + if (start > this.length) { + return '' + } + + if (end === undefined || end > this.length) { + end = this.length + } + + if (end <= 0) { + return '' + } + + // Force coercion to uint32. This will also coerce falsey/NaN values to 0. + end >>>= 0 + start >>>= 0 + + if (end <= start) { + return '' + } + + if (!encoding) encoding = 'utf8' + + while (true) { + switch (encoding) { + case 'hex': + return hexSlice(this, start, end) + + case 'utf8': + case 'utf-8': + return utf8Slice(this, start, end) + + case 'ascii': + return asciiSlice(this, start, end) + + case 'latin1': + case 'binary': + return latin1Slice(this, start, end) + + case 'base64': + return base64Slice(this, start, end) + + case 'ucs2': + case 'ucs-2': + case 'utf16le': + case 'utf-16le': + return utf16leSlice(this, start, end) + + default: + if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding) + encoding = (encoding + '').toLowerCase() + loweredCase = true + } + } +} + +// This property is used by `Buffer.isBuffer` (and the `is-buffer` npm package) +// to detect a Buffer instance. It's not possible to use `instanceof Buffer` +// reliably in a browserify context because there could be multiple different +// copies of the 'buffer' package in use. This method works even for Buffer +// instances that were created from another copy of the `buffer` package. +// See: https://github.com/feross/buffer/issues/154 +Buffer.prototype._isBuffer = true + +function swap (b, n, m) { + var i = b[n] + b[n] = b[m] + b[m] = i +} + +Buffer.prototype.swap16 = function swap16 () { + var len = this.length + if (len % 2 !== 0) { + throw new RangeError('Buffer size must be a multiple of 16-bits') + } + for (var i = 0; i < len; i += 2) { + swap(this, i, i + 1) + } + return this +} + +Buffer.prototype.swap32 = function swap32 () { + var len = this.length + if (len % 4 !== 0) { + throw new RangeError('Buffer size must be a multiple of 32-bits') + } + for (var i = 0; i < len; i += 4) { + swap(this, i, i + 3) + swap(this, i + 1, i + 2) + } + return this +} + +Buffer.prototype.swap64 = function swap64 () { + var len = this.length + if (len % 8 !== 0) { + throw new RangeError('Buffer size must be a multiple of 64-bits') + } + for (var i = 0; i < len; i += 8) { + swap(this, i, i + 7) + swap(this, i + 1, i + 6) + swap(this, i + 2, i + 5) + swap(this, i + 3, i + 4) + } + return this +} + +Buffer.prototype.toString = function toString () { + var length = this.length + if (length === 0) return '' + if (arguments.length === 0) return utf8Slice(this, 0, length) + return slowToString.apply(this, arguments) +} + +Buffer.prototype.toLocaleString = Buffer.prototype.toString + +Buffer.prototype.equals = function equals (b) { + if (!Buffer.isBuffer(b)) throw new TypeError('Argument must be a Buffer') + if (this === b) return true + return Buffer.compare(this, b) === 0 +} + +Buffer.prototype.inspect = function inspect () { + var str = '' + var max = exports.INSPECT_MAX_BYTES + str = this.toString('hex', 0, max).replace(/(.{2})/g, '$1 ').trim() + if (this.length > max) str += ' ... ' + return '' +} +if (customInspectSymbol) { + Buffer.prototype[customInspectSymbol] = Buffer.prototype.inspect +} + +Buffer.prototype.compare = function compare (target, start, end, thisStart, thisEnd) { + if (isInstance(target, Uint8Array)) { + target = Buffer.from(target, target.offset, target.byteLength) + } + if (!Buffer.isBuffer(target)) { + throw new TypeError( + 'The "target" argument must be one of type Buffer or Uint8Array. ' + + 'Received type ' + (typeof target) + ) + } + + if (start === undefined) { + start = 0 + } + if (end === undefined) { + end = target ? target.length : 0 + } + if (thisStart === undefined) { + thisStart = 0 + } + if (thisEnd === undefined) { + thisEnd = this.length + } + + if (start < 0 || end > target.length || thisStart < 0 || thisEnd > this.length) { + throw new RangeError('out of range index') + } + + if (thisStart >= thisEnd && start >= end) { + return 0 + } + if (thisStart >= thisEnd) { + return -1 + } + if (start >= end) { + return 1 + } + + start >>>= 0 + end >>>= 0 + thisStart >>>= 0 + thisEnd >>>= 0 + + if (this === target) return 0 + + var x = thisEnd - thisStart + var y = end - start + var len = Math.min(x, y) + + var thisCopy = this.slice(thisStart, thisEnd) + var targetCopy = target.slice(start, end) + + for (var i = 0; i < len; ++i) { + if (thisCopy[i] !== targetCopy[i]) { + x = thisCopy[i] + y = targetCopy[i] + break + } + } + + if (x < y) return -1 + if (y < x) return 1 + return 0 +} + +// Finds either the first index of `val` in `buffer` at offset >= `byteOffset`, +// OR the last index of `val` in `buffer` at offset <= `byteOffset`. +// +// Arguments: +// - buffer - a Buffer to search +// - val - a string, Buffer, or number +// - byteOffset - an index into `buffer`; will be clamped to an int32 +// - encoding - an optional encoding, relevant is val is a string +// - dir - true for indexOf, false for lastIndexOf +function bidirectionalIndexOf (buffer, val, byteOffset, encoding, dir) { + // Empty buffer means no match + if (buffer.length === 0) return -1 + + // Normalize byteOffset + if (typeof byteOffset === 'string') { + encoding = byteOffset + byteOffset = 0 + } else if (byteOffset > 0x7fffffff) { + byteOffset = 0x7fffffff + } else if (byteOffset < -0x80000000) { + byteOffset = -0x80000000 + } + byteOffset = +byteOffset // Coerce to Number. + if (numberIsNaN(byteOffset)) { + // byteOffset: it it's undefined, null, NaN, "foo", etc, search whole buffer + byteOffset = dir ? 0 : (buffer.length - 1) + } + + // Normalize byteOffset: negative offsets start from the end of the buffer + if (byteOffset < 0) byteOffset = buffer.length + byteOffset + if (byteOffset >= buffer.length) { + if (dir) return -1 + else byteOffset = buffer.length - 1 + } else if (byteOffset < 0) { + if (dir) byteOffset = 0 + else return -1 + } + + // Normalize val + if (typeof val === 'string') { + val = Buffer.from(val, encoding) + } + + // Finally, search either indexOf (if dir is true) or lastIndexOf + if (Buffer.isBuffer(val)) { + // Special case: looking for empty string/buffer always fails + if (val.length === 0) { + return -1 + } + return arrayIndexOf(buffer, val, byteOffset, encoding, dir) + } else if (typeof val === 'number') { + val = val & 0xFF // Search for a byte value [0-255] + if (typeof Uint8Array.prototype.indexOf === 'function') { + if (dir) { + return Uint8Array.prototype.indexOf.call(buffer, val, byteOffset) + } else { + return Uint8Array.prototype.lastIndexOf.call(buffer, val, byteOffset) + } + } + return arrayIndexOf(buffer, [val], byteOffset, encoding, dir) + } + + throw new TypeError('val must be string, number or Buffer') +} + +function arrayIndexOf (arr, val, byteOffset, encoding, dir) { + var indexSize = 1 + var arrLength = arr.length + var valLength = val.length + + if (encoding !== undefined) { + encoding = String(encoding).toLowerCase() + if (encoding === 'ucs2' || encoding === 'ucs-2' || + encoding === 'utf16le' || encoding === 'utf-16le') { + if (arr.length < 2 || val.length < 2) { + return -1 + } + indexSize = 2 + arrLength /= 2 + valLength /= 2 + byteOffset /= 2 + } + } + + function read (buf, i) { + if (indexSize === 1) { + return buf[i] + } else { + return buf.readUInt16BE(i * indexSize) + } + } + + var i + if (dir) { + var foundIndex = -1 + for (i = byteOffset; i < arrLength; i++) { + if (read(arr, i) === read(val, foundIndex === -1 ? 0 : i - foundIndex)) { + if (foundIndex === -1) foundIndex = i + if (i - foundIndex + 1 === valLength) return foundIndex * indexSize + } else { + if (foundIndex !== -1) i -= i - foundIndex + foundIndex = -1 + } + } + } else { + if (byteOffset + valLength > arrLength) byteOffset = arrLength - valLength + for (i = byteOffset; i >= 0; i--) { + var found = true + for (var j = 0; j < valLength; j++) { + if (read(arr, i + j) !== read(val, j)) { + found = false + break + } + } + if (found) return i + } + } + + return -1 +} + +Buffer.prototype.includes = function includes (val, byteOffset, encoding) { + return this.indexOf(val, byteOffset, encoding) !== -1 +} + +Buffer.prototype.indexOf = function indexOf (val, byteOffset, encoding) { + return bidirectionalIndexOf(this, val, byteOffset, encoding, true) +} + +Buffer.prototype.lastIndexOf = function lastIndexOf (val, byteOffset, encoding) { + return bidirectionalIndexOf(this, val, byteOffset, encoding, false) +} + +function hexWrite (buf, string, offset, length) { + offset = Number(offset) || 0 + var remaining = buf.length - offset + if (!length) { + length = remaining + } else { + length = Number(length) + if (length > remaining) { + length = remaining + } + } + + var strLen = string.length + + if (length > strLen / 2) { + length = strLen / 2 + } + for (var i = 0; i < length; ++i) { + var parsed = parseInt(string.substr(i * 2, 2), 16) + if (numberIsNaN(parsed)) return i + buf[offset + i] = parsed + } + return i +} + +function utf8Write (buf, string, offset, length) { + return blitBuffer(utf8ToBytes(string, buf.length - offset), buf, offset, length) +} + +function asciiWrite (buf, string, offset, length) { + return blitBuffer(asciiToBytes(string), buf, offset, length) +} + +function base64Write (buf, string, offset, length) { + return blitBuffer(base64ToBytes(string), buf, offset, length) +} + +function ucs2Write (buf, string, offset, length) { + return blitBuffer(utf16leToBytes(string, buf.length - offset), buf, offset, length) +} + +Buffer.prototype.write = function write (string, offset, length, encoding) { + // Buffer#write(string) + if (offset === undefined) { + encoding = 'utf8' + length = this.length + offset = 0 + // Buffer#write(string, encoding) + } else if (length === undefined && typeof offset === 'string') { + encoding = offset + length = this.length + offset = 0 + // Buffer#write(string, offset[, length][, encoding]) + } else if (isFinite(offset)) { + offset = offset >>> 0 + if (isFinite(length)) { + length = length >>> 0 + if (encoding === undefined) encoding = 'utf8' + } else { + encoding = length + length = undefined + } + } else { + throw new Error( + 'Buffer.write(string, encoding, offset[, length]) is no longer supported' + ) + } + + var remaining = this.length - offset + if (length === undefined || length > remaining) length = remaining + + if ((string.length > 0 && (length < 0 || offset < 0)) || offset > this.length) { + throw new RangeError('Attempt to write outside buffer bounds') + } + + if (!encoding) encoding = 'utf8' + + var loweredCase = false + for (;;) { + switch (encoding) { + case 'hex': + return hexWrite(this, string, offset, length) + + case 'utf8': + case 'utf-8': + return utf8Write(this, string, offset, length) + + case 'ascii': + case 'latin1': + case 'binary': + return asciiWrite(this, string, offset, length) + + case 'base64': + // Warning: maxLength not taken into account in base64Write + return base64Write(this, string, offset, length) + + case 'ucs2': + case 'ucs-2': + case 'utf16le': + case 'utf-16le': + return ucs2Write(this, string, offset, length) + + default: + if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding) + encoding = ('' + encoding).toLowerCase() + loweredCase = true + } + } +} + +Buffer.prototype.toJSON = function toJSON () { + return { + type: 'Buffer', + data: Array.prototype.slice.call(this._arr || this, 0) + } +} + +function base64Slice (buf, start, end) { + if (start === 0 && end === buf.length) { + return base64.fromByteArray(buf) + } else { + return base64.fromByteArray(buf.slice(start, end)) + } +} + +function utf8Slice (buf, start, end) { + end = Math.min(buf.length, end) + var res = [] + + var i = start + while (i < end) { + var firstByte = buf[i] + var codePoint = null + var bytesPerSequence = (firstByte > 0xEF) + ? 4 + : (firstByte > 0xDF) + ? 3 + : (firstByte > 0xBF) + ? 2 + : 1 + + if (i + bytesPerSequence <= end) { + var secondByte, thirdByte, fourthByte, tempCodePoint + + switch (bytesPerSequence) { + case 1: + if (firstByte < 0x80) { + codePoint = firstByte + } + break + case 2: + secondByte = buf[i + 1] + if ((secondByte & 0xC0) === 0x80) { + tempCodePoint = (firstByte & 0x1F) << 0x6 | (secondByte & 0x3F) + if (tempCodePoint > 0x7F) { + codePoint = tempCodePoint + } + } + break + case 3: + secondByte = buf[i + 1] + thirdByte = buf[i + 2] + if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80) { + tempCodePoint = (firstByte & 0xF) << 0xC | (secondByte & 0x3F) << 0x6 | (thirdByte & 0x3F) + if (tempCodePoint > 0x7FF && (tempCodePoint < 0xD800 || tempCodePoint > 0xDFFF)) { + codePoint = tempCodePoint + } + } + break + case 4: + secondByte = buf[i + 1] + thirdByte = buf[i + 2] + fourthByte = buf[i + 3] + if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80 && (fourthByte & 0xC0) === 0x80) { + tempCodePoint = (firstByte & 0xF) << 0x12 | (secondByte & 0x3F) << 0xC | (thirdByte & 0x3F) << 0x6 | (fourthByte & 0x3F) + if (tempCodePoint > 0xFFFF && tempCodePoint < 0x110000) { + codePoint = tempCodePoint + } + } + } + } + + if (codePoint === null) { + // we did not generate a valid codePoint so insert a + // replacement char (U+FFFD) and advance only 1 byte + codePoint = 0xFFFD + bytesPerSequence = 1 + } else if (codePoint > 0xFFFF) { + // encode to utf16 (surrogate pair dance) + codePoint -= 0x10000 + res.push(codePoint >>> 10 & 0x3FF | 0xD800) + codePoint = 0xDC00 | codePoint & 0x3FF + } + + res.push(codePoint) + i += bytesPerSequence + } + + return decodeCodePointsArray(res) +} + +// Based on http://stackoverflow.com/a/22747272/680742, the browser with +// the lowest limit is Chrome, with 0x10000 args. +// We go 1 magnitude less, for safety +var MAX_ARGUMENTS_LENGTH = 0x1000 + +function decodeCodePointsArray (codePoints) { + var len = codePoints.length + if (len <= MAX_ARGUMENTS_LENGTH) { + return String.fromCharCode.apply(String, codePoints) // avoid extra slice() + } + + // Decode in chunks to avoid "call stack size exceeded". + var res = '' + var i = 0 + while (i < len) { + res += String.fromCharCode.apply( + String, + codePoints.slice(i, i += MAX_ARGUMENTS_LENGTH) + ) + } + return res +} + +function asciiSlice (buf, start, end) { + var ret = '' + end = Math.min(buf.length, end) + + for (var i = start; i < end; ++i) { + ret += String.fromCharCode(buf[i] & 0x7F) + } + return ret +} + +function latin1Slice (buf, start, end) { + var ret = '' + end = Math.min(buf.length, end) + + for (var i = start; i < end; ++i) { + ret += String.fromCharCode(buf[i]) + } + return ret +} + +function hexSlice (buf, start, end) { + var len = buf.length + + if (!start || start < 0) start = 0 + if (!end || end < 0 || end > len) end = len + + var out = '' + for (var i = start; i < end; ++i) { + out += hexSliceLookupTable[buf[i]] + } + return out +} + +function utf16leSlice (buf, start, end) { + var bytes = buf.slice(start, end) + var res = '' + // If bytes.length is odd, the last 8 bits must be ignored (same as node.js) + for (var i = 0; i < bytes.length - 1; i += 2) { + res += String.fromCharCode(bytes[i] + (bytes[i + 1] * 256)) + } + return res +} + +Buffer.prototype.slice = function slice (start, end) { + var len = this.length + start = ~~start + end = end === undefined ? len : ~~end + + if (start < 0) { + start += len + if (start < 0) start = 0 + } else if (start > len) { + start = len + } + + if (end < 0) { + end += len + if (end < 0) end = 0 + } else if (end > len) { + end = len + } + + if (end < start) end = start + + var newBuf = this.subarray(start, end) + // Return an augmented `Uint8Array` instance + Object.setPrototypeOf(newBuf, Buffer.prototype) + + return newBuf +} + +/* + * Need to make sure that buffer isn't trying to write out of bounds. + */ +function checkOffset (offset, ext, length) { + if ((offset % 1) !== 0 || offset < 0) throw new RangeError('offset is not uint') + if (offset + ext > length) throw new RangeError('Trying to access beyond buffer length') +} + +Buffer.prototype.readUintLE = +Buffer.prototype.readUIntLE = function readUIntLE (offset, byteLength, noAssert) { + offset = offset >>> 0 + byteLength = byteLength >>> 0 + if (!noAssert) checkOffset(offset, byteLength, this.length) + + var val = this[offset] + var mul = 1 + var i = 0 + while (++i < byteLength && (mul *= 0x100)) { + val += this[offset + i] * mul + } + + return val +} + +Buffer.prototype.readUintBE = +Buffer.prototype.readUIntBE = function readUIntBE (offset, byteLength, noAssert) { + offset = offset >>> 0 + byteLength = byteLength >>> 0 + if (!noAssert) { + checkOffset(offset, byteLength, this.length) + } + + var val = this[offset + --byteLength] + var mul = 1 + while (byteLength > 0 && (mul *= 0x100)) { + val += this[offset + --byteLength] * mul + } + + return val +} + +Buffer.prototype.readUint8 = +Buffer.prototype.readUInt8 = function readUInt8 (offset, noAssert) { + offset = offset >>> 0 + if (!noAssert) checkOffset(offset, 1, this.length) + return this[offset] +} + +Buffer.prototype.readUint16LE = +Buffer.prototype.readUInt16LE = function readUInt16LE (offset, noAssert) { + offset = offset >>> 0 + if (!noAssert) checkOffset(offset, 2, this.length) + return this[offset] | (this[offset + 1] << 8) +} + +Buffer.prototype.readUint16BE = +Buffer.prototype.readUInt16BE = function readUInt16BE (offset, noAssert) { + offset = offset >>> 0 + if (!noAssert) checkOffset(offset, 2, this.length) + return (this[offset] << 8) | this[offset + 1] +} + +Buffer.prototype.readUint32LE = +Buffer.prototype.readUInt32LE = function readUInt32LE (offset, noAssert) { + offset = offset >>> 0 + if (!noAssert) checkOffset(offset, 4, this.length) + + return ((this[offset]) | + (this[offset + 1] << 8) | + (this[offset + 2] << 16)) + + (this[offset + 3] * 0x1000000) +} + +Buffer.prototype.readUint32BE = +Buffer.prototype.readUInt32BE = function readUInt32BE (offset, noAssert) { + offset = offset >>> 0 + if (!noAssert) checkOffset(offset, 4, this.length) + + return (this[offset] * 0x1000000) + + ((this[offset + 1] << 16) | + (this[offset + 2] << 8) | + this[offset + 3]) +} + +Buffer.prototype.readIntLE = function readIntLE (offset, byteLength, noAssert) { + offset = offset >>> 0 + byteLength = byteLength >>> 0 + if (!noAssert) checkOffset(offset, byteLength, this.length) + + var val = this[offset] + var mul = 1 + var i = 0 + while (++i < byteLength && (mul *= 0x100)) { + val += this[offset + i] * mul + } + mul *= 0x80 + + if (val >= mul) val -= Math.pow(2, 8 * byteLength) + + return val +} + +Buffer.prototype.readIntBE = function readIntBE (offset, byteLength, noAssert) { + offset = offset >>> 0 + byteLength = byteLength >>> 0 + if (!noAssert) checkOffset(offset, byteLength, this.length) + + var i = byteLength + var mul = 1 + var val = this[offset + --i] + while (i > 0 && (mul *= 0x100)) { + val += this[offset + --i] * mul + } + mul *= 0x80 + + if (val >= mul) val -= Math.pow(2, 8 * byteLength) + + return val +} + +Buffer.prototype.readInt8 = function readInt8 (offset, noAssert) { + offset = offset >>> 0 + if (!noAssert) checkOffset(offset, 1, this.length) + if (!(this[offset] & 0x80)) return (this[offset]) + return ((0xff - this[offset] + 1) * -1) +} + +Buffer.prototype.readInt16LE = function readInt16LE (offset, noAssert) { + offset = offset >>> 0 + if (!noAssert) checkOffset(offset, 2, this.length) + var val = this[offset] | (this[offset + 1] << 8) + return (val & 0x8000) ? val | 0xFFFF0000 : val +} + +Buffer.prototype.readInt16BE = function readInt16BE (offset, noAssert) { + offset = offset >>> 0 + if (!noAssert) checkOffset(offset, 2, this.length) + var val = this[offset + 1] | (this[offset] << 8) + return (val & 0x8000) ? val | 0xFFFF0000 : val +} + +Buffer.prototype.readInt32LE = function readInt32LE (offset, noAssert) { + offset = offset >>> 0 + if (!noAssert) checkOffset(offset, 4, this.length) + + return (this[offset]) | + (this[offset + 1] << 8) | + (this[offset + 2] << 16) | + (this[offset + 3] << 24) +} + +Buffer.prototype.readInt32BE = function readInt32BE (offset, noAssert) { + offset = offset >>> 0 + if (!noAssert) checkOffset(offset, 4, this.length) + + return (this[offset] << 24) | + (this[offset + 1] << 16) | + (this[offset + 2] << 8) | + (this[offset + 3]) +} + +Buffer.prototype.readFloatLE = function readFloatLE (offset, noAssert) { + offset = offset >>> 0 + if (!noAssert) checkOffset(offset, 4, this.length) + return ieee754.read(this, offset, true, 23, 4) +} + +Buffer.prototype.readFloatBE = function readFloatBE (offset, noAssert) { + offset = offset >>> 0 + if (!noAssert) checkOffset(offset, 4, this.length) + return ieee754.read(this, offset, false, 23, 4) +} + +Buffer.prototype.readDoubleLE = function readDoubleLE (offset, noAssert) { + offset = offset >>> 0 + if (!noAssert) checkOffset(offset, 8, this.length) + return ieee754.read(this, offset, true, 52, 8) +} + +Buffer.prototype.readDoubleBE = function readDoubleBE (offset, noAssert) { + offset = offset >>> 0 + if (!noAssert) checkOffset(offset, 8, this.length) + return ieee754.read(this, offset, false, 52, 8) +} + +function checkInt (buf, value, offset, ext, max, min) { + if (!Buffer.isBuffer(buf)) throw new TypeError('"buffer" argument must be a Buffer instance') + if (value > max || value < min) throw new RangeError('"value" argument is out of bounds') + if (offset + ext > buf.length) throw new RangeError('Index out of range') +} + +Buffer.prototype.writeUintLE = +Buffer.prototype.writeUIntLE = function writeUIntLE (value, offset, byteLength, noAssert) { + value = +value + offset = offset >>> 0 + byteLength = byteLength >>> 0 + if (!noAssert) { + var maxBytes = Math.pow(2, 8 * byteLength) - 1 + checkInt(this, value, offset, byteLength, maxBytes, 0) + } + + var mul = 1 + var i = 0 + this[offset] = value & 0xFF + while (++i < byteLength && (mul *= 0x100)) { + this[offset + i] = (value / mul) & 0xFF + } + + return offset + byteLength +} + +Buffer.prototype.writeUintBE = +Buffer.prototype.writeUIntBE = function writeUIntBE (value, offset, byteLength, noAssert) { + value = +value + offset = offset >>> 0 + byteLength = byteLength >>> 0 + if (!noAssert) { + var maxBytes = Math.pow(2, 8 * byteLength) - 1 + checkInt(this, value, offset, byteLength, maxBytes, 0) + } + + var i = byteLength - 1 + var mul = 1 + this[offset + i] = value & 0xFF + while (--i >= 0 && (mul *= 0x100)) { + this[offset + i] = (value / mul) & 0xFF + } + + return offset + byteLength +} + +Buffer.prototype.writeUint8 = +Buffer.prototype.writeUInt8 = function writeUInt8 (value, offset, noAssert) { + value = +value + offset = offset >>> 0 + if (!noAssert) checkInt(this, value, offset, 1, 0xff, 0) + this[offset] = (value & 0xff) + return offset + 1 +} + +Buffer.prototype.writeUint16LE = +Buffer.prototype.writeUInt16LE = function writeUInt16LE (value, offset, noAssert) { + value = +value + offset = offset >>> 0 + if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0) + this[offset] = (value & 0xff) + this[offset + 1] = (value >>> 8) + return offset + 2 +} + +Buffer.prototype.writeUint16BE = +Buffer.prototype.writeUInt16BE = function writeUInt16BE (value, offset, noAssert) { + value = +value + offset = offset >>> 0 + if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0) + this[offset] = (value >>> 8) + this[offset + 1] = (value & 0xff) + return offset + 2 +} + +Buffer.prototype.writeUint32LE = +Buffer.prototype.writeUInt32LE = function writeUInt32LE (value, offset, noAssert) { + value = +value + offset = offset >>> 0 + if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0) + this[offset + 3] = (value >>> 24) + this[offset + 2] = (value >>> 16) + this[offset + 1] = (value >>> 8) + this[offset] = (value & 0xff) + return offset + 4 +} + +Buffer.prototype.writeUint32BE = +Buffer.prototype.writeUInt32BE = function writeUInt32BE (value, offset, noAssert) { + value = +value + offset = offset >>> 0 + if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0) + this[offset] = (value >>> 24) + this[offset + 1] = (value >>> 16) + this[offset + 2] = (value >>> 8) + this[offset + 3] = (value & 0xff) + return offset + 4 +} + +Buffer.prototype.writeIntLE = function writeIntLE (value, offset, byteLength, noAssert) { + value = +value + offset = offset >>> 0 + if (!noAssert) { + var limit = Math.pow(2, (8 * byteLength) - 1) + + checkInt(this, value, offset, byteLength, limit - 1, -limit) + } + + var i = 0 + var mul = 1 + var sub = 0 + this[offset] = value & 0xFF + while (++i < byteLength && (mul *= 0x100)) { + if (value < 0 && sub === 0 && this[offset + i - 1] !== 0) { + sub = 1 + } + this[offset + i] = ((value / mul) >> 0) - sub & 0xFF + } + + return offset + byteLength +} + +Buffer.prototype.writeIntBE = function writeIntBE (value, offset, byteLength, noAssert) { + value = +value + offset = offset >>> 0 + if (!noAssert) { + var limit = Math.pow(2, (8 * byteLength) - 1) + + checkInt(this, value, offset, byteLength, limit - 1, -limit) + } + + var i = byteLength - 1 + var mul = 1 + var sub = 0 + this[offset + i] = value & 0xFF + while (--i >= 0 && (mul *= 0x100)) { + if (value < 0 && sub === 0 && this[offset + i + 1] !== 0) { + sub = 1 + } + this[offset + i] = ((value / mul) >> 0) - sub & 0xFF + } + + return offset + byteLength +} + +Buffer.prototype.writeInt8 = function writeInt8 (value, offset, noAssert) { + value = +value + offset = offset >>> 0 + if (!noAssert) checkInt(this, value, offset, 1, 0x7f, -0x80) + if (value < 0) value = 0xff + value + 1 + this[offset] = (value & 0xff) + return offset + 1 +} + +Buffer.prototype.writeInt16LE = function writeInt16LE (value, offset, noAssert) { + value = +value + offset = offset >>> 0 + if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000) + this[offset] = (value & 0xff) + this[offset + 1] = (value >>> 8) + return offset + 2 +} + +Buffer.prototype.writeInt16BE = function writeInt16BE (value, offset, noAssert) { + value = +value + offset = offset >>> 0 + if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000) + this[offset] = (value >>> 8) + this[offset + 1] = (value & 0xff) + return offset + 2 +} + +Buffer.prototype.writeInt32LE = function writeInt32LE (value, offset, noAssert) { + value = +value + offset = offset >>> 0 + if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000) + this[offset] = (value & 0xff) + this[offset + 1] = (value >>> 8) + this[offset + 2] = (value >>> 16) + this[offset + 3] = (value >>> 24) + return offset + 4 +} + +Buffer.prototype.writeInt32BE = function writeInt32BE (value, offset, noAssert) { + value = +value + offset = offset >>> 0 + if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000) + if (value < 0) value = 0xffffffff + value + 1 + this[offset] = (value >>> 24) + this[offset + 1] = (value >>> 16) + this[offset + 2] = (value >>> 8) + this[offset + 3] = (value & 0xff) + return offset + 4 +} + +function checkIEEE754 (buf, value, offset, ext, max, min) { + if (offset + ext > buf.length) throw new RangeError('Index out of range') + if (offset < 0) throw new RangeError('Index out of range') +} + +function writeFloat (buf, value, offset, littleEndian, noAssert) { + value = +value + offset = offset >>> 0 + if (!noAssert) { + checkIEEE754(buf, value, offset, 4, 3.4028234663852886e+38, -3.4028234663852886e+38) + } + ieee754.write(buf, value, offset, littleEndian, 23, 4) + return offset + 4 +} + +Buffer.prototype.writeFloatLE = function writeFloatLE (value, offset, noAssert) { + return writeFloat(this, value, offset, true, noAssert) +} + +Buffer.prototype.writeFloatBE = function writeFloatBE (value, offset, noAssert) { + return writeFloat(this, value, offset, false, noAssert) +} + +function writeDouble (buf, value, offset, littleEndian, noAssert) { + value = +value + offset = offset >>> 0 + if (!noAssert) { + checkIEEE754(buf, value, offset, 8, 1.7976931348623157E+308, -1.7976931348623157E+308) + } + ieee754.write(buf, value, offset, littleEndian, 52, 8) + return offset + 8 +} + +Buffer.prototype.writeDoubleLE = function writeDoubleLE (value, offset, noAssert) { + return writeDouble(this, value, offset, true, noAssert) +} + +Buffer.prototype.writeDoubleBE = function writeDoubleBE (value, offset, noAssert) { + return writeDouble(this, value, offset, false, noAssert) +} + +// copy(targetBuffer, targetStart=0, sourceStart=0, sourceEnd=buffer.length) +Buffer.prototype.copy = function copy (target, targetStart, start, end) { + if (!Buffer.isBuffer(target)) throw new TypeError('argument should be a Buffer') + if (!start) start = 0 + if (!end && end !== 0) end = this.length + if (targetStart >= target.length) targetStart = target.length + if (!targetStart) targetStart = 0 + if (end > 0 && end < start) end = start + + // Copy 0 bytes; we're done + if (end === start) return 0 + if (target.length === 0 || this.length === 0) return 0 + + // Fatal error conditions + if (targetStart < 0) { + throw new RangeError('targetStart out of bounds') + } + if (start < 0 || start >= this.length) throw new RangeError('Index out of range') + if (end < 0) throw new RangeError('sourceEnd out of bounds') + + // Are we oob? + if (end > this.length) end = this.length + if (target.length - targetStart < end - start) { + end = target.length - targetStart + start + } + + var len = end - start + + if (this === target && typeof Uint8Array.prototype.copyWithin === 'function') { + // Use built-in when available, missing from IE11 + this.copyWithin(targetStart, start, end) + } else { + Uint8Array.prototype.set.call( + target, + this.subarray(start, end), + targetStart + ) + } + + return len +} + +// Usage: +// buffer.fill(number[, offset[, end]]) +// buffer.fill(buffer[, offset[, end]]) +// buffer.fill(string[, offset[, end]][, encoding]) +Buffer.prototype.fill = function fill (val, start, end, encoding) { + // Handle string cases: + if (typeof val === 'string') { + if (typeof start === 'string') { + encoding = start + start = 0 + end = this.length + } else if (typeof end === 'string') { + encoding = end + end = this.length + } + if (encoding !== undefined && typeof encoding !== 'string') { + throw new TypeError('encoding must be a string') + } + if (typeof encoding === 'string' && !Buffer.isEncoding(encoding)) { + throw new TypeError('Unknown encoding: ' + encoding) + } + if (val.length === 1) { + var code = val.charCodeAt(0) + if ((encoding === 'utf8' && code < 128) || + encoding === 'latin1') { + // Fast path: If `val` fits into a single byte, use that numeric value. + val = code + } + } + } else if (typeof val === 'number') { + val = val & 255 + } else if (typeof val === 'boolean') { + val = Number(val) + } + + // Invalid ranges are not set to a default, so can range check early. + if (start < 0 || this.length < start || this.length < end) { + throw new RangeError('Out of range index') + } + + if (end <= start) { + return this + } + + start = start >>> 0 + end = end === undefined ? this.length : end >>> 0 + + if (!val) val = 0 + + var i + if (typeof val === 'number') { + for (i = start; i < end; ++i) { + this[i] = val + } + } else { + var bytes = Buffer.isBuffer(val) + ? val + : Buffer.from(val, encoding) + var len = bytes.length + if (len === 0) { + throw new TypeError('The value "' + val + + '" is invalid for argument "value"') + } + for (i = 0; i < end - start; ++i) { + this[i + start] = bytes[i % len] + } + } + + return this +} + +// HELPER FUNCTIONS +// ================ + +var INVALID_BASE64_RE = /[^+/0-9A-Za-z-_]/g + +function base64clean (str) { + // Node takes equal signs as end of the Base64 encoding + str = str.split('=')[0] + // Node strips out invalid characters like \n and \t from the string, base64-js does not + str = str.trim().replace(INVALID_BASE64_RE, '') + // Node converts strings with length < 2 to '' + if (str.length < 2) return '' + // Node allows for non-padded base64 strings (missing trailing ===), base64-js does not + while (str.length % 4 !== 0) { + str = str + '=' + } + return str +} + +function utf8ToBytes (string, units) { + units = units || Infinity + var codePoint + var length = string.length + var leadSurrogate = null + var bytes = [] + + for (var i = 0; i < length; ++i) { + codePoint = string.charCodeAt(i) + + // is surrogate component + if (codePoint > 0xD7FF && codePoint < 0xE000) { + // last char was a lead + if (!leadSurrogate) { + // no lead yet + if (codePoint > 0xDBFF) { + // unexpected trail + if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD) + continue + } else if (i + 1 === length) { + // unpaired lead + if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD) + continue + } + + // valid lead + leadSurrogate = codePoint + + continue + } + + // 2 leads in a row + if (codePoint < 0xDC00) { + if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD) + leadSurrogate = codePoint + continue + } + + // valid surrogate pair + codePoint = (leadSurrogate - 0xD800 << 10 | codePoint - 0xDC00) + 0x10000 + } else if (leadSurrogate) { + // valid bmp char, but last char was a lead + if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD) + } + + leadSurrogate = null + + // encode utf8 + if (codePoint < 0x80) { + if ((units -= 1) < 0) break + bytes.push(codePoint) + } else if (codePoint < 0x800) { + if ((units -= 2) < 0) break + bytes.push( + codePoint >> 0x6 | 0xC0, + codePoint & 0x3F | 0x80 + ) + } else if (codePoint < 0x10000) { + if ((units -= 3) < 0) break + bytes.push( + codePoint >> 0xC | 0xE0, + codePoint >> 0x6 & 0x3F | 0x80, + codePoint & 0x3F | 0x80 + ) + } else if (codePoint < 0x110000) { + if ((units -= 4) < 0) break + bytes.push( + codePoint >> 0x12 | 0xF0, + codePoint >> 0xC & 0x3F | 0x80, + codePoint >> 0x6 & 0x3F | 0x80, + codePoint & 0x3F | 0x80 + ) + } else { + throw new Error('Invalid code point') + } + } + + return bytes +} + +function asciiToBytes (str) { + var byteArray = [] + for (var i = 0; i < str.length; ++i) { + // Node's code seems to be doing this and not & 0x7F.. + byteArray.push(str.charCodeAt(i) & 0xFF) + } + return byteArray +} + +function utf16leToBytes (str, units) { + var c, hi, lo + var byteArray = [] + for (var i = 0; i < str.length; ++i) { + if ((units -= 2) < 0) break + + c = str.charCodeAt(i) + hi = c >> 8 + lo = c % 256 + byteArray.push(lo) + byteArray.push(hi) + } + + return byteArray +} + +function base64ToBytes (str) { + return base64.toByteArray(base64clean(str)) +} + +function blitBuffer (src, dst, offset, length) { + for (var i = 0; i < length; ++i) { + if ((i + offset >= dst.length) || (i >= src.length)) break + dst[i + offset] = src[i] + } + return i +} + +// ArrayBuffer or Uint8Array objects from other contexts (i.e. iframes) do not pass +// the `instanceof` check but they should be treated as of that type. +// See: https://github.com/feross/buffer/issues/166 +function isInstance (obj, type) { + return obj instanceof type || + (obj != null && obj.constructor != null && obj.constructor.name != null && + obj.constructor.name === type.name) +} +function numberIsNaN (obj) { + // For IE11 support + return obj !== obj // eslint-disable-line no-self-compare +} + +// Create lookup table for `toString('hex')` +// See: https://github.com/feross/buffer/issues/219 +var hexSliceLookupTable = (function () { + var alphabet = '0123456789abcdef' + var table = new Array(256) + for (var i = 0; i < 16; ++i) { + var i16 = i * 16 + for (var j = 0; j < 16; ++j) { + table[i16 + j] = alphabet[i] + alphabet[j] + } + } + return table +})() diff --git a/ts-ticket-office-service/node_modules/buffer/package.json b/ts-ticket-office-service/node_modules/buffer/package.json new file mode 100644 index 000000000..3b1b4986f --- /dev/null +++ b/ts-ticket-office-service/node_modules/buffer/package.json @@ -0,0 +1,96 @@ +{ + "name": "buffer", + "description": "Node.js Buffer API, for the browser", + "version": "5.7.1", + "author": { + "name": "Feross Aboukhadijeh", + "email": "feross@feross.org", + "url": "https://feross.org" + }, + "bugs": { + "url": "https://github.com/feross/buffer/issues" + }, + "contributors": [ + "Romain Beauxis ", + "James Halliday " + ], + "dependencies": { + "base64-js": "^1.3.1", + "ieee754": "^1.1.13" + }, + "devDependencies": { + "airtap": "^3.0.0", + "benchmark": "^2.1.4", + "browserify": "^17.0.0", + "concat-stream": "^2.0.0", + "hyperquest": "^2.1.3", + "is-buffer": "^2.0.4", + "is-nan": "^1.3.0", + "split": "^1.0.1", + "standard": "*", + "tape": "^5.0.1", + "through2": "^4.0.2", + "uglify-js": "^3.11.3" + }, + "homepage": "https://github.com/feross/buffer", + "jspm": { + "map": { + "./index.js": { + "node": "@node/buffer" + } + } + }, + "keywords": [ + "arraybuffer", + "browser", + "browserify", + "buffer", + "compatible", + "dataview", + "uint8array" + ], + "license": "MIT", + "main": "index.js", + "types": "index.d.ts", + "repository": { + "type": "git", + "url": "git://github.com/feross/buffer.git" + }, + "scripts": { + "perf": "browserify --debug perf/bracket-notation.js > perf/bundle.js && open perf/index.html", + "perf-node": "node perf/bracket-notation.js && node perf/concat.js && node perf/copy-big.js && node perf/copy.js && node perf/new-big.js && node perf/new.js && node perf/readDoubleBE.js && node perf/readFloatBE.js && node perf/readUInt32LE.js && node perf/slice.js && node perf/writeFloatBE.js", + "size": "browserify -r ./ | uglifyjs -c -m | gzip | wc -c", + "test": "standard && node ./bin/test.js", + "test-browser-es5": "airtap -- test/*.js", + "test-browser-es5-local": "airtap --local -- test/*.js", + "test-browser-es6": "airtap -- test/*.js test/node/*.js", + "test-browser-es6-local": "airtap --local -- test/*.js test/node/*.js", + "test-node": "tape test/*.js test/node/*.js", + "update-authors": "./bin/update-authors.sh" + }, + "standard": { + "ignore": [ + "test/node/**/*.js", + "test/common.js", + "test/_polyfill.js", + "perf/**/*.js" + ], + "globals": [ + "SharedArrayBuffer" + ] + }, + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/feross" + }, + { + "type": "patreon", + "url": "https://www.patreon.com/feross" + }, + { + "type": "consulting", + "url": "https://feross.org/support" + } + ] +} diff --git a/ts-ticket-office-service/node_modules/clean-css/bin/cleancss b/ts-ticket-office-service/node_modules/clean-css/bin/cleancss old mode 100644 new mode 100755 diff --git a/ts-ticket-office-service/node_modules/denque/CHANGELOG.md b/ts-ticket-office-service/node_modules/denque/CHANGELOG.md new file mode 100644 index 000000000..391a1f514 --- /dev/null +++ b/ts-ticket-office-service/node_modules/denque/CHANGELOG.md @@ -0,0 +1,29 @@ +## 2.1.0 + + - fix: issue where `clear()` is still keeping references to the elements (#47) + - refactor: performance optimizations for growth and array copy (#43) + - refactor: performance optimizations for toArray and fromArray (#46) + - test: add additional benchmarks for queue growth and `toArray` (#45) + +## 2.0.1 + + - fix(types): incorrect return type on `size()` + +## 2.0.0 + + - fix!: `push` & `unshift` now accept `undefined` values to match behaviour of `Array` (fixes #25) (#35) + - This is only a **BREAKING** change if you are currently expecting `push(undefined)` and `unshift(undefined)` to do + nothing - the new behaviour now correctly adds undefined values to the queue. + - **Note**: behaviour of `push()` & `unshift()` (no arguments) remains unchanged (nothing gets added to the queue). + - **Note**: If you need to differentiate between `undefined` values in the queue and the return value of `pop()` then + check the queue `.length` before popping. + - fix: incorrect methods in types definition file + +## 1.5.1 + + - perf: minor performance tweak when growing queue size (#29) + +## 1.5.0 + + - feat: adds capacity option for circular buffers (#27) + diff --git a/ts-ticket-office-service/node_modules/require_optional/LICENSE b/ts-ticket-office-service/node_modules/denque/LICENSE similarity index 99% rename from ts-ticket-office-service/node_modules/require_optional/LICENSE rename to ts-ticket-office-service/node_modules/denque/LICENSE index 8dada3eda..c9cde9201 100644 --- a/ts-ticket-office-service/node_modules/require_optional/LICENSE +++ b/ts-ticket-office-service/node_modules/denque/LICENSE @@ -178,7 +178,7 @@ APPENDIX: How to apply the Apache License to your work. To apply the Apache License to your work, attach the following - boilerplate notice, with the fields enclosed by brackets "{}" + boilerplate notice, with the fields enclosed by brackets "[]" replaced with your own identifying information. (Don't include the brackets!) The text should be enclosed in the appropriate comment syntax for the file format. We also recommend that a @@ -186,7 +186,7 @@ same "printed page" as the copyright notice for easier identification within third-party archives. - Copyright {yyyy} {name of copyright owner} + Copyright 2018-present Invertase Limited Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/ts-ticket-office-service/node_modules/denque/README.md b/ts-ticket-office-service/node_modules/denque/README.md new file mode 100644 index 000000000..3c645d39c --- /dev/null +++ b/ts-ticket-office-service/node_modules/denque/README.md @@ -0,0 +1,77 @@ +

+

Denque

+

+ +

+ NPM downloads + NPM version + Tests status + Coverage + License + Follow on Twitter +

+ +Denque is a well tested, extremely fast and lightweight [double-ended queue](http://en.wikipedia.org/wiki/Double-ended_queue) +implementation with zero dependencies and includes TypeScript types. + +Double-ended queues can also be used as a: + +- [Stack](http://en.wikipedia.org/wiki/Stack_\(abstract_data_type\)) +- [Queue](http://en.wikipedia.org/wiki/Queue_\(data_structure\)) + +This implementation is currently the fastest available, even faster than `double-ended-queue`, see the [benchmarks](https://docs.page/invertase/denque/benchmarks). + +Every queue operation is done at a constant `O(1)` - including random access from `.peekAt(index)`. + +**Works on all node versions >= v0.10** + +## Quick Start + +Install the package: + +```bash +npm install denque +``` + +Create and consume a queue: + +```js +const Denque = require("denque"); + +const denque = new Denque([1,2,3,4]); +denque.shift(); // 1 +denque.pop(); // 4 +``` + + +See the [API reference documentation](https://docs.page/invertase/denque/api) for more examples. + +--- + +## Who's using it? + +- [Kafka Node.js client](https://www.npmjs.com/package/kafka-node) +- [MariaDB Node.js client](https://www.npmjs.com/package/mariadb) +- [MongoDB Node.js client](https://www.npmjs.com/package/mongodb) +- [MySQL Node.js client](https://www.npmjs.com/package/mysql2) +- [Redis Node.js clients](https://www.npmjs.com/package/redis) + +... and [many more](https://www.npmjs.com/browse/depended/denque). + + +--- + +## License + +- See [LICENSE](/LICENSE) + +--- + +

+ + + +

+ Built and maintained by Invertase. +

+

diff --git a/ts-ticket-office-service/node_modules/denque/index.d.ts b/ts-ticket-office-service/node_modules/denque/index.d.ts new file mode 100644 index 000000000..e125dd471 --- /dev/null +++ b/ts-ticket-office-service/node_modules/denque/index.d.ts @@ -0,0 +1,47 @@ +declare class Denque { + length: number; + + constructor(); + + constructor(array: T[]); + + constructor(array: T[], options: IDenqueOptions); + + push(item: T): number; + + unshift(item: T): number; + + pop(): T | undefined; + + shift(): T | undefined; + + peekBack(): T | undefined; + + peekFront(): T | undefined; + + peekAt(index: number): T | undefined; + + get(index: number): T | undefined; + + remove(index: number, count: number): T[]; + + removeOne(index: number): T | undefined; + + splice(index: number, count: number, ...item: T[]): T[] | undefined; + + isEmpty(): boolean; + + clear(): void; + + size(): number; + + toString(): string; + + toArray(): T[]; +} + +interface IDenqueOptions { + capacity?: number +} + +export = Denque; diff --git a/ts-ticket-office-service/node_modules/denque/index.js b/ts-ticket-office-service/node_modules/denque/index.js new file mode 100644 index 000000000..6b2e9d862 --- /dev/null +++ b/ts-ticket-office-service/node_modules/denque/index.js @@ -0,0 +1,481 @@ +'use strict'; + +/** + * Custom implementation of a double ended queue. + */ +function Denque(array, options) { + var options = options || {}; + this._capacity = options.capacity; + + this._head = 0; + this._tail = 0; + + if (Array.isArray(array)) { + this._fromArray(array); + } else { + this._capacityMask = 0x3; + this._list = new Array(4); + } +} + +/** + * -------------- + * PUBLIC API + * ------------- + */ + +/** + * Returns the item at the specified index from the list. + * 0 is the first element, 1 is the second, and so on... + * Elements at negative values are that many from the end: -1 is one before the end + * (the last element), -2 is two before the end (one before last), etc. + * @param index + * @returns {*} + */ +Denque.prototype.peekAt = function peekAt(index) { + var i = index; + // expect a number or return undefined + if ((i !== (i | 0))) { + return void 0; + } + var len = this.size(); + if (i >= len || i < -len) return undefined; + if (i < 0) i += len; + i = (this._head + i) & this._capacityMask; + return this._list[i]; +}; + +/** + * Alias for peekAt() + * @param i + * @returns {*} + */ +Denque.prototype.get = function get(i) { + return this.peekAt(i); +}; + +/** + * Returns the first item in the list without removing it. + * @returns {*} + */ +Denque.prototype.peek = function peek() { + if (this._head === this._tail) return undefined; + return this._list[this._head]; +}; + +/** + * Alias for peek() + * @returns {*} + */ +Denque.prototype.peekFront = function peekFront() { + return this.peek(); +}; + +/** + * Returns the item that is at the back of the queue without removing it. + * Uses peekAt(-1) + */ +Denque.prototype.peekBack = function peekBack() { + return this.peekAt(-1); +}; + +/** + * Returns the current length of the queue + * @return {Number} + */ +Object.defineProperty(Denque.prototype, 'length', { + get: function length() { + return this.size(); + } +}); + +/** + * Return the number of items on the list, or 0 if empty. + * @returns {number} + */ +Denque.prototype.size = function size() { + if (this._head === this._tail) return 0; + if (this._head < this._tail) return this._tail - this._head; + else return this._capacityMask + 1 - (this._head - this._tail); +}; + +/** + * Add an item at the beginning of the list. + * @param item + */ +Denque.prototype.unshift = function unshift(item) { + if (arguments.length === 0) return this.size(); + var len = this._list.length; + this._head = (this._head - 1 + len) & this._capacityMask; + this._list[this._head] = item; + if (this._tail === this._head) this._growArray(); + if (this._capacity && this.size() > this._capacity) this.pop(); + if (this._head < this._tail) return this._tail - this._head; + else return this._capacityMask + 1 - (this._head - this._tail); +}; + +/** + * Remove and return the first item on the list, + * Returns undefined if the list is empty. + * @returns {*} + */ +Denque.prototype.shift = function shift() { + var head = this._head; + if (head === this._tail) return undefined; + var item = this._list[head]; + this._list[head] = undefined; + this._head = (head + 1) & this._capacityMask; + if (head < 2 && this._tail > 10000 && this._tail <= this._list.length >>> 2) this._shrinkArray(); + return item; +}; + +/** + * Add an item to the bottom of the list. + * @param item + */ +Denque.prototype.push = function push(item) { + if (arguments.length === 0) return this.size(); + var tail = this._tail; + this._list[tail] = item; + this._tail = (tail + 1) & this._capacityMask; + if (this._tail === this._head) { + this._growArray(); + } + if (this._capacity && this.size() > this._capacity) { + this.shift(); + } + if (this._head < this._tail) return this._tail - this._head; + else return this._capacityMask + 1 - (this._head - this._tail); +}; + +/** + * Remove and return the last item on the list. + * Returns undefined if the list is empty. + * @returns {*} + */ +Denque.prototype.pop = function pop() { + var tail = this._tail; + if (tail === this._head) return undefined; + var len = this._list.length; + this._tail = (tail - 1 + len) & this._capacityMask; + var item = this._list[this._tail]; + this._list[this._tail] = undefined; + if (this._head < 2 && tail > 10000 && tail <= len >>> 2) this._shrinkArray(); + return item; +}; + +/** + * Remove and return the item at the specified index from the list. + * Returns undefined if the list is empty. + * @param index + * @returns {*} + */ +Denque.prototype.removeOne = function removeOne(index) { + var i = index; + // expect a number or return undefined + if ((i !== (i | 0))) { + return void 0; + } + if (this._head === this._tail) return void 0; + var size = this.size(); + var len = this._list.length; + if (i >= size || i < -size) return void 0; + if (i < 0) i += size; + i = (this._head + i) & this._capacityMask; + var item = this._list[i]; + var k; + if (index < size / 2) { + for (k = index; k > 0; k--) { + this._list[i] = this._list[i = (i - 1 + len) & this._capacityMask]; + } + this._list[i] = void 0; + this._head = (this._head + 1 + len) & this._capacityMask; + } else { + for (k = size - 1 - index; k > 0; k--) { + this._list[i] = this._list[i = (i + 1 + len) & this._capacityMask]; + } + this._list[i] = void 0; + this._tail = (this._tail - 1 + len) & this._capacityMask; + } + return item; +}; + +/** + * Remove number of items from the specified index from the list. + * Returns array of removed items. + * Returns undefined if the list is empty. + * @param index + * @param count + * @returns {array} + */ +Denque.prototype.remove = function remove(index, count) { + var i = index; + var removed; + var del_count = count; + // expect a number or return undefined + if ((i !== (i | 0))) { + return void 0; + } + if (this._head === this._tail) return void 0; + var size = this.size(); + var len = this._list.length; + if (i >= size || i < -size || count < 1) return void 0; + if (i < 0) i += size; + if (count === 1 || !count) { + removed = new Array(1); + removed[0] = this.removeOne(i); + return removed; + } + if (i === 0 && i + count >= size) { + removed = this.toArray(); + this.clear(); + return removed; + } + if (i + count > size) count = size - i; + var k; + removed = new Array(count); + for (k = 0; k < count; k++) { + removed[k] = this._list[(this._head + i + k) & this._capacityMask]; + } + i = (this._head + i) & this._capacityMask; + if (index + count === size) { + this._tail = (this._tail - count + len) & this._capacityMask; + for (k = count; k > 0; k--) { + this._list[i = (i + 1 + len) & this._capacityMask] = void 0; + } + return removed; + } + if (index === 0) { + this._head = (this._head + count + len) & this._capacityMask; + for (k = count - 1; k > 0; k--) { + this._list[i = (i + 1 + len) & this._capacityMask] = void 0; + } + return removed; + } + if (i < size / 2) { + this._head = (this._head + index + count + len) & this._capacityMask; + for (k = index; k > 0; k--) { + this.unshift(this._list[i = (i - 1 + len) & this._capacityMask]); + } + i = (this._head - 1 + len) & this._capacityMask; + while (del_count > 0) { + this._list[i = (i - 1 + len) & this._capacityMask] = void 0; + del_count--; + } + if (index < 0) this._tail = i; + } else { + this._tail = i; + i = (i + count + len) & this._capacityMask; + for (k = size - (count + index); k > 0; k--) { + this.push(this._list[i++]); + } + i = this._tail; + while (del_count > 0) { + this._list[i = (i + 1 + len) & this._capacityMask] = void 0; + del_count--; + } + } + if (this._head < 2 && this._tail > 10000 && this._tail <= len >>> 2) this._shrinkArray(); + return removed; +}; + +/** + * Native splice implementation. + * Remove number of items from the specified index from the list and/or add new elements. + * Returns array of removed items or empty array if count == 0. + * Returns undefined if the list is empty. + * + * @param index + * @param count + * @param {...*} [elements] + * @returns {array} + */ +Denque.prototype.splice = function splice(index, count) { + var i = index; + // expect a number or return undefined + if ((i !== (i | 0))) { + return void 0; + } + var size = this.size(); + if (i < 0) i += size; + if (i > size) return void 0; + if (arguments.length > 2) { + var k; + var temp; + var removed; + var arg_len = arguments.length; + var len = this._list.length; + var arguments_index = 2; + if (!size || i < size / 2) { + temp = new Array(i); + for (k = 0; k < i; k++) { + temp[k] = this._list[(this._head + k) & this._capacityMask]; + } + if (count === 0) { + removed = []; + if (i > 0) { + this._head = (this._head + i + len) & this._capacityMask; + } + } else { + removed = this.remove(i, count); + this._head = (this._head + i + len) & this._capacityMask; + } + while (arg_len > arguments_index) { + this.unshift(arguments[--arg_len]); + } + for (k = i; k > 0; k--) { + this.unshift(temp[k - 1]); + } + } else { + temp = new Array(size - (i + count)); + var leng = temp.length; + for (k = 0; k < leng; k++) { + temp[k] = this._list[(this._head + i + count + k) & this._capacityMask]; + } + if (count === 0) { + removed = []; + if (i != size) { + this._tail = (this._head + i + len) & this._capacityMask; + } + } else { + removed = this.remove(i, count); + this._tail = (this._tail - leng + len) & this._capacityMask; + } + while (arguments_index < arg_len) { + this.push(arguments[arguments_index++]); + } + for (k = 0; k < leng; k++) { + this.push(temp[k]); + } + } + return removed; + } else { + return this.remove(i, count); + } +}; + +/** + * Soft clear - does not reset capacity. + */ +Denque.prototype.clear = function clear() { + this._list = new Array(this._list.length); + this._head = 0; + this._tail = 0; +}; + +/** + * Returns true or false whether the list is empty. + * @returns {boolean} + */ +Denque.prototype.isEmpty = function isEmpty() { + return this._head === this._tail; +}; + +/** + * Returns an array of all queue items. + * @returns {Array} + */ +Denque.prototype.toArray = function toArray() { + return this._copyArray(false); +}; + +/** + * ------------- + * INTERNALS + * ------------- + */ + +/** + * Fills the queue with items from an array + * For use in the constructor + * @param array + * @private + */ +Denque.prototype._fromArray = function _fromArray(array) { + var length = array.length; + var capacity = this._nextPowerOf2(length); + + this._list = new Array(capacity); + this._capacityMask = capacity - 1; + this._tail = length; + + for (var i = 0; i < length; i++) this._list[i] = array[i]; +}; + +/** + * + * @param fullCopy + * @param size Initialize the array with a specific size. Will default to the current list size + * @returns {Array} + * @private + */ +Denque.prototype._copyArray = function _copyArray(fullCopy, size) { + var src = this._list; + var capacity = src.length; + var length = this.length; + size = size | length; + + // No prealloc requested and the buffer is contiguous + if (size == length && this._head < this._tail) { + // Simply do a fast slice copy + return this._list.slice(this._head, this._tail); + } + + var dest = new Array(size); + + var k = 0; + var i; + if (fullCopy || this._head > this._tail) { + for (i = this._head; i < capacity; i++) dest[k++] = src[i]; + for (i = 0; i < this._tail; i++) dest[k++] = src[i]; + } else { + for (i = this._head; i < this._tail; i++) dest[k++] = src[i]; + } + + return dest; +} + +/** + * Grows the internal list array. + * @private + */ +Denque.prototype._growArray = function _growArray() { + if (this._head != 0) { + // double array size and copy existing data, head to end, then beginning to tail. + var newList = this._copyArray(true, this._list.length << 1); + + this._tail = this._list.length; + this._head = 0; + + this._list = newList; + } else { + this._tail = this._list.length; + this._list.length <<= 1; + } + + this._capacityMask = (this._capacityMask << 1) | 1; +}; + +/** + * Shrinks the internal list array. + * @private + */ +Denque.prototype._shrinkArray = function _shrinkArray() { + this._list.length >>>= 1; + this._capacityMask >>>= 1; +}; + +/** + * Find the next power of 2, at least 4 + * @private + * @param {number} num + * @returns {number} + */ +Denque.prototype._nextPowerOf2 = function _nextPowerOf2(num) { + var log2 = Math.log(num) / Math.log(2); + var nextPow2 = 1 << (log2 + 1); + + return Math.max(nextPow2, 4); +} + +module.exports = Denque; diff --git a/ts-ticket-office-service/node_modules/denque/package.json b/ts-ticket-office-service/node_modules/denque/package.json new file mode 100644 index 000000000..a63591030 --- /dev/null +++ b/ts-ticket-office-service/node_modules/denque/package.json @@ -0,0 +1,58 @@ +{ + "name": "denque", + "version": "2.1.0", + "description": "The fastest javascript implementation of a double-ended queue. Used by the official Redis, MongoDB, MariaDB & MySQL libraries for Node.js and many other libraries. Maintains compatability with deque.", + "main": "index.js", + "engines": { + "node": ">=0.10" + }, + "keywords": [ + "data-structure", + "data-structures", + "queue", + "double", + "end", + "ended", + "deque", + "denque", + "double-ended-queue" + ], + "scripts": { + "test": "istanbul cover --report lcov _mocha && npm run typescript", + "coveralls": "cat ./coverage/lcov.info | coveralls", + "typescript": "tsc --project ./test/type/tsconfig.json", + "benchmark_thousand": "node benchmark/thousand", + "benchmark_2mil": "node benchmark/two_million", + "benchmark_splice": "node benchmark/splice", + "benchmark_remove": "node benchmark/remove", + "benchmark_removeOne": "node benchmark/removeOne", + "benchmark_growth": "node benchmark/growth", + "benchmark_toArray": "node benchmark/toArray", + "benchmark_fromArray": "node benchmark/fromArray" + }, + "repository": { + "type": "git", + "url": "git+https://github.com/invertase/denque.git" + }, + "license": "Apache-2.0", + "author": { + "name": "Invertase", + "email": "oss@invertase.io", + "url": "http://github.com/invertase/" + }, + "contributors": [ + "Mike Diarmid (Salakar) " + ], + "bugs": { + "url": "https://github.com/invertase/denque/issues" + }, + "homepage": "https://docs.page/invertase/denque", + "devDependencies": { + "benchmark": "^2.1.4", + "codecov": "^3.8.3", + "double-ended-queue": "^2.1.0-0", + "istanbul": "^0.4.5", + "mocha": "^3.5.3", + "typescript": "^3.4.1" + } +} diff --git a/ts-ticket-office-service/node_modules/es6-promise/CHANGELOG.md b/ts-ticket-office-service/node_modules/es6-promise/CHANGELOG.md deleted file mode 100644 index cc8aa1070..000000000 --- a/ts-ticket-office-service/node_modules/es6-promise/CHANGELOG.md +++ /dev/null @@ -1,65 +0,0 @@ -# Master - -# 3.2.0 - -* improve tamper resistence of Promise.all Promise.race and - Promise.prototype.then (note, this isn't complete, but addresses an exception - when used \w core-js, follow up work will address entirely) -* remove spec incompatible then chaining fast-path -* add eslint -* update build deps - -# 3.1.2 - -* fix node detection issues with NWJS/electron - -# 3.1.0 - -* improve performance of Promise.all when it encounters a non-promise input object input -* then/resolve tamper protection -* reduce AST size of promise constructor, to facilitate more inlining -* Update README.md with details about PhantomJS requirement for running tests -* Mangle and compress the minified version - -# 3.0.1 - -* no longer include dist/test in npm releases - -# 3.0.0 - -* use nextTick() instead of setImmediate() to schedule microtasks with node 0.10. Later versions of - nodes are not affected as they were already using nextTick(). Note that using nextTick() might - trigger a depreciation warning on 0.10 as described at https://github.com/cujojs/when/issues/410. - The reason why nextTick() is preferred is that is setImmediate() would schedule a macrotask - instead of a microtask and might result in a different scheduling. - If needed you can revert to the former behavior as follow: - - var Promise = require('es6-promise').Promise; - Promise._setScheduler(setImmediate); - -# 2.3.0 - -* #121: Ability to override the internal asap implementation -* #120: Use an ascii character for an apostrophe, for source maps - -# 2.2.0 - -* #116: Expose asap() and a way to override the scheduling mechanism on Promise -* Lock to v0.2.3 of ember-cli - -# 2.1.1 - -* Fix #100 via #105: tell browserify to ignore vertx require -* Fix #101 via #102: "follow thenable state, not own state" - -# 2.1.0 - -* ? (see the commit log) - -# 2.0.0 - -* re-sync with RSVP. Many large performance improvements and bugfixes. - -# 1.0.0 - -* first subset of RSVP diff --git a/ts-ticket-office-service/node_modules/es6-promise/README.md b/ts-ticket-office-service/node_modules/es6-promise/README.md deleted file mode 100644 index 16739ca54..000000000 --- a/ts-ticket-office-service/node_modules/es6-promise/README.md +++ /dev/null @@ -1,74 +0,0 @@ -# ES6-Promise (subset of [rsvp.js](https://github.com/tildeio/rsvp.js)) - -This is a polyfill of the [ES6 Promise](http://people.mozilla.org/~jorendorff/es6-draft.html#sec-promise-constructor). The implementation is a subset of [rsvp.js](https://github.com/tildeio/rsvp.js) extracted by @jakearchibald, if you're wanting extra features and more debugging options, check out the [full library](https://github.com/tildeio/rsvp.js). - -For API details and how to use promises, see the JavaScript Promises HTML5Rocks article. - -## Downloads - -* [es6-promise](https://raw.githubusercontent.com/stefanpenner/es6-promise/master/dist/es6-promise.js) -* [es6-promise-min](https://raw.githubusercontent.com/stefanpenner/es6-promise/master/dist/es6-promise.min.js) - -## Node.js - -To install: - -```sh -npm install es6-promise -``` - -To use: - -```js -var Promise = require('es6-promise').Promise; -``` - -## Bower - -To install: - -```sh -bower install es6-promise --save -``` - - -## Usage in IE<9 - -`catch` is a reserved word in IE<9, meaning `promise.catch(func)` throws a syntax error. To work around this, you can use a string to access the property as shown in the following example. - -However, please remember that such technique is already provided by most common minifiers, making the resulting code safe for old browsers and production: - -```js -promise['catch'](function(err) { - // ... -}); -``` - -Or use `.then` instead: - -```js -promise.then(undefined, function(err) { - // ... -}); -``` - -## Auto-polyfill - -To polyfill the global environment (either in Node or in the browser via CommonJS) use the following code snippet: - -```js -require('es6-promise').polyfill(); -``` - -Notice that we don't assign the result of `polyfill()` to any variable. The `polyfill()` method will patch the global environment (in this case to the `Promise` name) when called. - -## Building & Testing - -You will need to have PhantomJS installed globally in order to run the tests. - -`npm install -g phantomjs` - -* `npm run build` to build -* `npm test` to run tests -* `npm start` to run a build watcher, and webserver to test -* `npm run test:server` for a testem test runner and watching builder diff --git a/ts-ticket-office-service/node_modules/es6-promise/dist/es6-promise.js b/ts-ticket-office-service/node_modules/es6-promise/dist/es6-promise.js deleted file mode 100644 index 0755e9b78..000000000 --- a/ts-ticket-office-service/node_modules/es6-promise/dist/es6-promise.js +++ /dev/null @@ -1,959 +0,0 @@ -/*! - * @overview es6-promise - a tiny implementation of Promises/A+. - * @copyright Copyright (c) 2014 Yehuda Katz, Tom Dale, Stefan Penner and contributors (Conversion to ES6 API by Jake Archibald) - * @license Licensed under MIT license - * See https://raw.githubusercontent.com/jakearchibald/es6-promise/master/LICENSE - * @version 3.2.1 - */ - -(function() { - "use strict"; - function lib$es6$promise$utils$$objectOrFunction(x) { - return typeof x === 'function' || (typeof x === 'object' && x !== null); - } - - function lib$es6$promise$utils$$isFunction(x) { - return typeof x === 'function'; - } - - function lib$es6$promise$utils$$isMaybeThenable(x) { - return typeof x === 'object' && x !== null; - } - - var lib$es6$promise$utils$$_isArray; - if (!Array.isArray) { - lib$es6$promise$utils$$_isArray = function (x) { - return Object.prototype.toString.call(x) === '[object Array]'; - }; - } else { - lib$es6$promise$utils$$_isArray = Array.isArray; - } - - var lib$es6$promise$utils$$isArray = lib$es6$promise$utils$$_isArray; - var lib$es6$promise$asap$$len = 0; - var lib$es6$promise$asap$$vertxNext; - var lib$es6$promise$asap$$customSchedulerFn; - - var lib$es6$promise$asap$$asap = function asap(callback, arg) { - lib$es6$promise$asap$$queue[lib$es6$promise$asap$$len] = callback; - lib$es6$promise$asap$$queue[lib$es6$promise$asap$$len + 1] = arg; - lib$es6$promise$asap$$len += 2; - if (lib$es6$promise$asap$$len === 2) { - // If len is 2, that means that we need to schedule an async flush. - // If additional callbacks are queued before the queue is flushed, they - // will be processed by this flush that we are scheduling. - if (lib$es6$promise$asap$$customSchedulerFn) { - lib$es6$promise$asap$$customSchedulerFn(lib$es6$promise$asap$$flush); - } else { - lib$es6$promise$asap$$scheduleFlush(); - } - } - } - - function lib$es6$promise$asap$$setScheduler(scheduleFn) { - lib$es6$promise$asap$$customSchedulerFn = scheduleFn; - } - - function lib$es6$promise$asap$$setAsap(asapFn) { - lib$es6$promise$asap$$asap = asapFn; - } - - var lib$es6$promise$asap$$browserWindow = (typeof window !== 'undefined') ? window : undefined; - var lib$es6$promise$asap$$browserGlobal = lib$es6$promise$asap$$browserWindow || {}; - var lib$es6$promise$asap$$BrowserMutationObserver = lib$es6$promise$asap$$browserGlobal.MutationObserver || lib$es6$promise$asap$$browserGlobal.WebKitMutationObserver; - var lib$es6$promise$asap$$isNode = typeof self === 'undefined' && typeof process !== 'undefined' && {}.toString.call(process) === '[object process]'; - - // test for web worker but not in IE10 - var lib$es6$promise$asap$$isWorker = typeof Uint8ClampedArray !== 'undefined' && - typeof importScripts !== 'undefined' && - typeof MessageChannel !== 'undefined'; - - // node - function lib$es6$promise$asap$$useNextTick() { - // node version 0.10.x displays a deprecation warning when nextTick is used recursively - // see https://github.com/cujojs/when/issues/410 for details - return function() { - process.nextTick(lib$es6$promise$asap$$flush); - }; - } - - // vertx - function lib$es6$promise$asap$$useVertxTimer() { - return function() { - lib$es6$promise$asap$$vertxNext(lib$es6$promise$asap$$flush); - }; - } - - function lib$es6$promise$asap$$useMutationObserver() { - var iterations = 0; - var observer = new lib$es6$promise$asap$$BrowserMutationObserver(lib$es6$promise$asap$$flush); - var node = document.createTextNode(''); - observer.observe(node, { characterData: true }); - - return function() { - node.data = (iterations = ++iterations % 2); - }; - } - - // web worker - function lib$es6$promise$asap$$useMessageChannel() { - var channel = new MessageChannel(); - channel.port1.onmessage = lib$es6$promise$asap$$flush; - return function () { - channel.port2.postMessage(0); - }; - } - - function lib$es6$promise$asap$$useSetTimeout() { - return function() { - setTimeout(lib$es6$promise$asap$$flush, 1); - }; - } - - var lib$es6$promise$asap$$queue = new Array(1000); - function lib$es6$promise$asap$$flush() { - for (var i = 0; i < lib$es6$promise$asap$$len; i+=2) { - var callback = lib$es6$promise$asap$$queue[i]; - var arg = lib$es6$promise$asap$$queue[i+1]; - - callback(arg); - - lib$es6$promise$asap$$queue[i] = undefined; - lib$es6$promise$asap$$queue[i+1] = undefined; - } - - lib$es6$promise$asap$$len = 0; - } - - function lib$es6$promise$asap$$attemptVertx() { - try { - var r = require; - var vertx = r('vertx'); - lib$es6$promise$asap$$vertxNext = vertx.runOnLoop || vertx.runOnContext; - return lib$es6$promise$asap$$useVertxTimer(); - } catch(e) { - return lib$es6$promise$asap$$useSetTimeout(); - } - } - - var lib$es6$promise$asap$$scheduleFlush; - // Decide what async method to use to triggering processing of queued callbacks: - if (lib$es6$promise$asap$$isNode) { - lib$es6$promise$asap$$scheduleFlush = lib$es6$promise$asap$$useNextTick(); - } else if (lib$es6$promise$asap$$BrowserMutationObserver) { - lib$es6$promise$asap$$scheduleFlush = lib$es6$promise$asap$$useMutationObserver(); - } else if (lib$es6$promise$asap$$isWorker) { - lib$es6$promise$asap$$scheduleFlush = lib$es6$promise$asap$$useMessageChannel(); - } else if (lib$es6$promise$asap$$browserWindow === undefined && typeof require === 'function') { - lib$es6$promise$asap$$scheduleFlush = lib$es6$promise$asap$$attemptVertx(); - } else { - lib$es6$promise$asap$$scheduleFlush = lib$es6$promise$asap$$useSetTimeout(); - } - function lib$es6$promise$then$$then(onFulfillment, onRejection) { - var parent = this; - - var child = new this.constructor(lib$es6$promise$$internal$$noop); - - if (child[lib$es6$promise$$internal$$PROMISE_ID] === undefined) { - lib$es6$promise$$internal$$makePromise(child); - } - - var state = parent._state; - - if (state) { - var callback = arguments[state - 1]; - lib$es6$promise$asap$$asap(function(){ - lib$es6$promise$$internal$$invokeCallback(state, child, callback, parent._result); - }); - } else { - lib$es6$promise$$internal$$subscribe(parent, child, onFulfillment, onRejection); - } - - return child; - } - var lib$es6$promise$then$$default = lib$es6$promise$then$$then; - function lib$es6$promise$promise$resolve$$resolve(object) { - /*jshint validthis:true */ - var Constructor = this; - - if (object && typeof object === 'object' && object.constructor === Constructor) { - return object; - } - - var promise = new Constructor(lib$es6$promise$$internal$$noop); - lib$es6$promise$$internal$$resolve(promise, object); - return promise; - } - var lib$es6$promise$promise$resolve$$default = lib$es6$promise$promise$resolve$$resolve; - var lib$es6$promise$$internal$$PROMISE_ID = Math.random().toString(36).substring(16); - - function lib$es6$promise$$internal$$noop() {} - - var lib$es6$promise$$internal$$PENDING = void 0; - var lib$es6$promise$$internal$$FULFILLED = 1; - var lib$es6$promise$$internal$$REJECTED = 2; - - var lib$es6$promise$$internal$$GET_THEN_ERROR = new lib$es6$promise$$internal$$ErrorObject(); - - function lib$es6$promise$$internal$$selfFulfillment() { - return new TypeError("You cannot resolve a promise with itself"); - } - - function lib$es6$promise$$internal$$cannotReturnOwn() { - return new TypeError('A promises callback cannot return that same promise.'); - } - - function lib$es6$promise$$internal$$getThen(promise) { - try { - return promise.then; - } catch(error) { - lib$es6$promise$$internal$$GET_THEN_ERROR.error = error; - return lib$es6$promise$$internal$$GET_THEN_ERROR; - } - } - - function lib$es6$promise$$internal$$tryThen(then, value, fulfillmentHandler, rejectionHandler) { - try { - then.call(value, fulfillmentHandler, rejectionHandler); - } catch(e) { - return e; - } - } - - function lib$es6$promise$$internal$$handleForeignThenable(promise, thenable, then) { - lib$es6$promise$asap$$asap(function(promise) { - var sealed = false; - var error = lib$es6$promise$$internal$$tryThen(then, thenable, function(value) { - if (sealed) { return; } - sealed = true; - if (thenable !== value) { - lib$es6$promise$$internal$$resolve(promise, value); - } else { - lib$es6$promise$$internal$$fulfill(promise, value); - } - }, function(reason) { - if (sealed) { return; } - sealed = true; - - lib$es6$promise$$internal$$reject(promise, reason); - }, 'Settle: ' + (promise._label || ' unknown promise')); - - if (!sealed && error) { - sealed = true; - lib$es6$promise$$internal$$reject(promise, error); - } - }, promise); - } - - function lib$es6$promise$$internal$$handleOwnThenable(promise, thenable) { - if (thenable._state === lib$es6$promise$$internal$$FULFILLED) { - lib$es6$promise$$internal$$fulfill(promise, thenable._result); - } else if (thenable._state === lib$es6$promise$$internal$$REJECTED) { - lib$es6$promise$$internal$$reject(promise, thenable._result); - } else { - lib$es6$promise$$internal$$subscribe(thenable, undefined, function(value) { - lib$es6$promise$$internal$$resolve(promise, value); - }, function(reason) { - lib$es6$promise$$internal$$reject(promise, reason); - }); - } - } - - function lib$es6$promise$$internal$$handleMaybeThenable(promise, maybeThenable, then) { - if (maybeThenable.constructor === promise.constructor && - then === lib$es6$promise$then$$default && - constructor.resolve === lib$es6$promise$promise$resolve$$default) { - lib$es6$promise$$internal$$handleOwnThenable(promise, maybeThenable); - } else { - if (then === lib$es6$promise$$internal$$GET_THEN_ERROR) { - lib$es6$promise$$internal$$reject(promise, lib$es6$promise$$internal$$GET_THEN_ERROR.error); - } else if (then === undefined) { - lib$es6$promise$$internal$$fulfill(promise, maybeThenable); - } else if (lib$es6$promise$utils$$isFunction(then)) { - lib$es6$promise$$internal$$handleForeignThenable(promise, maybeThenable, then); - } else { - lib$es6$promise$$internal$$fulfill(promise, maybeThenable); - } - } - } - - function lib$es6$promise$$internal$$resolve(promise, value) { - if (promise === value) { - lib$es6$promise$$internal$$reject(promise, lib$es6$promise$$internal$$selfFulfillment()); - } else if (lib$es6$promise$utils$$objectOrFunction(value)) { - lib$es6$promise$$internal$$handleMaybeThenable(promise, value, lib$es6$promise$$internal$$getThen(value)); - } else { - lib$es6$promise$$internal$$fulfill(promise, value); - } - } - - function lib$es6$promise$$internal$$publishRejection(promise) { - if (promise._onerror) { - promise._onerror(promise._result); - } - - lib$es6$promise$$internal$$publish(promise); - } - - function lib$es6$promise$$internal$$fulfill(promise, value) { - if (promise._state !== lib$es6$promise$$internal$$PENDING) { return; } - - promise._result = value; - promise._state = lib$es6$promise$$internal$$FULFILLED; - - if (promise._subscribers.length !== 0) { - lib$es6$promise$asap$$asap(lib$es6$promise$$internal$$publish, promise); - } - } - - function lib$es6$promise$$internal$$reject(promise, reason) { - if (promise._state !== lib$es6$promise$$internal$$PENDING) { return; } - promise._state = lib$es6$promise$$internal$$REJECTED; - promise._result = reason; - - lib$es6$promise$asap$$asap(lib$es6$promise$$internal$$publishRejection, promise); - } - - function lib$es6$promise$$internal$$subscribe(parent, child, onFulfillment, onRejection) { - var subscribers = parent._subscribers; - var length = subscribers.length; - - parent._onerror = null; - - subscribers[length] = child; - subscribers[length + lib$es6$promise$$internal$$FULFILLED] = onFulfillment; - subscribers[length + lib$es6$promise$$internal$$REJECTED] = onRejection; - - if (length === 0 && parent._state) { - lib$es6$promise$asap$$asap(lib$es6$promise$$internal$$publish, parent); - } - } - - function lib$es6$promise$$internal$$publish(promise) { - var subscribers = promise._subscribers; - var settled = promise._state; - - if (subscribers.length === 0) { return; } - - var child, callback, detail = promise._result; - - for (var i = 0; i < subscribers.length; i += 3) { - child = subscribers[i]; - callback = subscribers[i + settled]; - - if (child) { - lib$es6$promise$$internal$$invokeCallback(settled, child, callback, detail); - } else { - callback(detail); - } - } - - promise._subscribers.length = 0; - } - - function lib$es6$promise$$internal$$ErrorObject() { - this.error = null; - } - - var lib$es6$promise$$internal$$TRY_CATCH_ERROR = new lib$es6$promise$$internal$$ErrorObject(); - - function lib$es6$promise$$internal$$tryCatch(callback, detail) { - try { - return callback(detail); - } catch(e) { - lib$es6$promise$$internal$$TRY_CATCH_ERROR.error = e; - return lib$es6$promise$$internal$$TRY_CATCH_ERROR; - } - } - - function lib$es6$promise$$internal$$invokeCallback(settled, promise, callback, detail) { - var hasCallback = lib$es6$promise$utils$$isFunction(callback), - value, error, succeeded, failed; - - if (hasCallback) { - value = lib$es6$promise$$internal$$tryCatch(callback, detail); - - if (value === lib$es6$promise$$internal$$TRY_CATCH_ERROR) { - failed = true; - error = value.error; - value = null; - } else { - succeeded = true; - } - - if (promise === value) { - lib$es6$promise$$internal$$reject(promise, lib$es6$promise$$internal$$cannotReturnOwn()); - return; - } - - } else { - value = detail; - succeeded = true; - } - - if (promise._state !== lib$es6$promise$$internal$$PENDING) { - // noop - } else if (hasCallback && succeeded) { - lib$es6$promise$$internal$$resolve(promise, value); - } else if (failed) { - lib$es6$promise$$internal$$reject(promise, error); - } else if (settled === lib$es6$promise$$internal$$FULFILLED) { - lib$es6$promise$$internal$$fulfill(promise, value); - } else if (settled === lib$es6$promise$$internal$$REJECTED) { - lib$es6$promise$$internal$$reject(promise, value); - } - } - - function lib$es6$promise$$internal$$initializePromise(promise, resolver) { - try { - resolver(function resolvePromise(value){ - lib$es6$promise$$internal$$resolve(promise, value); - }, function rejectPromise(reason) { - lib$es6$promise$$internal$$reject(promise, reason); - }); - } catch(e) { - lib$es6$promise$$internal$$reject(promise, e); - } - } - - var lib$es6$promise$$internal$$id = 0; - function lib$es6$promise$$internal$$nextId() { - return lib$es6$promise$$internal$$id++; - } - - function lib$es6$promise$$internal$$makePromise(promise) { - promise[lib$es6$promise$$internal$$PROMISE_ID] = lib$es6$promise$$internal$$id++; - promise._state = undefined; - promise._result = undefined; - promise._subscribers = []; - } - - function lib$es6$promise$promise$all$$all(entries) { - return new lib$es6$promise$enumerator$$default(this, entries).promise; - } - var lib$es6$promise$promise$all$$default = lib$es6$promise$promise$all$$all; - function lib$es6$promise$promise$race$$race(entries) { - /*jshint validthis:true */ - var Constructor = this; - - if (!lib$es6$promise$utils$$isArray(entries)) { - return new Constructor(function(resolve, reject) { - reject(new TypeError('You must pass an array to race.')); - }); - } else { - return new Constructor(function(resolve, reject) { - var length = entries.length; - for (var i = 0; i < length; i++) { - Constructor.resolve(entries[i]).then(resolve, reject); - } - }); - } - } - var lib$es6$promise$promise$race$$default = lib$es6$promise$promise$race$$race; - function lib$es6$promise$promise$reject$$reject(reason) { - /*jshint validthis:true */ - var Constructor = this; - var promise = new Constructor(lib$es6$promise$$internal$$noop); - lib$es6$promise$$internal$$reject(promise, reason); - return promise; - } - var lib$es6$promise$promise$reject$$default = lib$es6$promise$promise$reject$$reject; - - - function lib$es6$promise$promise$$needsResolver() { - throw new TypeError('You must pass a resolver function as the first argument to the promise constructor'); - } - - function lib$es6$promise$promise$$needsNew() { - throw new TypeError("Failed to construct 'Promise': Please use the 'new' operator, this object constructor cannot be called as a function."); - } - - var lib$es6$promise$promise$$default = lib$es6$promise$promise$$Promise; - /** - Promise objects represent the eventual result of an asynchronous operation. The - primary way of interacting with a promise is through its `then` method, which - registers callbacks to receive either a promise's eventual value or the reason - why the promise cannot be fulfilled. - - Terminology - ----------- - - - `promise` is an object or function with a `then` method whose behavior conforms to this specification. - - `thenable` is an object or function that defines a `then` method. - - `value` is any legal JavaScript value (including undefined, a thenable, or a promise). - - `exception` is a value that is thrown using the throw statement. - - `reason` is a value that indicates why a promise was rejected. - - `settled` the final resting state of a promise, fulfilled or rejected. - - A promise can be in one of three states: pending, fulfilled, or rejected. - - Promises that are fulfilled have a fulfillment value and are in the fulfilled - state. Promises that are rejected have a rejection reason and are in the - rejected state. A fulfillment value is never a thenable. - - Promises can also be said to *resolve* a value. If this value is also a - promise, then the original promise's settled state will match the value's - settled state. So a promise that *resolves* a promise that rejects will - itself reject, and a promise that *resolves* a promise that fulfills will - itself fulfill. - - - Basic Usage: - ------------ - - ```js - var promise = new Promise(function(resolve, reject) { - // on success - resolve(value); - - // on failure - reject(reason); - }); - - promise.then(function(value) { - // on fulfillment - }, function(reason) { - // on rejection - }); - ``` - - Advanced Usage: - --------------- - - Promises shine when abstracting away asynchronous interactions such as - `XMLHttpRequest`s. - - ```js - function getJSON(url) { - return new Promise(function(resolve, reject){ - var xhr = new XMLHttpRequest(); - - xhr.open('GET', url); - xhr.onreadystatechange = handler; - xhr.responseType = 'json'; - xhr.setRequestHeader('Accept', 'application/json'); - xhr.send(); - - function handler() { - if (this.readyState === this.DONE) { - if (this.status === 200) { - resolve(this.response); - } else { - reject(new Error('getJSON: `' + url + '` failed with status: [' + this.status + ']')); - } - } - }; - }); - } - - getJSON('/posts.json').then(function(json) { - // on fulfillment - }, function(reason) { - // on rejection - }); - ``` - - Unlike callbacks, promises are great composable primitives. - - ```js - Promise.all([ - getJSON('/posts'), - getJSON('/comments') - ]).then(function(values){ - values[0] // => postsJSON - values[1] // => commentsJSON - - return values; - }); - ``` - - @class Promise - @param {function} resolver - Useful for tooling. - @constructor - */ - function lib$es6$promise$promise$$Promise(resolver) { - this[lib$es6$promise$$internal$$PROMISE_ID] = lib$es6$promise$$internal$$nextId(); - this._result = this._state = undefined; - this._subscribers = []; - - if (lib$es6$promise$$internal$$noop !== resolver) { - typeof resolver !== 'function' && lib$es6$promise$promise$$needsResolver(); - this instanceof lib$es6$promise$promise$$Promise ? lib$es6$promise$$internal$$initializePromise(this, resolver) : lib$es6$promise$promise$$needsNew(); - } - } - - lib$es6$promise$promise$$Promise.all = lib$es6$promise$promise$all$$default; - lib$es6$promise$promise$$Promise.race = lib$es6$promise$promise$race$$default; - lib$es6$promise$promise$$Promise.resolve = lib$es6$promise$promise$resolve$$default; - lib$es6$promise$promise$$Promise.reject = lib$es6$promise$promise$reject$$default; - lib$es6$promise$promise$$Promise._setScheduler = lib$es6$promise$asap$$setScheduler; - lib$es6$promise$promise$$Promise._setAsap = lib$es6$promise$asap$$setAsap; - lib$es6$promise$promise$$Promise._asap = lib$es6$promise$asap$$asap; - - lib$es6$promise$promise$$Promise.prototype = { - constructor: lib$es6$promise$promise$$Promise, - - /** - The primary way of interacting with a promise is through its `then` method, - which registers callbacks to receive either a promise's eventual value or the - reason why the promise cannot be fulfilled. - - ```js - findUser().then(function(user){ - // user is available - }, function(reason){ - // user is unavailable, and you are given the reason why - }); - ``` - - Chaining - -------- - - The return value of `then` is itself a promise. This second, 'downstream' - promise is resolved with the return value of the first promise's fulfillment - or rejection handler, or rejected if the handler throws an exception. - - ```js - findUser().then(function (user) { - return user.name; - }, function (reason) { - return 'default name'; - }).then(function (userName) { - // If `findUser` fulfilled, `userName` will be the user's name, otherwise it - // will be `'default name'` - }); - - findUser().then(function (user) { - throw new Error('Found user, but still unhappy'); - }, function (reason) { - throw new Error('`findUser` rejected and we're unhappy'); - }).then(function (value) { - // never reached - }, function (reason) { - // if `findUser` fulfilled, `reason` will be 'Found user, but still unhappy'. - // If `findUser` rejected, `reason` will be '`findUser` rejected and we're unhappy'. - }); - ``` - If the downstream promise does not specify a rejection handler, rejection reasons will be propagated further downstream. - - ```js - findUser().then(function (user) { - throw new PedagogicalException('Upstream error'); - }).then(function (value) { - // never reached - }).then(function (value) { - // never reached - }, function (reason) { - // The `PedgagocialException` is propagated all the way down to here - }); - ``` - - Assimilation - ------------ - - Sometimes the value you want to propagate to a downstream promise can only be - retrieved asynchronously. This can be achieved by returning a promise in the - fulfillment or rejection handler. The downstream promise will then be pending - until the returned promise is settled. This is called *assimilation*. - - ```js - findUser().then(function (user) { - return findCommentsByAuthor(user); - }).then(function (comments) { - // The user's comments are now available - }); - ``` - - If the assimliated promise rejects, then the downstream promise will also reject. - - ```js - findUser().then(function (user) { - return findCommentsByAuthor(user); - }).then(function (comments) { - // If `findCommentsByAuthor` fulfills, we'll have the value here - }, function (reason) { - // If `findCommentsByAuthor` rejects, we'll have the reason here - }); - ``` - - Simple Example - -------------- - - Synchronous Example - - ```javascript - var result; - - try { - result = findResult(); - // success - } catch(reason) { - // failure - } - ``` - - Errback Example - - ```js - findResult(function(result, err){ - if (err) { - // failure - } else { - // success - } - }); - ``` - - Promise Example; - - ```javascript - findResult().then(function(result){ - // success - }, function(reason){ - // failure - }); - ``` - - Advanced Example - -------------- - - Synchronous Example - - ```javascript - var author, books; - - try { - author = findAuthor(); - books = findBooksByAuthor(author); - // success - } catch(reason) { - // failure - } - ``` - - Errback Example - - ```js - - function foundBooks(books) { - - } - - function failure(reason) { - - } - - findAuthor(function(author, err){ - if (err) { - failure(err); - // failure - } else { - try { - findBoooksByAuthor(author, function(books, err) { - if (err) { - failure(err); - } else { - try { - foundBooks(books); - } catch(reason) { - failure(reason); - } - } - }); - } catch(error) { - failure(err); - } - // success - } - }); - ``` - - Promise Example; - - ```javascript - findAuthor(). - then(findBooksByAuthor). - then(function(books){ - // found books - }).catch(function(reason){ - // something went wrong - }); - ``` - - @method then - @param {Function} onFulfilled - @param {Function} onRejected - Useful for tooling. - @return {Promise} - */ - then: lib$es6$promise$then$$default, - - /** - `catch` is simply sugar for `then(undefined, onRejection)` which makes it the same - as the catch block of a try/catch statement. - - ```js - function findAuthor(){ - throw new Error('couldn't find that author'); - } - - // synchronous - try { - findAuthor(); - } catch(reason) { - // something went wrong - } - - // async with promises - findAuthor().catch(function(reason){ - // something went wrong - }); - ``` - - @method catch - @param {Function} onRejection - Useful for tooling. - @return {Promise} - */ - 'catch': function(onRejection) { - return this.then(null, onRejection); - } - }; - var lib$es6$promise$enumerator$$default = lib$es6$promise$enumerator$$Enumerator; - function lib$es6$promise$enumerator$$Enumerator(Constructor, input) { - this._instanceConstructor = Constructor; - this.promise = new Constructor(lib$es6$promise$$internal$$noop); - - if (!this.promise[lib$es6$promise$$internal$$PROMISE_ID]) { - lib$es6$promise$$internal$$makePromise(this.promise); - } - - if (lib$es6$promise$utils$$isArray(input)) { - this._input = input; - this.length = input.length; - this._remaining = input.length; - - this._result = new Array(this.length); - - if (this.length === 0) { - lib$es6$promise$$internal$$fulfill(this.promise, this._result); - } else { - this.length = this.length || 0; - this._enumerate(); - if (this._remaining === 0) { - lib$es6$promise$$internal$$fulfill(this.promise, this._result); - } - } - } else { - lib$es6$promise$$internal$$reject(this.promise, lib$es6$promise$enumerator$$validationError()); - } - } - - function lib$es6$promise$enumerator$$validationError() { - return new Error('Array Methods must be provided an Array'); - } - - lib$es6$promise$enumerator$$Enumerator.prototype._enumerate = function() { - var length = this.length; - var input = this._input; - - for (var i = 0; this._state === lib$es6$promise$$internal$$PENDING && i < length; i++) { - this._eachEntry(input[i], i); - } - }; - - lib$es6$promise$enumerator$$Enumerator.prototype._eachEntry = function(entry, i) { - var c = this._instanceConstructor; - var resolve = c.resolve; - - if (resolve === lib$es6$promise$promise$resolve$$default) { - var then = lib$es6$promise$$internal$$getThen(entry); - - if (then === lib$es6$promise$then$$default && - entry._state !== lib$es6$promise$$internal$$PENDING) { - this._settledAt(entry._state, i, entry._result); - } else if (typeof then !== 'function') { - this._remaining--; - this._result[i] = entry; - } else if (c === lib$es6$promise$promise$$default) { - var promise = new c(lib$es6$promise$$internal$$noop); - lib$es6$promise$$internal$$handleMaybeThenable(promise, entry, then); - this._willSettleAt(promise, i); - } else { - this._willSettleAt(new c(function(resolve) { resolve(entry); }), i); - } - } else { - this._willSettleAt(resolve(entry), i); - } - }; - - lib$es6$promise$enumerator$$Enumerator.prototype._settledAt = function(state, i, value) { - var promise = this.promise; - - if (promise._state === lib$es6$promise$$internal$$PENDING) { - this._remaining--; - - if (state === lib$es6$promise$$internal$$REJECTED) { - lib$es6$promise$$internal$$reject(promise, value); - } else { - this._result[i] = value; - } - } - - if (this._remaining === 0) { - lib$es6$promise$$internal$$fulfill(promise, this._result); - } - }; - - lib$es6$promise$enumerator$$Enumerator.prototype._willSettleAt = function(promise, i) { - var enumerator = this; - - lib$es6$promise$$internal$$subscribe(promise, undefined, function(value) { - enumerator._settledAt(lib$es6$promise$$internal$$FULFILLED, i, value); - }, function(reason) { - enumerator._settledAt(lib$es6$promise$$internal$$REJECTED, i, reason); - }); - }; - function lib$es6$promise$polyfill$$polyfill() { - var local; - - if (typeof global !== 'undefined') { - local = global; - } else if (typeof self !== 'undefined') { - local = self; - } else { - try { - local = Function('return this')(); - } catch (e) { - throw new Error('polyfill failed because global object is unavailable in this environment'); - } - } - - var P = local.Promise; - - if (P && Object.prototype.toString.call(P.resolve()) === '[object Promise]' && !P.cast) { - return; - } - - local.Promise = lib$es6$promise$promise$$default; - } - var lib$es6$promise$polyfill$$default = lib$es6$promise$polyfill$$polyfill; - - var lib$es6$promise$umd$$ES6Promise = { - 'Promise': lib$es6$promise$promise$$default, - 'polyfill': lib$es6$promise$polyfill$$default - }; - - /* global define:true module:true window: true */ - if (typeof define === 'function' && define['amd']) { - define(function() { return lib$es6$promise$umd$$ES6Promise; }); - } else if (typeof module !== 'undefined' && module['exports']) { - module['exports'] = lib$es6$promise$umd$$ES6Promise; - } else if (typeof this !== 'undefined') { - this['ES6Promise'] = lib$es6$promise$umd$$ES6Promise; - } - - lib$es6$promise$polyfill$$default(); -}).call(this); - diff --git a/ts-ticket-office-service/node_modules/es6-promise/dist/es6-promise.min.js b/ts-ticket-office-service/node_modules/es6-promise/dist/es6-promise.min.js deleted file mode 100644 index 13151c2d9..000000000 --- a/ts-ticket-office-service/node_modules/es6-promise/dist/es6-promise.min.js +++ /dev/null @@ -1,9 +0,0 @@ -/*! - * @overview es6-promise - a tiny implementation of Promises/A+. - * @copyright Copyright (c) 2014 Yehuda Katz, Tom Dale, Stefan Penner and contributors (Conversion to ES6 API by Jake Archibald) - * @license Licensed under MIT license - * See https://raw.githubusercontent.com/jakearchibald/es6-promise/master/LICENSE - * @version 3.2.1 - */ - -(function(){"use strict";function t(t){return"function"==typeof t||"object"==typeof t&&null!==t}function e(t){return"function"==typeof t}function n(t){G=t}function r(t){Q=t}function o(){return function(){process.nextTick(a)}}function i(){return function(){B(a)}}function s(){var t=0,e=new X(a),n=document.createTextNode("");return e.observe(n,{characterData:!0}),function(){n.data=t=++t%2}}function u(){var t=new MessageChannel;return t.port1.onmessage=a,function(){t.port2.postMessage(0)}}function c(){return function(){setTimeout(a,1)}}function a(){for(var t=0;J>t;t+=2){var e=tt[t],n=tt[t+1];e(n),tt[t]=void 0,tt[t+1]=void 0}J=0}function f(){try{var t=require,e=t("vertx");return B=e.runOnLoop||e.runOnContext,i()}catch(n){return c()}}function l(t,e){var n=this,r=new this.constructor(p);void 0===r[rt]&&k(r);var o=n._state;if(o){var i=arguments[o-1];Q(function(){x(o,r,i,n._result)})}else E(n,r,t,e);return r}function h(t){var e=this;if(t&&"object"==typeof t&&t.constructor===e)return t;var n=new e(p);return g(n,t),n}function p(){}function _(){return new TypeError("You cannot resolve a promise with itself")}function d(){return new TypeError("A promises callback cannot return that same promise.")}function v(t){try{return t.then}catch(e){return ut.error=e,ut}}function y(t,e,n,r){try{t.call(e,n,r)}catch(o){return o}}function m(t,e,n){Q(function(t){var r=!1,o=y(n,e,function(n){r||(r=!0,e!==n?g(t,n):S(t,n))},function(e){r||(r=!0,j(t,e))},"Settle: "+(t._label||" unknown promise"));!r&&o&&(r=!0,j(t,o))},t)}function b(t,e){e._state===it?S(t,e._result):e._state===st?j(t,e._result):E(e,void 0,function(e){g(t,e)},function(e){j(t,e)})}function w(t,n,r){n.constructor===t.constructor&&r===et&&constructor.resolve===nt?b(t,n):r===ut?j(t,ut.error):void 0===r?S(t,n):e(r)?m(t,n,r):S(t,n)}function g(e,n){e===n?j(e,_()):t(n)?w(e,n,v(n)):S(e,n)}function A(t){t._onerror&&t._onerror(t._result),T(t)}function S(t,e){t._state===ot&&(t._result=e,t._state=it,0!==t._subscribers.length&&Q(T,t))}function j(t,e){t._state===ot&&(t._state=st,t._result=e,Q(A,t))}function E(t,e,n,r){var o=t._subscribers,i=o.length;t._onerror=null,o[i]=e,o[i+it]=n,o[i+st]=r,0===i&&t._state&&Q(T,t)}function T(t){var e=t._subscribers,n=t._state;if(0!==e.length){for(var r,o,i=t._result,s=0;si;i++)e.resolve(t[i]).then(n,r)}:function(t,e){e(new TypeError("You must pass an array to race."))})}function F(t){var e=this,n=new e(p);return j(n,t),n}function D(){throw new TypeError("You must pass a resolver function as the first argument to the promise constructor")}function K(){throw new TypeError("Failed to construct 'Promise': Please use the 'new' operator, this object constructor cannot be called as a function.")}function L(t){this[rt]=O(),this._result=this._state=void 0,this._subscribers=[],p!==t&&("function"!=typeof t&&D(),this instanceof L?C(this,t):K())}function N(t,e){this._instanceConstructor=t,this.promise=new t(p),this.promise[rt]||k(this.promise),I(e)?(this._input=e,this.length=e.length,this._remaining=e.length,this._result=new Array(this.length),0===this.length?S(this.promise,this._result):(this.length=this.length||0,this._enumerate(),0===this._remaining&&S(this.promise,this._result))):j(this.promise,U())}function U(){return new Error("Array Methods must be provided an Array")}function W(){var t;if("undefined"!=typeof global)t=global;else if("undefined"!=typeof self)t=self;else try{t=Function("return this")()}catch(e){throw new Error("polyfill failed because global object is unavailable in this environment")}var n=t.Promise;(!n||"[object Promise]"!==Object.prototype.toString.call(n.resolve())||n.cast)&&(t.Promise=pt)}var z;z=Array.isArray?Array.isArray:function(t){return"[object Array]"===Object.prototype.toString.call(t)};var B,G,H,I=z,J=0,Q=function(t,e){tt[J]=t,tt[J+1]=e,J+=2,2===J&&(G?G(a):H())},R="undefined"!=typeof window?window:void 0,V=R||{},X=V.MutationObserver||V.WebKitMutationObserver,Z="undefined"==typeof self&&"undefined"!=typeof process&&"[object process]"==={}.toString.call(process),$="undefined"!=typeof Uint8ClampedArray&&"undefined"!=typeof importScripts&&"undefined"!=typeof MessageChannel,tt=new Array(1e3);H=Z?o():X?s():$?u():void 0===R&&"function"==typeof require?f():c();var et=l,nt=h,rt=Math.random().toString(36).substring(16),ot=void 0,it=1,st=2,ut=new M,ct=new M,at=0,ft=Y,lt=q,ht=F,pt=L;L.all=ft,L.race=lt,L.resolve=nt,L.reject=ht,L._setScheduler=n,L._setAsap=r,L._asap=Q,L.prototype={constructor:L,then:et,"catch":function(t){return this.then(null,t)}};var _t=N;N.prototype._enumerate=function(){for(var t=this.length,e=this._input,n=0;this._state===ot&&t>n;n++)this._eachEntry(e[n],n)},N.prototype._eachEntry=function(t,e){var n=this._instanceConstructor,r=n.resolve;if(r===nt){var o=v(t);if(o===et&&t._state!==ot)this._settledAt(t._state,e,t._result);else if("function"!=typeof o)this._remaining--,this._result[e]=t;else if(n===pt){var i=new n(p);w(i,t,o),this._willSettleAt(i,e)}else this._willSettleAt(new n(function(e){e(t)}),e)}else this._willSettleAt(r(t),e)},N.prototype._settledAt=function(t,e,n){var r=this.promise;r._state===ot&&(this._remaining--,t===st?j(r,n):this._result[e]=n),0===this._remaining&&S(r,this._result)},N.prototype._willSettleAt=function(t,e){var n=this;E(t,void 0,function(t){n._settledAt(it,e,t)},function(t){n._settledAt(st,e,t)})};var dt=W,vt={Promise:pt,polyfill:dt};"function"==typeof define&&define.amd?define(function(){return vt}):"undefined"!=typeof module&&module.exports?module.exports=vt:"undefined"!=typeof this&&(this.ES6Promise=vt),dt()}).call(this); \ No newline at end of file diff --git a/ts-ticket-office-service/node_modules/es6-promise/lib/es6-promise.umd.js b/ts-ticket-office-service/node_modules/es6-promise/lib/es6-promise.umd.js deleted file mode 100644 index 5984f7056..000000000 --- a/ts-ticket-office-service/node_modules/es6-promise/lib/es6-promise.umd.js +++ /dev/null @@ -1,18 +0,0 @@ -import Promise from './es6-promise/promise'; -import polyfill from './es6-promise/polyfill'; - -var ES6Promise = { - 'Promise': Promise, - 'polyfill': polyfill -}; - -/* global define:true module:true window: true */ -if (typeof define === 'function' && define['amd']) { - define(function() { return ES6Promise; }); -} else if (typeof module !== 'undefined' && module['exports']) { - module['exports'] = ES6Promise; -} else if (typeof this !== 'undefined') { - this['ES6Promise'] = ES6Promise; -} - -polyfill(); diff --git a/ts-ticket-office-service/node_modules/es6-promise/lib/es6-promise/-internal.js b/ts-ticket-office-service/node_modules/es6-promise/lib/es6-promise/-internal.js deleted file mode 100644 index aeebf5766..000000000 --- a/ts-ticket-office-service/node_modules/es6-promise/lib/es6-promise/-internal.js +++ /dev/null @@ -1,273 +0,0 @@ -import { - objectOrFunction, - isFunction -} from './utils'; - -import { - asap -} from './asap'; - -import originalThen from './then'; -import originalResolve from './promise/resolve'; - -export var PROMISE_ID = Math.random().toString(36).substring(16); - -function noop() {} - -var PENDING = void 0; -var FULFILLED = 1; -var REJECTED = 2; - -var GET_THEN_ERROR = new ErrorObject(); - -function selfFulfillment() { - return new TypeError("You cannot resolve a promise with itself"); -} - -function cannotReturnOwn() { - return new TypeError('A promises callback cannot return that same promise.'); -} - -function getThen(promise) { - try { - return promise.then; - } catch(error) { - GET_THEN_ERROR.error = error; - return GET_THEN_ERROR; - } -} - -function tryThen(then, value, fulfillmentHandler, rejectionHandler) { - try { - then.call(value, fulfillmentHandler, rejectionHandler); - } catch(e) { - return e; - } -} - -function handleForeignThenable(promise, thenable, then) { - asap(function(promise) { - var sealed = false; - var error = tryThen(then, thenable, function(value) { - if (sealed) { return; } - sealed = true; - if (thenable !== value) { - resolve(promise, value); - } else { - fulfill(promise, value); - } - }, function(reason) { - if (sealed) { return; } - sealed = true; - - reject(promise, reason); - }, 'Settle: ' + (promise._label || ' unknown promise')); - - if (!sealed && error) { - sealed = true; - reject(promise, error); - } - }, promise); -} - -function handleOwnThenable(promise, thenable) { - if (thenable._state === FULFILLED) { - fulfill(promise, thenable._result); - } else if (thenable._state === REJECTED) { - reject(promise, thenable._result); - } else { - subscribe(thenable, undefined, function(value) { - resolve(promise, value); - }, function(reason) { - reject(promise, reason); - }); - } -} - -function handleMaybeThenable(promise, maybeThenable, then) { - if (maybeThenable.constructor === promise.constructor && - then === originalThen && - constructor.resolve === originalResolve) { - handleOwnThenable(promise, maybeThenable); - } else { - if (then === GET_THEN_ERROR) { - reject(promise, GET_THEN_ERROR.error); - } else if (then === undefined) { - fulfill(promise, maybeThenable); - } else if (isFunction(then)) { - handleForeignThenable(promise, maybeThenable, then); - } else { - fulfill(promise, maybeThenable); - } - } -} - -function resolve(promise, value) { - if (promise === value) { - reject(promise, selfFulfillment()); - } else if (objectOrFunction(value)) { - handleMaybeThenable(promise, value, getThen(value)); - } else { - fulfill(promise, value); - } -} - -function publishRejection(promise) { - if (promise._onerror) { - promise._onerror(promise._result); - } - - publish(promise); -} - -function fulfill(promise, value) { - if (promise._state !== PENDING) { return; } - - promise._result = value; - promise._state = FULFILLED; - - if (promise._subscribers.length !== 0) { - asap(publish, promise); - } -} - -function reject(promise, reason) { - if (promise._state !== PENDING) { return; } - promise._state = REJECTED; - promise._result = reason; - - asap(publishRejection, promise); -} - -function subscribe(parent, child, onFulfillment, onRejection) { - var subscribers = parent._subscribers; - var length = subscribers.length; - - parent._onerror = null; - - subscribers[length] = child; - subscribers[length + FULFILLED] = onFulfillment; - subscribers[length + REJECTED] = onRejection; - - if (length === 0 && parent._state) { - asap(publish, parent); - } -} - -function publish(promise) { - var subscribers = promise._subscribers; - var settled = promise._state; - - if (subscribers.length === 0) { return; } - - var child, callback, detail = promise._result; - - for (var i = 0; i < subscribers.length; i += 3) { - child = subscribers[i]; - callback = subscribers[i + settled]; - - if (child) { - invokeCallback(settled, child, callback, detail); - } else { - callback(detail); - } - } - - promise._subscribers.length = 0; -} - -function ErrorObject() { - this.error = null; -} - -var TRY_CATCH_ERROR = new ErrorObject(); - -function tryCatch(callback, detail) { - try { - return callback(detail); - } catch(e) { - TRY_CATCH_ERROR.error = e; - return TRY_CATCH_ERROR; - } -} - -function invokeCallback(settled, promise, callback, detail) { - var hasCallback = isFunction(callback), - value, error, succeeded, failed; - - if (hasCallback) { - value = tryCatch(callback, detail); - - if (value === TRY_CATCH_ERROR) { - failed = true; - error = value.error; - value = null; - } else { - succeeded = true; - } - - if (promise === value) { - reject(promise, cannotReturnOwn()); - return; - } - - } else { - value = detail; - succeeded = true; - } - - if (promise._state !== PENDING) { - // noop - } else if (hasCallback && succeeded) { - resolve(promise, value); - } else if (failed) { - reject(promise, error); - } else if (settled === FULFILLED) { - fulfill(promise, value); - } else if (settled === REJECTED) { - reject(promise, value); - } -} - -function initializePromise(promise, resolver) { - try { - resolver(function resolvePromise(value){ - resolve(promise, value); - }, function rejectPromise(reason) { - reject(promise, reason); - }); - } catch(e) { - reject(promise, e); - } -} - -var id = 0; -function nextId() { - return id++; -} - -function makePromise(promise) { - promise[PROMISE_ID] = id++; - promise._state = undefined; - promise._result = undefined; - promise._subscribers = []; -} - -export { - nextId, - makePromise, - getThen, - noop, - resolve, - reject, - fulfill, - subscribe, - publish, - publishRejection, - initializePromise, - invokeCallback, - FULFILLED, - REJECTED, - PENDING, - handleMaybeThenable -}; diff --git a/ts-ticket-office-service/node_modules/es6-promise/lib/es6-promise/asap.js b/ts-ticket-office-service/node_modules/es6-promise/lib/es6-promise/asap.js deleted file mode 100644 index 40f1d252c..000000000 --- a/ts-ticket-office-service/node_modules/es6-promise/lib/es6-promise/asap.js +++ /dev/null @@ -1,119 +0,0 @@ -var len = 0; -var vertxNext; -var customSchedulerFn; - -export var asap = function asap(callback, arg) { - queue[len] = callback; - queue[len + 1] = arg; - len += 2; - if (len === 2) { - // If len is 2, that means that we need to schedule an async flush. - // If additional callbacks are queued before the queue is flushed, they - // will be processed by this flush that we are scheduling. - if (customSchedulerFn) { - customSchedulerFn(flush); - } else { - scheduleFlush(); - } - } -} - -export function setScheduler(scheduleFn) { - customSchedulerFn = scheduleFn; -} - -export function setAsap(asapFn) { - asap = asapFn; -} - -var browserWindow = (typeof window !== 'undefined') ? window : undefined; -var browserGlobal = browserWindow || {}; -var BrowserMutationObserver = browserGlobal.MutationObserver || browserGlobal.WebKitMutationObserver; -var isNode = typeof self === 'undefined' && typeof process !== 'undefined' && {}.toString.call(process) === '[object process]'; - -// test for web worker but not in IE10 -var isWorker = typeof Uint8ClampedArray !== 'undefined' && - typeof importScripts !== 'undefined' && - typeof MessageChannel !== 'undefined'; - -// node -function useNextTick() { - // node version 0.10.x displays a deprecation warning when nextTick is used recursively - // see https://github.com/cujojs/when/issues/410 for details - return function() { - process.nextTick(flush); - }; -} - -// vertx -function useVertxTimer() { - return function() { - vertxNext(flush); - }; -} - -function useMutationObserver() { - var iterations = 0; - var observer = new BrowserMutationObserver(flush); - var node = document.createTextNode(''); - observer.observe(node, { characterData: true }); - - return function() { - node.data = (iterations = ++iterations % 2); - }; -} - -// web worker -function useMessageChannel() { - var channel = new MessageChannel(); - channel.port1.onmessage = flush; - return function () { - channel.port2.postMessage(0); - }; -} - -function useSetTimeout() { - return function() { - setTimeout(flush, 1); - }; -} - -var queue = new Array(1000); -function flush() { - for (var i = 0; i < len; i+=2) { - var callback = queue[i]; - var arg = queue[i+1]; - - callback(arg); - - queue[i] = undefined; - queue[i+1] = undefined; - } - - len = 0; -} - -function attemptVertx() { - try { - var r = require; - var vertx = r('vertx'); - vertxNext = vertx.runOnLoop || vertx.runOnContext; - return useVertxTimer(); - } catch(e) { - return useSetTimeout(); - } -} - -var scheduleFlush; -// Decide what async method to use to triggering processing of queued callbacks: -if (isNode) { - scheduleFlush = useNextTick(); -} else if (BrowserMutationObserver) { - scheduleFlush = useMutationObserver(); -} else if (isWorker) { - scheduleFlush = useMessageChannel(); -} else if (browserWindow === undefined && typeof require === 'function') { - scheduleFlush = attemptVertx(); -} else { - scheduleFlush = useSetTimeout(); -} diff --git a/ts-ticket-office-service/node_modules/es6-promise/lib/es6-promise/enumerator.js b/ts-ticket-office-service/node_modules/es6-promise/lib/es6-promise/enumerator.js deleted file mode 100644 index 2a7a28f27..000000000 --- a/ts-ticket-office-service/node_modules/es6-promise/lib/es6-promise/enumerator.js +++ /dev/null @@ -1,118 +0,0 @@ -import { - isArray, - isMaybeThenable -} from './utils'; - -import { - noop, - reject, - fulfill, - subscribe, - FULFILLED, - REJECTED, - PENDING, - getThen, - handleMaybeThenable -} from './-internal'; - -import then from './then'; -import Promise from './promise'; -import originalResolve from './promise/resolve'; -import originalThen from './then'; -import { makePromise, PROMISE_ID } from './-internal'; - -export default Enumerator; -function Enumerator(Constructor, input) { - this._instanceConstructor = Constructor; - this.promise = new Constructor(noop); - - if (!this.promise[PROMISE_ID]) { - makePromise(this.promise); - } - - if (isArray(input)) { - this._input = input; - this.length = input.length; - this._remaining = input.length; - - this._result = new Array(this.length); - - if (this.length === 0) { - fulfill(this.promise, this._result); - } else { - this.length = this.length || 0; - this._enumerate(); - if (this._remaining === 0) { - fulfill(this.promise, this._result); - } - } - } else { - reject(this.promise, validationError()); - } -} - -function validationError() { - return new Error('Array Methods must be provided an Array'); -}; - -Enumerator.prototype._enumerate = function() { - var length = this.length; - var input = this._input; - - for (var i = 0; this._state === PENDING && i < length; i++) { - this._eachEntry(input[i], i); - } -}; - -Enumerator.prototype._eachEntry = function(entry, i) { - var c = this._instanceConstructor; - var resolve = c.resolve; - - if (resolve === originalResolve) { - var then = getThen(entry); - - if (then === originalThen && - entry._state !== PENDING) { - this._settledAt(entry._state, i, entry._result); - } else if (typeof then !== 'function') { - this._remaining--; - this._result[i] = entry; - } else if (c === Promise) { - var promise = new c(noop); - handleMaybeThenable(promise, entry, then); - this._willSettleAt(promise, i); - } else { - this._willSettleAt(new c(function(resolve) { resolve(entry); }), i); - } - } else { - this._willSettleAt(resolve(entry), i); - } -}; - -Enumerator.prototype._settledAt = function(state, i, value) { - var promise = this.promise; - - if (promise._state === PENDING) { - this._remaining--; - - if (state === REJECTED) { - reject(promise, value); - } else { - this._result[i] = value; - } - } - - if (this._remaining === 0) { - fulfill(promise, this._result); - } -}; - -Enumerator.prototype._willSettleAt = function(promise, i) { - var enumerator = this; - - subscribe(promise, undefined, function(value) { - enumerator._settledAt(FULFILLED, i, value); - }, function(reason) { - enumerator._settledAt(REJECTED, i, reason); - }); -}; diff --git a/ts-ticket-office-service/node_modules/es6-promise/lib/es6-promise/polyfill.js b/ts-ticket-office-service/node_modules/es6-promise/lib/es6-promise/polyfill.js deleted file mode 100644 index 6696dfc6a..000000000 --- a/ts-ticket-office-service/node_modules/es6-promise/lib/es6-promise/polyfill.js +++ /dev/null @@ -1,26 +0,0 @@ -/*global self*/ -import Promise from './promise'; - -export default function polyfill() { - var local; - - if (typeof global !== 'undefined') { - local = global; - } else if (typeof self !== 'undefined') { - local = self; - } else { - try { - local = Function('return this')(); - } catch (e) { - throw new Error('polyfill failed because global object is unavailable in this environment'); - } - } - - var P = local.Promise; - - if (P && Object.prototype.toString.call(P.resolve()) === '[object Promise]' && !P.cast) { - return; - } - - local.Promise = Promise; -} diff --git a/ts-ticket-office-service/node_modules/es6-promise/lib/es6-promise/promise.js b/ts-ticket-office-service/node_modules/es6-promise/lib/es6-promise/promise.js deleted file mode 100644 index d95951e2c..000000000 --- a/ts-ticket-office-service/node_modules/es6-promise/lib/es6-promise/promise.js +++ /dev/null @@ -1,384 +0,0 @@ -import { - isFunction -} from './utils'; - -import { - noop, - nextId, - PROMISE_ID, - initializePromise -} from './-internal'; - -import { - asap, - setAsap, - setScheduler -} from './asap'; - -import all from './promise/all'; -import race from './promise/race'; -import Resolve from './promise/resolve'; -import Reject from './promise/reject'; -import then from './then'; - - -function needsResolver() { - throw new TypeError('You must pass a resolver function as the first argument to the promise constructor'); -} - -function needsNew() { - throw new TypeError("Failed to construct 'Promise': Please use the 'new' operator, this object constructor cannot be called as a function."); -} - -export default Promise; -/** - Promise objects represent the eventual result of an asynchronous operation. The - primary way of interacting with a promise is through its `then` method, which - registers callbacks to receive either a promise's eventual value or the reason - why the promise cannot be fulfilled. - - Terminology - ----------- - - - `promise` is an object or function with a `then` method whose behavior conforms to this specification. - - `thenable` is an object or function that defines a `then` method. - - `value` is any legal JavaScript value (including undefined, a thenable, or a promise). - - `exception` is a value that is thrown using the throw statement. - - `reason` is a value that indicates why a promise was rejected. - - `settled` the final resting state of a promise, fulfilled or rejected. - - A promise can be in one of three states: pending, fulfilled, or rejected. - - Promises that are fulfilled have a fulfillment value and are in the fulfilled - state. Promises that are rejected have a rejection reason and are in the - rejected state. A fulfillment value is never a thenable. - - Promises can also be said to *resolve* a value. If this value is also a - promise, then the original promise's settled state will match the value's - settled state. So a promise that *resolves* a promise that rejects will - itself reject, and a promise that *resolves* a promise that fulfills will - itself fulfill. - - - Basic Usage: - ------------ - - ```js - var promise = new Promise(function(resolve, reject) { - // on success - resolve(value); - - // on failure - reject(reason); - }); - - promise.then(function(value) { - // on fulfillment - }, function(reason) { - // on rejection - }); - ``` - - Advanced Usage: - --------------- - - Promises shine when abstracting away asynchronous interactions such as - `XMLHttpRequest`s. - - ```js - function getJSON(url) { - return new Promise(function(resolve, reject){ - var xhr = new XMLHttpRequest(); - - xhr.open('GET', url); - xhr.onreadystatechange = handler; - xhr.responseType = 'json'; - xhr.setRequestHeader('Accept', 'application/json'); - xhr.send(); - - function handler() { - if (this.readyState === this.DONE) { - if (this.status === 200) { - resolve(this.response); - } else { - reject(new Error('getJSON: `' + url + '` failed with status: [' + this.status + ']')); - } - } - }; - }); - } - - getJSON('/posts.json').then(function(json) { - // on fulfillment - }, function(reason) { - // on rejection - }); - ``` - - Unlike callbacks, promises are great composable primitives. - - ```js - Promise.all([ - getJSON('/posts'), - getJSON('/comments') - ]).then(function(values){ - values[0] // => postsJSON - values[1] // => commentsJSON - - return values; - }); - ``` - - @class Promise - @param {function} resolver - Useful for tooling. - @constructor -*/ -function Promise(resolver) { - this[PROMISE_ID] = nextId(); - this._result = this._state = undefined; - this._subscribers = []; - - if (noop !== resolver) { - typeof resolver !== 'function' && needsResolver(); - this instanceof Promise ? initializePromise(this, resolver) : needsNew(); - } -} - -Promise.all = all; -Promise.race = race; -Promise.resolve = Resolve; -Promise.reject = Reject; -Promise._setScheduler = setScheduler; -Promise._setAsap = setAsap; -Promise._asap = asap; - -Promise.prototype = { - constructor: Promise, - -/** - The primary way of interacting with a promise is through its `then` method, - which registers callbacks to receive either a promise's eventual value or the - reason why the promise cannot be fulfilled. - - ```js - findUser().then(function(user){ - // user is available - }, function(reason){ - // user is unavailable, and you are given the reason why - }); - ``` - - Chaining - -------- - - The return value of `then` is itself a promise. This second, 'downstream' - promise is resolved with the return value of the first promise's fulfillment - or rejection handler, or rejected if the handler throws an exception. - - ```js - findUser().then(function (user) { - return user.name; - }, function (reason) { - return 'default name'; - }).then(function (userName) { - // If `findUser` fulfilled, `userName` will be the user's name, otherwise it - // will be `'default name'` - }); - - findUser().then(function (user) { - throw new Error('Found user, but still unhappy'); - }, function (reason) { - throw new Error('`findUser` rejected and we're unhappy'); - }).then(function (value) { - // never reached - }, function (reason) { - // if `findUser` fulfilled, `reason` will be 'Found user, but still unhappy'. - // If `findUser` rejected, `reason` will be '`findUser` rejected and we're unhappy'. - }); - ``` - If the downstream promise does not specify a rejection handler, rejection reasons will be propagated further downstream. - - ```js - findUser().then(function (user) { - throw new PedagogicalException('Upstream error'); - }).then(function (value) { - // never reached - }).then(function (value) { - // never reached - }, function (reason) { - // The `PedgagocialException` is propagated all the way down to here - }); - ``` - - Assimilation - ------------ - - Sometimes the value you want to propagate to a downstream promise can only be - retrieved asynchronously. This can be achieved by returning a promise in the - fulfillment or rejection handler. The downstream promise will then be pending - until the returned promise is settled. This is called *assimilation*. - - ```js - findUser().then(function (user) { - return findCommentsByAuthor(user); - }).then(function (comments) { - // The user's comments are now available - }); - ``` - - If the assimliated promise rejects, then the downstream promise will also reject. - - ```js - findUser().then(function (user) { - return findCommentsByAuthor(user); - }).then(function (comments) { - // If `findCommentsByAuthor` fulfills, we'll have the value here - }, function (reason) { - // If `findCommentsByAuthor` rejects, we'll have the reason here - }); - ``` - - Simple Example - -------------- - - Synchronous Example - - ```javascript - var result; - - try { - result = findResult(); - // success - } catch(reason) { - // failure - } - ``` - - Errback Example - - ```js - findResult(function(result, err){ - if (err) { - // failure - } else { - // success - } - }); - ``` - - Promise Example; - - ```javascript - findResult().then(function(result){ - // success - }, function(reason){ - // failure - }); - ``` - - Advanced Example - -------------- - - Synchronous Example - - ```javascript - var author, books; - - try { - author = findAuthor(); - books = findBooksByAuthor(author); - // success - } catch(reason) { - // failure - } - ``` - - Errback Example - - ```js - - function foundBooks(books) { - - } - - function failure(reason) { - - } - - findAuthor(function(author, err){ - if (err) { - failure(err); - // failure - } else { - try { - findBoooksByAuthor(author, function(books, err) { - if (err) { - failure(err); - } else { - try { - foundBooks(books); - } catch(reason) { - failure(reason); - } - } - }); - } catch(error) { - failure(err); - } - // success - } - }); - ``` - - Promise Example; - - ```javascript - findAuthor(). - then(findBooksByAuthor). - then(function(books){ - // found books - }).catch(function(reason){ - // something went wrong - }); - ``` - - @method then - @param {Function} onFulfilled - @param {Function} onRejected - Useful for tooling. - @return {Promise} -*/ - then: then, - -/** - `catch` is simply sugar for `then(undefined, onRejection)` which makes it the same - as the catch block of a try/catch statement. - - ```js - function findAuthor(){ - throw new Error('couldn't find that author'); - } - - // synchronous - try { - findAuthor(); - } catch(reason) { - // something went wrong - } - - // async with promises - findAuthor().catch(function(reason){ - // something went wrong - }); - ``` - - @method catch - @param {Function} onRejection - Useful for tooling. - @return {Promise} -*/ - 'catch': function(onRejection) { - return this.then(null, onRejection); - } -}; diff --git a/ts-ticket-office-service/node_modules/es6-promise/lib/es6-promise/promise/all.js b/ts-ticket-office-service/node_modules/es6-promise/lib/es6-promise/promise/all.js deleted file mode 100644 index 03033f0dc..000000000 --- a/ts-ticket-office-service/node_modules/es6-promise/lib/es6-promise/promise/all.js +++ /dev/null @@ -1,52 +0,0 @@ -import Enumerator from '../enumerator'; - -/** - `Promise.all` accepts an array of promises, and returns a new promise which - is fulfilled with an array of fulfillment values for the passed promises, or - rejected with the reason of the first passed promise to be rejected. It casts all - elements of the passed iterable to promises as it runs this algorithm. - - Example: - - ```javascript - var promise1 = resolve(1); - var promise2 = resolve(2); - var promise3 = resolve(3); - var promises = [ promise1, promise2, promise3 ]; - - Promise.all(promises).then(function(array){ - // The array here would be [ 1, 2, 3 ]; - }); - ``` - - If any of the `promises` given to `all` are rejected, the first promise - that is rejected will be given as an argument to the returned promises's - rejection handler. For example: - - Example: - - ```javascript - var promise1 = resolve(1); - var promise2 = reject(new Error("2")); - var promise3 = reject(new Error("3")); - var promises = [ promise1, promise2, promise3 ]; - - Promise.all(promises).then(function(array){ - // Code here never runs because there are rejected promises! - }, function(error) { - // error.message === "2" - }); - ``` - - @method all - @static - @param {Array} entries array of promises - @param {String} label optional string for labeling the promise. - Useful for tooling. - @return {Promise} promise that is fulfilled when all `promises` have been - fulfilled, or rejected if any of them become rejected. - @static -*/ -export default function all(entries) { - return new Enumerator(this, entries).promise; -} diff --git a/ts-ticket-office-service/node_modules/es6-promise/lib/es6-promise/promise/race.js b/ts-ticket-office-service/node_modules/es6-promise/lib/es6-promise/promise/race.js deleted file mode 100644 index 8c922e312..000000000 --- a/ts-ticket-office-service/node_modules/es6-promise/lib/es6-promise/promise/race.js +++ /dev/null @@ -1,86 +0,0 @@ -import { - isArray -} from "../utils"; - -/** - `Promise.race` returns a new promise which is settled in the same way as the - first passed promise to settle. - - Example: - - ```javascript - var promise1 = new Promise(function(resolve, reject){ - setTimeout(function(){ - resolve('promise 1'); - }, 200); - }); - - var promise2 = new Promise(function(resolve, reject){ - setTimeout(function(){ - resolve('promise 2'); - }, 100); - }); - - Promise.race([promise1, promise2]).then(function(result){ - // result === 'promise 2' because it was resolved before promise1 - // was resolved. - }); - ``` - - `Promise.race` is deterministic in that only the state of the first - settled promise matters. For example, even if other promises given to the - `promises` array argument are resolved, but the first settled promise has - become rejected before the other promises became fulfilled, the returned - promise will become rejected: - - ```javascript - var promise1 = new Promise(function(resolve, reject){ - setTimeout(function(){ - resolve('promise 1'); - }, 200); - }); - - var promise2 = new Promise(function(resolve, reject){ - setTimeout(function(){ - reject(new Error('promise 2')); - }, 100); - }); - - Promise.race([promise1, promise2]).then(function(result){ - // Code here never runs - }, function(reason){ - // reason.message === 'promise 2' because promise 2 became rejected before - // promise 1 became fulfilled - }); - ``` - - An example real-world use case is implementing timeouts: - - ```javascript - Promise.race([ajax('foo.json'), timeout(5000)]) - ``` - - @method race - @static - @param {Array} promises array of promises to observe - Useful for tooling. - @return {Promise} a promise which settles in the same way as the first passed - promise to settle. -*/ -export default function race(entries) { - /*jshint validthis:true */ - var Constructor = this; - - if (!isArray(entries)) { - return new Constructor(function(resolve, reject) { - reject(new TypeError('You must pass an array to race.')); - }); - } else { - return new Constructor(function(resolve, reject) { - var length = entries.length; - for (var i = 0; i < length; i++) { - Constructor.resolve(entries[i]).then(resolve, reject); - } - }); - } -} diff --git a/ts-ticket-office-service/node_modules/es6-promise/lib/es6-promise/promise/reject.js b/ts-ticket-office-service/node_modules/es6-promise/lib/es6-promise/promise/reject.js deleted file mode 100644 index 63b86cba1..000000000 --- a/ts-ticket-office-service/node_modules/es6-promise/lib/es6-promise/promise/reject.js +++ /dev/null @@ -1,46 +0,0 @@ -import { - noop, - reject as _reject -} from '../-internal'; - -/** - `Promise.reject` returns a promise rejected with the passed `reason`. - It is shorthand for the following: - - ```javascript - var promise = new Promise(function(resolve, reject){ - reject(new Error('WHOOPS')); - }); - - promise.then(function(value){ - // Code here doesn't run because the promise is rejected! - }, function(reason){ - // reason.message === 'WHOOPS' - }); - ``` - - Instead of writing the above, your code now simply becomes the following: - - ```javascript - var promise = Promise.reject(new Error('WHOOPS')); - - promise.then(function(value){ - // Code here doesn't run because the promise is rejected! - }, function(reason){ - // reason.message === 'WHOOPS' - }); - ``` - - @method reject - @static - @param {Any} reason value that the returned promise will be rejected with. - Useful for tooling. - @return {Promise} a promise rejected with the given `reason`. -*/ -export default function reject(reason) { - /*jshint validthis:true */ - var Constructor = this; - var promise = new Constructor(noop); - _reject(promise, reason); - return promise; -} diff --git a/ts-ticket-office-service/node_modules/es6-promise/lib/es6-promise/promise/resolve.js b/ts-ticket-office-service/node_modules/es6-promise/lib/es6-promise/promise/resolve.js deleted file mode 100644 index 201a545d6..000000000 --- a/ts-ticket-office-service/node_modules/es6-promise/lib/es6-promise/promise/resolve.js +++ /dev/null @@ -1,48 +0,0 @@ -import { - noop, - resolve as _resolve -} from '../-internal'; - -/** - `Promise.resolve` returns a promise that will become resolved with the - passed `value`. It is shorthand for the following: - - ```javascript - var promise = new Promise(function(resolve, reject){ - resolve(1); - }); - - promise.then(function(value){ - // value === 1 - }); - ``` - - Instead of writing the above, your code now simply becomes the following: - - ```javascript - var promise = Promise.resolve(1); - - promise.then(function(value){ - // value === 1 - }); - ``` - - @method resolve - @static - @param {Any} value value that the returned promise will be resolved with - Useful for tooling. - @return {Promise} a promise that will become fulfilled with the given - `value` -*/ -export default function resolve(object) { - /*jshint validthis:true */ - var Constructor = this; - - if (object && typeof object === 'object' && object.constructor === Constructor) { - return object; - } - - var promise = new Constructor(noop); - _resolve(promise, object); - return promise; -} diff --git a/ts-ticket-office-service/node_modules/es6-promise/lib/es6-promise/then.js b/ts-ticket-office-service/node_modules/es6-promise/lib/es6-promise/then.js deleted file mode 100644 index f97e946ad..000000000 --- a/ts-ticket-office-service/node_modules/es6-promise/lib/es6-promise/then.js +++ /dev/null @@ -1,34 +0,0 @@ -import { - invokeCallback, - subscribe, - FULFILLED, - REJECTED, - noop, - makePromise, - PROMISE_ID -} from './-internal'; - -import { asap } from './asap'; - -export default function then(onFulfillment, onRejection) { - var parent = this; - - var child = new this.constructor(noop); - - if (child[PROMISE_ID] === undefined) { - makePromise(child); - } - - var state = parent._state; - - if (state) { - var callback = arguments[state - 1]; - asap(function(){ - invokeCallback(state, child, callback, parent._result); - }); - } else { - subscribe(parent, child, onFulfillment, onRejection); - } - - return child; -} diff --git a/ts-ticket-office-service/node_modules/es6-promise/lib/es6-promise/utils.js b/ts-ticket-office-service/node_modules/es6-promise/lib/es6-promise/utils.js deleted file mode 100644 index 31ec6f9c5..000000000 --- a/ts-ticket-office-service/node_modules/es6-promise/lib/es6-promise/utils.js +++ /dev/null @@ -1,22 +0,0 @@ -export function objectOrFunction(x) { - return typeof x === 'function' || (typeof x === 'object' && x !== null); -} - -export function isFunction(x) { - return typeof x === 'function'; -} - -export function isMaybeThenable(x) { - return typeof x === 'object' && x !== null; -} - -var _isArray; -if (!Array.isArray) { - _isArray = function (x) { - return Object.prototype.toString.call(x) === '[object Array]'; - }; -} else { - _isArray = Array.isArray; -} - -export var isArray = _isArray; diff --git a/ts-ticket-office-service/node_modules/es6-promise/package.json b/ts-ticket-office-service/node_modules/es6-promise/package.json deleted file mode 100644 index 518f05315..000000000 --- a/ts-ticket-office-service/node_modules/es6-promise/package.json +++ /dev/null @@ -1,130 +0,0 @@ -{ - "_args": [ - [ - { - "raw": "es6-promise@3.2.1", - "scope": null, - "escapedName": "es6-promise", - "name": "es6-promise", - "rawSpec": "3.2.1", - "spec": "3.2.1", - "type": "version" - }, - "F:\\gitwork\\workspace_microservices\\ts-ticket-office-service\\node_modules\\mongodb" - ] - ], - "_from": "es6-promise@3.2.1", - "_id": "es6-promise@3.2.1", - "_inCache": true, - "_location": "/es6-promise", - "_nodeVersion": "5.10.1", - "_npmOperationalInternal": { - "host": "packages-12-west.internal.npmjs.com", - "tmp": "tmp/es6-promise-3.2.1.tgz_1463027774105_0.6333294357173145" - }, - "_npmUser": { - "name": "stefanpenner", - "email": "stefan.penner@gmail.com" - }, - "_npmVersion": "3.8.8", - "_phantomChildren": {}, - "_requested": { - "raw": "es6-promise@3.2.1", - "scope": null, - "escapedName": "es6-promise", - "name": "es6-promise", - "rawSpec": "3.2.1", - "spec": "3.2.1", - "type": "version" - }, - "_requiredBy": [ - "/mongodb" - ], - "_resolved": "https://registry.npmjs.org/es6-promise/-/es6-promise-3.2.1.tgz", - "_shasum": "ec56233868032909207170c39448e24449dd1fc4", - "_shrinkwrap": null, - "_spec": "es6-promise@3.2.1", - "_where": "F:\\gitwork\\workspace_microservices\\ts-ticket-office-service\\node_modules\\mongodb", - "author": { - "name": "Yehuda Katz, Tom Dale, Stefan Penner and contributors", - "url": "Conversion to ES6 API by Jake Archibald" - }, - "browser": { - "vertx": false - }, - "bugs": { - "url": "https://github.com/jakearchibald/ES6-Promises/issues" - }, - "dependencies": {}, - "description": "A lightweight library that provides tools for organizing asynchronous code", - "devDependencies": { - "babel-eslint": "^6.0.0", - "broccoli-es6-module-transpiler": "^0.5.0", - "broccoli-jshint": "^2.1.0", - "broccoli-merge-trees": "^1.1.1", - "broccoli-replace": "^0.12.0", - "broccoli-stew": "^1.2.0", - "broccoli-uglify-js": "^0.1.3", - "broccoli-watchify": "^0.2.0", - "ember-cli": "2.5.0", - "ember-publisher": "0.0.7", - "git-repo-version": "0.0.3", - "json3": "^3.3.2", - "mocha": "^1.20.1", - "promises-aplus-tests-phantom": "^2.1.0-revise", - "release-it": "0.0.10" - }, - "directories": { - "lib": "lib" - }, - "dist": { - "shasum": "ec56233868032909207170c39448e24449dd1fc4", - "tarball": "https://registry.npmjs.org/es6-promise/-/es6-promise-3.2.1.tgz" - }, - "files": [ - "dist", - "lib", - "!dist/test" - ], - "gitHead": "5df472ec56d5b9fbc76589383852008d46055c61", - "homepage": "https://github.com/jakearchibald/ES6-Promises#readme", - "keywords": [ - "promises", - "futures" - ], - "license": "MIT", - "main": "dist/es6-promise.js", - "maintainers": [ - { - "name": "jaffathecake", - "email": "jaffathecake@gmail.com" - }, - { - "name": "stefanpenner", - "email": "stefan.penner@gmail.com" - } - ], - "name": "es6-promise", - "namespace": "es6-promise", - "optionalDependencies": {}, - "readme": "ERROR: No README data found!", - "repository": { - "type": "git", - "url": "git://github.com/jakearchibald/ES6-Promises.git" - }, - "scripts": { - "build": "ember build", - "build:production": "ember build --environment production", - "dry-run-release": "ember build --environment production && release-it --dry-run --non-interactive", - "lint": "jshint lib", - "prepublish": "ember build --environment production", - "start": "ember s", - "test": "ember test", - "test:node": "ember build && mocha ./dist/test/browserify", - "test:server": "ember test --server" - }, - "spm": { - "main": "dist/es6-promise.js" - }, - "version": "3.2.1" -} diff --git a/ts-ticket-office-service/node_modules/ieee754/LICENSE b/ts-ticket-office-service/node_modules/ieee754/LICENSE new file mode 100644 index 000000000..5aac82c78 --- /dev/null +++ b/ts-ticket-office-service/node_modules/ieee754/LICENSE @@ -0,0 +1,11 @@ +Copyright 2008 Fair Oaks Labs, Inc. + +Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: + +1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. + +2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. + +3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. diff --git a/ts-ticket-office-service/node_modules/ieee754/README.md b/ts-ticket-office-service/node_modules/ieee754/README.md new file mode 100644 index 000000000..cb7527b3c --- /dev/null +++ b/ts-ticket-office-service/node_modules/ieee754/README.md @@ -0,0 +1,51 @@ +# ieee754 [![travis][travis-image]][travis-url] [![npm][npm-image]][npm-url] [![downloads][downloads-image]][downloads-url] [![javascript style guide][standard-image]][standard-url] + +[travis-image]: https://img.shields.io/travis/feross/ieee754/master.svg +[travis-url]: https://travis-ci.org/feross/ieee754 +[npm-image]: https://img.shields.io/npm/v/ieee754.svg +[npm-url]: https://npmjs.org/package/ieee754 +[downloads-image]: https://img.shields.io/npm/dm/ieee754.svg +[downloads-url]: https://npmjs.org/package/ieee754 +[standard-image]: https://img.shields.io/badge/code_style-standard-brightgreen.svg +[standard-url]: https://standardjs.com + +[![saucelabs][saucelabs-image]][saucelabs-url] + +[saucelabs-image]: https://saucelabs.com/browser-matrix/ieee754.svg +[saucelabs-url]: https://saucelabs.com/u/ieee754 + +### Read/write IEEE754 floating point numbers from/to a Buffer or array-like object. + +## install + +``` +npm install ieee754 +``` + +## methods + +`var ieee754 = require('ieee754')` + +The `ieee754` object has the following functions: + +``` +ieee754.read = function (buffer, offset, isLE, mLen, nBytes) +ieee754.write = function (buffer, value, offset, isLE, mLen, nBytes) +``` + +The arguments mean the following: + +- buffer = the buffer +- offset = offset into the buffer +- value = value to set (only for `write`) +- isLe = is little endian? +- mLen = mantissa length +- nBytes = number of bytes + +## what is ieee754? + +The IEEE Standard for Floating-Point Arithmetic (IEEE 754) is a technical standard for floating-point computation. [Read more](http://en.wikipedia.org/wiki/IEEE_floating_point). + +## license + +BSD 3 Clause. Copyright (c) 2008, Fair Oaks Labs, Inc. diff --git a/ts-ticket-office-service/node_modules/ieee754/index.d.ts b/ts-ticket-office-service/node_modules/ieee754/index.d.ts new file mode 100644 index 000000000..f1e435487 --- /dev/null +++ b/ts-ticket-office-service/node_modules/ieee754/index.d.ts @@ -0,0 +1,10 @@ +declare namespace ieee754 { + export function read( + buffer: Uint8Array, offset: number, isLE: boolean, mLen: number, + nBytes: number): number; + export function write( + buffer: Uint8Array, value: number, offset: number, isLE: boolean, + mLen: number, nBytes: number): void; + } + + export = ieee754; \ No newline at end of file diff --git a/ts-ticket-office-service/node_modules/ieee754/index.js b/ts-ticket-office-service/node_modules/ieee754/index.js new file mode 100644 index 000000000..81d26c343 --- /dev/null +++ b/ts-ticket-office-service/node_modules/ieee754/index.js @@ -0,0 +1,85 @@ +/*! ieee754. BSD-3-Clause License. Feross Aboukhadijeh */ +exports.read = function (buffer, offset, isLE, mLen, nBytes) { + var e, m + var eLen = (nBytes * 8) - mLen - 1 + var eMax = (1 << eLen) - 1 + var eBias = eMax >> 1 + var nBits = -7 + var i = isLE ? (nBytes - 1) : 0 + var d = isLE ? -1 : 1 + var s = buffer[offset + i] + + i += d + + e = s & ((1 << (-nBits)) - 1) + s >>= (-nBits) + nBits += eLen + for (; nBits > 0; e = (e * 256) + buffer[offset + i], i += d, nBits -= 8) {} + + m = e & ((1 << (-nBits)) - 1) + e >>= (-nBits) + nBits += mLen + for (; nBits > 0; m = (m * 256) + buffer[offset + i], i += d, nBits -= 8) {} + + if (e === 0) { + e = 1 - eBias + } else if (e === eMax) { + return m ? NaN : ((s ? -1 : 1) * Infinity) + } else { + m = m + Math.pow(2, mLen) + e = e - eBias + } + return (s ? -1 : 1) * m * Math.pow(2, e - mLen) +} + +exports.write = function (buffer, value, offset, isLE, mLen, nBytes) { + var e, m, c + var eLen = (nBytes * 8) - mLen - 1 + var eMax = (1 << eLen) - 1 + var eBias = eMax >> 1 + var rt = (mLen === 23 ? Math.pow(2, -24) - Math.pow(2, -77) : 0) + var i = isLE ? 0 : (nBytes - 1) + var d = isLE ? 1 : -1 + var s = value < 0 || (value === 0 && 1 / value < 0) ? 1 : 0 + + value = Math.abs(value) + + if (isNaN(value) || value === Infinity) { + m = isNaN(value) ? 1 : 0 + e = eMax + } else { + e = Math.floor(Math.log(value) / Math.LN2) + if (value * (c = Math.pow(2, -e)) < 1) { + e-- + c *= 2 + } + if (e + eBias >= 1) { + value += rt / c + } else { + value += rt * Math.pow(2, 1 - eBias) + } + if (value * c >= 2) { + e++ + c /= 2 + } + + if (e + eBias >= eMax) { + m = 0 + e = eMax + } else if (e + eBias >= 1) { + m = ((value * c) - 1) * Math.pow(2, mLen) + e = e + eBias + } else { + m = value * Math.pow(2, eBias - 1) * Math.pow(2, mLen) + e = 0 + } + } + + for (; mLen >= 8; buffer[offset + i] = m & 0xff, i += d, m /= 256, mLen -= 8) {} + + e = (e << mLen) | m + eLen += mLen + for (; eLen > 0; buffer[offset + i] = e & 0xff, i += d, e /= 256, eLen -= 8) {} + + buffer[offset + i - d] |= s * 128 +} diff --git a/ts-ticket-office-service/node_modules/ieee754/package.json b/ts-ticket-office-service/node_modules/ieee754/package.json new file mode 100644 index 000000000..7b2385138 --- /dev/null +++ b/ts-ticket-office-service/node_modules/ieee754/package.json @@ -0,0 +1,52 @@ +{ + "name": "ieee754", + "description": "Read/write IEEE754 floating point numbers from/to a Buffer or array-like object", + "version": "1.2.1", + "author": { + "name": "Feross Aboukhadijeh", + "email": "feross@feross.org", + "url": "https://feross.org" + }, + "contributors": [ + "Romain Beauxis " + ], + "devDependencies": { + "airtap": "^3.0.0", + "standard": "*", + "tape": "^5.0.1" + }, + "keywords": [ + "IEEE 754", + "buffer", + "convert", + "floating point", + "ieee754" + ], + "license": "BSD-3-Clause", + "main": "index.js", + "types": "index.d.ts", + "repository": { + "type": "git", + "url": "git://github.com/feross/ieee754.git" + }, + "scripts": { + "test": "standard && npm run test-node && npm run test-browser", + "test-browser": "airtap -- test/*.js", + "test-browser-local": "airtap --local -- test/*.js", + "test-node": "tape test/*.js" + }, + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/feross" + }, + { + "type": "patreon", + "url": "https://www.patreon.com/feross" + }, + { + "type": "consulting", + "url": "https://feross.org/support" + } + ] +} diff --git a/ts-ticket-office-service/node_modules/ip/README.md b/ts-ticket-office-service/node_modules/ip/README.md new file mode 100644 index 000000000..22e5819ff --- /dev/null +++ b/ts-ticket-office-service/node_modules/ip/README.md @@ -0,0 +1,90 @@ +# IP +[![](https://badge.fury.io/js/ip.svg)](https://www.npmjs.com/package/ip) + +IP address utilities for node.js + +## Installation + +### npm +```shell +npm install ip +``` + +### git + +```shell +git clone https://github.com/indutny/node-ip.git +``` + +## Usage +Get your ip address, compare ip addresses, validate ip addresses, etc. + +```js +var ip = require('ip'); + +ip.address() // my ip address +ip.isEqual('::1', '::0:1'); // true +ip.toBuffer('127.0.0.1') // Buffer([127, 0, 0, 1]) +ip.toString(new Buffer([127, 0, 0, 1])) // 127.0.0.1 +ip.fromPrefixLen(24) // 255.255.255.0 +ip.mask('192.168.1.134', '255.255.255.0') // 192.168.1.0 +ip.cidr('192.168.1.134/26') // 192.168.1.128 +ip.not('255.255.255.0') // 0.0.0.255 +ip.or('192.168.1.134', '0.0.0.255') // 192.168.1.255 +ip.isPrivate('127.0.0.1') // true +ip.isV4Format('127.0.0.1'); // true +ip.isV6Format('::ffff:127.0.0.1'); // true + +// operate on buffers in-place +var buf = new Buffer(128); +var offset = 64; +ip.toBuffer('127.0.0.1', buf, offset); // [127, 0, 0, 1] at offset 64 +ip.toString(buf, offset, 4); // '127.0.0.1' + +// subnet information +ip.subnet('192.168.1.134', '255.255.255.192') +// { networkAddress: '192.168.1.128', +// firstAddress: '192.168.1.129', +// lastAddress: '192.168.1.190', +// broadcastAddress: '192.168.1.191', +// subnetMask: '255.255.255.192', +// subnetMaskLength: 26, +// numHosts: 62, +// length: 64, +// contains: function(addr){...} } +ip.cidrSubnet('192.168.1.134/26') +// Same as previous. + +// range checking +ip.cidrSubnet('192.168.1.134/26').contains('192.168.1.190') // true + + +// ipv4 long conversion +ip.toLong('127.0.0.1'); // 2130706433 +ip.fromLong(2130706433); // '127.0.0.1' +``` + +### License + +This software is licensed under the MIT License. + +Copyright Fedor Indutny, 2012. + +Permission is hereby granted, free of charge, to any person obtaining a +copy of this software and associated documentation files (the +"Software"), to deal in the Software without restriction, including +without limitation the rights to use, copy, modify, merge, publish, +distribute, sublicense, and/or sell copies of the Software, and to permit +persons to whom the Software is furnished to do so, subject to the +following conditions: + +The above copyright notice and this permission notice shall be included +in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/ts-ticket-office-service/node_modules/ip/lib/ip.js b/ts-ticket-office-service/node_modules/ip/lib/ip.js new file mode 100644 index 000000000..4b2adb5ad --- /dev/null +++ b/ts-ticket-office-service/node_modules/ip/lib/ip.js @@ -0,0 +1,422 @@ +const ip = exports; +const { Buffer } = require('buffer'); +const os = require('os'); + +ip.toBuffer = function (ip, buff, offset) { + offset = ~~offset; + + let result; + + if (this.isV4Format(ip)) { + result = buff || Buffer.alloc(offset + 4); + ip.split(/\./g).map((byte) => { + result[offset++] = parseInt(byte, 10) & 0xff; + }); + } else if (this.isV6Format(ip)) { + const sections = ip.split(':', 8); + + let i; + for (i = 0; i < sections.length; i++) { + const isv4 = this.isV4Format(sections[i]); + let v4Buffer; + + if (isv4) { + v4Buffer = this.toBuffer(sections[i]); + sections[i] = v4Buffer.slice(0, 2).toString('hex'); + } + + if (v4Buffer && ++i < 8) { + sections.splice(i, 0, v4Buffer.slice(2, 4).toString('hex')); + } + } + + if (sections[0] === '') { + while (sections.length < 8) sections.unshift('0'); + } else if (sections[sections.length - 1] === '') { + while (sections.length < 8) sections.push('0'); + } else if (sections.length < 8) { + for (i = 0; i < sections.length && sections[i] !== ''; i++); + const argv = [i, 1]; + for (i = 9 - sections.length; i > 0; i--) { + argv.push('0'); + } + sections.splice(...argv); + } + + result = buff || Buffer.alloc(offset + 16); + for (i = 0; i < sections.length; i++) { + const word = parseInt(sections[i], 16); + result[offset++] = (word >> 8) & 0xff; + result[offset++] = word & 0xff; + } + } + + if (!result) { + throw Error(`Invalid ip address: ${ip}`); + } + + return result; +}; + +ip.toString = function (buff, offset, length) { + offset = ~~offset; + length = length || (buff.length - offset); + + let result = []; + if (length === 4) { + // IPv4 + for (let i = 0; i < length; i++) { + result.push(buff[offset + i]); + } + result = result.join('.'); + } else if (length === 16) { + // IPv6 + for (let i = 0; i < length; i += 2) { + result.push(buff.readUInt16BE(offset + i).toString(16)); + } + result = result.join(':'); + result = result.replace(/(^|:)0(:0)*:0(:|$)/, '$1::$3'); + result = result.replace(/:{3,4}/, '::'); + } + + return result; +}; + +const ipv4Regex = /^(\d{1,3}\.){3,3}\d{1,3}$/; +const ipv6Regex = /^(::)?(((\d{1,3}\.){3}(\d{1,3}){1})?([0-9a-f]){0,4}:{0,2}){1,8}(::)?$/i; + +ip.isV4Format = function (ip) { + return ipv4Regex.test(ip); +}; + +ip.isV6Format = function (ip) { + return ipv6Regex.test(ip); +}; + +function _normalizeFamily(family) { + if (family === 4) { + return 'ipv4'; + } + if (family === 6) { + return 'ipv6'; + } + return family ? family.toLowerCase() : 'ipv4'; +} + +ip.fromPrefixLen = function (prefixlen, family) { + if (prefixlen > 32) { + family = 'ipv6'; + } else { + family = _normalizeFamily(family); + } + + let len = 4; + if (family === 'ipv6') { + len = 16; + } + const buff = Buffer.alloc(len); + + for (let i = 0, n = buff.length; i < n; ++i) { + let bits = 8; + if (prefixlen < 8) { + bits = prefixlen; + } + prefixlen -= bits; + + buff[i] = ~(0xff >> bits) & 0xff; + } + + return ip.toString(buff); +}; + +ip.mask = function (addr, mask) { + addr = ip.toBuffer(addr); + mask = ip.toBuffer(mask); + + const result = Buffer.alloc(Math.max(addr.length, mask.length)); + + // Same protocol - do bitwise and + let i; + if (addr.length === mask.length) { + for (i = 0; i < addr.length; i++) { + result[i] = addr[i] & mask[i]; + } + } else if (mask.length === 4) { + // IPv6 address and IPv4 mask + // (Mask low bits) + for (i = 0; i < mask.length; i++) { + result[i] = addr[addr.length - 4 + i] & mask[i]; + } + } else { + // IPv6 mask and IPv4 addr + for (i = 0; i < result.length - 6; i++) { + result[i] = 0; + } + + // ::ffff:ipv4 + result[10] = 0xff; + result[11] = 0xff; + for (i = 0; i < addr.length; i++) { + result[i + 12] = addr[i] & mask[i + 12]; + } + i += 12; + } + for (; i < result.length; i++) { + result[i] = 0; + } + + return ip.toString(result); +}; + +ip.cidr = function (cidrString) { + const cidrParts = cidrString.split('/'); + + const addr = cidrParts[0]; + if (cidrParts.length !== 2) { + throw new Error(`invalid CIDR subnet: ${addr}`); + } + + const mask = ip.fromPrefixLen(parseInt(cidrParts[1], 10)); + + return ip.mask(addr, mask); +}; + +ip.subnet = function (addr, mask) { + const networkAddress = ip.toLong(ip.mask(addr, mask)); + + // Calculate the mask's length. + const maskBuffer = ip.toBuffer(mask); + let maskLength = 0; + + for (let i = 0; i < maskBuffer.length; i++) { + if (maskBuffer[i] === 0xff) { + maskLength += 8; + } else { + let octet = maskBuffer[i] & 0xff; + while (octet) { + octet = (octet << 1) & 0xff; + maskLength++; + } + } + } + + const numberOfAddresses = 2 ** (32 - maskLength); + + return { + networkAddress: ip.fromLong(networkAddress), + firstAddress: numberOfAddresses <= 2 + ? ip.fromLong(networkAddress) + : ip.fromLong(networkAddress + 1), + lastAddress: numberOfAddresses <= 2 + ? ip.fromLong(networkAddress + numberOfAddresses - 1) + : ip.fromLong(networkAddress + numberOfAddresses - 2), + broadcastAddress: ip.fromLong(networkAddress + numberOfAddresses - 1), + subnetMask: mask, + subnetMaskLength: maskLength, + numHosts: numberOfAddresses <= 2 + ? numberOfAddresses : numberOfAddresses - 2, + length: numberOfAddresses, + contains(other) { + return networkAddress === ip.toLong(ip.mask(other, mask)); + }, + }; +}; + +ip.cidrSubnet = function (cidrString) { + const cidrParts = cidrString.split('/'); + + const addr = cidrParts[0]; + if (cidrParts.length !== 2) { + throw new Error(`invalid CIDR subnet: ${addr}`); + } + + const mask = ip.fromPrefixLen(parseInt(cidrParts[1], 10)); + + return ip.subnet(addr, mask); +}; + +ip.not = function (addr) { + const buff = ip.toBuffer(addr); + for (let i = 0; i < buff.length; i++) { + buff[i] = 0xff ^ buff[i]; + } + return ip.toString(buff); +}; + +ip.or = function (a, b) { + a = ip.toBuffer(a); + b = ip.toBuffer(b); + + // same protocol + if (a.length === b.length) { + for (let i = 0; i < a.length; ++i) { + a[i] |= b[i]; + } + return ip.toString(a); + + // mixed protocols + } + let buff = a; + let other = b; + if (b.length > a.length) { + buff = b; + other = a; + } + + const offset = buff.length - other.length; + for (let i = offset; i < buff.length; ++i) { + buff[i] |= other[i - offset]; + } + + return ip.toString(buff); +}; + +ip.isEqual = function (a, b) { + a = ip.toBuffer(a); + b = ip.toBuffer(b); + + // Same protocol + if (a.length === b.length) { + for (let i = 0; i < a.length; i++) { + if (a[i] !== b[i]) return false; + } + return true; + } + + // Swap + if (b.length === 4) { + const t = b; + b = a; + a = t; + } + + // a - IPv4, b - IPv6 + for (let i = 0; i < 10; i++) { + if (b[i] !== 0) return false; + } + + const word = b.readUInt16BE(10); + if (word !== 0 && word !== 0xffff) return false; + + for (let i = 0; i < 4; i++) { + if (a[i] !== b[i + 12]) return false; + } + + return true; +}; + +ip.isPrivate = function (addr) { + return /^(::f{4}:)?10\.([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})$/i + .test(addr) + || /^(::f{4}:)?192\.168\.([0-9]{1,3})\.([0-9]{1,3})$/i.test(addr) + || /^(::f{4}:)?172\.(1[6-9]|2\d|30|31)\.([0-9]{1,3})\.([0-9]{1,3})$/i + .test(addr) + || /^(::f{4}:)?127\.([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})$/i.test(addr) + || /^(::f{4}:)?169\.254\.([0-9]{1,3})\.([0-9]{1,3})$/i.test(addr) + || /^f[cd][0-9a-f]{2}:/i.test(addr) + || /^fe80:/i.test(addr) + || /^::1$/.test(addr) + || /^::$/.test(addr); +}; + +ip.isPublic = function (addr) { + return !ip.isPrivate(addr); +}; + +ip.isLoopback = function (addr) { + return /^(::f{4}:)?127\.([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})/ + .test(addr) + || /^fe80::1$/.test(addr) + || /^::1$/.test(addr) + || /^::$/.test(addr); +}; + +ip.loopback = function (family) { + // + // Default to `ipv4` + // + family = _normalizeFamily(family); + + if (family !== 'ipv4' && family !== 'ipv6') { + throw new Error('family must be ipv4 or ipv6'); + } + + return family === 'ipv4' ? '127.0.0.1' : 'fe80::1'; +}; + +// +// ### function address (name, family) +// #### @name {string|'public'|'private'} **Optional** Name or security +// of the network interface. +// #### @family {ipv4|ipv6} **Optional** IP family of the address (defaults +// to ipv4). +// +// Returns the address for the network interface on the current system with +// the specified `name`: +// * String: First `family` address of the interface. +// If not found see `undefined`. +// * 'public': the first public ip address of family. +// * 'private': the first private ip address of family. +// * undefined: First address with `ipv4` or loopback address `127.0.0.1`. +// +ip.address = function (name, family) { + const interfaces = os.networkInterfaces(); + + // + // Default to `ipv4` + // + family = _normalizeFamily(family); + + // + // If a specific network interface has been named, + // return the address. + // + if (name && name !== 'private' && name !== 'public') { + const res = interfaces[name].filter((details) => { + const itemFamily = _normalizeFamily(details.family); + return itemFamily === family; + }); + if (res.length === 0) { + return undefined; + } + return res[0].address; + } + + const all = Object.keys(interfaces).map((nic) => { + // + // Note: name will only be `public` or `private` + // when this is called. + // + const addresses = interfaces[nic].filter((details) => { + details.family = _normalizeFamily(details.family); + if (details.family !== family || ip.isLoopback(details.address)) { + return false; + } if (!name) { + return true; + } + + return name === 'public' ? ip.isPrivate(details.address) + : ip.isPublic(details.address); + }); + + return addresses.length ? addresses[0].address : undefined; + }).filter(Boolean); + + return !all.length ? ip.loopback(family) : all[0]; +}; + +ip.toLong = function (ip) { + let ipl = 0; + ip.split('.').forEach((octet) => { + ipl <<= 8; + ipl += parseInt(octet); + }); + return (ipl >>> 0); +}; + +ip.fromLong = function (ipl) { + return (`${ipl >>> 24}.${ + ipl >> 16 & 255}.${ + ipl >> 8 & 255}.${ + ipl & 255}`); +}; diff --git a/ts-ticket-office-service/node_modules/ip/package.json b/ts-ticket-office-service/node_modules/ip/package.json new file mode 100644 index 000000000..f0d95e9b7 --- /dev/null +++ b/ts-ticket-office-service/node_modules/ip/package.json @@ -0,0 +1,25 @@ +{ + "name": "ip", + "version": "2.0.0", + "author": "Fedor Indutny ", + "homepage": "https://github.com/indutny/node-ip", + "repository": { + "type": "git", + "url": "http://github.com/indutny/node-ip.git" + }, + "files": [ + "lib", + "README.md" + ], + "main": "lib/ip", + "devDependencies": { + "eslint": "^8.15.0", + "mocha": "^10.0.0" + }, + "scripts": { + "lint": "eslint lib/*.js test/*.js", + "test": "npm run lint && mocha --reporter spec test/*-test.js", + "fix": "npm run lint -- --fix" + }, + "license": "MIT" +} diff --git a/ts-ticket-office-service/node_modules/jade/bin/jade.js b/ts-ticket-office-service/node_modules/jade/bin/jade.js old mode 100644 new mode 100755 diff --git a/ts-ticket-office-service/node_modules/es6-promise/LICENSE b/ts-ticket-office-service/node_modules/memory-pager/LICENSE similarity index 51% rename from ts-ticket-office-service/node_modules/es6-promise/LICENSE rename to ts-ticket-office-service/node_modules/memory-pager/LICENSE index 954ec5992..56fce0895 100644 --- a/ts-ticket-office-service/node_modules/es6-promise/LICENSE +++ b/ts-ticket-office-service/node_modules/memory-pager/LICENSE @@ -1,19 +1,21 @@ -Copyright (c) 2014 Yehuda Katz, Tom Dale, Stefan Penner and contributors +The MIT License (MIT) -Permission is hereby granted, free of charge, to any person obtaining a copy of -this software and associated documentation files (the "Software"), to deal in -the Software without restriction, including without limitation the rights to -use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies -of the Software, and to permit persons to whom the Software is furnished to do -so, subject to the following conditions: +Copyright (c) 2017 Mathias Buus -The above copyright notice and this permission notice shall be included in all -copies or substantial portions of the Software. +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE -SOFTWARE. +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. diff --git a/ts-ticket-office-service/node_modules/memory-pager/README.md b/ts-ticket-office-service/node_modules/memory-pager/README.md new file mode 100644 index 000000000..aed176140 --- /dev/null +++ b/ts-ticket-office-service/node_modules/memory-pager/README.md @@ -0,0 +1,65 @@ +# memory-pager + +Access memory using small fixed sized buffers instead of allocating a huge buffer. +Useful if you are implementing sparse data structures (such as large bitfield). + +![travis](https://travis-ci.org/mafintosh/memory-pager.svg?branch=master) + +``` +npm install memory-pager +``` + +## Usage + +``` js +var pager = require('paged-memory') + +var pages = pager(1024) // use 1kb per page + +var page = pages.get(10) // get page #10 + +console.log(page.offset) // 10240 +console.log(page.buffer) // a blank 1kb buffer +``` + +## API + +#### `var pages = pager(pageSize)` + +Create a new pager. `pageSize` defaults to `1024`. + +#### `var page = pages.get(pageNumber, [noAllocate])` + +Get a page. The page will be allocated at first access. + +Optionally you can set the `noAllocate` flag which will make the +method return undefined if no page has been allocated already + +A page looks like this + +``` js +{ + offset: byteOffset, + buffer: bufferWithPageSize +} +``` + +#### `pages.set(pageNumber, buffer)` + +Explicitly set the buffer for a page. + +#### `pages.updated(page)` + +Mark a page as updated. + +#### `pages.lastUpdate()` + +Get the last page that was updated. + +#### `var buf = pages.toBuffer()` + +Concat all pages allocated pages into a single buffer + +## License + +MIT diff --git a/ts-ticket-office-service/node_modules/memory-pager/index.js b/ts-ticket-office-service/node_modules/memory-pager/index.js new file mode 100644 index 000000000..687f346f3 --- /dev/null +++ b/ts-ticket-office-service/node_modules/memory-pager/index.js @@ -0,0 +1,160 @@ +module.exports = Pager + +function Pager (pageSize, opts) { + if (!(this instanceof Pager)) return new Pager(pageSize, opts) + + this.length = 0 + this.updates = [] + this.path = new Uint16Array(4) + this.pages = new Array(32768) + this.maxPages = this.pages.length + this.level = 0 + this.pageSize = pageSize || 1024 + this.deduplicate = opts ? opts.deduplicate : null + this.zeros = this.deduplicate ? alloc(this.deduplicate.length) : null +} + +Pager.prototype.updated = function (page) { + while (this.deduplicate && page.buffer[page.deduplicate] === this.deduplicate[page.deduplicate]) { + page.deduplicate++ + if (page.deduplicate === this.deduplicate.length) { + page.deduplicate = 0 + if (page.buffer.equals && page.buffer.equals(this.deduplicate)) page.buffer = this.deduplicate + break + } + } + if (page.updated || !this.updates) return + page.updated = true + this.updates.push(page) +} + +Pager.prototype.lastUpdate = function () { + if (!this.updates || !this.updates.length) return null + var page = this.updates.pop() + page.updated = false + return page +} + +Pager.prototype._array = function (i, noAllocate) { + if (i >= this.maxPages) { + if (noAllocate) return + grow(this, i) + } + + factor(i, this.path) + + var arr = this.pages + + for (var j = this.level; j > 0; j--) { + var p = this.path[j] + var next = arr[p] + + if (!next) { + if (noAllocate) return + next = arr[p] = new Array(32768) + } + + arr = next + } + + return arr +} + +Pager.prototype.get = function (i, noAllocate) { + var arr = this._array(i, noAllocate) + var first = this.path[0] + var page = arr && arr[first] + + if (!page && !noAllocate) { + page = arr[first] = new Page(i, alloc(this.pageSize)) + if (i >= this.length) this.length = i + 1 + } + + if (page && page.buffer === this.deduplicate && this.deduplicate && !noAllocate) { + page.buffer = copy(page.buffer) + page.deduplicate = 0 + } + + return page +} + +Pager.prototype.set = function (i, buf) { + var arr = this._array(i, false) + var first = this.path[0] + + if (i >= this.length) this.length = i + 1 + + if (!buf || (this.zeros && buf.equals && buf.equals(this.zeros))) { + arr[first] = undefined + return + } + + if (this.deduplicate && buf.equals && buf.equals(this.deduplicate)) { + buf = this.deduplicate + } + + var page = arr[first] + var b = truncate(buf, this.pageSize) + + if (page) page.buffer = b + else arr[first] = new Page(i, b) +} + +Pager.prototype.toBuffer = function () { + var list = new Array(this.length) + var empty = alloc(this.pageSize) + var ptr = 0 + + while (ptr < list.length) { + var arr = this._array(ptr, true) + for (var i = 0; i < 32768 && ptr < list.length; i++) { + list[ptr++] = (arr && arr[i]) ? arr[i].buffer : empty + } + } + + return Buffer.concat(list) +} + +function grow (pager, index) { + while (pager.maxPages < index) { + var old = pager.pages + pager.pages = new Array(32768) + pager.pages[0] = old + pager.level++ + pager.maxPages *= 32768 + } +} + +function truncate (buf, len) { + if (buf.length === len) return buf + if (buf.length > len) return buf.slice(0, len) + var cpy = alloc(len) + buf.copy(cpy) + return cpy +} + +function alloc (size) { + if (Buffer.alloc) return Buffer.alloc(size) + var buf = new Buffer(size) + buf.fill(0) + return buf +} + +function copy (buf) { + var cpy = Buffer.allocUnsafe ? Buffer.allocUnsafe(buf.length) : new Buffer(buf.length) + buf.copy(cpy) + return cpy +} + +function Page (i, buf) { + this.offset = i * buf.length + this.buffer = buf + this.updated = false + this.deduplicate = 0 +} + +function factor (n, out) { + n = (n - (out[0] = (n & 32767))) / 32768 + n = (n - (out[1] = (n & 32767))) / 32768 + out[3] = ((n - (out[2] = (n & 32767))) / 32768) & 32767 +} diff --git a/ts-ticket-office-service/node_modules/memory-pager/package.json b/ts-ticket-office-service/node_modules/memory-pager/package.json new file mode 100644 index 000000000..f4847e8cd --- /dev/null +++ b/ts-ticket-office-service/node_modules/memory-pager/package.json @@ -0,0 +1,24 @@ +{ + "name": "memory-pager", + "version": "1.5.0", + "description": "Access memory using small fixed sized buffers", + "main": "index.js", + "dependencies": {}, + "devDependencies": { + "standard": "^9.0.0", + "tape": "^4.6.3" + }, + "scripts": { + "test": "standard && tape test.js" + }, + "repository": { + "type": "git", + "url": "https://github.com/mafintosh/memory-pager.git" + }, + "author": "Mathias Buus (@mafintosh)", + "license": "MIT", + "bugs": { + "url": "https://github.com/mafintosh/memory-pager/issues" + }, + "homepage": "https://github.com/mafintosh/memory-pager" +} diff --git a/ts-ticket-office-service/node_modules/memory-pager/test.js b/ts-ticket-office-service/node_modules/memory-pager/test.js new file mode 100644 index 000000000..163821003 --- /dev/null +++ b/ts-ticket-office-service/node_modules/memory-pager/test.js @@ -0,0 +1,80 @@ +var tape = require('tape') +var pager = require('./') + +tape('get page', function (t) { + var pages = pager(1024) + + var page = pages.get(0) + + t.same(page.offset, 0) + t.same(page.buffer, Buffer.alloc(1024)) + t.end() +}) + +tape('get page twice', function (t) { + var pages = pager(1024) + t.same(pages.length, 0) + + var page = pages.get(0) + + t.same(page.offset, 0) + t.same(page.buffer, Buffer.alloc(1024)) + t.same(pages.length, 1) + + var other = pages.get(0) + + t.same(other, page) + t.end() +}) + +tape('get no mutable page', function (t) { + var pages = pager(1024) + + t.ok(!pages.get(141, true)) + t.ok(pages.get(141)) + t.ok(pages.get(141, true)) + + t.end() +}) + +tape('get far out page', function (t) { + var pages = pager(1024) + + var page = pages.get(1000000) + + t.same(page.offset, 1000000 * 1024) + t.same(page.buffer, Buffer.alloc(1024)) + t.same(pages.length, 1000000 + 1) + + var other = pages.get(1) + + t.same(other.offset, 1024) + t.same(other.buffer, Buffer.alloc(1024)) + t.same(pages.length, 1000000 + 1) + t.ok(other !== page) + + t.end() +}) + +tape('updates', function (t) { + var pages = pager(1024) + + t.same(pages.lastUpdate(), null) + + var page = pages.get(10) + + page.buffer[42] = 1 + pages.updated(page) + + t.same(pages.lastUpdate(), page) + t.same(pages.lastUpdate(), null) + + page.buffer[42] = 2 + pages.updated(page) + pages.updated(page) + + t.same(pages.lastUpdate(), page) + t.same(pages.lastUpdate(), null) + + t.end() +}) diff --git a/ts-ticket-office-service/node_modules/mime/cli.js b/ts-ticket-office-service/node_modules/mime/cli.js old mode 100644 new mode 100755 diff --git a/ts-ticket-office-service/node_modules/minimist/.travis.yml b/ts-ticket-office-service/node_modules/minimist/.travis.yml index cc4dba29d..74c57bf15 100644 --- a/ts-ticket-office-service/node_modules/minimist/.travis.yml +++ b/ts-ticket-office-service/node_modules/minimist/.travis.yml @@ -2,3 +2,7 @@ language: node_js node_js: - "0.8" - "0.10" + - "0.12" + - "iojs" +before_install: + - npm install -g npm@~1.4.6 diff --git a/ts-ticket-office-service/node_modules/minimist/example/parse.js b/ts-ticket-office-service/node_modules/minimist/example/parse.js index abff3e8ee..f7c8d4980 100644 --- a/ts-ticket-office-service/node_modules/minimist/example/parse.js +++ b/ts-ticket-office-service/node_modules/minimist/example/parse.js @@ -1,2 +1,2 @@ var argv = require('../')(process.argv.slice(2)); -console.dir(argv); +console.log(argv); diff --git a/ts-ticket-office-service/node_modules/minimist/index.js b/ts-ticket-office-service/node_modules/minimist/index.js index 584f551a6..d9c3eb79f 100644 --- a/ts-ticket-office-service/node_modules/minimist/index.js +++ b/ts-ticket-office-service/node_modules/minimist/index.js @@ -1,15 +1,19 @@ module.exports = function (args, opts) { if (!opts) opts = {}; - var flags = { bools : {}, strings : {} }; - - [].concat(opts['boolean']).filter(Boolean).forEach(function (key) { - flags.bools[key] = true; - }); - - [].concat(opts.string).filter(Boolean).forEach(function (key) { - flags.strings[key] = true; - }); + var flags = { bools : {}, strings : {}, unknownFn: null }; + + if (typeof opts['unknown'] === 'function') { + flags.unknownFn = opts['unknown']; + } + + if (typeof opts['boolean'] === 'boolean' && opts['boolean']) { + flags.allBools = true; + } else { + [].concat(opts['boolean']).filter(Boolean).forEach(function (key) { + flags.bools[key] = true; + }); + } var aliases = {}; Object.keys(opts.alias || {}).forEach(function (key) { @@ -20,7 +24,14 @@ module.exports = function (args, opts) { })); }); }); - + + [].concat(opts.string).filter(Boolean).forEach(function (key) { + flags.strings[key] = true; + if (aliases[key]) { + flags.strings[aliases[key]] = true; + } + }); + var defaults = opts['default'] || {}; var argv = { _ : [] }; @@ -35,7 +46,16 @@ module.exports = function (args, opts) { args = args.slice(0, args.indexOf('--')); } - function setArg (key, val) { + function argDefined(key, arg) { + return (flags.allBools && /^--[^=]+$/.test(arg)) || + flags.strings[key] || flags.bools[key] || aliases[key]; + } + + function setArg (key, val, arg) { + if (arg && flags.unknownFn && !argDefined(key, arg)) { + if (flags.unknownFn(arg) === false) return; + } + var value = !flags.strings[key] && isNumber(val) ? Number(val) : val ; @@ -45,7 +65,41 @@ module.exports = function (args, opts) { setKey(argv, x.split('.'), value); }); } + + function setKey (obj, keys, value) { + var o = obj; + for (var i = 0; i < keys.length-1; i++) { + var key = keys[i]; + if (isConstructorOrProto(o, key)) return; + if (o[key] === undefined) o[key] = {}; + if (o[key] === Object.prototype || o[key] === Number.prototype + || o[key] === String.prototype) o[key] = {}; + if (o[key] === Array.prototype) o[key] = []; + o = o[key]; + } + + var key = keys[keys.length - 1]; + if (isConstructorOrProto(o, key)) return; + if (o === Object.prototype || o === Number.prototype + || o === String.prototype) o = {}; + if (o === Array.prototype) o = []; + if (o[key] === undefined || flags.bools[key] || typeof o[key] === 'boolean') { + o[key] = value; + } + else if (Array.isArray(o[key])) { + o[key].push(value); + } + else { + o[key] = [ o[key], value ]; + } + } + function aliasIsBoolean(key) { + return aliases[key].some(function (x) { + return flags.bools[x]; + }); + } + for (var i = 0; i < args.length; i++) { var arg = args[i]; @@ -54,27 +108,33 @@ module.exports = function (args, opts) { // 'dotall' regex modifier. See: // http://stackoverflow.com/a/1068308/13216 var m = arg.match(/^--([^=]+)=([\s\S]*)$/); - setArg(m[1], m[2]); + var key = m[1]; + var value = m[2]; + if (flags.bools[key]) { + value = value !== 'false'; + } + setArg(key, value, arg); } else if (/^--no-.+/.test(arg)) { var key = arg.match(/^--no-(.+)/)[1]; - setArg(key, false); + setArg(key, false, arg); } else if (/^--.+/.test(arg)) { var key = arg.match(/^--(.+)/)[1]; var next = args[i + 1]; if (next !== undefined && !/^-/.test(next) && !flags.bools[key] - && (aliases[key] ? !flags.bools[aliases[key]] : true)) { - setArg(key, next); + && !flags.allBools + && (aliases[key] ? !aliasIsBoolean(key) : true)) { + setArg(key, next, arg); i++; } else if (/^(true|false)$/.test(next)) { - setArg(key, next === 'true'); + setArg(key, next === 'true', arg); i++; } else { - setArg(key, flags.strings[key] ? '' : true); + setArg(key, flags.strings[key] ? '' : true, arg); } } else if (/^-[^-]+/.test(arg)) { @@ -85,24 +145,30 @@ module.exports = function (args, opts) { var next = arg.slice(j+2); if (next === '-') { - setArg(letters[j], next) + setArg(letters[j], next, arg) continue; } + if (/[A-Za-z]/.test(letters[j]) && /=/.test(next)) { + setArg(letters[j], next.split('=')[1], arg); + broken = true; + break; + } + if (/[A-Za-z]/.test(letters[j]) && /-?\d+(\.\d*)?(e-?\d+)?$/.test(next)) { - setArg(letters[j], next); + setArg(letters[j], next, arg); broken = true; break; } if (letters[j+1] && letters[j+1].match(/\W/)) { - setArg(letters[j], arg.slice(j+2)); + setArg(letters[j], arg.slice(j+2), arg); broken = true; break; } else { - setArg(letters[j], flags.strings[letters[j]] ? '' : true); + setArg(letters[j], flags.strings[letters[j]] ? '' : true, arg); } } @@ -110,23 +176,29 @@ module.exports = function (args, opts) { if (!broken && key !== '-') { if (args[i+1] && !/^(-|--)[^-]/.test(args[i+1]) && !flags.bools[key] - && (aliases[key] ? !flags.bools[aliases[key]] : true)) { - setArg(key, args[i+1]); + && (aliases[key] ? !aliasIsBoolean(key) : true)) { + setArg(key, args[i+1], arg); i++; } - else if (args[i+1] && /true|false/.test(args[i+1])) { - setArg(key, args[i+1] === 'true'); + else if (args[i+1] && /^(true|false)$/.test(args[i+1])) { + setArg(key, args[i+1] === 'true', arg); i++; } else { - setArg(key, flags.strings[key] ? '' : true); + setArg(key, flags.strings[key] ? '' : true, arg); } } } else { - argv._.push( - flags.strings['_'] || !isNumber(arg) ? arg : Number(arg) - ); + if (!flags.unknownFn || flags.unknownFn(arg) !== false) { + argv._.push( + flags.strings['_'] || !isNumber(arg) ? arg : Number(arg) + ); + } + if (opts.stopEarly) { + argv._.push.apply(argv._, args.slice(i + 1)); + break; + } } } @@ -140,9 +212,17 @@ module.exports = function (args, opts) { } }); - notFlags.forEach(function(key) { - argv._.push(key); - }); + if (opts['--']) { + argv['--'] = new Array(); + notFlags.forEach(function(key) { + argv['--'].push(key); + }); + } + else { + notFlags.forEach(function(key) { + argv._.push(key); + }); + } return argv; }; @@ -157,31 +237,13 @@ function hasKey (obj, keys) { return key in o; } -function setKey (obj, keys, value) { - var o = obj; - keys.slice(0,-1).forEach(function (key) { - if (o[key] === undefined) o[key] = {}; - o = o[key]; - }); - - var key = keys[keys.length - 1]; - if (o[key] === undefined || typeof o[key] === 'boolean') { - o[key] = value; - } - else if (Array.isArray(o[key])) { - o[key].push(value); - } - else { - o[key] = [ o[key], value ]; - } -} - function isNumber (x) { if (typeof x === 'number') return true; if (/^0x[0-9a-f]+$/i.test(x)) return true; return /^[-+]?(?:\d+(?:\.\d*)?|\.\d+)(e[-+]?\d+)?$/.test(x); } -function longest (xs) { - return Math.max.apply(null, xs.map(function (x) { return x.length })); + +function isConstructorOrProto (obj, key) { + return key === 'constructor' && typeof obj[key] === 'function' || key === '__proto__'; } diff --git a/ts-ticket-office-service/node_modules/minimist/package.json b/ts-ticket-office-service/node_modules/minimist/package.json index ffa346c98..c22585335 100644 --- a/ts-ticket-office-service/node_modules/minimist/package.json +++ b/ts-ticket-office-service/node_modules/minimist/package.json @@ -1,88 +1,16 @@ { - "_args": [ - [ - { - "raw": "minimist@0.0.8", - "scope": null, - "escapedName": "minimist", - "name": "minimist", - "rawSpec": "0.0.8", - "spec": "0.0.8", - "type": "version" - }, - "F:\\gitwork\\workspace_microservices\\ts-ticket-office-service\\node_modules\\mkdirp" - ] - ], - "_from": "minimist@0.0.8", - "_id": "minimist@0.0.8", - "_inCache": true, - "_location": "/minimist", - "_npmUser": { - "name": "substack", - "email": "mail@substack.net" - }, - "_npmVersion": "1.4.3", - "_phantomChildren": {}, - "_requested": { - "raw": "minimist@0.0.8", - "scope": null, - "escapedName": "minimist", - "name": "minimist", - "rawSpec": "0.0.8", - "spec": "0.0.8", - "type": "version" - }, - "_requiredBy": [ - "/mkdirp" - ], - "_resolved": "https://registry.npmjs.org/minimist/-/minimist-0.0.8.tgz", - "_shasum": "857fcabfc3397d2625b8228262e86aa7a011b05d", - "_shrinkwrap": null, - "_spec": "minimist@0.0.8", - "_where": "F:\\gitwork\\workspace_microservices\\ts-ticket-office-service\\node_modules\\mkdirp", - "author": { - "name": "James Halliday", - "email": "mail@substack.net", - "url": "http://substack.net" - }, - "bugs": { - "url": "https://github.com/substack/minimist/issues" - }, - "dependencies": {}, + "name": "minimist", + "version": "1.2.6", "description": "parse argument options", + "main": "index.js", "devDependencies": { + "covert": "^1.0.0", "tap": "~0.4.0", - "tape": "~1.0.4" - }, - "directories": {}, - "dist": { - "shasum": "857fcabfc3397d2625b8228262e86aa7a011b05d", - "tarball": "https://registry.npmjs.org/minimist/-/minimist-0.0.8.tgz" - }, - "homepage": "https://github.com/substack/minimist", - "keywords": [ - "argv", - "getopt", - "parser", - "optimist" - ], - "license": "MIT", - "main": "index.js", - "maintainers": [ - { - "name": "substack", - "email": "mail@substack.net" - } - ], - "name": "minimist", - "optionalDependencies": {}, - "readme": "ERROR: No README data found!", - "repository": { - "type": "git", - "url": "git://github.com/substack/minimist.git" + "tape": "^3.5.0" }, "scripts": { - "test": "tap test/*.js" + "test": "tap test/*.js", + "coverage": "covert test/*.js" }, "testling": { "files": "test/*.js", @@ -97,5 +25,21 @@ "opera/12" ] }, - "version": "0.0.8" + "repository": { + "type": "git", + "url": "git://github.com/substack/minimist.git" + }, + "homepage": "https://github.com/substack/minimist", + "keywords": [ + "argv", + "getopt", + "parser", + "optimist" + ], + "author": { + "name": "James Halliday", + "email": "mail@substack.net", + "url": "http://substack.net" + }, + "license": "MIT" } diff --git a/ts-ticket-office-service/node_modules/minimist/readme.markdown b/ts-ticket-office-service/node_modules/minimist/readme.markdown index c25635323..859d1ab45 100644 --- a/ts-ticket-office-service/node_modules/minimist/readme.markdown +++ b/ts-ticket-office-service/node_modules/minimist/readme.markdown @@ -5,15 +5,11 @@ parse argument options This module is the guts of optimist's argument parser without all the fanciful decoration. -[![browser support](https://ci.testling.com/substack/minimist.png)](http://ci.testling.com/substack/minimist) - -[![build status](https://secure.travis-ci.org/substack/minimist.png)](http://travis-ci.org/substack/minimist) - # example ``` js var argv = require('minimist')(process.argv.slice(2)); -console.dir(argv); +console.log(argv); ``` ``` @@ -33,6 +29,16 @@ $ node example/parse.js -x 3 -y 4 -n5 -abc --beep=boop foo bar baz beep: 'boop' } ``` +# security + +Previous versions had a prototype pollution bug that could cause privilege +escalation in some circumstances when handling untrusted user input. + +Please use version 1.2.6 or later: + +* https://security.snyk.io/vuln/SNYK-JS-MINIMIST-2429795 (version <=1.2.5) +* https://snyk.io/vuln/SNYK-JS-MINIMIST-559764 (version <=1.2.3) + # methods ``` js @@ -55,10 +61,29 @@ options can be: * `opts.string` - a string or array of strings argument names to always treat as strings -* `opts.boolean` - a string or array of strings to always treat as booleans +* `opts.boolean` - a boolean, string or array of strings to always treat as +booleans. if `true` will treat all double hyphenated arguments without equal signs +as boolean (e.g. affects `--foo`, not `-f` or `--foo=bar`) * `opts.alias` - an object mapping string names to strings or arrays of string argument names to use as aliases * `opts.default` - an object mapping string argument names to default values +* `opts.stopEarly` - when true, populate `argv._` with everything after the +first non-option +* `opts['--']` - when true, populate `argv._` with everything before the `--` +and `argv['--']` with everything after the `--`. Here's an example: + + ``` + > require('./')('one two three -- four five --six'.split(' '), { '--': true }) + { _: [ 'one', 'two', 'three' ], + '--': [ 'four', 'five', '--six' ] } + ``` + + Note that with `opts['--']` set, parsing for arguments still stops after the + `--`. + +* `opts.unknown` - a function which is invoked with a command line parameter not +defined in the `opts` configuration object. If the function returns `false`, the +unknown option is not added to `argv`. # install diff --git a/ts-ticket-office-service/node_modules/minimist/test/all_bool.js b/ts-ticket-office-service/node_modules/minimist/test/all_bool.js new file mode 100644 index 000000000..ac835483d --- /dev/null +++ b/ts-ticket-office-service/node_modules/minimist/test/all_bool.js @@ -0,0 +1,32 @@ +var parse = require('../'); +var test = require('tape'); + +test('flag boolean true (default all --args to boolean)', function (t) { + var argv = parse(['moo', '--honk', 'cow'], { + boolean: true + }); + + t.deepEqual(argv, { + honk: true, + _: ['moo', 'cow'] + }); + + t.deepEqual(typeof argv.honk, 'boolean'); + t.end(); +}); + +test('flag boolean true only affects double hyphen arguments without equals signs', function (t) { + var argv = parse(['moo', '--honk', 'cow', '-p', '55', '--tacos=good'], { + boolean: true + }); + + t.deepEqual(argv, { + honk: true, + tacos: 'good', + p: 55, + _: ['moo', 'cow'] + }); + + t.deepEqual(typeof argv.honk, 'boolean'); + t.end(); +}); diff --git a/ts-ticket-office-service/node_modules/minimist/test/bool.js b/ts-ticket-office-service/node_modules/minimist/test/bool.js new file mode 100644 index 000000000..5f7dbde16 --- /dev/null +++ b/ts-ticket-office-service/node_modules/minimist/test/bool.js @@ -0,0 +1,178 @@ +var parse = require('../'); +var test = require('tape'); + +test('flag boolean default false', function (t) { + var argv = parse(['moo'], { + boolean: ['t', 'verbose'], + default: { verbose: false, t: false } + }); + + t.deepEqual(argv, { + verbose: false, + t: false, + _: ['moo'] + }); + + t.deepEqual(typeof argv.verbose, 'boolean'); + t.deepEqual(typeof argv.t, 'boolean'); + t.end(); + +}); + +test('boolean groups', function (t) { + var argv = parse([ '-x', '-z', 'one', 'two', 'three' ], { + boolean: ['x','y','z'] + }); + + t.deepEqual(argv, { + x : true, + y : false, + z : true, + _ : [ 'one', 'two', 'three' ] + }); + + t.deepEqual(typeof argv.x, 'boolean'); + t.deepEqual(typeof argv.y, 'boolean'); + t.deepEqual(typeof argv.z, 'boolean'); + t.end(); +}); +test('boolean and alias with chainable api', function (t) { + var aliased = [ '-h', 'derp' ]; + var regular = [ '--herp', 'derp' ]; + var opts = { + herp: { alias: 'h', boolean: true } + }; + var aliasedArgv = parse(aliased, { + boolean: 'herp', + alias: { h: 'herp' } + }); + var propertyArgv = parse(regular, { + boolean: 'herp', + alias: { h: 'herp' } + }); + var expected = { + herp: true, + h: true, + '_': [ 'derp' ] + }; + + t.same(aliasedArgv, expected); + t.same(propertyArgv, expected); + t.end(); +}); + +test('boolean and alias with options hash', function (t) { + var aliased = [ '-h', 'derp' ]; + var regular = [ '--herp', 'derp' ]; + var opts = { + alias: { 'h': 'herp' }, + boolean: 'herp' + }; + var aliasedArgv = parse(aliased, opts); + var propertyArgv = parse(regular, opts); + var expected = { + herp: true, + h: true, + '_': [ 'derp' ] + }; + t.same(aliasedArgv, expected); + t.same(propertyArgv, expected); + t.end(); +}); + +test('boolean and alias array with options hash', function (t) { + var aliased = [ '-h', 'derp' ]; + var regular = [ '--herp', 'derp' ]; + var alt = [ '--harp', 'derp' ]; + var opts = { + alias: { 'h': ['herp', 'harp'] }, + boolean: 'h' + }; + var aliasedArgv = parse(aliased, opts); + var propertyArgv = parse(regular, opts); + var altPropertyArgv = parse(alt, opts); + var expected = { + harp: true, + herp: true, + h: true, + '_': [ 'derp' ] + }; + t.same(aliasedArgv, expected); + t.same(propertyArgv, expected); + t.same(altPropertyArgv, expected); + t.end(); +}); + +test('boolean and alias using explicit true', function (t) { + var aliased = [ '-h', 'true' ]; + var regular = [ '--herp', 'true' ]; + var opts = { + alias: { h: 'herp' }, + boolean: 'h' + }; + var aliasedArgv = parse(aliased, opts); + var propertyArgv = parse(regular, opts); + var expected = { + herp: true, + h: true, + '_': [ ] + }; + + t.same(aliasedArgv, expected); + t.same(propertyArgv, expected); + t.end(); +}); + +// regression, see https://github.com/substack/node-optimist/issues/71 +test('boolean and --x=true', function(t) { + var parsed = parse(['--boool', '--other=true'], { + boolean: 'boool' + }); + + t.same(parsed.boool, true); + t.same(parsed.other, 'true'); + + parsed = parse(['--boool', '--other=false'], { + boolean: 'boool' + }); + + t.same(parsed.boool, true); + t.same(parsed.other, 'false'); + t.end(); +}); + +test('boolean --boool=true', function (t) { + var parsed = parse(['--boool=true'], { + default: { + boool: false + }, + boolean: ['boool'] + }); + + t.same(parsed.boool, true); + t.end(); +}); + +test('boolean --boool=false', function (t) { + var parsed = parse(['--boool=false'], { + default: { + boool: true + }, + boolean: ['boool'] + }); + + t.same(parsed.boool, false); + t.end(); +}); + +test('boolean using something similar to true', function (t) { + var opts = { boolean: 'h' }; + var result = parse(['-h', 'true.txt'], opts); + var expected = { + h: true, + '_': ['true.txt'] + }; + + t.same(result, expected); + t.end(); +}); \ No newline at end of file diff --git a/ts-ticket-office-service/node_modules/minimist/test/dash.js b/ts-ticket-office-service/node_modules/minimist/test/dash.js index 8b034b99a..5a4fa5be4 100644 --- a/ts-ticket-office-service/node_modules/minimist/test/dash.js +++ b/ts-ticket-office-service/node_modules/minimist/test/dash.js @@ -22,3 +22,10 @@ test('-a -- b', function (t) { t.deepEqual(parse([ '--a', '--', 'b' ]), { a: true, _: [ 'b' ] }); t.deepEqual(parse([ '--a', '--', 'b' ]), { a: true, _: [ 'b' ] }); }); + +test('move arguments after the -- into their own `--` array', function(t) { + t.plan(1); + t.deepEqual( + parse([ '--name', 'John', 'before', '--', 'after' ], { '--': true }), + { name: 'John', _: [ 'before' ], '--': [ 'after' ] }); +}); diff --git a/ts-ticket-office-service/node_modules/minimist/test/default_bool.js b/ts-ticket-office-service/node_modules/minimist/test/default_bool.js index f0041ee40..780a31127 100644 --- a/ts-ticket-office-service/node_modules/minimist/test/default_bool.js +++ b/ts-ticket-office-service/node_modules/minimist/test/default_bool.js @@ -18,3 +18,18 @@ test('boolean default false', function (t) { t.equal(argv.somefalse, false); t.end(); }); + +test('boolean default to null', function (t) { + var argv = parse([], { + boolean: 'maybe', + default: { maybe: null } + }); + t.equal(argv.maybe, null); + var argv = parse(['--maybe'], { + boolean: 'maybe', + default: { maybe: null } + }); + t.equal(argv.maybe, true); + t.end(); + +}) diff --git a/ts-ticket-office-service/node_modules/minimist/test/dotted.js b/ts-ticket-office-service/node_modules/minimist/test/dotted.js index ef0ae349b..d8b3e856e 100644 --- a/ts-ticket-office-service/node_modules/minimist/test/dotted.js +++ b/ts-ticket-office-service/node_modules/minimist/test/dotted.js @@ -14,3 +14,9 @@ test('dotted default', function (t) { t.equal(argv.aa.bb, 11); t.end(); }); + +test('dotted default with no alias', function (t) { + var argv = parse('', {default: {'a.b': 11}}); + t.equal(argv.a.b, 11); + t.end(); +}); diff --git a/ts-ticket-office-service/node_modules/minimist/test/kv_short.js b/ts-ticket-office-service/node_modules/minimist/test/kv_short.js new file mode 100644 index 000000000..f813b3050 --- /dev/null +++ b/ts-ticket-office-service/node_modules/minimist/test/kv_short.js @@ -0,0 +1,16 @@ +var parse = require('../'); +var test = require('tape'); + +test('short -k=v' , function (t) { + t.plan(1); + + var argv = parse([ '-b=123' ]); + t.deepEqual(argv, { b: 123, _: [] }); +}); + +test('multi short -k=v' , function (t) { + t.plan(1); + + var argv = parse([ '-a=whatever', '-b=robots' ]); + t.deepEqual(argv, { a: 'whatever', b: 'robots', _: [] }); +}); diff --git a/ts-ticket-office-service/node_modules/minimist/test/num.js b/ts-ticket-office-service/node_modules/minimist/test/num.js new file mode 100644 index 000000000..2cc77f4d6 --- /dev/null +++ b/ts-ticket-office-service/node_modules/minimist/test/num.js @@ -0,0 +1,36 @@ +var parse = require('../'); +var test = require('tape'); + +test('nums', function (t) { + var argv = parse([ + '-x', '1234', + '-y', '5.67', + '-z', '1e7', + '-w', '10f', + '--hex', '0xdeadbeef', + '789' + ]); + t.deepEqual(argv, { + x : 1234, + y : 5.67, + z : 1e7, + w : '10f', + hex : 0xdeadbeef, + _ : [ 789 ] + }); + t.deepEqual(typeof argv.x, 'number'); + t.deepEqual(typeof argv.y, 'number'); + t.deepEqual(typeof argv.z, 'number'); + t.deepEqual(typeof argv.w, 'string'); + t.deepEqual(typeof argv.hex, 'number'); + t.deepEqual(typeof argv._[0], 'number'); + t.end(); +}); + +test('already a number', function (t) { + var argv = parse([ '-x', 1234, 789 ]); + t.deepEqual(argv, { x : 1234, _ : [ 789 ] }); + t.deepEqual(typeof argv.x, 'number'); + t.deepEqual(typeof argv._[0], 'number'); + t.end(); +}); diff --git a/ts-ticket-office-service/node_modules/minimist/test/parse.js b/ts-ticket-office-service/node_modules/minimist/test/parse.js index 8a9064669..7b4a2a17c 100644 --- a/ts-ticket-office-service/node_modules/minimist/test/parse.js +++ b/ts-ticket-office-service/node_modules/minimist/test/parse.js @@ -42,32 +42,6 @@ test('comprehensive', function (t) { t.end(); }); -test('nums', function (t) { - var argv = parse([ - '-x', '1234', - '-y', '5.67', - '-z', '1e7', - '-w', '10f', - '--hex', '0xdeadbeef', - '789' - ]); - t.deepEqual(argv, { - x : 1234, - y : 5.67, - z : 1e7, - w : '10f', - hex : 0xdeadbeef, - _ : [ 789 ] - }); - t.deepEqual(typeof argv.x, 'number'); - t.deepEqual(typeof argv.y, 'number'); - t.deepEqual(typeof argv.z, 'number'); - t.deepEqual(typeof argv.w, 'string'); - t.deepEqual(typeof argv.hex, 'number'); - t.deepEqual(typeof argv._[0], 'number'); - t.end(); -}); - test('flag boolean', function (t) { var argv = parse([ '-t', 'moo' ], { boolean: 't' }); t.deepEqual(argv, { t : true, _ : [ 'moo' ] }); @@ -92,42 +66,6 @@ test('flag boolean value', function (t) { t.end(); }); -test('flag boolean default false', function (t) { - var argv = parse(['moo'], { - boolean: ['t', 'verbose'], - default: { verbose: false, t: false } - }); - - t.deepEqual(argv, { - verbose: false, - t: false, - _: ['moo'] - }); - - t.deepEqual(typeof argv.verbose, 'boolean'); - t.deepEqual(typeof argv.t, 'boolean'); - t.end(); - -}); - -test('boolean groups', function (t) { - var argv = parse([ '-x', '-z', 'one', 'two', 'three' ], { - boolean: ['x','y','z'] - }); - - t.deepEqual(argv, { - x : true, - y : false, - z : true, - _ : [ 'one', 'two', 'three' ] - }); - - t.deepEqual(typeof argv.x, 'boolean'); - t.deepEqual(typeof argv.y, 'boolean'); - t.deepEqual(typeof argv.z, 'boolean'); - t.end(); -}); - test('newlines in params' , function (t) { var args = parse([ '-s', "X\nX" ]) t.deepEqual(args, { _ : [], s : "X\nX" }); @@ -183,6 +121,29 @@ test('empty strings', function(t) { }); +test('string and alias', function(t) { + var x = parse([ '--str', '000123' ], { + string: 's', + alias: { s: 'str' } + }); + + t.equal(x.str, '000123'); + t.equal(typeof x.str, 'string'); + t.equal(x.s, '000123'); + t.equal(typeof x.s, 'string'); + + var y = parse([ '-s', '000123' ], { + string: 'str', + alias: { str: 's' } + }); + + t.equal(y.str, '000123'); + t.equal(typeof y.str, 'string'); + t.equal(y.s, '000123'); + t.equal(typeof y.s, 'string'); + t.end(); +}); + test('slashBreak', function (t) { t.same( parse([ '-I/foo/bar/baz' ]), @@ -234,85 +195,3 @@ test('nested dotted objects', function (t) { t.same(argv.beep, { boop : true }); t.end(); }); - -test('boolean and alias with chainable api', function (t) { - var aliased = [ '-h', 'derp' ]; - var regular = [ '--herp', 'derp' ]; - var opts = { - herp: { alias: 'h', boolean: true } - }; - var aliasedArgv = parse(aliased, { - boolean: 'herp', - alias: { h: 'herp' } - }); - var propertyArgv = parse(regular, { - boolean: 'herp', - alias: { h: 'herp' } - }); - var expected = { - herp: true, - h: true, - '_': [ 'derp' ] - }; - - t.same(aliasedArgv, expected); - t.same(propertyArgv, expected); - t.end(); -}); - -test('boolean and alias with options hash', function (t) { - var aliased = [ '-h', 'derp' ]; - var regular = [ '--herp', 'derp' ]; - var opts = { - alias: { 'h': 'herp' }, - boolean: 'herp' - }; - var aliasedArgv = parse(aliased, opts); - var propertyArgv = parse(regular, opts); - var expected = { - herp: true, - h: true, - '_': [ 'derp' ] - }; - t.same(aliasedArgv, expected); - t.same(propertyArgv, expected); - t.end(); -}); - -test('boolean and alias using explicit true', function (t) { - var aliased = [ '-h', 'true' ]; - var regular = [ '--herp', 'true' ]; - var opts = { - alias: { h: 'herp' }, - boolean: 'h' - }; - var aliasedArgv = parse(aliased, opts); - var propertyArgv = parse(regular, opts); - var expected = { - herp: true, - h: true, - '_': [ ] - }; - - t.same(aliasedArgv, expected); - t.same(propertyArgv, expected); - t.end(); -}); - -// regression, see https://github.com/substack/node-optimist/issues/71 -test('boolean and --x=true', function(t) { - var parsed = parse(['--boool', '--other=true'], { - boolean: 'boool' - }); - - t.same(parsed.boool, true); - t.same(parsed.other, 'true'); - - parsed = parse(['--boool', '--other=false'], { - boolean: 'boool' - }); - - t.same(parsed.boool, true); - t.same(parsed.other, 'false'); - t.end(); -}); diff --git a/ts-ticket-office-service/node_modules/minimist/test/parse_modified.js b/ts-ticket-office-service/node_modules/minimist/test/parse_modified.js index 21851b036..ab620dc5e 100644 --- a/ts-ticket-office-service/node_modules/minimist/test/parse_modified.js +++ b/ts-ticket-office-service/node_modules/minimist/test/parse_modified.js @@ -5,5 +5,5 @@ test('parse with modifier functions' , function (t) { t.plan(1); var argv = parse([ '-b', '123' ], { boolean: 'b' }); - t.deepEqual(argv, { b: true, _: ['123'] }); + t.deepEqual(argv, { b: true, _: [123] }); }); diff --git a/ts-ticket-office-service/node_modules/minimist/test/proto.js b/ts-ticket-office-service/node_modules/minimist/test/proto.js new file mode 100644 index 000000000..4ac62df26 --- /dev/null +++ b/ts-ticket-office-service/node_modules/minimist/test/proto.js @@ -0,0 +1,60 @@ +var parse = require('../'); +var test = require('tape'); + +test('proto pollution', function (t) { + var argv = parse(['--__proto__.x','123']); + t.equal({}.x, undefined); + t.equal(argv.__proto__.x, undefined); + t.equal(argv.x, undefined); + t.end(); +}); + +test('proto pollution (array)', function (t) { + var argv = parse(['--x','4','--x','5','--x.__proto__.z','789']); + t.equal({}.z, undefined); + t.deepEqual(argv.x, [4,5]); + t.equal(argv.x.z, undefined); + t.equal(argv.x.__proto__.z, undefined); + t.end(); +}); + +test('proto pollution (number)', function (t) { + var argv = parse(['--x','5','--x.__proto__.z','100']); + t.equal({}.z, undefined); + t.equal((4).z, undefined); + t.equal(argv.x, 5); + t.equal(argv.x.z, undefined); + t.end(); +}); + +test('proto pollution (string)', function (t) { + var argv = parse(['--x','abc','--x.__proto__.z','def']); + t.equal({}.z, undefined); + t.equal('...'.z, undefined); + t.equal(argv.x, 'abc'); + t.equal(argv.x.z, undefined); + t.end(); +}); + +test('proto pollution (constructor)', function (t) { + var argv = parse(['--constructor.prototype.y','123']); + t.equal({}.y, undefined); + t.equal(argv.y, undefined); + t.end(); +}); + +test('proto pollution (constructor function)', function (t) { + var argv = parse(['--_.concat.constructor.prototype.y', '123']); + function fnToBeTested() {} + t.equal(fnToBeTested.y, undefined); + t.equal(argv.y, undefined); + t.end(); +}); + +// powered by snyk - https://github.com/backstage/backstage/issues/10343 +test('proto pollution (constructor function) snyk', function (t) { + var argv = parse('--_.constructor.constructor.prototype.foo bar'.split(' ')); + t.equal((function(){}).foo, undefined); + t.equal(argv.y, undefined); + t.end(); +}) diff --git a/ts-ticket-office-service/node_modules/minimist/test/stop_early.js b/ts-ticket-office-service/node_modules/minimist/test/stop_early.js new file mode 100644 index 000000000..bdf9fbcb0 --- /dev/null +++ b/ts-ticket-office-service/node_modules/minimist/test/stop_early.js @@ -0,0 +1,15 @@ +var parse = require('../'); +var test = require('tape'); + +test('stops parsing on the first non-option when stopEarly is set', function (t) { + var argv = parse(['--aaa', 'bbb', 'ccc', '--ddd'], { + stopEarly: true + }); + + t.deepEqual(argv, { + aaa: 'bbb', + _: ['ccc', '--ddd'] + }); + + t.end(); +}); diff --git a/ts-ticket-office-service/node_modules/minimist/test/unknown.js b/ts-ticket-office-service/node_modules/minimist/test/unknown.js new file mode 100644 index 000000000..462a36bdd --- /dev/null +++ b/ts-ticket-office-service/node_modules/minimist/test/unknown.js @@ -0,0 +1,102 @@ +var parse = require('../'); +var test = require('tape'); + +test('boolean and alias is not unknown', function (t) { + var unknown = []; + function unknownFn(arg) { + unknown.push(arg); + return false; + } + var aliased = [ '-h', 'true', '--derp', 'true' ]; + var regular = [ '--herp', 'true', '-d', 'true' ]; + var opts = { + alias: { h: 'herp' }, + boolean: 'h', + unknown: unknownFn + }; + var aliasedArgv = parse(aliased, opts); + var propertyArgv = parse(regular, opts); + + t.same(unknown, ['--derp', '-d']); + t.end(); +}); + +test('flag boolean true any double hyphen argument is not unknown', function (t) { + var unknown = []; + function unknownFn(arg) { + unknown.push(arg); + return false; + } + var argv = parse(['--honk', '--tacos=good', 'cow', '-p', '55'], { + boolean: true, + unknown: unknownFn + }); + t.same(unknown, ['--tacos=good', 'cow', '-p']); + t.same(argv, { + honk: true, + _: [] + }); + t.end(); +}); + +test('string and alias is not unknown', function (t) { + var unknown = []; + function unknownFn(arg) { + unknown.push(arg); + return false; + } + var aliased = [ '-h', 'hello', '--derp', 'goodbye' ]; + var regular = [ '--herp', 'hello', '-d', 'moon' ]; + var opts = { + alias: { h: 'herp' }, + string: 'h', + unknown: unknownFn + }; + var aliasedArgv = parse(aliased, opts); + var propertyArgv = parse(regular, opts); + + t.same(unknown, ['--derp', '-d']); + t.end(); +}); + +test('default and alias is not unknown', function (t) { + var unknown = []; + function unknownFn(arg) { + unknown.push(arg); + return false; + } + var aliased = [ '-h', 'hello' ]; + var regular = [ '--herp', 'hello' ]; + var opts = { + default: { 'h': 'bar' }, + alias: { 'h': 'herp' }, + unknown: unknownFn + }; + var aliasedArgv = parse(aliased, opts); + var propertyArgv = parse(regular, opts); + + t.same(unknown, []); + t.end(); + unknownFn(); // exercise fn for 100% coverage +}); + +test('value following -- is not unknown', function (t) { + var unknown = []; + function unknownFn(arg) { + unknown.push(arg); + return false; + } + var aliased = [ '--bad', '--', 'good', 'arg' ]; + var opts = { + '--': true, + unknown: unknownFn + }; + var argv = parse(aliased, opts); + + t.same(unknown, ['--bad']); + t.same(argv, { + '--': ['good', 'arg'], + '_': [] + }) + t.end(); +}); diff --git a/ts-ticket-office-service/node_modules/mkdirp/.travis.yml b/ts-ticket-office-service/node_modules/mkdirp/.travis.yml deleted file mode 100644 index 74c57bf15..000000000 --- a/ts-ticket-office-service/node_modules/mkdirp/.travis.yml +++ /dev/null @@ -1,8 +0,0 @@ -language: node_js -node_js: - - "0.8" - - "0.10" - - "0.12" - - "iojs" -before_install: - - npm install -g npm@~1.4.6 diff --git a/ts-ticket-office-service/node_modules/mkdirp/bin/cmd.js b/ts-ticket-office-service/node_modules/mkdirp/bin/cmd.js old mode 100644 new mode 100755 diff --git a/ts-ticket-office-service/node_modules/mkdirp/examples/pow.js b/ts-ticket-office-service/node_modules/mkdirp/examples/pow.js deleted file mode 100644 index e6924212e..000000000 --- a/ts-ticket-office-service/node_modules/mkdirp/examples/pow.js +++ /dev/null @@ -1,6 +0,0 @@ -var mkdirp = require('mkdirp'); - -mkdirp('/tmp/foo/bar/baz', function (err) { - if (err) console.error(err) - else console.log('pow!') -}); diff --git a/ts-ticket-office-service/node_modules/mkdirp/index.js b/ts-ticket-office-service/node_modules/mkdirp/index.js index 6ce241b58..0890ac3bd 100644 --- a/ts-ticket-office-service/node_modules/mkdirp/index.js +++ b/ts-ticket-office-service/node_modules/mkdirp/index.js @@ -17,11 +17,11 @@ function mkdirP (p, opts, f, made) { var xfs = opts.fs || fs; if (mode === undefined) { - mode = _0777 & (~process.umask()); + mode = _0777 } if (!made) made = null; - var cb = f || function () {}; + var cb = f || /* istanbul ignore next */ function () {}; p = path.resolve(p); xfs.mkdir(p, mode, function (er) { @@ -31,7 +31,10 @@ function mkdirP (p, opts, f, made) { } switch (er.code) { case 'ENOENT': + /* istanbul ignore if */ + if (path.dirname(p) === p) return cb(er); mkdirP(path.dirname(p), opts, function (er, made) { + /* istanbul ignore if */ if (er) cb(er, made); else mkdirP(p, opts, cb, made); }); @@ -61,7 +64,7 @@ mkdirP.sync = function sync (p, opts, made) { var xfs = opts.fs || fs; if (mode === undefined) { - mode = _0777 & (~process.umask()); + mode = _0777 } if (!made) made = null; @@ -86,9 +89,10 @@ mkdirP.sync = function sync (p, opts, made) { try { stat = xfs.statSync(p); } - catch (err1) { + catch (err1) /* istanbul ignore next */ { throw err0; } + /* istanbul ignore if */ if (!stat.isDirectory()) throw err0; break; } diff --git a/ts-ticket-office-service/node_modules/mkdirp/package.json b/ts-ticket-office-service/node_modules/mkdirp/package.json index 80cd8b665..951e58da9 100644 --- a/ts-ticket-office-service/node_modules/mkdirp/package.json +++ b/ts-ticket-office-service/node_modules/mkdirp/package.json @@ -1,93 +1,33 @@ { - "_args": [ - [ - { - "raw": "mkdirp@~0.5.0", - "scope": null, - "escapedName": "mkdirp", - "name": "mkdirp", - "rawSpec": "~0.5.0", - "spec": ">=0.5.0 <0.6.0", - "type": "range" - }, - "F:\\gitwork\\workspace_microservices\\ts-ticket-office-service\\node_modules\\jade" - ] - ], - "_from": "mkdirp@>=0.5.0 <0.6.0", - "_id": "mkdirp@0.5.1", - "_inCache": true, - "_location": "/mkdirp", - "_nodeVersion": "2.0.0", - "_npmUser": { - "name": "substack", - "email": "substack@gmail.com" - }, - "_npmVersion": "2.9.0", - "_phantomChildren": {}, - "_requested": { - "raw": "mkdirp@~0.5.0", - "scope": null, - "escapedName": "mkdirp", - "name": "mkdirp", - "rawSpec": "~0.5.0", - "spec": ">=0.5.0 <0.6.0", - "type": "range" - }, - "_requiredBy": [ - "/jade" - ], - "_resolved": "https://registry.npmjs.org/mkdirp/-/mkdirp-0.5.1.tgz", - "_shasum": "30057438eac6cf7f8c4767f38648d6697d75c903", - "_shrinkwrap": null, - "_spec": "mkdirp@~0.5.0", - "_where": "F:\\gitwork\\workspace_microservices\\ts-ticket-office-service\\node_modules\\jade", - "author": { - "name": "James Halliday", - "email": "mail@substack.net", - "url": "http://substack.net" - }, - "bin": { - "mkdirp": "bin/cmd.js" - }, - "bugs": { - "url": "https://github.com/substack/node-mkdirp/issues" - }, - "dependencies": { - "minimist": "0.0.8" - }, + "name": "mkdirp", "description": "Recursively mkdir, like `mkdir -p`", - "devDependencies": { - "mock-fs": "2 >=2.7.0", - "tap": "1" + "version": "0.5.6", + "publishConfig": { + "tag": "legacy" }, - "directories": {}, - "dist": { - "shasum": "30057438eac6cf7f8c4767f38648d6697d75c903", - "tarball": "https://registry.npmjs.org/mkdirp/-/mkdirp-0.5.1.tgz" - }, - "gitHead": "d4eff0f06093aed4f387e88e9fc301cb76beedc7", - "homepage": "https://github.com/substack/node-mkdirp#readme", + "author": "James Halliday (http://substack.net)", + "main": "index.js", "keywords": [ "mkdir", "directory" ], - "license": "MIT", - "main": "index.js", - "maintainers": [ - { - "name": "substack", - "email": "mail@substack.net" - } - ], - "name": "mkdirp", - "optionalDependencies": {}, - "readme": "ERROR: No README data found!", "repository": { "type": "git", - "url": "git+https://github.com/substack/node-mkdirp.git" + "url": "https://github.com/substack/node-mkdirp.git" }, "scripts": { "test": "tap test/*.js" }, - "version": "0.5.1" + "dependencies": { + "minimist": "^1.2.6" + }, + "devDependencies": { + "tap": "^16.0.1" + }, + "bin": "bin/cmd.js", + "license": "MIT", + "files": [ + "bin", + "index.js" + ] } diff --git a/ts-ticket-office-service/node_modules/mkdirp/readme.markdown b/ts-ticket-office-service/node_modules/mkdirp/readme.markdown index 3cc131538..fc314bfbd 100644 --- a/ts-ticket-office-service/node_modules/mkdirp/readme.markdown +++ b/ts-ticket-office-service/node_modules/mkdirp/readme.markdown @@ -37,7 +37,7 @@ Create a new directory and any necessary subdirectories at `dir` with octal permission string `opts.mode`. If `opts` is a non-object, it will be treated as the `opts.mode`. -If `opts.mode` isn't specified, it defaults to `0777 & (~process.umask())`. +If `opts.mode` isn't specified, it defaults to `0777`. `cb(err, made)` fires with the error or the first directory `made` that had to be created, if any. @@ -52,7 +52,7 @@ Synchronously create a new directory and any necessary subdirectories at `dir` with octal permission string `opts.mode`. If `opts` is a non-object, it will be treated as the `opts.mode`. -If `opts.mode` isn't specified, it defaults to `0777 & (~process.umask())`. +If `opts.mode` isn't specified, it defaults to `0777`. Returns the first directory that had to be created, if any. diff --git a/ts-ticket-office-service/node_modules/mkdirp/test/chmod.js b/ts-ticket-office-service/node_modules/mkdirp/test/chmod.js deleted file mode 100644 index 6a404b932..000000000 --- a/ts-ticket-office-service/node_modules/mkdirp/test/chmod.js +++ /dev/null @@ -1,41 +0,0 @@ -var mkdirp = require('../').mkdirp; -var path = require('path'); -var fs = require('fs'); -var test = require('tap').test; -var _0777 = parseInt('0777', 8); -var _0755 = parseInt('0755', 8); -var _0744 = parseInt('0744', 8); - -var ps = [ '', 'tmp' ]; - -for (var i = 0; i < 25; i++) { - var dir = Math.floor(Math.random() * Math.pow(16,4)).toString(16); - ps.push(dir); -} - -var file = ps.join('/'); - -test('chmod-pre', function (t) { - var mode = _0744 - mkdirp(file, mode, function (er) { - t.ifError(er, 'should not error'); - fs.stat(file, function (er, stat) { - t.ifError(er, 'should exist'); - t.ok(stat && stat.isDirectory(), 'should be directory'); - t.equal(stat && stat.mode & _0777, mode, 'should be 0744'); - t.end(); - }); - }); -}); - -test('chmod', function (t) { - var mode = _0755 - mkdirp(file, mode, function (er) { - t.ifError(er, 'should not error'); - fs.stat(file, function (er, stat) { - t.ifError(er, 'should exist'); - t.ok(stat && stat.isDirectory(), 'should be directory'); - t.end(); - }); - }); -}); diff --git a/ts-ticket-office-service/node_modules/mkdirp/test/clobber.js b/ts-ticket-office-service/node_modules/mkdirp/test/clobber.js deleted file mode 100644 index 2433b9ad5..000000000 --- a/ts-ticket-office-service/node_modules/mkdirp/test/clobber.js +++ /dev/null @@ -1,38 +0,0 @@ -var mkdirp = require('../').mkdirp; -var path = require('path'); -var fs = require('fs'); -var test = require('tap').test; -var _0755 = parseInt('0755', 8); - -var ps = [ '', 'tmp' ]; - -for (var i = 0; i < 25; i++) { - var dir = Math.floor(Math.random() * Math.pow(16,4)).toString(16); - ps.push(dir); -} - -var file = ps.join('/'); - -// a file in the way -var itw = ps.slice(0, 3).join('/'); - - -test('clobber-pre', function (t) { - console.error("about to write to "+itw) - fs.writeFileSync(itw, 'I AM IN THE WAY, THE TRUTH, AND THE LIGHT.'); - - fs.stat(itw, function (er, stat) { - t.ifError(er) - t.ok(stat && stat.isFile(), 'should be file') - t.end() - }) -}) - -test('clobber', function (t) { - t.plan(2); - mkdirp(file, _0755, function (err) { - t.ok(err); - t.equal(err.code, 'ENOTDIR'); - t.end(); - }); -}); diff --git a/ts-ticket-office-service/node_modules/mkdirp/test/mkdirp.js b/ts-ticket-office-service/node_modules/mkdirp/test/mkdirp.js deleted file mode 100644 index eaa8921c7..000000000 --- a/ts-ticket-office-service/node_modules/mkdirp/test/mkdirp.js +++ /dev/null @@ -1,28 +0,0 @@ -var mkdirp = require('../'); -var path = require('path'); -var fs = require('fs'); -var exists = fs.exists || path.exists; -var test = require('tap').test; -var _0777 = parseInt('0777', 8); -var _0755 = parseInt('0755', 8); - -test('woo', function (t) { - t.plan(5); - var x = Math.floor(Math.random() * Math.pow(16,4)).toString(16); - var y = Math.floor(Math.random() * Math.pow(16,4)).toString(16); - var z = Math.floor(Math.random() * Math.pow(16,4)).toString(16); - - var file = '/tmp/' + [x,y,z].join('/'); - - mkdirp(file, _0755, function (err) { - t.ifError(err); - exists(file, function (ex) { - t.ok(ex, 'file created'); - fs.stat(file, function (err, stat) { - t.ifError(err); - t.equal(stat.mode & _0777, _0755); - t.ok(stat.isDirectory(), 'target not a directory'); - }) - }) - }); -}); diff --git a/ts-ticket-office-service/node_modules/mkdirp/test/opts_fs.js b/ts-ticket-office-service/node_modules/mkdirp/test/opts_fs.js deleted file mode 100644 index 97186b62e..000000000 --- a/ts-ticket-office-service/node_modules/mkdirp/test/opts_fs.js +++ /dev/null @@ -1,29 +0,0 @@ -var mkdirp = require('../'); -var path = require('path'); -var test = require('tap').test; -var mockfs = require('mock-fs'); -var _0777 = parseInt('0777', 8); -var _0755 = parseInt('0755', 8); - -test('opts.fs', function (t) { - t.plan(5); - - var x = Math.floor(Math.random() * Math.pow(16,4)).toString(16); - var y = Math.floor(Math.random() * Math.pow(16,4)).toString(16); - var z = Math.floor(Math.random() * Math.pow(16,4)).toString(16); - - var file = '/beep/boop/' + [x,y,z].join('/'); - var xfs = mockfs.fs(); - - mkdirp(file, { fs: xfs, mode: _0755 }, function (err) { - t.ifError(err); - xfs.exists(file, function (ex) { - t.ok(ex, 'created file'); - xfs.stat(file, function (err, stat) { - t.ifError(err); - t.equal(stat.mode & _0777, _0755); - t.ok(stat.isDirectory(), 'target not a directory'); - }); - }); - }); -}); diff --git a/ts-ticket-office-service/node_modules/mkdirp/test/opts_fs_sync.js b/ts-ticket-office-service/node_modules/mkdirp/test/opts_fs_sync.js deleted file mode 100644 index 6c370aa6e..000000000 --- a/ts-ticket-office-service/node_modules/mkdirp/test/opts_fs_sync.js +++ /dev/null @@ -1,27 +0,0 @@ -var mkdirp = require('../'); -var path = require('path'); -var test = require('tap').test; -var mockfs = require('mock-fs'); -var _0777 = parseInt('0777', 8); -var _0755 = parseInt('0755', 8); - -test('opts.fs sync', function (t) { - t.plan(4); - - var x = Math.floor(Math.random() * Math.pow(16,4)).toString(16); - var y = Math.floor(Math.random() * Math.pow(16,4)).toString(16); - var z = Math.floor(Math.random() * Math.pow(16,4)).toString(16); - - var file = '/beep/boop/' + [x,y,z].join('/'); - var xfs = mockfs.fs(); - - mkdirp.sync(file, { fs: xfs, mode: _0755 }); - xfs.exists(file, function (ex) { - t.ok(ex, 'created file'); - xfs.stat(file, function (err, stat) { - t.ifError(err); - t.equal(stat.mode & _0777, _0755); - t.ok(stat.isDirectory(), 'target not a directory'); - }); - }); -}); diff --git a/ts-ticket-office-service/node_modules/mkdirp/test/perm.js b/ts-ticket-office-service/node_modules/mkdirp/test/perm.js deleted file mode 100644 index fbce44b82..000000000 --- a/ts-ticket-office-service/node_modules/mkdirp/test/perm.js +++ /dev/null @@ -1,32 +0,0 @@ -var mkdirp = require('../'); -var path = require('path'); -var fs = require('fs'); -var exists = fs.exists || path.exists; -var test = require('tap').test; -var _0777 = parseInt('0777', 8); -var _0755 = parseInt('0755', 8); - -test('async perm', function (t) { - t.plan(5); - var file = '/tmp/' + (Math.random() * (1<<30)).toString(16); - - mkdirp(file, _0755, function (err) { - t.ifError(err); - exists(file, function (ex) { - t.ok(ex, 'file created'); - fs.stat(file, function (err, stat) { - t.ifError(err); - t.equal(stat.mode & _0777, _0755); - t.ok(stat.isDirectory(), 'target not a directory'); - }) - }) - }); -}); - -test('async root perm', function (t) { - mkdirp('/tmp', _0755, function (err) { - if (err) t.fail(err); - t.end(); - }); - t.end(); -}); diff --git a/ts-ticket-office-service/node_modules/mkdirp/test/perm_sync.js b/ts-ticket-office-service/node_modules/mkdirp/test/perm_sync.js deleted file mode 100644 index 398229fe5..000000000 --- a/ts-ticket-office-service/node_modules/mkdirp/test/perm_sync.js +++ /dev/null @@ -1,36 +0,0 @@ -var mkdirp = require('../'); -var path = require('path'); -var fs = require('fs'); -var exists = fs.exists || path.exists; -var test = require('tap').test; -var _0777 = parseInt('0777', 8); -var _0755 = parseInt('0755', 8); - -test('sync perm', function (t) { - t.plan(4); - var file = '/tmp/' + (Math.random() * (1<<30)).toString(16) + '.json'; - - mkdirp.sync(file, _0755); - exists(file, function (ex) { - t.ok(ex, 'file created'); - fs.stat(file, function (err, stat) { - t.ifError(err); - t.equal(stat.mode & _0777, _0755); - t.ok(stat.isDirectory(), 'target not a directory'); - }); - }); -}); - -test('sync root perm', function (t) { - t.plan(3); - - var file = '/tmp'; - mkdirp.sync(file, _0755); - exists(file, function (ex) { - t.ok(ex, 'file created'); - fs.stat(file, function (err, stat) { - t.ifError(err); - t.ok(stat.isDirectory(), 'target not a directory'); - }) - }); -}); diff --git a/ts-ticket-office-service/node_modules/mkdirp/test/race.js b/ts-ticket-office-service/node_modules/mkdirp/test/race.js deleted file mode 100644 index b0b9e183c..000000000 --- a/ts-ticket-office-service/node_modules/mkdirp/test/race.js +++ /dev/null @@ -1,37 +0,0 @@ -var mkdirp = require('../').mkdirp; -var path = require('path'); -var fs = require('fs'); -var exists = fs.exists || path.exists; -var test = require('tap').test; -var _0777 = parseInt('0777', 8); -var _0755 = parseInt('0755', 8); - -test('race', function (t) { - t.plan(10); - var ps = [ '', 'tmp' ]; - - for (var i = 0; i < 25; i++) { - var dir = Math.floor(Math.random() * Math.pow(16,4)).toString(16); - ps.push(dir); - } - var file = ps.join('/'); - - var res = 2; - mk(file); - - mk(file); - - function mk (file, cb) { - mkdirp(file, _0755, function (err) { - t.ifError(err); - exists(file, function (ex) { - t.ok(ex, 'file created'); - fs.stat(file, function (err, stat) { - t.ifError(err); - t.equal(stat.mode & _0777, _0755); - t.ok(stat.isDirectory(), 'target not a directory'); - }); - }) - }); - } -}); diff --git a/ts-ticket-office-service/node_modules/mkdirp/test/rel.js b/ts-ticket-office-service/node_modules/mkdirp/test/rel.js deleted file mode 100644 index 4ddb34276..000000000 --- a/ts-ticket-office-service/node_modules/mkdirp/test/rel.js +++ /dev/null @@ -1,32 +0,0 @@ -var mkdirp = require('../'); -var path = require('path'); -var fs = require('fs'); -var exists = fs.exists || path.exists; -var test = require('tap').test; -var _0777 = parseInt('0777', 8); -var _0755 = parseInt('0755', 8); - -test('rel', function (t) { - t.plan(5); - var x = Math.floor(Math.random() * Math.pow(16,4)).toString(16); - var y = Math.floor(Math.random() * Math.pow(16,4)).toString(16); - var z = Math.floor(Math.random() * Math.pow(16,4)).toString(16); - - var cwd = process.cwd(); - process.chdir('/tmp'); - - var file = [x,y,z].join('/'); - - mkdirp(file, _0755, function (err) { - t.ifError(err); - exists(file, function (ex) { - t.ok(ex, 'file created'); - fs.stat(file, function (err, stat) { - t.ifError(err); - process.chdir(cwd); - t.equal(stat.mode & _0777, _0755); - t.ok(stat.isDirectory(), 'target not a directory'); - }) - }) - }); -}); diff --git a/ts-ticket-office-service/node_modules/mkdirp/test/return.js b/ts-ticket-office-service/node_modules/mkdirp/test/return.js deleted file mode 100644 index bce68e561..000000000 --- a/ts-ticket-office-service/node_modules/mkdirp/test/return.js +++ /dev/null @@ -1,25 +0,0 @@ -var mkdirp = require('../'); -var path = require('path'); -var fs = require('fs'); -var test = require('tap').test; - -test('return value', function (t) { - t.plan(4); - var x = Math.floor(Math.random() * Math.pow(16,4)).toString(16); - var y = Math.floor(Math.random() * Math.pow(16,4)).toString(16); - var z = Math.floor(Math.random() * Math.pow(16,4)).toString(16); - - var file = '/tmp/' + [x,y,z].join('/'); - - // should return the first dir created. - // By this point, it would be profoundly surprising if /tmp didn't - // already exist, since every other test makes things in there. - mkdirp(file, function (err, made) { - t.ifError(err); - t.equal(made, '/tmp/' + x); - mkdirp(file, function (err, made) { - t.ifError(err); - t.equal(made, null); - }); - }); -}); diff --git a/ts-ticket-office-service/node_modules/mkdirp/test/return_sync.js b/ts-ticket-office-service/node_modules/mkdirp/test/return_sync.js deleted file mode 100644 index 7c222d355..000000000 --- a/ts-ticket-office-service/node_modules/mkdirp/test/return_sync.js +++ /dev/null @@ -1,24 +0,0 @@ -var mkdirp = require('../'); -var path = require('path'); -var fs = require('fs'); -var test = require('tap').test; - -test('return value', function (t) { - t.plan(2); - var x = Math.floor(Math.random() * Math.pow(16,4)).toString(16); - var y = Math.floor(Math.random() * Math.pow(16,4)).toString(16); - var z = Math.floor(Math.random() * Math.pow(16,4)).toString(16); - - var file = '/tmp/' + [x,y,z].join('/'); - - // should return the first dir created. - // By this point, it would be profoundly surprising if /tmp didn't - // already exist, since every other test makes things in there. - // Note that this will throw on failure, which will fail the test. - var made = mkdirp.sync(file); - t.equal(made, '/tmp/' + x); - - // making the same file again should have no effect. - made = mkdirp.sync(file); - t.equal(made, null); -}); diff --git a/ts-ticket-office-service/node_modules/mkdirp/test/root.js b/ts-ticket-office-service/node_modules/mkdirp/test/root.js deleted file mode 100644 index 9e7d079d9..000000000 --- a/ts-ticket-office-service/node_modules/mkdirp/test/root.js +++ /dev/null @@ -1,19 +0,0 @@ -var mkdirp = require('../'); -var path = require('path'); -var fs = require('fs'); -var test = require('tap').test; -var _0755 = parseInt('0755', 8); - -test('root', function (t) { - // '/' on unix, 'c:/' on windows. - var file = path.resolve('/'); - - mkdirp(file, _0755, function (err) { - if (err) throw err - fs.stat(file, function (er, stat) { - if (er) throw er - t.ok(stat.isDirectory(), 'target is a directory'); - t.end(); - }) - }); -}); diff --git a/ts-ticket-office-service/node_modules/mkdirp/test/sync.js b/ts-ticket-office-service/node_modules/mkdirp/test/sync.js deleted file mode 100644 index 8c8dc938c..000000000 --- a/ts-ticket-office-service/node_modules/mkdirp/test/sync.js +++ /dev/null @@ -1,32 +0,0 @@ -var mkdirp = require('../'); -var path = require('path'); -var fs = require('fs'); -var exists = fs.exists || path.exists; -var test = require('tap').test; -var _0777 = parseInt('0777', 8); -var _0755 = parseInt('0755', 8); - -test('sync', function (t) { - t.plan(4); - var x = Math.floor(Math.random() * Math.pow(16,4)).toString(16); - var y = Math.floor(Math.random() * Math.pow(16,4)).toString(16); - var z = Math.floor(Math.random() * Math.pow(16,4)).toString(16); - - var file = '/tmp/' + [x,y,z].join('/'); - - try { - mkdirp.sync(file, _0755); - } catch (err) { - t.fail(err); - return t.end(); - } - - exists(file, function (ex) { - t.ok(ex, 'file created'); - fs.stat(file, function (err, stat) { - t.ifError(err); - t.equal(stat.mode & _0777, _0755); - t.ok(stat.isDirectory(), 'target not a directory'); - }); - }); -}); diff --git a/ts-ticket-office-service/node_modules/mkdirp/test/umask.js b/ts-ticket-office-service/node_modules/mkdirp/test/umask.js deleted file mode 100644 index 2033c63a4..000000000 --- a/ts-ticket-office-service/node_modules/mkdirp/test/umask.js +++ /dev/null @@ -1,28 +0,0 @@ -var mkdirp = require('../'); -var path = require('path'); -var fs = require('fs'); -var exists = fs.exists || path.exists; -var test = require('tap').test; -var _0777 = parseInt('0777', 8); -var _0755 = parseInt('0755', 8); - -test('implicit mode from umask', function (t) { - t.plan(5); - var x = Math.floor(Math.random() * Math.pow(16,4)).toString(16); - var y = Math.floor(Math.random() * Math.pow(16,4)).toString(16); - var z = Math.floor(Math.random() * Math.pow(16,4)).toString(16); - - var file = '/tmp/' + [x,y,z].join('/'); - - mkdirp(file, function (err) { - t.ifError(err); - exists(file, function (ex) { - t.ok(ex, 'file created'); - fs.stat(file, function (err, stat) { - t.ifError(err); - t.equal(stat.mode & _0777, _0777 & (~process.umask())); - t.ok(stat.isDirectory(), 'target not a directory'); - }); - }) - }); -}); diff --git a/ts-ticket-office-service/node_modules/mkdirp/test/umask_sync.js b/ts-ticket-office-service/node_modules/mkdirp/test/umask_sync.js deleted file mode 100644 index 11a761474..000000000 --- a/ts-ticket-office-service/node_modules/mkdirp/test/umask_sync.js +++ /dev/null @@ -1,32 +0,0 @@ -var mkdirp = require('../'); -var path = require('path'); -var fs = require('fs'); -var exists = fs.exists || path.exists; -var test = require('tap').test; -var _0777 = parseInt('0777', 8); -var _0755 = parseInt('0755', 8); - -test('umask sync modes', function (t) { - t.plan(4); - var x = Math.floor(Math.random() * Math.pow(16,4)).toString(16); - var y = Math.floor(Math.random() * Math.pow(16,4)).toString(16); - var z = Math.floor(Math.random() * Math.pow(16,4)).toString(16); - - var file = '/tmp/' + [x,y,z].join('/'); - - try { - mkdirp.sync(file); - } catch (err) { - t.fail(err); - return t.end(); - } - - exists(file, function (ex) { - t.ok(ex, 'file created'); - fs.stat(file, function (err, stat) { - t.ifError(err); - t.equal(stat.mode & _0777, (_0777 & (~process.umask()))); - t.ok(stat.isDirectory(), 'target not a directory'); - }); - }); -}); diff --git a/ts-ticket-office-service/node_modules/mongodb-connection-string-url/.esm-wrapper.mjs b/ts-ticket-office-service/node_modules/mongodb-connection-string-url/.esm-wrapper.mjs new file mode 100644 index 000000000..a0f5be52e --- /dev/null +++ b/ts-ticket-office-service/node_modules/mongodb-connection-string-url/.esm-wrapper.mjs @@ -0,0 +1,6 @@ +import mod from "./lib/index.js"; + +export default mod["default"]; +export const CommaAndColonSeparatedRecord = mod.CommaAndColonSeparatedRecord; +export const ConnectionString = mod.ConnectionString; +export const redactConnectionString = mod.redactConnectionString; diff --git a/ts-ticket-office-service/node_modules/mongodb/LICENSE b/ts-ticket-office-service/node_modules/mongodb-connection-string-url/LICENSE similarity index 94% rename from ts-ticket-office-service/node_modules/mongodb/LICENSE rename to ts-ticket-office-service/node_modules/mongodb-connection-string-url/LICENSE index ad410e113..d57f55f4e 100644 --- a/ts-ticket-office-service/node_modules/mongodb/LICENSE +++ b/ts-ticket-office-service/node_modules/mongodb-connection-string-url/LICENSE @@ -1,4 +1,5 @@ -Apache License + + Apache License Version 2.0, January 2004 http://www.apache.org/licenses/ @@ -175,18 +176,7 @@ Apache License END OF TERMS AND CONDITIONS - APPENDIX: How to apply the Apache License to your work. - - To apply the Apache License to your work, attach the following - boilerplate notice, with the fields enclosed by brackets "{}" - replaced with your own identifying information. (Don't include - the brackets!) The text should be enclosed in the appropriate - comment syntax for the file format. We also recommend that a - file or class name and description of purpose be included on the - same "printed page" as the copyright notice for easier - identification within third-party archives. - - Copyright {yyyy} {name of copyright owner} + Copyright 2020 MongoDB Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. @@ -198,4 +188,5 @@ Apache License distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and - limitations under the License. \ No newline at end of file + limitations under the License. + diff --git a/ts-ticket-office-service/node_modules/mongodb-connection-string-url/README.md b/ts-ticket-office-service/node_modules/mongodb-connection-string-url/README.md new file mode 100644 index 000000000..0eb65d00f --- /dev/null +++ b/ts-ticket-office-service/node_modules/mongodb-connection-string-url/README.md @@ -0,0 +1,25 @@ +# mongodb-connection-string-url + +MongoDB connection strings, based on the WhatWG URL API + +```js +import ConnectionString from 'mongodb-connection-string-url'; + +const cs = new ConnectionString('mongodb://localhost'); +cs.searchParams.set('readPreference', 'secondary'); +console.log(cs.href); // 'mongodb://localhost/?readPreference=secondary' +``` + +## Deviations from the WhatWG URL package + +- URL parameters are case-insensitive +- The `.host`, `.hostname` and `.port` properties cannot be set, and reading + them does not return meaningful results (and are typed as `never`in TypeScript) +- The `.hosts` property contains a list of all hosts in the connection string +- The `.href` property cannot be set, only read +- There is an additional `.isSRV` property, set to `true` for `mongodb+srv://` +- There is an additional `.clone()` utility method on the prototype + +## LICENSE + +Apache-2.0 diff --git a/ts-ticket-office-service/node_modules/mongodb-connection-string-url/lib/index.d.ts b/ts-ticket-office-service/node_modules/mongodb-connection-string-url/lib/index.d.ts new file mode 100644 index 000000000..49c18ea29 --- /dev/null +++ b/ts-ticket-office-service/node_modules/mongodb-connection-string-url/lib/index.d.ts @@ -0,0 +1,62 @@ +import { URL } from 'whatwg-url'; +import { redactConnectionString, ConnectionStringRedactionOptions } from './redact'; +export { redactConnectionString, ConnectionStringRedactionOptions }; +declare class CaseInsensitiveMap extends Map { + delete(name: K): boolean; + get(name: K): string | undefined; + has(name: K): boolean; + set(name: K, value: any): this; + _normalizeKey(name: any): K; +} +declare abstract class URLWithoutHost extends URL { + abstract get host(): never; + abstract set host(value: never); + abstract get hostname(): never; + abstract set hostname(value: never); + abstract get port(): never; + abstract set port(value: never); + abstract get href(): string; + abstract set href(value: string); +} +export interface ConnectionStringParsingOptions { + looseValidation?: boolean; +} +export declare class ConnectionString extends URLWithoutHost { + _hosts: string[]; + constructor(uri: string, options?: ConnectionStringParsingOptions); + get host(): never; + set host(_ignored: never); + get hostname(): never; + set hostname(_ignored: never); + get port(): never; + set port(_ignored: never); + get href(): string; + set href(_ignored: string); + get isSRV(): boolean; + get hosts(): string[]; + set hosts(list: string[]); + toString(): string; + clone(): ConnectionString; + redact(options?: ConnectionStringRedactionOptions): ConnectionString; + typedSearchParams(): { + append(name: keyof T & string, value: any): void; + delete(name: keyof T & string): void; + get(name: keyof T & string): string | null; + getAll(name: keyof T & string): string[]; + has(name: keyof T & string): boolean; + set(name: keyof T & string, value: any): void; + keys(): IterableIterator; + values(): IterableIterator; + entries(): IterableIterator<[keyof T & string, string]>; + _normalizeKey(name: keyof T & string): string; + [Symbol.iterator](): IterableIterator<[keyof T & string, string]>; + sort(): void; + forEach(callback: (this: THIS_ARG, value: string, name: string, searchParams: any) => void, thisArg?: THIS_ARG | undefined): void; + readonly [Symbol.toStringTag]: "URLSearchParams"; + }; +} +export declare class CommaAndColonSeparatedRecord> extends CaseInsensitiveMap { + constructor(from?: string | null); + toString(): string; +} +export default ConnectionString; diff --git a/ts-ticket-office-service/node_modules/mongodb-connection-string-url/lib/index.js b/ts-ticket-office-service/node_modules/mongodb-connection-string-url/lib/index.js new file mode 100644 index 000000000..8e4864d20 --- /dev/null +++ b/ts-ticket-office-service/node_modules/mongodb-connection-string-url/lib/index.js @@ -0,0 +1,213 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.CommaAndColonSeparatedRecord = exports.ConnectionString = exports.redactConnectionString = void 0; +const whatwg_url_1 = require("whatwg-url"); +const redact_1 = require("./redact"); +Object.defineProperty(exports, "redactConnectionString", { enumerable: true, get: function () { return redact_1.redactConnectionString; } }); +const DUMMY_HOSTNAME = '__this_is_a_placeholder__'; +function connectionStringHasValidScheme(connectionString) { + return (connectionString.startsWith('mongodb://') || + connectionString.startsWith('mongodb+srv://')); +} +const HOSTS_REGEX = /^(?[^/]+):\/\/(?:(?[^:@]*)(?::(?[^@]*))?@)?(?(?!:)[^/?@]*)(?.*)/; +class CaseInsensitiveMap extends Map { + delete(name) { + return super.delete(this._normalizeKey(name)); + } + get(name) { + return super.get(this._normalizeKey(name)); + } + has(name) { + return super.has(this._normalizeKey(name)); + } + set(name, value) { + return super.set(this._normalizeKey(name), value); + } + _normalizeKey(name) { + name = `${name}`; + for (const key of this.keys()) { + if (key.toLowerCase() === name.toLowerCase()) { + name = key; + break; + } + } + return name; + } +} +function caseInsenstiveURLSearchParams(Ctor) { + return class CaseInsenstiveURLSearchParams extends Ctor { + append(name, value) { + return super.append(this._normalizeKey(name), value); + } + delete(name) { + return super.delete(this._normalizeKey(name)); + } + get(name) { + return super.get(this._normalizeKey(name)); + } + getAll(name) { + return super.getAll(this._normalizeKey(name)); + } + has(name) { + return super.has(this._normalizeKey(name)); + } + set(name, value) { + return super.set(this._normalizeKey(name), value); + } + keys() { + return super.keys(); + } + values() { + return super.values(); + } + entries() { + return super.entries(); + } + [Symbol.iterator]() { + return super[Symbol.iterator](); + } + _normalizeKey(name) { + return CaseInsensitiveMap.prototype._normalizeKey.call(this, name); + } + }; +} +class URLWithoutHost extends whatwg_url_1.URL { +} +class MongoParseError extends Error { + get name() { + return 'MongoParseError'; + } +} +class ConnectionString extends URLWithoutHost { + constructor(uri, options = {}) { + var _a; + const { looseValidation } = options; + if (!looseValidation && !connectionStringHasValidScheme(uri)) { + throw new MongoParseError('Invalid scheme, expected connection string to start with "mongodb://" or "mongodb+srv://"'); + } + const match = uri.match(HOSTS_REGEX); + if (!match) { + throw new MongoParseError(`Invalid connection string "${uri}"`); + } + const { protocol, username, password, hosts, rest } = (_a = match.groups) !== null && _a !== void 0 ? _a : {}; + if (!looseValidation) { + if (!protocol || !hosts) { + throw new MongoParseError(`Protocol and host list are required in "${uri}"`); + } + try { + decodeURIComponent(username !== null && username !== void 0 ? username : ''); + decodeURIComponent(password !== null && password !== void 0 ? password : ''); + } + catch (err) { + throw new MongoParseError(err.message); + } + const illegalCharacters = /[:/?#[\]@]/gi; + if (username === null || username === void 0 ? void 0 : username.match(illegalCharacters)) { + throw new MongoParseError(`Username contains unescaped characters ${username}`); + } + if (!username || !password) { + const uriWithoutProtocol = uri.replace(`${protocol}://`, ''); + if (uriWithoutProtocol.startsWith('@') || uriWithoutProtocol.startsWith(':')) { + throw new MongoParseError('URI contained empty userinfo section'); + } + } + if (password === null || password === void 0 ? void 0 : password.match(illegalCharacters)) { + throw new MongoParseError('Password contains unescaped characters'); + } + } + let authString = ''; + if (typeof username === 'string') + authString += username; + if (typeof password === 'string') + authString += `:${password}`; + if (authString) + authString += '@'; + try { + super(`${protocol.toLowerCase()}://${authString}${DUMMY_HOSTNAME}${rest}`); + } + catch (err) { + if (looseValidation) { + new ConnectionString(uri, { + ...options, + looseValidation: false + }); + } + if (typeof err.message === 'string') { + err.message = err.message.replace(DUMMY_HOSTNAME, hosts); + } + throw err; + } + this._hosts = hosts.split(','); + if (!looseValidation) { + if (this.isSRV && this.hosts.length !== 1) { + throw new MongoParseError('mongodb+srv URI cannot have multiple service names'); + } + if (this.isSRV && this.hosts.some(host => host.includes(':'))) { + throw new MongoParseError('mongodb+srv URI cannot have port number'); + } + } + if (!this.pathname) { + this.pathname = '/'; + } + Object.setPrototypeOf(this.searchParams, caseInsenstiveURLSearchParams(this.searchParams.constructor).prototype); + } + get host() { return DUMMY_HOSTNAME; } + set host(_ignored) { throw new Error('No single host for connection string'); } + get hostname() { return DUMMY_HOSTNAME; } + set hostname(_ignored) { throw new Error('No single host for connection string'); } + get port() { return ''; } + set port(_ignored) { throw new Error('No single host for connection string'); } + get href() { return this.toString(); } + set href(_ignored) { throw new Error('Cannot set href for connection strings'); } + get isSRV() { + return this.protocol.includes('srv'); + } + get hosts() { + return this._hosts; + } + set hosts(list) { + this._hosts = list; + } + toString() { + return super.toString().replace(DUMMY_HOSTNAME, this.hosts.join(',')); + } + clone() { + return new ConnectionString(this.toString(), { + looseValidation: true + }); + } + redact(options) { + return (0, redact_1.redactValidConnectionString)(this, options); + } + typedSearchParams() { + const sametype = false && new (caseInsenstiveURLSearchParams(whatwg_url_1.URLSearchParams))(); + return this.searchParams; + } + [Symbol.for('nodejs.util.inspect.custom')]() { + const { href, origin, protocol, username, password, hosts, pathname, search, searchParams, hash } = this; + return { href, origin, protocol, username, password, hosts, pathname, search, searchParams, hash }; + } +} +exports.ConnectionString = ConnectionString; +class CommaAndColonSeparatedRecord extends CaseInsensitiveMap { + constructor(from) { + super(); + for (const entry of (from !== null && from !== void 0 ? from : '').split(',')) { + if (!entry) + continue; + const colonIndex = entry.indexOf(':'); + if (colonIndex === -1) { + this.set(entry, ''); + } + else { + this.set(entry.slice(0, colonIndex), entry.slice(colonIndex + 1)); + } + } + } + toString() { + return [...this].map(entry => entry.join(':')).join(','); + } +} +exports.CommaAndColonSeparatedRecord = CommaAndColonSeparatedRecord; +exports.default = ConnectionString; +//# sourceMappingURL=index.js.map \ No newline at end of file diff --git a/ts-ticket-office-service/node_modules/mongodb-connection-string-url/lib/index.js.map b/ts-ticket-office-service/node_modules/mongodb-connection-string-url/lib/index.js.map new file mode 100644 index 000000000..d325062aa --- /dev/null +++ b/ts-ticket-office-service/node_modules/mongodb-connection-string-url/lib/index.js.map @@ -0,0 +1 @@ +{"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":";;;AAAA,2CAAkD;AAClD,qCAIkB;AACT,uGAHP,+BAAsB,OAGO;AAE/B,MAAM,cAAc,GAAG,2BAA2B,CAAC;AAEnD,SAAS,8BAA8B,CAAC,gBAAwB;IAC9D,OAAO,CACL,gBAAgB,CAAC,UAAU,CA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AC,KAAK;gBAAE,SAAS;YACrB,MAAM,UAAU,GAAG,KAAK,CAAC,OAAO,CAAC,GAAG,CAAC,CAAC;YAEtC,IAAI,UAAU,KAAK,CAAC,CAAC,EAAE;gBACrB,IAAI,CAAC,GAAG,CAAC,KAA2B,EAAE,EAAE,CAAC,CAAC;aAC3C;iBAAM;gBACL,IAAI,CAAC,GAAG,CAAC,KAAK,CAAC,KAAK,CAAC,CAAC,EAAE,UAAU,CAAuB,EAAE,KAAK,CAAC,KAAK,CAAC,UAAU,GAAG,CAAC,CAAC,CAAC,CAAC;aACzF;SACF;IACH,CAAC;IAED,QAAQ;QACN,OAAO,CAAC,GAAG,IAAI,CAAC,CAAC,GAAG,CAAC,KAAK,CAAC,EAAE,CAAC,KAAK,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC;IAC3D,CAAC;CACF;AAlBD,oEAkBC;AAED,kBAAe,gBAAgB,CAAC"} \ No newline at end of file diff --git a/ts-ticket-office-service/node_modules/mongodb-connection-string-url/lib/redact.d.ts b/ts-ticket-office-service/node_modules/mongodb-connection-string-url/lib/redact.d.ts new file mode 100644 index 000000000..94a64defc --- /dev/null +++ b/ts-ticket-office-service/node_modules/mongodb-connection-string-url/lib/redact.d.ts @@ -0,0 +1,7 @@ +import ConnectionString from './index'; +export interface ConnectionStringRedactionOptions { + redactUsernames?: boolean; + replacementString?: string; +} +export declare function redactValidConnectionString(inputUrl: Readonly, options?: ConnectionStringRedactionOptions): ConnectionString; +export declare function redactConnectionString(uri: string, options?: ConnectionStringRedactionOptions): string; diff --git a/ts-ticket-office-service/node_modules/mongodb-connection-string-url/lib/redact.js b/ts-ticket-office-service/node_modules/mongodb-connection-string-url/lib/redact.js new file mode 100644 index 000000000..c24460c0e --- /dev/null +++ b/ts-ticket-office-service/node_modules/mongodb-connection-string-url/lib/redact.js @@ -0,0 +1,87 @@ +"use strict"; +var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + var desc = Object.getOwnPropertyDescriptor(m, k); + if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { return m[k]; } }; + } + Object.defineProperty(o, k2, desc); +}) : (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + o[k2] = m[k]; +})); +var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); +}) : function(o, v) { + o["default"] = v; +}); +var __importStar = (this && this.__importStar) || function (mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); + __setModuleDefault(result, mod); + return result; +}; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.redactConnectionString = exports.redactValidConnectionString = void 0; +const index_1 = __importStar(require("./index")); +function redactValidConnectionString(inputUrl, options) { + var _a, _b; + const url = inputUrl.clone(); + const replacementString = (_a = options === null || options === void 0 ? void 0 : options.replacementString) !== null && _a !== void 0 ? _a : '_credentials_'; + const redactUsernames = (_b = options === null || options === void 0 ? void 0 : options.redactUsernames) !== null && _b !== void 0 ? _b : true; + if ((url.username || url.password) && redactUsernames) { + url.username = replacementString; + url.password = ''; + } + else if (url.password) { + url.password = replacementString; + } + if (url.searchParams.has('authMechanismProperties')) { + const props = new index_1.CommaAndColonSeparatedRecord(url.searchParams.get('authMechanismProperties')); + if (props.get('AWS_SESSION_TOKEN')) { + props.set('AWS_SESSION_TOKEN', replacementString); + url.searchParams.set('authMechanismProperties', props.toString()); + } + } + if (url.searchParams.has('tlsCertificateKeyFilePassword')) { + url.searchParams.set('tlsCertificateKeyFilePassword', replacementString); + } + if (url.searchParams.has('proxyUsername') && redactUsernames) { + url.searchParams.set('proxyUsername', replacementString); + } + if (url.searchParams.has('proxyPassword')) { + url.searchParams.set('proxyPassword', replacementString); + } + return url; +} +exports.redactValidConnectionString = redactValidConnectionString; +function redactConnectionString(uri, options) { + var _a, _b; + const replacementString = (_a = options === null || options === void 0 ? void 0 : options.replacementString) !== null && _a !== void 0 ? _a : ''; + const redactUsernames = (_b = options === null || options === void 0 ? void 0 : options.redactUsernames) !== null && _b !== void 0 ? _b : true; + let parsed; + try { + parsed = new index_1.default(uri); + } + catch (_c) { } + if (parsed) { + options = { ...options, replacementString: '___credentials___' }; + return parsed.redact(options).toString().replace(/___credentials___/g, replacementString); + } + const regexes = [ + redactUsernames ? /(?<=\/\/)(.*)(?=@)/g : /(?<=\/\/[^@]+:)(.*)(?=@)/g, + /(?<=AWS_SESSION_TOKEN(:|%3A))([^,&]+)/gi, + /(?<=tlsCertificateKeyFilePassword=)([^&]+)/gi, + redactUsernames ? /(?<=proxyUsername=)([^&]+)/gi : null, + /(?<=proxyPassword=)([^&]+)/gi + ]; + for (const r of regexes) { + if (r !== null) { + uri = uri.replace(r, replacementString); + } + } + return uri; +} +exports.redactConnectionString = redactConnectionString; +//# sourceMappingURL=redact.js.map \ No newline at end of file diff --git a/ts-ticket-office-service/node_modules/mongodb-connection-string-url/lib/redact.js.map b/ts-ticket-office-service/node_modules/mongodb-connection-string-url/lib/redact.js.map new file mode 100644 index 000000000..0ed15d4d5 --- /dev/null +++ b/ts-ticket-office-service/node_modules/mongodb-connection-string-url/lib/redact.js.map @@ -0,0 +1 @@ +{"version":3,"file":"redact.js","sourceRoot":"","sources":["../src/redact.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;AAAA,iDAAyE;AAOzE,SAAgB,2BAA2B,CACzC,QAAoC,EACpC,OAA0C;;IAC1C,MAAM,GAAG,GAAG,QAAQ,CAAC,KAAK,EAAE,CAAC;IAC7B,MAAM,iBAAiB,GAAG,MAAA,OAAO,aAAP,OAAO,uBAAP,OAAO,CAAE,iBAAiB,mCAAI,eAAe,CAAC;IACxE,MAAM,eAAe,GAAG,MAAA,OAAO,aAAP,OAAO,uBAAP,OAAO,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CACpC,GAAW,EACX,OAA0C;;IAC1C,MAAM,iBAAiB,GAAG,MAAA,OAAO,aAAP,OAAO,uBAAP,OAAO,CAAE,iBAAiB,mCAAI,eAAe,CAAC;IACxE,MAAM,eAAe,GAAG,MAAA,OAAO,aAAP,OAAO,uBAAP,OAAO,CAAE,eAAe,mCAAI,IAAI,CAAC;IAEzD,IAAI,MAAoC,CAAC;IACzC,IAAI;QACF,MAAM,GAAG,IAAI,eAAgB,CAAC,GAAG,CAAC,CAAC;KACpC;IAAC,WAAM,GAAE;IACV,IAAI,MAAM,EAAE;QAGV,OAAO,GAAG,EAAE,GAAG,OAAO,EAAE,iBAAiB,EAAE,mBAAmB,EAAE,CAAC;QACjE,OAAO,MAAM,CAAC,MAAM,CAAC,OAAO,CAAC,CAAC,QAAQ,EAAE,CAAC,OAAO,CAAC,oBAAoB,EAAE,iBAAiB,CAAC,CAAC;KAC3F;IAED,MAAM,OAAO,GAAsB;QAEjC,eAAe,CAAC,CAAC,CAAC,qBAAqB,CAAC,CAAC,CAAC,2BAA2B;QAErE,yCAAyC;QAEzC,8CAA8C;QAE9C,eAAe,CAAC,CAAC,CAAC,8BAA8B,CAAC,CAAC,CAAC,IAAI;QAEvD,8BAA8B;KAC/B,CAAC;IACF,KAAK,MAAM,CAAC,IAAI,OAAO,EAAE;QACvB,IAAI,CAAC,KAAK,IAAI,EAAE;YACd,GAAG,GAAG,GAAG,CAAC,OAAO,CAAC,CAAC,EAAE,iBAAiB,CAAC,CAAC;SACzC;KACF;IACD,OAAO,GAAG,CAAC;AACb,CAAC;AAnCD,wDAmCC"} \ No newline at end of file diff --git a/ts-ticket-office-service/node_modules/mongodb-connection-string-url/package.json b/ts-ticket-office-service/node_modules/mongodb-connection-string-url/package.json new file mode 100644 index 000000000..9d3433fae --- /dev/null +++ b/ts-ticket-office-service/node_modules/mongodb-connection-string-url/package.json @@ -0,0 +1,62 @@ +{ + "name": "mongodb-connection-string-url", + "version": "2.5.3", + "description": "MongoDB connection strings, based on the WhatWG URL API", + "keywords": [ + "password", + "prompt", + "tty" + ], + "homepage": "https://github.com/mongodb-js/mongodb-connection-string-url", + "repository": { + "type": "git", + "url": "https://github.com/mongodb-js/mongodb-connection-string-url.git" + }, + "bugs": { + "url": "https://github.com/mongodb-js/mongodb-connection-string-url/issues" + }, + "main": "lib/index.js", + "exports": { + "require": "./lib/index.js", + "import": "./.esm-wrapper.mjs" + }, + "files": [ + "LICENSE", + "lib", + "package.json", + "README.md", + ".esm-wrapper.mjs" + ], + "scripts": { + "lint": "eslint \"{src,test}/**/*.ts\"", + "test": "npm run lint && npm run build && nyc mocha --colors -r ts-node/register test/*.ts", + "build": "npm run compile-ts && gen-esm-wrapper . ./.esm-wrapper.mjs", + "prepack": "npm run build", + "compile-ts": "tsc -p tsconfig.json" + }, + "license": "Apache-2.0", + "devDependencies": { + "@types/chai": "^4.2.5", + "@types/mocha": "^8.0.3", + "@types/node": "^14.11.1", + "@typescript-eslint/eslint-plugin": "^4.2.0", + "@typescript-eslint/parser": "^4.2.0", + "chai": "^4.2.0", + "eslint": "^7.9.0", + "eslint-config-semistandard": "^15.0.1", + "eslint-config-standard": "^14.1.1", + "eslint-plugin-import": "^2.22.0", + "eslint-plugin-node": "^11.1.0", + "eslint-plugin-promise": "^4.2.1", + "eslint-plugin-standard": "^4.0.1", + "gen-esm-wrapper": "^1.1.3", + "mocha": "^8.1.3", + "nyc": "^15.1.0", + "ts-node": "^10.9.1", + "typescript": "^4.7.4" + }, + "dependencies": { + "@types/whatwg-url": "^8.2.1", + "whatwg-url": "^11.0.0" + } +} diff --git a/ts-ticket-office-service/node_modules/mongodb-core/.coveralls.yml b/ts-ticket-office-service/node_modules/mongodb-core/.coveralls.yml deleted file mode 100644 index a0b4fb6c0..000000000 --- a/ts-ticket-office-service/node_modules/mongodb-core/.coveralls.yml +++ /dev/null @@ -1 +0,0 @@ -repo_token: 47iIZ0B3llo2Wc4dxWRltvgdImqcrVDTi diff --git a/ts-ticket-office-service/node_modules/mongodb-core/.eslintrc b/ts-ticket-office-service/node_modules/mongodb-core/.eslintrc deleted file mode 100644 index 753e2a525..000000000 --- a/ts-ticket-office-service/node_modules/mongodb-core/.eslintrc +++ /dev/null @@ -1,15 +0,0 @@ -{ - "extends": ["eslint:recommended"], - "env": { - "node": true, - "mocha": true - }, - "ecmaFeatures": { - "es6": true, - }, - "plugins": [ - ], - "rules": { - "no-console":0 - } -} diff --git a/ts-ticket-office-service/node_modules/mongodb-core/HISTORY.md b/ts-ticket-office-service/node_modules/mongodb-core/HISTORY.md deleted file mode 100644 index 93126c473..000000000 --- a/ts-ticket-office-service/node_modules/mongodb-core/HISTORY.md +++ /dev/null @@ -1,691 +0,0 @@ -2.1.17 2017-10-11 ------------------ -* fix a typo that completely broke SCRAM-SHA1 authentication - -2.1.16 2017-10-11 ------------------ -* avoid waiting for reconnect if reconnect disabled in Server topology -* avoid waiting for reconnect if reconnect disabled in Cursor -* NODE-990 cache the ScramSHA1 salted passwords up to 200 entries -* NODE-1153 ensure that errors are propagated on force destroy -* NODE-1153 ensure inUse and connecting queues are cleared on reauth - -2.1.15 2017-08-08 ------------------ -* Emit SDAM events on close and reconnect - -2.1.14 2017-07-07 ------------------ -* NODE-1073 updates scram.js hi() algorithm to utilize crypto.pbkdf2Sync() -* NODE-1049 only include primary server if there are no secondary servers for - readPrefrence secondaryPreferred -* moved `assign` polyfill to shared utils, replace usage of `extend` in tests - -2.1.13 2017-06-19 ------------------ -* NODE-1039 ensure we force destroy server instances, forcing queue to be flushed. -* Use actual server type in standalone SDAM events. - -2.1.12 2017-06-02 ------------------ -* NODE-1019 Set keepAlive to 300 seconds or 1/2 of socketTimeout if socketTimeout < keepAlive. -* Minor fix to report the correct state on error. -* NODE-1020 'family' was added to options to provide high priority for ipv6 addresses (Issue #1518, https://github.com/firej). -* Fix require_optional loading of bson-ext. -* Ensure no errors are thrown by replset if topology is destroyed before it finished connecting. -* NODE-999 SDAM fixes for Mongos and single Server event emitting. -* NODE-1014 Set socketTimeout to default to 360 seconds. -* NODE-1019 Set keepAlive to 300 seconds or 1/2 of socketTimeout if socketTimeout < keepAlive. - -2.1.11 2017-05-22 ------------------ -* NODE-987 Clear out old intervalIds on when calling topologyMonitor. -* NODE-987 Moved filtering to pingServer method and added test case. -* Check for connection destroyed just before writing out and flush out operations correctly if it is (Issue #179, https://github.com/jmholzinger). -* NODE-989 Refactored Replicaset monitoring to correcly monitor newly added servers, Also extracted setTimeout and setInterval to use custom wrappers Timeout and Interva. - -2.1.10 2017-04-18 ------------------ -* NODE-981 delegate auth to replset/mongos if inTopology is set. -* NODE-978 Wrap connection.end in try/catch for node 0.10.x issue causing exceptions to be thrown, Also surfaced getConnection for mongos and replset. -* Remove dynamic require (Issue #175, https://github.com/tellnes). -* NODE-696 Handle interrupted error for createIndexes. -* Fixed isse when user is executing find command using Server.command and it get interpreted as a wire protcol message, #172. -* NODE-966 promoteValues not being promoted correctly to getMore. -* Merged in fix for flushing out monitoring operations. - -2.1.9 2017-03-17 ----------------- -* Return lastIsMaster correctly when connecting with secondaryOnlyConnectionAllowed is set to true and only a secondary is available in replica state. -* Clone options when passed to wireProtocol handler to avoid intermittent modifications causing errors. -* Ensure SSL error propegates better for Replset connections when there is a SSL validation error. -* NODE-957 Fixed issue where < batchSize not causing cursor to be closed on execution of first batch. -* NODE-958 Store reconnectConnection on pool object to allow destroy to close immediately. - -2.1.8 2017-02-13 ----------------- -* NODE-925 ensure we reschedule operations while pool is < poolSize while pool is growing and there are no connections with not currently performing work. -* NODE-927 fixes issue where authentication was performed against arbiter instances. -* NODE-915 Normalize all host names to avoid comparison issues. -* Fixed issue where pool.destroy would never finish due to a single operation not being executed and keeping it open. - -2.1.7 2017-01-24 ----------------- -* NODE-919 ReplicaSet connection does not close immediately (Issue #156). -* NODE-901 Fixed bug when normalizing host names. -* NODE-909 Fixed readPreference issue caused by direct connection to primary. -* NODE-910 Fixed issue when bufferMaxEntries == 0 and read preference set to nearest. - -2.1.6 2017-01-13 ----------------- -* NODE-908 Keep auth contexts in replset and mongos topology to ensure correct application of authentication credentials when primary is first server to be detected causing an immediate connect event to happen. - -2.1.5 2017-01-11 ----------------- -* updated bson and bson-ext dependencies to 1.0.4 to work past early node 4.x.x version having a broken Buffer.from implementation. - -2.1.4 2017-01-03 ----------------- -* updated bson and bson-ext dependencies to 1.0.3 due to util.inspect issue with ObjectId optimizations. - -2.1.3 2017-01-03 ----------------- -* Monitoring operations are re-scheduled in pool if it cannot find a connection that does not already have scheduled work on it, this is to avoid the monitoring socket timeout being applied to any existing operations on the socket due to pipelining -* Moved replicaset monitoring away from serial mode and to parallel mode. -* updated bson and bson-ext dependencies to 1.0.2. - -2.1.2 2016-12-10 ----------------- -* Delay topologyMonitoring on successful attemptReconnect as no need to run a full scan immediately. -* Emit reconnect event in primary joining when in connected status for a replicaset. - -2.1.1 2016-12-08 ----------------- -* Updated bson library to 1.0.1. -* Added optional support for bson-ext 1.0.1. - -2.1.0 2016-12-05 ----------------- -* Updated bson library to 1.0.0. -* Added optional support for bson-ext 1.0.0. -* Expose property parserType allowing for identification of currently configured parser. - -2.0.14 2016-11-29 ------------------ -* Updated bson library to 0.5.7. -* Dont leak connection.workItems elments when killCursor is called (Issue #150, https://github.com/mdlavin). -* Remove unnecessary errors formatting (Issue #149, https://github.com/akryvomaz). -* Only check isConnected against availableConnections (Issue #142). -* NODE-838 Provide better error message on failed to connect on first retry for Mongos topology. -* Set default servername to host is not passed through for sni. -* Made monitoring happen on exclusive connection and using connectionTimeout to handle the wait time before failure (Issue #148). -* NODE-859 Make minimum value of maxStalenessSeconds 90 seconds. -* NODE-852 Fix Kerberos module deprecations on linux and windows and release new kerberos version. -* NODE-850 Update Max Staleness implementation. -* NODE-849 username no longer required for MONGODB-X509 auth. -* NODE-848 BSON Regex flags must be alphabetically ordered. -* NODE-846 Create notice for all third party libraries. -* NODE-843 Executing bulk operations overwrites write concern parameter. -* NODE-842 Re-sync SDAM and SDAM Monitoring tests from Specs repo. -* NODE-840 Resync CRUD spec tests. -* Unescapable while(true) loop (Issue #152). - -2.0.13 2016-10-21 ------------------ -* Updated bson library to 0.5.6. - - Included cyclic dependency detection -* Fire callback when topology was destroyed (Issue #147, https://github.com/vkarpov15). -* Refactoring to support pipelining ala 1.4.x branch will retaining the benefits of the growing/shrinking pool (Issue #146). -* Fix typo in serverHeartbeatFailed event name (Issue #143, https://github.com/jakesjews). -* NODE-798 Driver hangs on count command in replica set with one member (Issue #141, https://github.com/isayme). - -2.0.12 2016-09-15 ------------------ -* fix debug logging message not printing server name. -* fixed application metadata being sent by wrong ismaster. -* NODE-812 Fixed mongos stall due to proxy monitoring ismaster failure causing reconnect. -* NODE-818 Replicaset timeouts in initial connect sequence can "no primary found". -* Updated bson library to 0.5.5. -* Added DBPointer up conversion to DBRef. - -2.0.11 2016-08-29 ------------------ -* NODE-803, Fixed issue in how the latency window is calculated for Mongos topology causing issues for single proxy connections. -* Avoid timeout in attemptReconnect causing multiple attemptReconnect attempts to happen (Issue #134, https://github.com/dead-horse). -* Ensure promoteBuffers is propagated in same fashion as promoteValues and promoteLongs - -2.0.10 2016-08-23 ------------------ -* Added promoteValues flag (default to true) to allow user to specify they only want wrapped BSON values back instead of promotion to native types. -* Do not close mongos proxy connection on failed ismaster check in ha process (Issue #130). - -2.0.9 2016-08-19 ----------------- -* Allow promoteLongs to be passed in through Response.parse method and overrides default set on the connection. -* NODE-798 Driver hangs on count command in replica set with one member. -* Allow promoteLongs to be passed in through Response.parse method and overrides default set on the connection. -* Allow passing in servername for TLS connections for SNI support. - -2.0.8 2016-08-16 ----------------- -* Allow execution of store operations indepent of having both a primary and secondary available (Issue #123). -* Fixed command execution issue for mongos to ensure buffering of commands when no mongos available. -* Added hashed connection names and fullResult. -* Updated bson library to 0.5.3. -* Wrap callback in nextTick to ensure exceptions are thrown correctly. - -2.0.7 2016-07-28 ----------------- -* Allow primary to be returned when secondaryPreferred is passed (Issue #117, https://github.com/dhendo). -* Added better warnings when passing in illegal seed list members to a Mongos topology. -* Minor attemptReconnect bug that would cause multiple attemptReconnect to run in parallel. -* Fix wrong opType passed to disconnectHandler.add (Issue #121, https://github.com/adrian-gierakowski) -* Implemented domain backward comp support enabled via domainsEnabled options on Server/ReplSet/Mongos and MongoClient.connect. -* Initial max staleness implementation for ReplSet and Mongos for 3.4 support. -* Added handling of collation for 3.4 support. - -2.0.6 2016-07-19 ----------------- -* Destroy connection on socket timeout due to newer node versions not closing the socket. - -2.0.5 2016-07-15 ----------------- -* Minor fixes to handle faster MongoClient connectivity from the driver, allowing single server instances to detect if they are a proxy. -* Added numberOfConsecutiveTimeouts to pool that will destroy the pool if the number of consecutive timeouts > reconnectTries. -* Print warning if seedlist servers host name does not match the one provided in it's ismaster.me field for Replicaset members. -* Fix issue where Replicaset connection would not succeeed if there the replicaset was a single primary server setup. - -2.0.4 2016-07-11 ------------------ -* Updated bson to version 0.5.1. -* handle situation where user is providing seedlist names that do not match host list. fix allows for a single full discovery connection sweep before erroring out. -* NODE-747 Polyfill for Object.assign for 0.12.x or 0.10.x. -* NODE-746 Improves replicaset errors for wrong setName. - -2.0.3 2016-07-08 ------------------ -* Implemented Server Selection Specification test suite. -* Added warning level to logger. -* Added warning message when sockeTimeout < haInterval for Replset/Mongos. - -2.0.2 2016-07-06 ------------------ -* Mongos emits close event on no proxies available or when reconnect attempt fails. -* Replset emits close event when no servers available or when attemptReconnect fails to reconnect. -* Don't throw in auth methods but return error in callback. - -2.0.1 2016-07-05 ------------------ -* Added missing logout method on mongos proxy topology. -* Fixed logger error serialization issue. -* Documentation fixes. - -2.0.0 2016-07-05 ------------------ -* Moved all authentication and handling of growing/shrinking of pool connections into actual pool. -* All authentication methods now handle both auth/reauthenticate and logout events. -* Introduced logout method to get rid of onAll option for logout command. -* Updated bson to 0.5.0 that includes Decimal128 support. - -1.3.21 2016-05-30 ------------------ -* Pool gets stuck if a connection marked for immediateRelease times out (Issue #99, https://github.com/nbrachet). -* Make authentication process retry up to authenticationRetries at authenticationRetryIntervalMS interval. -* Made ismaster replicaset calls operate with connectTimeout or monitorSocketTimeout to lower impact of big socketTimeouts on monitoring performance. -* Make sure connections mark as "immediateRelease" don't linger the inUserConnections list. Otherwise, after that connection times out, getAll() incorrectly returns more connections than are effectively present, causing the pool to not get restarted by reconnectServer. (Issue #99, https://github.com/nbrachet). -* Make cursor getMore or killCursor correctly trigger pool reconnect to single server if pool has not been destroyed. -* Make ismaster monitoring for single server connection default to avoid user confusion due to change in behavior. - -1.3.20 2016-05-25 ------------------ -* NODE-710 Allow setting driver loggerLevel and logger function from MongoClient options. -* Minor fix for SSL errors on connection attempts, minor fix to reconnect handler for the server. -* Don't write to socket before having registered the callback for commands, work around for windows issuing error events twice on node.js when socket gets destroyed by firewall. -* Fix minor issue where connectingServers would not be removed correctly causing single server connections to not auto-reconnect. - -1.3.19 2016-05-17 ------------------ -- Handle situation where a server connection in a replicaset sometimes fails to be destroyed properly due to being in the middle of authentication when the destroy method is called on the replicaset causing it to be orphaned and never collected. -- Set keepAlive to false by default to work around bug in node.js for Windows XP and Windows 2003. -- Ensure replicaset topology destroy is never called by SDAM. -- Ensure all paths are correctly returned on inspectServer in replset. - -1.3.18 2016-04-27 ------------------ -- Hardened cursor connection handling for getMore and killCursor to ensure mid operation connection kill does not throw null exception. -- Fixes for Node 6.0 support. - -1.3.17 2016-04-26 ------------------ -- Added improved handling of reconnect when topology is a single server. -- Added better handling of $query queries passed down for 3.2 or higher. -- Introduced getServerFrom method to topologies to let cursor grab a new pool for getMore and killCursors commands and not use connection pipelining. -- NODE-693 Move authentication to be after ismaster call to avoid authenticating against arbiters. - -1.3.16 2016-04-07 ------------------ -- Only call unref on destroy if it exists to ensure proper working destroy method on early node v0.10.x versions. - -1.3.15 2016-04-06 ------------------ -- NODE-687 Fixed issue where a server object failed to be destroyed if the replicaset state did not update successfully. This could leave active connections accumulating over time. -- Fixed some situations where all connections are flushed due to a single connection in the connection pool closing. - -1.3.14 2016-04-01 ------------------ -- Ensure server inquireServerState exits immediately on server.destroy call. -- Refactored readPreference handling in 2.4, 2.6 and 3.2 wire protocol handling. - -1.3.13 2016-03-30 ------------------ -- Handle missing cursor on getMore when going through a mongos proxy by pinning to socket connection and not server. - -1.3.12 2016-03-29 ------------------ -- Mongos pickProxies fall back to closest mongos if no proxies meet latency window specified. - -1.3.11 2016-03-29 ------------------ -- isConnected method for mongos uses same selection code as getServer. -- Exceptions in cursor getServer trapped and correctly delegated to high level handler. - -1.3.10 2016-03-22 ------------------ -- SDAM Monitoring emits diff for Replicasets to simplify detecting the state changes. -- SDAM Monitoring correctly emits Mongos as serverDescriptionEvent. - -1.3.9 2016-03-20 ----------------- -- Removed monitoring exclusive connection, should resolve timeouts and reconnects on idle replicasets where haInteval > socketTimeout. - -1.3.8 2016-03-18 ----------------- -- Implements the SDAM monitoring specification. -- Fix issue where cursor would error out and not be buffered when primary is not connected. - -1.3.7 2016-03-16 ----------------- -- Fixed issue with replicasetInquirer where it could stop performing monitoring if there was no servers available. - -1.3.6 2016-03-15 ----------------- -- Fixed raise condition where multiple replicasetInquirer operations could be started in parallel creating redundant connections. - -1.3.5 2016-03-14 ----------------- -- Handle rogue SSL exceptions (Issue #85, https://github.com/durran). - -1.3.4 2016-03-14 ----------------- -- Added unref options on server, replicaset and mongos (Issue #81, https://github.com/allevo) -- cursorNotFound flag always false (Issue #83, https://github.com/xgfd) -- refactor of events emission of fullsetup and all events (Issue #84, https://github.com/xizhibei) - -1.3.3 2016-03-08 ----------------- -- Added support for promoteLongs option for command function. -- Return connection if no callback available -- Emit connect event when server reconnects after initial connection failed (Issue #76, https://github.com/vkarpov15) -- Introduced optional monitoringSocketTimeout option to allow better control of SDAM monitoring timeouts. -- Made monitoringSocketTimeout default to 30000 if no connectionTimeout value specified or if set to 0. -- Fixed issue where tailable cursor would not retry even though cursor was still alive. -- Disabled exhaust flag support to avoid issues where users could easily write code that would cause memory to run out. -- Handle the case where the first command result document returns an empty list of documents but a live cursor. -- Allow passing down off CANONICALIZE_HOST_NAME and SERVICE_REALM options for kerberos. - -1.3.2 2016-02-09 ----------------- -- Harden MessageHandler in server.js to avoid issues where we cannot find a callback for an operation. -- Ensure RequestId can never be larger than Max Number integer size. - -1.3.1 2016-02-05 ----------------- -- Removed annoying missing Kerberos error (NODE-654). - -1.3.0 2016-02-03 ----------------- -- Added raw support for the command function on topologies. -- Fixed issue where raw results that fell on batchSize boundaries failed (Issue #72) -- Copy over all the properties to the callback returned from bindToDomain, (Issue #72) -- Added connection hash id to be able to reference connection host/name without leaking it outside of driver. -- NODE-638, Cannot authenticate database user with utf-8 password. -- Refactored pool to be worker queue based, minimizing the impact a slow query have on throughput as long as # slow queries < # connections in the pool. -- Pool now grows and shrinks correctly depending on demand not causing a full pool reconnect. -- Improvements in monitoring of a Replicaset where in certain situations the inquiry process could get exited. -- Switched to using Array.push instead of concat for use cases of a lot of documents. -- Fixed issue where re-authentication could loose the credentials if whole Replicaset disconnected at once. -- Added peer optional dependencies support using require_optional module. - -1.2.32 2016-01-12 ------------------ -- Bumped bson to V0.4.21 to allow using minor optimizations. - -1.2.31 2016-01-04 ------------------ -- Allow connection to secondary if primaryPreferred or secondaryPreferred (Issue #70, https://github.com/leichter) - -1.2.30 2015-12-23 ------------------ -- Pool allocates size + 1 connections when using replicasets, reserving additional pool connection for monitoring exclusively. -- Fixes bug when all replicaset members are down, that would cause it to fail to reconnect using the originally provided seedlist. - -1.2.29 2015-12-17 ------------------ -- Correctly emit close event when calling destroy on server topology. - -1.2.28 2015-12-13 ------------------ -- Backed out Prevent Maximum call stack exceeded by calling all callbacks on nextTick, (Issue #64, https://github.com/iamruinous) as it breaks node 0.10.x support. - -1.2.27 2015-12-13 ------------------ -- Added [options.checkServerIdentity=true] {boolean|function}. Ensure we check server identify during SSL, set to false to disable checking. Only works for Node 0.12.x or higher. You can pass in a boolean or your own checkServerIdentity override function, (Issue #29). -- Prevent Maximum call stack exceeded by calling all callbacks on nextTick, (Issue #64, https://github.com/iamruinous). -- State is not defined in mongos, (Issue #63, https://github.com/flyingfisher). -- Fixed corner case issue on exhaust cursors on pre 3.0.x MongoDB. - -1.2.26 2015-11-23 ------------------ -- Converted test suite to use mongodb-topology-manager. -- Upgraded bson library to V0.4.20. -- Minor fixes for 3.2 readPreferences. - -1.2.25 2015-11-23 ------------------ -- Correctly error out when passed a seedlist of non-valid server members. - -1.2.24 2015-11-20 ------------------ -- Fix Automattic/mongoose#3481; flush callbacks on error, (Issue #57, https://github.com/vkarpov15). -- $explain query for wire protocol 2.6 and 2.4 does not set number of returned documents to -1 but to 0. - -1.2.23 2015-11-16 ------------------ -- ismaster runs against admin.$cmd instead of system.$cmd. - -1.2.22 2015-11-16 ------------------ -- Fixes to handle getMore command errors for MongoDB 3.2 -- Allows the process to properly close upon a Db.close() call on the replica set by shutting down the haTimer and closing arbiter connections. - -1.2.21 2015-11-07 ------------------ -- Hardened the checking for replicaset equality checks. -- OpReplay flag correctly set on Wire protocol query. -- Mongos load balancing added, introduced localThresholdMS to control the feature. -- Kerberos now a peerDependency, making it not install it by default in Node 5.0 or higher. - -1.2.20 2015-10-28 ------------------ -- Fixed bug in arbiter connection capping code. -- NODE-599 correctly handle arrays of server tags in order of priority. -- Fix for 2.6 wire protocol handler related to readPreference handling. -- Added maxAwaitTimeMS support for 3.2 getMore to allow for custom timeouts on tailable cursors. -- Make CoreCursor check for $err before saying that 'next' succeeded (Issue #53, https://github.com/vkarpov15). - -1.2.19 2015-10-15 ------------------ -- Make batchSize always be > 0 for 3.2 wire protocol to make it work consistently with pre 3.2 servers. -- Locked to bson 0.4.19. - -1.2.18 2015-10-15 ------------------ -- Minor 3.2 fix for handling readPreferences on sharded commands. -- Minor fixes to correctly pass APM specification test suite. - -1.2.17 2015-10-08 ------------------ -- Connections to arbiters only maintain a single connection. - -1.2.15 2015-10-06 ------------------ -- Set slaveOk to true for getMore and killCursors commands. -- Don't swallow callback errors for 2.4 single server (Issue #49, https://github.com/vkarpov15). -- Apply toString('hex') to each buffer in an array when logging (Issue #48, https://github.com/nbrachet). - -1.2.14 2015-09-28 ------------------ -- NODE-547 only emit error if there are any listeners. -- Fixed APM issue with issuing readConcern. - -1.2.13 2015-09-18 ------------------ -- Added BSON serializer ignoreUndefined option for insert/update/remove/command/cursor. - -1.2.12 2015-09-08 ------------------ -- NODE-541 Added initial support for readConcern. - -1.2.11 2015-08-31 ------------------ -- NODE-535 If connectWithNoPrimary is true then primary-only connection is not allowed. -- NODE-534 Passive secondaries are not allowed for secondaryOnlyConnectionAllowed. -- Fixed filtering bug for logging (Issue 30, https://github.com/christkv/mongodb-core/issues/30). - -1.2.10 2015-08-14 ------------------ -- Added missing Mongos.prototype.parserType function. - -1.2.9 2015-08-05 ----------------- -- NODE-525 Reset connectionTimeout after it's overwritten by tls.connect. -- NODE-518 connectTimeoutMS is doubled in 2.0.39. - -1.2.8 2015-07-24 ------------------ -- Minor fix to handle 2.4.x errors better by correctly return driver layer issues. - -1.2.7 2015-07-16 ------------------ -- Refactoring to allow to tap into find/getmore/killcursor in cursors for APM monitoring in driver. - -1.2.6 2015-07-14 ------------------ -- NODE-505 Query fails to find records that have a 'result' property with an array value. - -1.2.5 2015-07-14 ------------------ -- NODE-492 correctly handle hanging replicaset monitoring connections when server is unavailable due to network partitions or firewalls dropping packets, configureable using the connectionTimeoutMS setting. - -1.2.4 2015-07-07 ------------------ -- NODE-493 staggering the socket connections to avoid overwhelming the mongod process. - -1.2.3 2015-06-26 ------------------ -- Minor bug fixes. - -1.2.2 2015-06-22 ------------------ -- Fix issue with SCRAM authentication causing authentication to return true on failed authentication (Issue 26, https://github.com/cglass17). - -1.2.1 2015-06-17 ------------------ -- Ensure serializeFunctions passed down correctly to wire protocol. - -1.2.0 2015-06-17 ------------------ -- Switching to using the 0.4.x pure JS serializer, removing dependency on C++ parser. -- Refactoring wire protocol messages to avoid expensive size calculations of documents in favor of writing out an array of buffers to the sockets. -- NODE-486 fixed issue related to limit and skip when calling toArray in 2.0 driver. -- NODE-483 throw error if capabilities of topology is queries before topology has performed connection setup. -- NODE-487 fixed issue where killcursor command was not being sent correctly on limit and skip queries. - -1.1.33 2015-05-31 ------------------ -- NODE-478 Work around authentication race condition in mongos authentication due to multi step authentication methods like SCRAM. - -1.1.32 2015-05-20 ------------------ -- After reconnect, it updates the allowable reconnect retries to the option settings (Issue #23, https://github.com/owenallenaz) - -1.1.31 2015-05-19 ------------------ -- Minor fixes for issues with re-authentication of mongos. - -1.1.30 2015-05-18 ------------------ -- Correctly emit 'all' event when primary + all secondaries have connected. - -1.1.29 2015-05-17 ------------------ -- NODE-464 Only use a single socket against arbiters and hidden servers. -- Ensure we filter out hidden servers from any server queries. - -1.1.28 2015-05-12 ------------------ -- Fixed buffer compare for electionId for < node 12.0.2 - -1.1.27 2015-05-12 ------------------ -- NODE-455 Update SDAM specification support to cover electionId and Mongos load balancing. - -1.1.26 2015-05-06 ------------------ -- NODE-456 Allow mongodb-core to pipeline commands (ex findAndModify+GLE) along the same connection and handle the returned results. -- Fixes to make mongodb-core work for node 0.8.x when using scram and setImmediate. - -1.1.25 2015-04-24 ------------------ -- Handle lack of callback in crud operations when returning error on application closed. - -1.1.24 2015-04-22 ------------------ -- Error out when topology has been destroyed either by connection retries being exhausted or destroy called on topology. - -1.1.23 2015-04-15 ------------------ -- Standardizing mongoErrors and its API (Issue #14) -- Creating a new connection is slow because of 100ms setTimeout() (Issue #17, https://github.com/vkarpov15) -- remove mkdirp and rimraf dependencies (Issue #12) -- Updated default value of param options.rejectUnauthorized to match documentation (Issue #16) -- ISSUE: NODE-417 Resolution. Improving behavior of thrown errors (Issue #14, https://github.com/owenallenaz) -- Fix cursor hanging when next() called on exhausted cursor (Issue #18, https://github.com/vkarpov15) - -1.1.22 2015-04-10 ------------------ -- Minor refactorings in cursor code to make extending the cursor simpler. -- NODE-417 Resolution. Improving behavior of thrown errors using Error.captureStackTrace. - -1.1.21 2015-03-26 ------------------ -- Updated bson module to 0.3.0 that extracted the c++ parser into bson-ext and made it an optional dependency. - -1.1.20 2015-03-24 ------------------ -- NODE-395 Socket Not Closing, db.close called before full set finished initalizing leading to server connections in progress not being closed properly. - -1.1.19 2015-03-21 ------------------ -- Made kerberos module ~0.0 to allow for quicker releases due to io.js of kerberos module. - -1.1.18 2015-03-17 ------------------ -- Added support for minHeartbeatFrequencyMS on server reconnect according to the SDAM specification. - -1.1.17 2015-03-16 ------------------ -- NODE-377, fixed issue where tags would correctly be checked on secondary and nearest to filter out eligible server candidates. - -1.1.16 2015-03-06 ------------------ -- rejectUnauthorized parameter is set to true for ssl certificates by default instead of false. - -1.1.15 2015-03-04 ------------------ -- Removed check for type in replset pickserver function. - -1.1.14 2015-02-26 ------------------ -- NODE-374 correctly adding passive secondaries to the list of eligable servers for reads - -1.1.13 2015-02-24 ------------------ -- NODE-365 mongoDB native node.js driver infinite reconnect attempts (fixed issue around handling of retry attempts) - -1.1.12 2015-02-16 ------------------ -- Fixed cursor transforms for buffered document reads from cursor. - -1.1.11 2015-02-02 ------------------ -- Remove the required setName for replicaset connections, if not set it will pick the first setName returned. - -1.1.10 2015-31-01 ------------------ -- Added tranforms.doc option to cursor to allow for pr. document transformations. - -1.1.9 2015-21-01 ----------------- -- Updated BSON dependency to 0.2.18 to fix issues with io.js and node. -- Updated Kerberos dependency to 0.0.8 to fix issues with io.js and node. -- Don't treat findOne() as a command cursor. -- Refactored out state changes into methods to simplify read the next method. - -1.1.8 2015-09-12 ----------------- -- Stripped out Object.defineProperty for performance reasons -- Applied more performance optimizations. -- properties cursorBatchSize, cursorSkip, cursorLimit are not methods setCursorBatchSize/cursorBatchSize, setCursorSkip/cursorSkip, setCursorLimit/cursorLimit - -1.1.7 2014-18-12 ----------------- -- Use ns variable for getMore commands for command cursors to work properly with cursor version of listCollections and listIndexes. - -1.1.6 2014-18-12 ----------------- -- Server manager fixed to support 2.2.X servers for travis test matrix. - -1.1.5 2014-17-12 ----------------- -- Fall back to errmsg when creating MongoError for command errors - -1.1.4 2014-17-12 ----------------- -- Added transform method support for cursor (initially just for initial query results) to support listCollections/listIndexes in 2.8. -- Fixed variable leak in scram. -- Fixed server manager to deal better with killing processes. -- Bumped bson to 0.2.16. - -1.1.3 2014-01-12 ----------------- -- Fixed error handling issue with nonce generation in mongocr. -- Fixed issues with restarting servers when using ssl. -- Using strict for all classes. -- Cleaned up any escaping global variables. - -1.1.2 2014-20-11 ----------------- -- Correctly encoding UTF8 collection names on wire protocol messages. -- Added emitClose parameter to topology destroy methods to allow users to specify that they wish the topology to emit the close event to any listeners. - -1.1.1 2014-14-11 ----------------- -- Refactored code to use prototype instead of privileged methods. -- Fixed issue with auth where a runtime condition could leave replicaset members without proper authentication. -- Several deopt optimizations for v8 to improve performance and reduce GC pauses. - -1.0.5 2014-29-10 ----------------- -- Fixed issue with wrong namespace being created for command cursors. - -1.0.4 2014-24-10 ----------------- -- switched from using shift for the cursor due to bad slowdown on big batchSizes as shift causes entire array to be copied on each call. - -1.0.3 2014-21-10 ----------------- -- fixed error issuing problem on cursor.next when iterating over a huge dataset with a very small batchSize. - -1.0.2 2014-07-10 ----------------- -- fullsetup is now defined as a primary and secondary being available allowing for all read preferences to be satisfied. -- fixed issue with replset_state logging. - -1.0.1 2014-07-10 ----------------- -- Dependency issue solved - -1.0.0 2014-07-10 ----------------- -- Initial release of mongodb-core diff --git a/ts-ticket-office-service/node_modules/mongodb-core/Makefile b/ts-ticket-office-service/node_modules/mongodb-core/Makefile deleted file mode 100644 index 36e120248..000000000 --- a/ts-ticket-office-service/node_modules/mongodb-core/Makefile +++ /dev/null @@ -1,11 +0,0 @@ -NODE = node -NPM = npm -JSDOC = jsdoc -name = all - -generate_docs: - # cp -R ./HISTORY.md ./docs/content/meta/release-notes.md - hugo -s docs/reference -d ../../public - $(JSDOC) -c conf.json -t docs/jsdoc-template/ -d ./public/api - cp -R ./public/api/scripts ./public/. - cp -R ./public/api/styles ./public/. diff --git a/ts-ticket-office-service/node_modules/mongodb-core/README.md b/ts-ticket-office-service/node_modules/mongodb-core/README.md deleted file mode 100644 index 433dd8869..000000000 --- a/ts-ticket-office-service/node_modules/mongodb-core/README.md +++ /dev/null @@ -1,228 +0,0 @@ -[![Build Status](https://secure.travis-ci.org/christkv/mongodb-core.png)](http://travis-ci.org/christkv/mongodb-core) -[![Coverage Status](https://coveralls.io/repos/github/christkv/mongodb-core/badge.svg?branch=1.3)](https://coveralls.io/github/christkv/mongodb-core?branch=1.3) - -# Description - -The MongoDB Core driver is the low level part of the 2.0 or higher MongoDB driver and is meant for library developers not end users. It does not contain any abstractions or helpers outside of the basic management of MongoDB topology connections, CRUD operations and authentication. - -## MongoDB Node.JS Core Driver - -| what | where | -|---------------|------------------------------------------------| -| documentation | http://mongodb.github.io/node-mongodb-native/ | -| apidoc | http://mongodb.github.io/node-mongodb-native/ | -| source | https://github.com/christkv/mongodb-core | -| mongodb | http://www.mongodb.org/ | - -### Blogs of Engineers involved in the driver -- Christian Kvalheim [@christkv](https://twitter.com/christkv) - -### Bugs / Feature Requests - -Think you’ve found a bug? Want to see a new feature in node-mongodb-native? Please open a -case in our issue management tool, JIRA: - -- Create an account and login . -- Navigate to the NODE project . -- Click **Create Issue** - Please provide as much information as possible about the issue type and how to reproduce it. - -Bug reports in JIRA for all driver projects (i.e. NODE, PYTHON, CSHARP, JAVA) and the -Core Server (i.e. SERVER) project are **public**. - -### Questions and Bug Reports - - * mailing list: https://groups.google.com/forum/#!forum/node-mongodb-native - * jira: http://jira.mongodb.org/ - -### Change Log - -http://jira.mongodb.org/browse/NODE - -# QuickStart - -The quick start guide will show you how to set up a simple application using Core driver and MongoDB. It scope is only how to set up the driver and perform the simple crud operations. For more inn depth coverage we encourage reading the tutorials. - -## Create the package.json file - -Let's create a directory where our application will live. In our case we will put this under our projects directory. - -``` -mkdir myproject -cd myproject -``` - -Create a **package.json** using your favorite text editor and fill it in. - -```json -{ - "name": "myproject", - "version": "1.0.0", - "description": "My first project", - "main": "index.js", - "repository": { - "type": "git", - "url": "git://github.com/christkv/myfirstproject.git" - }, - "dependencies": { - "mongodb-core": "~1.0" - }, - "author": "Christian Kvalheim", - "license": "Apache 2.0", - "bugs": { - "url": "https://github.com/christkv/myfirstproject/issues" - }, - "homepage": "https://github.com/christkv/myfirstproject" -} -``` - -Save the file and return to the shell or command prompt and use **NPM** to install all the dependencies. - -``` -npm install -``` - -You should see **NPM** download a lot of files. Once it's done you'll find all the downloaded packages under the **node_modules** directory. - -Booting up a MongoDB Server ---------------------------- -Let's boot up a MongoDB server instance. Download the right MongoDB version from [MongoDB](http://www.mongodb.org), open a new shell or command line and ensure the **mongod** command is in the shell or command line path. Now let's create a database directory (in our case under **/data**). - -``` -mongod --dbpath=/data --port 27017 -``` - -You should see the **mongod** process start up and print some status information. - -## Connecting to MongoDB - -Let's create a new **app.js** file that we will use to show the basic CRUD operations using the MongoDB driver. - -First let's add code to connect to the server. Notice that there is no concept of a database here and we use the topology directly to perform the connection. - -```js -var Server = require('mongodb-core').Server - , assert = require('assert'); - -// Set up server connection -var server = new Server({ - host: 'localhost' - , port: 27017 - , reconnect: true - , reconnectInterval: 50 -}); - -// Add event listeners -server.on('connect', function(_server) { - console.log('connected'); - test.done(); -}); - -server.on('close', function() { - console.log('closed'); -}); - -server.on('reconnect', function() { - console.log('reconnect'); -}); - -// Start connection -server.connect(); -``` - -To connect to a replicaset we would use the `ReplSet` class and for a set of Mongos proxies we use the `Mongos` class. Each topology class offer the same CRUD operations and you operate on the topology directly. Let's look at an example exercising all the different available CRUD operations. - -```js -var Server = require('mongodb-core').Server - , assert = require('assert'); - -// Set up server connection -var server = new Server({ - host: 'localhost' - , port: 27017 - , reconnect: true - , reconnectInterval: 50 -}); - -// Add event listeners -server.on('connect', function(_server) { - console.log('connected'); - - // Execute the ismaster command - _server.command('system.$cmd', {ismaster: true}, function(err, result) { - - // Perform a document insert - _server.insert('myproject.inserts1', [{a:1}, {a:2}], { - writeConcern: {w:1}, ordered:true - }, function(err, results) { - assert.equal(null, err); - assert.equal(2, results.result.n); - - // Perform a document update - _server.update('myproject.inserts1', [{ - q: {a: 1}, u: {'$set': {b:1}} - }], { - writeConcern: {w:1}, ordered:true - }, function(err, results) { - assert.equal(null, err); - assert.equal(1, results.result.n); - - // Remove a document - _server.remove('myproject.inserts1', [{ - q: {a: 1}, limit: 1 - }], { - writeConcern: {w:1}, ordered:true - }, function(err, results) { - assert.equal(null, err); - assert.equal(1, results.result.n); - - // Get a document - var cursor = _server.cursor('integration_tests.inserts_example4', { - find: 'integration_tests.example4' - , query: {a:1} - }); - - // Get the first document - cursor.next(function(err, doc) { - assert.equal(null, err); - assert.equal(2, doc.a); - - // Execute the ismaster command - _server.command("system.$cmd" - , {ismaster: true}, function(err, result) { - assert.equal(null, err) - _server.destroy(); - }); - }); - }); - }); - - test.done(); - }); -}); - -server.on('close', function() { - console.log('closed'); -}); - -server.on('reconnect', function() { - console.log('reconnect'); -}); - -// Start connection -server.connect(); -``` - -The core driver does not contain any helpers or abstractions only the core crud operations. These consist of the following commands. - -* `insert`, Insert takes an array of 1 or more documents to be inserted against the topology and allows you to specify a write concern and if you wish to execute the inserts in order or out of order. -* `update`, Update takes an array of 1 or more update commands to be executed against the server topology and also allows you to specify a write concern and if you wish to execute the updates in order or out of order. -* `remove`, Remove takes an array of 1 or more remove commands to be executed against the server topology and also allows you to specify a write concern and if you wish to execute the removes in order or out of order. -* `cursor`, Returns you a cursor for either the 'virtual' `find` command, a command that returns a cursor id or a plain cursor id. Read the cursor tutorial for more inn depth coverage. -* `command`, Executes a command against MongoDB and returns the result. -* `auth`, Authenticates the current topology using a supported authentication scheme. - -The Core Driver is a building block for library builders and is not meant for usage by end users as it lacks a lot of features the end user might need such as automatic buffering of operations when a primary is changing in a replicaset or the db and collections abstraction. - -## Next steps - -The next step is to get more in depth information about how the different aspects of the core driver works and how to leverage them to extend the functionality of the cursors. Please view the tutorials for more detailed information. diff --git a/ts-ticket-office-service/node_modules/mongodb-core/TESTING.md b/ts-ticket-office-service/node_modules/mongodb-core/TESTING.md deleted file mode 100644 index fe03ea0f7..000000000 --- a/ts-ticket-office-service/node_modules/mongodb-core/TESTING.md +++ /dev/null @@ -1,18 +0,0 @@ -Testing setup -============= - -Single Server -------------- -mongod --dbpath=./db - -Replicaset ----------- -mongo --nodb -var x = new ReplSetTest({"useHostName":"false", "nodes" : {node0 : {}, node1 : {}, node2 : {}}}) -x.startSet(); -var config = x.getReplSetConfig() -x.initiate(config); - -Mongos ------- -var s = new ShardingTest( "auth1", 1 , 0 , 2 , {rs: true, noChunkSize : true}); \ No newline at end of file diff --git a/ts-ticket-office-service/node_modules/mongodb-core/THIRD-PARTY-NOTICES b/ts-ticket-office-service/node_modules/mongodb-core/THIRD-PARTY-NOTICES deleted file mode 100644 index c13e5d9a3..000000000 --- a/ts-ticket-office-service/node_modules/mongodb-core/THIRD-PARTY-NOTICES +++ /dev/null @@ -1,41 +0,0 @@ -Mongodb-core uses third-party libraries or other resources that may -be distributed under licenses different than the Mongodb-core software. - -In the event that we accidentally failed to list a required notice, -please bring it to our attention through any of the ways detailed here: - - mongodb-dev@googlegroups.com - -The attached notices are provided for information only. - -For any licenses that require disclosure of source, sources are available at -https://github.com/mongodb/node-mongodb-native. - -1) License Notice for nan.h ---------------------------- - -The MIT License (MIT) -===================== - -Copyright (c) 2016 NAN contributors ------------------------------------ - -NAN contributors listed at - -Permission is hereby granted, free of charge, to any person obtaining a copy of -this software and associated documentation files (the "Software"), to deal in -the Software without restriction, including without limitation the rights to -use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies -of the Software, and to permit persons to whom the Software is furnished to -do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in all -copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING -FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS -IN THE SOFTWARE. diff --git a/ts-ticket-office-service/node_modules/mongodb-core/conf.json b/ts-ticket-office-service/node_modules/mongodb-core/conf.json deleted file mode 100644 index 12ce4c7ad..000000000 --- a/ts-ticket-office-service/node_modules/mongodb-core/conf.json +++ /dev/null @@ -1,59 +0,0 @@ -{ - "plugins": ["plugins/markdown", "docs/lib/jsdoc/examples_plugin.js"], - "source": { - "include": [ - "test/tests/functional/operation_example_tests.js", - "lib/connection/command_result.js", - "lib/topologies/mongos.js", - "lib/topologies/read_preference.js", - "lib/topologies/replset.js", - "lib/topologies/server.js", - "lib/topologies/replset_state.js", - "lib/connection/logger.js", - "lib/connection/connection.js", - "lib/cursor.js", - "lib/error.js", - "node_modules/bson/lib/bson/binary.js", - "node_modules/bson/lib/bson/code.js", - "node_modules/bson/lib/bson/db_ref.js", - "node_modules/bson/lib/bson/double.js", - "node_modules/bson/lib/bson/long.js", - "node_modules/bson/lib/bson/objectid.js", - "node_modules/bson/lib/bson/symbol.js", - "node_modules/bson/lib/bson/timestamp.js", - "node_modules/bson/lib/bson/max_key.js", - "node_modules/bson/lib/bson/min_key.js" - ] - }, - "templates": { - "cleverLinks": true, - "monospaceLinks": true, - "default": { - "outputSourceFiles" : true - }, - "applicationName": "Node.js MongoDB Driver API", - "disqus": true, - "googleAnalytics": "UA-29229787-1", - "openGraph": { - "title": "", - "type": "website", - "image": "", - "site_name": "", - "url": "" - }, - "meta": { - "title": "", - "description": "", - "keyword": "" - }, - "linenums": true - }, - "markdown": { - "parser": "gfm", - "hardwrap": true, - "tags": ["examples"] - }, - "examples": { - "indent": 4 - } -} diff --git a/ts-ticket-office-service/node_modules/mongodb-core/index.js b/ts-ticket-office-service/node_modules/mongodb-core/index.js deleted file mode 100644 index 4a63acc65..000000000 --- a/ts-ticket-office-service/node_modules/mongodb-core/index.js +++ /dev/null @@ -1,32 +0,0 @@ -var BSON = require('bson'); -var require_optional = require('require_optional'); - -try { - // Attempt to grab the native BSON parser - var BSONNative = require_optional('bson-ext'); - // If we got the native parser, use it instead of the - // Javascript one - if(BSONNative) { - BSON = BSONNative - } -} catch(err) {} - -module.exports = { - MongoError: require('./lib/error') - , Connection: require('./lib/connection/connection') - , Server: require('./lib/topologies/server') - , ReplSet: require('./lib/topologies/replset') - , Mongos: require('./lib/topologies/mongos') - , Logger: require('./lib/connection/logger') - , Cursor: require('./lib/cursor') - , ReadPreference: require('./lib/topologies/read_preference') - , BSON: BSON - // Raw operations - , Query: require('./lib/connection/commands').Query - // Auth mechanisms - , MongoCR: require('./lib/auth/mongocr') - , X509: require('./lib/auth/x509') - , Plain: require('./lib/auth/plain') - , GSSAPI: require('./lib/auth/gssapi') - , ScramSHA1: require('./lib/auth/scram') -} diff --git a/ts-ticket-office-service/node_modules/mongodb-core/lib/auth/gssapi.js b/ts-ticket-office-service/node_modules/mongodb-core/lib/auth/gssapi.js deleted file mode 100644 index 7fe30265f..000000000 --- a/ts-ticket-office-service/node_modules/mongodb-core/lib/auth/gssapi.js +++ /dev/null @@ -1,262 +0,0 @@ -"use strict"; - -var f = require('util').format - , require_optional = require('require_optional') - , Query = require('../connection/commands').Query - , MongoError = require('../error'); - -var AuthSession = function(db, username, password, options) { - this.db = db; - this.username = username; - this.password = password; - this.options = options; -} - -AuthSession.prototype.equal = function(session) { - return session.db == this.db - && session.username == this.username - && session.password == this.password; -} - -// Kerberos class -var Kerberos = null; -var MongoAuthProcess = null; - -// Try to grab the Kerberos class -try { - Kerberos = require_optional('kerberos').Kerberos; - // Authentication process for Mongo - MongoAuthProcess = require_optional('kerberos').processes.MongoAuthProcess; -} catch(err) { -} - -/** - * Creates a new GSSAPI authentication mechanism - * @class - * @return {GSSAPI} A cursor instance - */ -var GSSAPI = function(bson) { - this.bson = bson; - this.authStore = []; -} - -/** - * Authenticate - * @method - * @param {{Server}|{ReplSet}|{Mongos}} server Topology the authentication method is being called on - * @param {[]Connections} connections Connections to authenticate using this authenticator - * @param {string} db Name of the database - * @param {string} username Username - * @param {string} password Password - * @param {authResultCallback} callback The callback to return the result from the authentication - * @return {object} - */ -GSSAPI.prototype.auth = function(server, connections, db, username, password, options, callback) { - var self = this; - // We don't have the Kerberos library - if(Kerberos == null) return callback(new Error("Kerberos library is not installed")); - var gssapiServiceName = options['gssapiServiceName'] || 'mongodb'; - // Total connections - var count = connections.length; - if(count == 0) return callback(null, null); - - // Valid connections - var numberOfValidConnections = 0; - var errorObject = null; - - // For each connection we need to authenticate - while(connections.length > 0) { - // Execute MongoCR - var execute = function(connection) { - // Start Auth process for a connection - GSSAPIInitialize(self, db, username, password, db, gssapiServiceName, server, connection, options, function(err, r) { - // Adjust count - count = count - 1; - - // If we have an error - if(err) { - errorObject = err; - } else if(r.result['$err']) { - errorObject = r.result; - } else if(r.result['errmsg']) { - errorObject = r.result; - } else { - numberOfValidConnections = numberOfValidConnections + 1; - } - - // We have authenticated all connections - if(count == 0 && numberOfValidConnections > 0) { - // Store the auth details - addAuthSession(self.authStore, new AuthSession(db, username, password, options)); - // Return correct authentication - callback(null, true); - } else if(count == 0) { - if(errorObject == null) errorObject = new MongoError(f("failed to authenticate using mongocr")); - callback(errorObject, false); - } - }); - } - - var _execute = function(_connection) { - process.nextTick(function() { - execute(_connection); - }); - } - - _execute(connections.shift()); - } -} - -// -// Initialize step -var GSSAPIInitialize = function(self, db, username, password, authdb, gssapiServiceName, server, connection, options, callback) { - // Create authenticator - var mongo_auth_process = new MongoAuthProcess(connection.host, connection.port, gssapiServiceName, options); - - // Perform initialization - mongo_auth_process.init(username, password, function(err) { - if(err) return callback(err, false); - - // Perform the first step - mongo_auth_process.transition('', function(err, payload) { - if(err) return callback(err, false); - - // Call the next db step - MongoDBGSSAPIFirstStep(self, mongo_auth_process, payload, db, username, password, authdb, server, connection, callback); - }); - }); -} - -// -// Perform first step against mongodb -var MongoDBGSSAPIFirstStep = function(self, mongo_auth_process, payload, db, username, password, authdb, server, connection, callback) { - // Build the sasl start command - var command = { - saslStart: 1 - , mechanism: 'GSSAPI' - , payload: payload - , autoAuthorize: 1 - }; - - // Write the commmand on the connection - server(connection, new Query(self.bson, "$external.$cmd", command, { - numberToSkip: 0, numberToReturn: 1 - }), function(err, r) { - if(err) return callback(err, false); - var doc = r.result; - // Execute mongodb transition - mongo_auth_process.transition(r.result.payload, function(err, payload) { - if(err) return callback(err, false); - - // MongoDB API Second Step - MongoDBGSSAPISecondStep(self, mongo_auth_process, payload, doc, db, username, password, authdb, server, connection, callback); - }); - }); -} - -// -// Perform first step against mongodb -var MongoDBGSSAPISecondStep = function(self, mongo_auth_process, payload, doc, db, username, password, authdb, server, connection, callback) { - // Build Authentication command to send to MongoDB - var command = { - saslContinue: 1 - , conversationId: doc.conversationId - , payload: payload - }; - - // Execute the command - // Write the commmand on the connection - server(connection, new Query(self.bson, "$external.$cmd", command, { - numberToSkip: 0, numberToReturn: 1 - }), function(err, r) { - if(err) return callback(err, false); - var doc = r.result; - // Call next transition for kerberos - mongo_auth_process.transition(doc.payload, function(err, payload) { - if(err) return callback(err, false); - - // Call the last and third step - MongoDBGSSAPIThirdStep(self, mongo_auth_process, payload, doc, db, username, password, authdb, server, connection, callback); - }); - }); -} - -var MongoDBGSSAPIThirdStep = function(self, mongo_auth_process, payload, doc, db, username, password, authdb, server, connection, callback) { - // Build final command - var command = { - saslContinue: 1 - , conversationId: doc.conversationId - , payload: payload - }; - - // Execute the command - server(connection, new Query(self.bson, "$external.$cmd", command, { - numberToSkip: 0, numberToReturn: 1 - }), function(err, r) { - if(err) return callback(err, false); - mongo_auth_process.transition(null, function(err) { - if(err) return callback(err, null); - callback(null, r); - }); - }); -} - -// Add to store only if it does not exist -var addAuthSession = function(authStore, session) { - var found = false; - - for(var i = 0; i < authStore.length; i++) { - if(authStore[i].equal(session)) { - found = true; - break; - } - } - - if(!found) authStore.push(session); -} - -/** - * Remove authStore credentials - * @method - * @param {string} db Name of database we are removing authStore details about - * @return {object} - */ -GSSAPI.prototype.logout = function(dbName) { - this.authStore = this.authStore.filter(function(x) { - return x.db != dbName; - }); -} - -/** - * Re authenticate pool - * @method - * @param {{Server}|{ReplSet}|{Mongos}} server Topology the authentication method is being called on - * @param {[]Connections} connections Connections to authenticate using this authenticator - * @param {authResultCallback} callback The callback to return the result from the authentication - * @return {object} - */ -GSSAPI.prototype.reauthenticate = function(server, connections, callback) { - var authStore = this.authStore.slice(0); - var count = authStore.length; - if(count == 0) return callback(null, null); - // Iterate over all the auth details stored - for(var i = 0; i < authStore.length; i++) { - this.auth(server, connections, authStore[i].db, authStore[i].username, authStore[i].password, authStore[i].options, function(err) { - count = count - 1; - // Done re-authenticating - if(count == 0) { - callback(err, null); - } - }); - } -} - -/** - * This is a result from a authentication strategy - * - * @callback authResultCallback - * @param {error} error An error object. Set to null if no error present - * @param {boolean} result The result of the authentication process - */ - -module.exports = GSSAPI; diff --git a/ts-ticket-office-service/node_modules/mongodb-core/lib/auth/mongocr.js b/ts-ticket-office-service/node_modules/mongodb-core/lib/auth/mongocr.js deleted file mode 100644 index 14e3c4d0b..000000000 --- a/ts-ticket-office-service/node_modules/mongodb-core/lib/auth/mongocr.js +++ /dev/null @@ -1,181 +0,0 @@ -"use strict"; - -var f = require('util').format - , crypto = require('crypto') - , Query = require('../connection/commands').Query - , MongoError = require('../error'); - -var AuthSession = function(db, username, password) { - this.db = db; - this.username = username; - this.password = password; -} - -AuthSession.prototype.equal = function(session) { - return session.db == this.db - && session.username == this.username - && session.password == this.password; -} - -/** - * Creates a new MongoCR authentication mechanism - * @class - * @return {MongoCR} A cursor instance - */ -var MongoCR = function(bson) { - this.bson = bson; - this.authStore = []; -} - -// Add to store only if it does not exist -var addAuthSession = function(authStore, session) { - var found = false; - - for(var i = 0; i < authStore.length; i++) { - if(authStore[i].equal(session)) { - found = true; - break; - } - } - - if(!found) authStore.push(session); -} - -/** - * Authenticate - * @method - * @param {{Server}|{ReplSet}|{Mongos}} server Topology the authentication method is being called on - * @param {[]Connections} connections Connections to authenticate using this authenticator - * @param {string} db Name of the database - * @param {string} username Username - * @param {string} password Password - * @param {authResultCallback} callback The callback to return the result from the authentication - * @return {object} - */ -MongoCR.prototype.auth = function(server, connections, db, username, password, callback) { - var self = this; - // Total connections - var count = connections.length; - if(count == 0) return callback(null, null); - - // Valid connections - var numberOfValidConnections = 0; - var errorObject = null; - - // For each connection we need to authenticate - while(connections.length > 0) { - // Execute MongoCR - var executeMongoCR = function(connection) { - // Write the commmand on the connection - server(connection, new Query(self.bson, f("%s.$cmd", db), { - getnonce:1 - }, { - numberToSkip: 0, numberToReturn: 1 - }), function(err, r) { - var nonce = null; - var key = null; - - // Adjust the number of connections left - // Get nonce - if(err == null) { - nonce = r.result.nonce; - // Use node md5 generator - var md5 = crypto.createHash('md5'); - // Generate keys used for authentication - md5.update(username + ":mongo:" + password, 'utf8'); - var hash_password = md5.digest('hex'); - // Final key - md5 = crypto.createHash('md5'); - md5.update(nonce + username + hash_password, 'utf8'); - key = md5.digest('hex'); - } - - // Execute command - // Write the commmand on the connection - server(connection, new Query(self.bson, f("%s.$cmd", db), { - authenticate: 1, user: username, nonce: nonce, key:key - }, { - numberToSkip: 0, numberToReturn: 1 - }), function(err, r) { - count = count - 1; - - // If we have an error - if(err) { - errorObject = err; - } else if(r.result['$err']) { - errorObject = r.result; - } else if(r.result['errmsg']) { - errorObject = r.result; - } else { - numberOfValidConnections = numberOfValidConnections + 1; - } - - // We have authenticated all connections - if(count == 0 && numberOfValidConnections > 0) { - // Store the auth details - addAuthSession(self.authStore, new AuthSession(db, username, password)); - // Return correct authentication - callback(null, true); - } else if(count == 0) { - if(errorObject == null) errorObject = new MongoError(f("failed to authenticate using mongocr")); - callback(errorObject, false); - } - }); - }); - } - - var _execute = function(_connection) { - process.nextTick(function() { - executeMongoCR(_connection); - }); - } - - _execute(connections.shift()); - } -} - -/** - * Remove authStore credentials - * @method - * @param {string} db Name of database we are removing authStore details about - * @return {object} - */ -MongoCR.prototype.logout = function(dbName) { - this.authStore = this.authStore.filter(function(x) { - return x.db != dbName; - }); -} - -/** - * Re authenticate pool - * @method - * @param {{Server}|{ReplSet}|{Mongos}} server Topology the authentication method is being called on - * @param {[]Connections} connections Connections to authenticate using this authenticator - * @param {authResultCallback} callback The callback to return the result from the authentication - * @return {object} - */ -MongoCR.prototype.reauthenticate = function(server, connections, callback) { - var authStore = this.authStore.slice(0); - var count = authStore.length; - if(count == 0) return callback(null, null); - // Iterate over all the auth details stored - for(var i = 0; i < authStore.length; i++) { - this.auth(server, connections, authStore[i].db, authStore[i].username, authStore[i].password, function(err) { - count = count - 1; - // Done re-authenticating - if(count == 0) { - callback(err, null); - } - }); - } -} - -/** - * This is a result from a authentication strategy - * - * @callback authResultCallback - * @param {error} error An error object. Set to null if no error present - * @param {boolean} result The result of the authentication process - */ - -module.exports = MongoCR; diff --git a/ts-ticket-office-service/node_modules/mongodb-core/lib/auth/plain.js b/ts-ticket-office-service/node_modules/mongodb-core/lib/auth/plain.js deleted file mode 100644 index e3fb1a8f7..000000000 --- a/ts-ticket-office-service/node_modules/mongodb-core/lib/auth/plain.js +++ /dev/null @@ -1,170 +0,0 @@ -"use strict"; - -var BSON = require('bson'); - -var f = require('util').format - , Binary = BSON.Binary - , retrieveBSON = require('../connection/utils').retrieveBSON - , Query = require('../connection/commands').Query - , MongoError = require('../error'); - -var BSON = retrieveBSON(); - -var AuthSession = function(db, username, password) { - this.db = db; - this.username = username; - this.password = password; -} - -AuthSession.prototype.equal = function(session) { - return session.db == this.db - && session.username == this.username - && session.password == this.password; -} - -/** - * Creates a new Plain authentication mechanism - * @class - * @return {Plain} A cursor instance - */ -var Plain = function(bson) { - this.bson = bson; - this.authStore = []; -} - -/** - * Authenticate - * @method - * @param {{Server}|{ReplSet}|{Mongos}} server Topology the authentication method is being called on - * @param {[]Connections} connections Connections to authenticate using this authenticator - * @param {string} db Name of the database - * @param {string} username Username - * @param {string} password Password - * @param {authResultCallback} callback The callback to return the result from the authentication - * @return {object} - */ -Plain.prototype.auth = function(server, connections, db, username, password, callback) { - var self = this; - // Total connections - var count = connections.length; - if(count == 0) return callback(null, null); - - // Valid connections - var numberOfValidConnections = 0; - var errorObject = null; - - // For each connection we need to authenticate - while(connections.length > 0) { - // Execute MongoCR - var execute = function(connection) { - // Create payload - var payload = new Binary(f("\x00%s\x00%s", username, password)); - - // Let's start the sasl process - var command = { - saslStart: 1 - , mechanism: 'PLAIN' - , payload: payload - , autoAuthorize: 1 - }; - - // Let's start the process - server(connection, new Query(self.bson, "$external.$cmd", command, { - numberToSkip: 0, numberToReturn: 1 - }), function(err, r) { - // Adjust count - count = count - 1; - - // If we have an error - if(err) { - errorObject = err; - } else if(r.result['$err']) { - errorObject = r.result; - } else if(r.result['errmsg']) { - errorObject = r.result; - } else { - numberOfValidConnections = numberOfValidConnections + 1; - } - - // We have authenticated all connections - if(count == 0 && numberOfValidConnections > 0) { - // Store the auth details - addAuthSession(self.authStore, new AuthSession(db, username, password)); - // Return correct authentication - callback(null, true); - } else if(count == 0) { - if(errorObject == null) errorObject = new MongoError(f("failed to authenticate using mongocr")); - callback(errorObject, false); - } - }); - } - - var _execute = function(_connection) { - process.nextTick(function() { - execute(_connection); - }); - } - - _execute(connections.shift()); - } -} - -// Add to store only if it does not exist -var addAuthSession = function(authStore, session) { - var found = false; - - for(var i = 0; i < authStore.length; i++) { - if(authStore[i].equal(session)) { - found = true; - break; - } - } - - if(!found) authStore.push(session); -} - -/** - * Remove authStore credentials - * @method - * @param {string} db Name of database we are removing authStore details about - * @return {object} - */ -Plain.prototype.logout = function(dbName) { - this.authStore = this.authStore.filter(function(x) { - return x.db != dbName; - }); -} - -/** - * Re authenticate pool - * @method - * @param {{Server}|{ReplSet}|{Mongos}} server Topology the authentication method is being called on - * @param {[]Connections} connections Connections to authenticate using this authenticator - * @param {authResultCallback} callback The callback to return the result from the authentication - * @return {object} - */ -Plain.prototype.reauthenticate = function(server, connections, callback) { - var authStore = this.authStore.slice(0); - var count = authStore.length; - if(count == 0) return callback(null, null); - // Iterate over all the auth details stored - for(var i = 0; i < authStore.length; i++) { - this.auth(server, connections, authStore[i].db, authStore[i].username, authStore[i].password, function(err) { - count = count - 1; - // Done re-authenticating - if(count == 0) { - callback(err, null); - } - }); - } -} - -/** - * This is a result from a authentication strategy - * - * @callback authResultCallback - * @param {error} error An error object. Set to null if no error present - * @param {boolean} result The result of the authentication process - */ - -module.exports = Plain; diff --git a/ts-ticket-office-service/node_modules/mongodb-core/lib/auth/scram.js b/ts-ticket-office-service/node_modules/mongodb-core/lib/auth/scram.js deleted file mode 100644 index a02a159af..000000000 --- a/ts-ticket-office-service/node_modules/mongodb-core/lib/auth/scram.js +++ /dev/null @@ -1,339 +0,0 @@ -"use strict"; - -var f = require('util').format - , crypto = require('crypto') - , retrieveBSON = require('../connection/utils').retrieveBSON - , Query = require('../connection/commands').Query - , MongoError = require('../error'); - -var BSON = retrieveBSON(), - Binary = BSON.Binary; - -var AuthSession = function(db, username, password) { - this.db = db; - this.username = username; - this.password = password; -} - -AuthSession.prototype.equal = function(session) { - return session.db == this.db - && session.username == this.username - && session.password == this.password; -} - -var id = 0; - -/** - * Creates a new ScramSHA1 authentication mechanism - * @class - * @return {ScramSHA1} A cursor instance - */ -var ScramSHA1 = function(bson) { - this.bson = bson; - this.authStore = []; - this.id = id++; -} - -var parsePayload = function(payload) { - var dict = {}; - var parts = payload.split(','); - - for(var i = 0; i < parts.length; i++) { - var valueParts = parts[i].split('='); - dict[valueParts[0]] = valueParts[1]; - } - - return dict; -} - -var passwordDigest = function(username, password) { - if(typeof username != 'string') throw new MongoError("username must be a string"); - if(typeof password != 'string') throw new MongoError("password must be a string"); - if(password.length == 0) throw new MongoError("password cannot be empty"); - // Use node md5 generator - var md5 = crypto.createHash('md5'); - // Generate keys used for authentication - md5.update(username + ":mongo:" + password, 'utf8'); - return md5.digest('hex'); -} - -// XOR two buffers -var xor = function(a, b) { - if (!Buffer.isBuffer(a)) a = new Buffer(a) - if (!Buffer.isBuffer(b)) b = new Buffer(b) - var res = [] - if (a.length > b.length) { - for (var i = 0; i < b.length; i++) { - res.push(a[i] ^ b[i]) - } - } else { - for (i = 0; i < a.length; i++) { - res.push(a[i] ^ b[i]) - } - } - return new Buffer(res); -} - -var _hiCache = {}; -var _hiCacheCount = 0; -var _hiCachePurge = function() { - _hiCache = {}; - _hiCacheCount = 0; -}; - -var hi = function(data, salt, iterations) { - // omit the work if already generated - var key = [data, salt.toString('base64'), iterations].join('_'); - if (_hiCache[key] !== undefined) { - return _hiCache[key]; - } - - // generate the salt - var saltedData = crypto.pbkdf2Sync(data, salt, iterations, 20, "sha1"); - - // cache a copy to speed up the next lookup, but prevent unbounded cache growth - if (_hiCacheCount >= 200) { - _hiCachePurge(); - } - - _hiCache[key] = saltedData; - _hiCacheCount += 1; - return saltedData; -}; - -/** - * Authenticate - * @method - * @param {{Server}|{ReplSet}|{Mongos}} server Topology the authentication method is being called on - * @param {[]Connections} connections Connections to authenticate using this authenticator - * @param {string} db Name of the database - * @param {string} username Username - * @param {string} password Password - * @param {authResultCallback} callback The callback to return the result from the authentication - * @return {object} - */ -ScramSHA1.prototype.auth = function(server, connections, db, username, password, callback) { - var self = this; - // Total connections - var count = connections.length; - if(count == 0) return callback(null, null); - - // Valid connections - var numberOfValidConnections = 0; - var errorObject = null; - - // Execute MongoCR - var executeScram = function(connection) { - // Clean up the user - username = username.replace('=', "=3D").replace(',', '=2C'); - - // Create a random nonce - var nonce = crypto.randomBytes(24).toString('base64'); - // var nonce = 'MsQUY9iw0T9fx2MUEz6LZPwGuhVvWAhc' - var firstBare = f("n=%s,r=%s", username, nonce); - - // Build command structure - var cmd = { - saslStart: 1 - , mechanism: 'SCRAM-SHA-1' - , payload: new Binary(f("n,,%s", firstBare)) - , autoAuthorize: 1 - } - - // Handle the error - var handleError = function(err, r) { - if(err) { - numberOfValidConnections = numberOfValidConnections - 1; - errorObject = err; return false; - } else if(r.result['$err']) { - errorObject = r.result; return false; - } else if(r.result['errmsg']) { - errorObject = r.result; return false; - } else { - numberOfValidConnections = numberOfValidConnections + 1; - } - - return true - } - - // Finish up - var finish = function(_count, _numberOfValidConnections) { - if(_count == 0 && _numberOfValidConnections > 0) { - // Store the auth details - addAuthSession(self.authStore, new AuthSession(db, username, password)); - // Return correct authentication - return callback(null, true); - } else if(_count == 0) { - if(errorObject == null) errorObject = new MongoError(f("failed to authenticate using scram")); - return callback(errorObject, false); - } - } - - var handleEnd = function(_err, _r) { - // Handle any error - handleError(_err, _r) - // Adjust the number of connections - count = count - 1; - // Execute the finish - finish(count, numberOfValidConnections); - } - - // Write the commmand on the connection - server(connection, new Query(self.bson, f("%s.$cmd", db), cmd, { - numberToSkip: 0, numberToReturn: 1 - }), function(err, r) { - // Do we have an error, handle it - if(handleError(err, r) == false) { - count = count - 1; - - if(count == 0 && numberOfValidConnections > 0) { - // Store the auth details - addAuthSession(self.authStore, new AuthSession(db, username, password)); - // Return correct authentication - return callback(null, true); - } else if(count == 0) { - if(errorObject == null) errorObject = new MongoError(f("failed to authenticate using scram")); - return callback(errorObject, false); - } - - return; - } - - // Get the dictionary - var dict = parsePayload(r.result.payload.value()) - - // Unpack dictionary - var iterations = parseInt(dict.i, 10); - var salt = dict.s; - var rnonce = dict.r; - - // Set up start of proof - var withoutProof = f("c=biws,r=%s", rnonce); - var passwordDig = passwordDigest(username, password); - var saltedPassword = hi(passwordDig - , new Buffer(salt, 'base64') - , iterations); - - // Create the client key - var hmac = crypto.createHmac('sha1', saltedPassword); - hmac.update(new Buffer("Client Key")); - var clientKey = new Buffer(hmac.digest('base64'), 'base64'); - - // Create the stored key - var hash = crypto.createHash('sha1'); - hash.update(clientKey); - var storedKey = new Buffer(hash.digest('base64'), 'base64'); - - // Create the authentication message - var authMsg = [firstBare, r.result.payload.value().toString('base64'), withoutProof].join(','); - - // Create client signature - hmac = crypto.createHmac('sha1', storedKey); - hmac.update(new Buffer(authMsg)); - var clientSig = new Buffer(hmac.digest('base64'), 'base64'); - - // Create client proof - var clientProof = f("p=%s", new Buffer(xor(clientKey, clientSig)).toString('base64')); - - // Create client final - var clientFinal = [withoutProof, clientProof].join(','); - - // - // Create continue message - var cmd = { - saslContinue: 1 - , conversationId: r.result.conversationId - , payload: new Binary(new Buffer(clientFinal)) - } - - // - // Execute sasl continue - // Write the commmand on the connection - server(connection, new Query(self.bson, f("%s.$cmd", db), cmd, { - numberToSkip: 0, numberToReturn: 1 - }), function(err, r) { - if(r && r.result.done == false) { - var cmd = { - saslContinue: 1 - , conversationId: r.result.conversationId - , payload: new Buffer(0) - } - - // Write the commmand on the connection - server(connection, new Query(self.bson, f("%s.$cmd", db), cmd, { - numberToSkip: 0, numberToReturn: 1 - }), function(err, r) { - handleEnd(err, r); - }); - } else { - handleEnd(err, r); - } - }); - }); - } - - var _execute = function(_connection) { - process.nextTick(function() { - executeScram(_connection); - }); - } - - // For each connection we need to authenticate - while(connections.length > 0) { - _execute(connections.shift()); - } -} - -// Add to store only if it does not exist -var addAuthSession = function(authStore, session) { - var found = false; - - for(var i = 0; i < authStore.length; i++) { - if(authStore[i].equal(session)) { - found = true; - break; - } - } - - if(!found) authStore.push(session); -} - -/** - * Remove authStore credentials - * @method - * @param {string} db Name of database we are removing authStore details about - * @return {object} - */ -ScramSHA1.prototype.logout = function(dbName) { - this.authStore = this.authStore.filter(function(x) { - return x.db != dbName; - }); -} - -/** - * Re authenticate pool - * @method - * @param {{Server}|{ReplSet}|{Mongos}} server Topology the authentication method is being called on - * @param {[]Connections} connections Connections to authenticate using this authenticator - * @param {authResultCallback} callback The callback to return the result from the authentication - * @return {object} - */ -ScramSHA1.prototype.reauthenticate = function(server, connections, callback) { - var authStore = this.authStore.slice(0); - var count = authStore.length; - // No connections - if(count == 0) return callback(null, null); - // Iterate over all the auth details stored - for(var i = 0; i < authStore.length; i++) { - this.auth(server, connections, authStore[i].db, authStore[i].username, authStore[i].password, function(err) { - count = count - 1; - // Done re-authenticating - if(count == 0) { - callback(err, null); - } - }); - } -} - - -module.exports = ScramSHA1; diff --git a/ts-ticket-office-service/node_modules/mongodb-core/lib/auth/sspi.js b/ts-ticket-office-service/node_modules/mongodb-core/lib/auth/sspi.js deleted file mode 100644 index ef4874c3e..000000000 --- a/ts-ticket-office-service/node_modules/mongodb-core/lib/auth/sspi.js +++ /dev/null @@ -1,250 +0,0 @@ -"use strict"; - -var f = require('util').format - , require_optional = require('require_optional') - , Query = require('../connection/commands').Query - , MongoError = require('../error'); - -var AuthSession = function(db, username, password, options) { - this.db = db; - this.username = username; - this.password = password; - this.options = options; -} - -AuthSession.prototype.equal = function(session) { - return session.db == this.db - && session.username == this.username - && session.password == this.password; -} - -// Kerberos class -var Kerberos = null; -var MongoAuthProcess = null; - -// Try to grab the Kerberos class -try { - Kerberos = require_optional('kerberos').Kerberos - // Authentication process for Mongo - MongoAuthProcess = require_optional('kerberos').processes.MongoAuthProcess -} catch(err) {} - -/** - * Creates a new SSPI authentication mechanism - * @class - * @return {SSPI} A cursor instance - */ -var SSPI = function(bson) { - this.bson = bson; - this.authStore = []; -} - -/** - * Authenticate - * @method - * @param {{Server}|{ReplSet}|{Mongos}} server Topology the authentication method is being called on - * @param {[]Connections} connections Connections to authenticate using this authenticator - * @param {string} db Name of the database - * @param {string} username Username - * @param {string} password Password - * @param {authResultCallback} callback The callback to return the result from the authentication - * @return {object} - */ -SSPI.prototype.auth = function(server, connections, db, username, password, options, callback) { - var self = this; - // We don't have the Kerberos library - if(Kerberos == null) return callback(new Error("Kerberos library is not installed")); - var gssapiServiceName = options['gssapiServiceName'] || 'mongodb'; - // Total connections - var count = connections.length; - if(count == 0) return callback(null, null); - - // Valid connections - var numberOfValidConnections = 0; - var errorObject = null; - - // For each connection we need to authenticate - while(connections.length > 0) { - // Execute MongoCR - var execute = function(connection) { - // Start Auth process for a connection - SSIPAuthenticate(self, username, password, gssapiServiceName, server, connection, options, function(err, r) { - // Adjust count - count = count - 1; - - // If we have an error - if(err) { - errorObject = err; - } else if(r && typeof r == 'object' && r.result['$err']) { - errorObject = r.result; - } else if(r && typeof r == 'object' && r.result['errmsg']) { - errorObject = r.result; - } else { - numberOfValidConnections = numberOfValidConnections + 1; - } - - // We have authenticated all connections - if(count == 0 && numberOfValidConnections > 0) { - // Store the auth details - addAuthSession(self.authStore, new AuthSession(db, username, password, options)); - // Return correct authentication - callback(null, true); - } else if(count == 0) { - if(errorObject == null) errorObject = new MongoError(f("failed to authenticate using mongocr")); - callback(errorObject, false); - } - }); - } - - var _execute = function(_connection) { - process.nextTick(function() { - execute(_connection); - }); - } - - _execute(connections.shift()); - } -} - -var SSIPAuthenticate = function(self, username, password, gssapiServiceName, server, connection, options, callback) { - // Build Authentication command to send to MongoDB - var command = { - saslStart: 1 - , mechanism: 'GSSAPI' - , payload: '' - , autoAuthorize: 1 - }; - - // Create authenticator - var mongo_auth_process = new MongoAuthProcess(connection.host, connection.port, gssapiServiceName, options); - - // Execute first sasl step - server(connection, new Query(self.bson, "$external.$cmd", command, { - numberToSkip: 0, numberToReturn: 1 - }), function(err, r) { - if(err) return callback(err, false); - var doc = r.result; - - mongo_auth_process.init(username, password, function(err) { - if(err) return callback(err); - - mongo_auth_process.transition(doc.payload, function(err, payload) { - if(err) return callback(err); - - // Perform the next step against mongod - var command = { - saslContinue: 1 - , conversationId: doc.conversationId - , payload: payload - }; - - // Execute the command - server(connection, new Query(self.bson, "$external.$cmd", command, { - numberToSkip: 0, numberToReturn: 1 - }), function(err, r) { - if(err) return callback(err, false); - var doc = r.result; - - mongo_auth_process.transition(doc.payload, function(err, payload) { - if(err) return callback(err); - - // Perform the next step against mongod - var command = { - saslContinue: 1 - , conversationId: doc.conversationId - , payload: payload - }; - - // Execute the command - server(connection, new Query(self.bson, "$external.$cmd", command, { - numberToSkip: 0, numberToReturn: 1 - }), function(err, r) { - if(err) return callback(err, false); - var doc = r.result; - - mongo_auth_process.transition(doc.payload, function(err, payload) { - // Perform the next step against mongod - var command = { - saslContinue: 1 - , conversationId: doc.conversationId - , payload: payload - }; - - // Execute the command - server(connection, new Query(self.bson, "$external.$cmd", command, { - numberToSkip: 0, numberToReturn: 1 - }), function(err, r) { - if(err) return callback(err, false); - var doc = r.result; - - if(doc.done) return callback(null, true); - callback(new Error("Authentication failed"), false); - }); - }); - }); - }); - }); - }); - }); - }); -} - -// Add to store only if it does not exist -var addAuthSession = function(authStore, session) { - var found = false; - - for(var i = 0; i < authStore.length; i++) { - if(authStore[i].equal(session)) { - found = true; - break; - } - } - - if(!found) authStore.push(session); -} - -/** - * Remove authStore credentials - * @method - * @param {string} db Name of database we are removing authStore details about - * @return {object} - */ -SSPI.prototype.logout = function(dbName) { - this.authStore = this.authStore.filter(function(x) { - return x.db != dbName; - }); -} - -/** - * Re authenticate pool - * @method - * @param {{Server}|{ReplSet}|{Mongos}} server Topology the authentication method is being called on - * @param {[]Connections} connections Connections to authenticate using this authenticator - * @param {authResultCallback} callback The callback to return the result from the authentication - * @return {object} - */ -SSPI.prototype.reauthenticate = function(server, connections, callback) { - var authStore = this.authStore.slice(0); - var count = authStore.length; - if(count == 0) return callback(null, null); - // Iterate over all the auth details stored - for(var i = 0; i < authStore.length; i++) { - this.auth(server, connections, authStore[i].db, authStore[i].username, authStore[i].password, authStore[i].options, function(err) { - count = count - 1; - // Done re-authenticating - if(count == 0) { - callback(err, null); - } - }); - } -} - -/** - * This is a result from a authentication strategy - * - * @callback authResultCallback - * @param {error} error An error object. Set to null if no error present - * @param {boolean} result The result of the authentication process - */ - -module.exports = SSPI; diff --git a/ts-ticket-office-service/node_modules/mongodb-core/lib/auth/x509.js b/ts-ticket-office-service/node_modules/mongodb-core/lib/auth/x509.js deleted file mode 100644 index 0b75d7978..000000000 --- a/ts-ticket-office-service/node_modules/mongodb-core/lib/auth/x509.js +++ /dev/null @@ -1,164 +0,0 @@ -"use strict"; - -var f = require('util').format - , Query = require('../connection/commands').Query - , MongoError = require('../error'); - -var AuthSession = function(db, username, password) { - this.db = db; - this.username = username; - this.password = password; -} - -AuthSession.prototype.equal = function(session) { - return session.db == this.db - && session.username == this.username - && session.password == this.password; -} - -/** - * Creates a new X509 authentication mechanism - * @class - * @return {X509} A cursor instance - */ -var X509 = function(bson) { - this.bson = bson; - this.authStore = []; -} - -/** - * Authenticate - * @method - * @param {{Server}|{ReplSet}|{Mongos}} server Topology the authentication method is being called on - * @param {[]Connections} connections Connections to authenticate using this authenticator - * @param {string} db Name of the database - * @param {string} username Username - * @param {string} password Password - * @param {authResultCallback} callback The callback to return the result from the authentication - * @return {object} - */ -X509.prototype.auth = function(server, connections, db, username, password, callback) { - var self = this; - // Total connections - var count = connections.length; - if(count == 0) return callback(null, null); - - // Valid connections - var numberOfValidConnections = 0; - var errorObject = null; - - // For each connection we need to authenticate - while(connections.length > 0) { - // Execute MongoCR - var execute = function(connection) { - // Let's start the sasl process - var command = { - authenticate: 1 - , mechanism: 'MONGODB-X509' - }; - - // Add username if specified - if(username) { - command.user = username; - } - - // Let's start the process - server(connection, new Query(self.bson, "$external.$cmd", command, { - numberToSkip: 0, numberToReturn: 1 - }), function(err, r) { - // Adjust count - count = count - 1; - - // If we have an error - if(err) { - errorObject = err; - } else if(r.result['$err']) { - errorObject = r.result; - } else if(r.result['errmsg']) { - errorObject = r.result; - } else { - numberOfValidConnections = numberOfValidConnections + 1; - } - - // We have authenticated all connections - if(count == 0 && numberOfValidConnections > 0) { - // Store the auth details - addAuthSession(self.authStore, new AuthSession(db, username, password)); - // Return correct authentication - callback(null, true); - } else if(count == 0) { - if(errorObject == null) errorObject = new MongoError(f("failed to authenticate using mongocr")); - callback(errorObject, false); - } - }); - } - - var _execute = function(_connection) { - process.nextTick(function() { - execute(_connection); - }); - } - - _execute(connections.shift()); - } -} - -// Add to store only if it does not exist -var addAuthSession = function(authStore, session) { - var found = false; - - for(var i = 0; i < authStore.length; i++) { - if(authStore[i].equal(session)) { - found = true; - break; - } - } - - if(!found) authStore.push(session); -} - -/** - * Remove authStore credentials - * @method - * @param {string} db Name of database we are removing authStore details about - * @return {object} - */ -X509.prototype.logout = function(dbName) { - this.authStore = this.authStore.filter(function(x) { - return x.db != dbName; - }); -} - -/** - * Re authenticate pool - * @method - * @param {{Server}|{ReplSet}|{Mongos}} server Topology the authentication method is being called on - * @param {[]Connections} connections Connections to authenticate using this authenticator - * @param {authResultCallback} callback The callback to return the result from the authentication - * @return {object} - */ -X509.prototype.reauthenticate = function(server, connections, callback) { - var authStore = this.authStore.slice(0); - var count = authStore.length; - if(count == 0) return callback(null, null); - // Iterate over all the auth details stored - for(var i = 0; i < authStore.length; i++) { - this.auth(server, connections, authStore[i].db, authStore[i].username, authStore[i].password, function(err) { - count = count - 1; - // Done re-authenticating - if(count == 0) { - callback(err, null); - } - }); - } -} - -/** - * This is a result from a authentication strategy - * - * @callback authResultCallback - * @param {error} error An error object. Set to null if no error present - * @param {boolean} result The result of the authentication process - */ - -module.exports = X509; diff --git a/ts-ticket-office-service/node_modules/mongodb-core/lib/connection/command_result.js b/ts-ticket-office-service/node_modules/mongodb-core/lib/connection/command_result.js deleted file mode 100644 index 2b15dd764..000000000 --- a/ts-ticket-office-service/node_modules/mongodb-core/lib/connection/command_result.js +++ /dev/null @@ -1,34 +0,0 @@ -"use strict"; - -/** - * Creates a new CommandResult instance - * @class - * @param {object} result CommandResult object - * @param {Connection} connection A connection instance associated with this result - * @return {CommandResult} A cursor instance - */ -var CommandResult = function(result, connection, message) { - this.result = result; - this.connection = connection; - this.message = message; -} - -/** - * Convert CommandResult to JSON - * @method - * @return {object} - */ -CommandResult.prototype.toJSON = function() { - return this.result; -} - -/** - * Convert CommandResult to String representation - * @method - * @return {string} - */ -CommandResult.prototype.toString = function() { - return JSON.stringify(this.toJSON()); -} - -module.exports = CommandResult; diff --git a/ts-ticket-office-service/node_modules/mongodb-core/lib/connection/commands.js b/ts-ticket-office-service/node_modules/mongodb-core/lib/connection/commands.js deleted file mode 100644 index b4c1684c7..000000000 --- a/ts-ticket-office-service/node_modules/mongodb-core/lib/connection/commands.js +++ /dev/null @@ -1,546 +0,0 @@ -"use strict"; - -var retrieveBSON = require('../connection/utils').retrieveBSON; -var BSON = retrieveBSON(); -var Long = BSON.Long; - -// Incrementing request id -var _requestId = 0; - -// Wire command operation ids -var OP_QUERY = 2004; -var OP_GETMORE = 2005; -var OP_KILL_CURSORS = 2007; - -// Query flags -var OPTS_TAILABLE_CURSOR = 2; -var OPTS_SLAVE = 4; -var OPTS_OPLOG_REPLAY = 8; -var OPTS_NO_CURSOR_TIMEOUT = 16; -var OPTS_AWAIT_DATA = 32; -var OPTS_EXHAUST = 64; -var OPTS_PARTIAL = 128; - -// Response flags -var CURSOR_NOT_FOUND = 0; -var QUERY_FAILURE = 2; -var SHARD_CONFIG_STALE = 4; -var AWAIT_CAPABLE = 8; - -/************************************************************** - * QUERY - **************************************************************/ -var Query = function(bson, ns, query, options) { - var self = this; - // Basic options needed to be passed in - if(ns == null) throw new Error("ns must be specified for query"); - if(query == null) throw new Error("query must be specified for query"); - - // Validate that we are not passing 0x00 in the collection name - if(!!~ns.indexOf("\x00")) { - throw new Error("namespace cannot contain a null character"); - } - - // Basic options - this.bson = bson; - this.ns = ns; - this.query = query; - - // Ensure empty options - this.options = options || {}; - - // Additional options - this.numberToSkip = options.numberToSkip || 0; - this.numberToReturn = options.numberToReturn || 0; - this.returnFieldSelector = options.returnFieldSelector || null; - this.requestId = Query.getRequestId(); - - // Serialization option - this.serializeFunctions = typeof options.serializeFunctions == 'boolean' ? options.serializeFunctions : false; - this.ignoreUndefined = typeof options.ignoreUndefined == 'boolean' ? options.ignoreUndefined : false; - this.maxBsonSize = options.maxBsonSize || 1024 * 1024 * 16; - this.checkKeys = typeof options.checkKeys == 'boolean' ? options.checkKeys : true; - this.batchSize = self.numberToReturn; - - // Flags - this.tailable = false; - this.slaveOk = typeof options.slaveOk == 'boolean'? options.slaveOk : false; - this.oplogReplay = false; - this.noCursorTimeout = false; - this.awaitData = false; - this.exhaust = false; - this.partial = false; -} - -// -// Assign a new request Id -Query.prototype.incRequestId = function() { - this.requestId = _requestId++; -} - -// -// Assign a new request Id -Query.nextRequestId = function() { - return _requestId + 1; -} - -// -// Uses a single allocated buffer for the process, avoiding multiple memory allocations -Query.prototype.toBin = function() { - var self = this; - var buffers = []; - var projection = null; - - // Set up the flags - var flags = 0; - if(this.tailable) { - flags |= OPTS_TAILABLE_CURSOR; - } - - if(this.slaveOk) { - flags |= OPTS_SLAVE; - } - - if(this.oplogReplay) { - flags |= OPTS_OPLOG_REPLAY; - } - - if(this.noCursorTimeout) { - flags |= OPTS_NO_CURSOR_TIMEOUT; - } - - if(this.awaitData) { - flags |= OPTS_AWAIT_DATA; - } - - if(this.exhaust) { - flags |= OPTS_EXHAUST; - } - - if(this.partial) { - flags |= OPTS_PARTIAL; - } - - // If batchSize is different to self.numberToReturn - if(self.batchSize != self.numberToReturn) self.numberToReturn = self.batchSize; - - // Allocate write protocol header buffer - var header = new Buffer( - 4 * 4 // Header - + 4 // Flags - + Buffer.byteLength(self.ns) + 1 // namespace - + 4 // numberToSkip - + 4 // numberToReturn - ); - - // Add header to buffers - buffers.push(header); - - // Serialize the query - var query = self.bson.serialize(this.query, { - checkKeys: this.checkKeys, - serializeFunctions: this.serializeFunctions, - ignoreUndefined: this.ignoreUndefined, - }); - - // Add query document - buffers.push(query); - - if(self.returnFieldSelector && Object.keys(self.returnFieldSelector).length > 0) { - // Serialize the projection document - projection = self.bson.serialize(this.returnFieldSelector, { - checkKeys: this.checkKeys, - serializeFunctions: this.serializeFunctions, - ignoreUndefined: this.ignoreUndefined, - }); - // Add projection document - buffers.push(projection); - } - - // Total message size - var totalLength = header.length + query.length + (projection ? projection.length : 0); - - // Set up the index - var index = 4; - - // Write total document length - header[3] = (totalLength >> 24) & 0xff; - header[2] = (totalLength >> 16) & 0xff; - header[1] = (totalLength >> 8) & 0xff; - header[0] = (totalLength) & 0xff; - - // Write header information requestId - header[index + 3] = (this.requestId >> 24) & 0xff; - header[index + 2] = (this.requestId >> 16) & 0xff; - header[index + 1] = (this.requestId >> 8) & 0xff; - header[index] = (this.requestId) & 0xff; - index = index + 4; - - // Write header information responseTo - header[index + 3] = (0 >> 24) & 0xff; - header[index + 2] = (0 >> 16) & 0xff; - header[index + 1] = (0 >> 8) & 0xff; - header[index] = (0) & 0xff; - index = index + 4; - - // Write header information OP_QUERY - header[index + 3] = (OP_QUERY >> 24) & 0xff; - header[index + 2] = (OP_QUERY >> 16) & 0xff; - header[index + 1] = (OP_QUERY >> 8) & 0xff; - header[index] = (OP_QUERY) & 0xff; - index = index + 4; - - // Write header information flags - header[index + 3] = (flags >> 24) & 0xff; - header[index + 2] = (flags >> 16) & 0xff; - header[index + 1] = (flags >> 8) & 0xff; - header[index] = (flags) & 0xff; - index = index + 4; - - // Write collection name - index = index + header.write(this.ns, index, 'utf8') + 1; - header[index - 1] = 0; - - // Write header information flags numberToSkip - header[index + 3] = (this.numberToSkip >> 24) & 0xff; - header[index + 2] = (this.numberToSkip >> 16) & 0xff; - header[index + 1] = (this.numberToSkip >> 8) & 0xff; - header[index] = (this.numberToSkip) & 0xff; - index = index + 4; - - // Write header information flags numberToReturn - header[index + 3] = (this.numberToReturn >> 24) & 0xff; - header[index + 2] = (this.numberToReturn >> 16) & 0xff; - header[index + 1] = (this.numberToReturn >> 8) & 0xff; - header[index] = (this.numberToReturn) & 0xff; - index = index + 4; - - // Return the buffers - return buffers; -} - -Query.getRequestId = function() { - return ++_requestId; -} - -/************************************************************** - * GETMORE - **************************************************************/ -var GetMore = function(bson, ns, cursorId, opts) { - opts = opts || {}; - this.numberToReturn = opts.numberToReturn || 0; - this.requestId = _requestId++; - this.bson = bson; - this.ns = ns; - this.cursorId = cursorId; -} - -// -// Uses a single allocated buffer for the process, avoiding multiple memory allocations -GetMore.prototype.toBin = function() { - var length = 4 + Buffer.byteLength(this.ns) + 1 + 4 + 8 + (4 * 4); - // Create command buffer - var index = 0; - // Allocate buffer - var _buffer = new Buffer(length); - - // Write header information - // index = write32bit(index, _buffer, length); - _buffer[index + 3] = (length >> 24) & 0xff; - _buffer[index + 2] = (length >> 16) & 0xff; - _buffer[index + 1] = (length >> 8) & 0xff; - _buffer[index] = (length) & 0xff; - index = index + 4; - - // index = write32bit(index, _buffer, requestId); - _buffer[index + 3] = (this.requestId >> 24) & 0xff; - _buffer[index + 2] = (this.requestId >> 16) & 0xff; - _buffer[index + 1] = (this.requestId >> 8) & 0xff; - _buffer[index] = (this.requestId) & 0xff; - index = index + 4; - - // index = write32bit(index, _buffer, 0); - _buffer[index + 3] = (0 >> 24) & 0xff; - _buffer[index + 2] = (0 >> 16) & 0xff; - _buffer[index + 1] = (0 >> 8) & 0xff; - _buffer[index] = (0) & 0xff; - index = index + 4; - - // index = write32bit(index, _buffer, OP_GETMORE); - _buffer[index + 3] = (OP_GETMORE >> 24) & 0xff; - _buffer[index + 2] = (OP_GETMORE >> 16) & 0xff; - _buffer[index + 1] = (OP_GETMORE >> 8) & 0xff; - _buffer[index] = (OP_GETMORE) & 0xff; - index = index + 4; - - // index = write32bit(index, _buffer, 0); - _buffer[index + 3] = (0 >> 24) & 0xff; - _buffer[index + 2] = (0 >> 16) & 0xff; - _buffer[index + 1] = (0 >> 8) & 0xff; - _buffer[index] = (0) & 0xff; - index = index + 4; - - // Write collection name - index = index + _buffer.write(this.ns, index, 'utf8') + 1; - _buffer[index - 1] = 0; - - // Write batch size - // index = write32bit(index, _buffer, numberToReturn); - _buffer[index + 3] = (this.numberToReturn >> 24) & 0xff; - _buffer[index + 2] = (this.numberToReturn >> 16) & 0xff; - _buffer[index + 1] = (this.numberToReturn >> 8) & 0xff; - _buffer[index] = (this.numberToReturn) & 0xff; - index = index + 4; - - // Write cursor id - // index = write32bit(index, _buffer, cursorId.getLowBits()); - _buffer[index + 3] = (this.cursorId.getLowBits() >> 24) & 0xff; - _buffer[index + 2] = (this.cursorId.getLowBits() >> 16) & 0xff; - _buffer[index + 1] = (this.cursorId.getLowBits() >> 8) & 0xff; - _buffer[index] = (this.cursorId.getLowBits()) & 0xff; - index = index + 4; - - // index = write32bit(index, _buffer, cursorId.getHighBits()); - _buffer[index + 3] = (this.cursorId.getHighBits() >> 24) & 0xff; - _buffer[index + 2] = (this.cursorId.getHighBits() >> 16) & 0xff; - _buffer[index + 1] = (this.cursorId.getHighBits() >> 8) & 0xff; - _buffer[index] = (this.cursorId.getHighBits()) & 0xff; - index = index + 4; - - // Return buffer - return _buffer; -} - -/************************************************************** - * KILLCURSOR - **************************************************************/ -var KillCursor = function(bson, cursorIds) { - this.requestId = _requestId++; - this.cursorIds = cursorIds; -} - -// -// Uses a single allocated buffer for the process, avoiding multiple memory allocations -KillCursor.prototype.toBin = function() { - var length = 4 + 4 + (4 * 4) + (this.cursorIds.length * 8); - - // Create command buffer - var index = 0; - var _buffer = new Buffer(length); - - // Write header information - // index = write32bit(index, _buffer, length); - _buffer[index + 3] = (length >> 24) & 0xff; - _buffer[index + 2] = (length >> 16) & 0xff; - _buffer[index + 1] = (length >> 8) & 0xff; - _buffer[index] = (length) & 0xff; - index = index + 4; - - // index = write32bit(index, _buffer, requestId); - _buffer[index + 3] = (this.requestId >> 24) & 0xff; - _buffer[index + 2] = (this.requestId >> 16) & 0xff; - _buffer[index + 1] = (this.requestId >> 8) & 0xff; - _buffer[index] = (this.requestId) & 0xff; - index = index + 4; - - // index = write32bit(index, _buffer, 0); - _buffer[index + 3] = (0 >> 24) & 0xff; - _buffer[index + 2] = (0 >> 16) & 0xff; - _buffer[index + 1] = (0 >> 8) & 0xff; - _buffer[index] = (0) & 0xff; - index = index + 4; - - // index = write32bit(index, _buffer, OP_KILL_CURSORS); - _buffer[index + 3] = (OP_KILL_CURSORS >> 24) & 0xff; - _buffer[index + 2] = (OP_KILL_CURSORS >> 16) & 0xff; - _buffer[index + 1] = (OP_KILL_CURSORS >> 8) & 0xff; - _buffer[index] = (OP_KILL_CURSORS) & 0xff; - index = index + 4; - - // index = write32bit(index, _buffer, 0); - _buffer[index + 3] = (0 >> 24) & 0xff; - _buffer[index + 2] = (0 >> 16) & 0xff; - _buffer[index + 1] = (0 >> 8) & 0xff; - _buffer[index] = (0) & 0xff; - index = index + 4; - - // Write batch size - // index = write32bit(index, _buffer, this.cursorIds.length); - _buffer[index + 3] = (this.cursorIds.length >> 24) & 0xff; - _buffer[index + 2] = (this.cursorIds.length >> 16) & 0xff; - _buffer[index + 1] = (this.cursorIds.length >> 8) & 0xff; - _buffer[index] = (this.cursorIds.length) & 0xff; - index = index + 4; - - // Write all the cursor ids into the array - for(var i = 0; i < this.cursorIds.length; i++) { - // Write cursor id - // index = write32bit(index, _buffer, cursorIds[i].getLowBits()); - _buffer[index + 3] = (this.cursorIds[i].getLowBits() >> 24) & 0xff; - _buffer[index + 2] = (this.cursorIds[i].getLowBits() >> 16) & 0xff; - _buffer[index + 1] = (this.cursorIds[i].getLowBits() >> 8) & 0xff; - _buffer[index] = (this.cursorIds[i].getLowBits()) & 0xff; - index = index + 4; - - // index = write32bit(index, _buffer, cursorIds[i].getHighBits()); - _buffer[index + 3] = (this.cursorIds[i].getHighBits() >> 24) & 0xff; - _buffer[index + 2] = (this.cursorIds[i].getHighBits() >> 16) & 0xff; - _buffer[index + 1] = (this.cursorIds[i].getHighBits() >> 8) & 0xff; - _buffer[index] = (this.cursorIds[i].getHighBits()) & 0xff; - index = index + 4; - } - - // Return buffer - return _buffer; -} - -var Response = function(bson, data, opts) { - opts = opts || {promoteLongs: true, promoteValues: true, promoteBuffers: false}; - this.parsed = false; - - // - // Parse Header - // - this.index = 0; - this.raw = data; - this.data = data; - this.bson = bson; - this.opts = opts; - - // Read the message length - this.length = data[this.index] | data[this.index + 1] << 8 | data[this.index + 2] << 16 | data[this.index + 3] << 24; - this.index = this.index + 4; - - // Fetch the request id for this reply - this.requestId = data[this.index] | data[this.index + 1] << 8 | data[this.index + 2] << 16 | data[this.index + 3] << 24; - this.index = this.index + 4; - - // Fetch the id of the request that triggered the response - this.responseTo = data[this.index] | data[this.index + 1] << 8 | data[this.index + 2] << 16 | data[this.index + 3] << 24; - this.index = this.index + 4; - - // Skip op-code field - this.index = this.index + 4; - - // Unpack flags - this.responseFlags = data[this.index] | data[this.index + 1] << 8 | data[this.index + 2] << 16 | data[this.index + 3] << 24; - this.index = this.index + 4; - - // Unpack the cursor - var lowBits = data[this.index] | data[this.index + 1] << 8 | data[this.index + 2] << 16 | data[this.index + 3] << 24; - this.index = this.index + 4; - var highBits = data[this.index] | data[this.index + 1] << 8 | data[this.index + 2] << 16 | data[this.index + 3] << 24; - this.index = this.index + 4; - // Create long object - this.cursorId = new Long(lowBits, highBits); - - // Unpack the starting from - this.startingFrom = data[this.index] | data[this.index + 1] << 8 | data[this.index + 2] << 16 | data[this.index + 3] << 24; - this.index = this.index + 4; - - // Unpack the number of objects returned - this.numberReturned = data[this.index] | data[this.index + 1] << 8 | data[this.index + 2] << 16 | data[this.index + 3] << 24; - this.index = this.index + 4; - - // Preallocate document array - this.documents = new Array(this.numberReturned); - - // Flag values - this.cursorNotFound = (this.responseFlags & CURSOR_NOT_FOUND) != 0; - this.queryFailure = (this.responseFlags & QUERY_FAILURE) != 0; - this.shardConfigStale = (this.responseFlags & SHARD_CONFIG_STALE) != 0; - this.awaitCapable = (this.responseFlags & AWAIT_CAPABLE) != 0; - this.promoteLongs = typeof opts.promoteLongs == 'boolean' ? opts.promoteLongs : true; - this.promoteValues = typeof opts.promoteValues == 'boolean' ? opts.promoteValues : true; - this.promoteBuffers = typeof opts.promoteBuffers == 'boolean' ? opts.promoteBuffers : false; -} - -Response.prototype.isParsed = function() { - return this.parsed; -} - -Response.prototype.parse = function(options) { - // Don't parse again if not needed - if(this.parsed) return; - options = options || {}; - - // Allow the return of raw documents instead of parsing - var raw = options.raw || false; - var documentsReturnedIn = options.documentsReturnedIn || null; - var promoteLongs = typeof options.promoteLongs == 'boolean' - ? options.promoteLongs - : this.opts.promoteLongs; - var promoteValues = typeof options.promoteValues == 'boolean' - ? options.promoteValues - : this.opts.promoteValues; - var promoteBuffers = typeof options.promoteBuffers == 'boolean' - ? options.promoteBuffers - : this.opts.promoteBuffers - var bsonSize, _options; - - // Set up the options - _options = { - promoteLongs: promoteLongs, - promoteValues: promoteValues, - promoteBuffers: promoteBuffers - }; - - // - // Single document and documentsReturnedIn set - // - if(this.numberReturned == 1 && documentsReturnedIn != null && raw) { - // Calculate the bson size - bsonSize = this.data[this.index] | this.data[this.index + 1] << 8 | this.data[this.index + 2] << 16 | this.data[this.index + 3] << 24; - // Slice out the buffer containing the command result document - var document = this.data.slice(this.index, this.index + bsonSize); - // Set up field we wish to keep as raw - var fieldsAsRaw = {} - fieldsAsRaw[documentsReturnedIn] = true; - _options.fieldsAsRaw = fieldsAsRaw; - - // Deserialize but keep the array of documents in non-parsed form - var doc = this.bson.deserialize(document, _options); - - // Get the documents - this.documents = doc.cursor[documentsReturnedIn]; - this.numberReturned = this.documents.length; - // Ensure we have a Long valie cursor id - this.cursorId = typeof doc.cursor.id == 'number' - ? Long.fromNumber(doc.cursor.id) - : doc.cursor.id; - - // Adjust the index - this.index = this.index + bsonSize; - - // Set as parsed - this.parsed = true - return; - } - - // - // Parse Body - // - for(var i = 0; i < this.numberReturned; i++) { - bsonSize = this.data[this.index] | this.data[this.index + 1] << 8 | this.data[this.index + 2] << 16 | this.data[this.index + 3] << 24; - - // If we have raw results specified slice the return document - if(raw) { - this.documents[i] = this.data.slice(this.index, this.index + bsonSize); - } else { - this.documents[i] = this.bson.deserialize(this.data.slice(this.index, this.index + bsonSize), _options); - } - - // Adjust the index - this.index = this.index + bsonSize; - } - - // Set parsed - this.parsed = true; -} - -module.exports = { - Query: Query - , GetMore: GetMore - , Response: Response - , KillCursor: KillCursor -} diff --git a/ts-ticket-office-service/node_modules/mongodb-core/lib/connection/connection.js b/ts-ticket-office-service/node_modules/mongodb-core/lib/connection/connection.js deleted file mode 100644 index 746556216..000000000 --- a/ts-ticket-office-service/node_modules/mongodb-core/lib/connection/connection.js +++ /dev/null @@ -1,611 +0,0 @@ -"use strict"; - -var inherits = require('util').inherits - , EventEmitter = require('events').EventEmitter - , net = require('net') - , tls = require('tls') - , crypto = require('crypto') - , f = require('util').format - , debugOptions = require('./utils').debugOptions - , Response = require('./commands').Response - , MongoError = require('../error') - , Logger = require('./logger'); - -var _id = 0; -var debugFields = ['host', 'port', 'size', 'keepAlive', 'keepAliveInitialDelay', 'noDelay' - , 'connectionTimeout', 'socketTimeout', 'singleBufferSerializtion', 'ssl', 'ca', 'crl', 'cert' - , 'rejectUnauthorized', 'promoteLongs', 'promoteValues', 'promoteBuffers', 'checkServerIdentity']; -var connectionAccounting = false; -var connections = {}; - -/** - * Creates a new Connection instance - * @class - * @param {string} options.host The server host - * @param {number} options.port The server port - * @param {number} [options.family=4] Version of IP stack. Defaults to 4. - * @param {boolean} [options.keepAlive=true] TCP Connection keep alive enabled - * @param {number} [options.keepAliveInitialDelay=300000] Initial delay before TCP keep alive enabled - * @param {boolean} [options.noDelay=true] TCP Connection no delay - * @param {number} [options.connectionTimeout=30000] TCP Connection timeout setting - * @param {number} [options.socketTimeout=360000] TCP Socket timeout setting - * @param {boolean} [options.singleBufferSerializtion=true] Serialize into single buffer, trade of peak memory for serialization speed - * @param {boolean} [options.ssl=false] Use SSL for connection - * @param {boolean|function} [options.checkServerIdentity=true] Ensure we check server identify during SSL, set to false to disable checking. Only works for Node 0.12.x or higher. You can pass in a boolean or your own checkServerIdentity override function. - * @param {Buffer} [options.ca] SSL Certificate store binary buffer - * @param {Buffer} [options.crl] SSL Certificate revocation store binary buffer - * @param {Buffer} [options.cert] SSL Certificate binary buffer - * @param {Buffer} [options.key] SSL Key file binary buffer - * @param {string} [options.passphrase] SSL Certificate pass phrase - * @param {boolean} [options.rejectUnauthorized=true] Reject unauthorized server certificates - * @param {boolean} [options.promoteLongs=true] Convert Long values from the db into Numbers if they fit into 53 bits - * @param {boolean} [options.promoteValues=true] Promotes BSON values to native types where possible, set to false to only receive wrapper types. - * @param {boolean} [options.promoteBuffers=false] Promotes Binary BSON values to native Node Buffers. - * @fires Connection#connect - * @fires Connection#close - * @fires Connection#error - * @fires Connection#timeout - * @fires Connection#parseError - * @return {Connection} A cursor instance - */ -var Connection = function(messageHandler, options) { - // Add event listener - EventEmitter.call(this); - // Set empty if no options passed - this.options = options || {}; - // Identification information - this.id = _id++; - // Logger instance - this.logger = Logger('Connection', options); - // No bson parser passed in - if(!options.bson) throw new Error("must pass in valid bson parser"); - // Get bson parser - this.bson = options.bson; - // Grouping tag used for debugging purposes - this.tag = options.tag; - // Message handler - this.messageHandler = messageHandler; - - // Max BSON message size - this.maxBsonMessageSize = options.maxBsonMessageSize || (1024 * 1024 * 16 * 4); - // Debug information - if(this.logger.isDebug()) this.logger.debug(f('creating connection %s with options [%s]', this.id, JSON.stringify(debugOptions(debugFields, options)))); - - // Default options - this.port = options.port || 27017; - this.host = options.host || 'localhost'; - this.family = typeof options.family == 'number' ? options.family : 4; - this.keepAlive = typeof options.keepAlive == 'boolean' ? options.keepAlive : true; - this.keepAliveInitialDelay = typeof options.keepAliveInitialDelay == 'number' - ? options.keepAliveInitialDelay : 300000; - this.noDelay = typeof options.noDelay == 'boolean' ? options.noDelay : true; - this.connectionTimeout = typeof options.connectionTimeout == 'number' - ? options.connectionTimeout : 30000; - this.socketTimeout = typeof options.socketTimeout == 'number' - ? options.socketTimeout : 360000; - - // Is the keepAliveInitialDelay > socketTimeout set it to half of socketTimeout - if(this.keepAliveInitialDelay > this.socketTimeout) { - this.keepAliveInitialDelay = Math.round(this.socketTimeout/2); - } - - // If connection was destroyed - this.destroyed = false; - - // Check if we have a entity socket - this.domainSocket = this.host.indexOf('\/') != -1; - - // Serialize commands using function - this.singleBufferSerializtion = typeof options.singleBufferSerializtion == 'boolean' ? options.singleBufferSerializtion : true; - this.serializationFunction = this.singleBufferSerializtion ? 'toBinUnified' : 'toBin'; - - // SSL options - this.ca = options.ca || null; - this.crl = options.crl || null; - this.cert = options.cert || null; - this.key = options.key || null; - this.passphrase = options.passphrase || null; - this.ssl = typeof options.ssl == 'boolean' ? options.ssl : false; - this.rejectUnauthorized = typeof options.rejectUnauthorized == 'boolean' ? options.rejectUnauthorized : true; - this.checkServerIdentity = typeof options.checkServerIdentity == 'boolean' - || typeof options.checkServerIdentity == 'function' ? options.checkServerIdentity : true; - - // If ssl not enabled - if(!this.ssl) this.rejectUnauthorized = false; - - // Response options - this.responseOptions = { - promoteLongs: typeof options.promoteLongs == 'boolean' ? options.promoteLongs : true, - promoteValues: typeof options.promoteValues == 'boolean' ? options.promoteValues : true, - promoteBuffers: typeof options.promoteBuffers == 'boolean' ? options.promoteBuffers: false - } - - // Flushing - this.flushing = false; - this.queue = []; - - // Internal state - this.connection = null; - this.writeStream = null; - - // Create hash method - var hash = crypto.createHash('sha1'); - hash.update(f('%s:%s', this.host, this.port)); - - // Create a hash name - this.hashedName = hash.digest('hex'); - - // All operations in flight on the connection - this.workItems = []; -} - -inherits(Connection, EventEmitter); - -Connection.prototype.setSocketTimeout = function(value) { - if(this.connection) { - this.connection.setTimeout(value); - } -} - -Connection.prototype.resetSocketTimeout = function() { - if(this.connection) { - this.connection.setTimeout(this.socketTimeout); - } -} - -Connection.enableConnectionAccounting = function() { - connectionAccounting = true; - connections = {}; -} - -Connection.disableConnectionAccounting = function() { - connectionAccounting = false; -} - -Connection.connections = function() { - return connections; -} - -function deleteConnection(id) { - // console.log("=== deleted connection " + id + " :: " + (connections[id] ? connections[id].port : '')) - delete connections[id]; -} - -function addConnection(id, connection) { - // console.log("=== added connection " + id + " :: " + connection.port) - connections[id] = connection; -} - -// -// Connection handlers -var errorHandler = function(self) { - return function(err) { - if(connectionAccounting) deleteConnection(self.id); - // Debug information - if(self.logger.isDebug()) self.logger.debug(f('connection %s for [%s:%s] errored out with [%s]', self.id, self.host, self.port, JSON.stringify(err))); - // Emit the error - if(self.listeners('error').length > 0) self.emit("error", MongoError.create(err), self); - } -} - -var timeoutHandler = function(self) { - return function() { - if(connectionAccounting) deleteConnection(self.id); - // Debug information - if(self.logger.isDebug()) self.logger.debug(f('connection %s for [%s:%s] timed out', self.id, self.host, self.port)); - // Emit timeout error - self.emit("timeout" - , MongoError.create(f("connection %s to %s:%s timed out", self.id, self.host, self.port)) - , self); - } -} - -var closeHandler = function(self) { - return function(hadError) { - if(connectionAccounting) deleteConnection(self.id); - // Debug information - if(self.logger.isDebug()) self.logger.debug(f('connection %s with for [%s:%s] closed', self.id, self.host, self.port)); - - // Emit close event - if(!hadError) { - self.emit("close" - , MongoError.create(f("connection %s to %s:%s closed", self.id, self.host, self.port)) - , self); - } - } -} - -var dataHandler = function(self) { - return function(data) { - // Parse until we are done with the data - while(data.length > 0) { - // If we still have bytes to read on the current message - if(self.bytesRead > 0 && self.sizeOfMessage > 0) { - // Calculate the amount of remaining bytes - var remainingBytesToRead = self.sizeOfMessage - self.bytesRead; - // Check if the current chunk contains the rest of the message - if(remainingBytesToRead > data.length) { - // Copy the new data into the exiting buffer (should have been allocated when we know the message size) - data.copy(self.buffer, self.bytesRead); - // Adjust the number of bytes read so it point to the correct index in the buffer - self.bytesRead = self.bytesRead + data.length; - - // Reset state of buffer - data = new Buffer(0); - } else { - // Copy the missing part of the data into our current buffer - data.copy(self.buffer, self.bytesRead, 0, remainingBytesToRead); - // Slice the overflow into a new buffer that we will then re-parse - data = data.slice(remainingBytesToRead); - - // Emit current complete message - try { - var emitBuffer = self.buffer; - // Reset state of buffer - self.buffer = null; - self.sizeOfMessage = 0; - self.bytesRead = 0; - self.stubBuffer = null; - // Emit the buffer - self.messageHandler(new Response(self.bson, emitBuffer, self.responseOptions), self); - } catch(err) { - var errorObject = {err:"socketHandler", trace:err, bin:self.buffer, parseState:{ - sizeOfMessage:self.sizeOfMessage, - bytesRead:self.bytesRead, - stubBuffer:self.stubBuffer}}; - // We got a parse Error fire it off then keep going - self.emit("parseError", errorObject, self); - } - } - } else { - // Stub buffer is kept in case we don't get enough bytes to determine the - // size of the message (< 4 bytes) - if(self.stubBuffer != null && self.stubBuffer.length > 0) { - // If we have enough bytes to determine the message size let's do it - if(self.stubBuffer.length + data.length > 4) { - // Prepad the data - var newData = new Buffer(self.stubBuffer.length + data.length); - self.stubBuffer.copy(newData, 0); - data.copy(newData, self.stubBuffer.length); - // Reassign for parsing - data = newData; - - // Reset state of buffer - self.buffer = null; - self.sizeOfMessage = 0; - self.bytesRead = 0; - self.stubBuffer = null; - - } else { - - // Add the the bytes to the stub buffer - var newStubBuffer = new Buffer(self.stubBuffer.length + data.length); - // Copy existing stub buffer - self.stubBuffer.copy(newStubBuffer, 0); - // Copy missing part of the data - data.copy(newStubBuffer, self.stubBuffer.length); - // Exit parsing loop - data = new Buffer(0); - } - } else { - if(data.length > 4) { - // Retrieve the message size - // var sizeOfMessage = data.readUInt32LE(0); - var sizeOfMessage = data[0] | data[1] << 8 | data[2] << 16 | data[3] << 24; - // If we have a negative sizeOfMessage emit error and return - if(sizeOfMessage < 0 || sizeOfMessage > self.maxBsonMessageSize) { - errorObject = {err:"socketHandler", trace:'', bin:self.buffer, parseState:{ - sizeOfMessage: sizeOfMessage, - bytesRead: self.bytesRead, - stubBuffer: self.stubBuffer}}; - // We got a parse Error fire it off then keep going - self.emit("parseError", errorObject, self); - return; - } - - // Ensure that the size of message is larger than 0 and less than the max allowed - if(sizeOfMessage > 4 && sizeOfMessage < self.maxBsonMessageSize && sizeOfMessage > data.length) { - self.buffer = new Buffer(sizeOfMessage); - // Copy all the data into the buffer - data.copy(self.buffer, 0); - // Update bytes read - self.bytesRead = data.length; - // Update sizeOfMessage - self.sizeOfMessage = sizeOfMessage; - // Ensure stub buffer is null - self.stubBuffer = null; - // Exit parsing loop - data = new Buffer(0); - - } else if(sizeOfMessage > 4 && sizeOfMessage < self.maxBsonMessageSize && sizeOfMessage == data.length) { - try { - emitBuffer = data; - // Reset state of buffer - self.buffer = null; - self.sizeOfMessage = 0; - self.bytesRead = 0; - self.stubBuffer = null; - // Exit parsing loop - data = new Buffer(0); - // Emit the message - self.messageHandler(new Response(self.bson, emitBuffer, self.responseOptions), self); - } catch (err) { - self.emit("parseError", err, self); - } - } else if(sizeOfMessage <= 4 || sizeOfMessage > self.maxBsonMessageSize) { - errorObject = {err:"socketHandler", trace:null, bin:data, parseState:{ - sizeOfMessage:sizeOfMessage, - bytesRead:0, - buffer:null, - stubBuffer:null}}; - // We got a parse Error fire it off then keep going - self.emit("parseError", errorObject, self); - - // Clear out the state of the parser - self.buffer = null; - self.sizeOfMessage = 0; - self.bytesRead = 0; - self.stubBuffer = null; - // Exit parsing loop - data = new Buffer(0); - } else { - emitBuffer = data.slice(0, sizeOfMessage); - // Reset state of buffer - self.buffer = null; - self.sizeOfMessage = 0; - self.bytesRead = 0; - self.stubBuffer = null; - // Copy rest of message - data = data.slice(sizeOfMessage); - // Emit the message - self.messageHandler(new Response(self.bson, emitBuffer, self.responseOptions), self); - } - } else { - // Create a buffer that contains the space for the non-complete message - self.stubBuffer = new Buffer(data.length) - // Copy the data to the stub buffer - data.copy(self.stubBuffer, 0); - // Exit parsing loop - data = new Buffer(0); - } - } - } - } - } -} - -// List of socket level valid ssl options -var legalSslSocketOptions = ['pfx', 'key', 'passphrase', 'cert', 'ca', 'ciphers' - , 'NPNProtocols', 'ALPNProtocols', 'servername' - , 'secureProtocol', 'secureContext', 'session' - , 'minDHSize']; - -function merge(options1, options2) { - // Merge in any allowed ssl options - for(var name in options2) { - if(options2[name] != null && legalSslSocketOptions.indexOf(name) != -1) { - options1[name] = options2[name]; - } - } -} - -/** - * Connect - * @method - */ -Connection.prototype.connect = function(_options) { - var self = this; - _options = _options || {}; - // Set the connections - if(connectionAccounting) addConnection(this.id, this); - // Check if we are overriding the promoteLongs - if(typeof _options.promoteLongs == 'boolean') { - self.responseOptions.promoteLongs = _options.promoteLongs; - self.responseOptions.promoteValues = _options.promoteValues; - self.responseOptions.promoteBuffers = _options.promoteBuffers; - } - - // Create new connection instance - var connection_options = self.domainSocket - ? {path: self.host} - : {port: self.port, host: self.host, family: self.family}; - self.connection = net.createConnection(connection_options); - - // Set the options for the connection - self.connection.setKeepAlive(self.keepAlive, self.keepAliveInitialDelay); - self.connection.setTimeout(self.connectionTimeout); - self.connection.setNoDelay(self.noDelay); - - // If we have ssl enabled - if(self.ssl) { - var sslOptions = { - socket: self.connection - , rejectUnauthorized: self.rejectUnauthorized - } - - // Merge in options - merge(sslOptions, this.options); - merge(sslOptions, _options); - - // Set options for ssl - if(self.ca) sslOptions.ca = self.ca; - if(self.crl) sslOptions.crl = self.crl; - if(self.cert) sslOptions.cert = self.cert; - if(self.key) sslOptions.key = self.key; - if(self.passphrase) sslOptions.passphrase = self.passphrase; - - // Override checkServerIdentity behavior - if(self.checkServerIdentity == false) { - // Skip the identiy check by retuning undefined as per node documents - // https://nodejs.org/api/tls.html#tls_tls_connect_options_callback - sslOptions.checkServerIdentity = function() { - return undefined; - } - } else if(typeof self.checkServerIdentity == 'function') { - sslOptions.checkServerIdentity = self.checkServerIdentity; - } - - // Set default sni servername to be the same as host - if(sslOptions.servername == null) { - sslOptions.servername = self.host; - } - - // Attempt SSL connection - self.connection = tls.connect(self.port, self.host, sslOptions, function() { - // Error on auth or skip - if(self.connection.authorizationError && self.rejectUnauthorized) { - return self.emit("error", self.connection.authorizationError, self, {ssl:true}); - } - - // Set socket timeout instead of connection timeout - self.connection.setTimeout(self.socketTimeout); - // We are done emit connect - self.emit('connect', self); - }); - self.connection.setTimeout(self.connectionTimeout); - } else { - self.connection.on('connect', function() { - // Set socket timeout instead of connection timeout - self.connection.setTimeout(self.socketTimeout); - // Emit connect event - self.emit('connect', self); - }); - } - - // Add handlers for events - self.connection.once('error', errorHandler(self)); - self.connection.once('timeout', timeoutHandler(self)); - self.connection.once('close', closeHandler(self)); - self.connection.on('data', dataHandler(self)); -} - -/** - * Unref this connection - * @method - * @return {boolean} - */ -Connection.prototype.unref = function() { - if (this.connection) this.connection.unref(); - else { - var self = this; - this.once('connect', function() { - self.connection.unref(); - }); - } -} - -/** - * Destroy connection - * @method - */ -Connection.prototype.destroy = function() { - // Set the connections - if(connectionAccounting) deleteConnection(this.id); - if(this.connection) { - // Catch posssible exception thrown by node 0.10.x - try { this.connection.end(); } catch (err) {} - // Destroy connection - this.connection.destroy(); - } - - this.destroyed = true; -} - -/** - * Write to connection - * @method - * @param {Command} command Command to write out need to implement toBin and toBinUnified - */ -Connection.prototype.write = function(buffer) { - var i; - // Debug Log - if(this.logger.isDebug()) { - if(!Array.isArray(buffer)) { - this.logger.debug(f('writing buffer [%s] to %s:%s', buffer.toString('hex'), this.host, this.port)); - } else { - for(i = 0; i < buffer.length; i++) - this.logger.debug(f('writing buffer [%s] to %s:%s', buffer[i].toString('hex'), this.host, this.port)); - } - } - - // Double check that the connection is not destroyed - if(this.connection.destroyed === false) { - // Write out the command - if(!Array.isArray(buffer)) { - this.connection.write(buffer, 'binary'); - return true; - } - - // Iterate over all buffers and write them in order to the socket - for(i = 0; i < buffer.length; i++) this.connection.write(buffer[i], 'binary'); - return true; - } - - // Connection is destroyed return write failed - return false; -} - -/** - * Return id of connection as a string - * @method - * @return {string} - */ -Connection.prototype.toString = function() { - return "" + this.id; -} - -/** - * Return json object of connection - * @method - * @return {object} - */ -Connection.prototype.toJSON = function() { - return {id: this.id, host: this.host, port: this.port}; -} - -/** - * Is the connection connected - * @method - * @return {boolean} - */ -Connection.prototype.isConnected = function() { - if(this.destroyed) return false; - return !this.connection.destroyed && this.connection.writable; -} - -/** - * A server connect event, used to verify that the connection is up and running - * - * @event Connection#connect - * @type {Connection} - */ - -/** - * The server connection closed, all pool connections closed - * - * @event Connection#close - * @type {Connection} - */ - -/** - * The server connection caused an error, all pool connections closed - * - * @event Connection#error - * @type {Connection} - */ - -/** - * The server connection timed out, all pool connections closed - * - * @event Connection#timeout - * @type {Connection} - */ - -/** - * The driver experienced an invalid message, all pool connections closed - * - * @event Connection#parseError - * @type {Connection} - */ - -module.exports = Connection; diff --git a/ts-ticket-office-service/node_modules/mongodb-core/lib/connection/logger.js b/ts-ticket-office-service/node_modules/mongodb-core/lib/connection/logger.js deleted file mode 100644 index b8b18187f..000000000 --- a/ts-ticket-office-service/node_modules/mongodb-core/lib/connection/logger.js +++ /dev/null @@ -1,228 +0,0 @@ -"use strict"; - -var f = require('util').format - , MongoError = require('../error'); - -// Filters for classes -var classFilters = {}; -var filteredClasses = {}; -var level = null; -// Save the process id -var pid = process.pid; -// current logger -var currentLogger = null; - -/** - * Creates a new Logger instance - * @class - * @param {string} className The Class name associated with the logging instance - * @param {object} [options=null] Optional settings. - * @param {Function} [options.logger=null] Custom logger function; - * @param {string} [options.loggerLevel=error] Override default global log level. - * @return {Logger} a Logger instance. - */ -var Logger = function(className, options) { - if(!(this instanceof Logger)) return new Logger(className, options); - options = options || {}; - - // Current reference - this.className = className; - - // Current logger - if(options.logger) { - currentLogger = options.logger; - } else if(currentLogger == null) { - currentLogger = console.log; - } - - // Set level of logging, default is error - if(options.loggerLevel) { - level = options.loggerLevel || 'error'; - } - - // Add all class names - if(filteredClasses[this.className] == null) classFilters[this.className] = true; -} - -/** - * Log a message at the debug level - * @method - * @param {string} message The message to log - * @param {object} object additional meta data to log - * @return {null} - */ -Logger.prototype.debug = function(message, object) { - if(this.isDebug() - && ((Object.keys(filteredClasses).length > 0 && filteredClasses[this.className]) - || (Object.keys(filteredClasses).length == 0 && classFilters[this.className]))) { - var dateTime = new Date().getTime(); - var msg = f("[%s-%s:%s] %s %s", 'DEBUG', this.className, pid, dateTime, message); - var state = { - type: 'debug', message: message, className: this.className, pid: pid, date: dateTime - }; - if(object) state.meta = object; - currentLogger(msg, state); - } -} - -/** - * Log a message at the warn level - * @method - * @param {string} message The message to log - * @param {object} object additional meta data to log - * @return {null} - */ -Logger.prototype.warn = function(message, object) { - if(this.isWarn() - && ((Object.keys(filteredClasses).length > 0 && filteredClasses[this.className]) - || (Object.keys(filteredClasses).length == 0 && classFilters[this.className]))) { - var dateTime = new Date().getTime(); - var msg = f("[%s-%s:%s] %s %s", 'WARN', this.className, pid, dateTime, message); - var state = { - type: 'warn', message: message, className: this.className, pid: pid, date: dateTime - }; - if(object) state.meta = object; - currentLogger(msg, state); - } -}, - -/** - * Log a message at the info level - * @method - * @param {string} message The message to log - * @param {object} object additional meta data to log - * @return {null} - */ -Logger.prototype.info = function(message, object) { - if(this.isInfo() - && ((Object.keys(filteredClasses).length > 0 && filteredClasses[this.className]) - || (Object.keys(filteredClasses).length == 0 && classFilters[this.className]))) { - var dateTime = new Date().getTime(); - var msg = f("[%s-%s:%s] %s %s", 'INFO', this.className, pid, dateTime, message); - var state = { - type: 'info', message: message, className: this.className, pid: pid, date: dateTime - }; - if(object) state.meta = object; - currentLogger(msg, state); - } -}, - -/** - * Log a message at the error level - * @method - * @param {string} message The message to log - * @param {object} object additional meta data to log - * @return {null} - */ -Logger.prototype.error = function(message, object) { - if(this.isError() - && ((Object.keys(filteredClasses).length > 0 && filteredClasses[this.className]) - || (Object.keys(filteredClasses).length == 0 && classFilters[this.className]))) { - var dateTime = new Date().getTime(); - var msg = f("[%s-%s:%s] %s %s", 'ERROR', this.className, pid, dateTime, message); - var state = { - type: 'error', message: message, className: this.className, pid: pid, date: dateTime - }; - if(object) state.meta = object; - currentLogger(msg, state); - } -}, - -/** - * Is the logger set at info level - * @method - * @return {boolean} - */ -Logger.prototype.isInfo = function() { - return level == 'info' || level == 'debug'; -}, - -/** - * Is the logger set at error level - * @method - * @return {boolean} - */ -Logger.prototype.isError = function() { - return level == 'error' || level == 'info' || level == 'debug'; -}, - -/** - * Is the logger set at error level - * @method - * @return {boolean} - */ -Logger.prototype.isWarn = function() { - return level == 'error' || level == 'warn' || level == 'info' || level == 'debug'; -}, - -/** - * Is the logger set at debug level - * @method - * @return {boolean} - */ -Logger.prototype.isDebug = function() { - return level == 'debug'; -} - -/** - * Resets the logger to default settings, error and no filtered classes - * @method - * @return {null} - */ -Logger.reset = function() { - level = 'error'; - filteredClasses = {}; -} - -/** - * Get the current logger function - * @method - * @return {function} - */ -Logger.currentLogger = function() { - return currentLogger; -} - -/** - * Set the current logger function - * @method - * @param {function} logger Logger function. - * @return {null} - */ -Logger.setCurrentLogger = function(logger) { - if(typeof logger != 'function') throw new MongoError("current logger must be a function"); - currentLogger = logger; -} - -/** - * Set what classes to log. - * @method - * @param {string} type The type of filter (currently only class) - * @param {string[]} values The filters to apply - * @return {null} - */ -Logger.filter = function(type, values) { - if(type == 'class' && Array.isArray(values)) { - filteredClasses = {}; - - values.forEach(function(x) { - filteredClasses[x] = true; - }); - } -} - -/** - * Set the current log level - * @method - * @param {string} level Set current log level (debug, info, error) - * @return {null} - */ -Logger.setLevel = function(_level) { - if(_level != 'info' && _level != 'error' && _level != 'debug' && _level != 'warn') { - throw new Error(f("%s is an illegal logging level", _level)); - } - - level = _level; -} - -module.exports = Logger; diff --git a/ts-ticket-office-service/node_modules/mongodb-core/lib/connection/pool.js b/ts-ticket-office-service/node_modules/mongodb-core/lib/connection/pool.js deleted file mode 100644 index 4e4e388b6..000000000 --- a/ts-ticket-office-service/node_modules/mongodb-core/lib/connection/pool.js +++ /dev/null @@ -1,1387 +0,0 @@ -"use strict"; - -var inherits = require('util').inherits, - EventEmitter = require('events').EventEmitter, - Connection = require('./connection'), - MongoError = require('../error'), - Logger = require('./logger'), - f = require('util').format, - Query = require('./commands').Query, - CommandResult = require('./command_result'), - assign = require('../utils').assign; - -var MongoCR = require('../auth/mongocr') - , X509 = require('../auth/x509') - , Plain = require('../auth/plain') - , GSSAPI = require('../auth/gssapi') - , SSPI = require('../auth/sspi') - , ScramSHA1 = require('../auth/scram'); - -var DISCONNECTED = 'disconnected'; -var CONNECTING = 'connecting'; -var CONNECTED = 'connected'; -var DESTROYING = 'destroying'; -var DESTROYED = 'destroyed'; - -var _id = 0; - -/** - * Creates a new Pool instance - * @class - * @param {string} options.host The server host - * @param {number} options.port The server port - * @param {number} [options.size=1] Max server connection pool size - * @param {boolean} [options.reconnect=true] Server will attempt to reconnect on loss of connection - * @param {number} [options.reconnectTries=30] Server attempt to reconnect #times - * @param {number} [options.reconnectInterval=1000] Server will wait # milliseconds between retries - * @param {boolean} [options.keepAlive=true] TCP Connection keep alive enabled - * @param {number} [options.keepAliveInitialDelay=300000] Initial delay before TCP keep alive enabled - * @param {boolean} [options.noDelay=true] TCP Connection no delay - * @param {number} [options.connectionTimeout=30000] TCP Connection timeout setting - * @param {number} [options.socketTimeout=360000] TCP Socket timeout setting - * @param {number} [options.monitoringSocketTimeout=30000] TCP Socket timeout setting for replicaset monitoring socket - * @param {boolean} [options.ssl=false] Use SSL for connection - * @param {boolean|function} [options.checkServerIdentity=true] Ensure we check server identify during SSL, set to false to disable checking. Only works for Node 0.12.x or higher. You can pass in a boolean or your own checkServerIdentity override function. - * @param {Buffer} [options.ca] SSL Certificate store binary buffer - * @param {Buffer} [options.crl] SSL Certificate revocation store binary buffer - * @param {Buffer} [options.cert] SSL Certificate binary buffer - * @param {Buffer} [options.key] SSL Key file binary buffer - * @param {string} [options.passPhrase] SSL Certificate pass phrase - * @param {boolean} [options.rejectUnauthorized=false] Reject unauthorized server certificates - * @param {boolean} [options.promoteLongs=true] Convert Long values from the db into Numbers if they fit into 53 bits - * @param {boolean} [options.promoteValues=true] Promotes BSON values to native types where possible, set to false to only receive wrapper types. - * @param {boolean} [options.promoteBuffers=false] Promotes Binary BSON values to native Node Buffers. - * @param {boolean} [options.domainsEnabled=false] Enable the wrapping of the callback in the current entity, disabled by default to avoid perf hit. - * @fires Pool#connect - * @fires Pool#close - * @fires Pool#error - * @fires Pool#timeout - * @fires Pool#parseError - * @return {Pool} A cursor instance - */ -var Pool = function(options) { - // Add event listener - EventEmitter.call(this); - // Add the options - this.options = assign({ - // Host and port settings - host: 'localhost', - port: 27017, - // Pool default max size - size: 5, - // socket settings - connectionTimeout: 30000, - socketTimeout: 360000, - keepAlive: true, - keepAliveInitialDelay: 300000, - noDelay: true, - // SSL Settings - ssl: false, checkServerIdentity: true, - ca: null, crl: null, cert: null, key: null, passPhrase: null, - rejectUnauthorized: false, - promoteLongs: true, - promoteValues: true, - promoteBuffers: false, - // Reconnection options - reconnect: true, - reconnectInterval: 1000, - reconnectTries: 30, - // Enable domains - domainsEnabled: false - }, options); - - // console.log("=================================== pool options") - // console.dir(this.options) - - // Identification information - this.id = _id++; - // Current reconnect retries - this.retriesLeft = this.options.reconnectTries; - this.reconnectId = null; - // No bson parser passed in - if(!options.bson || (options.bson - && (typeof options.bson.serialize != 'function' - || typeof options.bson.deserialize != 'function'))) { - throw new Error("must pass in valid bson parser"); - } - - // Logger instance - this.logger = Logger('Pool', options); - // Pool state - this.state = DISCONNECTED; - // Connections - this.availableConnections = []; - this.inUseConnections = []; - this.connectingConnections = []; - // Currently executing - this.executing = false; - // Operation work queue - this.queue = []; - - // All the authProviders - this.authProviders = options.authProviders || { - 'mongocr': new MongoCR(options.bson), 'x509': new X509(options.bson) - , 'plain': new Plain(options.bson), 'gssapi': new GSSAPI(options.bson) - , 'sspi': new SSPI(options.bson), 'scram-sha-1': new ScramSHA1(options.bson) - } - - // Contains the reconnect connection - this.reconnectConnection = null; - - // Are we currently authenticating - this.authenticating = false; - this.loggingout = false; - this.nonAuthenticatedConnections = []; - this.authenticatingTimestamp = null; - // Number of consecutive timeouts caught - this.numberOfConsecutiveTimeouts = 0; - // Current pool Index - this.connectionIndex = 0; -} - -inherits(Pool, EventEmitter); - -Object.defineProperty(Pool.prototype, 'size', { - enumerable:true, - get: function() { return this.options.size; } -}); - -Object.defineProperty(Pool.prototype, 'connectionTimeout', { - enumerable:true, - get: function() { return this.options.connectionTimeout; } -}); - -Object.defineProperty(Pool.prototype, 'socketTimeout', { - enumerable:true, - get: function() { return this.options.socketTimeout; } -}); - -function stateTransition(self, newState) { - var legalTransitions = { - 'disconnected': [CONNECTING, DESTROYING, DISCONNECTED], - 'connecting': [CONNECTING, DESTROYING, CONNECTED, DISCONNECTED], - 'connected': [CONNECTED, DISCONNECTED, DESTROYING], - 'destroying': [DESTROYING, DESTROYED], - 'destroyed': [DESTROYED] - } - - // Get current state - var legalStates = legalTransitions[self.state]; - if(legalStates && legalStates.indexOf(newState) != -1) { - self.state = newState; - } else { - self.logger.error(f('Pool with id [%s] failed attempted illegal state transition from [%s] to [%s] only following state allowed [%s]' - , self.id, self.state, newState, legalStates)); - } -} - -function authenticate(pool, auth, connection, cb) { - if(auth[0] === undefined) return cb(null); - // We need to authenticate the server - var mechanism = auth[0]; - var db = auth[1]; - // Validate if the mechanism exists - if(!pool.authProviders[mechanism]) { - throw new MongoError(f('authMechanism %s not supported', mechanism)); - } - - // Get the provider - var provider = pool.authProviders[mechanism]; - - // Authenticate using the provided mechanism - provider.auth.apply(provider, [write(pool), [connection], db].concat(auth.slice(2)).concat([cb])); -} - -// The write function used by the authentication mechanism (bypasses external) -function write(self) { - return function(connection, command, callback) { - // Get the raw buffer - // Ensure we stop auth if pool was destroyed - if(self.state == DESTROYED || self.state == DESTROYING) { - return callback(new MongoError('pool destroyed')); - } - - // Set the connection workItem callback - connection.workItems.push({ - cb: callback, command: true, requestId: command.requestId - }); - - // Write the buffer out to the connection - connection.write(command.toBin()); - }; -} - - -function reauthenticate(pool, connection, cb) { - // Authenticate - function authenticateAgainstProvider(pool, connection, providers, cb) { - // Finished re-authenticating against providers - if(providers.length == 0) return cb(); - // Get the provider name - var provider = pool.authProviders[providers.pop()]; - - // Auth provider - provider.reauthenticate(write(pool), [connection], function(err) { - // We got an error return immediately - if(err) return cb(err); - // Continue authenticating the connection - authenticateAgainstProvider(pool, connection, providers, cb); - }); - } - - // Start re-authenticating process - authenticateAgainstProvider(pool, connection, Object.keys(pool.authProviders), cb); -} - -function connectionFailureHandler(self, event) { - return function(err) { - // console.log("========== connectionFailureHandler :: " + event) - // console.dir(err) - - if (this._connectionFailHandled) return; - this._connectionFailHandled = true; - // Destroy the connection - this.destroy(); - - // Remove the connection - removeConnection(self, this); - - // Flush all work Items on this connection - while(this.workItems.length > 0) { - var workItem = this.workItems.shift(); - // if(workItem.cb) workItem.cb(err); - if(workItem.cb) workItem.cb(err); - } - - // Did we catch a timeout, increment the numberOfConsecutiveTimeouts - if(event == 'timeout') { - self.numberOfConsecutiveTimeouts = self.numberOfConsecutiveTimeouts + 1; - - // Have we timed out more than reconnectTries in a row ? - // Force close the pool as we are trying to connect to tcp sink hole - if(self.numberOfConsecutiveTimeouts > self.options.reconnectTries) { - self.numberOfConsecutiveTimeouts = 0; - // Destroy all connections and pool - self.destroy(true); - // Emit close event - return self.emit('close', self); - } - } - - // No more socket available propegate the event - if(self.socketCount() == 0) { - if(self.state != DESTROYED && self.state != DESTROYING) { - stateTransition(self, DISCONNECTED); - } - - // Do not emit error events, they are always close events - // do not trigger the low level error handler in node - event = event == 'error' ? 'close' : event; - self.emit(event, err); - } - - // Start reconnection attempts - if(!self.reconnectId && self.options.reconnect) { - self.reconnectId = setTimeout(attemptReconnect(self), self.options.reconnectInterval); - } - }; -} - -function attemptReconnect(self) { - return function() { - // console.log("========================= attemptReconnect") - self.emit('attemptReconnect', self); - if(self.state == DESTROYED || self.state == DESTROYING) return; - - // We are connected do not try again - if(self.isConnected()) { - self.reconnectId = null; - return; - } - - // If we have failure schedule a retry - function _connectionFailureHandler(self, event) { - return function() { - // console.log("========== _connectionFailureHandler :: " + event) - if (this._connectionFailHandled) return; - this._connectionFailHandled = true; - // Destroy the connection - this.destroy(); - // Count down the number of reconnects - self.retriesLeft = self.retriesLeft - 1; - // How many retries are left - if(self.retriesLeft == 0) { - // Destroy the instance - self.destroy(); - // Emit close event - self.emit('reconnectFailed' - , new MongoError(f('failed to reconnect after %s attempts with interval %s ms', self.options.reconnectTries, self.options.reconnectInterval))); - } else { - self.reconnectId = setTimeout(attemptReconnect(self), self.options.reconnectInterval); - } - } - } - - // Got a connect handler - function _connectHandler(self) { - return function() { - // Assign - var connection = this; - - // Pool destroyed stop the connection - if(self.state == DESTROYED || self.state == DESTROYING) { - return connection.destroy(); - } - - // Clear out all handlers - handlers.forEach(function(event) { - connection.removeAllListeners(event); - }); - - // Reset reconnect id - self.reconnectId = null; - - // Apply pool connection handlers - connection.on('error', connectionFailureHandler(self, 'error')); - connection.on('close', connectionFailureHandler(self, 'close')); - connection.on('timeout', connectionFailureHandler(self, 'timeout')); - connection.on('parseError', connectionFailureHandler(self, 'parseError')); - - // Apply any auth to the connection - reauthenticate(self, this, function() { - // Reset retries - self.retriesLeft = self.options.reconnectTries; - // Push to available connections - self.availableConnections.push(connection); - // Set the reconnectConnection to null - self.reconnectConnection = null; - // Emit reconnect event - self.emit('reconnect', self); - // Trigger execute to start everything up again - _execute(self)(); - }); - } - } - - // Create a connection - self.reconnectConnection = new Connection(messageHandler(self), self.options); - // Add handlers - self.reconnectConnection.on('close', _connectionFailureHandler(self, 'close')); - self.reconnectConnection.on('error', _connectionFailureHandler(self, 'error')); - self.reconnectConnection.on('timeout', _connectionFailureHandler(self, 'timeout')); - self.reconnectConnection.on('parseError', _connectionFailureHandler(self, 'parseError')); - // On connection - self.reconnectConnection.on('connect', _connectHandler(self)); - // Attempt connection - self.reconnectConnection.connect(); - } -} - -function moveConnectionBetween(connection, from, to) { - var index = from.indexOf(connection); - // Move the connection from connecting to available - if(index != -1) { - from.splice(index, 1); - to.push(connection); - } -} - -function messageHandler(self) { - return function(message, connection) { - // workItem to execute - var workItem = null; - - // Locate the workItem - for(var i = 0; i < connection.workItems.length; i++) { - if(connection.workItems[i].requestId == message.responseTo) { - // Get the callback - workItem = connection.workItems[i]; - // Remove from list of workItems - connection.workItems.splice(i, 1); - } - } - - - // Reset timeout counter - self.numberOfConsecutiveTimeouts = 0; - - // Reset the connection timeout if we modified it for - // this operation - if(workItem.socketTimeout) { - connection.resetSocketTimeout(); - } - - // Log if debug enabled - if(self.logger.isDebug()) { - self.logger.debug(f('message [%s] received from %s:%s' - , message.raw.toString('hex'), self.options.host, self.options.port)); - } - - // Authenticate any straggler connections - function authenticateStragglers(self, connection, callback) { - // Get any non authenticated connections - var connections = self.nonAuthenticatedConnections.slice(0); - var nonAuthenticatedConnections = self.nonAuthenticatedConnections; - self.nonAuthenticatedConnections = []; - - // Establish if the connection need to be authenticated - // Add to authentication list if - // 1. we were in an authentication process when the operation was executed - // 2. our current authentication timestamp is from the workItem one, meaning an auth has happened - if(connection.workItems.length == 1 && (connection.workItems[0].authenticating == true - || (typeof connection.workItems[0].authenticatingTimestamp == 'number' - && connection.workItems[0].authenticatingTimestamp != self.authenticatingTimestamp))) { - // Add connection to the list - connections.push(connection); - } - - // No connections need to be re-authenticated - if(connections.length == 0) { - // Release the connection back to the pool - moveConnectionBetween(connection, self.inUseConnections, self.availableConnections); - // Finish - return callback(); - } - - // Apply re-authentication to all connections before releasing back to pool - var connectionCount = connections.length; - // Authenticate all connections - for(var i = 0; i < connectionCount; i++) { - reauthenticate(self, connections[i], function() { - connectionCount = connectionCount - 1; - - if(connectionCount == 0) { - // Put non authenticated connections in available connections - self.availableConnections = self.availableConnections.concat(nonAuthenticatedConnections); - // Release the connection back to the pool - moveConnectionBetween(connection, self.inUseConnections, self.availableConnections); - // Return - callback(); - } - }); - } - } - - function handleOperationCallback(self, cb, err, result) { - // No entity enabled - if(!self.options.domainsEnabled) { - return process.nextTick(function() { - return cb(err, result); - }); - } - - // Domain enabled just call the callback - cb(err, result); - } - - authenticateStragglers(self, connection, function() { - // Keep executing, ensure current message handler does not stop execution - if(!self.executing) { - process.nextTick(function() { - _execute(self)(); - }); - } - - // Time to dispatch the message if we have a callback - if(!workItem.immediateRelease) { - try { - // Parse the message according to the provided options - message.parse(workItem); - } catch(err) { - return handleOperationCallback(self, workItem.cb, MongoError.create(err)); - } - - // Establish if we have an error - if(workItem.command && message.documents[0] && (message.documents[0].ok == 0 || message.documents[0]['$err'] - || message.documents[0]['errmsg'] || message.documents[0]['code'])) { - return handleOperationCallback(self, workItem.cb, MongoError.create(message.documents[0])); - } - - // Add the connection details - message.hashedName = connection.hashedName; - - // Return the documents - handleOperationCallback(self, workItem.cb, null, new CommandResult(workItem.fullResult ? message : message.documents[0], connection, message)); - } - }); - } -} - -/** - * Return the total socket count in the pool. - * @method - * @return {Number} The number of socket available. - */ -Pool.prototype.socketCount = function() { - return this.availableConnections.length - + this.inUseConnections.length; - // + this.connectingConnections.length; -} - -/** - * Return all pool connections - * @method - * @return {Connection[]} The pool connections - */ -Pool.prototype.allConnections = function() { - return this.availableConnections - .concat(this.inUseConnections) - .concat(this.connectingConnections); -} - -/** - * Get a pool connection (round-robin) - * @method - * @return {Connection} - */ -Pool.prototype.get = function() { - return this.allConnections()[0]; -} - -/** - * Is the pool connected - * @method - * @return {boolean} - */ -Pool.prototype.isConnected = function() { - // We are in a destroyed state - if(this.state == DESTROYED || this.state == DESTROYING) { - return false; - } - - // Get connections - var connections = this.availableConnections - .concat(this.inUseConnections); - - // Check if we have any connected connections - for(var i = 0; i < connections.length; i++) { - if(connections[i].isConnected()) return true; - } - - // Might be authenticating, but we are still connected - if(connections.length == 0 && this.authenticating) { - return true - } - - // Not connected - return false; -} - -/** - * Was the pool destroyed - * @method - * @return {boolean} - */ -Pool.prototype.isDestroyed = function() { - return this.state == DESTROYED || this.state == DESTROYING; -} - -/** - * Is the pool in a disconnected state - * @method - * @return {boolean} - */ -Pool.prototype.isDisconnected = function() { - return this.state == DISCONNECTED; -} - -/** - * Connect pool - * @method - */ -Pool.prototype.connect = function() { - if(this.state != DISCONNECTED) { - throw new MongoError('connection in unlawful state ' + this.state); - } - - var self = this; - // Transition to connecting state - stateTransition(this, CONNECTING); - // Create an array of the arguments - var args = Array.prototype.slice.call(arguments, 0); - // Create a connection - var connection = new Connection(messageHandler(self), this.options); - // Add to list of connections - this.connectingConnections.push(connection); - // Add listeners to the connection - connection.once('connect', function(connection) { - if(self.state == DESTROYED || self.state == DESTROYING) return self.destroy(); - - // If we are in a topology, delegate the auth to it - // This is to avoid issues where we would auth against an - // arbiter - if(self.options.inTopology) { - // Set connected mode - stateTransition(self, CONNECTED); - - // Move the active connection - moveConnectionBetween(connection, self.connectingConnections, self.availableConnections); - - // Emit the connect event - return self.emit('connect', self); - } - - // Apply any store credentials - reauthenticate(self, connection, function(err) { - if(self.state == DESTROYED || self.state == DESTROYING) return self.destroy(); - - // We have an error emit it - if(err) { - // Destroy the pool - self.destroy(); - // Emit the error - return self.emit('error', err); - } - - // Authenticate - authenticate(self, args, connection, function(err) { - if(self.state == DESTROYED || self.state == DESTROYING) return self.destroy(); - - // We have an error emit it - if(err) { - // Destroy the pool - self.destroy(); - // Emit the error - return self.emit('error', err); - } - // Set connected mode - stateTransition(self, CONNECTED); - - // Move the active connection - moveConnectionBetween(connection, self.connectingConnections, self.availableConnections); - - // Emit the connect event - self.emit('connect', self); - }); - }); - }); - - // Add error handlers - connection.once('error', connectionFailureHandler(this, 'error')); - connection.once('close', connectionFailureHandler(this, 'close')); - connection.once('timeout', connectionFailureHandler(this, 'timeout')); - connection.once('parseError', connectionFailureHandler(this, 'parseError')); - - try { - connection.connect(); - } catch(err) { - // SSL or something threw on connect - process.nextTick(function() { - self.emit('error', err); - }); - } -} - -/** - * Authenticate using a specified mechanism - * @method - * @param {string} mechanism The Auth mechanism we are invoking - * @param {string} db The db we are invoking the mechanism against - * @param {...object} param Parameters for the specific mechanism - * @param {authResultCallback} callback A callback function - */ -Pool.prototype.auth = function(mechanism) { - var self = this; - var args = Array.prototype.slice.call(arguments, 0); - var callback = args.pop(); - - // If we don't have the mechanism fail - if(self.authProviders[mechanism] == null && mechanism != 'default') { - throw new MongoError(f("auth provider %s does not exist", mechanism)); - } - - // Signal that we are authenticating a new set of credentials - this.authenticating = true; - this.authenticatingTimestamp = new Date().getTime(); - - // Authenticate all live connections - function authenticateLiveConnections(self, args, cb) { - // Get the current viable connections - var connections = self.allConnections(); - // Allow nothing else to use the connections while we authenticate them - self.availableConnections = []; - self.inUseConnections = []; - self.connectingConnections = []; - - var connectionsCount = connections.length; - var error = null; - // No connections available, return - if(connectionsCount == 0) { - self.authenticating = false; - return callback(null); - } - - // Authenticate the connections - for(var i = 0; i < connections.length; i++) { - authenticate(self, args, connections[i], function(err) { - connectionsCount = connectionsCount - 1; - - // Store the error - if(err) error = err; - - // Processed all connections - if(connectionsCount == 0) { - // Auth finished - self.authenticating = false; - // Add the connections back to available connections - self.availableConnections = self.availableConnections.concat(connections); - // We had an error, return it - if(error) { - // Log the error - if(self.logger.isError()) { - self.logger.error(f('[%s] failed to authenticate against server %s:%s' - , self.id, self.options.host, self.options.port)); - } - - return cb(error); - } - cb(null); - } - }); - } - } - - // Wait for a logout in process to happen - function waitForLogout(self, cb) { - if(!self.loggingout) return cb(); - setTimeout(function() { - waitForLogout(self, cb); - }, 1) - } - - // Wait for loggout to finish - waitForLogout(self, function() { - // Authenticate all live connections - authenticateLiveConnections(self, args, function(err) { - // Credentials correctly stored in auth provider if successful - // Any new connections will now reauthenticate correctly - self.authenticating = false; - // Return after authentication connections - callback(err); - }); - }); -} - -/** - * Logout all users against a database - * @method - * @param {string} dbName The database name - * @param {authResultCallback} callback A callback function - */ -Pool.prototype.logout = function(dbName, callback) { - var self = this; - if(typeof dbName != 'string') { - throw new MongoError('logout method requires a db name as first argument'); - } - - if(typeof callback != 'function') { - throw new MongoError('logout method requires a callback'); - } - - // Indicate logout in process - this.loggingout = true; - - // Get all relevant connections - var connections = self.availableConnections.concat(self.inUseConnections); - var count = connections.length; - // Store any error - var error = null; - - // Send logout command over all the connections - for(var i = 0; i < connections.length; i++) { - write(self)(connections[i], new Query(this.options.bson - , f('%s.$cmd', dbName) - , {logout:1}, {numberToSkip: 0, numberToReturn: 1}), function(err) { - count = count - 1; - if(err) error = err; - - if(count == 0) { - self.loggingout = false; - callback(error); - } - }); - } -} - -/** - * Unref the pool - * @method - */ -Pool.prototype.unref = function() { - // Get all the known connections - var connections = this.availableConnections - .concat(this.inUseConnections) - .concat(this.connectingConnections); - connections.forEach(function(c) { - c.unref(); - }); -} - -// Events -var events = ['error', 'close', 'timeout', 'parseError', 'connect']; - -// Destroy the connections -function destroy(self, connections) { - // Destroy all connections - connections.forEach(function(c) { - // Remove all listeners - for(var i = 0; i < events.length; i++) { - c.removeAllListeners(events[i]); - } - // Destroy connection - c.destroy(); - }); - - // Zero out all connections - self.inUseConnections = []; - self.availableConnections = []; - self.nonAuthenticatedConnections = []; - self.connectingConnections = []; - - // Set state to destroyed - stateTransition(self, DESTROYED); -} - -/** - * Destroy pool - * @method - */ -Pool.prototype.destroy = function(force) { - var self = this; - // Do not try again if the pool is already dead - if(this.state == DESTROYED || self.state == DESTROYING) return; - // Set state to destroyed - stateTransition(this, DESTROYING); - - // Are we force closing - if(force) { - // Get all the known connections - var connections = self.availableConnections - .concat(self.inUseConnections) - .concat(self.nonAuthenticatedConnections) - .concat(self.connectingConnections); - - // Flush any remaining work items with - // an error - while(self.queue.length > 0) { - var workItem = self.queue.shift(); - if(typeof workItem.cb == 'function') { - workItem.cb(new MongoError('Pool was force destroyed')); - } - } - - // Destroy the topology - return destroy(self, connections); - } - - // Clear out the reconnect if set - if (this.reconnectId) { - clearTimeout(this.reconnectId); - } - - // If we have a reconnect connection running, close - // immediately - if (this.reconnectConnection) { - this.reconnectConnection.destroy(); - } - - // Wait for the operations to drain before we close the pool - function checkStatus() { - flushMonitoringOperations(self.queue); - - if(self.queue.length == 0) { - // Get all the known connections - var connections = self.availableConnections - .concat(self.inUseConnections) - .concat(self.nonAuthenticatedConnections) - .concat(self.connectingConnections); - - // Check if we have any in flight operations - for(var i = 0; i < connections.length; i++) { - // There is an operation still in flight, reschedule a - // check waiting for it to drain - if(connections[i].workItems.length > 0) { - return setTimeout(checkStatus, 1); - } - } - - destroy(self, connections); - // } else if (self.queue.length > 0 && !this.reconnectId) { - - } else { - // Ensure we empty the queue - _execute(self)(); - // Set timeout - setTimeout(checkStatus, 1); - } - } - - // Initiate drain of operations - checkStatus(); -} - -/** - * Write a message to MongoDB - * @method - * @return {Connection} - */ -Pool.prototype.write = function(commands, options, cb) { - var self = this; - // Ensure we have a callback - if(typeof options == 'function') { - cb = options; - } - - // Always have options - options = options || {}; - - // Pool was destroyed error out - if(this.state == DESTROYED || this.state == DESTROYING) { - // Callback with an error - if(cb) { - try { - cb(new MongoError('pool destroyed')); - } catch(err) { - process.nextTick(function() { - throw err; - }); - } - } - - return; - } - - if(this.options.domainsEnabled - && process.domain && typeof cb === "function") { - // if we have a entity bind to it - var oldCb = cb; - cb = process.domain.bind(function() { - // v8 - argumentsToArray one-liner - var args = new Array(arguments.length); for(var i = 0; i < arguments.length; i++) { args[i] = arguments[i]; } - // bounce off event loop so entity switch takes place - process.nextTick(function() { - oldCb.apply(null, args); - }); - }); - } - - // Do we have an operation - var operation = { - cb: cb, raw: false, promoteLongs: true, promoteValues: true, promoteBuffers: false, fullResult: false - }; - - var buffer = null - - if(Array.isArray(commands)) { - buffer = []; - - for(var i = 0; i < commands.length; i++) { - buffer.push(commands[i].toBin()); - } - - // Get the requestId - operation.requestId = commands[commands.length - 1].requestId; - } else { - operation.requestId = commands.requestId; - buffer = commands.toBin(); - } - - // Set the buffers - operation.buffer = buffer; - - // Set the options for the parsing - operation.promoteLongs = typeof options.promoteLongs == 'boolean' ? options.promoteLongs : true; - operation.promoteValues = typeof options.promoteValues == 'boolean' ? options.promoteValues : true; - operation.promoteBuffers = typeof options.promoteBuffers == 'boolean' ? options.promoteBuffers : false; - operation.raw = typeof options.raw == 'boolean' ? options.raw : false; - operation.immediateRelease = typeof options.immediateRelease == 'boolean' ? options.immediateRelease : false; - operation.documentsReturnedIn = options.documentsReturnedIn; - operation.command = typeof options.command == 'boolean' ? options.command : false; - operation.fullResult = typeof options.fullResult == 'boolean' ? options.fullResult : false; - operation.noResponse = typeof options.noResponse == 'boolean' ? options.noResponse : false; - // operation.requestId = options.requestId; - - // Optional per operation socketTimeout - operation.socketTimeout = options.socketTimeout; - operation.monitoring = options.monitoring; - // Custom socket Timeout - if(options.socketTimeout) { - operation.socketTimeout = options.socketTimeout; - } - - // We need to have a callback function unless the message returns no response - if(!(typeof cb == 'function') && !options.noResponse) { - throw new MongoError('write method must provide a callback'); - } - - // If we have a monitoring operation schedule as the very first operation - // Otherwise add to back of queue - if(options.monitoring) { - this.queue.unshift(operation); - } else { - this.queue.push(operation); - } - - // Attempt to execute the operation - if(!self.executing) { - process.nextTick(function() { - _execute(self)(); - }); - } -} - -// Remove connection method -function remove(connection, connections) { - for(var i = 0; i < connections.length; i++) { - if(connections[i] === connection) { - connections.splice(i, 1); - return true; - } - } -} - -function removeConnection(self, connection) { - if(remove(connection, self.availableConnections)) return; - if(remove(connection, self.inUseConnections)) return; - if(remove(connection, self.connectingConnections)) return; - if(remove(connection, self.nonAuthenticatedConnections)) return; -} - -// All event handlers -var handlers = ["close", "message", "error", "timeout", "parseError", "connect"]; - -function _createConnection(self) { - if(self.state == DESTROYED || self.state == DESTROYING) { - return; - } - var connection = new Connection(messageHandler(self), self.options); - - // Push the connection - self.connectingConnections.push(connection); - - // Handle any errors - var tempErrorHandler = function(_connection) { - return function() { - // Destroy the connection - _connection.destroy(); - // Remove the connection from the connectingConnections list - removeConnection(self, _connection); - // Start reconnection attempts - if(!self.reconnectId && self.options.reconnect) { - self.reconnectId = setTimeout(attemptReconnect(self), self.options.reconnectInterval); - } - } - } - - // Handle successful connection - var tempConnectHandler = function(_connection) { - return function() { - // Destroyed state return - if(self.state == DESTROYED || self.state == DESTROYING) { - // Remove the connection from the list - removeConnection(self, _connection); - return _connection.destroy(); - } - - // Destroy all event emitters - handlers.forEach(function(e) { - _connection.removeAllListeners(e); - }); - - // Add the final handlers - _connection.once('close', connectionFailureHandler(self, 'close')); - _connection.once('error', connectionFailureHandler(self, 'error')); - _connection.once('timeout', connectionFailureHandler(self, 'timeout')); - _connection.once('parseError', connectionFailureHandler(self, 'parseError')); - - // Signal - reauthenticate(self, _connection, function(err) { - if(self.state == DESTROYED || self.state == DESTROYING) { - return _connection.destroy(); - } - // Remove the connection from the connectingConnections list - removeConnection(self, _connection); - - // Handle error - if(err) { - return _connection.destroy(); - } - - // If we are c at the moment - // Do not automatially put in available connections - // As we need to apply the credentials first - if(self.authenticating) { - self.nonAuthenticatedConnections.push(_connection); - } else { - // Push to available - self.availableConnections.push(_connection); - // Execute any work waiting - _execute(self)(); - } - }); - } - } - - // Add all handlers - connection.once('close', tempErrorHandler(connection)); - connection.once('error', tempErrorHandler(connection)); - connection.once('timeout', tempErrorHandler(connection)); - connection.once('parseError', tempErrorHandler(connection)); - connection.once('connect', tempConnectHandler(connection)); - - // Start connection - connection.connect(); -} - -function flushMonitoringOperations(queue) { - for(var i = 0; i < queue.length; i++) { - if(queue[i].monitoring) { - var workItem = queue[i]; - queue.splice(i, 1); - workItem.cb(new MongoError({ message: 'no connection available for monitoring', driver:true })); - } - } -} - -function _execute(self) { - return function() { - if(self.state == DESTROYED) return; - // Already executing, skip - if(self.executing) return; - // Set pool as executing - self.executing = true; - - // Wait for auth to clear before continuing - function waitForAuth(cb) { - if(!self.authenticating) return cb(); - // Wait for a milisecond and try again - setTimeout(function() { - waitForAuth(cb); - }, 1); - } - - // Block on any auth in process - waitForAuth(function() { - // New pool connections are in progress, wait them to finish - // before executing any more operation to ensure distribution of - // operations - if(self.connectingConnections.length > 0) { - return; - } - - // As long as we have available connections - while(true) { - // Total availble connections - var totalConnections = self.availableConnections.length - + self.connectingConnections.length - + self.inUseConnections.length; - - // No available connections available, flush any monitoring ops - if(self.availableConnections.length == 0) { - // Flush any monitoring operations - flushMonitoringOperations(self.queue); - break; - } - - // No queue break - if(self.queue.length == 0) { - break; - } - - // Get a connection - var connection = null; - - // Locate all connections that have no work - var connections = []; - // Get a list of all connections - for(var i = 0; i < self.availableConnections.length; i++) { - if(self.availableConnections[i].workItems.length == 0) { - connections.push(self.availableConnections[i]); - } - } - - // No connection found that has no work on it, just pick one for pipelining - if(connections.length == 0) { - connection = self.availableConnections[self.connectionIndex++ % self.availableConnections.length]; - } else { - connection = connections[self.connectionIndex++ % connections.length]; - } - - // Is the connection connected - if(connection.isConnected()) { - // Get the next work item - var workItem = self.queue.shift(); - - // If we are monitoring we need to use a connection that is not - // running another operation to avoid socket timeout changes - // affecting an existing operation - if (workItem.monitoring) { - var foundValidConnection = false; - - for (var i = 0; i < self.availableConnections.length; i++) { - // If the connection is connected - // And there are no pending workItems on it - // Then we can safely use it for monitoring. - if(self.availableConnections[i].isConnected() - && self.availableConnections[i].workItems.length == 0) { - foundValidConnection = true; - connection = self.availableConnections[i]; - break; - } - } - - // No safe connection found, attempt to grow the connections - // if possible and break from the loop - if(!foundValidConnection) { - // Put workItem back on the queue - self.queue.unshift(workItem); - - // Attempt to grow the pool if it's not yet maxsize - if(totalConnections < self.options.size - && self.queue.length > 0) { - // Create a new connection - _createConnection(self); - } - - // Re-execute the operation - setTimeout(function() { - _execute(self)(); - }, 10); - - break; - } - } - - // Don't execute operation until we have a full pool - if(totalConnections < self.options.size) { - // Connection has work items, then put it back on the queue - // and create a new connection - if(connection.workItems.length > 0) { - // Lets put the workItem back on the list - self.queue.unshift(workItem); - // Create a new connection - _createConnection(self); - // Break from the loop - break; - } - } - - // Get actual binary commands - var buffer = workItem.buffer; - - // Set current status of authentication process - workItem.authenticating = self.authenticating; - workItem.authenticatingTimestamp = self.authenticatingTimestamp; - - // If we are monitoring take the connection of the availableConnections - if (workItem.monitoring) { - moveConnectionBetween(connection, self.availableConnections, self.inUseConnections); - } - - // Track the executing commands on the mongo server - // as long as there is an expected response - if (! workItem.noResponse) { - connection.workItems.push(workItem); - } - - // We have a custom socketTimeout - if(!workItem.immediateRelease && typeof workItem.socketTimeout == 'number') { - connection.setSocketTimeout(workItem.socketTimeout); - } - - // Capture if write was successful - var writeSuccessful = true; - - // Put operation on the wire - if(Array.isArray(buffer)) { - for(var i = 0; i < buffer.length; i++) { - writeSuccessful = connection.write(buffer[i]) - } - } else { - writeSuccessful = connection.write(buffer); - } - - if(writeSuccessful && workItem.immediateRelease && self.authenticating) { - removeConnection(self, connection); - self.nonAuthenticatedConnections.push(connection); - } else if(writeSuccessful === false) { - // If write not successful put back on queue - self.queue.unshift(workItem); - // Remove the disconnected connection - removeConnection(self, connection); - // Flush any monitoring operations in the queue, failing fast - flushMonitoringOperations(self.queue); - } - } else { - // Remove the disconnected connection - removeConnection(self, connection); - // Flush any monitoring operations in the queue, failing fast - flushMonitoringOperations(self.queue); - } - } - }); - - self.executing = false; - } -} - -// Make execution loop available for testing -Pool._execute = _execute; - -/** - * A server connect event, used to verify that the connection is up and running - * - * @event Pool#connect - * @type {Pool} - */ - -/** - * A server reconnect event, used to verify that pool reconnected. - * - * @event Pool#reconnect - * @type {Pool} - */ - -/** - * The server connection closed, all pool connections closed - * - * @event Pool#close - * @type {Pool} - */ - -/** - * The server connection caused an error, all pool connections closed - * - * @event Pool#error - * @type {Pool} - */ - -/** - * The server connection timed out, all pool connections closed - * - * @event Pool#timeout - * @type {Pool} - */ - -/** - * The driver experienced an invalid message, all pool connections closed - * - * @event Pool#parseError - * @type {Pool} - */ - -/** - * The driver attempted to reconnect - * - * @event Pool#attemptReconnect - * @type {Pool} - */ - -/** - * The driver exhausted all reconnect attempts - * - * @event Pool#reconnectFailed - * @type {Pool} - */ - -module.exports = Pool; diff --git a/ts-ticket-office-service/node_modules/mongodb-core/lib/connection/utils.js b/ts-ticket-office-service/node_modules/mongodb-core/lib/connection/utils.js deleted file mode 100644 index 958f21ce5..000000000 --- a/ts-ticket-office-service/node_modules/mongodb-core/lib/connection/utils.js +++ /dev/null @@ -1,86 +0,0 @@ -"use strict"; - -var f = require('util').format, - require_optional = require('require_optional'); - -// Set property function -var setProperty = function(obj, prop, flag, values) { - Object.defineProperty(obj, prop.name, { - enumerable:true, - set: function(value) { - if(typeof value != 'boolean') throw new Error(f("%s required a boolean", prop.name)); - // Flip the bit to 1 - if(value == true) values.flags |= flag; - // Flip the bit to 0 if it's set, otherwise ignore - if(value == false && (values.flags & flag) == flag) values.flags ^= flag; - prop.value = value; - } - , get: function() { return prop.value; } - }); -} - -// Set property function -var getProperty = function(obj, propName, fieldName, values, func) { - Object.defineProperty(obj, propName, { - enumerable:true, - get: function() { - // Not parsed yet, parse it - if(values[fieldName] == null && obj.isParsed && !obj.isParsed()) { - obj.parse(); - } - - // Do we have a post processing function - if(typeof func == 'function') return func(values[fieldName]); - // Return raw value - return values[fieldName]; - } - }); -} - -// Set simple property -var getSingleProperty = function(obj, name, value) { - Object.defineProperty(obj, name, { - enumerable:true, - get: function() { - return value - } - }); -} - -// Shallow copy -var copy = function(fObj, tObj) { - tObj = tObj || {}; - for(var name in fObj) tObj[name] = fObj[name]; - return tObj; -} - -var debugOptions = function(debugFields, options) { - var finaloptions = {}; - debugFields.forEach(function(n) { - finaloptions[n] = options[n]; - }); - - return finaloptions; -} - -var retrieveBSON = function() { - var BSON = require('bson'); - BSON.native = false; - - try { - var optionalBSON = require_optional('bson-ext'); - if(optionalBSON) { - optionalBSON.native = true; - return optionalBSON; - } - } catch(err) {} - - return BSON; -} - -exports.setProperty = setProperty; -exports.getProperty = getProperty; -exports.getSingleProperty = getSingleProperty; -exports.copy = copy; -exports.debugOptions = debugOptions; -exports.retrieveBSON = retrieveBSON; diff --git a/ts-ticket-office-service/node_modules/mongodb-core/lib/cursor.js b/ts-ticket-office-service/node_modules/mongodb-core/lib/cursor.js deleted file mode 100644 index d2d776a1d..000000000 --- a/ts-ticket-office-service/node_modules/mongodb-core/lib/cursor.js +++ /dev/null @@ -1,702 +0,0 @@ -"use strict"; - -var Logger = require('./connection/logger') - , retrieveBSON = require('./connection/utils').retrieveBSON - , MongoError = require('./error') - , f = require('util').format; - -var BSON = retrieveBSON(), - Long = BSON.Long; - -/** - * This is a cursor results callback - * - * @callback resultCallback - * @param {error} error An error object. Set to null if no error present - * @param {object} document - */ - -/** - * @fileOverview The **Cursor** class is an internal class that embodies a cursor on MongoDB - * allowing for iteration over the results returned from the underlying query. - * - * **CURSORS Cannot directly be instantiated** - * @example - * var Server = require('mongodb-core').Server - * , ReadPreference = require('mongodb-core').ReadPreference - * , assert = require('assert'); - * - * var server = new Server({host: 'localhost', port: 27017}); - * // Wait for the connection event - * server.on('connect', function(server) { - * assert.equal(null, err); - * - * // Execute the write - * var cursor = _server.cursor('integration_tests.inserts_example4', { - * find: 'integration_tests.example4' - * , query: {a:1} - * }, { - * readPreference: new ReadPreference('secondary'); - * }); - * - * // Get the first document - * cursor.next(function(err, doc) { - * assert.equal(null, err); - * server.destroy(); - * }); - * }); - * - * // Start connecting - * server.connect(); - */ - -/** - * Creates a new Cursor, not to be used directly - * @class - * @param {object} bson An instance of the BSON parser - * @param {string} ns The MongoDB fully qualified namespace (ex: db1.collection1) - * @param {{object}|Long} cmd The selector (can be a command or a cursorId) - * @param {object} [options=null] Optional settings. - * @param {object} [options.batchSize=1000] Batchsize for the operation - * @param {array} [options.documents=[]] Initial documents list for cursor - * @param {object} [options.transforms=null] Transform methods for the cursor results - * @param {function} [options.transforms.query] Transform the value returned from the initial query - * @param {function} [options.transforms.doc] Transform each document returned from Cursor.prototype.next - * @param {object} topology The server topology instance. - * @param {object} topologyOptions The server topology options. - * @return {Cursor} A cursor instance - * @property {number} cursorBatchSize The current cursorBatchSize for the cursor - * @property {number} cursorLimit The current cursorLimit for the cursor - * @property {number} cursorSkip The current cursorSkip for the cursor - */ -var Cursor = function(bson, ns, cmd, options, topology, topologyOptions) { - options = options || {}; - - // Cursor pool - this.pool = null; - // Cursor server - this.server = null; - - // Do we have a not connected handler - this.disconnectHandler = options.disconnectHandler; - - // Set local values - this.bson = bson; - this.ns = ns; - this.cmd = cmd; - this.options = options; - this.topology = topology; - - // All internal state - this.cursorState = { - cursorId: null - , cmd: cmd - , documents: options.documents || [] - , cursorIndex: 0 - , dead: false - , killed: false - , init: false - , notified: false - , limit: options.limit || cmd.limit || 0 - , skip: options.skip || cmd.skip || 0 - , batchSize: options.batchSize || cmd.batchSize || 1000 - , currentLimit: 0 - // Result field name if not a cursor (contains the array of results) - , transforms: options.transforms - } - - // Add promoteLong to cursor state - if(typeof topologyOptions.promoteLongs == 'boolean') { - this.cursorState.promoteLongs = topologyOptions.promoteLongs; - } else if(typeof options.promoteLongs == 'boolean') { - this.cursorState.promoteLongs = options.promoteLongs; - } - - // Add promoteValues to cursor state - if(typeof topologyOptions.promoteValues == 'boolean') { - this.cursorState.promoteValues = topologyOptions.promoteValues; - } else if(typeof options.promoteValues == 'boolean') { - this.cursorState.promoteValues = options.promoteValues; - } - - // Add promoteBuffers to cursor state - if(typeof topologyOptions.promoteBuffers == 'boolean') { - this.cursorState.promoteBuffers = topologyOptions.promoteBuffers; - } else if(typeof options.promoteBuffers == 'boolean') { - this.cursorState.promoteBuffers = options.promoteBuffers; - } - - // Logger - this.logger = Logger('Cursor', topologyOptions); - - // - // Did we pass in a cursor id - if(typeof cmd == 'number') { - this.cursorState.cursorId = Long.fromNumber(cmd); - this.cursorState.lastCursorId = this.cursorState.cursorId; - } else if(cmd instanceof Long) { - this.cursorState.cursorId = cmd; - this.cursorState.lastCursorId = cmd; - } -} - -Cursor.prototype.setCursorBatchSize = function(value) { - this.cursorState.batchSize = value; -} - -Cursor.prototype.cursorBatchSize = function() { - return this.cursorState.batchSize; -} - -Cursor.prototype.setCursorLimit = function(value) { - this.cursorState.limit = value; -} - -Cursor.prototype.cursorLimit = function() { - return this.cursorState.limit; -} - -Cursor.prototype.setCursorSkip = function(value) { - this.cursorState.skip = value; -} - -Cursor.prototype.cursorSkip = function() { - return this.cursorState.skip; -} - -// -// Handle callback (including any exceptions thrown) -var handleCallback = function(callback, err, result) { - try { - callback(err, result); - } catch(err) { - process.nextTick(function() { - throw err; - }); - } -} - -// Internal methods -Cursor.prototype._find = function(callback) { - var self = this; - - if(self.logger.isDebug()) { - self.logger.debug(f('issue initial query [%s] with flags [%s]' - , JSON.stringify(self.cmd) - , JSON.stringify(self.query))); - } - - var queryCallback = function(err, r) { - if(err) return callback(err); - - // Get the raw message - var result = r.message; - - // Query failure bit set - if(result.queryFailure) { - return callback(MongoError.create(result.documents[0]), null); - } - - // Check if we have a command cursor - if(Array.isArray(result.documents) && result.documents.length == 1 - && (!self.cmd.find || (self.cmd.find && self.cmd.virtual == false)) - && (result.documents[0].cursor != 'string' - || result.documents[0]['$err'] - || result.documents[0]['errmsg'] - || Array.isArray(result.documents[0].result)) - ) { - - // We have a an error document return the error - if(result.documents[0]['$err'] - || result.documents[0]['errmsg']) { - return callback(MongoError.create(result.documents[0]), null); - } - - // We have a cursor document - if(result.documents[0].cursor != null - && typeof result.documents[0].cursor != 'string') { - var id = result.documents[0].cursor.id; - // If we have a namespace change set the new namespace for getmores - if(result.documents[0].cursor.ns) { - self.ns = result.documents[0].cursor.ns; - } - // Promote id to long if needed - self.cursorState.cursorId = typeof id == 'number' ? Long.fromNumber(id) : id; - self.cursorState.lastCursorId = self.cursorState.cursorId; - // If we have a firstBatch set it - if(Array.isArray(result.documents[0].cursor.firstBatch)) { - self.cursorState.documents = result.documents[0].cursor.firstBatch;//.reverse(); - } - - // Return after processing command cursor - return callback(null, null); - } - - if(Array.isArray(result.documents[0].result)) { - self.cursorState.documents = result.documents[0].result; - self.cursorState.cursorId = Long.ZERO; - return callback(null, null); - } - } - - // Otherwise fall back to regular find path - self.cursorState.cursorId = result.cursorId; - self.cursorState.documents = result.documents; - self.cursorState.lastCursorId = result.cursorId; - - // Transform the results with passed in transformation method if provided - if(self.cursorState.transforms && typeof self.cursorState.transforms.query == 'function') { - self.cursorState.documents = self.cursorState.transforms.query(result); - } - - // Return callback - callback(null, null); - } - - // Options passed to the pool - var queryOptions = {}; - - // If we have a raw query decorate the function - if(self.options.raw || self.cmd.raw) { - // queryCallback.raw = self.options.raw || self.cmd.raw; - queryOptions.raw = self.options.raw || self.cmd.raw; - } - - // Do we have documentsReturnedIn set on the query - if(typeof self.query.documentsReturnedIn == 'string') { - // queryCallback.documentsReturnedIn = self.query.documentsReturnedIn; - queryOptions.documentsReturnedIn = self.query.documentsReturnedIn; - } - - // Add promote Long value if defined - if(typeof self.cursorState.promoteLongs == 'boolean') { - queryOptions.promoteLongs = self.cursorState.promoteLongs; - } - - // Add promote values if defined - if(typeof self.cursorState.promoteValues == 'boolean') { - queryOptions.promoteValues = self.cursorState.promoteValues; - } - - // Add promote values if defined - if(typeof self.cursorState.promoteBuffers == 'boolean') { - queryOptions.promoteBuffers = self.cursorState.promoteBuffers; - } - // Write the initial command out - self.server.s.pool.write(self.query, queryOptions, queryCallback); -} - -Cursor.prototype._getmore = function(callback) { - if(this.logger.isDebug()) this.logger.debug(f('schedule getMore call for query [%s]', JSON.stringify(this.query))) - // Determine if it's a raw query - var raw = this.options.raw || this.cmd.raw; - - // Set the current batchSize - var batchSize = this.cursorState.batchSize; - if(this.cursorState.limit > 0 - && ((this.cursorState.currentLimit + batchSize) > this.cursorState.limit)) { - batchSize = this.cursorState.limit - this.cursorState.currentLimit; - } - - // Default pool - var pool = this.server.s.pool; - - // We have a wire protocol handler - this.server.wireProtocolHandler.getMore(this.bson, this.ns, this.cursorState, batchSize, raw, pool, this.options, callback); -} - -Cursor.prototype._killcursor = function(callback) { - // Set cursor to dead - this.cursorState.dead = true; - this.cursorState.killed = true; - // Remove documents - this.cursorState.documents = []; - - // If no cursor id just return - if(this.cursorState.cursorId == null || this.cursorState.cursorId.isZero() || this.cursorState.init == false) { - if(callback) callback(null, null); - return; - } - - // Default pool - var pool = this.server.s.pool; - // Execute command - this.server.wireProtocolHandler.killCursor(this.bson, this.ns, this.cursorState.cursorId, pool, callback); -} - -/** - * Clone the cursor - * @method - * @return {Cursor} - */ -Cursor.prototype.clone = function() { - return this.topology.cursor(this.ns, this.cmd, this.options); -} - -/** - * Checks if the cursor is dead - * @method - * @return {boolean} A boolean signifying if the cursor is dead or not - */ -Cursor.prototype.isDead = function() { - return this.cursorState.dead == true; -} - -/** - * Checks if the cursor was killed by the application - * @method - * @return {boolean} A boolean signifying if the cursor was killed by the application - */ -Cursor.prototype.isKilled = function() { - return this.cursorState.killed == true; -} - -/** - * Checks if the cursor notified it's caller about it's death - * @method - * @return {boolean} A boolean signifying if the cursor notified the callback - */ -Cursor.prototype.isNotified = function() { - return this.cursorState.notified == true; -} - -/** - * Returns current buffered documents length - * @method - * @return {number} The number of items in the buffered documents - */ -Cursor.prototype.bufferedCount = function() { - return this.cursorState.documents.length - this.cursorState.cursorIndex; -} - -/** - * Returns current buffered documents - * @method - * @return {Array} An array of buffered documents - */ -Cursor.prototype.readBufferedDocuments = function(number) { - var unreadDocumentsLength = this.cursorState.documents.length - this.cursorState.cursorIndex; - var length = number < unreadDocumentsLength ? number : unreadDocumentsLength; - var elements = this.cursorState.documents.slice(this.cursorState.cursorIndex, this.cursorState.cursorIndex + length); - - // Transform the doc with passed in transformation method if provided - if(this.cursorState.transforms && typeof this.cursorState.transforms.doc == 'function') { - // Transform all the elements - for(var i = 0; i < elements.length; i++) { - elements[i] = this.cursorState.transforms.doc(elements[i]); - } - } - - // Ensure we do not return any more documents than the limit imposed - // Just return the number of elements up to the limit - if(this.cursorState.limit > 0 && (this.cursorState.currentLimit + elements.length) > this.cursorState.limit) { - elements = elements.slice(0, (this.cursorState.limit - this.cursorState.currentLimit)); - this.kill(); - } - - // Adjust current limit - this.cursorState.currentLimit = this.cursorState.currentLimit + elements.length; - this.cursorState.cursorIndex = this.cursorState.cursorIndex + elements.length; - - // Return elements - return elements; -} - -/** - * Kill the cursor - * @method - * @param {resultCallback} callback A callback function - */ -Cursor.prototype.kill = function(callback) { - this._killcursor(callback); -} - -/** - * Resets the cursor - * @method - * @return {null} - */ -Cursor.prototype.rewind = function() { - if(this.cursorState.init) { - if(!this.cursorState.dead) { - this.kill(); - } - - this.cursorState.currentLimit = 0; - this.cursorState.init = false; - this.cursorState.dead = false; - this.cursorState.killed = false; - this.cursorState.notified = false; - this.cursorState.documents = []; - this.cursorState.cursorId = null; - this.cursorState.cursorIndex = 0; - } -} - -/** - * Validate if the pool is dead and return error - */ -var isConnectionDead = function(self, callback) { - if(self.pool - && self.pool.isDestroyed()) { - self.cursorState.notified = true; - self.cursorState.killed = true; - self.cursorState.documents = []; - self.cursorState.cursorIndex = 0; - callback(MongoError.create(f('connection to host %s:%s was destroyed', self.pool.host, self.pool.port))) - return true; - } - - return false; -} - -/** - * Validate if the cursor is dead but was not explicitly killed by user - */ -var isCursorDeadButNotkilled = function(self, callback) { - // Cursor is dead but not marked killed, return null - if(self.cursorState.dead && !self.cursorState.killed) { - self.cursorState.notified = true; - self.cursorState.killed = true; - self.cursorState.documents = []; - self.cursorState.cursorIndex = 0; - handleCallback(callback, null, null); - return true; - } - - return false; -} - -/** - * Validate if the cursor is dead and was killed by user - */ -var isCursorDeadAndKilled = function(self, callback) { - if(self.cursorState.dead && self.cursorState.killed) { - handleCallback(callback, MongoError.create('cursor is dead')); - return true; - } - - return false; -} - -/** - * Validate if the cursor was killed by the user - */ -var isCursorKilled = function(self, callback) { - if(self.cursorState.killed) { - self.cursorState.notified = true; - self.cursorState.documents = []; - self.cursorState.cursorIndex = 0; - handleCallback(callback, null, null); - return true; - } - - return false; -} - -/** - * Mark cursor as being dead and notified - */ -var setCursorDeadAndNotified = function(self, callback) { - self.cursorState.dead = true; - self.cursorState.notified = true; - self.cursorState.documents = []; - self.cursorState.cursorIndex = 0; - handleCallback(callback, null, null); -} - -/** - * Mark cursor as being notified - */ -var setCursorNotified = function(self, callback) { - self.cursorState.notified = true; - self.cursorState.documents = []; - self.cursorState.cursorIndex = 0; - handleCallback(callback, null, null); -} - -var nextFunction = function(self, callback) { - // We have notified about it - if(self.cursorState.notified) { - return callback(new Error('cursor is exhausted')); - } - - // Cursor is killed return null - if(isCursorKilled(self, callback)) return; - - // Cursor is dead but not marked killed, return null - if(isCursorDeadButNotkilled(self, callback)) return; - - // We have a dead and killed cursor, attempting to call next should error - if(isCursorDeadAndKilled(self, callback)) return; - - // We have just started the cursor - if(!self.cursorState.init) { - // Topology is not connected, save the call in the provided store to be - // Executed at some point when the handler deems it's reconnected - if(!self.topology.isConnected(self.options)) { - if (!self.topology.s.options.reconnect) { - // Reconnect is disabled, so we'll never reconnect - return callback(new MongoError('no connection available')); - } - if (self.disconnectHandler != null) { - if (self.topology.isDestroyed()) { - // Topology was destroyed, so don't try to wait for it to reconnect - return callback(new MongoError('Topology was destroyed')); - } - - return self.disconnectHandler.addObjectAndMethod('cursor', self, 'next', [callback], callback); - } - } - - try { - self.server = self.topology.getServer(self.options); - } catch(err) { - // Handle the error and add object to next method call - if(self.disconnectHandler != null) { - return self.disconnectHandler.addObjectAndMethod('cursor', self, 'next', [callback], callback); - } - - // Otherwise return the error - return callback(err); - } - - // Set as init - self.cursorState.init = true; - - // Server does not support server - if(self.cmd - && self.cmd.collation - && self.server.ismaster.maxWireVersion < 5) { - return callback(new MongoError(f('server %s does not support collation', self.server.name))); - } - - try { - self.query = self.server.wireProtocolHandler.command(self.bson, self.ns, self.cmd, self.cursorState, self.topology, self.options); - } catch(err) { - return callback(err); - } - } - - // If we don't have a cursorId execute the first query - if(self.cursorState.cursorId == null) { - // Check if pool is dead and return if not possible to - // execute the query against the db - if(isConnectionDead(self, callback)) return; - - // Check if topology is destroyed - if(self.topology.isDestroyed()) return callback(new MongoError('connection destroyed, not possible to instantiate cursor')); - - // query, cmd, options, cursorState, callback - self._find(function(err) { - if(err) return handleCallback(callback, err, null); - - if(self.cursorState.documents.length == 0 - && self.cursorState.cursorId && self.cursorState.cursorId.isZero() - && !self.cmd.tailable && !self.cmd.awaitData) { - return setCursorNotified(self, callback); - } - - nextFunction(self, callback); - }); - } else if(self.cursorState.limit > 0 && self.cursorState.currentLimit >= self.cursorState.limit) { - // Ensure we kill the cursor on the server - self.kill(); - // Set cursor in dead and notified state - return setCursorDeadAndNotified(self, callback); - } else if(self.cursorState.cursorIndex == self.cursorState.documents.length - && !Long.ZERO.equals(self.cursorState.cursorId)) { - // Ensure an empty cursor state - self.cursorState.documents = []; - self.cursorState.cursorIndex = 0; - - // Check if topology is destroyed - if(self.topology.isDestroyed()) return callback(new MongoError('connection destroyed, not possible to instantiate cursor')); - - // Check if connection is dead and return if not possible to - // execute a getmore on this connection - if(isConnectionDead(self, callback)) return; - - // Execute the next get more - self._getmore(function(err, doc, connection) { - if(err) return handleCallback(callback, err); - - // Save the returned connection to ensure all getMore's fire over the same connection - self.connection = connection; - - // Tailable cursor getMore result, notify owner about it - // No attempt is made here to retry, this is left to the user of the - // core module to handle to keep core simple - if(self.cursorState.documents.length == 0 - && self.cmd.tailable && Long.ZERO.equals(self.cursorState.cursorId)) { - // No more documents in the tailed cursor - return handleCallback(callback, MongoError.create({ - message: 'No more documents in tailed cursor' - , tailable: self.cmd.tailable - , awaitData: self.cmd.awaitData - })); - } else if(self.cursorState.documents.length == 0 - && self.cmd.tailable && !Long.ZERO.equals(self.cursorState.cursorId)) { - return nextFunction(self, callback); - } - - if(self.cursorState.limit > 0 && self.cursorState.currentLimit >= self.cursorState.limit) { - return setCursorDeadAndNotified(self, callback); - } - - nextFunction(self, callback); - }); - } else if(self.cursorState.documents.length == self.cursorState.cursorIndex - && self.cmd.tailable && Long.ZERO.equals(self.cursorState.cursorId)) { - return handleCallback(callback, MongoError.create({ - message: 'No more documents in tailed cursor' - , tailable: self.cmd.tailable - , awaitData: self.cmd.awaitData - })); - } else if(self.cursorState.documents.length == self.cursorState.cursorIndex - && Long.ZERO.equals(self.cursorState.cursorId)) { - setCursorDeadAndNotified(self, callback); - } else { - if(self.cursorState.limit > 0 && self.cursorState.currentLimit >= self.cursorState.limit) { - // Ensure we kill the cursor on the server - self.kill(); - // Set cursor in dead and notified state - return setCursorDeadAndNotified(self, callback); - } - - // Increment the current cursor limit - self.cursorState.currentLimit += 1; - - // Get the document - var doc = self.cursorState.documents[self.cursorState.cursorIndex++]; - - // Doc overflow - if(!doc || doc.$err) { - // Ensure we kill the cursor on the server - self.kill(); - // Set cursor in dead and notified state - return setCursorDeadAndNotified(self, function() { - handleCallback(callback, new MongoError(doc ? doc.$err : undefined)); - }); - } - - // Transform the doc with passed in transformation method if provided - if(self.cursorState.transforms && typeof self.cursorState.transforms.doc == 'function') { - doc = self.cursorState.transforms.doc(doc); - } - - // Return the document - handleCallback(callback, null, doc); - } -} - -/** - * Retrieve the next document from the cursor - * @method - * @param {resultCallback} callback A callback function - */ -Cursor.prototype.next = function(callback) { - nextFunction(this, callback); -} - -module.exports = Cursor; diff --git a/ts-ticket-office-service/node_modules/mongodb-core/lib/error.js b/ts-ticket-office-service/node_modules/mongodb-core/lib/error.js deleted file mode 100644 index 31ede94d1..000000000 --- a/ts-ticket-office-service/node_modules/mongodb-core/lib/error.js +++ /dev/null @@ -1,44 +0,0 @@ -"use strict"; - -/** - * Creates a new MongoError - * @class - * @augments Error - * @param {string} message The error message - * @return {MongoError} A MongoError instance - */ -function MongoError(message) { - this.name = 'MongoError'; - this.message = message; - Error.captureStackTrace(this, MongoError); -} - -/** - * Creates a new MongoError object - * @method - * @param {object} options The error options - * @return {MongoError} A MongoError instance - */ -MongoError.create = function(options) { - var err = null; - - if(options instanceof Error) { - err = new MongoError(options.message); - err.stack = options.stack; - } else if(typeof options == 'string') { - err = new MongoError(options); - } else { - err = new MongoError(options.message || options.errmsg || options.$err || "n/a"); - // Other options - for(var name in options) { - err[name] = options[name]; - } - } - - return err; -} - -// Extend JavaScript error -MongoError.prototype = new Error; - -module.exports = MongoError; diff --git a/ts-ticket-office-service/node_modules/mongodb-core/lib/tools/smoke_plugin.js b/ts-ticket-office-service/node_modules/mongodb-core/lib/tools/smoke_plugin.js deleted file mode 100644 index dcceda4bc..000000000 --- a/ts-ticket-office-service/node_modules/mongodb-core/lib/tools/smoke_plugin.js +++ /dev/null @@ -1,59 +0,0 @@ -var fs = require('fs'); - -/* Note: because this plugin uses process.on('uncaughtException'), only one - * of these can exist at any given time. This plugin and anything else that - * uses process.on('uncaughtException') will conflict. */ -exports.attachToRunner = function(runner, outputFile) { - var smokeOutput = { results : [] }; - var runningTests = {}; - - var integraPlugin = { - beforeTest: function(test, callback) { - test.startTime = Date.now(); - runningTests[test.name] = test; - callback(); - }, - afterTest: function(test, callback) { - smokeOutput.results.push({ - status: test.status, - start: test.startTime, - end: Date.now(), - test_file: test.name, - exit_code: 0, - url: "" - }); - delete runningTests[test.name]; - callback(); - }, - beforeExit: function(obj, callback) { - fs.writeFile(outputFile, JSON.stringify(smokeOutput), function() { - callback(); - }); - } - }; - - // In case of exception, make sure we write file - process.on('uncaughtException', function(err) { - // Mark all currently running tests as failed - for (var testName in runningTests) { - smokeOutput.results.push({ - status: "fail", - start: runningTests[testName].startTime, - end: Date.now(), - test_file: testName, - exit_code: 0, - url: "" - }); - } - - // write file - fs.writeFileSync(outputFile, JSON.stringify(smokeOutput)); - - // Standard NodeJS uncaught exception handler - console.error(err.stack); - process.exit(1); - }); - - runner.plugin(integraPlugin); - return integraPlugin; -}; diff --git a/ts-ticket-office-service/node_modules/mongodb-core/lib/topologies/mongos.js b/ts-ticket-office-service/node_modules/mongodb-core/lib/topologies/mongos.js deleted file mode 100644 index 2717916fa..000000000 --- a/ts-ticket-office-service/node_modules/mongodb-core/lib/topologies/mongos.js +++ /dev/null @@ -1,1307 +0,0 @@ -"use strict" - -var inherits = require('util').inherits, - f = require('util').format, - EventEmitter = require('events').EventEmitter, - BasicCursor = require('../cursor'), - Logger = require('../connection/logger'), - retrieveBSON = require('../connection/utils').retrieveBSON, - MongoError = require('../error'), - Server = require('./server'), - assign = require('../utils').assign, - clone = require('./shared').clone, - sdam = require('./shared'), - diff = require('./shared').diff, - cloneOptions = require('./shared').cloneOptions, - createClientInfo = require('./shared').createClientInfo; - -var BSON = retrieveBSON(); - -/** - * @fileOverview The **Mongos** class is a class that represents a Mongos Proxy topology and is - * used to construct connections. - * - * @example - * var Mongos = require('mongodb-core').Mongos - * , ReadPreference = require('mongodb-core').ReadPreference - * , assert = require('assert'); - * - * var server = new Mongos([{host: 'localhost', port: 30000}]); - * // Wait for the connection event - * server.on('connect', function(server) { - * server.destroy(); - * }); - * - * // Start connecting - * server.connect(); - */ - -var MongoCR = require('../auth/mongocr') - , X509 = require('../auth/x509') - , Plain = require('../auth/plain') - , GSSAPI = require('../auth/gssapi') - , SSPI = require('../auth/sspi') - , ScramSHA1 = require('../auth/scram'); - -// -// States -var DISCONNECTED = 'disconnected'; -var CONNECTING = 'connecting'; -var CONNECTED = 'connected'; -var UNREFERENCED = 'unreferenced'; -var DESTROYED = 'destroyed'; - -function stateTransition(self, newState) { - var legalTransitions = { - 'disconnected': [CONNECTING, DESTROYED, DISCONNECTED], - 'connecting': [CONNECTING, DESTROYED, CONNECTED, DISCONNECTED], - 'connected': [CONNECTED, DISCONNECTED, DESTROYED, UNREFERENCED], - 'unreferenced': [UNREFERENCED, DESTROYED], - 'destroyed': [DESTROYED] - } - - // Get current state - var legalStates = legalTransitions[self.state]; - if(legalStates && legalStates.indexOf(newState) != -1) { - self.state = newState; - } else { - self.logger.error(f('Pool with id [%s] failed attempted illegal state transition from [%s] to [%s] only following state allowed [%s]' - , self.id, self.state, newState, legalStates)); - } -} - -// -// ReplSet instance id -var id = 1; -var handlers = ['connect', 'close', 'error', 'timeout', 'parseError']; - -/** - * Creates a new Mongos instance - * @class - * @param {array} seedlist A list of seeds for the replicaset - * @param {number} [options.haInterval=5000] The High availability period for replicaset inquiry - * @param {Cursor} [options.cursorFactory=Cursor] The cursor factory class used for all query cursors - * @param {number} [options.size=5] Server connection pool size - * @param {boolean} [options.keepAlive=true] TCP Connection keep alive enabled - * @param {number} [options.keepAliveInitialDelay=0] Initial delay before TCP keep alive enabled - * @param {number} [options.localThresholdMS=15] Cutoff latency point in MS for MongoS proxy selection - * @param {boolean} [options.noDelay=true] TCP Connection no delay - * @param {number} [options.connectionTimeout=1000] TCP Connection timeout setting - * @param {number} [options.socketTimeout=0] TCP Socket timeout setting - * @param {boolean} [options.singleBufferSerializtion=true] Serialize into single buffer, trade of peak memory for serialization speed - * @param {boolean} [options.ssl=false] Use SSL for connection - * @param {boolean|function} [options.checkServerIdentity=true] Ensure we check server identify during SSL, set to false to disable checking. Only works for Node 0.12.x or higher. You can pass in a boolean or your own checkServerIdentity override function. - * @param {Buffer} [options.ca] SSL Certificate store binary buffer - * @param {Buffer} [options.crl] SSL Certificate revocation store binary buffer - * @param {Buffer} [options.cert] SSL Certificate binary buffer - * @param {Buffer} [options.key] SSL Key file binary buffer - * @param {string} [options.passphrase] SSL Certificate pass phrase - * @param {string} [options.servername=null] String containing the server name requested via TLS SNI. - * @param {boolean} [options.rejectUnauthorized=true] Reject unauthorized server certificates - * @param {boolean} [options.promoteLongs=true] Convert Long values from the db into Numbers if they fit into 53 bits - * @param {boolean} [options.promoteValues=true] Promotes BSON values to native types where possible, set to false to only receive wrapper types. - * @param {boolean} [options.promoteBuffers=false] Promotes Binary BSON values to native Node Buffers. - * @param {boolean} [options.domainsEnabled=false] Enable the wrapping of the callback in the current entity, disabled by default to avoid perf hit. - * @return {Mongos} A cursor instance - * @fires Mongos#connect - * @fires Mongos#reconnect - * @fires Mongos#joined - * @fires Mongos#left - * @fires Mongos#failed - * @fires Mongos#fullsetup - * @fires Mongos#all - * @fires Mongos#serverHeartbeatStarted - * @fires Mongos#serverHeartbeatSucceeded - * @fires Mongos#serverHeartbeatFailed - * @fires Mongos#topologyOpening - * @fires Mongos#topologyClosed - * @fires Mongos#topologyDescriptionChanged - * @property {string} type the topology type. - * @property {string} parserType the parser type used (c++ or js). - */ -var Mongos = function(seedlist, options) { - options = options || {}; - - // Get replSet Id - this.id = id++; - - // Internal state - this.s = { - options: assign({}, options), - // BSON instance - bson: options.bson || new BSON([BSON.Binary, BSON.Code, BSON.DBRef, BSON.Decimal128, - BSON.Double, BSON.Int32, BSON.Long, BSON.Map, BSON.MaxKey, BSON.MinKey, - BSON.ObjectId, BSON.BSONRegExp, BSON.Symbol, BSON.Timestamp]), - // Factory overrides - Cursor: options.cursorFactory || BasicCursor, - // Logger instance - logger: Logger('Mongos', options), - // Seedlist - seedlist: seedlist, - // Ha interval - haInterval: options.haInterval ? options.haInterval : 10000, - // Disconnect handler - disconnectHandler: options.disconnectHandler, - // Server selection index - index: 0, - // Connect function options passed in - connectOptions: {}, - // Are we running in debug mode - debug: typeof options.debug == 'boolean' ? options.debug : false, - // localThresholdMS - localThresholdMS: options.localThresholdMS || 15, - // Client info - clientInfo: createClientInfo(options), - // Authentication context - authenticationContexts: [], - } - - // Set the client info - this.s.options.clientInfo = createClientInfo(options); - - // Log info warning if the socketTimeout < haInterval as it will cause - // a lot of recycled connections to happen. - if(this.s.logger.isWarn() - && this.s.options.socketTimeout != 0 - && this.s.options.socketTimeout < this.s.haInterval) { - this.s.logger.warn(f('warning socketTimeout %s is less than haInterval %s. This might cause unnecessary server reconnections due to socket timeouts' - , this.s.options.socketTimeout, this.s.haInterval)); - } - - // All the authProviders - this.authProviders = options.authProviders || { - 'mongocr': new MongoCR(this.s.bson), 'x509': new X509(this.s.bson) - , 'plain': new Plain(this.s.bson), 'gssapi': new GSSAPI(this.s.bson) - , 'sspi': new SSPI(this.s.bson), 'scram-sha-1': new ScramSHA1(this.s.bson) - } - - // Disconnected state - this.state = DISCONNECTED; - - // Current proxies we are connecting to - this.connectingProxies = []; - // Currently connected proxies - this.connectedProxies = []; - // Disconnected proxies - this.disconnectedProxies = []; - // Are we authenticating - this.authenticating = false; - // Index of proxy to run operations against - this.index = 0; - // High availability timeout id - this.haTimeoutId = null; - // Last ismaster - this.ismaster = null; - - // Description of the Replicaset - this.topologyDescription = { - "topologyType": "Unknown", "servers": [] - }; - - // Add event listener - EventEmitter.call(this); -} - -inherits(Mongos, EventEmitter); - -Object.defineProperty(Mongos.prototype, 'type', { - enumerable:true, get: function() { return 'mongos'; } -}); - -Object.defineProperty(Mongos.prototype, 'parserType', { - enumerable:true, get: function() { - return BSON.native ? "c++" : "js"; - } -}); - -/** - * Emit event if it exists - * @method - */ -function emitSDAMEvent(self, event, description) { - if(self.listeners(event).length > 0) { - self.emit(event, description); - } -} - -/** - * Initiate server connect - * @method - * @param {array} [options.auth=null] Array of auth options to apply on connect - */ -Mongos.prototype.connect = function(options) { - var self = this; - // Add any connect level options to the internal state - this.s.connectOptions = options || {}; - // Set connecting state - stateTransition(this, CONNECTING); - // Create server instances - var servers = this.s.seedlist.map(function(x) { - return new Server(assign({}, self.s.options, x, { - authProviders: self.authProviders, reconnect:false, monitoring:false, inTopology: true - }, { - clientInfo: clone(self.s.clientInfo) - })); - }); - - servers.forEach(function(server) { - server.on('serverDescriptionChanged', function(event) { self.emit('serverDescriptionChanged', event); }); - }); - - // Emit the topology opening event - emitSDAMEvent(this, 'topologyOpening', { topologyId: this.id }); - - // Start all server connections - connectProxies(self, servers); -} - -function handleEvent(self) { - return function() { - if(self.state == DESTROYED) return; - // Move to list of disconnectedProxies - moveServerFrom(self.connectedProxies, self.disconnectedProxies, this); - // Emit the initial topology - emitTopologyDescriptionChanged(self); - // Emit the left signal - self.emit('left', 'mongos', this); - // Emit the sdam event - self.emit('serverClosed', { - topologyId: self.id, - address: this.name - }); - } -} - -function handleInitialConnectEvent(self, event) { - return function() { - var _this = this; - - // Destroy the instance - if(self.state == DESTROYED) { - // Emit the initial topology - emitTopologyDescriptionChanged(self); - // Move from connectingProxies - moveServerFrom(self.connectingProxies, self.disconnectedProxies, this); - return this.destroy(); - } - - // Check the type of server - if(event == 'connect') { - // Do we have authentication contexts that need to be applied - applyAuthenticationContexts(self, _this, function() { - // Get last known ismaster - self.ismaster = _this.lastIsMaster(); - - // Is this not a proxy, remove t - if(self.ismaster.msg == 'isdbgrid') { - // Add to the connectd list - for(var i = 0; i < self.connectedProxies.length; i++) { - if(self.connectedProxies[i].name == _this.name) { - // Move from connectingProxies - moveServerFrom(self.connectingProxies, self.disconnectedProxies, _this); - // Emit the initial topology - emitTopologyDescriptionChanged(self); - _this.destroy(); - return self.emit('failed', _this); - } - } - - // Remove the handlers - for(i = 0; i < handlers.length; i++) { - _this.removeAllListeners(handlers[i]); - } - - // Add stable state handlers - _this.on('error', handleEvent(self, 'error')); - _this.on('close', handleEvent(self, 'close')); - _this.on('timeout', handleEvent(self, 'timeout')); - _this.on('parseError', handleEvent(self, 'parseError')); - - // Move from connecting proxies connected - moveServerFrom(self.connectingProxies, self.connectedProxies, _this); - // Emit the joined event - self.emit('joined', 'mongos', _this); - } else { - - // Print warning if we did not find a mongos proxy - if(self.s.logger.isWarn()) { - var message = 'expected mongos proxy, but found replicaset member mongod for server %s'; - // We have a standalone server - if(!self.ismaster.hosts) { - message = 'expected mongos proxy, but found standalone mongod for server %s'; - } - - self.s.logger.warn(f(message, _this.name)); - } - - // This is not a mongos proxy, remove it completely - removeProxyFrom(self.connectingProxies, _this); - // Emit the left event - self.emit('left', 'server', _this); - // Emit failed event - self.emit('failed', _this); - } - }); - } else { - moveServerFrom(self.connectingProxies, self.disconnectedProxies, this); - // Emit the left event - self.emit('left', 'mongos', this); - // Emit failed event - self.emit('failed', this); - } - - // Emit the initial topology - emitTopologyDescriptionChanged(self); - - // Trigger topologyMonitor - if(self.connectingProxies.length == 0) { - // Emit connected if we are connected - if(self.connectedProxies.length > 0) { - // Set the state to connected - stateTransition(self, CONNECTED); - // Emit the connect event - self.emit('connect', self); - self.emit('fullsetup', self); - self.emit('all', self); - } else if(self.disconnectedProxies.length == 0) { - // Print warning if we did not find a mongos proxy - if(self.s.logger.isWarn()) { - self.s.logger.warn(f('no mongos proxies found in seed list, did you mean to connect to a replicaset')); - } - - // Emit the error that no proxies were found - return self.emit('error', new MongoError('no mongos proxies found in seed list')); - } - - // Topology monitor - topologyMonitor(self, {firstConnect:true}); - } - }; -} - -function connectProxies(self, servers) { - // Update connectingProxies - self.connectingProxies = self.connectingProxies.concat(servers); - - // Index used to interleaf the server connects, avoiding - // runtime issues on io constrained vm's - var timeoutInterval = 0; - - function connect(server, timeoutInterval) { - setTimeout(function() { - // Emit opening server event - self.emit('serverOpening', { - topologyId: self.id, - address: server.name - }); - - // Emit the initial topology - emitTopologyDescriptionChanged(self); - - // Add event handlers - server.once('close', handleInitialConnectEvent(self, 'close')); - server.once('timeout', handleInitialConnectEvent(self, 'timeout')); - server.once('parseError', handleInitialConnectEvent(self, 'parseError')); - server.once('error', handleInitialConnectEvent(self, 'error')); - server.once('connect', handleInitialConnectEvent(self, 'connect')); - // Start connection - server.connect(self.s.connectOptions); - }, timeoutInterval); - } - // Start all the servers - while(servers.length > 0) { - connect(servers.shift(), timeoutInterval++); - } -} - -function pickProxy(self) { - // Get the currently connected Proxies - var connectedProxies = self.connectedProxies.slice(0); - - // Set lower bound - var lowerBoundLatency = Number.MAX_VALUE; - - // Determine the lower bound for the Proxies - for(var i = 0; i < connectedProxies.length; i++) { - if(connectedProxies[i].lastIsMasterMS < lowerBoundLatency) { - lowerBoundLatency = connectedProxies[i].lastIsMasterMS; - } - } - - // Filter out the possible servers - connectedProxies = connectedProxies.filter(function(server) { - if((server.lastIsMasterMS <= (lowerBoundLatency + self.s.localThresholdMS)) - && server.isConnected()) { - return true; - } - }); - - // We have no connectedProxies pick first of the connected ones - if(connectedProxies.length == 0) { - return self.connectedProxies[0]; - } - - // Get proxy - var proxy = connectedProxies[self.index % connectedProxies.length]; - // Update the index - self.index = (self.index + 1) % connectedProxies.length; - // Return the proxy - return proxy; -} - -function moveServerFrom(from, to, proxy) { - for(var i = 0; i < from.length; i++) { - if(from[i].name == proxy.name) { - from.splice(i, 1); - } - } - - for(i = 0; i < to.length; i++) { - if(to[i].name == proxy.name) { - to.splice(i, 1); - } - } - - to.push(proxy); -} - -function removeProxyFrom(from, proxy) { - for(var i = 0; i < from.length; i++) { - if(from[i].name == proxy.name) { - from.splice(i, 1); - } - } -} - -function reconnectProxies(self, proxies, callback) { - // Count lefts - var count = proxies.length; - - // Handle events - var _handleEvent = function(self, event) { - return function() { - var _self = this; - count = count - 1; - - // Destroyed - if(self.state == DESTROYED || self.state == UNREFERENCED) { - moveServerFrom(self.connectingProxies, self.disconnectedProxies, _self); - // Return destroy - return this.destroy(); - } - - if(event == 'connect' && !self.authenticating) { - // Do we have authentication contexts that need to be applied - applyAuthenticationContexts(self, _self, function() { - // Destroyed - if(self.state == DESTROYED || self.state == UNREFERENCED) { - moveServerFrom(self.connectingProxies, self.disconnectedProxies, _self); - return _self.destroy(); - } - - // Remove the handlers - for(var i = 0; i < handlers.length; i++) { - _self.removeAllListeners(handlers[i]); - } - - // Add stable state handlers - _self.on('error', handleEvent(self, 'error')); - _self.on('close', handleEvent(self, 'close')); - _self.on('timeout', handleEvent(self, 'timeout')); - _self.on('parseError', handleEvent(self, 'parseError')); - - // Move to the connected servers - moveServerFrom(self.disconnectedProxies, self.connectedProxies, _self); - // Emit topology Change - emitTopologyDescriptionChanged(self); - // Emit joined event - self.emit('joined', 'mongos', _self); - }); - } else if(event == 'connect' && self.authenticating) { - // Move from connectingProxies - moveServerFrom(self.connectingProxies, self.disconnectedProxies, _self); - this.destroy(); - } - - // Are we done finish up callback - if(count == 0) { - callback(); - } - } - } - - // No new servers - if(count == 0) { - return callback(); - } - - // Execute method - function execute(_server, i) { - setTimeout(function() { - // Destroyed - if(self.state == DESTROYED || self.state == UNREFERENCED) { - return; - } - - // Create a new server instance - var server = new Server(assign({}, self.s.options, { - host: _server.name.split(':')[0], - port: parseInt(_server.name.split(':')[1], 10) - }, { - authProviders: self.authProviders, reconnect:false, monitoring: false, inTopology: true - }, { - clientInfo: clone(self.s.clientInfo) - })); - - // Relay the server description change - server.on('serverDescriptionChanged', function(event) { self.emit('serverDescriptionChanged', event); }); - - // Emit opening server event - self.emit('serverOpening', { - topologyId: server.s.topologyId != -1 ? server.s.topologyId : self.id, - address: server.name - }); - - // Add temp handlers - server.once('connect', _handleEvent(self, 'connect')); - server.once('close', _handleEvent(self, 'close')); - server.once('timeout', _handleEvent(self, 'timeout')); - server.once('error', _handleEvent(self, 'error')); - server.once('parseError', _handleEvent(self, 'parseError')); - - // Connect to proxy - server.connect(self.s.connectOptions); - }, i); - } - - // Create new instances - for(var i = 0; i < proxies.length; i++) { - execute(proxies[i], i); - } -} - -function applyAuthenticationContexts(self, server, callback) { - if(self.s.authenticationContexts.length == 0) { - return callback(); - } - - // Copy contexts to ensure no modificiation in the middle of - // auth process. - var authContexts = self.s.authenticationContexts.slice(0); - - // Apply one of the contexts - function applyAuth(authContexts, server, callback) { - if(authContexts.length == 0) return callback(); - // Get the first auth context - var authContext = authContexts.shift(); - // Copy the params - var customAuthContext = authContext.slice(0); - // Push our callback handler - customAuthContext.push(function(err) { - applyAuth(authContexts, server, callback); - }); - - // Attempt authentication - server.auth.apply(server, customAuthContext) - } - - // Apply all auth contexts - applyAuth(authContexts, server, callback); -} - -function topologyMonitor(self, options) { - options = options || {}; - - // Set momitoring timeout - self.haTimeoutId = setTimeout(function() { - if(self.state == DESTROYED || self.state == UNREFERENCED) return; - // If we have a primary and a disconnect handler, execute - // buffered operations - if(self.isConnected() && self.s.disconnectHandler) { - self.s.disconnectHandler.execute(); - } - - // Get the connectingServers - var proxies = self.connectedProxies.slice(0); - // Get the count - var count = proxies.length; - - // If the count is zero schedule a new fast - function pingServer(_self, _server, cb) { - // Measure running time - var start = new Date().getTime(); - - // Emit the server heartbeat start - emitSDAMEvent(self, 'serverHeartbeatStarted', { connectionId: _server.name }); - - // Execute ismaster - _server.command('admin.$cmd', { - ismaster:true - }, { - monitoring: true, - socketTimeout: self.s.options.connectionTimeout || 2000, - }, function(err, r) { - if(self.state == DESTROYED || self.state == UNREFERENCED) { - // Move from connectingProxies - moveServerFrom(self.connectedProxies, self.disconnectedProxies, _server); - _server.destroy(); - return cb(err, r); - } - - // Calculate latency - var latencyMS = new Date().getTime() - start; - - // We had an error, remove it from the state - if(err) { - // Emit the server heartbeat failure - emitSDAMEvent(self, 'serverHeartbeatFailed', { durationMS: latencyMS, failure: err, connectionId: _server.name }); - // Move from connected proxies to disconnected proxies - moveServerFrom(self.connectedProxies, self.disconnectedProxies, _server); - } else { - // Update the server ismaster - _server.ismaster = r.result; - _server.lastIsMasterMS = latencyMS; - - // Server heart beat event - emitSDAMEvent(self, 'serverHeartbeatSucceeded', { durationMS: latencyMS, reply: r.result, connectionId: _server.name }); - } - - cb(err, r); - }); - } - - // No proxies initiate monitor again - if(proxies.length == 0) { - // Emit close event if any listeners registered - if(self.listeners("close").length > 0 && self.state == CONNECTING) { - self.emit('error', new MongoError('no mongos proxy available')); - } else { - self.emit('close', self); - } - - // Attempt to connect to any unknown servers - return reconnectProxies(self, self.disconnectedProxies, function() { - if(self.state == DESTROYED || self.state == UNREFERENCED) return; - - // Are we connected ? emit connect event - if(self.state == CONNECTING && options.firstConnect) { - self.emit('connect', self); - self.emit('fullsetup', self); - self.emit('all', self); - } else if(self.isConnected()) { - self.emit('reconnect', self); - } else if(!self.isConnected() && self.listeners("close").length > 0) { - self.emit('close', self); - } - - // Perform topology monitor - topologyMonitor(self); - }); - } - - // Ping all servers - for(var i = 0; i < proxies.length; i++) { - pingServer(self, proxies[i], function() { - count = count - 1; - - if(count == 0) { - if(self.state == DESTROYED || self.state == UNREFERENCED) return; - - // Attempt to connect to any unknown servers - reconnectProxies(self, self.disconnectedProxies, function() { - if(self.state == DESTROYED || self.state == UNREFERENCED) return; - // Perform topology monitor - topologyMonitor(self); - }); - } - }); - } - }, self.s.haInterval); -} - -/** - * Returns the last known ismaster document for this server - * @method - * @return {object} - */ -Mongos.prototype.lastIsMaster = function() { - return this.ismaster; -} - -/** - * Unref all connections belong to this server - * @method - */ -Mongos.prototype.unref = function() { - // Transition state - stateTransition(this, UNREFERENCED); - // Get all proxies - var proxies = this.connectedProxies.concat(this.connectingProxies); - proxies.forEach(function(x) { - x.unref(); - }); - - clearTimeout(this.haTimeoutId); -} - -/** - * Destroy the server connection - * @param {boolean} [options.force=false] Force destroy the pool - * @method - */ -Mongos.prototype.destroy = function(options) { - var self = this; - // Transition state - stateTransition(this, DESTROYED); - // Get all proxies - var proxies = this.connectedProxies.concat(this.connectingProxies); - // Clear out any monitoring process - if(this.haTimeoutId) clearTimeout(this.haTimeoutId); - // Clear out authentication contexts - this.s.authenticationContexts = []; - - // Destroy all connecting servers - proxies.forEach(function(x) { - // Emit the sdam event - self.emit('serverClosed', { - topologyId: self.id, - address: x.name - }); - - // Destroy the server - x.destroy(options); - // Move to list of disconnectedProxies - moveServerFrom(self.connectedProxies, self.disconnectedProxies, x); - }); - - // Emit the final topology change - emitTopologyDescriptionChanged(self); - // Emit toplogy closing event - emitSDAMEvent(this, 'topologyClosed', { topologyId: this.id }); -} - -/** - * Figure out if the server is connected - * @method - * @return {boolean} - */ -Mongos.prototype.isConnected = function() { - return this.connectedProxies.length > 0; -} - -/** - * Figure out if the server instance was destroyed by calling destroy - * @method - * @return {boolean} - */ -Mongos.prototype.isDestroyed = function() { - return this.state == DESTROYED; -} - -// -// Operations -// - -// Execute write operation -var executeWriteOperation = function(self, op, ns, ops, options, callback) { - if(typeof options == 'function') callback = options, options = {}, options = options || {}; - // Ensure we have no options - options = options || {}; - // Pick a server - var server = pickProxy(self); - // No server found error out - if(!server) return callback(new MongoError('no mongos proxy available')); - // Execute the command - server[op](ns, ops, options, callback); -} - -/** - * Insert one or more documents - * @method - * @param {string} ns The MongoDB fully qualified namespace (ex: db1.collection1) - * @param {array} ops An array of documents to insert - * @param {boolean} [options.ordered=true] Execute in order or out of order - * @param {object} [options.writeConcern={}] Write concern for the operation - * @param {Boolean} [options.serializeFunctions=false] Specify if functions on an object should be serialized. - * @param {Boolean} [options.ignoreUndefined=false] Specify if the BSON serializer should ignore undefined fields. - * @param {opResultCallback} callback A callback function - */ -Mongos.prototype.insert = function(ns, ops, options, callback) { - if(typeof options == 'function') callback = options, options = {}, options = options || {}; - if(this.state == DESTROYED) return callback(new MongoError(f('topology was destroyed'))); - - // Not connected but we have a disconnecthandler - if(!this.isConnected() && this.s.disconnectHandler != null) { - return this.s.disconnectHandler.add('insert', ns, ops, options, callback); - } - - // No mongos proxy available - if(!this.isConnected()) { - return callback(new MongoError('no mongos proxy available')); - } - - // Execute write operation - executeWriteOperation(this, 'insert', ns, ops, options, callback); -} - -/** - * Perform one or more update operations - * @method - * @param {string} ns The MongoDB fully qualified namespace (ex: db1.collection1) - * @param {array} ops An array of updates - * @param {boolean} [options.ordered=true] Execute in order or out of order - * @param {object} [options.writeConcern={}] Write concern for the operation - * @param {Boolean} [options.serializeFunctions=false] Specify if functions on an object should be serialized. - * @param {Boolean} [options.ignoreUndefined=false] Specify if the BSON serializer should ignore undefined fields. - * @param {opResultCallback} callback A callback function - */ -Mongos.prototype.update = function(ns, ops, options, callback) { - if(typeof options == 'function') callback = options, options = {}, options = options || {}; - if(this.state == DESTROYED) return callback(new MongoError(f('topology was destroyed'))); - - // Not connected but we have a disconnecthandler - if(!this.isConnected() && this.s.disconnectHandler != null) { - return this.s.disconnectHandler.add('update', ns, ops, options, callback); - } - - // No mongos proxy available - if(!this.isConnected()) { - return callback(new MongoError('no mongos proxy available')); - } - - // Execute write operation - executeWriteOperation(this, 'update', ns, ops, options, callback); -} - -/** - * Perform one or more remove operations - * @method - * @param {string} ns The MongoDB fully qualified namespace (ex: db1.collection1) - * @param {array} ops An array of removes - * @param {boolean} [options.ordered=true] Execute in order or out of order - * @param {object} [options.writeConcern={}] Write concern for the operation - * @param {Boolean} [options.serializeFunctions=false] Specify if functions on an object should be serialized. - * @param {Boolean} [options.ignoreUndefined=false] Specify if the BSON serializer should ignore undefined fields. - * @param {opResultCallback} callback A callback function - */ -Mongos.prototype.remove = function(ns, ops, options, callback) { - if(typeof options == 'function') callback = options, options = {}, options = options || {}; - if(this.state == DESTROYED) return callback(new MongoError(f('topology was destroyed'))); - - // Not connected but we have a disconnecthandler - if(!this.isConnected() && this.s.disconnectHandler != null) { - return this.s.disconnectHandler.add('remove', ns, ops, options, callback); - } - - // No mongos proxy available - if(!this.isConnected()) { - return callback(new MongoError('no mongos proxy available')); - } - - // Execute write operation - executeWriteOperation(this, 'remove', ns, ops, options, callback); -} - -/** - * Execute a command - * @method - * @param {string} ns The MongoDB fully qualified namespace (ex: db1.collection1) - * @param {object} cmd The command hash - * @param {ReadPreference} [options.readPreference] Specify read preference if command supports it - * @param {Connection} [options.connection] Specify connection object to execute command against - * @param {Boolean} [options.serializeFunctions=false] Specify if functions on an object should be serialized. - * @param {Boolean} [options.ignoreUndefined=false] Specify if the BSON serializer should ignore undefined fields. - * @param {opResultCallback} callback A callback function - */ -Mongos.prototype.command = function(ns, cmd, options, callback) { - if(typeof options == 'function') callback = options, options = {}, options = options || {}; - if(this.state == DESTROYED) return callback(new MongoError(f('topology was destroyed'))); - var self = this; - - // Pick a proxy - var server = pickProxy(self); - - // Topology is not connected, save the call in the provided store to be - // Executed at some point when the handler deems it's reconnected - if((server == null || !server.isConnected()) && this.s.disconnectHandler != null) { - return this.s.disconnectHandler.add('command', ns, cmd, options, callback); - } - - // No server returned we had an error - if(server == null) { - return callback(new MongoError('no mongos proxy available')); - } - - // Cloned options - var clonedOptions = cloneOptions(options); - clonedOptions.topology = self; - - // Execute the command - server.command(ns, cmd, clonedOptions, callback); -} - -/** - * Perform one or more remove operations - * @method - * @param {string} ns The MongoDB fully qualified namespace (ex: db1.collection1) - * @param {{object}|{Long}} cmd Can be either a command returning a cursor or a cursorId - * @param {object} [options.batchSize=0] Batchsize for the operation - * @param {array} [options.documents=[]] Initial documents list for cursor - * @param {ReadPreference} [options.readPreference] Specify read preference if command supports it - * @param {Boolean} [options.serializeFunctions=false] Specify if functions on an object should be serialized. - * @param {Boolean} [options.ignoreUndefined=false] Specify if the BSON serializer should ignore undefined fields. - * @param {opResultCallback} callback A callback function - */ -Mongos.prototype.cursor = function(ns, cmd, cursorOptions) { - cursorOptions = cursorOptions || {}; - var FinalCursor = cursorOptions.cursorFactory || this.s.Cursor; - return new FinalCursor(this.s.bson, ns, cmd, cursorOptions, this, this.s.options); -} - -/** - * Authenticate using a specified mechanism - * @method - * @param {string} mechanism The Auth mechanism we are invoking - * @param {string} db The db we are invoking the mechanism against - * @param {...object} param Parameters for the specific mechanism - * @param {authResultCallback} callback A callback function - */ -Mongos.prototype.auth = function(mechanism, db) { - var allArgs = Array.prototype.slice.call(arguments, 0).slice(0); - var self = this; - var args = Array.prototype.slice.call(arguments, 2); - var callback = args.pop(); - var currentContextIndex = 0; - - // If we don't have the mechanism fail - if(this.authProviders[mechanism] == null && mechanism != 'default') { - return callback(new MongoError(f("auth provider %s does not exist", mechanism))); - } - - // Are we already authenticating, throw - if(this.authenticating) { - return callback(new MongoError('authentication or logout allready in process')); - } - - // Topology is not connected, save the call in the provided store to be - // Executed at some point when the handler deems it's reconnected - if(!self.isConnected() && self.s.disconnectHandler != null) { - return self.s.disconnectHandler.add('auth', db, allArgs, {}, callback); - } - - // Set to authenticating - this.authenticating = true; - // All errors - var errors = []; - - // Get all the servers - var servers = this.connectedProxies.slice(0); - // No servers return - if(servers.length == 0) { - this.authenticating = false; - callback(null, true); - } - - // Authenticate - function auth(server) { - // Arguments without a callback - var argsWithoutCallback = [mechanism, db].concat(args.slice(0)); - // Create arguments - var finalArguments = argsWithoutCallback.concat([function(err) { - count = count - 1; - // Save all the errors - if(err) errors.push({name: server.name, err: err}); - // We are done - if(count == 0) { - // Auth is done - self.authenticating = false; - - // Return the auth error - if(errors.length) { - // Remove the entry from the stored authentication contexts - self.s.authenticationContexts.splice(currentContextIndex, 0); - // Return error - return callback(MongoError.create({ - message: 'authentication fail', errors: errors - }), false); - } - - // Successfully authenticated session - callback(null, self); - } - }]); - - // Execute the auth only against non arbiter servers - if(!server.lastIsMaster().arbiterOnly) { - server.auth.apply(server, finalArguments); - } - } - - // Save current context index - currentContextIndex = this.s.authenticationContexts.length; - // Store the auth context and return the last index - this.s.authenticationContexts.push([mechanism, db].concat(args.slice(0))); - - // Get total count - var count = servers.length; - // Authenticate against all servers - while(servers.length > 0) { - auth(servers.shift()); - } -} - -/** - * Logout from a database - * @method - * @param {string} db The db we are logging out from - * @param {authResultCallback} callback A callback function - */ -Mongos.prototype.logout = function(dbName, callback) { - var self = this; - // Are we authenticating or logging out, throw - if(this.authenticating) { - throw new MongoError('authentication or logout allready in process'); - } - - // Ensure no new members are processed while logging out - this.authenticating = true; - - // Remove from all auth providers (avoid any reaplication of the auth details) - var providers = Object.keys(this.authProviders); - for(var i = 0; i < providers.length; i++) { - this.authProviders[providers[i]].logout(dbName); - } - - // Now logout all the servers - var servers = this.connectedProxies.slice(0); - var count = servers.length; - if(count == 0) return callback(); - var errors = []; - - function logoutServer(_server, cb) { - _server.logout(dbName, function(err) { - if(err) errors.push({name: _server.name, err: err}); - cb(); - }); - } - - // Execute logout on all server instances - for(i = 0; i < servers.length; i++) { - logoutServer(servers[i], function() { - count = count - 1; - - if(count == 0) { - // Do not block new operations - self.authenticating = false; - // If we have one or more errors - if(errors.length) return callback(MongoError.create({ - message: f('logout failed against db %s', dbName), errors: errors - }), false); - - // No errors - callback(); - } - }) - } -} - -/** - * Get server - * @method - * @return {Server} - */ -Mongos.prototype.getServer = function() { - var server = pickProxy(this); - if(this.s.debug) this.emit('pickedServer', null, server); - return server; -} - -/** - * Get a direct connection - * @method - * @return {Connection} - */ -Mongos.prototype.getConnection = function() { - var server = this.getServer(); - if(server) return server.getConnection(); -} - -/** - * All raw connections - * @method - * @return {Connection[]} - */ -Mongos.prototype.connections = function() { - var connections = []; - - for(var i = 0; i < this.connectedProxies.length; i++) { - connections = connections.concat(this.connectedProxies[i].connections()); - } - - return connections; -} - -function emitTopologyDescriptionChanged(self) { - if(self.listeners('topologyDescriptionChanged').length > 0) { - var topology = 'Unknown'; - var setName = self.setName; - - if(self.connectedProxies.length > 0) { - topology = 'Sharded'; - } - - // Generate description - var description = { - topologyType: topology, - servers: [] - } - - // All proxies - var proxies = self.disconnectedProxies - .concat(self.connectingProxies); - - // Add all the disconnected proxies - description.servers = description.servers.concat(proxies.map(function(x) { - var description = x.getDescription(); - description.type = 'Unknown'; - return description; - })); - - // Add all the connected proxies - description.servers = description.servers.concat(self.connectedProxies.map(function(x) { - var description = x.getDescription(); - description.type = 'Mongos'; - return description; - })); - - // Get the diff - var diffResult = diff(self.topologyDescription, description); - - // Create the result - var result = { - topologyId: self.id, - previousDescription: self.topologyDescription, - newDescription: description, - diff: diffResult - }; - - // Emit the topologyDescription change - if(diffResult.servers.length > 0) { - self.emit('topologyDescriptionChanged', result); - } - - // Set the new description - self.topologyDescription = description; - } -} - -/** - * A mongos connect event, used to verify that the connection is up and running - * - * @event Mongos#connect - * @type {Mongos} - */ - -/** - * A mongos reconnect event, used to verify that the mongos topology has reconnected - * - * @event Mongos#reconnect - * @type {Mongos} - */ - -/** - * A mongos fullsetup event, used to signal that all topology members have been contacted. - * - * @event Mongos#fullsetup - * @type {Mongos} - */ - -/** - * A mongos all event, used to signal that all topology members have been contacted. - * - * @event Mongos#all - * @type {Mongos} - */ - -/** - * A server member left the mongos list - * - * @event Mongos#left - * @type {Mongos} - * @param {string} type The type of member that left (mongos) - * @param {Server} server The server object that left - */ - -/** - * A server member joined the mongos list - * - * @event Mongos#joined - * @type {Mongos} - * @param {string} type The type of member that left (mongos) - * @param {Server} server The server object that joined - */ - -/** - * A server opening SDAM monitoring event - * - * @event Mongos#serverOpening - * @type {object} - */ - -/** - * A server closed SDAM monitoring event - * - * @event Mongos#serverClosed - * @type {object} - */ - -/** - * A server description SDAM change monitoring event - * - * @event Mongos#serverDescriptionChanged - * @type {object} - */ - -/** - * A topology open SDAM event - * - * @event Mongos#topologyOpening - * @type {object} - */ - -/** - * A topology closed SDAM event - * - * @event Mongos#topologyClosed - * @type {object} - */ - -/** - * A topology structure SDAM change event - * - * @event Mongos#topologyDescriptionChanged - * @type {object} - */ - -/** - * A topology serverHeartbeatStarted SDAM event - * - * @event Mongos#serverHeartbeatStarted - * @type {object} - */ - -/** - * A topology serverHeartbeatFailed SDAM event - * - * @event Mongos#serverHeartbeatFailed - * @type {object} - */ - -/** - * A topology serverHeartbeatSucceeded SDAM change event - * - * @event Mongos#serverHeartbeatSucceeded - * @type {object} - */ - -module.exports = Mongos; diff --git a/ts-ticket-office-service/node_modules/mongodb-core/lib/topologies/read_preference.js b/ts-ticket-office-service/node_modules/mongodb-core/lib/topologies/read_preference.js deleted file mode 100644 index 1f10dd97e..000000000 --- a/ts-ticket-office-service/node_modules/mongodb-core/lib/topologies/read_preference.js +++ /dev/null @@ -1,118 +0,0 @@ -"use strict"; - -var needSlaveOk = ['primaryPreferred', 'secondary', 'secondaryPreferred', 'nearest']; - -/** - * @fileOverview The **ReadPreference** class is a class that represents a MongoDB ReadPreference and is - * used to construct connections. - * - * @example - * var ReplSet = require('mongodb-core').ReplSet - * , ReadPreference = require('mongodb-core').ReadPreference - * , assert = require('assert'); - * - * var server = new ReplSet([{host: 'localhost', port: 30000}], {setName: 'rs'}); - * // Wait for the connection event - * server.on('connect', function(server) { - * var cursor = server.cursor('db.test' - * , {find: 'db.test', query: {}} - * , {readPreference: new ReadPreference('secondary')}); - * cursor.next(function(err, doc) { - * server.destroy(); - * }); - * }); - * - * // Start connecting - * server.connect(); - */ - -/** - * Creates a new Pool instance - * @class - * @param {string} preference A string describing the preference (primary|primaryPreferred|secondary|secondaryPreferred|nearest) - * @param {array} tags The tags object - * @param {object} [options] Additional read preference options - * @param {number} [options.maxStalenessSeconds] Max Secondary Read Stalleness in Seconds, Minimum value is 90 seconds. - * @property {string} preference The preference string (primary|primaryPreferred|secondary|secondaryPreferred|nearest) - * @property {array} tags The tags object - * @property {object} options Additional read preference options - * @property {number} maxStalenessSeconds MaxStalenessSeconds value for the read preference - * @return {ReadPreference} - */ -var ReadPreference = function(preference, tags, options) { - this.preference = preference; - this.tags = tags; - this.options = options; - - // Add the maxStalenessSeconds value to the read Preference - if(this.options && this.options.maxStalenessSeconds != null) { - this.options = options; - this.maxStalenessSeconds = this.options.maxStalenessSeconds >= 0 - ? this.options.maxStalenessSeconds : null; - } else if(tags && typeof tags == 'object') { - this.options = tags, tags = null; - } -} - -/** - * This needs slaveOk bit set - * @method - * @return {boolean} - */ -ReadPreference.prototype.slaveOk = function() { - return needSlaveOk.indexOf(this.preference) != -1; -} - -/** - * Are the two read preference equal - * @method - * @return {boolean} - */ -ReadPreference.prototype.equals = function(readPreference) { - return readPreference.preference == this.preference; -} - -/** - * Return JSON representation - * @method - * @return {Object} - */ -ReadPreference.prototype.toJSON = function() { - var readPreference = {mode: this.preference}; - if(Array.isArray(this.tags)) readPreference.tags = this.tags; - if(this.maxStalenessSeconds) readPreference.maxStalenessSeconds = this.maxStalenessSeconds; - return readPreference; -} - -/** - * Primary read preference - * @method - * @return {ReadPreference} - */ -ReadPreference.primary = new ReadPreference('primary'); -/** - * Primary Preferred read preference - * @method - * @return {ReadPreference} - */ -ReadPreference.primaryPreferred = new ReadPreference('primaryPreferred'); -/** - * Secondary read preference - * @method - * @return {ReadPreference} - */ -ReadPreference.secondary = new ReadPreference('secondary'); -/** - * Secondary Preferred read preference - * @method - * @return {ReadPreference} - */ -ReadPreference.secondaryPreferred = new ReadPreference('secondaryPreferred'); -/** - * Nearest read preference - * @method - * @return {ReadPreference} - */ -ReadPreference.nearest = new ReadPreference('nearest'); - -module.exports = ReadPreference; diff --git a/ts-ticket-office-service/node_modules/mongodb-core/lib/topologies/replset.js b/ts-ticket-office-service/node_modules/mongodb-core/lib/topologies/replset.js deleted file mode 100644 index fe04f21d1..000000000 --- a/ts-ticket-office-service/node_modules/mongodb-core/lib/topologies/replset.js +++ /dev/null @@ -1,1454 +0,0 @@ -"use strict" - -var inherits = require('util').inherits, - f = require('util').format, - EventEmitter = require('events').EventEmitter, - ReadPreference = require('./read_preference'), - BasicCursor = require('../cursor'), - retrieveBSON = require('../connection/utils').retrieveBSON, - Logger = require('../connection/logger'), - MongoError = require('../error'), - Server = require('./server'), - ReplSetState = require('./replset_state'), - assign = require('../utils').assign, - clone = require('./shared').clone, - Timeout = require('./shared').Timeout, - Interval = require('./shared').Interval, - createClientInfo = require('./shared').createClientInfo; - -var MongoCR = require('../auth/mongocr') - , X509 = require('../auth/x509') - , Plain = require('../auth/plain') - , GSSAPI = require('../auth/gssapi') - , SSPI = require('../auth/sspi') - , ScramSHA1 = require('../auth/scram'); - -var BSON = retrieveBSON(); - -// -// States -var DISCONNECTED = 'disconnected'; -var CONNECTING = 'connecting'; -var CONNECTED = 'connected'; -var UNREFERENCED = 'unreferenced'; -var DESTROYED = 'destroyed'; - -function stateTransition(self, newState) { - var legalTransitions = { - 'disconnected': [CONNECTING, DESTROYED, DISCONNECTED], - 'connecting': [CONNECTING, DESTROYED, CONNECTED, DISCONNECTED], - 'connected': [CONNECTED, DISCONNECTED, DESTROYED, UNREFERENCED], - 'unreferenced': [UNREFERENCED, DESTROYED], - 'destroyed': [DESTROYED] - } - - // Get current state - var legalStates = legalTransitions[self.state]; - if(legalStates && legalStates.indexOf(newState) != -1) { - self.state = newState; - } else { - self.s.logger.error(f('Pool with id [%s] failed attempted illegal state transition from [%s] to [%s] only following state allowed [%s]' - , self.id, self.state, newState, legalStates)); - } -} - -// -// ReplSet instance id -var id = 1; -var handlers = ['connect', 'close', 'error', 'timeout', 'parseError']; - -/** - * Creates a new Replset instance - * @class - * @param {array} seedlist A list of seeds for the replicaset - * @param {boolean} options.setName The Replicaset set name - * @param {boolean} [options.secondaryOnlyConnectionAllowed=false] Allow connection to a secondary only replicaset - * @param {number} [options.haInterval=10000] The High availability period for replicaset inquiry - * @param {boolean} [options.emitError=false] Server will emit errors events - * @param {Cursor} [options.cursorFactory=Cursor] The cursor factory class used for all query cursors - * @param {number} [options.size=5] Server connection pool size - * @param {boolean} [options.keepAlive=true] TCP Connection keep alive enabled - * @param {number} [options.keepAliveInitialDelay=0] Initial delay before TCP keep alive enabled - * @param {boolean} [options.noDelay=true] TCP Connection no delay - * @param {number} [options.connectionTimeout=10000] TCP Connection timeout setting - * @param {number} [options.socketTimeout=0] TCP Socket timeout setting - * @param {boolean} [options.singleBufferSerializtion=true] Serialize into single buffer, trade of peak memory for serialization speed - * @param {boolean} [options.ssl=false] Use SSL for connection - * @param {boolean|function} [options.checkServerIdentity=true] Ensure we check server identify during SSL, set to false to disable checking. Only works for Node 0.12.x or higher. You can pass in a boolean or your own checkServerIdentity override function. - * @param {Buffer} [options.ca] SSL Certificate store binary buffer - * @param {Buffer} [options.crl] SSL Certificate revocation store binary buffer - * @param {Buffer} [options.cert] SSL Certificate binary buffer - * @param {Buffer} [options.key] SSL Key file binary buffer - * @param {string} [options.passphrase] SSL Certificate pass phrase - * @param {string} [options.servername=null] String containing the server name requested via TLS SNI. - * @param {boolean} [options.rejectUnauthorized=true] Reject unauthorized server certificates - * @param {boolean} [options.promoteLongs=true] Convert Long values from the db into Numbers if they fit into 53 bits - * @param {boolean} [options.promoteValues=true] Promotes BSON values to native types where possible, set to false to only receive wrapper types. - * @param {boolean} [options.promoteBuffers=false] Promotes Binary BSON values to native Node Buffers. - * @param {number} [options.pingInterval=5000] Ping interval to check the response time to the different servers - * @param {number} [options.localThresholdMS=15] Cutoff latency point in MS for Replicaset member selection - * @param {boolean} [options.domainsEnabled=false] Enable the wrapping of the callback in the current entity, disabled by default to avoid perf hit. - * @return {ReplSet} A cursor instance - * @fires ReplSet#connect - * @fires ReplSet#ha - * @fires ReplSet#joined - * @fires ReplSet#left - * @fires ReplSet#failed - * @fires ReplSet#fullsetup - * @fires ReplSet#all - * @fires ReplSet#error - * @fires ReplSet#serverHeartbeatStarted - * @fires ReplSet#serverHeartbeatSucceeded - * @fires ReplSet#serverHeartbeatFailed - * @fires ReplSet#topologyOpening - * @fires ReplSet#topologyClosed - * @fires ReplSet#topologyDescriptionChanged - * @property {string} type the topology type. - * @property {string} parserType the parser type used (c++ or js). - */ -var ReplSet = function(seedlist, options) { - var self = this; - options = options || {}; - - // Validate seedlist - if(!Array.isArray(seedlist)) throw new MongoError("seedlist must be an array"); - // Validate list - if(seedlist.length == 0) throw new MongoError("seedlist must contain at least one entry"); - // Validate entries - seedlist.forEach(function(e) { - if(typeof e.host != 'string' || typeof e.port != 'number') - throw new MongoError("seedlist entry must contain a host and port"); - }); - - // Add event listener - EventEmitter.call(this); - - // Get replSet Id - this.id = id++; - - // Get the localThresholdMS - var localThresholdMS = options.localThresholdMS || 15; - // Backward compatibility - if(options.acceptableLatency) localThresholdMS = options.acceptableLatency; - - // Create a logger - var logger = Logger('ReplSet', options); - - // Internal state - this.s = { - options: assign({}, options), - // BSON instance - bson: options.bson || new BSON([BSON.Binary, BSON.Code, BSON.DBRef, BSON.Decimal128, - BSON.Double, BSON.Int32, BSON.Long, BSON.Map, BSON.MaxKey, BSON.MinKey, - BSON.ObjectId, BSON.BSONRegExp, BSON.Symbol, BSON.Timestamp]), - // Factory overrides - Cursor: options.cursorFactory || BasicCursor, - // Logger instance - logger: logger, - // Seedlist - seedlist: seedlist, - // Replicaset state - replicaSetState: new ReplSetState({ - id: this.id, setName: options.setName, - acceptableLatency: localThresholdMS, - heartbeatFrequencyMS: options.haInterval ? options.haInterval : 10000, - logger: logger - }), - // Current servers we are connecting to - connectingServers: [], - // Ha interval - haInterval: options.haInterval ? options.haInterval : 10000, - // Minimum heartbeat frequency used if we detect a server close - minHeartbeatFrequencyMS: 500, - // Disconnect handler - disconnectHandler: options.disconnectHandler, - // Server selection index - index: 0, - // Connect function options passed in - connectOptions: {}, - // Are we running in debug mode - debug: typeof options.debug == 'boolean' ? options.debug : false, - // Client info - clientInfo: createClientInfo(options), - // Authentication context - authenticationContexts: [], - } - - // Add handler for topology change - this.s.replicaSetState.on('topologyDescriptionChanged', function(r) { self.emit('topologyDescriptionChanged', r); }); - - // Log info warning if the socketTimeout < haInterval as it will cause - // a lot of recycled connections to happen. - if(this.s.logger.isWarn() - && this.s.options.socketTimeout != 0 - && this.s.options.socketTimeout < this.s.haInterval) { - this.s.logger.warn(f('warning socketTimeout %s is less than haInterval %s. This might cause unnecessary server reconnections due to socket timeouts' - , this.s.options.socketTimeout, this.s.haInterval)); - } - - // All the authProviders - this.authProviders = options.authProviders || { - 'mongocr': new MongoCR(this.s.bson), 'x509': new X509(this.s.bson) - , 'plain': new Plain(this.s.bson), 'gssapi': new GSSAPI(this.s.bson) - , 'sspi': new SSPI(this.s.bson), 'scram-sha-1': new ScramSHA1(this.s.bson) - } - - // Add forwarding of events from state handler - var types = ['joined', 'left']; - types.forEach(function(x) { - self.s.replicaSetState.on(x, function(t, s) { - self.emit(x, t, s); - }); - }); - - // Connect stat - this.initialConnectState = { - connect: false, fullsetup: false, all: false - } - - // Disconnected state - this.state = DISCONNECTED; - this.haTimeoutId = null; - // Are we authenticating - this.authenticating = false; - // Last ismaster - this.ismaster = null; - // Contains the intervalId - this.intervalIds = []; -} - -inherits(ReplSet, EventEmitter); - -Object.defineProperty(ReplSet.prototype, 'type', { - enumerable:true, get: function() { return 'replset'; } -}); - -Object.defineProperty(ReplSet.prototype, 'parserType', { - enumerable:true, get: function() { - return BSON.native ? "c++" : "js"; - } -}); - -function rexecuteOperations(self) { - // If we have a primary and a disconnect handler, execute - // buffered operations - if(self.s.replicaSetState.hasPrimaryAndSecondary() && self.s.disconnectHandler) { - self.s.disconnectHandler.execute(); - } else if(self.s.replicaSetState.hasPrimary() && self.s.disconnectHandler) { - self.s.disconnectHandler.execute({ executePrimary:true }); - } else if(self.s.replicaSetState.hasSecondary() && self.s.disconnectHandler) { - self.s.disconnectHandler.execute({ executeSecondary:true }); - } -} - -function connectNewServers(self, servers, callback) { - // Count lefts - var count = servers.length; - var error = null; - - // Handle events - var _handleEvent = function(self, event) { - return function(err) { - var _self = this; - count = count - 1; - - // Destroyed - if(self.state == DESTROYED || self.state == UNREFERENCED) { - return this.destroy({force:true}); - } - - if(event == 'connect' && !self.authenticating) { - // Destroyed - if(self.state == DESTROYED || self.state == UNREFERENCED) { - return _self.destroy({force:true}); - } - - // Do we have authentication contexts that need to be applied - applyAuthenticationContexts(self, _self, function() { - // Destroy the instance - if(self.state == DESTROYED || self.state == UNREFERENCED) { - return _self.destroy({force:true}); - } - - // Update the state - var result = self.s.replicaSetState.update(_self); - // Update the state with the new server - if(result) { - // Primary lastIsMaster store it - if(_self.lastIsMaster() && _self.lastIsMaster().ismaster) { - self.ismaster = _self.lastIsMaster(); - } - - // Remove the handlers - for(var i = 0; i < handlers.length; i++) { - _self.removeAllListeners(handlers[i]); - } - - // Add stable state handlers - _self.on('error', handleEvent(self, 'error')); - _self.on('close', handleEvent(self, 'close')); - _self.on('timeout', handleEvent(self, 'timeout')); - _self.on('parseError', handleEvent(self, 'parseError')); - - // Enalbe the monitoring of the new server - monitorServer(_self.lastIsMaster().me, self, {}); - - // Rexecute any stalled operation - rexecuteOperations(self); - } else { - _self.destroy({force:true}); - } - }); - } else if(event == 'connect' && self.authenticating) { - this.destroy({force:true}); - } else if(event == 'error') { - error = err; - } - - // Rexecute any stalled operation - rexecuteOperations(self); - - // Are we done finish up callback - if(count == 0) { callback(error); } - } - } - - // No new servers - if(count == 0) return callback(); - - // Execute method - function execute(_server, i) { - setTimeout(function() { - // Destroyed - if(self.state == DESTROYED || self.state == UNREFERENCED) { - return; - } - - // Create a new server instance - var server = new Server(assign({}, self.s.options, { - host: _server.split(':')[0], - port: parseInt(_server.split(':')[1], 10) - }, { - authProviders: self.authProviders, reconnect:false, monitoring: false, inTopology: true - }, { - clientInfo: clone(self.s.clientInfo) - })); - - // Add temp handlers - server.once('connect', _handleEvent(self, 'connect')); - server.once('close', _handleEvent(self, 'close')); - server.once('timeout', _handleEvent(self, 'timeout')); - server.once('error', _handleEvent(self, 'error')); - server.once('parseError', _handleEvent(self, 'parseError')); - - // SDAM Monitoring events - server.on('serverOpening', function(e) { self.emit('serverOpening', e); }); - server.on('serverDescriptionChanged', function(e) { self.emit('serverDescriptionChanged', e); }); - server.on('serverClosed', function(e) { self.emit('serverClosed', e); }); - server.connect(self.s.connectOptions); - }, i); - } - - // Create new instances - for(var i = 0; i < servers.length; i++) { - execute(servers[i], i); - } -} - -// Ping the server -var pingServer = function(self, server, cb) { - // Measure running time - var start = new Date().getTime(); - - // Emit the server heartbeat start - emitSDAMEvent(self, 'serverHeartbeatStarted', { connectionId: server.name }); - - // Execute ismaster - // Set the socketTimeout for a monitoring message to a low number - // Ensuring ismaster calls are timed out quickly - server.command('admin.$cmd', { - ismaster:true - }, { - monitoring: true, - socketTimeout: self.s.options.connectionTimeout || 2000, - }, function(err, r) { - if(self.state == DESTROYED || self.state == UNREFERENCED) { - server.destroy({force:true}); - return cb(err, r); - } - - // Calculate latency - var latencyMS = new Date().getTime() - start; - // Set the last updatedTime - var hrTime = process.hrtime(); - // Calculate the last update time - server.lastUpdateTime = hrTime[0] * 1000 + Math.round(hrTime[1]/1000); - - // We had an error, remove it from the state - if(err) { - // Emit the server heartbeat failure - emitSDAMEvent(self, 'serverHeartbeatFailed', { durationMS: latencyMS, failure: err, connectionId: server.name }); - - // Remove server from the state - self.s.replicaSetState.remove(server); - } else { - // Update the server ismaster - server.ismaster = r.result; - - // Check if we have a lastWriteDate convert it to MS - // and store on the server instance for later use - if(server.ismaster.lastWrite && server.ismaster.lastWrite.lastWriteDate) { - server.lastWriteDate = server.ismaster.lastWrite.lastWriteDate.getTime(); - } - - // Do we have a brand new server - if(server.lastIsMasterMS == -1) { - server.lastIsMasterMS = latencyMS; - } else if(server.lastIsMasterMS) { - // After the first measurement, average RTT MUST be computed using an - // exponentially-weighted moving average formula, with a weighting factor (alpha) of 0.2. - // If the prior average is denoted old_rtt, then the new average (new_rtt) is - // computed from a new RTT measurement (x) using the following formula: - // alpha = 0.2 - // new_rtt = alpha * x + (1 - alpha) * old_rtt - server.lastIsMasterMS = 0.2 * latencyMS + (1 - 0.2) * server.lastIsMasterMS; - } - - if(self.s.replicaSetState.update(server)) { - // Primary lastIsMaster store it - if(server.lastIsMaster() && server.lastIsMaster().ismaster) { - self.ismaster = server.lastIsMaster(); - } - } - - // Server heart beat event - emitSDAMEvent(self, 'serverHeartbeatSucceeded', { durationMS: latencyMS, reply: r.result, connectionId: server.name }); - } - - // Calculate the staleness for this server - self.s.replicaSetState.updateServerMaxStaleness(server, self.s.haInterval); - - // Callback - cb(err, r); - }); -} - -// Each server is monitored in parallel in their own timeout loop -var monitorServer = function(host, self, options) { - // If this is not the initial scan - // Is this server already being monitoried, then skip monitoring - if(!options.haInterval) { - for(var i = 0; i < self.intervalIds.length; i++) { - if(self.intervalIds[i].__host === host) { - return; - } - } - } - - // Get the haInterval - var _process = options.haInterval ? Timeout : Interval; - var _haInterval = options.haInterval ? options.haInterval : self.s.haInterval; - - // Create the interval - var intervalId = new _process(function() { - if(self.state == DESTROYED || self.state == UNREFERENCED) { - // clearInterval(intervalId); - intervalId.stop(); - return; - } - - // Do we already have server connection available for this host - var _server = self.s.replicaSetState.get(host); - - // Check if we have a known server connection and reuse - if(_server) { - // Ping the server - return pingServer(self, _server, function(err) { - if(self.state == DESTROYED || self.state == UNREFERENCED) { - intervalId.stop(); - return; - } - - // Filter out all called intervaliIds - self.intervalIds = self.intervalIds.filter(function(intervalId) { - return intervalId.isRunning(); - } ); - - // Initial sweep - if(_process === Timeout) { - if(self.state == CONNECTING && ( - ( - self.s.replicaSetState.hasSecondary() - && self.s.options.secondaryOnlyConnectionAllowed - ) - || self.s.replicaSetState.hasPrimary() - )) { - self.state = CONNECTED; - - // Emit connected sign - process.nextTick(function() { - self.emit('connect', self); - }); - - // Start topology interval check - topologyMonitor(self, {}); - } - } else { - if(self.state == DISCONNECTED && ( - ( - self.s.replicaSetState.hasSecondary() - && self.s.options.secondaryOnlyConnectionAllowed - ) - || self.s.replicaSetState.hasPrimary() - )) { - self.state = CONNECTED; - - // Rexecute any stalled operation - rexecuteOperations(self); - - // Emit connected sign - process.nextTick(function() { - self.emit('reconnect', self); - }); - } - } - - if(self.initialConnectState.connect - && !self.initialConnectState.fullsetup - && self.s.replicaSetState.hasPrimaryAndSecondary()) { - // Set initial connect state - self.initialConnectState.fullsetup = true; - self.initialConnectState.all = true; - - process.nextTick(function() { - self.emit('fullsetup', self); - self.emit('all', self); - }); - } - }); - } - }, _haInterval); - - // Start the interval - intervalId.start(); - // Add the intervalId host name - intervalId.__host = host; - // Add the intervalId to our list of intervalIds - self.intervalIds.push(intervalId); -} - -function topologyMonitor(self, options) { - if(self.state == DESTROYED || self.state == UNREFERENCED) return; - options = options || {}; - - // Get the servers - var servers = Object.keys(self.s.replicaSetState.set); - - // Get the haInterval - var _process = options.haInterval ? Timeout : Interval; - var _haInterval = options.haInterval ? options.haInterval : self.s.haInterval; - - if(_process === Timeout) { - return connectNewServers(self, self.s.replicaSetState.unknownServers, function(err) { - // Don't emit errors if the connection was already - if(self.state === DESTROYED || self.state === UNREFERENCED) { - return; - } - - if(!self.s.replicaSetState.hasPrimary() && !self.s.options.secondaryOnlyConnectionAllowed) { - if(err) return self.emit('error', err); - self.emit('error', new MongoError('no primary found in replicaset')); - return self.destroy({force:true}); - } else if(!self.s.replicaSetState.hasSecondary() && self.s.options.secondaryOnlyConnectionAllowed) { - if(err) return self.emit('error', err); - self.emit('error', new MongoError('no secondary found in replicaset')); - return self.destroy({force:true}); - } - - for(var i = 0; i < servers.length; i++) { - monitorServer(servers[i], self, options); - } - }); - } else { - for(var i = 0; i < servers.length; i++) { - monitorServer(servers[i], self, options); - } - } - - // Run the reconnect process - function executeReconnect(self) { - return function() { - if(self.state == DESTROYED || self.state == UNREFERENCED) { - return; - } - - connectNewServers(self, self.s.replicaSetState.unknownServers, function() { - var monitoringFrequencey = self.s.replicaSetState.hasPrimary() - ? _haInterval : self.s.minHeartbeatFrequencyMS; - - // Create a timeout - self.intervalIds.push(new Timeout(executeReconnect(self), monitoringFrequencey).start()); - }); - } - } - - // Decide what kind of interval to use - var intervalTime = !self.s.replicaSetState.hasPrimary() - ? self.s.minHeartbeatFrequencyMS - : _haInterval - - self.intervalIds.push(new Timeout(executeReconnect(self), intervalTime).start()); -} - -function addServerToList(list, server) { - for(var i = 0; i < list.length; i++) { - if(list[i].name.toLowerCase() === server.name.toLowerCase()) return true; - } - - list.push(server); -} - -function handleEvent(self, event) { - return function() { - if(self.state == DESTROYED || self.state == UNREFERENCED) return; - // Debug log - if(self.s.logger.isDebug()) { - self.s.logger.debug(f('handleEvent %s from server %s in replset with id %s', event, this.name, self.id)); - } - - // Remove from the replicaset state - self.s.replicaSetState.remove(this); - - // Are we in a destroyed state return - if(self.state == DESTROYED || self.state == UNREFERENCED) return; - - // If no primary and secondary available - if(!self.s.replicaSetState.hasPrimary() - && !self.s.replicaSetState.hasSecondary() - && self.s.options.secondaryOnlyConnectionAllowed) { - stateTransition(self, DISCONNECTED); - } else if(!self.s.replicaSetState.hasPrimary()) { - stateTransition(self, DISCONNECTED); - } - - addServerToList(self.s.connectingServers, this); - } -} - -function applyAuthenticationContexts(self, server, callback) { - if(self.s.authenticationContexts.length == 0) { - return callback(); - } - - // Do not apply any auth contexts if it's an arbiter - if(server.lastIsMaster() && server.lastIsMaster().arbiterOnly) { - return callback(); - } - - // Copy contexts to ensure no modificiation in the middle of - // auth process. - var authContexts = self.s.authenticationContexts.slice(0); - - // Apply one of the contexts - function applyAuth(authContexts, server, callback) { - if(authContexts.length == 0) return callback(); - // Get the first auth context - var authContext = authContexts.shift(); - // Copy the params - var customAuthContext = authContext.slice(0); - // Push our callback handler - customAuthContext.push(function(err) { - applyAuth(authContexts, server, callback); - }); - - // Attempt authentication - server.auth.apply(server, customAuthContext) - } - - // Apply all auth contexts - applyAuth(authContexts, server, callback); -} - -function handleInitialConnectEvent(self, event) { - return function() { - var _this = this; - // Debug log - if(self.s.logger.isDebug()) { - self.s.logger.debug(f('handleInitialConnectEvent %s from server %s in replset with id %s', event, this.name, self.id)); - } - - // Destroy the instance - if(self.state == DESTROYED || self.state == UNREFERENCED) { - return this.destroy({force:true}); - } - - // Check the type of server - if(event == 'connect') { - // Do we have authentication contexts that need to be applied - applyAuthenticationContexts(self, _this, function() { - // Destroy the instance - if(self.state == DESTROYED || self.state == UNREFERENCED) { - return _this.destroy({force:true}); - } - - // Update the state - var result = self.s.replicaSetState.update(_this); - if(result == true) { - // Primary lastIsMaster store it - if(_this.lastIsMaster() && _this.lastIsMaster().ismaster) { - self.ismaster = _this.lastIsMaster(); - } - - // Debug log - if(self.s.logger.isDebug()) { - self.s.logger.debug(f('handleInitialConnectEvent %s from server %s in replset with id %s has state [%s]', event, _this.name, self.id, JSON.stringify(self.s.replicaSetState.set))); - } - - // Remove the handlers - for(var i = 0; i < handlers.length; i++) { - _this.removeAllListeners(handlers[i]); - } - - // Add stable state handlers - _this.on('error', handleEvent(self, 'error')); - _this.on('close', handleEvent(self, 'close')); - _this.on('timeout', handleEvent(self, 'timeout')); - _this.on('parseError', handleEvent(self, 'parseError')); - - // Do we have a primary or primaryAndSecondary - if(self.state === CONNECTING && self.s.replicaSetState.hasPrimary() - || (self.s.replicaSetState.hasSecondary() && self.s.options.secondaryOnlyConnectionAllowed)) { - // We are connected - self.state = CONNECTED; - - // Set initial connect state - self.initialConnectState.connect = true; - // Emit connect event - process.nextTick(function() { - self.emit('connect', self); - }); - - topologyMonitor(self, {}); - } - } else if(result instanceof MongoError) { - _this.destroy({force:true}); - self.destroy({force:true}); - return self.emit('error', result); - } else { - _this.destroy({force:true}); - } - }); - } else { - // Emit failure to connect - self.emit('failed', this); - - addServerToList(self.s.connectingServers, this); - // Remove from the state - self.s.replicaSetState.remove(this); - } - - if(self.initialConnectState.connect - && !self.initialConnectState.fullsetup - && self.s.replicaSetState.hasPrimaryAndSecondary()) { - // Set initial connect state - self.initialConnectState.fullsetup = true; - self.initialConnectState.all = true; - - process.nextTick(function() { - self.emit('fullsetup', self); - self.emit('all', self); - }); - } - - // Remove from the list from connectingServers - for(var i = 0; i < self.s.connectingServers.length; i++) { - if(self.s.connectingServers[i].equals(this)) { - self.s.connectingServers.splice(i, 1); - } - } - - // Trigger topologyMonitor - if(self.s.connectingServers.length == 0 && self.state == CONNECTING) { - topologyMonitor(self, {haInterval: 1}); - } - }; -} - -function connectServers(self, servers) { - // Update connectingServers - self.s.connectingServers = self.s.connectingServers.concat(servers); - - // Index used to interleaf the server connects, avoiding - // runtime issues on io constrained vm's - var timeoutInterval = 0; - - function connect(server, timeoutInterval) { - setTimeout(function() { - // Add the server to the state - if(self.s.replicaSetState.update(server)) { - // Primary lastIsMaster store it - if(server.lastIsMaster() && server.lastIsMaster().ismaster) { - self.ismaster = server.lastIsMaster(); - } - } - - // Add event handlers - server.once('close', handleInitialConnectEvent(self, 'close')); - server.once('timeout', handleInitialConnectEvent(self, 'timeout')); - server.once('parseError', handleInitialConnectEvent(self, 'parseError')); - server.once('error', handleInitialConnectEvent(self, 'error')); - server.once('connect', handleInitialConnectEvent(self, 'connect')); - // SDAM Monitoring events - server.on('serverOpening', function(e) { self.emit('serverOpening', e); }); - server.on('serverDescriptionChanged', function(e) { self.emit('serverDescriptionChanged', e); }); - server.on('serverClosed', function(e) { self.emit('serverClosed', e); }); - // Start connection - server.connect(self.s.connectOptions); - }, timeoutInterval); - } - - // Start all the servers - while(servers.length > 0) { - connect(servers.shift(), timeoutInterval++); - } -} - -/** - * Emit event if it exists - * @method - */ -function emitSDAMEvent(self, event, description) { - if(self.listeners(event).length > 0) { - self.emit(event, description); - } -} - -/** - * Initiate server connect - * @method - * @param {array} [options.auth=null] Array of auth options to apply on connect - */ -ReplSet.prototype.connect = function(options) { - var self = this; - // Add any connect level options to the internal state - this.s.connectOptions = options || {}; - // Set connecting state - stateTransition(this, CONNECTING); - // Create server instances - var servers = this.s.seedlist.map(function(x) { - return new Server(assign({}, self.s.options, x, { - authProviders: self.authProviders, reconnect:false, monitoring:false, inTopology: true - }, { - clientInfo: clone(self.s.clientInfo) - })); - }); - - // Error out as high availbility interval must be < than socketTimeout - if(this.s.options.socketTimeout > 0 && this.s.options.socketTimeout <= this.s.options.haInterval) { - return self.emit('error', new MongoError(f("haInterval [%s] MS must be set to less than socketTimeout [%s] MS" - , this.s.options.haInterval, this.s.options.socketTimeout))); - } - - // Emit the topology opening event - emitSDAMEvent(this, 'topologyOpening', { topologyId: this.id }); - // Start all server connections - connectServers(self, servers); -} - -/** - * Destroy the server connection - * @param {boolean} [options.force=false] Force destroy the pool - * @method - */ -ReplSet.prototype.destroy = function(options) { - options = options || {}; - // Transition state - stateTransition(this, DESTROYED); - // Clear out any monitoring process - if(this.haTimeoutId) clearTimeout(this.haTimeoutId); - // Destroy the replicaset - this.s.replicaSetState.destroy(options); - // Clear out authentication contexts - this.s.authenticationContexts = []; - - // Destroy all connecting servers - this.s.connectingServers.forEach(function(x) { - x.destroy(options); - }); - - // Clear out all monitoring - for(var i = 0; i < this.intervalIds.length; i++) { - this.intervalIds[i].stop(); - this.intervalIds[i].stop(); - } - - // Reset list of intervalIds - this.intervalIds = []; - - // Emit toplogy closing event - emitSDAMEvent(this, 'topologyClosed', { topologyId: this.id }); -} - -/** - * Unref all connections belong to this server - * @method - */ -ReplSet.prototype.unref = function() { - // Transition state - stateTransition(this, UNREFERENCED); - - this.s.replicaSetState.allServers().forEach(function(x) { - x.unref(); - }); - - clearTimeout(this.haTimeoutId); -} - -/** - * Returns the last known ismaster document for this server - * @method - * @return {object} - */ -ReplSet.prototype.lastIsMaster = function() { - // If secondaryOnlyConnectionAllowed and no primary but secondary - // return the secondaries ismaster result. - if (this.s.options.secondaryOnlyConnectionAllowed - && !this.s.replicaSetState.hasPrimary() - && this.s.replicaSetState.hasSecondary()) { - return this.s.replicaSetState.secondaries[0].lastIsMaster(); - } - - return this.s.replicaSetState.primary - ? this.s.replicaSetState.primary.lastIsMaster() : this.ismaster; -} - -/** - * All raw connections - * @method - * @return {Connection[]} - */ -ReplSet.prototype.connections = function() { - var servers = this.s.replicaSetState.allServers(); - var connections = []; - for(var i = 0; i < servers.length; i++) { - connections = connections.concat(servers[i].connections()); - } - - return connections; -} - -/** - * Figure out if the server is connected - * @method - * @param {ReadPreference} [options.readPreference] Specify read preference if command supports it - * @return {boolean} - */ -ReplSet.prototype.isConnected = function(options) { - options = options || {}; - - // If we are authenticating signal not connected - // To avoid interleaving of operations - if(this.authenticating) return false; - - // If we specified a read preference check if we are connected to something - // than can satisfy this - if(options.readPreference - && options.readPreference.equals(ReadPreference.secondary)) { - return this.s.replicaSetState.hasSecondary(); - } - - if(options.readPreference - && options.readPreference.equals(ReadPreference.primary)) { - return this.s.replicaSetState.hasPrimary(); - } - - if(options.readPreference - && options.readPreference.equals(ReadPreference.primaryPreferred)) { - return this.s.replicaSetState.hasSecondary() || this.s.replicaSetState.hasPrimary(); - } - - if(options.readPreference - && options.readPreference.equals(ReadPreference.secondaryPreferred)) { - return this.s.replicaSetState.hasSecondary() || this.s.replicaSetState.hasPrimary(); - } - - if(this.s.options.secondaryOnlyConnectionAllowed - && this.s.replicaSetState.hasSecondary()) { - return true; - } - - return this.s.replicaSetState.hasPrimary(); -} - -/** - * Figure out if the replicaset instance was destroyed by calling destroy - * @method - * @return {boolean} - */ -ReplSet.prototype.isDestroyed = function() { - return this.state == DESTROYED; -} - -/** - * Get server - * @method - * @param {ReadPreference} [options.readPreference] Specify read preference if command supports it - * @return {Server} - */ -ReplSet.prototype.getServer = function(options) { - // Ensure we have no options - options = options || {}; - // Pick the right server baspickServerd on readPreference - var server = this.s.replicaSetState.pickServer(options.readPreference); - if(this.s.debug) this.emit('pickedServer', options.readPreference, server); - return server; -} - -/** - * Get a direct connection - * @method - * @param {ReadPreference} [options.readPreference] Specify read preference if command supports it - * @return {Connection} - */ -ReplSet.prototype.getConnection = function(options) { - var server = this.getServer(options); - if(server) return server.getConnection(); -} - -/** - * Get all connected servers - * @method - * @return {Server[]} - */ -ReplSet.prototype.getServers = function() { - return this.s.replicaSetState.allServers(); -} - -// -// Execute write operation -var executeWriteOperation = function(self, op, ns, ops, options, callback) { - if(typeof options == 'function') callback = options, options = {}, options = options || {}; - // Ensure we have no options - options = options || {}; - - // No server returned we had an error - if(self.s.replicaSetState.primary == null) { - return callback(new MongoError("no primary server found")); - } - - // Execute the command - self.s.replicaSetState.primary[op](ns, ops, options, callback); -} - -/** - * Insert one or more documents - * @method - * @param {string} ns The MongoDB fully qualified namespace (ex: db1.collection1) - * @param {array} ops An array of documents to insert - * @param {boolean} [options.ordered=true] Execute in order or out of order - * @param {object} [options.writeConcern={}] Write concern for the operation - * @param {Boolean} [options.serializeFunctions=false] Specify if functions on an object should be serialized. - * @param {Boolean} [options.ignoreUndefined=false] Specify if the BSON serializer should ignore undefined fields. - * @param {opResultCallback} callback A callback function - */ -ReplSet.prototype.insert = function(ns, ops, options, callback) { - if(typeof options == 'function') callback = options, options = {}, options = options || {}; - if(this.state == DESTROYED) return callback(new MongoError(f('topology was destroyed'))); - - // Not connected but we have a disconnecthandler - if(!this.s.replicaSetState.hasPrimary() && this.s.disconnectHandler != null) { - return this.s.disconnectHandler.add('insert', ns, ops, options, callback); - } - - // Execute write operation - executeWriteOperation(this, 'insert', ns, ops, options, callback); -} - -/** - * Perform one or more update operations - * @method - * @param {string} ns The MongoDB fully qualified namespace (ex: db1.collection1) - * @param {array} ops An array of updates - * @param {boolean} [options.ordered=true] Execute in order or out of order - * @param {object} [options.writeConcern={}] Write concern for the operation - * @param {Boolean} [options.serializeFunctions=false] Specify if functions on an object should be serialized. - * @param {Boolean} [options.ignoreUndefined=false] Specify if the BSON serializer should ignore undefined fields. - * @param {opResultCallback} callback A callback function - */ -ReplSet.prototype.update = function(ns, ops, options, callback) { - if(typeof options == 'function') callback = options, options = {}, options = options || {}; - if(this.state == DESTROYED) return callback(new MongoError(f('topology was destroyed'))); - - // Not connected but we have a disconnecthandler - if(!this.s.replicaSetState.hasPrimary() && this.s.disconnectHandler != null) { - return this.s.disconnectHandler.add('update', ns, ops, options, callback); - } - - // Execute write operation - executeWriteOperation(this, 'update', ns, ops, options, callback); -} - -/** - * Perform one or more remove operations - * @method - * @param {string} ns The MongoDB fully qualified namespace (ex: db1.collection1) - * @param {array} ops An array of removes - * @param {boolean} [options.ordered=true] Execute in order or out of order - * @param {object} [options.writeConcern={}] Write concern for the operation - * @param {Boolean} [options.serializeFunctions=false] Specify if functions on an object should be serialized. - * @param {Boolean} [options.ignoreUndefined=false] Specify if the BSON serializer should ignore undefined fields. - * @param {opResultCallback} callback A callback function - */ -ReplSet.prototype.remove = function(ns, ops, options, callback) { - if(typeof options == 'function') callback = options, options = {}, options = options || {}; - if(this.state == DESTROYED) return callback(new MongoError(f('topology was destroyed'))); - - // Not connected but we have a disconnecthandler - if(!this.s.replicaSetState.hasPrimary() && this.s.disconnectHandler != null) { - return this.s.disconnectHandler.add('remove', ns, ops, options, callback); - } - - // Execute write operation - executeWriteOperation(this, 'remove', ns, ops, options, callback); -} - -/** - * Execute a command - * @method - * @param {string} ns The MongoDB fully qualified namespace (ex: db1.collection1) - * @param {object} cmd The command hash - * @param {ReadPreference} [options.readPreference] Specify read preference if command supports it - * @param {Connection} [options.connection] Specify connection object to execute command against - * @param {Boolean} [options.serializeFunctions=false] Specify if functions on an object should be serialized. - * @param {Boolean} [options.ignoreUndefined=false] Specify if the BSON serializer should ignore undefined fields. - * @param {opResultCallback} callback A callback function - */ -ReplSet.prototype.command = function(ns, cmd, options, callback) { - if(typeof options == 'function') callback = options, options = {}, options = options || {}; - if(this.state == DESTROYED) return callback(new MongoError(f('topology was destroyed'))); - var self = this; - - // Establish readPreference - var readPreference = options.readPreference ? options.readPreference : ReadPreference.primary; - - // If the readPreference is primary and we have no primary, store it - if(readPreference.preference == 'primary' && !this.s.replicaSetState.hasPrimary() && this.s.disconnectHandler != null) { - return this.s.disconnectHandler.add('command', ns, cmd, options, callback); - } else if(readPreference.preference == 'secondary' && !this.s.replicaSetState.hasSecondary() && this.s.disconnectHandler != null) { - return this.s.disconnectHandler.add('command', ns, cmd, options, callback); - } else if(readPreference.preference != 'primary' && !this.s.replicaSetState.hasSecondary() && !this.s.replicaSetState.hasPrimary() && this.s.disconnectHandler != null) { - return this.s.disconnectHandler.add('command', ns, cmd, options, callback); - } - - // Pick a server - var server = this.s.replicaSetState.pickServer(readPreference); - // We received an error, return it - if(!(server instanceof Server)) return callback(server); - // Emit debug event - if(self.s.debug) self.emit('pickedServer', ReadPreference.primary, server); - - // No server returned we had an error - if(server == null) { - return callback(new MongoError(f("no server found that matches the provided readPreference %s", readPreference))); - } - - // Execute the command - server.command(ns, cmd, options, callback); -} - -/** - * Authenticate using a specified mechanism - * @method - * @param {string} mechanism The Auth mechanism we are invoking - * @param {string} db The db we are invoking the mechanism against - * @param {...object} param Parameters for the specific mechanism - * @param {authResultCallback} callback A callback function - */ -ReplSet.prototype.auth = function(mechanism, db) { - var allArgs = Array.prototype.slice.call(arguments, 0).slice(0); - var self = this; - var args = Array.prototype.slice.call(arguments, 2); - var callback = args.pop(); - var currentContextIndex = 0; - - // If we don't have the mechanism fail - if(this.authProviders[mechanism] == null && mechanism != 'default') { - return callback(new MongoError(f("auth provider %s does not exist", mechanism))); - } - - // Are we already authenticating, throw - if(this.authenticating) { - return callback(new MongoError('authentication or logout allready in process')); - } - - // Topology is not connected, save the call in the provided store to be - // Executed at some point when the handler deems it's reconnected - if(self.s.disconnectHandler != null) { - if(!self.s.replicaSetState.hasPrimary() && !self.s.options.secondaryOnlyConnectionAllowed) { - return self.s.disconnectHandler.add('auth', db, allArgs, {}, callback); - } else if(!self.s.replicaSetState.hasSecondary() && self.s.options.secondaryOnlyConnectionAllowed) { - return self.s.disconnectHandler.add('auth', db, allArgs, {}, callback); - } - } - - // Set to authenticating - this.authenticating = true; - // All errors - var errors = []; - - // Get all the servers - var servers = this.s.replicaSetState.allServers(); - // No servers return - if(servers.length == 0) { - this.authenticating = false; - callback(null, true); - } - - // Authenticate - function auth(server) { - // Arguments without a callback - var argsWithoutCallback = [mechanism, db].concat(args.slice(0)); - // Create arguments - var finalArguments = argsWithoutCallback.concat([function(err) { - count = count - 1; - // Save all the errors - if(err) errors.push({name: server.name, err: err}); - // We are done - if(count == 0) { - // Auth is done - self.authenticating = false; - - // Return the auth error - if(errors.length) { - // Remove the entry from the stored authentication contexts - self.s.authenticationContexts.splice(currentContextIndex, 0); - // Return error - return callback(MongoError.create({ - message: 'authentication fail', errors: errors - }), false); - } - - // Successfully authenticated session - callback(null, self); - } - }]); - - if(!server.lastIsMaster().arbiterOnly) { - // Execute the auth only against non arbiter servers - server.auth.apply(server, finalArguments); - } else { - // If we are authenticating against an arbiter just ignore it - finalArguments.pop()(null); - } - } - - // Get total count - var count = servers.length; - - // Save current context index - currentContextIndex = this.s.authenticationContexts.length; - - // Store the auth context and return the last index - this.s.authenticationContexts.push([mechanism, db].concat(args.slice(0))); - - // Authenticate against all servers - while(servers.length > 0) { - auth(servers.shift()); - } -} - -/** - * Logout from a database - * @method - * @param {string} db The db we are logging out from - * @param {authResultCallback} callback A callback function - */ -ReplSet.prototype.logout = function(dbName, callback) { - var self = this; - // Are we authenticating or logging out, throw - if(this.authenticating) { - throw new MongoError('authentication or logout allready in process'); - } - - // Ensure no new members are processed while logging out - this.authenticating = true; - - // Remove from all auth providers (avoid any reaplication of the auth details) - var providers = Object.keys(this.authProviders); - for(var i = 0; i < providers.length; i++) { - this.authProviders[providers[i]].logout(dbName); - } - - // Clear out any contexts associated with the db - self.s.authenticationContexts = self.s.authenticationContexts.filter(function(context) { - return context[1] !== dbName; - }); - - // Now logout all the servers - var servers = this.s.replicaSetState.allServers(); - var count = servers.length; - if(count == 0) return callback(); - var errors = []; - - function logoutServer(_server, cb) { - _server.logout(dbName, function(err) { - if(err) errors.push({name: _server.name, err: err}); - cb(); - }); - } - - // Execute logout on all server instances - for(i = 0; i < servers.length; i++) { - logoutServer(servers[i], function() { - count = count - 1; - - if(count == 0) { - // Do not block new operations - self.authenticating = false; - // If we have one or more errors - if(errors.length) return callback(MongoError.create({ - message: f('logout failed against db %s', dbName), errors: errors - }), false); - - // No errors - callback(); - } - }) - } -} - -/** - * Perform one or more remove operations - * @method - * @param {string} ns The MongoDB fully qualified namespace (ex: db1.collection1) - * @param {{object}|{Long}} cmd Can be either a command returning a cursor or a cursorId - * @param {object} [options.batchSize=0] Batchsize for the operation - * @param {array} [options.documents=[]] Initial documents list for cursor - * @param {ReadPreference} [options.readPreference] Specify read preference if command supports it - * @param {Boolean} [options.serializeFunctions=false] Specify if functions on an object should be serialized. - * @param {Boolean} [options.ignoreUndefined=false] Specify if the BSON serializer should ignore undefined fields. - * @param {opResultCallback} callback A callback function - */ -ReplSet.prototype.cursor = function(ns, cmd, cursorOptions) { - cursorOptions = cursorOptions || {}; - var FinalCursor = cursorOptions.cursorFactory || this.s.Cursor; - return new FinalCursor(this.s.bson, ns, cmd, cursorOptions, this, this.s.options); -} - -/** - * A replset connect event, used to verify that the connection is up and running - * - * @event ReplSet#connect - * @type {ReplSet} - */ - -/** - * A replset reconnect event, used to verify that the topology reconnected - * - * @event ReplSet#reconnect - * @type {ReplSet} - */ - -/** - * A replset fullsetup event, used to signal that all topology members have been contacted. - * - * @event ReplSet#fullsetup - * @type {ReplSet} - */ - -/** - * A replset all event, used to signal that all topology members have been contacted. - * - * @event ReplSet#all - * @type {ReplSet} - */ - -/** - * A replset failed event, used to signal that initial replset connection failed. - * - * @event ReplSet#failed - * @type {ReplSet} - */ - -/** - * A server member left the replicaset - * - * @event ReplSet#left - * @type {function} - * @param {string} type The type of member that left (primary|secondary|arbiter) - * @param {Server} server The server object that left - */ - -/** - * A server member joined the replicaset - * - * @event ReplSet#joined - * @type {function} - * @param {string} type The type of member that joined (primary|secondary|arbiter) - * @param {Server} server The server object that joined - */ - -/** - * A server opening SDAM monitoring event - * - * @event ReplSet#serverOpening - * @type {object} - */ - -/** - * A server closed SDAM monitoring event - * - * @event ReplSet#serverClosed - * @type {object} - */ - -/** - * A server description SDAM change monitoring event - * - * @event ReplSet#serverDescriptionChanged - * @type {object} - */ - -/** - * A topology open SDAM event - * - * @event ReplSet#topologyOpening - * @type {object} - */ - -/** - * A topology closed SDAM event - * - * @event ReplSet#topologyClosed - * @type {object} - */ - -/** - * A topology structure SDAM change event - * - * @event ReplSet#topologyDescriptionChanged - * @type {object} - */ - -/** - * A topology serverHeartbeatStarted SDAM event - * - * @event ReplSet#serverHeartbeatStarted - * @type {object} - */ - -/** - * A topology serverHeartbeatFailed SDAM event - * - * @event ReplSet#serverHeartbeatFailed - * @type {object} - */ - -/** - * A topology serverHeartbeatSucceeded SDAM change event - * - * @event ReplSet#serverHeartbeatSucceeded - * @type {object} - */ - -module.exports = ReplSet; diff --git a/ts-ticket-office-service/node_modules/mongodb-core/lib/topologies/replset_state.js b/ts-ticket-office-service/node_modules/mongodb-core/lib/topologies/replset_state.js deleted file mode 100644 index 65d450f51..000000000 --- a/ts-ticket-office-service/node_modules/mongodb-core/lib/topologies/replset_state.js +++ /dev/null @@ -1,1001 +0,0 @@ -"use strict" - -var inherits = require('util').inherits, - f = require('util').format, - diff = require('./shared').diff, - EventEmitter = require('events').EventEmitter, - Logger = require('../connection/logger'), - ReadPreference = require('./read_preference'), - MongoError = require('../error'); - -var TopologyType = { - 'Single': 'Single', 'ReplicaSetNoPrimary': 'ReplicaSetNoPrimary', - 'ReplicaSetWithPrimary': 'ReplicaSetWithPrimary', 'Sharded': 'Sharded', - 'Unknown': 'Unknown' -}; - -var ServerType = { - 'Standalone': 'Standalone', 'Mongos': 'Mongos', 'PossiblePrimary': 'PossiblePrimary', - 'RSPrimary': 'RSPrimary', 'RSSecondary': 'RSSecondary', 'RSArbiter': 'RSArbiter', - 'RSOther': 'RSOther', 'RSGhost': 'RSGhost', 'Unknown': 'Unknown' -}; - -var ReplSetState = function(options) { - options = options || {}; - // Add event listener - EventEmitter.call(this); - // Topology state - this.topologyType = TopologyType.ReplicaSetNoPrimary; - this.setName = options.setName; - - // Server set - this.set = {}; - - // Unpacked options - this.id = options.id; - this.setName = options.setName; - - // Replicaset logger - this.logger = options.logger || Logger('ReplSet', options); - - // Server selection index - this.index = 0; - // Acceptable latency - this.acceptableLatency = options.acceptableLatency || 15; - - // heartbeatFrequencyMS - this.heartbeatFrequencyMS = options.heartbeatFrequencyMS || 10000; - - // Server side - this.primary = null; - this.secondaries = []; - this.arbiters = []; - this.passives = []; - this.ghosts = []; - // Current unknown hosts - this.unknownServers = []; - // In set status - this.set = {}; - // Status - this.maxElectionId = null; - this.maxSetVersion = 0; - // Description of the Replicaset - this.replicasetDescription = { - "topologyType": "Unknown", "servers": [] - }; -} - -inherits(ReplSetState, EventEmitter); - -ReplSetState.prototype.hasPrimaryAndSecondary = function() { - return this.primary != null && this.secondaries.length > 0; -} - -ReplSetState.prototype.hasPrimaryOrSecondary = function() { - return this.hasPrimary() || this.hasSecondary(); -} - -ReplSetState.prototype.hasPrimary = function() { - return this.primary != null; -} - -ReplSetState.prototype.hasSecondary = function() { - return this.secondaries.length > 0; -} - -ReplSetState.prototype.get = function(host) { - var servers = this.allServers(); - - for(var i = 0; i < servers.length; i++) { - if(servers[i].name.toLowerCase() === host.toLowerCase()) { - return servers[i]; - } - } - - return null; -} - -ReplSetState.prototype.allServers = function(options) { - options = options || {}; - var servers = this.primary ? [this.primary] : []; - servers = servers.concat(this.secondaries); - if(!options.ignoreArbiters) servers = servers.concat(this.arbiters); - servers = servers.concat(this.passives); - return servers; -} - -ReplSetState.prototype.destroy = function(options) { - // Destroy all sockets - if(this.primary) this.primary.destroy(options); - this.secondaries.forEach(function(x) { x.destroy(options); }); - this.arbiters.forEach(function(x) { x.destroy(options); }); - this.passives.forEach(function(x) { x.destroy(options); }); - this.ghosts.forEach(function(x) { x.destroy(options); }); - // Clear out the complete state - this.secondaries = []; - this.arbiters = []; - this.passives = []; - this.ghosts = []; - this.unknownServers = []; - this.set = {}; - this.primary = null; - // Emit the topology changed - emitTopologyDescriptionChanged(this); -} - -ReplSetState.prototype.remove = function(server, options) { - options = options || {}; - - // Get the server name and lowerCase it - var serverName = server.name.toLowerCase(); - - // Only remove if the current server is not connected - var servers = this.primary ? [this.primary] : []; - servers = servers.concat(this.secondaries); - servers = servers.concat(this.arbiters); - servers = servers.concat(this.passives); - - // Check if it's active and this is just a failed connection attempt - for(var i = 0; i < servers.length; i++) { - if(!options.force - && servers[i].equals(server) - && servers[i].isConnected - && servers[i].isConnected()) { - return; - } - } - - // If we have it in the set remove it - if(this.set[serverName]) { - this.set[serverName].type = ServerType.Unknown; - this.set[serverName].electionId = null; - this.set[serverName].setName = null; - this.set[serverName].setVersion = null; - } - - // Remove type - var removeType = null; - - // Remove from any lists - if(this.primary && this.primary.equals(server)) { - this.primary = null; - this.topologyType = TopologyType.ReplicaSetNoPrimary; - removeType = 'primary'; - } - - // Remove from any other server lists - removeType = removeFrom(server, this.secondaries) ? 'secondary' : removeType; - removeType = removeFrom(server, this.arbiters) ? 'arbiter' : removeType; - removeType = removeFrom(server, this.passives) ? 'secondary' : removeType; - removeFrom(server, this.ghosts); - removeFrom(server, this.unknownServers); - - // Push to unknownServers - this.unknownServers.push(serverName); - - // Do we have a removeType - if(removeType) { - this.emit('left', removeType, server); - } -} - -ReplSetState.prototype.update = function(server) { - var self = this; - // Get the current ismaster - var ismaster = server.lastIsMaster(); - - // Get the server name and lowerCase it - var serverName = server.name.toLowerCase(); - - // - // Add any hosts - // - if(ismaster) { - // Join all the possible new hosts - var hosts = Array.isArray(ismaster.hosts) ? ismaster.hosts : []; - hosts = hosts.concat(Array.isArray(ismaster.arbiters) ? ismaster.arbiters : []); - hosts = hosts.concat(Array.isArray(ismaster.passives) ? ismaster.passives : []); - hosts = hosts.map(function(s) { return s.toLowerCase() }); - - // Add all hosts as unknownServers - for(var i = 0; i < hosts.length; i++) { - // Add to the list of unknown server - if(this.unknownServers.indexOf(hosts[i]) == -1 - && (!this.set[hosts[i]] || this.set[hosts[i]].type == ServerType.Unknown)) { - this.unknownServers.push(hosts[i].toLowerCase()); - } - - if(!this.set[hosts[i]]) { - this.set[hosts[i]] = { - type: ServerType.Unknown, - electionId: null, - setName: null, - setVersion: null - } - } - } - } - - // - // Unknown server - // - if(!ismaster && !inList(ismaster, server, this.unknownServers)) { - self.set[serverName] = { - type: ServerType.Unknown, setVersion: null, electionId: null, setName: null - } - // Update set information about the server instance - self.set[serverName].type = ServerType.Unknown; - self.set[serverName].electionId = ismaster ? ismaster.electionId : ismaster; - self.set[serverName].setName = ismaster ? ismaster.setName : ismaster; - self.set[serverName].setVersion = ismaster ? ismaster.setVersion : ismaster; - - if(self.unknownServers.indexOf(server.name) == -1) { - self.unknownServers.push(serverName); - } - - // Set the topology - return false; - } - - // - // Is this a mongos - // - if(ismaster && ismaster.msg == 'isdbgrid') { - return false; - } - - // A RSOther instance - if((ismaster.setName && ismaster.hidden) - || (ismaster.setName && !ismaster.ismaster && !ismaster.secondary && !ismaster.arbiterOnly && !ismaster.passive)) { - self.set[serverName] = { - type: ServerType.RSOther, setVersion: null, - electionId: null, setName: ismaster.setName - } - // Set the topology - this.topologyType = this.primary ? TopologyType.ReplicaSetWithPrimary : TopologyType.ReplicaSetNoPrimary; - if(ismaster.setName) this.setName = ismaster.setName; - return false; - } - - // A RSGhost instance - if(ismaster.isreplicaset) { - self.set[serverName] = { - type: ServerType.RSGhost, setVersion: null, - electionId: null, setName: null - } - - // Set the topology - this.topologyType = this.primary ? TopologyType.ReplicaSetWithPrimary : TopologyType.ReplicaSetNoPrimary; - if(ismaster.setName) this.setName = ismaster.setName; - - // Set the topology - return false; - } - - // - // Standalone server, destroy and return - // - if(ismaster && ismaster.ismaster && !ismaster.setName) { - this.topologyType = this.primary ? TopologyType.ReplicaSetWithPrimary : TopologyType.Unknown; - this.remove(server, {force:true}); - return false; - } - - // - // Server in maintanance mode - // - if(ismaster && !ismaster.ismaster && !ismaster.secondary && !ismaster.arbiterOnly) { - this.remove(server, {force:true}); - return false; - } - - // - // If the .me field does not match the passed in server - // - if(ismaster.me && ismaster.me.toLowerCase() != serverName) { - if(this.logger.isWarn()) { - this.logger.warn(f('the seedlist server was removed due to its address %s not matching its ismaster.me address %s', server.name, ismaster.me)); - } - - // Delete from the set - delete this.set[serverName]; - // Delete unknown servers - removeFrom(server, self.unknownServers); - - // Destroy the instance - server.destroy(); - - // Set the type of topology we have - if(this.primary && !this.primary.equals(server)) { - this.topologyType = TopologyType.ReplicaSetWithPrimary; - } else { - this.topologyType = TopologyType.ReplicaSetNoPrimary; - } - - // - // We have a potential primary - // - if(!this.primary && ismaster.primary) { - this.set[ismaster.primary.toLowerCase()] = { - type: ServerType.PossiblePrimary, - setName: null, - electionId: null, - setVersion: null, - } - } - - return false; - } - - // - // Primary handling - // - if(!this.primary && ismaster.ismaster && ismaster.setName) { - var ismasterElectionId = server.lastIsMaster().electionId; - if(this.setName && this.setName != ismaster.setName) { - this.topologyType = TopologyType.ReplicaSetNoPrimary; - return new MongoError(f('setName from ismaster does not match provided connection setName [%s] != [%s]', ismaster.setName, this.setName)); - } - - if(!this.maxElectionId && ismasterElectionId) { - this.maxElectionId = ismasterElectionId; - } else if(this.maxElectionId && ismasterElectionId) { - var result = compareObjectIds(this.maxElectionId, ismasterElectionId); - // Get the electionIds - var ismasterSetVersion = server.lastIsMaster().setVersion; - - if(result == 1) { - this.topologyType = TopologyType.ReplicaSetNoPrimary; - return false; - } else if(result == 0 && ismasterSetVersion) { - if(ismasterSetVersion < this.maxSetVersion) { - this.topologyType = TopologyType.ReplicaSetNoPrimary; - return false; - } - } - - this.maxSetVersion = ismasterSetVersion; - this.maxElectionId = ismasterElectionId; - } - - // Hande normalization of server names - var normalizedHosts = ismaster.hosts.map(function(x) { return x.toLowerCase() }); - var locationIndex = normalizedHosts.indexOf(serverName); - - // Validate that the server exists in the host list - if(locationIndex != -1) { - self.primary = server; - self.set[serverName] = { - type: ServerType.RSPrimary, - setVersion: ismaster.setVersion, - electionId: ismaster.electionId, - setName: ismaster.setName - } - - // Set the topology - this.topologyType = TopologyType.ReplicaSetWithPrimary; - if(ismaster.setName) this.setName = ismaster.setName; - removeFrom(server, self.unknownServers); - removeFrom(server, self.secondaries); - removeFrom(server, self.passives); - self.emit('joined', 'primary', server); - } else { - this.topologyType = TopologyType.ReplicaSetNoPrimary; - } - - emitTopologyDescriptionChanged(self); - return true; - } else if(ismaster.ismaster && ismaster.setName) { - // Get the electionIds - var currentElectionId = self.set[self.primary.name.toLowerCase()].electionId; - var currentSetVersion = self.set[self.primary.name.toLowerCase()].setVersion; - var currentSetName = self.set[self.primary.name.toLowerCase()].setName; - ismasterElectionId = server.lastIsMaster().electionId; - ismasterSetVersion = server.lastIsMaster().setVersion; - var ismasterSetName = server.lastIsMaster().setName; - - // Is it the same server instance - if(this.primary.equals(server) - && currentSetName == ismasterSetName) { - return false; - } - - // If we do not have the same rs name - if(currentSetName && currentSetName != ismasterSetName) { - if(!this.primary.equals(server)) { - this.topologyType = TopologyType.ReplicaSetWithPrimary; - } else { - this.topologyType = TopologyType.ReplicaSetNoPrimary; - } - - return false; - } - - // Check if we need to replace the server - if(currentElectionId && ismasterElectionId) { - result = compareObjectIds(currentElectionId, ismasterElectionId); - - if(result == 1) { - return false; - } else if(result == 0 && (currentSetVersion > ismasterSetVersion)) { - return false; - } - } else if(!currentElectionId && ismasterElectionId - && ismasterSetVersion) { - if(ismasterSetVersion < this.maxSetVersion) { - return false; - } - } - - if(!this.maxElectionId && ismasterElectionId) { - this.maxElectionId = ismasterElectionId; - } else if(this.maxElectionId && ismasterElectionId) { - result = compareObjectIds(this.maxElectionId, ismasterElectionId); - - if(result == 1) { - return false; - } else if(result == 0 && currentSetVersion && ismasterSetVersion) { - if(ismasterSetVersion < this.maxSetVersion) { - return false; - } - } else { - if(ismasterSetVersion < this.maxSetVersion) { - return false; - } - } - - this.maxElectionId = ismasterElectionId; - this.maxSetVersion = ismasterSetVersion; - } else { - this.maxSetVersion = ismasterSetVersion; - } - - // Modify the entry to unknown - self.set[self.primary.name.toLowerCase()] = { - type: ServerType.Unknown, setVersion: null, - electionId: null, setName: null - } - - // Signal primary left - self.emit('left', 'primary', this.primary); - // Destroy the instance - self.primary.destroy(); - // Set the new instance - self.primary = server; - // Set the set information - self.set[serverName] = { - type: ServerType.RSPrimary, setVersion: ismaster.setVersion, - electionId: ismaster.electionId, setName: ismaster.setName - } - - // Set the topology - this.topologyType = TopologyType.ReplicaSetWithPrimary; - if(ismaster.setName) this.setName = ismaster.setName; - removeFrom(server, self.unknownServers); - removeFrom(server, self.secondaries); - removeFrom(server, self.passives); - self.emit('joined', 'primary', server); - emitTopologyDescriptionChanged(self); - return true; - } - - // A possible instance - if(!this.primary && ismaster.primary) { - self.set[ismaster.primary.toLowerCase()] = { - type: ServerType.PossiblePrimary, setVersion: null, - electionId: null, setName: null - } - } - - // - // Secondary handling - // - if(ismaster.secondary && ismaster.setName - && !inList(ismaster, server, this.secondaries) - && this.setName && this.setName == ismaster.setName) { - addToList(self, ServerType.RSSecondary, ismaster, server, this.secondaries); - // Set the topology - this.topologyType = this.primary ? TopologyType.ReplicaSetWithPrimary : TopologyType.ReplicaSetNoPrimary; - if(ismaster.setName) this.setName = ismaster.setName; - removeFrom(server, self.unknownServers); - - // Remove primary - if(this.primary - && this.primary.name.toLowerCase() == serverName) { - server.destroy(); - this.primary = null; - self.emit('left', 'primary', server); - } - - // Emit secondary joined replicaset - self.emit('joined', 'secondary', server); - emitTopologyDescriptionChanged(self); - return true; - } - - // - // Arbiter handling - // - if(ismaster.arbiterOnly && ismaster.setName - && !inList(ismaster, server, this.arbiters) - && this.setName && this.setName == ismaster.setName) { - addToList(self, ServerType.RSArbiter, ismaster, server, this.arbiters); - // Set the topology - this.topologyType = this.primary ? TopologyType.ReplicaSetWithPrimary : TopologyType.ReplicaSetNoPrimary; - if(ismaster.setName) this.setName = ismaster.setName; - removeFrom(server, self.unknownServers); - self.emit('joined', 'arbiter', server); - emitTopologyDescriptionChanged(self); - return true; - } - - // - // Passive handling - // - if(ismaster.passive && ismaster.setName - && !inList(ismaster, server, this.passives) - && this.setName && this.setName == ismaster.setName) { - addToList(self, ServerType.RSSecondary, ismaster, server, this.passives); - // Set the topology - this.topologyType = this.primary ? TopologyType.ReplicaSetWithPrimary : TopologyType.ReplicaSetNoPrimary; - if(ismaster.setName) this.setName = ismaster.setName; - removeFrom(server, self.unknownServers); - - // Remove primary - if(this.primary - && this.primary.name.toLowerCase() == serverName) { - server.destroy(); - this.primary = null; - self.emit('left', 'primary', server); - } - - self.emit('joined', 'secondary', server); - emitTopologyDescriptionChanged(self); - return true; - } - - // - // Remove the primary - // - if(this.set[serverName] && this.set[serverName].type == ServerType.RSPrimary) { - self.emit('left', 'primary', this.primary); - this.primary.destroy(); - this.primary = null; - this.topologyType = TopologyType.ReplicaSetNoPrimary; - return false; - } - - this.topologyType = this.primary ? TopologyType.ReplicaSetWithPrimary : TopologyType.ReplicaSetNoPrimary; - return false; -} - -/** - * Recalculate single server max staleness - * @method - */ -ReplSetState.prototype.updateServerMaxStaleness = function(server, haInterval) { - // Locate the max secondary lastwrite - var max = 0; - // Go over all secondaries - for(var i = 0; i < this.secondaries.length; i++) { - max = Math.max(max, this.secondaries[i].lastWriteDate); - } - - // Perform this servers staleness calculation - if(server.ismaster.maxWireVersion >= 5 - && server.ismaster.secondary - && this.hasPrimary()) { - server.staleness = (server.lastUpdateTime - server.lastWriteDate) - - (this.primary.lastUpdateTime - this.primary.lastWriteDate) - + haInterval; - } else if(server.ismaster.maxWireVersion >= 5 - && server.ismaster.secondary){ - server.staleness = max - server.lastWriteDate + haInterval; - } -} - -/** - * Recalculate all the staleness values for secodaries - * @method - */ -ReplSetState.prototype.updateSecondariesMaxStaleness = function(haInterval) { - for(var i = 0; i < this.secondaries.length; i++) { - this.updateServerMaxStaleness(this.secondaries[i], haInterval); - } -} - -/** - * Pick a server by the passed in ReadPreference - * @method - * @param {ReadPreference} readPreference The ReadPreference instance to use - */ -ReplSetState.prototype.pickServer = function(readPreference) { - // If no read Preference set to primary by default - readPreference = readPreference || ReadPreference.primary; - - // maxStalenessSeconds is not allowed with a primary read - if(readPreference.preference == 'primary' && readPreference.maxStalenessSeconds != null) { - return new MongoError('primary readPreference incompatible with maxStalenessSeconds'); - } - - // Check if we have any non compatible servers for maxStalenessSeconds - var allservers = this.primary ? [this.primary] : []; - allservers = allservers.concat(this.secondaries); - - // Does any of the servers not support the right wire protocol version - // for maxStalenessSeconds when maxStalenessSeconds specified on readPreference. Then error out - if(readPreference.maxStalenessSeconds != null) { - for(var i = 0; i < allservers.length; i++) { - if(allservers[i].ismaster.maxWireVersion < 5) { - return new MongoError('maxStalenessSeconds not supported by at least one of the replicaset members'); - } - } - } - - // Do we have the nearest readPreference - if(readPreference.preference == 'nearest' && readPreference.maxStalenessSeconds == null) { - return pickNearest(this, readPreference); - } else if(readPreference.preference == 'nearest' && readPreference.maxStalenessSeconds != null) { - return pickNearestMaxStalenessSeconds(this, readPreference); - } - - // Get all the secondaries - var secondaries = this.secondaries; - - // Check if we can satisfy and of the basic read Preferences - if(readPreference.equals(ReadPreference.secondary) - && secondaries.length == 0) { - return new MongoError("no secondary server available"); - } - - if(readPreference.equals(ReadPreference.secondaryPreferred) - && secondaries.length == 0 - && this.primary == null) { - return new MongoError("no secondary or primary server available"); - } - - if(readPreference.equals(ReadPreference.primary) - && this.primary == null) { - return new MongoError("no primary server available"); - } - - // Secondary preferred or just secondaries - if(readPreference.equals(ReadPreference.secondaryPreferred) - || readPreference.equals(ReadPreference.secondary)) { - - if(secondaries.length > 0 && readPreference.maxStalenessSeconds == null) { - // Pick nearest of any other servers available - var server = pickNearest(this, readPreference); - // No server in the window return primary - if(server) { - return server; - } - } else if(secondaries.length > 0 && readPreference.maxStalenessSeconds != null) { - // Pick nearest of any other servers available - server = pickNearestMaxStalenessSeconds(this, readPreference); - // No server in the window return primary - if(server) { - return server; - } - } - - if(readPreference.equals(ReadPreference.secondaryPreferred)){ - return this.primary; - } - - return null; - } - - // Primary preferred - if(readPreference.equals(ReadPreference.primaryPreferred)) { - server = null; - - // We prefer the primary if it's available - if(this.primary) { - return this.primary; - } - - // Pick a secondary - if(secondaries.length > 0 && readPreference.maxStalenessSeconds == null) { - server = pickNearest(this, readPreference); - } else if(secondaries.length > 0 && readPreference.maxStalenessSeconds != null) { - server = pickNearestMaxStalenessSeconds(this, readPreference); - } - - // Did we find a server - if(server) return server; - } - - // Return the primary - return this.primary; -} - -// -// Filter serves by tags -var filterByTags = function(readPreference, servers) { - if(readPreference.tags == null) return servers; - var filteredServers = []; - var tagsArray = Array.isArray(readPreference.tags) ? readPreference.tags : [readPreference.tags]; - - // Iterate over the tags - for(var j = 0; j < tagsArray.length; j++) { - var tags = tagsArray[j]; - - // Iterate over all the servers - for(var i = 0; i < servers.length; i++) { - var serverTag = servers[i].lastIsMaster().tags || {}; - - // Did we find the a matching server - var found = true; - // Check if the server is valid - for(var name in tags) { - if(serverTag[name] != tags[name]) { - found = false; - } - } - - // Add to candidate list - if(found) { - filteredServers.push(servers[i]); - } - } - } - - // Returned filtered servers - return filteredServers; -} - -function pickNearestMaxStalenessSeconds(self, readPreference) { - // Only get primary and secondaries as seeds - var servers = []; - var heartbeatFrequencyMS = self.heartbeatFrequencyMS; - - // Get the maxStalenessMS - var maxStalenessMS = readPreference.maxStalenessSeconds * 1000; - - // Check if the maxStalenessMS > 90 seconds - if(maxStalenessMS < 90 * 1000) { - return new MongoError('maxStalenessSeconds must be set to at least 90 seconds'); - } - - // Add primary to list if not a secondary read preference - if(self.primary - && readPreference.preference != 'secondary' - && readPreference.preference != 'secondaryPreferred') { - servers.push(self.primary); - } - - // Add all the secondaries - for(var i = 0; i < self.secondaries.length; i++) { - servers.push(self.secondaries[i]); - } - - // If we have a secondaryPreferred readPreference and no server add the primary - if(self.primary - && servers.length == 0 - && readPreference.preference != 'secondaryPreferred') { - servers.push(self.primary); - } - - // Filter by tags - servers = filterByTags(readPreference, servers); - - // - // Locate lowest time (picked servers are lowest time + acceptable Latency margin) - // var lowest = servers.length > 0 ? servers[0].lastIsMasterMS : 0; - - // Filter by latency - servers = servers.filter(function(s) { - return s.staleness <= maxStalenessMS; - }); - - // Sort by time - servers.sort(function(a, b) { - // return a.time > b.time; - return a.lastIsMasterMS > b.lastIsMasterMS - }); - - // No servers, default to primary - if(servers.length == 0) { - return null - } - - // Ensure index does not overflow the number of available servers - self.index = self.index % servers.length; - - // Get the server - var server = servers[self.index]; - // Add to the index - self.index = self.index + 1; - // Return the first server of the sorted and filtered list - return server; -} - -function pickNearest(self, readPreference) { - // Only get primary and secondaries as seeds - var servers = []; - - // Add primary to list if not a secondary read preference - if(self.primary - && readPreference.preference != 'secondary' - && readPreference.preference != 'secondaryPreferred') { - servers.push(self.primary); - } - - // Add all the secondaries - for(var i = 0; i < self.secondaries.length; i++) { - servers.push(self.secondaries[i]); - } - - // If we have a secondaryPreferred readPreference and no server add the primary - if(servers.length == 0 - && self.primary - && readPreference.preference != 'secondaryPreferred') { - servers.push(self.primary); - } - - // Filter by tags - servers = filterByTags(readPreference, servers); - - // Sort by time - servers.sort(function(a, b) { - // return a.time > b.time; - return a.lastIsMasterMS > b.lastIsMasterMS - }); - - // Locate lowest time (picked servers are lowest time + acceptable Latency margin) - var lowest = servers.length > 0 ? servers[0].lastIsMasterMS : 0; - - // Filter by latency - servers = servers.filter(function(s) { - return s.lastIsMasterMS <= lowest + self.acceptableLatency; - }); - - // No servers, default to primary - if(servers.length == 0) { - return null - } - - // Ensure index does not overflow the number of available servers - self.index = self.index % servers.length; - // Get the server - var server = servers[self.index]; - // Add to the index - self.index = self.index + 1; - // Return the first server of the sorted and filtered list - return server; -} - -function inList(ismaster, server, list) { - for(var i = 0; i < list.length; i++) { - if(list[i] && list[i].name - && list[i].name.toLowerCase() == server.name.toLowerCase()) return true; - } - - return false; -} - -function addToList(self, type, ismaster, server, list) { - var serverName = server.name.toLowerCase(); - // Update set information about the server instance - self.set[serverName].type = type; - self.set[serverName].electionId = ismaster ? ismaster.electionId : ismaster; - self.set[serverName].setName = ismaster ? ismaster.setName : ismaster; - self.set[serverName].setVersion = ismaster ? ismaster.setVersion : ismaster; - // Add to the list - list.push(server); -} - -function compareObjectIds(id1, id2) { - var a = new Buffer(id1.toHexString(), 'hex'); - var b = new Buffer(id2.toHexString(), 'hex'); - - if(a === b) { - return 0; - } - - if(typeof Buffer.compare === 'function') { - return Buffer.compare(a, b); - } - - var x = a.length; - var y = b.length; - var len = Math.min(x, y); - - for (var i = 0; i < len; i++) { - if (a[i] !== b[i]) { - break; - } - } - - if (i !== len) { - x = a[i]; - y = b[i]; - } - - return x < y ? -1 : y < x ? 1 : 0; -} - -function removeFrom(server, list) { - for(var i = 0; i < list.length; i++) { - if(list[i].equals && list[i].equals(server)) { - list.splice(i, 1); - return true; - } else if(typeof list[i] == 'string' - && list[i].toLowerCase() == server.name.toLowerCase()) { - list.splice(i, 1); - return true; - } - } - - return false; -} - -function emitTopologyDescriptionChanged(self) { - if(self.listeners('topologyDescriptionChanged').length > 0) { - var topology = 'Unknown'; - var setName = self.setName; - - if(self.hasPrimaryAndSecondary()) { - topology = 'ReplicaSetWithPrimary'; - } else if(!self.hasPrimary() && self.hasSecondary()) { - topology = 'ReplicaSetNoPrimary'; - } - - // Generate description - var description = { - topologyType: topology, - setName: setName, - servers: [] - } - - // Add the primary to the list - if(self.hasPrimary()) { - var desc = self.primary.getDescription(); - desc.type = 'RSPrimary'; - description.servers.push(desc); - } - - // Add all the secondaries - description.servers = description.servers.concat(self.secondaries.map(function(x) { - var description = x.getDescription(); - description.type = 'RSSecondary'; - return description; - })); - - // Add all the arbiters - description.servers = description.servers.concat(self.arbiters.map(function(x) { - var description = x.getDescription(); - description.type = 'RSArbiter'; - return description; - })); - - // Add all the passives - description.servers = description.servers.concat(self.passives.map(function(x) { - var description = x.getDescription(); - description.type = 'RSSecondary'; - return description; - })); - - // Get the diff - var diffResult = diff(self.replicasetDescription, description); - - // Create the result - var result = { - topologyId: self.id, - previousDescription: self.replicasetDescription, - newDescription: description, - diff: diffResult, - }; - - // Emit the topologyDescription change - // if(diffResult.servers.length > 0) { - self.emit('topologyDescriptionChanged', result); - // } - - // Set the new description - self.replicasetDescription = description; - } -} - -module.exports = ReplSetState; diff --git a/ts-ticket-office-service/node_modules/mongodb-core/lib/topologies/server.js b/ts-ticket-office-service/node_modules/mongodb-core/lib/topologies/server.js deleted file mode 100644 index e92cbfdfe..000000000 --- a/ts-ticket-office-service/node_modules/mongodb-core/lib/topologies/server.js +++ /dev/null @@ -1,880 +0,0 @@ -"use strict" - -var inherits = require('util').inherits, - f = require('util').format, - EventEmitter = require('events').EventEmitter, - ReadPreference = require('./read_preference'), - Logger = require('../connection/logger'), - debugOptions = require('../connection/utils').debugOptions, - retrieveBSON = require('../connection/utils').retrieveBSON, - Pool = require('../connection/pool'), - Query = require('../connection/commands').Query, - MongoError = require('../error'), - PreTwoSixWireProtocolSupport = require('../wireprotocol/2_4_support'), - TwoSixWireProtocolSupport = require('../wireprotocol/2_6_support'), - ThreeTwoWireProtocolSupport = require('../wireprotocol/3_2_support'), - BasicCursor = require('../cursor'), - sdam = require('./shared'), - assign = require('../utils').assign, - createClientInfo = require('./shared').createClientInfo; - -// Used for filtering out fields for loggin -var debugFields = ['reconnect', 'reconnectTries', 'reconnectInterval', 'emitError', 'cursorFactory', 'host' - , 'port', 'size', 'keepAlive', 'keepAliveInitialDelay', 'noDelay', 'connectionTimeout', 'checkServerIdentity' - , 'socketTimeout', 'singleBufferSerializtion', 'ssl', 'ca', 'crl', 'cert', 'key', 'rejectUnauthorized', 'promoteLongs', 'promoteValues' - , 'promoteBuffers', 'servername']; - -// Server instance id -var id = 0; -var serverAccounting = false; -var servers = {}; -var BSON = retrieveBSON(); - -/** - * Creates a new Server instance - * @class - * @param {boolean} [options.reconnect=true] Server will attempt to reconnect on loss of connection - * @param {number} [options.reconnectTries=30] Server attempt to reconnect #times - * @param {number} [options.reconnectInterval=1000] Server will wait # milliseconds between retries - * @param {number} [options.monitoring=true] Enable the server state monitoring (calling ismaster at monitoringInterval) - * @param {number} [options.monitoringInterval=5000] The interval of calling ismaster when monitoring is enabled. - * @param {Cursor} [options.cursorFactory=Cursor] The cursor factory class used for all query cursors - * @param {string} options.host The server host - * @param {number} options.port The server port - * @param {number} [options.size=5] Server connection pool size - * @param {boolean} [options.keepAlive=true] TCP Connection keep alive enabled - * @param {number} [options.keepAliveInitialDelay=300000] Initial delay before TCP keep alive enabled - * @param {boolean} [options.noDelay=true] TCP Connection no delay - * @param {number} [options.connectionTimeout=30000] TCP Connection timeout setting - * @param {number} [options.socketTimeout=360000] TCP Socket timeout setting - * @param {boolean} [options.ssl=false] Use SSL for connection - * @param {boolean|function} [options.checkServerIdentity=true] Ensure we check server identify during SSL, set to false to disable checking. Only works for Node 0.12.x or higher. You can pass in a boolean or your own checkServerIdentity override function. - * @param {Buffer} [options.ca] SSL Certificate store binary buffer - * @param {Buffer} [options.crl] SSL Certificate revocation store binary buffer - * @param {Buffer} [options.cert] SSL Certificate binary buffer - * @param {Buffer} [options.key] SSL Key file binary buffer - * @param {string} [options.passphrase] SSL Certificate pass phrase - * @param {boolean} [options.rejectUnauthorized=true] Reject unauthorized server certificates - * @param {string} [options.servername=null] String containing the server name requested via TLS SNI. - * @param {boolean} [options.promoteLongs=true] Convert Long values from the db into Numbers if they fit into 53 bits - * @param {boolean} [options.promoteValues=true] Promotes BSON values to native types where possible, set to false to only receive wrapper types. - * @param {boolean} [options.promoteBuffers=false] Promotes Binary BSON values to native Node Buffers. - * @param {string} [options.appname=null] Application name, passed in on ismaster call and logged in mongod server logs. Maximum size 128 bytes. - * @param {boolean} [options.domainsEnabled=false] Enable the wrapping of the callback in the current entity, disabled by default to avoid perf hit. - * @return {Server} A cursor instance - * @fires Server#connect - * @fires Server#close - * @fires Server#error - * @fires Server#timeout - * @fires Server#parseError - * @fires Server#reconnect - * @fires Server#reconnectFailed - * @fires Server#serverHeartbeatStarted - * @fires Server#serverHeartbeatSucceeded - * @fires Server#serverHeartbeatFailed - * @fires Server#topologyOpening - * @fires Server#topologyClosed - * @fires Server#topologyDescriptionChanged - * @property {string} type the topology type. - * @property {string} parserType the parser type used (c++ or js). - */ -var Server = function(options) { - options = options || {}; - - // Add event listener - EventEmitter.call(this); - - // Server instance id - this.id = id++; - - // Internal state - this.s = { - // Options - options: options, - // Logger - logger: Logger('Server', options), - // Factory overrides - Cursor: options.cursorFactory || BasicCursor, - // BSON instance - bson: options.bson || new BSON([BSON.Binary, BSON.Code, BSON.DBRef, BSON.Decimal128, - BSON.Double, BSON.Int32, BSON.Long, BSON.Map, BSON.MaxKey, BSON.MinKey, - BSON.ObjectId, BSON.BSONRegExp, BSON.Symbol, BSON.Timestamp]), - // Pool - pool: null, - // Disconnect handler - disconnectHandler: options.disconnectHandler, - // Monitor thread (keeps the connection alive) - monitoring: typeof options.monitoring == 'boolean' ? options.monitoring : true, - // Is the server in a topology - inTopology: typeof options.inTopology == 'boolean' ? options.inTopology : false, - // Monitoring timeout - monitoringInterval: typeof options.monitoringInterval == 'number' - ? options.monitoringInterval - : 5000, - // Topology id - topologyId: -1 - } - - // Curent ismaster - this.ismaster = null; - // Current ping time - this.lastIsMasterMS = -1; - // The monitoringProcessId - this.monitoringProcessId = null; - // Initial connection - this.initalConnect = true; - // Wire protocol handler, default to oldest known protocol handler - // this gets changed when the first ismaster is called. - this.wireProtocolHandler = new PreTwoSixWireProtocolSupport(); - // Default type - this._type = 'server'; - // Set the client info - this.clientInfo = createClientInfo(options); - - // Max Stalleness values - // last time we updated the ismaster state - this.lastUpdateTime = 0; - // Last write time - this.lastWriteDate = 0; - // Stalleness - this.staleness = 0; -} - -inherits(Server, EventEmitter); - -Object.defineProperty(Server.prototype, 'type', { - enumerable:true, get: function() { return this._type; } -}); - -Object.defineProperty(Server.prototype, 'parserType', { - enumerable:true, get: function() { - return BSON.native ? "c++" : "js"; - } -}); - -Server.enableServerAccounting = function() { - serverAccounting = true; - servers = {}; -} - -Server.disableServerAccounting = function() { - serverAccounting = false; -} - -Server.servers = function() { - return servers; -} - -Object.defineProperty(Server.prototype, 'name', { - enumerable:true, - get: function() { return this.s.options.host + ":" + this.s.options.port; } -}); - -function configureWireProtocolHandler(self, ismaster) { - // 3.2 wire protocol handler - if(ismaster.maxWireVersion >= 4) { - return new ThreeTwoWireProtocolSupport(new TwoSixWireProtocolSupport()); - } - - // 2.6 wire protocol handler - if(ismaster.maxWireVersion >= 2) { - return new TwoSixWireProtocolSupport(); - } - - // 2.4 or earlier wire protocol handler - return new PreTwoSixWireProtocolSupport(); -} - -function disconnectHandler(self, type, ns, cmd, options, callback) { - // Topology is not connected, save the call in the provided store to be - // Executed at some point when the handler deems it's reconnected - if(!self.s.pool.isConnected() && self.s.options.reconnect && self.s.disconnectHandler != null && !options.monitoring) { - self.s.disconnectHandler.add(type, ns, cmd, options, callback); - return true; - } - - // If we have no connection error - if(!self.s.pool.isConnected()) { - callback(MongoError.create(f("no connection available to server %s", self.name))); - return true; - } -} - -function monitoringProcess(self) { - return function() { - // Pool was destroyed do not continue process - if(self.s.pool.isDestroyed()) return; - // Emit monitoring Process event - self.emit('monitoring', self); - // Perform ismaster call - // Query options - var queryOptions = { numberToSkip: 0, numberToReturn: -1, checkKeys: false, slaveOk: true }; - // Create a query instance - var query = new Query(self.s.bson, 'admin.$cmd', {ismaster:true}, queryOptions); - // Get start time - var start = new Date().getTime(); - - // Execute the ismaster query - self.s.pool.write(query, { - socketTimeout: (typeof self.s.options.connectionTimeout !== 'number') ? 2000 : self.s.options.connectionTimeout, - monitoring: true, - }, function(err, result) { - // Set initial lastIsMasterMS - self.lastIsMasterMS = new Date().getTime() - start; - if(self.s.pool.isDestroyed()) return; - // Update the ismaster view if we have a result - if(result) { - self.ismaster = result.result; - } - // Re-schedule the monitoring process - self.monitoringProcessId = setTimeout(monitoringProcess(self), self.s.monitoringInterval); - }); - } -} - -var eventHandler = function(self, event) { - return function(err) { - // Log information of received information if in info mode - if(self.s.logger.isInfo()) { - var object = err instanceof MongoError ? JSON.stringify(err) : {} - self.s.logger.info(f('server %s fired event %s out with message %s' - , self.name, event, object)); - } - - // Handle connect event - if(event == 'connect') { - // Issue an ismaster command at connect - // Query options - var queryOptions = { numberToSkip: 0, numberToReturn: -1, checkKeys: false, slaveOk: true }; - // Create a query instance - var query = new Query(self.s.bson, 'admin.$cmd', {ismaster:true, client: self.clientInfo}, queryOptions); - // Get start time - var start = new Date().getTime(); - // Execute the ismaster query - self.s.pool.write(query, { - socketTimeout: self.s.options.connectionTimeout || 2000, - }, function(err, result) { - // Set initial lastIsMasterMS - self.lastIsMasterMS = new Date().getTime() - start; - if(err) { - self.destroy(); - if(self.listeners('error').length > 0) self.emit('error', err); - return; - } - - // Ensure no error emitted after initial connect when reconnecting - self.initalConnect = false; - // Save the ismaster - self.ismaster = result.result; - - // It's a proxy change the type so - // the wireprotocol will send $readPreference - if(self.ismaster.msg == 'isdbgrid') { - self._type = 'mongos'; - } - // Add the correct wire protocol handler - self.wireProtocolHandler = configureWireProtocolHandler(self, self.ismaster); - // Have we defined self monitoring - if(self.s.monitoring) { - self.monitoringProcessId = setTimeout(monitoringProcess(self), self.s.monitoringInterval); - } - - // Emit server description changed if something listening - sdam.emitServerDescriptionChanged(self, { - address: self.name, arbiters: [], hosts: [], passives: [], type: sdam.getTopologyType(self) - }); - - if(!self.s.inTopology) { - // Emit topology description changed if something listening - sdam.emitTopologyDescriptionChanged(self, { - topologyType: 'Single', servers: [{address: self.name, arbiters: [], hosts: [], passives: [], type: sdam.getTopologyType(self)}] - }); - } - - // Log the ismaster if available - if(self.s.logger.isInfo()) { - self.s.logger.info(f('server %s connected with ismaster [%s]', self.name, JSON.stringify(self.ismaster))); - } - - // Emit connect - self.emit('connect', self); - }); - } else if(event == 'error' || event == 'parseError' - || event == 'close' || event == 'timeout' || event == 'reconnect' - || event == 'attemptReconnect' || 'reconnectFailed') { - // Remove server instance from accounting - if(serverAccounting && ['close', 'timeout', 'error', 'parseError', 'reconnectFailed'].indexOf(event) != -1) { - // Emit toplogy opening event if not in topology - if(!self.s.inTopology) { - self.emit('topologyOpening', { topologyId: self.id }); - } - - delete servers[self.id]; - } - - if (event === 'close') { - // Closing emits a server description changed event going to unknown. - sdam.emitServerDescriptionChanged(self, { - address: self.name, arbiters: [], hosts: [], passives: [], type: 'Unknown' - }); - } - - // Reconnect failed return error - if(event == 'reconnectFailed') { - self.emit('reconnectFailed', err); - // Emit error if any listeners - if(self.listeners('error').length > 0) { - self.emit('error', err); - } - // Terminate - return; - } - - // On first connect fail - if(self.s.pool.state == 'disconnected' && self.initalConnect && ['close', 'timeout', 'error', 'parseError'].indexOf(event) != -1) { - self.initalConnect = false; - return self.emit('error', new MongoError(f('failed to connect to server [%s] on first connect [%s]', self.name, err))); - } - - // Reconnect event, emit the server - if(event == 'reconnect') { - // Reconnecting emits a server description changed event going from unknown to the - // current server type. - sdam.emitServerDescriptionChanged(self, { - address: self.name, arbiters: [], hosts: [], passives: [], type: sdam.getTopologyType(self) - }); - return self.emit(event, self); - } - - // Emit the event - self.emit(event, err); - } - } -} - -/** - * Initiate server connect - * @method - * @param {array} [options.auth=null] Array of auth options to apply on connect - */ -Server.prototype.connect = function(options) { - var self = this; - options = options || {}; - - // Set the connections - if(serverAccounting) servers[this.id] = this; - - // Do not allow connect to be called on anything that's not disconnected - if(self.s.pool && !self.s.pool.isDisconnected() && !self.s.pool.isDestroyed()) { - throw MongoError.create(f('server instance in invalid state %s', self.s.pool.state)); - } - - // Create a pool - self.s.pool = new Pool(assign(self.s.options, options, {bson: this.s.bson})); - - // Set up listeners - self.s.pool.on('close', eventHandler(self, 'close')); - self.s.pool.on('error', eventHandler(self, 'error')); - self.s.pool.on('timeout', eventHandler(self, 'timeout')); - self.s.pool.on('parseError', eventHandler(self, 'parseError')); - self.s.pool.on('connect', eventHandler(self, 'connect')); - self.s.pool.on('reconnect', eventHandler(self, 'reconnect')); - self.s.pool.on('reconnectFailed', eventHandler(self, 'reconnectFailed')); - - // Emit toplogy opening event if not in topology - if(!self.s.inTopology) { - this.emit('topologyOpening', { topologyId: self.id }); - } - - // Emit opening server event - self.emit('serverOpening', { - topologyId: self.s.topologyId != -1 ? self.s.topologyId : self.id, - address: self.name - }); - - // Connect with optional auth settings - if(options.auth) { - self.s.pool.connect.apply(self.s.pool, options.auth); - } else { - self.s.pool.connect(); - } -} - -/** - * Get the server description - * @method - * @return {object} -*/ -Server.prototype.getDescription = function() { - var ismaster = this.ismaster || {}; - var description = { - type: sdam.getTopologyType(this), - address: this.name, - }; - - // Add fields if available - if(ismaster.hosts) description.hosts = ismaster.hosts; - if(ismaster.arbiters) description.arbiters = ismaster.arbiters; - if(ismaster.passives) description.passives = ismaster.passives; - if(ismaster.setName) description.setName = ismaster.setName; - return description; -} - -/** - * Returns the last known ismaster document for this server - * @method - * @return {object} - */ -Server.prototype.lastIsMaster = function() { - return this.ismaster; -} - -/** - * Unref all connections belong to this server - * @method - */ -Server.prototype.unref = function() { - this.s.pool.unref(); -} - -/** - * Figure out if the server is connected - * @method - * @return {boolean} - */ -Server.prototype.isConnected = function() { - if(!this.s.pool) return false; - return this.s.pool.isConnected(); -} - -/** - * Figure out if the server instance was destroyed by calling destroy - * @method - * @return {boolean} - */ -Server.prototype.isDestroyed = function() { - if(!this.s.pool) return false; - return this.s.pool.isDestroyed(); -} - -function basicWriteValidations(self) { - if(!self.s.pool) return MongoError.create('server instance is not connected'); - if(self.s.pool.isDestroyed()) return MongoError.create('server instance pool was destroyed'); -} - -function basicReadValidations(self, options) { - basicWriteValidations(self, options); - - if(options.readPreference && !(options.readPreference instanceof ReadPreference)) { - throw new Error("readPreference must be an instance of ReadPreference"); - } -} - -/** - * Execute a command - * @method - * @param {string} ns The MongoDB fully qualified namespace (ex: db1.collection1) - * @param {object} cmd The command hash - * @param {ReadPreference} [options.readPreference] Specify read preference if command supports it - * @param {Boolean} [options.serializeFunctions=false] Specify if functions on an object should be serialized. - * @param {Boolean} [options.checkKeys=false] Specify if the bson parser should validate keys. - * @param {Boolean} [options.ignoreUndefined=false] Specify if the BSON serializer should ignore undefined fields. - * @param {Boolean} [options.fullResult=false] Return the full envelope instead of just the result document. - * @param {opResultCallback} callback A callback function - */ -Server.prototype.command = function(ns, cmd, options, callback) { - var self = this; - if(typeof options == 'function') callback = options, options = {}, options = options || {}; - var result = basicReadValidations(self, options); - if(result) return callback(result); - - // Clone the options - options = assign({}, options, { wireProtocolCommand: false }); - - // Debug log - if(self.s.logger.isDebug()) self.s.logger.debug(f('executing command [%s] against %s', JSON.stringify({ - ns: ns, cmd: cmd, options: debugOptions(debugFields, options) - }), self.name)); - - // If we are not connected or have a disconnectHandler specified - if(disconnectHandler(self, 'command', ns, cmd, options, callback)) return; - - // Check if we have collation support - if(this.ismaster && this.ismaster.maxWireVersion < 5 && cmd.collation) { - return callback(new MongoError(f('server %s does not support collation', this.name))); - } - - // Query options - var queryOptions = { - numberToSkip: 0, - numberToReturn: -1, - checkKeys: typeof options.checkKeys == 'boolean' ? options.checkKeys: false, - serializeFunctions: typeof options.serializeFunctions == 'boolean' ? options.serializeFunctions : false, - ignoreUndefined: typeof options.ignoreUndefined == 'boolean' ? options.ignoreUndefined : false - }; - - // Are we executing against a specific topology - var topology = options.topology || {}; - // Create the query object - var query = self.wireProtocolHandler.command(self.s.bson, ns, cmd, {}, topology, options); - // Set slave OK of the query - query.slaveOk = options.readPreference ? options.readPreference.slaveOk() : false; - - // Write options - var writeOptions = { - raw: typeof options.raw == 'boolean' ? options.raw : false, - promoteLongs: typeof options.promoteLongs == 'boolean' ? options.promoteLongs : true, - promoteValues: typeof options.promoteValues == 'boolean' ? options.promoteValues : true, - promoteBuffers: typeof options.promoteBuffers == 'boolean' ? options.promoteBuffers : false, - command: true, - monitoring: typeof options.monitoring == 'boolean' ? options.monitoring : false, - fullResult: typeof options.fullResult == 'boolean' ? options.fullResult : false, - requestId: query.requestId, - socketTimeout: typeof options.socketTimeout == 'number' ? options.socketTimeout : null, - }; - - // Write the operation to the pool - self.s.pool.write(query, writeOptions, callback); -} - -/** - * Insert one or more documents - * @method - * @param {string} ns The MongoDB fully qualified namespace (ex: db1.collection1) - * @param {array} ops An array of documents to insert - * @param {boolean} [options.ordered=true] Execute in order or out of order - * @param {object} [options.writeConcern={}] Write concern for the operation - * @param {Boolean} [options.serializeFunctions=false] Specify if functions on an object should be serialized. - * @param {Boolean} [options.ignoreUndefined=false] Specify if the BSON serializer should ignore undefined fields. - * @param {opResultCallback} callback A callback function - */ -Server.prototype.insert = function(ns, ops, options, callback) { - var self = this; - if(typeof options == 'function') callback = options, options = {}, options = options || {}; - var result = basicWriteValidations(self, options); - if(result) return callback(result); - - // If we are not connected or have a disconnectHandler specified - if(disconnectHandler(self, 'insert', ns, ops, options, callback)) return; - - // Setup the docs as an array - ops = Array.isArray(ops) ? ops : [ops]; - - // Execute write - return self.wireProtocolHandler.insert(self.s.pool, self.ismaster, ns, self.s.bson, ops, options, callback); -} - -/** - * Perform one or more update operations - * @method - * @param {string} ns The MongoDB fully qualified namespace (ex: db1.collection1) - * @param {array} ops An array of updates - * @param {boolean} [options.ordered=true] Execute in order or out of order - * @param {object} [options.writeConcern={}] Write concern for the operation - * @param {Boolean} [options.serializeFunctions=false] Specify if functions on an object should be serialized. - * @param {Boolean} [options.ignoreUndefined=false] Specify if the BSON serializer should ignore undefined fields. - * @param {opResultCallback} callback A callback function - */ -Server.prototype.update = function(ns, ops, options, callback) { - var self = this; - if(typeof options == 'function') callback = options, options = {}, options = options || {}; - var result = basicWriteValidations(self, options); - if(result) return callback(result); - - // If we are not connected or have a disconnectHandler specified - if(disconnectHandler(self, 'update', ns, ops, options, callback)) return; - - // Check if we have collation support - if(this.ismaster && this.ismaster.maxWireVersion < 5 && options.collation) { - return callback(new MongoError(f('server %s does not support collation', this.name))); - } - - // Setup the docs as an array - ops = Array.isArray(ops) ? ops : [ops]; - // Execute write - return self.wireProtocolHandler.update(self.s.pool, self.ismaster, ns, self.s.bson, ops, options, callback); -} - -/** - * Perform one or more remove operations - * @method - * @param {string} ns The MongoDB fully qualified namespace (ex: db1.collection1) - * @param {array} ops An array of removes - * @param {boolean} [options.ordered=true] Execute in order or out of order - * @param {object} [options.writeConcern={}] Write concern for the operation - * @param {Boolean} [options.serializeFunctions=false] Specify if functions on an object should be serialized. - * @param {Boolean} [options.ignoreUndefined=false] Specify if the BSON serializer should ignore undefined fields. - * @param {opResultCallback} callback A callback function - */ -Server.prototype.remove = function(ns, ops, options, callback) { - var self = this; - if(typeof options == 'function') callback = options, options = {}, options = options || {}; - var result = basicWriteValidations(self, options); - if(result) return callback(result); - - // If we are not connected or have a disconnectHandler specified - if(disconnectHandler(self, 'remove', ns, ops, options, callback)) return; - - // Check if we have collation support - if(this.ismaster && this.ismaster.maxWireVersion < 5 && options.collation) { - return callback(new MongoError(f('server %s does not support collation', this.name))); - } - - // Setup the docs as an array - ops = Array.isArray(ops) ? ops : [ops]; - // Execute write - return self.wireProtocolHandler.remove(self.s.pool, self.ismaster, ns, self.s.bson, ops, options, callback); -} - -/** - * Get a new cursor - * @method - * @param {string} ns The MongoDB fully qualified namespace (ex: db1.collection1) - * @param {{object}|{Long}} cmd Can be either a command returning a cursor or a cursorId - * @param {object} [options.batchSize=0] Batchsize for the operation - * @param {array} [options.documents=[]] Initial documents list for cursor - * @param {ReadPreference} [options.readPreference] Specify read preference if command supports it - * @param {Boolean} [options.serializeFunctions=false] Specify if functions on an object should be serialized. - * @param {Boolean} [options.ignoreUndefined=false] Specify if the BSON serializer should ignore undefined fields. - * @param {opResultCallback} callback A callback function - */ -Server.prototype.cursor = function(ns, cmd, cursorOptions) { - var s = this.s; - cursorOptions = cursorOptions || {}; - // Set up final cursor type - var FinalCursor = cursorOptions.cursorFactory || s.Cursor; - // Return the cursor - return new FinalCursor(s.bson, ns, cmd, cursorOptions, this, s.options); -} - -/** - * Logout from a database - * @method - * @param {string} db The db we are logging out from - * @param {authResultCallback} callback A callback function - */ -Server.prototype.logout = function(dbName, callback) { - this.s.pool.logout(dbName, callback); -} - -/** - * Authenticate using a specified mechanism - * @method - * @param {string} mechanism The Auth mechanism we are invoking - * @param {string} db The db we are invoking the mechanism against - * @param {...object} param Parameters for the specific mechanism - * @param {authResultCallback} callback A callback function - */ -Server.prototype.auth = function(mechanism, db) { - var self = this; - - // If we have the default mechanism we pick mechanism based on the wire - // protocol max version. If it's >= 3 then scram-sha1 otherwise mongodb-cr - if(mechanism == 'default' && self.ismaster && self.ismaster.maxWireVersion >= 3) { - mechanism = 'scram-sha-1'; - } else if(mechanism == 'default') { - mechanism = 'mongocr'; - } - - // Slice all the arguments off - var args = Array.prototype.slice.call(arguments, 0); - // Set the mechanism - args[0] = mechanism; - // Get the callback - var callback = args[args.length - 1]; - - // If we are not connected or have a disconnectHandler specified - if(disconnectHandler(self, 'auth', db, args, {}, callback)) { - return; - } - - // Do not authenticate if we are an arbiter - if(this.lastIsMaster() && this.lastIsMaster().arbiterOnly) { - return callback(null, true); - } - - // Apply the arguments to the pool - self.s.pool.auth.apply(self.s.pool, args); -} - -/** - * Compare two server instances - * @method - * @param {Server} server Server to compare equality against - * @return {boolean} - */ -Server.prototype.equals = function(server) { - if(typeof server == 'string') return this.name.toLowerCase() == server.toLowerCase(); - if(server.name) return this.name.toLowerCase() == server.name.toLowerCase(); - return false; -} - -/** - * All raw connections - * @method - * @return {Connection[]} - */ -Server.prototype.connections = function() { - return this.s.pool.allConnections(); -} - -/** - * Get server - * @method - * @return {Server} - */ -Server.prototype.getServer = function() { - return this; -} - -/** - * Get connection - * @method - * @return {Connection} - */ -Server.prototype.getConnection = function() { - return this.s.pool.get(); -} - -var listeners = ['close', 'error', 'timeout', 'parseError', 'connect']; - -/** - * Destroy the server connection - * @method - * @param {boolean} [options.emitClose=false] Emit close event on destroy - * @param {boolean} [options.emitDestroy=false] Emit destroy event on destroy - * @param {boolean} [options.force=false] Force destroy the pool - */ -Server.prototype.destroy = function(options) { - options = options || {}; - var self = this; - - // Set the connections - if(serverAccounting) delete servers[this.id]; - - // Destroy the monitoring process if any - if(this.monitoringProcessId) { - clearTimeout(this.monitoringProcessId); - } - - // No pool, return - if(!self.s.pool) return; - - // Emit close event - if(options.emitClose) { - self.emit('close', self); - } - - // Emit destroy event - if(options.emitDestroy) { - self.emit('destroy', self); - } - - // Remove all listeners - listeners.forEach(function(event) { - self.s.pool.removeAllListeners(event); - }); - - // Emit opening server event - if(self.listeners('serverClosed').length > 0) self.emit('serverClosed', { - topologyId: self.s.topologyId != -1 ? self.s.topologyId : self.id, address: self.name - }); - - // Emit toplogy opening event if not in topology - if(self.listeners('topologyClosed').length > 0 && !self.s.inTopology) { - self.emit('topologyClosed', { topologyId: self.id }); - } - - if(self.s.logger.isDebug()) { - self.s.logger.debug(f('destroy called on server %s', self.name)); - } - - // Destroy the pool - this.s.pool.destroy(options.force); -} - -/** - * A server connect event, used to verify that the connection is up and running - * - * @event Server#connect - * @type {Server} - */ - -/** - * A server reconnect event, used to verify that the server topology has reconnected - * - * @event Server#reconnect - * @type {Server} - */ - -/** - * A server opening SDAM monitoring event - * - * @event Server#serverOpening - * @type {object} - */ - -/** - * A server closed SDAM monitoring event - * - * @event Server#serverClosed - * @type {object} - */ - -/** - * A server description SDAM change monitoring event - * - * @event Server#serverDescriptionChanged - * @type {object} - */ - -/** - * A topology open SDAM event - * - * @event Server#topologyOpening - * @type {object} - */ - -/** - * A topology closed SDAM event - * - * @event Server#topologyClosed - * @type {object} - */ - -/** - * A topology structure SDAM change event - * - * @event Server#topologyDescriptionChanged - * @type {object} - */ - -/** - * Server reconnect failed - * - * @event Server#reconnectFailed - * @type {Error} - */ - -/** - * Server connection pool closed - * - * @event Server#close - * @type {object} - */ - -/** - * Server connection pool caused an error - * - * @event Server#error - * @type {Error} - */ - -/** - * Server destroyed was called - * - * @event Server#destroy - * @type {Server} - */ - -module.exports = Server; diff --git a/ts-ticket-office-service/node_modules/mongodb-core/lib/topologies/shared.js b/ts-ticket-office-service/node_modules/mongodb-core/lib/topologies/shared.js deleted file mode 100644 index 0de356232..000000000 --- a/ts-ticket-office-service/node_modules/mongodb-core/lib/topologies/shared.js +++ /dev/null @@ -1,328 +0,0 @@ -"use strict" - -var os = require('os'), - f = require('util').format; - -/** - * Emit event if it exists - * @method - */ -function emitSDAMEvent(self, event, description) { - if(self.listeners(event).length > 0) { - self.emit(event, description); - } -} - -// Get package.json variable -var driverVersion = require('../../package.json').version; -var nodejsversion = f('Node.js %s, %s', process.version, os.endianness()); -var type = os.type(); -var name = process.platform; -var architecture = process.arch; -var release = os.release(); - -function createClientInfo(options) { - // Build default client information - var clientInfo = options.clientInfo ? clone(options.clientInfo) : { - driver: { - name: "nodejs-core", - version: driverVersion - }, - os: { - type: type, - name: name, - architecture: architecture, - version: release - } - } - - // Is platform specified - if(clientInfo.platform && clientInfo.platform.indexOf('mongodb-core') == -1) { - clientInfo.platform = f('%s, mongodb-core: %s', clientInfo.platform, driverVersion); - } else if(!clientInfo.platform){ - clientInfo.platform = nodejsversion; - } - - // Do we have an application specific string - if(options.appname) { - // Cut at 128 bytes - var buffer = new Buffer(options.appname); - // Return the truncated appname - var appname = buffer.length > 128 ? buffer.slice(0, 128).toString('utf8') : options.appname; - // Add to the clientInfo - clientInfo.application = { name: appname }; - } - - return clientInfo; -} - -function clone(object) { - return JSON.parse(JSON.stringify(object)); -} - -var getPreviousDescription = function(self) { - if(!self.s.serverDescription) { - self.s.serverDescription = { - address: self.name, - arbiters: [], hosts: [], passives: [], type: 'Unknown' - } - } - - return self.s.serverDescription; -} - -var emitServerDescriptionChanged = function(self, description) { - if(self.listeners('serverDescriptionChanged').length > 0) { - // Emit the server description changed events - self.emit('serverDescriptionChanged', { - topologyId: self.s.topologyId != -1 ? self.s.topologyId : self.id, address: self.name, - previousDescription: getPreviousDescription(self), - newDescription: description - }); - - self.s.serverDescription = description; - } -} - -var getPreviousTopologyDescription = function(self) { - if(!self.s.topologyDescription) { - self.s.topologyDescription = { - topologyType: 'Unknown', - servers: [{ - address: self.name, arbiters: [], hosts: [], passives: [], type: 'Unknown' - }] - } - } - - return self.s.topologyDescription; -} - -var emitTopologyDescriptionChanged = function(self, description) { - if(self.listeners('topologyDescriptionChanged').length > 0) { - // Emit the server description changed events - self.emit('topologyDescriptionChanged', { - topologyId: self.s.topologyId != -1 ? self.s.topologyId : self.id, address: self.name, - previousDescription: getPreviousTopologyDescription(self), - newDescription: description - }); - - self.s.serverDescription = description; - } -} - -var changedIsMaster = function(self, currentIsmaster, ismaster) { - var currentType = getTopologyType(self, currentIsmaster); - var newType = getTopologyType(self, ismaster); - if(newType != currentType) return true; - return false; -} - -var getTopologyType = function(self, ismaster) { - if(!ismaster) { - ismaster = self.ismaster; - } - - if(!ismaster) return 'Unknown'; - if(ismaster.ismaster && ismaster.msg == 'isdbgrid') return 'Mongos'; - if(ismaster.ismaster && !ismaster.hosts) return 'Standalone'; - if(ismaster.ismaster) return 'RSPrimary'; - if(ismaster.secondary) return 'RSSecondary'; - if(ismaster.arbiterOnly) return 'RSArbiter'; - return 'Unknown'; -} - -var inquireServerState = function(self) { - return function(callback) { - if(self.s.state == 'destroyed') return; - // Record response time - var start = new Date().getTime(); - - // emitSDAMEvent - emitSDAMEvent(self, 'serverHeartbeatStarted', { connectionId: self.name }); - - // Attempt to execute ismaster command - self.command('admin.$cmd', { ismaster:true }, { monitoring:true }, function(err, r) { - if(!err) { - // Legacy event sender - self.emit('ismaster', r, self); - - // Calculate latencyMS - var latencyMS = new Date().getTime() - start; - - // Server heart beat event - emitSDAMEvent(self, 'serverHeartbeatSucceeded', { durationMS: latencyMS, reply: r.result, connectionId: self.name }); - - // Did the server change - if(changedIsMaster(self, self.s.ismaster, r.result)) { - // Emit server description changed if something listening - emitServerDescriptionChanged(self, { - address: self.name, arbiters: [], hosts: [], passives: [], type: !self.s.inTopology ? 'Standalone' : getTopologyType(self) - }); - } - - // Updat ismaster view - self.s.ismaster = r.result; - - // Set server response time - self.s.isMasterLatencyMS = latencyMS; - } else { - emitSDAMEvent(self, 'serverHeartbeatFailed', { durationMS: latencyMS, failure: err, connectionId: self.name }); - } - - // Peforming an ismaster monitoring callback operation - if(typeof callback == 'function') { - return callback(err, r); - } - - // Perform another sweep - self.s.inquireServerStateTimeout = setTimeout(inquireServerState(self), self.s.haInterval); - }); - }; -} - -// -// Clone the options -var cloneOptions = function(options) { - var opts = {}; - for(var name in options) { - opts[name] = options[name]; - } - return opts; -} - -function Interval(fn, time) { - var timer = false; - - this.start = function () { - if (!this.isRunning()) { - timer = setInterval(fn, time); - } - - return this; - }; - - this.stop = function () { - clearInterval(timer); - timer = false; - return this; - }; - - this.isRunning = function () { - return timer !== false; - }; -} - -function Timeout(fn, time) { - var timer = false; - - this.start = function () { - if (!this.isRunning()) { - timer = setTimeout(fn, time); - } - return this; - }; - - this.stop = function () { - clearTimeout(timer); - timer = false; - return this; - }; - - this.isRunning = function () { - if(timer && timer._called) return false; - return timer !== false; - }; -} - -function diff(previous, current) { - // Difference document - var diff = { - servers: [] - } - - // Previous entry - if(!previous) { - previous = { servers: [] }; - } - - // Check if we have any previous servers missing in the current ones - for(var i = 0; i < previous.servers.length; i++) { - var found = false; - - for(var j = 0; j < current.servers.length; j++) { - if(current.servers[j].address.toLowerCase() - === previous.servers[i].address.toLowerCase()) { - found = true; - break; - } - } - - if(!found) { - // Add to the diff - diff.servers.push({ - address: previous.servers[i].address, - from: previous.servers[i].type, - to: 'Unknown', - }); - } - } - - // Check if there are any severs that don't exist - for(var j = 0; j < current.servers.length; j++) { - var found = false; - - // Go over all the previous servers - for(var i = 0; i < previous.servers.length; i++) { - if(previous.servers[i].address.toLowerCase() - === current.servers[j].address.toLowerCase()) { - found = true; - break; - } - } - - // Add the server to the diff - if(!found) { - diff.servers.push({ - address: current.servers[j].address, - from: 'Unknown', - to: current.servers[j].type, - }); - } - } - - // Got through all the servers - for(var i = 0; i < previous.servers.length; i++) { - var prevServer = previous.servers[i]; - - // Go through all current servers - for(var j = 0; j < current.servers.length; j++) { - var currServer = current.servers[j]; - - // Matching server - if(prevServer.address.toLowerCase() === currServer.address.toLowerCase()) { - // We had a change in state - if(prevServer.type != currServer.type) { - diff.servers.push({ - address: prevServer.address, - from: prevServer.type, - to: currServer.type - }); - } - } - } - } - - // Return difference - return diff; -} - -module.exports.inquireServerState = inquireServerState -module.exports.getTopologyType = getTopologyType; -module.exports.emitServerDescriptionChanged = emitServerDescriptionChanged; -module.exports.emitTopologyDescriptionChanged = emitTopologyDescriptionChanged; -module.exports.cloneOptions = cloneOptions; -module.exports.createClientInfo = createClientInfo; -module.exports.clone = clone; -module.exports.diff = diff; -module.exports.Interval = Interval; -module.exports.Timeout = Timeout; diff --git a/ts-ticket-office-service/node_modules/mongodb-core/lib/utils.js b/ts-ticket-office-service/node_modules/mongodb-core/lib/utils.js deleted file mode 100644 index afc2cedb0..000000000 --- a/ts-ticket-office-service/node_modules/mongodb-core/lib/utils.js +++ /dev/null @@ -1,32 +0,0 @@ -/** - * Copy the values of all enumerable own properties from one or more - * source objects to a target object. It will return the target object. - */ -var assign = Object.assign ? Object.assign : function assign(target) { - if (target === undefined || target === null) { - throw new TypeError('Cannot convert first argument to object'); - } - - var to = Object(target); - for (var i = 1; i < arguments.length; i++) { - var nextSource = arguments[i]; - if (nextSource === undefined || nextSource === null) { - continue; - } - - var keysArray = Object.keys(Object(nextSource)); - for (var nextIndex = 0, len = keysArray.length; nextIndex < len; nextIndex++) { - var nextKey = keysArray[nextIndex]; - var desc = Object.getOwnPropertyDescriptor(nextSource, nextKey); - if (desc !== undefined && desc.enumerable) { - to[nextKey] = nextSource[nextKey]; - } - } - } - - return to; -} - -module.exports = { - assign: assign -}; diff --git a/ts-ticket-office-service/node_modules/mongodb-core/lib/wireprotocol/2_4_support.js b/ts-ticket-office-service/node_modules/mongodb-core/lib/wireprotocol/2_4_support.js deleted file mode 100644 index b3056fd99..000000000 --- a/ts-ticket-office-service/node_modules/mongodb-core/lib/wireprotocol/2_4_support.js +++ /dev/null @@ -1,570 +0,0 @@ -"use strict"; - -var Insert = require('./commands').Insert - , Update = require('./commands').Update - , Remove = require('./commands').Remove - , copy = require('../connection/utils').copy - , retrieveBSON = require('../connection/utils').retrieveBSON - , KillCursor = require('../connection/commands').KillCursor - , GetMore = require('../connection/commands').GetMore - , Query = require('../connection/commands').Query - , f = require('util').format - , CommandResult = require('../connection/command_result') - , MongoError = require('../error') - , getReadPreference = require('./shared').getReadPreference; - -var BSON = retrieveBSON(), - Long = BSON.Long; - -// Write concern fields -var writeConcernFields = ['w', 'wtimeout', 'j', 'fsync']; - -var WireProtocol = function() {} - -// -// Needs to support legacy mass insert as well as ordered/unordered legacy -// emulation -// -WireProtocol.prototype.insert = function(pool, ismaster, ns, bson, ops, options, callback) { - options = options || {}; - // Default is ordered execution - var ordered = typeof options.ordered == 'boolean' ? options.ordered : true; - ops = Array.isArray(ops) ? ops :[ops]; - - // If we have more than a 1000 ops fails - if(ops.length > 1000) return callback(new MongoError("exceeded maximum write batch size of 1000")); - - // Write concern - var writeConcern = options.writeConcern || {w:1}; - - // We are unordered - if(!ordered || writeConcern.w == 0) { - return executeUnordered('insert', Insert, ismaster, ns, bson, pool, ops, options, callback); - } - - return executeOrdered('insert', Insert, ismaster, ns, bson, pool, ops, options, callback); -} - -WireProtocol.prototype.update = function(pool, ismaster, ns, bson, ops, options, callback) { - options = options || {}; - // Default is ordered execution - var ordered = typeof options.ordered == 'boolean' ? options.ordered : true; - ops = Array.isArray(ops) ? ops :[ops]; - - // Write concern - var writeConcern = options.writeConcern || {w:1}; - - // We are unordered - if(!ordered || writeConcern.w == 0) { - return executeUnordered('update', Update, ismaster, ns, bson, pool, ops, options, callback); - } - - return executeOrdered('update', Update, ismaster, ns, bson, pool, ops, options, callback); -} - -WireProtocol.prototype.remove = function(pool, ismaster, ns, bson, ops, options, callback) { - options = options || {}; - // Default is ordered execution - var ordered = typeof options.ordered == 'boolean' ? options.ordered : true; - ops = Array.isArray(ops) ? ops :[ops]; - - // Write concern - var writeConcern = options.writeConcern || {w:1}; - - // We are unordered - if(!ordered || writeConcern.w == 0) { - return executeUnordered('remove', Remove, ismaster, ns, bson, pool, ops, options, callback); - } - - return executeOrdered('remove', Remove, ismaster, ns, bson, pool, ops, options, callback); -} - -WireProtocol.prototype.killCursor = function(bson, ns, cursorId, pool, callback) { - // Create a kill cursor command - var killCursor = new KillCursor(bson, [cursorId]); - // Execute the kill cursor command - if(pool && pool.isConnected()) { - pool.write(killCursor, { - immediateRelease:true, noResponse: true - }); - } - - // Callback - if(typeof callback == 'function') callback(null, null); -} - -WireProtocol.prototype.getMore = function(bson, ns, cursorState, batchSize, raw, connection, options, callback) { - // Create getMore command - var getMore = new GetMore(bson, ns, cursorState.cursorId, {numberToReturn: batchSize}); - - // Query callback - var queryCallback = function(err, result) { - if(err) return callback(err); - // Get the raw message - var r = result.message; - - // If we have a timed out query or a cursor that was killed - if((r.responseFlags & (1 << 0)) != 0) { - return callback(new MongoError("cursor does not exist, was killed or timed out"), null); - } - - // Ensure we have a Long valie cursor id - var cursorId = typeof r.cursorId == 'number' - ? Long.fromNumber(r.cursorId) - : r.cursorId; - - // Set all the values - cursorState.documents = r.documents; - cursorState.cursorId = cursorId; - - // Return - callback(null, null, r.connection); - } - - // Contains any query options - var queryOptions = {}; - - // If we have a raw query decorate the function - if(raw) { - queryOptions.raw = raw; - } - - // Check if we need to promote longs - if(typeof cursorState.promoteLongs == 'boolean') { - queryOptions.promoteLongs = cursorState.promoteLongs; - } - - if(typeof cursorState.promoteValues == 'boolean') { - queryOptions.promoteValues = cursorState.promoteValues; - } - - if(typeof cursorState.promoteBuffers == 'boolean') { - queryOptions.promoteBuffers = cursorState.promoteBuffers; - } - - // Write out the getMore command - connection.write(getMore, queryOptions, queryCallback); -} - -WireProtocol.prototype.command = function(bson, ns, cmd, cursorState, topology, options) { - // Establish type of command - if(cmd.find) { - return setupClassicFind(bson, ns, cmd, cursorState, topology, options) - } else if(cursorState.cursorId != null) { - return; - } else if(cmd) { - return setupCommand(bson, ns, cmd, cursorState, topology, options); - } else { - throw new MongoError(f("command %s does not return a cursor", JSON.stringify(cmd))); - } -} - -// -// Execute a find command -var setupClassicFind = function(bson, ns, cmd, cursorState, topology, options) { - // Ensure we have at least some options - options = options || {}; - // Get the readPreference - var readPreference = getReadPreference(cmd, options); - // Set the optional batchSize - cursorState.batchSize = cmd.batchSize || cursorState.batchSize; - var numberToReturn = 0; - - // Unpack the limit and batchSize values - if(cursorState.limit == 0) { - numberToReturn = cursorState.batchSize; - } else if(cursorState.limit < 0 || cursorState.limit < cursorState.batchSize || (cursorState.limit > 0 && cursorState.batchSize == 0)) { - numberToReturn = cursorState.limit; - } else { - numberToReturn = cursorState.batchSize; - } - - var numberToSkip = cursorState.skip || 0; - // Build actual find command - var findCmd = {}; - // Using special modifier - var usesSpecialModifier = false; - - // We have a Mongos topology, check if we need to add a readPreference - if(topology.type == 'mongos' && readPreference) { - findCmd['$readPreference'] = readPreference.toJSON(); - usesSpecialModifier = true; - } - - // Add special modifiers to the query - if(cmd.sort) findCmd['orderby'] = cmd.sort, usesSpecialModifier = true; - if(cmd.hint) findCmd['$hint'] = cmd.hint, usesSpecialModifier = true; - if(cmd.snapshot) findCmd['$snapshot'] = cmd.snapshot, usesSpecialModifier = true; - if(cmd.returnKey) findCmd['$returnKey'] = cmd.returnKey, usesSpecialModifier = true; - if(cmd.maxScan) findCmd['$maxScan'] = cmd.maxScan, usesSpecialModifier = true; - if(cmd.min) findCmd['$min'] = cmd.min, usesSpecialModifier = true; - if(cmd.max) findCmd['$max'] = cmd.max, usesSpecialModifier = true; - if(cmd.showDiskLoc) findCmd['$showDiskLoc'] = cmd.showDiskLoc, usesSpecialModifier = true; - if(cmd.comment) findCmd['$comment'] = cmd.comment, usesSpecialModifier = true; - if(cmd.maxTimeMS) findCmd['$maxTimeMS'] = cmd.maxTimeMS, usesSpecialModifier = true; - - if(cmd.explain) { - // nToReturn must be 0 (match all) or negative (match N and close cursor) - // nToReturn > 0 will give explain results equivalent to limit(0) - numberToReturn = -Math.abs(cmd.limit || 0); - usesSpecialModifier = true; - findCmd['$explain'] = true; - } - - // If we have a special modifier - if(usesSpecialModifier) { - findCmd['$query'] = cmd.query; - } else { - findCmd = cmd.query; - } - - // Throw on majority readConcern passed in - if(cmd.readConcern && cmd.readConcern.level != 'local') { - throw new MongoError(f('server find command does not support a readConcern level of %s', cmd.readConcern.level)); - } - - // Remove readConcern, ensure no failing commands - if(cmd.readConcern) { - cmd = copy(cmd); - delete cmd['readConcern']; - } - - // Set up the serialize and ignoreUndefined fields - var serializeFunctions = typeof options.serializeFunctions == 'boolean' - ? options.serializeFunctions : false; - var ignoreUndefined = typeof options.ignoreUndefined == 'boolean' - ? options.ignoreUndefined : false; - - // Build Query object - var query = new Query(bson, ns, findCmd, { - numberToSkip: numberToSkip, numberToReturn: numberToReturn - , checkKeys: false, returnFieldSelector: cmd.fields - , serializeFunctions: serializeFunctions, ignoreUndefined: ignoreUndefined - }); - - // Set query flags - query.slaveOk = readPreference.slaveOk(); - - // Set up the option bits for wire protocol - if(typeof cmd.tailable == 'boolean') query.tailable = cmd.tailable; - if(typeof cmd.oplogReplay == 'boolean') query.oplogReplay = cmd.oplogReplay; - if(typeof cmd.noCursorTimeout == 'boolean') query.noCursorTimeout = cmd.noCursorTimeout; - if(typeof cmd.awaitData == 'boolean') query.awaitData = cmd.awaitData; - if(typeof cmd.partial == 'boolean') query.partial = cmd.partial; - // Return the query - return query; -} - -// -// Set up a command cursor -var setupCommand = function(bson, ns, cmd, cursorState, topology, options) { - // Set empty options object - options = options || {} - // Get the readPreference - var readPreference = getReadPreference(cmd, options); - // Final query - var finalCmd = {}; - for(var name in cmd) { - finalCmd[name] = cmd[name]; - } - - // Build command namespace - var parts = ns.split(/\./); - - // Throw on majority readConcern passed in - if(cmd.readConcern && cmd.readConcern.level != 'local') { - throw new MongoError(f('server %s command does not support a readConcern level of %s', JSON.stringify(cmd), cmd.readConcern.level)); - } - - // Remove readConcern, ensure no failing commands - if(cmd.readConcern) delete cmd['readConcern']; - - // Serialize functions - var serializeFunctions = typeof options.serializeFunctions == 'boolean' - ? options.serializeFunctions : false; - - // Set up the serialize and ignoreUndefined fields - var ignoreUndefined = typeof options.ignoreUndefined == 'boolean' - ? options.ignoreUndefined : false; - - // We have a Mongos topology, check if we need to add a readPreference - if(topology.type == 'mongos' - && readPreference - && readPreference.preference != 'primary') { - finalCmd = { - '$query': finalCmd, - '$readPreference': readPreference.toJSON() - }; - } - - // Build Query object - var query = new Query(bson, f('%s.$cmd', parts.shift()), finalCmd, { - numberToSkip: 0, numberToReturn: -1 - , checkKeys: false, serializeFunctions: serializeFunctions - , ignoreUndefined: ignoreUndefined - }); - - // Set query flags - query.slaveOk = readPreference.slaveOk(); - - // Return the query - return query; -} - -var hasWriteConcern = function(writeConcern) { - if(writeConcern.w - || writeConcern.wtimeout - || writeConcern.j == true - || writeConcern.fsync == true - || Object.keys(writeConcern).length == 0) { - return true; - } - return false; -} - -var cloneWriteConcern = function(writeConcern) { - var wc = {}; - if(writeConcern.w != null) wc.w = writeConcern.w; - if(writeConcern.wtimeout != null) wc.wtimeout = writeConcern.wtimeout; - if(writeConcern.j != null) wc.j = writeConcern.j; - if(writeConcern.fsync != null) wc.fsync = writeConcern.fsync; - return wc; -} - -// -// Aggregate up all the results -// -var aggregateWriteOperationResults = function(opType, ops, results, connection) { - var finalResult = { ok: 1, n: 0 } - if(opType == 'update') { - finalResult.nModified = 0; - } - - // Map all the results coming back - for(var i = 0; i < results.length; i++) { - var result = results[i]; - var op = ops[i]; - - if((result.upserted || (result.updatedExisting == false)) && finalResult.upserted == null) { - finalResult.upserted = []; - } - - // Push the upserted document to the list of upserted values - if(result.upserted) { - finalResult.upserted.push({index: i, _id: result.upserted}); - } - - // We have an upsert where we passed in a _id - if(result.updatedExisting == false && result.n == 1 && result.upserted == null) { - finalResult.upserted.push({index: i, _id: op.q._id}); - } else if(result.updatedExisting == true) { - finalResult.nModified += result.n; - } - - // We have an insert command - if(result.ok == 1 && opType == 'insert' && result.err == null) { - finalResult.n = finalResult.n + 1; - } - - // We have a command error - if(result != null && result.ok == 0 || result.err || result.errmsg) { - if(result.ok == 0) finalResult.ok = 0; - finalResult.code = result.code; - finalResult.errmsg = result.errmsg || result.err || result.errMsg; - - // Check if we have a write error - if(result.code == 11000 - || result.code == 11001 - || result.code == 12582 - || result.code == 16544 - || result.code == 16538 - || result.code == 16542 - || result.code == 14 - || result.code == 13511) { - if(finalResult.writeErrors == null) finalResult.writeErrors = []; - finalResult.writeErrors.push({ - index: i - , code: result.code - , errmsg: result.errmsg || result.err || result.errMsg - }); - } else { - finalResult.writeConcernError = { - code: result.code - , errmsg: result.errmsg || result.err || result.errMsg - } - } - } else if(typeof result.n == 'number') { - finalResult.n += result.n; - } else { - finalResult.n += 1; - } - - // Result as expected - if(result != null && result.lastOp) finalResult.lastOp = result.lastOp; - } - - // Return finalResult aggregated results - return new CommandResult(finalResult, connection); -} - -// -// Execute all inserts in an ordered manner -// -var executeOrdered = function(opType ,command, ismaster, ns, bson, pool, ops, options, callback) { - var _ops = ops.slice(0); - // Collect all the getLastErrors - var getLastErrors = []; - // Execute an operation - var executeOp = function(list, _callback) { - // No more items in the list - if(list.length == 0) { - return process.nextTick(function() { - _callback(null, aggregateWriteOperationResults(opType, ops, getLastErrors, null)); - }); - } - - // Get the first operation - var doc = list.shift(); - // Create an insert command - var op = new command(Query.getRequestId(), ismaster, bson, ns, [doc], options); - // Write concern - var optionWriteConcern = options.writeConcern || {w:1}; - // Final write concern - var writeConcern = cloneWriteConcern(optionWriteConcern); - - // Get the db name - var db = ns.split('.').shift(); - - try { - // Add binary message to list of commands to execute - var commands = [op]; - - // Add getLastOrdered - var getLastErrorCmd = {getlasterror: 1}; - // Merge all the fields - for(var i = 0; i < writeConcernFields.length; i++) { - if(writeConcern[writeConcernFields[i]] != null) { - getLastErrorCmd[writeConcernFields[i]] = writeConcern[writeConcernFields[i]]; - } - } - - // Create a getLastError command - var getLastErrorOp = new Query(bson, f("%s.$cmd", db), getLastErrorCmd, {numberToReturn: -1}); - // Add getLastError command to list of ops to execute - commands.push(getLastErrorOp); - - // getLastError callback - var getLastErrorCallback = function(err, result) { - if(err) return callback(err); - // Get the document - var doc = result.result; - // Save the getLastError document - getLastErrors.push(doc); - - // If we have an error terminate - if(doc.ok == 0 || doc.err || doc.errmsg) { - return callback(null, aggregateWriteOperationResults(opType, ops, getLastErrors, result.connection)); - } - - // Execute the next op in the list - executeOp(list, callback); - } - - // Write both commands out at the same time - pool.write(commands, getLastErrorCallback); - } catch(err) { - // We have a serialization error, rewrite as a write error to have same behavior as modern - // write commands - getLastErrors.push({ ok: 1, errmsg: typeof err == 'string' ? err : err.message, code: 14 }); - // Return due to an error - process.nextTick(function() { - _callback(null, aggregateWriteOperationResults(opType, ops, getLastErrors, null)); - }); - } - } - - // Execute the operations - executeOp(_ops, callback); -} - -var executeUnordered = function(opType, command, ismaster, ns, bson, pool, ops, options, callback) { - // Total operations to write - var totalOps = ops.length; - // Collect all the getLastErrors - var getLastErrors = []; - // Write concern - var optionWriteConcern = options.writeConcern || {w:1}; - // Final write concern - var writeConcern = cloneWriteConcern(optionWriteConcern); - // Driver level error - var error; - - // Execute all the operations - for(var i = 0; i < ops.length; i++) { - // Create an insert command - var op = new command(Query.getRequestId(), ismaster, bson, ns, [ops[i]], options); - // Get db name - var db = ns.split('.').shift(); - - try { - // Add binary message to list of commands to execute - var commands = [op]; - - // If write concern 0 don't fire getLastError - if(hasWriteConcern(writeConcern)) { - var getLastErrorCmd = {getlasterror: 1}; - // Merge all the fields - for(var j = 0; j < writeConcernFields.length; j++) { - if(writeConcern[writeConcernFields[j]] != null) - getLastErrorCmd[writeConcernFields[j]] = writeConcern[writeConcernFields[j]]; - } - - // Create a getLastError command - var getLastErrorOp = new Query(bson, f("%s.$cmd", db), getLastErrorCmd, {numberToReturn: -1}); - // Add getLastError command to list of ops to execute - commands.push(getLastErrorOp); - - // Give the result from getLastError the right index - var callbackOp = function(_index) { - return function(err, result) { - if(err) error = err; - // Update the number of operations executed - totalOps = totalOps - 1; - // Save the getLastError document - if(!err) getLastErrors[_index] = result.result; - // Check if we are done - if(totalOps == 0) { - process.nextTick(function() { - if(error) return callback(error); - callback(null, aggregateWriteOperationResults(opType, ops, getLastErrors, result.connection)); - }); - } - } - } - - // Write both commands out at the same time - pool.write(commands, callbackOp(i)); - } else { - pool.write(commands, {immediateRelease:true, noResponse:true}); - } - } catch(err) { - // Update the number of operations executed - totalOps = totalOps - 1; - // We have a serialization error, rewrite as a write error to have same behavior as modern - // write commands - getLastErrors[i] = { ok: 1, errmsg: typeof err == 'string' ? err : err.message, code: 14 }; - // Check if we are done - if(totalOps == 0) { - callback(null, aggregateWriteOperationResults(opType, ops, getLastErrors, null)); - } - } - } - - // Empty w:0 return - if(writeConcern - && writeConcern.w == 0 && callback) { - callback(null, new CommandResult({ok:1}, null)); - } -} - -module.exports = WireProtocol; diff --git a/ts-ticket-office-service/node_modules/mongodb-core/lib/wireprotocol/2_6_support.js b/ts-ticket-office-service/node_modules/mongodb-core/lib/wireprotocol/2_6_support.js deleted file mode 100644 index 90e510c80..000000000 --- a/ts-ticket-office-service/node_modules/mongodb-core/lib/wireprotocol/2_6_support.js +++ /dev/null @@ -1,334 +0,0 @@ -"use strict"; - -var copy = require('../connection/utils').copy - , retrieveBSON = require('../connection/utils').retrieveBSON - , KillCursor = require('../connection/commands').KillCursor - , GetMore = require('../connection/commands').GetMore - , Query = require('../connection/commands').Query - , f = require('util').format - , MongoError = require('../error') - , getReadPreference = require('./shared').getReadPreference; - -var BSON = retrieveBSON(), - Long = BSON.Long; - -var WireProtocol = function() {} - -// -// Execute a write operation -var executeWrite = function(pool, bson, type, opsField, ns, ops, options, callback) { - if(ops.length == 0) throw new MongoError("insert must contain at least one document"); - if(typeof options == 'function') { - callback = options; - options = {}; - options = options || {}; - } - - // Split the ns up to get db and collection - var p = ns.split("."); - var d = p.shift(); - // Options - var ordered = typeof options.ordered == 'boolean' ? options.ordered : true; - var writeConcern = options.writeConcern; - - // return skeleton - var writeCommand = {}; - writeCommand[type] = p.join('.'); - writeCommand[opsField] = ops; - writeCommand.ordered = ordered; - - // Did we specify a write concern - if(writeConcern && Object.keys(writeConcern).length > 0) { - writeCommand.writeConcern = writeConcern; - } - - // Do we have bypassDocumentValidation set, then enable it on the write command - if(typeof options.bypassDocumentValidation == 'boolean') { - writeCommand.bypassDocumentValidation = options.bypassDocumentValidation; - } - - // Options object - var opts = { command: true }; - var queryOptions = { checkKeys : false, numberToSkip: 0, numberToReturn: 1 }; - if(type == 'insert') queryOptions.checkKeys = true; - if(typeof options.checkKeys == 'boolean') queryOptions.checkKeys = options.checkKeys; - // Ensure we support serialization of functions - if(options.serializeFunctions) queryOptions.serializeFunctions = options.serializeFunctions; - // Do not serialize the undefined fields - if(options.ignoreUndefined) queryOptions.ignoreUndefined = options.ignoreUndefined; - - try { - // Create write command - var cmd = new Query(bson, f("%s.$cmd", d), writeCommand, queryOptions); - // Execute command - pool.write(cmd, opts, callback); - } catch(err) { - callback(err); - } -} - -// -// Needs to support legacy mass insert as well as ordered/unordered legacy -// emulation -// -WireProtocol.prototype.insert = function(pool, ismaster, ns, bson, ops, options, callback) { - executeWrite(pool, bson, 'insert', 'documents', ns, ops, options, callback); -} - -WireProtocol.prototype.update = function(pool, ismaster, ns, bson, ops, options, callback) { - executeWrite(pool, bson, 'update', 'updates', ns, ops, options, callback); -} - -WireProtocol.prototype.remove = function(pool, ismaster, ns, bson, ops, options, callback) { - executeWrite(pool, bson, 'delete', 'deletes', ns, ops, options, callback); -} - -WireProtocol.prototype.killCursor = function(bson, ns, cursorId, pool, callback) { - // Create a kill cursor command - var killCursor = new KillCursor(bson, [cursorId]); - // Execute the kill cursor command - if(pool && pool.isConnected()) { - pool.write(killCursor, { - immediateRelease:true, noResponse: true - }); - } - - // Callback - if(typeof callback == 'function') callback(null, null); -} - -WireProtocol.prototype.getMore = function(bson, ns, cursorState, batchSize, raw, connection, options, callback) { - // Create getMore command - var getMore = new GetMore(bson, ns, cursorState.cursorId, {numberToReturn: batchSize}); - - // Query callback - var queryCallback = function(err, result) { - if(err) return callback(err); - // Get the raw message - var r = result.message; - - // If we have a timed out query or a cursor that was killed - if((r.responseFlags & (1 << 0)) != 0) { - return callback(new MongoError("cursor does not exist, was killed or timed out"), null); - } - - // Ensure we have a Long valie cursor id - var cursorId = typeof r.cursorId == 'number' - ? Long.fromNumber(r.cursorId) - : r.cursorId; - - // Set all the values - cursorState.documents = r.documents; - cursorState.cursorId = cursorId; - - // Return - callback(null, null, r.connection); - } - - // Contains any query options - var queryOptions = {}; - - // If we have a raw query decorate the function - if(raw) { - queryOptions.raw = raw; - } - - // Check if we need to promote longs - if(typeof cursorState.promoteLongs == 'boolean') { - queryOptions.promoteLongs = cursorState.promoteLongs; - } - - if(typeof cursorState.promoteValues == 'boolean') { - queryOptions.promoteValues = cursorState.promoteValues; - } - - if(typeof cursorState.promoteBuffers == 'boolean') { - queryOptions.promoteBuffers = cursorState.promoteBuffers; - } - - // Write out the getMore command - connection.write(getMore, queryOptions, queryCallback); -} - -WireProtocol.prototype.command = function(bson, ns, cmd, cursorState, topology, options) { - // Establish type of command - if(cmd.find) { - return setupClassicFind(bson, ns, cmd, cursorState, topology, options) - } else if(cursorState.cursorId != null) { - return; - } else if(cmd) { - return setupCommand(bson, ns, cmd, cursorState, topology, options); - } else { - throw new MongoError(f("command %s does not return a cursor", JSON.stringify(cmd))); - } -} - -// -// Execute a find command -var setupClassicFind = function(bson, ns, cmd, cursorState, topology, options) { - // Ensure we have at least some options - options = options || {}; - // Get the readPreference - var readPreference = getReadPreference(cmd, options); - // Set the optional batchSize - cursorState.batchSize = cmd.batchSize || cursorState.batchSize; - var numberToReturn = 0; - - // Unpack the limit and batchSize values - if(cursorState.limit == 0) { - numberToReturn = cursorState.batchSize; - } else if(cursorState.limit < 0 || cursorState.limit < cursorState.batchSize || (cursorState.limit > 0 && cursorState.batchSize == 0)) { - numberToReturn = cursorState.limit; - } else { - numberToReturn = cursorState.batchSize; - } - - var numberToSkip = cursorState.skip || 0; - // Build actual find command - var findCmd = {}; - // Using special modifier - var usesSpecialModifier = false; - - // We have a Mongos topology, check if we need to add a readPreference - if(topology.type == 'mongos' && readPreference) { - findCmd['$readPreference'] = readPreference.toJSON(); - usesSpecialModifier = true; - } - - // Add special modifiers to the query - if(cmd.sort) findCmd['orderby'] = cmd.sort, usesSpecialModifier = true; - if(cmd.hint) findCmd['$hint'] = cmd.hint, usesSpecialModifier = true; - if(cmd.snapshot) findCmd['$snapshot'] = cmd.snapshot, usesSpecialModifier = true; - if(cmd.returnKey) findCmd['$returnKey'] = cmd.returnKey, usesSpecialModifier = true; - if(cmd.maxScan) findCmd['$maxScan'] = cmd.maxScan, usesSpecialModifier = true; - if(cmd.min) findCmd['$min'] = cmd.min, usesSpecialModifier = true; - if(cmd.max) findCmd['$max'] = cmd.max, usesSpecialModifier = true; - if(cmd.showDiskLoc) findCmd['$showDiskLoc'] = cmd.showDiskLoc, usesSpecialModifier = true; - if(cmd.comment) findCmd['$comment'] = cmd.comment, usesSpecialModifier = true; - if(cmd.maxTimeMS) findCmd['$maxTimeMS'] = cmd.maxTimeMS, usesSpecialModifier = true; - - if(cmd.explain) { - // nToReturn must be 0 (match all) or negative (match N and close cursor) - // nToReturn > 0 will give explain results equivalent to limit(0) - numberToReturn = -Math.abs(cmd.limit || 0); - usesSpecialModifier = true; - findCmd['$explain'] = true; - } - - // If we have a special modifier - if(usesSpecialModifier) { - findCmd['$query'] = cmd.query; - } else { - findCmd = cmd.query; - } - - // Throw on majority readConcern passed in - if(cmd.readConcern && cmd.readConcern.level != 'local') { - throw new MongoError(f('server find command does not support a readConcern level of %s', cmd.readConcern.level)); - } - - // Remove readConcern, ensure no failing commands - if(cmd.readConcern) { - cmd = copy(cmd); - delete cmd['readConcern']; - } - - // Serialize functions - var serializeFunctions = typeof options.serializeFunctions == 'boolean' - ? options.serializeFunctions : false; - var ignoreUndefined = typeof options.ignoreUndefined == 'boolean' - ? options.ignoreUndefined : false; - - // Build Query object - var query = new Query(bson, ns, findCmd, { - numberToSkip: numberToSkip, numberToReturn: numberToReturn - , checkKeys: false, returnFieldSelector: cmd.fields - , serializeFunctions: serializeFunctions - , ignoreUndefined: ignoreUndefined - }); - - // Set query flags - query.slaveOk = readPreference.slaveOk(); - - // Set up the option bits for wire protocol - if(typeof cmd.tailable == 'boolean') { - query.tailable = cmd.tailable; - } - - if(typeof cmd.oplogReplay == 'boolean') { - query.oplogReplay = cmd.oplogReplay; - } - - if(typeof cmd.noCursorTimeout == 'boolean') { - query.noCursorTimeout = cmd.noCursorTimeout; - } - - if(typeof cmd.awaitData == 'boolean') { - query.awaitData = cmd.awaitData; - } - - if(typeof cmd.partial == 'boolean') { - query.partial = cmd.partial; - } - - // Return the query - return query; -} - -// -// Set up a command cursor -var setupCommand = function(bson, ns, cmd, cursorState, topology, options) { - // Set empty options object - options = options || {} - // Get the readPreference - var readPreference = getReadPreference(cmd, options); - - // Final query - var finalCmd = {}; - for(var name in cmd) { - finalCmd[name] = cmd[name]; - } - - // Build command namespace - var parts = ns.split(/\./); - - // Serialize functions - var serializeFunctions = typeof options.serializeFunctions == 'boolean' - ? options.serializeFunctions : false; - - var ignoreUndefined = typeof options.ignoreUndefined == 'boolean' - ? options.ignoreUndefined : false; - - // Throw on majority readConcern passed in - if(cmd.readConcern && cmd.readConcern.level != 'local') { - throw new MongoError(f('server %s command does not support a readConcern level of %s', JSON.stringify(cmd), cmd.readConcern.level)); - } - - // Remove readConcern, ensure no failing commands - if(cmd.readConcern) delete cmd['readConcern']; - - // We have a Mongos topology, check if we need to add a readPreference - if(topology.type == 'mongos' - && readPreference - && readPreference.preference != 'primary') { - finalCmd = { - '$query': finalCmd, - '$readPreference': readPreference.toJSON() - }; - } - - // Build Query object - var query = new Query(bson, f('%s.$cmd', parts.shift()), finalCmd, { - numberToSkip: 0, numberToReturn: -1 - , checkKeys: false, serializeFunctions: serializeFunctions - , ignoreUndefined: ignoreUndefined - }); - - // Set query flags - query.slaveOk = readPreference.slaveOk(); - - // Return the query - return query; -} - -module.exports = WireProtocol; diff --git a/ts-ticket-office-service/node_modules/mongodb-core/lib/wireprotocol/3_2_support.js b/ts-ticket-office-service/node_modules/mongodb-core/lib/wireprotocol/3_2_support.js deleted file mode 100644 index c48857bdc..000000000 --- a/ts-ticket-office-service/node_modules/mongodb-core/lib/wireprotocol/3_2_support.js +++ /dev/null @@ -1,549 +0,0 @@ -"use strict"; - -var Query = require('../connection/commands').Query - , retrieveBSON = require('../connection/utils').retrieveBSON - , f = require('util').format - , MongoError = require('../error') - , getReadPreference = require('./shared').getReadPreference; - -var BSON = retrieveBSON(), - Long = BSON.Long; - -var WireProtocol = function(legacyWireProtocol) { - this.legacyWireProtocol = legacyWireProtocol; -} - -// -// Execute a write operation -var executeWrite = function(pool, bson, type, opsField, ns, ops, options, callback) { - if(ops.length == 0) throw new MongoError("insert must contain at least one document"); - if(typeof options == 'function') { - callback = options; - options = {}; - options = options || {}; - } - - // Split the ns up to get db and collection - var p = ns.split("."); - var d = p.shift(); - // Options - var ordered = typeof options.ordered == 'boolean' ? options.ordered : true; - var writeConcern = options.writeConcern; - - // return skeleton - var writeCommand = {}; - writeCommand[type] = p.join('.'); - writeCommand[opsField] = ops; - writeCommand.ordered = ordered; - - // Did we specify a write concern - if(writeConcern && Object.keys(writeConcern).length > 0) { - writeCommand.writeConcern = writeConcern; - } - - // If we have collation passed in - if(options.collation) { - for(var i = 0; i < writeCommand[opsField].length; i++) { - if(!writeCommand[opsField][i].collation) { - writeCommand[opsField][i].collation = options.collation; - } - } - } - - // Do we have bypassDocumentValidation set, then enable it on the write command - if(typeof options.bypassDocumentValidation == 'boolean') { - writeCommand.bypassDocumentValidation = options.bypassDocumentValidation; - } - - // Options object - var opts = { command: true }; - var queryOptions = { checkKeys : false, numberToSkip: 0, numberToReturn: 1 }; - if(type == 'insert') queryOptions.checkKeys = true; - if(typeof options.checkKeys == 'boolean') queryOptions.checkKeys = options.checkKeys; - - // Ensure we support serialization of functions - if(options.serializeFunctions) queryOptions.serializeFunctions = options.serializeFunctions; - // Do not serialize the undefined fields - if(options.ignoreUndefined) queryOptions.ignoreUndefined = options.ignoreUndefined; - - try { - // Create write command - var cmd = new Query(bson, f("%s.$cmd", d), writeCommand, queryOptions); - // Execute command - pool.write(cmd, opts, callback); - } catch(err) { - callback(err); - } -} - -// -// Needs to support legacy mass insert as well as ordered/unordered legacy -// emulation -// -WireProtocol.prototype.insert = function(pool, ismaster, ns, bson, ops, options, callback) { - executeWrite(pool, bson, 'insert', 'documents', ns, ops, options, callback); -} - -WireProtocol.prototype.update = function(pool, ismaster, ns, bson, ops, options, callback) { - executeWrite(pool, bson, 'update', 'updates', ns, ops, options, callback); -} - -WireProtocol.prototype.remove = function(pool, ismaster, ns, bson, ops, options, callback) { - executeWrite(pool, bson, 'delete', 'deletes', ns, ops, options, callback); -} - -WireProtocol.prototype.killCursor = function(bson, ns, cursorId, pool, callback) { - // Build command namespace - var parts = ns.split(/\./); - // Command namespace - var commandns = f('%s.$cmd', parts.shift()); - // Create getMore command - var killcursorCmd = { - killCursors: parts.join('.'), - cursors: [cursorId] - } - - // Build Query object - var query = new Query(bson, commandns, killcursorCmd, { - numberToSkip: 0, numberToReturn: -1 - , checkKeys: false, returnFieldSelector: null - }); - - // Set query flags - query.slaveOk = true; - - // Kill cursor callback - var killCursorCallback = function(err, result) { - if(err) { - if(typeof callback != 'function') return; - return callback(err); - } - - // Result - var r = result.message; - // If we have a timed out query or a cursor that was killed - if((r.responseFlags & (1 << 0)) != 0) { - if(typeof callback != 'function') return; - return callback(new MongoError("cursor killed or timed out"), null); - } - - if(!Array.isArray(r.documents) || r.documents.length == 0) { - if(typeof callback != 'function') return; - return callback(new MongoError(f('invalid killCursors result returned for cursor id %s', cursorId))); - } - - // Return the result - if(typeof callback == 'function') { - callback(null, r.documents[0]); - } - } - - // Execute the kill cursor command - if(pool && pool.isConnected()) { - pool.write(query, { - command: true - }, killCursorCallback); - } -} - -WireProtocol.prototype.getMore = function(bson, ns, cursorState, batchSize, raw, connection, options, callback) { - options = options || {}; - // Build command namespace - var parts = ns.split(/\./); - // Command namespace - var commandns = f('%s.$cmd', parts.shift()); - - // Create getMore command - var getMoreCmd = { - getMore: cursorState.cursorId, - collection: parts.join('.'), - batchSize: Math.abs(batchSize) - } - - if(cursorState.cmd.tailable - && typeof cursorState.cmd.maxAwaitTimeMS == 'number') { - getMoreCmd.maxTimeMS = cursorState.cmd.maxAwaitTimeMS; - } - - // Build Query object - var query = new Query(bson, commandns, getMoreCmd, { - numberToSkip: 0, numberToReturn: -1 - , checkKeys: false, returnFieldSelector: null - }); - - // Set query flags - query.slaveOk = true; - - // Query callback - var queryCallback = function(err, result) { - if(err) return callback(err); - // Get the raw message - var r = result.message; - - // If we have a timed out query or a cursor that was killed - if((r.responseFlags & (1 << 0)) != 0) { - return callback(new MongoError("cursor killed or timed out"), null); - } - - // Raw, return all the extracted documents - if(raw) { - cursorState.documents = r.documents; - cursorState.cursorId = r.cursorId; - return callback(null, r.documents); - } - - // We have an error detected - if(r.documents[0].ok == 0) { - return callback(MongoError.create(r.documents[0])); - } - - // Ensure we have a Long valid cursor id - var cursorId = typeof r.documents[0].cursor.id == 'number' - ? Long.fromNumber(r.documents[0].cursor.id) - : r.documents[0].cursor.id; - - // Set all the values - cursorState.documents = r.documents[0].cursor.nextBatch; - cursorState.cursorId = cursorId; - - // Return the result - callback(null, r.documents[0], r.connection); - } - - // Query options - var queryOptions = { command: true }; - - // If we have a raw query decorate the function - if(raw) { - queryOptions.raw = raw; - } - - // Add the result field needed - queryOptions.documentsReturnedIn = 'nextBatch'; - - // Check if we need to promote longs - if(typeof cursorState.promoteLongs == 'boolean') { - queryOptions.promoteLongs = cursorState.promoteLongs; - } - - if(typeof cursorState.promoteValues == 'boolean') { - queryOptions.promoteValues = cursorState.promoteValues; - } - - if(typeof cursorState.promoteBuffers == 'boolean') { - queryOptions.promoteBuffers = cursorState.promoteBuffers; - } - - // Write out the getMore command - connection.write(query, queryOptions, queryCallback); -} - -WireProtocol.prototype.command = function(bson, ns, cmd, cursorState, topology, options) { - options = options || {} - // Check if this is a wire protocol command or not - var wireProtocolCommand = typeof options.wireProtocolCommand == 'boolean' ? options.wireProtocolCommand : true; - - // Establish type of command - if(cmd.find && wireProtocolCommand) { - // Create the find command - var query = executeFindCommand(bson, ns, cmd, cursorState, topology, options) - // Mark the cmd as virtual - cmd.virtual = false; - // Signal the documents are in the firstBatch value - query.documentsReturnedIn = 'firstBatch'; - // Return the query - return query; - } else if(cursorState.cursorId != null) { - return; - } else if(cmd) { - return setupCommand(bson, ns, cmd, cursorState, topology, options); - } else { - throw new MongoError(f("command %s does not return a cursor", JSON.stringify(cmd))); - } -} - -// // Command -// { -// find: ns -// , query: -// , limit: -// , fields: -// , skip: -// , hint: -// , explain: -// , snapshot: -// , batchSize: -// , returnKey: -// , maxScan: -// , min: -// , max: -// , showDiskLoc: -// , comment: -// , maxTimeMS: -// , raw: -// , readPreference: -// , tailable: -// , oplogReplay: -// , noCursorTimeout: -// , awaitdata: -// , exhaust: -// , partial: -// } - -// FIND/GETMORE SPEC -// { -// “find”: , -// “filter”: { ... }, -// “sort”: { ... }, -// “projection”: { ... }, -// “hint”: { ... }, -// “skip”: , -// “limit”: , -// “batchSize”: , -// “singleBatch”: , -// “comment”: , -// “maxScan”: , -// “maxTimeMS”: , -// “max”: { ... }, -// “min”: { ... }, -// “returnKey”: , -// “showRecordId”: , -// “snapshot”: , -// “tailable”: , -// “oplogReplay”: , -// “noCursorTimeout”: , -// “awaitData”: , -// “partial”: , -// “$readPreference”: { ... } -// } - -// -// Execute a find command -var executeFindCommand = function(bson, ns, cmd, cursorState, topology, options) { - // Ensure we have at least some options - options = options || {}; - // Get the readPreference - var readPreference = getReadPreference(cmd, options); - // Set the optional batchSize - cursorState.batchSize = cmd.batchSize || cursorState.batchSize; - - // Build command namespace - var parts = ns.split(/\./); - // Command namespace - var commandns = f('%s.$cmd', parts.shift()); - - // Build actual find command - var findCmd = { - find: parts.join('.') - }; - - // I we provided a filter - if(cmd.query) { - // Check if the user is passing in the $query parameter - if(cmd.query['$query']) { - findCmd.filter = cmd.query['$query']; - } else { - findCmd.filter = cmd.query; - } - } - - // Sort value - var sortValue = cmd.sort; - - // Handle issue of sort being an Array - if(Array.isArray(sortValue)) { - var sortObject = {}; - - if(sortValue.length > 0 && !Array.isArray(sortValue[0])) { - var sortDirection = sortValue[1]; - // Translate the sort order text - if(sortDirection == 'asc') { - sortDirection = 1; - } else if(sortDirection == 'desc') { - sortDirection = -1; - } - - // Set the sort order - sortObject[sortValue[0]] = sortDirection; - } else { - for(var i = 0; i < sortValue.length; i++) { - sortDirection = sortValue[i][1]; - // Translate the sort order text - if(sortDirection == 'asc') { - sortDirection = 1; - } else if(sortDirection == 'desc') { - sortDirection = -1; - } - - // Set the sort order - sortObject[sortValue[i][0]] = sortDirection; - } - } - - sortValue = sortObject; - } - - // Add sort to command - if(cmd.sort) findCmd.sort = sortValue; - // Add a projection to the command - if(cmd.fields) findCmd.projection = cmd.fields; - // Add a hint to the command - if(cmd.hint) findCmd.hint = cmd.hint; - // Add a skip - if(cmd.skip) findCmd.skip = cmd.skip; - // Add a limit - if(cmd.limit) findCmd.limit = cmd.limit; - - // Check if we wish to have a singleBatch - if(cmd.limit < 0) { - findCmd.limit = Math.abs(cmd.limit); - findCmd.singleBatch = true; - } - - // Add a batchSize - if(typeof cmd.batchSize == 'number') { - if (cmd.batchSize < 0) { - if (cmd.limit != 0 && Math.abs(cmd.batchSize) < Math.abs(cmd.limit)) { - findCmd.limit = Math.abs(cmd.batchSize); - } - - findCmd.singleBatch = true; - } - - findCmd.batchSize = Math.abs(cmd.batchSize); - } - - // If we have comment set - if(cmd.comment) findCmd.comment = cmd.comment; - - // If we have maxScan - if(cmd.maxScan) findCmd.maxScan = cmd.maxScan; - - // If we have maxTimeMS set - if(cmd.maxTimeMS) findCmd.maxTimeMS = cmd.maxTimeMS; - - // If we have min - if(cmd.min) findCmd.min = cmd.min; - - // If we have max - if(cmd.max) findCmd.max = cmd.max; - - // If we have returnKey set - if(cmd.returnKey) findCmd.returnKey = cmd.returnKey; - - // If we have showDiskLoc set - if(cmd.showDiskLoc) findCmd.showRecordId = cmd.showDiskLoc; - - // If we have snapshot set - if(cmd.snapshot) findCmd.snapshot = cmd.snapshot; - - // If we have tailable set - if(cmd.tailable) findCmd.tailable = cmd.tailable; - - // If we have oplogReplay set - if(cmd.oplogReplay) findCmd.oplogReplay = cmd.oplogReplay; - - // If we have noCursorTimeout set - if(cmd.noCursorTimeout) findCmd.noCursorTimeout = cmd.noCursorTimeout; - - // If we have awaitData set - if(cmd.awaitData) findCmd.awaitData = cmd.awaitData; - if(cmd.awaitdata) findCmd.awaitData = cmd.awaitdata; - - // If we have partial set - if(cmd.partial) findCmd.partial = cmd.partial; - - // If we have collation passed in - if(cmd.collation) findCmd.collation = cmd.collation; - - // If we have explain, we need to rewrite the find command - // to wrap it in the explain command - if(cmd.explain) { - findCmd = { - explain: findCmd - } - } - - // Did we provide a readConcern - if(cmd.readConcern) findCmd.readConcern = cmd.readConcern; - - // Set up the serialize and ignoreUndefined fields - var serializeFunctions = typeof options.serializeFunctions == 'boolean' - ? options.serializeFunctions : false; - var ignoreUndefined = typeof options.ignoreUndefined == 'boolean' - ? options.ignoreUndefined : false; - - // We have a Mongos topology, check if we need to add a readPreference - if(topology.type == 'mongos' - && readPreference - && readPreference.preference != 'primary') { - findCmd = { - '$query': findCmd, - '$readPreference': readPreference.toJSON() - }; - } - - // Build Query object - var query = new Query(bson, commandns, findCmd, { - numberToSkip: 0, numberToReturn: 1 - , checkKeys: false, returnFieldSelector: null - , serializeFunctions: serializeFunctions, ignoreUndefined: ignoreUndefined - }); - - // Set query flags - query.slaveOk = readPreference.slaveOk(); - - // Return the query - return query; -} - -// -// Set up a command cursor -var setupCommand = function(bson, ns, cmd, cursorState, topology, options) { - // Set empty options object - options = options || {} - // Get the readPreference - var readPreference = getReadPreference(cmd, options); - - // Final query - var finalCmd = {}; - for(var name in cmd) { - finalCmd[name] = cmd[name]; - } - - // Build command namespace - var parts = ns.split(/\./); - - // Serialize functions - var serializeFunctions = typeof options.serializeFunctions == 'boolean' - ? options.serializeFunctions : false; - - // Set up the serialize and ignoreUndefined fields - var ignoreUndefined = typeof options.ignoreUndefined == 'boolean' - ? options.ignoreUndefined : false; - - // We have a Mongos topology, check if we need to add a readPreference - if(topology.type == 'mongos' - && readPreference - && readPreference.preference != 'primary') { - finalCmd = { - '$query': finalCmd, - '$readPreference': readPreference.toJSON() - }; - } - - // Build Query object - var query = new Query(bson, f('%s.$cmd', parts.shift()), finalCmd, { - numberToSkip: 0, numberToReturn: -1 - , checkKeys: false, serializeFunctions: serializeFunctions - , ignoreUndefined: ignoreUndefined - }); - - // Set query flags - query.slaveOk = readPreference.slaveOk(); - - // Return the query - return query; -} - -module.exports = WireProtocol; diff --git a/ts-ticket-office-service/node_modules/mongodb-core/lib/wireprotocol/commands.js b/ts-ticket-office-service/node_modules/mongodb-core/lib/wireprotocol/commands.js deleted file mode 100644 index a2da1c6aa..000000000 --- a/ts-ticket-office-service/node_modules/mongodb-core/lib/wireprotocol/commands.js +++ /dev/null @@ -1,357 +0,0 @@ -"use strict"; - -var MongoError = require('../error'); - -// Wire command operation ids -var OP_UPDATE = 2001; -var OP_INSERT = 2002; -var OP_DELETE = 2006; - -var Insert = function(requestId, ismaster, bson, ns, documents, options) { - // Basic options needed to be passed in - if(ns == null) throw new MongoError("ns must be specified for query"); - if(!Array.isArray(documents) || documents.length == 0) throw new MongoError("documents array must contain at least one document to insert"); - - // Validate that we are not passing 0x00 in the collection name - if(!!~ns.indexOf("\x00")) { - throw new MongoError("namespace cannot contain a null character"); - } - - // Set internal - this.requestId = requestId; - this.bson = bson; - this.ns = ns; - this.documents = documents; - this.ismaster = ismaster; - - // Ensure empty options - options = options || {}; - - // Unpack options - this.serializeFunctions = typeof options.serializeFunctions == 'boolean' ? options.serializeFunctions : false; - this.ignoreUndefined = typeof options.ignoreUndefined == 'boolean' ? options.ignoreUndefined : false; - this.checkKeys = typeof options.checkKeys == 'boolean' ? options.checkKeys : true; - this.continueOnError = typeof options.continueOnError == 'boolean' ? options.continueOnError : false; - // Set flags - this.flags = this.continueOnError ? 1 : 0; -} - -// To Binary -Insert.prototype.toBin = function() { - // Contains all the buffers to be written - var buffers = []; - - // Header buffer - var header = new Buffer( - 4 * 4 // Header - + 4 // Flags - + Buffer.byteLength(this.ns) + 1 // namespace - ); - - // Add header to buffers - buffers.push(header); - - // Total length of the message - var totalLength = header.length; - - // Serialize all the documents - for(var i = 0; i < this.documents.length; i++) { - var buffer = this.bson.serialize(this.documents[i], { - checkKeys: this.checkKeys, - serializeFunctions: this.serializeFunctions, - ignoreUndefined: this.ignoreUndefined, - }); - - // Document is larger than maxBsonObjectSize, terminate serialization - if(buffer.length > this.ismaster.maxBsonObjectSize) { - throw new MongoError("Document exceeds maximum allowed bson size of " + this.ismaster.maxBsonObjectSize + " bytes"); - } - - // Add to total length of wire protocol message - totalLength = totalLength + buffer.length; - // Add to buffer - buffers.push(buffer); - } - - // Command is larger than maxMessageSizeBytes terminate serialization - if(totalLength > this.ismaster.maxMessageSizeBytes) { - throw new MongoError("Command exceeds maximum message size of " + this.ismaster.maxMessageSizeBytes + " bytes"); - } - - // Add all the metadata - var index = 0; - - // Write header length - header[index + 3] = (totalLength >> 24) & 0xff; - header[index + 2] = (totalLength >> 16) & 0xff; - header[index + 1] = (totalLength >> 8) & 0xff; - header[index] = (totalLength) & 0xff; - index = index + 4; - - // Write header requestId - header[index + 3] = (this.requestId >> 24) & 0xff; - header[index + 2] = (this.requestId >> 16) & 0xff; - header[index + 1] = (this.requestId >> 8) & 0xff; - header[index] = (this.requestId) & 0xff; - index = index + 4; - - // No flags - header[index + 3] = (0 >> 24) & 0xff; - header[index + 2] = (0 >> 16) & 0xff; - header[index + 1] = (0 >> 8) & 0xff; - header[index] = (0) & 0xff; - index = index + 4; - - // Operation - header[index + 3] = (OP_INSERT >> 24) & 0xff; - header[index + 2] = (OP_INSERT >> 16) & 0xff; - header[index + 1] = (OP_INSERT >> 8) & 0xff; - header[index] = (OP_INSERT) & 0xff; - index = index + 4; - - // Flags - header[index + 3] = (this.flags >> 24) & 0xff; - header[index + 2] = (this.flags >> 16) & 0xff; - header[index + 1] = (this.flags >> 8) & 0xff; - header[index] = (this.flags) & 0xff; - index = index + 4; - - // Write collection name - index = index + header.write(this.ns, index, 'utf8') + 1; - header[index - 1] = 0; - - // Return the buffers - return buffers; -} - -var Update = function(requestId, ismaster, bson, ns, update, options) { - // Basic options needed to be passed in - if(ns == null) throw new MongoError("ns must be specified for query"); - - // Ensure empty options - options = options || {}; - - // Set internal - this.requestId = requestId; - this.bson = bson; - this.ns = ns; - this.ismaster = ismaster; - - // Unpack options - this.serializeFunctions = typeof options.serializeFunctions == 'boolean' ? options.serializeFunctions : false; - this.ignoreUndefined = typeof options.ignoreUndefined == 'boolean' ? options.ignoreUndefined : false; - this.checkKeys = typeof options.checkKeys == 'boolean' ? options.checkKeys : false; - - // Unpack the update document - this.upsert = typeof update[0].upsert == 'boolean' ? update[0].upsert : false; - this.multi = typeof update[0].multi == 'boolean' ? update[0].multi : false; - this.q = update[0].q; - this.u = update[0].u; - - // Create flag value - this.flags = this.upsert ? 1 : 0; - this.flags = this.multi ? this.flags | 2 : this.flags; -} - -// To Binary -Update.prototype.toBin = function() { - // Contains all the buffers to be written - var buffers = []; - - // Header buffer - var header = new Buffer( - 4 * 4 // Header - + 4 // ZERO - + Buffer.byteLength(this.ns) + 1 // namespace - + 4 // Flags - ); - - // Add header to buffers - buffers.push(header); - - // Total length of the message - var totalLength = header.length; - - // Serialize the selector - var selector = this.bson.serialize(this.q, { - checkKeys: this.checkKeys, - serializeFunctions: this.serializeFunctions, - ignoreUndefined: this.ignoreUndefined, - }); - buffers.push(selector); - totalLength = totalLength + selector.length; - - // Serialize the update - var update = this.bson.serialize(this.u, { - checkKeys: this.checkKeys, - serializeFunctions: this.serializeFunctions, - ignoreUndefined: this.ignoreUndefined, - }); - buffers.push(update); - totalLength = totalLength + update.length; - - // Index in header buffer - var index = 0; - - // Write header length - header[index + 3] = (totalLength >> 24) & 0xff; - header[index + 2] = (totalLength >> 16) & 0xff; - header[index + 1] = (totalLength >> 8) & 0xff; - header[index] = (totalLength) & 0xff; - index = index + 4; - - // Write header requestId - header[index + 3] = (this.requestId >> 24) & 0xff; - header[index + 2] = (this.requestId >> 16) & 0xff; - header[index + 1] = (this.requestId >> 8) & 0xff; - header[index] = (this.requestId) & 0xff; - index = index + 4; - - // No flags - header[index + 3] = (0 >> 24) & 0xff; - header[index + 2] = (0 >> 16) & 0xff; - header[index + 1] = (0 >> 8) & 0xff; - header[index] = (0) & 0xff; - index = index + 4; - - // Operation - header[index + 3] = (OP_UPDATE >> 24) & 0xff; - header[index + 2] = (OP_UPDATE >> 16) & 0xff; - header[index + 1] = (OP_UPDATE >> 8) & 0xff; - header[index] = (OP_UPDATE) & 0xff; - index = index + 4; - - // Write ZERO - header[index + 3] = (0 >> 24) & 0xff; - header[index + 2] = (0 >> 16) & 0xff; - header[index + 1] = (0 >> 8) & 0xff; - header[index] = (0) & 0xff; - index = index + 4; - - // Write collection name - index = index + header.write(this.ns, index, 'utf8') + 1; - header[index - 1] = 0; - - // Flags - header[index + 3] = (this.flags >> 24) & 0xff; - header[index + 2] = (this.flags >> 16) & 0xff; - header[index + 1] = (this.flags >> 8) & 0xff; - header[index] = (this.flags) & 0xff; - index = index + 4; - - // Return the buffers - return buffers; -} - -var Remove = function(requestId, ismaster, bson, ns, remove, options) { - // Basic options needed to be passed in - if(ns == null) throw new MongoError("ns must be specified for query"); - - // Ensure empty options - options = options || {}; - - // Set internal - this.requestId = requestId; - this.bson = bson; - this.ns = ns; - this.ismaster = ismaster; - - // Unpack options - this.serializeFunctions = typeof options.serializeFunctions == 'boolean' ? options.serializeFunctions : false; - this.ignoreUndefined = typeof options.ignoreUndefined == 'boolean' ? options.ignoreUndefined : false; - this.checkKeys = typeof options.checkKeys == 'boolean' ? options.checkKeys : false; - - // Unpack the update document - this.limit = typeof remove[0].limit == 'number' ? remove[0].limit : 1; - this.q = remove[0].q; - - // Create flag value - this.flags = this.limit == 1 ? 1 : 0; -} - -// To Binary -Remove.prototype.toBin = function() { - // Contains all the buffers to be written - var buffers = []; - - // Header buffer - var header = new Buffer( - 4 * 4 // Header - + 4 // ZERO - + Buffer.byteLength(this.ns) + 1 // namespace - + 4 // Flags - ); - - // Add header to buffers - buffers.push(header); - - // Total length of the message - var totalLength = header.length; - - // Serialize the selector - var selector = this.bson.serialize(this.q, { - checkKeys: this.checkKeys, - serializeFunctions: this.serializeFunctions, - ignoreUndefined: this.ignoreUndefined, - }); - buffers.push(selector); - totalLength = totalLength + selector.length; - - // Index in header buffer - var index = 0; - - // Write header length - header[index + 3] = (totalLength >> 24) & 0xff; - header[index + 2] = (totalLength >> 16) & 0xff; - header[index + 1] = (totalLength >> 8) & 0xff; - header[index] = (totalLength) & 0xff; - index = index + 4; - - // Write header requestId - header[index + 3] = (this.requestId >> 24) & 0xff; - header[index + 2] = (this.requestId >> 16) & 0xff; - header[index + 1] = (this.requestId >> 8) & 0xff; - header[index] = (this.requestId) & 0xff; - index = index + 4; - - // No flags - header[index + 3] = (0 >> 24) & 0xff; - header[index + 2] = (0 >> 16) & 0xff; - header[index + 1] = (0 >> 8) & 0xff; - header[index] = (0) & 0xff; - index = index + 4; - - // Operation - header[index + 3] = (OP_DELETE >> 24) & 0xff; - header[index + 2] = (OP_DELETE >> 16) & 0xff; - header[index + 1] = (OP_DELETE >> 8) & 0xff; - header[index] = (OP_DELETE) & 0xff; - index = index + 4; - - // Write ZERO - header[index + 3] = (0 >> 24) & 0xff; - header[index + 2] = (0 >> 16) & 0xff; - header[index + 1] = (0 >> 8) & 0xff; - header[index] = (0) & 0xff; - index = index + 4; - - // Write collection name - index = index + header.write(this.ns, index, 'utf8') + 1; - header[index - 1] = 0; - - // Write ZERO - header[index + 3] = (this.flags >> 24) & 0xff; - header[index + 2] = (this.flags >> 16) & 0xff; - header[index + 1] = (this.flags >> 8) & 0xff; - header[index] = (this.flags) & 0xff; - index = index + 4; - - // Return the buffers - return buffers; -} - -module.exports = { - Insert: Insert - , Update: Update - , Remove: Remove -} diff --git a/ts-ticket-office-service/node_modules/mongodb-core/lib/wireprotocol/shared.js b/ts-ticket-office-service/node_modules/mongodb-core/lib/wireprotocol/shared.js deleted file mode 100644 index 25bd3946d..000000000 --- a/ts-ticket-office-service/node_modules/mongodb-core/lib/wireprotocol/shared.js +++ /dev/null @@ -1,27 +0,0 @@ -"use strict" - -var ReadPreference = require('../topologies/read_preference'), - MongoError = require('../error'); - -var getReadPreference = function(cmd, options) { - // Default to command version of the readPreference - var readPreference = cmd.readPreference || new ReadPreference('primary'); - // If we have an option readPreference override the command one - if(options.readPreference) { - readPreference = options.readPreference; - } - - if(typeof readPreference == 'string') { - readPreference = new ReadPreference(readPreference); - } - - if(!(readPreference instanceof ReadPreference)) { - throw new MongoError('readPreference must be a ReadPreference instance'); - } - - return readPreference; -} - -module.exports = { - getReadPreference: getReadPreference -} diff --git a/ts-ticket-office-service/node_modules/mongodb-core/package.json b/ts-ticket-office-service/node_modules/mongodb-core/package.json deleted file mode 100644 index 0b2f85d08..000000000 --- a/ts-ticket-office-service/node_modules/mongodb-core/package.json +++ /dev/null @@ -1,114 +0,0 @@ -{ - "_args": [ - [ - { - "raw": "mongodb-core@2.1.17", - "scope": null, - "escapedName": "mongodb-core", - "name": "mongodb-core", - "rawSpec": "2.1.17", - "spec": "2.1.17", - "type": "version" - }, - "F:\\gitwork\\workspace_microservices\\ts-ticket-office-service\\node_modules\\mongodb" - ] - ], - "_from": "mongodb-core@2.1.17", - "_id": "mongodb-core@2.1.17", - "_inCache": true, - "_location": "/mongodb-core", - "_nodeVersion": "6.9.5", - "_npmOperationalInternal": { - "host": "s3://npm-registry-packages", - "tmp": "tmp/mongodb-core-2.1.17.tgz_1507835788962_0.5027369784656912" - }, - "_npmUser": { - "name": "mbroadst", - "email": "mbroadst@gmail.com" - }, - "_npmVersion": "3.10.10", - "_phantomChildren": {}, - "_requested": { - "raw": "mongodb-core@2.1.17", - "scope": null, - "escapedName": "mongodb-core", - "name": "mongodb-core", - "rawSpec": "2.1.17", - "spec": "2.1.17", - "type": "version" - }, - "_requiredBy": [ - "/mongodb" - ], - "_resolved": "https://registry.npmjs.org/mongodb-core/-/mongodb-core-2.1.17.tgz", - "_shasum": "a418b337a14a14990fb510b923dee6a813173df8", - "_shrinkwrap": null, - "_spec": "mongodb-core@2.1.17", - "_where": "F:\\gitwork\\workspace_microservices\\ts-ticket-office-service\\node_modules\\mongodb", - "author": { - "name": "Christian Kvalheim" - }, - "bugs": { - "url": "https://github.com/christkv/mongodb-core/issues" - }, - "dependencies": { - "bson": "~1.0.4", - "require_optional": "~1.0.0" - }, - "description": "Core MongoDB driver functionality, no bells and whistles and meant for integration not end applications", - "devDependencies": { - "co": "^4.5.4", - "coveralls": "^2.11.6", - "es6-promise": "^3.0.2", - "gleak": "0.5.0", - "integra": "0.1.8", - "jsdoc": "3.3.0-alpha8", - "mkdirp": "0.5.0", - "mongodb-topology-manager": "1.0.x", - "mongodb-version-manager": "github:christkv/mongodb-version-manager#master", - "nyc": "^5.5.0", - "optimist": "latest", - "rimraf": "2.2.6", - "semver": "4.1.0" - }, - "directories": {}, - "dist": { - "shasum": "a418b337a14a14990fb510b923dee6a813173df8", - "tarball": "https://registry.npmjs.org/mongodb-core/-/mongodb-core-2.1.17.tgz" - }, - "gitHead": "e981c3215ac4e273aa383beee7a1686e60a92be1", - "homepage": "https://github.com/christkv/mongodb-core", - "keywords": [ - "mongodb", - "core" - ], - "license": "Apache-2.0", - "main": "index.js", - "maintainers": [ - { - "name": "mbroadst", - "email": "mbroadst@gmail.com" - }, - { - "name": "christkv", - "email": "christkv@gmail.com" - } - ], - "name": "mongodb-core", - "optionalDependencies": {}, - "peerOptionalDependencies": { - "kerberos": "~0.0", - "bson-ext": "1.0.5" - }, - "readme": "ERROR: No README data found!", - "repository": { - "type": "git", - "url": "git://github.com/christkv/mongodb-core.git" - }, - "scripts": { - "coverage": "nyc node test/runner.js -t functional -l && node_modules/.bin/nyc report --reporter=text-lcov | node_modules/.bin/coveralls", - "lint": "eslint lib", - "test": "node test/runner.js -t functional" - }, - "version": "2.1.17" -} diff --git a/ts-ticket-office-service/node_modules/mongodb-core/test.js b/ts-ticket-office-service/node_modules/mongodb-core/test.js deleted file mode 100644 index 886428433..000000000 --- a/ts-ticket-office-service/node_modules/mongodb-core/test.js +++ /dev/null @@ -1,71 +0,0 @@ -var ReplSet = require('./lib2/topologies/replset'), - ReadPreference = require('./lib2/topologies/read_preference'); - -// Attempt to connect -var server = new ReplSet([{ - host: 'localhost', port: 31000 -}, { - host: 'localhost', port: 31001 -}], { - setName: 'rs' -}); - -function executeCursors(_server, cb) { - var count = 100; - - for(var i = 0; i < 100; i++) { - // Execute the write - var cursor = _server.cursor('test.test', { - find: 'test.test' - , query: {a:1} - }, {readPreference: new ReadPreference('secondary')}); - - // Get the first document - cursor.next(function(err, doc) { - count = count - 1; - if(err) console.dir(err) - if(count == 0) return cb(); - }); - } -} - -server.on('connect', function(_server) { - console.log("---------------------------------- 0") - // Attempt authentication - _server.auth('scram-sha-1', 'admin', 'root', 'root', function(err, r) { - console.log("---------------------------------- 1") - // console.dir(err) - // console.dir(r) - - _server.insert('test.test', [{a:1}], function(err, r) { - console.log("---------------------------------- 2") - console.dir(err) - if(r)console.dir(r.result) - var name = null; - - _server.on('joined', function(_t, _server) { - if(name == _server.name) { - console.log("=========== joined :: " + _t + " :: " + _server.name) - executeCursors(_server, function() { - }); - } - }) - - // var s = _server.s.replicaSetState.secondaries[0]; - // s.destroy({emitClose:true}); - executeCursors(_server, function() { - console.log("============== 0") - // Attempt to force a server reconnect - var s = _server.s.replicaSetState.secondaries[0]; - name = s.name; - s.destroy({emitClose:true}); - // console.log("============== 1") - - // _server.destroy(); - // test.done(); - }); - }); - }); -}); - -server.connect(); diff --git a/ts-ticket-office-service/node_modules/mongodb-core/test1.js b/ts-ticket-office-service/node_modules/mongodb-core/test1.js deleted file mode 100644 index 6e05ebd55..000000000 --- a/ts-ticket-office-service/node_modules/mongodb-core/test1.js +++ /dev/null @@ -1,72 +0,0 @@ -var Server = require('./lib/topologies/server'); - -// Attempt to connect -var server = new Server({ - host: 'localhost', port: 27017, socketTimeout: 500 -}); - -// function executeCursors(_server, cb) { -// var count = 100; -// -// for(var i = 0; i < 100; i++) { -// // Execute the write -// var cursor = _server.cursor('test.test', { -// find: 'test.test' -// , query: {a:1} -// }, {readPreference: new ReadPreference('secondary')}); -// -// // Get the first document -// cursor.next(function(err, doc) { -// count = count - 1; -// if(err) console.dir(err) -// if(count == 0) return cb(); -// }); -// } -// } - -server.on('connect', function(_server) { - - setInterval(function() { - _server.insert('test.test', [{a:1}], function(err, r) { - console.log("insert") - }); - }, 1000) - // console.log("---------------------------------- 0") - // // Attempt authentication - // _server.auth('scram-sha-1', 'admin', 'root', 'root', function(err, r) { - // console.log("---------------------------------- 1") - // // console.dir(err) - // // console.dir(r) - // - // _server.insert('test.test', [{a:1}], function(err, r) { - // console.log("---------------------------------- 2") - // console.dir(err) - // if(r)console.dir(r.result) - // var name = null; - // - // _server.on('joined', function(_t, _server) { - // if(name == _server.name) { - // console.log("=========== joined :: " + _t + " :: " + _server.name) - // executeCursors(_server, function() { - // }); - // } - // }) - // - // // var s = _server.s.replicaSetState.secondaries[0]; - // // s.destroy({emitClose:true}); - // executeCursors(_server, function() { - // console.log("============== 0") - // // Attempt to force a server reconnect - // var s = _server.s.replicaSetState.secondaries[0]; - // name = s.name; - // s.destroy({emitClose:true}); - // // console.log("============== 1") - // - // // _server.destroy(); - // // test.done(); - // }); - // }); - // }); -}); - -server.connect(); diff --git a/ts-ticket-office-service/node_modules/mongodb-core/yarn.lock b/ts-ticket-office-service/node_modules/mongodb-core/yarn.lock deleted file mode 100644 index f4e45805c..000000000 --- a/ts-ticket-office-service/node_modules/mongodb-core/yarn.lock +++ /dev/null @@ -1,2588 +0,0 @@ -# THIS IS AN AUTOGENERATED FILE. DO NOT EDIT THIS FILE DIRECTLY. -# yarn lockfile v1 - - -abbrev@1: - version "1.1.1" - resolved "https://registry.yarnpkg.com/abbrev/-/abbrev-1.1.1.tgz#f8f2c887ad10bf67f634f005b6987fed3179aac8" - -abbrev@1.0.x: - version "1.0.9" - resolved "https://registry.yarnpkg.com/abbrev/-/abbrev-1.0.9.tgz#91b4792588a7738c25f35dd6f63752a2f8776135" - -ajv@^5.1.0: - version "5.2.3" - resolved "https://registry.yarnpkg.com/ajv/-/ajv-5.2.3.tgz#c06f598778c44c6b161abafe3466b81ad1814ed2" - dependencies: - co "^4.6.0" - fast-deep-equal "^1.0.0" - json-schema-traverse "^0.3.0" - json-stable-stringify "^1.0.1" - -align-text@^0.1.1, align-text@^0.1.3: - version "0.1.4" - resolved "https://registry.yarnpkg.com/align-text/-/align-text-0.1.4.tgz#0cd90a561093f35d0a99256c22b7069433fad117" - dependencies: - kind-of "^3.0.2" - longest "^1.0.1" - repeat-string "^1.5.2" - -amdefine@>=0.0.4: - version "1.0.1" - resolved "https://registry.yarnpkg.com/amdefine/-/amdefine-1.0.1.tgz#4a5282ac164729e93619bcfd3ad151f817ce91f5" - -ampersand-events@^2.0.1: - version "2.0.2" - resolved "https://registry.yarnpkg.com/ampersand-events/-/ampersand-events-2.0.2.tgz#f402bc2e18305fabd995dbdcd3b7057bbdd7d347" - dependencies: - ampersand-version "^1.0.2" - lodash "^4.6.1" - -ampersand-state@^5.0.1: - version "5.0.2" - resolved "https://registry.yarnpkg.com/ampersand-state/-/ampersand-state-5.0.2.tgz#16830def866c644ecd21da8c8ba8717aa2b8d23c" - dependencies: - ampersand-events "^2.0.1" - ampersand-version "^1.0.0" - array-next "~0.0.1" - key-tree-store "^1.3.0" - lodash "^4.11.1" - -ampersand-version@^1.0.0, ampersand-version@^1.0.2: - version "1.0.2" - resolved "https://registry.yarnpkg.com/ampersand-version/-/ampersand-version-1.0.2.tgz#ff8f3d4ceac4d32ccd83f6bd6697397f7b59e2c0" - dependencies: - find-root "^0.1.1" - through2 "^0.6.3" - -ansi-regex@^2.0.0: - version "2.1.1" - resolved "https://registry.yarnpkg.com/ansi-regex/-/ansi-regex-2.1.1.tgz#c3b33ab5ee360d86e0e628f0468ae7ef27d654df" - -ansi-styles@^2.2.1: - version "2.2.1" - resolved "https://registry.yarnpkg.com/ansi-styles/-/ansi-styles-2.2.1.tgz#b432dd3358b634cf75e1e4664368240533c1ddbe" - -ansi@^0.3.0, ansi@~0.3.0: - version "0.3.1" - resolved "https://registry.yarnpkg.com/ansi/-/ansi-0.3.1.tgz#0c42d4fb17160d5a9af1e484bace1c66922c1b21" - -append-transform@^0.2.0: - version "0.2.2" - resolved "https://registry.yarnpkg.com/append-transform/-/append-transform-0.2.2.tgz#c41f3763e910cfe79646092667e6471809938c85" - -are-we-there-yet@~1.0.0: - version "1.0.6" - resolved "https://registry.yarnpkg.com/are-we-there-yet/-/are-we-there-yet-1.0.6.tgz#a2d28c93102aa6cc96245a26cb954de06ec53f0c" - dependencies: - delegates "^1.0.0" - readable-stream "^2.0.0 || ^1.1.13" - -argparse@^1.0.7: - version "1.0.9" - resolved "https://registry.yarnpkg.com/argparse/-/argparse-1.0.9.tgz#73d83bc263f86e97f8cc4f6bae1b0e90a7d22c86" - dependencies: - sprintf-js "~1.0.2" - -arr-diff@^1.0.1: - version "1.1.0" - resolved "https://registry.yarnpkg.com/arr-diff/-/arr-diff-1.1.0.tgz#687c32758163588fef7de7b36fabe495eb1a399a" - dependencies: - arr-flatten "^1.0.1" - array-slice "^0.2.3" - -arr-flatten@^1.0.1: - version "1.1.0" - resolved "https://registry.yarnpkg.com/arr-flatten/-/arr-flatten-1.1.0.tgz#36048bbff4e7b47e136644316c99669ea5ae91f1" - -array-find-index@^1.0.1: - version "1.0.2" - resolved "https://registry.yarnpkg.com/array-find-index/-/array-find-index-1.0.2.tgz#df010aa1287e164bbda6f9723b0a96a1ec4187a1" - -array-next@~0.0.1: - version "0.0.1" - resolved "https://registry.yarnpkg.com/array-next/-/array-next-0.0.1.tgz#e5e4660a4c27fda8151ff7764275d00900062be1" - -array-slice@^0.2.3: - version "0.2.3" - resolved "https://registry.yarnpkg.com/array-slice/-/array-slice-0.2.3.tgz#dd3cfb80ed7973a75117cdac69b0b99ec86186f5" - -arrify@^1.0.1: - version "1.0.1" - resolved "https://registry.yarnpkg.com/arrify/-/arrify-1.0.1.tgz#898508da2226f380df904728456849c1501a4b0d" - -asn1@~0.2.3: - version "0.2.3" - resolved "https://registry.yarnpkg.com/asn1/-/asn1-0.2.3.tgz#dac8787713c9966849fc8180777ebe9c1ddf3b86" - -assert-plus@1.0.0, assert-plus@^1.0.0: - version "1.0.0" - resolved "https://registry.yarnpkg.com/assert-plus/-/assert-plus-1.0.0.tgz#f12e0f3c5d77b0b1cdd9146942e4e96c1e4dd525" - -assert-plus@^0.2.0: - version "0.2.0" - resolved "https://registry.yarnpkg.com/assert-plus/-/assert-plus-0.2.0.tgz#d74e1b87e7affc0db8aadb7021f3fe48101ab234" - -async@1.x, async@^1.4.0, async@^1.5.0, async@~1.5.0: - version "1.5.2" - resolved "https://registry.yarnpkg.com/async/-/async-1.5.2.tgz#ec6a61ae56480c0c3cb241c95618e20892f9672a" - -async@~0.1.22: - version "0.1.22" - resolved "https://registry.yarnpkg.com/async/-/async-0.1.22.tgz#0fc1aaa088a0e3ef0ebe2d8831bab0dcf8845061" - -async@~0.2.6: - version "0.2.10" - resolved "https://registry.yarnpkg.com/async/-/async-0.2.10.tgz#b6bbe0b0674b9d719708ca38de8c237cb526c3d1" - -asynckit@^0.4.0: - version "0.4.0" - resolved "https://registry.yarnpkg.com/asynckit/-/asynckit-0.4.0.tgz#c79ed97f7f34cb8f2ba1bc9790bcc366474b4b79" - -aws-sign2@~0.6.0: - version "0.6.0" - resolved "https://registry.yarnpkg.com/aws-sign2/-/aws-sign2-0.6.0.tgz#14342dd38dbcc94d0e5b87d763cd63612c0e794f" - -aws-sign2@~0.7.0: - version "0.7.0" - resolved "https://registry.yarnpkg.com/aws-sign2/-/aws-sign2-0.7.0.tgz#b46e890934a9591f2d2f6f86d7e6a9f1b3fe76a8" - -aws4@^1.2.1, aws4@^1.6.0: - version "1.6.0" - resolved "https://registry.yarnpkg.com/aws4/-/aws4-1.6.0.tgz#83ef5ca860b2b32e4a0deedee8c771b9db57471e" - -babel-code-frame@^6.26.0: - version "6.26.0" - resolved "https://registry.yarnpkg.com/babel-code-frame/-/babel-code-frame-6.26.0.tgz#63fd43f7dc1e3bb7ce35947db8fe369a3f58c74b" - dependencies: - chalk "^1.1.3" - esutils "^2.0.2" - js-tokens "^3.0.2" - -babel-core@^6.25.0, babel-core@^6.26.0: - version "6.26.0" - resolved "https://registry.yarnpkg.com/babel-core/-/babel-core-6.26.0.tgz#af32f78b31a6fcef119c87b0fd8d9753f03a0bb8" - dependencies: - babel-code-frame "^6.26.0" - babel-generator "^6.26.0" - babel-helpers "^6.24.1" - babel-messages "^6.23.0" - babel-register "^6.26.0" - babel-runtime "^6.26.0" - babel-template "^6.26.0" - babel-traverse "^6.26.0" - babel-types "^6.26.0" - babylon "^6.18.0" - convert-source-map "^1.5.0" - debug "^2.6.8" - json5 "^0.5.1" - lodash "^4.17.4" - minimatch "^3.0.4" - path-is-absolute "^1.0.1" - private "^0.1.7" - slash "^1.0.0" - source-map "^0.5.6" - -babel-generator@^6.26.0: - version "6.26.0" - resolved "https://registry.yarnpkg.com/babel-generator/-/babel-generator-6.26.0.tgz#ac1ae20070b79f6e3ca1d3269613053774f20dc5" - dependencies: - babel-messages "^6.23.0" - babel-runtime "^6.26.0" - babel-types "^6.26.0" - detect-indent "^4.0.0" - jsesc "^1.3.0" - lodash "^4.17.4" - source-map "^0.5.6" - trim-right "^1.0.1" - -babel-helpers@^6.24.1: - version "6.24.1" - resolved "https://registry.yarnpkg.com/babel-helpers/-/babel-helpers-6.24.1.tgz#3471de9caec388e5c850e597e58a26ddf37602b2" - dependencies: - babel-runtime "^6.22.0" - babel-template "^6.24.1" - -babel-messages@^6.23.0: - version "6.23.0" - resolved "https://registry.yarnpkg.com/babel-messages/-/babel-messages-6.23.0.tgz#f3cdf4703858035b2a2951c6ec5edf6c62f2630e" - dependencies: - babel-runtime "^6.22.0" - -babel-polyfill@^6.23.0: - version "6.26.0" - resolved "https://registry.yarnpkg.com/babel-polyfill/-/babel-polyfill-6.26.0.tgz#379937abc67d7895970adc621f284cd966cf2153" - dependencies: - babel-runtime "^6.26.0" - core-js "^2.5.0" - regenerator-runtime "^0.10.5" - -babel-register@^6.26.0: - version "6.26.0" - resolved "https://registry.yarnpkg.com/babel-register/-/babel-register-6.26.0.tgz#6ed021173e2fcb486d7acb45c6009a856f647071" - dependencies: - babel-core "^6.26.0" - babel-runtime "^6.26.0" - core-js "^2.5.0" - home-or-tmp "^2.0.0" - lodash "^4.17.4" - mkdirp "^0.5.1" - source-map-support "^0.4.15" - -babel-runtime@^6.22.0, babel-runtime@^6.26.0: - version "6.26.0" - resolved "https://registry.yarnpkg.com/babel-runtime/-/babel-runtime-6.26.0.tgz#965c7058668e82b55d7bfe04ff2337bc8b5647fe" - dependencies: - core-js "^2.4.0" - regenerator-runtime "^0.11.0" - -babel-template@^6.24.1, babel-template@^6.26.0: - version "6.26.0" - resolved "https://registry.yarnpkg.com/babel-template/-/babel-template-6.26.0.tgz#de03e2d16396b069f46dd9fff8521fb1a0e35e02" - dependencies: - babel-runtime "^6.26.0" - babel-traverse "^6.26.0" - babel-types "^6.26.0" - babylon "^6.18.0" - lodash "^4.17.4" - -babel-traverse@^6.26.0: - version "6.26.0" - resolved "https://registry.yarnpkg.com/babel-traverse/-/babel-traverse-6.26.0.tgz#46a9cbd7edcc62c8e5c064e2d2d8d0f4035766ee" - dependencies: - babel-code-frame "^6.26.0" - babel-messages "^6.23.0" - babel-runtime "^6.26.0" - babel-types "^6.26.0" - babylon "^6.18.0" - debug "^2.6.8" - globals "^9.18.0" - invariant "^2.2.2" - lodash "^4.17.4" - -babel-types@^6.26.0: - version "6.26.0" - resolved "https://registry.yarnpkg.com/babel-types/-/babel-types-6.26.0.tgz#a3b073f94ab49eb6fa55cd65227a334380632497" - dependencies: - babel-runtime "^6.26.0" - esutils "^2.0.2" - lodash "^4.17.4" - to-fast-properties "^1.0.3" - -babylon@^6.18.0: - version "6.18.0" - resolved "https://registry.yarnpkg.com/babylon/-/babylon-6.18.0.tgz#af2f3b88fa6f5c1e4c634d1a0f8eac4f55b395e3" - -balanced-match@^1.0.0: - version "1.0.0" - resolved "https://registry.yarnpkg.com/balanced-match/-/balanced-match-1.0.0.tgz#89b4d199ab2bee49de164ea02b89ce462d71b767" - -bcrypt-pbkdf@^1.0.0: - version "1.0.1" - resolved "https://registry.yarnpkg.com/bcrypt-pbkdf/-/bcrypt-pbkdf-1.0.1.tgz#63bc5dcb61331b92bc05fd528953c33462a06f8d" - dependencies: - tweetnacl "^0.14.3" - -"binary@>= 0.3.0 < 1": - version "0.3.0" - resolved "https://registry.yarnpkg.com/binary/-/binary-0.3.0.tgz#9f60553bc5ce8c3386f3b553cff47462adecaa79" - dependencies: - buffers "~0.1.1" - chainsaw "~0.1.0" - -block-stream@*: - version "0.0.9" - resolved "https://registry.yarnpkg.com/block-stream/-/block-stream-0.0.9.tgz#13ebfe778a03205cfe03751481ebb4b3300c126a" - dependencies: - inherits "~2.0.0" - -bluebird@^3.5.0: - version "3.5.1" - resolved "https://registry.yarnpkg.com/bluebird/-/bluebird-3.5.1.tgz#d9551f9de98f1fcda1e683d17ee91a0602ee2eb9" - -boolbase@~1.0.0: - version "1.0.0" - resolved "https://registry.yarnpkg.com/boolbase/-/boolbase-1.0.0.tgz#68dff5fbe60c51eb37725ea9e3ed310dcc1e776e" - -boom@2.x.x: - version "2.10.1" - resolved "https://registry.yarnpkg.com/boom/-/boom-2.10.1.tgz#39c8918ceff5799f83f9492a848f625add0c766f" - dependencies: - hoek "2.x.x" - -boom@4.x.x: - version "4.3.1" - resolved "https://registry.yarnpkg.com/boom/-/boom-4.3.1.tgz#4f8a3005cb4a7e3889f749030fd25b96e01d2e31" - dependencies: - hoek "4.x.x" - -boom@5.x.x: - version "5.2.0" - resolved "https://registry.yarnpkg.com/boom/-/boom-5.2.0.tgz#5dd9da6ee3a5f302077436290cb717d3f4a54e02" - dependencies: - hoek "4.x.x" - -brace-expansion@^1.1.7: - version "1.1.8" - resolved "https://registry.yarnpkg.com/brace-expansion/-/brace-expansion-1.1.8.tgz#c07b211c7c952ec1f8efd51a77ef0d1d3990a292" - dependencies: - balanced-match "^1.0.0" - concat-map "0.0.1" - -braces@^1.8.0: - version "1.8.5" - resolved "https://registry.yarnpkg.com/braces/-/braces-1.8.5.tgz#ba77962e12dff969d6b76711e914b737857bf6a7" - dependencies: - expand-range "^1.8.1" - preserve "^0.2.0" - repeat-element "^1.1.2" - -bson@~1.0.4: - version "1.0.4" - resolved "https://registry.yarnpkg.com/bson/-/bson-1.0.4.tgz#93c10d39eaa5b58415cbc4052f3e53e562b0b72c" - -buffer-shims@~1.0.0: - version "1.0.0" - resolved "https://registry.yarnpkg.com/buffer-shims/-/buffer-shims-1.0.0.tgz#9978ce317388c649ad8793028c3477ef044a8b51" - -buffers@~0.1.1: - version "0.1.1" - resolved "https://registry.yarnpkg.com/buffers/-/buffers-0.1.1.tgz#b24579c3bed4d6d396aeee6d9a8ae7f5482ab7bb" - -builtin-modules@^1.0.0: - version "1.1.1" - resolved "https://registry.yarnpkg.com/builtin-modules/-/builtin-modules-1.1.1.tgz#270f076c5a72c02f5b65a47df94c5fe3a278892f" - -caching-transform@^1.0.0: - version "1.0.1" - resolved "https://registry.yarnpkg.com/caching-transform/-/caching-transform-1.0.1.tgz#6dbdb2f20f8d8fbce79f3e94e9d1742dcdf5c0a1" - dependencies: - md5-hex "^1.2.0" - mkdirp "^0.5.1" - write-file-atomic "^1.1.4" - -camelcase-keys@^2.0.0: - version "2.1.0" - resolved "https://registry.yarnpkg.com/camelcase-keys/-/camelcase-keys-2.1.0.tgz#308beeaffdf28119051efa1d932213c91b8f92e7" - dependencies: - camelcase "^2.0.0" - map-obj "^1.0.0" - -camelcase@^1.0.2: - version "1.2.1" - resolved "https://registry.yarnpkg.com/camelcase/-/camelcase-1.2.1.tgz#9bb5304d2e0b56698b2c758b08a3eaa9daa58a39" - -camelcase@^2.0.0, camelcase@^2.0.1: - version "2.1.1" - resolved "https://registry.yarnpkg.com/camelcase/-/camelcase-2.1.1.tgz#7c1d16d679a1bbe59ca02cacecfb011e201f5a1f" - -caseless@~0.11.0: - version "0.11.0" - resolved "https://registry.yarnpkg.com/caseless/-/caseless-0.11.0.tgz#715b96ea9841593cc33067923f5ec60ebda4f7d7" - -caseless@~0.12.0: - version "0.12.0" - resolved "https://registry.yarnpkg.com/caseless/-/caseless-0.12.0.tgz#1b681c21ff84033c826543090689420d187151dc" - -catharsis@~0.8.2: - version "0.8.9" - resolved "https://registry.yarnpkg.com/catharsis/-/catharsis-0.8.9.tgz#98cc890ca652dd2ef0e70b37925310ff9e90fc8b" - dependencies: - underscore-contrib "~0.3.0" - -center-align@^0.1.1: - version "0.1.3" - resolved "https://registry.yarnpkg.com/center-align/-/center-align-0.1.3.tgz#aa0d32629b6ee972200411cbd4461c907bc2b7ad" - dependencies: - align-text "^0.1.3" - lazy-cache "^1.0.3" - -chainsaw@~0.1.0: - version "0.1.0" - resolved "https://registry.yarnpkg.com/chainsaw/-/chainsaw-0.1.0.tgz#5eab50b28afe58074d0d58291388828b5e5fbc98" - dependencies: - traverse ">=0.3.0 <0.4" - -chalk@^1.1.1, chalk@^1.1.3: - version "1.1.3" - resolved "https://registry.yarnpkg.com/chalk/-/chalk-1.1.3.tgz#a8115c55e4a702fe4d150abd3872822a7e09fc98" - dependencies: - ansi-styles "^2.2.1" - escape-string-regexp "^1.0.2" - has-ansi "^2.0.0" - strip-ansi "^3.0.0" - supports-color "^2.0.0" - -cheerio@^0.19.0: - version "0.19.0" - resolved "https://registry.yarnpkg.com/cheerio/-/cheerio-0.19.0.tgz#772e7015f2ee29965096d71ea4175b75ab354925" - dependencies: - css-select "~1.0.0" - dom-serializer "~0.1.0" - entities "~1.1.1" - htmlparser2 "~3.8.1" - lodash "^3.2.0" - -cliui@^2.1.0: - version "2.1.0" - resolved "https://registry.yarnpkg.com/cliui/-/cliui-2.1.0.tgz#4b475760ff80264c762c3a1719032e91c7fea0d1" - dependencies: - center-align "^0.1.1" - right-align "^0.1.1" - wordwrap "0.0.2" - -cliui@^3.0.3: - version "3.2.0" - resolved "https://registry.yarnpkg.com/cliui/-/cliui-3.2.0.tgz#120601537a916d29940f934da3b48d585a39213d" - dependencies: - string-width "^1.0.1" - strip-ansi "^3.0.1" - wrap-ansi "^2.0.0" - -co@^4.5.4, co@^4.6.0: - version "4.6.0" - resolved "https://registry.yarnpkg.com/co/-/co-4.6.0.tgz#6ea6bdf3d853ae54ccb8e47bfa0bf3f9031fb184" - -code-point-at@^1.0.0: - version "1.1.0" - resolved "https://registry.yarnpkg.com/code-point-at/-/code-point-at-1.1.0.tgz#0d070b4d043a5bea33a2f1a40e2edb3d9a4ccf77" - -combined-stream@^1.0.5, combined-stream@~1.0.5: - version "1.0.5" - resolved "https://registry.yarnpkg.com/combined-stream/-/combined-stream-1.0.5.tgz#938370a57b4a51dea2c77c15d5c5fdf895164009" - dependencies: - delayed-stream "~1.0.0" - -commander@^2.9.0: - version "2.11.0" - resolved "https://registry.yarnpkg.com/commander/-/commander-2.11.0.tgz#157152fd1e7a6c8d98a5b715cf376df928004563" - -commondir@^1.0.1: - version "1.0.1" - resolved "https://registry.yarnpkg.com/commondir/-/commondir-1.0.1.tgz#ddd800da0c66127393cca5950ea968a3aaf1253b" - -concat-map@0.0.1: - version "0.0.1" - resolved "https://registry.yarnpkg.com/concat-map/-/concat-map-0.0.1.tgz#d8a96bd77fd68df7793a73036a3ba0d5405d477b" - -convert-source-map@^1.1.2, convert-source-map@^1.5.0: - version "1.5.0" - resolved "https://registry.yarnpkg.com/convert-source-map/-/convert-source-map-1.5.0.tgz#9acd70851c6d5dfdd93d9282e5edf94a03ff46b5" - -core-js@^2.4.0, core-js@^2.5.0: - version "2.5.1" - resolved "https://registry.yarnpkg.com/core-js/-/core-js-2.5.1.tgz#ae6874dc66937789b80754ff5428df66819ca50b" - -core-util-is@1.0.2, core-util-is@~1.0.0: - version "1.0.2" - resolved "https://registry.yarnpkg.com/core-util-is/-/core-util-is-1.0.2.tgz#b5fd54220aa2bc5ab57aab7140c940754503c1a7" - -coveralls@^2.11.6: - version "2.13.3" - resolved "https://registry.yarnpkg.com/coveralls/-/coveralls-2.13.3.tgz#9ad7c2ae527417f361e8b626483f48ee92dd2bc7" - dependencies: - js-yaml "3.6.1" - lcov-parse "0.0.10" - log-driver "1.2.5" - minimist "1.2.0" - request "2.79.0" - -cross-spawn@^4: - version "4.0.2" - resolved "https://registry.yarnpkg.com/cross-spawn/-/cross-spawn-4.0.2.tgz#7b9247621c23adfdd3856004a823cbe397424d41" - dependencies: - lru-cache "^4.0.1" - which "^1.2.9" - -cryptiles@2.x.x: - version "2.0.5" - resolved "https://registry.yarnpkg.com/cryptiles/-/cryptiles-2.0.5.tgz#3bdfecdc608147c1c67202fa291e7dca59eaa3b8" - dependencies: - boom "2.x.x" - -cryptiles@3.x.x: - version "3.1.2" - resolved "https://registry.yarnpkg.com/cryptiles/-/cryptiles-3.1.2.tgz#a89fbb220f5ce25ec56e8c4aa8a4fd7b5b0d29fe" - dependencies: - boom "5.x.x" - -css-select@~1.0.0: - version "1.0.0" - resolved "https://registry.yarnpkg.com/css-select/-/css-select-1.0.0.tgz#b1121ca51848dd264e2244d058cee254deeb44b0" - dependencies: - boolbase "~1.0.0" - css-what "1.0" - domutils "1.4" - nth-check "~1.0.0" - -css-what@1.0: - version "1.0.0" - resolved "https://registry.yarnpkg.com/css-what/-/css-what-1.0.0.tgz#d7cc2df45180666f99d2b14462639469e00f736c" - -currently-unhandled@^0.4.1: - version "0.4.1" - resolved "https://registry.yarnpkg.com/currently-unhandled/-/currently-unhandled-0.4.1.tgz#988df33feab191ef799a61369dd76c17adf957ea" - dependencies: - array-find-index "^1.0.1" - -dashdash@^1.12.0: - version "1.14.1" - resolved "https://registry.yarnpkg.com/dashdash/-/dashdash-1.14.1.tgz#853cfa0f7cbe2fed5de20326b8dd581035f6e2f0" - dependencies: - assert-plus "^1.0.0" - -debug@^2.1.3, debug@^2.2.0, debug@^2.6.8: - version "2.6.9" - resolved "https://registry.yarnpkg.com/debug/-/debug-2.6.9.tgz#5d128515df134ff327e90a4c93f4e077a536341f" - dependencies: - ms "2.0.0" - -debug@~2.2.0: - version "2.2.0" - resolved "https://registry.yarnpkg.com/debug/-/debug-2.2.0.tgz#f87057e995b1a1f6ae6a4960664137bc56f039da" - dependencies: - ms "0.7.1" - -decamelize@^1.0.0, decamelize@^1.1.1, decamelize@^1.1.2: - version "1.2.0" - resolved "https://registry.yarnpkg.com/decamelize/-/decamelize-1.2.0.tgz#f6534d15148269b20352e7bee26f501f9a191290" - -deep-is@~0.1.3: - version "0.1.3" - resolved "https://registry.yarnpkg.com/deep-is/-/deep-is-0.1.3.tgz#b369d6fb5dbc13eecf524f91b070feedc357cf34" - -delayed-stream@~1.0.0: - version "1.0.0" - resolved "https://registry.yarnpkg.com/delayed-stream/-/delayed-stream-1.0.0.tgz#df3ae199acadfb7d440aaae0b29e2272b24ec619" - -delegates@^1.0.0: - version "1.0.0" - resolved "https://registry.yarnpkg.com/delegates/-/delegates-1.0.0.tgz#84c6e159b81904fdca59a0ef44cd870d31250f9a" - -detect-indent@^4.0.0: - version "4.0.0" - resolved "https://registry.yarnpkg.com/detect-indent/-/detect-indent-4.0.0.tgz#f76d064352cdf43a1cb6ce619c4ee3a9475de208" - dependencies: - repeating "^2.0.0" - -docopt@~0.6.2: - version "0.6.2" - resolved "https://registry.yarnpkg.com/docopt/-/docopt-0.6.2.tgz#b28e9e2220da5ec49f7ea5bb24a47787405eeb11" - -dom-serializer@0, dom-serializer@~0.1.0: - version "0.1.0" - resolved "https://registry.yarnpkg.com/dom-serializer/-/dom-serializer-0.1.0.tgz#073c697546ce0780ce23be4a28e293e40bc30c82" - dependencies: - domelementtype "~1.1.1" - entities "~1.1.1" - -domelementtype@1: - version "1.3.0" - resolved "https://registry.yarnpkg.com/domelementtype/-/domelementtype-1.3.0.tgz#b17aed82e8ab59e52dd9c19b1756e0fc187204c2" - -domelementtype@~1.1.1: - version "1.1.3" - resolved "https://registry.yarnpkg.com/domelementtype/-/domelementtype-1.1.3.tgz#bd28773e2642881aec51544924299c5cd822185b" - -domhandler@2.3: - version "2.3.0" - resolved "https://registry.yarnpkg.com/domhandler/-/domhandler-2.3.0.tgz#2de59a0822d5027fabff6f032c2b25a2a8abe738" - dependencies: - domelementtype "1" - -domutils@1.4: - version "1.4.3" - resolved "https://registry.yarnpkg.com/domutils/-/domutils-1.4.3.tgz#0865513796c6b306031850e175516baf80b72a6f" - dependencies: - domelementtype "1" - -domutils@1.5: - version "1.5.1" - resolved "https://registry.yarnpkg.com/domutils/-/domutils-1.5.1.tgz#dcd8488a26f563d61079e48c9f7b7e32373682cf" - dependencies: - dom-serializer "0" - domelementtype "1" - -downcache@0.0.8: - version "0.0.8" - resolved "https://registry.yarnpkg.com/downcache/-/downcache-0.0.8.tgz#332320dde5806ea55d2e6d2ea674990bda4e8b75" - dependencies: - extend "2.0.x" - graceful-fs "2.0.3" - limiter "1.0.x" - mkdirp "~0.3.5" - npmlog "1.0.0" - request "^2.34.0" - -ecc-jsbn@~0.1.1: - version "0.1.1" - resolved "https://registry.yarnpkg.com/ecc-jsbn/-/ecc-jsbn-0.1.1.tgz#0fc73a9ed5f0d53c38193398523ef7e543777505" - dependencies: - jsbn "~0.1.0" - -entities@1.0: - version "1.0.0" - resolved "https://registry.yarnpkg.com/entities/-/entities-1.0.0.tgz#b2987aa3821347fcde642b24fdfc9e4fb712bf26" - -entities@~1.1.1: - version "1.1.1" - resolved "https://registry.yarnpkg.com/entities/-/entities-1.1.1.tgz#6e5c2d0a5621b5dadaecef80b90edfb5cd7772f0" - -error-ex@^1.2.0: - version "1.3.1" - resolved "https://registry.yarnpkg.com/error-ex/-/error-ex-1.3.1.tgz#f855a86ce61adc4e8621c3cda21e7a7612c3a8dc" - dependencies: - is-arrayish "^0.2.1" - -es6-promise@3.2.1: - version "3.2.1" - resolved "https://registry.yarnpkg.com/es6-promise/-/es6-promise-3.2.1.tgz#ec56233868032909207170c39448e24449dd1fc4" - -es6-promise@^3.0.2: - version "3.3.1" - resolved "https://registry.yarnpkg.com/es6-promise/-/es6-promise-3.3.1.tgz#a08cdde84ccdbf34d027a1451bc91d4bcd28a613" - -escape-string-regexp@^1.0.2, escape-string-regexp@^1.0.5: - version "1.0.5" - resolved "https://registry.yarnpkg.com/escape-string-regexp/-/escape-string-regexp-1.0.5.tgz#1b61c0562190a8dff6ae3bb2cf0200ca130b86d4" - -escodegen@1.1.x: - version "1.1.0" - resolved "https://registry.yarnpkg.com/escodegen/-/escodegen-1.1.0.tgz#c663923f6e20aad48d0c0fa49f31c6d4f49360cf" - dependencies: - esprima "~1.0.4" - estraverse "~1.5.0" - esutils "~1.0.0" - optionalDependencies: - source-map "~0.1.30" - -escodegen@1.8.x: - version "1.8.1" - resolved "https://registry.yarnpkg.com/escodegen/-/escodegen-1.8.1.tgz#5a5b53af4693110bebb0867aa3430dd3b70a1018" - dependencies: - esprima "^2.7.1" - estraverse "^1.9.1" - esutils "^2.0.2" - optionator "^0.8.1" - optionalDependencies: - source-map "~0.2.0" - -esprima@1.0.x, esprima@~1.0.4: - version "1.0.4" - resolved "https://registry.yarnpkg.com/esprima/-/esprima-1.0.4.tgz#9f557e08fc3b4d26ece9dd34f8fbf476b62585ad" - -esprima@2.7.x, esprima@^2.6.0, esprima@^2.7.1: - version "2.7.3" - resolved "https://registry.yarnpkg.com/esprima/-/esprima-2.7.3.tgz#96e3b70d5779f6ad49cd032673d1c312767ba581" - -esprima@^4.0.0: - version "4.0.0" - resolved "https://registry.yarnpkg.com/esprima/-/esprima-4.0.0.tgz#4499eddcd1110e0b218bacf2fa7f7f59f55ca804" - -"esprima@https://github.com/ariya/esprima/tarball/49a2eccb243f29bd653b11e9419241a9d726af7c": - version "1.1.0-dev-harmony" - resolved "https://github.com/ariya/esprima/tarball/49a2eccb243f29bd653b11e9419241a9d726af7c#a03eaca83ec1125aa3d4acddd2636b4dd707db67" - -estraverse@^1.9.1: - version "1.9.3" - resolved "https://registry.yarnpkg.com/estraverse/-/estraverse-1.9.3.tgz#af67f2dc922582415950926091a4005d29c9bb44" - -estraverse@~1.5.0: - version "1.5.1" - resolved "https://registry.yarnpkg.com/estraverse/-/estraverse-1.5.1.tgz#867a3e8e58a9f84618afb6c2ddbcd916b7cbaf71" - -esutils@^2.0.2: - version "2.0.2" - resolved "https://registry.yarnpkg.com/esutils/-/esutils-2.0.2.tgz#0abf4f1caa5bcb1f7a9d8acc6dea4faaa04bac9b" - -esutils@~1.0.0: - version "1.0.0" - resolved "https://registry.yarnpkg.com/esutils/-/esutils-1.0.0.tgz#8151d358e20c8acc7fb745e7472c0025fe496570" - -expand-brackets@^0.1.1: - version "0.1.5" - resolved "https://registry.yarnpkg.com/expand-brackets/-/expand-brackets-0.1.5.tgz#df07284e342a807cd733ac5af72411e581d1177b" - dependencies: - is-posix-bracket "^0.1.0" - -expand-range@^1.8.1: - version "1.8.2" - resolved "https://registry.yarnpkg.com/expand-range/-/expand-range-1.8.2.tgz#a299effd335fe2721ebae8e257ec79644fc85337" - dependencies: - fill-range "^2.1.0" - -extend@2.0.x: - version "2.0.1" - resolved "https://registry.yarnpkg.com/extend/-/extend-2.0.1.tgz#1ee8010689e7395ff9448241c98652bc759a8260" - -extend@~3.0.0, extend@~3.0.1: - version "3.0.1" - resolved "https://registry.yarnpkg.com/extend/-/extend-3.0.1.tgz#a755ea7bc1adfcc5a31ce7e762dbaadc5e636444" - -extsprintf@1.3.0, extsprintf@^1.2.0: - version "1.3.0" - resolved "https://registry.yarnpkg.com/extsprintf/-/extsprintf-1.3.0.tgz#96918440e3041a7a414f8c52e3c574eb3c3e1e05" - -fast-deep-equal@^1.0.0: - version "1.0.0" - resolved "https://registry.yarnpkg.com/fast-deep-equal/-/fast-deep-equal-1.0.0.tgz#96256a3bc975595eb36d82e9929d060d893439ff" - -fast-levenshtein@~2.0.4: - version "2.0.6" - resolved "https://registry.yarnpkg.com/fast-levenshtein/-/fast-levenshtein-2.0.6.tgz#3d8a5c66883a16a30ca8643e851f19baa7797917" - -figures@^1.4.0: - version "1.7.0" - resolved "https://registry.yarnpkg.com/figures/-/figures-1.7.0.tgz#cbe1e3affcf1cd44b80cadfed28dc793a9701d2e" - dependencies: - escape-string-regexp "^1.0.5" - object-assign "^4.1.0" - -filename-regex@^2.0.0: - version "2.0.1" - resolved "https://registry.yarnpkg.com/filename-regex/-/filename-regex-2.0.1.tgz#c1c4b9bee3e09725ddb106b75c1e301fe2f18b26" - -fill-range@^2.1.0: - version "2.2.3" - resolved "https://registry.yarnpkg.com/fill-range/-/fill-range-2.2.3.tgz#50b77dfd7e469bc7492470963699fe7a8485a723" - dependencies: - is-number "^2.1.0" - isobject "^2.0.0" - randomatic "^1.1.3" - repeat-element "^1.1.2" - repeat-string "^1.5.2" - -find-cache-dir@^0.1.1: - version "0.1.1" - resolved "https://registry.yarnpkg.com/find-cache-dir/-/find-cache-dir-0.1.1.tgz#c8defae57c8a52a8a784f9e31c57c742e993a0b9" - dependencies: - commondir "^1.0.1" - mkdirp "^0.5.1" - pkg-dir "^1.0.0" - -find-root@^0.1.1: - version "0.1.2" - resolved "https://registry.yarnpkg.com/find-root/-/find-root-0.1.2.tgz#98d2267cff1916ccaf2743b3a0eea81d79d7dcd1" - -find-up@^1.0.0: - version "1.1.2" - resolved "https://registry.yarnpkg.com/find-up/-/find-up-1.1.2.tgz#6b2e9822b1a2ce0a60ab64d610eccad53cb24d0f" - dependencies: - path-exists "^2.0.0" - pinkie-promise "^2.0.0" - -for-in@^1.0.1: - version "1.0.2" - resolved "https://registry.yarnpkg.com/for-in/-/for-in-1.0.2.tgz#81068d295a8142ec0ac726c6e2200c30fb6d5e80" - -for-own@^0.1.1: - version "0.1.5" - resolved "https://registry.yarnpkg.com/for-own/-/for-own-0.1.5.tgz#5265c681a4f294dabbf17c9509b6763aa84510ce" - dependencies: - for-in "^1.0.1" - -foreground-child@^1.3.5, foreground-child@^1.5.6: - version "1.5.6" - resolved "https://registry.yarnpkg.com/foreground-child/-/foreground-child-1.5.6.tgz#4fd71ad2dfde96789b980a5c0a295937cb2f5ce9" - dependencies: - cross-spawn "^4" - signal-exit "^3.0.0" - -forever-agent@~0.6.1: - version "0.6.1" - resolved "https://registry.yarnpkg.com/forever-agent/-/forever-agent-0.6.1.tgz#fbc71f0c41adeb37f96c577ad1ed42d8fdacca91" - -form-data@~2.1.1: - version "2.1.4" - resolved "https://registry.yarnpkg.com/form-data/-/form-data-2.1.4.tgz#33c183acf193276ecaa98143a69e94bfee1750d1" - dependencies: - asynckit "^0.4.0" - combined-stream "^1.0.5" - mime-types "^2.1.12" - -form-data@~2.3.1: - version "2.3.1" - resolved "https://registry.yarnpkg.com/form-data/-/form-data-2.3.1.tgz#6fb94fbd71885306d73d15cc497fe4cc4ecd44bf" - dependencies: - asynckit "^0.4.0" - combined-stream "^1.0.5" - mime-types "^2.1.12" - -fs-extra@^0.22.1: - version "0.22.1" - resolved "https://registry.yarnpkg.com/fs-extra/-/fs-extra-0.22.1.tgz#5fd6f8049dc976ca19eb2355d658173cabcce056" - dependencies: - graceful-fs "^4.1.2" - jsonfile "^2.1.0" - rimraf "^2.2.8" - -fs-extra@~0.30.0: - version "0.30.0" - resolved "https://registry.yarnpkg.com/fs-extra/-/fs-extra-0.30.0.tgz#f233ffcc08d4da7d432daa449776989db1df93f0" - dependencies: - graceful-fs "^4.1.2" - jsonfile "^2.1.0" - klaw "^1.0.0" - path-is-absolute "^1.0.0" - rimraf "^2.2.8" - -fs.realpath@^1.0.0: - version "1.0.0" - resolved "https://registry.yarnpkg.com/fs.realpath/-/fs.realpath-1.0.0.tgz#1504ad2523158caa40db4a2787cb01411994ea4f" - -"fstream@>= 0.1.30 < 1": - version "0.1.31" - resolved "https://registry.yarnpkg.com/fstream/-/fstream-0.1.31.tgz#7337f058fbbbbefa8c9f561a28cab0849202c988" - dependencies: - graceful-fs "~3.0.2" - inherits "~2.0.0" - mkdirp "0.5" - rimraf "2" - -fstream@^1.0.2: - version "1.0.11" - resolved "https://registry.yarnpkg.com/fstream/-/fstream-1.0.11.tgz#5c1fb1f117477114f0632a0eb4b71b3cb0fd3171" - dependencies: - graceful-fs "^4.1.2" - inherits "~2.0.0" - mkdirp ">=0.5 0" - rimraf "2" - -gauge@~1.0.2: - version "1.0.2" - resolved "https://registry.yarnpkg.com/gauge/-/gauge-1.0.2.tgz#53e25965dfaf1c85be3a2a0633306a24a67dc2f9" - dependencies: - ansi "^0.3.0" - has-unicode "^1.0.0" - -generate-function@^2.0.0: - version "2.0.0" - resolved "https://registry.yarnpkg.com/generate-function/-/generate-function-2.0.0.tgz#6858fe7c0969b7d4e9093337647ac79f60dfbe74" - -generate-object-property@^1.1.0: - version "1.2.0" - resolved "https://registry.yarnpkg.com/generate-object-property/-/generate-object-property-1.2.0.tgz#9c0e1c40308ce804f4783618b937fa88f99d50d0" - dependencies: - is-property "^1.0.0" - -get-mongodb-version@0.0.1: - version "0.0.1" - resolved "https://registry.yarnpkg.com/get-mongodb-version/-/get-mongodb-version-0.0.1.tgz#bc8aa433ba2fdd57fa33312dcf89f06f3a908caa" - dependencies: - debug "^2.2.0" - lodash.startswith "^3.0.1" - minimist "^1.1.1" - mongodb "^2.0.39" - which "^1.1.1" - -get-stdin@^4.0.1: - version "4.0.1" - resolved "https://registry.yarnpkg.com/get-stdin/-/get-stdin-4.0.1.tgz#b968c6b0a04384324902e8bf1a5df32579a450fe" - -getpass@^0.1.1: - version "0.1.7" - resolved "https://registry.yarnpkg.com/getpass/-/getpass-0.1.7.tgz#5eff8e3e684d569ae4cb2b1282604e8ba62149fa" - dependencies: - assert-plus "^1.0.0" - -gleak@0.5.0: - version "0.5.0" - resolved "https://registry.yarnpkg.com/gleak/-/gleak-0.5.0.tgz#9cd7694be50d6dbeb842021ed8160814c51faddf" - -glob-base@^0.3.0: - version "0.3.0" - resolved "https://registry.yarnpkg.com/glob-base/-/glob-base-0.3.0.tgz#dbb164f6221b1c0b1ccf82aea328b497df0ea3c4" - dependencies: - glob-parent "^2.0.0" - is-glob "^2.0.0" - -glob-parent@^2.0.0: - version "2.0.0" - resolved "https://registry.yarnpkg.com/glob-parent/-/glob-parent-2.0.0.tgz#81383d72db054fcccf5336daa902f182f6edbb28" - dependencies: - is-glob "^2.0.0" - -glob@^5.0.15: - version "5.0.15" - resolved "https://registry.yarnpkg.com/glob/-/glob-5.0.15.tgz#1bc936b9e02f4a603fcc222ecf7633d30b8b93b1" - dependencies: - inflight "^1.0.4" - inherits "2" - minimatch "2 || 3" - once "^1.3.0" - path-is-absolute "^1.0.0" - -glob@^6.0.2: - version "6.0.4" - resolved "https://registry.yarnpkg.com/glob/-/glob-6.0.4.tgz#0f08860f6a155127b2fadd4f9ce24b1aab6e4d22" - dependencies: - inflight "^1.0.4" - inherits "2" - minimatch "2 || 3" - once "^1.3.0" - path-is-absolute "^1.0.0" - -glob@^7.0.5: - version "7.1.2" - resolved "https://registry.yarnpkg.com/glob/-/glob-7.1.2.tgz#c19c9df9a028702d678612384a6552404c636d15" - dependencies: - fs.realpath "^1.0.0" - inflight "^1.0.4" - inherits "2" - minimatch "^3.0.4" - once "^1.3.0" - path-is-absolute "^1.0.0" - -globals@^9.18.0: - version "9.18.0" - resolved "https://registry.yarnpkg.com/globals/-/globals-9.18.0.tgz#aa3896b3e69b487f17e31ed2143d69a8e30c2d8a" - -graceful-fs@2.0.3: - version "2.0.3" - resolved "https://registry.yarnpkg.com/graceful-fs/-/graceful-fs-2.0.3.tgz#7cd2cdb228a4a3f36e95efa6cc142de7d1a136d0" - -graceful-fs@^4.1.11, graceful-fs@^4.1.2, graceful-fs@^4.1.6, graceful-fs@^4.1.9: - version "4.1.11" - resolved "https://registry.yarnpkg.com/graceful-fs/-/graceful-fs-4.1.11.tgz#0e8bdfe4d1ddb8854d64e04ea7c00e2a026e5658" - -graceful-fs@~3.0.2: - version "3.0.11" - resolved "https://registry.yarnpkg.com/graceful-fs/-/graceful-fs-3.0.11.tgz#7613c778a1afea62f25c630a086d7f3acbbdd818" - dependencies: - natives "^1.1.0" - -handlebars@2.0.0-alpha.1: - version "2.0.0-alpha.1" - resolved "https://registry.yarnpkg.com/handlebars/-/handlebars-2.0.0-alpha.1.tgz#c4d149068c713de0afa7f45bbb88a2ca73715afd" - dependencies: - optimist "~0.3" - optionalDependencies: - uglify-js "~2.3" - -handlebars@^4.0.1: - version "4.0.10" - resolved "https://registry.yarnpkg.com/handlebars/-/handlebars-4.0.10.tgz#3d30c718b09a3d96f23ea4cc1f403c4d3ba9ff4f" - dependencies: - async "^1.4.0" - optimist "^0.6.1" - source-map "^0.4.4" - optionalDependencies: - uglify-js "^2.6" - -har-schema@^2.0.0: - version "2.0.0" - resolved "https://registry.yarnpkg.com/har-schema/-/har-schema-2.0.0.tgz#a94c2224ebcac04782a0d9035521f24735b7ec92" - -har-validator@~2.0.6: - version "2.0.6" - resolved "https://registry.yarnpkg.com/har-validator/-/har-validator-2.0.6.tgz#cdcbc08188265ad119b6a5a7c8ab70eecfb5d27d" - dependencies: - chalk "^1.1.1" - commander "^2.9.0" - is-my-json-valid "^2.12.4" - pinkie-promise "^2.0.0" - -har-validator@~5.0.3: - version "5.0.3" - resolved "https://registry.yarnpkg.com/har-validator/-/har-validator-5.0.3.tgz#ba402c266194f15956ef15e0fcf242993f6a7dfd" - dependencies: - ajv "^5.1.0" - har-schema "^2.0.0" - -has-ansi@^2.0.0: - version "2.0.0" - resolved "https://registry.yarnpkg.com/has-ansi/-/has-ansi-2.0.0.tgz#34f5049ce1ecdf2b0649af3ef24e45ed35416d91" - dependencies: - ansi-regex "^2.0.0" - -has-flag@^1.0.0: - version "1.0.0" - resolved "https://registry.yarnpkg.com/has-flag/-/has-flag-1.0.0.tgz#9d9e793165ce017a00f00418c43f942a7b1d11fa" - -has-unicode@^1.0.0: - version "1.0.1" - resolved "https://registry.yarnpkg.com/has-unicode/-/has-unicode-1.0.1.tgz#c46fceea053eb8ec789bffbba25fca52dfdcf38e" - -hawk@~3.1.3: - version "3.1.3" - resolved "https://registry.yarnpkg.com/hawk/-/hawk-3.1.3.tgz#078444bd7c1640b0fe540d2c9b73d59678e8e1c4" - dependencies: - boom "2.x.x" - cryptiles "2.x.x" - hoek "2.x.x" - sntp "1.x.x" - -hawk@~6.0.2: - version "6.0.2" - resolved "https://registry.yarnpkg.com/hawk/-/hawk-6.0.2.tgz#af4d914eb065f9b5ce4d9d11c1cb2126eecc3038" - dependencies: - boom "4.x.x" - cryptiles "3.x.x" - hoek "4.x.x" - sntp "2.x.x" - -hoek@2.x.x: - version "2.16.3" - resolved "https://registry.yarnpkg.com/hoek/-/hoek-2.16.3.tgz#20bb7403d3cea398e91dc4710a8ff1b8274a25ed" - -hoek@4.x.x: - version "4.2.0" - resolved "https://registry.yarnpkg.com/hoek/-/hoek-4.2.0.tgz#72d9d0754f7fe25ca2d01ad8f8f9a9449a89526d" - -home-or-tmp@^2.0.0: - version "2.0.0" - resolved "https://registry.yarnpkg.com/home-or-tmp/-/home-or-tmp-2.0.0.tgz#e36c3f2d2cae7d746a857e38d18d5f32a7882db8" - dependencies: - os-homedir "^1.0.0" - os-tmpdir "^1.0.1" - -hosted-git-info@^2.1.4: - version "2.5.0" - resolved "https://registry.yarnpkg.com/hosted-git-info/-/hosted-git-info-2.5.0.tgz#6d60e34b3abbc8313062c3b798ef8d901a07af3c" - -htmlparser2@~3.8.1: - version "3.8.3" - resolved "https://registry.yarnpkg.com/htmlparser2/-/htmlparser2-3.8.3.tgz#996c28b191516a8be86501a7d79757e5c70c1068" - dependencies: - domelementtype "1" - domhandler "2.3" - domutils "1.5" - entities "1.0" - readable-stream "1.1" - -http-signature@~1.1.0: - version "1.1.1" - resolved "https://registry.yarnpkg.com/http-signature/-/http-signature-1.1.1.tgz#df72e267066cd0ac67fb76adf8e134a8fbcf91bf" - dependencies: - assert-plus "^0.2.0" - jsprim "^1.2.2" - sshpk "^1.7.0" - -http-signature@~1.2.0: - version "1.2.0" - resolved "https://registry.yarnpkg.com/http-signature/-/http-signature-1.2.0.tgz#9aecd925114772f3d95b65a60abb8f7c18fbace1" - dependencies: - assert-plus "^1.0.0" - jsprim "^1.2.2" - sshpk "^1.7.0" - -imurmurhash@^0.1.4: - version "0.1.4" - resolved "https://registry.yarnpkg.com/imurmurhash/-/imurmurhash-0.1.4.tgz#9218b9b2b928a238b13dc4fb6b6d576f231453ea" - -indent-string@^2.1.0: - version "2.1.0" - resolved "https://registry.yarnpkg.com/indent-string/-/indent-string-2.1.0.tgz#8e2d48348742121b4a8218b7a137e9a52049dc80" - dependencies: - repeating "^2.0.0" - -inflight@^1.0.4: - version "1.0.6" - resolved "https://registry.yarnpkg.com/inflight/-/inflight-1.0.6.tgz#49bd6331d7d02d0c09bc910a1075ba8165b56df9" - dependencies: - once "^1.3.0" - wrappy "1" - -inherits@2, inherits@~2.0.0, inherits@~2.0.1, inherits@~2.0.3: - version "2.0.3" - resolved "https://registry.yarnpkg.com/inherits/-/inherits-2.0.3.tgz#633c2c83e3da42a502f52466022480f4208261de" - -integra@0.1.8: - version "0.1.8" - resolved "https://registry.yarnpkg.com/integra/-/integra-0.1.8.tgz#8d5b8019f87ea3704e6c97da2c912e14ec3bece7" - dependencies: - escodegen "1.1.x" - esprima "1.0.x" - handlebars "2.0.0-alpha.1" - mkdirp latest - rimraf "2.2.6" - -invariant@^2.2.2: - version "2.2.2" - resolved "https://registry.yarnpkg.com/invariant/-/invariant-2.2.2.tgz#9e1f56ac0acdb6bf303306f338be3b204ae60360" - dependencies: - loose-envify "^1.0.0" - -invert-kv@^1.0.0: - version "1.0.0" - resolved "https://registry.yarnpkg.com/invert-kv/-/invert-kv-1.0.0.tgz#104a8e4aaca6d3d8cd157a8ef8bfab2d7a3ffdb6" - -is-arrayish@^0.2.1: - version "0.2.1" - resolved "https://registry.yarnpkg.com/is-arrayish/-/is-arrayish-0.2.1.tgz#77c99840527aa8ecb1a8ba697b80645a7a926a9d" - -is-buffer@^1.1.5: - version "1.1.5" - resolved "https://registry.yarnpkg.com/is-buffer/-/is-buffer-1.1.5.tgz#1f3b26ef613b214b88cbca23cc6c01d87961eecc" - -is-builtin-module@^1.0.0: - version "1.0.0" - resolved "https://registry.yarnpkg.com/is-builtin-module/-/is-builtin-module-1.0.0.tgz#540572d34f7ac3119f8f76c30cbc1b1e037affbe" - dependencies: - builtin-modules "^1.0.0" - -is-dotfile@^1.0.0: - version "1.0.3" - resolved "https://registry.yarnpkg.com/is-dotfile/-/is-dotfile-1.0.3.tgz#a6a2f32ffd2dfb04f5ca25ecd0f6b83cf798a1e1" - -is-equal-shallow@^0.1.3: - version "0.1.3" - resolved "https://registry.yarnpkg.com/is-equal-shallow/-/is-equal-shallow-0.1.3.tgz#2238098fc221de0bcfa5d9eac4c45d638aa1c534" - dependencies: - is-primitive "^2.0.0" - -is-extglob@^1.0.0: - version "1.0.0" - resolved "https://registry.yarnpkg.com/is-extglob/-/is-extglob-1.0.0.tgz#ac468177c4943405a092fc8f29760c6ffc6206c0" - -is-finite@^1.0.0: - version "1.0.2" - resolved "https://registry.yarnpkg.com/is-finite/-/is-finite-1.0.2.tgz#cc6677695602be550ef11e8b4aa6305342b6d0aa" - dependencies: - number-is-nan "^1.0.0" - -is-fullwidth-code-point@^1.0.0: - version "1.0.0" - resolved "https://registry.yarnpkg.com/is-fullwidth-code-point/-/is-fullwidth-code-point-1.0.0.tgz#ef9e31386f031a7f0d643af82fde50c457ef00cb" - dependencies: - number-is-nan "^1.0.0" - -is-glob@^1.1.3: - version "1.1.3" - resolved "https://registry.yarnpkg.com/is-glob/-/is-glob-1.1.3.tgz#b4c64b8303d39114492a460d364ccfb0d3c0a045" - -is-glob@^2.0.0: - version "2.0.1" - resolved "https://registry.yarnpkg.com/is-glob/-/is-glob-2.0.1.tgz#d096f926a3ded5600f3fdfd91198cb0888c2d863" - dependencies: - is-extglob "^1.0.0" - -is-my-json-valid@^2.12.4: - version "2.16.1" - resolved "https://registry.yarnpkg.com/is-my-json-valid/-/is-my-json-valid-2.16.1.tgz#5a846777e2c2620d1e69104e5d3a03b1f6088f11" - dependencies: - generate-function "^2.0.0" - generate-object-property "^1.1.0" - jsonpointer "^4.0.0" - xtend "^4.0.0" - -is-number@^2.1.0: - version "2.1.0" - resolved "https://registry.yarnpkg.com/is-number/-/is-number-2.1.0.tgz#01fcbbb393463a548f2f466cce16dece49db908f" - dependencies: - kind-of "^3.0.2" - -is-number@^3.0.0: - version "3.0.0" - resolved "https://registry.yarnpkg.com/is-number/-/is-number-3.0.0.tgz#24fd6201a4782cf50561c810276afc7d12d71195" - dependencies: - kind-of "^3.0.2" - -is-posix-bracket@^0.1.0: - version "0.1.1" - resolved "https://registry.yarnpkg.com/is-posix-bracket/-/is-posix-bracket-0.1.1.tgz#3334dc79774368e92f016e6fbc0a88f5cd6e6bc4" - -is-primitive@^2.0.0: - version "2.0.0" - resolved "https://registry.yarnpkg.com/is-primitive/-/is-primitive-2.0.0.tgz#207bab91638499c07b2adf240a41a87210034575" - -is-property@^1.0.0: - version "1.0.2" - resolved "https://registry.yarnpkg.com/is-property/-/is-property-1.0.2.tgz#57fe1c4e48474edd65b09911f26b1cd4095dda84" - -is-typedarray@~1.0.0: - version "1.0.0" - resolved "https://registry.yarnpkg.com/is-typedarray/-/is-typedarray-1.0.0.tgz#e479c80858df0c1b11ddda6940f96011fcda4a9a" - -is-utf8@^0.2.0: - version "0.2.1" - resolved "https://registry.yarnpkg.com/is-utf8/-/is-utf8-0.2.1.tgz#4b0da1442104d1b336340e80797e865cf39f7d72" - -isarray@0.0.1: - version "0.0.1" - resolved "https://registry.yarnpkg.com/isarray/-/isarray-0.0.1.tgz#8a18acfca9a8f4177e09abfc6038939b05d1eedf" - -isarray@1.0.0, isarray@~1.0.0: - version "1.0.0" - resolved "https://registry.yarnpkg.com/isarray/-/isarray-1.0.0.tgz#bb935d48582cba168c06834957a54a3e07124f11" - -isexe@^2.0.0: - version "2.0.0" - resolved "https://registry.yarnpkg.com/isexe/-/isexe-2.0.0.tgz#e8fbf374dc556ff8947a10dcb0572d633f2cfa10" - -isobject@^0.2.0: - version "0.2.0" - resolved "https://registry.yarnpkg.com/isobject/-/isobject-0.2.0.tgz#a3432192f39b910b5f02cc989487836ec70aa85e" - -isobject@^2.0.0: - version "2.1.0" - resolved "https://registry.yarnpkg.com/isobject/-/isobject-2.1.0.tgz#f065561096a3f1da2ef46272f815c840d87e0c89" - dependencies: - isarray "1.0.0" - -isstream@~0.1.2: - version "0.1.2" - resolved "https://registry.yarnpkg.com/isstream/-/isstream-0.1.2.tgz#47e63f7af55afa6f92e1500e690eb8b8529c099a" - -istanbul@^0.4.1: - version "0.4.5" - resolved "https://registry.yarnpkg.com/istanbul/-/istanbul-0.4.5.tgz#65c7d73d4c4da84d4f3ac310b918fb0b8033733b" - dependencies: - abbrev "1.0.x" - async "1.x" - escodegen "1.8.x" - esprima "2.7.x" - glob "^5.0.15" - handlebars "^4.0.1" - js-yaml "3.x" - mkdirp "0.5.x" - nopt "3.x" - once "1.x" - resolve "1.1.x" - supports-color "^3.1.0" - which "^1.1.1" - wordwrap "^1.0.0" - -js-tokens@^3.0.0, js-tokens@^3.0.2: - version "3.0.2" - resolved "https://registry.yarnpkg.com/js-tokens/-/js-tokens-3.0.2.tgz#9866df395102130e38f7f996bceb65443209c25b" - -js-yaml@3.6.1: - version "3.6.1" - resolved "https://registry.yarnpkg.com/js-yaml/-/js-yaml-3.6.1.tgz#6e5fe67d8b205ce4d22fad05b7781e8dadcc4b30" - dependencies: - argparse "^1.0.7" - esprima "^2.6.0" - -js-yaml@3.x: - version "3.10.0" - resolved "https://registry.yarnpkg.com/js-yaml/-/js-yaml-3.10.0.tgz#2e78441646bd4682e963f22b6e92823c309c62dc" - dependencies: - argparse "^1.0.7" - esprima "^4.0.0" - -js2xmlparser@~0.1.0: - version "0.1.9" - resolved "https://registry.yarnpkg.com/js2xmlparser/-/js2xmlparser-0.1.9.tgz#2c516788e09460637f9a403dfed7b925f71d239e" - -jsbn@~0.1.0: - version "0.1.1" - resolved "https://registry.yarnpkg.com/jsbn/-/jsbn-0.1.1.tgz#a5e654c2e5a2deb5f201d96cefbca80c0ef2f513" - -jsdoc@3.3.0-alpha8: - version "3.3.0-alpha8" - resolved "https://registry.yarnpkg.com/jsdoc/-/jsdoc-3.3.0-alpha8.tgz#d7960708ec99f5390dca78ba8da9677188a17363" - dependencies: - async "~0.1.22" - catharsis "~0.8.2" - esprima "https://github.com/ariya/esprima/tarball/49a2eccb243f29bd653b11e9419241a9d726af7c" - js2xmlparser "~0.1.0" - marked "~0.3.1" - requizzle "~0.1.1" - strip-json-comments "~0.1.3" - taffydb "https://github.com/hegemonic/taffydb/tarball/master" - underscore "~1.6.0" - wrench "~1.3.9" - -jsesc@^1.3.0: - version "1.3.0" - resolved "https://registry.yarnpkg.com/jsesc/-/jsesc-1.3.0.tgz#46c3fec8c1892b12b0833db9bc7622176dbab34b" - -json-schema-traverse@^0.3.0: - version "0.3.1" - resolved "https://registry.yarnpkg.com/json-schema-traverse/-/json-schema-traverse-0.3.1.tgz#349a6d44c53a51de89b40805c5d5e59b417d3340" - -json-schema@0.2.3: - version "0.2.3" - resolved "https://registry.yarnpkg.com/json-schema/-/json-schema-0.2.3.tgz#b480c892e59a2f05954ce727bd3f2a4e882f9e13" - -json-stable-stringify@^1.0.1: - version "1.0.1" - resolved "https://registry.yarnpkg.com/json-stable-stringify/-/json-stable-stringify-1.0.1.tgz#9a759d39c5f2ff503fd5300646ed445f88c4f9af" - dependencies: - jsonify "~0.0.0" - -json-stringify-safe@~5.0.1: - version "5.0.1" - resolved "https://registry.yarnpkg.com/json-stringify-safe/-/json-stringify-safe-5.0.1.tgz#1296a2d58fd45f19a0f6ce01d65701e2c735b6eb" - -json5@^0.5.1: - version "0.5.1" - resolved "https://registry.yarnpkg.com/json5/-/json5-0.5.1.tgz#1eade7acc012034ad84e2396767ead9fa5495821" - -jsonfile@^2.1.0: - version "2.4.0" - resolved "https://registry.yarnpkg.com/jsonfile/-/jsonfile-2.4.0.tgz#3736a2b428b87bbda0cc83b53fa3d633a35c2ae8" - optionalDependencies: - graceful-fs "^4.1.6" - -jsonify@~0.0.0: - version "0.0.0" - resolved "https://registry.yarnpkg.com/jsonify/-/jsonify-0.0.0.tgz#2c74b6ee41d93ca51b7b5aaee8f503631d252a73" - -jsonpointer@^4.0.0: - version "4.0.1" - resolved "https://registry.yarnpkg.com/jsonpointer/-/jsonpointer-4.0.1.tgz#4fd92cb34e0e9db3c89c8622ecf51f9b978c6cb9" - -jsprim@^1.2.2: - version "1.4.1" - resolved "https://registry.yarnpkg.com/jsprim/-/jsprim-1.4.1.tgz#313e66bc1e5cc06e438bc1b7499c2e5c56acb6a2" - dependencies: - assert-plus "1.0.0" - extsprintf "1.3.0" - json-schema "0.2.3" - verror "1.10.0" - -kerberos@^0.0.23: - version "0.0.23" - resolved "https://registry.yarnpkg.com/kerberos/-/kerberos-0.0.23.tgz#6aa46afdb9786c6919388cc5b408f012c71f0fd1" - dependencies: - nan "~2.5.1" - -key-tree-store@^1.3.0: - version "1.3.0" - resolved "https://registry.yarnpkg.com/key-tree-store/-/key-tree-store-1.3.0.tgz#5ea29afc2529a425938437d6955b714ce6a9791f" - -kind-of@^1.1.0: - version "1.1.0" - resolved "https://registry.yarnpkg.com/kind-of/-/kind-of-1.1.0.tgz#140a3d2d41a36d2efcfa9377b62c24f8495a5c44" - -kind-of@^3.0.2: - version "3.2.2" - resolved "https://registry.yarnpkg.com/kind-of/-/kind-of-3.2.2.tgz#31ea21a734bab9bbb0f32466d893aea51e4a3c64" - dependencies: - is-buffer "^1.1.5" - -kind-of@^4.0.0: - version "4.0.0" - resolved "https://registry.yarnpkg.com/kind-of/-/kind-of-4.0.0.tgz#20813df3d712928b207378691a45066fae72dd57" - dependencies: - is-buffer "^1.1.5" - -klaw@^1.0.0: - version "1.3.1" - resolved "https://registry.yarnpkg.com/klaw/-/klaw-1.3.1.tgz#4088433b46b3b1ba259d78785d8e96f73ba02439" - optionalDependencies: - graceful-fs "^4.1.9" - -lazy-cache@^1.0.3: - version "1.0.4" - resolved "https://registry.yarnpkg.com/lazy-cache/-/lazy-cache-1.0.4.tgz#a1d78fc3a50474cb80845d3b3b6e1da49a446e8e" - -lcid@^1.0.0: - version "1.0.0" - resolved "https://registry.yarnpkg.com/lcid/-/lcid-1.0.0.tgz#308accafa0bc483a3867b4b6f2b9506251d1b835" - dependencies: - invert-kv "^1.0.0" - -lcov-parse@0.0.10: - version "0.0.10" - resolved "https://registry.yarnpkg.com/lcov-parse/-/lcov-parse-0.0.10.tgz#1b0b8ff9ac9c7889250582b70b71315d9da6d9a3" - -levn@~0.3.0: - version "0.3.0" - resolved "https://registry.yarnpkg.com/levn/-/levn-0.3.0.tgz#3b09924edf9f083c0490fdd4c0bc4421e04764ee" - dependencies: - prelude-ls "~1.1.2" - type-check "~0.3.2" - -limiter@1.0.x: - version "1.0.5" - resolved "https://registry.yarnpkg.com/limiter/-/limiter-1.0.5.tgz#9630b2a0d3bad63203f96e3d96f32f83d442dfc8" - -load-json-file@^1.0.0: - version "1.1.0" - resolved "https://registry.yarnpkg.com/load-json-file/-/load-json-file-1.1.0.tgz#956905708d58b4bab4c2261b04f59f31c99374c0" - dependencies: - graceful-fs "^4.1.2" - parse-json "^2.2.0" - pify "^2.0.0" - pinkie-promise "^2.0.0" - strip-bom "^2.0.0" - -lodash._baseassign@^3.0.0: - version "3.2.0" - resolved "https://registry.yarnpkg.com/lodash._baseassign/-/lodash._baseassign-3.2.0.tgz#8c38a099500f215ad09e59f1722fd0c52bfe0a4e" - dependencies: - lodash._basecopy "^3.0.0" - lodash.keys "^3.0.0" - -lodash._basecopy@^3.0.0: - version "3.0.1" - resolved "https://registry.yarnpkg.com/lodash._basecopy/-/lodash._basecopy-3.0.1.tgz#8da0e6a876cf344c0ad8a54882111dd3c5c7ca36" - -lodash._bindcallback@^3.0.0: - version "3.0.1" - resolved "https://registry.yarnpkg.com/lodash._bindcallback/-/lodash._bindcallback-3.0.1.tgz#e531c27644cf8b57a99e17ed95b35c748789392e" - -lodash._createassigner@^3.0.0: - version "3.1.1" - resolved "https://registry.yarnpkg.com/lodash._createassigner/-/lodash._createassigner-3.1.1.tgz#838a5bae2fdaca63ac22dee8e19fa4e6d6970b11" - dependencies: - lodash._bindcallback "^3.0.0" - lodash._isiterateecall "^3.0.0" - lodash.restparam "^3.0.0" - -lodash._getnative@^3.0.0: - version "3.9.1" - resolved "https://registry.yarnpkg.com/lodash._getnative/-/lodash._getnative-3.9.1.tgz#570bc7dede46d61cdcde687d65d3eecbaa3aaff5" - -lodash._isiterateecall@^3.0.0: - version "3.0.9" - resolved "https://registry.yarnpkg.com/lodash._isiterateecall/-/lodash._isiterateecall-3.0.9.tgz#5203ad7ba425fae842460e696db9cf3e6aac057c" - -lodash._root@^3.0.0: - version "3.0.1" - resolved "https://registry.yarnpkg.com/lodash._root/-/lodash._root-3.0.1.tgz#fba1c4524c19ee9a5f8136b4609f017cf4ded692" - -lodash.assign@^3.0.0: - version "3.2.0" - resolved "https://registry.yarnpkg.com/lodash.assign/-/lodash.assign-3.2.0.tgz#3ce9f0234b4b2223e296b8fa0ac1fee8ebca64fa" - dependencies: - lodash._baseassign "^3.0.0" - lodash._createassigner "^3.0.0" - lodash.keys "^3.0.0" - -lodash.defaults@^3.1.2: - version "3.1.2" - resolved "https://registry.yarnpkg.com/lodash.defaults/-/lodash.defaults-3.1.2.tgz#c7308b18dbf8bc9372d701a73493c61192bd2e2c" - dependencies: - lodash.assign "^3.0.0" - lodash.restparam "^3.0.0" - -lodash.defaults@^4.0.0: - version "4.2.0" - resolved "https://registry.yarnpkg.com/lodash.defaults/-/lodash.defaults-4.2.0.tgz#d09178716ffea4dde9e5fb7b37f6f0802274580c" - -lodash.difference@^4.1.1: - version "4.5.0" - resolved "https://registry.yarnpkg.com/lodash.difference/-/lodash.difference-4.5.0.tgz#9ccb4e505d486b91651345772885a2df27fd017c" - -lodash.isarguments@^3.0.0: - version "3.1.0" - resolved "https://registry.yarnpkg.com/lodash.isarguments/-/lodash.isarguments-3.1.0.tgz#2f573d85c6a24289ff00663b491c1d338ff3458a" - -lodash.isarray@^3.0.0: - version "3.0.4" - resolved "https://registry.yarnpkg.com/lodash.isarray/-/lodash.isarray-3.0.4.tgz#79e4eb88c36a8122af86f844aa9bcd851b5fbb55" - -lodash.keys@^3.0.0: - version "3.1.2" - resolved "https://registry.yarnpkg.com/lodash.keys/-/lodash.keys-3.1.2.tgz#4dbc0472b156be50a0b286855d1bd0b0c656098a" - dependencies: - lodash._getnative "^3.0.0" - lodash.isarguments "^3.0.0" - lodash.isarray "^3.0.0" - -lodash.restparam@^3.0.0: - version "3.6.1" - resolved "https://registry.yarnpkg.com/lodash.restparam/-/lodash.restparam-3.6.1.tgz#936a4e309ef330a7645ed4145986c85ae5b20805" - -lodash.startswith@^3.0.1: - version "3.2.0" - resolved "https://registry.yarnpkg.com/lodash.startswith/-/lodash.startswith-3.2.0.tgz#fc2e1ed2c6df8c777117632e87fe4a9181d483fb" - dependencies: - lodash._root "^3.0.0" - -lodash@^3.2.0: - version "3.10.1" - resolved "https://registry.yarnpkg.com/lodash/-/lodash-3.10.1.tgz#5bf45e8e49ba4189e17d482789dfd15bd140b7b6" - -lodash@^4.11.1, lodash@^4.17.4, lodash@^4.6.1: - version "4.17.4" - resolved "https://registry.yarnpkg.com/lodash/-/lodash-4.17.4.tgz#78203a4d1c328ae1d86dca6460e369b57f4055ae" - -log-driver@1.2.5: - version "1.2.5" - resolved "https://registry.yarnpkg.com/log-driver/-/log-driver-1.2.5.tgz#7ae4ec257302fd790d557cb10c97100d857b0056" - -longest@^1.0.1: - version "1.0.1" - resolved "https://registry.yarnpkg.com/longest/-/longest-1.0.1.tgz#30a0b2da38f73770e8294a0d22e6625ed77d0097" - -loose-envify@^1.0.0: - version "1.3.1" - resolved "https://registry.yarnpkg.com/loose-envify/-/loose-envify-1.3.1.tgz#d1a8ad33fa9ce0e713d65fdd0ac8b748d478c848" - dependencies: - js-tokens "^3.0.0" - -loud-rejection@^1.0.0: - version "1.6.0" - resolved "https://registry.yarnpkg.com/loud-rejection/-/loud-rejection-1.6.0.tgz#5b46f80147edee578870f086d04821cf998e551f" - dependencies: - currently-unhandled "^0.4.1" - signal-exit "^3.0.0" - -lru-cache@^4.0.1: - version "4.1.1" - resolved "https://registry.yarnpkg.com/lru-cache/-/lru-cache-4.1.1.tgz#622e32e82488b49279114a4f9ecf45e7cd6bba55" - dependencies: - pseudomap "^1.0.2" - yallist "^2.1.2" - -map-obj@^1.0.0, map-obj@^1.0.1: - version "1.0.1" - resolved "https://registry.yarnpkg.com/map-obj/-/map-obj-1.0.1.tgz#d933ceb9205d82bdcf4886f6742bdc2b4dea146d" - -marked@~0.3.1: - version "0.3.6" - resolved "https://registry.yarnpkg.com/marked/-/marked-0.3.6.tgz#b2c6c618fccece4ef86c4fc6cb8a7cbf5aeda8d7" - -"match-stream@>= 0.0.2 < 1": - version "0.0.2" - resolved "https://registry.yarnpkg.com/match-stream/-/match-stream-0.0.2.tgz#99eb050093b34dffade421b9ac0b410a9cfa17cf" - dependencies: - buffers "~0.1.1" - readable-stream "~1.0.0" - -md5-hex@^1.2.0: - version "1.3.0" - resolved "https://registry.yarnpkg.com/md5-hex/-/md5-hex-1.3.0.tgz#d2c4afe983c4370662179b8cad145219135046c4" - dependencies: - md5-o-matic "^0.1.1" - -md5-o-matic@^0.1.1: - version "0.1.1" - resolved "https://registry.yarnpkg.com/md5-o-matic/-/md5-o-matic-0.1.1.tgz#822bccd65e117c514fab176b25945d54100a03c3" - -meow@^3.1.0: - version "3.7.0" - resolved "https://registry.yarnpkg.com/meow/-/meow-3.7.0.tgz#72cb668b425228290abbfa856892587308a801fb" - dependencies: - camelcase-keys "^2.0.0" - decamelize "^1.1.2" - loud-rejection "^1.0.0" - map-obj "^1.0.1" - minimist "^1.1.3" - normalize-package-data "^2.3.4" - object-assign "^4.0.1" - read-pkg-up "^1.0.1" - redent "^1.0.0" - trim-newlines "^1.0.0" - -micromatch@~2.1.6: - version "2.1.6" - resolved "https://registry.yarnpkg.com/micromatch/-/micromatch-2.1.6.tgz#51a65a9dcbfb92113292a071e04da35a81e9050e" - dependencies: - arr-diff "^1.0.1" - braces "^1.8.0" - debug "^2.1.3" - expand-brackets "^0.1.1" - filename-regex "^2.0.0" - is-glob "^1.1.3" - kind-of "^1.1.0" - object.omit "^0.2.1" - parse-glob "^3.0.0" - regex-cache "^0.4.0" - -mime-db@~1.30.0: - version "1.30.0" - resolved "https://registry.yarnpkg.com/mime-db/-/mime-db-1.30.0.tgz#74c643da2dd9d6a45399963465b26d5ca7d71f01" - -mime-types@^2.1.12, mime-types@~2.1.17, mime-types@~2.1.7: - version "2.1.17" - resolved "https://registry.yarnpkg.com/mime-types/-/mime-types-2.1.17.tgz#09d7a393f03e995a79f8af857b70a9e0ab16557a" - dependencies: - mime-db "~1.30.0" - -"minimatch@2 || 3", minimatch@^3.0.4: - version "3.0.4" - resolved "https://registry.yarnpkg.com/minimatch/-/minimatch-3.0.4.tgz#5166e286457f03306064be5497e8dbb0c3d32083" - dependencies: - brace-expansion "^1.1.7" - -minimist@0.0.8: - version "0.0.8" - resolved "https://registry.yarnpkg.com/minimist/-/minimist-0.0.8.tgz#857fcabfc3397d2625b8228262e86aa7a011b05d" - -minimist@1.2.0, minimist@^1.1.0, minimist@^1.1.1, minimist@^1.1.3, minimist@^1.2.0: - version "1.2.0" - resolved "https://registry.yarnpkg.com/minimist/-/minimist-1.2.0.tgz#a35008b20f41383eec1fb914f4cd5df79a264284" - -minimist@~0.0.1: - version "0.0.10" - resolved "https://registry.yarnpkg.com/minimist/-/minimist-0.0.10.tgz#de3f98543dbf96082be48ad1a0c7cda836301dcf" - -mkdirp@0.5, mkdirp@0.5.x, "mkdirp@>=0.5 0", mkdirp@^0.5.0, mkdirp@^0.5.1, mkdirp@latest: - version "0.5.1" - resolved "https://registry.yarnpkg.com/mkdirp/-/mkdirp-0.5.1.tgz#30057438eac6cf7f8c4767f38648d6697d75c903" - dependencies: - minimist "0.0.8" - -mkdirp@0.5.0: - version "0.5.0" - resolved "https://registry.yarnpkg.com/mkdirp/-/mkdirp-0.5.0.tgz#1d73076a6df986cd9344e15e71fcc05a4c9abf12" - dependencies: - minimist "0.0.8" - -mkdirp@~0.3.5: - version "0.3.5" - resolved "https://registry.yarnpkg.com/mkdirp/-/mkdirp-0.3.5.tgz#de3e5f8961c88c787ee1368df849ac4413eca8d7" - -mongodb-core@2.1.16, mongodb-core@^2.1.12: - version "2.1.16" - resolved "https://registry.yarnpkg.com/mongodb-core/-/mongodb-core-2.1.16.tgz#5dc20a48b1f0a2515fd57daaea2c4853467454e0" - dependencies: - bson "~1.0.4" - require_optional "~1.0.0" - -mongodb-download-url@^0.1.10: - version "0.1.10" - resolved "https://registry.yarnpkg.com/mongodb-download-url/-/mongodb-download-url-0.1.10.tgz#a7047eec95001de9f4df39f7e4030dc87eb3f806" - dependencies: - async "^1.5.0" - debug "^2.2.0" - lodash.defaults "^4.0.0" - minimist "^1.2.0" - mongodb-version-list "^0.0.3" - request "^2.65.0" - semver "^5.0.3" - -mongodb-topology-manager@1.0.x: - version "1.0.13" - resolved "https://registry.yarnpkg.com/mongodb-topology-manager/-/mongodb-topology-manager-1.0.13.tgz#053577386c587d2cfcc1cc45a0567b93b0f8710b" - dependencies: - babel-core "^6.25.0" - babel-polyfill "^6.23.0" - bluebird "^3.5.0" - co "^4.6.0" - kerberos "^0.0.23" - mkdirp "^0.5.1" - mongodb-core "^2.1.12" - rimraf "^2.6.1" - -mongodb-version-list@0.0.3, mongodb-version-list@^0.0.3: - version "0.0.3" - resolved "https://registry.yarnpkg.com/mongodb-version-list/-/mongodb-version-list-0.0.3.tgz#bbb261861f041fcfc5bc72b5fe2681788bd52cef" - dependencies: - cheerio "^0.19.0" - debug "^2.2.0" - downcache "0.0.8" - fs-extra "^0.22.1" - minimist "^1.1.1" - semver "^5.0.1" - -mongodb-version-manager@christkv/mongodb-version-manager#master: - version "1.0.7" - resolved "https://codeload.github.com/christkv/mongodb-version-manager/tar.gz/3ea7c20925d6a0b3a9243d341d3c69abf95e66b6" - dependencies: - ampersand-state "^5.0.1" - async "~1.5.0" - chalk "^1.1.1" - debug "~2.2.0" - docopt "~0.6.2" - figures "^1.4.0" - fs-extra "~0.30.0" - get-mongodb-version "0.0.1" - lodash.defaults "^3.1.2" - lodash.difference "^4.1.1" - mongodb-download-url "^0.1.10" - mongodb-version-list "0.0.3" - nugget "^2.0.0" - semver "~5.1.0" - tar "~2.2.1" - tildify "~1.2.0" - untildify "~2.1.0" - unzip "^0.1.11" - -mongodb@^2.0.39: - version "2.2.32" - resolved "https://registry.yarnpkg.com/mongodb/-/mongodb-2.2.32.tgz#620eaaa1995fb457c4ef7054e5f560257a697e58" - dependencies: - es6-promise "3.2.1" - mongodb-core "2.1.16" - readable-stream "2.2.7" - -ms@0.7.1: - version "0.7.1" - resolved "https://registry.yarnpkg.com/ms/-/ms-0.7.1.tgz#9cd13c03adbff25b65effde7ce864ee952017098" - -ms@2.0.0: - version "2.0.0" - resolved "https://registry.yarnpkg.com/ms/-/ms-2.0.0.tgz#5608aeadfc00be6c2901df5f9861788de0d597c8" - -nan@~2.5.1: - version "2.5.1" - resolved "https://registry.yarnpkg.com/nan/-/nan-2.5.1.tgz#d5b01691253326a97a2bbee9e61c55d8d60351e2" - -natives@^1.1.0: - version "1.1.0" - resolved "https://registry.yarnpkg.com/natives/-/natives-1.1.0.tgz#e9ff841418a6b2ec7a495e939984f78f163e6e31" - -nopt@3.x: - version "3.0.6" - resolved "https://registry.yarnpkg.com/nopt/-/nopt-3.0.6.tgz#c6465dbf08abcd4db359317f79ac68a646b28ff9" - dependencies: - abbrev "1" - -normalize-package-data@^2.3.2, normalize-package-data@^2.3.4: - version "2.4.0" - resolved "https://registry.yarnpkg.com/normalize-package-data/-/normalize-package-data-2.4.0.tgz#12f95a307d58352075a04907b84ac8be98ac012f" - dependencies: - hosted-git-info "^2.1.4" - is-builtin-module "^1.0.0" - semver "2 || 3 || 4 || 5" - validate-npm-package-license "^3.0.1" - -npmlog@1.0.0: - version "1.0.0" - resolved "https://registry.yarnpkg.com/npmlog/-/npmlog-1.0.0.tgz#ed2f290b60316887c39e0da9f09f8d13847cef0f" - dependencies: - ansi "~0.3.0" - are-we-there-yet "~1.0.0" - gauge "~1.0.2" - -nth-check@~1.0.0: - version "1.0.1" - resolved "https://registry.yarnpkg.com/nth-check/-/nth-check-1.0.1.tgz#9929acdf628fc2c41098deab82ac580cf149aae4" - dependencies: - boolbase "~1.0.0" - -nugget@^2.0.0: - version "2.0.1" - resolved "https://registry.yarnpkg.com/nugget/-/nugget-2.0.1.tgz#201095a487e1ad36081b3432fa3cada4f8d071b0" - dependencies: - debug "^2.1.3" - minimist "^1.1.0" - pretty-bytes "^1.0.2" - progress-stream "^1.1.0" - request "^2.45.0" - single-line-log "^1.1.2" - throttleit "0.0.2" - -number-is-nan@^1.0.0: - version "1.0.1" - resolved "https://registry.yarnpkg.com/number-is-nan/-/number-is-nan-1.0.1.tgz#097b602b53422a522c1afb8790318336941a011d" - -nyc@^5.5.0: - version "5.6.0" - resolved "https://registry.yarnpkg.com/nyc/-/nyc-5.6.0.tgz#0eb394d16f3ef9ff1b440fd93b1a7ab530092754" - dependencies: - append-transform "^0.2.0" - arrify "^1.0.1" - caching-transform "^1.0.0" - convert-source-map "^1.1.2" - find-cache-dir "^0.1.1" - foreground-child "^1.3.5" - glob "^6.0.2" - istanbul "^0.4.1" - md5-hex "^1.2.0" - micromatch "~2.1.6" - mkdirp "^0.5.0" - pkg-up "^1.0.0" - read-pkg "^1.1.0" - resolve-from "^2.0.0" - rimraf "^2.5.0" - signal-exit "^2.1.1" - source-map "^0.5.3" - spawn-wrap "^1.1.1" - strip-bom "^2.0.0" - yargs "^3.15.0" - -oauth-sign@~0.8.1, oauth-sign@~0.8.2: - version "0.8.2" - resolved "https://registry.yarnpkg.com/oauth-sign/-/oauth-sign-0.8.2.tgz#46a6ab7f0aead8deae9ec0565780b7d4efeb9d43" - -object-assign@^4.0.1, object-assign@^4.1.0: - version "4.1.1" - resolved "https://registry.yarnpkg.com/object-assign/-/object-assign-4.1.1.tgz#2109adc7965887cfc05cbbd442cac8bfbb360863" - -object-keys@~0.4.0: - version "0.4.0" - resolved "https://registry.yarnpkg.com/object-keys/-/object-keys-0.4.0.tgz#28a6aae7428dd2c3a92f3d95f21335dd204e0336" - -object.omit@^0.2.1: - version "0.2.1" - resolved "https://registry.yarnpkg.com/object.omit/-/object.omit-0.2.1.tgz#ca9af6631df6883fe61bae74df82a4fbc9df2e92" - dependencies: - for-own "^0.1.1" - isobject "^0.2.0" - -once@1.x, once@^1.3.0: - version "1.4.0" - resolved "https://registry.yarnpkg.com/once/-/once-1.4.0.tgz#583b1aa775961d4b113ac17d9c50baef9dd76bd1" - dependencies: - wrappy "1" - -optimist@^0.6.1, optimist@latest: - version "0.6.1" - resolved "https://registry.yarnpkg.com/optimist/-/optimist-0.6.1.tgz#da3ea74686fa21a19a111c326e90eb15a0196686" - dependencies: - minimist "~0.0.1" - wordwrap "~0.0.2" - -optimist@~0.3, optimist@~0.3.5: - version "0.3.7" - resolved "https://registry.yarnpkg.com/optimist/-/optimist-0.3.7.tgz#c90941ad59e4273328923074d2cf2e7cbc6ec0d9" - dependencies: - wordwrap "~0.0.2" - -optionator@^0.8.1: - version "0.8.2" - resolved "https://registry.yarnpkg.com/optionator/-/optionator-0.8.2.tgz#364c5e409d3f4d6301d6c0b4c05bba50180aeb64" - dependencies: - deep-is "~0.1.3" - fast-levenshtein "~2.0.4" - levn "~0.3.0" - prelude-ls "~1.1.2" - type-check "~0.3.2" - wordwrap "~1.0.0" - -os-homedir@^1.0.0, os-homedir@^1.0.1: - version "1.0.2" - resolved "https://registry.yarnpkg.com/os-homedir/-/os-homedir-1.0.2.tgz#ffbc4988336e0e833de0c168c7ef152121aa7fb3" - -os-locale@^1.4.0: - version "1.4.0" - resolved "https://registry.yarnpkg.com/os-locale/-/os-locale-1.4.0.tgz#20f9f17ae29ed345e8bde583b13d2009803c14d9" - dependencies: - lcid "^1.0.0" - -os-tmpdir@^1.0.1: - version "1.0.2" - resolved "https://registry.yarnpkg.com/os-tmpdir/-/os-tmpdir-1.0.2.tgz#bbe67406c79aa85c5cfec766fe5734555dfa1274" - -"over@>= 0.0.5 < 1": - version "0.0.5" - resolved "https://registry.yarnpkg.com/over/-/over-0.0.5.tgz#f29852e70fd7e25f360e013a8ec44c82aedb5708" - -parse-glob@^3.0.0: - version "3.0.4" - resolved "https://registry.yarnpkg.com/parse-glob/-/parse-glob-3.0.4.tgz#b2c376cfb11f35513badd173ef0bb6e3a388391c" - dependencies: - glob-base "^0.3.0" - is-dotfile "^1.0.0" - is-extglob "^1.0.0" - is-glob "^2.0.0" - -parse-json@^2.2.0: - version "2.2.0" - resolved "https://registry.yarnpkg.com/parse-json/-/parse-json-2.2.0.tgz#f480f40434ef80741f8469099f8dea18f55a4dc9" - dependencies: - error-ex "^1.2.0" - -path-exists@^2.0.0: - version "2.1.0" - resolved "https://registry.yarnpkg.com/path-exists/-/path-exists-2.1.0.tgz#0feb6c64f0fc518d9a754dd5efb62c7022761f4b" - dependencies: - pinkie-promise "^2.0.0" - -path-is-absolute@^1.0.0, path-is-absolute@^1.0.1: - version "1.0.1" - resolved "https://registry.yarnpkg.com/path-is-absolute/-/path-is-absolute-1.0.1.tgz#174b9268735534ffbc7ace6bf53a5a9e1b5c5f5f" - -path-type@^1.0.0: - version "1.1.0" - resolved "https://registry.yarnpkg.com/path-type/-/path-type-1.1.0.tgz#59c44f7ee491da704da415da5a4070ba4f8fe441" - dependencies: - graceful-fs "^4.1.2" - pify "^2.0.0" - pinkie-promise "^2.0.0" - -performance-now@^2.1.0: - version "2.1.0" - resolved "https://registry.yarnpkg.com/performance-now/-/performance-now-2.1.0.tgz#6309f4e0e5fa913ec1c69307ae364b4b377c9e7b" - -pify@^2.0.0: - version "2.3.0" - resolved "https://registry.yarnpkg.com/pify/-/pify-2.3.0.tgz#ed141a6ac043a849ea588498e7dca8b15330e90c" - -pinkie-promise@^2.0.0: - version "2.0.1" - resolved "https://registry.yarnpkg.com/pinkie-promise/-/pinkie-promise-2.0.1.tgz#2135d6dfa7a358c069ac9b178776288228450ffa" - dependencies: - pinkie "^2.0.0" - -pinkie@^2.0.0: - version "2.0.4" - resolved "https://registry.yarnpkg.com/pinkie/-/pinkie-2.0.4.tgz#72556b80cfa0d48a974e80e77248e80ed4f7f870" - -pkg-dir@^1.0.0: - version "1.0.0" - resolved "https://registry.yarnpkg.com/pkg-dir/-/pkg-dir-1.0.0.tgz#7a4b508a8d5bb2d629d447056ff4e9c9314cf3d4" - dependencies: - find-up "^1.0.0" - -pkg-up@^1.0.0: - version "1.0.0" - resolved "https://registry.yarnpkg.com/pkg-up/-/pkg-up-1.0.0.tgz#3e08fb461525c4421624a33b9f7e6d0af5b05a26" - dependencies: - find-up "^1.0.0" - -prelude-ls@~1.1.2: - version "1.1.2" - resolved "https://registry.yarnpkg.com/prelude-ls/-/prelude-ls-1.1.2.tgz#21932a549f5e52ffd9a827f570e04be62a97da54" - -preserve@^0.2.0: - version "0.2.0" - resolved "https://registry.yarnpkg.com/preserve/-/preserve-0.2.0.tgz#815ed1f6ebc65926f865b310c0713bcb3315ce4b" - -pretty-bytes@^1.0.2: - version "1.0.4" - resolved "https://registry.yarnpkg.com/pretty-bytes/-/pretty-bytes-1.0.4.tgz#0a22e8210609ad35542f8c8d5d2159aff0751c84" - dependencies: - get-stdin "^4.0.1" - meow "^3.1.0" - -private@^0.1.7: - version "0.1.7" - resolved "https://registry.yarnpkg.com/private/-/private-0.1.7.tgz#68ce5e8a1ef0a23bb570cc28537b5332aba63ef1" - -process-nextick-args@~1.0.6: - version "1.0.7" - resolved "https://registry.yarnpkg.com/process-nextick-args/-/process-nextick-args-1.0.7.tgz#150e20b756590ad3f91093f25a4f2ad8bff30ba3" - -progress-stream@^1.1.0: - version "1.2.0" - resolved "https://registry.yarnpkg.com/progress-stream/-/progress-stream-1.2.0.tgz#2cd3cfea33ba3a89c9c121ec3347abe9ab125f77" - dependencies: - speedometer "~0.1.2" - through2 "~0.2.3" - -pseudomap@^1.0.2: - version "1.0.2" - resolved "https://registry.yarnpkg.com/pseudomap/-/pseudomap-1.0.2.tgz#f052a28da70e618917ef0a8ac34c1ae5a68286b3" - -"pullstream@>= 0.4.1 < 1": - version "0.4.1" - resolved "https://registry.yarnpkg.com/pullstream/-/pullstream-0.4.1.tgz#d6fb3bf5aed697e831150eb1002c25a3f8ae1314" - dependencies: - over ">= 0.0.5 < 1" - readable-stream "~1.0.31" - setimmediate ">= 1.0.2 < 2" - slice-stream ">= 1.0.0 < 2" - -punycode@^1.4.1: - version "1.4.1" - resolved "https://registry.yarnpkg.com/punycode/-/punycode-1.4.1.tgz#c0d5a63b2718800ad8e1eb0fa5269c84dd41845e" - -qs@~6.3.0: - version "6.3.2" - resolved "https://registry.yarnpkg.com/qs/-/qs-6.3.2.tgz#e75bd5f6e268122a2a0e0bda630b2550c166502c" - -qs@~6.5.1: - version "6.5.1" - resolved "https://registry.yarnpkg.com/qs/-/qs-6.5.1.tgz#349cdf6eef89ec45c12d7d5eb3fc0c870343a6d8" - -randomatic@^1.1.3: - version "1.1.7" - resolved "https://registry.yarnpkg.com/randomatic/-/randomatic-1.1.7.tgz#c7abe9cc8b87c0baa876b19fde83fd464797e38c" - dependencies: - is-number "^3.0.0" - kind-of "^4.0.0" - -read-pkg-up@^1.0.1: - version "1.0.1" - resolved "https://registry.yarnpkg.com/read-pkg-up/-/read-pkg-up-1.0.1.tgz#9d63c13276c065918d57f002a57f40a1b643fb02" - dependencies: - find-up "^1.0.0" - read-pkg "^1.0.0" - -read-pkg@^1.0.0, read-pkg@^1.1.0: - version "1.1.0" - resolved "https://registry.yarnpkg.com/read-pkg/-/read-pkg-1.1.0.tgz#f5ffaa5ecd29cb31c0474bca7d756b6bb29e3f28" - dependencies: - load-json-file "^1.0.0" - normalize-package-data "^2.3.2" - path-type "^1.0.0" - -readable-stream@1.1: - version "1.1.13" - resolved "https://registry.yarnpkg.com/readable-stream/-/readable-stream-1.1.13.tgz#f6eef764f514c89e2b9e23146a75ba106756d23e" - dependencies: - core-util-is "~1.0.0" - inherits "~2.0.1" - isarray "0.0.1" - string_decoder "~0.10.x" - -readable-stream@2.2.7: - version "2.2.7" - resolved "https://registry.yarnpkg.com/readable-stream/-/readable-stream-2.2.7.tgz#07057acbe2467b22042d36f98c5ad507054e95b1" - dependencies: - buffer-shims "~1.0.0" - core-util-is "~1.0.0" - inherits "~2.0.1" - isarray "~1.0.0" - process-nextick-args "~1.0.6" - string_decoder "~1.0.0" - util-deprecate "~1.0.1" - -"readable-stream@>=1.0.33-1 <1.1.0-0", readable-stream@~1.0.0, readable-stream@~1.0.31: - version "1.0.34" - resolved "https://registry.yarnpkg.com/readable-stream/-/readable-stream-1.0.34.tgz#125820e34bc842d2f2aaafafe4c2916ee32c157c" - dependencies: - core-util-is "~1.0.0" - inherits "~2.0.1" - isarray "0.0.1" - string_decoder "~0.10.x" - -"readable-stream@^2.0.0 || ^1.1.13": - version "2.3.3" - resolved "https://registry.yarnpkg.com/readable-stream/-/readable-stream-2.3.3.tgz#368f2512d79f9d46fdfc71349ae7878bbc1eb95c" - dependencies: - core-util-is "~1.0.0" - inherits "~2.0.3" - isarray "~1.0.0" - process-nextick-args "~1.0.6" - safe-buffer "~5.1.1" - string_decoder "~1.0.3" - util-deprecate "~1.0.1" - -readable-stream@~1.1.9: - version "1.1.14" - resolved "https://registry.yarnpkg.com/readable-stream/-/readable-stream-1.1.14.tgz#7cf4c54ef648e3813084c636dd2079e166c081d9" - dependencies: - core-util-is "~1.0.0" - inherits "~2.0.1" - isarray "0.0.1" - string_decoder "~0.10.x" - -redent@^1.0.0: - version "1.0.0" - resolved "https://registry.yarnpkg.com/redent/-/redent-1.0.0.tgz#cf916ab1fd5f1f16dfb20822dd6ec7f730c2afde" - dependencies: - indent-string "^2.1.0" - strip-indent "^1.0.1" - -regenerator-runtime@^0.10.5: - version "0.10.5" - resolved "https://registry.yarnpkg.com/regenerator-runtime/-/regenerator-runtime-0.10.5.tgz#336c3efc1220adcedda2c9fab67b5a7955a33658" - -regenerator-runtime@^0.11.0: - version "0.11.0" - resolved "https://registry.yarnpkg.com/regenerator-runtime/-/regenerator-runtime-0.11.0.tgz#7e54fe5b5ccd5d6624ea6255c3473be090b802e1" - -regex-cache@^0.4.0: - version "0.4.4" - resolved "https://registry.yarnpkg.com/regex-cache/-/regex-cache-0.4.4.tgz#75bdc58a2a1496cec48a12835bc54c8d562336dd" - dependencies: - is-equal-shallow "^0.1.3" - -repeat-element@^1.1.2: - version "1.1.2" - resolved "https://registry.yarnpkg.com/repeat-element/-/repeat-element-1.1.2.tgz#ef089a178d1483baae4d93eb98b4f9e4e11d990a" - -repeat-string@^1.5.2: - version "1.6.1" - resolved "https://registry.yarnpkg.com/repeat-string/-/repeat-string-1.6.1.tgz#8dcae470e1c88abc2d600fff4a776286da75e637" - -repeating@^2.0.0: - version "2.0.1" - resolved "https://registry.yarnpkg.com/repeating/-/repeating-2.0.1.tgz#5214c53a926d3552707527fbab415dbc08d06dda" - dependencies: - is-finite "^1.0.0" - -request@2.79.0: - version "2.79.0" - resolved "https://registry.yarnpkg.com/request/-/request-2.79.0.tgz#4dfe5bf6be8b8cdc37fcf93e04b65577722710de" - dependencies: - aws-sign2 "~0.6.0" - aws4 "^1.2.1" - caseless "~0.11.0" - combined-stream "~1.0.5" - extend "~3.0.0" - forever-agent "~0.6.1" - form-data "~2.1.1" - har-validator "~2.0.6" - hawk "~3.1.3" - http-signature "~1.1.0" - is-typedarray "~1.0.0" - isstream "~0.1.2" - json-stringify-safe "~5.0.1" - mime-types "~2.1.7" - oauth-sign "~0.8.1" - qs "~6.3.0" - stringstream "~0.0.4" - tough-cookie "~2.3.0" - tunnel-agent "~0.4.1" - uuid "^3.0.0" - -request@^2.34.0, request@^2.45.0, request@^2.65.0: - version "2.83.0" - resolved "https://registry.yarnpkg.com/request/-/request-2.83.0.tgz#ca0b65da02ed62935887808e6f510381034e3356" - dependencies: - aws-sign2 "~0.7.0" - aws4 "^1.6.0" - caseless "~0.12.0" - combined-stream "~1.0.5" - extend "~3.0.1" - forever-agent "~0.6.1" - form-data "~2.3.1" - har-validator "~5.0.3" - hawk "~6.0.2" - http-signature "~1.2.0" - is-typedarray "~1.0.0" - isstream "~0.1.2" - json-stringify-safe "~5.0.1" - mime-types "~2.1.17" - oauth-sign "~0.8.2" - performance-now "^2.1.0" - qs "~6.5.1" - safe-buffer "^5.1.1" - stringstream "~0.0.5" - tough-cookie "~2.3.3" - tunnel-agent "^0.6.0" - uuid "^3.1.0" - -require_optional@~1.0.0: - version "1.0.1" - resolved "https://registry.yarnpkg.com/require_optional/-/require_optional-1.0.1.tgz#4cf35a4247f64ca3df8c2ef208cc494b1ca8fc2e" - dependencies: - resolve-from "^2.0.0" - semver "^5.1.0" - -requizzle@~0.1.1: - version "0.1.1" - resolved "https://registry.yarnpkg.com/requizzle/-/requizzle-0.1.1.tgz#bad811e66c59251fe97e084295c33bcdbcf8e0ba" - dependencies: - underscore "~1.6.0" - -resolve-from@^2.0.0: - version "2.0.0" - resolved "https://registry.yarnpkg.com/resolve-from/-/resolve-from-2.0.0.tgz#9480ab20e94ffa1d9e80a804c7ea147611966b57" - -resolve@1.1.x: - version "1.1.7" - resolved "https://registry.yarnpkg.com/resolve/-/resolve-1.1.7.tgz#203114d82ad2c5ed9e8e0411b3932875e889e97b" - -right-align@^0.1.1: - version "0.1.3" - resolved "https://registry.yarnpkg.com/right-align/-/right-align-0.1.3.tgz#61339b722fe6a3515689210d24e14c96148613ef" - dependencies: - align-text "^0.1.1" - -rimraf@2, rimraf@^2.2.8, rimraf@^2.3.3, rimraf@^2.5.0, rimraf@^2.6.1: - version "2.6.2" - resolved "https://registry.yarnpkg.com/rimraf/-/rimraf-2.6.2.tgz#2ed8150d24a16ea8651e6d6ef0f47c4158ce7a36" - dependencies: - glob "^7.0.5" - -rimraf@2.2.6: - version "2.2.6" - resolved "https://registry.yarnpkg.com/rimraf/-/rimraf-2.2.6.tgz#c59597569b14d956ad29cacc42bdddf5f0ea4f4c" - -safe-buffer@^5.0.1, safe-buffer@^5.1.1, safe-buffer@~5.1.0, safe-buffer@~5.1.1: - version "5.1.1" - resolved "https://registry.yarnpkg.com/safe-buffer/-/safe-buffer-5.1.1.tgz#893312af69b2123def71f57889001671eeb2c853" - -"semver@2 || 3 || 4 || 5", semver@^5.0.1, semver@^5.0.3, semver@^5.1.0: - version "5.4.1" - resolved "https://registry.yarnpkg.com/semver/-/semver-5.4.1.tgz#e059c09d8571f0540823733433505d3a2f00b18e" - -semver@4.1.0: - version "4.1.0" - resolved "https://registry.yarnpkg.com/semver/-/semver-4.1.0.tgz#bc80a9ff68532814362cc3cfda3c7b75ed9c321c" - -semver@~5.1.0: - version "5.1.1" - resolved "https://registry.yarnpkg.com/semver/-/semver-5.1.1.tgz#a3292a373e6f3e0798da0b20641b9a9c5bc47e19" - -"setimmediate@>= 1.0.1 < 2", "setimmediate@>= 1.0.2 < 2": - version "1.0.5" - resolved "https://registry.yarnpkg.com/setimmediate/-/setimmediate-1.0.5.tgz#290cbb232e306942d7d7ea9b83732ab7856f8285" - -signal-exit@^2.1.1: - version "2.1.2" - resolved "https://registry.yarnpkg.com/signal-exit/-/signal-exit-2.1.2.tgz#375879b1f92ebc3b334480d038dc546a6d558564" - -signal-exit@^3.0.0, signal-exit@^3.0.2: - version "3.0.2" - resolved "https://registry.yarnpkg.com/signal-exit/-/signal-exit-3.0.2.tgz#b5fdc08f1287ea1178628e415e25132b73646c6d" - -single-line-log@^1.1.2: - version "1.1.2" - resolved "https://registry.yarnpkg.com/single-line-log/-/single-line-log-1.1.2.tgz#c2f83f273a3e1a16edb0995661da0ed5ef033364" - dependencies: - string-width "^1.0.1" - -slash@^1.0.0: - version "1.0.0" - resolved "https://registry.yarnpkg.com/slash/-/slash-1.0.0.tgz#c41f2f6c39fc16d1cd17ad4b5d896114ae470d55" - -"slice-stream@>= 1.0.0 < 2": - version "1.0.0" - resolved "https://registry.yarnpkg.com/slice-stream/-/slice-stream-1.0.0.tgz#5b33bd66f013b1a7f86460b03d463dec39ad3ea0" - dependencies: - readable-stream "~1.0.31" - -slide@^1.1.5: - version "1.1.6" - resolved "https://registry.yarnpkg.com/slide/-/slide-1.1.6.tgz#56eb027d65b4d2dce6cb2e2d32c4d4afc9e1d707" - -sntp@1.x.x: - version "1.0.9" - resolved "https://registry.yarnpkg.com/sntp/-/sntp-1.0.9.tgz#6541184cc90aeea6c6e7b35e2659082443c66198" - dependencies: - hoek "2.x.x" - -sntp@2.x.x: - version "2.0.2" - resolved "https://registry.yarnpkg.com/sntp/-/sntp-2.0.2.tgz#5064110f0af85f7cfdb7d6b67a40028ce52b4b2b" - dependencies: - hoek "4.x.x" - -source-map-support@^0.4.15: - version "0.4.18" - resolved "https://registry.yarnpkg.com/source-map-support/-/source-map-support-0.4.18.tgz#0286a6de8be42641338594e97ccea75f0a2c585f" - dependencies: - source-map "^0.5.6" - -source-map@^0.4.4: - version "0.4.4" - resolved "https://registry.yarnpkg.com/source-map/-/source-map-0.4.4.tgz#eba4f5da9c0dc999de68032d8b4f76173652036b" - dependencies: - amdefine ">=0.0.4" - -source-map@^0.5.3, source-map@^0.5.6, source-map@~0.5.1: - version "0.5.7" - resolved "https://registry.yarnpkg.com/source-map/-/source-map-0.5.7.tgz#8a039d2d1021d22d1ea14c80d8ea468ba2ef3fcc" - -source-map@~0.1.30, source-map@~0.1.7: - version "0.1.43" - resolved "https://registry.yarnpkg.com/source-map/-/source-map-0.1.43.tgz#c24bc146ca517c1471f5dacbe2571b2b7f9e3346" - dependencies: - amdefine ">=0.0.4" - -source-map@~0.2.0: - version "0.2.0" - resolved "https://registry.yarnpkg.com/source-map/-/source-map-0.2.0.tgz#dab73fbcfc2ba819b4de03bd6f6eaa48164b3f9d" - dependencies: - amdefine ">=0.0.4" - -spawn-wrap@^1.1.1: - version "1.3.8" - resolved "https://registry.yarnpkg.com/spawn-wrap/-/spawn-wrap-1.3.8.tgz#fa2a79b990cbb0bb0018dca6748d88367b19ec31" - dependencies: - foreground-child "^1.5.6" - mkdirp "^0.5.0" - os-homedir "^1.0.1" - rimraf "^2.3.3" - signal-exit "^3.0.2" - which "^1.2.4" - -spdx-correct@~1.0.0: - version "1.0.2" - resolved "https://registry.yarnpkg.com/spdx-correct/-/spdx-correct-1.0.2.tgz#4b3073d933ff51f3912f03ac5519498a4150db40" - dependencies: - spdx-license-ids "^1.0.2" - -spdx-expression-parse@~1.0.0: - version "1.0.4" - resolved "https://registry.yarnpkg.com/spdx-expression-parse/-/spdx-expression-parse-1.0.4.tgz#9bdf2f20e1f40ed447fbe273266191fced51626c" - -spdx-license-ids@^1.0.2: - version "1.2.2" - resolved "https://registry.yarnpkg.com/spdx-license-ids/-/spdx-license-ids-1.2.2.tgz#c9df7a3424594ade6bd11900d596696dc06bac57" - -speedometer@~0.1.2: - version "0.1.4" - resolved "https://registry.yarnpkg.com/speedometer/-/speedometer-0.1.4.tgz#9876dbd2a169d3115402d48e6ea6329c8816a50d" - -sprintf-js@~1.0.2: - version "1.0.3" - resolved "https://registry.yarnpkg.com/sprintf-js/-/sprintf-js-1.0.3.tgz#04e6926f662895354f3dd015203633b857297e2c" - -sshpk@^1.7.0: - version "1.13.1" - resolved "https://registry.yarnpkg.com/sshpk/-/sshpk-1.13.1.tgz#512df6da6287144316dc4c18fe1cf1d940739be3" - dependencies: - asn1 "~0.2.3" - assert-plus "^1.0.0" - dashdash "^1.12.0" - getpass "^0.1.1" - optionalDependencies: - bcrypt-pbkdf "^1.0.0" - ecc-jsbn "~0.1.1" - jsbn "~0.1.0" - tweetnacl "~0.14.0" - -string-width@^1.0.1: - version "1.0.2" - resolved "https://registry.yarnpkg.com/string-width/-/string-width-1.0.2.tgz#118bdf5b8cdc51a2a7e70d211e07e2b0b9b107d3" - dependencies: - code-point-at "^1.0.0" - is-fullwidth-code-point "^1.0.0" - strip-ansi "^3.0.0" - -string_decoder@~0.10.x: - version "0.10.31" - resolved "https://registry.yarnpkg.com/string_decoder/-/string_decoder-0.10.31.tgz#62e203bc41766c6c28c9fc84301dab1c5310fa94" - -string_decoder@~1.0.0, string_decoder@~1.0.3: - version "1.0.3" - resolved "https://registry.yarnpkg.com/string_decoder/-/string_decoder-1.0.3.tgz#0fc67d7c141825de94282dd536bec6b9bce860ab" - dependencies: - safe-buffer "~5.1.0" - -stringstream@~0.0.4, stringstream@~0.0.5: - version "0.0.5" - resolved "https://registry.yarnpkg.com/stringstream/-/stringstream-0.0.5.tgz#4e484cd4de5a0bbbee18e46307710a8a81621878" - -strip-ansi@^3.0.0, strip-ansi@^3.0.1: - version "3.0.1" - resolved "https://registry.yarnpkg.com/strip-ansi/-/strip-ansi-3.0.1.tgz#6a385fb8853d952d5ff05d0e8aaf94278dc63dcf" - dependencies: - ansi-regex "^2.0.0" - -strip-bom@^2.0.0: - version "2.0.0" - resolved "https://registry.yarnpkg.com/strip-bom/-/strip-bom-2.0.0.tgz#6219a85616520491f35788bdbf1447a99c7e6b0e" - dependencies: - is-utf8 "^0.2.0" - -strip-indent@^1.0.1: - version "1.0.1" - resolved "https://registry.yarnpkg.com/strip-indent/-/strip-indent-1.0.1.tgz#0c7962a6adefa7bbd4ac366460a638552ae1a0a2" - dependencies: - get-stdin "^4.0.1" - -strip-json-comments@~0.1.3: - version "0.1.3" - resolved "https://registry.yarnpkg.com/strip-json-comments/-/strip-json-comments-0.1.3.tgz#164c64e370a8a3cc00c9e01b539e569823f0ee54" - -supports-color@^2.0.0: - version "2.0.0" - resolved "https://registry.yarnpkg.com/supports-color/-/supports-color-2.0.0.tgz#535d045ce6b6363fa40117084629995e9df324c7" - -supports-color@^3.1.0: - version "3.2.3" - resolved "https://registry.yarnpkg.com/supports-color/-/supports-color-3.2.3.tgz#65ac0504b3954171d8a64946b2ae3cbb8a5f54f6" - dependencies: - has-flag "^1.0.0" - -"taffydb@https://github.com/hegemonic/taffydb/tarball/master": - version "2.6.2" - resolved "https://github.com/hegemonic/taffydb/tarball/master#a4ee71882143901531fc170f6d22af053565a0c5" - -tar@~2.2.1: - version "2.2.1" - resolved "https://registry.yarnpkg.com/tar/-/tar-2.2.1.tgz#8e4d2a256c0e2185c6b18ad694aec968b83cb1d1" - dependencies: - block-stream "*" - fstream "^1.0.2" - inherits "2" - -throttleit@0.0.2: - version "0.0.2" - resolved "https://registry.yarnpkg.com/throttleit/-/throttleit-0.0.2.tgz#cfedf88e60c00dd9697b61fdd2a8343a9b680eaf" - -through2@^0.6.3: - version "0.6.5" - resolved "https://registry.yarnpkg.com/through2/-/through2-0.6.5.tgz#41ab9c67b29d57209071410e1d7a7a968cd3ad48" - dependencies: - readable-stream ">=1.0.33-1 <1.1.0-0" - xtend ">=4.0.0 <4.1.0-0" - -through2@~0.2.3: - version "0.2.3" - resolved "https://registry.yarnpkg.com/through2/-/through2-0.2.3.tgz#eb3284da4ea311b6cc8ace3653748a52abf25a3f" - dependencies: - readable-stream "~1.1.9" - xtend "~2.1.1" - -tildify@~1.2.0: - version "1.2.0" - resolved "https://registry.yarnpkg.com/tildify/-/tildify-1.2.0.tgz#dcec03f55dca9b7aa3e5b04f21817eb56e63588a" - dependencies: - os-homedir "^1.0.0" - -to-fast-properties@^1.0.3: - version "1.0.3" - resolved "https://registry.yarnpkg.com/to-fast-properties/-/to-fast-properties-1.0.3.tgz#b83571fa4d8c25b82e231b06e3a3055de4ca1a47" - -tough-cookie@~2.3.0, tough-cookie@~2.3.3: - version "2.3.3" - resolved "https://registry.yarnpkg.com/tough-cookie/-/tough-cookie-2.3.3.tgz#0b618a5565b6dea90bf3425d04d55edc475a7561" - dependencies: - punycode "^1.4.1" - -"traverse@>=0.3.0 <0.4": - version "0.3.9" - resolved "https://registry.yarnpkg.com/traverse/-/traverse-0.3.9.tgz#717b8f220cc0bb7b44e40514c22b2e8bbc70d8b9" - -trim-newlines@^1.0.0: - version "1.0.0" - resolved "https://registry.yarnpkg.com/trim-newlines/-/trim-newlines-1.0.0.tgz#5887966bb582a4503a41eb524f7d35011815a613" - -trim-right@^1.0.1: - version "1.0.1" - resolved "https://registry.yarnpkg.com/trim-right/-/trim-right-1.0.1.tgz#cb2e1203067e0c8de1f614094b9fe45704ea6003" - -tunnel-agent@^0.6.0: - version "0.6.0" - resolved "https://registry.yarnpkg.com/tunnel-agent/-/tunnel-agent-0.6.0.tgz#27a5dea06b36b04a0a9966774b290868f0fc40fd" - dependencies: - safe-buffer "^5.0.1" - -tunnel-agent@~0.4.1: - version "0.4.3" - resolved "https://registry.yarnpkg.com/tunnel-agent/-/tunnel-agent-0.4.3.tgz#6373db76909fe570e08d73583365ed828a74eeeb" - -tweetnacl@^0.14.3, tweetnacl@~0.14.0: - version "0.14.5" - resolved "https://registry.yarnpkg.com/tweetnacl/-/tweetnacl-0.14.5.tgz#5ae68177f192d4456269d108afa93ff8743f4f64" - -type-check@~0.3.2: - version "0.3.2" - resolved "https://registry.yarnpkg.com/type-check/-/type-check-0.3.2.tgz#5884cab512cf1d355e3fb784f30804b2b520db72" - dependencies: - prelude-ls "~1.1.2" - -uglify-js@^2.6: - version "2.8.29" - resolved "https://registry.yarnpkg.com/uglify-js/-/uglify-js-2.8.29.tgz#29c5733148057bb4e1f75df35b7a9cb72e6a59dd" - dependencies: - source-map "~0.5.1" - yargs "~3.10.0" - optionalDependencies: - uglify-to-browserify "~1.0.0" - -uglify-js@~2.3: - version "2.3.6" - resolved "https://registry.yarnpkg.com/uglify-js/-/uglify-js-2.3.6.tgz#fa0984770b428b7a9b2a8058f46355d14fef211a" - dependencies: - async "~0.2.6" - optimist "~0.3.5" - source-map "~0.1.7" - -uglify-to-browserify@~1.0.0: - version "1.0.2" - resolved "https://registry.yarnpkg.com/uglify-to-browserify/-/uglify-to-browserify-1.0.2.tgz#6e0924d6bda6b5afe349e39a6d632850a0f882b7" - -underscore-contrib@~0.3.0: - version "0.3.0" - resolved "https://registry.yarnpkg.com/underscore-contrib/-/underscore-contrib-0.3.0.tgz#665b66c24783f8fa2b18c9f8cbb0e2c7d48c26c7" - dependencies: - underscore "1.6.0" - -underscore@1.6.0, underscore@~1.6.0: - version "1.6.0" - resolved "https://registry.yarnpkg.com/underscore/-/underscore-1.6.0.tgz#8b38b10cacdef63337b8b24e4ff86d45aea529a8" - -untildify@~2.1.0: - version "2.1.0" - resolved "https://registry.yarnpkg.com/untildify/-/untildify-2.1.0.tgz#17eb2807987f76952e9c0485fc311d06a826a2e0" - dependencies: - os-homedir "^1.0.0" - -unzip@^0.1.11: - version "0.1.11" - resolved "https://registry.yarnpkg.com/unzip/-/unzip-0.1.11.tgz#89749c63b058d7d90d619f86b98aa1535d3b97f0" - dependencies: - binary ">= 0.3.0 < 1" - fstream ">= 0.1.30 < 1" - match-stream ">= 0.0.2 < 1" - pullstream ">= 0.4.1 < 1" - readable-stream "~1.0.31" - setimmediate ">= 1.0.1 < 2" - -util-deprecate@~1.0.1: - version "1.0.2" - resolved "https://registry.yarnpkg.com/util-deprecate/-/util-deprecate-1.0.2.tgz#450d4dc9fa70de732762fbd2d4a28981419a0ccf" - -uuid@^3.0.0, uuid@^3.1.0: - version "3.1.0" - resolved "https://registry.yarnpkg.com/uuid/-/uuid-3.1.0.tgz#3dd3d3e790abc24d7b0d3a034ffababe28ebbc04" - -validate-npm-package-license@^3.0.1: - version "3.0.1" - resolved "https://registry.yarnpkg.com/validate-npm-package-license/-/validate-npm-package-license-3.0.1.tgz#2804babe712ad3379459acfbe24746ab2c303fbc" - dependencies: - spdx-correct "~1.0.0" - spdx-expression-parse "~1.0.0" - -verror@1.10.0: - version "1.10.0" - resolved "https://registry.yarnpkg.com/verror/-/verror-1.10.0.tgz#3a105ca17053af55d6e270c1f8288682e18da400" - dependencies: - assert-plus "^1.0.0" - core-util-is "1.0.2" - extsprintf "^1.2.0" - -which@^1.1.1, which@^1.2.4, which@^1.2.9: - version "1.3.0" - resolved "https://registry.yarnpkg.com/which/-/which-1.3.0.tgz#ff04bdfc010ee547d780bec38e1ac1c2777d253a" - dependencies: - isexe "^2.0.0" - -window-size@0.1.0: - version "0.1.0" - resolved "https://registry.yarnpkg.com/window-size/-/window-size-0.1.0.tgz#5438cd2ea93b202efa3a19fe8887aee7c94f9c9d" - -window-size@^0.1.4: - version "0.1.4" - resolved "https://registry.yarnpkg.com/window-size/-/window-size-0.1.4.tgz#f8e1aa1ee5a53ec5bf151ffa09742a6ad7697876" - -wordwrap@0.0.2: - version "0.0.2" - resolved "https://registry.yarnpkg.com/wordwrap/-/wordwrap-0.0.2.tgz#b79669bb42ecb409f83d583cad52ca17eaa1643f" - -wordwrap@^1.0.0, wordwrap@~1.0.0: - version "1.0.0" - resolved "https://registry.yarnpkg.com/wordwrap/-/wordwrap-1.0.0.tgz#27584810891456a4171c8d0226441ade90cbcaeb" - -wordwrap@~0.0.2: - version "0.0.3" - resolved "https://registry.yarnpkg.com/wordwrap/-/wordwrap-0.0.3.tgz#a3d5da6cd5c0bc0008d37234bbaf1bed63059107" - -wrap-ansi@^2.0.0: - version "2.1.0" - resolved "https://registry.yarnpkg.com/wrap-ansi/-/wrap-ansi-2.1.0.tgz#d8fc3d284dd05794fe84973caecdd1cf824fdd85" - dependencies: - string-width "^1.0.1" - strip-ansi "^3.0.1" - -wrappy@1: - version "1.0.2" - resolved "https://registry.yarnpkg.com/wrappy/-/wrappy-1.0.2.tgz#b5243d8f3ec1aa35f1364605bc0d1036e30ab69f" - -wrench@~1.3.9: - version "1.3.9" - resolved "https://registry.yarnpkg.com/wrench/-/wrench-1.3.9.tgz#6f13ec35145317eb292ca5f6531391b244111411" - -write-file-atomic@^1.1.4: - version "1.3.4" - resolved "https://registry.yarnpkg.com/write-file-atomic/-/write-file-atomic-1.3.4.tgz#f807a4f0b1d9e913ae7a48112e6cc3af1991b45f" - dependencies: - graceful-fs "^4.1.11" - imurmurhash "^0.1.4" - slide "^1.1.5" - -"xtend@>=4.0.0 <4.1.0-0", xtend@^4.0.0: - version "4.0.1" - resolved "https://registry.yarnpkg.com/xtend/-/xtend-4.0.1.tgz#a5c6d532be656e23db820efb943a1f04998d63af" - -xtend@~2.1.1: - version "2.1.2" - resolved "https://registry.yarnpkg.com/xtend/-/xtend-2.1.2.tgz#6efecc2a4dad8e6962c4901b337ce7ba87b5d28b" - dependencies: - object-keys "~0.4.0" - -y18n@^3.2.0: - version "3.2.1" - resolved "https://registry.yarnpkg.com/y18n/-/y18n-3.2.1.tgz#6d15fba884c08679c0d77e88e7759e811e07fa41" - -yallist@^2.1.2: - version "2.1.2" - resolved "https://registry.yarnpkg.com/yallist/-/yallist-2.1.2.tgz#1c11f9218f076089a47dd512f93c6699a6a81d52" - -yargs@^3.15.0: - version "3.32.0" - resolved "https://registry.yarnpkg.com/yargs/-/yargs-3.32.0.tgz#03088e9ebf9e756b69751611d2a5ef591482c995" - dependencies: - camelcase "^2.0.1" - cliui "^3.0.3" - decamelize "^1.1.1" - os-locale "^1.4.0" - string-width "^1.0.1" - window-size "^0.1.4" - y18n "^3.2.0" - -yargs@~3.10.0: - version "3.10.0" - resolved "https://registry.yarnpkg.com/yargs/-/yargs-3.10.0.tgz#f7ee7bd857dd7c1d2d38c0e74efbd681d1431fd1" - dependencies: - camelcase "^1.0.2" - cliui "^2.1.0" - decamelize "^1.0.0" - window-size "0.1.0" diff --git a/ts-ticket-office-service/node_modules/mongodb/.coveralls.yml b/ts-ticket-office-service/node_modules/mongodb/.coveralls.yml deleted file mode 100644 index ad1e93c37..000000000 --- a/ts-ticket-office-service/node_modules/mongodb/.coveralls.yml +++ /dev/null @@ -1 +0,0 @@ -repo_token: GZFmqKPy7XEX0uOl9TDZFUoOQ5AHADMkU diff --git a/ts-ticket-office-service/node_modules/mongodb/.eslintrc b/ts-ticket-office-service/node_modules/mongodb/.eslintrc deleted file mode 100644 index 753e2a525..000000000 --- a/ts-ticket-office-service/node_modules/mongodb/.eslintrc +++ /dev/null @@ -1,15 +0,0 @@ -{ - "extends": ["eslint:recommended"], - "env": { - "node": true, - "mocha": true - }, - "ecmaFeatures": { - "es6": true, - }, - "plugins": [ - ], - "rules": { - "no-console":0 - } -} diff --git a/ts-ticket-office-service/node_modules/mongodb/HISTORY.md b/ts-ticket-office-service/node_modules/mongodb/HISTORY.md deleted file mode 100644 index 46a56a306..000000000 --- a/ts-ticket-office-service/node_modules/mongodb/HISTORY.md +++ /dev/null @@ -1,1748 +0,0 @@ -2.2.33 2017-10-12 ------------------ -* update to mongodb-core 2.1.17 - -2.2.32 2017-10-11 ------------------ -* update to mongodb-core 2.1.16 -* ensure that the `cursor` key is always present in aggregation commands -* `Cursor.prototype.hasNext` now propagates errors when using callback -* allow passing `noCursorTimeout` as an option to `find()` -* bubble up `reconnectFailed` event from Server topology - -2.2.31 2017-08-08 ------------------ -* update mongodb-core to 2.1.15 -* allow auth option in MongoClient.connect -* remove duplicate option `promoteLongs` from MongoClient's `connect` -* bulk operations should not throw an error on empty batch - -2.2.30 2017-07-07 ------------------ -* Update mongodb-core to 2.1.14 -* MongoClient - * add `appname` to list of valid option names - * added test for passing appname as option -* NODE-1052 ensure user options are applied while parsing connection string uris - -2.2.29 2017-06-19 ------------------ -* Update mongodb-core to 2.1.13 - * NODE-1039 ensure we force destroy server instances, forcing queue to be flushed. - * Use actual server type in standalone SDAM events. -* Allow multiple map calls (Issue #1521, https://github.com/Robbilie). -* Clone insertMany options before mutating (Issue #1522, https://github.com/vkarpov15). -* NODE-1034 Fix GridStore issue caused by Node 8.0.0 breaking backward compatible fs.read API. -* NODE-1026, use operator instead of skip function in order to avoid useless fetch stage. - -2.2.28 2017-06-02 ------------------ -* Update mongodb-core to 2.1.12 - * NODE-1019 Set keepAlive to 300 seconds or 1/2 of socketTimeout if socketTimeout < keepAlive. - * Minor fix to report the correct state on error. - * NODE-1020 'family' was added to options to provide high priority for ipv6 addresses (Issue #1518, https://github.com/firej). - * Fix require_optional loading of bson-ext. - * Ensure no errors are thrown by replset if topology is destroyed before it finished connecting. - * NODE-999 SDAM fixes for Mongos and single Server event emitting. - * NODE-1014 Set socketTimeout to default to 360 seconds. - * NODE-1019 Set keepAlive to 300 seconds or 1/2 of socketTimeout if socketTimeout < keepAlive. -* Just handle Collection name errors distinctly from general callback errors avoiding double callbacks in Db.collection. -* NODE-999 SDAM fixes for Mongos and single Server event emitting. -* NODE-1000 Added guard condition for upload.js checkDone function in case of race condition caused by late arriving chunk write. - -2.2.27 2017-05-22 ------------------ -* Updated mongodb-core to 2.1.11 - * NODE-987 Clear out old intervalIds on when calling topologyMonitor. - * NODE-987 Moved filtering to pingServer method and added test case. - * Check for connection destroyed just before writing out and flush out operations correctly if it is (Issue #179, https://github.com/jmholzinger). - * NODE-989 Refactored Replicaset monitoring to correcly monitor newly added servers, Also extracted setTimeout and setInterval to use custom wrappers Timeout and Interval. -* NODE-985 Deprecated Db.authenticate and Admin.authenticate and moved auth methods into authenticate.js to ensure MongoClient.connect does not print deprecation warnings. -* NODE-988 Merged readConcern and hint correctly on collection(...).find(...).count() -* Fix passing the readConcern option to MongoClient.connect (Issue #1514, https://github.com/bausmeier). -* NODE-996 Propegate all events up to a MongoClient instance. -* Allow saving doc with null `_id` (Issue #1517, https://github.com/vkarpov15). -* NODE-993 Expose hasNext for command cursor and add docs for both CommandCursor and Aggregation Cursor. - -2.2.26 2017-04-18 ------------------ -* Updated mongodb-core to 2.1.10 - * NODE-981 delegate auth to replset/mongos if inTopology is set. - * NODE-978 Wrap connection.end in try/catch for node 0.10.x issue causing exceptions to be thrown, Also surfaced getConnection for mongos and replset. - * Remove dynamic require (Issue #175, https://github.com/tellnes). - * NODE-696 Handle interrupted error for createIndexes. - * Fixed isse when user is executing find command using Server.command and it get interpreted as a wire protcol message, #172. - * NODE-966 promoteValues not being promoted correctly to getMore. - * Merged in fix for flushing out monitoring operations. -* NODE-983 Add cursorId to aggregate and listCollections commands (Issue, #1510). -* Mark group and profilingInfo as deprecated methods -* NODE-956 DOCS Examples. -* Update readable-stream to version 2.2.7. -* NODE-978 Added test case to uncover connection.end issue for node 0.10.x. -* NODE-972 Fix(db): don't remove database name if collectionName == dbName (Issue, #1502) -* Fixed merging of writeConcerns on db.collection method. -* NODE-970 mix in readPreference for strict mode listCollections callback. -* NODE-966 added testcase for promoteValues being applied to getMore commands. -* NODE-962 Merge in ignoreUndefined from collection level for find/findOne. -* Remove multi option from updateMany tests/docs (Issue #1499, https://github.com/spratt). -* NODE-963 Correctly handle cursor.count when using APM. - -2.2.25 2017-03-17 ------------------ -* Don't rely on global toString() for checking if object (Issue #1494, https://github.com/vkarpov15). -* Remove obsolete option uri_decode_auth (Issue #1488, https://github.com/kamagatos). -* NODE-936 Correctly translate ReadPreference to CoreReadPreference for mongos queries. -* Exposed BSONRegExp type. -* NODE-950 push correct index for INSERT ops (https://github.com/mbroadst). -* NODE-951 Added support for sslCRL option and added a test case for it. -* NODE-953 Made batchSize issue general at cursor level. -* NODE-954 Remove write concern from reindex helper as it will not be supported in 3.6. -* Updated mongodb-core to 2.1.9. - * Return lastIsMaster correctly when connecting with secondaryOnlyConnectionAllowed is set to true and only a secondary is available in replica state. - * Clone options when passed to wireProtocol handler to avoid intermittent modifications causing errors. - * Ensure SSL error propegates better for Replset connections when there is a SSL validation error. - * NODE-957 Fixed issue where < batchSize not causing cursor to be closed on execution of first batch. - * NODE-958 Store reconnectConnection on pool object to allow destroy to close immediately. - -2.2.24 2017-02-14 ------------------ -* NODE-935, NODE-931 Make MongoClient strict options validation optional and instead print annoying console.warn entries. - -2.2.23 2017-02-13 ------------------ -* Updated mongodb-core to 2.1.8. - * NODE-925 ensure we reschedule operations while pool is < poolSize while pool is growing and there are no connections with not currently performing work. - * NODE-927 fixes issue where authentication was performed against arbiter instances. - * NODE-915 Normalize all host names to avoid comparison issues. - * Fixed issue where pool.destroy would never finish due to a single operation not being executed and keeping it open. -* NODE-931 Validates all the options for MongoClient.connect and fixes missing connection settings. -* NODE-929 Update SSL tutorial to correctly reflect the non-need for server/mongos/replset subobjects -* Fix sensitive command check (Issue #1473, https://github.com/Annoraaq) - -2.2.22 2017-01-24 ------------------ -* Updated mongodb-core to 2.1.7. - * NODE-919 ReplicaSet connection does not close immediately (Issue #156). - * NODE-901 Fixed bug when normalizing host names. - * NODE-909 Fixed readPreference issue caused by direct connection to primary. - * NODE-910 Fixed issue when bufferMaxEntries == 0 and read preference set to nearest. -* Add missing unref implementations for replset, mongos (Issue #1455, https://github.com/zbjornson) - -2.2.21 2017-01-13 ------------------ -* Updated mongodb-core to 2.1.6. - * NODE-908 Keep auth contexts in replset and mongos topology to ensure correct application of authentication credentials when primary is first server to be detected causing an immediate connect event to happen. - -2.2.20 2017-01-11 ------------------ -* Updated mongodb-core to 2.1.5 to include bson 1.0.4 and bson-ext 1.0.4 due to Buffer.from being broken in early node 4.x versions. - -2.2.19 2017-01-03 ------------------ -* Corrupted Npm release fix. - -2.2.18 2017-01-03 ------------------ -* Updated mongodb-core to 2.1.4 to fix bson ObjectId toString issue with utils.inspect messing with toString parameters in node 6. - -2.2.17 2017-01-02 ------------------ -* updated createCollection doc options and linked to create command. -* Updated mongodb-core to 2.1.3. - * Monitoring operations are re-scheduled in pool if it cannot find a connection that does not already have scheduled work on it, this is to avoid the monitoring socket timeout being applied to any existing operations on the socket due to pipelining - * Moved replicaset monitoring away from serial mode and to parallel mode. - * updated bson and bson-ext dependencies to 1.0.2. - -2.2.16 2016-12-13 ------------------ -* NODE-899 reversed upsertedId change to bring back old behavior. - -2.2.15 2016-12-10 ------------------ -* Updated mongodb-core to 2.1.2. - * Delay topologyMonitoring on successful attemptReconnect as no need to run a full scan immediately. - * Emit reconnect event in primary joining when in connected status for a replicaset (Fixes mongoose reconnect issue). - -2.2.14 2016-12-08 ------------------ -* Updated mongodb-core to 2.1.1. -* NODE-892 Passthrough options.readPreference to mongodb-core ReplSet instance. - -2.2.13 2016-12-05 ------------------ -* Updated mongodb-core to 2.1.0. -* NODE-889 Fixed issue where legacy killcursor wire protocol messages would not be sent when APM is enabled. -* Expose parserType as property on topology objects. - -2.2.12 2016-11-29 ------------------ -* Updated mongodb-core to 2.0.14. - * Updated bson library to 0.5.7. - * Dont leak connection.workItems elments when killCursor is called (Issue #150, https://github.com/mdlavin). - * Remove unnecessary errors formatting (Issue #149, https://github.com/akryvomaz). - * Only check isConnected against availableConnections (Issue #142). - * NODE-838 Provide better error message on failed to connect on first retry for Mongos topology. - * Set default servername to host is not passed through for sni. - * Made monitoring happen on exclusive connection and using connectionTimeout to handle the wait time before failure (Issue #148). - * NODE-859 Make minimum value of maxStalenessSeconds 90 seconds. - * NODE-852 Fix Kerberos module deprecations on linux and windows and release new kerberos version. - * NODE-850 Update Max Staleness implementation. - * NODE-849 username no longer required for MONGODB-X509 auth. - * NODE-848 BSON Regex flags must be alphabetically ordered. - * NODE-846 Create notice for all third party libraries. - * NODE-843 Executing bulk operations overwrites write concern parameter. - * NODE-842 Re-sync SDAM and SDAM Monitoring tests from Specs repo. - * NODE-840 Resync CRUD spec tests. - * Unescapable while(true) loop (Issue #152). -* NODE-864 close event not emits during network issues using single server topology. -* Introduced maxStalenessSeconds. -* NODE-840 Added CRUD specification test cases and fix minor issues with upserts reporting matchedCount > 0. -* Don't ignore Db-level authSource when using auth method. (https://github.com/donaldguy). - -2.2.11 2016-10-21 ------------------ -* Updated mongodb-core to 2.0.13. - - Fire callback when topology was destroyed (Issue #147, https://github.com/vkarpov15). - - Refactoring to support pipelining ala 1.4.x branch will retaining the benefits of the growing/shrinking pool (Issue #146). - - Fix typo in serverHeartbeatFailed event name (Issue #143, https://github.com/jakesjews). - - NODE-798 Driver hangs on count command in replica set with one member (Issue #141, https://github.com/isayme). -* Updated bson library to 0.5.6. - - Included cyclic dependency detection -* Fix typo in serverHeartbeatFailed event name (Issue #1418, https://github.com/jakesjews). -* NODE-824, readPreference "nearest" does not work when specified at collection level. -* NODE-822, GridFSBucketWriteStream end method does not handle optional parameters. -* NODE-823, GridFSBucketWriteStream end: callback is invoked with invalid parameters. -* NODE-829, Using Start/End offset option in GridFSBucketReadStream doesn't return the right sized buffer. - -2.2.10 2016-09-15 ------------------ -* Updated mongodb-core to 2.0.12. -* fix debug logging message not printing server name. -* fixed application metadata being sent by wrong ismaster. -* NODE-812 Fixed mongos stall due to proxy monitoring ismaster failure causing reconnect. -* NODE-818 Replicaset timeouts in initial connect sequence can "no primary found". -* Updated bson library to 0.5.5. -* Added DBPointer up conversion to DBRef. -* MongoDB 3.4-RC Pass **appname** through MongoClient.connect uri or options to allow metadata to be passed. -* MongoDB 3.4-RC Pass collation options on update, findOne, find, createIndex, aggregate. -* MongoDB 3.4-RC Allow write concerns to be passed to all supporting server commands. -* MongoDB 3.4-RC Allow passing of **servername** as SSL options to support SNI. - -2.2.9 2016-08-29 ----------------- -* Updated mongodb-core to 2.0.11. -* NODE-803, Fixed issue in how the latency window is calculated for Mongos topology causing issues for single proxy connections. -* Avoid timeout in attemptReconnect causing multiple attemptReconnect attempts to happen (Issue #134, https://github.com/dead-horse). -* Ensure promoteBuffers is propegated in same fashion as promoteValues and promoteLongs. -* Don't treat ObjectId as object for mapReduce scope (Issue #1397, https://github.com/vkarpov15). - -2.2.8 2016-08-23 ----------------- -* Updated mongodb-core to 2.0.10. -* Added promoteValues flag (default to true) to allow user to specify they only want wrapped BSON values back instead of promotion to native types. -* Do not close mongos proxy connection on failed ismaster check in ha process (Issue #130). - -2.2.7 2016-08-19 ----------------- -* If only a single mongos is provided in the seedlist, fix issue where it would be assigned as single standalone server instead of mongos topology (Issue #130). -* Updated mongodb-core to 2.0.9. -* Allow promoteLongs to be passed in through Response.parse method and overrides default set on the connection. -* NODE-798 Driver hangs on count command in replica set with one member. -* Allow promoteLongs to be passed in through Response.parse method and overrides default set on the connection. -* Allow passing in servername for TLS connections for SNI support. - -2.2.6 2016-08-16 ----------------- -* Updated mongodb-core to 2.0.8. -* Allow execution of store operations independent of having both a primary and secondary available (Issue #123). -* Fixed command execution issue for mongos to ensure buffering of commands when no mongos available. -* Allow passing in an array of tags to ReadPreference constructor (Issue #1382, https://github.com/vkarpov15) -* Added hashed connection names and fullResult. -* Updated bson library to 0.5.3. -* Enable maxTimeMS in count, distinct, findAndModify. - -2.2.5 2016-07-28 ----------------- -* Updated mongodb-core to 2.0.7. -* Allow primary to be returned when secondaryPreferred is passed (Issue #117, https://github.com/dhendo). -* Added better warnings when passing in illegal seed list members to a Mongos topology. -* Minor attemptReconnect bug that would cause multiple attemptReconnect to run in parallel. -* Fix wrong opType passed to disconnectHandler.add (Issue #121, https://github.com/adrian-gierakowski) -* Implemented domain backward comp support enabled via domainsEnabled options on Server/ReplSet/Mongos and MongoClient.connect. - -2.2.4 2016-07-19 ----------------- -* NPM corrupted upload fix. - -2.2.3 2016-07-19 ----------------- -* Updated mongodb-core to 2.0.6. -* Destroy connection on socket timeout due to newer node versions not closing the socket. - -2.2.2 2016-07-15 ----------------- -* Updated mongodb-core to 2.0.5. -* Minor fixes to handle faster MongoClient connectivity from the driver, allowing single server instances to detect if they are a proxy. -* Added numberOfConsecutiveTimeouts to pool that will destroy the pool if the number of consecutive timeouts > reconnectTries. -* Print warning if seedlist servers host name does not match the one provided in it's ismaster.me field for Replicaset members. -* Fix issue where Replicaset connection would not succeeed if there the replicaset was a single primary server setup. - -2.2.1 2016-07-11 ----------------- -* Updated mongodb-core to 2.0.4. -* handle situation where user is providing seedlist names that do not match host list. fix allows for a single full discovery connection sweep before erroring out. -* NODE-747 Polyfill for Object.assign for 0.12.x or 0.10.x. -* NODE-746 Improves replicaset errors for wrong setName. - -2.2.0 2016-07-05 ----------------- -* Updated mongodb-core to 2.0.3. -* Moved all authentication and handling of growing/shrinking of pool connections into actual pool. -* All authentication methods now handle both auth/reauthenticate and logout events. -* Introduced logout method to get rid of onAll option for logout command. -* Updated bson to 0.5.0 that includes Decimal128 support. -* Fixed logger error serialization issue. -* Documentation fixes. -* Implemented Server Selection Specification test suite. -* Added warning level to logger. -* Added warning message when sockeTimeout < haInterval for Replset/Mongos. -* Mongos emits close event on no proxies available or when reconnect attempt fails. -* Replset emits close event when no servers available or when attemptReconnect fails to reconnect. -* Don't throw in auth methods but return error in callback. - -2.1.21 2016-05-30 ------------------ -* Updated mongodb-core to 1.3.21. -* Pool gets stuck if a connection marked for immediateRelease times out (Issue #99, https://github.com/nbrachet). -* Make authentication process retry up to authenticationRetries at authenticationRetryIntervalMS interval. -* Made ismaster replicaset calls operate with connectTimeout or monitorSocketTimeout to lower impact of big socketTimeouts on monitoring performance. -* Make sure connections mark as "immediateRelease" don't linger the inUserConnections list. Otherwise, after that connection times out, getAll() incorrectly returns more connections than are effectively present, causing the pool to not get restarted by reconnectServer. (Issue #99, https://github.com/nbrachet). -* Make cursor getMore or killCursor correctly trigger pool reconnect to single server if pool has not been destroyed. -* Make ismaster monitoring for single server connection default to avoid user confusion due to change in behavior. - -2.1.20 2016-05-25 ------------------ -* Refactored MongoClient options handling to simplify the logic, unifying it. -* NODE-707 Implemented openUploadStreamWithId on GridFS to allow for custom fileIds so users are able to customize shard key and shard distribution. -* NODE-710 Allow setting driver loggerLevel and logger function from MongoClient options. -* Updated mongodb-core to 1.3.20. -* Minor fix for SSL errors on connection attempts, minor fix to reconnect handler for the server. -* Don't write to socket before having registered the callback for commands, work around for windows issuing error events twice on node.js when socket gets destroyed by firewall. -* Fix minor issue where connectingServers would not be removed correctly causing single server connections to not auto-reconnect. - -2.1.19 2016-05-17 ----------------- -* Handle situation where a server connection in a replicaset sometimes fails to be destroyed properly due to being in the middle of authentication when the destroy method is called on the replicaset causing it to be orphaned and never collected. -* Ensure replicaset topology destroy is never called by SDAM. -* Ensure all paths are correctly returned on inspectServer in replset. -* Updated mongodb-core to 1.3.19 to fix minor connectivity issue on quick open/close of MongoClient connections on auth enabled mongodb Replicasets. - -2.1.18 2016-04-27 ------------------ -* Updated mongodb-core to 1.3.18 to fix Node 6.0 issues. - -2.1.17 2016-04-26 ------------------ -* Updated mongodb-core to 1.3.16 to work around issue with early versions of node 0.10.x due to missing unref method on ClearText streams. -* INT-1308: Allow listIndexes to inherit readPreference from Collection or DB. -* Fix timeout issue using new flags #1361. -* Updated mongodb-core to 1.3.17. -* Better handling of unique createIndex error. -* Emit error only if db instance has an error listener. -* DEFAULT authMechanism; don't throw error if explicitly set by user. - -2.1.16 2016-04-06 ------------------ -* Updated mongodb-core to 1.3.16. - -2.1.15 2016-04-06 ------------------ -* Updated mongodb-core to 1.3.15. -* Set ssl, sslValidate etc to mongosOptions on url_parser (Issue #1352, https://github.com/rubenstolk). -- NODE-687 Fixed issue where a server object failed to be destroyed if the replicaset state did not update successfully. This could leave active connections accumulating over time. -- Fixed some situations where all connections are flushed due to a single connection in the connection pool closing. - -2.1.14 2016-03-29 ------------------ -* Updated mongodb-core to 1.3.13. -* Handle missing cursor on getMore when going through a mongos proxy by pinning to socket connection and not server. - -2.1.13 2016-03-29 ------------------ -* Updated mongodb-core to 1.3.12. - -2.1.12 2016-03-29 ------------------ -* Updated mongodb-core to 1.3.11. -* Mongos setting acceptableLatencyMS exposed to control the latency women for mongos selection. -* Mongos pickProxies fall back to closest mongos if no proxies meet latency window specified. -* isConnected method for mongos uses same selection code as getServer. -* Exceptions in cursor getServer trapped and correctly delegated to high level handler. - -2.1.11 2016-03-23 ------------------ -* Updated mongodb-core to 1.3.10. -* Introducing simplified connections settings. - -2.1.10 2016-03-21 ------------------ -* Updated mongodb-core to 1.3.9. -* Fixing issue that prevented mapReduce stats from being resolved (Issue #1351, https://github.com/davidgtonge) -* Forwards SDAM monitoring events from mongodb-core. - -2.1.9 2016-03-16 ----------------- -* Updated mongodb-core to 1.3.7 to fix intermittent race condition that causes some users to experience big amounts of socket connections. -* Makde bson parser in ordered/unordered bulk be directly from mongodb-core to avoid intermittent null error on mongoose. - -2.1.8 2016-03-14 ----------------- -* Updated mongodb-core to 1.3.5. -* NODE-660 TypeError: Cannot read property 'noRelease' of undefined. -* Harden MessageHandler in server.js to avoid issues where we cannot find a callback for an operation. -* Ensure RequestId can never be larger than Max Number integer size. -* NODE-661 typo in url_parser.js resulting in replSetServerOptions is not defined when connecting over ssl. -* Confusing error with invalid partial index filter (Issue #1341, https://github.com/vkarpov15). -* NODE-669 Should only error out promise for bulkWrite when error is a driver level error not a write error or write concern error. -* NODE-662 shallow copy options on methods that are not currently doing it to avoid passed in options mutiation. -* NODE-663 added lookup helper on aggregation cursor. -* NODE-585 Result object specified incorrectly for findAndModify?. -* NODE-666 harden validation for findAndModify CRUD methods. - -2.1.7 2016-02-09 ----------------- -* NODE-656 fixed corner case where cursor count command could be left without a connection available. -* NODE-658 Work around issue that bufferMaxEntries:-1 for js gets interpreted wrongly due to double nature of Javascript numbers. -* Fix: GridFS always returns the oldest version due to incorrect field name (Issue #1338, https://github.com/mdebruijne). -* NODE-655 GridFS stream support for cancelling upload streams and download streams (Issue #1339, https://github.com/vkarpov15). -* NODE-657 insertOne don`t return promise in some cases. -* Added destroy alias for abort function on GridFSBucketWriteStream. - -2.1.6 2016-02-05 ----------------- -* Updated mongodb-core to 1.3.1. - -2.1.5 2016-02-04 ----------------- -* Updated mongodb-core to 1.3.0. -* Added raw support for the command function on topologies. -* Fixed issue where raw results that fell on batchSize boundaries failed (Issue #72) -* Copy over all the properties to the callback returned from bindToDomain, (Issue #72) -* Added connection hash id to be able to reference connection host/name without leaking it outside of driver. -* NODE-638, Cannot authenticate database user with utf-8 password. -* Refactored pool to be worker queue based, minimizing the impact a slow query have on throughput as long as # slow queries < # connections in the pool. -* Pool now grows and shrinks correctly depending on demand not causing a full pool reconnect. -* Improvements in monitoring of a Replicaset where in certain situations the inquiry process could get exited. -* Switched to using Array.push instead of concat for use cases of a lot of documents. -* Fixed issue where re-authentication could loose the credentials if whole Replicaset disconnected at once. -* Added peer optional dependencies support using require_optional module. -* Bug is listCollections for collection names that start with db name (Issue #1333, https://github.com/flyingfisher) -* Emit error before closing stream (Issue #1335, https://github.com/eagleeye) - -2.1.4 2016-01-12 ----------------- -* Restricted node engine to >0.10.3 (https://jira.mongodb.org/browse/NODE-635). -* Multiple database names ignored without a warning (https://jira.mongodb.org/browse/NODE-636, Issue #1324, https://github.com/yousefhamza). -* Convert custom readPreference objects in collection.js (Issue #1326, https://github.com/Machyne). - -2.1.3 2016-01-04 ----------------- -* Updated mongodb-core to 1.2.31. -* Allow connection to secondary if primaryPreferred or secondaryPreferred (Issue #70, https://github.com/leichter) - -2.1.2 2015-12-23 ----------------- -* Updated mongodb-core to 1.2.30. -* Pool allocates size + 1 connections when using replicasets, reserving additional pool connection for monitoring exclusively. -* Fixes bug when all replicaset members are down, that would cause it to fail to reconnect using the originally provided seedlist. - -2.1.1 2015-12-13 ----------------- -* Surfaced checkServerIdentity options for MongoClient, Server, ReplSet and Mongos to allow for control of the checkServerIdentity method available in Node.s 0.12.x or higher. -* Added readPreference support to listCollections and listIndexes helpers. -* Updated mongodb-core to 1.2.28. - -2.1.0 2015-12-06 ----------------- -* Implements the connection string specification, https://github.com/mongodb/specifications/blob/master/source/connection-string/connection-string-spec.rst. -* Implements the new GridFS specification, https://github.com/mongodb/specifications/blob/master/source/gridfs/gridfs-spec.rst. -* Full MongoDB 3.2 support. -* NODE-601 Added maxAwaitTimeMS support for 3.2 getMore to allow for custom timeouts on tailable cursors. -* Updated mongodb-core to 1.2.26. -* Return destination in GridStore pipe function. -* NODE-606 better error handling on destroyed topology for db.js methods. -* Added isDestroyed method to server, replset and mongos topologies. -* Upgraded test suite to run using mongodb-topology-manager. - -2.0.53 2015-12-23 ------------------ -* Updated mongodb-core to 1.2.30. -* Pool allocates size + 1 connections when using replicasets, reserving additional pool connection for monitoring exclusively. -* Fixes bug when all replicaset members are down, that would cause it to fail to reconnect using the originally provided seedlist. - -2.0.52 2015-12-14 ------------------ -* removed remove from Gridstore.close. - -2.0.51 2015-12-13 ------------------ -* Surfaced checkServerIdentity options for MongoClient, Server, ReplSet and Mongos to allow for control of the checkServerIdentity method available in Node.s 0.12.x or higher. -* Added readPreference support to listCollections and listIndexes helpers. -* Updated mongodb-core to 1.2.28. - -2.0.50 2015-12-06 ------------------ -* Updated mongodb-core to 1.2.26. - -2.0.49 2015-11-20 ------------------ -* Updated mongodb-core to 1.2.24 with several fixes. - * Fix Automattic/mongoose#3481; flush callbacks on error, (Issue #57, https://github.com/vkarpov15). - * $explain query for wire protocol 2.6 and 2.4 does not set number of returned documents to -1 but to 0. - * ismaster runs against admin.$cmd instead of system.$cmd. - * Fixes to handle getMore command errors for MongoDB 3.2 - * Allows the process to properly close upon a Db.close() call on the replica set by shutting down the haTimer and closing arbiter connections. - -2.0.48 2015-11-07 ------------------ -* GridFS no longer performs any deletes when writing a brand new file that does not have any previous .fs.chunks or .fs.files documents. -* Updated mongodb-core to 1.2.21. -* Hardened the checking for replicaset equality checks. -* OpReplay flag correctly set on Wire protocol query. -* Mongos load balancing added, introduced localThresholdMS to control the feature. -* Kerberos now a peerDependency, making it not install it by default in Node 5.0 or higher. - -2.0.47 2015-10-28 ------------------ -* Updated mongodb-core to 1.2.20. -* Fixed bug in arbiter connection capping code. -* NODE-599 correctly handle arrays of server tags in order of priority. -* Fix for 2.6 wire protocol handler related to readPreference handling. -* Added maxAwaitTimeMS support for 3.2 getMore to allow for custom timeouts on tailable cursors. -* Make CoreCursor check for $err before saying that 'next' succeeded (Issue #53, https://github.com/vkarpov15). - -2.0.46 2015-10-15 ------------------ -* Updated mongodb-core to 1.2.19. -* NODE-578 Order of sort fields is lost for numeric field names. -* Expose BSON Map (ES6 Map or polyfill). -* Minor fixes for APM support to pass extended APM test suite. - -2.0.45 2015-09-30 ------------------ -* NODE-566 Fix issue with rewind on capped collections causing cursor state to be reset on connection loss. - -2.0.44 2015-09-28 ------------------ -* Bug fixes for APM upconverting of legacy INSERT/UPDATE/REMOVE wire protocol messages. -* NODE-562, fixed issue where a Replicaset MongoDB URI with a single seed and replSet name set would cause a single direct connection instead of topology discovery. -* Updated mongodb-core to 1.2.14. -* NODE-563 Introduced options.ignoreUndefined for db class and MongoClient db options, made serialize undefined to null default again but allowing for overrides on insert/update/delete operations. -* Use handleCallback if result is an error for count queries. (Issue #1298, https://github.com/agclever) -* Rewind cursor to correctly force reconnect on capped collections when first query comes back empty. -* NODE-571 added code 59 to legacy server errors when SCRAM-SHA-1 mechanism fails. -* NODE-572 Remove examples that use the second parameter to `find()`. - -2.0.43 2015-09-14 ------------------ -* Propagate timeout event correctly to db instances. -* Application Monitoring API (APM) implemented. -* NOT providing replSet name in MongoClient connection URI will force single server connection. Fixes issue where it was impossible to directly connect to a replicaset member server. -* Updated mongodb-core to 1.2.12. -* NODE-541 Initial Support "read committed" isolation level where "committed" means confimed by the voting majority of a replica set. -* GridStore doesn't share readPreference setting from connection string. (Issue #1295, https://github.com/zhangyaoxing) -* fixed forceServerObjectId calls (Issue #1292, https://github.com/d-mon-) -* Pass promise library through to DB function (Issue #1294, https://github.com/RovingCodeMonkey) - -2.0.42 2015-08-18 ------------------ -* Added test case to exercise all non-crud methods on mongos topologies, fixed numberOfConnectedServers on mongos topology instance. - -2.0.41 2015-08-14 ------------------ -* Added missing Mongos.prototype.parserType function. -* Updated mongodb-core to 1.2.10. - -2.0.40 2015-07-14 ------------------ -* Updated mongodb-core to 1.2.9 for 2.4 wire protocol error handler fix. -* NODE-525 Reset connectionTimeout after it's overwritten by tls.connect. -* NODE-518 connectTimeoutMS is doubled in 2.0.39. -* NODE-506 Ensures that errors from bulk unordered and ordered are instanceof Error (Issue #1282, https://github.com/owenallenaz). -* NODE-526 Unique index not throwing duplicate key error. -* NODE-528 Ignore undefined fields in Collection.find(). -* NODE-527 The API example for collection.createIndex shows Db.createIndex functionality. - -2.0.39 2015-07-14 ------------------ -* Updated mongodb-core to 1.2.6 for NODE-505. - -2.0.38 2015-07-14 ------------------ -* NODE-505 Query fails to find records that have a 'result' property with an array value. - -2.0.37 2015-07-14 ------------------ -* NODE-504 Collection * Default options when using promiseLibrary. -* NODE-500 Accidental repeat of hostname in seed list multiplies total connections persistently. -* Updated mongodb-core to 1.2.5 to fix NODE-492. - -2.0.36 2015-07-07 ------------------ -* Fully promisified allowing the use of ES6 generators and libraries like co. Also allows for BYOP (Bring your own promises). -* NODE-493 updated mongodb-core to 1.2.4 to ensure we cannot DDOS the mongod or mongos process on large connection pool sizes. - -2.0.35 2015-06-17 ------------------ -* Upgraded to mongodb-core 1.2.2 including removing warnings when C++ bson parser is not available and a fix for SCRAM authentication. - -2.0.34 2015-06-17 ------------------ -* Upgraded to mongodb-core 1.2.1 speeding up serialization and removing the need for the c++ bson extension. -* NODE-486 fixed issue related to limit and skip when calling toArray in 2.0 driver. -* NODE-483 throw error if capabilities of topology is queries before topology has performed connection setup. -* NODE-482 fixed issue where MongoClient.connect would incorrectly identify a replset seed list server as a non replicaset member. -* NODE-487 fixed issue where killcursor command was not being sent correctly on limit and skip queries. - -2.0.33 2015-05-20 ------------------ -* Bumped mongodb-core to 1.1.32. - -2.0.32 2015-05-19 ------------------ -* NODE-463 db.close immediately executes its callback. -* Don't only emit server close event once (Issue #1276, https://github.com/vkarpov15). -* NODE-464 Updated mongodb-core to 1.1.31 that uses a single socket connection to arbiters and hidden servers as well as emitting all event correctly. - -2.0.31 2015-05-08 ------------------ -* NODE-461 Tripping on error "no chunks found for file, possibly corrupt" when there is no error. - -2.0.30 2015-05-07 ------------------ -* NODE-460 fix; don't set authMechanism for user in db.authenticate() to avoid mongoose authentication issue. - -2.0.29 2015-05-07 ------------------ -* NODE-444 Possible memory leak, too many listeners added. -* NODE-459 Auth failure using Node 0.8.28, MongoDB 3.0.2 & mongodb-node-native 1.4.35. -* Bumped mongodb-core to 1.1.26. - -2.0.28 2015-04-24 ------------------ -* Bumped mongodb-core to 1.1.25 -* Added Cursor.prototype.setCursorOption to allow for setting node specific cursor options for tailable cursors. -* NODE-430 Cursor.count() opts argument masked by var opts = {} -* NODE-406 Implemented Cursor.prototype.map function tapping into MongoClient cursor transforms. -* NODE-438 replaceOne is not returning the result.ops property as described in the docs. -* NODE-433 _read, pipe and write all open gridstore automatically if not open. -* NODE-426 ensure drain event is emitted after write function returns, fixes intermittent issues in writing files to gridstore. -* NODE-440 GridStoreStream._read() doesn't check GridStore.read() error. -* Always use readPreference = primary for findAndModify command (ignore passed in read preferences) (Issue #1274, https://github.com/vkarpov15). -* Minor fix in GridStore.exists for dealing with regular expressions searches. - -2.0.27 2015-04-07 ------------------ -* NODE-410 Correctly handle issue with pause/resume in Node 0.10.x that causes exceptions when using the Node 0.12.0 style streams. - -2.0.26 2015-04-07 ------------------ -* Implements the Common Index specification Standard API at https://github.com/mongodb/specifications/blob/master/source/index-management.rst. -* NODE-408 Expose GridStore.currentChunk.chunkNumber. - -2.0.25 2015-03-26 ------------------ -* Upgraded mongodb-core to 1.1.21, making the C++ bson code an optional dependency to the bson module. - -2.0.24 2015-03-24 ------------------ -* NODE-395 Socket Not Closing, db.close called before full set finished initalizing leading to server connections in progress not being closed properly. -* Upgraded mongodb-core to 1.1.20. - -2.0.23 2015-03-21 ------------------ -* NODE-380 Correctly return MongoError from toError method. -* Fixed issue where addCursorFlag was not correctly setting the flag on the command for mongodb-core. -* NODE-388 Changed length from method to property on order.js/unordered.js bulk operations. -* Upgraded mongodb-core to 1.1.19. - -2.0.22 2015-03-16 ------------------ -* NODE-377, fixed issue where tags would correctly be checked on secondary and nearest to filter out eligible server candidates. -* Upgraded mongodb-core to 1.1.17. - -2.0.21 2015-03-06 ------------------ -* Upgraded mongodb-core to 1.1.16 making sslValidate default to true to force validation on connection unless overriden by the user. - -2.0.20 2015-03-04 ------------------ -* Updated mongodb-core 1.1.15 to relax pickserver method. - -2.0.19 2015-03-03 ------------------ -* NODE-376 Fixes issue * Unordered batch incorrectly tracks batch size when switching batch types (Issue #1261, https://github.com/meirgottlieb) -* NODE-379 Fixes bug in cursor.count() that causes the result to always be zero for dotted collection names (Issue #1262, https://github.com/vsivsi) -* Expose MongoError from mongodb-core (Issue #1260, https://github.com/tjconcept) - -2.0.18 2015-02-27 ------------------ -* Bumped mongodb-core 1.1.14 to ensure passives are correctly added as secondaries. - -2.0.17 2015-02-27 ------------------ -* NODE-336 Added length function to ordered and unordered bulk operations to be able know the amount of current operations in bulk. -* Bumped mongodb-core 1.1.13 to ensure passives are correctly added as secondaries. - -2.0.16 2015-02-16 ------------------ -* listCollection now returns filtered result correctly removing db name for 2.6 or earlier servers. -* Bumped mongodb-core 1.1.12 to correctly work for node 0.12.0 and io.js. -* Add ability to get collection name from cursor (Issue #1253, https://github.com/vkarpov15) - -2.0.15 2015-02-02 ------------------ -* Unified behavior of listCollections results so 3.0 and pre 3.0 return same type of results. -* Bumped mongodb-core to 1.1.11 to support per document tranforms in cursors as well as relaxing the setName requirement. -* NODE-360 Aggregation cursor and command correctly passing down the maxTimeMS property. -* Added ~1.0 mongodb-tools module for test running. -* Remove the required setName for replicaset connections, if not set it will pick the first setName returned. - -2.0.14 2015-01-21 ------------------ -* Fixed some MongoClient.connect options pass through issues and added test coverage. -* Bumped mongodb-core to 1.1.9 including fixes for io.js - -2.0.13 2015-01-09 ------------------ -* Bumped mongodb-core to 1.1.8. -* Optimized query path for performance, moving Object.defineProperty outside of constructors. - -2.0.12 2014-12-22 ------------------ -* Minor fixes to listCollections to ensure correct querying of a collection when using a string. - -2.0.11 2014-12-19 ------------------ -* listCollections filters out index namespaces on < 2.8 correctly -* Bumped mongo-client to 1.1.7 - -2.0.10 2014-12-18 ------------------ -* NODE-328 fixed db.open return when no callback available issue and added test. -* NODE-327 Refactored listCollections to return cursor to support 2.8. -* NODE-327 Added listIndexes method and refactored internal methods to use the new command helper. -* NODE-335 Cannot create index for nested objects fixed by relaxing key checking for createIndex helper. -* Enable setting of connectTimeoutMS (Issue #1235, https://github.com/vkarpov15) -* Bumped mongo-client to 1.1.6 - -2.0.9 2014-12-01 ----------------- -* Bumped mongodb-core to 1.1.3 fixing global leaked variables and introducing strict across all classes. -* All classes are now strict (Issue #1233) -* NODE-324 Refactored insert/update/remove and all other crud opts to rely on internal methods to avoid any recursion. -* Fixed recursion issues in debug logging due to JSON.stringify() -* Documentation fixes (Issue #1232, https://github.com/wsmoak) -* Fix writeConcern in Db.prototype.ensureIndex (Issue #1231, https://github.com/Qard) - -2.0.8 2014-11-28 ----------------- -* NODE-322 Finished up prototype refactoring of Db class. -* NODE-322 Exposed Cursor in index.js for New Relic. - -2.0.7 2014-11-20 ----------------- -* Bumped mongodb-core to 1.1.2 fixing a UTF8 encoding issue for collection names. -* NODE-318 collection.update error while setting a function with serializeFunctions option. -* Documentation fixes. - -2.0.6 2014-11-14 ----------------- -* Refactored code to be prototype based instead of privileged methods. -* Bumped mongodb-core to 1.1.1 to take advantage of the prototype based refactorings. -* Implemented missing aspects of the CRUD specification. -* Fixed documentation issues. -* Fixed global leak REFERENCE_BY_ID in gridfs grid_store (Issue #1225, https://github.com/j) -* Fix LearnBoost/mongoose#2313: don't let user accidentally clobber geoNear params (Issue #1223, https://github.com/vkarpov15) - -2.0.5 2014-10-29 ----------------- -* Minor fixes to documentation and generation of documentation. -* NODE-306 (No results in aggregation cursor when collection name contains a dot), Merged code for cursor and aggregation cursor. - -2.0.4 2014-10-23 ----------------- -* Allow for single replicaset seed list with no setName specified (Issue #1220, https://github.com/imaman) -* Made each rewind on each call allowing for re-using the cursor. -* Fixed issue where incorrect iterations would happen on each for extensive batchSizes. -* NODE-301 specifying maxTimeMS on find causes all fields to be omitted from result. - -2.0.3 2014-10-14 ----------------- -* NODE-297 Aggregate Broken for case of pipeline with no options. - -2.0.2 2014-10-08 ----------------- -* Bumped mongodb-core to 1.0.2. -* Fixed bson module dependency issue by relying on the mongodb-core one. -* Use findOne instead of find followed by nextObject (Issue #1216, https://github.com/sergeyksv) - -2.0.1 2014-10-07 ----------------- -* Dependency fix - -2.0.0 2014-10-07 ----------------- -* First release of 2.0 driver - -2.0.0-alpha2 2014-10-02 ------------------------ -* CRUD API (insertOne, insertMany, updateOne, updateMany, removeOne, removeMany, bulkWrite, findOneAndDelete, findOneAndUpdate, findOneAndReplace) -* Cluster Management Spec compatible. - -2.0.0-alpha1 2014-09-08 ------------------------ -* Insert method allows only up 1000 pr batch for legacy as well as 2.6 mode -* Streaming behavior is 0.10.x or higher with backwards compatibility using readable-stream npm package -* Gridfs stream only available through .stream() method due to overlapping names on Gridstore object and streams in 0.10.x and higher of node -* remove third result on update and remove and return the whole result document instead (getting rid of the weird 3 result parameters) - * Might break some application -* Returns the actual mongodb-core result instead of just the number of records changed for insert/update/remove -* MongoClient only has the connect method (no ability instantiate with Server, ReplSet or similar) -* Removed Grid class -* GridStore only supports w+ for metadata updates, no appending to file as it's not thread safe and can cause corruption of the data - + seek will fail if attempt to use with w or w+ - + write will fail if attempted with w+ or r - + w+ only works for updating metadata on a file -* Cursor toArray and each resets and re-runs the cursor -* FindAndModify returns whole result document instead of just value -* Extend cursor to allow for setting all the options via methods instead of dealing with the current messed up find -* Removed db.dereference method -* Removed db.cursorInfo method -* Removed db.stats method -* Removed db.collectionNames not needed anymore as it's just a specialized case of listCollections -* Removed db.collectionInfo removed due to not being compatible with new storage engines in 2.8 as they need to use the listCollections command due to system collections not working for namespaces. -* Added db.listCollections to replace several methods above - -1.4.10 2014-09-04 ------------------ -* Fixed BSON and Kerberos compilation issues -* Bumped BSON to ~0.2 always installing latest BSON 0.2.x series -* Fixed Kerberos and bumped to 0.0.4 - -1.4.9 2014-08-26 ----------------- -* Check _bsonType for Binary (Issue #1202, https://github.com/mchapman) -* Remove duplicate Cursor constructor (Issue #1201, https://github.com/KenPowers) -* Added missing parameter in the documentation (Issue #1199, https://github.com/wpjunior) -* Documented third parameter on the update callback(Issue #1196, https://github.com/gabmontes) -* NODE-240 Operations on SSL connection hang on node 0.11.x -* NODE-235 writeResult is not being passed on when error occurs in insert -* NODE-229 Allow count to work with query hints -* NODE-233 collection.save() does not support fullResult -* NODE-244 Should parseError also emit a `disconnected` event? -* NODE-246 Cursors are inefficiently constructed and consequently cannot be promisified. -* NODE-248 Crash with X509 auth -* NODE-252 Uncaught Exception in Base.__executeAllServerSpecificErrorCallbacks -* Bumped BSON parser to 0.2.12 - - -1.4.8 2014-08-01 ----------------- -* NODE-205 correctly emit authenticate event -* NODE-210 ensure no undefined connection error when checking server state -* NODE-212 correctly inherit socketTimeoutMS from replicaset when HA process adds new servers or reconnects to existing ones -* NODE-220 don't throw error if ensureIndex errors out in Gridstore -* Updated bson to 0.2.11 to ensure correct toBSON behavior when returning non object in nested classes -* Fixed test running filters -* Wrap debug log in a call to format (Issue #1187, https://github.com/andyroyle) -* False option values should not trigger w:1 (Issue #1186, https://github.com/jsdevel) -* Fix aggregatestream.close(Issue #1194, https://github.com/jonathanong) -* Fixed parsing issue for w:0 in url parser when in connection string -* Modified collection.geoNear to support a geoJSON point or legacy coordinate pair (Issue #1198, https://github.com/mmacmillan) - -1.4.7 2014-06-18 ----------------- -* Make callbacks to be executed in right domain when server comes back up (Issue #1184, https://github.com/anton-kotenko) -* Fix issue where currentOp query against mongos would fail due to mongos passing through $readPreference field to mongod (CS-X) - -1.4.6 2014-06-12 ----------------- -* Added better support for MongoClient IP6 parsing (Issue #1181, https://github.com/micovery) -* Remove options check on index creation (Issue #1179, Issue #1183, https://github.com/jdesboeufs, https://github.com/rubenvereecken) -* Added missing type check before calling optional callback function (Issue #1180) - -1.4.5 2014-05-21 ----------------- -* Added fullResult flag to insert/update/remove which will pass raw result document back. Document contents will vary depending on the server version the driver is talking to. No attempt is made to coerce a joint response. -* Fix to avoid MongoClient.connect hanging during auth when secondaries building indexes pre 2.6. -* return the destination stream in GridStore.pipe (Issue #1176, https://github.com/iamdoron) - -1.4.4 2014-05-13 ----------------- -* Bumped BSON version to use the NaN 1.0 package, fixed strict comparison issue for ObjectID -* Removed leaking global variable (Issue #1174, https://github.com/dainis) -* MongoClient respects connectTimeoutMS for initial discovery process (NODE-185) -* Fix bug with return messages larger than 16MB but smaller than max BSON Message Size (NODE-184) - -1.4.3 2014-05-01 ----------------- -* Clone options for commands to avoid polluting original options passed from Mongoose (Issue #1171, https://github.com/vkarpov15) -* Made geoNear and geoHaystackSearch only clean out allowed options from command generation (Issue #1167) -* Fixed typo for allowDiskUse (Issue #1168, https://github.com/joaofranca) -* A 'mapReduce' function changed 'function' to instance '\' of 'Code' class (Issue #1165, https://github.com/exabugs) -* Made findAndModify set sort only when explicitly set (Issue #1163, https://github.com/sars) -* Rewriting a gridStore file by id should use a new filename if provided (Issue #1169, https://github.com/vsivsi) - -1.4.2 2014-04-15 ----------------- -* Fix for inheritance of readPreferences from MongoClient NODE-168/NODE-169 -* Merged in fix for ping strategy to avoid hitting non-pinged servers (Issue #1161, https://github.com/vaseker) -* Merged in fix for correct debug output for connection messages (Issue #1158, https://github.com/vaseker) -* Fixed global variable leak (Issue #1160, https://github.com/vaseker) - -1.4.1 2014-04-09 ----------------- -* Correctly emit joined event when primary change -* Add _id to documents correctly when using bulk operations - -1.4.0 2014-04-03 ----------------- -* All node exceptions will no longer be caught if on('error') is defined -* Added X509 auth support -* Fix for MongoClient connection timeout issue (NODE-97) -* Pass through error messages from parseError instead of just text (Issue #1125) -* Close db connection on error (Issue #1128, https://github.com/benighted) -* Fixed documentation generation -* Added aggregation cursor for 2.6 and emulated cursor for pre 2.6 (uses stream2) -* New Bulk API implementation using write commands for 2.6 and down converts for pre 2.6 -* Insert/Update/Remove using new write commands when available -* Added support for new roles based API's in 2.6 for addUser/removeUser -* Added bufferMaxEntries to start failing if the buffer hits the specified number of entries -* Upgraded BSON parser to version 0.2.7 to work with < 0.11.10 C++ API changes -* Support for OP_LOG_REPLAY flag (NODE-94) -* Fixes for SSL HA ping and discovery. -* Uses createIndexes if available for ensureIndex/createIndex -* Added parallelCollectionScan method to collection returning CommandCursor instances for cursors -* Made CommandCursor behave as Readable stream. -* Only Db honors readPreference settings, removed Server.js legacy readPreference settings due to user confusion. -* Reconnect event emitted by ReplSet/Mongos/Server after reconnect and before replaying of buffered operations. -* GridFS buildMongoObject returns error on illegal md5 (NODE-157, https://github.com/iantocristian) -* Default GridFS chunk size changed to (255 * 1024) bytes to optimize for collections defaulting to power of 2 sizes on 2.6. -* Refactored commands to all go through command function ensuring consistent command execution. -* Fixed issues where readPreferences where not correctly passed to mongos. -* Catch error == null and make err detection more prominent (NODE-130) -* Allow reads from arbiter for single server connection (NODE-117) -* Handle error coming back with no documents (NODE-130) -* Correctly use close parameter in Gridstore.write() (NODE-125) -* Throw an error on a bulk find with no selector (NODE-129, https://github.com/vkarpov15) -* Use a shallow copy of options in find() (NODE-124, https://github.com/vkarpov15) -* Fix statistical strategy (NODE-158, https://github.com/vkarpov15) -* GridFS off-by-one bug in lastChunkNumber() causes uncaught throw and data loss (Issue #1154, https://github.com/vsivsi) -* GridStore drops passed `aliases` option, always results in `null` value in GridFS files (Issue #1152, https://github.com/vsivsi) -* Remove superfluous connect object copying in index.js (Issue #1145, https://github.com/thomseddon) -* Do not return false when the connection buffer is still empty (Issue #1143, https://github.com/eknkc) -* Check ReadPreference object on ReplSet.canRead (Issue #1142, https://github.com/eknkc) -* Fix unpack error on _executeQueryCommand (Issue #1141, https://github.com/eknkc) -* Close db on failed connect so node can exit (Issue #1128, https://github.com/benighted) -* Fix global leak with _write_concern (Issue #1126, https://github.com/shanejonas) - -1.3.19 2013-08-21 ------------------ -* Correctly rethrowing errors after change from event emission to callbacks, compatibility with 0.10.X domains without breaking 0.8.X support. -* Small fix to return the entire findAndModify result as the third parameter (Issue #1068) -* No removal of "close" event handlers on server reconnect, emits "reconnect" event when reconnection happens. Reconnect Only applies for single server connections as of now as semantics for ReplSet and Mongos is not clear (Issue #1056) - -1.3.18 2013-08-10 ------------------ -* Fixed issue when throwing exceptions in MongoClient.connect/Db.open (Issue #1057) -* Fixed an issue where _events is not cleaned up correctly causing a slow steady memory leak. - -1.3.17 2013-08-07 ------------------ -* Ignore return commands that have no registered callback -* Made collection.count not use the db.command function -* Fix throw exception on ping command (Issue #1055) - -1.3.16 2013-08-02 ------------------ -* Fixes connection issue where lots of connections would happen if a server is in recovery mode during connection (Issue #1050, NODE-50, NODE-51) -* Bug in unlink mulit filename (Issue #1054) - -1.3.15 2013-08-01 ------------------ -* Memory leak issue due to node Issue #4390 where _events[id] is set to undefined instead of deleted leading to leaks in the Event Emitter over time - -1.3.14 2013-08-01 ------------------ -* Fixed issue with checkKeys where it would error on X.X - -1.3.13 2013-07-31 ------------------ -* Added override for checkKeys on insert/update (Warning will expose you to injection attacks) (Issue #1046) -* BSON size checking now done pre serialization (Issue #1037) -* Added isConnected returns false when no connection Pool exists (Issue #1043) -* Unified command handling to ensure same handling (Issue #1041, #1042) -* Correctly emit "open" and "fullsetup" across all Db's associated with Mongos, ReplSet or Server (Issue #1040) -* Correctly handles bug in authentication when attempting to connect to a recovering node in a replicaset. -* Correctly remove recovering servers from available servers in replicaset. Piggybacks on the ping command. -* Removed findAndModify chaining to be compliant with behavior in other official drivers and to fix a known mongos issue. -* Fixed issue with Kerberos authentication on Windows for re-authentication. -* Fixed Mongos failover behavior to correctly throw out old servers. -* Ensure stored queries/write ops are executed correctly after connection timeout -* Added promoteLongs option for to allow for overriding the promotion of Longs to Numbers and return the actual Long. - -1.3.12 2013-07-19 ------------------ -* Fixed issue where timeouts sometimes would behave wrongly (Issue #1032) -* Fixed bug with callback third parameter on some commands (Issue #1033) -* Fixed possible issue where killcursor command might leave hanging functions -* Fixed issue where Mongos was not correctly removing dead servers from the pool of eligable servers -* Throw error if dbName or collection name contains null character (at command level and at collection level) -* Updated bson parser to 0.2.1 with security fix and non-promotion of Long values to javascript Numbers (once a long always a long) - -1.3.11 2013-07-04 ------------------ -* Fixed errors on geoNear and geoSearch (Issue #1024, https://github.com/ebensing) -* Add driver version to export (Issue #1021, https://github.com/aheckmann) -* Add text to readpreference obedient commands (Issue #1019) -* Drivers should check the query failure bit even on getmore response (Issue #1018) -* Map reduce has incorrect expectations of 'inline' value for 'out' option (Issue #1016, https://github.com/rcotter) -* Support SASL PLAIN authentication (Issue #1009) -* Ability to use different Service Name on the driver for Kerberos Authentication (Issue #1008) -* Remove unnecessary octal literal to allow the code to run in strict mode (Issue #1005, https://github.com/jamesallardice) -* Proper handling of recovering nodes (when they go into recovery and when they return from recovery, Issue #1027) - -1.3.10 2013-06-17 ------------------ -* Guard against possible undefined in server::canCheckoutWriter (Issue #992, https://github.com/willyaranda) -* Fixed some duplicate test names (Issue #993, https://github.com/kawanet) -* Introduced write and read concerns for GridFS (Issue #996) -* Fixed commands not correctly respecting Collection level read preference (Issue #995, #999) -* Fixed issue with pool size on replicaset connections (Issue #1000) -* Execute all query commands on master switch (Issue #1002, https://github.com/fogaztuc) - -1.3.9 2013-06-05 ----------------- -* Fixed memory leak when findAndModify errors out on w>1 and chained callbacks not properly cleaned up. - -1.3.8 2013-05-31 ----------------- -* Fixed issue with socket death on windows where it emits error event instead of close event (Issue #987) -* Emit authenticate event on db after authenticate method has finished on db instance (Issue #984) -* Allows creation of MongoClient and do new MongoClient().connect(..). Emits open event when connection correct allowing for apps to react on event. - -1.3.7 2013-05-29 ----------------- -* After reconnect, tailable getMores go on inconsistent connections (Issue #981, #982, https://github.com/glasser) -* Updated Bson to 0.1.9 to fix ARM support (Issue #985) - -1.3.6 2013-05-21 ----------------- -* Fixed issue where single server reconnect attempt would throw due to missing options variable (Issue #979) -* Fixed issue where difference in ismaster server name and seed list caused connections issues, (Issue #976) - -1.3.5 2013-05-14 ----------------- -* Fixed issue where HA for replicaset would pick the same broken connection when attempting to ping the replicaset causing the replicaset to never recover. - -1.3.4 2013-05-14 ----------------- -* Fixed bug where options not correctly passed in for uri parser (Issue #973, https://github.com/supershabam) -* Fixed bug when passing a named index hint (Issue #974) - -1.3.3 2013-05-09 ----------------- -* Fixed auto-reconnect issue with single server instance. - -1.3.2 2013-05-08 ----------------- -* Fixes for an issue where replicaset would be pronounced dead when high priority primary caused double elections. - -1.3.1 2013-05-06 ----------------- -* Fix for replicaset consisting of primary/secondary/arbiter with priority applied failing to reconnect properly -* Applied auth before server instance is set as connected when single server connection -* Throw error if array of documents passed to save method - -1.3.0 2013-04-25 ----------------- -* Whole High availability handling for Replicaset, Server and Mongos connections refactored to ensure better handling of failover cases. -* Fixed issue where findAndModify would not correctly skip issuing of chained getLastError (Issue #941) -* Fixed throw error issue on errors with findAndModify during write out operation (Issue #939, https://github.com/autopulated) -* Gridstore.prototype.writeFile now returns gridstore object correctly (Issue #938) -* Kerberos support is now an optional module that allows for use of GSSAPI authentication using MongoDB Subscriber edition -* Fixed issue where cursor.toArray could blow the stack on node 0.10.X (#950) - -1.2.14 2013-03-14 ------------------ -* Refactored test suite to speed up running of replicaset tests -* Fix of async error handling when error happens in callback (Issue #909, https://github.com/medikoo) -* Corrected a slaveOk setting issue (Issue #906, #905) -* Fixed HA issue where ping's would not go to correct server on HA server connection failure. -* Uses setImmediate if on 0.10 otherwise nextTick for cursor stream -* Fixed race condition in Cursor stream (NODE-31) -* Fixed issues related to node 0.10 and process.nextTick now correctly using setImmediate where needed on node 0.10 -* Added support for maxMessageSizeBytes if available (DRIVERS-1) -* Added support for authSource (2.4) to MongoClient URL and db.authenticate method (DRIVER-69/NODE-34) -* Fixed issue in GridStore seek and GridStore read to correctly work on multiple seeks (Issue #895) - -1.2.13 2013-02-22 ------------------ -* Allow strategy 'none' for repliaset if no strategy wanted (will default to round robin selection of servers on a set readPreference) -* Fixed missing MongoErrors on some cursor methods (Issue #882) -* Correctly returning a null for the db instance on MongoClient.connect when auth fails (Issue #890) -* Added dropTarget option support for renameCollection/rename (Issue #891, help from https://github.com/jbottigliero) -* Fixed issue where connection using MongoClient.connect would fail if first server did not exist (Issue #885) - -1.2.12 2013-02-13 ------------------ -* Added limit/skip options to Collection.count (Issue #870) -* Added applySkipLimit option to Cursor.count (Issue #870) -* Enabled ping strategy as default for Replicaset if none specified (Issue #876) -* Should correctly pick nearest server for SECONDARY/SECONDARY_PREFERRED/NEAREST (Issue #878) - -1.2.11 2013-01-29 ------------------ -* Added fixes for handling type 2 binary due to PHP driver (Issue #864) -* Moved callBackStore to Base class to have single unified store (Issue #866) -* Ping strategy now reuses sockets unless they are closed by the server to avoid overhead - -1.2.10 2013-01-25 ------------------ -* Merged in SSL support for 2.4 supporting certificate validation and presenting certificates to the server. -* Only open a new HA socket when previous one dead (Issue #859, #857) -* Minor fixes - -1.2.9 2013-01-15 ----------------- -* Fixed bug in SSL support for MongoClient/Db.connect when discovering servers (Issue #849) -* Connection string with no db specified should default to admin db (Issue #848) -* Support port passed as string to Server class (Issue #844) -* Removed noOpen support for MongoClient/Db.connect as auto discovery of servers for Mongod/Mongos makes it not possible (Issue #842) -* Included toError wrapper code moved to utils.js file (Issue #839, #840) -* Rewrote cursor handling to avoid process.nextTick using trampoline instead to avoid stack overflow, speedup about 40% - -1.2.8 2013-01-07 ----------------- -* Accept function in a Map Reduce scope object not only a function string (Issue #826, https://github.com/aheckmann) -* Typo in db.authenticate caused a check (for provided connection) to return false, causing a connection AND onAll=true to be passed into __executeQueryCommand downstream (Issue #831, https://github.com/m4tty) -* Allow gridfs objects to use non ObjectID ids (Issue #825, https://github.com/nailgun) -* Removed the double wrap, by not passing an Error object to the wrap function (Issue #832, https://github.com/m4tty) -* Fix connection leak (gh-827) for HA replicaset health checks (Issue #833, https://github.com/aheckmann) -* Modified findOne to use nextObject instead of toArray avoiding a nextTick operation (Issue #836) -* Fixes for cursor stream to avoid multiple getmore issues when one in progress (Issue #818) -* Fixes .open replaying all backed up commands correctly if called after operations performed, (Issue #829 and #823) - -1.2.7 2012-12-23 ----------------- -* Rolled back batches as they hang in certain situations -* Fixes for NODE-25, keep reading from secondaries when primary goes down - -1.2.6 2012-12-21 ----------------- -* domain sockets shouldn't require a port arg (Issue #815, https://github.com/aheckmann) -* Cannot read property 'info' of null (Issue #809, https://github.com/thesmart) -* Cursor.each should work in batches (Issue #804, https://github.com/Swatinem) -* Cursor readPreference bug for non-supported read preferences (Issue #817) - -1.2.5 2012-12-12 ----------------- -* Fixed ssl regression, added more test coverage (Issue #800) -* Added better error reporting to the Db.connect if no valid serverConfig setup found (Issue #798) - -1.2.4 2012-12-11 ----------------- -* Fix to ensure authentication is correctly applied across all secondaries when using MongoClient. - -1.2.3 2012-12-10 ----------------- -* Fix for new replicaset members correctly authenticating when being added (Issue #791, https://github.com/m4tty) -* Fixed seek issue in gridstore when using stream (Issue #790) - -1.2.2 2012-12-03 ----------------- -* Fix for journal write concern not correctly being passed under some circumstances. -* Fixed correct behavior and re-auth for servers that get stepped down (Issue #779). - -1.2.1 2012-11-30 ----------------- -* Fix for double callback on insert with w:0 specified (Issue #783) -* Small cleanup of urlparser. - -1.2.0 2012-11-27 ----------------- -* Honor connectTimeoutMS option for replicasets (Issue #750, https://github.com/aheckmann) -* Fix ping strategy regression (Issue #738, https://github.com/aheckmann) -* Small cleanup of code (Issue #753, https://github.com/sokra/node-mongodb-native) -* Fixed index declaration using objects/arrays from other contexts (Issue #755, https://github.com/sokra/node-mongodb-native) -* Intermittent (and rare) null callback exception when using ReplicaSets (Issue #752) -* Force correct setting of read_secondary based on the read preference (Issue #741) -* If using read preferences with secondaries queries will not fail if primary is down (Issue #744) -* noOpen connection for Db.connect removed as not compatible with autodetection of Mongo type -* Mongos connection with auth not working (Issue #737) -* Use the connect method directly from the require. require('mongodb')("mongodb://localhost:27017/db") -* new MongoClient introduced as the point of connecting to MongoDB's instead of the Db - * open/close/db/connect methods implemented -* Implemented common URL connection format using MongoClient.connect allowing for simialar interface across all drivers. -* Fixed a bug with aggregation helper not properly accepting readPreference - -1.1.11 2012-10-10 ------------------ -* Removed strict mode and introduced normal handling of safe at DB level. - -1.1.10 2012-10-08 ------------------ -* fix Admin.serverStatus (Issue #723, https://github.com/Contra) -* logging on connection open/close(Issue #721, https://github.com/asiletto) -* more fixes for windows bson install (Issue #724) - -1.1.9 2012-10-05 ----------------- -* Updated bson to 0.1.5 to fix build problem on sunos/windows. - -1.1.8 2012-10-01 ----------------- -* Fixed db.eval to correctly handle system.js global javascript functions (Issue #709) -* Cleanup of non-closing connections (Issue #706) -* More cleanup of connections under replicaset (Issue #707, https://github.com/elbert3) -* Set keepalive on as default, override if not needed -* Cleanup of jsbon install to correctly build without install.js script (https://github.com/shtylman) -* Added domain socket support new Server("/tmp/mongodb.sock") style - -1.1.7 2012-09-10 ----------------- -* Protect against starting PingStrategy being called more than once (Issue #694, https://github.com/aheckmann) -* Make PingStrategy interval configurable (was 1 second, relaxed to 5) (Issue #693, https://github.com/aheckmann) -* Made PingStrategy api more consistant, callback to start/stop methods are optional (Issue #693, https://github.com/aheckmann) -* Proper stopping of strategy on replicaset stop -* Throw error when gridstore file is not found in read mode (Issue #702, https://github.com/jbrumwell) -* Cursor stream resume now using nextTick to avoid duplicated records (Issue #696) - -1.1.6 2012-09-01 ----------------- -* Fix for readPreference NEAREST for replicasets (Issue #693, https://github.com/aheckmann) -* Emit end correctly on stream cursor (Issue #692, https://github.com/Raynos) - -1.1.5 2012-08-29 ----------------- -* Fix for eval on replicaset Issue #684 -* Use helpful error msg when native parser not compiled (Issue #685, https://github.com/aheckmann) -* Arbiter connect hotfix (Issue #681, https://github.com/fengmk2) -* Upgraded bson parser to 0.1.2 using gyp, deprecated support for node 0.4.X -* Added name parameter to createIndex/ensureIndex to be able to override index names larger than 128 bytes -* Added exhaust option for find for feature completion (not recommended for normal use) -* Added tailableRetryInterval to find for tailable cursors to allow to control getMore retry time interval -* Fixes for read preferences when using MongoS to correctly handle no read preference set when iterating over a cursor (Issue #686) - -1.1.4 2012-08-12 ----------------- -* Added Mongos connection type with a fallback list for mongos proxies, supports ha (on by default) and will attempt to reconnect to failed proxies. -* Documents can now have a toBSON method that lets the user control the serialization behavior for documents being saved. -* Gridstore instance object now works as a readstream or writestream (thanks to code from Aaron heckmann (https://github.com/aheckmann/gridfs-stream)). -* Fix gridfs readstream (Issue #607, https://github.com/tedeh). -* Added disableDriverBSONSizeCheck property to Server.js for people who wish to push the inserts to the limit (Issue #609). -* Fixed bug where collection.group keyf given as Code is processed as a regular object (Issue #608, https://github.com/rrusso2007). -* Case mismatch between driver's ObjectID and mongo's ObjectId, allow both (Issue #618). -* Cleanup map reduce (Issue #614, https://github.com/aheckmann). -* Add proper error handling to gridfs (Issue #615, https://github.com/aheckmann). -* Ensure cursor is using same connection for all operations to avoid potential jump of servers when using replicasets. -* Date identification handled correctly in bson js parser when running in vm context. -* Documentation updates -* GridStore filename not set on read (Issue #621) -* Optimizations on the C++ bson parser to fix a potential memory leak and avoid non-needed calls -* Added support for awaitdata for tailable cursors (Issue #624) -* Implementing read preference setting at collection and cursor level - * collection.find().setReadPreference(Server.SECONDARY_PREFERRED) - * db.collection("some", {readPreference:Server.SECONDARY}) -* Replicaset now returns when the master is discovered on db.open and lets the rest of the connections happen asynchronous. - * ReplSet/ReplSetServers emits "fullsetup" when all servers have been connected to -* Prevent callback from executing more than once in getMore function (Issue #631, https://github.com/shankar0306) -* Corrupt bson messages now errors out to all callbacks and closes up connections correctly, Issue #634 -* Replica set member status update when primary changes bug (Issue #635, https://github.com/alinsilvian) -* Fixed auth to work better when multiple connections are involved. -* Default connection pool size increased to 5 connections. -* Fixes for the ReadStream class to work properly with 0.8 of Node.js -* Added explain function support to aggregation helper -* Added socketTimeoutMS and connectTimeoutMS to socket options for repl_set.js and server.js -* Fixed addUser to correctly handle changes in 2.2 for getLastError authentication required -* Added index to gridstore chunks on file_id (Issue #649, https://github.com/jacobbubu) -* Fixed Always emit db events (Issue #657) -* Close event not correctly resets DB openCalled variable to allow reconnect -* Added open event on connection established for replicaset, mongos and server -* Much faster BSON C++ parser thanks to Lucasfilm Singapore. -* Refactoring of replicaset connection logic to simplify the code. -* Add `options.connectArbiter` to decide connect arbiters or not (Issue #675) -* Minor optimization for findAndModify when not using j,w or fsync for safe - -1.0.2 2012-05-15 ----------------- -* Reconnect functionality for replicaset fix for mongodb 2.0.5 - -1.0.1 2012-05-12 ----------------- -* Passing back getLastError object as 3rd parameter on findAndModify command. -* Fixed a bunch of performance regressions in objectId and cursor. -* Fixed issue #600 allowing for single document delete to be passed in remove command. - -1.0.0 2012-04-25 ----------------- -* Fixes to handling of failover on server error -* Only emits error messages if there are error listeners to avoid uncaught events -* Server.isConnected using the server state variable not the connection pool state - -0.9.9.8 2012-04-12 ------------------- -* _id=0 is being turned into an ObjectID (Issue #551) -* fix for error in GridStore write method (Issue #559) -* Fix for reading a GridStore from arbitrary, non-chunk aligned offsets, added test (Issue #563, https://github.com/subroutine) -* Modified limitRequest to allow negative limits to pass through to Mongo, added test (Issue #561) -* Corrupt GridFS files when chunkSize < fileSize, fixed concurrency issue (Issue #555) -* Handle dead tailable cursors (Issue #568, https://github.com/aheckmann) -* Connection pools handles closing themselves down and clearing the state -* Check bson size of documents against maxBsonSize and throw client error instead of server error, (Issue #553) -* Returning update status document at the end of the callback for updates, (Issue #569) -* Refactor use of Arguments object to gain performance (Issue #574, https://github.com/AaronAsAChimp) - -0.9.9.7 2012-03-16 ------------------- -* Stats not returned from map reduce with inline results (Issue #542) -* Re-enable testing of whether or not the callback is called in the multi-chunk seek, fix small GridStore bug (Issue #543, https://github.com/pgebheim) -* Streaming large files from GridFS causes truncation (Issue #540) -* Make callback type checks agnostic to V8 context boundaries (Issue #545) -* Correctly throw error if an attempt is made to execute an insert/update/remove/createIndex/ensureIndex with safe enabled and no callback -* Db.open throws if the application attemps to call open again without calling close first - -0.9.9.6 2012-03-12 ------------------- -* BSON parser is externalized in it's own repository, currently using git master -* Fixes for Replicaset connectivity issue (Issue #537) -* Fixed issues with node 0.4.X vs 0.6.X (Issue #534) -* Removed SimpleEmitter and replaced with standard EventEmitter -* GridStore.seek fails to change chunks and call callback when in read mode (Issue #532) - -0.9.9.5 2012-03-07 ------------------- -* Merged in replSetGetStatus helper to admin class (Issue #515, https://github.com/mojodna) -* Merged in serverStatus helper to admin class (Issue #516, https://github.com/mojodna) -* Fixed memory leak in C++ bson parser (Issue #526) -* Fix empty MongoError "message" property (Issue #530, https://github.com/aheckmann) -* Cannot save files with the same file name to GridFS (Issue #531) - -0.9.9.4 2012-02-26 ------------------- -* bugfix for findAndModify: Error: corrupt bson message < 5 bytes long (Issue #519) - -0.9.9.3 2012-02-23 ------------------- -* document: save callback arguments are both undefined, (Issue #518) -* Native BSON parser install error with npm, (Issue #517) - -0.9.9.2 2012-02-17 ------------------- -* Improved detection of Buffers using Buffer.isBuffer instead of instanceof. -* Added wrap error around db.dropDatabase to catch all errors (Issue #512) -* Added aggregate helper to collection, only for MongoDB >= 2.1 - -0.9.9.1 2012-02-15 ------------------- -* Better handling of safe when using some commands such as createIndex, ensureIndex, addUser, removeUser, createCollection. -* Mapreduce now throws error if out parameter is not specified. - -0.9.9 2012-02-13 ----------------- -* Added createFromTime method on ObjectID to allow for queries against _id more easily using the timestamp. -* Db.close(true) now makes connection unusable as it's been force closed by app. -* Fixed mapReduce and group functions to correctly send slaveOk on queries. -* Fixes for find method to correctly work with find(query, fields, callback) (Issue #506). -* A fix for connection error handling when using the SSL on MongoDB. - -0.9.8-7 2012-02-06 ------------------- -* Simplified findOne to use the find command instead of the custom code (Issue #498). -* BSON JS parser not also checks for _bsonType variable in case BSON object is in weird scope (Issue #495). - -0.9.8-6 2012-02-04 ------------------- -* Removed the check for replicaset change code as it will never work with node.js. - -0.9.8-5 2012-02-02 ------------------- -* Added geoNear command to Collection. -* Added geoHaystackSearch command to Collection. -* Added indexes command to collection to retrieve the indexes on a Collection. -* Added stats command to collection to retrieve the statistics on a Collection. -* Added listDatabases command to admin object to allow retrieval of all available dbs. -* Changed createCreateIndexCommand to work better with options. -* Fixed dereference method on Db class to correctly dereference Db reference objects. -* Moved connect object onto Db class(Db.connect) as well as keeping backward compatibility. -* Removed writeBuffer method from gridstore, write handles switching automatically now. -* Changed readBuffer to read on Gridstore, Gridstore now only supports Binary Buffers no Strings anymore. -* Moved Long class to bson directory. - -0.9.8-4 2012-01-28 ------------------- -* Added reIndex command to collection and db level. -* Added support for $returnKey, $maxScan, $min, $max, $showDiskLoc, $comment to cursor and find/findOne methods. -* Added dropDups and v option to createIndex and ensureIndex. -* Added isCapped method to Collection. -* Added indexExists method to Collection. -* Added findAndRemove method to Collection. -* Fixed bug for replicaset connection when no active servers in the set. -* Fixed bug for replicaset connections when errors occur during connection. -* Merged in patch for BSON Number handling from Lee Salzman, did some small fixes and added test coverage. - -0.9.8-3 2012-01-21 ------------------- -* Workaround for issue with Object.defineProperty (Issue #484) -* ObjectID generation with date does not set rest of fields to zero (Issue #482) - -0.9.8-2 2012-01-20 ------------------- -* Fixed a missing this in the ReplSetServers constructor. - -0.9.8-1 2012-01-17 ------------------- -* FindAndModify bug fix for duplicate errors (Issue #481) - -0.9.8 2012-01-17 ----------------- -* Replicasets now correctly adjusts to live changes in the replicaset configuration on the servers, reconnecting correctly. - * Set the interval for checking for changes setting the replicaSetCheckInterval property when creating the ReplSetServers instance or on db.serverConfig.replicaSetCheckInterval. (default 1000 miliseconds) -* Fixes formattedOrderClause in collection.js to accept a plain hash as a parameter (Issue #469) https://github.com/tedeh -* Removed duplicate code for formattedOrderClause and moved to utils module -* Pass in poolSize for ReplSetServers to set default poolSize for new replicaset members -* Bug fix for BSON JS deserializer. Isolating the eval functions in separate functions to avoid V8 deoptimizations -* Correct handling of illegal BSON messages during deserialization -* Fixed Infinite loop when reading GridFs file with no chunks (Issue #471) -* Correctly update existing user password when using addUser (Issue #470) - -0.9.7.3-5 2012-01-04 --------------------- -* Fix for RegExp serialization for 0.4.X where typeof /regexp/ == 'function' vs in 0.6.X typeof /regexp/ == 'object' -* Don't allow keepAlive and setNoDelay for 0.4.X as it throws errors - -0.9.7.3-4 2012-01-04 --------------------- -* Chased down potential memory leak on findAndModify, Issue #467 (node.js removeAllListeners leaves the key in the _events object, node.js bug on eventlistener?, leads to extremely slow memory leak on listener object) -* Sanity checks for GridFS performance with benchmark added - -0.9.7.3-3 2012-01-04 --------------------- -* Bug fixes for performance issues going form 0.9.6.X to 0.9.7.X on linux -* BSON bug fixes for performance - -0.9.7.3-2 2012-01-02 --------------------- -* Fixed up documentation to reflect the preferred way of instantiating bson types -* GC bug fix for JS bson parser to avoid stop-and-go GC collection - -0.9.7.3-1 2012-01-02 --------------------- -* Fix to make db.bson_serializer and db.bson_deserializer work as it did previously - -0.9.7.3 2011-12-30 --------------------- -* Moved BSON_BINARY_SUBTYPE_DEFAULT from BSON object to Binary object and removed the BSON_BINARY_ prefixes -* Removed Native BSON types, C++ parser uses JS types (faster due to cost of crossing the JS-C++ barrier for each call) -* Added build fix for 0.4.X branch of Node.js where GetOwnPropertyNames is not defined in v8 -* Fix for wire protocol parser for corner situation where the message is larger than the maximum socket buffer in node.js (Issue #464, #461, #447) -* Connection pool status set to connected on poolReady, isConnected returns false on anything but connected status (Issue #455) - -0.9.7.2-5 2011-12-22 --------------------- -* Brand spanking new Streaming Cursor support Issue #458 (https://github.com/christkv/node-mongodb-native/pull/458) thanks to Mr Aaron Heckmann - -0.9.7.2-4 2011-12-21 --------------------- -* Refactoring of callback code to work around performance regression on linux -* Fixed group function to correctly use the command mode as default - -0.9.7.2-3 2011-12-18 --------------------- -* Fixed error handling for findAndModify while still working for mongodb 1.8.6 (Issue #450). -* Allow for force send query to primary, pass option (read:'primary') on find command. - * ``find({a:1}, {read:'primary'}).toArray(function(err, items) {});`` - -0.9.7.2-2 2011-12-16 --------------------- -* Fixes infinite streamRecords QueryFailure fix when using Mongos (Issue #442) - -0.9.7.2-1 2011-12-16 --------------------- -* ~10% perf improvement for ObjectId#toHexString (Issue #448, https://github.com/aheckmann) -* Only using process.nextTick on errors emitted on callbacks not on all parsing, reduces number of ticks in the driver -* Changed parsing off bson messages to use process.nextTick to do bson parsing in batches if the message is over 10K as to yield more time to the event look increasing concurrency on big mongoreply messages with multiple documents - -0.9.7.2 2011-12-15 ------------------- -* Added SSL support for future version of mongodb (VERY VERY EXPERIMENTAL) - * pass in the ssl:true option to the server or replicaset server config to enable - * a bug either in mongodb or node.js does not allow for more than 1 connection pr db instance (poolSize:1). -* Added getTimestamp() method to objectID that returns a date object -* Added finalize function to collection.group - * function group (keys, condition, initial, reduce, finalize, command, callback) -* Reaper no longer using setTimeout to handle reaping. Triggering is done in the general flow leading to predictable behavior. - * reaperInterval, set interval for reaper (default 10000 miliseconds) - * reaperTimeout, set timeout for calls (default 30000 miliseconds) - * reaper, enable/disable reaper (default false) -* Work around for issues with findAndModify during high concurrency load, insure that the behavior is the same across the 1.8.X branch and 2.X branch of MongoDb -* Reworked multiple db's sharing same connection pool to behave correctly on error, timeout and close -* EnsureIndex command can be executed without a callback (Issue #438) -* Eval function no accepts options including nolock (Issue #432) - * eval(code, parameters, options, callback) (where options = {nolock:true}) - -0.9.7.1-4 2011-11-27 --------------------- -* Replaced install.sh with install.js to install correctly on all supported os's - -0.9.7.1-3 2011-11-27 --------------------- -* Fixes incorrect scope for ensureIndex error wrapping (Issue #419) https://github.com/ritch - -0.9.7.1-2 2011-11-27 --------------------- -* Set statistical selection strategy as default for secondary choice. - -0.9.7.1-1 2011-11-27 --------------------- -* Better handling of single server reconnect (fixes some bugs) -* Better test coverage of single server failure -* Correct handling of callbacks on replicaset servers when firewall dropping packets, correct reconnect - -0.9.7.1 2011-11-24 ------------------- -* Better handling of dead server for single server instances -* FindOne and find treats selector == null as {}, Issue #403 -* Possible to pass in a strategy for the replicaset to pick secondary reader node - * parameter strategy - * ping (default), pings the servers and picks the one with the lowest ping time - * statistical, measures each request and pick the one with the lowest mean and std deviation -* Set replicaset read preference replicaset.setReadPreference() - * Server.READ_PRIMARY (use primary server for reads) - * Server.READ_SECONDARY (from a secondary server (uses the strategy set)) - * tags, {object of tags} -* Added replay of commands issued to a closed connection when the connection is re-established -* Fix isConnected and close on unopened connections. Issue #409, fix by (https://github.com/sethml) -* Moved reaper to db.open instead of constructor (Issue #406) -* Allows passing through of socket connection settings to Server or ReplSetServer under the option socketOptions - * timeout = set seconds before connection times out (default 0) - * noDelay = Disables the Nagle algorithm (default true) - * keepAlive = Set if keepAlive is used (default 0, which means no keepAlive, set higher than 0 for keepAlive) - * encoding = ['ascii', 'utf8', or 'base64'] (default null) -* Fixes for handling of errors during shutdown off a socket connection -* Correctly applies socket options including timeout -* Cleanup of test management code to close connections correctly -* Handle parser errors better, closing down the connection and emitting an error -* Correctly emit errors from server.js only wrapping errors that are strings - -0.9.7 2011-11-10 ----------------- -* Added priority setting to replicaset manager -* Added correct handling of passive servers in replicaset -* Reworked socket code for simpler clearer handling -* Correct handling of connections in test helpers -* Added control of retries on failure - * control with parameters retryMiliSeconds and numberOfRetries when creating a db instance -* Added reaper that will timeout and cleanup queries that never return - * control with parameters reaperInterval and reaperTimeout when creating a db instance -* Refactored test helper classes for replicaset tests -* Allows raw (no bson parser mode for insert, update, remove, find and findOne) - * control raw mode passing in option raw:true on the commands - * will return buffers with the binary bson objects -* Fixed memory leak in cursor.toArray -* Fixed bug in command creation for mongodb server with wrong scope of call -* Added db(dbName) method to db.js to allow for reuse of connections against other databases -* Serialization of functions in an object is off by default, override with parameter - * serializeFunctions [true/false] on db level, collection level or individual insert/update/findAndModify -* Added Long.fromString to c++ class and fixed minor bug in the code (Test case for $gt operator on 64-bit integers, Issue #394) -* FindOne and find now share same code execution and will work in the same manner, Issue #399 -* Fix for tailable cursors, Issue #384 -* Fix for Cursor rewind broken, Issue #389 -* Allow Gridstore.exist to query using regexp, Issue #387, fix by (https://github.com/kaij) -* Updated documentation on https://github.com/christkv/node-mongodb-native -* Fixed toJSON methods across all objects for BSON, Binary return Base64 Encoded data - -0.9.6-22 2011-10-15 -------------------- -* Fixed bug in js bson parser that could cause wrong object size on serialization, Issue #370 -* Fixed bug in findAndModify that did not throw error on replicaset timeout, Issue #373 - -0.9.6-21 2011-10-05 -------------------- -* Reworked reconnect code to work correctly -* Handling errors in different parts of the code to ensure that it does not lock the connection -* Consistent error handling for Object.createFromHexString for JS and C++ - -0.9.6-20 2011-10-04 -------------------- -* Reworked bson.js parser to get rid off Array.shift() due to it allocating new memory for each call. Speedup varies between 5-15% depending on doc -* Reworked bson.cc to throw error when trying to serialize js bson types -* Added MinKey, MaxKey and Double support for JS and C++ parser -* Reworked socket handling code to emit errors on unparsable messages -* Added logger option for Db class, lets you pass in a function in the shape - { - log : function(message, object) {}, - error : function(errorMessage, errorObject) {}, - debug : function(debugMessage, object) {}, - } - - Usage is new Db(new Server(..), {logger: loggerInstance}) - -0.9.6-19 2011-09-29 -------------------- -* Fixing compatibility issues between C++ bson parser and js parser -* Added Symbol support to C++ parser -* Fixed socket handling bug for seldom misaligned message from mongodb -* Correctly handles serialization of functions using the C++ bson parser - -0.9.6-18 2011-09-22 -------------------- -* Fixed bug in waitForConnection that would lead to 100% cpu usage, Issue #352 - -0.9.6-17 2011-09-21 -------------------- -* Fixed broken exception test causing bamboo to hang -* Handling correctly command+lastError when both return results as in findAndModify, Issue #351 - -0.9.6-16 2011-09-14 -------------------- -* Fixing a bunch of issues with compatibility with MongoDB 2.0.X branch. Some fairly big changes in behavior from 1.8.X to 2.0.X on the server. -* Error Connection MongoDB V2.0.0 with Auth=true, Issue #348 - -0.9.6-15 2011-09-09 -------------------- -* Fixed issue where pools would not be correctly cleaned up after an error, Issue #345 -* Fixed authentication issue with secondary servers in Replicaset, Issue #334 -* Duplicate replica-set servers when omitting port, Issue #341 -* Fixing findAndModify to correctly work with Replicasets ensuring proper error handling, Issue #336 -* Merged in code from (https://github.com/aheckmann) that checks for global variable leaks - -0.9.6-14 2011-09-05 -------------------- -* Minor fixes for error handling in cursor streaming (https://github.com/sethml), Issue #332 -* Minor doc fixes -* Some more cursor sort tests added, Issue #333 -* Fixes to work with 0.5.X branch -* Fix Db not removing reconnect listener from serverConfig, (https://github.com/sbrekken), Issue #337 -* Removed node_events.h includes (https://github.com/jannehietamaki), Issue #339 -* Implement correct safe/strict mode for findAndModify. - -0.9.6-13 2011-08-24 -------------------- -* Db names correctly error checked for illegal characters - -0.9.6-12 2011-08-24 -------------------- -* Nasty bug in GridFS if you changed the default chunk size -* Fixed error handling bug in findOne - -0.9.6-11 2011-08-23 -------------------- -* Timeout option not correctly making it to the cursor, Issue #320, Fix from (https://github.com/year2013) -* Fixes for memory leaks when using buffers and C++ parser -* Fixes to make tests pass on 0.5.X -* Cleanup of bson.js to remove duplicated code paths -* Fix for errors occurring in ensureIndex, Issue #326 -* Removing require.paths to make tests work with the 0.5.X branch - -0.9.6-10 2011-08-11 -------------------- -* Specific type Double for capped collections (https://github.com/mbostock), Issue #312 -* Decorating Errors with all all object info from Mongo (https://github.com/laurie71), Issue #308 -* Implementing fixes for mongodb 1.9.1 and higher to make tests pass -* Admin validateCollection now takes an options argument for you to pass in full option -* Implemented keepGoing parameter for mongodb 1.9.1 or higher, Issue #310 -* Added test for read_secondary count issue, merged in fix from (https://github.com/year2013), Issue #317 - -0.9.6-9 -------- -* Bug fix for bson parsing the key '':'' correctly without crashing - -0.9.6-8 -------- -* Changed to using node.js crypto library MD5 digest -* Connect method support documented mongodb: syntax by (https://github.com/sethml) -* Support Symbol type for BSON, serializes to it's own type Symbol, Issue #302, #288 -* Code object without scope serializing to correct BSON type -* Lot's of fixes to avoid double callbacks (https://github.com/aheckmann) Issue #304 -* Long deserializes as Number for values in the range -2^53 to 2^53, Issue #305 (https://github.com/sethml) -* Fixed C++ parser to reflect JS parser handling of long deserialization -* Bson small optimizations - -0.9.6-7 2011-07-13 ------------------- -* JS Bson deserialization bug #287 - -0.9.6-6 2011-07-12 ------------------- -* FindAndModify not returning error message as other methods Issue #277 -* Added test coverage for $push, $pushAll and $inc atomic operations -* Correct Error handling for non 12/24 bit ids on Pure JS ObjectID class Issue #276 -* Fixed terrible deserialization bug in js bson code #285 -* Fix by andrewjstone to avoid throwing errors when this.primary not defined - -0.9.6-5 2011-07-06 ------------------- -* Rewritten BSON js parser now faster than the C parser on my core2duo laptop -* Added option full to indexInformation to get all index info Issue #265 -* Passing in ObjectID for new Gridstore works correctly Issue #272 - -0.9.6-4 2011-07-01 ------------------- -* Added test and bug fix for insert/update/remove without callback supplied - -0.9.6-3 2011-07-01 ------------------- -* Added simple grid class called Grid with put, get, delete methods -* Fixed writeBuffer/readBuffer methods on GridStore so they work correctly -* Automatic handling of buffers when using write method on GridStore -* GridStore now accepts a ObjectID instead of file name for write and read methods -* GridStore.list accepts id option to return of file ids instead of filenames -* GridStore close method returns document for the file allowing user to reference _id field - -0.9.6-2 2011-06-30 ------------------- -* Fixes for reconnect logic for server object (replays auth correctly) -* More testcases for auth -* Fixes in error handling for replicaset -* Fixed bug with safe parameter that would fail to execute safe when passing w or wtimeout -* Fixed slaveOk bug for findOne method -* Implemented auth support for replicaset and test cases -* Fixed error when not passing in rs_name - -0.9.6-1 2011-06-25 ------------------- -* Fixes for test to run properly using c++ bson parser -* Fixes for dbref in native parser (correctly handles ref without db component) -* Connection fixes for replicasets to avoid runtime conditions in cygwin (https://github.com/vincentcr) -* Fixes for timestamp in js bson parser (distinct timestamp type now) - -0.9.6 2011-06-21 ----------------- -* Worked around npm version handling bug -* Race condition fix for cygwin (https://github.com/vincentcr) - -0.9.5-1 2011-06-21 ------------------- -* Extracted Timestamp as separate class for bson js parser to avoid instanceof problems -* Fixed driver strict mode issue - -0.9.5 2011-06-20 ----------------- -* Replicaset support (failover and reading from secondary servers) -* Removed ServerPair and ServerCluster -* Added connection pool functionality -* Fixed serious bug in C++ bson parser where bytes > 127 would generate 2 byte sequences -* Allows for forcing the server to assign ObjectID's using the option {forceServerObjectId: true} - -0.6.8 ------ -* Removed multiple message concept from bson -* Changed db.open(db) to be db.open(err, db) - -0.1 2010-01-30 --------------- -* Initial release support of driver using native node.js interface -* Supports gridfs specification -* Supports admin functionality diff --git a/ts-ticket-office-service/node_modules/mongodb-core/LICENSE b/ts-ticket-office-service/node_modules/mongodb/LICENSE.md similarity index 100% rename from ts-ticket-office-service/node_modules/mongodb-core/LICENSE rename to ts-ticket-office-service/node_modules/mongodb/LICENSE.md diff --git a/ts-ticket-office-service/node_modules/mongodb/Makefile b/ts-ticket-office-service/node_modules/mongodb/Makefile deleted file mode 100644 index 36e120248..000000000 --- a/ts-ticket-office-service/node_modules/mongodb/Makefile +++ /dev/null @@ -1,11 +0,0 @@ -NODE = node -NPM = npm -JSDOC = jsdoc -name = all - -generate_docs: - # cp -R ./HISTORY.md ./docs/content/meta/release-notes.md - hugo -s docs/reference -d ../../public - $(JSDOC) -c conf.json -t docs/jsdoc-template/ -d ./public/api - cp -R ./public/api/scripts ./public/. - cp -R ./public/api/styles ./public/. diff --git a/ts-ticket-office-service/node_modules/mongodb/README.md b/ts-ticket-office-service/node_modules/mongodb/README.md index 3dce17192..1811de369 100644 --- a/ts-ticket-office-service/node_modules/mongodb/README.md +++ b/ts-ticket-office-service/node_modules/mongodb/README.md @@ -1,415 +1,280 @@ -[![NPM](https://nodei.co/npm/mongodb.png?downloads=true&downloadRank=true)](https://nodei.co/npm/mongodb/) [![NPM](https://nodei.co/npm-dl/mongodb.png?months=6&height=3)](https://nodei.co/npm/mongodb/) +# MongoDB NodeJS Driver -[![Build Status](https://secure.travis-ci.org/mongodb/node-mongodb-native.svg?branch=2.1)](http://travis-ci.org/mongodb/node-mongodb-native) -[![Coverage Status](https://coveralls.io/repos/github/mongodb/node-mongodb-native/badge.svg?branch=2.1)](https://coveralls.io/github/mongodb/node-mongodb-native?branch=2.1) -[![Gitter](https://badges.gitter.im/Join%20Chat.svg)](https://gitter.im/mongodb/node-mongodb-native?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge) +The official [MongoDB](https://www.mongodb.com/) driver for Node.js. -# Description +**Upgrading to version 4? Take a look at our [upgrade guide here](https://github.com/mongodb/node-mongodb-native/blob/HEAD/etc/notes/CHANGES_4.0.0.md)!** -The official [MongoDB](https://www.mongodb.com/) driver for Node.js. Provides a high-level API on top of [mongodb-core](https://www.npmjs.com/package/mongodb-core) that is meant for end users. +## Quick Links -## MongoDB Node.JS Driver - -| what | where | -|---------------|------------------------------------------------| -| documentation | http://mongodb.github.io/node-mongodb-native/ | -| api-doc | http://mongodb.github.io/node-mongodb-native/2.2/api/ | -| source | https://github.com/mongodb/node-mongodb-native | -| mongodb | http://www.mongodb.org/ | - -### Blogs of Engineers involved in the driver -- Christian Kvalheim [@christkv](https://twitter.com/christkv) +| what | where | +| ------------- | ------------------------------------------------------------------------------------------------------- | +| documentation | [docs.mongodb.com/drivers/node](https://docs.mongodb.com/drivers/node) | +| api-doc | [mongodb.github.io/node-mongodb-native/](https://mongodb.github.io/node-mongodb-native/) | +| npm package | [www.npmjs.com/package/mongodb](https://www.npmjs.com/package/mongodb) | +| source | [github.com/mongodb/node-mongodb-native](https://github.com/mongodb/node-mongodb-native) | +| mongodb | [www.mongodb.com](https://www.mongodb.com) | +| changelog | [HISTORY.md](https://github.com/mongodb/node-mongodb-native/blob/HEAD/HISTORY.md) | +| upgrade to v4 | [etc/notes/CHANGES_4.0.0.md](https://github.com/mongodb/node-mongodb-native/blob/HEAD/etc/notes/CHANGES_4.0.0.md) | +| contributing | [CONTRIBUTING.md](https://github.com/mongodb/node-mongodb-native/blob/HEAD/CONTRIBUTING.md) | ### Bugs / Feature Requests -Think you’ve found a bug? Want to see a new feature in node-mongodb-native? Please open a +Think you’ve found a bug? Want to see a new feature in `node-mongodb-native`? Please open a case in our issue management tool, JIRA: -- Create an account and login . -- Navigate to the NODE project . +- Create an account and login [jira.mongodb.org](https://jira.mongodb.org). +- Navigate to the NODE project [jira.mongodb.org/browse/NODE](https://jira.mongodb.org/browse/NODE). - Click **Create Issue** - Please provide as much information as possible about the issue type and how to reproduce it. Bug reports in JIRA for all driver projects (i.e. NODE, PYTHON, CSHARP, JAVA) and the Core Server (i.e. SERVER) project are **public**. -### Questions and Bug Reports +### Support / Feedback - * mailing list: https://groups.google.com/forum/#!forum/node-mongodb-native - * jira: http://jira.mongodb.org/ +For issues with, questions about, or feedback for the Node.js driver, please look into our [support channels](https://docs.mongodb.com/manual/support). Please do not email any of the driver developers directly with issues or questions - you're more likely to get an answer on the [MongoDB Community Forums](https://community.mongodb.com/tags/c/drivers-odms-connectors/7/node-js-driver). ### Change Log -http://jira.mongodb.org/browse/NODE +Change history can be found in [`HISTORY.md`](https://github.com/mongodb/node-mongodb-native/blob/HEAD/HISTORY.md). -# Installation +### Compatibility -The recommended way to get started using the Node.js 2.0 driver is by using the `NPM` (Node Package Manager) to install the dependency in your project. +For version compatibility matrices, please refer to the following links: -## MongoDB Driver +- [MongoDB](https://docs.mongodb.com/drivers/node/current/compatibility/#mongodb-compatibility) +- [NodeJS](https://docs.mongodb.com/drivers/node/current/compatibility/#language-compatibility) -Given that you have created your own project using `npm init` we install the mongodb driver and it's dependencies by executing the following `NPM` command. +#### Typescript Version -``` -npm install mongodb --save -``` +We recommend using the latest version of typescript, however we currently ensure the driver's public types compile against `typescript@4.1.6`. +This is the lowest typescript version guaranteed to work with our driver: older versions may or may not work - use at your own risk. +Since typescript [does not restrict breaking changes to major versions](https://github.com/Microsoft/TypeScript/wiki/Breaking-Changes) we consider this support best effort. +If you run into any unexpected compiler failures against our supported TypeScript versions please let us know by filing an issue on our [JIRA](https://jira.mongodb.org/browse/NODE). -This will download the MongoDB driver and add a dependency entry in your `package.json` file. +## Installation -## Troubleshooting +The recommended way to get started using the Node.js 4.x driver is by using the `npm` (Node Package Manager) to install the dependency in your project. -The MongoDB driver depends on several other packages. These are. +After you've created your own project using `npm init`, you can run: -* mongodb-core -* bson -* kerberos -* node-gyp +```bash +npm install mongodb +# or ... +yarn add mongodb +``` -The `kerberos` package is a C++ extension that requires a build environment to be installed on your system. You must be able to build node.js itself to be able to compile and install the `kerberos` module. Furthermore the `kerberos` module requires the MIT Kerberos package to correctly compile on UNIX operating systems. Consult your UNIX operation system package manager what libraries to install. +This will download the MongoDB driver and add a dependency entry in your `package.json` file. -{{% note class="important" %}} -Windows already contains the SSPI API used for Kerberos authentication. However you will need to install a full compiler tool chain using visual studio C++ to correctly install the kerberos extension. -{{% /note %}} +If you are a Typescript user, you will need the Node.js type definitions to use the driver's definitions: -### Diagnosing on UNIX +```sh +npm install -D @types/node +``` -If you don’t have the build essentials it won’t build. In the case of linux you will need gcc and g++, node.js with all the headers and python. The easiest way to figure out what’s missing is by trying to build the kerberos project. You can do this by performing the following steps. +## Troubleshooting -``` -git clone https://github.com/christkv/kerberos.git -cd kerberos -npm install -``` +The MongoDB driver depends on several other packages. These are: -If all the steps complete you have the right toolchain installed. If you get node-gyp not found you need to install it globally by doing. +- [bson](https://github.com/mongodb/js-bson) +- [bson-ext](https://github.com/mongodb-js/bson-ext) +- [kerberos](https://github.com/mongodb-js/kerberos) +- [mongodb-client-encryption](https://github.com/mongodb/libmongocrypt#readme) -``` -npm install -g node-gyp -``` +Some of these packages include native C++ extensions. Consult the [trouble shooting guide here](https://github.com/mongodb/node-mongodb-native/blob/HEAD/etc/notes/native-extensions.md) if you run into issues. -If correctly compiles and runs the tests you are golden. We can now try to install the mongod driver by performing the following command. +## Quick Start -``` -cd yourproject -npm install mongodb --save -``` +This guide will show you how to set up a simple application using Node.js and MongoDB. Its scope is only how to set up the driver and perform the simple CRUD operations. For more in-depth coverage, see the [official documentation](https://docs.mongodb.com/drivers/node/). -If it still fails the next step is to examine the npm log. Rerun the command but in this case in verbose mode. +### Create the `package.json` file -``` -npm --loglevel verbose install mongodb +First, create a directory where your application will live. + +```bash +mkdir myProject +cd myProject ``` -This will print out all the steps npm is performing while trying to install the module. +Enter the following command and answer the questions to create the initial structure for your new project: -### Diagnosing on Windows +```bash +npm init -y +``` -A known compiler tool chain known to work for compiling `kerberos` on windows is the following. +Next, install the driver as a dependency. -* Visual Studio c++ 2010 (do not use higher versions) -* Windows 7 64bit SDK -* Python 2.7 or higher +```bash +npm install mongodb +``` -Open visual studio command prompt. Ensure node.exe is in your path and install node-gyp. +### Start a MongoDB Server -``` -npm install -g node-gyp -``` +For complete MongoDB installation instructions, see [the manual](https://docs.mongodb.org/manual/installation/). -Next you will have to build the project manually to test it. Use any tool you use with git and grab the repo. +1. Download the right MongoDB version from [MongoDB](https://www.mongodb.org/downloads) +2. Create a database directory (in this case under **/data**). +3. Install and start a `mongod` process. -``` -git clone https://github.com/christkv/kerberos.git -cd kerberos -npm install -node-gyp rebuild +```bash +mongod --dbpath=/data ``` -This should rebuild the driver successfully if you have everything set up correctly. +You should see the **mongod** process start up and print some status information. -### Other possible issues +### Connect to MongoDB -Your python installation might be hosed making gyp break. I always recommend that you test your deployment environment first by trying to build node itself on the server in question as this should unearth any issues with broken packages (and there are a lot of broken packages out there). +Create a new **app.js** file and add the following code to try out some basic CRUD +operations using the MongoDB driver. -Another thing is to ensure your user has write permission to wherever the node modules are being installed. +Add code to connect to the server and the database **myProject**: -QuickStart -========== -The quick start guide will show you how to setup a simple application using node.js and MongoDB. Its scope is only how to set up the driver and perform the simple crud operations. For more in depth coverage we encourage reading the tutorials. +> **NOTE:** All the examples below use async/await syntax. +> +> However, all async API calls support an optional callback as the final argument, +> if a callback is provided a Promise will not be returned. -Create the package.json file ----------------------------- -Let's create a directory where our application will live. In our case we will put this under our projects directory. +```js +const { MongoClient } = require('mongodb'); +// or as an es module: +// import { MongoClient } from 'mongodb' -``` -mkdir myproject -cd myproject -``` +// Connection URL +const url = 'mongodb://localhost:27017'; +const client = new MongoClient(url); -Enter the following command and answer the questions to create the initial structure for your new project +// Database Name +const dbName = 'myProject'; -``` -npm init -``` +async function main() { + // Use connect method to connect to the server + await client.connect(); + console.log('Connected successfully to server'); + const db = client.db(dbName); + const collection = db.collection('documents'); -Next we need to edit the generated package.json file to add the dependency for the MongoDB driver. The package.json file below is just an example and your will look different depending on how you answered the questions after entering `npm init` + // the following code examples can be pasted here... -``` -{ - "name": "myproject", - "version": "1.0.0", - "description": "My first project", - "main": "index.js", - "repository": { - "type": "git", - "url": "git://github.com/christkv/myfirstproject.git" - }, - "dependencies": { - "mongodb": "~2.0" - }, - "author": "Christian Kvalheim", - "license": "Apache 2.0", - "bugs": { - "url": "https://github.com/christkv/myfirstproject/issues" - }, - "homepage": "https://github.com/christkv/myfirstproject" + return 'done.'; } -``` - -Save the file and return to the shell or command prompt and use **NPM** to install all the dependencies. +main() + .then(console.log) + .catch(console.error) + .finally(() => client.close()); ``` -npm install -``` - -You should see **NPM** download a lot of files. Once it's done you'll find all the downloaded packages under the **node_modules** directory. -Booting up a MongoDB Server ---------------------------- -Let's boot up a MongoDB server instance. Download the right MongoDB version from [MongoDB](http://www.mongodb.org), open a new shell or command line and ensure the **mongod** command is in the shell or command line path. Now let's create a database directory (in our case under **/data**). +Run your app from the command line with: -``` -mongod --dbpath=/data --port 27017 +```bash +node app.js ``` -You should see the **mongod** process start up and print some status information. +The application should print **Connected successfully to server** to the console. -Connecting to MongoDB ---------------------- -Let's create a new **app.js** file that we will use to show the basic CRUD operations using the MongoDB driver. +### Insert a Document -First let's add code to connect to the server and the database **myproject**. +Add to **app.js** the following function which uses the **insertMany** +method to add three documents to the **documents** collection. ```js -var MongoClient = require('mongodb').MongoClient - , assert = require('assert'); - -// Connection URL -var url = 'mongodb://localhost:27017/myproject'; -// Use connect method to connect to the Server -MongoClient.connect(url, function(err, db) { - assert.equal(null, err); - console.log("Connected correctly to server"); - - db.close(); -}); +const insertResult = await collection.insertMany([{ a: 1 }, { a: 2 }, { a: 3 }]); +console.log('Inserted documents =>', insertResult); ``` -Given that you booted up the **mongod** process earlier the application should connect successfully and print **Connected correctly to server** to the console. +The **insertMany** command returns an object with information about the insert operations. -Let's Add some code to show the different CRUD operations available. +### Find All Documents -Inserting a Document --------------------- -Let's create a function that will insert some documents for us. +Add a query that returns all the documents. ```js -var insertDocuments = function(db, callback) { - // Get the documents collection - var collection = db.collection('documents'); - // Insert some documents - collection.insertMany([ - {a : 1}, {a : 2}, {a : 3} - ], function(err, result) { - assert.equal(err, null); - assert.equal(3, result.result.n); - assert.equal(3, result.ops.length); - console.log("Inserted 3 documents into the document collection"); - callback(result); - }); -} +const findResult = await collection.find({}).toArray(); +console.log('Found documents =>', findResult); ``` -The insert command will return a results object that contains several fields that might be useful. +This query returns all the documents in the **documents** collection. +If you add this below the insertMany example you'll see the document's you've inserted. -* **result** Contains the result document from MongoDB -* **ops** Contains the documents inserted with added **_id** fields -* **connection** Contains the connection used to perform the insert +### Find Documents with a Query Filter -Let's add call the **insertDocuments** command to the **MongoClient.connect** method callback. +Add a query filter to find only documents which meet the query criteria. ```js -var MongoClient = require('mongodb').MongoClient - , assert = require('assert'); - -// Connection URL -var url = 'mongodb://localhost:27017/myproject'; -// Use connect method to connect to the Server -MongoClient.connect(url, function(err, db) { - assert.equal(null, err); - console.log("Connected correctly to server"); - - insertDocuments(db, function() { - db.close(); - }); -}); +const filteredDocs = await collection.find({ a: 3 }).toArray(); +console.log('Found documents filtered by { a: 3 } =>', filteredDocs); ``` -We can now run the update **app.js** file. +Only the documents which match `'a' : 3` should be returned. -``` -node app.js -``` +### Update a document -You should see the following output after running the **app.js** file. +The following operation updates a document in the **documents** collection. -``` -Connected correctly to server -Inserted 3 documents into the document collection +```js +const updateResult = await collection.updateOne({ a: 3 }, { $set: { b: 1 } }); +console.log('Updated documents =>', updateResult); ``` -Updating a document -------------------- -Let's look at how to do a simple document update by adding a new field **b** to the document that has the field **a** set to **2**. +The method updates the first document where the field **a** is equal to **3** by adding a new field **b** to the document set to **1**. `updateResult` contains information about whether there was a matching document to update or not. -```js -var updateDocument = function(db, callback) { - // Get the documents collection - var collection = db.collection('documents'); - // Update document where a is 2, set b equal to 1 - collection.updateOne({ a : 2 } - , { $set: { b : 1 } }, function(err, result) { - assert.equal(err, null); - assert.equal(1, result.result.n); - console.log("Updated the document with the field a equal to 2"); - callback(result); - }); -} -``` +### Remove a document -The method will update the first document where the field **a** is equal to **2** by adding a new field **b** to the document set to **1**. Let's update the callback function from **MongoClient.connect** to include the update method. +Remove the document where the field **a** is equal to **3**. ```js -var MongoClient = require('mongodb').MongoClient - , assert = require('assert'); - -// Connection URL -var url = 'mongodb://localhost:27017/myproject'; -// Use connect method to connect to the Server -MongoClient.connect(url, function(err, db) { - assert.equal(null, err); - console.log("Connected correctly to server"); - - insertDocuments(db, function() { - updateDocument(db, function() { - db.close(); - }); - }); -}); +const deleteResult = await collection.deleteMany({ a: 3 }); +console.log('Deleted documents =>', deleteResult); ``` -Delete a document ------------------ -Next lets delete the document where the field **a** equals to **3**. +### Index a Collection + +[Indexes](https://docs.mongodb.org/manual/indexes/) can improve your application's +performance. The following function creates an index on the **a** field in the +**documents** collection. ```js -var deleteDocument = function(db, callback) { - // Get the documents collection - var collection = db.collection('documents'); - // Insert some documents - collection.deleteOne({ a : 3 }, function(err, result) { - assert.equal(err, null); - assert.equal(1, result.result.n); - console.log("Removed the document with the field a equal to 3"); - callback(result); - }); -} +const indexName = await collection.createIndex({ a: 1 }); +console.log('index name =', indexName); ``` -This will delete the first document where the field **a** equals to **3**. Let's add the method to the **MongoClient -.connect** callback function. +For more detailed information, see the [indexing strategies page](https://docs.mongodb.com/manual/applications/indexes/). -```js -var MongoClient = require('mongodb').MongoClient - , assert = require('assert'); +## Error Handling -// Connection URL -var url = 'mongodb://localhost:27017/myproject'; -// Use connect method to connect to the Server -MongoClient.connect(url, function(err, db) { - assert.equal(null, err); - console.log("Connected correctly to server"); - - insertDocuments(db, function() { - updateDocument(db, function() { - deleteDocument(db, function() { - db.close(); - }); - }); - }); -}); -``` +If you need to filter certain errors from our driver we have a helpful tree of errors described in [etc/notes/errors.md](https://github.com/mongodb/node-mongodb-native/blob/HEAD/etc/notes/errors.md). -Finally let's retrieve all the documents using a simple find. +It is our recommendation to use `instanceof` checks on errors and to avoid relying on parsing `error.message` and `error.name` strings in your code. +We guarantee `instanceof` checks will pass according to semver guidelines, but errors may be sub-classed or their messages may change at any time, even patch releases, as we see fit to increase the helpfulness of the errors. -Find All Documents ------------------- -We will finish up the Quickstart CRUD methods by performing a simple query that returns all the documents matching the query. +Any new errors we add to the driver will directly extend an existing error class and no existing error will be moved to a different parent class outside of a major release. +This means `instanceof` will always be able to accurately capture the errors that our driver throws (or returns in a callback). -```js -var findDocuments = function(db, callback) { - // Get the documents collection - var collection = db.collection('documents'); - // Find some documents - collection.find({}).toArray(function(err, docs) { - assert.equal(err, null); - assert.equal(2, docs.length); - console.log("Found the following records"); - console.dir(docs); - callback(docs); - }); +```typescript +const client = new MongoClient(url); +await client.connect(); +const collection = client.db().collection('collection'); + +try { + await collection.insertOne({ _id: 1 }); + await collection.insertOne({ _id: 1 }); // duplicate key error +} catch (error) { + if (error instanceof MongoServerError) { + console.log(`Error worth logging: ${error}`); // special case for some reason + } + throw error; // still want to crash } ``` -This query will return all the documents in the **documents** collection. Since we deleted a document the total -documents returned is **2**. Finally let's add the findDocument method to the **MongoClient.connect** callback. - -```js -var MongoClient = require('mongodb').MongoClient - , assert = require('assert'); +## Next Steps -// Connection URL -var url = 'mongodb://localhost:27017/myproject'; -// Use connect method to connect to the Server -MongoClient.connect(url, function(err, db) { - assert.equal(null, err); - console.log("Connected correctly to server"); - - insertDocuments(db, function() { - updateDocument(db, function() { - deleteDocument(db, function() { - findDocuments(db, function() { - db.close(); - }); - }); - }); - }); -}); -``` +- [MongoDB Documentation](https://docs.mongodb.com/manual/) +- [MongoDB Node Driver Documentation](https://docs.mongodb.com/drivers/node/) +- [Read about Schemas](https://docs.mongodb.com/manual/core/data-modeling-introduction/) +- [Star us on GitHub](https://github.com/mongodb/node-mongodb-native) -This concludes the QuickStart of connecting and performing some Basic operations using the MongoDB Node.js driver. For more detailed information you can look at the tutorials covering more specific topics of interest. +## License -## Next Steps +[Apache 2.0](LICENSE.md) - * [MongoDB Documentation](http://mongodb.org/) - * [Read about Schemas](http://learnmongodbthehardway.com/) - * [Star us on GitHub](https://github.com/mongodb/node-mongodb-native) +© 2009-2012 Christian Amor Kvalheim +© 2012-present MongoDB [Contributors](https://github.com/mongodb/node-mongodb-native/blob/HEAD/CONTRIBUTORS.md) diff --git a/ts-ticket-office-service/node_modules/mongodb/THIRD-PARTY-NOTICES b/ts-ticket-office-service/node_modules/mongodb/THIRD-PARTY-NOTICES deleted file mode 100644 index c13e5d9a3..000000000 --- a/ts-ticket-office-service/node_modules/mongodb/THIRD-PARTY-NOTICES +++ /dev/null @@ -1,41 +0,0 @@ -Mongodb-core uses third-party libraries or other resources that may -be distributed under licenses different than the Mongodb-core software. - -In the event that we accidentally failed to list a required notice, -please bring it to our attention through any of the ways detailed here: - - mongodb-dev@googlegroups.com - -The attached notices are provided for information only. - -For any licenses that require disclosure of source, sources are available at -https://github.com/mongodb/node-mongodb-native. - -1) License Notice for nan.h ---------------------------- - -The MIT License (MIT) -===================== - -Copyright (c) 2016 NAN contributors ------------------------------------ - -NAN contributors listed at - -Permission is hereby granted, free of charge, to any person obtaining a copy of -this software and associated documentation files (the "Software"), to deal in -the Software without restriction, including without limitation the rights to -use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies -of the Software, and to permit persons to whom the Software is furnished to -do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in all -copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING -FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS -IN THE SOFTWARE. diff --git a/ts-ticket-office-service/node_modules/mongodb/boot_auth.js b/ts-ticket-office-service/node_modules/mongodb/boot_auth.js deleted file mode 100644 index 95956c7a5..000000000 --- a/ts-ticket-office-service/node_modules/mongodb/boot_auth.js +++ /dev/null @@ -1,52 +0,0 @@ -var ReplSetManager = require('mongodb-topology-manager').ReplSet, - f = require('util').format; - -var rsOptions = { - server: { - keyFile: __dirname + '/test/functional/data/keyfile.txt', - auth: null, - replSet: 'rs' - }, - client: { - replSet: 'rs' - } -} - -// Set up the nodes -var nodes = [{ - options: { - bind_ip: 'localhost', port: 31000, - dbpath: f('%s/../db/31000', __dirname), - } -}, { - options: { - bind_ip: 'localhost', port: 31001, - dbpath: f('%s/../db/31001', __dirname), - } -}, { - options: { - bind_ip: 'localhost', port: 31002, - dbpath: f('%s/../db/31002', __dirname), - } -}] - -// Merge in any node start up options -for(var i = 0; i < nodes.length; i++) { - for(var name in rsOptions.server) { - nodes[i].options[name] = rsOptions.server[name]; - } -} - -// Create a manager -var replicasetManager = new ReplSetManager('mongod', nodes, rsOptions.client); -// Purge the set -replicasetManager.purge().then(function() { - // Start the server - replicasetManager.start().then(function() { - process.exit(0); - }).catch(function(e) { - console.log("====== ") - console.dir(e) - // // console.dir(e); - }); -}); diff --git a/ts-ticket-office-service/node_modules/mongodb/conf.json b/ts-ticket-office-service/node_modules/mongodb/conf.json deleted file mode 100644 index 99eb3a771..000000000 --- a/ts-ticket-office-service/node_modules/mongodb/conf.json +++ /dev/null @@ -1,76 +0,0 @@ -{ - "plugins": ["plugins/markdown", "docs/lib/jsdoc/examples_plugin.js"], - "source": { - "include": [ - "test/functional/operation_example_tests.js", - "test/functional/operation_promises_example_tests.js", - "test/functional/operation_generators_example_tests.js", - "test/functional/authentication_tests.js", - "test/functional/gridfs_stream_tests.js", - "lib/admin.js", - "lib/collection.js", - "lib/cursor.js", - "lib/aggregation_cursor.js", - "lib/command_cursor.js", - "lib/db.js", - "lib/mongo_client.js", - "lib/mongos.js", - "lib/read_preference.js", - "lib/replset.js", - "lib/server.js", - "lib/bulk/common.js", - "lib/bulk/ordered.js", - "lib/bulk/unordered.js", - "lib/gridfs/grid_store.js", - "node_modules/mongodb-core/lib/error.js", - "lib/gridfs-stream/index.js", - "lib/gridfs-stream/download.js", - "lib/gridfs-stream/upload.js", - "node_modules/mongodb-core/lib/connection/logger.js", - "node_modules/bson/lib/bson/binary.js", - "node_modules/bson/lib/bson/code.js", - "node_modules/bson/lib/bson/db_ref.js", - "node_modules/bson/lib/bson/double.js", - "node_modules/bson/lib/bson/long.js", - "node_modules/bson/lib/bson/objectid.js", - "node_modules/bson/lib/bson/symbol.js", - "node_modules/bson/lib/bson/timestamp.js", - "node_modules/bson/lib/bson/max_key.js", - "node_modules/bson/lib/bson/min_key.js", - "node_modules/bson/lib/bson/decimal128.js", - "node_modules/bson/lib/bson/int_32.js", - "node_modules/bson/lib/bson/regexp.js" - ] - }, - "templates": { - "cleverLinks": true, - "monospaceLinks": true, - "default": { - "outputSourceFiles" : true - }, - "applicationName": "Node.js MongoDB Driver API", - "disqus": true, - "googleAnalytics": "UA-29229787-1", - "openGraph": { - "title": "", - "type": "website", - "image": "", - "site_name": "", - "url": "" - }, - "meta": { - "title": "", - "description": "", - "keyword": "" - }, - "linenums": true - }, - "markdown": { - "parser": "gfm", - "hardwrap": true, - "tags": ["examples"] - }, - "examples": { - "indent": 4 - } -} diff --git a/ts-ticket-office-service/node_modules/mongodb/etc/prepare.js b/ts-ticket-office-service/node_modules/mongodb/etc/prepare.js new file mode 100755 index 000000000..2039d0b33 --- /dev/null +++ b/ts-ticket-office-service/node_modules/mongodb/etc/prepare.js @@ -0,0 +1,12 @@ +#! /usr/bin/env node +var cp = require('child_process'); +var fs = require('fs'); +var os = require('os'); + +if (fs.existsSync('src')) { + cp.spawn('npm', ['run', 'build:dts'], { stdio: 'inherit', shell: os.platform() === 'win32' }); +} else { + if (!fs.existsSync('lib')) { + console.warn('MongoDB: No compiled javascript present, the driver is not installed correctly.'); + } +} diff --git a/ts-ticket-office-service/node_modules/mongodb/index.js b/ts-ticket-office-service/node_modules/mongodb/index.js deleted file mode 100644 index 4e328fa3d..000000000 --- a/ts-ticket-office-service/node_modules/mongodb/index.js +++ /dev/null @@ -1,56 +0,0 @@ -// Core module -var core = require('mongodb-core'), - Instrumentation = require('./lib/apm'); - -// Set up the connect function -var connect = require('./lib/mongo_client').connect; - -// Expose error class -connect.MongoError = core.MongoError; - -// Actual driver classes exported -connect.Admin = require('./lib/admin'); -connect.MongoClient = require('./lib/mongo_client'); -connect.Db = require('./lib/db'); -connect.Collection = require('./lib/collection'); -connect.Server = require('./lib/server'); -connect.ReplSet = require('./lib/replset'); -connect.Mongos = require('./lib/mongos'); -connect.ReadPreference = require('./lib/read_preference'); -connect.GridStore = require('./lib/gridfs/grid_store'); -connect.Chunk = require('./lib/gridfs/chunk'); -connect.Logger = core.Logger; -connect.Cursor = require('./lib/cursor'); -connect.GridFSBucket = require('./lib/gridfs-stream'); -// Exported to be used in tests not to be used anywhere else -connect.CoreServer = require('mongodb-core').Server; -connect.CoreConnection = require('mongodb-core').Connection; - -// BSON types exported -connect.Binary = core.BSON.Binary; -connect.Code = core.BSON.Code; -connect.Map = core.BSON.Map; -connect.DBRef = core.BSON.DBRef; -connect.Double = core.BSON.Double; -connect.Int32 = core.BSON.Int32; -connect.Long = core.BSON.Long; -connect.MinKey = core.BSON.MinKey; -connect.MaxKey = core.BSON.MaxKey; -connect.ObjectID = core.BSON.ObjectID; -connect.ObjectId = core.BSON.ObjectID; -connect.Symbol = core.BSON.Symbol; -connect.Timestamp = core.BSON.Timestamp; -connect.BSONRegExp = core.BSON.BSONRegExp; -connect.Decimal128 = core.BSON.Decimal128; - -// Add connect method -connect.connect = connect; - -// Set up the instrumentation method -connect.instrument = function(options, callback) { - if(typeof options == 'function') callback = options, options = {}; - return new Instrumentation(core, options, callback); -} - -// Set our exports to be the connect function -module.exports = connect; diff --git a/ts-ticket-office-service/node_modules/mongodb/insert_bench.js b/ts-ticket-office-service/node_modules/mongodb/insert_bench.js deleted file mode 100644 index 5c4d0b9ef..000000000 --- a/ts-ticket-office-service/node_modules/mongodb/insert_bench.js +++ /dev/null @@ -1,231 +0,0 @@ -var MongoClient = require('./').MongoClient, - assert = require('assert'); - -// var memwatch = require('memwatch-next'); -// memwatch.on('leak', function(info) { -// console.log("======== leak") -// }); -// -// memwatch.on('stats', function(stats) { -// console.log("======== stats") -// console.dir(stats) -// }); - -// // Take first snapshot -// var hd = new memwatch.HeapDiff(); - -MongoClient.connect('mongodb://localhost:27017/bench', function(err, db) { - var docs = []; - var total = 1000; - var count = total; - var measurements = []; - - // Insert a bunch of documents - for(var i = 0; i < 100; i++) { - docs.push(JSON.parse(data)); - } - - var col = db.collection('inserts'); - - function execute(col, callback) { - var start = new Date().getTime(); - - col.find({}).limit(100).toArray(function(e, docs) { - measurements.push(new Date().getTime() - start); - assert.equal(null, e); - callback(); - }); - } - - console.log("== insert documents") - col.insert(docs, function(e, r) { - docs = []; - assert.equal(null, e); - - console.log("== start bench") - for(var i = 0; i < total; i++) { - execute(col, function(e) { - count = count - 1; - - if(count == 0) { - // Calculate total execution time for operations - var totalTime = measurements.reduce(function(prev, curr) { - return prev + curr; - }, 0); - - console.log("==========================================="); - console.log("total time: " + totalTime) - - // var diff = hd.end(); - // console.log("==========================================="); - // console.log(JSON.stringify(diff, null, 2)) - - db.close(); - process.exit(0) - } - }); - } - }); -}); - -var data = JSON.stringify({ - "data": [ - { - "_id": 1, - "x": 11 - }, - { - "_id": 2, - "x": 22 - }, - { - "_id": 3, - "x": 33 - } - ], - "collection_name": "test", - "database_name": "command-monitoring-tests", - "tests": [ - { - "description": "A successful mixed bulk write", - "operation": { - "name": "bulkWrite", - "arguments": { - "requests": [ - { - "insertOne": { - "document": { - "_id": 4, - "x": 44 - } - } - }, - { - "updateOne": { - "filter": { - "_id": 3 - }, - "update": { - "set": { - "x": 333 - } - } - } - } - ] - } - }, - "expectations": [ - { - "command_started_event": { - "command": { - "insert": "test", - "documents": [ - { - "_id": 4, - "x": 44 - } - ], - "ordered": true - }, - "command_name": "insert", - "database_name": "command-monitoring-tests" - } - }, - { - "command_succeeded_event": { - "reply": { - "ok": 1.0, - "n": 1 - }, - "command_name": "insert" - } - }, - { - "command_started_event": { - "command": { - "update": "test", - "updates": [ - { - "q": { - "_id": 3 - }, - "u": { - "set": { - "x": 333 - } - }, - "upsert": false, - "multi": false - } - ], - "ordered": true - }, - "command_name": "update", - "database_name": "command-monitoring-tests" - } - }, - { - "command_succeeded_event": { - "reply": { - "ok": 1.0, - "n": 1 - }, - "command_name": "update" - } - } - ] - }, - { - "description": "A successful unordered bulk write with an unacknowledged write concern", - "operation": { - "name": "bulkWrite", - "arguments": { - "requests": [ - { - "insertOne": { - "document": { - "_id": 4, - "x": 44 - } - } - } - ], - "ordered": false, - "writeConcern": { - "w": 0 - } - } - }, - "expectations": [ - { - "command_started_event": { - "command": { - "insert": "test", - "documents": [ - { - "_id": 4, - "x": 44 - } - ], - "ordered": false, - "writeConcern": { - "w": 0 - } - }, - "command_name": "insert", - "database_name": "command-monitoring-tests" - } - }, - { - "command_succeeded_event": { - "reply": { - "ok": 1.0 - }, - "command_name": "insert" - } - } - ] - } - ] -}); diff --git a/ts-ticket-office-service/node_modules/mongodb/lib/admin.js b/ts-ticket-office-service/node_modules/mongodb/lib/admin.js index 4675da432..f984a9ee5 100644 --- a/ts-ticket-office-service/node_modules/mongodb/lib/admin.js +++ b/ts-ticket-office-service/node_modules/mongodb/lib/admin.js @@ -1,579 +1,123 @@ "use strict"; - -var toError = require('./utils').toError, - Define = require('./metadata'), - shallowClone = require('./utils').shallowClone, - assign = require('./utils').assign, - authenticate = require('./authenticate'); - -/** - * @fileOverview The **Admin** class is an internal class that allows convenient access to +Object.defineProperty(exports, "__esModule", { value: true }); +exports.Admin = void 0; +const add_user_1 = require("./operations/add_user"); +const execute_operation_1 = require("./operations/execute_operation"); +const list_databases_1 = require("./operations/list_databases"); +const remove_user_1 = require("./operations/remove_user"); +const run_command_1 = require("./operations/run_command"); +const validate_collection_1 = require("./operations/validate_collection"); +/** + * The **Admin** class is an internal class that allows convenient access to * the admin functionality and commands for MongoDB. * * **ADMIN Cannot directly be instantiated** + * @public + * * @example - * var MongoClient = require('mongodb').MongoClient, - * test = require('assert'); + * ```js + * const MongoClient = require('mongodb').MongoClient; + * const test = require('assert'); * // Connection url - * var url = 'mongodb://localhost:27017/test'; + * const url = 'mongodb://localhost:27017'; + * // Database Name + * const dbName = 'test'; + * * // Connect using MongoClient - * MongoClient.connect(url, function(err, db) { + * MongoClient.connect(url, function(err, client) { * // Use the admin database for the operation - * var adminDb = db.admin(); + * const adminDb = client.db(dbName).admin(); * * // List all the available databases * adminDb.listDatabases(function(err, dbs) { - * test.equal(null, err); + * expect(err).to.not.exist; * test.ok(dbs.databases.length > 0); - * db.close(); + * client.close(); * }); * }); - */ - -/** - * Create a new Admin instance (INTERNAL TYPE, do not instantiate directly) - * @class - * @return {Admin} a collection instance. - */ -var Admin = function(db, topology, promiseLibrary) { - if(!(this instanceof Admin)) return new Admin(db, topology); - - // Internal state - this.s = { - db: db - , topology: topology - , promiseLibrary: promiseLibrary - } -} - -var define = Admin.define = new Define('Admin', Admin, false); - -/** - * The callback format for results - * @callback Admin~resultCallback - * @param {MongoError} error An error instance representing the error during the execution. - * @param {object} result The result object if the command was executed successfully. - */ - -/** - * Execute a command - * @method - * @param {object} command The command hash - * @param {object} [options=null] Optional settings. - * @param {(ReadPreference|string)} [options.readPreference=null] The preferred read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST). - * @param {number} [options.maxTimeMS=null] Number of milliseconds to wait before aborting the query. - * @param {Admin~resultCallback} [callback] The command result callback - * @return {Promise} returns Promise if no callback passed - */ -Admin.prototype.command = function(command, options, callback) { - var self = this; - var args = Array.prototype.slice.call(arguments, 1); - callback = args.pop(); - if(typeof callback != 'function') args.push(callback); - options = args.length ? args.shift() : {}; - - // Execute using callback - if(typeof callback == 'function') return this.s.db.executeDbAdminCommand(command, options, function(err, doc) { - return callback != null ? callback(err, doc) : null; - }); - - // Return a Promise - return new this.s.promiseLibrary(function(resolve, reject) { - self.s.db.executeDbAdminCommand(command, options, function(err, doc) { - if(err) return reject(err); - resolve(doc); - }); - }); -} - -define.classMethod('command', {callback: true, promise:true}); - -/** - * Retrieve the server information for the current - * instance of the db client - * - * @param {Admin~resultCallback} [callback] The command result callback - * @return {Promise} returns Promise if no callback passed - */ -Admin.prototype.buildInfo = function(callback) { - var self = this; - // Execute using callback - if(typeof callback == 'function') return this.serverInfo(callback); - - // Return a Promise - return new this.s.promiseLibrary(function(resolve, reject) { - self.serverInfo(function(err, r) { - if(err) return reject(err); - resolve(r); - }); - }); -} - -define.classMethod('buildInfo', {callback: true, promise:true}); - -/** - * Retrieve the server information for the current - * instance of the db client - * - * @param {Admin~resultCallback} [callback] The command result callback - * @return {Promise} returns Promise if no callback passed - */ -Admin.prototype.serverInfo = function(callback) { - var self = this; - // Execute using callback - if(typeof callback == 'function') return this.s.db.executeDbAdminCommand({buildinfo:1}, function(err, doc) { - if(err != null) return callback(err, null); - callback(null, doc); - }); - - // Return a Promise - return new this.s.promiseLibrary(function(resolve, reject) { - self.s.db.executeDbAdminCommand({buildinfo:1}, function(err, doc) { - if(err) return reject(err); - resolve(doc); - }); - }); -} - -define.classMethod('serverInfo', {callback: true, promise:true}); - -/** - * Retrieve this db's server status. - * - * @param {Admin~resultCallback} [callback] The command result callback - * @return {Promise} returns Promise if no callback passed - */ -Admin.prototype.serverStatus = function(callback) { - var self = this; - - // Execute using callback - if(typeof callback == 'function') return serverStatus(self, callback) - - // Return a Promise - return new this.s.promiseLibrary(function(resolve, reject) { - serverStatus(self, function(err, r) { - if(err) return reject(err); - resolve(r); - }); - }); -}; - -var serverStatus = function(self, callback) { - self.s.db.executeDbAdminCommand({serverStatus: 1}, function(err, doc) { - if(err == null && doc.ok === 1) { - callback(null, doc); - } else { - if(err) return callback(err, false); - return callback(toError(doc), false); + * ``` + */ +class Admin { + /** + * Create a new Admin instance + * @internal + */ + constructor(db) { + this.s = { db }; } - }); -} - -define.classMethod('serverStatus', {callback: true, promise:true}); - -/** - * Retrieve the current profiling Level for MongoDB - * - * @param {Admin~resultCallback} [callback] The command result callback - * @return {Promise} returns Promise if no callback passed - */ -Admin.prototype.profilingLevel = function(callback) { - var self = this; - - // Execute using callback - if(typeof callback == 'function') return profilingLevel(self, callback) - - // Return a Promise - return new this.s.promiseLibrary(function(resolve, reject) { - profilingLevel(self, function(err, r) { - if(err) return reject(err); - resolve(r); - }); - }); -}; - -var profilingLevel = function(self, callback) { - self.s.db.executeDbAdminCommand({profile:-1}, function(err, doc) { - if(err == null && doc.ok === 1) { - var was = doc.was; - if(was == 0) return callback(null, "off"); - if(was == 1) return callback(null, "slow_only"); - if(was == 2) return callback(null, "all"); - return callback(new Error("Error: illegal profiling level value " + was), null); - } else { - err != null ? callback(err, null) : callback(new Error("Error with profile command"), null); + command(command, options, callback) { + if (typeof options === 'function') + (callback = options), (options = {}); + options = Object.assign({ dbName: 'admin' }, options); + return (0, execute_operation_1.executeOperation)(this.s.db.s.client, new run_command_1.RunCommandOperation(this.s.db, command, options), callback); } - }); -} - -define.classMethod('profilingLevel', {callback: true, promise:true}); - -/** - * Ping the MongoDB server and retrieve results - * - * @param {Admin~resultCallback} [callback] The command result callback - * @return {Promise} returns Promise if no callback passed - */ -Admin.prototype.ping = function(options, callback) { - var self = this; - var args = Array.prototype.slice.call(arguments, 0); - callback = args.pop(); - if(typeof callback != 'function') args.push(callback); - - // Execute using callback - if(typeof callback == 'function') return this.s.db.executeDbAdminCommand({ping: 1}, callback); - - // Return a Promise - return new this.s.promiseLibrary(function(resolve, reject) { - self.s.db.executeDbAdminCommand({ping: 1}, function(err, r) { - if(err) return reject(err); - resolve(r); - }); - }); -} - -define.classMethod('ping', {callback: true, promise:true}); - -/** - * Authenticate a user against the server. - * @method - * @param {string} username The username. - * @param {string} [password] The password. - * @param {Admin~resultCallback} [callback] The command result callback - * @return {Promise} returns Promise if no callback passed - * @deprecated This method will no longer be available in the next major release 3.x as MongoDB 3.6 will only allow auth against users in the admin db and will no longer allow multiple credentials on a socket. Please authenticate using MongoClient.connect with auth credentials. - */ -Admin.prototype.authenticate = function(username, password, options, callback) { - console.warn("Admin.prototype.authenticate method will no longer be available in the next major release 3.x as MongoDB 3.6 will only allow auth against users in the admin db and will no longer allow multiple credentials on a socket. Please authenticate using MongoClient.connect with auth credentials."); - var finalArguments = [this.s.db]; - if(typeof username == 'string') finalArguments.push(username); - if(typeof password == 'string') finalArguments.push(password); - if(typeof options == 'function') { - finalArguments.push({ authdb: 'admin' }); - finalArguments.push(options); - } else { - finalArguments.push(assign({}, options, { authdb: 'admin' })); - } - - if(typeof callback == 'function') finalArguments.push(callback); - // Execute authenticate method - return authenticate.apply(this.s.db, finalArguments); -} - -define.classMethod('authenticate', {callback: true, promise:true}); - -/** - * Logout user from server, fire off on all connections and remove all auth info - * @method - * @param {Admin~resultCallback} [callback] The command result callback - * @return {Promise} returns Promise if no callback passed - */ -Admin.prototype.logout = function(callback) { - var self = this; - // Execute using callback - if(typeof callback == 'function') return this.s.db.logout({dbName: 'admin'}, callback); - - // Return a Promise - return new this.s.promiseLibrary(function(resolve, reject) { - self.s.db.logout({dbName: 'admin'}, function(err) { - if(err) return reject(err); - resolve(true); - }); - }); -} - -define.classMethod('logout', {callback: true, promise:true}); - -// Get write concern -var writeConcern = function(options, db) { - options = shallowClone(options); - - // If options already contain write concerns return it - if(options.w || options.wtimeout || options.j || options.fsync) { - return options; - } - - // Set db write concern if available - if(db.writeConcern) { - if(options.w) options.w = db.writeConcern.w; - if(options.wtimeout) options.wtimeout = db.writeConcern.wtimeout; - if(options.j) options.j = db.writeConcern.j; - if(options.fsync) options.fsync = db.writeConcern.fsync; - } - - // Return modified options - return options; -} - -/** - * Add a user to the database. - * @method - * @param {string} username The username. - * @param {string} password The password. - * @param {object} [options=null] Optional settings. - * @param {(number|string)} [options.w=null] The write concern. - * @param {number} [options.wtimeout=null] The write concern timeout. - * @param {boolean} [options.j=false] Specify a journal write concern. - * @param {boolean} [options.fsync=false] Specify a file sync write concern. - * @param {object} [options.customData=null] Custom data associated with the user (only Mongodb 2.6 or higher) - * @param {object[]} [options.roles=null] Roles associated with the created user (only Mongodb 2.6 or higher) - * @param {Admin~resultCallback} [callback] The command result callback - * @return {Promise} returns Promise if no callback passed - */ -Admin.prototype.addUser = function(username, password, options, callback) { - var self = this; - var args = Array.prototype.slice.call(arguments, 2); - callback = args.pop(); - if(typeof callback != 'function') args.push(callback); - options = args.length ? args.shift() : {}; - options = options || {}; - // Get the options - options = writeConcern(options, self.s.db) - // Set the db name to admin - options.dbName = 'admin'; - - // Execute using callback - if(typeof callback == 'function') - return self.s.db.addUser(username, password, options, callback); - - // Return a Promise - return new this.s.promiseLibrary(function(resolve, reject) { - self.s.db.addUser(username, password, options, function(err, r) { - if(err) return reject(err); - resolve(r); - }); - }); -} - -define.classMethod('addUser', {callback: true, promise:true}); - -/** - * Remove a user from a database - * @method - * @param {string} username The username. - * @param {object} [options=null] Optional settings. - * @param {(number|string)} [options.w=null] The write concern. - * @param {number} [options.wtimeout=null] The write concern timeout. - * @param {boolean} [options.j=false] Specify a journal write concern. - * @param {boolean} [options.fsync=false] Specify a file sync write concern. - * @param {Admin~resultCallback} [callback] The command result callback - * @return {Promise} returns Promise if no callback passed - */ -Admin.prototype.removeUser = function(username, options, callback) { - var self = this; - var args = Array.prototype.slice.call(arguments, 1); - callback = args.pop(); - if(typeof callback != 'function') args.push(callback); - options = args.length ? args.shift() : {}; - options = options || {}; - // Get the options - options = writeConcern(options, self.s.db) - // Set the db name - options.dbName = 'admin'; - - // Execute using callback - if(typeof callback == 'function') - return self.s.db.removeUser(username, options, callback); - - // Return a Promise - return new this.s.promiseLibrary(function(resolve, reject) { - self.s.db.removeUser(username, options, function(err, r) { - if(err) return reject(err); - resolve(r); - }); - }); -} - -define.classMethod('removeUser', {callback: true, promise:true}); - -/** - * Set the current profiling level of MongoDB - * - * @param {string} level The new profiling level (off, slow_only, all). - * @param {Admin~resultCallback} [callback] The command result callback. - * @return {Promise} returns Promise if no callback passed - */ -Admin.prototype.setProfilingLevel = function(level, callback) { - var self = this; - - // Execute using callback - if(typeof callback == 'function') return setProfilingLevel(self, level, callback); - - // Return a Promise - return new this.s.promiseLibrary(function(resolve, reject) { - setProfilingLevel(self, level, function(err, r) { - if(err) return reject(err); - resolve(r); - }); - }); -}; - -var setProfilingLevel = function(self, level, callback) { - var command = {}; - var profile = 0; - - if(level == "off") { - profile = 0; - } else if(level == "slow_only") { - profile = 1; - } else if(level == "all") { - profile = 2; - } else { - return callback(new Error("Error: illegal profiling level value " + level)); - } - - // Set up the profile number - command['profile'] = profile; - - self.s.db.executeDbAdminCommand(command, function(err, doc) { - if(err == null && doc.ok === 1) - return callback(null, level); - return err != null ? callback(err, null) : callback(new Error("Error with profile command"), null); - }); -} - -define.classMethod('setProfilingLevel', {callback: true, promise:true}); - -/** - * Retrieve the current profiling information for MongoDB - * - * @param {Admin~resultCallback} [callback] The command result callback. - * @return {Promise} returns Promise if no callback passed - * @deprecated Query the system.profile collection directly. - */ -Admin.prototype.profilingInfo = function(callback) { - var self = this; - - // Execute using callback - if(typeof callback == 'function') return profilingInfo(self, callback); - - // Return a Promise - return new this.s.promiseLibrary(function(resolve, reject) { - profilingInfo(self, function(err, r) { - if(err) return reject(err); - resolve(r); - }); - }); -}; - -var profilingInfo = function(self, callback) { - try { - self.s.topology.cursor("admin.system.profile", { find: 'system.profile', query: {}}, {}).toArray(callback); - } catch (err) { - return callback(err, null); - } -} - -define.classMethod('profilingLevel', {callback: true, promise:true}); - -/** - * Validate an existing collection - * - * @param {string} collectionName The name of the collection to validate. - * @param {object} [options=null] Optional settings. - * @param {Admin~resultCallback} [callback] The command result callback. - * @return {Promise} returns Promise if no callback passed - */ -Admin.prototype.validateCollection = function(collectionName, options, callback) { - var self = this; - var args = Array.prototype.slice.call(arguments, 1); - callback = args.pop(); - if(typeof callback != 'function') args.push(callback); - options = args.length ? args.shift() : {}; - options = options || {}; - - // Execute using callback - if(typeof callback == 'function') - return validateCollection(self, collectionName, options, callback); - - // Return a Promise - return new this.s.promiseLibrary(function(resolve, reject) { - validateCollection(self, collectionName, options, function(err, r) { - if(err) return reject(err); - resolve(r); - }); - }); -}; - -var validateCollection = function(self, collectionName, options, callback) { - var command = {validate: collectionName}; - var keys = Object.keys(options); - - // Decorate command with extra options - for(var i = 0; i < keys.length; i++) { - if(options.hasOwnProperty(keys[i])) { - command[keys[i]] = options[keys[i]]; + buildInfo(options, callback) { + if (typeof options === 'function') + (callback = options), (options = {}); + options = options !== null && options !== void 0 ? options : {}; + return this.command({ buildinfo: 1 }, options, callback); + } + serverInfo(options, callback) { + if (typeof options === 'function') + (callback = options), (options = {}); + options = options !== null && options !== void 0 ? options : {}; + return this.command({ buildinfo: 1 }, options, callback); + } + serverStatus(options, callback) { + if (typeof options === 'function') + (callback = options), (options = {}); + options = options !== null && options !== void 0 ? options : {}; + return this.command({ serverStatus: 1 }, options, callback); + } + ping(options, callback) { + if (typeof options === 'function') + (callback = options), (options = {}); + options = options !== null && options !== void 0 ? options : {}; + return this.command({ ping: 1 }, options, callback); + } + addUser(username, password, options, callback) { + if (typeof password === 'function') { + (callback = password), (password = undefined), (options = {}); + } + else if (typeof password !== 'string') { + if (typeof options === 'function') { + (callback = options), (options = password), (password = undefined); + } + else { + (options = password), (callback = undefined), (password = undefined); + } + } + else { + if (typeof options === 'function') + (callback = options), (options = {}); + } + options = Object.assign({ dbName: 'admin' }, options); + return (0, execute_operation_1.executeOperation)(this.s.db.s.client, new add_user_1.AddUserOperation(this.s.db, username, password, options), callback); + } + removeUser(username, options, callback) { + if (typeof options === 'function') + (callback = options), (options = {}); + options = Object.assign({ dbName: 'admin' }, options); + return (0, execute_operation_1.executeOperation)(this.s.db.s.client, new remove_user_1.RemoveUserOperation(this.s.db, username, options), callback); + } + validateCollection(collectionName, options, callback) { + if (typeof options === 'function') + (callback = options), (options = {}); + options = options !== null && options !== void 0 ? options : {}; + return (0, execute_operation_1.executeOperation)(this.s.db.s.client, new validate_collection_1.ValidateCollectionOperation(this, collectionName, options), callback); + } + listDatabases(options, callback) { + if (typeof options === 'function') + (callback = options), (options = {}); + options = options !== null && options !== void 0 ? options : {}; + return (0, execute_operation_1.executeOperation)(this.s.db.s.client, new list_databases_1.ListDatabasesOperation(this.s.db, options), callback); + } + replSetGetStatus(options, callback) { + if (typeof options === 'function') + (callback = options), (options = {}); + options = options !== null && options !== void 0 ? options : {}; + return this.command({ replSetGetStatus: 1 }, options, callback); } - } - - self.s.db.command(command, function(err, doc) { - if(err != null) return callback(err, null); - - if(doc.ok === 0) - return callback(new Error("Error with validate command"), null); - if(doc.result != null && doc.result.constructor != String) - return callback(new Error("Error with validation data"), null); - if(doc.result != null && doc.result.match(/exception|corrupt/) != null) - return callback(new Error("Error: invalid collection " + collectionName), null); - if(doc.valid != null && !doc.valid) - return callback(new Error("Error: invalid collection " + collectionName), null); - - return callback(null, doc); - }); -} - -define.classMethod('validateCollection', {callback: true, promise:true}); - -/** - * List the available databases - * - * @param {Admin~resultCallback} [callback] The command result callback. - * @return {Promise} returns Promise if no callback passed - */ -Admin.prototype.listDatabases = function(callback) { - var self = this; - // Execute using callback - if(typeof callback == 'function') return self.s.db.executeDbAdminCommand({listDatabases:1}, {}, callback); - - // Return a Promise - return new this.s.promiseLibrary(function(resolve, reject) { - self.s.db.executeDbAdminCommand({listDatabases:1}, {}, function(err, r) { - if(err) return reject(err); - resolve(r); - }); - }); -} - -define.classMethod('listDatabases', {callback: true, promise:true}); - -/** - * Get ReplicaSet status - * - * @param {Admin~resultCallback} [callback] The command result callback. - * @return {Promise} returns Promise if no callback passed - */ -Admin.prototype.replSetGetStatus = function(callback) { - var self = this; - // Execute using callback - if(typeof callback == 'function') return replSetGetStatus(self, callback); - // Return a Promise - return new this.s.promiseLibrary(function(resolve, reject) { - replSetGetStatus(self, function(err, r) { - if(err) return reject(err); - resolve(r); - }); - }); -}; - -var replSetGetStatus = function(self, callback) { - self.s.db.executeDbAdminCommand({replSetGetStatus:1}, function(err, doc) { - if(err == null && doc.ok === 1) - return callback(null, doc); - if(err) return callback(err, false); - callback(toError(doc), false); - }); } - -define.classMethod('replSetGetStatus', {callback: true, promise:true}); - -module.exports = Admin; +exports.Admin = Admin; +//# sourceMappingURL=admin.js.map \ No newline at end of file diff --git a/ts-ticket-office-service/node_modules/mongodb/lib/admin.js.map b/ts-ticket-office-service/node_modules/mongodb/lib/admin.js.map new file mode 100644 index 000000000..da5ef61d4 --- /dev/null +++ b/ts-ticket-office-service/node_modules/mongodb/lib/admin.js.map @@ -0,0 +1 @@ +{"version":3,"file":"admin.js","sourceRoot":"","sources":["../src/admin.ts"],"names":[],"mappings":";;;AAEA,oDAAyE;AAEzE,sEAAkE;AAClE,gEAIqC;AACrC,0DAAkF;AAClF,0DAAkF;AAClF,0EAG0C;AAQ1C;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA6BG;AACH,MAAa,KAAK;IAIhB;;;OAGG;IACH,YAAY,EAAM;QAChB,IAAI,CAAC,CAAC,GAAG,EAAE,EAAE,EAAE,CAAC;IAClB,CAAC;IAaD,OAAO,CACL,OAAiB,EACjB,OAAgD,EAChD,QAA6B;QAE7B,IAAI,OAAO,OAAO,KAAK,UAAU;YAAE,CAAC,QAAQ,GAAG,OAAO,CAAC,EAAE,CAAC,OAAO,GAAG,EAAE,CAAC,CAAC;QACxE,OAAO,GAAG,MAAM,CAAC,MAAM,CAAC,EAAE,MAAM,EAAE,OAAO,EAAE,EAAE,OAAO,CAAC,CAAC;QAEtD,OAAO,IAAA,oCAAgB,EACrB,IAAI,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,MAAM,EAClB,IAAI,iCAAmB,CAAC,IAAI,CAAC,CAAC,CAAC,EAAE,EAAE,OAAO,EAAE,OAAO,CAAC,EACpD,QAAQ,CACT,CAAC;IACJ,CAAC;IAYD,SAAS,CACP,OAAsD,EACtD,QAA6B;QAE7B,IAAI,OAAO,OAAO,KAAK,UAAU;YAAE,CAAC,QAAQ,GAAG,OAAO,CAAC,EAAE,CAAC,OAAO,GAAG,EAAE,CAAC,CAAC;QACxE,OAAO,GAAG,OAAO,aAAP,OAAO,cAAP,OAAO,GAAI,EAAE,CAAC;QACxB,OAAO,IAAI,CAAC,OAAO,CAAC,EAAE,SAAS,EAAE,CAAC,EAAE,EAAE,OAAO,EAAE,QAA8B,CAAC,CAAC;IACjF,C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xF,CAAC;CACF;AApQD,sBAoQC"} \ No newline at end of file diff --git a/ts-ticket-office-service/node_modules/mongodb/lib/aggregation_cursor.js b/ts-ticket-office-service/node_modules/mongodb/lib/aggregation_cursor.js deleted file mode 100644 index a0d7f2459..000000000 --- a/ts-ticket-office-service/node_modules/mongodb/lib/aggregation_cursor.js +++ /dev/null @@ -1,438 +0,0 @@ -"use strict"; - -var inherits = require('util').inherits - , MongoError = require('mongodb-core').MongoError - , Readable = require('stream').Readable || require('readable-stream').Readable - , Define = require('./metadata') - , CoreCursor = require('./cursor'); - -/** - * @fileOverview The **AggregationCursor** class is an internal class that embodies an aggregation cursor on MongoDB - * allowing for iteration over the results returned from the underlying query. It supports - * one by one document iteration, conversion to an array or can be iterated as a Node 0.10.X - * or higher stream - * - * **AGGREGATIONCURSOR Cannot directly be instantiated** - * @example - * var MongoClient = require('mongodb').MongoClient, - * test = require('assert'); - * // Connection url - * var url = 'mongodb://localhost:27017/test'; - * // Connect using MongoClient - * MongoClient.connect(url, function(err, db) { - * // Create a collection we want to drop later - * var col = db.collection('createIndexExample1'); - * // Insert a bunch of documents - * col.insert([{a:1, b:1} - * , {a:2, b:2}, {a:3, b:3} - * , {a:4, b:4}], {w:1}, function(err, result) { - * test.equal(null, err); - * // Show that duplicate records got dropped - * col.aggregation({}, {cursor: {}}).toArray(function(err, items) { - * test.equal(null, err); - * test.equal(4, items.length); - * db.close(); - * }); - * }); - * }); - */ - -/** - * Namespace provided by the browser. - * @external Readable - */ - -/** - * Creates a new Aggregation Cursor instance (INTERNAL TYPE, do not instantiate directly) - * @class AggregationCursor - * @extends external:Readable - * @fires AggregationCursor#data - * @fires AggregationCursor#end - * @fires AggregationCursor#close - * @fires AggregationCursor#readable - * @return {AggregationCursor} an AggregationCursor instance. - */ -var AggregationCursor = function(bson, ns, cmd, options, topology, topologyOptions) { - CoreCursor.apply(this, Array.prototype.slice.call(arguments, 0)); - var state = AggregationCursor.INIT; - var streamOptions = {}; - - // MaxTimeMS - var maxTimeMS = null; - - // Get the promiseLibrary - var promiseLibrary = options.promiseLibrary; - - // No promise library selected fall back - if(!promiseLibrary) { - promiseLibrary = typeof global.Promise == 'function' ? - global.Promise : require('es6-promise').Promise; - } - - // Set up - Readable.call(this, {objectMode: true}); - - // Internal state - this.s = { - // MaxTimeMS - maxTimeMS: maxTimeMS - // State - , state: state - // Stream options - , streamOptions: streamOptions - // BSON - , bson: bson - // Namespace - , ns: ns - // Command - , cmd: cmd - // Options - , options: options - // Topology - , topology: topology - // Topology Options - , topologyOptions: topologyOptions - // Promise library - , promiseLibrary: promiseLibrary - } -} - -/** - * AggregationCursor stream data event, fired for each document in the cursor. - * - * @event AggregationCursor#data - * @type {object} - */ - -/** - * AggregationCursor stream end event - * - * @event AggregationCursor#end - * @type {null} - */ - -/** - * AggregationCursor stream close event - * - * @event AggregationCursor#close - * @type {null} - */ - -/** - * AggregationCursor stream readable event - * - * @event AggregationCursor#readable - * @type {null} - */ - -// Inherit from Readable -inherits(AggregationCursor, Readable); - -// Extend the Cursor -for(var name in CoreCursor.prototype) { - AggregationCursor.prototype[name] = CoreCursor.prototype[name]; -} - -var define = AggregationCursor.define = new Define('AggregationCursor', AggregationCursor, true); - -/** - * Set the batch size for the cursor. - * @method - * @param {number} value The batchSize for the cursor. - * @throws {MongoError} - * @return {AggregationCursor} - */ -AggregationCursor.prototype.batchSize = function(value) { - if(this.s.state == AggregationCursor.CLOSED || this.isDead()) throw MongoError.create({message: "Cursor is closed", driver:true }); - if(typeof value != 'number') throw MongoError.create({message: "batchSize requires an integer", driver:true }); - if(this.s.cmd.cursor) this.s.cmd.cursor.batchSize = value; - this.setCursorBatchSize(value); - return this; -} - -define.classMethod('batchSize', {callback: false, promise:false, returns: [AggregationCursor]}); - -/** - * Add a geoNear stage to the aggregation pipeline - * @method - * @param {object} document The geoNear stage document. - * @return {AggregationCursor} - */ -AggregationCursor.prototype.geoNear = function(document) { - this.s.cmd.pipeline.push({$geoNear: document}); - return this; -} - -define.classMethod('geoNear', {callback: false, promise:false, returns: [AggregationCursor]}); - -/** - * Add a group stage to the aggregation pipeline - * @method - * @param {object} document The group stage document. - * @return {AggregationCursor} - */ -AggregationCursor.prototype.group = function(document) { - this.s.cmd.pipeline.push({$group: document}); - return this; -} - -define.classMethod('group', {callback: false, promise:false, returns: [AggregationCursor]}); - -/** - * Add a limit stage to the aggregation pipeline - * @method - * @param {number} value The state limit value. - * @return {AggregationCursor} - */ -AggregationCursor.prototype.limit = function(value) { - this.s.cmd.pipeline.push({$limit: value}); - return this; -} - -define.classMethod('limit', {callback: false, promise:false, returns: [AggregationCursor]}); - -/** - * Add a match stage to the aggregation pipeline - * @method - * @param {object} document The match stage document. - * @return {AggregationCursor} - */ -AggregationCursor.prototype.match = function(document) { - this.s.cmd.pipeline.push({$match: document}); - return this; -} - -define.classMethod('match', {callback: false, promise:false, returns: [AggregationCursor]}); - -/** - * Add a maxTimeMS stage to the aggregation pipeline - * @method - * @param {number} value The state maxTimeMS value. - * @return {AggregationCursor} - */ -AggregationCursor.prototype.maxTimeMS = function(value) { - if(this.s.topology.lastIsMaster().minWireVersion > 2) { - this.s.cmd.maxTimeMS = value; - } - return this; -} - -define.classMethod('maxTimeMS', {callback: false, promise:false, returns: [AggregationCursor]}); - -/** - * Add a out stage to the aggregation pipeline - * @method - * @param {number} destination The destination name. - * @return {AggregationCursor} - */ -AggregationCursor.prototype.out = function(destination) { - this.s.cmd.pipeline.push({$out: destination}); - return this; -} - -define.classMethod('out', {callback: false, promise:false, returns: [AggregationCursor]}); - -/** - * Add a project stage to the aggregation pipeline - * @method - * @param {object} document The project stage document. - * @return {AggregationCursor} - */ -AggregationCursor.prototype.project = function(document) { - this.s.cmd.pipeline.push({$project: document}); - return this; -} - -define.classMethod('project', {callback: false, promise:false, returns: [AggregationCursor]}); - -/** - * Add a lookup stage to the aggregation pipeline - * @method - * @param {object} document The lookup stage document. - * @return {AggregationCursor} - */ -AggregationCursor.prototype.lookup = function(document) { - this.s.cmd.pipeline.push({$lookup: document}); - return this; -} - -define.classMethod('lookup', {callback: false, promise:false, returns: [AggregationCursor]}); - -/** - * Add a redact stage to the aggregation pipeline - * @method - * @param {object} document The redact stage document. - * @return {AggregationCursor} - */ -AggregationCursor.prototype.redact = function(document) { - this.s.cmd.pipeline.push({$redact: document}); - return this; -} - -define.classMethod('redact', {callback: false, promise:false, returns: [AggregationCursor]}); - -/** - * Add a skip stage to the aggregation pipeline - * @method - * @param {number} value The state skip value. - * @return {AggregationCursor} - */ -AggregationCursor.prototype.skip = function(value) { - this.s.cmd.pipeline.push({$skip: value}); - return this; -} - -define.classMethod('skip', {callback: false, promise:false, returns: [AggregationCursor]}); - -/** - * Add a sort stage to the aggregation pipeline - * @method - * @param {object} document The sort stage document. - * @return {AggregationCursor} - */ -AggregationCursor.prototype.sort = function(document) { - this.s.cmd.pipeline.push({$sort: document}); - return this; -} - -define.classMethod('sort', {callback: false, promise:false, returns: [AggregationCursor]}); - -/** - * Add a unwind stage to the aggregation pipeline - * @method - * @param {number} field The unwind field name. - * @return {AggregationCursor} - */ -AggregationCursor.prototype.unwind = function(field) { - this.s.cmd.pipeline.push({$unwind: field}); - return this; -} - -define.classMethod('unwind', {callback: false, promise:false, returns: [AggregationCursor]}); - -AggregationCursor.prototype.get = AggregationCursor.prototype.toArray; - -// Inherited methods -define.classMethod('toArray', {callback: true, promise:true}); -define.classMethod('each', {callback: true, promise:false}); -define.classMethod('forEach', {callback: true, promise:false}); -define.classMethod('hasNext', {callback: true, promise:true}); -define.classMethod('next', {callback: true, promise:true}); -define.classMethod('close', {callback: true, promise:true}); -define.classMethod('isClosed', {callback: false, promise:false, returns: [Boolean]}); -define.classMethod('rewind', {callback: false, promise:false}); -define.classMethod('bufferedCount', {callback: false, promise:false, returns: [Number]}); -define.classMethod('readBufferedDocuments', {callback: false, promise:false, returns: [Array]}); - -/** - * Get the next available document from the cursor, returns null if no more documents are available. - * @function AggregationCursor.prototype.next - * @param {AggregationCursor~resultCallback} [callback] The result callback. - * @throws {MongoError} - * @return {Promise} returns Promise if no callback passed - */ - -/** - * Check if there is any document still available in the cursor - * @function AggregationCursor.prototype.hasNext - * @param {AggregationCursor~resultCallback} [callback] The result callback. - * @throws {MongoError} - * @return {Promise} returns Promise if no callback passed - */ - -/** - * The callback format for results - * @callback AggregationCursor~toArrayResultCallback - * @param {MongoError} error An error instance representing the error during the execution. - * @param {object[]} documents All the documents the satisfy the cursor. - */ - -/** - * Returns an array of documents. The caller is responsible for making sure that there - * is enough memory to store the results. Note that the array only contain partial - * results when this cursor had been previously accessed. In that case, - * cursor.rewind() can be used to reset the cursor. - * @method AggregationCursor.prototype.toArray - * @param {AggregationCursor~toArrayResultCallback} [callback] The result callback. - * @throws {MongoError} - * @return {Promise} returns Promise if no callback passed - */ - -/** - * The callback format for results - * @callback AggregationCursor~resultCallback - * @param {MongoError} error An error instance representing the error during the execution. - * @param {(object|null)} result The result object if the command was executed successfully. - */ - -/** - * Iterates over all the documents for this cursor. As with **{cursor.toArray}**, - * not all of the elements will be iterated if this cursor had been previously accessed. - * In that case, **{cursor.rewind}** can be used to reset the cursor. However, unlike - * **{cursor.toArray}**, the cursor will only hold a maximum of batch size elements - * at any given time if batch size is specified. Otherwise, the caller is responsible - * for making sure that the entire result can fit the memory. - * @method AggregationCursor.prototype.each - * @param {AggregationCursor~resultCallback} callback The result callback. - * @throws {MongoError} - * @return {null} - */ - -/** - * Close the cursor, sending a AggregationCursor command and emitting close. - * @method AggregationCursor.prototype.close - * @param {AggregationCursor~resultCallback} [callback] The result callback. - * @return {Promise} returns Promise if no callback passed - */ - -/** - * Is the cursor closed - * @method AggregationCursor.prototype.isClosed - * @return {boolean} - */ - -/** - * Execute the explain for the cursor - * @method AggregationCursor.prototype.explain - * @param {AggregationCursor~resultCallback} [callback] The result callback. - * @return {Promise} returns Promise if no callback passed - */ - -/** - * Clone the cursor - * @function AggregationCursor.prototype.clone - * @return {AggregationCursor} - */ - -/** - * Resets the cursor - * @function AggregationCursor.prototype.rewind - * @return {AggregationCursor} - */ - -/** - * The callback format for the forEach iterator method - * @callback AggregationCursor~iteratorCallback - * @param {Object} doc An emitted document for the iterator - */ - -/** - * The callback error format for the forEach iterator method - * @callback AggregationCursor~endCallback - * @param {MongoError} error An error instance representing the error during the execution. - */ - -/* - * Iterates over all the documents for this cursor using the iterator, callback pattern. - * @method AggregationCursor.prototype.forEach - * @param {AggregationCursor~iteratorCallback} iterator The iteration callback. - * @param {AggregationCursor~endCallback} callback The end callback. - * @throws {MongoError} - * @return {null} - */ - -AggregationCursor.INIT = 0; -AggregationCursor.OPEN = 1; -AggregationCursor.CLOSED = 2; - -module.exports = AggregationCursor; diff --git a/ts-ticket-office-service/node_modules/mongodb/lib/apm.js b/ts-ticket-office-service/node_modules/mongodb/lib/apm.js deleted file mode 100644 index 494820540..000000000 --- a/ts-ticket-office-service/node_modules/mongodb/lib/apm.js +++ /dev/null @@ -1,596 +0,0 @@ -var EventEmitter = require('events').EventEmitter, - inherits = require('util').inherits; - -// Get prototypes -var AggregationCursor = require('./aggregation_cursor'), - CommandCursor = require('./command_cursor'), - OrderedBulkOperation = require('./bulk/ordered').OrderedBulkOperation, - UnorderedBulkOperation = require('./bulk/unordered').UnorderedBulkOperation, - GridStore = require('./gridfs/grid_store'), - Cursor = require('./cursor'), - Collection = require('./collection'), - Db = require('./db'); - -var basicOperationIdGenerator = { - operationId: 1, - - next: function() { - return this.operationId++; - } -} - -var basicTimestampGenerator = { - current: function() { - return new Date().getTime(); - }, - - duration: function(start, end) { - return end - start; - } -} - -var senstiveCommands = ['authenticate', 'saslStart', 'saslContinue', 'getnonce', - 'createUser', 'updateUser', 'copydbgetnonce', 'copydbsaslstart', 'copydb']; - -var Instrumentation = function(core, options, callback) { - options = options || {}; - - // Optional id generators - var operationIdGenerator = options.operationIdGenerator || basicOperationIdGenerator; - // Optional timestamp generator - var timestampGenerator = options.timestampGenerator || basicTimestampGenerator; - // Extend with event emitter functionality - EventEmitter.call(this); - - // Contains all the instrumentation overloads - this.overloads = []; - - // --------------------------------------------------------- - // - // Instrument prototype - // - // --------------------------------------------------------- - - var instrumentPrototype = function(callback) { - var instrumentations = [] - - // Classes to support - var classes = [GridStore, OrderedBulkOperation, UnorderedBulkOperation, - CommandCursor, AggregationCursor, Cursor, Collection, Db]; - - // Add instrumentations to the available list - for(var i = 0; i < classes.length; i++) { - if(classes[i].define) { - instrumentations.push(classes[i].define.generate()); - } - } - - // Return the list of instrumentation points - callback(null, instrumentations); - } - - // Did the user want to instrument the prototype - if(typeof callback == 'function') { - instrumentPrototype(callback); - } - - // --------------------------------------------------------- - // - // Server - // - // --------------------------------------------------------- - - // Reference - var self = this; - // Names of methods we need to wrap - var methods = ['command', 'insert', 'update', 'remove']; - // Prototype - var proto = core.Server.prototype; - // Core server method we are going to wrap - methods.forEach(function(x) { - var func = proto[x]; - - // Add to overloaded methods - self.overloads.push({proto: proto, name:x, func:func}); - - // The actual prototype - proto[x] = function() { - var requestId = core.Query.nextRequestId(); - // Get the arguments - var args = Array.prototype.slice.call(arguments, 0); - var ns = args[0]; - var commandObj = args[1]; - var options = args[2] || {}; - var keys = Object.keys(commandObj); - var commandName = keys[0]; - var db = ns.split('.')[0]; - - // Get the collection - var col = ns.split('.'); - col.shift(); - col = col.join('.'); - - // Do we have a legacy insert/update/remove command - if(x == 'insert') { //} && !this.lastIsMaster().maxWireVersion) { - commandName = 'insert'; - - // Re-write the command - commandObj = { - insert: col, documents: commandObj - } - - if(options.writeConcern && Object.keys(options.writeConcern).length > 0) { - commandObj.writeConcern = options.writeConcern; - } - - commandObj.ordered = options.ordered != undefined ? options.ordered : true; - } else if(x == 'update') { // && !this.lastIsMaster().maxWireVersion) { - commandName = 'update'; - - // Re-write the command - commandObj = { - update: col, updates: commandObj - } - - if(options.writeConcern && Object.keys(options.writeConcern).length > 0) { - commandObj.writeConcern = options.writeConcern; - } - - commandObj.ordered = options.ordered != undefined ? options.ordered : true; - } else if(x == 'remove') { //&& !this.lastIsMaster().maxWireVersion) { - commandName = 'delete'; - - // Re-write the command - commandObj = { - delete: col, deletes: commandObj - } - - if(options.writeConcern && Object.keys(options.writeConcern).length > 0) { - commandObj.writeConcern = options.writeConcern; - } - - commandObj.ordered = options.ordered != undefined ? options.ordered : true; - } - - // Get the callback - var callback = args.pop(); - // Set current callback operation id from the current context or create - // a new one - var ourOpId = callback.operationId || operationIdGenerator.next(); - - // Get a connection reference for this server instance - var connection = this.s.pool.get() - - // Emit the start event for the command - var command = { - // Returns the command. - command: commandObj, - // Returns the database name. - databaseName: db, - // Returns the command name. - commandName: commandName, - // Returns the driver generated request id. - requestId: requestId, - // Returns the driver generated operation id. - // This is used to link events together such as bulk write operations. OPTIONAL. - operationId: ourOpId, - // Returns the connection id for the command. For languages that do not have this, - // this MUST return the driver equivalent which MUST include the server address and port. - // The name of this field is flexible to match the object that is returned from the driver. - connectionId: connection - }; - - // Filter out any sensitive commands - if(senstiveCommands.indexOf(commandName.toLowerCase()) != -1) { - command.commandObj = {}; - command.commandObj[commandName] = true; - } - - // Emit the started event - self.emit('started', command) - - // Start time - var startTime = timestampGenerator.current(); - - // Push our handler callback - args.push(function(err, r) { - var endTime = timestampGenerator.current(); - var command = { - duration: timestampGenerator.duration(startTime, endTime), - commandName: commandName, - requestId: requestId, - operationId: ourOpId, - connectionId: connection - }; - - // If we have an error - if(err || (r && r.result && r.result.ok == 0)) { - command.failure = err || r.result.writeErrors || r.result; - - // Filter out any sensitive commands - if(senstiveCommands.indexOf(commandName.toLowerCase()) != -1) { - command.failure = {}; - } - - self.emit('failed', command); - } else if(commandObj && commandObj.writeConcern - && commandObj.writeConcern.w == 0) { - // If we have write concern 0 - command.reply = {ok:1}; - self.emit('succeeded', command); - } else { - command.reply = r && r.result ? r.result : r; - - // Filter out any sensitive commands - if(senstiveCommands.indexOf(commandName.toLowerCase()) != -1) { - command.reply = {}; - } - - self.emit('succeeded', command); - } - - // Return to caller - callback(err, r); - }); - - // Apply the call - func.apply(this, args); - } - }); - - // --------------------------------------------------------- - // - // Bulk Operations - // - // --------------------------------------------------------- - - // Inject ourselves into the Bulk methods - methods = ['execute']; - var prototypes = [ - require('./bulk/ordered').Bulk.prototype, - require('./bulk/unordered').Bulk.prototype - ] - - prototypes.forEach(function(proto) { - // Core server method we are going to wrap - methods.forEach(function(x) { - var func = proto[x]; - - // Add to overloaded methods - self.overloads.push({proto: proto, name:x, func:func}); - - // The actual prototype - proto[x] = function() { - // Get the arguments - var args = Array.prototype.slice.call(arguments, 0); - // Set an operation Id on the bulk object - this.operationId = operationIdGenerator.next(); - - // Get the callback - var callback = args.pop(); - // If we have a callback use this - if(typeof callback == 'function') { - args.push(function(err, r) { - // Return to caller - callback(err, r); - }); - - // Apply the call - func.apply(this, args); - } else { - return func.apply(this, args); - } - } - }); - }); - - // --------------------------------------------------------- - // - // Cursor - // - // --------------------------------------------------------- - - // Inject ourselves into the Cursor methods - methods = ['_find', '_getmore', '_killcursor']; - prototypes = [ - require('./cursor').prototype, - require('./command_cursor').prototype, - require('./aggregation_cursor').prototype - ] - - // Command name translation - var commandTranslation = { - '_find': 'find', '_getmore': 'getMore', '_killcursor': 'killCursors', '_explain': 'explain' - } - - prototypes.forEach(function(proto) { - - // Core server method we are going to wrap - methods.forEach(function(x) { - var func = proto[x]; - - // Add to overloaded methods - self.overloads.push({proto: proto, name:x, func:func}); - - // The actual prototype - proto[x] = function() { - var cursor = this; - var requestId = core.Query.nextRequestId(); - var ourOpId = operationIdGenerator.next(); - var parts = this.ns.split('.'); - var db = parts[0]; - - // Get the collection - parts.shift(); - var collection = parts.join('.'); - - // Set the command - var command = this.query; - var cmd = this.s.cmd; - - // If we have a find method, set the operationId on the cursor - if(x == '_find') { - cursor.operationId = ourOpId; - } - - // Do we have a find command rewrite it - if(x == '_getmore') { - command = { - getMore: this.cursorState.cursorId, - collection: collection, - batchSize: cmd.batchSize - } - - if(cmd.maxTimeMS) command.maxTimeMS = cmd.maxTimeMS; - } else if(x == '_killcursor') { - command = { - killCursors: collection, - cursors: [this.cursorState.cursorId] - } - } else if(cmd.find) { - command = { - find: collection, filter: cmd.query - } - - if(cmd.sort) command.sort = cmd.sort; - if(cmd.fields) command.projection = cmd.fields; - if(cmd.limit && cmd.limit < 0) { - command.limit = Math.abs(cmd.limit); - command.singleBatch = true; - } else if(cmd.limit) { - command.limit = Math.abs(cmd.limit); - } - - // Options - if(cmd.skip) command.skip = cmd.skip; - if(cmd.hint) command.hint = cmd.hint; - if(cmd.batchSize) command.batchSize = cmd.batchSize; - if(typeof cmd.returnKey == 'boolean') command.returnKey = cmd.returnKey; - if(cmd.comment) command.comment = cmd.comment; - if(cmd.min) command.min = cmd.min; - if(cmd.max) command.max = cmd.max; - if(cmd.maxScan) command.maxScan = cmd.maxScan; - if(cmd.maxTimeMS) command.maxTimeMS = cmd.maxTimeMS; - - // Flags - if(typeof cmd.awaitData == 'boolean') command.awaitData = cmd.awaitData; - if(typeof cmd.snapshot == 'boolean') command.snapshot = cmd.snapshot; - if(typeof cmd.tailable == 'boolean') command.tailable = cmd.tailable; - if(typeof cmd.oplogReplay == 'boolean') command.oplogReplay = cmd.oplogReplay; - if(typeof cmd.noCursorTimeout == 'boolean') command.noCursorTimeout = cmd.noCursorTimeout; - if(typeof cmd.partial == 'boolean') command.partial = cmd.partial; - if(typeof cmd.showDiskLoc == 'boolean') command.showRecordId = cmd.showDiskLoc; - - // Read Concern - if(cmd.readConcern) command.readConcern = cmd.readConcern; - - // Override method - if(cmd.explain) command.explain = cmd.explain; - if(cmd.exhaust) command.exhaust = cmd.exhaust; - - // If we have a explain flag - if(cmd.explain) { - // Create fake explain command - command = { - explain: command, - verbosity: 'allPlansExecution' - } - - // Set readConcern on the command if available - if(cmd.readConcern) command.readConcern = cmd.readConcern - - // Set up the _explain name for the command - x = '_explain'; - } - } else { - command = cmd; - } - - // Set up the connection - var connectionId = null; - - // Set local connection - if(this.connection) connectionId = this.connection; - if(!connectionId && this.server && this.server.getConnection) connectionId = this.server.getConnection(); - - // Get the command Name - var commandName = x == '_find' ? Object.keys(command)[0] : commandTranslation[x]; - - // Emit the start event for the command - command = { - // Returns the command. - command: command, - // Returns the database name. - databaseName: db, - // Returns the command name. - commandName: commandName, - // Returns the driver generated request id. - requestId: requestId, - // Returns the driver generated operation id. - // This is used to link events together such as bulk write operations. OPTIONAL. - operationId: this.operationId, - // Returns the connection id for the command. For languages that do not have this, - // this MUST return the driver equivalent which MUST include the server address and port. - // The name of this field is flexible to match the object that is returned from the driver. - connectionId: connectionId - }; - - // Get the arguments - var args = Array.prototype.slice.call(arguments, 0); - - // Get the callback - var callback = args.pop(); - - // We do not have a callback but a Promise - if(typeof callback == 'function' || command.commandName == 'killCursors') { - var startTime = timestampGenerator.current(); - // Emit the started event - self.emit('started', command) - - // Emit succeeded event with killcursor if we have a legacy protocol - if(command.commandName == 'killCursors' - && this.server.lastIsMaster() - && this.server.lastIsMaster().maxWireVersion < 4) { - // Emit the succeeded command - command = { - duration: timestampGenerator.duration(startTime, timestampGenerator.current()), - commandName: commandName, - requestId: requestId, - operationId: cursor.operationId, - connectionId: cursor.server.getConnection(), - reply: [{ok:1}] - }; - - // Apply callback to the list of args - args.push(callback); - // Apply the call - func.apply(this, args); - // Emit the command - return self.emit('succeeded', command) - } - - // Add our callback handler - args.push(function(err, r) { - if(err) { - // Command - var command = { - duration: timestampGenerator.duration(startTime, timestampGenerator.current()), - commandName: commandName, - requestId: requestId, - operationId: ourOpId, - connectionId: cursor.server.getConnection(), - failure: err }; - - // Emit the command - self.emit('failed', command) - } else { - // Do we have a getMore - if(commandName.toLowerCase() == 'getmore' && r == null) { - r = { - cursor: { - id: cursor.cursorState.cursorId, - ns: cursor.ns, - nextBatch: cursor.cursorState.documents - }, ok:1 - } - } else if((commandName.toLowerCase() == 'find' - || commandName.toLowerCase() == 'aggregate' - || commandName.toLowerCase() == 'listcollections') && r == null) { - r = { - cursor: { - id: cursor.cursorState.cursorId, - ns: cursor.ns, - firstBatch: cursor.cursorState.documents - }, ok:1 - } - } else if(commandName.toLowerCase() == 'killcursors' && r == null) { - r = { - cursorsUnknown:[cursor.cursorState.lastCursorId], - ok:1 - } - } - - // cursor id is zero, we can issue success command - command = { - duration: timestampGenerator.duration(startTime, timestampGenerator.current()), - commandName: commandName, - requestId: requestId, - operationId: cursor.operationId, - connectionId: cursor.server.getConnection(), - reply: r && r.result ? r.result : r - }; - - // Emit the command - self.emit('succeeded', command) - } - - // Return - if(!callback) return; - - // Return to caller - callback(err, r); - }); - - // Apply the call - func.apply(this, args); - } else { - // Assume promise, push back the missing value - args.push(callback); - // Get the promise - var promise = func.apply(this, args); - // Return a new promise - return new cursor.s.promiseLibrary(function(resolve, reject) { - var startTime = timestampGenerator.current(); - // Emit the started event - self.emit('started', command) - // Execute the function - promise.then(function() { - // cursor id is zero, we can issue success command - var command = { - duration: timestampGenerator.duration(startTime, timestampGenerator.current()), - commandName: commandName, - requestId: requestId, - operationId: cursor.operationId, - connectionId: cursor.server.getConnection(), - reply: cursor.cursorState.documents - }; - - // Emit the command - self.emit('succeeded', command) - }).catch(function(err) { - // Command - var command = { - duration: timestampGenerator.duration(startTime, timestampGenerator.current()), - commandName: commandName, - requestId: requestId, - operationId: ourOpId, - connectionId: cursor.server.getConnection(), - failure: err }; - - // Emit the command - self.emit('failed', command) - // reject the promise - reject(err); - }); - }); - } - } - }); - }); -} - -inherits(Instrumentation, EventEmitter); - -Instrumentation.prototype.uninstrument = function() { - for(var i = 0; i < this.overloads.length; i++) { - var obj = this.overloads[i]; - obj.proto[obj.name] = obj.func; - } - - // Remove all listeners - this.removeAllListeners('started'); - this.removeAllListeners('succeeded'); - this.removeAllListeners('failed'); -} - -module.exports = Instrumentation; diff --git a/ts-ticket-office-service/node_modules/mongodb/lib/authenticate.js b/ts-ticket-office-service/node_modules/mongodb/lib/authenticate.js deleted file mode 100644 index e732625dd..000000000 --- a/ts-ticket-office-service/node_modules/mongodb/lib/authenticate.js +++ /dev/null @@ -1,109 +0,0 @@ -var shallowClone = require('./utils').shallowClone - , handleCallback = require('./utils').handleCallback - , MongoError = require('mongodb-core').MongoError; - -var authenticate = function(self, username, password, options, callback) { - // Did the user destroy the topology - if(self.serverConfig && self.serverConfig.isDestroyed()) return callback(new MongoError('topology was destroyed')); - - // the default db to authenticate against is 'self' - // if authenticate is called from a retry context, it may be another one, like admin - var authdb = options.dbName ? options.dbName : self.databaseName; - authdb = self.authSource ? self.authSource : authdb; - authdb = options.authdb ? options.authdb : authdb; - authdb = options.authSource ? options.authSource : authdb; - - // Callback - var _callback = function(err, result) { - if(self.listeners('authenticated').length > 0) { - self.emit('authenticated', err, result); - } - - // Return to caller - handleCallback(callback, err, result); - } - - // authMechanism - var authMechanism = options.authMechanism || ''; - authMechanism = authMechanism.toUpperCase(); - - // If classic auth delegate to auth command - if(authMechanism == 'MONGODB-CR') { - self.s.topology.auth('mongocr', authdb, username, password, function(err) { - if(err) return handleCallback(callback, err, false); - _callback(null, true); - }); - } else if(authMechanism == 'PLAIN') { - self.s.topology.auth('plain', authdb, username, password, function(err) { - if(err) return handleCallback(callback, err, false); - _callback(null, true); - }); - } else if(authMechanism == 'MONGODB-X509') { - self.s.topology.auth('x509', authdb, username, password, function(err) { - if(err) return handleCallback(callback, err, false); - _callback(null, true); - }); - } else if(authMechanism == 'SCRAM-SHA-1') { - self.s.topology.auth('scram-sha-1', authdb, username, password, function(err) { - if(err) return handleCallback(callback, err, false); - _callback(null, true); - }); - } else if(authMechanism == 'GSSAPI') { - if(process.platform == 'win32') { - self.s.topology.auth('sspi', authdb, username, password, options, function(err) { - if(err) return handleCallback(callback, err, false); - _callback(null, true); - }); - } else { - self.s.topology.auth('gssapi', authdb, username, password, options, function(err) { - if(err) return handleCallback(callback, err, false); - _callback(null, true); - }); - } - } else if(authMechanism == 'DEFAULT') { - self.s.topology.auth('default', authdb, username, password, function(err) { - if(err) return handleCallback(callback, err, false); - _callback(null, true); - }); - } else { - handleCallback(callback, MongoError.create({message: f("authentication mechanism %s not supported", options.authMechanism), driver:true})); - } -} - -module.exports = function(self, username, password, options, callback) { - if(typeof options == 'function') callback = options, options = {}; - // Shallow copy the options - options = shallowClone(options); - - // Set default mechanism - if(!options.authMechanism) { - options.authMechanism = 'DEFAULT'; - } else if(options.authMechanism != 'GSSAPI' - && options.authMechanism != 'DEFAULT' - && options.authMechanism != 'MONGODB-CR' - && options.authMechanism != 'MONGODB-X509' - && options.authMechanism != 'SCRAM-SHA-1' - && options.authMechanism != 'PLAIN') { - return handleCallback(callback, MongoError.create({message: "only DEFAULT, GSSAPI, PLAIN, MONGODB-X509, SCRAM-SHA-1 or MONGODB-CR is supported by authMechanism", driver:true})); - } - - // If we have a callback fallback - if(typeof callback == 'function') return authenticate(self, username, password, options, function(err, r) { - // Support failed auth method - if(err && err.message && err.message.indexOf('saslStart') != -1) err.code = 59; - // Reject error - if(err) return callback(err, r); - callback(null, r); - }); - - // Return a promise - return new self.s.promiseLibrary(function(resolve, reject) { - authenticate(self, username, password, options, function(err, r) { - // Support failed auth method - if(err && err.message && err.message.indexOf('saslStart') != -1) err.code = 59; - // Reject error - if(err) return reject(err); - resolve(r); - }); - }); -}; diff --git a/ts-ticket-office-service/node_modules/mongodb/lib/bson.js b/ts-ticket-office-service/node_modules/mongodb/lib/bson.js new file mode 100644 index 000000000..f825a907f --- /dev/null +++ b/ts-ticket-office-service/node_modules/mongodb/lib/bson.js @@ -0,0 +1,69 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.resolveBSONOptions = exports.pluckBSONSerializeOptions = exports.Timestamp = exports.ObjectId = exports.MinKey = exports.MaxKey = exports.Map = exports.Long = exports.Int32 = exports.Double = exports.Decimal128 = exports.DBRef = exports.Code = exports.BSONSymbol = exports.BSONRegExp = exports.Binary = exports.calculateObjectSize = exports.serialize = exports.deserialize = void 0; +// eslint-disable-next-line @typescript-eslint/no-var-requires +let BSON = require('bson'); +try { + // Ensure you always wrap an optional require in the try block NODE-3199 + BSON = require('bson-ext'); +} +catch { } // eslint-disable-line +/** @internal */ +exports.deserialize = BSON.deserialize; +/** @internal */ +exports.serialize = BSON.serialize; +/** @internal */ +exports.calculateObjectSize = BSON.calculateObjectSize; +var bson_1 = require("bson"); +Object.defineProperty(exports, "Binary", { enumerable: true, get: function () { return bson_1.Binary; } }); +Object.defineProperty(exports, "BSONRegExp", { enumerable: true, get: function () { return bson_1.BSONRegExp; } }); +Object.defineProperty(exports, "BSONSymbol", { enumerable: true, get: function () { return bson_1.BSONSymbol; } }); +Object.defineProperty(exports, "Code", { enumerable: true, get: function () { return bson_1.Code; } }); +Object.defineProperty(exports, "DBRef", { enumerable: true, get: function () { return bson_1.DBRef; } }); +Object.defineProperty(exports, "Decimal128", { enumerable: true, get: function () { return bson_1.Decimal128; } }); +Object.defineProperty(exports, "Double", { enumerable: true, get: function () { return bson_1.Double; } }); +Object.defineProperty(exports, "Int32", { enumerable: true, get: function () { return bson_1.Int32; } }); +Object.defineProperty(exports, "Long", { enumerable: true, get: function () { return bson_1.Long; } }); +Object.defineProperty(exports, "Map", { enumerable: true, get: function () { return bson_1.Map; } }); +Object.defineProperty(exports, "MaxKey", { enumerable: true, get: function () { return bson_1.MaxKey; } }); +Object.defineProperty(exports, "MinKey", { enumerable: true, get: function () { return bson_1.MinKey; } }); +Object.defineProperty(exports, "ObjectId", { enumerable: true, get: function () { return bson_1.ObjectId; } }); +Object.defineProperty(exports, "Timestamp", { enumerable: true, get: function () { return bson_1.Timestamp; } }); +function pluckBSONSerializeOptions(options) { + const { fieldsAsRaw, promoteValues, promoteBuffers, promoteLongs, serializeFunctions, ignoreUndefined, bsonRegExp, raw, enableUtf8Validation } = options; + return { + fieldsAsRaw, + promoteValues, + promoteBuffers, + promoteLongs, + serializeFunctions, + ignoreUndefined, + bsonRegExp, + raw, + enableUtf8Validation + }; +} +exports.pluckBSONSerializeOptions = pluckBSONSerializeOptions; +/** + * Merge the given BSONSerializeOptions, preferring options over the parent's options, and + * substituting defaults for values not set. + * + * @internal + */ +function resolveBSONOptions(options, parent) { + var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l, _m, _o, _p, _q, _r, _s, _t; + const parentOptions = parent === null || parent === void 0 ? void 0 : parent.bsonOptions; + return { + raw: (_b = (_a = options === null || options === void 0 ? void 0 : options.raw) !== null && _a !== void 0 ? _a : parentOptions === null || parentOptions === void 0 ? void 0 : parentOptions.raw) !== null && _b !== void 0 ? _b : false, + promoteLongs: (_d = (_c = options === null || options === void 0 ? void 0 : options.promoteLongs) !== null && _c !== void 0 ? _c : parentOptions === null || parentOptions === void 0 ? void 0 : parentOptions.promoteLongs) !== null && _d !== void 0 ? _d : true, + promoteValues: (_f = (_e = options === null || options === void 0 ? void 0 : options.promoteValues) !== null && _e !== void 0 ? _e : parentOptions === null || parentOptions === void 0 ? void 0 : parentOptions.promoteValues) !== null && _f !== void 0 ? _f : true, + promoteBuffers: (_h = (_g = options === null || options === void 0 ? void 0 : options.promoteBuffers) !== null && _g !== void 0 ? _g : parentOptions === null || parentOptions === void 0 ? void 0 : parentOptions.promoteBuffers) !== null && _h !== void 0 ? _h : false, + ignoreUndefined: (_k = (_j = options === null || options === void 0 ? void 0 : options.ignoreUndefined) !== null && _j !== void 0 ? _j : parentOptions === null || parentOptions === void 0 ? void 0 : parentOptions.ignoreUndefined) !== null && _k !== void 0 ? _k : false, + bsonRegExp: (_m = (_l = options === null || options === void 0 ? void 0 : options.bsonRegExp) !== null && _l !== void 0 ? _l : parentOptions === null || parentOptions === void 0 ? void 0 : parentOptions.bsonRegExp) !== null && _m !== void 0 ? _m : false, + serializeFunctions: (_p = (_o = options === null || options === void 0 ? void 0 : options.serializeFunctions) !== null && _o !== void 0 ? _o : parentOptions === null || parentOptions === void 0 ? void 0 : parentOptions.serializeFunctions) !== null && _p !== void 0 ? _p : false, + fieldsAsRaw: (_r = (_q = options === null || options === void 0 ? void 0 : options.fieldsAsRaw) !== null && _q !== void 0 ? _q : parentOptions === null || parentOptions === void 0 ? void 0 : parentOptions.fieldsAsRaw) !== null && _r !== void 0 ? _r : {}, + enableUtf8Validation: (_t = (_s = options === null || options === void 0 ? void 0 : options.enableUtf8Validation) !== null && _s !== void 0 ? _s : parentOptions === null || parentOptions === void 0 ? void 0 : parentOptions.enableUtf8Validation) !== null && _t !== void 0 ? _t : true + }; +} +exports.resolveBSONOptions = resolveBSONOptions; +//# sourceMappingURL=bson.js.map \ No newline at end of file diff --git a/ts-ticket-office-service/node_modules/mongodb/lib/bson.js.map b/ts-ticket-office-service/node_modules/mongodb/lib/bson.js.map new file mode 100644 index 000000000..fcd7b7a3f --- /dev/null +++ b/ts-ticket-office-service/node_modules/mongodb/lib/bson.js.map @@ -0,0 +1 @@ +{"version":3,"file":"bson.js","sourceRoot":"","sources":["../src/bson.ts"],"names":[],"mappings":";;;AAQA,8DAA8D;AAC9D,IAAI,IAAI,GAAG,OAAO,CAAC,MAAM,CAAC,CAAC;AAE3B,IAAI;IACF,wEAAwE;IACxE,IAAI,GAAG,OAAO,CAAC,UAAU,CAAC,CAAC;CAC5B;AAAC,MAAM,GAAE,CAAC,sBAAsB;AAEjC,gBAAgB;AACH,QAAA,WAAW,GAAG,IAAI,CAAC,WAAmC,CAAC;AACpE,gBAAgB;AACH,QAAA,SAAS,GAAG,IAAI,CAAC,SAA+B,CAAC;AAC9D,gBAAgB;AACH,QAAA,mBAAmB,GAAG,IAAI,CAAC,mBAAmD,CAAC;AAE5F,6BAgBc;AAfZ,8FAAA,MAAM,OAAA;AACN,kGAAA,UAAU,OAAA;AACV,kGAAA,UAAU,OAAA;AACV,4FAAA,IAAI,OAAA;AACJ,6FAAA,KAAK,OAAA;AACL,kGAAA,UAAU,OAAA;AAEV,8FAAA,MAAM,OAAA;AACN,6FAAA,KAAK,OAAA;AACL,4FAAA,IAAI,OAAA;AACJ,2FAAA,GAAG,OAAA;AACH,8FAAA,MAAM,OAAA;AACN,8FAAA,MAAM,OAAA;AACN,gGAAA,QAAQ,OAAA;AACR,iGAAA,SAAS,OAAA;AAyBX,SAAgB,yBAAyB,CAAC,OAA6B;IACrE,MAAM,EACJ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a,CAAE,UAAU,mCAAI,KAAK;QACrE,kBAAkB,EAAE,MAAA,MAAA,OAAO,aAAP,OAAO,uBAAP,OAAO,CAAE,kBAAkB,mCAAI,aAAa,aAAb,aAAa,uBAAb,aAAa,CAAE,kBAAkB,mCAAI,KAAK;QAC7F,WAAW,EAAE,MAAA,MAAA,OAAO,aAAP,OAAO,uBAAP,OAAO,CAAE,WAAW,mCAAI,aAAa,aAAb,aAAa,uBAAb,aAAa,CAAE,WAAW,mCAAI,EAAE;QACrE,oBAAoB,EAClB,MAAA,MAAA,OAAO,aAAP,OAAO,uBAAP,OAAO,CAAE,oBAAoB,mCAAI,aAAa,aAAb,aAAa,uBAAb,aAAa,CAAE,oBAAoB,mCAAI,IAAI;KAC/E,CAAC;AACJ,CAAC;AAjBD,gDAiBC"} \ No newline at end of file diff --git a/ts-ticket-office-service/node_modules/mongodb/lib/bulk/common.js b/ts-ticket-office-service/node_modules/mongodb/lib/bulk/common.js index 6ebe3ef33..330761cab 100644 --- a/ts-ticket-office-service/node_modules/mongodb/lib/bulk/common.js +++ b/ts-ticket-office-service/node_modules/mongodb/lib/bulk/common.js @@ -1,440 +1,966 @@ "use strict"; - -var Long = require('mongodb-core').BSON.Long, - Timestamp = require('mongodb-core').BSON.Timestamp; - -// Error codes -var UNKNOWN_ERROR = 8; -var INVALID_BSON_ERROR = 22; -var WRITE_CONCERN_ERROR = 64; -var MULTIPLE_ERROR = 65; - -// Insert types -var INSERT = 1; -var UPDATE = 2; -var REMOVE = 3 - - -// Get write concern -var writeConcern = function(target, col, options) { - var writeConcern = {}; - - // Collection level write concern - if(col.writeConcern && col.writeConcern.w != null) writeConcern.w = col.writeConcern.w; - if(col.writeConcern && col.writeConcern.j != null) writeConcern.j = col.writeConcern.j; - if(col.writeConcern && col.writeConcern.fsync != null) writeConcern.fsync = col.writeConcern.fsync; - if(col.writeConcern && col.writeConcern.wtimeout != null) writeConcern.wtimeout = col.writeConcern.wtimeout; - - // Options level write concern - if(options && options.w != null) writeConcern.w = options.w; - if(options && options.wtimeout != null) writeConcern.wtimeout = options.wtimeout; - if(options && options.j != null) writeConcern.j = options.j; - if(options && options.fsync != null) writeConcern.fsync = options.fsync; - - // Return write concern - return writeConcern; -} - +Object.defineProperty(exports, "__esModule", { value: true }); +exports.BulkOperationBase = exports.FindOperators = exports.MongoBulkWriteError = exports.mergeBatchResults = exports.WriteError = exports.WriteConcernError = exports.BulkWriteResult = exports.Batch = exports.BatchType = void 0; +const bson_1 = require("../bson"); +const error_1 = require("../error"); +const delete_1 = require("../operations/delete"); +const execute_operation_1 = require("../operations/execute_operation"); +const insert_1 = require("../operations/insert"); +const operation_1 = require("../operations/operation"); +const update_1 = require("../operations/update"); +const promise_provider_1 = require("../promise_provider"); +const utils_1 = require("../utils"); +const write_concern_1 = require("../write_concern"); +/** @internal */ +const kServerError = Symbol('serverError'); +/** @public */ +exports.BatchType = Object.freeze({ + INSERT: 1, + UPDATE: 2, + DELETE: 3 +}); /** - * Helper function to define properties - * @ignore + * Keeps the state of a unordered batch so we can rewrite the results + * correctly after command execution + * + * @public */ -var defineReadOnlyProperty = function(self, name, value) { - Object.defineProperty(self, name, { - enumerable: true - , get: function() { - return value; +class Batch { + constructor(batchType, originalZeroIndex) { + this.originalZeroIndex = originalZeroIndex; + this.currentIndex = 0; + this.originalIndexes = []; + this.batchType = batchType; + this.operations = []; + this.size = 0; + this.sizeBytes = 0; } - }); } - +exports.Batch = Batch; /** - * Keeps the state of a unordered batch so we can rewrite the results - * correctly after command execution - * @ignore + * @public + * The result of a bulk write. */ -var Batch = function(batchType, originalZeroIndex) { - this.originalZeroIndex = originalZeroIndex; - this.currentIndex = 0; - this.originalIndexes = []; - this.batchType = batchType; - this.operations = []; - this.size = 0; - this.sizeBytes = 0; +class BulkWriteResult { + /** + * Create a new BulkWriteResult instance + * @internal + */ + constructor(bulkResult) { + this.result = bulkResult; + } + /** Number of documents inserted. */ + get insertedCount() { + var _a; + return (_a = this.result.nInserted) !== null && _a !== void 0 ? _a : 0; + } + /** Number of documents matched for update. */ + get matchedCount() { + var _a; + return (_a = this.result.nMatched) !== null && _a !== void 0 ? _a : 0; + } + /** Number of documents modified. */ + get modifiedCount() { + var _a; + return (_a = this.result.nModified) !== null && _a !== void 0 ? _a : 0; + } + /** Number of documents deleted. */ + get deletedCount() { + var _a; + return (_a = this.result.nRemoved) !== null && _a !== void 0 ? _a : 0; + } + /** Number of documents upserted. */ + get upsertedCount() { + var _a; + return (_a = this.result.upserted.length) !== null && _a !== void 0 ? _a : 0; + } + /** Upserted document generated Id's, hash key is the index of the originating operation */ + get upsertedIds() { + var _a; + const upserted = {}; + for (const doc of (_a = this.result.upserted) !== null && _a !== void 0 ? _a : []) { + upserted[doc.index] = doc._id; + } + return upserted; + } + /** Inserted document generated Id's, hash key is the index of the originating operation */ + get insertedIds() { + var _a; + const inserted = {}; + for (const doc of (_a = this.result.insertedIds) !== null && _a !== void 0 ? _a : []) { + inserted[doc.index] = doc._id; + } + return inserted; + } + /** Evaluates to true if the bulk operation correctly executes */ + get ok() { + return this.result.ok; + } + /** The number of inserted documents */ + get nInserted() { + return this.result.nInserted; + } + /** Number of upserted documents */ + get nUpserted() { + return this.result.nUpserted; + } + /** Number of matched documents */ + get nMatched() { + return this.result.nMatched; + } + /** Number of documents updated physically on disk */ + get nModified() { + return this.result.nModified; + } + /** Number of removed documents */ + get nRemoved() { + return this.result.nRemoved; + } + /** Returns an array of all inserted ids */ + getInsertedIds() { + return this.result.insertedIds; + } + /** Returns an array of all upserted ids */ + getUpsertedIds() { + return this.result.upserted; + } + /** Returns the upserted id at the given index */ + getUpsertedIdAt(index) { + return this.result.upserted[index]; + } + /** Returns raw internal result */ + getRawResponse() { + return this.result; + } + /** Returns true if the bulk operation contains a write error */ + hasWriteErrors() { + return this.result.writeErrors.length > 0; + } + /** Returns the number of write errors off the bulk operation */ + getWriteErrorCount() { + return this.result.writeErrors.length; + } + /** Returns a specific write error object */ + getWriteErrorAt(index) { + return index < this.result.writeErrors.length ? this.result.writeErrors[index] : undefined; + } + /** Retrieve all write errors */ + getWriteErrors() { + return this.result.writeErrors; + } + /** Retrieve lastOp if available */ + getLastOp() { + return this.result.opTime; + } + /** Retrieve the write concern error if one exists */ + getWriteConcernError() { + if (this.result.writeConcernErrors.length === 0) { + return; + } + else if (this.result.writeConcernErrors.length === 1) { + // Return the error + return this.result.writeConcernErrors[0]; + } + else { + // Combine the errors + let errmsg = ''; + for (let i = 0; i < this.result.writeConcernErrors.length; i++) { + const err = this.result.writeConcernErrors[i]; + errmsg = errmsg + err.errmsg; + // TODO: Something better + if (i === 0) + errmsg = errmsg + ' and '; + } + return new WriteConcernError({ errmsg, code: error_1.MONGODB_ERROR_CODES.WriteConcernFailed }); + } + } + toJSON() { + return this.result; + } + toString() { + return `BulkWriteResult(${this.toJSON()})`; + } + isOk() { + return this.result.ok === 1; + } } - +exports.BulkWriteResult = BulkWriteResult; /** - * Wraps a legacy operation so we can correctly rewrite it's error - * @ignore + * An error representing a failure by the server to apply the requested write concern to the bulk operation. + * @public + * @category Error */ -var LegacyOp = function(batchType, operation, index) { - this.batchType = batchType; - this.index = index; - this.operation = operation; +class WriteConcernError { + constructor(error) { + this[kServerError] = error; + } + /** Write concern error code. */ + get code() { + return this[kServerError].code; + } + /** Write concern error message. */ + get errmsg() { + return this[kServerError].errmsg; + } + /** Write concern error info. */ + get errInfo() { + return this[kServerError].errInfo; + } + /** @deprecated The `err` prop that contained a MongoServerError has been deprecated. */ + get err() { + return this[kServerError]; + } + toJSON() { + return this[kServerError]; + } + toString() { + return `WriteConcernError(${this.errmsg})`; + } } - +exports.WriteConcernError = WriteConcernError; /** - * Create a new BulkWriteResult instance (INTERNAL TYPE, do not instantiate directly) - * - * @class - * @property {boolean} ok Did bulk operation correctly execute - * @property {number} nInserted number of inserted documents - * @property {number} nUpdated number of documents updated logically - * @property {number} nUpserted Number of upserted documents - * @property {number} nModified Number of documents updated physically on disk - * @property {number} nRemoved Number of removed documents - * @return {BulkWriteResult} a BulkWriteResult instance + * An error that occurred during a BulkWrite on the server. + * @public + * @category Error */ -var BulkWriteResult = function(bulkResult) { - defineReadOnlyProperty(this, "ok", bulkResult.ok); - defineReadOnlyProperty(this, "nInserted", bulkResult.nInserted); - defineReadOnlyProperty(this, "nUpserted", bulkResult.nUpserted); - defineReadOnlyProperty(this, "nMatched", bulkResult.nMatched); - defineReadOnlyProperty(this, "nModified", bulkResult.nModified); - defineReadOnlyProperty(this, "nRemoved", bulkResult.nRemoved); - - /** - * Return an array of inserted ids - * - * @return {object[]} - */ - this.getInsertedIds = function() { - return bulkResult.insertedIds; - } - - /** - * Return an array of upserted ids - * - * @return {object[]} - */ - this.getUpsertedIds = function() { - return bulkResult.upserted; - } - - /** - * Return the upserted id at position x - * - * @param {number} index the number of the upserted id to return, returns undefined if no result for passed in index - * @return {object} - */ - this.getUpsertedIdAt = function(index) { - return bulkResult.upserted[index]; - } - - /** - * Return raw internal result - * - * @return {object} - */ - this.getRawResponse = function() { - return bulkResult; - } - - /** - * Returns true if the bulk operation contains a write error - * - * @return {boolean} - */ - this.hasWriteErrors = function() { - return bulkResult.writeErrors.length > 0; - } - - /** - * Returns the number of write errors off the bulk operation - * - * @return {number} - */ - this.getWriteErrorCount = function() { - return bulkResult.writeErrors.length; - } - - /** - * Returns a specific write error object - * - * @param {number} index of the write error to return, returns null if there is no result for passed in index - * @return {WriteError} - */ - this.getWriteErrorAt = function(index) { - if(index < bulkResult.writeErrors.length) { - return bulkResult.writeErrors[index]; - } - return null; - } - - /** - * Retrieve all write errors - * - * @return {object[]} - */ - this.getWriteErrors = function() { - return bulkResult.writeErrors; - } - - /** - * Retrieve lastOp if available - * - * @return {object} - */ - this.getLastOp = function() { - return bulkResult.lastOp; - } - - /** - * Retrieve the write concern error if any - * - * @return {WriteConcernError} - */ - this.getWriteConcernError = function() { - if(bulkResult.writeConcernErrors.length == 0) { - return null; - } else if(bulkResult.writeConcernErrors.length == 1) { - // Return the error - return bulkResult.writeConcernErrors[0]; - } else { - - // Combine the errors - var errmsg = ""; - for(var i = 0; i < bulkResult.writeConcernErrors.length; i++) { - var err = bulkResult.writeConcernErrors[i]; - errmsg = errmsg + err.errmsg; - - // TODO: Something better - if(i == 0) errmsg = errmsg + " and "; - } - - return new WriteConcernError({ errmsg : errmsg, code : WRITE_CONCERN_ERROR }); - } - } - - this.toJSON = function() { - return bulkResult; - } - - this.toString = function() { - return "BulkWriteResult(" + this.toJSON(bulkResult) + ")"; - } - - this.isOk = function() { - return bulkResult.ok == 1; - } +class WriteError { + constructor(err) { + this.err = err; + } + /** WriteError code. */ + get code() { + return this.err.code; + } + /** WriteError original bulk operation index. */ + get index() { + return this.err.index; + } + /** WriteError message. */ + get errmsg() { + return this.err.errmsg; + } + /** WriteError details. */ + get errInfo() { + return this.err.errInfo; + } + /** Returns the underlying operation that caused the error */ + getOperation() { + return this.err.op; + } + toJSON() { + return { code: this.err.code, index: this.err.index, errmsg: this.err.errmsg, op: this.err.op }; + } + toString() { + return `WriteError(${JSON.stringify(this.toJSON())})`; + } +} +exports.WriteError = WriteError; +/** Converts the number to a Long or returns it. */ +function longOrConvert(value) { + return typeof value === 'number' ? bson_1.Long.fromNumber(value) : value; +} +/** Merges results into shared data structure */ +function mergeBatchResults(batch, bulkResult, err, result) { + // If we have an error set the result to be the err object + if (err) { + result = err; + } + else if (result && result.result) { + result = result.result; + } + if (result == null) { + return; + } + // Do we have a top level error stop processing and return + if (result.ok === 0 && bulkResult.ok === 1) { + bulkResult.ok = 0; + const writeError = { + index: 0, + code: result.code || 0, + errmsg: result.message, + errInfo: result.errInfo, + op: batch.operations[0] + }; + bulkResult.writeErrors.push(new WriteError(writeError)); + return; + } + else if (result.ok === 0 && bulkResult.ok === 0) { + return; + } + // The server write command specification states that lastOp is an optional + // mongod only field that has a type of timestamp. Across various scarce specs + // where opTime is mentioned, it is an "opaque" object that can have a "ts" and + // "t" field with Timestamp and Long as their types respectively. + // The "lastOp" field of the bulk write result is never mentioned in the driver + // specifications or the bulk write spec, so we should probably just keep its + // value consistent since it seems to vary. + // See: https://github.com/mongodb/specifications/blob/master/source/driver-bulk-update.rst#results-object + if (result.opTime || result.lastOp) { + let opTime = result.lastOp || result.opTime; + // If the opTime is a Timestamp, convert it to a consistent format to be + // able to compare easily. Converting to the object from a timestamp is + // much more straightforward than the other direction. + if (opTime._bsontype === 'Timestamp') { + opTime = { ts: opTime, t: bson_1.Long.ZERO }; + } + // If there's no lastOp, just set it. + if (!bulkResult.opTime) { + bulkResult.opTime = opTime; + } + else { + // First compare the ts values and set if the opTimeTS value is greater. + const lastOpTS = longOrConvert(bulkResult.opTime.ts); + const opTimeTS = longOrConvert(opTime.ts); + if (opTimeTS.greaterThan(lastOpTS)) { + bulkResult.opTime = opTime; + } + else if (opTimeTS.equals(lastOpTS)) { + // If the ts values are equal, then compare using the t values. + const lastOpT = longOrConvert(bulkResult.opTime.t); + const opTimeT = longOrConvert(opTime.t); + if (opTimeT.greaterThan(lastOpT)) { + bulkResult.opTime = opTime; + } + } + } + } + // If we have an insert Batch type + if (isInsertBatch(batch) && result.n) { + bulkResult.nInserted = bulkResult.nInserted + result.n; + } + // If we have an insert Batch type + if (isDeleteBatch(batch) && result.n) { + bulkResult.nRemoved = bulkResult.nRemoved + result.n; + } + let nUpserted = 0; + // We have an array of upserted values, we need to rewrite the indexes + if (Array.isArray(result.upserted)) { + nUpserted = result.upserted.length; + for (let i = 0; i < result.upserted.length; i++) { + bulkResult.upserted.push({ + index: result.upserted[i].index + batch.originalZeroIndex, + _id: result.upserted[i]._id + }); + } + } + else if (result.upserted) { + nUpserted = 1; + bulkResult.upserted.push({ + index: batch.originalZeroIndex, + _id: result.upserted + }); + } + // If we have an update Batch type + if (isUpdateBatch(batch) && result.n) { + const nModified = result.nModified; + bulkResult.nUpserted = bulkResult.nUpserted + nUpserted; + bulkResult.nMatched = bulkResult.nMatched + (result.n - nUpserted); + if (typeof nModified === 'number') { + bulkResult.nModified = bulkResult.nModified + nModified; + } + else { + bulkResult.nModified = 0; + } + } + if (Array.isArray(result.writeErrors)) { + for (let i = 0; i < result.writeErrors.length; i++) { + const writeError = { + index: batch.originalIndexes[result.writeErrors[i].index], + code: result.writeErrors[i].code, + errmsg: result.writeErrors[i].errmsg, + errInfo: result.writeErrors[i].errInfo, + op: batch.operations[result.writeErrors[i].index] + }; + bulkResult.writeErrors.push(new WriteError(writeError)); + } + } + if (result.writeConcernError) { + bulkResult.writeConcernErrors.push(new WriteConcernError(result.writeConcernError)); + } +} +exports.mergeBatchResults = mergeBatchResults; +function executeCommands(bulkOperation, options, callback) { + if (bulkOperation.s.batches.length === 0) { + return callback(undefined, new BulkWriteResult(bulkOperation.s.bulkResult)); + } + const batch = bulkOperation.s.batches.shift(); + function resultHandler(err, result) { + // Error is a driver related error not a bulk op error, return early + if (err && 'message' in err && !(err instanceof error_1.MongoWriteConcernError)) { + return callback(new MongoBulkWriteError(err, new BulkWriteResult(bulkOperation.s.bulkResult))); + } + if (err instanceof error_1.MongoWriteConcernError) { + return handleMongoWriteConcernError(batch, bulkOperation.s.bulkResult, err, callback); + } + // Merge the results together + const writeResult = new BulkWriteResult(bulkOperation.s.bulkResult); + const mergeResult = mergeBatchResults(batch, bulkOperation.s.bulkResult, err, result); + if (mergeResult != null) { + return callback(undefined, writeResult); + } + if (bulkOperation.handleWriteError(callback, writeResult)) + return; + // Execute the next command in line + executeCommands(bulkOperation, options, callback); + } + const finalOptions = (0, utils_1.resolveOptions)(bulkOperation, { + ...options, + ordered: bulkOperation.isOrdered + }); + if (finalOptions.bypassDocumentValidation !== true) { + delete finalOptions.bypassDocumentValidation; + } + // Set an operationIf if provided + if (bulkOperation.operationId) { + resultHandler.operationId = bulkOperation.operationId; + } + // Is the bypassDocumentValidation options specific + if (bulkOperation.s.bypassDocumentValidation === true) { + finalOptions.bypassDocumentValidation = true; + } + // Is the checkKeys option disabled + if (bulkOperation.s.checkKeys === false) { + finalOptions.checkKeys = false; + } + if (finalOptions.retryWrites) { + if (isUpdateBatch(batch)) { + finalOptions.retryWrites = finalOptions.retryWrites && !batch.operations.some(op => op.multi); + } + if (isDeleteBatch(batch)) { + finalOptions.retryWrites = + finalOptions.retryWrites && !batch.operations.some(op => op.limit === 0); + } + } + try { + if (isInsertBatch(batch)) { + (0, execute_operation_1.executeOperation)(bulkOperation.s.collection.s.db.s.client, new insert_1.InsertOperation(bulkOperation.s.namespace, batch.operations, finalOptions), resultHandler); + } + else if (isUpdateBatch(batch)) { + (0, execute_operation_1.executeOperation)(bulkOperation.s.collection.s.db.s.client, new update_1.UpdateOperation(bulkOperation.s.namespace, batch.operations, finalOptions), resultHandler); + } + else if (isDeleteBatch(batch)) { + (0, execute_operation_1.executeOperation)(bulkOperation.s.collection.s.db.s.client, new delete_1.DeleteOperation(bulkOperation.s.namespace, batch.operations, finalOptions), resultHandler); + } + } + catch (err) { + // Force top level error + err.ok = 0; + // Merge top level error and return + mergeBatchResults(batch, bulkOperation.s.bulkResult, err, undefined); + callback(); + } +} +function handleMongoWriteConcernError(batch, bulkResult, err, callback) { + var _a, _b; + mergeBatchResults(batch, bulkResult, undefined, err.result); + callback(new MongoBulkWriteError({ + message: (_a = err.result) === null || _a === void 0 ? void 0 : _a.writeConcernError.errmsg, + code: (_b = err.result) === null || _b === void 0 ? void 0 : _b.writeConcernError.result + }, new BulkWriteResult(bulkResult))); } - /** - * Create a new WriteConcernError instance (INTERNAL TYPE, do not instantiate directly) - * - * @class - * @property {number} code Write concern error code. - * @property {string} errmsg Write concern error message. - * @return {WriteConcernError} a WriteConcernError instance + * An error indicating an unsuccessful Bulk Write + * @public + * @category Error */ -var WriteConcernError = function(err) { - if(!(this instanceof WriteConcernError)) return new WriteConcernError(err); - - // Define properties - defineReadOnlyProperty(this, "code", err.code); - defineReadOnlyProperty(this, "errmsg", err.errmsg); - - this.toJSON = function() { - return {code: err.code, errmsg: err.errmsg}; - } - - this.toString = function() { - return "WriteConcernError(" + err.errmsg + ")"; - } +class MongoBulkWriteError extends error_1.MongoServerError { + /** Creates a new MongoBulkWriteError */ + constructor(error, result) { + var _a; + super(error); + this.writeErrors = []; + if (error instanceof WriteConcernError) + this.err = error; + else if (!(error instanceof Error)) { + this.message = error.message; + this.code = error.code; + this.writeErrors = (_a = error.writeErrors) !== null && _a !== void 0 ? _a : []; + } + this.result = result; + Object.assign(this, error); + } + get name() { + return 'MongoBulkWriteError'; + } + /** Number of documents inserted. */ + get insertedCount() { + return this.result.insertedCount; + } + /** Number of documents matched for update. */ + get matchedCount() { + return this.result.matchedCount; + } + /** Number of documents modified. */ + get modifiedCount() { + return this.result.modifiedCount; + } + /** Number of documents deleted. */ + get deletedCount() { + return this.result.deletedCount; + } + /** Number of documents upserted. */ + get upsertedCount() { + return this.result.upsertedCount; + } + /** Inserted document generated Id's, hash key is the index of the originating operation */ + get insertedIds() { + return this.result.insertedIds; + } + /** Upserted document generated Id's, hash key is the index of the originating operation */ + get upsertedIds() { + return this.result.upsertedIds; + } } - +exports.MongoBulkWriteError = MongoBulkWriteError; /** - * Create a new WriteError instance (INTERNAL TYPE, do not instantiate directly) + * A builder object that is returned from {@link BulkOperationBase#find}. + * Is used to build a write operation that involves a query filter. * - * @class - * @property {number} code Write concern error code. - * @property {number} index Write concern error original bulk operation index. - * @property {string} errmsg Write concern error message. - * @return {WriteConcernError} a WriteConcernError instance + * @public */ -var WriteError = function(err) { - if(!(this instanceof WriteError)) return new WriteError(err); - - // Define properties - defineReadOnlyProperty(this, "code", err.code); - defineReadOnlyProperty(this, "index", err.index); - defineReadOnlyProperty(this, "errmsg", err.errmsg); - - // - // Define access methods - this.getOperation = function() { - return err.op; - } - - this.toJSON = function() { - return {code: err.code, index: err.index, errmsg: err.errmsg, op: err.op}; - } - - this.toString = function() { - return "WriteError(" + JSON.stringify(this.toJSON()) + ")"; - } +class FindOperators { + /** + * Creates a new FindOperators object. + * @internal + */ + constructor(bulkOperation) { + this.bulkOperation = bulkOperation; + } + /** Add a multiple update operation to the bulk operation */ + update(updateDocument) { + const currentOp = buildCurrentOp(this.bulkOperation); + return this.bulkOperation.addToOperationsList(exports.BatchType.UPDATE, (0, update_1.makeUpdateStatement)(currentOp.selector, updateDocument, { + ...currentOp, + multi: true + })); + } + /** Add a single update operation to the bulk operation */ + updateOne(updateDocument) { + if (!(0, utils_1.hasAtomicOperators)(updateDocument)) { + throw new error_1.MongoInvalidArgumentError('Update document requires atomic operators'); + } + const currentOp = buildCurrentOp(this.bulkOperation); + return this.bulkOperation.addToOperationsList(exports.BatchType.UPDATE, (0, update_1.makeUpdateStatement)(currentOp.selector, updateDocument, { ...currentOp, multi: false })); + } + /** Add a replace one operation to the bulk operation */ + replaceOne(replacement) { + if ((0, utils_1.hasAtomicOperators)(replacement)) { + throw new error_1.MongoInvalidArgumentError('Replacement document must not use atomic operators'); + } + const currentOp = buildCurrentOp(this.bulkOperation); + return this.bulkOperation.addToOperationsList(exports.BatchType.UPDATE, (0, update_1.makeUpdateStatement)(currentOp.selector, replacement, { ...currentOp, multi: false })); + } + /** Add a delete one operation to the bulk operation */ + deleteOne() { + const currentOp = buildCurrentOp(this.bulkOperation); + return this.bulkOperation.addToOperationsList(exports.BatchType.DELETE, (0, delete_1.makeDeleteStatement)(currentOp.selector, { ...currentOp, limit: 1 })); + } + /** Add a delete many operation to the bulk operation */ + delete() { + const currentOp = buildCurrentOp(this.bulkOperation); + return this.bulkOperation.addToOperationsList(exports.BatchType.DELETE, (0, delete_1.makeDeleteStatement)(currentOp.selector, { ...currentOp, limit: 0 })); + } + /** Upsert modifier for update bulk operation, noting that this operation is an upsert. */ + upsert() { + if (!this.bulkOperation.s.currentOp) { + this.bulkOperation.s.currentOp = {}; + } + this.bulkOperation.s.currentOp.upsert = true; + return this; + } + /** Specifies the collation for the query condition. */ + collation(collation) { + if (!this.bulkOperation.s.currentOp) { + this.bulkOperation.s.currentOp = {}; + } + this.bulkOperation.s.currentOp.collation = collation; + return this; + } + /** Specifies arrayFilters for UpdateOne or UpdateMany bulk operations. */ + arrayFilters(arrayFilters) { + if (!this.bulkOperation.s.currentOp) { + this.bulkOperation.s.currentOp = {}; + } + this.bulkOperation.s.currentOp.arrayFilters = arrayFilters; + return this; + } } - +exports.FindOperators = FindOperators; /** - * Merges results into shared data structure - * @ignore + * TODO(NODE-4063) + * BulkWrites merge complexity is implemented in executeCommands + * This provides a vehicle to treat bulkOperations like any other operation (hence "shim") + * We would like this logic to simply live inside the BulkWriteOperation class + * @internal */ -var mergeBatchResults = function(ordered, batch, bulkResult, err, result) { - // If we have an error set the result to be the err object - if(err) { - result = err; - } else if(result && result.result) { - result = result.result; - } else if(result == null) { - return; - } - - // Do we have a top level error stop processing and return - if(result.ok == 0 && bulkResult.ok == 1) { - bulkResult.ok = 0; - - var writeError = { - index: 0 - , code: result.code || 0 - , errmsg: result.message - , op: batch.operations[0] - }; - - bulkResult.writeErrors.push(new WriteError(writeError)); - return; - } else if(result.ok == 0 && bulkResult.ok == 0) { - return; - } - - // Deal with opTime if available - if(result.opTime || result.lastOp) { - var opTime = result.lastOp || result.opTime; - var lastOpTS = null; - var lastOpT = null; - - // We have a time stamp - if(opTime && opTime._bsontype == 'Timestamp') { - if(bulkResult.lastOp == null) { - bulkResult.lastOp = opTime; - } else if(opTime.greaterThan(bulkResult.lastOp)) { - bulkResult.lastOp = opTime; - } - } else { - // Existing TS - if(bulkResult.lastOp) { - lastOpTS = typeof bulkResult.lastOp.ts == 'number' - ? Long.fromNumber(bulkResult.lastOp.ts) : bulkResult.lastOp.ts; - lastOpT = typeof bulkResult.lastOp.t == 'number' - ? Long.fromNumber(bulkResult.lastOp.t) : bulkResult.lastOp.t; - } - - // Current OpTime TS - var opTimeTS = typeof opTime.ts == 'number' - ? Long.fromNumber(opTime.ts) : opTime.ts; - var opTimeT = typeof opTime.t == 'number' - ? Long.fromNumber(opTime.t) : opTime.t; - - // Compare the opTime's - if(bulkResult.lastOp == null) { - bulkResult.lastOp = opTime; - } else if(opTimeTS.greaterThan(lastOpTS)) { - bulkResult.lastOp = opTime; - } else if(opTimeTS.equals(lastOpTS)) { - if(opTimeT.greaterThan(lastOpT)) { - bulkResult.lastOp = opTime; - } - } - } - } - - // If we have an insert Batch type - if(batch.batchType == INSERT && result.n) { - bulkResult.nInserted = bulkResult.nInserted + result.n; - } - - // If we have an insert Batch type - if(batch.batchType == REMOVE && result.n) { - bulkResult.nRemoved = bulkResult.nRemoved + result.n; - } - - var nUpserted = 0; - - // We have an array of upserted values, we need to rewrite the indexes - if(Array.isArray(result.upserted)) { - nUpserted = result.upserted.length; - - for(var i = 0; i < result.upserted.length; i++) { - bulkResult.upserted.push({ - index: result.upserted[i].index + batch.originalZeroIndex - , _id: result.upserted[i]._id - }); - } - } else if(result.upserted) { - - nUpserted = 1; - - bulkResult.upserted.push({ - index: batch.originalZeroIndex - , _id: result.upserted - }); - } - - // If we have an update Batch type - if(batch.batchType == UPDATE && result.n) { - var nModified = result.nModified; - bulkResult.nUpserted = bulkResult.nUpserted + nUpserted; - bulkResult.nMatched = bulkResult.nMatched + (result.n - nUpserted); - - if(typeof nModified == 'number') { - bulkResult.nModified = bulkResult.nModified + nModified; - } else { - bulkResult.nModified = null; - } - } - - if(Array.isArray(result.writeErrors)) { - for(i = 0; i < result.writeErrors.length; i++) { - - writeError = { - index: batch.originalZeroIndex + result.writeErrors[i].index - , code: result.writeErrors[i].code - , errmsg: result.writeErrors[i].errmsg - , op: batch.operations[result.writeErrors[i].index] - }; - - bulkResult.writeErrors.push(new WriteError(writeError)); - } - } - - if(result.writeConcernError) { - bulkResult.writeConcernErrors.push(new WriteConcernError(result.writeConcernError)); - } +class BulkWriteShimOperation extends operation_1.AbstractOperation { + constructor(bulkOperation, options) { + super(options); + this.bulkOperation = bulkOperation; + } + execute(server, session, callback) { + if (this.options.session == null) { + // An implicit session could have been created by 'executeOperation' + // So if we stick it on finalOptions here, each bulk operation + // will use this same session, it'll be passed in the same way + // an explicit session would be + this.options.session = session; + } + return executeCommands(this.bulkOperation, this.options, callback); + } +} +/** @public */ +class BulkOperationBase { + /** + * Create a new OrderedBulkOperation or UnorderedBulkOperation instance + * @internal + */ + constructor(collection, options, isOrdered) { + // determine whether bulkOperation is ordered or unordered + this.isOrdered = isOrdered; + const topology = (0, utils_1.getTopology)(collection); + options = options == null ? {} : options; + // TODO Bring from driver information in hello + // Get the namespace for the write operations + const namespace = collection.s.namespace; + // Used to mark operation as executed + const executed = false; + // Current item + const currentOp = undefined; + // Set max byte size + const hello = topology.lastHello(); + // If we have autoEncryption on, batch-splitting must be done on 2mb chunks, but single documents + // over 2mb are still allowed + const usingAutoEncryption = !!(topology.s.options && topology.s.options.autoEncrypter); + const maxBsonObjectSize = hello && hello.maxBsonObjectSize ? hello.maxBsonObjectSize : 1024 * 1024 * 16; + const maxBatchSizeBytes = usingAutoEncryption ? 1024 * 1024 * 2 : maxBsonObjectSize; + const maxWriteBatchSize = hello && hello.maxWriteBatchSize ? hello.maxWriteBatchSize : 1000; + // Calculates the largest possible size of an Array key, represented as a BSON string + // element. This calculation: + // 1 byte for BSON type + // # of bytes = length of (string representation of (maxWriteBatchSize - 1)) + // + 1 bytes for null terminator + const maxKeySize = (maxWriteBatchSize - 1).toString(10).length + 2; + // Final options for retryable writes + let finalOptions = Object.assign({}, options); + finalOptions = (0, utils_1.applyRetryableWrites)(finalOptions, collection.s.db); + // Final results + const bulkResult = { + ok: 1, + writeErrors: [], + writeConcernErrors: [], + insertedIds: [], + nInserted: 0, + nUpserted: 0, + nMatched: 0, + nModified: 0, + nRemoved: 0, + upserted: [] + }; + // Internal state + this.s = { + // Final result + bulkResult, + // Current batch state + currentBatch: undefined, + currentIndex: 0, + // ordered specific + currentBatchSize: 0, + currentBatchSizeBytes: 0, + // unordered specific + currentInsertBatch: undefined, + currentUpdateBatch: undefined, + currentRemoveBatch: undefined, + batches: [], + // Write concern + writeConcern: write_concern_1.WriteConcern.fromOptions(options), + // Max batch size options + maxBsonObjectSize, + maxBatchSizeBytes, + maxWriteBatchSize, + maxKeySize, + // Namespace + namespace, + // Topology + topology, + // Options + options: finalOptions, + // BSON options + bsonOptions: (0, bson_1.resolveBSONOptions)(options), + // Current operation + currentOp, + // Executed + executed, + // Collection + collection, + // Fundamental error + err: undefined, + // check keys + checkKeys: typeof options.checkKeys === 'boolean' ? options.checkKeys : false + }; + // bypass Validation + if (options.bypassDocumentValidation === true) { + this.s.bypassDocumentValidation = true; + } + } + /** + * Add a single insert document to the bulk operation + * + * @example + * ```js + * const bulkOp = collection.initializeOrderedBulkOp(); + * + * // Adds three inserts to the bulkOp. + * bulkOp + * .insert({ a: 1 }) + * .insert({ b: 2 }) + * .insert({ c: 3 }); + * await bulkOp.execute(); + * ``` + */ + insert(document) { + if (document._id == null && !shouldForceServerObjectId(this)) { + document._id = new bson_1.ObjectId(); + } + return this.addToOperationsList(exports.BatchType.INSERT, document); + } + /** + * Builds a find operation for an update/updateOne/delete/deleteOne/replaceOne. + * Returns a builder object used to complete the definition of the operation. + * + * @example + * ```js + * const bulkOp = collection.initializeOrderedBulkOp(); + * + * // Add an updateOne to the bulkOp + * bulkOp.find({ a: 1 }).updateOne({ $set: { b: 2 } }); + * + * // Add an updateMany to the bulkOp + * bulkOp.find({ c: 3 }).update({ $set: { d: 4 } }); + * + * // Add an upsert + * bulkOp.find({ e: 5 }).upsert().updateOne({ $set: { f: 6 } }); + * + * // Add a deletion + * bulkOp.find({ g: 7 }).deleteOne(); + * + * // Add a multi deletion + * bulkOp.find({ h: 8 }).delete(); + * + * // Add a replaceOne + * bulkOp.find({ i: 9 }).replaceOne({writeConcern: { j: 10 }}); + * + * // Update using a pipeline (requires Mongodb 4.2 or higher) + * bulk.find({ k: 11, y: { $exists: true }, z: { $exists: true } }).updateOne([ + * { $set: { total: { $sum: [ '$y', '$z' ] } } } + * ]); + * + * // All of the ops will now be executed + * await bulkOp.execute(); + * ``` + */ + find(selector) { + if (!selector) { + throw new error_1.MongoInvalidArgumentError('Bulk find operation must specify a selector'); + } + // Save a current selector + this.s.currentOp = { + selector: selector + }; + return new FindOperators(this); + } + /** Specifies a raw operation to perform in the bulk write. */ + raw(op) { + if (op == null || typeof op !== 'object') { + throw new error_1.MongoInvalidArgumentError('Operation must be an object with an operation key'); + } + if ('insertOne' in op) { + const forceServerObjectId = shouldForceServerObjectId(this); + if (op.insertOne && op.insertOne.document == null) { + // NOTE: provided for legacy support, but this is a malformed operation + if (forceServerObjectId !== true && op.insertOne._id == null) { + op.insertOne._id = new bson_1.ObjectId(); + } + return this.addToOperationsList(exports.BatchType.INSERT, op.insertOne); + } + if (forceServerObjectId !== true && op.insertOne.document._id == null) { + op.insertOne.document._id = new bson_1.ObjectId(); + } + return this.addToOperationsList(exports.BatchType.INSERT, op.insertOne.document); + } + if ('replaceOne' in op || 'updateOne' in op || 'updateMany' in op) { + if ('replaceOne' in op) { + if ('q' in op.replaceOne) { + throw new error_1.MongoInvalidArgumentError('Raw operations are not allowed'); + } + const updateStatement = (0, update_1.makeUpdateStatement)(op.replaceOne.filter, op.replaceOne.replacement, { ...op.replaceOne, multi: false }); + if ((0, utils_1.hasAtomicOperators)(updateStatement.u)) { + throw new error_1.MongoInvalidArgumentError('Replacement document must not use atomic operators'); + } + return this.addToOperationsList(exports.BatchType.UPDATE, updateStatement); + } + if ('updateOne' in op) { + if ('q' in op.updateOne) { + throw new error_1.MongoInvalidArgumentError('Raw operations are not allowed'); + } + const updateStatement = (0, update_1.makeUpdateStatement)(op.updateOne.filter, op.updateOne.update, { + ...op.updateOne, + multi: false + }); + if (!(0, utils_1.hasAtomicOperators)(updateStatement.u)) { + throw new error_1.MongoInvalidArgumentError('Update document requires atomic operators'); + } + return this.addToOperationsList(exports.BatchType.UPDATE, updateStatement); + } + if ('updateMany' in op) { + if ('q' in op.updateMany) { + throw new error_1.MongoInvalidArgumentError('Raw operations are not allowed'); + } + const updateStatement = (0, update_1.makeUpdateStatement)(op.updateMany.filter, op.updateMany.update, { + ...op.updateMany, + multi: true + }); + if (!(0, utils_1.hasAtomicOperators)(updateStatement.u)) { + throw new error_1.MongoInvalidArgumentError('Update document requires atomic operators'); + } + return this.addToOperationsList(exports.BatchType.UPDATE, updateStatement); + } + } + if ('deleteOne' in op) { + if ('q' in op.deleteOne) { + throw new error_1.MongoInvalidArgumentError('Raw operations are not allowed'); + } + return this.addToOperationsList(exports.BatchType.DELETE, (0, delete_1.makeDeleteStatement)(op.deleteOne.filter, { ...op.deleteOne, limit: 1 })); + } + if ('deleteMany' in op) { + if ('q' in op.deleteMany) { + throw new error_1.MongoInvalidArgumentError('Raw operations are not allowed'); + } + return this.addToOperationsList(exports.BatchType.DELETE, (0, delete_1.makeDeleteStatement)(op.deleteMany.filter, { ...op.deleteMany, limit: 0 })); + } + // otherwise an unknown operation was provided + throw new error_1.MongoInvalidArgumentError('bulkWrite only supports insertOne, updateOne, updateMany, deleteOne, deleteMany'); + } + get bsonOptions() { + return this.s.bsonOptions; + } + get writeConcern() { + return this.s.writeConcern; + } + get batches() { + const batches = [...this.s.batches]; + if (this.isOrdered) { + if (this.s.currentBatch) + batches.push(this.s.currentBatch); + } + else { + if (this.s.currentInsertBatch) + batches.push(this.s.currentInsertBatch); + if (this.s.currentUpdateBatch) + batches.push(this.s.currentUpdateBatch); + if (this.s.currentRemoveBatch) + batches.push(this.s.currentRemoveBatch); + } + return batches; + } + execute(options, callback) { + if (typeof options === 'function') + (callback = options), (options = {}); + options = options !== null && options !== void 0 ? options : {}; + if (this.s.executed) { + return handleEarlyError(new error_1.MongoBatchReExecutionError(), callback); + } + const writeConcern = write_concern_1.WriteConcern.fromOptions(options); + if (writeConcern) { + this.s.writeConcern = writeConcern; + } + // If we have current batch + if (this.isOrdered) { + if (this.s.currentBatch) + this.s.batches.push(this.s.currentBatch); + } + else { + if (this.s.currentInsertBatch) + this.s.batches.push(this.s.currentInsertBatch); + if (this.s.currentUpdateBatch) + this.s.batches.push(this.s.currentUpdateBatch); + if (this.s.currentRemoveBatch) + this.s.batches.push(this.s.currentRemoveBatch); + } + // If we have no operations in the bulk raise an error + if (this.s.batches.length === 0) { + const emptyBatchError = new error_1.MongoInvalidArgumentError('Invalid BulkOperation, Batch cannot be empty'); + return handleEarlyError(emptyBatchError, callback); + } + this.s.executed = true; + const finalOptions = { ...this.s.options, ...options }; + const operation = new BulkWriteShimOperation(this, finalOptions); + return (0, execute_operation_1.executeOperation)(this.s.collection.s.db.s.client, operation, callback); + } + /** + * Handles the write error before executing commands + * @internal + */ + handleWriteError(callback, writeResult) { + if (this.s.bulkResult.writeErrors.length > 0) { + const msg = this.s.bulkResult.writeErrors[0].errmsg + ? this.s.bulkResult.writeErrors[0].errmsg + : 'write operation failed'; + callback(new MongoBulkWriteError({ + message: msg, + code: this.s.bulkResult.writeErrors[0].code, + writeErrors: this.s.bulkResult.writeErrors + }, writeResult)); + return true; + } + const writeConcernError = writeResult.getWriteConcernError(); + if (writeConcernError) { + callback(new MongoBulkWriteError(writeConcernError, writeResult)); + return true; + } + return false; + } } - -// -// Clone the options -var cloneOptions = function(options) { - var clone = {}; - var keys = Object.keys(options); - for(var i = 0; i < keys.length; i++) { - clone[keys[i]] = options[keys[i]]; - } - - return clone; +exports.BulkOperationBase = BulkOperationBase; +Object.defineProperty(BulkOperationBase.prototype, 'length', { + enumerable: true, + get() { + return this.s.currentIndex; + } +}); +/** helper function to assist with promiseOrCallback behavior */ +function handleEarlyError(err, callback) { + const Promise = promise_provider_1.PromiseProvider.get(); + if (typeof callback === 'function') { + callback(err); + return; + } + return Promise.reject(err); } - -// Exports symbols -exports.BulkWriteResult = BulkWriteResult; -exports.WriteError = WriteError; -exports.Batch = Batch; -exports.LegacyOp = LegacyOp; -exports.mergeBatchResults = mergeBatchResults; -exports.cloneOptions = cloneOptions; -exports.writeConcern = writeConcern; -exports.INVALID_BSON_ERROR = INVALID_BSON_ERROR; -exports.WRITE_CONCERN_ERROR = WRITE_CONCERN_ERROR; -exports.MULTIPLE_ERROR = MULTIPLE_ERROR; -exports.UNKNOWN_ERROR = UNKNOWN_ERROR; -exports.INSERT = INSERT; -exports.UPDATE = UPDATE; -exports.REMOVE = REMOVE; +function shouldForceServerObjectId(bulkOperation) { + var _a, _b; + if (typeof bulkOperation.s.options.forceServerObjectId === 'boolean') { + return bulkOperation.s.options.forceServerObjectId; + } + if (typeof ((_a = bulkOperation.s.collection.s.db.options) === null || _a === void 0 ? void 0 : _a.forceServerObjectId) === 'boolean') { + return (_b = bulkOperation.s.collection.s.db.options) === null || _b === void 0 ? void 0 : _b.forceServerObjectId; + } + return false; +} +function isInsertBatch(batch) { + return batch.batchType === exports.BatchType.INSERT; +} +function isUpdateBatch(batch) { + return batch.batchType === exports.BatchType.UPDATE; +} +function isDeleteBatch(batch) { + return batch.batchType === exports.BatchType.DELETE; +} +function buildCurrentOp(bulkOp) { + let { currentOp } = bulkOp.s; + bulkOp.s.currentOp = undefined; + if (!currentOp) + currentOp = {}; + return currentOp; +} +//# sourceMappingURL=common.js.map \ No newline at end of file diff --git a/ts-ticket-office-service/node_modules/mongodb/lib/bulk/common.js.map b/ts-ticket-office-service/node_modules/mongodb/lib/bulk/common.js.map new file mode 100644 index 000000000..c512e0af3 --- /dev/null +++ b/ts-ticket-office-service/node_modules/mongodb/lib/bulk/common.js.map @@ -0,0 +1 @@ +{"version":3,"file":"common.js","sourceRoot":"","sources":["../../src/bulk/common.ts"],"names":[],"mappings":";;;AAAA,kCAOiB;AAEjB,oCAOkB;AAGlB,iDAA6F;AAC7F,uEAAmE;AACnE,iDAAuD;AACvD,uDAAkE;AAClE,iDAA6F;AAC7F,0DAAsD;AAItD,oCAOkB;AAClB,oDAAgD;AAEhD,gBAAgB;AAChB,MAAM,YAAY,GAAG,MAAM,CAAC,aAAa,CAAC,CAAC;AAE3C,cAAc;AACD,QAAA,SAAS,GAAG,MAAM,CAAC,MAAM,CAAC;IACrC,MAAM,EAAE,CAAC;IACT,MAAM,EAAE,CAAC;IACT,MAAM,EAAE,CAAC;CACD,CAAC,CAAC;AAqGZ;;;;;GAKG;AACH,MAAa,KAAK;IAShB,YAAY,SAAoB,EAAE,iBAAyB;QACzD,IAAI,CAAC,iBAAiB,GAA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AC,CAAC,CAAC,OAAO,CAAC,mBAAmB,CAAC;KACpD;IAED,IAAI,OAAO,CAAA,MAAA,aAAa,CAAC,CAAC,CAAC,UAAU,CAAC,CAAC,CAAC,EAAE,CAAC,OAAO,0CAAE,mBAAmB,CAAA,KAAK,SAAS,EAAE;QACrF,OAAO,MAAA,aAAa,CAAC,CAAC,CAAC,UAAU,CAAC,CAAC,CAAC,EAAE,CAAC,OAAO,0CAAE,mBAAmB,CAAC;KACrE;IAED,OAAO,KAAK,CAAC;AACf,CAAC;AAED,SAAS,aAAa,CAAC,KAAY;IACjC,OAAO,KAAK,CAAC,SAAS,KAAK,iBAAS,CAAC,MAAM,CAAC;AAC9C,CAAC;AAED,SAAS,aAAa,CAAC,KAAY;IACjC,OAAO,KAAK,CAAC,SAAS,KAAK,iBAAS,CAAC,MAAM,CAAC;AAC9C,CAAC;AAED,SAAS,aAAa,CAAC,KAAY;IACjC,OAAO,KAAK,CAAC,SAAS,KAAK,iBAAS,CAAC,MAAM,CAAC;AAC9C,CAAC;AAED,SAAS,cAAc,CAAC,MAAyB;IAC/C,IAAI,EAAE,SAAS,EAAE,GAAG,MAAM,CAAC,CAAC,CAAC;IAC7B,MAAM,CAAC,CAAC,CAAC,SAAS,GAAG,SAAS,CAAC;IAC/B,IAAI,CAAC,SAAS;QAAE,SAAS,GAAG,EAAE,CAAC;IAC/B,OAAO,SAAS,CAAC;AACnB,CAAC"} \ No newline at end of file diff --git a/ts-ticket-office-service/node_modules/mongodb/lib/bulk/ordered.js b/ts-ticket-office-service/node_modules/mongodb/lib/bulk/ordered.js index e1ae3d7cd..f7e5418d7 100644 --- a/ts-ticket-office-service/node_modules/mongodb/lib/bulk/ordered.js +++ b/ts-ticket-office-service/node_modules/mongodb/lib/bulk/ordered.js @@ -1,539 +1,66 @@ "use strict"; - -var common = require('./common') - , utils = require('../utils') - , toError = require('../utils').toError - , handleCallback = require('../utils').handleCallback - , shallowClone = utils.shallowClone - , BulkWriteResult = common.BulkWriteResult - , ObjectID = require('mongodb-core').BSON.ObjectID - , Define = require('../metadata') - , BSON = require('mongodb-core').BSON - , Batch = common.Batch - , mergeBatchResults = common.mergeBatchResults; - -var bson = new BSON([BSON.Binary, BSON.Code, BSON.DBRef, BSON.Decimal128, - BSON.Double, BSON.Int32, BSON.Long, BSON.Map, BSON.MaxKey, BSON.MinKey, - BSON.ObjectId, BSON.BSONRegExp, BSON.Symbol, BSON.Timestamp]); - -/** - * Create a FindOperatorsOrdered instance (INTERNAL TYPE, do not instantiate directly) - * @class - * @return {FindOperatorsOrdered} a FindOperatorsOrdered instance. - */ -var FindOperatorsOrdered = function(self) { - this.s = self.s; -} - -/** - * Add a single update document to the bulk operation - * - * @method - * @param {object} doc update operations - * @throws {MongoError} - * @return {OrderedBulkOperation} - */ -FindOperatorsOrdered.prototype.update = function(updateDocument) { - // Perform upsert - var upsert = typeof this.s.currentOp.upsert == 'boolean' ? this.s.currentOp.upsert : false; - - // Establish the update command - var document = { - q: this.s.currentOp.selector - , u: updateDocument - , multi: true - , upsert: upsert - } - - // Clear out current Op - this.s.currentOp = null; - // Add the update document to the list - return addToOperationsList(this, common.UPDATE, document); -} - -/** - * Add a single update one document to the bulk operation - * - * @method - * @param {object} doc update operations - * @throws {MongoError} - * @return {OrderedBulkOperation} - */ -FindOperatorsOrdered.prototype.updateOne = function(updateDocument) { - // Perform upsert - var upsert = typeof this.s.currentOp.upsert == 'boolean' ? this.s.currentOp.upsert : false; - - // Establish the update command - var document = { - q: this.s.currentOp.selector - , u: updateDocument - , multi: false - , upsert: upsert - } - - // Clear out current Op - this.s.currentOp = null; - // Add the update document to the list - return addToOperationsList(this, common.UPDATE, document); -} - -/** - * Add a replace one operation to the bulk operation - * - * @method - * @param {object} doc the new document to replace the existing one with - * @throws {MongoError} - * @return {OrderedBulkOperation} - */ -FindOperatorsOrdered.prototype.replaceOne = function(updateDocument) { - this.updateOne(updateDocument); -} - -/** - * Upsert modifier for update bulk operation - * - * @method - * @throws {MongoError} - * @return {FindOperatorsOrdered} - */ -FindOperatorsOrdered.prototype.upsert = function() { - this.s.currentOp.upsert = true; - return this; -} - -/** - * Add a remove one operation to the bulk operation - * - * @method - * @throws {MongoError} - * @return {OrderedBulkOperation} - */ -FindOperatorsOrdered.prototype.deleteOne = function() { - // Establish the update command - var document = { - q: this.s.currentOp.selector - , limit: 1 - } - - // Clear out current Op - this.s.currentOp = null; - // Add the remove document to the list - return addToOperationsList(this, common.REMOVE, document); -} - -// Backward compatibility -FindOperatorsOrdered.prototype.removeOne = FindOperatorsOrdered.prototype.deleteOne; - -/** - * Add a remove operation to the bulk operation - * - * @method - * @throws {MongoError} - * @return {OrderedBulkOperation} - */ -FindOperatorsOrdered.prototype.delete = function() { - // Establish the update command - var document = { - q: this.s.currentOp.selector - , limit: 0 - } - - // Clear out current Op - this.s.currentOp = null; - // Add the remove document to the list - return addToOperationsList(this, common.REMOVE, document); -} - -// Backward compatibility -FindOperatorsOrdered.prototype.remove = FindOperatorsOrdered.prototype.delete; - -// Add to internal list of documents -var addToOperationsList = function(_self, docType, document) { - // Get the bsonSize - var bsonSize = bson.calculateObjectSize(document, { - checkKeys: false, - }); - - // Throw error if the doc is bigger than the max BSON size - if(bsonSize >= _self.s.maxBatchSizeBytes) { - throw toError("document is larger than the maximum size " + _self.s.maxBatchSizeBytes); - } - - // Create a new batch object if we don't have a current one - if(_self.s.currentBatch == null) _self.s.currentBatch = new Batch(docType, _self.s.currentIndex); - - // Check if we need to create a new batch - if(((_self.s.currentBatchSize + 1) >= _self.s.maxWriteBatchSize) - || ((_self.s.currentBatchSizeBytes + _self.s.currentBatchSizeBytes) >= _self.s.maxBatchSizeBytes) - || (_self.s.currentBatch.batchType != docType)) { - // Save the batch to the execution stack - _self.s.batches.push(_self.s.currentBatch); - - // Create a new batch - _self.s.currentBatch = new Batch(docType, _self.s.currentIndex); - - // Reset the current size trackers - _self.s.currentBatchSize = 0; - _self.s.currentBatchSizeBytes = 0; - } else { - // Update current batch size - _self.s.currentBatchSize = _self.s.currentBatchSize + 1; - _self.s.currentBatchSizeBytes = _self.s.currentBatchSizeBytes + bsonSize; - } - - if(docType == common.INSERT) { - _self.s.bulkResult.insertedIds.push({index: _self.s.currentIndex, _id: document._id}); - } - - // We have an array of documents - if(Array.isArray(document)) { - throw toError("operation passed in cannot be an Array"); - } else { - _self.s.currentBatch.originalIndexes.push(_self.s.currentIndex); - _self.s.currentBatch.operations.push(document) - _self.s.currentBatchSizeBytes = _self.s.currentBatchSizeBytes + bsonSize; - _self.s.currentIndex = _self.s.currentIndex + 1; - } - - // Return self - return _self; -} - -/** - * Create a new OrderedBulkOperation instance (INTERNAL TYPE, do not instantiate directly) - * @class - * @property {number} length Get the number of operations in the bulk. - * @return {OrderedBulkOperation} a OrderedBulkOperation instance. - */ -function OrderedBulkOperation(topology, collection, options) { - options = options == null ? {} : options; - // TODO Bring from driver information in isMaster - var executed = false; - - // Current item - var currentOp = null; - - // Handle to the bson serializer, used to calculate running sizes - var bson = topology.bson; - - // Namespace for the operation - var namespace = collection.collectionName; - - // Set max byte size - var maxBatchSizeBytes = topology.isMasterDoc && topology.isMasterDoc.maxBsonObjectSize - ? topology.isMasterDoc.maxBsonObjectSize : (1024*1025*16); - var maxWriteBatchSize = topology.isMasterDoc && topology.isMasterDoc.maxWriteBatchSize - ? topology.isMasterDoc.maxWriteBatchSize : 1000; - - // Get the write concern - var writeConcern = common.writeConcern(shallowClone(options), collection, options); - - // Get the promiseLibrary - var promiseLibrary = options.promiseLibrary; - - // No promise library selected fall back - if(!promiseLibrary) { - promiseLibrary = typeof global.Promise == 'function' ? - global.Promise : require('es6-promise').Promise; - } - - // Final results - var bulkResult = { - ok: 1 - , writeErrors: [] - , writeConcernErrors: [] - , insertedIds: [] - , nInserted: 0 - , nUpserted: 0 - , nMatched: 0 - , nModified: 0 - , nRemoved: 0 - , upserted: [] - }; - - // Internal state - this.s = { - // Final result - bulkResult: bulkResult - // Current batch state - , currentBatch: null - , currentIndex: 0 - , currentBatchSize: 0 - , currentBatchSizeBytes: 0 - , batches: [] - // Write concern - , writeConcern: writeConcern - // Max batch size options - , maxBatchSizeBytes: maxBatchSizeBytes - , maxWriteBatchSize: maxWriteBatchSize - // Namespace - , namespace: namespace - // BSON - , bson: bson - // Topology - , topology: topology - // Options - , options: options - // Current operation - , currentOp: currentOp - // Executed - , executed: executed - // Collection - , collection: collection - // Promise Library - , promiseLibrary: promiseLibrary - // Fundamental error - , err: null - // Bypass validation - , bypassDocumentValidation: typeof options.bypassDocumentValidation == 'boolean' ? options.bypassDocumentValidation : false - } -} - -var define = OrderedBulkOperation.define = new Define('OrderedBulkOperation', OrderedBulkOperation, false); - -OrderedBulkOperation.prototype.raw = function(op) { - var key = Object.keys(op)[0]; - - // Set up the force server object id - var forceServerObjectId = typeof this.s.options.forceServerObjectId == 'boolean' - ? this.s.options.forceServerObjectId : this.s.collection.s.db.options.forceServerObjectId; - - // Update operations - if((op.updateOne && op.updateOne.q) - || (op.updateMany && op.updateMany.q) - || (op.replaceOne && op.replaceOne.q)) { - op[key].multi = op.updateOne || op.replaceOne ? false : true; - return addToOperationsList(this, common.UPDATE, op[key]); - } - - // Crud spec update format - if(op.updateOne || op.updateMany || op.replaceOne) { - var multi = op.updateOne || op.replaceOne ? false : true; - var operation = {q: op[key].filter, u: op[key].update || op[key].replacement, multi: multi} - operation.upsert = op[key].upsert ? true: false; - if(op.collation) operation.collation = op.collation; - return addToOperationsList(this, common.UPDATE, operation); - } - - // Remove operations - if(op.removeOne || op.removeMany || (op.deleteOne && op.deleteOne.q) || op.deleteMany && op.deleteMany.q) { - op[key].limit = op.removeOne ? 1 : 0; - return addToOperationsList(this, common.REMOVE, op[key]); - } - - // Crud spec delete operations, less efficient - if(op.deleteOne || op.deleteMany) { - var limit = op.deleteOne ? 1 : 0; - operation = {q: op[key].filter, limit: limit} - if(op.collation) operation.collation = op.collation; - return addToOperationsList(this, common.REMOVE, operation); - } - - // Insert operations - if(op.insertOne && op.insertOne.document == null) { - if(forceServerObjectId !== true && op.insertOne._id == null) op.insertOne._id = new ObjectID(); - return addToOperationsList(this, common.INSERT, op.insertOne); - } else if(op.insertOne && op.insertOne.document) { - if(forceServerObjectId !== true && op.insertOne.document._id == null) op.insertOne.document._id = new ObjectID(); - return addToOperationsList(this, common.INSERT, op.insertOne.document); - } - - if(op.insertMany) { - for(var i = 0; i < op.insertMany.length; i++) { - if(forceServerObjectId !== true && op.insertMany[i]._id == null) op.insertMany[i]._id = new ObjectID(); - addToOperationsList(this, common.INSERT, op.insertMany[i]); - } - - return; - } - - // No valid type of operation - throw toError("bulkWrite only supports insertOne, insertMany, updateOne, updateMany, removeOne, removeMany, deleteOne, deleteMany"); -} - -/** - * Add a single insert document to the bulk operation - * - * @param {object} doc the document to insert - * @throws {MongoError} - * @return {OrderedBulkOperation} - */ -OrderedBulkOperation.prototype.insert = function(document) { - if(this.s.collection.s.db.options.forceServerObjectId !== true && document._id == null) document._id = new ObjectID(); - return addToOperationsList(this, common.INSERT, document); -} - -/** - * Initiate a find operation for an update/updateOne/remove/removeOne/replaceOne - * - * @method - * @param {object} selector The selector for the bulk operation. - * @throws {MongoError} - * @return {FindOperatorsOrdered} - */ -OrderedBulkOperation.prototype.find = function(selector) { - if (!selector) { - throw toError("Bulk find operation must specify a selector"); - } - - // Save a current selector - this.s.currentOp = { - selector: selector - } - - return new FindOperatorsOrdered(this); -} - -Object.defineProperty(OrderedBulkOperation.prototype, 'length', { - enumerable: true, - get: function() { - return this.s.currentIndex; - } -}); - -// -// Execute next write command in a chain -var executeCommands = function(self, callback) { - if(self.s.batches.length == 0) { - return handleCallback(callback, null, new BulkWriteResult(self.s.bulkResult)); - } - - // Ordered execution of the command - var batch = self.s.batches.shift(); - - var resultHandler = function(err, result) { - // Error is a driver related error not a bulk op error, terminate - if(err && err.driver || err && err.message) { - return handleCallback(callback, err); - } - - // If we have and error - if(err) err.ok = 0; - // Merge the results together - var mergeResult = mergeBatchResults(true, batch, self.s.bulkResult, err, result); - if(mergeResult != null) { - return handleCallback(callback, null, new BulkWriteResult(self.s.bulkResult)); - } - - // If we are ordered and have errors and they are - // not all replication errors terminate the operation - if(self.s.bulkResult.writeErrors.length > 0) { - return handleCallback(callback, toError(self.s.bulkResult.writeErrors[0]), new BulkWriteResult(self.s.bulkResult)); +Object.defineProperty(exports, "__esModule", { value: true }); +exports.OrderedBulkOperation = void 0; +const BSON = require("../bson"); +const error_1 = require("../error"); +const common_1 = require("./common"); +/** @public */ +class OrderedBulkOperation extends common_1.BulkOperationBase { + constructor(collection, options) { + super(collection, options, true); } - - // Execute the next command in line - executeCommands(self, callback); - } - - var finalOptions = {ordered: true} - if(self.s.writeConcern != null) { - finalOptions.writeConcern = self.s.writeConcern; - } - - // Set an operationIf if provided - if(self.operationId) { - resultHandler.operationId = self.operationId; - } - - // Serialize functions - if(self.s.options.serializeFunctions) { - finalOptions.serializeFunctions = true - } - - // Serialize functions - if(self.s.options.ignoreUndefined) { - finalOptions.ignoreUndefined = true - } - - // Is the bypassDocumentValidation options specific - if(self.s.bypassDocumentValidation == true) { - finalOptions.bypassDocumentValidation = true; - } - - try { - if(batch.batchType == common.INSERT) { - self.s.topology.insert(self.s.collection.namespace, batch.operations, finalOptions, resultHandler); - } else if(batch.batchType == common.UPDATE) { - self.s.topology.update(self.s.collection.namespace, batch.operations, finalOptions, resultHandler); - } else if(batch.batchType == common.REMOVE) { - self.s.topology.remove(self.s.collection.namespace, batch.operations, finalOptions, resultHandler); + addToOperationsList(batchType, document) { + // Get the bsonSize + const bsonSize = BSON.calculateObjectSize(document, { + checkKeys: false, + // Since we don't know what the user selected for BSON options here, + // err on the safe side, and check the size with ignoreUndefined: false. + ignoreUndefined: false + }); + // Throw error if the doc is bigger than the max BSON size + if (bsonSize >= this.s.maxBsonObjectSize) + // TODO(NODE-3483): Change this to MongoBSONError + throw new error_1.MongoInvalidArgumentError(`Document is larger than the maximum size ${this.s.maxBsonObjectSize}`); + // Create a new batch object if we don't have a current one + if (this.s.currentBatch == null) { + this.s.currentBatch = new common_1.Batch(batchType, this.s.currentIndex); + } + const maxKeySize = this.s.maxKeySize; + // Check if we need to create a new batch + if ( + // New batch if we exceed the max batch op size + this.s.currentBatchSize + 1 >= this.s.maxWriteBatchSize || + // New batch if we exceed the maxBatchSizeBytes. Only matters if batch already has a doc, + // since we can't sent an empty batch + (this.s.currentBatchSize > 0 && + this.s.currentBatchSizeBytes + maxKeySize + bsonSize >= this.s.maxBatchSizeBytes) || + // New batch if the new op does not have the same op type as the current batch + this.s.currentBatch.batchType !== batchType) { + // Save the batch to the execution stack + this.s.batches.push(this.s.currentBatch); + // Create a new batch + this.s.currentBatch = new common_1.Batch(batchType, this.s.currentIndex); + // Reset the current size trackers + this.s.currentBatchSize = 0; + this.s.currentBatchSizeBytes = 0; + } + if (batchType === common_1.BatchType.INSERT) { + this.s.bulkResult.insertedIds.push({ + index: this.s.currentIndex, + _id: document._id + }); + } + // We have an array of documents + if (Array.isArray(document)) { + throw new error_1.MongoInvalidArgumentError('Operation passed in cannot be an Array'); + } + this.s.currentBatch.originalIndexes.push(this.s.currentIndex); + this.s.currentBatch.operations.push(document); + this.s.currentBatchSize += 1; + this.s.currentBatchSizeBytes += maxKeySize + bsonSize; + this.s.currentIndex += 1; + return this; } - } catch(err) { - // Force top level error - err.ok = 0; - // Merge top level error and return - handleCallback(callback, null, mergeBatchResults(false, batch, self.s.bulkResult, err, null)); - } -} - -/** - * The callback format for results - * @callback OrderedBulkOperation~resultCallback - * @param {MongoError} error An error instance representing the error during the execution. - * @param {BulkWriteResult} result The bulk write result. - */ - -/** - * Execute the ordered bulk operation - * - * @method - * @param {object} [options=null] Optional settings. - * @param {(number|string)} [options.w=null] The write concern. - * @param {number} [options.wtimeout=null] The write concern timeout. - * @param {boolean} [options.j=false] Specify a journal write concern. - * @param {boolean} [options.fsync=false] Specify a file sync write concern. - * @param {OrderedBulkOperation~resultCallback} [callback] The result callback - * @throws {MongoError} - * @return {Promise} returns Promise if no callback passed - */ -OrderedBulkOperation.prototype.execute = function(_writeConcern, callback) { - var self = this; - if (this.s.executed) { - var executedError = toError('batch cannot be re-executed'); - return (typeof callback === 'function') ? - callback(executedError, null) : this.s.promiseLibrary.reject(executedError); - } - - if (typeof _writeConcern === 'function') { - callback = _writeConcern; - } else if (_writeConcern && typeof _writeConcern === 'object') { - this.s.writeConcern = _writeConcern; - } - - // If we have current batch - if (this.s.currentBatch) this.s.batches.push(this.s.currentBatch) - - // If we have no operations in the bulk raise an error - if (this.s.batches.length == 0) { - var emptyBatchError = toError('Invalid Operation, no operations specified'); - return (typeof callback === 'function') ? - callback(emptyBatchError, null) : this.s.promiseLibrary.reject(emptyBatchError); - } - - // Execute using callback - if (typeof callback === 'function') { - return executeCommands(this, callback); - } - - // Return a Promise - return new this.s.promiseLibrary(function(resolve, reject) { - executeCommands(self, function(err, r) { - if (err) return reject(err); - resolve(r); - }); - }); -} - -define.classMethod('execute', {callback: true, promise:false}); - -/** - * Returns an unordered batch object - * @ignore - */ -var initializeOrderedBulkOp = function(topology, collection, options) { - return new OrderedBulkOperation(topology, collection, options); } - -initializeOrderedBulkOp.OrderedBulkOperation = OrderedBulkOperation; -module.exports = initializeOrderedBulkOp; -module.exports.Bulk = OrderedBulkOperation; +exports.OrderedBulkOperation = OrderedBulkOperation; +//# sourceMappingURL=ordered.js.map \ No newline at end of file diff --git a/ts-ticket-office-service/node_modules/mongodb/lib/bulk/ordered.js.map b/ts-ticket-office-service/node_modules/mongodb/lib/bulk/ordered.js.map new file mode 100644 index 000000000..4058c1cde --- /dev/null +++ b/ts-ticket-office-service/node_modules/mongodb/lib/bulk/ordered.js.map @@ -0,0 +1 @@ +{"version":3,"file":"ordered.js","sourceRoot":"","sources":["../../src/bulk/ordered.ts"],"names":[],"mappings":";;;AACA,gCAAgC;AAEhC,oCAAqD;AAGrD,qCAAiF;AAEjF,cAAc;AACd,MAAa,oBAAqB,SAAQ,0BAAiB;IACzD,YAAY,UAAsB,EAAE,OAAyB;QAC3D,KAAK,CAAC,UAAU,E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,IAAI,CAAC,CAAC,CAAC,YAAY,GAAG,IAAI,cAAK,CAAC,SAAS,EAAE,IAAI,CAAC,CAAC,CAAC,YAAY,CAAC,CAAC;YAEhE,kCAAkC;YAClC,IAAI,CAAC,CAAC,CAAC,gBAAgB,GAAG,CAAC,CAAC;YAC5B,IAAI,CAAC,CAAC,CAAC,qBAAqB,GAAG,CAAC,CAAC;SAClC;QAED,IAAI,SAAS,KAAK,kBAAS,CAAC,MAAM,EAAE;YAClC,IAAI,CAAC,CAAC,CAAC,UAAU,CAAC,WAAW,CAAC,IAAI,CAAC;gBACjC,KAAK,EAAE,IAAI,CAAC,CAAC,CAAC,YAAY;gBAC1B,GAAG,EAAG,QAAqB,CAAC,GAAG;aAChC,CAAC,CAAC;SACJ;QAED,gCAAgC;QAChC,IAAI,KAAK,CAAC,OAAO,CAAC,QAAQ,CAAC,EAAE;YAC3B,MAAM,IAAI,iCAAyB,CAAC,wCAAwC,CAAC,CAAC;SAC/E;QAED,IAAI,CAAC,CAAC,CAAC,YAAY,CAAC,eAAe,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC,CAAC,YAAY,CAAC,CAAC;QAC9D,IAAI,CAAC,CAAC,CAAC,YAAY,CAAC,UAAU,CAAC,IAAI,CAAC,QAAQ,CAAC,CAAC;QAC9C,IAAI,CAAC,CAAC,CAAC,gBAAgB,IAAI,CAAC,CAAC;QAC7B,IAAI,CAAC,CAAC,CAAC,qBAAqB,IAAI,UAAU,GAAG,QAAQ,CAAC;QACtD,IAAI,CAAC,CAAC,CAAC,YAAY,IAAI,CAAC,CAAC;QACzB,OAAO,IAAI,CAAC;IACd,CAAC;CACF;AAxED,oDAwEC"} \ No newline at end of file diff --git a/ts-ticket-office-service/node_modules/mongodb/lib/bulk/unordered.js b/ts-ticket-office-service/node_modules/mongodb/lib/bulk/unordered.js index f6a801ef5..f5a34180e 100644 --- a/ts-ticket-office-service/node_modules/mongodb/lib/bulk/unordered.js +++ b/ts-ticket-office-service/node_modules/mongodb/lib/bulk/unordered.js @@ -1,541 +1,91 @@ "use strict"; - -var common = require('./common') - , utils = require('../utils') - , toError = require('../utils').toError - , handleCallback = require('../utils').handleCallback - , shallowClone = utils.shallowClone - , BulkWriteResult = common.BulkWriteResult - , ObjectID = require('mongodb-core').BSON.ObjectID - , BSON = require('mongodb-core').BSON - , Define = require('../metadata') - , Batch = common.Batch - , mergeBatchResults = common.mergeBatchResults; - -var bson = new BSON([BSON.Binary, BSON.Code, BSON.DBRef, BSON.Decimal128, - BSON.Double, BSON.Int32, BSON.Long, BSON.Map, BSON.MaxKey, BSON.MinKey, - BSON.ObjectId, BSON.BSONRegExp, BSON.Symbol, BSON.Timestamp]); - -/** - * Create a FindOperatorsUnordered instance (INTERNAL TYPE, do not instantiate directly) - * @class - * @property {number} length Get the number of operations in the bulk. - * @return {FindOperatorsUnordered} a FindOperatorsUnordered instance. - */ -var FindOperatorsUnordered = function(self) { - this.s = self.s; -} - -/** - * Add a single update document to the bulk operation - * - * @method - * @param {object} doc update operations - * @throws {MongoError} - * @return {UnorderedBulkOperation} - */ -FindOperatorsUnordered.prototype.update = function(updateDocument) { - // Perform upsert - var upsert = typeof this.s.currentOp.upsert == 'boolean' ? this.s.currentOp.upsert : false; - - // Establish the update command - var document = { - q: this.s.currentOp.selector - , u: updateDocument - , multi: true - , upsert: upsert - } - - // Clear out current Op - this.s.currentOp = null; - // Add the update document to the list - return addToOperationsList(this, common.UPDATE, document); -} - -/** - * Add a single update one document to the bulk operation - * - * @method - * @param {object} doc update operations - * @throws {MongoError} - * @return {UnorderedBulkOperation} - */ -FindOperatorsUnordered.prototype.updateOne = function(updateDocument) { - // Perform upsert - var upsert = typeof this.s.currentOp.upsert == 'boolean' ? this.s.currentOp.upsert : false; - - // Establish the update command - var document = { - q: this.s.currentOp.selector - , u: updateDocument - , multi: false - , upsert: upsert - } - - // Clear out current Op - this.s.currentOp = null; - // Add the update document to the list - return addToOperationsList(this, common.UPDATE, document); -} - -/** - * Add a replace one operation to the bulk operation - * - * @method - * @param {object} doc the new document to replace the existing one with - * @throws {MongoError} - * @return {UnorderedBulkOperation} - */ -FindOperatorsUnordered.prototype.replaceOne = function(updateDocument) { - this.updateOne(updateDocument); -} - -/** - * Upsert modifier for update bulk operation - * - * @method - * @throws {MongoError} - * @return {FindOperatorsUnordered} - */ -FindOperatorsUnordered.prototype.upsert = function() { - this.s.currentOp.upsert = true; - return this; -} - -/** - * Add a remove one operation to the bulk operation - * - * @method - * @throws {MongoError} - * @return {UnorderedBulkOperation} - */ -FindOperatorsUnordered.prototype.removeOne = function() { - // Establish the update command - var document = { - q: this.s.currentOp.selector - , limit: 1 - } - - // Clear out current Op - this.s.currentOp = null; - // Add the remove document to the list - return addToOperationsList(this, common.REMOVE, document); -} - -/** - * Add a remove operation to the bulk operation - * - * @method - * @throws {MongoError} - * @return {UnorderedBulkOperation} - */ -FindOperatorsUnordered.prototype.remove = function() { - // Establish the update command - var document = { - q: this.s.currentOp.selector - , limit: 0 - } - - // Clear out current Op - this.s.currentOp = null; - // Add the remove document to the list - return addToOperationsList(this, common.REMOVE, document); -} - -// -// Add to the operations list -// -var addToOperationsList = function(_self, docType, document) { - // Get the bsonSize - var bsonSize = bson.calculateObjectSize(document, { - checkKeys: false, - }); - // Throw error if the doc is bigger than the max BSON size - if(bsonSize >= _self.s.maxBatchSizeBytes) throw toError("document is larger than the maximum size " + _self.s.maxBatchSizeBytes); - // Holds the current batch - _self.s.currentBatch = null; - // Get the right type of batch - if(docType == common.INSERT) { - _self.s.currentBatch = _self.s.currentInsertBatch; - } else if(docType == common.UPDATE) { - _self.s.currentBatch = _self.s.currentUpdateBatch; - } else if(docType == common.REMOVE) { - _self.s.currentBatch = _self.s.currentRemoveBatch; - } - - // Create a new batch object if we don't have a current one - if(_self.s.currentBatch == null) _self.s.currentBatch = new Batch(docType, _self.s.currentIndex); - - // Check if we need to create a new batch - if(((_self.s.currentBatch.size + 1) >= _self.s.maxWriteBatchSize) - || ((_self.s.currentBatch.sizeBytes + bsonSize) >= _self.s.maxBatchSizeBytes) - || (_self.s.currentBatch.batchType != docType)) { - // Save the batch to the execution stack - _self.s.batches.push(_self.s.currentBatch); - - // Create a new batch - _self.s.currentBatch = new Batch(docType, _self.s.currentIndex); - } - - // We have an array of documents - if(Array.isArray(document)) { - throw toError("operation passed in cannot be an Array"); - } else { - _self.s.currentBatch.operations.push(document); - _self.s.currentBatch.originalIndexes.push(_self.s.currentIndex); - _self.s.currentIndex = _self.s.currentIndex + 1; - } - - // Save back the current Batch to the right type - if(docType == common.INSERT) { - _self.s.currentInsertBatch = _self.s.currentBatch; - _self.s.bulkResult.insertedIds.push({index: _self.s.bulkResult.insertedIds.length, _id: document._id}); - } else if(docType == common.UPDATE) { - _self.s.currentUpdateBatch = _self.s.currentBatch; - } else if(docType == common.REMOVE) { - _self.s.currentRemoveBatch = _self.s.currentBatch; - } - - // Update current batch size - _self.s.currentBatch.size = _self.s.currentBatch.size + 1; - _self.s.currentBatch.sizeBytes = _self.s.currentBatch.sizeBytes + bsonSize; - - // Return self - return _self; -} - -/** - * Create a new UnorderedBulkOperation instance (INTERNAL TYPE, do not instantiate directly) - * @class - * @property {number} length Get the number of operations in the bulk. - * @return {UnorderedBulkOperation} a UnorderedBulkOperation instance. - */ -var UnorderedBulkOperation = function(topology, collection, options) { - options = options == null ? {} : options; - - // Get the namespace for the write operations - var namespace = collection.collectionName; - // Used to mark operation as executed - var executed = false; - - // Current item - // var currentBatch = null; - var currentOp = null; - - // Handle to the bson serializer, used to calculate running sizes - var bson = topology.bson; - - // Set max byte size - var maxBatchSizeBytes = topology.isMasterDoc && topology.isMasterDoc.maxBsonObjectSize - ? topology.isMasterDoc.maxBsonObjectSize : (1024*1025*16); - var maxWriteBatchSize = topology.isMasterDoc && topology.isMasterDoc.maxWriteBatchSize - ? topology.isMasterDoc.maxWriteBatchSize : 1000; - - // Get the write concern - var writeConcern = common.writeConcern(shallowClone(options), collection, options); - - // Get the promiseLibrary - var promiseLibrary = options.promiseLibrary; - - // No promise library selected fall back - if(!promiseLibrary) { - promiseLibrary = typeof global.Promise == 'function' ? - global.Promise : require('es6-promise').Promise; - } - - // Final results - var bulkResult = { - ok: 1 - , writeErrors: [] - , writeConcernErrors: [] - , insertedIds: [] - , nInserted: 0 - , nUpserted: 0 - , nMatched: 0 - , nModified: 0 - , nRemoved: 0 - , upserted: [] - }; - - // Internal state - this.s = { - // Final result - bulkResult: bulkResult - // Current batch state - , currentInsertBatch: null - , currentUpdateBatch: null - , currentRemoveBatch: null - , currentBatch: null - , currentIndex: 0 - , batches: [] - // Write concern - , writeConcern: writeConcern - // Max batch size options - , maxBatchSizeBytes: maxBatchSizeBytes - , maxWriteBatchSize: maxWriteBatchSize - // Namespace - , namespace: namespace - // BSON - , bson: bson - // Topology - , topology: topology - // Options - , options: options - // Current operation - , currentOp: currentOp - // Executed - , executed: executed - // Collection - , collection: collection - // Promise Library - , promiseLibrary: promiseLibrary - // Bypass validation - , bypassDocumentValidation: typeof options.bypassDocumentValidation == 'boolean' ? options.bypassDocumentValidation : false - } -} - -var define = UnorderedBulkOperation.define = new Define('UnorderedBulkOperation', UnorderedBulkOperation, false); - -/** - * Add a single insert document to the bulk operation - * - * @param {object} doc the document to insert - * @throws {MongoError} - * @return {UnorderedBulkOperation} - */ -UnorderedBulkOperation.prototype.insert = function(document) { - if(this.s.collection.s.db.options.forceServerObjectId !== true && document._id == null) document._id = new ObjectID(); - return addToOperationsList(this, common.INSERT, document); -} - -/** - * Initiate a find operation for an update/updateOne/remove/removeOne/replaceOne - * - * @method - * @param {object} selector The selector for the bulk operation. - * @throws {MongoError} - * @return {FindOperatorsUnordered} - */ -UnorderedBulkOperation.prototype.find = function(selector) { - if (!selector) { - throw toError("Bulk find operation must specify a selector"); - } - - // Save a current selector - this.s.currentOp = { - selector: selector - } - - return new FindOperatorsUnordered(this); -} - -Object.defineProperty(UnorderedBulkOperation.prototype, 'length', { - enumerable: true, - get: function() { - return this.s.currentIndex; - } -}); - -UnorderedBulkOperation.prototype.raw = function(op) { - var key = Object.keys(op)[0]; - - // Set up the force server object id - var forceServerObjectId = typeof this.s.options.forceServerObjectId == 'boolean' - ? this.s.options.forceServerObjectId : this.s.collection.s.db.options.forceServerObjectId; - - // Update operations - if((op.updateOne && op.updateOne.q) - || (op.updateMany && op.updateMany.q) - || (op.replaceOne && op.replaceOne.q)) { - op[key].multi = op.updateOne || op.replaceOne ? false : true; - return addToOperationsList(this, common.UPDATE, op[key]); - } - - // Crud spec update format - if(op.updateOne || op.updateMany || op.replaceOne) { - var multi = op.updateOne || op.replaceOne ? false : true; - var operation = {q: op[key].filter, u: op[key].update || op[key].replacement, multi: multi} - if(op[key].upsert) operation.upsert = true; - return addToOperationsList(this, common.UPDATE, operation); - } - - // Remove operations - if(op.removeOne || op.removeMany || (op.deleteOne && op.deleteOne.q) || op.deleteMany && op.deleteMany.q) { - op[key].limit = op.removeOne ? 1 : 0; - return addToOperationsList(this, common.REMOVE, op[key]); - } - - // Crud spec delete operations, less efficient - if(op.deleteOne || op.deleteMany) { - var limit = op.deleteOne ? 1 : 0; - operation = {q: op[key].filter, limit: limit} - return addToOperationsList(this, common.REMOVE, operation); - } - - // Insert operations - if(op.insertOne && op.insertOne.document == null) { - if(forceServerObjectId !== true && op.insertOne._id == null) op.insertOne._id = new ObjectID(); - return addToOperationsList(this, common.INSERT, op.insertOne); - } else if(op.insertOne && op.insertOne.document) { - if(forceServerObjectId !== true && op.insertOne.document._id == null) op.insertOne.document._id = new ObjectID(); - return addToOperationsList(this, common.INSERT, op.insertOne.document); - } - - if(op.insertMany) { - for(var i = 0; i < op.insertMany.length; i++) { - if(forceServerObjectId !== true && op.insertMany[i]._id == null) op.insertMany[i]._id = new ObjectID(); - addToOperationsList(this, common.INSERT, op.insertMany[i]); +Object.defineProperty(exports, "__esModule", { value: true }); +exports.UnorderedBulkOperation = void 0; +const BSON = require("../bson"); +const error_1 = require("../error"); +const common_1 = require("./common"); +/** @public */ +class UnorderedBulkOperation extends common_1.BulkOperationBase { + constructor(collection, options) { + super(collection, options, false); } - - return; - } - - // No valid type of operation - throw toError("bulkWrite only supports insertOne, insertMany, updateOne, updateMany, removeOne, removeMany, deleteOne, deleteMany"); -} - -// -// Execute the command -var executeBatch = function(self, batch, callback) { - var finalOptions = {ordered: false} - if(self.s.writeConcern != null) { - finalOptions.writeConcern = self.s.writeConcern; - } - - var resultHandler = function(err, result) { - // Error is a driver related error not a bulk op error, terminate - if(err && err.driver || err && err.message) { - return handleCallback(callback, err); - } - - // If we have and error - if(err) err.ok = 0; - handleCallback(callback, null, mergeBatchResults(false, batch, self.s.bulkResult, err, result)); - } - - // Set an operationIf if provided - if(self.operationId) { - resultHandler.operationId = self.operationId; - } - - // Serialize functions - if(self.s.options.serializeFunctions) { - finalOptions.serializeFunctions = true - } - - // Is the bypassDocumentValidation options specific - if(self.s.bypassDocumentValidation == true) { - finalOptions.bypassDocumentValidation = true; - } - - try { - if(batch.batchType == common.INSERT) { - self.s.topology.insert(self.s.collection.namespace, batch.operations, finalOptions, resultHandler); - } else if(batch.batchType == common.UPDATE) { - self.s.topology.update(self.s.collection.namespace, batch.operations, finalOptions, resultHandler); - } else if(batch.batchType == common.REMOVE) { - self.s.topology.remove(self.s.collection.namespace, batch.operations, finalOptions, resultHandler); + handleWriteError(callback, writeResult) { + if (this.s.batches.length) { + return false; + } + return super.handleWriteError(callback, writeResult); + } + addToOperationsList(batchType, document) { + // Get the bsonSize + const bsonSize = BSON.calculateObjectSize(document, { + checkKeys: false, + // Since we don't know what the user selected for BSON options here, + // err on the safe side, and check the size with ignoreUndefined: false. + ignoreUndefined: false + }); + // Throw error if the doc is bigger than the max BSON size + if (bsonSize >= this.s.maxBsonObjectSize) { + // TODO(NODE-3483): Change this to MongoBSONError + throw new error_1.MongoInvalidArgumentError(`Document is larger than the maximum size ${this.s.maxBsonObjectSize}`); + } + // Holds the current batch + this.s.currentBatch = undefined; + // Get the right type of batch + if (batchType === common_1.BatchType.INSERT) { + this.s.currentBatch = this.s.currentInsertBatch; + } + else if (batchType === common_1.BatchType.UPDATE) { + this.s.currentBatch = this.s.currentUpdateBatch; + } + else if (batchType === common_1.BatchType.DELETE) { + this.s.currentBatch = this.s.currentRemoveBatch; + } + const maxKeySize = this.s.maxKeySize; + // Create a new batch object if we don't have a current one + if (this.s.currentBatch == null) { + this.s.currentBatch = new common_1.Batch(batchType, this.s.currentIndex); + } + // Check if we need to create a new batch + if ( + // New batch if we exceed the max batch op size + this.s.currentBatch.size + 1 >= this.s.maxWriteBatchSize || + // New batch if we exceed the maxBatchSizeBytes. Only matters if batch already has a doc, + // since we can't sent an empty batch + (this.s.currentBatch.size > 0 && + this.s.currentBatch.sizeBytes + maxKeySize + bsonSize >= this.s.maxBatchSizeBytes) || + // New batch if the new op does not have the same op type as the current batch + this.s.currentBatch.batchType !== batchType) { + // Save the batch to the execution stack + this.s.batches.push(this.s.currentBatch); + // Create a new batch + this.s.currentBatch = new common_1.Batch(batchType, this.s.currentIndex); + } + // We have an array of documents + if (Array.isArray(document)) { + throw new error_1.MongoInvalidArgumentError('Operation passed in cannot be an Array'); + } + this.s.currentBatch.operations.push(document); + this.s.currentBatch.originalIndexes.push(this.s.currentIndex); + this.s.currentIndex = this.s.currentIndex + 1; + // Save back the current Batch to the right type + if (batchType === common_1.BatchType.INSERT) { + this.s.currentInsertBatch = this.s.currentBatch; + this.s.bulkResult.insertedIds.push({ + index: this.s.bulkResult.insertedIds.length, + _id: document._id + }); + } + else if (batchType === common_1.BatchType.UPDATE) { + this.s.currentUpdateBatch = this.s.currentBatch; + } + else if (batchType === common_1.BatchType.DELETE) { + this.s.currentRemoveBatch = this.s.currentBatch; + } + // Update current batch size + this.s.currentBatch.size += 1; + this.s.currentBatch.sizeBytes += maxKeySize + bsonSize; + return this; } - } catch(err) { - // Force top level error - err.ok = 0; - // Merge top level error and return - handleCallback(callback, null, mergeBatchResults(false, batch, self.s.bulkResult, err, null)); - } -} - -// -// Execute all the commands -var executeBatches = function(self, callback) { - var numberOfCommandsToExecute = self.s.batches.length; - // Execute over all the batches - for(var i = 0; i < self.s.batches.length; i++) { - executeBatch(self, self.s.batches[i], function(err) { - // Driver layer error capture it - if(err) error = err; - // Count down the number of commands left to execute - numberOfCommandsToExecute = numberOfCommandsToExecute - 1; - - // Execute - if(numberOfCommandsToExecute == 0) { - // Driver level error - if(error) return handleCallback(callback, error); - // Treat write errors - var error = self.s.bulkResult.writeErrors.length > 0 ? toError(self.s.bulkResult.writeErrors[0]) : null; - handleCallback(callback, error, new BulkWriteResult(self.s.bulkResult)); - } - }); - } -} - -/** - * The callback format for results - * @callback UnorderedBulkOperation~resultCallback - * @param {MongoError} error An error instance representing the error during the execution. - * @param {BulkWriteResult} result The bulk write result. - */ - -/** - * Execute the ordered bulk operation - * - * @method - * @param {object} [options=null] Optional settings. - * @param {(number|string)} [options.w=null] The write concern. - * @param {number} [options.wtimeout=null] The write concern timeout. - * @param {boolean} [options.j=false] Specify a journal write concern. - * @param {boolean} [options.fsync=false] Specify a file sync write concern. - * @param {UnorderedBulkOperation~resultCallback} [callback] The result callback - * @throws {MongoError} - * @return {Promise} returns Promise if no callback passed - */ -UnorderedBulkOperation.prototype.execute = function(_writeConcern, callback) { - var self = this; - if (this.s.executed) { - var executedError = toError('batch cannot be re-executed'); - return (typeof callback === 'function') ? - callback(executedError, null) : this.s.promiseLibrary.reject(executedError); - } - - if (typeof _writeConcern === 'function') { - callback = _writeConcern; - } else if (_writeConcern && typeof _writeConcern === 'object') { - this.s.writeConcern = _writeConcern; - } - - // If we have current batch - if (this.s.currentInsertBatch) this.s.batches.push(this.s.currentInsertBatch); - if (this.s.currentUpdateBatch) this.s.batches.push(this.s.currentUpdateBatch); - if (this.s.currentRemoveBatch) this.s.batches.push(this.s.currentRemoveBatch); - - // If we have no operations in the bulk raise an error - if (this.s.batches.length == 0) { - var emptyBatchError = toError('Invalid Operation, no operations specified'); - return (typeof callback === 'function') ? - callback(emptyBatchError, null) : this.s.promiseLibrary.reject(emptyBatchError); - } - - // Execute using callback - if (typeof callback === 'function') return executeBatches(this, callback); - - // Return a Promise - return new this.s.promiseLibrary(function(resolve, reject) { - executeBatches(self, function(err, r) { - if (err) return reject(err); - resolve(r); - }); - }); -} - -define.classMethod('execute', {callback: true, promise:false}); - -/** - * Returns an unordered batch object - * @ignore - */ -var initializeUnorderedBulkOp = function(topology, collection, options) { - return new UnorderedBulkOperation(topology, collection, options); } - -initializeUnorderedBulkOp.UnorderedBulkOperation = UnorderedBulkOperation; -module.exports = initializeUnorderedBulkOp; -module.exports.Bulk = UnorderedBulkOperation; +exports.UnorderedBulkOperation = UnorderedBulkOperation; +//# sourceMappingURL=unordered.js.map \ No newline at end of file diff --git a/ts-ticket-office-service/node_modules/mongodb/lib/bulk/unordered.js.map b/ts-ticket-office-service/node_modules/mongodb/lib/bulk/unordered.js.map new file mode 100644 index 000000000..476e1998e --- /dev/null +++ b/ts-ticket-office-service/node_modules/mongodb/lib/bulk/unordered.js.map @@ -0,0 +1 @@ +{"version":3,"file":"unordered.js","sourceRoot":"","sources":["../../src/bulk/unordered.ts"],"names":[],"mappings":";;;AACA,gCAAgC;AAEhC,oCAAqD;AAIrD,qCAAkG;AAElG,cAAc;AACd,MAAa,sBAAuB,SAAQ,0BAAiB;IAC3D,YAAY,UAAsB,EAAE,OAAyB;QAC3D,KAAK,CAAC,UAAU,EAAE,OAAO,EAAE,KAAK,CAAC,CAAC;IACpC,CAAC;IAEQ,gBAAgB,CAAC,QAAkB,EAAE,WAA4B;QACxE,IAAI,IAAI,CAAC,CAAC,CAAC,OAAO,CAAC,MAAM,EAAE;YACzB,OAAO,KAAK,CAAC;SACd;QAED,OAAO,KAAK,CAAC,gBAAgB,CAAC,QAAQ,EAAE,WAAW,CAAC,CAAC;IACvD,CAAC;IAED,mBAAmB,CACjB,SAAoB,EACpB,QAAsD;QAEtD,mBAAmB;QACnB,MAAM,QAAQ,GAAG,IAAI,CAAC,mBAAmB,CAAC,QAAQ,EAAE;YAClD,SAAS,EAAE,KAAK;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AAS,KAAK,kBAAS,CAAC,MAAM,EAAE;YACzC,IAAI,CAAC,CAAC,CAAC,kBAAkB,GAAG,IAAI,CAAC,CAAC,CAAC,YAAY,CAAC;SACjD;aAAM,IAAI,SAAS,KAAK,kBAAS,CAAC,MAAM,EAAE;YACzC,IAAI,CAAC,CAAC,CAAC,kBAAkB,GAAG,IAAI,CAAC,CAAC,CAAC,YAAY,CAAC;SACjD;QAED,4BAA4B;QAC5B,IAAI,CAAC,CAAC,CAAC,YAAY,CAAC,IAAI,IAAI,CAAC,CAAC;QAC9B,IAAI,CAAC,CAAC,CAAC,YAAY,CAAC,SAAS,IAAI,UAAU,GAAG,QAAQ,CAAC;QAEvD,OAAO,IAAI,CAAC;IACd,CAAC;CACF;AAlGD,wDAkGC"} \ No newline at end of file diff --git a/ts-ticket-office-service/node_modules/mongodb/lib/change_stream.js b/ts-ticket-office-service/node_modules/mongodb/lib/change_stream.js new file mode 100644 index 000000000..49ef1bc3e --- /dev/null +++ b/ts-ticket-office-service/node_modules/mongodb/lib/change_stream.js @@ -0,0 +1,374 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.ChangeStream = void 0; +const util_1 = require("util"); +const collection_1 = require("./collection"); +const constants_1 = require("./constants"); +const change_stream_cursor_1 = require("./cursor/change_stream_cursor"); +const db_1 = require("./db"); +const error_1 = require("./error"); +const mongo_client_1 = require("./mongo_client"); +const mongo_types_1 = require("./mongo_types"); +const utils_1 = require("./utils"); +/** @internal */ +const kCursorStream = Symbol('cursorStream'); +/** @internal */ +const kClosed = Symbol('closed'); +/** @internal */ +const kMode = Symbol('mode'); +const CHANGE_STREAM_OPTIONS = [ + 'resumeAfter', + 'startAfter', + 'startAtOperationTime', + 'fullDocument', + 'fullDocumentBeforeChange', + 'showExpandedEvents' +]; +const CHANGE_DOMAIN_TYPES = { + COLLECTION: Symbol('Collection'), + DATABASE: Symbol('Database'), + CLUSTER: Symbol('Cluster') +}; +const CHANGE_STREAM_EVENTS = [constants_1.RESUME_TOKEN_CHANGED, constants_1.END, constants_1.CLOSE]; +const NO_RESUME_TOKEN_ERROR = 'A change stream document has been received that lacks a resume token (_id).'; +const CHANGESTREAM_CLOSED_ERROR = 'ChangeStream is closed'; +/** + * Creates a new Change Stream instance. Normally created using {@link Collection#watch|Collection.watch()}. + * @public + */ +class ChangeStream extends mongo_types_1.TypedEventEmitter { + /** + * @internal + * + * @param parent - The parent object that created this change stream + * @param pipeline - An array of {@link https://docs.mongodb.com/manual/reference/operator/aggregation-pipeline/|aggregation pipeline stages} through which to pass change stream documents + */ + constructor(parent, pipeline = [], options = {}) { + super(); + /** + * @internal + * + * TODO(NODE-4320): promisify selectServer and refactor this code to be async + * + * we promisify _processErrorIteratorModeCallback until we have a promisifed version of selectServer. + */ + // eslint-disable-next-line @typescript-eslint/unbound-method + this._processErrorIteratorMode = (0, util_1.promisify)(this._processErrorIteratorModeCallback); + this.pipeline = pipeline; + this.options = options; + if (parent instanceof collection_1.Collection) { + this.type = CHANGE_DOMAIN_TYPES.COLLECTION; + } + else if (parent instanceof db_1.Db) { + this.type = CHANGE_DOMAIN_TYPES.DATABASE; + } + else if (parent instanceof mongo_client_1.MongoClient) { + this.type = CHANGE_DOMAIN_TYPES.CLUSTER; + } + else { + throw new error_1.MongoChangeStreamError('Parent provided to ChangeStream constructor must be an instance of Collection, Db, or MongoClient'); + } + this.parent = parent; + this.namespace = parent.s.namespace; + if (!this.options.readPreference && parent.readPreference) { + this.options.readPreference = parent.readPreference; + } + // Create contained Change Stream cursor + this.cursor = this._createChangeStreamCursor(options); + this[kClosed] = false; + this[kMode] = false; + // Listen for any `change` listeners being added to ChangeStream + this.on('newListener', eventName => { + if (eventName === 'change' && this.cursor && this.listenerCount('change') === 0) { + this._streamEvents(this.cursor); + } + }); + this.on('removeListener', eventName => { + var _a; + if (eventName === 'change' && this.listenerCount('change') === 0 && this.cursor) { + (_a = this[kCursorStream]) === null || _a === void 0 ? void 0 : _a.removeAllListeners('data'); + } + }); + } + /** @internal */ + get cursorStream() { + return this[kCursorStream]; + } + /** The cached resume token that is used to resume after the most recently returned change. */ + get resumeToken() { + var _a; + return (_a = this.cursor) === null || _a === void 0 ? void 0 : _a.resumeToken; + } + hasNext(callback) { + this._setIsIterator(); + // TOOD(NODE-4319): Add eslint rule preventing accidental variable shadowing + // Shadowing is intentional here. We want to override the `callback` variable + // from the outer scope so that the inner scope doesn't accidentally call the wrong callback. + return (0, utils_1.maybePromise)(callback, callback => { + (async () => { + try { + const hasNext = await this.cursor.hasNext(); + return hasNext; + } + catch (error) { + try { + await this._processErrorIteratorMode(error); + const hasNext = await this.cursor.hasNext(); + return hasNext; + } + catch (error) { + await this.close().catch(err => err); + throw error; + } + } + })().then(hasNext => callback(undefined, hasNext), error => callback(error)); + }); + } + next(callback) { + this._setIsIterator(); + // TOOD(NODE-4319): Add eslint rule preventing accidental variable shadowing + // Shadowing is intentional here. We want to override the `callback` variable + // from the outer scope so that the inner scope doesn't accidentally call the wrong callback. + return (0, utils_1.maybePromise)(callback, callback => { + (async () => { + try { + const change = await this.cursor.next(); + const processedChange = this._processChange(change !== null && change !== void 0 ? change : null); + return processedChange; + } + catch (error) { + try { + await this._processErrorIteratorMode(error); + const change = await this.cursor.next(); + const processedChange = this._processChange(change !== null && change !== void 0 ? change : null); + return processedChange; + } + catch (error) { + await this.close().catch(err => err); + throw error; + } + } + })().then(change => callback(undefined, change), error => callback(error)); + }); + } + tryNext(callback) { + this._setIsIterator(); + // TOOD(NODE-4319): Add eslint rule preventing accidental variable shadowing + // Shadowing is intentional here. We want to override the `callback` variable + // from the outer scope so that the inner scope doesn't accidentally call the wrong callback. + return (0, utils_1.maybePromise)(callback, callback => { + (async () => { + try { + const change = await this.cursor.tryNext(); + return change !== null && change !== void 0 ? change : null; + } + catch (error) { + try { + await this._processErrorIteratorMode(error); + const change = await this.cursor.tryNext(); + return change !== null && change !== void 0 ? change : null; + } + catch (error) { + await this.close().catch(err => err); + throw error; + } + } + })().then(change => callback(undefined, change), error => callback(error)); + }); + } + /** Is the cursor closed */ + get closed() { + return this[kClosed] || this.cursor.closed; + } + close(callback) { + this[kClosed] = true; + return (0, utils_1.maybePromise)(callback, cb => { + const cursor = this.cursor; + return cursor.close(err => { + this._endStream(); + return cb(err); + }); + }); + } + /** + * Return a modified Readable stream including a possible transform method. + * + * NOTE: When using a Stream to process change stream events, the stream will + * NOT automatically resume in the case a resumable error is encountered. + * + * @throws MongoChangeStreamError if the underlying cursor or the change stream is closed + */ + stream(options) { + if (this.closed) { + throw new error_1.MongoChangeStreamError(CHANGESTREAM_CLOSED_ERROR); + } + this.streamOptions = options; + return this.cursor.stream(options); + } + /** @internal */ + _setIsEmitter() { + if (this[kMode] === 'iterator') { + // TODO(NODE-3485): Replace with MongoChangeStreamModeError + throw new error_1.MongoAPIError('ChangeStream cannot be used as an EventEmitter after being used as an iterator'); + } + this[kMode] = 'emitter'; + } + /** @internal */ + _setIsIterator() { + if (this[kMode] === 'emitter') { + // TODO(NODE-3485): Replace with MongoChangeStreamModeError + throw new error_1.MongoAPIError('ChangeStream cannot be used as an iterator after being used as an EventEmitter'); + } + this[kMode] = 'iterator'; + } + /** + * Create a new change stream cursor based on self's configuration + * @internal + */ + _createChangeStreamCursor(options) { + const changeStreamStageOptions = (0, utils_1.filterOptions)(options, CHANGE_STREAM_OPTIONS); + if (this.type === CHANGE_DOMAIN_TYPES.CLUSTER) { + changeStreamStageOptions.allChangesForCluster = true; + } + const pipeline = [{ $changeStream: changeStreamStageOptions }, ...this.pipeline]; + const client = this.type === CHANGE_DOMAIN_TYPES.CLUSTER + ? this.parent + : this.type === CHANGE_DOMAIN_TYPES.DATABASE + ? this.parent.s.client + : this.type === CHANGE_DOMAIN_TYPES.COLLECTION + ? this.parent.s.db.s.client + : null; + if (client == null) { + // This should never happen because of the assertion in the constructor + throw new error_1.MongoRuntimeError(`Changestream type should only be one of cluster, database, collection. Found ${this.type.toString()}`); + } + const changeStreamCursor = new change_stream_cursor_1.ChangeStreamCursor(client, this.namespace, pipeline, options); + for (const event of CHANGE_STREAM_EVENTS) { + changeStreamCursor.on(event, e => this.emit(event, e)); + } + if (this.listenerCount(ChangeStream.CHANGE) > 0) { + this._streamEvents(changeStreamCursor); + } + return changeStreamCursor; + } + /** @internal */ + _closeEmitterModeWithError(error) { + this.emit(ChangeStream.ERROR, error); + this.close(() => { + // nothing to do + }); + } + /** @internal */ + _streamEvents(cursor) { + var _a; + this._setIsEmitter(); + const stream = (_a = this[kCursorStream]) !== null && _a !== void 0 ? _a : cursor.stream(); + this[kCursorStream] = stream; + stream.on('data', change => { + try { + const processedChange = this._processChange(change); + this.emit(ChangeStream.CHANGE, processedChange); + } + catch (error) { + this.emit(ChangeStream.ERROR, error); + } + }); + stream.on('error', error => this._processErrorStreamMode(error)); + } + /** @internal */ + _endStream() { + const cursorStream = this[kCursorStream]; + if (cursorStream) { + ['data', 'close', 'end', 'error'].forEach(event => cursorStream.removeAllListeners(event)); + cursorStream.destroy(); + } + this[kCursorStream] = undefined; + } + /** @internal */ + _processChange(change) { + if (this[kClosed]) { + // TODO(NODE-3485): Replace with MongoChangeStreamClosedError + throw new error_1.MongoAPIError(CHANGESTREAM_CLOSED_ERROR); + } + // a null change means the cursor has been notified, implicitly closing the change stream + if (change == null) { + // TODO(NODE-3485): Replace with MongoChangeStreamClosedError + throw new error_1.MongoRuntimeError(CHANGESTREAM_CLOSED_ERROR); + } + if (change && !change._id) { + throw new error_1.MongoChangeStreamError(NO_RESUME_TOKEN_ERROR); + } + // cache the resume token + this.cursor.cacheResumeToken(change._id); + // wipe the startAtOperationTime if there was one so that there won't be a conflict + // between resumeToken and startAtOperationTime if we need to reconnect the cursor + this.options.startAtOperationTime = undefined; + return change; + } + /** @internal */ + _processErrorStreamMode(changeStreamError) { + // If the change stream has been closed explicitly, do not process error. + if (this[kClosed]) + return; + if ((0, error_1.isResumableError)(changeStreamError, this.cursor.maxWireVersion)) { + this._endStream(); + this.cursor.close().catch(() => null); + const topology = (0, utils_1.getTopology)(this.parent); + topology.selectServer(this.cursor.readPreference, {}, serverSelectionError => { + if (serverSelectionError) + return this._closeEmitterModeWithError(changeStreamError); + this.cursor = this._createChangeStreamCursor(this.cursor.resumeOptions); + }); + } + else { + this._closeEmitterModeWithError(changeStreamError); + } + } + /** @internal */ + _processErrorIteratorModeCallback(changeStreamError, callback) { + if (this[kClosed]) { + // TODO(NODE-3485): Replace with MongoChangeStreamClosedError + return callback(new error_1.MongoAPIError(CHANGESTREAM_CLOSED_ERROR)); + } + if ((0, error_1.isResumableError)(changeStreamError, this.cursor.maxWireVersion)) { + this.cursor.close().catch(() => null); + const topology = (0, utils_1.getTopology)(this.parent); + topology.selectServer(this.cursor.readPreference, {}, serverSelectionError => { + // if the topology can't reconnect, close the stream + if (serverSelectionError) + return this.close(() => callback(changeStreamError)); + this.cursor = this._createChangeStreamCursor(this.cursor.resumeOptions); + callback(); + }); + } + else { + this.close(() => callback(changeStreamError)); + } + } +} +exports.ChangeStream = ChangeStream; +/** @event */ +ChangeStream.RESPONSE = constants_1.RESPONSE; +/** @event */ +ChangeStream.MORE = constants_1.MORE; +/** @event */ +ChangeStream.INIT = constants_1.INIT; +/** @event */ +ChangeStream.CLOSE = constants_1.CLOSE; +/** + * Fired for each new matching change in the specified namespace. Attaching a `change` + * event listener to a Change Stream will switch the stream into flowing mode. Data will + * then be passed as soon as it is available. + * @event + */ +ChangeStream.CHANGE = constants_1.CHANGE; +/** @event */ +ChangeStream.END = constants_1.END; +/** @event */ +ChangeStream.ERROR = constants_1.ERROR; +/** + * Emitted each time the change stream stores a new resume token. + * @event + */ +ChangeStream.RESUME_TOKEN_CHANGED = constants_1.RESUME_TOKEN_CHANGED; +//# sourceMappingURL=change_stream.js.map \ No newline at end of file diff --git a/ts-ticket-office-service/node_modules/mongodb/lib/change_stream.js.map b/ts-ticket-office-service/node_modules/mongodb/lib/change_stream.js.map new file mode 100644 index 000000000..70ae147bb --- /dev/null +++ b/ts-ticket-office-service/node_modules/mongodb/lib/change_stream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auth/auth_provider.js b/ts-ticket-office-service/node_modules/mongodb/lib/cmap/auth/auth_provider.js new file mode 100644 index 000000000..b9a840ee8 --- /dev/null +++ b/ts-ticket-office-service/node_modules/mongodb/lib/cmap/auth/auth_provider.js @@ -0,0 +1,36 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.AuthProvider = exports.AuthContext = void 0; +const error_1 = require("../../error"); +/** Context used during authentication */ +class AuthContext { + constructor(connection, credentials, options) { + this.connection = connection; + this.credentials = credentials; + this.options = options; + } +} +exports.AuthContext = AuthContext; +class AuthProvider { + /** + * Prepare the handshake document before the initial handshake. + * + * @param handshakeDoc - The document used for the initial handshake on a connection + * @param authContext - Context for authentication flow + */ + prepare(handshakeDoc, authContext, callback) { + callback(undefined, handshakeDoc); + } + /** + * Authenticate + * + * @param context - A shared context for authentication flow + * @param callback - The callback to return the result from the authentication + */ + auth(context, callback) { + // TODO(NODE-3483): Replace this with MongoMethodOverrideError + callback(new error_1.MongoRuntimeError('`auth` method must be overridden by subclass')); + } +} +exports.AuthProvider = AuthProvider; +//# sourceMappingURL=auth_provider.js.map \ No newline at end of file diff --git a/ts-ticket-office-service/node_modules/mongodb/lib/cmap/auth/auth_provider.js.map b/ts-ticket-office-service/node_modules/mongodb/lib/cmap/auth/auth_provider.js.map new file mode 100644 index 000000000..c03ab3749 --- /dev/null +++ b/ts-ticket-office-service/node_modules/mongodb/lib/cmap/auth/auth_provider.js.map @@ -0,0 +1 @@ +{"version":3,"file":"auth_provider.js","sourceRoot":"","sources":["../../../src/cmap/auth/auth_provider.ts"],"names":[],"mappings":";;;AACA,uCAAgD;AAQhD,yCAAyC;AACzC,MAAa,WAAW;IAatB,YACE,UAAsB,EACtB,WAAyC,EACzC,OAA2B;QAE3B,IAAI,CAAC,UAAU,GAAG,UAAU,CAAC;QAC7B,IAAI,CAAC,WAAW,GAAG,WAAW,CAAC;QAC/B,IAAI,CAAC,OAAO,GAAG,OAAO,CAAC;IACzB,CAAC;CACF;AAtBD,kCAsBC;AAED,MAAa,YAAY;IACvB;;;;;OAKG;IACH,OAAO,CACL,YAA+B,EAC/B,WAAwB,EACxB,QAAqC;QAErC,QAAQ,CAAC,SAAS,EAAE,YAAY,CAAC,CAAC;IACpC,CAAC;IAED;;;;;OAKG;IACH,IAAI,CAAC,OAAoB,EAAE,QAAkB;QAC3C,8DAA8D;QAC9D,QAAQ,CAAC,IAAI,yBAAiB,CAAC,8CAA8C,CAAC,CAAC,CAAC;IAClF,CAAC;CACF;AAzBD,oCAyBC"} \ No newline at end of file diff --git a/ts-ticket-office-service/node_modules/mongodb/lib/cmap/auth/gssapi.js b/ts-ticket-office-service/node_modules/mongodb/lib/cmap/auth/gssapi.js new file mode 100644 index 000000000..0f16b587e --- /dev/null +++ b/ts-ticket-office-service/node_modules/mongodb/lib/cmap/auth/gssapi.js @@ -0,0 +1,190 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.resolveCname = exports.performGSSAPICanonicalizeHostName = exports.GSSAPI = exports.GSSAPICanonicalizationValue = void 0; +const dns = require("dns"); +const deps_1 = require("../../deps"); +const error_1 = require("../../error"); +const utils_1 = require("../../utils"); +const auth_provider_1 = require("./auth_provider"); +/** @public */ +exports.GSSAPICanonicalizationValue = Object.freeze({ + on: true, + off: false, + none: 'none', + forward: 'forward', + forwardAndReverse: 'forwardAndReverse' +}); +class GSSAPI extends auth_provider_1.AuthProvider { + auth(authContext, callback) { + const { connection, credentials } = authContext; + if (credentials == null) + return callback(new error_1.MongoMissingCredentialsError('Credentials required for GSSAPI authentication')); + const { username } = credentials; + function externalCommand(command, cb) { + return connection.command((0, utils_1.ns)('$external.$cmd'), command, undefined, cb); + } + makeKerberosClient(authContext, (err, client) => { + if (err) + return callback(err); + if (client == null) + return callback(new error_1.MongoMissingDependencyError('GSSAPI client missing')); + client.step('', (err, payload) => { + if (err) + return callback(err); + externalCommand(saslStart(payload), (err, result) => { + if (err) + return callback(err); + if (result == null) + return callback(); + negotiate(client, 10, result.payload, (err, payload) => { + if (err) + return callback(err); + externalCommand(saslContinue(payload, result.conversationId), (err, result) => { + if (err) + return callback(err); + if (result == null) + return callback(); + finalize(client, username, result.payload, (err, payload) => { + if (err) + return callback(err); + externalCommand({ + saslContinue: 1, + conversationId: result.conversationId, + payload + }, (err, result) => { + if (err) + return callback(err); + callback(undefined, result); + }); + }); + }); + }); + }); + }); + }); + } +} +exports.GSSAPI = GSSAPI; +function makeKerberosClient(authContext, callback) { + var _a; + const { hostAddress } = authContext.options; + const { credentials } = authContext; + if (!hostAddress || typeof hostAddress.host !== 'string' || !credentials) { + return callback(new error_1.MongoInvalidArgumentError('Connection must have host and port and credentials defined.')); + } + if ('kModuleError' in deps_1.Kerberos) { + return callback(deps_1.Kerberos['kModuleError']); + } + const { initializeClient } = deps_1.Kerberos; + const { username, password } = credentials; + const mechanismProperties = credentials.mechanismProperties; + const serviceName = (_a = mechanismProperties.SERVICE_NAME) !== null && _a !== void 0 ? _a : 'mongodb'; + performGSSAPICanonicalizeHostName(hostAddress.host, mechanismProperties, (err, host) => { + var _a; + if (err) + return callback(err); + const initOptions = {}; + if (password != null) { + Object.assign(initOptions, { user: username, password: password }); + } + const spnHost = (_a = mechanismProperties.SERVICE_HOST) !== null && _a !== void 0 ? _a : host; + let spn = `${serviceName}${process.platform === 'win32' ? '/' : '@'}${spnHost}`; + if ('SERVICE_REALM' in mechanismProperties) { + spn = `${spn}@${mechanismProperties.SERVICE_REALM}`; + } + initializeClient(spn, initOptions, (err, client) => { + // TODO(NODE-3483) + if (err) + return callback(new error_1.MongoRuntimeError(err)); + callback(undefined, client); + }); + }); +} +function saslStart(payload) { + return { + saslStart: 1, + mechanism: 'GSSAPI', + payload, + autoAuthorize: 1 + }; +} +function saslContinue(payload, conversationId) { + return { + saslContinue: 1, + conversationId, + payload + }; +} +function negotiate(client, retries, payload, callback) { + client.step(payload, (err, response) => { + // Retries exhausted, raise error + if (err && retries === 0) + return callback(err); + // Adjust number of retries and call step again + if (err) + return negotiate(client, retries - 1, payload, callback); + // Return the payload + callback(undefined, response || ''); + }); +} +function finalize(client, user, payload, callback) { + // GSS Client Unwrap + client.unwrap(payload, (err, response) => { + if (err) + return callback(err); + // Wrap the response + client.wrap(response || '', { user }, (err, wrapped) => { + if (err) + return callback(err); + // Return the payload + callback(undefined, wrapped); + }); + }); +} +function performGSSAPICanonicalizeHostName(host, mechanismProperties, callback) { + const mode = mechanismProperties.CANONICALIZE_HOST_NAME; + if (!mode || mode === exports.GSSAPICanonicalizationValue.none) { + return callback(undefined, host); + } + // If forward and reverse or true + if (mode === exports.GSSAPICanonicalizationValue.on || + mode === exports.GSSAPICanonicalizationValue.forwardAndReverse) { + // Perform the lookup of the ip address. + dns.lookup(host, (error, address) => { + // No ip found, return the error. + if (error) + return callback(error); + // Perform a reverse ptr lookup on the ip address. + dns.resolvePtr(address, (err, results) => { + // This can error as ptr records may not exist for all ips. In this case + // fallback to a cname lookup as dns.lookup() does not return the + // cname. + if (err) { + return resolveCname(host, callback); + } + // If the ptr did not error but had no results, return the host. + callback(undefined, results.length > 0 ? results[0] : host); + }); + }); + } + else { + // The case for forward is just to resolve the cname as dns.lookup() + // will not return it. + resolveCname(host, callback); + } +} +exports.performGSSAPICanonicalizeHostName = performGSSAPICanonicalizeHostName; +function resolveCname(host, callback) { + // Attempt to resolve the host name + dns.resolveCname(host, (err, r) => { + if (err) + return callback(undefined, host); + // Get the first resolve host id + if (r.length > 0) { + return callback(undefined, r[0]); + } + callback(undefined, host); + }); +} +exports.resolveCname = resolveCname; +//# sourceMappingURL=gssapi.js.map \ No newline at end of file diff --git a/ts-ticket-office-service/node_modules/mongodb/lib/cmap/auth/gssapi.js.map b/ts-ticket-office-service/node_modules/mongodb/lib/cmap/auth/gssapi.js.map new file mode 100644 index 000000000..341c2e07a --- /dev/null +++ b/ts-ticket-office-service/node_modules/mongodb/lib/cmap/auth/gssapi.js.map @@ -0,0 +1 @@ +{"version":3,"file":"gssapi.js","sourceRoot":"","sources":["../../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G,CAAC,CAAC,CAAC,CAAC,OAAO,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,IAAI,CAAC,CAAC;YAC9D,CAAC,CAAC,CAAC;QACL,CAAC,CAAC,CAAC;KACJ;SAAM;QACL,oEAAoE;QACpE,sBAAsB;QACtB,YAAY,CAAC,IAAI,EAAE,QAAQ,CAAC,CAAC;KAC9B;AACH,CAAC;AArCD,8EAqCC;AAED,SAAgB,YAAY,CAAC,IAAY,EAAE,QAA0B;IACnE,mCAAmC;IACnC,GAAG,CAAC,YAAY,CAAC,IAAI,EAAE,CAAC,GAAG,EAAE,CAAC,EAAE,EAAE;QAChC,IAAI,GAAG;YAAE,OAAO,QAAQ,CAAC,SAAS,EAAE,IAAI,CAAC,CAAC;QAE1C,gCAAgC;QAChC,IAAI,CAAC,CAAC,MAAM,GAAG,CAAC,EAAE;YAChB,OAAO,QAAQ,CAAC,SAAS,EAAE,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC;SAClC;QAED,QAAQ,CAAC,SAAS,EAAE,IAAI,CAAC,CAAC;IAC5B,CAAC,CAAC,CAAC;AACL,CAAC;AAZD,oCAYC"} \ No newline at end of file diff --git a/ts-ticket-office-service/node_modules/mongodb/lib/cmap/auth/mongo_credentials.js b/ts-ticket-office-service/node_modules/mongodb/lib/cmap/auth/mongo_credentials.js new file mode 100644 index 000000000..7fe66e5b5 --- /dev/null +++ b/ts-ticket-office-service/node_modules/mongodb/lib/cmap/auth/mongo_credentials.js @@ -0,0 +1,134 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.MongoCredentials = void 0; +const error_1 = require("../../error"); +const utils_1 = require("../../utils"); +const gssapi_1 = require("./gssapi"); +const providers_1 = require("./providers"); +// https://github.com/mongodb/specifications/blob/master/source/auth/auth.rst +function getDefaultAuthMechanism(hello) { + if (hello) { + // If hello contains saslSupportedMechs, use scram-sha-256 + // if it is available, else scram-sha-1 + if (Array.isArray(hello.saslSupportedMechs)) { + return hello.saslSupportedMechs.includes(providers_1.AuthMechanism.MONGODB_SCRAM_SHA256) + ? providers_1.AuthMechanism.MONGODB_SCRAM_SHA256 + : providers_1.AuthMechanism.MONGODB_SCRAM_SHA1; + } + // Fallback to legacy selection method. If wire version >= 3, use scram-sha-1 + if (hello.maxWireVersion >= 3) { + return providers_1.AuthMechanism.MONGODB_SCRAM_SHA1; + } + } + // Default for wireprotocol < 3 + return providers_1.AuthMechanism.MONGODB_CR; +} +/** + * A representation of the credentials used by MongoDB + * @public + */ +class MongoCredentials { + constructor(options) { + this.username = options.username; + this.password = options.password; + this.source = options.source; + if (!this.source && options.db) { + this.source = options.db; + } + this.mechanism = options.mechanism || providers_1.AuthMechanism.MONGODB_DEFAULT; + this.mechanismProperties = options.mechanismProperties || {}; + if (this.mechanism.match(/MONGODB-AWS/i)) { + if (!this.username && process.env.AWS_ACCESS_KEY_ID) { + this.username = process.env.AWS_ACCESS_KEY_ID; + } + if (!this.password && process.env.AWS_SECRET_ACCESS_KEY) { + this.password = process.env.AWS_SECRET_ACCESS_KEY; + } + if (this.mechanismProperties.AWS_SESSION_TOKEN == null && + process.env.AWS_SESSION_TOKEN != null) { + this.mechanismProperties = { + ...this.mechanismProperties, + AWS_SESSION_TOKEN: process.env.AWS_SESSION_TOKEN + }; + } + } + if ('gssapiCanonicalizeHostName' in this.mechanismProperties) { + (0, utils_1.emitWarningOnce)('gssapiCanonicalizeHostName is deprecated. Please use CANONICALIZE_HOST_NAME instead.'); + this.mechanismProperties.CANONICALIZE_HOST_NAME = + this.mechanismProperties.gssapiCanonicalizeHostName; + } + Object.freeze(this.mechanismProperties); + Object.freeze(this); + } + /** Determines if two MongoCredentials objects are equivalent */ + equals(other) { + return (this.mechanism === other.mechanism && + this.username === other.username && + this.password === other.password && + this.source === other.source); + } + /** + * If the authentication mechanism is set to "default", resolves the authMechanism + * based on the server version and server supported sasl mechanisms. + * + * @param hello - A hello response from the server + */ + resolveAuthMechanism(hello) { + // If the mechanism is not "default", then it does not need to be resolved + if (this.mechanism.match(/DEFAULT/i)) { + return new MongoCredentials({ + username: this.username, + password: this.password, + source: this.source, + mechanism: getDefaultAuthMechanism(hello), + mechanismProperties: this.mechanismProperties + }); + } + return this; + } + validate() { + var _a; + if ((this.mechanism === providers_1.AuthMechanism.MONGODB_GSSAPI || + this.mechanism === providers_1.AuthMechanism.MONGODB_CR || + this.mechanism === providers_1.AuthMechanism.MONGODB_PLAIN || + this.mechanism === providers_1.AuthMechanism.MONGODB_SCRAM_SHA1 || + this.mechanism === providers_1.AuthMechanism.MONGODB_SCRAM_SHA256) && + !this.username) { + throw new error_1.MongoMissingCredentialsError(`Username required for mechanism '${this.mechanism}'`); + } + if (providers_1.AUTH_MECHS_AUTH_SRC_EXTERNAL.has(this.mechanism)) { + if (this.source != null && this.source !== '$external') { + // TODO(NODE-3485): Replace this with a MongoAuthValidationError + throw new error_1.MongoAPIError(`Invalid source '${this.source}' for mechanism '${this.mechanism}' specified.`); + } + } + if (this.mechanism === providers_1.AuthMechanism.MONGODB_PLAIN && this.source == null) { + // TODO(NODE-3485): Replace this with a MongoAuthValidationError + throw new error_1.MongoAPIError('PLAIN Authentication Mechanism needs an auth source'); + } + if (this.mechanism === providers_1.AuthMechanism.MONGODB_X509 && this.password != null) { + if (this.password === '') { + Reflect.set(this, 'password', undefined); + return; + } + // TODO(NODE-3485): Replace this with a MongoAuthValidationError + throw new error_1.MongoAPIError(`Password not allowed for mechanism MONGODB-X509`); + } + const canonicalization = (_a = this.mechanismProperties.CANONICALIZE_HOST_NAME) !== null && _a !== void 0 ? _a : false; + if (!Object.values(gssapi_1.GSSAPICanonicalizationValue).includes(canonicalization)) { + throw new error_1.MongoAPIError(`Invalid CANONICALIZE_HOST_NAME value: ${canonicalization}`); + } + } + static merge(creds, options) { + var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l; + return new MongoCredentials({ + username: (_b = (_a = options.username) !== null && _a !== void 0 ? _a : creds === null || creds === void 0 ? void 0 : creds.username) !== null && _b !== void 0 ? _b : '', + password: (_d = (_c = options.password) !== null && _c !== void 0 ? _c : creds === null || creds === void 0 ? void 0 : creds.password) !== null && _d !== void 0 ? _d : '', + mechanism: (_f = (_e = options.mechanism) !== null && _e !== void 0 ? _e : creds === null || creds === void 0 ? void 0 : creds.mechanism) !== null && _f !== void 0 ? _f : providers_1.AuthMechanism.MONGODB_DEFAULT, + mechanismProperties: (_h = (_g = options.mechanismProperties) !== null && _g !== void 0 ? _g : creds === null || creds === void 0 ? void 0 : creds.mechanismProperties) !== null && _h !== void 0 ? _h : {}, + source: (_l = (_k = (_j = options.source) !== null && _j !== void 0 ? _j : options.db) !== null && _k !== void 0 ? _k : creds === null || creds === void 0 ? void 0 : creds.source) !== null && _l !== void 0 ? _l : 'admin' + }); + } +} +exports.MongoCredentials = MongoCredentials; +//# sourceMappingURL=mongo_credentials.js.map \ No newline at end of file diff --git a/ts-ticket-office-service/node_modules/mongodb/lib/cmap/auth/mongo_credentials.js.map b/ts-ticket-office-service/node_modules/mongodb/lib/cmap/auth/mongo_credentials.js.map new file mode 100644 index 000000000..3f88b0fe6 --- /dev/null +++ b/ts-ticket-office-service/node_modules/mongodb/lib/cmap/auth/mongo_credentials.js.map @@ -0,0 +1 @@ +{"version":3,"file":"mongo_credentials.js","sourceRoot":"","sources":["../../../src/cmap/auth/mongo_credentials.ts"],"names":[],"mappings":";;;AAEA,uCAA0E;AAC1E,uCAA8C;AAC9C,qCAAuD;AACvD,2CAA0E;AAE1E,6EAA6E;AAC7E,SAAS,uBAAuB,CAAC,KAAgB;IAC/C,IAAI,KAAK,EAAE;QACT,0DAA0D;QAC1D,uCAAuC;QACvC,IAAI,KAAK,CAAC,OAAO,CAAC,KAAK,CAAC,kBAAkB,CAAC,EAAE;YAC3C,OAAO,KAAK,CAAC,kBAAkB,CAAC,QAAQ,CAAC,yBAAa,CAAC,oBAAoB,CAAC;gBAC1E,CAAC,CAAC,yBAAa,CAAC,oBAAoB;gBACpC,CAAC,CAAC,yBAAa,CAAC,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AE;YAC1E,MAAM,IAAI,qBAAa,CAAC,yCAAyC,gBAAgB,EAAE,CAAC,CAAC;SACtF;IACH,CAAC;IAED,MAAM,CAAC,KAAK,CACV,KAAmC,EACnC,OAAyC;;QAEzC,OAAO,IAAI,gBAAgB,CAAC;YAC1B,QAAQ,EAAE,MAAA,MAAA,OAAO,CAAC,QAAQ,mCAAI,KAAK,aAAL,KAAK,uBAAL,KAAK,CAAE,QAAQ,mCAAI,EAAE;YACnD,QAAQ,EAAE,MAAA,MAAA,OAAO,CAAC,QAAQ,mCAAI,KAAK,aAAL,KAAK,uBAAL,KAAK,CAAE,QAAQ,mCAAI,EAAE;YACnD,SAAS,EAAE,MAAA,MAAA,OAAO,CAAC,SAAS,mCAAI,KAAK,aAAL,KAAK,uBAAL,KAAK,CAAE,SAAS,mCAAI,yBAAa,CAAC,eAAe;YACjF,mBAAmB,EAAE,MAAA,MAAA,OAAO,CAAC,mBAAmB,mCAAI,KAAK,aAAL,KAAK,uBAAL,KAAK,CAAE,mBAAmB,mCAAI,EAAE;YACpF,MAAM,EAAE,MAAA,MAAA,MAAA,OAAO,CAAC,MAAM,mCAAI,OAAO,CAAC,EAAE,mCAAI,KAAK,aAAL,KAAK,uBAAL,KAAK,CAAE,MAAM,mCAAI,OAAO;SACjE,CAAC,CAAC;IACL,CAAC;CACF;AA1ID,4CA0IC"} \ No newline at end of file diff --git a/ts-ticket-office-service/node_modules/mongodb/lib/cmap/auth/mongocr.js b/ts-ticket-office-service/node_modules/mongodb/lib/cmap/auth/mongocr.js new file mode 100644 index 000000000..f8afea2dd --- /dev/null +++ b/ts-ticket-office-service/node_modules/mongodb/lib/cmap/auth/mongocr.js @@ -0,0 +1,44 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.MongoCR = void 0; +const crypto = require("crypto"); +const error_1 = require("../../error"); +const utils_1 = require("../../utils"); +const auth_provider_1 = require("./auth_provider"); +class MongoCR extends auth_provider_1.AuthProvider { + auth(authContext, callback) { + const { connection, credentials } = authContext; + if (!credentials) { + return callback(new error_1.MongoMissingCredentialsError('AuthContext must provide credentials.')); + } + const username = credentials.username; + const password = credentials.password; + const source = credentials.source; + connection.command((0, utils_1.ns)(`${source}.$cmd`), { getnonce: 1 }, undefined, (err, r) => { + let nonce = null; + let key = null; + // Get nonce + if (err == null) { + nonce = r.nonce; + // Use node md5 generator + let md5 = crypto.createHash('md5'); + // Generate keys used for authentication + md5.update(`${username}:mongo:${password}`, 'utf8'); + const hash_password = md5.digest('hex'); + // Final key + md5 = crypto.createHash('md5'); + md5.update(nonce + username + hash_password, 'utf8'); + key = md5.digest('hex'); + } + const authenticateCommand = { + authenticate: 1, + user: username, + nonce, + key + }; + connection.command((0, utils_1.ns)(`${source}.$cmd`), authenticateCommand, undefined, callback); + }); + } +} +exports.MongoCR = MongoCR; +//# sourceMappingURL=mongocr.js.map \ No newline at end of file diff --git a/ts-ticket-office-service/node_modules/mongodb/lib/cmap/auth/mongocr.js.map b/ts-ticket-office-service/node_modules/mongodb/lib/cmap/auth/mongocr.js.map new file mode 100644 index 000000000..62e4f9796 --- /dev/null +++ b/ts-ticket-office-service/node_modules/mongodb/lib/cmap/auth/mongocr.js.map @@ -0,0 +1 @@ +{"version":3,"file":"mongocr.js","sourceRoot":"","sources":["../../../src/cmap/auth/mongocr.ts"],"names":[],"mappings":";;;AAAA,iCAAiC;AAEjC,uCAA2D;AAC3D,uCAA2C;AAC3C,mDAA4D;AAE5D,MAAa,OAAQ,SAAQ,4BAAY;IAC9B,IAAI,CAAC,WAAwB,EAAE,QAAkB;QACxD,MAAM,EAAE,UAAU,EAAE,WAAW,EAAE,GAAG,WAAW,CAAC;QAChD,IAAI,CAAC,WAAW,EAAE;YAChB,OAAO,QAAQ,CAAC,IAAI,oCAA4B,CAAC,uCAAuC,CAAC,CAAC,CAAC;SAC5F;QACD,MAAM,QAAQ,GAAG,WAAW,CAAC,QAAQ,CAAC;QACtC,MAAM,QAAQ,GAAG,WAAW,CAAC,QAAQ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ts-ticket-office-service/node_modules/mongodb/lib/cmap/auth/mongodb_aws.js new file mode 100644 index 000000000..ba0679fd1 --- /dev/null +++ b/ts-ticket-office-service/node_modules/mongodb/lib/cmap/auth/mongodb_aws.js @@ -0,0 +1,204 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.MongoDBAWS = void 0; +const crypto = require("crypto"); +const http = require("http"); +const url = require("url"); +const BSON = require("../../bson"); +const deps_1 = require("../../deps"); +const error_1 = require("../../error"); +const utils_1 = require("../../utils"); +const auth_provider_1 = require("./auth_provider"); +const mongo_credentials_1 = require("./mongo_credentials"); +const providers_1 = require("./providers"); +const ASCII_N = 110; +const AWS_RELATIVE_URI = 'http://169.254.170.2'; +const AWS_EC2_URI = 'http://169.254.169.254'; +const AWS_EC2_PATH = '/latest/meta-data/iam/security-credentials'; +const bsonOptions = { + promoteLongs: true, + promoteValues: true, + promoteBuffers: false, + bsonRegExp: false +}; +class MongoDBAWS extends auth_provider_1.AuthProvider { + auth(authContext, callback) { + const { connection, credentials } = authContext; + if (!credentials) { + return callback(new error_1.MongoMissingCredentialsError('AuthContext must provide credentials.')); + } + if ('kModuleError' in deps_1.aws4) { + return callback(deps_1.aws4['kModuleError']); + } + const { sign } = deps_1.aws4; + if ((0, utils_1.maxWireVersion)(connection) < 9) { + callback(new error_1.MongoCompatibilityError('MONGODB-AWS authentication requires MongoDB version 4.4 or later')); + return; + } + if (!credentials.username) { + makeTempCredentials(credentials, (err, tempCredentials) => { + if (err || !tempCredentials) + return callback(err); + authContext.credentials = tempCredentials; + this.auth(authContext, callback); + }); + return; + } + const accessKeyId = credentials.username; + const secretAccessKey = credentials.password; + const sessionToken = credentials.mechanismProperties.AWS_SESSION_TOKEN; + // If all three defined, include sessionToken, else include username and pass, else no credentials + const awsCredentials = accessKeyId && secretAccessKey && sessionToken + ? { accessKeyId, secretAccessKey, sessionToken } + : accessKeyId && secretAccessKey + ? { accessKeyId, secretAccessKey } + : undefined; + const db = credentials.source; + crypto.randomBytes(32, (err, nonce) => { + if (err) { + callback(err); + return; + } + const saslStart = { + saslStart: 1, + mechanism: 'MONGODB-AWS', + payload: BSON.serialize({ r: nonce, p: ASCII_N }, bsonOptions) + }; + connection.command((0, utils_1.ns)(`${db}.$cmd`), saslStart, undefined, (err, res) => { + if (err) + return callback(err); + const serverResponse = BSON.deserialize(res.payload.buffer, bsonOptions); + const host = serverResponse.h; + const serverNonce = serverResponse.s.buffer; + if (serverNonce.length !== 64) { + callback( + // TODO(NODE-3483) + new error_1.MongoRuntimeError(`Invalid server nonce length ${serverNonce.length}, expected 64`)); + return; + } + if (serverNonce.compare(nonce, 0, nonce.length, 0, nonce.length) !== 0) { + // TODO(NODE-3483) + callback(new error_1.MongoRuntimeError('Server nonce does not begin with client nonce')); + return; + } + if (host.length < 1 || host.length > 255 || host.indexOf('..') !== -1) { + // TODO(NODE-3483) + callback(new error_1.MongoRuntimeError(`Server returned an invalid host: "${host}"`)); + return; + } + const body = 'Action=GetCallerIdentity&Version=2011-06-15'; + const options = sign({ + method: 'POST', + host, + region: deriveRegion(serverResponse.h), + service: 'sts', + headers: { + 'Content-Type': 'application/x-www-form-urlencoded', + 'Content-Length': body.length, + 'X-MongoDB-Server-Nonce': serverNonce.toString('base64'), + 'X-MongoDB-GS2-CB-Flag': 'n' + }, + path: '/', + body + }, awsCredentials); + const payload = { + a: options.headers.Authorization, + d: options.headers['X-Amz-Date'] + }; + if (sessionToken) { + payload.t = sessionToken; + } + const saslContinue = { + saslContinue: 1, + conversationId: 1, + payload: BSON.serialize(payload, bsonOptions) + }; + connection.command((0, utils_1.ns)(`${db}.$cmd`), saslContinue, undefined, callback); + }); + }); + } +} +exports.MongoDBAWS = MongoDBAWS; +function makeTempCredentials(credentials, callback) { + function done(creds) { + if (!creds.AccessKeyId || !creds.SecretAccessKey || !creds.Token) { + callback(new error_1.MongoMissingCredentialsError('Could not obtain temporary MONGODB-AWS credentials')); + return; + } + callback(undefined, new mongo_credentials_1.MongoCredentials({ + username: creds.AccessKeyId, + password: creds.SecretAccessKey, + source: credentials.source, + mechanism: providers_1.AuthMechanism.MONGODB_AWS, + mechanismProperties: { + AWS_SESSION_TOKEN: creds.Token + } + })); + } + // If the environment variable AWS_CONTAINER_CREDENTIALS_RELATIVE_URI + // is set then drivers MUST assume that it was set by an AWS ECS agent + if (process.env.AWS_CONTAINER_CREDENTIALS_RELATIVE_URI) { + request(`${AWS_RELATIVE_URI}${process.env.AWS_CONTAINER_CREDENTIALS_RELATIVE_URI}`, undefined, (err, res) => { + if (err) + return callback(err); + done(res); + }); + return; + } + // Otherwise assume we are on an EC2 instance + // get a token + request(`${AWS_EC2_URI}/latest/api/token`, { method: 'PUT', json: false, headers: { 'X-aws-ec2-metadata-token-ttl-seconds': 30 } }, (err, token) => { + if (err) + return callback(err); + // get role name + request(`${AWS_EC2_URI}/${AWS_EC2_PATH}`, { json: false, headers: { 'X-aws-ec2-metadata-token': token } }, (err, roleName) => { + if (err) + return callback(err); + // get temp credentials + request(`${AWS_EC2_URI}/${AWS_EC2_PATH}/${roleName}`, { headers: { 'X-aws-ec2-metadata-token': token } }, (err, creds) => { + if (err) + return callback(err); + done(creds); + }); + }); + }); +} +function deriveRegion(host) { + const parts = host.split('.'); + if (parts.length === 1 || parts[1] === 'amazonaws') { + return 'us-east-1'; + } + return parts[1]; +} +function request(uri, _options, callback) { + const options = Object.assign({ + method: 'GET', + timeout: 10000, + json: true + }, url.parse(uri), _options); + const req = http.request(options, res => { + res.setEncoding('utf8'); + let data = ''; + res.on('data', d => (data += d)); + res.on('end', () => { + if (options.json === false) { + callback(undefined, data); + return; + } + try { + const parsed = JSON.parse(data); + callback(undefined, parsed); + } + catch (err) { + // TODO(NODE-3483) + callback(new error_1.MongoRuntimeError(`Invalid JSON response: "${data}"`)); + } + }); + }); + req.on('timeout', () => { + req.destroy(new error_1.MongoAWSError(`AWS request to ${uri} timed out after ${options.timeout} ms`)); + }); + req.on('error', err => callback(err)); + req.end(); +} +//# sourceMappingURL=mongodb_aws.js.map \ No newline at end of file diff --git a/ts-ticket-office-service/node_modules/mongodb/lib/cmap/auth/mongodb_aws.js.map b/ts-ticket-office-service/node_modules/mongodb/lib/cmap/auth/mongodb_aws.js.map new file mode 100644 index 000000000..f88f08b05 --- /dev/null +++ b/ts-ticket-office-service/node_modules/mongodb/lib/cmap/auth/mongodb_aws.js.map @@ -0,0 +1 @@ +{"version":3,"file":"mongodb_aws.js","sourceRoot":"","sources":["../../../src/cmap/auth/mongodb_aws.ts"],"names":[],"mappings":";;;AAAA,iCAAiC;AACjC,6BAA6B;AAC7B,2BAA2B;AAG3B,mCAAmC;AACnC,qCAAkC;AAClC,uCAKqB;AACrB,uCAA2D;AAC3D,mDAA4D;AAC5D,2DAAuD;AACvD,2CAA4C;AAE5C,MAAM,OAAO,GAAG,GAAG,CAAC;AACpB,MAAM,gBAAgB,GAAG,sBAAsB,CAAC;AAChD,MAAM,WAAW,GAAG,wBAAwB,CAAC;AAC7C,MAAM,YAAY,GAAG,4CAA4C,CAAC;AAClE,MAAM,WAAW,GAAyB;IACxC,YAAY,EAAE,IAAI;IAClB,aAAa,EAAE,IAAI;IACnB,cAAc,EAAE,KAAK;IACrB,UAAU,EAAE,KAAK;CAClB,CAAC;AAQF,MAAa,UAAW,SAAQ,4BAAY;IACjC,IAAI,CAAC,WAAwB,EAAE,QAAkB;QACxD,MAAM,EAAE,UAAU,EAAE,WAAW,EAAE,GAAG,WAAW,CAAC;QAChD,IAAI,CAAC,WAAW,EAAE;YAChB,OAAO,QAAQ,CAAC,IAAI,oCAA4B,CAAC,uCAAuC,CAAC,CAAC,CAAC;SAC5F;QAED,IAAI,cAAc,IAAI,WAAI,EAAE;YAC1B,OAAO,QAAQ,CAAC,WAAI,CAAC,cAAc,CAAC,CAAC,CAAC;SACvC;QACD,MAAM,EAAE,IAAI,EAAE,GAAG,WAAI,CAAC;QAEtB,IAAI,IAAA,sBAAc,EAAC,UAAU,CAAC,GAAG,CAAC,EAAE;YAClC,QAAQ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AAI,CAAC,CAAC;gBAChC,QAAQ,CAAC,SAAS,EAAE,MAAM,CAAC,CAAC;aAC7B;YAAC,OAAO,GAAG,EAAE;gBACZ,kBAAkB;gBAClB,QAAQ,CAAC,IAAI,yBAAiB,CAAC,2BAA2B,IAAI,GAAG,CAAC,CAAC,CAAC;aACrE;QACH,CAAC,CAAC,CAAC;IACL,CAAC,CAAC,CAAC;IAEH,GAAG,CAAC,EAAE,CAAC,SAAS,EAAE,GAAG,EAAE;QACrB,GAAG,CAAC,OAAO,CAAC,IAAI,qBAAa,CAAC,kBAAkB,GAAG,oBAAoB,OAAO,CAAC,OAAO,KAAK,CAAC,CAAC,CAAC;IAChG,CAAC,CAAC,CAAC;IAEH,GAAG,CAAC,EAAE,CAAC,OAAO,EAAE,GAAG,CAAC,EAAE,CAAC,QAAQ,CAAC,GAAG,CAAC,CAAC,CAAC;IACtC,GAAG,CAAC,GAAG,EAAE,CAAC;AACZ,CAAC"} \ No newline at end of file diff --git a/ts-ticket-office-service/node_modules/mongodb/lib/cmap/auth/plain.js b/ts-ticket-office-service/node_modules/mongodb/lib/cmap/auth/plain.js new file mode 100644 index 000000000..e7153a58c --- /dev/null +++ b/ts-ticket-office-service/node_modules/mongodb/lib/cmap/auth/plain.js @@ -0,0 +1,27 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.Plain = void 0; +const bson_1 = require("../../bson"); +const error_1 = require("../../error"); +const utils_1 = require("../../utils"); +const auth_provider_1 = require("./auth_provider"); +class Plain extends auth_provider_1.AuthProvider { + auth(authContext, callback) { + const { connection, credentials } = authContext; + if (!credentials) { + return callback(new error_1.MongoMissingCredentialsError('AuthContext must provide credentials.')); + } + const username = credentials.username; + const password = credentials.password; + const payload = new bson_1.Binary(Buffer.from(`\x00${username}\x00${password}`)); + const command = { + saslStart: 1, + mechanism: 'PLAIN', + payload: payload, + autoAuthorize: 1 + }; + connection.command((0, utils_1.ns)('$external.$cmd'), command, undefined, callback); + } +} +exports.Plain = Plain; +//# sourceMappingURL=plain.js.map \ No newline at end of file diff --git a/ts-ticket-office-service/node_modules/mongodb/lib/cmap/auth/plain.js.map b/ts-ticket-office-service/node_modules/mongodb/lib/cmap/auth/plain.js.map new file mode 100644 index 000000000..a03580a35 --- /dev/null +++ b/ts-ticket-office-service/node_modules/mongodb/lib/cmap/auth/plain.js.map @@ -0,0 +1 @@ +{"version":3,"file":"plain.js","sourceRoot":"","sources":["../../../src/cmap/auth/plain.ts"],"names":[],"mappings":";;;AAAA,qCAAoC;AACpC,uCAA2D;AAC3D,uCAA2C;AAC3C,mDAA4D;AAE5D,MAAa,KAAM,SAAQ,4BAAY;IAC5B,IAAI,CAAC,WAAwB,EAAE,QAAkB;QACxD,MAAM,EAAE,UAAU,EAAE,WAAW,EAAE,GAAG,WAAW,CAAC;QAChD,IAAI,CAAC,WAAW,EAAE;YAChB,OAAO,QAAQ,CAAC,IAAI,oCAA4B,CAAC,uCAAuC,CAAC,CAAC,CAAC;SAC5F;QACD,MAAM,QAAQ,GAAG,WAAW,CAAC,QAAQ,CAAC;QACtC,MAAM,QAAQ,GAAG,WAAW,CAAC,QAAQ,CAAC;QAEtC,MAAM,OAAO,GAAG,IAAI,aAAM,CAAC,MAAM,CAAC,IAAI,CAAC,OAAO,QAAQ,OAAO,QAAQ,EAAE,CAAC,CAAC,CAAC;QAC1E,MAAM,OAAO,GAAG;YACd,SAAS,EAAE,CAAC;YACZ,SAAS,EAAE,OAAO;YAClB,OAAO,EAAE,OAAO;YAChB,aAAa,EAAE,CAAC;SACjB,CAAC;QAEF,UAAU,CAAC,OAAO,CAAC,IAAA,UAAE,EAAC,gBAAgB,CAAC,EAAE,OAAO,EAAE,SAAS,EAAE,QAAQ,CAAC,CAAC;IACzE,CAAC;CACF;AAnBD,sBAmBC"} \ No newline at end of file diff --git a/ts-ticket-office-service/node_modules/mongodb/lib/cmap/auth/providers.js b/ts-ticket-office-service/node_modules/mongodb/lib/cmap/auth/providers.js new file mode 100644 index 000000000..d287765f0 --- /dev/null +++ b/ts-ticket-office-service/node_modules/mongodb/lib/cmap/auth/providers.js @@ -0,0 +1,21 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.AUTH_MECHS_AUTH_SRC_EXTERNAL = exports.AuthMechanism = void 0; +/** @public */ +exports.AuthMechanism = Object.freeze({ + MONGODB_AWS: 'MONGODB-AWS', + MONGODB_CR: 'MONGODB-CR', + MONGODB_DEFAULT: 'DEFAULT', + MONGODB_GSSAPI: 'GSSAPI', + MONGODB_PLAIN: 'PLAIN', + MONGODB_SCRAM_SHA1: 'SCRAM-SHA-1', + MONGODB_SCRAM_SHA256: 'SCRAM-SHA-256', + MONGODB_X509: 'MONGODB-X509' +}); +/** @internal */ +exports.AUTH_MECHS_AUTH_SRC_EXTERNAL = new Set([ + exports.AuthMechanism.MONGODB_GSSAPI, + exports.AuthMechanism.MONGODB_AWS, + exports.AuthMechanism.MONGODB_X509 +]); +//# sourceMappingURL=providers.js.map \ No newline at end of file diff --git a/ts-ticket-office-service/node_modules/mongodb/lib/cmap/auth/providers.js.map b/ts-ticket-office-service/node_modules/mongodb/lib/cmap/auth/providers.js.map new file mode 100644 index 000000000..48b58e79e --- /dev/null +++ b/ts-ticket-office-service/node_modules/mongodb/lib/cmap/auth/providers.js.map @@ -0,0 +1 @@ +{"version":3,"file":"providers.js","sourceRoot":"","sources":["../../../src/cmap/auth/providers.ts"],"names":[],"mappings":";;;AAAA,cAAc;AACD,QAAA,aAAa,GAAG,MAAM,CAAC,MAAM,CAAC;IACzC,WAAW,EAAE,aAAa;IAC1B,UAAU,EAAE,YAAY;IACxB,eAAe,EAAE,SAAS;IAC1B,cAAc,EAAE,QAAQ;IACxB,aAAa,EAAE,OAAO;IACtB,kBAAkB,EAAE,aAAa;IACjC,oBAAoB,EAAE,eAAe;IACrC,YAAY,EAAE,cAAc;CACpB,CAAC,CAAC;AAKZ,gBAAgB;AACH,QAAA,4BAA4B,GAAG,IAAI,GAAG,CAAgB;IACjE,qBAAa,CAAC,cAAc;IAC5B,qBAAa,CAAC,WAAW;IACzB,qBAAa,CAAC,YAAY;CAC3B,CAAC,CAAC"} \ No newline at end of file diff --git a/ts-ticket-office-service/node_modules/mongodb/lib/cmap/auth/scram.js b/ts-ticket-office-service/node_modules/mongodb/lib/cmap/auth/scram.js new file mode 100644 index 000000000..00a77ac00 --- /dev/null +++ b/ts-ticket-office-service/node_modules/mongodb/lib/cmap/auth/scram.js @@ -0,0 +1,288 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.ScramSHA256 = exports.ScramSHA1 = void 0; +const crypto = require("crypto"); +const bson_1 = require("../../bson"); +const deps_1 = require("../../deps"); +const error_1 = require("../../error"); +const utils_1 = require("../../utils"); +const auth_provider_1 = require("./auth_provider"); +const providers_1 = require("./providers"); +class ScramSHA extends auth_provider_1.AuthProvider { + constructor(cryptoMethod) { + super(); + this.cryptoMethod = cryptoMethod || 'sha1'; + } + prepare(handshakeDoc, authContext, callback) { + const cryptoMethod = this.cryptoMethod; + const credentials = authContext.credentials; + if (!credentials) { + return callback(new error_1.MongoMissingCredentialsError('AuthContext must provide credentials.')); + } + if (cryptoMethod === 'sha256' && deps_1.saslprep == null) { + (0, utils_1.emitWarning)('Warning: no saslprep library specified. Passwords will not be sanitized'); + } + crypto.randomBytes(24, (err, nonce) => { + if (err) { + return callback(err); + } + // store the nonce for later use + Object.assign(authContext, { nonce }); + const request = Object.assign({}, handshakeDoc, { + speculativeAuthenticate: Object.assign(makeFirstMessage(cryptoMethod, credentials, nonce), { + db: credentials.source + }) + }); + callback(undefined, request); + }); + } + auth(authContext, callback) { + const response = authContext.response; + if (response && response.speculativeAuthenticate) { + continueScramConversation(this.cryptoMethod, response.speculativeAuthenticate, authContext, callback); + return; + } + executeScram(this.cryptoMethod, authContext, callback); + } +} +function cleanUsername(username) { + return username.replace('=', '=3D').replace(',', '=2C'); +} +function clientFirstMessageBare(username, nonce) { + // NOTE: This is done b/c Javascript uses UTF-16, but the server is hashing in UTF-8. + // Since the username is not sasl-prep-d, we need to do this here. + return Buffer.concat([ + Buffer.from('n=', 'utf8'), + Buffer.from(username, 'utf8'), + Buffer.from(',r=', 'utf8'), + Buffer.from(nonce.toString('base64'), 'utf8') + ]); +} +function makeFirstMessage(cryptoMethod, credentials, nonce) { + const username = cleanUsername(credentials.username); + const mechanism = cryptoMethod === 'sha1' ? providers_1.AuthMechanism.MONGODB_SCRAM_SHA1 : providers_1.AuthMechanism.MONGODB_SCRAM_SHA256; + // NOTE: This is done b/c Javascript uses UTF-16, but the server is hashing in UTF-8. + // Since the username is not sasl-prep-d, we need to do this here. + return { + saslStart: 1, + mechanism, + payload: new bson_1.Binary(Buffer.concat([Buffer.from('n,,', 'utf8'), clientFirstMessageBare(username, nonce)])), + autoAuthorize: 1, + options: { skipEmptyExchange: true } + }; +} +function executeScram(cryptoMethod, authContext, callback) { + const { connection, credentials } = authContext; + if (!credentials) { + return callback(new error_1.MongoMissingCredentialsError('AuthContext must provide credentials.')); + } + if (!authContext.nonce) { + return callback(new error_1.MongoInvalidArgumentError('AuthContext must contain a valid nonce property')); + } + const nonce = authContext.nonce; + const db = credentials.source; + const saslStartCmd = makeFirstMessage(cryptoMethod, credentials, nonce); + connection.command((0, utils_1.ns)(`${db}.$cmd`), saslStartCmd, undefined, (_err, result) => { + const err = resolveError(_err, result); + if (err) { + return callback(err); + } + continueScramConversation(cryptoMethod, result, authContext, callback); + }); +} +function continueScramConversation(cryptoMethod, response, authContext, callback) { + const connection = authContext.connection; + const credentials = authContext.credentials; + if (!credentials) { + return callback(new error_1.MongoMissingCredentialsError('AuthContext must provide credentials.')); + } + if (!authContext.nonce) { + return callback(new error_1.MongoInvalidArgumentError('Unable to continue SCRAM without valid nonce')); + } + const nonce = authContext.nonce; + const db = credentials.source; + const username = cleanUsername(credentials.username); + const password = credentials.password; + let processedPassword; + if (cryptoMethod === 'sha256') { + processedPassword = 'kModuleError' in deps_1.saslprep ? password : (0, deps_1.saslprep)(password); + } + else { + try { + processedPassword = passwordDigest(username, password); + } + catch (e) { + return callback(e); + } + } + const payload = Buffer.isBuffer(response.payload) + ? new bson_1.Binary(response.payload) + : response.payload; + const dict = parsePayload(payload.value()); + const iterations = parseInt(dict.i, 10); + if (iterations && iterations < 4096) { + callback( + // TODO(NODE-3483) + new error_1.MongoRuntimeError(`Server returned an invalid iteration count ${iterations}`), false); + return; + } + const salt = dict.s; + const rnonce = dict.r; + if (rnonce.startsWith('nonce')) { + // TODO(NODE-3483) + callback(new error_1.MongoRuntimeError(`Server returned an invalid nonce: ${rnonce}`), false); + return; + } + // Set up start of proof + const withoutProof = `c=biws,r=${rnonce}`; + const saltedPassword = HI(processedPassword, Buffer.from(salt, 'base64'), iterations, cryptoMethod); + const clientKey = HMAC(cryptoMethod, saltedPassword, 'Client Key'); + const serverKey = HMAC(cryptoMethod, saltedPassword, 'Server Key'); + const storedKey = H(cryptoMethod, clientKey); + const authMessage = [clientFirstMessageBare(username, nonce), payload.value(), withoutProof].join(','); + const clientSignature = HMAC(cryptoMethod, storedKey, authMessage); + const clientProof = `p=${xor(clientKey, clientSignature)}`; + const clientFinal = [withoutProof, clientProof].join(','); + const serverSignature = HMAC(cryptoMethod, serverKey, authMessage); + const saslContinueCmd = { + saslContinue: 1, + conversationId: response.conversationId, + payload: new bson_1.Binary(Buffer.from(clientFinal)) + }; + connection.command((0, utils_1.ns)(`${db}.$cmd`), saslContinueCmd, undefined, (_err, r) => { + const err = resolveError(_err, r); + if (err) { + return callback(err); + } + const parsedResponse = parsePayload(r.payload.value()); + if (!compareDigest(Buffer.from(parsedResponse.v, 'base64'), serverSignature)) { + callback(new error_1.MongoRuntimeError('Server returned an invalid signature')); + return; + } + if (!r || r.done !== false) { + return callback(err, r); + } + const retrySaslContinueCmd = { + saslContinue: 1, + conversationId: r.conversationId, + payload: Buffer.alloc(0) + }; + connection.command((0, utils_1.ns)(`${db}.$cmd`), retrySaslContinueCmd, undefined, callback); + }); +} +function parsePayload(payload) { + const dict = {}; + const parts = payload.split(','); + for (let i = 0; i < parts.length; i++) { + const valueParts = parts[i].split('='); + dict[valueParts[0]] = valueParts[1]; + } + return dict; +} +function passwordDigest(username, password) { + if (typeof username !== 'string') { + throw new error_1.MongoInvalidArgumentError('Username must be a string'); + } + if (typeof password !== 'string') { + throw new error_1.MongoInvalidArgumentError('Password must be a string'); + } + if (password.length === 0) { + throw new error_1.MongoInvalidArgumentError('Password cannot be empty'); + } + let md5; + try { + md5 = crypto.createHash('md5'); + } + catch (err) { + if (crypto.getFips()) { + // This error is (slightly) more helpful than what comes from OpenSSL directly, e.g. + // 'Error: error:060800C8:digital envelope routines:EVP_DigestInit_ex:disabled for FIPS' + throw new Error('Auth mechanism SCRAM-SHA-1 is not supported in FIPS mode'); + } + throw err; + } + md5.update(`${username}:mongo:${password}`, 'utf8'); + return md5.digest('hex'); +} +// XOR two buffers +function xor(a, b) { + if (!Buffer.isBuffer(a)) { + a = Buffer.from(a); + } + if (!Buffer.isBuffer(b)) { + b = Buffer.from(b); + } + const length = Math.max(a.length, b.length); + const res = []; + for (let i = 0; i < length; i += 1) { + res.push(a[i] ^ b[i]); + } + return Buffer.from(res).toString('base64'); +} +function H(method, text) { + return crypto.createHash(method).update(text).digest(); +} +function HMAC(method, key, text) { + return crypto.createHmac(method, key).update(text).digest(); +} +let _hiCache = {}; +let _hiCacheCount = 0; +function _hiCachePurge() { + _hiCache = {}; + _hiCacheCount = 0; +} +const hiLengthMap = { + sha256: 32, + sha1: 20 +}; +function HI(data, salt, iterations, cryptoMethod) { + // omit the work if already generated + const key = [data, salt.toString('base64'), iterations].join('_'); + if (_hiCache[key] != null) { + return _hiCache[key]; + } + // generate the salt + const saltedData = crypto.pbkdf2Sync(data, salt, iterations, hiLengthMap[cryptoMethod], cryptoMethod); + // cache a copy to speed up the next lookup, but prevent unbounded cache growth + if (_hiCacheCount >= 200) { + _hiCachePurge(); + } + _hiCache[key] = saltedData; + _hiCacheCount += 1; + return saltedData; +} +function compareDigest(lhs, rhs) { + if (lhs.length !== rhs.length) { + return false; + } + if (typeof crypto.timingSafeEqual === 'function') { + return crypto.timingSafeEqual(lhs, rhs); + } + let result = 0; + for (let i = 0; i < lhs.length; i++) { + result |= lhs[i] ^ rhs[i]; + } + return result === 0; +} +function resolveError(err, result) { + if (err) + return err; + if (result) { + if (result.$err || result.errmsg) + return new error_1.MongoServerError(result); + } + return; +} +class ScramSHA1 extends ScramSHA { + constructor() { + super('sha1'); + } +} +exports.ScramSHA1 = ScramSHA1; +class ScramSHA256 extends ScramSHA { + constructor() { + super('sha256'); + } +} +exports.ScramSHA256 = ScramSHA256; +//# sourceMappingURL=scram.js.map \ No newline at end of file diff --git a/ts-ticket-office-service/node_modules/mongodb/lib/cmap/auth/scram.js.map b/ts-ticket-office-service/node_modules/mongodb/lib/cmap/auth/scram.js.map new file mode 100644 index 000000000..c94940db2 --- /dev/null +++ b/ts-ticket-office-service/node_modules/mongodb/lib/cmap/auth/scram.js.map @@ -0,0 +1 @@ +{"version":3,"file":"scram.js","sourceRoot":"","sources":["../../../src/cmap/auth/scram.ts"],"names":[],"mappings":";;;AAAA,iCAAiC;AAEjC,qCAA8C;AAC9C,qCAAsC;AACtC,uCAMqB;AACrB,uCAAwD;AAExD,mDAA4D;AAE5D,2CAA4C;AAI5C,MAAM,QAAS,SAAQ,4BAAY;IAEjC,YAAY,YAA0B;QACpC,KAAK,EAAE,CAAC;QACR,IAAI,CAAC,YAAY,GAAG,YAAY,IAAI,MAAM,CAAC;IAC7C,CAAC;IAEQ,OAAO,CAAC,YAA+B,EAAE,WAAwB,EAAE,QAAkB;QAC5F,MAAM,YAAY,GAAG,IAAI,CAAC,YAAY,CAAC;QACvC,MAAM,WAAW,GAAG,WAAW,CAAC,WAAW,CAAC;QAC5C,IAAI,CAAC,WAAW,EAAE;YAChB,OAAO,QAAQ,CAAC,IAAI,oCAA4B,CAAC,uCAAuC,CAAC,CAAC,CAAC;SAC5F;QACD,IAAI,YAAY,KAAK,QAAQ,IA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-service/node_modules/mongodb/lib/cmap/auth/x509.js b/ts-ticket-office-service/node_modules/mongodb/lib/cmap/auth/x509.js new file mode 100644 index 000000000..02fe38539 --- /dev/null +++ b/ts-ticket-office-service/node_modules/mongodb/lib/cmap/auth/x509.js @@ -0,0 +1,39 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.X509 = void 0; +const error_1 = require("../../error"); +const utils_1 = require("../../utils"); +const auth_provider_1 = require("./auth_provider"); +class X509 extends auth_provider_1.AuthProvider { + prepare(handshakeDoc, authContext, callback) { + const { credentials } = authContext; + if (!credentials) { + return callback(new error_1.MongoMissingCredentialsError('AuthContext must provide credentials.')); + } + Object.assign(handshakeDoc, { + speculativeAuthenticate: x509AuthenticateCommand(credentials) + }); + callback(undefined, handshakeDoc); + } + auth(authContext, callback) { + const connection = authContext.connection; + const credentials = authContext.credentials; + if (!credentials) { + return callback(new error_1.MongoMissingCredentialsError('AuthContext must provide credentials.')); + } + const response = authContext.response; + if (response && response.speculativeAuthenticate) { + return callback(); + } + connection.command((0, utils_1.ns)('$external.$cmd'), x509AuthenticateCommand(credentials), undefined, callback); + } +} +exports.X509 = X509; +function x509AuthenticateCommand(credentials) { + const command = { authenticate: 1, mechanism: 'MONGODB-X509' }; + if (credentials.username) { + command.user = credentials.username; + } + return command; +} +//# sourceMappingURL=x509.js.map \ No newline at end of file diff --git a/ts-ticket-office-service/node_modules/mongodb/lib/cmap/auth/x509.js.map b/ts-ticket-office-service/node_modules/mongodb/lib/cmap/auth/x509.js.map new file mode 100644 index 000000000..84af5792f --- /dev/null +++ b/ts-ticket-office-service/node_modules/mongodb/lib/cmap/auth/x509.js.map @@ -0,0 +1 @@ +{"version":3,"file":"x509.js","sourceRoot":"","sources":["../../../src/cmap/auth/x509.ts"],"names":[],"mappings":";;;AACA,uCAA2D;AAC3D,uCAA2C;AAE3C,mDAA4D;AAG5D,MAAa,IAAK,SAAQ,4BAAY;IAC3B,OAAO,CACd,YAA+B,EAC/B,WAAwB,EACxB,QAAkB;QAElB,MAAM,EAAE,WAAW,EAAE,GAAG,WAAW,CAAC;QACpC,IAAI,CAAC,WAAW,EAAE;YAChB,OAAO,QAAQ,CAAC,IAAI,oCAA4B,CAAC,uCAAuC,CAAC,CAAC,CAAC;SAC5F;QACD,MAAM,CAAC,MAAM,CAAC,YAAY,EAAE;YAC1B,uBAAuB,EAAE,uBAAuB,CAAC,WAAW,CAAC;SAC9D,CAAC,CAAC;QAEH,QAAQ,CAAC,SAAS,EAAE,YAAY,CAAC,CAAC;IACpC,CAAC;IAEQ,IAAI,CAAC,WAAwB,EAAE,QAAkB;QACxD,MAAM,UAAU,GAAG,WAAW,CAAC,UAAU,CAAC;QAC1C,MAAM,WAAW,GAAG,WAAW,CAAC,WAAW,CAAC;QAC5C,IAAI,CAAC,WAAW,EAAE;YAChB,OAAO,QAAQ,CAAC,IAAI,oCAA4B,CAAC,uCAAuC,CAAC,CAAC,CAAC;SAC5F;QACD,MAAM,QAAQ,GAAG,WAAW,CAAC,QAAQ,CAAC;QAEtC,IAAI,QAAQ,IAAI,QAAQ,CAAC,uBAAuB,EAAE;YAChD,OAAO,QAAQ,EAAE,CAAC;SACnB;QAED,UAAU,CAAC,OAAO,CAChB,IAAA,UAAE,EAAC,gBAAgB,CAAC,EACpB,uBAAuB,CAAC,WAAW,CAAC,EACpC,SAAS,EACT,QAAQ,CACT,CAAC;IACJ,CAAC;CACF;AApCD,oBAoCC;AAED,SAAS,uBAAuB,CAAC,WAA6B;IAC5D,MAAM,OAAO,GAAa,EAAE,YAAY,EAAE,CAAC,EAAE,SAAS,EAAE,cAAc,EAAE,CAAC;IACzE,IAAI,WAAW,CAAC,QAAQ,EAAE;QACxB,OAAO,CAAC,IAAI,GAAG,WAAW,CAAC,QAAQ,CAAC;KACrC;IAED,OAAO,OAAO,CAAC;AACjB,CAAC"} \ No newline at end of file diff --git a/ts-ticket-office-service/node_modules/mongodb/lib/cmap/command_monitoring_events.js b/ts-ticket-office-service/node_modules/mongodb/lib/cmap/command_monitoring_events.js new file mode 100644 index 000000000..3f967b439 --- /dev/null +++ b/ts-ticket-office-service/node_modules/mongodb/lib/cmap/command_monitoring_events.js @@ -0,0 +1,272 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.CommandFailedEvent = exports.CommandSucceededEvent = exports.CommandStartedEvent = void 0; +const constants_1 = require("../constants"); +const utils_1 = require("../utils"); +const commands_1 = require("./commands"); +/** + * An event indicating the start of a given + * @public + * @category Event + */ +class CommandStartedEvent { + /** + * Create a started event + * + * @internal + * @param pool - the pool that originated the command + * @param command - the command + */ + constructor(connection, command) { + const cmd = extractCommand(command); + const commandName = extractCommandName(cmd); + const { address, connectionId, serviceId } = extractConnectionDetails(connection); + // TODO: remove in major revision, this is not spec behavior + if (SENSITIVE_COMMANDS.has(commandName)) { + this.commandObj = {}; + this.commandObj[commandName] = true; + } + this.address = address; + this.connectionId = connectionId; + this.serviceId = serviceId; + this.requestId = command.requestId; + this.databaseName = databaseName(command); + this.commandName = commandName; + this.command = maybeRedact(commandName, cmd, cmd); + } + /* @internal */ + get hasServiceId() { + return !!this.serviceId; + } +} +exports.CommandStartedEvent = CommandStartedEvent; +/** + * An event indicating the success of a given command + * @public + * @category Event + */ +class CommandSucceededEvent { + /** + * Create a succeeded event + * + * @internal + * @param pool - the pool that originated the command + * @param command - the command + * @param reply - the reply for this command from the server + * @param started - a high resolution tuple timestamp of when the command was first sent, to calculate duration + */ + constructor(connection, command, reply, started) { + const cmd = extractCommand(command); + const commandName = extractCommandName(cmd); + const { address, connectionId, serviceId } = extractConnectionDetails(connection); + this.address = address; + this.connectionId = connectionId; + this.serviceId = serviceId; + this.requestId = command.requestId; + this.commandName = commandName; + this.duration = (0, utils_1.calculateDurationInMs)(started); + this.reply = maybeRedact(commandName, cmd, extractReply(command, reply)); + } + /* @internal */ + get hasServiceId() { + return !!this.serviceId; + } +} +exports.CommandSucceededEvent = CommandSucceededEvent; +/** + * An event indicating the failure of a given command + * @public + * @category Event + */ +class CommandFailedEvent { + /** + * Create a failure event + * + * @internal + * @param pool - the pool that originated the command + * @param command - the command + * @param error - the generated error or a server error response + * @param started - a high resolution tuple timestamp of when the command was first sent, to calculate duration + */ + constructor(connection, command, error, started) { + const cmd = extractCommand(command); + const commandName = extractCommandName(cmd); + const { address, connectionId, serviceId } = extractConnectionDetails(connection); + this.address = address; + this.connectionId = connectionId; + this.serviceId = serviceId; + this.requestId = command.requestId; + this.commandName = commandName; + this.duration = (0, utils_1.calculateDurationInMs)(started); + this.failure = maybeRedact(commandName, cmd, error); + } + /* @internal */ + get hasServiceId() { + return !!this.serviceId; + } +} +exports.CommandFailedEvent = CommandFailedEvent; +/** Commands that we want to redact because of the sensitive nature of their contents */ +const SENSITIVE_COMMANDS = new Set([ + 'authenticate', + 'saslStart', + 'saslContinue', + 'getnonce', + 'createUser', + 'updateUser', + 'copydbgetnonce', + 'copydbsaslstart', + 'copydb' +]); +const HELLO_COMMANDS = new Set(['hello', constants_1.LEGACY_HELLO_COMMAND, constants_1.LEGACY_HELLO_COMMAND_CAMEL_CASE]); +// helper methods +const extractCommandName = (commandDoc) => Object.keys(commandDoc)[0]; +const namespace = (command) => command.ns; +const databaseName = (command) => command.ns.split('.')[0]; +const collectionName = (command) => command.ns.split('.')[1]; +const maybeRedact = (commandName, commandDoc, result) => SENSITIVE_COMMANDS.has(commandName) || + (HELLO_COMMANDS.has(commandName) && commandDoc.speculativeAuthenticate) + ? {} + : result; +const LEGACY_FIND_QUERY_MAP = { + $query: 'filter', + $orderby: 'sort', + $hint: 'hint', + $comment: 'comment', + $maxScan: 'maxScan', + $max: 'max', + $min: 'min', + $returnKey: 'returnKey', + $showDiskLoc: 'showRecordId', + $maxTimeMS: 'maxTimeMS', + $snapshot: 'snapshot' +}; +const LEGACY_FIND_OPTIONS_MAP = { + numberToSkip: 'skip', + numberToReturn: 'batchSize', + returnFieldSelector: 'projection' +}; +const OP_QUERY_KEYS = [ + 'tailable', + 'oplogReplay', + 'noCursorTimeout', + 'awaitData', + 'partial', + 'exhaust' +]; +/** Extract the actual command from the query, possibly up-converting if it's a legacy format */ +function extractCommand(command) { + var _a; + if (command instanceof commands_1.GetMore) { + return { + getMore: (0, utils_1.deepCopy)(command.cursorId), + collection: collectionName(command), + batchSize: command.numberToReturn + }; + } + if (command instanceof commands_1.KillCursor) { + return { + killCursors: collectionName(command), + cursors: (0, utils_1.deepCopy)(command.cursorIds) + }; + } + if (command instanceof commands_1.Msg) { + return (0, utils_1.deepCopy)(command.command); + } + if ((_a = command.query) === null || _a === void 0 ? void 0 : _a.$query) { + let result; + if (command.ns === 'admin.$cmd') { + // up-convert legacy command + result = Object.assign({}, command.query.$query); + } + else { + // up-convert legacy find command + result = { find: collectionName(command) }; + Object.keys(LEGACY_FIND_QUERY_MAP).forEach(key => { + if (command.query[key] != null) { + result[LEGACY_FIND_QUERY_MAP[key]] = (0, utils_1.deepCopy)(command.query[key]); + } + }); + } + Object.keys(LEGACY_FIND_OPTIONS_MAP).forEach(key => { + const legacyKey = key; + if (command[legacyKey] != null) { + result[LEGACY_FIND_OPTIONS_MAP[legacyKey]] = (0, utils_1.deepCopy)(command[legacyKey]); + } + }); + OP_QUERY_KEYS.forEach(key => { + if (command[key]) { + result[key] = command[key]; + } + }); + if (command.pre32Limit != null) { + result.limit = command.pre32Limit; + } + if (command.query.$explain) { + return { explain: result }; + } + return result; + } + const clonedQuery = {}; + const clonedCommand = {}; + if (command.query) { + for (const k in command.query) { + clonedQuery[k] = (0, utils_1.deepCopy)(command.query[k]); + } + clonedCommand.query = clonedQuery; + } + for (const k in command) { + if (k === 'query') + continue; + clonedCommand[k] = (0, utils_1.deepCopy)(command[k]); + } + return command.query ? clonedQuery : clonedCommand; +} +function extractReply(command, reply) { + if (command instanceof commands_1.KillCursor) { + return { + ok: 1, + cursorsUnknown: command.cursorIds + }; + } + if (!reply) { + return reply; + } + if (command instanceof commands_1.GetMore) { + return { + ok: 1, + cursor: { + id: (0, utils_1.deepCopy)(reply.cursorId), + ns: namespace(command), + nextBatch: (0, utils_1.deepCopy)(reply.documents) + } + }; + } + if (command instanceof commands_1.Msg) { + return (0, utils_1.deepCopy)(reply.result ? reply.result : reply); + } + // is this a legacy find command? + if (command.query && command.query.$query != null) { + return { + ok: 1, + cursor: { + id: (0, utils_1.deepCopy)(reply.cursorId), + ns: namespace(command), + firstBatch: (0, utils_1.deepCopy)(reply.documents) + } + }; + } + return (0, utils_1.deepCopy)(reply.result ? reply.result : reply); +} +function extractConnectionDetails(connection) { + let connectionId; + if ('id' in connection) { + connectionId = connection.id; + } + return { + address: connection.address, + serviceId: connection.serviceId, + connectionId + }; +} +//# sourceMappingURL=command_monitoring_events.js.map \ No newline at end of file diff --git a/ts-ticket-office-service/node_modules/mongodb/lib/cmap/command_monitoring_events.js.map b/ts-ticket-office-service/node_modules/mongodb/lib/cmap/command_monitoring_events.js.map new file mode 100644 index 000000000..33c3451b5 --- /dev/null +++ b/ts-ticket-office-service/node_modules/mongodb/lib/cmap/command_monitoring_events.js.map @@ -0,0 +1 @@ +{"version":3,"file":"command_monitoring_events.js","sourceRoot":"","sources":["../../src/cmap/command_monitoring_events.ts"],"names":[],"mappings":";;;AACA,4CAAqF;AACrF,oCAA2D;AAC3D,yCAAgF;AAGhF;;;;GAIG;AACH,MAAa,mBAAmB;IAU9B;;;;;;OAMG;IACH,YAAY,UAAsB,EAAE,OAAiC;QACnE,MAAM,GAAG,GAAG,cAAc,CAAC,OAAO,CAAC,CAAC;QACpC,MAAM,WAAW,GAAG,kBAAkB,CAAC,GAAG,CAAC,CAAC;QAC5C,MAAM,EAAE,OAAO,EAAE,YAAY,EAAE,SAAS,EAAE,GAAG,wBAAwB,CAAC,UAAU,CAAC,CAAC;QAElF,4DAA4D;QAC5D,IAAI,kBAAkB,CAAC,GAAG,CAAC,WAAW,CAAC,EAAE;YACvC,IAAI,CAAC,UAAU,GAAG,EAAE,CAAC;YACrB,IAAI,CAAC,UAAU,CAAC,WAAW,CAAC,GAAG,I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AAS,wBAAwB,CAAC,UAAsB;IACtD,IAAI,YAAY,CAAC;IACjB,IAAI,IAAI,IAAI,UAAU,EAAE;QACtB,YAAY,GAAG,UAAU,CAAC,EAAE,CAAC;KAC9B;IACD,OAAO;QACL,OAAO,EAAE,UAAU,CAAC,OAAO;QAC3B,SAAS,EAAE,UAAU,CAAC,SAAS;QAC/B,YAAY;KACb,CAAC;AACJ,CAAC"} \ No newline at end of file diff --git a/ts-ticket-office-service/node_modules/mongodb/lib/cmap/commands.js b/ts-ticket-office-service/node_modules/mongodb/lib/cmap/commands.js new file mode 100644 index 000000000..415a4b6f1 --- /dev/null +++ b/ts-ticket-office-service/node_modules/mongodb/lib/cmap/commands.js @@ -0,0 +1,633 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.BinMsg = exports.Msg = exports.Response = exports.KillCursor = exports.GetMore = exports.Query = void 0; +const BSON = require("../bson"); +const error_1 = require("../error"); +const read_preference_1 = require("../read_preference"); +const utils_1 = require("../utils"); +const constants_1 = require("./wire_protocol/constants"); +// Incrementing request id +let _requestId = 0; +// Query flags +const OPTS_TAILABLE_CURSOR = 2; +const OPTS_SECONDARY = 4; +const OPTS_OPLOG_REPLAY = 8; +const OPTS_NO_CURSOR_TIMEOUT = 16; +const OPTS_AWAIT_DATA = 32; +const OPTS_EXHAUST = 64; +const OPTS_PARTIAL = 128; +// Response flags +const CURSOR_NOT_FOUND = 1; +const QUERY_FAILURE = 2; +const SHARD_CONFIG_STALE = 4; +const AWAIT_CAPABLE = 8; +/************************************************************** + * QUERY + **************************************************************/ +/** @internal */ +class Query { + constructor(ns, query, options) { + // Basic options needed to be passed in + // TODO(NODE-3483): Replace with MongoCommandError + if (ns == null) + throw new error_1.MongoRuntimeError('Namespace must be specified for query'); + // TODO(NODE-3483): Replace with MongoCommandError + if (query == null) + throw new error_1.MongoRuntimeError('A query document must be specified for query'); + // Validate that we are not passing 0x00 in the collection name + if (ns.indexOf('\x00') !== -1) { + // TODO(NODE-3483): Use MongoNamespace static method + throw new error_1.MongoRuntimeError('Namespace cannot contain a null character'); + } + // Basic options + this.ns = ns; + this.query = query; + // Additional options + this.numberToSkip = options.numberToSkip || 0; + this.numberToReturn = options.numberToReturn || 0; + this.returnFieldSelector = options.returnFieldSelector || undefined; + this.requestId = Query.getRequestId(); + // special case for pre-3.2 find commands, delete ASAP + this.pre32Limit = options.pre32Limit; + // Serialization option + this.serializeFunctions = + typeof options.serializeFunctions === 'boolean' ? options.serializeFunctions : false; + this.ignoreUndefined = + typeof options.ignoreUndefined === 'boolean' ? options.ignoreUndefined : false; + this.maxBsonSize = options.maxBsonSize || 1024 * 1024 * 16; + this.checkKeys = typeof options.checkKeys === 'boolean' ? options.checkKeys : false; + this.batchSize = this.numberToReturn; + // Flags + this.tailable = false; + this.secondaryOk = typeof options.secondaryOk === 'boolean' ? options.secondaryOk : false; + this.oplogReplay = false; + this.noCursorTimeout = false; + this.awaitData = false; + this.exhaust = false; + this.partial = false; + } + /** Assign next request Id. */ + incRequestId() { + this.requestId = _requestId++; + } + /** Peek next request Id. */ + nextRequestId() { + return _requestId + 1; + } + /** Increment then return next request Id. */ + static getRequestId() { + return ++_requestId; + } + // Uses a single allocated buffer for the process, avoiding multiple memory allocations + toBin() { + const buffers = []; + let projection = null; + // Set up the flags + let flags = 0; + if (this.tailable) { + flags |= OPTS_TAILABLE_CURSOR; + } + if (this.secondaryOk) { + flags |= OPTS_SECONDARY; + } + if (this.oplogReplay) { + flags |= OPTS_OPLOG_REPLAY; + } + if (this.noCursorTimeout) { + flags |= OPTS_NO_CURSOR_TIMEOUT; + } + if (this.awaitData) { + flags |= OPTS_AWAIT_DATA; + } + if (this.exhaust) { + flags |= OPTS_EXHAUST; + } + if (this.partial) { + flags |= OPTS_PARTIAL; + } + // If batchSize is different to this.numberToReturn + if (this.batchSize !== this.numberToReturn) + this.numberToReturn = this.batchSize; + // Allocate write protocol header buffer + const header = Buffer.alloc(4 * 4 + // Header + 4 + // Flags + Buffer.byteLength(this.ns) + + 1 + // namespace + 4 + // numberToSkip + 4 // numberToReturn + ); + // Add header to buffers + buffers.push(header); + // Serialize the query + const query = BSON.serialize(this.query, { + checkKeys: this.checkKeys, + serializeFunctions: this.serializeFunctions, + ignoreUndefined: this.ignoreUndefined + }); + // Add query document + buffers.push(query); + if (this.returnFieldSelector && Object.keys(this.returnFieldSelector).length > 0) { + // Serialize the projection document + projection = BSON.serialize(this.returnFieldSelector, { + checkKeys: this.checkKeys, + serializeFunctions: this.serializeFunctions, + ignoreUndefined: this.ignoreUndefined + }); + // Add projection document + buffers.push(projection); + } + // Total message size + const totalLength = header.length + query.length + (projection ? projection.length : 0); + // Set up the index + let index = 4; + // Write total document length + header[3] = (totalLength >> 24) & 0xff; + header[2] = (totalLength >> 16) & 0xff; + header[1] = (totalLength >> 8) & 0xff; + header[0] = totalLength & 0xff; + // Write header information requestId + header[index + 3] = (this.requestId >> 24) & 0xff; + header[index + 2] = (this.requestId >> 16) & 0xff; + header[index + 1] = (this.requestId >> 8) & 0xff; + header[index] = this.requestId & 0xff; + index = index + 4; + // Write header information responseTo + header[index + 3] = (0 >> 24) & 0xff; + header[index + 2] = (0 >> 16) & 0xff; + header[index + 1] = (0 >> 8) & 0xff; + header[index] = 0 & 0xff; + index = index + 4; + // Write header information OP_QUERY + header[index + 3] = (constants_1.OP_QUERY >> 24) & 0xff; + header[index + 2] = (constants_1.OP_QUERY >> 16) & 0xff; + header[index + 1] = (constants_1.OP_QUERY >> 8) & 0xff; + header[index] = constants_1.OP_QUERY & 0xff; + index = index + 4; + // Write header information flags + header[index + 3] = (flags >> 24) & 0xff; + header[index + 2] = (flags >> 16) & 0xff; + header[index + 1] = (flags >> 8) & 0xff; + header[index] = flags & 0xff; + index = index + 4; + // Write collection name + index = index + header.write(this.ns, index, 'utf8') + 1; + header[index - 1] = 0; + // Write header information flags numberToSkip + header[index + 3] = (this.numberToSkip >> 24) & 0xff; + header[index + 2] = (this.numberToSkip >> 16) & 0xff; + header[index + 1] = (this.numberToSkip >> 8) & 0xff; + header[index] = this.numberToSkip & 0xff; + index = index + 4; + // Write header information flags numberToReturn + header[index + 3] = (this.numberToReturn >> 24) & 0xff; + header[index + 2] = (this.numberToReturn >> 16) & 0xff; + header[index + 1] = (this.numberToReturn >> 8) & 0xff; + header[index] = this.numberToReturn & 0xff; + index = index + 4; + // Return the buffers + return buffers; + } +} +exports.Query = Query; +/************************************************************** + * GETMORE + **************************************************************/ +/** @internal */ +class GetMore { + constructor(ns, cursorId, opts = {}) { + this.numberToReturn = opts.numberToReturn || 0; + this.requestId = _requestId++; + this.ns = ns; + this.cursorId = cursorId; + } + // Uses a single allocated buffer for the process, avoiding multiple memory allocations + toBin() { + const length = 4 + Buffer.byteLength(this.ns) + 1 + 4 + 8 + 4 * 4; + // Create command buffer + let index = 0; + // Allocate buffer + const _buffer = Buffer.alloc(length); + // Write header information + // index = write32bit(index, _buffer, length); + _buffer[index + 3] = (length >> 24) & 0xff; + _buffer[index + 2] = (length >> 16) & 0xff; + _buffer[index + 1] = (length >> 8) & 0xff; + _buffer[index] = length & 0xff; + index = index + 4; + // index = write32bit(index, _buffer, requestId); + _buffer[index + 3] = (this.requestId >> 24) & 0xff; + _buffer[index + 2] = (this.requestId >> 16) & 0xff; + _buffer[index + 1] = (this.requestId >> 8) & 0xff; + _buffer[index] = this.requestId & 0xff; + index = index + 4; + // index = write32bit(index, _buffer, 0); + _buffer[index + 3] = (0 >> 24) & 0xff; + _buffer[index + 2] = (0 >> 16) & 0xff; + _buffer[index + 1] = (0 >> 8) & 0xff; + _buffer[index] = 0 & 0xff; + index = index + 4; + // index = write32bit(index, _buffer, OP_GETMORE); + _buffer[index + 3] = (constants_1.OP_GETMORE >> 24) & 0xff; + _buffer[index + 2] = (constants_1.OP_GETMORE >> 16) & 0xff; + _buffer[index + 1] = (constants_1.OP_GETMORE >> 8) & 0xff; + _buffer[index] = constants_1.OP_GETMORE & 0xff; + index = index + 4; + // index = write32bit(index, _buffer, 0); + _buffer[index + 3] = (0 >> 24) & 0xff; + _buffer[index + 2] = (0 >> 16) & 0xff; + _buffer[index + 1] = (0 >> 8) & 0xff; + _buffer[index] = 0 & 0xff; + index = index + 4; + // Write collection name + index = index + _buffer.write(this.ns, index, 'utf8') + 1; + _buffer[index - 1] = 0; + // Write batch size + // index = write32bit(index, _buffer, numberToReturn); + _buffer[index + 3] = (this.numberToReturn >> 24) & 0xff; + _buffer[index + 2] = (this.numberToReturn >> 16) & 0xff; + _buffer[index + 1] = (this.numberToReturn >> 8) & 0xff; + _buffer[index] = this.numberToReturn & 0xff; + index = index + 4; + // Write cursor id + // index = write32bit(index, _buffer, cursorId.getLowBits()); + _buffer[index + 3] = (this.cursorId.getLowBits() >> 24) & 0xff; + _buffer[index + 2] = (this.cursorId.getLowBits() >> 16) & 0xff; + _buffer[index + 1] = (this.cursorId.getLowBits() >> 8) & 0xff; + _buffer[index] = this.cursorId.getLowBits() & 0xff; + index = index + 4; + // index = write32bit(index, _buffer, cursorId.getHighBits()); + _buffer[index + 3] = (this.cursorId.getHighBits() >> 24) & 0xff; + _buffer[index + 2] = (this.cursorId.getHighBits() >> 16) & 0xff; + _buffer[index + 1] = (this.cursorId.getHighBits() >> 8) & 0xff; + _buffer[index] = this.cursorId.getHighBits() & 0xff; + index = index + 4; + // Return buffer + return [_buffer]; + } +} +exports.GetMore = GetMore; +/************************************************************** + * KILLCURSOR + **************************************************************/ +/** @internal */ +class KillCursor { + constructor(ns, cursorIds) { + this.ns = ns; + this.requestId = _requestId++; + this.cursorIds = cursorIds; + } + // Uses a single allocated buffer for the process, avoiding multiple memory allocations + toBin() { + const length = 4 + 4 + 4 * 4 + this.cursorIds.length * 8; + // Create command buffer + let index = 0; + const _buffer = Buffer.alloc(length); + // Write header information + // index = write32bit(index, _buffer, length); + _buffer[index + 3] = (length >> 24) & 0xff; + _buffer[index + 2] = (length >> 16) & 0xff; + _buffer[index + 1] = (length >> 8) & 0xff; + _buffer[index] = length & 0xff; + index = index + 4; + // index = write32bit(index, _buffer, requestId); + _buffer[index + 3] = (this.requestId >> 24) & 0xff; + _buffer[index + 2] = (this.requestId >> 16) & 0xff; + _buffer[index + 1] = (this.requestId >> 8) & 0xff; + _buffer[index] = this.requestId & 0xff; + index = index + 4; + // index = write32bit(index, _buffer, 0); + _buffer[index + 3] = (0 >> 24) & 0xff; + _buffer[index + 2] = (0 >> 16) & 0xff; + _buffer[index + 1] = (0 >> 8) & 0xff; + _buffer[index] = 0 & 0xff; + index = index + 4; + // index = write32bit(index, _buffer, OP_KILL_CURSORS); + _buffer[index + 3] = (constants_1.OP_KILL_CURSORS >> 24) & 0xff; + _buffer[index + 2] = (constants_1.OP_KILL_CURSORS >> 16) & 0xff; + _buffer[index + 1] = (constants_1.OP_KILL_CURSORS >> 8) & 0xff; + _buffer[index] = constants_1.OP_KILL_CURSORS & 0xff; + index = index + 4; + // index = write32bit(index, _buffer, 0); + _buffer[index + 3] = (0 >> 24) & 0xff; + _buffer[index + 2] = (0 >> 16) & 0xff; + _buffer[index + 1] = (0 >> 8) & 0xff; + _buffer[index] = 0 & 0xff; + index = index + 4; + // Write batch size + // index = write32bit(index, _buffer, this.cursorIds.length); + _buffer[index + 3] = (this.cursorIds.length >> 24) & 0xff; + _buffer[index + 2] = (this.cursorIds.length >> 16) & 0xff; + _buffer[index + 1] = (this.cursorIds.length >> 8) & 0xff; + _buffer[index] = this.cursorIds.length & 0xff; + index = index + 4; + // Write all the cursor ids into the array + for (let i = 0; i < this.cursorIds.length; i++) { + // Write cursor id + // index = write32bit(index, _buffer, cursorIds[i].getLowBits()); + _buffer[index + 3] = (this.cursorIds[i].getLowBits() >> 24) & 0xff; + _buffer[index + 2] = (this.cursorIds[i].getLowBits() >> 16) & 0xff; + _buffer[index + 1] = (this.cursorIds[i].getLowBits() >> 8) & 0xff; + _buffer[index] = this.cursorIds[i].getLowBits() & 0xff; + index = index + 4; + // index = write32bit(index, _buffer, cursorIds[i].getHighBits()); + _buffer[index + 3] = (this.cursorIds[i].getHighBits() >> 24) & 0xff; + _buffer[index + 2] = (this.cursorIds[i].getHighBits() >> 16) & 0xff; + _buffer[index + 1] = (this.cursorIds[i].getHighBits() >> 8) & 0xff; + _buffer[index] = this.cursorIds[i].getHighBits() & 0xff; + index = index + 4; + } + // Return buffer + return [_buffer]; + } +} +exports.KillCursor = KillCursor; +/** @internal */ +class Response { + constructor(message, msgHeader, msgBody, opts) { + this.documents = new Array(0); + this.parsed = false; + this.raw = message; + this.data = msgBody; + this.opts = opts !== null && opts !== void 0 ? opts : { + promoteLongs: true, + promoteValues: true, + promoteBuffers: false, + bsonRegExp: false + }; + // Read the message header + this.length = msgHeader.length; + this.requestId = msgHeader.requestId; + this.responseTo = msgHeader.responseTo; + this.opCode = msgHeader.opCode; + this.fromCompressed = msgHeader.fromCompressed; + // Flag values + this.promoteLongs = typeof this.opts.promoteLongs === 'boolean' ? this.opts.promoteLongs : true; + this.promoteValues = + typeof this.opts.promoteValues === 'boolean' ? this.opts.promoteValues : true; + this.promoteBuffers = + typeof this.opts.promoteBuffers === 'boolean' ? this.opts.promoteBuffers : false; + this.bsonRegExp = typeof this.opts.bsonRegExp === 'boolean' ? this.opts.bsonRegExp : false; + } + isParsed() { + return this.parsed; + } + parse(options) { + var _a, _b, _c, _d; + // Don't parse again if not needed + if (this.parsed) + return; + options = options !== null && options !== void 0 ? options : {}; + // Allow the return of raw documents instead of parsing + const raw = options.raw || false; + const documentsReturnedIn = options.documentsReturnedIn || null; + const promoteLongs = (_a = options.promoteLongs) !== null && _a !== void 0 ? _a : this.opts.promoteLongs; + const promoteValues = (_b = options.promoteValues) !== null && _b !== void 0 ? _b : this.opts.promoteValues; + const promoteBuffers = (_c = options.promoteBuffers) !== null && _c !== void 0 ? _c : this.opts.promoteBuffers; + const bsonRegExp = (_d = options.bsonRegExp) !== null && _d !== void 0 ? _d : this.opts.bsonRegExp; + let bsonSize; + // Set up the options + const _options = { + promoteLongs, + promoteValues, + promoteBuffers, + bsonRegExp + }; + // Position within OP_REPLY at which documents start + // (See https://docs.mongodb.com/manual/reference/mongodb-wire-protocol/#wire-op-reply) + this.index = 20; + // Read the message body + this.responseFlags = this.data.readInt32LE(0); + this.cursorId = new BSON.Long(this.data.readInt32LE(4), this.data.readInt32LE(8)); + this.startingFrom = this.data.readInt32LE(12); + this.numberReturned = this.data.readInt32LE(16); + // Preallocate document array + this.documents = new Array(this.numberReturned); + this.cursorNotFound = (this.responseFlags & CURSOR_NOT_FOUND) !== 0; + this.queryFailure = (this.responseFlags & QUERY_FAILURE) !== 0; + this.shardConfigStale = (this.responseFlags & SHARD_CONFIG_STALE) !== 0; + this.awaitCapable = (this.responseFlags & AWAIT_CAPABLE) !== 0; + // Parse Body + for (let i = 0; i < this.numberReturned; i++) { + bsonSize = + this.data[this.index] | + (this.data[this.index + 1] << 8) | + (this.data[this.index + 2] << 16) | + (this.data[this.index + 3] << 24); + // If we have raw results specified slice the return document + if (raw) { + this.documents[i] = this.data.slice(this.index, this.index + bsonSize); + } + else { + this.documents[i] = BSON.deserialize(this.data.slice(this.index, this.index + bsonSize), _options); + } + // Adjust the index + this.index = this.index + bsonSize; + } + if (this.documents.length === 1 && documentsReturnedIn != null && raw) { + const fieldsAsRaw = {}; + fieldsAsRaw[documentsReturnedIn] = true; + _options.fieldsAsRaw = fieldsAsRaw; + const doc = BSON.deserialize(this.documents[0], _options); + this.documents = [doc]; + } + // Set parsed + this.parsed = true; + } +} +exports.Response = Response; +// Implementation of OP_MSG spec: +// https://github.com/mongodb/specifications/blob/master/source/message/OP_MSG.rst +// +// struct Section { +// uint8 payloadType; +// union payload { +// document document; // payloadType == 0 +// struct sequence { // payloadType == 1 +// int32 size; +// cstring identifier; +// document* documents; +// }; +// }; +// }; +// struct OP_MSG { +// struct MsgHeader { +// int32 messageLength; +// int32 requestID; +// int32 responseTo; +// int32 opCode = 2013; +// }; +// uint32 flagBits; +// Section+ sections; +// [uint32 checksum;] +// }; +// Msg Flags +const OPTS_CHECKSUM_PRESENT = 1; +const OPTS_MORE_TO_COME = 2; +const OPTS_EXHAUST_ALLOWED = 1 << 16; +/** @internal */ +class Msg { + constructor(ns, command, options) { + // Basic options needed to be passed in + if (command == null) + throw new error_1.MongoInvalidArgumentError('Query document must be specified for query'); + // Basic options + this.ns = ns; + this.command = command; + this.command.$db = (0, utils_1.databaseNamespace)(ns); + if (options.readPreference && options.readPreference.mode !== read_preference_1.ReadPreference.PRIMARY) { + this.command.$readPreference = options.readPreference.toJSON(); + } + // Ensure empty options + this.options = options !== null && options !== void 0 ? options : {}; + // Additional options + this.requestId = options.requestId ? options.requestId : Msg.getRequestId(); + // Serialization option + this.serializeFunctions = + typeof options.serializeFunctions === 'boolean' ? options.serializeFunctions : false; + this.ignoreUndefined = + typeof options.ignoreUndefined === 'boolean' ? options.ignoreUndefined : false; + this.checkKeys = typeof options.checkKeys === 'boolean' ? options.checkKeys : false; + this.maxBsonSize = options.maxBsonSize || 1024 * 1024 * 16; + // flags + this.checksumPresent = false; + this.moreToCome = options.moreToCome || false; + this.exhaustAllowed = + typeof options.exhaustAllowed === 'boolean' ? options.exhaustAllowed : false; + } + toBin() { + const buffers = []; + let flags = 0; + if (this.checksumPresent) { + flags |= OPTS_CHECKSUM_PRESENT; + } + if (this.moreToCome) { + flags |= OPTS_MORE_TO_COME; + } + if (this.exhaustAllowed) { + flags |= OPTS_EXHAUST_ALLOWED; + } + const header = Buffer.alloc(4 * 4 + // Header + 4 // Flags + ); + buffers.push(header); + let totalLength = header.length; + const command = this.command; + totalLength += this.makeDocumentSegment(buffers, command); + header.writeInt32LE(totalLength, 0); // messageLength + header.writeInt32LE(this.requestId, 4); // requestID + header.writeInt32LE(0, 8); // responseTo + header.writeInt32LE(constants_1.OP_MSG, 12); // opCode + header.writeUInt32LE(flags, 16); // flags + return buffers; + } + makeDocumentSegment(buffers, document) { + const payloadTypeBuffer = Buffer.alloc(1); + payloadTypeBuffer[0] = 0; + const documentBuffer = this.serializeBson(document); + buffers.push(payloadTypeBuffer); + buffers.push(documentBuffer); + return payloadTypeBuffer.length + documentBuffer.length; + } + serializeBson(document) { + return BSON.serialize(document, { + checkKeys: this.checkKeys, + serializeFunctions: this.serializeFunctions, + ignoreUndefined: this.ignoreUndefined + }); + } + static getRequestId() { + _requestId = (_requestId + 1) & 0x7fffffff; + return _requestId; + } +} +exports.Msg = Msg; +/** @internal */ +class BinMsg { + constructor(message, msgHeader, msgBody, opts) { + this.parsed = false; + this.raw = message; + this.data = msgBody; + this.opts = opts !== null && opts !== void 0 ? opts : { + promoteLongs: true, + promoteValues: true, + promoteBuffers: false, + bsonRegExp: false + }; + // Read the message header + this.length = msgHeader.length; + this.requestId = msgHeader.requestId; + this.responseTo = msgHeader.responseTo; + this.opCode = msgHeader.opCode; + this.fromCompressed = msgHeader.fromCompressed; + // Read response flags + this.responseFlags = msgBody.readInt32LE(0); + this.checksumPresent = (this.responseFlags & OPTS_CHECKSUM_PRESENT) !== 0; + this.moreToCome = (this.responseFlags & OPTS_MORE_TO_COME) !== 0; + this.exhaustAllowed = (this.responseFlags & OPTS_EXHAUST_ALLOWED) !== 0; + this.promoteLongs = typeof this.opts.promoteLongs === 'boolean' ? this.opts.promoteLongs : true; + this.promoteValues = + typeof this.opts.promoteValues === 'boolean' ? this.opts.promoteValues : true; + this.promoteBuffers = + typeof this.opts.promoteBuffers === 'boolean' ? this.opts.promoteBuffers : false; + this.bsonRegExp = typeof this.opts.bsonRegExp === 'boolean' ? this.opts.bsonRegExp : false; + this.documents = []; + } + isParsed() { + return this.parsed; + } + parse(options) { + var _a, _b, _c, _d; + // Don't parse again if not needed + if (this.parsed) + return; + options = options !== null && options !== void 0 ? options : {}; + this.index = 4; + // Allow the return of raw documents instead of parsing + const raw = options.raw || false; + const documentsReturnedIn = options.documentsReturnedIn || null; + const promoteLongs = (_a = options.promoteLongs) !== null && _a !== void 0 ? _a : this.opts.promoteLongs; + const promoteValues = (_b = options.promoteValues) !== null && _b !== void 0 ? _b : this.opts.promoteValues; + const promoteBuffers = (_c = options.promoteBuffers) !== null && _c !== void 0 ? _c : this.opts.promoteBuffers; + const bsonRegExp = (_d = options.bsonRegExp) !== null && _d !== void 0 ? _d : this.opts.bsonRegExp; + const validation = this.parseBsonSerializationOptions(options); + // Set up the options + const bsonOptions = { + promoteLongs, + promoteValues, + promoteBuffers, + bsonRegExp, + validation + // Due to the strictness of the BSON libraries validation option we need this cast + }; + while (this.index < this.data.length) { + const payloadType = this.data.readUInt8(this.index++); + if (payloadType === 0) { + const bsonSize = this.data.readUInt32LE(this.index); + const bin = this.data.slice(this.index, this.index + bsonSize); + this.documents.push(raw ? bin : BSON.deserialize(bin, bsonOptions)); + this.index += bsonSize; + } + else if (payloadType === 1) { + // It was decided that no driver makes use of payload type 1 + // TODO(NODE-3483): Replace with MongoDeprecationError + throw new error_1.MongoRuntimeError('OP_MSG Payload Type 1 detected unsupported protocol'); + } + } + if (this.documents.length === 1 && documentsReturnedIn != null && raw) { + const fieldsAsRaw = {}; + fieldsAsRaw[documentsReturnedIn] = true; + bsonOptions.fieldsAsRaw = fieldsAsRaw; + const doc = BSON.deserialize(this.documents[0], bsonOptions); + this.documents = [doc]; + } + this.parsed = true; + } + parseBsonSerializationOptions({ enableUtf8Validation }) { + if (enableUtf8Validation === false) { + return { utf8: false }; + } + return { utf8: { writeErrors: false } }; + } +} +exports.BinMsg = BinMsg; +//# sourceMappingURL=commands.js.map \ No newline at end of file diff --git a/ts-ticket-office-service/node_modules/mongodb/lib/cmap/commands.js.map b/ts-ticket-office-service/node_modules/mongodb/lib/cmap/commands.js.map new file mode 100644 index 000000000..051635790 --- /dev/null +++ b/ts-ticket-office-service/node_modules/mongodb/lib/cmap/commands.js.map @@ -0,0 +1 @@ +{"version":3,"file":"commands.js","sourceRoot":"","sources":["../../src/cmap/commands.ts"],"names":[],"mappings":";;;AACA,gCAAgC;AAChC,oCAAwE;AACxE,wDAAoD;AAEpD,oCAA6C;AAE7C,yDAA0F;AAE1F,0BAA0B;AAC1B,IAAI,UAAU,GAAG,CAAC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b/lib/cmap/connect.js b/ts-ticket-office-service/node_modules/mongodb/lib/cmap/connect.js new file mode 100644 index 000000000..9440a6527 --- /dev/null +++ b/ts-ticket-office-service/node_modules/mongodb/lib/cmap/connect.js @@ -0,0 +1,390 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.LEGAL_TCP_SOCKET_OPTIONS = exports.LEGAL_TLS_SOCKET_OPTIONS = exports.connect = void 0; +const net = require("net"); +const socks_1 = require("socks"); +const tls = require("tls"); +const bson_1 = require("../bson"); +const constants_1 = require("../constants"); +const error_1 = require("../error"); +const utils_1 = require("../utils"); +const auth_provider_1 = require("./auth/auth_provider"); +const gssapi_1 = require("./auth/gssapi"); +const mongocr_1 = require("./auth/mongocr"); +const mongodb_aws_1 = require("./auth/mongodb_aws"); +const plain_1 = require("./auth/plain"); +const providers_1 = require("./auth/providers"); +const scram_1 = require("./auth/scram"); +const x509_1 = require("./auth/x509"); +const connection_1 = require("./connection"); +const constants_2 = require("./wire_protocol/constants"); +const AUTH_PROVIDERS = new Map([ + [providers_1.AuthMechanism.MONGODB_AWS, new mongodb_aws_1.MongoDBAWS()], + [providers_1.AuthMechanism.MONGODB_CR, new mongocr_1.MongoCR()], + [providers_1.AuthMechanism.MONGODB_GSSAPI, new gssapi_1.GSSAPI()], + [providers_1.AuthMechanism.MONGODB_PLAIN, new plain_1.Plain()], + [providers_1.AuthMechanism.MONGODB_SCRAM_SHA1, new scram_1.ScramSHA1()], + [providers_1.AuthMechanism.MONGODB_SCRAM_SHA256, new scram_1.ScramSHA256()], + [providers_1.AuthMechanism.MONGODB_X509, new x509_1.X509()] +]); +function connect(options, callback) { + makeConnection({ ...options, existingSocket: undefined }, (err, socket) => { + var _a; + if (err || !socket) { + return callback(err); + } + let ConnectionType = (_a = options.connectionType) !== null && _a !== void 0 ? _a : connection_1.Connection; + if (options.autoEncrypter) { + ConnectionType = connection_1.CryptoConnection; + } + performInitialHandshake(new ConnectionType(socket, options), options, callback); + }); +} +exports.connect = connect; +function checkSupportedServer(hello, options) { + var _a; + const serverVersionHighEnough = hello && + (typeof hello.maxWireVersion === 'number' || hello.maxWireVersion instanceof bson_1.Int32) && + hello.maxWireVersion >= constants_2.MIN_SUPPORTED_WIRE_VERSION; + const serverVersionLowEnough = hello && + (typeof hello.minWireVersion === 'number' || hello.minWireVersion instanceof bson_1.Int32) && + hello.minWireVersion <= constants_2.MAX_SUPPORTED_WIRE_VERSION; + if (serverVersionHighEnough) { + if (serverVersionLowEnough) { + return null; + } + const message = `Server at ${options.hostAddress} reports minimum wire version ${JSON.stringify(hello.minWireVersion)}, but this version of the Node.js Driver requires at most ${constants_2.MAX_SUPPORTED_WIRE_VERSION} (MongoDB ${constants_2.MAX_SUPPORTED_SERVER_VERSION})`; + return new error_1.MongoCompatibilityError(message); + } + const message = `Server at ${options.hostAddress} reports maximum wire version ${(_a = JSON.stringify(hello.maxWireVersion)) !== null && _a !== void 0 ? _a : 0}, but this version of the Node.js Driver requires at least ${constants_2.MIN_SUPPORTED_WIRE_VERSION} (MongoDB ${constants_2.MIN_SUPPORTED_SERVER_VERSION})`; + return new error_1.MongoCompatibilityError(message); +} +function performInitialHandshake(conn, options, _callback) { + const callback = function (err, ret) { + if (err && conn) { + conn.destroy(); + } + _callback(err, ret); + }; + const credentials = options.credentials; + if (credentials) { + if (!(credentials.mechanism === providers_1.AuthMechanism.MONGODB_DEFAULT) && + !AUTH_PROVIDERS.get(credentials.mechanism)) { + callback(new error_1.MongoInvalidArgumentError(`AuthMechanism '${credentials.mechanism}' not supported`)); + return; + } + } + const authContext = new auth_provider_1.AuthContext(conn, credentials, options); + prepareHandshakeDocument(authContext, (err, handshakeDoc) => { + if (err || !handshakeDoc) { + return callback(err); + } + const handshakeOptions = Object.assign({}, options); + if (typeof options.connectTimeoutMS === 'number') { + // The handshake technically is a monitoring check, so its socket timeout should be connectTimeoutMS + handshakeOptions.socketTimeoutMS = options.connectTimeoutMS; + } + const start = new Date().getTime(); + conn.command((0, utils_1.ns)('admin.$cmd'), handshakeDoc, handshakeOptions, (err, response) => { + if (err) { + callback(err); + return; + } + if ((response === null || response === void 0 ? void 0 : response.ok) === 0) { + callback(new error_1.MongoServerError(response)); + return; + } + if (!('isWritablePrimary' in response)) { + // Provide hello-style response document. + response.isWritablePrimary = response[constants_1.LEGACY_HELLO_COMMAND]; + } + if (response.helloOk) { + conn.helloOk = true; + } + const supportedServerErr = checkSupportedServer(response, options); + if (supportedServerErr) { + callback(supportedServerErr); + return; + } + if (options.loadBalanced) { + if (!response.serviceId) { + return callback(new error_1.MongoCompatibilityError('Driver attempted to initialize in load balancing mode, ' + + 'but the server does not support this mode.')); + } + } + // NOTE: This is metadata attached to the connection while porting away from + // handshake being done in the `Server` class. Likely, it should be + // relocated, or at very least restructured. + conn.hello = response; + conn.lastHelloMS = new Date().getTime() - start; + if (!response.arbiterOnly && credentials) { + // store the response on auth context + authContext.response = response; + const resolvedCredentials = credentials.resolveAuthMechanism(response); + const provider = AUTH_PROVIDERS.get(resolvedCredentials.mechanism); + if (!provider) { + return callback(new error_1.MongoInvalidArgumentError(`No AuthProvider for ${resolvedCredentials.mechanism} defined.`)); + } + provider.auth(authContext, err => { + if (err) { + if (err instanceof error_1.MongoError) { + err.addErrorLabel(error_1.MongoErrorLabel.HandshakeError); + if ((0, error_1.needsRetryableWriteLabel)(err, response.maxWireVersion)) { + err.addErrorLabel(error_1.MongoErrorLabel.RetryableWriteError); + } + } + return callback(err); + } + callback(undefined, conn); + }); + return; + } + callback(undefined, conn); + }); + }); +} +function prepareHandshakeDocument(authContext, callback) { + const options = authContext.options; + const compressors = options.compressors ? options.compressors : []; + const { serverApi } = authContext.connection; + const handshakeDoc = { + [(serverApi === null || serverApi === void 0 ? void 0 : serverApi.version) ? 'hello' : constants_1.LEGACY_HELLO_COMMAND]: true, + helloOk: true, + client: options.metadata || (0, utils_1.makeClientMetadata)(options), + compression: compressors, + loadBalanced: options.loadBalanced + }; + const credentials = authContext.credentials; + if (credentials) { + if (credentials.mechanism === providers_1.AuthMechanism.MONGODB_DEFAULT && credentials.username) { + handshakeDoc.saslSupportedMechs = `${credentials.source}.${credentials.username}`; + const provider = AUTH_PROVIDERS.get(providers_1.AuthMechanism.MONGODB_SCRAM_SHA256); + if (!provider) { + // This auth mechanism is always present. + return callback(new error_1.MongoInvalidArgumentError(`No AuthProvider for ${providers_1.AuthMechanism.MONGODB_SCRAM_SHA256} defined.`)); + } + return provider.prepare(handshakeDoc, authContext, callback); + } + const provider = AUTH_PROVIDERS.get(credentials.mechanism); + if (!provider) { + return callback(new error_1.MongoInvalidArgumentError(`No AuthProvider for ${credentials.mechanism} defined.`)); + } + return provider.prepare(handshakeDoc, authContext, callback); + } + callback(undefined, handshakeDoc); +} +/** @public */ +exports.LEGAL_TLS_SOCKET_OPTIONS = [ + 'ALPNProtocols', + 'ca', + 'cert', + 'checkServerIdentity', + 'ciphers', + 'crl', + 'ecdhCurve', + 'key', + 'minDHSize', + 'passphrase', + 'pfx', + 'rejectUnauthorized', + 'secureContext', + 'secureProtocol', + 'servername', + 'session' +]; +/** @public */ +exports.LEGAL_TCP_SOCKET_OPTIONS = [ + 'family', + 'hints', + 'localAddress', + 'localPort', + 'lookup' +]; +function parseConnectOptions(options) { + const hostAddress = options.hostAddress; + if (!hostAddress) + throw new error_1.MongoInvalidArgumentError('Option "hostAddress" is required'); + const result = {}; + for (const name of exports.LEGAL_TCP_SOCKET_OPTIONS) { + if (options[name] != null) { + result[name] = options[name]; + } + } + if (typeof hostAddress.socketPath === 'string') { + result.path = hostAddress.socketPath; + return result; + } + else if (typeof hostAddress.host === 'string') { + result.host = hostAddress.host; + result.port = hostAddress.port; + return result; + } + else { + // This should never happen since we set up HostAddresses + // But if we don't throw here the socket could hang until timeout + // TODO(NODE-3483) + throw new error_1.MongoRuntimeError(`Unexpected HostAddress ${JSON.stringify(hostAddress)}`); + } +} +function parseSslOptions(options) { + const result = parseConnectOptions(options); + // Merge in valid SSL options + for (const name of exports.LEGAL_TLS_SOCKET_OPTIONS) { + if (options[name] != null) { + result[name] = options[name]; + } + } + if (options.existingSocket) { + result.socket = options.existingSocket; + } + // Set default sni servername to be the same as host + if (result.servername == null && result.host && !net.isIP(result.host)) { + result.servername = result.host; + } + return result; +} +const SOCKET_ERROR_EVENT_LIST = ['error', 'close', 'timeout', 'parseError']; +const SOCKET_ERROR_EVENTS = new Set(SOCKET_ERROR_EVENT_LIST); +function makeConnection(options, _callback) { + var _a, _b, _c, _d, _e, _f, _g, _h, _j; + const useTLS = (_a = options.tls) !== null && _a !== void 0 ? _a : false; + const keepAlive = (_b = options.keepAlive) !== null && _b !== void 0 ? _b : true; + const socketTimeoutMS = (_d = (_c = options.socketTimeoutMS) !== null && _c !== void 0 ? _c : Reflect.get(options, 'socketTimeout')) !== null && _d !== void 0 ? _d : 0; + const noDelay = (_e = options.noDelay) !== null && _e !== void 0 ? _e : true; + const connectTimeoutMS = (_f = options.connectTimeoutMS) !== null && _f !== void 0 ? _f : 30000; + const rejectUnauthorized = (_g = options.rejectUnauthorized) !== null && _g !== void 0 ? _g : true; + const keepAliveInitialDelay = (_j = (((_h = options.keepAliveInitialDelay) !== null && _h !== void 0 ? _h : 120000) > socketTimeoutMS + ? Math.round(socketTimeoutMS / 2) + : options.keepAliveInitialDelay)) !== null && _j !== void 0 ? _j : 120000; + const existingSocket = options.existingSocket; + let socket; + const callback = function (err, ret) { + if (err && socket) { + socket.destroy(); + } + _callback(err, ret); + }; + if (options.proxyHost != null) { + // Currently, only Socks5 is supported. + return makeSocks5Connection({ + ...options, + connectTimeoutMS // Should always be present for Socks5 + }, callback); + } + if (useTLS) { + const tlsSocket = tls.connect(parseSslOptions(options)); + if (typeof tlsSocket.disableRenegotiation === 'function') { + tlsSocket.disableRenegotiation(); + } + socket = tlsSocket; + } + else if (existingSocket) { + // In the TLS case, parseSslOptions() sets options.socket to existingSocket, + // so we only need to handle the non-TLS case here (where existingSocket + // gives us all we need out of the box). + socket = existingSocket; + } + else { + socket = net.createConnection(parseConnectOptions(options)); + } + socket.setKeepAlive(keepAlive, keepAliveInitialDelay); + socket.setTimeout(connectTimeoutMS); + socket.setNoDelay(noDelay); + const connectEvent = useTLS ? 'secureConnect' : 'connect'; + let cancellationHandler; + function errorHandler(eventName) { + return (err) => { + SOCKET_ERROR_EVENTS.forEach(event => socket.removeAllListeners(event)); + if (cancellationHandler && options.cancellationToken) { + options.cancellationToken.removeListener('cancel', cancellationHandler); + } + socket.removeListener(connectEvent, connectHandler); + callback(connectionFailureError(eventName, err)); + }; + } + function connectHandler() { + SOCKET_ERROR_EVENTS.forEach(event => socket.removeAllListeners(event)); + if (cancellationHandler && options.cancellationToken) { + options.cancellationToken.removeListener('cancel', cancellationHandler); + } + if ('authorizationError' in socket) { + if (socket.authorizationError && rejectUnauthorized) { + return callback(socket.authorizationError); + } + } + socket.setTimeout(socketTimeoutMS); + callback(undefined, socket); + } + SOCKET_ERROR_EVENTS.forEach(event => socket.once(event, errorHandler(event))); + if (options.cancellationToken) { + cancellationHandler = errorHandler('cancel'); + options.cancellationToken.once('cancel', cancellationHandler); + } + if (existingSocket) { + process.nextTick(connectHandler); + } + else { + socket.once(connectEvent, connectHandler); + } +} +function makeSocks5Connection(options, callback) { + var _a, _b; + const hostAddress = utils_1.HostAddress.fromHostPort((_a = options.proxyHost) !== null && _a !== void 0 ? _a : '', // proxyHost is guaranteed to set here + (_b = options.proxyPort) !== null && _b !== void 0 ? _b : 1080); + // First, connect to the proxy server itself: + makeConnection({ + ...options, + hostAddress, + tls: false, + proxyHost: undefined + }, (err, rawSocket) => { + if (err) { + return callback(err); + } + const destination = parseConnectOptions(options); + if (typeof destination.host !== 'string' || typeof destination.port !== 'number') { + return callback(new error_1.MongoInvalidArgumentError('Can only make Socks5 connections to TCP hosts')); + } + // Then, establish the Socks5 proxy connection: + socks_1.SocksClient.createConnection({ + existing_socket: rawSocket, + timeout: options.connectTimeoutMS, + command: 'connect', + destination: { + host: destination.host, + port: destination.port + }, + proxy: { + // host and port are ignored because we pass existing_socket + host: 'iLoveJavaScript', + port: 0, + type: 5, + userId: options.proxyUsername || undefined, + password: options.proxyPassword || undefined + } + }).then(({ socket }) => { + // Finally, now treat the resulting duplex stream as the + // socket over which we send and receive wire protocol messages: + makeConnection({ + ...options, + existingSocket: socket, + proxyHost: undefined + }, callback); + }, error => callback(connectionFailureError('error', error))); + }); +} +function connectionFailureError(type, err) { + switch (type) { + case 'error': + return new error_1.MongoNetworkError(err); + case 'timeout': + return new error_1.MongoNetworkTimeoutError('connection timed out'); + case 'close': + return new error_1.MongoNetworkError('connection closed'); + case 'cancel': + return new error_1.MongoNetworkError('connection establishment was cancelled'); + default: + return new error_1.MongoNetworkError('unknown network error'); + } +} +//# sourceMappingURL=connect.js.map \ No newline at end of file diff --git a/ts-ticket-office-service/node_modules/mongodb/lib/cmap/connect.js.map b/ts-ticket-office-service/node_modules/mongodb/lib/cmap/connect.js.map new file mode 100644 index 000000000..76926c818 --- /dev/null +++ b/ts-ticket-office-service/node_modules/mongodb/lib/cmap/connect.js.map @@ -0,0 +1 @@ +{"version":3,"file":"connect.js","sourceRoot":"","sources":["../../src/cmap/connect.ts"],"names":[],"mappings":";;;AACA,2BAA2B;AAC3B,iCAAoC;AAEpC,2BAA2B;AAG3B,kCAAgC;AAChC,4CAAoD;AACpD,oCAUkB;AAClB,oCAAyF;AACzF,wDAAiE;AACjE,0CAAuC;AACvC,4CAAyC;AACzC,oDAAgD;AAChD,wCAAqC;AACrC,gDAAiD;AACjD,wCAAsD;AACtD,sCAAmC;AACnC,6CAA+E;AAC/E,yDAKmC;AAEnC,MAAM,cAAc,GAAG,IAAI,GAAG,CAAuC;IACnE,CAAC,yBAAa,CAAC,WAAW,EAAE,IAAI,wBAAU,EAAE,CAAC;IAC7C,CAAC,yBAAa,CAAC,UAAU,EAAE,IAAI,iBAAO,EAAE,CAAC;IACzC,CAAC,yBAAa,CAAC,cAAc,EAAE,IAAI,eAAM,EAAE,CAAC;IAC5C,CAAC,yBAAa,CAAC,aAAa,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AAC,CAAC;QACpD,KAAK,QAAQ;YACX,OAAO,IAAI,yBAAiB,CAAC,wCAAwC,CAAC,CAAC;QACzE;YACE,OAAO,IAAI,yBAAiB,CAAC,uBAAuB,CAAC,CAAC;KACzD;AACH,CAAC"} \ No newline at end of file diff --git a/ts-ticket-office-service/node_modules/mongodb/lib/cmap/connection.js b/ts-ticket-office-service/node_modules/mongodb/lib/cmap/connection.js new file mode 100644 index 000000000..1ad803cd7 --- /dev/null +++ b/ts-ticket-office-service/node_modules/mongodb/lib/cmap/connection.js @@ -0,0 +1,532 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.hasSessionSupport = exports.CryptoConnection = exports.Connection = void 0; +const timers_1 = require("timers"); +const bson_1 = require("../bson"); +const constants_1 = require("../constants"); +const error_1 = require("../error"); +const mongo_types_1 = require("../mongo_types"); +const sessions_1 = require("../sessions"); +const utils_1 = require("../utils"); +const command_monitoring_events_1 = require("./command_monitoring_events"); +const commands_1 = require("./commands"); +const message_stream_1 = require("./message_stream"); +const stream_description_1 = require("./stream_description"); +const shared_1 = require("./wire_protocol/shared"); +/** @internal */ +const kStream = Symbol('stream'); +/** @internal */ +const kQueue = Symbol('queue'); +/** @internal */ +const kMessageStream = Symbol('messageStream'); +/** @internal */ +const kGeneration = Symbol('generation'); +/** @internal */ +const kLastUseTime = Symbol('lastUseTime'); +/** @internal */ +const kClusterTime = Symbol('clusterTime'); +/** @internal */ +const kDescription = Symbol('description'); +/** @internal */ +const kHello = Symbol('hello'); +/** @internal */ +const kAutoEncrypter = Symbol('autoEncrypter'); +/** @internal */ +const kFullResult = Symbol('fullResult'); +/** @internal */ +const kDelayedTimeoutId = Symbol('delayedTimeoutId'); +/** @internal */ +class Connection extends mongo_types_1.TypedEventEmitter { + constructor(stream, options) { + var _a, _b; + super(); + this.id = options.id; + this.address = streamIdentifier(stream, options); + this.socketTimeoutMS = (_a = options.socketTimeoutMS) !== null && _a !== void 0 ? _a : 0; + this.monitorCommands = options.monitorCommands; + this.serverApi = options.serverApi; + this.closed = false; + this.destroyed = false; + this[kHello] = null; + this[kClusterTime] = null; + this[kDescription] = new stream_description_1.StreamDescription(this.address, options); + this[kGeneration] = options.generation; + this[kLastUseTime] = (0, utils_1.now)(); + // setup parser stream and message handling + this[kQueue] = new Map(); + this[kMessageStream] = new message_stream_1.MessageStream({ + ...options, + maxBsonMessageSize: (_b = this.hello) === null || _b === void 0 ? void 0 : _b.maxBsonMessageSize + }); + this[kStream] = stream; + this[kDelayedTimeoutId] = null; + this[kMessageStream].on('message', message => this.onMessage(message)); + this[kMessageStream].on('error', error => this.onError(error)); + this[kStream].on('close', () => this.onClose()); + this[kStream].on('timeout', () => this.onTimeout()); + this[kStream].on('error', () => { + /* ignore errors, listen to `close` instead */ + }); + // hook the message stream up to the passed in stream + this[kStream].pipe(this[kMessageStream]); + this[kMessageStream].pipe(this[kStream]); + } + get description() { + return this[kDescription]; + } + get hello() { + return this[kHello]; + } + // the `connect` method stores the result of the handshake hello on the connection + set hello(response) { + this[kDescription].receiveResponse(response); + this[kDescription] = Object.freeze(this[kDescription]); + // TODO: remove this, and only use the `StreamDescription` in the future + this[kHello] = response; + } + // Set the whether the message stream is for a monitoring connection. + set isMonitoringConnection(value) { + this[kMessageStream].isMonitoringConnection = value; + } + get isMonitoringConnection() { + return this[kMessageStream].isMonitoringConnection; + } + get serviceId() { + var _a; + return (_a = this.hello) === null || _a === void 0 ? void 0 : _a.serviceId; + } + get loadBalanced() { + return this.description.loadBalanced; + } + get generation() { + return this[kGeneration] || 0; + } + set generation(generation) { + this[kGeneration] = generation; + } + get idleTime() { + return (0, utils_1.calculateDurationInMs)(this[kLastUseTime]); + } + get clusterTime() { + return this[kClusterTime]; + } + get stream() { + return this[kStream]; + } + markAvailable() { + this[kLastUseTime] = (0, utils_1.now)(); + } + onError(error) { + if (this.closed) { + return; + } + this[kStream].destroy(error); + this.closed = true; + for (const op of this[kQueue].values()) { + op.cb(error); + } + this[kQueue].clear(); + this.emit(Connection.CLOSE); + } + onClose() { + if (this.closed) { + return; + } + this.closed = true; + const message = `connection ${this.id} to ${this.address} closed`; + for (const op of this[kQueue].values()) { + op.cb(new error_1.MongoNetworkError(message)); + } + this[kQueue].clear(); + this.emit(Connection.CLOSE); + } + onTimeout() { + if (this.closed) { + return; + } + this[kDelayedTimeoutId] = (0, timers_1.setTimeout)(() => { + this[kStream].destroy(); + this.closed = true; + const message = `connection ${this.id} to ${this.address} timed out`; + const beforeHandshake = this.hello == null; + for (const op of this[kQueue].values()) { + op.cb(new error_1.MongoNetworkTimeoutError(message, { beforeHandshake })); + } + this[kQueue].clear(); + this.emit(Connection.CLOSE); + }, 1).unref(); // No need for this timer to hold the event loop open + } + onMessage(message) { + const delayedTimeoutId = this[kDelayedTimeoutId]; + if (delayedTimeoutId != null) { + clearTimeout(delayedTimeoutId); + this[kDelayedTimeoutId] = null; + } + // always emit the message, in case we are streaming + this.emit('message', message); + const operationDescription = this[kQueue].get(message.responseTo); + if (!operationDescription) { + return; + } + const callback = operationDescription.cb; + // SERVER-45775: For exhaust responses we should be able to use the same requestId to + // track response, however the server currently synthetically produces remote requests + // making the `responseTo` change on each response + this[kQueue].delete(message.responseTo); + if ('moreToCome' in message && message.moreToCome) { + // requeue the callback for next synthetic request + this[kQueue].set(message.requestId, operationDescription); + } + else if (operationDescription.socketTimeoutOverride) { + this[kStream].setTimeout(this.socketTimeoutMS); + } + try { + // Pass in the entire description because it has BSON parsing options + message.parse(operationDescription); + } + catch (err) { + // If this error is generated by our own code, it will already have the correct class applied + // if it is not, then it is coming from a catastrophic data parse failure or the BSON library + // in either case, it should not be wrapped + callback(err); + return; + } + if (message.documents[0]) { + const document = message.documents[0]; + const session = operationDescription.session; + if (session) { + (0, sessions_1.updateSessionFromResponse)(session, document); + } + if (document.$clusterTime) { + this[kClusterTime] = document.$clusterTime; + this.emit(Connection.CLUSTER_TIME_RECEIVED, document.$clusterTime); + } + if (operationDescription.command) { + if (document.writeConcernError) { + callback(new error_1.MongoWriteConcernError(document.writeConcernError, document)); + return; + } + if (document.ok === 0 || document.$err || document.errmsg || document.code) { + callback(new error_1.MongoServerError(document)); + return; + } + } + else { + // Pre 3.2 support + if (document.ok === 0 || document.$err || document.errmsg) { + callback(new error_1.MongoServerError(document)); + return; + } + } + } + callback(undefined, operationDescription.fullResult ? message : message.documents[0]); + } + destroy(options, callback) { + if (typeof options === 'function') { + callback = options; + options = { force: false }; + } + this.removeAllListeners(Connection.PINNED); + this.removeAllListeners(Connection.UNPINNED); + options = Object.assign({ force: false }, options); + if (this[kStream] == null || this.destroyed) { + this.destroyed = true; + if (typeof callback === 'function') { + callback(); + } + return; + } + if (options.force) { + this[kStream].destroy(); + this.destroyed = true; + if (typeof callback === 'function') { + callback(); + } + return; + } + this[kStream].end(() => { + this.destroyed = true; + if (typeof callback === 'function') { + callback(); + } + }); + } + command(ns, cmd, options, callback) { + if (!(ns instanceof utils_1.MongoDBNamespace)) { + // TODO(NODE-3483): Replace this with a MongoCommandError + throw new error_1.MongoRuntimeError('Must provide a MongoDBNamespace instance'); + } + const readPreference = (0, shared_1.getReadPreference)(cmd, options); + const shouldUseOpMsg = supportsOpMsg(this); + const session = options === null || options === void 0 ? void 0 : options.session; + let clusterTime = this.clusterTime; + let finalCmd = Object.assign({}, cmd); + if (this.serverApi) { + const { version, strict, deprecationErrors } = this.serverApi; + finalCmd.apiVersion = version; + if (strict != null) + finalCmd.apiStrict = strict; + if (deprecationErrors != null) + finalCmd.apiDeprecationErrors = deprecationErrors; + } + if (hasSessionSupport(this) && session) { + if (session.clusterTime && + clusterTime && + session.clusterTime.clusterTime.greaterThan(clusterTime.clusterTime)) { + clusterTime = session.clusterTime; + } + const err = (0, sessions_1.applySession)(session, finalCmd, options); + if (err) { + return callback(err); + } + } + // if we have a known cluster time, gossip it + if (clusterTime) { + finalCmd.$clusterTime = clusterTime; + } + if ((0, shared_1.isSharded)(this) && !shouldUseOpMsg && readPreference && readPreference.mode !== 'primary') { + finalCmd = { + $query: finalCmd, + $readPreference: readPreference.toJSON() + }; + } + const commandOptions = Object.assign({ + command: true, + numberToSkip: 0, + numberToReturn: -1, + checkKeys: false, + // This value is not overridable + secondaryOk: readPreference.secondaryOk() + }, options); + const cmdNs = `${ns.db}.$cmd`; + const message = shouldUseOpMsg + ? new commands_1.Msg(cmdNs, finalCmd, commandOptions) + : new commands_1.Query(cmdNs, finalCmd, commandOptions); + try { + write(this, message, commandOptions, callback); + } + catch (err) { + callback(err); + } + } + getMore(ns, cursorId, options, callback) { + const fullResult = !!options[kFullResult]; + const wireVersion = (0, utils_1.maxWireVersion)(this); + if (!cursorId) { + // TODO(NODE-3483): Replace this with a MongoCommandError + callback(new error_1.MongoRuntimeError('Invalid internal cursor state, no known cursor id')); + return; + } + if (wireVersion < 4) { + const getMoreOp = new commands_1.GetMore(ns.toString(), cursorId, { numberToReturn: options.batchSize }); + const queryOptions = (0, shared_1.applyCommonQueryOptions)({}, Object.assign(options, { ...(0, bson_1.pluckBSONSerializeOptions)(options) })); + queryOptions[kFullResult] = true; + queryOptions.command = true; + write(this, getMoreOp, queryOptions, (err, response) => { + if (fullResult) + return callback(err, response); + if (err) + return callback(err); + callback(undefined, { cursor: { id: response.cursorId, nextBatch: response.documents } }); + }); + return; + } + const getMoreCmd = { + getMore: cursorId, + collection: ns.collection + }; + if (typeof options.batchSize === 'number') { + getMoreCmd.batchSize = Math.abs(options.batchSize); + } + if (typeof options.maxAwaitTimeMS === 'number') { + getMoreCmd.maxTimeMS = options.maxAwaitTimeMS; + } + // we check for undefined specifically here to allow falsy values + // eslint-disable-next-line no-restricted-syntax + if (options.comment !== undefined) { + getMoreCmd.comment = options.comment; + } + const commandOptions = Object.assign({ + returnFieldSelector: null, + documentsReturnedIn: 'nextBatch' + }, options); + this.command(ns, getMoreCmd, commandOptions, callback); + } + killCursors(ns, cursorIds, options, callback) { + if (!cursorIds || !Array.isArray(cursorIds)) { + // TODO(NODE-3483): Replace this with a MongoCommandError + throw new error_1.MongoRuntimeError(`Invalid list of cursor ids provided: ${cursorIds}`); + } + if ((0, utils_1.maxWireVersion)(this) < 4) { + try { + write(this, new commands_1.KillCursor(ns.toString(), cursorIds), { noResponse: true, ...options }, callback); + } + catch (err) { + callback(err); + } + return; + } + this.command(ns, { killCursors: ns.collection, cursors: cursorIds }, { [kFullResult]: true, ...options }, (err, response) => { + if (err || !response) + return callback(err); + if (response.cursorNotFound) { + return callback(new error_1.MongoNetworkError('cursor killed or timed out'), null); + } + if (!Array.isArray(response.documents) || response.documents.length === 0) { + return callback( + // TODO(NODE-3483) + new error_1.MongoRuntimeError(`invalid killCursors result returned for cursor id ${cursorIds[0]}`)); + } + callback(undefined, response.documents[0]); + }); + } +} +exports.Connection = Connection; +/** @event */ +Connection.COMMAND_STARTED = constants_1.COMMAND_STARTED; +/** @event */ +Connection.COMMAND_SUCCEEDED = constants_1.COMMAND_SUCCEEDED; +/** @event */ +Connection.COMMAND_FAILED = constants_1.COMMAND_FAILED; +/** @event */ +Connection.CLUSTER_TIME_RECEIVED = constants_1.CLUSTER_TIME_RECEIVED; +/** @event */ +Connection.CLOSE = constants_1.CLOSE; +/** @event */ +Connection.MESSAGE = constants_1.MESSAGE; +/** @event */ +Connection.PINNED = constants_1.PINNED; +/** @event */ +Connection.UNPINNED = constants_1.UNPINNED; +/** @internal */ +class CryptoConnection extends Connection { + constructor(stream, options) { + super(stream, options); + this[kAutoEncrypter] = options.autoEncrypter; + } + /** @internal @override */ + command(ns, cmd, options, callback) { + const autoEncrypter = this[kAutoEncrypter]; + if (!autoEncrypter) { + return callback(new error_1.MongoMissingDependencyError('No AutoEncrypter available for encryption')); + } + const serverWireVersion = (0, utils_1.maxWireVersion)(this); + if (serverWireVersion === 0) { + // This means the initial handshake hasn't happened yet + return super.command(ns, cmd, options, callback); + } + if (serverWireVersion < 8) { + callback(new error_1.MongoCompatibilityError('Auto-encryption requires a minimum MongoDB version of 4.2')); + return; + } + autoEncrypter.encrypt(ns.toString(), cmd, options, (err, encrypted) => { + if (err || encrypted == null) { + callback(err, null); + return; + } + super.command(ns, encrypted, options, (err, response) => { + if (err || response == null) { + callback(err, response); + return; + } + autoEncrypter.decrypt(response, options, callback); + }); + }); + } +} +exports.CryptoConnection = CryptoConnection; +/** @internal */ +function hasSessionSupport(conn) { + const description = conn.description; + return description.logicalSessionTimeoutMinutes != null || !!description.loadBalanced; +} +exports.hasSessionSupport = hasSessionSupport; +function supportsOpMsg(conn) { + const description = conn.description; + if (description == null) { + return false; + } + return (0, utils_1.maxWireVersion)(conn) >= 6 && !description.__nodejs_mock_server__; +} +function streamIdentifier(stream, options) { + if (options.proxyHost) { + // If proxy options are specified, the properties of `stream` itself + // will not accurately reflect what endpoint this is connected to. + return options.hostAddress.toString(); + } + if (typeof stream.address === 'function') { + return `${stream.remoteAddress}:${stream.remotePort}`; + } + return (0, utils_1.uuidV4)().toString('hex'); +} +function write(conn, command, options, callback) { + if (typeof options === 'function') { + callback = options; + } + options = options !== null && options !== void 0 ? options : {}; + const operationDescription = { + requestId: command.requestId, + cb: callback, + session: options.session, + fullResult: !!options[kFullResult], + noResponse: typeof options.noResponse === 'boolean' ? options.noResponse : false, + documentsReturnedIn: options.documentsReturnedIn, + command: !!options.command, + // for BSON parsing + promoteLongs: typeof options.promoteLongs === 'boolean' ? options.promoteLongs : true, + promoteValues: typeof options.promoteValues === 'boolean' ? options.promoteValues : true, + promoteBuffers: typeof options.promoteBuffers === 'boolean' ? options.promoteBuffers : false, + bsonRegExp: typeof options.bsonRegExp === 'boolean' ? options.bsonRegExp : false, + enableUtf8Validation: typeof options.enableUtf8Validation === 'boolean' ? options.enableUtf8Validation : true, + raw: typeof options.raw === 'boolean' ? options.raw : false, + started: 0 + }; + if (conn[kDescription] && conn[kDescription].compressor) { + operationDescription.agreedCompressor = conn[kDescription].compressor; + if (conn[kDescription].zlibCompressionLevel) { + operationDescription.zlibCompressionLevel = conn[kDescription].zlibCompressionLevel; + } + } + if (typeof options.socketTimeoutMS === 'number') { + operationDescription.socketTimeoutOverride = true; + conn[kStream].setTimeout(options.socketTimeoutMS); + } + // if command monitoring is enabled we need to modify the callback here + if (conn.monitorCommands) { + conn.emit(Connection.COMMAND_STARTED, new command_monitoring_events_1.CommandStartedEvent(conn, command)); + operationDescription.started = (0, utils_1.now)(); + operationDescription.cb = (err, reply) => { + if (err) { + conn.emit(Connection.COMMAND_FAILED, new command_monitoring_events_1.CommandFailedEvent(conn, command, err, operationDescription.started)); + } + else { + if (reply && (reply.ok === 0 || reply.$err)) { + conn.emit(Connection.COMMAND_FAILED, new command_monitoring_events_1.CommandFailedEvent(conn, command, reply, operationDescription.started)); + } + else { + conn.emit(Connection.COMMAND_SUCCEEDED, new command_monitoring_events_1.CommandSucceededEvent(conn, command, reply, operationDescription.started)); + } + } + if (typeof callback === 'function') { + callback(err, reply); + } + }; + } + if (!operationDescription.noResponse) { + conn[kQueue].set(operationDescription.requestId, operationDescription); + } + try { + conn[kMessageStream].writeCommand(command, operationDescription); + } + catch (e) { + if (!operationDescription.noResponse) { + conn[kQueue].delete(operationDescription.requestId); + operationDescription.cb(e); + return; + } + } + if (operationDescription.noResponse) { + operationDescription.cb(); + } +} +//# sourceMappingURL=connection.js.map \ No newline at end of file diff --git a/ts-ticket-office-service/node_modules/mongodb/lib/cmap/connection.js.map b/ts-ticket-office-service/node_modules/mongodb/lib/cmap/connection.js.map new file mode 100644 index 000000000..2dc8ee3f5 --- /dev/null +++ b/ts-ticket-office-service/node_modules/mongodb/lib/cmap/connection.js.map @@ -0,0 +1 @@ +{"version":3,"file":"connection.js","sourceRoot":"","sources":["../../src/cmap/connection.ts"],"names":[],"mappings":";;;AAAA,mCAAoC;AAEpC,kCAAoG;AACpG,4CASsB;AAEtB,oCAQkB;AAElB,gDAAsE;AAEtE,0CAAqF;AACrF,oCASkB;AAGlB,2EAIqC;AACrC,yCAQoB;AAEpB,qDAAuE;AACvE,6DAAmF;AACnF,mDAA+F;AAE/F,gBAAgB;AAChB,MAAM,OAAO,GAAG,MAAM,CAAC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AAqB,CAAC,IAAI,EAAE,OAAO,EAAE,KAAK,EAAE,oBAAoB,CAAC,OAAO,CAAC,CAC9E,CAAC;iBACH;aACF;YAED,IAAI,OAAO,QAAQ,KAAK,UAAU,EAAE;gBAClC,QAAQ,CAAC,GAAG,EAAE,KAAK,CAAC,CAAC;aACtB;QACH,CAAC,CAAC;KACH;IAED,IAAI,CAAC,oBAAoB,CAAC,UAAU,EAAE;QACpC,IAAI,CAAC,MAAM,CAAC,CAAC,GAAG,CAAC,oBAAoB,CAAC,SAAS,EAAE,oBAAoB,CAAC,CAAC;KACxE;IAED,IAAI;QACF,IAAI,CAAC,cAAc,CAAC,CAAC,YAAY,CAAC,OAAO,EAAE,oBAAoB,CAAC,CAAC;KAClE;IAAC,OAAO,CAAC,EAAE;QACV,IAAI,CAAC,oBAAoB,CAAC,UAAU,EAAE;YACpC,IAAI,CAAC,MAAM,CAAC,CAAC,MAAM,CAAC,oBAAoB,CAAC,SAAS,CAAC,CAAC;YACpD,oBAAoB,CAAC,EAAE,CAAC,CAAC,CAAC,CAAC;YAC3B,OAAO;SACR;KACF;IAED,IAAI,oBAAoB,CAAC,UAAU,EAAE;QACnC,oBAAoB,CAAC,EAAE,EAAE,CAAC;KAC3B;AACH,CAAC"} \ No newline at end of file diff --git a/ts-ticket-office-service/node_modules/mongodb/lib/cmap/connection_pool.js b/ts-ticket-office-service/node_modules/mongodb/lib/cmap/connection_pool.js new file mode 100644 index 000000000..257572af4 --- /dev/null +++ b/ts-ticket-office-service/node_modules/mongodb/lib/cmap/connection_pool.js @@ -0,0 +1,497 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.ConnectionPool = void 0; +const Denque = require("denque"); +const timers_1 = require("timers"); +const constants_1 = require("../constants"); +const error_1 = require("../error"); +const logger_1 = require("../logger"); +const mongo_types_1 = require("../mongo_types"); +const utils_1 = require("../utils"); +const connect_1 = require("./connect"); +const connection_1 = require("./connection"); +const connection_pool_events_1 = require("./connection_pool_events"); +const errors_1 = require("./errors"); +const metrics_1 = require("./metrics"); +/** @internal */ +const kLogger = Symbol('logger'); +/** @internal */ +const kConnections = Symbol('connections'); +/** @internal */ +const kPending = Symbol('pending'); +/** @internal */ +const kCheckedOut = Symbol('checkedOut'); +/** @internal */ +const kMinPoolSizeTimer = Symbol('minPoolSizeTimer'); +/** @internal */ +const kGeneration = Symbol('generation'); +/** @internal */ +const kServiceGenerations = Symbol('serviceGenerations'); +/** @internal */ +const kConnectionCounter = Symbol('connectionCounter'); +/** @internal */ +const kCancellationToken = Symbol('cancellationToken'); +/** @internal */ +const kWaitQueue = Symbol('waitQueue'); +/** @internal */ +const kCancelled = Symbol('cancelled'); +/** @internal */ +const kMetrics = Symbol('metrics'); +/** @internal */ +const kProcessingWaitQueue = Symbol('processingWaitQueue'); +/** + * A pool of connections which dynamically resizes, and emit events related to pool activity + * @internal + */ +class ConnectionPool extends mongo_types_1.TypedEventEmitter { + /** @internal */ + constructor(options) { + var _a, _b, _c, _d, _e; + super(); + this.closed = false; + this.options = Object.freeze({ + ...options, + connectionType: connection_1.Connection, + maxPoolSize: (_a = options.maxPoolSize) !== null && _a !== void 0 ? _a : 100, + minPoolSize: (_b = options.minPoolSize) !== null && _b !== void 0 ? _b : 0, + maxConnecting: (_c = options.maxConnecting) !== null && _c !== void 0 ? _c : 2, + maxIdleTimeMS: (_d = options.maxIdleTimeMS) !== null && _d !== void 0 ? _d : 0, + waitQueueTimeoutMS: (_e = options.waitQueueTimeoutMS) !== null && _e !== void 0 ? _e : 0, + autoEncrypter: options.autoEncrypter, + metadata: options.metadata + }); + if (this.options.minPoolSize > this.options.maxPoolSize) { + throw new error_1.MongoInvalidArgumentError('Connection pool minimum size must not be greater than maximum pool size'); + } + this[kLogger] = new logger_1.Logger('ConnectionPool'); + this[kConnections] = new Denque(); + this[kPending] = 0; + this[kCheckedOut] = 0; + this[kMinPoolSizeTimer] = undefined; + this[kGeneration] = 0; + this[kServiceGenerations] = new Map(); + this[kConnectionCounter] = (0, utils_1.makeCounter)(1); + this[kCancellationToken] = new mongo_types_1.CancellationToken(); + this[kCancellationToken].setMaxListeners(Infinity); + this[kWaitQueue] = new Denque(); + this[kMetrics] = new metrics_1.ConnectionPoolMetrics(); + this[kProcessingWaitQueue] = false; + process.nextTick(() => { + this.emit(ConnectionPool.CONNECTION_POOL_CREATED, new connection_pool_events_1.ConnectionPoolCreatedEvent(this)); + ensureMinPoolSize(this); + }); + } + /** The address of the endpoint the pool is connected to */ + get address() { + return this.options.hostAddress.toString(); + } + /** An integer representing the SDAM generation of the pool */ + get generation() { + return this[kGeneration]; + } + /** An integer expressing how many total connections (available + pending + in use) the pool currently has */ + get totalConnectionCount() { + return (this.availableConnectionCount + this.pendingConnectionCount + this.currentCheckedOutCount); + } + /** An integer expressing how many connections are currently available in the pool. */ + get availableConnectionCount() { + return this[kConnections].length; + } + get pendingConnectionCount() { + return this[kPending]; + } + get currentCheckedOutCount() { + return this[kCheckedOut]; + } + get waitQueueSize() { + return this[kWaitQueue].length; + } + get loadBalanced() { + return this.options.loadBalanced; + } + get serviceGenerations() { + return this[kServiceGenerations]; + } + /** + * Get the metrics information for the pool when a wait queue timeout occurs. + */ + waitQueueErrorMetrics() { + return this[kMetrics].info(this.options.maxPoolSize); + } + /** + * Check a connection out of this pool. The connection will continue to be tracked, but no reference to it + * will be held by the pool. This means that if a connection is checked out it MUST be checked back in or + * explicitly destroyed by the new owner. + */ + checkOut(callback) { + this.emit(ConnectionPool.CONNECTION_CHECK_OUT_STARTED, new connection_pool_events_1.ConnectionCheckOutStartedEvent(this)); + if (this.closed) { + this.emit(ConnectionPool.CONNECTION_CHECK_OUT_FAILED, new connection_pool_events_1.ConnectionCheckOutFailedEvent(this, 'poolClosed')); + callback(new errors_1.PoolClosedError(this)); + return; + } + const waitQueueMember = { callback }; + const waitQueueTimeoutMS = this.options.waitQueueTimeoutMS; + if (waitQueueTimeoutMS) { + waitQueueMember.timer = (0, timers_1.setTimeout)(() => { + waitQueueMember[kCancelled] = true; + waitQueueMember.timer = undefined; + this.emit(ConnectionPool.CONNECTION_CHECK_OUT_FAILED, new connection_pool_events_1.ConnectionCheckOutFailedEvent(this, 'timeout')); + waitQueueMember.callback(new errors_1.WaitQueueTimeoutError(this.loadBalanced + ? this.waitQueueErrorMetrics() + : 'Timed out while checking out a connection from connection pool', this.address)); + }, waitQueueTimeoutMS); + } + this[kWaitQueue].push(waitQueueMember); + process.nextTick(processWaitQueue, this); + } + /** + * Check a connection into the pool. + * + * @param connection - The connection to check in + */ + checkIn(connection) { + const poolClosed = this.closed; + const stale = connectionIsStale(this, connection); + const willDestroy = !!(poolClosed || stale || connection.closed); + if (!willDestroy) { + connection.markAvailable(); + this[kConnections].unshift(connection); + } + this[kCheckedOut]--; + this.emit(ConnectionPool.CONNECTION_CHECKED_IN, new connection_pool_events_1.ConnectionCheckedInEvent(this, connection)); + if (willDestroy) { + const reason = connection.closed ? 'error' : poolClosed ? 'poolClosed' : 'stale'; + destroyConnection(this, connection, reason); + } + process.nextTick(processWaitQueue, this); + } + /** + * Clear the pool + * + * Pool reset is handled by incrementing the pool's generation count. Any existing connection of a + * previous generation will eventually be pruned during subsequent checkouts. + */ + clear(serviceId) { + if (this.loadBalanced && serviceId) { + const sid = serviceId.toHexString(); + const generation = this.serviceGenerations.get(sid); + // Only need to worry if the generation exists, since it should + // always be there but typescript needs the check. + if (generation == null) { + // TODO(NODE-3483) + throw new error_1.MongoRuntimeError('Service generations are required in load balancer mode.'); + } + else { + // Increment the generation for the service id. + this.serviceGenerations.set(sid, generation + 1); + } + } + else { + this[kGeneration] += 1; + } + this.emit('connectionPoolCleared', new connection_pool_events_1.ConnectionPoolClearedEvent(this, serviceId)); + } + close(_options, _cb) { + let options = _options; + const callback = (_cb !== null && _cb !== void 0 ? _cb : _options); + if (typeof options === 'function') { + options = {}; + } + options = Object.assign({ force: false }, options); + if (this.closed) { + return callback(); + } + // immediately cancel any in-flight connections + this[kCancellationToken].emit('cancel'); + // drain the wait queue + while (this.waitQueueSize) { + const waitQueueMember = this[kWaitQueue].pop(); + if (waitQueueMember) { + if (waitQueueMember.timer) { + clearTimeout(waitQueueMember.timer); + } + if (!waitQueueMember[kCancelled]) { + // TODO(NODE-3483): Replace with MongoConnectionPoolClosedError + waitQueueMember.callback(new error_1.MongoRuntimeError('Connection pool closed')); + } + } + } + // clear the min pool size timer + const minPoolSizeTimer = this[kMinPoolSizeTimer]; + if (minPoolSizeTimer) { + clearTimeout(minPoolSizeTimer); + } + // end the connection counter + if (typeof this[kConnectionCounter].return === 'function') { + this[kConnectionCounter].return(undefined); + } + // mark the pool as closed immediately + this.closed = true; + (0, utils_1.eachAsync)(this[kConnections].toArray(), (conn, cb) => { + this.emit(ConnectionPool.CONNECTION_CLOSED, new connection_pool_events_1.ConnectionClosedEvent(this, conn, 'poolClosed')); + conn.destroy(options, cb); + }, err => { + this[kConnections].clear(); + this.emit(ConnectionPool.CONNECTION_POOL_CLOSED, new connection_pool_events_1.ConnectionPoolClosedEvent(this)); + callback(err); + }); + } + /** + * Runs a lambda with an implicitly checked out connection, checking that connection back in when the lambda + * has completed by calling back. + * + * NOTE: please note the required signature of `fn` + * + * @remarks When in load balancer mode, connections can be pinned to cursors or transactions. + * In these cases we pass the connection in to this method to ensure it is used and a new + * connection is not checked out. + * + * @param conn - A pinned connection for use in load balancing mode. + * @param fn - A function which operates on a managed connection + * @param callback - The original callback + */ + withConnection(conn, fn, callback) { + if (conn) { + // use the provided connection, and do _not_ check it in after execution + fn(undefined, conn, (fnErr, result) => { + if (typeof callback === 'function') { + if (fnErr) { + callback(fnErr); + } + else { + callback(undefined, result); + } + } + }); + return; + } + this.checkOut((err, conn) => { + // don't callback with `err` here, we might want to act upon it inside `fn` + fn(err, conn, (fnErr, result) => { + if (typeof callback === 'function') { + if (fnErr) { + callback(fnErr); + } + else { + callback(undefined, result); + } + } + if (conn) { + this.checkIn(conn); + } + }); + }); + } +} +exports.ConnectionPool = ConnectionPool; +/** + * Emitted when the connection pool is created. + * @event + */ +ConnectionPool.CONNECTION_POOL_CREATED = constants_1.CONNECTION_POOL_CREATED; +/** + * Emitted once when the connection pool is closed + * @event + */ +ConnectionPool.CONNECTION_POOL_CLOSED = constants_1.CONNECTION_POOL_CLOSED; +/** + * Emitted each time the connection pool is cleared and it's generation incremented + * @event + */ +ConnectionPool.CONNECTION_POOL_CLEARED = constants_1.CONNECTION_POOL_CLEARED; +/** + * Emitted when a connection is created. + * @event + */ +ConnectionPool.CONNECTION_CREATED = constants_1.CONNECTION_CREATED; +/** + * Emitted when a connection becomes established, and is ready to use + * @event + */ +ConnectionPool.CONNECTION_READY = constants_1.CONNECTION_READY; +/** + * Emitted when a connection is closed + * @event + */ +ConnectionPool.CONNECTION_CLOSED = constants_1.CONNECTION_CLOSED; +/** + * Emitted when an attempt to check out a connection begins + * @event + */ +ConnectionPool.CONNECTION_CHECK_OUT_STARTED = constants_1.CONNECTION_CHECK_OUT_STARTED; +/** + * Emitted when an attempt to check out a connection fails + * @event + */ +ConnectionPool.CONNECTION_CHECK_OUT_FAILED = constants_1.CONNECTION_CHECK_OUT_FAILED; +/** + * Emitted each time a connection is successfully checked out of the connection pool + * @event + */ +ConnectionPool.CONNECTION_CHECKED_OUT = constants_1.CONNECTION_CHECKED_OUT; +/** + * Emitted each time a connection is successfully checked into the connection pool + * @event + */ +ConnectionPool.CONNECTION_CHECKED_IN = constants_1.CONNECTION_CHECKED_IN; +function ensureMinPoolSize(pool) { + const minPoolSize = pool.options.minPoolSize; + if (pool.closed || minPoolSize === 0) { + return; + } + if (pool.totalConnectionCount < minPoolSize && + pool.pendingConnectionCount < pool.options.maxConnecting) { + // NOTE: ensureMinPoolSize should not try to get all the pending + // connection permits because that potentially delays the availability of + // the connection to a checkout request + createConnection(pool, (err, connection) => { + pool[kPending]--; + if (!err && connection) { + pool[kConnections].push(connection); + process.nextTick(processWaitQueue, pool); + } + pool[kMinPoolSizeTimer] = (0, timers_1.setTimeout)(() => ensureMinPoolSize(pool), 10); + }); + } + else { + pool[kMinPoolSizeTimer] = (0, timers_1.setTimeout)(() => ensureMinPoolSize(pool), 100); + } +} +function connectionIsStale(pool, connection) { + const serviceId = connection.serviceId; + if (pool.loadBalanced && serviceId) { + const sid = serviceId.toHexString(); + const generation = pool.serviceGenerations.get(sid); + return connection.generation !== generation; + } + return connection.generation !== pool[kGeneration]; +} +function connectionIsIdle(pool, connection) { + return !!(pool.options.maxIdleTimeMS && connection.idleTime > pool.options.maxIdleTimeMS); +} +function createConnection(pool, callback) { + const connectOptions = { + ...pool.options, + id: pool[kConnectionCounter].next().value, + generation: pool[kGeneration], + cancellationToken: pool[kCancellationToken] + }; + pool[kPending]++; + // This is our version of a "virtual" no-I/O connection as the spec requires + pool.emit(ConnectionPool.CONNECTION_CREATED, new connection_pool_events_1.ConnectionCreatedEvent(pool, { id: connectOptions.id })); + (0, connect_1.connect)(connectOptions, (err, connection) => { + if (err || !connection) { + pool[kLogger].debug(`connection attempt failed with error [${JSON.stringify(err)}]`); + callback(err); + return; + } + // The pool might have closed since we started trying to create a connection + if (pool.closed) { + pool[kPending]--; + connection.destroy({ force: true }); + return; + } + // forward all events from the connection to the pool + for (const event of [...constants_1.APM_EVENTS, connection_1.Connection.CLUSTER_TIME_RECEIVED]) { + connection.on(event, (e) => pool.emit(event, e)); + } + if (pool.loadBalanced) { + connection.on(connection_1.Connection.PINNED, pinType => pool[kMetrics].markPinned(pinType)); + connection.on(connection_1.Connection.UNPINNED, pinType => pool[kMetrics].markUnpinned(pinType)); + const serviceId = connection.serviceId; + if (serviceId) { + let generation; + const sid = serviceId.toHexString(); + if ((generation = pool.serviceGenerations.get(sid))) { + connection.generation = generation; + } + else { + pool.serviceGenerations.set(sid, 0); + connection.generation = 0; + } + } + } + connection.markAvailable(); + pool.emit(ConnectionPool.CONNECTION_READY, new connection_pool_events_1.ConnectionReadyEvent(pool, connection)); + callback(undefined, connection); + return; + }); +} +function destroyConnection(pool, connection, reason) { + pool.emit(ConnectionPool.CONNECTION_CLOSED, new connection_pool_events_1.ConnectionClosedEvent(pool, connection, reason)); + // destroy the connection + process.nextTick(() => connection.destroy()); +} +function processWaitQueue(pool) { + if (pool.closed || pool[kProcessingWaitQueue]) { + return; + } + pool[kProcessingWaitQueue] = true; + while (pool.waitQueueSize) { + const waitQueueMember = pool[kWaitQueue].peekFront(); + if (!waitQueueMember) { + pool[kWaitQueue].shift(); + continue; + } + if (waitQueueMember[kCancelled]) { + pool[kWaitQueue].shift(); + continue; + } + if (!pool.availableConnectionCount) { + break; + } + const connection = pool[kConnections].shift(); + if (!connection) { + break; + } + const isStale = connectionIsStale(pool, connection); + const isIdle = connectionIsIdle(pool, connection); + if (!isStale && !isIdle && !connection.closed) { + pool[kCheckedOut]++; + pool.emit(ConnectionPool.CONNECTION_CHECKED_OUT, new connection_pool_events_1.ConnectionCheckedOutEvent(pool, connection)); + if (waitQueueMember.timer) { + clearTimeout(waitQueueMember.timer); + } + pool[kWaitQueue].shift(); + waitQueueMember.callback(undefined, connection); + } + else { + const reason = connection.closed ? 'error' : isStale ? 'stale' : 'idle'; + destroyConnection(pool, connection, reason); + } + } + const { maxPoolSize, maxConnecting } = pool.options; + while (pool.waitQueueSize > 0 && + pool.pendingConnectionCount < maxConnecting && + (maxPoolSize === 0 || pool.totalConnectionCount < maxPoolSize)) { + const waitQueueMember = pool[kWaitQueue].shift(); + if (!waitQueueMember || waitQueueMember[kCancelled]) { + continue; + } + createConnection(pool, (err, connection) => { + pool[kPending]--; + if (waitQueueMember[kCancelled]) { + if (!err && connection) { + pool[kConnections].push(connection); + } + } + else { + if (err) { + pool.emit(ConnectionPool.CONNECTION_CHECK_OUT_FAILED, new connection_pool_events_1.ConnectionCheckOutFailedEvent(pool, err)); + } + else if (connection) { + pool[kCheckedOut]++; + pool.emit(ConnectionPool.CONNECTION_CHECKED_OUT, new connection_pool_events_1.ConnectionCheckedOutEvent(pool, connection)); + } + if (waitQueueMember.timer) { + clearTimeout(waitQueueMember.timer); + } + waitQueueMember.callback(err, connection); + } + process.nextTick(processWaitQueue, pool); + }); + } + pool[kProcessingWaitQueue] = false; +} +//# sourceMappingURL=connection_pool.js.map \ No newline at end of file diff --git a/ts-ticket-office-service/node_modules/mongodb/lib/cmap/connection_pool.js.map b/ts-ticket-office-service/node_modules/mongodb/lib/cmap/connection_pool.js.map new file mode 100644 index 000000000..d0dd20db2 --- /dev/null +++ b/ts-ticket-office-service/node_modules/mongodb/lib/cmap/connection_pool.js.map @@ -0,0 +1 @@ +{"version":3,"file":"connection_pool.js","sourceRoot":"","sources":["../../src/cmap/connection_pool.ts"],"names":[],"mappings":";;;AAAA,iCAAkC;AAClC,mCAAoC;AAGpC,4CAYsB;AACtB,oCAAoF;AACpF,sCAAmC;AACnC,gDAAsE;AACtE,oCAA4D;AAC5D,uCAAoC;AACpC,6CAA+E;AAC/E,qEAWkC;AAClC,qCAAkE;AAClE,uCAAkD;AAElD,gBAAgB;AAChB,MAAM,OAAO,GAAG,MAAM,CAAC,QAAQ,CAAC,CAAC;AACjC,gBAAgB;AAChB,MAAM,YAAY,GAAG,MAAM,CAAC,aAAa,CAAC,CAAC;AAC3C,gBAAgB;AAChB,MAAM,QAAQ,GAAG,MAAM,CAAC,SAAS,CAAC,CAAC;AACnC,gBAAgB;AAChB,MAAM,WAAW,GAAG,MAAM,CAAC,YAAY,CAAC,CAAC;AACzC,gBAAgB;AAChB,MAAM,iBAAiB,GAAG,MAAM,CAAC,kBAAkB,CAAC,CAAC;AACrD,gBAAgB;AAChB,MAAM,WAAW,GAAG,MAAM,CAAC,YAAY,CAAC,CAAC;AACzC,gBAAgB;AAChB,MAAM,mBAAmB,GAAG,MAAM,CAAC,oBAAoB,CAAC,CAAC;AACzD,gBAAgB;AAChB,MAAM,kBAAkB,GAAG,MAAM,CAAC,mBAAmB,CAAC,CAAC;AACvD,gBAAgB;AAChB,MAAM,kBAAkB,GAAG,MAAM,CAAC,mBAAmB,CAAC,CAAC;AACvD,gBAAgB;AAChB,MAAM,UAAU,GAAG,MAAM,CAA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AG,EAAE,UAAU,EAAE,EAAE;YACzC,IAAI,CAAC,QAAQ,CAAC,EAAE,CAAC;YACjB,IAAI,eAAe,CAAC,UAAU,CAAC,EAAE;gBAC/B,IAAI,CAAC,GAAG,IAAI,UAAU,EAAE;oBACtB,IAAI,CAAC,YAAY,CAAC,CAAC,IAAI,CAAC,UAAU,CAAC,CAAC;iBACrC;aACF;iBAAM;gBACL,IAAI,GAAG,EAAE;oBACP,IAAI,CAAC,IAAI,CACP,cAAc,CAAC,2BAA2B,EAC1C,IAAI,sDAA6B,CAAC,IAAI,EAAE,GAAG,CAAC,CAC7C,CAAC;iBACH;qBAAM,IAAI,UAAU,EAAE;oBACrB,IAAI,CAAC,WAAW,CAAC,EAAE,CAAC;oBACpB,IAAI,CAAC,IAAI,CACP,cAAc,CAAC,sBAAsB,EACrC,IAAI,kDAAyB,CAAC,IAAI,EAAE,UAAU,CAAC,CAChD,CAAC;iBACH;gBAED,IAAI,eAAe,CAAC,KAAK,EAAE;oBACzB,YAAY,CAAC,eAAe,CAAC,KAAK,CAAC,CAAC;iBACrC;gBACD,eAAe,CAAC,QAAQ,CAAC,GAAG,EAAE,UAAU,CAAC,CAAC;aAC3C;YACD,OAAO,CAAC,QAAQ,CAAC,gBAAgB,EAAE,IAAI,CAAC,CAAC;QAC3C,CAAC,CAAC,CAAC;KACJ;IACD,IAAI,CAAC,oBAAoB,CAAC,GAAG,KAAK,CAAC;AACrC,CAAC"} \ No newline at end of file diff --git a/ts-ticket-office-service/node_modules/mongodb/lib/cmap/connection_pool_events.js b/ts-ticket-office-service/node_modules/mongodb/lib/cmap/connection_pool_events.js new file mode 100644 index 000000000..86aeaef8a --- /dev/null +++ b/ts-ticket-office-service/node_modules/mongodb/lib/cmap/connection_pool_events.js @@ -0,0 +1,147 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.ConnectionPoolClearedEvent = exports.ConnectionCheckedInEvent = exports.ConnectionCheckedOutEvent = exports.ConnectionCheckOutFailedEvent = exports.ConnectionCheckOutStartedEvent = exports.ConnectionClosedEvent = exports.ConnectionReadyEvent = exports.ConnectionCreatedEvent = exports.ConnectionPoolClosedEvent = exports.ConnectionPoolCreatedEvent = exports.ConnectionPoolMonitoringEvent = void 0; +/** + * The base export class for all monitoring events published from the connection pool + * @public + * @category Event + */ +class ConnectionPoolMonitoringEvent { + /** @internal */ + constructor(pool) { + this.time = new Date(); + this.address = pool.address; + } +} +exports.ConnectionPoolMonitoringEvent = ConnectionPoolMonitoringEvent; +/** + * An event published when a connection pool is created + * @public + * @category Event + */ +class ConnectionPoolCreatedEvent extends ConnectionPoolMonitoringEvent { + /** @internal */ + constructor(pool) { + super(pool); + this.options = pool.options; + } +} +exports.ConnectionPoolCreatedEvent = ConnectionPoolCreatedEvent; +/** + * An event published when a connection pool is closed + * @public + * @category Event + */ +class ConnectionPoolClosedEvent extends ConnectionPoolMonitoringEvent { + /** @internal */ + constructor(pool) { + super(pool); + } +} +exports.ConnectionPoolClosedEvent = ConnectionPoolClosedEvent; +/** + * An event published when a connection pool creates a new connection + * @public + * @category Event + */ +class ConnectionCreatedEvent extends ConnectionPoolMonitoringEvent { + /** @internal */ + constructor(pool, connection) { + super(pool); + this.connectionId = connection.id; + } +} +exports.ConnectionCreatedEvent = ConnectionCreatedEvent; +/** + * An event published when a connection is ready for use + * @public + * @category Event + */ +class ConnectionReadyEvent extends ConnectionPoolMonitoringEvent { + /** @internal */ + constructor(pool, connection) { + super(pool); + this.connectionId = connection.id; + } +} +exports.ConnectionReadyEvent = ConnectionReadyEvent; +/** + * An event published when a connection is closed + * @public + * @category Event + */ +class ConnectionClosedEvent extends ConnectionPoolMonitoringEvent { + /** @internal */ + constructor(pool, connection, reason) { + super(pool); + this.connectionId = connection.id; + this.reason = reason || 'unknown'; + this.serviceId = connection.serviceId; + } +} +exports.ConnectionClosedEvent = ConnectionClosedEvent; +/** + * An event published when a request to check a connection out begins + * @public + * @category Event + */ +class ConnectionCheckOutStartedEvent extends ConnectionPoolMonitoringEvent { + /** @internal */ + constructor(pool) { + super(pool); + } +} +exports.ConnectionCheckOutStartedEvent = ConnectionCheckOutStartedEvent; +/** + * An event published when a request to check a connection out fails + * @public + * @category Event + */ +class ConnectionCheckOutFailedEvent extends ConnectionPoolMonitoringEvent { + /** @internal */ + constructor(pool, reason) { + super(pool); + this.reason = reason; + } +} +exports.ConnectionCheckOutFailedEvent = ConnectionCheckOutFailedEvent; +/** + * An event published when a connection is checked out of the connection pool + * @public + * @category Event + */ +class ConnectionCheckedOutEvent extends ConnectionPoolMonitoringEvent { + /** @internal */ + constructor(pool, connection) { + super(pool); + this.connectionId = connection.id; + } +} +exports.ConnectionCheckedOutEvent = ConnectionCheckedOutEvent; +/** + * An event published when a connection is checked into the connection pool + * @public + * @category Event + */ +class ConnectionCheckedInEvent extends ConnectionPoolMonitoringEvent { + /** @internal */ + constructor(pool, connection) { + super(pool); + this.connectionId = connection.id; + } +} +exports.ConnectionCheckedInEvent = ConnectionCheckedInEvent; +/** + * An event published when a connection pool is cleared + * @public + * @category Event + */ +class ConnectionPoolClearedEvent extends ConnectionPoolMonitoringEvent { + /** @internal */ + constructor(pool, serviceId) { + super(pool); + this.serviceId = serviceId; + } +} +exports.ConnectionPoolClearedEvent = ConnectionPoolClearedEvent; +//# sourceMappingURL=connection_pool_events.js.map \ No newline at end of file diff --git a/ts-ticket-office-service/node_modules/mongodb/lib/cmap/connection_pool_events.js.map b/ts-ticket-office-service/node_modules/mongodb/lib/cmap/connection_pool_events.js.map new file mode 100644 index 000000000..47ecacd5a --- /dev/null +++ b/ts-ticket-office-service/node_modules/mongodb/lib/cmap/connection_pool_events.js.map @@ -0,0 +1 @@ +{"version":3,"file":"connection_pool_events.js","sourceRoot":"","sources":["../../src/cmap/connection_pool_events.ts"],"names":[],"mappings":";;;AAKA;;;;GAIG;AACH,MAAa,6BAA6B;IAMxC,gBAAgB;IAChB,YAAY,IAAoB;QAC9B,IAAI,CAAC,IAAI,GAAG,IAAI,IAAI,EAA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ACH,MAAa,8BAA+B,SAAQ,6BAA6B;IAC/E,gBAAgB;IAChB,YAAY,IAAoB;QAC9B,KAAK,CAAC,IAAI,CAAC,CAAC;IACd,CAAC;CACF;AALD,wEAKC;AAED;;;;GAIG;AACH,MAAa,6BAA8B,SAAQ,6BAA6B;IAI9E,gBAAgB;IAChB,YAAY,IAAoB,EAAE,MAAyB;QACzD,KAAK,CAAC,IAAI,CAAC,CAAC;QACZ,IAAI,CAAC,MAAM,GAAG,MAAM,CAAC;IACvB,CAAC;CACF;AATD,sEASC;AAED;;;;GAIG;AACH,MAAa,yBAA0B,SAAQ,6BAA6B;IAI1E,gBAAgB;IAChB,YAAY,IAAoB,EAAE,UAAsB;QACtD,KAAK,CAAC,IAAI,CAAC,CAAC;QACZ,IAAI,CAAC,YAAY,GAAG,UAAU,CAAC,EAAE,CAAC;IACpC,CAAC;CACF;AATD,8DASC;AAED;;;;GAIG;AACH,MAAa,wBAAyB,SAAQ,6BAA6B;IAIzE,gBAAgB;IAChB,YAAY,IAAoB,EAAE,UAAsB;QACtD,KAAK,CAAC,IAAI,CAAC,CAAC;QACZ,IAAI,CAAC,YAAY,GAAG,UAAU,CAAC,EAAE,CAAC;IACpC,CAAC;CACF;AATD,4DASC;AAED;;;;GAIG;AACH,MAAa,0BAA2B,SAAQ,6BAA6B;IAI3E,gBAAgB;IAChB,YAAY,IAAoB,EAAE,SAAoB;QACpD,KAAK,CAAC,IAAI,CAAC,CAAC;QACZ,IAAI,CAAC,SAAS,GAAG,SAAS,CAAC;IAC7B,CAAC;CACF;AATD,gEASC"} \ No newline at end of file diff --git a/ts-ticket-office-service/node_modules/mongodb/lib/cmap/errors.js b/ts-ticket-office-service/node_modules/mongodb/lib/cmap/errors.js new file mode 100644 index 000000000..63112628a --- /dev/null +++ b/ts-ticket-office-service/node_modules/mongodb/lib/cmap/errors.js @@ -0,0 +1,33 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.WaitQueueTimeoutError = exports.PoolClosedError = void 0; +const error_1 = require("../error"); +/** + * An error indicating a connection pool is closed + * @category Error + */ +class PoolClosedError extends error_1.MongoDriverError { + constructor(pool) { + super('Attempted to check out a connection from closed connection pool'); + this.address = pool.address; + } + get name() { + return 'MongoPoolClosedError'; + } +} +exports.PoolClosedError = PoolClosedError; +/** + * An error thrown when a request to check out a connection times out + * @category Error + */ +class WaitQueueTimeoutError extends error_1.MongoDriverError { + constructor(message, address) { + super(message); + this.address = address; + } + get name() { + return 'MongoWaitQueueTimeoutError'; + } +} +exports.WaitQueueTimeoutError = WaitQueueTimeoutError; +//# sourceMappingURL=errors.js.map \ No newline at end of file diff --git a/ts-ticket-office-service/node_modules/mongodb/lib/cmap/errors.js.map b/ts-ticket-office-service/node_modules/mongodb/lib/cmap/errors.js.map new file mode 100644 index 000000000..ae7e49659 --- /dev/null +++ b/ts-ticket-office-service/node_modules/mongodb/lib/cmap/errors.js.map @@ -0,0 +1 @@ +{"version":3,"file":"errors.js","sourceRoot":"","sources":["../../src/cmap/errors.ts"],"names":[],"mappings":";;;AAAA,oCAA4C;AAG5C;;;GAGG;AACH,MAAa,eAAgB,SAAQ,wBAAgB;IAInD,YAAY,IAAoB;QAC9B,KAAK,CAAC,iEAAiE,CAAC,CAAC;QACzE,IAAI,CAAC,OAAO,GAAG,IAAI,CAAC,OAAO,CAAC;IAC9B,CAAC;IAED,IAAa,IAAI;QACf,OAAO,sBAAsB,CAAC;IAChC,CAAC;CACF;AAZD,0CAYC;AAED;;;GAGG;AACH,MAAa,qBAAsB,SAAQ,wBAAgB;IAIzD,YAAY,OAAe,EAAE,OAAe;QAC1C,KAAK,CAAC,OAAO,CAAC,CAAC;QACf,IAAI,CAAC,OAAO,GAAG,OAAO,CAAC;IACzB,CAAC;IAED,IAAa,IAAI;QACf,OAAO,4BAA4B,CAAC;IACtC,CAAC;CACF;AAZD,sDAYC"} \ No newline at end of file diff --git a/ts-ticket-office-service/node_modules/mongodb/lib/cmap/message_stream.js b/ts-ticket-office-service/node_modules/mongodb/lib/cmap/message_stream.js new file mode 100644 index 000000000..de7e7d7a5 --- /dev/null +++ b/ts-ticket-office-service/node_modules/mongodb/lib/cmap/message_stream.js @@ -0,0 +1,175 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.MessageStream = void 0; +const stream_1 = require("stream"); +const error_1 = require("../error"); +const utils_1 = require("../utils"); +const commands_1 = require("./commands"); +const compression_1 = require("./wire_protocol/compression"); +const constants_1 = require("./wire_protocol/constants"); +const MESSAGE_HEADER_SIZE = 16; +const COMPRESSION_DETAILS_SIZE = 9; // originalOpcode + uncompressedSize, compressorID +const kDefaultMaxBsonMessageSize = 1024 * 1024 * 16 * 4; +/** @internal */ +const kBuffer = Symbol('buffer'); +/** + * A duplex stream that is capable of reading and writing raw wire protocol messages, with + * support for optional compression + * @internal + */ +class MessageStream extends stream_1.Duplex { + constructor(options = {}) { + super(options); + /** @internal */ + this.isMonitoringConnection = false; + this.maxBsonMessageSize = options.maxBsonMessageSize || kDefaultMaxBsonMessageSize; + this[kBuffer] = new utils_1.BufferPool(); + } + get buffer() { + return this[kBuffer]; + } + _write(chunk, _, callback) { + this[kBuffer].append(chunk); + processIncomingData(this, callback); + } + _read( /* size */) { + // NOTE: This implementation is empty because we explicitly push data to be read + // when `writeMessage` is called. + return; + } + writeCommand(command, operationDescription) { + // TODO: agreed compressor should live in `StreamDescription` + const compressorName = operationDescription && operationDescription.agreedCompressor + ? operationDescription.agreedCompressor + : 'none'; + if (compressorName === 'none' || !canCompress(command)) { + const data = command.toBin(); + this.push(Array.isArray(data) ? Buffer.concat(data) : data); + return; + } + // otherwise, compress the message + const concatenatedOriginalCommandBuffer = Buffer.concat(command.toBin()); + const messageToBeCompressed = concatenatedOriginalCommandBuffer.slice(MESSAGE_HEADER_SIZE); + // Extract information needed for OP_COMPRESSED from the uncompressed message + const originalCommandOpCode = concatenatedOriginalCommandBuffer.readInt32LE(12); + // Compress the message body + (0, compression_1.compress)({ options: operationDescription }, messageToBeCompressed, (err, compressedMessage) => { + if (err || !compressedMessage) { + operationDescription.cb(err); + return; + } + // Create the msgHeader of OP_COMPRESSED + const msgHeader = Buffer.alloc(MESSAGE_HEADER_SIZE); + msgHeader.writeInt32LE(MESSAGE_HEADER_SIZE + COMPRESSION_DETAILS_SIZE + compressedMessage.length, 0); // messageLength + msgHeader.writeInt32LE(command.requestId, 4); // requestID + msgHeader.writeInt32LE(0, 8); // responseTo (zero) + msgHeader.writeInt32LE(constants_1.OP_COMPRESSED, 12); // opCode + // Create the compression details of OP_COMPRESSED + const compressionDetails = Buffer.alloc(COMPRESSION_DETAILS_SIZE); + compressionDetails.writeInt32LE(originalCommandOpCode, 0); // originalOpcode + compressionDetails.writeInt32LE(messageToBeCompressed.length, 4); // Size of the uncompressed compressedMessage, excluding the MsgHeader + compressionDetails.writeUInt8(compression_1.Compressor[compressorName], 8); // compressorID + this.push(Buffer.concat([msgHeader, compressionDetails, compressedMessage])); + }); + } +} +exports.MessageStream = MessageStream; +// Return whether a command contains an uncompressible command term +// Will return true if command contains no uncompressible command terms +function canCompress(command) { + const commandDoc = command instanceof commands_1.Msg ? command.command : command.query; + const commandName = Object.keys(commandDoc)[0]; + return !compression_1.uncompressibleCommands.has(commandName); +} +function processIncomingData(stream, callback) { + const buffer = stream[kBuffer]; + if (buffer.length < 4) { + callback(); + return; + } + const sizeOfMessage = buffer.peek(4).readInt32LE(); + if (sizeOfMessage < 0) { + callback(new error_1.MongoParseError(`Invalid message size: ${sizeOfMessage}`)); + return; + } + if (sizeOfMessage > stream.maxBsonMessageSize) { + callback(new error_1.MongoParseError(`Invalid message size: ${sizeOfMessage}, max allowed: ${stream.maxBsonMessageSize}`)); + return; + } + if (sizeOfMessage > buffer.length) { + callback(); + return; + } + const message = buffer.read(sizeOfMessage); + const messageHeader = { + length: message.readInt32LE(0), + requestId: message.readInt32LE(4), + responseTo: message.readInt32LE(8), + opCode: message.readInt32LE(12) + }; + const monitorHasAnotherHello = () => { + if (stream.isMonitoringConnection) { + // Can we read the next message size? + if (buffer.length >= 4) { + const sizeOfMessage = buffer.peek(4).readInt32LE(); + if (sizeOfMessage <= buffer.length) { + return true; + } + } + } + return false; + }; + let ResponseType = messageHeader.opCode === constants_1.OP_MSG ? commands_1.BinMsg : commands_1.Response; + if (messageHeader.opCode !== constants_1.OP_COMPRESSED) { + const messageBody = message.slice(MESSAGE_HEADER_SIZE); + // If we are a monitoring connection message stream and + // there is more in the buffer that can be read, skip processing since we + // want the last hello command response that is in the buffer. + if (monitorHasAnotherHello()) { + processIncomingData(stream, callback); + } + else { + stream.emit('message', new ResponseType(message, messageHeader, messageBody)); + if (buffer.length >= 4) { + processIncomingData(stream, callback); + } + else { + callback(); + } + } + return; + } + messageHeader.fromCompressed = true; + messageHeader.opCode = message.readInt32LE(MESSAGE_HEADER_SIZE); + messageHeader.length = message.readInt32LE(MESSAGE_HEADER_SIZE + 4); + const compressorID = message[MESSAGE_HEADER_SIZE + 8]; + const compressedBuffer = message.slice(MESSAGE_HEADER_SIZE + 9); + // recalculate based on wrapped opcode + ResponseType = messageHeader.opCode === constants_1.OP_MSG ? commands_1.BinMsg : commands_1.Response; + (0, compression_1.decompress)(compressorID, compressedBuffer, (err, messageBody) => { + if (err || !messageBody) { + callback(err); + return; + } + if (messageBody.length !== messageHeader.length) { + callback(new error_1.MongoDecompressionError('Message body and message header must be the same length')); + return; + } + // If we are a monitoring connection message stream and + // there is more in the buffer that can be read, skip processing since we + // want the last hello command response that is in the buffer. + if (monitorHasAnotherHello()) { + processIncomingData(stream, callback); + } + else { + stream.emit('message', new ResponseType(message, messageHeader, messageBody)); + if (buffer.length >= 4) { + processIncomingData(stream, callback); + } + else { + callback(); + } + } + }); +} +//# sourceMappingURL=message_stream.js.map \ No newline at end of file diff --git a/ts-ticket-office-service/node_modules/mongodb/lib/cmap/message_stream.js.map b/ts-ticket-office-service/node_modules/mongodb/lib/cmap/message_stream.js.map new file mode 100644 index 000000000..e2aa88dc6 --- /dev/null +++ b/ts-ticket-office-service/node_modules/mongodb/lib/cmap/message_stream.js.map @@ -0,0 +1 @@ +{"version":3,"file":"message_stream.js","sourceRoot":"","sources":["../../src/cmap/message_stream.ts"],"names":[],"mappings":";;;AAAA,mCAA+C;AAG/C,oCAAoE;AAEpE,oCAAgD;AAChD,yCAAmG;AACnG,6DAMqC;AACrC,yDAAkE;AAElE,MAAM,mBAAmB,GAAG,EAAE,CAAC;AAC/B,MAAM,wBAAwB,GAAG,CAAC,CAAC,CAAC,kDAAkD;AAEtF,MAAM,0BAA0B,GAAG,IAAI,GAAG,IAAI,GAAG,EAAE,GAAG,CAAC,CAAC;AACxD,gBAAgB;AAChB,MAAM,OAAO,GAAG,MAAM,CAAC,QAAQ,CAAC,CAAC;AAwBjC;;;;GAIG;AACH,MAAa,aAAc,SAAQ,eAAM;IAQvC,YAAY,UAAgC,EAAE;QAC5C,KAAK,CAAC,OAAO,CAAC,CAAC;QAJjB,gBAAgB;QAChB,2BAAsB,GAAG,KAAK,CAAC;QAI7B,IAAI,CAAC,kBAAkB,GAAG,OAAO,CAAC,kBAAkB,IAAI,0BAA0B,CAAC;QACnF,IAAI,CAAC,OAAO,CAAC,GAAG,IAAI,kBAAU,EAAE,CAAC;IACnC,CAAC;IAED,IAAI,MAAM;QACR,OAAO,IAAI,CAAC,OAAO,CAAC,CAAC;IACvB,CAAC;IAEQ,MAAM,CAAC,KAAa,EAAE,CAAU,EAAE,QAA0B;QACnE,IAAI,CAAC,OAAO,CAAC,CAAC,MAAM,CAAC,KAAK,CAAC,CAAC;QAC5B,mBAAmB,CAAC,IAAI,EAAE,QAAQ,CAAC,CAAC;IACtC,CAAC;IAEQ,KAAK,EAAC,UAAU;QACvB,gFAAgF;QAChF,uCAAuC;QACvC,OAAO;IACT,CAAC;IAED,YAAY,CACV,OAAiC,EACjC,oBAA0C;QAE1C,6DAA6D;QAC7D,MAAM,cAAc,GAClB,oBAAoB,IAAI,oBAAoB,CAAC,gBAAgB;YAC3D,CAAC,CAAC,oBA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ACvF,CAAC;YAEF,OAAO;SACR;QAED,uDAAuD;QACvD,yEAAyE;QACzE,8DAA8D;QAC9D,IAAI,sBAAsB,EAAE,EAAE;YAC5B,mBAAmB,CAAC,MAAM,EAAE,QAAQ,CAAC,CAAC;SACvC;aAAM;YACL,MAAM,CAAC,IAAI,CAAC,SAAS,EAAE,IAAI,YAAY,CAAC,OAAO,EAAE,aAAa,EAAE,WAAW,CAAC,CAAC,CAAC;YAE9E,IAAI,MAAM,CAAC,MAAM,IAAI,CAAC,EAAE;gBACtB,mBAAmB,CAAC,MAAM,EAAE,QAAQ,CAAC,CAAC;aACvC;iBAAM;gBACL,QAAQ,EAAE,CAAC;aACZ;SACF;IACH,CAAC,CAAC,CAAC;AACL,CAAC"} \ No newline at end of file diff --git a/ts-ticket-office-service/node_modules/mongodb/lib/cmap/metrics.js b/ts-ticket-office-service/node_modules/mongodb/lib/cmap/metrics.js new file mode 100644 index 000000000..89c221091 --- /dev/null +++ b/ts-ticket-office-service/node_modules/mongodb/lib/cmap/metrics.js @@ -0,0 +1,62 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.ConnectionPoolMetrics = void 0; +/** @internal */ +class ConnectionPoolMetrics { + constructor() { + this.txnConnections = 0; + this.cursorConnections = 0; + this.otherConnections = 0; + } + /** + * Mark a connection as pinned for a specific operation. + */ + markPinned(pinType) { + if (pinType === ConnectionPoolMetrics.TXN) { + this.txnConnections += 1; + } + else if (pinType === ConnectionPoolMetrics.CURSOR) { + this.cursorConnections += 1; + } + else { + this.otherConnections += 1; + } + } + /** + * Unmark a connection as pinned for an operation. + */ + markUnpinned(pinType) { + if (pinType === ConnectionPoolMetrics.TXN) { + this.txnConnections -= 1; + } + else if (pinType === ConnectionPoolMetrics.CURSOR) { + this.cursorConnections -= 1; + } + else { + this.otherConnections -= 1; + } + } + /** + * Return information about the cmap metrics as a string. + */ + info(maxPoolSize) { + return ('Timed out while checking out a connection from connection pool: ' + + `maxPoolSize: ${maxPoolSize}, ` + + `connections in use by cursors: ${this.cursorConnections}, ` + + `connections in use by transactions: ${this.txnConnections}, ` + + `connections in use by other operations: ${this.otherConnections}`); + } + /** + * Reset the metrics to the initial values. + */ + reset() { + this.txnConnections = 0; + this.cursorConnections = 0; + this.otherConnections = 0; + } +} +exports.ConnectionPoolMetrics = ConnectionPoolMetrics; +ConnectionPoolMetrics.TXN = 'txn'; +ConnectionPoolMetrics.CURSOR = 'cursor'; +ConnectionPoolMetrics.OTHER = 'other'; +//# sourceMappingURL=metrics.js.map \ No newline at end of file diff --git a/ts-ticket-office-service/node_modules/mongodb/lib/cmap/metrics.js.map b/ts-ticket-office-service/node_modules/mongodb/lib/cmap/metrics.js.map new file mode 100644 index 000000000..270cefe79 --- /dev/null +++ b/ts-ticket-office-service/node_modules/mongodb/lib/cmap/metrics.js.map @@ -0,0 +1 @@ +{"version":3,"file":"metrics.js","sourceRoot":"","sources":["../../src/cmap/metrics.ts"],"names":[],"mappings":";;;AAAA,gBAAgB;AAChB,MAAa,qBAAqB;IAAlC;QAKE,mBAAc,GAAG,CAAC,CAAC;QACnB,sBAAiB,GAAG,CAAC,CAAC;QACtB,qBAAgB,GAAG,CAAC,CAAC;IAiDvB,CAAC;IA/CC;;OAEG;IACH,UAAU,CAAC,OAAe;QACxB,IAAI,OAAO,KAAK,qBAAqB,CAAC,GAAG,EAAE;YACzC,IAAI,CAAC,cAAc,IAAI,CAAC,CAAC;SAC1B;aAAM,IAAI,OAAO,KAAK,qBAAqB,CAAC,MAAM,EAAE;YACnD,IAAI,CAAC,iBAAiB,IAAI,CAAC,CAAC;SAC7B;aAAM;YACL,IAAI,CAAC,gBAAgB,IAAI,CAAC,CAAC;SAC5B;IACH,CAAC;IAED;;OAEG;IACH,YAAY,CAAC,OAAe;QAC1B,IAAI,OAAO,KAAK,qBAAqB,CAAC,GAAG,EAAE;YACzC,IAAI,CAAC,cAAc,IAAI,CAAC,CAAC;SAC1B;aAAM,IAAI,OAAO,KAAK,qBAAqB,CAAC,MAAM,EAAE;YACnD,IAAI,CAAC,iBAAiB,IAAI,CAAC,CAAC;SAC7B;aAAM;YACL,IAAI,CAAC,gBAAgB,IAAI,CAAC,CAAC;SAC5B;IACH,CAAC;IAED;;OAEG;IACH,IAAI,CAAC,WAAmB;QACtB,OAAO,CACL,kEAAkE;YAClE,gBAAgB,WAAW,IAAI;YAC/B,kCAAkC,IAAI,CAAC,iBAAiB,IAAI;YAC5D,uCAAuC,IAAI,CAAC,cAAc,IAAI;YAC9D,2CAA2C,IAAI,CAAC,gBAAgB,EAAE,CACnE,CAAC;IACJ,CAAC;IAED;;OAEG;IACH,KAAK;QACH,IAAI,CAAC,cAAc,GAAG,CAAC,CAAC;QACxB,IAAI,CAAC,iBAAiB,GAAG,CAAC,CAAC;QAC3B,IAAI,CAAC,gBAAgB,GAAG,CAAC,CAAC;IAC5B,CAAC;;AAvDH,sDAwDC;AAvDiB,yBAAG,GAAG,KAAc,CAAC;AACrB,4BAAM,GAAG,QAAiB,CAAC;AAC3B,2BAAK,GAAG,OAAgB,CAAC"} \ No newline at end of file diff --git a/ts-ticket-office-service/node_modules/mongodb/lib/cmap/stream_description.js b/ts-ticket-office-service/node_modules/mongodb/lib/cmap/stream_description.js new file mode 100644 index 000000000..4d4eb3293 --- /dev/null +++ b/ts-ticket-office-service/node_modules/mongodb/lib/cmap/stream_description.js @@ -0,0 +1,51 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.StreamDescription = void 0; +const common_1 = require("../sdam/common"); +const server_description_1 = require("../sdam/server_description"); +const RESPONSE_FIELDS = [ + 'minWireVersion', + 'maxWireVersion', + 'maxBsonObjectSize', + 'maxMessageSizeBytes', + 'maxWriteBatchSize', + 'logicalSessionTimeoutMinutes' +]; +/** @public */ +class StreamDescription { + constructor(address, options) { + this.address = address; + this.type = common_1.ServerType.Unknown; + this.minWireVersion = undefined; + this.maxWireVersion = undefined; + this.maxBsonObjectSize = 16777216; + this.maxMessageSizeBytes = 48000000; + this.maxWriteBatchSize = 100000; + this.logicalSessionTimeoutMinutes = options === null || options === void 0 ? void 0 : options.logicalSessionTimeoutMinutes; + this.loadBalanced = !!(options === null || options === void 0 ? void 0 : options.loadBalanced); + this.compressors = + options && options.compressors && Array.isArray(options.compressors) + ? options.compressors + : []; + } + receiveResponse(response) { + if (response == null) { + return; + } + this.type = (0, server_description_1.parseServerType)(response); + for (const field of RESPONSE_FIELDS) { + if (response[field] != null) { + this[field] = response[field]; + } + // testing case + if ('__nodejs_mock_server__' in response) { + this.__nodejs_mock_server__ = response['__nodejs_mock_server__']; + } + } + if (response.compression) { + this.compressor = this.compressors.filter(c => { var _a; return (_a = response.compression) === null || _a === void 0 ? void 0 : _a.includes(c); })[0]; + } + } +} +exports.StreamDescription = StreamDescription; +//# sourceMappingURL=stream_description.js.map \ No newline at end of file diff --git a/ts-ticket-office-service/node_modules/mongodb/lib/cmap/stream_description.js.map b/ts-ticket-office-service/node_modules/mongodb/lib/cmap/stream_description.js.map new file mode 100644 index 000000000..1cebe013f --- /dev/null +++ b/ts-ticket-office-service/node_modules/mongodb/lib/cmap/stream_description.js.map @@ -0,0 +1 @@ +{"version":3,"file":"stream_description.js","sourceRoot":"","sources":["../../src/cmap/stream_description.ts"],"names":[],"mappings":";;;AACA,2CAA4C;AAC5C,mEAA6D;AAG7D,MAAM,eAAe,GAAG;IACtB,gBAAgB;IAChB,gBAAgB;IAChB,mBAAmB;IACnB,qBAAqB;IACrB,mBAAmB;IACnB,8BAA8B;CACtB,CAAC;AASX,cAAc;AACd,MAAa,iBAAiB;IAiB5B,YAAY,OAAe,EAAE,OAAkC;QAC7D,IAAI,CAAC,OAAO,GAAG,OAAO,CAAC;QACvB,IAAI,CAAC,IAAI,GAAG,mBAAU,CAAC,OAAO,CAAC;QAC/B,IAAI,CAAC,cAAc,GAAG,SAAS,CAAC;QAChC,IAAI,CAAC,cAAc,GAAG,SAAS,CAAC;QAChC,IAAI,CAAC,iBAAiB,GAAG,QAAQ,CAAC;QACl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/cmap/wire_protocol/compression.js b/ts-ticket-office-service/node_modules/mongodb/lib/cmap/wire_protocol/compression.js new file mode 100644 index 000000000..e198be865 --- /dev/null +++ b/ts-ticket-office-service/node_modules/mongodb/lib/cmap/wire_protocol/compression.js @@ -0,0 +1,96 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.decompress = exports.compress = exports.uncompressibleCommands = exports.Compressor = void 0; +const zlib = require("zlib"); +const constants_1 = require("../../constants"); +const deps_1 = require("../../deps"); +const error_1 = require("../../error"); +/** @public */ +exports.Compressor = Object.freeze({ + none: 0, + snappy: 1, + zlib: 2, + zstd: 3 +}); +exports.uncompressibleCommands = new Set([ + constants_1.LEGACY_HELLO_COMMAND, + 'saslStart', + 'saslContinue', + 'getnonce', + 'authenticate', + 'createUser', + 'updateUser', + 'copydbSaslStart', + 'copydbgetnonce', + 'copydb' +]); +const MAX_COMPRESSOR_ID = 3; +const ZSTD_COMPRESSION_LEVEL = 3; +// Facilitate compressing a message using an agreed compressor +function compress(self, dataToBeCompressed, callback) { + const zlibOptions = {}; + switch (self.options.agreedCompressor) { + case 'snappy': { + if ('kModuleError' in deps_1.Snappy) { + return callback(deps_1.Snappy['kModuleError']); + } + if (deps_1.Snappy[deps_1.PKG_VERSION].major <= 6) { + deps_1.Snappy.compress(dataToBeCompressed, callback); + } + else { + deps_1.Snappy.compress(dataToBeCompressed).then(buffer => callback(undefined, buffer), error => callback(error)); + } + break; + } + case 'zlib': + // Determine zlibCompressionLevel + if (self.options.zlibCompressionLevel) { + zlibOptions.level = self.options.zlibCompressionLevel; + } + zlib.deflate(dataToBeCompressed, zlibOptions, callback); + break; + case 'zstd': + if ('kModuleError' in deps_1.ZStandard) { + return callback(deps_1.ZStandard['kModuleError']); + } + deps_1.ZStandard.compress(dataToBeCompressed, ZSTD_COMPRESSION_LEVEL).then(buffer => callback(undefined, buffer), error => callback(error)); + break; + default: + throw new error_1.MongoInvalidArgumentError(`Unknown compressor ${self.options.agreedCompressor} failed to compress`); + } +} +exports.compress = compress; +// Decompress a message using the given compressor +function decompress(compressorID, compressedData, callback) { + if (compressorID < 0 || compressorID > MAX_COMPRESSOR_ID) { + throw new error_1.MongoDecompressionError(`Server sent message compressed using an unsupported compressor. (Received compressor ID ${compressorID})`); + } + switch (compressorID) { + case exports.Compressor.snappy: { + if ('kModuleError' in deps_1.Snappy) { + return callback(deps_1.Snappy['kModuleError']); + } + if (deps_1.Snappy[deps_1.PKG_VERSION].major <= 6) { + deps_1.Snappy.uncompress(compressedData, { asBuffer: true }, callback); + } + else { + deps_1.Snappy.uncompress(compressedData, { asBuffer: true }).then(buffer => callback(undefined, buffer), error => callback(error)); + } + break; + } + case exports.Compressor.zstd: { + if ('kModuleError' in deps_1.ZStandard) { + return callback(deps_1.ZStandard['kModuleError']); + } + deps_1.ZStandard.decompress(compressedData).then(buffer => callback(undefined, buffer), error => callback(error)); + break; + } + case exports.Compressor.zlib: + zlib.inflate(compressedData, callback); + break; + default: + callback(undefined, compressedData); + } +} +exports.decompress = decompress; +//# sourceMappingURL=compression.js.map \ No newline at end of file diff --git a/ts-ticket-office-service/node_modules/mongodb/lib/cmap/wire_protocol/compression.js.map b/ts-ticket-office-service/node_modules/mongodb/lib/cmap/wire_protocol/compression.js.map new file mode 100644 index 000000000..e2ecbbd3e --- /dev/null +++ b/ts-ticket-office-service/node_modules/mongodb/lib/cmap/wire_protocol/compression.js.map @@ -0,0 +1 @@ +{"version":3,"file":"compression.js","sourceRoot":"","sources":["../../../src/cmap/wire_protocol/compression.ts"],"names":[],"mappings":";;;AAAA,6BAA6B;AAE7B,+CAAuD;AACvD,qCAA4D;AAC5D,uCAAiF;AAIjF,cAAc;AACD,QAAA,UAAU,GAAG,MAAM,CAAC,MAAM,CAAC;IACtC,IAAI,EAAE,CAAC;IACP,MAAM,EAAE,CAAC;IACT,IAAI,EAAE,CAAC;IACP,IAAI,EAAE,CAAC;CACC,CAAC,CAAC;AAQC,QAAA,sBAAsB,GAAG,IAAI,GAA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B,IAAI,cAAc,IAAI,gBAAS,EAAE;gBAC/B,OAAO,QAAQ,CAAC,gBAAS,CAAC,cAAc,CAAC,CAAC,CAAC;aAC5C;YAED,gBAAS,CAAC,UAAU,CAAC,cAAc,CAAC,CAAC,IAAI,CACvC,MAAM,CAAC,EAAE,CAAC,QAAQ,CAAC,SAAS,EAAE,MAAM,CAAC,EACrC,KAAK,CAAC,EAAE,CAAC,QAAQ,CAAC,KAAK,CAAC,CACzB,CAAC;YACF,MAAM;SACP;QACD,KAAK,kBAAU,CAAC,IAAI;YAClB,IAAI,CAAC,OAAO,CAAC,cAAc,EAAE,QAAiC,CAAC,CAAC;YAChE,MAAM;QACR;YACE,QAAQ,CAAC,SAAS,EAAE,cAAc,CAAC,CAAC;KACvC;AACH,CAAC;AA5CD,gCA4CC"} \ No newline at end of file diff --git a/ts-ticket-office-service/node_modules/mongodb/lib/cmap/wire_protocol/constants.js b/ts-ticket-office-service/node_modules/mongodb/lib/cmap/wire_protocol/constants.js new file mode 100644 index 000000000..ee5de73aa --- /dev/null +++ b/ts-ticket-office-service/node_modules/mongodb/lib/cmap/wire_protocol/constants.js @@ -0,0 +1,17 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.OP_MSG = exports.OP_COMPRESSED = exports.OP_KILL_CURSORS = exports.OP_DELETE = exports.OP_GETMORE = exports.OP_QUERY = exports.OP_INSERT = exports.OP_UPDATE = exports.OP_REPLY = exports.MAX_SUPPORTED_WIRE_VERSION = exports.MIN_SUPPORTED_WIRE_VERSION = exports.MAX_SUPPORTED_SERVER_VERSION = exports.MIN_SUPPORTED_SERVER_VERSION = void 0; +exports.MIN_SUPPORTED_SERVER_VERSION = '3.6'; +exports.MAX_SUPPORTED_SERVER_VERSION = '6.0'; +exports.MIN_SUPPORTED_WIRE_VERSION = 6; +exports.MAX_SUPPORTED_WIRE_VERSION = 17; +exports.OP_REPLY = 1; +exports.OP_UPDATE = 2001; +exports.OP_INSERT = 2002; +exports.OP_QUERY = 2004; +exports.OP_GETMORE = 2005; +exports.OP_DELETE = 2006; +exports.OP_KILL_CURSORS = 2007; +exports.OP_COMPRESSED = 2012; +exports.OP_MSG = 2013; +//# sourceMappingURL=constants.js.map \ No newline at end of file diff --git a/ts-ticket-office-service/node_modules/mongodb/lib/cmap/wire_protocol/constants.js.map b/ts-ticket-office-service/node_modules/mongodb/lib/cmap/wire_protocol/constants.js.map new file mode 100644 index 000000000..9dc053b22 --- /dev/null +++ b/ts-ticket-office-service/node_modules/mongodb/lib/cmap/wire_protocol/constants.js.map @@ -0,0 +1 @@ +{"version":3,"file":"constants.js","sourceRoot":"","sources":["../../../src/cmap/wire_protocol/constants.ts"],"names":[],"mappings":";;;AAAa,QAAA,4BAA4B,GAAG,KAAK,CAAC;AACrC,QAAA,4BAA4B,GAAG,KAAK,CAAC;AACrC,QAAA,0BAA0B,GAAG,CAAC,CAAC;AAC/B,QAAA,0BAA0B,GAAG,EAAE,CAAC;AAChC,QAAA,QAAQ,GAAG,CAAC,CAAC;AACb,QAAA,SAAS,GAAG,IAAI,CAAC;AACjB,QAAA,SAAS,GAAG,IAAI,CAAC;AACjB,QAAA,QAAQ,GAAG,IAAI,CAAC;AAChB,QAAA,UAAU,GAAG,IAAI,CAAC;AAClB,QAAA,SAAS,GAAG,IAAI,CAAC;AACjB,QAAA,eAAe,GAAG,IAAI,CAAC;AACvB,QAAA,aAAa,GAAG,IAAI,CAAC;AACrB,QAAA,MAAM,GAAG,IAAI,CAAC"} \ No newline at end of file diff --git a/ts-ticket-office-service/node_modules/mongodb/lib/cmap/wire_protocol/shared.js b/ts-ticket-office-service/node_modules/mongodb/lib/cmap/wire_protocol/shared.js new file mode 100644 index 000000000..b5d127828 --- /dev/null +++ b/ts-ticket-office-service/node_modules/mongodb/lib/cmap/wire_protocol/shared.js @@ -0,0 +1,55 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.isSharded = exports.applyCommonQueryOptions = exports.getReadPreference = void 0; +const error_1 = require("../../error"); +const read_preference_1 = require("../../read_preference"); +const common_1 = require("../../sdam/common"); +const topology_description_1 = require("../../sdam/topology_description"); +function getReadPreference(cmd, options) { + // Default to command version of the readPreference + let readPreference = cmd.readPreference || read_preference_1.ReadPreference.primary; + // If we have an option readPreference override the command one + if (options === null || options === void 0 ? void 0 : options.readPreference) { + readPreference = options.readPreference; + } + if (typeof readPreference === 'string') { + readPreference = read_preference_1.ReadPreference.fromString(readPreference); + } + if (!(readPreference instanceof read_preference_1.ReadPreference)) { + throw new error_1.MongoInvalidArgumentError('Option "readPreference" must be a ReadPreference instance'); + } + return readPreference; +} +exports.getReadPreference = getReadPreference; +function applyCommonQueryOptions(queryOptions, options) { + Object.assign(queryOptions, { + raw: typeof options.raw === 'boolean' ? options.raw : false, + promoteLongs: typeof options.promoteLongs === 'boolean' ? options.promoteLongs : true, + promoteValues: typeof options.promoteValues === 'boolean' ? options.promoteValues : true, + promoteBuffers: typeof options.promoteBuffers === 'boolean' ? options.promoteBuffers : false, + bsonRegExp: typeof options.bsonRegExp === 'boolean' ? options.bsonRegExp : false, + enableUtf8Validation: typeof options.enableUtf8Validation === 'boolean' ? options.enableUtf8Validation : true + }); + if (options.session) { + queryOptions.session = options.session; + } + return queryOptions; +} +exports.applyCommonQueryOptions = applyCommonQueryOptions; +function isSharded(topologyOrServer) { + if (topologyOrServer == null) { + return false; + } + if (topologyOrServer.description && topologyOrServer.description.type === common_1.ServerType.Mongos) { + return true; + } + // NOTE: This is incredibly inefficient, and should be removed once command construction + // happens based on `Server` not `Topology`. + if (topologyOrServer.description && topologyOrServer.description instanceof topology_description_1.TopologyDescription) { + const servers = Array.from(topologyOrServer.description.servers.values()); + return servers.some((server) => server.type === common_1.ServerType.Mongos); + } + return false; +} +exports.isSharded = isSharded; +//# sourceMappingURL=shared.js.map \ No newline at end of file diff --git a/ts-ticket-office-service/node_modules/mongodb/lib/cmap/wire_protocol/shared.js.map b/ts-ticket-office-service/node_modules/mongodb/lib/cmap/wire_protocol/shared.js.map new file mode 100644 index 000000000..2d5b2275f --- /dev/null +++ b/ts-ticket-office-service/node_modules/mongodb/lib/cmap/wire_protocol/shared.js.map @@ -0,0 +1 @@ +{"version":3,"file":"shared.js","sourceRoot":"","sources":["../../../src/cmap/wire_protocol/shared.ts"],"names":[],"mappings":";;;AACA,uCAAwD;AAExD,2DAAuD;AACvD,8CAA+C;AAI/C,0EAAsE;AAQtE,SAAgB,iBAAiB,CAAC,GAAa,EAAE,OAA8B;IAC7E,mDAAmD;IACnD,IAAI,cAAc,GAAG,GAAG,CAAC,cAAc,IAAI,gCAAc,CAAC,OAAO,CAAC;IAClE,+DAA+D;IAC/D,IAAI,OAAO,aAAP,OAAO,uBAAP,OAAO,CAAE,cAAc,EAAE;QAC3B,cAAc,GAAG,OAAO,CAAC,cAAc,CAAC;KACzC;IAED,IAAI,OAAO,cAAc,KAAK,QAAQ,EAAE;QACtC,cAAc,GAAG,gCAAc,CAAC,UAAU,CAAC,cAAc,CAAC,CAAC;KAC5D;IAED,IAAI,CAAC,CAAC,cAAc,YAAY,gCAAc,CAAC,EAAE;QAC/C,MAAM,IAAI,iCAAyB,CACjC,2DAA2D,CAC5D,CAAC;KACH;IAED,OAAO,cAAc,CAAC;AACxB,CAAC;AAnBD,8CAmBC;AAED,SAAgB,uBAAuB,CACrC,YAA4B,EAC5B,OAAuB;IAEvB,MAAM,CAAC,MAAM,CAAC,YAAY,EAAE;QAC1B,GAAG,EAAE,OAAO,OAAO,CAAC,GAAG,KAAK,SAAS,CAAC,CAAC,CAAC,OAAO,CAAC,GAAG,CAAC,CAAC,CAAC,KAAK;QAC3D,YAAY,EAAE,OAAO,OAAO,CAAC,YAAY,KAAK,SAAS,CAAC,CAAC,CAAC,OAAO,CAAC,YAAY,CAAC,CAAC,CAAC,IAAI;QACrF,aAAa,EAAE,OAAO,OAAO,CAAC,aAAa,KAAK,SAAS,CAAC,CAAC,CAAC,OAAO,CAAC,aAAa,CAAC,CAAC,CAAC,IAAI;QACxF,cAAc,EAAE,OAAO,OAAO,CAAC,cAAc,KAAK,SAAS,CAAC,CAAC,CAAC,OAAO,CAAC,cAAc,CAAC,CAAC,CAAC,KAAK;QAC5F,UAAU,EAAE,OAAO,OAAO,CAAC,UAAU,KAAK,SAAS,CAAC,CAAC,CAAC,OAAO,CAAC,UAAU,CAAC,CAAC,CAAC,KAAK;QAChF,oBAAoB,EAClB,OAAO,OAAO,CAAC,oBAAoB,KAAK,SAAS,CAAC,CAAC,CAAC,OAAO,CAAC,oBAAoB,CAAC,CAAC,CAAC,IAAI;KAC1F,CAAC,CAAC;IAEH,IAAI,OAAO,CAAC,OAAO,EAAE;QACnB,YAAY,CAAC,OAAO,GAAG,OAAO,CAAC,OAAO,CAAC;KACxC;IAED,OAAO,YAAY,CAAC;AACtB,CAAC;AAnBD,0DAmBC;AAED,SAAgB,SAAS,CAAC,gBAAiD;IACzE,IAAI,gBAAgB,IAAI,IAAI,EAAE;QAC5B,OAAO,KAAK,CAAC;KACd;IAED,IAAI,gBAAgB,CAAC,WAAW,IAAI,gBAAgB,CAAC,WAAW,CAAC,IAAI,KAAK,mBAAU,CAAC,MAAM,EAAE;QAC3F,OAAO,IAAI,CAAC;KACb;IAED,wFAAwF;IACxF,kDAAkD;IAClD,IAAI,gBAAgB,CAAC,WAAW,IAAI,gBAAgB,CAAC,WAAW,YAAY,0CAAmB,EAAE;QAC/F,MAAM,OAAO,GAAwB,KAAK,CAAC,IAAI,CAAC,gBAAgB,CAAC,WAAW,CAAC,OAAO,CAAC,MAAM,EAAE,CAAC,CAAC;QAC/F,OAAO,OAAO,CAAC,IAAI,CAAC,CAAC,MAAyB,EAAE,EAAE,CAAC,MAAM,CAAC,IAAI,KAAK,mBAAU,CAAC,MAAM,CAAC,CAAC;KACvF;IAED,OAAO,KAAK,CAAC;AACf,CAAC;AAjBD,8BAiBC"} \ No newline at end of file diff --git a/ts-ticket-office-service/node_modules/mongodb/lib/collection.js b/ts-ticket-office-service/node_modules/mongodb/lib/collection.js index 53025e538..8409d390f 100644 --- a/ts-ticket-office-service/node_modules/mongodb/lib/collection.js +++ b/ts-ticket-office-service/node_modules/mongodb/lib/collection.js @@ -1,3377 +1,537 @@ "use strict"; - -var checkCollectionName = require('./utils').checkCollectionName - , ObjectID = require('mongodb-core').BSON.ObjectID - , Long = require('mongodb-core').BSON.Long - , Code = require('mongodb-core').BSON.Code - , f = require('util').format - , AggregationCursor = require('./aggregation_cursor') - , MongoError = require('mongodb-core').MongoError - , shallowClone = require('./utils').shallowClone - , isObject = require('./utils').isObject - , toError = require('./utils').toError - , normalizeHintField = require('./utils').normalizeHintField - , handleCallback = require('./utils').handleCallback - , decorateCommand = require('./utils').decorateCommand - , formattedOrderClause = require('./utils').formattedOrderClause - , ReadPreference = require('./read_preference') - , CoreReadPreference = require('mongodb-core').ReadPreference - , CommandCursor = require('./command_cursor') - , Define = require('./metadata') - , Cursor = require('./cursor') - , unordered = require('./bulk/unordered') - , ordered = require('./bulk/ordered') - , assign = require('./utils').assign; - -/** - * @fileOverview The **Collection** class is an internal class that embodies a MongoDB collection +Object.defineProperty(exports, "__esModule", { value: true }); +exports.Collection = void 0; +const bson_1 = require("./bson"); +const ordered_1 = require("./bulk/ordered"); +const unordered_1 = require("./bulk/unordered"); +const change_stream_1 = require("./change_stream"); +const aggregation_cursor_1 = require("./cursor/aggregation_cursor"); +const find_cursor_1 = require("./cursor/find_cursor"); +const list_indexes_cursor_1 = require("./cursor/list_indexes_cursor"); +const error_1 = require("./error"); +const bulk_write_1 = require("./operations/bulk_write"); +const count_1 = require("./operations/count"); +const count_documents_1 = require("./operations/count_documents"); +const delete_1 = require("./operations/delete"); +const distinct_1 = require("./operations/distinct"); +const drop_1 = require("./operations/drop"); +const estimated_document_count_1 = require("./operations/estimated_document_count"); +const execute_operation_1 = require("./operations/execute_operation"); +const find_and_modify_1 = require("./operations/find_and_modify"); +const indexes_1 = require("./operations/indexes"); +const insert_1 = require("./operations/insert"); +const is_capped_1 = require("./operations/is_capped"); +const map_reduce_1 = require("./operations/map_reduce"); +const options_operation_1 = require("./operations/options_operation"); +const rename_1 = require("./operations/rename"); +const stats_1 = require("./operations/stats"); +const update_1 = require("./operations/update"); +const read_concern_1 = require("./read_concern"); +const read_preference_1 = require("./read_preference"); +const utils_1 = require("./utils"); +const write_concern_1 = require("./write_concern"); +/** + * The **Collection** class is an internal class that embodies a MongoDB collection * allowing for insert/update/remove/find and other command operation on that MongoDB collection. * * **COLLECTION Cannot directly be instantiated** + * @public + * * @example - * var MongoClient = require('mongodb').MongoClient, - * test = require('assert'); + * ```js + * const MongoClient = require('mongodb').MongoClient; + * const test = require('assert'); * // Connection url - * var url = 'mongodb://localhost:27017/test'; + * const url = 'mongodb://localhost:27017'; + * // Database Name + * const dbName = 'test'; * // Connect using MongoClient - * MongoClient.connect(url, function(err, db) { + * MongoClient.connect(url, function(err, client) { * // Create a collection we want to drop later - * var col = db.collection('createIndexExample1'); + * const col = client.db(dbName).collection('createIndexExample1'); * // Show that duplicate records got dropped * col.find({}).toArray(function(err, items) { - * test.equal(null, err); + * expect(err).to.not.exist; * test.equal(4, items.length); - * db.close(); + * client.close(); * }); * }); - */ - -var mergeKeys = ['readPreference', 'ignoreUndefined']; - -/** - * Create a new Collection instance (INTERNAL TYPE, do not instantiate directly) - * @class - * @property {string} collectionName Get the collection name. - * @property {string} namespace Get the full collection namespace. - * @property {object} writeConcern The current write concern values. - * @property {object} readConcern The current read concern values. - * @property {object} hint Get current index hint for collection. - * @return {Collection} a Collection instance. - */ -var Collection = function(db, topology, dbName, name, pkFactory, options) { - checkCollectionName(name); - - // Unpack variables - var internalHint = null; - var slaveOk = options == null || options.slaveOk == null ? db.slaveOk : options.slaveOk; - var serializeFunctions = options == null || options.serializeFunctions == null ? db.s.options.serializeFunctions : options.serializeFunctions; - var raw = options == null || options.raw == null ? db.s.options.raw : options.raw; - var promoteLongs = options == null || options.promoteLongs == null ? db.s.options.promoteLongs : options.promoteLongs; - var promoteValues = options == null || options.promoteValues == null ? db.s.options.promoteValues : options.promoteValues; - var promoteBuffers = options == null || options.promoteBuffers == null ? db.s.options.promoteBuffers : options.promoteBuffers; - var readPreference = null; - var collectionHint = null; - var namespace = f("%s.%s", dbName, name); - - // Get the promiseLibrary - var promiseLibrary = options.promiseLibrary; - - // No promise library selected fall back - if(!promiseLibrary) { - promiseLibrary = typeof global.Promise == 'function' ? - global.Promise : require('es6-promise').Promise; - } - - // Assign the right collection level readPreference - if(options && options.readPreference) { - readPreference = options.readPreference; - } else if(db.options.readPreference) { - readPreference = db.options.readPreference; - } - - // Set custom primary key factory if provided - pkFactory = pkFactory == null - ? ObjectID - : pkFactory; - - // Internal state - this.s = { - // Set custom primary key factory if provided - pkFactory: pkFactory - // Db - , db: db - // Topology - , topology: topology - // dbName - , dbName: dbName - // Options - , options: options - // Namespace - , namespace: namespace - // Read preference - , readPreference: readPreference - // SlaveOK - , slaveOk: slaveOk - // Serialize functions - , serializeFunctions: serializeFunctions - // Raw - , raw: raw - // promoteLongs - , promoteLongs: promoteLongs - // promoteValues - , promoteValues: promoteValues - // promoteBuffers - , promoteBuffers: promoteBuffers - // internalHint - , internalHint: internalHint - // collectionHint - , collectionHint: collectionHint - // Name - , name: name - // Promise library - , promiseLibrary: promiseLibrary - // Read Concern - , readConcern: options.readConcern - } -} - -var define = Collection.define = new Define('Collection', Collection, false); - -Object.defineProperty(Collection.prototype, 'collectionName', { - enumerable: true, get: function() { return this.s.name; } -}); - -Object.defineProperty(Collection.prototype, 'namespace', { - enumerable: true, get: function() { return this.s.namespace; } -}); - -Object.defineProperty(Collection.prototype, 'readConcern', { - enumerable: true, get: function() { return this.s.readConcern || {level: 'local'}; } -}); - -Object.defineProperty(Collection.prototype, 'writeConcern', { - enumerable:true, - get: function() { - var ops = {}; - if(this.s.options.w != null) ops.w = this.s.options.w; - if(this.s.options.j != null) ops.j = this.s.options.j; - if(this.s.options.fsync != null) ops.fsync = this.s.options.fsync; - if(this.s.options.wtimeout != null) ops.wtimeout = this.s.options.wtimeout; - return ops; - } -}); - -/** - * @ignore - */ -Object.defineProperty(Collection.prototype, "hint", { - enumerable: true - , get: function () { return this.s.collectionHint; } - , set: function (v) { this.s.collectionHint = normalizeHintField(v); } -}); - -/** - * Creates a cursor for a query that can be used to iterate over results from MongoDB - * @method - * @param {object} query The cursor query object. - * @throws {MongoError} - * @return {Cursor} - */ -Collection.prototype.find = function() { - var options - , args = Array.prototype.slice.call(arguments, 0) - , has_callback = typeof args[args.length - 1] === 'function' - , has_weird_callback = typeof args[0] === 'function' - , callback = has_callback ? args.pop() : (has_weird_callback ? args.shift() : null) - , len = args.length - , selector = len >= 1 ? args[0] : {} - , fields = len >= 2 ? args[1] : undefined; - - if(len === 1 && has_weird_callback) { - // backwards compat for callback?, options case - selector = {}; - options = args[0]; - } - - if(len === 2 && fields !== undefined && !Array.isArray(fields)) { - var fieldKeys = Object.keys(fields); - var is_option = false; - - for(var i = 0; i < fieldKeys.length; i++) { - if(testForFields[fieldKeys[i]] != null) { - is_option = true; - break; - } - } - - if(is_option) { - options = fields; - fields = undefined; - } else { - options = {}; - } - } else if(len === 2 && Array.isArray(fields) && !Array.isArray(fields[0])) { - var newFields = {}; - // Rewrite the array - for(i = 0; i < fields.length; i++) { - newFields[fields[i]] = 1; - } - // Set the fields - fields = newFields; - } - - if(3 === len) { - options = args[2]; - } - - // Ensure selector is not null - selector = selector == null ? {} : selector; - // Validate correctness off the selector - var object = selector; - if(Buffer.isBuffer(object)) { - var object_size = object[0] | object[1] << 8 | object[2] << 16 | object[3] << 24; - if(object_size != object.length) { - var error = new Error("query selector raw message size does not match message header size [" + object.length + "] != [" + object_size + "]"); - error.name = 'MongoError'; - throw error; - } - } - - // Validate correctness of the field selector - object = fields; - if(Buffer.isBuffer(object)) { - object_size = object[0] | object[1] << 8 | object[2] << 16 | object[3] << 24; - if(object_size != object.length) { - error = new Error("query fields raw message size does not match message header size [" + object.length + "] != [" + object_size + "]"); - error.name = 'MongoError'; - throw error; - } - } - - // Check special case where we are using an objectId - if(selector != null && selector._bsontype == 'ObjectID') { - selector = {_id:selector}; - } - - // If it's a serialized fields field we need to just let it through - // user be warned it better be good - if(options && options.fields && !(Buffer.isBuffer(options.fields))) { - fields = {}; - - if(Array.isArray(options.fields)) { - if(!options.fields.length) { - fields['_id'] = 1; - } else { - var l = options.fields.length; - - for (i = 0; i < l; i++) { - fields[options.fields[i]] = 1; + * ``` + */ +class Collection { + /** + * Create a new Collection instance + * @internal + */ + constructor(db, name, options) { + var _a, _b; + (0, utils_1.checkCollectionName)(name); + // Internal state + this.s = { + db, + options, + namespace: new utils_1.MongoDBNamespace(db.databaseName, name), + pkFactory: (_b = (_a = db.options) === null || _a === void 0 ? void 0 : _a.pkFactory) !== null && _b !== void 0 ? _b : utils_1.DEFAULT_PK_FACTORY, + readPreference: read_preference_1.ReadPreference.fromOptions(options), + bsonOptions: (0, bson_1.resolveBSONOptions)(options, db), + readConcern: read_concern_1.ReadConcern.fromOptions(options), + writeConcern: write_concern_1.WriteConcern.fromOptions(options) + }; + } + /** + * The name of the database this collection belongs to + */ + get dbName() { + return this.s.namespace.db; + } + /** + * The name of this collection + */ + get collectionName() { + // eslint-disable-next-line @typescript-eslint/no-non-null-assertion + return this.s.namespace.collection; + } + /** + * The namespace of this collection, in the format `${this.dbName}.${this.collectionName}` + */ + get namespace() { + return this.s.namespace.toString(); + } + /** + * The current readConcern of the collection. If not explicitly defined for + * this collection, will be inherited from the parent DB + */ + get readConcern() { + if (this.s.readConcern == null) { + return this.s.db.readConcern; } - } - } else { - fields = options.fields; - } - } - - if (!options) options = {}; - - var newOptions = {}; - - // Make a shallow copy of the collection options - for(var key in this.s.options) { - if(mergeKeys.indexOf(key) != -1) { - newOptions[key] = this.s.options[key]; - } - } - - // Make a shallow copy of options - for (var key in options) { - newOptions[key] = options[key]; - } - - // Unpack options - newOptions.skip = len > 3 ? args[2] : options.skip ? options.skip : 0; - newOptions.limit = len > 3 ? args[3] : options.limit ? options.limit : 0; - newOptions.raw = options.raw != null && typeof options.raw === 'boolean' ? options.raw : this.s.raw; - newOptions.hint = options.hint != null ? normalizeHintField(options.hint) : this.s.collectionHint; - newOptions.timeout = len == 5 ? args[4] : typeof options.timeout === 'undefined' ? undefined : options.timeout; - // // If we have overridden slaveOk otherwise use the default db setting - newOptions.slaveOk = options.slaveOk != null ? options.slaveOk : this.s.db.slaveOk; - - // Add read preference if needed - newOptions = getReadPreference(this, newOptions, this.s.db, this); - - // Set slave ok to true if read preference different from primary - if(newOptions.readPreference != null - && (newOptions.readPreference != 'primary' || newOptions.readPreference.mode != 'primary')) { - newOptions.slaveOk = true; - } - - // Ensure the query is an object - if(selector != null && typeof selector != 'object') { - throw MongoError.create({message: "query selector must be an object", driver:true }); - } - - // Build the find command - var findCommand = { - find: this.s.namespace - , limit: newOptions.limit - , skip: newOptions.skip - , query: selector - } - - // Ensure we use the right await data option - if(typeof newOptions.awaitdata == 'boolean') { - newOptions.awaitData = newOptions.awaitdata - } - - // Translate to new command option noCursorTimeout - if(typeof newOptions.timeout == 'boolean') newOptions.noCursorTimeout = newOptions.timeout; - - // Merge in options to command - for(var name in newOptions) { - if(newOptions[name] != null) findCommand[name] = newOptions[name]; - } - - // Format the fields - var formatFields = function(fields) { - var object = {}; - if(Array.isArray(fields)) { - for(var i = 0; i < fields.length; i++) { - if(Array.isArray(fields[i])) { - object[fields[i][0]] = fields[i][1]; - } else { - object[fields[i][0]] = 1; + return this.s.readConcern; + } + /** + * The current readPreference of the collection. If not explicitly defined for + * this collection, will be inherited from the parent DB + */ + get readPreference() { + if (this.s.readPreference == null) { + return this.s.db.readPreference; } - } - } else { - object = fields; - } - - return object; - } - - // Special treatment for the fields selector - if(fields) findCommand.fields = formatFields(fields); - - // Add db object to the new options - newOptions.db = this.s.db; - - // Add the promise library - newOptions.promiseLibrary = this.s.promiseLibrary; - - // Set raw if available at collection level - if(newOptions.raw == null && typeof this.s.raw == 'boolean') newOptions.raw = this.s.raw; - // Set promoteLongs if available at collection level - if(newOptions.promoteLongs == null && typeof this.s.promoteLongs == 'boolean') newOptions.promoteLongs = this.s.promoteLongs; - if(newOptions.promoteValues == null && typeof this.s.promoteValues == 'boolean') newOptions.promoteValues = this.s.promoteValues; - if(newOptions.promoteBuffers == null && typeof this.s.promoteBuffers == 'boolean') newOptions.promoteBuffers = this.s.promoteBuffers; - - // Sort options - if(findCommand.sort) { - findCommand.sort = formattedOrderClause(findCommand.sort); - } - - // Set the readConcern - if(this.s.readConcern) { - findCommand.readConcern = this.s.readConcern; - } - - // Decorate find command with collation options - decorateWithCollation(findCommand, this, options); - - // Create the cursor - if(typeof callback == 'function') return handleCallback(callback, null, this.s.topology.cursor(this.s.namespace, findCommand, newOptions)); - return this.s.topology.cursor(this.s.namespace, findCommand, newOptions); -} - -define.classMethod('find', {callback: false, promise:false, returns: [Cursor]}); - -/** - * Inserts a single document into MongoDB. If documents passed in do not contain the **_id** field, - * one will be added to each of the documents missing it by the driver, mutating the document. This behavior - * can be overridden by setting the **forceServerObjectId** flag. - * - * @method - * @param {object} doc Document to insert. - * @param {object} [options=null] Optional settings. - * @param {(number|string)} [options.w=null] The write concern. - * @param {number} [options.wtimeout=null] The write concern timeout. - * @param {boolean} [options.j=false] Specify a journal write concern. - * @param {boolean} [options.serializeFunctions=false] Serialize functions on any object. - * @param {boolean} [options.forceServerObjectId=false] Force server to assign _id values instead of driver. - * @param {boolean} [options.bypassDocumentValidation=false] Allow driver to bypass schema validation in MongoDB 3.2 or higher. - * @param {Collection~insertOneWriteOpCallback} [callback] The command result callback - * @return {Promise} returns Promise if no callback passed - */ -Collection.prototype.insertOne = function(doc, options, callback) { - var self = this; - if(typeof options == 'function') callback = options, options = {}; - options = options || {}; - if(Array.isArray(doc) && typeof callback == 'function') { - return callback(MongoError.create({message: 'doc parameter must be an object', driver:true })); - } else if(Array.isArray(doc)) { - return new this.s.promiseLibrary(function(resolve, reject) { - reject(MongoError.create({message: 'doc parameter must be an object', driver:true })); - }); - } - - // Add ignoreUndefined - if(this.s.options.ignoreUndefined) { - options = shallowClone(options); - options.ignoreUndefined = this.s.options.ignoreUndefined; - } - - // Execute using callback - if(typeof callback == 'function') return insertOne(self, doc, options, callback); - - // Return a Promise - return new this.s.promiseLibrary(function(resolve, reject) { - insertOne(self, doc, options, function(err, r) { - if(err) return reject(err); - resolve(r); - }); - }); -} - -var insertOne = function(self, doc, options, callback) { - insertDocuments(self, [doc], options, function(err, r) { - if(callback == null) return; - if(err && callback) return callback(err); - // Workaround for pre 2.6 servers - if(r == null) return callback(null, {result: {ok:1}}); - // Add values to top level to ensure crud spec compatibility - r.insertedCount = r.result.n; - r.insertedId = doc._id; - if(callback) callback(null, r); - }); -} - -var mapInsertManyResults = function(docs, r) { - var ids = r.getInsertedIds(); - var keys = Object.keys(ids); - var finalIds = new Array(keys.length); - - for(var i = 0; i < keys.length; i++) { - if(ids[keys[i]]._id) { - finalIds[ids[keys[i]].index] = ids[keys[i]]._id; - } - } - - var finalResult = { - result: {ok: 1, n: r.insertedCount}, - ops: docs, - insertedCount: r.insertedCount, - insertedIds: finalIds - }; - - if(r.getLastOp()) { - finalResult.result.opTime = r.getLastOp(); - } - - return finalResult; -} - -define.classMethod('insertOne', {callback: true, promise:true}); - -/** - * Inserts an array of documents into MongoDB. If documents passed in do not contain the **_id** field, - * one will be added to each of the documents missing it by the driver, mutating the document. This behavior - * can be overridden by setting the **forceServerObjectId** flag. - * - * @method - * @param {object[]} docs Documents to insert. - * @param {object} [options=null] Optional settings. - * @param {(number|string)} [options.w=null] The write concern. - * @param {number} [options.wtimeout=null] The write concern timeout. - * @param {boolean} [options.j=false] Specify a journal write concern. - * @param {boolean} [options.serializeFunctions=false] Serialize functions on any object. - * @param {boolean} [options.forceServerObjectId=false] Force server to assign _id values instead of driver. - * @param {boolean} [options.bypassDocumentValidation=false] Allow driver to bypass schema validation in MongoDB 3.2 or higher. - * @param {boolean} [options.ordered=true] If true, when an insert fails, don't execute the remaining writes. If false, continue with remaining inserts when one fails. - * @param {Collection~insertWriteOpCallback} [callback] The command result callback - * @return {Promise} returns Promise if no callback passed - */ -Collection.prototype.insertMany = function(docs, options, callback) { - var self = this; - if(typeof options == 'function') callback = options, options = {}; - options = options ? shallowClone(options) : {ordered:true}; - if(!Array.isArray(docs) && typeof callback == 'function') { - return callback(MongoError.create({message: 'docs parameter must be an array of documents', driver:true })); - } else if(!Array.isArray(docs)) { - return new this.s.promiseLibrary(function(resolve, reject) { - reject(MongoError.create({message: 'docs parameter must be an array of documents', driver:true })); - }); - } - - // Get the write concern options - if(typeof options.checkKeys != 'boolean') { - options.checkKeys = true; - } - - // If keep going set unordered - options['serializeFunctions'] = options['serializeFunctions'] || self.s.serializeFunctions; - - // Set up the force server object id - var forceServerObjectId = typeof options.forceServerObjectId == 'boolean' - ? options.forceServerObjectId : self.s.db.options.forceServerObjectId; - - // Do we want to force the server to assign the _id key - if(forceServerObjectId !== true) { - // Add _id if not specified - for(var i = 0; i < docs.length; i++) { - if(docs[i]._id == null) docs[i]._id = self.s.pkFactory.createPk(); - } - } - - // Generate the bulk write operations - var operations = [{ - insertMany: docs - }]; - - // Execute using callback - if(typeof callback == 'function') return bulkWrite(self, operations, options, function(err, r) { - if(err) return callback(err, r); - callback(null, mapInsertManyResults(docs, r)); - }); - - // Return a Promise - return new this.s.promiseLibrary(function(resolve, reject) { - bulkWrite(self, operations, options, function(err, r) { - if(err) return reject(err); - resolve(mapInsertManyResults(docs, r)); - }); - }); -} - -define.classMethod('insertMany', {callback: true, promise:true}); - -/** - * @typedef {Object} Collection~BulkWriteOpResult - * @property {number} insertedCount Number of documents inserted. - * @property {number} matchedCount Number of documents matched for update. - * @property {number} modifiedCount Number of documents modified. - * @property {number} deletedCount Number of documents deleted. - * @property {number} upsertedCount Number of documents upserted. - * @property {object} insertedIds Inserted document generated Id's, hash key is the index of the originating operation - * @property {object} upsertedIds Upserted document generated Id's, hash key is the index of the originating operation - * @property {object} result The command result object. - */ - -/** - * The callback format for inserts - * @callback Collection~bulkWriteOpCallback - * @param {MongoError} error An error instance representing the error during the execution. - * @param {Collection~BulkWriteOpResult} result The result object if the command was executed successfully. - */ - -/** - * Perform a bulkWrite operation without a fluent API - * - * Legal operation types are - * - * { insertOne: { document: { a: 1 } } } - * - * { updateOne: { filter: {a:2}, update: {$set: {a:2}}, upsert:true } } - * - * { updateMany: { filter: {a:2}, update: {$set: {a:2}}, upsert:true } } - * - * { deleteOne: { filter: {c:1} } } - * - * { deleteMany: { filter: {c:1} } } - * - * { replaceOne: { filter: {c:3}, replacement: {c:4}, upsert:true}} - * - * If documents passed in do not contain the **_id** field, - * one will be added to each of the documents missing it by the driver, mutating the document. This behavior - * can be overridden by setting the **forceServerObjectId** flag. - * - * @method - * @param {object[]} operations Bulk operations to perform. - * @param {object} [options=null] Optional settings. - * @param {(number|string)} [options.w=null] The write concern. - * @param {number} [options.wtimeout=null] The write concern timeout. - * @param {boolean} [options.j=false] Specify a journal write concern. - * @param {boolean} [options.serializeFunctions=false] Serialize functions on any object. - * @param {boolean} [options.ordered=true] Execute write operation in ordered or unordered fashion. - * @param {boolean} [options.bypassDocumentValidation=false] Allow driver to bypass schema validation in MongoDB 3.2 or higher. - * @param {Collection~bulkWriteOpCallback} [callback] The command result callback - * @return {Promise} returns Promise if no callback passed - */ -Collection.prototype.bulkWrite = function(operations, options, callback) { - var self = this; - if(typeof options == 'function') callback = options, options = {}; - options = options || {ordered:true}; - - if(!Array.isArray(operations)) { - throw MongoError.create({message: "operations must be an array of documents", driver:true }); - } - - // Execute using callback - if(typeof callback == 'function') return bulkWrite(self, operations, options, callback); - - // Return a Promise - return new this.s.promiseLibrary(function(resolve, reject) { - bulkWrite(self, operations, options, function(err, r) { - if(err && r == null) return reject(err); - resolve(r); - }); - }); -} - -var bulkWrite = function(self, operations, options, callback) { - // Add ignoreUndefined - if(self.s.options.ignoreUndefined) { - options = shallowClone(options); - options.ignoreUndefined = self.s.options.ignoreUndefined; - } - - // Create the bulk operation - var bulk = options.ordered == true || options.ordered == null ? self.initializeOrderedBulkOp(options) : self.initializeUnorderedBulkOp(options); - - // Do we have a collation - var collation = false; - - // for each op go through and add to the bulk - try { - for(var i = 0; i < operations.length; i++) { - // Get the operation type - var key = Object.keys(operations[i])[0]; - // Check if we have a collation - if(operations[i][key].collation) { - collation = true; - } - - // Pass to the raw bulk - bulk.raw(operations[i]); - } - } catch(err) { - return callback(err, null); - } - - // Final options for write concern - var finalOptions = writeConcern(shallowClone(options), self.s.db, self, options); - var writeCon = finalOptions.writeConcern ? finalOptions.writeConcern : {}; - var capabilities = self.s.topology.capabilities(); - - // Did the user pass in a collation, check if our write server supports it - if(collation && capabilities && !capabilities.commandsTakeCollation) { - return callback(new MongoError(f('server/primary/mongos does not support collation'))); - } - - // Execute the bulk - bulk.execute(writeCon, function(err, r) { - // We have connection level error - if(!r && err) return callback(err, null); - // We have single error - if(r && r.hasWriteErrors() && r.getWriteErrorCount() == 1) { - return callback(toError(r.getWriteErrorAt(0)), r); - } - - r.insertedCount = r.nInserted; - r.matchedCount = r.nMatched; - r.modifiedCount = r.nModified || 0; - r.deletedCount = r.nRemoved; - r.upsertedCount = r.getUpsertedIds().length; - r.upsertedIds = {}; - r.insertedIds = {}; - - // Update the n - r.n = r.insertedCount; - - // Inserted documents - var inserted = r.getInsertedIds(); - // Map inserted ids - for(var i = 0; i < inserted.length; i++) { - r.insertedIds[inserted[i].index] = inserted[i]._id; - } - - // Upserted documents - var upserted = r.getUpsertedIds(); - // Map upserted ids - for(i = 0; i < upserted.length; i++) { - r.upsertedIds[upserted[i].index] = upserted[i]._id; - } - - // Check if we have write errors - if(r.hasWriteErrors()) { - // Get all the errors - var errors = r.getWriteErrors(); - // Return the MongoError object - return callback(toError({ - message: 'write operation failed', code: errors[0].code, writeErrors: errors - }), r); - } - - // Check if we have a writeConcern error - if(r.getWriteConcernError()) { - // Return the MongoError object - return callback(toError(r.getWriteConcernError()), r); - } - - // Return the results - callback(null, r); - }); -} - -var insertDocuments = function(self, docs, options, callback) { - if(typeof options == 'function') callback = options, options = {}; - options = options || {}; - // Ensure we are operating on an array op docs - docs = Array.isArray(docs) ? docs : [docs]; - - // Get the write concern options - var finalOptions = writeConcern(shallowClone(options), self.s.db, self, options); - if(typeof finalOptions.checkKeys != 'boolean') finalOptions.checkKeys = true; - - // If keep going set unordered - if(finalOptions.keepGoing == true) finalOptions.ordered = false; - finalOptions['serializeFunctions'] = options['serializeFunctions'] || self.s.serializeFunctions; - - // Set up the force server object id - var forceServerObjectId = typeof options.forceServerObjectId == 'boolean' - ? options.forceServerObjectId : self.s.db.options.forceServerObjectId; - - // Add _id if not specified - if(forceServerObjectId !== true){ - for(var i = 0; i < docs.length; i++) { - if(docs[i]._id === void 0) docs[i]._id = self.s.pkFactory.createPk(); - } - } - - // File inserts - self.s.topology.insert(self.s.namespace, docs, finalOptions, function(err, result) { - if(callback == null) return; - if(err) return handleCallback(callback, err); - if(result == null) return handleCallback(callback, null, null); - if(result.result.code) return handleCallback(callback, toError(result.result)); - if(result.result.writeErrors) return handleCallback(callback, toError(result.result.writeErrors[0])); - // Add docs to the list - result.ops = docs; - // Return the results - handleCallback(callback, null, result); - }); -} - -define.classMethod('bulkWrite', {callback: true, promise:true}); - -/** - * @typedef {Object} Collection~WriteOpResult - * @property {object[]} ops All the documents inserted using insertOne/insertMany/replaceOne. Documents contain the _id field if forceServerObjectId == false for insertOne/insertMany - * @property {object} connection The connection object used for the operation. - * @property {object} result The command result object. - */ - -/** - * The callback format for inserts - * @callback Collection~writeOpCallback - * @param {MongoError} error An error instance representing the error during the execution. - * @param {Collection~WriteOpResult} result The result object if the command was executed successfully. - */ - -/** - * @typedef {Object} Collection~insertWriteOpResult - * @property {Number} insertedCount The total amount of documents inserted. - * @property {object[]} ops All the documents inserted using insertOne/insertMany/replaceOne. Documents contain the _id field if forceServerObjectId == false for insertOne/insertMany - * @property {ObjectId[]} insertedIds All the generated _id's for the inserted documents. - * @property {object} connection The connection object used for the operation. - * @property {object} result The raw command result object returned from MongoDB (content might vary by server version). - * @property {Number} result.ok Is 1 if the command executed correctly. - * @property {Number} result.n The total count of documents inserted. - */ - -/** - * @typedef {Object} Collection~insertOneWriteOpResult - * @property {Number} insertedCount The total amount of documents inserted. - * @property {object[]} ops All the documents inserted using insertOne/insertMany/replaceOne. Documents contain the _id field if forceServerObjectId == false for insertOne/insertMany - * @property {ObjectId} insertedId The driver generated ObjectId for the insert operation. - * @property {object} connection The connection object used for the operation. - * @property {object} result The raw command result object returned from MongoDB (content might vary by server version). - * @property {Number} result.ok Is 1 if the command executed correctly. - * @property {Number} result.n The total count of documents inserted. - */ - -/** - * The callback format for inserts - * @callback Collection~insertWriteOpCallback - * @param {MongoError} error An error instance representing the error during the execution. - * @param {Collection~insertWriteOpResult} result The result object if the command was executed successfully. - */ - -/** - * The callback format for inserts - * @callback Collection~insertOneWriteOpCallback - * @param {MongoError} error An error instance representing the error during the execution. - * @param {Collection~insertOneWriteOpResult} result The result object if the command was executed successfully. - */ - -/** - * Inserts a single document or a an array of documents into MongoDB. If documents passed in do not contain the **_id** field, - * one will be added to each of the documents missing it by the driver, mutating the document. This behavior - * can be overridden by setting the **forceServerObjectId** flag. - * - * @method - * @param {(object|object[])} docs Documents to insert. - * @param {object} [options=null] Optional settings. - * @param {(number|string)} [options.w=null] The write concern. - * @param {number} [options.wtimeout=null] The write concern timeout. - * @param {boolean} [options.j=false] Specify a journal write concern. - * @param {boolean} [options.serializeFunctions=false] Serialize functions on any object. - * @param {boolean} [options.forceServerObjectId=false] Force server to assign _id values instead of driver. - * @param {boolean} [options.bypassDocumentValidation=false] Allow driver to bypass schema validation in MongoDB 3.2 or higher. - * @param {Collection~insertWriteOpCallback} [callback] The command result callback - * @return {Promise} returns Promise if no callback passed - * @deprecated Use insertOne, insertMany or bulkWrite - */ -Collection.prototype.insert = function(docs, options, callback) { - if(typeof options == 'function') callback = options, options = {}; - options = options || {ordered:false}; - docs = !Array.isArray(docs) ? [docs] : docs; - - if(options.keepGoing == true) { - options.ordered = false; - } - - return this.insertMany(docs, options, callback); -} - -define.classMethod('insert', {callback: true, promise:true}); - -/** - * @typedef {Object} Collection~updateWriteOpResult - * @property {Object} result The raw result returned from MongoDB, field will vary depending on server version. - * @property {Number} result.ok Is 1 if the command executed correctly. - * @property {Number} result.n The total count of documents scanned. - * @property {Number} result.nModified The total count of documents modified. - * @property {Object} connection The connection object used for the operation. - * @property {Number} matchedCount The number of documents that matched the filter. - * @property {Number} modifiedCount The number of documents that were modified. - * @property {Number} upsertedCount The number of documents upserted. - * @property {Object} upsertedId The upserted id. - * @property {ObjectId} upsertedId._id The upserted _id returned from the server. - */ - -/** - * The callback format for inserts - * @callback Collection~updateWriteOpCallback - * @param {MongoError} error An error instance representing the error during the execution. - * @param {Collection~updateWriteOpResult} result The result object if the command was executed successfully. - */ - -/** - * Update a single document on MongoDB - * @method - * @param {object} filter The Filter used to select the document to update - * @param {object} update The update operations to be applied to the document - * @param {object} [options=null] Optional settings. - * @param {boolean} [options.upsert=false] Update operation is an upsert. - * @param {(number|string)} [options.w=null] The write concern. - * @param {number} [options.wtimeout=null] The write concern timeout. - * @param {boolean} [options.j=false] Specify a journal write concern. - * @param {boolean} [options.bypassDocumentValidation=false] Allow driver to bypass schema validation in MongoDB 3.2 or higher. - * @param {Collection~updateWriteOpCallback} [callback] The command result callback - * @return {Promise} returns Promise if no callback passed - */ -Collection.prototype.updateOne = function(filter, update, options, callback) { - var self = this; - if(typeof options == 'function') callback = options, options = {}; - options = shallowClone(options) - - // Add ignoreUndefined - if(this.s.options.ignoreUndefined) { - options = shallowClone(options); - options.ignoreUndefined = this.s.options.ignoreUndefined; - } - - // Execute using callback - if(typeof callback == 'function') return updateOne(self, filter, update, options, callback); - - // Return a Promise - return new this.s.promiseLibrary(function(resolve, reject) { - updateOne(self, filter, update, options, function(err, r) { - if(err) return reject(err); - resolve(r); - }); - }); -} - -var updateOne = function(self, filter, update, options, callback) { - // Set single document update - options.multi = false; - // Execute update - updateDocuments(self, filter, update, options, function(err, r) { - if(callback == null) return; - if(err && callback) return callback(err); - if(r == null) return callback(null, {result: {ok:1}}); - r.modifiedCount = r.result.nModified != null ? r.result.nModified : r.result.n; - r.upsertedId = Array.isArray(r.result.upserted) && r.result.upserted.length > 0 ? r.result.upserted[0] : null; - r.upsertedCount = Array.isArray(r.result.upserted) && r.result.upserted.length ? r.result.upserted.length : 0; - r.matchedCount = Array.isArray(r.result.upserted) && r.result.upserted.length > 0 ? 0 : r.result.n; - if(callback) callback(null, r); - }); -} - -define.classMethod('updateOne', {callback: true, promise:true}); - -/** - * Replace a document on MongoDB - * @method - * @param {object} filter The Filter used to select the document to update - * @param {object} doc The Document that replaces the matching document - * @param {object} [options=null] Optional settings. - * @param {boolean} [options.upsert=false] Update operation is an upsert. - * @param {(number|string)} [options.w=null] The write concern. - * @param {number} [options.wtimeout=null] The write concern timeout. - * @param {boolean} [options.j=false] Specify a journal write concern. - * @param {boolean} [options.bypassDocumentValidation=false] Allow driver to bypass schema validation in MongoDB 3.2 or higher. - * @param {Collection~updateWriteOpCallback} [callback] The command result callback - * @return {Promise} returns Promise if no callback passed - */ -Collection.prototype.replaceOne = function(filter, doc, options, callback) { - var self = this; - if(typeof options == 'function') callback = options, options = {}; - options = shallowClone(options) - - // Add ignoreUndefined - if(this.s.options.ignoreUndefined) { - options = shallowClone(options); - options.ignoreUndefined = this.s.options.ignoreUndefined; - } - - // Execute using callback - if(typeof callback == 'function') return replaceOne(self, filter, doc, options, callback); - - // Return a Promise - return new this.s.promiseLibrary(function(resolve, reject) { - replaceOne(self, filter, doc, options, function(err, r) { - if(err) return reject(err); - resolve(r); - }); - }); -} - -var replaceOne = function(self, filter, doc, options, callback) { - // Set single document update - options.multi = false; - - // Execute update - updateDocuments(self, filter, doc, options, function(err, r) { - if(callback == null) return; - if(err && callback) return callback(err); - if(r == null) return callback(null, {result: {ok:1}}); - - r.modifiedCount = r.result.nModified != null ? r.result.nModified : r.result.n; - r.upsertedId = Array.isArray(r.result.upserted) && r.result.upserted.length > 0 ? r.result.upserted[0] : null; - r.upsertedCount = Array.isArray(r.result.upserted) && r.result.upserted.length ? r.result.upserted.length : 0; - r.matchedCount = Array.isArray(r.result.upserted) && r.result.upserted.length > 0 ? 0 : r.result.n; - r.ops = [doc]; - if(callback) callback(null, r); - }); -} - -define.classMethod('replaceOne', {callback: true, promise:true}); - -/** - * Update multiple documents on MongoDB - * @method - * @param {object} filter The Filter used to select the document to update - * @param {object} update The update operations to be applied to the document - * @param {object} [options=null] Optional settings. - * @param {boolean} [options.upsert=false] Update operation is an upsert. - * @param {(number|string)} [options.w=null] The write concern. - * @param {number} [options.wtimeout=null] The write concern timeout. - * @param {boolean} [options.j=false] Specify a journal write concern. - * @param {Collection~updateWriteOpCallback} [callback] The command result callback - * @return {Promise} returns Promise if no callback passed - */ -Collection.prototype.updateMany = function(filter, update, options, callback) { - var self = this; - if(typeof options == 'function') callback = options, options = {}; - options = shallowClone(options) - - // Add ignoreUndefined - if(this.s.options.ignoreUndefined) { - options = shallowClone(options); - options.ignoreUndefined = this.s.options.ignoreUndefined; - } - - // Execute using callback - if(typeof callback == 'function') return updateMany(self, filter, update, options, callback); - - // Return a Promise - return new this.s.promiseLibrary(function(resolve, reject) { - updateMany(self, filter, update, options, function(err, r) { - if(err) return reject(err); - resolve(r); - }); - }); -} - -var updateMany = function(self, filter, update, options, callback) { - // Set single document update - options.multi = true; - // Execute update - updateDocuments(self, filter, update, options, function(err, r) { - if(callback == null) return; - if(err && callback) return callback(err); - if(r == null) return callback(null, {result: {ok:1}}); - r.modifiedCount = r.result.nModified != null ? r.result.nModified : r.result.n; - r.upsertedId = Array.isArray(r.result.upserted) && r.result.upserted.length > 0 ? r.result.upserted[0] : null; - r.upsertedCount = Array.isArray(r.result.upserted) && r.result.upserted.length ? r.result.upserted.length : 0; - r.matchedCount = Array.isArray(r.result.upserted) && r.result.upserted.length > 0 ? 0 : r.result.n; - if(callback) callback(null, r); - }); -} - -define.classMethod('updateMany', {callback: true, promise:true}); - -var updateDocuments = function(self, selector, document, options, callback) { - if('function' === typeof options) callback = options, options = null; - if(options == null) options = {}; - if(!('function' === typeof callback)) callback = null; - - // If we are not providing a selector or document throw - if(selector == null || typeof selector != 'object') return callback(toError("selector must be a valid JavaScript object")); - if(document == null || typeof document != 'object') return callback(toError("document must be a valid JavaScript object")); - - // Get the write concern options - var finalOptions = writeConcern(shallowClone(options), self.s.db, self, options); - - // Do we return the actual result document - // Either use override on the function, or go back to default on either the collection - // level or db - finalOptions['serializeFunctions'] = options['serializeFunctions'] || self.s.serializeFunctions; - - // Execute the operation - var op = {q: selector, u: document}; - op.upsert = typeof options.upsert == 'boolean' ? options.upsert : false; - op.multi = typeof options.multi == 'boolean' ? options.multi : false; - - // Have we specified collation - decorateWithCollation(finalOptions, self, options); - - // Update options - self.s.topology.update(self.s.namespace, [op], finalOptions, function(err, result) { - if(callback == null) return; - if(err) return handleCallback(callback, err, null); - if(result == null) return handleCallback(callback, null, null); - if(result.result.code) return handleCallback(callback, toError(result.result)); - if(result.result.writeErrors) return handleCallback(callback, toError(result.result.writeErrors[0])); - // Return the results - handleCallback(callback, null, result); - }); -} - -/** - * Updates documents. - * @method - * @param {object} selector The selector for the update operation. - * @param {object} document The update document. - * @param {object} [options=null] Optional settings. - * @param {(number|string)} [options.w=null] The write concern. - * @param {number} [options.wtimeout=null] The write concern timeout. - * @param {boolean} [options.j=false] Specify a journal write concern. - * @param {boolean} [options.upsert=false] Update operation is an upsert. - * @param {boolean} [options.multi=false] Update one/all documents with operation. - * @param {boolean} [options.bypassDocumentValidation=false] Allow driver to bypass schema validation in MongoDB 3.2 or higher. - * @param {object} [options.collation=null] Specify collation (MongoDB 3.4 or higher) settings for update operation (see 3.4 documentation for available fields). - * @param {Collection~writeOpCallback} [callback] The command result callback - * @throws {MongoError} - * @return {Promise} returns Promise if no callback passed - * @deprecated use updateOne, updateMany or bulkWrite - */ -Collection.prototype.update = function(selector, document, options, callback) { - var self = this; - - // Add ignoreUndefined - if(this.s.options.ignoreUndefined) { - options = shallowClone(options); - options.ignoreUndefined = this.s.options.ignoreUndefined; - } - - // Execute using callback - if(typeof callback == 'function') return updateDocuments(self, selector, document, options, callback); - - // Return a Promise - return new this.s.promiseLibrary(function(resolve, reject) { - updateDocuments(self, selector, document, options, function(err, r) { - if(err) return reject(err); - resolve(r); - }); - }); -} - -define.classMethod('update', {callback: true, promise:true}); - -/** - * @typedef {Object} Collection~deleteWriteOpResult - * @property {Object} result The raw result returned from MongoDB, field will vary depending on server version. - * @property {Number} result.ok Is 1 if the command executed correctly. - * @property {Number} result.n The total count of documents deleted. - * @property {Object} connection The connection object used for the operation. - * @property {Number} deletedCount The number of documents deleted. - */ - -/** - * The callback format for inserts - * @callback Collection~deleteWriteOpCallback - * @param {MongoError} error An error instance representing the error during the execution. - * @param {Collection~deleteWriteOpResult} result The result object if the command was executed successfully. - */ - -/** - * Delete a document on MongoDB - * @method - * @param {object} filter The Filter used to select the document to remove - * @param {object} [options=null] Optional settings. - * @param {(number|string)} [options.w=null] The write concern. - * @param {number} [options.wtimeout=null] The write concern timeout. - * @param {boolean} [options.j=false] Specify a journal write concern. - * @param {Collection~deleteWriteOpCallback} [callback] The command result callback - * @return {Promise} returns Promise if no callback passed - */ -Collection.prototype.deleteOne = function(filter, options, callback) { - var self = this; - if(typeof options == 'function') callback = options, options = {}; - options = shallowClone(options); - - // Add ignoreUndefined - if(this.s.options.ignoreUndefined) { - options = shallowClone(options); - options.ignoreUndefined = this.s.options.ignoreUndefined; - } - - // Execute using callback - if(typeof callback == 'function') return deleteOne(self, filter, options, callback); - - // Return a Promise - return new this.s.promiseLibrary(function(resolve, reject) { - deleteOne(self, filter, options, function(err, r) { - if(err) return reject(err); - resolve(r); - }); - }); -} - -var deleteOne = function(self, filter, options, callback) { - options.single = true; - removeDocuments(self, filter, options, function(err, r) { - if(callback == null) return; - if(err && callback) return callback(err); - if(r == null) return callback(null, {result: {ok:1}}); - r.deletedCount = r.result.n; - if(callback) callback(null, r); - }); -} - -define.classMethod('deleteOne', {callback: true, promise:true}); - -Collection.prototype.removeOne = Collection.prototype.deleteOne; - -define.classMethod('removeOne', {callback: true, promise:true}); - -/** - * Delete multiple documents on MongoDB - * @method - * @param {object} filter The Filter used to select the documents to remove - * @param {object} [options=null] Optional settings. - * @param {(number|string)} [options.w=null] The write concern. - * @param {number} [options.wtimeout=null] The write concern timeout. - * @param {boolean} [options.j=false] Specify a journal write concern. - * @param {Collection~deleteWriteOpCallback} [callback] The command result callback - * @return {Promise} returns Promise if no callback passed - */ -Collection.prototype.deleteMany = function(filter, options, callback) { - var self = this; - if(typeof options == 'function') callback = options, options = {}; - options = shallowClone(options); - - // Add ignoreUndefined - if(this.s.options.ignoreUndefined) { - options = shallowClone(options); - options.ignoreUndefined = this.s.options.ignoreUndefined; - } - - // Execute using callback - if(typeof callback == 'function') return deleteMany(self, filter, options, callback); - - // Return a Promise - return new this.s.promiseLibrary(function(resolve, reject) { - deleteMany(self, filter, options, function(err, r) { - if(err) return reject(err); - resolve(r); - }); - }); -} - -var deleteMany = function(self, filter, options, callback) { - options.single = false; - - removeDocuments(self, filter, options, function(err, r) { - if(callback == null) return; - if(err && callback) return callback(err); - if(r == null) return callback(null, {result: {ok:1}}); - r.deletedCount = r.result.n; - if(callback) callback(null, r); - }); -} - -var removeDocuments = function(self, selector, options, callback) { - if(typeof options == 'function') { - callback = options, options = {}; - } else if (typeof selector === 'function') { - callback = selector; - options = {}; - selector = {}; - } - - // Create an empty options object if the provided one is null - options = options || {}; - - // Get the write concern options - var finalOptions = writeConcern(shallowClone(options), self.s.db, self, options); - - // If selector is null set empty - if(selector == null) selector = {}; - - // Build the op - var op = {q: selector, limit: 0}; - if(options.single) op.limit = 1; - - // Have we specified collation - decorateWithCollation(finalOptions, self, options); - - // Execute the remove - self.s.topology.remove(self.s.namespace, [op], finalOptions, function(err, result) { - if(callback == null) return; - if(err) return handleCallback(callback, err, null); - if(result == null) return handleCallback(callback, null, null); - if(result.result.code) return handleCallback(callback, toError(result.result)); - if(result.result.writeErrors) return handleCallback(callback, toError(result.result.writeErrors[0])); - // Return the results - handleCallback(callback, null, result); - }); -} - -define.classMethod('deleteMany', {callback: true, promise:true}); - -Collection.prototype.removeMany = Collection.prototype.deleteMany; - -define.classMethod('removeMany', {callback: true, promise:true}); - -/** - * Remove documents. - * @method - * @param {object} selector The selector for the update operation. - * @param {object} [options=null] Optional settings. - * @param {(number|string)} [options.w=null] The write concern. - * @param {number} [options.wtimeout=null] The write concern timeout. - * @param {boolean} [options.j=false] Specify a journal write concern. - * @param {boolean} [options.single=false] Removes the first document found. - * @param {Collection~writeOpCallback} [callback] The command result callback - * @return {Promise} returns Promise if no callback passed - * @deprecated use deleteOne, deleteMany or bulkWrite - */ -Collection.prototype.remove = function(selector, options, callback) { - var self = this; - - // Add ignoreUndefined - if(this.s.options.ignoreUndefined) { - options = shallowClone(options); - options.ignoreUndefined = this.s.options.ignoreUndefined; - } - - // Execute using callback - if(typeof callback == 'function') return removeDocuments(self, selector, options, callback); - - // Return a Promise - return new this.s.promiseLibrary(function(resolve, reject) { - removeDocuments(self, selector, options, function(err, r) { - if(err) return reject(err); - resolve(r); - }); - }); -} - -define.classMethod('remove', {callback: true, promise:true}); - -/** - * Save a document. Simple full document replacement function. Not recommended for efficiency, use atomic - * operators and update instead for more efficient operations. - * @method - * @param {object} doc Document to save - * @param {object} [options=null] Optional settings. - * @param {(number|string)} [options.w=null] The write concern. - * @param {number} [options.wtimeout=null] The write concern timeout. - * @param {boolean} [options.j=false] Specify a journal write concern. - * @param {Collection~writeOpCallback} [callback] The command result callback - * @return {Promise} returns Promise if no callback passed - * @deprecated use insertOne, insertMany, updateOne or updateMany - */ -Collection.prototype.save = function(doc, options, callback) { - var self = this; - if(typeof options == 'function') callback = options, options = {}; - options = options || {}; - - // Add ignoreUndefined - if(this.s.options.ignoreUndefined) { - options = shallowClone(options); - options.ignoreUndefined = this.s.options.ignoreUndefined; - } - - // Execute using callback - if(typeof callback == 'function') return save(self, doc, options, callback); - - // Return a Promise - return new this.s.promiseLibrary(function(resolve, reject) { - save(self, doc, options, function(err, r) { - if(err) return reject(err); - resolve(r); - }); - }); -} - -var save = function(self, doc, options, callback) { - // Get the write concern options - var finalOptions = writeConcern(shallowClone(options), self.s.db, self, options); - // Establish if we need to perform an insert or update - if(doc._id != null) { - finalOptions.upsert = true; - return updateDocuments(self, {_id: doc._id}, doc, finalOptions, callback); - } - - // Insert the document - insertDocuments(self, [doc], options, function(err, r) { - if(callback == null) return; - if(doc == null) return handleCallback(callback, null, null); - if(err) return handleCallback(callback, err, null); - handleCallback(callback, null, r); - }); -} - -define.classMethod('save', {callback: true, promise:true}); - -/** - * The callback format for results - * @callback Collection~resultCallback - * @param {MongoError} error An error instance representing the error during the execution. - * @param {object} result The result object if the command was executed successfully. - */ - -/** - * Fetches the first document that matches the query - * @method - * @param {object} query Query for find Operation - * @param {object} [options=null] Optional settings. - * @param {number} [options.limit=0] Sets the limit of documents returned in the query. - * @param {(array|object)} [options.sort=null] Set to sort the documents coming back from the query. Array of indexes, [['a', 1]] etc. - * @param {object} [options.fields=null] The fields to return in the query. Object of fields to include or exclude (not both), {'a':1} - * @param {number} [options.skip=0] Set to skip N documents ahead in your query (useful for pagination). - * @param {Object} [options.hint=null] Tell the query to use specific indexes in the query. Object of indexes to use, {'_id':1} - * @param {boolean} [options.explain=false] Explain the query instead of returning the data. - * @param {boolean} [options.snapshot=false] Snapshot query. - * @param {boolean} [options.timeout=false] Specify if the cursor can timeout. - * @param {boolean} [options.tailable=false] Specify if the cursor is tailable. - * @param {number} [options.batchSize=0] Set the batchSize for the getMoreCommand when iterating over the query results. - * @param {boolean} [options.returnKey=false] Only return the index key. - * @param {number} [options.maxScan=null] Limit the number of items to scan. - * @param {number} [options.min=null] Set index bounds. - * @param {number} [options.max=null] Set index bounds. - * @param {boolean} [options.showDiskLoc=false] Show disk location of results. - * @param {string} [options.comment=null] You can put a $comment field on a query to make looking in the profiler logs simpler. - * @param {boolean} [options.raw=false] Return document results as raw BSON buffers. - * @param {boolean} [options.promoteLongs=true] Promotes Long values to number if they fit inside the 53 bits resolution. - * @param {boolean} [options.promoteValues=true] Promotes BSON values to native types where possible, set to false to only receive wrapper types. - * @param {boolean} [options.promoteBuffers=false] Promotes Binary BSON values to native Node Buffers. - * @param {(ReadPreference|string)} [options.readPreference=null] The preferred read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST). - * @param {boolean} [options.partial=false] Specify if the cursor should return partial results when querying against a sharded system - * @param {number} [options.maxTimeMS=null] Number of milliseconds to wait before aborting the query. - * @param {object} [options.collation=null] Specify collation (MongoDB 3.4 or higher) settings for update operation (see 3.4 documentation for available fields). - * @param {Collection~resultCallback} [callback] The command result callback - * @return {Promise} returns Promise if no callback passed - */ -Collection.prototype.findOne = function() { - var self = this; - var args = Array.prototype.slice.call(arguments, 0); - var callback = args.pop(); - if(typeof callback != 'function') args.push(callback); - - // Execute using callback - if(typeof callback == 'function') return findOne(self, args, callback); - - // Return a Promise - return new this.s.promiseLibrary(function(resolve, reject) { - findOne(self, args, function(err, r) { - if(err) return reject(err); - resolve(r); - }); - }); -} - -var findOne = function(self, args, callback) { - var cursor = self.find.apply(self, args).limit(-1).batchSize(1); - // Return the item - cursor.next(function(err, item) { - if(err != null) return handleCallback(callback, toError(err), null); - handleCallback(callback, null, item); - }); -} - -define.classMethod('findOne', {callback: true, promise:true}); - -/** - * The callback format for the collection method, must be used if strict is specified - * @callback Collection~collectionResultCallback - * @param {MongoError} error An error instance representing the error during the execution. - * @param {Collection} collection The collection instance. - */ - -/** - * Rename the collection. - * - * @method - * @param {string} newName New name of of the collection. - * @param {object} [options=null] Optional settings. - * @param {boolean} [options.dropTarget=false] Drop the target name collection if it previously exists. - * @param {Collection~collectionResultCallback} [callback] The results callback - * @return {Promise} returns Promise if no callback passed - */ -Collection.prototype.rename = function(newName, opt, callback) { - var self = this; - if(typeof opt == 'function') callback = opt, opt = {}; - opt = assign({}, opt, {readPreference: ReadPreference.PRIMARY}); - - // Execute using callback - if(typeof callback == 'function') return rename(self, newName, opt, callback); - - // Return a Promise - return new this.s.promiseLibrary(function(resolve, reject) { - rename(self, newName, opt, function(err, r) { - if(err) return reject(err); - resolve(r); - }); - }); -} - -var rename = function(self, newName, opt, callback) { - // Check the collection name - checkCollectionName(newName); - // Build the command - var renameCollection = f("%s.%s", self.s.dbName, self.s.name); - var toCollection = f("%s.%s", self.s.dbName, newName); - var dropTarget = typeof opt.dropTarget == 'boolean' ? opt.dropTarget : false; - var cmd = {'renameCollection':renameCollection, 'to':toCollection, 'dropTarget':dropTarget}; - - // Decorate command with writeConcern if supported - decorateWithWriteConcern(cmd, self, opt); - - // Execute against admin - self.s.db.admin().command(cmd, opt, function(err, doc) { - if(err) return handleCallback(callback, err, null); - // We have an error - if(doc.errmsg) return handleCallback(callback, toError(doc), null); - try { - return handleCallback(callback, null, new Collection(self.s.db, self.s.topology, self.s.dbName, newName, self.s.pkFactory, self.s.options)); - } catch(err) { - return handleCallback(callback, toError(err), null); - } - }); -} - -define.classMethod('rename', {callback: true, promise:true}); - -/** - * Drop the collection from the database, removing it permanently. New accesses will create a new collection. - * - * @method - * @param {object} [options=null] Optional settings. - * @param {Collection~resultCallback} [callback] The results callback - * @return {Promise} returns Promise if no callback passed - */ -Collection.prototype.drop = function(options, callback) { - var self = this; - if(typeof options == 'function') callback = options, options = {}; - options = options || {}; - - // Execute using callback - if(typeof callback == 'function') return self.s.db.dropCollection(self.s.name, options, callback); - // Return a Promise - return new this.s.promiseLibrary(function(resolve, reject) { - self.s.db.dropCollection(self.s.name, options, function(err, r) { - if(err) return reject(err); - resolve(r); - }); - }); -} - -define.classMethod('drop', {callback: true, promise:true}); - -/** - * Returns the options of the collection. - * - * @method - * @param {Collection~resultCallback} [callback] The results callback - * @return {Promise} returns Promise if no callback passed - */ -Collection.prototype.options = function(callback) { - var self = this; - - // Execute using callback - if(typeof callback == 'function') return options(self, callback); - - // Return a Promise - return new this.s.promiseLibrary(function(resolve, reject) { - options(self, function(err, r) { - if(err) return reject(err); - resolve(r); - }); - }); -} - -var options = function(self, callback) { - self.s.db.listCollections({name: self.s.name}).toArray(function(err, collections) { - if(err) return handleCallback(callback, err); - if(collections.length == 0) { - return handleCallback(callback, MongoError.create({message: f("collection %s not found", self.s.namespace), driver:true })); - } - - handleCallback(callback, err, collections[0].options || null); - }); -} - -define.classMethod('options', {callback: true, promise:true}); - -/** - * Returns if the collection is a capped collection - * - * @method - * @param {Collection~resultCallback} [callback] The results callback - * @return {Promise} returns Promise if no callback passed - */ -Collection.prototype.isCapped = function(callback) { - var self = this; - - // Execute using callback - if(typeof callback == 'function') return isCapped(self, callback); - - // Return a Promise - return new this.s.promiseLibrary(function(resolve, reject) { - isCapped(self, function(err, r) { - if(err) return reject(err); - resolve(r); - }); - }); -} - -var isCapped = function(self, callback) { - self.options(function(err, document) { - if(err) return handleCallback(callback, err); - handleCallback(callback, null, document && document.capped); - }); -} - -define.classMethod('isCapped', {callback: true, promise:true}); - -/** - * Creates an index on the db and collection collection. - * @method - * @param {(string|object)} fieldOrSpec Defines the index. - * @param {object} [options=null] Optional settings. - * @param {(number|string)} [options.w=null] The write concern. - * @param {number} [options.wtimeout=null] The write concern timeout. - * @param {boolean} [options.j=false] Specify a journal write concern. - * @param {boolean} [options.unique=false] Creates an unique index. - * @param {boolean} [options.sparse=false] Creates a sparse index. - * @param {boolean} [options.background=false] Creates the index in the background, yielding whenever possible. - * @param {boolean} [options.dropDups=false] A unique index cannot be created on a key that has pre-existing duplicate values. If you would like to create the index anyway, keeping the first document the database indexes and deleting all subsequent documents that have duplicate value - * @param {number} [options.min=null] For geospatial indexes set the lower bound for the co-ordinates. - * @param {number} [options.max=null] For geospatial indexes set the high bound for the co-ordinates. - * @param {number} [options.v=null] Specify the format version of the indexes. - * @param {number} [options.expireAfterSeconds=null] Allows you to expire data on indexes applied to a data (MongoDB 2.2 or higher) - * @param {string} [options.name=null] Override the autogenerated index name (useful if the resulting name is larger than 128 bytes) - * @param {object} [options.partialFilterExpression=null] Creates a partial index based on the given filter object (MongoDB 3.2 or higher) - * @param {object} [options.collation=null] Specify collation (MongoDB 3.4 or higher) settings for update operation (see 3.4 documentation for available fields). - * @param {Collection~resultCallback} [callback] The command result callback - * @return {Promise} returns Promise if no callback passed - */ -Collection.prototype.createIndex = function(fieldOrSpec, options, callback) { - var self = this; - var args = Array.prototype.slice.call(arguments, 1); - callback = args.pop(); - if(typeof callback != 'function') args.push(callback); - options = args.length ? args.shift() || {} : {}; - options = typeof callback === 'function' ? options : callback; - options = options == null ? {} : options; - - // Execute using callback - if(typeof callback == 'function') return createIndex(self, fieldOrSpec, options, callback); - - // Return a Promise - return new this.s.promiseLibrary(function(resolve, reject) { - createIndex(self, fieldOrSpec, options, function(err, r) { - if(err) return reject(err); - resolve(r); - }); - }); -} - -var createIndex = function(self, fieldOrSpec, options, callback) { - self.s.db.createIndex(self.s.name, fieldOrSpec, options, callback); -} - -define.classMethod('createIndex', {callback: true, promise:true}); - -/** - * Creates multiple indexes in the collection, this method is only supported for - * MongoDB 2.6 or higher. Earlier version of MongoDB will throw a command not supported - * error. Index specifications are defined at http://docs.mongodb.org/manual/reference/command/createIndexes/. - * @method - * @param {array} indexSpecs An array of index specifications to be created - * @param {Collection~resultCallback} [callback] The command result callback - * @return {Promise} returns Promise if no callback passed - */ -Collection.prototype.createIndexes = function(indexSpecs, callback) { - var self = this; - - // Execute using callback - if(typeof callback == 'function') return createIndexes(self, indexSpecs, callback); - - // Return a Promise - return new this.s.promiseLibrary(function(resolve, reject) { - createIndexes(self, indexSpecs, function(err, r) { - if(err) return reject(err); - resolve(r); - }); - }); -} - -var createIndexes = function(self, indexSpecs, callback) { - var capabilities = self.s.topology.capabilities(); - - // Ensure we generate the correct name if the parameter is not set - for(var i = 0; i < indexSpecs.length; i++) { - if(indexSpecs[i].name == null) { - var keys = []; - - // Did the user pass in a collation, check if our write server supports it - if(indexSpecs[i].collation && capabilities && !capabilities.commandsTakeCollation) { - return callback(new MongoError(f('server/primary/mongos does not support collation'))); - } - - for(var name in indexSpecs[i].key) { - keys.push(f('%s_%s', name, indexSpecs[i].key[name])); - } - - // Set the name - indexSpecs[i].name = keys.join('_'); - } - } - - // Execute the index - self.s.db.command({ - createIndexes: self.s.name, indexes: indexSpecs - }, { readPreference: ReadPreference.PRIMARY }, callback); -} - -define.classMethod('createIndexes', {callback: true, promise:true}); - -/** - * Drops an index from this collection. - * @method - * @param {string} indexName Name of the index to drop. - * @param {object} [options=null] Optional settings. - * @param {(number|string)} [options.w=null] The write concern. - * @param {number} [options.wtimeout=null] The write concern timeout. - * @param {boolean} [options.j=false] Specify a journal write concern. - * @param {Collection~resultCallback} [callback] The command result callback - * @return {Promise} returns Promise if no callback passed - */ -Collection.prototype.dropIndex = function(indexName, options, callback) { - var self = this; - var args = Array.prototype.slice.call(arguments, 1); - callback = args.pop(); - if(typeof callback != 'function') args.push(callback); - options = args.length ? args.shift() || {} : {}; - // Run only against primary - options.readPreference = ReadPreference.PRIMARY; - - // Execute using callback - if(typeof callback == 'function') return dropIndex(self, indexName, options, callback); - - // Return a Promise - return new this.s.promiseLibrary(function(resolve, reject) { - dropIndex(self, indexName, options, function(err, r) { - if(err) return reject(err); - resolve(r); - }); - }); -} - -var dropIndex = function(self, indexName, options, callback) { - // Delete index command - var cmd = {'dropIndexes':self.s.name, 'index':indexName}; - - // Decorate command with writeConcern if supported - decorateWithWriteConcern(cmd, self, options); - - // Execute command - self.s.db.command(cmd, options, function(err, result) { - if(typeof callback != 'function') return; - if(err) return handleCallback(callback, err, null); - handleCallback(callback, null, result); - }); -} - -define.classMethod('dropIndex', {callback: true, promise:true}); - -/** - * Drops all indexes from this collection. - * @method - * @param {Collection~resultCallback} [callback] The command result callback - * @return {Promise} returns Promise if no callback passed - */ -Collection.prototype.dropIndexes = function(options, callback) { - var self = this; - - // Do we have options - if(typeof options == 'function') callback = options, options = {}; - options = options || {}; - - // Execute using callback - if(typeof callback == 'function') return dropIndexes(self, options, callback); - - // Return a Promise - return new this.s.promiseLibrary(function(resolve, reject) { - dropIndexes(self, function(err, r) { - if(err) return reject(err); - resolve(r); - }); - }); -} - -var dropIndexes = function(self, options, callback) { - self.dropIndex('*', options, function(err) { - if(err) return handleCallback(callback, err, false); - handleCallback(callback, null, true); - }); -} - -define.classMethod('dropIndexes', {callback: true, promise:true}); - -/** - * Drops all indexes from this collection. - * @method - * @deprecated use dropIndexes - * @param {Collection~resultCallback} callback The command result callback - * @return {Promise} returns Promise if no [callback] passed - */ -Collection.prototype.dropAllIndexes = Collection.prototype.dropIndexes; - -define.classMethod('dropAllIndexes', {callback: true, promise:true}); - -/** - * Reindex all indexes on the collection - * Warning: reIndex is a blocking operation (indexes are rebuilt in the foreground) and will be slow for large collections. - * @method - * @param {Collection~resultCallback} [callback] The command result callback - * @return {Promise} returns Promise if no callback passed - */ -Collection.prototype.reIndex = function(options, callback) { - var self = this; - if(typeof options == 'function') callback = options, options = {}; - options = options || {}; - - // Execute using callback - if(typeof callback == 'function') return reIndex(self, options, callback); - - // Return a Promise - return new this.s.promiseLibrary(function(resolve, reject) { - reIndex(self, options, function(err, r) { - if(err) return reject(err); - resolve(r); - }); - }); -} - -var reIndex = function(self, options, callback) { - // Reindex - var cmd = {'reIndex':self.s.name}; - - // Execute the command - self.s.db.command(cmd, options, function(err, result) { - if(callback == null) return; - if(err) return handleCallback(callback, err, null); - handleCallback(callback, null, result.ok ? true : false); - }); -} - -define.classMethod('reIndex', {callback: true, promise:true}); - -/** - * Get the list of all indexes information for the collection. - * - * @method - * @param {object} [options=null] Optional settings. - * @param {number} [options.batchSize=null] The batchSize for the returned command cursor or if pre 2.8 the systems batch collection - * @param {(ReadPreference|string)} [options.readPreference=null] The preferred read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST). - * @return {CommandCursor} - */ -Collection.prototype.listIndexes = function(options) { - options = options || {}; - // Clone the options - options = shallowClone(options); - // Determine the read preference in the options. - options = getReadPreference(this, options, this.s.db, this); - // Set the CommandCursor constructor - options.cursorFactory = CommandCursor; - // Set the promiseLibrary - options.promiseLibrary = this.s.promiseLibrary; - - if(!this.s.topology.capabilities()) { - throw new MongoError('cannot connect to server'); - } - - // We have a list collections command - if(this.s.topology.capabilities().hasListIndexesCommand) { - // Cursor options - var cursor = options.batchSize ? {batchSize: options.batchSize} : {} - // Build the command - var command = { listIndexes: this.s.name, cursor: cursor }; - // Execute the cursor - cursor = this.s.topology.cursor(f('%s.$cmd', this.s.dbName), command, options); - // Do we have a readPreference, apply it - if(options.readPreference) cursor.setReadPreference(options.readPreference); - // Return the cursor - return cursor; - } - - // Get the namespace - var ns = f('%s.system.indexes', this.s.dbName); - // Get the query - cursor = this.s.topology.cursor(ns, {find: ns, query: {ns: this.s.namespace}}, options); - // Do we have a readPreference, apply it - if(options.readPreference) cursor.setReadPreference(options.readPreference); - // Set the passed in batch size if one was provided - if(options.batchSize) cursor = cursor.batchSize(options.batchSize); - // Return the cursor - return cursor; -}; - -define.classMethod('listIndexes', {callback: false, promise:false, returns: [CommandCursor]}); - -/** - * Ensures that an index exists, if it does not it creates it - * @method - * @deprecated use createIndexes instead - * @param {(string|object)} fieldOrSpec Defines the index. - * @param {object} [options=null] Optional settings. - * @param {(number|string)} [options.w=null] The write concern. - * @param {number} [options.wtimeout=null] The write concern timeout. - * @param {boolean} [options.j=false] Specify a journal write concern. - * @param {boolean} [options.unique=false] Creates an unique index. - * @param {boolean} [options.sparse=false] Creates a sparse index. - * @param {boolean} [options.background=false] Creates the index in the background, yielding whenever possible. - * @param {boolean} [options.dropDups=false] A unique index cannot be created on a key that has pre-existing duplicate values. If you would like to create the index anyway, keeping the first document the database indexes and deleting all subsequent documents that have duplicate value - * @param {number} [options.min=null] For geospatial indexes set the lower bound for the co-ordinates. - * @param {number} [options.max=null] For geospatial indexes set the high bound for the co-ordinates. - * @param {number} [options.v=null] Specify the format version of the indexes. - * @param {number} [options.expireAfterSeconds=null] Allows you to expire data on indexes applied to a data (MongoDB 2.2 or higher) - * @param {number} [options.name=null] Override the autogenerated index name (useful if the resulting name is larger than 128 bytes) - * @param {object} [options.collation=null] Specify collation (MongoDB 3.4 or higher) settings for update operation (see 3.4 documentation for available fields). - * @param {Collection~resultCallback} [callback] The command result callback - * @return {Promise} returns Promise if no callback passed - */ -Collection.prototype.ensureIndex = function(fieldOrSpec, options, callback) { - var self = this; - if(typeof options == 'function') callback = options, options = {}; - options = options || {}; - - // Execute using callback - if(typeof callback == 'function') return ensureIndex(self, fieldOrSpec, options, callback); - - // Return a Promise - return new this.s.promiseLibrary(function(resolve, reject) { - ensureIndex(self, fieldOrSpec, options, function(err, r) { - if(err) return reject(err); - resolve(r); - }); - }); -} - -var ensureIndex = function(self, fieldOrSpec, options, callback) { - self.s.db.ensureIndex(self.s.name, fieldOrSpec, options, callback); -} - -define.classMethod('ensureIndex', {callback: true, promise:true}); - -/** - * Checks if one or more indexes exist on the collection, fails on first non-existing index - * @method - * @param {(string|array)} indexes One or more index names to check. - * @param {Collection~resultCallback} [callback] The command result callback - * @return {Promise} returns Promise if no callback passed - */ -Collection.prototype.indexExists = function(indexes, callback) { - var self = this; - - // Execute using callback - if(typeof callback == 'function') return indexExists(self, indexes, callback); - - // Return a Promise - return new this.s.promiseLibrary(function(resolve, reject) { - indexExists(self, indexes, function(err, r) { - if(err) return reject(err); - resolve(r); - }); - }); -} - -var indexExists = function(self, indexes, callback) { - self.indexInformation(function(err, indexInformation) { - // If we have an error return - if(err != null) return handleCallback(callback, err, null); - // Let's check for the index names - if(!Array.isArray(indexes)) return handleCallback(callback, null, indexInformation[indexes] != null); - // Check in list of indexes - for(var i = 0; i < indexes.length; i++) { - if(indexInformation[indexes[i]] == null) { - return handleCallback(callback, null, false); - } - } - - // All keys found return true - return handleCallback(callback, null, true); - }); -} - -define.classMethod('indexExists', {callback: true, promise:true}); - -/** - * Retrieves this collections index info. - * @method - * @param {object} [options=null] Optional settings. - * @param {boolean} [options.full=false] Returns the full raw index information. - * @param {Collection~resultCallback} [callback] The command result callback - * @return {Promise} returns Promise if no callback passed - */ -Collection.prototype.indexInformation = function(options, callback) { - var self = this; - // Unpack calls - var args = Array.prototype.slice.call(arguments, 0); - callback = args.pop(); - if(typeof callback != 'function') args.push(callback); - options = args.length ? args.shift() || {} : {}; - - // Execute using callback - if(typeof callback == 'function') return indexInformation(self, options, callback); - - // Return a Promise - return new this.s.promiseLibrary(function(resolve, reject) { - indexInformation(self, options, function(err, r) { - if(err) return reject(err); - resolve(r); - }); - }); -} - -var indexInformation = function(self, options, callback) { - self.s.db.indexInformation(self.s.name, options, callback); -} - -define.classMethod('indexInformation', {callback: true, promise:true}); - -/** - * The callback format for results - * @callback Collection~countCallback - * @param {MongoError} error An error instance representing the error during the execution. - * @param {number} result The count of documents that matched the query. - */ - -/** - * Count number of matching documents in the db to a query. - * @method - * @param {object} query The query for the count. - * @param {object} [options=null] Optional settings. - * @param {boolean} [options.limit=null] The limit of documents to count. - * @param {boolean} [options.skip=null] The number of documents to skip for the count. - * @param {string} [options.hint=null] An index name hint for the query. - * @param {(ReadPreference|string)} [options.readPreference=null] The preferred read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST). - * @param {number} [options.maxTimeMS=null] Number of milliseconds to wait before aborting the query. - * @param {Collection~countCallback} [callback] The command result callback - * @return {Promise} returns Promise if no callback passed - */ -Collection.prototype.count = function(query, options, callback) { - var self = this; - var args = Array.prototype.slice.call(arguments, 0); - callback = args.pop(); - if(typeof callback != 'function') args.push(callback); - var queryOption = args.length ? args.shift() || {} : {}; - var optionsOption = args.length ? args.shift() || {} : {}; - - // Execute using callback - if(typeof callback == 'function') return count(self, queryOption, optionsOption, callback); - - // Check if query is empty - query = query || {}; - options = options || {}; - - // Return a Promise - return new this.s.promiseLibrary(function(resolve, reject) { - count(self, query, options, function(err, r) { - if(err) return reject(err); - resolve(r); - }); - }); -}; - -var count = function(self, query, options, callback) { - var skip = options.skip; - var limit = options.limit; - var hint = options.hint; - var maxTimeMS = options.maxTimeMS; - - // Final query - var cmd = { - 'count': self.s.name, 'query': query - }; - - // Add limit, skip and maxTimeMS if defined - if(typeof skip == 'number') cmd.skip = skip; - if(typeof limit == 'number') cmd.limit = limit; - if(typeof maxTimeMS == 'number') cmd.maxTimeMS = maxTimeMS; - if(hint) cmd.hint = hint; - - options = shallowClone(options); - // Ensure we have the right read preference inheritance - options = getReadPreference(self, options, self.s.db, self); - - // Do we have a readConcern specified - if(self.s.readConcern) { - cmd.readConcern = self.s.readConcern; - } - - // Have we specified collation - decorateWithCollation(cmd, self, options); - - // Execute command - self.s.db.command(cmd, options, function(err, result) { - if(err) return handleCallback(callback, err); - handleCallback(callback, null, result.n); - }); -} - -define.classMethod('count', {callback: true, promise:true}); - -/** - * The distinct command returns returns a list of distinct values for the given key across a collection. - * @method - * @param {string} key Field of the document to find distinct values for. - * @param {object} query The query for filtering the set of documents to which we apply the distinct filter. - * @param {object} [options=null] Optional settings. - * @param {(ReadPreference|string)} [options.readPreference=null] The preferred read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST). - * @param {number} [options.maxTimeMS=null] Number of milliseconds to wait before aborting the query. - * @param {Collection~resultCallback} [callback] The command result callback - * @return {Promise} returns Promise if no callback passed - */ -Collection.prototype.distinct = function(key, query, options, callback) { - var self = this; - var args = Array.prototype.slice.call(arguments, 1); - callback = args.pop(); - if(typeof callback != 'function') args.push(callback); - var queryOption = args.length ? args.shift() || {} : {}; - var optionsOption = args.length ? args.shift() || {} : {}; - - // Execute using callback - if(typeof callback == 'function') return distinct(self, key, queryOption, optionsOption, callback); - - // Ensure the query and options are set - query = query || {}; - options = options || {}; - - // Return a Promise - return new this.s.promiseLibrary(function(resolve, reject) { - distinct(self, key, query, options, function(err, r) { - if(err) return reject(err); - resolve(r); - }); - }); -}; - -var distinct = function(self, key, query, options, callback) { - // maxTimeMS option - var maxTimeMS = options.maxTimeMS; - - // Distinct command - var cmd = { - 'distinct': self.s.name, 'key': key, 'query': query - }; - - options = shallowClone(options); - // Ensure we have the right read preference inheritance - options = getReadPreference(self, options, self.s.db, self); - - // Add maxTimeMS if defined - if(typeof maxTimeMS == 'number') - cmd.maxTimeMS = maxTimeMS; - - // Do we have a readConcern specified - if(self.s.readConcern) { - cmd.readConcern = self.s.readConcern; - } - - // Have we specified collation - decorateWithCollation(cmd, self, options); - - // Execute the command - self.s.db.command(cmd, options, function(err, result) { - if(err) return handleCallback(callback, err); - handleCallback(callback, null, result.values); - }); -} - -define.classMethod('distinct', {callback: true, promise:true}); - -/** - * Retrieve all the indexes on the collection. - * @method - * @param {Collection~resultCallback} [callback] The command result callback - * @return {Promise} returns Promise if no callback passed - */ -Collection.prototype.indexes = function(callback) { - var self = this; - // Execute using callback - if(typeof callback == 'function') return indexes(self, callback); - - // Return a Promise - return new this.s.promiseLibrary(function(resolve, reject) { - indexes(self, function(err, r) { - if(err) return reject(err); - resolve(r); - }); - }); -} - -var indexes = function(self, callback) { - self.s.db.indexInformation(self.s.name, {full:true}, callback); -} - -define.classMethod('indexes', {callback: true, promise:true}); - -/** - * Get all the collection statistics. - * - * @method - * @param {object} [options=null] Optional settings. - * @param {number} [options.scale=null] Divide the returned sizes by scale value. - * @param {Collection~resultCallback} [callback] The collection result callback - * @return {Promise} returns Promise if no callback passed - */ -Collection.prototype.stats = function(options, callback) { - var self = this; - var args = Array.prototype.slice.call(arguments, 0); - callback = args.pop(); - if(typeof callback != 'function') args.push(callback); - // Fetch all commands - options = args.length ? args.shift() || {} : {}; - - // Execute using callback - if(typeof callback == 'function') return stats(self, options, callback); - - // Return a Promise - return new this.s.promiseLibrary(function(resolve, reject) { - stats(self, options, function(err, r) { - if(err) return reject(err); - resolve(r); - }); - }); -} - -var stats = function(self, options, callback) { - // Build command object - var commandObject = { - collStats:self.s.name - } - - // Check if we have the scale value - if(options['scale'] != null) commandObject['scale'] = options['scale']; - - options = shallowClone(options); - // Ensure we have the right read preference inheritance - options = getReadPreference(self, options, self.s.db, self); - - // Execute the command - self.s.db.command(commandObject, options, callback); -} - -define.classMethod('stats', {callback: true, promise:true}); - -/** - * @typedef {Object} Collection~findAndModifyWriteOpResult - * @property {object} value Document returned from findAndModify command. - * @property {object} lastErrorObject The raw lastErrorObject returned from the command. - * @property {Number} ok Is 1 if the command executed correctly. - */ - -/** - * The callback format for inserts - * @callback Collection~findAndModifyCallback - * @param {MongoError} error An error instance representing the error during the execution. - * @param {Collection~findAndModifyWriteOpResult} result The result object if the command was executed successfully. - */ - -/** - * Find a document and delete it in one atomic operation, requires a write lock for the duration of the operation. - * - * @method - * @param {object} filter Document selection filter. - * @param {object} [options=null] Optional settings. - * @param {object} [options.projection=null] Limits the fields to return for all matching documents. - * @param {object} [options.sort=null] Determines which document the operation modifies if the query selects multiple documents. - * @param {number} [options.maxTimeMS=null] The maximum amount of time to allow the query to run. - * @param {Collection~findAndModifyCallback} [callback] The collection result callback - * @return {Promise} returns Promise if no callback passed - */ -Collection.prototype.findOneAndDelete = function(filter, options, callback) { - var self = this; - if(typeof options == 'function') callback = options, options = {}; - options = options || {}; - - // Basic validation - if(filter == null || typeof filter != 'object') throw toError('filter parameter must be an object'); - - // Execute using callback - if(typeof callback == 'function') return findOneAndDelete(self, filter, options, callback); - - // Return a Promise - return new this.s.promiseLibrary(function(resolve, reject) { - options = options || {}; - - findOneAndDelete(self, filter, options, function(err, r) { - if(err) return reject(err); - resolve(r); - }); - }); -} - -var findOneAndDelete = function(self, filter, options, callback) { - // Final options - var finalOptions = shallowClone(options); - finalOptions['fields'] = options.projection; - finalOptions['remove'] = true; - // Execute find and Modify - self.findAndModify( - filter - , options.sort - , null - , finalOptions - , callback - ); -} - -define.classMethod('findOneAndDelete', {callback: true, promise:true}); - -/** - * Find a document and replace it in one atomic operation, requires a write lock for the duration of the operation. - * - * @method - * @param {object} filter Document selection filter. - * @param {object} replacement Document replacing the matching document. - * @param {object} [options=null] Optional settings. - * @param {object} [options.projection=null] Limits the fields to return for all matching documents. - * @param {object} [options.sort=null] Determines which document the operation modifies if the query selects multiple documents. - * @param {number} [options.maxTimeMS=null] The maximum amount of time to allow the query to run. - * @param {boolean} [options.upsert=false] Upsert the document if it does not exist. - * @param {boolean} [options.returnOriginal=true] When false, returns the updated document rather than the original. The default is true. - * @param {Collection~findAndModifyCallback} [callback] The collection result callback - * @return {Promise} returns Promise if no callback passed - */ -Collection.prototype.findOneAndReplace = function(filter, replacement, options, callback) { - var self = this; - if(typeof options == 'function') callback = options, options = {}; - options = options || {}; - - // Basic validation - if(filter == null || typeof filter != 'object') throw toError('filter parameter must be an object'); - if(replacement == null || typeof replacement != 'object') throw toError('replacement parameter must be an object'); - - // Execute using callback - if(typeof callback == 'function') return findOneAndReplace(self, filter, replacement, options, callback); - - // Return a Promise - return new this.s.promiseLibrary(function(resolve, reject) { - options = options || {}; - - findOneAndReplace(self, filter, replacement, options, function(err, r) { - if(err) return reject(err); - resolve(r); - }); - }); -} - -var findOneAndReplace = function(self, filter, replacement, options, callback) { - // Final options - var finalOptions = shallowClone(options); - finalOptions['fields'] = options.projection; - finalOptions['update'] = true; - finalOptions['new'] = typeof options.returnOriginal == 'boolean' ? !options.returnOriginal : false; - finalOptions['upsert'] = typeof options.upsert == 'boolean' ? options.upsert : false; - - // Execute findAndModify - self.findAndModify( - filter - , options.sort - , replacement - , finalOptions - , callback - ); -} - -define.classMethod('findOneAndReplace', {callback: true, promise:true}); - -/** - * Find a document and update it in one atomic operation, requires a write lock for the duration of the operation. - * - * @method - * @param {object} filter Document selection filter. - * @param {object} update Update operations to be performed on the document - * @param {object} [options=null] Optional settings. - * @param {object} [options.projection=null] Limits the fields to return for all matching documents. - * @param {object} [options.sort=null] Determines which document the operation modifies if the query selects multiple documents. - * @param {number} [options.maxTimeMS=null] The maximum amount of time to allow the query to run. - * @param {boolean} [options.upsert=false] Upsert the document if it does not exist. - * @param {boolean} [options.returnOriginal=true] When false, returns the updated document rather than the original. The default is true. - * @param {Collection~findAndModifyCallback} [callback] The collection result callback - * @return {Promise} returns Promise if no callback passed - */ -Collection.prototype.findOneAndUpdate = function(filter, update, options, callback) { - var self = this; - if(typeof options == 'function') callback = options, options = {}; - options = options || {}; - - // Basic validation - if(filter == null || typeof filter != 'object') throw toError('filter parameter must be an object'); - if(update == null || typeof update != 'object') throw toError('update parameter must be an object'); - - // Execute using callback - if(typeof callback == 'function') return findOneAndUpdate(self, filter, update, options, callback); - - // Return a Promise - return new this.s.promiseLibrary(function(resolve, reject) { - options = options || {}; - - findOneAndUpdate(self, filter, update, options, function(err, r) { - if(err) return reject(err); - resolve(r); - }); - }); -} - -var findOneAndUpdate = function(self, filter, update, options, callback) { - // Final options - var finalOptions = shallowClone(options); - finalOptions['fields'] = options.projection; - finalOptions['update'] = true; - finalOptions['new'] = typeof options.returnOriginal == 'boolean' ? !options.returnOriginal : false; - finalOptions['upsert'] = typeof options.upsert == 'boolean' ? options.upsert : false; - - // Execute findAndModify - self.findAndModify( - filter - , options.sort - , update - , finalOptions - , callback - ); -} - -define.classMethod('findOneAndUpdate', {callback: true, promise:true}); - -/** - * Find and update a document. - * @method - * @param {object} query Query object to locate the object to modify. - * @param {array} sort If multiple docs match, choose the first one in the specified sort order as the object to manipulate. - * @param {object} doc The fields/vals to be updated. - * @param {object} [options=null] Optional settings. - * @param {(number|string)} [options.w=null] The write concern. - * @param {number} [options.wtimeout=null] The write concern timeout. - * @param {boolean} [options.j=false] Specify a journal write concern. - * @param {boolean} [options.remove=false] Set to true to remove the object before returning. - * @param {boolean} [options.upsert=false] Perform an upsert operation. - * @param {boolean} [options.new=false] Set to true if you want to return the modified object rather than the original. Ignored for remove. - * @param {object} [options.fields=null] Object containing the field projection for the result returned from the operation. - * @param {Collection~findAndModifyCallback} [callback] The command result callback - * @return {Promise} returns Promise if no callback passed - * @deprecated use findOneAndUpdate, findOneAndReplace or findOneAndDelete instead - */ -Collection.prototype.findAndModify = function(query, sort, doc, options, callback) { - var self = this; - var args = Array.prototype.slice.call(arguments, 1); - callback = args.pop(); - if(typeof callback != 'function') args.push(callback); - sort = args.length ? args.shift() || [] : []; - doc = args.length ? args.shift() : null; - options = args.length ? args.shift() || {} : {}; - - // Clone options - options = shallowClone(options); - // Force read preference primary - options.readPreference = ReadPreference.PRIMARY; - - // Execute using callback - if(typeof callback == 'function') return findAndModify(self, query, sort, doc, options, callback); - - // Return a Promise - return new this.s.promiseLibrary(function(resolve, reject) { - options = options || {}; - - findAndModify(self, query, sort, doc, options, function(err, r) { - if(err) return reject(err); - resolve(r); - }); - }); -} - -var findAndModify = function(self, query, sort, doc, options, callback) { - // Create findAndModify command object - var queryObject = { - 'findandmodify': self.s.name - , 'query': query - }; - - sort = formattedOrderClause(sort); - if(sort) { - queryObject.sort = sort; - } - - queryObject.new = options.new ? true : false; - queryObject.remove = options.remove ? true : false; - queryObject.upsert = options.upsert ? true : false; - - if(options.fields) { - queryObject.fields = options.fields; - } - - if(doc && !options.remove) { - queryObject.update = doc; - } - - if(options.maxTimeMS) - queryObject.maxTimeMS = options.maxTimeMS; - - // Either use override on the function, or go back to default on either the collection - // level or db - if(options['serializeFunctions'] != null) { - options['serializeFunctions'] = options['serializeFunctions']; - } else { - options['serializeFunctions'] = self.s.serializeFunctions; - } - - // No check on the documents - options.checkKeys = false; - - // Get the write concern settings - var finalOptions = writeConcern(options, self.s.db, self, options); - - // Decorate the findAndModify command with the write Concern - if(finalOptions.writeConcern) { - queryObject.writeConcern = finalOptions.writeConcern; - } - - // Have we specified bypassDocumentValidation - if(typeof finalOptions.bypassDocumentValidation == 'boolean') { - queryObject.bypassDocumentValidation = finalOptions.bypassDocumentValidation; - } - - // Have we specified collation - decorateWithCollation(queryObject, self, options); - - // Execute the command - self.s.db.command(queryObject - , options, function(err, result) { - if(err) return handleCallback(callback, err, null); - return handleCallback(callback, null, result); - }); -} - -define.classMethod('findAndModify', {callback: true, promise:true}); - -/** - * Find and remove a document. - * @method - * @param {object} query Query object to locate the object to modify. - * @param {array} sort If multiple docs match, choose the first one in the specified sort order as the object to manipulate. - * @param {object} [options=null] Optional settings. - * @param {(number|string)} [options.w=null] The write concern. - * @param {number} [options.wtimeout=null] The write concern timeout. - * @param {boolean} [options.j=false] Specify a journal write concern. - * @param {Collection~resultCallback} [callback] The command result callback - * @return {Promise} returns Promise if no callback passed - * @deprecated use findOneAndDelete instead - */ -Collection.prototype.findAndRemove = function(query, sort, options, callback) { - var self = this; - var args = Array.prototype.slice.call(arguments, 1); - callback = args.pop(); - if(typeof callback != 'function') args.push(callback); - sort = args.length ? args.shift() || [] : []; - options = args.length ? args.shift() || {} : {}; - - // Execute using callback - if(typeof callback == 'function') return findAndRemove(self, query, sort, options, callback); - - // Return a Promise - return new this.s.promiseLibrary(function(resolve, reject) { - findAndRemove(self, query, sort, options, function(err, r) { - if(err) return reject(err); - resolve(r); - }); - }); -} - -var findAndRemove = function(self, query, sort, options, callback) { - // Add the remove option - options['remove'] = true; - // Execute the callback - self.findAndModify(query, sort, null, options, callback); -} - -define.classMethod('findAndRemove', {callback: true, promise:true}); - -function decorateWithWriteConcern(command, self, options) { - // Do we support collation 3.4 and higher - var capabilities = self.s.topology.capabilities(); - // Do we support write concerns 3.4 and higher - if(capabilities && capabilities.commandsTakeWriteConcern) { - // Get the write concern settings - var finalOptions = writeConcern(shallowClone(options), self.s.db, self, options); - // Add the write concern to the command - if(finalOptions.writeConcern) { - command.writeConcern = finalOptions.writeConcern; - } - } -} - -function decorateWithCollation(command, self, options) { - // Do we support collation 3.4 and higher - var capabilities = self.s.topology.capabilities(); - // Do we support write concerns 3.4 and higher - if(capabilities && capabilities.commandsTakeCollation) { - if(options.collation && typeof options.collation == 'object') { - command.collation = options.collation; - } - } -} - -/** - * Execute an aggregation framework pipeline against the collection, needs MongoDB >= 2.2 - * @method - * @param {object} pipeline Array containing all the aggregation framework commands for the execution. - * @param {object} [options=null] Optional settings. - * @param {(ReadPreference|string)} [options.readPreference=null] The preferred read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST). - * @param {object} [options.cursor=null] Return the query as cursor, on 2.6 > it returns as a real cursor on pre 2.6 it returns as an emulated cursor. - * @param {number} [options.cursor.batchSize=null] The batchSize for the cursor - * @param {boolean} [options.explain=false] Explain returns the aggregation execution plan (requires mongodb 2.6 >). - * @param {boolean} [options.allowDiskUse=false] allowDiskUse lets the server know if it can use disk to store temporary results for the aggregation (requires mongodb 2.6 >). - * @param {number} [options.maxTimeMS=null] maxTimeMS specifies a cumulative time limit in milliseconds for processing operations on the cursor. MongoDB interrupts the operation at the earliest following interrupt point. - * @param {boolean} [options.bypassDocumentValidation=false] Allow driver to bypass schema validation in MongoDB 3.2 or higher. - * @param {boolean} [options.raw=false] Return document results as raw BSON buffers. - * @param {boolean} [options.promoteLongs=true] Promotes Long values to number if they fit inside the 53 bits resolution. - * @param {boolean} [options.promoteValues=true] Promotes BSON values to native types where possible, set to false to only receive wrapper types. - * @param {boolean} [options.promoteBuffers=false] Promotes Binary BSON values to native Node Buffers. - * @param {object} [options.collation=null] Specify collation (MongoDB 3.4 or higher) settings for update operation (see 3.4 documentation for available fields). - * @param {Collection~resultCallback} callback The command result callback - * @return {(null|AggregationCursor)} - */ -Collection.prototype.aggregate = function(pipeline, options, callback) { - var self = this; - - if(Array.isArray(pipeline)) { - // Set up callback if one is provided - if(typeof options == 'function') { - callback = options; - options = {}; - } - - // If we have no options or callback we are doing - // a cursor based aggregation - if(options == null && callback == null) { - options = {}; - } - } else { - // Aggregation pipeline passed as arguments on the method - var args = Array.prototype.slice.call(arguments, 0); - // Get the callback - callback = args.pop(); - // Get the possible options object - var opts = args[args.length - 1]; - // If it contains any of the admissible options pop it of the args - options = opts && (opts.readPreference - || opts.explain || opts.cursor || opts.out - || opts.maxTimeMS || opts.allowDiskUse) ? args.pop() : {}; - // Left over arguments is the pipeline - pipeline = args; - } - - // Ignore readConcern option - var ignoreReadConcern = false; - - // Build the command - var command = { aggregate : this.s.name, pipeline : pipeline}; - - // If out was specified - if(typeof options.out == 'string') { - pipeline.push({$out: options.out}); - // Ignore read concern - ignoreReadConcern = true; - } else if(pipeline.length > 0 && pipeline[pipeline.length - 1]['$out']) { - ignoreReadConcern = true; - } - - // Decorate command with writeConcern if out has been specified - if(pipeline.length > 0 && pipeline[pipeline.length - 1]['$out']) { - decorateWithWriteConcern(command, self, options); - } - - // Have we specified collation - decorateWithCollation(command, self, options); - - // If we have bypassDocumentValidation set - if(typeof options.bypassDocumentValidation == 'boolean') { - command.bypassDocumentValidation = options.bypassDocumentValidation; - } - - // Do we have a readConcern specified - if(!ignoreReadConcern && this.s.readConcern) { - command.readConcern = this.s.readConcern; - } - - // If we have allowDiskUse defined - if(options.allowDiskUse) command.allowDiskUse = options.allowDiskUse; - if(typeof options.maxTimeMS == 'number') command.maxTimeMS = options.maxTimeMS; - - options = shallowClone(options); - // Ensure we have the right read preference inheritance - options = getReadPreference(this, options, this.s.db, this); - - // If explain has been specified add it - if (options.explain) command.explain = options.explain; - - // Validate that cursor options is valid - if(options.cursor != null && typeof options.cursor != 'object') { - throw toError('cursor options must be an object'); - } - - if (this.s.topology.capabilities().hasAggregationCursor) { - options.cursor = options.cursor || { batchSize : 1000 }; - command.cursor = options.cursor; - } - - // promiseLibrary - options.promiseLibrary = this.s.promiseLibrary; - - // Set the AggregationCursor constructor - options.cursorFactory = AggregationCursor; - if(typeof callback != 'function') { - if(!this.s.topology.capabilities()) { - throw new MongoError('cannot connect to server'); - } - - // Allow disk usage command - if(typeof options.allowDiskUse == 'boolean') command.allowDiskUse = options.allowDiskUse; - if(typeof options.maxTimeMS == 'number') command.maxTimeMS = options.maxTimeMS; - - // Execute the cursor - return this.s.topology.cursor(this.s.namespace, command, options); - } - - if (options.cursor) { - var cursor = this.s.topology.cursor(this.s.namespace, command, options); - return cursor.toArray(function(err, result) { - if (err) { - return handleCallback(callback, err); - } - - handleCallback(callback, null, result); - }); - } - - // For legacy server versions, we execute the command and format the result - this.s.db.command(command, options, function(err, result) { - if(err) { - handleCallback(callback, err); - } else if(result['err'] || result['errmsg']) { - handleCallback(callback, toError(result)); - } else if(typeof result == 'object' && result['serverPipeline']) { - handleCallback(callback, null, result['serverPipeline']); - } else if(typeof result == 'object' && result['stages']) { - handleCallback(callback, null, result['stages']); - } else { - handleCallback(callback, null, result.result); - } - }); -} - -define.classMethod('aggregate', {callback: true, promise:false}); - -/** - * The callback format for results - * @callback Collection~parallelCollectionScanCallback - * @param {MongoError} error An error instance representing the error during the execution. - * @param {Cursor[]} cursors A list of cursors returned allowing for parallel reading of collection. - */ - -/** - * Return N number of parallel cursors for a collection allowing parallel reading of entire collection. There are - * no ordering guarantees for returned results. - * @method - * @param {object} [options=null] Optional settings. - * @param {(ReadPreference|string)} [options.readPreference=null] The preferred read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST). - * @param {number} [options.batchSize=null] Set the batchSize for the getMoreCommand when iterating over the query results. - * @param {number} [options.numCursors=1] The maximum number of parallel command cursors to return (the number of returned cursors will be in the range 1:numCursors) - * @param {boolean} [options.raw=false] Return all BSON documents as Raw Buffer documents. - * @param {Collection~parallelCollectionScanCallback} [callback] The command result callback - * @return {Promise} returns Promise if no callback passed - */ -Collection.prototype.parallelCollectionScan = function(options, callback) { - var self = this; - if(typeof options == 'function') callback = options, options = {numCursors: 1}; - // Set number of cursors to 1 - options.numCursors = options.numCursors || 1; - options.batchSize = options.batchSize || 1000; - - options = shallowClone(options); - // Ensure we have the right read preference inheritance - options = getReadPreference(this, options, this.s.db, this); - - // Add a promiseLibrary - options.promiseLibrary = this.s.promiseLibrary; - - // Execute using callback - if(typeof callback == 'function') return parallelCollectionScan(self, options, callback); - - // Return a Promise - return new this.s.promiseLibrary(function(resolve, reject) { - parallelCollectionScan(self, options, function(err, r) { - if(err) return reject(err); - resolve(r); - }); - }); -} - -var parallelCollectionScan = function(self, options, callback) { - // Create command object - var commandObject = { - parallelCollectionScan: self.s.name - , numCursors: options.numCursors - } - - // Do we have a readConcern specified - if(self.s.readConcern) { - commandObject.readConcern = self.s.readConcern; - } - - // Store the raw value - var raw = options.raw; - delete options['raw']; - - // Execute the command - self.s.db.command(commandObject, options, function(err, result) { - if(err) return handleCallback(callback, err, null); - if(result == null) return handleCallback(callback, new Error("no result returned for parallelCollectionScan"), null); - - var cursors = []; - // Add the raw back to the option - if(raw) options.raw = raw; - // Create command cursors for each item - for(var i = 0; i < result.cursors.length; i++) { - var rawId = result.cursors[i].cursor.id - // Convert cursorId to Long if needed - var cursorId = typeof rawId == 'number' ? Long.fromNumber(rawId) : rawId; - // Add a command cursor - cursors.push(self.s.topology.cursor(self.s.namespace, cursorId, options)); - } - - handleCallback(callback, null, cursors); - }); -} - -define.classMethod('parallelCollectionScan', {callback: true, promise:true}); - -/** - * Execute the geoNear command to search for items in the collection - * - * @method - * @param {number} x Point to search on the x axis, ensure the indexes are ordered in the same order. - * @param {number} y Point to search on the y axis, ensure the indexes are ordered in the same order. - * @param {object} [options=null] Optional settings. - * @param {(ReadPreference|string)} [options.readPreference=null] The preferred read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST). - * @param {number} [options.num=null] Max number of results to return. - * @param {number} [options.minDistance=null] Include results starting at minDistance from a point (2.6 or higher) - * @param {number} [options.maxDistance=null] Include results up to maxDistance from the point. - * @param {number} [options.distanceMultiplier=null] Include a value to multiply the distances with allowing for range conversions. - * @param {object} [options.query=null] Filter the results by a query. - * @param {boolean} [options.spherical=false] Perform query using a spherical model. - * @param {boolean} [options.uniqueDocs=false] The closest location in a document to the center of the search region will always be returned MongoDB > 2.X. - * @param {boolean} [options.includeLocs=false] Include the location data fields in the top level of the results MongoDB > 2.X. - * @param {Collection~resultCallback} [callback] The command result callback - * @return {Promise} returns Promise if no callback passed - */ -Collection.prototype.geoNear = function(x, y, options, callback) { - var self = this; - var point = typeof(x) == 'object' && x - , args = Array.prototype.slice.call(arguments, point?1:2); - - callback = args.pop(); - if(typeof callback != 'function') args.push(callback); - // Fetch all commands - options = args.length ? args.shift() || {} : {}; - - // Execute using callback - if(typeof callback == 'function') return geoNear(self, x, y, point, options, callback); - - // Return a Promise - return new this.s.promiseLibrary(function(resolve, reject) { - geoNear(self, x, y, point, options, function(err, r) { - if(err) return reject(err); - resolve(r); - }); - }); -} - -var geoNear = function(self, x, y, point, options, callback) { - // Build command object - var commandObject = { - geoNear:self.s.name, - near: point || [x, y] - } - - options = shallowClone(options); - // Ensure we have the right read preference inheritance - options = getReadPreference(self, options, self.s.db, self); - - // Exclude readPreference and existing options to prevent user from - // shooting themselves in the foot - var exclude = { - readPreference: true, - geoNear: true, - near: true - }; - - // Filter out any excluded objects - commandObject = decorateCommand(commandObject, options, exclude); - - // Do we have a readConcern specified - if(self.s.readConcern) { - commandObject.readConcern = self.s.readConcern; - } - - // Have we specified collation - decorateWithCollation(commandObject, self, options); - - // Execute the command - self.s.db.command(commandObject, options, function (err, res) { - if(err) return handleCallback(callback, err); - if(res.err || res.errmsg) return handleCallback(callback, toError(res)); - // should we only be returning res.results here? Not sure if the user - // should see the other return information - handleCallback(callback, null, res); - }); -} - -define.classMethod('geoNear', {callback: true, promise:true}); - -/** - * Execute a geo search using a geo haystack index on a collection. - * - * @method - * @param {number} x Point to search on the x axis, ensure the indexes are ordered in the same order. - * @param {number} y Point to search on the y axis, ensure the indexes are ordered in the same order. - * @param {object} [options=null] Optional settings. - * @param {(ReadPreference|string)} [options.readPreference=null] The preferred read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST). - * @param {number} [options.maxDistance=null] Include results up to maxDistance from the point. - * @param {object} [options.search=null] Filter the results by a query. - * @param {number} [options.limit=false] Max number of results to return. - * @param {Collection~resultCallback} [callback] The command result callback - * @return {Promise} returns Promise if no callback passed - */ -Collection.prototype.geoHaystackSearch = function(x, y, options, callback) { - var self = this; - var args = Array.prototype.slice.call(arguments, 2); - callback = args.pop(); - if(typeof callback != 'function') args.push(callback); - // Fetch all commands - options = args.length ? args.shift() || {} : {}; - - // Execute using callback - if(typeof callback == 'function') return geoHaystackSearch(self, x, y, options, callback); - - // Return a Promise - return new this.s.promiseLibrary(function(resolve, reject) { - geoHaystackSearch(self, x, y, options, function(err, r) { - if(err) return reject(err); - resolve(r); - }); - }); -} - -var geoHaystackSearch = function(self, x, y, options, callback) { - // Build command object - var commandObject = { - geoSearch: self.s.name, - near: [x, y] - } - - // Remove read preference from hash if it exists - commandObject = decorateCommand(commandObject, options, {readPreference: true}); - - options = shallowClone(options); - // Ensure we have the right read preference inheritance - options = getReadPreference(self, options, self.s.db, self); - - // Do we have a readConcern specified - if(self.s.readConcern) { - commandObject.readConcern = self.s.readConcern; - } - - // Execute the command - self.s.db.command(commandObject, options, function (err, res) { - if(err) return handleCallback(callback, err); - if(res.err || res.errmsg) handleCallback(callback, toError(res)); - // should we only be returning res.results here? Not sure if the user - // should see the other return information - handleCallback(callback, null, res); - }); -} - -define.classMethod('geoHaystackSearch', {callback: true, promise:true}); - -/** - * Group function helper - * @ignore - */ -// var groupFunction = function () { -// var c = db[ns].find(condition); -// var map = new Map(); -// var reduce_function = reduce; -// -// while (c.hasNext()) { -// var obj = c.next(); -// var key = {}; -// -// for (var i = 0, len = keys.length; i < len; ++i) { -// var k = keys[i]; -// key[k] = obj[k]; -// } -// -// var aggObj = map.get(key); -// -// if (aggObj == null) { -// var newObj = Object.extend({}, key); -// aggObj = Object.extend(newObj, initial); -// map.put(key, aggObj); -// } -// -// reduce_function(obj, aggObj); -// } -// -// return { "result": map.values() }; -// }.toString(); -var groupFunction = 'function () {\nvar c = db[ns].find(condition);\nvar map = new Map();\nvar reduce_function = reduce;\n\nwhile (c.hasNext()) {\nvar obj = c.next();\nvar key = {};\n\nfor (var i = 0, len = keys.length; i < len; ++i) {\nvar k = keys[i];\nkey[k] = obj[k];\n}\n\nvar aggObj = map.get(key);\n\nif (aggObj == null) {\nvar newObj = Object.extend({}, key);\naggObj = Object.extend(newObj, initial);\nmap.put(key, aggObj);\n}\n\nreduce_function(obj, aggObj);\n}\n\nreturn { "result": map.values() };\n}'; - -/** - * Run a group command across a collection - * - * @method - * @param {(object|array|function|code)} keys An object, array or function expressing the keys to group by. - * @param {object} condition An optional condition that must be true for a row to be considered. - * @param {object} initial Initial value of the aggregation counter object. - * @param {(function|Code)} reduce The reduce function aggregates (reduces) the objects iterated - * @param {(function|Code)} finalize An optional function to be run on each item in the result set just before the item is returned. - * @param {boolean} command Specify if you wish to run using the internal group command or using eval, default is true. - * @param {object} [options=null] Optional settings. - * @param {(ReadPreference|string)} [options.readPreference=null] The preferred read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST). - * @param {Collection~resultCallback} [callback] The command result callback - * @return {Promise} returns Promise if no callback passed - * @deprecated MongoDB 3.6 or higher will no longer support the group command. We recommend rewriting using the aggregation framework. - */ -Collection.prototype.group = function(keys, condition, initial, reduce, finalize, command, options, callback) { - var self = this; - var args = Array.prototype.slice.call(arguments, 3); - callback = args.pop(); - if(typeof callback != 'function') args.push(callback); - // Fetch all commands - reduce = args.length ? args.shift() : null; - finalize = args.length ? args.shift() : null; - command = args.length ? args.shift() : null; - options = args.length ? args.shift() || {} : {}; - - // Make sure we are backward compatible - if(!(typeof finalize == 'function')) { - command = finalize; - finalize = null; - } - - if (!Array.isArray(keys) && keys instanceof Object && typeof(keys) !== 'function' && !(keys._bsontype == 'Code')) { - keys = Object.keys(keys); - } - - if(typeof reduce === 'function') { - reduce = reduce.toString(); - } - - if(typeof finalize === 'function') { - finalize = finalize.toString(); - } - - // Set up the command as default - command = command == null ? true : command; - - // Execute using callback - if(typeof callback == 'function') return group(self, keys, condition, initial, reduce, finalize, command, options, callback); - // Return a Promise - return new this.s.promiseLibrary(function(resolve, reject) { - group(self, keys, condition, initial, reduce, finalize, command, options, function(err, r) { - if(err) return reject(err); - resolve(r); - }); - }); -} - -var group = function(self, keys, condition, initial, reduce, finalize, command, options, callback) { - // Execute using the command - if(command) { - var reduceFunction = reduce && reduce._bsontype == 'Code' - ? reduce - : new Code(reduce); - - var selector = { - group: { - 'ns': self.s.name - , '$reduce': reduceFunction - , 'cond': condition - , 'initial': initial - , 'out': "inline" - } - }; - - // if finalize is defined - if(finalize != null) selector.group['finalize'] = finalize; - // Set up group selector - if ('function' === typeof keys || (keys && keys._bsontype == 'Code')) { - selector.group.$keyf = keys && keys._bsontype == 'Code' - ? keys - : new Code(keys); - } else { - var hash = {}; - keys.forEach(function (key) { - hash[key] = 1; - }); - selector.group.key = hash; - } - - options = shallowClone(options); - // Ensure we have the right read preference inheritance - options = getReadPreference(self, options, self.s.db, self); - - // Do we have a readConcern specified - if(self.s.readConcern) { - selector.readConcern = self.s.readConcern; - } - - // Have we specified collation - decorateWithCollation(selector, self, options); - - // Execute command - self.s.db.command(selector, options, function(err, result) { - if(err) return handleCallback(callback, err, null); - handleCallback(callback, null, result.retval); - }); - } else { - // Create execution scope - var scope = reduce != null && reduce._bsontype == 'Code' - ? reduce.scope - : {}; - - scope.ns = self.s.name; - scope.keys = keys; - scope.condition = condition; - scope.initial = initial; - - // Pass in the function text to execute within mongodb. - var groupfn = groupFunction.replace(/ reduce;/, reduce.toString() + ';'); - - self.s.db.eval(new Code(groupfn, scope), function (err, results) { - if (err) return handleCallback(callback, err, null); - handleCallback(callback, null, results.result || results); - }); - } -} - -define.classMethod('group', {callback: true, promise:true}); - -/** - * Functions that are passed as scope args must - * be converted to Code instances. - * @ignore - */ -function processScope (scope) { - if(!isObject(scope) || scope._bsontype == 'ObjectID') { - return scope; - } - - var keys = Object.keys(scope); - var i = keys.length; - var key; - var new_scope = {}; - - while (i--) { - key = keys[i]; - if ('function' == typeof scope[key]) { - new_scope[key] = new Code(String(scope[key])); - } else { - new_scope[key] = processScope(scope[key]); - } - } - - return new_scope; -} - -/** - * Run Map Reduce across a collection. Be aware that the inline option for out will return an array of results not a collection. - * - * @method - * @param {(function|string)} map The mapping function. - * @param {(function|string)} reduce The reduce function. - * @param {object} [options=null] Optional settings. - * @param {(ReadPreference|string)} [options.readPreference=null] The preferred read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST). - * @param {object} [options.out=null] Sets the output target for the map reduce job. *{inline:1} | {replace:'collectionName'} | {merge:'collectionName'} | {reduce:'collectionName'}* - * @param {object} [options.query=null] Query filter object. - * @param {object} [options.sort=null] Sorts the input objects using this key. Useful for optimization, like sorting by the emit key for fewer reduces. - * @param {number} [options.limit=null] Number of objects to return from collection. - * @param {boolean} [options.keeptemp=false] Keep temporary data. - * @param {(function|string)} [options.finalize=null] Finalize function. - * @param {object} [options.scope=null] Can pass in variables that can be access from map/reduce/finalize. - * @param {boolean} [options.jsMode=false] It is possible to make the execution stay in JS. Provided in MongoDB > 2.0.X. - * @param {boolean} [options.verbose=false] Provide statistics on job execution time. - * @param {boolean} [options.bypassDocumentValidation=false] Allow driver to bypass schema validation in MongoDB 3.2 or higher. - * @param {Collection~resultCallback} [callback] The command result callback - * @throws {MongoError} - * @return {Promise} returns Promise if no callback passed - */ -Collection.prototype.mapReduce = function(map, reduce, options, callback) { - var self = this; - if('function' === typeof options) callback = options, options = {}; - // Out must allways be defined (make sure we don't break weirdly on pre 1.8+ servers) - if(null == options.out) { - throw new Error("the out option parameter must be defined, see mongodb docs for possible values"); - } - - if('function' === typeof map) { - map = map.toString(); - } - - if('function' === typeof reduce) { - reduce = reduce.toString(); - } - - if('function' === typeof options.finalize) { - options.finalize = options.finalize.toString(); - } - - // Execute using callback - if(typeof callback == 'function') return mapReduce(self, map, reduce, options, callback); - - // Return a Promise - return new this.s.promiseLibrary(function(resolve, reject) { - mapReduce(self, map, reduce, options, function(err, r, r1) { - if(err) return reject(err); - if(!r1) return resolve(r); - resolve({results: r, stats: r1}); - }); - }); -} - -var mapReduce = function(self, map, reduce, options, callback) { - var mapCommandHash = { - mapreduce: self.s.name - , map: map - , reduce: reduce - }; - - // Exclusion list - var exclusionList = ['readPreference']; - - // Add any other options passed in - for(var n in options) { - if('scope' == n) { - mapCommandHash[n] = processScope(options[n]); - } else { - // Only include if not in exclusion list - if(exclusionList.indexOf(n) == -1) { - mapCommandHash[n] = options[n]; - } + return this.s.readPreference; + } + get bsonOptions() { + return this.s.bsonOptions; + } + /** + * The current writeConcern of the collection. If not explicitly defined for + * this collection, will be inherited from the parent DB + */ + get writeConcern() { + if (this.s.writeConcern == null) { + return this.s.db.writeConcern; + } + return this.s.writeConcern; } - } - - options = shallowClone(options); - - // Ensure we have the right read preference inheritance - options = getReadPreference(self, options, self.s.db, self); - - // If we have a read preference and inline is not set as output fail hard - if((options.readPreference != false && options.readPreference != 'primary') - && options['out'] && (options['out'].inline != 1 && options['out'] != 'inline')) { - // Force readPreference to primary - options.readPreference = 'primary'; - // Decorate command with writeConcern if supported - decorateWithWriteConcern(mapCommandHash, self, options); - } else if(self.s.readConcern) { - mapCommandHash.readConcern = self.s.readConcern; - } - - // Is bypassDocumentValidation specified - if(typeof options.bypassDocumentValidation == 'boolean') { - mapCommandHash.bypassDocumentValidation = options.bypassDocumentValidation; - } - - // Have we specified collation - decorateWithCollation(mapCommandHash, self, options); - - // Execute command - self.s.db.command(mapCommandHash, {readPreference:options.readPreference}, function (err, result) { - if(err) return handleCallback(callback, err); - // Check if we have an error - if(1 != result.ok || result.err || result.errmsg) { - return handleCallback(callback, toError(result)); + /** The current index hint for the collection */ + get hint() { + return this.s.collectionHint; } - - // Create statistics value - var stats = {}; - if(result.timeMillis) stats['processtime'] = result.timeMillis; - if(result.counts) stats['counts'] = result.counts; - if(result.timing) stats['timing'] = result.timing; - - // invoked with inline? - if(result.results) { - // If we wish for no verbosity - if(options['verbose'] == null || !options['verbose']) { - return handleCallback(callback, null, result.results); - } - - return handleCallback(callback, null, result.results, stats); + set hint(v) { + this.s.collectionHint = (0, utils_1.normalizeHintField)(v); } - - // The returned collection - var collection = null; - - // If we have an object it's a different db - if(result.result != null && typeof result.result == 'object') { - var doc = result.result; - collection = self.s.db.db(doc.db).collection(doc.collection); - } else { - // Create a collection object that wraps the result collection - collection = self.s.db.collection(result.result) + insertOne(doc, options, callback) { + if (typeof options === 'function') { + callback = options; + options = {}; + } + // CSFLE passes in { w: 'majority' } to ensure the lib works in both 3.x and 4.x + // we support that option style here only + if (options && Reflect.get(options, 'w')) { + options.writeConcern = write_concern_1.WriteConcern.fromOptions(Reflect.get(options, 'w')); + } + return (0, execute_operation_1.executeOperation)(this.s.db.s.client, new insert_1.InsertOneOperation(this, doc, (0, utils_1.resolveOptions)(this, options)), callback); + } + insertMany(docs, options, callback) { + if (typeof options === 'function') + (callback = options), (options = {}); + options = options ? Object.assign({}, options) : { ordered: true }; + return (0, execute_operation_1.executeOperation)(this.s.db.s.client, new insert_1.InsertManyOperation(this, docs, (0, utils_1.resolveOptions)(this, options)), callback); + } + bulkWrite(operations, options, callback) { + if (typeof options === 'function') + (callback = options), (options = {}); + options = options || { ordered: true }; + if (!Array.isArray(operations)) { + throw new error_1.MongoInvalidArgumentError('Argument "operations" must be an array of documents'); + } + return (0, execute_operation_1.executeOperation)(this.s.db.s.client, new bulk_write_1.BulkWriteOperation(this, operations, (0, utils_1.resolveOptions)(this, options)), callback); + } + updateOne(filter, update, options, callback) { + if (typeof options === 'function') + (callback = options), (options = {}); + return (0, execute_operation_1.executeOperation)(this.s.db.s.client, new update_1.UpdateOneOperation(this, filter, update, (0, utils_1.resolveOptions)(this, options)), callback); + } + replaceOne(filter, replacement, options, callback) { + if (typeof options === 'function') + (callback = options), (options = {}); + return (0, execute_operation_1.executeOperation)(this.s.db.s.client, new update_1.ReplaceOneOperation(this, filter, replacement, (0, utils_1.resolveOptions)(this, options)), callback); + } + updateMany(filter, update, options, callback) { + if (typeof options === 'function') + (callback = options), (options = {}); + return (0, execute_operation_1.executeOperation)(this.s.db.s.client, new update_1.UpdateManyOperation(this, filter, update, (0, utils_1.resolveOptions)(this, options)), callback); + } + deleteOne(filter, options, callback) { + if (typeof options === 'function') + (callback = options), (options = {}); + return (0, execute_operation_1.executeOperation)(this.s.db.s.client, new delete_1.DeleteOneOperation(this, filter, (0, utils_1.resolveOptions)(this, options)), callback); + } + deleteMany(filter, options, callback) { + if (filter == null) { + filter = {}; + options = {}; + callback = undefined; + } + else if (typeof filter === 'function') { + callback = filter; + filter = {}; + options = {}; + } + else if (typeof options === 'function') { + callback = options; + options = {}; + } + return (0, execute_operation_1.executeOperation)(this.s.db.s.client, new delete_1.DeleteManyOperation(this, filter, (0, utils_1.resolveOptions)(this, options)), callback); + } + rename(newName, options, callback) { + if (typeof options === 'function') + (callback = options), (options = {}); + // Intentionally, we do not inherit options from parent for this operation. + return (0, execute_operation_1.executeOperation)(this.s.db.s.client, new rename_1.RenameOperation(this, newName, { + ...options, + readPreference: read_preference_1.ReadPreference.PRIMARY + }), callback); + } + drop(options, callback) { + if (typeof options === 'function') + (callback = options), (options = {}); + options = options !== null && options !== void 0 ? options : {}; + return (0, execute_operation_1.executeOperation)(this.s.db.s.client, new drop_1.DropCollectionOperation(this.s.db, this.collectionName, options), callback); + } + findOne(filter, options, callback) { + if (callback != null && typeof callback !== 'function') { + throw new error_1.MongoInvalidArgumentError('Third parameter to `findOne()` must be a callback or undefined'); + } + if (typeof filter === 'function') { + callback = filter; + filter = {}; + options = {}; + } + if (typeof options === 'function') { + callback = options; + options = {}; + } + const finalFilter = filter !== null && filter !== void 0 ? filter : {}; + const finalOptions = options !== null && options !== void 0 ? options : {}; + return this.find(finalFilter, finalOptions).limit(-1).batchSize(1).next(callback); } - - // If we wish for no verbosity - if(options['verbose'] == null || !options['verbose']) { - return handleCallback(callback, err, collection); + find(filter, options) { + if (arguments.length > 2) { + throw new error_1.MongoInvalidArgumentError('Method "collection.find()" accepts at most two arguments'); + } + if (typeof options === 'function') { + throw new error_1.MongoInvalidArgumentError('Argument "options" must not be function'); + } + return new find_cursor_1.FindCursor(this.s.db.s.client, this.s.namespace, filter, (0, utils_1.resolveOptions)(this, options)); + } + options(options, callback) { + if (typeof options === 'function') + (callback = options), (options = {}); + return (0, execute_operation_1.executeOperation)(this.s.db.s.client, new options_operation_1.OptionsOperation(this, (0, utils_1.resolveOptions)(this, options)), callback); + } + isCapped(options, callback) { + if (typeof options === 'function') + (callback = options), (options = {}); + return (0, execute_operation_1.executeOperation)(this.s.db.s.client, new is_capped_1.IsCappedOperation(this, (0, utils_1.resolveOptions)(this, options)), callback); + } + createIndex(indexSpec, options, callback) { + if (typeof options === 'function') + (callback = options), (options = {}); + return (0, execute_operation_1.executeOperation)(this.s.db.s.client, new indexes_1.CreateIndexOperation(this, this.collectionName, indexSpec, (0, utils_1.resolveOptions)(this, options)), callback); + } + createIndexes(indexSpecs, options, callback) { + if (typeof options === 'function') + (callback = options), (options = {}); + options = options ? Object.assign({}, options) : {}; + if (typeof options.maxTimeMS !== 'number') + delete options.maxTimeMS; + return (0, execute_operation_1.executeOperation)(this.s.db.s.client, new indexes_1.CreateIndexesOperation(this, this.collectionName, indexSpecs, (0, utils_1.resolveOptions)(this, options)), callback); + } + dropIndex(indexName, options, callback) { + if (typeof options === 'function') + (callback = options), (options = {}); + options = (0, utils_1.resolveOptions)(this, options); + // Run only against primary + options.readPreference = read_preference_1.ReadPreference.primary; + return (0, execute_operation_1.executeOperation)(this.s.db.s.client, new indexes_1.DropIndexOperation(this, indexName, options), callback); + } + dropIndexes(options, callback) { + if (typeof options === 'function') + (callback = options), (options = {}); + return (0, execute_operation_1.executeOperation)(this.s.db.s.client, new indexes_1.DropIndexesOperation(this, (0, utils_1.resolveOptions)(this, options)), callback); + } + /** + * Get the list of all indexes information for the collection. + * + * @param options - Optional settings for the command + */ + listIndexes(options) { + return new list_indexes_cursor_1.ListIndexesCursor(this, (0, utils_1.resolveOptions)(this, options)); + } + indexExists(indexes, options, callback) { + if (typeof options === 'function') + (callback = options), (options = {}); + return (0, execute_operation_1.executeOperation)(this.s.db.s.client, new indexes_1.IndexExistsOperation(this, indexes, (0, utils_1.resolveOptions)(this, options)), callback); + } + indexInformation(options, callback) { + if (typeof options === 'function') + (callback = options), (options = {}); + return (0, execute_operation_1.executeOperation)(this.s.db.s.client, new indexes_1.IndexInformationOperation(this.s.db, this.collectionName, (0, utils_1.resolveOptions)(this, options)), callback); + } + estimatedDocumentCount(options, callback) { + if (typeof options === 'function') + (callback = options), (options = {}); + return (0, execute_operation_1.executeOperation)(this.s.db.s.client, new estimated_document_count_1.EstimatedDocumentCountOperation(this, (0, utils_1.resolveOptions)(this, options)), callback); + } + countDocuments(filter, options, callback) { + if (filter == null) { + (filter = {}), (options = {}), (callback = undefined); + } + else if (typeof filter === 'function') { + (callback = filter), (filter = {}), (options = {}); + } + else { + if (arguments.length === 2) { + if (typeof options === 'function') + (callback = options), (options = {}); + } + } + filter !== null && filter !== void 0 ? filter : (filter = {}); + return (0, execute_operation_1.executeOperation)(this.s.db.s.client, new count_documents_1.CountDocumentsOperation(this, filter, (0, utils_1.resolveOptions)(this, options)), callback); } - - // Return stats as third set of values - handleCallback(callback, err, collection, stats); - }); -} - -define.classMethod('mapReduce', {callback: true, promise:true}); - -/** - * Initiate a Out of order batch write operation. All operations will be buffered into insert/update/remove commands executed out of order. - * - * @method - * @param {object} [options=null] Optional settings. - * @param {(number|string)} [options.w=null] The write concern. - * @param {number} [options.wtimeout=null] The write concern timeout. - * @param {boolean} [options.j=false] Specify a journal write concern. - * @return {UnorderedBulkOperation} - */ -Collection.prototype.initializeUnorderedBulkOp = function(options) { - options = options || {}; - options.promiseLibrary = this.s.promiseLibrary; - return unordered(this.s.topology, this, options); -} - -define.classMethod('initializeUnorderedBulkOp', {callback: false, promise:false, returns: [ordered.UnorderedBulkOperation]}); - -/** - * Initiate an In order bulk write operation, operations will be serially executed in the order they are added, creating a new operation for each switch in types. - * - * @method - * @param {object} [options=null] Optional settings. - * @param {(number|string)} [options.w=null] The write concern. - * @param {number} [options.wtimeout=null] The write concern timeout. - * @param {boolean} [options.j=false] Specify a journal write concern. - * @param {OrderedBulkOperation} callback The command result callback - * @return {null} - */ -Collection.prototype.initializeOrderedBulkOp = function(options) { - options = options || {}; - options.promiseLibrary = this.s.promiseLibrary; - return ordered(this.s.topology, this, options); -} - -define.classMethod('initializeOrderedBulkOp', {callback: false, promise:false, returns: [ordered.OrderedBulkOperation]}); - -// Get write concern -var writeConcern = function(target, db, col, options) { - if(options.w != null || options.j != null || options.fsync != null) { - var opts = {}; - if(options.w != null) opts.w = options.w; - if(options.wtimeout != null) opts.wtimeout = options.wtimeout; - if(options.j != null) opts.j = options.j; - if(options.fsync != null) opts.fsync = options.fsync; - target.writeConcern = opts; - } else if(col.writeConcern.w != null || col.writeConcern.j != null || col.writeConcern.fsync != null) { - target.writeConcern = col.writeConcern; - } else if(db.writeConcern.w != null || db.writeConcern.j != null || db.writeConcern.fsync != null) { - target.writeConcern = db.writeConcern; - } - - return target -} - -// Figure out the read preference -var getReadPreference = function(self, options, db) { - var r = null - if(options.readPreference) { - r = options.readPreference - } else if(self.s.readPreference) { - r = self.s.readPreference - } else if(db.s.readPreference) { - r = db.s.readPreference; - } - - if(r instanceof ReadPreference) { - options.readPreference = new CoreReadPreference(r.mode, r.tags, {maxStalenessSeconds: r.maxStalenessSeconds}); - } else if(typeof r == 'string') { - options.readPreference = new CoreReadPreference(r); - } else if(r && !(r instanceof ReadPreference) && typeof r == 'object') { - var mode = r.mode || r.preference; - if (mode && typeof mode == 'string') { - options.readPreference = new CoreReadPreference(mode, r.tags, {maxStalenessSeconds: r.maxStalenessSeconds}); + // Implementation + distinct(key, filter, options, callback) { + if (typeof filter === 'function') { + (callback = filter), (filter = {}), (options = {}); + } + else { + if (arguments.length === 3 && typeof options === 'function') { + (callback = options), (options = {}); + } + } + filter !== null && filter !== void 0 ? filter : (filter = {}); + return (0, execute_operation_1.executeOperation)(this.s.db.s.client, new distinct_1.DistinctOperation(this, key, filter, (0, utils_1.resolveOptions)(this, options)), callback); + } + indexes(options, callback) { + if (typeof options === 'function') + (callback = options), (options = {}); + return (0, execute_operation_1.executeOperation)(this.s.db.s.client, new indexes_1.IndexesOperation(this, (0, utils_1.resolveOptions)(this, options)), callback); + } + stats(options, callback) { + if (typeof options === 'function') + (callback = options), (options = {}); + options = options !== null && options !== void 0 ? options : {}; + return (0, execute_operation_1.executeOperation)(this.s.db.s.client, new stats_1.CollStatsOperation(this, options), callback); + } + findOneAndDelete(filter, options, callback) { + if (typeof options === 'function') + (callback = options), (options = {}); + return (0, execute_operation_1.executeOperation)(this.s.db.s.client, new find_and_modify_1.FindOneAndDeleteOperation(this, filter, (0, utils_1.resolveOptions)(this, options)), callback); + } + findOneAndReplace(filter, replacement, options, callback) { + if (typeof options === 'function') + (callback = options), (options = {}); + return (0, execute_operation_1.executeOperation)(this.s.db.s.client, new find_and_modify_1.FindOneAndReplaceOperation(this, filter, replacement, (0, utils_1.resolveOptions)(this, options)), callback); + } + findOneAndUpdate(filter, update, options, callback) { + if (typeof options === 'function') + (callback = options), (options = {}); + return (0, execute_operation_1.executeOperation)(this.s.db.s.client, new find_and_modify_1.FindOneAndUpdateOperation(this, filter, update, (0, utils_1.resolveOptions)(this, options)), callback); + } + /** + * Execute an aggregation framework pipeline against the collection, needs MongoDB \>= 2.2 + * + * @param pipeline - An array of aggregation pipelines to execute + * @param options - Optional settings for the command + */ + aggregate(pipeline = [], options) { + if (arguments.length > 2) { + throw new error_1.MongoInvalidArgumentError('Method "collection.aggregate()" accepts at most two arguments'); + } + if (!Array.isArray(pipeline)) { + throw new error_1.MongoInvalidArgumentError('Argument "pipeline" must be an array of aggregation stages'); + } + if (typeof options === 'function') { + throw new error_1.MongoInvalidArgumentError('Argument "options" must not be function'); + } + return new aggregation_cursor_1.AggregationCursor(this.s.db.s.client, this.s.namespace, pipeline, (0, utils_1.resolveOptions)(this, options)); + } + /** + * Create a new Change Stream, watching for new changes (insertions, updates, replacements, deletions, and invalidations) in this collection. + * + * @remarks + * watch() accepts two generic arguments for distinct usecases: + * - The first is to override the schema that may be defined for this specific collection + * - The second is to override the shape of the change stream document entirely, if it is not provided the type will default to ChangeStreamDocument of the first argument + * @example + * By just providing the first argument I can type the change to be `ChangeStreamDocument<{ _id: number }>` + * ```ts + * collection.watch<{ _id: number }>() + * .on('change', change => console.log(change._id.toFixed(4))); + * ``` + * + * @example + * Passing a second argument provides a way to reflect the type changes caused by an advanced pipeline. + * Here, we are using a pipeline to have MongoDB filter for insert changes only and add a comment. + * No need start from scratch on the ChangeStreamInsertDocument type! + * By using an intersection we can save time and ensure defaults remain the same type! + * ```ts + * collection + * .watch & { comment: string }>([ + * { $addFields: { comment: 'big changes' } }, + * { $match: { operationType: 'insert' } } + * ]) + * .on('change', change => { + * change.comment.startsWith('big'); + * change.operationType === 'insert'; + * // No need to narrow in code because the generics did that for us! + * expectType(change.fullDocument); + * }); + * ``` + * + * @param pipeline - An array of {@link https://docs.mongodb.com/manual/reference/operator/aggregation-pipeline/|aggregation pipeline stages} through which to pass change stream documents. This allows for filtering (using $match) and manipulating the change stream documents. + * @param options - Optional settings for the command + * @typeParam TLocal - Type of the data being detected by the change stream + * @typeParam TChange - Type of the whole change stream document emitted + */ + watch(pipeline = [], options = {}) { + // Allow optionally not specifying a pipeline + if (!Array.isArray(pipeline)) { + options = pipeline; + pipeline = []; + } + return new change_stream_1.ChangeStream(this, pipeline, (0, utils_1.resolveOptions)(this, options)); + } + mapReduce(map, reduce, options, callback) { + (0, utils_1.emitWarningOnce)('collection.mapReduce is deprecated. Use the aggregation pipeline instead. Visit https://docs.mongodb.com/manual/reference/map-reduce-to-aggregation-pipeline for more information on how to translate map-reduce operations to the aggregation pipeline.'); + if ('function' === typeof options) + (callback = options), (options = {}); + // Out must always be defined (make sure we don't break weirdly on pre 1.8+ servers) + // TODO NODE-3339: Figure out if this is still necessary given we no longer officially support pre-1.8 + if ((options === null || options === void 0 ? void 0 : options.out) == null) { + throw new error_1.MongoInvalidArgumentError('Option "out" must be defined, see mongodb docs for possible values'); + } + if ('function' === typeof map) { + map = map.toString(); + } + if ('function' === typeof reduce) { + reduce = reduce.toString(); + } + if ('function' === typeof options.finalize) { + options.finalize = options.finalize.toString(); + } + return (0, execute_operation_1.executeOperation)(this.s.db.s.client, new map_reduce_1.MapReduceOperation(this, map, reduce, (0, utils_1.resolveOptions)(this, options)), callback); + } + /** + * Initiate an Out of order batch write operation. All operations will be buffered into insert/update/remove commands executed out of order. + * + * @throws MongoNotConnectedError + * @remarks + * **NOTE:** MongoClient must be connected prior to calling this method due to a known limitation in this legacy implemenation. + * However, `collection.bulkWrite()` provides an equivalent API that does not require prior connecting. + */ + initializeUnorderedBulkOp(options) { + return new unordered_1.UnorderedBulkOperation(this, (0, utils_1.resolveOptions)(this, options)); + } + /** + * Initiate an In order bulk write operation. Operations will be serially executed in the order they are added, creating a new operation for each switch in types. + * + * @throws MongoNotConnectedError + * @remarks + * **NOTE:** MongoClient must be connected prior to calling this method due to a known limitation in this legacy implemenation. + * However, `collection.bulkWrite()` provides an equivalent API that does not require prior connecting. + */ + initializeOrderedBulkOp(options) { + return new ordered_1.OrderedBulkOperation(this, (0, utils_1.resolveOptions)(this, options)); + } + /** Get the db scoped logger */ + getLogger() { + return this.s.db.s.logger; + } + get logger() { + return this.s.db.s.logger; + } + /** + * Inserts a single document or a an array of documents into MongoDB. If documents passed in do not contain the **_id** field, + * one will be added to each of the documents missing it by the driver, mutating the document. This behavior + * can be overridden by setting the **forceServerObjectId** flag. + * + * @deprecated Use insertOne, insertMany or bulkWrite instead. + * @param docs - The documents to insert + * @param options - Optional settings for the command + * @param callback - An optional callback, a Promise will be returned if none is provided + */ + insert(docs, options, callback) { + (0, utils_1.emitWarningOnce)('collection.insert is deprecated. Use insertOne, insertMany or bulkWrite instead.'); + if (typeof options === 'function') + (callback = options), (options = {}); + options = options || { ordered: false }; + docs = !Array.isArray(docs) ? [docs] : docs; + if (options.keepGoing === true) { + options.ordered = false; + } + return this.insertMany(docs, options, callback); + } + /** + * Updates documents. + * + * @deprecated use updateOne, updateMany or bulkWrite + * @param selector - The selector for the update operation. + * @param update - The update operations to be applied to the documents + * @param options - Optional settings for the command + * @param callback - An optional callback, a Promise will be returned if none is provided + */ + update(selector, update, options, callback) { + (0, utils_1.emitWarningOnce)('collection.update is deprecated. Use updateOne, updateMany, or bulkWrite instead.'); + if (typeof options === 'function') + (callback = options), (options = {}); + options = options !== null && options !== void 0 ? options : {}; + return this.updateMany(selector, update, options, callback); + } + /** + * Remove documents. + * + * @deprecated use deleteOne, deleteMany or bulkWrite + * @param selector - The selector for the update operation. + * @param options - Optional settings for the command + * @param callback - An optional callback, a Promise will be returned if none is provided + */ + remove(selector, options, callback) { + (0, utils_1.emitWarningOnce)('collection.remove is deprecated. Use deleteOne, deleteMany, or bulkWrite instead.'); + if (typeof options === 'function') + (callback = options), (options = {}); + options = options !== null && options !== void 0 ? options : {}; + return this.deleteMany(selector, options, callback); + } + count(filter, options, callback) { + if (typeof filter === 'function') { + (callback = filter), (filter = {}), (options = {}); + } + else { + if (typeof options === 'function') + (callback = options), (options = {}); + } + filter !== null && filter !== void 0 ? filter : (filter = {}); + return (0, execute_operation_1.executeOperation)(this.s.db.s.client, new count_1.CountOperation(utils_1.MongoDBNamespace.fromString(this.namespace), filter, (0, utils_1.resolveOptions)(this, options)), callback); } - } - - return options; -} - -var testForFields = { - limit: 1, sort: 1, fields:1, skip: 1, hint: 1, explain: 1, snapshot: 1, timeout: 1, tailable: 1, tailableRetryInterval: 1 - , numberOfRetries: 1, awaitdata: 1, awaitData: 1, exhaust: 1, batchSize: 1, returnKey: 1, maxScan: 1, min: 1, max: 1, showDiskLoc: 1 - , comment: 1, raw: 1, readPreference: 1, partial: 1, read: 1, dbName: 1, oplogReplay: 1, connection: 1, maxTimeMS: 1, transforms: 1 - , collation: 1 - , noCursorTimeout: 1 } - -module.exports = Collection; +exports.Collection = Collection; +//# sourceMappingURL=collection.js.map \ No newline at end of file diff --git a/ts-ticket-office-service/node_modules/mongodb/lib/collection.js.map b/ts-ticket-office-service/node_modules/mongodb/lib/collection.js.map new file mode 100644 index 000000000..865d3cb6a --- /dev/null +++ b/ts-ticket-office-service/node_modules/mongodb/lib/collection.js.map @@ -0,0 +1 @@ +{"version":3,"file":"collection.js","sourceRoot":"","sources":["../src/collection.ts"],"names":[],"mappings":";;;AAAA,iCAA4E;AAE5E,4CAAsD;AACtD,gDAA0D;AAC1D,mDAA0F;AAC1F,oEAAgE;AAChE,sDAAkD;AAClD,sEAAiE;AAEjE,mCAAoD;AAapD,wDAA6D;AAE7D,8CAAkE;AAClE,kEAA8F;AAC9F,gDAK6B;AAC7B,oDAA2E;AAC3E,4CAAmF;AACnF,oFAG+C;AAC/C,sEAAkE;AAElE,kEAOsC;AACtC,kDAa8B;AAC9B,gDAM6B;AAC7B,sDAA2D;AAC3D,wDAKiC;AAEjC,sEAAkE;AAClE,gDAAqE;AACrE,8CAAqF;AACrF,gDAO6B;AAC7B,iDAA8D;AAC9D,uDAAuE;AACvE,mCAQiB;AACjB,mDAAoE;AAqCpE;;;;;;;;;;;;;;;;;;;;;;;;;;;GA2BG;AACH,MAAa,UAAU;IAIrB;;;OAGG;IACH,YAAY,EAAM,EAAE,IAAY,EAAE,OAA2B;;QAC3D,IAAA,2BAAmB,EAAC,IAAI,CAAC,CAAC;QAE1B,iBAAiB;QACjB,IAAI,CAAC,CAAC,GAAG;YACP,EAAE;YACF,OAAO;YACP,SAAS,EAAE,IAAI,wBAAgB,CAAC,EAAE,CAAC,YAAY,EAAE,IAAI,CAAC;YACtD,SAAS,EA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AAC,CAC9B,EACD,QAAQ,CACT,CAAC;IACJ,CAAC;CACF;AA//CD,gCA+/CC"} \ No newline at end of file diff --git a/ts-ticket-office-service/node_modules/mongodb/lib/command_cursor.js b/ts-ticket-office-service/node_modules/mongodb/lib/command_cursor.js deleted file mode 100644 index a29d1fc37..000000000 --- a/ts-ticket-office-service/node_modules/mongodb/lib/command_cursor.js +++ /dev/null @@ -1,320 +0,0 @@ -"use strict"; - -var inherits = require('util').inherits - , ReadPreference = require('./read_preference') - , MongoError = require('mongodb-core').MongoError - , Readable = require('stream').Readable || require('readable-stream').Readable - , Define = require('./metadata') - , CoreCursor = require('./cursor') - , CoreReadPreference = require('mongodb-core').ReadPreference; - -/** - * @fileOverview The **CommandCursor** class is an internal class that embodies a - * generalized cursor based on a MongoDB command allowing for iteration over the - * results returned. It supports one by one document iteration, conversion to an - * array or can be iterated as a Node 0.10.X or higher stream - * - * **CommandCursor Cannot directly be instantiated** - * @example - * var MongoClient = require('mongodb').MongoClient, - * test = require('assert'); - * // Connection url - * var url = 'mongodb://localhost:27017/test'; - * // Connect using MongoClient - * MongoClient.connect(url, function(err, db) { - * // Create a collection we want to drop later - * var col = db.collection('listCollectionsExample1'); - * // Insert a bunch of documents - * col.insert([{a:1, b:1} - * , {a:2, b:2}, {a:3, b:3} - * , {a:4, b:4}], {w:1}, function(err, result) { - * test.equal(null, err); - * - * // List the database collections available - * db.listCollections().toArray(function(err, items) { - * test.equal(null, err); - * db.close(); - * }); - * }); - * }); - */ - -/** - * Namespace provided by the browser. - * @external Readable - */ - -/** - * Creates a new Command Cursor instance (INTERNAL TYPE, do not instantiate directly) - * @class CommandCursor - * @extends external:Readable - * @fires CommandCursor#data - * @fires CommandCursor#end - * @fires CommandCursor#close - * @fires CommandCursor#readable - * @return {CommandCursor} an CommandCursor instance. - */ -var CommandCursor = function(bson, ns, cmd, options, topology, topologyOptions) { - CoreCursor.apply(this, Array.prototype.slice.call(arguments, 0)); - var state = CommandCursor.INIT; - var streamOptions = {}; - - // MaxTimeMS - var maxTimeMS = null; - - // Get the promiseLibrary - var promiseLibrary = options.promiseLibrary; - - // No promise library selected fall back - if(!promiseLibrary) { - promiseLibrary = typeof global.Promise == 'function' ? - global.Promise : require('es6-promise').Promise; - } - - // Set up - Readable.call(this, {objectMode: true}); - - // Internal state - this.s = { - // MaxTimeMS - maxTimeMS: maxTimeMS - // State - , state: state - // Stream options - , streamOptions: streamOptions - // BSON - , bson: bson - // Namespace - , ns: ns - // Command - , cmd: cmd - // Options - , options: options - // Topology - , topology: topology - // Topology Options - , topologyOptions: topologyOptions - // Promise library - , promiseLibrary: promiseLibrary - } -} - -/** - * CommandCursor stream data event, fired for each document in the cursor. - * - * @event CommandCursor#data - * @type {object} - */ - -/** - * CommandCursor stream end event - * - * @event CommandCursor#end - * @type {null} - */ - -/** - * CommandCursor stream close event - * - * @event CommandCursor#close - * @type {null} - */ - -/** - * CommandCursor stream readable event - * - * @event CommandCursor#readable - * @type {null} - */ - -// Inherit from Readable -inherits(CommandCursor, Readable); - -// Set the methods to inherit from prototype -var methodsToInherit = ['_next', 'next', 'hasNext', 'each', 'forEach', 'toArray' - , 'rewind', 'bufferedCount', 'readBufferedDocuments', 'close', 'isClosed', 'kill', 'setCursorBatchSize' - , '_find', '_getmore', '_killcursor', 'isDead', 'explain', 'isNotified', 'isKilled']; - -// Only inherit the types we need -for(var i = 0; i < methodsToInherit.length; i++) { - CommandCursor.prototype[methodsToInherit[i]] = CoreCursor.prototype[methodsToInherit[i]]; -} - -var define = CommandCursor.define = new Define('CommandCursor', CommandCursor, true); - -/** - * Set the ReadPreference for the cursor. - * @method - * @param {(string|ReadPreference)} readPreference The new read preference for the cursor. - * @throws {MongoError} - * @return {Cursor} - */ -CommandCursor.prototype.setReadPreference = function(r) { - if(this.s.state == CommandCursor.CLOSED || this.isDead()) throw MongoError.create({message: "Cursor is closed", driver:true}); - if(this.s.state != CommandCursor.INIT) throw MongoError.create({message: 'cannot change cursor readPreference after cursor has been accessed', driver:true}); - - if(r instanceof ReadPreference) { - this.s.options.readPreference = new CoreReadPreference(r.mode, r.tags, {maxStalenessSeconds: r.maxStalenessSeconds}); - } else if(typeof r == 'string') { - this.s.options.readPreference = new CoreReadPreference(r); - } else if(r instanceof CoreReadPreference) { - this.s.options.readPreference = r; - } - - return this; -} - -define.classMethod('setReadPreference', {callback: false, promise:false, returns: [CommandCursor]}); - -/** - * Set the batch size for the cursor. - * @method - * @param {number} value The batchSize for the cursor. - * @throws {MongoError} - * @return {CommandCursor} - */ -CommandCursor.prototype.batchSize = function(value) { - if(this.s.state == CommandCursor.CLOSED || this.isDead()) throw MongoError.create({message: "Cursor is closed", driver:true}); - if(typeof value != 'number') throw MongoError.create({message: "batchSize requires an integer", driver:true}); - if(this.s.cmd.cursor) this.s.cmd.cursor.batchSize = value; - this.setCursorBatchSize(value); - return this; -} - -define.classMethod('batchSize', {callback: false, promise:false, returns: [CommandCursor]}); - -/** - * Add a maxTimeMS stage to the aggregation pipeline - * @method - * @param {number} value The state maxTimeMS value. - * @return {CommandCursor} - */ -CommandCursor.prototype.maxTimeMS = function(value) { - if(this.s.topology.lastIsMaster().minWireVersion > 2) { - this.s.cmd.maxTimeMS = value; - } - return this; -} - -define.classMethod('maxTimeMS', {callback: false, promise:false, returns: [CommandCursor]}); - -CommandCursor.prototype.get = CommandCursor.prototype.toArray; - -define.classMethod('get', {callback: true, promise:false}); - -// Inherited methods -define.classMethod('toArray', {callback: true, promise:true}); -define.classMethod('each', {callback: true, promise:false}); -define.classMethod('forEach', {callback: true, promise:false}); -define.classMethod('next', {callback: true, promise:true}); -define.classMethod('hasNext', {callback: true, promise:true}); -define.classMethod('close', {callback: true, promise:true}); -define.classMethod('isClosed', {callback: false, promise:false, returns: [Boolean]}); -define.classMethod('rewind', {callback: false, promise:false}); -define.classMethod('bufferedCount', {callback: false, promise:false, returns: [Number]}); -define.classMethod('readBufferedDocuments', {callback: false, promise:false, returns: [Array]}); - -/** - * Get the next available document from the cursor, returns null if no more documents are available. - * @function CommandCursor.prototype.next - * @param {CommandCursor~resultCallback} [callback] The result callback. - * @throws {MongoError} - * @return {Promise} returns Promise if no callback passed - */ - -/** - * Check if there is any document still available in the cursor - * @function CommandCursor.prototype.hasNext - * @param {CommandCursor~resultCallback} [callback] The result callback. - * @throws {MongoError} - * @return {Promise} returns Promise if no callback passed - */ - -/** - * The callback format for results - * @callback CommandCursor~toArrayResultCallback - * @param {MongoError} error An error instance representing the error during the execution. - * @param {object[]} documents All the documents the satisfy the cursor. - */ - -/** - * Returns an array of documents. The caller is responsible for making sure that there - * is enough memory to store the results. Note that the array only contain partial - * results when this cursor had been previously accessed. - * @method CommandCursor.prototype.toArray - * @param {CommandCursor~toArrayResultCallback} [callback] The result callback. - * @throws {MongoError} - * @return {Promise} returns Promise if no callback passed - */ - -/** - * The callback format for results - * @callback CommandCursor~resultCallback - * @param {MongoError} error An error instance representing the error during the execution. - * @param {(object|null)} result The result object if the command was executed successfully. - */ - -/** - * Iterates over all the documents for this cursor. As with **{cursor.toArray}**, - * not all of the elements will be iterated if this cursor had been previously accessed. - * In that case, **{cursor.rewind}** can be used to reset the cursor. However, unlike - * **{cursor.toArray}**, the cursor will only hold a maximum of batch size elements - * at any given time if batch size is specified. Otherwise, the caller is responsible - * for making sure that the entire result can fit the memory. - * @method CommandCursor.prototype.each - * @param {CommandCursor~resultCallback} callback The result callback. - * @throws {MongoError} - * @return {null} - */ - -/** - * Close the cursor, sending a KillCursor command and emitting close. - * @method CommandCursor.prototype.close - * @param {CommandCursor~resultCallback} [callback] The result callback. - * @return {Promise} returns Promise if no callback passed - */ - -/** - * Is the cursor closed - * @method CommandCursor.prototype.isClosed - * @return {boolean} - */ - -/** - * Clone the cursor - * @function CommandCursor.prototype.clone - * @return {CommandCursor} - */ - -/** - * Resets the cursor - * @function CommandCursor.prototype.rewind - * @return {CommandCursor} - */ - -/** - * The callback format for the forEach iterator method - * @callback CommandCursor~iteratorCallback - * @param {Object} doc An emitted document for the iterator - */ - -/** - * The callback error format for the forEach iterator method - * @callback CommandCursor~endCallback - * @param {MongoError} error An error instance representing the error during the execution. - */ - -/* - * Iterates over all the documents for this cursor using the iterator, callback pattern. - * @method CommandCursor.prototype.forEach - * @param {CommandCursor~iteratorCallback} iterator The iteration callback. - * @param {CommandCursor~endCallback} callback The end callback. - * @throws {MongoError} - * @return {null} - */ - -CommandCursor.INIT = 0; -CommandCursor.OPEN = 1; -CommandCursor.CLOSED = 2; - -module.exports = CommandCursor; diff --git a/ts-ticket-office-service/node_modules/mongodb/lib/connection_string.js b/ts-ticket-office-service/node_modules/mongodb/lib/connection_string.js new file mode 100644 index 000000000..f48447fef --- /dev/null +++ b/ts-ticket-office-service/node_modules/mongodb/lib/connection_string.js @@ -0,0 +1,1094 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.FEATURE_FLAGS = exports.DEFAULT_OPTIONS = exports.OPTIONS = exports.parseOptions = exports.checkTLSOptions = exports.resolveSRVRecord = void 0; +const dns = require("dns"); +const fs = require("fs"); +const mongodb_connection_string_url_1 = require("mongodb-connection-string-url"); +const url_1 = require("url"); +const mongo_credentials_1 = require("./cmap/auth/mongo_credentials"); +const providers_1 = require("./cmap/auth/providers"); +const compression_1 = require("./cmap/wire_protocol/compression"); +const encrypter_1 = require("./encrypter"); +const error_1 = require("./error"); +const logger_1 = require("./logger"); +const mongo_client_1 = require("./mongo_client"); +const promise_provider_1 = require("./promise_provider"); +const read_concern_1 = require("./read_concern"); +const read_preference_1 = require("./read_preference"); +const utils_1 = require("./utils"); +const write_concern_1 = require("./write_concern"); +const VALID_TXT_RECORDS = ['authSource', 'replicaSet', 'loadBalanced']; +const LB_SINGLE_HOST_ERROR = 'loadBalanced option only supported with a single host in the URI'; +const LB_REPLICA_SET_ERROR = 'loadBalanced option not supported with a replicaSet option'; +const LB_DIRECT_CONNECTION_ERROR = 'loadBalanced option not supported when directConnection is provided'; +/** + * Determines whether a provided address matches the provided parent domain in order + * to avoid certain attack vectors. + * + * @param srvAddress - The address to check against a domain + * @param parentDomain - The domain to check the provided address against + * @returns Whether the provided address matches the parent domain + */ +function matchesParentDomain(srvAddress, parentDomain) { + const regex = /^.*?\./; + const srv = `.${srvAddress.replace(regex, '')}`; + const parent = `.${parentDomain.replace(regex, '')}`; + return srv.endsWith(parent); +} +/** + * Lookup a `mongodb+srv` connection string, combine the parts and reparse it as a normal + * connection string. + * + * @param uri - The connection string to parse + * @param options - Optional user provided connection string options + */ +function resolveSRVRecord(options, callback) { + if (typeof options.srvHost !== 'string') { + return callback(new error_1.MongoAPIError('Option "srvHost" must not be empty')); + } + if (options.srvHost.split('.').length < 3) { + // TODO(NODE-3484): Replace with MongoConnectionStringError + return callback(new error_1.MongoAPIError('URI must include hostname, domain name, and tld')); + } + // Resolve the SRV record and use the result as the list of hosts to connect to. + const lookupAddress = options.srvHost; + dns.resolveSrv(`_${options.srvServiceName}._tcp.${lookupAddress}`, (err, addresses) => { + if (err) + return callback(err); + if (addresses.length === 0) { + return callback(new error_1.MongoAPIError('No addresses found at host')); + } + for (const { name } of addresses) { + if (!matchesParentDomain(name, lookupAddress)) { + return callback(new error_1.MongoAPIError('Server record does not share hostname with parent URI')); + } + } + const hostAddresses = addresses.map(r => { var _a; return utils_1.HostAddress.fromString(`${r.name}:${(_a = r.port) !== null && _a !== void 0 ? _a : 27017}`); }); + const lbError = validateLoadBalancedOptions(hostAddresses, options, true); + if (lbError) { + return callback(lbError); + } + // Resolve TXT record and add options from there if they exist. + dns.resolveTxt(lookupAddress, (err, record) => { + var _a, _b, _c; + if (err) { + if (err.code !== 'ENODATA' && err.code !== 'ENOTFOUND') { + return callback(err); + } + } + else { + if (record.length > 1) { + return callback(new error_1.MongoParseError('Multiple text records not allowed')); + } + const txtRecordOptions = new url_1.URLSearchParams(record[0].join('')); + const txtRecordOptionKeys = [...txtRecordOptions.keys()]; + if (txtRecordOptionKeys.some(key => !VALID_TXT_RECORDS.includes(key))) { + return callback(new error_1.MongoParseError(`Text record may only set any of: ${VALID_TXT_RECORDS.join(', ')}`)); + } + if (VALID_TXT_RECORDS.some(option => txtRecordOptions.get(option) === '')) { + return callback(new error_1.MongoParseError('Cannot have empty URI params in DNS TXT Record')); + } + const source = (_a = txtRecordOptions.get('authSource')) !== null && _a !== void 0 ? _a : undefined; + const replicaSet = (_b = txtRecordOptions.get('replicaSet')) !== null && _b !== void 0 ? _b : undefined; + const loadBalanced = (_c = txtRecordOptions.get('loadBalanced')) !== null && _c !== void 0 ? _c : undefined; + if (!options.userSpecifiedAuthSource && + source && + options.credentials && + !providers_1.AUTH_MECHS_AUTH_SRC_EXTERNAL.has(options.credentials.mechanism)) { + options.credentials = mongo_credentials_1.MongoCredentials.merge(options.credentials, { source }); + } + if (!options.userSpecifiedReplicaSet && replicaSet) { + options.replicaSet = replicaSet; + } + if (loadBalanced === 'true') { + options.loadBalanced = true; + } + if (options.replicaSet && options.srvMaxHosts > 0) { + return callback(new error_1.MongoParseError('Cannot combine replicaSet option with srvMaxHosts')); + } + const lbError = validateLoadBalancedOptions(hostAddresses, options, true); + if (lbError) { + return callback(lbError); + } + } + callback(undefined, hostAddresses); + }); + }); +} +exports.resolveSRVRecord = resolveSRVRecord; +/** + * Checks if TLS options are valid + * + * @param options - The options used for options parsing + * @throws MongoParseError if TLS options are invalid + */ +function checkTLSOptions(options) { + if (!options) + return; + const check = (a, b) => { + if (Reflect.has(options, a) && Reflect.has(options, b)) { + throw new error_1.MongoParseError(`The '${a}' option cannot be used with '${b}'`); + } + }; + check('tlsInsecure', 'tlsAllowInvalidCertificates'); + check('tlsInsecure', 'tlsAllowInvalidHostnames'); + check('tlsInsecure', 'tlsDisableCertificateRevocationCheck'); + check('tlsInsecure', 'tlsDisableOCSPEndpointCheck'); + check('tlsAllowInvalidCertificates', 'tlsDisableCertificateRevocationCheck'); + check('tlsAllowInvalidCertificates', 'tlsDisableOCSPEndpointCheck'); + check('tlsDisableCertificateRevocationCheck', 'tlsDisableOCSPEndpointCheck'); +} +exports.checkTLSOptions = checkTLSOptions; +const TRUTHS = new Set(['true', 't', '1', 'y', 'yes']); +const FALSEHOODS = new Set(['false', 'f', '0', 'n', 'no', '-1']); +function getBoolean(name, value) { + if (typeof value === 'boolean') + return value; + const valueString = String(value).toLowerCase(); + if (TRUTHS.has(valueString)) { + if (valueString !== 'true') { + (0, utils_1.emitWarningOnce)(`deprecated value for ${name} : ${valueString} - please update to ${name} : true instead`); + } + return true; + } + if (FALSEHOODS.has(valueString)) { + if (valueString !== 'false') { + (0, utils_1.emitWarningOnce)(`deprecated value for ${name} : ${valueString} - please update to ${name} : false instead`); + } + return false; + } + throw new error_1.MongoParseError(`Expected ${name} to be stringified boolean value, got: ${value}`); +} +function getInt(name, value) { + if (typeof value === 'number') + return Math.trunc(value); + const parsedValue = Number.parseInt(String(value), 10); + if (!Number.isNaN(parsedValue)) + return parsedValue; + throw new error_1.MongoParseError(`Expected ${name} to be stringified int value, got: ${value}`); +} +function getUint(name, value) { + const parsedValue = getInt(name, value); + if (parsedValue < 0) { + throw new error_1.MongoParseError(`${name} can only be a positive int value, got: ${value}`); + } + return parsedValue; +} +function* entriesFromString(value) { + const keyValuePairs = value.split(','); + for (const keyValue of keyValuePairs) { + const [key, value] = keyValue.split(':'); + if (value == null) { + throw new error_1.MongoParseError('Cannot have undefined values in key value pairs'); + } + yield [key, value]; + } +} +class CaseInsensitiveMap extends Map { + constructor(entries = []) { + super(entries.map(([k, v]) => [k.toLowerCase(), v])); + } + has(k) { + return super.has(k.toLowerCase()); + } + get(k) { + return super.get(k.toLowerCase()); + } + set(k, v) { + return super.set(k.toLowerCase(), v); + } + delete(k) { + return super.delete(k.toLowerCase()); + } +} +function parseOptions(uri, mongoClient = undefined, options = {}) { + if (mongoClient != null && !(mongoClient instanceof mongo_client_1.MongoClient)) { + options = mongoClient; + mongoClient = undefined; + } + const url = new mongodb_connection_string_url_1.default(uri); + const { hosts, isSRV } = url; + const mongoOptions = Object.create(null); + // Feature flags + for (const flag of Object.getOwnPropertySymbols(options)) { + if (exports.FEATURE_FLAGS.has(flag)) { + mongoOptions[flag] = options[flag]; + } + } + mongoOptions.hosts = isSRV ? [] : hosts.map(utils_1.HostAddress.fromString); + const urlOptions = new CaseInsensitiveMap(); + if (url.pathname !== '/' && url.pathname !== '') { + const dbName = decodeURIComponent(url.pathname[0] === '/' ? url.pathname.slice(1) : url.pathname); + if (dbName) { + urlOptions.set('dbName', [dbName]); + } + } + if (url.username !== '') { + const auth = { + username: decodeURIComponent(url.username) + }; + if (typeof url.password === 'string') { + auth.password = decodeURIComponent(url.password); + } + urlOptions.set('auth', [auth]); + } + for (const key of url.searchParams.keys()) { + const values = [...url.searchParams.getAll(key)]; + if (values.includes('')) { + throw new error_1.MongoAPIError('URI cannot contain options with no value'); + } + if (!urlOptions.has(key)) { + urlOptions.set(key, values); + } + } + const objectOptions = new CaseInsensitiveMap(Object.entries(options).filter(([, v]) => v != null)); + // Validate options that can only be provided by one of uri or object + if (urlOptions.has('serverApi')) { + throw new error_1.MongoParseError('URI cannot contain `serverApi`, it can only be passed to the client'); + } + if (objectOptions.has('loadBalanced')) { + throw new error_1.MongoParseError('loadBalanced is only a valid option in the URI'); + } + // All option collection + const allOptions = new CaseInsensitiveMap(); + const allKeys = new Set([ + ...urlOptions.keys(), + ...objectOptions.keys(), + ...exports.DEFAULT_OPTIONS.keys() + ]); + for (const key of allKeys) { + const values = []; + const objectOptionValue = objectOptions.get(key); + if (objectOptionValue != null) { + values.push(objectOptionValue); + } + const urlValue = urlOptions.get(key); + if (urlValue != null) { + values.push(...urlValue); + } + const defaultOptionsValue = exports.DEFAULT_OPTIONS.get(key); + if (defaultOptionsValue != null) { + values.push(defaultOptionsValue); + } + allOptions.set(key, values); + } + if (allOptions.has('tlsCertificateKeyFile') && !allOptions.has('tlsCertificateFile')) { + allOptions.set('tlsCertificateFile', allOptions.get('tlsCertificateKeyFile')); + } + if (allOptions.has('tls') || allOptions.has('ssl')) { + const tlsAndSslOpts = (allOptions.get('tls') || []) + .concat(allOptions.get('ssl') || []) + .map(getBoolean.bind(null, 'tls/ssl')); + if (new Set(tlsAndSslOpts).size !== 1) { + throw new error_1.MongoParseError('All values of tls/ssl must be the same.'); + } + } + const unsupportedOptions = (0, utils_1.setDifference)(allKeys, Array.from(Object.keys(exports.OPTIONS)).map(s => s.toLowerCase())); + if (unsupportedOptions.size !== 0) { + const optionWord = unsupportedOptions.size > 1 ? 'options' : 'option'; + const isOrAre = unsupportedOptions.size > 1 ? 'are' : 'is'; + throw new error_1.MongoParseError(`${optionWord} ${Array.from(unsupportedOptions).join(', ')} ${isOrAre} not supported`); + } + // Option parsing and setting + for (const [key, descriptor] of Object.entries(exports.OPTIONS)) { + const values = allOptions.get(key); + if (!values || values.length === 0) + continue; + setOption(mongoOptions, key, descriptor, values); + } + if (mongoOptions.credentials) { + const isGssapi = mongoOptions.credentials.mechanism === providers_1.AuthMechanism.MONGODB_GSSAPI; + const isX509 = mongoOptions.credentials.mechanism === providers_1.AuthMechanism.MONGODB_X509; + const isAws = mongoOptions.credentials.mechanism === providers_1.AuthMechanism.MONGODB_AWS; + if ((isGssapi || isX509) && + allOptions.has('authSource') && + mongoOptions.credentials.source !== '$external') { + // If authSource was explicitly given and its incorrect, we error + throw new error_1.MongoParseError(`${mongoOptions.credentials} can only have authSource set to '$external'`); + } + if (!(isGssapi || isX509 || isAws) && mongoOptions.dbName && !allOptions.has('authSource')) { + // inherit the dbName unless GSSAPI or X509, then silently ignore dbName + // and there was no specific authSource given + mongoOptions.credentials = mongo_credentials_1.MongoCredentials.merge(mongoOptions.credentials, { + source: mongoOptions.dbName + }); + } + mongoOptions.credentials.validate(); + // Check if the only auth related option provided was authSource, if so we can remove credentials + if (mongoOptions.credentials.password === '' && + mongoOptions.credentials.username === '' && + mongoOptions.credentials.mechanism === providers_1.AuthMechanism.MONGODB_DEFAULT && + Object.keys(mongoOptions.credentials.mechanismProperties).length === 0) { + delete mongoOptions.credentials; + } + } + if (!mongoOptions.dbName) { + // dbName default is applied here because of the credential validation above + mongoOptions.dbName = 'test'; + } + checkTLSOptions(mongoOptions); + if (options.promiseLibrary) + promise_provider_1.PromiseProvider.set(options.promiseLibrary); + const lbError = validateLoadBalancedOptions(hosts, mongoOptions, isSRV); + if (lbError) { + throw lbError; + } + if (mongoClient && mongoOptions.autoEncryption) { + encrypter_1.Encrypter.checkForMongoCrypt(); + mongoOptions.encrypter = new encrypter_1.Encrypter(mongoClient, uri, options); + mongoOptions.autoEncrypter = mongoOptions.encrypter.autoEncrypter; + } + // Potential SRV Overrides and SRV connection string validations + mongoOptions.userSpecifiedAuthSource = + objectOptions.has('authSource') || urlOptions.has('authSource'); + mongoOptions.userSpecifiedReplicaSet = + objectOptions.has('replicaSet') || urlOptions.has('replicaSet'); + if (isSRV) { + // SRV Record is resolved upon connecting + mongoOptions.srvHost = hosts[0]; + if (mongoOptions.directConnection) { + throw new error_1.MongoAPIError('SRV URI does not support directConnection'); + } + if (mongoOptions.srvMaxHosts > 0 && typeof mongoOptions.replicaSet === 'string') { + throw new error_1.MongoParseError('Cannot use srvMaxHosts option with replicaSet'); + } + // SRV turns on TLS by default, but users can override and turn it off + const noUserSpecifiedTLS = !objectOptions.has('tls') && !urlOptions.has('tls'); + const noUserSpecifiedSSL = !objectOptions.has('ssl') && !urlOptions.has('ssl'); + if (noUserSpecifiedTLS && noUserSpecifiedSSL) { + mongoOptions.tls = true; + } + } + else { + const userSpecifiedSrvOptions = urlOptions.has('srvMaxHosts') || + objectOptions.has('srvMaxHosts') || + urlOptions.has('srvServiceName') || + objectOptions.has('srvServiceName'); + if (userSpecifiedSrvOptions) { + throw new error_1.MongoParseError('Cannot use srvMaxHosts or srvServiceName with a non-srv connection string'); + } + } + if (mongoOptions.directConnection && mongoOptions.hosts.length !== 1) { + throw new error_1.MongoParseError('directConnection option requires exactly one host'); + } + if (!mongoOptions.proxyHost && + (mongoOptions.proxyPort || mongoOptions.proxyUsername || mongoOptions.proxyPassword)) { + throw new error_1.MongoParseError('Must specify proxyHost if other proxy options are passed'); + } + if ((mongoOptions.proxyUsername && !mongoOptions.proxyPassword) || + (!mongoOptions.proxyUsername && mongoOptions.proxyPassword)) { + throw new error_1.MongoParseError('Can only specify both of proxy username/password or neither'); + } + const proxyOptions = ['proxyHost', 'proxyPort', 'proxyUsername', 'proxyPassword'].map(key => { var _a; return (_a = urlOptions.get(key)) !== null && _a !== void 0 ? _a : []; }); + if (proxyOptions.some(options => options.length > 1)) { + throw new error_1.MongoParseError('Proxy options cannot be specified multiple times in the connection string'); + } + return mongoOptions; +} +exports.parseOptions = parseOptions; +function validateLoadBalancedOptions(hosts, mongoOptions, isSrv) { + if (mongoOptions.loadBalanced) { + if (hosts.length > 1) { + return new error_1.MongoParseError(LB_SINGLE_HOST_ERROR); + } + if (mongoOptions.replicaSet) { + return new error_1.MongoParseError(LB_REPLICA_SET_ERROR); + } + if (mongoOptions.directConnection) { + return new error_1.MongoParseError(LB_DIRECT_CONNECTION_ERROR); + } + if (isSrv && mongoOptions.srvMaxHosts > 0) { + return new error_1.MongoParseError('Cannot limit srv hosts with loadBalanced enabled'); + } + } + return; +} +function setOption(mongoOptions, key, descriptor, values) { + const { target, type, transform, deprecated } = descriptor; + const name = target !== null && target !== void 0 ? target : key; + if (deprecated) { + const deprecatedMsg = typeof deprecated === 'string' ? `: ${deprecated}` : ''; + (0, utils_1.emitWarning)(`${key} is a deprecated option${deprecatedMsg}`); + } + switch (type) { + case 'boolean': + mongoOptions[name] = getBoolean(name, values[0]); + break; + case 'int': + mongoOptions[name] = getInt(name, values[0]); + break; + case 'uint': + mongoOptions[name] = getUint(name, values[0]); + break; + case 'string': + if (values[0] == null) { + break; + } + mongoOptions[name] = String(values[0]); + break; + case 'record': + if (!(0, utils_1.isRecord)(values[0])) { + throw new error_1.MongoParseError(`${name} must be an object`); + } + mongoOptions[name] = values[0]; + break; + case 'any': + mongoOptions[name] = values[0]; + break; + default: { + if (!transform) { + throw new error_1.MongoParseError('Descriptors missing a type must define a transform'); + } + const transformValue = transform({ name, options: mongoOptions, values }); + mongoOptions[name] = transformValue; + break; + } + } +} +exports.OPTIONS = { + appName: { + target: 'metadata', + transform({ options, values: [value] }) { + return (0, utils_1.makeClientMetadata)({ ...options.driverInfo, appName: String(value) }); + } + }, + auth: { + target: 'credentials', + transform({ name, options, values: [value] }) { + if (!(0, utils_1.isRecord)(value, ['username', 'password'])) { + throw new error_1.MongoParseError(`${name} must be an object with 'username' and 'password' properties`); + } + return mongo_credentials_1.MongoCredentials.merge(options.credentials, { + username: value.username, + password: value.password + }); + } + }, + authMechanism: { + target: 'credentials', + transform({ options, values: [value] }) { + var _a, _b; + const mechanisms = Object.values(providers_1.AuthMechanism); + const [mechanism] = mechanisms.filter(m => m.match(RegExp(String.raw `\b${value}\b`, 'i'))); + if (!mechanism) { + throw new error_1.MongoParseError(`authMechanism one of ${mechanisms}, got ${value}`); + } + let source = (_a = options.credentials) === null || _a === void 0 ? void 0 : _a.source; + if (mechanism === providers_1.AuthMechanism.MONGODB_PLAIN || + providers_1.AUTH_MECHS_AUTH_SRC_EXTERNAL.has(mechanism)) { + // some mechanisms have '$external' as the Auth Source + source = '$external'; + } + let password = (_b = options.credentials) === null || _b === void 0 ? void 0 : _b.password; + if (mechanism === providers_1.AuthMechanism.MONGODB_X509 && password === '') { + password = undefined; + } + return mongo_credentials_1.MongoCredentials.merge(options.credentials, { + mechanism, + source, + password + }); + } + }, + authMechanismProperties: { + target: 'credentials', + transform({ options, values: [optionValue] }) { + if (typeof optionValue === 'string') { + const mechanismProperties = Object.create(null); + for (const [key, value] of entriesFromString(optionValue)) { + try { + mechanismProperties[key] = getBoolean(key, value); + } + catch { + mechanismProperties[key] = value; + } + } + return mongo_credentials_1.MongoCredentials.merge(options.credentials, { + mechanismProperties + }); + } + if (!(0, utils_1.isRecord)(optionValue)) { + throw new error_1.MongoParseError('AuthMechanismProperties must be an object'); + } + return mongo_credentials_1.MongoCredentials.merge(options.credentials, { mechanismProperties: optionValue }); + } + }, + authSource: { + target: 'credentials', + transform({ options, values: [value] }) { + const source = String(value); + return mongo_credentials_1.MongoCredentials.merge(options.credentials, { source }); + } + }, + autoEncryption: { + type: 'record' + }, + bsonRegExp: { + type: 'boolean' + }, + serverApi: { + target: 'serverApi', + transform({ values: [version] }) { + const serverApiToValidate = typeof version === 'string' ? { version } : version; + const versionToValidate = serverApiToValidate && serverApiToValidate.version; + if (!versionToValidate) { + throw new error_1.MongoParseError(`Invalid \`serverApi\` property; must specify a version from the following enum: ["${Object.values(mongo_client_1.ServerApiVersion).join('", "')}"]`); + } + if (!Object.values(mongo_client_1.ServerApiVersion).some(v => v === versionToValidate)) { + throw new error_1.MongoParseError(`Invalid server API version=${versionToValidate}; must be in the following enum: ["${Object.values(mongo_client_1.ServerApiVersion).join('", "')}"]`); + } + return serverApiToValidate; + } + }, + checkKeys: { + type: 'boolean' + }, + compressors: { + default: 'none', + target: 'compressors', + transform({ values }) { + const compressionList = new Set(); + for (const compVal of values) { + const compValArray = typeof compVal === 'string' ? compVal.split(',') : compVal; + if (!Array.isArray(compValArray)) { + throw new error_1.MongoInvalidArgumentError('compressors must be an array or a comma-delimited list of strings'); + } + for (const c of compValArray) { + if (Object.keys(compression_1.Compressor).includes(String(c))) { + compressionList.add(String(c)); + } + else { + throw new error_1.MongoInvalidArgumentError(`${c} is not a valid compression mechanism. Must be one of: ${Object.keys(compression_1.Compressor)}.`); + } + } + } + return [...compressionList]; + } + }, + connectTimeoutMS: { + default: 30000, + type: 'uint' + }, + dbName: { + type: 'string' + }, + directConnection: { + default: false, + type: 'boolean' + }, + driverInfo: { + target: 'metadata', + default: (0, utils_1.makeClientMetadata)(), + transform({ options, values: [value] }) { + var _a, _b; + if (!(0, utils_1.isRecord)(value)) + throw new error_1.MongoParseError('DriverInfo must be an object'); + return (0, utils_1.makeClientMetadata)({ + driverInfo: value, + appName: (_b = (_a = options.metadata) === null || _a === void 0 ? void 0 : _a.application) === null || _b === void 0 ? void 0 : _b.name + }); + } + }, + enableUtf8Validation: { type: 'boolean', default: true }, + family: { + transform({ name, values: [value] }) { + const transformValue = getInt(name, value); + if (transformValue === 4 || transformValue === 6) { + return transformValue; + } + throw new error_1.MongoParseError(`Option 'family' must be 4 or 6 got ${transformValue}.`); + } + }, + fieldsAsRaw: { + type: 'record' + }, + forceServerObjectId: { + default: false, + type: 'boolean' + }, + fsync: { + deprecated: 'Please use journal instead', + target: 'writeConcern', + transform({ name, options, values: [value] }) { + const wc = write_concern_1.WriteConcern.fromOptions({ + writeConcern: { + ...options.writeConcern, + fsync: getBoolean(name, value) + } + }); + if (!wc) + throw new error_1.MongoParseError(`Unable to make a writeConcern from fsync=${value}`); + return wc; + } + }, + heartbeatFrequencyMS: { + default: 10000, + type: 'uint' + }, + ignoreUndefined: { + type: 'boolean' + }, + j: { + deprecated: 'Please use journal instead', + target: 'writeConcern', + transform({ name, options, values: [value] }) { + const wc = write_concern_1.WriteConcern.fromOptions({ + writeConcern: { + ...options.writeConcern, + journal: getBoolean(name, value) + } + }); + if (!wc) + throw new error_1.MongoParseError(`Unable to make a writeConcern from journal=${value}`); + return wc; + } + }, + journal: { + target: 'writeConcern', + transform({ name, options, values: [value] }) { + const wc = write_concern_1.WriteConcern.fromOptions({ + writeConcern: { + ...options.writeConcern, + journal: getBoolean(name, value) + } + }); + if (!wc) + throw new error_1.MongoParseError(`Unable to make a writeConcern from journal=${value}`); + return wc; + } + }, + keepAlive: { + default: true, + type: 'boolean' + }, + keepAliveInitialDelay: { + default: 120000, + type: 'uint' + }, + loadBalanced: { + default: false, + type: 'boolean' + }, + localThresholdMS: { + default: 15, + type: 'uint' + }, + logger: { + default: new logger_1.Logger('MongoClient'), + transform({ values: [value] }) { + if (value instanceof logger_1.Logger) { + return value; + } + (0, utils_1.emitWarning)('Alternative loggers might not be supported'); + // TODO: make Logger an interface that others can implement, make usage consistent in driver + // DRIVERS-1204 + return; + } + }, + loggerLevel: { + target: 'logger', + transform({ values: [value] }) { + return new logger_1.Logger('MongoClient', { loggerLevel: value }); + } + }, + maxConnecting: { + default: 2, + transform({ name, values: [value] }) { + const maxConnecting = getUint(name, value); + if (maxConnecting === 0) { + throw new error_1.MongoInvalidArgumentError('maxConnecting must be > 0 if specified'); + } + return maxConnecting; + } + }, + maxIdleTimeMS: { + default: 0, + type: 'uint' + }, + maxPoolSize: { + default: 100, + type: 'uint' + }, + maxStalenessSeconds: { + target: 'readPreference', + transform({ name, options, values: [value] }) { + const maxStalenessSeconds = getUint(name, value); + if (options.readPreference) { + return read_preference_1.ReadPreference.fromOptions({ + readPreference: { ...options.readPreference, maxStalenessSeconds } + }); + } + else { + return new read_preference_1.ReadPreference('secondary', undefined, { maxStalenessSeconds }); + } + } + }, + minInternalBufferSize: { + type: 'uint' + }, + minPoolSize: { + default: 0, + type: 'uint' + }, + minHeartbeatFrequencyMS: { + default: 500, + type: 'uint' + }, + monitorCommands: { + default: false, + type: 'boolean' + }, + name: { + target: 'driverInfo', + transform({ values: [value], options }) { + return { ...options.driverInfo, name: String(value) }; + } + }, + noDelay: { + default: true, + type: 'boolean' + }, + pkFactory: { + default: utils_1.DEFAULT_PK_FACTORY, + transform({ values: [value] }) { + if ((0, utils_1.isRecord)(value, ['createPk']) && typeof value.createPk === 'function') { + return value; + } + throw new error_1.MongoParseError(`Option pkFactory must be an object with a createPk function, got ${value}`); + } + }, + promiseLibrary: { + deprecated: true, + type: 'any' + }, + promoteBuffers: { + type: 'boolean' + }, + promoteLongs: { + type: 'boolean' + }, + promoteValues: { + type: 'boolean' + }, + proxyHost: { + type: 'string' + }, + proxyPassword: { + type: 'string' + }, + proxyPort: { + type: 'uint' + }, + proxyUsername: { + type: 'string' + }, + raw: { + default: false, + type: 'boolean' + }, + readConcern: { + transform({ values: [value], options }) { + if (value instanceof read_concern_1.ReadConcern || (0, utils_1.isRecord)(value, ['level'])) { + return read_concern_1.ReadConcern.fromOptions({ ...options.readConcern, ...value }); + } + throw new error_1.MongoParseError(`ReadConcern must be an object, got ${JSON.stringify(value)}`); + } + }, + readConcernLevel: { + target: 'readConcern', + transform({ values: [level], options }) { + return read_concern_1.ReadConcern.fromOptions({ + ...options.readConcern, + level: level + }); + } + }, + readPreference: { + default: read_preference_1.ReadPreference.primary, + transform({ values: [value], options }) { + var _a, _b, _c; + if (value instanceof read_preference_1.ReadPreference) { + return read_preference_1.ReadPreference.fromOptions({ + readPreference: { ...options.readPreference, ...value }, + ...value + }); + } + if ((0, utils_1.isRecord)(value, ['mode'])) { + const rp = read_preference_1.ReadPreference.fromOptions({ + readPreference: { ...options.readPreference, ...value }, + ...value + }); + if (rp) + return rp; + else + throw new error_1.MongoParseError(`Cannot make read preference from ${JSON.stringify(value)}`); + } + if (typeof value === 'string') { + const rpOpts = { + hedge: (_a = options.readPreference) === null || _a === void 0 ? void 0 : _a.hedge, + maxStalenessSeconds: (_b = options.readPreference) === null || _b === void 0 ? void 0 : _b.maxStalenessSeconds + }; + return new read_preference_1.ReadPreference(value, (_c = options.readPreference) === null || _c === void 0 ? void 0 : _c.tags, rpOpts); + } + throw new error_1.MongoParseError(`Unknown ReadPreference value: ${value}`); + } + }, + readPreferenceTags: { + target: 'readPreference', + transform({ values, options }) { + const tags = Array.isArray(values[0]) + ? values[0] + : values; + const readPreferenceTags = []; + for (const tag of tags) { + const readPreferenceTag = Object.create(null); + if (typeof tag === 'string') { + for (const [k, v] of entriesFromString(tag)) { + readPreferenceTag[k] = v; + } + } + if ((0, utils_1.isRecord)(tag)) { + for (const [k, v] of Object.entries(tag)) { + readPreferenceTag[k] = v; + } + } + readPreferenceTags.push(readPreferenceTag); + } + return read_preference_1.ReadPreference.fromOptions({ + readPreference: options.readPreference, + readPreferenceTags + }); + } + }, + replicaSet: { + type: 'string' + }, + retryReads: { + default: true, + type: 'boolean' + }, + retryWrites: { + default: true, + type: 'boolean' + }, + serializeFunctions: { + type: 'boolean' + }, + serverSelectionTimeoutMS: { + default: 30000, + type: 'uint' + }, + servername: { + type: 'string' + }, + socketTimeoutMS: { + default: 0, + type: 'uint' + }, + srvMaxHosts: { + type: 'uint', + default: 0 + }, + srvServiceName: { + type: 'string', + default: 'mongodb' + }, + ssl: { + target: 'tls', + type: 'boolean' + }, + sslCA: { + target: 'ca', + transform({ values: [value] }) { + return fs.readFileSync(String(value), { encoding: 'ascii' }); + } + }, + sslCRL: { + target: 'crl', + transform({ values: [value] }) { + return fs.readFileSync(String(value), { encoding: 'ascii' }); + } + }, + sslCert: { + target: 'cert', + transform({ values: [value] }) { + return fs.readFileSync(String(value), { encoding: 'ascii' }); + } + }, + sslKey: { + target: 'key', + transform({ values: [value] }) { + return fs.readFileSync(String(value), { encoding: 'ascii' }); + } + }, + sslPass: { + deprecated: true, + target: 'passphrase', + type: 'string' + }, + sslValidate: { + target: 'rejectUnauthorized', + type: 'boolean' + }, + tls: { + type: 'boolean' + }, + tlsAllowInvalidCertificates: { + target: 'rejectUnauthorized', + transform({ name, values: [value] }) { + // allowInvalidCertificates is the inverse of rejectUnauthorized + return !getBoolean(name, value); + } + }, + tlsAllowInvalidHostnames: { + target: 'checkServerIdentity', + transform({ name, values: [value] }) { + // tlsAllowInvalidHostnames means setting the checkServerIdentity function to a noop + return getBoolean(name, value) ? () => undefined : undefined; + } + }, + tlsCAFile: { + target: 'ca', + transform({ values: [value] }) { + return fs.readFileSync(String(value), { encoding: 'ascii' }); + } + }, + tlsCertificateFile: { + target: 'cert', + transform({ values: [value] }) { + return fs.readFileSync(String(value), { encoding: 'ascii' }); + } + }, + tlsCertificateKeyFile: { + target: 'key', + transform({ values: [value] }) { + return fs.readFileSync(String(value), { encoding: 'ascii' }); + } + }, + tlsCertificateKeyFilePassword: { + target: 'passphrase', + type: 'any' + }, + tlsInsecure: { + transform({ name, options, values: [value] }) { + const tlsInsecure = getBoolean(name, value); + if (tlsInsecure) { + options.checkServerIdentity = () => undefined; + options.rejectUnauthorized = false; + } + else { + options.checkServerIdentity = options.tlsAllowInvalidHostnames + ? () => undefined + : undefined; + options.rejectUnauthorized = options.tlsAllowInvalidCertificates ? false : true; + } + return tlsInsecure; + } + }, + w: { + target: 'writeConcern', + transform({ values: [value], options }) { + return write_concern_1.WriteConcern.fromOptions({ writeConcern: { ...options.writeConcern, w: value } }); + } + }, + waitQueueTimeoutMS: { + default: 0, + type: 'uint' + }, + writeConcern: { + target: 'writeConcern', + transform({ values: [value], options }) { + if ((0, utils_1.isRecord)(value) || value instanceof write_concern_1.WriteConcern) { + return write_concern_1.WriteConcern.fromOptions({ + writeConcern: { + ...options.writeConcern, + ...value + } + }); + } + else if (value === 'majority' || typeof value === 'number') { + return write_concern_1.WriteConcern.fromOptions({ + writeConcern: { + ...options.writeConcern, + w: value + } + }); + } + throw new error_1.MongoParseError(`Invalid WriteConcern cannot parse: ${JSON.stringify(value)}`); + } + }, + wtimeout: { + deprecated: 'Please use wtimeoutMS instead', + target: 'writeConcern', + transform({ values: [value], options }) { + const wc = write_concern_1.WriteConcern.fromOptions({ + writeConcern: { + ...options.writeConcern, + wtimeout: getUint('wtimeout', value) + } + }); + if (wc) + return wc; + throw new error_1.MongoParseError(`Cannot make WriteConcern from wtimeout`); + } + }, + wtimeoutMS: { + target: 'writeConcern', + transform({ values: [value], options }) { + const wc = write_concern_1.WriteConcern.fromOptions({ + writeConcern: { + ...options.writeConcern, + wtimeoutMS: getUint('wtimeoutMS', value) + } + }); + if (wc) + return wc; + throw new error_1.MongoParseError(`Cannot make WriteConcern from wtimeout`); + } + }, + zlibCompressionLevel: { + default: 0, + type: 'int' + }, + // Custom types for modifying core behavior + connectionType: { type: 'any' }, + srvPoller: { type: 'any' }, + // Accepted NodeJS Options + minDHSize: { type: 'any' }, + pskCallback: { type: 'any' }, + secureContext: { type: 'any' }, + enableTrace: { type: 'any' }, + requestCert: { type: 'any' }, + rejectUnauthorized: { type: 'any' }, + checkServerIdentity: { type: 'any' }, + ALPNProtocols: { type: 'any' }, + SNICallback: { type: 'any' }, + session: { type: 'any' }, + requestOCSP: { type: 'any' }, + localAddress: { type: 'any' }, + localPort: { type: 'any' }, + hints: { type: 'any' }, + lookup: { type: 'any' }, + ca: { type: 'any' }, + cert: { type: 'any' }, + ciphers: { type: 'any' }, + crl: { type: 'any' }, + ecdhCurve: { type: 'any' }, + key: { type: 'any' }, + passphrase: { type: 'any' }, + pfx: { type: 'any' }, + secureProtocol: { type: 'any' }, + index: { type: 'any' }, + // Legacy Options, these are unused but left here to avoid errors with CSFLE lib + useNewUrlParser: { type: 'boolean' }, + useUnifiedTopology: { type: 'boolean' } +}; +exports.DEFAULT_OPTIONS = new CaseInsensitiveMap(Object.entries(exports.OPTIONS) + .filter(([, descriptor]) => descriptor.default != null) + .map(([k, d]) => [k, d.default])); +/** + * Set of permitted feature flags + * @internal + */ +exports.FEATURE_FLAGS = new Set([Symbol.for('@@mdb.skipPingOnConnect')]); +//# sourceMappingURL=connection_string.js.map \ No newline at end of file diff --git a/ts-ticket-office-service/node_modules/mongodb/lib/connection_string.js.map b/ts-ticket-office-service/node_modules/mongodb/lib/connection_string.js.map new file mode 100644 index 000000000..1584fccce --- /dev/null +++ b/ts-ticket-office-service/node_modules/mongodb/lib/connection_string.js.map @@ -0,0 +1 @@ +{"version":3,"file":"connection_string.js","sourceRoot":"","sources":["../src/connection_string.ts"],"names":[],"mappings":";;;AAAA,2BAA2B;AAC3B,yBAAyB;AACzB,iFAA6D;AAC7D,6BAAsC;AAGtC,qEAAiE;AACjE,qDAAoF;AACpF,kEAA8E;AAC9E,2CAAwC;AACxC,mCAAoF;AACpF,qCAA+C;AAC/C,iDAQwB;AACxB,yDAAqD;AACrD,iDAA+D;AAC/D,uDAAuE;AAEvE,mCAUiB;AACjB,mDAAkD;AAElD,MAAM,iBAAiB,GAAG,CAAC,YAAY,EAAE,YAAY,EAAE,cAAc,CAAC,CAAC;AAEvE,MAAM,oBAAoB,GAAG,kEAAkE,CAAC;AAChG,MAAM,oBAAoB,GAAG,4DAA4D,CAAC;AAC1F,MAAM,0BAA0B,GAC9B,qEAAqE,CAAC;AAExE;;;;;;;GAOG;AACH,SAAS,mBAAmB,CAAC,UAAkB,EAAE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EAAE,EAAE,IAAI,EAAE,KAAK,EAAE;IACpB,cAAc,EAAE,EAAE,IAAI,EAAE,KAAK,EAAE;IAC/B,KAAK,EAAE,EAAE,IAAI,EAAE,KAAK,EAAE;IACtB,gFAAgF;IAChF,eAAe,EAAE,EAAE,IAAI,EAAE,SAAS,EAAsB;IACxD,kBAAkB,EAAE,EAAE,IAAI,EAAE,SAAS,EAAsB;CACN,CAAC;AAE3C,QAAA,eAAe,GAAG,IAAI,kBAAkB,CACnD,MAAM,CAAC,OAAO,CAAC,eAAO,CAAC;KACpB,MAAM,CAAC,CAAC,CAAC,EAAE,UAAU,CAAC,EAAE,EAAE,CAAC,UAAU,CAAC,OAAO,IAAI,IAAI,CAAC;KACtD,GAAG,CAAC,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC,OAAO,CAAC,CAAC,CACnC,CAAC;AAEF;;;GAGG;AACU,QAAA,aAAa,GAAG,IAAI,GAAG,CAAC,CAAC,MAAM,CAAC,GAAG,CAAC,yBAAyB,CAAC,CAAC,CAAC,CAAC"} \ No newline at end of file diff --git a/ts-ticket-office-service/node_modules/mongodb/lib/constants.js b/ts-ticket-office-service/node_modules/mongodb/lib/constants.js new file mode 100644 index 000000000..83653840d --- /dev/null +++ b/ts-ticket-office-service/node_modules/mongodb/lib/constants.js @@ -0,0 +1,129 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.APM_EVENTS = exports.TOPOLOGY_EVENTS = exports.CMAP_EVENTS = exports.HEARTBEAT_EVENTS = exports.RESUME_TOKEN_CHANGED = exports.END = exports.CHANGE = exports.INIT = exports.MORE = exports.RESPONSE = exports.SERVER_HEARTBEAT_FAILED = exports.SERVER_HEARTBEAT_SUCCEEDED = exports.SERVER_HEARTBEAT_STARTED = exports.COMMAND_FAILED = exports.COMMAND_SUCCEEDED = exports.COMMAND_STARTED = exports.CLUSTER_TIME_RECEIVED = exports.CONNECTION_CHECKED_IN = exports.CONNECTION_CHECKED_OUT = exports.CONNECTION_CHECK_OUT_FAILED = exports.CONNECTION_CHECK_OUT_STARTED = exports.CONNECTION_CLOSED = exports.CONNECTION_READY = exports.CONNECTION_CREATED = exports.CONNECTION_POOL_CLEARED = exports.CONNECTION_POOL_CLOSED = exports.CONNECTION_POOL_CREATED = exports.TOPOLOGY_DESCRIPTION_CHANGED = exports.TOPOLOGY_CLOSED = exports.TOPOLOGY_OPENING = exports.SERVER_DESCRIPTION_CHANGED = exports.SERVER_CLOSED = exports.SERVER_OPENING = exports.DESCRIPTION_RECEIVED = exports.UNPINNED = exports.PINNED = exports.MESSAGE = exports.ENDED = exports.CLOSED = exports.CONNECT = exports.OPEN = exports.CLOSE = exports.TIMEOUT = exports.ERROR = exports.SYSTEM_JS_COLLECTION = exports.SYSTEM_COMMAND_COLLECTION = exports.SYSTEM_USER_COLLECTION = exports.SYSTEM_PROFILE_COLLECTION = exports.SYSTEM_INDEX_COLLECTION = exports.SYSTEM_NAMESPACE_COLLECTION = void 0; +exports.LEGACY_HELLO_COMMAND_CAMEL_CASE = exports.LEGACY_HELLO_COMMAND = exports.MONGO_CLIENT_EVENTS = exports.LOCAL_SERVER_EVENTS = exports.SERVER_RELAY_EVENTS = void 0; +exports.SYSTEM_NAMESPACE_COLLECTION = 'system.namespaces'; +exports.SYSTEM_INDEX_COLLECTION = 'system.indexes'; +exports.SYSTEM_PROFILE_COLLECTION = 'system.profile'; +exports.SYSTEM_USER_COLLECTION = 'system.users'; +exports.SYSTEM_COMMAND_COLLECTION = '$cmd'; +exports.SYSTEM_JS_COLLECTION = 'system.js'; +// events +exports.ERROR = 'error'; +exports.TIMEOUT = 'timeout'; +exports.CLOSE = 'close'; +exports.OPEN = 'open'; +exports.CONNECT = 'connect'; +exports.CLOSED = 'closed'; +exports.ENDED = 'ended'; +exports.MESSAGE = 'message'; +exports.PINNED = 'pinned'; +exports.UNPINNED = 'unpinned'; +exports.DESCRIPTION_RECEIVED = 'descriptionReceived'; +exports.SERVER_OPENING = 'serverOpening'; +exports.SERVER_CLOSED = 'serverClosed'; +exports.SERVER_DESCRIPTION_CHANGED = 'serverDescriptionChanged'; +exports.TOPOLOGY_OPENING = 'topologyOpening'; +exports.TOPOLOGY_CLOSED = 'topologyClosed'; +exports.TOPOLOGY_DESCRIPTION_CHANGED = 'topologyDescriptionChanged'; +exports.CONNECTION_POOL_CREATED = 'connectionPoolCreated'; +exports.CONNECTION_POOL_CLOSED = 'connectionPoolClosed'; +exports.CONNECTION_POOL_CLEARED = 'connectionPoolCleared'; +exports.CONNECTION_CREATED = 'connectionCreated'; +exports.CONNECTION_READY = 'connectionReady'; +exports.CONNECTION_CLOSED = 'connectionClosed'; +exports.CONNECTION_CHECK_OUT_STARTED = 'connectionCheckOutStarted'; +exports.CONNECTION_CHECK_OUT_FAILED = 'connectionCheckOutFailed'; +exports.CONNECTION_CHECKED_OUT = 'connectionCheckedOut'; +exports.CONNECTION_CHECKED_IN = 'connectionCheckedIn'; +exports.CLUSTER_TIME_RECEIVED = 'clusterTimeReceived'; +exports.COMMAND_STARTED = 'commandStarted'; +exports.COMMAND_SUCCEEDED = 'commandSucceeded'; +exports.COMMAND_FAILED = 'commandFailed'; +exports.SERVER_HEARTBEAT_STARTED = 'serverHeartbeatStarted'; +exports.SERVER_HEARTBEAT_SUCCEEDED = 'serverHeartbeatSucceeded'; +exports.SERVER_HEARTBEAT_FAILED = 'serverHeartbeatFailed'; +exports.RESPONSE = 'response'; +exports.MORE = 'more'; +exports.INIT = 'init'; +exports.CHANGE = 'change'; +exports.END = 'end'; +exports.RESUME_TOKEN_CHANGED = 'resumeTokenChanged'; +/** @public */ +exports.HEARTBEAT_EVENTS = Object.freeze([ + exports.SERVER_HEARTBEAT_STARTED, + exports.SERVER_HEARTBEAT_SUCCEEDED, + exports.SERVER_HEARTBEAT_FAILED +]); +/** @public */ +exports.CMAP_EVENTS = Object.freeze([ + exports.CONNECTION_POOL_CREATED, + exports.CONNECTION_POOL_CLOSED, + exports.CONNECTION_CREATED, + exports.CONNECTION_READY, + exports.CONNECTION_CLOSED, + exports.CONNECTION_CHECK_OUT_STARTED, + exports.CONNECTION_CHECK_OUT_FAILED, + exports.CONNECTION_CHECKED_OUT, + exports.CONNECTION_CHECKED_IN, + exports.CONNECTION_POOL_CLEARED +]); +/** @public */ +exports.TOPOLOGY_EVENTS = Object.freeze([ + exports.SERVER_OPENING, + exports.SERVER_CLOSED, + exports.SERVER_DESCRIPTION_CHANGED, + exports.TOPOLOGY_OPENING, + exports.TOPOLOGY_CLOSED, + exports.TOPOLOGY_DESCRIPTION_CHANGED, + exports.ERROR, + exports.TIMEOUT, + exports.CLOSE +]); +/** @public */ +exports.APM_EVENTS = Object.freeze([ + exports.COMMAND_STARTED, + exports.COMMAND_SUCCEEDED, + exports.COMMAND_FAILED +]); +/** + * All events that we relay to the `Topology` + * @internal + */ +exports.SERVER_RELAY_EVENTS = Object.freeze([ + exports.SERVER_HEARTBEAT_STARTED, + exports.SERVER_HEARTBEAT_SUCCEEDED, + exports.SERVER_HEARTBEAT_FAILED, + exports.COMMAND_STARTED, + exports.COMMAND_SUCCEEDED, + exports.COMMAND_FAILED, + ...exports.CMAP_EVENTS +]); +/** + * All events we listen to from `Server` instances, but do not forward to the client + * @internal + */ +exports.LOCAL_SERVER_EVENTS = Object.freeze([ + exports.CONNECT, + exports.DESCRIPTION_RECEIVED, + exports.CLOSED, + exports.ENDED +]); +/** @public */ +exports.MONGO_CLIENT_EVENTS = Object.freeze([ + ...exports.CMAP_EVENTS, + ...exports.APM_EVENTS, + ...exports.TOPOLOGY_EVENTS, + ...exports.HEARTBEAT_EVENTS +]); +/** + * @internal + * The legacy hello command that was deprecated in MongoDB 5.0. + */ +exports.LEGACY_HELLO_COMMAND = 'ismaster'; +/** + * @internal + * The legacy hello command that was deprecated in MongoDB 5.0. + */ +exports.LEGACY_HELLO_COMMAND_CAMEL_CASE = 'isMaster'; +//# sourceMappingURL=constants.js.map \ No newline at end of file diff --git a/ts-ticket-office-service/node_modules/mongodb/lib/constants.js.map b/ts-ticket-office-service/node_modules/mongodb/lib/constants.js.map new file mode 100644 index 000000000..f6e3365c5 --- /dev/null +++ b/ts-ticket-office-service/node_modules/mongodb/lib/constants.js.map @@ -0,0 +1 @@ +{"version":3,"file":"constants.js","sourceRoot":"","sources":["../src/constants.ts"],"names":[],"mappings":";;;;AAAa,QAAA,2BAA2B,GAAG,mBAAmB,CAAC;AAClD,QAAA,uBAAuB,GAAG,gBAAgB,CAAC;AAC3C,QAAA,yBAAyB,GAAG,gBAAgB,CAAC;AAC7C,QAAA,sBAAsB,GAAG,cAAc,CAAC;AACxC,QAAA,yBAAyB,GAAG,MAAM,CAAC;AACnC,QAAA,oBAAoB,GAAG,WAAW,CAAC;AAEhD,SAAS;AACI,QAAA,KAAK,GAAG,OAAgB,CAAC;AACzB,QAAA,OAAO,GAAG,SAAkB,CAAC;AAC7B,QAAA,KAAK,GAAG,OAAgB,CAAC;AACzB,QAAA,IAAI,GAAG,MAAe,CAAC;AACvB,QAAA,OAAO,GAAG,SAAkB,CAAC;AAC7B,QAAA,MAAM,GAAG,QAAiB,CAAC;AAC3B,QAAA,KAAK,GAAG,OAAgB,CAAC;AACzB,QAAA,OAAO,GAAG,SAAkB,CAAC;AAC7B,QAAA,MAAM,GAAG,QAAiB,CAAC;AAC3B,QAAA,QAAQ,GAAG,UAAmB,CAAC;AAC/B,QAAA,oBAAoB,GAAG,qBAAqB,CAAC;AAC7C,QAAA,cAAc,GAAG,eAAwB,CAAC;AAC1C,QAAA,aAAa,GAAG,cAAuB,CAAC;AACxC,QAAA,0BAA0B,GAAG,0BAAmC,CAAC;AACjE,QAAA,gBAAgB,GAAG,iBAA0B,CAAC;AAC9C,QAAA,eAAe,GAAG,gBAAyB,CAAC;AAC5C,QAAA,4BAA4B,GAAG,4BAAqC,CAAC;AACrE,QAAA,uBAAuB,GAAG,uBAAgC,CAAC;AAC3D,QAAA,sBAAsB,GAAG,sBAA+B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,MAAM,CAAC,MAAM,CAAC;IAC3C,sBAAc;IACd,qBAAa;IACb,kCAA0B;IAC1B,wBAAgB;IAChB,uBAAe;IACf,oCAA4B;IAC5B,aAAK;IACL,eAAO;IACP,aAAK;CACG,CAAC,CAAC;AAEZ,cAAc;AACD,QAAA,UAAU,GAAG,MAAM,CAAC,MAAM,CAAC;IACtC,uBAAe;IACf,yBAAiB;IACjB,sBAAc;CACN,CAAC,CAAC;AAEZ;;;GAGG;AACU,QAAA,mBAAmB,GAAG,MAAM,CAAC,MAAM,CAAC;IAC/C,gCAAwB;IACxB,kCAA0B;IAC1B,+BAAuB;IACvB,uBAAe;IACf,yBAAiB;IACjB,sBAAc;IACd,GAAG,mBAAW;CACN,CAAC,CAAC;AAEZ;;;GAGG;AACU,QAAA,mBAAmB,GAAG,MAAM,CAAC,MAAM,CAAC;IAC/C,eAAO;IACP,4BAAoB;IACpB,cAAM;IACN,aAAK;CACG,CAAC,CAAC;AAEZ,cAAc;AACD,QAAA,mBAAmB,GAAG,MAAM,CAAC,MAAM,CAAC;IAC/C,GAAG,mBAAW;IACd,GAAG,kBAAU;IACb,GAAG,uBAAe;IAClB,GAAG,wBAAgB;CACX,CAAC,CAAC;AAEZ;;;GAGG;AACU,QAAA,oBAAoB,GAAG,UAAU,CAAC;AAE/C;;;GAGG;AACU,QAAA,+BAA+B,GAAG,UAAU,CAAC"} \ No newline at end of file diff --git a/ts-ticket-office-service/node_modules/mongodb/lib/cursor.js b/ts-ticket-office-service/node_modules/mongodb/lib/cursor.js deleted file mode 100644 index 9a9bd4d4f..000000000 --- a/ts-ticket-office-service/node_modules/mongodb/lib/cursor.js +++ /dev/null @@ -1,1208 +0,0 @@ -"use strict"; - -var inherits = require('util').inherits - , f = require('util').format - , formattedOrderClause = require('./utils').formattedOrderClause - , handleCallback = require('./utils').handleCallback - , ReadPreference = require('./read_preference') - , MongoError = require('mongodb-core').MongoError - , Readable = require('stream').Readable || require('readable-stream').Readable - , Define = require('./metadata') - , CoreCursor = require('mongodb-core').Cursor - , Map = require('mongodb-core').BSON.Map - , CoreReadPreference = require('mongodb-core').ReadPreference; - -/** - * @fileOverview The **Cursor** class is an internal class that embodies a cursor on MongoDB - * allowing for iteration over the results returned from the underlying query. It supports - * one by one document iteration, conversion to an array or can be iterated as a Node 0.10.X - * or higher stream - * - * **CURSORS Cannot directly be instantiated** - * @example - * var MongoClient = require('mongodb').MongoClient, - * test = require('assert'); - * // Connection url - * var url = 'mongodb://localhost:27017/test'; - * // Connect using MongoClient - * MongoClient.connect(url, function(err, db) { - * // Create a collection we want to drop later - * var col = db.collection('createIndexExample1'); - * // Insert a bunch of documents - * col.insert([{a:1, b:1} - * , {a:2, b:2}, {a:3, b:3} - * , {a:4, b:4}], {w:1}, function(err, result) { - * test.equal(null, err); - * - * // Show that duplicate records got dropped - * col.find({}).toArray(function(err, items) { - * test.equal(null, err); - * test.equal(4, items.length); - * db.close(); - * }); - * }); - * }); - */ - -/** - * Namespace provided by the mongodb-core and node.js - * @external CoreCursor - * @external Readable - */ - -// Flags allowed for cursor -var flags = ['tailable', 'oplogReplay', 'noCursorTimeout', 'awaitData', 'exhaust', 'partial']; -var fields = ['numberOfRetries', 'tailableRetryInterval']; -var push = Array.prototype.push; - -/** - * Creates a new Cursor instance (INTERNAL TYPE, do not instantiate directly) - * @class Cursor - * @extends external:CoreCursor - * @extends external:Readable - * @property {string} sortValue Cursor query sort setting. - * @property {boolean} timeout Is Cursor able to time out. - * @property {ReadPreference} readPreference Get cursor ReadPreference. - * @fires Cursor#data - * @fires Cursor#end - * @fires Cursor#close - * @fires Cursor#readable - * @return {Cursor} a Cursor instance. - * @example - * Cursor cursor options. - * - * collection.find({}).project({a:1}) // Create a projection of field a - * collection.find({}).skip(1).limit(10) // Skip 1 and limit 10 - * collection.find({}).batchSize(5) // Set batchSize on cursor to 5 - * collection.find({}).filter({a:1}) // Set query on the cursor - * collection.find({}).comment('add a comment') // Add a comment to the query, allowing to correlate queries - * collection.find({}).addCursorFlag('tailable', true) // Set cursor as tailable - * collection.find({}).addCursorFlag('oplogReplay', true) // Set cursor as oplogReplay - * collection.find({}).addCursorFlag('noCursorTimeout', true) // Set cursor as noCursorTimeout - * collection.find({}).addCursorFlag('awaitData', true) // Set cursor as awaitData - * collection.find({}).addCursorFlag('partial', true) // Set cursor as partial - * collection.find({}).addQueryModifier('$orderby', {a:1}) // Set $orderby {a:1} - * collection.find({}).max(10) // Set the cursor maxScan - * collection.find({}).maxScan(10) // Set the cursor maxScan - * collection.find({}).maxTimeMS(1000) // Set the cursor maxTimeMS - * collection.find({}).min(100) // Set the cursor min - * collection.find({}).returnKey(10) // Set the cursor returnKey - * collection.find({}).setReadPreference(ReadPreference.PRIMARY) // Set the cursor readPreference - * collection.find({}).showRecordId(true) // Set the cursor showRecordId - * collection.find({}).snapshot(true) // Set the cursor snapshot - * collection.find({}).sort([['a', 1]]) // Sets the sort order of the cursor query - * collection.find({}).hint('a_1') // Set the cursor hint - * - * All options are chainable, so one can do the following. - * - * collection.find({}).maxTimeMS(1000).maxScan(100).skip(1).toArray(..) - */ -var Cursor = function(bson, ns, cmd, options, topology, topologyOptions) { - CoreCursor.apply(this, Array.prototype.slice.call(arguments, 0)); - var self = this; - var state = Cursor.INIT; - var streamOptions = {}; - - // Tailable cursor options - var numberOfRetries = options.numberOfRetries || 5; - var tailableRetryInterval = options.tailableRetryInterval || 500; - var currentNumberOfRetries = numberOfRetries; - - // Get the promiseLibrary - var promiseLibrary = options.promiseLibrary; - - // No promise library selected fall back - if(!promiseLibrary) { - promiseLibrary = typeof global.Promise == 'function' ? - global.Promise : require('es6-promise').Promise; - } - - // Set up - Readable.call(this, {objectMode: true}); - - // Internal cursor state - this.s = { - // Tailable cursor options - numberOfRetries: numberOfRetries - , tailableRetryInterval: tailableRetryInterval - , currentNumberOfRetries: currentNumberOfRetries - // State - , state: state - // Stream options - , streamOptions: streamOptions - // BSON - , bson: bson - // Namespace - , ns: ns - // Command - , cmd: cmd - // Options - , options: options - // Topology - , topology: topology - // Topology options - , topologyOptions: topologyOptions - // Promise library - , promiseLibrary: promiseLibrary - // Current doc - , currentDoc: null - } - - // Translate correctly - if(self.s.options.noCursorTimeout == true) { - self.addCursorFlag('noCursorTimeout', true); - } - - // Set the sort value - this.sortValue = self.s.cmd.sort; - - // Get the batchSize - var batchSize = cmd.cursor && cmd.cursor.batchSize - ? cmd.cursor && cmd.cursor.batchSize - : (options.cursor && options.cursor.batchSize ? options.cursor.batchSize : 1000); - - // Set the batchSize - this.setCursorBatchSize(batchSize); -} - -/** - * Cursor stream data event, fired for each document in the cursor. - * - * @event Cursor#data - * @type {object} - */ - -/** - * Cursor stream end event - * - * @event Cursor#end - * @type {null} - */ - -/** - * Cursor stream close event - * - * @event Cursor#close - * @type {null} - */ - -/** - * Cursor stream readable event - * - * @event Cursor#readable - * @type {null} - */ - -// Inherit from Readable -inherits(Cursor, Readable); - -// Map core cursor _next method so we can apply mapping -CoreCursor.prototype._next = CoreCursor.prototype.next; - -for(var name in CoreCursor.prototype) { - Cursor.prototype[name] = CoreCursor.prototype[name]; -} - -var define = Cursor.define = new Define('Cursor', Cursor, true); - -/** - * Check if there is any document still available in the cursor - * @method - * @param {Cursor~resultCallback} [callback] The result callback. - * @throws {MongoError} - * @return {Promise} returns Promise if no callback passed - */ -Cursor.prototype.hasNext = function(callback) { - var self = this; - - // Execute using callback - if(typeof callback == 'function') { - if(self.s.currentDoc){ - return callback(null, true); - } else { - return nextObject(self, function(err, doc) { - if (err) return callback(err, null); - if (!doc) return callback(null, false); - self.s.currentDoc = doc; - callback(null, true); - }); - } - } - - // Return a Promise - return new this.s.promiseLibrary(function(resolve, reject) { - if(self.s.currentDoc){ - resolve(true); - } else { - nextObject(self, function(err, doc) { - if(self.s.state == Cursor.CLOSED || self.isDead()) return resolve(false); - if(err) return reject(err); - if(!doc) return resolve(false); - self.s.currentDoc = doc; - resolve(true); - }); - } - }); -} - -define.classMethod('hasNext', {callback: true, promise:true}); - -/** - * Get the next available document from the cursor, returns null if no more documents are available. - * @method - * @param {Cursor~resultCallback} [callback] The result callback. - * @throws {MongoError} - * @return {Promise} returns Promise if no callback passed - */ -Cursor.prototype.next = function(callback) { - var self = this; - - // Execute using callback - if(typeof callback == 'function') { - // Return the currentDoc if someone called hasNext first - if(self.s.currentDoc) { - var doc = self.s.currentDoc; - self.s.currentDoc = null; - return callback(null, doc); - } - - // Return the next object - return nextObject(self, callback) - } - - // Return a Promise - return new this.s.promiseLibrary(function(resolve, reject) { - // Return the currentDoc if someone called hasNext first - if(self.s.currentDoc) { - var doc = self.s.currentDoc; - self.s.currentDoc = null; - return resolve(doc); - } - - nextObject(self, function(err, r) { - if(err) return reject(err); - resolve(r); - }); - }); -} - -define.classMethod('next', {callback: true, promise:true}); - -/** - * Set the cursor query - * @method - * @param {object} filter The filter object used for the cursor. - * @return {Cursor} - */ -Cursor.prototype.filter = function(filter) { - if(this.s.state == Cursor.CLOSED || this.s.state == Cursor.OPEN || this.isDead()) throw MongoError.create({message: "Cursor is closed", driver:true}); - this.s.cmd.query = filter; - return this; -} - -define.classMethod('filter', {callback: false, promise:false, returns: [Cursor]}); - -/** - * Set the cursor maxScan - * @method - * @param {object} maxScan Constrains the query to only scan the specified number of documents when fulfilling the query - * @return {Cursor} - */ -Cursor.prototype.maxScan = function(maxScan) { - if(this.s.state == Cursor.CLOSED || this.s.state == Cursor.OPEN || this.isDead()) throw MongoError.create({message: "Cursor is closed", driver:true}); - this.s.cmd.maxScan = maxScan; - return this; -} - -define.classMethod('maxScan', {callback: false, promise:false, returns: [Cursor]}); - -/** - * Set the cursor hint - * @method - * @param {object} hint If specified, then the query system will only consider plans using the hinted index. - * @return {Cursor} - */ -Cursor.prototype.hint = function(hint) { - if(this.s.state == Cursor.CLOSED || this.s.state == Cursor.OPEN || this.isDead()) throw MongoError.create({message: "Cursor is closed", driver:true}); - this.s.cmd.hint = hint; - return this; -} - -define.classMethod('hint', {callback: false, promise:false, returns: [Cursor]}); - -/** - * Set the cursor min - * @method - * @param {object} min Specify a $min value to specify the inclusive lower bound for a specific index in order to constrain the results of find(). The $min specifies the lower bound for all keys of a specific index in order. - * @return {Cursor} - */ -Cursor.prototype.min = function(min) { - if(this.s.state == Cursor.CLOSED || this.s.state == Cursor.OPEN || this.isDead()) throw MongoError.create({message: "Cursor is closed", driver:true}); - this.s.cmd.min = min; - return this; -} - -define.classMethod('min', {callback: false, promise:false, returns: [Cursor]}); - -/** - * Set the cursor max - * @method - * @param {object} max Specify a $max value to specify the exclusive upper bound for a specific index in order to constrain the results of find(). The $max specifies the upper bound for all keys of a specific index in order. - * @return {Cursor} - */ -Cursor.prototype.max = function(max) { - if(this.s.state == Cursor.CLOSED || this.s.state == Cursor.OPEN || this.isDead()) throw MongoError.create({message: "Cursor is closed", driver:true}); - this.s.cmd.max = max; - return this; -} - -define.classMethod('max', {callback: false, promise:false, returns: [Cursor]}); - -/** - * Set the cursor returnKey - * @method - * @param {object} returnKey Only return the index field or fields for the results of the query. If $returnKey is set to true and the query does not use an index to perform the read operation, the returned documents will not contain any fields. Use one of the following forms: - * @return {Cursor} - */ -Cursor.prototype.returnKey = function(value) { - if(this.s.state == Cursor.CLOSED || this.s.state == Cursor.OPEN || this.isDead()) throw MongoError.create({message: "Cursor is closed", driver:true}); - this.s.cmd.returnKey = value; - return this; -} - -define.classMethod('returnKey', {callback: false, promise:false, returns: [Cursor]}); - -/** - * Set the cursor showRecordId - * @method - * @param {object} showRecordId The $showDiskLoc option has now been deprecated and replaced with the showRecordId field. $showDiskLoc will still be accepted for OP_QUERY stye find. - * @return {Cursor} - */ -Cursor.prototype.showRecordId = function(value) { - if(this.s.state == Cursor.CLOSED || this.s.state == Cursor.OPEN || this.isDead()) throw MongoError.create({message: "Cursor is closed", driver:true}); - this.s.cmd.showDiskLoc = value; - return this; -} - -define.classMethod('showRecordId', {callback: false, promise:false, returns: [Cursor]}); - -/** - * Set the cursor snapshot - * @method - * @param {object} snapshot The $snapshot operator prevents the cursor from returning a document more than once because an intervening write operation results in a move of the document. - * @return {Cursor} - */ -Cursor.prototype.snapshot = function(value) { - if(this.s.state == Cursor.CLOSED || this.s.state == Cursor.OPEN || this.isDead()) throw MongoError.create({message: "Cursor is closed", driver:true}); - this.s.cmd.snapshot = value; - return this; -} - -define.classMethod('snapshot', {callback: false, promise:false, returns: [Cursor]}); - -/** - * Set a node.js specific cursor option - * @method - * @param {string} field The cursor option to set ['numberOfRetries', 'tailableRetryInterval']. - * @param {object} value The field value. - * @throws {MongoError} - * @return {Cursor} - */ -Cursor.prototype.setCursorOption = function(field, value) { - if(this.s.state == Cursor.CLOSED || this.s.state == Cursor.OPEN || this.isDead()) throw MongoError.create({message: "Cursor is closed", driver:true}); - if(fields.indexOf(field) == -1) throw MongoError.create({message: f("option %s not a supported option %s", field, fields), driver:true }); - this.s[field] = value; - if(field == 'numberOfRetries') - this.s.currentNumberOfRetries = value; - return this; -} - -define.classMethod('setCursorOption', {callback: false, promise:false, returns: [Cursor]}); - -/** - * Add a cursor flag to the cursor - * @method - * @param {string} flag The flag to set, must be one of following ['tailable', 'oplogReplay', 'noCursorTimeout', 'awaitData', 'partial']. - * @param {boolean} value The flag boolean value. - * @throws {MongoError} - * @return {Cursor} - */ -Cursor.prototype.addCursorFlag = function(flag, value) { - if(this.s.state == Cursor.CLOSED || this.s.state == Cursor.OPEN || this.isDead()) throw MongoError.create({message: "Cursor is closed", driver:true}); - if(flags.indexOf(flag) == -1) throw MongoError.create({message: f("flag %s not a supported flag %s", flag, flags), driver:true }); - if(typeof value != 'boolean') throw MongoError.create({message: f("flag %s must be a boolean value", flag), driver:true}); - this.s.cmd[flag] = value; - return this; -} - -define.classMethod('addCursorFlag', {callback: false, promise:false, returns: [Cursor]}); - -/** - * Add a query modifier to the cursor query - * @method - * @param {string} name The query modifier (must start with $, such as $orderby etc) - * @param {boolean} value The flag boolean value. - * @throws {MongoError} - * @return {Cursor} - */ -Cursor.prototype.addQueryModifier = function(name, value) { - if(this.s.state == Cursor.CLOSED || this.s.state == Cursor.OPEN || this.isDead()) throw MongoError.create({message: "Cursor is closed", driver:true}); - if(name[0] != '$') throw MongoError.create({message: f("%s is not a valid query modifier"), driver:true}); - // Strip of the $ - var field = name.substr(1); - // Set on the command - this.s.cmd[field] = value; - // Deal with the special case for sort - if(field == 'orderby') this.s.cmd.sort = this.s.cmd[field]; - return this; -} - -define.classMethod('addQueryModifier', {callback: false, promise:false, returns: [Cursor]}); - -/** - * Add a comment to the cursor query allowing for tracking the comment in the log. - * @method - * @param {string} value The comment attached to this query. - * @throws {MongoError} - * @return {Cursor} - */ -Cursor.prototype.comment = function(value) { - if(this.s.state == Cursor.CLOSED || this.s.state == Cursor.OPEN || this.isDead()) throw MongoError.create({message: "Cursor is closed", driver:true}); - this.s.cmd.comment = value; - return this; -} - -define.classMethod('comment', {callback: false, promise:false, returns: [Cursor]}); - -/** - * Set a maxAwaitTimeMS on a tailing cursor query to allow to customize the timeout value for the option awaitData (Only supported on MongoDB 3.2 or higher, ignored otherwise) - * @method - * @param {number} value Number of milliseconds to wait before aborting the tailed query. - * @throws {MongoError} - * @return {Cursor} - */ -Cursor.prototype.maxAwaitTimeMS = function(value) { - if(typeof value != 'number') throw MongoError.create({message: "maxAwaitTimeMS must be a number", driver:true}); - if(this.s.state == Cursor.CLOSED || this.s.state == Cursor.OPEN || this.isDead()) throw MongoError.create({message: "Cursor is closed", driver:true}); - this.s.cmd.maxAwaitTimeMS = value; - return this; -} - -define.classMethod('maxAwaitTimeMS', {callback: false, promise:false, returns: [Cursor]}); - -/** - * Set a maxTimeMS on the cursor query, allowing for hard timeout limits on queries (Only supported on MongoDB 2.6 or higher) - * @method - * @param {number} value Number of milliseconds to wait before aborting the query. - * @throws {MongoError} - * @return {Cursor} - */ -Cursor.prototype.maxTimeMS = function(value) { - if(typeof value != 'number') throw MongoError.create({message: "maxTimeMS must be a number", driver:true}); - if(this.s.state == Cursor.CLOSED || this.s.state == Cursor.OPEN || this.isDead()) throw MongoError.create({message: "Cursor is closed", driver:true}); - this.s.cmd.maxTimeMS = value; - return this; -} - -define.classMethod('maxTimeMS', {callback: false, promise:false, returns: [Cursor]}); - -Cursor.prototype.maxTimeMs = Cursor.prototype.maxTimeMS; - -define.classMethod('maxTimeMs', {callback: false, promise:false, returns: [Cursor]}); - -/** - * Sets a field projection for the query. - * @method - * @param {object} value The field projection object. - * @throws {MongoError} - * @return {Cursor} - */ -Cursor.prototype.project = function(value) { - if(this.s.state == Cursor.CLOSED || this.s.state == Cursor.OPEN || this.isDead()) throw MongoError.create({message: "Cursor is closed", driver:true}); - this.s.cmd.fields = value; - return this; -} - -define.classMethod('project', {callback: false, promise:false, returns: [Cursor]}); - -/** - * Sets the sort order of the cursor query. - * @method - * @param {(string|array|object)} keyOrList The key or keys set for the sort. - * @param {number} [direction] The direction of the sorting (1 or -1). - * @throws {MongoError} - * @return {Cursor} - */ -Cursor.prototype.sort = function(keyOrList, direction) { - if(this.s.options.tailable) throw MongoError.create({message: "Tailable cursor doesn't support sorting", driver:true}); - if(this.s.state == Cursor.CLOSED || this.s.state == Cursor.OPEN || this.isDead()) throw MongoError.create({message: "Cursor is closed", driver:true}); - var order = keyOrList; - - // We have an array of arrays, we need to preserve the order of the sort - // so we will us a Map - if(Array.isArray(order) && Array.isArray(order[0])) { - order = new Map(order.map(function(x) { - var value = [x[0], null]; - if(x[1] == 'asc') { - value[1] = 1; - } else if(x[1] == 'desc') { - value[1] = -1; - } else if(x[1] == 1 || x[1] == -1) { - value[1] = x[1]; - } else { - throw new MongoError("Illegal sort clause, must be of the form [['field1', '(ascending|descending)'], ['field2', '(ascending|descending)']]"); - } - - return value; - })); - } - - if(direction != null) { - order = [[keyOrList, direction]]; - } - - this.s.cmd.sort = order; - this.sortValue = order; - return this; -} - -define.classMethod('sort', {callback: false, promise:false, returns: [Cursor]}); - -/** - * Set the batch size for the cursor. - * @method - * @param {number} value The batchSize for the cursor. - * @throws {MongoError} - * @return {Cursor} - */ -Cursor.prototype.batchSize = function(value) { - if(this.s.options.tailable) throw MongoError.create({message: "Tailable cursor doesn't support batchSize", driver:true}); - if(this.s.state == Cursor.CLOSED || this.isDead()) throw MongoError.create({message: "Cursor is closed", driver:true}); - if(typeof value != 'number') throw MongoError.create({message: "batchSize requires an integer", driver:true}); - this.s.cmd.batchSize = value; - this.setCursorBatchSize(value); - return this; -} - -define.classMethod('batchSize', {callback: false, promise:false, returns: [Cursor]}); - -/** - * Set the collation options for the cursor. - * @method - * @param {object} value The cursor collation options (MongoDB 3.4 or higher) settings for update operation (see 3.4 documentation for available fields). - * @throws {MongoError} - * @return {Cursor} - */ -Cursor.prototype.collation = function(value) { - this.s.cmd.collation = value; - return this; -} - -define.classMethod('collation', {callback: false, promise:false, returns: [Cursor]}); - -/** - * Set the limit for the cursor. - * @method - * @param {number} value The limit for the cursor query. - * @throws {MongoError} - * @return {Cursor} - */ -Cursor.prototype.limit = function(value) { - if(this.s.options.tailable) throw MongoError.create({message: "Tailable cursor doesn't support limit", driver:true}); - if(this.s.state == Cursor.OPEN || this.s.state == Cursor.CLOSED || this.isDead()) throw MongoError.create({message: "Cursor is closed", driver:true}); - if(typeof value != 'number') throw MongoError.create({message: "limit requires an integer", driver:true}); - this.s.cmd.limit = value; - // this.cursorLimit = value; - this.setCursorLimit(value); - return this; -} - -define.classMethod('limit', {callback: false, promise:false, returns: [Cursor]}); - -/** - * Set the skip for the cursor. - * @method - * @param {number} value The skip for the cursor query. - * @throws {MongoError} - * @return {Cursor} - */ -Cursor.prototype.skip = function(value) { - if(this.s.options.tailable) throw MongoError.create({message: "Tailable cursor doesn't support skip", driver:true}); - if(this.s.state == Cursor.OPEN || this.s.state == Cursor.CLOSED || this.isDead()) throw MongoError.create({message: "Cursor is closed", driver:true}); - if(typeof value != 'number') throw MongoError.create({message: "skip requires an integer", driver:true}); - this.s.cmd.skip = value; - this.setCursorSkip(value); - return this; -} - -define.classMethod('skip', {callback: false, promise:false, returns: [Cursor]}); - -/** - * The callback format for results - * @callback Cursor~resultCallback - * @param {MongoError} error An error instance representing the error during the execution. - * @param {(object|null|boolean)} result The result object if the command was executed successfully. - */ - -/** - * Clone the cursor - * @function external:CoreCursor#clone - * @return {Cursor} - */ - -/** - * Resets the cursor - * @function external:CoreCursor#rewind - * @return {null} - */ - -/** - * Get the next available document from the cursor, returns null if no more documents are available. - * @method - * @param {Cursor~resultCallback} [callback] The result callback. - * @throws {MongoError} - * @deprecated - * @return {Promise} returns Promise if no callback passed - */ -Cursor.prototype.nextObject = Cursor.prototype.next; - -var nextObject = function(self, callback) { - if(self.s.state == Cursor.CLOSED || self.isDead && self.isDead()) return handleCallback(callback, MongoError.create({message: "Cursor is closed", driver:true})); - if(self.s.state == Cursor.INIT && self.s.cmd.sort) { - try { - self.s.cmd.sort = formattedOrderClause(self.s.cmd.sort); - } catch(err) { - return handleCallback(callback, err); - } - } - - // Get the next object - self._next(function(err, doc) { - self.s.state = Cursor.OPEN; - if(err) return handleCallback(callback, err); - handleCallback(callback, null, doc); - }); -} - -define.classMethod('nextObject', {callback: true, promise:true}); - -// Trampoline emptying the number of retrieved items -// without incurring a nextTick operation -var loop = function(self, callback) { - // No more items we are done - if(self.bufferedCount() == 0) return; - // Get the next document - self._next(callback); - // Loop - return loop; -} - -Cursor.prototype.next = Cursor.prototype.nextObject; - -define.classMethod('next', {callback: true, promise:true}); - -/** - * Iterates over all the documents for this cursor. As with **{cursor.toArray}**, - * not all of the elements will be iterated if this cursor had been previously accessed. - * In that case, **{cursor.rewind}** can be used to reset the cursor. However, unlike - * **{cursor.toArray}**, the cursor will only hold a maximum of batch size elements - * at any given time if batch size is specified. Otherwise, the caller is responsible - * for making sure that the entire result can fit the memory. - * @method - * @deprecated - * @param {Cursor~resultCallback} callback The result callback. - * @throws {MongoError} - * @return {null} - */ -Cursor.prototype.each = function(callback) { - // Rewind cursor state - this.rewind(); - // Set current cursor to INIT - this.s.state = Cursor.INIT; - // Run the query - _each(this, callback); -}; - -define.classMethod('each', {callback: true, promise:false}); - -// Run the each loop -var _each = function(self, callback) { - if(!callback) throw MongoError.create({message: 'callback is mandatory', driver:true}); - if(self.isNotified()) return; - if(self.s.state == Cursor.CLOSED || self.isDead()) { - return handleCallback(callback, MongoError.create({message: "Cursor is closed", driver:true})); - } - - if(self.s.state == Cursor.INIT) self.s.state = Cursor.OPEN; - - // Define function to avoid global scope escape - var fn = null; - // Trampoline all the entries - if(self.bufferedCount() > 0) { - while(fn = loop(self, callback)) fn(self, callback); - _each(self, callback); - } else { - self.next(function(err, item) { - if(err) return handleCallback(callback, err); - if(item == null) { - self.s.state = Cursor.CLOSED; - return handleCallback(callback, null, null); - } - - if(handleCallback(callback, null, item) == false) return; - _each(self, callback); - }) - } -} - -/** - * The callback format for the forEach iterator method - * @callback Cursor~iteratorCallback - * @param {Object} doc An emitted document for the iterator - */ - -/** - * The callback error format for the forEach iterator method - * @callback Cursor~endCallback - * @param {MongoError} error An error instance representing the error during the execution. - */ - -/** - * Iterates over all the documents for this cursor using the iterator, callback pattern. - * @method - * @param {Cursor~iteratorCallback} iterator The iteration callback. - * @param {Cursor~endCallback} callback The end callback. - * @throws {MongoError} - * @return {null} - */ -Cursor.prototype.forEach = function(iterator, callback) { - this.each(function(err, doc){ - if(err) { callback(err); return false; } - if(doc != null) { iterator(doc); return true; } - if(doc == null && callback) { - var internalCallback = callback; - callback = null; - internalCallback(null); - return false; - } - }); -} - -define.classMethod('forEach', {callback: true, promise:false}); - -/** - * Set the ReadPreference for the cursor. - * @method - * @param {(string|ReadPreference)} readPreference The new read preference for the cursor. - * @throws {MongoError} - * @return {Cursor} - */ -Cursor.prototype.setReadPreference = function(r) { - if(this.s.state != Cursor.INIT) throw MongoError.create({message: 'cannot change cursor readPreference after cursor has been accessed', driver:true}); - if(r instanceof ReadPreference) { - this.s.options.readPreference = new CoreReadPreference(r.mode, r.tags, {maxStalenessSeconds: r.maxStalenessSeconds}); - } else if(typeof r == 'string'){ - this.s.options.readPreference = new CoreReadPreference(r); - } else if(r instanceof CoreReadPreference) { - this.s.options.readPreference = r; - } - - return this; -} - -define.classMethod('setReadPreference', {callback: false, promise:false, returns: [Cursor]}); - -/** - * The callback format for results - * @callback Cursor~toArrayResultCallback - * @param {MongoError} error An error instance representing the error during the execution. - * @param {object[]} documents All the documents the satisfy the cursor. - */ - -/** - * Returns an array of documents. The caller is responsible for making sure that there - * is enough memory to store the results. Note that the array only contain partial - * results when this cursor had been previously accessed. In that case, - * cursor.rewind() can be used to reset the cursor. - * @method - * @param {Cursor~toArrayResultCallback} [callback] The result callback. - * @throws {MongoError} - * @return {Promise} returns Promise if no callback passed - */ -Cursor.prototype.toArray = function(callback) { - var self = this; - if(self.s.options.tailable) throw MongoError.create({message: 'Tailable cursor cannot be converted to array', driver:true}); - - // Execute using callback - if(typeof callback == 'function') return toArray(self, callback); - - // Return a Promise - return new this.s.promiseLibrary(function(resolve, reject) { - toArray(self, function(err, r) { - if(err) return reject(err); - resolve(r); - }); - }); -} - -var toArray = function(self, callback) { - var items = []; - - // Reset cursor - self.rewind(); - self.s.state = Cursor.INIT; - - // Fetch all the documents - var fetchDocs = function() { - self._next(function(err, doc) { - if(err) return handleCallback(callback, err); - if(doc == null) { - self.s.state = Cursor.CLOSED; - return handleCallback(callback, null, items); - } - - // Add doc to items - items.push(doc) - - // Get all buffered objects - if(self.bufferedCount() > 0) { - var docs = self.readBufferedDocuments(self.bufferedCount()) - - // Transform the doc if transform method added - if(self.s.transforms && typeof self.s.transforms.doc == 'function') { - docs = docs.map(self.s.transforms.doc); - } - - push.apply(items, docs); - } - - // Attempt a fetch - fetchDocs(); - }) - } - - fetchDocs(); -} - -define.classMethod('toArray', {callback: true, promise:true}); - -/** - * The callback format for results - * @callback Cursor~countResultCallback - * @param {MongoError} error An error instance representing the error during the execution. - * @param {number} count The count of documents. - */ - -/** - * Get the count of documents for this cursor - * @method - * @param {boolean} [applySkipLimit=true] Should the count command apply limit and skip settings on the cursor or in the passed in options. - * @param {object} [options=null] Optional settings. - * @param {number} [options.skip=null] The number of documents to skip. - * @param {number} [options.limit=null] The maximum amounts to count before aborting. - * @param {number} [options.maxTimeMS=null] Number of milliseconds to wait before aborting the query. - * @param {string} [options.hint=null] An index name hint for the query. - * @param {(ReadPreference|string)} [options.readPreference=null] The preferred read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST). - * @param {Cursor~countResultCallback} [callback] The result callback. - * @return {Promise} returns Promise if no callback passed - */ -Cursor.prototype.count = function(applySkipLimit, opts, callback) { - var self = this; - if(self.s.cmd.query == null) throw MongoError.create({message: "count can only be used with find command", driver:true}); - if(typeof opts == 'function') callback = opts, opts = {}; - opts = opts || {}; - - // Execute using callback - if(typeof callback == 'function') return count(self, applySkipLimit, opts, callback); - - // Return a Promise - return new this.s.promiseLibrary(function(resolve, reject) { - count(self, applySkipLimit, opts, function(err, r) { - if(err) return reject(err); - resolve(r); - }); - }); -}; - -var count = function(self, applySkipLimit, opts, callback) { - if(typeof applySkipLimit == 'function') { - callback = applySkipLimit; - applySkipLimit = true; - } - - if(applySkipLimit) { - if(typeof self.cursorSkip() == 'number') opts.skip = self.cursorSkip(); - if(typeof self.cursorLimit() == 'number') opts.limit = self.cursorLimit(); - } - - // Command - var delimiter = self.s.ns.indexOf('.'); - - var command = { - 'count': self.s.ns.substr(delimiter+1), 'query': self.s.cmd.query - } - - // Apply a readConcern if set - if(self.s.cmd.readConcern) { - command.readConcern = self.s.cmd.readConcern; - } - - // Apply a hint if set - if(self.s.cmd.hint) { - command.hint = self.s.cmd.hint; - } - - if(typeof opts.maxTimeMS == 'number') { - command.maxTimeMS = opts.maxTimeMS; - } else if(self.s.cmd && typeof self.s.cmd.maxTimeMS == 'number') { - command.maxTimeMS = self.s.cmd.maxTimeMS; - } - - // Merge in any options - if(opts.skip) command.skip = opts.skip; - if(opts.limit) command.limit = opts.limit; - if(self.s.options.hint) command.hint = self.s.options.hint; - - // Set cursor server to the same as the topology - self.server = self.topology; - - // Execute the command - self.topology.command(f("%s.$cmd", self.s.ns.substr(0, delimiter)) - , command, function(err, result) { - callback(err, result ? result.result.n : null) - }, self.options); -} - -define.classMethod('count', {callback: true, promise:true}); - -/** - * Close the cursor, sending a KillCursor command and emitting close. - * @method - * @param {Cursor~resultCallback} [callback] The result callback. - * @return {Promise} returns Promise if no callback passed - */ -Cursor.prototype.close = function(callback) { - this.s.state = Cursor.CLOSED; - // Kill the cursor - this.kill(); - // Emit the close event for the cursor - this.emit('close'); - // Callback if provided - if(typeof callback == 'function') return handleCallback(callback, null, this); - // Return a Promise - return new this.s.promiseLibrary(function(resolve) { - resolve(); - }); -} - -define.classMethod('close', {callback: true, promise:true}); - -/** - * Map all documents using the provided function - * @method - * @param {function} [transform] The mapping transformation method. - * @return {Cursor} - */ -Cursor.prototype.map = function(transform) { - if(this.cursorState.transforms && this.cursorState.transforms.doc) { - var oldTransform = this.cursorState.transforms.doc; - this.cursorState.transforms.doc = function (doc) { return transform(oldTransform(doc)); }; - } else { - this.cursorState.transforms = { doc: transform }; - } - return this; -} - -define.classMethod('map', {callback: false, promise:false, returns: [Cursor]}); - -/** - * Is the cursor closed - * @method - * @return {boolean} - */ -Cursor.prototype.isClosed = function() { - return this.isDead(); -} - -define.classMethod('isClosed', {callback: false, promise:false, returns: [Boolean]}); - -Cursor.prototype.destroy = function(err) { - if(err) this.emit('error', err); - this.pause(); - this.close(); -} - -define.classMethod('destroy', {callback: false, promise:false}); - -/** - * Return a modified Readable stream including a possible transform method. - * @method - * @param {object} [options=null] Optional settings. - * @param {function} [options.transform=null] A transformation method applied to each document emitted by the stream. - * @return {Cursor} - */ -Cursor.prototype.stream = function(options) { - this.s.streamOptions = options || {}; - return this; -} - -define.classMethod('stream', {callback: false, promise:false, returns: [Cursor]}); - -/** - * Execute the explain for the cursor - * @method - * @param {Cursor~resultCallback} [callback] The result callback. - * @return {Promise} returns Promise if no callback passed - */ -Cursor.prototype.explain = function(callback) { - var self = this; - this.s.cmd.explain = true; - - // Do we have a readConcern - if(this.s.cmd.readConcern) { - delete this.s.cmd['readConcern']; - } - - // Execute using callback - if(typeof callback == 'function') return this._next(callback); - - // Return a Promise - return new this.s.promiseLibrary(function(resolve, reject) { - self._next(function(err, r) { - if(err) return reject(err); - resolve(r); - }); - }); -} - -define.classMethod('explain', {callback: true, promise:true}); - -Cursor.prototype._read = function() { - var self = this; - if(self.s.state == Cursor.CLOSED || self.isDead()) { - return self.push(null); - } - - // Get the next item - self.nextObject(function(err, result) { - if(err) { - if(self.listeners('error') && self.listeners('error').length > 0) { - self.emit('error', err); - } - if(!self.isDead()) self.close(); - - // Emit end event - self.emit('end'); - return self.emit('finish'); - } - - // If we provided a transformation method - if(typeof self.s.streamOptions.transform == 'function' && result != null) { - return self.push(self.s.streamOptions.transform(result)); - } - - // If we provided a map function - if(self.cursorState.transforms && typeof self.cursorState.transforms.doc == 'function' && result != null) { - return self.push(self.cursorState.transforms.doc(result)); - } - - // Return the result - self.push(result); - }); -} - -Object.defineProperty(Cursor.prototype, 'readPreference', { - enumerable:true, - get: function() { - if (!this || !this.s) { - return null; - } - - return this.s.options.readPreference; - } -}); - -Object.defineProperty(Cursor.prototype, 'namespace', { - enumerable: true, - get: function() { - if (!this || !this.s) { - return null; - } - - // TODO: refactor this logic into core - var ns = this.s.ns || ''; - var firstDot = ns.indexOf('.'); - if (firstDot < 0) { - return { - database: this.s.ns, - collection: '' - }; - } - return { - database: ns.substr(0, firstDot), - collection: ns.substr(firstDot + 1) - }; - } -}); - -/** - * The read() method pulls some data out of the internal buffer and returns it. If there is no data available, then it will return null. - * @function external:Readable#read - * @param {number} size Optional argument to specify how much data to read. - * @return {(String | Buffer | null)} - */ - -/** - * Call this function to cause the stream to return strings of the specified encoding instead of Buffer objects. - * @function external:Readable#setEncoding - * @param {string} encoding The encoding to use. - * @return {null} - */ - -/** - * This method will cause the readable stream to resume emitting data events. - * @function external:Readable#resume - * @return {null} - */ - -/** - * This method will cause a stream in flowing-mode to stop emitting data events. Any data that becomes available will remain in the internal buffer. - * @function external:Readable#pause - * @return {null} - */ - -/** - * This method pulls all the data out of a readable stream, and writes it to the supplied destination, automatically managing the flow so that the destination is not overwhelmed by a fast readable stream. - * @function external:Readable#pipe - * @param {Writable} destination The destination for writing data - * @param {object} [options] Pipe options - * @return {null} - */ - -/** - * This method will remove the hooks set up for a previous pipe() call. - * @function external:Readable#unpipe - * @param {Writable} [destination] The destination for writing data - * @return {null} - */ - -/** - * This is useful in certain cases where a stream is being consumed by a parser, which needs to "un-consume" some data that it has optimistically pulled out of the source, so that the stream can be passed on to some other party. - * @function external:Readable#unshift - * @param {(Buffer|string)} chunk Chunk of data to unshift onto the read queue. - * @return {null} - */ - -/** - * Versions of Node prior to v0.10 had streams that did not implement the entire Streams API as it is today. (See "Compatibility" below for more information.) - * @function external:Readable#wrap - * @param {Stream} stream An "old style" readable stream. - * @return {null} - */ - -Cursor.INIT = 0; -Cursor.OPEN = 1; -Cursor.CLOSED = 2; -Cursor.GET_MORE = 3; - -module.exports = Cursor; diff --git a/ts-ticket-office-service/node_modules/mongodb/lib/cursor/abstract_cursor.js b/ts-ticket-office-service/node_modules/mongodb/lib/cursor/abstract_cursor.js new file mode 100644 index 000000000..c9a6dbe23 --- /dev/null +++ b/ts-ticket-office-service/node_modules/mongodb/lib/cursor/abstract_cursor.js @@ -0,0 +1,652 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.assertUninitialized = exports.next = exports.AbstractCursor = exports.CURSOR_FLAGS = void 0; +const stream_1 = require("stream"); +const bson_1 = require("../bson"); +const error_1 = require("../error"); +const mongo_types_1 = require("../mongo_types"); +const execute_operation_1 = require("../operations/execute_operation"); +const get_more_1 = require("../operations/get_more"); +const kill_cursors_1 = require("../operations/kill_cursors"); +const read_concern_1 = require("../read_concern"); +const read_preference_1 = require("../read_preference"); +const sessions_1 = require("../sessions"); +const utils_1 = require("../utils"); +/** @internal */ +const kId = Symbol('id'); +/** @internal */ +const kDocuments = Symbol('documents'); +/** @internal */ +const kServer = Symbol('server'); +/** @internal */ +const kNamespace = Symbol('namespace'); +/** @internal */ +const kClient = Symbol('client'); +/** @internal */ +const kSession = Symbol('session'); +/** @internal */ +const kOptions = Symbol('options'); +/** @internal */ +const kTransform = Symbol('transform'); +/** @internal */ +const kInitialized = Symbol('initialized'); +/** @internal */ +const kClosed = Symbol('closed'); +/** @internal */ +const kKilled = Symbol('killed'); +/** @internal */ +const kInit = Symbol('kInit'); +/** @public */ +exports.CURSOR_FLAGS = [ + 'tailable', + 'oplogReplay', + 'noCursorTimeout', + 'awaitData', + 'exhaust', + 'partial' +]; +/** @public */ +class AbstractCursor extends mongo_types_1.TypedEventEmitter { + /** @internal */ + constructor(client, namespace, options = {}) { + super(); + if (!client.s.isMongoClient) { + throw new error_1.MongoRuntimeError('Cursor must be constructed with MongoClient'); + } + this[kClient] = client; + this[kNamespace] = namespace; + this[kDocuments] = []; // TODO: https://github.com/microsoft/TypeScript/issues/36230 + this[kInitialized] = false; + this[kClosed] = false; + this[kKilled] = false; + this[kOptions] = { + readPreference: options.readPreference && options.readPreference instanceof read_preference_1.ReadPreference + ? options.readPreference + : read_preference_1.ReadPreference.primary, + ...(0, bson_1.pluckBSONSerializeOptions)(options) + }; + const readConcern = read_concern_1.ReadConcern.fromOptions(options); + if (readConcern) { + this[kOptions].readConcern = readConcern; + } + if (typeof options.batchSize === 'number') { + this[kOptions].batchSize = options.batchSize; + } + // we check for undefined specifically here to allow falsy values + // eslint-disable-next-line no-restricted-syntax + if (options.comment !== undefined) { + this[kOptions].comment = options.comment; + } + if (typeof options.maxTimeMS === 'number') { + this[kOptions].maxTimeMS = options.maxTimeMS; + } + if (options.session instanceof sessions_1.ClientSession) { + this[kSession] = options.session; + } + else { + this[kSession] = this[kClient].startSession({ owner: this, explicit: false }); + } + } + get id() { + return this[kId]; + } + /** @internal */ + get client() { + return this[kClient]; + } + /** @internal */ + get server() { + return this[kServer]; + } + get namespace() { + return this[kNamespace]; + } + get readPreference() { + return this[kOptions].readPreference; + } + get readConcern() { + return this[kOptions].readConcern; + } + /** @internal */ + get session() { + return this[kSession]; + } + set session(clientSession) { + this[kSession] = clientSession; + } + /** @internal */ + get cursorOptions() { + return this[kOptions]; + } + get closed() { + return this[kClosed]; + } + get killed() { + return this[kKilled]; + } + get loadBalanced() { + var _a; + return !!((_a = this[kClient].topology) === null || _a === void 0 ? void 0 : _a.loadBalanced); + } + /** Returns current buffered documents length */ + bufferedCount() { + return this[kDocuments].length; + } + /** Returns current buffered documents */ + readBufferedDocuments(number) { + return this[kDocuments].splice(0, number !== null && number !== void 0 ? number : this[kDocuments].length); + } + [Symbol.asyncIterator]() { + return { + next: () => this.next().then(value => value != null ? { value, done: false } : { value: undefined, done: true }) + }; + } + stream(options) { + if (options === null || options === void 0 ? void 0 : options.transform) { + const transform = options.transform; + const readable = new ReadableCursorStream(this); + return readable.pipe(new stream_1.Transform({ + objectMode: true, + highWaterMark: 1, + transform(chunk, _, callback) { + try { + const transformed = transform(chunk); + callback(undefined, transformed); + } + catch (err) { + callback(err); + } + } + })); + } + return new ReadableCursorStream(this); + } + hasNext(callback) { + return (0, utils_1.maybePromise)(callback, done => { + if (this[kId] === bson_1.Long.ZERO) { + return done(undefined, false); + } + if (this[kDocuments].length) { + return done(undefined, true); + } + next(this, true, (err, doc) => { + if (err) + return done(err); + if (doc) { + this[kDocuments].unshift(doc); + done(undefined, true); + return; + } + done(undefined, false); + }); + }); + } + next(callback) { + return (0, utils_1.maybePromise)(callback, done => { + if (this[kId] === bson_1.Long.ZERO) { + return done(new error_1.MongoCursorExhaustedError()); + } + next(this, true, done); + }); + } + tryNext(callback) { + return (0, utils_1.maybePromise)(callback, done => { + if (this[kId] === bson_1.Long.ZERO) { + return done(new error_1.MongoCursorExhaustedError()); + } + next(this, false, done); + }); + } + forEach(iterator, callback) { + if (typeof iterator !== 'function') { + throw new error_1.MongoInvalidArgumentError('Argument "iterator" must be a function'); + } + return (0, utils_1.maybePromise)(callback, done => { + const transform = this[kTransform]; + const fetchDocs = () => { + next(this, true, (err, doc) => { + if (err || doc == null) + return done(err); + let result; + // NOTE: no need to transform because `next` will do this automatically + try { + result = iterator(doc); // TODO(NODE-3283): Improve transform typing + } + catch (error) { + return done(error); + } + if (result === false) + return done(); + // these do need to be transformed since they are copying the rest of the batch + const internalDocs = this[kDocuments].splice(0, this[kDocuments].length); + for (let i = 0; i < internalDocs.length; ++i) { + try { + result = iterator((transform ? transform(internalDocs[i]) : internalDocs[i]) // TODO(NODE-3283): Improve transform typing + ); + } + catch (error) { + return done(error); + } + if (result === false) + return done(); + } + fetchDocs(); + }); + }; + fetchDocs(); + }); + } + close(options, callback) { + if (typeof options === 'function') + (callback = options), (options = {}); + options = options !== null && options !== void 0 ? options : {}; + const needsToEmitClosed = !this[kClosed]; + this[kClosed] = true; + return (0, utils_1.maybePromise)(callback, done => cleanupCursor(this, { needsToEmitClosed }, done)); + } + toArray(callback) { + return (0, utils_1.maybePromise)(callback, done => { + const docs = []; + const transform = this[kTransform]; + const fetchDocs = () => { + // NOTE: if we add a `nextBatch` then we should use it here + next(this, true, (err, doc) => { + if (err) + return done(err); + if (doc == null) + return done(undefined, docs); + // NOTE: no need to transform because `next` will do this automatically + docs.push(doc); + // these do need to be transformed since they are copying the rest of the batch + const internalDocs = (transform + ? this[kDocuments].splice(0, this[kDocuments].length).map(transform) + : this[kDocuments].splice(0, this[kDocuments].length)); // TODO(NODE-3283): Improve transform typing + if (internalDocs) { + docs.push(...internalDocs); + } + fetchDocs(); + }); + }; + fetchDocs(); + }); + } + /** + * Add a cursor flag to the cursor + * + * @param flag - The flag to set, must be one of following ['tailable', 'oplogReplay', 'noCursorTimeout', 'awaitData', 'partial' -. + * @param value - The flag boolean value. + */ + addCursorFlag(flag, value) { + assertUninitialized(this); + if (!exports.CURSOR_FLAGS.includes(flag)) { + throw new error_1.MongoInvalidArgumentError(`Flag ${flag} is not one of ${exports.CURSOR_FLAGS}`); + } + if (typeof value !== 'boolean') { + throw new error_1.MongoInvalidArgumentError(`Flag ${flag} must be a boolean value`); + } + this[kOptions][flag] = value; + return this; + } + /** + * Map all documents using the provided function + * If there is a transform set on the cursor, that will be called first and the result passed to + * this function's transform. + * + * @remarks + * **Note for Typescript Users:** adding a transform changes the return type of the iteration of this cursor, + * it **does not** return a new instance of a cursor. This means when calling map, + * you should always assign the result to a new variable in order to get a correctly typed cursor variable. + * Take note of the following example: + * + * @example + * ```typescript + * const cursor: FindCursor = coll.find(); + * const mappedCursor: FindCursor = cursor.map(doc => Object.keys(doc).length); + * const keyCounts: number[] = await mappedCursor.toArray(); // cursor.toArray() still returns Document[] + * ``` + * @param transform - The mapping transformation method. + */ + map(transform) { + assertUninitialized(this); + const oldTransform = this[kTransform]; // TODO(NODE-3283): Improve transform typing + if (oldTransform) { + this[kTransform] = doc => { + return transform(oldTransform(doc)); + }; + } + else { + this[kTransform] = transform; + } + return this; + } + /** + * Set the ReadPreference for the cursor. + * + * @param readPreference - The new read preference for the cursor. + */ + withReadPreference(readPreference) { + assertUninitialized(this); + if (readPreference instanceof read_preference_1.ReadPreference) { + this[kOptions].readPreference = readPreference; + } + else if (typeof readPreference === 'string') { + this[kOptions].readPreference = read_preference_1.ReadPreference.fromString(readPreference); + } + else { + throw new error_1.MongoInvalidArgumentError(`Invalid read preference: ${readPreference}`); + } + return this; + } + /** + * Set the ReadPreference for the cursor. + * + * @param readPreference - The new read preference for the cursor. + */ + withReadConcern(readConcern) { + assertUninitialized(this); + const resolvedReadConcern = read_concern_1.ReadConcern.fromOptions({ readConcern }); + if (resolvedReadConcern) { + this[kOptions].readConcern = resolvedReadConcern; + } + return this; + } + /** + * Set a maxTimeMS on the cursor query, allowing for hard timeout limits on queries (Only supported on MongoDB 2.6 or higher) + * + * @param value - Number of milliseconds to wait before aborting the query. + */ + maxTimeMS(value) { + assertUninitialized(this); + if (typeof value !== 'number') { + throw new error_1.MongoInvalidArgumentError('Argument for maxTimeMS must be a number'); + } + this[kOptions].maxTimeMS = value; + return this; + } + /** + * Set the batch size for the cursor. + * + * @param value - The number of documents to return per batch. See {@link https://docs.mongodb.com/manual/reference/command/find/|find command documentation}. + */ + batchSize(value) { + assertUninitialized(this); + if (this[kOptions].tailable) { + throw new error_1.MongoTailableCursorError('Tailable cursor does not support batchSize'); + } + if (typeof value !== 'number') { + throw new error_1.MongoInvalidArgumentError('Operation "batchSize" requires an integer'); + } + this[kOptions].batchSize = value; + return this; + } + /** + * Rewind this cursor to its uninitialized state. Any options that are present on the cursor will + * remain in effect. Iterating this cursor will cause new queries to be sent to the server, even + * if the resultant data has already been retrieved by this cursor. + */ + rewind() { + if (!this[kInitialized]) { + return; + } + this[kId] = undefined; + this[kDocuments] = []; + this[kClosed] = false; + this[kKilled] = false; + this[kInitialized] = false; + const session = this[kSession]; + if (session) { + // We only want to end this session if we created it, and it hasn't ended yet + if (session.explicit === false) { + if (!session.hasEnded) { + session.endSession().catch(() => null); + } + this[kSession] = this.client.startSession({ owner: this, explicit: false }); + } + } + } + /** @internal */ + _getMore(batchSize, callback) { + const cursorId = this[kId]; + const cursorNs = this[kNamespace]; + const server = this[kServer]; + if (cursorId == null) { + callback(new error_1.MongoRuntimeError('Unable to iterate cursor with no id')); + return; + } + if (server == null) { + callback(new error_1.MongoRuntimeError('Unable to iterate cursor without selected server')); + return; + } + const getMoreOperation = new get_more_1.GetMoreOperation(cursorNs, cursorId, server, { + ...this[kOptions], + session: this[kSession], + batchSize + }); + (0, execute_operation_1.executeOperation)(this[kClient], getMoreOperation, callback); + } + /** + * @internal + * + * This function is exposed for the unified test runner's createChangeStream + * operation. We cannot refactor to use the abstract _initialize method without + * a significant refactor. + */ + [kInit](callback) { + this._initialize(this[kSession], (err, state) => { + if (state) { + const response = state.response; + this[kServer] = state.server; + if (response.cursor) { + this[kId] = + typeof response.cursor.id === 'number' + ? bson_1.Long.fromNumber(response.cursor.id) + : response.cursor.id; + if (response.cursor.ns) { + this[kNamespace] = (0, utils_1.ns)(response.cursor.ns); + } + this[kDocuments] = response.cursor.firstBatch; + } + // When server responses return without a cursor document, we close this cursor + // and return the raw server response. This is often the case for explain commands + // for example + if (this[kId] == null) { + this[kId] = bson_1.Long.ZERO; + // TODO(NODE-3286): ExecutionResult needs to accept a generic parameter + this[kDocuments] = [state.response]; + } + } + // the cursor is now initialized, even if an error occurred or it is dead + this[kInitialized] = true; + if (err || cursorIsDead(this)) { + return cleanupCursor(this, { error: err }, () => callback(err, nextDocument(this))); + } + callback(); + }); + } +} +exports.AbstractCursor = AbstractCursor; +/** @event */ +AbstractCursor.CLOSE = 'close'; +function nextDocument(cursor) { + if (cursor[kDocuments] == null || !cursor[kDocuments].length) { + return null; + } + const doc = cursor[kDocuments].shift(); + if (doc) { + const transform = cursor[kTransform]; + if (transform) { + return transform(doc); + } + return doc; + } + return null; +} +/** + * @param cursor - the cursor on which to call `next` + * @param blocking - a boolean indicating whether or not the cursor should `block` until data + * is available. Generally, this flag is set to `false` because if the getMore returns no documents, + * the cursor has been exhausted. In certain scenarios (ChangeStreams, tailable await cursors and + * `tryNext`, for example) blocking is necessary because a getMore returning no documents does + * not indicate the end of the cursor. + * @param callback - callback to return the result to the caller + * @returns + */ +function next(cursor, blocking, callback) { + const cursorId = cursor[kId]; + if (cursor.closed) { + return callback(undefined, null); + } + if (cursor[kDocuments] && cursor[kDocuments].length) { + callback(undefined, nextDocument(cursor)); + return; + } + if (cursorId == null) { + // All cursors must operate within a session, one must be made implicitly if not explicitly provided + cursor[kInit]((err, value) => { + if (err) + return callback(err); + if (value) { + return callback(undefined, value); + } + return next(cursor, blocking, callback); + }); + return; + } + if (cursorIsDead(cursor)) { + return cleanupCursor(cursor, undefined, () => callback(undefined, null)); + } + // otherwise need to call getMore + const batchSize = cursor[kOptions].batchSize || 1000; + cursor._getMore(batchSize, (err, response) => { + if (response) { + const cursorId = typeof response.cursor.id === 'number' + ? bson_1.Long.fromNumber(response.cursor.id) + : response.cursor.id; + cursor[kDocuments] = response.cursor.nextBatch; + cursor[kId] = cursorId; + } + if (err || cursorIsDead(cursor)) { + return cleanupCursor(cursor, { error: err }, () => callback(err, nextDocument(cursor))); + } + if (cursor[kDocuments].length === 0 && blocking === false) { + return callback(undefined, null); + } + next(cursor, blocking, callback); + }); +} +exports.next = next; +function cursorIsDead(cursor) { + const cursorId = cursor[kId]; + return !!cursorId && cursorId.isZero(); +} +function cleanupCursor(cursor, options, callback) { + var _a; + const cursorId = cursor[kId]; + const cursorNs = cursor[kNamespace]; + const server = cursor[kServer]; + const session = cursor[kSession]; + const error = options === null || options === void 0 ? void 0 : options.error; + const needsToEmitClosed = (_a = options === null || options === void 0 ? void 0 : options.needsToEmitClosed) !== null && _a !== void 0 ? _a : cursor[kDocuments].length === 0; + if (error) { + if (cursor.loadBalanced && error instanceof error_1.MongoNetworkError) { + return completeCleanup(); + } + } + if (cursorId == null || server == null || cursorId.isZero() || cursorNs == null) { + if (needsToEmitClosed) { + cursor[kClosed] = true; + cursor[kId] = bson_1.Long.ZERO; + cursor.emit(AbstractCursor.CLOSE); + } + if (session) { + if (session.owner === cursor) { + return session.endSession({ error }, callback); + } + if (!session.inTransaction()) { + (0, sessions_1.maybeClearPinnedConnection)(session, { error }); + } + } + return callback(); + } + function completeCleanup() { + if (session) { + if (session.owner === cursor) { + return session.endSession({ error }, () => { + cursor.emit(AbstractCursor.CLOSE); + callback(); + }); + } + if (!session.inTransaction()) { + (0, sessions_1.maybeClearPinnedConnection)(session, { error }); + } + } + cursor.emit(AbstractCursor.CLOSE); + return callback(); + } + cursor[kKilled] = true; + return (0, execute_operation_1.executeOperation)(cursor[kClient], new kill_cursors_1.KillCursorsOperation(cursorId, cursorNs, server, { session }), completeCleanup); +} +/** @internal */ +function assertUninitialized(cursor) { + if (cursor[kInitialized]) { + throw new error_1.MongoCursorInUseError(); + } +} +exports.assertUninitialized = assertUninitialized; +class ReadableCursorStream extends stream_1.Readable { + constructor(cursor) { + super({ + objectMode: true, + autoDestroy: false, + highWaterMark: 1 + }); + this._readInProgress = false; + this._cursor = cursor; + } + // eslint-disable-next-line @typescript-eslint/no-unused-vars + _read(size) { + if (!this._readInProgress) { + this._readInProgress = true; + this._readNext(); + } + } + _destroy(error, callback) { + this._cursor.close(err => process.nextTick(callback, err || error)); + } + _readNext() { + next(this._cursor, true, (err, result) => { + if (err) { + // NOTE: This is questionable, but we have a test backing the behavior. It seems the + // desired behavior is that a stream ends cleanly when a user explicitly closes + // a client during iteration. Alternatively, we could do the "right" thing and + // propagate the error message by removing this special case. + if (err.message.match(/server is closed/)) { + this._cursor.close().catch(() => null); + return this.push(null); + } + // NOTE: This is also perhaps questionable. The rationale here is that these errors tend + // to be "operation interrupted", where a cursor has been closed but there is an + // active getMore in-flight. This used to check if the cursor was killed but once + // that changed to happen in cleanup legitimate errors would not destroy the + // stream. There are change streams test specifically test these cases. + if (err.message.match(/interrupted/)) { + return this.push(null); + } + return this.destroy(err); + } + if (result == null) { + this.push(null); + } + else if (this.destroyed) { + this._cursor.close().catch(() => null); + } + else { + if (this.push(result)) { + return this._readNext(); + } + this._readInProgress = false; + } + }); + } +} +//# sourceMappingURL=abstract_cursor.js.map \ No newline at end of file diff --git a/ts-ticket-office-service/node_modules/mongodb/lib/cursor/abstract_cursor.js.map b/ts-ticket-office-service/node_modules/mongodb/lib/cursor/abstract_cursor.js.map new file mode 100644 index 000000000..26cc068cd --- /dev/null +++ b/ts-ticket-office-service/node_modules/mongodb/lib/cursor/abstract_cursor.js.map @@ -0,0 +1 @@ +{"version":3,"file":"abstract_cursor.js","sourceRoot":"","sources":["../../src/cursor/abstract_cursor.ts"],"names":[],"mappings":";;;AAAA,mCAA6C;AAE7C,kCAA0F;AAC1F,oCAQkB;AAElB,gDAAmE;AACnE,uEAAoF;AACpF,qDAA0D;AAC1D,6DAAkE;AAClE,kDAA+D;AAC/D,wDAAwE;AAExE,0CAAwE;AACxE,oCAAwE;AAExE,gBAAgB;AAChB,MAAM,GAAG,GAAG,MAAM,CAAC,IAAI,CAAC,CAAC;AACzB,gBAAgB;AAChB,MAAM,UAAU,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 No newline at end of file diff --git a/ts-ticket-office-service/node_modules/mongodb/lib/cursor/aggregation_cursor.js b/ts-ticket-office-service/node_modules/mongodb/lib/cursor/aggregation_cursor.js new file mode 100644 index 000000000..ad77c58a0 --- /dev/null +++ b/ts-ticket-office-service/node_modules/mongodb/lib/cursor/aggregation_cursor.js @@ -0,0 +1,172 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.AggregationCursor = void 0; +const aggregate_1 = require("../operations/aggregate"); +const execute_operation_1 = require("../operations/execute_operation"); +const utils_1 = require("../utils"); +const abstract_cursor_1 = require("./abstract_cursor"); +/** @internal */ +const kPipeline = Symbol('pipeline'); +/** @internal */ +const kOptions = Symbol('options'); +/** + * The **AggregationCursor** class is an internal class that embodies an aggregation cursor on MongoDB + * allowing for iteration over the results returned from the underlying query. It supports + * one by one document iteration, conversion to an array or can be iterated as a Node 4.X + * or higher stream + * @public + */ +class AggregationCursor extends abstract_cursor_1.AbstractCursor { + /** @internal */ + constructor(client, namespace, pipeline = [], options = {}) { + super(client, namespace, options); + this[kPipeline] = pipeline; + this[kOptions] = options; + } + get pipeline() { + return this[kPipeline]; + } + clone() { + const clonedOptions = (0, utils_1.mergeOptions)({}, this[kOptions]); + delete clonedOptions.session; + return new AggregationCursor(this.client, this.namespace, this[kPipeline], { + ...clonedOptions + }); + } + map(transform) { + return super.map(transform); + } + /** @internal */ + _initialize(session, callback) { + const aggregateOperation = new aggregate_1.AggregateOperation(this.namespace, this[kPipeline], { + ...this[kOptions], + ...this.cursorOptions, + session + }); + (0, execute_operation_1.executeOperation)(this.client, aggregateOperation, (err, response) => { + if (err || response == null) + return callback(err); + // TODO: NODE-2882 + callback(undefined, { server: aggregateOperation.server, session, response }); + }); + } + explain(verbosity, callback) { + if (typeof verbosity === 'function') + (callback = verbosity), (verbosity = true); + if (verbosity == null) + verbosity = true; + return (0, execute_operation_1.executeOperation)(this.client, new aggregate_1.AggregateOperation(this.namespace, this[kPipeline], { + ...this[kOptions], + ...this.cursorOptions, + explain: verbosity + }), callback); + } + group($group) { + (0, abstract_cursor_1.assertUninitialized)(this); + this[kPipeline].push({ $group }); + return this; + } + /** Add a limit stage to the aggregation pipeline */ + limit($limit) { + (0, abstract_cursor_1.assertUninitialized)(this); + this[kPipeline].push({ $limit }); + return this; + } + /** Add a match stage to the aggregation pipeline */ + match($match) { + (0, abstract_cursor_1.assertUninitialized)(this); + this[kPipeline].push({ $match }); + return this; + } + /** Add an out stage to the aggregation pipeline */ + out($out) { + (0, abstract_cursor_1.assertUninitialized)(this); + this[kPipeline].push({ $out }); + return this; + } + /** + * Add a project stage to the aggregation pipeline + * + * @remarks + * In order to strictly type this function you must provide an interface + * that represents the effect of your projection on the result documents. + * + * By default chaining a projection to your cursor changes the returned type to the generic {@link Document} type. + * You should specify a parameterized type to have assertions on your final results. + * + * @example + * ```typescript + * // Best way + * const docs: AggregationCursor<{ a: number }> = cursor.project<{ a: number }>({ _id: 0, a: true }); + * // Flexible way + * const docs: AggregationCursor = cursor.project({ _id: 0, a: true }); + * ``` + * + * @remarks + * In order to strictly type this function you must provide an interface + * that represents the effect of your projection on the result documents. + * + * **Note for Typescript Users:** adding a transform changes the return type of the iteration of this cursor, + * it **does not** return a new instance of a cursor. This means when calling project, + * you should always assign the result to a new variable in order to get a correctly typed cursor variable. + * Take note of the following example: + * + * @example + * ```typescript + * const cursor: AggregationCursor<{ a: number; b: string }> = coll.aggregate([]); + * const projectCursor = cursor.project<{ a: number }>({ _id: 0, a: true }); + * const aPropOnlyArray: {a: number}[] = await projectCursor.toArray(); + * + * // or always use chaining and save the final cursor + * + * const cursor = coll.aggregate().project<{ a: string }>({ + * _id: 0, + * a: { $convert: { input: '$a', to: 'string' } + * }}); + * ``` + */ + project($project) { + (0, abstract_cursor_1.assertUninitialized)(this); + this[kPipeline].push({ $project }); + return this; + } + /** Add a lookup stage to the aggregation pipeline */ + lookup($lookup) { + (0, abstract_cursor_1.assertUninitialized)(this); + this[kPipeline].push({ $lookup }); + return this; + } + /** Add a redact stage to the aggregation pipeline */ + redact($redact) { + (0, abstract_cursor_1.assertUninitialized)(this); + this[kPipeline].push({ $redact }); + return this; + } + /** Add a skip stage to the aggregation pipeline */ + skip($skip) { + (0, abstract_cursor_1.assertUninitialized)(this); + this[kPipeline].push({ $skip }); + return this; + } + /** Add a sort stage to the aggregation pipeline */ + sort($sort) { + (0, abstract_cursor_1.assertUninitialized)(this); + this[kPipeline].push({ $sort }); + return this; + } + /** Add a unwind stage to the aggregation pipeline */ + unwind($unwind) { + (0, abstract_cursor_1.assertUninitialized)(this); + this[kPipeline].push({ $unwind }); + return this; + } + // deprecated methods + /** @deprecated Add a geoNear stage to the aggregation pipeline */ + geoNear($geoNear) { + (0, abstract_cursor_1.assertUninitialized)(this); + this[kPipeline].push({ $geoNear }); + return this; + } +} +exports.AggregationCursor = AggregationCursor; +//# sourceMappingURL=aggregation_cursor.js.map \ No newline at end of file diff --git a/ts-ticket-office-service/node_modules/mongodb/lib/cursor/aggregation_cursor.js.map b/ts-ticket-office-service/node_modules/mongodb/lib/cursor/aggregation_cursor.js.map new file mode 100644 index 000000000..ed6d31ea0 --- /dev/null +++ b/ts-ticket-office-service/node_modules/mongodb/lib/cursor/aggregation_cursor.js.map @@ -0,0 +1 @@ +{"version":3,"file":"aggregation_cursor.js","sourceRoot":"","sources":["../../src/cursor/aggregation_cursor.ts"],"names":[],"mappings":";;;AAGA,uDAA+E;AAC/E,uEAAoF;AAIpF,oCAAwC;AAExC,uDAAwE;AAKxE,gBAAgB;AAChB,MAAM,SAAS,GAAG,MAAM,CAAC,UAAU,CAAC,CAAC;AACrC,gBAAgB;AAChB,MAAM,QAAQ,GAAG,MAAM,CAAC,SAAS,CAAC,CAAC;AAEnC;;;;;;GAMG;AACH,MAAa,iBAAiC,SAAQ,gCAAuB;IAM3E,gBAAgB;IAChB,YACE,MAAmB,EACnB,SAA2B,EAC3B,WAAuB,EAAE,EACzB,UAA4B,EAAE;QAE9B,KAAK,CAAC,MAAM,E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,CAAC;IAED,qBAAqB;IACrB,kEAAkE;IAClE,OAAO,CAAC,QAAkB;QACxB,IAAA,qCAAmB,EAAC,IAAI,CAAC,CAAC;QAC1B,IAAI,CAAC,SAAS,CAAC,CAAC,IAAI,CAAC,EAAE,QAAQ,EAAE,CAAC,CAAC;QACnC,OAAO,IAAI,CAAC;IACd,CAAC;CACF;AA/LD,8CA+LC"} \ No newline at end of file diff --git a/ts-ticket-office-service/node_modules/mongodb/lib/cursor/change_stream_cursor.js b/ts-ticket-office-service/node_modules/mongodb/lib/cursor/change_stream_cursor.js new file mode 100644 index 000000000..471fb6cd3 --- /dev/null +++ b/ts-ticket-office-service/node_modules/mongodb/lib/cursor/change_stream_cursor.js @@ -0,0 +1,115 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.ChangeStreamCursor = void 0; +const change_stream_1 = require("../change_stream"); +const constants_1 = require("../constants"); +const aggregate_1 = require("../operations/aggregate"); +const execute_operation_1 = require("../operations/execute_operation"); +const utils_1 = require("../utils"); +const abstract_cursor_1 = require("./abstract_cursor"); +/** @internal */ +class ChangeStreamCursor extends abstract_cursor_1.AbstractCursor { + constructor(client, namespace, pipeline = [], options = {}) { + super(client, namespace, options); + this.pipeline = pipeline; + this.options = options; + this._resumeToken = null; + this.startAtOperationTime = options.startAtOperationTime; + if (options.startAfter) { + this.resumeToken = options.startAfter; + } + else if (options.resumeAfter) { + this.resumeToken = options.resumeAfter; + } + } + set resumeToken(token) { + this._resumeToken = token; + this.emit(change_stream_1.ChangeStream.RESUME_TOKEN_CHANGED, token); + } + get resumeToken() { + return this._resumeToken; + } + get resumeOptions() { + const options = { + ...this.options + }; + for (const key of ['resumeAfter', 'startAfter', 'startAtOperationTime']) { + delete options[key]; + } + if (this.resumeToken != null) { + if (this.options.startAfter && !this.hasReceived) { + options.startAfter = this.resumeToken; + } + else { + options.resumeAfter = this.resumeToken; + } + } + else if (this.startAtOperationTime != null && (0, utils_1.maxWireVersion)(this.server) >= 7) { + options.startAtOperationTime = this.startAtOperationTime; + } + return options; + } + cacheResumeToken(resumeToken) { + if (this.bufferedCount() === 0 && this.postBatchResumeToken) { + this.resumeToken = this.postBatchResumeToken; + } + else { + this.resumeToken = resumeToken; + } + this.hasReceived = true; + } + _processBatch(response) { + const cursor = response.cursor; + if (cursor.postBatchResumeToken) { + this.postBatchResumeToken = response.cursor.postBatchResumeToken; + const batch = 'firstBatch' in response.cursor ? response.cursor.firstBatch : response.cursor.nextBatch; + if (batch.length === 0) { + this.resumeToken = cursor.postBatchResumeToken; + } + } + } + clone() { + return new ChangeStreamCursor(this.client, this.namespace, this.pipeline, { + ...this.cursorOptions + }); + } + _initialize(session, callback) { + const aggregateOperation = new aggregate_1.AggregateOperation(this.namespace, this.pipeline, { + ...this.cursorOptions, + ...this.options, + session + }); + (0, execute_operation_1.executeOperation)(session.client, aggregateOperation, (err, response) => { + if (err || response == null) { + return callback(err); + } + const server = aggregateOperation.server; + this.maxWireVersion = (0, utils_1.maxWireVersion)(server); + if (this.startAtOperationTime == null && + this.resumeAfter == null && + this.startAfter == null && + this.maxWireVersion >= 7) { + this.startAtOperationTime = response.operationTime; + } + this._processBatch(response); + this.emit(constants_1.INIT, response); + this.emit(constants_1.RESPONSE); + // TODO: NODE-2882 + callback(undefined, { server, session, response }); + }); + } + _getMore(batchSize, callback) { + super._getMore(batchSize, (err, response) => { + if (err) { + return callback(err); + } + this.maxWireVersion = (0, utils_1.maxWireVersion)(this.server); + this._processBatch(response); + this.emit(change_stream_1.ChangeStream.MORE, response); + this.emit(change_stream_1.ChangeStream.RESPONSE); + callback(err, response); + }); + } +} +exports.ChangeStreamCursor = ChangeStreamCursor; +//# sourceMappingURL=change_stream_cursor.js.map \ No newline at end of file diff --git a/ts-ticket-office-service/node_modules/mongodb/lib/cursor/change_stream_cursor.js.map b/ts-ticket-office-service/node_modules/mongodb/lib/cursor/change_stream_cursor.js.map new file mode 100644 index 000000000..259e3ded1 --- /dev/null +++ b/ts-ticket-office-service/node_modules/mongodb/lib/cursor/change_stream_cursor.js.map @@ -0,0 +1 @@ +{"version":3,"file":"change_stream_cursor.js","sourceRoot":"","sources":["../../src/cursor/change_stream_cursor.ts"],"names":[],"mappings":";;;AACA,oDAM0B;AAC1B,4CAA8C;AAG9C,uDAA6D;AAE7D,uEAAyF;AAEzF,oCAAgF;AAChF,uDAA+E;AAwB/E,gBAAgB;AAChB,MAAa,kBAGX,SAAQ,gCAA2C;IAkBnD,YACE,MAAmB,EACnB,SAA2B,EAC3B,WAAuB,EAAE,EACzB,UAAqC,EAAE;QAEvC,KAAK,CAAC,MAAM,EAAE,SAAS,EAAE,OAAO,CAAC,CAAC;QAElC,IAAI,CAAC,QAAQ,GAAG,QAAQ,CAAC;QACzB,IAAI,CAAC,OAAO,GAAG,OAAO,CAAC;QACvB,IAAI,CAAC,YAAY,GAAG,IAAI,CAAC;QACzB,IAAI,CAAC,oBAAoB,GAAG,OAAO,CAAC,oBAAoB,CAAC;QAEzD,IAAI,OAAO,CAAC,UAAU,EAAE;YACtB,IAAI,CAAC,WAAW,GAAG,OAAO,CAAC,UAAU,CAAC;SACvC;aAAM,IAAI,OAAO,CAAC,WAAW,EAAE;YAC9B,IAAI,CAAC,WAAW,GAAG,OAAO,CAAC,WAAW,CAAC;SACxC;IACH,CAAC;IAED,IAAI,WAAW,CAAC,KAAkB;QAChC,IAAI,CAAC,YAAY,GAAG,KAAK,CAAC;QAC1B,IAAI,CAAC,IAAI,CAAC,4BAAY,CAAC,oBAAoB,EAAE,KAAK,CAAC,CAAC;IACtD,CAAC;IAED,IAAI,WAAW;QACb,OAAO,IAAI,CAAC,YAAY,CAAC;IAC3B,CAAC;IAED,IAAI,aAAa;QACf,MAAM,OAAO,GAA8B;YACzC,GAAG,IAAI,CAAC,OAAO;SAChB,CAAC;QAEF,KAAK,MAAM,GAAG,IAAI,CAAC,aAAa,EAAE,YAAY,EAAE,sBAAsB,CAAU,EAAE;YAChF,OAAO,OAAO,CAAC,GAAG,CAAC,CAA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C;IACJ,CAAC;IAEQ,QAAQ,CAAC,SAAiB,EAAE,QAAkB;QACrD,KAAK,CAAC,QAAQ,CAAC,SAAS,EAAE,CAAC,GAAG,EAAE,QAAQ,EAAE,EAAE;YAC1C,IAAI,GAAG,EAAE;gBACP,OAAO,QAAQ,CAAC,GAAG,CAAC,CAAC;aACtB;YAED,IAAI,CAAC,cAAc,GAAG,IAAA,sBAAc,EAAC,IAAI,CAAC,MAAM,CAAC,CAAC;YAClD,IAAI,CAAC,aAAa,CAAC,QAAqE,CAAC,CAAC;YAE1F,IAAI,CAAC,IAAI,CAAC,4BAAY,CAAC,IAAI,EAAE,QAAQ,CAAC,CAAC;YACvC,IAAI,CAAC,IAAI,CAAC,4BAAY,CAAC,QAAQ,CAAC,CAAC;YACjC,QAAQ,CAAC,GAAG,EAAE,QAAQ,CAAC,CAAC;QAC1B,CAAC,CAAC,CAAC;IACL,CAAC;CACF;AAxJD,gDAwJC"} \ No newline at end of file diff --git a/ts-ticket-office-service/node_modules/mongodb/lib/cursor/find_cursor.js b/ts-ticket-office-service/node_modules/mongodb/lib/cursor/find_cursor.js new file mode 100644 index 000000000..072bf789d --- /dev/null +++ b/ts-ticket-office-service/node_modules/mongodb/lib/cursor/find_cursor.js @@ -0,0 +1,382 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.FindCursor = exports.FLAGS = void 0; +const error_1 = require("../error"); +const count_1 = require("../operations/count"); +const execute_operation_1 = require("../operations/execute_operation"); +const find_1 = require("../operations/find"); +const sort_1 = require("../sort"); +const utils_1 = require("../utils"); +const abstract_cursor_1 = require("./abstract_cursor"); +/** @internal */ +const kFilter = Symbol('filter'); +/** @internal */ +const kNumReturned = Symbol('numReturned'); +/** @internal */ +const kBuiltOptions = Symbol('builtOptions'); +/** @public Flags allowed for cursor */ +exports.FLAGS = [ + 'tailable', + 'oplogReplay', + 'noCursorTimeout', + 'awaitData', + 'exhaust', + 'partial' +]; +/** @public */ +class FindCursor extends abstract_cursor_1.AbstractCursor { + /** @internal */ + constructor(client, namespace, filter, options = {}) { + super(client, namespace, options); + this[kFilter] = filter || {}; + this[kBuiltOptions] = options; + if (options.sort != null) { + this[kBuiltOptions].sort = (0, sort_1.formatSort)(options.sort); + } + } + clone() { + const clonedOptions = (0, utils_1.mergeOptions)({}, this[kBuiltOptions]); + delete clonedOptions.session; + return new FindCursor(this.client, this.namespace, this[kFilter], { + ...clonedOptions + }); + } + map(transform) { + return super.map(transform); + } + /** @internal */ + _initialize(session, callback) { + const findOperation = new find_1.FindOperation(undefined, this.namespace, this[kFilter], { + ...this[kBuiltOptions], + ...this.cursorOptions, + session + }); + (0, execute_operation_1.executeOperation)(this.client, findOperation, (err, response) => { + if (err || response == null) + return callback(err); + // TODO: We only need this for legacy queries that do not support `limit`, maybe + // the value should only be saved in those cases. + if (response.cursor) { + this[kNumReturned] = response.cursor.firstBatch.length; + } + else { + this[kNumReturned] = response.documents ? response.documents.length : 0; + } + // TODO: NODE-2882 + callback(undefined, { server: findOperation.server, session, response }); + }); + } + /** @internal */ + _getMore(batchSize, callback) { + // NOTE: this is to support client provided limits in pre-command servers + const numReturned = this[kNumReturned]; + if (numReturned) { + const limit = this[kBuiltOptions].limit; + batchSize = + limit && limit > 0 && numReturned + batchSize > limit ? limit - numReturned : batchSize; + if (batchSize <= 0) { + return this.close(callback); + } + } + super._getMore(batchSize, (err, response) => { + if (err) + return callback(err); + // TODO: wrap this in some logic to prevent it from happening if we don't need this support + if (response) { + this[kNumReturned] = this[kNumReturned] + response.cursor.nextBatch.length; + } + callback(undefined, response); + }); + } + count(options, callback) { + (0, utils_1.emitWarningOnce)('cursor.count is deprecated and will be removed in the next major version, please use `collection.estimatedDocumentCount` or `collection.countDocuments` instead '); + if (typeof options === 'boolean') { + throw new error_1.MongoInvalidArgumentError('Invalid first parameter to count'); + } + if (typeof options === 'function') + (callback = options), (options = {}); + options = options !== null && options !== void 0 ? options : {}; + return (0, execute_operation_1.executeOperation)(this.client, new count_1.CountOperation(this.namespace, this[kFilter], { + ...this[kBuiltOptions], + ...this.cursorOptions, + ...options + }), callback); + } + explain(verbosity, callback) { + if (typeof verbosity === 'function') + (callback = verbosity), (verbosity = true); + if (verbosity == null) + verbosity = true; + return (0, execute_operation_1.executeOperation)(this.client, new find_1.FindOperation(undefined, this.namespace, this[kFilter], { + ...this[kBuiltOptions], + ...this.cursorOptions, + explain: verbosity + }), callback); + } + /** Set the cursor query */ + filter(filter) { + (0, abstract_cursor_1.assertUninitialized)(this); + this[kFilter] = filter; + return this; + } + /** + * Set the cursor hint + * + * @param hint - If specified, then the query system will only consider plans using the hinted index. + */ + hint(hint) { + (0, abstract_cursor_1.assertUninitialized)(this); + this[kBuiltOptions].hint = hint; + return this; + } + /** + * Set the cursor min + * + * @param min - Specify a $min value to specify the inclusive lower bound for a specific index in order to constrain the results of find(). The $min specifies the lower bound for all keys of a specific index in order. + */ + min(min) { + (0, abstract_cursor_1.assertUninitialized)(this); + this[kBuiltOptions].min = min; + return this; + } + /** + * Set the cursor max + * + * @param max - Specify a $max value to specify the exclusive upper bound for a specific index in order to constrain the results of find(). The $max specifies the upper bound for all keys of a specific index in order. + */ + max(max) { + (0, abstract_cursor_1.assertUninitialized)(this); + this[kBuiltOptions].max = max; + return this; + } + /** + * Set the cursor returnKey. + * If set to true, modifies the cursor to only return the index field or fields for the results of the query, rather than documents. + * If set to true and the query does not use an index to perform the read operation, the returned documents will not contain any fields. + * + * @param value - the returnKey value. + */ + returnKey(value) { + (0, abstract_cursor_1.assertUninitialized)(this); + this[kBuiltOptions].returnKey = value; + return this; + } + /** + * Modifies the output of a query by adding a field $recordId to matching documents. $recordId is the internal key which uniquely identifies a document in a collection. + * + * @param value - The $showDiskLoc option has now been deprecated and replaced with the showRecordId field. $showDiskLoc will still be accepted for OP_QUERY stye find. + */ + showRecordId(value) { + (0, abstract_cursor_1.assertUninitialized)(this); + this[kBuiltOptions].showRecordId = value; + return this; + } + /** + * Add a query modifier to the cursor query + * + * @param name - The query modifier (must start with $, such as $orderby etc) + * @param value - The modifier value. + */ + addQueryModifier(name, value) { + (0, abstract_cursor_1.assertUninitialized)(this); + if (name[0] !== '$') { + throw new error_1.MongoInvalidArgumentError(`${name} is not a valid query modifier`); + } + // Strip of the $ + const field = name.substr(1); + // NOTE: consider some TS magic for this + switch (field) { + case 'comment': + this[kBuiltOptions].comment = value; + break; + case 'explain': + this[kBuiltOptions].explain = value; + break; + case 'hint': + this[kBuiltOptions].hint = value; + break; + case 'max': + this[kBuiltOptions].max = value; + break; + case 'maxTimeMS': + this[kBuiltOptions].maxTimeMS = value; + break; + case 'min': + this[kBuiltOptions].min = value; + break; + case 'orderby': + this[kBuiltOptions].sort = (0, sort_1.formatSort)(value); + break; + case 'query': + this[kFilter] = value; + break; + case 'returnKey': + this[kBuiltOptions].returnKey = value; + break; + case 'showDiskLoc': + this[kBuiltOptions].showRecordId = value; + break; + default: + throw new error_1.MongoInvalidArgumentError(`Invalid query modifier: ${name}`); + } + return this; + } + /** + * Add a comment to the cursor query allowing for tracking the comment in the log. + * + * @param value - The comment attached to this query. + */ + comment(value) { + (0, abstract_cursor_1.assertUninitialized)(this); + this[kBuiltOptions].comment = value; + return this; + } + /** + * Set a maxAwaitTimeMS on a tailing cursor query to allow to customize the timeout value for the option awaitData (Only supported on MongoDB 3.2 or higher, ignored otherwise) + * + * @param value - Number of milliseconds to wait before aborting the tailed query. + */ + maxAwaitTimeMS(value) { + (0, abstract_cursor_1.assertUninitialized)(this); + if (typeof value !== 'number') { + throw new error_1.MongoInvalidArgumentError('Argument for maxAwaitTimeMS must be a number'); + } + this[kBuiltOptions].maxAwaitTimeMS = value; + return this; + } + /** + * Set a maxTimeMS on the cursor query, allowing for hard timeout limits on queries (Only supported on MongoDB 2.6 or higher) + * + * @param value - Number of milliseconds to wait before aborting the query. + */ + maxTimeMS(value) { + (0, abstract_cursor_1.assertUninitialized)(this); + if (typeof value !== 'number') { + throw new error_1.MongoInvalidArgumentError('Argument for maxTimeMS must be a number'); + } + this[kBuiltOptions].maxTimeMS = value; + return this; + } + /** + * Add a project stage to the aggregation pipeline + * + * @remarks + * In order to strictly type this function you must provide an interface + * that represents the effect of your projection on the result documents. + * + * By default chaining a projection to your cursor changes the returned type to the generic + * {@link Document} type. + * You should specify a parameterized type to have assertions on your final results. + * + * @example + * ```typescript + * // Best way + * const docs: FindCursor<{ a: number }> = cursor.project<{ a: number }>({ _id: 0, a: true }); + * // Flexible way + * const docs: FindCursor = cursor.project({ _id: 0, a: true }); + * ``` + * + * @remarks + * + * **Note for Typescript Users:** adding a transform changes the return type of the iteration of this cursor, + * it **does not** return a new instance of a cursor. This means when calling project, + * you should always assign the result to a new variable in order to get a correctly typed cursor variable. + * Take note of the following example: + * + * @example + * ```typescript + * const cursor: FindCursor<{ a: number; b: string }> = coll.find(); + * const projectCursor = cursor.project<{ a: number }>({ _id: 0, a: true }); + * const aPropOnlyArray: {a: number}[] = await projectCursor.toArray(); + * + * // or always use chaining and save the final cursor + * + * const cursor = coll.find().project<{ a: string }>({ + * _id: 0, + * a: { $convert: { input: '$a', to: 'string' } + * }}); + * ``` + */ + project(value) { + (0, abstract_cursor_1.assertUninitialized)(this); + this[kBuiltOptions].projection = value; + return this; + } + /** + * Sets the sort order of the cursor query. + * + * @param sort - The key or keys set for the sort. + * @param direction - The direction of the sorting (1 or -1). + */ + sort(sort, direction) { + (0, abstract_cursor_1.assertUninitialized)(this); + if (this[kBuiltOptions].tailable) { + throw new error_1.MongoTailableCursorError('Tailable cursor does not support sorting'); + } + this[kBuiltOptions].sort = (0, sort_1.formatSort)(sort, direction); + return this; + } + /** + * Allows disk use for blocking sort operations exceeding 100MB memory. (MongoDB 3.2 or higher) + * + * @remarks + * {@link https://docs.mongodb.com/manual/reference/command/find/#find-cmd-allowdiskuse | find command allowDiskUse documentation} + */ + allowDiskUse(allow = true) { + (0, abstract_cursor_1.assertUninitialized)(this); + if (!this[kBuiltOptions].sort) { + throw new error_1.MongoInvalidArgumentError('Option "allowDiskUse" requires a sort specification'); + } + // As of 6.0 the default is true. This allows users to get back to the old behaviour. + if (!allow) { + this[kBuiltOptions].allowDiskUse = false; + return this; + } + this[kBuiltOptions].allowDiskUse = true; + return this; + } + /** + * Set the collation options for the cursor. + * + * @param value - The cursor collation options (MongoDB 3.4 or higher) settings for update operation (see 3.4 documentation for available fields). + */ + collation(value) { + (0, abstract_cursor_1.assertUninitialized)(this); + this[kBuiltOptions].collation = value; + return this; + } + /** + * Set the limit for the cursor. + * + * @param value - The limit for the cursor query. + */ + limit(value) { + (0, abstract_cursor_1.assertUninitialized)(this); + if (this[kBuiltOptions].tailable) { + throw new error_1.MongoTailableCursorError('Tailable cursor does not support limit'); + } + if (typeof value !== 'number') { + throw new error_1.MongoInvalidArgumentError('Operation "limit" requires an integer'); + } + this[kBuiltOptions].limit = value; + return this; + } + /** + * Set the skip for the cursor. + * + * @param value - The skip for the cursor query. + */ + skip(value) { + (0, abstract_cursor_1.assertUninitialized)(this); + if (this[kBuiltOptions].tailable) { + throw new error_1.MongoTailableCursorError('Tailable cursor does not support skip'); + } + if (typeof value !== 'number') { + throw new error_1.MongoInvalidArgumentError('Operation "skip" requires an integer'); + } + this[kBuiltOptions].skip = value; + return this; + } +} +exports.FindCursor = FindCursor; +//# sourceMappingURL=find_cursor.js.map \ No newline at end of file diff --git a/ts-ticket-office-service/node_modules/mongodb/lib/cursor/find_cursor.js.map b/ts-ticket-office-service/node_modules/mongodb/lib/cursor/find_cursor.js.map new file mode 100644 index 000000000..494320a58 --- /dev/null +++ b/ts-ticket-office-service/node_modules/mongodb/lib/cursor/find_cursor.js.map @@ -0,0 +1 @@ +{"version":3,"file":"find_cursor.js","sourceRoot":"","sources":["../../src/cursor/find_cursor.ts"],"names":[],"mappings":";;;AACA,oCAA+E;AAI/E,+CAAmE;AACnE,uEAAoF;AACpF,6CAAgE;AAGhE,kCAA0D;AAC1D,oCAAqF;AACrF,uDAAwE;AAExE,gBAAgB;AAChB,MAAM,OAAO,GAAG,MAAM,CAAC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,KAAK,KAAK,QAAQ,EAAE;YAC7B,MAAM,IAAI,iCAAyB,CAAC,uCAAuC,CAAC,CAAC;SAC9E;QAED,IAAI,CAAC,aAAa,CAAC,CAAC,KAAK,GAAG,KAAK,CAAC;QAClC,OAAO,IAAI,CAAC;IACd,CAAC;IAED;;;;OAIG;IACH,IAAI,CAAC,KAAa;QAChB,IAAA,qCAAmB,EAAC,IAAI,CAAC,CAAC;QAC1B,IAAI,IAAI,CAAC,aAAa,CAAC,CAAC,QAAQ,EAAE;YAChC,MAAM,IAAI,gCAAwB,CAAC,uCAAuC,CAAC,CAAC;SAC7E;QAED,IAAI,OAAO,KAAK,KAAK,QAAQ,EAAE;YAC7B,MAAM,IAAI,iCAAyB,CAAC,sCAAsC,CAAC,CAAC;SAC7E;QAED,IAAI,CAAC,aAAa,CAAC,CAAC,IAAI,GAAG,KAAK,CAAC;QACjC,OAAO,IAAI,CAAC;IACd,CAAC;CACF;AA/bD,gCA+bC"} \ No newline at end of file diff --git a/ts-ticket-office-service/node_modules/mongodb/lib/cursor/list_collections_cursor.js b/ts-ticket-office-service/node_modules/mongodb/lib/cursor/list_collections_cursor.js new file mode 100644 index 000000000..883474b08 --- /dev/null +++ b/ts-ticket-office-service/node_modules/mongodb/lib/cursor/list_collections_cursor.js @@ -0,0 +1,37 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.ListCollectionsCursor = void 0; +const execute_operation_1 = require("../operations/execute_operation"); +const list_collections_1 = require("../operations/list_collections"); +const abstract_cursor_1 = require("./abstract_cursor"); +/** @public */ +class ListCollectionsCursor extends abstract_cursor_1.AbstractCursor { + constructor(db, filter, options) { + super(db.s.client, db.s.namespace, options); + this.parent = db; + this.filter = filter; + this.options = options; + } + clone() { + return new ListCollectionsCursor(this.parent, this.filter, { + ...this.options, + ...this.cursorOptions + }); + } + /** @internal */ + _initialize(session, callback) { + const operation = new list_collections_1.ListCollectionsOperation(this.parent, this.filter, { + ...this.cursorOptions, + ...this.options, + session + }); + (0, execute_operation_1.executeOperation)(this.parent.s.client, operation, (err, response) => { + if (err || response == null) + return callback(err); + // TODO: NODE-2882 + callback(undefined, { server: operation.server, session, response }); + }); + } +} +exports.ListCollectionsCursor = ListCollectionsCursor; +//# sourceMappingURL=list_collections_cursor.js.map \ No newline at end of file diff --git a/ts-ticket-office-service/node_modules/mongodb/lib/cursor/list_collections_cursor.js.map b/ts-ticket-office-service/node_modules/mongodb/lib/cursor/list_collections_cursor.js.map new file mode 100644 index 000000000..2f8ecbe33 --- /dev/null +++ b/ts-ticket-office-service/node_modules/mongodb/lib/cursor/list_collections_cursor.js.map @@ -0,0 +1 @@ +{"version":3,"file":"list_collections_cursor.js","sourceRoot":"","sources":["../../src/cursor/list_collections_cursor.ts"],"names":[],"mappings":";;;AAEA,uEAAoF;AACpF,qEAIwC;AAGxC,uDAAmD;AAEnD,cAAc;AACd,MAAa,qBAIX,SAAQ,gCAAiB;IAKzB,YAAY,EAAM,EAAE,MAAgB,EAAE,OAAgC;QACpE,KAAK,CAAC,EAAE,CAAC,CAAC,CAAC,MAAM,EAAE,EAAE,CAAC,CAAC,CAAC,SAAS,EAAE,OAAO,CAAC,CAAC;QAC5C,IAAI,CAAC,MAAM,GAAG,EAAE,CAAC;QACjB,IAAI,CAAC,MAAM,GAAG,MAAM,CAAC;QACrB,IAAI,CAAC,OAAO,GAAG,OAAO,CAAC;IACzB,CAAC;IAED,KAAK;QACH,OAAO,IAAI,qBAAqB,CAAC,IAAI,CAAC,MAAM,EAAE,IAAI,CAAC,MAAM,EAAE;YACzD,GAAG,IAAI,CAAC,OAAO;YACf,GAAG,IAAI,CAAC,aAAa;SACtB,CAAC,CAAC;IACL,CAAC;IAED,gBAAgB;IAChB,WAAW,CAAC,OAAkC,EAAE,QAAmC;QACjF,MAAM,SAAS,GAAG,IAAI,2CAAwB,CAAC,IAAI,CAAC,MAAM,EAAE,IAAI,CAAC,MAAM,EAAE;YACvE,GAAG,IAAI,CAAC,aAAa;YACrB,GAAG,IAAI,CAAC,OAAO;YACf,OAAO;SACR,CAAC,CAAC;QAEH,IAAA,oCAAgB,EAAC,IAAI,CAAC,MAAM,CAAC,CAAC,CAAC,MAAM,EAAE,SAAS,EAAE,CAAC,GAAG,EAAE,QAAQ,EAAE,EAAE;YAClE,IAAI,GAAG,IAAI,QAAQ,IAAI,IAAI;gBAAE,OAAO,QAAQ,CAAC,GAAG,CAAC,CAAC;YAElD,kBAAkB;YAClB,QAAQ,CAAC,SAAS,EAAE,EAAE,MAAM,EAAE,SAAS,CAAC,MAAM,EAAE,OAAO,EAAE,QAAQ,EAAE,CAAC,CAAC;QACvE,CAAC,CAAC,CAAC;IACL,CAAC;CACF;AAtCD,sDAsCC"} \ No newline at end of file diff --git a/ts-ticket-office-service/node_modules/mongodb/lib/cursor/list_indexes_cursor.js b/ts-ticket-office-service/node_modules/mongodb/lib/cursor/list_indexes_cursor.js new file mode 100644 index 000000000..7d62d78fd --- /dev/null +++ b/ts-ticket-office-service/node_modules/mongodb/lib/cursor/list_indexes_cursor.js @@ -0,0 +1,36 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.ListIndexesCursor = void 0; +const execute_operation_1 = require("../operations/execute_operation"); +const indexes_1 = require("../operations/indexes"); +const abstract_cursor_1 = require("./abstract_cursor"); +/** @public */ +class ListIndexesCursor extends abstract_cursor_1.AbstractCursor { + constructor(collection, options) { + super(collection.s.db.s.client, collection.s.namespace, options); + this.parent = collection; + this.options = options; + } + clone() { + return new ListIndexesCursor(this.parent, { + ...this.options, + ...this.cursorOptions + }); + } + /** @internal */ + _initialize(session, callback) { + const operation = new indexes_1.ListIndexesOperation(this.parent, { + ...this.cursorOptions, + ...this.options, + session + }); + (0, execute_operation_1.executeOperation)(this.parent.s.db.s.client, operation, (err, response) => { + if (err || response == null) + return callback(err); + // TODO: NODE-2882 + callback(undefined, { server: operation.server, session, response }); + }); + } +} +exports.ListIndexesCursor = ListIndexesCursor; +//# sourceMappingURL=list_indexes_cursor.js.map \ No newline at end of file diff --git a/ts-ticket-office-service/node_modules/mongodb/lib/cursor/list_indexes_cursor.js.map b/ts-ticket-office-service/node_modules/mongodb/lib/cursor/list_indexes_cursor.js.map new file mode 100644 index 000000000..f17b57685 --- /dev/null +++ b/ts-ticket-office-service/node_modules/mongodb/lib/cursor/list_indexes_cursor.js.map @@ -0,0 +1 @@ +{"version":3,"file":"list_indexes_cursor.js","sourceRoot":"","sources":["../../src/cursor/list_indexes_cursor.ts"],"names":[],"mappings":";;;AACA,uEAAoF;AACpF,mDAAiF;AAGjF,uDAAmD;AAEnD,cAAc;AACd,MAAa,iBAAkB,SAAQ,gCAAc;IAInD,YAAY,UAAsB,EAAE,OAA4B;QAC9D,KAAK,CAAC,UAAU,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,MAAM,EAAE,UAAU,CAAC,CAAC,CAAC,SAAS,EAAE,OAAO,CAAC,CAAC;QACjE,IAAI,CAAC,MAAM,GAAG,UAAU,CAAC;QACzB,IAAI,CAAC,OAAO,GAAG,OAAO,CAAC;IACzB,CAAC;IAED,KAAK;QACH,OAAO,IAAI,iBAAiB,CAAC,IAAI,CAAC,MAAM,EAAE;YACxC,GAAG,IAAI,CAAC,OAAO;YACf,GAAG,IAAI,CAAC,aAAa;SACtB,CAAC,CAAC;IACL,CAAC;IAED,gBAAgB;IAChB,WAAW,CAAC,OAAkC,EAAE,QAAmC;QACjF,MAAM,SAAS,GAAG,IAAI,8BAAoB,CAAC,IAAI,CAAC,MAAM,EAAE;YACtD,GAAG,IAAI,CAAC,aAAa;YACrB,GAAG,IAAI,CAAC,OAAO;YACf,OAAO;SACR,CAAC,CAAC;QAEH,IAAA,oCAAgB,EAAC,IAAI,CAAC,MAAM,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,MAAM,EAAE,SAAS,EAAE,CAAC,GAAG,EAAE,QAAQ,EAAE,EAAE;YACvE,IAAI,GAAG,IAAI,QAAQ,IAAI,IAAI;gBAAE,OAAO,QAAQ,CAAC,GAAG,CAAC,CAAC;YAElD,kBAAkB;YAClB,QAAQ,CAAC,SAAS,EAAE,EAAE,MAAM,EAAE,SAAS,CAAC,MAAM,EAAE,OAAO,EAAE,QAAQ,EAAE,CAAC,CAAC;QACvE,CAAC,CAAC,CAAC;IACL,CAAC;CACF;AAhCD,8CAgCC"} \ No newline at end of file diff --git a/ts-ticket-office-service/node_modules/mongodb/lib/db.js b/ts-ticket-office-service/node_modules/mongodb/lib/db.js index 287fa7f15..18b837bf1 100644 --- a/ts-ticket-office-service/node_modules/mongodb/lib/db.js +++ b/ts-ticket-office-service/node_modules/mongodb/lib/db.js @@ -1,1803 +1,334 @@ "use strict"; - -var EventEmitter = require('events').EventEmitter - , authenticate = require('./authenticate') - , inherits = require('util').inherits - , getSingleProperty = require('./utils').getSingleProperty - , shallowClone = require('./utils').shallowClone - , parseIndexOptions = require('./utils').parseIndexOptions - , debugOptions = require('./utils').debugOptions - , CommandCursor = require('./command_cursor') - , handleCallback = require('./utils').handleCallback - , filterOptions = require('./utils').filterOptions - , toError = require('./utils').toError - , ReadPreference = require('./read_preference') - , f = require('util').format - , Admin = require('./admin') - , Code = require('mongodb-core').BSON.Code - , CoreReadPreference = require('mongodb-core').ReadPreference - , MongoError = require('mongodb-core').MongoError - , ObjectID = require('mongodb-core').ObjectID - , Define = require('./metadata') - , Logger = require('mongodb-core').Logger - , Collection = require('./collection') - , crypto = require('crypto') - , mergeOptionsAndWriteConcern = require('./utils').mergeOptionsAndWriteConcern - , assign = require('./utils').assign; - -var debugFields = ['authSource', 'w', 'wtimeout', 'j', 'native_parser', 'forceServerObjectId' - , 'serializeFunctions', 'raw', 'promoteLongs', 'promoteValues', 'promoteBuffers', 'bufferMaxEntries', 'numberOfRetries', 'retryMiliSeconds' - , 'readPreference', 'pkFactory', 'parentDb', 'promiseLibrary', 'noListener']; - -// Filter out any write concern options -var illegalCommandFields = ['w', 'wtimeout', 'j', 'fsync', 'autoIndexId' - , 'strict', 'serializeFunctions', 'pkFactory', 'raw', 'readPreference']; - -/** - * @fileOverview The **Db** class is a class that represents a MongoDB Database. +Object.defineProperty(exports, "__esModule", { value: true }); +exports.Db = void 0; +const admin_1 = require("./admin"); +const bson_1 = require("./bson"); +const change_stream_1 = require("./change_stream"); +const collection_1 = require("./collection"); +const CONSTANTS = require("./constants"); +const aggregation_cursor_1 = require("./cursor/aggregation_cursor"); +const list_collections_cursor_1 = require("./cursor/list_collections_cursor"); +const error_1 = require("./error"); +const logger_1 = require("./logger"); +const add_user_1 = require("./operations/add_user"); +const collections_1 = require("./operations/collections"); +const create_collection_1 = require("./operations/create_collection"); +const drop_1 = require("./operations/drop"); +const execute_operation_1 = require("./operations/execute_operation"); +const indexes_1 = require("./operations/indexes"); +const profiling_level_1 = require("./operations/profiling_level"); +const remove_user_1 = require("./operations/remove_user"); +const rename_1 = require("./operations/rename"); +const run_command_1 = require("./operations/run_command"); +const set_profiling_level_1 = require("./operations/set_profiling_level"); +const stats_1 = require("./operations/stats"); +const read_concern_1 = require("./read_concern"); +const read_preference_1 = require("./read_preference"); +const utils_1 = require("./utils"); +const write_concern_1 = require("./write_concern"); +// Allowed parameters +const DB_OPTIONS_ALLOW_LIST = [ + 'writeConcern', + 'readPreference', + 'readPreferenceTags', + 'native_parser', + 'forceServerObjectId', + 'pkFactory', + 'serializeFunctions', + 'raw', + 'authSource', + 'ignoreUndefined', + 'readConcern', + 'retryMiliSeconds', + 'numberOfRetries', + 'loggerLevel', + 'logger', + 'promoteBuffers', + 'promoteLongs', + 'bsonRegExp', + 'enableUtf8Validation', + 'promoteValues', + 'compression', + 'retryWrites' +]; +/** + * The **Db** class is a class that represents a MongoDB Database. + * @public * * @example - * var MongoClient = require('mongodb').MongoClient, - * test = require('assert'); + * ```js + * const { MongoClient } = require('mongodb'); * // Connection url - * var url = 'mongodb://localhost:27017/test'; + * const url = 'mongodb://localhost:27017'; + * // Database Name + * const dbName = 'test'; * // Connect using MongoClient - * MongoClient.connect(url, function(err, db) { - * // Get an additional db - * var testDb = db.db('test'); - * db.close(); + * MongoClient.connect(url, function(err, client) { + * // Select the database by name + * const testDb = client.db(dbName); + * client.close(); * }); - */ - -// Allowed parameters -var legalOptionNames = ['w', 'wtimeout', 'fsync', 'j', 'readPreference', 'readPreferenceTags', 'native_parser' - , 'forceServerObjectId', 'pkFactory', 'serializeFunctions', 'raw', 'bufferMaxEntries', 'authSource' - , 'ignoreUndefined', 'promoteLongs', 'promiseLibrary', 'readConcern', 'retryMiliSeconds', 'numberOfRetries' - , 'parentDb', 'noListener', 'loggerLevel', 'logger', 'promoteBuffers', 'promoteLongs', 'promoteValues']; - -/** - * Creates a new Db instance - * @class - * @param {string} databaseName The name of the database this instance represents. - * @param {(Server|ReplSet|Mongos)} topology The server topology for the database. - * @param {object} [options=null] Optional settings. - * @param {string} [options.authSource=null] If the database authentication is dependent on another databaseName. - * @param {(number|string)} [options.w=null] The write concern. - * @param {number} [options.wtimeout=null] The write concern timeout. - * @param {boolean} [options.j=false] Specify a journal write concern. - * @param {boolean} [options.forceServerObjectId=false] Force server to assign _id values instead of driver. - * @param {boolean} [options.serializeFunctions=false] Serialize functions on any object. - * @param {Boolean} [options.ignoreUndefined=false] Specify if the BSON serializer should ignore undefined fields. - * @param {boolean} [options.raw=false] Return document results as raw BSON buffers. - * @param {boolean} [options.promoteLongs=true] Promotes Long values to number if they fit inside the 53 bits resolution. - * @param {boolean} [options.promoteBuffers=false] Promotes Binary BSON values to native Node Buffers. - * @param {boolean} [options.promoteValues=true] Promotes BSON values to native types where possible, set to false to only receive wrapper types. - * @param {number} [options.bufferMaxEntries=-1] Sets a cap on how many operations the driver will buffer up before giving up on getting a working connection, default is -1 which is unlimited. - * @param {(ReadPreference|string)} [options.readPreference=null] The preferred read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST). - * @param {object} [options.pkFactory=null] A primary key factory object for generation of custom _id keys. - * @param {object} [options.promiseLibrary=null] A Promise library class the application wishes to use such as Bluebird, must be ES6 compatible - * @param {object} [options.readConcern=null] Specify a read concern for the collection. (only MongoDB 3.2 or higher supported) - * @param {object} [options.readConcern.level='local'] Specify a read concern level for the collection operations, one of [local|majority]. (only MongoDB 3.2 or higher supported) - * @property {(Server|ReplSet|Mongos)} serverConfig Get the current db topology. - * @property {number} bufferMaxEntries Current bufferMaxEntries value for the database - * @property {string} databaseName The name of the database this instance represents. - * @property {object} options The options associated with the db instance. - * @property {boolean} native_parser The current value of the parameter native_parser. - * @property {boolean} slaveOk The current slaveOk value for the db instance. - * @property {object} writeConcern The current write concern values. - * @property {object} topology Access the topology object (single server, replicaset or mongos). - * @fires Db#close - * @fires Db#authenticated - * @fires Db#reconnect - * @fires Db#error - * @fires Db#timeout - * @fires Db#parseError - * @fires Db#fullsetup - * @return {Db} a Db instance. - */ -var Db = function(databaseName, topology, options) { - options = options || {}; - if(!(this instanceof Db)) return new Db(databaseName, topology, options); - EventEmitter.call(this); - var self = this; - - // Get the promiseLibrary - var promiseLibrary = options.promiseLibrary; - - // No promise library selected fall back - if(!promiseLibrary) { - promiseLibrary = typeof global.Promise == 'function' ? - global.Promise : require('es6-promise').Promise; - } - - // Filter the options - options = filterOptions(options, legalOptionNames); - - // Ensure we put the promiseLib in the options - options.promiseLibrary = promiseLibrary; - - // var self = this; // Internal state of the db object - this.s = { - // Database name - databaseName: databaseName - // DbCache - , dbCache: {} - // Children db's - , children: [] - // Topology - , topology: topology + * ``` + */ +class Db { + /** + * Creates a new Db instance + * + * @param client - The MongoClient for the database. + * @param databaseName - The name of the database this instance represents. + * @param options - Optional settings for Db construction + */ + constructor(client, databaseName, options) { + var _a; + options = options !== null && options !== void 0 ? options : {}; + // Filter the options + options = (0, utils_1.filterOptions)(options, DB_OPTIONS_ALLOW_LIST); + // Ensure we have a valid db name + validateDatabaseName(databaseName); + // Internal state of the db object + this.s = { + // Client + client, + // Options + options, + // Logger instance + logger: new logger_1.Logger('Db', options), + // Unpack read preference + readPreference: read_preference_1.ReadPreference.fromOptions(options), + // Merge bson options + bsonOptions: (0, bson_1.resolveBSONOptions)(options, client), + // Set up the primary key factory or fallback to ObjectId + pkFactory: (_a = options === null || options === void 0 ? void 0 : options.pkFactory) !== null && _a !== void 0 ? _a : utils_1.DEFAULT_PK_FACTORY, + // ReadConcern + readConcern: read_concern_1.ReadConcern.fromOptions(options), + writeConcern: write_concern_1.WriteConcern.fromOptions(options), + // Namespace + namespace: new utils_1.MongoDBNamespace(databaseName) + }; + } + get databaseName() { + return this.s.namespace.db; + } // Options - , options: options - // Logger instance - , logger: Logger('Db', options) - // Get the bson parser - , bson: topology ? topology.bson : null - // Authsource if any - , authSource: options.authSource - // Unpack read preference - , readPreference: options.readPreference - // Set buffermaxEntries - , bufferMaxEntries: typeof options.bufferMaxEntries == 'number' ? options.bufferMaxEntries : -1 - // Parent db (if chained) - , parentDb: options.parentDb || null - // Set up the primary key factory or fallback to ObjectID - , pkFactory: options.pkFactory || ObjectID - // Get native parser - , nativeParser: options.nativeParser || options.native_parser - // Promise library - , promiseLibrary: promiseLibrary - // No listener - , noListener: typeof options.noListener == 'boolean' ? options.noListener : false - // ReadConcern - , readConcern: options.readConcern - } - - // Ensure we have a valid db name - validateDatabaseName(self.s.databaseName); - - // Add a read Only property - getSingleProperty(this, 'serverConfig', self.s.topology); - getSingleProperty(this, 'bufferMaxEntries', self.s.bufferMaxEntries); - getSingleProperty(this, 'databaseName', self.s.databaseName); - - // This is a child db, do not register any listeners - if(options.parentDb) return; - if(this.s.noListener) return; - - // Add listeners - topology.on('error', createListener(self, 'error', self)); - topology.on('timeout', createListener(self, 'timeout', self)); - topology.on('close', createListener(self, 'close', self)); - topology.on('parseError', createListener(self, 'parseError', self)); - topology.once('open', createListener(self, 'open', self)); - topology.once('fullsetup', createListener(self, 'fullsetup', self)); - topology.once('all', createListener(self, 'all', self)); - topology.on('reconnect', createListener(self, 'reconnect', self)); - topology.on('reconnectFailed', createListener(self, 'reconnectFailed', self)); -} - -inherits(Db, EventEmitter); - -var define = Db.define = new Define('Db', Db, false); - -// Topology -Object.defineProperty(Db.prototype, 'topology', { - enumerable:true, - get: function() { return this.s.topology; } -}); - -// Options -Object.defineProperty(Db.prototype, 'options', { - enumerable:true, - get: function() { return this.s.options; } -}); - -// slaveOk specified -Object.defineProperty(Db.prototype, 'slaveOk', { - enumerable:true, - get: function() { - if(this.s.options.readPreference != null - && (this.s.options.readPreference != 'primary' || this.s.options.readPreference.mode != 'primary')) { - return true; + get options() { + return this.s.options; } - return false; - } -}); - -// get the write Concern -Object.defineProperty(Db.prototype, 'writeConcern', { - enumerable:true, - get: function() { - var ops = {}; - if(this.s.options.w != null) ops.w = this.s.options.w; - if(this.s.options.j != null) ops.j = this.s.options.j; - if(this.s.options.fsync != null) ops.fsync = this.s.options.fsync; - if(this.s.options.wtimeout != null) ops.wtimeout = this.s.options.wtimeout; - return ops; - } -}); - -/** - * The callback format for the Db.open method - * @callback Db~openCallback - * @param {MongoError} error An error instance representing the error during the execution. - * @param {Db} db The Db instance if the open method was successful. - */ - -// Internal method -var open = function(self, callback) { - self.s.topology.connect(self, self.s.options, function(err) { - if(callback == null) return; - var internalCallback = callback; - callback == null; - - if(err) { - self.close(); - return internalCallback(err); + /** + * slaveOk specified + * @deprecated Use secondaryOk instead + */ + get slaveOk() { + return this.secondaryOk; } - - internalCallback(null, self); - }); -} - -/** - * Open the database - * @method - * @param {Db~openCallback} [callback] Callback - * @return {Promise} returns Promise if no callback passed - */ -Db.prototype.open = function(callback) { - var self = this; - // We provided a callback leg - if(typeof callback == 'function') return open(self, callback); - // Return promise - return new self.s.promiseLibrary(function(resolve, reject) { - open(self, function(err, db) { - if(err) return reject(err); - resolve(db); - }) - }); -} - -define.classMethod('open', {callback: true, promise:true}); - -/** - * Converts provided read preference to CoreReadPreference - * @param {(ReadPreference|string|object)} readPreference the user provided read preference - * @return {CoreReadPreference} - */ -var convertReadPreference = function(readPreference) { - if(readPreference && typeof readPreference == 'string') { - return new CoreReadPreference(readPreference); - } else if(readPreference instanceof ReadPreference) { - return new CoreReadPreference(readPreference.mode, readPreference.tags, {maxStalenessSeconds: readPreference.maxStalenessSeconds}); - } else if(readPreference && typeof readPreference == 'object') { - var mode = readPreference.mode || readPreference.preference; - if (mode && typeof mode == 'string') { - readPreference = new CoreReadPreference(mode, readPreference.tags, {maxStalenessSeconds: readPreference.maxStalenessSeconds}); + /** + * Check if a secondary can be used (because the read preference is *not* set to primary) + */ + get secondaryOk() { + var _a; + return ((_a = this.s.readPreference) === null || _a === void 0 ? void 0 : _a.preference) !== 'primary' || false; } - } - return readPreference; -} - -/** - * The callback format for results - * @callback Db~resultCallback - * @param {MongoError} error An error instance representing the error during the execution. - * @param {object} result The result object if the command was executed successfully. - */ - -var executeCommand = function(self, command, options, callback) { - // Did the user destroy the topology - if(self.serverConfig && self.serverConfig.isDestroyed()) return callback(new MongoError('topology was destroyed')); - // Get the db name we are executing against - var dbName = options.dbName || options.authdb || self.s.databaseName; - - // If we have a readPreference set - if(options.readPreference == null && self.s.readPreference) { - options.readPreference = self.s.readPreference; - } - - // Convert the readPreference if its not a write - if(options.readPreference) { - options.readPreference = convertReadPreference(options.readPreference); - } else { - options.readPreference = CoreReadPreference.primary; - } - - // Debug information - if(self.s.logger.isDebug()) self.s.logger.debug(f('executing command %s against %s with options [%s]' - , JSON.stringify(command), f('%s.$cmd', dbName), JSON.stringify(debugOptions(debugFields, options)))); - - // Execute command - self.s.topology.command(f('%s.$cmd', dbName), command, options, function(err, result) { - if(err) return handleCallback(callback, err); - if(options.full) return handleCallback(callback, null, result); - handleCallback(callback, null, result.result); - }); -} - -/** - * Execute a command - * @method - * @param {object} command The command hash - * @param {object} [options=null] Optional settings. - * @param {(ReadPreference|string)} [options.readPreference=null] The preferred read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST). - * @param {Db~resultCallback} [callback] The command result callback - * @return {Promise} returns Promise if no callback passed - */ -Db.prototype.command = function(command, options, callback) { - var self = this; - // Change the callback - if(typeof options == 'function') callback = options, options = {}; - // Clone the options - options = shallowClone(options); - - // Do we have a callback - if(typeof callback == 'function') return executeCommand(self, command, options, callback); - // Return a promise - return new this.s.promiseLibrary(function(resolve, reject) { - executeCommand(self, command, options, function(err, r) { - if(err) return reject(err); - resolve(r); - }); - }); -} - -define.classMethod('command', {callback: true, promise:true}); - -/** - * The callback format for results - * @callback Db~noResultCallback - * @param {MongoError} error An error instance representing the error during the execution. - * @param {null} result Is not set to a value - */ - -/** - * Close the db and its underlying connections - * @method - * @param {boolean} force Force close, emitting no events - * @param {Db~noResultCallback} [callback] The result callback - * @return {Promise} returns Promise if no callback passed - */ -Db.prototype.close = function(force, callback) { - if(typeof force == 'function') callback = force, force = false; - this.s.topology.close(force); - var self = this; - - // Fire close event if any listeners - if(this.listeners('close').length > 0) { - this.emit('close'); - - // If it's the top level db emit close on all children - if(this.parentDb == null) { - // Fire close on all children - for(var i = 0; i < this.s.children.length; i++) { - this.s.children[i].emit('close'); - } + get readConcern() { + return this.s.readConcern; } - - // Remove listeners after emit - self.removeAllListeners('close'); - } - - // Close parent db if set - if(this.s.parentDb) this.s.parentDb.close(); - // Callback after next event loop tick - if(typeof callback == 'function') return process.nextTick(function() { - handleCallback(callback, null); - }) - - // Return dummy promise - return new this.s.promiseLibrary(function(resolve) { - resolve(); - }); -} - -define.classMethod('close', {callback: true, promise:true}); - -/** - * Return the Admin db instance - * @method - * @return {Admin} return the new Admin db instance - */ -Db.prototype.admin = function() { - return new Admin(this, this.s.topology, this.s.promiseLibrary); -}; - -define.classMethod('admin', {callback: false, promise:false, returns: [Admin]}); - -/** - * The callback format for the collection method, must be used if strict is specified - * @callback Db~collectionResultCallback - * @param {MongoError} error An error instance representing the error during the execution. - * @param {Collection} collection The collection instance. - */ - -var collectionKeys = ['pkFactory', 'readPreference' - , 'serializeFunctions', 'strict', 'readConcern', 'ignoreUndefined', 'promoteValues', 'promoteBuffers', 'promoteLongs']; - -/** - * Fetch a specific collection (containing the actual collection information). If the application does not use strict mode you can - * can use it without a callback in the following way: `var collection = db.collection('mycollection');` - * - * @method - * @param {string} name the collection name we wish to access. - * @param {object} [options=null] Optional settings. - * @param {(number|string)} [options.w=null] The write concern. - * @param {number} [options.wtimeout=null] The write concern timeout. - * @param {boolean} [options.j=false] Specify a journal write concern. - * @param {boolean} [options.raw=false] Return document results as raw BSON buffers. - * @param {object} [options.pkFactory=null] A primary key factory object for generation of custom _id keys. - * @param {(ReadPreference|string)} [options.readPreference=null] The preferred read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST). - * @param {boolean} [options.serializeFunctions=false] Serialize functions on any object. - * @param {boolean} [options.strict=false] Returns an error if the collection does not exist - * @param {object} [options.readConcern=null] Specify a read concern for the collection. (only MongoDB 3.2 or higher supported) - * @param {object} [options.readConcern.level='local'] Specify a read concern level for the collection operations, one of [local|majority]. (only MongoDB 3.2 or higher supported) - * @param {Db~collectionResultCallback} callback The collection result callback - * @return {Collection} return the new Collection instance if not in strict mode - */ -Db.prototype.collection = function(name, options, callback) { - var self = this; - if(typeof options == 'function') callback = options, options = {}; - options = options || {}; - options = shallowClone(options); - // Set the promise library - options.promiseLibrary = this.s.promiseLibrary; - - // If we have not set a collection level readConcern set the db level one - options.readConcern = options.readConcern || this.s.readConcern; - - // Do we have ignoreUndefined set - if(this.s.options.ignoreUndefined) { - options.ignoreUndefined = this.s.options.ignoreUndefined; - } - - // Merge in all needed options and ensure correct writeConcern merging from db level - options = mergeOptionsAndWriteConcern(options, this.s.options, collectionKeys, true); - - // Execute - if(options == null || !options.strict) { - try { - var collection = new Collection(this, this.s.topology, this.s.databaseName, name, this.s.pkFactory, options); - if(callback) callback(null, collection); - return collection; - } catch(err) { - // if(err instanceof MongoError && callback) return callback(err); - if(callback) return callback(err); - throw err; + /** + * The current readPreference of the Db. If not explicitly defined for + * this Db, will be inherited from the parent MongoClient + */ + get readPreference() { + if (this.s.readPreference == null) { + return this.s.client.readPreference; + } + return this.s.readPreference; } - } - - // Strict mode - if(typeof callback != 'function') { - throw toError(f("A callback is required in strict mode. While getting collection %s.", name)); - } - - // Did the user destroy the topology - if(self.serverConfig && self.serverConfig.isDestroyed()) { - return callback(new MongoError('topology was destroyed')); - } - - // Strict mode - this.listCollections({name:name}, options).toArray(function(err, collections) { - if(err != null) return handleCallback(callback, err, null); - if(collections.length == 0) return handleCallback(callback, toError(f("Collection %s does not exist. Currently in strict mode.", name)), null); - - try { - return handleCallback(callback, null, new Collection(self, self.s.topology, self.s.databaseName, name, self.s.pkFactory, options)); - } catch(err) { - return handleCallback(callback, err, null); + get bsonOptions() { + return this.s.bsonOptions; } - }); -} - -define.classMethod('collection', {callback: true, promise:false, returns: [Collection]}); - -function decorateWithWriteConcern(command, self, options) { - // Do we support write concerns 3.4 and higher - if(self.s.topology.capabilities().commandsTakeWriteConcern) { - // Get the write concern settings - var finalOptions = writeConcern(shallowClone(options), self, options); - // Add the write concern to the command - if(finalOptions.writeConcern) { - command.writeConcern = finalOptions.writeConcern; + // get the write Concern + get writeConcern() { + return this.s.writeConcern; } - } -} - -var createCollection = function(self, name, options, callback) { - // Get the write concern options - var finalOptions = writeConcern(shallowClone(options), self, options); - // Did the user destroy the topology - if(self.serverConfig && self.serverConfig.isDestroyed()) return callback(new MongoError('topology was destroyed')); - // Check if we have the name - self.listCollections({name: name}) - .setReadPreference(ReadPreference.PRIMARY) - .toArray(function(err, collections) { - if(err != null) return handleCallback(callback, err, null); - if(collections.length > 0 && finalOptions.strict) { - return handleCallback(callback, MongoError.create({message: f("Collection %s already exists. Currently in strict mode.", name), driver:true}), null); - } else if (collections.length > 0) { - try { return handleCallback(callback, null, new Collection(self, self.s.topology, self.s.databaseName, name, self.s.pkFactory, options)); } - catch(err) { return handleCallback(callback, err); } - } - - // Create collection command - var cmd = {'create':name}; - - // Decorate command with writeConcern if supported - decorateWithWriteConcern(cmd, self, options); - // Add all optional parameters - for(var n in options) { - if(options[n] != null - && typeof options[n] != 'function' && illegalCommandFields.indexOf(n) == -1) { - cmd[n] = options[n]; + get namespace() { + return this.s.namespace.toString(); + } + createCollection(name, options, callback) { + if (typeof options === 'function') + (callback = options), (options = {}); + return (0, execute_operation_1.executeOperation)(this.s.client, new create_collection_1.CreateCollectionOperation(this, name, (0, utils_1.resolveOptions)(this, options)), callback); + } + command(command, options, callback) { + if (typeof options === 'function') + (callback = options), (options = {}); + // Intentionally, we do not inherit options from parent for this operation. + return (0, execute_operation_1.executeOperation)(this.s.client, new run_command_1.RunCommandOperation(this, command, options !== null && options !== void 0 ? options : {}), callback); + } + /** + * Execute an aggregation framework pipeline against the database, needs MongoDB \>= 3.6 + * + * @param pipeline - An array of aggregation stages to be executed + * @param options - Optional settings for the command + */ + aggregate(pipeline = [], options) { + if (arguments.length > 2) { + throw new error_1.MongoInvalidArgumentError('Method "db.aggregate()" accepts at most two arguments'); } - } - - // Force a primary read Preference - finalOptions.readPreference = ReadPreference.PRIMARY; - - // Execute command - self.command(cmd, finalOptions, function(err) { - if(err) return handleCallback(callback, err); - handleCallback(callback, null, new Collection(self, self.s.topology, self.s.databaseName, name, self.s.pkFactory, options)); - }); - }); -} - -/** - * Create a new collection on a server with the specified options. Use this to create capped collections. - * More information about command options available at https://docs.mongodb.com/manual/reference/command/create/ - * - * @method - * @param {string} name the collection name we wish to access. - * @param {object} [options=null] Optional settings. - * @param {(number|string)} [options.w=null] The write concern. - * @param {number} [options.wtimeout=null] The write concern timeout. - * @param {boolean} [options.j=false] Specify a journal write concern. - * @param {boolean} [options.raw=false] Return document results as raw BSON buffers. - * @param {object} [options.pkFactory=null] A primary key factory object for generation of custom _id keys. - * @param {(ReadPreference|string)} [options.readPreference=null] The preferred read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST). - * @param {boolean} [options.serializeFunctions=false] Serialize functions on any object. - * @param {boolean} [options.strict=false] Returns an error if the collection does not exist - * @param {boolean} [options.capped=false] Create a capped collection. - * @param {boolean} [options.autoIndexId=true] Create an index on the _id field of the document, True by default on MongoDB 2.2 or higher off for version < 2.2. - * @param {number} [options.size=null] The size of the capped collection in bytes. - * @param {number} [options.max=null] The maximum number of documents in the capped collection. - * @param {number} [options.flags=null] Optional. Available for the MMAPv1 storage engine only to set the usePowerOf2Sizes and the noPadding flag. - * @param {object} [options.storageEngine=null] Allows users to specify configuration to the storage engine on a per-collection basis when creating a collection on MongoDB 3.0 or higher. - * @param {object} [options.validator=null] Allows users to specify validation rules or expressions for the collection. For more information, see Document Validation on MongoDB 3.2 or higher. - * @param {string} [options.validationLevel=null] Determines how strictly MongoDB applies the validation rules to existing documents during an update on MongoDB 3.2 or higher. - * @param {string} [options.validationAction=null] Determines whether to error on invalid documents or just warn about the violations but allow invalid documents to be inserted on MongoDB 3.2 or higher. - * @param {object} [options.indexOptionDefaults=null] Allows users to specify a default configuration for indexes when creating a collection on MongoDB 3.2 or higher. - * @param {string} [options.viewOn=null] The name of the source collection or view from which to create the view. The name is not the full namespace of the collection or view; i.e. does not include the database name and implies the same database as the view to create on MongoDB 3.4 or higher. - * @param {array} [options.pipeline=null] An array that consists of the aggregation pipeline stage. create creates the view by applying the specified pipeline to the viewOn collection or view on MongoDB 3.4 or higher. - * @param {object} [options.collation=null] Specify collation (MongoDB 3.4 or higher) settings for update operation (see 3.4 documentation for available fields). - * @param {Db~collectionResultCallback} [callback] The results callback - * @return {Promise} returns Promise if no callback passed - */ -Db.prototype.createCollection = function(name, options, callback) { - var self = this; - var args = Array.prototype.slice.call(arguments, 0); - callback = args.pop(); - if(typeof callback != 'function') args.push(callback); - name = args.length ? args.shift() : null; - options = args.length ? args.shift() || {} : {}; - - // Do we have a promisesLibrary - options.promiseLibrary = options.promiseLibrary || this.s.promiseLibrary; - - // Check if the callback is in fact a string - if(typeof callback == 'string') name = callback; - - // Execute the fallback callback - if(typeof callback == 'function') return createCollection(self, name, options, callback); - return new this.s.promiseLibrary(function(resolve, reject) { - createCollection(self, name, options, function(err, r) { - if(err) return reject(err); - resolve(r); - }); - }); -} - -define.classMethod('createCollection', {callback: true, promise:true}); - -/** - * Get all the db statistics. - * - * @method - * @param {object} [options=null] Optional settings. - * @param {number} [options.scale=null] Divide the returned sizes by scale value. - * @param {Db~resultCallback} [callback] The collection result callback - * @return {Promise} returns Promise if no callback passed - */ -Db.prototype.stats = function(options, callback) { - if(typeof options == 'function') callback = options, options = {}; - options = options || {}; - // Build command object - var commandObject = { dbStats:true }; - // Check if we have the scale value - if(options['scale'] != null) commandObject['scale'] = options['scale']; - - // If we have a readPreference set - if(options.readPreference == null && this.s.readPreference) { - options.readPreference = this.s.readPreference; - } - - // Execute the command - return this.command(commandObject, options, callback); -} - -define.classMethod('stats', {callback: true, promise:true}); - -// Transformation methods for cursor results -var listCollectionsTranforms = function(databaseName) { - var matching = f('%s.', databaseName); - - return { - doc: function(doc) { - var index = doc.name.indexOf(matching); - // Remove database name if available - if(doc.name && index == 0) { - doc.name = doc.name.substr(index + matching.length); - } - - return doc; + if (typeof pipeline === 'function') { + throw new error_1.MongoInvalidArgumentError('Argument "pipeline" must not be function'); + } + if (typeof options === 'function') { + throw new error_1.MongoInvalidArgumentError('Argument "options" must not be function'); + } + return new aggregation_cursor_1.AggregationCursor(this.s.client, this.s.namespace, pipeline, (0, utils_1.resolveOptions)(this, options)); } - } -} - -/** - * Get the list of all collection information for the specified db. - * - * @method - * @param {object} filter Query to filter collections by - * @param {object} [options=null] Optional settings. - * @param {number} [options.batchSize=null] The batchSize for the returned command cursor or if pre 2.8 the systems batch collection - * @param {(ReadPreference|string)} [options.readPreference=null] The preferred read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST). - * @return {CommandCursor} - */ -Db.prototype.listCollections = function(filter, options) { - filter = filter || {}; - options = options || {}; - - // Shallow clone the object - options = shallowClone(options); - // Set the promise library - options.promiseLibrary = this.s.promiseLibrary; - - // Ensure valid readPreference - if(options.readPreference) { - options.readPreference = convertReadPreference(options.readPreference); - } - - // We have a list collections command - if(this.serverConfig.capabilities().hasListCollectionsCommand) { - // Cursor options - var cursor = options.batchSize ? {batchSize: options.batchSize} : {} - // Build the command - var command = { listCollections : true, filter: filter, cursor: cursor }; - // Set the AggregationCursor constructor - options.cursorFactory = CommandCursor; - // Create the cursor - cursor = this.s.topology.cursor(f('%s.$cmd', this.s.databaseName), command, options); - // Do we have a readPreference, apply it - if(options.readPreference) { - cursor.setReadPreference(options.readPreference); + /** Return the Admin db instance */ + admin() { + return new admin_1.Admin(this); } - // Return the cursor - return cursor; - } - - // We cannot use the listCollectionsCommand - if(!this.serverConfig.capabilities().hasListCollectionsCommand) { - // If we have legacy mode and have not provided a full db name filter it - if(typeof filter.name == 'string' && !(new RegExp('^' + this.databaseName + '\\.').test(filter.name))) { - filter = shallowClone(filter); - filter.name = f('%s.%s', this.s.databaseName, filter.name); + /** + * Returns a reference to a MongoDB Collection. If it does not exist it will be created implicitly. + * + * @param name - the collection name we wish to access. + * @returns return the new Collection instance + */ + collection(name, options = {}) { + if (typeof options === 'function') { + throw new error_1.MongoInvalidArgumentError('The callback form of this helper has been removed.'); + } + const finalOptions = (0, utils_1.resolveOptions)(this, options); + return new collection_1.Collection(this, name, finalOptions); } - } - - // No filter, filter by current database - if(filter == null) { - filter.name = f('/%s/', this.s.databaseName); - } - - // Rewrite the filter to use $and to filter out indexes - if(filter.name) { - filter = {$and: [{name: filter.name}, {name:/^((?!\$).)*$/}]}; - } else { - filter = {name:/^((?!\$).)*$/}; - } - - // Return options - var _options = {transforms: listCollectionsTranforms(this.s.databaseName)} - // Get the cursor - cursor = this.collection(Db.SYSTEM_NAMESPACE_COLLECTION).find(filter, _options); - // Do we have a readPreference, apply it - if(options.readPreference) cursor.setReadPreference(options.readPreference); - // Set the passed in batch size if one was provided - if(options.batchSize) cursor = cursor.batchSize(options.batchSize); - // We have a fallback mode using legacy systems collections - return cursor; -}; - -define.classMethod('listCollections', {callback: false, promise:false, returns: [CommandCursor]}); - -var evaluate = function(self, code, parameters, options, callback) { - var finalCode = code; - var finalParameters = []; - - // Did the user destroy the topology - if(self.serverConfig && self.serverConfig.isDestroyed()) return callback(new MongoError('topology was destroyed')); - - // If not a code object translate to one - if(!(finalCode && finalCode._bsontype == 'Code')) finalCode = new Code(finalCode); - // Ensure the parameters are correct - if(parameters != null && !Array.isArray(parameters) && typeof parameters !== 'function') { - finalParameters = [parameters]; - } else if(parameters != null && Array.isArray(parameters) && typeof parameters !== 'function') { - finalParameters = parameters; - } - - // Create execution selector - var cmd = {'$eval':finalCode, 'args':finalParameters}; - // Check if the nolock parameter is passed in - if(options['nolock']) { - cmd['nolock'] = options['nolock']; - } - - // Set primary read preference - options.readPreference = new CoreReadPreference(ReadPreference.PRIMARY); - - // Execute the command - self.command(cmd, options, function(err, result) { - if(err) return handleCallback(callback, err, null); - if(result && result.ok == 1) return handleCallback(callback, null, result.retval); - if(result) return handleCallback(callback, MongoError.create({message: f("eval failed: %s", result.errmsg), driver:true}), null); - handleCallback(callback, err, result); - }); -} - -/** - * Evaluate JavaScript on the server - * - * @method - * @param {Code} code JavaScript to execute on server. - * @param {(object|array)} parameters The parameters for the call. - * @param {object} [options=null] Optional settings. - * @param {boolean} [options.nolock=false] Tell MongoDB not to block on the evaluation of the javascript. - * @param {Db~resultCallback} [callback] The results callback - * @deprecated Eval is deprecated on MongoDB 3.2 and forward - * @return {Promise} returns Promise if no callback passed - */ -Db.prototype.eval = function(code, parameters, options, callback) { - var self = this; - var args = Array.prototype.slice.call(arguments, 1); - callback = args.pop(); - if(typeof callback != 'function') args.push(callback); - parameters = args.length ? args.shift() : parameters; - options = args.length ? args.shift() || {} : {}; - - // Check if the callback is in fact a string - if(typeof callback == 'function') return evaluate(self, code, parameters, options, callback); - // Execute the command - return new this.s.promiseLibrary(function(resolve, reject) { - evaluate(self, code, parameters, options, function(err, r) { - if(err) return reject(err); - resolve(r); - }); - }); -}; - -define.classMethod('eval', {callback: true, promise:true}); - -/** - * Rename a collection. - * - * @method - * @param {string} fromCollection Name of current collection to rename. - * @param {string} toCollection New name of of the collection. - * @param {object} [options=null] Optional settings. - * @param {boolean} [options.dropTarget=false] Drop the target name collection if it previously exists. - * @param {Db~collectionResultCallback} [callback] The results callback - * @return {Promise} returns Promise if no callback passed - */ -Db.prototype.renameCollection = function(fromCollection, toCollection, options, callback) { - var self = this; - if(typeof options == 'function') callback = options, options = {}; - options = options || {}; - // Add return new collection - options.new_collection = true; - - // Check if the callback is in fact a string - if(typeof callback == 'function') { - return this.collection(fromCollection).rename(toCollection, options, callback); - } - - // Return a promise - return new this.s.promiseLibrary(function(resolve, reject) { - self.collection(fromCollection).rename(toCollection, options, function(err, r) { - if(err) return reject(err); - resolve(r); - }); - }); -}; - -define.classMethod('renameCollection', {callback: true, promise:true}); - -/** - * Drop a collection from the database, removing it permanently. New accesses will create a new collection. - * - * @method - * @param {string} name Name of collection to drop - * @param {Db~resultCallback} [callback] The results callback - * @return {Promise} returns Promise if no callback passed - */ -Db.prototype.dropCollection = function(name, options, callback) { - var self = this; - if(typeof options == 'function') callback = options, options = {}; - options = options || {}; - - // Command to execute - var cmd = {'drop':name} - - // Decorate with write concern - decorateWithWriteConcern(cmd, self, options); - - // options - options = assign({}, this.s.options, {readPreference: ReadPreference.PRIMARY}); - - // Check if the callback is in fact a string - if(typeof callback == 'function') return this.command(cmd, options, function(err, result) { - // Did the user destroy the topology - if(self.serverConfig && self.serverConfig.isDestroyed()) return callback(new MongoError('topology was destroyed')); - if(err) return handleCallback(callback, err); - if(result.ok) return handleCallback(callback, null, true); - handleCallback(callback, null, false); - }); - - // Clone the options - options = shallowClone(self.s.options); - // Set readPreference PRIMARY - options.readPreference = ReadPreference.PRIMARY; - - // Execute the command - return new this.s.promiseLibrary(function(resolve, reject) { - // Execute command - self.command(cmd, options, function(err, result) { - // Did the user destroy the topology - if(self.serverConfig && self.serverConfig.isDestroyed()) return reject(new MongoError('topology was destroyed')); - if(err) return reject(err); - if(result.ok) return resolve(true); - resolve(false); - }); - }); -}; - -define.classMethod('dropCollection', {callback: true, promise:true}); - -/** - * Drop a database, removing it permanently from the server. - * - * @method - * @param {Db~resultCallback} [callback] The results callback - * @return {Promise} returns Promise if no callback passed - */ -Db.prototype.dropDatabase = function(options, callback) { - var self = this; - if(typeof options == 'function') callback = options, options = {}; - options = options || {}; - // Drop database command - var cmd = {'dropDatabase':1}; - - // Decorate with write concern - decorateWithWriteConcern(cmd, self, options); - - // Ensure primary only - options = assign({}, this.s.options, {readPreference: ReadPreference.PRIMARY}); - - // Check if the callback is in fact a string - if(typeof callback == 'function') return this.command(cmd, options, function(err, result) { - // Did the user destroy the topology - if(self.serverConfig && self.serverConfig.isDestroyed()) return callback(new MongoError('topology was destroyed')); - if(callback == null) return; - if(err) return handleCallback(callback, err, null); - handleCallback(callback, null, result.ok ? true : false); - }); - - // Execute the command - return new this.s.promiseLibrary(function(resolve, reject) { - // Execute command - self.command(cmd, options, function(err, result) { - // Did the user destroy the topology - if(self.serverConfig && self.serverConfig.isDestroyed()) return reject(new MongoError('topology was destroyed')); - if(err) return reject(err); - if(result.ok) return resolve(true); - resolve(false); - }); - }); -} - -define.classMethod('dropDatabase', {callback: true, promise:true}); - -/** - * The callback format for the collections method. - * @callback Db~collectionsResultCallback - * @param {MongoError} error An error instance representing the error during the execution. - * @param {Collection[]} collections An array of all the collections objects for the db instance. - */ -var collections = function(self, callback) { - // Let's get the collection names - self.listCollections().toArray(function(err, documents) { - if(err != null) return handleCallback(callback, err, null); - // Filter collections removing any illegal ones - documents = documents.filter(function(doc) { - return doc.name.indexOf('$') == -1; - }); - - // Return the collection objects - handleCallback(callback, null, documents.map(function(d) { - return new Collection(self, self.s.topology, self.s.databaseName, d.name, self.s.pkFactory, self.s.options); - })); - }); -} - -/** - * Fetch all collections for the current db. - * - * @method - * @param {Db~collectionsResultCallback} [callback] The results callback - * @return {Promise} returns Promise if no callback passed - */ -Db.prototype.collections = function(callback) { - var self = this; - - // Return the callback - if(typeof callback == 'function') return collections(self, callback); - // Return the promise - return new self.s.promiseLibrary(function(resolve, reject) { - collections(self, function(err, r) { - if(err) return reject(err); - resolve(r); - }); - }); -}; - -define.classMethod('collections', {callback: true, promise:true}); - -/** - * Runs a command on the database as admin. - * @method - * @param {object} command The command hash - * @param {object} [options=null] Optional settings. - * @param {(ReadPreference|string)} [options.readPreference=null] The preferred read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST). - * @param {Db~resultCallback} [callback] The command result callback - * @return {Promise} returns Promise if no callback passed - */ -Db.prototype.executeDbAdminCommand = function(selector, options, callback) { - var self = this; - if(typeof options == 'function') callback = options, options = {}; - options = options || {}; - - // Return the callback - if(typeof callback == 'function') { - // Convert read preference - if(options.readPreference) { - options.readPreference = convertReadPreference(options.readPreference) + stats(options, callback) { + if (typeof options === 'function') + (callback = options), (options = {}); + return (0, execute_operation_1.executeOperation)(this.s.client, new stats_1.DbStatsOperation(this, (0, utils_1.resolveOptions)(this, options)), callback); } - - return self.s.topology.command('admin.$cmd', selector, options, function(err, result) { - // Did the user destroy the topology - if(self.serverConfig && self.serverConfig.isDestroyed()) return callback(new MongoError('topology was destroyed')); - if(err) return handleCallback(callback, err); - handleCallback(callback, null, result.result); - }); - } - - // Return promise - return new self.s.promiseLibrary(function(resolve, reject) { - self.s.topology.command('admin.$cmd', selector, options, function(err, result) { - // Did the user destroy the topology - if(self.serverConfig && self.serverConfig.isDestroyed()) return reject(new MongoError('topology was destroyed')); - if(err) return reject(err); - resolve(result.result); - }); - }); -}; - -define.classMethod('executeDbAdminCommand', {callback: true, promise:true}); - -/** - * Creates an index on the db and collection collection. - * @method - * @param {string} name Name of the collection to create the index on. - * @param {(string|object)} fieldOrSpec Defines the index. - * @param {object} [options=null] Optional settings. - * @param {(number|string)} [options.w=null] The write concern. - * @param {number} [options.wtimeout=null] The write concern timeout. - * @param {boolean} [options.j=false] Specify a journal write concern. - * @param {boolean} [options.unique=false] Creates an unique index. - * @param {boolean} [options.sparse=false] Creates a sparse index. - * @param {boolean} [options.background=false] Creates the index in the background, yielding whenever possible. - * @param {boolean} [options.dropDups=false] A unique index cannot be created on a key that has pre-existing duplicate values. If you would like to create the index anyway, keeping the first document the database indexes and deleting all subsequent documents that have duplicate value - * @param {number} [options.min=null] For geospatial indexes set the lower bound for the co-ordinates. - * @param {number} [options.max=null] For geospatial indexes set the high bound for the co-ordinates. - * @param {number} [options.v=null] Specify the format version of the indexes. - * @param {number} [options.expireAfterSeconds=null] Allows you to expire data on indexes applied to a data (MongoDB 2.2 or higher) - * @param {number} [options.name=null] Override the autogenerated index name (useful if the resulting name is larger than 128 bytes) - * @param {object} [options.partialFilterExpression=null] Creates a partial index based on the given filter object (MongoDB 3.2 or higher) - * @param {Db~resultCallback} [callback] The command result callback - * @return {Promise} returns Promise if no callback passed - */ -Db.prototype.createIndex = function(name, fieldOrSpec, options, callback) { - var self = this; - var args = Array.prototype.slice.call(arguments, 2); - callback = args.pop(); - if(typeof callback != 'function') args.push(callback); - options = args.length ? args.shift() || {} : {}; - options = typeof callback === 'function' ? options : callback; - options = options == null ? {} : options; - // Shallow clone the options - options = shallowClone(options); - - // If we have a callback fallback - if(typeof callback == 'function') return createIndex(self, name, fieldOrSpec, options, callback); - // Return a promise - return new this.s.promiseLibrary(function(resolve, reject) { - createIndex(self, name, fieldOrSpec, options, function(err, r) { - if(err) return reject(err); - resolve(r); - }); - }); -}; - -var createIndex = function(self, name, fieldOrSpec, options, callback) { - // Get the write concern options - var finalOptions = writeConcern({}, self, options, { readPreference: ReadPreference.PRIMARY }); - // Ensure we have a callback - if(finalOptions.writeConcern && typeof callback != 'function') { - throw MongoError.create({message: "Cannot use a writeConcern without a provided callback", driver:true}); - } - - // Run only against primary - options.readPreference = ReadPreference.PRIMARY; - - // Did the user destroy the topology - if(self.serverConfig && self.serverConfig.isDestroyed()) return callback(new MongoError('topology was destroyed')); - - // Attempt to run using createIndexes command - createIndexUsingCreateIndexes(self, name, fieldOrSpec, options, function(err, result) { - if(err == null) return handleCallback(callback, err, result); - - // 67 = 'CannotCreateIndex' (malformed index options) - // 85 = 'IndexOptionsConflict' (index already exists with different options) - // 11000 = 'DuplicateKey' (couldn't build unique index because of dupes) - // 11600 = 'InterruptedAtShutdown' (interrupted at shutdown) - // These errors mean that the server recognized `createIndex` as a command - // and so we don't need to fallback to an insert. - if(err.code === 67 || err.code == 11000 || err.code === 85 || err.code == 11600) { - return handleCallback(callback, err, result); + listCollections(filter = {}, options = {}) { + return new list_collections_cursor_1.ListCollectionsCursor(this, filter, (0, utils_1.resolveOptions)(this, options)); } - - // Create command - var doc = createCreateIndexCommand(self, name, fieldOrSpec, options); - // Set no key checking - finalOptions.checkKeys = false; - // Insert document - self.s.topology.insert(f("%s.%s", self.s.databaseName, Db.SYSTEM_INDEX_COLLECTION), doc, finalOptions, function(err, result) { - if(callback == null) return; - if(err) return handleCallback(callback, err); - if(result == null) return handleCallback(callback, null, null); - if(result.result.writeErrors) return handleCallback(callback, MongoError.create(result.result.writeErrors[0]), null); - handleCallback(callback, null, doc.name); - }); - }); -} - -define.classMethod('createIndex', {callback: true, promise:true}); - -/** - * Ensures that an index exists, if it does not it creates it - * @method - * @deprecated since version 2.0 - * @param {string} name The index name - * @param {(string|object)} fieldOrSpec Defines the index. - * @param {object} [options=null] Optional settings. - * @param {(number|string)} [options.w=null] The write concern. - * @param {number} [options.wtimeout=null] The write concern timeout. - * @param {boolean} [options.j=false] Specify a journal write concern. - * @param {boolean} [options.unique=false] Creates an unique index. - * @param {boolean} [options.sparse=false] Creates a sparse index. - * @param {boolean} [options.background=false] Creates the index in the background, yielding whenever possible. - * @param {boolean} [options.dropDups=false] A unique index cannot be created on a key that has pre-existing duplicate values. If you would like to create the index anyway, keeping the first document the database indexes and deleting all subsequent documents that have duplicate value - * @param {number} [options.min=null] For geospatial indexes set the lower bound for the co-ordinates. - * @param {number} [options.max=null] For geospatial indexes set the high bound for the co-ordinates. - * @param {number} [options.v=null] Specify the format version of the indexes. - * @param {number} [options.expireAfterSeconds=null] Allows you to expire data on indexes applied to a data (MongoDB 2.2 or higher) - * @param {number} [options.name=null] Override the autogenerated index name (useful if the resulting name is larger than 128 bytes) - * @param {Db~resultCallback} [callback] The command result callback - * @return {Promise} returns Promise if no callback passed - */ -Db.prototype.ensureIndex = function(name, fieldOrSpec, options, callback) { - var self = this; - if(typeof options == 'function') callback = options, options = {}; - options = options || {}; - - // If we have a callback fallback - if(typeof callback == 'function') return ensureIndex(self, name, fieldOrSpec, options, callback); - - // Return a promise - return new this.s.promiseLibrary(function(resolve, reject) { - ensureIndex(self, name, fieldOrSpec, options, function(err, r) { - if(err) return reject(err); - resolve(r); - }); - }); -}; - -var ensureIndex = function(self, name, fieldOrSpec, options, callback) { - // Get the write concern options - var finalOptions = writeConcern({}, self, options); - // Create command - var selector = createCreateIndexCommand(self, name, fieldOrSpec, options); - var index_name = selector.name; - - // Did the user destroy the topology - if(self.serverConfig && self.serverConfig.isDestroyed()) return callback(new MongoError('topology was destroyed')); - - // Merge primary readPreference - finalOptions.readPreference = ReadPreference.PRIMARY - - // Check if the index already exists - self.indexInformation(name, finalOptions, function(err, indexInformation) { - if(err != null && err.code != 26) return handleCallback(callback, err, null); - // If the index does not exist, create it - if(indexInformation == null || !indexInformation[index_name]) { - self.createIndex(name, fieldOrSpec, options, callback); - } else { - if(typeof callback === 'function') return handleCallback(callback, null, index_name); + renameCollection(fromCollection, toCollection, options, callback) { + if (typeof options === 'function') + (callback = options), (options = {}); + // Intentionally, we do not inherit options from parent for this operation. + options = { ...options, readPreference: read_preference_1.ReadPreference.PRIMARY }; + // Add return new collection + options.new_collection = true; + return (0, execute_operation_1.executeOperation)(this.s.client, new rename_1.RenameOperation(this.collection(fromCollection), toCollection, options), callback); } - }); -} - -define.classMethod('ensureIndex', {callback: true, promise:true}); - -Db.prototype.addChild = function(db) { - if(this.s.parentDb) return this.s.parentDb.addChild(db); - this.s.children.push(db); -} - -/** - * Create a new Db instance sharing the current socket connections. Be aware that the new db instances are - * related in a parent-child relationship to the original instance so that events are correctly emitted on child - * db instances. Child db instances are cached so performing db('db1') twice will return the same instance. - * You can control these behaviors with the options noListener and returnNonCachedInstance. - * - * @method - * @param {string} name The name of the database we want to use. - * @param {object} [options=null] Optional settings. - * @param {boolean} [options.noListener=false] Do not make the db an event listener to the original connection. - * @param {boolean} [options.returnNonCachedInstance=false] Control if you want to return a cached instance or have a new one created - * @return {Db} - */ -Db.prototype.db = function(dbName, options) { - options = options || {}; - - // Copy the options and add out internal override of the not shared flag - var finalOptions = assign({}, this.options, options); - - // Do we have the db in the cache already - if(this.s.dbCache[dbName] && finalOptions.returnNonCachedInstance !== true) { - return this.s.dbCache[dbName]; - } - - // Add current db as parentDb - if(finalOptions.noListener == null || finalOptions.noListener == false) { - finalOptions.parentDb = this; - } - - // Add promiseLibrary - finalOptions.promiseLibrary = this.s.promiseLibrary; - - // Return the db object - var db = new Db(dbName, this.s.topology, finalOptions) - - // Add as child - if(finalOptions.noListener == null || finalOptions.noListener == false) { - this.addChild(db); - } - - // Add the db to the cache - this.s.dbCache[dbName] = db; - // Return the database - return db; -}; - -define.classMethod('db', {callback: false, promise:false, returns: [Db]}); - -var _executeAuthCreateUserCommand = function(self, username, password, options, callback) { - // Special case where there is no password ($external users) - if(typeof username == 'string' - && password != null && typeof password == 'object') { - options = password; - password = null; - } - - // Unpack all options - if(typeof options == 'function') { - callback = options; - options = {}; - } - - // Error out if we digestPassword set - if(options.digestPassword != null) { - throw toError("The digestPassword option is not supported via add_user. Please use db.command('createUser', ...) instead for this option."); - } - - // Get additional values - var customData = options.customData != null ? options.customData : {}; - var roles = Array.isArray(options.roles) ? options.roles : []; - var maxTimeMS = typeof options.maxTimeMS == 'number' ? options.maxTimeMS : null; - - // If not roles defined print deprecated message - if(roles.length == 0) { - console.log("Creating a user without roles is deprecated in MongoDB >= 2.6"); - } - - // Get the error options - var commandOptions = {writeCommand:true}; - if(options['dbName']) commandOptions.dbName = options['dbName']; - - // Add maxTimeMS to options if set - if(maxTimeMS != null) commandOptions.maxTimeMS = maxTimeMS; - - // Check the db name and add roles if needed - if((self.databaseName.toLowerCase() == 'admin' || options.dbName == 'admin') && !Array.isArray(options.roles)) { - roles = ['root'] - } else if(!Array.isArray(options.roles)) { - roles = ['dbOwner'] - } - - // Build the command to execute - var command = { - createUser: username - , customData: customData - , roles: roles - , digestPassword:false - } - - // Apply write concern to command - command = writeConcern(command, self, options); - - // Use node md5 generator - var md5 = crypto.createHash('md5'); - // Generate keys used for authentication - md5.update(username + ":mongo:" + password); - var userPassword = md5.digest('hex'); - - // No password - if(typeof password == 'string') { - command.pwd = userPassword; - } - - // Force write using primary - commandOptions.readPreference = ReadPreference.primary; - - // Execute the command - self.command(command, commandOptions, function(err, result) { - if(err && err.ok == 0 && err.code == undefined) return handleCallback(callback, {code: -5000}, null); - if(err) return handleCallback(callback, err, null); - handleCallback(callback, !result.ok ? toError(result) : null - , result.ok ? [{user: username, pwd: ''}] : null); - }) -} - -var addUser = function(self, username, password, options, callback) { - // Did the user destroy the topology - if(self.serverConfig && self.serverConfig.isDestroyed()) return callback(new MongoError('topology was destroyed')); - // Attempt to execute auth command - _executeAuthCreateUserCommand(self, username, password, options, function(err, r) { - // We need to perform the backward compatible insert operation - if(err && err.code == -5000) { - var finalOptions = writeConcern(shallowClone(options), self, options); - // Use node md5 generator - var md5 = crypto.createHash('md5'); - // Generate keys used for authentication - md5.update(username + ":mongo:" + password); - var userPassword = md5.digest('hex'); - - // If we have another db set - var db = options.dbName ? self.db(options.dbName) : self; - - // Fetch a user collection - var collection = db.collection(Db.SYSTEM_USER_COLLECTION); - - // Check if we are inserting the first user - collection.count({}, function(err, count) { - // We got an error (f.ex not authorized) - if(err != null) return handleCallback(callback, err, null); - // Check if the user exists and update i - collection.find({user: username}, {dbName: options['dbName']}).toArray(function(err) { - // We got an error (f.ex not authorized) - if(err != null) return handleCallback(callback, err, null); - // Add command keys - finalOptions.upsert = true; - - // We have a user, let's update the password or upsert if not - collection.update({user: username},{$set: {user: username, pwd: userPassword}}, finalOptions, function(err) { - if(count == 0 && err) return handleCallback(callback, null, [{user:username, pwd:userPassword}]); - if(err) return handleCallback(callback, err, null) - handleCallback(callback, null, [{user:username, pwd:userPassword}]); - }); - }); - }); - - return; + dropCollection(name, options, callback) { + if (typeof options === 'function') + (callback = options), (options = {}); + return (0, execute_operation_1.executeOperation)(this.s.client, new drop_1.DropCollectionOperation(this, name, (0, utils_1.resolveOptions)(this, options)), callback); } - - if(err) return handleCallback(callback, err); - handleCallback(callback, err, r); - }); -} - -/** - * Add a user to the database. - * @method - * @param {string} username The username. - * @param {string} password The password. - * @param {object} [options=null] Optional settings. - * @param {(number|string)} [options.w=null] The write concern. - * @param {number} [options.wtimeout=null] The write concern timeout. - * @param {boolean} [options.j=false] Specify a journal write concern. - * @param {object} [options.customData=null] Custom data associated with the user (only Mongodb 2.6 or higher) - * @param {object[]} [options.roles=null] Roles associated with the created user (only Mongodb 2.6 or higher) - * @param {Db~resultCallback} [callback] The command result callback - * @return {Promise} returns Promise if no callback passed - */ -Db.prototype.addUser = function(username, password, options, callback) { - // Unpack the parameters - var self = this; - var args = Array.prototype.slice.call(arguments, 2); - callback = args.pop(); - if(typeof callback != 'function') args.push(callback); - options = args.length ? args.shift() || {} : {}; - - // If we have a callback fallback - if(typeof callback == 'function') return addUser(self, username, password, options, callback); - - // Return a promise - return new this.s.promiseLibrary(function(resolve, reject) { - addUser(self, username, password, options, function(err, r) { - if(err) return reject(err); - resolve(r); - }); - }); -}; - -define.classMethod('addUser', {callback: true, promise:true}); - -var _executeAuthRemoveUserCommand = function(self, username, options, callback) { - if(typeof options == 'function') callback = options, options = {}; - // Did the user destroy the topology - if(self.serverConfig && self.serverConfig.isDestroyed()) return callback(new MongoError('topology was destroyed')); - // Get the error options - var commandOptions = {writeCommand:true}; - if(options['dbName']) commandOptions.dbName = options['dbName']; - - // Get additional values - var maxTimeMS = typeof options.maxTimeMS == 'number' ? options.maxTimeMS : null; - - // Add maxTimeMS to options if set - if(maxTimeMS != null) commandOptions.maxTimeMS = maxTimeMS; - - // Build the command to execute - var command = { - dropUser: username - } - - // Apply write concern to command - command = writeConcern(command, self, options); - - // Force write using primary - commandOptions.readPreference = ReadPreference.primary; - - // Execute the command - self.command(command, commandOptions, function(err, result) { - if(err && !err.ok && err.code == undefined) return handleCallback(callback, {code: -5000}); - if(err) return handleCallback(callback, err, null); - handleCallback(callback, null, result.ok ? true : false); - }) -} - -var removeUser = function(self, username, options, callback) { - // Attempt to execute command - _executeAuthRemoveUserCommand(self, username, options, function(err, result) { - if(err && err.code == -5000) { - var finalOptions = writeConcern(shallowClone(options), self, options); - // If we have another db set - var db = options.dbName ? self.db(options.dbName) : self; - - // Fetch a user collection - var collection = db.collection(Db.SYSTEM_USER_COLLECTION); - - // Locate the user - collection.findOne({user: username}, {}, function(err, user) { - if(user == null) return handleCallback(callback, err, false); - collection.remove({user: username}, finalOptions, function(err) { - handleCallback(callback, err, true); - }); - }); - - return; + dropDatabase(options, callback) { + if (typeof options === 'function') + (callback = options), (options = {}); + return (0, execute_operation_1.executeOperation)(this.s.client, new drop_1.DropDatabaseOperation(this, (0, utils_1.resolveOptions)(this, options)), callback); } - - if(err) return handleCallback(callback, err); - handleCallback(callback, err, result); - }); -} - -define.classMethod('removeUser', {callback: true, promise:true}); - -/** - * Remove a user from a database - * @method - * @param {string} username The username. - * @param {object} [options=null] Optional settings. - * @param {(number|string)} [options.w=null] The write concern. - * @param {number} [options.wtimeout=null] The write concern timeout. - * @param {boolean} [options.j=false] Specify a journal write concern. - * @param {Db~resultCallback} [callback] The command result callback - * @return {Promise} returns Promise if no callback passed - */ -Db.prototype.removeUser = function(username, options, callback) { - // Unpack the parameters - var self = this; - var args = Array.prototype.slice.call(arguments, 1); - callback = args.pop(); - if(typeof callback != 'function') args.push(callback); - options = args.length ? args.shift() || {} : {}; - - // If we have a callback fallback - if(typeof callback == 'function') return removeUser(self, username, options, callback); - - // Return a promise - return new this.s.promiseLibrary(function(resolve, reject) { - removeUser(self, username, options, function(err, r) { - if(err) return reject(err); - resolve(r); - }); - }); -}; - -/** - * Authenticate a user against the server. - * @method - * @param {string} username The username. - * @param {string} [password] The password. - * @param {object} [options=null] Optional settings. - * @param {string} [options.authMechanism=MONGODB-CR] The authentication mechanism to use, GSSAPI, MONGODB-CR, MONGODB-X509, PLAIN - * @param {Db~resultCallback} [callback] The command result callback - * @return {Promise} returns Promise if no callback passed - * @deprecated This method will no longer be available in the next major release 3.x as MongoDB 3.6 will only allow auth against users in the admin db and will no longer allow multiple credentials on a socket. Please authenticate using MongoClient.connect with auth credentials. - */ -Db.prototype.authenticate = function(username, password, options, callback) { - console.warn("Db.prototype.authenticate method will no longer be available in the next major release 3.x as MongoDB 3.6 will only allow auth against users in the admin db and will no longer allow multiple credentials on a socket. Please authenticate using MongoClient.connect with auth credentials."); - return authenticate.apply(this, [this].concat(Array.prototype.slice.call(arguments))); -}; - -define.classMethod('authenticate', {callback: true, promise:true}); - -/** - * Logout user from server, fire off on all connections and remove all auth info - * @method - * @param {object} [options=null] Optional settings. - * @param {string} [options.dbName=null] Logout against different database than current. - * @param {Db~resultCallback} [callback] The command result callback - * @return {Promise} returns Promise if no callback passed - */ -Db.prototype.logout = function(options, callback) { - var self = this; - if(typeof options == 'function') callback = options, options = {}; - options = options || {}; - - // Establish the correct database name - var dbName = this.s.authSource ? this.s.authSource : this.s.databaseName; - dbName = options.dbName ? options.dbName : dbName; - - // If we have a callback - if(typeof callback == 'function') { - return self.s.topology.logout(dbName, function(err) { - if(err) return callback(err); - callback(null, true); - }); - } - - // Return a promise - return new this.s.promiseLibrary(function(resolve, reject) { - self.s.topology.logout(dbName, function(err) { - if(err) return reject(err); - resolve(true); - }); - }); -} - -define.classMethod('logout', {callback: true, promise:true}); - -/** - * Retrieves this collections index info. - * @method - * @param {string} name The name of the collection. - * @param {object} [options=null] Optional settings. - * @param {boolean} [options.full=false] Returns the full raw index information. - * @param {(ReadPreference|string)} [options.readPreference=null] The preferred read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST). - * @param {Db~resultCallback} [callback] The command result callback - * @return {Promise} returns Promise if no callback passed - */ -Db.prototype.indexInformation = function(name, options, callback) { - var self = this; - if(typeof options == 'function') callback = options, options = {}; - options = options || {}; - - // If we have a callback fallback - if(typeof callback == 'function') return indexInformation(self, name, options, callback); - - // Return a promise - return new this.s.promiseLibrary(function(resolve, reject) { - indexInformation(self, name, options, function(err, r) { - if(err) return reject(err); - resolve(r); - }); - }); -}; - -var indexInformation = function(self, name, options, callback) { - // If we specified full information - var full = options['full'] == null ? false : options['full']; - - // Did the user destroy the topology - if(self.serverConfig && self.serverConfig.isDestroyed()) return callback(new MongoError('topology was destroyed')); - // Process all the results from the index command and collection - var processResults = function(indexes) { - // Contains all the information - var info = {}; - // Process all the indexes - for(var i = 0; i < indexes.length; i++) { - var index = indexes[i]; - // Let's unpack the object - info[index.name] = []; - for(var name in index.key) { - info[index.name].push([name, index.key[name]]); - } + collections(options, callback) { + if (typeof options === 'function') + (callback = options), (options = {}); + return (0, execute_operation_1.executeOperation)(this.s.client, new collections_1.CollectionsOperation(this, (0, utils_1.resolveOptions)(this, options)), callback); } - - return info; - } - - // Get the list of indexes of the specified collection - self.collection(name).listIndexes(options).toArray(function(err, indexes) { - if(err) return callback(toError(err)); - if(!Array.isArray(indexes)) return handleCallback(callback, null, []); - if(full) return handleCallback(callback, null, indexes); - handleCallback(callback, null, processResults(indexes)); - }); -} - -define.classMethod('indexInformation', {callback: true, promise:true}); - -var createCreateIndexCommand = function(db, name, fieldOrSpec, options) { - var indexParameters = parseIndexOptions(fieldOrSpec); - var fieldHash = indexParameters.fieldHash; - - // Generate the index name - var indexName = typeof options.name == 'string' ? options.name : indexParameters.name; - var selector = { - 'ns': db.databaseName + "." + name, 'key': fieldHash, 'name': indexName - } - - // Ensure we have a correct finalUnique - var finalUnique = options == null || 'object' === typeof options ? false : options; - // Set up options - options = options == null || typeof options == 'boolean' ? {} : options; - - // Add all the options - var keysToOmit = Object.keys(selector); - for(var optionName in options) { - if(keysToOmit.indexOf(optionName) == -1) { - selector[optionName] = options[optionName]; + createIndex(name, indexSpec, options, callback) { + if (typeof options === 'function') + (callback = options), (options = {}); + return (0, execute_operation_1.executeOperation)(this.s.client, new indexes_1.CreateIndexOperation(this, name, indexSpec, (0, utils_1.resolveOptions)(this, options)), callback); } - } - - if(selector['unique'] == null) selector['unique'] = finalUnique; - - // Remove any write concern operations - var removeKeys = ['w', 'wtimeout', 'j', 'fsync', 'readPreference']; - for(var i = 0; i < removeKeys.length; i++) { - delete selector[removeKeys[i]]; - } - - // Return the command creation selector - return selector; -} - -var createIndexUsingCreateIndexes = function(self, name, fieldOrSpec, options, callback) { - // Build the index - var indexParameters = parseIndexOptions(fieldOrSpec); - // Generate the index name - var indexName = typeof options.name == 'string' ? options.name : indexParameters.name; - // Set up the index - var indexes = [{ name: indexName, key: indexParameters.fieldHash }]; - // merge all the options - var keysToOmit = Object.keys(indexes[0]); - for(var optionName in options) { - if(keysToOmit.indexOf(optionName) == -1) { - indexes[0][optionName] = options[optionName]; + addUser(username, password, options, callback) { + if (typeof password === 'function') { + (callback = password), (password = undefined), (options = {}); + } + else if (typeof password !== 'string') { + if (typeof options === 'function') { + (callback = options), (options = password), (password = undefined); + } + else { + (options = password), (callback = undefined), (password = undefined); + } + } + else { + if (typeof options === 'function') + (callback = options), (options = {}); + } + return (0, execute_operation_1.executeOperation)(this.s.client, new add_user_1.AddUserOperation(this, username, password, (0, utils_1.resolveOptions)(this, options)), callback); + } + removeUser(username, options, callback) { + if (typeof options === 'function') + (callback = options), (options = {}); + return (0, execute_operation_1.executeOperation)(this.s.client, new remove_user_1.RemoveUserOperation(this, username, (0, utils_1.resolveOptions)(this, options)), callback); + } + setProfilingLevel(level, options, callback) { + if (typeof options === 'function') + (callback = options), (options = {}); + return (0, execute_operation_1.executeOperation)(this.s.client, new set_profiling_level_1.SetProfilingLevelOperation(this, level, (0, utils_1.resolveOptions)(this, options)), callback); + } + profilingLevel(options, callback) { + if (typeof options === 'function') + (callback = options), (options = {}); + return (0, execute_operation_1.executeOperation)(this.s.client, new profiling_level_1.ProfilingLevelOperation(this, (0, utils_1.resolveOptions)(this, options)), callback); + } + indexInformation(name, options, callback) { + if (typeof options === 'function') + (callback = options), (options = {}); + return (0, execute_operation_1.executeOperation)(this.s.client, new indexes_1.IndexInformationOperation(this, name, (0, utils_1.resolveOptions)(this, options)), callback); } - - // Remove any write concern operations - var removeKeys = ['w', 'wtimeout', 'j', 'fsync', 'readPreference']; - for(var i = 0; i < removeKeys.length; i++) { - delete indexes[0][removeKeys[i]]; + /** + * Unref all sockets + * @deprecated This function is deprecated and will be removed in the next major version. + */ + unref() { + (0, utils_1.getTopology)(this).unref(); + } + /** + * Create a new Change Stream, watching for new changes (insertions, updates, + * replacements, deletions, and invalidations) in this database. Will ignore all + * changes to system collections. + * + * @remarks + * watch() accepts two generic arguments for distinct usecases: + * - The first is to provide the schema that may be defined for all the collections within this database + * - The second is to override the shape of the change stream document entirely, if it is not provided the type will default to ChangeStreamDocument of the first argument + * + * @param pipeline - An array of {@link https://docs.mongodb.com/manual/reference/operator/aggregation-pipeline/|aggregation pipeline stages} through which to pass change stream documents. This allows for filtering (using $match) and manipulating the change stream documents. + * @param options - Optional settings for the command + * @typeParam TSchema - Type of the data being detected by the change stream + * @typeParam TChange - Type of the whole change stream document emitted + */ + watch(pipeline = [], options = {}) { + // Allow optionally not specifying a pipeline + if (!Array.isArray(pipeline)) { + options = pipeline; + pipeline = []; + } + return new change_stream_1.ChangeStream(this, pipeline, (0, utils_1.resolveOptions)(this, options)); + } + /** Return the db logger */ + getLogger() { + return this.s.logger; + } + get logger() { + return this.s.logger; } - } - - // Get capabilities - var capabilities = self.s.topology.capabilities(); - - // Did the user pass in a collation, check if our write server supports it - if(indexes[0].collation && capabilities && !capabilities.commandsTakeCollation) { - // Create a new error - var error = new MongoError(f('server/primary/mongos does not support collation')); - error.code = 67; - // Return the error - return callback(error); - } - - // Create command, apply write concern to command - var cmd = writeConcern({createIndexes: name, indexes: indexes}, self, options); - - // Decorate command with writeConcern if supported - decorateWithWriteConcern(cmd, self, options); - - // ReadPreference primary - options.readPreference = ReadPreference.PRIMARY; - - // Build the command - self.command(cmd, options, function(err, result) { - if(err) return handleCallback(callback, err, null); - if(result.ok == 0) return handleCallback(callback, toError(result), null); - // Return the indexName for backward compatibility - handleCallback(callback, null, indexName); - }); } - +exports.Db = Db; +Db.SYSTEM_NAMESPACE_COLLECTION = CONSTANTS.SYSTEM_NAMESPACE_COLLECTION; +Db.SYSTEM_INDEX_COLLECTION = CONSTANTS.SYSTEM_INDEX_COLLECTION; +Db.SYSTEM_PROFILE_COLLECTION = CONSTANTS.SYSTEM_PROFILE_COLLECTION; +Db.SYSTEM_USER_COLLECTION = CONSTANTS.SYSTEM_USER_COLLECTION; +Db.SYSTEM_COMMAND_COLLECTION = CONSTANTS.SYSTEM_COMMAND_COLLECTION; +Db.SYSTEM_JS_COLLECTION = CONSTANTS.SYSTEM_JS_COLLECTION; +// TODO(NODE-3484): Refactor into MongoDBNamespace // Validate the database name -var validateDatabaseName = function(databaseName) { - if(typeof databaseName !== 'string') throw MongoError.create({message: "database name must be a string", driver:true}); - if(databaseName.length === 0) throw MongoError.create({message: "database name cannot be the empty string", driver:true}); - if(databaseName == '$external') return; - - var invalidChars = [" ", ".", "$", "/", "\\"]; - for(var i = 0; i < invalidChars.length; i++) { - if(databaseName.indexOf(invalidChars[i]) != -1) throw MongoError.create({message: "database names cannot contain the character '" + invalidChars[i] + "'", driver:true}); - } -} - -// Get write concern -var writeConcern = function(target, db, options) { - if(options.w != null || options.j != null || options.fsync != null) { - var opts = {}; - if(options.w) opts.w = options.w; - if(options.wtimeout) opts.wtimeout = options.wtimeout; - if(options.j) opts.j = options.j; - if(options.fsync) opts.fsync = options.fsync; - target.writeConcern = opts; - } else if(db.writeConcern.w != null || db.writeConcern.j != null || db.writeConcern.fsync != null) { - target.writeConcern = db.writeConcern; - } - - return target -} - -// Add listeners to topology -var createListener = function(self, e, object) { - var listener = function(err) { - if(object.listeners(e).length > 0) { - object.emit(e, err, self); - - // Emit on all associated db's if available - for(var i = 0; i < self.s.children.length; i++) { - self.s.children[i].emit(e, err, self.s.children[i]); - } +function validateDatabaseName(databaseName) { + if (typeof databaseName !== 'string') + throw new error_1.MongoInvalidArgumentError('Database name must be a string'); + if (databaseName.length === 0) + throw new error_1.MongoInvalidArgumentError('Database name cannot be the empty string'); + if (databaseName === '$external') + return; + const invalidChars = [' ', '.', '$', '/', '\\']; + for (let i = 0; i < invalidChars.length; i++) { + if (databaseName.indexOf(invalidChars[i]) !== -1) + throw new error_1.MongoAPIError(`database names cannot contain the character '${invalidChars[i]}'`); } - } - return listener; } - - -/** - * Unref all sockets - * @method - */ -Db.prototype.unref = function() { - this.s.topology.unref(); -} - -/** - * Db close event - * - * Emitted after a socket closed against a single server or mongos proxy. - * - * @event Db#close - * @type {MongoError} - */ - -/** - * Db authenticated event - * - * Emitted after all server members in the topology (single server, replicaset or mongos) have successfully authenticated. - * - * @event Db#authenticated - * @type {object} - */ - -/** - * Db reconnect event - * - * * Server: Emitted when the driver has reconnected and re-authenticated. - * * ReplicaSet: N/A - * * Mongos: Emitted when the driver reconnects and re-authenticates successfully against a Mongos. - * - * @event Db#reconnect - * @type {object} - */ - -/** - * Db error event - * - * Emitted after an error occurred against a single server or mongos proxy. - * - * @event Db#error - * @type {MongoError} - */ - -/** - * Db timeout event - * - * Emitted after a socket timeout occurred against a single server or mongos proxy. - * - * @event Db#timeout - * @type {MongoError} - */ - -/** - * Db parseError event - * - * The parseError event is emitted if the driver detects illegal or corrupt BSON being received from the server. - * - * @event Db#parseError - * @type {MongoError} - */ - -/** - * Db fullsetup event, emitted when all servers in the topology have been connected to at start up time. - * - * * Server: Emitted when the driver has connected to the single server and has authenticated. - * * ReplSet: Emitted after the driver has attempted to connect to all replicaset members. - * * Mongos: Emitted after the driver has attempted to connect to all mongos proxies. - * - * @event Db#fullsetup - * @type {Db} - */ - -// Constants -Db.SYSTEM_NAMESPACE_COLLECTION = "system.namespaces"; -Db.SYSTEM_INDEX_COLLECTION = "system.indexes"; -Db.SYSTEM_PROFILE_COLLECTION = "system.profile"; -Db.SYSTEM_USER_COLLECTION = "system.users"; -Db.SYSTEM_COMMAND_COLLECTION = "$cmd"; -Db.SYSTEM_JS_COLLECTION = "system.js"; - -module.exports = Db; +//# sourceMappingURL=db.js.map \ No newline at end of file diff --git a/ts-ticket-office-service/node_modules/mongodb/lib/db.js.map b/ts-ticket-office-service/node_modules/mongodb/lib/db.js.map new file mode 100644 index 000000000..534c74a6c --- /dev/null +++ b/ts-ticket-office-service/node_modules/mongodb/lib/db.js.map @@ -0,0 +1 @@ +{"version":3,"file":"db.js","sourceRoot":"","sources":["../src/db.ts"],"names":[],"mappings":";;;AAAA,mCAAgC;AAChC,iCAA4E;AAC5E,mDAA0F;AAC1F,6CAA6D;AAC7D,yCAAyC;AACzC,oEAAgE;AAChE,8EAAyE;AACzE,mCAAmE;AACnE,qCAAiD;AAGjD,oDAAyE;AAEzE,0DAAgE;AAEhE,sEAAoG;AACpG,4CAK2B;AAC3B,sEAAkE;AAClE,kDAK8B;AAE9B,kEAA8F;AAC9F,0DAAkF;AAClF,gDAAqE;AACrE,0DAAkF;AAClF,0EAI0C;AAC1C,8CAAsE;AACtE,iDAA6C;AAC7C,uDAAuE;AACvE,mCAOiB;AACjB,mDAAoE;AAEpE,qBAAqB;AACrB,MAAM,qBAAqB,GAAG;IAC5B,cAA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iCAAyB,CAAC,0CAA0C,CAAC,CAAC;IAClF,IAAI,YAAY,KAAK,WAAW;QAAE,OAAO;IAEzC,MAAM,YAAY,GAAG,CAAC,GAAG,EAAE,GAAG,EAAE,GAAG,EAAE,GAAG,EAAE,IAAI,CAAC,CAAC;IAChD,KAAK,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC,GAAG,YAAY,CAAC,MAAM,EAAE,CAAC,EAAE,EAAE;QAC5C,IAAI,YAAY,CAAC,OAAO,CAAC,YAAY,CAAC,CAAC,CAAC,CAAC,KAAK,CAAC,CAAC;YAC9C,MAAM,IAAI,qBAAa,CAAC,gDAAgD,YAAY,CAAC,CAAC,CAAC,GAAG,CAAC,CAAC;KAC/F;AACH,CAAC"} \ No newline at end of file diff --git a/ts-ticket-office-service/node_modules/mongodb/lib/deps.js b/ts-ticket-office-service/node_modules/mongodb/lib/deps.js new file mode 100644 index 000000000..6a73e6322 --- /dev/null +++ b/ts-ticket-office-service/node_modules/mongodb/lib/deps.js @@ -0,0 +1,63 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.AutoEncryptionLoggerLevel = exports.aws4 = exports.saslprep = exports.Snappy = exports.ZStandard = exports.Kerberos = exports.PKG_VERSION = void 0; +const error_1 = require("./error"); +const utils_1 = require("./utils"); +exports.PKG_VERSION = Symbol('kPkgVersion'); +function makeErrorModule(error) { + const props = error ? { kModuleError: error } : {}; + return new Proxy(props, { + get: (_, key) => { + if (key === 'kModuleError') { + return error; + } + throw error; + }, + set: () => { + throw error; + } + }); +} +exports.Kerberos = makeErrorModule(new error_1.MongoMissingDependencyError('Optional module `kerberos` not found. Please install it to enable kerberos authentication')); +try { + // Ensure you always wrap an optional require in the try block NODE-3199 + exports.Kerberos = require('kerberos'); +} +catch { } // eslint-disable-line +exports.ZStandard = makeErrorModule(new error_1.MongoMissingDependencyError('Optional module `@mongodb-js/zstd` not found. Please install it to enable zstd compression')); +try { + exports.ZStandard = require('@mongodb-js/zstd'); +} +catch { } // eslint-disable-line +exports.Snappy = makeErrorModule(new error_1.MongoMissingDependencyError('Optional module `snappy` not found. Please install it to enable snappy compression')); +try { + // Ensure you always wrap an optional require in the try block NODE-3199 + exports.Snappy = require('snappy'); + try { + exports.Snappy[exports.PKG_VERSION] = (0, utils_1.parsePackageVersion)(require('snappy/package.json')); + } + catch { } // eslint-disable-line +} +catch { } // eslint-disable-line +exports.saslprep = makeErrorModule(new error_1.MongoMissingDependencyError('Optional module `saslprep` not found.' + + ' Please install it to enable Stringprep Profile for User Names and Passwords')); +try { + // Ensure you always wrap an optional require in the try block NODE-3199 + exports.saslprep = require('saslprep'); +} +catch { } // eslint-disable-line +exports.aws4 = makeErrorModule(new error_1.MongoMissingDependencyError('Optional module `aws4` not found. Please install it to enable AWS authentication')); +try { + // Ensure you always wrap an optional require in the try block NODE-3199 + exports.aws4 = require('aws4'); +} +catch { } // eslint-disable-line +/** @public */ +exports.AutoEncryptionLoggerLevel = Object.freeze({ + FatalError: 0, + Error: 1, + Warning: 2, + Info: 3, + Trace: 4 +}); +//# sourceMappingURL=deps.js.map \ No newline at end of file diff --git a/ts-ticket-office-service/node_modules/mongodb/lib/deps.js.map b/ts-ticket-office-service/node_modules/mongodb/lib/deps.js.map new file mode 100644 index 000000000..cd11aec10 --- /dev/null +++ b/ts-ticket-office-service/node_modules/mongodb/lib/deps.js.map @@ -0,0 +1 @@ +{"version":3,"file":"deps.js","sourceRoot":"","sources":["../src/deps.ts"],"names":[],"mappings":";;;AAGA,mCAAsD;AAEtD,mCAAwD;AAE3C,QAAA,WAAW,GAAG,MAAM,CAAC,aAAa,CAAC,CAAC;AAEjD,SAAS,eAAe,CAAC,KAAU;IACjC,MAAM,KAAK,GAAG,KAAK,CAAC,CAAC,CAAC,EAAE,YAAY,EAAE,KAAK,EAAE,CAAC,CAAC,CAAC,EAAE,CAAC;IACnD,OAAO,IAAI,KAAK,CAAC,KAAK,EAAE;QACtB,GAAG,EAAE,CAAC,CAAM,EAAE,GAAQ,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,CAAC;AAEF,IAAI;IACF,wEAAwE;IACxE,YAAI,GAAG,OAAO,CAAC,MAAM,CAAC,CAAC;CACxB;AAAC,MAAM,GAAE,CAAC,sBAAsB;AAEjC,cAAc;AACD,QAAA,yBAAyB,GAAG,MAAM,CAAC,MAAM,CAAC;IACrD,UAAU,EAAE,CAAC;IACb,KAAK,EAAE,CAAC;IACR,OAAO,EAAE,CAAC;IACV,IAAI,EAAE,CAAC;IACP,KAAK,EAAE,CAAC;CACA,CAAC,CAAC"} \ No newline at end of file diff --git a/ts-ticket-office-service/node_modules/mongodb/lib/encrypter.js b/ts-ticket-office-service/node_modules/mongodb/lib/encrypter.js new file mode 100644 index 000000000..b921b4fa6 --- /dev/null +++ b/ts-ticket-office-service/node_modules/mongodb/lib/encrypter.js @@ -0,0 +1,112 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.Encrypter = void 0; +/* eslint-disable @typescript-eslint/no-var-requires */ +const bson_1 = require("./bson"); +const constants_1 = require("./constants"); +const error_1 = require("./error"); +const mongo_client_1 = require("./mongo_client"); +const utils_1 = require("./utils"); +let AutoEncrypterClass; +/** @internal */ +const kInternalClient = Symbol('internalClient'); +/** @internal */ +class Encrypter { + constructor(client, uri, options) { + if (typeof options.autoEncryption !== 'object') { + throw new error_1.MongoInvalidArgumentError('Option "autoEncryption" must be specified'); + } + // initialize to null, if we call getInternalClient, we may set this it is important to not overwrite those function calls. + this[kInternalClient] = null; + this.bypassAutoEncryption = !!options.autoEncryption.bypassAutoEncryption; + this.needsConnecting = false; + if (options.maxPoolSize === 0 && options.autoEncryption.keyVaultClient == null) { + options.autoEncryption.keyVaultClient = client; + } + else if (options.autoEncryption.keyVaultClient == null) { + options.autoEncryption.keyVaultClient = this.getInternalClient(client, uri, options); + } + if (this.bypassAutoEncryption) { + options.autoEncryption.metadataClient = undefined; + } + else if (options.maxPoolSize === 0) { + options.autoEncryption.metadataClient = client; + } + else { + options.autoEncryption.metadataClient = this.getInternalClient(client, uri, options); + } + if (options.proxyHost) { + options.autoEncryption.proxyOptions = { + proxyHost: options.proxyHost, + proxyPort: options.proxyPort, + proxyUsername: options.proxyUsername, + proxyPassword: options.proxyPassword + }; + } + options.autoEncryption.bson = Object.create(null); + // eslint-disable-next-line @typescript-eslint/no-non-null-assertion + options.autoEncryption.bson.serialize = bson_1.serialize; + // eslint-disable-next-line @typescript-eslint/no-non-null-assertion + options.autoEncryption.bson.deserialize = bson_1.deserialize; + this.autoEncrypter = new AutoEncrypterClass(client, options.autoEncryption); + } + getInternalClient(client, uri, options) { + // TODO(NODE-4144): Remove new variable for type narrowing + let internalClient = this[kInternalClient]; + if (internalClient == null) { + const clonedOptions = {}; + for (const key of [ + ...Object.getOwnPropertyNames(options), + ...Object.getOwnPropertySymbols(options) + ]) { + if (['autoEncryption', 'minPoolSize', 'servers', 'caseTranslate', 'dbName'].includes(key)) + continue; + Reflect.set(clonedOptions, key, Reflect.get(options, key)); + } + clonedOptions.minPoolSize = 0; + internalClient = new mongo_client_1.MongoClient(uri, clonedOptions); + this[kInternalClient] = internalClient; + for (const eventName of constants_1.MONGO_CLIENT_EVENTS) { + for (const listener of client.listeners(eventName)) { + internalClient.on(eventName, listener); + } + } + client.on('newListener', (eventName, listener) => { + internalClient === null || internalClient === void 0 ? void 0 : internalClient.on(eventName, listener); + }); + this.needsConnecting = true; + } + return internalClient; + } + connectInternalClient(callback) { + // TODO(NODE-4144): Remove new variable for type narrowing + const internalClient = this[kInternalClient]; + if (this.needsConnecting && internalClient != null) { + this.needsConnecting = false; + return internalClient.connect(callback); + } + return callback(); + } + close(client, force, callback) { + this.autoEncrypter.teardown(!!force, e => { + const internalClient = this[kInternalClient]; + if (internalClient != null && client !== internalClient) { + return internalClient.close(force, callback); + } + callback(e); + }); + } + static checkForMongoCrypt() { + try { + // NOTE(NODE-3199): Ensure you always wrap an optional require in the try block + const mongodbClientEncryption = (0, utils_1.getMongoDBClientEncryption)(); + AutoEncrypterClass = mongodbClientEncryption.extension(require('../lib/index')).AutoEncrypter; + } + catch { + throw new error_1.MongoMissingDependencyError('Auto-encryption requested, but the module is not installed. ' + + 'Please add `mongodb-client-encryption` as a dependency of your project'); + } + } +} +exports.Encrypter = Encrypter; +//# sourceMappingURL=encrypter.js.map \ No newline at end of file diff --git a/ts-ticket-office-service/node_modules/mongodb/lib/encrypter.js.map b/ts-ticket-office-service/node_modules/mongodb/lib/encrypter.js.map new file mode 100644 index 000000000..7cca6a0f6 --- /dev/null +++ b/ts-ticket-office-service/node_modules/mongodb/lib/encrypter.js.map @@ -0,0 +1 @@ +{"version":3,"file":"encrypter.js","sourceRoot":"","sources":["../src/encrypter.ts"],"names":[],"mappings":";;;AAAA,uDAAuD;AACvD,iCAAgD;AAChD,2CAAkD;AAElD,mCAAiF;AACjF,iDAAiE;AACjE,mCAA+D;AAE/D,IAAI,kBAAiC,CAAC;AAEtC,gBAAgB;AAChB,MAAM,eAAe,GAAG,MAAM,CAAC,gBAAgB,CAAC,CAAC;AAQjD,gBAAgB;AAChB,MAAa,SAAS;IAMpB,YAAY,MAAmB,EAAE,GAAW,EAAE,OAA2B;QACvE,IAAI,OAAO,OAAO,CAAC,cAAc,KAAK,QAAQ,EAAE;YAC9C,MAAM,IAAI,iCAAyB,CAAC,2CAA2C,CAAC,CAAC;SAClF;QACD,2HAA2H;QAC3H,IAAI,CAAC,eAAe,CAAC,GAAG,IAAI,CAAC;QAE7B,IAAI,CAAC,oBAAoB,GAAG,CAAC,CAAC,OAAO,CAAC,cAAc,CAAC,oBAAoB,CAAC;QAC1E,IAAI,CAAC,eAAe,GAAG,KAAK,CAAC;QAE7B,IAAI,OAAO,CAAC,WAAW,KAAK,CAAC,IAAI,OAAO,CAAC,cAAc,CAAC,cAAc,IAAI,IAAI,EAAE;YAC9E,OAAO,CAAC,cAAc,CAAC,cAAc,GAAG,MAAM,CAAC;SAChD;aAAM,IAAI,OAAO,CAAC,cAAc,CAAC,cAAc,IAAI,IAAI,EAAE;YACxD,OAAO,CAAC,c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AAc,CAAC,OAAO,CAAC,QAAQ,CAAC,CAAC;SACzC;QAED,OAAO,QAAQ,EAAE,CAAC;IACpB,CAAC;IAED,KAAK,CAAC,MAAmB,EAAE,KAAc,EAAE,QAAkB;QAC3D,IAAI,CAAC,aAAa,CAAC,QAAQ,CAAC,CAAC,CAAC,KAAK,EAAE,CAAC,CAAC,EAAE;YACvC,MAAM,cAAc,GAAG,IAAI,CAAC,eAAe,CAAC,CAAC;YAC7C,IAAI,cAAc,IAAI,IAAI,IAAI,MAAM,KAAK,cAAc,EAAE;gBACvD,OAAO,cAAc,CAAC,KAAK,CAAC,KAAK,EAAE,QAAQ,CAAC,CAAC;aAC9C;YACD,QAAQ,CAAC,CAAC,CAAC,CAAC;QACd,CAAC,CAAC,CAAC;IACL,CAAC;IAED,MAAM,CAAC,kBAAkB;QACvB,IAAI;YACF,+EAA+E;YAC/E,MAAM,uBAAuB,GAAG,IAAA,kCAA0B,GAAE,CAAC;YAC7D,kBAAkB,GAAG,uBAAuB,CAAC,SAAS,CAAC,OAAO,CAAC,cAAc,CAAC,CAAC,CAAC,aAAa,CAAC;SAC/F;QAAC,MAAM;YACN,MAAM,IAAI,mCAA2B,CACnC,8DAA8D;gBAC5D,wEAAwE,CAC3E,CAAC;SACH;IACH,CAAC;CACF;AApHD,8BAoHC"} \ No newline at end of file diff --git a/ts-ticket-office-service/node_modules/mongodb/lib/error.js b/ts-ticket-office-service/node_modules/mongodb/lib/error.js new file mode 100644 index 000000000..cf28508db --- /dev/null +++ b/ts-ticket-office-service/node_modules/mongodb/lib/error.js @@ -0,0 +1,799 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.isResumableError = exports.isNetworkTimeoutError = exports.isSDAMUnrecoverableError = exports.isNodeShuttingDownError = exports.isRetryableReadError = exports.isRetryableWriteError = exports.needsRetryableWriteLabel = exports.MongoWriteConcernError = exports.MongoServerSelectionError = exports.MongoSystemError = exports.MongoMissingDependencyError = exports.MongoMissingCredentialsError = exports.MongoCompatibilityError = exports.MongoInvalidArgumentError = exports.MongoParseError = exports.MongoNetworkTimeoutError = exports.MongoNetworkError = exports.isNetworkErrorBeforeHandshake = exports.MongoTopologyClosedError = exports.MongoCursorExhaustedError = exports.MongoServerClosedError = exports.MongoCursorInUseError = exports.MongoUnexpectedServerResponseError = exports.MongoGridFSChunkError = exports.MongoGridFSStreamError = exports.MongoTailableCursorError = exports.MongoChangeStreamError = exports.MongoAWSError = exports.MongoKerberosError = exports.MongoExpiredSessionError = exports.MongoTransactionError = exports.MongoNotConnectedError = exports.MongoDecompressionError = exports.MongoBatchReExecutionError = exports.MongoRuntimeError = exports.MongoAPIError = exports.MongoDriverError = exports.MongoServerError = exports.MongoError = exports.MongoErrorLabel = exports.GET_MORE_RESUMABLE_CODES = exports.MONGODB_ERROR_CODES = exports.NODE_IS_RECOVERING_ERROR_MESSAGE = exports.LEGACY_NOT_PRIMARY_OR_SECONDARY_ERROR_MESSAGE = exports.LEGACY_NOT_WRITABLE_PRIMARY_ERROR_MESSAGE = void 0; +/** @internal */ +const kErrorLabels = Symbol('errorLabels'); +/** + * @internal + * The legacy error message from the server that indicates the node is not a writable primary + * https://github.com/mongodb/specifications/blob/b07c26dc40d04ac20349f989db531c9845fdd755/source/server-discovery-and-monitoring/server-discovery-and-monitoring.rst#not-writable-primary-and-node-is-recovering + */ +exports.LEGACY_NOT_WRITABLE_PRIMARY_ERROR_MESSAGE = new RegExp('not master', 'i'); +/** + * @internal + * The legacy error message from the server that indicates the node is not a primary or secondary + * https://github.com/mongodb/specifications/blob/b07c26dc40d04ac20349f989db531c9845fdd755/source/server-discovery-and-monitoring/server-discovery-and-monitoring.rst#not-writable-primary-and-node-is-recovering + */ +exports.LEGACY_NOT_PRIMARY_OR_SECONDARY_ERROR_MESSAGE = new RegExp('not master or secondary', 'i'); +/** + * @internal + * The error message from the server that indicates the node is recovering + * https://github.com/mongodb/specifications/blob/b07c26dc40d04ac20349f989db531c9845fdd755/source/server-discovery-and-monitoring/server-discovery-and-monitoring.rst#not-writable-primary-and-node-is-recovering + */ +exports.NODE_IS_RECOVERING_ERROR_MESSAGE = new RegExp('node is recovering', 'i'); +/** @internal MongoDB Error Codes */ +exports.MONGODB_ERROR_CODES = Object.freeze({ + HostUnreachable: 6, + HostNotFound: 7, + NetworkTimeout: 89, + ShutdownInProgress: 91, + PrimarySteppedDown: 189, + ExceededTimeLimit: 262, + SocketException: 9001, + NotWritablePrimary: 10107, + InterruptedAtShutdown: 11600, + InterruptedDueToReplStateChange: 11602, + NotPrimaryNoSecondaryOk: 13435, + NotPrimaryOrSecondary: 13436, + StaleShardVersion: 63, + StaleEpoch: 150, + StaleConfig: 13388, + RetryChangeStream: 234, + FailedToSatisfyReadPreference: 133, + CursorNotFound: 43, + LegacyNotPrimary: 10058, + WriteConcernFailed: 64, + NamespaceNotFound: 26, + IllegalOperation: 20, + MaxTimeMSExpired: 50, + UnknownReplWriteConcern: 79, + UnsatisfiableWriteConcern: 100 +}); +// From spec@https://github.com/mongodb/specifications/blob/f93d78191f3db2898a59013a7ed5650352ef6da8/source/change-streams/change-streams.rst#resumable-error +exports.GET_MORE_RESUMABLE_CODES = new Set([ + exports.MONGODB_ERROR_CODES.HostUnreachable, + exports.MONGODB_ERROR_CODES.HostNotFound, + exports.MONGODB_ERROR_CODES.NetworkTimeout, + exports.MONGODB_ERROR_CODES.ShutdownInProgress, + exports.MONGODB_ERROR_CODES.PrimarySteppedDown, + exports.MONGODB_ERROR_CODES.ExceededTimeLimit, + exports.MONGODB_ERROR_CODES.SocketException, + exports.MONGODB_ERROR_CODES.NotWritablePrimary, + exports.MONGODB_ERROR_CODES.InterruptedAtShutdown, + exports.MONGODB_ERROR_CODES.InterruptedDueToReplStateChange, + exports.MONGODB_ERROR_CODES.NotPrimaryNoSecondaryOk, + exports.MONGODB_ERROR_CODES.NotPrimaryOrSecondary, + exports.MONGODB_ERROR_CODES.StaleShardVersion, + exports.MONGODB_ERROR_CODES.StaleEpoch, + exports.MONGODB_ERROR_CODES.StaleConfig, + exports.MONGODB_ERROR_CODES.RetryChangeStream, + exports.MONGODB_ERROR_CODES.FailedToSatisfyReadPreference, + exports.MONGODB_ERROR_CODES.CursorNotFound +]); +/** @public */ +exports.MongoErrorLabel = Object.freeze({ + RetryableWriteError: 'RetryableWriteError', + TransientTransactionError: 'TransientTransactionError', + UnknownTransactionCommitResult: 'UnknownTransactionCommitResult', + ResumableChangeStreamError: 'ResumableChangeStreamError', + HandshakeError: 'HandshakeError' +}); +/** + * @public + * @category Error + * + * @privateRemarks + * CSFLE has a dependency on this error, it uses the constructor with a string argument + */ +class MongoError extends Error { + constructor(message) { + if (message instanceof Error) { + super(message.message); + } + else { + super(message); + } + this[kErrorLabels] = new Set(); + } + get name() { + return 'MongoError'; + } + /** Legacy name for server error responses */ + get errmsg() { + return this.message; + } + /** + * Checks the error to see if it has an error label + * + * @param label - The error label to check for + * @returns returns true if the error has the provided error label + */ + hasErrorLabel(label) { + return this[kErrorLabels].has(label); + } + addErrorLabel(label) { + this[kErrorLabels].add(label); + } + get errorLabels() { + return Array.from(this[kErrorLabels]); + } +} +exports.MongoError = MongoError; +/** + * An error coming from the mongo server + * + * @public + * @category Error + */ +class MongoServerError extends MongoError { + constructor(message) { + super(message.message || message.errmsg || message.$err || 'n/a'); + if (message.errorLabels) { + this[kErrorLabels] = new Set(message.errorLabels); + } + for (const name in message) { + if (name !== 'errorLabels' && name !== 'errmsg' && name !== 'message') + this[name] = message[name]; + } + } + get name() { + return 'MongoServerError'; + } +} +exports.MongoServerError = MongoServerError; +/** + * An error generated by the driver + * + * @public + * @category Error + */ +class MongoDriverError extends MongoError { + constructor(message) { + super(message); + } + get name() { + return 'MongoDriverError'; + } +} +exports.MongoDriverError = MongoDriverError; +/** + * An error generated when the driver API is used incorrectly + * + * @privateRemarks + * Should **never** be directly instantiated + * + * @public + * @category Error + */ +class MongoAPIError extends MongoDriverError { + constructor(message) { + super(message); + } + get name() { + return 'MongoAPIError'; + } +} +exports.MongoAPIError = MongoAPIError; +/** + * An error generated when the driver encounters unexpected input + * or reaches an unexpected/invalid internal state + * + * @privateRemarks + * Should **never** be directly instantiated. + * + * @public + * @category Error + */ +class MongoRuntimeError extends MongoDriverError { + constructor(message) { + super(message); + } + get name() { + return 'MongoRuntimeError'; + } +} +exports.MongoRuntimeError = MongoRuntimeError; +/** + * An error generated when a batch command is re-executed after one of the commands in the batch + * has failed + * + * @public + * @category Error + */ +class MongoBatchReExecutionError extends MongoAPIError { + constructor(message = 'This batch has already been executed, create new batch to execute') { + super(message); + } + get name() { + return 'MongoBatchReExecutionError'; + } +} +exports.MongoBatchReExecutionError = MongoBatchReExecutionError; +/** + * An error generated when the driver fails to decompress + * data received from the server. + * + * @public + * @category Error + */ +class MongoDecompressionError extends MongoRuntimeError { + constructor(message) { + super(message); + } + get name() { + return 'MongoDecompressionError'; + } +} +exports.MongoDecompressionError = MongoDecompressionError; +/** + * An error thrown when the user attempts to operate on a database or collection through a MongoClient + * that has not yet successfully called the "connect" method + * + * @public + * @category Error + */ +class MongoNotConnectedError extends MongoAPIError { + constructor(message) { + super(message); + } + get name() { + return 'MongoNotConnectedError'; + } +} +exports.MongoNotConnectedError = MongoNotConnectedError; +/** + * An error generated when the user makes a mistake in the usage of transactions. + * (e.g. attempting to commit a transaction with a readPreference other than primary) + * + * @public + * @category Error + */ +class MongoTransactionError extends MongoAPIError { + constructor(message) { + super(message); + } + get name() { + return 'MongoTransactionError'; + } +} +exports.MongoTransactionError = MongoTransactionError; +/** + * An error generated when the user attempts to operate + * on a session that has expired or has been closed. + * + * @public + * @category Error + */ +class MongoExpiredSessionError extends MongoAPIError { + constructor(message = 'Cannot use a session that has ended') { + super(message); + } + get name() { + return 'MongoExpiredSessionError'; + } +} +exports.MongoExpiredSessionError = MongoExpiredSessionError; +/** + * A error generated when the user attempts to authenticate + * via Kerberos, but fails to connect to the Kerberos client. + * + * @public + * @category Error + */ +class MongoKerberosError extends MongoRuntimeError { + constructor(message) { + super(message); + } + get name() { + return 'MongoKerberosError'; + } +} +exports.MongoKerberosError = MongoKerberosError; +/** + * A error generated when the user attempts to authenticate + * via AWS, but fails + * + * @public + * @category Error + */ +class MongoAWSError extends MongoRuntimeError { + constructor(message) { + super(message); + } + get name() { + return 'MongoAWSError'; + } +} +exports.MongoAWSError = MongoAWSError; +/** + * An error generated when a ChangeStream operation fails to execute. + * + * @public + * @category Error + */ +class MongoChangeStreamError extends MongoRuntimeError { + constructor(message) { + super(message); + } + get name() { + return 'MongoChangeStreamError'; + } +} +exports.MongoChangeStreamError = MongoChangeStreamError; +/** + * An error thrown when the user calls a function or method not supported on a tailable cursor + * + * @public + * @category Error + */ +class MongoTailableCursorError extends MongoAPIError { + constructor(message = 'Tailable cursor does not support this operation') { + super(message); + } + get name() { + return 'MongoTailableCursorError'; + } +} +exports.MongoTailableCursorError = MongoTailableCursorError; +/** An error generated when a GridFSStream operation fails to execute. + * + * @public + * @category Error + */ +class MongoGridFSStreamError extends MongoRuntimeError { + constructor(message) { + super(message); + } + get name() { + return 'MongoGridFSStreamError'; + } +} +exports.MongoGridFSStreamError = MongoGridFSStreamError; +/** + * An error generated when a malformed or invalid chunk is + * encountered when reading from a GridFSStream. + * + * @public + * @category Error + */ +class MongoGridFSChunkError extends MongoRuntimeError { + constructor(message) { + super(message); + } + get name() { + return 'MongoGridFSChunkError'; + } +} +exports.MongoGridFSChunkError = MongoGridFSChunkError; +/** + * An error generated when a **parsable** unexpected response comes from the server. + * This is generally an error where the driver in a state expecting a certain behavior to occur in + * the next message from MongoDB but it receives something else. + * This error **does not** represent an issue with wire message formatting. + * + * #### Example + * When an operation fails, it is the driver's job to retry it. It must perform serverSelection + * again to make sure that it attempts the operation against a server in a good state. If server + * selection returns a server that does not support retryable operations, this error is used. + * This scenario is unlikely as retryable support would also have been determined on the first attempt + * but it is possible the state change could report a selectable server that does not support retries. + * + * @public + * @category Error + */ +class MongoUnexpectedServerResponseError extends MongoRuntimeError { + constructor(message) { + super(message); + } + get name() { + return 'MongoUnexpectedServerResponseError'; + } +} +exports.MongoUnexpectedServerResponseError = MongoUnexpectedServerResponseError; +/** + * An error thrown when the user attempts to add options to a cursor that has already been + * initialized + * + * @public + * @category Error + */ +class MongoCursorInUseError extends MongoAPIError { + constructor(message = 'Cursor is already initialized') { + super(message); + } + get name() { + return 'MongoCursorInUseError'; + } +} +exports.MongoCursorInUseError = MongoCursorInUseError; +/** + * An error generated when an attempt is made to operate + * on a closed/closing server. + * + * @public + * @category Error + */ +class MongoServerClosedError extends MongoAPIError { + constructor(message = 'Server is closed') { + super(message); + } + get name() { + return 'MongoServerClosedError'; + } +} +exports.MongoServerClosedError = MongoServerClosedError; +/** + * An error thrown when an attempt is made to read from a cursor that has been exhausted + * + * @public + * @category Error + */ +class MongoCursorExhaustedError extends MongoAPIError { + constructor(message) { + super(message || 'Cursor is exhausted'); + } + get name() { + return 'MongoCursorExhaustedError'; + } +} +exports.MongoCursorExhaustedError = MongoCursorExhaustedError; +/** + * An error generated when an attempt is made to operate on a + * dropped, or otherwise unavailable, database. + * + * @public + * @category Error + */ +class MongoTopologyClosedError extends MongoAPIError { + constructor(message = 'Topology is closed') { + super(message); + } + get name() { + return 'MongoTopologyClosedError'; + } +} +exports.MongoTopologyClosedError = MongoTopologyClosedError; +/** @internal */ +const kBeforeHandshake = Symbol('beforeHandshake'); +function isNetworkErrorBeforeHandshake(err) { + return err[kBeforeHandshake] === true; +} +exports.isNetworkErrorBeforeHandshake = isNetworkErrorBeforeHandshake; +/** + * An error indicating an issue with the network, including TCP errors and timeouts. + * @public + * @category Error + */ +class MongoNetworkError extends MongoError { + constructor(message, options) { + super(message); + if (options && typeof options.beforeHandshake === 'boolean') { + this[kBeforeHandshake] = options.beforeHandshake; + } + } + get name() { + return 'MongoNetworkError'; + } +} +exports.MongoNetworkError = MongoNetworkError; +/** + * An error indicating a network timeout occurred + * @public + * @category Error + * + * @privateRemarks + * CSFLE has a dependency on this error with an instanceof check + */ +class MongoNetworkTimeoutError extends MongoNetworkError { + constructor(message, options) { + super(message, options); + } + get name() { + return 'MongoNetworkTimeoutError'; + } +} +exports.MongoNetworkTimeoutError = MongoNetworkTimeoutError; +/** + * An error used when attempting to parse a value (like a connection string) + * @public + * @category Error + */ +class MongoParseError extends MongoDriverError { + constructor(message) { + super(message); + } + get name() { + return 'MongoParseError'; + } +} +exports.MongoParseError = MongoParseError; +/** + * An error generated when the user supplies malformed or unexpected arguments + * or when a required argument or field is not provided. + * + * + * @public + * @category Error + */ +class MongoInvalidArgumentError extends MongoAPIError { + constructor(message) { + super(message); + } + get name() { + return 'MongoInvalidArgumentError'; + } +} +exports.MongoInvalidArgumentError = MongoInvalidArgumentError; +/** + * An error generated when a feature that is not enabled or allowed for the current server + * configuration is used + * + * + * @public + * @category Error + */ +class MongoCompatibilityError extends MongoAPIError { + constructor(message) { + super(message); + } + get name() { + return 'MongoCompatibilityError'; + } +} +exports.MongoCompatibilityError = MongoCompatibilityError; +/** + * An error generated when the user fails to provide authentication credentials before attempting + * to connect to a mongo server instance. + * + * + * @public + * @category Error + */ +class MongoMissingCredentialsError extends MongoAPIError { + constructor(message) { + super(message); + } + get name() { + return 'MongoMissingCredentialsError'; + } +} +exports.MongoMissingCredentialsError = MongoMissingCredentialsError; +/** + * An error generated when a required module or dependency is not present in the local environment + * + * @public + * @category Error + */ +class MongoMissingDependencyError extends MongoAPIError { + constructor(message) { + super(message); + } + get name() { + return 'MongoMissingDependencyError'; + } +} +exports.MongoMissingDependencyError = MongoMissingDependencyError; +/** + * An error signifying a general system issue + * @public + * @category Error + */ +class MongoSystemError extends MongoError { + constructor(message, reason) { + var _a; + if (reason && reason.error) { + super(reason.error.message || reason.error); + } + else { + super(message); + } + if (reason) { + this.reason = reason; + } + this.code = (_a = reason.error) === null || _a === void 0 ? void 0 : _a.code; + } + get name() { + return 'MongoSystemError'; + } +} +exports.MongoSystemError = MongoSystemError; +/** + * An error signifying a client-side server selection error + * @public + * @category Error + */ +class MongoServerSelectionError extends MongoSystemError { + constructor(message, reason) { + super(message, reason); + } + get name() { + return 'MongoServerSelectionError'; + } +} +exports.MongoServerSelectionError = MongoServerSelectionError; +function makeWriteConcernResultObject(input) { + const output = Object.assign({}, input); + if (output.ok === 0) { + output.ok = 1; + delete output.errmsg; + delete output.code; + delete output.codeName; + } + return output; +} +/** + * An error thrown when the server reports a writeConcernError + * @public + * @category Error + */ +class MongoWriteConcernError extends MongoServerError { + constructor(message, result) { + if (result && Array.isArray(result.errorLabels)) { + message.errorLabels = result.errorLabels; + } + super(message); + this.errInfo = message.errInfo; + if (result != null) { + this.result = makeWriteConcernResultObject(result); + } + } + get name() { + return 'MongoWriteConcernError'; + } +} +exports.MongoWriteConcernError = MongoWriteConcernError; +// https://github.com/mongodb/specifications/blob/master/source/retryable-reads/retryable-reads.rst#retryable-error +const RETRYABLE_READ_ERROR_CODES = new Set([ + exports.MONGODB_ERROR_CODES.HostUnreachable, + exports.MONGODB_ERROR_CODES.HostNotFound, + exports.MONGODB_ERROR_CODES.NetworkTimeout, + exports.MONGODB_ERROR_CODES.ShutdownInProgress, + exports.MONGODB_ERROR_CODES.PrimarySteppedDown, + exports.MONGODB_ERROR_CODES.SocketException, + exports.MONGODB_ERROR_CODES.NotWritablePrimary, + exports.MONGODB_ERROR_CODES.InterruptedAtShutdown, + exports.MONGODB_ERROR_CODES.InterruptedDueToReplStateChange, + exports.MONGODB_ERROR_CODES.NotPrimaryNoSecondaryOk, + exports.MONGODB_ERROR_CODES.NotPrimaryOrSecondary +]); +// see: https://github.com/mongodb/specifications/blob/master/source/retryable-writes/retryable-writes.rst#terms +const RETRYABLE_WRITE_ERROR_CODES = new Set([ + ...RETRYABLE_READ_ERROR_CODES, + exports.MONGODB_ERROR_CODES.ExceededTimeLimit +]); +function needsRetryableWriteLabel(error, maxWireVersion) { + var _a, _b, _c; + // pre-4.4 server, then the driver adds an error label for every valid case + // execute operation will only inspect the label, code/message logic is handled here + if (error instanceof MongoNetworkError) { + return true; + } + if (error instanceof MongoError) { + if ((maxWireVersion >= 9 || error.hasErrorLabel(exports.MongoErrorLabel.RetryableWriteError)) && + !error.hasErrorLabel(exports.MongoErrorLabel.HandshakeError)) { + // If we already have the error label no need to add it again. 4.4+ servers add the label. + // In the case where we have a handshake error, need to fall down to the logic checking + // the codes. + return false; + } + } + if (error instanceof MongoWriteConcernError) { + return RETRYABLE_WRITE_ERROR_CODES.has((_c = (_b = (_a = error.result) === null || _a === void 0 ? void 0 : _a.code) !== null && _b !== void 0 ? _b : error.code) !== null && _c !== void 0 ? _c : 0); + } + if (error instanceof MongoError && typeof error.code === 'number') { + return RETRYABLE_WRITE_ERROR_CODES.has(error.code); + } + const isNotWritablePrimaryError = exports.LEGACY_NOT_WRITABLE_PRIMARY_ERROR_MESSAGE.test(error.message); + if (isNotWritablePrimaryError) { + return true; + } + const isNodeIsRecoveringError = exports.NODE_IS_RECOVERING_ERROR_MESSAGE.test(error.message); + if (isNodeIsRecoveringError) { + return true; + } + return false; +} +exports.needsRetryableWriteLabel = needsRetryableWriteLabel; +function isRetryableWriteError(error) { + return error.hasErrorLabel(exports.MongoErrorLabel.RetryableWriteError); +} +exports.isRetryableWriteError = isRetryableWriteError; +/** Determines whether an error is something the driver should attempt to retry */ +function isRetryableReadError(error) { + const hasRetryableErrorCode = typeof error.code === 'number' ? RETRYABLE_READ_ERROR_CODES.has(error.code) : false; + if (hasRetryableErrorCode) { + return true; + } + if (error instanceof MongoNetworkError) { + return true; + } + const isNotWritablePrimaryError = exports.LEGACY_NOT_WRITABLE_PRIMARY_ERROR_MESSAGE.test(error.message); + if (isNotWritablePrimaryError) { + return true; + } + const isNodeIsRecoveringError = exports.NODE_IS_RECOVERING_ERROR_MESSAGE.test(error.message); + if (isNodeIsRecoveringError) { + return true; + } + return false; +} +exports.isRetryableReadError = isRetryableReadError; +const SDAM_RECOVERING_CODES = new Set([ + exports.MONGODB_ERROR_CODES.ShutdownInProgress, + exports.MONGODB_ERROR_CODES.PrimarySteppedDown, + exports.MONGODB_ERROR_CODES.InterruptedAtShutdown, + exports.MONGODB_ERROR_CODES.InterruptedDueToReplStateChange, + exports.MONGODB_ERROR_CODES.NotPrimaryOrSecondary +]); +const SDAM_NOT_PRIMARY_CODES = new Set([ + exports.MONGODB_ERROR_CODES.NotWritablePrimary, + exports.MONGODB_ERROR_CODES.NotPrimaryNoSecondaryOk, + exports.MONGODB_ERROR_CODES.LegacyNotPrimary +]); +const SDAM_NODE_SHUTTING_DOWN_ERROR_CODES = new Set([ + exports.MONGODB_ERROR_CODES.InterruptedAtShutdown, + exports.MONGODB_ERROR_CODES.ShutdownInProgress +]); +function isRecoveringError(err) { + if (typeof err.code === 'number') { + // If any error code exists, we ignore the error.message + return SDAM_RECOVERING_CODES.has(err.code); + } + return (exports.LEGACY_NOT_PRIMARY_OR_SECONDARY_ERROR_MESSAGE.test(err.message) || + exports.NODE_IS_RECOVERING_ERROR_MESSAGE.test(err.message)); +} +function isNotWritablePrimaryError(err) { + if (typeof err.code === 'number') { + // If any error code exists, we ignore the error.message + return SDAM_NOT_PRIMARY_CODES.has(err.code); + } + if (isRecoveringError(err)) { + return false; + } + return exports.LEGACY_NOT_WRITABLE_PRIMARY_ERROR_MESSAGE.test(err.message); +} +function isNodeShuttingDownError(err) { + return !!(typeof err.code === 'number' && SDAM_NODE_SHUTTING_DOWN_ERROR_CODES.has(err.code)); +} +exports.isNodeShuttingDownError = isNodeShuttingDownError; +/** + * Determines whether SDAM can recover from a given error. If it cannot + * then the pool will be cleared, and server state will completely reset + * locally. + * + * @see https://github.com/mongodb/specifications/blob/master/source/server-discovery-and-monitoring/server-discovery-and-monitoring.rst#not-master-and-node-is-recovering + */ +function isSDAMUnrecoverableError(error) { + // NOTE: null check is here for a strictly pre-CMAP world, a timeout or + // close event are considered unrecoverable + if (error instanceof MongoParseError || error == null) { + return true; + } + return isRecoveringError(error) || isNotWritablePrimaryError(error); +} +exports.isSDAMUnrecoverableError = isSDAMUnrecoverableError; +function isNetworkTimeoutError(err) { + return !!(err instanceof MongoNetworkError && err.message.match(/timed out/)); +} +exports.isNetworkTimeoutError = isNetworkTimeoutError; +function isResumableError(error, wireVersion) { + if (error == null || !(error instanceof MongoError)) { + return false; + } + if (error instanceof MongoNetworkError) { + return true; + } + if (wireVersion != null && wireVersion >= 9) { + // DRIVERS-1308: For 4.4 drivers running against 4.4 servers, drivers will add a special case to treat the CursorNotFound error code as resumable + if (error.code === exports.MONGODB_ERROR_CODES.CursorNotFound) { + return true; + } + return error.hasErrorLabel(exports.MongoErrorLabel.ResumableChangeStreamError); + } + if (typeof error.code === 'number') { + return exports.GET_MORE_RESUMABLE_CODES.has(error.code); + } + return false; +} +exports.isResumableError = isResumableError; +//# sourceMappingURL=error.js.map \ No newline at end of file diff --git a/ts-ticket-office-service/node_modules/mongodb/lib/error.js.map b/ts-ticket-office-service/node_modules/mongodb/lib/error.js.map new file mode 100644 index 000000000..c02c2d88e --- /dev/null +++ b/ts-ticket-office-service/node_modules/mongodb/lib/error.js.map @@ -0,0 +1 @@ +{"version":3,"file":"error.js","sourceRoot":"","sources":["../src/error.ts"],"names":[],"mappings":";;;AAOA,gBAAgB;AAChB,MAAM,YAAY,GAAG,MAAM,CAAC,aAAa,CAAC,CAAC;AAE3C;;;;GAIG;AACU,QAAA,yCAAyC,GAAG,IAAI,MAAM,CAAC,YAAY,EAAE,GAAG,CAAC,CAAC;AAEvF;;;;GAIG;AACU,QAAA,6CAA6C,GAAG,IAAI,MAAM,CACrE,yBAAyB,EACzB,GAAG,CACJ,CAAC;AAEF;;;;GAIG;AACU,QAAA,gCAAgC,GAAG,IAAI,MAAM,CAAC,oBAAoB,EAAE,GAAG,CAAC,CAAC;AAEtF,oCAAoC;AACvB,QAAA,mBAAmB,GAAG,MAAM,CAAC,MAAM,CAAC;IAC/C,eAAe,EAAE,CAAC;IAClB,YAAY,EAAE,CAAC;IACf,cAAc,EAAE,EAAE;IAClB,kBAAkB,EAAE,EAAE;IACtB,kBAAkB,EAAE,GAAG;IACvB,iBAAiB,EAAE,GAAG;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;AACtE,CAAC;AARD,4DAQC;AAED,SAAgB,qBAAqB,CAAC,GAAe;IACnD,OAAO,CAAC,CAAC,CAAC,GAAG,YAAY,iBAAiB,IAAI,GAAG,CAAC,OAAO,CAAC,KAAK,CAAC,WAAW,CAAC,CAAC,CAAC;AAChF,CAAC;AAFD,sDAEC;AAED,SAAgB,gBAAgB,CAAC,KAAa,EAAE,WAAoB;IAClE,IAAI,KAAK,IAAI,IAAI,IAAI,CAAC,CAAC,KAAK,YAAY,UAAU,CAAC,EAAE;QACnD,OAAO,KAAK,CAAC;KACd;IAED,IAAI,KAAK,YAAY,iBAAiB,EAAE;QACtC,OAAO,IAAI,CAAC;KACb;IAED,IAAI,WAAW,IAAI,IAAI,IAAI,WAAW,IAAI,CAAC,EAAE;QAC3C,iJAAiJ;QACjJ,IAAI,KAAK,CAAC,IAAI,KAAK,2BAAmB,CAAC,cAAc,EAAE;YACrD,OAAO,IAAI,CAAC;SACb;QACD,OAAO,KAAK,CAAC,aAAa,CAAC,uBAAe,CAAC,0BAA0B,CAAC,CAAC;KACxE;IAED,IAAI,OAAO,KAAK,CAAC,IAAI,KAAK,QAAQ,EAAE;QAClC,OAAO,gCAAwB,CAAC,GAAG,CAAC,KAAK,CAAC,IAAI,CAAC,CAAC;KACjD;IAED,OAAO,KAAK,CAAC;AACf,CAAC;AAtBD,4CAsBC"} \ No newline at end of file diff --git a/ts-ticket-office-service/node_modules/mongodb/lib/explain.js b/ts-ticket-office-service/node_modules/mongodb/lib/explain.js new file mode 100644 index 000000000..bc55e1fee --- /dev/null +++ b/ts-ticket-office-service/node_modules/mongodb/lib/explain.js @@ -0,0 +1,35 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.Explain = exports.ExplainVerbosity = void 0; +const error_1 = require("./error"); +/** @public */ +exports.ExplainVerbosity = Object.freeze({ + queryPlanner: 'queryPlanner', + queryPlannerExtended: 'queryPlannerExtended', + executionStats: 'executionStats', + allPlansExecution: 'allPlansExecution' +}); +/** @internal */ +class Explain { + constructor(verbosity) { + if (typeof verbosity === 'boolean') { + this.verbosity = verbosity + ? exports.ExplainVerbosity.allPlansExecution + : exports.ExplainVerbosity.queryPlanner; + } + else { + this.verbosity = verbosity; + } + } + static fromOptions(options) { + if ((options === null || options === void 0 ? void 0 : options.explain) == null) + return; + const explain = options.explain; + if (typeof explain === 'boolean' || typeof explain === 'string') { + return new Explain(explain); + } + throw new error_1.MongoInvalidArgumentError('Field "explain" must be a string or a boolean'); + } +} +exports.Explain = Explain; +//# sourceMappingURL=explain.js.map \ No newline at end of file diff --git a/ts-ticket-office-service/node_modules/mongodb/lib/explain.js.map b/ts-ticket-office-service/node_modules/mongodb/lib/explain.js.map new file mode 100644 index 000000000..ae503b22b --- /dev/null +++ b/ts-ticket-office-service/node_modules/mongodb/lib/explain.js.map @@ -0,0 +1 @@ +{"version":3,"file":"explain.js","sourceRoot":"","sources":["../src/explain.ts"],"names":[],"mappings":";;;AAAA,mCAAoD;AAEpD,cAAc;AACD,QAAA,gBAAgB,GAAG,MAAM,CAAC,MAAM,CAAC;IAC5C,YAAY,EAAE,cAAc;IAC5B,oBAAoB,EAAE,sBAAsB;IAC5C,cAAc,EAAE,gBAAgB;IAChC,iBAAiB,EAAE,mBAAmB;CAC9B,CAAC,CAAC;AAmBZ,gBAAgB;AAChB,MAAa,OAAO;IAGlB,YAAY,SAA+B;QACzC,IAAI,OAAO,SAAS,KAAK,SAAS,EAAE;YAClC,IAAI,CAAC,SAAS,GAAG,SAAS;gBACxB,CAAC,CAAC,wBAAgB,CAAC,iBAAiB;gBACpC,CAAC,CAAC,wBAAgB,CAAC,YAAY,CAAC;SACnC;aAAM;YACL,IAAI,CAAC,SAAS,GAAG,SAAS,CAAC;SAC5B;IACH,CAAC;IAED,MAAM,CAAC,WAAW,CAAC,OAAwB;QACzC,IAAI,CAAA,OAAO,aAAP,OAAO,uBAAP,OAAO,CAAE,OAAO,KAAI,IAAI;YAAE,OAAO;QAErC,MAAM,OAAO,GAAG,OAAO,CAAC,OAAO,CAAC;QAChC,IAAI,OAAO,OAAO,KAAK,SAAS,IAAI,OAAO,OAAO,KAAK,QAAQ,EAAE;YAC/D,OAAO,IAAI,OAAO,CAAC,OAAO,CAAC,CAAC;SAC7B;QAED,MAAM,IAAI,iCAAyB,CAAC,+CAA+C,CAAC,CAAC;IACvF,CAAC;CACF;AAvBD,0BAuBC"} \ No newline at end of file diff --git a/ts-ticket-office-service/node_modules/mongodb/lib/gridfs-stream/download.js b/ts-ticket-office-service/node_modules/mongodb/lib/gridfs-stream/download.js deleted file mode 100644 index d7dc284b6..000000000 --- a/ts-ticket-office-service/node_modules/mongodb/lib/gridfs-stream/download.js +++ /dev/null @@ -1,408 +0,0 @@ -var stream = require('stream'), - util = require('util'); - -module.exports = GridFSBucketReadStream; - -/** - * A readable stream that enables you to read buffers from GridFS. - * - * Do not instantiate this class directly. Use `openDownloadStream()` instead. - * - * @class - * @param {Collection} chunks Handle for chunks collection - * @param {Collection} files Handle for files collection - * @param {Object} readPreference The read preference to use - * @param {Object} filter The query to use to find the file document - * @param {Object} [options=null] Optional settings. - * @param {Number} [options.sort=null] Optional sort for the file find query - * @param {Number} [options.skip=null] Optional skip for the file find query - * @param {Number} [options.start=null] Optional 0-based offset in bytes to start streaming from - * @param {Number} [options.end=null] Optional 0-based offset in bytes to stop streaming before - * @fires GridFSBucketReadStream#error - * @fires GridFSBucketReadStream#file - * @return {GridFSBucketReadStream} a GridFSBucketReadStream instance. - */ - -function GridFSBucketReadStream(chunks, files, readPreference, filter, options) { - this.s = { - bytesRead: 0, - chunks: chunks, - cursor: null, - expected: 0, - files: files, - filter: filter, - init: false, - expectedEnd: 0, - file: null, - options: options, - readPreference: readPreference - }; - - stream.Readable.call(this); -} - -util.inherits(GridFSBucketReadStream, stream.Readable); - -/** - * An error occurred - * - * @event GridFSBucketReadStream#error - * @type {Error} - */ - -/** - * Fires when the stream loaded the file document corresponding to the - * provided id. - * - * @event GridFSBucketReadStream#file - * @type {object} - */ - -/** - * Emitted when a chunk of data is available to be consumed. - * - * @event GridFSBucketReadStream#data - * @type {object} - */ - -/** - * Fired when the stream is exhausted (no more data events). - * - * @event GridFSBucketReadStream#end - * @type {object} - */ - -/** - * Fired when the stream is exhausted and the underlying cursor is killed - * - * @event GridFSBucketReadStream#close - * @type {object} - */ - -/** - * Reads from the cursor and pushes to the stream. - * @method - */ - -GridFSBucketReadStream.prototype._read = function() { - var _this = this; - if (this.destroyed) { - return; - } - - waitForFile(_this, function() { - doRead(_this); - }); -}; - -/** - * Sets the 0-based offset in bytes to start streaming from. Throws - * an error if this stream has entered flowing mode - * (e.g. if you've already called `on('data')`) - * @method - * @param {Number} start Offset in bytes to start reading at - * @return {GridFSBucketReadStream} - */ - -GridFSBucketReadStream.prototype.start = function(start) { - throwIfInitialized(this); - this.s.options.start = start; - return this; -}; - -/** - * Sets the 0-based offset in bytes to start streaming from. Throws - * an error if this stream has entered flowing mode - * (e.g. if you've already called `on('data')`) - * @method - * @param {Number} end Offset in bytes to stop reading at - * @return {GridFSBucketReadStream} - */ - -GridFSBucketReadStream.prototype.end = function(end) { - throwIfInitialized(this); - this.s.options.end = end; - return this; -}; - -/** - * Marks this stream as aborted (will never push another `data` event) - * and kills the underlying cursor. Will emit the 'end' event, and then - * the 'close' event once the cursor is successfully killed. - * - * @method - * @param {GridFSBucket~errorCallback} [callback] called when the cursor is successfully closed or an error occurred. - * @fires GridFSBucketWriteStream#close - * @fires GridFSBucketWriteStream#end - */ - -GridFSBucketReadStream.prototype.abort = function(callback) { - var _this = this; - this.push(null); - this.destroyed = true; - if (this.s.cursor) { - this.s.cursor.close(function(error) { - _this.emit('close'); - callback && callback(error); - }); - } else { - if (!this.s.init) { - // If not initialized, fire close event because we will never - // get a cursor - _this.emit('close'); - } - callback && callback(); - } -}; - -/** - * @ignore - */ - -function throwIfInitialized(self) { - if (self.s.init) { - throw new Error('You cannot change options after the stream has entered' + - 'flowing mode!'); - } -} - -/** - * @ignore - */ - -function doRead(_this) { - if (_this.destroyed) { - return; - } - - _this.s.cursor.next(function(error, doc) { - if (_this.destroyed) { - return; - } - if (error) { - return __handleError(_this, error); - } - if (!doc) { - _this.push(null); - return _this.s.cursor.close(function(error) { - if (error) { - return __handleError(_this, error); - } - _this.emit('close'); - }); - } - - var bytesRemaining = _this.s.file.length - _this.s.bytesRead; - var expectedN = _this.s.expected++; - var expectedLength = Math.min(_this.s.file.chunkSize, - bytesRemaining); - - if (doc.n > expectedN) { - var errmsg = 'ChunkIsMissing: Got unexpected n: ' + doc.n + - ', expected: ' + expectedN; - return __handleError(_this, new Error(errmsg)); - } - - if (doc.n < expectedN) { - errmsg = 'ExtraChunk: Got unexpected n: ' + doc.n + - ', expected: ' + expectedN; - return __handleError(_this, new Error(errmsg)); - } - - if (doc.data.length() !== expectedLength) { - if (bytesRemaining <= 0) { - errmsg = 'ExtraChunk: Got unexpected n: ' + doc.n; - return __handleError(_this, new Error(errmsg)); - } - - errmsg = 'ChunkIsWrongSize: Got unexpected length: ' + - doc.data.length() + ', expected: ' + expectedLength; - return __handleError(_this, new Error(errmsg)); - } - - _this.s.bytesRead += doc.data.length(); - - if (doc.data.buffer.length === 0) { - return _this.push(null); - } - - var sliceStart = null; - var sliceEnd = null; - var buf = doc.data.buffer; - - if (_this.s.bytesToSkip != null) { - sliceStart = _this.s.bytesToSkip; - _this.s.bytesToSkip = 0; - } - - if (expectedN === _this.s.expectedEnd && _this.s.bytesToTrim != null) { - sliceEnd = _this.s.bytesToTrim; - } - - // If the remaining amount of data left is < chunkSize read the right amount of data - if (_this.s.options.end && ( - (_this.s.options.end - _this.s.bytesToSkip) < doc.data.length() - )) { - sliceEnd = (_this.s.options.end - _this.s.bytesToSkip); - } - - if (sliceStart != null || sliceEnd != null) { - buf = buf.slice(sliceStart || 0, sliceEnd || buf.length); - } - - _this.push(buf); - }) -} - -/** - * @ignore - */ - -function init(self) { - var findOneOptions = {}; - if (self.s.readPreference) { - findOneOptions.readPreference = self.s.readPreference; - } - if (self.s.options && self.s.options.sort) { - findOneOptions.sort = self.s.options.sort; - } - if (self.s.options && self.s.options.skip) { - findOneOptions.skip = self.s.options.skip; - } - - self.s.files.findOne(self.s.filter, findOneOptions, function(error, doc) { - if (error) { - return __handleError(self, error); - } - if (!doc) { - var identifier = self.s.filter._id ? - self.s.filter._id.toString() : self.s.filter.filename; - var errmsg = 'FileNotFound: file ' + identifier + ' was not found'; - var err = new Error(errmsg); - err.code = 'ENOENT'; - return __handleError(self, err); - } - - // If document is empty, kill the stream immediately and don't - // execute any reads - if (doc.length <= 0) { - self.push(null); - return; - } - - if (self.destroyed) { - // If user destroys the stream before we have a cursor, wait - // until the query is done to say we're 'closed' because we can't - // cancel a query. - self.emit('close'); - return; - } - - self.s.bytesToSkip = handleStartOption(self, doc, self.s.options); - - var filter = { files_id: doc._id }; - - // Currently (MongoDB 3.4.4) skip function does not support the index, - // it needs to retrieve all the documents first and then skip them. (CS-25811) - // As work around we use $gte on the "n" field. - if (self.s.options && self.s.options.start != null){ - var skip = Math.floor(self.s.options.start / doc.chunkSize); - if (skip > 0){ - filter["n"] = {"$gte": skip}; - } - } - self.s.cursor = self.s.chunks.find(filter).sort({ n: 1 }); - - if (self.s.readPreference) { - self.s.cursor.setReadPreference(self.s.readPreference); - } - - self.s.expectedEnd = Math.ceil(doc.length / doc.chunkSize); - self.s.file = doc; - self.s.bytesToTrim = handleEndOption(self, doc, self.s.cursor, - self.s.options); - self.emit('file', doc); - }); -} - -/** - * @ignore - */ - -function waitForFile(_this, callback) { - if (_this.s.file) { - return callback(); - } - - if (!_this.s.init) { - init(_this); - _this.s.init = true; - } - - _this.once('file', function() { - callback(); - }) -} - -/** - * @ignore - */ - -function handleStartOption(stream, doc, options) { - if (options && options.start != null) { - if (options.start > doc.length) { - throw new Error('Stream start (' + options.start + ') must not be ' + - 'more than the length of the file (' + doc.length +')'); - } - if (options.start < 0) { - throw new Error('Stream start (' + options.start + ') must not be ' + - 'negative'); - } - if (options.end != null && options.end < options.start) { - throw new Error('Stream start (' + options.start + ') must not be ' + - 'greater than stream end (' + options.end + ')'); - } - - stream.s.bytesRead = Math.floor(options.start / doc.chunkSize) * - doc.chunkSize; - stream.s.expected = Math.floor(options.start / doc.chunkSize); - - return options.start - stream.s.bytesRead; - } -} - -/** - * @ignore - */ - -function handleEndOption(stream, doc, cursor, options) { - if (options && options.end != null) { - if (options.end > doc.length) { - throw new Error('Stream end (' + options.end + ') must not be ' + - 'more than the length of the file (' + doc.length +')') - } - if (options.start < 0) { - throw new Error('Stream end (' + options.end + ') must not be ' + - 'negative'); - } - - var start = options.start != null ? - Math.floor(options.start / doc.chunkSize) : - 0; - - cursor.limit(Math.ceil(options.end / doc.chunkSize) - start); - - stream.s.expectedEnd = Math.ceil(options.end / doc.chunkSize); - - return (Math.ceil(options.end / doc.chunkSize) * doc.chunkSize) - - options.end; - } -} - -/** - * @ignore - */ - -function __handleError(_this, error) { - _this.emit('error', error); -} diff --git a/ts-ticket-office-service/node_modules/mongodb/lib/gridfs-stream/index.js b/ts-ticket-office-service/node_modules/mongodb/lib/gridfs-stream/index.js deleted file mode 100644 index e0e02c0a2..000000000 --- a/ts-ticket-office-service/node_modules/mongodb/lib/gridfs-stream/index.js +++ /dev/null @@ -1,367 +0,0 @@ -var Emitter = require('events').EventEmitter; -var GridFSBucketReadStream = require('./download'); -var GridFSBucketWriteStream = require('./upload'); -var shallowClone = require('../utils').shallowClone; -var toError = require('../utils').toError; -var util = require('util'); - -var DEFAULT_GRIDFS_BUCKET_OPTIONS = { - bucketName: 'fs', - chunkSizeBytes: 255 * 1024 -}; - -module.exports = GridFSBucket; - -/** - * Constructor for a streaming GridFS interface - * @class - * @param {Db} db A db handle - * @param {object} [options=null] Optional settings. - * @param {string} [options.bucketName="fs"] The 'files' and 'chunks' collections will be prefixed with the bucket name followed by a dot. - * @param {number} [options.chunkSizeBytes=255 * 1024] Number of bytes stored in each chunk. Defaults to 255KB - * @param {object} [options.writeConcern=null] Optional write concern to be passed to write operations, for instance `{ w: 1 }` - * @param {object} [options.readPreference=null] Optional read preference to be passed to read operations - * @fires GridFSBucketWriteStream#index - * @return {GridFSBucket} - */ - -function GridFSBucket(db, options) { - Emitter.apply(this); - this.setMaxListeners(0); - - if (options && typeof options === 'object') { - options = shallowClone(options); - var keys = Object.keys(DEFAULT_GRIDFS_BUCKET_OPTIONS); - for (var i = 0; i < keys.length; ++i) { - if (!options[keys[i]]) { - options[keys[i]] = DEFAULT_GRIDFS_BUCKET_OPTIONS[keys[i]]; - } - } - } else { - options = DEFAULT_GRIDFS_BUCKET_OPTIONS; - } - - this.s = { - db: db, - options: options, - _chunksCollection: db.collection(options.bucketName + '.chunks'), - _filesCollection: db.collection(options.bucketName + '.files'), - checkedIndexes: false, - calledOpenUploadStream: false, - promiseLibrary: db.s.promiseLibrary || - (typeof global.Promise == 'function' ? global.Promise : require('es6-promise').Promise) - }; -} - -util.inherits(GridFSBucket, Emitter); - -/** - * When the first call to openUploadStream is made, the upload stream will - * check to see if it needs to create the proper indexes on the chunks and - * files collections. This event is fired either when 1) it determines that - * no index creation is necessary, 2) when it successfully creates the - * necessary indexes. - * - * @event GridFSBucket#index - * @type {Error} - */ - -/** - * Returns a writable stream (GridFSBucketWriteStream) for writing - * buffers to GridFS. The stream's 'id' property contains the resulting - * file's id. - * @method - * @param {string} filename The value of the 'filename' key in the files doc - * @param {object} [options=null] Optional settings. - * @param {number} [options.chunkSizeBytes=null] Optional overwrite this bucket's chunkSizeBytes for this file - * @param {object} [options.metadata=null] Optional object to store in the file document's `metadata` field - * @param {string} [options.contentType=null] Optional string to store in the file document's `contentType` field - * @param {array} [options.aliases=null] Optional array of strings to store in the file document's `aliases` field - * @return {GridFSBucketWriteStream} - */ - -GridFSBucket.prototype.openUploadStream = function(filename, options) { - if (options) { - options = shallowClone(options); - } else { - options = {}; - } - if (!options.chunkSizeBytes) { - options.chunkSizeBytes = this.s.options.chunkSizeBytes; - } - return new GridFSBucketWriteStream(this, filename, options); -}; - -/** - * Returns a writable stream (GridFSBucketWriteStream) for writing - * buffers to GridFS for a custom file id. The stream's 'id' property contains the resulting - * file's id. - * @method - * @param {string|number|object} id A custom id used to identify the file - * @param {string} filename The value of the 'filename' key in the files doc - * @param {object} [options=null] Optional settings. - * @param {number} [options.chunkSizeBytes=null] Optional overwrite this bucket's chunkSizeBytes for this file - * @param {object} [options.metadata=null] Optional object to store in the file document's `metadata` field - * @param {string} [options.contentType=null] Optional string to store in the file document's `contentType` field - * @param {array} [options.aliases=null] Optional array of strings to store in the file document's `aliases` field - * @return {GridFSBucketWriteStream} - */ - -GridFSBucket.prototype.openUploadStreamWithId = function(id, filename, options) { - if (options) { - options = shallowClone(options); - } else { - options = {}; - } - - if (!options.chunkSizeBytes) { - options.chunkSizeBytes = this.s.options.chunkSizeBytes; - } - - options.id = id; - - return new GridFSBucketWriteStream(this, filename, options); -}; - -/** - * Returns a readable stream (GridFSBucketReadStream) for streaming file - * data from GridFS. - * @method - * @param {ObjectId} id The id of the file doc - * @param {Object} [options=null] Optional settings. - * @param {Number} [options.start=null] Optional 0-based offset in bytes to start streaming from - * @param {Number} [options.end=null] Optional 0-based offset in bytes to stop streaming before - * @return {GridFSBucketReadStream} - */ - -GridFSBucket.prototype.openDownloadStream = function(id, options) { - var filter = { _id: id }; - options = { - start: options && options.start, - end: options && options.end - }; - - return new GridFSBucketReadStream(this.s._chunksCollection, - this.s._filesCollection, this.s.options.readPreference, filter, options); -}; - -/** - * Deletes a file with the given id - * @method - * @param {ObjectId} id The id of the file doc - * @param {GridFSBucket~errorCallback} [callback] - */ - -GridFSBucket.prototype.delete = function(id, callback) { - if (typeof callback === 'function') { - return _delete(this, id, callback); - } - - var _this = this; - return new this.s.promiseLibrary(function(resolve, reject) { - _delete(_this, id, function(error, res) { - if (error) { - reject(error); - } else { - resolve(res); - } - }); - }); -}; - -/** - * @ignore - */ - -function _delete(_this, id, callback) { - _this.s._filesCollection.deleteOne({ _id: id }, function(error, res) { - if (error) { - return callback(error); - } - - _this.s._chunksCollection.deleteMany({ files_id: id }, function(error) { - if (error) { - return callback(error); - } - - // Delete orphaned chunks before returning FileNotFound - if (!res.result.n) { - var errmsg = 'FileNotFound: no file with id ' + id + ' found'; - return callback(new Error(errmsg)); - } - - callback(); - }); - }); -} - -/** - * Convenience wrapper around find on the files collection - * @method - * @param {Object} filter - * @param {Object} [options=null] Optional settings for cursor - * @param {number} [options.batchSize=null] Optional batch size for cursor - * @param {number} [options.limit=null] Optional limit for cursor - * @param {number} [options.maxTimeMS=null] Optional maxTimeMS for cursor - * @param {boolean} [options.noCursorTimeout=null] Optionally set cursor's `noCursorTimeout` flag - * @param {number} [options.skip=null] Optional skip for cursor - * @param {object} [options.sort=null] Optional sort for cursor - * @return {Cursor} - */ - -GridFSBucket.prototype.find = function(filter, options) { - filter = filter || {}; - options = options || {}; - - var cursor = this.s._filesCollection.find(filter); - - if (options.batchSize != null) { - cursor.batchSize(options.batchSize); - } - if (options.limit != null) { - cursor.limit(options.limit); - } - if (options.maxTimeMS != null) { - cursor.maxTimeMS(options.maxTimeMS); - } - if (options.noCursorTimeout != null) { - cursor.addCursorFlag('noCursorTimeout', options.noCursorTimeout); - } - if (options.skip != null) { - cursor.skip(options.skip); - } - if (options.sort != null) { - cursor.sort(options.sort); - } - - return cursor; -}; - -/** - * Returns a readable stream (GridFSBucketReadStream) for streaming the - * file with the given name from GridFS. If there are multiple files with - * the same name, this will stream the most recent file with the given name - * (as determined by the `uploadDate` field). You can set the `revision` - * option to change this behavior. - * @method - * @param {String} filename The name of the file to stream - * @param {Object} [options=null] Optional settings - * @param {number} [options.revision=-1] The revision number relative to the oldest file with the given filename. 0 gets you the oldest file, 1 gets you the 2nd oldest, -1 gets you the newest. - * @param {Number} [options.start=null] Optional 0-based offset in bytes to start streaming from - * @param {Number} [options.end=null] Optional 0-based offset in bytes to stop streaming before - * @return {GridFSBucketReadStream} - */ - -GridFSBucket.prototype.openDownloadStreamByName = function(filename, options) { - var sort = { uploadDate: -1 }; - var skip = null; - if (options && options.revision != null) { - if (options.revision >= 0) { - sort = { uploadDate: 1 }; - skip = options.revision; - } else { - skip = -options.revision - 1; - } - } - - var filter = { filename: filename }; - options = { - sort: sort, - skip: skip, - start: options && options.start, - end: options && options.end - }; - return new GridFSBucketReadStream(this.s._chunksCollection, - this.s._filesCollection, this.s.options.readPreference, filter, options); -}; - -/** - * Renames the file with the given _id to the given string - * @method - * @param {ObjectId} id the id of the file to rename - * @param {String} filename new name for the file - * @param {GridFSBucket~errorCallback} [callback] - */ - -GridFSBucket.prototype.rename = function(id, filename, callback) { - if (typeof callback === 'function') { - return _rename(this, id, filename, callback); - } - - var _this = this; - return new this.s.promiseLibrary(function(resolve, reject) { - _rename(_this, id, filename, function(error, res) { - if (error) { - reject(error); - } else { - resolve(res); - } - }); - }); -}; - -/** - * @ignore - */ - -function _rename(_this, id, filename, callback) { - var filter = { _id: id }; - var update = { $set: { filename: filename } }; - _this.s._filesCollection.updateOne(filter, update, function(error, res) { - if (error) { - return callback(error); - } - if (!res.result.n) { - return callback(toError('File with id ' + id + ' not found')); - } - callback(); - }); -} - -/** - * Removes this bucket's files collection, followed by its chunks collection. - * @method - * @param {GridFSBucket~errorCallback} [callback] - */ - -GridFSBucket.prototype.drop = function(callback) { - if (typeof callback === 'function') { - return _drop(this, callback); - } - - var _this = this; - return new this.s.promiseLibrary(function(resolve, reject) { - _drop(_this, function(error, res) { - if (error) { - reject(error); - } else { - resolve(res); - } - }); - }); -}; - -/** - * @ignore - */ - -function _drop(_this, callback) { - _this.s._filesCollection.drop(function(error) { - if (error) { - return callback(error); - } - _this.s._chunksCollection.drop(function(error) { - if (error) { - return callback(error); - } - - return callback(); - }); - }); -} - -/** - * Callback format for all GridFSBucket methods that can accept a callback. - * @callback GridFSBucket~errorCallback - * @param {MongoError} error An error instance representing any errors that occurred - */ diff --git a/ts-ticket-office-service/node_modules/mongodb/lib/gridfs-stream/upload.js b/ts-ticket-office-service/node_modules/mongodb/lib/gridfs-stream/upload.js deleted file mode 100644 index 180666ebe..000000000 --- a/ts-ticket-office-service/node_modules/mongodb/lib/gridfs-stream/upload.js +++ /dev/null @@ -1,527 +0,0 @@ -var core = require('mongodb-core'); -var crypto = require('crypto'); -var stream = require('stream'); -var util = require('util'); - -var ERROR_NAMESPACE_NOT_FOUND = 26; - -module.exports = GridFSBucketWriteStream; - -/** - * A writable stream that enables you to write buffers to GridFS. - * - * Do not instantiate this class directly. Use `openUploadStream()` instead. - * - * @class - * @param {GridFSBucket} bucket Handle for this stream's corresponding bucket - * @param {string} filename The value of the 'filename' key in the files doc - * @param {object} [options=null] Optional settings. - * @param {string|number|object} [options.id=null] Custom file id for the GridFS file. - * @param {number} [options.chunkSizeBytes=null] The chunk size to use, in bytes - * @param {number} [options.w=null] The write concern - * @param {number} [options.wtimeout=null] The write concern timeout - * @param {number} [options.j=null] The journal write concern - * @fires GridFSBucketWriteStream#error - * @fires GridFSBucketWriteStream#finish - * @return {GridFSBucketWriteStream} a GridFSBucketWriteStream instance. - */ - -function GridFSBucketWriteStream(bucket, filename, options) { - options = options || {}; - this.bucket = bucket; - this.chunks = bucket.s._chunksCollection; - this.filename = filename; - this.files = bucket.s._filesCollection; - this.options = options; - // Signals the write is all done - this.done = false; - - this.id = options.id ? options.id : core.BSON.ObjectId(); - this.chunkSizeBytes = this.options.chunkSizeBytes; - this.bufToStore = new Buffer(this.chunkSizeBytes); - this.length = 0; - this.md5 = crypto.createHash('md5'); - this.n = 0; - this.pos = 0; - this.state = { - streamEnd: false, - outstandingRequests: 0, - errored: false, - aborted: false, - promiseLibrary: this.bucket.s.promiseLibrary - }; - - if (!this.bucket.s.calledOpenUploadStream) { - this.bucket.s.calledOpenUploadStream = true; - - var _this = this; - checkIndexes(this, function() { - _this.bucket.s.checkedIndexes = true; - _this.bucket.emit('index'); - }); - } -} - -util.inherits(GridFSBucketWriteStream, stream.Writable); - -/** - * An error occurred - * - * @event GridFSBucketWriteStream#error - * @type {Error} - */ - -/** - * `end()` was called and the write stream successfully wrote the file - * metadata and all the chunks to MongoDB. - * - * @event GridFSBucketWriteStream#finish - * @type {object} - */ - -/** - * Write a buffer to the stream. - * - * @method - * @param {Buffer} chunk Buffer to write - * @param {String} encoding Optional encoding for the buffer - * @param {Function} callback Function to call when the chunk was added to the buffer, or if the entire chunk was persisted to MongoDB if this chunk caused a flush. - * @return {Boolean} False if this write required flushing a chunk to MongoDB. True otherwise. - */ - -GridFSBucketWriteStream.prototype.write = function(chunk, encoding, callback) { - var _this = this; - return waitForIndexes(this, function() { - return doWrite(_this, chunk, encoding, callback); - }); -}; - -/** - * Places this write stream into an aborted state (all future writes fail) - * and deletes all chunks that have already been written. - * - * @method - * @param {GridFSBucket~errorCallback} callback called when chunks are successfully removed or error occurred - * @return {Promise} if no callback specified - */ - -GridFSBucketWriteStream.prototype.abort = function(callback) { - if (this.state.streamEnd) { - var error = new Error('Cannot abort a stream that has already completed'); - if (typeof callback == 'function') { - return callback(error); - } - return this.state.promiseLibrary.reject(error); - } - if (this.state.aborted) { - error = new Error('Cannot call abort() on a stream twice'); - if (typeof callback == 'function') { - return callback(error); - } - return this.state.promiseLibrary.reject(error); - } - this.state.aborted = true; - this.chunks.deleteMany({ files_id: this.id }, function(error) { - if(typeof callback == 'function') callback(error); - }); -}; - -/** - * Tells the stream that no more data will be coming in. The stream will - * persist the remaining data to MongoDB, write the files document, and - * then emit a 'finish' event. - * - * @method - * @param {Buffer} chunk Buffer to write - * @param {String} encoding Optional encoding for the buffer - * @param {Function} callback Function to call when all files and chunks have been persisted to MongoDB - */ - -GridFSBucketWriteStream.prototype.end = function(chunk, encoding, callback) { - var _this = this; - if(typeof chunk == 'function') { - callback = chunk, chunk = null, encoding = null; - } else if(typeof encoding == 'function') { - callback = encoding, encoding = null; - } - - if (checkAborted(this, callback)) { - return; - } - this.state.streamEnd = true; - - if (callback) { - this.once('finish', function(result) { - callback(null, result); - }); - } - - if (!chunk) { - waitForIndexes(this, function() { - writeRemnant(_this); - }); - return; - } - - this.write(chunk, encoding, function() { - writeRemnant(_this); - }); -}; - -/** - * @ignore - */ - -function __handleError(_this, error, callback) { - if (_this.state.errored) { - return; - } - _this.state.errored = true; - if (callback) { - return callback(error); - } - _this.emit('error', error); -} - -/** - * @ignore - */ - -function createChunkDoc(filesId, n, data) { - return { - _id: core.BSON.ObjectId(), - files_id: filesId, - n: n, - data: data - }; -} - -/** - * @ignore - */ - -function checkChunksIndex(_this, callback) { - _this.chunks.listIndexes().toArray(function(error, indexes) { - if (error) { - // Collection doesn't exist so create index - if (error.code === ERROR_NAMESPACE_NOT_FOUND) { - var index = { files_id: 1, n: 1 }; - _this.chunks.createIndex(index, { background: false, unique: true }, function(error) { - if (error) { - return callback(error); - } - - callback(); - }); - return; - } - return callback(error); - } - - var hasChunksIndex = false; - indexes.forEach(function(index) { - if (index.key) { - var keys = Object.keys(index.key); - if (keys.length === 2 && index.key.files_id === 1 && - index.key.n === 1) { - hasChunksIndex = true; - } - } - }); - - if (hasChunksIndex) { - callback(); - } else { - index = { files_id: 1, n: 1 }; - var indexOptions = getWriteOptions(_this); - - indexOptions.background = false; - indexOptions.unique = true; - - _this.chunks.createIndex(index, indexOptions, function(error) { - if (error) { - return callback(error); - } - - callback(); - }); - } - }); -} - -/** - * @ignore - */ - -function checkDone(_this, callback) { - if(_this.done) return true; - if (_this.state.streamEnd && - _this.state.outstandingRequests === 0 && - !_this.state.errored) { - // Set done so we dont' trigger duplicate createFilesDoc - _this.done = true; - // Create a new files doc - var filesDoc = createFilesDoc(_this.id, _this.length, _this.chunkSizeBytes, - _this.md5.digest('hex'), _this.filename, _this.options.contentType, - _this.options.aliases, _this.options.metadata); - - if (checkAborted(_this, callback)) { - return false; - } - - _this.files.insert(filesDoc, getWriteOptions(_this), function(error) { - if (error) { - return __handleError(_this, error, callback); - } - _this.emit('finish', filesDoc); - }); - - return true; - } - - return false; -} - -/** - * @ignore - */ - -function checkIndexes(_this, callback) { - _this.files.findOne({}, { _id: 1 }, function(error, doc) { - if (error) { - return callback(error); - } - if (doc) { - return callback(); - } - - _this.files.listIndexes().toArray(function(error, indexes) { - if (error) { - // Collection doesn't exist so create index - if (error.code === ERROR_NAMESPACE_NOT_FOUND) { - var index = { filename: 1, uploadDate: 1 }; - _this.files.createIndex(index, { background: false }, function(error) { - if (error) { - return callback(error); - } - - checkChunksIndex(_this, callback); - }); - return; - } - return callback(error); - } - - var hasFileIndex = false; - indexes.forEach(function(index) { - var keys = Object.keys(index.key); - if (keys.length === 2 && index.key.filename === 1 && - index.key.uploadDate === 1) { - hasFileIndex = true; - } - }); - - if (hasFileIndex) { - checkChunksIndex(_this, callback); - } else { - index = { filename: 1, uploadDate: 1 }; - - var indexOptions = getWriteOptions(_this); - - indexOptions.background = false; - - _this.files.createIndex(index, indexOptions, function(error) { - if (error) { - return callback(error); - } - - checkChunksIndex(_this, callback); - }); - } - }); - }); -} - -/** - * @ignore - */ - -function createFilesDoc(_id, length, chunkSize, md5, filename, contentType, - aliases, metadata) { - var ret = { - _id: _id, - length: length, - chunkSize: chunkSize, - uploadDate: new Date(), - md5: md5, - filename: filename - }; - - if (contentType) { - ret.contentType = contentType; - } - - if (aliases) { - ret.aliases = aliases; - } - - if (metadata) { - ret.metadata = metadata; - } - - return ret; -} - -/** - * @ignore - */ - -function doWrite(_this, chunk, encoding, callback) { - if (checkAborted(_this, callback)) { - return false; - } - - var inputBuf = (Buffer.isBuffer(chunk)) ? - chunk : new Buffer(chunk, encoding); - - _this.length += inputBuf.length; - - // Input is small enough to fit in our buffer - if (_this.pos + inputBuf.length < _this.chunkSizeBytes) { - inputBuf.copy(_this.bufToStore, _this.pos); - _this.pos += inputBuf.length; - - callback && callback(); - - // Note that we reverse the typical semantics of write's return value - // to be compatible with node's `.pipe()` function. - // True means client can keep writing. - return true; - } - - // Otherwise, buffer is too big for current chunk, so we need to flush - // to MongoDB. - var inputBufRemaining = inputBuf.length; - var spaceRemaining = _this.chunkSizeBytes - _this.pos; - var numToCopy = Math.min(spaceRemaining, inputBuf.length); - var outstandingRequests = 0; - while (inputBufRemaining > 0) { - var inputBufPos = inputBuf.length - inputBufRemaining; - inputBuf.copy(_this.bufToStore, _this.pos, - inputBufPos, inputBufPos + numToCopy); - _this.pos += numToCopy; - spaceRemaining -= numToCopy; - if (spaceRemaining === 0) { - _this.md5.update(_this.bufToStore); - var doc = createChunkDoc(_this.id, _this.n, _this.bufToStore); - ++_this.state.outstandingRequests; - ++outstandingRequests; - - if (checkAborted(_this, callback)) { - return false; - } - - _this.chunks.insert(doc, getWriteOptions(_this), function(error) { - if (error) { - return __handleError(_this, error); - } - --_this.state.outstandingRequests; - --outstandingRequests; - - if (!outstandingRequests) { - _this.emit('drain', doc); - callback && callback(); - checkDone(_this); - } - }); - - spaceRemaining = _this.chunkSizeBytes; - _this.pos = 0; - ++_this.n; - } - inputBufRemaining -= numToCopy; - numToCopy = Math.min(spaceRemaining, inputBufRemaining); - } - - // Note that we reverse the typical semantics of write's return value - // to be compatible with node's `.pipe()` function. - // False means the client should wait for the 'drain' event. - return false; -} - -/** - * @ignore - */ - -function getWriteOptions(_this) { - var obj = {}; - if (_this.options.writeConcern) { - obj.w = _this.options.writeConcern.w; - obj.wtimeout = _this.options.writeConcern.wtimeout; - obj.j = _this.options.writeConcern.j; - } - return obj; -} - -/** - * @ignore - */ - -function waitForIndexes(_this, callback) { - if (_this.bucket.s.checkedIndexes) { - return callback(false); - } - - _this.bucket.once('index', function() { - callback(true); - }); - - return true; -} - -/** - * @ignore - */ - -function writeRemnant(_this, callback) { - // Buffer is empty, so don't bother to insert - if (_this.pos === 0) { - return checkDone(_this, callback); - } - - ++_this.state.outstandingRequests; - - // Create a new buffer to make sure the buffer isn't bigger than it needs - // to be. - var remnant = new Buffer(_this.pos); - _this.bufToStore.copy(remnant, 0, 0, _this.pos); - _this.md5.update(remnant); - var doc = createChunkDoc(_this.id, _this.n, remnant); - - // If the stream was aborted, do not write remnant - if (checkAborted(_this, callback)) { - return false; - } - - _this.chunks.insert(doc, getWriteOptions(_this), function(error) { - if (error) { - return __handleError(_this, error); - } - --_this.state.outstandingRequests; - checkDone(_this); - }); -} - -/** - * @ignore - */ - -function checkAborted(_this, callback) { - if (_this.state.aborted) { - if(typeof callback == 'function') { - callback(new Error('this stream has been aborted')); - } - return true; - } - return false; -} diff --git a/ts-ticket-office-service/node_modules/mongodb/lib/gridfs/chunk.js b/ts-ticket-office-service/node_modules/mongodb/lib/gridfs/chunk.js deleted file mode 100644 index 9100197d9..000000000 --- a/ts-ticket-office-service/node_modules/mongodb/lib/gridfs/chunk.js +++ /dev/null @@ -1,230 +0,0 @@ -"use strict"; - -var Binary = require('mongodb-core').BSON.Binary, - ObjectID = require('mongodb-core').BSON.ObjectID; - -/** - * Class for representing a single chunk in GridFS. - * - * @class - * - * @param file {GridStore} The {@link GridStore} object holding this chunk. - * @param mongoObject {object} The mongo object representation of this chunk. - * - * @throws Error when the type of data field for {@link mongoObject} is not - * supported. Currently supported types for data field are instances of - * {@link String}, {@link Array}, {@link Binary} and {@link Binary} - * from the bson module - * - * @see Chunk#buildMongoObject - */ -var Chunk = function(file, mongoObject, writeConcern) { - if(!(this instanceof Chunk)) return new Chunk(file, mongoObject); - - this.file = file; - var mongoObjectFinal = mongoObject == null ? {} : mongoObject; - this.writeConcern = writeConcern || {w:1}; - this.objectId = mongoObjectFinal._id == null ? new ObjectID() : mongoObjectFinal._id; - this.chunkNumber = mongoObjectFinal.n == null ? 0 : mongoObjectFinal.n; - this.data = new Binary(); - - if(typeof mongoObjectFinal.data == "string") { - var buffer = new Buffer(mongoObjectFinal.data.length); - buffer.write(mongoObjectFinal.data, 0, mongoObjectFinal.data.length, 'binary'); - this.data = new Binary(buffer); - } else if(Array.isArray(mongoObjectFinal.data)) { - buffer = new Buffer(mongoObjectFinal.data.length); - var data = mongoObjectFinal.data.join(''); - buffer.write(data, 0, data.length, 'binary'); - this.data = new Binary(buffer); - } else if(mongoObjectFinal.data && mongoObjectFinal.data._bsontype === 'Binary') { - this.data = mongoObjectFinal.data; - } else if(!Buffer.isBuffer(mongoObjectFinal.data) && !(mongoObjectFinal.data == null)){ - throw Error("Illegal chunk format"); - } - - // Update position - this.internalPosition = 0; -}; - -/** - * Writes a data to this object and advance the read/write head. - * - * @param data {string} the data to write - * @param callback {function(*, GridStore)} This will be called after executing - * this method. The first parameter will contain null and the second one - * will contain a reference to this object. - */ -Chunk.prototype.write = function(data, callback) { - this.data.write(data, this.internalPosition, data.length, 'binary'); - this.internalPosition = this.data.length(); - if(callback != null) return callback(null, this); - return this; -}; - -/** - * Reads data and advances the read/write head. - * - * @param length {number} The length of data to read. - * - * @return {string} The data read if the given length will not exceed the end of - * the chunk. Returns an empty String otherwise. - */ -Chunk.prototype.read = function(length) { - // Default to full read if no index defined - length = length == null || length == 0 ? this.length() : length; - - if(this.length() - this.internalPosition + 1 >= length) { - var data = this.data.read(this.internalPosition, length); - this.internalPosition = this.internalPosition + length; - return data; - } else { - return ''; - } -}; - -Chunk.prototype.readSlice = function(length) { - if ((this.length() - this.internalPosition) >= length) { - var data = null; - if (this.data.buffer != null) { //Pure BSON - data = this.data.buffer.slice(this.internalPosition, this.internalPosition + length); - } else { //Native BSON - data = new Buffer(length); - length = this.data.readInto(data, this.internalPosition); - } - this.internalPosition = this.internalPosition + length; - return data; - } else { - return null; - } -}; - -/** - * Checks if the read/write head is at the end. - * - * @return {boolean} Whether the read/write head has reached the end of this - * chunk. - */ -Chunk.prototype.eof = function() { - return this.internalPosition == this.length() ? true : false; -}; - -/** - * Reads one character from the data of this chunk and advances the read/write - * head. - * - * @return {string} a single character data read if the the read/write head is - * not at the end of the chunk. Returns an empty String otherwise. - */ -Chunk.prototype.getc = function() { - return this.read(1); -}; - -/** - * Clears the contents of the data in this chunk and resets the read/write head - * to the initial position. - */ -Chunk.prototype.rewind = function() { - this.internalPosition = 0; - this.data = new Binary(); -}; - -/** - * Saves this chunk to the database. Also overwrites existing entries having the - * same id as this chunk. - * - * @param callback {function(*, GridStore)} This will be called after executing - * this method. The first parameter will contain null and the second one - * will contain a reference to this object. - */ -Chunk.prototype.save = function(options, callback) { - var self = this; - if(typeof options == 'function') { - callback = options; - options = {}; - } - - self.file.chunkCollection(function(err, collection) { - if(err) return callback(err); - - // Merge the options - var writeOptions = { upsert: true }; - for(var name in options) writeOptions[name] = options[name]; - for(name in self.writeConcern) writeOptions[name] = self.writeConcern[name]; - - if(self.data.length() > 0) { - self.buildMongoObject(function(mongoObject) { - var options = {forceServerObjectId:true}; - for(var name in self.writeConcern) { - options[name] = self.writeConcern[name]; - } - - collection.replaceOne({'_id':self.objectId}, mongoObject, writeOptions, function(err) { - callback(err, self); - }); - }); - } else { - callback(null, self); - } - // }); - }); -}; - -/** - * Creates a mongoDB object representation of this chunk. - * - * @param callback {function(Object)} This will be called after executing this - * method. The object will be passed to the first parameter and will have - * the structure: - * - *

- *        {
- *          '_id' : , // {number} id for this chunk
- *          'files_id' : , // {number} foreign key to the file collection
- *          'n' : , // {number} chunk number
- *          'data' : , // {bson#Binary} the chunk data itself
- *        }
- *        
- * - * @see MongoDB GridFS Chunk Object Structure - */ -Chunk.prototype.buildMongoObject = function(callback) { - var mongoObject = { - 'files_id': this.file.fileId, - 'n': this.chunkNumber, - 'data': this.data}; - // If we are saving using a specific ObjectId - if(this.objectId != null) mongoObject._id = this.objectId; - - callback(mongoObject); -}; - -/** - * @return {number} the length of the data - */ -Chunk.prototype.length = function() { - return this.data.length(); -}; - -/** - * The position of the read/write head - * @name position - * @lends Chunk# - * @field - */ -Object.defineProperty(Chunk.prototype, "position", { enumerable: true - , get: function () { - return this.internalPosition; - } - , set: function(value) { - this.internalPosition = value; - } -}); - -/** - * The default chunk size - * @constant - */ -Chunk.DEFAULT_CHUNK_SIZE = 1024 * 255; - -module.exports = Chunk; diff --git a/ts-ticket-office-service/node_modules/mongodb/lib/gridfs/download.js b/ts-ticket-office-service/node_modules/mongodb/lib/gridfs/download.js new file mode 100644 index 000000000..ad7c2d08f --- /dev/null +++ b/ts-ticket-office-service/node_modules/mongodb/lib/gridfs/download.js @@ -0,0 +1,317 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.GridFSBucketReadStream = void 0; +const stream_1 = require("stream"); +const error_1 = require("../error"); +/** + * A readable stream that enables you to read buffers from GridFS. + * + * Do not instantiate this class directly. Use `openDownloadStream()` instead. + * @public + */ +class GridFSBucketReadStream extends stream_1.Readable { + /** @internal + * @param chunks - Handle for chunks collection + * @param files - Handle for files collection + * @param readPreference - The read preference to use + * @param filter - The filter to use to find the file document + */ + constructor(chunks, files, readPreference, filter, options) { + super(); + this.s = { + bytesToTrim: 0, + bytesToSkip: 0, + bytesRead: 0, + chunks, + expected: 0, + files, + filter, + init: false, + expectedEnd: 0, + options: { + start: 0, + end: 0, + ...options + }, + readPreference + }; + } + /** + * Reads from the cursor and pushes to the stream. + * Private Impl, do not call directly + * @internal + */ + _read() { + if (this.destroyed) + return; + waitForFile(this, () => doRead(this)); + } + /** + * Sets the 0-based offset in bytes to start streaming from. Throws + * an error if this stream has entered flowing mode + * (e.g. if you've already called `on('data')`) + * + * @param start - 0-based offset in bytes to start streaming from + */ + start(start = 0) { + throwIfInitialized(this); + this.s.options.start = start; + return this; + } + /** + * Sets the 0-based offset in bytes to start streaming from. Throws + * an error if this stream has entered flowing mode + * (e.g. if you've already called `on('data')`) + * + * @param end - Offset in bytes to stop reading at + */ + end(end = 0) { + throwIfInitialized(this); + this.s.options.end = end; + return this; + } + /** + * Marks this stream as aborted (will never push another `data` event) + * and kills the underlying cursor. Will emit the 'end' event, and then + * the 'close' event once the cursor is successfully killed. + * + * @param callback - called when the cursor is successfully closed or an error occurred. + */ + abort(callback) { + this.push(null); + this.destroyed = true; + if (this.s.cursor) { + this.s.cursor.close(error => { + this.emit(GridFSBucketReadStream.CLOSE); + callback && callback(error); + }); + } + else { + if (!this.s.init) { + // If not initialized, fire close event because we will never + // get a cursor + this.emit(GridFSBucketReadStream.CLOSE); + } + callback && callback(); + } + } +} +exports.GridFSBucketReadStream = GridFSBucketReadStream; +/** + * An error occurred + * @event + */ +GridFSBucketReadStream.ERROR = 'error'; +/** + * Fires when the stream loaded the file document corresponding to the provided id. + * @event + */ +GridFSBucketReadStream.FILE = 'file'; +/** + * Emitted when a chunk of data is available to be consumed. + * @event + */ +GridFSBucketReadStream.DATA = 'data'; +/** + * Fired when the stream is exhausted (no more data events). + * @event + */ +GridFSBucketReadStream.END = 'end'; +/** + * Fired when the stream is exhausted and the underlying cursor is killed + * @event + */ +GridFSBucketReadStream.CLOSE = 'close'; +function throwIfInitialized(stream) { + if (stream.s.init) { + throw new error_1.MongoGridFSStreamError('Options cannot be changed after the stream is initialized'); + } +} +function doRead(stream) { + if (stream.destroyed) + return; + if (!stream.s.cursor) + return; + if (!stream.s.file) + return; + stream.s.cursor.next((error, doc) => { + if (stream.destroyed) { + return; + } + if (error) { + stream.emit(GridFSBucketReadStream.ERROR, error); + return; + } + if (!doc) { + stream.push(null); + process.nextTick(() => { + if (!stream.s.cursor) + return; + stream.s.cursor.close(error => { + if (error) { + stream.emit(GridFSBucketReadStream.ERROR, error); + return; + } + stream.emit(GridFSBucketReadStream.CLOSE); + }); + }); + return; + } + if (!stream.s.file) + return; + const bytesRemaining = stream.s.file.length - stream.s.bytesRead; + const expectedN = stream.s.expected++; + const expectedLength = Math.min(stream.s.file.chunkSize, bytesRemaining); + if (doc.n > expectedN) { + return stream.emit(GridFSBucketReadStream.ERROR, new error_1.MongoGridFSChunkError(`ChunkIsMissing: Got unexpected n: ${doc.n}, expected: ${expectedN}`)); + } + if (doc.n < expectedN) { + return stream.emit(GridFSBucketReadStream.ERROR, new error_1.MongoGridFSChunkError(`ExtraChunk: Got unexpected n: ${doc.n}, expected: ${expectedN}`)); + } + let buf = Buffer.isBuffer(doc.data) ? doc.data : doc.data.buffer; + if (buf.byteLength !== expectedLength) { + if (bytesRemaining <= 0) { + return stream.emit(GridFSBucketReadStream.ERROR, new error_1.MongoGridFSChunkError(`ExtraChunk: Got unexpected n: ${doc.n}, expected file length ${stream.s.file.length} bytes but already read ${stream.s.bytesRead} bytes`)); + } + return stream.emit(GridFSBucketReadStream.ERROR, new error_1.MongoGridFSChunkError(`ChunkIsWrongSize: Got unexpected length: ${buf.byteLength}, expected: ${expectedLength}`)); + } + stream.s.bytesRead += buf.byteLength; + if (buf.byteLength === 0) { + return stream.push(null); + } + let sliceStart = null; + let sliceEnd = null; + if (stream.s.bytesToSkip != null) { + sliceStart = stream.s.bytesToSkip; + stream.s.bytesToSkip = 0; + } + const atEndOfStream = expectedN === stream.s.expectedEnd - 1; + const bytesLeftToRead = stream.s.options.end - stream.s.bytesToSkip; + if (atEndOfStream && stream.s.bytesToTrim != null) { + sliceEnd = stream.s.file.chunkSize - stream.s.bytesToTrim; + } + else if (stream.s.options.end && bytesLeftToRead < doc.data.byteLength) { + sliceEnd = bytesLeftToRead; + } + if (sliceStart != null || sliceEnd != null) { + buf = buf.slice(sliceStart || 0, sliceEnd || buf.byteLength); + } + stream.push(buf); + return; + }); +} +function init(stream) { + const findOneOptions = {}; + if (stream.s.readPreference) { + findOneOptions.readPreference = stream.s.readPreference; + } + if (stream.s.options && stream.s.options.sort) { + findOneOptions.sort = stream.s.options.sort; + } + if (stream.s.options && stream.s.options.skip) { + findOneOptions.skip = stream.s.options.skip; + } + stream.s.files.findOne(stream.s.filter, findOneOptions, (error, doc) => { + if (error) { + return stream.emit(GridFSBucketReadStream.ERROR, error); + } + if (!doc) { + const identifier = stream.s.filter._id + ? stream.s.filter._id.toString() + : stream.s.filter.filename; + const errmsg = `FileNotFound: file ${identifier} was not found`; + // TODO(NODE-3483) + const err = new error_1.MongoRuntimeError(errmsg); + err.code = 'ENOENT'; // TODO: NODE-3338 set property as part of constructor + return stream.emit(GridFSBucketReadStream.ERROR, err); + } + // If document is empty, kill the stream immediately and don't + // execute any reads + if (doc.length <= 0) { + stream.push(null); + return; + } + if (stream.destroyed) { + // If user destroys the stream before we have a cursor, wait + // until the query is done to say we're 'closed' because we can't + // cancel a query. + stream.emit(GridFSBucketReadStream.CLOSE); + return; + } + try { + stream.s.bytesToSkip = handleStartOption(stream, doc, stream.s.options); + } + catch (error) { + return stream.emit(GridFSBucketReadStream.ERROR, error); + } + const filter = { files_id: doc._id }; + // Currently (MongoDB 3.4.4) skip function does not support the index, + // it needs to retrieve all the documents first and then skip them. (CS-25811) + // As work around we use $gte on the "n" field. + if (stream.s.options && stream.s.options.start != null) { + const skip = Math.floor(stream.s.options.start / doc.chunkSize); + if (skip > 0) { + filter['n'] = { $gte: skip }; + } + } + stream.s.cursor = stream.s.chunks.find(filter).sort({ n: 1 }); + if (stream.s.readPreference) { + stream.s.cursor.withReadPreference(stream.s.readPreference); + } + stream.s.expectedEnd = Math.ceil(doc.length / doc.chunkSize); + stream.s.file = doc; + try { + stream.s.bytesToTrim = handleEndOption(stream, doc, stream.s.cursor, stream.s.options); + } + catch (error) { + return stream.emit(GridFSBucketReadStream.ERROR, error); + } + stream.emit(GridFSBucketReadStream.FILE, doc); + return; + }); +} +function waitForFile(stream, callback) { + if (stream.s.file) { + return callback(); + } + if (!stream.s.init) { + init(stream); + stream.s.init = true; + } + stream.once('file', () => { + callback(); + }); +} +function handleStartOption(stream, doc, options) { + if (options && options.start != null) { + if (options.start > doc.length) { + throw new error_1.MongoInvalidArgumentError(`Stream start (${options.start}) must not be more than the length of the file (${doc.length})`); + } + if (options.start < 0) { + throw new error_1.MongoInvalidArgumentError(`Stream start (${options.start}) must not be negative`); + } + if (options.end != null && options.end < options.start) { + throw new error_1.MongoInvalidArgumentError(`Stream start (${options.start}) must not be greater than stream end (${options.end})`); + } + stream.s.bytesRead = Math.floor(options.start / doc.chunkSize) * doc.chunkSize; + stream.s.expected = Math.floor(options.start / doc.chunkSize); + return options.start - stream.s.bytesRead; + } + throw new error_1.MongoInvalidArgumentError('Start option must be defined'); +} +function handleEndOption(stream, doc, cursor, options) { + if (options && options.end != null) { + if (options.end > doc.length) { + throw new error_1.MongoInvalidArgumentError(`Stream end (${options.end}) must not be more than the length of the file (${doc.length})`); + } + if (options.start == null || options.start < 0) { + throw new error_1.MongoInvalidArgumentError(`Stream end (${options.end}) must not be negative`); + } + const start = options.start != null ? Math.floor(options.start / doc.chunkSize) : 0; + cursor.limit(Math.ceil(options.end / doc.chunkSize) - start); + stream.s.expectedEnd = Math.ceil(options.end / doc.chunkSize); + return Math.ceil(options.end / doc.chunkSize) * doc.chunkSize - options.end; + } + throw new error_1.MongoInvalidArgumentError('End option must be defined'); +} +//# sourceMappingURL=download.js.map \ No newline at end of file diff --git a/ts-ticket-office-service/node_modules/mongodb/lib/gridfs/download.js.map b/ts-ticket-office-service/node_modules/mongodb/lib/gridfs/download.js.map new file mode 100644 index 000000000..a06049afc --- /dev/null +++ b/ts-ticket-office-service/node_modules/mongodb/lib/gridfs/download.js.map @@ -0,0 +1 @@ +{"version":3,"file":"download.js","sourceRoot":"","sources":["../../src/gridfs/download.ts"],"names":[],"mappings":";;;AAAA,mCAAkC;AAKlC,oCAKkB;AA2DlB;;;;;GAKG;AACH,MAAa,sBAAuB,SAAQ,iBAAQ;IA8BlD;;;;;OAKG;IACH,YACE,MAA+B,EAC/B,KAA6B,EAC7B,cAA0C,EAC1C,MAAgB,EAChB,OAAuC;QAEvC,KAAK,EAAE,CAAC;QACR,IAAI,CAAC,CAAC,GAAG;YACP,WAAW,EAAE,CAAC;YACd,WAAW,EAAE,CAAC;YACd,SAAS,EAAE,CAAC;YACZ,MAAM;YACN,QAAQ,EAAE,CAAC;YACX,KAAK;YACL,MAAM;YACN,IAAI,EAAE,KAAK;YACX,WAAW,EAAE,CAAC;YACd,OAAO,EAAE;gBACP,KAAK,EAAE,CAAC;gBACR,GAAG,EAAE,CAAC;gBACN,GAAG,OAAO;aACX;YACD,cAAc;SACf,CAAC;IACJ,CAAC;IAED;;;;OAIG;IACM,KAAK;QACZ,IAAI,IAAI,CAAC,SAAS;YAAE,OAAO;QAC3B,WAAW,CAAC,IAAI,EAAE,GAAG,EAAE,CAAC,MAAM,CAAC,IAAI,CAAC,CAAC,CAAC;I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AAO,CAAC,GAAG,mDAAmD,GAAG,CAAC,MAAM,GAAG,CAC3F,CAAC;SACH;QACD,IAAI,OAAO,CAAC,KAAK,IAAI,IAAI,IAAI,OAAO,CAAC,KAAK,GAAG,CAAC,EAAE;YAC9C,MAAM,IAAI,iCAAyB,CAAC,eAAe,OAAO,CAAC,GAAG,wBAAwB,CAAC,CAAC;SACzF;QAED,MAAM,KAAK,GAAG,OAAO,CAAC,KAAK,IAAI,IAAI,CAAC,CAAC,CAAC,IAAI,CAAC,KAAK,CAAC,OAAO,CAAC,KAAK,GAAG,GAAG,CAAC,SAAS,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC;QAEpF,MAAM,CAAC,KAAK,CAAC,IAAI,CAAC,IAAI,CAAC,OAAO,CAAC,GAAG,GAAG,GAAG,CAAC,SAAS,CAAC,GAAG,KAAK,CAAC,CAAC;QAE7D,MAAM,CAAC,CAAC,CAAC,WAAW,GAAG,IAAI,CAAC,IAAI,CAAC,OAAO,CAAC,GAAG,GAAG,GAAG,CAAC,SAAS,CAAC,CAAC;QAE9D,OAAO,IAAI,CAAC,IAAI,CAAC,OAAO,CAAC,GAAG,GAAG,GAAG,CAAC,SAAS,CAAC,GAAG,GAAG,CAAC,SAAS,GAAG,OAAO,CAAC,GAAG,CAAC;KAC7E;IACD,MAAM,IAAI,iCAAyB,CAAC,4BAA4B,CAAC,CAAC;AACpE,CAAC"} \ No newline at end of file diff --git a/ts-ticket-office-service/node_modules/mongodb/lib/gridfs/grid_store.js b/ts-ticket-office-service/node_modules/mongodb/lib/gridfs/grid_store.js deleted file mode 100644 index ebf6613fc..000000000 --- a/ts-ticket-office-service/node_modules/mongodb/lib/gridfs/grid_store.js +++ /dev/null @@ -1,1954 +0,0 @@ -"use strict"; - -/** - * @fileOverview GridFS is a tool for MongoDB to store files to the database. - * Because of the restrictions of the object size the database can hold, a - * facility to split a file into several chunks is needed. The {@link GridStore} - * class offers a simplified api to interact with files while managing the - * chunks of split files behind the scenes. More information about GridFS can be - * found here. - * - * @example - * var MongoClient = require('mongodb').MongoClient, - * GridStore = require('mongodb').GridStore, - * ObjectID = require('mongodb').ObjectID, - * test = require('assert'); - * - * // Connection url - * var url = 'mongodb://localhost:27017/test'; - * // Connect using MongoClient - * MongoClient.connect(url, function(err, db) { - * var gridStore = new GridStore(db, null, "w"); - * gridStore.open(function(err, gridStore) { - * gridStore.write("hello world!", function(err, gridStore) { - * gridStore.close(function(err, result) { - * - * // Let's read the file using object Id - * GridStore.read(db, result._id, function(err, data) { - * test.equal('hello world!', data); - * db.close(); - * test.done(); - * }); - * }); - * }); - * }); - * }); - */ -var Chunk = require('./chunk'), - ObjectID = require('mongodb-core').BSON.ObjectID, - ReadPreference = require('../read_preference'), - Buffer = require('buffer').Buffer, - Collection = require('../collection'), - fs = require('fs'), - f = require('util').format, - util = require('util'), - Define = require('../metadata'), - MongoError = require('mongodb-core').MongoError, - inherits = util.inherits, - Duplex = require('stream').Duplex || require('readable-stream').Duplex, - shallowClone = require('../utils').shallowClone; - -var REFERENCE_BY_FILENAME = 0, - REFERENCE_BY_ID = 1; - -/** - * Namespace provided by the mongodb-core and node.js - * @external Duplex - */ - -/** - * Create a new GridStore instance - * - * Modes - * - **"r"** - read only. This is the default mode. - * - **"w"** - write in truncate mode. Existing data will be overwritten. - * - * @class - * @param {Db} db A database instance to interact with. - * @param {object} [id] optional unique id for this file - * @param {string} [filename] optional filename for this file, no unique constrain on the field - * @param {string} mode set the mode for this file. - * @param {object} [options=null] Optional settings. - * @param {(number|string)} [options.w=null] The write concern. - * @param {number} [options.wtimeout=null] The write concern timeout. - * @param {boolean} [options.j=false] Specify a journal write concern. - * @param {boolean} [options.fsync=false] Specify a file sync write concern. - * @param {string} [options.root=null] Root collection to use. Defaults to **{GridStore.DEFAULT_ROOT_COLLECTION}**. - * @param {string} [options.content_type=null] MIME type of the file. Defaults to **{GridStore.DEFAULT_CONTENT_TYPE}**. - * @param {number} [options.chunk_size=261120] Size for the chunk. Defaults to **{Chunk.DEFAULT_CHUNK_SIZE}**. - * @param {object} [options.metadata=null] Arbitrary data the user wants to store. - * @param {object} [options.promiseLibrary=null] A Promise library class the application wishes to use such as Bluebird, must be ES6 compatible - * @param {(ReadPreference|string)} [options.readPreference=null] The preferred read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST). - * @property {number} chunkSize Get the gridstore chunk size. - * @property {number} md5 The md5 checksum for this file. - * @property {number} chunkNumber The current chunk number the gridstore has materialized into memory - * @return {GridStore} a GridStore instance. - * @deprecated Use GridFSBucket API instead - */ -var GridStore = function GridStore(db, id, filename, mode, options) { - if(!(this instanceof GridStore)) return new GridStore(db, id, filename, mode, options); - this.db = db; - - // Handle options - if(typeof options === 'undefined') options = {}; - // Handle mode - if(typeof mode === 'undefined') { - mode = filename; - filename = undefined; - } else if(typeof mode == 'object') { - options = mode; - mode = filename; - filename = undefined; - } - - if(id && id._bsontype == 'ObjectID') { - this.referenceBy = REFERENCE_BY_ID; - this.fileId = id; - this.filename = filename; - } else if(typeof filename == 'undefined') { - this.referenceBy = REFERENCE_BY_FILENAME; - this.filename = id; - if (mode.indexOf('w') != null) { - this.fileId = new ObjectID(); - } - } else { - this.referenceBy = REFERENCE_BY_ID; - this.fileId = id; - this.filename = filename; - } - - // Set up the rest - this.mode = mode == null ? "r" : mode; - this.options = options || {}; - - // Opened - this.isOpen = false; - - // Set the root if overridden - this.root = this.options['root'] == null ? GridStore.DEFAULT_ROOT_COLLECTION : this.options['root']; - this.position = 0; - this.readPreference = this.options.readPreference || db.options.readPreference || ReadPreference.PRIMARY; - this.writeConcern = _getWriteConcern(db, this.options); - // Set default chunk size - this.internalChunkSize = this.options['chunkSize'] == null ? Chunk.DEFAULT_CHUNK_SIZE : this.options['chunkSize']; - - // Get the promiseLibrary - var promiseLibrary = this.options.promiseLibrary; - - // No promise library selected fall back - if(!promiseLibrary) { - promiseLibrary = typeof global.Promise == 'function' ? - global.Promise : require('es6-promise').Promise; - } - - // Set the promiseLibrary - this.promiseLibrary = promiseLibrary; - - Object.defineProperty(this, "chunkSize", { enumerable: true - , get: function () { - return this.internalChunkSize; - } - , set: function(value) { - if(!(this.mode[0] == "w" && this.position == 0 && this.uploadDate == null)) { - this.internalChunkSize = this.internalChunkSize; - } else { - this.internalChunkSize = value; - } - } - }); - - Object.defineProperty(this, "md5", { enumerable: true - , get: function () { - return this.internalMd5; - } - }); - - Object.defineProperty(this, "chunkNumber", { enumerable: true - , get: function () { - return this.currentChunk && this.currentChunk.chunkNumber ? this.currentChunk.chunkNumber : null; - } - }); -} - -var define = GridStore.define = new Define('Gridstore', GridStore, true); - -/** - * The callback format for the Gridstore.open method - * @callback GridStore~openCallback - * @param {MongoError} error An error instance representing the error during the execution. - * @param {GridStore} gridStore The GridStore instance if the open method was successful. - */ - -/** - * Opens the file from the database and initialize this object. Also creates a - * new one if file does not exist. - * - * @method - * @param {GridStore~openCallback} [callback] this will be called after executing this method - * @return {Promise} returns Promise if no callback passed - * @deprecated Use GridFSBucket API instead - */ -GridStore.prototype.open = function(callback) { - var self = this; - if( this.mode != "w" && this.mode != "w+" && this.mode != "r"){ - throw MongoError.create({message: "Illegal mode " + this.mode, driver:true}); - } - - // We provided a callback leg - if(typeof callback == 'function') return open(self, callback); - // Return promise - return new self.promiseLibrary(function(resolve, reject) { - open(self, function(err, store) { - if(err) return reject(err); - resolve(store); - }) - }); -}; - -var open = function(self, callback) { - // Get the write concern - var writeConcern = _getWriteConcern(self.db, self.options); - - // If we are writing we need to ensure we have the right indexes for md5's - if((self.mode == "w" || self.mode == "w+")) { - // Get files collection - var collection = self.collection(); - // Put index on filename - collection.ensureIndex([['filename', 1]], writeConcern, function() { - // Get chunk collection - var chunkCollection = self.chunkCollection(); - // Make an unique index for compatibility with mongo-cxx-driver:legacy - var chunkIndexOptions = shallowClone(writeConcern); - chunkIndexOptions.unique = true; - // Ensure index on chunk collection - chunkCollection.ensureIndex([['files_id', 1], ['n', 1]], chunkIndexOptions, function() { - // Open the connection - _open(self, writeConcern, function(err, r) { - if(err) return callback(err); - self.isOpen = true; - callback(err, r); - }); - }); - }); - } else { - // Open the gridstore - _open(self, writeConcern, function(err, r) { - if(err) return callback(err); - self.isOpen = true; - callback(err, r); - }); - } -} - -// Push the definition for open -define.classMethod('open', {callback: true, promise:true}); - -/** - * Verify if the file is at EOF. - * - * @method - * @return {boolean} true if the read/write head is at the end of this file. - * @deprecated Use GridFSBucket API instead - */ -GridStore.prototype.eof = function() { - return this.position == this.length ? true : false; -} - -define.classMethod('eof', {callback: false, promise:false, returns: [Boolean]}); - -/** - * The callback result format. - * @callback GridStore~resultCallback - * @param {MongoError} error An error instance representing the error during the execution. - * @param {object} result The result from the callback. - */ - -/** - * Retrieves a single character from this file. - * - * @method - * @param {GridStore~resultCallback} [callback] this gets called after this method is executed. Passes null to the first parameter and the character read to the second or null to the second if the read/write head is at the end of the file. - * @return {Promise} returns Promise if no callback passed - * @deprecated Use GridFSBucket API instead - */ -GridStore.prototype.getc = function(callback) { - var self = this; - // We provided a callback leg - if(typeof callback == 'function') return eof(self, callback); - // Return promise - return new self.promiseLibrary(function(resolve, reject) { - eof(self, function(err, r) { - if(err) return reject(err); - resolve(r); - }) - }); -} - -var eof = function(self, callback) { - if(self.eof()) { - callback(null, null); - } else if(self.currentChunk.eof()) { - nthChunk(self, self.currentChunk.chunkNumber + 1, function(err, chunk) { - self.currentChunk = chunk; - self.position = self.position + 1; - callback(err, self.currentChunk.getc()); - }); - } else { - self.position = self.position + 1; - callback(null, self.currentChunk.getc()); - } -} - -define.classMethod('getc', {callback: true, promise:true}); - -/** - * Writes a string to the file with a newline character appended at the end if - * the given string does not have one. - * - * @method - * @param {string} string the string to write. - * @param {GridStore~resultCallback} [callback] this will be called after executing this method. The first parameter will contain null and the second one will contain a reference to this object. - * @return {Promise} returns Promise if no callback passed - * @deprecated Use GridFSBucket API instead - */ -GridStore.prototype.puts = function(string, callback) { - var self = this; - var finalString = string.match(/\n$/) == null ? string + "\n" : string; - // We provided a callback leg - if(typeof callback == 'function') return this.write(finalString, callback); - // Return promise - return new self.promiseLibrary(function(resolve, reject) { - self.write(finalString, function(err, r) { - if(err) return reject(err); - resolve(r); - }) - }); -} - -define.classMethod('puts', {callback: true, promise:true}); - -/** - * Return a modified Readable stream including a possible transform method. - * - * @method - * @return {GridStoreStream} - * @deprecated Use GridFSBucket API instead - */ -GridStore.prototype.stream = function() { - return new GridStoreStream(this); -} - -define.classMethod('stream', {callback: false, promise:false, returns: [GridStoreStream]}); - -/** - * Writes some data. This method will work properly only if initialized with mode "w" or "w+". - * - * @method - * @param {(string|Buffer)} data the data to write. - * @param {boolean} [close] closes this file after writing if set to true. - * @param {GridStore~resultCallback} [callback] this will be called after executing this method. The first parameter will contain null and the second one will contain a reference to this object. - * @return {Promise} returns Promise if no callback passed - * @deprecated Use GridFSBucket API instead - */ -GridStore.prototype.write = function write(data, close, callback) { - var self = this; - // We provided a callback leg - if(typeof callback == 'function') return _writeNormal(this, data, close, callback); - // Return promise - return new self.promiseLibrary(function(resolve, reject) { - _writeNormal(self, data, close, function(err, r) { - if(err) return reject(err); - resolve(r); - }) - }); -} - -define.classMethod('write', {callback: true, promise:true}); - -/** - * Handles the destroy part of a stream - * - * @method - * @result {null} - * @deprecated Use GridFSBucket API instead - */ -GridStore.prototype.destroy = function destroy() { - // close and do not emit any more events. queued data is not sent. - if(!this.writable) return; - this.readable = false; - if(this.writable) { - this.writable = false; - this._q.length = 0; - this.emit('close'); - } -} - -define.classMethod('destroy', {callback: false, promise:false}); - -/** - * Stores a file from the file system to the GridFS database. - * - * @method - * @param {(string|Buffer|FileHandle)} file the file to store. - * @param {GridStore~resultCallback} [callback] this will be called after executing this method. The first parameter will contain null and the second one will contain a reference to this object. - * @return {Promise} returns Promise if no callback passed - * @deprecated Use GridFSBucket API instead - */ -GridStore.prototype.writeFile = function (file, callback) { - var self = this; - // We provided a callback leg - if(typeof callback == 'function') return writeFile(self, file, callback); - // Return promise - return new self.promiseLibrary(function(resolve, reject) { - writeFile(self, file, function(err, r) { - if(err) return reject(err); - resolve(r); - }) - }); -}; - -var writeFile = function(self, file, callback) { - if (typeof file === 'string') { - fs.open(file, 'r', function (err, fd) { - if(err) return callback(err); - self.writeFile(fd, callback); - }); - return; - } - - self.open(function (err, self) { - if(err) return callback(err, self); - - fs.fstat(file, function (err, stats) { - if(err) return callback(err, self); - - var offset = 0; - var index = 0; - - // Write a chunk - var writeChunk = function() { - // Allocate the buffer - var _buffer = new Buffer(self.chunkSize); - // Read the file - fs.read(file, _buffer, 0, _buffer.length, offset, function(err, bytesRead, data) { - if(err) return callback(err, self); - - offset = offset + bytesRead; - - // Create a new chunk for the data - var chunk = new Chunk(self, {n:index++}, self.writeConcern); - chunk.write(data.slice(0, bytesRead), function(err, chunk) { - if(err) return callback(err, self); - - chunk.save({}, function(err) { - if(err) return callback(err, self); - - self.position = self.position + bytesRead; - - // Point to current chunk - self.currentChunk = chunk; - - if(offset >= stats.size) { - fs.close(file); - self.close(function(err) { - if(err) return callback(err, self); - return callback(null, self); - }); - } else { - return process.nextTick(writeChunk); - } - }); - }); - }); - } - - // Process the first write - process.nextTick(writeChunk); - }); - }); -} - -define.classMethod('writeFile', {callback: true, promise:true}); - -/** - * Saves this file to the database. This will overwrite the old entry if it - * already exists. This will work properly only if mode was initialized to - * "w" or "w+". - * - * @method - * @param {GridStore~resultCallback} [callback] this will be called after executing this method. The first parameter will contain null and the second one will contain a reference to this object. - * @return {Promise} returns Promise if no callback passed - * @deprecated Use GridFSBucket API instead - */ -GridStore.prototype.close = function(callback) { - var self = this; - // We provided a callback leg - if(typeof callback == 'function') return close(self, callback); - // Return promise - return new self.promiseLibrary(function(resolve, reject) { - close(self, function(err, r) { - if(err) return reject(err); - resolve(r); - }) - }); -}; - -var close = function(self, callback) { - if(self.mode[0] == "w") { - // Set up options - var options = self.writeConcern; - - if(self.currentChunk != null && self.currentChunk.position > 0) { - self.currentChunk.save({}, function(err) { - if(err && typeof callback == 'function') return callback(err); - - self.collection(function(err, files) { - if(err && typeof callback == 'function') return callback(err); - - // Build the mongo object - if(self.uploadDate != null) { - buildMongoObject(self, function(err, mongoObject) { - if(err) { - if(typeof callback == 'function') return callback(err); else throw err; - } - - files.save(mongoObject, options, function(err) { - if(typeof callback == 'function') - callback(err, mongoObject); - }); - }); - } else { - self.uploadDate = new Date(); - buildMongoObject(self, function(err, mongoObject) { - if(err) { - if(typeof callback == 'function') return callback(err); else throw err; - } - - files.save(mongoObject, options, function(err) { - if(typeof callback == 'function') - callback(err, mongoObject); - }); - }); - } - }); - }); - } else { - self.collection(function(err, files) { - if(err && typeof callback == 'function') return callback(err); - - self.uploadDate = new Date(); - buildMongoObject(self, function(err, mongoObject) { - if(err) { - if(typeof callback == 'function') return callback(err); else throw err; - } - - files.save(mongoObject, options, function(err) { - if(typeof callback == 'function') - callback(err, mongoObject); - }); - }); - }); - } - } else if(self.mode[0] == "r") { - if(typeof callback == 'function') - callback(null, null); - } else { - if(typeof callback == 'function') - callback(MongoError.create({message: f("Illegal mode %s", self.mode), driver:true})); - } -} - -define.classMethod('close', {callback: true, promise:true}); - -/** - * The collection callback format. - * @callback GridStore~collectionCallback - * @param {MongoError} error An error instance representing the error during the execution. - * @param {Collection} collection The collection from the command execution. - */ - -/** - * Retrieve this file's chunks collection. - * - * @method - * @param {GridStore~collectionCallback} callback the command callback. - * @return {Collection} - * @deprecated Use GridFSBucket API instead - */ -GridStore.prototype.chunkCollection = function(callback) { - if(typeof callback == 'function') - return this.db.collection((this.root + ".chunks"), callback); - return this.db.collection((this.root + ".chunks")); -}; - -define.classMethod('chunkCollection', {callback: true, promise:false, returns: [Collection]}); - -/** - * Deletes all the chunks of this file in the database. - * - * @method - * @param {GridStore~resultCallback} [callback] the command callback. - * @return {Promise} returns Promise if no callback passed - * @deprecated Use GridFSBucket API instead - */ -GridStore.prototype.unlink = function(callback) { - var self = this; - // We provided a callback leg - if(typeof callback == 'function') return unlink(self, callback); - // Return promise - return new self.promiseLibrary(function(resolve, reject) { - unlink(self, function(err, r) { - if(err) return reject(err); - resolve(r); - }) - }); -}; - -var unlink = function(self, callback) { - deleteChunks(self, function(err) { - if(err!==null) { - err.message = "at deleteChunks: " + err.message; - return callback(err); - } - - self.collection(function(err, collection) { - if(err!==null) { - err.message = "at collection: " + err.message; - return callback(err); - } - - collection.remove({'_id':self.fileId}, self.writeConcern, function(err) { - callback(err, self); - }); - }); - }); -} - -define.classMethod('unlink', {callback: true, promise:true}); - -/** - * Retrieves the file collection associated with this object. - * - * @method - * @param {GridStore~collectionCallback} callback the command callback. - * @return {Collection} - * @deprecated Use GridFSBucket API instead - */ -GridStore.prototype.collection = function(callback) { - if(typeof callback == 'function') - this.db.collection(this.root + ".files", callback); - return this.db.collection(this.root + ".files"); -}; - -define.classMethod('collection', {callback: true, promise:false, returns: [Collection]}); - -/** - * The readlines callback format. - * @callback GridStore~readlinesCallback - * @param {MongoError} error An error instance representing the error during the execution. - * @param {string[]} strings The array of strings returned. - */ - -/** - * Read the entire file as a list of strings splitting by the provided separator. - * - * @method - * @param {string} [separator] The character to be recognized as the newline separator. - * @param {GridStore~readlinesCallback} [callback] the command callback. - * @return {Promise} returns Promise if no callback passed - * @deprecated Use GridFSBucket API instead - */ -GridStore.prototype.readlines = function(separator, callback) { - var self = this; - var args = Array.prototype.slice.call(arguments, 0); - callback = args.pop(); - if(typeof callback != 'function') args.push(callback); - separator = args.length ? args.shift() : "\n"; - separator = separator || "\n"; - - // We provided a callback leg - if(typeof callback == 'function') return readlines(self, separator, callback); - - // Return promise - return new self.promiseLibrary(function(resolve, reject) { - readlines(self, separator, function(err, r) { - if(err) return reject(err); - resolve(r); - }) - }); -}; - -var readlines = function(self, separator, callback) { - self.read(function(err, data) { - if(err) return callback(err); - - var items = data.toString().split(separator); - items = items.length > 0 ? items.splice(0, items.length - 1) : []; - for(var i = 0; i < items.length; i++) { - items[i] = items[i] + separator; - } - - callback(null, items); - }); -} - -define.classMethod('readlines', {callback: true, promise:true}); - -/** - * Deletes all the chunks of this file in the database if mode was set to "w" or - * "w+" and resets the read/write head to the initial position. - * - * @method - * @param {GridStore~resultCallback} [callback] this will be called after executing this method. The first parameter will contain null and the second one will contain a reference to this object. - * @return {Promise} returns Promise if no callback passed - * @deprecated Use GridFSBucket API instead - */ -GridStore.prototype.rewind = function(callback) { - var self = this; - // We provided a callback leg - if(typeof callback == 'function') return rewind(self, callback); - // Return promise - return new self.promiseLibrary(function(resolve, reject) { - rewind(self, function(err, r) { - if(err) return reject(err); - resolve(r); - }) - }); -}; - -var rewind = function(self, callback) { - if(self.currentChunk.chunkNumber != 0) { - if(self.mode[0] == "w") { - deleteChunks(self, function(err) { - if(err) return callback(err); - self.currentChunk = new Chunk(self, {'n': 0}, self.writeConcern); - self.position = 0; - callback(null, self); - }); - } else { - self.currentChunk(0, function(err, chunk) { - if(err) return callback(err); - self.currentChunk = chunk; - self.currentChunk.rewind(); - self.position = 0; - callback(null, self); - }); - } - } else { - self.currentChunk.rewind(); - self.position = 0; - callback(null, self); - } -} - -define.classMethod('rewind', {callback: true, promise:true}); - -/** - * The read callback format. - * @callback GridStore~readCallback - * @param {MongoError} error An error instance representing the error during the execution. - * @param {Buffer} data The data read from the GridStore object - */ - -/** - * Retrieves the contents of this file and advances the read/write head. Works with Buffers only. - * - * There are 3 signatures for this method: - * - * (callback) - * (length, callback) - * (length, buffer, callback) - * - * @method - * @param {number} [length] the number of characters to read. Reads all the characters from the read/write head to the EOF if not specified. - * @param {(string|Buffer)} [buffer] a string to hold temporary data. This is used for storing the string data read so far when recursively calling this method. - * @param {GridStore~readCallback} [callback] the command callback. - * @return {Promise} returns Promise if no callback passed - * @deprecated Use GridFSBucket API instead - */ -GridStore.prototype.read = function(length, buffer, callback) { - var self = this; - - var args = Array.prototype.slice.call(arguments, 0); - callback = args.pop(); - if(typeof callback != 'function') args.push(callback); - length = args.length ? args.shift() : null; - buffer = args.length ? args.shift() : null; - // We provided a callback leg - if(typeof callback == 'function') return read(self, length, buffer, callback); - // Return promise - return new self.promiseLibrary(function(resolve, reject) { - read(self, length, buffer, function(err, r) { - if(err) return reject(err); - resolve(r); - }) - }); -} - -var read = function(self, length, buffer, callback) { - // The data is a c-terminated string and thus the length - 1 - var finalLength = length == null ? self.length - self.position : length; - var finalBuffer = buffer == null ? new Buffer(finalLength) : buffer; - // Add a index to buffer to keep track of writing position or apply current index - finalBuffer._index = buffer != null && buffer._index != null ? buffer._index : 0; - - if((self.currentChunk.length() - self.currentChunk.position + finalBuffer._index) >= finalLength) { - var slice = self.currentChunk.readSlice(finalLength - finalBuffer._index); - // Copy content to final buffer - slice.copy(finalBuffer, finalBuffer._index); - // Update internal position - self.position = self.position + finalBuffer.length; - // Check if we don't have a file at all - if(finalLength == 0 && finalBuffer.length == 0) return callback(MongoError.create({message: "File does not exist", driver:true}), null); - // Else return data - return callback(null, finalBuffer); - } - - // Read the next chunk - slice = self.currentChunk.readSlice(self.currentChunk.length() - self.currentChunk.position); - // Copy content to final buffer - slice.copy(finalBuffer, finalBuffer._index); - // Update index position - finalBuffer._index += slice.length; - - // Load next chunk and read more - nthChunk(self, self.currentChunk.chunkNumber + 1, function(err, chunk) { - if(err) return callback(err); - - if(chunk.length() > 0) { - self.currentChunk = chunk; - self.read(length, finalBuffer, callback); - } else { - if(finalBuffer._index > 0) { - callback(null, finalBuffer) - } else { - callback(MongoError.create({message: "no chunks found for file, possibly corrupt", driver:true}), null); - } - } - }); -} - -define.classMethod('read', {callback: true, promise:true}); - -/** - * The tell callback format. - * @callback GridStore~tellCallback - * @param {MongoError} error An error instance representing the error during the execution. - * @param {number} position The current read position in the GridStore. - */ - -/** - * Retrieves the position of the read/write head of this file. - * - * @method - * @param {number} [length] the number of characters to read. Reads all the characters from the read/write head to the EOF if not specified. - * @param {(string|Buffer)} [buffer] a string to hold temporary data. This is used for storing the string data read so far when recursively calling this method. - * @param {GridStore~tellCallback} [callback] the command callback. - * @return {Promise} returns Promise if no callback passed - * @deprecated Use GridFSBucket API instead - */ -GridStore.prototype.tell = function(callback) { - var self = this; - // We provided a callback leg - if(typeof callback == 'function') return callback(null, this.position); - // Return promise - return new self.promiseLibrary(function(resolve) { - resolve(self.position); - }); -}; - -define.classMethod('tell', {callback: true, promise:true}); - -/** - * The tell callback format. - * @callback GridStore~gridStoreCallback - * @param {MongoError} error An error instance representing the error during the execution. - * @param {GridStore} gridStore The gridStore. - */ - -/** - * Moves the read/write head to a new location. - * - * There are 3 signatures for this method - * - * Seek Location Modes - * - **GridStore.IO_SEEK_SET**, **(default)** set the position from the start of the file. - * - **GridStore.IO_SEEK_CUR**, set the position from the current position in the file. - * - **GridStore.IO_SEEK_END**, set the position from the end of the file. - * - * @method - * @param {number} [position] the position to seek to - * @param {number} [seekLocation] seek mode. Use one of the Seek Location modes. - * @param {GridStore~gridStoreCallback} [callback] the command callback. - * @return {Promise} returns Promise if no callback passed - * @deprecated Use GridFSBucket API instead - */ -GridStore.prototype.seek = function(position, seekLocation, callback) { - var self = this; - - var args = Array.prototype.slice.call(arguments, 1); - callback = args.pop(); - if(typeof callback != 'function') args.push(callback); - seekLocation = args.length ? args.shift() : null; - - // We provided a callback leg - if(typeof callback == 'function') return seek(self, position, seekLocation, callback); - // Return promise - return new self.promiseLibrary(function(resolve, reject) { - seek(self, position, seekLocation, function(err, r) { - if(err) return reject(err); - resolve(r); - }) - }); -} - -var seek = function(self, position, seekLocation, callback) { - // Seek only supports read mode - if(self.mode != 'r') { - return callback(MongoError.create({message: "seek is only supported for mode r", driver:true})) - } - - var seekLocationFinal = seekLocation == null ? GridStore.IO_SEEK_SET : seekLocation; - var finalPosition = position; - var targetPosition = 0; - - // Calculate the position - if(seekLocationFinal == GridStore.IO_SEEK_CUR) { - targetPosition = self.position + finalPosition; - } else if(seekLocationFinal == GridStore.IO_SEEK_END) { - targetPosition = self.length + finalPosition; - } else { - targetPosition = finalPosition; - } - - // Get the chunk - var newChunkNumber = Math.floor(targetPosition/self.chunkSize); - var seekChunk = function() { - nthChunk(self, newChunkNumber, function(err, chunk) { - if(err) return callback(err, null); - if(chunk == null) return callback(new Error('no chunk found')); - - // Set the current chunk - self.currentChunk = chunk; - self.position = targetPosition; - self.currentChunk.position = (self.position % self.chunkSize); - callback(err, self); - }); - }; - - seekChunk(); -} - -define.classMethod('seek', {callback: true, promise:true}); - -/** - * @ignore - */ -var _open = function(self, options, callback) { - var collection = self.collection(); - // Create the query - var query = self.referenceBy == REFERENCE_BY_ID ? {_id:self.fileId} : {filename:self.filename}; - query = null == self.fileId && self.filename == null ? null : query; - options.readPreference = self.readPreference; - - // Fetch the chunks - if(query != null) { - collection.findOne(query, options, function(err, doc) { - if(err) return error(err); - - // Check if the collection for the files exists otherwise prepare the new one - if(doc != null) { - self.fileId = doc._id; - // Prefer a new filename over the existing one if this is a write - self.filename = ((self.mode == 'r') || (self.filename == undefined)) ? doc.filename : self.filename; - self.contentType = doc.contentType; - self.internalChunkSize = doc.chunkSize; - self.uploadDate = doc.uploadDate; - self.aliases = doc.aliases; - self.length = doc.length; - self.metadata = doc.metadata; - self.internalMd5 = doc.md5; - } else if (self.mode != 'r') { - self.fileId = self.fileId == null ? new ObjectID() : self.fileId; - self.contentType = GridStore.DEFAULT_CONTENT_TYPE; - self.internalChunkSize = self.internalChunkSize == null ? Chunk.DEFAULT_CHUNK_SIZE : self.internalChunkSize; - self.length = 0; - } else { - self.length = 0; - var txtId = self.fileId._bsontype == "ObjectID" ? self.fileId.toHexString() : self.fileId; - return error(MongoError.create({message: f("file with id %s not opened for writing", (self.referenceBy == REFERENCE_BY_ID ? txtId : self.filename)), driver:true}), self); - } - - // Process the mode of the object - if(self.mode == "r") { - nthChunk(self, 0, options, function(err, chunk) { - if(err) return error(err); - self.currentChunk = chunk; - self.position = 0; - callback(null, self); - }); - } else if(self.mode == "w" && doc) { - // Delete any existing chunks - deleteChunks(self, options, function(err) { - if(err) return error(err); - self.currentChunk = new Chunk(self, {'n':0}, self.writeConcern); - self.contentType = self.options['content_type'] == null ? self.contentType : self.options['content_type']; - self.internalChunkSize = self.options['chunk_size'] == null ? self.internalChunkSize : self.options['chunk_size']; - self.metadata = self.options['metadata'] == null ? self.metadata : self.options['metadata']; - self.aliases = self.options['aliases'] == null ? self.aliases : self.options['aliases']; - self.position = 0; - callback(null, self); - }); - } else if(self.mode == "w") { - self.currentChunk = new Chunk(self, {'n':0}, self.writeConcern); - self.contentType = self.options['content_type'] == null ? self.contentType : self.options['content_type']; - self.internalChunkSize = self.options['chunk_size'] == null ? self.internalChunkSize : self.options['chunk_size']; - self.metadata = self.options['metadata'] == null ? self.metadata : self.options['metadata']; - self.aliases = self.options['aliases'] == null ? self.aliases : self.options['aliases']; - self.position = 0; - callback(null, self); - } else if(self.mode == "w+") { - nthChunk(self, lastChunkNumber(self), options, function(err, chunk) { - if(err) return error(err); - // Set the current chunk - self.currentChunk = chunk == null ? new Chunk(self, {'n':0}, self.writeConcern) : chunk; - self.currentChunk.position = self.currentChunk.data.length(); - self.metadata = self.options['metadata'] == null ? self.metadata : self.options['metadata']; - self.aliases = self.options['aliases'] == null ? self.aliases : self.options['aliases']; - self.position = self.length; - callback(null, self); - }); - } - }); - } else { - // Write only mode - self.fileId = null == self.fileId ? new ObjectID() : self.fileId; - self.contentType = GridStore.DEFAULT_CONTENT_TYPE; - self.internalChunkSize = self.internalChunkSize == null ? Chunk.DEFAULT_CHUNK_SIZE : self.internalChunkSize; - self.length = 0; - - // No file exists set up write mode - if(self.mode == "w") { - // Delete any existing chunks - deleteChunks(self, options, function(err) { - if(err) return error(err); - self.currentChunk = new Chunk(self, {'n':0}, self.writeConcern); - self.contentType = self.options['content_type'] == null ? self.contentType : self.options['content_type']; - self.internalChunkSize = self.options['chunk_size'] == null ? self.internalChunkSize : self.options['chunk_size']; - self.metadata = self.options['metadata'] == null ? self.metadata : self.options['metadata']; - self.aliases = self.options['aliases'] == null ? self.aliases : self.options['aliases']; - self.position = 0; - callback(null, self); - }); - } else if(self.mode == "w+") { - nthChunk(self, lastChunkNumber(self), options, function(err, chunk) { - if(err) return error(err); - // Set the current chunk - self.currentChunk = chunk == null ? new Chunk(self, {'n':0}, self.writeConcern) : chunk; - self.currentChunk.position = self.currentChunk.data.length(); - self.metadata = self.options['metadata'] == null ? self.metadata : self.options['metadata']; - self.aliases = self.options['aliases'] == null ? self.aliases : self.options['aliases']; - self.position = self.length; - callback(null, self); - }); - } - } - - // only pass error to callback once - function error (err) { - if(error.err) return; - callback(error.err = err); - } -}; - -/** - * @ignore - */ -var writeBuffer = function(self, buffer, close, callback) { - if(typeof close === "function") { callback = close; close = null; } - var finalClose = typeof close == 'boolean' ? close : false; - - if(self.mode != "w") { - callback(MongoError.create({message: f("file with id %s not opened for writing", (self.referenceBy == REFERENCE_BY_ID ? self.referenceBy : self.filename)), driver:true}), null); - } else { - if(self.currentChunk.position + buffer.length >= self.chunkSize) { - // Write out the current Chunk and then keep writing until we have less data left than a chunkSize left - // to a new chunk (recursively) - var previousChunkNumber = self.currentChunk.chunkNumber; - var leftOverDataSize = self.chunkSize - self.currentChunk.position; - var firstChunkData = buffer.slice(0, leftOverDataSize); - var leftOverData = buffer.slice(leftOverDataSize); - // A list of chunks to write out - var chunksToWrite = [self.currentChunk.write(firstChunkData)]; - // If we have more data left than the chunk size let's keep writing new chunks - while(leftOverData.length >= self.chunkSize) { - // Create a new chunk and write to it - var newChunk = new Chunk(self, {'n': (previousChunkNumber + 1)}, self.writeConcern); - firstChunkData = leftOverData.slice(0, self.chunkSize); - leftOverData = leftOverData.slice(self.chunkSize); - // Update chunk number - previousChunkNumber = previousChunkNumber + 1; - // Write data - newChunk.write(firstChunkData); - // Push chunk to save list - chunksToWrite.push(newChunk); - } - - // Set current chunk with remaining data - self.currentChunk = new Chunk(self, {'n': (previousChunkNumber + 1)}, self.writeConcern); - // If we have left over data write it - if(leftOverData.length > 0) self.currentChunk.write(leftOverData); - - // Update the position for the gridstore - self.position = self.position + buffer.length; - // Total number of chunks to write - var numberOfChunksToWrite = chunksToWrite.length; - - for(var i = 0; i < chunksToWrite.length; i++) { - chunksToWrite[i].save({}, function(err) { - if(err) return callback(err); - - numberOfChunksToWrite = numberOfChunksToWrite - 1; - - if(numberOfChunksToWrite <= 0) { - // We care closing the file before returning - if(finalClose) { - return self.close(function(err) { - callback(err, self); - }); - } - - // Return normally - return callback(null, self); - } - }); - } - } else { - // Update the position for the gridstore - self.position = self.position + buffer.length; - // We have less data than the chunk size just write it and callback - self.currentChunk.write(buffer); - // We care closing the file before returning - if(finalClose) { - return self.close(function(err) { - callback(err, self); - }); - } - // Return normally - return callback(null, self); - } - } -}; - -/** - * Creates a mongoDB object representation of this object. - * - *

- *        {
- *          '_id' : , // {number} id for this file
- *          'filename' : , // {string} name for this file
- *          'contentType' : , // {string} mime type for this file
- *          'length' : , // {number} size of this file?
- *          'chunksize' : , // {number} chunk size used by this file
- *          'uploadDate' : , // {Date}
- *          'aliases' : , // {array of string}
- *          'metadata' : , // {string}
- *        }
- *        
- * - * @ignore - */ -var buildMongoObject = function(self, callback) { - // Calcuate the length - var mongoObject = { - '_id': self.fileId, - 'filename': self.filename, - 'contentType': self.contentType, - 'length': self.position ? self.position : 0, - 'chunkSize': self.chunkSize, - 'uploadDate': self.uploadDate, - 'aliases': self.aliases, - 'metadata': self.metadata - }; - - var md5Command = {filemd5:self.fileId, root:self.root}; - self.db.command(md5Command, function(err, results) { - if(err) return callback(err); - - mongoObject.md5 = results.md5; - callback(null, mongoObject); - }); -}; - -/** - * Gets the nth chunk of this file. - * @ignore - */ -var nthChunk = function(self, chunkNumber, options, callback) { - if(typeof options == 'function') { - callback = options; - options = {}; - } - - options = options || self.writeConcern; - options.readPreference = self.readPreference; - // Get the nth chunk - self.chunkCollection().findOne({'files_id':self.fileId, 'n':chunkNumber}, options, function(err, chunk) { - if(err) return callback(err); - - var finalChunk = chunk == null ? {} : chunk; - callback(null, new Chunk(self, finalChunk, self.writeConcern)); - }); -}; - -/** - * @ignore - */ -var lastChunkNumber = function(self) { - return Math.floor((self.length ? self.length - 1 : 0)/self.chunkSize); -}; - -/** - * Deletes all the chunks of this file in the database. - * - * @ignore - */ -var deleteChunks = function(self, options, callback) { - if(typeof options == 'function') { - callback = options; - options = {}; - } - - options = options || self.writeConcern; - - if(self.fileId != null) { - self.chunkCollection().remove({'files_id':self.fileId}, options, function(err) { - if(err) return callback(err, false); - callback(null, true); - }); - } else { - callback(null, true); - } -}; - -/** -* The collection to be used for holding the files and chunks collection. -* -* @classconstant DEFAULT_ROOT_COLLECTION -**/ -GridStore.DEFAULT_ROOT_COLLECTION = 'fs'; - -/** -* Default file mime type -* -* @classconstant DEFAULT_CONTENT_TYPE -**/ -GridStore.DEFAULT_CONTENT_TYPE = 'binary/octet-stream'; - -/** -* Seek mode where the given length is absolute. -* -* @classconstant IO_SEEK_SET -**/ -GridStore.IO_SEEK_SET = 0; - -/** -* Seek mode where the given length is an offset to the current read/write head. -* -* @classconstant IO_SEEK_CUR -**/ -GridStore.IO_SEEK_CUR = 1; - -/** -* Seek mode where the given length is an offset to the end of the file. -* -* @classconstant IO_SEEK_END -**/ -GridStore.IO_SEEK_END = 2; - -/** - * Checks if a file exists in the database. - * - * @method - * @static - * @param {Db} db the database to query. - * @param {string} name The name of the file to look for. - * @param {string} [rootCollection] The root collection that holds the files and chunks collection. Defaults to **{GridStore.DEFAULT_ROOT_COLLECTION}**. - * @param {object} [options=null] Optional settings. - * @param {(ReadPreference|string)} [options.readPreference=null] The preferred read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST). - * @param {object} [options.promiseLibrary=null] A Promise library class the application wishes to use such as Bluebird, must be ES6 compatible - * @param {GridStore~resultCallback} [callback] result from exists. - * @return {Promise} returns Promise if no callback passed - * @deprecated Use GridFSBucket API instead - */ -GridStore.exist = function(db, fileIdObject, rootCollection, options, callback) { - var args = Array.prototype.slice.call(arguments, 2); - callback = args.pop(); - if(typeof callback != 'function') args.push(callback); - rootCollection = args.length ? args.shift() : null; - options = args.length ? args.shift() : {}; - options = options || {}; - - // Get the promiseLibrary - var promiseLibrary = options.promiseLibrary; - - // No promise library selected fall back - if(!promiseLibrary) { - promiseLibrary = typeof global.Promise == 'function' ? - global.Promise : require('es6-promise').Promise; - } - - // We provided a callback leg - if(typeof callback == 'function') return exists(db, fileIdObject, rootCollection, options, callback); - // Return promise - return new promiseLibrary(function(resolve, reject) { - exists(db, fileIdObject, rootCollection, options, function(err, r) { - if(err) return reject(err); - resolve(r); - }) - }); -}; - -var exists = function(db, fileIdObject, rootCollection, options, callback) { - // Establish read preference - var readPreference = options.readPreference || ReadPreference.PRIMARY; - // Fetch collection - var rootCollectionFinal = rootCollection != null ? rootCollection : GridStore.DEFAULT_ROOT_COLLECTION; - db.collection(rootCollectionFinal + ".files", function(err, collection) { - if(err) return callback(err); - - // Build query - var query = (typeof fileIdObject == 'string' || Object.prototype.toString.call(fileIdObject) == '[object RegExp]' ) - ? {'filename':fileIdObject} - : {'_id':fileIdObject}; // Attempt to locate file - - // We have a specific query - if(fileIdObject != null - && typeof fileIdObject == 'object' - && Object.prototype.toString.call(fileIdObject) != '[object RegExp]') { - query = fileIdObject; - } - - // Check if the entry exists - collection.findOne(query, {readPreference:readPreference}, function(err, item) { - if(err) return callback(err); - callback(null, item == null ? false : true); - }); - }); -} - -define.staticMethod('exist', {callback: true, promise:true}); - -/** - * Gets the list of files stored in the GridFS. - * - * @method - * @static - * @param {Db} db the database to query. - * @param {string} [rootCollection] The root collection that holds the files and chunks collection. Defaults to **{GridStore.DEFAULT_ROOT_COLLECTION}**. - * @param {object} [options=null] Optional settings. - * @param {(ReadPreference|string)} [options.readPreference=null] The preferred read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST). - * @param {object} [options.promiseLibrary=null] A Promise library class the application wishes to use such as Bluebird, must be ES6 compatible - * @param {GridStore~resultCallback} [callback] result from exists. - * @return {Promise} returns Promise if no callback passed - * @deprecated Use GridFSBucket API instead - */ -GridStore.list = function(db, rootCollection, options, callback) { - var args = Array.prototype.slice.call(arguments, 1); - callback = args.pop(); - if(typeof callback != 'function') args.push(callback); - rootCollection = args.length ? args.shift() : null; - options = args.length ? args.shift() : {}; - options = options || {}; - - // Get the promiseLibrary - var promiseLibrary = options.promiseLibrary; - - // No promise library selected fall back - if(!promiseLibrary) { - promiseLibrary = typeof global.Promise == 'function' ? - global.Promise : require('es6-promise').Promise; - } - - // We provided a callback leg - if(typeof callback == 'function') return list(db, rootCollection, options, callback); - // Return promise - return new promiseLibrary(function(resolve, reject) { - list(db, rootCollection, options, function(err, r) { - if(err) return reject(err); - resolve(r); - }) - }); -}; - -var list = function(db, rootCollection, options, callback) { - // Ensure we have correct values - if(rootCollection != null && typeof rootCollection == 'object') { - options = rootCollection; - rootCollection = null; - } - - // Establish read preference - var readPreference = options.readPreference || ReadPreference.PRIMARY; - // Check if we are returning by id not filename - var byId = options['id'] != null ? options['id'] : false; - // Fetch item - var rootCollectionFinal = rootCollection != null ? rootCollection : GridStore.DEFAULT_ROOT_COLLECTION; - var items = []; - db.collection((rootCollectionFinal + ".files"), function(err, collection) { - if(err) return callback(err); - - collection.find({}, {readPreference:readPreference}, function(err, cursor) { - if(err) return callback(err); - - cursor.each(function(err, item) { - if(item != null) { - items.push(byId ? item._id : item.filename); - } else { - callback(err, items); - } - }); - }); - }); -} - -define.staticMethod('list', {callback: true, promise:true}); - -/** - * Reads the contents of a file. - * - * This method has the following signatures - * - * (db, name, callback) - * (db, name, length, callback) - * (db, name, length, offset, callback) - * (db, name, length, offset, options, callback) - * - * @method - * @static - * @param {Db} db the database to query. - * @param {string} name The name of the file. - * @param {number} [length] The size of data to read. - * @param {number} [offset] The offset from the head of the file of which to start reading from. - * @param {object} [options=null] Optional settings. - * @param {(ReadPreference|string)} [options.readPreference=null] The preferred read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST). - * @param {object} [options.promiseLibrary=null] A Promise library class the application wishes to use such as Bluebird, must be ES6 compatible - * @param {GridStore~readCallback} [callback] the command callback. - * @return {Promise} returns Promise if no callback passed - * @deprecated Use GridFSBucket API instead - */ -GridStore.read = function(db, name, length, offset, options, callback) { - var args = Array.prototype.slice.call(arguments, 2); - callback = args.pop(); - if(typeof callback != 'function') args.push(callback); - length = args.length ? args.shift() : null; - offset = args.length ? args.shift() : null; - options = args.length ? args.shift() : null; - options = options || {}; - - // Get the promiseLibrary - var promiseLibrary = options ? options.promiseLibrary : null; - - // No promise library selected fall back - if(!promiseLibrary) { - promiseLibrary = typeof global.Promise == 'function' ? - global.Promise : require('es6-promise').Promise; - } - - // We provided a callback leg - if(typeof callback == 'function') return readStatic(db, name, length, offset, options, callback); - // Return promise - return new promiseLibrary(function(resolve, reject) { - readStatic(db, name, length, offset, options, function(err, r) { - if(err) return reject(err); - resolve(r); - }) - }); -}; - -var readStatic = function(db, name, length, offset, options, callback) { - new GridStore(db, name, "r", options).open(function(err, gridStore) { - if(err) return callback(err); - // Make sure we are not reading out of bounds - if(offset && offset >= gridStore.length) return callback("offset larger than size of file", null); - if(length && length > gridStore.length) return callback("length is larger than the size of the file", null); - if(offset && length && (offset + length) > gridStore.length) return callback("offset and length is larger than the size of the file", null); - - if(offset != null) { - gridStore.seek(offset, function(err, gridStore) { - if(err) return callback(err); - gridStore.read(length, callback); - }); - } else { - gridStore.read(length, callback); - } - }); -} - -define.staticMethod('read', {callback: true, promise:true}); - -/** - * Read the entire file as a list of strings splitting by the provided separator. - * - * @method - * @static - * @param {Db} db the database to query. - * @param {(String|object)} name the name of the file. - * @param {string} [separator] The character to be recognized as the newline separator. - * @param {object} [options=null] Optional settings. - * @param {(ReadPreference|string)} [options.readPreference=null] The preferred read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST). - * @param {object} [options.promiseLibrary=null] A Promise library class the application wishes to use such as Bluebird, must be ES6 compatible - * @param {GridStore~readlinesCallback} [callback] the command callback. - * @return {Promise} returns Promise if no callback passed - * @deprecated Use GridFSBucket API instead - */ -GridStore.readlines = function(db, name, separator, options, callback) { - var args = Array.prototype.slice.call(arguments, 2); - callback = args.pop(); - if(typeof callback != 'function') args.push(callback); - separator = args.length ? args.shift() : null; - options = args.length ? args.shift() : null; - options = options || {}; - - // Get the promiseLibrary - var promiseLibrary = options ? options.promiseLibrary : null; - - // No promise library selected fall back - if(!promiseLibrary) { - promiseLibrary = typeof global.Promise == 'function' ? - global.Promise : require('es6-promise').Promise; - } - - // We provided a callback leg - if(typeof callback == 'function') return readlinesStatic(db, name, separator, options, callback); - // Return promise - return new promiseLibrary(function(resolve, reject) { - readlinesStatic(db, name, separator, options, function(err, r) { - if(err) return reject(err); - resolve(r); - }) - }); -}; - -var readlinesStatic = function(db, name, separator, options, callback) { - var finalSeperator = separator == null ? "\n" : separator; - new GridStore(db, name, "r", options).open(function(err, gridStore) { - if(err) return callback(err); - gridStore.readlines(finalSeperator, callback); - }); -} - -define.staticMethod('readlines', {callback: true, promise:true}); - -/** - * Deletes the chunks and metadata information of a file from GridFS. - * - * @method - * @static - * @param {Db} db The database to query. - * @param {(string|array)} names The name/names of the files to delete. - * @param {object} [options=null] Optional settings. - * @param {object} [options.promiseLibrary=null] A Promise library class the application wishes to use such as Bluebird, must be ES6 compatible - * @param {GridStore~resultCallback} [callback] the command callback. - * @return {Promise} returns Promise if no callback passed - * @deprecated Use GridFSBucket API instead - */ -GridStore.unlink = function(db, names, options, callback) { - var self = this; - var args = Array.prototype.slice.call(arguments, 2); - callback = args.pop(); - if(typeof callback != 'function') args.push(callback); - options = args.length ? args.shift() : {}; - options = options || {}; - - // Get the promiseLibrary - var promiseLibrary = options.promiseLibrary; - - // No promise library selected fall back - if(!promiseLibrary) { - promiseLibrary = typeof global.Promise == 'function' ? - global.Promise : require('es6-promise').Promise; - } - - // We provided a callback leg - if(typeof callback == 'function') return unlinkStatic(self, db, names, options, callback); - - // Return promise - return new promiseLibrary(function(resolve, reject) { - unlinkStatic(self, db, names, options, function(err, r) { - if(err) return reject(err); - resolve(r); - }) - }); -}; - -var unlinkStatic = function(self, db, names, options, callback) { - // Get the write concern - var writeConcern = _getWriteConcern(db, options); - - // List of names - if(names.constructor == Array) { - var tc = 0; - for(var i = 0; i < names.length; i++) { - ++tc; - GridStore.unlink(db, names[i], options, function() { - if(--tc == 0) { - callback(null, self); - } - }); - } - } else { - new GridStore(db, names, "w", options).open(function(err, gridStore) { - if(err) return callback(err); - deleteChunks(gridStore, function(err) { - if(err) return callback(err); - gridStore.collection(function(err, collection) { - if(err) return callback(err); - collection.remove({'_id':gridStore.fileId}, writeConcern, function(err) { - callback(err, self); - }); - }); - }); - }); - } -} - -define.staticMethod('unlink', {callback: true, promise:true}); - -/** - * @ignore - */ -var _writeNormal = function(self, data, close, callback) { - // If we have a buffer write it using the writeBuffer method - if(Buffer.isBuffer(data)) { - return writeBuffer(self, data, close, callback); - } else { - return writeBuffer(self, new Buffer(data, 'binary'), close, callback); - } -} - -/** - * @ignore - */ -var _setWriteConcernHash = function(options) { - var finalOptions = {}; - if(options.w != null) finalOptions.w = options.w; - if(options.journal == true) finalOptions.j = options.journal; - if(options.j == true) finalOptions.j = options.j; - if(options.fsync == true) finalOptions.fsync = options.fsync; - if(options.wtimeout != null) finalOptions.wtimeout = options.wtimeout; - return finalOptions; -} - -/** - * @ignore - */ -var _getWriteConcern = function(self, options) { - // Final options - var finalOptions = {w:1}; - options = options || {}; - - // Local options verification - if(options.w != null || typeof options.j == 'boolean' || typeof options.journal == 'boolean' || typeof options.fsync == 'boolean') { - finalOptions = _setWriteConcernHash(options); - } else if(options.safe != null && typeof options.safe == 'object') { - finalOptions = _setWriteConcernHash(options.safe); - } else if(typeof options.safe == "boolean") { - finalOptions = {w: (options.safe ? 1 : 0)}; - } else if(self.options.w != null || typeof self.options.j == 'boolean' || typeof self.options.journal == 'boolean' || typeof self.options.fsync == 'boolean') { - finalOptions = _setWriteConcernHash(self.options); - } else if(self.safe && (self.safe.w != null || typeof self.safe.j == 'boolean' || typeof self.safe.journal == 'boolean' || typeof self.safe.fsync == 'boolean')) { - finalOptions = _setWriteConcernHash(self.safe); - } else if(typeof self.safe == "boolean") { - finalOptions = {w: (self.safe ? 1 : 0)}; - } - - // Ensure we don't have an invalid combination of write concerns - if(finalOptions.w < 1 - && (finalOptions.journal == true || finalOptions.j == true || finalOptions.fsync == true)) throw MongoError.create({message: "No acknowledgement using w < 1 cannot be combined with journal:true or fsync:true", driver:true}); - - // Return the options - return finalOptions; -} - -/** - * Create a new GridStoreStream instance (INTERNAL TYPE, do not instantiate directly) - * - * @class - * @extends external:Duplex - * @return {GridStoreStream} a GridStoreStream instance. - * @deprecated Use GridFSBucket API instead - */ -var GridStoreStream = function(gs) { - // Initialize the duplex stream - Duplex.call(this); - - // Get the gridstore - this.gs = gs; - - // End called - this.endCalled = false; - - // If we have a seek - this.totalBytesToRead = this.gs.length - this.gs.position; - this.seekPosition = this.gs.position; -} - -// -// Inherit duplex -inherits(GridStoreStream, Duplex); - -GridStoreStream.prototype._pipe = GridStoreStream.prototype.pipe; - -// Set up override -GridStoreStream.prototype.pipe = function(destination) { - var self = this; - - // Only open gridstore if not already open - if(!self.gs.isOpen) { - self.gs.open(function(err) { - if(err) return self.emit('error', err); - self.totalBytesToRead = self.gs.length - self.gs.position; - self._pipe.apply(self, [destination]); - }); - } else { - self.totalBytesToRead = self.gs.length - self.gs.position; - self._pipe.apply(self, [destination]); - } - - return destination; -} - -// Called by stream -GridStoreStream.prototype._read = function() { - var self = this; - - var read = function() { - // Read data - self.gs.read(length, function(err, buffer) { - if(err && !self.endCalled) return self.emit('error', err); - - // Stream is closed - if(self.endCalled || buffer == null) return self.push(null); - // Remove bytes read - if(buffer.length <= self.totalBytesToRead) { - self.totalBytesToRead = self.totalBytesToRead - buffer.length; - self.push(buffer); - } else if(buffer.length > self.totalBytesToRead) { - self.totalBytesToRead = self.totalBytesToRead - buffer._index; - self.push(buffer.slice(0, buffer._index)); - } - - // Finished reading - if(self.totalBytesToRead <= 0) { - self.endCalled = true; - } - }); - } - - // Set read length - var length = self.gs.length < self.gs.chunkSize ? self.gs.length - self.seekPosition : self.gs.chunkSize; - if(!self.gs.isOpen) { - self.gs.open(function(err) { - self.totalBytesToRead = self.gs.length - self.gs.position; - if(err) return self.emit('error', err); - read(); - }); - } else { - read(); - } -} - -GridStoreStream.prototype.destroy = function() { - this.pause(); - this.endCalled = true; - this.gs.close(); - this.emit('end'); -} - -GridStoreStream.prototype.write = function(chunk) { - var self = this; - if(self.endCalled) return self.emit('error', MongoError.create({message: 'attempting to write to stream after end called', driver:true})) - // Do we have to open the gridstore - if(!self.gs.isOpen) { - self.gs.open(function() { - self.gs.isOpen = true; - self.gs.write(chunk, function() { - process.nextTick(function() { - self.emit('drain'); - }); - }); - }); - return false; - } else { - self.gs.write(chunk, function() { - self.emit('drain'); - }); - return true; - } -} - -GridStoreStream.prototype.end = function(chunk, encoding, callback) { - var self = this; - var args = Array.prototype.slice.call(arguments, 0); - callback = args.pop(); - if(typeof callback != 'function') args.push(callback); - chunk = args.length ? args.shift() : null; - encoding = args.length ? args.shift() : null; - self.endCalled = true; - - if(chunk) { - self.gs.write(chunk, function() { - self.gs.close(function() { - if(typeof callback == 'function') callback(); - self.emit('end') - }); - }); - } - - self.gs.close(function() { - if(typeof callback == 'function') callback(); - self.emit('end') - }); -} - -/** - * The read() method pulls some data out of the internal buffer and returns it. If there is no data available, then it will return null. - * @function external:Duplex#read - * @param {number} size Optional argument to specify how much data to read. - * @return {(String | Buffer | null)} - */ - -/** - * Call this function to cause the stream to return strings of the specified encoding instead of Buffer objects. - * @function external:Duplex#setEncoding - * @param {string} encoding The encoding to use. - * @return {null} - */ - -/** - * This method will cause the readable stream to resume emitting data events. - * @function external:Duplex#resume - * @return {null} - */ - -/** - * This method will cause a stream in flowing-mode to stop emitting data events. Any data that becomes available will remain in the internal buffer. - * @function external:Duplex#pause - * @return {null} - */ - -/** - * This method pulls all the data out of a readable stream, and writes it to the supplied destination, automatically managing the flow so that the destination is not overwhelmed by a fast readable stream. - * @function external:Duplex#pipe - * @param {Writable} destination The destination for writing data - * @param {object} [options] Pipe options - * @return {null} - */ - -/** - * This method will remove the hooks set up for a previous pipe() call. - * @function external:Duplex#unpipe - * @param {Writable} [destination] The destination for writing data - * @return {null} - */ - -/** - * This is useful in certain cases where a stream is being consumed by a parser, which needs to "un-consume" some data that it has optimistically pulled out of the source, so that the stream can be passed on to some other party. - * @function external:Duplex#unshift - * @param {(Buffer|string)} chunk Chunk of data to unshift onto the read queue. - * @return {null} - */ - -/** - * Versions of Node prior to v0.10 had streams that did not implement the entire Streams API as it is today. (See "Compatibility" below for more information.) - * @function external:Duplex#wrap - * @param {Stream} stream An "old style" readable stream. - * @return {null} - */ - -/** - * This method writes some data to the underlying system, and calls the supplied callback once the data has been fully handled. - * @function external:Duplex#write - * @param {(string|Buffer)} chunk The data to write - * @param {string} encoding The encoding, if chunk is a String - * @param {function} callback Callback for when this chunk of data is flushed - * @return {boolean} - */ - -/** - * Call this method when no more data will be written to the stream. If supplied, the callback is attached as a listener on the finish event. - * @function external:Duplex#end - * @param {(string|Buffer)} chunk The data to write - * @param {string} encoding The encoding, if chunk is a String - * @param {function} callback Callback for when this chunk of data is flushed - * @return {null} - */ - -/** - * GridStoreStream stream data event, fired for each document in the cursor. - * - * @event GridStoreStream#data - * @type {object} - */ - -/** - * GridStoreStream stream end event - * - * @event GridStoreStream#end - * @type {null} - */ - -/** - * GridStoreStream stream close event - * - * @event GridStoreStream#close - * @type {null} - */ - -/** - * GridStoreStream stream readable event - * - * @event GridStoreStream#readable - * @type {null} - */ - -/** - * GridStoreStream stream drain event - * - * @event GridStoreStream#drain - * @type {null} - */ - -/** - * GridStoreStream stream finish event - * - * @event GridStoreStream#finish - * @type {null} - */ - -/** - * GridStoreStream stream pipe event - * - * @event GridStoreStream#pipe - * @type {null} - */ - -/** - * GridStoreStream stream unpipe event - * - * @event GridStoreStream#unpipe - * @type {null} - */ - -/** - * GridStoreStream stream error event - * - * @event GridStoreStream#error - * @type {null} - */ - -/** - * @ignore - */ -module.exports = GridStore; diff --git a/ts-ticket-office-service/node_modules/mongodb/lib/gridfs/index.js b/ts-ticket-office-service/node_modules/mongodb/lib/gridfs/index.js new file mode 100644 index 000000000..cfe89d060 --- /dev/null +++ b/ts-ticket-office-service/node_modules/mongodb/lib/gridfs/index.js @@ -0,0 +1,152 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.GridFSBucket = void 0; +const error_1 = require("../error"); +const mongo_types_1 = require("../mongo_types"); +const utils_1 = require("../utils"); +const write_concern_1 = require("../write_concern"); +const download_1 = require("./download"); +const upload_1 = require("./upload"); +const DEFAULT_GRIDFS_BUCKET_OPTIONS = { + bucketName: 'fs', + chunkSizeBytes: 255 * 1024 +}; +/** + * Constructor for a streaming GridFS interface + * @public + */ +class GridFSBucket extends mongo_types_1.TypedEventEmitter { + constructor(db, options) { + super(); + this.setMaxListeners(0); + const privateOptions = { + ...DEFAULT_GRIDFS_BUCKET_OPTIONS, + ...options, + writeConcern: write_concern_1.WriteConcern.fromOptions(options) + }; + this.s = { + db, + options: privateOptions, + _chunksCollection: db.collection(privateOptions.bucketName + '.chunks'), + _filesCollection: db.collection(privateOptions.bucketName + '.files'), + checkedIndexes: false, + calledOpenUploadStream: false + }; + } + /** + * Returns a writable stream (GridFSBucketWriteStream) for writing + * buffers to GridFS. The stream's 'id' property contains the resulting + * file's id. + * + * @param filename - The value of the 'filename' key in the files doc + * @param options - Optional settings. + */ + openUploadStream(filename, options) { + return new upload_1.GridFSBucketWriteStream(this, filename, options); + } + /** + * Returns a writable stream (GridFSBucketWriteStream) for writing + * buffers to GridFS for a custom file id. The stream's 'id' property contains the resulting + * file's id. + */ + openUploadStreamWithId(id, filename, options) { + return new upload_1.GridFSBucketWriteStream(this, filename, { ...options, id }); + } + /** Returns a readable stream (GridFSBucketReadStream) for streaming file data from GridFS. */ + openDownloadStream(id, options) { + return new download_1.GridFSBucketReadStream(this.s._chunksCollection, this.s._filesCollection, this.s.options.readPreference, { _id: id }, options); + } + delete(id, callback) { + return (0, utils_1.maybePromise)(callback, callback => { + return this.s._filesCollection.deleteOne({ _id: id }, (error, res) => { + if (error) { + return callback(error); + } + return this.s._chunksCollection.deleteMany({ files_id: id }, error => { + if (error) { + return callback(error); + } + // Delete orphaned chunks before returning FileNotFound + if (!(res === null || res === void 0 ? void 0 : res.deletedCount)) { + // TODO(NODE-3483): Replace with more appropriate error + // Consider creating new error MongoGridFSFileNotFoundError + return callback(new error_1.MongoRuntimeError(`File not found for id ${id}`)); + } + return callback(); + }); + }); + }); + } + /** Convenience wrapper around find on the files collection */ + find(filter, options) { + filter !== null && filter !== void 0 ? filter : (filter = {}); + options = options !== null && options !== void 0 ? options : {}; + return this.s._filesCollection.find(filter, options); + } + /** + * Returns a readable stream (GridFSBucketReadStream) for streaming the + * file with the given name from GridFS. If there are multiple files with + * the same name, this will stream the most recent file with the given name + * (as determined by the `uploadDate` field). You can set the `revision` + * option to change this behavior. + */ + openDownloadStreamByName(filename, options) { + let sort = { uploadDate: -1 }; + let skip = undefined; + if (options && options.revision != null) { + if (options.revision >= 0) { + sort = { uploadDate: 1 }; + skip = options.revision; + } + else { + skip = -options.revision - 1; + } + } + return new download_1.GridFSBucketReadStream(this.s._chunksCollection, this.s._filesCollection, this.s.options.readPreference, { filename }, { ...options, sort, skip }); + } + rename(id, filename, callback) { + return (0, utils_1.maybePromise)(callback, callback => { + const filter = { _id: id }; + const update = { $set: { filename } }; + return this.s._filesCollection.updateOne(filter, update, (error, res) => { + if (error) { + return callback(error); + } + if (!(res === null || res === void 0 ? void 0 : res.matchedCount)) { + return callback(new error_1.MongoRuntimeError(`File with id ${id} not found`)); + } + return callback(); + }); + }); + } + drop(callback) { + return (0, utils_1.maybePromise)(callback, callback => { + return this.s._filesCollection.drop(error => { + if (error) { + return callback(error); + } + return this.s._chunksCollection.drop(error => { + if (error) { + return callback(error); + } + return callback(); + }); + }); + }); + } + /** Get the Db scoped logger. */ + getLogger() { + return this.s.db.s.logger; + } +} +exports.GridFSBucket = GridFSBucket; +/** + * When the first call to openUploadStream is made, the upload stream will + * check to see if it needs to create the proper indexes on the chunks and + * files collections. This event is fired either when 1) it determines that + * no index creation is necessary, 2) when it successfully creates the + * necessary indexes. + * @event + */ +GridFSBucket.INDEX = 'index'; +//# sourceMappingURL=index.js.map \ No newline at end of file diff --git a/ts-ticket-office-service/node_modules/mongodb/lib/gridfs/index.js.map b/ts-ticket-office-service/node_modules/mongodb/lib/gridfs/index.js.map new file mode 100644 index 000000000..861e3b8c2 --- /dev/null +++ b/ts-ticket-office-service/node_modules/mongodb/lib/gridfs/index.js.map @@ -0,0 +1 @@ +{"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/gridfs/index.ts"],"names":[],"mappings":";;;AAIA,oCAA6C;AAE7C,gDAA2D;AAG3D,oCAAkD;AAClD,oDAAqE;AAErE,yCAKoB;AACpB,qCAAgG;AAEhG,MAAM,6BAA6B,GAG/B;IACF,UAAU,EAAE,IAAI;IAChB,cAAc,EAAE,GAAG,GAAG,IAAI;CAC3B,CAAC;AAgCF;;;GAGG;AACH,MAAa,YAAa,SAAQ,+BAAqC;IAcrE,YAAY,EAAM,EAAE,OAA6B;QAC/C,KAAK,EAAE,CAAC;QACR,IAAI,CAAC,eAAe,CAAC,CAAC,CAAC,CAAC;QACxB,MAAM,cAAc,GAAG;YACrB,GAAG,6BAA6B;YAChC,GAAG,OAAO;YACV,YAAY,EAAE,4BAAY,CAAC,WAAW,CAAC,OAAO,CAAC;SAChD,CAAC;QACF,IAAI,CAAC,CAAC,GAAG;YACP,EAAE;YACF,OAAO,EAAE,cAAc;YACvB,iBAAiB,EAAE,EAAE,CAAC,U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BAC3C,IAAI,KAAK,EAAE;wBACT,OAAO,QAAQ,CAAC,KAAK,CAAC,CAAC;qBACxB;oBAED,OAAO,QAAQ,EAAE,CAAC;gBACpB,CAAC,CAAC,CAAC;YACL,CAAC,CAAC,CAAC;QACL,CAAC,CAAC,CAAC;IACL,CAAC;IAED,gCAAgC;IAChC,SAAS;QACP,OAAO,IAAI,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,MAAM,CAAC;IAC5B,CAAC;;AAjMH,oCAkMC;AA9LC;;;;;;;GAOG;AACa,kBAAK,GAAG,OAAgB,CAAC"} \ No newline at end of file diff --git a/ts-ticket-office-service/node_modules/mongodb/lib/gridfs/upload.js b/ts-ticket-office-service/node_modules/mongodb/lib/gridfs/upload.js new file mode 100644 index 000000000..71507d377 --- /dev/null +++ b/ts-ticket-office-service/node_modules/mongodb/lib/gridfs/upload.js @@ -0,0 +1,376 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.GridFSBucketWriteStream = void 0; +const stream_1 = require("stream"); +const bson_1 = require("../bson"); +const error_1 = require("../error"); +const utils_1 = require("../utils"); +const write_concern_1 = require("./../write_concern"); +/** + * A writable stream that enables you to write buffers to GridFS. + * + * Do not instantiate this class directly. Use `openUploadStream()` instead. + * @public + */ +class GridFSBucketWriteStream extends stream_1.Writable { + /** @internal + * @param bucket - Handle for this stream's corresponding bucket + * @param filename - The value of the 'filename' key in the files doc + * @param options - Optional settings. + */ + constructor(bucket, filename, options) { + super(); + options = options !== null && options !== void 0 ? options : {}; + this.bucket = bucket; + this.chunks = bucket.s._chunksCollection; + this.filename = filename; + this.files = bucket.s._filesCollection; + this.options = options; + this.writeConcern = write_concern_1.WriteConcern.fromOptions(options) || bucket.s.options.writeConcern; + // Signals the write is all done + this.done = false; + this.id = options.id ? options.id : new bson_1.ObjectId(); + // properly inherit the default chunksize from parent + this.chunkSizeBytes = options.chunkSizeBytes || this.bucket.s.options.chunkSizeBytes; + this.bufToStore = Buffer.alloc(this.chunkSizeBytes); + this.length = 0; + this.n = 0; + this.pos = 0; + this.state = { + streamEnd: false, + outstandingRequests: 0, + errored: false, + aborted: false + }; + if (!this.bucket.s.calledOpenUploadStream) { + this.bucket.s.calledOpenUploadStream = true; + checkIndexes(this, () => { + this.bucket.s.checkedIndexes = true; + this.bucket.emit('index'); + }); + } + } + write(chunk, encodingOrCallback, callback) { + const encoding = typeof encodingOrCallback === 'function' ? undefined : encodingOrCallback; + callback = typeof encodingOrCallback === 'function' ? encodingOrCallback : callback; + return waitForIndexes(this, () => doWrite(this, chunk, encoding, callback)); + } + abort(callback) { + return (0, utils_1.maybePromise)(callback, callback => { + if (this.state.streamEnd) { + // TODO(NODE-3485): Replace with MongoGridFSStreamClosed + return callback(new error_1.MongoAPIError('Cannot abort a stream that has already completed')); + } + if (this.state.aborted) { + // TODO(NODE-3485): Replace with MongoGridFSStreamClosed + return callback(new error_1.MongoAPIError('Cannot call abort() on a stream twice')); + } + this.state.aborted = true; + this.chunks.deleteMany({ files_id: this.id }, error => callback(error)); + }); + } + end(chunkOrCallback, encodingOrCallback, callback) { + const chunk = typeof chunkOrCallback === 'function' ? undefined : chunkOrCallback; + const encoding = typeof encodingOrCallback === 'function' ? undefined : encodingOrCallback; + callback = + typeof chunkOrCallback === 'function' + ? chunkOrCallback + : typeof encodingOrCallback === 'function' + ? encodingOrCallback + : callback; + if (this.state.streamEnd || checkAborted(this, callback)) + return this; + this.state.streamEnd = true; + if (callback) { + this.once(GridFSBucketWriteStream.FINISH, (result) => { + if (callback) + callback(undefined, result); + }); + } + if (!chunk) { + waitForIndexes(this, () => !!writeRemnant(this)); + return this; + } + this.write(chunk, encoding, () => { + writeRemnant(this); + }); + return this; + } +} +exports.GridFSBucketWriteStream = GridFSBucketWriteStream; +/** @event */ +GridFSBucketWriteStream.CLOSE = 'close'; +/** @event */ +GridFSBucketWriteStream.ERROR = 'error'; +/** + * `end()` was called and the write stream successfully wrote the file metadata and all the chunks to MongoDB. + * @event + */ +GridFSBucketWriteStream.FINISH = 'finish'; +function __handleError(stream, error, callback) { + if (stream.state.errored) { + return; + } + stream.state.errored = true; + if (callback) { + return callback(error); + } + stream.emit(GridFSBucketWriteStream.ERROR, error); +} +function createChunkDoc(filesId, n, data) { + return { + _id: new bson_1.ObjectId(), + files_id: filesId, + n, + data + }; +} +function checkChunksIndex(stream, callback) { + stream.chunks.listIndexes().toArray((error, indexes) => { + let index; + if (error) { + // Collection doesn't exist so create index + if (error instanceof error_1.MongoError && error.code === error_1.MONGODB_ERROR_CODES.NamespaceNotFound) { + index = { files_id: 1, n: 1 }; + stream.chunks.createIndex(index, { background: false, unique: true }, error => { + if (error) { + return callback(error); + } + callback(); + }); + return; + } + return callback(error); + } + let hasChunksIndex = false; + if (indexes) { + indexes.forEach((index) => { + if (index.key) { + const keys = Object.keys(index.key); + if (keys.length === 2 && index.key.files_id === 1 && index.key.n === 1) { + hasChunksIndex = true; + } + } + }); + } + if (hasChunksIndex) { + callback(); + } + else { + index = { files_id: 1, n: 1 }; + const writeConcernOptions = getWriteOptions(stream); + stream.chunks.createIndex(index, { + ...writeConcernOptions, + background: true, + unique: true + }, callback); + } + }); +} +function checkDone(stream, callback) { + if (stream.done) + return true; + if (stream.state.streamEnd && stream.state.outstandingRequests === 0 && !stream.state.errored) { + // Set done so we do not trigger duplicate createFilesDoc + stream.done = true; + // Create a new files doc + const filesDoc = createFilesDoc(stream.id, stream.length, stream.chunkSizeBytes, stream.filename, stream.options.contentType, stream.options.aliases, stream.options.metadata); + if (checkAborted(stream, callback)) { + return false; + } + stream.files.insertOne(filesDoc, getWriteOptions(stream), (error) => { + if (error) { + return __handleError(stream, error, callback); + } + stream.emit(GridFSBucketWriteStream.FINISH, filesDoc); + stream.emit(GridFSBucketWriteStream.CLOSE); + }); + return true; + } + return false; +} +function checkIndexes(stream, callback) { + stream.files.findOne({}, { projection: { _id: 1 } }, (error, doc) => { + if (error) { + return callback(error); + } + if (doc) { + return callback(); + } + stream.files.listIndexes().toArray((error, indexes) => { + let index; + if (error) { + // Collection doesn't exist so create index + if (error instanceof error_1.MongoError && error.code === error_1.MONGODB_ERROR_CODES.NamespaceNotFound) { + index = { filename: 1, uploadDate: 1 }; + stream.files.createIndex(index, { background: false }, (error) => { + if (error) { + return callback(error); + } + checkChunksIndex(stream, callback); + }); + return; + } + return callback(error); + } + let hasFileIndex = false; + if (indexes) { + indexes.forEach((index) => { + const keys = Object.keys(index.key); + if (keys.length === 2 && index.key.filename === 1 && index.key.uploadDate === 1) { + hasFileIndex = true; + } + }); + } + if (hasFileIndex) { + checkChunksIndex(stream, callback); + } + else { + index = { filename: 1, uploadDate: 1 }; + const writeConcernOptions = getWriteOptions(stream); + stream.files.createIndex(index, { + ...writeConcernOptions, + background: false + }, (error) => { + if (error) { + return callback(error); + } + checkChunksIndex(stream, callback); + }); + } + }); + }); +} +function createFilesDoc(_id, length, chunkSize, filename, contentType, aliases, metadata) { + const ret = { + _id, + length, + chunkSize, + uploadDate: new Date(), + filename + }; + if (contentType) { + ret.contentType = contentType; + } + if (aliases) { + ret.aliases = aliases; + } + if (metadata) { + ret.metadata = metadata; + } + return ret; +} +function doWrite(stream, chunk, encoding, callback) { + if (checkAborted(stream, callback)) { + return false; + } + const inputBuf = Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk, encoding); + stream.length += inputBuf.length; + // Input is small enough to fit in our buffer + if (stream.pos + inputBuf.length < stream.chunkSizeBytes) { + inputBuf.copy(stream.bufToStore, stream.pos); + stream.pos += inputBuf.length; + callback && callback(); + // Note that we reverse the typical semantics of write's return value + // to be compatible with node's `.pipe()` function. + // True means client can keep writing. + return true; + } + // Otherwise, buffer is too big for current chunk, so we need to flush + // to MongoDB. + let inputBufRemaining = inputBuf.length; + let spaceRemaining = stream.chunkSizeBytes - stream.pos; + let numToCopy = Math.min(spaceRemaining, inputBuf.length); + let outstandingRequests = 0; + while (inputBufRemaining > 0) { + const inputBufPos = inputBuf.length - inputBufRemaining; + inputBuf.copy(stream.bufToStore, stream.pos, inputBufPos, inputBufPos + numToCopy); + stream.pos += numToCopy; + spaceRemaining -= numToCopy; + let doc; + if (spaceRemaining === 0) { + doc = createChunkDoc(stream.id, stream.n, Buffer.from(stream.bufToStore)); + ++stream.state.outstandingRequests; + ++outstandingRequests; + if (checkAborted(stream, callback)) { + return false; + } + stream.chunks.insertOne(doc, getWriteOptions(stream), (error) => { + if (error) { + return __handleError(stream, error); + } + --stream.state.outstandingRequests; + --outstandingRequests; + if (!outstandingRequests) { + stream.emit('drain', doc); + callback && callback(); + checkDone(stream); + } + }); + spaceRemaining = stream.chunkSizeBytes; + stream.pos = 0; + ++stream.n; + } + inputBufRemaining -= numToCopy; + numToCopy = Math.min(spaceRemaining, inputBufRemaining); + } + // Note that we reverse the typical semantics of write's return value + // to be compatible with node's `.pipe()` function. + // False means the client should wait for the 'drain' event. + return false; +} +function getWriteOptions(stream) { + const obj = {}; + if (stream.writeConcern) { + obj.writeConcern = { + w: stream.writeConcern.w, + wtimeout: stream.writeConcern.wtimeout, + j: stream.writeConcern.j + }; + } + return obj; +} +function waitForIndexes(stream, callback) { + if (stream.bucket.s.checkedIndexes) { + return callback(false); + } + stream.bucket.once('index', () => { + callback(true); + }); + return true; +} +function writeRemnant(stream, callback) { + // Buffer is empty, so don't bother to insert + if (stream.pos === 0) { + return checkDone(stream, callback); + } + ++stream.state.outstandingRequests; + // Create a new buffer to make sure the buffer isn't bigger than it needs + // to be. + const remnant = Buffer.alloc(stream.pos); + stream.bufToStore.copy(remnant, 0, 0, stream.pos); + const doc = createChunkDoc(stream.id, stream.n, remnant); + // If the stream was aborted, do not write remnant + if (checkAborted(stream, callback)) { + return false; + } + stream.chunks.insertOne(doc, getWriteOptions(stream), (error) => { + if (error) { + return __handleError(stream, error); + } + --stream.state.outstandingRequests; + checkDone(stream); + }); + return true; +} +function checkAborted(stream, callback) { + if (stream.state.aborted) { + if (typeof callback === 'function') { + // TODO(NODE-3485): Replace with MongoGridFSStreamClosedError + callback(new error_1.MongoAPIError('Stream has been aborted')); + } + return true; + } + return false; +} +//# sourceMappingURL=upload.js.map \ No newline at end of file diff --git a/ts-ticket-office-service/node_modules/mongodb/lib/gridfs/upload.js.map b/ts-ticket-office-service/node_modules/mongodb/lib/gridfs/upload.js.map new file mode 100644 index 000000000..c9c6c481a --- /dev/null +++ b/ts-ticket-office-service/node_modules/mongodb/lib/gridfs/upload.js.map @@ -0,0 +1 @@ +{"version":3,"file":"upload.js","sourceRoot":"","sources":["../../src/gridfs/upload.ts"],"names":[],"mappings":";;;AAAA,mCAAkC;AAGlC,kCAAmC;AAEnC,oCAAoF;AACpF,oCAAkD;AAElD,sDAAkD;AA0BlD;;;;;GAKG;AACH,MAAa,uBAAwB,SAAQ,iBAAQ;IA+BnD;;;;OAIG;IACH,YAAY,MAAoB,EAAE,QAAgB,EAAE,OAAwC;QAC1F,KAAK,EAAE,CAAC;QAER,OAAO,GAAG,OAAO,aAAP,OAAO,cAAP,OAAO,GAAI,EAAE,CAAC;QACxB,IAAI,CAAC,MAAM,GAAG,MAAM,CAAC;QACrB,IAAI,CAAC,MAAM,GAAG,MAAM,CAAC,CAAC,CAAC,iBAAiB,CAAC;QACzC,IAAI,CAAC,QAAQ,GAAG,QAAQ,CAAC;QACzB,IAAI,CAAC,KAAK,GAAG,MAAM,CAAC,CAAC,CAAC,gBAAgB,CAAC;QACvC,IAAI,CAAC,OAAO,GAAG,OAAO,CAAC;QACvB,IAAI,CAAC,YAAY,GAAG,4BAAY,CAAC,WAAW,CAAC,OAAO,CAAC,IAAI,MAAM,CAAC,CAAC,CAAC,OAAO,CAAC,YAAY,CAAC;QACvF,gCAAgC;QAChC,IAAI,CAAC,IAAI,GAAG,KAAK,CAAC;QAElB,IAAI,CAAC,EAAE,GAAG,OAAO,CAAC,EAAE,CAAC,CAAC,CAAC,OAAO,CAAC,EAAE,CAAC,CAAC,CAAC,IAAI,eAAQ,EAAE,CAAC;QACnD,qDAAqD;QACrD,IAAI,CAAC,cAAc,GAAG,OAA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AC,CAAC;IAEzD,kDAAkD;IAClD,IAAI,YAAY,CAAC,MAAM,EAAE,QAAQ,CAAC,EAAE;QAClC,OAAO,KAAK,CAAC;KACd;IAED,MAAM,CAAC,MAAM,CAAC,SAAS,CAAC,GAAG,EAAE,eAAe,CAAC,MAAM,CAAC,EAAE,CAAC,KAAgB,EAAE,EAAE;QACzE,IAAI,KAAK,EAAE;YACT,OAAO,aAAa,CAAC,MAAM,EAAE,KAAK,CAAC,CAAC;SACrC;QACD,EAAE,MAAM,CAAC,KAAK,CAAC,mBAAmB,CAAC;QACnC,SAAS,CAAC,MAAM,CAAC,CAAC;IACpB,CAAC,CAAC,CAAC;IACH,OAAO,IAAI,CAAC;AACd,CAAC;AAED,SAAS,YAAY,CAAC,MAA+B,EAAE,QAAyB;IAC9E,IAAI,MAAM,CAAC,KAAK,CAAC,OAAO,EAAE;QACxB,IAAI,OAAO,QAAQ,KAAK,UAAU,EAAE;YAClC,6DAA6D;YAC7D,QAAQ,CAAC,IAAI,qBAAa,CAAC,yBAAyB,CAAC,CAAC,CAAC;SACxD;QACD,OAAO,IAAI,CAAC;KACb;IACD,OAAO,KAAK,CAAC;AACf,CAAC"} \ No newline at end of file diff --git a/ts-ticket-office-service/node_modules/mongodb/lib/index.js b/ts-ticket-office-service/node_modules/mongodb/lib/index.js new file mode 100644 index 000000000..5ea1b903b --- /dev/null +++ b/ts-ticket-office-service/node_modules/mongodb/lib/index.js @@ -0,0 +1,159 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.Admin = exports.AbstractCursor = exports.MongoWriteConcernError = exports.MongoUnexpectedServerResponseError = exports.MongoTransactionError = exports.MongoTopologyClosedError = exports.MongoTailableCursorError = exports.MongoSystemError = exports.MongoServerSelectionError = exports.MongoServerError = exports.MongoServerClosedError = exports.MongoRuntimeError = exports.MongoParseError = exports.MongoNotConnectedError = exports.MongoNetworkTimeoutError = exports.MongoNetworkError = exports.MongoMissingDependencyError = exports.MongoMissingCredentialsError = exports.MongoKerberosError = exports.MongoInvalidArgumentError = exports.MongoGridFSStreamError = exports.MongoGridFSChunkError = exports.MongoExpiredSessionError = exports.MongoError = exports.MongoDriverError = exports.MongoDecompressionError = exports.MongoCursorInUseError = exports.MongoCursorExhaustedError = exports.MongoCompatibilityError = exports.MongoChangeStreamError = exports.MongoBatchReExecutionError = exports.MongoAWSError = exports.MongoAPIError = exports.MongoBulkWriteError = exports.ObjectID = exports.ChangeStreamCursor = exports.Timestamp = exports.ObjectId = exports.MinKey = exports.MaxKey = exports.Map = exports.Long = exports.Int32 = exports.Double = exports.Decimal128 = exports.DBRef = exports.Code = exports.BSONSymbol = exports.BSONRegExp = exports.Binary = void 0; +exports.ServerHeartbeatSucceededEvent = exports.ServerHeartbeatStartedEvent = exports.ServerHeartbeatFailedEvent = exports.ServerDescriptionChangedEvent = exports.ServerClosedEvent = exports.ConnectionReadyEvent = exports.ConnectionPoolMonitoringEvent = exports.ConnectionPoolCreatedEvent = exports.ConnectionPoolClosedEvent = exports.ConnectionPoolClearedEvent = exports.ConnectionCreatedEvent = exports.ConnectionClosedEvent = exports.ConnectionCheckOutStartedEvent = exports.ConnectionCheckOutFailedEvent = exports.ConnectionCheckedOutEvent = exports.ConnectionCheckedInEvent = exports.CommandSucceededEvent = exports.CommandStartedEvent = exports.CommandFailedEvent = exports.WriteConcern = exports.ReadPreference = exports.ReadConcern = exports.TopologyType = exports.ServerType = exports.ReadPreferenceMode = exports.ReadConcernLevel = exports.ProfilingLevel = exports.ReturnDocument = exports.BSONType = exports.ServerApiVersion = exports.LoggerLevel = exports.ExplainVerbosity = exports.MongoErrorLabel = exports.AutoEncryptionLoggerLevel = exports.CURSOR_FLAGS = exports.Compressor = exports.AuthMechanism = exports.GSSAPICanonicalizationValue = exports.BatchType = exports.Promise = exports.MongoClient = exports.Logger = exports.ListIndexesCursor = exports.ListCollectionsCursor = exports.GridFSBucket = exports.FindCursor = exports.Db = exports.Collection = exports.CancellationToken = exports.AggregationCursor = void 0; +exports.SrvPollingEvent = exports.TopologyOpeningEvent = exports.TopologyDescriptionChangedEvent = exports.TopologyClosedEvent = exports.ServerOpeningEvent = void 0; +const admin_1 = require("./admin"); +Object.defineProperty(exports, "Admin", { enumerable: true, get: function () { return admin_1.Admin; } }); +const bson_1 = require("./bson"); +const collection_1 = require("./collection"); +Object.defineProperty(exports, "Collection", { enumerable: true, get: function () { return collection_1.Collection; } }); +const abstract_cursor_1 = require("./cursor/abstract_cursor"); +Object.defineProperty(exports, "AbstractCursor", { enumerable: true, get: function () { return abstract_cursor_1.AbstractCursor; } }); +const aggregation_cursor_1 = require("./cursor/aggregation_cursor"); +Object.defineProperty(exports, "AggregationCursor", { enumerable: true, get: function () { return aggregation_cursor_1.AggregationCursor; } }); +const find_cursor_1 = require("./cursor/find_cursor"); +Object.defineProperty(exports, "FindCursor", { enumerable: true, get: function () { return find_cursor_1.FindCursor; } }); +const list_collections_cursor_1 = require("./cursor/list_collections_cursor"); +Object.defineProperty(exports, "ListCollectionsCursor", { enumerable: true, get: function () { return list_collections_cursor_1.ListCollectionsCursor; } }); +const list_indexes_cursor_1 = require("./cursor/list_indexes_cursor"); +Object.defineProperty(exports, "ListIndexesCursor", { enumerable: true, get: function () { return list_indexes_cursor_1.ListIndexesCursor; } }); +const db_1 = require("./db"); +Object.defineProperty(exports, "Db", { enumerable: true, get: function () { return db_1.Db; } }); +const gridfs_1 = require("./gridfs"); +Object.defineProperty(exports, "GridFSBucket", { enumerable: true, get: function () { return gridfs_1.GridFSBucket; } }); +const logger_1 = require("./logger"); +Object.defineProperty(exports, "Logger", { enumerable: true, get: function () { return logger_1.Logger; } }); +const mongo_client_1 = require("./mongo_client"); +Object.defineProperty(exports, "MongoClient", { enumerable: true, get: function () { return mongo_client_1.MongoClient; } }); +const mongo_types_1 = require("./mongo_types"); +Object.defineProperty(exports, "CancellationToken", { enumerable: true, get: function () { return mongo_types_1.CancellationToken; } }); +const promise_provider_1 = require("./promise_provider"); +Object.defineProperty(exports, "Promise", { enumerable: true, get: function () { return promise_provider_1.PromiseProvider; } }); +var bson_2 = require("./bson"); +Object.defineProperty(exports, "Binary", { enumerable: true, get: function () { return bson_2.Binary; } }); +Object.defineProperty(exports, "BSONRegExp", { enumerable: true, get: function () { return bson_2.BSONRegExp; } }); +Object.defineProperty(exports, "BSONSymbol", { enumerable: true, get: function () { return bson_2.BSONSymbol; } }); +Object.defineProperty(exports, "Code", { enumerable: true, get: function () { return bson_2.Code; } }); +Object.defineProperty(exports, "DBRef", { enumerable: true, get: function () { return bson_2.DBRef; } }); +Object.defineProperty(exports, "Decimal128", { enumerable: true, get: function () { return bson_2.Decimal128; } }); +Object.defineProperty(exports, "Double", { enumerable: true, get: function () { return bson_2.Double; } }); +Object.defineProperty(exports, "Int32", { enumerable: true, get: function () { return bson_2.Int32; } }); +Object.defineProperty(exports, "Long", { enumerable: true, get: function () { return bson_2.Long; } }); +Object.defineProperty(exports, "Map", { enumerable: true, get: function () { return bson_2.Map; } }); +Object.defineProperty(exports, "MaxKey", { enumerable: true, get: function () { return bson_2.MaxKey; } }); +Object.defineProperty(exports, "MinKey", { enumerable: true, get: function () { return bson_2.MinKey; } }); +Object.defineProperty(exports, "ObjectId", { enumerable: true, get: function () { return bson_2.ObjectId; } }); +Object.defineProperty(exports, "Timestamp", { enumerable: true, get: function () { return bson_2.Timestamp; } }); +var change_stream_cursor_1 = require("./cursor/change_stream_cursor"); +Object.defineProperty(exports, "ChangeStreamCursor", { enumerable: true, get: function () { return change_stream_cursor_1.ChangeStreamCursor; } }); +/** + * @public + * @deprecated Please use `ObjectId` + */ +exports.ObjectID = bson_1.ObjectId; +var common_1 = require("./bulk/common"); +Object.defineProperty(exports, "MongoBulkWriteError", { enumerable: true, get: function () { return common_1.MongoBulkWriteError; } }); +var error_1 = require("./error"); +Object.defineProperty(exports, "MongoAPIError", { enumerable: true, get: function () { return error_1.MongoAPIError; } }); +Object.defineProperty(exports, "MongoAWSError", { enumerable: true, get: function () { return error_1.MongoAWSError; } }); +Object.defineProperty(exports, "MongoBatchReExecutionError", { enumerable: true, get: function () { return error_1.MongoBatchReExecutionError; } }); +Object.defineProperty(exports, "MongoChangeStreamError", { enumerable: true, get: function () { return error_1.MongoChangeStreamError; } }); +Object.defineProperty(exports, "MongoCompatibilityError", { enumerable: true, get: function () { return error_1.MongoCompatibilityError; } }); +Object.defineProperty(exports, "MongoCursorExhaustedError", { enumerable: true, get: function () { return error_1.MongoCursorExhaustedError; } }); +Object.defineProperty(exports, "MongoCursorInUseError", { enumerable: true, get: function () { return error_1.MongoCursorInUseError; } }); +Object.defineProperty(exports, "MongoDecompressionError", { enumerable: true, get: function () { return error_1.MongoDecompressionError; } }); +Object.defineProperty(exports, "MongoDriverError", { enumerable: true, get: function () { return error_1.MongoDriverError; } }); +Object.defineProperty(exports, "MongoError", { enumerable: true, get: function () { return error_1.MongoError; } }); +Object.defineProperty(exports, "MongoExpiredSessionError", { enumerable: true, get: function () { return error_1.MongoExpiredSessionError; } }); +Object.defineProperty(exports, "MongoGridFSChunkError", { enumerable: true, get: function () { return error_1.MongoGridFSChunkError; } }); +Object.defineProperty(exports, "MongoGridFSStreamError", { enumerable: true, get: function () { return error_1.MongoGridFSStreamError; } }); +Object.defineProperty(exports, "MongoInvalidArgumentError", { enumerable: true, get: function () { return error_1.MongoInvalidArgumentError; } }); +Object.defineProperty(exports, "MongoKerberosError", { enumerable: true, get: function () { return error_1.MongoKerberosError; } }); +Object.defineProperty(exports, "MongoMissingCredentialsError", { enumerable: true, get: function () { return error_1.MongoMissingCredentialsError; } }); +Object.defineProperty(exports, "MongoMissingDependencyError", { enumerable: true, get: function () { return error_1.MongoMissingDependencyError; } }); +Object.defineProperty(exports, "MongoNetworkError", { enumerable: true, get: function () { return error_1.MongoNetworkError; } }); +Object.defineProperty(exports, "MongoNetworkTimeoutError", { enumerable: true, get: function () { return error_1.MongoNetworkTimeoutError; } }); +Object.defineProperty(exports, "MongoNotConnectedError", { enumerable: true, get: function () { return error_1.MongoNotConnectedError; } }); +Object.defineProperty(exports, "MongoParseError", { enumerable: true, get: function () { return error_1.MongoParseError; } }); +Object.defineProperty(exports, "MongoRuntimeError", { enumerable: true, get: function () { return error_1.MongoRuntimeError; } }); +Object.defineProperty(exports, "MongoServerClosedError", { enumerable: true, get: function () { return error_1.MongoServerClosedError; } }); +Object.defineProperty(exports, "MongoServerError", { enumerable: true, get: function () { return error_1.MongoServerError; } }); +Object.defineProperty(exports, "MongoServerSelectionError", { enumerable: true, get: function () { return error_1.MongoServerSelectionError; } }); +Object.defineProperty(exports, "MongoSystemError", { enumerable: true, get: function () { return error_1.MongoSystemError; } }); +Object.defineProperty(exports, "MongoTailableCursorError", { enumerable: true, get: function () { return error_1.MongoTailableCursorError; } }); +Object.defineProperty(exports, "MongoTopologyClosedError", { enumerable: true, get: function () { return error_1.MongoTopologyClosedError; } }); +Object.defineProperty(exports, "MongoTransactionError", { enumerable: true, get: function () { return error_1.MongoTransactionError; } }); +Object.defineProperty(exports, "MongoUnexpectedServerResponseError", { enumerable: true, get: function () { return error_1.MongoUnexpectedServerResponseError; } }); +Object.defineProperty(exports, "MongoWriteConcernError", { enumerable: true, get: function () { return error_1.MongoWriteConcernError; } }); +// enums +var common_2 = require("./bulk/common"); +Object.defineProperty(exports, "BatchType", { enumerable: true, get: function () { return common_2.BatchType; } }); +var gssapi_1 = require("./cmap/auth/gssapi"); +Object.defineProperty(exports, "GSSAPICanonicalizationValue", { enumerable: true, get: function () { return gssapi_1.GSSAPICanonicalizationValue; } }); +var providers_1 = require("./cmap/auth/providers"); +Object.defineProperty(exports, "AuthMechanism", { enumerable: true, get: function () { return providers_1.AuthMechanism; } }); +var compression_1 = require("./cmap/wire_protocol/compression"); +Object.defineProperty(exports, "Compressor", { enumerable: true, get: function () { return compression_1.Compressor; } }); +var abstract_cursor_2 = require("./cursor/abstract_cursor"); +Object.defineProperty(exports, "CURSOR_FLAGS", { enumerable: true, get: function () { return abstract_cursor_2.CURSOR_FLAGS; } }); +var deps_1 = require("./deps"); +Object.defineProperty(exports, "AutoEncryptionLoggerLevel", { enumerable: true, get: function () { return deps_1.AutoEncryptionLoggerLevel; } }); +var error_2 = require("./error"); +Object.defineProperty(exports, "MongoErrorLabel", { enumerable: true, get: function () { return error_2.MongoErrorLabel; } }); +var explain_1 = require("./explain"); +Object.defineProperty(exports, "ExplainVerbosity", { enumerable: true, get: function () { return explain_1.ExplainVerbosity; } }); +var logger_2 = require("./logger"); +Object.defineProperty(exports, "LoggerLevel", { enumerable: true, get: function () { return logger_2.LoggerLevel; } }); +var mongo_client_2 = require("./mongo_client"); +Object.defineProperty(exports, "ServerApiVersion", { enumerable: true, get: function () { return mongo_client_2.ServerApiVersion; } }); +var mongo_types_2 = require("./mongo_types"); +Object.defineProperty(exports, "BSONType", { enumerable: true, get: function () { return mongo_types_2.BSONType; } }); +var find_and_modify_1 = require("./operations/find_and_modify"); +Object.defineProperty(exports, "ReturnDocument", { enumerable: true, get: function () { return find_and_modify_1.ReturnDocument; } }); +var set_profiling_level_1 = require("./operations/set_profiling_level"); +Object.defineProperty(exports, "ProfilingLevel", { enumerable: true, get: function () { return set_profiling_level_1.ProfilingLevel; } }); +var read_concern_1 = require("./read_concern"); +Object.defineProperty(exports, "ReadConcernLevel", { enumerable: true, get: function () { return read_concern_1.ReadConcernLevel; } }); +var read_preference_1 = require("./read_preference"); +Object.defineProperty(exports, "ReadPreferenceMode", { enumerable: true, get: function () { return read_preference_1.ReadPreferenceMode; } }); +var common_3 = require("./sdam/common"); +Object.defineProperty(exports, "ServerType", { enumerable: true, get: function () { return common_3.ServerType; } }); +Object.defineProperty(exports, "TopologyType", { enumerable: true, get: function () { return common_3.TopologyType; } }); +// Helper classes +var read_concern_2 = require("./read_concern"); +Object.defineProperty(exports, "ReadConcern", { enumerable: true, get: function () { return read_concern_2.ReadConcern; } }); +var read_preference_2 = require("./read_preference"); +Object.defineProperty(exports, "ReadPreference", { enumerable: true, get: function () { return read_preference_2.ReadPreference; } }); +var write_concern_1 = require("./write_concern"); +Object.defineProperty(exports, "WriteConcern", { enumerable: true, get: function () { return write_concern_1.WriteConcern; } }); +// events +var command_monitoring_events_1 = require("./cmap/command_monitoring_events"); +Object.defineProperty(exports, "CommandFailedEvent", { enumerable: true, get: function () { return command_monitoring_events_1.CommandFailedEvent; } }); +Object.defineProperty(exports, "CommandStartedEvent", { enumerable: true, get: function () { return command_monitoring_events_1.CommandStartedEvent; } }); +Object.defineProperty(exports, "CommandSucceededEvent", { enumerable: true, get: function () { return command_monitoring_events_1.CommandSucceededEvent; } }); +var connection_pool_events_1 = require("./cmap/connection_pool_events"); +Object.defineProperty(exports, "ConnectionCheckedInEvent", { enumerable: true, get: function () { return connection_pool_events_1.ConnectionCheckedInEvent; } }); +Object.defineProperty(exports, "ConnectionCheckedOutEvent", { enumerable: true, get: function () { return connection_pool_events_1.ConnectionCheckedOutEvent; } }); +Object.defineProperty(exports, "ConnectionCheckOutFailedEvent", { enumerable: true, get: function () { return connection_pool_events_1.ConnectionCheckOutFailedEvent; } }); +Object.defineProperty(exports, "ConnectionCheckOutStartedEvent", { enumerable: true, get: function () { return connection_pool_events_1.ConnectionCheckOutStartedEvent; } }); +Object.defineProperty(exports, "ConnectionClosedEvent", { enumerable: true, get: function () { return connection_pool_events_1.ConnectionClosedEvent; } }); +Object.defineProperty(exports, "ConnectionCreatedEvent", { enumerable: true, get: function () { return connection_pool_events_1.ConnectionCreatedEvent; } }); +Object.defineProperty(exports, "ConnectionPoolClearedEvent", { enumerable: true, get: function () { return connection_pool_events_1.ConnectionPoolClearedEvent; } }); +Object.defineProperty(exports, "ConnectionPoolClosedEvent", { enumerable: true, get: function () { return connection_pool_events_1.ConnectionPoolClosedEvent; } }); +Object.defineProperty(exports, "ConnectionPoolCreatedEvent", { enumerable: true, get: function () { return connection_pool_events_1.ConnectionPoolCreatedEvent; } }); +Object.defineProperty(exports, "ConnectionPoolMonitoringEvent", { enumerable: true, get: function () { return connection_pool_events_1.ConnectionPoolMonitoringEvent; } }); +Object.defineProperty(exports, "ConnectionReadyEvent", { enumerable: true, get: function () { return connection_pool_events_1.ConnectionReadyEvent; } }); +var events_1 = require("./sdam/events"); +Object.defineProperty(exports, "ServerClosedEvent", { enumerable: true, get: function () { return events_1.ServerClosedEvent; } }); +Object.defineProperty(exports, "ServerDescriptionChangedEvent", { enumerable: true, get: function () { return events_1.ServerDescriptionChangedEvent; } }); +Object.defineProperty(exports, "ServerHeartbeatFailedEvent", { enumerable: true, get: function () { return events_1.ServerHeartbeatFailedEvent; } }); +Object.defineProperty(exports, "ServerHeartbeatStartedEvent", { enumerable: true, get: function () { return events_1.ServerHeartbeatStartedEvent; } }); +Object.defineProperty(exports, "ServerHeartbeatSucceededEvent", { enumerable: true, get: function () { return events_1.ServerHeartbeatSucceededEvent; } }); +Object.defineProperty(exports, "ServerOpeningEvent", { enumerable: true, get: function () { return events_1.ServerOpeningEvent; } }); +Object.defineProperty(exports, "TopologyClosedEvent", { enumerable: true, get: function () { return events_1.TopologyClosedEvent; } }); +Object.defineProperty(exports, "TopologyDescriptionChangedEvent", { enumerable: true, get: function () { return events_1.TopologyDescriptionChangedEvent; } }); +Object.defineProperty(exports, "TopologyOpeningEvent", { enumerable: true, get: function () { return events_1.TopologyOpeningEvent; } }); +var srv_polling_1 = require("./sdam/srv_polling"); +Object.defineProperty(exports, "SrvPollingEvent", { enumerable: true, get: function () { return srv_polling_1.SrvPollingEvent; } }); +//# sourceMappingURL=index.js.map \ No newline at end of file diff --git a/ts-ticket-office-service/node_modules/mongodb/lib/index.js.map b/ts-ticket-office-service/node_modules/mongodb/lib/index.js.map new file mode 100644 index 000000000..1e9f635bb --- /dev/null +++ b/ts-ticket-office-service/node_modules/mongodb/lib/index.js.map @@ -0,0 +1 @@ +{"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":";;;;;AAAA,mCAAgC;AA2E9B,sFA3EO,aAAK,OA2EP;AA1EP,iCAAkC;AAClC,6CAA0C;AA4ExC,2FA5EO,uBAA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;AAAzC,gHAAA,gBAAgB,OAAA;AACzB,qDAAuD;AAA9C,qHAAA,kBAAkB,OAAA;AAC3B,wCAAyD;AAAhD,oGAAA,UAAU,OAAA;AAAE,sGAAA,YAAY,OAAA;AAEjC,iBAAiB;AACjB,+CAA6C;AAApC,2GAAA,WAAW,OAAA;AACpB,qDAAmD;AAA1C,iHAAA,cAAc,OAAA;AACvB,iDAA+C;AAAtC,6GAAA,YAAY,OAAA;AAErB,SAAS;AACT,8EAI0C;AAHxC,+HAAA,kBAAkB,OAAA;AAClB,gIAAA,mBAAmB,OAAA;AACnB,kIAAA,qBAAqB,OAAA;AAEvB,wEAYuC;AAXrC,kIAAA,wBAAwB,OAAA;AACxB,mIAAA,yBAAyB,OAAA;AACzB,uIAAA,6BAA6B,OAAA;AAC7B,wIAAA,8BAA8B,OAAA;AAC9B,+HAAA,qBAAqB,OAAA;AACrB,gIAAA,sBAAsB,OAAA;AACtB,oIAAA,0BAA0B,OAAA;AAC1B,mIAAA,yBAAyB,OAAA;AACzB,oIAAA,0BAA0B,OAAA;AAC1B,uIAAA,6BAA6B,OAAA;AAC7B,8HAAA,oBAAoB,OAAA;AAEtB,wCAUuB;AATrB,2GAAA,iBAAiB,OAAA;AACjB,uHAAA,6BAA6B,OAAA;AAC7B,oHAAA,0BAA0B,OAAA;AAC1B,qHAAA,2BAA2B,OAAA;AAC3B,uHAAA,6BAA6B,OAAA;AAC7B,4GAAA,kBAAkB,OAAA;AAClB,6GAAA,mBAAmB,OAAA;AACnB,yHAAA,+BAA+B,OAAA;AAC/B,8GAAA,oBAAoB,OAAA;AAEtB,kDAAqD;AAA5C,8GAAA,eAAe,OAAA"} \ No newline at end of file diff --git a/ts-ticket-office-service/node_modules/mongodb/lib/logger.js b/ts-ticket-office-service/node_modules/mongodb/lib/logger.js new file mode 100644 index 000000000..03e036e7c --- /dev/null +++ b/ts-ticket-office-service/node_modules/mongodb/lib/logger.js @@ -0,0 +1,217 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.Logger = exports.LoggerLevel = void 0; +const util_1 = require("util"); +const error_1 = require("./error"); +const utils_1 = require("./utils"); +// Filters for classes +const classFilters = {}; +let filteredClasses = {}; +let level; +// Save the process id +const pid = process.pid; +// current logger +// eslint-disable-next-line no-console +let currentLogger = console.warn; +/** @public */ +exports.LoggerLevel = Object.freeze({ + ERROR: 'error', + WARN: 'warn', + INFO: 'info', + DEBUG: 'debug', + error: 'error', + warn: 'warn', + info: 'info', + debug: 'debug' +}); +/** + * @public + */ +class Logger { + /** + * Creates a new Logger instance + * + * @param className - The Class name associated with the logging instance + * @param options - Optional logging settings + */ + constructor(className, options) { + options = options !== null && options !== void 0 ? options : {}; + // Current reference + this.className = className; + // Current logger + if (!(options.logger instanceof Logger) && typeof options.logger === 'function') { + currentLogger = options.logger; + } + // Set level of logging, default is error + if (options.loggerLevel) { + level = options.loggerLevel || exports.LoggerLevel.ERROR; + } + // Add all class names + if (filteredClasses[this.className] == null) { + classFilters[this.className] = true; + } + } + /** + * Log a message at the debug level + * + * @param message - The message to log + * @param object - Additional meta data to log + */ + debug(message, object) { + if (this.isDebug() && + ((Object.keys(filteredClasses).length > 0 && filteredClasses[this.className]) || + (Object.keys(filteredClasses).length === 0 && classFilters[this.className]))) { + const dateTime = new Date().getTime(); + const msg = (0, util_1.format)('[%s-%s:%s] %s %s', 'DEBUG', this.className, pid, dateTime, message); + const state = { + type: exports.LoggerLevel.DEBUG, + message, + className: this.className, + pid, + date: dateTime + }; + if (object) + state.meta = object; + currentLogger(msg, state); + } + } + /** + * Log a message at the warn level + * + * @param message - The message to log + * @param object - Additional meta data to log + */ + warn(message, object) { + if (this.isWarn() && + ((Object.keys(filteredClasses).length > 0 && filteredClasses[this.className]) || + (Object.keys(filteredClasses).length === 0 && classFilters[this.className]))) { + const dateTime = new Date().getTime(); + const msg = (0, util_1.format)('[%s-%s:%s] %s %s', 'WARN', this.className, pid, dateTime, message); + const state = { + type: exports.LoggerLevel.WARN, + message, + className: this.className, + pid, + date: dateTime + }; + if (object) + state.meta = object; + currentLogger(msg, state); + } + } + /** + * Log a message at the info level + * + * @param message - The message to log + * @param object - Additional meta data to log + */ + info(message, object) { + if (this.isInfo() && + ((Object.keys(filteredClasses).length > 0 && filteredClasses[this.className]) || + (Object.keys(filteredClasses).length === 0 && classFilters[this.className]))) { + const dateTime = new Date().getTime(); + const msg = (0, util_1.format)('[%s-%s:%s] %s %s', 'INFO', this.className, pid, dateTime, message); + const state = { + type: exports.LoggerLevel.INFO, + message, + className: this.className, + pid, + date: dateTime + }; + if (object) + state.meta = object; + currentLogger(msg, state); + } + } + /** + * Log a message at the error level + * + * @param message - The message to log + * @param object - Additional meta data to log + */ + error(message, object) { + if (this.isError() && + ((Object.keys(filteredClasses).length > 0 && filteredClasses[this.className]) || + (Object.keys(filteredClasses).length === 0 && classFilters[this.className]))) { + const dateTime = new Date().getTime(); + const msg = (0, util_1.format)('[%s-%s:%s] %s %s', 'ERROR', this.className, pid, dateTime, message); + const state = { + type: exports.LoggerLevel.ERROR, + message, + className: this.className, + pid, + date: dateTime + }; + if (object) + state.meta = object; + currentLogger(msg, state); + } + } + /** Is the logger set at info level */ + isInfo() { + return level === exports.LoggerLevel.INFO || level === exports.LoggerLevel.DEBUG; + } + /** Is the logger set at error level */ + isError() { + return level === exports.LoggerLevel.ERROR || level === exports.LoggerLevel.INFO || level === exports.LoggerLevel.DEBUG; + } + /** Is the logger set at error level */ + isWarn() { + return (level === exports.LoggerLevel.ERROR || + level === exports.LoggerLevel.WARN || + level === exports.LoggerLevel.INFO || + level === exports.LoggerLevel.DEBUG); + } + /** Is the logger set at debug level */ + isDebug() { + return level === exports.LoggerLevel.DEBUG; + } + /** Resets the logger to default settings, error and no filtered classes */ + static reset() { + level = exports.LoggerLevel.ERROR; + filteredClasses = {}; + } + /** Get the current logger function */ + static currentLogger() { + return currentLogger; + } + /** + * Set the current logger function + * + * @param logger - Custom logging function + */ + static setCurrentLogger(logger) { + if (typeof logger !== 'function') { + throw new error_1.MongoInvalidArgumentError('Current logger must be a function'); + } + currentLogger = logger; + } + /** + * Filter log messages for a particular class + * + * @param type - The type of filter (currently only class) + * @param values - The filters to apply + */ + static filter(type, values) { + if (type === 'class' && Array.isArray(values)) { + filteredClasses = {}; + values.forEach(x => (filteredClasses[x] = true)); + } + } + /** + * Set the current log level + * + * @param newLevel - Set current log level (debug, warn, info, error) + */ + static setLevel(newLevel) { + if (newLevel !== exports.LoggerLevel.INFO && + newLevel !== exports.LoggerLevel.ERROR && + newLevel !== exports.LoggerLevel.DEBUG && + newLevel !== exports.LoggerLevel.WARN) { + throw new error_1.MongoInvalidArgumentError(`Argument "newLevel" should be one of ${(0, utils_1.enumToString)(exports.LoggerLevel)}`); + } + level = newLevel; + } +} +exports.Logger = Logger; +//# sourceMappingURL=logger.js.map \ No newline at end of file diff --git a/ts-ticket-office-service/node_modules/mongodb/lib/logger.js.map b/ts-ticket-office-service/node_modules/mongodb/lib/logger.js.map new file mode 100644 index 000000000..4bd0592f8 --- /dev/null +++ b/ts-ticket-office-service/node_modules/mongodb/lib/logger.js.map @@ -0,0 +1 @@ +{"version":3,"file":"logger.js","sourceRoot":"","sources":["../src/logger.ts"],"names":[],"mappings":";;;AAAA,+BAA8B;AAE9B,mCAAoD;AACpD,mCAAuC;AAEvC,sBAAsB;AACtB,MAAM,YAAY,GAAQ,EAAE,CAAC;AAC7B,IAAI,eAAe,GAAQ,EAAE,CAAC;AAC9B,IAAI,KAAkB,CAAC;AAEvB,sBAAsB;AACtB,MAAM,GAAG,GAAG,OAAO,CAAC,GAAG,CAAC;AAExB,iBAAiB;AACjB,sCAAsC;AACtC,IAAI,aAAa,GAAmB,OAAO,CAAC,IAAI,CAAC;AAEjD,cAAc;AACD,QAAA,WAAW,GAAG,MAAM,CAAC,MAAM,CAAC;IACvC,KAAK,EAAE,OAAO;IACd,IAAI,EAAE,MAAM;IACZ,IAAI,EAAE,MAAM;IACZ,KAAK,EAAE,OAAO;IACd,KAAK,EAA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,MAAsB;QAC5C,IAAI,OAAO,MAAM,KAAK,UAAU,EAAE;YAChC,MAAM,IAAI,iCAAyB,CAAC,mCAAmC,CAAC,CAAC;SAC1E;QAED,aAAa,GAAG,MAAM,CAAC;IACzB,CAAC;IAED;;;;;OAKG;IACH,MAAM,CAAC,MAAM,CAAC,IAAY,EAAE,MAAgB;QAC1C,IAAI,IAAI,KAAK,OAAO,IAAI,KAAK,CAAC,OAAO,CAAC,MAAM,CAAC,EAAE;YAC7C,eAAe,GAAG,EAAE,CAAC;YACrB,MAAM,CAAC,OAAO,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC,eAAe,CAAC,CAAC,CAAC,GAAG,IAAI,CAAC,CAAC,CAAC;SAClD;IACH,CAAC;IAED;;;;OAIG;IACH,MAAM,CAAC,QAAQ,CAAC,QAAqB;QACnC,IACE,QAAQ,KAAK,mBAAW,CAAC,IAAI;YAC7B,QAAQ,KAAK,mBAAW,CAAC,KAAK;YAC9B,QAAQ,KAAK,mBAAW,CAAC,KAAK;YAC9B,QAAQ,KAAK,mBAAW,CAAC,IAAI,EAC7B;YACA,MAAM,IAAI,iCAAyB,CACjC,wCAAwC,IAAA,oBAAY,EAAC,mBAAW,CAAC,EAAE,CACpE,CAAC;SACH;QAED,KAAK,GAAG,QAAQ,CAAC;IACnB,CAAC;CACF;AA5ND,wBA4NC"} \ No newline at end of file diff --git a/ts-ticket-office-service/node_modules/mongodb/lib/metadata.js b/ts-ticket-office-service/node_modules/mongodb/lib/metadata.js deleted file mode 100644 index 2c6fe94df..000000000 --- a/ts-ticket-office-service/node_modules/mongodb/lib/metadata.js +++ /dev/null @@ -1,64 +0,0 @@ -var f = require('util').format; - -var Define = function(name, object, stream) { - this.name = name; - this.object = object; - this.stream = typeof stream == 'boolean' ? stream : false; - this.instrumentations = {}; -} - -Define.prototype.classMethod = function(name, options) { - var keys = Object.keys(options).sort(); - var key = generateKey(keys, options); - - // Add a list of instrumentations - if(this.instrumentations[key] == null) { - this.instrumentations[key] = { - methods: [], options: options - } - } - - // Push to list of method for this instrumentation - this.instrumentations[key].methods.push(name); -} - -var generateKey = function(keys, options) { - var parts = []; - for(var i = 0; i < keys.length; i++) { - parts.push(f('%s=%s', keys[i], options[keys[i]])); - } - - return parts.join(); -} - -Define.prototype.staticMethod = function(name, options) { - options.static = true; - var keys = Object.keys(options).sort(); - var key = generateKey(keys, options); - - // Add a list of instrumentations - if(this.instrumentations[key] == null) { - this.instrumentations[key] = { - methods: [], options: options - } - } - - // Push to list of method for this instrumentation - this.instrumentations[key].methods.push(name); -} - -Define.prototype.generate = function() { - // Generate the return object - var object = { - name: this.name, obj: this.object, stream: this.stream, - instrumentations: [] - } - - for(var name in this.instrumentations) { - object.instrumentations.push(this.instrumentations[name]); - } - - return object; -} - -module.exports = Define; diff --git a/ts-ticket-office-service/node_modules/mongodb/lib/mongo_client.js b/ts-ticket-office-service/node_modules/mongodb/lib/mongo_client.js index 289e76b4e..bc9418e2f 100644 --- a/ts-ticket-office-service/node_modules/mongodb/lib/mongo_client.js +++ b/ts-ticket-office-service/node_modules/mongodb/lib/mongo_client.js @@ -1,528 +1,295 @@ "use strict"; - -var parse = require('./url_parser') - , Server = require('./server') - , Mongos = require('./mongos') - , ReplSet = require('./replset') - , EventEmitter = require('events').EventEmitter - , inherits = require('util').inherits - , Define = require('./metadata') - , ReadPreference = require('./read_preference') - , Logger = require('mongodb-core').Logger - , MongoError = require('mongodb-core').MongoError - , Db = require('./db') - , f = require('util').format - , assign = require('./utils').assign - , shallowClone = require('./utils').shallowClone - , authenticate = require('./authenticate'); - +Object.defineProperty(exports, "__esModule", { value: true }); +exports.MongoClient = exports.ServerApiVersion = void 0; +const bson_1 = require("./bson"); +const change_stream_1 = require("./change_stream"); +const connection_string_1 = require("./connection_string"); +const db_1 = require("./db"); +const error_1 = require("./error"); +const mongo_types_1 = require("./mongo_types"); +const connect_1 = require("./operations/connect"); +const promise_provider_1 = require("./promise_provider"); +const read_preference_1 = require("./read_preference"); +const sessions_1 = require("./sessions"); +const utils_1 = require("./utils"); +/** @public */ +exports.ServerApiVersion = Object.freeze({ + v1: '1' +}); +/** @internal */ +const kOptions = Symbol('options'); /** - * @fileOverview The **MongoClient** class is a class that allows for making Connections to MongoDB. + * The **MongoClient** class is a class that allows for making Connections to MongoDB. + * @public + * + * @remarks + * The programmatically provided options take precedence over the URI options. + * + * @example + * ```js + * // Connect using a MongoClient instance + * const MongoClient = require('mongodb').MongoClient; + * const test = require('assert'); + * // Connection url + * const url = 'mongodb://localhost:27017'; + * // Database Name + * const dbName = 'test'; + * // Connect using MongoClient + * const mongoClient = new MongoClient(url); + * mongoClient.connect(function(err, client) { + * const db = client.db(dbName); + * client.close(); + * }); + * ``` * * @example - * var MongoClient = require('mongodb').MongoClient, - * test = require('assert'); + * ```js + * // Connect using the MongoClient.connect static method + * const MongoClient = require('mongodb').MongoClient; + * const test = require('assert'); * // Connection url - * var url = 'mongodb://localhost:27017/test'; + * const url = 'mongodb://localhost:27017'; + * // Database Name + * const dbName = 'test'; * // Connect using MongoClient - * MongoClient.connect(url, function(err, db) { - * // Get an additional db - * db.close(); + * MongoClient.connect(url, function(err, client) { + * const db = client.db(dbName); + * client.close(); * }); + * ``` */ -var validOptionNames = ['poolSize', 'ssl', 'sslValidate', 'sslCA', 'sslCert', - 'sslKey', 'sslPass', 'sslCRL', 'autoReconnect', 'noDelay', 'keepAlive', 'connectTimeoutMS', 'family', - 'socketTimeoutMS', 'reconnectTries', 'reconnectInterval', 'ha', 'haInterval', - 'replicaSet', 'secondaryAcceptableLatencyMS', 'acceptableLatencyMS', - 'connectWithNoPrimary', 'authSource', 'w', 'wtimeout', 'j', 'forceServerObjectId', - 'serializeFunctions', 'ignoreUndefined', 'raw', 'bufferMaxEntries', - 'readPreference', 'pkFactory', 'promiseLibrary', 'readConcern', 'maxStalenessSeconds', - 'loggerLevel', 'logger', 'promoteValues', 'promoteBuffers', 'promoteLongs', - 'domainsEnabled', 'keepAliveInitialDelay', 'checkServerIdentity', 'validateOptions', 'appname', 'auth']; -var ignoreOptionNames = ['native_parser']; -var legacyOptionNames = ['server', 'replset', 'replSet', 'mongos', 'db']; - -function validOptions(options) { - var _validOptions = validOptionNames.concat(legacyOptionNames); - - for(var name in options) { - if(ignoreOptionNames.indexOf(name) != -1) { - continue; +class MongoClient extends mongo_types_1.TypedEventEmitter { + constructor(url, options) { + super(); + this[kOptions] = (0, connection_string_1.parseOptions)(url, this, options); + // eslint-disable-next-line @typescript-eslint/no-this-alias + const client = this; + // The internal state + this.s = { + url, + bsonOptions: (0, bson_1.resolveBSONOptions)(this[kOptions]), + namespace: (0, utils_1.ns)('admin'), + hasBeenClosed: false, + sessionPool: new sessions_1.ServerSessionPool(this), + activeSessions: new Set(), + get options() { + return client[kOptions]; + }, + get readConcern() { + return client[kOptions].readConcern; + }, + get writeConcern() { + return client[kOptions].writeConcern; + }, + get readPreference() { + return client[kOptions].readPreference; + }, + get logger() { + return client[kOptions].logger; + }, + get isMongoClient() { + return true; + } + }; } - - if(_validOptions.indexOf(name) == -1 && options.validateOptions) { - return new MongoError(f('option %s is not supported', name)); - } else if(_validOptions.indexOf(name) == -1) { - console.warn(f('the options [%s] is not supported', name)); + get options() { + return Object.freeze({ ...this[kOptions] }); } - - if(legacyOptionNames.indexOf(name) != -1) { - console.warn(f('the server/replset/mongos options are deprecated, ' - + 'all their options are supported at the top level of the options object [%s]', validOptionNames)); + get serverApi() { + return this[kOptions].serverApi && Object.freeze({ ...this[kOptions].serverApi }); } - } -} - -/** - * Creates a new MongoClient instance - * @class - * @return {MongoClient} a MongoClient instance. - */ -function MongoClient() { - if(!(this instanceof MongoClient)) return new MongoClient(); - - // Set up event emitter - EventEmitter.call(this); - - /** - * The callback format for results - * @callback MongoClient~connectCallback - * @param {MongoError} error An error instance representing the error during the execution. - * @param {Db} db The connected database. - */ - - /** - * Connect to MongoDB using a url as documented at - * - * docs.mongodb.org/manual/reference/connection-string/ - * - * Note that for replicasets the replicaSet query parameter is required in the 2.0 driver - * - * @method - * @param {string} url The connection URI string - * @param {object} [options] Optional settings. - * @param {number} [options.poolSize=5] poolSize The maximum size of the individual server pool. - * @param {boolean} [options.ssl=false] Enable SSL connection. - * @param {Buffer} [options.sslCA=undefined] SSL Certificate store binary buffer - * @param {Buffer} [options.sslCRL=undefined] SSL Certificate revocation list binary buffer - * @param {Buffer} [options.sslCert=undefined] SSL Certificate binary buffer - * @param {Buffer} [options.sslKey=undefined] SSL Key file binary buffer - * @param {string} [options.sslPass=undefined] SSL Certificate pass phrase - * @param {boolean|function} [options.checkServerIdentity=true] Ensure we check server identify during SSL, set to false to disable checking. Only works for Node 0.12.x or higher. You can pass in a boolean or your own checkServerIdentity override function. - * @param {boolean} [options.autoReconnect=true] Enable autoReconnect for single server instances - * @param {boolean} [options.noDelay=true] TCP Connection no delay - * @param {number} [options.family=4] Version of IP stack. Defaults to 4. - * @param {boolean} [options.keepAlive=30000] The number of milliseconds to wait before initiating keepAlive on the TCP socket. - * @param {number} [options.connectTimeoutMS=30000] TCP Connection timeout setting - * @param {number} [options.socketTimeoutMS=360000] TCP Socket timeout setting - * @param {number} [options.reconnectTries=30] Server attempt to reconnect #times - * @param {number} [options.reconnectInterval=1000] Server will wait # milliseconds between retries - * @param {boolean} [options.ha=true] Control if high availability monitoring runs for Replicaset or Mongos proxies. - * @param {number} [options.haInterval=10000] The High availability period for replicaset inquiry - * @param {string} [options.replicaSet=undefined] The Replicaset set name - * @param {number} [options.secondaryAcceptableLatencyMS=15] Cutoff latency point in MS for Replicaset member selection - * @param {number} [options.acceptableLatencyMS=15] Cutoff latency point in MS for Mongos proxies selection. - * @param {boolean} [options.connectWithNoPrimary=false] Sets if the driver should connect even if no primary is available - * @param {string} [options.authSource=undefined] Define the database to authenticate against - * @param {string} [options.auth.user=undefined] The username for auth - * @param {string} [options.auth.password=undefined] The password for auth - * @param {(number|string)} [options.w=null] The write concern. - * @param {number} [options.wtimeout=null] The write concern timeout. - * @param {boolean} [options.j=false] Specify a journal write concern. - * @param {boolean} [options.forceServerObjectId=false] Force server to assign _id values instead of driver. - * @param {boolean} [options.serializeFunctions=false] Serialize functions on any object. - * @param {Boolean} [options.ignoreUndefined=false] Specify if the BSON serializer should ignore undefined fields. - * @param {boolean} [options.raw=false] Return document results as raw BSON buffers. - * @param {boolean} [options.promoteLongs=true] Promotes Long values to number if they fit inside the 53 bits resolution. - * @param {boolean} [options.promoteBuffers=false] Promotes Binary BSON values to native Node Buffers. - * @param {boolean} [options.promoteValues=true] Promotes BSON values to native types where possible, set to false to only receive wrapper types. - * @param {number} [options.bufferMaxEntries=-1] Sets a cap on how many operations the driver will buffer up before giving up on getting a working connection, default is -1 which is unlimited. - * @param {(ReadPreference|string)} [options.readPreference=null] The preferred read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST). - * @param {boolean} [options.domainsEnabled=false] Enable the wrapping of the callback in the current entity, disabled by default to avoid perf hit. - * @param {object} [options.pkFactory=null] A primary key factory object for generation of custom _id keys. - * @param {object} [options.promiseLibrary=null] A Promise library class the application wishes to use such as Bluebird, must be ES6 compatible - * @param {object} [options.readConcern=null] Specify a read concern for the collection. (only MongoDB 3.2 or higher supported) - * @param {string} [options.readConcern.level='local'] Specify a read concern level for the collection operations, one of [local|majority]. (only MongoDB 3.2 or higher supported) - * @param {number} [options.maxStalenessSeconds=undefined] The max staleness to secondary reads (values under 10 seconds cannot be guaranteed); - * @param {string} [options.appname=undefined] The name of the application that created this MongoClient instance. MongoDB 3.4 and newer will print this value in the server log upon establishing each connection. It is also recorded in the slow query log and profile collections. - * @param {string} [options.loggerLevel=undefined] The logging level (error/warn/info/debug) - * @param {object} [options.logger=undefined] Custom logger object - * @param {object} [options.validateOptions=false] Validate MongoClient passed in options for correctness. - * @param {MongoClient~connectCallback} [callback] The command result callback - * @return {Promise} returns Promise if no callback passed - */ - this.connect = MongoClient.connect; -} - -/** - * @ignore - */ -inherits(MongoClient, EventEmitter); - -var define = MongoClient.define = new Define('MongoClient', MongoClient, false); - -/** - * Connect to MongoDB using a url as documented at - * - * docs.mongodb.org/manual/reference/connection-string/ - * - * Note that for replicasets the replicaSet query parameter is required in the 2.0 driver - * - * @method - * @static - * @param {string} url The connection URI string - * @param {object} [options] Optional settings. - * @param {number} [options.poolSize=5] poolSize The maximum size of the individual server pool. - * @param {boolean} [options.ssl=false] Enable SSL connection. - * @param {Buffer} [options.sslCA=undefined] SSL Certificate store binary buffer - * @param {Buffer} [options.sslCRL=undefined] SSL Certificate revocation list binary buffer - * @param {Buffer} [options.sslCert=undefined] SSL Certificate binary buffer - * @param {Buffer} [options.sslKey=undefined] SSL Key file binary buffer - * @param {string} [options.sslPass=undefined] SSL Certificate pass phrase - * @param {boolean|function} [options.checkServerIdentity=true] Ensure we check server identify during SSL, set to false to disable checking. Only works for Node 0.12.x or higher. You can pass in a boolean or your own checkServerIdentity override function. - * @param {boolean} [options.autoReconnect=true] Enable autoReconnect for single server instances - * @param {boolean} [options.noDelay=true] TCP Connection no delay - * @param {number} [options.family=4] Version of IP stack. Defaults to 4. - * @param {boolean} [options.keepAlive=30000] The number of milliseconds to wait before initiating keepAlive on the TCP socket. - * @param {number} [options.connectTimeoutMS=30000] TCP Connection timeout setting - * @param {number} [options.socketTimeoutMS=360000] TCP Socket timeout setting - * @param {number} [options.reconnectTries=30] Server attempt to reconnect #times - * @param {number} [options.reconnectInterval=1000] Server will wait # milliseconds between retries - * @param {boolean} [options.ha=true] Control if high availability monitoring runs for Replicaset or Mongos proxies. - * @param {number} [options.haInterval=10000] The High availability period for replicaset inquiry - * @param {string} [options.replicaSet=undefined] The Replicaset set name - * @param {number} [options.secondaryAcceptableLatencyMS=15] Cutoff latency point in MS for Replicaset member selection - * @param {number} [options.acceptableLatencyMS=15] Cutoff latency point in MS for Mongos proxies selection. - * @param {boolean} [options.connectWithNoPrimary=false] Sets if the driver should connect even if no primary is available - * @param {string} [options.authSource=undefined] Define the database to authenticate against - * @param {string} [options.auth.user=undefined] The username for auth - * @param {string} [options.auth.password=undefined] The password for auth - * @param {(number|string)} [options.w=null] The write concern. - * @param {number} [options.wtimeout=null] The write concern timeout. - * @param {boolean} [options.j=false] Specify a journal write concern. - * @param {boolean} [options.forceServerObjectId=false] Force server to assign _id values instead of driver. - * @param {boolean} [options.serializeFunctions=false] Serialize functions on any object. - * @param {Boolean} [options.ignoreUndefined=false] Specify if the BSON serializer should ignore undefined fields. - * @param {boolean} [options.raw=false] Return document results as raw BSON buffers. - * @param {boolean} [options.promoteLongs=true] Promotes Long values to number if they fit inside the 53 bits resolution. - * @param {boolean} [options.promoteBuffers=false] Promotes Binary BSON values to native Node Buffers. - * @param {boolean} [options.promoteValues=true] Promotes BSON values to native types where possible, set to false to only receive wrapper types. - * @param {number} [options.bufferMaxEntries=-1] Sets a cap on how many operations the driver will buffer up before giving up on getting a working connection, default is -1 which is unlimited. - * @param {(ReadPreference|string)} [options.readPreference=null] The preferred read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST). - * @param {boolean} [options.domainsEnabled=false] Enable the wrapping of the callback in the current entity, disabled by default to avoid perf hit. - * @param {object} [options.pkFactory=null] A primary key factory object for generation of custom _id keys. - * @param {object} [options.promiseLibrary=null] A Promise library class the application wishes to use such as Bluebird, must be ES6 compatible - * @param {object} [options.readConcern=null] Specify a read concern for the collection. (only MongoDB 3.2 or higher supported) - * @param {string} [options.readConcern.level='local'] Specify a read concern level for the collection operations, one of [local|majority]. (only MongoDB 3.2 or higher supported) - * @param {number} [options.maxStalenessSeconds=undefined] The max staleness to secondary reads (values under 10 seconds cannot be guaranteed); - * @param {string} [options.appname=undefined] The name of the application that created this MongoClient instance. MongoDB 3.4 and newer will print this value in the server log upon establishing each connection. It is also recorded in the slow query log and profile collections. - * @param {string} [options.loggerLevel=undefined] The logging level (error/warn/info/debug) - * @param {object} [options.logger=undefined] Custom logger object - * @param {object} [options.validateOptions=false] Validate MongoClient passed in options for correctness. - * @param {MongoClient~connectCallback} [callback] The command result callback - * @return {Promise} returns Promise if no callback passed - */ -MongoClient.connect = function(url, options, callback) { - var args = Array.prototype.slice.call(arguments, 1); - callback = typeof args[args.length - 1] == 'function' ? args.pop() : null; - options = args.length ? args.shift() : null; - options = options || {}; - var self = this; - - // Validate options object - var err = validOptions(options); - - // Get the promiseLibrary - var promiseLibrary = options.promiseLibrary; - - // No promise library selected fall back - if(!promiseLibrary) { - promiseLibrary = typeof global.Promise == 'function' ? - global.Promise : require('es6-promise').Promise; - } - - // Return a promise - if(typeof callback != 'function') { - return new promiseLibrary(function(resolve, reject) { - // Did we have a validation error - if(err) return reject(err); - // Attempt to connect - connect(self, url, options, function(err, db) { - if(err) return reject(err); - resolve(db); - }); - }); - } - - // Did we have a validation error - if(err) return callback(err); - // Fallback to callback based connect - connect(self, url, options, callback); -} - -define.staticMethod('connect', {callback: true, promise:true}); - -var mergeOptions = function(target, source, flatten) { - for(var name in source) { - if(source[name] && typeof source[name] == 'object' && flatten) { - target = mergeOptions(target, source[name], flatten); - } else { - target[name] = source[name]; + /** + * Intended for APM use only + * @internal + */ + get monitorCommands() { + return this[kOptions].monitorCommands; } - } - - return target; -} - -var createUnifiedOptions = function(finalOptions, options) { - var childOptions = ['mongos', 'server', 'db' - , 'replset', 'db_options', 'server_options', 'rs_options', 'mongos_options']; - var noMerge = ['readconcern']; - - for(var name in options) { - if(noMerge.indexOf(name.toLowerCase()) != -1) { - finalOptions[name] = options[name]; - } else if(childOptions.indexOf(name.toLowerCase()) != -1) { - finalOptions = mergeOptions(finalOptions, options[name], false); - } else { - if(options[name] && typeof options[name] == 'object' && !Buffer.isBuffer(options[name]) && !Array.isArray(options[name])) { - finalOptions = mergeOptions(finalOptions, options[name], true); - } else { - finalOptions[name] = options[name]; - } + set monitorCommands(value) { + this[kOptions].monitorCommands = value; } - } - - return finalOptions; -} - -function translateOptions(options) { - // If we have a readPreference passed in by the db options - if(typeof options.readPreference == 'string' || typeof options.read_preference == 'string') { - options.readPreference = new ReadPreference(options.readPreference || options.read_preference); - } - - // Do we have readPreference tags, add them - if(options.readPreference && (options.readPreferenceTags || options.read_preference_tags)) { - options.readPreference.tags = options.readPreferenceTags || options.read_preference_tags; - } - - // Do we have maxStalenessSeconds - if(options.maxStalenessSeconds) { - options.readPreference.maxStalenessSeconds = options.maxStalenessSeconds; - } - - // Set the socket and connection timeouts - if(options.socketTimeoutMS == null) options.socketTimeoutMS = 360000; - if(options.connectTimeoutMS == null) options.connectTimeoutMS = 30000; - - // Create server instances - return options.servers.map(function(serverObj) { - return serverObj.domain_socket ? - new Server(serverObj.domain_socket, 27017, options) - : new Server(serverObj.host, serverObj.port, options); - }); -} - -// -// Collect all events in order from SDAM -// -function collectEvents(self, db) { - var collectedEvents = []; - - if(self instanceof MongoClient) { - var events = ["timeout", "close", 'serverOpening', 'serverDescriptionChanged', 'serverHeartbeatStarted', - 'serverHeartbeatSucceeded', 'serverHeartbeatFailed', 'serverClosed', 'topologyOpening', - 'topologyClosed', 'topologyDescriptionChanged', 'joined', 'left', 'ping', 'ha', 'all', 'fullsetup']; - events.forEach(function(event) { - db.serverConfig.on(event, function(object1, object2) { - collectedEvents.push({ - event: event, object1: object1, object2: object2 + get autoEncrypter() { + return this[kOptions].autoEncrypter; + } + get readConcern() { + return this.s.readConcern; + } + get writeConcern() { + return this.s.writeConcern; + } + get readPreference() { + return this.s.readPreference; + } + get bsonOptions() { + return this.s.bsonOptions; + } + get logger() { + return this.s.logger; + } + connect(callback) { + if (callback && typeof callback !== 'function') { + throw new error_1.MongoInvalidArgumentError('Method `connect` only accepts a callback'); + } + return (0, utils_1.maybePromise)(callback, cb => { + (0, connect_1.connect)(this, this[kOptions], err => { + if (err) + return cb(err); + cb(undefined, this); + }); }); - }); - }); - } - - return collectedEvents; -} - -// -// Replay any events due to single server connection switching to Mongos -// -function replayEvents(self, events) { - for(var i = 0; i < events.length; i++) { - self.emit(events[i].event, events[i].object1, events[i].object2); - } -} - -function relayEvents(self, db) { - if(self instanceof MongoClient) { - var events = ["timeout", "close", 'serverOpening', 'serverDescriptionChanged', 'serverHeartbeatStarted', - 'serverHeartbeatSucceeded', 'serverHeartbeatFailed', 'serverClosed', 'topologyOpening', - 'topologyClosed', 'topologyDescriptionChanged', 'joined', 'left', 'ping', 'ha', 'all', 'fullsetup']; - events.forEach(function(event) { - db.serverConfig.on(event, function(object1, object2) { - self.emit(event, object1, object2); - }); - }); - } -} - -function createReplicaset(self, options, callback) { - // Set default options - var servers = translateOptions(options); - // Create Db instance - var db = new Db(options.dbName, new ReplSet(servers, options), options); - // Propegate the events to the client - relayEvents(self, db); - // Open the connection - db.open(callback); -} - -function createMongos(self, options, callback) { - // Set default options - var servers = translateOptions(options); - // Create Db instance - var db = new Db(options.dbName, new Mongos(servers, options), options) - // Propegate the events to the client - relayEvents(self, db); - // Open the connection - db.open(callback); -} - -function createServer(self, options, callback) { - // Set default options - var servers = translateOptions(options); - // Create db instance - var db = new Db(options.dbName, servers[0], options); - // Propegate the events to the client - var collectedEvents = collectEvents(self, db); - // Create Db instance - db.open(function(err, db) { - if(err) return callback(err); - // Check if we are really speaking to a mongos - var ismaster = db.serverConfig.lastIsMaster(); - - // Do we actually have a mongos - if(ismaster && ismaster.msg == 'isdbgrid') { - // Destroy the current connection - db.close(); - // Create mongos connection instead - return createMongos(self, options, callback); } - - // Fire all the events - replayEvents(self, collectedEvents); - // Propegate the events to the client - relayEvents(self, db); - // Otherwise callback - callback(err, db); - }); -} - -function connectHandler(options, callback) { - return function (err, db) { - if(err) { - return process.nextTick(function() { - try { - callback(err, null); - } catch (err) { - if(db) db.close(); - throw err + close(forceOrCallback, callback) { + // There's no way to set hasBeenClosed back to false + Object.defineProperty(this.s, 'hasBeenClosed', { + value: true, + enumerable: true, + configurable: false, + writable: false + }); + if (typeof forceOrCallback === 'function') { + callback = forceOrCallback; } - }); + const force = typeof forceOrCallback === 'boolean' ? forceOrCallback : false; + return (0, utils_1.maybePromise)(callback, callback => { + if (this.topology == null) { + // Do not connect just to end sessions + return callback(); + } + const activeSessionEnds = Array.from(this.s.activeSessions, session => session.endSession()); + this.s.activeSessions.clear(); + Promise.all(activeSessionEnds) + .then(() => { + const endSessions = Array.from(this.s.sessionPool.sessions, ({ id }) => id); + if (endSessions.length === 0) + return; + return this.db('admin') + .command({ endSessions }, { readPreference: read_preference_1.ReadPreference.primaryPreferred, noResponse: true }) + .catch(() => null); // outcome does not matter + }) + .then(() => { + if (this.topology == null) { + return callback(); + } + // clear out references to old topology + const topology = this.topology; + this.topology = undefined; + return new Promise((resolve, reject) => { + topology.close({ force }, error => { + if (error) + return reject(error); + const { encrypter } = this[kOptions]; + if (encrypter) { + return encrypter.close(this, force, error => { + if (error) + return reject(error); + resolve(); + }); + } + resolve(); + }); + }); + }) + .then(() => callback(), error => callback(error)); + }); } - - // No authentication just reconnect - if(!options.auth) { - return process.nextTick(function() { - try { - callback(err, db); - } catch (err) { - if(db) db.close(); - throw err + /** + * Create a new Db instance sharing the current socket connections. + * + * @param dbName - The name of the database we want to use. If not provided, use database name from connection string. + * @param options - Optional settings for Db construction + */ + db(dbName, options) { + options = options !== null && options !== void 0 ? options : {}; + // Default to db from connection string if not provided + if (!dbName) { + dbName = this.options.dbName; } - }) + // Copy the options and add out internal override of the not shared flag + const finalOptions = Object.assign({}, this[kOptions], options); + // Return the db object + const db = new db_1.Db(this, dbName, finalOptions); + // Return the database + return db; } - - // What db to authenticate against - var authentication_db = db; - if(options.authSource) { - authentication_db = db.db(options.authSource); + static connect(url, options, callback) { + if (typeof options === 'function') + (callback = options), (options = {}); + options = options !== null && options !== void 0 ? options : {}; + try { + // Create client + const mongoClient = new MongoClient(url, options); + // Execute the connect method + if (callback) { + return mongoClient.connect(callback); + } + else { + return mongoClient.connect(); + } + } + catch (error) { + if (callback) + return callback(error); + else + return promise_provider_1.PromiseProvider.get().reject(error); + } } - - // Authenticate - authenticate(authentication_db, options.user, options.password, options, function(err, success) { - if(success){ - process.nextTick(function() { - try { - callback(null, db); - } catch (err) { - if(db) db.close(); - throw err - } + startSession(options) { + const session = new sessions_1.ClientSession(this, this.s.sessionPool, { explicit: true, ...options }, this[kOptions]); + this.s.activeSessions.add(session); + session.once('ended', () => { + this.s.activeSessions.delete(session); }); - } else { - if(db) db.close(); - process.nextTick(function() { - try { - callback(err ? err : new Error('Could not authenticate user ' + options.auth[0]), null); - } catch (err) { - if(db) db.close(); - throw err - } + return session; + } + withSession(optionsOrOperation, callback) { + const options = { + // Always define an owner + owner: Symbol(), + // If it's an object inherit the options + ...(typeof optionsOrOperation === 'object' ? optionsOrOperation : {}) + }; + const withSessionCallback = typeof optionsOrOperation === 'function' ? optionsOrOperation : callback; + if (withSessionCallback == null) { + throw new error_1.MongoInvalidArgumentError('Missing required callback parameter'); + } + const session = this.startSession(options); + const Promise = promise_provider_1.PromiseProvider.get(); + return Promise.resolve() + .then(() => withSessionCallback(session)) + .then(() => { + // Do not return the result of callback + }) + .finally(() => { + session.endSession().catch(() => null); }); - } - }); - } -} - -/* - * Connect using MongoClient - */ -var connect = function(self, url, options, callback) { - options = options || {}; - options = shallowClone(options); - - // If callback is null throw an exception - if(callback == null) { - throw new Error("no callback function provided"); - } - - // Get a logger for MongoClient - var logger = Logger('MongoClient', options); - - // Parse the string - var object = parse(url, options); - var _finalOptions = createUnifiedOptions({}, object); - _finalOptions = mergeOptions(_finalOptions, object, false); - _finalOptions = createUnifiedOptions(_finalOptions, options); - - // Check if we have connection and socket timeout set - if(_finalOptions.socketTimeoutMS == null) _finalOptions.socketTimeoutMS = 360000; - if(_finalOptions.connectTimeoutMS == null) _finalOptions.connectTimeoutMS = 30000; - - if (_finalOptions.db_options && _finalOptions.db_options.auth) { - delete _finalOptions.db_options.auth; - } - - // Failure modes - if(object.servers.length == 0) { - throw new Error("connection string must contain at least one seed host"); - } - - function connectCallback(err, db) { - if(err && err.message == 'no mongos proxies found in seed list') { - if(logger.isWarn()) { - logger.warn(f('seed list contains no mongos proxies, replicaset connections requires the parameter replicaSet to be supplied in the URI or options object, mongodb://server:port/db?replicaSet=name')); - } - - // Return a more specific error message for MongoClient.connect - return callback(new MongoError('seed list contains no mongos proxies, replicaset connections requires the parameter replicaSet to be supplied in the URI or options object, mongodb://server:port/db?replicaSet=name')); } - - // Return the error and db instance - callback(err, db); - } - - // Do we have a replicaset then skip discovery and go straight to connectivity - if(_finalOptions.replicaSet || _finalOptions.rs_name) { - return createReplicaset(self, _finalOptions, connectHandler(_finalOptions, connectCallback)); - } else if(object.servers.length > 1) { - return createMongos(self, _finalOptions, connectHandler(_finalOptions, connectCallback)); - } else { - return createServer(self, _finalOptions, connectHandler(_finalOptions, connectCallback)); - } + /** + * Create a new Change Stream, watching for new changes (insertions, updates, + * replacements, deletions, and invalidations) in this cluster. Will ignore all + * changes to system collections, as well as the local, admin, and config databases. + * + * @remarks + * watch() accepts two generic arguments for distinct usecases: + * - The first is to provide the schema that may be defined for all the data within the current cluster + * - The second is to override the shape of the change stream document entirely, if it is not provided the type will default to ChangeStreamDocument of the first argument + * + * @param pipeline - An array of {@link https://docs.mongodb.com/manual/reference/operator/aggregation-pipeline/|aggregation pipeline stages} through which to pass change stream documents. This allows for filtering (using $match) and manipulating the change stream documents. + * @param options - Optional settings for the command + * @typeParam TSchema - Type of the data being detected by the change stream + * @typeParam TChange - Type of the whole change stream document emitted + */ + watch(pipeline = [], options = {}) { + // Allow optionally not specifying a pipeline + if (!Array.isArray(pipeline)) { + options = pipeline; + pipeline = []; + } + return new change_stream_1.ChangeStream(this, pipeline, (0, utils_1.resolveOptions)(this, options)); + } + /** Return the mongo client logger */ + getLogger() { + return this.s.logger; + } } - -module.exports = MongoClient +exports.MongoClient = MongoClient; +//# sourceMappingURL=mongo_client.js.map \ No newline at end of file diff --git a/ts-ticket-office-service/node_modules/mongodb/lib/mongo_client.js.map b/ts-ticket-office-service/node_modules/mongodb/lib/mongo_client.js.map new file mode 100644 index 000000000..66eb805c6 --- /dev/null +++ b/ts-ticket-office-service/node_modules/mongodb/lib/mongo_client.js.map @@ -0,0 +1 @@ +{"version":3,"file":"mongo_client.js","sourceRoot":"","sources":["../src/mongo_client.ts"],"names":[],"mappings":";;;AAGA,iCAA4E;AAC5E,mDAA0F;AAM1F,2DAAmD;AAEnD,6BAAqC;AAGrC,mCAAoD;AAEpD,+CAAkD;AAClD,kDAA+C;AAC/C,yDAAqD;AAErD,uDAAuE;AAIvE,yCAAoF;AACpF,mCAQiB;AAGjB,cAAc;AACD,QAAA,gBAAgB,GAAG,MAAM,CAAC,MAAM,CAAC;IAC5C,EAAE,EAAE,GAAG;CACC,CAAC,CAAC;AA8PZ,gBAAgB;AAChB,MAAM,QAAQ,GAAG,MAAM,CAAC,SAAS,CAAC,CAAC;AAEnC;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAuCG;AACH,MAAa,WAAY,SAAQ,+BAAoC;IAYnE,YAAY,GAAW,EAAE,OAA4B;QACnD,KAAK,EAAE,CAAC;QAER,IAAI,CAAC,QAAQ,CAAC,GAAG,IAAA,gCAAY,EAAC,GAAG,EAAE,IAAI,EAAE,OAAO,CAAC,CAAC;QAElD,4DAA4D;QAC5D,MAAM,MAAM,GAAG,IAAI,CAAC;QAEpB,qBAAqB;QACrB,IAAI,CAAC,CAAC,GAAG;YACP,GAAG;YACH,WAAW,EAAE,IAAA,yBAAkB,EAAC,IAAI,CAAC,QAAQ,CAAC,CAAC;YAC/C,SAAS,EAAE,IAAA,UAAE,EAAC,OAAO,CAAC;YACtB,aAAa,EAAE,KAAK;YACpB,WAAW,EAAE,IAAI,4BAAiB,CAAC,IAAI,CAAC;YACxC,cAAc,EAAE,IAAI,GAAG,EAAE;YAEzB,IAAI,OAAO;gBACT,OAAO,MAAM,CAAC,QAAQ,CAAC,CAAC;YAC1B,CAAC;YACD,IAAI,WAAW;gBACb,OAAO,MAAM,CAAC,QAAQ,CAAC,CAAC,WAAW,CAAC;YACtC,CA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;QAED,MAAM,OAAO,GAAG,IAAI,CAAC,YAAY,CAAC,OAAO,CAAC,CAAC;QAC3C,MAAM,OAAO,GAAG,kCAAe,CAAC,GAAG,EAAE,CAAC;QAEtC,OAAO,OAAO,CAAC,OAAO,EAAE;aACrB,IAAI,CAAC,GAAG,EAAE,CAAC,mBAAmB,CAAC,OAAO,CAAC,CAAC;aACxC,IAAI,CAAC,GAAG,EAAE;YACT,uCAAuC;QACzC,CAAC,CAAC;aACD,OAAO,CAAC,GAAG,EAAE;YACZ,OAAO,CAAC,UAAU,EAAE,CAAC,KAAK,CAAC,GAAG,EAAE,CAAC,IAAI,CAAC,CAAC;QACzC,CAAC,CAAC,CAAC;IACP,CAAC;IAED;;;;;;;;;;;;;;OAcG;IACH,KAAK,CAGH,WAAuB,EAAE,EAAE,UAA+B,EAAE;QAC5D,6CAA6C;QAC7C,IAAI,CAAC,KAAK,CAAC,OAAO,CAAC,QAAQ,CAAC,EAAE;YAC5B,OAAO,GAAG,QAAQ,CAAC;YACnB,QAAQ,GAAG,EAAE,CAAC;SACf;QAED,OAAO,IAAI,4BAAY,CAAmB,IAAI,EAAE,QAAQ,EAAE,IAAA,sBAAc,EAAC,IAAI,EAAE,OAAO,CAAC,CAAC,CAAC;IAC3F,CAAC;IAED,qCAAqC;IACrC,SAAS;QACP,OAAO,IAAI,CAAC,CAAC,CAAC,MAAM,CAAC;IACvB,CAAC;CACF;AAnVD,kCAmVC"} \ No newline at end of file diff --git a/ts-ticket-office-service/node_modules/mongodb/lib/mongo_types.js b/ts-ticket-office-service/node_modules/mongodb/lib/mongo_types.js new file mode 100644 index 000000000..7cd40483f --- /dev/null +++ b/ts-ticket-office-service/node_modules/mongodb/lib/mongo_types.js @@ -0,0 +1,41 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.CancellationToken = exports.TypedEventEmitter = exports.BSONType = void 0; +const events_1 = require("events"); +/** @public */ +exports.BSONType = Object.freeze({ + double: 1, + string: 2, + object: 3, + array: 4, + binData: 5, + undefined: 6, + objectId: 7, + bool: 8, + date: 9, + null: 10, + regex: 11, + dbPointer: 12, + javascript: 13, + symbol: 14, + javascriptWithScope: 15, + int: 16, + timestamp: 17, + long: 18, + decimal: 19, + minKey: -1, + maxKey: 127 +}); +/** + * Typescript type safe event emitter + * @public + */ +// eslint-disable-next-line @typescript-eslint/no-unused-vars +class TypedEventEmitter extends events_1.EventEmitter { +} +exports.TypedEventEmitter = TypedEventEmitter; +/** @public */ +class CancellationToken extends TypedEventEmitter { +} +exports.CancellationToken = CancellationToken; +//# sourceMappingURL=mongo_types.js.map \ No newline at end of file diff --git a/ts-ticket-office-service/node_modules/mongodb/lib/mongo_types.js.map b/ts-ticket-office-service/node_modules/mongodb/lib/mongo_types.js.map new file mode 100644 index 000000000..e1221e563 --- /dev/null +++ b/ts-ticket-office-service/node_modules/mongodb/lib/mongo_types.js.map @@ -0,0 +1 @@ +{"version":3,"file":"mongo_types.js","sourceRoot":"","sources":["../src/mongo_types.ts"],"names":[],"mappings":";;;AACA,mCAAsC;AAmKtC,cAAc;AACD,QAAA,QAAQ,GAAG,MAAM,CAAC,MAAM,CAAC;IACpC,MAAM,EAAE,CAAC;IACT,MAAM,EAAE,CAAC;IACT,MAAM,EAAE,CAAC;IACT,KAAK,EAAE,CAAC;IACR,OAAO,EAAE,CAAC;IACV,SAAS,EAAE,CAAC;IACZ,QAAQ,EAAE,CAAC;IACX,IAAI,EAAE,CAAC;IACP,IAAI,EAAE,CAAC;IACP,IAAI,EAAE,EAAE;IACR,KAAK,EAAE,EAAE;IACT,SAAS,EAAE,EAAE;IACb,UAAU,EAAE,EAAE;IACd,MAAM,EAAE,EAAE;IACV,mBAAmB,EAAE,EAAE;IACvB,GAAG,EAAE,EAAE;IACP,SAAS,EAAE,EAAE;IACb,IAAI,EAAE,EAAE;IACR,OAAO,EAAE,EAAE;IACX,MAAM,EAAE,CAAC,CAAC;IACV,MAAM,EAAE,GAAG;CACH,CAAC,CAAC;AAyQZ;;;GAGG;AACH,6DAA6D;AAC7D,MAAa,iBAAoD,SAAQ,qBAAY;CAAG;AAAxF,8CAAwF;AAExF,cAAc;AACd,MAAa,iBAAkB,SAAQ,iBAAqC;CAAG;AAA/E,8CAA+E"} \ No newline at end of file diff --git a/ts-ticket-office-service/node_modules/mongodb/lib/mongos.js b/ts-ticket-office-service/node_modules/mongodb/lib/mongos.js deleted file mode 100644 index e3631fabb..000000000 --- a/ts-ticket-office-service/node_modules/mongodb/lib/mongos.js +++ /dev/null @@ -1,533 +0,0 @@ -"use strict"; - -var EventEmitter = require('events').EventEmitter - , inherits = require('util').inherits - , f = require('util').format - , ServerCapabilities = require('./topology_base').ServerCapabilities - , MongoError = require('mongodb-core').MongoError - , CMongos = require('mongodb-core').Mongos - , Cursor = require('./cursor') - , AggregationCursor = require('./aggregation_cursor') - , CommandCursor = require('./command_cursor') - , Define = require('./metadata') - , Server = require('./server') - , Store = require('./topology_base').Store - , MAX_JS_INT = require('./utils').MAX_JS_INT - , translateOptions = require('./utils').translateOptions - , filterOptions = require('./utils').filterOptions - , mergeOptions = require('./utils').mergeOptions - , getReadPreference = require('./utils').getReadPreference - , os = require('os'); - -// Get package.json variable -var driverVersion = require('../package.json').version; -var nodejsversion = f('Node.js %s, %s', process.version, os.endianness()); -var type = os.type(); -var name = process.platform; -var architecture = process.arch; -var release = os.release(); - -/** - * @fileOverview The **Mongos** class is a class that represents a Mongos Proxy topology and is - * used to construct connections. - * - * **Mongos Should not be used, use MongoClient.connect** - * @example - * var Db = require('mongodb').Db, - * Mongos = require('mongodb').Mongos, - * Server = require('mongodb').Server, - * test = require('assert'); - * // Connect using Mongos - * var server = new Server('localhost', 27017); - * var db = new Db('test', new Mongos([server])); - * db.open(function(err, db) { - * // Get an additional db - * db.close(); - * }); - */ - - // Allowed parameters - var legalOptionNames = ['ha', 'haInterval', 'acceptableLatencyMS' - , 'poolSize', 'ssl', 'checkServerIdentity', 'sslValidate' - , 'sslCA', 'sslCRL', 'sslCert', 'sslKey', 'sslPass', 'socketOptions', 'bufferMaxEntries' - , 'store', 'auto_reconnect', 'autoReconnect', 'emitError' - , 'keepAlive', 'noDelay', 'connectTimeoutMS', 'socketTimeoutMS' - , 'loggerLevel', 'logger', 'reconnectTries', 'appname', 'domainsEnabled' - , 'servername', 'promoteLongs', 'promoteValues', 'promoteBuffers']; - -/** - * Creates a new Mongos instance - * @class - * @deprecated - * @param {Server[]} servers A seedlist of servers participating in the replicaset. - * @param {object} [options=null] Optional settings. - * @param {booelan} [options.ha=true] Turn on high availability monitoring. - * @param {number} [options.haInterval=5000] Time between each replicaset status check. - * @param {number} [options.poolSize=5] Number of connections in the connection pool for each server instance, set to 5 as default for legacy reasons. - * @param {number} [options.acceptableLatencyMS=15] Cutoff latency point in MS for MongoS proxy selection - * @param {boolean} [options.ssl=false] Use ssl connection (needs to have a mongod server with ssl support) - * @param {boolean|function} [options.checkServerIdentity=true] Ensure we check server identify during SSL, set to false to disable checking. Only works for Node 0.12.x or higher. You can pass in a boolean or your own checkServerIdentity override function. - * @param {object} [options.sslValidate=true] Validate mongod server certificate against ca (needs to have a mongod server with ssl support, 2.4 or higher) - * @param {array} [options.sslCA=null] Array of valid certificates either as Buffers or Strings (needs to have a mongod server with ssl support, 2.4 or higher) - * @param {array} [options.sslCRL=null] Array of revocation certificates either as Buffers or Strings (needs to have a mongod server with ssl support, 2.4 or higher) - * @param {(Buffer|string)} [options.sslCert=null] String or buffer containing the certificate we wish to present (needs to have a mongod server with ssl support, 2.4 or higher) - * @param {(Buffer|string)} [options.sslKey=null] String or buffer containing the certificate private key we wish to present (needs to have a mongod server with ssl support, 2.4 or higher) - * @param {(Buffer|string)} [options.sslPass=null] String or buffer containing the certificate password (needs to have a mongod server with ssl support, 2.4 or higher) - * @param {string} [options.servername=null] String containing the server name requested via TLS SNI. - * @param {object} [options.socketOptions=null] Socket options - * @param {boolean} [options.socketOptions.noDelay=true] TCP Socket NoDelay option. - * @param {number} [options.socketOptions.keepAlive=0] TCP KeepAlive on the socket with a X ms delay before start. - * @param {number} [options.socketOptions.connectTimeoutMS=0] TCP Connection timeout setting - * @param {number} [options.socketOptions.socketTimeoutMS=0] TCP Socket timeout setting - * @param {boolean} [options.domainsEnabled=false] Enable the wrapping of the callback in the current entity, disabled by default to avoid perf hit. - * @fires Mongos#connect - * @fires Mongos#ha - * @fires Mongos#joined - * @fires Mongos#left - * @fires Mongos#fullsetup - * @fires Mongos#open - * @fires Mongos#close - * @fires Mongos#error - * @fires Mongos#timeout - * @fires Mongos#parseError - * @property {string} parserType the parser type used (c++ or js). - * @return {Mongos} a Mongos instance. - */ -var Mongos = function(servers, options) { - if(!(this instanceof Mongos)) return new Mongos(servers, options); - options = options || {}; - var self = this; - - // Filter the options - options = filterOptions(options, legalOptionNames); - - // Ensure all the instances are Server - for(var i = 0; i < servers.length; i++) { - if(!(servers[i] instanceof Server)) { - throw MongoError.create({message: "all seed list instances must be of the Server type", driver:true}); - } - } - - // Stored options - var storeOptions = { - force: false - , bufferMaxEntries: typeof options.bufferMaxEntries == 'number' ? options.bufferMaxEntries : MAX_JS_INT - } - - // Shared global store - var store = options.store || new Store(self, storeOptions); - - // Set up event emitter - EventEmitter.call(this); - - // Build seed list - var seedlist = servers.map(function(x) { - return {host: x.host, port: x.port} - }); - - // Get the reconnect option - var reconnect = typeof options.auto_reconnect == 'boolean' ? options.auto_reconnect : true; - reconnect = typeof options.autoReconnect == 'boolean' ? options.autoReconnect : reconnect; - - // Clone options - var clonedOptions = mergeOptions({}, { - disconnectHandler: store, - cursorFactory: Cursor, - reconnect: reconnect, - emitError: typeof options.emitError == 'boolean' ? options.emitError : true, - size: typeof options.poolSize == 'number' ? options.poolSize : 5 - }); - - // Translate any SSL options and other connectivity options - clonedOptions = translateOptions(clonedOptions, options); - - // Socket options - var socketOptions = options.socketOptions && Object.keys(options.socketOptions).length > 0 - ? options.socketOptions : options; - - // Translate all the options to the mongodb-core ones - clonedOptions = translateOptions(clonedOptions, socketOptions); - if(typeof clonedOptions.keepAlive == 'number') { - clonedOptions.keepAliveInitialDelay = clonedOptions.keepAlive; - clonedOptions.keepAlive = clonedOptions.keepAlive > 0; - } - - // Build default client information - this.clientInfo = { - driver: { - name: "nodejs", - version: driverVersion - }, - os: { - type: type, - name: name, - architecture: architecture, - version: release - }, - platform: nodejsversion - } - - // Build default client information - clonedOptions.clientInfo = this.clientInfo; - // Do we have an application specific string - if(options.appname) { - clonedOptions.clientInfo.application = { name: options.appname }; - } - - // Create the Mongos - var mongos = new CMongos(seedlist, clonedOptions) - // Server capabilities - var sCapabilities = null; - - // Internal state - this.s = { - // Create the Mongos - mongos: mongos - // Server capabilities - , sCapabilities: sCapabilities - // Debug turned on - , debug: clonedOptions.debug - // Store option defaults - , storeOptions: storeOptions - // Cloned options - , clonedOptions: clonedOptions - // Actual store of callbacks - , store: store - // Options - , options: options - } -} - -var define = Mongos.define = new Define('Mongos', Mongos, false); - -/** - * @ignore - */ -inherits(Mongos, EventEmitter); - -// Last ismaster -Object.defineProperty(Mongos.prototype, 'isMasterDoc', { - enumerable:true, get: function() { return this.s.mongos.lastIsMaster(); } -}); - -Object.defineProperty(Mongos.prototype, 'parserType', { - enumerable:true, get: function() { - return this.s.mongos.parserType; - } -}); - -// BSON property -Object.defineProperty(Mongos.prototype, 'bson', { - enumerable: true, get: function() { - return this.s.mongos.s.bson; - } -}); - -Object.defineProperty(Mongos.prototype, 'haInterval', { - enumerable:true, get: function() { return this.s.mongos.s.haInterval; } -}); - -// Connect -Mongos.prototype.connect = function(db, _options, callback) { - var self = this; - if('function' === typeof _options) callback = _options, _options = {}; - if(_options == null) _options = {}; - if(!('function' === typeof callback)) callback = null; - self.s.options = _options; - - // Update bufferMaxEntries - self.s.storeOptions.bufferMaxEntries = db.bufferMaxEntries; - - // Error handler - var connectErrorHandler = function() { - return function(err) { - // Remove all event handlers - var events = ['timeout', 'error', 'close']; - events.forEach(function(e) { - self.removeListener(e, connectErrorHandler); - }); - - self.s.mongos.removeListener('connect', connectErrorHandler); - - // Try to callback - try { - callback(err); - } catch(err) { - process.nextTick(function() { throw err; }) - } - } - } - - // Actual handler - var errorHandler = function(event) { - return function(err) { - if(event != 'error') { - self.emit(event, err); - } - } - } - - // Error handler - var reconnectHandler = function() { - self.emit('reconnect'); - self.s.store.execute(); - } - - // relay the event - var relay = function(event) { - return function(t, server) { - self.emit(event, t, server); - } - } - - // Connect handler - var connectHandler = function() { - // Clear out all the current handlers left over - var events = ["timeout", "error", "close", 'fullsetup']; - events.forEach(function(e) { - self.s.mongos.removeAllListeners(e); - }); - - // Set up listeners - self.s.mongos.once('timeout', errorHandler('timeout')); - self.s.mongos.once('error', errorHandler('error')); - self.s.mongos.once('close', errorHandler('close')); - - // Set up serverConfig listeners - self.s.mongos.on('fullsetup', function() { self.emit('fullsetup', self); }); - - // Emit open event - self.emit('open', null, self); - - // Return correctly - try { - callback(null, self); - } catch(err) { - process.nextTick(function() { throw err; }) - } - } - - // Clear out all the current handlers left over - var events = ["timeout", "error", "close", 'serverOpening', 'serverDescriptionChanged', 'serverHeartbeatStarted', - 'serverHeartbeatSucceeded', 'serverHeartbeatFailed', 'serverClosed', 'topologyOpening', - 'topologyClosed', 'topologyDescriptionChanged']; - events.forEach(function(e) { - self.s.mongos.removeAllListeners(e); - }); - - // Set up SDAM listeners - self.s.mongos.on('serverDescriptionChanged', relay('serverDescriptionChanged')); - self.s.mongos.on('serverHeartbeatStarted', relay('serverHeartbeatStarted')); - self.s.mongos.on('serverHeartbeatSucceeded', relay('serverHeartbeatSucceeded')); - self.s.mongos.on('serverHeartbeatFailed', relay('serverHeartbeatFailed')); - self.s.mongos.on('serverOpening', relay('serverOpening')); - self.s.mongos.on('serverClosed', relay('serverClosed')); - self.s.mongos.on('topologyOpening', relay('topologyOpening')); - self.s.mongos.on('topologyClosed', relay('topologyClosed')); - self.s.mongos.on('topologyDescriptionChanged', relay('topologyDescriptionChanged')); - - // Set up listeners - self.s.mongos.once('timeout', connectErrorHandler('timeout')); - self.s.mongos.once('error', connectErrorHandler('error')); - self.s.mongos.once('close', connectErrorHandler('close')); - self.s.mongos.once('connect', connectHandler); - // Join and leave events - self.s.mongos.on('joined', relay('joined')); - self.s.mongos.on('left', relay('left')); - - // Reconnect server - self.s.mongos.on('reconnect', reconnectHandler); - - // Start connection - self.s.mongos.connect(_options); -} - -// Server capabilities -Mongos.prototype.capabilities = function() { - if(this.s.sCapabilities) return this.s.sCapabilities; - if(this.s.mongos.lastIsMaster() == null) return null; - this.s.sCapabilities = new ServerCapabilities(this.s.mongos.lastIsMaster()); - return this.s.sCapabilities; -} - -define.classMethod('capabilities', {callback: false, promise:false, returns: [ServerCapabilities]}); - -// Command -Mongos.prototype.command = function(ns, cmd, options, callback) { - this.s.mongos.command(ns, cmd, getReadPreference(options), callback); -} - -define.classMethod('command', {callback: true, promise:false}); - -// Insert -Mongos.prototype.insert = function(ns, ops, options, callback) { - this.s.mongos.insert(ns, ops, options, function(e, m) { - callback(e, m) - }); -} - -define.classMethod('insert', {callback: true, promise:false}); - -// Update -Mongos.prototype.update = function(ns, ops, options, callback) { - this.s.mongos.update(ns, ops, options, callback); -} - -define.classMethod('update', {callback: true, promise:false}); - -// Remove -Mongos.prototype.remove = function(ns, ops, options, callback) { - this.s.mongos.remove(ns, ops, options, callback); -} - -define.classMethod('remove', {callback: true, promise:false}); - -// Destroyed -Mongos.prototype.isDestroyed = function() { - return this.s.mongos.isDestroyed(); -} - -// IsConnected -Mongos.prototype.isConnected = function() { - return this.s.mongos.isConnected(); -} - -define.classMethod('isConnected', {callback: false, promise:false, returns: [Boolean]}); - -// Insert -Mongos.prototype.cursor = function(ns, cmd, options) { - options.disconnectHandler = this.s.store; - return this.s.mongos.cursor(ns, cmd, options); -} - -define.classMethod('cursor', {callback: false, promise:false, returns: [Cursor, AggregationCursor, CommandCursor]}); - -Mongos.prototype.lastIsMaster = function() { - return this.s.mongos.lastIsMaster(); -} - -/** - * Unref all sockets - * @method - */ -Mongos.prototype.unref = function () { - return this.s.mongos.unref(); -} - -Mongos.prototype.close = function(forceClosed) { - this.s.mongos.destroy({ - force: typeof forceClosed == 'boolean' ? forceClosed : false, - }); - // We need to wash out all stored processes - if(forceClosed == true) { - this.s.storeOptions.force = forceClosed; - this.s.store.flush(); - } -} - -define.classMethod('close', {callback: false, promise:false}); - -Mongos.prototype.auth = function() { - var args = Array.prototype.slice.call(arguments, 0); - this.s.mongos.auth.apply(this.s.mongos, args); -} - -define.classMethod('auth', {callback: true, promise:false}); - -Mongos.prototype.logout = function() { - var args = Array.prototype.slice.call(arguments, 0); - this.s.mongos.logout.apply(this.s.mongos, args); -} - -define.classMethod('logout', {callback: true, promise:false}); - -/** - * All raw connections - * @method - * @return {array} - */ -Mongos.prototype.connections = function() { - return this.s.mongos.connections(); -} - -define.classMethod('connections', {callback: false, promise:false, returns:[Array]}); - -/** - * A mongos connect event, used to verify that the connection is up and running - * - * @event Mongos#connect - * @type {Mongos} - */ - -/** - * The mongos high availability event - * - * @event Mongos#ha - * @type {function} - * @param {string} type The stage in the high availability event (start|end) - * @param {boolean} data.norepeat This is a repeating high availability process or a single execution only - * @param {number} data.id The id for this high availability request - * @param {object} data.state An object containing the information about the current replicaset - */ - -/** - * A server member left the mongos set - * - * @event Mongos#left - * @type {function} - * @param {string} type The type of member that left (primary|secondary|arbiter) - * @param {Server} server The server object that left - */ - -/** - * A server member joined the mongos set - * - * @event Mongos#joined - * @type {function} - * @param {string} type The type of member that joined (primary|secondary|arbiter) - * @param {Server} server The server object that joined - */ - -/** - * Mongos fullsetup event, emitted when all proxies in the topology have been connected to. - * - * @event Mongos#fullsetup - * @type {Mongos} - */ - -/** - * Mongos open event, emitted when mongos can start processing commands. - * - * @event Mongos#open - * @type {Mongos} - */ - -/** - * Mongos close event - * - * @event Mongos#close - * @type {object} - */ - -/** - * Mongos error event, emitted if there is an error listener. - * - * @event Mongos#error - * @type {MongoError} - */ - -/** - * Mongos timeout event - * - * @event Mongos#timeout - * @type {object} - */ - -/** - * Mongos parseError event - * - * @event Mongos#parseError - * @type {object} - */ - -module.exports = Mongos; diff --git a/ts-ticket-office-service/node_modules/mongodb/lib/operations/add_user.js b/ts-ticket-office-service/node_modules/mongodb/lib/operations/add_user.js new file mode 100644 index 000000000..0ef426bb3 --- /dev/null +++ b/ts-ticket-office-service/node_modules/mongodb/lib/operations/add_user.js @@ -0,0 +1,72 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.AddUserOperation = void 0; +const crypto = require("crypto"); +const error_1 = require("../error"); +const utils_1 = require("../utils"); +const command_1 = require("./command"); +const operation_1 = require("./operation"); +/** @internal */ +class AddUserOperation extends command_1.CommandOperation { + constructor(db, username, password, options) { + super(db, options); + this.db = db; + this.username = username; + this.password = password; + this.options = options !== null && options !== void 0 ? options : {}; + } + execute(server, session, callback) { + const db = this.db; + const username = this.username; + const password = this.password; + const options = this.options; + // Error out if digestPassword set + if (options.digestPassword != null) { + return callback(new error_1.MongoInvalidArgumentError('Option "digestPassword" not supported via addUser, use db.command(...) instead')); + } + let roles; + if (!options.roles || (Array.isArray(options.roles) && options.roles.length === 0)) { + (0, utils_1.emitWarningOnce)('Creating a user without roles is deprecated. Defaults to "root" if db is "admin" or "dbOwner" otherwise'); + if (db.databaseName.toLowerCase() === 'admin') { + roles = ['root']; + } + else { + roles = ['dbOwner']; + } + } + else { + roles = Array.isArray(options.roles) ? options.roles : [options.roles]; + } + let topology; + try { + topology = (0, utils_1.getTopology)(db); + } + catch (error) { + return callback(error); + } + const digestPassword = topology.lastHello().maxWireVersion >= 7; + let userPassword = password; + if (!digestPassword) { + // Use node md5 generator + const md5 = crypto.createHash('md5'); + // Generate keys used for authentication + md5.update(`${username}:mongo:${password}`); + userPassword = md5.digest('hex'); + } + // Build the command to execute + const command = { + createUser: username, + customData: options.customData || {}, + roles: roles, + digestPassword + }; + // No password + if (typeof password === 'string') { + command.pwd = userPassword; + } + super.executeCommand(server, session, command, callback); + } +} +exports.AddUserOperation = AddUserOperation; +(0, operation_1.defineAspects)(AddUserOperation, [operation_1.Aspect.WRITE_OPERATION]); +//# sourceMappingURL=add_user.js.map \ No newline at end of file diff --git a/ts-ticket-office-service/node_modules/mongodb/lib/operations/add_user.js.map b/ts-ticket-office-service/node_modules/mongodb/lib/operations/add_user.js.map new file mode 100644 index 000000000..c102b8a16 --- /dev/null +++ b/ts-ticket-office-service/node_modules/mongodb/lib/operations/add_user.js.map @@ -0,0 +1 @@ +{"version":3,"file":"add_user.js","sourceRoot":"","sources":["../../src/operations/add_user.ts"],"names":[],"mappings":";;;AAAA,iCAAiC;AAIjC,oCAAqD;AAGrD,oCAAkE;AAClE,uCAAsE;AACtE,2CAAoD;AAuBpD,gBAAgB;AAChB,MAAa,gBAAiB,SAAQ,0BAA0B;IAM9D,YAAY,EAAM,EAAE,QAAgB,EAAE,QAA4B,EAAE,OAAwB;QAC1F,KAAK,CAAC,EAAE,EAAE,OAAO,CAAC,CAAC;QAEnB,IAAI,CAAC,EAAE,GAAG,EAAE,CAAC;QACb,IAAI,CAAC,QAAQ,GAAG,QAAQ,CAAC;QACzB,IAAI,CAAC,QAAQ,GAAG,QAAQ,CAAC;QACzB,IAAI,CAAC,OAAO,GAAG,OAAO,aAAP,OAAO,cAAP,OAAO,GAAI,EAAE,CAAC;IAC/B,CAAC;IAEQ,OAAO,CACd,MAAc,EACd,OAAkC,EAClC,QAA4B;QAE5B,MAAM,EAAE,GAAG,IAAI,CAAC,EAAE,CAAC;QACnB,MAAM,QAAQ,GAAG,IAAI,CAAC,QAAQ,CAAC;QAC/B,MAAM,QAAQ,GAAG,IAAI,CAAC,QAAQ,CAAC;QAC/B,MAAM,OAAO,GAAG,IAAI,CAAC,OAAO,CAAC;QAE7B,kCAAkC;QAClC,IAAI,OAAO,CAAC,cAAc,IAAI,IAAI,EAAE;YAClC,OAAO,QAAQ,CACb,IAAI,iCAAyB,CAC3B,gFAAgF,CACjF,CACF,CAAC;SACH;QAED,IAAI,KAAK,CAAC;QACV,IAAI,CAAC,OAAO,CAAC,KAAK,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c;QACd,IAAI,OAAO,QAAQ,KAAK,QAAQ,EAAE;YAChC,OAAO,CAAC,GAAG,GAAG,YAAY,CAAC;SAC5B;QAED,KAAK,CAAC,cAAc,CAAC,MAAM,EAAE,OAAO,EAAE,OAAO,EAAE,QAAQ,CAAC,CAAC;IAC3D,CAAC;CACF;AAlFD,4CAkFC;AAED,IAAA,yBAAa,EAAC,gBAAgB,EAAE,CAAC,kBAAM,CAAC,eAAe,CAAC,CAAC,CAAC"} \ No newline at end of file diff --git a/ts-ticket-office-service/node_modules/mongodb/lib/operations/aggregate.js b/ts-ticket-office-service/node_modules/mongodb/lib/operations/aggregate.js new file mode 100644 index 000000000..33b513600 --- /dev/null +++ b/ts-ticket-office-service/node_modules/mongodb/lib/operations/aggregate.js @@ -0,0 +1,90 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.AggregateOperation = exports.DB_AGGREGATE_COLLECTION = void 0; +const error_1 = require("../error"); +const utils_1 = require("../utils"); +const command_1 = require("./command"); +const operation_1 = require("./operation"); +/** @internal */ +exports.DB_AGGREGATE_COLLECTION = 1; +const MIN_WIRE_VERSION_$OUT_READ_CONCERN_SUPPORT = 8; +/** @internal */ +class AggregateOperation extends command_1.CommandOperation { + constructor(ns, pipeline, options) { + super(undefined, { ...options, dbName: ns.db }); + this.options = options !== null && options !== void 0 ? options : {}; + // Covers when ns.collection is null, undefined or the empty string, use DB_AGGREGATE_COLLECTION + this.target = ns.collection || exports.DB_AGGREGATE_COLLECTION; + this.pipeline = pipeline; + // determine if we have a write stage, override read preference if so + this.hasWriteStage = false; + if (typeof (options === null || options === void 0 ? void 0 : options.out) === 'string') { + this.pipeline = this.pipeline.concat({ $out: options.out }); + this.hasWriteStage = true; + } + else if (pipeline.length > 0) { + const finalStage = pipeline[pipeline.length - 1]; + if (finalStage.$out || finalStage.$merge) { + this.hasWriteStage = true; + } + } + if (this.hasWriteStage) { + this.trySecondaryWrite = true; + } + if (this.explain && this.writeConcern) { + throw new error_1.MongoInvalidArgumentError('Option "explain" cannot be used on an aggregate call with writeConcern'); + } + if ((options === null || options === void 0 ? void 0 : options.cursor) != null && typeof options.cursor !== 'object') { + throw new error_1.MongoInvalidArgumentError('Cursor options must be an object'); + } + } + get canRetryRead() { + return !this.hasWriteStage; + } + addToPipeline(stage) { + this.pipeline.push(stage); + } + execute(server, session, callback) { + const options = this.options; + const serverWireVersion = (0, utils_1.maxWireVersion)(server); + const command = { aggregate: this.target, pipeline: this.pipeline }; + if (this.hasWriteStage && serverWireVersion < MIN_WIRE_VERSION_$OUT_READ_CONCERN_SUPPORT) { + this.readConcern = undefined; + } + if (serverWireVersion >= 5) { + if (this.hasWriteStage && this.writeConcern) { + Object.assign(command, { writeConcern: this.writeConcern }); + } + } + if (options.bypassDocumentValidation === true) { + command.bypassDocumentValidation = options.bypassDocumentValidation; + } + if (typeof options.allowDiskUse === 'boolean') { + command.allowDiskUse = options.allowDiskUse; + } + if (options.hint) { + command.hint = options.hint; + } + if (options.let) { + command.let = options.let; + } + // we check for undefined specifically here to allow falsy values + // eslint-disable-next-line no-restricted-syntax + if (options.comment !== undefined) { + command.comment = options.comment; + } + command.cursor = options.cursor || {}; + if (options.batchSize && !this.hasWriteStage) { + command.cursor.batchSize = options.batchSize; + } + super.executeCommand(server, session, command, callback); + } +} +exports.AggregateOperation = AggregateOperation; +(0, operation_1.defineAspects)(AggregateOperation, [ + operation_1.Aspect.READ_OPERATION, + operation_1.Aspect.RETRYABLE, + operation_1.Aspect.EXPLAINABLE, + operation_1.Aspect.CURSOR_CREATING +]); +//# sourceMappingURL=aggregate.js.map \ No newline at end of file diff --git a/ts-ticket-office-service/node_modules/mongodb/lib/operations/aggregate.js.map b/ts-ticket-office-service/node_modules/mongodb/lib/operations/aggregate.js.map new file mode 100644 index 000000000..a8dc5fcfb --- /dev/null +++ b/ts-ticket-office-service/node_modules/mongodb/lib/operations/aggregate.js.map @@ -0,0 +1 @@ +{"version":3,"file":"aggregate.js","sourceRoot":"","sources":["../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AAO,CAAC,YAAY,KAAK,SAAS,EAAE;YAC7C,OAAO,CAAC,YAAY,GAAG,OAAO,CAAC,YAAY,CAAC;SAC7C;QAED,IAAI,OAAO,CAAC,IAAI,EAAE;YAChB,OAAO,CAAC,IAAI,GAAG,OAAO,CAAC,IAAI,CAAC;SAC7B;QAED,IAAI,OAAO,CAAC,GAAG,EAAE;YACf,OAAO,CAAC,GAAG,GAAG,OAAO,CAAC,GAAG,CAAC;SAC3B;QAED,iEAAiE;QACjE,gDAAgD;QAChD,IAAI,OAAO,CAAC,OAAO,KAAK,SAAS,EAAE;YACjC,OAAO,CAAC,OAAO,GAAG,OAAO,CAAC,OAAO,CAAC;SACnC;QAED,OAAO,CAAC,MAAM,GAAG,OAAO,CAAC,MAAM,IAAI,EAAE,CAAC;QACtC,IAAI,OAAO,CAAC,SAAS,IAAI,CAAC,IAAI,CAAC,aAAa,EAAE;YAC5C,OAAO,CAAC,MAAM,CAAC,SAAS,GAAG,OAAO,CAAC,SAAS,CAAC;SAC9C;QAED,KAAK,CAAC,cAAc,CAAC,MAAM,EAAE,OAAO,EAAE,OAAO,EAAE,QAAQ,CAAC,CAAC;IAC3D,CAAC;CACF;AAnGD,gDAmGC;AAED,IAAA,yBAAa,EAAC,kBAAkB,EAAE;IAChC,kBAAM,CAAC,cAAc;IACrB,kBAAM,CAAC,SAAS;IAChB,kBAAM,CAAC,WAAW;IAClB,kBAAM,CAAC,eAAe;CACvB,CAAC,CAAC"} \ No newline at end of file diff --git a/ts-ticket-office-service/node_modules/mongodb/lib/operations/bulk_write.js b/ts-ticket-office-service/node_modules/mongodb/lib/operations/bulk_write.js new file mode 100644 index 000000000..cab8ab7e2 --- /dev/null +++ b/ts-ticket-office-service/node_modules/mongodb/lib/operations/bulk_write.js @@ -0,0 +1,43 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.BulkWriteOperation = void 0; +const operation_1 = require("./operation"); +/** @internal */ +class BulkWriteOperation extends operation_1.AbstractOperation { + constructor(collection, operations, options) { + super(options); + this.options = options; + this.collection = collection; + this.operations = operations; + } + execute(server, session, callback) { + const coll = this.collection; + const operations = this.operations; + const options = { ...this.options, ...this.bsonOptions, readPreference: this.readPreference }; + // Create the bulk operation + const bulk = options.ordered === false + ? coll.initializeUnorderedBulkOp(options) + : coll.initializeOrderedBulkOp(options); + // for each op go through and add to the bulk + try { + for (let i = 0; i < operations.length; i++) { + bulk.raw(operations[i]); + } + } + catch (err) { + return callback(err); + } + // Execute the bulk + bulk.execute({ ...options, session }, (err, r) => { + // We have connection level error + if (!r && err) { + return callback(err); + } + // Return the results + callback(undefined, r); + }); + } +} +exports.BulkWriteOperation = BulkWriteOperation; +(0, operation_1.defineAspects)(BulkWriteOperation, [operation_1.Aspect.WRITE_OPERATION]); +//# sourceMappingURL=bulk_write.js.map \ No newline at end of file diff --git a/ts-ticket-office-service/node_modules/mongodb/lib/operations/bulk_write.js.map b/ts-ticket-office-service/node_modules/mongodb/lib/operations/bulk_write.js.map new file mode 100644 index 000000000..e49d9459c --- /dev/null +++ b/ts-ticket-office-service/node_modules/mongodb/lib/operations/bulk_write.js.map @@ -0,0 +1 @@ +{"version":3,"file":"bulk_write.js","sourceRoot":"","sources":["../../src/operations/bulk_write.ts"],"names":[],"mappings":";;;AAUA,2CAAuE;AAEvE,gBAAgB;AAChB,MAAa,kBAAmB,SAAQ,6BAAkC;IAKxE,YACE,UAAsB,EACtB,UAAmC,EACnC,OAAyB;QAEzB,KAAK,CAAC,OAAO,CAAC,CAAC;QACf,IAAI,CAAC,OAAO,GAAG,OAAO,CAAC;QACvB,IAAI,CAAC,UAAU,GAAG,UAAU,CAAC;QAC7B,IAAI,CAAC,UAAU,GAAG,UAAU,CAAC;IAC/B,CAAC;IAEQ,OAAO,CACd,MAAc,EACd,OAAkC,EAClC,QAAmC;QAEnC,MAAM,IAAI,GAAG,IAAI,CAAC,UAAU,CAAC;QAC7B,MAAM,UAAU,GAAG,IAAI,CAAC,UAAU,CAAC;QACnC,MAAM,OAAO,GAAG,EAAE,GAAG,IAAI,CAAC,OAAO,EAAE,GAAG,IAAI,CAAC,WAAW,EAAE,cAAc,EAAE,IAAI,CAAC,cAAc,EAAE,CAAC;QAE9F,4BAA4B;QAC5B,MAAM,IAAI,GACR,OAAO,CAAC,OAAO,KAAK,KAAK;YACvB,CAAC,CAAC,IAAI,CAAC,yBAAyB,CAAC,OAAO,CAAC;YACzC,CAAC,CAAC,IAAI,CAAC,uBAAuB,CAAC,OAAO,CAAC,CAAC;QAE5C,6CAA6C;QAC7C,IAAI;YACF,KAAK,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC,GAAG,UAAU,CAAC,MAAM,EAAE,CAAC,EAAE,EAAE;gBAC1C,IAAI,CAAC,GAAG,CAAC,UAAU,CAAC,CAAC,CAAC,CAAC,CAAC;aACzB;SACF;QAAC,OAAO,GAAG,EAAE;YACZ,OAAO,QAAQ,CAAC,GAAG,CAAC,CAAC;SACtB;QAED,mBAAmB;QACnB,IAAI,CAAC,OAAO,CAAC,EAAE,GAAG,OAAO,EAAE,OAAO,EAAE,EAAE,CAAC,GAAG,EAAE,CAAC,EAAE,EAAE;YAC/C,iCAAiC;YACjC,IAAI,CAAC,CAAC,IAAI,GAAG,EAAE;gBACb,OAAO,QAAQ,CAAC,GAAG,CAAC,CAAC;aACtB;YAED,qBAAqB;YACrB,QAAQ,CAAC,SAAS,EAAE,CAAC,CAAC,CAAC;QACzB,CAAC,CAAC,CAAC;IACL,CAAC;CACF;AAnDD,gDAmDC;AAED,IAAA,yBAAa,EAAC,kBAAkB,EAAE,CAAC,kBAAM,CAAC,eAAe,CAAC,CAAC,CAAC"} \ No newline at end of file diff --git a/ts-ticket-office-service/node_modules/mongodb/lib/operations/collections.js b/ts-ticket-office-service/node_modules/mongodb/lib/operations/collections.js new file mode 100644 index 000000000..d0a1b1fd8 --- /dev/null +++ b/ts-ticket-office-service/node_modules/mongodb/lib/operations/collections.js @@ -0,0 +1,29 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.CollectionsOperation = void 0; +const collection_1 = require("../collection"); +const operation_1 = require("./operation"); +/** @internal */ +class CollectionsOperation extends operation_1.AbstractOperation { + constructor(db, options) { + super(options); + this.options = options; + this.db = db; + } + execute(server, session, callback) { + const db = this.db; + // Let's get the collection names + db.listCollections({}, { ...this.options, nameOnly: true, readPreference: this.readPreference, session }).toArray((err, documents) => { + if (err || !documents) + return callback(err); + // Filter collections removing any illegal ones + documents = documents.filter(doc => doc.name.indexOf('$') === -1); + // Return the collection objects + callback(undefined, documents.map(d => { + return new collection_1.Collection(db, d.name, db.s.options); + })); + }); + } +} +exports.CollectionsOperation = CollectionsOperation; +//# sourceMappingURL=collections.js.map \ No newline at end of file diff --git a/ts-ticket-office-service/node_modules/mongodb/lib/operations/collections.js.map b/ts-ticket-office-service/node_modules/mongodb/lib/operations/collections.js.map new file mode 100644 index 000000000..960c51a66 --- /dev/null +++ b/ts-ticket-office-service/node_modules/mongodb/lib/operations/collections.js.map @@ -0,0 +1 @@ +{"version":3,"file":"collections.js","sourceRoot":"","sources":["../../src/operations/collections.ts"],"names":[],"mappings":";;;AAAA,8CAA2C;AAK3C,2CAAkE;AAMlE,gBAAgB;AAChB,MAAa,oBAAqB,SAAQ,6BAA+B;IAIvE,YAAY,EAAM,EAAE,OAA2B;QAC7C,KAAK,CAAC,OAAO,CAAC,CAAC;QACf,IAAI,CAAC,OAAO,GAAG,OAAO,CAAC;QACvB,IAAI,CAAC,EAAE,GAAG,EAAE,CAAC;IACf,CAAC;IAEQ,OAAO,CACd,MAAc,EACd,OAAkC,EAClC,QAAgC;QAEhC,MAAM,EAAE,GAAG,IAAI,CAAC,EAAE,CAAC;QAEnB,iCAAiC;QACjC,EAAE,CAAC,eAAe,CAChB,EAAE,EACF,EAAE,GAAG,IAAI,CAAC,OAAO,EAAE,QAAQ,EAAE,IAAI,EAAE,cAAc,EAAE,IAAI,CAAC,cAAc,EAAE,OAAO,EAAE,CAClF,CAAC,OAAO,CAAC,CAAC,GAAG,EAAE,SAAS,EAAE,EAAE;YAC3B,IAAI,GAAG,IAAI,CAAC,SAAS;gBAAE,OAAO,QAAQ,CAAC,GAAG,CAAC,CAAC;YAC5C,+CAA+C;YAC/C,SAAS,GAAG,SAAS,CAAC,MAAM,CAAC,GAAG,CAAC,EAAE,CAAC,GAAG,CAAC,IAAI,CAAC,OAAO,CAAC,GAAG,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC;YAElE,gCAAgC;YAChC,QAAQ,CACN,SAAS,EACT,SAAS,CAAC,GAAG,CAAC,CAAC,CAAC,EAAE;gBAChB,OAAO,IAAI,uBAAU,CAAC,EAAE,EAAE,CAAC,CAAC,IAAI,EAAE,EAAE,CAAC,CAAC,CAAC,OAAO,CAAC,CAAC;YAClD,CAAC,CAAC,CACH,CAAC;QACJ,CAAC,CAAC,CAAC;IACL,CAAC;CACF;AAnCD,oDAmCC"} \ No newline at end of file diff --git a/ts-ticket-office-service/node_modules/mongodb/lib/operations/command.js b/ts-ticket-office-service/node_modules/mongodb/lib/operations/command.js new file mode 100644 index 000000000..55ce871ee --- /dev/null +++ b/ts-ticket-office-service/node_modules/mongodb/lib/operations/command.js @@ -0,0 +1,95 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.CommandOperation = void 0; +const error_1 = require("../error"); +const explain_1 = require("../explain"); +const read_concern_1 = require("../read_concern"); +const server_selection_1 = require("../sdam/server_selection"); +const utils_1 = require("../utils"); +const write_concern_1 = require("../write_concern"); +const operation_1 = require("./operation"); +const SUPPORTS_WRITE_CONCERN_AND_COLLATION = 5; +/** @internal */ +class CommandOperation extends operation_1.AbstractOperation { + constructor(parent, options) { + super(options); + this.options = options !== null && options !== void 0 ? options : {}; + // NOTE: this was explicitly added for the add/remove user operations, it's likely + // something we'd want to reconsider. Perhaps those commands can use `Admin` + // as a parent? + const dbNameOverride = (options === null || options === void 0 ? void 0 : options.dbName) || (options === null || options === void 0 ? void 0 : options.authdb); + if (dbNameOverride) { + this.ns = new utils_1.MongoDBNamespace(dbNameOverride, '$cmd'); + } + else { + this.ns = parent + ? parent.s.namespace.withCollection('$cmd') + : new utils_1.MongoDBNamespace('admin', '$cmd'); + } + this.readConcern = read_concern_1.ReadConcern.fromOptions(options); + this.writeConcern = write_concern_1.WriteConcern.fromOptions(options); + // TODO(NODE-2056): make logger another "inheritable" property + if (parent && parent.logger) { + this.logger = parent.logger; + } + if (this.hasAspect(operation_1.Aspect.EXPLAINABLE)) { + this.explain = explain_1.Explain.fromOptions(options); + } + else if ((options === null || options === void 0 ? void 0 : options.explain) != null) { + throw new error_1.MongoInvalidArgumentError(`Option "explain" is not supported on this command`); + } + } + get canRetryWrite() { + if (this.hasAspect(operation_1.Aspect.EXPLAINABLE)) { + return this.explain == null; + } + return true; + } + executeCommand(server, session, cmd, callback) { + // TODO: consider making this a non-enumerable property + this.server = server; + const options = { + ...this.options, + ...this.bsonOptions, + readPreference: this.readPreference, + session + }; + const serverWireVersion = (0, utils_1.maxWireVersion)(server); + const inTransaction = this.session && this.session.inTransaction(); + if (this.readConcern && (0, utils_1.commandSupportsReadConcern)(cmd) && !inTransaction) { + Object.assign(cmd, { readConcern: this.readConcern }); + } + if (this.trySecondaryWrite && serverWireVersion < server_selection_1.MIN_SECONDARY_WRITE_WIRE_VERSION) { + options.omitReadPreference = true; + } + if (options.collation && serverWireVersion < SUPPORTS_WRITE_CONCERN_AND_COLLATION) { + callback(new error_1.MongoCompatibilityError(`Server ${server.name}, which reports wire version ${serverWireVersion}, does not support collation`)); + return; + } + if (this.writeConcern && this.hasAspect(operation_1.Aspect.WRITE_OPERATION) && !inTransaction) { + Object.assign(cmd, { writeConcern: this.writeConcern }); + } + if (serverWireVersion >= SUPPORTS_WRITE_CONCERN_AND_COLLATION) { + if (options.collation && + typeof options.collation === 'object' && + !this.hasAspect(operation_1.Aspect.SKIP_COLLATION)) { + Object.assign(cmd, { collation: options.collation }); + } + } + if (typeof options.maxTimeMS === 'number') { + cmd.maxTimeMS = options.maxTimeMS; + } + if (this.hasAspect(operation_1.Aspect.EXPLAINABLE) && this.explain) { + if (serverWireVersion < 6 && cmd.aggregate) { + // Prior to 3.6, with aggregate, verbosity is ignored, and we must pass in "explain: true" + cmd.explain = true; + } + else { + cmd = (0, utils_1.decorateWithExplain)(cmd, this.explain); + } + } + server.command(this.ns, cmd, options, callback); + } +} +exports.CommandOperation = CommandOperation; +//# sourceMappingURL=command.js.map \ No newline at end of file diff --git a/ts-ticket-office-service/node_modules/mongodb/lib/operations/command.js.map b/ts-ticket-office-service/node_modules/mongodb/lib/operations/command.js.map new file mode 100644 index 000000000..5f49482f9 --- /dev/null +++ b/ts-ticket-office-service/node_modules/mongodb/lib/operations/command.js.map @@ -0,0 +1 @@ +{"version":3,"file":"command.js","sourceRoot":"","sources":["../../src/operations/command.ts"],"names":[],"mappings":";;;AACA,oCAA8E;AAC9E,wCAAqD;AAErD,kDAA8C;AAG9C,+DAA4E;AAE5E,oCAMkB;AAClB,oDAAqE;AAErE,2CAA0E;AAE1E,MAAM,oCAAoC,GAAG,CAAC,CAAC;AAuD/C,gBAAgB;AAChB,MAAsB,gBAAoB,SAAQ,6BAAoB;IAOpE,YAAY,MAAwB,EAAE,OAAiC;QACrE,KAAK,CAAC,OAAO,CAAC,CAAC;QACf,IAAI,CAAC,OAAO,GAAG,OAAO,aAAP,OAAO,cAAP,OAAO,GAAI,EAAE,CAAC;QAE7B,kFAAkF;QAClF,kFAAkF;QAClF,qBAAqB;QACrB,MAAM,cAAc,GAAG,CAAA,OAAO,aAAP,OAAO,uBAAP,OAAO,CAAE,MAAM,MAAI,OAAO,aAAP,OAAO,uBAAP,OAAO,CAAE,MAAM,CAAA,CAAC;QAC1D,IAAI,cAAc,EAAE;YAClB,IAAI,CAAC,EAAE,GAAG,IAAI,wBAAgB,CAAC,cAAc,EAAE,MAAM,CAAC,CAAC;SACxD;aAAM;YACL,IAAI,CAAC,EAAE,GAAG,MAAM;gBACd,CAAC,CAAC,MA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AAI,IAAI,CAAC,OAAO,EAAE;YACtD,IAAI,iBAAiB,GAAG,CAAC,IAAI,GAAG,CAAC,SAAS,EAAE;gBAC1C,0FAA0F;gBAC1F,GAAG,CAAC,OAAO,GAAG,IAAI,CAAC;aACpB;iBAAM;gBACL,GAAG,GAAG,IAAA,2BAAmB,EAAC,GAAG,EAAE,IAAI,CAAC,OAAO,CAAC,CAAC;aAC9C;SACF;QAED,MAAM,CAAC,OAAO,CAAC,IAAI,CAAC,EAAE,EAAE,GAAG,EAAE,OAAO,EAAE,QAAQ,CAAC,CAAC;IAClD,CAAC;CACF;AApHD,4CAoHC"} \ No newline at end of file diff --git a/ts-ticket-office-service/node_modules/mongodb/lib/operations/common_functions.js b/ts-ticket-office-service/node_modules/mongodb/lib/operations/common_functions.js new file mode 100644 index 000000000..60ac62d5e --- /dev/null +++ b/ts-ticket-office-service/node_modules/mongodb/lib/operations/common_functions.js @@ -0,0 +1,71 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.prepareDocs = exports.indexInformation = void 0; +const error_1 = require("../error"); +const utils_1 = require("../utils"); +function indexInformation(db, name, _optionsOrCallback, _callback) { + let options = _optionsOrCallback; + let callback = _callback; + if ('function' === typeof _optionsOrCallback) { + callback = _optionsOrCallback; + options = {}; + } + // If we specified full information + const full = options.full == null ? false : options.full; + let topology; + try { + topology = (0, utils_1.getTopology)(db); + } + catch (error) { + return callback(error); + } + // Did the user destroy the topology + if (topology.isDestroyed()) + return callback(new error_1.MongoTopologyClosedError()); + // Process all the results from the index command and collection + function processResults(indexes) { + // Contains all the information + const info = {}; + // Process all the indexes + for (let i = 0; i < indexes.length; i++) { + const index = indexes[i]; + // Let's unpack the object + info[index.name] = []; + for (const name in index.key) { + info[index.name].push([name, index.key[name]]); + } + } + return info; + } + // Get the list of indexes of the specified collection + db.collection(name) + .listIndexes(options) + .toArray((err, indexes) => { + if (err) + return callback(err); + if (!Array.isArray(indexes)) + return callback(undefined, []); + if (full) + return callback(undefined, indexes); + callback(undefined, processResults(indexes)); + }); +} +exports.indexInformation = indexInformation; +function prepareDocs(coll, docs, options) { + var _a; + const forceServerObjectId = typeof options.forceServerObjectId === 'boolean' + ? options.forceServerObjectId + : (_a = coll.s.db.options) === null || _a === void 0 ? void 0 : _a.forceServerObjectId; + // no need to modify the docs if server sets the ObjectId + if (forceServerObjectId === true) { + return docs; + } + return docs.map(doc => { + if (doc._id == null) { + doc._id = coll.s.pkFactory.createPk(); + } + return doc; + }); +} +exports.prepareDocs = prepareDocs; +//# sourceMappingURL=common_functions.js.map \ No newline at end of file diff --git a/ts-ticket-office-service/node_modules/mongodb/lib/operations/common_functions.js.map b/ts-ticket-office-service/node_modules/mongodb/lib/operations/common_functions.js.map new file mode 100644 index 000000000..60d1acb09 --- /dev/null +++ b/ts-ticket-office-service/node_modules/mongodb/lib/operations/common_functions.js.map @@ -0,0 +1 @@ +{"version":3,"file":"common_functions.js","sourceRoot":"","sources":["../../src/operations/common_functions.ts"],"names":[],"mappings":";;;AAGA,oCAAoD;AAGpD,oCAAiD;AAqBjD,SAAgB,gBAAgB,CAC9B,EAAM,EACN,IAAY,EACZ,kBAAsD,EACtD,SAAoB;IAEpB,IAAI,OAAO,GAAG,kBAA6C,CAAC;IAC5D,IAAI,QAAQ,GAAG,SAAqB,CAAC;IACrC,IAAI,UAAU,KAAK,OAAO,kBAAkB,EAAE;QAC5C,QAAQ,GAAG,kBAAkB,CAAC;QAC9B,OAAO,GAAG,EAAE,CAAC;KACd;IACD,mCAAmC;IACnC,MAAM,IAAI,GAAG,OAAO,CAAC,IAAI,IAAI,IAAI,CAAC,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC,OAAO,CAAC,IAAI,CAAC;IAEzD,IAAI,QAAQ,CAAC;IACb,IAAI;QACF,QAAQ,GAAG,IAAA,mBAAW,EAAC,EAAE,CAAC,CAAC;KAC5B;IAAC,OAAO,KAAK,EAAE;QACd,OAAO,QAAQ,CAAC,KAAK,CAAC,CAAC;KACxB;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,EAChB,OAA0C;;IAE1C,MAAM,mBAAmB,GACvB,OAAO,OAAO,CAAC,mBAAmB,KAAK,SAAS;QAC9C,CAAC,CAAC,OAAO,CAAC,mBAAmB;QAC7B,CAAC,CAAC,MAAA,IAAI,CAAC,CAAC,CAAC,EAAE,CAAC,OAAO,0CAAE,mBAAmB,CAAC;IAE7C,yDAAyD;IACzD,IAAI,mBAAmB,KAAK,IAAI,EAAE;QAChC,OAAO,IAAI,CAAC;KACb;IAED,OAAO,IAAI,CAAC,GAAG,CAAC,GAAG,CAAC,EAAE;QACpB,IAAI,GAAG,CAAC,GAAG,IAAI,IAAI,EAAE;YACnB,GAAG,CAAC,GAAG,GAAG,IAAI,CAAC,CAAC,CAAC,SAAS,CAAC,QAAQ,EAAE,CAAC;SACvC;QAED,OAAO,GAAG,CAAC;IACb,CAAC,CAAC,CAAC;AACL,CAAC;AAtBD,kCAsBC"} \ No newline at end of file diff --git a/ts-ticket-office-service/node_modules/mongodb/lib/operations/connect.js b/ts-ticket-office-service/node_modules/mongodb/lib/operations/connect.js new file mode 100644 index 000000000..eb7abc874 --- /dev/null +++ b/ts-ticket-office-service/node_modules/mongodb/lib/operations/connect.js @@ -0,0 +1,85 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.connect = void 0; +const connection_string_1 = require("../connection_string"); +const constants_1 = require("../constants"); +const error_1 = require("../error"); +const topology_1 = require("../sdam/topology"); +function connect(mongoClient, options, callback) { + if (!callback) { + throw new error_1.MongoInvalidArgumentError('Callback function must be provided'); + } + // If a connection already been established, we can terminate early + if (mongoClient.topology && mongoClient.topology.isConnected()) { + return callback(undefined, mongoClient); + } + const logger = mongoClient.logger; + const connectCallback = err => { + const warningMessage = 'seed list contains no mongos proxies, replicaset connections requires ' + + 'the parameter replicaSet to be supplied in the URI or options object, ' + + 'mongodb://server:port/db?replicaSet=name'; + if (err && err.message === 'no mongos proxies found in seed list') { + if (logger.isWarn()) { + logger.warn(warningMessage); + } + // Return a more specific error message for MongoClient.connect + // TODO(NODE-3483) + return callback(new error_1.MongoRuntimeError(warningMessage)); + } + callback(err, mongoClient); + }; + if (typeof options.srvHost === 'string') { + return (0, connection_string_1.resolveSRVRecord)(options, (err, hosts) => { + if (err || !hosts) + return callback(err); + for (const [index, host] of hosts.entries()) { + options.hosts[index] = host; + } + return createTopology(mongoClient, options, connectCallback); + }); + } + return createTopology(mongoClient, options, connectCallback); +} +exports.connect = connect; +function createTopology(mongoClient, options, callback) { + // Create the topology + const topology = new topology_1.Topology(options.hosts, options); + // Events can be emitted before initialization is complete so we have to + // save the reference to the topology on the client ASAP if the event handlers need to access it + mongoClient.topology = topology; + topology.client = mongoClient; + topology.once(topology_1.Topology.OPEN, () => mongoClient.emit('open', mongoClient)); + for (const event of constants_1.MONGO_CLIENT_EVENTS) { + topology.on(event, (...args) => mongoClient.emit(event, ...args)); + } + // initialize CSFLE if requested + if (mongoClient.autoEncrypter) { + mongoClient.autoEncrypter.init(err => { + if (err) { + return callback(err); + } + topology.connect(options, err => { + if (err) { + topology.close({ force: true }); + return callback(err); + } + options.encrypter.connectInternalClient(error => { + if (error) + return callback(error); + callback(undefined, topology); + }); + }); + }); + return; + } + // otherwise connect normally + topology.connect(options, err => { + if (err) { + topology.close({ force: true }); + return callback(err); + } + callback(undefined, topology); + return; + }); +} +//# sourceMappingURL=connect.js.map \ No newline at end of file diff --git a/ts-ticket-office-service/node_modules/mongodb/lib/operations/connect.js.map b/ts-ticket-office-service/node_modules/mongodb/lib/operations/connect.js.map new file mode 100644 index 000000000..f39e04be5 --- /dev/null +++ b/ts-ticket-office-service/node_modules/mongodb/lib/operations/connect.js.map @@ -0,0 +1 @@ +{"version":3,"file":"connect.js","sourceRoot":"","sources":["../../src/operations/connect.ts"],"names":[],"mappings":";;;AAAA,4DAAwD;AACxD,4CAAmD;AACnD,oCAAwE;AAExE,+CAA4C;AAG5C,SAAgB,OAAO,CACrB,WAAwB,EACxB,OAAqB,EACrB,QAA+B;IAE/B,IAAI,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AC,CAAC;gBAChC,CAAC,CAAC,CAAC;YACL,CAAC,CAAC,CAAC;QACL,CAAC,CAAC,CAAC;QAEH,OAAO;KACR;IAED,6BAA6B;IAC7B,QAAQ,CAAC,OAAO,CAAC,OAAO,EAAE,GAAG,CAAC,EAAE;QAC9B,IAAI,GAAG,EAAE;YACP,QAAQ,CAAC,KAAK,CAAC,EAAE,KAAK,EAAE,IAAI,EAAE,CAAC,CAAC;YAChC,OAAO,QAAQ,CAAC,GAAG,CAAC,CAAC;SACtB;QAED,QAAQ,CAAC,SAAS,EAAE,QAAQ,CAAC,CAAC;QAC9B,OAAO;IACT,CAAC,CAAC,CAAC;AACL,CAAC"} \ No newline at end of file diff --git a/ts-ticket-office-service/node_modules/mongodb/lib/operations/count.js b/ts-ticket-office-service/node_modules/mongodb/lib/operations/count.js new file mode 100644 index 000000000..706dde671 --- /dev/null +++ b/ts-ticket-office-service/node_modules/mongodb/lib/operations/count.js @@ -0,0 +1,39 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.CountOperation = void 0; +const command_1 = require("./command"); +const operation_1 = require("./operation"); +/** @internal */ +class CountOperation extends command_1.CommandOperation { + constructor(namespace, filter, options) { + super({ s: { namespace: namespace } }, options); + this.options = options; + this.collectionName = namespace.collection; + this.query = filter; + } + execute(server, session, callback) { + const options = this.options; + const cmd = { + count: this.collectionName, + query: this.query + }; + if (typeof options.limit === 'number') { + cmd.limit = options.limit; + } + if (typeof options.skip === 'number') { + cmd.skip = options.skip; + } + if (options.hint != null) { + cmd.hint = options.hint; + } + if (typeof options.maxTimeMS === 'number') { + cmd.maxTimeMS = options.maxTimeMS; + } + super.executeCommand(server, session, cmd, (err, result) => { + callback(err, result ? result.n : 0); + }); + } +} +exports.CountOperation = CountOperation; +(0, operation_1.defineAspects)(CountOperation, [operation_1.Aspect.READ_OPERATION, operation_1.Aspect.RETRYABLE]); +//# sourceMappingURL=count.js.map \ No newline at end of file diff --git a/ts-ticket-office-service/node_modules/mongodb/lib/operations/count.js.map b/ts-ticket-office-service/node_modules/mongodb/lib/operations/count.js.map new file mode 100644 index 000000000..aeee5fd7c --- /dev/null +++ b/ts-ticket-office-service/node_modules/mongodb/lib/operations/count.js.map @@ -0,0 +1 @@ +{"version":3,"file":"count.js","sourceRoot":"","sources":["../../src/operations/count.ts"],"names":[],"mappings":";;;AAKA,uCAAsE;AACtE,2CAAoD;AAcpD,gBAAgB;AAChB,MAAa,cAAe,SAAQ,0BAAwB;IAK1D,YAAY,SAA2B,EAAE,MAAgB,EAAE,OAAqB;QAC9E,KAAK,CAAC,EAAE,CAAC,EAAE,EAAE,SAAS,EAAE,SAAS,EAAE,EAA2B,EAAE,OAAO,CAAC,CAAC;QAEzE,IAAI,CAAC,OAAO,GAAG,OAAO,CAAC;QACvB,IAAI,CAAC,cAAc,GAAG,SAAS,CAAC,UAAU,CAAC;QAC3C,IAAI,CAAC,KAAK,GAAG,MAAM,CAAC;IACtB,CAAC;IAEQ,OAAO,CACd,MAAc,EACd,OAAkC,EAClC,QAA0B;QAE1B,MAAM,OAAO,GAAG,IAAI,CAAC,OAAO,CAAC;QAC7B,MAAM,GAAG,GAAa;YACpB,KAAK,EAAE,IAAI,CAAC,cAAc;YAC1B,KAAK,EAAE,IAAI,CAAC,KAAK;SAClB,CAAC;QAEF,IAAI,OAAO,OAAO,CAAC,KAAK,KAAK,QAAQ,EAAE;YACrC,GAAG,CAAC,KAAK,GAAG,OAAO,CAAC,KAAK,CAAC;SAC3B;QAED,IAAI,OAAO,OAAO,CAAC,IAAI,KAAK,QAAQ,EAAE;YACpC,GAAG,CAAC,IAAI,GAAG,OAAO,CAAC,IAAI,CAAC;SACzB;QAED,IAAI,OAAO,CAAC,IAAI,IAAI,IAAI,EAAE;YACxB,GAAG,CAAC,IAAI,GAAG,OAAO,CAAC,IAAI,CAAC;SACzB;QAED,IAAI,OAAO,OAAO,CAAC,SAAS,KAAK,QAAQ,EAAE;YACzC,GAAG,CAAC,SAAS,GAAG,OAAO,CAAC,SAAS,CAAC;SACnC;QAED,KAAK,CAAC,cAAc,CAAC,MAAM,EAAE,OAAO,EAAE,GAAG,EAAE,CAAC,GAAG,EAAE,MAAM,EAAE,EAAE;YACzD,QAAQ,CAAC,GAAG,EAAE,MAAM,CAAC,CAAC,CAAC,MAAM,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC;QACvC,CAAC,CAAC,CAAC;IACL,CAAC;CACF;AA5CD,wCA4CC;AAED,IAAA,yBAAa,EAAC,cAAc,EAAE,CAAC,kBAAM,CAAC,cAAc,EAAE,kBAAM,CAAC,SAAS,CAAC,CAAC,CAAC"} \ No newline at end of file diff --git a/ts-ticket-office-service/node_modules/mongodb/lib/operations/count_documents.js b/ts-ticket-office-service/node_modules/mongodb/lib/operations/count_documents.js new file mode 100644 index 000000000..562c9c068 --- /dev/null +++ b/ts-ticket-office-service/node_modules/mongodb/lib/operations/count_documents.js @@ -0,0 +1,37 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.CountDocumentsOperation = void 0; +const aggregate_1 = require("./aggregate"); +/** @internal */ +class CountDocumentsOperation extends aggregate_1.AggregateOperation { + constructor(collection, query, options) { + const pipeline = []; + pipeline.push({ $match: query }); + if (typeof options.skip === 'number') { + pipeline.push({ $skip: options.skip }); + } + if (typeof options.limit === 'number') { + pipeline.push({ $limit: options.limit }); + } + pipeline.push({ $group: { _id: 1, n: { $sum: 1 } } }); + super(collection.s.namespace, pipeline, options); + } + execute(server, session, callback) { + super.execute(server, session, (err, result) => { + if (err || !result) { + callback(err); + return; + } + // NOTE: We're avoiding creating a cursor here to reduce the callstack. + const response = result; + if (response.cursor == null || response.cursor.firstBatch == null) { + callback(undefined, 0); + return; + } + const docs = response.cursor.firstBatch; + callback(undefined, docs.length ? docs[0].n : 0); + }); + } +} +exports.CountDocumentsOperation = CountDocumentsOperation; +//# sourceMappingURL=count_documents.js.map \ No newline at end of file diff --git a/ts-ticket-office-service/node_modules/mongodb/lib/operations/count_documents.js.map b/ts-ticket-office-service/node_modules/mongodb/lib/operations/count_documents.js.map new file mode 100644 index 000000000..bc1ce7b67 --- /dev/null +++ b/ts-ticket-office-service/node_modules/mongodb/lib/operations/count_documents.js.map @@ -0,0 +1 @@ +{"version":3,"file":"count_documents.js","sourceRoot":"","sources":["../../src/operations/count_documents.ts"],"names":[],"mappings":";;;AAKA,2CAAmE;AAUnE,gBAAgB;AAChB,MAAa,uBAAwB,SAAQ,8BAA0B;IACrE,YAAY,UAAsB,EAAE,KAAe,EAAE,OAA8B;QACjF,MAAM,QAAQ,GAAG,EAAE,CAAC;QACpB,QAAQ,CAAC,IAAI,CAAC,EAAE,MAAM,EAAE,KAAK,EAAE,CAAC,CAAC;QAEjC,IAAI,OAAO,OAAO,CAAC,IAAI,KAAK,QAAQ,EAAE;YACpC,QAAQ,CAAC,IAAI,CAAC,EAAE,KAAK,EAAE,OAAO,CAAC,IAAI,EAAE,CAAC,CAAC;SACxC;QAED,IAAI,OAAO,OAAO,CAAC,KAAK,KAAK,QAAQ,EAAE;YACrC,QAAQ,CAAC,IAAI,CAAC,EAAE,MAAM,EAAE,OAAO,CAAC,KAAK,EAAE,CAAC,CAAC;SAC1C;QAED,QAAQ,CAAC,IAAI,CAAC,EAAE,MAAM,EAAE,EAAE,GAAG,EAAE,CAAC,EAAE,CAAC,EAAE,EAAE,IAAI,EAAE,CAAC,EAAE,EAAE,EAAE,CAAC,CAAC;QAEtD,KAAK,CAAC,UAAU,CAAC,CAAC,CAAC,SAAS,EAAE,QAAQ,EAAE,OAAO,CAAC,CAAC;IACnD,CAAC;IAEQ,OAAO,CACd,MAAc,EACd,OAAkC,EAClC,QAA0B;QAE1B,KAAK,CAAC,OAAO,CAAC,MAAM,EAAE,OAAO,EAAE,CAAC,GAAG,EAAE,MAAM,EAAE,EAAE;YAC7C,IAAI,GAAG,IAAI,CAAC,MAAM,EAAE;gBAClB,QAAQ,CAAC,GAAG,CAAC,CAAC;gBACd,OAAO;aACR;YAED,uEAAuE;YACvE,MAAM,QAAQ,GAAG,MAA6B,CAAC;YAC/C,IAAI,QAAQ,CAAC,MAAM,IAAI,IAAI,IAAI,QAAQ,CAAC,MAAM,CAAC,UAAU,IAAI,IAAI,EAAE;gBACjE,QAAQ,CAAC,SAAS,EAAE,CAAC,CAAC,CAAC;gBACvB,OAAO;aACR;YAED,MAAM,IAAI,GAAG,QAAQ,CAAC,MAAM,CAAC,UAAU,CAAC;YACxC,QAAQ,CAAC,SAAS,EAAE,IAAI,CAAC,MAAM,CAAC,CAAC,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC;QACnD,CAAC,CAAC,CAAC;IACL,CAAC;CACF;AAxCD,0DAwCC"} \ No newline at end of file diff --git a/ts-ticket-office-service/node_modules/mongodb/lib/operations/create_collection.js b/ts-ticket-office-service/node_modules/mongodb/lib/operations/create_collection.js new file mode 100644 index 000000000..4d6c8a50e --- /dev/null +++ b/ts-ticket-office-service/node_modules/mongodb/lib/operations/create_collection.js @@ -0,0 +1,100 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.CreateCollectionOperation = void 0; +const collection_1 = require("../collection"); +const command_1 = require("./command"); +const indexes_1 = require("./indexes"); +const operation_1 = require("./operation"); +const ILLEGAL_COMMAND_FIELDS = new Set([ + 'w', + 'wtimeout', + 'j', + 'fsync', + 'autoIndexId', + 'pkFactory', + 'raw', + 'readPreference', + 'session', + 'readConcern', + 'writeConcern', + 'raw', + 'fieldsAsRaw', + 'promoteLongs', + 'promoteValues', + 'promoteBuffers', + 'bsonRegExp', + 'serializeFunctions', + 'ignoreUndefined', + 'enableUtf8Validation' +]); +/** @internal */ +class CreateCollectionOperation extends command_1.CommandOperation { + constructor(db, name, options = {}) { + super(db, options); + this.options = options; + this.db = db; + this.name = name; + } + execute(server, session, callback) { + (async () => { + var _a, _b, _c, _d, _e, _f; + const db = this.db; + const name = this.name; + const options = this.options; + const encryptedFields = (_a = options.encryptedFields) !== null && _a !== void 0 ? _a : (_c = (_b = db.s.client.options.autoEncryption) === null || _b === void 0 ? void 0 : _b.encryptedFieldsMap) === null || _c === void 0 ? void 0 : _c[`${db.databaseName}.${name}`]; + if (encryptedFields) { + // Create auxilliary collections for queryable encryption support. + const escCollection = (_d = encryptedFields.escCollection) !== null && _d !== void 0 ? _d : `enxcol_.${name}.esc`; + const eccCollection = (_e = encryptedFields.eccCollection) !== null && _e !== void 0 ? _e : `enxcol_.${name}.ecc`; + const ecocCollection = (_f = encryptedFields.ecocCollection) !== null && _f !== void 0 ? _f : `enxcol_.${name}.ecoc`; + for (const collectionName of [escCollection, eccCollection, ecocCollection]) { + const createOp = new CreateCollectionOperation(db, collectionName, { + clusteredIndex: { + key: { _id: 1 }, + unique: true + } + }); + await createOp.executeWithoutEncryptedFieldsCheck(server, session); + } + if (!options.encryptedFields) { + this.options = { ...this.options, encryptedFields }; + } + } + const coll = await this.executeWithoutEncryptedFieldsCheck(server, session); + if (encryptedFields) { + // Create the required index for queryable encryption support. + const createIndexOp = new indexes_1.CreateIndexOperation(db, name, { __safeContent__: 1 }, {}); + await new Promise((resolve, reject) => { + createIndexOp.execute(server, session, err => (err ? reject(err) : resolve())); + }); + } + return coll; + })().then(coll => callback(undefined, coll), err => callback(err)); + } + executeWithoutEncryptedFieldsCheck(server, session) { + return new Promise((resolve, reject) => { + const db = this.db; + const name = this.name; + const options = this.options; + const done = err => { + if (err) { + return reject(err); + } + resolve(new collection_1.Collection(db, name, options)); + }; + const cmd = { create: name }; + for (const n in options) { + if (options[n] != null && + typeof options[n] !== 'function' && + !ILLEGAL_COMMAND_FIELDS.has(n)) { + cmd[n] = options[n]; + } + } + // otherwise just execute the command + super.executeCommand(server, session, cmd, done); + }); + } +} +exports.CreateCollectionOperation = CreateCollectionOperation; +(0, operation_1.defineAspects)(CreateCollectionOperation, [operation_1.Aspect.WRITE_OPERATION]); +//# sourceMappingURL=create_collection.js.map \ No newline at end of file diff --git a/ts-ticket-office-service/node_modules/mongodb/lib/operations/create_collection.js.map b/ts-ticket-office-service/node_modules/mongodb/lib/operations/create_collection.js.map new file mode 100644 index 000000000..397690f8b --- /dev/null +++ b/ts-ticket-office-service/node_modules/mongodb/lib/operations/create_collection.js.map @@ -0,0 +1 @@ +{"version":3,"file":"create_collection.js","sourceRoot":"","sources":["../../src/operations/create_collection.ts"],"names":[],"mappings":";;;AACA,8CAA2C;AAM3C,uCAAsE;AACtE,uCAAiD;AACjD,2CAAoD;AAEpD,MAAM,sBAAsB,GAAG,IAAI,GAAG,CAAC;IACrC,GAAG;IACH,UAAU;IACV,GAAG;IACH,OAAO;IACP,aAAa;IACb,WAAW;IACX,KAAK;IACL,gBAAgB;IAChB,SAAS;IACT,aAAa;IACb,cAAc;IACd,KAAK;IACL,aAAa;IACb,cAAc;IACd,eAAe;IACf,gBAAgB;IAChB,YAAY;IACZ,oBAAoB;IACpB,iBAAiB;IACjB,sBAAsB;CACvB,CAAC,CAAC;AAoEH,gBAAgB;AAChB,MAAa,yBAA0B,SAAQ,0BAA4B;IAKzE,YAAY,EAAM,EAAE,IAAY,EAAE,UAAmC,EAAE;QACrE,KAAK,CAAC,EAAE,EAAE,OAAO,CAAC,CAAC;QAEnB,IAAI,CAAC,OAAO,GAAG,OAAO,CAAC;QACvB,IAAI,CAAC,EAAE,GAAG,EAAE,CAAC;QACb,IAAI,CAAC,IAAI,GAAG,IAAI,CAAC;IACnB,CAAC;IAEQ,OAAO,CACd,MAAc,EACd,OAAkC,EAClC,QAA8B;QAE9B,CAAC,KAAK,IAAI,EAAE;;YACV,MAAM,EAAE,GAAG,IAAI,CAAC,EAAE,CAAC;YACnB,MAAM,IAAI,GAAG,IAAI,CAAC,IAAI,CAAC;YACvB,MAAM,OAAO,GAAG,IAAI,CAAC,OAAO,CAAC;YAE7B,MAAM,eAAe,GACnB,MAAA,OAAO,CAAC,eAAe,mCACvB,MAAA,MAAA,EAAE,CAAC,CAAC,CAAC,MAAM,CAAC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M,EAAE,OAAO,EAAE,GAAG,EAAE,IAAI,CAAC,CAAC;QACnD,CAAC,CAAC,CAAC;IACL,CAAC;CACF;AAjGD,8DAiGC;AAED,IAAA,yBAAa,EAAC,yBAAyB,EAAE,CAAC,kBAAM,CAAC,eAAe,CAAC,CAAC,CAAC"} \ No newline at end of file diff --git a/ts-ticket-office-service/node_modules/mongodb/lib/operations/delete.js b/ts-ticket-office-service/node_modules/mongodb/lib/operations/delete.js new file mode 100644 index 000000000..34cd24a10 --- /dev/null +++ b/ts-ticket-office-service/node_modules/mongodb/lib/operations/delete.js @@ -0,0 +1,135 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.makeDeleteStatement = exports.DeleteManyOperation = exports.DeleteOneOperation = exports.DeleteOperation = void 0; +const error_1 = require("../error"); +const utils_1 = require("../utils"); +const command_1 = require("./command"); +const operation_1 = require("./operation"); +/** @internal */ +class DeleteOperation extends command_1.CommandOperation { + constructor(ns, statements, options) { + super(undefined, options); + this.options = options; + this.ns = ns; + this.statements = statements; + } + get canRetryWrite() { + if (super.canRetryWrite === false) { + return false; + } + return this.statements.every(op => (op.limit != null ? op.limit > 0 : true)); + } + execute(server, session, callback) { + var _a; + const options = (_a = this.options) !== null && _a !== void 0 ? _a : {}; + const ordered = typeof options.ordered === 'boolean' ? options.ordered : true; + const command = { + delete: this.ns.collection, + deletes: this.statements, + ordered + }; + if (options.let) { + command.let = options.let; + } + // we check for undefined specifically here to allow falsy values + // eslint-disable-next-line no-restricted-syntax + if (options.comment !== undefined) { + command.comment = options.comment; + } + if (options.explain != null && (0, utils_1.maxWireVersion)(server) < 3) { + return callback + ? callback(new error_1.MongoCompatibilityError(`Server ${server.name} does not support explain on delete`)) + : undefined; + } + const unacknowledgedWrite = this.writeConcern && this.writeConcern.w === 0; + if (unacknowledgedWrite || (0, utils_1.maxWireVersion)(server) < 5) { + if (this.statements.find((o) => o.hint)) { + callback(new error_1.MongoCompatibilityError(`Servers < 3.4 do not support hint on delete`)); + return; + } + } + const statementWithCollation = this.statements.find(statement => !!statement.collation); + if (statementWithCollation && (0, utils_1.collationNotSupported)(server, statementWithCollation)) { + callback(new error_1.MongoCompatibilityError(`Server ${server.name} does not support collation`)); + return; + } + super.executeCommand(server, session, command, callback); + } +} +exports.DeleteOperation = DeleteOperation; +class DeleteOneOperation extends DeleteOperation { + constructor(collection, filter, options) { + super(collection.s.namespace, [makeDeleteStatement(filter, { ...options, limit: 1 })], options); + } + execute(server, session, callback) { + super.execute(server, session, (err, res) => { + var _a, _b; + if (err || res == null) + return callback(err); + if (res.code) + return callback(new error_1.MongoServerError(res)); + if (res.writeErrors) + return callback(new error_1.MongoServerError(res.writeErrors[0])); + if (this.explain) + return callback(undefined, res); + callback(undefined, { + acknowledged: (_b = ((_a = this.writeConcern) === null || _a === void 0 ? void 0 : _a.w) !== 0) !== null && _b !== void 0 ? _b : true, + deletedCount: res.n + }); + }); + } +} +exports.DeleteOneOperation = DeleteOneOperation; +class DeleteManyOperation extends DeleteOperation { + constructor(collection, filter, options) { + super(collection.s.namespace, [makeDeleteStatement(filter, options)], options); + } + execute(server, session, callback) { + super.execute(server, session, (err, res) => { + var _a, _b; + if (err || res == null) + return callback(err); + if (res.code) + return callback(new error_1.MongoServerError(res)); + if (res.writeErrors) + return callback(new error_1.MongoServerError(res.writeErrors[0])); + if (this.explain) + return callback(undefined, res); + callback(undefined, { + acknowledged: (_b = ((_a = this.writeConcern) === null || _a === void 0 ? void 0 : _a.w) !== 0) !== null && _b !== void 0 ? _b : true, + deletedCount: res.n + }); + }); + } +} +exports.DeleteManyOperation = DeleteManyOperation; +function makeDeleteStatement(filter, options) { + const op = { + q: filter, + limit: typeof options.limit === 'number' ? options.limit : 0 + }; + if (options.single === true) { + op.limit = 1; + } + if (options.collation) { + op.collation = options.collation; + } + if (options.hint) { + op.hint = options.hint; + } + return op; +} +exports.makeDeleteStatement = makeDeleteStatement; +(0, operation_1.defineAspects)(DeleteOperation, [operation_1.Aspect.RETRYABLE, operation_1.Aspect.WRITE_OPERATION]); +(0, operation_1.defineAspects)(DeleteOneOperation, [ + operation_1.Aspect.RETRYABLE, + operation_1.Aspect.WRITE_OPERATION, + operation_1.Aspect.EXPLAINABLE, + operation_1.Aspect.SKIP_COLLATION +]); +(0, operation_1.defineAspects)(DeleteManyOperation, [ + operation_1.Aspect.WRITE_OPERATION, + operation_1.Aspect.EXPLAINABLE, + operation_1.Aspect.SKIP_COLLATION +]); +//# sourceMappingURL=delete.js.map \ No newline at end of file diff --git a/ts-ticket-office-service/node_modules/mongodb/lib/operations/delete.js.map b/ts-ticket-office-service/node_modules/mongodb/lib/operations/delete.js.map new file mode 100644 index 000000000..e716dfe5e --- /dev/null +++ b/ts-ticket-office-service/node_modules/mongodb/lib/operations/delete.js.map @@ -0,0 +1 @@ +{"version":3,"file":"delete.js","sourceRoot":"","sources":["../../src/operations/delete.ts"],"names":[],"mappings":";;;AAEA,oCAAqE;AAGrE,oCAA6F;AAE7F,uCAAwF;AACxF,2CAA0D;AAqC1D,gBAAgB;AAChB,MAAa,eAAgB,SAAQ,0BAA0B;IAI7D,YAAY,EAAoB,EAAE,UAA6B,EAAE,OAAsB;QACrF,KAAK,CAAC,SAAS,EAAE,OAAO,CAAC,CAAC;QAC1B,IAAI,CAAC,OAAO,GAAG,OAAO,CAAC;QACvB,IAAI,CAAC,EAAE,GAAG,EAAE,CAAC;QACb,IAAI,CAAC,UAAU,GAAG,UAAU,CAAC;IAC/B,CAAC;IAED,IAAa,aAAa;QACxB,IAAI,KAAK,CAAC,aAAa,KAAK,KAAK,EAAE;YACjC,OAAO,KAAK,CAAC;SACd;QAED,OAAO,IAAI,CAAC,UAAU,CAAC,KAAK,CAAC,EAAE,CAAC,EAAE,CAAC,CAAC,EAAE,CAAC,KAAK,IAAI,IAAI,CAAC,CAAC,CAAC,EAAE,CAAC,KAAK,GAAG,CAAC,CAAC,CAAC,CAAC,IAAI,CAAC,CAAC,CAAC;IAC/E,CAAC;IAEQ,OAAO,CA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AsBC;AAED,SAAgB,mBAAmB,CACjC,MAAgB,EAChB,OAA2C;IAE3C,MAAM,EAAE,GAAoB;QAC1B,CAAC,EAAE,MAAM;QACT,KAAK,EAAE,OAAO,OAAO,CAAC,KAAK,KAAK,QAAQ,CAAC,CAAC,CAAC,OAAO,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC;KAC7D,CAAC;IAEF,IAAI,OAAO,CAAC,MAAM,KAAK,IAAI,EAAE;QAC3B,EAAE,CAAC,KAAK,GAAG,CAAC,CAAC;KACd;IAED,IAAI,OAAO,CAAC,SAAS,EAAE;QACrB,EAAE,CAAC,SAAS,GAAG,OAAO,CAAC,SAAS,CAAC;KAClC;IAED,IAAI,OAAO,CAAC,IAAI,EAAE;QAChB,EAAE,CAAC,IAAI,GAAG,OAAO,CAAC,IAAI,CAAC;KACxB;IAED,OAAO,EAAE,CAAC;AACZ,CAAC;AAtBD,kDAsBC;AAED,IAAA,yBAAa,EAAC,eAAe,EAAE,CAAC,kBAAM,CAAC,SAAS,EAAE,kBAAM,CAAC,eAAe,CAAC,CAAC,CAAC;AAC3E,IAAA,yBAAa,EAAC,kBAAkB,EAAE;IAChC,kBAAM,CAAC,SAAS;IAChB,kBAAM,CAAC,eAAe;IACtB,kBAAM,CAAC,WAAW;IAClB,kBAAM,CAAC,cAAc;CACtB,CAAC,CAAC;AACH,IAAA,yBAAa,EAAC,mBAAmB,EAAE;IACjC,kBAAM,CAAC,eAAe;IACtB,kBAAM,CAAC,WAAW;IAClB,kBAAM,CAAC,cAAc;CACtB,CAAC,CAAC"} \ No newline at end of file diff --git a/ts-ticket-office-service/node_modules/mongodb/lib/operations/distinct.js b/ts-ticket-office-service/node_modules/mongodb/lib/operations/distinct.js new file mode 100644 index 000000000..4e2e8264f --- /dev/null +++ b/ts-ticket-office-service/node_modules/mongodb/lib/operations/distinct.js @@ -0,0 +1,67 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.DistinctOperation = void 0; +const error_1 = require("../error"); +const utils_1 = require("../utils"); +const command_1 = require("./command"); +const operation_1 = require("./operation"); +/** + * Return a list of distinct values for the given key across a collection. + * @internal + */ +class DistinctOperation extends command_1.CommandOperation { + /** + * Construct a Distinct operation. + * + * @param collection - Collection instance. + * @param key - Field of the document to find distinct values for. + * @param query - The query for filtering the set of documents to which we apply the distinct filter. + * @param options - Optional settings. See Collection.prototype.distinct for a list of options. + */ + constructor(collection, key, query, options) { + super(collection, options); + this.options = options !== null && options !== void 0 ? options : {}; + this.collection = collection; + this.key = key; + this.query = query; + } + execute(server, session, callback) { + const coll = this.collection; + const key = this.key; + const query = this.query; + const options = this.options; + // Distinct command + const cmd = { + distinct: coll.collectionName, + key: key, + query: query + }; + // Add maxTimeMS if defined + if (typeof options.maxTimeMS === 'number') { + cmd.maxTimeMS = options.maxTimeMS; + } + // Do we have a readConcern specified + (0, utils_1.decorateWithReadConcern)(cmd, coll, options); + // Have we specified collation + try { + (0, utils_1.decorateWithCollation)(cmd, coll, options); + } + catch (err) { + return callback(err); + } + if (this.explain && (0, utils_1.maxWireVersion)(server) < 4) { + callback(new error_1.MongoCompatibilityError(`Server ${server.name} does not support explain on distinct`)); + return; + } + super.executeCommand(server, session, cmd, (err, result) => { + if (err) { + callback(err); + return; + } + callback(undefined, this.explain ? result : result.values); + }); + } +} +exports.DistinctOperation = DistinctOperation; +(0, operation_1.defineAspects)(DistinctOperation, [operation_1.Aspect.READ_OPERATION, operation_1.Aspect.RETRYABLE, operation_1.Aspect.EXPLAINABLE]); +//# sourceMappingURL=distinct.js.map \ No newline at end of file diff --git a/ts-ticket-office-service/node_modules/mongodb/lib/operations/distinct.js.map b/ts-ticket-office-service/node_modules/mongodb/lib/operations/distinct.js.map new file mode 100644 index 000000000..1b111c909 --- /dev/null +++ b/ts-ticket-office-service/node_modules/mongodb/lib/operations/distinct.js.map @@ -0,0 +1 @@ +{"version":3,"file":"distinct.js","sourceRoot":"","sources":["../../src/operations/distinct.ts"],"names":[],"mappings":";;;AAEA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AI,CAAC,OAAO,IAAI,IAAA,sBAAc,EAAC,MAAM,CAAC,GAAG,CAAC,EAAE;YAC9C,QAAQ,CACN,IAAI,+BAAuB,CAAC,UAAU,MAAM,CAAC,IAAI,uCAAuC,CAAC,CAC1F,CAAC;YACF,OAAO;SACR;QAED,KAAK,CAAC,cAAc,CAAC,MAAM,EAAE,OAAO,EAAE,GAAG,EAAE,CAAC,GAAG,EAAE,MAAM,EAAE,EAAE;YACzD,IAAI,GAAG,EAAE;gBACP,QAAQ,CAAC,GAAG,CAAC,CAAC;gBACd,OAAO;aACR;YAED,QAAQ,CAAC,SAAS,EAAE,IAAI,CAAC,OAAO,CAAC,CAAC,CAAC,MAAM,CAAC,CAAC,CAAC,MAAM,CAAC,MAAM,CAAC,CAAC;QAC7D,CAAC,CAAC,CAAC;IACL,CAAC;CACF;AAzED,8CAyEC;AAED,IAAA,yBAAa,EAAC,iBAAiB,EAAE,CAAC,kBAAM,CAAC,cAAc,EAAE,kBAAM,CAAC,SAAS,EAAE,kBAAM,CAAC,WAAW,CAAC,CAAC,CAAC"} \ No newline at end of file diff --git a/ts-ticket-office-service/node_modules/mongodb/lib/operations/drop.js b/ts-ticket-office-service/node_modules/mongodb/lib/operations/drop.js new file mode 100644 index 000000000..c0cbcf2f4 --- /dev/null +++ b/ts-ticket-office-service/node_modules/mongodb/lib/operations/drop.js @@ -0,0 +1,84 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.DropDatabaseOperation = exports.DropCollectionOperation = void 0; +const error_1 = require("../error"); +const command_1 = require("./command"); +const operation_1 = require("./operation"); +/** @internal */ +class DropCollectionOperation extends command_1.CommandOperation { + constructor(db, name, options = {}) { + super(db, options); + this.db = db; + this.options = options; + this.name = name; + } + execute(server, session, callback) { + (async () => { + var _a, _b, _c, _d; + const db = this.db; + const options = this.options; + const name = this.name; + const encryptedFieldsMap = (_a = db.s.client.options.autoEncryption) === null || _a === void 0 ? void 0 : _a.encryptedFieldsMap; + let encryptedFields = (_b = options.encryptedFields) !== null && _b !== void 0 ? _b : encryptedFieldsMap === null || encryptedFieldsMap === void 0 ? void 0 : encryptedFieldsMap[`${db.databaseName}.${name}`]; + if (!encryptedFields && encryptedFieldsMap) { + // If the MongoClient was configued with an encryptedFieldsMap, + // and no encryptedFields config was available in it or explicitly + // passed as an argument, the spec tells us to look one up using + // listCollections(). + const listCollectionsResult = await db + .listCollections({ name }, { nameOnly: false }) + .toArray(); + encryptedFields = (_d = (_c = listCollectionsResult === null || listCollectionsResult === void 0 ? void 0 : listCollectionsResult[0]) === null || _c === void 0 ? void 0 : _c.options) === null || _d === void 0 ? void 0 : _d.encryptedFields; + } + if (encryptedFields) { + const escCollection = encryptedFields.escCollection || `enxcol_.${name}.esc`; + const eccCollection = encryptedFields.eccCollection || `enxcol_.${name}.ecc`; + const ecocCollection = encryptedFields.ecocCollection || `enxcol_.${name}.ecoc`; + for (const collectionName of [escCollection, eccCollection, ecocCollection]) { + // Drop auxilliary collections, ignoring potential NamespaceNotFound errors. + const dropOp = new DropCollectionOperation(db, collectionName); + try { + await dropOp.executeWithoutEncryptedFieldsCheck(server, session); + } + catch (err) { + if (!(err instanceof error_1.MongoServerError) || + err.code !== error_1.MONGODB_ERROR_CODES.NamespaceNotFound) { + throw err; + } + } + } + } + return await this.executeWithoutEncryptedFieldsCheck(server, session); + })().then(result => callback(undefined, result), err => callback(err)); + } + executeWithoutEncryptedFieldsCheck(server, session) { + return new Promise((resolve, reject) => { + super.executeCommand(server, session, { drop: this.name }, (err, result) => { + if (err) + return reject(err); + resolve(!!result.ok); + }); + }); + } +} +exports.DropCollectionOperation = DropCollectionOperation; +/** @internal */ +class DropDatabaseOperation extends command_1.CommandOperation { + constructor(db, options) { + super(db, options); + this.options = options; + } + execute(server, session, callback) { + super.executeCommand(server, session, { dropDatabase: 1 }, (err, result) => { + if (err) + return callback(err); + if (result.ok) + return callback(undefined, true); + callback(undefined, false); + }); + } +} +exports.DropDatabaseOperation = DropDatabaseOperation; +(0, operation_1.defineAspects)(DropCollectionOperation, [operation_1.Aspect.WRITE_OPERATION]); +(0, operation_1.defineAspects)(DropDatabaseOperation, [operation_1.Aspect.WRITE_OPERATION]); +//# sourceMappingURL=drop.js.map \ No newline at end of file diff --git a/ts-ticket-office-service/node_modules/mongodb/lib/operations/drop.js.map b/ts-ticket-office-service/node_modules/mongodb/lib/operations/drop.js.map new file mode 100644 index 000000000..6f6e283b4 --- /dev/null +++ b/ts-ticket-office-service/node_modules/mongodb/lib/operations/drop.js.map @@ -0,0 +1 @@ +{"version":3,"file":"drop.js","sourceRoot":"","sources":["../../src/operations/drop.ts"],"names":[],"mappings":";;;AAEA,oCAAiE;AAIjE,uCAAsE;AACtE,2CAAoD;AAQpD,gBAAgB;AAChB,MAAa,uBAAwB,SAAQ,0BAAyB;IAKpE,YAAY,EAAM,EAAE,IAAY,EAAE,UAAiC,EAAE;QACnE,KAAK,CAAC,EAAE,EAAE,OAAO,CAAC,CAAC;QACnB,IAAI,CAAC,EAAE,GAAG,EAAE,CAAC;QACb,IAAI,CAAC,OAAO,GAAG,OAAO,CAAC;QACvB,IAAI,CAAC,IAAI,GAAG,IAAI,CAAC;IACnB,CAAC;IAEQ,OAAO,CACd,MAAc,EACd,OAAkC,EAClC,QAA2B;QAE3B,CAAC,KAAK,IAAI,EAAE;;YACV,MAAM,EAAE,GAAG,IAAI,CAAC,EAAE,CAAC;YACnB,MAAM,OAAO,GAAG,IAAI,CAAC,OAAO,CAAC;YAC7B,MAAM,IAAI,GAAG,IAAI,CAAC,IAAI,CAAC;YAEvB,MAAM,kBAAkB,GAAG,MAAA,EAAE,CAAC,CAAC,CAAC,MAAM,CAAC,OAAO,CAAC,cAAc,0CAAE,kBAAkB,CAAC;YAClF,IAAI,eAAe,GACjB,MAAA,OAAO,CAAC,eAAe,mCAAI,kBAAkB,aAAlB,kBAAkB,uBAAlB,kBAAkB,CAAG,GAAG,EAAE,CAAC,YAAY,IAAI,IAAI,EAAE,CAAC,CAAC;YAEh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AC,CAAC;AACjE,IAAA,yBAAa,EAAC,qBAAqB,EAAE,CAAC,kBAAM,CAAC,eAAe,CAAC,CAAC,CAAC"} \ No newline at end of file diff --git a/ts-ticket-office-service/node_modules/mongodb/lib/operations/estimated_document_count.js b/ts-ticket-office-service/node_modules/mongodb/lib/operations/estimated_document_count.js new file mode 100644 index 000000000..1cd7f60bf --- /dev/null +++ b/ts-ticket-office-service/node_modules/mongodb/lib/operations/estimated_document_count.js @@ -0,0 +1,38 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.EstimatedDocumentCountOperation = void 0; +const command_1 = require("./command"); +const operation_1 = require("./operation"); +/** @internal */ +class EstimatedDocumentCountOperation extends command_1.CommandOperation { + constructor(collection, options = {}) { + super(collection, options); + this.options = options; + this.collectionName = collection.collectionName; + } + execute(server, session, callback) { + const cmd = { count: this.collectionName }; + if (typeof this.options.maxTimeMS === 'number') { + cmd.maxTimeMS = this.options.maxTimeMS; + } + // we check for undefined specifically here to allow falsy values + // eslint-disable-next-line no-restricted-syntax + if (this.options.comment !== undefined) { + cmd.comment = this.options.comment; + } + super.executeCommand(server, session, cmd, (err, response) => { + if (err) { + callback(err); + return; + } + callback(undefined, (response === null || response === void 0 ? void 0 : response.n) || 0); + }); + } +} +exports.EstimatedDocumentCountOperation = EstimatedDocumentCountOperation; +(0, operation_1.defineAspects)(EstimatedDocumentCountOperation, [ + operation_1.Aspect.READ_OPERATION, + operation_1.Aspect.RETRYABLE, + operation_1.Aspect.CURSOR_CREATING +]); +//# sourceMappingURL=estimated_document_count.js.map \ No newline at end of file diff --git a/ts-ticket-office-service/node_modules/mongodb/lib/operations/estimated_document_count.js.map b/ts-ticket-office-service/node_modules/mongodb/lib/operations/estimated_document_count.js.map new file mode 100644 index 000000000..e325a23d5 --- /dev/null +++ b/ts-ticket-office-service/node_modules/mongodb/lib/operations/estimated_document_count.js.map @@ -0,0 +1 @@ +{"version":3,"file":"estimated_document_count.js","sourceRoot":"","sources":["../../src/oper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ts-ticket-office-service/node_modules/mongodb/lib/operations/eval.js b/ts-ticket-office-service/node_modules/mongodb/lib/operations/eval.js new file mode 100644 index 000000000..7227ce458 --- /dev/null +++ b/ts-ticket-office-service/node_modules/mongodb/lib/operations/eval.js @@ -0,0 +1,55 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.EvalOperation = void 0; +const bson_1 = require("../bson"); +const error_1 = require("../error"); +const read_preference_1 = require("../read_preference"); +const command_1 = require("./command"); +/** @internal */ +class EvalOperation extends command_1.CommandOperation { + constructor(db, code, parameters, options) { + super(db, options); + this.options = options !== null && options !== void 0 ? options : {}; + this.code = code; + this.parameters = parameters; + // force primary read preference + Object.defineProperty(this, 'readPreference', { + value: read_preference_1.ReadPreference.primary, + configurable: false, + writable: false + }); + } + execute(server, session, callback) { + let finalCode = this.code; + let finalParameters = []; + // If not a code object translate to one + if (!(finalCode && finalCode._bsontype === 'Code')) { + finalCode = new bson_1.Code(finalCode); + } + // Ensure the parameters are correct + if (this.parameters != null && typeof this.parameters !== 'function') { + finalParameters = Array.isArray(this.parameters) ? this.parameters : [this.parameters]; + } + // Create execution selector + const cmd = { $eval: finalCode, args: finalParameters }; + // Check if the nolock parameter is passed in + if (this.options.nolock) { + cmd.nolock = this.options.nolock; + } + // Execute the command + super.executeCommand(server, session, cmd, (err, result) => { + if (err) + return callback(err); + if (result && result.ok === 1) { + return callback(undefined, result.retval); + } + if (result) { + callback(new error_1.MongoServerError({ message: `eval failed: ${result.errmsg}` })); + return; + } + callback(err, result); + }); + } +} +exports.EvalOperation = EvalOperation; +//# sourceMappingURL=eval.js.map \ No newline at end of file diff --git a/ts-ticket-office-service/node_modules/mongodb/lib/operations/eval.js.map b/ts-ticket-office-service/node_modules/mongodb/lib/operations/eval.js.map new file mode 100644 index 000000000..de1692de4 --- /dev/null +++ b/ts-ticket-office-service/node_modules/mongodb/lib/operations/eval.js.map @@ -0,0 +1 @@ +{"version":3,"file":"eval.js","sourceRoot":"","sources":["../../src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EAAE,eAAe,EAAE,CAAC;QAElE,6CAA6C;QAC7C,IAAI,IAAI,CAAC,OAAO,CAAC,MAAM,EAAE;YACvB,GAAG,CAAC,MAAM,GAAG,IAAI,CAAC,OAAO,CAAC,MAAM,CAAC;SAClC;QAED,sBAAsB;QACtB,KAAK,CAAC,cAAc,CAAC,MAAM,EAAE,OAAO,EAAE,GAAG,EAAE,CAAC,GAAG,EAAE,MAAM,EAAE,EAAE;YACzD,IAAI,GAAG;gBAAE,OAAO,QAAQ,CAAC,GAAG,CAAC,CAAC;YAC9B,IAAI,MAAM,IAAI,MAAM,CAAC,EAAE,KAAK,CAAC,EAAE;gBAC7B,OAAO,QAAQ,CAAC,SAAS,EAAE,MAAM,CAAC,MAAM,CAAC,CAAC;aAC3C;YAED,IAAI,MAAM,EAAE;gBACV,QAAQ,CAAC,IAAI,wBAAgB,CAAC,EAAE,OAAO,EAAE,gBAAgB,MAAM,CAAC,MAAM,EAAE,EAAE,CAAC,CAAC,CAAC;gBAC7E,OAAO;aACR;YAED,QAAQ,CAAC,GAAG,EAAE,MAAM,CAAC,CAAC;QACxB,CAAC,CAAC,CAAC;IACL,CAAC;CACF;AAjED,sCAiEC"} \ No newline at end of file diff --git a/ts-ticket-office-service/node_modules/mongodb/lib/operations/execute_operation.js b/ts-ticket-office-service/node_modules/mongodb/lib/operations/execute_operation.js new file mode 100644 index 000000000..e9a242715 --- /dev/null +++ b/ts-ticket-office-service/node_modules/mongodb/lib/operations/execute_operation.js @@ -0,0 +1,185 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.executeOperation = void 0; +const error_1 = require("../error"); +const read_preference_1 = require("../read_preference"); +const server_selection_1 = require("../sdam/server_selection"); +const utils_1 = require("../utils"); +const operation_1 = require("./operation"); +const MMAPv1_RETRY_WRITES_ERROR_CODE = error_1.MONGODB_ERROR_CODES.IllegalOperation; +const MMAPv1_RETRY_WRITES_ERROR_MESSAGE = 'This MongoDB deployment does not support retryable writes. Please add retryWrites=false to your connection string.'; +function executeOperation(client, operation, callback) { + if (!(operation instanceof operation_1.AbstractOperation)) { + // TODO(NODE-3483): Extend MongoRuntimeError + throw new error_1.MongoRuntimeError('This method requires a valid operation instance'); + } + return (0, utils_1.maybePromise)(callback, callback => { + const topology = client.topology; + if (topology == null) { + if (client.s.hasBeenClosed) { + return callback(new error_1.MongoNotConnectedError('Client must be connected before running operations')); + } + client.s.options[Symbol.for('@@mdb.skipPingOnConnect')] = true; + return client.connect(error => { + delete client.s.options[Symbol.for('@@mdb.skipPingOnConnect')]; + if (error) { + return callback(error); + } + return executeOperation(client, operation, callback); + }); + } + if (topology.shouldCheckForSessionSupport()) { + return topology.selectServer(read_preference_1.ReadPreference.primaryPreferred, {}, err => { + if (err) + return callback(err); + executeOperation(client, operation, callback); + }); + } + // The driver sessions spec mandates that we implicitly create sessions for operations + // that are not explicitly provided with a session. + let session = operation.session; + let owner; + if (topology.hasSessionSupport()) { + if (session == null) { + owner = Symbol(); + session = client.startSession({ owner, explicit: false }); + } + else if (session.hasEnded) { + return callback(new error_1.MongoExpiredSessionError('Use of expired sessions is not permitted')); + } + else if (session.snapshotEnabled && !topology.capabilities.supportsSnapshotReads) { + return callback(new error_1.MongoCompatibilityError('Snapshot reads require MongoDB 5.0 or later')); + } + } + else { + // no session support + if (session && session.explicit) { + // If the user passed an explicit session and we are still, after server selection, + // trying to run against a topology that doesn't support sessions we error out. + return callback(new error_1.MongoCompatibilityError('Current topology does not support sessions')); + } + else if (session && !session.explicit) { + // We do not have to worry about ending the session because the server session has not been acquired yet + delete operation.options.session; + operation.clearSession(); + session = undefined; + } + } + try { + executeWithServerSelection(topology, session, operation, (error, result) => { + if ((session === null || session === void 0 ? void 0 : session.owner) != null && session.owner === owner) { + return session.endSession(endSessionError => callback(endSessionError !== null && endSessionError !== void 0 ? endSessionError : error, result)); + } + callback(error, result); + }); + } + catch (error) { + if ((session === null || session === void 0 ? void 0 : session.owner) != null && session.owner === owner) { + session.endSession().catch(() => null); + } + throw error; + } + }); +} +exports.executeOperation = executeOperation; +function executeWithServerSelection(topology, session, operation, callback) { + var _a, _b; + const readPreference = (_a = operation.readPreference) !== null && _a !== void 0 ? _a : read_preference_1.ReadPreference.primary; + const inTransaction = !!(session === null || session === void 0 ? void 0 : session.inTransaction()); + if (inTransaction && !readPreference.equals(read_preference_1.ReadPreference.primary)) { + return callback(new error_1.MongoTransactionError(`Read preference in a transaction must be primary, not: ${readPreference.mode}`)); + } + if ((session === null || session === void 0 ? void 0 : session.isPinned) && session.transaction.isCommitted && !operation.bypassPinningCheck) { + session.unpin(); + } + let selector; + if (operation.hasAspect(operation_1.Aspect.MUST_SELECT_SAME_SERVER)) { + // GetMore and KillCursor operations must always select the same server, but run through + // server selection to potentially force monitor checks if the server is + // in an unknown state. + selector = (0, server_selection_1.sameServerSelector)((_b = operation.server) === null || _b === void 0 ? void 0 : _b.description); + } + else if (operation.trySecondaryWrite) { + // If operation should try to write to secondary use the custom server selector + // otherwise provide the read preference. + selector = (0, server_selection_1.secondaryWritableServerSelector)(topology.commonWireVersion, readPreference); + } + else { + selector = readPreference; + } + const serverSelectionOptions = { session }; + function retryOperation(originalError) { + const isWriteOperation = operation.hasAspect(operation_1.Aspect.WRITE_OPERATION); + const isReadOperation = operation.hasAspect(operation_1.Aspect.READ_OPERATION); + if (isWriteOperation && originalError.code === MMAPv1_RETRY_WRITES_ERROR_CODE) { + return callback(new error_1.MongoServerError({ + message: MMAPv1_RETRY_WRITES_ERROR_MESSAGE, + errmsg: MMAPv1_RETRY_WRITES_ERROR_MESSAGE, + originalError + })); + } + if (isWriteOperation && !(0, error_1.isRetryableWriteError)(originalError)) { + return callback(originalError); + } + if (isReadOperation && !(0, error_1.isRetryableReadError)(originalError)) { + return callback(originalError); + } + if (originalError instanceof error_1.MongoNetworkError && + (session === null || session === void 0 ? void 0 : session.isPinned) && + !session.inTransaction() && + operation.hasAspect(operation_1.Aspect.CURSOR_CREATING)) { + // If we have a cursor and the initial command fails with a network error, + // we can retry it on another connection. So we need to check it back in, clear the + // pool for the service id, and retry again. + session.unpin({ force: true, forceClear: true }); + } + // select a new server, and attempt to retry the operation + topology.selectServer(selector, serverSelectionOptions, (error, server) => { + if (!error && isWriteOperation && !(0, utils_1.supportsRetryableWrites)(server)) { + return callback(new error_1.MongoUnexpectedServerResponseError('Selected server does not support retryable writes')); + } + if (error || !server) { + return callback(error !== null && error !== void 0 ? error : new error_1.MongoUnexpectedServerResponseError('Server selection failed without error')); + } + operation.execute(server, session, callback); + }); + } + if (readPreference && + !readPreference.equals(read_preference_1.ReadPreference.primary) && + (session === null || session === void 0 ? void 0 : session.inTransaction())) { + callback(new error_1.MongoTransactionError(`Read preference in a transaction must be primary, not: ${readPreference.mode}`)); + return; + } + // select a server, and execute the operation against it + topology.selectServer(selector, serverSelectionOptions, (error, server) => { + if (error || !server) { + return callback(error); + } + if (session && operation.hasAspect(operation_1.Aspect.RETRYABLE)) { + const willRetryRead = topology.s.options.retryReads && !inTransaction && operation.canRetryRead; + const willRetryWrite = topology.s.options.retryWrites && + !inTransaction && + (0, utils_1.supportsRetryableWrites)(server) && + operation.canRetryWrite; + const hasReadAspect = operation.hasAspect(operation_1.Aspect.READ_OPERATION); + const hasWriteAspect = operation.hasAspect(operation_1.Aspect.WRITE_OPERATION); + if ((hasReadAspect && willRetryRead) || (hasWriteAspect && willRetryWrite)) { + if (hasWriteAspect && willRetryWrite) { + operation.options.willRetryWrite = true; + session.incrementTransactionNumber(); + } + return operation.execute(server, session, (error, result) => { + if (error instanceof error_1.MongoError) { + return retryOperation(error); + } + else if (error) { + return callback(error); + } + callback(undefined, result); + }); + } + } + return operation.execute(server, session, callback); + }); +} +//# sourceMappingURL=execute_operation.js.map \ No newline at end of file diff --git a/ts-ticket-office-service/node_modules/mongodb/lib/operations/execute_operation.js.map b/ts-ticket-office-service/node_modules/mongodb/lib/operations/execute_operation.js.map new file mode 100644 index 000000000..cf63e23f8 --- /dev/null +++ b/ts-ticket-office-service/node_modules/mongodb/lib/operations/execute_operation.js.map @@ -0,0 +1 @@ +{"version":3,"file":"execute_operation.js","sourceRoot":"","sources":["../../src/operations/execute_operation.ts"],"names":[],"mappings":";;;AACA,oCAakB;AAElB,wDAAoD;AAEpD,+DAIkC;AAGlC,oCAA2E;AAC3E,2CAAwD;AAExD,MAAM,8BAA8B,GAAG,2BAAmB,CAAC,gBAAgB,CAAC;AAC5E,MAAM,iCAAiC,GACrC,oHAAoH,CAAC;AA2CvH,SAAgB,gBAAgB,CAG9B,MAAmB,EAAE,SAAY,EAAE,QAA4B;IAC/D,IAAI,CAAC,CAAC,SAAS,YAAY,6BAAiB,CAAC,EAAE;QAC7C,4CAA4C;QAC5C,MAAM,IAAI,yBAAiB,CAAC,iDAAiD,CAAC,CAAC;KAChF;IAED,OAAO,IAAA,oBAAY,EAAC,QAAQ,EAAE,QAAQ,CAAC,EAAE;QACvC,MAAM,QAAQ,GAAG,MAAM,CAAC,QAAQ,CAAC;QAEjC,IAAI,QAAQ,IAAI,IAAI,EAAE;YACpB,IAAI,MAAM,CAAC,CAAC,CAAC,aAAa,EAAE;gBAC1B,OAAO,QAAQ,CACb,IAAI,8BAAsB,CAAC,oDAAoD,CAAC,CACjF,CAAC;aACH;YACD,MAAM,CAAC,CAAC,CAAC,OAAO,CAAC,MAAM,CAAC,GAAG,CAAC,yBAAyB,CAAC,CAAC,GAAG,IAAI,CAAC;YAC/D,OAAO,MAAM,CAAC,OAAO,CAAC,KAAK,CAAC,EAAE;gBAC5B,OAAO,MAAM,CAAC,CAAC,CAAC,OAAO,CAAC,MAAM,CAAC,GAAG,CAAC,yBAAyB,CAAC,CAAC,CAAC;gBAC/D,IAAI,KAAK,EAAE;oBACT,OAAO,QAAQ,CAAC,KAAK,CAAC,CAAC;iBACxB;gBACD,OAAO,gBAAgB,CAAa,MAAM,EAAE,SAAS,EAAE,QAAQ,CAAC,CAAC;YACnE,CAAC,CAAC,CAAC;SACJ;QAED,IAAI,QAAQ,CAAC,4BAA4B,EAAE,EAA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C,CAAC,CAAC;aACJ;SACF;QAED,OAAO,SAAS,CAAC,OAAO,CAAC,MAAM,EAAE,OAAO,EAAE,QAAQ,CAAC,CAAC;IACtD,CAAC,CAAC,CAAC;AACL,CAAC"} \ No newline at end of file diff --git a/ts-ticket-office-service/node_modules/mongodb/lib/operations/find.js b/ts-ticket-office-service/node_modules/mongodb/lib/operations/find.js new file mode 100644 index 000000000..f961909f3 --- /dev/null +++ b/ts-ticket-office-service/node_modules/mongodb/lib/operations/find.js @@ -0,0 +1,162 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.FindOperation = void 0; +const error_1 = require("../error"); +const read_concern_1 = require("../read_concern"); +const sort_1 = require("../sort"); +const utils_1 = require("../utils"); +const command_1 = require("./command"); +const operation_1 = require("./operation"); +const SUPPORTS_WRITE_CONCERN_AND_COLLATION = 5; +/** @internal */ +class FindOperation extends command_1.CommandOperation { + constructor(collection, ns, filter = {}, options = {}) { + super(collection, options); + this.options = options; + this.ns = ns; + if (typeof filter !== 'object' || Array.isArray(filter)) { + throw new error_1.MongoInvalidArgumentError('Query filter must be a plain object or ObjectId'); + } + // If the filter is a buffer, validate that is a valid BSON document + if (Buffer.isBuffer(filter)) { + const objectSize = filter[0] | (filter[1] << 8) | (filter[2] << 16) | (filter[3] << 24); + if (objectSize !== filter.length) { + throw new error_1.MongoInvalidArgumentError(`Query filter raw message size does not match message header size [${filter.length}] != [${objectSize}]`); + } + } + // special case passing in an ObjectId as a filter + this.filter = filter != null && filter._bsontype === 'ObjectID' ? { _id: filter } : filter; + } + execute(server, session, callback) { + this.server = server; + const serverWireVersion = (0, utils_1.maxWireVersion)(server); + const options = this.options; + if (options.allowDiskUse != null && serverWireVersion < 4) { + callback(new error_1.MongoCompatibilityError('Option "allowDiskUse" is not supported on MongoDB < 3.2')); + return; + } + if (options.collation && serverWireVersion < SUPPORTS_WRITE_CONCERN_AND_COLLATION) { + callback(new error_1.MongoCompatibilityError(`Server ${server.name}, which reports wire version ${serverWireVersion}, does not support collation`)); + return; + } + let findCommand = makeFindCommand(this.ns, this.filter, options); + if (this.explain) { + findCommand = (0, utils_1.decorateWithExplain)(findCommand, this.explain); + } + server.command(this.ns, findCommand, { + ...this.options, + ...this.bsonOptions, + documentsReturnedIn: 'firstBatch', + session + }, callback); + } +} +exports.FindOperation = FindOperation; +function makeFindCommand(ns, filter, options) { + const findCommand = { + find: ns.collection, + filter + }; + if (options.sort) { + findCommand.sort = (0, sort_1.formatSort)(options.sort); + } + if (options.projection) { + let projection = options.projection; + if (projection && Array.isArray(projection)) { + projection = projection.length + ? projection.reduce((result, field) => { + result[field] = 1; + return result; + }, {}) + : { _id: 1 }; + } + findCommand.projection = projection; + } + if (options.hint) { + findCommand.hint = (0, utils_1.normalizeHintField)(options.hint); + } + if (typeof options.skip === 'number') { + findCommand.skip = options.skip; + } + if (typeof options.limit === 'number') { + if (options.limit < 0) { + findCommand.limit = -options.limit; + findCommand.singleBatch = true; + } + else { + findCommand.limit = options.limit; + } + } + if (typeof options.batchSize === 'number') { + if (options.batchSize < 0) { + if (options.limit && + options.limit !== 0 && + Math.abs(options.batchSize) < Math.abs(options.limit)) { + findCommand.limit = -options.batchSize; + } + findCommand.singleBatch = true; + } + else { + findCommand.batchSize = options.batchSize; + } + } + if (typeof options.singleBatch === 'boolean') { + findCommand.singleBatch = options.singleBatch; + } + // we check for undefined specifically here to allow falsy values + // eslint-disable-next-line no-restricted-syntax + if (options.comment !== undefined) { + findCommand.comment = options.comment; + } + if (typeof options.maxTimeMS === 'number') { + findCommand.maxTimeMS = options.maxTimeMS; + } + const readConcern = read_concern_1.ReadConcern.fromOptions(options); + if (readConcern) { + findCommand.readConcern = readConcern.toJSON(); + } + if (options.max) { + findCommand.max = options.max; + } + if (options.min) { + findCommand.min = options.min; + } + if (typeof options.returnKey === 'boolean') { + findCommand.returnKey = options.returnKey; + } + if (typeof options.showRecordId === 'boolean') { + findCommand.showRecordId = options.showRecordId; + } + if (typeof options.tailable === 'boolean') { + findCommand.tailable = options.tailable; + } + if (typeof options.timeout === 'boolean') { + findCommand.noCursorTimeout = !options.timeout; + } + else if (typeof options.noCursorTimeout === 'boolean') { + findCommand.noCursorTimeout = options.noCursorTimeout; + } + if (typeof options.awaitData === 'boolean') { + findCommand.awaitData = options.awaitData; + } + if (typeof options.allowPartialResults === 'boolean') { + findCommand.allowPartialResults = options.allowPartialResults; + } + if (options.collation) { + findCommand.collation = options.collation; + } + if (typeof options.allowDiskUse === 'boolean') { + findCommand.allowDiskUse = options.allowDiskUse; + } + if (options.let) { + findCommand.let = options.let; + } + return findCommand; +} +(0, operation_1.defineAspects)(FindOperation, [ + operation_1.Aspect.READ_OPERATION, + operation_1.Aspect.RETRYABLE, + operation_1.Aspect.EXPLAINABLE, + operation_1.Aspect.CURSOR_CREATING +]); +//# sourceMappingURL=find.js.map \ No newline at end of file diff --git a/ts-ticket-office-service/node_modules/mongodb/lib/operations/find.js.map b/ts-ticket-office-service/node_modules/mongodb/lib/operations/find.js.map new file mode 100644 index 000000000..d8b587edc --- /dev/null +++ b/ts-ticket-office-service/node_modules/mongodb/lib/operations/find.js.map @@ -0,0 +1 @@ +{"version":3,"file":"find.js","sourceRoot":"","sources":["../../src/operations/find.ts"],"names":[],"mappings":";;;AAEA,oCAA8E;AAC9E,kDAA8C;AAG9C,kCAA2C;AAC3C,oCAMkB;AAClB,uCAAwF;AACxF,2CAA0D;AAoD1D,MAAM,oCAAoC,GAAG,CAAC,CAAC;AAE/C,gBAAgB;AAChB,MAAa,aAAc,SAAQ,0BAA0B;IAI3D,YACE,UAAkC,EAClC,EAAoB,EACpB,SAAmB,EAAE,EACrB,UAAuB,EAAE;QAEzB,KAAK,CAAC,UAAU,EAAE,OAAO,CAAC,CAAC;QAE3B,IAAI,CAAC,OAAO,GAAG,OAAO,CAAC;QACvB,IAAI,CAAC,EAAE,GAAG,EAAE,CAAC;QAEb,IAAI,OAAO,MAAM,KAAK,QAAQ,IAAI,KAAK,CAAC,OAAO,CAAC,MA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B,CAAC;KAC/D;IAED,IAAI,OAAO,CAAC,SAAS,EAAE;QACrB,WAAW,CAAC,SAAS,GAAG,OAAO,CAAC,SAAS,CAAC;KAC3C;IAED,IAAI,OAAO,OAAO,CAAC,YAAY,KAAK,SAAS,EAAE;QAC7C,WAAW,CAAC,YAAY,GAAG,OAAO,CAAC,YAAY,CAAC;KACjD;IAED,IAAI,OAAO,CAAC,GAAG,EAAE;QACf,WAAW,CAAC,GAAG,GAAG,OAAO,CAAC,GAAG,CAAC;KAC/B;IAED,OAAO,WAAW,CAAC;AACrB,CAAC;AAED,IAAA,yBAAa,EAAC,aAAa,EAAE;IAC3B,kBAAM,CAAC,cAAc;IACrB,kBAAM,CAAC,SAAS;IAChB,kBAAM,CAAC,WAAW;IAClB,kBAAM,CAAC,eAAe;CACvB,CAAC,CAAC"} \ No newline at end of file diff --git a/ts-ticket-office-service/node_modules/mongodb/lib/operations/find_and_modify.js b/ts-ticket-office-service/node_modules/mongodb/lib/operations/find_and_modify.js new file mode 100644 index 000000000..525bdc692 --- /dev/null +++ b/ts-ticket-office-service/node_modules/mongodb/lib/operations/find_and_modify.js @@ -0,0 +1,156 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.FindOneAndUpdateOperation = exports.FindOneAndReplaceOperation = exports.FindOneAndDeleteOperation = exports.ReturnDocument = void 0; +const error_1 = require("../error"); +const read_preference_1 = require("../read_preference"); +const sort_1 = require("../sort"); +const utils_1 = require("../utils"); +const command_1 = require("./command"); +const operation_1 = require("./operation"); +/** @public */ +exports.ReturnDocument = Object.freeze({ + BEFORE: 'before', + AFTER: 'after' +}); +function configureFindAndModifyCmdBaseUpdateOpts(cmdBase, options) { + cmdBase.new = options.returnDocument === exports.ReturnDocument.AFTER; + cmdBase.upsert = options.upsert === true; + if (options.bypassDocumentValidation === true) { + cmdBase.bypassDocumentValidation = options.bypassDocumentValidation; + } + return cmdBase; +} +/** @internal */ +class FindAndModifyOperation extends command_1.CommandOperation { + constructor(collection, query, options) { + super(collection, options); + this.options = options !== null && options !== void 0 ? options : {}; + this.cmdBase = { + remove: false, + new: false, + upsert: false + }; + const sort = (0, sort_1.formatSort)(options.sort); + if (sort) { + this.cmdBase.sort = sort; + } + if (options.projection) { + this.cmdBase.fields = options.projection; + } + if (options.maxTimeMS) { + this.cmdBase.maxTimeMS = options.maxTimeMS; + } + // Decorate the findAndModify command with the write Concern + if (options.writeConcern) { + this.cmdBase.writeConcern = options.writeConcern; + } + if (options.let) { + this.cmdBase.let = options.let; + } + // we check for undefined specifically here to allow falsy values + // eslint-disable-next-line no-restricted-syntax + if (options.comment !== undefined) { + this.cmdBase.comment = options.comment; + } + // force primary read preference + this.readPreference = read_preference_1.ReadPreference.primary; + this.collection = collection; + this.query = query; + } + execute(server, session, callback) { + var _a; + const coll = this.collection; + const query = this.query; + const options = { ...this.options, ...this.bsonOptions }; + // Create findAndModify command object + const cmd = { + findAndModify: coll.collectionName, + query: query, + ...this.cmdBase + }; + // Have we specified collation + try { + (0, utils_1.decorateWithCollation)(cmd, coll, options); + } + catch (err) { + return callback(err); + } + if (options.hint) { + // TODO: once this method becomes a CommandOperation we will have the server + // in place to check. + const unacknowledgedWrite = ((_a = this.writeConcern) === null || _a === void 0 ? void 0 : _a.w) === 0; + if (unacknowledgedWrite || (0, utils_1.maxWireVersion)(server) < 8) { + callback(new error_1.MongoCompatibilityError('The current topology does not support a hint on findAndModify commands')); + return; + } + cmd.hint = options.hint; + } + if (this.explain && (0, utils_1.maxWireVersion)(server) < 4) { + callback(new error_1.MongoCompatibilityError(`Server ${server.name} does not support explain on findAndModify`)); + return; + } + // Execute the command + super.executeCommand(server, session, cmd, (err, result) => { + if (err) + return callback(err); + return callback(undefined, result); + }); + } +} +/** @internal */ +class FindOneAndDeleteOperation extends FindAndModifyOperation { + constructor(collection, filter, options) { + // Basic validation + if (filter == null || typeof filter !== 'object') { + throw new error_1.MongoInvalidArgumentError('Argument "filter" must be an object'); + } + super(collection, filter, options); + this.cmdBase.remove = true; + } +} +exports.FindOneAndDeleteOperation = FindOneAndDeleteOperation; +/** @internal */ +class FindOneAndReplaceOperation extends FindAndModifyOperation { + constructor(collection, filter, replacement, options) { + if (filter == null || typeof filter !== 'object') { + throw new error_1.MongoInvalidArgumentError('Argument "filter" must be an object'); + } + if (replacement == null || typeof replacement !== 'object') { + throw new error_1.MongoInvalidArgumentError('Argument "replacement" must be an object'); + } + if ((0, utils_1.hasAtomicOperators)(replacement)) { + throw new error_1.MongoInvalidArgumentError('Replacement document must not contain atomic operators'); + } + super(collection, filter, options); + this.cmdBase.update = replacement; + configureFindAndModifyCmdBaseUpdateOpts(this.cmdBase, options); + } +} +exports.FindOneAndReplaceOperation = FindOneAndReplaceOperation; +/** @internal */ +class FindOneAndUpdateOperation extends FindAndModifyOperation { + constructor(collection, filter, update, options) { + if (filter == null || typeof filter !== 'object') { + throw new error_1.MongoInvalidArgumentError('Argument "filter" must be an object'); + } + if (update == null || typeof update !== 'object') { + throw new error_1.MongoInvalidArgumentError('Argument "update" must be an object'); + } + if (!(0, utils_1.hasAtomicOperators)(update)) { + throw new error_1.MongoInvalidArgumentError('Update document requires atomic operators'); + } + super(collection, filter, options); + this.cmdBase.update = update; + configureFindAndModifyCmdBaseUpdateOpts(this.cmdBase, options); + if (options.arrayFilters) { + this.cmdBase.arrayFilters = options.arrayFilters; + } + } +} +exports.FindOneAndUpdateOperation = FindOneAndUpdateOperation; +(0, operation_1.defineAspects)(FindAndModifyOperation, [ + operation_1.Aspect.WRITE_OPERATION, + operation_1.Aspect.RETRYABLE, + operation_1.Aspect.EXPLAINABLE +]); +//# sourceMappingURL=find_and_modify.js.map \ No newline at end of file diff --git a/ts-ticket-office-service/node_modules/mongodb/lib/operations/find_and_modify.js.map b/ts-ticket-office-service/node_modules/mongodb/lib/operations/find_and_modify.js.map new file mode 100644 index 000000000..2d6262aff --- /dev/null +++ b/ts-ticket-office-service/node_modules/mongodb/lib/operations/find_and_modify.js.map @@ -0,0 +1 @@ +{"version":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AAM,CAAC;QAC7B,uCAAuC,CAAC,IAAI,CAAC,OAAO,EAAE,OAAO,CAAC,CAAC;QAE/D,IAAI,OAAO,CAAC,YAAY,EAAE;YACxB,IAAI,CAAC,OAAO,CAAC,YAAY,GAAG,OAAO,CAAC,YAAY,CAAC;SAClD;IACH,CAAC;CACF;AA3BD,8DA2BC;AAED,IAAA,yBAAa,EAAC,sBAAsB,EAAE;IACpC,kBAAM,CAAC,eAAe;IACtB,kBAAM,CAAC,SAAS;IAChB,kBAAM,CAAC,WAAW;CACnB,CAAC,CAAC"} \ No newline at end of file diff --git a/ts-ticket-office-service/node_modules/mongodb/lib/operations/get_more.js b/ts-ticket-office-service/node_modules/mongodb/lib/operations/get_more.js new file mode 100644 index 000000000..3988b1b78 --- /dev/null +++ b/ts-ticket-office-service/node_modules/mongodb/lib/operations/get_more.js @@ -0,0 +1,33 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.GetMoreOperation = void 0; +const error_1 = require("../error"); +const utils_1 = require("../utils"); +const operation_1 = require("./operation"); +/** @internal */ +class GetMoreOperation extends operation_1.AbstractOperation { + constructor(ns, cursorId, server, options = {}) { + super(options); + this.options = options; + // comment on getMore is only supported for server versions 4.4 and above + if ((0, utils_1.maxWireVersion)(server) < 9) { + delete this.options.comment; + } + this.ns = ns; + this.cursorId = cursorId; + this.server = server; + } + /** + * Although there is a server already associated with the get more operation, the signature + * for execute passes a server so we will just use that one. + */ + execute(server, session, callback) { + if (server !== this.server) { + return callback(new error_1.MongoRuntimeError('Getmore must run on the same server operation began on')); + } + server.getMore(this.ns, this.cursorId, this.options, callback); + } +} +exports.GetMoreOperation = GetMoreOperation; +(0, operation_1.defineAspects)(GetMoreOperation, [operation_1.Aspect.READ_OPERATION, operation_1.Aspect.MUST_SELECT_SAME_SERVER]); +//# sourceMappingURL=get_more.js.map \ No newline at end of file diff --git a/ts-ticket-office-service/node_modules/mongodb/lib/operations/get_more.js.map b/ts-ticket-office-service/node_modules/mongodb/lib/operations/get_more.js.map new file mode 100644 index 000000000..f7668b0cf --- /dev/null +++ b/ts-ticket-office-service/node_modules/mongodb/lib/operations/get_more.js.map @@ -0,0 +1 @@ +{"version":3,"file":"get_more.js","sourceRoot":"","sources":["../../src/operations/get_more.ts"],"names":[],"mappings":";;;AACA,oCAA6C;AAG7C,oCAAsE;AACtE,2CAAyF;AAmBzF,gBAAgB;AAChB,MAAa,gBAAiB,SAAQ,6BAAiB;IAIrD,YAAY,EAAoB,EAAE,QAAc,EAAE,MAAc,EAAE,UAA0B,EAAE;QAC5F,KAAK,CAAC,OAAO,CAAC,CAAC;QAEf,IAAI,CAAC,OAAO,GAAG,OAAO,CAAC;QAEvB,yEAAyE;QACzE,IAAI,IAAA,sBAAc,EAAC,MAAM,CAAC,GAAG,CAAC,EAAE;YAC9B,OAAO,IAAI,CAAC,OAAO,CAAC,OAAO,CAAC;SAC7B;QAED,IAAI,CAAC,EAAE,GAAG,EAAE,CAAC;QACb,IAAI,CAAC,QAAQ,GAAG,QAAQ,CAAC;QACzB,IAAI,CAAC,MAAM,GAAG,MAAM,CAAC;IACvB,CAAC;IAED;;;OAGG;IACM,OAAO,CACd,MAAc,EACd,OAAkC,EAClC,QAA4B;QAE5B,IAAI,MAAM,KAAK,IAAI,CAAC,MAAM,EAAE;YAC1B,OAAO,QAAQ,CACb,IAAI,yBAAiB,CAAC,wDAAwD,CAAC,CAChF,CAAC;SACH;QACD,MAAM,CAAC,OAAO,CAAC,IAAI,CAAC,EAAE,EAAE,IAAI,CAAC,QAAQ,EAAE,IAAI,CAAC,OAAO,EAAE,QAAQ,CAAC,CAAC;IACjE,CAAC;CACF;AAnCD,4CAmCC;AAED,IAAA,yBAAa,EAAC,gBAAgB,EAAE,CAAC,kBAAM,CAAC,cAAc,EAAE,kBAAM,CAAC,uBAAuB,CAAC,CAAC,CAAC"} \ No newline at end of file diff --git a/ts-ticket-office-service/node_modules/mongodb/lib/operations/indexes.js b/ts-ticket-office-service/node_modules/mongodb/lib/operations/indexes.js new file mode 100644 index 000000000..d5a8cf076 --- /dev/null +++ b/ts-ticket-office-service/node_modules/mongodb/lib/operations/indexes.js @@ -0,0 +1,265 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.IndexInformationOperation = exports.IndexExistsOperation = exports.ListIndexesOperation = exports.DropIndexesOperation = exports.DropIndexOperation = exports.EnsureIndexOperation = exports.CreateIndexOperation = exports.CreateIndexesOperation = exports.IndexesOperation = void 0; +const error_1 = require("../error"); +const read_preference_1 = require("../read_preference"); +const utils_1 = require("../utils"); +const command_1 = require("./command"); +const common_functions_1 = require("./common_functions"); +const operation_1 = require("./operation"); +const VALID_INDEX_OPTIONS = new Set([ + 'background', + 'unique', + 'name', + 'partialFilterExpression', + 'sparse', + 'hidden', + 'expireAfterSeconds', + 'storageEngine', + 'collation', + 'version', + // text indexes + 'weights', + 'default_language', + 'language_override', + 'textIndexVersion', + // 2d-sphere indexes + '2dsphereIndexVersion', + // 2d indexes + 'bits', + 'min', + 'max', + // geoHaystack Indexes + 'bucketSize', + // wildcard indexes + 'wildcardProjection' +]); +function makeIndexSpec(indexSpec, options) { + const indexParameters = (0, utils_1.parseIndexOptions)(indexSpec); + // Generate the index name + const name = typeof options.name === 'string' ? options.name : indexParameters.name; + // Set up the index + const finalIndexSpec = { name, key: indexParameters.fieldHash }; + // merge valid index options into the index spec + for (const optionName in options) { + if (VALID_INDEX_OPTIONS.has(optionName)) { + finalIndexSpec[optionName] = options[optionName]; + } + } + return finalIndexSpec; +} +/** @internal */ +class IndexesOperation extends operation_1.AbstractOperation { + constructor(collection, options) { + super(options); + this.options = options; + this.collection = collection; + } + execute(server, session, callback) { + const coll = this.collection; + const options = this.options; + (0, common_functions_1.indexInformation)(coll.s.db, coll.collectionName, { full: true, ...options, readPreference: this.readPreference, session }, callback); + } +} +exports.IndexesOperation = IndexesOperation; +/** @internal */ +class CreateIndexesOperation extends command_1.CommandOperation { + constructor(parent, collectionName, indexes, options) { + super(parent, options); + this.options = options !== null && options !== void 0 ? options : {}; + this.collectionName = collectionName; + this.indexes = indexes; + } + execute(server, session, callback) { + const options = this.options; + const indexes = this.indexes; + const serverWireVersion = (0, utils_1.maxWireVersion)(server); + // Ensure we generate the correct name if the parameter is not set + for (let i = 0; i < indexes.length; i++) { + // Did the user pass in a collation, check if our write server supports it + if (indexes[i].collation && serverWireVersion < 5) { + callback(new error_1.MongoCompatibilityError(`Server ${server.name}, which reports wire version ${serverWireVersion}, ` + + 'does not support collation')); + return; + } + if (indexes[i].name == null) { + const keys = []; + for (const name in indexes[i].key) { + keys.push(`${name}_${indexes[i].key[name]}`); + } + // Set the name + indexes[i].name = keys.join('_'); + } + } + const cmd = { createIndexes: this.collectionName, indexes }; + if (options.commitQuorum != null) { + if (serverWireVersion < 9) { + callback(new error_1.MongoCompatibilityError('Option `commitQuorum` for `createIndexes` not supported on servers < 4.4')); + return; + } + cmd.commitQuorum = options.commitQuorum; + } + // collation is set on each index, it should not be defined at the root + this.options.collation = undefined; + super.executeCommand(server, session, cmd, err => { + if (err) { + callback(err); + return; + } + const indexNames = indexes.map(index => index.name || ''); + callback(undefined, indexNames); + }); + } +} +exports.CreateIndexesOperation = CreateIndexesOperation; +/** @internal */ +class CreateIndexOperation extends CreateIndexesOperation { + constructor(parent, collectionName, indexSpec, options) { + // createIndex can be called with a variety of styles: + // coll.createIndex('a'); + // coll.createIndex({ a: 1 }); + // coll.createIndex([['a', 1]]); + // createIndexes is always called with an array of index spec objects + super(parent, collectionName, [makeIndexSpec(indexSpec, options)], options); + } + execute(server, session, callback) { + super.execute(server, session, (err, indexNames) => { + if (err || !indexNames) + return callback(err); + return callback(undefined, indexNames[0]); + }); + } +} +exports.CreateIndexOperation = CreateIndexOperation; +/** @internal */ +class EnsureIndexOperation extends CreateIndexOperation { + constructor(db, collectionName, indexSpec, options) { + super(db, collectionName, indexSpec, options); + this.readPreference = read_preference_1.ReadPreference.primary; + this.db = db; + this.collectionName = collectionName; + } + execute(server, session, callback) { + const indexName = this.indexes[0].name; + const cursor = this.db.collection(this.collectionName).listIndexes({ session }); + cursor.toArray((err, indexes) => { + /// ignore "NamespaceNotFound" errors + if (err && err.code !== error_1.MONGODB_ERROR_CODES.NamespaceNotFound) { + return callback(err); + } + if (indexes) { + indexes = Array.isArray(indexes) ? indexes : [indexes]; + if (indexes.some(index => index.name === indexName)) { + callback(undefined, indexName); + return; + } + } + super.execute(server, session, callback); + }); + } +} +exports.EnsureIndexOperation = EnsureIndexOperation; +/** @internal */ +class DropIndexOperation extends command_1.CommandOperation { + constructor(collection, indexName, options) { + super(collection, options); + this.options = options !== null && options !== void 0 ? options : {}; + this.collection = collection; + this.indexName = indexName; + } + execute(server, session, callback) { + const cmd = { dropIndexes: this.collection.collectionName, index: this.indexName }; + super.executeCommand(server, session, cmd, callback); + } +} +exports.DropIndexOperation = DropIndexOperation; +/** @internal */ +class DropIndexesOperation extends DropIndexOperation { + constructor(collection, options) { + super(collection, '*', options); + } + execute(server, session, callback) { + super.execute(server, session, err => { + if (err) + return callback(err, false); + callback(undefined, true); + }); + } +} +exports.DropIndexesOperation = DropIndexesOperation; +/** @internal */ +class ListIndexesOperation extends command_1.CommandOperation { + constructor(collection, options) { + super(collection, options); + this.options = options !== null && options !== void 0 ? options : {}; + this.collectionNamespace = collection.s.namespace; + } + execute(server, session, callback) { + const serverWireVersion = (0, utils_1.maxWireVersion)(server); + const cursor = this.options.batchSize ? { batchSize: this.options.batchSize } : {}; + const command = { listIndexes: this.collectionNamespace.collection, cursor }; + // we check for undefined specifically here to allow falsy values + // eslint-disable-next-line no-restricted-syntax + if (serverWireVersion >= 9 && this.options.comment !== undefined) { + command.comment = this.options.comment; + } + super.executeCommand(server, session, command, callback); + } +} +exports.ListIndexesOperation = ListIndexesOperation; +/** @internal */ +class IndexExistsOperation extends operation_1.AbstractOperation { + constructor(collection, indexes, options) { + super(options); + this.options = options; + this.collection = collection; + this.indexes = indexes; + } + execute(server, session, callback) { + const coll = this.collection; + const indexes = this.indexes; + (0, common_functions_1.indexInformation)(coll.s.db, coll.collectionName, { ...this.options, readPreference: this.readPreference, session }, (err, indexInformation) => { + // If we have an error return + if (err != null) + return callback(err); + // Let's check for the index names + if (!Array.isArray(indexes)) + return callback(undefined, indexInformation[indexes] != null); + // Check in list of indexes + for (let i = 0; i < indexes.length; i++) { + if (indexInformation[indexes[i]] == null) { + return callback(undefined, false); + } + } + // All keys found return true + return callback(undefined, true); + }); + } +} +exports.IndexExistsOperation = IndexExistsOperation; +/** @internal */ +class IndexInformationOperation extends operation_1.AbstractOperation { + constructor(db, name, options) { + super(options); + this.options = options !== null && options !== void 0 ? options : {}; + this.db = db; + this.name = name; + } + execute(server, session, callback) { + const db = this.db; + const name = this.name; + (0, common_functions_1.indexInformation)(db, name, { ...this.options, readPreference: this.readPreference, session }, callback); + } +} +exports.IndexInformationOperation = IndexInformationOperation; +(0, operation_1.defineAspects)(ListIndexesOperation, [ + operation_1.Aspect.READ_OPERATION, + operation_1.Aspect.RETRYABLE, + operation_1.Aspect.CURSOR_CREATING +]); +(0, operation_1.defineAspects)(CreateIndexesOperation, [operation_1.Aspect.WRITE_OPERATION]); +(0, operation_1.defineAspects)(CreateIndexOperation, [operation_1.Aspect.WRITE_OPERATION]); +(0, operation_1.defineAspects)(EnsureIndexOperation, [operation_1.Aspect.WRITE_OPERATION]); +(0, operation_1.defineAspects)(DropIndexOperation, [operation_1.Aspect.WRITE_OPERATION]); +(0, operation_1.defineAspects)(DropIndexesOperation, [operation_1.Aspect.WRITE_OPERATION]); +//# sourceMappingURL=indexes.js.map \ No newline at end of file diff --git a/ts-ticket-office-service/node_modules/mongodb/lib/operations/indexes.js.map b/ts-ticket-office-service/node_modules/mongodb/lib/operations/indexes.js.map new file mode 100644 index 000000000..ce88d8e94 --- /dev/null +++ b/ts-ticket-office-service/node_modules/mongodb/lib/operations/indexes.js.map @@ -0,0 +1 @@ +{"version":3,"file":"indexes.js","sourceRoot":"","sources":["../../src/operations/indexes.ts"],"names":[],"m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AoB,EAAE,CAAC,kBAAM,CAAC,eAAe,CAAC,CAAC,CAAC;AAC9D,IAAA,yBAAa,EAAC,oBAAoB,EAAE,CAAC,kBAAM,CAAC,eAAe,CAAC,CAAC,CAAC;AAC9D,IAAA,yBAAa,EAAC,kBAAkB,EAAE,CAAC,kBAAM,CAAC,eAAe,CAAC,CAAC,CAAC;AAC5D,IAAA,yBAAa,EAAC,oBAAoB,EAAE,CAAC,kBAAM,CAAC,eAAe,CAAC,CAAC,CAAC"} \ No newline at end of file diff --git a/ts-ticket-office-service/node_modules/mongodb/lib/operations/insert.js b/ts-ticket-office-service/node_modules/mongodb/lib/operations/insert.js new file mode 100644 index 000000000..aa617b487 --- /dev/null +++ b/ts-ticket-office-service/node_modules/mongodb/lib/operations/insert.js @@ -0,0 +1,99 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.InsertManyOperation = exports.InsertOneOperation = exports.InsertOperation = void 0; +const error_1 = require("../error"); +const write_concern_1 = require("../write_concern"); +const bulk_write_1 = require("./bulk_write"); +const command_1 = require("./command"); +const common_functions_1 = require("./common_functions"); +const operation_1 = require("./operation"); +/** @internal */ +class InsertOperation extends command_1.CommandOperation { + constructor(ns, documents, options) { + var _a; + super(undefined, options); + this.options = { ...options, checkKeys: (_a = options.checkKeys) !== null && _a !== void 0 ? _a : false }; + this.ns = ns; + this.documents = documents; + } + execute(server, session, callback) { + var _a; + const options = (_a = this.options) !== null && _a !== void 0 ? _a : {}; + const ordered = typeof options.ordered === 'boolean' ? options.ordered : true; + const command = { + insert: this.ns.collection, + documents: this.documents, + ordered + }; + if (typeof options.bypassDocumentValidation === 'boolean') { + command.bypassDocumentValidation = options.bypassDocumentValidation; + } + // we check for undefined specifically here to allow falsy values + // eslint-disable-next-line no-restricted-syntax + if (options.comment !== undefined) { + command.comment = options.comment; + } + super.executeCommand(server, session, command, callback); + } +} +exports.InsertOperation = InsertOperation; +class InsertOneOperation extends InsertOperation { + constructor(collection, doc, options) { + super(collection.s.namespace, (0, common_functions_1.prepareDocs)(collection, [doc], options), options); + } + execute(server, session, callback) { + super.execute(server, session, (err, res) => { + var _a, _b; + if (err || res == null) + return callback(err); + if (res.code) + return callback(new error_1.MongoServerError(res)); + if (res.writeErrors) { + // This should be a WriteError but we can't change it now because of error hierarchy + return callback(new error_1.MongoServerError(res.writeErrors[0])); + } + callback(undefined, { + acknowledged: (_b = ((_a = this.writeConcern) === null || _a === void 0 ? void 0 : _a.w) !== 0) !== null && _b !== void 0 ? _b : true, + insertedId: this.documents[0]._id + }); + }); + } +} +exports.InsertOneOperation = InsertOneOperation; +/** @internal */ +class InsertManyOperation extends operation_1.AbstractOperation { + constructor(collection, docs, options) { + super(options); + if (!Array.isArray(docs)) { + throw new error_1.MongoInvalidArgumentError('Argument "docs" must be an array of documents'); + } + this.options = options; + this.collection = collection; + this.docs = docs; + } + execute(server, session, callback) { + const coll = this.collection; + const options = { ...this.options, ...this.bsonOptions, readPreference: this.readPreference }; + const writeConcern = write_concern_1.WriteConcern.fromOptions(options); + const bulkWriteOperation = new bulk_write_1.BulkWriteOperation(coll, (0, common_functions_1.prepareDocs)(coll, this.docs, options).map(document => ({ insertOne: { document } })), options); + bulkWriteOperation.execute(server, session, (err, res) => { + var _a; + if (err || res == null) { + if (err && err.message === 'Operation must be an object with an operation key') { + err = new error_1.MongoInvalidArgumentError('Collection.insertMany() cannot be called with an array that has null/undefined values'); + } + return callback(err); + } + callback(undefined, { + acknowledged: (_a = (writeConcern === null || writeConcern === void 0 ? void 0 : writeConcern.w) !== 0) !== null && _a !== void 0 ? _a : true, + insertedCount: res.insertedCount, + insertedIds: res.insertedIds + }); + }); + } +} +exports.InsertManyOperation = InsertManyOperation; +(0, operation_1.defineAspects)(InsertOperation, [operation_1.Aspect.RETRYABLE, operation_1.Aspect.WRITE_OPERATION]); +(0, operation_1.defineAspects)(InsertOneOperation, [operation_1.Aspect.RETRYABLE, operation_1.Aspect.WRITE_OPERATION]); +(0, operation_1.defineAspects)(InsertManyOperation, [operation_1.Aspect.WRITE_OPERATION]); +//# sourceMappingURL=insert.js.map \ No newline at end of file diff --git a/ts-ticket-office-service/node_modules/mongodb/lib/operations/insert.js.map b/ts-ticket-office-service/node_modules/mongodb/lib/operations/insert.js.map new file mode 100644 index 000000000..67a93dde3 --- /dev/null +++ b/ts-ticket-office-service/node_modules/mongodb/lib/operations/insert.js.map @@ -0,0 +1 @@ +{"version":3,"file":"insert.js","sourceRoot":"","sources":["../../src/operations/insert.ts"],"names":[],"mappings":";;;AAGA,oCAAuE;AAKvE,oDAAgD;AAChD,6CAAkD;AAClD,uCAAsE;AACtE,yDAAiD;AACjD,2CAAuE;AAEvE,gBAAgB;AAChB,MAAa,eAAgB,SAAQ,0BAA0B;IAI7D,YAAY,EAAoB,EAAE,SAAqB,EAAE,OAAyB;;QAChF,KAAK,CAAC,SAAS,EAAE,OAAO,CAAC,CAAC;QAC1B,IAAI,CAAC,OAAO,GAAG,EAAE,GAAG,OAAO,EAAE,SAAS,EAAE,MAAA,OAAO,CAAC,SAAS,mCAAI,KAAK,EAAE,CAAC;QACrE,IAAI,CAAC,EAAE,GAAG,EAAE,CAAC;QACb,IAAI,CAAC,SAAS,GAAG,SAAS,CAAC;IAC7B,CAAC;IAEQ,OAAO,CACd,MAAc,EACd,OAAkC,EAClC,QAA4B;;QAE5B,MAAM,OAAO,GAAG,MAAA,IAAI,CAAC,OAAO,mCAAI,EAAE,CAAC;QACnC,MAAM,OAAO,GAAG,OAAO,OAAO,CAAC,OAAO,KAAK,SAAS,CAAC,CAAC,CAAC,OAAO,CAAC,OAAO,CAAC,CAAC,CAAC,IAAI,CAAC;QAC9E,MAAM,OAAO,GAAa;YACxB,MAAM,EAAE,IAAI,CAAC,EAAE,CAAC,UAAU;YAC1B,SAAS,EAAE,IAAI,CAAC,SAAS;YACzB,OAAO;SACR,CAAC;QAEF,IAAI,OAAO,OAAO,CAAC,wBAAwB,KAAK,SAAS,EAAE;YACzD,OAAO,CAAC,wBAAwB,GA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CAAyB,CACjC,uFAAuF,CACxF,CAAC;iBACH;gBACD,OAAO,QAAQ,CAAC,GAAG,CAAC,CAAC;aACtB;YACD,QAAQ,CAAC,SAAS,EAAE;gBAClB,YAAY,EAAE,MAAA,CAAA,YAAY,aAAZ,YAAY,uBAAZ,YAAY,CAAE,CAAC,MAAK,CAAC,mCAAI,IAAI;gBAC3C,aAAa,EAAE,GAAG,CAAC,aAAa;gBAChC,WAAW,EAAE,GAAG,CAAC,WAAW;aAC7B,CAAC,CAAC;QACL,CAAC,CAAC,CAAC;IACL,CAAC;CACF;AA/CD,kDA+CC;AAED,IAAA,yBAAa,EAAC,eAAe,EAAE,CAAC,kBAAM,CAAC,SAAS,EAAE,kBAAM,CAAC,eAAe,CAAC,CAAC,CAAC;AAC3E,IAAA,yBAAa,EAAC,kBAAkB,EAAE,CAAC,kBAAM,CAAC,SAAS,EAAE,kBAAM,CAAC,eAAe,CAAC,CAAC,CAAC;AAC9E,IAAA,yBAAa,EAAC,mBAAmB,EAAE,CAAC,kBAAM,CAAC,eAAe,CAAC,CAAC,CAAC"} \ No newline at end of file diff --git a/ts-ticket-office-service/node_modules/mongodb/lib/operations/is_capped.js b/ts-ticket-office-service/node_modules/mongodb/lib/operations/is_capped.js new file mode 100644 index 000000000..dd2917a6d --- /dev/null +++ b/ts-ticket-office-service/node_modules/mongodb/lib/operations/is_capped.js @@ -0,0 +1,30 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.IsCappedOperation = void 0; +const error_1 = require("../error"); +const operation_1 = require("./operation"); +/** @internal */ +class IsCappedOperation extends operation_1.AbstractOperation { + constructor(collection, options) { + super(options); + this.options = options; + this.collection = collection; + } + execute(server, session, callback) { + const coll = this.collection; + coll.s.db + .listCollections({ name: coll.collectionName }, { ...this.options, nameOnly: false, readPreference: this.readPreference, session }) + .toArray((err, collections) => { + if (err || !collections) + return callback(err); + if (collections.length === 0) { + // TODO(NODE-3485) + return callback(new error_1.MongoAPIError(`collection ${coll.namespace} not found`)); + } + const collOptions = collections[0].options; + callback(undefined, !!(collOptions && collOptions.capped)); + }); + } +} +exports.IsCappedOperation = IsCappedOperation; +//# sourceMappingURL=is_capped.js.map \ No newline at end of file diff --git a/ts-ticket-office-service/node_modules/mongodb/lib/operations/is_capped.js.map b/ts-ticket-office-service/node_modules/mongodb/lib/operations/is_capped.js.map new file mode 100644 index 000000000..13a584207 --- /dev/null +++ b/ts-ticket-office-service/node_modules/mongodb/lib/operations/is_capped.js.map @@ -0,0 +1 @@ +{"version":3,"file":"is_capped.js","sourceRoot":"","sources":["../../src/operations/is_capped.ts"],"names":[],"mappings":";;;AACA,oCAAyC;AAIzC,2CAAkE;AAElE,gBAAgB;AAChB,MAAa,iBAAkB,SAAQ,6BAA0B;IAI/D,YAAY,UAAsB,EAAE,OAAyB;QAC3D,KAAK,CAAC,OAAO,CAAC,CAAC;QACf,IAAI,CAAC,OAAO,GAAG,OAAO,CAAC;QACvB,IAAI,CAAC,UAAU,GAAG,UAAU,CAAC;IAC/B,CAAC;IAEQ,OAAO,CACd,MAAc,EACd,OAAkC,EAClC,QAA2B;QAE3B,MAAM,IAAI,GAAG,IAAI,CAAC,UAAU,CAAC;QAE7B,IAAI,CAAC,CAAC,CAAC,EAAE;aACN,eAAe,CACd,EAAE,IAAI,EAAE,IAAI,CAAC,cAAc,EAAE,EAC7B,EAAE,GAAG,IAAI,CAAC,OAAO,EAAE,QAAQ,EAAE,KAAK,EAAE,cAAc,EAAE,IAAI,CAAC,cAAc,EAAE,OAAO,EAAE,CACnF;aACA,OAAO,CAAC,CAAC,GAAG,EAAE,WAAW,EAAE,EAAE;YAC5B,IAAI,GAAG,IAAI,CAAC,WAAW;gBAAE,OAAO,QAAQ,CAAC,GAAG,CAAC,CAAC;YAC9C,IAAI,WAAW,CAAC,MAAM,KAAK,CAAC,EAAE;gBAC5B,kBAAkB;gBAClB,OAAO,QAAQ,CAAC,IAAI,qBAAa,CAAC,cAAc,IAAI,CAAC,SAAS,YAAY,CAAC,CAAC,CAAC;aAC9E;YAED,MAAM,WAAW,GAAG,WAAW,CAAC,CAAC,CAAC,CAAC,OAAO,CAAC;YAC3C,QAAQ,CAAC,SAAS,EAAE,CAAC,CAAC,CAAC,WAAW,IAAI,WAAW,CAAC,MAAM,CAAC,CAAC,CAAC;QAC7D,CAAC,CAAC,CAAC;IACP,CAAC;CACF;AAjCD,8CAiCC"} \ No newline at end of file diff --git a/ts-ticket-office-service/node_modules/mongodb/lib/operations/kill_cursors.js b/ts-ticket-office-service/node_modules/mongodb/lib/operations/kill_cursors.js new file mode 100644 index 000000000..75e625476 --- /dev/null +++ b/ts-ticket-office-service/node_modules/mongodb/lib/operations/kill_cursors.js @@ -0,0 +1,22 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.KillCursorsOperation = void 0; +const error_1 = require("../error"); +const operation_1 = require("./operation"); +class KillCursorsOperation extends operation_1.AbstractOperation { + constructor(cursorId, ns, server, options) { + super(options); + this.ns = ns; + this.cursorId = cursorId; + this.server = server; + } + execute(server, session, callback) { + if (server !== this.server) { + return callback(new error_1.MongoRuntimeError('Killcursor must run on the same server operation began on')); + } + server.killCursors(this.ns, [this.cursorId], { session }, () => callback()); + } +} +exports.KillCursorsOperation = KillCursorsOperation; +(0, operation_1.defineAspects)(KillCursorsOperation, [operation_1.Aspect.MUST_SELECT_SAME_SERVER]); +//# sourceMappingURL=kill_cursors.js.map \ No newline at end of file diff --git a/ts-ticket-office-service/node_modules/mongodb/lib/operations/kill_cursors.js.map b/ts-ticket-office-service/node_modules/mongodb/lib/operations/kill_cursors.js.map new file mode 100644 index 000000000..d44790a77 --- /dev/null +++ b/ts-ticket-office-service/node_modules/mongodb/lib/operations/kill_cursors.js.map @@ -0,0 +1 @@ +{"version":3,"file":"kill_cursors.js","sourceRoot":"","sources":["../../src/operations/kill_cursors.ts"],"names":[],"mappings":";;;AACA,oCAA6C;AAI7C,2CAAyF;AAEzF,MAAa,oBAAqB,SAAQ,6BAAiB;IAEzD,YAAY,QAAc,EAAE,EAAoB,EAAE,MAAc,EAAE,OAAyB;QACzF,KAAK,CAAC,OAAO,CAAC,CAAC;QACf,IAAI,CAAC,EAAE,GAAG,EAAE,CAAC;QACb,IAAI,CAAC,QAAQ,GAAG,QAAQ,CAAC;QACzB,IAAI,CAAC,MAAM,GAAG,MAAM,CAAC;IACvB,CAAC;IAED,OAAO,CAAC,MAAc,EAAE,OAAkC,EAAE,QAAwB;QAClF,IAAI,MAAM,KAAK,IAAI,CAAC,MAAM,EAAE;YAC1B,OAAO,QAAQ,CACb,IAAI,yBAAiB,CAAC,2DAA2D,CAAC,CACnF,CAAC;SACH;QACD,MAAM,CAAC,WAAW,CAAC,IAAI,CAAC,EAAE,EAAE,CAAC,IAAI,CAAC,QAAQ,CAAC,EAAE,EAAE,OAAO,EAAE,EAAE,GAAG,EAAE,CAAC,QAAQ,EAAE,CAAC,CAAC;IAC9E,CAAC;CACF;AAjBD,oDAiBC;AAED,IAAA,yBAAa,EAAC,oBAAoB,EAAE,CAAC,kBAAM,CAAC,uBAAuB,CAAC,CAAC,CAAC"} \ No newline at end of file diff --git a/ts-ticket-office-service/node_modules/mongodb/lib/operations/list_collections.js b/ts-ticket-office-service/node_modules/mongodb/lib/operations/list_collections.js new file mode 100644 index 000000000..4badea166 --- /dev/null +++ b/ts-ticket-office-service/node_modules/mongodb/lib/operations/list_collections.js @@ -0,0 +1,46 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.ListCollectionsOperation = void 0; +const utils_1 = require("../utils"); +const command_1 = require("./command"); +const operation_1 = require("./operation"); +/** @internal */ +class ListCollectionsOperation extends command_1.CommandOperation { + constructor(db, filter, options) { + super(db, options); + this.options = options !== null && options !== void 0 ? options : {}; + this.db = db; + this.filter = filter; + this.nameOnly = !!this.options.nameOnly; + this.authorizedCollections = !!this.options.authorizedCollections; + if (typeof this.options.batchSize === 'number') { + this.batchSize = this.options.batchSize; + } + } + execute(server, session, callback) { + return super.executeCommand(server, session, this.generateCommand((0, utils_1.maxWireVersion)(server)), callback); + } + /* This is here for the purpose of unit testing the final command that gets sent. */ + generateCommand(wireVersion) { + const command = { + listCollections: 1, + filter: this.filter, + cursor: this.batchSize ? { batchSize: this.batchSize } : {}, + nameOnly: this.nameOnly, + authorizedCollections: this.authorizedCollections + }; + // we check for undefined specifically here to allow falsy values + // eslint-disable-next-line no-restricted-syntax + if (wireVersion >= 9 && this.options.comment !== undefined) { + command.comment = this.options.comment; + } + return command; + } +} +exports.ListCollectionsOperation = ListCollectionsOperation; +(0, operation_1.defineAspects)(ListCollectionsOperation, [ + operation_1.Aspect.READ_OPERATION, + operation_1.Aspect.RETRYABLE, + operation_1.Aspect.CURSOR_CREATING +]); +//# sourceMappingURL=list_collections.js.map \ No newline at end of file diff --git a/ts-ticket-office-service/node_modules/mongodb/lib/operations/list_collections.js.map b/ts-ticket-office-service/node_modules/mongodb/lib/operations/list_collections.js.map new file mode 100644 index 000000000..615be1329 --- /dev/null +++ b/ts-ticket-office-service/node_modules/mongodb/lib/operations/list_collections.js.map @@ -0,0 +1 @@ +{"version":3,"file":"list_collections.js","sourceRoot":"","sources":["../../src/operations/list_collections.ts"],"names":[],"mappings":";;;AAIA,oCAAoD;AACpD,uCAAsE;AACtE,2CAAoD;AAYpD,gBAAgB;AAChB,MAAa,wBAAyB,SAAQ,0BAA0B;IAQtE,YAAY,EAAM,EAAE,MAAgB,EAAE,OAAgC;QACpE,KAAK,CAAC,EAAE,EAAE,OAAO,CAAC,CAAC;QAEnB,IAAI,CAAC,OAAO,GAAG,OAAO,aAAP,OAAO,cAAP,OAAO,GAAI,EAAE,CAAC;QAC7B,IAAI,CAAC,EAAE,GAAG,EAAE,CAAC;QACb,IAAI,CAAC,MAAM,GAAG,MAAM,CAAC;QACrB,IAAI,CAAC,QAAQ,GAAG,CAAC,CAAC,IAAI,CAAC,OAAO,CAAC,QAAQ,CAAC;QACxC,IAAI,CAAC,qBAAqB,GAAG,CAAC,CAAC,IAAI,CAAC,OAAO,CAAC,qBAAqB,CAAC;QAElE,IAAI,OAAO,IAAI,CAAC,OAAO,CAAC,SAAS,KAAK,QAAQ,EAAE;YAC9C,IAAI,CAAC,SAAS,GAAG,IAAI,CAAC,OAAO,CAAC,SAAS,CAAC;SACzC;IACH,CAAC;IAEQ,OAAO,CACd,MAAc,EACd,OAAkC,EAClC,QAA4B;QAE5B,OAAO,KAAK,CAAC,cAAc,CACzB,MAAM,EACN,OAAO,EACP,IAAI,CAAC,eAAe,CAAC,IAAA,sBAAc,EAAC,MAAM,CAAC,CAAC,EAC5C,QAAQ,CACT,CAAC;IACJ,CAAC;IAED,oFAAoF;IACpF,eAAe,CAAC,WAAmB;QACjC,MAAM,OAAO,GAAa;YACxB,eAAe,EAAE,CAAC;YAClB,MAAM,EAAE,IAAI,CAAC,MAAM;YACnB,MAAM,EAAE,IAAI,CAAC,SAAS,CAAC,CAAC,CAAC,EAAE,SAAS,EAAE,IAAI,CAAC,SAAS,EAAE,CAAC,CAAC,CAAC,EAAE;YAC3D,QAAQ,EAAE,IAAI,CAAC,QAAQ;YACvB,qBAAqB,EAAE,IAAI,CAAC,qBAAqB;SAClD,CAAC;QAEF,iEAAiE;QACjE,gDAAgD;QAChD,IAAI,WAAW,IAAI,CAAC,IAAI,IAAI,CAAC,OAAO,CAAC,OAAO,KAAK,SAAS,EAAE;YAC1D,OAAO,CAAC,OAAO,GAAG,IAAI,CAAC,OAAO,CAAC,OAAO,CAAC;SACxC;QAED,OAAO,OAAO,CAAC;IACjB,CAAC;CACF;AArDD,4DAqDC;AAcD,IAAA,yBAAa,EAAC,wBAAwB,EAAE;IACtC,kBAAM,CAAC,cAAc;IACrB,kBAAM,CAAC,SAAS;IAChB,kBAAM,CAAC,eAAe;CACvB,CAAC,CAAC"} \ No newline at end of file diff --git a/ts-ticket-office-service/node_modules/mongodb/lib/operations/list_databases.js b/ts-ticket-office-service/node_modules/mongodb/lib/operations/list_databases.js new file mode 100644 index 000000000..967ab4e40 --- /dev/null +++ b/ts-ticket-office-service/node_modules/mongodb/lib/operations/list_databases.js @@ -0,0 +1,35 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.ListDatabasesOperation = void 0; +const utils_1 = require("../utils"); +const command_1 = require("./command"); +const operation_1 = require("./operation"); +/** @internal */ +class ListDatabasesOperation extends command_1.CommandOperation { + constructor(db, options) { + super(db, options); + this.options = options !== null && options !== void 0 ? options : {}; + this.ns = new utils_1.MongoDBNamespace('admin', '$cmd'); + } + execute(server, session, callback) { + const cmd = { listDatabases: 1 }; + if (this.options.nameOnly) { + cmd.nameOnly = Number(cmd.nameOnly); + } + if (this.options.filter) { + cmd.filter = this.options.filter; + } + if (typeof this.options.authorizedDatabases === 'boolean') { + cmd.authorizedDatabases = this.options.authorizedDatabases; + } + // we check for undefined specifically here to allow falsy values + // eslint-disable-next-line no-restricted-syntax + if ((0, utils_1.maxWireVersion)(server) >= 9 && this.options.comment !== undefined) { + cmd.comment = this.options.comment; + } + super.executeCommand(server, session, cmd, callback); + } +} +exports.ListDatabasesOperation = ListDatabasesOperation; +(0, operation_1.defineAspects)(ListDatabasesOperation, [operation_1.Aspect.READ_OPERATION, operation_1.Aspect.RETRYABLE]); +//# sourceMappingURL=list_databases.js.map \ No newline at end of file diff --git a/ts-ticket-office-service/node_modules/mongodb/lib/operations/list_databases.js.map b/ts-ticket-office-service/node_modules/mongodb/lib/operations/list_databases.js.map new file mode 100644 index 000000000..8ea522d41 --- /dev/null +++ b/ts-ticket-office-service/node_modules/mongodb/lib/operations/list_databases.js.map @@ -0,0 +1 @@ +{"version":3,"file":"list_databases.js","sourceRoot":"","sources":["../../src/operations/list_databases.ts"],"names":[],"mappings":";;;AAIA,oCAAsE;AACtE,uCAAsE;AACtE,2CAAoD;AAoBpD,gBAAgB;AAChB,MAAa,sBAAuB,SAAQ,0BAAqC;IAG/E,YAAY,EAAM,EAAE,OAA8B;QAChD,KAAK,CAAC,EAAE,EAAE,OAAO,CAAC,CAAC;QACnB,IAAI,CAAC,OAAO,GAAG,OAAO,aAAP,OAAO,cAAP,OAAO,GAAI,EAAE,CAAC;QAC7B,IAAI,CAAC,EAAE,GAAG,IAAI,wBAAgB,CAAC,OAAO,EAAE,MAAM,CAAC,CAAC;IAClD,CAAC;IAEQ,OAAO,CACd,MAAc,EACd,OAAkC,EAClC,QAAuC;QAEvC,MAAM,GAAG,GAAa,EAAE,aAAa,EAAE,CAAC,EAAE,CAAC;QAC3C,IAAI,IAAI,CAAC,OAAO,CAAC,QAAQ,EAAE;YACzB,GAAG,CAAC,QAAQ,GAAG,MAAM,CAAC,GAAG,CAAC,QAAQ,CAAC,CAAC;SACrC;QAED,IAAI,IAAI,CAAC,OAAO,CAAC,MAAM,EAAE;YACvB,GAAG,CAAC,MAAM,GAAG,IAAI,CAAC,OAAO,CAAC,MAAM,CAAC;SAClC;QAED,IAAI,OAAO,IAAI,CAAC,OAAO,CAAC,mBAAmB,KAAK,SAAS,EAAE;YACzD,GAAG,CAAC,mBAAmB,GAAG,IAAI,CAAC,OAAO,CAAC,mBAAmB,CAAC;SAC5D;QAED,iEAAiE;QACjE,gDAAgD;QAChD,IAAI,IAAA,sBAAc,EAAC,MAAM,CAAC,IAAI,CAAC,IAAI,IAAI,CAAC,OAAO,CAAC,OAAO,KAAK,SAAS,EAAE;YACrE,GAAG,CAAC,OAAO,GAAG,IAAI,CAAC,OAAO,CAAC,OAAO,CAAC;SACpC;QAED,KAAK,CAAC,cAAc,CAAC,MAAM,EAAE,OAAO,EAAE,GAAG,EAAE,QAAQ,CAAC,CAAC;IACvD,CAAC;CACF;AAnCD,wDAmCC;AAED,IAAA,yBAAa,EAAC,sBAAsB,EAAE,CAAC,kBAAM,CAAC,cAAc,EAAE,kBAAM,CAAC,SAAS,CAAC,CAAC,CAAC"} \ No newline at end of file diff --git a/ts-ticket-office-service/node_modules/mongodb/lib/operations/map_reduce.js b/ts-ticket-office-service/node_modules/mongodb/lib/operations/map_reduce.js new file mode 100644 index 000000000..43f63a43f --- /dev/null +++ b/ts-ticket-office-service/node_modules/mongodb/lib/operations/map_reduce.js @@ -0,0 +1,166 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.MapReduceOperation = void 0; +const bson_1 = require("../bson"); +const error_1 = require("../error"); +const read_preference_1 = require("../read_preference"); +const utils_1 = require("../utils"); +const command_1 = require("./command"); +const operation_1 = require("./operation"); +const exclusionList = [ + 'explain', + 'readPreference', + 'readConcern', + 'session', + 'bypassDocumentValidation', + 'writeConcern', + 'raw', + 'fieldsAsRaw', + 'promoteLongs', + 'promoteValues', + 'promoteBuffers', + 'bsonRegExp', + 'serializeFunctions', + 'ignoreUndefined', + 'enableUtf8Validation', + 'scope' // this option is reformatted thus exclude the original +]; +/** + * Run Map Reduce across a collection. Be aware that the inline option for out will return an array of results not a collection. + * @internal + */ +class MapReduceOperation extends command_1.CommandOperation { + /** + * Constructs a MapReduce operation. + * + * @param collection - Collection instance. + * @param map - The mapping function. + * @param reduce - The reduce function. + * @param options - Optional settings. See Collection.prototype.mapReduce for a list of options. + */ + constructor(collection, map, reduce, options) { + super(collection, options); + this.options = options !== null && options !== void 0 ? options : {}; + this.collection = collection; + this.map = map; + this.reduce = reduce; + } + execute(server, session, callback) { + const coll = this.collection; + const map = this.map; + const reduce = this.reduce; + let options = this.options; + const mapCommandHash = { + mapReduce: coll.collectionName, + map: map, + reduce: reduce + }; + if (options.scope) { + mapCommandHash.scope = processScope(options.scope); + } + // Add any other options passed in + for (const n in options) { + // Only include if not in exclusion list + if (exclusionList.indexOf(n) === -1) { + mapCommandHash[n] = options[n]; + } + } + options = Object.assign({}, options); + // If we have a read preference and inline is not set as output fail hard + if (this.readPreference.mode === read_preference_1.ReadPreferenceMode.primary && + options.out && + options.out.inline !== 1 && + options.out !== 'inline') { + // Force readPreference to primary + options.readPreference = read_preference_1.ReadPreference.primary; + // Decorate command with writeConcern if supported + (0, utils_1.applyWriteConcern)(mapCommandHash, { db: coll.s.db, collection: coll }, options); + } + else { + (0, utils_1.decorateWithReadConcern)(mapCommandHash, coll, options); + } + // Is bypassDocumentValidation specified + if (options.bypassDocumentValidation === true) { + mapCommandHash.bypassDocumentValidation = options.bypassDocumentValidation; + } + // Have we specified collation + try { + (0, utils_1.decorateWithCollation)(mapCommandHash, coll, options); + } + catch (err) { + return callback(err); + } + if (this.explain && (0, utils_1.maxWireVersion)(server) < 9) { + callback(new error_1.MongoCompatibilityError(`Server ${server.name} does not support explain on mapReduce`)); + return; + } + // Execute command + super.executeCommand(server, session, mapCommandHash, (err, result) => { + if (err) + return callback(err); + // Check if we have an error + if (1 !== result.ok || result.err || result.errmsg) { + return callback(new error_1.MongoServerError(result)); + } + // If an explain option was executed, don't process the server results + if (this.explain) + return callback(undefined, result); + // Create statistics value + const stats = {}; + if (result.timeMillis) + stats['processtime'] = result.timeMillis; + if (result.counts) + stats['counts'] = result.counts; + if (result.timing) + stats['timing'] = result.timing; + // invoked with inline? + if (result.results) { + // If we wish for no verbosity + if (options['verbose'] == null || !options['verbose']) { + return callback(undefined, result.results); + } + return callback(undefined, { results: result.results, stats: stats }); + } + // The returned collection + let collection = null; + // If we have an object it's a different db + if (result.result != null && typeof result.result === 'object') { + const doc = result.result; + // Return a collection from another db + collection = coll.s.db.s.client.db(doc.db, coll.s.db.s.options).collection(doc.collection); + } + else { + // Create a collection object that wraps the result collection + collection = coll.s.db.collection(result.result); + } + // If we wish for no verbosity + if (options['verbose'] == null || !options['verbose']) { + return callback(err, collection); + } + // Return stats as third set of values + callback(err, { collection, stats }); + }); + } +} +exports.MapReduceOperation = MapReduceOperation; +/** Functions that are passed as scope args must be converted to Code instances. */ +function processScope(scope) { + if (!(0, utils_1.isObject)(scope) || scope._bsontype === 'ObjectID') { + return scope; + } + const newScope = {}; + for (const key of Object.keys(scope)) { + if ('function' === typeof scope[key]) { + newScope[key] = new bson_1.Code(String(scope[key])); + } + else if (scope[key]._bsontype === 'Code') { + newScope[key] = scope[key]; + } + else { + newScope[key] = processScope(scope[key]); + } + } + return newScope; +} +(0, operation_1.defineAspects)(MapReduceOperation, [operation_1.Aspect.EXPLAINABLE]); +//# sourceMappingURL=map_reduce.js.map \ No newline at end of file diff --git a/ts-ticket-office-service/node_modules/mongodb/lib/operations/map_reduce.js.map b/ts-ticket-office-service/node_modules/mongodb/lib/operations/map_reduce.js.map new file mode 100644 index 000000000..0cab777c7 --- /dev/null +++ b/ts-ticket-office-service/node_modules/mongodb/lib/operations/map_reduce.js.map @@ -0,0 +1 @@ +{"version":3,"file":"map_reduce.js","sourceRoot":"","sources":["../../src/operations/map_reduce.ts"],"names":[],"mappings":";;;AACA,kCAAyC;AAEzC,oCAAqE;AACrE,wDAAwE;AAIxE,oCAOkB;AAClB,uCAAsE;AACtE,2CAAoD;AAEpD,MAAM,aAAa,GAAG;IACpB,SAAS;IACT,gBAAgB;IAChB,aAAa;IACb,SAAS;IACT,0BAA0B;IAC1B,cAAc;IACd,KAAK;IACL,aAAa;IACb,cAAc;IACd,eAAe;IACf,gBAAgB;IAChB,YAAY;IACZ,oBAAoB;IACpB,iBAAiB;IACjB,sBAAsB;IACtB,OAAO,CAAC,uDAAuD;CAChE,CAAC;AA2CF;;;GAGG;AACH,MAAa,kBAAmB,SAAQ,0BAAuC;IAQ7E;;;;;;;OAOG;IACH,YACE,UAAsB,EACtB,GAAyB,EACzB,MAA+B,EAC/B,OAA0B;QAE1B,KAAK,CAAC,UAAU,EAAE,OAAO,CAAC,CAAC;QAE3B,IAAI,CAAC,OAAO,GAAG,OAAO,aAAP,OAAO,cAAP,OAAO,GAAI,EAAE,CAAC;QAC7B,IAAI,CAAC,UAAU,GAAG,UAAU,CAAC;QAC7B,IAAI,CAAC,GAAG,GAAG,GAAG,CAAC;QACf,IAAI,CAAC,MAAM,GAAG,MAAM,CAAC;IACvB,CAAC;IAEQ,OAAO,CACd,MAAc,EACd,OAAkC,EAClC,QAAyC;QAEzC,MAAM,IAAI,GAAG,IAAI,CAAC,UAAU,CAAC;QAC7B,MAAM,G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A/ID,gDA+IC;AAED,mFAAmF;AACnF,SAAS,YAAY,CAAC,KAA0B;IAC9C,IAAI,CAAC,IAAA,gBAAQ,EAAC,KAAK,CAAC,IAAK,KAAa,CAAC,SAAS,KAAK,UAAU,EAAE;QAC/D,OAAO,KAAK,CAAC;KACd;IAED,MAAM,QAAQ,GAAa,EAAE,CAAC;IAE9B,KAAK,MAAM,GAAG,IAAI,MAAM,CAAC,IAAI,CAAC,KAAK,CAAC,EAAE;QACpC,IAAI,UAAU,KAAK,OAAQ,KAAkB,CAAC,GAAG,CAAC,EAAE;YAClD,QAAQ,CAAC,GAAG,CAAC,GAAG,IAAI,WAAI,CAAC,MAAM,CAAE,KAAkB,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC;SAC5D;aAAM,IAAK,KAAkB,CAAC,GAAG,CAAC,CAAC,SAAS,KAAK,MAAM,EAAE;YACxD,QAAQ,CAAC,GAAG,CAAC,GAAI,KAAkB,CAAC,GAAG,CAAC,CAAC;SAC1C;aAAM;YACL,QAAQ,CAAC,GAAG,CAAC,GAAG,YAAY,CAAE,KAAkB,CAAC,GAAG,CAAC,CAAC,CAAC;SACxD;KACF;IAED,OAAO,QAAQ,CAAC;AAClB,CAAC;AAED,IAAA,yBAAa,EAAC,kBAAkB,EAAE,CAAC,kBAAM,CAAC,WAAW,CAAC,CAAC,CAAC"} \ No newline at end of file diff --git a/ts-ticket-office-service/node_modules/mongodb/lib/operations/operation.js b/ts-ticket-office-service/node_modules/mongodb/lib/operations/operation.js new file mode 100644 index 000000000..2f6c54fba --- /dev/null +++ b/ts-ticket-office-service/node_modules/mongodb/lib/operations/operation.js @@ -0,0 +1,70 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.defineAspects = exports.AbstractOperation = exports.Aspect = void 0; +const bson_1 = require("../bson"); +const read_preference_1 = require("../read_preference"); +exports.Aspect = { + READ_OPERATION: Symbol('READ_OPERATION'), + WRITE_OPERATION: Symbol('WRITE_OPERATION'), + RETRYABLE: Symbol('RETRYABLE'), + EXPLAINABLE: Symbol('EXPLAINABLE'), + SKIP_COLLATION: Symbol('SKIP_COLLATION'), + CURSOR_CREATING: Symbol('CURSOR_CREATING'), + MUST_SELECT_SAME_SERVER: Symbol('MUST_SELECT_SAME_SERVER') +}; +/** @internal */ +const kSession = Symbol('session'); +/** + * This class acts as a parent class for any operation and is responsible for setting this.options, + * as well as setting and getting a session. + * Additionally, this class implements `hasAspect`, which determines whether an operation has + * a specific aspect. + * @internal + */ +class AbstractOperation { + constructor(options = {}) { + var _a; + this.readPreference = this.hasAspect(exports.Aspect.WRITE_OPERATION) + ? read_preference_1.ReadPreference.primary + : (_a = read_preference_1.ReadPreference.fromOptions(options)) !== null && _a !== void 0 ? _a : read_preference_1.ReadPreference.primary; + // Pull the BSON serialize options from the already-resolved options + this.bsonOptions = (0, bson_1.resolveBSONOptions)(options); + this[kSession] = options.session != null ? options.session : undefined; + this.options = options; + this.bypassPinningCheck = !!options.bypassPinningCheck; + this.trySecondaryWrite = false; + } + hasAspect(aspect) { + const ctor = this.constructor; + if (ctor.aspects == null) { + return false; + } + return ctor.aspects.has(aspect); + } + get session() { + return this[kSession]; + } + clearSession() { + this[kSession] = undefined; + } + get canRetryRead() { + return true; + } + get canRetryWrite() { + return true; + } +} +exports.AbstractOperation = AbstractOperation; +function defineAspects(operation, aspects) { + if (!Array.isArray(aspects) && !(aspects instanceof Set)) { + aspects = [aspects]; + } + aspects = new Set(aspects); + Object.defineProperty(operation, 'aspects', { + value: aspects, + writable: false + }); + return aspects; +} +exports.defineAspects = defineAspects; +//# sourceMappingURL=operation.js.map \ No newline at end of file diff --git a/ts-ticket-office-service/node_modules/mongodb/lib/operations/operation.js.map b/ts-ticket-office-service/node_modules/mongodb/lib/operations/operation.js.map new file mode 100644 index 000000000..b5d2ae070 --- /dev/null +++ b/ts-ticket-office-service/node_modules/mongodb/lib/operations/operation.js.map @@ -0,0 +1 @@ +{"version":3,"file":"operation.js","sourceRoot":"","sources":["../../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IAAI,CAAC,OAAO,IAAI,IAAI,EAAE;YACxB,OAAO,KAAK,CAAC;SACd;QAED,OAAO,IAAI,CAAC,OAAO,CAAC,GAAG,CAAC,MAAM,CAAC,CAAC;IAClC,CAAC;IAED,IAAI,OAAO;QACT,OAAO,IAAI,CAAC,QAAQ,CAAC,CAAC;IACxB,CAAC;IAED,YAAY;QACV,IAAI,CAAC,QAAQ,CAAC,GAAG,SAAS,CAAC;IAC7B,CAAC;IAED,IAAI,YAAY;QACd,OAAO,IAAI,CAAC;IACd,CAAC;IAED,IAAI,aAAa;QACf,OAAO,IAAI,CAAC;IACd,CAAC;CACF;AA5DD,8CA4DC;AAED,SAAgB,aAAa,CAC3B,SAA+B,EAC/B,OAAwC;IAExC,IAAI,CAAC,KAAK,CAAC,OAAO,CAAC,OAAO,CAAC,IAAI,CAAC,CAAC,OAAO,YAAY,GAAG,CAAC,EAAE;QACxD,OAAO,GAAG,CAAC,OAAO,CAAC,CAAC;KACrB;IAED,OAAO,GAAG,IAAI,GAAG,CAAC,OAAO,CAAC,CAAC;IAC3B,MAAM,CAAC,cAAc,CAAC,SAAS,EAAE,SAAS,EAAE;QAC1C,KAAK,EAAE,OAAO;QACd,QAAQ,EAAE,KAAK;KAChB,CAAC,CAAC;IAEH,OAAO,OAAO,CAAC;AACjB,CAAC;AAfD,sCAeC"} \ No newline at end of file diff --git a/ts-ticket-office-service/node_modules/mongodb/lib/operations/options_operation.js b/ts-ticket-office-service/node_modules/mongodb/lib/operations/options_operation.js new file mode 100644 index 000000000..f07f104dc --- /dev/null +++ b/ts-ticket-office-service/node_modules/mongodb/lib/operations/options_operation.js @@ -0,0 +1,29 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.OptionsOperation = void 0; +const error_1 = require("../error"); +const operation_1 = require("./operation"); +/** @internal */ +class OptionsOperation extends operation_1.AbstractOperation { + constructor(collection, options) { + super(options); + this.options = options; + this.collection = collection; + } + execute(server, session, callback) { + const coll = this.collection; + coll.s.db + .listCollections({ name: coll.collectionName }, { ...this.options, nameOnly: false, readPreference: this.readPreference, session }) + .toArray((err, collections) => { + if (err || !collections) + return callback(err); + if (collections.length === 0) { + // TODO(NODE-3485) + return callback(new error_1.MongoAPIError(`collection ${coll.namespace} not found`)); + } + callback(err, collections[0].options); + }); + } +} +exports.OptionsOperation = OptionsOperation; +//# sourceMappingURL=options_operation.js.map \ No newline at end of file diff --git a/ts-ticket-office-service/node_modules/mongodb/lib/operations/options_operation.js.map b/ts-ticket-office-service/node_modules/mongodb/lib/operations/options_operation.js.map new file mode 100644 index 000000000..9d6b05c00 --- /dev/null +++ b/ts-ticket-office-service/node_modules/mongodb/lib/operations/options_operation.js.map @@ -0,0 +1 @@ +{"version":3,"file":"options_operation.js","sourceRoot":"","sources":["../../src/operations/options_operation.ts"],"names":[],"mappings":";;;AAEA,oCAAyC;AAIzC,2CAAkE;AAElE,gBAAgB;AAChB,MAAa,gBAAiB,SAAQ,6BAA2B;IAI/D,YAAY,UAAsB,EAAE,OAAyB;QAC3D,KAAK,CAAC,OAAO,CAAC,CAAC;QACf,IAAI,CAAC,OAAO,GAAG,OAAO,CAAC;QACvB,IAAI,CAAC,UAAU,GAAG,UAAU,CAAC;IAC/B,CAAC;IAEQ,OAAO,CACd,MAAc,EACd,OAAkC,EAClC,QAA4B;QAE5B,MAAM,IAAI,GAAG,IAAI,CAAC,UAAU,CAAC;QAE7B,IAAI,CAAC,CAAC,CAAC,EAAE;aACN,eAAe,CACd,EAAE,IAAI,EAAE,IAAI,CAAC,cAAc,EAAE,EAC7B,EAAE,GAAG,IAAI,CAAC,OAAO,EAAE,QAAQ,EAAE,KAAK,EAAE,cAAc,EAAE,IAAI,CAAC,cAAc,EAAE,OAAO,EAAE,CACnF;aACA,OAAO,CAAC,CAAC,GAAG,EAAE,WAAW,EAAE,EAAE;YAC5B,IAAI,GAAG,IAAI,CAAC,WAAW;gBAAE,OAAO,QAAQ,CAAC,GAAG,CAAC,CAAC;YAC9C,IAAI,WAAW,CAAC,MAAM,KAAK,CAAC,EAAE;gBAC5B,kBAAkB;gBAClB,OAAO,QAAQ,CAAC,IAAI,qBAAa,CAAC,cAAc,IAAI,CAAC,SAAS,YAAY,CAAC,CAAC,CAAC;aAC9E;YAED,QAAQ,CAAC,GAAG,EAAE,WAAW,CAAC,CAAC,CAAC,CAAC,OAAO,CAAC,CAAC;QACxC,CAAC,CAAC,CAAC;IACP,CAAC;CACF;AAhCD,4CAgCC"} \ No newline at end of file diff --git a/ts-ticket-office-service/node_modules/mongodb/lib/operations/profiling_level.js b/ts-ticket-office-service/node_modules/mongodb/lib/operations/profiling_level.js new file mode 100644 index 000000000..33802dfa2 --- /dev/null +++ b/ts-ticket-office-service/node_modules/mongodb/lib/operations/profiling_level.js @@ -0,0 +1,33 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.ProfilingLevelOperation = void 0; +const error_1 = require("../error"); +const command_1 = require("./command"); +/** @internal */ +class ProfilingLevelOperation extends command_1.CommandOperation { + constructor(db, options) { + super(db, options); + this.options = options; + } + execute(server, session, callback) { + super.executeCommand(server, session, { profile: -1 }, (err, doc) => { + if (err == null && doc.ok === 1) { + const was = doc.was; + if (was === 0) + return callback(undefined, 'off'); + if (was === 1) + return callback(undefined, 'slow_only'); + if (was === 2) + return callback(undefined, 'all'); + // TODO(NODE-3483) + return callback(new error_1.MongoRuntimeError(`Illegal profiling level value ${was}`)); + } + else { + // TODO(NODE-3483): Consider MongoUnexpectedServerResponseError + err != null ? callback(err) : callback(new error_1.MongoRuntimeError('Error with profile command')); + } + }); + } +} +exports.ProfilingLevelOperation = ProfilingLevelOperation; +//# sourceMappingURL=profiling_level.js.map \ No newline at end of file diff --git a/ts-ticket-office-service/node_modules/mongodb/lib/operations/profiling_level.js.map b/ts-ticket-office-service/node_modules/mongodb/lib/operations/profiling_level.js.map new file mode 100644 index 000000000..8630fdc00 --- /dev/null +++ b/ts-ticket-office-service/node_modules/mongodb/lib/operations/profiling_level.js.map @@ -0,0 +1 @@ +{"version":3,"file":"profiling_level.js","sourceRoot":"","sources":["../../src/operations/profiling_level.ts"],"names":[],"mappings":";;;AACA,oCAA6C;AAI7C,uCAAsE;AAKtE,gBAAgB;AAChB,MAAa,uBAAwB,SAAQ,0BAAwB;IAGnE,YAAY,EAAM,EAAE,OAA8B;QAChD,KAAK,CAAC,EAAE,EAAE,OAAO,CAAC,CAAC;QACnB,IAAI,CAAC,OAAO,GAAG,OAAO,CAAC;IACzB,CAAC;IAEQ,OAAO,CACd,MAAc,EACd,OAAkC,EAClC,QAA0B;QAE1B,KAAK,CAAC,cAAc,CAAC,MAAM,EAAE,OAAO,EAAE,EAAE,OAAO,EAAE,CAAC,CAAC,EAAE,EAAE,CAAC,GAAG,EAAE,GAAG,EAAE,EAAE;YAClE,IAAI,GAAG,IAAI,IAAI,IAAI,GAAG,CAAC,EAAE,KAAK,CAAC,EAAE;gBAC/B,MAAM,GAAG,GAAG,GAAG,CAAC,GAAG,CAAC;gBACpB,IAAI,GAAG,KAAK,CAAC;oBAAE,OAAO,QAAQ,CAAC,SAAS,EAAE,KAAK,CAAC,CAAC;gBACjD,IAAI,GAAG,KAAK,CAAC;oBAAE,OAAO,QAAQ,CAAC,SAAS,EAAE,WAAW,CAAC,CAAC;gBACvD,IAAI,GAAG,KAAK,CAAC;oBAAE,OAAO,QAAQ,CAAC,SAAS,EAAE,KAAK,CAAC,CAAC;gBACjD,kBAAkB;gBAClB,OAAO,QAAQ,CAAC,IAAI,yBAAiB,CAAC,iCAAiC,GAAG,EAAE,CAAC,CAAC,CAAC;aAChF;iBAAM;gBACL,+DAA+D;gBAC/D,GAAG,IAAI,IAAI,CAAC,CAAC,CAAC,QAAQ,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC,QAAQ,CAAC,IAAI,yBAAiB,CAAC,4BAA4B,CAAC,CAAC,CAAC;aAC7F;QACH,CAAC,CAAC,CAAC;IACL,CAAC;CACF;AA3BD,0DA2BC"} \ No newline at end of file diff --git a/ts-ticket-office-service/node_modules/mongodb/lib/operations/remove_user.js b/ts-ticket-office-service/node_modules/mongodb/lib/operations/remove_user.js new file mode 100644 index 000000000..daab3ebff --- /dev/null +++ b/ts-ticket-office-service/node_modules/mongodb/lib/operations/remove_user.js @@ -0,0 +1,21 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.RemoveUserOperation = void 0; +const command_1 = require("./command"); +const operation_1 = require("./operation"); +/** @internal */ +class RemoveUserOperation extends command_1.CommandOperation { + constructor(db, username, options) { + super(db, options); + this.options = options; + this.username = username; + } + execute(server, session, callback) { + super.executeCommand(server, session, { dropUser: this.username }, err => { + callback(err, err ? false : true); + }); + } +} +exports.RemoveUserOperation = RemoveUserOperation; +(0, operation_1.defineAspects)(RemoveUserOperation, [operation_1.Aspect.WRITE_OPERATION]); +//# sourceMappingURL=remove_user.js.map \ No newline at end of file diff --git a/ts-ticket-office-service/node_modules/mongodb/lib/operations/remove_user.js.map b/ts-ticket-office-service/node_modules/mongodb/lib/operations/remove_user.js.map new file mode 100644 index 000000000..d689529ab --- /dev/null +++ b/ts-ticket-office-service/node_modules/mongodb/lib/operations/remove_user.js.map @@ -0,0 +1 @@ +{"version":3,"file":"remove_user.js","sourceRoot":"","sources":["../../src/operations/remove_user.ts"],"names":[],"mappings":";;;AAIA,uCAAsE;AACtE,2CAAoD;AAKpD,gBAAgB;AAChB,MAAa,mBAAoB,SAAQ,0BAAyB;IAIhE,YAAY,EAAM,EAAE,QAAgB,EAAE,OAA0B;QAC9D,KAAK,CAAC,EAAE,EAAE,OAAO,CAAC,CAAC;QACnB,IAAI,CAAC,OAAO,GAAG,OAAO,CAAC;QACvB,IAAI,CAAC,QAAQ,GAAG,QAAQ,CAAC;IAC3B,CAAC;IAEQ,OAAO,CACd,MAAc,EACd,OAAkC,EAClC,QAA2B;QAE3B,KAAK,CAAC,cAAc,CAAC,MAAM,EAAE,OAAO,EAAE,EAAE,QAAQ,EAAE,IAAI,CAAC,QAAQ,EAAE,EAAE,GAAG,CAAC,EAAE;YACvE,QAAQ,CAAC,GAAG,EAAE,GAAG,CAAC,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC,IAAI,CAAC,CAAC;QACpC,CAAC,CAAC,CAAC;IACL,CAAC;CACF;AAnBD,kDAmBC;AAED,IAAA,yBAAa,EAAC,mBAAmB,EAAE,CAAC,kBAAM,CAAC,eAAe,CAAC,CAAC,CAAC"} \ No newline at end of file diff --git a/ts-ticket-office-service/node_modules/mongodb/lib/operations/rename.js b/ts-ticket-office-service/node_modules/mongodb/lib/operations/rename.js new file mode 100644 index 000000000..06ec124d2 --- /dev/null +++ b/ts-ticket-office-service/node_modules/mongodb/lib/operations/rename.js @@ -0,0 +1,46 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.RenameOperation = void 0; +const collection_1 = require("../collection"); +const error_1 = require("../error"); +const utils_1 = require("../utils"); +const operation_1 = require("./operation"); +const run_command_1 = require("./run_command"); +/** @internal */ +class RenameOperation extends run_command_1.RunAdminCommandOperation { + constructor(collection, newName, options) { + // Check the collection name + (0, utils_1.checkCollectionName)(newName); + // Build the command + const renameCollection = collection.namespace; + const toCollection = collection.s.namespace.withCollection(newName).toString(); + const dropTarget = typeof options.dropTarget === 'boolean' ? options.dropTarget : false; + const cmd = { renameCollection: renameCollection, to: toCollection, dropTarget: dropTarget }; + super(collection, cmd, options); + this.options = options; + this.collection = collection; + this.newName = newName; + } + execute(server, session, callback) { + const coll = this.collection; + super.execute(server, session, (err, doc) => { + if (err) + return callback(err); + // We have an error + if (doc === null || doc === void 0 ? void 0 : doc.errmsg) { + return callback(new error_1.MongoServerError(doc)); + } + let newColl; + try { + newColl = new collection_1.Collection(coll.s.db, this.newName, coll.s.options); + } + catch (err) { + return callback(err); + } + return callback(undefined, newColl); + }); + } +} +exports.RenameOperation = RenameOperation; +(0, operation_1.defineAspects)(RenameOperation, [operation_1.Aspect.WRITE_OPERATION]); +//# sourceMappingURL=rename.js.map \ No newline at end of file diff --git a/ts-ticket-office-service/node_modules/mongodb/lib/operations/rename.js.map b/ts-ticket-office-service/node_modules/mongodb/lib/operations/rename.js.map new file mode 100644 index 000000000..03255d1cd --- /dev/null +++ b/ts-ticket-office-service/node_modules/mongodb/lib/operations/rename.js.map @@ -0,0 +1 @@ +{"version":3,"file":"rename.js","sourceRoot":"","sources":["../../src/operations/rename.ts"],"names":[],"mappings":";;;AACA,8CAA2C;AAC3C,oCAA4C;AAG5C,oCAAyD;AAEzD,2CAAoD;AACpD,+CAAyD;AAUzD,gBAAgB;AAChB,MAAa,eAAgB,SAAQ,sCAAwB;IAK3D,YAAY,UAAsB,EAAE,OAAe,EAAE,OAAsB;QACzE,4BAA4B;QAC5B,IAAA,2BAAmB,EAAC,OAAO,CAAC,CAAC;QAE7B,oBAAoB;QACpB,MAAM,gBAAgB,GAAG,UAAU,CAAC,SAAS,CAAC;QAC9C,MAAM,YAAY,GAAG,UAAU,CAAC,CAAC,CAAC,SAAS,CAAC,cAAc,CAAC,OAAO,CAAC,CAAC,QAAQ,EAAE,CAAC;QAC/E,MAAM,UAAU,GAAG,OAAO,OAAO,CAAC,UAAU,KAAK,SAAS,CAAC,CAAC,CAAC,OAAO,CAAC,UAAU,CAAC,CAAC,CAAC,KAAK,CAAC;QACxF,MAAM,GAAG,GAAG,EAAE,gBAAgB,EAAE,gBAAgB,EAAE,EAAE,EAAE,YAAY,EAAE,UAAU,EAAE,UAAU,EAAE,CAAC;QAE7F,KAAK,CAAC,UAAU,EAAE,GAAG,EAAE,OAAO,CAAC,CAAC;QAChC,IAAI,CAAC,OAAO,GAAG,OAAO,CAAC;QACvB,IAAI,CAAC,UAAU,GAAG,UAAU,CAAC;QAC7B,IAAI,CAAC,OAAO,GAAG,OAAO,CAAC;IACzB,CAAC;IAEQ,OAAO,CACd,MAAc,EACd,OAAkC,EAClC,QAA8B;QAE9B,MAAM,IAAI,GAAG,IAAI,CAAC,UAAU,CAAC;QAE7B,KAAK,CAAC,OAAO,CAAC,MAAM,EAAE,OAAO,EAAE,CAAC,GAAG,EAAE,GAAG,EAAE,EAAE;YAC1C,IAAI,GAAG;gBAAE,OAAO,QAAQ,CAAC,GAAG,CAAC,CAAC;YAC9B,mBAAmB;YACnB,IAAI,GAAG,aAAH,GAAG,uBAAH,GAAG,CAAE,MAAM,EAAE;gBACf,OAAO,QAAQ,CAAC,IAAI,wBAAgB,CAAC,GAAG,CAAC,CAAC,CAAC;aAC5C;YAED,IAAI,OAA6B,CAAC;YAClC,IAAI;gBACF,OAAO,GAAG,IAAI,uBAAU,CAAC,IAAI,CAAC,CAAC,CAAC,EAAE,EAAE,IAAI,CAAC,OAAO,EAAE,IAAI,CAAC,CAAC,CAAC,OAAO,CAAC,CAAC;aACnE;YAAC,OAAO,GAAG,EAAE;gBACZ,OAAO,QAAQ,CAAC,GAAG,CAAC,CAAC;aACtB;YAED,OAAO,QAAQ,CAAC,SAAS,EAAE,OAAO,CAAC,CAAC;QACtC,CAAC,CAAC,CAAC;IACL,CAAC;CACF;AA7CD,0CA6CC;AAED,IAAA,yBAAa,EAAC,eAAe,EAAE,CAAC,kBAAM,CAAC,eAAe,CAAC,CAAC,CAAC"} \ No newline at end of file diff --git a/ts-ticket-office-service/node_modules/mongodb/lib/operations/run_command.js b/ts-ticket-office-service/node_modules/mongodb/lib/operations/run_command.js new file mode 100644 index 000000000..3ebab39a4 --- /dev/null +++ b/ts-ticket-office-service/node_modules/mongodb/lib/operations/run_command.js @@ -0,0 +1,26 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.RunAdminCommandOperation = exports.RunCommandOperation = void 0; +const utils_1 = require("../utils"); +const command_1 = require("./command"); +/** @internal */ +class RunCommandOperation extends command_1.CommandOperation { + constructor(parent, command, options) { + super(parent, options); + this.options = options !== null && options !== void 0 ? options : {}; + this.command = command; + } + execute(server, session, callback) { + const command = this.command; + this.executeCommand(server, session, command, callback); + } +} +exports.RunCommandOperation = RunCommandOperation; +class RunAdminCommandOperation extends RunCommandOperation { + constructor(parent, command, options) { + super(parent, command, options); + this.ns = new utils_1.MongoDBNamespace('admin'); + } +} +exports.RunAdminCommandOperation = RunAdminCommandOperation; +//# sourceMappingURL=run_command.js.map \ No newline at end of file diff --git a/ts-ticket-office-service/node_modules/mongodb/lib/operations/run_command.js.map b/ts-ticket-office-service/node_modules/mongodb/lib/operations/run_command.js.map new file mode 100644 index 000000000..f698f3449 --- /dev/null +++ b/ts-ticket-office-service/node_modules/mongodb/lib/operations/run_command.js.map @@ -0,0 +1 @@ +{"version":3,"file":"run_command.js","sourceRoot":"","sources":["../../src/operations/run_command.ts"],"names":[],"mappings":";;;AAGA,oCAAsD;AACtD,uCAAuF;AAKvF,gBAAgB;AAChB,MAAa,mBAAkC,SAAQ,0BAAmB;IAIxE,YAAY,MAAmC,EAAE,OAAiB,EAAE,OAA2B;QAC7F,KAAK,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC;QACvB,IAAI,CAAC,OAAO,GAAG,OAAO,aAAP,OAAO,cAAP,OAAO,GAAI,EAAE,CAAC;QAC7B,IAAI,CAAC,OAAO,GAAG,OAAO,CAAC;IACzB,CAAC;IAEQ,OAAO,CACd,MAAc,EACd,OAAkC,EAClC,QAAqB;QAErB,MAAM,OAAO,GAAG,IAAI,CAAC,OAAO,CAAC;QAC7B,IAAI,CAAC,cAAc,CAAC,MAAM,EAAE,OAAO,EAAE,OAAO,EAAE,QAAQ,CAAC,CAAC;IAC1D,CAAC;CACF;AAlBD,kDAkBC;AAED,MAAa,wBAAuC,SAAQ,mBAAsB;IAChF,YAAY,MAAmC,EAAE,OAAiB,EAAE,OAA2B;QAC7F,KAAK,CAAC,MAAM,EAAE,OAAO,EAAE,OAAO,CAAC,CAAC;QAChC,IAAI,CAAC,EAAE,GAAG,IAAI,wBAAgB,CAAC,OAAO,CAAC,CAAC;IAC1C,CAAC;CACF;AALD,4DAKC"} \ No newline at end of file diff --git a/ts-ticket-office-service/node_modules/mongodb/lib/operations/set_profiling_level.js b/ts-ticket-office-service/node_modules/mongodb/lib/operations/set_profiling_level.js new file mode 100644 index 000000000..4ff83297d --- /dev/null +++ b/ts-ticket-office-service/node_modules/mongodb/lib/operations/set_profiling_level.js @@ -0,0 +1,51 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.SetProfilingLevelOperation = exports.ProfilingLevel = void 0; +const error_1 = require("../error"); +const utils_1 = require("../utils"); +const command_1 = require("./command"); +const levelValues = new Set(['off', 'slow_only', 'all']); +/** @public */ +exports.ProfilingLevel = Object.freeze({ + off: 'off', + slowOnly: 'slow_only', + all: 'all' +}); +/** @internal */ +class SetProfilingLevelOperation extends command_1.CommandOperation { + constructor(db, level, options) { + super(db, options); + this.options = options; + switch (level) { + case exports.ProfilingLevel.off: + this.profile = 0; + break; + case exports.ProfilingLevel.slowOnly: + this.profile = 1; + break; + case exports.ProfilingLevel.all: + this.profile = 2; + break; + default: + this.profile = 0; + break; + } + this.level = level; + } + execute(server, session, callback) { + const level = this.level; + if (!levelValues.has(level)) { + return callback(new error_1.MongoInvalidArgumentError(`Profiling level must be one of "${(0, utils_1.enumToString)(exports.ProfilingLevel)}"`)); + } + // TODO(NODE-3483): Determine error to put here + super.executeCommand(server, session, { profile: this.profile }, (err, doc) => { + if (err == null && doc.ok === 1) + return callback(undefined, level); + return err != null + ? callback(err) + : callback(new error_1.MongoRuntimeError('Error with profile command')); + }); + } +} +exports.SetProfilingLevelOperation = SetProfilingLevelOperation; +//# sourceMappingURL=set_profiling_level.js.map \ No newline at end of file diff --git a/ts-ticket-office-service/node_modules/mongodb/lib/operations/set_profiling_level.js.map b/ts-ticket-office-service/node_modules/mongodb/lib/operations/set_profiling_level.js.map new file mode 100644 index 000000000..4928b6165 --- /dev/null +++ b/ts-ticket-office-service/node_modules/mongodb/lib/operations/set_profiling_level.js.map @@ -0,0 +1 @@ +{"version":3,"file":"set_profiling_level.js","sourceRoot":"","sources":["../../src/operations/set_profiling_level.ts"],"names":[],"mappings":";;;AACA,oCAA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AAE,IAAI,CAAC,OAAO,EAAE,EAAE,CAAC,GAAG,EAAE,GAAG,EAAE,EAAE;YAC5E,IAAI,GAAG,IAAI,IAAI,IAAI,GAAG,CAAC,EAAE,KAAK,CAAC;gBAAE,OAAO,QAAQ,CAAC,SAAS,EAAE,KAAK,CAAC,CAAC;YACnE,OAAO,GAAG,IAAI,IAAI;gBAChB,CAAC,CAAC,QAAQ,CAAC,GAAG,CAAC;gBACf,CAAC,CAAC,QAAQ,CAAC,IAAI,yBAAiB,CAAC,4BAA4B,CAAC,CAAC,CAAC;QACpE,CAAC,CAAC,CAAC;IACL,CAAC;CACF;AAjDD,gEAiDC"} \ No newline at end of file diff --git a/ts-ticket-office-service/node_modules/mongodb/lib/operations/stats.js b/ts-ticket-office-service/node_modules/mongodb/lib/operations/stats.js new file mode 100644 index 000000000..21b736dfc --- /dev/null +++ b/ts-ticket-office-service/node_modules/mongodb/lib/operations/stats.js @@ -0,0 +1,48 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.DbStatsOperation = exports.CollStatsOperation = void 0; +const command_1 = require("./command"); +const operation_1 = require("./operation"); +/** + * Get all the collection statistics. + * @internal + */ +class CollStatsOperation extends command_1.CommandOperation { + /** + * Construct a Stats operation. + * + * @param collection - Collection instance + * @param options - Optional settings. See Collection.prototype.stats for a list of options. + */ + constructor(collection, options) { + super(collection, options); + this.options = options !== null && options !== void 0 ? options : {}; + this.collectionName = collection.collectionName; + } + execute(server, session, callback) { + const command = { collStats: this.collectionName }; + if (this.options.scale != null) { + command.scale = this.options.scale; + } + super.executeCommand(server, session, command, callback); + } +} +exports.CollStatsOperation = CollStatsOperation; +/** @internal */ +class DbStatsOperation extends command_1.CommandOperation { + constructor(db, options) { + super(db, options); + this.options = options; + } + execute(server, session, callback) { + const command = { dbStats: true }; + if (this.options.scale != null) { + command.scale = this.options.scale; + } + super.executeCommand(server, session, command, callback); + } +} +exports.DbStatsOperation = DbStatsOperation; +(0, operation_1.defineAspects)(CollStatsOperation, [operation_1.Aspect.READ_OPERATION]); +(0, operation_1.defineAspects)(DbStatsOperation, [operation_1.Aspect.READ_OPERATION]); +//# sourceMappingURL=stats.js.map \ No newline at end of file diff --git a/ts-ticket-office-service/node_modules/mongodb/lib/operations/stats.js.map b/ts-ticket-office-service/node_modules/mongodb/lib/operations/stats.js.map new file mode 100644 index 000000000..aca364553 --- /dev/null +++ b/ts-ticket-office-service/node_modules/mongodb/lib/operations/stats.js.map @@ -0,0 +1 @@ +{"version":3,"file":"stats.js","sourceRoot":"","sources":["../../src/operations/stats.ts"],"names":[],"mappings":";;;AAMA,uCAAsE;AACtE,2CAAoD;AAQpD;;;GAGG;AACH,MAAa,kBAAmB,SAAQ,0BAA0B;IAIhE;;;;;OAKG;IACH,YAAY,UAAsB,EAAE,OAA0B;QAC5D,KAAK,CAAC,UAAU,EAAE,OAAO,CAAC,CAAC;QAC3B,IAAI,CAAC,OAAO,GAAG,OAAO,aAAP,OAAO,cAAP,OAAO,GAAI,EAAE,CAAC;QAC7B,IAAI,CAAC,cAAc,GAAG,UAAU,CAAC,cAAc,CAAC;IAClD,CAAC;IAEQ,OAAO,CACd,MAAc,EACd,OAAkC,EAClC,QAA6B;QAE7B,MAAM,OAAO,GAAa,EAAE,SAAS,EAAE,IAAI,CAAC,cAAc,EAAE,CAAC;QAC7D,IAAI,IAAI,CAAC,OAAO,CAAC,KAAK,IAAI,IAAI,EAAE;YAC9B,OAAO,CAAC,KAAK,GAAG,IAAI,CAAC,OAAO,CAAC,KAAK,CAAC;SACpC;QAED,KAAK,CAAC,cAAc,CAAC,MAAM,EAAE,OAAO,EAAE,OAAO,EAAE,QAAQ,CAAC,CAAC;IAC3D,CAAC;CACF;AA5BD,gDA4BC;AAQD,gBAAgB;AAChB,MAAa,gBAAiB,SAAQ,0BAA0B;IAG9D,YAAY,EAAM,EAAE,OAAuB;QACzC,KAAK,CAAC,EAAE,EAAE,OAAO,CAAC,CAAC;QACnB,IAAI,CAAC,OAAO,GAAG,OAAO,CAAC;IACzB,CAAC;IAEQ,OAAO,CACd,MAAc,EACd,OAAkC,EAClC,QAA4B;QAE5B,MAAM,OAAO,GAAa,EAAE,OAAO,EAAE,IAAI,EAAE,CAAC;QAC5C,IAAI,IAAI,CAAC,OAAO,CAAC,KAAK,IAAI,IAAI,EAAE;YAC9B,OAAO,CAAC,KAAK,GAAG,IAAI,CAAC,OAAO,CAAC,KAAK,CAAC;SACpC;QAED,KAAK,CAAC,cAAc,CAAC,MAAM,EAAE,OAAO,EAAE,OAAO,EAAE,QAAQ,CAAC,CAAC;IAC3D,CAAC;CACF;AApBD,4CAoBC;AAiMD,IAAA,yBAAa,EAAC,kBAAkB,EAAE,CAAC,kBAAM,CAAC,cAAc,CAAC,CAAC,CAAC;AAC3D,IAAA,yBAAa,EAAC,gBAAgB,EAAE,CAAC,kBAAM,CAAC,cAAc,CAAC,CAAC,CAAC"} \ No newline at end of file diff --git a/ts-ticket-office-service/node_modules/mongodb/lib/operations/update.js b/ts-ticket-office-service/node_modules/mongodb/lib/operations/update.js new file mode 100644 index 000000000..03c825ec7 --- /dev/null +++ b/ts-ticket-office-service/node_modules/mongodb/lib/operations/update.js @@ -0,0 +1,200 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.makeUpdateStatement = exports.ReplaceOneOperation = exports.UpdateManyOperation = exports.UpdateOneOperation = exports.UpdateOperation = void 0; +const error_1 = require("../error"); +const utils_1 = require("../utils"); +const command_1 = require("./command"); +const operation_1 = require("./operation"); +/** @internal */ +class UpdateOperation extends command_1.CommandOperation { + constructor(ns, statements, options) { + super(undefined, options); + this.options = options; + this.ns = ns; + this.statements = statements; + } + get canRetryWrite() { + if (super.canRetryWrite === false) { + return false; + } + return this.statements.every(op => op.multi == null || op.multi === false); + } + execute(server, session, callback) { + var _a; + const options = (_a = this.options) !== null && _a !== void 0 ? _a : {}; + const ordered = typeof options.ordered === 'boolean' ? options.ordered : true; + const command = { + update: this.ns.collection, + updates: this.statements, + ordered + }; + if (typeof options.bypassDocumentValidation === 'boolean') { + command.bypassDocumentValidation = options.bypassDocumentValidation; + } + if (options.let) { + command.let = options.let; + } + // we check for undefined specifically here to allow falsy values + // eslint-disable-next-line no-restricted-syntax + if (options.comment !== undefined) { + command.comment = options.comment; + } + const statementWithCollation = this.statements.find(statement => !!statement.collation); + if ((0, utils_1.collationNotSupported)(server, options) || + (statementWithCollation && (0, utils_1.collationNotSupported)(server, statementWithCollation))) { + callback(new error_1.MongoCompatibilityError(`Server ${server.name} does not support collation`)); + return; + } + const unacknowledgedWrite = this.writeConcern && this.writeConcern.w === 0; + if (unacknowledgedWrite || (0, utils_1.maxWireVersion)(server) < 5) { + if (this.statements.find((o) => o.hint)) { + callback(new error_1.MongoCompatibilityError(`Servers < 3.4 do not support hint on update`)); + return; + } + } + if (this.explain && (0, utils_1.maxWireVersion)(server) < 3) { + callback(new error_1.MongoCompatibilityError(`Server ${server.name} does not support explain on update`)); + return; + } + if (this.statements.some(statement => !!statement.arrayFilters) && (0, utils_1.maxWireVersion)(server) < 6) { + callback(new error_1.MongoCompatibilityError('Option "arrayFilters" is only supported on MongoDB 3.6+')); + return; + } + super.executeCommand(server, session, command, callback); + } +} +exports.UpdateOperation = UpdateOperation; +/** @internal */ +class UpdateOneOperation extends UpdateOperation { + constructor(collection, filter, update, options) { + super(collection.s.namespace, [makeUpdateStatement(filter, update, { ...options, multi: false })], options); + if (!(0, utils_1.hasAtomicOperators)(update)) { + throw new error_1.MongoInvalidArgumentError('Update document requires atomic operators'); + } + } + execute(server, session, callback) { + super.execute(server, session, (err, res) => { + var _a, _b; + if (err || !res) + return callback(err); + if (this.explain != null) + return callback(undefined, res); + if (res.code) + return callback(new error_1.MongoServerError(res)); + if (res.writeErrors) + return callback(new error_1.MongoServerError(res.writeErrors[0])); + callback(undefined, { + acknowledged: (_b = ((_a = this.writeConcern) === null || _a === void 0 ? void 0 : _a.w) !== 0) !== null && _b !== void 0 ? _b : true, + modifiedCount: res.nModified != null ? res.nModified : res.n, + upsertedId: Array.isArray(res.upserted) && res.upserted.length > 0 ? res.upserted[0]._id : null, + upsertedCount: Array.isArray(res.upserted) && res.upserted.length ? res.upserted.length : 0, + matchedCount: Array.isArray(res.upserted) && res.upserted.length > 0 ? 0 : res.n + }); + }); + } +} +exports.UpdateOneOperation = UpdateOneOperation; +/** @internal */ +class UpdateManyOperation extends UpdateOperation { + constructor(collection, filter, update, options) { + super(collection.s.namespace, [makeUpdateStatement(filter, update, { ...options, multi: true })], options); + if (!(0, utils_1.hasAtomicOperators)(update)) { + throw new error_1.MongoInvalidArgumentError('Update document requires atomic operators'); + } + } + execute(server, session, callback) { + super.execute(server, session, (err, res) => { + var _a, _b; + if (err || !res) + return callback(err); + if (this.explain != null) + return callback(undefined, res); + if (res.code) + return callback(new error_1.MongoServerError(res)); + if (res.writeErrors) + return callback(new error_1.MongoServerError(res.writeErrors[0])); + callback(undefined, { + acknowledged: (_b = ((_a = this.writeConcern) === null || _a === void 0 ? void 0 : _a.w) !== 0) !== null && _b !== void 0 ? _b : true, + modifiedCount: res.nModified != null ? res.nModified : res.n, + upsertedId: Array.isArray(res.upserted) && res.upserted.length > 0 ? res.upserted[0]._id : null, + upsertedCount: Array.isArray(res.upserted) && res.upserted.length ? res.upserted.length : 0, + matchedCount: Array.isArray(res.upserted) && res.upserted.length > 0 ? 0 : res.n + }); + }); + } +} +exports.UpdateManyOperation = UpdateManyOperation; +/** @internal */ +class ReplaceOneOperation extends UpdateOperation { + constructor(collection, filter, replacement, options) { + super(collection.s.namespace, [makeUpdateStatement(filter, replacement, { ...options, multi: false })], options); + if ((0, utils_1.hasAtomicOperators)(replacement)) { + throw new error_1.MongoInvalidArgumentError('Replacement document must not contain atomic operators'); + } + } + execute(server, session, callback) { + super.execute(server, session, (err, res) => { + var _a, _b; + if (err || !res) + return callback(err); + if (this.explain != null) + return callback(undefined, res); + if (res.code) + return callback(new error_1.MongoServerError(res)); + if (res.writeErrors) + return callback(new error_1.MongoServerError(res.writeErrors[0])); + callback(undefined, { + acknowledged: (_b = ((_a = this.writeConcern) === null || _a === void 0 ? void 0 : _a.w) !== 0) !== null && _b !== void 0 ? _b : true, + modifiedCount: res.nModified != null ? res.nModified : res.n, + upsertedId: Array.isArray(res.upserted) && res.upserted.length > 0 ? res.upserted[0]._id : null, + upsertedCount: Array.isArray(res.upserted) && res.upserted.length ? res.upserted.length : 0, + matchedCount: Array.isArray(res.upserted) && res.upserted.length > 0 ? 0 : res.n + }); + }); + } +} +exports.ReplaceOneOperation = ReplaceOneOperation; +function makeUpdateStatement(filter, update, options) { + if (filter == null || typeof filter !== 'object') { + throw new error_1.MongoInvalidArgumentError('Selector must be a valid JavaScript object'); + } + if (update == null || typeof update !== 'object') { + throw new error_1.MongoInvalidArgumentError('Document must be a valid JavaScript object'); + } + const op = { q: filter, u: update }; + if (typeof options.upsert === 'boolean') { + op.upsert = options.upsert; + } + if (options.multi) { + op.multi = options.multi; + } + if (options.hint) { + op.hint = options.hint; + } + if (options.arrayFilters) { + op.arrayFilters = options.arrayFilters; + } + if (options.collation) { + op.collation = options.collation; + } + return op; +} +exports.makeUpdateStatement = makeUpdateStatement; +(0, operation_1.defineAspects)(UpdateOperation, [operation_1.Aspect.RETRYABLE, operation_1.Aspect.WRITE_OPERATION, operation_1.Aspect.SKIP_COLLATION]); +(0, operation_1.defineAspects)(UpdateOneOperation, [ + operation_1.Aspect.RETRYABLE, + operation_1.Aspect.WRITE_OPERATION, + operation_1.Aspect.EXPLAINABLE, + operation_1.Aspect.SKIP_COLLATION +]); +(0, operation_1.defineAspects)(UpdateManyOperation, [ + operation_1.Aspect.WRITE_OPERATION, + operation_1.Aspect.EXPLAINABLE, + operation_1.Aspect.SKIP_COLLATION +]); +(0, operation_1.defineAspects)(ReplaceOneOperation, [ + operation_1.Aspect.RETRYABLE, + operation_1.Aspect.WRITE_OPERATION, + operation_1.Aspect.SKIP_COLLATION +]); +//# sourceMappingURL=update.js.map \ No newline at end of file diff --git a/ts-ticket-office-service/node_modules/mongodb/lib/operations/update.js.map b/ts-ticket-office-service/node_modules/mongodb/lib/operations/update.js.map new file mode 100644 index 000000000..bc10fed98 --- /dev/null +++ b/ts-ticket-office-service/node_modules/mongodb/lib/operations/update.js.map @@ -0,0 +1 @@ +{"version":3,"file":"update.js","sourceRoot":"","sources":["../../src/operations/update.ts"],"names":[],"mappings":";;;AAEA,oCAAgG;AAGhG,oCAMkB;AAClB,uCAAwF;AACxF,2CAA0D;AAkD1D,gBAAgB;AAChB,MAAa,eAAgB,SAAQ,0BAA0B;IAI7D,YACE,EAAoB,EACpB,UAA6B,EAC7B,OAA8C;QAE9C,KAAK,CAAC,SAAS,EAAE,OAAO,CAAC,CAAC;QAC1B,IAAI,CAAC,OAAO,GAAG,OAAO,CAAC;QACvB,IAAI,CAAC,EAAE,GAAG,EAAE,CAAC;QAEb,IAAI,CAAC,UAAU,GAAG,UAAU,CAAC;IAC/B,CAAC;IAED,IAAa,aAAa;QACxB,IAAI,KAAK,CAAC,aAAa,KAAK,KAAK,EAAE;YACjC,OAAO,KAAK,CAAC;SACd;QAED,OAAO,IAAI,CAAC,UAAU,CAAC,KAAK,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,KAAK,IAAI,IAAI,IAAI,EAAE,CAAC,KAAK,KAAK,KAAK,CAAC,CAAC;IAC7E,CAAC;IAEQ,OAAO,CACd,MAAc,EACd,OAAkC,EAClC,QAA4B;;QAE5B,MAAM,OAAO,GAAG,MAAA,IAAI,CAAC,OAAO,mCAAI,EAAE,CAAC;QACnC,MAAM,OAAO,GAAG,OAAO,OAAO,CAAC,OAAO,KAAK,SAAS,CAAC,CAAC,CAAC,OAAO,CAAC,OAAO,CAAC,CAAC,CAAC,IAAI,CAAC;QAC9E,MAAM,OAAO,GAAa;YACxB,MAAM,EAAE,IAAI,CAAC,EAAE,CAAC,UAAU;YAC1B,OAAO,EAAE,IAAI,CAAC,UAAU;YACxB,OAAO;SACR,CAAC;QAEF,IAAI,OAAO,OAA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,SAAS;IAChB,kBAAM,CAAC,eAAe;IACtB,kBAAM,CAAC,cAAc;CACtB,CAAC,CAAC"} \ No newline at end of file diff --git a/ts-ticket-office-service/node_modules/mongodb/lib/operations/validate_collection.js b/ts-ticket-office-service/node_modules/mongodb/lib/operations/validate_collection.js new file mode 100644 index 000000000..1a7c978ec --- /dev/null +++ b/ts-ticket-office-service/node_modules/mongodb/lib/operations/validate_collection.js @@ -0,0 +1,41 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.ValidateCollectionOperation = void 0; +const error_1 = require("../error"); +const command_1 = require("./command"); +/** @internal */ +class ValidateCollectionOperation extends command_1.CommandOperation { + constructor(admin, collectionName, options) { + // Decorate command with extra options + const command = { validate: collectionName }; + const keys = Object.keys(options); + for (let i = 0; i < keys.length; i++) { + if (Object.prototype.hasOwnProperty.call(options, keys[i]) && keys[i] !== 'session') { + command[keys[i]] = options[keys[i]]; + } + } + super(admin.s.db, options); + this.options = options; + this.command = command; + this.collectionName = collectionName; + } + execute(server, session, callback) { + const collectionName = this.collectionName; + super.executeCommand(server, session, this.command, (err, doc) => { + if (err != null) + return callback(err); + // TODO(NODE-3483): Replace these with MongoUnexpectedServerResponseError + if (doc.ok === 0) + return callback(new error_1.MongoRuntimeError('Error with validate command')); + if (doc.result != null && typeof doc.result !== 'string') + return callback(new error_1.MongoRuntimeError('Error with validation data')); + if (doc.result != null && doc.result.match(/exception|corrupt/) != null) + return callback(new error_1.MongoRuntimeError(`Invalid collection ${collectionName}`)); + if (doc.valid != null && !doc.valid) + return callback(new error_1.MongoRuntimeError(`Invalid collection ${collectionName}`)); + return callback(undefined, doc); + }); + } +} +exports.ValidateCollectionOperation = ValidateCollectionOperation; +//# sourceMappingURL=validate_collection.js.map \ No newline at end of file diff --git a/ts-ticket-office-service/node_modules/mongodb/lib/operations/validate_collection.js.map b/ts-ticket-office-service/node_modules/mongodb/lib/operations/validate_collection.js.map new file mode 100644 index 000000000..9d72c4185 --- /dev/null +++ b/ts-ticket-office-service/node_modules/mongodb/lib/operations/validate_collection.js.map @@ -0,0 +1 @@ +{"version":3,"file":"validate_collection.js","sourceRoot":"","sources":["../../src/operations/validate_collection.ts"],"names":[],"mappings":";;;AAEA,oCAA6C;AAI7C,uCAAsE;AAQtE,gBAAgB;AAChB,MAAa,2BAA4B,SAAQ,0BAA0B;IAKzE,YAAY,KAAY,EAAE,cAAsB,EAAE,OAAkC;QAClF,sCAAsC;QACtC,MAAM,OAAO,GAAa,EAAE,QAAQ,EAAE,cAAc,EAAE,CAAC;QACvD,MAAM,IAAI,GAAG,MAAM,CAAC,IAAI,CAAC,OAAO,CAAC,CAAC;QAClC,KAAK,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC,GAAG,IAAI,CAAC,MAAM,EAAE,CAAC,EAAE,EAAE;YACpC,IAAI,MAAM,CAAC,SAAS,CAAC,cAAc,CAAC,IAAI,CAAC,OAAO,EAAE,IAAI,CAAC,CAAC,CAAC,CAAC,IAAI,IAAI,CAAC,CAAC,CAAC,KAAK,SAAS,EAAE;gBACnF,OAAO,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC,GAAI,OAAoB,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC,CAAC;aACnD;SACF;QAED,KAAK,CAAC,KAAK,CAAC,CAAC,CAAC,EAAE,EAAE,OAAO,CAAC,CAAC;QAC3B,IAAI,CAAC,OAAO,GAAG,OAAO,CAAC;QACvB,IAAI,CAAC,OAAO,GAAG,OAAO,CAAC;QACvB,IAAI,CAAC,cAAc,GAAG,cAAc,CAAC;IACvC,CAAC;IAEQ,OAAO,CACd,MAAc,EACd,OAAkC,EAClC,QAA4B;QAE5B,MAAM,cAAc,GAAG,IAAI,CAAC,cAAc,CAAC;QAE3C,KAAK,CAAC,cAAc,CAAC,MAAM,EAAE,OAAO,EAAE,IAAI,CAAC,OAAO,EAAE,CAAC,GAAG,EAAE,GAAG,EAAE,EAAE;YAC/D,IAAI,GAAG,IAAI,IAAI;gBAAE,OAAO,QAAQ,CAAC,GAAG,CAAC,CAAC;YAEtC,yEAAyE;YACzE,IAAI,GAAG,CAAC,EAAE,KAAK,CAAC;gBAAE,OAAO,QAAQ,CAAC,IAAI,yBAAiB,CAAC,6BAA6B,CAAC,CAAC,CAAC;YACxF,IAAI,GAAG,CAAC,MAAM,IAAI,IAAI,IAAI,OAAO,GAAG,CAAC,MAAM,KAAK,QAAQ;gBACtD,OAAO,QAAQ,CAAC,IAAI,yBAAiB,CAAC,4BAA4B,CAAC,CAAC,CAAC;YACvE,IAAI,GAAG,CAAC,MAAM,IAAI,IAAI,IAAI,GAAG,CAAC,MAAM,CAAC,KAAK,CAAC,mBAAmB,CAAC,IAAI,IAAI;gBACrE,OAAO,QAAQ,CAAC,IAAI,yBAAiB,CAAC,sBAAsB,cAAc,EAAE,CAAC,CAAC,CAAC;YACjF,IAAI,GAAG,CAAC,KAAK,IAAI,IAAI,IAAI,CAAC,GAAG,CAAC,KAAK;gBACjC,OAAO,QAAQ,CAAC,IAAI,yBAAiB,CAAC,sBAAsB,cAAc,EAAE,CAAC,CAAC,CAAC;YAEjF,OAAO,QAAQ,CAAC,SAAS,EAAE,GAAG,CAAC,CAAC;QAClC,CAAC,CAAC,CAAC;IACL,CAAC;CACF;AA3CD,kEA2CC"} \ No newline at end of file diff --git a/ts-ticket-office-service/node_modules/mongodb/lib/promise_provider.js b/ts-ticket-office-service/node_modules/mongodb/lib/promise_provider.js new file mode 100644 index 000000000..e76480a29 --- /dev/null +++ b/ts-ticket-office-service/node_modules/mongodb/lib/promise_provider.js @@ -0,0 +1,36 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.PromiseProvider = void 0; +const error_1 = require("./error"); +/** @internal */ +const kPromise = Symbol('promise'); +const store = { + [kPromise]: undefined +}; +/** + * Global promise store allowing user-provided promises + * @public + */ +class PromiseProvider { + /** Validates the passed in promise library */ + static validate(lib) { + if (typeof lib !== 'function') + throw new error_1.MongoInvalidArgumentError(`Promise must be a function, got ${lib}`); + return !!lib; + } + /** Sets the promise library */ + static set(lib) { + if (!PromiseProvider.validate(lib)) { + // validate + return; + } + store[kPromise] = lib; + } + /** Get the stored promise library, or resolves passed in */ + static get() { + return store[kPromise]; + } +} +exports.PromiseProvider = PromiseProvider; +PromiseProvider.set(global.Promise); +//# sourceMappingURL=promise_provider.js.map \ No newline at end of file diff --git a/ts-ticket-office-service/node_modules/mongodb/lib/promise_provider.js.map b/ts-ticket-office-service/node_modules/mongodb/lib/promise_provider.js.map new file mode 100644 index 000000000..703bee2c9 --- /dev/null +++ b/ts-ticket-office-service/node_modules/mongodb/lib/promise_provider.js.map @@ -0,0 +1 @@ +{"version":3,"file":"promise_provider.js","sourceRoot":"","sources":["../src/promise_provider.ts"],"names":[],"mappings":";;;AAAA,mCAAoD;AAEpD,gBAAgB;AAChB,MAAM,QAAQ,GAAG,MAAM,CAAC,SAAS,CAAC,CAAC;AAMnC,MAAM,KAAK,GAAiB;IAC1B,CAAC,QAAQ,CAAC,EAAE,SAAS;CACtB,CAAC;AAEF;;;GAGG;AACH,MAAa,eAAe;IAC1B,8CAA8C;IAC9C,MAAM,CAAC,QAAQ,CAAC,GAAY;QAC1B,IAAI,OAAO,GAAG,KAAK,UAAU;YAC3B,MAAM,IAAI,iCAAyB,CAAC,mCAAmC,GAAG,EAAE,CAAC,CAAC;QAChF,OAAO,CAAC,CAAC,GAAG,CAAC;IACf,CAAC;IAED,+BAA+B;IAC/B,MAAM,CAAC,GAAG,CAAC,GAAuB;QAChC,IAAI,CAAC,eAAe,CAAC,QAAQ,CAAC,GAAG,CAAC,EAAE;YAClC,WAAW;YACX,OAAO;SACR;QACD,KAAK,CAAC,QAAQ,CAAC,GAAG,GAAG,CAAC;IACxB,CAAC;IAED,4DAA4D;IAC5D,MAAM,CAAC,GAAG;QACR,OAAO,KAAK,CAAC,QAAQ,CAAuB,CAAC;IAC/C,CAAC;CACF;AArBD,0CAqBC;AAED,eAAe,CAAC,GAAG,CAAC,MAAM,CAAC,OAAO,CAAC,CAAC"} \ No newline at end of file diff --git a/ts-ticket-office-service/node_modules/mongodb/lib/read_concern.js b/ts-ticket-office-service/node_modules/mongodb/lib/read_concern.js new file mode 100644 index 000000000..9b1e067a9 --- /dev/null +++ b/ts-ticket-office-service/node_modules/mongodb/lib/read_concern.js @@ -0,0 +1,74 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.ReadConcern = exports.ReadConcernLevel = void 0; +/** @public */ +exports.ReadConcernLevel = Object.freeze({ + local: 'local', + majority: 'majority', + linearizable: 'linearizable', + available: 'available', + snapshot: 'snapshot' +}); +/** + * The MongoDB ReadConcern, which allows for control of the consistency and isolation properties + * of the data read from replica sets and replica set shards. + * @public + * + * @see https://docs.mongodb.com/manual/reference/read-concern/index.html + */ +class ReadConcern { + /** Constructs a ReadConcern from the read concern level.*/ + constructor(level) { + var _a; + /** + * A spec test exists that allows level to be any string. + * "invalid readConcern with out stage" + * @see ./test/spec/crud/v2/aggregate-out-readConcern.json + * @see https://github.com/mongodb/specifications/blob/master/source/read-write-concern/read-write-concern.rst#unknown-levels-and-additional-options-for-string-based-readconcerns + */ + this.level = (_a = exports.ReadConcernLevel[level]) !== null && _a !== void 0 ? _a : level; + } + /** + * Construct a ReadConcern given an options object. + * + * @param options - The options object from which to extract the write concern. + */ + static fromOptions(options) { + if (options == null) { + return; + } + if (options.readConcern) { + const { readConcern } = options; + if (readConcern instanceof ReadConcern) { + return readConcern; + } + else if (typeof readConcern === 'string') { + return new ReadConcern(readConcern); + } + else if ('level' in readConcern && readConcern.level) { + return new ReadConcern(readConcern.level); + } + } + if (options.level) { + return new ReadConcern(options.level); + } + return; + } + static get MAJORITY() { + return exports.ReadConcernLevel.majority; + } + static get AVAILABLE() { + return exports.ReadConcernLevel.available; + } + static get LINEARIZABLE() { + return exports.ReadConcernLevel.linearizable; + } + static get SNAPSHOT() { + return exports.ReadConcernLevel.snapshot; + } + toJSON() { + return { level: this.level }; + } +} +exports.ReadConcern = ReadConcern; +//# sourceMappingURL=read_concern.js.map \ No newline at end of file diff --git a/ts-ticket-office-service/node_modules/mongodb/lib/read_concern.js.map b/ts-ticket-office-service/node_modules/mongodb/lib/read_concern.js.map new file mode 100644 index 000000000..3f74a96e6 --- /dev/null +++ b/ts-ticket-office-service/node_modules/mongodb/lib/read_concern.js.map @@ -0,0 +1 @@ +{"version":3,"file":"read_concern.js","sourceRoot":"","sources":["../src/read_concern.ts"],"names":[],"mappings":";;;AAEA,cAAc;AACD,QAAA,gBAAgB,GAAG,MAAM,CAAC,MAAM,CAAC;IAC5C,KAAK,EAAE,OAAO;IACd,QAAQ,EAAE,UAAU;IACpB,YAAY,EAAE,cAAc;IAC5B,SAAS,EAAE,WAAW;IACtB,QAAQ,EAAE,UAAU;CACZ,CAAC,CAAC;AAQZ;;;;;;GAMG;AACH,MAAa,WAAW;IAGtB,2DAA2D;IAC3D,YAAY,KAAuB;;QACjC;;;;;WAKG;QACH,IAAI,CAAC,KAAK,GAAG,MAAA,wBAAgB,CAAC,KAAK,CAAC,mCAAI,KAAK,CAAC;IAChD,CAAC;IAED;;;;OAIG;IACH,MAAM,CAAC,WAAW,CAAC,OAGlB;QACC,IAAI,OAAO,IAAI,IAAI,EAAE;YACnB,OAAO;SACR;QAED,IAAI,OAAO,CAAC,WAAW,EAAE;YACvB,MAAM,EAAE,WAAW,EAAE,GAAG,OAAO,CAAC;YAChC,IAAI,WAAW,YAAY,WAAW,EAAE;gBACtC,OAAO,WAAW,CAAC;aACpB;iBAAM,IAAI,OAAO,WAAW,KAAK,QAAQ,EAAE;gBAC1C,OAAO,IAAI,WAAW,CAAC,WAAW,CAAC,CAAC;aACrC;iBAAM,IAAI,OAAO,IAAI,WAAW,IAAI,WAAW,CAAC,KAAK,EAAE;gBACtD,OAAO,IAAI,WAAW,CAAC,WAAW,CAAC,KAAK,CAAC,CAAC;aAC3C;SACF;QAED,IAAI,OAAO,CAAC,KAAK,EAAE;YACjB,OAAO,IAAI,WAAW,CAAC,OAAO,CAAC,KAAK,CAAC,CAAC;SACvC;QACD,OAAO;IACT,CAAC;IAED,MAAM,KAAK,QAAQ;QACjB,OAAO,wBAAgB,CAAC,QAAQ,CAAC;IACnC,CAAC;IAED,MAAM,KAAK,SAAS;QAClB,OAAO,wBAAgB,CAAC,SAAS,CAAC;IACpC,CAAC;IAED,MAAM,KAAK,YAAY;QACrB,OAAO,wBAAgB,CAAC,YAAY,CAAC;IACvC,CAAC;IAED,MAAM,KAAK,QAAQ;QACjB,OAAO,wBAAgB,CAAC,QAAQ,CAAC;IACnC,CAAC;IAED,MAAM;QACJ,OAAO,EAAE,KAAK,EAAE,IAAI,CAAC,KAAK,EAAE,CAAC;IAC/B,CAAC;CACF;AA/DD,kCA+DC"} \ No newline at end of file diff --git a/ts-ticket-office-service/node_modules/mongodb/lib/read_preference.js b/ts-ticket-office-service/node_modules/mongodb/lib/read_preference.js index eecc60514..6df80eff8 100644 --- a/ts-ticket-office-service/node_modules/mongodb/lib/read_preference.js +++ b/ts-ticket-office-service/node_modules/mongodb/lib/read_preference.js @@ -1,131 +1,204 @@ "use strict"; - +Object.defineProperty(exports, "__esModule", { value: true }); +exports.ReadPreference = exports.ReadPreferenceMode = void 0; +const error_1 = require("./error"); +/** @public */ +exports.ReadPreferenceMode = Object.freeze({ + primary: 'primary', + primaryPreferred: 'primaryPreferred', + secondary: 'secondary', + secondaryPreferred: 'secondaryPreferred', + nearest: 'nearest' +}); /** - * @fileOverview The **ReadPreference** class is a class that represents a MongoDB ReadPreference and is + * The **ReadPreference** class is a class that represents a MongoDB ReadPreference and is * used to construct connections. + * @public * - * @example - * var Db = require('mongodb').Db, - * ReplSet = require('mongodb').ReplSet, - * Server = require('mongodb').Server, - * ReadPreference = require('mongodb').ReadPreference, - * test = require('assert'); - * // Connect using ReplSet - * var server = new Server('localhost', 27017); - * var db = new Db('test', new ReplSet([server])); - * db.open(function(err, db) { - * test.equal(null, err); - * // Perform a read - * var cursor = db.collection('t').find({}); - * cursor.setReadPreference(ReadPreference.PRIMARY); - * cursor.toArray(function(err, docs) { - * test.equal(null, err); - * db.close(); - * }); - * }); + * @see https://docs.mongodb.com/manual/core/read-preference/ */ - -/** - * Creates a new ReadPreference instance - * - * Read Preferences - * - **ReadPreference.PRIMARY**, Read from primary only. All operations produce an error (throw an exception where applicable) if primary is unavailable. Cannot be combined with tags (This is the default.). - * - **ReadPreference.PRIMARY_PREFERRED**, Read from primary if available, otherwise a secondary. - * - **ReadPreference.SECONDARY**, Read from secondary if available, otherwise error. - * - **ReadPreference.SECONDARY_PREFERRED**, Read from a secondary if available, otherwise read from the primary. - * - **ReadPreference.NEAREST**, All modes read from among the nearest candidates, but unlike other modes, NEAREST will include both the primary and all secondaries in the random selection. - * - * @class - * @param {string} mode The ReadPreference mode as listed above. - * @param {array|object} tags An object representing read preference tags. - * @param {object} [options] Additional read preference options - * @param {number} [options.maxStalenessSeconds] Max Secondary Read Staleness in Seconds - * @return {ReadPreference} a ReadPreference instance. - */ -var ReadPreference = function(mode, tags, options) { - if(!(this instanceof ReadPreference)) { - return new ReadPreference(mode, tags, options); - } - - this._type = 'ReadPreference'; - this.mode = mode; - this.tags = tags; - this.options = options; - - // If no tags were passed in - if(tags && typeof tags == 'object' && !Array.isArray(tags)) { - if(tags.maxStalenessSeconds) { - this.options = tags; - this.tags = null; +class ReadPreference { + /** + * @param mode - A string describing the read preference mode (primary|primaryPreferred|secondary|secondaryPreferred|nearest) + * @param tags - A tag set used to target reads to members with the specified tag(s). tagSet is not available if using read preference mode primary. + * @param options - Additional read preference options + */ + constructor(mode, tags, options) { + if (!ReadPreference.isValid(mode)) { + throw new error_1.MongoInvalidArgumentError(`Invalid read preference mode ${JSON.stringify(mode)}`); + } + if (options == null && typeof tags === 'object' && !Array.isArray(tags)) { + options = tags; + tags = undefined; + } + else if (tags && !Array.isArray(tags)) { + throw new error_1.MongoInvalidArgumentError('ReadPreference tags must be an array'); + } + this.mode = mode; + this.tags = tags; + this.hedge = options === null || options === void 0 ? void 0 : options.hedge; + this.maxStalenessSeconds = undefined; + this.minWireVersion = undefined; + options = options !== null && options !== void 0 ? options : {}; + if (options.maxStalenessSeconds != null) { + if (options.maxStalenessSeconds <= 0) { + throw new error_1.MongoInvalidArgumentError('maxStalenessSeconds must be a positive integer'); + } + this.maxStalenessSeconds = options.maxStalenessSeconds; + // NOTE: The minimum required wire version is 5 for this read preference. If the existing + // topology has a lower value then a MongoError will be thrown during server selection. + this.minWireVersion = 5; + } + if (this.mode === ReadPreference.PRIMARY) { + if (this.tags && Array.isArray(this.tags) && this.tags.length > 0) { + throw new error_1.MongoInvalidArgumentError('Primary read preference cannot be combined with tags'); + } + if (this.maxStalenessSeconds) { + throw new error_1.MongoInvalidArgumentError('Primary read preference cannot be combined with maxStalenessSeconds'); + } + if (this.hedge) { + throw new error_1.MongoInvalidArgumentError('Primary read preference cannot be combined with hedge'); + } + } + } + // Support the deprecated `preference` property introduced in the porcelain layer + get preference() { + return this.mode; + } + static fromString(mode) { + return new ReadPreference(mode); + } + /** + * Construct a ReadPreference given an options object. + * + * @param options - The options object from which to extract the read preference. + */ + static fromOptions(options) { + var _a, _b, _c; + if (!options) + return; + const readPreference = (_a = options.readPreference) !== null && _a !== void 0 ? _a : (_b = options.session) === null || _b === void 0 ? void 0 : _b.transaction.options.readPreference; + const readPreferenceTags = options.readPreferenceTags; + if (readPreference == null) { + return; + } + if (typeof readPreference === 'string') { + return new ReadPreference(readPreference, readPreferenceTags, { + maxStalenessSeconds: options.maxStalenessSeconds, + hedge: options.hedge + }); + } + else if (!(readPreference instanceof ReadPreference) && typeof readPreference === 'object') { + const mode = readPreference.mode || readPreference.preference; + if (mode && typeof mode === 'string') { + return new ReadPreference(mode, (_c = readPreference.tags) !== null && _c !== void 0 ? _c : readPreferenceTags, { + maxStalenessSeconds: readPreference.maxStalenessSeconds, + hedge: options.hedge + }); + } + } + if (readPreferenceTags) { + readPreference.tags = readPreferenceTags; + } + return readPreference; + } + /** + * Replaces options.readPreference with a ReadPreference instance + */ + static translate(options) { + if (options.readPreference == null) + return options; + const r = options.readPreference; + if (typeof r === 'string') { + options.readPreference = new ReadPreference(r); + } + else if (r && !(r instanceof ReadPreference) && typeof r === 'object') { + const mode = r.mode || r.preference; + if (mode && typeof mode === 'string') { + options.readPreference = new ReadPreference(mode, r.tags, { + maxStalenessSeconds: r.maxStalenessSeconds + }); + } + } + else if (!(r instanceof ReadPreference)) { + throw new error_1.MongoInvalidArgumentError(`Invalid read preference: ${r}`); + } + return options; + } + /** + * Validate if a mode is legal + * + * @param mode - The string representing the read preference mode. + */ + static isValid(mode) { + const VALID_MODES = new Set([ + ReadPreference.PRIMARY, + ReadPreference.PRIMARY_PREFERRED, + ReadPreference.SECONDARY, + ReadPreference.SECONDARY_PREFERRED, + ReadPreference.NEAREST, + null + ]); + return VALID_MODES.has(mode); + } + /** + * Validate if a mode is legal + * + * @param mode - The string representing the read preference mode. + */ + isValid(mode) { + return ReadPreference.isValid(typeof mode === 'string' ? mode : this.mode); + } + /** + * Indicates that this readPreference needs the "secondaryOk" bit when sent over the wire + * @deprecated Use secondaryOk instead + * @see https://docs.mongodb.com/manual/reference/mongodb-wire-protocol/#op-query + */ + slaveOk() { + return this.secondaryOk(); + } + /** + * Indicates that this readPreference needs the "SecondaryOk" bit when sent over the wire + * @see https://docs.mongodb.com/manual/reference/mongodb-wire-protocol/#op-query + */ + secondaryOk() { + const NEEDS_SECONDARYOK = new Set([ + ReadPreference.PRIMARY_PREFERRED, + ReadPreference.SECONDARY, + ReadPreference.SECONDARY_PREFERRED, + ReadPreference.NEAREST + ]); + return NEEDS_SECONDARYOK.has(this.mode); + } + /** + * Check if the two ReadPreferences are equivalent + * + * @param readPreference - The read preference with which to check equality + */ + equals(readPreference) { + return readPreference.mode === this.mode; + } + /** Return JSON representation */ + toJSON() { + const readPreference = { mode: this.mode }; + if (Array.isArray(this.tags)) + readPreference.tags = this.tags; + if (this.maxStalenessSeconds) + readPreference.maxStalenessSeconds = this.maxStalenessSeconds; + if (this.hedge) + readPreference.hedge = this.hedge; + return readPreference; } - } - - // Add the maxStalenessSeconds value to the read Preference - if(this.options && this.options.maxStalenessSeconds) { - this.maxStalenessSeconds = this.options.maxStalenessSeconds; - } -} - -/** - * Validate if a mode is legal - * - * @method - * @param {string} mode The string representing the read preference mode. - * @return {boolean} - */ -ReadPreference.isValid = function(_mode) { - return (_mode == ReadPreference.PRIMARY || _mode == ReadPreference.PRIMARY_PREFERRED - || _mode == ReadPreference.SECONDARY || _mode == ReadPreference.SECONDARY_PREFERRED - || _mode == ReadPreference.NEAREST - || _mode == true || _mode == false || _mode == null); -} - -/** - * Validate if a mode is legal - * - * @method - * @param {string} mode The string representing the read preference mode. - * @return {boolean} - */ -ReadPreference.prototype.isValid = function(mode) { - var _mode = typeof mode == 'string' ? mode : this.mode; - return ReadPreference.isValid(_mode); -} - -/** - * @ignore - */ -ReadPreference.prototype.toObject = function() { - var object = {mode:this.mode}; - - if(this.tags != null) { - object['tags'] = this.tags; - } - - if(this.maxStalenessSeconds) { - object['maxStalenessSeconds'] = this.maxStalenessSeconds; - } - - return object; -} - -/** - * @ignore - */ -ReadPreference.prototype.toJSON = function() { - return this.toObject(); } - -/** - * @ignore - */ -ReadPreference.PRIMARY = 'primary'; -ReadPreference.PRIMARY_PREFERRED = 'primaryPreferred'; -ReadPreference.SECONDARY = 'secondary'; -ReadPreference.SECONDARY_PREFERRED = 'secondaryPreferred'; -ReadPreference.NEAREST = 'nearest' - -/** - * @ignore - */ -module.exports = ReadPreference; +exports.ReadPreference = ReadPreference; +ReadPreference.PRIMARY = exports.ReadPreferenceMode.primary; +ReadPreference.PRIMARY_PREFERRED = exports.ReadPreferenceMode.primaryPreferred; +ReadPreference.SECONDARY = exports.ReadPreferenceMode.secondary; +ReadPreference.SECONDARY_PREFERRED = exports.ReadPreferenceMode.secondaryPreferred; +ReadPreference.NEAREST = exports.ReadPreferenceMode.nearest; +ReadPreference.primary = new ReadPreference(exports.ReadPreferenceMode.primary); +ReadPreference.primaryPreferred = new ReadPreference(exports.ReadPreferenceMode.primaryPreferred); +ReadPreference.secondary = new ReadPreference(exports.ReadPreferenceMode.secondary); +ReadPreference.secondaryPreferred = new ReadPreference(exports.ReadPreferenceMode.secondaryPreferred); +ReadPreference.nearest = new ReadPreference(exports.ReadPreferenceMode.nearest); +//# sourceMappingURL=read_preference.js.map \ No newline at end of file diff --git a/ts-ticket-office-service/node_modules/mongodb/lib/read_preference.js.map b/ts-ticket-office-service/node_modules/mongodb/lib/read_preference.js.map new file mode 100644 index 000000000..a5c1a4fc3 --- /dev/null +++ b/ts-ticket-office-service/node_modules/mongodb/lib/read_preference.js.map @@ -0,0 +1 @@ +{"version":3,"file":"read_preference.js","sourceRoot":"","sources":["../src/read_preference.ts"],"names":[],"mappings":";;;AACA,mCAAoD;AAOpD,cAAc;AACD,QAAA,kBAAkB,GAAG,MAAM,CAAC,MAAM,CAAC;IAC9C,OAAO,EAAE,SAAS;IAClB,gBAAgB,EAAE,kBAAkB;IACpC,SAAS,EAAE,WAAW;IACtB,kBAAkB,EAAE,oBAAoB;IACxC,OAAO,EAAE,SAAS;CACV,CAAC,CAAC;AAsCZ;;;;;;GAMG;AACH,MAAa,cAAc;IAmBzB;;;;OAIG;IACH,YAAY,IAAwB,EAAE,IAAe,EAAE,OAA+B;QACpF,IAAI,CAAC,cAAc,CAAC,OAAO,CAAC,IAAI,CAAC,EAAE;YACjC,MAAM,IAAI,iCAAyB,CAAC,gCAAgC,IAAI,CAAC,SAAS,CAAC,IAAI,CAAC,EAAE,CAAC,CAAC;SAC7F;QACD,IAAI,OAAO,IAAI,IAAI,IAAI,OAAO,IAAI,KAAK,QAAQ,IAAI,CAAC,KAAK,CAAC,OAAO,CAAC,IAAI,CAAC,EAAE;YACvE,OAAO,GAAG,IAAI,CAAC;YACf,IAAI,GAAG,SAAS,CAAC;SAClB;aAAM,IAAI,IAAI,IAAI,CAAC,KAAK,CAAC,OAAO,CAAC,IAAI,CAAC,EAAE;YACvC,MAAM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0BAAkB,CAAC,gBAAgB,CAAC,CAAC;AAC3E,wBAAS,GAAG,IAAI,cAAc,CAAC,0BAAkB,CAAC,SAAS,CAAC,CAAC;AAC7D,iCAAkB,GAAG,IAAI,cAAc,CAAC,0BAAkB,CAAC,kBAAkB,CAAC,CAAC;AAC/E,sBAAO,GAAG,IAAI,cAAc,CAAC,0BAAkB,CAAC,OAAO,CAAC,CAAC"} \ No newline at end of file diff --git a/ts-ticket-office-service/node_modules/mongodb/lib/replset.js b/ts-ticket-office-service/node_modules/mongodb/lib/replset.js deleted file mode 100644 index 21e6d4ccb..000000000 --- a/ts-ticket-office-service/node_modules/mongodb/lib/replset.js +++ /dev/null @@ -1,582 +0,0 @@ -"use strict"; - -var EventEmitter = require('events').EventEmitter - , inherits = require('util').inherits - , f = require('util').format - , Server = require('./server') - , Cursor = require('./cursor') - , AggregationCursor = require('./aggregation_cursor') - , CommandCursor = require('./command_cursor') - , ReadPreference = require('./read_preference') - , MongoError = require('mongodb-core').MongoError - , ServerCapabilities = require('./topology_base').ServerCapabilities - , Store = require('./topology_base').Store - , Define = require('./metadata') - , CReplSet = require('mongodb-core').ReplSet - , CoreReadPreference = require('mongodb-core').ReadPreference - , MAX_JS_INT = require('./utils').MAX_JS_INT - , translateOptions = require('./utils').translateOptions - , filterOptions = require('./utils').filterOptions - , getReadPreference = require('./utils').getReadPreference - , mergeOptions = require('./utils').mergeOptions - , os = require('os'); -/** - * @fileOverview The **ReplSet** class is a class that represents a Replicaset topology and is - * used to construct connections. - * - * **ReplSet Should not be used, use MongoClient.connect** - * @example - * var Db = require('mongodb').Db, - * ReplSet = require('mongodb').ReplSet, - * Server = require('mongodb').Server, - * test = require('assert'); - * // Connect using ReplSet - * var server = new Server('localhost', 27017); - * var db = new Db('test', new ReplSet([server])); - * db.open(function(err, db) { - * // Get an additional db - * db.close(); - * }); - */ - -// Allowed parameters -var legalOptionNames = ['ha', 'haInterval', 'replicaSet', 'rs_name', 'secondaryAcceptableLatencyMS' - , 'connectWithNoPrimary', 'poolSize', 'ssl', 'checkServerIdentity', 'sslValidate' - , 'sslCA', 'sslCert', 'sslCRL', 'sslKey', 'sslPass', 'socketOptions', 'bufferMaxEntries' - , 'store', 'auto_reconnect', 'autoReconnect', 'emitError' - , 'keepAlive', 'noDelay', 'connectTimeoutMS', 'socketTimeoutMS', 'strategy', 'debug', 'family' - , 'loggerLevel', 'logger', 'reconnectTries', 'appname', 'domainsEnabled' - , 'servername', 'promoteLongs', 'promoteValues', 'promoteBuffers', 'maxStalenessSeconds']; - -// Get package.json variable -var driverVersion = require('../package.json').version; -var nodejsversion = f('Node.js %s, %s', process.version, os.endianness()); -var type = os.type(); -var name = process.platform; -var architecture = process.arch; -var release = os.release(); - -/** - * Creates a new ReplSet instance - * @class - * @deprecated - * @param {Server[]} servers A seedlist of servers participating in the replicaset. - * @param {object} [options=null] Optional settings. - * @param {boolean} [options.ha=true] Turn on high availability monitoring. - * @param {number} [options.haInterval=10000] Time between each replicaset status check. - * @param {string} [options.replicaSet] The name of the replicaset to connect to. - * @param {number} [options.secondaryAcceptableLatencyMS=15] Sets the range of servers to pick when using NEAREST (lowest ping ms + the latency fence, ex: range of 1 to (1 + 15) ms) - * @param {boolean} [options.connectWithNoPrimary=false] Sets if the driver should connect even if no primary is available - * @param {number} [options.poolSize=5] Number of connections in the connection pool for each server instance, set to 5 as default for legacy reasons. - * @param {boolean} [options.ssl=false] Use ssl connection (needs to have a mongod server with ssl support) - * @param {boolean|function} [options.checkServerIdentity=true] Ensure we check server identify during SSL, set to false to disable checking. Only works for Node 0.12.x or higher. You can pass in a boolean or your own checkServerIdentity override function. - * @param {object} [options.sslValidate=true] Validate mongod server certificate against ca (needs to have a mongod server with ssl support, 2.4 or higher) - * @param {array} [options.sslCA=null] Array of valid certificates either as Buffers or Strings (needs to have a mongod server with ssl support, 2.4 or higher) - * @param {array} [options.sslCRL=null] Array of revocation certificates either as Buffers or Strings (needs to have a mongod server with ssl support, 2.4 or higher) - * @param {(Buffer|string)} [options.sslCert=null] String or buffer containing the certificate we wish to present (needs to have a mongod server with ssl support, 2.4 or higher) - * @param {(Buffer|string)} [options.sslKey=null] String or buffer containing the certificate private key we wish to present (needs to have a mongod server with ssl support, 2.4 or higher) - * @param {(Buffer|string)} [options.sslPass=null] String or buffer containing the certificate password (needs to have a mongod server with ssl support, 2.4 or higher) - * @param {string} [options.servername=null] String containing the server name requested via TLS SNI. - * @param {object} [options.socketOptions=null] Socket options - * @param {boolean} [options.socketOptions.noDelay=true] TCP Socket NoDelay option. - * @param {number} [options.socketOptions.keepAlive=0] TCP KeepAlive on the socket with a X ms delay before start. - * @param {number} [options.socketOptions.connectTimeoutMS=10000] TCP Connection timeout setting - * @param {number} [options.socketOptions.socketTimeoutMS=0] TCP Socket timeout setting - * @param {boolean} [options.domainsEnabled=false] Enable the wrapping of the callback in the current entity, disabled by default to avoid perf hit. - * @param {number} [options.maxStalenessSeconds=undefined] The max staleness to secondary reads (values under 10 seconds cannot be guaranteed); - * @fires ReplSet#connect - * @fires ReplSet#ha - * @fires ReplSet#joined - * @fires ReplSet#left - * @fires ReplSet#fullsetup - * @fires ReplSet#open - * @fires ReplSet#close - * @fires ReplSet#error - * @fires ReplSet#timeout - * @fires ReplSet#parseError - * @property {string} parserType the parser type used (c++ or js). - * @return {ReplSet} a ReplSet instance. - */ -var ReplSet = function(servers, options) { - if(!(this instanceof ReplSet)) return new ReplSet(servers, options); - options = options || {}; - var self = this; - // Set up event emitter - EventEmitter.call(this); - - // Filter the options - options = filterOptions(options, legalOptionNames); - - // Ensure all the instances are Server - for(var i = 0; i < servers.length; i++) { - if(!(servers[i] instanceof Server)) { - throw MongoError.create({message: "all seed list instances must be of the Server type", driver:true}); - } - } - - // Stored options - var storeOptions = { - force: false - , bufferMaxEntries: typeof options.bufferMaxEntries == 'number' ? options.bufferMaxEntries : MAX_JS_INT - } - - // Shared global store - var store = options.store || new Store(self, storeOptions); - - // Build seed list - var seedlist = servers.map(function(x) { - return {host: x.host, port: x.port} - }); - - // Clone options - var clonedOptions = mergeOptions({}, { - disconnectHandler: store, - cursorFactory: Cursor, - reconnect: false, - emitError: typeof options.emitError == 'boolean' ? options.emitError : true, - size: typeof options.poolSize == 'number' ? options.poolSize : 5 - }); - - // Translate any SSL options and other connectivity options - clonedOptions = translateOptions(clonedOptions, options); - - // Socket options - var socketOptions = options.socketOptions && Object.keys(options.socketOptions).length > 0 - ? options.socketOptions : options; - - // Translate all the options to the mongodb-core ones - clonedOptions = translateOptions(clonedOptions, socketOptions); - if(typeof clonedOptions.keepAlive == 'number') { - clonedOptions.keepAliveInitialDelay = clonedOptions.keepAlive; - clonedOptions.keepAlive = clonedOptions.keepAlive > 0; - } - - // Client info - this.clientInfo = { - driver: { - name: "nodejs", - version: driverVersion - }, - os: { - type: type, - name: name, - architecture: architecture, - version: release - }, - platform: nodejsversion - } - - // Build default client information - clonedOptions.clientInfo = this.clientInfo; - // Do we have an application specific string - if(options.appname) { - clonedOptions.clientInfo.application = { name: options.appname }; - } - - // Create the ReplSet - var replset = new CReplSet(seedlist, clonedOptions); - - // Listen to reconnect event - replset.on('reconnect', function() { - self.emit('reconnect'); - store.execute(); - }); - - // Internal state - this.s = { - // Replicaset - replset: replset - // Server capabilities - , sCapabilities: null - // Debug tag - , tag: options.tag - // Store options - , storeOptions: storeOptions - // Cloned options - , clonedOptions: clonedOptions - // Store - , store: store - // Options - , options: options - } - - // Debug - if(clonedOptions.debug) { - // Last ismaster - Object.defineProperty(this, 'replset', { - enumerable:true, get: function() { return replset; } - }); - } -} - -/** - * @ignore - */ -inherits(ReplSet, EventEmitter); - -// Last ismaster -Object.defineProperty(ReplSet.prototype, 'isMasterDoc', { - enumerable:true, get: function() { return this.s.replset.lastIsMaster(); } -}); - -Object.defineProperty(ReplSet.prototype, 'parserType', { - enumerable:true, get: function() { - return this.s.replset.parserType; - } -}); - -// BSON property -Object.defineProperty(ReplSet.prototype, 'bson', { - enumerable: true, get: function() { - return this.s.replset.s.bson; - } -}); - -Object.defineProperty(ReplSet.prototype, 'haInterval', { - enumerable:true, get: function() { return this.s.replset.s.haInterval; } -}); - -var define = ReplSet.define = new Define('ReplSet', ReplSet, false); - -// Ensure the right read Preference object -var translateReadPreference = function(options) { - if(typeof options.readPreference == 'string') { - options.readPreference = new CoreReadPreference(options.readPreference); - } else if(options.readPreference instanceof ReadPreference) { - options.readPreference = new CoreReadPreference(options.readPreference.mode - , options.readPreference.tags, {maxStalenessSeconds: options.readPreference.maxStalenessSeconds}); - } - - return options; -} - -// Connect method -ReplSet.prototype.connect = function(db, _options, callback) { - var self = this; - if('function' === typeof _options) callback = _options, _options = {}; - if(_options == null) _options = {}; - if(!('function' === typeof callback)) callback = null; - self.s.options = _options; - - // Update bufferMaxEntries - self.s.storeOptions.bufferMaxEntries = db.bufferMaxEntries; - - // Actual handler - var errorHandler = function(event) { - return function(err) { - if(event != 'error') { - self.emit(event, err); - } - } - } - - // Clear out all the current handlers left over - var events = ["timeout", "error", "close", 'serverOpening', 'serverDescriptionChanged', 'serverHeartbeatStarted', - 'serverHeartbeatSucceeded', 'serverHeartbeatFailed', 'serverClosed', 'topologyOpening', - 'topologyClosed', 'topologyDescriptionChanged', 'joined', 'left', 'ping', 'ha']; - events.forEach(function(e) { - self.s.replset.removeAllListeners(e); - }); - - // relay the event - var relay = function(event) { - return function(t, server) { - self.emit(event, t, server); - } - } - - // Replset events relay - var replsetRelay = function(event) { - return function(t, server) { - self.emit(event, t, server.lastIsMaster(), server); - } - } - - // Relay ha - var relayHa = function(t, state) { - self.emit('ha', t, state); - - if(t == 'start') { - self.emit('ha_connect', t, state); - } else if(t == 'end') { - self.emit('ha_ismaster', t, state); - } - } - - // Set up serverConfig listeners - self.s.replset.on('joined', replsetRelay('joined')); - self.s.replset.on('left', relay('left')); - self.s.replset.on('ping', relay('ping')); - self.s.replset.on('ha', relayHa); - - // Set up SDAM listeners - self.s.replset.on('serverDescriptionChanged', relay('serverDescriptionChanged')); - self.s.replset.on('serverHeartbeatStarted', relay('serverHeartbeatStarted')); - self.s.replset.on('serverHeartbeatSucceeded', relay('serverHeartbeatSucceeded')); - self.s.replset.on('serverHeartbeatFailed', relay('serverHeartbeatFailed')); - self.s.replset.on('serverOpening', relay('serverOpening')); - self.s.replset.on('serverClosed', relay('serverClosed')); - self.s.replset.on('topologyOpening', relay('topologyOpening')); - self.s.replset.on('topologyClosed', relay('topologyClosed')); - self.s.replset.on('topologyDescriptionChanged', relay('topologyDescriptionChanged')); - - self.s.replset.on('fullsetup', function() { - self.emit('fullsetup', self, self); - }); - - self.s.replset.on('all', function() { - self.emit('all', null, self); - }); - - // Connect handler - var connectHandler = function() { - // Set up listeners - self.s.replset.once('timeout', errorHandler('timeout')); - self.s.replset.once('error', errorHandler('error')); - self.s.replset.once('close', errorHandler('close')); - - // Emit open event - self.emit('open', null, self); - - // Return correctly - try { - callback(null, self); - } catch(err) { - process.nextTick(function() { throw err; }) - } - } - - // Error handler - var connectErrorHandler = function() { - return function(err) { - ['timeout', 'error', 'close'].forEach(function(e) { - self.s.replset.removeListener(e, connectErrorHandler); - }); - - self.s.replset.removeListener('connect', connectErrorHandler); - // Destroy the replset - self.s.replset.destroy(); - - // Try to callback - try { - callback(err); - } catch(err) { - if(!self.s.replset.isConnected()) - process.nextTick(function() { throw err; }) - } - } - } - - // Set up listeners - self.s.replset.once('timeout', connectErrorHandler('timeout')); - self.s.replset.once('error', connectErrorHandler('error')); - self.s.replset.once('close', connectErrorHandler('close')); - self.s.replset.once('connect', connectHandler); - - // Start connection - self.s.replset.connect(_options); -} - -// Server capabilities -ReplSet.prototype.capabilities = function() { - if(this.s.sCapabilities) return this.s.sCapabilities; - if(this.s.replset.lastIsMaster() == null) return null; - this.s.sCapabilities = new ServerCapabilities(this.s.replset.lastIsMaster()); - return this.s.sCapabilities; -} - -define.classMethod('capabilities', {callback: false, promise:false, returns: [ServerCapabilities]}); - -// Command -ReplSet.prototype.command = function(ns, cmd, options, callback) { - this.s.replset.command(ns, cmd, getReadPreference(options), callback); -} - -define.classMethod('command', {callback: true, promise:false}); - -// Insert -ReplSet.prototype.insert = function(ns, ops, options, callback) { - this.s.replset.insert(ns, ops, options, callback); -} - -define.classMethod('insert', {callback: true, promise:false}); - -// Update -ReplSet.prototype.update = function(ns, ops, options, callback) { - this.s.replset.update(ns, ops, options, callback); -} - -define.classMethod('update', {callback: true, promise:false}); - -// Remove -ReplSet.prototype.remove = function(ns, ops, options, callback) { - this.s.replset.remove(ns, ops, options, callback); -} - -define.classMethod('remove', {callback: true, promise:false}); - -// Destroyed -ReplSet.prototype.isDestroyed = function() { - return this.s.replset.isDestroyed(); -} - -// IsConnected -ReplSet.prototype.isConnected = function(options) { - options = options || {}; - - // If we passed in a readPreference, translate to - // a CoreReadPreference instance - if(options.readPreference) { - options.readPreference = translateReadPreference(options.readPreference); - } - - return this.s.replset.isConnected(options); -} - -define.classMethod('isConnected', {callback: false, promise:false, returns: [Boolean]}); - -// Insert -ReplSet.prototype.cursor = function(ns, cmd, options) { - options = translateReadPreference(options); - options.disconnectHandler = this.s.store; - return this.s.replset.cursor(ns, cmd, options); -} - -define.classMethod('cursor', {callback: false, promise:false, returns: [Cursor, AggregationCursor, CommandCursor]}); - -ReplSet.prototype.lastIsMaster = function() { - return this.s.replset.lastIsMaster(); -} - -/** - * Unref all sockets - * @method - */ -ReplSet.prototype.unref = function() { - return this.s.replset.unref(); -} - -ReplSet.prototype.close = function(forceClosed) { - var self = this; - // Call destroy on the topology - this.s.replset.destroy({ - force: typeof forceClosed == 'boolean' ? forceClosed : false, - }); - // We need to wash out all stored processes - if(forceClosed == true) { - this.s.storeOptions.force = forceClosed; - this.s.store.flush(); - } - - var events = ['timeout', 'error', 'close', 'joined', 'left']; - events.forEach(function(e) { - self.removeAllListeners(e); - }); -} - -define.classMethod('close', {callback: false, promise:false}); - -ReplSet.prototype.auth = function() { - var args = Array.prototype.slice.call(arguments, 0); - this.s.replset.auth.apply(this.s.replset, args); -} - -define.classMethod('auth', {callback: true, promise:false}); - -ReplSet.prototype.logout = function() { - var args = Array.prototype.slice.call(arguments, 0); - this.s.replset.logout.apply(this.s.replset, args); -} - -define.classMethod('logout', {callback: true, promise:false}); - -/** - * All raw connections - * @method - * @return {array} - */ -ReplSet.prototype.connections = function() { - return this.s.replset.connections(); -} - -define.classMethod('connections', {callback: false, promise:false, returns:[Array]}); - -/** - * A replset connect event, used to verify that the connection is up and running - * - * @event ReplSet#connect - * @type {ReplSet} - */ - -/** - * The replset high availability event - * - * @event ReplSet#ha - * @type {function} - * @param {string} type The stage in the high availability event (start|end) - * @param {boolean} data.norepeat This is a repeating high availability process or a single execution only - * @param {number} data.id The id for this high availability request - * @param {object} data.state An object containing the information about the current replicaset - */ - -/** - * A server member left the replicaset - * - * @event ReplSet#left - * @type {function} - * @param {string} type The type of member that left (primary|secondary|arbiter) - * @param {Server} server The server object that left - */ - -/** - * A server member joined the replicaset - * - * @event ReplSet#joined - * @type {function} - * @param {string} type The type of member that joined (primary|secondary|arbiter) - * @param {Server} server The server object that joined - */ - -/** - * ReplSet open event, emitted when replicaset can start processing commands. - * - * @event ReplSet#open - * @type {Replset} - */ - -/** - * ReplSet fullsetup event, emitted when all servers in the topology have been connected to. - * - * @event ReplSet#fullsetup - * @type {Replset} - */ - -/** - * ReplSet close event - * - * @event ReplSet#close - * @type {object} - */ - -/** - * ReplSet error event, emitted if there is an error listener. - * - * @event ReplSet#error - * @type {MongoError} - */ - -/** - * ReplSet timeout event - * - * @event ReplSet#timeout - * @type {object} - */ - -/** - * ReplSet parseError event - * - * @event ReplSet#parseError - * @type {object} - */ - -module.exports = ReplSet; diff --git a/ts-ticket-office-service/node_modules/mongodb/lib/sdam/common.js b/ts-ticket-office-service/node_modules/mongodb/lib/sdam/common.js new file mode 100644 index 000000000..3a6929e6a --- /dev/null +++ b/ts-ticket-office-service/node_modules/mongodb/lib/sdam/common.js @@ -0,0 +1,55 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports._advanceClusterTime = exports.drainTimerQueue = exports.ServerType = exports.TopologyType = exports.STATE_CONNECTED = exports.STATE_CONNECTING = exports.STATE_CLOSED = exports.STATE_CLOSING = void 0; +// shared state names +exports.STATE_CLOSING = 'closing'; +exports.STATE_CLOSED = 'closed'; +exports.STATE_CONNECTING = 'connecting'; +exports.STATE_CONNECTED = 'connected'; +/** + * An enumeration of topology types we know about + * @public + */ +exports.TopologyType = Object.freeze({ + Single: 'Single', + ReplicaSetNoPrimary: 'ReplicaSetNoPrimary', + ReplicaSetWithPrimary: 'ReplicaSetWithPrimary', + Sharded: 'Sharded', + Unknown: 'Unknown', + LoadBalanced: 'LoadBalanced' +}); +/** + * An enumeration of server types we know about + * @public + */ +exports.ServerType = Object.freeze({ + Standalone: 'Standalone', + Mongos: 'Mongos', + PossiblePrimary: 'PossiblePrimary', + RSPrimary: 'RSPrimary', + RSSecondary: 'RSSecondary', + RSArbiter: 'RSArbiter', + RSOther: 'RSOther', + RSGhost: 'RSGhost', + Unknown: 'Unknown', + LoadBalancer: 'LoadBalancer' +}); +/** @internal */ +function drainTimerQueue(queue) { + queue.forEach(clearTimeout); + queue.clear(); +} +exports.drainTimerQueue = drainTimerQueue; +/** Shared function to determine clusterTime for a given topology or session */ +function _advanceClusterTime(entity, $clusterTime) { + if (entity.clusterTime == null) { + entity.clusterTime = $clusterTime; + } + else { + if ($clusterTime.clusterTime.greaterThan(entity.clusterTime.clusterTime)) { + entity.clusterTime = $clusterTime; + } + } +} +exports._advanceClusterTime = _advanceClusterTime; +//# sourceMappingURL=common.js.map \ No newline at end of file diff --git a/ts-ticket-office-service/node_modules/mongodb/lib/sdam/common.js.map b/ts-ticket-office-service/node_modules/mongodb/lib/sdam/common.js.map new file mode 100644 index 000000000..8771ed460 --- /dev/null +++ b/ts-ticket-office-service/node_modules/mongodb/lib/sdam/common.js.map @@ -0,0 +1 @@ +{"version":3,"file":"common.js","sourceRoot":"","sources":["../../src/sdam/common.ts"],"names":[],"mappings":";;;AAIA,qBAAqB;AACR,QAAA,aAAa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odb/lib/sdam/events.js b/ts-ticket-office-service/node_modules/mongodb/lib/sdam/events.js new file mode 100644 index 000000000..9943108b1 --- /dev/null +++ b/ts-ticket-office-service/node_modules/mongodb/lib/sdam/events.js @@ -0,0 +1,125 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.ServerHeartbeatFailedEvent = exports.ServerHeartbeatSucceededEvent = exports.ServerHeartbeatStartedEvent = exports.TopologyClosedEvent = exports.TopologyOpeningEvent = exports.TopologyDescriptionChangedEvent = exports.ServerClosedEvent = exports.ServerOpeningEvent = exports.ServerDescriptionChangedEvent = void 0; +/** + * Emitted when server description changes, but does NOT include changes to the RTT. + * @public + * @category Event + */ +class ServerDescriptionChangedEvent { + /** @internal */ + constructor(topologyId, address, previousDescription, newDescription) { + this.topologyId = topologyId; + this.address = address; + this.previousDescription = previousDescription; + this.newDescription = newDescription; + } +} +exports.ServerDescriptionChangedEvent = ServerDescriptionChangedEvent; +/** + * Emitted when server is initialized. + * @public + * @category Event + */ +class ServerOpeningEvent { + /** @internal */ + constructor(topologyId, address) { + this.topologyId = topologyId; + this.address = address; + } +} +exports.ServerOpeningEvent = ServerOpeningEvent; +/** + * Emitted when server is closed. + * @public + * @category Event + */ +class ServerClosedEvent { + /** @internal */ + constructor(topologyId, address) { + this.topologyId = topologyId; + this.address = address; + } +} +exports.ServerClosedEvent = ServerClosedEvent; +/** + * Emitted when topology description changes. + * @public + * @category Event + */ +class TopologyDescriptionChangedEvent { + /** @internal */ + constructor(topologyId, previousDescription, newDescription) { + this.topologyId = topologyId; + this.previousDescription = previousDescription; + this.newDescription = newDescription; + } +} +exports.TopologyDescriptionChangedEvent = TopologyDescriptionChangedEvent; +/** + * Emitted when topology is initialized. + * @public + * @category Event + */ +class TopologyOpeningEvent { + /** @internal */ + constructor(topologyId) { + this.topologyId = topologyId; + } +} +exports.TopologyOpeningEvent = TopologyOpeningEvent; +/** + * Emitted when topology is closed. + * @public + * @category Event + */ +class TopologyClosedEvent { + /** @internal */ + constructor(topologyId) { + this.topologyId = topologyId; + } +} +exports.TopologyClosedEvent = TopologyClosedEvent; +/** + * Emitted when the server monitor’s hello command is started - immediately before + * the hello command is serialized into raw BSON and written to the socket. + * + * @public + * @category Event + */ +class ServerHeartbeatStartedEvent { + /** @internal */ + constructor(connectionId) { + this.connectionId = connectionId; + } +} +exports.ServerHeartbeatStartedEvent = ServerHeartbeatStartedEvent; +/** + * Emitted when the server monitor’s hello succeeds. + * @public + * @category Event + */ +class ServerHeartbeatSucceededEvent { + /** @internal */ + constructor(connectionId, duration, reply) { + this.connectionId = connectionId; + this.duration = duration; + this.reply = reply !== null && reply !== void 0 ? reply : {}; + } +} +exports.ServerHeartbeatSucceededEvent = ServerHeartbeatSucceededEvent; +/** + * Emitted when the server monitor’s hello fails, either with an “ok: 0” or a socket exception. + * @public + * @category Event + */ +class ServerHeartbeatFailedEvent { + /** @internal */ + constructor(connectionId, duration, failure) { + this.connectionId = connectionId; + this.duration = duration; + this.failure = failure; + } +} +exports.ServerHeartbeatFailedEvent = ServerHeartbeatFailedEvent; +//# sourceMappingURL=events.js.map \ No newline at end of file diff --git a/ts-ticket-office-service/node_modules/mongodb/lib/sdam/events.js.map b/ts-ticket-office-service/node_modules/mongodb/lib/sdam/events.js.map new file mode 100644 index 000000000..734a42575 --- /dev/null +++ b/ts-ticket-office-service/node_modules/mongodb/lib/sdam/events.js.map @@ -0,0 +1 @@ +{"version":3,"file":"events.js","sourceRoot":"","sources":["../../src/sdam/events.ts"],"names":[],"mappings":";;;AAIA;;;;GAIG;AACH,MAAa,6BAA6B;IAUxC,gBAAgB;IAChB,YACE,UAAkB,EAClB,OAAe,EACf,mBAAsC,EACtC,cAAiC;QAEjC,IAAI,CAAC,UAAU,GAAG,UAAU,CAAC;QAC7B,IAAI,CAAC,OAAO,GAAG,OAAO,CAAC;QACvB,IAAI,CAAC,mBAAmB,GAAG,mBAAmB,CAAC;QAC/C,IAAI,CAAC,cAAc,GAAG,cAAc,CAAC;IACv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GAAG,YAAY,CAAC;QACjC,IAAI,CAAC,QAAQ,GAAG,QAAQ,CAAC;QACzB,IAAI,CAAC,KAAK,GAAG,KAAK,aAAL,KAAK,cAAL,KAAK,GAAI,EAAE,CAAC;IAC3B,CAAC;CACF;AAdD,sEAcC;AAED;;;;GAIG;AACH,MAAa,0BAA0B;IAQrC,gBAAgB;IAChB,YAAY,YAAoB,EAAE,QAAgB,EAAE,OAAc;QAChE,IAAI,CAAC,YAAY,GAAG,YAAY,CAAC;QACjC,IAAI,CAAC,QAAQ,GAAG,QAAQ,CAAC;QACzB,IAAI,CAAC,OAAO,GAAG,OAAO,CAAC;IACzB,CAAC;CACF;AAdD,gEAcC"} \ No newline at end of file diff --git a/ts-ticket-office-service/node_modules/mongodb/lib/sdam/monitor.js b/ts-ticket-office-service/node_modules/mongodb/lib/sdam/monitor.js new file mode 100644 index 000000000..1149c7961 --- /dev/null +++ b/ts-ticket-office-service/node_modules/mongodb/lib/sdam/monitor.js @@ -0,0 +1,326 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.RTTPinger = exports.Monitor = void 0; +const timers_1 = require("timers"); +const bson_1 = require("../bson"); +const connect_1 = require("../cmap/connect"); +const connection_1 = require("../cmap/connection"); +const constants_1 = require("../constants"); +const error_1 = require("../error"); +const mongo_types_1 = require("../mongo_types"); +const utils_1 = require("../utils"); +const common_1 = require("./common"); +const events_1 = require("./events"); +const server_1 = require("./server"); +/** @internal */ +const kServer = Symbol('server'); +/** @internal */ +const kMonitorId = Symbol('monitorId'); +/** @internal */ +const kConnection = Symbol('connection'); +/** @internal */ +const kCancellationToken = Symbol('cancellationToken'); +/** @internal */ +const kRTTPinger = Symbol('rttPinger'); +/** @internal */ +const kRoundTripTime = Symbol('roundTripTime'); +const STATE_IDLE = 'idle'; +const STATE_MONITORING = 'monitoring'; +const stateTransition = (0, utils_1.makeStateMachine)({ + [common_1.STATE_CLOSING]: [common_1.STATE_CLOSING, STATE_IDLE, common_1.STATE_CLOSED], + [common_1.STATE_CLOSED]: [common_1.STATE_CLOSED, STATE_MONITORING], + [STATE_IDLE]: [STATE_IDLE, STATE_MONITORING, common_1.STATE_CLOSING], + [STATE_MONITORING]: [STATE_MONITORING, STATE_IDLE, common_1.STATE_CLOSING] +}); +const INVALID_REQUEST_CHECK_STATES = new Set([common_1.STATE_CLOSING, common_1.STATE_CLOSED, STATE_MONITORING]); +function isInCloseState(monitor) { + return monitor.s.state === common_1.STATE_CLOSED || monitor.s.state === common_1.STATE_CLOSING; +} +/** @internal */ +class Monitor extends mongo_types_1.TypedEventEmitter { + constructor(server, options) { + var _a, _b, _c; + super(); + this[kServer] = server; + this[kConnection] = undefined; + this[kCancellationToken] = new mongo_types_1.CancellationToken(); + this[kCancellationToken].setMaxListeners(Infinity); + this[kMonitorId] = undefined; + this.s = { + state: common_1.STATE_CLOSED + }; + this.address = server.description.address; + this.options = Object.freeze({ + connectTimeoutMS: (_a = options.connectTimeoutMS) !== null && _a !== void 0 ? _a : 10000, + heartbeatFrequencyMS: (_b = options.heartbeatFrequencyMS) !== null && _b !== void 0 ? _b : 10000, + minHeartbeatFrequencyMS: (_c = options.minHeartbeatFrequencyMS) !== null && _c !== void 0 ? _c : 500 + }); + const cancellationToken = this[kCancellationToken]; + // TODO: refactor this to pull it directly from the pool, requires new ConnectionPool integration + const connectOptions = Object.assign({ + id: '', + generation: server.s.pool.generation, + connectionType: connection_1.Connection, + cancellationToken, + hostAddress: server.description.hostAddress + }, options, + // force BSON serialization options + { + raw: false, + promoteLongs: true, + promoteValues: true, + promoteBuffers: true + }); + // ensure no authentication is used for monitoring + delete connectOptions.credentials; + if (connectOptions.autoEncrypter) { + delete connectOptions.autoEncrypter; + } + this.connectOptions = Object.freeze(connectOptions); + } + get connection() { + return this[kConnection]; + } + connect() { + if (this.s.state !== common_1.STATE_CLOSED) { + return; + } + // start + const heartbeatFrequencyMS = this.options.heartbeatFrequencyMS; + const minHeartbeatFrequencyMS = this.options.minHeartbeatFrequencyMS; + this[kMonitorId] = (0, utils_1.makeInterruptibleAsyncInterval)(monitorServer(this), { + interval: heartbeatFrequencyMS, + minInterval: minHeartbeatFrequencyMS, + immediate: true + }); + } + requestCheck() { + var _a; + if (INVALID_REQUEST_CHECK_STATES.has(this.s.state)) { + return; + } + (_a = this[kMonitorId]) === null || _a === void 0 ? void 0 : _a.wake(); + } + reset() { + const topologyVersion = this[kServer].description.topologyVersion; + if (isInCloseState(this) || topologyVersion == null) { + return; + } + stateTransition(this, common_1.STATE_CLOSING); + resetMonitorState(this); + // restart monitor + stateTransition(this, STATE_IDLE); + // restart monitoring + const heartbeatFrequencyMS = this.options.heartbeatFrequencyMS; + const minHeartbeatFrequencyMS = this.options.minHeartbeatFrequencyMS; + this[kMonitorId] = (0, utils_1.makeInterruptibleAsyncInterval)(monitorServer(this), { + interval: heartbeatFrequencyMS, + minInterval: minHeartbeatFrequencyMS + }); + } + close() { + if (isInCloseState(this)) { + return; + } + stateTransition(this, common_1.STATE_CLOSING); + resetMonitorState(this); + // close monitor + this.emit('close'); + stateTransition(this, common_1.STATE_CLOSED); + } +} +exports.Monitor = Monitor; +function resetMonitorState(monitor) { + var _a, _b, _c; + (_a = monitor[kMonitorId]) === null || _a === void 0 ? void 0 : _a.stop(); + monitor[kMonitorId] = undefined; + (_b = monitor[kRTTPinger]) === null || _b === void 0 ? void 0 : _b.close(); + monitor[kRTTPinger] = undefined; + monitor[kCancellationToken].emit('cancel'); + (_c = monitor[kConnection]) === null || _c === void 0 ? void 0 : _c.destroy({ force: true }); + monitor[kConnection] = undefined; +} +function checkServer(monitor, callback) { + let start = (0, utils_1.now)(); + monitor.emit(server_1.Server.SERVER_HEARTBEAT_STARTED, new events_1.ServerHeartbeatStartedEvent(monitor.address)); + function failureHandler(err) { + var _a; + (_a = monitor[kConnection]) === null || _a === void 0 ? void 0 : _a.destroy({ force: true }); + monitor[kConnection] = undefined; + monitor.emit(server_1.Server.SERVER_HEARTBEAT_FAILED, new events_1.ServerHeartbeatFailedEvent(monitor.address, (0, utils_1.calculateDurationInMs)(start), err)); + monitor.emit('resetServer', err); + monitor.emit('resetConnectionPool'); + callback(err); + } + const connection = monitor[kConnection]; + if (connection && !connection.closed) { + const { serverApi, helloOk } = connection; + const connectTimeoutMS = monitor.options.connectTimeoutMS; + const maxAwaitTimeMS = monitor.options.heartbeatFrequencyMS; + const topologyVersion = monitor[kServer].description.topologyVersion; + const isAwaitable = topologyVersion != null; + const cmd = { + [(serverApi === null || serverApi === void 0 ? void 0 : serverApi.version) || helloOk ? 'hello' : constants_1.LEGACY_HELLO_COMMAND]: true, + ...(isAwaitable && topologyVersion + ? { maxAwaitTimeMS, topologyVersion: makeTopologyVersion(topologyVersion) } + : {}) + }; + const options = isAwaitable + ? { + socketTimeoutMS: connectTimeoutMS ? connectTimeoutMS + maxAwaitTimeMS : 0, + exhaustAllowed: true + } + : { socketTimeoutMS: connectTimeoutMS }; + if (isAwaitable && monitor[kRTTPinger] == null) { + monitor[kRTTPinger] = new RTTPinger(monitor[kCancellationToken], Object.assign({ heartbeatFrequencyMS: monitor.options.heartbeatFrequencyMS }, monitor.connectOptions)); + } + connection.command((0, utils_1.ns)('admin.$cmd'), cmd, options, (err, hello) => { + var _a; + if (err) { + return failureHandler(err); + } + if (!('isWritablePrimary' in hello)) { + // Provide hello-style response document. + hello.isWritablePrimary = hello[constants_1.LEGACY_HELLO_COMMAND]; + } + const rttPinger = monitor[kRTTPinger]; + const duration = isAwaitable && rttPinger ? rttPinger.roundTripTime : (0, utils_1.calculateDurationInMs)(start); + monitor.emit(server_1.Server.SERVER_HEARTBEAT_SUCCEEDED, new events_1.ServerHeartbeatSucceededEvent(monitor.address, duration, hello)); + // if we are using the streaming protocol then we immediately issue another `started` + // event, otherwise the "check" is complete and return to the main monitor loop + if (isAwaitable && hello.topologyVersion) { + monitor.emit(server_1.Server.SERVER_HEARTBEAT_STARTED, new events_1.ServerHeartbeatStartedEvent(monitor.address)); + start = (0, utils_1.now)(); + } + else { + (_a = monitor[kRTTPinger]) === null || _a === void 0 ? void 0 : _a.close(); + monitor[kRTTPinger] = undefined; + callback(undefined, hello); + } + }); + return; + } + // connecting does an implicit `hello` + (0, connect_1.connect)(monitor.connectOptions, (err, conn) => { + if (err) { + monitor[kConnection] = undefined; + // we already reset the connection pool on network errors in all cases + if (!(err instanceof error_1.MongoNetworkError)) { + monitor.emit('resetConnectionPool'); + } + failureHandler(err); + return; + } + if (conn) { + // Tell the connection that we are using the streaming protocol so that the + // connection's message stream will only read the last hello on the buffer. + conn.isMonitoringConnection = true; + if (isInCloseState(monitor)) { + conn.destroy({ force: true }); + return; + } + monitor[kConnection] = conn; + monitor.emit(server_1.Server.SERVER_HEARTBEAT_SUCCEEDED, new events_1.ServerHeartbeatSucceededEvent(monitor.address, (0, utils_1.calculateDurationInMs)(start), conn.hello)); + callback(undefined, conn.hello); + } + }); +} +function monitorServer(monitor) { + return (callback) => { + stateTransition(monitor, STATE_MONITORING); + function done() { + if (!isInCloseState(monitor)) { + stateTransition(monitor, STATE_IDLE); + } + callback(); + } + checkServer(monitor, (err, hello) => { + if (err) { + // otherwise an error occurred on initial discovery, also bail + if (monitor[kServer].description.type === common_1.ServerType.Unknown) { + monitor.emit('resetServer', err); + return done(); + } + } + // if the check indicates streaming is supported, immediately reschedule monitoring + if (hello && hello.topologyVersion) { + (0, timers_1.setTimeout)(() => { + var _a; + if (!isInCloseState(monitor)) { + (_a = monitor[kMonitorId]) === null || _a === void 0 ? void 0 : _a.wake(); + } + }, 0); + } + done(); + }); + }; +} +function makeTopologyVersion(tv) { + return { + processId: tv.processId, + // tests mock counter as just number, but in a real situation counter should always be a Long + counter: bson_1.Long.isLong(tv.counter) ? tv.counter : bson_1.Long.fromNumber(tv.counter) + }; +} +/** @internal */ +class RTTPinger { + constructor(cancellationToken, options) { + this[kConnection] = undefined; + this[kCancellationToken] = cancellationToken; + this[kRoundTripTime] = 0; + this.closed = false; + const heartbeatFrequencyMS = options.heartbeatFrequencyMS; + this[kMonitorId] = (0, timers_1.setTimeout)(() => measureRoundTripTime(this, options), heartbeatFrequencyMS); + } + get roundTripTime() { + return this[kRoundTripTime]; + } + close() { + var _a; + this.closed = true; + clearTimeout(this[kMonitorId]); + (_a = this[kConnection]) === null || _a === void 0 ? void 0 : _a.destroy({ force: true }); + this[kConnection] = undefined; + } +} +exports.RTTPinger = RTTPinger; +function measureRoundTripTime(rttPinger, options) { + const start = (0, utils_1.now)(); + options.cancellationToken = rttPinger[kCancellationToken]; + const heartbeatFrequencyMS = options.heartbeatFrequencyMS; + if (rttPinger.closed) { + return; + } + function measureAndReschedule(conn) { + if (rttPinger.closed) { + conn === null || conn === void 0 ? void 0 : conn.destroy({ force: true }); + return; + } + if (rttPinger[kConnection] == null) { + rttPinger[kConnection] = conn; + } + rttPinger[kRoundTripTime] = (0, utils_1.calculateDurationInMs)(start); + rttPinger[kMonitorId] = (0, timers_1.setTimeout)(() => measureRoundTripTime(rttPinger, options), heartbeatFrequencyMS); + } + const connection = rttPinger[kConnection]; + if (connection == null) { + (0, connect_1.connect)(options, (err, conn) => { + if (err) { + rttPinger[kConnection] = undefined; + rttPinger[kRoundTripTime] = 0; + return; + } + measureAndReschedule(conn); + }); + return; + } + connection.command((0, utils_1.ns)('admin.$cmd'), { [constants_1.LEGACY_HELLO_COMMAND]: 1 }, undefined, err => { + if (err) { + rttPinger[kConnection] = undefined; + rttPinger[kRoundTripTime] = 0; + return; + } + measureAndReschedule(); + }); +} +//# sourceMappingURL=monitor.js.map \ No newline at end of file diff --git a/ts-ticket-office-service/node_modules/mongodb/lib/sdam/monitor.js.map b/ts-ticket-office-service/node_modules/mongodb/lib/sdam/monitor.js.map new file mode 100644 index 000000000..f2ef5a83e --- /dev/null +++ b/ts-ticket-office-service/node_modules/mongodb/lib/sdam/monitor.js.map @@ -0,0 +1 @@ +{"version":3,"file":"monitor.js","sourceRoot":"","sources":["../../src/sdam/monitor.ts"],"names":[],"mappings":";;;AAAA,mCAAoC;AAEpC,kCAAyC;AACzC,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C,CAAC;AACL,CAAC"} \ No newline at end of file diff --git a/ts-ticket-office-service/node_modules/mongodb/lib/sdam/server.js b/ts-ticket-office-service/node_modules/mongodb/lib/sdam/server.js new file mode 100644 index 000000000..70e4ec376 --- /dev/null +++ b/ts-ticket-office-service/node_modules/mongodb/lib/sdam/server.js @@ -0,0 +1,396 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.Server = void 0; +const connection_1 = require("../cmap/connection"); +const connection_pool_1 = require("../cmap/connection_pool"); +const constants_1 = require("../constants"); +const error_1 = require("../error"); +const logger_1 = require("../logger"); +const mongo_types_1 = require("../mongo_types"); +const transactions_1 = require("../transactions"); +const utils_1 = require("../utils"); +const common_1 = require("./common"); +const monitor_1 = require("./monitor"); +const server_description_1 = require("./server_description"); +const stateTransition = (0, utils_1.makeStateMachine)({ + [common_1.STATE_CLOSED]: [common_1.STATE_CLOSED, common_1.STATE_CONNECTING], + [common_1.STATE_CONNECTING]: [common_1.STATE_CONNECTING, common_1.STATE_CLOSING, common_1.STATE_CONNECTED, common_1.STATE_CLOSED], + [common_1.STATE_CONNECTED]: [common_1.STATE_CONNECTED, common_1.STATE_CLOSING, common_1.STATE_CLOSED], + [common_1.STATE_CLOSING]: [common_1.STATE_CLOSING, common_1.STATE_CLOSED] +}); +/** @internal */ +const kMonitor = Symbol('monitor'); +/** @internal */ +class Server extends mongo_types_1.TypedEventEmitter { + /** + * Create a server + */ + constructor(topology, description, options) { + super(); + this.serverApi = options.serverApi; + const poolOptions = { hostAddress: description.hostAddress, ...options }; + this.s = { + description, + options, + logger: new logger_1.Logger('Server'), + state: common_1.STATE_CLOSED, + topology, + pool: new connection_pool_1.ConnectionPool(poolOptions), + operationCount: 0 + }; + for (const event of [...constants_1.CMAP_EVENTS, ...constants_1.APM_EVENTS]) { + this.s.pool.on(event, (e) => this.emit(event, e)); + } + this.s.pool.on(connection_1.Connection.CLUSTER_TIME_RECEIVED, (clusterTime) => { + this.clusterTime = clusterTime; + }); + if (this.loadBalanced) { + this[kMonitor] = null; + // monitoring is disabled in load balancing mode + return; + } + // create the monitor + // TODO(NODE-4144): Remove new variable for type narrowing + const monitor = new monitor_1.Monitor(this, this.s.options); + this[kMonitor] = monitor; + for (const event of constants_1.HEARTBEAT_EVENTS) { + monitor.on(event, (e) => this.emit(event, e)); + } + monitor.on('resetConnectionPool', () => { + this.s.pool.clear(); + }); + monitor.on('resetServer', (error) => markServerUnknown(this, error)); + monitor.on(Server.SERVER_HEARTBEAT_SUCCEEDED, (event) => { + this.emit(Server.DESCRIPTION_RECEIVED, new server_description_1.ServerDescription(this.description.hostAddress, event.reply, { + roundTripTime: calculateRoundTripTime(this.description.roundTripTime, event.duration) + })); + if (this.s.state === common_1.STATE_CONNECTING) { + stateTransition(this, common_1.STATE_CONNECTED); + this.emit(Server.CONNECT, this); + } + }); + } + get clusterTime() { + return this.s.topology.clusterTime; + } + set clusterTime(clusterTime) { + this.s.topology.clusterTime = clusterTime; + } + get description() { + return this.s.description; + } + get name() { + return this.s.description.address; + } + get autoEncrypter() { + if (this.s.options && this.s.options.autoEncrypter) { + return this.s.options.autoEncrypter; + } + return; + } + get loadBalanced() { + return this.s.topology.description.type === common_1.TopologyType.LoadBalanced; + } + /** + * Initiate server connect + */ + connect() { + var _a; + if (this.s.state !== common_1.STATE_CLOSED) { + return; + } + stateTransition(this, common_1.STATE_CONNECTING); + // If in load balancer mode we automatically set the server to + // a load balancer. It never transitions out of this state and + // has no monitor. + if (!this.loadBalanced) { + (_a = this[kMonitor]) === null || _a === void 0 ? void 0 : _a.connect(); + } + else { + stateTransition(this, common_1.STATE_CONNECTED); + this.emit(Server.CONNECT, this); + } + } + /** Destroy the server connection */ + destroy(options, callback) { + var _a; + if (typeof options === 'function') + (callback = options), (options = {}); + options = Object.assign({}, { force: false }, options); + if (this.s.state === common_1.STATE_CLOSED) { + if (typeof callback === 'function') { + callback(); + } + return; + } + stateTransition(this, common_1.STATE_CLOSING); + if (!this.loadBalanced) { + (_a = this[kMonitor]) === null || _a === void 0 ? void 0 : _a.close(); + } + this.s.pool.close(options, err => { + stateTransition(this, common_1.STATE_CLOSED); + this.emit('closed'); + if (typeof callback === 'function') { + callback(err); + } + }); + } + /** + * Immediately schedule monitoring of this server. If there already an attempt being made + * this will be a no-op. + */ + requestCheck() { + var _a; + if (!this.loadBalanced) { + (_a = this[kMonitor]) === null || _a === void 0 ? void 0 : _a.requestCheck(); + } + } + /** + * Execute a command + * @internal + */ + command(ns, cmd, options, callback) { + if (callback == null) { + throw new error_1.MongoInvalidArgumentError('Callback must be provided'); + } + if (ns.db == null || typeof ns === 'string') { + throw new error_1.MongoInvalidArgumentError('Namespace must not be a string'); + } + if (this.s.state === common_1.STATE_CLOSING || this.s.state === common_1.STATE_CLOSED) { + callback(new error_1.MongoServerClosedError()); + return; + } + // Clone the options + const finalOptions = Object.assign({}, options, { wireProtocolCommand: false }); + // There are cases where we need to flag the read preference not to get sent in + // the command, such as pre-5.0 servers attempting to perform an aggregate write + // with a non-primary read preference. In this case the effective read preference + // (primary) is not the same as the provided and must be removed completely. + if (finalOptions.omitReadPreference) { + delete finalOptions.readPreference; + } + // error if collation not supported + if ((0, utils_1.collationNotSupported)(this, cmd)) { + callback(new error_1.MongoCompatibilityError(`Server ${this.name} does not support collation`)); + return; + } + const session = finalOptions.session; + const conn = session === null || session === void 0 ? void 0 : session.pinnedConnection; + // NOTE: This is a hack! We can't retrieve the connections used for executing an operation + // (and prevent them from being checked back in) at the point of operation execution. + // This should be considered as part of the work for NODE-2882 + // NOTE: + // When incrementing operation count, it's important that we increment it before we + // attempt to check out a connection from the pool. This ensures that operations that + // are waiting for a connection are included in the operation count. Load balanced + // mode will only ever have a single server, so the operation count doesn't matter. + // Incrementing the operation count above the logic to handle load balanced mode would + // require special logic to decrement it again, or would double increment (the load + // balanced code makes a recursive call). Instead, we increment the count after this + // check. + if (this.loadBalanced && session && conn == null && isPinnableCommand(cmd, session)) { + this.s.pool.checkOut((err, checkedOut) => { + if (err || checkedOut == null) { + if (callback) + return callback(err); + return; + } + session.pin(checkedOut); + this.command(ns, cmd, finalOptions, callback); + }); + return; + } + this.s.operationCount += 1; + this.s.pool.withConnection(conn, (err, conn, cb) => { + if (err || !conn) { + this.s.operationCount -= 1; + markServerUnknown(this, err); + return cb(err); + } + conn.command(ns, cmd, finalOptions, makeOperationHandler(this, conn, cmd, finalOptions, (error, response) => { + this.s.operationCount -= 1; + cb(error, response); + })); + }, callback); + } + /** + * Execute a `getMore` against the server + * @internal + */ + getMore(ns, cursorId, options, callback) { + var _a; + if (this.s.state === common_1.STATE_CLOSING || this.s.state === common_1.STATE_CLOSED) { + callback(new error_1.MongoServerClosedError()); + return; + } + this.s.operationCount += 1; + this.s.pool.withConnection((_a = options.session) === null || _a === void 0 ? void 0 : _a.pinnedConnection, (err, conn, cb) => { + if (err || !conn) { + this.s.operationCount -= 1; + markServerUnknown(this, err); + return cb(err); + } + conn.getMore(ns, cursorId, options, makeOperationHandler(this, conn, {}, options, (error, response) => { + this.s.operationCount -= 1; + cb(error, response); + })); + }, callback); + } + /** + * Execute a `killCursors` command against the server + * @internal + */ + killCursors(ns, cursorIds, options, callback) { + var _a; + if (this.s.state === common_1.STATE_CLOSING || this.s.state === common_1.STATE_CLOSED) { + if (typeof callback === 'function') { + callback(new error_1.MongoServerClosedError()); + } + return; + } + this.s.operationCount += 1; + this.s.pool.withConnection((_a = options.session) === null || _a === void 0 ? void 0 : _a.pinnedConnection, (err, conn, cb) => { + if (err || !conn) { + this.s.operationCount -= 1; + markServerUnknown(this, err); + return cb(err); + } + conn.killCursors(ns, cursorIds, options, makeOperationHandler(this, conn, {}, undefined, (error, response) => { + this.s.operationCount -= 1; + cb(error, response); + })); + }, callback); + } +} +exports.Server = Server; +/** @event */ +Server.SERVER_HEARTBEAT_STARTED = constants_1.SERVER_HEARTBEAT_STARTED; +/** @event */ +Server.SERVER_HEARTBEAT_SUCCEEDED = constants_1.SERVER_HEARTBEAT_SUCCEEDED; +/** @event */ +Server.SERVER_HEARTBEAT_FAILED = constants_1.SERVER_HEARTBEAT_FAILED; +/** @event */ +Server.CONNECT = constants_1.CONNECT; +/** @event */ +Server.DESCRIPTION_RECEIVED = constants_1.DESCRIPTION_RECEIVED; +/** @event */ +Server.CLOSED = constants_1.CLOSED; +/** @event */ +Server.ENDED = constants_1.ENDED; +function calculateRoundTripTime(oldRtt, duration) { + if (oldRtt === -1) { + return duration; + } + const alpha = 0.2; + return alpha * duration + (1 - alpha) * oldRtt; +} +function markServerUnknown(server, error) { + var _a; + // Load balancer servers can never be marked unknown. + if (server.loadBalanced) { + return; + } + if (error instanceof error_1.MongoNetworkError && !(error instanceof error_1.MongoNetworkTimeoutError)) { + (_a = server[kMonitor]) === null || _a === void 0 ? void 0 : _a.reset(); + } + server.emit(Server.DESCRIPTION_RECEIVED, new server_description_1.ServerDescription(server.description.hostAddress, undefined, { + error, + topologyVersion: error && error.topologyVersion ? error.topologyVersion : server.description.topologyVersion + })); +} +function isPinnableCommand(cmd, session) { + if (session) { + return (session.inTransaction() || + 'aggregate' in cmd || + 'find' in cmd || + 'getMore' in cmd || + 'listCollections' in cmd || + 'listIndexes' in cmd); + } + return false; +} +function connectionIsStale(pool, connection) { + if (connection.serviceId) { + return (connection.generation !== pool.serviceGenerations.get(connection.serviceId.toHexString())); + } + return connection.generation !== pool.generation; +} +function shouldHandleStateChangeError(server, err) { + const etv = err.topologyVersion; + const stv = server.description.topologyVersion; + return (0, server_description_1.compareTopologyVersion)(stv, etv) < 0; +} +function inActiveTransaction(session, cmd) { + return session && session.inTransaction() && !(0, transactions_1.isTransactionCommand)(cmd); +} +/** this checks the retryWrites option passed down from the client options, it + * does not check if the server supports retryable writes */ +function isRetryableWritesEnabled(topology) { + return topology.s.options.retryWrites !== false; +} +function makeOperationHandler(server, connection, cmd, options, callback) { + const session = options === null || options === void 0 ? void 0 : options.session; + return function handleOperationResult(error, result) { + if (result != null) { + return callback(undefined, result); + } + if (!error) { + return callback(new error_1.MongoUnexpectedServerResponseError('Empty response with no error')); + } + if (!(error instanceof error_1.MongoError)) { + // Node.js or some other error we have not special handling for + return callback(error); + } + if (connectionIsStale(server.s.pool, connection)) { + return callback(error); + } + if (error instanceof error_1.MongoNetworkError) { + if (session && !session.hasEnded && session.serverSession) { + session.serverSession.isDirty = true; + } + // inActiveTransaction check handles commit and abort. + if (inActiveTransaction(session, cmd) && + !error.hasErrorLabel(error_1.MongoErrorLabel.TransientTransactionError)) { + error.addErrorLabel(error_1.MongoErrorLabel.TransientTransactionError); + } + if ((isRetryableWritesEnabled(server.s.topology) || (0, transactions_1.isTransactionCommand)(cmd)) && + (0, utils_1.supportsRetryableWrites)(server) && + !inActiveTransaction(session, cmd)) { + error.addErrorLabel(error_1.MongoErrorLabel.RetryableWriteError); + } + if (!(error instanceof error_1.MongoNetworkTimeoutError) || (0, error_1.isNetworkErrorBeforeHandshake)(error)) { + // In load balanced mode we never mark the server as unknown and always + // clear for the specific service id. + server.s.pool.clear(connection.serviceId); + if (!server.loadBalanced) { + markServerUnknown(server, error); + } + } + } + else { + if ((isRetryableWritesEnabled(server.s.topology) || (0, transactions_1.isTransactionCommand)(cmd)) && + (0, error_1.needsRetryableWriteLabel)(error, (0, utils_1.maxWireVersion)(server)) && + !inActiveTransaction(session, cmd)) { + error.addErrorLabel(error_1.MongoErrorLabel.RetryableWriteError); + } + if ((0, error_1.isSDAMUnrecoverableError)(error)) { + if (shouldHandleStateChangeError(server, error)) { + if ((0, utils_1.maxWireVersion)(server) <= 7 || (0, error_1.isNodeShuttingDownError)(error)) { + server.s.pool.clear(connection.serviceId); + } + if (!server.loadBalanced) { + markServerUnknown(server, error); + process.nextTick(() => server.requestCheck()); + } + } + } + } + if (session && + session.isPinned && + error.hasErrorLabel(error_1.MongoErrorLabel.TransientTransactionError)) { + session.unpin({ force: true }); + } + return callback(error); + }; +} +//# sourceMappingURL=server.js.map \ No newline at end of file diff --git a/ts-ticket-office-service/node_modules/mongodb/lib/sdam/server.js.map b/ts-ticket-office-service/node_modules/mongodb/lib/sdam/server.js.map new file mode 100644 index 000000000..ea6340f6b --- /dev/null +++ b/ts-ticket-office-service/node_modules/mongodb/lib/sdam/server.js.map @@ -0,0 +1 @@ +{"version":3,"file":"server.js","sourceRoot":"","sources":["../../src/sdam/server.ts"],"names":[],"mappings":";;;AACA,mDAAgG;AAChG,6DAIiC;AACjC,4CAWsB;AAEtB,oCAakB;AAClB,sCAAmC;AAEnC,gDAAmD;AAEnD,kDAAuD;AACvD,oCAQkB;AAClB,qCAOkB;AAMlB,uCAAoD;AACpD,6DAAiF;AAGjF,MAAM,eAAe,GAAG,IAAA,wBAAgB,EAAC;IACvC,CAAC,qBAAY,CAAC,EAAE,CAAC,qBAAY,EAAE,yBAAgB,CAAC;IAChD,CAAC,yBAAgB,CAAC,EAAE,CAAC,yBAAgB,EAAE,sBAAa,EAAE,wBAAe,EAAE,qBAAY,CAAC;IACpF,CAAC,wBAAe,CAAC,EAAE,CAAC,wBAAe,EAAE,sBAAa,EAAE,qBAAY,CAAC;IACjE,CAAC,sBAAa,CAAC,EAAE,CAAC,sBAAa,EAAE,qBAAY,CAAC;CAC/C,CAAC,CAAC;AAEH,gBAAgB;AAChB,MAAM,QAAQ,GAAG,MAAM,CAAC,SAAS,CAAC,CAAC;AAuCnC,gBAAgB;AAChB,MAAa,MAAO,SAAQ,+BAA+B;IAsBzD;;OAEG;IACH,YAAY,QAAkB,EAAE,WAA8B,EAAE,OAAsB;QACpF,KAAK,EAAE,CAAC;QAER,IAAI,CAAC,SAAS,GAAG,OAAO,CAAC,SAAS,CAAC;QAEnC,MAAM,WAAW,GAAG,EAAE,WAAW,EAAE,WAAW,CAAC,WAAW,EAAE,GAAG,OAAO,EAAE,CAAC;QAEzE,IAAI,CAAC,CAAC,GAAG;YACP,WAAW;YACX,OAAO;YACP,MAAM,EAAE,IAAI,eAAM,CAAC,QAAQ,CAAC;YAC5B,KAAK,EAAE,qBAAY;YACnB,QAAQ;YACR,IAAI,EAAE,IAAI,gCAAc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xB,iBAAiB,CAAC,MAAM,EAAE,KAAK,CAAC,CAAC;iBAClC;aACF;SACF;aAAM;YACL,IACE,CAAC,wBAAwB,CAAC,MAAM,CAAC,CAAC,CAAC,QAAQ,CAAC,IAAI,IAAA,mCAAoB,EAAC,GAAG,CAAC,CAAC;gBAC1E,IAAA,gCAAwB,EAAC,KAAK,EAAE,IAAA,sBAAc,EAAC,MAAM,CAAC,CAAC;gBACvD,CAAC,mBAAmB,CAAC,OAAO,EAAE,GAAG,CAAC,EAClC;gBACA,KAAK,CAAC,aAAa,CAAC,uBAAe,CAAC,mBAAmB,CAAC,CAAC;aAC1D;YAED,IAAI,IAAA,gCAAwB,EAAC,KAAK,CAAC,EAAE;gBACnC,IAAI,4BAA4B,CAAC,MAAM,EAAE,KAAK,CAAC,EAAE;oBAC/C,IAAI,IAAA,sBAAc,EAAC,MAAM,CAAC,IAAI,CAAC,IAAI,IAAA,+BAAuB,EAAC,KAAK,CAAC,EAAE;wBACjE,MAAM,CAAC,CAAC,CAAC,IAAI,CAAC,KAAK,CAAC,UAAU,CAAC,SAAS,CAAC,CAAC;qBAC3C;oBAED,IAAI,CAAC,MAAM,CAAC,YAAY,EAAE;wBACxB,iBAAiB,CAAC,MAAM,EAAE,KAAK,CAAC,CAAC;wBACjC,OAAO,CAAC,QAAQ,CAAC,GAAG,EAAE,CAAC,MAAM,CAAC,YAAY,EAAE,CAAC,CAAC;qBAC/C;iBACF;aACF;SACF;QAED,IACE,OAAO;YACP,OAAO,CAAC,QAAQ;YAChB,KAAK,CAAC,aAAa,CAAC,uBAAe,CAAC,yBAAyB,CAAC,EAC9D;YACA,OAAO,CAAC,KAAK,CAAC,EAAE,KAAK,EAAE,IAAI,EAAE,CAAC,CAAC;SAChC;QAED,OAAO,QAAQ,CAAC,KAAK,CAAC,CAAC;IACzB,CAAC,CAAC;AACJ,CAAC"} \ No newline at end of file diff --git a/ts-ticket-office-service/node_modules/mongodb/lib/sdam/server_description.js b/ts-ticket-office-service/node_modules/mongodb/lib/sdam/server_description.js new file mode 100644 index 000000000..fc3e3e5b3 --- /dev/null +++ b/ts-ticket-office-service/node_modules/mongodb/lib/sdam/server_description.js @@ -0,0 +1,197 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.compareTopologyVersion = exports.parseServerType = exports.ServerDescription = void 0; +const bson_1 = require("../bson"); +const utils_1 = require("../utils"); +const common_1 = require("./common"); +const WRITABLE_SERVER_TYPES = new Set([ + common_1.ServerType.RSPrimary, + common_1.ServerType.Standalone, + common_1.ServerType.Mongos, + common_1.ServerType.LoadBalancer +]); +const DATA_BEARING_SERVER_TYPES = new Set([ + common_1.ServerType.RSPrimary, + common_1.ServerType.RSSecondary, + common_1.ServerType.Mongos, + common_1.ServerType.Standalone, + common_1.ServerType.LoadBalancer +]); +/** + * The client's view of a single server, based on the most recent hello outcome. + * + * Internal type, not meant to be directly instantiated + * @public + */ +class ServerDescription { + /** + * Create a ServerDescription + * @internal + * + * @param address - The address of the server + * @param hello - An optional hello response for this server + */ + constructor(address, hello, options) { + var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l, _m; + if (typeof address === 'string') { + this._hostAddress = new utils_1.HostAddress(address); + this.address = this._hostAddress.toString(); + } + else { + this._hostAddress = address; + this.address = this._hostAddress.toString(); + } + this.type = parseServerType(hello, options); + this.hosts = (_b = (_a = hello === null || hello === void 0 ? void 0 : hello.hosts) === null || _a === void 0 ? void 0 : _a.map((host) => host.toLowerCase())) !== null && _b !== void 0 ? _b : []; + this.passives = (_d = (_c = hello === null || hello === void 0 ? void 0 : hello.passives) === null || _c === void 0 ? void 0 : _c.map((host) => host.toLowerCase())) !== null && _d !== void 0 ? _d : []; + this.arbiters = (_f = (_e = hello === null || hello === void 0 ? void 0 : hello.arbiters) === null || _e === void 0 ? void 0 : _e.map((host) => host.toLowerCase())) !== null && _f !== void 0 ? _f : []; + this.tags = (_g = hello === null || hello === void 0 ? void 0 : hello.tags) !== null && _g !== void 0 ? _g : {}; + this.minWireVersion = (_h = hello === null || hello === void 0 ? void 0 : hello.minWireVersion) !== null && _h !== void 0 ? _h : 0; + this.maxWireVersion = (_j = hello === null || hello === void 0 ? void 0 : hello.maxWireVersion) !== null && _j !== void 0 ? _j : 0; + this.roundTripTime = (_k = options === null || options === void 0 ? void 0 : options.roundTripTime) !== null && _k !== void 0 ? _k : -1; + this.lastUpdateTime = (0, utils_1.now)(); + this.lastWriteDate = (_m = (_l = hello === null || hello === void 0 ? void 0 : hello.lastWrite) === null || _l === void 0 ? void 0 : _l.lastWriteDate) !== null && _m !== void 0 ? _m : 0; + if (options === null || options === void 0 ? void 0 : options.topologyVersion) { + this.topologyVersion = options.topologyVersion; + } + else if (hello === null || hello === void 0 ? void 0 : hello.topologyVersion) { + this.topologyVersion = hello.topologyVersion; + } + if (options === null || options === void 0 ? void 0 : options.error) { + this.error = options.error; + } + if (hello === null || hello === void 0 ? void 0 : hello.primary) { + this.primary = hello.primary; + } + if (hello === null || hello === void 0 ? void 0 : hello.me) { + this.me = hello.me.toLowerCase(); + } + if (hello === null || hello === void 0 ? void 0 : hello.setName) { + this.setName = hello.setName; + } + if (hello === null || hello === void 0 ? void 0 : hello.setVersion) { + this.setVersion = hello.setVersion; + } + if (hello === null || hello === void 0 ? void 0 : hello.electionId) { + this.electionId = hello.electionId; + } + if (hello === null || hello === void 0 ? void 0 : hello.logicalSessionTimeoutMinutes) { + this.logicalSessionTimeoutMinutes = hello.logicalSessionTimeoutMinutes; + } + if (hello === null || hello === void 0 ? void 0 : hello.$clusterTime) { + this.$clusterTime = hello.$clusterTime; + } + } + get hostAddress() { + if (this._hostAddress) + return this._hostAddress; + else + return new utils_1.HostAddress(this.address); + } + get allHosts() { + return this.hosts.concat(this.arbiters).concat(this.passives); + } + /** Is this server available for reads*/ + get isReadable() { + return this.type === common_1.ServerType.RSSecondary || this.isWritable; + } + /** Is this server data bearing */ + get isDataBearing() { + return DATA_BEARING_SERVER_TYPES.has(this.type); + } + /** Is this server available for writes */ + get isWritable() { + return WRITABLE_SERVER_TYPES.has(this.type); + } + get host() { + const chopLength = `:${this.port}`.length; + return this.address.slice(0, -chopLength); + } + get port() { + const port = this.address.split(':').pop(); + return port ? Number.parseInt(port, 10) : 27017; + } + /** + * Determines if another `ServerDescription` is equal to this one per the rules defined + * in the {@link https://github.com/mongodb/specifications/blob/master/source/server-discovery-and-monitoring/server-discovery-and-monitoring.rst#serverdescription|SDAM spec} + */ + equals(other) { + const topologyVersionsEqual = this.topologyVersion === other.topologyVersion || + compareTopologyVersion(this.topologyVersion, other.topologyVersion) === 0; + const electionIdsEqual = this.electionId && other.electionId + ? other.electionId && this.electionId.equals(other.electionId) + : this.electionId === other.electionId; + return (other != null && + (0, utils_1.errorStrictEqual)(this.error, other.error) && + this.type === other.type && + this.minWireVersion === other.minWireVersion && + (0, utils_1.arrayStrictEqual)(this.hosts, other.hosts) && + tagsStrictEqual(this.tags, other.tags) && + this.setName === other.setName && + this.setVersion === other.setVersion && + electionIdsEqual && + this.primary === other.primary && + this.logicalSessionTimeoutMinutes === other.logicalSessionTimeoutMinutes && + topologyVersionsEqual); + } +} +exports.ServerDescription = ServerDescription; +// Parses a `hello` message and determines the server type +function parseServerType(hello, options) { + if (options === null || options === void 0 ? void 0 : options.loadBalanced) { + return common_1.ServerType.LoadBalancer; + } + if (!hello || !hello.ok) { + return common_1.ServerType.Unknown; + } + if (hello.isreplicaset) { + return common_1.ServerType.RSGhost; + } + if (hello.msg && hello.msg === 'isdbgrid') { + return common_1.ServerType.Mongos; + } + if (hello.setName) { + if (hello.hidden) { + return common_1.ServerType.RSOther; + } + else if (hello.isWritablePrimary) { + return common_1.ServerType.RSPrimary; + } + else if (hello.secondary) { + return common_1.ServerType.RSSecondary; + } + else if (hello.arbiterOnly) { + return common_1.ServerType.RSArbiter; + } + else { + return common_1.ServerType.RSOther; + } + } + return common_1.ServerType.Standalone; +} +exports.parseServerType = parseServerType; +function tagsStrictEqual(tags, tags2) { + const tagsKeys = Object.keys(tags); + const tags2Keys = Object.keys(tags2); + return (tagsKeys.length === tags2Keys.length && + tagsKeys.every((key) => tags2[key] === tags[key])); +} +/** + * Compares two topology versions. + * + * @returns A negative number if `lhs` is older than `rhs`; positive if `lhs` is newer than `rhs`; 0 if they are equivalent. + */ +function compareTopologyVersion(lhs, rhs) { + if (lhs == null || rhs == null) { + return -1; + } + if (lhs.processId.equals(rhs.processId)) { + // tests mock counter as just number, but in a real situation counter should always be a Long + const lhsCounter = bson_1.Long.isLong(lhs.counter) ? lhs.counter : bson_1.Long.fromNumber(lhs.counter); + const rhsCounter = bson_1.Long.isLong(rhs.counter) ? lhs.counter : bson_1.Long.fromNumber(rhs.counter); + return lhsCounter.compare(rhsCounter); + } + return -1; +} +exports.compareTopologyVersion = compareTopologyVersion; +//# sourceMappingURL=server_description.js.map \ No newline at end of file diff --git a/ts-ticket-office-service/node_modules/mongodb/lib/sdam/server_description.js.map b/ts-ticket-office-service/node_modules/mongodb/lib/sdam/server_description.js.map new file mode 100644 index 000000000..d81da31ae --- /dev/null +++ b/ts-ticket-office-service/node_modules/mongodb/lib/sdam/server_description.js.map @@ -0,0 +1 @@ +{"version":3,"file":"server_description.js","sourceRoot":"","sources":["../../src/sdam/server_description.ts"],"names":[],"mappings":";;;AAAA,kCAAmD;AAEnD,oCAAgF;AAEhF,qCAAsC;AAEtC,MAAM,qBAAqB,GAAG,IAAI,GAAG,CAAa;IAChD,mBAAU,CAAC,SAAS;IACpB,mBAAU,CAAC,UAAU;IACrB,mBAAU,CAAC,MAAM;IACjB,mBAAU,CAAC,YAAY;CACxB,CAAC,CAAC;AAEH,MAAM,yBAAyB,GAAG,IAAI,GAAG,CAAa;IACpD,mBAAU,CAAC,SAAS;IACpB,mBAAU,CAAC,WAAW;IACtB,mBAAU,CAAC,MAAM;IACjB,mBAAU,CAAC,UAAU;IACrB,mBAAU,CAAC,YAAY;CACxB,CAAC,CAAC;AA0BH;;;;;GAKG;AACH,MAAa,iBAAiB;IA2B5B;;;;;;OAMG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,CAAC,KAAK,CAAC,CAAC,GAAW,EAAE,EAAE,CAAC,KAAK,CAAC,GAAG,CAAC,KAAK,IAAI,CAAC,GAAG,CAAC,CAAC,CAC1D,CAAC;AACJ,CAAC;AAED;;;;GAIG;AACH,SAAgB,sBAAsB,CAAC,GAAqB,EAAE,GAAqB;IACjF,IAAI,GAAG,IAAI,IAAI,IAAI,GAAG,IAAI,IAAI,EAAE;QAC9B,OAAO,CAAC,CAAC,CAAC;KACX;IAED,IAAI,GAAG,CAAC,SAAS,CAAC,MAAM,CAAC,GAAG,CAAC,SAAS,CAAC,EAAE;QACvC,6FAA6F;QAC7F,MAAM,UAAU,GAAG,WAAI,CAAC,MAAM,CAAC,GAAG,CAAC,OAAO,CAAC,CAAC,CAAC,CAAC,GAAG,CAAC,OAAO,CAAC,CAAC,CAAC,WAAI,CAAC,UAAU,CAAC,GAAG,CAAC,OAAO,CAAC,CAAC;QACzF,MAAM,UAAU,GAAG,WAAI,CAAC,MAAM,CAAC,GAAG,CAAC,OAAO,CAAC,CAAC,CAAC,CAAC,GAAG,CAAC,OAAO,CAAC,CAAC,CAAC,WAAI,CAAC,UAAU,CAAC,GAAG,CAAC,OAAO,CAAC,CAAC;QACzF,OAAO,UAAU,CAAC,OAAO,CAAC,UAAU,CAAC,CAAC;KACvC;IAED,OAAO,CAAC,CAAC,CAAC;AACZ,CAAC;AAbD,wDAaC"} \ No newline at end of file diff --git a/ts-ticket-office-service/node_modules/mongodb/lib/sdam/server_selection.js b/ts-ticket-office-service/node_modules/mongodb/lib/sdam/server_selection.js new file mode 100644 index 000000000..1d3c878ec --- /dev/null +++ b/ts-ticket-office-service/node_modules/mongodb/lib/sdam/server_selection.js @@ -0,0 +1,228 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.readPreferenceServerSelector = exports.secondaryWritableServerSelector = exports.sameServerSelector = exports.writableServerSelector = exports.MIN_SECONDARY_WRITE_WIRE_VERSION = void 0; +const error_1 = require("../error"); +const read_preference_1 = require("../read_preference"); +const common_1 = require("./common"); +// max staleness constants +const IDLE_WRITE_PERIOD = 10000; +const SMALLEST_MAX_STALENESS_SECONDS = 90; +// Minimum version to try writes on secondaries. +exports.MIN_SECONDARY_WRITE_WIRE_VERSION = 13; +/** + * Returns a server selector that selects for writable servers + */ +function writableServerSelector() { + return (topologyDescription, servers) => latencyWindowReducer(topologyDescription, servers.filter((s) => s.isWritable)); +} +exports.writableServerSelector = writableServerSelector; +/** + * The purpose of this selector is to select the same server, only + * if it is in a state that it can have commands sent to it. + */ +function sameServerSelector(description) { + return (topologyDescription, servers) => { + if (!description) + return []; + // Filter the servers to match the provided description only if + // the type is not unknown. + return servers.filter(sd => { + return sd.address === description.address && sd.type !== common_1.ServerType.Unknown; + }); + }; +} +exports.sameServerSelector = sameServerSelector; +/** + * Returns a server selector that uses a read preference to select a + * server potentially for a write on a secondary. + */ +function secondaryWritableServerSelector(wireVersion, readPreference) { + // If server version < 5.0, read preference always primary. + // If server version >= 5.0... + // - If read preference is supplied, use that. + // - If no read preference is supplied, use primary. + if (!readPreference || + !wireVersion || + (wireVersion && wireVersion < exports.MIN_SECONDARY_WRITE_WIRE_VERSION)) { + return readPreferenceServerSelector(read_preference_1.ReadPreference.primary); + } + return readPreferenceServerSelector(readPreference); +} +exports.secondaryWritableServerSelector = secondaryWritableServerSelector; +/** + * Reduces the passed in array of servers by the rules of the "Max Staleness" specification + * found here: https://github.com/mongodb/specifications/blob/master/source/max-staleness/max-staleness.rst + * + * @param readPreference - The read preference providing max staleness guidance + * @param topologyDescription - The topology description + * @param servers - The list of server descriptions to be reduced + * @returns The list of servers that satisfy the requirements of max staleness + */ +function maxStalenessReducer(readPreference, topologyDescription, servers) { + if (readPreference.maxStalenessSeconds == null || readPreference.maxStalenessSeconds < 0) { + return servers; + } + const maxStaleness = readPreference.maxStalenessSeconds; + const maxStalenessVariance = (topologyDescription.heartbeatFrequencyMS + IDLE_WRITE_PERIOD) / 1000; + if (maxStaleness < maxStalenessVariance) { + throw new error_1.MongoInvalidArgumentError(`Option "maxStalenessSeconds" must be at least ${maxStalenessVariance} seconds`); + } + if (maxStaleness < SMALLEST_MAX_STALENESS_SECONDS) { + throw new error_1.MongoInvalidArgumentError(`Option "maxStalenessSeconds" must be at least ${SMALLEST_MAX_STALENESS_SECONDS} seconds`); + } + if (topologyDescription.type === common_1.TopologyType.ReplicaSetWithPrimary) { + const primary = Array.from(topologyDescription.servers.values()).filter(primaryFilter)[0]; + return servers.reduce((result, server) => { + var _a; + const stalenessMS = server.lastUpdateTime - + server.lastWriteDate - + (primary.lastUpdateTime - primary.lastWriteDate) + + topologyDescription.heartbeatFrequencyMS; + const staleness = stalenessMS / 1000; + const maxStalenessSeconds = (_a = readPreference.maxStalenessSeconds) !== null && _a !== void 0 ? _a : 0; + if (staleness <= maxStalenessSeconds) { + result.push(server); + } + return result; + }, []); + } + if (topologyDescription.type === common_1.TopologyType.ReplicaSetNoPrimary) { + if (servers.length === 0) { + return servers; + } + const sMax = servers.reduce((max, s) => s.lastWriteDate > max.lastWriteDate ? s : max); + return servers.reduce((result, server) => { + var _a; + const stalenessMS = sMax.lastWriteDate - server.lastWriteDate + topologyDescription.heartbeatFrequencyMS; + const staleness = stalenessMS / 1000; + const maxStalenessSeconds = (_a = readPreference.maxStalenessSeconds) !== null && _a !== void 0 ? _a : 0; + if (staleness <= maxStalenessSeconds) { + result.push(server); + } + return result; + }, []); + } + return servers; +} +/** + * Determines whether a server's tags match a given set of tags + * + * @param tagSet - The requested tag set to match + * @param serverTags - The server's tags + */ +function tagSetMatch(tagSet, serverTags) { + const keys = Object.keys(tagSet); + const serverTagKeys = Object.keys(serverTags); + for (let i = 0; i < keys.length; ++i) { + const key = keys[i]; + if (serverTagKeys.indexOf(key) === -1 || serverTags[key] !== tagSet[key]) { + return false; + } + } + return true; +} +/** + * Reduces a set of server descriptions based on tags requested by the read preference + * + * @param readPreference - The read preference providing the requested tags + * @param servers - The list of server descriptions to reduce + * @returns The list of servers matching the requested tags + */ +function tagSetReducer(readPreference, servers) { + if (readPreference.tags == null || + (Array.isArray(readPreference.tags) && readPreference.tags.length === 0)) { + return servers; + } + for (let i = 0; i < readPreference.tags.length; ++i) { + const tagSet = readPreference.tags[i]; + const serversMatchingTagset = servers.reduce((matched, server) => { + if (tagSetMatch(tagSet, server.tags)) + matched.push(server); + return matched; + }, []); + if (serversMatchingTagset.length) { + return serversMatchingTagset; + } + } + return []; +} +/** + * Reduces a list of servers to ensure they fall within an acceptable latency window. This is + * further specified in the "Server Selection" specification, found here: + * https://github.com/mongodb/specifications/blob/master/source/server-selection/server-selection.rst + * + * @param topologyDescription - The topology description + * @param servers - The list of servers to reduce + * @returns The servers which fall within an acceptable latency window + */ +function latencyWindowReducer(topologyDescription, servers) { + const low = servers.reduce((min, server) => min === -1 ? server.roundTripTime : Math.min(server.roundTripTime, min), -1); + const high = low + topologyDescription.localThresholdMS; + return servers.reduce((result, server) => { + if (server.roundTripTime <= high && server.roundTripTime >= low) + result.push(server); + return result; + }, []); +} +// filters +function primaryFilter(server) { + return server.type === common_1.ServerType.RSPrimary; +} +function secondaryFilter(server) { + return server.type === common_1.ServerType.RSSecondary; +} +function nearestFilter(server) { + return server.type === common_1.ServerType.RSSecondary || server.type === common_1.ServerType.RSPrimary; +} +function knownFilter(server) { + return server.type !== common_1.ServerType.Unknown; +} +function loadBalancerFilter(server) { + return server.type === common_1.ServerType.LoadBalancer; +} +/** + * Returns a function which selects servers based on a provided read preference + * + * @param readPreference - The read preference to select with + */ +function readPreferenceServerSelector(readPreference) { + if (!readPreference.isValid()) { + throw new error_1.MongoInvalidArgumentError('Invalid read preference specified'); + } + return (topologyDescription, servers) => { + const commonWireVersion = topologyDescription.commonWireVersion; + if (commonWireVersion && + readPreference.minWireVersion && + readPreference.minWireVersion > commonWireVersion) { + throw new error_1.MongoCompatibilityError(`Minimum wire version '${readPreference.minWireVersion}' required, but found '${commonWireVersion}'`); + } + if (topologyDescription.type === common_1.TopologyType.LoadBalanced) { + return servers.filter(loadBalancerFilter); + } + if (topologyDescription.type === common_1.TopologyType.Unknown) { + return []; + } + if (topologyDescription.type === common_1.TopologyType.Single || + topologyDescription.type === common_1.TopologyType.Sharded) { + return latencyWindowReducer(topologyDescription, servers.filter(knownFilter)); + } + const mode = readPreference.mode; + if (mode === read_preference_1.ReadPreference.PRIMARY) { + return servers.filter(primaryFilter); + } + if (mode === read_preference_1.ReadPreference.PRIMARY_PREFERRED) { + const result = servers.filter(primaryFilter); + if (result.length) { + return result; + } + } + const filter = mode === read_preference_1.ReadPreference.NEAREST ? nearestFilter : secondaryFilter; + const selectedServers = latencyWindowReducer(topologyDescription, tagSetReducer(readPreference, maxStalenessReducer(readPreference, topologyDescription, servers.filter(filter)))); + if (mode === read_preference_1.ReadPreference.SECONDARY_PREFERRED && selectedServers.length === 0) { + return servers.filter(primaryFilter); + } + return selectedServers; + }; +} +exports.readPreferenceServerSelector = readPreferenceServerSelector; +//# sourceMappingURL=server_selection.js.map \ No newline at end of file diff --git a/ts-ticket-office-service/node_modules/mongodb/lib/sdam/server_selection.js.map b/ts-ticket-office-service/node_modules/mongodb/lib/sdam/server_selection.js.map new file mode 100644 index 000000000..f8a94927b --- /dev/null +++ b/ts-ticket-office-service/node_modules/mongodb/lib/sdam/server_selection.js.map @@ -0,0 +1 @@ +{"version":3,"file":"server_selection.js","sourceRoot":"","sources":["../../src/sdam/server_selection.ts"],"names":[],"mappings":";;;AAAA,oCAA8E;AAC9E,wDAAoD;AACpD,qCAAoD;AAIpD,0BAA0B;AAC1B,MAAM,iBAAiB,GAAG,KAAK,CAAC;AAChC,MAAM,8BAA8B,GAAG,EAAE,CAAC;AAE1C,iDAAiD;AACpC,QAAA,gCAAgC,GAAG,EAAE,CAAC;AAQnD;;GAEG;AACH,SAAgB,sBAAsB;IACpC,OAAO,CACL,mBAAwC,EACxC,OAA4B,EACP,EAAE,CACvB,oBAAoB,CAClB,mBAAmB,EACnB,OAAO,CAAC,MAAM,CAAC,CAAC,CAAoB,E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IAAI,KAAK,qBAAY,CAAC,OAAO,EAAE;YACrD,OAAO,EAAE,CAAC;SACX;QAED,IACE,mBAAmB,CAAC,IAAI,KAAK,qBAAY,CAAC,MAAM;YAChD,mBAAmB,CAAC,IAAI,KAAK,qBAAY,CAAC,OAAO,EACjD;YACA,OAAO,oBAAoB,CAAC,mBAAmB,EAAE,OAAO,CAAC,MAAM,CAAC,WAAW,CAAC,CAAC,CAAC;SAC/E;QAED,MAAM,IAAI,GAAG,cAAc,CAAC,IAAI,CAAC;QACjC,IAAI,IAAI,KAAK,gCAAc,CAAC,OAAO,EAAE;YACnC,OAAO,OAAO,CAAC,MAAM,CAAC,aAAa,CAAC,CAAC;SACtC;QAED,IAAI,IAAI,KAAK,gCAAc,CAAC,iBAAiB,EAAE;YAC7C,MAAM,MAAM,GAAG,OAAO,CAAC,MAAM,CAAC,aAAa,CAAC,CAAC;YAC7C,IAAI,MAAM,CAAC,MAAM,EAAE;gBACjB,OAAO,MAAM,CAAC;aACf;SACF;QAED,MAAM,MAAM,GAAG,IAAI,KAAK,gCAAc,CAAC,OAAO,CAAC,CAAC,CAAC,aAAa,CAAC,CAAC,CAAC,eAAe,CAAC;QACjF,MAAM,eAAe,GAAG,oBAAoB,CAC1C,mBAAmB,EACnB,aAAa,CACX,cAAc,EACd,mBAAmB,CAAC,cAAc,EAAE,mBAAmB,EAAE,OAAO,CAAC,MAAM,CAAC,MAAM,CAAC,CAAC,CACjF,CACF,CAAC;QAEF,IAAI,IAAI,KAAK,gCAAc,CAAC,mBAAmB,IAAI,eAAe,CAAC,MAAM,KAAK,CAAC,EAAE;YAC/E,OAAO,OAAO,CAAC,MAAM,CAAC,aAAa,CAAC,CAAC;SACtC;QAED,OAAO,eAAe,CAAC;IACzB,CAAC,CAAC;AACJ,CAAC;AA9DD,oEA8DC"} \ No newline at end of file diff --git a/ts-ticket-office-service/node_modules/mongodb/lib/sdam/srv_polling.js b/ts-ticket-office-service/node_modules/mongodb/lib/sdam/srv_polling.js new file mode 100644 index 000000000..e8ced70f5 --- /dev/null +++ b/ts-ticket-office-service/node_modules/mongodb/lib/sdam/srv_polling.js @@ -0,0 +1,122 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.SrvPoller = exports.SrvPollingEvent = void 0; +const dns = require("dns"); +const timers_1 = require("timers"); +const error_1 = require("../error"); +const logger_1 = require("../logger"); +const mongo_types_1 = require("../mongo_types"); +const utils_1 = require("../utils"); +/** + * Determines whether a provided address matches the provided parent domain in order + * to avoid certain attack vectors. + * + * @param srvAddress - The address to check against a domain + * @param parentDomain - The domain to check the provided address against + * @returns Whether the provided address matches the parent domain + */ +function matchesParentDomain(srvAddress, parentDomain) { + const regex = /^.*?\./; + const srv = `.${srvAddress.replace(regex, '')}`; + const parent = `.${parentDomain.replace(regex, '')}`; + return srv.endsWith(parent); +} +/** + * @internal + * @category Event + */ +class SrvPollingEvent { + constructor(srvRecords) { + this.srvRecords = srvRecords; + } + hostnames() { + return new Set(this.srvRecords.map(r => utils_1.HostAddress.fromSrvRecord(r).toString())); + } +} +exports.SrvPollingEvent = SrvPollingEvent; +/** @internal */ +class SrvPoller extends mongo_types_1.TypedEventEmitter { + constructor(options) { + var _a, _b, _c; + super(); + if (!options || !options.srvHost) { + throw new error_1.MongoRuntimeError('Options for SrvPoller must exist and include srvHost'); + } + this.srvHost = options.srvHost; + this.srvMaxHosts = (_a = options.srvMaxHosts) !== null && _a !== void 0 ? _a : 0; + this.srvServiceName = (_b = options.srvServiceName) !== null && _b !== void 0 ? _b : 'mongodb'; + this.rescanSrvIntervalMS = 60000; + this.heartbeatFrequencyMS = (_c = options.heartbeatFrequencyMS) !== null && _c !== void 0 ? _c : 10000; + this.logger = new logger_1.Logger('srvPoller', options); + this.haMode = false; + this.generation = 0; + this._timeout = undefined; + } + get srvAddress() { + return `_${this.srvServiceName}._tcp.${this.srvHost}`; + } + get intervalMS() { + return this.haMode ? this.heartbeatFrequencyMS : this.rescanSrvIntervalMS; + } + start() { + if (!this._timeout) { + this.schedule(); + } + } + stop() { + if (this._timeout) { + clearTimeout(this._timeout); + this.generation += 1; + this._timeout = undefined; + } + } + schedule() { + if (this._timeout) { + clearTimeout(this._timeout); + } + this._timeout = (0, timers_1.setTimeout)(() => this._poll(), this.intervalMS); + } + success(srvRecords) { + this.haMode = false; + this.schedule(); + this.emit(SrvPoller.SRV_RECORD_DISCOVERY, new SrvPollingEvent(srvRecords)); + } + failure(message, obj) { + this.logger.warn(message, obj); + this.haMode = true; + this.schedule(); + } + parentDomainMismatch(srvRecord) { + this.logger.warn(`parent domain mismatch on SRV record (${srvRecord.name}:${srvRecord.port})`, srvRecord); + } + _poll() { + const generation = this.generation; + dns.resolveSrv(this.srvAddress, (err, srvRecords) => { + if (generation !== this.generation) { + return; + } + if (err) { + this.failure('DNS error', err); + return; + } + const finalAddresses = []; + for (const record of srvRecords) { + if (matchesParentDomain(record.name, this.srvHost)) { + finalAddresses.push(record); + } + else { + this.parentDomainMismatch(record); + } + } + if (!finalAddresses.length) { + this.failure('No valid addresses found at host'); + return; + } + this.success(finalAddresses); + }); + } +} +exports.SrvPoller = SrvPoller; +/** @event */ +SrvPoller.SRV_RECORD_DISCOVERY = 'srvRecordDiscovery'; +//# sourceMappingURL=srv_polling.js.map \ No newline at end of file diff --git a/ts-ticket-office-service/node_modules/mongodb/lib/sdam/srv_polling.js.map b/ts-ticket-office-service/node_modules/mongodb/lib/sdam/srv_polling.js.map new file mode 100644 index 000000000..18e86f585 --- /dev/null +++ b/ts-ticket-office-service/node_modules/mongodb/lib/sdam/srv_polling.js.map @@ -0,0 +1 @@ +{"version":3,"file":"srv_polling.js","sourceRoot":"","sources":["../../src/sdam/srv_polling.ts"],"names":[],"mappings":";;;AAAA,2BAA2B;AAC3B,mCAAoC;AAEpC,oCAA6C;AAC7C,sCAAkD;AAClD,gDAAmD;AACnD,oCAAuC;AAEvC;;;;;;;GAOG;AACH,SAAS,mBAAmB,CAAC,UAAkB,EAAE,YAAoB;IACnE,MAAM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AC/B,IAAI,CAAC,MAAM,GAAG,IAAI,CAAC;QACnB,IAAI,CAAC,QAAQ,EAAE,CAAC;IAClB,CAAC;IAED,oBAAoB,CAAC,SAAwB;QAC3C,IAAI,CAAC,MAAM,CAAC,IAAI,CACd,yCAAyC,SAAS,CAAC,IAAI,IAAI,SAAS,CAAC,IAAI,GAAG,EAC5E,SAAS,CACV,CAAC;IACJ,CAAC;IAED,KAAK;QACH,MAAM,UAAU,GAAG,IAAI,CAAC,UAAU,CAAC;QACnC,GAAG,CAAC,UAAU,CAAC,IAAI,CAAC,UAAU,EAAE,CAAC,GAAG,EAAE,UAAU,EAAE,EAAE;YAClD,IAAI,UAAU,KAAK,IAAI,CAAC,UAAU,EAAE;gBAClC,OAAO;aACR;YAED,IAAI,GAAG,EAAE;gBACP,IAAI,CAAC,OAAO,CAAC,WAAW,EAAE,GAAG,CAAC,CAAC;gBAC/B,OAAO;aACR;YAED,MAAM,cAAc,GAAoB,EAAE,CAAC;YAC3C,KAAK,MAAM,MAAM,IAAI,UAAU,EAAE;gBAC/B,IAAI,mBAAmB,CAAC,MAAM,CAAC,IAAI,EAAE,IAAI,CAAC,OAAO,CAAC,EAAE;oBAClD,cAAc,CAAC,IAAI,CAAC,MAAM,CAAC,CAAC;iBAC7B;qBAAM;oBACL,IAAI,CAAC,oBAAoB,CAAC,MAAM,CAAC,CAAC;iBACnC;aACF;YAED,IAAI,CAAC,cAAc,CAAC,MAAM,EAAE;gBAC1B,IAAI,CAAC,OAAO,CAAC,kCAAkC,CAAC,CAAC;gBACjD,OAAO;aACR;YAED,IAAI,CAAC,OAAO,CAAC,cAAc,CAAC,CAAC;QAC/B,CAAC,CAAC,CAAC;IACL,CAAC;;AA/GH,8BAgHC;AArGC,aAAa;AACG,8BAAoB,GAAG,oBAA6B,CAAC"} \ No newline at end of file diff --git a/ts-ticket-office-service/node_modules/mongodb/lib/sdam/topology.js b/ts-ticket-office-service/node_modules/mongodb/lib/sdam/topology.js new file mode 100644 index 000000000..8a2a0271b --- /dev/null +++ b/ts-ticket-office-service/node_modules/mongodb/lib/sdam/topology.js @@ -0,0 +1,645 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.ServerCapabilities = exports.Topology = void 0; +const Denque = require("denque"); +const timers_1 = require("timers"); +const util_1 = require("util"); +const bson_1 = require("../bson"); +const connection_string_1 = require("../connection_string"); +const constants_1 = require("../constants"); +const error_1 = require("../error"); +const mongo_types_1 = require("../mongo_types"); +const read_preference_1 = require("../read_preference"); +const utils_1 = require("../utils"); +const common_1 = require("./common"); +const events_1 = require("./events"); +const server_1 = require("./server"); +const server_description_1 = require("./server_description"); +const server_selection_1 = require("./server_selection"); +const srv_polling_1 = require("./srv_polling"); +const topology_description_1 = require("./topology_description"); +// Global state +let globalTopologyCounter = 0; +const stateTransition = (0, utils_1.makeStateMachine)({ + [common_1.STATE_CLOSED]: [common_1.STATE_CLOSED, common_1.STATE_CONNECTING], + [common_1.STATE_CONNECTING]: [common_1.STATE_CONNECTING, common_1.STATE_CLOSING, common_1.STATE_CONNECTED, common_1.STATE_CLOSED], + [common_1.STATE_CONNECTED]: [common_1.STATE_CONNECTED, common_1.STATE_CLOSING, common_1.STATE_CLOSED], + [common_1.STATE_CLOSING]: [common_1.STATE_CLOSING, common_1.STATE_CLOSED] +}); +/** @internal */ +const kCancelled = Symbol('cancelled'); +/** @internal */ +const kWaitQueue = Symbol('waitQueue'); +/** + * A container of server instances representing a connection to a MongoDB topology. + * @internal + */ +class Topology extends mongo_types_1.TypedEventEmitter { + /** + * @param seedlist - a list of HostAddress instances to connect to + */ + constructor(seeds, options) { + var _a; + super(); + // Legacy CSFLE support + this.bson = Object.create(null); + this.bson.serialize = bson_1.serialize; + this.bson.deserialize = bson_1.deserialize; + // Options should only be undefined in tests, MongoClient will always have defined options + options = options !== null && options !== void 0 ? options : { + hosts: [utils_1.HostAddress.fromString('localhost:27017')], + ...Object.fromEntries(connection_string_1.DEFAULT_OPTIONS.entries()), + ...Object.fromEntries(connection_string_1.FEATURE_FLAGS.entries()) + }; + if (typeof seeds === 'string') { + seeds = [utils_1.HostAddress.fromString(seeds)]; + } + else if (!Array.isArray(seeds)) { + seeds = [seeds]; + } + const seedlist = []; + for (const seed of seeds) { + if (typeof seed === 'string') { + seedlist.push(utils_1.HostAddress.fromString(seed)); + } + else if (seed instanceof utils_1.HostAddress) { + seedlist.push(seed); + } + else { + // FIXME(NODE-3483): May need to be a MongoParseError + throw new error_1.MongoRuntimeError(`Topology cannot be constructed from ${JSON.stringify(seed)}`); + } + } + const topologyType = topologyTypeFromOptions(options); + const topologyId = globalTopologyCounter++; + const selectedHosts = options.srvMaxHosts == null || + options.srvMaxHosts === 0 || + options.srvMaxHosts >= seedlist.length + ? seedlist + : (0, utils_1.shuffle)(seedlist, options.srvMaxHosts); + const serverDescriptions = new Map(); + for (const hostAddress of selectedHosts) { + serverDescriptions.set(hostAddress.toString(), new server_description_1.ServerDescription(hostAddress)); + } + this[kWaitQueue] = new Denque(); + this.s = { + // the id of this topology + id: topologyId, + // passed in options + options, + // initial seedlist of servers to connect to + seedlist, + // initial state + state: common_1.STATE_CLOSED, + // the topology description + description: new topology_description_1.TopologyDescription(topologyType, serverDescriptions, options.replicaSet, undefined, undefined, undefined, options), + serverSelectionTimeoutMS: options.serverSelectionTimeoutMS, + heartbeatFrequencyMS: options.heartbeatFrequencyMS, + minHeartbeatFrequencyMS: options.minHeartbeatFrequencyMS, + // a map of server instances to normalized addresses + servers: new Map(), + credentials: options === null || options === void 0 ? void 0 : options.credentials, + clusterTime: undefined, + // timer management + connectionTimers: new Set(), + detectShardedTopology: ev => this.detectShardedTopology(ev), + detectSrvRecords: ev => this.detectSrvRecords(ev) + }; + if (options.srvHost && !options.loadBalanced) { + this.s.srvPoller = + (_a = options.srvPoller) !== null && _a !== void 0 ? _a : new srv_polling_1.SrvPoller({ + heartbeatFrequencyMS: this.s.heartbeatFrequencyMS, + srvHost: options.srvHost, + srvMaxHosts: options.srvMaxHosts, + srvServiceName: options.srvServiceName + }); + this.on(Topology.TOPOLOGY_DESCRIPTION_CHANGED, this.s.detectShardedTopology); + } + } + detectShardedTopology(event) { + var _a, _b, _c; + const previousType = event.previousDescription.type; + const newType = event.newDescription.type; + const transitionToSharded = previousType !== common_1.TopologyType.Sharded && newType === common_1.TopologyType.Sharded; + const srvListeners = (_a = this.s.srvPoller) === null || _a === void 0 ? void 0 : _a.listeners(srv_polling_1.SrvPoller.SRV_RECORD_DISCOVERY); + const listeningToSrvPolling = !!(srvListeners === null || srvListeners === void 0 ? void 0 : srvListeners.includes(this.s.detectSrvRecords)); + if (transitionToSharded && !listeningToSrvPolling) { + (_b = this.s.srvPoller) === null || _b === void 0 ? void 0 : _b.on(srv_polling_1.SrvPoller.SRV_RECORD_DISCOVERY, this.s.detectSrvRecords); + (_c = this.s.srvPoller) === null || _c === void 0 ? void 0 : _c.start(); + } + } + detectSrvRecords(ev) { + const previousTopologyDescription = this.s.description; + this.s.description = this.s.description.updateFromSrvPollingEvent(ev, this.s.options.srvMaxHosts); + if (this.s.description === previousTopologyDescription) { + // Nothing changed, so return + return; + } + updateServers(this); + this.emit(Topology.TOPOLOGY_DESCRIPTION_CHANGED, new events_1.TopologyDescriptionChangedEvent(this.s.id, previousTopologyDescription, this.s.description)); + } + /** + * @returns A `TopologyDescription` for this topology + */ + get description() { + return this.s.description; + } + get loadBalanced() { + return this.s.options.loadBalanced; + } + get capabilities() { + return new ServerCapabilities(this.lastHello()); + } + /** Initiate server connect */ + connect(options, callback) { + var _a; + if (typeof options === 'function') + (callback = options), (options = {}); + options = options !== null && options !== void 0 ? options : {}; + if (this.s.state === common_1.STATE_CONNECTED) { + if (typeof callback === 'function') { + callback(); + } + return; + } + stateTransition(this, common_1.STATE_CONNECTING); + // emit SDAM monitoring events + this.emit(Topology.TOPOLOGY_OPENING, new events_1.TopologyOpeningEvent(this.s.id)); + // emit an event for the topology change + this.emit(Topology.TOPOLOGY_DESCRIPTION_CHANGED, new events_1.TopologyDescriptionChangedEvent(this.s.id, new topology_description_1.TopologyDescription(common_1.TopologyType.Unknown), // initial is always Unknown + this.s.description)); + // connect all known servers, then attempt server selection to connect + const serverDescriptions = Array.from(this.s.description.servers.values()); + this.s.servers = new Map(serverDescriptions.map(serverDescription => [ + serverDescription.address, + createAndConnectServer(this, serverDescription) + ])); + // In load balancer mode we need to fake a server description getting + // emitted from the monitor, since the monitor doesn't exist. + if (this.s.options.loadBalanced) { + for (const description of serverDescriptions) { + const newDescription = new server_description_1.ServerDescription(description.hostAddress, undefined, { + loadBalanced: this.s.options.loadBalanced + }); + this.serverUpdateHandler(newDescription); + } + } + const exitWithError = (error) => callback ? callback(error) : this.emit(Topology.ERROR, error); + const readPreference = (_a = options.readPreference) !== null && _a !== void 0 ? _a : read_preference_1.ReadPreference.primary; + this.selectServer((0, server_selection_1.readPreferenceServerSelector)(readPreference), options, (err, server) => { + if (err) { + return this.close({ force: false }, () => exitWithError(err)); + } + // TODO: NODE-2471 + const skipPingOnConnect = this.s.options[Symbol.for('@@mdb.skipPingOnConnect')] === true; + if (!skipPingOnConnect && server && this.s.credentials) { + server.command((0, utils_1.ns)('admin.$cmd'), { ping: 1 }, {}, err => { + if (err) { + return exitWithError(err); + } + stateTransition(this, common_1.STATE_CONNECTED); + this.emit(Topology.OPEN, this); + this.emit(Topology.CONNECT, this); + callback === null || callback === void 0 ? void 0 : callback(undefined, this); + }); + return; + } + stateTransition(this, common_1.STATE_CONNECTED); + this.emit(Topology.OPEN, this); + this.emit(Topology.CONNECT, this); + callback === null || callback === void 0 ? void 0 : callback(undefined, this); + }); + } + /** Close this topology */ + close(options, callback) { + if (typeof options === 'function') { + callback = options; + options = {}; + } + if (typeof options === 'boolean') { + options = { force: options }; + } + options = options !== null && options !== void 0 ? options : {}; + if (this.s.state === common_1.STATE_CLOSED || this.s.state === common_1.STATE_CLOSING) { + return callback === null || callback === void 0 ? void 0 : callback(); + } + const destroyedServers = Array.from(this.s.servers.values(), server => { + return (0, util_1.promisify)(destroyServer)(server, this, options); + }); + Promise.all(destroyedServers) + .then(() => { + this.s.servers.clear(); + stateTransition(this, common_1.STATE_CLOSING); + drainWaitQueue(this[kWaitQueue], new error_1.MongoTopologyClosedError()); + (0, common_1.drainTimerQueue)(this.s.connectionTimers); + if (this.s.srvPoller) { + this.s.srvPoller.stop(); + this.s.srvPoller.removeListener(srv_polling_1.SrvPoller.SRV_RECORD_DISCOVERY, this.s.detectSrvRecords); + } + this.removeListener(Topology.TOPOLOGY_DESCRIPTION_CHANGED, this.s.detectShardedTopology); + stateTransition(this, common_1.STATE_CLOSED); + // emit an event for close + this.emit(Topology.TOPOLOGY_CLOSED, new events_1.TopologyClosedEvent(this.s.id)); + }) + .finally(() => callback === null || callback === void 0 ? void 0 : callback()); + } + /** + * Selects a server according to the selection predicate provided + * + * @param selector - An optional selector to select servers by, defaults to a random selection within a latency window + * @param options - Optional settings related to server selection + * @param callback - The callback used to indicate success or failure + * @returns An instance of a `Server` meeting the criteria of the predicate provided + */ + selectServer(selector, options, callback) { + let serverSelector; + if (typeof selector !== 'function') { + if (typeof selector === 'string') { + serverSelector = (0, server_selection_1.readPreferenceServerSelector)(read_preference_1.ReadPreference.fromString(selector)); + } + else { + let readPreference; + if (selector instanceof read_preference_1.ReadPreference) { + readPreference = selector; + } + else { + read_preference_1.ReadPreference.translate(options); + readPreference = options.readPreference || read_preference_1.ReadPreference.primary; + } + serverSelector = (0, server_selection_1.readPreferenceServerSelector)(readPreference); + } + } + else { + serverSelector = selector; + } + options = Object.assign({}, { serverSelectionTimeoutMS: this.s.serverSelectionTimeoutMS }, options); + const isSharded = this.description.type === common_1.TopologyType.Sharded; + const session = options.session; + const transaction = session && session.transaction; + if (isSharded && transaction && transaction.server) { + callback(undefined, transaction.server); + return; + } + const waitQueueMember = { + serverSelector, + transaction, + callback + }; + const serverSelectionTimeoutMS = options.serverSelectionTimeoutMS; + if (serverSelectionTimeoutMS) { + waitQueueMember.timer = (0, timers_1.setTimeout)(() => { + waitQueueMember[kCancelled] = true; + waitQueueMember.timer = undefined; + const timeoutError = new error_1.MongoServerSelectionError(`Server selection timed out after ${serverSelectionTimeoutMS} ms`, this.description); + waitQueueMember.callback(timeoutError); + }, serverSelectionTimeoutMS); + } + this[kWaitQueue].push(waitQueueMember); + processWaitQueue(this); + } + // Sessions related methods + /** + * @returns Whether the topology should initiate selection to determine session support + */ + shouldCheckForSessionSupport() { + if (this.description.type === common_1.TopologyType.Single) { + return !this.description.hasKnownServers; + } + return !this.description.hasDataBearingServers; + } + /** + * @returns Whether sessions are supported on the current topology + */ + hasSessionSupport() { + return this.loadBalanced || this.description.logicalSessionTimeoutMinutes != null; + } + /** + * Update the internal TopologyDescription with a ServerDescription + * + * @param serverDescription - The server to update in the internal list of server descriptions + */ + serverUpdateHandler(serverDescription) { + if (!this.s.description.hasServer(serverDescription.address)) { + return; + } + // ignore this server update if its from an outdated topologyVersion + if (isStaleServerDescription(this.s.description, serverDescription)) { + return; + } + // these will be used for monitoring events later + const previousTopologyDescription = this.s.description; + const previousServerDescription = this.s.description.servers.get(serverDescription.address); + if (!previousServerDescription) { + return; + } + // Driver Sessions Spec: "Whenever a driver receives a cluster time from + // a server it MUST compare it to the current highest seen cluster time + // for the deployment. If the new cluster time is higher than the + // highest seen cluster time it MUST become the new highest seen cluster + // time. Two cluster times are compared using only the BsonTimestamp + // value of the clusterTime embedded field." + const clusterTime = serverDescription.$clusterTime; + if (clusterTime) { + (0, common_1._advanceClusterTime)(this, clusterTime); + } + // If we already know all the information contained in this updated description, then + // we don't need to emit SDAM events, but still need to update the description, in order + // to keep client-tracked attributes like last update time and round trip time up to date + const equalDescriptions = previousServerDescription && previousServerDescription.equals(serverDescription); + // first update the TopologyDescription + this.s.description = this.s.description.update(serverDescription); + if (this.s.description.compatibilityError) { + this.emit(Topology.ERROR, new error_1.MongoCompatibilityError(this.s.description.compatibilityError)); + return; + } + // emit monitoring events for this change + if (!equalDescriptions) { + const newDescription = this.s.description.servers.get(serverDescription.address); + if (newDescription) { + this.emit(Topology.SERVER_DESCRIPTION_CHANGED, new events_1.ServerDescriptionChangedEvent(this.s.id, serverDescription.address, previousServerDescription, newDescription)); + } + } + // update server list from updated descriptions + updateServers(this, serverDescription); + // attempt to resolve any outstanding server selection attempts + if (this[kWaitQueue].length > 0) { + processWaitQueue(this); + } + if (!equalDescriptions) { + this.emit(Topology.TOPOLOGY_DESCRIPTION_CHANGED, new events_1.TopologyDescriptionChangedEvent(this.s.id, previousTopologyDescription, this.s.description)); + } + } + auth(credentials, callback) { + if (typeof credentials === 'function') + (callback = credentials), (credentials = undefined); + if (typeof callback === 'function') + callback(undefined, true); + } + get clientMetadata() { + return this.s.options.metadata; + } + isConnected() { + return this.s.state === common_1.STATE_CONNECTED; + } + isDestroyed() { + return this.s.state === common_1.STATE_CLOSED; + } + /** + * @deprecated This function is deprecated and will be removed in the next major version. + */ + unref() { + (0, utils_1.emitWarning)('`unref` is a noop and will be removed in the next major version'); + } + // NOTE: There are many places in code where we explicitly check the last hello + // to do feature support detection. This should be done any other way, but for + // now we will just return the first hello seen, which should suffice. + lastHello() { + const serverDescriptions = Array.from(this.description.servers.values()); + if (serverDescriptions.length === 0) + return {}; + const sd = serverDescriptions.filter((sd) => sd.type !== common_1.ServerType.Unknown)[0]; + const result = sd || { maxWireVersion: this.description.commonWireVersion }; + return result; + } + get commonWireVersion() { + return this.description.commonWireVersion; + } + get logicalSessionTimeoutMinutes() { + return this.description.logicalSessionTimeoutMinutes; + } + get clusterTime() { + return this.s.clusterTime; + } + set clusterTime(clusterTime) { + this.s.clusterTime = clusterTime; + } +} +exports.Topology = Topology; +/** @event */ +Topology.SERVER_OPENING = constants_1.SERVER_OPENING; +/** @event */ +Topology.SERVER_CLOSED = constants_1.SERVER_CLOSED; +/** @event */ +Topology.SERVER_DESCRIPTION_CHANGED = constants_1.SERVER_DESCRIPTION_CHANGED; +/** @event */ +Topology.TOPOLOGY_OPENING = constants_1.TOPOLOGY_OPENING; +/** @event */ +Topology.TOPOLOGY_CLOSED = constants_1.TOPOLOGY_CLOSED; +/** @event */ +Topology.TOPOLOGY_DESCRIPTION_CHANGED = constants_1.TOPOLOGY_DESCRIPTION_CHANGED; +/** @event */ +Topology.ERROR = constants_1.ERROR; +/** @event */ +Topology.OPEN = constants_1.OPEN; +/** @event */ +Topology.CONNECT = constants_1.CONNECT; +/** @event */ +Topology.CLOSE = constants_1.CLOSE; +/** @event */ +Topology.TIMEOUT = constants_1.TIMEOUT; +/** Destroys a server, and removes all event listeners from the instance */ +function destroyServer(server, topology, options, callback) { + options = options !== null && options !== void 0 ? options : {}; + for (const event of constants_1.LOCAL_SERVER_EVENTS) { + server.removeAllListeners(event); + } + server.destroy(options, () => { + topology.emit(Topology.SERVER_CLOSED, new events_1.ServerClosedEvent(topology.s.id, server.description.address)); + for (const event of constants_1.SERVER_RELAY_EVENTS) { + server.removeAllListeners(event); + } + if (typeof callback === 'function') { + callback(); + } + }); +} +/** Predicts the TopologyType from options */ +function topologyTypeFromOptions(options) { + if (options === null || options === void 0 ? void 0 : options.directConnection) { + return common_1.TopologyType.Single; + } + if (options === null || options === void 0 ? void 0 : options.replicaSet) { + return common_1.TopologyType.ReplicaSetNoPrimary; + } + if (options === null || options === void 0 ? void 0 : options.loadBalanced) { + return common_1.TopologyType.LoadBalanced; + } + return common_1.TopologyType.Unknown; +} +/** + * Creates new server instances and attempts to connect them + * + * @param topology - The topology that this server belongs to + * @param serverDescription - The description for the server to initialize and connect to + */ +function createAndConnectServer(topology, serverDescription) { + topology.emit(Topology.SERVER_OPENING, new events_1.ServerOpeningEvent(topology.s.id, serverDescription.address)); + const server = new server_1.Server(topology, serverDescription, topology.s.options); + for (const event of constants_1.SERVER_RELAY_EVENTS) { + server.on(event, (e) => topology.emit(event, e)); + } + server.on(server_1.Server.DESCRIPTION_RECEIVED, description => topology.serverUpdateHandler(description)); + server.connect(); + return server; +} +/** + * @param topology - Topology to update. + * @param incomingServerDescription - New server description. + */ +function updateServers(topology, incomingServerDescription) { + // update the internal server's description + if (incomingServerDescription && topology.s.servers.has(incomingServerDescription.address)) { + const server = topology.s.servers.get(incomingServerDescription.address); + if (server) { + server.s.description = incomingServerDescription; + } + } + // add new servers for all descriptions we currently don't know about locally + for (const serverDescription of topology.description.servers.values()) { + if (!topology.s.servers.has(serverDescription.address)) { + const server = createAndConnectServer(topology, serverDescription); + topology.s.servers.set(serverDescription.address, server); + } + } + // for all servers no longer known, remove their descriptions and destroy their instances + for (const entry of topology.s.servers) { + const serverAddress = entry[0]; + if (topology.description.hasServer(serverAddress)) { + continue; + } + if (!topology.s.servers.has(serverAddress)) { + continue; + } + const server = topology.s.servers.get(serverAddress); + topology.s.servers.delete(serverAddress); + // prepare server for garbage collection + if (server) { + destroyServer(server, topology); + } + } +} +function drainWaitQueue(queue, err) { + while (queue.length) { + const waitQueueMember = queue.shift(); + if (!waitQueueMember) { + continue; + } + if (waitQueueMember.timer) { + clearTimeout(waitQueueMember.timer); + } + if (!waitQueueMember[kCancelled]) { + waitQueueMember.callback(err); + } + } +} +function processWaitQueue(topology) { + if (topology.s.state === common_1.STATE_CLOSED) { + drainWaitQueue(topology[kWaitQueue], new error_1.MongoTopologyClosedError()); + return; + } + const isSharded = topology.description.type === common_1.TopologyType.Sharded; + const serverDescriptions = Array.from(topology.description.servers.values()); + const membersToProcess = topology[kWaitQueue].length; + for (let i = 0; i < membersToProcess; ++i) { + const waitQueueMember = topology[kWaitQueue].shift(); + if (!waitQueueMember) { + continue; + } + if (waitQueueMember[kCancelled]) { + continue; + } + let selectedDescriptions; + try { + const serverSelector = waitQueueMember.serverSelector; + selectedDescriptions = serverSelector + ? serverSelector(topology.description, serverDescriptions) + : serverDescriptions; + } + catch (e) { + if (waitQueueMember.timer) { + clearTimeout(waitQueueMember.timer); + } + waitQueueMember.callback(e); + continue; + } + let selectedServer; + if (selectedDescriptions.length === 0) { + topology[kWaitQueue].push(waitQueueMember); + continue; + } + else if (selectedDescriptions.length === 1) { + selectedServer = topology.s.servers.get(selectedDescriptions[0].address); + } + else { + // don't shuffle the array if there are only two elements + const descriptions = selectedDescriptions.length === 2 ? selectedDescriptions : (0, utils_1.shuffle)(selectedDescriptions, 2); + const server1 = topology.s.servers.get(descriptions[0].address); + const server2 = topology.s.servers.get(descriptions[1].address); + selectedServer = + server1 && server2 && server1.s.operationCount < server2.s.operationCount + ? server1 + : server2; + } + if (!selectedServer) { + waitQueueMember.callback(new error_1.MongoServerSelectionError('server selection returned a server description but the server was not found in the topology', topology.description)); + return; + } + const transaction = waitQueueMember.transaction; + if (isSharded && transaction && transaction.isActive && selectedServer) { + transaction.pinServer(selectedServer); + } + if (waitQueueMember.timer) { + clearTimeout(waitQueueMember.timer); + } + waitQueueMember.callback(undefined, selectedServer); + } + if (topology[kWaitQueue].length > 0) { + // ensure all server monitors attempt monitoring soon + for (const [, server] of topology.s.servers) { + process.nextTick(function scheduleServerCheck() { + return server.requestCheck(); + }); + } + } +} +function isStaleServerDescription(topologyDescription, incomingServerDescription) { + const currentServerDescription = topologyDescription.servers.get(incomingServerDescription.address); + const currentTopologyVersion = currentServerDescription === null || currentServerDescription === void 0 ? void 0 : currentServerDescription.topologyVersion; + return ((0, server_description_1.compareTopologyVersion)(currentTopologyVersion, incomingServerDescription.topologyVersion) > 0); +} +/** @public */ +class ServerCapabilities { + constructor(hello) { + this.minWireVersion = hello.minWireVersion || 0; + this.maxWireVersion = hello.maxWireVersion || 0; + } + get hasAggregationCursor() { + return this.maxWireVersion >= 1; + } + get hasWriteCommands() { + return this.maxWireVersion >= 2; + } + get hasTextSearch() { + return this.minWireVersion >= 0; + } + get hasAuthCommands() { + return this.maxWireVersion >= 1; + } + get hasListCollectionsCommand() { + return this.maxWireVersion >= 3; + } + get hasListIndexesCommand() { + return this.maxWireVersion >= 3; + } + get supportsSnapshotReads() { + return this.maxWireVersion >= 13; + } + get commandsTakeWriteConcern() { + return this.maxWireVersion >= 5; + } + get commandsTakeCollation() { + return this.maxWireVersion >= 5; + } +} +exports.ServerCapabilities = ServerCapabilities; +//# sourceMappingURL=topology.js.map \ No newline at end of file diff --git a/ts-ticket-office-service/node_modules/mongodb/lib/sdam/topology.js.map b/ts-ticket-office-service/node_modules/mongodb/lib/sdam/topology.js.map new file mode 100644 index 000000000..03b17cf5a --- /dev/null +++ b/ts-ticket-office-service/node_modules/mongodb/lib/sdam/topology.js.map @@ -0,0 +1 @@ +{"version":3,"file":"topology.js","sourceRoot":"","sources":["../../src/sdam/topology.ts"],"names":[],"mappings":";;;AAAA,iCAAkC;AAClC,mCAAoC;AACpC,+BAAiC;AAGjC,kCAAiD;AAIjD,4DAAsE;AACtE,4CAcsB;AACtB,oCAMkB;AAElB,gDAAmD;AACnD,wDAAwE;AAGxE,oCASkB;AAClB,qCAWkB;AAClB,qCAOkB;AAClB,qCAA+D;AAC/D,6DAAiF;AACjF,yDAAkF;AAClF,+CAA2D;AAC3D,iEAA6D;AAE7D,eAAe;AACf,IAAI,qBAAqB,GAAG,CAAC,CAAC;AAE9B,MAAM,eAAe,GAAG,IAAA,wBAAgB,EAAC;IACvC,CAAC,qBAAY,CAAC,EAAE,CAAC,qBAAY,EAAE,yBAAgB,CAAC;IAChD,CAAC,yBAAgB,CAAC,EAAE,CAAC,yBAAgB,EAAE,sBAAa,EAAE,wBAAe,EAAE,qBAAY,CAAC;IACpF,CAAC,wBAAe,CAAC,EAAE,CAAC,wBAAe,EAAE,sBAAa,EAAE,qBAAY,CAAC;IACjE,CAAC,sBAAa,CAAC,EAAE,CAAC,sBAAa,EAAE,qBAAY,CAAC;CAC/C,CAAC,CAAC;AAEH,gBAAgB;AAChB,MAAM,UAAU,GAAG,MAAM,CAAC,WAAW,CAAC,CAAC;AACvC,gBAAgB;AAChB,MAAM,UAAU,GAAG,MAAM,CAAC,WAAW,CAAC,CAAC;AAkGvC;;;GAGG;AACH,MAAa,QAAS,SAAQ,+BAAiC;IA6C7D;;OAEG;IACH,YAAY,KAAsD,EAAE,OAAwB;;QAC1F,KAAK,EAAE,CAAC;QAER,uBAAuB;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wB,uBAAxB,wBAAwB,CAAE,eAAe,CAAC;IACzE,OAAO,CACL,IAAA,2CAAsB,EAAC,sBAAsB,EAAE,yBAAyB,CAAC,eAAe,CAAC,GAAG,CAAC,CAC9F,CAAC;AACJ,CAAC;AAED,cAAc;AACd,MAAa,kBAAkB;IAI7B,YAAY,KAAe;QACzB,IAAI,CAAC,cAAc,GAAG,KAAK,CAAC,cAAc,IAAI,CAAC,CAAC;QAChD,IAAI,CAAC,cAAc,GAAG,KAAK,CAAC,cAAc,IAAI,CAAC,CAAC;IAClD,CAAC;IAED,IAAI,oBAAoB;QACtB,OAAO,IAAI,CAAC,cAAc,IAAI,CAAC,CAAC;IAClC,CAAC;IAED,IAAI,gBAAgB;QAClB,OAAO,IAAI,CAAC,cAAc,IAAI,CAAC,CAAC;IAClC,CAAC;IACD,IAAI,aAAa;QACf,OAAO,IAAI,CAAC,cAAc,IAAI,CAAC,CAAC;IAClC,CAAC;IAED,IAAI,eAAe;QACjB,OAAO,IAAI,CAAC,cAAc,IAAI,CAAC,CAAC;IAClC,CAAC;IAED,IAAI,yBAAyB;QAC3B,OAAO,IAAI,CAAC,cAAc,IAAI,CAAC,CAAC;IAClC,CAAC;IAED,IAAI,qBAAqB;QACvB,OAAO,IAAI,CAAC,cAAc,IAAI,CAAC,CAAC;IAClC,CAAC;IAED,IAAI,qBAAqB;QACvB,OAAO,IAAI,CAAC,cAAc,IAAI,EAAE,CAAC;IACnC,CAAC;IAED,IAAI,wBAAwB;QAC1B,OAAO,IAAI,CAAC,cAAc,IAAI,CAAC,CAAC;IAClC,CAAC;IAED,IAAI,qBAAqB;QACvB,OAAO,IAAI,CAAC,cAAc,IAAI,CAAC,CAAC;IAClC,CAAC;CACF;AA3CD,gDA2CC"} \ No newline at end of file diff --git a/ts-ticket-office-service/node_modules/mongodb/lib/sdam/topology_description.js b/ts-ticket-office-service/node_modules/mongodb/lib/sdam/topology_description.js new file mode 100644 index 000000000..b6c4fd076 --- /dev/null +++ b/ts-ticket-office-service/node_modules/mongodb/lib/sdam/topology_description.js @@ -0,0 +1,358 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.TopologyDescription = void 0; +const WIRE_CONSTANTS = require("../cmap/wire_protocol/constants"); +const error_1 = require("../error"); +const utils_1 = require("../utils"); +const common_1 = require("./common"); +const server_description_1 = require("./server_description"); +// constants related to compatibility checks +const MIN_SUPPORTED_SERVER_VERSION = WIRE_CONSTANTS.MIN_SUPPORTED_SERVER_VERSION; +const MAX_SUPPORTED_SERVER_VERSION = WIRE_CONSTANTS.MAX_SUPPORTED_SERVER_VERSION; +const MIN_SUPPORTED_WIRE_VERSION = WIRE_CONSTANTS.MIN_SUPPORTED_WIRE_VERSION; +const MAX_SUPPORTED_WIRE_VERSION = WIRE_CONSTANTS.MAX_SUPPORTED_WIRE_VERSION; +const MONGOS_OR_UNKNOWN = new Set([common_1.ServerType.Mongos, common_1.ServerType.Unknown]); +const MONGOS_OR_STANDALONE = new Set([common_1.ServerType.Mongos, common_1.ServerType.Standalone]); +const NON_PRIMARY_RS_MEMBERS = new Set([ + common_1.ServerType.RSSecondary, + common_1.ServerType.RSArbiter, + common_1.ServerType.RSOther +]); +/** + * Representation of a deployment of servers + * @public + */ +class TopologyDescription { + /** + * Create a TopologyDescription + */ + constructor(topologyType, serverDescriptions, setName, maxSetVersion, maxElectionId, commonWireVersion, options) { + var _a, _b; + options = options !== null && options !== void 0 ? options : {}; + this.type = topologyType !== null && topologyType !== void 0 ? topologyType : common_1.TopologyType.Unknown; + this.servers = serverDescriptions !== null && serverDescriptions !== void 0 ? serverDescriptions : new Map(); + this.stale = false; + this.compatible = true; + this.heartbeatFrequencyMS = (_a = options.heartbeatFrequencyMS) !== null && _a !== void 0 ? _a : 0; + this.localThresholdMS = (_b = options.localThresholdMS) !== null && _b !== void 0 ? _b : 15; + if (setName) { + this.setName = setName; + } + if (maxSetVersion) { + this.maxSetVersion = maxSetVersion; + } + if (maxElectionId) { + this.maxElectionId = maxElectionId; + } + if (commonWireVersion) { + this.commonWireVersion = commonWireVersion; + } + // determine server compatibility + for (const serverDescription of this.servers.values()) { + // Load balancer mode is always compatible. + if (serverDescription.type === common_1.ServerType.Unknown || + serverDescription.type === common_1.ServerType.LoadBalancer) { + continue; + } + if (serverDescription.minWireVersion > MAX_SUPPORTED_WIRE_VERSION) { + this.compatible = false; + this.compatibilityError = `Server at ${serverDescription.address} requires wire version ${serverDescription.minWireVersion}, but this version of the driver only supports up to ${MAX_SUPPORTED_WIRE_VERSION} (MongoDB ${MAX_SUPPORTED_SERVER_VERSION})`; + } + if (serverDescription.maxWireVersion < MIN_SUPPORTED_WIRE_VERSION) { + this.compatible = false; + this.compatibilityError = `Server at ${serverDescription.address} reports wire version ${serverDescription.maxWireVersion}, but this version of the driver requires at least ${MIN_SUPPORTED_WIRE_VERSION} (MongoDB ${MIN_SUPPORTED_SERVER_VERSION}).`; + break; + } + } + // Whenever a client updates the TopologyDescription from a hello response, it MUST set + // TopologyDescription.logicalSessionTimeoutMinutes to the smallest logicalSessionTimeoutMinutes + // value among ServerDescriptions of all data-bearing server types. If any have a null + // logicalSessionTimeoutMinutes, then TopologyDescription.logicalSessionTimeoutMinutes MUST be + // set to null. + this.logicalSessionTimeoutMinutes = undefined; + for (const [, server] of this.servers) { + if (server.isReadable) { + if (server.logicalSessionTimeoutMinutes == null) { + // If any of the servers have a null logicalSessionsTimeout, then the whole topology does + this.logicalSessionTimeoutMinutes = undefined; + break; + } + if (this.logicalSessionTimeoutMinutes == null) { + // First server with a non null logicalSessionsTimeout + this.logicalSessionTimeoutMinutes = server.logicalSessionTimeoutMinutes; + continue; + } + // Always select the smaller of the: + // current server logicalSessionsTimeout and the topologies logicalSessionsTimeout + this.logicalSessionTimeoutMinutes = Math.min(this.logicalSessionTimeoutMinutes, server.logicalSessionTimeoutMinutes); + } + } + } + /** + * Returns a new TopologyDescription based on the SrvPollingEvent + * @internal + */ + updateFromSrvPollingEvent(ev, srvMaxHosts = 0) { + /** The SRV addresses defines the set of addresses we should be using */ + const incomingHostnames = ev.hostnames(); + const currentHostnames = new Set(this.servers.keys()); + const hostnamesToAdd = new Set(incomingHostnames); + const hostnamesToRemove = new Set(); + for (const hostname of currentHostnames) { + // filter hostnamesToAdd (made from incomingHostnames) down to what is *not* present in currentHostnames + hostnamesToAdd.delete(hostname); + if (!incomingHostnames.has(hostname)) { + // If the SRV Records no longer include this hostname + // we have to stop using it + hostnamesToRemove.add(hostname); + } + } + if (hostnamesToAdd.size === 0 && hostnamesToRemove.size === 0) { + // No new hosts to add and none to remove + return this; + } + const serverDescriptions = new Map(this.servers); + for (const removedHost of hostnamesToRemove) { + serverDescriptions.delete(removedHost); + } + if (hostnamesToAdd.size > 0) { + if (srvMaxHosts === 0) { + // Add all! + for (const hostToAdd of hostnamesToAdd) { + serverDescriptions.set(hostToAdd, new server_description_1.ServerDescription(hostToAdd)); + } + } + else if (serverDescriptions.size < srvMaxHosts) { + // Add only the amount needed to get us back to srvMaxHosts + const selectedHosts = (0, utils_1.shuffle)(hostnamesToAdd, srvMaxHosts - serverDescriptions.size); + for (const selectedHostToAdd of selectedHosts) { + serverDescriptions.set(selectedHostToAdd, new server_description_1.ServerDescription(selectedHostToAdd)); + } + } + } + return new TopologyDescription(this.type, serverDescriptions, this.setName, this.maxSetVersion, this.maxElectionId, this.commonWireVersion, { heartbeatFrequencyMS: this.heartbeatFrequencyMS, localThresholdMS: this.localThresholdMS }); + } + /** + * Returns a copy of this description updated with a given ServerDescription + * @internal + */ + update(serverDescription) { + const address = serverDescription.address; + // potentially mutated values + let { type: topologyType, setName, maxSetVersion, maxElectionId, commonWireVersion } = this; + if (serverDescription.setName && setName && serverDescription.setName !== setName) { + // TODO(NODE-4159): servers with an incorrect setName should be removed not marked Unknown + serverDescription = new server_description_1.ServerDescription(address, undefined); + } + const serverType = serverDescription.type; + const serverDescriptions = new Map(this.servers); + // update common wire version + if (serverDescription.maxWireVersion !== 0) { + if (commonWireVersion == null) { + commonWireVersion = serverDescription.maxWireVersion; + } + else { + commonWireVersion = Math.min(commonWireVersion, serverDescription.maxWireVersion); + } + } + // update the actual server description + serverDescriptions.set(address, serverDescription); + if (topologyType === common_1.TopologyType.Single) { + // once we are defined as single, that never changes + return new TopologyDescription(common_1.TopologyType.Single, serverDescriptions, setName, maxSetVersion, maxElectionId, commonWireVersion, { heartbeatFrequencyMS: this.heartbeatFrequencyMS, localThresholdMS: this.localThresholdMS }); + } + if (topologyType === common_1.TopologyType.Unknown) { + if (serverType === common_1.ServerType.Standalone && this.servers.size !== 1) { + serverDescriptions.delete(address); + } + else { + topologyType = topologyTypeForServerType(serverType); + } + } + if (topologyType === common_1.TopologyType.Sharded) { + if (!MONGOS_OR_UNKNOWN.has(serverType)) { + serverDescriptions.delete(address); + } + } + if (topologyType === common_1.TopologyType.ReplicaSetNoPrimary) { + if (MONGOS_OR_STANDALONE.has(serverType)) { + serverDescriptions.delete(address); + } + if (serverType === common_1.ServerType.RSPrimary) { + const result = updateRsFromPrimary(serverDescriptions, serverDescription, setName, maxSetVersion, maxElectionId); + topologyType = result[0]; + setName = result[1]; + maxSetVersion = result[2]; + maxElectionId = result[3]; + } + else if (NON_PRIMARY_RS_MEMBERS.has(serverType)) { + const result = updateRsNoPrimaryFromMember(serverDescriptions, serverDescription, setName); + topologyType = result[0]; + setName = result[1]; + } + } + if (topologyType === common_1.TopologyType.ReplicaSetWithPrimary) { + if (MONGOS_OR_STANDALONE.has(serverType)) { + serverDescriptions.delete(address); + topologyType = checkHasPrimary(serverDescriptions); + } + else if (serverType === common_1.ServerType.RSPrimary) { + const result = updateRsFromPrimary(serverDescriptions, serverDescription, setName, maxSetVersion, maxElectionId); + topologyType = result[0]; + setName = result[1]; + maxSetVersion = result[2]; + maxElectionId = result[3]; + } + else if (NON_PRIMARY_RS_MEMBERS.has(serverType)) { + topologyType = updateRsWithPrimaryFromMember(serverDescriptions, serverDescription, setName); + } + else { + topologyType = checkHasPrimary(serverDescriptions); + } + } + return new TopologyDescription(topologyType, serverDescriptions, setName, maxSetVersion, maxElectionId, commonWireVersion, { heartbeatFrequencyMS: this.heartbeatFrequencyMS, localThresholdMS: this.localThresholdMS }); + } + get error() { + const descriptionsWithError = Array.from(this.servers.values()).filter((sd) => sd.error); + if (descriptionsWithError.length > 0) { + return descriptionsWithError[0].error; + } + return; + } + /** + * Determines if the topology description has any known servers + */ + get hasKnownServers() { + return Array.from(this.servers.values()).some((sd) => sd.type !== common_1.ServerType.Unknown); + } + /** + * Determines if this topology description has a data-bearing server available. + */ + get hasDataBearingServers() { + return Array.from(this.servers.values()).some((sd) => sd.isDataBearing); + } + /** + * Determines if the topology has a definition for the provided address + * @internal + */ + hasServer(address) { + return this.servers.has(address); + } +} +exports.TopologyDescription = TopologyDescription; +function topologyTypeForServerType(serverType) { + switch (serverType) { + case common_1.ServerType.Standalone: + return common_1.TopologyType.Single; + case common_1.ServerType.Mongos: + return common_1.TopologyType.Sharded; + case common_1.ServerType.RSPrimary: + return common_1.TopologyType.ReplicaSetWithPrimary; + case common_1.ServerType.RSOther: + case common_1.ServerType.RSSecondary: + return common_1.TopologyType.ReplicaSetNoPrimary; + default: + return common_1.TopologyType.Unknown; + } +} +// TODO: improve these docs when ObjectId is properly typed +function compareObjectId(oid1, oid2) { + if (oid1 == null) { + return -1; + } + if (oid2 == null) { + return 1; + } + if (oid1.id instanceof Buffer && oid2.id instanceof Buffer) { + const oid1Buffer = oid1.id; + const oid2Buffer = oid2.id; + return oid1Buffer.compare(oid2Buffer); + } + const oid1String = oid1.toString(); + const oid2String = oid2.toString(); + return oid1String.localeCompare(oid2String); +} +function updateRsFromPrimary(serverDescriptions, serverDescription, setName, maxSetVersion, maxElectionId) { + setName = setName || serverDescription.setName; + if (setName !== serverDescription.setName) { + serverDescriptions.delete(serverDescription.address); + return [checkHasPrimary(serverDescriptions), setName, maxSetVersion, maxElectionId]; + } + const electionId = serverDescription.electionId ? serverDescription.electionId : null; + if (serverDescription.setVersion && electionId) { + if (maxSetVersion && maxElectionId) { + if (maxSetVersion > serverDescription.setVersion || + compareObjectId(maxElectionId, electionId) > 0) { + // this primary is stale, we must remove it + serverDescriptions.set(serverDescription.address, new server_description_1.ServerDescription(serverDescription.address)); + return [checkHasPrimary(serverDescriptions), setName, maxSetVersion, maxElectionId]; + } + } + maxElectionId = serverDescription.electionId; + } + if (serverDescription.setVersion != null && + (maxSetVersion == null || serverDescription.setVersion > maxSetVersion)) { + maxSetVersion = serverDescription.setVersion; + } + // We've heard from the primary. Is it the same primary as before? + for (const [address, server] of serverDescriptions) { + if (server.type === common_1.ServerType.RSPrimary && server.address !== serverDescription.address) { + // Reset old primary's type to Unknown. + serverDescriptions.set(address, new server_description_1.ServerDescription(server.address)); + // There can only be one primary + break; + } + } + // Discover new hosts from this primary's response. + serverDescription.allHosts.forEach((address) => { + if (!serverDescriptions.has(address)) { + serverDescriptions.set(address, new server_description_1.ServerDescription(address)); + } + }); + // Remove hosts not in the response. + const currentAddresses = Array.from(serverDescriptions.keys()); + const responseAddresses = serverDescription.allHosts; + currentAddresses + .filter((addr) => responseAddresses.indexOf(addr) === -1) + .forEach((address) => { + serverDescriptions.delete(address); + }); + return [checkHasPrimary(serverDescriptions), setName, maxSetVersion, maxElectionId]; +} +function updateRsWithPrimaryFromMember(serverDescriptions, serverDescription, setName) { + if (setName == null) { + // TODO(NODE-3483): should be an appropriate runtime error + throw new error_1.MongoRuntimeError('Argument "setName" is required if connected to a replica set'); + } + if (setName !== serverDescription.setName || + (serverDescription.me && serverDescription.address !== serverDescription.me)) { + serverDescriptions.delete(serverDescription.address); + } + return checkHasPrimary(serverDescriptions); +} +function updateRsNoPrimaryFromMember(serverDescriptions, serverDescription, setName) { + const topologyType = common_1.TopologyType.ReplicaSetNoPrimary; + setName = setName || serverDescription.setName; + if (setName !== serverDescription.setName) { + serverDescriptions.delete(serverDescription.address); + return [topologyType, setName]; + } + serverDescription.allHosts.forEach((address) => { + if (!serverDescriptions.has(address)) { + serverDescriptions.set(address, new server_description_1.ServerDescription(address)); + } + }); + if (serverDescription.me && serverDescription.address !== serverDescription.me) { + serverDescriptions.delete(serverDescription.address); + } + return [topologyType, setName]; +} +function checkHasPrimary(serverDescriptions) { + for (const serverDescription of serverDescriptions.values()) { + if (serverDescription.type === common_1.ServerType.RSPrimary) { + return common_1.TopologyType.ReplicaSetWithPrimary; + } + } + return common_1.TopologyType.ReplicaSetNoPrimary; +} +//# sourceMappingURL=topology_description.js.map \ No newline at end of file diff --git a/ts-ticket-office-service/node_modules/mongodb/lib/sdam/topology_description.js.map b/ts-ticket-office-service/node_modules/mongodb/lib/sdam/topology_description.js.map new file mode 100644 index 000000000..e32dd37a2 --- /dev/null +++ b/ts-ticket-office-service/node_modules/mongodb/lib/sdam/topology_description.js.map @@ -0,0 +1 @@ +{"version":3,"file":"topology_description.js","sourceRoot":"","sources":["../../src/sdam/topology_description.ts"],"names":[],"mappings":";;;AACA,kEAAkE;AAClE,oCAAyD;AACzD,oCAAmC;AACnC,qCAAoD;AACpD,6DAAyD;AAGzD,4CAA4C;AAC5C,MAAM,4BAA4B,GAAG,cAAc,CAAC,4BAA4B,CAAC;AACjF,MAAM,4BAA4B,GAAG,cAAc,CAAC,4BAA4B,CAAC;AACjF,MAAM,0BAA0B,GAAG,cAAc,CAAC,0BAA0B,CAAC;AAC7E,MAAM,0BAA0B,GAAG,cAAc,CAAC,0BAA0B,CAAC;AAE7E,MAAM,iBAAiB,GAAG,IAAI,GAAG,CAAa,CAAC,mBAAU,CAAC,MAAM,EAAE,mBAAU,CAAC,OAAO,CAAC,CAAC,CAAC;AACvF,MAAM,oBAAoB,GAAG,IAAI,GAAG,CAAa,CAAC,mBAAU,CAAC,MAAM,EAAE,mBAAU,CAAC,UAAU,CAAC,CAAC,CAAC;AAC7F,MAAM,sBAAsB,GAAG,IAAI,GAAG,CAAa;IACjD,mBAAU,CAAC,WAAW;IACtB,mBAAU,CAAC,SAAS;IACpB,mBAAU,CAAC,OAAO;CACnB,CAAC,CAAC;AAQH;;;GAGG;AAC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,iBAAiB,CAAC,OAAO,EAAE;QACzC,kBAAkB,CAAC,MAAM,CAAC,iBAAiB,CAAC,OAAO,CAAC,CAAC;QACrD,OAAO,CAAC,YAAY,EAAE,OAAO,CAAC,CAAC;KAChC;IAED,iBAAiB,CAAC,QAAQ,CAAC,OAAO,CAAC,CAAC,OAAe,EAAE,EAAE;QACrD,IAAI,CAAC,kBAAkB,CAAC,GAAG,CAAC,OAAO,CAAC,EAAE;YACpC,kBAAkB,CAAC,GAAG,CAAC,OAAO,EAAE,IAAI,sCAAiB,CAAC,OAAO,CAAC,CAAC,CAAC;SACjE;IACH,CAAC,CAAC,CAAC;IAEH,IAAI,iBAAiB,CAAC,EAAE,IAAI,iBAAiB,CAAC,OAAO,KAAK,iBAAiB,CAAC,EAAE,EAAE;QAC9E,kBAAkB,CAAC,MAAM,CAAC,iBAAiB,CAAC,OAAO,CAAC,CAAC;KACtD;IAED,OAAO,CAAC,YAAY,EAAE,OAAO,CAAC,CAAC;AACjC,CAAC;AAED,SAAS,eAAe,CAAC,kBAAkD;IACzE,KAAK,MAAM,iBAAiB,IAAI,kBAAkB,CAAC,MAAM,EAAE,EAAE;QAC3D,IAAI,iBAAiB,CAAC,IAAI,KAAK,mBAAU,CAAC,SAAS,EAAE;YACnD,OAAO,qBAAY,CAAC,qBAAqB,CAAC;SAC3C;KACF;IAED,OAAO,qBAAY,CAAC,mBAAmB,CAAC;AAC1C,CAAC"} \ No newline at end of file diff --git a/ts-ticket-office-service/node_modules/mongodb/lib/server.js b/ts-ticket-office-service/node_modules/mongodb/lib/server.js deleted file mode 100644 index e42dc6aac..000000000 --- a/ts-ticket-office-service/node_modules/mongodb/lib/server.js +++ /dev/null @@ -1,518 +0,0 @@ -"use strict"; - -var EventEmitter = require('events').EventEmitter - , inherits = require('util').inherits - , CServer = require('mongodb-core').Server - , Cursor = require('./cursor') - , AggregationCursor = require('./aggregation_cursor') - , CommandCursor = require('./command_cursor') - , f = require('util').format - , ServerCapabilities = require('./topology_base').ServerCapabilities - , Store = require('./topology_base').Store - , Define = require('./metadata') - , MongoError = require('mongodb-core').MongoError - , MAX_JS_INT = require('./utils').MAX_JS_INT - , translateOptions = require('./utils').translateOptions - , filterOptions = require('./utils').filterOptions - , mergeOptions = require('./utils').mergeOptions - , getReadPreference = require('./utils').getReadPreference - , os = require('os'); - -// Get package.json variable -var driverVersion = require('../package.json').version; -var nodejsversion = f('Node.js %s, %s', process.version, os.endianness()); -var type = os.type(); -var name = process.platform; -var architecture = process.arch; -var release = os.release(); - -/** - * @fileOverview The **Server** class is a class that represents a single server topology and is - * used to construct connections. - * - * **Server Should not be used, use MongoClient.connect** - * @example - * var Db = require('mongodb').Db, - * Server = require('mongodb').Server, - * test = require('assert'); - * // Connect using single Server - * var db = new Db('test', new Server('localhost', 27017);); - * db.open(function(err, db) { - * // Get an additional db - * db.close(); - * }); - */ - - // Allowed parameters - var legalOptionNames = ['ha', 'haInterval', 'acceptableLatencyMS' - , 'poolSize', 'ssl', 'checkServerIdentity', 'sslValidate' - , 'sslCA', 'sslCRL', 'sslCert', 'sslKey', 'sslPass', 'socketOptions', 'bufferMaxEntries' - , 'store', 'auto_reconnect', 'autoReconnect', 'emitError' - , 'keepAlive', 'noDelay', 'connectTimeoutMS', 'socketTimeoutMS', 'family' - , 'loggerLevel', 'logger', 'reconnectTries', 'reconnectInterval', 'monitoring' - , 'appname', 'domainsEnabled' - , 'servername', 'promoteLongs', 'promoteValues', 'promoteBuffers']; - -/** - * Creates a new Server instance - * @class - * @deprecated - * @param {string} host The host for the server, can be either an IP4, IP6 or entity socket style host. - * @param {number} [port] The server port if IP4. - * @param {object} [options=null] Optional settings. - * @param {number} [options.poolSize=5] Number of connections in the connection pool for each server instance, set to 5 as default for legacy reasons. - * @param {boolean} [options.ssl=false] Use ssl connection (needs to have a mongod server with ssl support) - * @param {object} [options.sslValidate=true] Validate mongod server certificate against ca (needs to have a mongod server with ssl support, 2.4 or higher) - * @param {boolean|function} [options.checkServerIdentity=true] Ensure we check server identify during SSL, set to false to disable checking. Only works for Node 0.12.x or higher. You can pass in a boolean or your own checkServerIdentity override function. - * @param {array} [options.sslCA=null] Array of valid certificates either as Buffers or Strings (needs to have a mongod server with ssl support, 2.4 or higher) - * @param {array} [options.sslCRL=null] Array of revocation certificates either as Buffers or Strings (needs to have a mongod server with ssl support, 2.4 or higher) - * @param {(Buffer|string)} [options.sslCert=null] String or buffer containing the certificate we wish to present (needs to have a mongod server with ssl support, 2.4 or higher) - * @param {(Buffer|string)} [options.sslKey=null] String or buffer containing the certificate private key we wish to present (needs to have a mongod server with ssl support, 2.4 or higher) - * @param {(Buffer|string)} [options.sslPass=null] String or buffer containing the certificate password (needs to have a mongod server with ssl support, 2.4 or higher) - * @param {string} [options.servername=null] String containing the server name requested via TLS SNI. - * @param {boolean} [options.autoReconnect=true] Reconnect on error or timeout. - * @param {object} [options.socketOptions=null] Socket options - * @param {boolean} [options.socketOptions.noDelay=true] TCP Socket NoDelay option. - * @param {number} [options.socketOptions.keepAlive=0] TCP KeepAlive on the socket with a X ms delay before start. - * @param {number} [options.socketOptions.connectTimeoutMS=0] TCP Connection timeout setting - * @param {number} [options.socketOptions.socketTimeoutMS=0] TCP Socket timeout setting - * @param {number} [options.reconnectTries=30] Server attempt to reconnect #times - * @param {number} [options.reconnectInterval=1000] Server will wait # milliseconds between retries - * @param {number} [options.monitoring=true] Triggers the server instance to call ismaster - * @param {number} [options.haInterval=10000] The interval of calling ismaster when monitoring is enabled. - * @param {boolean} [options.domainsEnabled=false] Enable the wrapping of the callback in the current entity, disabled by default to avoid perf hit. - * @fires Server#connect - * @fires Server#close - * @fires Server#error - * @fires Server#timeout - * @fires Server#parseError - * @fires Server#reconnect - * @property {string} parserType the parser type used (c++ or js). - * @return {Server} a Server instance. - */ -var Server = function(host, port, options) { - options = options || {}; - if(!(this instanceof Server)) return new Server(host, port, options); - EventEmitter.call(this); - var self = this; - - // Filter the options - options = filterOptions(options, legalOptionNames); - - // Stored options - var storeOptions = { - force: false - , bufferMaxEntries: typeof options.bufferMaxEntries == 'number' ? options.bufferMaxEntries : MAX_JS_INT - } - - // Shared global store - var store = options.store || new Store(self, storeOptions); - - // Detect if we have a socket connection - if(host.indexOf('\/') != -1) { - if(port != null && typeof port == 'object') { - options = port; - port = null; - } - } else if(port == null) { - throw MongoError.create({message: 'port must be specified', driver:true}); - } - - // Get the reconnect option - var reconnect = typeof options.auto_reconnect == 'boolean' ? options.auto_reconnect : true; - reconnect = typeof options.autoReconnect == 'boolean' ? options.autoReconnect : reconnect; - - // Clone options - var clonedOptions = mergeOptions({}, { - host: host, port: port, disconnectHandler: store, - cursorFactory: Cursor, - reconnect: reconnect, - emitError: typeof options.emitError == 'boolean' ? options.emitError : true, - size: typeof options.poolSize == 'number' ? options.poolSize : 5 - }); - - // Translate any SSL options and other connectivity options - clonedOptions = translateOptions(clonedOptions, options); - - // Socket options - var socketOptions = options.socketOptions && Object.keys(options.socketOptions).length > 0 - ? options.socketOptions : options; - - // Translate all the options to the mongodb-core ones - clonedOptions = translateOptions(clonedOptions, socketOptions); - if(typeof clonedOptions.keepAlive == 'number') { - clonedOptions.keepAliveInitialDelay = clonedOptions.keepAlive; - clonedOptions.keepAlive = clonedOptions.keepAlive > 0; - } - - // Build default client information - this.clientInfo = { - driver: { - name: "nodejs", - version: driverVersion - }, - os: { - type: type, - name: name, - architecture: architecture, - version: release - }, - platform: nodejsversion - } - - // Build default client information - clonedOptions.clientInfo = this.clientInfo; - // Do we have an application specific string - if(options.appname) { - clonedOptions.clientInfo.application = { name: options.appname }; - } - - // Create an instance of a server instance from mongodb-core - var server = new CServer(clonedOptions); - - // Define the internal properties - this.s = { - // Create an instance of a server instance from mongodb-core - server: server - // Server capabilities - , sCapabilities: null - // Cloned options - , clonedOptions: clonedOptions - // Reconnect - , reconnect: clonedOptions.reconnect - // Emit error - , emitError: clonedOptions.emitError - // Pool size - , poolSize: clonedOptions.size - // Store Options - , storeOptions: storeOptions - // Store - , store: store - // Host - , host: host - // Port - , port: port - // Options - , options: options - } -} - -inherits(Server, EventEmitter); - -var define = Server.define = new Define('Server', Server, false); - -// BSON property -Object.defineProperty(Server.prototype, 'bson', { - enumerable: true, get: function() { - return this.s.server.s.bson; - } -}); - -// Last ismaster -Object.defineProperty(Server.prototype, 'isMasterDoc', { - enumerable:true, get: function() { - return this.s.server.lastIsMaster(); - } -}); - -Object.defineProperty(Server.prototype, 'parserType', { - enumerable:true, get: function() { - return this.s.server.parserType; - } -}); - -// Last ismaster -Object.defineProperty(Server.prototype, 'poolSize', { - enumerable:true, get: function() { return this.s.server.connections().length; } -}); - -Object.defineProperty(Server.prototype, 'autoReconnect', { - enumerable:true, get: function() { return this.s.reconnect; } -}); - -Object.defineProperty(Server.prototype, 'host', { - enumerable:true, get: function() { return this.s.host; } -}); - -Object.defineProperty(Server.prototype, 'port', { - enumerable:true, get: function() { return this.s.port; } -}); - -// Connect -Server.prototype.connect = function(db, _options, callback) { - var self = this; - if('function' === typeof _options) callback = _options, _options = {}; - if(_options == null) _options = {}; - if(!('function' === typeof callback)) callback = null; - self.s.options = _options; - - // Update bufferMaxEntries - self.s.storeOptions.bufferMaxEntries = db.bufferMaxEntries; - - // Error handler - var connectErrorHandler = function() { - return function(err) { - // Remove all event handlers - var events = ['timeout', 'error', 'close']; - events.forEach(function(e) { - self.s.server.removeListener(e, connectHandlers[e]); - }); - - self.s.server.removeListener('connect', connectErrorHandler); - - // Try to callback - try { - callback(err); - } catch(err) { - process.nextTick(function() { throw err; }) - } - } - } - - // Actual handler - var errorHandler = function(event) { - return function(err) { - if(event != 'error') { - self.emit(event, err); - } - } - } - - // Error handler - var reconnectHandler = function() { - self.emit('reconnect', self); - self.s.store.execute(); - } - - // Reconnect failed - var reconnectFailedHandler = function(err) { - self.emit('reconnectFailed', err); - self.s.store.flush(err); - } - - // Destroy called on topology, perform cleanup - var destroyHandler = function() { - self.s.store.flush(); - } - - // relay the event - var relay = function(event) { - return function(t, server) { - self.emit(event, t, server); - } - } - - // Connect handler - var connectHandler = function() { - // Clear out all the current handlers left over - ["timeout", "error", "close", 'destroy'].forEach(function(e) { - self.s.server.removeAllListeners(e); - }); - - // Set up listeners - self.s.server.on('timeout', errorHandler('timeout')); - self.s.server.once('error', errorHandler('error')); - self.s.server.on('close', errorHandler('close')); - // Only called on destroy - self.s.server.on('destroy', destroyHandler); - - // Emit open event - self.emit('open', null, self); - - // Return correctly - try { - callback(null, self); - } catch(err) { - console.log(err.stack) - process.nextTick(function() { throw err; }) - } - } - - // Set up listeners - var connectHandlers = { - timeout: connectErrorHandler('timeout'), - error: connectErrorHandler('error'), - close: connectErrorHandler('close') - }; - - // Clear out all the current handlers left over - ["timeout", "error", "close", 'serverOpening', 'serverDescriptionChanged', 'serverHeartbeatStarted', - 'serverHeartbeatSucceeded', 'serverHeartbeatFailed', 'serverClosed', 'topologyOpening', - 'topologyClosed', 'topologyDescriptionChanged'].forEach(function(e) { - self.s.server.removeAllListeners(e); - }); - - // Add the event handlers - self.s.server.once('timeout', connectHandlers.timeout); - self.s.server.once('error', connectHandlers.error); - self.s.server.once('close', connectHandlers.close); - self.s.server.once('connect', connectHandler); - // Reconnect server - self.s.server.on('reconnect', reconnectHandler); - self.s.server.on('reconnectFailed', reconnectFailedHandler); - - // Set up SDAM listeners - self.s.server.on('serverDescriptionChanged', relay('serverDescriptionChanged')); - self.s.server.on('serverHeartbeatStarted', relay('serverHeartbeatStarted')); - self.s.server.on('serverHeartbeatSucceeded', relay('serverHeartbeatSucceeded')); - self.s.server.on('serverHeartbeatFailed', relay('serverHeartbeatFailed')); - self.s.server.on('serverOpening', relay('serverOpening')); - self.s.server.on('serverClosed', relay('serverClosed')); - self.s.server.on('topologyOpening', relay('topologyOpening')); - self.s.server.on('topologyClosed', relay('topologyClosed')); - self.s.server.on('topologyDescriptionChanged', relay('topologyDescriptionChanged')); - self.s.server.on('attemptReconnect', relay('attemptReconnect')); - self.s.server.on('monitoring', relay('monitoring')); - - // Start connection - self.s.server.connect(_options); -} - -// Server capabilities -Server.prototype.capabilities = function() { - if(this.s.sCapabilities) return this.s.sCapabilities; - if(this.s.server.lastIsMaster() == null) return null; - this.s.sCapabilities = new ServerCapabilities(this.s.server.lastIsMaster()); - return this.s.sCapabilities; -} - -define.classMethod('capabilities', {callback: false, promise:false, returns: [ServerCapabilities]}); - -// Command -Server.prototype.command = function(ns, cmd, options, callback) { - this.s.server.command(ns, cmd, getReadPreference(options), callback); -} - -define.classMethod('command', {callback: true, promise:false}); - -// Insert -Server.prototype.insert = function(ns, ops, options, callback) { - this.s.server.insert(ns, ops, options, callback); -} - -define.classMethod('insert', {callback: true, promise:false}); - -// Update -Server.prototype.update = function(ns, ops, options, callback) { - this.s.server.update(ns, ops, options, callback); -} - -define.classMethod('update', {callback: true, promise:false}); - -// Remove -Server.prototype.remove = function(ns, ops, options, callback) { - this.s.server.remove(ns, ops, options, callback); -} - -define.classMethod('remove', {callback: true, promise:false}); - -// IsConnected -Server.prototype.isConnected = function() { - return this.s.server.isConnected(); -} - -Server.prototype.isDestroyed = function() { - return this.s.server.isDestroyed(); -} - -define.classMethod('isConnected', {callback: false, promise:false, returns: [Boolean]}); - -// Insert -Server.prototype.cursor = function(ns, cmd, options) { - options.disconnectHandler = this.s.store; - return this.s.server.cursor(ns, cmd, options); -} - -define.classMethod('cursor', {callback: false, promise:false, returns: [Cursor, AggregationCursor, CommandCursor]}); - -Server.prototype.lastIsMaster = function() { - return this.s.server.lastIsMaster(); -} - -/** - * Unref all sockets - * @method - */ -Server.prototype.unref = function() { - this.s.server.unref(); -} - -Server.prototype.close = function(forceClosed) { - this.s.server.destroy(); - // We need to wash out all stored processes - if(forceClosed == true) { - this.s.storeOptions.force = forceClosed; - this.s.store.flush(); - } -} - -define.classMethod('close', {callback: false, promise:false}); - -Server.prototype.auth = function() { - var args = Array.prototype.slice.call(arguments, 0); - this.s.server.auth.apply(this.s.server, args); -} - -define.classMethod('auth', {callback: true, promise:false}); - -Server.prototype.logout = function() { - var args = Array.prototype.slice.call(arguments, 0); - this.s.server.logout.apply(this.s.server, args); -} - -define.classMethod('logout', {callback: true, promise:false}); - -/** - * All raw connections - * @method - * @return {array} - */ -Server.prototype.connections = function() { - return this.s.server.connections(); -} - -define.classMethod('connections', {callback: false, promise:false, returns:[Array]}); - -/** - * Server connect event - * - * @event Server#connect - * @type {object} - */ - -/** - * Server close event - * - * @event Server#close - * @type {object} - */ - -/** - * Server reconnect event - * - * @event Server#reconnect - * @type {object} - */ - -/** - * Server error event - * - * @event Server#error - * @type {MongoError} - */ - -/** - * Server timeout event - * - * @event Server#timeout - * @type {object} - */ - -/** - * Server parseError event - * - * @event Server#parseError - * @type {object} - */ - -module.exports = Server; diff --git a/ts-ticket-office-service/node_modules/mongodb/lib/sessions.js b/ts-ticket-office-service/node_modules/mongodb/lib/sessions.js new file mode 100644 index 000000000..232a762ee --- /dev/null +++ b/ts-ticket-office-service/node_modules/mongodb/lib/sessions.js @@ -0,0 +1,745 @@ +"use strict"; +var _a; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.updateSessionFromResponse = exports.applySession = exports.ServerSessionPool = exports.ServerSession = exports.maybeClearPinnedConnection = exports.ClientSession = void 0; +const bson_1 = require("./bson"); +const metrics_1 = require("./cmap/metrics"); +const shared_1 = require("./cmap/wire_protocol/shared"); +const constants_1 = require("./constants"); +const error_1 = require("./error"); +const mongo_types_1 = require("./mongo_types"); +const execute_operation_1 = require("./operations/execute_operation"); +const run_command_1 = require("./operations/run_command"); +const promise_provider_1 = require("./promise_provider"); +const read_concern_1 = require("./read_concern"); +const read_preference_1 = require("./read_preference"); +const common_1 = require("./sdam/common"); +const transactions_1 = require("./transactions"); +const utils_1 = require("./utils"); +const minWireVersionForShardedTransactions = 8; +/** @internal */ +const kServerSession = Symbol('serverSession'); +/** @internal */ +const kSnapshotTime = Symbol('snapshotTime'); +/** @internal */ +const kSnapshotEnabled = Symbol('snapshotEnabled'); +/** @internal */ +const kPinnedConnection = Symbol('pinnedConnection'); +/** @internal Accumulates total number of increments to add to txnNumber when applying session to command */ +const kTxnNumberIncrement = Symbol('txnNumberIncrement'); +/** + * A class representing a client session on the server + * + * NOTE: not meant to be instantiated directly. + * @public + */ +class ClientSession extends mongo_types_1.TypedEventEmitter { + /** + * Create a client session. + * @internal + * @param client - The current client + * @param sessionPool - The server session pool (Internal Class) + * @param options - Optional settings + * @param clientOptions - Optional settings provided when creating a MongoClient + */ + constructor(client, sessionPool, options, clientOptions) { + super(); + /** @internal */ + this[_a] = false; + if (client == null) { + // TODO(NODE-3483) + throw new error_1.MongoRuntimeError('ClientSession requires a MongoClient'); + } + if (sessionPool == null || !(sessionPool instanceof ServerSessionPool)) { + // TODO(NODE-3483) + throw new error_1.MongoRuntimeError('ClientSession requires a ServerSessionPool'); + } + options = options !== null && options !== void 0 ? options : {}; + if (options.snapshot === true) { + this[kSnapshotEnabled] = true; + if (options.causalConsistency === true) { + throw new error_1.MongoInvalidArgumentError('Properties "causalConsistency" and "snapshot" are mutually exclusive'); + } + } + this.client = client; + this.sessionPool = sessionPool; + this.hasEnded = false; + this.clientOptions = clientOptions; + this.explicit = !!options.explicit; + this[kServerSession] = this.explicit ? this.sessionPool.acquire() : null; + this[kTxnNumberIncrement] = 0; + this.supports = { + causalConsistency: options.snapshot !== true && options.causalConsistency !== false + }; + this.clusterTime = options.initialClusterTime; + this.operationTime = undefined; + this.owner = options.owner; + this.defaultTransactionOptions = Object.assign({}, options.defaultTransactionOptions); + this.transaction = new transactions_1.Transaction(); + } + /** The server id associated with this session */ + get id() { + var _b; + return (_b = this[kServerSession]) === null || _b === void 0 ? void 0 : _b.id; + } + get serverSession() { + let serverSession = this[kServerSession]; + if (serverSession == null) { + if (this.explicit) { + throw new error_1.MongoRuntimeError('Unexpected null serverSession for an explicit session'); + } + if (this.hasEnded) { + throw new error_1.MongoRuntimeError('Unexpected null serverSession for an ended implicit session'); + } + serverSession = this.sessionPool.acquire(); + this[kServerSession] = serverSession; + } + return serverSession; + } + /** Whether or not this session is configured for snapshot reads */ + get snapshotEnabled() { + return this[kSnapshotEnabled]; + } + get loadBalanced() { + var _b; + return ((_b = this.client.topology) === null || _b === void 0 ? void 0 : _b.description.type) === common_1.TopologyType.LoadBalanced; + } + /** @internal */ + get pinnedConnection() { + return this[kPinnedConnection]; + } + /** @internal */ + pin(conn) { + if (this[kPinnedConnection]) { + throw TypeError('Cannot pin multiple connections to the same session'); + } + this[kPinnedConnection] = conn; + conn.emit(constants_1.PINNED, this.inTransaction() ? metrics_1.ConnectionPoolMetrics.TXN : metrics_1.ConnectionPoolMetrics.CURSOR); + } + /** @internal */ + unpin(options) { + if (this.loadBalanced) { + return maybeClearPinnedConnection(this, options); + } + this.transaction.unpinServer(); + } + get isPinned() { + return this.loadBalanced ? !!this[kPinnedConnection] : this.transaction.isPinned; + } + endSession(options, callback) { + if (typeof options === 'function') + (callback = options), (options = {}); + const finalOptions = { force: true, ...options }; + return (0, utils_1.maybePromise)(callback, done => { + if (this.hasEnded) { + maybeClearPinnedConnection(this, finalOptions); + return done(); + } + const completeEndSession = () => { + maybeClearPinnedConnection(this, finalOptions); + const serverSession = this[kServerSession]; + if (serverSession != null) { + // release the server session back to the pool + this.sessionPool.release(serverSession); + // Make sure a new serverSession never makes it onto this ClientSession + Object.defineProperty(this, kServerSession, { + value: ServerSession.clone(serverSession), + writable: false + }); + } + // mark the session as ended, and emit a signal + this.hasEnded = true; + this.emit('ended', this); + // spec indicates that we should ignore all errors for `endSessions` + done(); + }; + if (this.inTransaction()) { + // If we've reached endSession and the transaction is still active + // by default we abort it + this.abortTransaction(err => { + if (err) + return done(err); + completeEndSession(); + }); + return; + } + completeEndSession(); + }); + } + /** + * Advances the operationTime for a ClientSession. + * + * @param operationTime - the `BSON.Timestamp` of the operation type it is desired to advance to + */ + advanceOperationTime(operationTime) { + if (this.operationTime == null) { + this.operationTime = operationTime; + return; + } + if (operationTime.greaterThan(this.operationTime)) { + this.operationTime = operationTime; + } + } + /** + * Advances the clusterTime for a ClientSession to the provided clusterTime of another ClientSession + * + * @param clusterTime - the $clusterTime returned by the server from another session in the form of a document containing the `BSON.Timestamp` clusterTime and signature + */ + advanceClusterTime(clusterTime) { + var _b, _c; + if (!clusterTime || typeof clusterTime !== 'object') { + throw new error_1.MongoInvalidArgumentError('input cluster time must be an object'); + } + if (!clusterTime.clusterTime || clusterTime.clusterTime._bsontype !== 'Timestamp') { + throw new error_1.MongoInvalidArgumentError('input cluster time "clusterTime" property must be a valid BSON Timestamp'); + } + if (!clusterTime.signature || + ((_b = clusterTime.signature.hash) === null || _b === void 0 ? void 0 : _b._bsontype) !== 'Binary' || + (typeof clusterTime.signature.keyId !== 'number' && + ((_c = clusterTime.signature.keyId) === null || _c === void 0 ? void 0 : _c._bsontype) !== 'Long') // apparently we decode the key to number? + ) { + throw new error_1.MongoInvalidArgumentError('input cluster time must have a valid "signature" property with BSON Binary hash and BSON Long keyId'); + } + (0, common_1._advanceClusterTime)(this, clusterTime); + } + /** + * Used to determine if this session equals another + * + * @param session - The session to compare to + */ + equals(session) { + if (!(session instanceof ClientSession)) { + return false; + } + if (this.id == null || session.id == null) { + return false; + } + return this.id.id.buffer.equals(session.id.id.buffer); + } + /** + * Increment the transaction number on the internal ServerSession + * + * @privateRemarks + * This helper increments a value stored on the client session that will be + * added to the serverSession's txnNumber upon applying it to a command. + * This is because the serverSession is lazily acquired after a connection is obtained + */ + incrementTransactionNumber() { + this[kTxnNumberIncrement] += 1; + } + /** @returns whether this session is currently in a transaction or not */ + inTransaction() { + return this.transaction.isActive; + } + /** + * Starts a new transaction with the given options. + * + * @param options - Options for the transaction + */ + startTransaction(options) { + var _b, _c, _d, _e, _f, _g, _h, _j, _k, _l; + if (this[kSnapshotEnabled]) { + throw new error_1.MongoCompatibilityError('Transactions are not allowed with snapshot sessions'); + } + if (this.inTransaction()) { + throw new error_1.MongoTransactionError('Transaction already in progress'); + } + if (this.isPinned && this.transaction.isCommitted) { + this.unpin(); + } + const topologyMaxWireVersion = (0, utils_1.maxWireVersion)(this.client.topology); + if ((0, shared_1.isSharded)(this.client.topology) && + topologyMaxWireVersion != null && + topologyMaxWireVersion < minWireVersionForShardedTransactions) { + throw new error_1.MongoCompatibilityError('Transactions are not supported on sharded clusters in MongoDB < 4.2.'); + } + // increment txnNumber + this.incrementTransactionNumber(); + // create transaction state + this.transaction = new transactions_1.Transaction({ + readConcern: (_c = (_b = options === null || options === void 0 ? void 0 : options.readConcern) !== null && _b !== void 0 ? _b : this.defaultTransactionOptions.readConcern) !== null && _c !== void 0 ? _c : (_d = this.clientOptions) === null || _d === void 0 ? void 0 : _d.readConcern, + writeConcern: (_f = (_e = options === null || options === void 0 ? void 0 : options.writeConcern) !== null && _e !== void 0 ? _e : this.defaultTransactionOptions.writeConcern) !== null && _f !== void 0 ? _f : (_g = this.clientOptions) === null || _g === void 0 ? void 0 : _g.writeConcern, + readPreference: (_j = (_h = options === null || options === void 0 ? void 0 : options.readPreference) !== null && _h !== void 0 ? _h : this.defaultTransactionOptions.readPreference) !== null && _j !== void 0 ? _j : (_k = this.clientOptions) === null || _k === void 0 ? void 0 : _k.readPreference, + maxCommitTimeMS: (_l = options === null || options === void 0 ? void 0 : options.maxCommitTimeMS) !== null && _l !== void 0 ? _l : this.defaultTransactionOptions.maxCommitTimeMS + }); + this.transaction.transition(transactions_1.TxnState.STARTING_TRANSACTION); + } + commitTransaction(callback) { + return (0, utils_1.maybePromise)(callback, cb => endTransaction(this, 'commitTransaction', cb)); + } + abortTransaction(callback) { + return (0, utils_1.maybePromise)(callback, cb => endTransaction(this, 'abortTransaction', cb)); + } + /** + * This is here to ensure that ClientSession is never serialized to BSON. + */ + toBSON() { + throw new error_1.MongoRuntimeError('ClientSession cannot be serialized to BSON.'); + } + /** + * Runs a provided callback within a transaction, retrying either the commitTransaction operation + * or entire transaction as needed (and when the error permits) to better ensure that + * the transaction can complete successfully. + * + * **IMPORTANT:** This method requires the user to return a Promise, and `await` all operations. + * Any callbacks that do not return a Promise will result in undefined behavior. + * + * @remarks + * This function: + * - Will return the command response from the final commitTransaction if every operation is successful (can be used as a truthy object) + * - Will return `undefined` if the transaction is explicitly aborted with `await session.abortTransaction()` + * - Will throw if one of the operations throws or `throw` statement is used inside the `withTransaction` callback + * + * Checkout a descriptive example here: + * @see https://www.mongodb.com/developer/quickstart/node-transactions/ + * + * @param fn - callback to run within a transaction + * @param options - optional settings for the transaction + * @returns A raw command response or undefined + */ + withTransaction(fn, options) { + const startTime = (0, utils_1.now)(); + return attemptTransaction(this, startTime, fn, options); + } +} +exports.ClientSession = ClientSession; +_a = kSnapshotEnabled; +const MAX_WITH_TRANSACTION_TIMEOUT = 120000; +const NON_DETERMINISTIC_WRITE_CONCERN_ERRORS = new Set([ + 'CannotSatisfyWriteConcern', + 'UnknownReplWriteConcern', + 'UnsatisfiableWriteConcern' +]); +function hasNotTimedOut(startTime, max) { + return (0, utils_1.calculateDurationInMs)(startTime) < max; +} +function isUnknownTransactionCommitResult(err) { + const isNonDeterministicWriteConcernError = err instanceof error_1.MongoServerError && + err.codeName && + NON_DETERMINISTIC_WRITE_CONCERN_ERRORS.has(err.codeName); + return (isMaxTimeMSExpiredError(err) || + (!isNonDeterministicWriteConcernError && + err.code !== error_1.MONGODB_ERROR_CODES.UnsatisfiableWriteConcern && + err.code !== error_1.MONGODB_ERROR_CODES.UnknownReplWriteConcern)); +} +function maybeClearPinnedConnection(session, options) { + // unpin a connection if it has been pinned + const conn = session[kPinnedConnection]; + const error = options === null || options === void 0 ? void 0 : options.error; + if (session.inTransaction() && + error && + error instanceof error_1.MongoError && + error.hasErrorLabel(error_1.MongoErrorLabel.TransientTransactionError)) { + return; + } + const topology = session.client.topology; + // NOTE: the spec talks about what to do on a network error only, but the tests seem to + // to validate that we don't unpin on _all_ errors? + if (conn && topology != null) { + const servers = Array.from(topology.s.servers.values()); + const loadBalancer = servers[0]; + if ((options === null || options === void 0 ? void 0 : options.error) == null || (options === null || options === void 0 ? void 0 : options.force)) { + loadBalancer.s.pool.checkIn(conn); + conn.emit(constants_1.UNPINNED, session.transaction.state !== transactions_1.TxnState.NO_TRANSACTION + ? metrics_1.ConnectionPoolMetrics.TXN + : metrics_1.ConnectionPoolMetrics.CURSOR); + if (options === null || options === void 0 ? void 0 : options.forceClear) { + loadBalancer.s.pool.clear(conn.serviceId); + } + } + session[kPinnedConnection] = undefined; + } +} +exports.maybeClearPinnedConnection = maybeClearPinnedConnection; +function isMaxTimeMSExpiredError(err) { + if (err == null || !(err instanceof error_1.MongoServerError)) { + return false; + } + return (err.code === error_1.MONGODB_ERROR_CODES.MaxTimeMSExpired || + (err.writeConcernError && err.writeConcernError.code === error_1.MONGODB_ERROR_CODES.MaxTimeMSExpired)); +} +function attemptTransactionCommit(session, startTime, fn, options) { + return session.commitTransaction().catch((err) => { + if (err instanceof error_1.MongoError && + hasNotTimedOut(startTime, MAX_WITH_TRANSACTION_TIMEOUT) && + !isMaxTimeMSExpiredError(err)) { + if (err.hasErrorLabel(error_1.MongoErrorLabel.UnknownTransactionCommitResult)) { + return attemptTransactionCommit(session, startTime, fn, options); + } + if (err.hasErrorLabel(error_1.MongoErrorLabel.TransientTransactionError)) { + return attemptTransaction(session, startTime, fn, options); + } + } + throw err; + }); +} +const USER_EXPLICIT_TXN_END_STATES = new Set([ + transactions_1.TxnState.NO_TRANSACTION, + transactions_1.TxnState.TRANSACTION_COMMITTED, + transactions_1.TxnState.TRANSACTION_ABORTED +]); +function userExplicitlyEndedTransaction(session) { + return USER_EXPLICIT_TXN_END_STATES.has(session.transaction.state); +} +function attemptTransaction(session, startTime, fn, options) { + const Promise = promise_provider_1.PromiseProvider.get(); + session.startTransaction(options); + let promise; + try { + promise = fn(session); + } + catch (err) { + promise = Promise.reject(err); + } + if (!(0, utils_1.isPromiseLike)(promise)) { + session.abortTransaction().catch(() => null); + throw new error_1.MongoInvalidArgumentError('Function provided to `withTransaction` must return a Promise'); + } + return promise.then(() => { + if (userExplicitlyEndedTransaction(session)) { + return; + } + return attemptTransactionCommit(session, startTime, fn, options); + }, err => { + function maybeRetryOrThrow(err) { + if (err instanceof error_1.MongoError && + err.hasErrorLabel(error_1.MongoErrorLabel.TransientTransactionError) && + hasNotTimedOut(startTime, MAX_WITH_TRANSACTION_TIMEOUT)) { + return attemptTransaction(session, startTime, fn, options); + } + if (isMaxTimeMSExpiredError(err)) { + err.addErrorLabel(error_1.MongoErrorLabel.UnknownTransactionCommitResult); + } + throw err; + } + if (session.inTransaction()) { + return session.abortTransaction().then(() => maybeRetryOrThrow(err)); + } + return maybeRetryOrThrow(err); + }); +} +function endTransaction(session, commandName, callback) { + // handle any initial problematic cases + const txnState = session.transaction.state; + if (txnState === transactions_1.TxnState.NO_TRANSACTION) { + callback(new error_1.MongoTransactionError('No transaction started')); + return; + } + if (commandName === 'commitTransaction') { + if (txnState === transactions_1.TxnState.STARTING_TRANSACTION || + txnState === transactions_1.TxnState.TRANSACTION_COMMITTED_EMPTY) { + // the transaction was never started, we can safely exit here + session.transaction.transition(transactions_1.TxnState.TRANSACTION_COMMITTED_EMPTY); + callback(); + return; + } + if (txnState === transactions_1.TxnState.TRANSACTION_ABORTED) { + callback(new error_1.MongoTransactionError('Cannot call commitTransaction after calling abortTransaction')); + return; + } + } + else { + if (txnState === transactions_1.TxnState.STARTING_TRANSACTION) { + // the transaction was never started, we can safely exit here + session.transaction.transition(transactions_1.TxnState.TRANSACTION_ABORTED); + callback(); + return; + } + if (txnState === transactions_1.TxnState.TRANSACTION_ABORTED) { + callback(new error_1.MongoTransactionError('Cannot call abortTransaction twice')); + return; + } + if (txnState === transactions_1.TxnState.TRANSACTION_COMMITTED || + txnState === transactions_1.TxnState.TRANSACTION_COMMITTED_EMPTY) { + callback(new error_1.MongoTransactionError('Cannot call abortTransaction after calling commitTransaction')); + return; + } + } + // construct and send the command + const command = { [commandName]: 1 }; + // apply a writeConcern if specified + let writeConcern; + if (session.transaction.options.writeConcern) { + writeConcern = Object.assign({}, session.transaction.options.writeConcern); + } + else if (session.clientOptions && session.clientOptions.writeConcern) { + writeConcern = { w: session.clientOptions.writeConcern.w }; + } + if (txnState === transactions_1.TxnState.TRANSACTION_COMMITTED) { + writeConcern = Object.assign({ wtimeout: 10000 }, writeConcern, { w: 'majority' }); + } + if (writeConcern) { + Object.assign(command, { writeConcern }); + } + if (commandName === 'commitTransaction' && session.transaction.options.maxTimeMS) { + Object.assign(command, { maxTimeMS: session.transaction.options.maxTimeMS }); + } + function commandHandler(error, result) { + if (commandName !== 'commitTransaction') { + session.transaction.transition(transactions_1.TxnState.TRANSACTION_ABORTED); + if (session.loadBalanced) { + maybeClearPinnedConnection(session, { force: false }); + } + // The spec indicates that we should ignore all errors on `abortTransaction` + return callback(); + } + session.transaction.transition(transactions_1.TxnState.TRANSACTION_COMMITTED); + if (error instanceof error_1.MongoError) { + if (error.hasErrorLabel(error_1.MongoErrorLabel.RetryableWriteError) || + error instanceof error_1.MongoWriteConcernError || + isMaxTimeMSExpiredError(error)) { + if (isUnknownTransactionCommitResult(error)) { + error.addErrorLabel(error_1.MongoErrorLabel.UnknownTransactionCommitResult); + // per txns spec, must unpin session in this case + session.unpin({ error }); + } + } + else if (error.hasErrorLabel(error_1.MongoErrorLabel.TransientTransactionError)) { + session.unpin({ error }); + } + } + callback(error, result); + } + if (session.transaction.recoveryToken) { + command.recoveryToken = session.transaction.recoveryToken; + } + // send the command + (0, execute_operation_1.executeOperation)(session.client, new run_command_1.RunAdminCommandOperation(undefined, command, { + session, + readPreference: read_preference_1.ReadPreference.primary, + bypassPinningCheck: true + }), (error, result) => { + if (command.abortTransaction) { + // always unpin on abort regardless of command outcome + session.unpin(); + } + if (error instanceof error_1.MongoError && error.hasErrorLabel(error_1.MongoErrorLabel.RetryableWriteError)) { + // SPEC-1185: apply majority write concern when retrying commitTransaction + if (command.commitTransaction) { + // per txns spec, must unpin session in this case + session.unpin({ force: true }); + command.writeConcern = Object.assign({ wtimeout: 10000 }, command.writeConcern, { + w: 'majority' + }); + } + return (0, execute_operation_1.executeOperation)(session.client, new run_command_1.RunAdminCommandOperation(undefined, command, { + session, + readPreference: read_preference_1.ReadPreference.primary, + bypassPinningCheck: true + }), commandHandler); + } + commandHandler(error, result); + }); +} +/** + * Reflects the existence of a session on the server. Can be reused by the session pool. + * WARNING: not meant to be instantiated directly. For internal use only. + * @public + */ +class ServerSession { + /** @internal */ + constructor() { + this.id = { id: new bson_1.Binary((0, utils_1.uuidV4)(), bson_1.Binary.SUBTYPE_UUID) }; + this.lastUse = (0, utils_1.now)(); + this.txnNumber = 0; + this.isDirty = false; + } + /** + * Determines if the server session has timed out. + * + * @param sessionTimeoutMinutes - The server's "logicalSessionTimeoutMinutes" + */ + hasTimedOut(sessionTimeoutMinutes) { + // Take the difference of the lastUse timestamp and now, which will result in a value in + // milliseconds, and then convert milliseconds to minutes to compare to `sessionTimeoutMinutes` + const idleTimeMinutes = Math.round((((0, utils_1.calculateDurationInMs)(this.lastUse) % 86400000) % 3600000) / 60000); + return idleTimeMinutes > sessionTimeoutMinutes - 1; + } + /** + * @internal + * Cloning meant to keep a readable reference to the server session data + * after ClientSession has ended + */ + static clone(serverSession) { + const arrayBuffer = new ArrayBuffer(16); + const idBytes = Buffer.from(arrayBuffer); + idBytes.set(serverSession.id.id.buffer); + const id = new bson_1.Binary(idBytes, serverSession.id.id.sub_type); + // Manual prototype construction to avoid modifying the constructor of this class + return Object.setPrototypeOf({ + id: { id }, + lastUse: serverSession.lastUse, + txnNumber: serverSession.txnNumber, + isDirty: serverSession.isDirty + }, ServerSession.prototype); + } +} +exports.ServerSession = ServerSession; +/** + * Maintains a pool of Server Sessions. + * For internal use only + * @internal + */ +class ServerSessionPool { + constructor(client) { + if (client == null) { + throw new error_1.MongoRuntimeError('ServerSessionPool requires a MongoClient'); + } + this.client = client; + this.sessions = []; + } + /** + * Acquire a Server Session from the pool. + * Iterates through each session in the pool, removing any stale sessions + * along the way. The first non-stale session found is removed from the + * pool and returned. If no non-stale session is found, a new ServerSession is created. + */ + acquire() { + var _b, _c, _d; + const sessionTimeoutMinutes = (_c = (_b = this.client.topology) === null || _b === void 0 ? void 0 : _b.logicalSessionTimeoutMinutes) !== null && _c !== void 0 ? _c : 10; + let session = null; + // Try to obtain from session pool + while (this.sessions.length > 0) { + const potentialSession = this.sessions.shift(); + if (potentialSession != null && + (!!((_d = this.client.topology) === null || _d === void 0 ? void 0 : _d.loadBalanced) || + !potentialSession.hasTimedOut(sessionTimeoutMinutes))) { + session = potentialSession; + break; + } + } + // If nothing valid came from the pool make a new one + if (session == null) { + session = new ServerSession(); + } + return session; + } + /** + * Release a session to the session pool + * Adds the session back to the session pool if the session has not timed out yet. + * This method also removes any stale sessions from the pool. + * + * @param session - The session to release to the pool + */ + release(session) { + var _b, _c, _d; + const sessionTimeoutMinutes = (_c = (_b = this.client.topology) === null || _b === void 0 ? void 0 : _b.logicalSessionTimeoutMinutes) !== null && _c !== void 0 ? _c : 10; + if (((_d = this.client.topology) === null || _d === void 0 ? void 0 : _d.loadBalanced) && !sessionTimeoutMinutes) { + this.sessions.unshift(session); + } + if (!sessionTimeoutMinutes) { + return; + } + while (this.sessions.length) { + const pooledSession = this.sessions[this.sessions.length - 1]; + if (pooledSession.hasTimedOut(sessionTimeoutMinutes)) { + this.sessions.pop(); + } + else { + break; + } + } + if (!session.hasTimedOut(sessionTimeoutMinutes)) { + if (session.isDirty) { + return; + } + // otherwise, readd this session to the session pool + this.sessions.unshift(session); + } + } +} +exports.ServerSessionPool = ServerSessionPool; +/** + * Optionally decorate a command with sessions specific keys + * + * @param session - the session tracking transaction state + * @param command - the command to decorate + * @param options - Optional settings passed to calling operation + * + * @internal + */ +function applySession(session, command, options) { + var _b, _c; + if (session.hasEnded) { + return new error_1.MongoExpiredSessionError(); + } + // May acquire serverSession here + const serverSession = session.serverSession; + if (serverSession == null) { + return new error_1.MongoRuntimeError('Unable to acquire server session'); + } + if (((_b = options.writeConcern) === null || _b === void 0 ? void 0 : _b.w) === 0) { + if (session && session.explicit) { + // Error if user provided an explicit session to an unacknowledged write (SPEC-1019) + return new error_1.MongoAPIError('Cannot have explicit session with unacknowledged writes'); + } + return; + } + // mark the last use of this session, and apply the `lsid` + serverSession.lastUse = (0, utils_1.now)(); + command.lsid = serverSession.id; + const inTxnOrTxnCommand = session.inTransaction() || (0, transactions_1.isTransactionCommand)(command); + const isRetryableWrite = !!options.willRetryWrite; + if (isRetryableWrite || inTxnOrTxnCommand) { + serverSession.txnNumber += session[kTxnNumberIncrement]; + session[kTxnNumberIncrement] = 0; + command.txnNumber = bson_1.Long.fromNumber(serverSession.txnNumber); + } + if (!inTxnOrTxnCommand) { + if (session.transaction.state !== transactions_1.TxnState.NO_TRANSACTION) { + session.transaction.transition(transactions_1.TxnState.NO_TRANSACTION); + } + if (session.supports.causalConsistency && + session.operationTime && + (0, utils_1.commandSupportsReadConcern)(command, options)) { + command.readConcern = command.readConcern || {}; + Object.assign(command.readConcern, { afterClusterTime: session.operationTime }); + } + else if (session[kSnapshotEnabled]) { + command.readConcern = command.readConcern || { level: read_concern_1.ReadConcernLevel.snapshot }; + if (session[kSnapshotTime] != null) { + Object.assign(command.readConcern, { atClusterTime: session[kSnapshotTime] }); + } + } + return; + } + // now attempt to apply transaction-specific sessions data + // `autocommit` must always be false to differentiate from retryable writes + command.autocommit = false; + if (session.transaction.state === transactions_1.TxnState.STARTING_TRANSACTION) { + session.transaction.transition(transactions_1.TxnState.TRANSACTION_IN_PROGRESS); + command.startTransaction = true; + const readConcern = session.transaction.options.readConcern || ((_c = session === null || session === void 0 ? void 0 : session.clientOptions) === null || _c === void 0 ? void 0 : _c.readConcern); + if (readConcern) { + command.readConcern = readConcern; + } + if (session.supports.causalConsistency && session.operationTime) { + command.readConcern = command.readConcern || {}; + Object.assign(command.readConcern, { afterClusterTime: session.operationTime }); + } + } + return; +} +exports.applySession = applySession; +function updateSessionFromResponse(session, document) { + var _b; + if (document.$clusterTime) { + (0, common_1._advanceClusterTime)(session, document.$clusterTime); + } + if (document.operationTime && session && session.supports.causalConsistency) { + session.advanceOperationTime(document.operationTime); + } + if (document.recoveryToken && session && session.inTransaction()) { + session.transaction._recoveryToken = document.recoveryToken; + } + if ((session === null || session === void 0 ? void 0 : session[kSnapshotEnabled]) && session[kSnapshotTime] == null) { + // find and aggregate commands return atClusterTime on the cursor + // distinct includes it in the response body + const atClusterTime = ((_b = document.cursor) === null || _b === void 0 ? void 0 : _b.atClusterTime) || document.atClusterTime; + if (atClusterTime) { + session[kSnapshotTime] = atClusterTime; + } + } +} +exports.updateSessionFromResponse = updateSessionFromResponse; +//# sourceMappingURL=sessions.js.map \ No newline at end of file diff --git a/ts-ticket-office-service/node_modules/mongodb/lib/sessions.js.map b/ts-ticket-office-service/node_modules/mongodb/lib/sessions.js.map new file mode 100644 index 000000000..66b234ef2 --- /dev/null +++ b/ts-ticket-office-service/node_modules/mongodb/lib/sessions.js.map @@ -0,0 +1 @@ +{"version":3,"file":"sessions.js","sourceRoot":"","sources":["../src/sessions.ts"],"names":[],"mappings":";;;;AAAA,iCAA2D;AAE3D,4CAAuD;AACvD,wDAAwD;AACxD,2CAA+C;AAE/C,mCAciB;AAEjB,+CAAkD;AAClD,sEAAkE;AAClE,0DAAoE;AACpE,yDAAqD;AACrD,iDAAkD;AAClD,uDAAmD;AACnD,0CAA+E;AAC/E,iDAAiG;AACjG,mCASiB;AAEjB,MAAM,oCAAoC,GAAG,CAAC,CAAC;AA2B/C,gBAAgB;AAChB,MAAM,cAAc,GAAG,MAAM,CAAC,eAAe,CAAC,CAAC;AAC/C,gBAAgB;AAChB,MAAM,aAAa,GAAG,MAAM,CAAC,cAAc,CAAC,CAAC;AAC7C,gBAAgB;AAChB,MAAM,gBAAgB,GAAG,MAAM,CAAC,iBAAiB,CAAC,CAAC;AACnD,gBAAgB;AAChB,MAAM,iBAAiB,GAAG,MAAM,CAAC,kBAAkB,CAAC,CAAC;AACrD,4GAA4G;AAC5G,MAAM,mBAAmB,GAAG,MAAM,CAAC,oBAAoB,CAAC,CAAC;AAazD;;;;;GAKG;AACH,MAAa,aAAc,SAAQ,+BAAsC;IA0BvE;;;;;;;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C7D;IAED,IAAI,CAAA,OAAO,aAAP,OAAO,uBAAP,OAAO,CAAG,gBAAgB,CAAC,KAAI,OAAO,CAAC,aAAa,CAAC,IAAI,IAAI,EAAE;QACjE,iEAAiE;QACjE,4CAA4C;QAC5C,MAAM,aAAa,GAAG,CAAA,MAAA,QAAQ,CAAC,MAAM,0CAAE,aAAa,KAAI,QAAQ,CAAC,aAAa,CAAC;QAC/E,IAAI,aAAa,EAAE;YACjB,OAAO,CAAC,aAAa,CAAC,GAAG,aAAa,CAAC;SACxC;KACF;AACH,CAAC;AArBD,8DAqBC"} \ No newline at end of file diff --git a/ts-ticket-office-service/node_modules/mongodb/lib/sort.js b/ts-ticket-office-service/node_modules/mongodb/lib/sort.js new file mode 100644 index 000000000..c04b6b54c --- /dev/null +++ b/ts-ticket-office-service/node_modules/mongodb/lib/sort.js @@ -0,0 +1,97 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.formatSort = void 0; +const error_1 = require("./error"); +/** @internal */ +function prepareDirection(direction = 1) { + const value = `${direction}`.toLowerCase(); + if (isMeta(direction)) + return direction; + switch (value) { + case 'ascending': + case 'asc': + case '1': + return 1; + case 'descending': + case 'desc': + case '-1': + return -1; + default: + throw new error_1.MongoInvalidArgumentError(`Invalid sort direction: ${JSON.stringify(direction)}`); + } +} +/** @internal */ +function isMeta(t) { + return typeof t === 'object' && t != null && '$meta' in t && typeof t.$meta === 'string'; +} +/** @internal */ +function isPair(t) { + if (Array.isArray(t) && t.length === 2) { + try { + prepareDirection(t[1]); + return true; + } + catch (e) { + return false; + } + } + return false; +} +function isDeep(t) { + return Array.isArray(t) && Array.isArray(t[0]); +} +function isMap(t) { + return t instanceof Map && t.size > 0; +} +/** @internal */ +function pairToMap(v) { + return new Map([[`${v[0]}`, prepareDirection([v[1]])]]); +} +/** @internal */ +function deepToMap(t) { + const sortEntries = t.map(([k, v]) => [`${k}`, prepareDirection(v)]); + return new Map(sortEntries); +} +/** @internal */ +function stringsToMap(t) { + const sortEntries = t.map(key => [`${key}`, 1]); + return new Map(sortEntries); +} +/** @internal */ +function objectToMap(t) { + const sortEntries = Object.entries(t).map(([k, v]) => [ + `${k}`, + prepareDirection(v) + ]); + return new Map(sortEntries); +} +/** @internal */ +function mapToMap(t) { + const sortEntries = Array.from(t).map(([k, v]) => [ + `${k}`, + prepareDirection(v) + ]); + return new Map(sortEntries); +} +/** converts a Sort type into a type that is valid for the server (SortForCmd) */ +function formatSort(sort, direction) { + if (sort == null) + return undefined; + if (typeof sort === 'string') + return new Map([[sort, prepareDirection(direction)]]); + if (typeof sort !== 'object') { + throw new error_1.MongoInvalidArgumentError(`Invalid sort format: ${JSON.stringify(sort)} Sort must be a valid object`); + } + if (!Array.isArray(sort)) { + return isMap(sort) ? mapToMap(sort) : Object.keys(sort).length ? objectToMap(sort) : undefined; + } + if (!sort.length) + return undefined; + if (isDeep(sort)) + return deepToMap(sort); + if (isPair(sort)) + return pairToMap(sort); + return stringsToMap(sort); +} +exports.formatSort = formatSort; +//# sourceMappingURL=sort.js.map \ No newline at end of file diff --git a/ts-ticket-office-service/node_modules/mongodb/lib/sort.js.map b/ts-ticket-office-service/node_modules/mongodb/lib/sort.js.map new file mode 100644 index 000000000..4072af4c8 --- /dev/null +++ b/ts-ticket-office-service/node_modules/mongodb/lib/sort.js.map @@ -0,0 +1 @@ +{"version":3,"file":"sort.js","sourceRoot":"","sources":["../src/sort.ts"],"names":[],"mappings":";;;AAAA,mCAAoD;AAiCpD,gBAAgB;AAChB,SAAS,gBAAgB,CAAC,YAAiB,CAAC;IAC1C,MAAM,KAAK,GAAG,GAAG,SAAS,EAAE,CAAC,WAAW,EAAE,CAAC;IAC3C,IAAI,MAAM,CAAC,SAAS,CAAC;QAAE,OAAO,SAAS,CAAC;IACxC,QAAQ,KAAK,EAAE;QACb,KAAK,WAAW,CAAC;QACjB,KAAK,KAAK,CAAC;QACX,KAAK,GAAG;YACN,OAAO,CAAC,CAAC;QACX,KAAK,YAAY,CAAC;QA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AAO,IAAI,KAAK,QAAQ;QAAE,OAAO,IAAI,GAAG,CAAC,CAAC,CAAC,IAAI,EAAE,gBAAgB,CAAC,SAAS,CAAC,CAAC,CAAC,CAAC,CAAC;IACpF,IAAI,OAAO,IAAI,KAAK,QAAQ,EAAE;QAC5B,MAAM,IAAI,iCAAyB,CACjC,wBAAwB,IAAI,CAAC,SAAS,CAAC,IAAI,CAAC,8BAA8B,CAC3E,CAAC;KACH;IACD,IAAI,CAAC,KAAK,CAAC,OAAO,CAAC,IAAI,CAAC,EAAE;QACxB,OAAO,KAAK,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC,QAAQ,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC,MAAM,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC,MAAM,CAAC,CAAC,CAAC,WAAW,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC,SAAS,CAAC;KAChG;IACD,IAAI,CAAC,IAAI,CAAC,MAAM;QAAE,OAAO,SAAS,CAAC;IACnC,IAAI,MAAM,CAAC,IAAI,CAAC;QAAE,OAAO,SAAS,CAAC,IAAI,CAAC,CAAC;IACzC,IAAI,MAAM,CAAC,IAAI,CAAC;QAAE,OAAO,SAAS,CAAC,IAAI,CAAC,CAAC;IACzC,OAAO,YAAY,CAAC,IAAI,CAAC,CAAC;AAC5B,CAAC;AAlBD,gCAkBC"} \ No newline at end of file diff --git a/ts-ticket-office-service/node_modules/mongodb/lib/topology_base.js b/ts-ticket-office-service/node_modules/mongodb/lib/topology_base.js deleted file mode 100644 index ebfd616e9..000000000 --- a/ts-ticket-office-service/node_modules/mongodb/lib/topology_base.js +++ /dev/null @@ -1,191 +0,0 @@ -"use strict"; - -var MongoError = require('mongodb-core').MongoError - , f = require('util').format; - -// The store of ops -var Store = function(topology, storeOptions) { - var self = this; - var storedOps = []; - storeOptions = storeOptions || {force:false, bufferMaxEntries: -1} - - // Internal state - this.s = { - storedOps: storedOps - , storeOptions: storeOptions - , topology: topology - } - - Object.defineProperty(this, 'length', { - enumerable:true, get: function() { return self.s.storedOps.length; } - }); -} - -Store.prototype.add = function(opType, ns, ops, options, callback) { - if(this.s.storeOptions.force) { - return callback(MongoError.create({message: "db closed by application", driver:true})); - } - - if(this.s.storeOptions.bufferMaxEntries == 0) { - return callback(MongoError.create({message: f("no connection available for operation and number of stored operation > %s", this.s.storeOptions.bufferMaxEntries), driver:true })); - } - - if(this.s.storeOptions.bufferMaxEntries > 0 && this.s.storedOps.length > this.s.storeOptions.bufferMaxEntries) { - while(this.s.storedOps.length > 0) { - var op = this.s.storedOps.shift(); - op.c(MongoError.create({message: f("no connection available for operation and number of stored operation > %s", this.s.storeOptions.bufferMaxEntries), driver:true })); - } - - return; - } - - this.s.storedOps.push({t: opType, n: ns, o: ops, op: options, c: callback}) -} - -Store.prototype.addObjectAndMethod = function(opType, object, method, params, callback) { - if(this.s.storeOptions.force) { - return callback(MongoError.create({message: "db closed by application", driver:true })); - } - - if(this.s.storeOptions.bufferMaxEntries == 0) { - return callback(MongoError.create({message: f("no connection available for operation and number of stored operation > %s", this.s.storeOptions.bufferMaxEntries), driver:true })); - } - - if(this.s.storeOptions.bufferMaxEntries > 0 && this.s.storedOps.length > this.s.storeOptions.bufferMaxEntries) { - while(this.s.storedOps.length > 0) { - var op = this.s.storedOps.shift(); - op.c(MongoError.create({message: f("no connection available for operation and number of stored operation > %s", this.s.storeOptions.bufferMaxEntries), driver:true })); - } - - return; - } - - this.s.storedOps.push({t: opType, m: method, o: object, p: params, c: callback}) -} - -Store.prototype.flush = function(err) { - while(this.s.storedOps.length > 0) { - this.s.storedOps.shift().c(err || MongoError.create({message: f("no connection available for operation"), driver:true })); - } -} - -var primaryOptions = ['primary', 'primaryPreferred', 'nearest', 'secondaryPreferred']; -var secondaryOptions = ['secondary', 'secondaryPreferred']; - -Store.prototype.execute = function(options) { - options = options || {}; - // Get current ops - var ops = this.s.storedOps; - // Reset the ops - this.s.storedOps = []; - - // Unpack options - var executePrimary = typeof options.executePrimary === 'boolean' - ? options.executePrimary : true; - var executeSecondary = typeof options.executeSecondary === 'boolean' - ? options.executeSecondary : true; - - // Execute all the stored ops - while(ops.length > 0) { - var op = ops.shift(); - - if(op.t == 'cursor') { - if(executePrimary && executeSecondary) { - op.o[op.m].apply(op.o, op.p); - } else if(executePrimary && op.o.options - && op.o.options.readPreference - && primaryOptions.indexOf(op.o.options.readPreference.mode) != -1) { - op.o[op.m].apply(op.o, op.p); - } else if(!executePrimary && executeSecondary && op.o.options - && op.o.options.readPreference - && secondaryOptions.indexOf(op.o.options.readPreference.mode) != -1) { - op.o[op.m].apply(op.o, op.p); - } - } else if(op.t == 'auth') { - this.s.topology[op.t].apply(this.s.topology, op.o); - } else { - if(executePrimary && executeSecondary) { - this.s.topology[op.t](op.n, op.o, op.op, op.c); - } else if(executePrimary && op.op && op.op.readPreference - && primaryOptions.indexOf(op.op.readPreference.mode) != -1) { - this.s.topology[op.t](op.n, op.o, op.op, op.c); - } else if(!executePrimary && executeSecondary && op.op && op.op.readPreference - && secondaryOptions.indexOf(op.op.readPreference.mode) != -1) { - this.s.topology[op.t](op.n, op.o, op.op, op.c); - } - } - } -} - -Store.prototype.all = function() { - return this.s.storedOps; -} - -// Server capabilities -var ServerCapabilities = function(ismaster) { - var setup_get_property = function(object, name, value) { - Object.defineProperty(object, name, { - enumerable: true - , get: function () { return value; } - }); - } - - // Capabilities - var aggregationCursor = false; - var writeCommands = false; - var textSearch = false; - var authCommands = false; - var listCollections = false; - var listIndexes = false; - var maxNumberOfDocsInBatch = ismaster.maxWriteBatchSize || 1000; - var commandsTakeWriteConcern = false; - var commandsTakeCollation = false; - - if(ismaster.minWireVersion >= 0) { - textSearch = true; - } - - if(ismaster.maxWireVersion >= 1) { - aggregationCursor = true; - authCommands = true; - } - - if(ismaster.maxWireVersion >= 2) { - writeCommands = true; - } - - if(ismaster.maxWireVersion >= 3) { - listCollections = true; - listIndexes = true; - } - - if(ismaster.maxWireVersion >= 5) { - commandsTakeWriteConcern = true; - commandsTakeCollation = true; - } - - // If no min or max wire version set to 0 - if(ismaster.minWireVersion == null) { - ismaster.minWireVersion = 0; - } - - if(ismaster.maxWireVersion == null) { - ismaster.maxWireVersion = 0; - } - - // Map up read only parameters - setup_get_property(this, "hasAggregationCursor", aggregationCursor); - setup_get_property(this, "hasWriteCommands", writeCommands); - setup_get_property(this, "hasTextSearch", textSearch); - setup_get_property(this, "hasAuthCommands", authCommands); - setup_get_property(this, "hasListCollectionsCommand", listCollections); - setup_get_property(this, "hasListIndexesCommand", listIndexes); - setup_get_property(this, "minWireVersion", ismaster.minWireVersion); - setup_get_property(this, "maxWireVersion", ismaster.maxWireVersion); - setup_get_property(this, "maxNumberOfDocsInBatch", maxNumberOfDocsInBatch); - setup_get_property(this, "commandsTakeWriteConcern", commandsTakeWriteConcern); - setup_get_property(this, "commandsTakeCollation", commandsTakeCollation); -} - -exports.Store = Store; -exports.ServerCapabilities = ServerCapabilities; diff --git a/ts-ticket-office-service/node_modules/mongodb/lib/transactions.js b/ts-ticket-office-service/node_modules/mongodb/lib/transactions.js new file mode 100644 index 000000000..4982eb449 --- /dev/null +++ b/ts-ticket-office-service/node_modules/mongodb/lib/transactions.js @@ -0,0 +1,138 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.isTransactionCommand = exports.Transaction = exports.TxnState = void 0; +const error_1 = require("./error"); +const read_concern_1 = require("./read_concern"); +const read_preference_1 = require("./read_preference"); +const write_concern_1 = require("./write_concern"); +/** @internal */ +exports.TxnState = Object.freeze({ + NO_TRANSACTION: 'NO_TRANSACTION', + STARTING_TRANSACTION: 'STARTING_TRANSACTION', + TRANSACTION_IN_PROGRESS: 'TRANSACTION_IN_PROGRESS', + TRANSACTION_COMMITTED: 'TRANSACTION_COMMITTED', + TRANSACTION_COMMITTED_EMPTY: 'TRANSACTION_COMMITTED_EMPTY', + TRANSACTION_ABORTED: 'TRANSACTION_ABORTED' +}); +const stateMachine = { + [exports.TxnState.NO_TRANSACTION]: [exports.TxnState.NO_TRANSACTION, exports.TxnState.STARTING_TRANSACTION], + [exports.TxnState.STARTING_TRANSACTION]: [ + exports.TxnState.TRANSACTION_IN_PROGRESS, + exports.TxnState.TRANSACTION_COMMITTED, + exports.TxnState.TRANSACTION_COMMITTED_EMPTY, + exports.TxnState.TRANSACTION_ABORTED + ], + [exports.TxnState.TRANSACTION_IN_PROGRESS]: [ + exports.TxnState.TRANSACTION_IN_PROGRESS, + exports.TxnState.TRANSACTION_COMMITTED, + exports.TxnState.TRANSACTION_ABORTED + ], + [exports.TxnState.TRANSACTION_COMMITTED]: [ + exports.TxnState.TRANSACTION_COMMITTED, + exports.TxnState.TRANSACTION_COMMITTED_EMPTY, + exports.TxnState.STARTING_TRANSACTION, + exports.TxnState.NO_TRANSACTION + ], + [exports.TxnState.TRANSACTION_ABORTED]: [exports.TxnState.STARTING_TRANSACTION, exports.TxnState.NO_TRANSACTION], + [exports.TxnState.TRANSACTION_COMMITTED_EMPTY]: [ + exports.TxnState.TRANSACTION_COMMITTED_EMPTY, + exports.TxnState.NO_TRANSACTION + ] +}; +const ACTIVE_STATES = new Set([ + exports.TxnState.STARTING_TRANSACTION, + exports.TxnState.TRANSACTION_IN_PROGRESS +]); +const COMMITTED_STATES = new Set([ + exports.TxnState.TRANSACTION_COMMITTED, + exports.TxnState.TRANSACTION_COMMITTED_EMPTY, + exports.TxnState.TRANSACTION_ABORTED +]); +/** + * @public + * A class maintaining state related to a server transaction. Internal Only + */ +class Transaction { + /** Create a transaction @internal */ + constructor(options) { + options = options !== null && options !== void 0 ? options : {}; + this.state = exports.TxnState.NO_TRANSACTION; + this.options = {}; + const writeConcern = write_concern_1.WriteConcern.fromOptions(options); + if (writeConcern) { + if (writeConcern.w === 0) { + throw new error_1.MongoTransactionError('Transactions do not support unacknowledged write concern'); + } + this.options.writeConcern = writeConcern; + } + if (options.readConcern) { + this.options.readConcern = read_concern_1.ReadConcern.fromOptions(options); + } + if (options.readPreference) { + this.options.readPreference = read_preference_1.ReadPreference.fromOptions(options); + } + if (options.maxCommitTimeMS) { + this.options.maxTimeMS = options.maxCommitTimeMS; + } + // TODO: This isn't technically necessary + this._pinnedServer = undefined; + this._recoveryToken = undefined; + } + /** @internal */ + get server() { + return this._pinnedServer; + } + get recoveryToken() { + return this._recoveryToken; + } + get isPinned() { + return !!this.server; + } + /** @returns Whether the transaction has started */ + get isStarting() { + return this.state === exports.TxnState.STARTING_TRANSACTION; + } + /** + * @returns Whether this session is presently in a transaction + */ + get isActive() { + return ACTIVE_STATES.has(this.state); + } + get isCommitted() { + return COMMITTED_STATES.has(this.state); + } + /** + * Transition the transaction in the state machine + * @internal + * @param nextState - The new state to transition to + */ + transition(nextState) { + const nextStates = stateMachine[this.state]; + if (nextStates && nextStates.includes(nextState)) { + this.state = nextState; + if (this.state === exports.TxnState.NO_TRANSACTION || + this.state === exports.TxnState.STARTING_TRANSACTION || + this.state === exports.TxnState.TRANSACTION_ABORTED) { + this.unpinServer(); + } + return; + } + throw new error_1.MongoRuntimeError(`Attempted illegal state transition from [${this.state}] to [${nextState}]`); + } + /** @internal */ + pinServer(server) { + if (this.isActive) { + this._pinnedServer = server; + } + } + /** @internal */ + unpinServer() { + this._pinnedServer = undefined; + } +} +exports.Transaction = Transaction; +function isTransactionCommand(command) { + return !!(command.commitTransaction || command.abortTransaction); +} +exports.isTransactionCommand = isTransactionCommand; +//# sourceMappingURL=transactions.js.map \ No newline at end of file diff --git a/ts-ticket-office-service/node_modules/mongodb/lib/transactions.js.map b/ts-ticket-office-service/node_modules/mongodb/lib/transactions.js.map new file mode 100644 index 000000000..5e261e908 --- /dev/null +++ b/ts-ticket-office-service/node_modules/mongodb/lib/transactions.js.map @@ -0,0 +1 @@ +{"version":3,"file":"transactions.js","sourceRoot":"","sources":["../src/transactions.ts"],"names":[],"mappings":";;;AACA,mCAAmE;AAEnE,iDAA8D;AAC9D,uDAAmD;AAEnD,mDAA+C;AAE/C,gBAAgB;AACH,QAAA,QAAQ,GAAG,MAAM,CAA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O,CAAC,gBAAgB,CAAC,CAAC;AACnE,CAAC;AAFD,oDAEC"} \ No newline at end of file diff --git a/ts-ticket-office-service/node_modules/mongodb/lib/url_parser.js b/ts-ticket-office-service/node_modules/mongodb/lib/url_parser.js deleted file mode 100644 index 8362ac13a..000000000 --- a/ts-ticket-office-service/node_modules/mongodb/lib/url_parser.js +++ /dev/null @@ -1,412 +0,0 @@ -"use strict"; - -var ReadPreference = require('./read_preference'), - parser = require('url'), - f = require('util').format, - assign = require('./utils').assign; - -module.exports = function(url, options) { - // Variables - var connection_part = ''; - var auth_part = ''; - var query_string_part = ''; - var dbName = 'admin'; - - // Url parser result - var result = parser.parse(url, true); - - if(result.protocol != 'mongodb:') { - throw new Error('invalid schema, expected mongodb'); - } - - if((result.hostname == null || result.hostname == '') && url.indexOf('.sock') == -1) { - throw new Error('no hostname or hostnames provided in connection string'); - } - - if(result.port == '0') { - throw new Error('invalid port (zero) with hostname'); - } - - if(!isNaN(parseInt(result.port, 10)) && parseInt(result.port, 10) > 65535) { - throw new Error('invalid port (larger than 65535) with hostname'); - } - - if(result.path - && result.path.length > 0 - && result.path[0] != '/' - && url.indexOf('.sock') == -1) { - throw new Error('missing delimiting slash between hosts and options'); - } - - if(result.query) { - for(var name in result.query) { - if(name.indexOf('::') != -1) { - throw new Error('double colon in host identifier'); - } - - if(result.query[name] == '') { - throw new Error('query parameter ' + name + ' is an incomplete value pair'); - } - } - } - - if(result.auth) { - var parts = result.auth.split(':'); - if(url.indexOf(result.auth) != -1 && parts.length > 2) { - throw new Error('Username with password containing an unescaped colon'); - } - - if(url.indexOf(result.auth) != -1 && result.auth.indexOf('@') != -1) { - throw new Error('Username containing an unescaped at-sign'); - } - } - - // Remove query - var clean = url.split('?').shift(); - - // Extract the list of hosts - var strings = clean.split(','); - var hosts = []; - - for(var i = 0; i < strings.length; i++) { - var hostString = strings[i]; - - if(hostString.indexOf('mongodb') != -1) { - if(hostString.indexOf('@') != -1) { - hosts.push(hostString.split('@').pop()) - } else { - hosts.push(hostString.substr('mongodb://'.length)); - } - } else if(hostString.indexOf('/') != -1) { - hosts.push(hostString.split('/').shift()); - } else if(hostString.indexOf('/') == -1) { - hosts.push(hostString.trim()); - } - } - - for(i = 0; i < hosts.length; i++) { - var r = parser.parse(f('mongodb://%s', hosts[i].trim())); - if(r.path && r.path.indexOf(':') != -1) { - throw new Error('double colon in host identifier'); - } - } - - // If we have a ? mark cut the query elements off - if(url.indexOf("?") != -1) { - query_string_part = url.substr(url.indexOf("?") + 1); - connection_part = url.substring("mongodb://".length, url.indexOf("?")) - } else { - connection_part = url.substring("mongodb://".length); - } - - // Check if we have auth params - if(connection_part.indexOf("@") != -1) { - auth_part = connection_part.split("@")[0]; - connection_part = connection_part.split("@")[1]; - } - - // Check if the connection string has a db - if(connection_part.indexOf(".sock") != -1) { - if(connection_part.indexOf(".sock/") != -1) { - dbName = connection_part.split(".sock/")[1]; - // Check if multiple database names provided, or just an illegal trailing backslash - if (dbName.indexOf("/") != -1) { - if (dbName.split("/").length == 2 && dbName.split("/")[1].length == 0) { - throw new Error('Illegal trailing backslash after database name'); - } - throw new Error('More than 1 database name in URL'); - } - connection_part = connection_part.split("/", connection_part.indexOf(".sock") + ".sock".length); - } - } else if(connection_part.indexOf("/") != -1) { - // Check if multiple database names provided, or just an illegal trailing backslash - if (connection_part.split("/").length > 2) { - if (connection_part.split("/")[2].length == 0) { - throw new Error('Illegal trailing backslash after database name'); - } - throw new Error('More than 1 database name in URL'); - } - dbName = connection_part.split("/")[1]; - connection_part = connection_part.split("/")[0]; - } - - // Result object - var object = {}; - - // Pick apart the authentication part of the string - var authPart = auth_part || ''; - var auth = authPart.split(':', 2); - - // Decode the URI components - auth[0] = decodeURIComponent(auth[0]); - if(auth[1]){ - auth[1] = decodeURIComponent(auth[1]); - } - - // Add auth to final object if we have 2 elements - if(auth.length == 2) object.auth = {user: auth[0], password: auth[1]}; - // if user provided auth options, use that - if(options && options.auth != null) object.auth = options.auth; - - // Variables used for temporary storage - var hostPart; - var urlOptions; - var servers; - var serverOptions = {socketOptions: {}}; - var dbOptions = {read_preference_tags: []}; - var replSetServersOptions = {socketOptions: {}}; - var mongosOptions = {socketOptions: {}}; - // Add server options to final object - object.server_options = serverOptions; - object.db_options = dbOptions; - object.rs_options = replSetServersOptions; - object.mongos_options = mongosOptions; - - // Let's check if we are using a entity socket - if(url.match(/\.sock/)) { - // Split out the socket part - var domainSocket = url.substring( - url.indexOf("mongodb://") + "mongodb://".length - , url.lastIndexOf(".sock") + ".sock".length); - // Clean out any auth stuff if any - if(domainSocket.indexOf("@") != -1) domainSocket = domainSocket.split("@")[1]; - servers = [{domain_socket: domainSocket}]; - } else { - // Split up the db - hostPart = connection_part; - // Deduplicate servers - var deduplicatedServers = {}; - - // Parse all server results - servers = hostPart.split(',').map(function(h) { - var _host, _port, ipv6match; - //check if it matches [IPv6]:port, where the port number is optional - if ((ipv6match = /\[([^\]]+)\](?:\:(.+))?/.exec(h))) { - _host = ipv6match[1]; - _port = parseInt(ipv6match[2], 10) || 27017; - } else { - //otherwise assume it's IPv4, or plain hostname - var hostPort = h.split(':', 2); - _host = hostPort[0] || 'localhost'; - _port = hostPort[1] != null ? parseInt(hostPort[1], 10) : 27017; - // Check for localhost?safe=true style case - if(_host.indexOf("?") != -1) _host = _host.split(/\?/)[0]; - } - - // No entry returned for duplicate server - if(deduplicatedServers[_host + "_" + _port]) return null; - deduplicatedServers[_host + "_" + _port] = 1; - - // Return the mapped object - return {host: _host, port: _port}; - }).filter(function(x) { - return x != null; - }); - } - - // Get the db name - object.dbName = dbName || 'admin'; - // Split up all the options - urlOptions = (query_string_part || '').split(/[&;]/); - // Ugh, we have to figure out which options go to which constructor manually. - urlOptions.forEach(function(opt) { - if(!opt) return; - var splitOpt = opt.split('='), name = splitOpt[0], value = splitOpt[1]; - // Options implementations - switch(name) { - case 'slaveOk': - case 'slave_ok': - serverOptions.slave_ok = (value == 'true'); - dbOptions.slaveOk = (value == 'true'); - break; - case 'maxPoolSize': - case 'poolSize': - serverOptions.poolSize = parseInt(value, 10); - replSetServersOptions.poolSize = parseInt(value, 10); - break; - case 'appname': - object.appname = decodeURIComponent(value); - break; - case 'autoReconnect': - case 'auto_reconnect': - serverOptions.auto_reconnect = (value == 'true'); - break; - case 'minPoolSize': - throw new Error("minPoolSize not supported"); - case 'maxIdleTimeMS': - throw new Error("maxIdleTimeMS not supported"); - case 'waitQueueMultiple': - throw new Error("waitQueueMultiple not supported"); - case 'waitQueueTimeoutMS': - throw new Error("waitQueueTimeoutMS not supported"); - case 'uuidRepresentation': - throw new Error("uuidRepresentation not supported"); - case 'ssl': - if(value == 'prefer') { - serverOptions.ssl = value; - replSetServersOptions.ssl = value; - mongosOptions.ssl = value; - break; - } - serverOptions.ssl = (value == 'true'); - replSetServersOptions.ssl = (value == 'true'); - mongosOptions.ssl = (value == 'true'); - break; - case 'sslValidate': - serverOptions.sslValidate = (value == 'true'); - replSetServersOptions.sslValidate = (value == 'true'); - mongosOptions.sslValidate = (value == 'true'); - break; - case 'replicaSet': - case 'rs_name': - replSetServersOptions.rs_name = value; - break; - case 'reconnectWait': - replSetServersOptions.reconnectWait = parseInt(value, 10); - break; - case 'retries': - replSetServersOptions.retries = parseInt(value, 10); - break; - case 'readSecondary': - case 'read_secondary': - replSetServersOptions.read_secondary = (value == 'true'); - break; - case 'fsync': - dbOptions.fsync = (value == 'true'); - break; - case 'journal': - dbOptions.j = (value == 'true'); - break; - case 'safe': - dbOptions.safe = (value == 'true'); - break; - case 'nativeParser': - case 'native_parser': - dbOptions.native_parser = (value == 'true'); - break; - case 'readConcernLevel': - dbOptions.readConcern = {level: value}; - break; - case 'connectTimeoutMS': - serverOptions.socketOptions.connectTimeoutMS = parseInt(value, 10); - replSetServersOptions.socketOptions.connectTimeoutMS = parseInt(value, 10); - mongosOptions.socketOptions.connectTimeoutMS = parseInt(value, 10); - break; - case 'socketTimeoutMS': - serverOptions.socketOptions.socketTimeoutMS = parseInt(value, 10); - replSetServersOptions.socketOptions.socketTimeoutMS = parseInt(value, 10); - mongosOptions.socketOptions.socketTimeoutMS = parseInt(value, 10); - break; - case 'w': - dbOptions.w = parseInt(value, 10); - if(isNaN(dbOptions.w)) dbOptions.w = value; - break; - case 'authSource': - dbOptions.authSource = value; - break; - case 'gssapiServiceName': - dbOptions.gssapiServiceName = value; - break; - case 'authMechanism': - if(value == 'GSSAPI') { - // If no password provided decode only the principal - if(object.auth == null) { - var urlDecodeAuthPart = decodeURIComponent(authPart); - if(urlDecodeAuthPart.indexOf("@") == -1) throw new Error("GSSAPI requires a provided principal"); - object.auth = {user: urlDecodeAuthPart, password: null}; - } else { - object.auth.user = decodeURIComponent(object.auth.user); - } - } else if(value == 'MONGODB-X509') { - object.auth = {user: decodeURIComponent(authPart)}; - } - - // Only support GSSAPI or MONGODB-CR for now - if(value != 'GSSAPI' - && value != 'MONGODB-X509' - && value != 'MONGODB-CR' - && value != 'DEFAULT' - && value != 'SCRAM-SHA-1' - && value != 'PLAIN') - throw new Error("only DEFAULT, GSSAPI, PLAIN, MONGODB-X509, SCRAM-SHA-1 or MONGODB-CR is supported by authMechanism"); - - // Authentication mechanism - dbOptions.authMechanism = value; - break; - case 'authMechanismProperties': - // Split up into key, value pairs - var values = value.split(','); - var o = {}; - // For each value split into key, value - values.forEach(function(x) { - var v = x.split(':'); - o[v[0]] = v[1]; - }); - - // Set all authMechanismProperties - dbOptions.authMechanismProperties = o; - // Set the service name value - if(typeof o.SERVICE_NAME == 'string') dbOptions.gssapiServiceName = o.SERVICE_NAME; - if(typeof o.SERVICE_REALM == 'string') dbOptions.gssapiServiceRealm = o.SERVICE_REALM; - if(typeof o.CANONICALIZE_HOST_NAME == 'string') dbOptions.gssapiCanonicalizeHostName = o.CANONICALIZE_HOST_NAME == 'true' ? true : false; - break; - case 'wtimeoutMS': - dbOptions.wtimeout = parseInt(value, 10); - break; - case 'readPreference': - if(!ReadPreference.isValid(value)) throw new Error("readPreference must be either primary/primaryPreferred/secondary/secondaryPreferred/nearest"); - dbOptions.readPreference = value; - break; - case 'maxStalenessSeconds': - dbOptions.maxStalenessSeconds = parseInt(value, 10); - break; - case 'readPreferenceTags': - // Decode the value - value = decodeURIComponent(value); - // Contains the tag object - var tagObject = {}; - if(value == null || value == '') { - dbOptions.read_preference_tags.push(tagObject); - break; - } - - // Split up the tags - var tags = value.split(/\,/); - for(var i = 0; i < tags.length; i++) { - var parts = tags[i].trim().split(/\:/); - tagObject[parts[0]] = parts[1]; - } - - // Set the preferences tags - dbOptions.read_preference_tags.push(tagObject); - break; - default: - break; - } - }); - - // No tags: should be null (not []) - if(dbOptions.read_preference_tags.length === 0) { - dbOptions.read_preference_tags = null; - } - - // Validate if there are an invalid write concern combinations - if((dbOptions.w == -1 || dbOptions.w == 0) && ( - dbOptions.journal == true - || dbOptions.fsync == true - || dbOptions.safe == true)) throw new Error("w set to -1 or 0 cannot be combined with safe/w/journal/fsync") - - // If no read preference set it to primary - if(!dbOptions.readPreference) { - dbOptions.readPreference = 'primary'; - } - - // make sure that user-provided options are applied with priority - dbOptions = assign(dbOptions, options); - - // Add servers to result - object.servers = servers; - - // Returned parsed object - return object; -} diff --git a/ts-ticket-office-service/node_modules/mongodb/lib/utils.js b/ts-ticket-office-service/node_modules/mongodb/lib/utils.js index c4efe495b..db140246a 100644 --- a/ts-ticket-office-service/node_modules/mongodb/lib/utils.js +++ b/ts-ticket-office-service/node_modules/mongodb/lib/utils.js @@ -1,375 +1,1131 @@ "use strict"; - -var MongoError = require('mongodb-core').MongoError, - ReadPreference = require('./read_preference'), - CoreReadPreference = require('mongodb-core').ReadPreference; - -var shallowClone = function(obj) { - var copy = {}; - for(var name in obj) copy[name] = obj[name]; - return copy; -} - -// Figure out the read preference -var getReadPreference = function(options) { - var r = null - if(options.readPreference) { - r = options.readPreference - } else { - return options; - } - - if(r instanceof ReadPreference) { - options.readPreference = new CoreReadPreference(r.mode, r.tags, {maxStalenessSeconds: r.maxStalenessSeconds}); - } else if(typeof r == 'string') { - options.readPreference = new CoreReadPreference(r); - } else if(r && !(r instanceof ReadPreference) && typeof r == 'object') { - var mode = r.mode || r.preference; - if (mode && typeof mode == 'string') { - options.readPreference = new CoreReadPreference(mode, r.tags, {maxStalenessSeconds: r.maxStalenessSeconds}); - } - } - - return options; -} - -// Set simple property -var getSingleProperty = function(obj, name, value) { - Object.defineProperty(obj, name, { - enumerable:true, - get: function() { - return value - } - }); -} - -var formatSortValue = exports.formatSortValue = function(sortDirection) { - var value = ("" + sortDirection).toLowerCase(); - - switch (value) { - case 'ascending': - case 'asc': - case '1': - return 1; - case 'descending': - case 'desc': - case '-1': - return -1; - default: - throw new Error("Illegal sort clause, must be of the form " - + "[['field1', '(ascending|descending)'], " - + "['field2', '(ascending|descending)']]"); - } -}; - -var formattedOrderClause = exports.formattedOrderClause = function(sortValue) { - var orderBy = {}; - if(sortValue == null) return null; - if (Array.isArray(sortValue)) { - if(sortValue.length === 0) { - return null; - } - - for(var i = 0; i < sortValue.length; i++) { - if(sortValue[i].constructor == String) { - orderBy[sortValue[i]] = 1; - } else { - orderBy[sortValue[i][0]] = formatSortValue(sortValue[i][1]); - } - } - } else if(sortValue != null && typeof sortValue == 'object') { - orderBy = sortValue; - } else if (typeof sortValue == 'string') { - orderBy[sortValue] = 1; - } else { - throw new Error("Illegal sort clause, must be of the form " + - "[['field1', '(ascending|descending)'], ['field2', '(ascending|descending)']]"); - } - - return orderBy; -}; - -var checkCollectionName = function checkCollectionName (collectionName) { - if('string' !== typeof collectionName) { - throw new MongoError("collection name must be a String"); - } - - if(!collectionName || collectionName.indexOf('..') != -1) { - throw new MongoError("collection names cannot be empty"); - } - - if(collectionName.indexOf('$') != -1 && - collectionName.match(/((^\$cmd)|(oplog\.\$main))/) == null) { - throw new MongoError("collection names must not contain '$'"); - } - - if(collectionName.match(/^\.|\.$/) != null) { - throw new MongoError("collection names must not start or end with '.'"); - } - - // Validate that we are not passing 0x00 in the collection name - if(!!~collectionName.indexOf("\x00")) { - throw new MongoError("collection names cannot contain a null character"); - } -}; - -var handleCallback = function(callback, err, value1, value2) { - try { - if(callback == null) return; - if(callback) { - return value2 ? callback(err, value1, value2) : callback(err, value1); - } - } catch(err) { - process.nextTick(function() { throw err; }); - return false; - } - - return true; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.shuffle = exports.parsePackageVersion = exports.supportsRetryableWrites = exports.enumToString = exports.emitWarningOnce = exports.emitWarning = exports.MONGODB_WARNING_CODE = exports.DEFAULT_PK_FACTORY = exports.HostAddress = exports.BufferPool = exports.deepCopy = exports.isRecord = exports.setDifference = exports.isHello = exports.isSuperset = exports.resolveOptions = exports.hasAtomicOperators = exports.makeInterruptibleAsyncInterval = exports.calculateDurationInMs = exports.now = exports.makeClientMetadata = exports.makeStateMachine = exports.errorStrictEqual = exports.arrayStrictEqual = exports.eachAsyncSeries = exports.eachAsync = exports.collationNotSupported = exports.maxWireVersion = exports.uuidV4 = exports.databaseNamespace = exports.maybePromise = exports.makeCounter = exports.MongoDBNamespace = exports.ns = exports.deprecateOptions = exports.defaultMsgHandler = exports.getTopology = exports.decorateWithExplain = exports.decorateWithReadConcern = exports.decorateWithCollation = exports.isPromiseLike = exports.applyWriteConcern = exports.applyRetryableWrites = exports.filterOptions = exports.mergeOptions = exports.isObject = exports.parseIndexOptions = exports.normalizeHintField = exports.checkCollectionName = exports.MAX_JS_INT = void 0; +exports.getMongoDBClientEncryption = exports.commandSupportsReadConcern = void 0; +const crypto = require("crypto"); +const os = require("os"); +const timers_1 = require("timers"); +const url_1 = require("url"); +const bson_1 = require("./bson"); +const constants_1 = require("./cmap/wire_protocol/constants"); +const constants_2 = require("./constants"); +const error_1 = require("./error"); +const promise_provider_1 = require("./promise_provider"); +const read_concern_1 = require("./read_concern"); +const read_preference_1 = require("./read_preference"); +const common_1 = require("./sdam/common"); +const write_concern_1 = require("./write_concern"); +exports.MAX_JS_INT = Number.MAX_SAFE_INTEGER + 1; +/** + * Throws if collectionName is not a valid mongodb collection namespace. + * @internal + */ +function checkCollectionName(collectionName) { + if ('string' !== typeof collectionName) { + throw new error_1.MongoInvalidArgumentError('Collection name must be a String'); + } + if (!collectionName || collectionName.indexOf('..') !== -1) { + throw new error_1.MongoInvalidArgumentError('Collection names cannot be empty'); + } + if (collectionName.indexOf('$') !== -1 && + collectionName.match(/((^\$cmd)|(oplog\.\$main))/) == null) { + // TODO(NODE-3483): Use MongoNamespace static method + throw new error_1.MongoInvalidArgumentError("Collection names must not contain '$'"); + } + if (collectionName.match(/^\.|\.$/) != null) { + // TODO(NODE-3483): Use MongoNamespace static method + throw new error_1.MongoInvalidArgumentError("Collection names must not start or end with '.'"); + } + // Validate that we are not passing 0x00 in the collection name + if (collectionName.indexOf('\x00') !== -1) { + // TODO(NODE-3483): Use MongoNamespace static method + throw new error_1.MongoInvalidArgumentError('Collection names cannot contain a null character'); + } } - +exports.checkCollectionName = checkCollectionName; /** - * Wrap a Mongo error document in an Error instance - * @ignore - * @api private + * Ensure Hint field is in a shape we expect: + * - object of index names mapping to 1 or -1 + * - just an index name + * @internal */ -var toError = function(error) { - if (error instanceof Error) return error; - - var msg = error.err || error.errmsg || error.errMessage || error; - var e = MongoError.create({message: msg, driver:true}); - - // Get all object keys - var keys = typeof error == 'object' - ? Object.keys(error) - : []; - - for(var i = 0; i < keys.length; i++) { - try { - e[keys[i]] = error[keys[i]]; - } catch(err) { - // continue - } - } - - return e; -} - +function normalizeHintField(hint) { + let finalHint = undefined; + if (typeof hint === 'string') { + finalHint = hint; + } + else if (Array.isArray(hint)) { + finalHint = {}; + hint.forEach(param => { + finalHint[param] = 1; + }); + } + else if (hint != null && typeof hint === 'object') { + finalHint = {}; + for (const name in hint) { + finalHint[name] = hint[name]; + } + } + return finalHint; +} +exports.normalizeHintField = normalizeHintField; /** - * @ignore + * Create an index specifier based on + * @internal */ -var normalizeHintField = function normalizeHintField(hint) { - var finalHint = null; - - if(typeof hint == 'string') { - finalHint = hint; - } else if(Array.isArray(hint)) { - finalHint = {}; - - hint.forEach(function(param) { - finalHint[param] = 1; - }); - } else if(hint != null && typeof hint == 'object') { - finalHint = {}; - for (var name in hint) { - finalHint[name] = hint[name]; - } - } - - return finalHint; -}; - +function parseIndexOptions(indexSpec) { + const fieldHash = {}; + const indexes = []; + let keys; + // Get all the fields accordingly + if ('string' === typeof indexSpec) { + // 'type' + indexes.push(indexSpec + '_' + 1); + fieldHash[indexSpec] = 1; + } + else if (Array.isArray(indexSpec)) { + indexSpec.forEach((f) => { + if ('string' === typeof f) { + // [{location:'2d'}, 'type'] + indexes.push(f + '_' + 1); + fieldHash[f] = 1; + } + else if (Array.isArray(f)) { + // [['location', '2d'],['type', 1]] + indexes.push(f[0] + '_' + (f[1] || 1)); + fieldHash[f[0]] = f[1] || 1; + } + else if (isObject(f)) { + // [{location:'2d'}, {type:1}] + keys = Object.keys(f); + keys.forEach(k => { + indexes.push(k + '_' + f[k]); + fieldHash[k] = f[k]; + }); + } + else { + // undefined (ignore) + } + }); + } + else if (isObject(indexSpec)) { + // {location:'2d', type:1} + keys = Object.keys(indexSpec); + Object.entries(indexSpec).forEach(([key, value]) => { + indexes.push(key + '_' + value); + fieldHash[key] = value; + }); + } + return { + name: indexes.join('_'), + keys: keys, + fieldHash: fieldHash + }; +} +exports.parseIndexOptions = parseIndexOptions; +const TO_STRING = (object) => Object.prototype.toString.call(object); +/** + * Checks if arg is an Object: + * - **NOTE**: the check is based on the `[Symbol.toStringTag]() === 'Object'` + * @internal + */ +function isObject(arg) { + return '[object Object]' === TO_STRING(arg); +} +exports.isObject = isObject; +/** @internal */ +function mergeOptions(target, source) { + return { ...target, ...source }; +} +exports.mergeOptions = mergeOptions; +/** @internal */ +function filterOptions(options, names) { + const filterOptions = {}; + for (const name in options) { + if (names.includes(name)) { + filterOptions[name] = options[name]; + } + } + // Filtered options + return filterOptions; +} +exports.filterOptions = filterOptions; +/** + * Applies retryWrites: true to a command if retryWrites is set on the command's database. + * @internal + * + * @param target - The target command to which we will apply retryWrites. + * @param db - The database from which we can inherit a retryWrites value. + */ +function applyRetryableWrites(target, db) { + var _a; + if (db && ((_a = db.s.options) === null || _a === void 0 ? void 0 : _a.retryWrites)) { + target.retryWrites = true; + } + return target; +} +exports.applyRetryableWrites = applyRetryableWrites; +/** + * Applies a write concern to a command based on well defined inheritance rules, optionally + * detecting support for the write concern in the first place. + * @internal + * + * @param target - the target command we will be applying the write concern to + * @param sources - sources where we can inherit default write concerns from + * @param options - optional settings passed into a command for write concern overrides + */ +function applyWriteConcern(target, sources, options) { + options = options !== null && options !== void 0 ? options : {}; + const db = sources.db; + const coll = sources.collection; + if (options.session && options.session.inTransaction()) { + // writeConcern is not allowed within a multi-statement transaction + if (target.writeConcern) { + delete target.writeConcern; + } + return target; + } + const writeConcern = write_concern_1.WriteConcern.fromOptions(options); + if (writeConcern) { + return Object.assign(target, { writeConcern }); + } + if (coll && coll.writeConcern) { + return Object.assign(target, { writeConcern: Object.assign({}, coll.writeConcern) }); + } + if (db && db.writeConcern) { + return Object.assign(target, { writeConcern: Object.assign({}, db.writeConcern) }); + } + return target; +} +exports.applyWriteConcern = applyWriteConcern; +/** + * Checks if a given value is a Promise + * + * @typeParam T - The result type of maybePromise + * @param maybePromise - An object that could be a promise + * @returns true if the provided value is a Promise + */ +function isPromiseLike(maybePromise) { + return !!maybePromise && typeof maybePromise.then === 'function'; +} +exports.isPromiseLike = isPromiseLike; +/** + * Applies collation to a given command. + * @internal + * + * @param command - the command on which to apply collation + * @param target - target of command + * @param options - options containing collation settings + */ +function decorateWithCollation(command, target, options) { + const capabilities = getTopology(target).capabilities; + if (options.collation && typeof options.collation === 'object') { + if (capabilities && capabilities.commandsTakeCollation) { + command.collation = options.collation; + } + else { + throw new error_1.MongoCompatibilityError(`Current topology does not support collation`); + } + } +} +exports.decorateWithCollation = decorateWithCollation; /** - * Create index name based on field spec + * Applies a read concern to a given command. + * @internal * - * @ignore - * @api private + * @param command - the command on which to apply the read concern + * @param coll - the parent collection of the operation calling this method */ -var parseIndexOptions = function(fieldOrSpec) { - var fieldHash = {}; - var indexes = []; - var keys; - - // Get all the fields accordingly - if('string' == typeof fieldOrSpec) { - // 'type' - indexes.push(fieldOrSpec + '_' + 1); - fieldHash[fieldOrSpec] = 1; - } else if(Array.isArray(fieldOrSpec)) { - fieldOrSpec.forEach(function(f) { - if('string' == typeof f) { - // [{location:'2d'}, 'type'] - indexes.push(f + '_' + 1); - fieldHash[f] = 1; - } else if(Array.isArray(f)) { - // [['location', '2d'],['type', 1]] - indexes.push(f[0] + '_' + (f[1] || 1)); - fieldHash[f[0]] = f[1] || 1; - } else if(isObject(f)) { - // [{location:'2d'}, {type:1}] - keys = Object.keys(f); - keys.forEach(function(k) { - indexes.push(k + '_' + f[k]); - fieldHash[k] = f[k]; +function decorateWithReadConcern(command, coll, options) { + if (options && options.session && options.session.inTransaction()) { + return; + } + const readConcern = Object.assign({}, command.readConcern || {}); + if (coll.s.readConcern) { + Object.assign(readConcern, coll.s.readConcern); + } + if (Object.keys(readConcern).length > 0) { + Object.assign(command, { readConcern: readConcern }); + } +} +exports.decorateWithReadConcern = decorateWithReadConcern; +/** + * Applies an explain to a given command. + * @internal + * + * @param command - the command on which to apply the explain + * @param options - the options containing the explain verbosity + */ +function decorateWithExplain(command, explain) { + if (command.explain) { + return command; + } + return { explain: command, verbosity: explain.verbosity }; +} +exports.decorateWithExplain = decorateWithExplain; +/** + * A helper function to get the topology from a given provider. Throws + * if the topology cannot be found. + * @throws MongoNotConnectedError + * @internal + */ +function getTopology(provider) { + // MongoClient or ClientSession or AbstractCursor + if ('topology' in provider && provider.topology) { + return provider.topology; + } + else if ('s' in provider && 'client' in provider.s && provider.s.client.topology) { + return provider.s.client.topology; + } + else if ('s' in provider && 'db' in provider.s && provider.s.db.s.client.topology) { + return provider.s.db.s.client.topology; + } + throw new error_1.MongoNotConnectedError('MongoClient must be connected to perform this operation'); +} +exports.getTopology = getTopology; +/** + * Default message handler for generating deprecation warnings. + * @internal + * + * @param name - function name + * @param option - option name + * @returns warning message + */ +function defaultMsgHandler(name, option) { + return `${name} option [${option}] is deprecated and will be removed in a later version.`; +} +exports.defaultMsgHandler = defaultMsgHandler; +/** + * Deprecates a given function's options. + * @internal + * + * @param this - the bound class if this is a method + * @param config - configuration for deprecation + * @param fn - the target function of deprecation + * @returns modified function that warns once per deprecated option, and executes original function + */ +function deprecateOptions(config, fn) { + if (process.noDeprecation === true) { + return fn; + } + const msgHandler = config.msgHandler ? config.msgHandler : defaultMsgHandler; + const optionsWarned = new Set(); + function deprecated(...args) { + const options = args[config.optionsIndex]; + // ensure options is a valid, non-empty object, otherwise short-circuit + if (!isObject(options) || Object.keys(options).length === 0) { + return fn.bind(this)(...args); // call the function, no change + } + // interrupt the function call with a warning + for (const deprecatedOption of config.deprecatedOptions) { + if (deprecatedOption in options && !optionsWarned.has(deprecatedOption)) { + optionsWarned.add(deprecatedOption); + const msg = msgHandler(config.name, deprecatedOption); + emitWarning(msg); + if (this && 'getLogger' in this) { + const logger = this.getLogger(); + if (logger) { + logger.warn(msg); + } + } + } + } + return fn.bind(this)(...args); + } + // These lines copied from https://github.com/nodejs/node/blob/25e5ae41688676a5fd29b2e2e7602168eee4ceb5/lib/internal/util.js#L73-L80 + // The wrapper will keep the same prototype as fn to maintain prototype chain + Object.setPrototypeOf(deprecated, fn); + if (fn.prototype) { + // Setting this (rather than using Object.setPrototype, as above) ensures + // that calling the unwrapped constructor gives an instanceof the wrapped + // constructor. + deprecated.prototype = fn.prototype; + } + return deprecated; +} +exports.deprecateOptions = deprecateOptions; +/** @internal */ +function ns(ns) { + return MongoDBNamespace.fromString(ns); +} +exports.ns = ns; +/** @public */ +class MongoDBNamespace { + /** + * Create a namespace object + * + * @param db - database name + * @param collection - collection name + */ + constructor(db, collection) { + this.db = db; + this.collection = collection; + } + toString() { + return this.collection ? `${this.db}.${this.collection}` : this.db; + } + withCollection(collection) { + return new MongoDBNamespace(this.db, collection); + } + static fromString(namespace) { + if (!namespace) { + // TODO(NODE-3483): Replace with MongoNamespaceError + throw new error_1.MongoRuntimeError(`Cannot parse namespace from "${namespace}"`); + } + const [db, ...collection] = namespace.split('.'); + return new MongoDBNamespace(db, collection.join('.')); + } +} +exports.MongoDBNamespace = MongoDBNamespace; +/** @internal */ +function* makeCounter(seed = 0) { + let count = seed; + while (true) { + const newCount = count; + count += 1; + yield newCount; + } +} +exports.makeCounter = makeCounter; +/** + * Helper function for either accepting a callback, or returning a promise + * @internal + * + * @param callback - The last function argument in exposed method, controls if a Promise is returned + * @param wrapper - A function that wraps the callback + * @returns Returns void if a callback is supplied, else returns a Promise. + */ +function maybePromise(callback, wrapper) { + const Promise = promise_provider_1.PromiseProvider.get(); + let result; + if (typeof callback !== 'function') { + result = new Promise((resolve, reject) => { + callback = (err, res) => { + if (err) + return reject(err); + resolve(res); + }; }); - } else { - // undefined (ignore) - } - }); - } else if(isObject(fieldOrSpec)) { - // {location:'2d', type:1} - keys = Object.keys(fieldOrSpec); - keys.forEach(function(key) { - indexes.push(key + '_' + fieldOrSpec[key]); - fieldHash[key] = fieldOrSpec[key]; + } + wrapper((err, res) => { + if (err != null) { + try { + // eslint-disable-next-line @typescript-eslint/no-non-null-assertion + callback(err); + } + catch (error) { + process.nextTick(() => { + throw error; + }); + } + return; + } + // eslint-disable-next-line @typescript-eslint/no-non-null-assertion + callback(err, res); }); - } - - return { - name: indexes.join("_"), keys: keys, fieldHash: fieldHash - } -} - -var isObject = exports.isObject = function (arg) { - return '[object Object]' == Object.prototype.toString.call(arg) -} - -var debugOptions = function(debugFields, options) { - var finaloptions = {}; - debugFields.forEach(function(n) { - finaloptions[n] = options[n]; - }); - - return finaloptions; -} - -var decorateCommand = function(command, options, exclude) { - for(var name in options) { - if(exclude[name] == null) command[name] = options[name]; - } - - return command; -} - -var mergeOptions = function(target, source) { - for(var name in source) { - target[name] = source[name]; - } - - return target; -} - -// Merge options with translation -var translateOptions = function(target, source) { - var translations = { - // SSL translation options - 'sslCA': 'ca', 'sslCRL': 'crl', 'sslValidate': 'rejectUnauthorized', 'sslKey': 'key', - 'sslCert': 'cert', 'sslPass': 'passphrase', - // SocketTimeout translation options - 'socketTimeoutMS': 'socketTimeout', 'connectTimeoutMS': 'connectionTimeout', - // Replicaset options - 'replicaSet': 'setName', 'rs_name': 'setName', 'secondaryAcceptableLatencyMS': 'acceptableLatency', - 'connectWithNoPrimary': 'secondaryOnlyConnectionAllowed', - // Mongos options - 'acceptableLatencyMS': 'localThresholdMS' - } - - for(var name in source) { - if(translations[name]) { - target[translations[name]] = source[name]; - } else { - target[name] = source[name]; - } - } - - return target; -} - -var filterOptions = function(options, names) { - var filterOptions = {}; - - for(var name in options) { - if(names.indexOf(name) != -1) filterOptions[name] = options[name]; - } - - // Filtered options - return filterOptions; -} - -// Object.assign method or polyfill -var assign = Object.assign ? Object.assign : function assign(target) { - if (target === undefined || target === null) { - throw new TypeError('Cannot convert first argument to object'); - } - - var to = Object(target); - for (var i = 1; i < arguments.length; i++) { - var nextSource = arguments[i]; - if (nextSource === undefined || nextSource === null) { - continue; - } - - var keysArray = Object.keys(Object(nextSource)); - for (var nextIndex = 0, len = keysArray.length; nextIndex < len; nextIndex++) { - var nextKey = keysArray[nextIndex]; - var desc = Object.getOwnPropertyDescriptor(nextSource, nextKey); - if (desc !== undefined && desc.enumerable) { - to[nextKey] = nextSource[nextKey]; - } - } - } - return to; -} - -// Write concern keys -var writeConcernKeys = ['w', 'j', 'wtimeout', 'fsync']; - -// Merge the write concern options -var mergeOptionsAndWriteConcern = function(targetOptions, sourceOptions, keys, mergeWriteConcern) { - // Mix in any allowed options - for(var i = 0; i < keys.length; i++) { - if(!targetOptions[keys[i]] && sourceOptions[keys[i]] != undefined) { - targetOptions[keys[i]] = sourceOptions[keys[i]]; - } - } - - // No merging of write concern - if(!mergeWriteConcern) return targetOptions; - - // Found no write Concern options - var found = false; - for(var i = 0; i < writeConcernKeys.length; i++) { - if(targetOptions[writeConcernKeys[i]]) { - found = true; - break; - } - } - - if(!found) { - for(var i = 0; i < writeConcernKeys.length; i++) { - if(sourceOptions[writeConcernKeys[i]]) { - targetOptions[writeConcernKeys[i]] = sourceOptions[writeConcernKeys[i]]; - } - } - } - - return targetOptions; -} - -exports.filterOptions = filterOptions; -exports.mergeOptions = mergeOptions; -exports.translateOptions = translateOptions; -exports.shallowClone = shallowClone; -exports.getSingleProperty = getSingleProperty; -exports.checkCollectionName = checkCollectionName; -exports.toError = toError; -exports.formattedOrderClause = formattedOrderClause; -exports.parseIndexOptions = parseIndexOptions; -exports.normalizeHintField = normalizeHintField; -exports.handleCallback = handleCallback; -exports.decorateCommand = decorateCommand; -exports.isObject = isObject; -exports.debugOptions = debugOptions; -exports.MAX_JS_INT = 0x20000000000000; -exports.assign = assign; -exports.mergeOptionsAndWriteConcern = mergeOptionsAndWriteConcern; -exports.getReadPreference = getReadPreference; + return result; +} +exports.maybePromise = maybePromise; +/** @internal */ +function databaseNamespace(ns) { + return ns.split('.')[0]; +} +exports.databaseNamespace = databaseNamespace; +/** + * Synchronously Generate a UUIDv4 + * @internal + */ +function uuidV4() { + const result = crypto.randomBytes(16); + result[6] = (result[6] & 0x0f) | 0x40; + result[8] = (result[8] & 0x3f) | 0x80; + return result; +} +exports.uuidV4 = uuidV4; +/** + * A helper function for determining `maxWireVersion` between legacy and new topology instances + * @internal + */ +function maxWireVersion(topologyOrServer) { + if (topologyOrServer) { + if (topologyOrServer.loadBalanced) { + // Since we do not have a monitor, we assume the load balanced server is always + // pointed at the latest mongodb version. There is a risk that for on-prem + // deployments that don't upgrade immediately that this could alert to the + // application that a feature is avaiable that is actually not. + return constants_1.MAX_SUPPORTED_WIRE_VERSION; + } + if (topologyOrServer.hello) { + return topologyOrServer.hello.maxWireVersion; + } + if ('lastHello' in topologyOrServer && typeof topologyOrServer.lastHello === 'function') { + const lastHello = topologyOrServer.lastHello(); + if (lastHello) { + return lastHello.maxWireVersion; + } + } + if (topologyOrServer.description && + 'maxWireVersion' in topologyOrServer.description && + topologyOrServer.description.maxWireVersion != null) { + return topologyOrServer.description.maxWireVersion; + } + } + return 0; +} +exports.maxWireVersion = maxWireVersion; +/** + * Checks that collation is supported by server. + * @internal + * + * @param server - to check against + * @param cmd - object where collation may be specified + */ +function collationNotSupported(server, cmd) { + return cmd && cmd.collation && maxWireVersion(server) < 5; +} +exports.collationNotSupported = collationNotSupported; +/** + * Applies the function `eachFn` to each item in `arr`, in parallel. + * @internal + * + * @param arr - An array of items to asynchronously iterate over + * @param eachFn - A function to call on each item of the array. The callback signature is `(item, callback)`, where the callback indicates iteration is complete. + * @param callback - The callback called after every item has been iterated + */ +function eachAsync(arr, eachFn, callback) { + arr = arr || []; + let idx = 0; + let awaiting = 0; + for (idx = 0; idx < arr.length; ++idx) { + awaiting++; + eachFn(arr[idx], eachCallback); + } + if (awaiting === 0) { + callback(); + return; + } + function eachCallback(err) { + awaiting--; + if (err) { + callback(err); + return; + } + if (idx === arr.length && awaiting <= 0) { + callback(); + } + } +} +exports.eachAsync = eachAsync; +/** @internal */ +function eachAsyncSeries(arr, eachFn, callback) { + arr = arr || []; + let idx = 0; + let awaiting = arr.length; + if (awaiting === 0) { + callback(); + return; + } + function eachCallback(err) { + idx++; + awaiting--; + if (err) { + callback(err); + return; + } + if (idx === arr.length && awaiting <= 0) { + callback(); + return; + } + eachFn(arr[idx], eachCallback); + } + eachFn(arr[idx], eachCallback); +} +exports.eachAsyncSeries = eachAsyncSeries; +/** @internal */ +function arrayStrictEqual(arr, arr2) { + if (!Array.isArray(arr) || !Array.isArray(arr2)) { + return false; + } + return arr.length === arr2.length && arr.every((elt, idx) => elt === arr2[idx]); +} +exports.arrayStrictEqual = arrayStrictEqual; +/** @internal */ +function errorStrictEqual(lhs, rhs) { + if (lhs === rhs) { + return true; + } + if (!lhs || !rhs) { + return lhs === rhs; + } + if ((lhs == null && rhs != null) || (lhs != null && rhs == null)) { + return false; + } + if (lhs.constructor.name !== rhs.constructor.name) { + return false; + } + if (lhs.message !== rhs.message) { + return false; + } + return true; +} +exports.errorStrictEqual = errorStrictEqual; +/** @internal */ +function makeStateMachine(stateTable) { + return function stateTransition(target, newState) { + const legalStates = stateTable[target.s.state]; + if (legalStates && legalStates.indexOf(newState) < 0) { + throw new error_1.MongoRuntimeError(`illegal state transition from [${target.s.state}] => [${newState}], allowed: [${legalStates}]`); + } + target.emit('stateChanged', target.s.state, newState); + target.s.state = newState; + }; +} +exports.makeStateMachine = makeStateMachine; +// eslint-disable-next-line @typescript-eslint/no-var-requires +const NODE_DRIVER_VERSION = require('../package.json').version; +function makeClientMetadata(options) { + options = options !== null && options !== void 0 ? options : {}; + const metadata = { + driver: { + name: 'nodejs', + version: NODE_DRIVER_VERSION + }, + os: { + type: os.type(), + name: process.platform, + architecture: process.arch, + version: os.release() + }, + platform: `Node.js ${process.version}, ${os.endianness()} (unified)` + }; + // support optionally provided wrapping driver info + if (options.driverInfo) { + if (options.driverInfo.name) { + metadata.driver.name = `${metadata.driver.name}|${options.driverInfo.name}`; + } + if (options.driverInfo.version) { + metadata.version = `${metadata.driver.version}|${options.driverInfo.version}`; + } + if (options.driverInfo.platform) { + metadata.platform = `${metadata.platform}|${options.driverInfo.platform}`; + } + } + if (options.appName) { + // MongoDB requires the appName not exceed a byte length of 128 + const buffer = Buffer.from(options.appName); + metadata.application = { + name: buffer.byteLength > 128 ? buffer.slice(0, 128).toString('utf8') : options.appName + }; + } + return metadata; +} +exports.makeClientMetadata = makeClientMetadata; +/** @internal */ +function now() { + const hrtime = process.hrtime(); + return Math.floor(hrtime[0] * 1000 + hrtime[1] / 1000000); +} +exports.now = now; +/** @internal */ +function calculateDurationInMs(started) { + if (typeof started !== 'number') { + throw new error_1.MongoInvalidArgumentError('Numeric value required to calculate duration'); + } + const elapsed = now() - started; + return elapsed < 0 ? 0 : elapsed; +} +exports.calculateDurationInMs = calculateDurationInMs; +/** + * Creates an interval timer which is able to be woken up sooner than + * the interval. The timer will also debounce multiple calls to wake + * ensuring that the function is only ever called once within a minimum + * interval window. + * @internal + * + * @param fn - An async function to run on an interval, must accept a `callback` as its only parameter + */ +function makeInterruptibleAsyncInterval(fn, options) { + let timerId; + let lastCallTime; + let cannotBeExpedited = false; + let stopped = false; + options = options !== null && options !== void 0 ? options : {}; + const interval = options.interval || 1000; + const minInterval = options.minInterval || 500; + const immediate = typeof options.immediate === 'boolean' ? options.immediate : false; + const clock = typeof options.clock === 'function' ? options.clock : now; + function wake() { + const currentTime = clock(); + const nextScheduledCallTime = lastCallTime + interval; + const timeUntilNextCall = nextScheduledCallTime - currentTime; + // For the streaming protocol: there is nothing obviously stopping this + // interval from being woken up again while we are waiting "infinitely" + // for `fn` to be called again`. Since the function effectively + // never completes, the `timeUntilNextCall` will continue to grow + // negatively unbounded, so it will never trigger a reschedule here. + // This is possible in virtualized environments like AWS Lambda where our + // clock is unreliable. In these cases the timer is "running" but never + // actually completes, so we want to execute immediately and then attempt + // to reschedule. + if (timeUntilNextCall < 0) { + executeAndReschedule(); + return; + } + // debounce multiple calls to wake within the `minInterval` + if (cannotBeExpedited) { + return; + } + // reschedule a call as soon as possible, ensuring the call never happens + // faster than the `minInterval` + if (timeUntilNextCall > minInterval) { + reschedule(minInterval); + cannotBeExpedited = true; + } + } + function stop() { + stopped = true; + if (timerId) { + clearTimeout(timerId); + timerId = undefined; + } + lastCallTime = 0; + cannotBeExpedited = false; + } + function reschedule(ms) { + if (stopped) + return; + if (timerId) { + clearTimeout(timerId); + } + timerId = (0, timers_1.setTimeout)(executeAndReschedule, ms || interval); + } + function executeAndReschedule() { + cannotBeExpedited = false; + lastCallTime = clock(); + fn(err => { + if (err) + throw err; + reschedule(interval); + }); + } + if (immediate) { + executeAndReschedule(); + } + else { + lastCallTime = clock(); + reschedule(undefined); + } + return { wake, stop }; +} +exports.makeInterruptibleAsyncInterval = makeInterruptibleAsyncInterval; +/** @internal */ +function hasAtomicOperators(doc) { + if (Array.isArray(doc)) { + for (const document of doc) { + if (hasAtomicOperators(document)) { + return true; + } + } + return false; + } + const keys = Object.keys(doc); + return keys.length > 0 && keys[0][0] === '$'; +} +exports.hasAtomicOperators = hasAtomicOperators; +/** + * Merge inherited properties from parent into options, prioritizing values from options, + * then values from parent. + * @internal + */ +function resolveOptions(parent, options) { + var _a, _b, _c; + const result = Object.assign({}, options, (0, bson_1.resolveBSONOptions)(options, parent)); + // Users cannot pass a readConcern/writeConcern to operations in a transaction + const session = options === null || options === void 0 ? void 0 : options.session; + if (!(session === null || session === void 0 ? void 0 : session.inTransaction())) { + const readConcern = (_a = read_concern_1.ReadConcern.fromOptions(options)) !== null && _a !== void 0 ? _a : parent === null || parent === void 0 ? void 0 : parent.readConcern; + if (readConcern) { + result.readConcern = readConcern; + } + const writeConcern = (_b = write_concern_1.WriteConcern.fromOptions(options)) !== null && _b !== void 0 ? _b : parent === null || parent === void 0 ? void 0 : parent.writeConcern; + if (writeConcern) { + result.writeConcern = writeConcern; + } + } + const readPreference = (_c = read_preference_1.ReadPreference.fromOptions(options)) !== null && _c !== void 0 ? _c : parent === null || parent === void 0 ? void 0 : parent.readPreference; + if (readPreference) { + result.readPreference = readPreference; + } + return result; +} +exports.resolveOptions = resolveOptions; +function isSuperset(set, subset) { + set = Array.isArray(set) ? new Set(set) : set; + subset = Array.isArray(subset) ? new Set(subset) : subset; + for (const elem of subset) { + if (!set.has(elem)) { + return false; + } + } + return true; +} +exports.isSuperset = isSuperset; +/** + * Checks if the document is a Hello request + * @internal + */ +function isHello(doc) { + return doc[constants_2.LEGACY_HELLO_COMMAND] || doc.hello ? true : false; +} +exports.isHello = isHello; +/** Returns the items that are uniquely in setA */ +function setDifference(setA, setB) { + const difference = new Set(setA); + for (const elem of setB) { + difference.delete(elem); + } + return difference; +} +exports.setDifference = setDifference; +const HAS_OWN = (object, prop) => Object.prototype.hasOwnProperty.call(object, prop); +function isRecord(value, requiredKeys = undefined) { + if (!isObject(value)) { + return false; + } + const ctor = value.constructor; + if (ctor && ctor.prototype) { + if (!isObject(ctor.prototype)) { + return false; + } + // Check to see if some method exists from the Object exists + if (!HAS_OWN(ctor.prototype, 'isPrototypeOf')) { + return false; + } + } + if (requiredKeys) { + const keys = Object.keys(value); + return isSuperset(keys, requiredKeys); + } + return true; +} +exports.isRecord = isRecord; +/** + * Make a deep copy of an object + * + * NOTE: This is not meant to be the perfect implementation of a deep copy, + * but instead something that is good enough for the purposes of + * command monitoring. + */ +function deepCopy(value) { + if (value == null) { + return value; + } + else if (Array.isArray(value)) { + return value.map(item => deepCopy(item)); + } + else if (isRecord(value)) { + const res = {}; + for (const key in value) { + res[key] = deepCopy(value[key]); + } + return res; + } + const ctor = value.constructor; + if (ctor) { + switch (ctor.name.toLowerCase()) { + case 'date': + return new ctor(Number(value)); + case 'map': + return new Map(value); + case 'set': + return new Set(value); + case 'buffer': + return Buffer.from(value); + } + } + return value; +} +exports.deepCopy = deepCopy; +/** @internal */ +const kBuffers = Symbol('buffers'); +/** @internal */ +const kLength = Symbol('length'); +/** + * A pool of Buffers which allow you to read them as if they were one + * @internal + */ +class BufferPool { + constructor() { + this[kBuffers] = []; + this[kLength] = 0; + } + get length() { + return this[kLength]; + } + /** Adds a buffer to the internal buffer pool list */ + append(buffer) { + this[kBuffers].push(buffer); + this[kLength] += buffer.length; + } + /** Returns the requested number of bytes without consuming them */ + peek(size) { + return this.read(size, false); + } + /** Reads the requested number of bytes, optionally consuming them */ + read(size, consume = true) { + if (typeof size !== 'number' || size < 0) { + throw new error_1.MongoInvalidArgumentError('Argument "size" must be a non-negative number'); + } + if (size > this[kLength]) { + return Buffer.alloc(0); + } + let result; + // read the whole buffer + if (size === this.length) { + result = Buffer.concat(this[kBuffers]); + if (consume) { + this[kBuffers] = []; + this[kLength] = 0; + } + } + // size is within first buffer, no need to concat + else if (size <= this[kBuffers][0].length) { + result = this[kBuffers][0].slice(0, size); + if (consume) { + this[kBuffers][0] = this[kBuffers][0].slice(size); + this[kLength] -= size; + } + } + // size is beyond first buffer, need to track and copy + else { + result = Buffer.allocUnsafe(size); + let idx; + let offset = 0; + let bytesToCopy = size; + for (idx = 0; idx < this[kBuffers].length; ++idx) { + let bytesCopied; + if (bytesToCopy > this[kBuffers][idx].length) { + bytesCopied = this[kBuffers][idx].copy(result, offset, 0); + offset += bytesCopied; + } + else { + bytesCopied = this[kBuffers][idx].copy(result, offset, 0, bytesToCopy); + if (consume) { + this[kBuffers][idx] = this[kBuffers][idx].slice(bytesCopied); + } + offset += bytesCopied; + break; + } + bytesToCopy -= bytesCopied; + } + // compact the internal buffer array + if (consume) { + this[kBuffers] = this[kBuffers].slice(idx); + this[kLength] -= size; + } + } + return result; + } +} +exports.BufferPool = BufferPool; +/** @public */ +class HostAddress { + constructor(hostString) { + const escapedHost = hostString.split(' ').join('%20'); // escape spaces, for socket path hosts + const { hostname, port } = new url_1.URL(`mongodb://${escapedHost}`); + if (hostname.endsWith('.sock')) { + // heuristically determine if we're working with a domain socket + this.socketPath = decodeURIComponent(hostname); + } + else if (typeof hostname === 'string') { + this.isIPv6 = false; + let normalized = decodeURIComponent(hostname).toLowerCase(); + if (normalized.startsWith('[') && normalized.endsWith(']')) { + this.isIPv6 = true; + normalized = normalized.substring(1, hostname.length - 1); + } + this.host = normalized.toLowerCase(); + if (typeof port === 'number') { + this.port = port; + } + else if (typeof port === 'string' && port !== '') { + this.port = Number.parseInt(port, 10); + } + else { + this.port = 27017; + } + if (this.port === 0) { + throw new error_1.MongoParseError('Invalid port (zero) with hostname'); + } + } + else { + throw new error_1.MongoInvalidArgumentError('Either socketPath or host must be defined.'); + } + Object.freeze(this); + } + [Symbol.for('nodejs.util.inspect.custom')]() { + return this.inspect(); + } + inspect() { + return `new HostAddress('${this.toString(true)}')`; + } + /** + * @param ipv6Brackets - optionally request ipv6 bracket notation required for connection strings + */ + toString(ipv6Brackets = false) { + if (typeof this.host === 'string') { + if (this.isIPv6 && ipv6Brackets) { + return `[${this.host}]:${this.port}`; + } + return `${this.host}:${this.port}`; + } + return `${this.socketPath}`; + } + static fromString(s) { + return new HostAddress(s); + } + static fromHostPort(host, port) { + if (host.includes(':')) { + host = `[${host}]`; // IPv6 address + } + return HostAddress.fromString(`${host}:${port}`); + } + static fromSrvRecord({ name, port }) { + return HostAddress.fromHostPort(name, port); + } +} +exports.HostAddress = HostAddress; +exports.DEFAULT_PK_FACTORY = { + // We prefer not to rely on ObjectId having a createPk method + createPk() { + return new bson_1.ObjectId(); + } +}; +/** + * When the driver used emitWarning the code will be equal to this. + * @public + * + * @example + * ```js + * process.on('warning', (warning) => { + * if (warning.code === MONGODB_WARNING_CODE) console.error('Ah an important warning! :)') + * }) + * ``` + */ +exports.MONGODB_WARNING_CODE = 'MONGODB DRIVER'; +/** @internal */ +function emitWarning(message) { + return process.emitWarning(message, { code: exports.MONGODB_WARNING_CODE }); +} +exports.emitWarning = emitWarning; +const emittedWarnings = new Set(); +/** + * Will emit a warning once for the duration of the application. + * Uses the message to identify if it has already been emitted + * so using string interpolation can cause multiple emits + * @internal + */ +function emitWarningOnce(message) { + if (!emittedWarnings.has(message)) { + emittedWarnings.add(message); + return emitWarning(message); + } +} +exports.emitWarningOnce = emitWarningOnce; +/** + * Takes a JS object and joins the values into a string separated by ', ' + */ +function enumToString(en) { + return Object.values(en).join(', '); +} +exports.enumToString = enumToString; +/** + * Determine if a server supports retryable writes. + * + * @internal + */ +function supportsRetryableWrites(server) { + if (!server) { + return false; + } + if (server.loadBalanced) { + // Loadbalanced topologies will always support retry writes + return true; + } + if (server.description.logicalSessionTimeoutMinutes != null) { + // that supports sessions + if (server.description.type !== common_1.ServerType.Standalone) { + // and that is not a standalone + return true; + } + } + return false; +} +exports.supportsRetryableWrites = supportsRetryableWrites; +function parsePackageVersion({ version }) { + const [major, minor, patch] = version.split('.').map((n) => Number.parseInt(n, 10)); + return { major, minor, patch }; +} +exports.parsePackageVersion = parsePackageVersion; +/** + * Fisher–Yates Shuffle + * + * Reference: https://bost.ocks.org/mike/shuffle/ + * @param sequence - items to be shuffled + * @param limit - Defaults to `0`. If nonzero shuffle will slice the randomized array e.g, `.slice(0, limit)` otherwise will return the entire randomized array. + */ +function shuffle(sequence, limit = 0) { + const items = Array.from(sequence); // shallow copy in order to never shuffle the input + if (limit > items.length) { + throw new error_1.MongoRuntimeError('Limit must be less than the number of items'); + } + let remainingItemsToShuffle = items.length; + const lowerBound = limit % items.length === 0 ? 1 : items.length - limit; + while (remainingItemsToShuffle > lowerBound) { + // Pick a remaining element + const randomIndex = Math.floor(Math.random() * remainingItemsToShuffle); + remainingItemsToShuffle -= 1; + // And swap it with the current element + const swapHold = items[remainingItemsToShuffle]; + items[remainingItemsToShuffle] = items[randomIndex]; + items[randomIndex] = swapHold; + } + return limit % items.length === 0 ? items : items.slice(lowerBound); +} +exports.shuffle = shuffle; +// TODO: this should be codified in command construction +// @see https://github.com/mongodb/specifications/blob/master/source/read-write-concern/read-write-concern.rst#read-concern +function commandSupportsReadConcern(command, options) { + if (command.aggregate || command.count || command.distinct || command.find || command.geoNear) { + return true; + } + if (command.mapReduce && + options && + options.out && + (options.out.inline === 1 || options.out === 'inline')) { + return true; + } + return false; +} +exports.commandSupportsReadConcern = commandSupportsReadConcern; +/** + * A utility function to get the instance of mongodb-client-encryption, if it exists. + * + * @throws MongoMissingDependencyError if mongodb-client-encryption isn't installed. + * @returns + */ +function getMongoDBClientEncryption() { + let mongodbClientEncryption; + // NOTE(NODE-4254): This is to get around the circular dependency between + // mongodb-client-encryption and the driver in the test scenarios. + if (typeof process.env.MONGODB_CLIENT_ENCRYPTION_OVERRIDE === 'string' && + process.env.MONGODB_CLIENT_ENCRYPTION_OVERRIDE.length > 0) { + mongodbClientEncryption = require(process.env.MONGODB_CLIENT_ENCRYPTION_OVERRIDE); + } + else { + mongodbClientEncryption = require('mongodb-client-encryption'); + } + return mongodbClientEncryption; +} +exports.getMongoDBClientEncryption = getMongoDBClientEncryption; +//# sourceMappingURL=utils.js.map \ No newline at end of file diff --git a/ts-ticket-office-service/node_modules/mongodb/lib/utils.js.map b/ts-ticket-office-service/node_modules/mongodb/lib/utils.js.map new file mode 100644 index 000000000..54d9bdbf2 --- /dev/null +++ b/ts-ticket-office-service/node_modules/mongodb/lib/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,CAAC,CAAC;KACnF;SAAM;QACL,uBAAuB,GAAG,OAAO,CAAC,2BAA2B,CAAC,CAAC;KAChE;IAED,OAAO,uBAAuB,CAAC;AACjC,CAAC;AAfD,gEAeC"} \ No newline at end of file diff --git a/ts-ticket-office-service/node_modules/mongodb/lib/write_concern.js b/ts-ticket-office-service/node_modules/mongodb/lib/write_concern.js new file mode 100644 index 000000000..4816b00eb --- /dev/null +++ b/ts-ticket-office-service/node_modules/mongodb/lib/write_concern.js @@ -0,0 +1,71 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.WriteConcern = exports.WRITE_CONCERN_KEYS = void 0; +exports.WRITE_CONCERN_KEYS = ['w', 'wtimeout', 'j', 'journal', 'fsync']; +/** + * A MongoDB WriteConcern, which describes the level of acknowledgement + * requested from MongoDB for write operations. + * @public + * + * @see https://docs.mongodb.com/manual/reference/write-concern/ + */ +class WriteConcern { + /** + * Constructs a WriteConcern from the write concern properties. + * @param w - request acknowledgment that the write operation has propagated to a specified number of mongod instances or to mongod instances with specified tags. + * @param wtimeout - specify a time limit to prevent write operations from blocking indefinitely + * @param j - request acknowledgment that the write operation has been written to the on-disk journal + * @param fsync - equivalent to the j option + */ + constructor(w, wtimeout, j, fsync) { + if (w != null) { + if (!Number.isNaN(Number(w))) { + this.w = Number(w); + } + else { + this.w = w; + } + } + if (wtimeout != null) { + this.wtimeout = wtimeout; + } + if (j != null) { + this.j = j; + } + if (fsync != null) { + this.fsync = fsync; + } + } + /** Construct a WriteConcern given an options object. */ + static fromOptions(options, inherit) { + if (options == null) + return undefined; + inherit = inherit !== null && inherit !== void 0 ? inherit : {}; + let opts; + if (typeof options === 'string' || typeof options === 'number') { + opts = { w: options }; + } + else if (options instanceof WriteConcern) { + opts = options; + } + else { + opts = options.writeConcern; + } + const parentOpts = inherit instanceof WriteConcern ? inherit : inherit.writeConcern; + const { w = undefined, wtimeout = undefined, j = undefined, fsync = undefined, journal = undefined, wtimeoutMS = undefined } = { + ...parentOpts, + ...opts + }; + if (w != null || + wtimeout != null || + wtimeoutMS != null || + j != null || + journal != null || + fsync != null) { + return new WriteConcern(w, wtimeout !== null && wtimeout !== void 0 ? wtimeout : wtimeoutMS, j !== null && j !== void 0 ? j : journal, fsync); + } + return undefined; + } +} +exports.WriteConcern = WriteConcern; +//# sourceMappingURL=write_concern.js.map \ No newline at end of file diff --git a/ts-ticket-office-service/node_modules/mongodb/lib/write_concern.js.map b/ts-ticket-office-service/node_modules/mongodb/lib/write_concern.js.map new file mode 100644 index 000000000..c2e21b7e1 --- /dev/null +++ b/ts-ticket-office-service/node_modules/mongodb/lib/write_concern.js.map @@ -0,0 +1 @@ +{"version":3,"file":"write_concern.js","sourceRoot":"","sources":["../src/write_concern.ts"],"names":[],"mappings":";;;AA2Ba,QAAA,kBAAkB,GAAG,CAAC,GAAG,EAAE,UAAU,EAAE,GAAG,EAAE,SAAS,EAAE,OAAO,CAAC,CAAC;AAE7E;;;;;;GAMG;AACH,MAAa,YAAY;IAUvB;;;;;;OAMG;IACH,YAAY,CAAK,EAAE,QAAiB,EAAE,CAAW,EAAE,KAAmB;QACpE,IAAI,CAAC,IAAI,IAAI,EAAE;YACb,IAAI,CAAC,MAAM,CAAC,KAAK,CAAC,MAAM,CAAC,CAAC,CAAC,CAAC,EAAE;gBAC5B,IAAI,CAAC,CAAC,GAAG,MAAM,CAAC,CAAC,CAAC,CAAC;aACpB;iBAAM;gBACL,IAAI,CAAC,CAAC,GAAG,CAAC,CAAC;aACZ;SACF;QACD,IAAI,QAAQ,IAAI,IAAI,EAAE;YACpB,IAAI,CAAC,QAAQ,GAAG,QAAQ,CAAC;SAC1B;QACD,IAAI,CAAC,IAAI,IAAI,EAAE;YACb,IAAI,CAAC,CAAC,GAAG,CAAC,CAAC;SACZ;QACD,IAAI,KAAK,IAAI,IAAI,EAAE;YACjB,IAAI,CAAC,KAAK,GAAG,KAAK,CAAC;SACpB;IACH,CAAC;IAED,wDAAwD;IACxD,MAAM,CAAC,WAAW,CAChB,OAAgD,EAChD,OAA4C;QAE5C,IAAI,OAAO,IAAI,IAAI;YAAE,OAAO,SAAS,CAAC;QACtC,OAAO,GAAG,OAAO,aAAP,OAAO,cAAP,OAAO,GAAI,EAAE,CAAC;QACxB,IAAI,IAAqD,CAAC;QAC1D,IAAI,OAAO,OAAO,KAAK,QAAQ,IAAI,OAAO,OAAO,KAAK,QAAQ,EAAE;YAC9D,IAAI,GAAG,EAAE,CAAC,EAAE,OAAO,EAAE,CAAC;SACvB;aAAM,IAAI,OAAO,YAAY,YAAY,EAAE;YAC1C,IAAI,GAAG,OAAO,CAAC;SAChB;aAAM;YACL,IAAI,GAAG,OAAO,CAAC,YAAY,CAAC;SAC7B;QACD,MAAM,UAAU,GACd,OAAO,YAAY,YAAY,CAAC,CAAC,CAAC,OAAO,CAAC,CAAC,CAAC,OAAO,CAAC,YAAY,CAAC;QAEnE,MAAM,EACJ,CAAC,GAAG,SAAS,EACb,QAAQ,GAAG,SAAS,EACpB,CAAC,GAAG,SAAS,EACb,KAAK,GAAG,SAAS,EACjB,OAAO,GAAG,SAAS,EACnB,UAAU,GAAG,SAAS,EACvB,GAAG;YACF,GAAG,UAAU;YACb,GAAG,IAAI;SACR,CAAC;QACF,IACE,CAAC,IAAI,IAAI;YACT,QAAQ,IAAI,IAAI;YAChB,UAAU,IAAI,IAAI;YAClB,CAAC,IAAI,IAAI;YACT,OAAO,IAAI,IAAI;YACf,KAAK,IAAI,IAAI,EACb;YACA,OAAO,IAAI,YAAY,CAAC,CAAC,EAAE,QAAQ,aAAR,QAAQ,cAAR,QAAQ,GAAI,UAAU,EAAE,CAAC,aAAD,CAAC,cAAD,CAAC,GAAI,OAAO,EAAE,KAAK,CAAC,CAAC;SACzE;QACD,OAAO,SAAS,CAAC;IACnB,CAAC;CACF;AA7ED,oCA6EC"} \ No newline at end of file diff --git a/ts-ticket-office-service/node_modules/mongodb/mongodb.d.ts b/ts-ticket-office-service/node_modules/mongodb/mongodb.d.ts new file mode 100644 index 000000000..f2c23fe5c --- /dev/null +++ b/ts-ticket-office-service/node_modules/mongodb/mongodb.d.ts @@ -0,0 +1,6684 @@ +/// + +import { Binary } from 'bson'; +import { BSONRegExp } from 'bson'; +import { BSONSymbol } from 'bson'; +import { Code } from 'bson'; +import type { ConnectionOptions as ConnectionOptions_2 } from 'tls'; +import { DBRef } from 'bson'; +import { Decimal128 } from 'bson'; +import Denque = require('denque'); +import type { deserialize as deserialize_2 } from 'bson'; +import type { DeserializeOptions } from 'bson'; +import * as dns from 'dns'; +import { Document } from 'bson'; +import { Double } from 'bson'; +import { Duplex } from 'stream'; +import { DuplexOptions } from 'stream'; +import { EventEmitter } from 'events'; +import { Int32 } from 'bson'; +import { Long } from 'bson'; +import { Map as Map_2 } from 'bson'; +import { MaxKey } from 'bson'; +import { MinKey } from 'bson'; +import { ObjectId } from 'bson'; +import type { ObjectIdLike } from 'bson'; +import { Readable } from 'stream'; +import type { serialize as serialize_2 } from 'bson'; +import type { SerializeOptions } from 'bson'; +import type { Socket } from 'net'; +import type { SrvRecord } from 'dns'; +import type { TcpNetConnectOpts } from 'net'; +import { Timestamp } from 'bson'; +import type { TLSSocket } from 'tls'; +import type { TLSSocketOptions } from 'tls'; +import { Writable } from 'stream'; + +/** @public */ +export declare abstract class AbstractCursor extends TypedEventEmitter { + /* Excluded from this release type: [kId] */ + /* Excluded from this release type: [kSession] */ + /* Excluded from this release type: [kServer] */ + /* Excluded from this release type: [kNamespace] */ + /* Excluded from this release type: [kDocuments] */ + /* Excluded from this release type: [kClient] */ + /* Excluded from this release type: [kTransform] */ + /* Excluded from this release type: [kInitialized] */ + /* Excluded from this release type: [kClosed] */ + /* Excluded from this release type: [kKilled] */ + /* Excluded from this release type: [kOptions] */ + /** @event */ + static readonly CLOSE: "close"; + /* Excluded from this release type: __constructor */ + get id(): Long | undefined; + /* Excluded from this release type: client */ + /* Excluded from this release type: server */ + get namespace(): MongoDBNamespace; + get readPreference(): ReadPreference; + get readConcern(): ReadConcern | undefined; + /* Excluded from this release type: session */ + /* Excluded from this release type: session */ + /* Excluded from this release type: cursorOptions */ + get closed(): boolean; + get killed(): boolean; + get loadBalanced(): boolean; + /** Returns current buffered documents length */ + bufferedCount(): number; + /** Returns current buffered documents */ + readBufferedDocuments(number?: number): TSchema[]; + [Symbol.asyncIterator](): AsyncIterator; + stream(options?: CursorStreamOptions): Readable & AsyncIterable; + hasNext(): Promise; + hasNext(callback: Callback): void; + /** Get the next available document from the cursor, returns null if no more documents are available. */ + next(): Promise; + next(callback: Callback): void; + next(callback?: Callback): Promise | void; + /** + * Try to get the next available document from the cursor or `null` if an empty batch is returned + */ + tryNext(): Promise; + tryNext(callback: Callback): void; + /** + * Iterates over all the documents for this cursor using the iterator, callback pattern. + * + * @param iterator - The iteration callback. + * @param callback - The end callback. + */ + forEach(iterator: (doc: TSchema) => boolean | void): Promise; + forEach(iterator: (doc: TSchema) => boolean | void, callback: Callback): void; + close(): Promise; + close(callback: Callback): void; + /** + * @deprecated options argument is deprecated + */ + close(options: CursorCloseOptions): Promise; + /** + * @deprecated options argument is deprecated + */ + close(options: CursorCloseOptions, callback: Callback): void; + /** + * Returns an array of documents. The caller is responsible for making sure that there + * is enough memory to store the results. Note that the array only contains partial + * results when this cursor had been previously accessed. In that case, + * cursor.rewind() can be used to reset the cursor. + * + * @param callback - The result callback. + */ + toArray(): Promise; + toArray(callback: Callback): void; + /** + * Add a cursor flag to the cursor + * + * @param flag - The flag to set, must be one of following ['tailable', 'oplogReplay', 'noCursorTimeout', 'awaitData', 'partial' -. + * @param value - The flag boolean value. + */ + addCursorFlag(flag: CursorFlag, value: boolean): this; + /** + * Map all documents using the provided function + * If there is a transform set on the cursor, that will be called first and the result passed to + * this function's transform. + * + * @remarks + * **Note for Typescript Users:** adding a transform changes the return type of the iteration of this cursor, + * it **does not** return a new instance of a cursor. This means when calling map, + * you should always assign the result to a new variable in order to get a correctly typed cursor variable. + * Take note of the following example: + * + * @example + * ```typescript + * const cursor: FindCursor = coll.find(); + * const mappedCursor: FindCursor = cursor.map(doc => Object.keys(doc).length); + * const keyCounts: number[] = await mappedCursor.toArray(); // cursor.toArray() still returns Document[] + * ``` + * @param transform - The mapping transformation method. + */ + map(transform: (doc: TSchema) => T): AbstractCursor; + /** + * Set the ReadPreference for the cursor. + * + * @param readPreference - The new read preference for the cursor. + */ + withReadPreference(readPreference: ReadPreferenceLike): this; + /** + * Set the ReadPreference for the cursor. + * + * @param readPreference - The new read preference for the cursor. + */ + withReadConcern(readConcern: ReadConcernLike): this; + /** + * Set a maxTimeMS on the cursor query, allowing for hard timeout limits on queries (Only supported on MongoDB 2.6 or higher) + * + * @param value - Number of milliseconds to wait before aborting the query. + */ + maxTimeMS(value: number): this; + /** + * Set the batch size for the cursor. + * + * @param value - The number of documents to return per batch. See {@link https://docs.mongodb.com/manual/reference/command/find/|find command documentation}. + */ + batchSize(value: number): this; + /** + * Rewind this cursor to its uninitialized state. Any options that are present on the cursor will + * remain in effect. Iterating this cursor will cause new queries to be sent to the server, even + * if the resultant data has already been retrieved by this cursor. + */ + rewind(): void; + /** + * Returns a new uninitialized copy of this cursor, with options matching those that have been set on the current instance + */ + abstract clone(): AbstractCursor; + /* Excluded from this release type: _initialize */ + /* Excluded from this release type: _getMore */ + /* Excluded from this release type: [kInit] */ +} + +/** @public */ +export declare type AbstractCursorEvents = { + [AbstractCursor.CLOSE](): void; +}; + +/** @public */ +export declare interface AbstractCursorOptions extends BSONSerializeOptions { + session?: ClientSession; + readPreference?: ReadPreferenceLike; + readConcern?: ReadConcernLike; + batchSize?: number; + maxTimeMS?: number; + /** + * Comment to apply to the operation. + * + * In server versions pre-4.4, 'comment' must be string. A server + * error will be thrown if any other type is provided. + * + * In server versions 4.4 and above, 'comment' can be any valid BSON type. + */ + comment?: unknown; + tailable?: boolean; + awaitData?: boolean; + noCursorTimeout?: boolean; +} + +/* Excluded from this release type: AbstractOperation */ + +/** @public */ +export declare type AcceptedFields = { + readonly [key in KeysOfAType]?: AssignableType; +}; + +/** @public */ +export declare type AddToSetOperators = { + $each?: Array>; +}; + +/** @public */ +export declare interface AddUserOptions extends CommandOperationOptions { + /** @deprecated Please use db.command('createUser', ...) instead for this option */ + digestPassword?: null; + /** Roles associated with the created user */ + roles?: string | string[] | RoleSpecification | RoleSpecification[]; + /** Custom data associated with the user (only Mongodb 2.6 or higher) */ + customData?: Document; +} + +/** + * The **Admin** class is an internal class that allows convenient access to + * the admin functionality and commands for MongoDB. + * + * **ADMIN Cannot directly be instantiated** + * @public + * + * @example + * ```js + * const MongoClient = require('mongodb').MongoClient; + * const test = require('assert'); + * // Connection url + * const url = 'mongodb://localhost:27017'; + * // Database Name + * const dbName = 'test'; + * + * // Connect using MongoClient + * MongoClient.connect(url, function(err, client) { + * // Use the admin database for the operation + * const adminDb = client.db(dbName).admin(); + * + * // List all the available databases + * adminDb.listDatabases(function(err, dbs) { + * expect(err).to.not.exist; + * test.ok(dbs.databases.length > 0); + * client.close(); + * }); + * }); + * ``` + */ +export declare class Admin { + /* Excluded from this release type: s */ + /* Excluded from this release type: __constructor */ + /** + * Execute a command + * + * @param command - The command to execute + * @param options - Optional settings for the command + * @param callback - An optional callback, a Promise will be returned if none is provided + */ + command(command: Document): Promise; + command(command: Document, callback: Callback): void; + command(command: Document, options: RunCommandOptions): Promise; + command(command: Document, options: RunCommandOptions, callback: Callback): void; + /** + * Retrieve the server build information + * + * @param options - Optional settings for the command + * @param callback - An optional callback, a Promise will be returned if none is provided + */ + buildInfo(): Promise; + buildInfo(callback: Callback): void; + buildInfo(options: CommandOperationOptions): Promise; + buildInfo(options: CommandOperationOptions, callback: Callback): void; + /** + * Retrieve the server build information + * + * @param options - Optional settings for the command + * @param callback - An optional callback, a Promise will be returned if none is provided + */ + serverInfo(): Promise; + serverInfo(callback: Callback): void; + serverInfo(options: CommandOperationOptions): Promise; + serverInfo(options: CommandOperationOptions, callback: Callback): void; + /** + * Retrieve this db's server status. + * + * @param options - Optional settings for the command + * @param callback - An optional callback, a Promise will be returned if none is provided + */ + serverStatus(): Promise; + serverStatus(callback: Callback): void; + serverStatus(options: CommandOperationOptions): Promise; + serverStatus(options: CommandOperationOptions, callback: Callback): void; + /** + * Ping the MongoDB server and retrieve results + * + * @param options - Optional settings for the command + * @param callback - An optional callback, a Promise will be returned if none is provided + */ + ping(): Promise; + ping(callback: Callback): void; + ping(options: CommandOperationOptions): Promise; + ping(options: CommandOperationOptions, callback: Callback): void; + /** + * Add a user to the database + * + * @param username - The username for the new user + * @param password - An optional password for the new user + * @param options - Optional settings for the command + * @param callback - An optional callback, a Promise will be returned if none is provided + */ + addUser(username: string): Promise; + addUser(username: string, callback: Callback): void; + addUser(username: string, password: string): Promise; + addUser(username: string, password: string, callback: Callback): void; + addUser(username: string, options: AddUserOptions): Promise; + addUser(username: string, options: AddUserOptions, callback: Callback): void; + addUser(username: string, password: string, options: AddUserOptions): Promise; + addUser(username: string, password: string, options: AddUserOptions, callback: Callback): void; + /** + * Remove a user from a database + * + * @param username - The username to remove + * @param options - Optional settings for the command + * @param callback - An optional callback, a Promise will be returned if none is provided + */ + removeUser(username: string): Promise; + removeUser(username: string, callback: Callback): void; + removeUser(username: string, options: RemoveUserOptions): Promise; + removeUser(username: string, options: RemoveUserOptions, callback: Callback): void; + /** + * Validate an existing collection + * + * @param collectionName - The name of the collection to validate. + * @param options - Optional settings for the command + * @param callback - An optional callback, a Promise will be returned if none is provided + */ + validateCollection(collectionName: string): Promise; + validateCollection(collectionName: string, callback: Callback): void; + validateCollection(collectionName: string, options: ValidateCollectionOptions): Promise; + validateCollection(collectionName: string, options: ValidateCollectionOptions, callback: Callback): void; + /** + * List the available databases + * + * @param options - Optional settings for the command + * @param callback - An optional callback, a Promise will be returned if none is provided + */ + listDatabases(): Promise; + listDatabases(callback: Callback): void; + listDatabases(options: ListDatabasesOptions): Promise; + listDatabases(options: ListDatabasesOptions, callback: Callback): void; + /** + * Get ReplicaSet status + * + * @param options - Optional settings for the command + * @param callback - An optional callback, a Promise will be returned if none is provided + */ + replSetGetStatus(): Promise; + replSetGetStatus(callback: Callback): void; + replSetGetStatus(options: CommandOperationOptions): Promise; + replSetGetStatus(options: CommandOperationOptions, callback: Callback): void; +} + +/* Excluded from this release type: AdminPrivate */ + +/* Excluded from this release type: AggregateOperation */ + +/** @public */ +export declare interface AggregateOptions extends CommandOperationOptions { + /** allowDiskUse lets the server know if it can use disk to store temporary results for the aggregation (requires mongodb 2.6 \>). */ + allowDiskUse?: boolean; + /** The number of documents to return per batch. See [aggregation documentation](https://docs.mongodb.com/manual/reference/command/aggregate). */ + batchSize?: number; + /** Allow driver to bypass schema validation in MongoDB 3.2 or higher. */ + bypassDocumentValidation?: boolean; + /** Return the query as cursor, on 2.6 \> it returns as a real cursor on pre 2.6 it returns as an emulated cursor. */ + cursor?: Document; + /** specifies a cumulative time limit in milliseconds for processing operations on the cursor. MongoDB interrupts the operation at the earliest following interrupt point. */ + maxTimeMS?: number; + /** The maximum amount of time for the server to wait on new documents to satisfy a tailable cursor query. */ + maxAwaitTimeMS?: number; + /** Specify collation. */ + collation?: CollationOptions; + /** Add an index selection hint to an aggregation command */ + hint?: Hint; + /** Map of parameter names and values that can be accessed using $$var (requires MongoDB 5.0). */ + let?: Document; + out?: string; +} + +/** + * The **AggregationCursor** class is an internal class that embodies an aggregation cursor on MongoDB + * allowing for iteration over the results returned from the underlying query. It supports + * one by one document iteration, conversion to an array or can be iterated as a Node 4.X + * or higher stream + * @public + */ +export declare class AggregationCursor extends AbstractCursor { + /* Excluded from this release type: [kPipeline] */ + /* Excluded from this release type: [kOptions] */ + /* Excluded from this release type: __constructor */ + get pipeline(): Document[]; + clone(): AggregationCursor; + map(transform: (doc: TSchema) => T): AggregationCursor; + /* Excluded from this release type: _initialize */ + /** Execute the explain for the cursor */ + explain(): Promise; + explain(callback: Callback): void; + explain(verbosity: ExplainVerbosityLike): Promise; + /** Add a group stage to the aggregation pipeline */ + group($group: Document): AggregationCursor; + /** Add a limit stage to the aggregation pipeline */ + limit($limit: number): this; + /** Add a match stage to the aggregation pipeline */ + match($match: Document): this; + /** Add an out stage to the aggregation pipeline */ + out($out: { + db: string; + coll: string; + } | string): this; + /** + * Add a project stage to the aggregation pipeline + * + * @remarks + * In order to strictly type this function you must provide an interface + * that represents the effect of your projection on the result documents. + * + * By default chaining a projection to your cursor changes the returned type to the generic {@link Document} type. + * You should specify a parameterized type to have assertions on your final results. + * + * @example + * ```typescript + * // Best way + * const docs: AggregationCursor<{ a: number }> = cursor.project<{ a: number }>({ _id: 0, a: true }); + * // Flexible way + * const docs: AggregationCursor = cursor.project({ _id: 0, a: true }); + * ``` + * + * @remarks + * In order to strictly type this function you must provide an interface + * that represents the effect of your projection on the result documents. + * + * **Note for Typescript Users:** adding a transform changes the return type of the iteration of this cursor, + * it **does not** return a new instance of a cursor. This means when calling project, + * you should always assign the result to a new variable in order to get a correctly typed cursor variable. + * Take note of the following example: + * + * @example + * ```typescript + * const cursor: AggregationCursor<{ a: number; b: string }> = coll.aggregate([]); + * const projectCursor = cursor.project<{ a: number }>({ _id: 0, a: true }); + * const aPropOnlyArray: {a: number}[] = await projectCursor.toArray(); + * + * // or always use chaining and save the final cursor + * + * const cursor = coll.aggregate().project<{ a: string }>({ + * _id: 0, + * a: { $convert: { input: '$a', to: 'string' } + * }}); + * ``` + */ + project($project: Document): AggregationCursor; + /** Add a lookup stage to the aggregation pipeline */ + lookup($lookup: Document): this; + /** Add a redact stage to the aggregation pipeline */ + redact($redact: Document): this; + /** Add a skip stage to the aggregation pipeline */ + skip($skip: number): this; + /** Add a sort stage to the aggregation pipeline */ + sort($sort: Sort): this; + /** Add a unwind stage to the aggregation pipeline */ + unwind($unwind: Document | string): this; + /** @deprecated Add a geoNear stage to the aggregation pipeline */ + geoNear($geoNear: Document): this; +} + +/** @public */ +export declare interface AggregationCursorOptions extends AbstractCursorOptions, AggregateOptions { +} + +/** + * It is possible to search using alternative types in mongodb e.g. + * string types can be searched using a regex in mongo + * array types can be searched using their element type + * @public + */ +export declare type AlternativeType = T extends ReadonlyArray ? T | RegExpOrString : RegExpOrString; + +/** @public */ +export declare type AnyBulkWriteOperation = { + insertOne: InsertOneModel; +} | { + replaceOne: ReplaceOneModel; +} | { + updateOne: UpdateOneModel; +} | { + updateMany: UpdateManyModel; +} | { + deleteOne: DeleteOneModel; +} | { + deleteMany: DeleteManyModel; +}; + +/** @public */ +export declare type AnyError = MongoError | Error; + +/** @public */ +export declare type ArrayElement = Type extends ReadonlyArray ? Item : never; + +/** @public */ +export declare type ArrayOperator = { + $each?: Array>; + $slice?: number; + $position?: number; + $sort?: Sort; +}; + +/** @public */ +export declare interface Auth { + /** The username for auth */ + username?: string; + /** The password for auth */ + password?: string; +} + +/** @public */ +export declare const AuthMechanism: Readonly<{ + readonly MONGODB_AWS: "MONGODB-AWS"; + readonly MONGODB_CR: "MONGODB-CR"; + readonly MONGODB_DEFAULT: "DEFAULT"; + readonly MONGODB_GSSAPI: "GSSAPI"; + readonly MONGODB_PLAIN: "PLAIN"; + readonly MONGODB_SCRAM_SHA1: "SCRAM-SHA-1"; + readonly MONGODB_SCRAM_SHA256: "SCRAM-SHA-256"; + readonly MONGODB_X509: "MONGODB-X509"; +}>; + +/** @public */ +export declare type AuthMechanism = typeof AuthMechanism[keyof typeof AuthMechanism]; + +/** @public */ +export declare interface AuthMechanismProperties extends Document { + SERVICE_HOST?: string; + SERVICE_NAME?: string; + SERVICE_REALM?: string; + CANONICALIZE_HOST_NAME?: GSSAPICanonicalizationValue; + AWS_SESSION_TOKEN?: string; +} + +/** @public */ +export declare interface AutoEncrypter { + new (client: MongoClient, options: AutoEncryptionOptions): AutoEncrypter; + init(cb: Callback): void; + teardown(force: boolean, callback: Callback): void; + encrypt(ns: string, cmd: Document, options: any, callback: Callback): void; + decrypt(cmd: Document, options: any, callback: Callback): void; + /** @experimental */ + readonly cryptSharedLibVersionInfo: { + version: bigint; + versionStr: string; + } | null; +} + +/** @public */ +export declare const AutoEncryptionLoggerLevel: Readonly<{ + readonly FatalError: 0; + readonly Error: 1; + readonly Warning: 2; + readonly Info: 3; + readonly Trace: 4; +}>; + +/** @public */ +export declare type AutoEncryptionLoggerLevel = typeof AutoEncryptionLoggerLevel[keyof typeof AutoEncryptionLoggerLevel]; + +/** @public */ +export declare interface AutoEncryptionOptions { + /* Excluded from this release type: bson */ + /* Excluded from this release type: metadataClient */ + /** A `MongoClient` used to fetch keys from a key vault */ + keyVaultClient?: MongoClient; + /** The namespace where keys are stored in the key vault */ + keyVaultNamespace?: string; + /** Configuration options that are used by specific KMS providers during key generation, encryption, and decryption. */ + kmsProviders?: { + /** Configuration options for using 'aws' as your KMS provider */ + aws?: { + /** The access key used for the AWS KMS provider */ + accessKeyId: string; + /** The secret access key used for the AWS KMS provider */ + secretAccessKey: string; + /** + * An optional AWS session token that will be used as the + * X-Amz-Security-Token header for AWS requests. + */ + sessionToken?: string; + }; + /** Configuration options for using 'local' as your KMS provider */ + local?: { + /** + * The master key used to encrypt/decrypt data keys. + * A 96-byte long Buffer or base64 encoded string. + */ + key: Buffer | string; + }; + /** Configuration options for using 'azure' as your KMS provider */ + azure?: { + /** The tenant ID identifies the organization for the account */ + tenantId: string; + /** The client ID to authenticate a registered application */ + clientId: string; + /** The client secret to authenticate a registered application */ + clientSecret: string; + /** + * If present, a host with optional port. E.g. "example.com" or "example.com:443". + * This is optional, and only needed if customer is using a non-commercial Azure instance + * (e.g. a government or China account, which use different URLs). + * Defaults to "login.microsoftonline.com" + */ + identityPlatformEndpoint?: string | undefined; + }; + /** Configuration options for using 'gcp' as your KMS provider */ + gcp?: { + /** The service account email to authenticate */ + email: string; + /** A PKCS#8 encrypted key. This can either be a base64 string or a binary representation */ + privateKey: string | Buffer; + /** + * If present, a host with optional port. E.g. "example.com" or "example.com:443". + * Defaults to "oauth2.googleapis.com" + */ + endpoint?: string | undefined; + }; + /** + * Configuration options for using 'kmip' as your KMS provider + */ + kmip?: { + /** + * The output endpoint string. + * The endpoint consists of a hostname and port separated by a colon. + * E.g. "example.com:123". A port is always present. + */ + endpoint?: string; + }; + }; + /** + * A map of namespaces to a local JSON schema for encryption + * + * **NOTE**: Supplying options.schemaMap provides more security than relying on JSON Schemas obtained from the server. + * It protects against a malicious server advertising a false JSON Schema, which could trick the client into sending decrypted data that should be encrypted. + * Schemas supplied in the schemaMap only apply to configuring automatic encryption for client side encryption. + * Other validation rules in the JSON schema will not be enforced by the driver and will result in an error. + */ + schemaMap?: Document; + /** @experimental Public Technical Preview: Supply a schema for the encrypted fields in the document */ + encryptedFieldsMap?: Document; + /** Allows the user to bypass auto encryption, maintaining implicit decryption */ + bypassAutoEncryption?: boolean; + /** @experimental Public Technical Preview: Allows users to bypass query analysis */ + bypassQueryAnalysis?: boolean; + options?: { + /** An optional hook to catch logging messages from the underlying encryption engine */ + logger?: (level: AutoEncryptionLoggerLevel, message: string) => void; + }; + extraOptions?: { + /** + * A local process the driver communicates with to determine how to encrypt values in a command. + * Defaults to "mongodb://%2Fvar%2Fmongocryptd.sock" if domain sockets are available or "mongodb://localhost:27020" otherwise + */ + mongocryptdURI?: string; + /** If true, autoEncryption will not attempt to spawn a mongocryptd before connecting */ + mongocryptdBypassSpawn?: boolean; + /** The path to the mongocryptd executable on the system */ + mongocryptdSpawnPath?: string; + /** Command line arguments to use when auto-spawning a mongocryptd */ + mongocryptdSpawnArgs?: string[]; + /** + * Full path to a MongoDB Crypt shared library to be used (instead of mongocryptd). + * + * This needs to be the path to the file itself, not a directory. + * It can be an absolute or relative path. If the path is relative and + * its first component is `$ORIGIN`, it will be replaced by the directory + * containing the mongodb-client-encryption native addon file. Otherwise, + * the path will be interpreted relative to the current working directory. + * + * Currently, loading different MongoDB Crypt shared library files from different + * MongoClients in the same process is not supported. + * + * If this option is provided and no MongoDB Crypt shared library could be loaded + * from the specified location, creating the MongoClient will fail. + * + * If this option is not provided and `cryptSharedLibRequired` is not specified, + * the AutoEncrypter will attempt to spawn and/or use mongocryptd according + * to the mongocryptd-specific `extraOptions` options. + * + * Specifying a path prevents mongocryptd from being used as a fallback. + * + * Requires the MongoDB Crypt shared library, available in MongoDB 6.0 or higher. + */ + cryptSharedLibPath?: string; + /** + * If specified, never use mongocryptd and instead fail when the MongoDB Crypt + * shared library could not be loaded. + * + * This is always true when `cryptSharedLibPath` is specified. + * + * Requires the MongoDB Crypt shared library, available in MongoDB 6.0 or higher. + */ + cryptSharedLibRequired?: boolean; + /* Excluded from this release type: cryptSharedLibSearchPaths */ + }; + proxyOptions?: ProxyOptions; + /** The TLS options to use connecting to the KMS provider */ + tlsOptions?: { + aws?: AutoEncryptionTlsOptions; + local?: AutoEncryptionTlsOptions; + azure?: AutoEncryptionTlsOptions; + gcp?: AutoEncryptionTlsOptions; + kmip?: AutoEncryptionTlsOptions; + }; +} + +/** @public */ +export declare interface AutoEncryptionTlsOptions { + /** + * Specifies the location of a local .pem file that contains + * either the client's TLS/SSL certificate and key or only the + * client's TLS/SSL key when tlsCertificateFile is used to + * provide the certificate. + */ + tlsCertificateKeyFile?: string; + /** + * Specifies the password to de-crypt the tlsCertificateKeyFile. + */ + tlsCertificateKeyFilePassword?: string; + /** + * Specifies the location of a local .pem file that contains the + * root certificate chain from the Certificate Authority. + * This file is used to validate the certificate presented by the + * KMS provider. + */ + tlsCAFile?: string; +} + +/** + * Keeps the state of a unordered batch so we can rewrite the results + * correctly after command execution + * + * @public + */ +export declare class Batch { + originalZeroIndex: number; + currentIndex: number; + originalIndexes: number[]; + batchType: BatchType; + operations: T[]; + size: number; + sizeBytes: number; + constructor(batchType: BatchType, originalZeroIndex: number); +} + +/** @public */ +export declare const BatchType: Readonly<{ + readonly INSERT: 1; + readonly UPDATE: 2; + readonly DELETE: 3; +}>; + +/** @public */ +export declare type BatchType = typeof BatchType[keyof typeof BatchType]; + +export { Binary } + +/* Excluded from this release type: BinMsg */ + +/** @public */ +export declare type BitwiseFilter = number /** numeric bit mask */ | Binary /** BinData bit mask */ | ReadonlyArray; + +export { BSONRegExp } + +/** + * BSON Serialization options. + * @public + */ +export declare interface BSONSerializeOptions extends Omit, Omit { + /** Return BSON filled buffers from operations */ + raw?: boolean; + /** Enable utf8 validation when deserializing BSON documents. Defaults to true. */ + enableUtf8Validation?: boolean; +} + +export { BSONSymbol } + +/** @public */ +export declare const BSONType: Readonly<{ + readonly double: 1; + readonly string: 2; + readonly object: 3; + readonly array: 4; + readonly binData: 5; + readonly undefined: 6; + readonly objectId: 7; + readonly bool: 8; + readonly date: 9; + readonly null: 10; + readonly regex: 11; + readonly dbPointer: 12; + readonly javascript: 13; + readonly symbol: 14; + readonly javascriptWithScope: 15; + readonly int: 16; + readonly timestamp: 17; + readonly long: 18; + readonly decimal: 19; + readonly minKey: -1; + readonly maxKey: 127; +}>; + +/** @public */ +export declare type BSONType = typeof BSONType[keyof typeof BSONType]; + +/** @public */ +export declare type BSONTypeAlias = keyof typeof BSONType; + +/* Excluded from this release type: BufferPool */ + +/** @public */ +export declare abstract class BulkOperationBase { + isOrdered: boolean; + /* Excluded from this release type: s */ + operationId?: number; + /* Excluded from this release type: __constructor */ + /** + * Add a single insert document to the bulk operation + * + * @example + * ```js + * const bulkOp = collection.initializeOrderedBulkOp(); + * + * // Adds three inserts to the bulkOp. + * bulkOp + * .insert({ a: 1 }) + * .insert({ b: 2 }) + * .insert({ c: 3 }); + * await bulkOp.execute(); + * ``` + */ + insert(document: Document): BulkOperationBase; + /** + * Builds a find operation for an update/updateOne/delete/deleteOne/replaceOne. + * Returns a builder object used to complete the definition of the operation. + * + * @example + * ```js + * const bulkOp = collection.initializeOrderedBulkOp(); + * + * // Add an updateOne to the bulkOp + * bulkOp.find({ a: 1 }).updateOne({ $set: { b: 2 } }); + * + * // Add an updateMany to the bulkOp + * bulkOp.find({ c: 3 }).update({ $set: { d: 4 } }); + * + * // Add an upsert + * bulkOp.find({ e: 5 }).upsert().updateOne({ $set: { f: 6 } }); + * + * // Add a deletion + * bulkOp.find({ g: 7 }).deleteOne(); + * + * // Add a multi deletion + * bulkOp.find({ h: 8 }).delete(); + * + * // Add a replaceOne + * bulkOp.find({ i: 9 }).replaceOne({writeConcern: { j: 10 }}); + * + * // Update using a pipeline (requires Mongodb 4.2 or higher) + * bulk.find({ k: 11, y: { $exists: true }, z: { $exists: true } }).updateOne([ + * { $set: { total: { $sum: [ '$y', '$z' ] } } } + * ]); + * + * // All of the ops will now be executed + * await bulkOp.execute(); + * ``` + */ + find(selector: Document): FindOperators; + /** Specifies a raw operation to perform in the bulk write. */ + raw(op: AnyBulkWriteOperation): this; + get bsonOptions(): BSONSerializeOptions; + get writeConcern(): WriteConcern | undefined; + get batches(): Batch[]; + execute(options?: BulkWriteOptions): Promise; + execute(callback: Callback): void; + execute(options: BulkWriteOptions | undefined, callback: Callback): void; + execute(options?: BulkWriteOptions | Callback, callback?: Callback): Promise | void; + /* Excluded from this release type: handleWriteError */ + abstract addToOperationsList(batchType: BatchType, document: Document | UpdateStatement | DeleteStatement): this; +} + +/* Excluded from this release type: BulkOperationPrivate */ + +/** @public */ +export declare interface BulkResult { + ok: number; + writeErrors: WriteError[]; + writeConcernErrors: WriteConcernError[]; + insertedIds: Document[]; + nInserted: number; + nUpserted: number; + nMatched: number; + nModified: number; + nRemoved: number; + upserted: Document[]; + opTime?: Document; +} + +/** @public */ +export declare interface BulkWriteOperationError { + index: number; + code: number; + errmsg: string; + errInfo: Document; + op: Document | UpdateStatement | DeleteStatement; +} + +/** @public */ +export declare interface BulkWriteOptions extends CommandOperationOptions { + /** Allow driver to bypass schema validation in MongoDB 3.2 or higher. */ + bypassDocumentValidation?: boolean; + /** If true, when an insert fails, don't execute the remaining writes. If false, continue with remaining inserts when one fails. */ + ordered?: boolean; + /** @deprecated use `ordered` instead */ + keepGoing?: boolean; + /** Force server to assign _id values instead of driver. */ + forceServerObjectId?: boolean; + /** Map of parameter names and values that can be accessed using $$var (requires MongoDB 5.0). */ + let?: Document; +} + +/** + * @public + * The result of a bulk write. + */ +export declare class BulkWriteResult { + result: BulkResult; + /* Excluded from this release type: __constructor */ + /** Number of documents inserted. */ + get insertedCount(): number; + /** Number of documents matched for update. */ + get matchedCount(): number; + /** Number of documents modified. */ + get modifiedCount(): number; + /** Number of documents deleted. */ + get deletedCount(): number; + /** Number of documents upserted. */ + get upsertedCount(): number; + /** Upserted document generated Id's, hash key is the index of the originating operation */ + get upsertedIds(): { + [key: number]: any; + }; + /** Inserted document generated Id's, hash key is the index of the originating operation */ + get insertedIds(): { + [key: number]: any; + }; + /** Evaluates to true if the bulk operation correctly executes */ + get ok(): number; + /** The number of inserted documents */ + get nInserted(): number; + /** Number of upserted documents */ + get nUpserted(): number; + /** Number of matched documents */ + get nMatched(): number; + /** Number of documents updated physically on disk */ + get nModified(): number; + /** Number of removed documents */ + get nRemoved(): number; + /** Returns an array of all inserted ids */ + getInsertedIds(): Document[]; + /** Returns an array of all upserted ids */ + getUpsertedIds(): Document[]; + /** Returns the upserted id at the given index */ + getUpsertedIdAt(index: number): Document | undefined; + /** Returns raw internal result */ + getRawResponse(): Document; + /** Returns true if the bulk operation contains a write error */ + hasWriteErrors(): boolean; + /** Returns the number of write errors off the bulk operation */ + getWriteErrorCount(): number; + /** Returns a specific write error object */ + getWriteErrorAt(index: number): WriteError | undefined; + /** Retrieve all write errors */ + getWriteErrors(): WriteError[]; + /** Retrieve lastOp if available */ + getLastOp(): Document | undefined; + /** Retrieve the write concern error if one exists */ + getWriteConcernError(): WriteConcernError | undefined; + toJSON(): BulkResult; + toString(): string; + isOk(): boolean; +} + +/** + * MongoDB Driver style callback + * @public + */ +export declare type Callback = (error?: AnyError, result?: T) => void; + +/** @public */ +export declare class CancellationToken extends TypedEventEmitter<{ + cancel(): void; +}> { +} + +/** + * Creates a new Change Stream instance. Normally created using {@link Collection#watch|Collection.watch()}. + * @public + */ +export declare class ChangeStream> extends TypedEventEmitter> { + pipeline: Document[]; + options: ChangeStreamOptions; + parent: MongoClient | Db | Collection; + namespace: MongoDBNamespace; + type: symbol; + /* Excluded from this release type: cursor */ + streamOptions?: CursorStreamOptions; + /* Excluded from this release type: [kCursorStream] */ + /* Excluded from this release type: [kClosed] */ + /* Excluded from this release type: [kMode] */ + /** @event */ + static readonly RESPONSE: "response"; + /** @event */ + static readonly MORE: "more"; + /** @event */ + static readonly INIT: "init"; + /** @event */ + static readonly CLOSE: "close"; + /** + * Fired for each new matching change in the specified namespace. Attaching a `change` + * event listener to a Change Stream will switch the stream into flowing mode. Data will + * then be passed as soon as it is available. + * @event + */ + static readonly CHANGE: "change"; + /** @event */ + static readonly END: "end"; + /** @event */ + static readonly ERROR: "error"; + /** + * Emitted each time the change stream stores a new resume token. + * @event + */ + static readonly RESUME_TOKEN_CHANGED: "resumeTokenChanged"; + /* Excluded from this release type: __constructor */ + /* Excluded from this release type: cursorStream */ + /** The cached resume token that is used to resume after the most recently returned change. */ + get resumeToken(): ResumeToken; + /** Check if there is any document still available in the Change Stream */ + hasNext(): Promise; + hasNext(callback: Callback): void; + /** Get the next available document from the Change Stream. */ + next(): Promise; + next(callback: Callback): void; + /** + * Try to get the next available document from the Change Stream's cursor or `null` if an empty batch is returned + */ + tryNext(): Promise; + tryNext(callback: Callback): void; + /** Is the cursor closed */ + get closed(): boolean; + /** Close the Change Stream */ + close(): Promise; + close(callback: Callback): void; + /** + * Return a modified Readable stream including a possible transform method. + * + * NOTE: When using a Stream to process change stream events, the stream will + * NOT automatically resume in the case a resumable error is encountered. + * + * @throws MongoChangeStreamError if the underlying cursor or the change stream is closed + */ + stream(options?: CursorStreamOptions): Readable & AsyncIterable; + /* Excluded from this release type: _setIsEmitter */ + /* Excluded from this release type: _setIsIterator */ + /* Excluded from this release type: _createChangeStreamCursor */ + /* Excluded from this release type: _closeEmitterModeWithError */ + /* Excluded from this release type: _streamEvents */ + /* Excluded from this release type: _endStream */ + /* Excluded from this release type: _processChange */ + /* Excluded from this release type: _processErrorStreamMode */ + /* Excluded from this release type: _processErrorIteratorMode */ + /* Excluded from this release type: _processErrorIteratorModeCallback */ +} + +/* Excluded from this release type: ChangeStreamAggregateRawResult */ + +/** + * Only present when the `showExpandedEvents` flag is enabled. + * @public + * @see https://www.mongodb.com/docs/manual/reference/change-events/ + */ +export declare interface ChangeStreamCollModDocument extends ChangeStreamDocumentCommon, ChangeStreamDocumentCollectionUUID { + /** Describes the type of operation represented in this change notification */ + operationType: 'modify'; +} + +/** + * @public + * @see https://www.mongodb.com/docs/manual/reference/change-events/ + */ +export declare interface ChangeStreamCreateDocument extends ChangeStreamDocumentCommon, ChangeStreamDocumentCollectionUUID { + /** Describes the type of operation represented in this change notification */ + operationType: 'create'; +} + +/** + * Only present when the `showExpandedEvents` flag is enabled. + * @public + * @see https://www.mongodb.com/docs/manual/reference/change-events/ + */ +export declare interface ChangeStreamCreateIndexDocument extends ChangeStreamDocumentCommon, ChangeStreamDocumentCollectionUUID, ChangeStreamDocumentOperationDescription { + /** Describes the type of operation represented in this change notification */ + operationType: 'createIndexes'; +} + +/* Excluded from this release type: ChangeStreamCursor */ + +/* Excluded from this release type: ChangeStreamCursorOptions */ + +/** + * @public + * @see https://www.mongodb.com/docs/manual/reference/change-events/#delete-event + */ +export declare interface ChangeStreamDeleteDocument extends ChangeStreamDocumentCommon, ChangeStreamDocumentKey, ChangeStreamDocumentCollectionUUID { + /** Describes the type of operation represented in this change notification */ + operationType: 'delete'; + /** Namespace the delete event occured on */ + ns: ChangeStreamNameSpace; + /** + * Contains the pre-image of the modified or deleted document if the + * pre-image is available for the change event and either 'required' or + * 'whenAvailable' was specified for the 'fullDocumentBeforeChange' option + * when creating the change stream. If 'whenAvailable' was specified but the + * pre-image is unavailable, this will be explicitly set to null. + */ + fullDocumentBeforeChange?: TSchema; +} + +/** @public */ +export declare type ChangeStreamDocument = ChangeStreamInsertDocument | ChangeStreamUpdateDocument | ChangeStreamReplaceDocument | ChangeStreamDeleteDocument | ChangeStreamDropDocument | ChangeStreamRenameDocument | ChangeStreamDropDatabaseDocument | ChangeStreamInvalidateDocument | ChangeStreamCreateIndexDocument | ChangeStreamCreateDocument | ChangeStreamCollModDocument | ChangeStreamDropIndexDocument | ChangeStreamShardCollectionDocument | ChangeStreamReshardCollectionDocument | ChangeStreamRefineCollectionShardKeyDocument; + +/** @public */ +export declare interface ChangeStreamDocumentCollectionUUID { + /** + * The UUID (Binary subtype 4) of the collection that the operation was performed on. + * + * Only present when the `showExpandedEvents` flag is enabled. + * + * **NOTE:** collectionUUID will be converted to a NodeJS Buffer if the promoteBuffers + * flag is enabled. + * + * @since 6.1.0 + */ + collectionUUID: Binary; +} + +/** @public */ +export declare interface ChangeStreamDocumentCommon { + /** + * The id functions as an opaque token for use when resuming an interrupted + * change stream. + */ + _id: ResumeToken; + /** + * The timestamp from the oplog entry associated with the event. + * For events that happened as part of a multi-document transaction, the associated change stream + * notifications will have the same clusterTime value, namely the time when the transaction was committed. + * On a sharded cluster, events that occur on different shards can have the same clusterTime but be + * associated with different transactions or even not be associated with any transaction. + * To identify events for a single transaction, you can use the combination of lsid and txnNumber in the change stream event document. + */ + clusterTime?: Timestamp; + /** + * The transaction number. + * Only present if the operation is part of a multi-document transaction. + * + * **NOTE:** txnNumber can be a Long if promoteLongs is set to false + */ + txnNumber?: number; + /** + * The identifier for the session associated with the transaction. + * Only present if the operation is part of a multi-document transaction. + */ + lsid?: ServerSessionId; +} + +/** @public */ +export declare interface ChangeStreamDocumentKey { + /** + * For unsharded collections this contains a single field `_id`. + * For sharded collections, this will contain all the components of the shard key + */ + documentKey: { + _id: InferIdType; + [shardKey: string]: any; + }; +} + +/** @public */ +export declare interface ChangeStreamDocumentOperationDescription { + /** + * An description of the operation. + * + * Only present when the `showExpandedEvents` flag is enabled. + * + * @since 6.1.0 + */ + operationDescription?: Document; +} + +/** + * @public + * @see https://www.mongodb.com/docs/manual/reference/change-events/#dropdatabase-event + */ +export declare interface ChangeStreamDropDatabaseDocument extends ChangeStreamDocumentCommon { + /** Describes the type of operation represented in this change notification */ + operationType: 'dropDatabase'; + /** The database dropped */ + ns: { + db: string; + }; +} + +/** + * @public + * @see https://www.mongodb.com/docs/manual/reference/change-events/#drop-event + */ +export declare interface ChangeStreamDropDocument extends ChangeStreamDocumentCommon, ChangeStreamDocumentCollectionUUID { + /** Describes the type of operation represented in this change notification */ + operationType: 'drop'; + /** Namespace the drop event occured on */ + ns: ChangeStreamNameSpace; +} + +/** + * Only present when the `showExpandedEvents` flag is enabled. + * @public + * @see https://www.mongodb.com/docs/manual/reference/change-events/ + */ +export declare interface ChangeStreamDropIndexDocument extends ChangeStreamDocumentCommon, ChangeStreamDocumentCollectionUUID, ChangeStreamDocumentOperationDescription { + /** Describes the type of operation represented in this change notification */ + operationType: 'dropIndexes'; +} + +/** @public */ +export declare type ChangeStreamEvents> = { + resumeTokenChanged(token: ResumeToken): void; + init(response: any): void; + more(response?: any): void; + response(): void; + end(): void; + error(error: Error): void; + change(change: TChange): void; +} & AbstractCursorEvents; + +/** + * @public + * @see https://www.mongodb.com/docs/manual/reference/change-events/#insert-event + */ +export declare interface ChangeStreamInsertDocument extends ChangeStreamDocumentCommon, ChangeStreamDocumentKey, ChangeStreamDocumentCollectionUUID { + /** Describes the type of operation represented in this change notification */ + operationType: 'insert'; + /** This key will contain the document being inserted */ + fullDocument: TSchema; + /** Namespace the insert event occured on */ + ns: ChangeStreamNameSpace; +} + +/** + * @public + * @see https://www.mongodb.com/docs/manual/reference/change-events/#invalidate-event + */ +export declare interface ChangeStreamInvalidateDocument extends ChangeStreamDocumentCommon { + /** Describes the type of operation represented in this change notification */ + operationType: 'invalidate'; +} + +/** @public */ +export declare interface ChangeStreamNameSpace { + db: string; + coll: string; +} + +/** + * Options that can be passed to a ChangeStream. Note that startAfter, resumeAfter, and startAtOperationTime are all mutually exclusive, and the server will error if more than one is specified. + * @public + */ +export declare interface ChangeStreamOptions extends AggregateOptions { + /** + * Allowed values: 'updateLookup', 'whenAvailable', 'required'. + * + * When set to 'updateLookup', the change notification for partial updates + * will include both a delta describing the changes to the document as well + * as a copy of the entire document that was changed from some time after + * the change occurred. + * + * When set to 'whenAvailable', configures the change stream to return the + * post-image of the modified document for replace and update change events + * if the post-image for this event is available. + * + * When set to 'required', the same behavior as 'whenAvailable' except that + * an error is raised if the post-image is not available. + */ + fullDocument?: string; + /** + * Allowed values: 'whenAvailable', 'required', 'off'. + * + * The default is to not send a value, which is equivalent to 'off'. + * + * When set to 'whenAvailable', configures the change stream to return the + * pre-image of the modified document for replace, update, and delete change + * events if it is available. + * + * When set to 'required', the same behavior as 'whenAvailable' except that + * an error is raised if the pre-image is not available. + */ + fullDocumentBeforeChange?: string; + /** The maximum amount of time for the server to wait on new documents to satisfy a change stream query. */ + maxAwaitTimeMS?: number; + /** + * Allows you to start a changeStream after a specified event. + * @see https://docs.mongodb.com/manual/changeStreams/#resumeafter-for-change-streams + */ + resumeAfter?: ResumeToken; + /** + * Similar to resumeAfter, but will allow you to start after an invalidated event. + * @see https://docs.mongodb.com/manual/changeStreams/#startafter-for-change-streams + */ + startAfter?: ResumeToken; + /** Will start the changeStream after the specified operationTime. */ + startAtOperationTime?: OperationTime; + /** + * The number of documents to return per batch. + * @see https://docs.mongodb.com/manual/reference/command/aggregate + */ + batchSize?: number; + /** + * When enabled, configures the change stream to include extra change events. + * + * - createIndexes + * - dropIndexes + * - modify + * - create + * - shardCollection + * - reshardCollection + * - refineCollectionShardKey + */ + showExpandedEvents?: boolean; +} + +/** + * @public + * @see https://www.mongodb.com/docs/manual/reference/change-events/ + */ +export declare interface ChangeStreamRefineCollectionShardKeyDocument extends ChangeStreamDocumentCommon, ChangeStreamDocumentCollectionUUID, ChangeStreamDocumentOperationDescription { + /** Describes the type of operation represented in this change notification */ + operationType: 'refineCollectionShardKey'; +} + +/** + * @public + * @see https://www.mongodb.com/docs/manual/reference/change-events/#rename-event + */ +export declare interface ChangeStreamRenameDocument extends ChangeStreamDocumentCommon, ChangeStreamDocumentCollectionUUID { + /** Describes the type of operation represented in this change notification */ + operationType: 'rename'; + /** The new name for the `ns.coll` collection */ + to: { + db: string; + coll: string; + }; + /** The "from" namespace that the rename occured on */ + ns: ChangeStreamNameSpace; +} + +/** + * @public + * @see https://www.mongodb.com/docs/manual/reference/change-events/#replace-event + */ +export declare interface ChangeStreamReplaceDocument extends ChangeStreamDocumentCommon, ChangeStreamDocumentKey { + /** Describes the type of operation represented in this change notification */ + operationType: 'replace'; + /** The fullDocument of a replace event represents the document after the insert of the replacement document */ + fullDocument: TSchema; + /** Namespace the replace event occured on */ + ns: ChangeStreamNameSpace; + /** + * Contains the pre-image of the modified or deleted document if the + * pre-image is available for the change event and either 'required' or + * 'whenAvailable' was specified for the 'fullDocumentBeforeChange' option + * when creating the change stream. If 'whenAvailable' was specified but the + * pre-image is unavailable, this will be explicitly set to null. + */ + fullDocumentBeforeChange?: TSchema; +} + +/** + * @public + * @see https://www.mongodb.com/docs/manual/reference/change-events/ + */ +export declare interface ChangeStreamReshardCollectionDocument extends ChangeStreamDocumentCommon, ChangeStreamDocumentCollectionUUID, ChangeStreamDocumentOperationDescription { + /** Describes the type of operation represented in this change notification */ + operationType: 'reshardCollection'; +} + +/** + * @public + * @see https://www.mongodb.com/docs/manual/reference/change-events/ + */ +export declare interface ChangeStreamShardCollectionDocument extends ChangeStreamDocumentCommon, ChangeStreamDocumentCollectionUUID, ChangeStreamDocumentOperationDescription { + /** Describes the type of operation represented in this change notification */ + operationType: 'shardCollection'; +} + +/** + * @public + * @see https://www.mongodb.com/docs/manual/reference/change-events/#update-event + */ +export declare interface ChangeStreamUpdateDocument extends ChangeStreamDocumentCommon, ChangeStreamDocumentKey, ChangeStreamDocumentCollectionUUID { + /** Describes the type of operation represented in this change notification */ + operationType: 'update'; + /** + * This is only set if `fullDocument` is set to `'updateLookup'` + * Contains the point-in-time post-image of the modified document if the + * post-image is available and either 'required' or 'whenAvailable' was + * specified for the 'fullDocument' option when creating the change stream. + */ + fullDocument?: TSchema; + /** Contains a description of updated and removed fields in this operation */ + updateDescription: UpdateDescription; + /** Namespace the update event occured on */ + ns: ChangeStreamNameSpace; + /** + * Contains the pre-image of the modified or deleted document if the + * pre-image is available for the change event and either 'required' or + * 'whenAvailable' was specified for the 'fullDocumentBeforeChange' option + * when creating the change stream. If 'whenAvailable' was specified but the + * pre-image is unavailable, this will be explicitly set to null. + */ + fullDocumentBeforeChange?: TSchema; +} + +/** @public */ +export declare interface ClientMetadata { + driver: { + name: string; + version: string; + }; + os: { + type: string; + name: NodeJS.Platform; + architecture: string; + version: string; + }; + platform: string; + version?: string; + application?: { + name: string; + }; +} + +/** @public */ +export declare interface ClientMetadataOptions { + driverInfo?: { + name?: string; + version?: string; + platform?: string; + }; + appName?: string; +} + +/** + * A class representing a client session on the server + * + * NOTE: not meant to be instantiated directly. + * @public + */ +export declare class ClientSession extends TypedEventEmitter { + /* Excluded from this release type: client */ + /* Excluded from this release type: sessionPool */ + hasEnded: boolean; + clientOptions?: MongoOptions; + supports: { + causalConsistency: boolean; + }; + clusterTime?: ClusterTime; + operationTime?: Timestamp; + explicit: boolean; + /* Excluded from this release type: owner */ + defaultTransactionOptions: TransactionOptions; + transaction: Transaction; + /* Excluded from this release type: [kServerSession] */ + /* Excluded from this release type: [kSnapshotTime] */ + /* Excluded from this release type: [kSnapshotEnabled] */ + /* Excluded from this release type: [kPinnedConnection] */ + /* Excluded from this release type: [kTxnNumberIncrement] */ + /* Excluded from this release type: __constructor */ + /** The server id associated with this session */ + get id(): ServerSessionId | undefined; + get serverSession(): ServerSession; + /** Whether or not this session is configured for snapshot reads */ + get snapshotEnabled(): boolean; + get loadBalanced(): boolean; + /* Excluded from this release type: pinnedConnection */ + /* Excluded from this release type: pin */ + /* Excluded from this release type: unpin */ + get isPinned(): boolean; + /** + * Ends this session on the server + * + * @param options - Optional settings. Currently reserved for future use + * @param callback - Optional callback for completion of this operation + */ + endSession(): Promise; + endSession(callback: Callback): void; + endSession(options: EndSessionOptions): Promise; + endSession(options: EndSessionOptions, callback: Callback): void; + /** + * Advances the operationTime for a ClientSession. + * + * @param operationTime - the `BSON.Timestamp` of the operation type it is desired to advance to + */ + advanceOperationTime(operationTime: Timestamp): void; + /** + * Advances the clusterTime for a ClientSession to the provided clusterTime of another ClientSession + * + * @param clusterTime - the $clusterTime returned by the server from another session in the form of a document containing the `BSON.Timestamp` clusterTime and signature + */ + advanceClusterTime(clusterTime: ClusterTime): void; + /** + * Used to determine if this session equals another + * + * @param session - The session to compare to + */ + equals(session: ClientSession): boolean; + /** + * Increment the transaction number on the internal ServerSession + * + * @privateRemarks + * This helper increments a value stored on the client session that will be + * added to the serverSession's txnNumber upon applying it to a command. + * This is because the serverSession is lazily acquired after a connection is obtained + */ + incrementTransactionNumber(): void; + /** @returns whether this session is currently in a transaction or not */ + inTransaction(): boolean; + /** + * Starts a new transaction with the given options. + * + * @param options - Options for the transaction + */ + startTransaction(options?: TransactionOptions): void; + /** + * Commits the currently active transaction in this session. + * + * @param callback - An optional callback, a Promise will be returned if none is provided + */ + commitTransaction(): Promise; + commitTransaction(callback: Callback): void; + /** + * Aborts the currently active transaction in this session. + * + * @param callback - An optional callback, a Promise will be returned if none is provided + */ + abortTransaction(): Promise; + abortTransaction(callback: Callback): void; + /** + * This is here to ensure that ClientSession is never serialized to BSON. + */ + toBSON(): never; + /** + * Runs a provided callback within a transaction, retrying either the commitTransaction operation + * or entire transaction as needed (and when the error permits) to better ensure that + * the transaction can complete successfully. + * + * **IMPORTANT:** This method requires the user to return a Promise, and `await` all operations. + * Any callbacks that do not return a Promise will result in undefined behavior. + * + * @remarks + * This function: + * - Will return the command response from the final commitTransaction if every operation is successful (can be used as a truthy object) + * - Will return `undefined` if the transaction is explicitly aborted with `await session.abortTransaction()` + * - Will throw if one of the operations throws or `throw` statement is used inside the `withTransaction` callback + * + * Checkout a descriptive example here: + * @see https://www.mongodb.com/developer/quickstart/node-transactions/ + * + * @param fn - callback to run within a transaction + * @param options - optional settings for the transaction + * @returns A raw command response or undefined + */ + withTransaction(fn: WithTransactionCallback, options?: TransactionOptions): Promise; +} + +/** @public */ +export declare type ClientSessionEvents = { + ended(session: ClientSession): void; +}; + +/** @public */ +export declare interface ClientSessionOptions { + /** Whether causal consistency should be enabled on this session */ + causalConsistency?: boolean; + /** Whether all read operations should be read from the same snapshot for this session (NOTE: not compatible with `causalConsistency=true`) */ + snapshot?: boolean; + /** The default TransactionOptions to use for transactions started on this session. */ + defaultTransactionOptions?: TransactionOptions; + /* Excluded from this release type: owner */ + /* Excluded from this release type: explicit */ + /* Excluded from this release type: initialClusterTime */ +} + +/** @public */ +export declare interface CloseOptions { + force?: boolean; +} + +/** @public + * Configuration options for clustered collections + * TODO: NODE-4230 replace with normal manual link once it is on there. + * @see https://www.mongodb.com/docs/v5.3/core/clustered-collections/ + */ +export declare interface ClusteredCollectionOptions extends Document { + name?: string; + key: Document; + unique: boolean; +} + +/** @public */ +export declare interface ClusterTime { + clusterTime: Timestamp; + signature: { + hash: Binary; + keyId: Long; + }; +} + +export { Code } + +/** @public */ +export declare interface CollationOptions { + locale: string; + caseLevel?: boolean; + caseFirst?: string; + strength?: number; + numericOrdering?: boolean; + alternate?: string; + maxVariable?: string; + backwards?: boolean; + normalization?: boolean; +} + +/** + * The **Collection** class is an internal class that embodies a MongoDB collection + * allowing for insert/update/remove/find and other command operation on that MongoDB collection. + * + * **COLLECTION Cannot directly be instantiated** + * @public + * + * @example + * ```js + * const MongoClient = require('mongodb').MongoClient; + * const test = require('assert'); + * // Connection url + * const url = 'mongodb://localhost:27017'; + * // Database Name + * const dbName = 'test'; + * // Connect using MongoClient + * MongoClient.connect(url, function(err, client) { + * // Create a collection we want to drop later + * const col = client.db(dbName).collection('createIndexExample1'); + * // Show that duplicate records got dropped + * col.find({}).toArray(function(err, items) { + * expect(err).to.not.exist; + * test.equal(4, items.length); + * client.close(); + * }); + * }); + * ``` + */ +export declare class Collection { + /* Excluded from this release type: s */ + /* Excluded from this release type: __constructor */ + /** + * The name of the database this collection belongs to + */ + get dbName(): string; + /** + * The name of this collection + */ + get collectionName(): string; + /** + * The namespace of this collection, in the format `${this.dbName}.${this.collectionName}` + */ + get namespace(): string; + /** + * The current readConcern of the collection. If not explicitly defined for + * this collection, will be inherited from the parent DB + */ + get readConcern(): ReadConcern | undefined; + /** + * The current readPreference of the collection. If not explicitly defined for + * this collection, will be inherited from the parent DB + */ + get readPreference(): ReadPreference | undefined; + get bsonOptions(): BSONSerializeOptions; + /** + * The current writeConcern of the collection. If not explicitly defined for + * this collection, will be inherited from the parent DB + */ + get writeConcern(): WriteConcern | undefined; + /** The current index hint for the collection */ + get hint(): Hint | undefined; + set hint(v: Hint | undefined); + /** + * Inserts a single document into MongoDB. If documents passed in do not contain the **_id** field, + * one will be added to each of the documents missing it by the driver, mutating the document. This behavior + * can be overridden by setting the **forceServerObjectId** flag. + * + * @param doc - The document to insert + * @param options - Optional settings for the command + * @param callback - An optional callback, a Promise will be returned if none is provided + */ + insertOne(doc: OptionalUnlessRequiredId): Promise>; + insertOne(doc: OptionalUnlessRequiredId, callback: Callback>): void; + insertOne(doc: OptionalUnlessRequiredId, options: InsertOneOptions): Promise>; + insertOne(doc: OptionalUnlessRequiredId, options: InsertOneOptions, callback: Callback>): void; + /** + * Inserts an array of documents into MongoDB. If documents passed in do not contain the **_id** field, + * one will be added to each of the documents missing it by the driver, mutating the document. This behavior + * can be overridden by setting the **forceServerObjectId** flag. + * + * @param docs - The documents to insert + * @param options - Optional settings for the command + * @param callback - An optional callback, a Promise will be returned if none is provided + */ + insertMany(docs: OptionalUnlessRequiredId[]): Promise>; + insertMany(docs: OptionalUnlessRequiredId[], callback: Callback>): void; + insertMany(docs: OptionalUnlessRequiredId[], options: BulkWriteOptions): Promise>; + insertMany(docs: OptionalUnlessRequiredId[], options: BulkWriteOptions, callback: Callback>): void; + /** + * Perform a bulkWrite operation without a fluent API + * + * Legal operation types are + * + * ```js + * { insertOne: { document: { a: 1 } } } + * + * { updateOne: { filter: {a:2}, update: {$set: {a:2}}, upsert:true } } + * + * { updateMany: { filter: {a:2}, update: {$set: {a:2}}, upsert:true } } + * + * { updateMany: { filter: {}, update: {$set: {"a.$[i].x": 5}}, arrayFilters: [{ "i.x": 5 }]} } + * + * { deleteOne: { filter: {c:1} } } + * + * { deleteMany: { filter: {c:1} } } + * + * { replaceOne: { filter: {c:3}, replacement: {c:4}, upsert:true} } + *``` + * Please note that raw operations are no longer accepted as of driver version 4.0. + * + * If documents passed in do not contain the **_id** field, + * one will be added to each of the documents missing it by the driver, mutating the document. This behavior + * can be overridden by setting the **forceServerObjectId** flag. + * + * @param operations - Bulk operations to perform + * @param options - Optional settings for the command + * @param callback - An optional callback, a Promise will be returned if none is provided + * @throws MongoDriverError if operations is not an array + */ + bulkWrite(operations: AnyBulkWriteOperation[]): Promise; + bulkWrite(operations: AnyBulkWriteOperation[], callback: Callback): void; + bulkWrite(operations: AnyBulkWriteOperation[], options: BulkWriteOptions): Promise; + bulkWrite(operations: AnyBulkWriteOperation[], options: BulkWriteOptions, callback: Callback): void; + /** + * Update a single document in a collection + * + * @param filter - The filter used to select the document to update + * @param update - The update operations to be applied to the document + * @param options - Optional settings for the command + * @param callback - An optional callback, a Promise will be returned if none is provided + */ + updateOne(filter: Filter, update: UpdateFilter | Partial): Promise; + updateOne(filter: Filter, update: UpdateFilter | Partial, callback: Callback): void; + updateOne(filter: Filter, update: UpdateFilter | Partial, options: UpdateOptions): Promise; + updateOne(filter: Filter, update: UpdateFilter | Partial, options: UpdateOptions, callback: Callback): void; + /** + * Replace a document in a collection with another document + * + * @param filter - The filter used to select the document to replace + * @param replacement - The Document that replaces the matching document + * @param options - Optional settings for the command + * @param callback - An optional callback, a Promise will be returned if none is provided + */ + replaceOne(filter: Filter, replacement: WithoutId): Promise; + replaceOne(filter: Filter, replacement: WithoutId, callback: Callback): void; + replaceOne(filter: Filter, replacement: WithoutId, options: ReplaceOptions): Promise; + replaceOne(filter: Filter, replacement: WithoutId, options: ReplaceOptions, callback: Callback): void; + /** + * Update multiple documents in a collection + * + * @param filter - The filter used to select the documents to update + * @param update - The update operations to be applied to the documents + * @param options - Optional settings for the command + * @param callback - An optional callback, a Promise will be returned if none is provided + */ + updateMany(filter: Filter, update: UpdateFilter): Promise; + updateMany(filter: Filter, update: UpdateFilter, callback: Callback): void; + updateMany(filter: Filter, update: UpdateFilter, options: UpdateOptions): Promise; + updateMany(filter: Filter, update: UpdateFilter, options: UpdateOptions, callback: Callback): void; + /** + * Delete a document from a collection + * + * @param filter - The filter used to select the document to remove + * @param options - Optional settings for the command + * @param callback - An optional callback, a Promise will be returned if none is provided + */ + deleteOne(filter: Filter): Promise; + deleteOne(filter: Filter, callback: Callback): void; + deleteOne(filter: Filter, options: DeleteOptions): Promise; + deleteOne(filter: Filter, options: DeleteOptions, callback?: Callback): void; + /** + * Delete multiple documents from a collection + * + * @param filter - The filter used to select the documents to remove + * @param options - Optional settings for the command + * @param callback - An optional callback, a Promise will be returned if none is provided + */ + deleteMany(filter: Filter): Promise; + deleteMany(filter: Filter, callback: Callback): void; + deleteMany(filter: Filter, options: DeleteOptions): Promise; + deleteMany(filter: Filter, options: DeleteOptions, callback: Callback): void; + /** + * Rename the collection. + * + * @remarks + * This operation does not inherit options from the Db or MongoClient. + * + * @param newName - New name of of the collection. + * @param options - Optional settings for the command + * @param callback - An optional callback, a Promise will be returned if none is provided + */ + rename(newName: string): Promise; + rename(newName: string, callback: Callback): void; + rename(newName: string, options: RenameOptions): Promise; + rename(newName: string, options: RenameOptions, callback: Callback): void; + /** + * Drop the collection from the database, removing it permanently. New accesses will create a new collection. + * + * @param options - Optional settings for the command + * @param callback - An optional callback, a Promise will be returned if none is provided + */ + drop(): Promise; + drop(callback: Callback): void; + drop(options: DropCollectionOptions): Promise; + drop(options: DropCollectionOptions, callback: Callback): void; + /** + * Fetches the first document that matches the filter + * + * @param filter - Query for find Operation + * @param options - Optional settings for the command + * @param callback - An optional callback, a Promise will be returned if none is provided + */ + findOne(): Promise | null>; + findOne(callback: Callback | null>): void; + findOne(filter: Filter): Promise | null>; + findOne(filter: Filter, callback: Callback | null>): void; + findOne(filter: Filter, options: FindOptions): Promise | null>; + findOne(filter: Filter, options: FindOptions, callback: Callback | null>): void; + findOne(): Promise; + findOne(callback: Callback): void; + findOne(filter: Filter): Promise; + findOne(filter: Filter, options?: FindOptions): Promise; + findOne(filter: Filter, options?: FindOptions, callback?: Callback): void; + /** + * Creates a cursor for a filter that can be used to iterate over results from MongoDB + * + * @param filter - The filter predicate. If unspecified, then all documents in the collection will match the predicate + */ + find(): FindCursor>; + find(filter: Filter, options?: FindOptions): FindCursor>; + find(filter: Filter, options?: FindOptions): FindCursor; + /** + * Returns the options of the collection. + * + * @param options - Optional settings for the command + * @param callback - An optional callback, a Promise will be returned if none is provided + */ + options(): Promise; + options(callback: Callback): void; + options(options: OperationOptions): Promise; + options(options: OperationOptions, callback: Callback): void; + /** + * Returns if the collection is a capped collection + * + * @param options - Optional settings for the command + * @param callback - An optional callback, a Promise will be returned if none is provided + */ + isCapped(): Promise; + isCapped(callback: Callback): void; + isCapped(options: OperationOptions): Promise; + isCapped(options: OperationOptions, callback: Callback): void; + /** + * Creates an index on the db and collection collection. + * + * @param indexSpec - The field name or index specification to create an index for + * @param options - Optional settings for the command + * @param callback - An optional callback, a Promise will be returned if none is provided + * + * @example + * ```js + * const collection = client.db('foo').collection('bar'); + * + * await collection.createIndex({ a: 1, b: -1 }); + * + * // Alternate syntax for { c: 1, d: -1 } that ensures order of indexes + * await collection.createIndex([ [c, 1], [d, -1] ]); + * + * // Equivalent to { e: 1 } + * await collection.createIndex('e'); + * + * // Equivalent to { f: 1, g: 1 } + * await collection.createIndex(['f', 'g']) + * + * // Equivalent to { h: 1, i: -1 } + * await collection.createIndex([ { h: 1 }, { i: -1 } ]); + * + * // Equivalent to { j: 1, k: -1, l: 2d } + * await collection.createIndex(['j', ['k', -1], { l: '2d' }]) + * ``` + */ + createIndex(indexSpec: IndexSpecification): Promise; + createIndex(indexSpec: IndexSpecification, callback: Callback): void; + createIndex(indexSpec: IndexSpecification, options: CreateIndexesOptions): Promise; + createIndex(indexSpec: IndexSpecification, options: CreateIndexesOptions, callback: Callback): void; + /** + * Creates multiple indexes in the collection, this method is only supported for + * MongoDB 2.6 or higher. Earlier version of MongoDB will throw a command not supported + * error. + * + * **Note**: Unlike {@link Collection#createIndex| createIndex}, this function takes in raw index specifications. + * Index specifications are defined {@link http://docs.mongodb.org/manual/reference/command/createIndexes/| here}. + * + * @param indexSpecs - An array of index specifications to be created + * @param options - Optional settings for the command + * @param callback - An optional callback, a Promise will be returned if none is provided + * + * @example + * ```js + * const collection = client.db('foo').collection('bar'); + * await collection.createIndexes([ + * // Simple index on field fizz + * { + * key: { fizz: 1 }, + * } + * // wildcard index + * { + * key: { '$**': 1 } + * }, + * // named index on darmok and jalad + * { + * key: { darmok: 1, jalad: -1 } + * name: 'tanagra' + * } + * ]); + * ``` + */ + createIndexes(indexSpecs: IndexDescription[]): Promise; + createIndexes(indexSpecs: IndexDescription[], callback: Callback): void; + createIndexes(indexSpecs: IndexDescription[], options: CreateIndexesOptions): Promise; + createIndexes(indexSpecs: IndexDescription[], options: CreateIndexesOptions, callback: Callback): void; + /** + * Drops an index from this collection. + * + * @param indexName - Name of the index to drop. + * @param options - Optional settings for the command + * @param callback - An optional callback, a Promise will be returned if none is provided + */ + dropIndex(indexName: string): Promise; + dropIndex(indexName: string, callback: Callback): void; + dropIndex(indexName: string, options: DropIndexesOptions): Promise; + dropIndex(indexName: string, options: DropIndexesOptions, callback: Callback): void; + /** + * Drops all indexes from this collection. + * + * @param options - Optional settings for the command + * @param callback - An optional callback, a Promise will be returned if none is provided + */ + dropIndexes(): Promise; + dropIndexes(callback: Callback): void; + dropIndexes(options: DropIndexesOptions): Promise; + dropIndexes(options: DropIndexesOptions, callback: Callback): void; + /** + * Get the list of all indexes information for the collection. + * + * @param options - Optional settings for the command + */ + listIndexes(options?: ListIndexesOptions): ListIndexesCursor; + /** + * Checks if one or more indexes exist on the collection, fails on first non-existing index + * + * @param indexes - One or more index names to check. + * @param options - Optional settings for the command + * @param callback - An optional callback, a Promise will be returned if none is provided + */ + indexExists(indexes: string | string[]): Promise; + indexExists(indexes: string | string[], callback: Callback): void; + indexExists(indexes: string | string[], options: IndexInformationOptions): Promise; + indexExists(indexes: string | string[], options: IndexInformationOptions, callback: Callback): void; + /** + * Retrieves this collections index info. + * + * @param options - Optional settings for the command + * @param callback - An optional callback, a Promise will be returned if none is provided + */ + indexInformation(): Promise; + indexInformation(callback: Callback): void; + indexInformation(options: IndexInformationOptions): Promise; + indexInformation(options: IndexInformationOptions, callback: Callback): void; + /** + * Gets an estimate of the count of documents in a collection using collection metadata. + * This will always run a count command on all server versions. + * + * due to an oversight in versions 5.0.0-5.0.8 of MongoDB, the count command, + * which estimatedDocumentCount uses in its implementation, was not included in v1 of + * the Stable API, and so users of the Stable API with estimatedDocumentCount are + * recommended to upgrade their server version to 5.0.9+ or set apiStrict: false to avoid + * encountering errors. + * + * @see {@link https://www.mongodb.com/docs/manual/reference/command/count/#behavior|Count: Behavior} + * @param options - Optional settings for the command + * @param callback - An optional callback, a Promise will be returned if none is provided + */ + estimatedDocumentCount(): Promise; + estimatedDocumentCount(callback: Callback): void; + estimatedDocumentCount(options: EstimatedDocumentCountOptions): Promise; + estimatedDocumentCount(options: EstimatedDocumentCountOptions, callback: Callback): void; + /** + * Gets the number of documents matching the filter. + * For a fast count of the total documents in a collection see {@link Collection#estimatedDocumentCount| estimatedDocumentCount}. + * **Note**: When migrating from {@link Collection#count| count} to {@link Collection#countDocuments| countDocuments} + * the following query operators must be replaced: + * + * | Operator | Replacement | + * | -------- | ----------- | + * | `$where` | [`$expr`][1] | + * | `$near` | [`$geoWithin`][2] with [`$center`][3] | + * | `$nearSphere` | [`$geoWithin`][2] with [`$centerSphere`][4] | + * + * [1]: https://docs.mongodb.com/manual/reference/operator/query/expr/ + * [2]: https://docs.mongodb.com/manual/reference/operator/query/geoWithin/ + * [3]: https://docs.mongodb.com/manual/reference/operator/query/center/#op._S_center + * [4]: https://docs.mongodb.com/manual/reference/operator/query/centerSphere/#op._S_centerSphere + * + * @param filter - The filter for the count + * @param options - Optional settings for the command + * @param callback - An optional callback, a Promise will be returned if none is provided + * + * @see https://docs.mongodb.com/manual/reference/operator/query/expr/ + * @see https://docs.mongodb.com/manual/reference/operator/query/geoWithin/ + * @see https://docs.mongodb.com/manual/reference/operator/query/center/#op._S_center + * @see https://docs.mongodb.com/manual/reference/operator/query/centerSphere/#op._S_centerSphere + */ + countDocuments(): Promise; + countDocuments(callback: Callback): void; + countDocuments(filter: Filter): Promise; + countDocuments(callback: Callback): void; + countDocuments(filter: Filter, options: CountDocumentsOptions): Promise; + countDocuments(filter: Filter, options: CountDocumentsOptions, callback: Callback): void; + countDocuments(filter: Filter, callback: Callback): void; + /** + * The distinct command returns a list of distinct values for the given key across a collection. + * + * @param key - Field of the document to find distinct values for + * @param filter - The filter for filtering the set of documents to which we apply the distinct filter. + * @param options - Optional settings for the command + * @param callback - An optional callback, a Promise will be returned if none is provided + */ + distinct>(key: Key): Promise[Key]>>>; + distinct>(key: Key, callback: Callback[Key]>>>): void; + distinct>(key: Key, filter: Filter): Promise[Key]>>>; + distinct>(key: Key, filter: Filter, callback: Callback[Key]>>>): void; + distinct>(key: Key, filter: Filter, options: DistinctOptions): Promise[Key]>>>; + distinct>(key: Key, filter: Filter, options: DistinctOptions, callback: Callback[Key]>>>): void; + distinct(key: string): Promise; + distinct(key: string, callback: Callback): void; + distinct(key: string, filter: Filter): Promise; + distinct(key: string, filter: Filter, callback: Callback): void; + distinct(key: string, filter: Filter, options: DistinctOptions): Promise; + distinct(key: string, filter: Filter, options: DistinctOptions, callback: Callback): void; + /** + * Retrieve all the indexes on the collection. + * + * @param options - Optional settings for the command + * @param callback - An optional callback, a Promise will be returned if none is provided + */ + indexes(): Promise; + indexes(callback: Callback): void; + indexes(options: IndexInformationOptions): Promise; + indexes(options: IndexInformationOptions, callback: Callback): void; + /** + * Get all the collection statistics. + * + * @param options - Optional settings for the command + * @param callback - An optional callback, a Promise will be returned if none is provided + */ + stats(): Promise; + stats(callback: Callback): void; + stats(options: CollStatsOptions): Promise; + stats(options: CollStatsOptions, callback: Callback): void; + /** + * Find a document and delete it in one atomic operation. Requires a write lock for the duration of the operation. + * + * @param filter - The filter used to select the document to remove + * @param options - Optional settings for the command + * @param callback - An optional callback, a Promise will be returned if none is provided + */ + findOneAndDelete(filter: Filter): Promise>; + findOneAndDelete(filter: Filter, options: FindOneAndDeleteOptions): Promise>; + findOneAndDelete(filter: Filter, callback: Callback>): void; + findOneAndDelete(filter: Filter, options: FindOneAndDeleteOptions, callback: Callback>): void; + /** + * Find a document and replace it in one atomic operation. Requires a write lock for the duration of the operation. + * + * @param filter - The filter used to select the document to replace + * @param replacement - The Document that replaces the matching document + * @param options - Optional settings for the command + * @param callback - An optional callback, a Promise will be returned if none is provided + */ + findOneAndReplace(filter: Filter, replacement: WithoutId): Promise>; + findOneAndReplace(filter: Filter, replacement: WithoutId, callback: Callback>): void; + findOneAndReplace(filter: Filter, replacement: WithoutId, options: FindOneAndReplaceOptions): Promise>; + findOneAndReplace(filter: Filter, replacement: WithoutId, options: FindOneAndReplaceOptions, callback: Callback>): void; + /** + * Find a document and update it in one atomic operation. Requires a write lock for the duration of the operation. + * + * @param filter - The filter used to select the document to update + * @param update - Update operations to be performed on the document + * @param options - Optional settings for the command + * @param callback - An optional callback, a Promise will be returned if none is provided + */ + findOneAndUpdate(filter: Filter, update: UpdateFilter): Promise>; + findOneAndUpdate(filter: Filter, update: UpdateFilter, callback: Callback>): void; + findOneAndUpdate(filter: Filter, update: UpdateFilter, options: FindOneAndUpdateOptions): Promise>; + findOneAndUpdate(filter: Filter, update: UpdateFilter, options: FindOneAndUpdateOptions, callback: Callback>): void; + /** + * Execute an aggregation framework pipeline against the collection, needs MongoDB \>= 2.2 + * + * @param pipeline - An array of aggregation pipelines to execute + * @param options - Optional settings for the command + */ + aggregate(pipeline?: Document[], options?: AggregateOptions): AggregationCursor; + /** + * Create a new Change Stream, watching for new changes (insertions, updates, replacements, deletions, and invalidations) in this collection. + * + * @remarks + * watch() accepts two generic arguments for distinct usecases: + * - The first is to override the schema that may be defined for this specific collection + * - The second is to override the shape of the change stream document entirely, if it is not provided the type will default to ChangeStreamDocument of the first argument + * @example + * By just providing the first argument I can type the change to be `ChangeStreamDocument<{ _id: number }>` + * ```ts + * collection.watch<{ _id: number }>() + * .on('change', change => console.log(change._id.toFixed(4))); + * ``` + * + * @example + * Passing a second argument provides a way to reflect the type changes caused by an advanced pipeline. + * Here, we are using a pipeline to have MongoDB filter for insert changes only and add a comment. + * No need start from scratch on the ChangeStreamInsertDocument type! + * By using an intersection we can save time and ensure defaults remain the same type! + * ```ts + * collection + * .watch & { comment: string }>([ + * { $addFields: { comment: 'big changes' } }, + * { $match: { operationType: 'insert' } } + * ]) + * .on('change', change => { + * change.comment.startsWith('big'); + * change.operationType === 'insert'; + * // No need to narrow in code because the generics did that for us! + * expectType(change.fullDocument); + * }); + * ``` + * + * @param pipeline - An array of {@link https://docs.mongodb.com/manual/reference/operator/aggregation-pipeline/|aggregation pipeline stages} through which to pass change stream documents. This allows for filtering (using $match) and manipulating the change stream documents. + * @param options - Optional settings for the command + * @typeParam TLocal - Type of the data being detected by the change stream + * @typeParam TChange - Type of the whole change stream document emitted + */ + watch>(pipeline?: Document[], options?: ChangeStreamOptions): ChangeStream; + /** + * Run Map Reduce across a collection. Be aware that the inline option for out will return an array of results not a collection. + * + * @deprecated collection.mapReduce is deprecated. Use the aggregation pipeline instead. Visit https://docs.mongodb.com/manual/reference/map-reduce-to-aggregation-pipeline for more information on how to translate map-reduce operations to the aggregation pipeline. + * @param map - The mapping function. + * @param reduce - The reduce function. + * @param options - Optional settings for the command + * @param callback - An optional callback, a Promise will be returned if none is provided + */ + mapReduce(map: string | MapFunction, reduce: string | ReduceFunction): Promise; + mapReduce(map: string | MapFunction, reduce: string | ReduceFunction, callback: Callback): void; + mapReduce(map: string | MapFunction, reduce: string | ReduceFunction, options: MapReduceOptions): Promise; + mapReduce(map: string | MapFunction, reduce: string | ReduceFunction, options: MapReduceOptions, callback: Callback): void; + /** + * Initiate an Out of order batch write operation. All operations will be buffered into insert/update/remove commands executed out of order. + * + * @throws MongoNotConnectedError + * @remarks + * **NOTE:** MongoClient must be connected prior to calling this method due to a known limitation in this legacy implemenation. + * However, `collection.bulkWrite()` provides an equivalent API that does not require prior connecting. + */ + initializeUnorderedBulkOp(options?: BulkWriteOptions): UnorderedBulkOperation; + /** + * Initiate an In order bulk write operation. Operations will be serially executed in the order they are added, creating a new operation for each switch in types. + * + * @throws MongoNotConnectedError + * @remarks + * **NOTE:** MongoClient must be connected prior to calling this method due to a known limitation in this legacy implemenation. + * However, `collection.bulkWrite()` provides an equivalent API that does not require prior connecting. + */ + initializeOrderedBulkOp(options?: BulkWriteOptions): OrderedBulkOperation; + /** Get the db scoped logger */ + getLogger(): Logger; + get logger(): Logger; + /** + * Inserts a single document or a an array of documents into MongoDB. If documents passed in do not contain the **_id** field, + * one will be added to each of the documents missing it by the driver, mutating the document. This behavior + * can be overridden by setting the **forceServerObjectId** flag. + * + * @deprecated Use insertOne, insertMany or bulkWrite instead. + * @param docs - The documents to insert + * @param options - Optional settings for the command + * @param callback - An optional callback, a Promise will be returned if none is provided + */ + insert(docs: OptionalUnlessRequiredId[], options: BulkWriteOptions, callback: Callback>): Promise> | void; + /** + * Updates documents. + * + * @deprecated use updateOne, updateMany or bulkWrite + * @param selector - The selector for the update operation. + * @param update - The update operations to be applied to the documents + * @param options - Optional settings for the command + * @param callback - An optional callback, a Promise will be returned if none is provided + */ + update(selector: Filter, update: UpdateFilter, options: UpdateOptions, callback: Callback): Promise | void; + /** + * Remove documents. + * + * @deprecated use deleteOne, deleteMany or bulkWrite + * @param selector - The selector for the update operation. + * @param options - Optional settings for the command + * @param callback - An optional callback, a Promise will be returned if none is provided + */ + remove(selector: Filter, options: DeleteOptions, callback: Callback): Promise | void; + /** + * An estimated count of matching documents in the db to a filter. + * + * **NOTE:** This method has been deprecated, since it does not provide an accurate count of the documents + * in a collection. To obtain an accurate count of documents in the collection, use {@link Collection#countDocuments| countDocuments}. + * To obtain an estimated count of all documents in the collection, use {@link Collection#estimatedDocumentCount| estimatedDocumentCount}. + * + * @deprecated use {@link Collection#countDocuments| countDocuments} or {@link Collection#estimatedDocumentCount| estimatedDocumentCount} instead + * + * @param filter - The filter for the count. + * @param options - Optional settings for the command + * @param callback - An optional callback, a Promise will be returned if none is provided + */ + count(): Promise; + count(callback: Callback): void; + count(filter: Filter): Promise; + count(filter: Filter, callback: Callback): void; + count(filter: Filter, options: CountOptions): Promise; + count(filter: Filter, options: CountOptions, callback: Callback): Promise | void; +} + +/** @public */ +export declare interface CollectionInfo extends Document { + name: string; + type?: string; + options?: Document; + info?: { + readOnly?: false; + uuid?: Binary; + }; + idIndex?: Document; +} + +/** @public */ +export declare interface CollectionOptions extends BSONSerializeOptions, WriteConcernOptions, LoggerOptions { + /** + * @deprecated Use readPreference instead + */ + slaveOk?: boolean; + /** Specify a read concern for the collection. (only MongoDB 3.2 or higher supported) */ + readConcern?: ReadConcernLike; + /** The preferred read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST). */ + readPreference?: ReadPreferenceLike; +} + +/* Excluded from this release type: CollectionPrivate */ + +/** + * @public + * @see https://docs.mongodb.org/manual/reference/command/collStats/ + */ +export declare interface CollStats extends Document { + /** Namespace */ + ns: string; + /** Number of documents */ + count: number; + /** Collection size in bytes */ + size: number; + /** Average object size in bytes */ + avgObjSize: number; + /** (Pre)allocated space for the collection in bytes */ + storageSize: number; + /** Number of extents (contiguously allocated chunks of datafile space) */ + numExtents: number; + /** Number of indexes */ + nindexes: number; + /** Size of the most recently created extent in bytes */ + lastExtentSize: number; + /** Padding can speed up updates if documents grow */ + paddingFactor: number; + /** A number that indicates the user-set flags on the collection. userFlags only appears when using the mmapv1 storage engine */ + userFlags?: number; + /** Total index size in bytes */ + totalIndexSize: number; + /** Size of specific indexes in bytes */ + indexSizes: { + _id_: number; + [index: string]: number; + }; + /** `true` if the collection is capped */ + capped: boolean; + /** The maximum number of documents that may be present in a capped collection */ + max: number; + /** The maximum size of a capped collection */ + maxSize: number; + /** This document contains data reported directly by the WiredTiger engine and other data for internal diagnostic use */ + wiredTiger?: WiredTigerData; + /** The fields in this document are the names of the indexes, while the values themselves are documents that contain statistics for the index provided by the storage engine */ + indexDetails?: any; + ok: number; + /** The amount of storage available for reuse. The scale argument affects this value. */ + freeStorageSize?: number; + /** An array that contains the names of the indexes that are currently being built on the collection */ + indexBuilds?: number; + /** The sum of the storageSize and totalIndexSize. The scale argument affects this value */ + totalSize: number; + /** The scale value used by the command. */ + scaleFactor: number; +} + +/** @public */ +export declare interface CollStatsOptions extends CommandOperationOptions { + /** Divide the returned sizes by scale value. */ + scale?: number; +} + +/** + * An event indicating the failure of a given command + * @public + * @category Event + */ +export declare class CommandFailedEvent { + address: string; + connectionId?: string | number; + requestId: number; + duration: number; + commandName: string; + failure: Error; + serviceId?: ObjectId; + /* Excluded from this release type: __constructor */ + get hasServiceId(): boolean; +} + +/* Excluded from this release type: CommandOperation */ + +/** @public */ +export declare interface CommandOperationOptions extends OperationOptions, WriteConcernOptions, ExplainOptions { + /** @deprecated This option does nothing */ + fullResponse?: boolean; + /** Specify a read concern and level for the collection. (only MongoDB 3.2 or higher supported) */ + readConcern?: ReadConcernLike; + /** Collation */ + collation?: CollationOptions; + maxTimeMS?: number; + /** + * Comment to apply to the operation. + * + * In server versions pre-4.4, 'comment' must be string. A server + * error will be thrown if any other type is provided. + * + * In server versions 4.4 and above, 'comment' can be any valid BSON type. + */ + comment?: unknown; + /** Should retry failed writes */ + retryWrites?: boolean; + dbName?: string; + authdb?: string; + noResponse?: boolean; +} + +/* Excluded from this release type: CommandOptions */ + +/** + * An event indicating the start of a given + * @public + * @category Event + */ +export declare class CommandStartedEvent { + commandObj?: Document; + requestId: number; + databaseName: string; + commandName: string; + command: Document; + address: string; + connectionId?: string | number; + serviceId?: ObjectId; + /* Excluded from this release type: __constructor */ + get hasServiceId(): boolean; +} + +/** + * An event indicating the success of a given command + * @public + * @category Event + */ +export declare class CommandSucceededEvent { + address: string; + connectionId?: string | number; + requestId: number; + duration: number; + commandName: string; + reply: unknown; + serviceId?: ObjectId; + /* Excluded from this release type: __constructor */ + get hasServiceId(): boolean; +} + +/** @public */ +export declare type CommonEvents = 'newListener' | 'removeListener'; + +/** @public */ +export declare const Compressor: Readonly<{ + readonly none: 0; + readonly snappy: 1; + readonly zlib: 2; + readonly zstd: 3; +}>; + +/** @public */ +export declare type Compressor = typeof Compressor[CompressorName]; + +/** @public */ +export declare type CompressorName = keyof typeof Compressor; + +/** @public */ +export declare type Condition = AlternativeType | FilterOperators>; + +/* Excluded from this release type: Connection */ + +/** + * An event published when a connection is checked into the connection pool + * @public + * @category Event + */ +export declare class ConnectionCheckedInEvent extends ConnectionPoolMonitoringEvent { + /** The id of the connection */ + connectionId: number | ''; + /* Excluded from this release type: __constructor */ +} + +/** + * An event published when a connection is checked out of the connection pool + * @public + * @category Event + */ +export declare class ConnectionCheckedOutEvent extends ConnectionPoolMonitoringEvent { + /** The id of the connection */ + connectionId: number | ''; + /* Excluded from this release type: __constructor */ +} + +/** + * An event published when a request to check a connection out fails + * @public + * @category Event + */ +export declare class ConnectionCheckOutFailedEvent extends ConnectionPoolMonitoringEvent { + /** The reason the attempt to check out failed */ + reason: AnyError | string; + /* Excluded from this release type: __constructor */ +} + +/** + * An event published when a request to check a connection out begins + * @public + * @category Event + */ +export declare class ConnectionCheckOutStartedEvent extends ConnectionPoolMonitoringEvent { + /* Excluded from this release type: __constructor */ +} + +/** + * An event published when a connection is closed + * @public + * @category Event + */ +export declare class ConnectionClosedEvent extends ConnectionPoolMonitoringEvent { + /** The id of the connection */ + connectionId: number | ''; + /** The reason the connection was closed */ + reason: string; + serviceId?: ObjectId; + /* Excluded from this release type: __constructor */ +} + +/** + * An event published when a connection pool creates a new connection + * @public + * @category Event + */ +export declare class ConnectionCreatedEvent extends ConnectionPoolMonitoringEvent { + /** A monotonically increasing, per-pool id for the newly created connection */ + connectionId: number | ''; + /* Excluded from this release type: __constructor */ +} + +/** @public */ +export declare type ConnectionEvents = { + commandStarted(event: CommandStartedEvent): void; + commandSucceeded(event: CommandSucceededEvent): void; + commandFailed(event: CommandFailedEvent): void; + clusterTimeReceived(clusterTime: Document): void; + close(): void; + message(message: any): void; + pinned(pinType: string): void; + unpinned(pinType: string): void; +}; + +/** @public */ +export declare interface ConnectionOptions extends SupportedNodeConnectionOptions, StreamDescriptionOptions, ProxyOptions { + id: number | ''; + generation: number; + hostAddress: HostAddress; + autoEncrypter?: AutoEncrypter; + serverApi?: ServerApi; + monitorCommands: boolean; + /* Excluded from this release type: connectionType */ + credentials?: MongoCredentials; + connectTimeoutMS?: number; + tls: boolean; + keepAlive?: boolean; + keepAliveInitialDelay?: number; + noDelay?: boolean; + socketTimeoutMS?: number; + cancellationToken?: CancellationToken; + metadata: ClientMetadata; +} + +/* Excluded from this release type: ConnectionPool */ + +/** + * An event published when a connection pool is cleared + * @public + * @category Event + */ +export declare class ConnectionPoolClearedEvent extends ConnectionPoolMonitoringEvent { + /* Excluded from this release type: serviceId */ + /* Excluded from this release type: __constructor */ +} + +/** + * An event published when a connection pool is closed + * @public + * @category Event + */ +export declare class ConnectionPoolClosedEvent extends ConnectionPoolMonitoringEvent { + /* Excluded from this release type: __constructor */ +} + +/** + * An event published when a connection pool is created + * @public + * @category Event + */ +export declare class ConnectionPoolCreatedEvent extends ConnectionPoolMonitoringEvent { + /** The options used to create this connection pool */ + options?: ConnectionPoolOptions; + /* Excluded from this release type: __constructor */ +} + +/** @public */ +export declare type ConnectionPoolEvents = { + connectionPoolCreated(event: ConnectionPoolCreatedEvent): void; + connectionPoolClosed(event: ConnectionPoolClosedEvent): void; + connectionPoolCleared(event: ConnectionPoolClearedEvent): void; + connectionCreated(event: ConnectionCreatedEvent): void; + connectionReady(event: ConnectionReadyEvent): void; + connectionClosed(event: ConnectionClosedEvent): void; + connectionCheckOutStarted(event: ConnectionCheckOutStartedEvent): void; + connectionCheckOutFailed(event: ConnectionCheckOutFailedEvent): void; + connectionCheckedOut(event: ConnectionCheckedOutEvent): void; + connectionCheckedIn(event: ConnectionCheckedInEvent): void; +} & Omit; + +/* Excluded from this release type: ConnectionPoolMetrics */ + +/** + * The base export class for all monitoring events published from the connection pool + * @public + * @category Event + */ +export declare class ConnectionPoolMonitoringEvent { + /** A timestamp when the event was created */ + time: Date; + /** The address (host/port pair) of the pool */ + address: string; + /* Excluded from this release type: __constructor */ +} + +/** @public */ +export declare interface ConnectionPoolOptions extends Omit { + /** The maximum number of connections that may be associated with a pool at a given time. This includes in use and available connections. */ + maxPoolSize: number; + /** The minimum number of connections that MUST exist at any moment in a single connection pool. */ + minPoolSize: number; + /** The maximum number of connections that may be in the process of being established concurrently by the connection pool. */ + maxConnecting: number; + /** The maximum amount of time a connection should remain idle in the connection pool before being marked idle. */ + maxIdleTimeMS: number; + /** The maximum amount of time operation execution should wait for a connection to become available. The default is 0 which means there is no limit. */ + waitQueueTimeoutMS: number; + /** If we are in load balancer mode. */ + loadBalanced: boolean; +} + +/** + * An event published when a connection is ready for use + * @public + * @category Event + */ +export declare class ConnectionReadyEvent extends ConnectionPoolMonitoringEvent { + /** The id of the connection */ + connectionId: number | ''; + /* Excluded from this release type: __constructor */ +} + +/** @public */ +export declare interface ConnectOptions { + readPreference?: ReadPreference; +} + +/** @public */ +export declare interface CountDocumentsOptions extends AggregateOptions { + /** The number of documents to skip. */ + skip?: number; + /** The maximum amounts to count before aborting. */ + limit?: number; +} + +/** @public */ +export declare interface CountOptions extends CommandOperationOptions { + /** The number of documents to skip. */ + skip?: number; + /** The maximum amounts to count before aborting. */ + limit?: number; + /** Number of milliseconds to wait before aborting the query. */ + maxTimeMS?: number; + /** An index name hint for the query. */ + hint?: string | Document; +} + +/** @public */ +export declare interface CreateCollectionOptions extends CommandOperationOptions { + /** Returns an error if the collection does not exist */ + strict?: boolean; + /** Create a capped collection */ + capped?: boolean; + /** @deprecated Create an index on the _id field of the document, True by default on MongoDB 2.6 - 3.0 */ + autoIndexId?: boolean; + /** The size of the capped collection in bytes */ + size?: number; + /** The maximum number of documents in the capped collection */ + max?: number; + /** Available for the MMAPv1 storage engine only to set the usePowerOf2Sizes and the noPadding flag */ + flags?: number; + /** Allows users to specify configuration to the storage engine on a per-collection basis when creating a collection on MongoDB 3.0 or higher */ + storageEngine?: Document; + /** Allows users to specify validation rules or expressions for the collection. For more information, see Document Validation on MongoDB 3.2 or higher */ + validator?: Document; + /** Determines how strictly MongoDB applies the validation rules to existing documents during an update on MongoDB 3.2 or higher */ + validationLevel?: string; + /** Determines whether to error on invalid documents or just warn about the violations but allow invalid documents to be inserted on MongoDB 3.2 or higher */ + validationAction?: string; + /** Allows users to specify a default configuration for indexes when creating a collection on MongoDB 3.2 or higher */ + indexOptionDefaults?: Document; + /** The name of the source collection or view from which to create the view. The name is not the full namespace of the collection or view; i.e. does not include the database name and implies the same database as the view to create on MongoDB 3.4 or higher */ + viewOn?: string; + /** An array that consists of the aggregation pipeline stage. Creates the view by applying the specified pipeline to the viewOn collection or view on MongoDB 3.4 or higher */ + pipeline?: Document[]; + /** A primary key factory function for generation of custom _id keys. */ + pkFactory?: PkFactory; + /** A document specifying configuration options for timeseries collections. */ + timeseries?: TimeSeriesCollectionOptions; + /** A document specifying configuration options for clustered collections. For MongoDB 5.3 and above. */ + clusteredIndex?: ClusteredCollectionOptions; + /** The number of seconds after which a document in a timeseries or clustered collection expires. */ + expireAfterSeconds?: number; + /** @experimental */ + encryptedFields?: Document; + /** + * If set, enables pre-update and post-update document events to be included for any + * change streams that listen on this collection. + */ + changeStreamPreAndPostImages?: { + enabled: boolean; + }; +} + +/** @public */ +export declare interface CreateIndexesOptions extends CommandOperationOptions { + /** Creates the index in the background, yielding whenever possible. */ + background?: boolean; + /** Creates an unique index. */ + unique?: boolean; + /** Override the autogenerated index name (useful if the resulting name is larger than 128 bytes) */ + name?: string; + /** Creates a partial index based on the given filter object (MongoDB 3.2 or higher) */ + partialFilterExpression?: Document; + /** Creates a sparse index. */ + sparse?: boolean; + /** Allows you to expire data on indexes applied to a data (MongoDB 2.2 or higher) */ + expireAfterSeconds?: number; + /** Allows users to configure the storage engine on a per-index basis when creating an index. (MongoDB 3.0 or higher) */ + storageEngine?: Document; + /** (MongoDB 4.4. or higher) Specifies how many data-bearing members of a replica set, including the primary, must complete the index builds successfully before the primary marks the indexes as ready. This option accepts the same values for the "w" field in a write concern plus "votingMembers", which indicates all voting data-bearing nodes. */ + commitQuorum?: number | string; + /** Specifies the index version number, either 0 or 1. */ + version?: number; + weights?: Document; + default_language?: string; + language_override?: string; + textIndexVersion?: number; + '2dsphereIndexVersion'?: number; + bits?: number; + /** For geospatial indexes set the lower bound for the co-ordinates. */ + min?: number; + /** For geospatial indexes set the high bound for the co-ordinates. */ + max?: number; + bucketSize?: number; + wildcardProjection?: Document; + /** Specifies that the index should exist on the target collection but should not be used by the query planner when executing operations. (MongoDB 4.4 or higher) */ + hidden?: boolean; +} + +/** @public */ +export declare const CURSOR_FLAGS: readonly ["tailable", "oplogReplay", "noCursorTimeout", "awaitData", "exhaust", "partial"]; + +/** @public + * @deprecated This interface is deprecated */ +export declare interface CursorCloseOptions { + /** Bypass calling killCursors when closing the cursor. */ + /** @deprecated the skipKillCursors option is deprecated */ + skipKillCursors?: boolean; +} + +/** @public */ +export declare type CursorFlag = typeof CURSOR_FLAGS[number]; + +/** @public */ +export declare interface CursorStreamOptions { + /** A transformation method applied to each document emitted by the stream */ + transform?(this: void, doc: Document): Document; +} + +/** + * The **Db** class is a class that represents a MongoDB Database. + * @public + * + * @example + * ```js + * const { MongoClient } = require('mongodb'); + * // Connection url + * const url = 'mongodb://localhost:27017'; + * // Database Name + * const dbName = 'test'; + * // Connect using MongoClient + * MongoClient.connect(url, function(err, client) { + * // Select the database by name + * const testDb = client.db(dbName); + * client.close(); + * }); + * ``` + */ +export declare class Db { + /* Excluded from this release type: s */ + static SYSTEM_NAMESPACE_COLLECTION: string; + static SYSTEM_INDEX_COLLECTION: string; + static SYSTEM_PROFILE_COLLECTION: string; + static SYSTEM_USER_COLLECTION: string; + static SYSTEM_COMMAND_COLLECTION: string; + static SYSTEM_JS_COLLECTION: string; + /** + * Creates a new Db instance + * + * @param client - The MongoClient for the database. + * @param databaseName - The name of the database this instance represents. + * @param options - Optional settings for Db construction + */ + constructor(client: MongoClient, databaseName: string, options?: DbOptions); + get databaseName(): string; + get options(): DbOptions | undefined; + /** + * slaveOk specified + * @deprecated Use secondaryOk instead + */ + get slaveOk(): boolean; + /** + * Check if a secondary can be used (because the read preference is *not* set to primary) + */ + get secondaryOk(): boolean; + get readConcern(): ReadConcern | undefined; + /** + * The current readPreference of the Db. If not explicitly defined for + * this Db, will be inherited from the parent MongoClient + */ + get readPreference(): ReadPreference; + get bsonOptions(): BSONSerializeOptions; + get writeConcern(): WriteConcern | undefined; + get namespace(): string; + /** + * Create a new collection on a server with the specified options. Use this to create capped collections. + * More information about command options available at https://docs.mongodb.com/manual/reference/command/create/ + * + * @param name - The name of the collection to create + * @param options - Optional settings for the command + * @param callback - An optional callback, a Promise will be returned if none is provided + */ + createCollection(name: string, options?: CreateCollectionOptions): Promise>; + createCollection(name: string, callback: Callback>): void; + createCollection(name: string, options: CreateCollectionOptions | undefined, callback: Callback>): void; + /** + * Execute a command + * + * @remarks + * This command does not inherit options from the MongoClient. + * + * @param command - The command to run + * @param options - Optional settings for the command + * @param callback - An optional callback, a Promise will be returned if none is provided + */ + command(command: Document): Promise; + command(command: Document, callback: Callback): void; + command(command: Document, options: RunCommandOptions): Promise; + command(command: Document, options: RunCommandOptions, callback: Callback): void; + /** + * Execute an aggregation framework pipeline against the database, needs MongoDB \>= 3.6 + * + * @param pipeline - An array of aggregation stages to be executed + * @param options - Optional settings for the command + */ + aggregate(pipeline?: Document[], options?: AggregateOptions): AggregationCursor; + /** Return the Admin db instance */ + admin(): Admin; + /** + * Returns a reference to a MongoDB Collection. If it does not exist it will be created implicitly. + * + * @param name - the collection name we wish to access. + * @returns return the new Collection instance + */ + collection(name: string, options?: CollectionOptions): Collection; + /** + * Get all the db statistics. + * + * @param options - Optional settings for the command + * @param callback - An optional callback, a Promise will be returned if none is provided + */ + stats(): Promise; + stats(callback: Callback): void; + stats(options: DbStatsOptions): Promise; + stats(options: DbStatsOptions, callback: Callback): void; + /** + * List all collections of this database with optional filter + * + * @param filter - Query to filter collections by + * @param options - Optional settings for the command + */ + listCollections(filter: Document, options: Exclude & { + nameOnly: true; + }): ListCollectionsCursor>; + listCollections(filter: Document, options: Exclude & { + nameOnly: false; + }): ListCollectionsCursor; + listCollections | CollectionInfo = Pick | CollectionInfo>(filter?: Document, options?: ListCollectionsOptions): ListCollectionsCursor; + /** + * Rename a collection. + * + * @remarks + * This operation does not inherit options from the MongoClient. + * + * @param fromCollection - Name of current collection to rename + * @param toCollection - New name of of the collection + * @param options - Optional settings for the command + * @param callback - An optional callback, a Promise will be returned if none is provided + */ + renameCollection(fromCollection: string, toCollection: string): Promise>; + renameCollection(fromCollection: string, toCollection: string, callback: Callback>): void; + renameCollection(fromCollection: string, toCollection: string, options: RenameOptions): Promise>; + renameCollection(fromCollection: string, toCollection: string, options: RenameOptions, callback: Callback>): void; + /** + * Drop a collection from the database, removing it permanently. New accesses will create a new collection. + * + * @param name - Name of collection to drop + * @param options - Optional settings for the command + * @param callback - An optional callback, a Promise will be returned if none is provided + */ + dropCollection(name: string): Promise; + dropCollection(name: string, callback: Callback): void; + dropCollection(name: string, options: DropCollectionOptions): Promise; + dropCollection(name: string, options: DropCollectionOptions, callback: Callback): void; + /** + * Drop a database, removing it permanently from the server. + * + * @param options - Optional settings for the command + * @param callback - An optional callback, a Promise will be returned if none is provided + */ + dropDatabase(): Promise; + dropDatabase(callback: Callback): void; + dropDatabase(options: DropDatabaseOptions): Promise; + dropDatabase(options: DropDatabaseOptions, callback: Callback): void; + /** + * Fetch all collections for the current db. + * + * @param options - Optional settings for the command + * @param callback - An optional callback, a Promise will be returned if none is provided + */ + collections(): Promise; + collections(callback: Callback): void; + collections(options: ListCollectionsOptions): Promise; + collections(options: ListCollectionsOptions, callback: Callback): void; + /** + * Creates an index on the db and collection. + * + * @param name - Name of the collection to create the index on. + * @param indexSpec - Specify the field to index, or an index specification + * @param options - Optional settings for the command + * @param callback - An optional callback, a Promise will be returned if none is provided + */ + createIndex(name: string, indexSpec: IndexSpecification): Promise; + createIndex(name: string, indexSpec: IndexSpecification, callback?: Callback): void; + createIndex(name: string, indexSpec: IndexSpecification, options: CreateIndexesOptions): Promise; + createIndex(name: string, indexSpec: IndexSpecification, options: CreateIndexesOptions, callback: Callback): void; + /** + * Add a user to the database + * + * @param username - The username for the new user + * @param password - An optional password for the new user + * @param options - Optional settings for the command + * @param callback - An optional callback, a Promise will be returned if none is provided + */ + addUser(username: string): Promise; + addUser(username: string, callback: Callback): void; + addUser(username: string, password: string): Promise; + addUser(username: string, password: string, callback: Callback): void; + addUser(username: string, options: AddUserOptions): Promise; + addUser(username: string, options: AddUserOptions, callback: Callback): void; + addUser(username: string, password: string, options: AddUserOptions): Promise; + addUser(username: string, password: string, options: AddUserOptions, callback: Callback): void; + /** + * Remove a user from a database + * + * @param username - The username to remove + * @param options - Optional settings for the command + * @param callback - An optional callback, a Promise will be returned if none is provided + */ + removeUser(username: string): Promise; + removeUser(username: string, callback: Callback): void; + removeUser(username: string, options: RemoveUserOptions): Promise; + removeUser(username: string, options: RemoveUserOptions, callback: Callback): void; + /** + * Set the current profiling level of MongoDB + * + * @param level - The new profiling level (off, slow_only, all). + * @param options - Optional settings for the command + * @param callback - An optional callback, a Promise will be returned if none is provided + */ + setProfilingLevel(level: ProfilingLevel): Promise; + setProfilingLevel(level: ProfilingLevel, callback: Callback): void; + setProfilingLevel(level: ProfilingLevel, options: SetProfilingLevelOptions): Promise; + setProfilingLevel(level: ProfilingLevel, options: SetProfilingLevelOptions, callback: Callback): void; + /** + * Retrieve the current profiling Level for MongoDB + * + * @param options - Optional settings for the command + * @param callback - An optional callback, a Promise will be returned if none is provided + */ + profilingLevel(): Promise; + profilingLevel(callback: Callback): void; + profilingLevel(options: ProfilingLevelOptions): Promise; + profilingLevel(options: ProfilingLevelOptions, callback: Callback): void; + /** + * Retrieves this collections index info. + * + * @param name - The name of the collection. + * @param options - Optional settings for the command + * @param callback - An optional callback, a Promise will be returned if none is provided + */ + indexInformation(name: string): Promise; + indexInformation(name: string, callback: Callback): void; + indexInformation(name: string, options: IndexInformationOptions): Promise; + indexInformation(name: string, options: IndexInformationOptions, callback: Callback): void; + /** + * Unref all sockets + * @deprecated This function is deprecated and will be removed in the next major version. + */ + unref(): void; + /** + * Create a new Change Stream, watching for new changes (insertions, updates, + * replacements, deletions, and invalidations) in this database. Will ignore all + * changes to system collections. + * + * @remarks + * watch() accepts two generic arguments for distinct usecases: + * - The first is to provide the schema that may be defined for all the collections within this database + * - The second is to override the shape of the change stream document entirely, if it is not provided the type will default to ChangeStreamDocument of the first argument + * + * @param pipeline - An array of {@link https://docs.mongodb.com/manual/reference/operator/aggregation-pipeline/|aggregation pipeline stages} through which to pass change stream documents. This allows for filtering (using $match) and manipulating the change stream documents. + * @param options - Optional settings for the command + * @typeParam TSchema - Type of the data being detected by the change stream + * @typeParam TChange - Type of the whole change stream document emitted + */ + watch>(pipeline?: Document[], options?: ChangeStreamOptions): ChangeStream; + /** Return the db logger */ + getLogger(): Logger; + get logger(): Logger; +} + +/* Excluded from this release type: DB_AGGREGATE_COLLECTION */ + +/** @public */ +export declare interface DbOptions extends BSONSerializeOptions, WriteConcernOptions, LoggerOptions { + /** If the database authentication is dependent on another databaseName. */ + authSource?: string; + /** Force server to assign _id values instead of driver. */ + forceServerObjectId?: boolean; + /** The preferred read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST). */ + readPreference?: ReadPreferenceLike; + /** A primary key factory object for generation of custom _id keys. */ + pkFactory?: PkFactory; + /** Specify a read concern for the collection. (only MongoDB 3.2 or higher supported) */ + readConcern?: ReadConcern; + /** Should retry failed writes */ + retryWrites?: boolean; +} + +/* Excluded from this release type: DbPrivate */ +export { DBRef } + +/** @public */ +export declare interface DbStatsOptions extends CommandOperationOptions { + /** Divide the returned sizes by scale value. */ + scale?: number; +} + +export { Decimal128 } + +/** @public */ +export declare interface DeleteManyModel { + /** The filter to limit the deleted documents. */ + filter: Filter; + /** Specifies a collation. */ + collation?: CollationOptions; + /** The index to use. If specified, then the query system will only consider plans using the hinted index. */ + hint?: Hint; +} + +/** @public */ +export declare interface DeleteOneModel { + /** The filter to limit the deleted documents. */ + filter: Filter; + /** Specifies a collation. */ + collation?: CollationOptions; + /** The index to use. If specified, then the query system will only consider plans using the hinted index. */ + hint?: Hint; +} + +/** @public */ +export declare interface DeleteOptions extends CommandOperationOptions, WriteConcernOptions { + /** If true, when an insert fails, don't execute the remaining writes. If false, continue with remaining inserts when one fails. */ + ordered?: boolean; + /** Specifies the collation to use for the operation */ + collation?: CollationOptions; + /** Specify that the update query should only consider plans using the hinted index */ + hint?: string | Document; + /** Map of parameter names and values that can be accessed using $$var (requires MongoDB 5.0). */ + let?: Document; + /** @deprecated use `removeOne` or `removeMany` to implicitly specify the limit */ + single?: boolean; +} + +/** @public */ +export declare interface DeleteResult { + /** Indicates whether this write result was acknowledged. If not, then all other members of this result will be undefined. */ + acknowledged: boolean; + /** The number of documents that were deleted */ + deletedCount: number; +} + +/** @public */ +export declare interface DeleteStatement { + /** The query that matches documents to delete. */ + q: Document; + /** The number of matching documents to delete. */ + limit: number; + /** Specifies the collation to use for the operation. */ + collation?: CollationOptions; + /** A document or string that specifies the index to use to support the query predicate. */ + hint?: Hint; +} + +/* Excluded from this release type: deserialize */ + +/** @public */ +export declare interface DestroyOptions { + /** Force the destruction. */ + force?: boolean; +} + +/** @public */ +export declare type DistinctOptions = CommandOperationOptions; + +export { Document } + +export { Double } + +/** @public */ +export declare interface DriverInfo { + name?: string; + version?: string; + platform?: string; +} + +/** @public */ +export declare interface DropCollectionOptions extends CommandOperationOptions { + /** @experimental */ + encryptedFields?: Document; +} + +/** @public */ +export declare type DropDatabaseOptions = CommandOperationOptions; + +/** @public */ +export declare type DropIndexesOptions = CommandOperationOptions; + +/* Excluded from this release type: Encrypter */ + +/* Excluded from this release type: EncrypterOptions */ + +/** @public */ +export declare interface EndSessionOptions { + /* Excluded from this release type: error */ + force?: boolean; + forceClear?: boolean; +} + +/** TypeScript Omit (Exclude to be specific) does not work for objects with an "any" indexed type, and breaks discriminated unions @public */ +export declare type EnhancedOmit = string extends keyof TRecordOrUnion ? TRecordOrUnion : TRecordOrUnion extends any ? Pick> : never; + +/** @public */ +export declare interface ErrorDescription extends Document { + message?: string; + errmsg?: string; + $err?: string; + errorLabels?: string[]; + errInfo?: Document; +} + +/** @public */ +export declare interface EstimatedDocumentCountOptions extends CommandOperationOptions { + /** + * The maximum amount of time to allow the operation to run. + * + * This option is sent only if the caller explicitly provides a value. The default is to not send a value. + */ + maxTimeMS?: number; +} + +/** @public */ +export declare interface EvalOptions extends CommandOperationOptions { + nolock?: boolean; +} + +/** @public */ +export declare type EventEmitterWithState = { + /* Excluded from this release type: stateChanged */ +}; + +/** + * Event description type + * @public + */ +export declare type EventsDescription = Record; + +/* Excluded from this release type: ExecutionResult */ + +/* Excluded from this release type: Explain */ + +/** @public */ +export declare interface ExplainOptions { + /** Specifies the verbosity mode for the explain output. */ + explain?: ExplainVerbosityLike; +} + +/** @public */ +export declare const ExplainVerbosity: Readonly<{ + readonly queryPlanner: "queryPlanner"; + readonly queryPlannerExtended: "queryPlannerExtended"; + readonly executionStats: "executionStats"; + readonly allPlansExecution: "allPlansExecution"; +}>; + +/** @public */ +export declare type ExplainVerbosity = string; + +/** + * For backwards compatibility, true is interpreted as "allPlansExecution" + * and false as "queryPlanner". Prior to server version 3.6, aggregate() + * ignores the verbosity parameter and executes in "queryPlanner". + * @public + */ +export declare type ExplainVerbosityLike = ExplainVerbosity | boolean; + +/** A MongoDB filter can be some portion of the schema or a set of operators @public */ +export declare type Filter = Partial | ({ + [Property in Join>, '.'>]?: Condition, Property>>; +} & RootFilterOperators>); + +/** @public */ +export declare type FilterOperations = T extends Record ? { + [key in keyof T]?: FilterOperators; +} : FilterOperators; + +/** @public */ +export declare interface FilterOperators extends NonObjectIdLikeDocument { + $eq?: TValue; + $gt?: TValue; + $gte?: TValue; + $in?: ReadonlyArray; + $lt?: TValue; + $lte?: TValue; + $ne?: TValue; + $nin?: ReadonlyArray; + $not?: TValue extends string ? FilterOperators | RegExp : FilterOperators; + /** + * When `true`, `$exists` matches the documents that contain the field, + * including documents where the field value is null. + */ + $exists?: boolean; + $type?: BSONType | BSONTypeAlias; + $expr?: Record; + $jsonSchema?: Record; + $mod?: TValue extends number ? [number, number] : never; + $regex?: TValue extends string ? RegExp | BSONRegExp | string : never; + $options?: TValue extends string ? string : never; + $geoIntersects?: { + $geometry: Document; + }; + $geoWithin?: Document; + $near?: Document; + $nearSphere?: Document; + $maxDistance?: number; + $all?: ReadonlyArray; + $elemMatch?: Document; + $size?: TValue extends ReadonlyArray ? number : never; + $bitsAllClear?: BitwiseFilter; + $bitsAllSet?: BitwiseFilter; + $bitsAnyClear?: BitwiseFilter; + $bitsAnySet?: BitwiseFilter; + $rand?: Record; +} + +/** @public */ +export declare type FinalizeFunction = (key: TKey, reducedValue: TValue) => TValue; + +/** @public */ +export declare class FindCursor extends AbstractCursor { + /* Excluded from this release type: [kFilter] */ + /* Excluded from this release type: [kNumReturned] */ + /* Excluded from this release type: [kBuiltOptions] */ + /* Excluded from this release type: __constructor */ + clone(): FindCursor; + map(transform: (doc: TSchema) => T): FindCursor; + /* Excluded from this release type: _initialize */ + /* Excluded from this release type: _getMore */ + /** + * Get the count of documents for this cursor + * @deprecated Use `collection.estimatedDocumentCount` or `collection.countDocuments` instead + */ + count(): Promise; + /** @deprecated Use `collection.estimatedDocumentCount` or `collection.countDocuments` instead */ + count(callback: Callback): void; + /** @deprecated Use `collection.estimatedDocumentCount` or `collection.countDocuments` instead */ + count(options: CountOptions): Promise; + /** @deprecated Use `collection.estimatedDocumentCount` or `collection.countDocuments` instead */ + count(options: CountOptions, callback: Callback): void; + /** Execute the explain for the cursor */ + explain(): Promise; + explain(callback: Callback): void; + explain(verbosity?: ExplainVerbosityLike): Promise; + /** Set the cursor query */ + filter(filter: Document): this; + /** + * Set the cursor hint + * + * @param hint - If specified, then the query system will only consider plans using the hinted index. + */ + hint(hint: Hint): this; + /** + * Set the cursor min + * + * @param min - Specify a $min value to specify the inclusive lower bound for a specific index in order to constrain the results of find(). The $min specifies the lower bound for all keys of a specific index in order. + */ + min(min: Document): this; + /** + * Set the cursor max + * + * @param max - Specify a $max value to specify the exclusive upper bound for a specific index in order to constrain the results of find(). The $max specifies the upper bound for all keys of a specific index in order. + */ + max(max: Document): this; + /** + * Set the cursor returnKey. + * If set to true, modifies the cursor to only return the index field or fields for the results of the query, rather than documents. + * If set to true and the query does not use an index to perform the read operation, the returned documents will not contain any fields. + * + * @param value - the returnKey value. + */ + returnKey(value: boolean): this; + /** + * Modifies the output of a query by adding a field $recordId to matching documents. $recordId is the internal key which uniquely identifies a document in a collection. + * + * @param value - The $showDiskLoc option has now been deprecated and replaced with the showRecordId field. $showDiskLoc will still be accepted for OP_QUERY stye find. + */ + showRecordId(value: boolean): this; + /** + * Add a query modifier to the cursor query + * + * @param name - The query modifier (must start with $, such as $orderby etc) + * @param value - The modifier value. + */ + addQueryModifier(name: string, value: string | boolean | number | Document): this; + /** + * Add a comment to the cursor query allowing for tracking the comment in the log. + * + * @param value - The comment attached to this query. + */ + comment(value: string): this; + /** + * Set a maxAwaitTimeMS on a tailing cursor query to allow to customize the timeout value for the option awaitData (Only supported on MongoDB 3.2 or higher, ignored otherwise) + * + * @param value - Number of milliseconds to wait before aborting the tailed query. + */ + maxAwaitTimeMS(value: number): this; + /** + * Set a maxTimeMS on the cursor query, allowing for hard timeout limits on queries (Only supported on MongoDB 2.6 or higher) + * + * @param value - Number of milliseconds to wait before aborting the query. + */ + maxTimeMS(value: number): this; + /** + * Add a project stage to the aggregation pipeline + * + * @remarks + * In order to strictly type this function you must provide an interface + * that represents the effect of your projection on the result documents. + * + * By default chaining a projection to your cursor changes the returned type to the generic + * {@link Document} type. + * You should specify a parameterized type to have assertions on your final results. + * + * @example + * ```typescript + * // Best way + * const docs: FindCursor<{ a: number }> = cursor.project<{ a: number }>({ _id: 0, a: true }); + * // Flexible way + * const docs: FindCursor = cursor.project({ _id: 0, a: true }); + * ``` + * + * @remarks + * + * **Note for Typescript Users:** adding a transform changes the return type of the iteration of this cursor, + * it **does not** return a new instance of a cursor. This means when calling project, + * you should always assign the result to a new variable in order to get a correctly typed cursor variable. + * Take note of the following example: + * + * @example + * ```typescript + * const cursor: FindCursor<{ a: number; b: string }> = coll.find(); + * const projectCursor = cursor.project<{ a: number }>({ _id: 0, a: true }); + * const aPropOnlyArray: {a: number}[] = await projectCursor.toArray(); + * + * // or always use chaining and save the final cursor + * + * const cursor = coll.find().project<{ a: string }>({ + * _id: 0, + * a: { $convert: { input: '$a', to: 'string' } + * }}); + * ``` + */ + project(value: Document): FindCursor; + /** + * Sets the sort order of the cursor query. + * + * @param sort - The key or keys set for the sort. + * @param direction - The direction of the sorting (1 or -1). + */ + sort(sort: Sort | string, direction?: SortDirection): this; + /** + * Allows disk use for blocking sort operations exceeding 100MB memory. (MongoDB 3.2 or higher) + * + * @remarks + * {@link https://docs.mongodb.com/manual/reference/command/find/#find-cmd-allowdiskuse | find command allowDiskUse documentation} + */ + allowDiskUse(allow?: boolean): this; + /** + * Set the collation options for the cursor. + * + * @param value - The cursor collation options (MongoDB 3.4 or higher) settings for update operation (see 3.4 documentation for available fields). + */ + collation(value: CollationOptions): this; + /** + * Set the limit for the cursor. + * + * @param value - The limit for the cursor query. + */ + limit(value: number): this; + /** + * Set the skip for the cursor. + * + * @param value - The skip for the cursor query. + */ + skip(value: number): this; +} + +/** @public */ +export declare interface FindOneAndDeleteOptions extends CommandOperationOptions { + /** An optional hint for query optimization. See the {@link https://docs.mongodb.com/manual/reference/command/update/#update-command-hint|update command} reference for more information.*/ + hint?: Document; + /** Limits the fields to return for all matching documents. */ + projection?: Document; + /** Determines which document the operation modifies if the query selects multiple documents. */ + sort?: Sort; + /** Map of parameter names and values that can be accessed using $$var (requires MongoDB 5.0). */ + let?: Document; +} + +/** @public */ +export declare interface FindOneAndReplaceOptions extends CommandOperationOptions { + /** Allow driver to bypass schema validation in MongoDB 3.2 or higher. */ + bypassDocumentValidation?: boolean; + /** An optional hint for query optimization. See the {@link https://docs.mongodb.com/manual/reference/command/update/#update-command-hint|update command} reference for more information.*/ + hint?: Document; + /** Limits the fields to return for all matching documents. */ + projection?: Document; + /** When set to 'after', returns the updated document rather than the original. The default is 'before'. */ + returnDocument?: ReturnDocument; + /** Determines which document the operation modifies if the query selects multiple documents. */ + sort?: Sort; + /** Upsert the document if it does not exist. */ + upsert?: boolean; + /** Map of parameter names and values that can be accessed using $$var (requires MongoDB 5.0). */ + let?: Document; +} + +/** @public */ +export declare interface FindOneAndUpdateOptions extends CommandOperationOptions { + /** Optional list of array filters referenced in filtered positional operators */ + arrayFilters?: Document[]; + /** Allow driver to bypass schema validation in MongoDB 3.2 or higher. */ + bypassDocumentValidation?: boolean; + /** An optional hint for query optimization. See the {@link https://docs.mongodb.com/manual/reference/command/update/#update-command-hint|update command} reference for more information.*/ + hint?: Document; + /** Limits the fields to return for all matching documents. */ + projection?: Document; + /** When set to 'after', returns the updated document rather than the original. The default is 'before'. */ + returnDocument?: ReturnDocument; + /** Determines which document the operation modifies if the query selects multiple documents. */ + sort?: Sort; + /** Upsert the document if it does not exist. */ + upsert?: boolean; + /** Map of parameter names and values that can be accessed using $$var (requires MongoDB 5.0). */ + let?: Document; +} + +/** + * A builder object that is returned from {@link BulkOperationBase#find}. + * Is used to build a write operation that involves a query filter. + * + * @public + */ +export declare class FindOperators { + bulkOperation: BulkOperationBase; + /* Excluded from this release type: __constructor */ + /** Add a multiple update operation to the bulk operation */ + update(updateDocument: Document): BulkOperationBase; + /** Add a single update operation to the bulk operation */ + updateOne(updateDocument: Document): BulkOperationBase; + /** Add a replace one operation to the bulk operation */ + replaceOne(replacement: Document): BulkOperationBase; + /** Add a delete one operation to the bulk operation */ + deleteOne(): BulkOperationBase; + /** Add a delete many operation to the bulk operation */ + delete(): BulkOperationBase; + /** Upsert modifier for update bulk operation, noting that this operation is an upsert. */ + upsert(): this; + /** Specifies the collation for the query condition. */ + collation(collation: CollationOptions): this; + /** Specifies arrayFilters for UpdateOne or UpdateMany bulk operations. */ + arrayFilters(arrayFilters: Document[]): this; +} + +/** + * @public + * @typeParam TSchema - Unused schema definition, deprecated usage, only specify `FindOptions` with no generic + */ +export declare interface FindOptions extends CommandOperationOptions { + /** Sets the limit of documents returned in the query. */ + limit?: number; + /** Set to sort the documents coming back from the query. Array of indexes, `[['a', 1]]` etc. */ + sort?: Sort; + /** The fields to return in the query. Object of fields to either include or exclude (one of, not both), `{'a':1, 'b': 1}` **or** `{'a': 0, 'b': 0}` */ + projection?: Document; + /** Set to skip N documents ahead in your query (useful for pagination). */ + skip?: number; + /** Tell the query to use specific indexes in the query. Object of indexes to use, `{'_id':1}` */ + hint?: Hint; + /** Specify if the cursor can timeout. */ + timeout?: boolean; + /** Specify if the cursor is tailable. */ + tailable?: boolean; + /** Specify if the cursor is a tailable-await cursor. Requires `tailable` to be true */ + awaitData?: boolean; + /** Set the batchSize for the getMoreCommand when iterating over the query results. */ + batchSize?: number; + /** If true, returns only the index keys in the resulting documents. */ + returnKey?: boolean; + /** The inclusive lower bound for a specific index */ + min?: Document; + /** The exclusive upper bound for a specific index */ + max?: Document; + /** Number of milliseconds to wait before aborting the query. */ + maxTimeMS?: number; + /** The maximum amount of time for the server to wait on new documents to satisfy a tailable cursor query. Requires `tailable` and `awaitData` to be true */ + maxAwaitTimeMS?: number; + /** The server normally times out idle cursors after an inactivity period (10 minutes) to prevent excess memory use. Set this option to prevent that. */ + noCursorTimeout?: boolean; + /** Specify collation (MongoDB 3.4 or higher) settings for update operation (see 3.4 documentation for available fields). */ + collation?: CollationOptions; + /** Allows disk use for blocking sort operations exceeding 100MB memory. (MongoDB 3.2 or higher) */ + allowDiskUse?: boolean; + /** Determines whether to close the cursor after the first batch. Defaults to false. */ + singleBatch?: boolean; + /** For queries against a sharded collection, allows the command (or subsequent getMore commands) to return partial results, rather than an error, if one or more queried shards are unavailable. */ + allowPartialResults?: boolean; + /** Determines whether to return the record identifier for each document. If true, adds a field $recordId to the returned documents. */ + showRecordId?: boolean; + /** Map of parameter names and values that can be accessed using $$var (requires MongoDB 5.0). */ + let?: Document; +} + +/** @public */ +export declare type Flatten = Type extends ReadonlyArray ? Item : Type; + +/** @public */ +export declare type GenericListener = (...args: any[]) => void; + +/* Excluded from this release type: GetMore */ + +/* Excluded from this release type: GetMoreOptions */ + +/** + * Constructor for a streaming GridFS interface + * @public + */ +export declare class GridFSBucket extends TypedEventEmitter { + /* Excluded from this release type: s */ + /** + * When the first call to openUploadStream is made, the upload stream will + * check to see if it needs to create the proper indexes on the chunks and + * files collections. This event is fired either when 1) it determines that + * no index creation is necessary, 2) when it successfully creates the + * necessary indexes. + * @event + */ + static readonly INDEX: "index"; + constructor(db: Db, options?: GridFSBucketOptions); + /** + * Returns a writable stream (GridFSBucketWriteStream) for writing + * buffers to GridFS. The stream's 'id' property contains the resulting + * file's id. + * + * @param filename - The value of the 'filename' key in the files doc + * @param options - Optional settings. + */ + openUploadStream(filename: string, options?: GridFSBucketWriteStreamOptions): GridFSBucketWriteStream; + /** + * Returns a writable stream (GridFSBucketWriteStream) for writing + * buffers to GridFS for a custom file id. The stream's 'id' property contains the resulting + * file's id. + */ + openUploadStreamWithId(id: ObjectId, filename: string, options?: GridFSBucketWriteStreamOptions): GridFSBucketWriteStream; + /** Returns a readable stream (GridFSBucketReadStream) for streaming file data from GridFS. */ + openDownloadStream(id: ObjectId, options?: GridFSBucketReadStreamOptions): GridFSBucketReadStream; + /** + * Deletes a file with the given id + * + * @param id - The id of the file doc + */ + delete(id: ObjectId): Promise; + delete(id: ObjectId, callback: Callback): void; + /** Convenience wrapper around find on the files collection */ + find(filter?: Filter, options?: FindOptions): FindCursor; + /** + * Returns a readable stream (GridFSBucketReadStream) for streaming the + * file with the given name from GridFS. If there are multiple files with + * the same name, this will stream the most recent file with the given name + * (as determined by the `uploadDate` field). You can set the `revision` + * option to change this behavior. + */ + openDownloadStreamByName(filename: string, options?: GridFSBucketReadStreamOptionsWithRevision): GridFSBucketReadStream; + /** + * Renames the file with the given _id to the given string + * + * @param id - the id of the file to rename + * @param filename - new name for the file + */ + rename(id: ObjectId, filename: string): Promise; + rename(id: ObjectId, filename: string, callback: Callback): void; + /** Removes this bucket's files collection, followed by its chunks collection. */ + drop(): Promise; + drop(callback: Callback): void; + /** Get the Db scoped logger. */ + getLogger(): Logger; +} + +/** @public */ +export declare type GridFSBucketEvents = { + index(): void; +}; + +/** @public */ +export declare interface GridFSBucketOptions extends WriteConcernOptions { + /** The 'files' and 'chunks' collections will be prefixed with the bucket name followed by a dot. */ + bucketName?: string; + /** Number of bytes stored in each chunk. Defaults to 255KB */ + chunkSizeBytes?: number; + /** Read preference to be passed to read operations */ + readPreference?: ReadPreference; +} + +/* Excluded from this release type: GridFSBucketPrivate */ + +/** + * A readable stream that enables you to read buffers from GridFS. + * + * Do not instantiate this class directly. Use `openDownloadStream()` instead. + * @public + */ +export declare class GridFSBucketReadStream extends Readable implements NodeJS.ReadableStream { + /* Excluded from this release type: s */ + /** + * An error occurred + * @event + */ + static readonly ERROR: "error"; + /** + * Fires when the stream loaded the file document corresponding to the provided id. + * @event + */ + static readonly FILE: "file"; + /** + * Emitted when a chunk of data is available to be consumed. + * @event + */ + static readonly DATA: "data"; + /** + * Fired when the stream is exhausted (no more data events). + * @event + */ + static readonly END: "end"; + /** + * Fired when the stream is exhausted and the underlying cursor is killed + * @event + */ + static readonly CLOSE: "close"; + /* Excluded from this release type: __constructor */ + /* Excluded from this release type: _read */ + /** + * Sets the 0-based offset in bytes to start streaming from. Throws + * an error if this stream has entered flowing mode + * (e.g. if you've already called `on('data')`) + * + * @param start - 0-based offset in bytes to start streaming from + */ + start(start?: number): this; + /** + * Sets the 0-based offset in bytes to start streaming from. Throws + * an error if this stream has entered flowing mode + * (e.g. if you've already called `on('data')`) + * + * @param end - Offset in bytes to stop reading at + */ + end(end?: number): this; + /** + * Marks this stream as aborted (will never push another `data` event) + * and kills the underlying cursor. Will emit the 'end' event, and then + * the 'close' event once the cursor is successfully killed. + * + * @param callback - called when the cursor is successfully closed or an error occurred. + */ + abort(callback?: Callback): void; +} + +/** @public */ +export declare interface GridFSBucketReadStreamOptions { + sort?: Sort; + skip?: number; + /** 0-based offset in bytes to start streaming from */ + start?: number; + /** 0-based offset in bytes to stop streaming before */ + end?: number; +} + +/** @public */ +export declare interface GridFSBucketReadStreamOptionsWithRevision extends GridFSBucketReadStreamOptions { + /** The revision number relative to the oldest file with the given filename. 0 + * gets you the oldest file, 1 gets you the 2nd oldest, -1 gets you the + * newest. */ + revision?: number; +} + +/* Excluded from this release type: GridFSBucketReadStreamPrivate */ + +/** + * A writable stream that enables you to write buffers to GridFS. + * + * Do not instantiate this class directly. Use `openUploadStream()` instead. + * @public + */ +export declare class GridFSBucketWriteStream extends Writable implements NodeJS.WritableStream { + bucket: GridFSBucket; + chunks: Collection; + filename: string; + files: Collection; + options: GridFSBucketWriteStreamOptions; + done: boolean; + id: ObjectId; + chunkSizeBytes: number; + bufToStore: Buffer; + length: number; + n: number; + pos: number; + state: { + streamEnd: boolean; + outstandingRequests: number; + errored: boolean; + aborted: boolean; + }; + writeConcern?: WriteConcern; + /** @event */ + static readonly CLOSE = "close"; + /** @event */ + static readonly ERROR = "error"; + /** + * `end()` was called and the write stream successfully wrote the file metadata and all the chunks to MongoDB. + * @event + */ + static readonly FINISH = "finish"; + /* Excluded from this release type: __constructor */ + /** + * Write a buffer to the stream. + * + * @param chunk - Buffer to write + * @param encodingOrCallback - Optional encoding for the buffer + * @param callback - Function to call when the chunk was added to the buffer, or if the entire chunk was persisted to MongoDB if this chunk caused a flush. + * @returns False if this write required flushing a chunk to MongoDB. True otherwise. + */ + write(chunk: Buffer | string): boolean; + write(chunk: Buffer | string, callback: Callback): boolean; + write(chunk: Buffer | string, encoding: BufferEncoding | undefined): boolean; + write(chunk: Buffer | string, encoding: BufferEncoding | undefined, callback: Callback): boolean; + /** + * Places this write stream into an aborted state (all future writes fail) + * and deletes all chunks that have already been written. + * + * @param callback - called when chunks are successfully removed or error occurred + */ + abort(): Promise; + abort(callback: Callback): void; + /** + * Tells the stream that no more data will be coming in. The stream will + * persist the remaining data to MongoDB, write the files document, and + * then emit a 'finish' event. + * + * @param chunk - Buffer to write + * @param encoding - Optional encoding for the buffer + * @param callback - Function to call when all files and chunks have been persisted to MongoDB + */ + end(): this; + end(chunk: Buffer): this; + end(callback: Callback): this; + end(chunk: Buffer, callback: Callback): this; + end(chunk: Buffer, encoding: BufferEncoding): this; + end(chunk: Buffer, encoding: BufferEncoding | undefined, callback: Callback): this; +} + +/** @public */ +export declare interface GridFSBucketWriteStreamOptions extends WriteConcernOptions { + /** Overwrite this bucket's chunkSizeBytes for this file */ + chunkSizeBytes?: number; + /** Custom file id for the GridFS file. */ + id?: ObjectId; + /** Object to store in the file document's `metadata` field */ + metadata?: Document; + /** String to store in the file document's `contentType` field */ + contentType?: string; + /** Array of strings to store in the file document's `aliases` field */ + aliases?: string[]; +} + +/** @public */ +export declare interface GridFSChunk { + _id: ObjectId; + files_id: ObjectId; + n: number; + data: Buffer | Uint8Array; +} + +/** @public */ +export declare interface GridFSFile { + _id: ObjectId; + length: number; + chunkSize: number; + filename: string; + contentType?: string; + aliases?: string[]; + metadata?: Document; + uploadDate: Date; +} + +/** @public */ +export declare const GSSAPICanonicalizationValue: Readonly<{ + readonly on: true; + readonly off: false; + readonly none: "none"; + readonly forward: "forward"; + readonly forwardAndReverse: "forwardAndReverse"; +}>; + +/** @public */ +export declare type GSSAPICanonicalizationValue = typeof GSSAPICanonicalizationValue[keyof typeof GSSAPICanonicalizationValue]; + +/** @public */ +export declare interface HedgeOptions { + /** Explicitly enable or disable hedged reads. */ + enabled?: boolean; +} + +/** @public */ +export declare type Hint = string | Document; + +/** @public */ +export declare class HostAddress { + host: string | undefined; + port: number | undefined; + socketPath: string | undefined; + isIPv6: boolean | undefined; + constructor(hostString: string); + inspect(): string; + /** + * @param ipv6Brackets - optionally request ipv6 bracket notation required for connection strings + */ + toString(ipv6Brackets?: boolean): string; + static fromString(this: void, s: string): HostAddress; + static fromHostPort(host: string, port: number): HostAddress; + static fromSrvRecord({ name, port }: SrvRecord): HostAddress; +} + +/** @public */ +export declare interface IndexDescription extends Pick { + collation?: CollationOptions; + name?: string; + key: Document; +} + +/** @public */ +export declare type IndexDirection = -1 | 1 | '2d' | '2dsphere' | 'text' | 'geoHaystack' | number; + +/** @public */ +export declare interface IndexInformationOptions { + full?: boolean; + readPreference?: ReadPreference; + session?: ClientSession; +} + +/** @public */ +export declare type IndexSpecification = OneOrMore; + +/** Given an object shaped type, return the type of the _id field or default to ObjectId @public */ +export declare type InferIdType = TSchema extends { + _id: infer IdType; +} ? Record extends IdType ? never : IdType : TSchema extends { + _id?: infer IdType; +} ? unknown extends IdType ? ObjectId : IdType : ObjectId; + +/** @public */ +export declare interface InsertManyResult { + /** Indicates whether this write result was acknowledged. If not, then all other members of this result will be undefined */ + acknowledged: boolean; + /** The number of inserted documents for this operations */ + insertedCount: number; + /** Map of the index of the inserted document to the id of the inserted document */ + insertedIds: { + [key: number]: InferIdType; + }; +} + +/** @public */ +export declare interface InsertOneModel { + /** The document to insert. */ + document: OptionalId; +} + +/** @public */ +export declare interface InsertOneOptions extends CommandOperationOptions { + /** Allow driver to bypass schema validation in MongoDB 3.2 or higher. */ + bypassDocumentValidation?: boolean; + /** Force server to assign _id values instead of driver. */ + forceServerObjectId?: boolean; +} + +/** @public */ +export declare interface InsertOneResult { + /** Indicates whether this write result was acknowledged. If not, then all other members of this result will be undefined */ + acknowledged: boolean; + /** The identifier that was inserted. If the server generated the identifier, this value will be null as the driver does not have access to that data */ + insertedId: InferIdType; +} + +export { Int32 } + +/** @public */ +export declare type IntegerType = number | Int32 | Long; + +/* Excluded from this release type: InternalAbstractCursorOptions */ + +/* Excluded from this release type: InterruptibleAsyncInterval */ + +/** @public */ +export declare type IsAny = true extends false & Type ? ResultIfAny : ResultIfNotAny; + +/** + * Helper types for dot-notation filter attributes + */ +/** @public */ +export declare type Join = T extends [] ? '' : T extends [string | number] ? `${T[0]}` : T extends [string | number, ...infer R] ? `${T[0]}${D}${Join}` : string; + +/* Excluded from this release type: kBeforeHandshake */ + +/* Excluded from this release type: kBuffer */ + +/* Excluded from this release type: kBuffers */ + +/* Excluded from this release type: kBuiltOptions */ + +/* Excluded from this release type: kCancellationToken */ + +/* Excluded from this release type: kCancellationToken_2 */ + +/* Excluded from this release type: kCancelled */ + +/* Excluded from this release type: kCancelled_2 */ + +/* Excluded from this release type: kCheckedOut */ + +/* Excluded from this release type: kClient */ + +/* Excluded from this release type: kClosed */ + +/* Excluded from this release type: kClosed_2 */ + +/* Excluded from this release type: kClusterTime */ + +/* Excluded from this release type: kConnection */ + +/* Excluded from this release type: kConnectionCounter */ + +/* Excluded from this release type: kConnections */ + +/* Excluded from this release type: kCursorStream */ + +/* Excluded from this release type: kDelayedTimeoutId */ + +/* Excluded from this release type: kDescription */ + +/* Excluded from this release type: kDocuments */ + +/* Excluded from this release type: kErrorLabels */ + +/** @public */ +export declare type KeysOfAType = { + [key in keyof TSchema]: NonNullable extends Type ? key : never; +}[keyof TSchema]; + +/** @public */ +export declare type KeysOfOtherType = { + [key in keyof TSchema]: NonNullable extends Type ? never : key; +}[keyof TSchema]; + +/* Excluded from this release type: kFilter */ + +/* Excluded from this release type: kFullResult */ + +/* Excluded from this release type: kGeneration */ + +/* Excluded from this release type: kGeneration_2 */ + +/* Excluded from this release type: kHello */ + +/* Excluded from this release type: kId */ + +/* Excluded from this release type: KillCursor */ + +/* Excluded from this release type: kInit */ + +/* Excluded from this release type: kInitialized */ + +/* Excluded from this release type: kInternalClient */ + +/* Excluded from this release type: kKilled */ + +/* Excluded from this release type: kLastUseTime */ + +/* Excluded from this release type: kLength */ + +/* Excluded from this release type: kLogger */ + +/* Excluded from this release type: kMessageStream */ + +/* Excluded from this release type: kMetrics */ + +/* Excluded from this release type: kMinPoolSizeTimer */ + +/* Excluded from this release type: kMode */ + +/* Excluded from this release type: kMonitor */ + +/* Excluded from this release type: kMonitorId */ + +/* Excluded from this release type: kNamespace */ + +/* Excluded from this release type: kNumReturned */ + +/* Excluded from this release type: kOptions */ + +/* Excluded from this release type: kOptions_2 */ + +/* Excluded from this release type: kOptions_3 */ + +/* Excluded from this release type: kPending */ + +/* Excluded from this release type: kPinnedConnection */ + +/* Excluded from this release type: kPipeline */ + +/* Excluded from this release type: kProcessingWaitQueue */ + +/* Excluded from this release type: kQueue */ + +/* Excluded from this release type: kRoundTripTime */ + +/* Excluded from this release type: kRTTPinger */ + +/* Excluded from this release type: kServer */ + +/* Excluded from this release type: kServer_2 */ + +/* Excluded from this release type: kServerError */ + +/* Excluded from this release type: kServerSession */ + +/* Excluded from this release type: kServiceGenerations */ + +/* Excluded from this release type: kSession */ + +/* Excluded from this release type: kSession_2 */ + +/* Excluded from this release type: kSnapshotEnabled */ + +/* Excluded from this release type: kSnapshotTime */ + +/* Excluded from this release type: kStream */ + +/* Excluded from this release type: kTransform */ + +/* Excluded from this release type: kTxnNumberIncrement */ + +/* Excluded from this release type: kWaitQueue */ + +/* Excluded from this release type: kWaitQueue_2 */ + +/** @public */ +export declare const LEGAL_TCP_SOCKET_OPTIONS: readonly ["family", "hints", "localAddress", "localPort", "lookup"]; + +/** @public */ +export declare const LEGAL_TLS_SOCKET_OPTIONS: readonly ["ALPNProtocols", "ca", "cert", "checkServerIdentity", "ciphers", "crl", "ecdhCurve", "key", "minDHSize", "passphrase", "pfx", "rejectUnauthorized", "secureContext", "secureProtocol", "servername", "session"]; + +/** @public */ +export declare class ListCollectionsCursor | CollectionInfo = Pick | CollectionInfo> extends AbstractCursor { + parent: Db; + filter: Document; + options?: ListCollectionsOptions; + constructor(db: Db, filter: Document, options?: ListCollectionsOptions); + clone(): ListCollectionsCursor; + /* Excluded from this release type: _initialize */ +} + +/** @public */ +export declare interface ListCollectionsOptions extends CommandOperationOptions { + /** Since 4.0: If true, will only return the collection name in the response, and will omit additional info */ + nameOnly?: boolean; + /** Since 4.0: If true and nameOnly is true, allows a user without the required privilege (i.e. listCollections action on the database) to run the command when access control is enforced. */ + authorizedCollections?: boolean; + /** The batchSize for the returned command cursor or if pre 2.8 the systems batch collection */ + batchSize?: number; +} + +/** @public */ +export declare interface ListDatabasesOptions extends CommandOperationOptions { + /** A query predicate that determines which databases are listed */ + filter?: Document; + /** A flag to indicate whether the command should return just the database names, or return both database names and size information */ + nameOnly?: boolean; + /** A flag that determines which databases are returned based on the user privileges when access control is enabled */ + authorizedDatabases?: boolean; +} + +/** @public */ +export declare interface ListDatabasesResult { + databases: ({ + name: string; + sizeOnDisk?: number; + empty?: boolean; + } & Document)[]; + totalSize?: number; + totalSizeMb?: number; + ok: 1 | 0; +} + +/** @public */ +export declare class ListIndexesCursor extends AbstractCursor { + parent: Collection; + options?: ListIndexesOptions; + constructor(collection: Collection, options?: ListIndexesOptions); + clone(): ListIndexesCursor; + /* Excluded from this release type: _initialize */ +} + +/** @public */ +export declare interface ListIndexesOptions extends CommandOperationOptions { + /** The batchSize for the returned command cursor or if pre 2.8 the systems batch collection */ + batchSize?: number; +} + +/** + * @public + */ +export declare class Logger { + className: string; + /** + * Creates a new Logger instance + * + * @param className - The Class name associated with the logging instance + * @param options - Optional logging settings + */ + constructor(className: string, options?: LoggerOptions); + /** + * Log a message at the debug level + * + * @param message - The message to log + * @param object - Additional meta data to log + */ + debug(message: string, object?: unknown): void; + /** + * Log a message at the warn level + * + * @param message - The message to log + * @param object - Additional meta data to log + */ + warn(message: string, object?: unknown): void; + /** + * Log a message at the info level + * + * @param message - The message to log + * @param object - Additional meta data to log + */ + info(message: string, object?: unknown): void; + /** + * Log a message at the error level + * + * @param message - The message to log + * @param object - Additional meta data to log + */ + error(message: string, object?: unknown): void; + /** Is the logger set at info level */ + isInfo(): boolean; + /** Is the logger set at error level */ + isError(): boolean; + /** Is the logger set at error level */ + isWarn(): boolean; + /** Is the logger set at debug level */ + isDebug(): boolean; + /** Resets the logger to default settings, error and no filtered classes */ + static reset(): void; + /** Get the current logger function */ + static currentLogger(): LoggerFunction; + /** + * Set the current logger function + * + * @param logger - Custom logging function + */ + static setCurrentLogger(logger: LoggerFunction): void; + /** + * Filter log messages for a particular class + * + * @param type - The type of filter (currently only class) + * @param values - The filters to apply + */ + static filter(type: string, values: string[]): void; + /** + * Set the current log level + * + * @param newLevel - Set current log level (debug, warn, info, error) + */ + static setLevel(newLevel: LoggerLevel): void; +} + +/** @public */ +export declare type LoggerFunction = (message?: any, ...optionalParams: any[]) => void; + +/** @public */ +export declare const LoggerLevel: Readonly<{ + readonly ERROR: "error"; + readonly WARN: "warn"; + readonly INFO: "info"; + readonly DEBUG: "debug"; + readonly error: "error"; + readonly warn: "warn"; + readonly info: "info"; + readonly debug: "debug"; +}>; + +/** @public */ +export declare type LoggerLevel = typeof LoggerLevel[keyof typeof LoggerLevel]; + +/** @public */ +export declare interface LoggerOptions { + logger?: LoggerFunction; + loggerLevel?: LoggerLevel; +} + +export { Long } + +export { Map_2 as Map } + +/** @public */ +export declare type MapFunction = (this: TSchema) => void; + +/** @public */ +export declare interface MapReduceOptions extends CommandOperationOptions { + /** Sets the output target for the map reduce job. */ + out?: 'inline' | { + inline: 1; + } | { + replace: string; + } | { + merge: string; + } | { + reduce: string; + }; + /** Query filter object. */ + query?: Document; + /** Sorts the input objects using this key. Useful for optimization, like sorting by the emit key for fewer reduces. */ + sort?: Sort; + /** Number of objects to return from collection. */ + limit?: number; + /** Keep temporary data. */ + keeptemp?: boolean; + /** Finalize function. */ + finalize?: FinalizeFunction | string; + /** Can pass in variables that can be access from map/reduce/finalize. */ + scope?: Document; + /** It is possible to make the execution stay in JS. Provided in MongoDB \> 2.0.X. */ + jsMode?: boolean; + /** Provide statistics on job execution time. */ + verbose?: boolean; + /** Allow driver to bypass schema validation in MongoDB 3.2 or higher. */ + bypassDocumentValidation?: boolean; +} + +/** @public */ +export declare type MatchKeysAndValues = Readonly<{ + [Property in Join, '.'>]?: PropertyType; +} & { + [Property in `${NestedPathsOfType}.$${`[${string}]` | ''}`]?: ArrayElement>; +} & { + [Property in `${NestedPathsOfType[]>}.$${`[${string}]` | ''}.${string}`]?: any; +}>; + +export { MaxKey } + +/* Excluded from this release type: MessageHeader */ + +/* Excluded from this release type: MessageStream */ + +/* Excluded from this release type: MessageStreamOptions */ +export { MinKey } + +/** @public */ +export declare interface ModifyResult { + value: WithId | null; + lastErrorObject?: Document; + ok: 0 | 1; +} + +/** @public */ +export declare const MONGO_CLIENT_EVENTS: readonly ["connectionPoolCreated", "connectionPoolClosed", "connectionCreated", "connectionReady", "connectionClosed", "connectionCheckOutStarted", "connectionCheckOutFailed", "connectionCheckedOut", "connectionCheckedIn", "connectionPoolCleared", "commandStarted", "commandSucceeded", "commandFailed", "serverOpening", "serverClosed", "serverDescriptionChanged", "topologyOpening", "topologyClosed", "topologyDescriptionChanged", "error", "timeout", "close", "serverHeartbeatStarted", "serverHeartbeatSucceeded", "serverHeartbeatFailed"]; + +/** + * An error generated when the driver API is used incorrectly + * + * @privateRemarks + * Should **never** be directly instantiated + * + * @public + * @category Error + */ +export declare class MongoAPIError extends MongoDriverError { + constructor(message: string); + get name(): string; +} + +/** + * A error generated when the user attempts to authenticate + * via AWS, but fails + * + * @public + * @category Error + */ +export declare class MongoAWSError extends MongoRuntimeError { + constructor(message: string); + get name(): string; +} + +/** + * An error generated when a batch command is re-executed after one of the commands in the batch + * has failed + * + * @public + * @category Error + */ +export declare class MongoBatchReExecutionError extends MongoAPIError { + constructor(message?: string); + get name(): string; +} + +/** + * An error indicating an unsuccessful Bulk Write + * @public + * @category Error + */ +export declare class MongoBulkWriteError extends MongoServerError { + result: BulkWriteResult; + writeErrors: OneOrMore; + err?: WriteConcernError; + /** Creates a new MongoBulkWriteError */ + constructor(error: { + message: string; + code: number; + writeErrors?: WriteError[]; + } | WriteConcernError | AnyError, result: BulkWriteResult); + get name(): string; + /** Number of documents inserted. */ + get insertedCount(): number; + /** Number of documents matched for update. */ + get matchedCount(): number; + /** Number of documents modified. */ + get modifiedCount(): number; + /** Number of documents deleted. */ + get deletedCount(): number; + /** Number of documents upserted. */ + get upsertedCount(): number; + /** Inserted document generated Id's, hash key is the index of the originating operation */ + get insertedIds(): { + [key: number]: any; + }; + /** Upserted document generated Id's, hash key is the index of the originating operation */ + get upsertedIds(): { + [key: number]: any; + }; +} + +/** + * An error generated when a ChangeStream operation fails to execute. + * + * @public + * @category Error + */ +export declare class MongoChangeStreamError extends MongoRuntimeError { + constructor(message: string); + get name(): string; +} + +/** + * The **MongoClient** class is a class that allows for making Connections to MongoDB. + * @public + * + * @remarks + * The programmatically provided options take precedence over the URI options. + * + * @example + * ```js + * // Connect using a MongoClient instance + * const MongoClient = require('mongodb').MongoClient; + * const test = require('assert'); + * // Connection url + * const url = 'mongodb://localhost:27017'; + * // Database Name + * const dbName = 'test'; + * // Connect using MongoClient + * const mongoClient = new MongoClient(url); + * mongoClient.connect(function(err, client) { + * const db = client.db(dbName); + * client.close(); + * }); + * ``` + * + * @example + * ```js + * // Connect using the MongoClient.connect static method + * const MongoClient = require('mongodb').MongoClient; + * const test = require('assert'); + * // Connection url + * const url = 'mongodb://localhost:27017'; + * // Database Name + * const dbName = 'test'; + * // Connect using MongoClient + * MongoClient.connect(url, function(err, client) { + * const db = client.db(dbName); + * client.close(); + * }); + * ``` + */ +export declare class MongoClient extends TypedEventEmitter { + /* Excluded from this release type: s */ + /* Excluded from this release type: topology */ + /* Excluded from this release type: [kOptions] */ + constructor(url: string, options?: MongoClientOptions); + get options(): Readonly; + get serverApi(): Readonly; + /* Excluded from this release type: monitorCommands */ + /* Excluded from this release type: monitorCommands */ + get autoEncrypter(): AutoEncrypter | undefined; + get readConcern(): ReadConcern | undefined; + get writeConcern(): WriteConcern | undefined; + get readPreference(): ReadPreference; + get bsonOptions(): BSONSerializeOptions; + get logger(): Logger; + /** + * Connect to MongoDB using a url + * + * @see docs.mongodb.org/manual/reference/connection-string/ + */ + connect(): Promise; + connect(callback: Callback): void; + /** + * Close the db and its underlying connections + * + * @param force - Force close, emitting no events + * @param callback - An optional callback, a Promise will be returned if none is provided + */ + close(): Promise; + close(callback: Callback): void; + close(force: boolean): Promise; + close(force: boolean, callback: Callback): void; + /** + * Create a new Db instance sharing the current socket connections. + * + * @param dbName - The name of the database we want to use. If not provided, use database name from connection string. + * @param options - Optional settings for Db construction + */ + db(dbName?: string, options?: DbOptions): Db; + /** + * Connect to MongoDB using a url + * + * @remarks + * The programmatically provided options take precedence over the URI options. + * + * @see https://docs.mongodb.org/manual/reference/connection-string/ + */ + static connect(url: string): Promise; + static connect(url: string, callback: Callback): void; + static connect(url: string, options: MongoClientOptions): Promise; + static connect(url: string, options: MongoClientOptions, callback: Callback): void; + /** Starts a new session on the server */ + startSession(): ClientSession; + startSession(options: ClientSessionOptions): ClientSession; + /** + * Runs a given operation with an implicitly created session. The lifetime of the session + * will be handled without the need for user interaction. + * + * NOTE: presently the operation MUST return a Promise (either explicit or implicitly as an async function) + * + * @param options - Optional settings for the command + * @param callback - An callback to execute with an implicitly created session + */ + withSession(callback: WithSessionCallback): Promise; + withSession(options: ClientSessionOptions, callback: WithSessionCallback): Promise; + /** + * Create a new Change Stream, watching for new changes (insertions, updates, + * replacements, deletions, and invalidations) in this cluster. Will ignore all + * changes to system collections, as well as the local, admin, and config databases. + * + * @remarks + * watch() accepts two generic arguments for distinct usecases: + * - The first is to provide the schema that may be defined for all the data within the current cluster + * - The second is to override the shape of the change stream document entirely, if it is not provided the type will default to ChangeStreamDocument of the first argument + * + * @param pipeline - An array of {@link https://docs.mongodb.com/manual/reference/operator/aggregation-pipeline/|aggregation pipeline stages} through which to pass change stream documents. This allows for filtering (using $match) and manipulating the change stream documents. + * @param options - Optional settings for the command + * @typeParam TSchema - Type of the data being detected by the change stream + * @typeParam TChange - Type of the whole change stream document emitted + */ + watch>(pipeline?: Document[], options?: ChangeStreamOptions): ChangeStream; + /** Return the mongo client logger */ + getLogger(): Logger; +} + +/** @public */ +export declare type MongoClientEvents = Pick & { + open(mongoClient: MongoClient): void; +}; + +/** + * Describes all possible URI query options for the mongo client + * @public + * @see https://docs.mongodb.com/manual/reference/connection-string + */ +export declare interface MongoClientOptions extends BSONSerializeOptions, SupportedNodeConnectionOptions { + /** Specifies the name of the replica set, if the mongod is a member of a replica set. */ + replicaSet?: string; + /** Enables or disables TLS/SSL for the connection. */ + tls?: boolean; + /** A boolean to enable or disables TLS/SSL for the connection. (The ssl option is equivalent to the tls option.) */ + ssl?: boolean; + /** Specifies the location of a local TLS Certificate */ + tlsCertificateFile?: string; + /** Specifies the location of a local .pem file that contains either the client's TLS/SSL certificate and key or only the client's TLS/SSL key when tlsCertificateFile is used to provide the certificate. */ + tlsCertificateKeyFile?: string; + /** Specifies the password to de-crypt the tlsCertificateKeyFile. */ + tlsCertificateKeyFilePassword?: string; + /** Specifies the location of a local .pem file that contains the root certificate chain from the Certificate Authority. This file is used to validate the certificate presented by the mongod/mongos instance. */ + tlsCAFile?: string; + /** Bypasses validation of the certificates presented by the mongod/mongos instance */ + tlsAllowInvalidCertificates?: boolean; + /** Disables hostname validation of the certificate presented by the mongod/mongos instance. */ + tlsAllowInvalidHostnames?: boolean; + /** Disables various certificate validations. */ + tlsInsecure?: boolean; + /** The time in milliseconds to attempt a connection before timing out. */ + connectTimeoutMS?: number; + /** The time in milliseconds to attempt a send or receive on a socket before the attempt times out. */ + socketTimeoutMS?: number; + /** An array or comma-delimited string of compressors to enable network compression for communication between this client and a mongod/mongos instance. */ + compressors?: CompressorName[] | string; + /** An integer that specifies the compression level if using zlib for network compression. */ + zlibCompressionLevel?: 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | undefined; + /** The maximum number of hosts to connect to when using an srv connection string, a setting of `0` means unlimited hosts */ + srvMaxHosts?: number; + /** + * Modifies the srv URI to look like: + * + * `_{srvServiceName}._tcp.{hostname}.{domainname}` + * + * Querying this DNS URI is expected to respond with SRV records + */ + srvServiceName?: string; + /** The maximum number of connections in the connection pool. */ + maxPoolSize?: number; + /** The minimum number of connections in the connection pool. */ + minPoolSize?: number; + /** The maximum number of connections that may be in the process of being established concurrently by the connection pool. */ + maxConnecting?: number; + /** The maximum number of milliseconds that a connection can remain idle in the pool before being removed and closed. */ + maxIdleTimeMS?: number; + /** The maximum time in milliseconds that a thread can wait for a connection to become available. */ + waitQueueTimeoutMS?: number; + /** Specify a read concern for the collection (only MongoDB 3.2 or higher supported) */ + readConcern?: ReadConcernLike; + /** The level of isolation */ + readConcernLevel?: ReadConcernLevel; + /** Specifies the read preferences for this connection */ + readPreference?: ReadPreferenceMode | ReadPreference; + /** Specifies, in seconds, how stale a secondary can be before the client stops using it for read operations. */ + maxStalenessSeconds?: number; + /** Specifies the tags document as a comma-separated list of colon-separated key-value pairs. */ + readPreferenceTags?: TagSet[]; + /** The auth settings for when connection to server. */ + auth?: Auth; + /** Specify the database name associated with the user’s credentials. */ + authSource?: string; + /** Specify the authentication mechanism that MongoDB will use to authenticate the connection. */ + authMechanism?: AuthMechanism; + /** Specify properties for the specified authMechanism as a comma-separated list of colon-separated key-value pairs. */ + authMechanismProperties?: AuthMechanismProperties; + /** The size (in milliseconds) of the latency window for selecting among multiple suitable MongoDB instances. */ + localThresholdMS?: number; + /** Specifies how long (in milliseconds) to block for server selection before throwing an exception. */ + serverSelectionTimeoutMS?: number; + /** heartbeatFrequencyMS controls when the driver checks the state of the MongoDB deployment. Specify the interval (in milliseconds) between checks, counted from the end of the previous check until the beginning of the next one. */ + heartbeatFrequencyMS?: number; + /** Sets the minimum heartbeat frequency. In the event that the driver has to frequently re-check a server's availability, it will wait at least this long since the previous check to avoid wasted effort. */ + minHeartbeatFrequencyMS?: number; + /** The name of the application that created this MongoClient instance. MongoDB 3.4 and newer will print this value in the server log upon establishing each connection. It is also recorded in the slow query log and profile collections */ + appName?: string; + /** Enables retryable reads. */ + retryReads?: boolean; + /** Enable retryable writes. */ + retryWrites?: boolean; + /** Allow a driver to force a Single topology type with a connection string containing one host */ + directConnection?: boolean; + /** Instruct the driver it is connecting to a load balancer fronting a mongos like service */ + loadBalanced?: boolean; + /** The write concern w value */ + w?: W; + /** The write concern timeout */ + wtimeoutMS?: number; + /** The journal write concern */ + journal?: boolean; + /** Validate mongod server certificate against Certificate Authority */ + sslValidate?: boolean; + /** SSL Certificate file path. */ + sslCA?: string; + /** SSL Certificate file path. */ + sslCert?: string; + /** SSL Key file file path. */ + sslKey?: string; + /** SSL Certificate pass phrase. */ + sslPass?: string; + /** SSL Certificate revocation list file path. */ + sslCRL?: string; + /** TCP Connection no delay */ + noDelay?: boolean; + /** TCP Connection keep alive enabled */ + keepAlive?: boolean; + /** The number of milliseconds to wait before initiating keepAlive on the TCP socket */ + keepAliveInitialDelay?: number; + /** Force server to assign `_id` values instead of driver */ + forceServerObjectId?: boolean; + /** Return document results as raw BSON buffers */ + raw?: boolean; + /** A primary key factory function for generation of custom `_id` keys */ + pkFactory?: PkFactory; + /** A Promise library class the application wishes to use such as Bluebird, must be ES6 compatible */ + promiseLibrary?: any; + /** The logging level */ + loggerLevel?: LoggerLevel; + /** Custom logger object */ + logger?: Logger; + /** Enable command monitoring for this client */ + monitorCommands?: boolean; + /** Server API version */ + serverApi?: ServerApi | ServerApiVersion; + /** + * Optionally enable client side auto encryption + * + * @remarks + * Automatic encryption is an enterprise only feature that only applies to operations on a collection. Automatic encryption is not supported for operations on a database or view, and operations that are not bypassed will result in error + * (see [libmongocrypt: Auto Encryption Allow-List](https://github.com/mongodb/specifications/blob/master/source/client-side-encryption/client-side-encryption.rst#libmongocrypt-auto-encryption-allow-list)). To bypass automatic encryption for all operations, set bypassAutoEncryption=true in AutoEncryptionOpts. + * + * Automatic encryption requires the authenticated user to have the [listCollections privilege action](https://docs.mongodb.com/manual/reference/command/listCollections/#dbcmd.listCollections). + * + * If a MongoClient with a limited connection pool size (i.e a non-zero maxPoolSize) is configured with AutoEncryptionOptions, a separate internal MongoClient is created if any of the following are true: + * - AutoEncryptionOptions.keyVaultClient is not passed. + * - AutoEncryptionOptions.bypassAutomaticEncryption is false. + * + * If an internal MongoClient is created, it is configured with the same options as the parent MongoClient except minPoolSize is set to 0 and AutoEncryptionOptions is omitted. + */ + autoEncryption?: AutoEncryptionOptions; + /** Allows a wrapping driver to amend the client metadata generated by the driver to include information about the wrapping driver */ + driverInfo?: DriverInfo; + /** Configures a Socks5 proxy host used for creating TCP connections. */ + proxyHost?: string; + /** Configures a Socks5 proxy port used for creating TCP connections. */ + proxyPort?: number; + /** Configures a Socks5 proxy username when the proxy in proxyHost requires username/password authentication. */ + proxyUsername?: string; + /** Configures a Socks5 proxy password when the proxy in proxyHost requires username/password authentication. */ + proxyPassword?: string; + /* Excluded from this release type: srvPoller */ + /* Excluded from this release type: connectionType */ + /* Excluded from this release type: __index */ +} + +/* Excluded from this release type: MongoClientPrivate */ + +/** + * An error generated when a feature that is not enabled or allowed for the current server + * configuration is used + * + * + * @public + * @category Error + */ +export declare class MongoCompatibilityError extends MongoAPIError { + constructor(message: string); + get name(): string; +} + +/** + * A representation of the credentials used by MongoDB + * @public + */ +export declare class MongoCredentials { + /** The username used for authentication */ + readonly username: string; + /** The password used for authentication */ + readonly password: string; + /** The database that the user should authenticate against */ + readonly source: string; + /** The method used to authenticate */ + readonly mechanism: AuthMechanism; + /** Special properties used by some types of auth mechanisms */ + readonly mechanismProperties: AuthMechanismProperties; + constructor(options: MongoCredentialsOptions); + /** Determines if two MongoCredentials objects are equivalent */ + equals(other: MongoCredentials): boolean; + /** + * If the authentication mechanism is set to "default", resolves the authMechanism + * based on the server version and server supported sasl mechanisms. + * + * @param hello - A hello response from the server + */ + resolveAuthMechanism(hello?: Document): MongoCredentials; + validate(): void; + static merge(creds: MongoCredentials | undefined, options: Partial): MongoCredentials; +} + +/** @public */ +export declare interface MongoCredentialsOptions { + username: string; + password: string; + source: string; + db?: string; + mechanism?: AuthMechanism; + mechanismProperties: AuthMechanismProperties; +} + +/** + * An error thrown when an attempt is made to read from a cursor that has been exhausted + * + * @public + * @category Error + */ +export declare class MongoCursorExhaustedError extends MongoAPIError { + constructor(message?: string); + get name(): string; +} + +/** + * An error thrown when the user attempts to add options to a cursor that has already been + * initialized + * + * @public + * @category Error + */ +export declare class MongoCursorInUseError extends MongoAPIError { + constructor(message?: string); + get name(): string; +} + +/** @public */ +export declare class MongoDBNamespace { + db: string; + collection?: string; + /** + * Create a namespace object + * + * @param db - database name + * @param collection - collection name + */ + constructor(db: string, collection?: string); + toString(): string; + withCollection(collection: string): MongoDBNamespace; + static fromString(namespace?: string): MongoDBNamespace; +} + +/** + * An error generated when the driver fails to decompress + * data received from the server. + * + * @public + * @category Error + */ +export declare class MongoDecompressionError extends MongoRuntimeError { + constructor(message: string); + get name(): string; +} + +/** + * An error generated by the driver + * + * @public + * @category Error + */ +export declare class MongoDriverError extends MongoError { + constructor(message: string); + get name(): string; +} + +/** + * @public + * @category Error + * + * @privateRemarks + * CSFLE has a dependency on this error, it uses the constructor with a string argument + */ +export declare class MongoError extends Error { + /* Excluded from this release type: [kErrorLabels] */ + /** + * This is a number in MongoServerError and a string in MongoDriverError + * @privateRemarks + * Define the type override on the subclasses when we can use the override keyword + */ + code?: number | string; + topologyVersion?: TopologyVersion; + constructor(message: string | Error); + get name(): string; + /** Legacy name for server error responses */ + get errmsg(): string; + /** + * Checks the error to see if it has an error label + * + * @param label - The error label to check for + * @returns returns true if the error has the provided error label + */ + hasErrorLabel(label: string): boolean; + addErrorLabel(label: string): void; + get errorLabels(): string[]; +} + +/** @public */ +export declare const MongoErrorLabel: Readonly<{ + readonly RetryableWriteError: "RetryableWriteError"; + readonly TransientTransactionError: "TransientTransactionError"; + readonly UnknownTransactionCommitResult: "UnknownTransactionCommitResult"; + readonly ResumableChangeStreamError: "ResumableChangeStreamError"; + readonly HandshakeError: "HandshakeError"; +}>; + +/** @public */ +export declare type MongoErrorLabel = typeof MongoErrorLabel[keyof typeof MongoErrorLabel]; + +/** + * An error generated when the user attempts to operate + * on a session that has expired or has been closed. + * + * @public + * @category Error + */ +export declare class MongoExpiredSessionError extends MongoAPIError { + constructor(message?: string); + get name(): string; +} + +/** + * An error generated when a malformed or invalid chunk is + * encountered when reading from a GridFSStream. + * + * @public + * @category Error + */ +export declare class MongoGridFSChunkError extends MongoRuntimeError { + constructor(message: string); + get name(): string; +} + +/** An error generated when a GridFSStream operation fails to execute. + * + * @public + * @category Error + */ +export declare class MongoGridFSStreamError extends MongoRuntimeError { + constructor(message: string); + get name(): string; +} + +/** + * An error generated when the user supplies malformed or unexpected arguments + * or when a required argument or field is not provided. + * + * + * @public + * @category Error + */ +export declare class MongoInvalidArgumentError extends MongoAPIError { + constructor(message: string); + get name(): string; +} + +/** + * A error generated when the user attempts to authenticate + * via Kerberos, but fails to connect to the Kerberos client. + * + * @public + * @category Error + */ +export declare class MongoKerberosError extends MongoRuntimeError { + constructor(message: string); + get name(): string; +} + +/** + * An error generated when the user fails to provide authentication credentials before attempting + * to connect to a mongo server instance. + * + * + * @public + * @category Error + */ +export declare class MongoMissingCredentialsError extends MongoAPIError { + constructor(message: string); + get name(): string; +} + +/** + * An error generated when a required module or dependency is not present in the local environment + * + * @public + * @category Error + */ +export declare class MongoMissingDependencyError extends MongoAPIError { + constructor(message: string); + get name(): string; +} + +/** + * An error indicating an issue with the network, including TCP errors and timeouts. + * @public + * @category Error + */ +export declare class MongoNetworkError extends MongoError { + /* Excluded from this release type: [kBeforeHandshake] */ + constructor(message: string | Error, options?: MongoNetworkErrorOptions); + get name(): string; +} + +/** @public */ +export declare interface MongoNetworkErrorOptions { + /** Indicates the timeout happened before a connection handshake completed */ + beforeHandshake: boolean; +} + +/** + * An error indicating a network timeout occurred + * @public + * @category Error + * + * @privateRemarks + * CSFLE has a dependency on this error with an instanceof check + */ +export declare class MongoNetworkTimeoutError extends MongoNetworkError { + constructor(message: string, options?: MongoNetworkErrorOptions); + get name(): string; +} + +/** + * An error thrown when the user attempts to operate on a database or collection through a MongoClient + * that has not yet successfully called the "connect" method + * + * @public + * @category Error + */ +export declare class MongoNotConnectedError extends MongoAPIError { + constructor(message: string); + get name(): string; +} + +/** + * Mongo Client Options + * @public + */ +export declare interface MongoOptions extends Required>, SupportedNodeConnectionOptions { + hosts: HostAddress[]; + srvHost?: string; + credentials?: MongoCredentials; + readPreference: ReadPreference; + readConcern: ReadConcern; + loadBalanced: boolean; + serverApi: ServerApi; + compressors: CompressorName[]; + writeConcern: WriteConcern; + dbName: string; + metadata: ClientMetadata; + autoEncrypter?: AutoEncrypter; + proxyHost?: string; + proxyPort?: number; + proxyUsername?: string; + proxyPassword?: string; + /* Excluded from this release type: connectionType */ + /* Excluded from this release type: encrypter */ + /* Excluded from this release type: userSpecifiedAuthSource */ + /* Excluded from this release type: userSpecifiedReplicaSet */ + /** + * # NOTE ABOUT TLS Options + * + * If set TLS enabled, equivalent to setting the ssl option. + * + * ### Additional options: + * + * | nodejs option | MongoDB equivalent | type | + * |:---------------------|--------------------------------------------------------- |:---------------------------------------| + * | `ca` | `sslCA`, `tlsCAFile` | `string \| Buffer \| Buffer[]` | + * | `crl` | `sslCRL` | `string \| Buffer \| Buffer[]` | + * | `cert` | `sslCert`, `tlsCertificateFile`, `tlsCertificateKeyFile` | `string \| Buffer \| Buffer[]` | + * | `key` | `sslKey`, `tlsCertificateKeyFile` | `string \| Buffer \| KeyObject[]` | + * | `passphrase` | `sslPass`, `tlsCertificateKeyFilePassword` | `string` | + * | `rejectUnauthorized` | `sslValidate` | `boolean` | + * + */ + tls: boolean; + /* Excluded from this release type: __index */ +} + +/** + * An error used when attempting to parse a value (like a connection string) + * @public + * @category Error + */ +export declare class MongoParseError extends MongoDriverError { + constructor(message: string); + get name(): string; +} + +/** + * An error generated when the driver encounters unexpected input + * or reaches an unexpected/invalid internal state + * + * @privateRemarks + * Should **never** be directly instantiated. + * + * @public + * @category Error + */ +export declare class MongoRuntimeError extends MongoDriverError { + constructor(message: string); + get name(): string; +} + +/** + * An error generated when an attempt is made to operate + * on a closed/closing server. + * + * @public + * @category Error + */ +export declare class MongoServerClosedError extends MongoAPIError { + constructor(message?: string); + get name(): string; +} + +/** + * An error coming from the mongo server + * + * @public + * @category Error + */ +export declare class MongoServerError extends MongoError { + codeName?: string; + writeConcernError?: Document; + errInfo?: Document; + ok?: number; + [key: string]: any; + constructor(message: ErrorDescription); + get name(): string; +} + +/** + * An error signifying a client-side server selection error + * @public + * @category Error + */ +export declare class MongoServerSelectionError extends MongoSystemError { + constructor(message: string, reason: TopologyDescription); + get name(): string; +} + +/** + * An error signifying a general system issue + * @public + * @category Error + */ +export declare class MongoSystemError extends MongoError { + /** An optional reason context, such as an error saved during flow of monitoring and selecting servers */ + reason?: TopologyDescription; + constructor(message: string, reason: TopologyDescription); + get name(): string; +} + +/** + * An error thrown when the user calls a function or method not supported on a tailable cursor + * + * @public + * @category Error + */ +export declare class MongoTailableCursorError extends MongoAPIError { + constructor(message?: string); + get name(): string; +} + +/** + * An error generated when an attempt is made to operate on a + * dropped, or otherwise unavailable, database. + * + * @public + * @category Error + */ +export declare class MongoTopologyClosedError extends MongoAPIError { + constructor(message?: string); + get name(): string; +} + +/** + * An error generated when the user makes a mistake in the usage of transactions. + * (e.g. attempting to commit a transaction with a readPreference other than primary) + * + * @public + * @category Error + */ +export declare class MongoTransactionError extends MongoAPIError { + constructor(message: string); + get name(): string; +} + +/** + * An error generated when a **parsable** unexpected response comes from the server. + * This is generally an error where the driver in a state expecting a certain behavior to occur in + * the next message from MongoDB but it receives something else. + * This error **does not** represent an issue with wire message formatting. + * + * #### Example + * When an operation fails, it is the driver's job to retry it. It must perform serverSelection + * again to make sure that it attempts the operation against a server in a good state. If server + * selection returns a server that does not support retryable operations, this error is used. + * This scenario is unlikely as retryable support would also have been determined on the first attempt + * but it is possible the state change could report a selectable server that does not support retries. + * + * @public + * @category Error + */ +export declare class MongoUnexpectedServerResponseError extends MongoRuntimeError { + constructor(message: string); + get name(): string; +} + +/** + * An error thrown when the server reports a writeConcernError + * @public + * @category Error + */ +export declare class MongoWriteConcernError extends MongoServerError { + /** The result document (provided if ok: 1) */ + result?: Document; + constructor(message: ErrorDescription, result?: Document); + get name(): string; +} + +/* Excluded from this release type: Monitor */ + +/** @public */ +export declare type MonitorEvents = { + serverHeartbeatStarted(event: ServerHeartbeatStartedEvent): void; + serverHeartbeatSucceeded(event: ServerHeartbeatSucceededEvent): void; + serverHeartbeatFailed(event: ServerHeartbeatFailedEvent): void; + resetServer(error?: Error): void; + resetConnectionPool(): void; + close(): void; +} & EventEmitterWithState; + +/** @public */ +export declare interface MonitorOptions extends Omit { + connectTimeoutMS: number; + heartbeatFrequencyMS: number; + minHeartbeatFrequencyMS: number; +} + +/* Excluded from this release type: MonitorPrivate */ + +/* Excluded from this release type: Msg */ + +/** + * @public + * returns tuple of strings (keys to be joined on '.') that represent every path into a schema + * https://docs.mongodb.com/manual/tutorial/query-embedded-documents/ + */ +export declare type NestedPaths = Type extends string | number | boolean | Date | RegExp | Buffer | Uint8Array | ((...args: any[]) => any) | { + _bsontype: string; +} ? [] : Type extends ReadonlyArray ? [] | [number, ...NestedPaths] : Type extends Map ? [string] : Type extends object ? { + [Key in Extract]: Type[Key] extends Type ? [Key] : Type extends Type[Key] ? [Key] : Type[Key] extends ReadonlyArray ? Type extends ArrayType ? [Key] : ArrayType extends Type ? [Key] : [ + Key, + ...NestedPaths + ] : [ + Key, + ...NestedPaths + ]; +}[Extract] : []; + +/** + * @public + * returns keys (strings) for every path into a schema with a value of type + * https://docs.mongodb.com/manual/tutorial/query-embedded-documents/ + */ +export declare type NestedPathsOfType = KeysOfAType<{ + [Property in Join, '.'>]: PropertyType; +}, Type>; + +/** + * @public + * A type that extends Document but forbids anything that "looks like" an object id. + */ +export declare type NonObjectIdLikeDocument = { + [key in keyof ObjectIdLike]?: never; +} & Document; + +/** It avoids using fields with not acceptable types @public */ +export declare type NotAcceptedFields = { + readonly [key in KeysOfOtherType]?: never; +}; + +/** @public */ +export declare type NumericType = IntegerType | Decimal128 | Double; + +/** + * @public + * @deprecated Please use `ObjectId` + */ +export declare const ObjectID: typeof ObjectId; + +export { ObjectId } + +/** @public */ +export declare type OneOrMore = T | ReadonlyArray; + +/** @public */ +export declare type OnlyFieldsOfType = IsAny, AcceptedFields & NotAcceptedFields & Record>; + +/* Excluded from this release type: OperationDescription */ + +/** @public */ +export declare interface OperationOptions extends BSONSerializeOptions { + /** Specify ClientSession for this command */ + session?: ClientSession; + willRetryWrite?: boolean; + /** The preferred read preference (ReadPreference.primary, ReadPreference.primary_preferred, ReadPreference.secondary, ReadPreference.secondary_preferred, ReadPreference.nearest). */ + readPreference?: ReadPreferenceLike; + /* Excluded from this release type: bypassPinningCheck */ + omitReadPreference?: boolean; +} + +/* Excluded from this release type: OperationParent */ + +/** + * Represents a specific point in time on a server. Can be retrieved by using `db.command()` + * @public + * @see https://docs.mongodb.com/manual/reference/method/db.runCommand/#response + */ +export declare type OperationTime = Timestamp; + +/* Excluded from this release type: OpGetMoreOptions */ + +/* Excluded from this release type: OpMsgOptions */ + +/* Excluded from this release type: OpQueryOptions */ + +/* Excluded from this release type: OpResponseOptions */ + +/** + * Add an optional _id field to an object shaped type + * @public + */ +export declare type OptionalId = EnhancedOmit & { + _id?: InferIdType; +}; + +/** + * Adds an optional _id field to an object shaped type, unless the _id field is requried on that type. + * In the case _id is required, this method continues to require_id. + * + * @public + * + * @privateRemarks + * `ObjectId extends TSchema['_id']` is a confusing ordering at first glance. Rather than ask + * `TSchema['_id'] extends ObjectId` which translated to "Is the _id property ObjectId?" + * we instead ask "Does ObjectId look like (have the same shape) as the _id?" + */ +export declare type OptionalUnlessRequiredId = TSchema extends { + _id: any; +} ? TSchema : OptionalId; + +/** @public */ +export declare class OrderedBulkOperation extends BulkOperationBase { + constructor(collection: Collection, options: BulkWriteOptions); + addToOperationsList(batchType: BatchType, document: Document | UpdateStatement | DeleteStatement): this; +} + +/** @public */ +export declare interface PipeOptions { + end?: boolean; +} + +/** @public */ +export declare interface PkFactory { + createPk(): any; +} + +/** @public */ +export declare const ProfilingLevel: Readonly<{ + readonly off: "off"; + readonly slowOnly: "slow_only"; + readonly all: "all"; +}>; + +/** @public */ +export declare type ProfilingLevel = typeof ProfilingLevel[keyof typeof ProfilingLevel]; + +/** @public */ +export declare type ProfilingLevelOptions = CommandOperationOptions; + +/** + * @public + * Projection is flexible to permit the wide array of aggregation operators + * @deprecated since v4.1.0: Since projections support all aggregation operations we have no plans to narrow this type further + */ +export declare type Projection = Document; + +/** + * @public + * @deprecated since v4.1.0: Since projections support all aggregation operations we have no plans to narrow this type further + */ +export declare type ProjectionOperators = Document; + +/** + * Global promise store allowing user-provided promises + * @public + */ +declare class Promise_2 { + /** Validates the passed in promise library */ + static validate(lib: unknown): lib is PromiseConstructor; + /** Sets the promise library */ + static set(lib: PromiseConstructor): void; + /** Get the stored promise library, or resolves passed in */ + static get(): PromiseConstructor; +} +export { Promise_2 as Promise } + +/** @public */ +export declare type PropertyType = string extends Property ? unknown : Property extends keyof Type ? Type[Property] : Property extends `${number}` ? Type extends ReadonlyArray ? ArrayType : unknown : Property extends `${infer Key}.${infer Rest}` ? Key extends `${number}` ? Type extends ReadonlyArray ? PropertyType : unknown : Key extends keyof Type ? Type[Key] extends Map ? MapType : PropertyType : unknown : unknown; + +/** @public */ +export declare interface ProxyOptions { + proxyHost?: string; + proxyPort?: number; + proxyUsername?: string; + proxyPassword?: string; +} + +/** @public */ +export declare type PullAllOperator = ({ + readonly [key in KeysOfAType>]?: TSchema[key]; +} & NotAcceptedFields>) & { + readonly [key: string]: ReadonlyArray; +}; + +/** @public */ +export declare type PullOperator = ({ + readonly [key in KeysOfAType>]?: Partial> | FilterOperations>; +} & NotAcceptedFields>) & { + readonly [key: string]: FilterOperators | any; +}; + +/** @public */ +export declare type PushOperator = ({ + readonly [key in KeysOfAType>]?: Flatten | ArrayOperator>>; +} & NotAcceptedFields>) & { + readonly [key: string]: ArrayOperator | any; +}; + +/* Excluded from this release type: Query */ + +/* Excluded from this release type: QueryOptions */ + +/** + * The MongoDB ReadConcern, which allows for control of the consistency and isolation properties + * of the data read from replica sets and replica set shards. + * @public + * + * @see https://docs.mongodb.com/manual/reference/read-concern/index.html + */ +export declare class ReadConcern { + level: ReadConcernLevel | string; + /** Constructs a ReadConcern from the read concern level.*/ + constructor(level: ReadConcernLevel); + /** + * Construct a ReadConcern given an options object. + * + * @param options - The options object from which to extract the write concern. + */ + static fromOptions(options?: { + readConcern?: ReadConcernLike; + level?: ReadConcernLevel; + }): ReadConcern | undefined; + static get MAJORITY(): 'majority'; + static get AVAILABLE(): 'available'; + static get LINEARIZABLE(): 'linearizable'; + static get SNAPSHOT(): 'snapshot'; + toJSON(): Document; +} + +/** @public */ +export declare const ReadConcernLevel: Readonly<{ + readonly local: "local"; + readonly majority: "majority"; + readonly linearizable: "linearizable"; + readonly available: "available"; + readonly snapshot: "snapshot"; +}>; + +/** @public */ +export declare type ReadConcernLevel = typeof ReadConcernLevel[keyof typeof ReadConcernLevel]; + +/** @public */ +export declare type ReadConcernLike = ReadConcern | { + level: ReadConcernLevel; +} | ReadConcernLevel; + +/** + * The **ReadPreference** class is a class that represents a MongoDB ReadPreference and is + * used to construct connections. + * @public + * + * @see https://docs.mongodb.com/manual/core/read-preference/ + */ +export declare class ReadPreference { + mode: ReadPreferenceMode; + tags?: TagSet[]; + hedge?: HedgeOptions; + maxStalenessSeconds?: number; + minWireVersion?: number; + static PRIMARY: "primary"; + static PRIMARY_PREFERRED: "primaryPreferred"; + static SECONDARY: "secondary"; + static SECONDARY_PREFERRED: "secondaryPreferred"; + static NEAREST: "nearest"; + static primary: ReadPreference; + static primaryPreferred: ReadPreference; + static secondary: ReadPreference; + static secondaryPreferred: ReadPreference; + static nearest: ReadPreference; + /** + * @param mode - A string describing the read preference mode (primary|primaryPreferred|secondary|secondaryPreferred|nearest) + * @param tags - A tag set used to target reads to members with the specified tag(s). tagSet is not available if using read preference mode primary. + * @param options - Additional read preference options + */ + constructor(mode: ReadPreferenceMode, tags?: TagSet[], options?: ReadPreferenceOptions); + get preference(): ReadPreferenceMode; + static fromString(mode: string): ReadPreference; + /** + * Construct a ReadPreference given an options object. + * + * @param options - The options object from which to extract the read preference. + */ + static fromOptions(options?: ReadPreferenceFromOptions): ReadPreference | undefined; + /** + * Replaces options.readPreference with a ReadPreference instance + */ + static translate(options: ReadPreferenceLikeOptions): ReadPreferenceLikeOptions; + /** + * Validate if a mode is legal + * + * @param mode - The string representing the read preference mode. + */ + static isValid(mode: string): boolean; + /** + * Validate if a mode is legal + * + * @param mode - The string representing the read preference mode. + */ + isValid(mode?: string): boolean; + /** + * Indicates that this readPreference needs the "secondaryOk" bit when sent over the wire + * @deprecated Use secondaryOk instead + * @see https://docs.mongodb.com/manual/reference/mongodb-wire-protocol/#op-query + */ + slaveOk(): boolean; + /** + * Indicates that this readPreference needs the "SecondaryOk" bit when sent over the wire + * @see https://docs.mongodb.com/manual/reference/mongodb-wire-protocol/#op-query + */ + secondaryOk(): boolean; + /** + * Check if the two ReadPreferences are equivalent + * + * @param readPreference - The read preference with which to check equality + */ + equals(readPreference: ReadPreference): boolean; + /** Return JSON representation */ + toJSON(): Document; +} + +/** @public */ +export declare interface ReadPreferenceFromOptions extends ReadPreferenceLikeOptions { + session?: ClientSession; + readPreferenceTags?: TagSet[]; + hedge?: HedgeOptions; +} + +/** @public */ +export declare type ReadPreferenceLike = ReadPreference | ReadPreferenceMode; + +/** @public */ +export declare interface ReadPreferenceLikeOptions extends ReadPreferenceOptions { + readPreference?: ReadPreferenceLike | { + mode?: ReadPreferenceMode; + preference?: ReadPreferenceMode; + tags?: TagSet[]; + maxStalenessSeconds?: number; + }; +} + +/** @public */ +export declare const ReadPreferenceMode: Readonly<{ + readonly primary: "primary"; + readonly primaryPreferred: "primaryPreferred"; + readonly secondary: "secondary"; + readonly secondaryPreferred: "secondaryPreferred"; + readonly nearest: "nearest"; +}>; + +/** @public */ +export declare type ReadPreferenceMode = typeof ReadPreferenceMode[keyof typeof ReadPreferenceMode]; + +/** @public */ +export declare interface ReadPreferenceOptions { + /** Max secondary read staleness in seconds, Minimum value is 90 seconds.*/ + maxStalenessSeconds?: number; + /** Server mode in which the same query is dispatched in parallel to multiple replica set members. */ + hedge?: HedgeOptions; +} + +/** @public */ +export declare type ReduceFunction = (key: TKey, values: TValue[]) => TValue; + +/** @public */ +export declare type RegExpOrString = T extends string ? BSONRegExp | RegExp | T : T; + +/** @public */ +export declare type RemoveUserOptions = CommandOperationOptions; + +/** @public */ +export declare interface RenameOptions extends CommandOperationOptions { + /** Drop the target name collection if it previously exists. */ + dropTarget?: boolean; + /** Unclear */ + new_collection?: boolean; +} + +/** @public */ +export declare interface ReplaceOneModel { + /** The filter to limit the replaced document. */ + filter: Filter; + /** The document with which to replace the matched document. */ + replacement: WithoutId; + /** Specifies a collation. */ + collation?: CollationOptions; + /** The index to use. If specified, then the query system will only consider plans using the hinted index. */ + hint?: Hint; + /** When true, creates a new document if no document matches the query. */ + upsert?: boolean; +} + +/** @public */ +export declare interface ReplaceOptions extends CommandOperationOptions { + /** If true, allows the write to opt-out of document level validation */ + bypassDocumentValidation?: boolean; + /** Specifies a collation */ + collation?: CollationOptions; + /** Specify that the update query should only consider plans using the hinted index */ + hint?: string | Document; + /** When true, creates a new document if no document matches the query */ + upsert?: boolean; + /** Map of parameter names and values that can be accessed using $$var (requires MongoDB 5.0). */ + let?: Document; +} + +/* Excluded from this release type: Response */ + +/** + * @public + * @deprecated Please use the ChangeStreamCursorOptions type instead. + */ +export declare interface ResumeOptions { + startAtOperationTime?: Timestamp; + batchSize?: number; + maxAwaitTimeMS?: number; + collation?: CollationOptions; + readPreference?: ReadPreference; + resumeAfter?: ResumeToken; + startAfter?: ResumeToken; + fullDocument?: string; +} + +/** + * Represents the logical starting point for a new ChangeStream or resuming a ChangeStream on the server. + * @see https://www.mongodb.com/docs/manual/changeStreams/#std-label-change-stream-resume + * @public + */ +export declare type ResumeToken = unknown; + +/** @public */ +export declare const ReturnDocument: Readonly<{ + readonly BEFORE: "before"; + readonly AFTER: "after"; +}>; + +/** @public */ +export declare type ReturnDocument = typeof ReturnDocument[keyof typeof ReturnDocument]; + +/** @public */ +export declare interface RoleSpecification { + /** + * A role grants privileges to perform sets of actions on defined resources. + * A given role applies to the database on which it is defined and can grant access down to a collection level of granularity. + */ + role: string; + /** The database this user's role should effect. */ + db: string; +} + +/** @public */ +export declare interface RootFilterOperators extends Document { + $and?: Filter[]; + $nor?: Filter[]; + $or?: Filter[]; + $text?: { + $search: string; + $language?: string; + $caseSensitive?: boolean; + $diacriticSensitive?: boolean; + }; + $where?: string | ((this: TSchema) => boolean); + $comment?: string | Document; +} + +/* Excluded from this release type: RTTPinger */ + +/* Excluded from this release type: RTTPingerOptions */ + +/** @public */ +export declare type RunCommandOptions = CommandOperationOptions; + +/** @public */ +export declare type SchemaMember = { + [P in keyof T]?: V; +} | { + [key: string]: V; +}; + +/** @public */ +export declare interface SelectServerOptions { + readPreference?: ReadPreferenceLike; + /** How long to block for server selection before throwing an error */ + serverSelectionTimeoutMS?: number; + session?: ClientSession; +} + +/* Excluded from this release type: serialize */ + +/* Excluded from this release type: Server */ + +/** @public */ +export declare interface ServerApi { + version: ServerApiVersion; + strict?: boolean; + deprecationErrors?: boolean; +} + +/** @public */ +export declare const ServerApiVersion: Readonly<{ + readonly v1: "1"; +}>; + +/** @public */ +export declare type ServerApiVersion = typeof ServerApiVersion[keyof typeof ServerApiVersion]; + +/** @public */ +export declare class ServerCapabilities { + maxWireVersion: number; + minWireVersion: number; + constructor(hello: Document); + get hasAggregationCursor(): boolean; + get hasWriteCommands(): boolean; + get hasTextSearch(): boolean; + get hasAuthCommands(): boolean; + get hasListCollectionsCommand(): boolean; + get hasListIndexesCommand(): boolean; + get supportsSnapshotReads(): boolean; + get commandsTakeWriteConcern(): boolean; + get commandsTakeCollation(): boolean; +} + +/** + * Emitted when server is closed. + * @public + * @category Event + */ +export declare class ServerClosedEvent { + /** A unique identifier for the topology */ + topologyId: number; + /** The address (host/port pair) of the server */ + address: string; + /* Excluded from this release type: __constructor */ +} + +/** + * The client's view of a single server, based on the most recent hello outcome. + * + * Internal type, not meant to be directly instantiated + * @public + */ +export declare class ServerDescription { + private _hostAddress; + address: string; + type: ServerType; + hosts: string[]; + passives: string[]; + arbiters: string[]; + tags: TagSet; + error?: MongoError; + topologyVersion?: TopologyVersion; + minWireVersion: number; + maxWireVersion: number; + roundTripTime: number; + lastUpdateTime: number; + lastWriteDate: number; + me?: string; + primary?: string; + setName?: string; + setVersion?: number; + electionId?: ObjectId; + logicalSessionTimeoutMinutes?: number; + $clusterTime?: ClusterTime; + /* Excluded from this release type: __constructor */ + get hostAddress(): HostAddress; + get allHosts(): string[]; + /** Is this server available for reads*/ + get isReadable(): boolean; + /** Is this server data bearing */ + get isDataBearing(): boolean; + /** Is this server available for writes */ + get isWritable(): boolean; + get host(): string; + get port(): number; + /** + * Determines if another `ServerDescription` is equal to this one per the rules defined + * in the {@link https://github.com/mongodb/specifications/blob/master/source/server-discovery-and-monitoring/server-discovery-and-monitoring.rst#serverdescription|SDAM spec} + */ + equals(other: ServerDescription): boolean; +} + +/** + * Emitted when server description changes, but does NOT include changes to the RTT. + * @public + * @category Event + */ +export declare class ServerDescriptionChangedEvent { + /** A unique identifier for the topology */ + topologyId: number; + /** The address (host/port pair) of the server */ + address: string; + /** The previous server description */ + previousDescription: ServerDescription; + /** The new server description */ + newDescription: ServerDescription; + /* Excluded from this release type: __constructor */ +} + +/* Excluded from this release type: ServerDescriptionOptions */ + +/** @public */ +export declare type ServerEvents = { + serverHeartbeatStarted(event: ServerHeartbeatStartedEvent): void; + serverHeartbeatSucceeded(event: ServerHeartbeatSucceededEvent): void; + serverHeartbeatFailed(event: ServerHeartbeatFailedEvent): void; + /* Excluded from this release type: connect */ + descriptionReceived(description: ServerDescription): void; + closed(): void; + ended(): void; +} & ConnectionPoolEvents & EventEmitterWithState; + +/** + * Emitted when the server monitor’s hello fails, either with an “ok: 0” or a socket exception. + * @public + * @category Event + */ +export declare class ServerHeartbeatFailedEvent { + /** The connection id for the command */ + connectionId: string; + /** The execution time of the event in ms */ + duration: number; + /** The command failure */ + failure: Error; + /* Excluded from this release type: __constructor */ +} + +/** + * Emitted when the server monitor’s hello command is started - immediately before + * the hello command is serialized into raw BSON and written to the socket. + * + * @public + * @category Event + */ +export declare class ServerHeartbeatStartedEvent { + /** The connection id for the command */ + connectionId: string; + /* Excluded from this release type: __constructor */ +} + +/** + * Emitted when the server monitor’s hello succeeds. + * @public + * @category Event + */ +export declare class ServerHeartbeatSucceededEvent { + /** The connection id for the command */ + connectionId: string; + /** The execution time of the event in ms */ + duration: number; + /** The command reply */ + reply: Document; + /* Excluded from this release type: __constructor */ +} + +/** + * Emitted when server is initialized. + * @public + * @category Event + */ +export declare class ServerOpeningEvent { + /** A unique identifier for the topology */ + topologyId: number; + /** The address (host/port pair) of the server */ + address: string; + /* Excluded from this release type: __constructor */ +} + +/** @public */ +export declare type ServerOptions = Omit & MonitorOptions; + +/* Excluded from this release type: ServerPrivate */ + +/* Excluded from this release type: ServerSelectionCallback */ + +/* Excluded from this release type: ServerSelectionRequest */ + +/** @public */ +export declare type ServerSelector = (topologyDescription: TopologyDescription, servers: ServerDescription[]) => ServerDescription[]; + +/** + * Reflects the existence of a session on the server. Can be reused by the session pool. + * WARNING: not meant to be instantiated directly. For internal use only. + * @public + */ +export declare class ServerSession { + id: ServerSessionId; + lastUse: number; + txnNumber: number; + isDirty: boolean; + /* Excluded from this release type: __constructor */ + /** + * Determines if the server session has timed out. + * + * @param sessionTimeoutMinutes - The server's "logicalSessionTimeoutMinutes" + */ + hasTimedOut(sessionTimeoutMinutes: number): boolean; + /* Excluded from this release type: clone */ +} + +/** @public */ +export declare type ServerSessionId = { + id: Binary; +}; + +/* Excluded from this release type: ServerSessionPool */ + +/** + * An enumeration of server types we know about + * @public + */ +export declare const ServerType: Readonly<{ + readonly Standalone: "Standalone"; + readonly Mongos: "Mongos"; + readonly PossiblePrimary: "PossiblePrimary"; + readonly RSPrimary: "RSPrimary"; + readonly RSSecondary: "RSSecondary"; + readonly RSArbiter: "RSArbiter"; + readonly RSOther: "RSOther"; + readonly RSGhost: "RSGhost"; + readonly Unknown: "Unknown"; + readonly LoadBalancer: "LoadBalancer"; +}>; + +/** @public */ +export declare type ServerType = typeof ServerType[keyof typeof ServerType]; + +/** @public */ +export declare type SetFields = ({ + readonly [key in KeysOfAType | undefined>]?: OptionalId> | AddToSetOperators>>>; +} & NotAcceptedFields | undefined>) & { + readonly [key: string]: AddToSetOperators | any; +}; + +/** @public */ +export declare type SetProfilingLevelOptions = CommandOperationOptions; + +/** @public */ +export declare type Sort = string | Exclude | string[] | { + [key: string]: SortDirection; +} | Map | [string, SortDirection][] | [string, SortDirection]; + +/** @public */ +export declare type SortDirection = 1 | -1 | 'asc' | 'desc' | 'ascending' | 'descending' | { + $meta: string; +}; + +/* Excluded from this release type: SortDirectionForCmd */ + +/* Excluded from this release type: SortForCmd */ + +/* Excluded from this release type: SrvPoller */ + +/* Excluded from this release type: SrvPollerEvents */ + +/* Excluded from this release type: SrvPollerOptions */ + +/* Excluded from this release type: SrvPollingEvent */ + +/** @public */ +export declare type Stream = Socket | TLSSocket; + +/** @public */ +export declare class StreamDescription { + address: string; + type: string; + minWireVersion?: number; + maxWireVersion?: number; + maxBsonObjectSize: number; + maxMessageSizeBytes: number; + maxWriteBatchSize: number; + compressors: CompressorName[]; + compressor?: CompressorName; + logicalSessionTimeoutMinutes?: number; + loadBalanced: boolean; + __nodejs_mock_server__?: boolean; + zlibCompressionLevel?: number; + constructor(address: string, options?: StreamDescriptionOptions); + receiveResponse(response: Document | null): void; +} + +/** @public */ +export declare interface StreamDescriptionOptions { + compressors?: CompressorName[]; + logicalSessionTimeoutMinutes?: number; + loadBalanced: boolean; +} + +/** @public */ +export declare type SupportedNodeConnectionOptions = SupportedTLSConnectionOptions & SupportedTLSSocketOptions & SupportedSocketOptions; + +/** @public */ +export declare type SupportedSocketOptions = Pick; + +/** @public */ +export declare type SupportedTLSConnectionOptions = Pick>; + +/** @public */ +export declare type SupportedTLSSocketOptions = Pick>; + +/** @public */ +export declare type TagSet = { + [key: string]: string; +}; + +/* Excluded from this release type: TimerQueue */ + +/** @public + * Configuration options for timeseries collections + * @see https://docs.mongodb.com/manual/core/timeseries-collections/ + */ +export declare interface TimeSeriesCollectionOptions extends Document { + timeField: string; + metaField?: string; + granularity?: 'seconds' | 'minutes' | 'hours' | string; +} + +export { Timestamp } + +/* Excluded from this release type: Topology */ + +/** + * Emitted when topology is closed. + * @public + * @category Event + */ +export declare class TopologyClosedEvent { + /** A unique identifier for the topology */ + topologyId: number; + /* Excluded from this release type: __constructor */ +} + +/** + * Representation of a deployment of servers + * @public + */ +export declare class TopologyDescription { + type: TopologyType; + setName?: string; + maxSetVersion?: number; + maxElectionId?: ObjectId; + servers: Map; + stale: boolean; + compatible: boolean; + compatibilityError?: string; + logicalSessionTimeoutMinutes?: number; + heartbeatFrequencyMS: number; + localThresholdMS: number; + commonWireVersion?: number; + /** + * Create a TopologyDescription + */ + constructor(topologyType: TopologyType, serverDescriptions?: Map, setName?: string, maxSetVersion?: number, maxElectionId?: ObjectId, commonWireVersion?: number, options?: TopologyDescriptionOptions); + /* Excluded from this release type: updateFromSrvPollingEvent */ + /* Excluded from this release type: update */ + get error(): MongoError | undefined; + /** + * Determines if the topology description has any known servers + */ + get hasKnownServers(): boolean; + /** + * Determines if this topology description has a data-bearing server available. + */ + get hasDataBearingServers(): boolean; + /* Excluded from this release type: hasServer */ +} + +/** + * Emitted when topology description changes. + * @public + * @category Event + */ +export declare class TopologyDescriptionChangedEvent { + /** A unique identifier for the topology */ + topologyId: number; + /** The old topology description */ + previousDescription: TopologyDescription; + /** The new topology description */ + newDescription: TopologyDescription; + /* Excluded from this release type: __constructor */ +} + +/** @public */ +export declare interface TopologyDescriptionOptions { + heartbeatFrequencyMS?: number; + localThresholdMS?: number; +} + +/** @public */ +export declare type TopologyEvents = { + /* Excluded from this release type: connect */ + serverOpening(event: ServerOpeningEvent): void; + serverClosed(event: ServerClosedEvent): void; + serverDescriptionChanged(event: ServerDescriptionChangedEvent): void; + topologyClosed(event: TopologyClosedEvent): void; + topologyOpening(event: TopologyOpeningEvent): void; + topologyDescriptionChanged(event: TopologyDescriptionChangedEvent): void; + error(error: Error): void; + /* Excluded from this release type: open */ + close(): void; + timeout(): void; +} & Omit & ConnectionPoolEvents & ConnectionEvents & EventEmitterWithState; + +/** + * Emitted when topology is initialized. + * @public + * @category Event + */ +export declare class TopologyOpeningEvent { + /** A unique identifier for the topology */ + topologyId: number; + /* Excluded from this release type: __constructor */ +} + +/** @public */ +export declare interface TopologyOptions extends BSONSerializeOptions, ServerOptions { + srvMaxHosts: number; + srvServiceName: string; + hosts: HostAddress[]; + retryWrites: boolean; + retryReads: boolean; + /** How long to block for server selection before throwing an error */ + serverSelectionTimeoutMS: number; + /** The name of the replica set to connect to */ + replicaSet?: string; + srvHost?: string; + /* Excluded from this release type: srvPoller */ + /** Indicates that a client should directly connect to a node without attempting to discover its topology type */ + directConnection: boolean; + loadBalanced: boolean; + metadata: ClientMetadata; + /** MongoDB server API version */ + serverApi?: ServerApi; + /* Excluded from this release type: __index */ +} + +/* Excluded from this release type: TopologyPrivate */ + +/** + * An enumeration of topology types we know about + * @public + */ +export declare const TopologyType: Readonly<{ + readonly Single: "Single"; + readonly ReplicaSetNoPrimary: "ReplicaSetNoPrimary"; + readonly ReplicaSetWithPrimary: "ReplicaSetWithPrimary"; + readonly Sharded: "Sharded"; + readonly Unknown: "Unknown"; + readonly LoadBalanced: "LoadBalanced"; +}>; + +/** @public */ +export declare type TopologyType = typeof TopologyType[keyof typeof TopologyType]; + +/** @public */ +export declare interface TopologyVersion { + processId: ObjectId; + counter: Long; +} + +/** + * @public + * A class maintaining state related to a server transaction. Internal Only + */ +export declare class Transaction { + /* Excluded from this release type: state */ + options: TransactionOptions; + /* Excluded from this release type: _pinnedServer */ + /* Excluded from this release type: _recoveryToken */ + /* Excluded from this release type: __constructor */ + /* Excluded from this release type: server */ + get recoveryToken(): Document | undefined; + get isPinned(): boolean; + /** @returns Whether the transaction has started */ + get isStarting(): boolean; + /** + * @returns Whether this session is presently in a transaction + */ + get isActive(): boolean; + get isCommitted(): boolean; + /* Excluded from this release type: transition */ + /* Excluded from this release type: pinServer */ + /* Excluded from this release type: unpinServer */ +} + +/** + * Configuration options for a transaction. + * @public + */ +export declare interface TransactionOptions extends CommandOperationOptions { + /** A default read concern for commands in this transaction */ + readConcern?: ReadConcernLike; + /** A default writeConcern for commands in this transaction */ + writeConcern?: WriteConcern; + /** A default read preference for commands in this transaction */ + readPreference?: ReadPreference; + /** Specifies the maximum amount of time to allow a commit action on a transaction to run in milliseconds */ + maxCommitTimeMS?: number; +} + +/* Excluded from this release type: TxnState */ + +/** + * Typescript type safe event emitter + * @public + */ +export declare interface TypedEventEmitter extends EventEmitter { + addListener(event: EventKey, listener: Events[EventKey]): this; + addListener(event: CommonEvents, listener: (eventName: string | symbol, listener: GenericListener) => void): this; + addListener(event: string | symbol, listener: GenericListener): this; + on(event: EventKey, listener: Events[EventKey]): this; + on(event: CommonEvents, listener: (eventName: string | symbol, listener: GenericListener) => void): this; + on(event: string | symbol, listener: GenericListener): this; + once(event: EventKey, listener: Events[EventKey]): this; + once(event: CommonEvents, listener: (eventName: string | symbol, listener: GenericListener) => void): this; + once(event: string | symbol, listener: GenericListener): this; + removeListener(event: EventKey, listener: Events[EventKey]): this; + removeListener(event: CommonEvents, listener: (eventName: string | symbol, listener: GenericListener) => void): this; + removeListener(event: string | symbol, listener: GenericListener): this; + off(event: EventKey, listener: Events[EventKey]): this; + off(event: CommonEvents, listener: (eventName: string | symbol, listener: GenericListener) => void): this; + off(event: string | symbol, listener: GenericListener): this; + removeAllListeners(event?: EventKey | CommonEvents | symbol | string): this; + listeners(event: EventKey | CommonEvents | symbol | string): Events[EventKey][]; + rawListeners(event: EventKey | CommonEvents | symbol | string): Events[EventKey][]; + emit(event: EventKey | symbol, ...args: Parameters): boolean; + listenerCount(type: EventKey | CommonEvents | symbol | string): number; + prependListener(event: EventKey, listener: Events[EventKey]): this; + prependListener(event: CommonEvents, listener: (eventName: string | symbol, listener: GenericListener) => void): this; + prependListener(event: string | symbol, listener: GenericListener): this; + prependOnceListener(event: EventKey, listener: Events[EventKey]): this; + prependOnceListener(event: CommonEvents, listener: (eventName: string | symbol, listener: GenericListener) => void): this; + prependOnceListener(event: string | symbol, listener: GenericListener): this; + eventNames(): string[]; + getMaxListeners(): number; + setMaxListeners(n: number): this; +} + +/** + * Typescript type safe event emitter + * @public + */ +export declare class TypedEventEmitter extends EventEmitter { +} + +/** @public */ +export declare class UnorderedBulkOperation extends BulkOperationBase { + constructor(collection: Collection, options: BulkWriteOptions); + handleWriteError(callback: Callback, writeResult: BulkWriteResult): boolean; + addToOperationsList(batchType: BatchType, document: Document | UpdateStatement | DeleteStatement): this; +} + +/** @public */ +export declare interface UpdateDescription { + /** + * A document containing key:value pairs of names of the fields that were + * changed, and the new value for those fields. + */ + updatedFields?: Partial; + /** + * An array of field names that were removed from the document. + */ + removedFields?: string[]; + /** + * An array of documents which record array truncations performed with pipeline-based updates using one or more of the following stages: + * - $addFields + * - $set + * - $replaceRoot + * - $replaceWith + */ + truncatedArrays?: Array<{ + /** The name of the truncated field. */ + field: string; + /** The number of elements in the truncated array. */ + newSize: number; + }>; +} + +/** @public */ +export declare type UpdateFilter = { + $currentDate?: OnlyFieldsOfType; + $inc?: OnlyFieldsOfType; + $min?: MatchKeysAndValues; + $max?: MatchKeysAndValues; + $mul?: OnlyFieldsOfType; + $rename?: Record; + $set?: MatchKeysAndValues; + $setOnInsert?: MatchKeysAndValues; + $unset?: OnlyFieldsOfType; + $addToSet?: SetFields; + $pop?: OnlyFieldsOfType, 1 | -1>; + $pull?: PullOperator; + $push?: PushOperator; + $pullAll?: PullAllOperator; + $bit?: OnlyFieldsOfType; +} & Document; + +/** @public */ +export declare interface UpdateManyModel { + /** The filter to limit the updated documents. */ + filter: Filter; + /** A document or pipeline containing update operators. */ + update: UpdateFilter | UpdateFilter[]; + /** A set of filters specifying to which array elements an update should apply. */ + arrayFilters?: Document[]; + /** Specifies a collation. */ + collation?: CollationOptions; + /** The index to use. If specified, then the query system will only consider plans using the hinted index. */ + hint?: Hint; + /** When true, creates a new document if no document matches the query. */ + upsert?: boolean; +} + +/** @public */ +export declare interface UpdateOneModel { + /** The filter to limit the updated documents. */ + filter: Filter; + /** A document or pipeline containing update operators. */ + update: UpdateFilter | UpdateFilter[]; + /** A set of filters specifying to which array elements an update should apply. */ + arrayFilters?: Document[]; + /** Specifies a collation. */ + collation?: CollationOptions; + /** The index to use. If specified, then the query system will only consider plans using the hinted index. */ + hint?: Hint; + /** When true, creates a new document if no document matches the query. */ + upsert?: boolean; +} + +/** @public */ +export declare interface UpdateOptions extends CommandOperationOptions { + /** A set of filters specifying to which array elements an update should apply */ + arrayFilters?: Document[]; + /** If true, allows the write to opt-out of document level validation */ + bypassDocumentValidation?: boolean; + /** Specifies a collation */ + collation?: CollationOptions; + /** Specify that the update query should only consider plans using the hinted index */ + hint?: string | Document; + /** When true, creates a new document if no document matches the query */ + upsert?: boolean; + /** Map of parameter names and values that can be accessed using $$var (requires MongoDB 5.0). */ + let?: Document; +} + +/** @public */ +export declare interface UpdateResult { + /** Indicates whether this write result was acknowledged. If not, then all other members of this result will be undefined */ + acknowledged: boolean; + /** The number of documents that matched the filter */ + matchedCount: number; + /** The number of documents that were modified */ + modifiedCount: number; + /** The number of documents that were upserted */ + upsertedCount: number; + /** The identifier of the inserted document if an upsert took place */ + upsertedId: ObjectId; +} + +/** @public */ +export declare interface UpdateStatement { + /** The query that matches documents to update. */ + q: Document; + /** The modifications to apply. */ + u: Document | Document[]; + /** If true, perform an insert if no documents match the query. */ + upsert?: boolean; + /** If true, updates all documents that meet the query criteria. */ + multi?: boolean; + /** Specifies the collation to use for the operation. */ + collation?: CollationOptions; + /** An array of filter documents that determines which array elements to modify for an update operation on an array field. */ + arrayFilters?: Document[]; + /** A document or string that specifies the index to use to support the query predicate. */ + hint?: Hint; +} + +/** @public */ +export declare interface ValidateCollectionOptions extends CommandOperationOptions { + /** Validates a collection in the background, without interrupting read or write traffic (only in MongoDB 4.4+) */ + background?: boolean; +} + +/** @public */ +export declare type W = number | 'majority'; + +/* Excluded from this release type: WaitQueueMember */ + +/** @public */ +export declare interface WiredTigerData extends Document { + LSM: { + 'bloom filter false positives': number; + 'bloom filter hits': number; + 'bloom filter misses': number; + 'bloom filter pages evicted from cache': number; + 'bloom filter pages read into cache': number; + 'bloom filters in the LSM tree': number; + 'chunks in the LSM tree': number; + 'highest merge generation in the LSM tree': number; + 'queries that could have benefited from a Bloom filter that did not exist': number; + 'sleep for LSM checkpoint throttle': number; + 'sleep for LSM merge throttle': number; + 'total size of bloom filters': number; + } & Document; + 'block-manager': { + 'allocations requiring file extension': number; + 'blocks allocated': number; + 'blocks freed': number; + 'checkpoint size': number; + 'file allocation unit size': number; + 'file bytes available for reuse': number; + 'file magic number': number; + 'file major version number': number; + 'file size in bytes': number; + 'minor version number': number; + }; + btree: { + 'btree checkpoint generation': number; + 'column-store fixed-size leaf pages': number; + 'column-store internal pages': number; + 'column-store variable-size RLE encoded values': number; + 'column-store variable-size deleted values': number; + 'column-store variable-size leaf pages': number; + 'fixed-record size': number; + 'maximum internal page key size': number; + 'maximum internal page size': number; + 'maximum leaf page key size': number; + 'maximum leaf page size': number; + 'maximum leaf page value size': number; + 'maximum tree depth': number; + 'number of key/value pairs': number; + 'overflow pages': number; + 'pages rewritten by compaction': number; + 'row-store internal pages': number; + 'row-store leaf pages': number; + } & Document; + cache: { + 'bytes currently in the cache': number; + 'bytes read into cache': number; + 'bytes written from cache': number; + 'checkpoint blocked page eviction': number; + 'data source pages selected for eviction unable to be evicted': number; + 'hazard pointer blocked page eviction': number; + 'in-memory page passed criteria to be split': number; + 'in-memory page splits': number; + 'internal pages evicted': number; + 'internal pages split during eviction': number; + 'leaf pages split during eviction': number; + 'modified pages evicted': number; + 'overflow pages read into cache': number; + 'overflow values cached in memory': number; + 'page split during eviction deepened the tree': number; + 'page written requiring lookaside records': number; + 'pages read into cache': number; + 'pages read into cache requiring lookaside entries': number; + 'pages requested from the cache': number; + 'pages written from cache': number; + 'pages written requiring in-memory restoration': number; + 'tracked dirty bytes in the cache': number; + 'unmodified pages evicted': number; + } & Document; + cache_walk: { + 'Average difference between current eviction generation when the page was last considered': number; + 'Average on-disk page image size seen': number; + 'Clean pages currently in cache': number; + 'Current eviction generation': number; + 'Dirty pages currently in cache': number; + 'Entries in the root page': number; + 'Internal pages currently in cache': number; + 'Leaf pages currently in cache': number; + 'Maximum difference between current eviction generation when the page was last considered': number; + 'Maximum page size seen': number; + 'Minimum on-disk page image size seen': number; + 'On-disk page image sizes smaller than a single allocation unit': number; + 'Pages created in memory and never written': number; + 'Pages currently queued for eviction': number; + 'Pages that could not be queued for eviction': number; + 'Refs skipped during cache traversal': number; + 'Size of the root page': number; + 'Total number of pages currently in cache': number; + } & Document; + compression: { + 'compressed pages read': number; + 'compressed pages written': number; + 'page written failed to compress': number; + 'page written was too small to compress': number; + 'raw compression call failed, additional data available': number; + 'raw compression call failed, no additional data available': number; + 'raw compression call succeeded': number; + } & Document; + cursor: { + 'bulk-loaded cursor-insert calls': number; + 'create calls': number; + 'cursor-insert key and value bytes inserted': number; + 'cursor-remove key bytes removed': number; + 'cursor-update value bytes updated': number; + 'insert calls': number; + 'next calls': number; + 'prev calls': number; + 'remove calls': number; + 'reset calls': number; + 'restarted searches': number; + 'search calls': number; + 'search near calls': number; + 'truncate calls': number; + 'update calls': number; + }; + reconciliation: { + 'dictionary matches': number; + 'fast-path pages deleted': number; + 'internal page key bytes discarded using suffix compression': number; + 'internal page multi-block writes': number; + 'internal-page overflow keys': number; + 'leaf page key bytes discarded using prefix compression': number; + 'leaf page multi-block writes': number; + 'leaf-page overflow keys': number; + 'maximum blocks required for a page': number; + 'overflow values written': number; + 'page checksum matches': number; + 'page reconciliation calls': number; + 'page reconciliation calls for eviction': number; + 'pages deleted': number; + } & Document; +} + +/* Excluded from this release type: WithConnectionCallback */ + +/** Add an _id field to an object shaped type @public */ +export declare type WithId = EnhancedOmit & { + _id: InferIdType; +}; + +/** Remove the _id field from an object shaped type @public */ +export declare type WithoutId = Omit; + +/** @public */ +export declare type WithSessionCallback = (session: ClientSession) => Promise; + +/** @public */ +export declare type WithTransactionCallback = (session: ClientSession) => Promise; + +/** + * A MongoDB WriteConcern, which describes the level of acknowledgement + * requested from MongoDB for write operations. + * @public + * + * @see https://docs.mongodb.com/manual/reference/write-concern/ + */ +export declare class WriteConcern { + /** request acknowledgment that the write operation has propagated to a specified number of mongod instances or to mongod instances with specified tags. */ + w?: W; + /** specify a time limit to prevent write operations from blocking indefinitely */ + wtimeout?: number; + /** request acknowledgment that the write operation has been written to the on-disk journal */ + j?: boolean; + /** equivalent to the j option */ + fsync?: boolean | 1; + /** + * Constructs a WriteConcern from the write concern properties. + * @param w - request acknowledgment that the write operation has propagated to a specified number of mongod instances or to mongod instances with specified tags. + * @param wtimeout - specify a time limit to prevent write operations from blocking indefinitely + * @param j - request acknowledgment that the write operation has been written to the on-disk journal + * @param fsync - equivalent to the j option + */ + constructor(w?: W, wtimeout?: number, j?: boolean, fsync?: boolean | 1); + /** Construct a WriteConcern given an options object. */ + static fromOptions(options?: WriteConcernOptions | WriteConcern | W, inherit?: WriteConcernOptions | WriteConcern): WriteConcern | undefined; +} + +/** + * An error representing a failure by the server to apply the requested write concern to the bulk operation. + * @public + * @category Error + */ +export declare class WriteConcernError { + /* Excluded from this release type: [kServerError] */ + constructor(error: WriteConcernErrorData); + /** Write concern error code. */ + get code(): number | undefined; + /** Write concern error message. */ + get errmsg(): string | undefined; + /** Write concern error info. */ + get errInfo(): Document | undefined; + /** @deprecated The `err` prop that contained a MongoServerError has been deprecated. */ + get err(): WriteConcernErrorData; + toJSON(): WriteConcernErrorData; + toString(): string; +} + +/** @public */ +export declare interface WriteConcernErrorData { + code: number; + errmsg: string; + errInfo?: Document; +} + +/** @public */ +export declare interface WriteConcernOptions { + /** Write Concern as an object */ + writeConcern?: WriteConcern | WriteConcernSettings; +} + +/** @public */ +export declare interface WriteConcernSettings { + /** The write concern */ + w?: W; + /** The write concern timeout */ + wtimeoutMS?: number; + /** The journal write concern */ + journal?: boolean; + /** The journal write concern */ + j?: boolean; + /** The write concern timeout */ + wtimeout?: number; + /** The file sync write concern */ + fsync?: boolean | 1; +} + +/** + * An error that occurred during a BulkWrite on the server. + * @public + * @category Error + */ +export declare class WriteError { + err: BulkWriteOperationError; + constructor(err: BulkWriteOperationError); + /** WriteError code. */ + get code(): number; + /** WriteError original bulk operation index. */ + get index(): number; + /** WriteError message. */ + get errmsg(): string | undefined; + /** WriteError details. */ + get errInfo(): Document | undefined; + /** Returns the underlying operation that caused the error */ + getOperation(): Document; + toJSON(): { + code: number; + index: number; + errmsg?: string; + op: Document; + }; + toString(): string; +} + +/* Excluded from this release type: WriteProtocolMessageType */ + +export { } diff --git a/ts-ticket-office-service/node_modules/mongodb/package.json b/ts-ticket-office-service/node_modules/mongodb/package.json index a4f8c2520..037b8ee20 100644 --- a/ts-ticket-office-service/node_modules/mongodb/package.json +++ b/ts-ticket-office-service/node_modules/mongodb/package.json @@ -1,129 +1,135 @@ { - "_args": [ - [ - { - "raw": "mongodb@*", - "scope": null, - "escapedName": "mongodb", - "name": "mongodb", - "rawSpec": "*", - "spec": "*", - "type": "range" - }, - "F:\\gitwork\\workspace_microservices\\ts-ticket-office-service\\node_modules\\mongo" - ] + "name": "mongodb", + "version": "4.8.0", + "description": "The official MongoDB driver for Node.js", + "main": "lib/index.js", + "files": [ + "lib", + "src", + "etc/prepare.js", + "mongodb.d.ts", + "tsconfig.json" ], - "_from": "mongodb@*", - "_id": "mongodb@2.2.33", - "_inCache": true, - "_location": "/mongodb", - "_nodeVersion": "6.9.5", - "_npmOperationalInternal": { - "host": "s3://npm-registry-packages", - "tmp": "tmp/mongodb-2.2.33.tgz_1507836335033_0.17075006803497672" - }, - "_npmUser": { - "name": "mbroadst", - "email": "mbroadst@gmail.com" - }, - "_npmVersion": "3.10.10", - "_phantomChildren": {}, - "_requested": { - "raw": "mongodb@*", - "scope": null, - "escapedName": "mongodb", - "name": "mongodb", - "rawSpec": "*", - "spec": "*", - "type": "range" + "types": "mongodb.d.ts", + "repository": { + "type": "git", + "url": "git@github.com:mongodb/node-mongodb-native.git" }, - "_requiredBy": [ - "/mongo" + "keywords": [ + "mongodb", + "driver", + "official" ], - "_resolved": "https://registry.npmjs.org/mongodb/-/mongodb-2.2.33.tgz", - "_shasum": "b537c471d34a6651b48f36fdbf29750340e08b50", - "_shrinkwrap": null, - "_spec": "mongodb@*", - "_where": "F:\\gitwork\\workspace_microservices\\ts-ticket-office-service\\node_modules\\mongo", "author": { - "name": "Christian Kvalheim" - }, - "bugs": { - "url": "https://github.com/mongodb/node-mongodb-native/issues" + "name": "The MongoDB NodeJS Team", + "email": "dbx-node@mongodb.com" }, "dependencies": { - "es6-promise": "3.2.1", - "mongodb-core": "2.1.17", - "readable-stream": "2.2.7" + "bson": "^4.6.5", + "denque": "^2.0.1", + "mongodb-connection-string-url": "^2.5.2", + "socks": "^2.6.2" }, - "description": "The official MongoDB driver for Node.js", "devDependencies": { - "JSONStream": "^1.0.7", - "betterbenchmarks": "^0.1.0", - "bluebird": "3.4.6", - "bson": "latest", - "cli-table": "^0.3.1", - "co": "4.6.0", - "colors": "^1.1.2", - "coveralls": "^2.11.6", - "eslint": "^3.8.1", - "event-stream": "^3.3.2", - "gleak": "0.5.0", - "integra": "0.1.8", - "jsdoc": "3.4.0", - "ldjson-stream": "^1.2.1", - "mongodb-extended-json": "1.7.1", - "mongodb-topology-manager": "1.0.x", - "mongodb-version-manager": "github:christkv/mongodb-version-manager#master", - "nyc": "^8.1.0", - "optimist": "0.6.1", - "rimraf": "2.5.4", - "semver": "5.3.0", - "worker-farm": "^1.3.1" - }, - "directories": {}, - "dist": { - "shasum": "b537c471d34a6651b48f36fdbf29750340e08b50", - "tarball": "https://registry.npmjs.org/mongodb/-/mongodb-2.2.33.tgz" + "@iarna/toml": "^2.2.5", + "@istanbuljs/nyc-config-typescript": "^1.0.2", + "@microsoft/api-extractor": "^7.25.0", + "@microsoft/tsdoc-config": "^0.16.1", + "@mongodb-js/zstd": "^1.0.0", + "@types/chai": "^4.3.1", + "@types/chai-subset": "^1.3.3", + "@types/express": "^4.17.13", + "@types/kerberos": "^1.1.1", + "@types/mocha": "^9.1.1", + "@types/node": "^17.0.42", + "@types/saslprep": "^1.0.1", + "@types/semver": "^7.3.9", + "@types/sinon": "^10.0.11", + "@types/sinon-chai": "^3.2.8", + "@types/whatwg-url": "^8.2.1", + "@typescript-eslint/eslint-plugin": "^5.28.0", + "@typescript-eslint/parser": "^5.28.0", + "bluebird": "^3.7.2", + "chai": "^4.3.6", + "chai-subset": "^1.6.0", + "chalk": "^4.1.2", + "eslint": "^8.17.0", + "eslint-config-prettier": "^8.5.0", + "eslint-plugin-import": "^2.26.0", + "eslint-plugin-prettier": "^4.0.0", + "eslint-plugin-simple-import-sort": "^7.0.0", + "eslint-plugin-tsdoc": "^0.2.16", + "express": "^4.18.1", + "js-yaml": "^4.1.0", + "mocha": "^9.2.2", + "mocha-sinon": "^2.1.2", + "nyc": "^15.1.0", + "prettier": "^2.7.0", + "rimraf": "^3.0.2", + "semver": "^7.3.7", + "sinon": "^13.0.1", + "sinon-chai": "^3.7.0", + "source-map-support": "^0.5.21", + "standard-version": "^9.5.0", + "ts-node": "^10.8.1", + "tsd": "^0.21.0", + "typescript": "^4.7.3", + "typescript-cached-transpile": "^0.0.6", + "xml2js": "^0.4.23", + "yargs": "^17.5.1" }, + "license": "Apache-2.0", "engines": { - "node": ">=0.10.3" + "node": ">=12.9.0" }, - "gitHead": "ec99d304e7bff9192eee9aa2ddbeab639bfa2639", - "homepage": "https://github.com/mongodb/node-mongodb-native", - "keywords": [ - "mongodb", - "driver", - "official" - ], - "license": "Apache-2.0", - "main": "index.js", - "maintainers": [ - { - "name": "mbroadst", - "email": "mbroadst@gmail.com" - }, - { - "name": "christkv", - "email": "christkv@gmail.com" - } - ], - "name": "mongodb", - "nyc": { - "include": [ - "lib/**/*.js" - ] + "bugs": { + "url": "https://jira.mongodb.org/projects/NODE/issues/" }, - "optionalDependencies": {}, - "readme": "ERROR: No README data found!", - "repository": { - "type": "git", - "url": "git+ssh://git@github.com/mongodb/node-mongodb-native.git" + "homepage": "https://github.com/mongodb/node-mongodb-native", + "optionalDependencies": { + "saslprep": "^1.0.3" }, "scripts": { - "coverage": "nyc node test/runner.js -t functional && node_modules/.bin/nyc report --reporter=text-lcov | node_modules/.bin/coveralls", - "lint": "eslint lib", - "test": "node test/runner.js -t functional" + "build:evergreen": "node .evergreen/generate_evergreen_tasks.js", + "build:ts": "node ./node_modules/typescript/bin/tsc", + "build:dts": "npm run build:ts && api-extractor run && rimraf 'lib/**/*.d.ts*'", + "build:docs": "./etc/docs/build.ts", + "build:typedoc": "typedoc", + "check:bench": "node test/benchmarks/driverBench", + "check:coverage": "nyc npm run test:all", + "check:integration-coverage": "nyc npm run check:test", + "check:lint": "npm run build:dts && npm run check:dts && npm run check:eslint && npm run check:tsd", + "check:eslint": "eslint -v && eslint --max-warnings=0 --ext '.js,.ts' src test", + "check:tsd": "tsd --version && tsd", + "check:dts": "node ./node_modules/typescript/bin/tsc --noEmit mongodb.d.ts && tsd", + "check:test": "mocha --config test/mocha_mongodb.json test/integration", + "check:unit": "mocha test/unit", + "check:ts": "node ./node_modules/typescript/bin/tsc -v && node ./node_modules/typescript/bin/tsc --noEmit", + "check:atlas": "mocha --config test/manual/mocharc.json test/manual/atlas_connectivity.test.js", + "check:adl": "mocha --config test/mocha_mongodb.json test/manual/atlas-data-lake-testing", + "check:aws": "mocha --config test/mocha_mongodb.json test/integration/auth/mongodb_aws.test.js", + "check:ocsp": "mocha --config test/manual/mocharc.json test/manual/ocsp_support.test.js", + "check:kerberos": "mocha --config test/manual/mocharc.json test/manual/kerberos.test.js", + "check:tls": "mocha --config test/manual/mocharc.json test/manual/tls_support.test.js", + "check:ldap": "mocha --config test/manual/mocharc.json test/manual/ldap.test.js", + "check:socks5": "mocha --config test/manual/mocharc.json test/manual/socks5.test.ts", + "check:csfle": "mocha --config test/mocha_mongodb.json test/integration/client-side-encryption", + "check:snappy": "mocha test/unit/assorted/snappy.test.js", + "fix:eslint": "npm run check:eslint -- --fix", + "prepare": "node etc/prepare.js", + "preview:docs": "ts-node etc/docs/preview.ts", + "release": "standard-version -a -i HISTORY.md", + "test": "npm run check:lint && npm run test:all", + "test:all": "npm run check:unit && npm run check:test", + "update:docs": "npm run build:docs -- --yes" }, - "version": "2.2.33" + "tsd": { + "directory": "test/types", + "compilerOptions": { + "strict": true, + "target": "esnext", + "module": "commonjs", + "moduleResolution": "node" + } + } } diff --git a/ts-ticket-office-service/node_modules/mongodb/src/admin.ts b/ts-ticket-office-service/node_modules/mongodb/src/admin.ts new file mode 100644 index 000000000..303af58a7 --- /dev/null +++ b/ts-ticket-office-service/node_modules/mongodb/src/admin.ts @@ -0,0 +1,314 @@ +import type { Document } from './bson'; +import type { Db } from './db'; +import { AddUserOperation, AddUserOptions } from './operations/add_user'; +import type { CommandOperationOptions } from './operations/command'; +import { executeOperation } from './operations/execute_operation'; +import { + ListDatabasesOperation, + ListDatabasesOptions, + ListDatabasesResult +} from './operations/list_databases'; +import { RemoveUserOperation, RemoveUserOptions } from './operations/remove_user'; +import { RunCommandOperation, RunCommandOptions } from './operations/run_command'; +import { + ValidateCollectionOperation, + ValidateCollectionOptions +} from './operations/validate_collection'; +import type { Callback } from './utils'; + +/** @internal */ +export interface AdminPrivate { + db: Db; +} + +/** + * The **Admin** class is an internal class that allows convenient access to + * the admin functionality and commands for MongoDB. + * + * **ADMIN Cannot directly be instantiated** + * @public + * + * @example + * ```js + * const MongoClient = require('mongodb').MongoClient; + * const test = require('assert'); + * // Connection url + * const url = 'mongodb://localhost:27017'; + * // Database Name + * const dbName = 'test'; + * + * // Connect using MongoClient + * MongoClient.connect(url, function(err, client) { + * // Use the admin database for the operation + * const adminDb = client.db(dbName).admin(); + * + * // List all the available databases + * adminDb.listDatabases(function(err, dbs) { + * expect(err).to.not.exist; + * test.ok(dbs.databases.length > 0); + * client.close(); + * }); + * }); + * ``` + */ +export class Admin { + /** @internal */ + s: AdminPrivate; + + /** + * Create a new Admin instance + * @internal + */ + constructor(db: Db) { + this.s = { db }; + } + + /** + * Execute a command + * + * @param command - The command to execute + * @param options - Optional settings for the command + * @param callback - An optional callback, a Promise will be returned if none is provided + */ + command(command: Document): Promise; + command(command: Document, callback: Callback): void; + command(command: Document, options: RunCommandOptions): Promise; + command(command: Document, options: RunCommandOptions, callback: Callback): void; + command( + command: Document, + options?: RunCommandOptions | Callback, + callback?: Callback + ): Promise | void { + if (typeof options === 'function') (callback = options), (options = {}); + options = Object.assign({ dbName: 'admin' }, options); + + return executeOperation( + this.s.db.s.client, + new RunCommandOperation(this.s.db, command, options), + callback + ); + } + + /** + * Retrieve the server build information + * + * @param options - Optional settings for the command + * @param callback - An optional callback, a Promise will be returned if none is provided + */ + buildInfo(): Promise; + buildInfo(callback: Callback): void; + buildInfo(options: CommandOperationOptions): Promise; + buildInfo(options: CommandOperationOptions, callback: Callback): void; + buildInfo( + options?: CommandOperationOptions | Callback, + callback?: Callback + ): Promise | void { + if (typeof options === 'function') (callback = options), (options = {}); + options = options ?? {}; + return this.command({ buildinfo: 1 }, options, callback as Callback); + } + + /** + * Retrieve the server build information + * + * @param options - Optional settings for the command + * @param callback - An optional callback, a Promise will be returned if none is provided + */ + serverInfo(): Promise; + serverInfo(callback: Callback): void; + serverInfo(options: CommandOperationOptions): Promise; + serverInfo(options: CommandOperationOptions, callback: Callback): void; + serverInfo( + options?: CommandOperationOptions | Callback, + callback?: Callback + ): Promise | void { + if (typeof options === 'function') (callback = options), (options = {}); + options = options ?? {}; + return this.command({ buildinfo: 1 }, options, callback as Callback); + } + + /** + * Retrieve this db's server status. + * + * @param options - Optional settings for the command + * @param callback - An optional callback, a Promise will be returned if none is provided + */ + serverStatus(): Promise; + serverStatus(callback: Callback): void; + serverStatus(options: CommandOperationOptions): Promise; + serverStatus(options: CommandOperationOptions, callback: Callback): void; + serverStatus( + options?: CommandOperationOptions | Callback, + callback?: Callback + ): Promise | void { + if (typeof options === 'function') (callback = options), (options = {}); + options = options ?? {}; + return this.command({ serverStatus: 1 }, options, callback as Callback); + } + + /** + * Ping the MongoDB server and retrieve results + * + * @param options - Optional settings for the command + * @param callback - An optional callback, a Promise will be returned if none is provided + */ + ping(): Promise; + ping(callback: Callback): void; + ping(options: CommandOperationOptions): Promise; + ping(options: CommandOperationOptions, callback: Callback): void; + ping( + options?: CommandOperationOptions | Callback, + callback?: Callback + ): Promise | void { + if (typeof options === 'function') (callback = options), (options = {}); + options = options ?? {}; + return this.command({ ping: 1 }, options, callback as Callback); + } + + /** + * Add a user to the database + * + * @param username - The username for the new user + * @param password - An optional password for the new user + * @param options - Optional settings for the command + * @param callback - An optional callback, a Promise will be returned if none is provided + */ + addUser(username: string): Promise; + addUser(username: string, callback: Callback): void; + addUser(username: string, password: string): Promise; + addUser(username: string, password: string, callback: Callback): void; + addUser(username: string, options: AddUserOptions): Promise; + addUser(username: string, options: AddUserOptions, callback: Callback): void; + addUser(username: string, password: string, options: AddUserOptions): Promise; + addUser( + username: string, + password: string, + options: AddUserOptions, + callback: Callback + ): void; + addUser( + username: string, + password?: string | AddUserOptions | Callback, + options?: AddUserOptions | Callback, + callback?: Callback + ): Promise | void { + if (typeof password === 'function') { + (callback = password), (password = undefined), (options = {}); + } else if (typeof password !== 'string') { + if (typeof options === 'function') { + (callback = options), (options = password), (password = undefined); + } else { + (options = password), (callback = undefined), (password = undefined); + } + } else { + if (typeof options === 'function') (callback = options), (options = {}); + } + + options = Object.assign({ dbName: 'admin' }, options); + + return executeOperation( + this.s.db.s.client, + new AddUserOperation(this.s.db, username, password, options), + callback + ); + } + + /** + * Remove a user from a database + * + * @param username - The username to remove + * @param options - Optional settings for the command + * @param callback - An optional callback, a Promise will be returned if none is provided + */ + removeUser(username: string): Promise; + removeUser(username: string, callback: Callback): void; + removeUser(username: string, options: RemoveUserOptions): Promise; + removeUser(username: string, options: RemoveUserOptions, callback: Callback): void; + removeUser( + username: string, + options?: RemoveUserOptions | Callback, + callback?: Callback + ): Promise | void { + if (typeof options === 'function') (callback = options), (options = {}); + options = Object.assign({ dbName: 'admin' }, options); + + return executeOperation( + this.s.db.s.client, + new RemoveUserOperation(this.s.db, username, options), + callback + ); + } + + /** + * Validate an existing collection + * + * @param collectionName - The name of the collection to validate. + * @param options - Optional settings for the command + * @param callback - An optional callback, a Promise will be returned if none is provided + */ + validateCollection(collectionName: string): Promise; + validateCollection(collectionName: string, callback: Callback): void; + validateCollection(collectionName: string, options: ValidateCollectionOptions): Promise; + validateCollection( + collectionName: string, + options: ValidateCollectionOptions, + callback: Callback + ): void; + validateCollection( + collectionName: string, + options?: ValidateCollectionOptions | Callback, + callback?: Callback + ): Promise | void { + if (typeof options === 'function') (callback = options), (options = {}); + options = options ?? {}; + + return executeOperation( + this.s.db.s.client, + new ValidateCollectionOperation(this, collectionName, options), + callback + ); + } + + /** + * List the available databases + * + * @param options - Optional settings for the command + * @param callback - An optional callback, a Promise will be returned if none is provided + */ + listDatabases(): Promise; + listDatabases(callback: Callback): void; + listDatabases(options: ListDatabasesOptions): Promise; + listDatabases(options: ListDatabasesOptions, callback: Callback): void; + listDatabases( + options?: ListDatabasesOptions | Callback, + callback?: Callback + ): Promise | void { + if (typeof options === 'function') (callback = options), (options = {}); + options = options ?? {}; + + return executeOperation( + this.s.db.s.client, + new ListDatabasesOperation(this.s.db, options), + callback + ); + } + + /** + * Get ReplicaSet status + * + * @param options - Optional settings for the command + * @param callback - An optional callback, a Promise will be returned if none is provided + */ + replSetGetStatus(): Promise; + replSetGetStatus(callback: Callback): void; + replSetGetStatus(options: CommandOperationOptions): Promise; + replSetGetStatus(options: CommandOperationOptions, callback: Callback): void; + replSetGetStatus( + options?: CommandOperationOptions | Callback, + callback?: Callback + ): Promise | void { + if (typeof options === 'function') (callback = options), (options = {}); + options = options ?? {}; + return this.command({ replSetGetStatus: 1 }, options, callback as Callback); + } +} diff --git a/ts-ticket-office-service/node_modules/mongodb/src/bson.ts b/ts-ticket-office-service/node_modules/mongodb/src/bson.ts new file mode 100644 index 000000000..42d9ab08d --- /dev/null +++ b/ts-ticket-office-service/node_modules/mongodb/src/bson.ts @@ -0,0 +1,112 @@ +import type { + calculateObjectSize as calculateObjectSizeFn, + deserialize as deserializeFn, + DeserializeOptions, + serialize as serializeFn, + SerializeOptions +} from 'bson'; + +// eslint-disable-next-line @typescript-eslint/no-var-requires +let BSON = require('bson'); + +try { + // Ensure you always wrap an optional require in the try block NODE-3199 + BSON = require('bson-ext'); +} catch {} // eslint-disable-line + +/** @internal */ +export const deserialize = BSON.deserialize as typeof deserializeFn; +/** @internal */ +export const serialize = BSON.serialize as typeof serializeFn; +/** @internal */ +export const calculateObjectSize = BSON.calculateObjectSize as typeof calculateObjectSizeFn; + +export { + Binary, + BSONRegExp, + BSONSymbol, + Code, + DBRef, + Decimal128, + Document, + Double, + Int32, + Long, + Map, + MaxKey, + MinKey, + ObjectId, + Timestamp +} from 'bson'; + +/** + * BSON Serialization options. + * @public + */ +export interface BSONSerializeOptions + extends Omit, + Omit< + DeserializeOptions, + | 'evalFunctions' + | 'cacheFunctions' + | 'cacheFunctionsCrc32' + | 'allowObjectSmallerThanBufferSize' + | 'index' + | 'validation' + > { + /** Return BSON filled buffers from operations */ + raw?: boolean; + + /** Enable utf8 validation when deserializing BSON documents. Defaults to true. */ + enableUtf8Validation?: boolean; +} + +export function pluckBSONSerializeOptions(options: BSONSerializeOptions): BSONSerializeOptions { + const { + fieldsAsRaw, + promoteValues, + promoteBuffers, + promoteLongs, + serializeFunctions, + ignoreUndefined, + bsonRegExp, + raw, + enableUtf8Validation + } = options; + return { + fieldsAsRaw, + promoteValues, + promoteBuffers, + promoteLongs, + serializeFunctions, + ignoreUndefined, + bsonRegExp, + raw, + enableUtf8Validation + }; +} + +/** + * Merge the given BSONSerializeOptions, preferring options over the parent's options, and + * substituting defaults for values not set. + * + * @internal + */ +export function resolveBSONOptions( + options?: BSONSerializeOptions, + parent?: { bsonOptions?: BSONSerializeOptions } +): BSONSerializeOptions { + const parentOptions = parent?.bsonOptions; + return { + raw: options?.raw ?? parentOptions?.raw ?? false, + promoteLongs: options?.promoteLongs ?? parentOptions?.promoteLongs ?? true, + promoteValues: options?.promoteValues ?? parentOptions?.promoteValues ?? true, + promoteBuffers: options?.promoteBuffers ?? parentOptions?.promoteBuffers ?? false, + ignoreUndefined: options?.ignoreUndefined ?? parentOptions?.ignoreUndefined ?? false, + bsonRegExp: options?.bsonRegExp ?? parentOptions?.bsonRegExp ?? false, + serializeFunctions: options?.serializeFunctions ?? parentOptions?.serializeFunctions ?? false, + fieldsAsRaw: options?.fieldsAsRaw ?? parentOptions?.fieldsAsRaw ?? {}, + enableUtf8Validation: + options?.enableUtf8Validation ?? parentOptions?.enableUtf8Validation ?? true + }; +} diff --git a/ts-ticket-office-service/node_modules/mongodb/src/bulk/common.ts b/ts-ticket-office-service/node_modules/mongodb/src/bulk/common.ts new file mode 100644 index 000000000..41b69da65 --- /dev/null +++ b/ts-ticket-office-service/node_modules/mongodb/src/bulk/common.ts @@ -0,0 +1,1383 @@ +import { + BSONSerializeOptions, + Document, + Long, + ObjectId, + resolveBSONOptions, + Timestamp +} from '../bson'; +import type { Collection } from '../collection'; +import { + AnyError, + MongoBatchReExecutionError, + MONGODB_ERROR_CODES, + MongoInvalidArgumentError, + MongoServerError, + MongoWriteConcernError +} from '../error'; +import type { Filter, OneOrMore, OptionalId, UpdateFilter, WithoutId } from '../mongo_types'; +import type { CollationOptions, CommandOperationOptions } from '../operations/command'; +import { DeleteOperation, DeleteStatement, makeDeleteStatement } from '../operations/delete'; +import { executeOperation } from '../operations/execute_operation'; +import { InsertOperation } from '../operations/insert'; +import { AbstractOperation, Hint } from '../operations/operation'; +import { makeUpdateStatement, UpdateOperation, UpdateStatement } from '../operations/update'; +import { PromiseProvider } from '../promise_provider'; +import type { Server } from '../sdam/server'; +import type { Topology } from '../sdam/topology'; +import type { ClientSession } from '../sessions'; +import { + applyRetryableWrites, + Callback, + getTopology, + hasAtomicOperators, + MongoDBNamespace, + resolveOptions +} from '../utils'; +import { WriteConcern } from '../write_concern'; + +/** @internal */ +const kServerError = Symbol('serverError'); + +/** @public */ +export const BatchType = Object.freeze({ + INSERT: 1, + UPDATE: 2, + DELETE: 3 +} as const); + +/** @public */ +export type BatchType = typeof BatchType[keyof typeof BatchType]; + +/** @public */ +export interface InsertOneModel { + /** The document to insert. */ + document: OptionalId; +} + +/** @public */ +export interface DeleteOneModel { + /** The filter to limit the deleted documents. */ + filter: Filter; + /** Specifies a collation. */ + collation?: CollationOptions; + /** The index to use. If specified, then the query system will only consider plans using the hinted index. */ + hint?: Hint; +} + +/** @public */ +export interface DeleteManyModel { + /** The filter to limit the deleted documents. */ + filter: Filter; + /** Specifies a collation. */ + collation?: CollationOptions; + /** The index to use. If specified, then the query system will only consider plans using the hinted index. */ + hint?: Hint; +} + +/** @public */ +export interface ReplaceOneModel { + /** The filter to limit the replaced document. */ + filter: Filter; + /** The document with which to replace the matched document. */ + replacement: WithoutId; + /** Specifies a collation. */ + collation?: CollationOptions; + /** The index to use. If specified, then the query system will only consider plans using the hinted index. */ + hint?: Hint; + /** When true, creates a new document if no document matches the query. */ + upsert?: boolean; +} + +/** @public */ +export interface UpdateOneModel { + /** The filter to limit the updated documents. */ + filter: Filter; + /** A document or pipeline containing update operators. */ + update: UpdateFilter | UpdateFilter[]; + /** A set of filters specifying to which array elements an update should apply. */ + arrayFilters?: Document[]; + /** Specifies a collation. */ + collation?: CollationOptions; + /** The index to use. If specified, then the query system will only consider plans using the hinted index. */ + hint?: Hint; + /** When true, creates a new document if no document matches the query. */ + upsert?: boolean; +} + +/** @public */ +export interface UpdateManyModel { + /** The filter to limit the updated documents. */ + filter: Filter; + /** A document or pipeline containing update operators. */ + update: UpdateFilter | UpdateFilter[]; + /** A set of filters specifying to which array elements an update should apply. */ + arrayFilters?: Document[]; + /** Specifies a collation. */ + collation?: CollationOptions; + /** The index to use. If specified, then the query system will only consider plans using the hinted index. */ + hint?: Hint; + /** When true, creates a new document if no document matches the query. */ + upsert?: boolean; +} + +/** @public */ +export type AnyBulkWriteOperation = + | { insertOne: InsertOneModel } + | { replaceOne: ReplaceOneModel } + | { updateOne: UpdateOneModel } + | { updateMany: UpdateManyModel } + | { deleteOne: DeleteOneModel } + | { deleteMany: DeleteManyModel }; + +/** @public */ +export interface BulkResult { + ok: number; + writeErrors: WriteError[]; + writeConcernErrors: WriteConcernError[]; + insertedIds: Document[]; + nInserted: number; + nUpserted: number; + nMatched: number; + nModified: number; + nRemoved: number; + upserted: Document[]; + opTime?: Document; +} + +/** + * Keeps the state of a unordered batch so we can rewrite the results + * correctly after command execution + * + * @public + */ +export class Batch { + originalZeroIndex: number; + currentIndex: number; + originalIndexes: number[]; + batchType: BatchType; + operations: T[]; + size: number; + sizeBytes: number; + + constructor(batchType: BatchType, originalZeroIndex: number) { + this.originalZeroIndex = originalZeroIndex; + this.currentIndex = 0; + this.originalIndexes = []; + this.batchType = batchType; + this.operations = []; + this.size = 0; + this.sizeBytes = 0; + } +} + +/** + * @public + * The result of a bulk write. + */ +export class BulkWriteResult { + result: BulkResult; + + /** + * Create a new BulkWriteResult instance + * @internal + */ + constructor(bulkResult: BulkResult) { + this.result = bulkResult; + } + + /** Number of documents inserted. */ + get insertedCount(): number { + return this.result.nInserted ?? 0; + } + /** Number of documents matched for update. */ + get matchedCount(): number { + return this.result.nMatched ?? 0; + } + /** Number of documents modified. */ + get modifiedCount(): number { + return this.result.nModified ?? 0; + } + /** Number of documents deleted. */ + get deletedCount(): number { + return this.result.nRemoved ?? 0; + } + /** Number of documents upserted. */ + get upsertedCount(): number { + return this.result.upserted.length ?? 0; + } + + /** Upserted document generated Id's, hash key is the index of the originating operation */ + get upsertedIds(): { [key: number]: any } { + const upserted: { [index: number]: any } = {}; + for (const doc of this.result.upserted ?? []) { + upserted[doc.index] = doc._id; + } + return upserted; + } + + /** Inserted document generated Id's, hash key is the index of the originating operation */ + get insertedIds(): { [key: number]: any } { + const inserted: { [index: number]: any } = {}; + for (const doc of this.result.insertedIds ?? []) { + inserted[doc.index] = doc._id; + } + return inserted; + } + + /** Evaluates to true if the bulk operation correctly executes */ + get ok(): number { + return this.result.ok; + } + + /** The number of inserted documents */ + get nInserted(): number { + return this.result.nInserted; + } + + /** Number of upserted documents */ + get nUpserted(): number { + return this.result.nUpserted; + } + + /** Number of matched documents */ + get nMatched(): number { + return this.result.nMatched; + } + + /** Number of documents updated physically on disk */ + get nModified(): number { + return this.result.nModified; + } + + /** Number of removed documents */ + get nRemoved(): number { + return this.result.nRemoved; + } + + /** Returns an array of all inserted ids */ + getInsertedIds(): Document[] { + return this.result.insertedIds; + } + + /** Returns an array of all upserted ids */ + getUpsertedIds(): Document[] { + return this.result.upserted; + } + + /** Returns the upserted id at the given index */ + getUpsertedIdAt(index: number): Document | undefined { + return this.result.upserted[index]; + } + + /** Returns raw internal result */ + getRawResponse(): Document { + return this.result; + } + + /** Returns true if the bulk operation contains a write error */ + hasWriteErrors(): boolean { + return this.result.writeErrors.length > 0; + } + + /** Returns the number of write errors off the bulk operation */ + getWriteErrorCount(): number { + return this.result.writeErrors.length; + } + + /** Returns a specific write error object */ + getWriteErrorAt(index: number): WriteError | undefined { + return index < this.result.writeErrors.length ? this.result.writeErrors[index] : undefined; + } + + /** Retrieve all write errors */ + getWriteErrors(): WriteError[] { + return this.result.writeErrors; + } + + /** Retrieve lastOp if available */ + getLastOp(): Document | undefined { + return this.result.opTime; + } + + /** Retrieve the write concern error if one exists */ + getWriteConcernError(): WriteConcernError | undefined { + if (this.result.writeConcernErrors.length === 0) { + return; + } else if (this.result.writeConcernErrors.length === 1) { + // Return the error + return this.result.writeConcernErrors[0]; + } else { + // Combine the errors + let errmsg = ''; + for (let i = 0; i < this.result.writeConcernErrors.length; i++) { + const err = this.result.writeConcernErrors[i]; + errmsg = errmsg + err.errmsg; + + // TODO: Something better + if (i === 0) errmsg = errmsg + ' and '; + } + + return new WriteConcernError({ errmsg, code: MONGODB_ERROR_CODES.WriteConcernFailed }); + } + } + + toJSON(): BulkResult { + return this.result; + } + + toString(): string { + return `BulkWriteResult(${this.toJSON()})`; + } + + isOk(): boolean { + return this.result.ok === 1; + } +} + +/** @public */ +export interface WriteConcernErrorData { + code: number; + errmsg: string; + errInfo?: Document; +} + +/** + * An error representing a failure by the server to apply the requested write concern to the bulk operation. + * @public + * @category Error + */ +export class WriteConcernError { + /** @internal */ + [kServerError]: WriteConcernErrorData; + + constructor(error: WriteConcernErrorData) { + this[kServerError] = error; + } + + /** Write concern error code. */ + get code(): number | undefined { + return this[kServerError].code; + } + + /** Write concern error message. */ + get errmsg(): string | undefined { + return this[kServerError].errmsg; + } + + /** Write concern error info. */ + get errInfo(): Document | undefined { + return this[kServerError].errInfo; + } + + /** @deprecated The `err` prop that contained a MongoServerError has been deprecated. */ + get err(): WriteConcernErrorData { + return this[kServerError]; + } + + toJSON(): WriteConcernErrorData { + return this[kServerError]; + } + + toString(): string { + return `WriteConcernError(${this.errmsg})`; + } +} + +/** @public */ +export interface BulkWriteOperationError { + index: number; + code: number; + errmsg: string; + errInfo: Document; + op: Document | UpdateStatement | DeleteStatement; +} + +/** + * An error that occurred during a BulkWrite on the server. + * @public + * @category Error + */ +export class WriteError { + err: BulkWriteOperationError; + + constructor(err: BulkWriteOperationError) { + this.err = err; + } + + /** WriteError code. */ + get code(): number { + return this.err.code; + } + + /** WriteError original bulk operation index. */ + get index(): number { + return this.err.index; + } + + /** WriteError message. */ + get errmsg(): string | undefined { + return this.err.errmsg; + } + + /** WriteError details. */ + get errInfo(): Document | undefined { + return this.err.errInfo; + } + + /** Returns the underlying operation that caused the error */ + getOperation(): Document { + return this.err.op; + } + + toJSON(): { code: number; index: number; errmsg?: string; op: Document } { + return { code: this.err.code, index: this.err.index, errmsg: this.err.errmsg, op: this.err.op }; + } + + toString(): string { + return `WriteError(${JSON.stringify(this.toJSON())})`; + } +} + +/** Converts the number to a Long or returns it. */ +function longOrConvert(value: number | Long | Timestamp): Long | Timestamp { + return typeof value === 'number' ? Long.fromNumber(value) : value; +} + +/** Merges results into shared data structure */ +export function mergeBatchResults( + batch: Batch, + bulkResult: BulkResult, + err?: AnyError, + result?: Document +): void { + // If we have an error set the result to be the err object + if (err) { + result = err; + } else if (result && result.result) { + result = result.result; + } + + if (result == null) { + return; + } + + // Do we have a top level error stop processing and return + if (result.ok === 0 && bulkResult.ok === 1) { + bulkResult.ok = 0; + + const writeError = { + index: 0, + code: result.code || 0, + errmsg: result.message, + errInfo: result.errInfo, + op: batch.operations[0] + }; + + bulkResult.writeErrors.push(new WriteError(writeError)); + return; + } else if (result.ok === 0 && bulkResult.ok === 0) { + return; + } + + // The server write command specification states that lastOp is an optional + // mongod only field that has a type of timestamp. Across various scarce specs + // where opTime is mentioned, it is an "opaque" object that can have a "ts" and + // "t" field with Timestamp and Long as their types respectively. + // The "lastOp" field of the bulk write result is never mentioned in the driver + // specifications or the bulk write spec, so we should probably just keep its + // value consistent since it seems to vary. + // See: https://github.com/mongodb/specifications/blob/master/source/driver-bulk-update.rst#results-object + if (result.opTime || result.lastOp) { + let opTime = result.lastOp || result.opTime; + + // If the opTime is a Timestamp, convert it to a consistent format to be + // able to compare easily. Converting to the object from a timestamp is + // much more straightforward than the other direction. + if (opTime._bsontype === 'Timestamp') { + opTime = { ts: opTime, t: Long.ZERO }; + } + + // If there's no lastOp, just set it. + if (!bulkResult.opTime) { + bulkResult.opTime = opTime; + } else { + // First compare the ts values and set if the opTimeTS value is greater. + const lastOpTS = longOrConvert(bulkResult.opTime.ts); + const opTimeTS = longOrConvert(opTime.ts); + if (opTimeTS.greaterThan(lastOpTS)) { + bulkResult.opTime = opTime; + } else if (opTimeTS.equals(lastOpTS)) { + // If the ts values are equal, then compare using the t values. + const lastOpT = longOrConvert(bulkResult.opTime.t); + const opTimeT = longOrConvert(opTime.t); + if (opTimeT.greaterThan(lastOpT)) { + bulkResult.opTime = opTime; + } + } + } + } + + // If we have an insert Batch type + if (isInsertBatch(batch) && result.n) { + bulkResult.nInserted = bulkResult.nInserted + result.n; + } + + // If we have an insert Batch type + if (isDeleteBatch(batch) && result.n) { + bulkResult.nRemoved = bulkResult.nRemoved + result.n; + } + + let nUpserted = 0; + + // We have an array of upserted values, we need to rewrite the indexes + if (Array.isArray(result.upserted)) { + nUpserted = result.upserted.length; + + for (let i = 0; i < result.upserted.length; i++) { + bulkResult.upserted.push({ + index: result.upserted[i].index + batch.originalZeroIndex, + _id: result.upserted[i]._id + }); + } + } else if (result.upserted) { + nUpserted = 1; + + bulkResult.upserted.push({ + index: batch.originalZeroIndex, + _id: result.upserted + }); + } + + // If we have an update Batch type + if (isUpdateBatch(batch) && result.n) { + const nModified = result.nModified; + bulkResult.nUpserted = bulkResult.nUpserted + nUpserted; + bulkResult.nMatched = bulkResult.nMatched + (result.n - nUpserted); + + if (typeof nModified === 'number') { + bulkResult.nModified = bulkResult.nModified + nModified; + } else { + bulkResult.nModified = 0; + } + } + + if (Array.isArray(result.writeErrors)) { + for (let i = 0; i < result.writeErrors.length; i++) { + const writeError = { + index: batch.originalIndexes[result.writeErrors[i].index], + code: result.writeErrors[i].code, + errmsg: result.writeErrors[i].errmsg, + errInfo: result.writeErrors[i].errInfo, + op: batch.operations[result.writeErrors[i].index] + }; + + bulkResult.writeErrors.push(new WriteError(writeError)); + } + } + + if (result.writeConcernError) { + bulkResult.writeConcernErrors.push(new WriteConcernError(result.writeConcernError)); + } +} + +function executeCommands( + bulkOperation: BulkOperationBase, + options: BulkWriteOptions, + callback: Callback +) { + if (bulkOperation.s.batches.length === 0) { + return callback(undefined, new BulkWriteResult(bulkOperation.s.bulkResult)); + } + + const batch = bulkOperation.s.batches.shift() as Batch; + + function resultHandler(err?: AnyError, result?: Document) { + // Error is a driver related error not a bulk op error, return early + if (err && 'message' in err && !(err instanceof MongoWriteConcernError)) { + return callback( + new MongoBulkWriteError(err, new BulkWriteResult(bulkOperation.s.bulkResult)) + ); + } + + if (err instanceof MongoWriteConcernError) { + return handleMongoWriteConcernError(batch, bulkOperation.s.bulkResult, err, callback); + } + + // Merge the results together + const writeResult = new BulkWriteResult(bulkOperation.s.bulkResult); + const mergeResult = mergeBatchResults(batch, bulkOperation.s.bulkResult, err, result); + if (mergeResult != null) { + return callback(undefined, writeResult); + } + + if (bulkOperation.handleWriteError(callback, writeResult)) return; + + // Execute the next command in line + executeCommands(bulkOperation, options, callback); + } + + const finalOptions = resolveOptions(bulkOperation, { + ...options, + ordered: bulkOperation.isOrdered + }); + + if (finalOptions.bypassDocumentValidation !== true) { + delete finalOptions.bypassDocumentValidation; + } + + // Set an operationIf if provided + if (bulkOperation.operationId) { + resultHandler.operationId = bulkOperation.operationId; + } + + // Is the bypassDocumentValidation options specific + if (bulkOperation.s.bypassDocumentValidation === true) { + finalOptions.bypassDocumentValidation = true; + } + + // Is the checkKeys option disabled + if (bulkOperation.s.checkKeys === false) { + finalOptions.checkKeys = false; + } + + if (finalOptions.retryWrites) { + if (isUpdateBatch(batch)) { + finalOptions.retryWrites = finalOptions.retryWrites && !batch.operations.some(op => op.multi); + } + + if (isDeleteBatch(batch)) { + finalOptions.retryWrites = + finalOptions.retryWrites && !batch.operations.some(op => op.limit === 0); + } + } + + try { + if (isInsertBatch(batch)) { + executeOperation( + bulkOperation.s.collection.s.db.s.client, + new InsertOperation(bulkOperation.s.namespace, batch.operations, finalOptions), + resultHandler + ); + } else if (isUpdateBatch(batch)) { + executeOperation( + bulkOperation.s.collection.s.db.s.client, + new UpdateOperation(bulkOperation.s.namespace, batch.operations, finalOptions), + resultHandler + ); + } else if (isDeleteBatch(batch)) { + executeOperation( + bulkOperation.s.collection.s.db.s.client, + new DeleteOperation(bulkOperation.s.namespace, batch.operations, finalOptions), + resultHandler + ); + } + } catch (err) { + // Force top level error + err.ok = 0; + // Merge top level error and return + mergeBatchResults(batch, bulkOperation.s.bulkResult, err, undefined); + callback(); + } +} + +function handleMongoWriteConcernError( + batch: Batch, + bulkResult: BulkResult, + err: MongoWriteConcernError, + callback: Callback +) { + mergeBatchResults(batch, bulkResult, undefined, err.result); + + callback( + new MongoBulkWriteError( + { + message: err.result?.writeConcernError.errmsg, + code: err.result?.writeConcernError.result + }, + new BulkWriteResult(bulkResult) + ) + ); +} + +/** + * An error indicating an unsuccessful Bulk Write + * @public + * @category Error + */ +export class MongoBulkWriteError extends MongoServerError { + result: BulkWriteResult; + writeErrors: OneOrMore = []; + err?: WriteConcernError; + + /** Creates a new MongoBulkWriteError */ + constructor( + error: + | { message: string; code: number; writeErrors?: WriteError[] } + | WriteConcernError + | AnyError, + result: BulkWriteResult + ) { + super(error); + + if (error instanceof WriteConcernError) this.err = error; + else if (!(error instanceof Error)) { + this.message = error.message; + this.code = error.code; + this.writeErrors = error.writeErrors ?? []; + } + + this.result = result; + Object.assign(this, error); + } + + override get name(): string { + return 'MongoBulkWriteError'; + } + + /** Number of documents inserted. */ + get insertedCount(): number { + return this.result.insertedCount; + } + /** Number of documents matched for update. */ + get matchedCount(): number { + return this.result.matchedCount; + } + /** Number of documents modified. */ + get modifiedCount(): number { + return this.result.modifiedCount; + } + /** Number of documents deleted. */ + get deletedCount(): number { + return this.result.deletedCount; + } + /** Number of documents upserted. */ + get upsertedCount(): number { + return this.result.upsertedCount; + } + /** Inserted document generated Id's, hash key is the index of the originating operation */ + get insertedIds(): { [key: number]: any } { + return this.result.insertedIds; + } + /** Upserted document generated Id's, hash key is the index of the originating operation */ + get upsertedIds(): { [key: number]: any } { + return this.result.upsertedIds; + } +} + +/** + * A builder object that is returned from {@link BulkOperationBase#find}. + * Is used to build a write operation that involves a query filter. + * + * @public + */ +export class FindOperators { + bulkOperation: BulkOperationBase; + + /** + * Creates a new FindOperators object. + * @internal + */ + constructor(bulkOperation: BulkOperationBase) { + this.bulkOperation = bulkOperation; + } + + /** Add a multiple update operation to the bulk operation */ + update(updateDocument: Document): BulkOperationBase { + const currentOp = buildCurrentOp(this.bulkOperation); + return this.bulkOperation.addToOperationsList( + BatchType.UPDATE, + makeUpdateStatement(currentOp.selector, updateDocument, { + ...currentOp, + multi: true + }) + ); + } + + /** Add a single update operation to the bulk operation */ + updateOne(updateDocument: Document): BulkOperationBase { + if (!hasAtomicOperators(updateDocument)) { + throw new MongoInvalidArgumentError('Update document requires atomic operators'); + } + + const currentOp = buildCurrentOp(this.bulkOperation); + return this.bulkOperation.addToOperationsList( + BatchType.UPDATE, + makeUpdateStatement(currentOp.selector, updateDocument, { ...currentOp, multi: false }) + ); + } + + /** Add a replace one operation to the bulk operation */ + replaceOne(replacement: Document): BulkOperationBase { + if (hasAtomicOperators(replacement)) { + throw new MongoInvalidArgumentError('Replacement document must not use atomic operators'); + } + + const currentOp = buildCurrentOp(this.bulkOperation); + return this.bulkOperation.addToOperationsList( + BatchType.UPDATE, + makeUpdateStatement(currentOp.selector, replacement, { ...currentOp, multi: false }) + ); + } + + /** Add a delete one operation to the bulk operation */ + deleteOne(): BulkOperationBase { + const currentOp = buildCurrentOp(this.bulkOperation); + return this.bulkOperation.addToOperationsList( + BatchType.DELETE, + makeDeleteStatement(currentOp.selector, { ...currentOp, limit: 1 }) + ); + } + + /** Add a delete many operation to the bulk operation */ + delete(): BulkOperationBase { + const currentOp = buildCurrentOp(this.bulkOperation); + return this.bulkOperation.addToOperationsList( + BatchType.DELETE, + makeDeleteStatement(currentOp.selector, { ...currentOp, limit: 0 }) + ); + } + + /** Upsert modifier for update bulk operation, noting that this operation is an upsert. */ + upsert(): this { + if (!this.bulkOperation.s.currentOp) { + this.bulkOperation.s.currentOp = {}; + } + + this.bulkOperation.s.currentOp.upsert = true; + return this; + } + + /** Specifies the collation for the query condition. */ + collation(collation: CollationOptions): this { + if (!this.bulkOperation.s.currentOp) { + this.bulkOperation.s.currentOp = {}; + } + + this.bulkOperation.s.currentOp.collation = collation; + return this; + } + + /** Specifies arrayFilters for UpdateOne or UpdateMany bulk operations. */ + arrayFilters(arrayFilters: Document[]): this { + if (!this.bulkOperation.s.currentOp) { + this.bulkOperation.s.currentOp = {}; + } + + this.bulkOperation.s.currentOp.arrayFilters = arrayFilters; + return this; + } +} + +/** @internal */ +export interface BulkOperationPrivate { + bulkResult: BulkResult; + currentBatch?: Batch; + currentIndex: number; + // ordered specific + currentBatchSize: number; + currentBatchSizeBytes: number; + // unordered specific + currentInsertBatch?: Batch; + currentUpdateBatch?: Batch; + currentRemoveBatch?: Batch; + batches: Batch[]; + // Write concern + writeConcern?: WriteConcern; + // Max batch size options + maxBsonObjectSize: number; + maxBatchSizeBytes: number; + maxWriteBatchSize: number; + maxKeySize: number; + // Namespace + namespace: MongoDBNamespace; + // Topology + topology: Topology; + // Options + options: BulkWriteOptions; + // BSON options + bsonOptions: BSONSerializeOptions; + // Document used to build a bulk operation + currentOp?: Document; + // Executed + executed: boolean; + // Collection + collection: Collection; + // Fundamental error + err?: AnyError; + // check keys + checkKeys: boolean; + bypassDocumentValidation?: boolean; +} + +/** @public */ +export interface BulkWriteOptions extends CommandOperationOptions { + /** Allow driver to bypass schema validation in MongoDB 3.2 or higher. */ + bypassDocumentValidation?: boolean; + /** If true, when an insert fails, don't execute the remaining writes. If false, continue with remaining inserts when one fails. */ + ordered?: boolean; + /** @deprecated use `ordered` instead */ + keepGoing?: boolean; + /** Force server to assign _id values instead of driver. */ + forceServerObjectId?: boolean; + /** Map of parameter names and values that can be accessed using $$var (requires MongoDB 5.0). */ + let?: Document; +} + +/** + * TODO(NODE-4063) + * BulkWrites merge complexity is implemented in executeCommands + * This provides a vehicle to treat bulkOperations like any other operation (hence "shim") + * We would like this logic to simply live inside the BulkWriteOperation class + * @internal + */ +class BulkWriteShimOperation extends AbstractOperation { + bulkOperation: BulkOperationBase; + constructor(bulkOperation: BulkOperationBase, options: BulkWriteOptions) { + super(options); + this.bulkOperation = bulkOperation; + } + + execute(server: Server, session: ClientSession | undefined, callback: Callback): void { + if (this.options.session == null) { + // An implicit session could have been created by 'executeOperation' + // So if we stick it on finalOptions here, each bulk operation + // will use this same session, it'll be passed in the same way + // an explicit session would be + this.options.session = session; + } + return executeCommands(this.bulkOperation, this.options, callback); + } +} + +/** @public */ +export abstract class BulkOperationBase { + isOrdered: boolean; + /** @internal */ + s: BulkOperationPrivate; + operationId?: number; + + /** + * Create a new OrderedBulkOperation or UnorderedBulkOperation instance + * @internal + */ + constructor(collection: Collection, options: BulkWriteOptions, isOrdered: boolean) { + // determine whether bulkOperation is ordered or unordered + this.isOrdered = isOrdered; + + const topology = getTopology(collection); + options = options == null ? {} : options; + // TODO Bring from driver information in hello + // Get the namespace for the write operations + const namespace = collection.s.namespace; + // Used to mark operation as executed + const executed = false; + + // Current item + const currentOp = undefined; + + // Set max byte size + const hello = topology.lastHello(); + + // If we have autoEncryption on, batch-splitting must be done on 2mb chunks, but single documents + // over 2mb are still allowed + const usingAutoEncryption = !!(topology.s.options && topology.s.options.autoEncrypter); + const maxBsonObjectSize = + hello && hello.maxBsonObjectSize ? hello.maxBsonObjectSize : 1024 * 1024 * 16; + const maxBatchSizeBytes = usingAutoEncryption ? 1024 * 1024 * 2 : maxBsonObjectSize; + const maxWriteBatchSize = hello && hello.maxWriteBatchSize ? hello.maxWriteBatchSize : 1000; + + // Calculates the largest possible size of an Array key, represented as a BSON string + // element. This calculation: + // 1 byte for BSON type + // # of bytes = length of (string representation of (maxWriteBatchSize - 1)) + // + 1 bytes for null terminator + const maxKeySize = (maxWriteBatchSize - 1).toString(10).length + 2; + + // Final options for retryable writes + let finalOptions = Object.assign({}, options); + finalOptions = applyRetryableWrites(finalOptions, collection.s.db); + + // Final results + const bulkResult: BulkResult = { + ok: 1, + writeErrors: [], + writeConcernErrors: [], + insertedIds: [], + nInserted: 0, + nUpserted: 0, + nMatched: 0, + nModified: 0, + nRemoved: 0, + upserted: [] + }; + + // Internal state + this.s = { + // Final result + bulkResult, + // Current batch state + currentBatch: undefined, + currentIndex: 0, + // ordered specific + currentBatchSize: 0, + currentBatchSizeBytes: 0, + // unordered specific + currentInsertBatch: undefined, + currentUpdateBatch: undefined, + currentRemoveBatch: undefined, + batches: [], + // Write concern + writeConcern: WriteConcern.fromOptions(options), + // Max batch size options + maxBsonObjectSize, + maxBatchSizeBytes, + maxWriteBatchSize, + maxKeySize, + // Namespace + namespace, + // Topology + topology, + // Options + options: finalOptions, + // BSON options + bsonOptions: resolveBSONOptions(options), + // Current operation + currentOp, + // Executed + executed, + // Collection + collection, + // Fundamental error + err: undefined, + // check keys + checkKeys: typeof options.checkKeys === 'boolean' ? options.checkKeys : false + }; + + // bypass Validation + if (options.bypassDocumentValidation === true) { + this.s.bypassDocumentValidation = true; + } + } + + /** + * Add a single insert document to the bulk operation + * + * @example + * ```js + * const bulkOp = collection.initializeOrderedBulkOp(); + * + * // Adds three inserts to the bulkOp. + * bulkOp + * .insert({ a: 1 }) + * .insert({ b: 2 }) + * .insert({ c: 3 }); + * await bulkOp.execute(); + * ``` + */ + insert(document: Document): BulkOperationBase { + if (document._id == null && !shouldForceServerObjectId(this)) { + document._id = new ObjectId(); + } + + return this.addToOperationsList(BatchType.INSERT, document); + } + + /** + * Builds a find operation for an update/updateOne/delete/deleteOne/replaceOne. + * Returns a builder object used to complete the definition of the operation. + * + * @example + * ```js + * const bulkOp = collection.initializeOrderedBulkOp(); + * + * // Add an updateOne to the bulkOp + * bulkOp.find({ a: 1 }).updateOne({ $set: { b: 2 } }); + * + * // Add an updateMany to the bulkOp + * bulkOp.find({ c: 3 }).update({ $set: { d: 4 } }); + * + * // Add an upsert + * bulkOp.find({ e: 5 }).upsert().updateOne({ $set: { f: 6 } }); + * + * // Add a deletion + * bulkOp.find({ g: 7 }).deleteOne(); + * + * // Add a multi deletion + * bulkOp.find({ h: 8 }).delete(); + * + * // Add a replaceOne + * bulkOp.find({ i: 9 }).replaceOne({writeConcern: { j: 10 }}); + * + * // Update using a pipeline (requires Mongodb 4.2 or higher) + * bulk.find({ k: 11, y: { $exists: true }, z: { $exists: true } }).updateOne([ + * { $set: { total: { $sum: [ '$y', '$z' ] } } } + * ]); + * + * // All of the ops will now be executed + * await bulkOp.execute(); + * ``` + */ + find(selector: Document): FindOperators { + if (!selector) { + throw new MongoInvalidArgumentError('Bulk find operation must specify a selector'); + } + + // Save a current selector + this.s.currentOp = { + selector: selector + }; + + return new FindOperators(this); + } + + /** Specifies a raw operation to perform in the bulk write. */ + raw(op: AnyBulkWriteOperation): this { + if (op == null || typeof op !== 'object') { + throw new MongoInvalidArgumentError('Operation must be an object with an operation key'); + } + if ('insertOne' in op) { + const forceServerObjectId = shouldForceServerObjectId(this); + if (op.insertOne && op.insertOne.document == null) { + // NOTE: provided for legacy support, but this is a malformed operation + if (forceServerObjectId !== true && (op.insertOne as Document)._id == null) { + (op.insertOne as Document)._id = new ObjectId(); + } + + return this.addToOperationsList(BatchType.INSERT, op.insertOne); + } + + if (forceServerObjectId !== true && op.insertOne.document._id == null) { + op.insertOne.document._id = new ObjectId(); + } + + return this.addToOperationsList(BatchType.INSERT, op.insertOne.document); + } + + if ('replaceOne' in op || 'updateOne' in op || 'updateMany' in op) { + if ('replaceOne' in op) { + if ('q' in op.replaceOne) { + throw new MongoInvalidArgumentError('Raw operations are not allowed'); + } + const updateStatement = makeUpdateStatement( + op.replaceOne.filter, + op.replaceOne.replacement, + { ...op.replaceOne, multi: false } + ); + if (hasAtomicOperators(updateStatement.u)) { + throw new MongoInvalidArgumentError('Replacement document must not use atomic operators'); + } + return this.addToOperationsList(BatchType.UPDATE, updateStatement); + } + + if ('updateOne' in op) { + if ('q' in op.updateOne) { + throw new MongoInvalidArgumentError('Raw operations are not allowed'); + } + const updateStatement = makeUpdateStatement(op.updateOne.filter, op.updateOne.update, { + ...op.updateOne, + multi: false + }); + if (!hasAtomicOperators(updateStatement.u)) { + throw new MongoInvalidArgumentError('Update document requires atomic operators'); + } + return this.addToOperationsList(BatchType.UPDATE, updateStatement); + } + + if ('updateMany' in op) { + if ('q' in op.updateMany) { + throw new MongoInvalidArgumentError('Raw operations are not allowed'); + } + const updateStatement = makeUpdateStatement(op.updateMany.filter, op.updateMany.update, { + ...op.updateMany, + multi: true + }); + if (!hasAtomicOperators(updateStatement.u)) { + throw new MongoInvalidArgumentError('Update document requires atomic operators'); + } + return this.addToOperationsList(BatchType.UPDATE, updateStatement); + } + } + + if ('deleteOne' in op) { + if ('q' in op.deleteOne) { + throw new MongoInvalidArgumentError('Raw operations are not allowed'); + } + return this.addToOperationsList( + BatchType.DELETE, + makeDeleteStatement(op.deleteOne.filter, { ...op.deleteOne, limit: 1 }) + ); + } + + if ('deleteMany' in op) { + if ('q' in op.deleteMany) { + throw new MongoInvalidArgumentError('Raw operations are not allowed'); + } + return this.addToOperationsList( + BatchType.DELETE, + makeDeleteStatement(op.deleteMany.filter, { ...op.deleteMany, limit: 0 }) + ); + } + + // otherwise an unknown operation was provided + throw new MongoInvalidArgumentError( + 'bulkWrite only supports insertOne, updateOne, updateMany, deleteOne, deleteMany' + ); + } + + get bsonOptions(): BSONSerializeOptions { + return this.s.bsonOptions; + } + + get writeConcern(): WriteConcern | undefined { + return this.s.writeConcern; + } + + get batches(): Batch[] { + const batches = [...this.s.batches]; + if (this.isOrdered) { + if (this.s.currentBatch) batches.push(this.s.currentBatch); + } else { + if (this.s.currentInsertBatch) batches.push(this.s.currentInsertBatch); + if (this.s.currentUpdateBatch) batches.push(this.s.currentUpdateBatch); + if (this.s.currentRemoveBatch) batches.push(this.s.currentRemoveBatch); + } + return batches; + } + + execute(options?: BulkWriteOptions): Promise; + execute(callback: Callback): void; + execute(options: BulkWriteOptions | undefined, callback: Callback): void; + execute( + options?: BulkWriteOptions | Callback, + callback?: Callback + ): Promise | void; + execute( + options?: BulkWriteOptions | Callback, + callback?: Callback + ): Promise | void { + if (typeof options === 'function') (callback = options), (options = {}); + options = options ?? {}; + + if (this.s.executed) { + return handleEarlyError(new MongoBatchReExecutionError(), callback); + } + + const writeConcern = WriteConcern.fromOptions(options); + if (writeConcern) { + this.s.writeConcern = writeConcern; + } + + // If we have current batch + if (this.isOrdered) { + if (this.s.currentBatch) this.s.batches.push(this.s.currentBatch); + } else { + if (this.s.currentInsertBatch) this.s.batches.push(this.s.currentInsertBatch); + if (this.s.currentUpdateBatch) this.s.batches.push(this.s.currentUpdateBatch); + if (this.s.currentRemoveBatch) this.s.batches.push(this.s.currentRemoveBatch); + } + // If we have no operations in the bulk raise an error + if (this.s.batches.length === 0) { + const emptyBatchError = new MongoInvalidArgumentError( + 'Invalid BulkOperation, Batch cannot be empty' + ); + return handleEarlyError(emptyBatchError, callback); + } + + this.s.executed = true; + const finalOptions = { ...this.s.options, ...options }; + const operation = new BulkWriteShimOperation(this, finalOptions); + + return executeOperation(this.s.collection.s.db.s.client, operation, callback); + } + + /** + * Handles the write error before executing commands + * @internal + */ + handleWriteError(callback: Callback, writeResult: BulkWriteResult): boolean { + if (this.s.bulkResult.writeErrors.length > 0) { + const msg = this.s.bulkResult.writeErrors[0].errmsg + ? this.s.bulkResult.writeErrors[0].errmsg + : 'write operation failed'; + + callback( + new MongoBulkWriteError( + { + message: msg, + code: this.s.bulkResult.writeErrors[0].code, + writeErrors: this.s.bulkResult.writeErrors + }, + writeResult + ) + ); + + return true; + } + + const writeConcernError = writeResult.getWriteConcernError(); + if (writeConcernError) { + callback(new MongoBulkWriteError(writeConcernError, writeResult)); + return true; + } + + return false; + } + + abstract addToOperationsList( + batchType: BatchType, + document: Document | UpdateStatement | DeleteStatement + ): this; +} + +Object.defineProperty(BulkOperationBase.prototype, 'length', { + enumerable: true, + get() { + return this.s.currentIndex; + } +}); + +/** helper function to assist with promiseOrCallback behavior */ +function handleEarlyError( + err?: AnyError, + callback?: Callback +): Promise | void { + const Promise = PromiseProvider.get(); + if (typeof callback === 'function') { + callback(err); + return; + } + + return Promise.reject(err); +} + +function shouldForceServerObjectId(bulkOperation: BulkOperationBase): boolean { + if (typeof bulkOperation.s.options.forceServerObjectId === 'boolean') { + return bulkOperation.s.options.forceServerObjectId; + } + + if (typeof bulkOperation.s.collection.s.db.options?.forceServerObjectId === 'boolean') { + return bulkOperation.s.collection.s.db.options?.forceServerObjectId; + } + + return false; +} + +function isInsertBatch(batch: Batch): boolean { + return batch.batchType === BatchType.INSERT; +} + +function isUpdateBatch(batch: Batch): batch is Batch { + return batch.batchType === BatchType.UPDATE; +} + +function isDeleteBatch(batch: Batch): batch is Batch { + return batch.batchType === BatchType.DELETE; +} + +function buildCurrentOp(bulkOp: BulkOperationBase): Document { + let { currentOp } = bulkOp.s; + bulkOp.s.currentOp = undefined; + if (!currentOp) currentOp = {}; + return currentOp; +} diff --git a/ts-ticket-office-service/node_modules/mongodb/src/bulk/ordered.ts b/ts-ticket-office-service/node_modules/mongodb/src/bulk/ordered.ts new file mode 100644 index 000000000..e0dbf9b7e --- /dev/null +++ b/ts-ticket-office-service/node_modules/mongodb/src/bulk/ordered.ts @@ -0,0 +1,82 @@ +import type { Document } from '../bson'; +import * as BSON from '../bson'; +import type { Collection } from '../collection'; +import { MongoInvalidArgumentError } from '../error'; +import type { DeleteStatement } from '../operations/delete'; +import type { UpdateStatement } from '../operations/update'; +import { Batch, BatchType, BulkOperationBase, BulkWriteOptions } from './common'; + +/** @public */ +export class OrderedBulkOperation extends BulkOperationBase { + constructor(collection: Collection, options: BulkWriteOptions) { + super(collection, options, true); + } + + addToOperationsList( + batchType: BatchType, + document: Document | UpdateStatement | DeleteStatement + ): this { + // Get the bsonSize + const bsonSize = BSON.calculateObjectSize(document, { + checkKeys: false, + // Since we don't know what the user selected for BSON options here, + // err on the safe side, and check the size with ignoreUndefined: false. + ignoreUndefined: false + } as any); + + // Throw error if the doc is bigger than the max BSON size + if (bsonSize >= this.s.maxBsonObjectSize) + // TODO(NODE-3483): Change this to MongoBSONError + throw new MongoInvalidArgumentError( + `Document is larger than the maximum size ${this.s.maxBsonObjectSize}` + ); + + // Create a new batch object if we don't have a current one + if (this.s.currentBatch == null) { + this.s.currentBatch = new Batch(batchType, this.s.currentIndex); + } + + const maxKeySize = this.s.maxKeySize; + + // Check if we need to create a new batch + if ( + // New batch if we exceed the max batch op size + this.s.currentBatchSize + 1 >= this.s.maxWriteBatchSize || + // New batch if we exceed the maxBatchSizeBytes. Only matters if batch already has a doc, + // since we can't sent an empty batch + (this.s.currentBatchSize > 0 && + this.s.currentBatchSizeBytes + maxKeySize + bsonSize >= this.s.maxBatchSizeBytes) || + // New batch if the new op does not have the same op type as the current batch + this.s.currentBatch.batchType !== batchType + ) { + // Save the batch to the execution stack + this.s.batches.push(this.s.currentBatch); + + // Create a new batch + this.s.currentBatch = new Batch(batchType, this.s.currentIndex); + + // Reset the current size trackers + this.s.currentBatchSize = 0; + this.s.currentBatchSizeBytes = 0; + } + + if (batchType === BatchType.INSERT) { + this.s.bulkResult.insertedIds.push({ + index: this.s.currentIndex, + _id: (document as Document)._id + }); + } + + // We have an array of documents + if (Array.isArray(document)) { + throw new MongoInvalidArgumentError('Operation passed in cannot be an Array'); + } + + this.s.currentBatch.originalIndexes.push(this.s.currentIndex); + this.s.currentBatch.operations.push(document); + this.s.currentBatchSize += 1; + this.s.currentBatchSizeBytes += maxKeySize + bsonSize; + this.s.currentIndex += 1; + return this; + } +} diff --git a/ts-ticket-office-service/node_modules/mongodb/src/bulk/unordered.ts b/ts-ticket-office-service/node_modules/mongodb/src/bulk/unordered.ts new file mode 100644 index 000000000..b4227e8d0 --- /dev/null +++ b/ts-ticket-office-service/node_modules/mongodb/src/bulk/unordered.ts @@ -0,0 +1,109 @@ +import type { Document } from '../bson'; +import * as BSON from '../bson'; +import type { Collection } from '../collection'; +import { MongoInvalidArgumentError } from '../error'; +import type { DeleteStatement } from '../operations/delete'; +import type { UpdateStatement } from '../operations/update'; +import type { Callback } from '../utils'; +import { Batch, BatchType, BulkOperationBase, BulkWriteOptions, BulkWriteResult } from './common'; + +/** @public */ +export class UnorderedBulkOperation extends BulkOperationBase { + constructor(collection: Collection, options: BulkWriteOptions) { + super(collection, options, false); + } + + override handleWriteError(callback: Callback, writeResult: BulkWriteResult): boolean { + if (this.s.batches.length) { + return false; + } + + return super.handleWriteError(callback, writeResult); + } + + addToOperationsList( + batchType: BatchType, + document: Document | UpdateStatement | DeleteStatement + ): this { + // Get the bsonSize + const bsonSize = BSON.calculateObjectSize(document, { + checkKeys: false, + + // Since we don't know what the user selected for BSON options here, + // err on the safe side, and check the size with ignoreUndefined: false. + ignoreUndefined: false + } as any); + + // Throw error if the doc is bigger than the max BSON size + if (bsonSize >= this.s.maxBsonObjectSize) { + // TODO(NODE-3483): Change this to MongoBSONError + throw new MongoInvalidArgumentError( + `Document is larger than the maximum size ${this.s.maxBsonObjectSize}` + ); + } + + // Holds the current batch + this.s.currentBatch = undefined; + // Get the right type of batch + if (batchType === BatchType.INSERT) { + this.s.currentBatch = this.s.currentInsertBatch; + } else if (batchType === BatchType.UPDATE) { + this.s.currentBatch = this.s.currentUpdateBatch; + } else if (batchType === BatchType.DELETE) { + this.s.currentBatch = this.s.currentRemoveBatch; + } + + const maxKeySize = this.s.maxKeySize; + + // Create a new batch object if we don't have a current one + if (this.s.currentBatch == null) { + this.s.currentBatch = new Batch(batchType, this.s.currentIndex); + } + + // Check if we need to create a new batch + if ( + // New batch if we exceed the max batch op size + this.s.currentBatch.size + 1 >= this.s.maxWriteBatchSize || + // New batch if we exceed the maxBatchSizeBytes. Only matters if batch already has a doc, + // since we can't sent an empty batch + (this.s.currentBatch.size > 0 && + this.s.currentBatch.sizeBytes + maxKeySize + bsonSize >= this.s.maxBatchSizeBytes) || + // New batch if the new op does not have the same op type as the current batch + this.s.currentBatch.batchType !== batchType + ) { + // Save the batch to the execution stack + this.s.batches.push(this.s.currentBatch); + + // Create a new batch + this.s.currentBatch = new Batch(batchType, this.s.currentIndex); + } + + // We have an array of documents + if (Array.isArray(document)) { + throw new MongoInvalidArgumentError('Operation passed in cannot be an Array'); + } + + this.s.currentBatch.operations.push(document); + this.s.currentBatch.originalIndexes.push(this.s.currentIndex); + this.s.currentIndex = this.s.currentIndex + 1; + + // Save back the current Batch to the right type + if (batchType === BatchType.INSERT) { + this.s.currentInsertBatch = this.s.currentBatch; + this.s.bulkResult.insertedIds.push({ + index: this.s.bulkResult.insertedIds.length, + _id: (document as Document)._id + }); + } else if (batchType === BatchType.UPDATE) { + this.s.currentUpdateBatch = this.s.currentBatch; + } else if (batchType === BatchType.DELETE) { + this.s.currentRemoveBatch = this.s.currentBatch; + } + + // Update current batch size + this.s.currentBatch.size += 1; + this.s.currentBatch.sizeBytes += maxKeySize + bsonSize; + + return this; + } +} diff --git a/ts-ticket-office-service/node_modules/mongodb/src/change_stream.ts b/ts-ticket-office-service/node_modules/mongodb/src/change_stream.ts new file mode 100644 index 000000000..93be71047 --- /dev/null +++ b/ts-ticket-office-service/node_modules/mongodb/src/change_stream.ts @@ -0,0 +1,941 @@ +import type { Readable } from 'stream'; +import { promisify } from 'util'; + +import type { Binary, Document, Timestamp } from './bson'; +import { Collection } from './collection'; +import { CHANGE, CLOSE, END, ERROR, INIT, MORE, RESPONSE, RESUME_TOKEN_CHANGED } from './constants'; +import type { AbstractCursorEvents, CursorStreamOptions } from './cursor/abstract_cursor'; +import { ChangeStreamCursor, ChangeStreamCursorOptions } from './cursor/change_stream_cursor'; +import { Db } from './db'; +import { + AnyError, + isResumableError, + MongoAPIError, + MongoChangeStreamError, + MongoRuntimeError +} from './error'; +import { MongoClient } from './mongo_client'; +import { InferIdType, TypedEventEmitter } from './mongo_types'; +import type { AggregateOptions } from './operations/aggregate'; +import type { CollationOptions, OperationParent } from './operations/command'; +import type { ReadPreference } from './read_preference'; +import type { ServerSessionId } from './sessions'; +import { Callback, filterOptions, getTopology, maybePromise, MongoDBNamespace } from './utils'; + +/** @internal */ +const kCursorStream = Symbol('cursorStream'); +/** @internal */ +const kClosed = Symbol('closed'); +/** @internal */ +const kMode = Symbol('mode'); + +const CHANGE_STREAM_OPTIONS = [ + 'resumeAfter', + 'startAfter', + 'startAtOperationTime', + 'fullDocument', + 'fullDocumentBeforeChange', + 'showExpandedEvents' +] as const; + +const CHANGE_DOMAIN_TYPES = { + COLLECTION: Symbol('Collection'), + DATABASE: Symbol('Database'), + CLUSTER: Symbol('Cluster') +}; + +const CHANGE_STREAM_EVENTS = [RESUME_TOKEN_CHANGED, END, CLOSE]; + +const NO_RESUME_TOKEN_ERROR = + 'A change stream document has been received that lacks a resume token (_id).'; +const CHANGESTREAM_CLOSED_ERROR = 'ChangeStream is closed'; + +/** + * @public + * @deprecated Please use the ChangeStreamCursorOptions type instead. + */ +export interface ResumeOptions { + startAtOperationTime?: Timestamp; + batchSize?: number; + maxAwaitTimeMS?: number; + collation?: CollationOptions; + readPreference?: ReadPreference; + resumeAfter?: ResumeToken; + startAfter?: ResumeToken; + fullDocument?: string; +} + +/** + * Represents the logical starting point for a new ChangeStream or resuming a ChangeStream on the server. + * @see https://www.mongodb.com/docs/manual/changeStreams/#std-label-change-stream-resume + * @public + */ +export type ResumeToken = unknown; + +/** + * Represents a specific point in time on a server. Can be retrieved by using `db.command()` + * @public + * @see https://docs.mongodb.com/manual/reference/method/db.runCommand/#response + */ +export type OperationTime = Timestamp; + +/** @public */ +export interface PipeOptions { + end?: boolean; +} + +/** + * Options that can be passed to a ChangeStream. Note that startAfter, resumeAfter, and startAtOperationTime are all mutually exclusive, and the server will error if more than one is specified. + * @public + */ +export interface ChangeStreamOptions extends AggregateOptions { + /** + * Allowed values: 'updateLookup', 'whenAvailable', 'required'. + * + * When set to 'updateLookup', the change notification for partial updates + * will include both a delta describing the changes to the document as well + * as a copy of the entire document that was changed from some time after + * the change occurred. + * + * When set to 'whenAvailable', configures the change stream to return the + * post-image of the modified document for replace and update change events + * if the post-image for this event is available. + * + * When set to 'required', the same behavior as 'whenAvailable' except that + * an error is raised if the post-image is not available. + */ + fullDocument?: string; + + /** + * Allowed values: 'whenAvailable', 'required', 'off'. + * + * The default is to not send a value, which is equivalent to 'off'. + * + * When set to 'whenAvailable', configures the change stream to return the + * pre-image of the modified document for replace, update, and delete change + * events if it is available. + * + * When set to 'required', the same behavior as 'whenAvailable' except that + * an error is raised if the pre-image is not available. + */ + fullDocumentBeforeChange?: string; + /** The maximum amount of time for the server to wait on new documents to satisfy a change stream query. */ + maxAwaitTimeMS?: number; + /** + * Allows you to start a changeStream after a specified event. + * @see https://docs.mongodb.com/manual/changeStreams/#resumeafter-for-change-streams + */ + resumeAfter?: ResumeToken; + /** + * Similar to resumeAfter, but will allow you to start after an invalidated event. + * @see https://docs.mongodb.com/manual/changeStreams/#startafter-for-change-streams + */ + startAfter?: ResumeToken; + /** Will start the changeStream after the specified operationTime. */ + startAtOperationTime?: OperationTime; + /** + * The number of documents to return per batch. + * @see https://docs.mongodb.com/manual/reference/command/aggregate + */ + batchSize?: number; + + /** + * When enabled, configures the change stream to include extra change events. + * + * - createIndexes + * - dropIndexes + * - modify + * - create + * - shardCollection + * - reshardCollection + * - refineCollectionShardKey + */ + showExpandedEvents?: boolean; +} + +/** @public */ +export interface ChangeStreamNameSpace { + db: string; + coll: string; +} + +/** @public */ +export interface ChangeStreamDocumentKey { + /** + * For unsharded collections this contains a single field `_id`. + * For sharded collections, this will contain all the components of the shard key + */ + documentKey: { _id: InferIdType; [shardKey: string]: any }; +} + +/** @public */ +export interface ChangeStreamDocumentCommon { + /** + * The id functions as an opaque token for use when resuming an interrupted + * change stream. + */ + _id: ResumeToken; + /** + * The timestamp from the oplog entry associated with the event. + * For events that happened as part of a multi-document transaction, the associated change stream + * notifications will have the same clusterTime value, namely the time when the transaction was committed. + * On a sharded cluster, events that occur on different shards can have the same clusterTime but be + * associated with different transactions or even not be associated with any transaction. + * To identify events for a single transaction, you can use the combination of lsid and txnNumber in the change stream event document. + */ + clusterTime?: Timestamp; + + /** + * The transaction number. + * Only present if the operation is part of a multi-document transaction. + * + * **NOTE:** txnNumber can be a Long if promoteLongs is set to false + */ + txnNumber?: number; + + /** + * The identifier for the session associated with the transaction. + * Only present if the operation is part of a multi-document transaction. + */ + lsid?: ServerSessionId; +} + +/** @public */ +export interface ChangeStreamDocumentCollectionUUID { + /** + * The UUID (Binary subtype 4) of the collection that the operation was performed on. + * + * Only present when the `showExpandedEvents` flag is enabled. + * + * **NOTE:** collectionUUID will be converted to a NodeJS Buffer if the promoteBuffers + * flag is enabled. + * + * @since 6.1.0 + */ + collectionUUID: Binary; +} + +/** @public */ +export interface ChangeStreamDocumentOperationDescription { + /** + * An description of the operation. + * + * Only present when the `showExpandedEvents` flag is enabled. + * + * @since 6.1.0 + */ + operationDescription?: Document; +} + +/** + * @public + * @see https://www.mongodb.com/docs/manual/reference/change-events/#insert-event + */ +export interface ChangeStreamInsertDocument + extends ChangeStreamDocumentCommon, + ChangeStreamDocumentKey, + ChangeStreamDocumentCollectionUUID { + /** Describes the type of operation represented in this change notification */ + operationType: 'insert'; + /** This key will contain the document being inserted */ + fullDocument: TSchema; + /** Namespace the insert event occured on */ + ns: ChangeStreamNameSpace; +} + +/** + * @public + * @see https://www.mongodb.com/docs/manual/reference/change-events/#update-event + */ +export interface ChangeStreamUpdateDocument + extends ChangeStreamDocumentCommon, + ChangeStreamDocumentKey, + ChangeStreamDocumentCollectionUUID { + /** Describes the type of operation represented in this change notification */ + operationType: 'update'; + /** + * This is only set if `fullDocument` is set to `'updateLookup'` + * Contains the point-in-time post-image of the modified document if the + * post-image is available and either 'required' or 'whenAvailable' was + * specified for the 'fullDocument' option when creating the change stream. + */ + fullDocument?: TSchema; + /** Contains a description of updated and removed fields in this operation */ + updateDescription: UpdateDescription; + /** Namespace the update event occured on */ + ns: ChangeStreamNameSpace; + /** + * Contains the pre-image of the modified or deleted document if the + * pre-image is available for the change event and either 'required' or + * 'whenAvailable' was specified for the 'fullDocumentBeforeChange' option + * when creating the change stream. If 'whenAvailable' was specified but the + * pre-image is unavailable, this will be explicitly set to null. + */ + fullDocumentBeforeChange?: TSchema; +} + +/** + * @public + * @see https://www.mongodb.com/docs/manual/reference/change-events/#replace-event + */ +export interface ChangeStreamReplaceDocument + extends ChangeStreamDocumentCommon, + ChangeStreamDocumentKey { + /** Describes the type of operation represented in this change notification */ + operationType: 'replace'; + /** The fullDocument of a replace event represents the document after the insert of the replacement document */ + fullDocument: TSchema; + /** Namespace the replace event occured on */ + ns: ChangeStreamNameSpace; + /** + * Contains the pre-image of the modified or deleted document if the + * pre-image is available for the change event and either 'required' or + * 'whenAvailable' was specified for the 'fullDocumentBeforeChange' option + * when creating the change stream. If 'whenAvailable' was specified but the + * pre-image is unavailable, this will be explicitly set to null. + */ + fullDocumentBeforeChange?: TSchema; +} + +/** + * @public + * @see https://www.mongodb.com/docs/manual/reference/change-events/#delete-event + */ +export interface ChangeStreamDeleteDocument + extends ChangeStreamDocumentCommon, + ChangeStreamDocumentKey, + ChangeStreamDocumentCollectionUUID { + /** Describes the type of operation represented in this change notification */ + operationType: 'delete'; + /** Namespace the delete event occured on */ + ns: ChangeStreamNameSpace; + /** + * Contains the pre-image of the modified or deleted document if the + * pre-image is available for the change event and either 'required' or + * 'whenAvailable' was specified for the 'fullDocumentBeforeChange' option + * when creating the change stream. If 'whenAvailable' was specified but the + * pre-image is unavailable, this will be explicitly set to null. + */ + fullDocumentBeforeChange?: TSchema; +} + +/** + * @public + * @see https://www.mongodb.com/docs/manual/reference/change-events/#drop-event + */ +export interface ChangeStreamDropDocument + extends ChangeStreamDocumentCommon, + ChangeStreamDocumentCollectionUUID { + /** Describes the type of operation represented in this change notification */ + operationType: 'drop'; + /** Namespace the drop event occured on */ + ns: ChangeStreamNameSpace; +} + +/** + * @public + * @see https://www.mongodb.com/docs/manual/reference/change-events/#rename-event + */ +export interface ChangeStreamRenameDocument + extends ChangeStreamDocumentCommon, + ChangeStreamDocumentCollectionUUID { + /** Describes the type of operation represented in this change notification */ + operationType: 'rename'; + /** The new name for the `ns.coll` collection */ + to: { db: string; coll: string }; + /** The "from" namespace that the rename occured on */ + ns: ChangeStreamNameSpace; +} + +/** + * @public + * @see https://www.mongodb.com/docs/manual/reference/change-events/#dropdatabase-event + */ +export interface ChangeStreamDropDatabaseDocument extends ChangeStreamDocumentCommon { + /** Describes the type of operation represented in this change notification */ + operationType: 'dropDatabase'; + /** The database dropped */ + ns: { db: string }; +} + +/** + * @public + * @see https://www.mongodb.com/docs/manual/reference/change-events/#invalidate-event + */ +export interface ChangeStreamInvalidateDocument extends ChangeStreamDocumentCommon { + /** Describes the type of operation represented in this change notification */ + operationType: 'invalidate'; +} + +/** + * Only present when the `showExpandedEvents` flag is enabled. + * @public + * @see https://www.mongodb.com/docs/manual/reference/change-events/ + */ +export interface ChangeStreamCreateIndexDocument + extends ChangeStreamDocumentCommon, + ChangeStreamDocumentCollectionUUID, + ChangeStreamDocumentOperationDescription { + /** Describes the type of operation represented in this change notification */ + operationType: 'createIndexes'; +} + +/** + * Only present when the `showExpandedEvents` flag is enabled. + * @public + * @see https://www.mongodb.com/docs/manual/reference/change-events/ + */ +export interface ChangeStreamDropIndexDocument + extends ChangeStreamDocumentCommon, + ChangeStreamDocumentCollectionUUID, + ChangeStreamDocumentOperationDescription { + /** Describes the type of operation represented in this change notification */ + operationType: 'dropIndexes'; +} + +/** + * Only present when the `showExpandedEvents` flag is enabled. + * @public + * @see https://www.mongodb.com/docs/manual/reference/change-events/ + */ +export interface ChangeStreamCollModDocument + extends ChangeStreamDocumentCommon, + ChangeStreamDocumentCollectionUUID { + /** Describes the type of operation represented in this change notification */ + operationType: 'modify'; +} + +/** + * @public + * @see https://www.mongodb.com/docs/manual/reference/change-events/ + */ +export interface ChangeStreamCreateDocument + extends ChangeStreamDocumentCommon, + ChangeStreamDocumentCollectionUUID { + /** Describes the type of operation represented in this change notification */ + operationType: 'create'; +} + +/** + * @public + * @see https://www.mongodb.com/docs/manual/reference/change-events/ + */ +export interface ChangeStreamShardCollectionDocument + extends ChangeStreamDocumentCommon, + ChangeStreamDocumentCollectionUUID, + ChangeStreamDocumentOperationDescription { + /** Describes the type of operation represented in this change notification */ + operationType: 'shardCollection'; +} + +/** + * @public + * @see https://www.mongodb.com/docs/manual/reference/change-events/ + */ +export interface ChangeStreamReshardCollectionDocument + extends ChangeStreamDocumentCommon, + ChangeStreamDocumentCollectionUUID, + ChangeStreamDocumentOperationDescription { + /** Describes the type of operation represented in this change notification */ + operationType: 'reshardCollection'; +} + +/** + * @public + * @see https://www.mongodb.com/docs/manual/reference/change-events/ + */ +export interface ChangeStreamRefineCollectionShardKeyDocument + extends ChangeStreamDocumentCommon, + ChangeStreamDocumentCollectionUUID, + ChangeStreamDocumentOperationDescription { + /** Describes the type of operation represented in this change notification */ + operationType: 'refineCollectionShardKey'; +} + +/** @public */ +export type ChangeStreamDocument = + | ChangeStreamInsertDocument + | ChangeStreamUpdateDocument + | ChangeStreamReplaceDocument + | ChangeStreamDeleteDocument + | ChangeStreamDropDocument + | ChangeStreamRenameDocument + | ChangeStreamDropDatabaseDocument + | ChangeStreamInvalidateDocument + | ChangeStreamCreateIndexDocument + | ChangeStreamCreateDocument + | ChangeStreamCollModDocument + | ChangeStreamDropIndexDocument + | ChangeStreamShardCollectionDocument + | ChangeStreamReshardCollectionDocument + | ChangeStreamRefineCollectionShardKeyDocument; + +/** @public */ +export interface UpdateDescription { + /** + * A document containing key:value pairs of names of the fields that were + * changed, and the new value for those fields. + */ + updatedFields?: Partial; + + /** + * An array of field names that were removed from the document. + */ + removedFields?: string[]; + + /** + * An array of documents which record array truncations performed with pipeline-based updates using one or more of the following stages: + * - $addFields + * - $set + * - $replaceRoot + * - $replaceWith + */ + truncatedArrays?: Array<{ + /** The name of the truncated field. */ + field: string; + /** The number of elements in the truncated array. */ + newSize: number; + }>; +} + +/** @public */ +export type ChangeStreamEvents< + TSchema extends Document = Document, + TChange extends Document = ChangeStreamDocument +> = { + resumeTokenChanged(token: ResumeToken): void; + init(response: any): void; + more(response?: any): void; + response(): void; + end(): void; + error(error: Error): void; + change(change: TChange): void; +} & AbstractCursorEvents; + +/** + * Creates a new Change Stream instance. Normally created using {@link Collection#watch|Collection.watch()}. + * @public + */ +export class ChangeStream< + TSchema extends Document = Document, + TChange extends Document = ChangeStreamDocument +> extends TypedEventEmitter> { + pipeline: Document[]; + options: ChangeStreamOptions; + parent: MongoClient | Db | Collection; + namespace: MongoDBNamespace; + type: symbol; + /** @internal */ + cursor: ChangeStreamCursor; + streamOptions?: CursorStreamOptions; + /** @internal */ + [kCursorStream]?: Readable & AsyncIterable; + /** @internal */ + [kClosed]: boolean; + /** @internal */ + [kMode]: false | 'iterator' | 'emitter'; + + /** @event */ + static readonly RESPONSE = RESPONSE; + /** @event */ + static readonly MORE = MORE; + /** @event */ + static readonly INIT = INIT; + /** @event */ + static readonly CLOSE = CLOSE; + /** + * Fired for each new matching change in the specified namespace. Attaching a `change` + * event listener to a Change Stream will switch the stream into flowing mode. Data will + * then be passed as soon as it is available. + * @event + */ + static readonly CHANGE = CHANGE; + /** @event */ + static readonly END = END; + /** @event */ + static readonly ERROR = ERROR; + /** + * Emitted each time the change stream stores a new resume token. + * @event + */ + static readonly RESUME_TOKEN_CHANGED = RESUME_TOKEN_CHANGED; + + /** + * @internal + * + * @param parent - The parent object that created this change stream + * @param pipeline - An array of {@link https://docs.mongodb.com/manual/reference/operator/aggregation-pipeline/|aggregation pipeline stages} through which to pass change stream documents + */ + constructor( + parent: OperationParent, + pipeline: Document[] = [], + options: ChangeStreamOptions = {} + ) { + super(); + + this.pipeline = pipeline; + this.options = options; + + if (parent instanceof Collection) { + this.type = CHANGE_DOMAIN_TYPES.COLLECTION; + } else if (parent instanceof Db) { + this.type = CHANGE_DOMAIN_TYPES.DATABASE; + } else if (parent instanceof MongoClient) { + this.type = CHANGE_DOMAIN_TYPES.CLUSTER; + } else { + throw new MongoChangeStreamError( + 'Parent provided to ChangeStream constructor must be an instance of Collection, Db, or MongoClient' + ); + } + + this.parent = parent; + this.namespace = parent.s.namespace; + if (!this.options.readPreference && parent.readPreference) { + this.options.readPreference = parent.readPreference; + } + + // Create contained Change Stream cursor + this.cursor = this._createChangeStreamCursor(options); + + this[kClosed] = false; + this[kMode] = false; + + // Listen for any `change` listeners being added to ChangeStream + this.on('newListener', eventName => { + if (eventName === 'change' && this.cursor && this.listenerCount('change') === 0) { + this._streamEvents(this.cursor); + } + }); + + this.on('removeListener', eventName => { + if (eventName === 'change' && this.listenerCount('change') === 0 && this.cursor) { + this[kCursorStream]?.removeAllListeners('data'); + } + }); + } + + /** @internal */ + get cursorStream(): (Readable & AsyncIterable) | undefined { + return this[kCursorStream]; + } + + /** The cached resume token that is used to resume after the most recently returned change. */ + get resumeToken(): ResumeToken { + return this.cursor?.resumeToken; + } + + /** Check if there is any document still available in the Change Stream */ + hasNext(): Promise; + hasNext(callback: Callback): void; + hasNext(callback?: Callback): Promise | void { + this._setIsIterator(); + // TOOD(NODE-4319): Add eslint rule preventing accidental variable shadowing + // Shadowing is intentional here. We want to override the `callback` variable + // from the outer scope so that the inner scope doesn't accidentally call the wrong callback. + return maybePromise(callback, callback => { + (async () => { + try { + const hasNext = await this.cursor.hasNext(); + return hasNext; + } catch (error) { + try { + await this._processErrorIteratorMode(error); + const hasNext = await this.cursor.hasNext(); + return hasNext; + } catch (error) { + await this.close().catch(err => err); + throw error; + } + } + })().then( + hasNext => callback(undefined, hasNext), + error => callback(error) + ); + }); + } + + /** Get the next available document from the Change Stream. */ + next(): Promise; + next(callback: Callback): void; + next(callback?: Callback): Promise | void { + this._setIsIterator(); + // TOOD(NODE-4319): Add eslint rule preventing accidental variable shadowing + // Shadowing is intentional here. We want to override the `callback` variable + // from the outer scope so that the inner scope doesn't accidentally call the wrong callback. + return maybePromise(callback, callback => { + (async () => { + try { + const change = await this.cursor.next(); + const processedChange = this._processChange(change ?? null); + return processedChange; + } catch (error) { + try { + await this._processErrorIteratorMode(error); + const change = await this.cursor.next(); + const processedChange = this._processChange(change ?? null); + return processedChange; + } catch (error) { + await this.close().catch(err => err); + throw error; + } + } + })().then( + change => callback(undefined, change), + error => callback(error) + ); + }); + } + + /** + * Try to get the next available document from the Change Stream's cursor or `null` if an empty batch is returned + */ + tryNext(): Promise; + tryNext(callback: Callback): void; + tryNext(callback?: Callback): Promise | void { + this._setIsIterator(); + // TOOD(NODE-4319): Add eslint rule preventing accidental variable shadowing + // Shadowing is intentional here. We want to override the `callback` variable + // from the outer scope so that the inner scope doesn't accidentally call the wrong callback. + return maybePromise(callback, callback => { + (async () => { + try { + const change = await this.cursor.tryNext(); + return change ?? null; + } catch (error) { + try { + await this._processErrorIteratorMode(error); + const change = await this.cursor.tryNext(); + return change ?? null; + } catch (error) { + await this.close().catch(err => err); + throw error; + } + } + })().then( + change => callback(undefined, change), + error => callback(error) + ); + }); + } + + /** Is the cursor closed */ + get closed(): boolean { + return this[kClosed] || this.cursor.closed; + } + + /** Close the Change Stream */ + close(): Promise; + close(callback: Callback): void; + close(callback?: Callback): Promise | void { + this[kClosed] = true; + + return maybePromise(callback, cb => { + const cursor = this.cursor; + return cursor.close(err => { + this._endStream(); + return cb(err); + }); + }); + } + + /** + * Return a modified Readable stream including a possible transform method. + * + * NOTE: When using a Stream to process change stream events, the stream will + * NOT automatically resume in the case a resumable error is encountered. + * + * @throws MongoChangeStreamError if the underlying cursor or the change stream is closed + */ + stream(options?: CursorStreamOptions): Readable & AsyncIterable { + if (this.closed) { + throw new MongoChangeStreamError(CHANGESTREAM_CLOSED_ERROR); + } + + this.streamOptions = options; + return this.cursor.stream(options); + } + + /** @internal */ + private _setIsEmitter(): void { + if (this[kMode] === 'iterator') { + // TODO(NODE-3485): Replace with MongoChangeStreamModeError + throw new MongoAPIError( + 'ChangeStream cannot be used as an EventEmitter after being used as an iterator' + ); + } + this[kMode] = 'emitter'; + } + + /** @internal */ + private _setIsIterator(): void { + if (this[kMode] === 'emitter') { + // TODO(NODE-3485): Replace with MongoChangeStreamModeError + throw new MongoAPIError( + 'ChangeStream cannot be used as an iterator after being used as an EventEmitter' + ); + } + this[kMode] = 'iterator'; + } + + /** + * Create a new change stream cursor based on self's configuration + * @internal + */ + private _createChangeStreamCursor( + options: ChangeStreamOptions | ChangeStreamCursorOptions + ): ChangeStreamCursor { + const changeStreamStageOptions = filterOptions(options, CHANGE_STREAM_OPTIONS); + if (this.type === CHANGE_DOMAIN_TYPES.CLUSTER) { + changeStreamStageOptions.allChangesForCluster = true; + } + const pipeline = [{ $changeStream: changeStreamStageOptions }, ...this.pipeline]; + + const client: MongoClient | null = + this.type === CHANGE_DOMAIN_TYPES.CLUSTER + ? (this.parent as MongoClient) + : this.type === CHANGE_DOMAIN_TYPES.DATABASE + ? (this.parent as Db).s.client + : this.type === CHANGE_DOMAIN_TYPES.COLLECTION + ? (this.parent as Collection).s.db.s.client + : null; + + if (client == null) { + // This should never happen because of the assertion in the constructor + throw new MongoRuntimeError( + `Changestream type should only be one of cluster, database, collection. Found ${this.type.toString()}` + ); + } + + const changeStreamCursor = new ChangeStreamCursor( + client, + this.namespace, + pipeline, + options + ); + + for (const event of CHANGE_STREAM_EVENTS) { + changeStreamCursor.on(event, e => this.emit(event, e)); + } + + if (this.listenerCount(ChangeStream.CHANGE) > 0) { + this._streamEvents(changeStreamCursor); + } + + return changeStreamCursor; + } + + /** @internal */ + private _closeEmitterModeWithError(error: AnyError): void { + this.emit(ChangeStream.ERROR, error); + + this.close(() => { + // nothing to do + }); + } + + /** @internal */ + private _streamEvents(cursor: ChangeStreamCursor): void { + this._setIsEmitter(); + const stream = this[kCursorStream] ?? cursor.stream(); + this[kCursorStream] = stream; + stream.on('data', change => { + try { + const processedChange = this._processChange(change); + this.emit(ChangeStream.CHANGE, processedChange); + } catch (error) { + this.emit(ChangeStream.ERROR, error); + } + }); + stream.on('error', error => this._processErrorStreamMode(error)); + } + + /** @internal */ + private _endStream(): void { + const cursorStream = this[kCursorStream]; + if (cursorStream) { + ['data', 'close', 'end', 'error'].forEach(event => cursorStream.removeAllListeners(event)); + cursorStream.destroy(); + } + + this[kCursorStream] = undefined; + } + + /** @internal */ + private _processChange(change: TChange | null): TChange { + if (this[kClosed]) { + // TODO(NODE-3485): Replace with MongoChangeStreamClosedError + throw new MongoAPIError(CHANGESTREAM_CLOSED_ERROR); + } + + // a null change means the cursor has been notified, implicitly closing the change stream + if (change == null) { + // TODO(NODE-3485): Replace with MongoChangeStreamClosedError + throw new MongoRuntimeError(CHANGESTREAM_CLOSED_ERROR); + } + + if (change && !change._id) { + throw new MongoChangeStreamError(NO_RESUME_TOKEN_ERROR); + } + + // cache the resume token + this.cursor.cacheResumeToken(change._id); + + // wipe the startAtOperationTime if there was one so that there won't be a conflict + // between resumeToken and startAtOperationTime if we need to reconnect the cursor + this.options.startAtOperationTime = undefined; + + return change; + } + + /** @internal */ + private _processErrorStreamMode(changeStreamError: AnyError) { + // If the change stream has been closed explicitly, do not process error. + if (this[kClosed]) return; + + if (isResumableError(changeStreamError, this.cursor.maxWireVersion)) { + this._endStream(); + this.cursor.close().catch(() => null); + + const topology = getTopology(this.parent); + topology.selectServer(this.cursor.readPreference, {}, serverSelectionError => { + if (serverSelectionError) return this._closeEmitterModeWithError(changeStreamError); + this.cursor = this._createChangeStreamCursor(this.cursor.resumeOptions); + }); + } else { + this._closeEmitterModeWithError(changeStreamError); + } + } + + /** + * @internal + * + * TODO(NODE-4320): promisify selectServer and refactor this code to be async + * + * we promisify _processErrorIteratorModeCallback until we have a promisifed version of selectServer. + */ + // eslint-disable-next-line @typescript-eslint/unbound-method + private _processErrorIteratorMode = promisify(this._processErrorIteratorModeCallback); + + /** @internal */ + private _processErrorIteratorModeCallback(changeStreamError: AnyError, callback: Callback) { + if (this[kClosed]) { + // TODO(NODE-3485): Replace with MongoChangeStreamClosedError + return callback(new MongoAPIError(CHANGESTREAM_CLOSED_ERROR)); + } + + if (isResumableError(changeStreamError, this.cursor.maxWireVersion)) { + this.cursor.close().catch(() => null); + + const topology = getTopology(this.parent); + topology.selectServer(this.cursor.readPreference, {}, serverSelectionError => { + // if the topology can't reconnect, close the stream + if (serverSelectionError) return this.close(() => callback(changeStreamError)); + + this.cursor = this._createChangeStreamCursor(this.cursor.resumeOptions); + callback(); + }); + } else { + this.close(() => callback(changeStreamError)); + } + } +} diff --git a/ts-ticket-office-service/node_modules/mongodb/src/cmap/auth/auth_provider.ts b/ts-ticket-office-service/node_modules/mongodb/src/cmap/auth/auth_provider.ts new file mode 100644 index 000000000..2a38abe9b --- /dev/null +++ b/ts-ticket-office-service/node_modules/mongodb/src/cmap/auth/auth_provider.ts @@ -0,0 +1,60 @@ +import type { Document } from '../../bson'; +import { MongoRuntimeError } from '../../error'; +import type { Callback, ClientMetadataOptions } from '../../utils'; +import type { HandshakeDocument } from '../connect'; +import type { Connection, ConnectionOptions } from '../connection'; +import type { MongoCredentials } from './mongo_credentials'; + +export type AuthContextOptions = ConnectionOptions & ClientMetadataOptions; + +/** Context used during authentication */ +export class AuthContext { + /** The connection to authenticate */ + connection: Connection; + /** The credentials to use for authentication */ + credentials?: MongoCredentials; + /** The options passed to the `connect` method */ + options: AuthContextOptions; + + /** A response from an initial auth attempt, only some mechanisms use this (e.g, SCRAM) */ + response?: Document; + /** A random nonce generated for use in an authentication conversation */ + nonce?: Buffer; + + constructor( + connection: Connection, + credentials: MongoCredentials | undefined, + options: AuthContextOptions + ) { + this.connection = connection; + this.credentials = credentials; + this.options = options; + } +} + +export class AuthProvider { + /** + * Prepare the handshake document before the initial handshake. + * + * @param handshakeDoc - The document used for the initial handshake on a connection + * @param authContext - Context for authentication flow + */ + prepare( + handshakeDoc: HandshakeDocument, + authContext: AuthContext, + callback: Callback + ): void { + callback(undefined, handshakeDoc); + } + + /** + * Authenticate + * + * @param context - A shared context for authentication flow + * @param callback - The callback to return the result from the authentication + */ + auth(context: AuthContext, callback: Callback): void { + // TODO(NODE-3483): Replace this with MongoMethodOverrideError + callback(new MongoRuntimeError('`auth` method must be overridden by subclass')); + } +} diff --git a/ts-ticket-office-service/node_modules/mongodb/src/cmap/auth/gssapi.ts b/ts-ticket-office-service/node_modules/mongodb/src/cmap/auth/gssapi.ts new file mode 100644 index 000000000..689d6e951 --- /dev/null +++ b/ts-ticket-office-service/node_modules/mongodb/src/cmap/auth/gssapi.ts @@ -0,0 +1,241 @@ +import * as dns from 'dns'; + +import type { Document } from '../../bson'; +import { Kerberos, KerberosClient } from '../../deps'; +import { + MongoError, + MongoInvalidArgumentError, + MongoMissingCredentialsError, + MongoMissingDependencyError, + MongoRuntimeError +} from '../../error'; +import { Callback, ns } from '../../utils'; +import { AuthContext, AuthProvider } from './auth_provider'; + +/** @public */ +export const GSSAPICanonicalizationValue = Object.freeze({ + on: true, + off: false, + none: 'none', + forward: 'forward', + forwardAndReverse: 'forwardAndReverse' +} as const); + +/** @public */ +export type GSSAPICanonicalizationValue = + typeof GSSAPICanonicalizationValue[keyof typeof GSSAPICanonicalizationValue]; + +type MechanismProperties = { + /** @deprecated use `CANONICALIZE_HOST_NAME` instead */ + gssapiCanonicalizeHostName?: boolean; + CANONICALIZE_HOST_NAME?: GSSAPICanonicalizationValue; + SERVICE_HOST?: string; + SERVICE_NAME?: string; + SERVICE_REALM?: string; +}; + +export class GSSAPI extends AuthProvider { + override auth(authContext: AuthContext, callback: Callback): void { + const { connection, credentials } = authContext; + if (credentials == null) + return callback( + new MongoMissingCredentialsError('Credentials required for GSSAPI authentication') + ); + const { username } = credentials; + function externalCommand( + command: Document, + cb: Callback<{ payload: string; conversationId: any }> + ) { + return connection.command(ns('$external.$cmd'), command, undefined, cb); + } + makeKerberosClient(authContext, (err, client) => { + if (err) return callback(err); + if (client == null) return callback(new MongoMissingDependencyError('GSSAPI client missing')); + client.step('', (err, payload) => { + if (err) return callback(err); + + externalCommand(saslStart(payload), (err, result) => { + if (err) return callback(err); + if (result == null) return callback(); + negotiate(client, 10, result.payload, (err, payload) => { + if (err) return callback(err); + + externalCommand(saslContinue(payload, result.conversationId), (err, result) => { + if (err) return callback(err); + if (result == null) return callback(); + finalize(client, username, result.payload, (err, payload) => { + if (err) return callback(err); + + externalCommand( + { + saslContinue: 1, + conversationId: result.conversationId, + payload + }, + (err, result) => { + if (err) return callback(err); + + callback(undefined, result); + } + ); + }); + }); + }); + }); + }); + }); + } +} + +function makeKerberosClient(authContext: AuthContext, callback: Callback): void { + const { hostAddress } = authContext.options; + const { credentials } = authContext; + if (!hostAddress || typeof hostAddress.host !== 'string' || !credentials) { + return callback( + new MongoInvalidArgumentError('Connection must have host and port and credentials defined.') + ); + } + + if ('kModuleError' in Kerberos) { + return callback(Kerberos['kModuleError']); + } + const { initializeClient } = Kerberos; + + const { username, password } = credentials; + const mechanismProperties = credentials.mechanismProperties as MechanismProperties; + + const serviceName = mechanismProperties.SERVICE_NAME ?? 'mongodb'; + + performGSSAPICanonicalizeHostName( + hostAddress.host, + mechanismProperties, + (err?: Error | MongoError, host?: string) => { + if (err) return callback(err); + + const initOptions = {}; + if (password != null) { + Object.assign(initOptions, { user: username, password: password }); + } + + const spnHost = mechanismProperties.SERVICE_HOST ?? host; + let spn = `${serviceName}${process.platform === 'win32' ? '/' : '@'}${spnHost}`; + if ('SERVICE_REALM' in mechanismProperties) { + spn = `${spn}@${mechanismProperties.SERVICE_REALM}`; + } + + initializeClient(spn, initOptions, (err: string, client: KerberosClient): void => { + // TODO(NODE-3483) + if (err) return callback(new MongoRuntimeError(err)); + callback(undefined, client); + }); + } + ); +} + +function saslStart(payload?: string): Document { + return { + saslStart: 1, + mechanism: 'GSSAPI', + payload, + autoAuthorize: 1 + }; +} + +function saslContinue(payload?: string, conversationId?: number): Document { + return { + saslContinue: 1, + conversationId, + payload + }; +} + +function negotiate( + client: KerberosClient, + retries: number, + payload: string, + callback: Callback +): void { + client.step(payload, (err, response) => { + // Retries exhausted, raise error + if (err && retries === 0) return callback(err); + + // Adjust number of retries and call step again + if (err) return negotiate(client, retries - 1, payload, callback); + + // Return the payload + callback(undefined, response || ''); + }); +} + +function finalize( + client: KerberosClient, + user: string, + payload: string, + callback: Callback +): void { + // GSS Client Unwrap + client.unwrap(payload, (err, response) => { + if (err) return callback(err); + + // Wrap the response + client.wrap(response || '', { user }, (err, wrapped) => { + if (err) return callback(err); + + // Return the payload + callback(undefined, wrapped); + }); + }); +} + +export function performGSSAPICanonicalizeHostName( + host: string, + mechanismProperties: MechanismProperties, + callback: Callback +): void { + const mode = mechanismProperties.CANONICALIZE_HOST_NAME; + if (!mode || mode === GSSAPICanonicalizationValue.none) { + return callback(undefined, host); + } + + // If forward and reverse or true + if ( + mode === GSSAPICanonicalizationValue.on || + mode === GSSAPICanonicalizationValue.forwardAndReverse + ) { + // Perform the lookup of the ip address. + dns.lookup(host, (error, address) => { + // No ip found, return the error. + if (error) return callback(error); + + // Perform a reverse ptr lookup on the ip address. + dns.resolvePtr(address, (err, results) => { + // This can error as ptr records may not exist for all ips. In this case + // fallback to a cname lookup as dns.lookup() does not return the + // cname. + if (err) { + return resolveCname(host, callback); + } + // If the ptr did not error but had no results, return the host. + callback(undefined, results.length > 0 ? results[0] : host); + }); + }); + } else { + // The case for forward is just to resolve the cname as dns.lookup() + // will not return it. + resolveCname(host, callback); + } +} + +export function resolveCname(host: string, callback: Callback): void { + // Attempt to resolve the host name + dns.resolveCname(host, (err, r) => { + if (err) return callback(undefined, host); + + // Get the first resolve host id + if (r.length > 0) { + return callback(undefined, r[0]); + } + + callback(undefined, host); + }); +} diff --git a/ts-ticket-office-service/node_modules/mongodb/src/cmap/auth/mongo_credentials.ts b/ts-ticket-office-service/node_modules/mongodb/src/cmap/auth/mongo_credentials.ts new file mode 100644 index 000000000..2c964c311 --- /dev/null +++ b/ts-ticket-office-service/node_modules/mongodb/src/cmap/auth/mongo_credentials.ts @@ -0,0 +1,190 @@ +// Resolves the default auth mechanism according to +import type { Document } from '../../bson'; +import { MongoAPIError, MongoMissingCredentialsError } from '../../error'; +import { emitWarningOnce } from '../../utils'; +import { GSSAPICanonicalizationValue } from './gssapi'; +import { AUTH_MECHS_AUTH_SRC_EXTERNAL, AuthMechanism } from './providers'; + +// https://github.com/mongodb/specifications/blob/master/source/auth/auth.rst +function getDefaultAuthMechanism(hello?: Document): AuthMechanism { + if (hello) { + // If hello contains saslSupportedMechs, use scram-sha-256 + // if it is available, else scram-sha-1 + if (Array.isArray(hello.saslSupportedMechs)) { + return hello.saslSupportedMechs.includes(AuthMechanism.MONGODB_SCRAM_SHA256) + ? AuthMechanism.MONGODB_SCRAM_SHA256 + : AuthMechanism.MONGODB_SCRAM_SHA1; + } + + // Fallback to legacy selection method. If wire version >= 3, use scram-sha-1 + if (hello.maxWireVersion >= 3) { + return AuthMechanism.MONGODB_SCRAM_SHA1; + } + } + + // Default for wireprotocol < 3 + return AuthMechanism.MONGODB_CR; +} + +/** @public */ +export interface AuthMechanismProperties extends Document { + SERVICE_HOST?: string; + SERVICE_NAME?: string; + SERVICE_REALM?: string; + CANONICALIZE_HOST_NAME?: GSSAPICanonicalizationValue; + AWS_SESSION_TOKEN?: string; +} + +/** @public */ +export interface MongoCredentialsOptions { + username: string; + password: string; + source: string; + db?: string; + mechanism?: AuthMechanism; + mechanismProperties: AuthMechanismProperties; +} + +/** + * A representation of the credentials used by MongoDB + * @public + */ +export class MongoCredentials { + /** The username used for authentication */ + readonly username: string; + /** The password used for authentication */ + readonly password: string; + /** The database that the user should authenticate against */ + readonly source: string; + /** The method used to authenticate */ + readonly mechanism: AuthMechanism; + /** Special properties used by some types of auth mechanisms */ + readonly mechanismProperties: AuthMechanismProperties; + + constructor(options: MongoCredentialsOptions) { + this.username = options.username; + this.password = options.password; + this.source = options.source; + if (!this.source && options.db) { + this.source = options.db; + } + this.mechanism = options.mechanism || AuthMechanism.MONGODB_DEFAULT; + this.mechanismProperties = options.mechanismProperties || {}; + + if (this.mechanism.match(/MONGODB-AWS/i)) { + if (!this.username && process.env.AWS_ACCESS_KEY_ID) { + this.username = process.env.AWS_ACCESS_KEY_ID; + } + + if (!this.password && process.env.AWS_SECRET_ACCESS_KEY) { + this.password = process.env.AWS_SECRET_ACCESS_KEY; + } + + if ( + this.mechanismProperties.AWS_SESSION_TOKEN == null && + process.env.AWS_SESSION_TOKEN != null + ) { + this.mechanismProperties = { + ...this.mechanismProperties, + AWS_SESSION_TOKEN: process.env.AWS_SESSION_TOKEN + }; + } + } + + if ('gssapiCanonicalizeHostName' in this.mechanismProperties) { + emitWarningOnce( + 'gssapiCanonicalizeHostName is deprecated. Please use CANONICALIZE_HOST_NAME instead.' + ); + this.mechanismProperties.CANONICALIZE_HOST_NAME = + this.mechanismProperties.gssapiCanonicalizeHostName; + } + + Object.freeze(this.mechanismProperties); + Object.freeze(this); + } + + /** Determines if two MongoCredentials objects are equivalent */ + equals(other: MongoCredentials): boolean { + return ( + this.mechanism === other.mechanism && + this.username === other.username && + this.password === other.password && + this.source === other.source + ); + } + + /** + * If the authentication mechanism is set to "default", resolves the authMechanism + * based on the server version and server supported sasl mechanisms. + * + * @param hello - A hello response from the server + */ + resolveAuthMechanism(hello?: Document): MongoCredentials { + // If the mechanism is not "default", then it does not need to be resolved + if (this.mechanism.match(/DEFAULT/i)) { + return new MongoCredentials({ + username: this.username, + password: this.password, + source: this.source, + mechanism: getDefaultAuthMechanism(hello), + mechanismProperties: this.mechanismProperties + }); + } + + return this; + } + + validate(): void { + if ( + (this.mechanism === AuthMechanism.MONGODB_GSSAPI || + this.mechanism === AuthMechanism.MONGODB_CR || + this.mechanism === AuthMechanism.MONGODB_PLAIN || + this.mechanism === AuthMechanism.MONGODB_SCRAM_SHA1 || + this.mechanism === AuthMechanism.MONGODB_SCRAM_SHA256) && + !this.username + ) { + throw new MongoMissingCredentialsError(`Username required for mechanism '${this.mechanism}'`); + } + + if (AUTH_MECHS_AUTH_SRC_EXTERNAL.has(this.mechanism)) { + if (this.source != null && this.source !== '$external') { + // TODO(NODE-3485): Replace this with a MongoAuthValidationError + throw new MongoAPIError( + `Invalid source '${this.source}' for mechanism '${this.mechanism}' specified.` + ); + } + } + + if (this.mechanism === AuthMechanism.MONGODB_PLAIN && this.source == null) { + // TODO(NODE-3485): Replace this with a MongoAuthValidationError + throw new MongoAPIError('PLAIN Authentication Mechanism needs an auth source'); + } + + if (this.mechanism === AuthMechanism.MONGODB_X509 && this.password != null) { + if (this.password === '') { + Reflect.set(this, 'password', undefined); + return; + } + // TODO(NODE-3485): Replace this with a MongoAuthValidationError + throw new MongoAPIError(`Password not allowed for mechanism MONGODB-X509`); + } + + const canonicalization = this.mechanismProperties.CANONICALIZE_HOST_NAME ?? false; + if (!Object.values(GSSAPICanonicalizationValue).includes(canonicalization)) { + throw new MongoAPIError(`Invalid CANONICALIZE_HOST_NAME value: ${canonicalization}`); + } + } + + static merge( + creds: MongoCredentials | undefined, + options: Partial + ): MongoCredentials { + return new MongoCredentials({ + username: options.username ?? creds?.username ?? '', + password: options.password ?? creds?.password ?? '', + mechanism: options.mechanism ?? creds?.mechanism ?? AuthMechanism.MONGODB_DEFAULT, + mechanismProperties: options.mechanismProperties ?? creds?.mechanismProperties ?? {}, + source: options.source ?? options.db ?? creds?.source ?? 'admin' + }); + } +} diff --git a/ts-ticket-office-service/node_modules/mongodb/src/cmap/auth/mongocr.ts b/ts-ticket-office-service/node_modules/mongodb/src/cmap/auth/mongocr.ts new file mode 100644 index 000000000..232378f0d --- /dev/null +++ b/ts-ticket-office-service/node_modules/mongodb/src/cmap/auth/mongocr.ts @@ -0,0 +1,47 @@ +import * as crypto from 'crypto'; + +import { MongoMissingCredentialsError } from '../../error'; +import { Callback, ns } from '../../utils'; +import { AuthContext, AuthProvider } from './auth_provider'; + +export class MongoCR extends AuthProvider { + override auth(authContext: AuthContext, callback: Callback): void { + const { connection, credentials } = authContext; + if (!credentials) { + return callback(new MongoMissingCredentialsError('AuthContext must provide credentials.')); + } + const username = credentials.username; + const password = credentials.password; + const source = credentials.source; + connection.command(ns(`${source}.$cmd`), { getnonce: 1 }, undefined, (err, r) => { + let nonce = null; + let key = null; + + // Get nonce + if (err == null) { + nonce = r.nonce; + + // Use node md5 generator + let md5 = crypto.createHash('md5'); + + // Generate keys used for authentication + md5.update(`${username}:mongo:${password}`, 'utf8'); + const hash_password = md5.digest('hex'); + + // Final key + md5 = crypto.createHash('md5'); + md5.update(nonce + username + hash_password, 'utf8'); + key = md5.digest('hex'); + } + + const authenticateCommand = { + authenticate: 1, + user: username, + nonce, + key + }; + + connection.command(ns(`${source}.$cmd`), authenticateCommand, undefined, callback); + }); + } +} diff --git a/ts-ticket-office-service/node_modules/mongodb/src/cmap/auth/mongodb_aws.ts b/ts-ticket-office-service/node_modules/mongodb/src/cmap/auth/mongodb_aws.ts new file mode 100644 index 000000000..3136dc879 --- /dev/null +++ b/ts-ticket-office-service/node_modules/mongodb/src/cmap/auth/mongodb_aws.ts @@ -0,0 +1,293 @@ +import * as crypto from 'crypto'; +import * as http from 'http'; +import * as url from 'url'; + +import type { Binary, BSONSerializeOptions } from '../../bson'; +import * as BSON from '../../bson'; +import { aws4 } from '../../deps'; +import { + MongoAWSError, + MongoCompatibilityError, + MongoMissingCredentialsError, + MongoRuntimeError +} from '../../error'; +import { Callback, maxWireVersion, ns } from '../../utils'; +import { AuthContext, AuthProvider } from './auth_provider'; +import { MongoCredentials } from './mongo_credentials'; +import { AuthMechanism } from './providers'; + +const ASCII_N = 110; +const AWS_RELATIVE_URI = 'http://169.254.170.2'; +const AWS_EC2_URI = 'http://169.254.169.254'; +const AWS_EC2_PATH = '/latest/meta-data/iam/security-credentials'; +const bsonOptions: BSONSerializeOptions = { + promoteLongs: true, + promoteValues: true, + promoteBuffers: false, + bsonRegExp: false +}; + +interface AWSSaslContinuePayload { + a: string; + d: string; + t?: string; +} + +export class MongoDBAWS extends AuthProvider { + override auth(authContext: AuthContext, callback: Callback): void { + const { connection, credentials } = authContext; + if (!credentials) { + return callback(new MongoMissingCredentialsError('AuthContext must provide credentials.')); + } + + if ('kModuleError' in aws4) { + return callback(aws4['kModuleError']); + } + const { sign } = aws4; + + if (maxWireVersion(connection) < 9) { + callback( + new MongoCompatibilityError( + 'MONGODB-AWS authentication requires MongoDB version 4.4 or later' + ) + ); + return; + } + + if (!credentials.username) { + makeTempCredentials(credentials, (err, tempCredentials) => { + if (err || !tempCredentials) return callback(err); + + authContext.credentials = tempCredentials; + this.auth(authContext, callback); + }); + + return; + } + + const accessKeyId = credentials.username; + const secretAccessKey = credentials.password; + const sessionToken = credentials.mechanismProperties.AWS_SESSION_TOKEN; + + // If all three defined, include sessionToken, else include username and pass, else no credentials + const awsCredentials = + accessKeyId && secretAccessKey && sessionToken + ? { accessKeyId, secretAccessKey, sessionToken } + : accessKeyId && secretAccessKey + ? { accessKeyId, secretAccessKey } + : undefined; + + const db = credentials.source; + crypto.randomBytes(32, (err, nonce) => { + if (err) { + callback(err); + return; + } + + const saslStart = { + saslStart: 1, + mechanism: 'MONGODB-AWS', + payload: BSON.serialize({ r: nonce, p: ASCII_N }, bsonOptions) + }; + + connection.command(ns(`${db}.$cmd`), saslStart, undefined, (err, res) => { + if (err) return callback(err); + + const serverResponse = BSON.deserialize(res.payload.buffer, bsonOptions) as { + s: Binary; + h: string; + }; + const host = serverResponse.h; + const serverNonce = serverResponse.s.buffer; + if (serverNonce.length !== 64) { + callback( + // TODO(NODE-3483) + new MongoRuntimeError(`Invalid server nonce length ${serverNonce.length}, expected 64`) + ); + + return; + } + + if (serverNonce.compare(nonce, 0, nonce.length, 0, nonce.length) !== 0) { + // TODO(NODE-3483) + callback(new MongoRuntimeError('Server nonce does not begin with client nonce')); + return; + } + + if (host.length < 1 || host.length > 255 || host.indexOf('..') !== -1) { + // TODO(NODE-3483) + callback(new MongoRuntimeError(`Server returned an invalid host: "${host}"`)); + return; + } + + const body = 'Action=GetCallerIdentity&Version=2011-06-15'; + const options = sign( + { + method: 'POST', + host, + region: deriveRegion(serverResponse.h), + service: 'sts', + headers: { + 'Content-Type': 'application/x-www-form-urlencoded', + 'Content-Length': body.length, + 'X-MongoDB-Server-Nonce': serverNonce.toString('base64'), + 'X-MongoDB-GS2-CB-Flag': 'n' + }, + path: '/', + body + }, + awsCredentials + ); + + const payload: AWSSaslContinuePayload = { + a: options.headers.Authorization, + d: options.headers['X-Amz-Date'] + }; + if (sessionToken) { + payload.t = sessionToken; + } + + const saslContinue = { + saslContinue: 1, + conversationId: 1, + payload: BSON.serialize(payload, bsonOptions) + }; + + connection.command(ns(`${db}.$cmd`), saslContinue, undefined, callback); + }); + }); + } +} + +interface AWSTempCredentials { + AccessKeyId?: string; + SecretAccessKey?: string; + Token?: string; + RoleArn?: string; + Expiration?: Date; +} + +function makeTempCredentials(credentials: MongoCredentials, callback: Callback) { + function done(creds: AWSTempCredentials) { + if (!creds.AccessKeyId || !creds.SecretAccessKey || !creds.Token) { + callback( + new MongoMissingCredentialsError('Could not obtain temporary MONGODB-AWS credentials') + ); + return; + } + + callback( + undefined, + new MongoCredentials({ + username: creds.AccessKeyId, + password: creds.SecretAccessKey, + source: credentials.source, + mechanism: AuthMechanism.MONGODB_AWS, + mechanismProperties: { + AWS_SESSION_TOKEN: creds.Token + } + }) + ); + } + + // If the environment variable AWS_CONTAINER_CREDENTIALS_RELATIVE_URI + // is set then drivers MUST assume that it was set by an AWS ECS agent + if (process.env.AWS_CONTAINER_CREDENTIALS_RELATIVE_URI) { + request( + `${AWS_RELATIVE_URI}${process.env.AWS_CONTAINER_CREDENTIALS_RELATIVE_URI}`, + undefined, + (err, res) => { + if (err) return callback(err); + done(res); + } + ); + + return; + } + + // Otherwise assume we are on an EC2 instance + + // get a token + request( + `${AWS_EC2_URI}/latest/api/token`, + { method: 'PUT', json: false, headers: { 'X-aws-ec2-metadata-token-ttl-seconds': 30 } }, + (err, token) => { + if (err) return callback(err); + + // get role name + request( + `${AWS_EC2_URI}/${AWS_EC2_PATH}`, + { json: false, headers: { 'X-aws-ec2-metadata-token': token } }, + (err, roleName) => { + if (err) return callback(err); + + // get temp credentials + request( + `${AWS_EC2_URI}/${AWS_EC2_PATH}/${roleName}`, + { headers: { 'X-aws-ec2-metadata-token': token } }, + (err, creds) => { + if (err) return callback(err); + done(creds); + } + ); + } + ); + } + ); +} + +function deriveRegion(host: string) { + const parts = host.split('.'); + if (parts.length === 1 || parts[1] === 'amazonaws') { + return 'us-east-1'; + } + + return parts[1]; +} + +interface RequestOptions { + json?: boolean; + method?: string; + timeout?: number; + headers?: http.OutgoingHttpHeaders; +} + +function request(uri: string, _options: RequestOptions | undefined, callback: Callback) { + const options = Object.assign( + { + method: 'GET', + timeout: 10000, + json: true + }, + url.parse(uri), + _options + ); + + const req = http.request(options, res => { + res.setEncoding('utf8'); + + let data = ''; + res.on('data', d => (data += d)); + res.on('end', () => { + if (options.json === false) { + callback(undefined, data); + return; + } + + try { + const parsed = JSON.parse(data); + callback(undefined, parsed); + } catch (err) { + // TODO(NODE-3483) + callback(new MongoRuntimeError(`Invalid JSON response: "${data}"`)); + } + }); + }); + + req.on('timeout', () => { + req.destroy(new MongoAWSError(`AWS request to ${uri} timed out after ${options.timeout} ms`)); + }); + + req.on('error', err => callback(err)); + req.end(); +} diff --git a/ts-ticket-office-service/node_modules/mongodb/src/cmap/auth/plain.ts b/ts-ticket-office-service/node_modules/mongodb/src/cmap/auth/plain.ts new file mode 100644 index 000000000..94b19a52b --- /dev/null +++ b/ts-ticket-office-service/node_modules/mongodb/src/cmap/auth/plain.ts @@ -0,0 +1,25 @@ +import { Binary } from '../../bson'; +import { MongoMissingCredentialsError } from '../../error'; +import { Callback, ns } from '../../utils'; +import { AuthContext, AuthProvider } from './auth_provider'; + +export class Plain extends AuthProvider { + override auth(authContext: AuthContext, callback: Callback): void { + const { connection, credentials } = authContext; + if (!credentials) { + return callback(new MongoMissingCredentialsError('AuthContext must provide credentials.')); + } + const username = credentials.username; + const password = credentials.password; + + const payload = new Binary(Buffer.from(`\x00${username}\x00${password}`)); + const command = { + saslStart: 1, + mechanism: 'PLAIN', + payload: payload, + autoAuthorize: 1 + }; + + connection.command(ns('$external.$cmd'), command, undefined, callback); + } +} diff --git a/ts-ticket-office-service/node_modules/mongodb/src/cmap/auth/providers.ts b/ts-ticket-office-service/node_modules/mongodb/src/cmap/auth/providers.ts new file mode 100644 index 000000000..9c7b1f4b8 --- /dev/null +++ b/ts-ticket-office-service/node_modules/mongodb/src/cmap/auth/providers.ts @@ -0,0 +1,21 @@ +/** @public */ +export const AuthMechanism = Object.freeze({ + MONGODB_AWS: 'MONGODB-AWS', + MONGODB_CR: 'MONGODB-CR', + MONGODB_DEFAULT: 'DEFAULT', + MONGODB_GSSAPI: 'GSSAPI', + MONGODB_PLAIN: 'PLAIN', + MONGODB_SCRAM_SHA1: 'SCRAM-SHA-1', + MONGODB_SCRAM_SHA256: 'SCRAM-SHA-256', + MONGODB_X509: 'MONGODB-X509' +} as const); + +/** @public */ +export type AuthMechanism = typeof AuthMechanism[keyof typeof AuthMechanism]; + +/** @internal */ +export const AUTH_MECHS_AUTH_SRC_EXTERNAL = new Set([ + AuthMechanism.MONGODB_GSSAPI, + AuthMechanism.MONGODB_AWS, + AuthMechanism.MONGODB_X509 +]); diff --git a/ts-ticket-office-service/node_modules/mongodb/src/cmap/auth/scram.ts b/ts-ticket-office-service/node_modules/mongodb/src/cmap/auth/scram.ts new file mode 100644 index 000000000..7a339151f --- /dev/null +++ b/ts-ticket-office-service/node_modules/mongodb/src/cmap/auth/scram.ts @@ -0,0 +1,384 @@ +import * as crypto from 'crypto'; + +import { Binary, Document } from '../../bson'; +import { saslprep } from '../../deps'; +import { + AnyError, + MongoInvalidArgumentError, + MongoMissingCredentialsError, + MongoRuntimeError, + MongoServerError +} from '../../error'; +import { Callback, emitWarning, ns } from '../../utils'; +import type { HandshakeDocument } from '../connect'; +import { AuthContext, AuthProvider } from './auth_provider'; +import type { MongoCredentials } from './mongo_credentials'; +import { AuthMechanism } from './providers'; + +type CryptoMethod = 'sha1' | 'sha256'; + +class ScramSHA extends AuthProvider { + cryptoMethod: CryptoMethod; + constructor(cryptoMethod: CryptoMethod) { + super(); + this.cryptoMethod = cryptoMethod || 'sha1'; + } + + override prepare(handshakeDoc: HandshakeDocument, authContext: AuthContext, callback: Callback) { + const cryptoMethod = this.cryptoMethod; + const credentials = authContext.credentials; + if (!credentials) { + return callback(new MongoMissingCredentialsError('AuthContext must provide credentials.')); + } + if (cryptoMethod === 'sha256' && saslprep == null) { + emitWarning('Warning: no saslprep library specified. Passwords will not be sanitized'); + } + + crypto.randomBytes(24, (err, nonce) => { + if (err) { + return callback(err); + } + + // store the nonce for later use + Object.assign(authContext, { nonce }); + + const request = Object.assign({}, handshakeDoc, { + speculativeAuthenticate: Object.assign(makeFirstMessage(cryptoMethod, credentials, nonce), { + db: credentials.source + }) + }); + + callback(undefined, request); + }); + } + + override auth(authContext: AuthContext, callback: Callback) { + const response = authContext.response; + if (response && response.speculativeAuthenticate) { + continueScramConversation( + this.cryptoMethod, + response.speculativeAuthenticate, + authContext, + callback + ); + + return; + } + + executeScram(this.cryptoMethod, authContext, callback); + } +} + +function cleanUsername(username: string) { + return username.replace('=', '=3D').replace(',', '=2C'); +} + +function clientFirstMessageBare(username: string, nonce: Buffer) { + // NOTE: This is done b/c Javascript uses UTF-16, but the server is hashing in UTF-8. + // Since the username is not sasl-prep-d, we need to do this here. + return Buffer.concat([ + Buffer.from('n=', 'utf8'), + Buffer.from(username, 'utf8'), + Buffer.from(',r=', 'utf8'), + Buffer.from(nonce.toString('base64'), 'utf8') + ]); +} + +function makeFirstMessage( + cryptoMethod: CryptoMethod, + credentials: MongoCredentials, + nonce: Buffer +) { + const username = cleanUsername(credentials.username); + const mechanism = + cryptoMethod === 'sha1' ? AuthMechanism.MONGODB_SCRAM_SHA1 : AuthMechanism.MONGODB_SCRAM_SHA256; + + // NOTE: This is done b/c Javascript uses UTF-16, but the server is hashing in UTF-8. + // Since the username is not sasl-prep-d, we need to do this here. + return { + saslStart: 1, + mechanism, + payload: new Binary( + Buffer.concat([Buffer.from('n,,', 'utf8'), clientFirstMessageBare(username, nonce)]) + ), + autoAuthorize: 1, + options: { skipEmptyExchange: true } + }; +} + +function executeScram(cryptoMethod: CryptoMethod, authContext: AuthContext, callback: Callback) { + const { connection, credentials } = authContext; + if (!credentials) { + return callback(new MongoMissingCredentialsError('AuthContext must provide credentials.')); + } + if (!authContext.nonce) { + return callback( + new MongoInvalidArgumentError('AuthContext must contain a valid nonce property') + ); + } + const nonce = authContext.nonce; + const db = credentials.source; + + const saslStartCmd = makeFirstMessage(cryptoMethod, credentials, nonce); + connection.command(ns(`${db}.$cmd`), saslStartCmd, undefined, (_err, result) => { + const err = resolveError(_err, result); + if (err) { + return callback(err); + } + + continueScramConversation(cryptoMethod, result, authContext, callback); + }); +} + +function continueScramConversation( + cryptoMethod: CryptoMethod, + response: Document, + authContext: AuthContext, + callback: Callback +) { + const connection = authContext.connection; + const credentials = authContext.credentials; + if (!credentials) { + return callback(new MongoMissingCredentialsError('AuthContext must provide credentials.')); + } + if (!authContext.nonce) { + return callback(new MongoInvalidArgumentError('Unable to continue SCRAM without valid nonce')); + } + const nonce = authContext.nonce; + + const db = credentials.source; + const username = cleanUsername(credentials.username); + const password = credentials.password; + + let processedPassword; + if (cryptoMethod === 'sha256') { + processedPassword = 'kModuleError' in saslprep ? password : saslprep(password); + } else { + try { + processedPassword = passwordDigest(username, password); + } catch (e) { + return callback(e); + } + } + + const payload = Buffer.isBuffer(response.payload) + ? new Binary(response.payload) + : response.payload; + const dict = parsePayload(payload.value()); + + const iterations = parseInt(dict.i, 10); + if (iterations && iterations < 4096) { + callback( + // TODO(NODE-3483) + new MongoRuntimeError(`Server returned an invalid iteration count ${iterations}`), + false + ); + return; + } + + const salt = dict.s; + const rnonce = dict.r; + if (rnonce.startsWith('nonce')) { + // TODO(NODE-3483) + callback(new MongoRuntimeError(`Server returned an invalid nonce: ${rnonce}`), false); + return; + } + + // Set up start of proof + const withoutProof = `c=biws,r=${rnonce}`; + const saltedPassword = HI( + processedPassword, + Buffer.from(salt, 'base64'), + iterations, + cryptoMethod + ); + + const clientKey = HMAC(cryptoMethod, saltedPassword, 'Client Key'); + const serverKey = HMAC(cryptoMethod, saltedPassword, 'Server Key'); + const storedKey = H(cryptoMethod, clientKey); + const authMessage = [clientFirstMessageBare(username, nonce), payload.value(), withoutProof].join( + ',' + ); + + const clientSignature = HMAC(cryptoMethod, storedKey, authMessage); + const clientProof = `p=${xor(clientKey, clientSignature)}`; + const clientFinal = [withoutProof, clientProof].join(','); + + const serverSignature = HMAC(cryptoMethod, serverKey, authMessage); + const saslContinueCmd = { + saslContinue: 1, + conversationId: response.conversationId, + payload: new Binary(Buffer.from(clientFinal)) + }; + + connection.command(ns(`${db}.$cmd`), saslContinueCmd, undefined, (_err, r) => { + const err = resolveError(_err, r); + if (err) { + return callback(err); + } + + const parsedResponse = parsePayload(r.payload.value()); + if (!compareDigest(Buffer.from(parsedResponse.v, 'base64'), serverSignature)) { + callback(new MongoRuntimeError('Server returned an invalid signature')); + return; + } + + if (!r || r.done !== false) { + return callback(err, r); + } + + const retrySaslContinueCmd = { + saslContinue: 1, + conversationId: r.conversationId, + payload: Buffer.alloc(0) + }; + + connection.command(ns(`${db}.$cmd`), retrySaslContinueCmd, undefined, callback); + }); +} + +function parsePayload(payload: string) { + const dict: Document = {}; + const parts = payload.split(','); + for (let i = 0; i < parts.length; i++) { + const valueParts = parts[i].split('='); + dict[valueParts[0]] = valueParts[1]; + } + + return dict; +} + +function passwordDigest(username: string, password: string) { + if (typeof username !== 'string') { + throw new MongoInvalidArgumentError('Username must be a string'); + } + + if (typeof password !== 'string') { + throw new MongoInvalidArgumentError('Password must be a string'); + } + + if (password.length === 0) { + throw new MongoInvalidArgumentError('Password cannot be empty'); + } + + let md5: crypto.Hash; + try { + md5 = crypto.createHash('md5'); + } catch (err) { + if (crypto.getFips()) { + // This error is (slightly) more helpful than what comes from OpenSSL directly, e.g. + // 'Error: error:060800C8:digital envelope routines:EVP_DigestInit_ex:disabled for FIPS' + throw new Error('Auth mechanism SCRAM-SHA-1 is not supported in FIPS mode'); + } + throw err; + } + md5.update(`${username}:mongo:${password}`, 'utf8'); + return md5.digest('hex'); +} + +// XOR two buffers +function xor(a: Buffer, b: Buffer) { + if (!Buffer.isBuffer(a)) { + a = Buffer.from(a); + } + + if (!Buffer.isBuffer(b)) { + b = Buffer.from(b); + } + + const length = Math.max(a.length, b.length); + const res = []; + + for (let i = 0; i < length; i += 1) { + res.push(a[i] ^ b[i]); + } + + return Buffer.from(res).toString('base64'); +} + +function H(method: CryptoMethod, text: Buffer) { + return crypto.createHash(method).update(text).digest(); +} + +function HMAC(method: CryptoMethod, key: Buffer, text: Buffer | string) { + return crypto.createHmac(method, key).update(text).digest(); +} + +interface HICache { + [key: string]: Buffer; +} + +let _hiCache: HICache = {}; +let _hiCacheCount = 0; +function _hiCachePurge() { + _hiCache = {}; + _hiCacheCount = 0; +} + +const hiLengthMap = { + sha256: 32, + sha1: 20 +}; + +function HI(data: string, salt: Buffer, iterations: number, cryptoMethod: CryptoMethod) { + // omit the work if already generated + const key = [data, salt.toString('base64'), iterations].join('_'); + if (_hiCache[key] != null) { + return _hiCache[key]; + } + + // generate the salt + const saltedData = crypto.pbkdf2Sync( + data, + salt, + iterations, + hiLengthMap[cryptoMethod], + cryptoMethod + ); + + // cache a copy to speed up the next lookup, but prevent unbounded cache growth + if (_hiCacheCount >= 200) { + _hiCachePurge(); + } + + _hiCache[key] = saltedData; + _hiCacheCount += 1; + return saltedData; +} + +function compareDigest(lhs: Buffer, rhs: Uint8Array) { + if (lhs.length !== rhs.length) { + return false; + } + + if (typeof crypto.timingSafeEqual === 'function') { + return crypto.timingSafeEqual(lhs, rhs); + } + + let result = 0; + for (let i = 0; i < lhs.length; i++) { + result |= lhs[i] ^ rhs[i]; + } + + return result === 0; +} + +function resolveError(err?: AnyError, result?: Document) { + if (err) return err; + if (result) { + if (result.$err || result.errmsg) return new MongoServerError(result); + } + return; +} + +export class ScramSHA1 extends ScramSHA { + constructor() { + super('sha1'); + } +} + +export class ScramSHA256 extends ScramSHA { + constructor() { + super('sha256'); + } +} diff --git a/ts-ticket-office-service/node_modules/mongodb/src/cmap/auth/x509.ts b/ts-ticket-office-service/node_modules/mongodb/src/cmap/auth/x509.ts new file mode 100644 index 000000000..a12e6f9d8 --- /dev/null +++ b/ts-ticket-office-service/node_modules/mongodb/src/cmap/auth/x509.ts @@ -0,0 +1,53 @@ +import type { Document } from '../../bson'; +import { MongoMissingCredentialsError } from '../../error'; +import { Callback, ns } from '../../utils'; +import type { HandshakeDocument } from '../connect'; +import { AuthContext, AuthProvider } from './auth_provider'; +import type { MongoCredentials } from './mongo_credentials'; + +export class X509 extends AuthProvider { + override prepare( + handshakeDoc: HandshakeDocument, + authContext: AuthContext, + callback: Callback + ): void { + const { credentials } = authContext; + if (!credentials) { + return callback(new MongoMissingCredentialsError('AuthContext must provide credentials.')); + } + Object.assign(handshakeDoc, { + speculativeAuthenticate: x509AuthenticateCommand(credentials) + }); + + callback(undefined, handshakeDoc); + } + + override auth(authContext: AuthContext, callback: Callback): void { + const connection = authContext.connection; + const credentials = authContext.credentials; + if (!credentials) { + return callback(new MongoMissingCredentialsError('AuthContext must provide credentials.')); + } + const response = authContext.response; + + if (response && response.speculativeAuthenticate) { + return callback(); + } + + connection.command( + ns('$external.$cmd'), + x509AuthenticateCommand(credentials), + undefined, + callback + ); + } +} + +function x509AuthenticateCommand(credentials: MongoCredentials) { + const command: Document = { authenticate: 1, mechanism: 'MONGODB-X509' }; + if (credentials.username) { + command.user = credentials.username; + } + + return command; +} diff --git a/ts-ticket-office-service/node_modules/mongodb/src/cmap/command_monitoring_events.ts b/ts-ticket-office-service/node_modules/mongodb/src/cmap/command_monitoring_events.ts new file mode 100644 index 000000000..6cd480568 --- /dev/null +++ b/ts-ticket-office-service/node_modules/mongodb/src/cmap/command_monitoring_events.ts @@ -0,0 +1,334 @@ +import type { Document, ObjectId } from '../bson'; +import { LEGACY_HELLO_COMMAND, LEGACY_HELLO_COMMAND_CAMEL_CASE } from '../constants'; +import { calculateDurationInMs, deepCopy } from '../utils'; +import { GetMore, KillCursor, Msg, WriteProtocolMessageType } from './commands'; +import type { Connection } from './connection'; + +/** + * An event indicating the start of a given + * @public + * @category Event + */ +export class CommandStartedEvent { + commandObj?: Document; + requestId: number; + databaseName: string; + commandName: string; + command: Document; + address: string; + connectionId?: string | number; + serviceId?: ObjectId; + + /** + * Create a started event + * + * @internal + * @param pool - the pool that originated the command + * @param command - the command + */ + constructor(connection: Connection, command: WriteProtocolMessageType) { + const cmd = extractCommand(command); + const commandName = extractCommandName(cmd); + const { address, connectionId, serviceId } = extractConnectionDetails(connection); + + // TODO: remove in major revision, this is not spec behavior + if (SENSITIVE_COMMANDS.has(commandName)) { + this.commandObj = {}; + this.commandObj[commandName] = true; + } + + this.address = address; + this.connectionId = connectionId; + this.serviceId = serviceId; + this.requestId = command.requestId; + this.databaseName = databaseName(command); + this.commandName = commandName; + this.command = maybeRedact(commandName, cmd, cmd); + } + + /* @internal */ + get hasServiceId(): boolean { + return !!this.serviceId; + } +} + +/** + * An event indicating the success of a given command + * @public + * @category Event + */ +export class CommandSucceededEvent { + address: string; + connectionId?: string | number; + requestId: number; + duration: number; + commandName: string; + reply: unknown; + serviceId?: ObjectId; + + /** + * Create a succeeded event + * + * @internal + * @param pool - the pool that originated the command + * @param command - the command + * @param reply - the reply for this command from the server + * @param started - a high resolution tuple timestamp of when the command was first sent, to calculate duration + */ + constructor( + connection: Connection, + command: WriteProtocolMessageType, + reply: Document | undefined, + started: number + ) { + const cmd = extractCommand(command); + const commandName = extractCommandName(cmd); + const { address, connectionId, serviceId } = extractConnectionDetails(connection); + + this.address = address; + this.connectionId = connectionId; + this.serviceId = serviceId; + this.requestId = command.requestId; + this.commandName = commandName; + this.duration = calculateDurationInMs(started); + this.reply = maybeRedact(commandName, cmd, extractReply(command, reply)); + } + + /* @internal */ + get hasServiceId(): boolean { + return !!this.serviceId; + } +} + +/** + * An event indicating the failure of a given command + * @public + * @category Event + */ +export class CommandFailedEvent { + address: string; + connectionId?: string | number; + requestId: number; + duration: number; + commandName: string; + failure: Error; + serviceId?: ObjectId; + + /** + * Create a failure event + * + * @internal + * @param pool - the pool that originated the command + * @param command - the command + * @param error - the generated error or a server error response + * @param started - a high resolution tuple timestamp of when the command was first sent, to calculate duration + */ + constructor( + connection: Connection, + command: WriteProtocolMessageType, + error: Error | Document, + started: number + ) { + const cmd = extractCommand(command); + const commandName = extractCommandName(cmd); + const { address, connectionId, serviceId } = extractConnectionDetails(connection); + + this.address = address; + this.connectionId = connectionId; + this.serviceId = serviceId; + + this.requestId = command.requestId; + this.commandName = commandName; + this.duration = calculateDurationInMs(started); + this.failure = maybeRedact(commandName, cmd, error) as Error; + } + + /* @internal */ + get hasServiceId(): boolean { + return !!this.serviceId; + } +} + +/** Commands that we want to redact because of the sensitive nature of their contents */ +const SENSITIVE_COMMANDS = new Set([ + 'authenticate', + 'saslStart', + 'saslContinue', + 'getnonce', + 'createUser', + 'updateUser', + 'copydbgetnonce', + 'copydbsaslstart', + 'copydb' +]); + +const HELLO_COMMANDS = new Set(['hello', LEGACY_HELLO_COMMAND, LEGACY_HELLO_COMMAND_CAMEL_CASE]); + +// helper methods +const extractCommandName = (commandDoc: Document) => Object.keys(commandDoc)[0]; +const namespace = (command: WriteProtocolMessageType) => command.ns; +const databaseName = (command: WriteProtocolMessageType) => command.ns.split('.')[0]; +const collectionName = (command: WriteProtocolMessageType) => command.ns.split('.')[1]; +const maybeRedact = (commandName: string, commandDoc: Document, result: Error | Document) => + SENSITIVE_COMMANDS.has(commandName) || + (HELLO_COMMANDS.has(commandName) && commandDoc.speculativeAuthenticate) + ? {} + : result; + +const LEGACY_FIND_QUERY_MAP: { [key: string]: string } = { + $query: 'filter', + $orderby: 'sort', + $hint: 'hint', + $comment: 'comment', + $maxScan: 'maxScan', + $max: 'max', + $min: 'min', + $returnKey: 'returnKey', + $showDiskLoc: 'showRecordId', + $maxTimeMS: 'maxTimeMS', + $snapshot: 'snapshot' +}; + +const LEGACY_FIND_OPTIONS_MAP = { + numberToSkip: 'skip', + numberToReturn: 'batchSize', + returnFieldSelector: 'projection' +} as const; + +const OP_QUERY_KEYS = [ + 'tailable', + 'oplogReplay', + 'noCursorTimeout', + 'awaitData', + 'partial', + 'exhaust' +] as const; + +/** Extract the actual command from the query, possibly up-converting if it's a legacy format */ +function extractCommand(command: WriteProtocolMessageType): Document { + if (command instanceof GetMore) { + return { + getMore: deepCopy(command.cursorId), + collection: collectionName(command), + batchSize: command.numberToReturn + }; + } + + if (command instanceof KillCursor) { + return { + killCursors: collectionName(command), + cursors: deepCopy(command.cursorIds) + }; + } + + if (command instanceof Msg) { + return deepCopy(command.command); + } + + if (command.query?.$query) { + let result: Document; + if (command.ns === 'admin.$cmd') { + // up-convert legacy command + result = Object.assign({}, command.query.$query); + } else { + // up-convert legacy find command + result = { find: collectionName(command) }; + Object.keys(LEGACY_FIND_QUERY_MAP).forEach(key => { + if (command.query[key] != null) { + result[LEGACY_FIND_QUERY_MAP[key]] = deepCopy(command.query[key]); + } + }); + } + + Object.keys(LEGACY_FIND_OPTIONS_MAP).forEach(key => { + const legacyKey = key as keyof typeof LEGACY_FIND_OPTIONS_MAP; + if (command[legacyKey] != null) { + result[LEGACY_FIND_OPTIONS_MAP[legacyKey]] = deepCopy(command[legacyKey]); + } + }); + + OP_QUERY_KEYS.forEach(key => { + if (command[key]) { + result[key] = command[key]; + } + }); + + if (command.pre32Limit != null) { + result.limit = command.pre32Limit; + } + + if (command.query.$explain) { + return { explain: result }; + } + return result; + } + + const clonedQuery: Record = {}; + const clonedCommand: Record = {}; + if (command.query) { + for (const k in command.query) { + clonedQuery[k] = deepCopy(command.query[k]); + } + clonedCommand.query = clonedQuery; + } + + for (const k in command) { + if (k === 'query') continue; + clonedCommand[k] = deepCopy((command as unknown as Record)[k]); + } + return command.query ? clonedQuery : clonedCommand; +} + +function extractReply(command: WriteProtocolMessageType, reply?: Document) { + if (command instanceof KillCursor) { + return { + ok: 1, + cursorsUnknown: command.cursorIds + }; + } + + if (!reply) { + return reply; + } + + if (command instanceof GetMore) { + return { + ok: 1, + cursor: { + id: deepCopy(reply.cursorId), + ns: namespace(command), + nextBatch: deepCopy(reply.documents) + } + }; + } + + if (command instanceof Msg) { + return deepCopy(reply.result ? reply.result : reply); + } + + // is this a legacy find command? + if (command.query && command.query.$query != null) { + return { + ok: 1, + cursor: { + id: deepCopy(reply.cursorId), + ns: namespace(command), + firstBatch: deepCopy(reply.documents) + } + }; + } + + return deepCopy(reply.result ? reply.result : reply); +} + +function extractConnectionDetails(connection: Connection) { + let connectionId; + if ('id' in connection) { + connectionId = connection.id; + } + return { + address: connection.address, + serviceId: connection.serviceId, + connectionId + }; +} diff --git a/ts-ticket-office-service/node_modules/mongodb/src/cmap/commands.ts b/ts-ticket-office-service/node_modules/mongodb/src/cmap/commands.ts new file mode 100644 index 000000000..a49d18431 --- /dev/null +++ b/ts-ticket-office-service/node_modules/mongodb/src/cmap/commands.ts @@ -0,0 +1,891 @@ +import type { BSONSerializeOptions, Document, Long } from '../bson'; +import * as BSON from '../bson'; +import { MongoInvalidArgumentError, MongoRuntimeError } from '../error'; +import { ReadPreference } from '../read_preference'; +import type { ClientSession } from '../sessions'; +import { databaseNamespace } from '../utils'; +import type { CommandOptions } from './connection'; +import { OP_GETMORE, OP_KILL_CURSORS, OP_MSG, OP_QUERY } from './wire_protocol/constants'; + +// Incrementing request id +let _requestId = 0; + +// Query flags +const OPTS_TAILABLE_CURSOR = 2; +const OPTS_SECONDARY = 4; +const OPTS_OPLOG_REPLAY = 8; +const OPTS_NO_CURSOR_TIMEOUT = 16; +const OPTS_AWAIT_DATA = 32; +const OPTS_EXHAUST = 64; +const OPTS_PARTIAL = 128; + +// Response flags +const CURSOR_NOT_FOUND = 1; +const QUERY_FAILURE = 2; +const SHARD_CONFIG_STALE = 4; +const AWAIT_CAPABLE = 8; + +/** @internal */ +export type WriteProtocolMessageType = Query | Msg | GetMore | KillCursor; + +/** @internal */ +export interface OpQueryOptions extends CommandOptions { + socketTimeoutMS?: number; + session?: ClientSession; + documentsReturnedIn?: string; + numberToSkip?: number; + numberToReturn?: number; + returnFieldSelector?: Document; + pre32Limit?: number; + serializeFunctions?: boolean; + ignoreUndefined?: boolean; + maxBsonSize?: number; + checkKeys?: boolean; + secondaryOk?: boolean; + + requestId?: number; + moreToCome?: boolean; + exhaustAllowed?: boolean; + readPreference?: ReadPreference; +} + +/************************************************************** + * QUERY + **************************************************************/ +/** @internal */ +export class Query { + ns: string; + query: Document; + numberToSkip: number; + numberToReturn: number; + returnFieldSelector?: Document; + requestId: number; + pre32Limit?: number; + serializeFunctions: boolean; + ignoreUndefined: boolean; + maxBsonSize: number; + checkKeys: boolean; + batchSize: number; + tailable: boolean; + secondaryOk: boolean; + oplogReplay: boolean; + noCursorTimeout: boolean; + awaitData: boolean; + exhaust: boolean; + partial: boolean; + documentsReturnedIn?: string; + + constructor(ns: string, query: Document, options: OpQueryOptions) { + // Basic options needed to be passed in + // TODO(NODE-3483): Replace with MongoCommandError + if (ns == null) throw new MongoRuntimeError('Namespace must be specified for query'); + // TODO(NODE-3483): Replace with MongoCommandError + if (query == null) throw new MongoRuntimeError('A query document must be specified for query'); + + // Validate that we are not passing 0x00 in the collection name + if (ns.indexOf('\x00') !== -1) { + // TODO(NODE-3483): Use MongoNamespace static method + throw new MongoRuntimeError('Namespace cannot contain a null character'); + } + + // Basic options + this.ns = ns; + this.query = query; + + // Additional options + this.numberToSkip = options.numberToSkip || 0; + this.numberToReturn = options.numberToReturn || 0; + this.returnFieldSelector = options.returnFieldSelector || undefined; + this.requestId = Query.getRequestId(); + + // special case for pre-3.2 find commands, delete ASAP + this.pre32Limit = options.pre32Limit; + + // Serialization option + this.serializeFunctions = + typeof options.serializeFunctions === 'boolean' ? options.serializeFunctions : false; + this.ignoreUndefined = + typeof options.ignoreUndefined === 'boolean' ? options.ignoreUndefined : false; + this.maxBsonSize = options.maxBsonSize || 1024 * 1024 * 16; + this.checkKeys = typeof options.checkKeys === 'boolean' ? options.checkKeys : false; + this.batchSize = this.numberToReturn; + + // Flags + this.tailable = false; + this.secondaryOk = typeof options.secondaryOk === 'boolean' ? options.secondaryOk : false; + this.oplogReplay = false; + this.noCursorTimeout = false; + this.awaitData = false; + this.exhaust = false; + this.partial = false; + } + + /** Assign next request Id. */ + incRequestId(): void { + this.requestId = _requestId++; + } + + /** Peek next request Id. */ + nextRequestId(): number { + return _requestId + 1; + } + + /** Increment then return next request Id. */ + static getRequestId(): number { + return ++_requestId; + } + + // Uses a single allocated buffer for the process, avoiding multiple memory allocations + toBin(): Buffer[] { + const buffers = []; + let projection = null; + + // Set up the flags + let flags = 0; + if (this.tailable) { + flags |= OPTS_TAILABLE_CURSOR; + } + + if (this.secondaryOk) { + flags |= OPTS_SECONDARY; + } + + if (this.oplogReplay) { + flags |= OPTS_OPLOG_REPLAY; + } + + if (this.noCursorTimeout) { + flags |= OPTS_NO_CURSOR_TIMEOUT; + } + + if (this.awaitData) { + flags |= OPTS_AWAIT_DATA; + } + + if (this.exhaust) { + flags |= OPTS_EXHAUST; + } + + if (this.partial) { + flags |= OPTS_PARTIAL; + } + + // If batchSize is different to this.numberToReturn + if (this.batchSize !== this.numberToReturn) this.numberToReturn = this.batchSize; + + // Allocate write protocol header buffer + const header = Buffer.alloc( + 4 * 4 + // Header + 4 + // Flags + Buffer.byteLength(this.ns) + + 1 + // namespace + 4 + // numberToSkip + 4 // numberToReturn + ); + + // Add header to buffers + buffers.push(header); + + // Serialize the query + const query = BSON.serialize(this.query, { + checkKeys: this.checkKeys, + serializeFunctions: this.serializeFunctions, + ignoreUndefined: this.ignoreUndefined + }); + + // Add query document + buffers.push(query); + + if (this.returnFieldSelector && Object.keys(this.returnFieldSelector).length > 0) { + // Serialize the projection document + projection = BSON.serialize(this.returnFieldSelector, { + checkKeys: this.checkKeys, + serializeFunctions: this.serializeFunctions, + ignoreUndefined: this.ignoreUndefined + }); + // Add projection document + buffers.push(projection); + } + + // Total message size + const totalLength = header.length + query.length + (projection ? projection.length : 0); + + // Set up the index + let index = 4; + + // Write total document length + header[3] = (totalLength >> 24) & 0xff; + header[2] = (totalLength >> 16) & 0xff; + header[1] = (totalLength >> 8) & 0xff; + header[0] = totalLength & 0xff; + + // Write header information requestId + header[index + 3] = (this.requestId >> 24) & 0xff; + header[index + 2] = (this.requestId >> 16) & 0xff; + header[index + 1] = (this.requestId >> 8) & 0xff; + header[index] = this.requestId & 0xff; + index = index + 4; + + // Write header information responseTo + header[index + 3] = (0 >> 24) & 0xff; + header[index + 2] = (0 >> 16) & 0xff; + header[index + 1] = (0 >> 8) & 0xff; + header[index] = 0 & 0xff; + index = index + 4; + + // Write header information OP_QUERY + header[index + 3] = (OP_QUERY >> 24) & 0xff; + header[index + 2] = (OP_QUERY >> 16) & 0xff; + header[index + 1] = (OP_QUERY >> 8) & 0xff; + header[index] = OP_QUERY & 0xff; + index = index + 4; + + // Write header information flags + header[index + 3] = (flags >> 24) & 0xff; + header[index + 2] = (flags >> 16) & 0xff; + header[index + 1] = (flags >> 8) & 0xff; + header[index] = flags & 0xff; + index = index + 4; + + // Write collection name + index = index + header.write(this.ns, index, 'utf8') + 1; + header[index - 1] = 0; + + // Write header information flags numberToSkip + header[index + 3] = (this.numberToSkip >> 24) & 0xff; + header[index + 2] = (this.numberToSkip >> 16) & 0xff; + header[index + 1] = (this.numberToSkip >> 8) & 0xff; + header[index] = this.numberToSkip & 0xff; + index = index + 4; + + // Write header information flags numberToReturn + header[index + 3] = (this.numberToReturn >> 24) & 0xff; + header[index + 2] = (this.numberToReturn >> 16) & 0xff; + header[index + 1] = (this.numberToReturn >> 8) & 0xff; + header[index] = this.numberToReturn & 0xff; + index = index + 4; + + // Return the buffers + return buffers; + } +} + +/** @internal */ +export interface OpGetMoreOptions { + numberToReturn?: number; +} + +/************************************************************** + * GETMORE + **************************************************************/ +/** @internal */ +export class GetMore { + numberToReturn: number; + requestId: number; + ns: string; + cursorId: Long; + + constructor(ns: string, cursorId: Long, opts: OpGetMoreOptions = {}) { + this.numberToReturn = opts.numberToReturn || 0; + this.requestId = _requestId++; + this.ns = ns; + this.cursorId = cursorId; + } + + // Uses a single allocated buffer for the process, avoiding multiple memory allocations + toBin(): Buffer[] { + const length = 4 + Buffer.byteLength(this.ns) + 1 + 4 + 8 + 4 * 4; + // Create command buffer + let index = 0; + // Allocate buffer + const _buffer = Buffer.alloc(length); + + // Write header information + // index = write32bit(index, _buffer, length); + _buffer[index + 3] = (length >> 24) & 0xff; + _buffer[index + 2] = (length >> 16) & 0xff; + _buffer[index + 1] = (length >> 8) & 0xff; + _buffer[index] = length & 0xff; + index = index + 4; + + // index = write32bit(index, _buffer, requestId); + _buffer[index + 3] = (this.requestId >> 24) & 0xff; + _buffer[index + 2] = (this.requestId >> 16) & 0xff; + _buffer[index + 1] = (this.requestId >> 8) & 0xff; + _buffer[index] = this.requestId & 0xff; + index = index + 4; + + // index = write32bit(index, _buffer, 0); + _buffer[index + 3] = (0 >> 24) & 0xff; + _buffer[index + 2] = (0 >> 16) & 0xff; + _buffer[index + 1] = (0 >> 8) & 0xff; + _buffer[index] = 0 & 0xff; + index = index + 4; + + // index = write32bit(index, _buffer, OP_GETMORE); + _buffer[index + 3] = (OP_GETMORE >> 24) & 0xff; + _buffer[index + 2] = (OP_GETMORE >> 16) & 0xff; + _buffer[index + 1] = (OP_GETMORE >> 8) & 0xff; + _buffer[index] = OP_GETMORE & 0xff; + index = index + 4; + + // index = write32bit(index, _buffer, 0); + _buffer[index + 3] = (0 >> 24) & 0xff; + _buffer[index + 2] = (0 >> 16) & 0xff; + _buffer[index + 1] = (0 >> 8) & 0xff; + _buffer[index] = 0 & 0xff; + index = index + 4; + + // Write collection name + index = index + _buffer.write(this.ns, index, 'utf8') + 1; + _buffer[index - 1] = 0; + + // Write batch size + // index = write32bit(index, _buffer, numberToReturn); + _buffer[index + 3] = (this.numberToReturn >> 24) & 0xff; + _buffer[index + 2] = (this.numberToReturn >> 16) & 0xff; + _buffer[index + 1] = (this.numberToReturn >> 8) & 0xff; + _buffer[index] = this.numberToReturn & 0xff; + index = index + 4; + + // Write cursor id + // index = write32bit(index, _buffer, cursorId.getLowBits()); + _buffer[index + 3] = (this.cursorId.getLowBits() >> 24) & 0xff; + _buffer[index + 2] = (this.cursorId.getLowBits() >> 16) & 0xff; + _buffer[index + 1] = (this.cursorId.getLowBits() >> 8) & 0xff; + _buffer[index] = this.cursorId.getLowBits() & 0xff; + index = index + 4; + + // index = write32bit(index, _buffer, cursorId.getHighBits()); + _buffer[index + 3] = (this.cursorId.getHighBits() >> 24) & 0xff; + _buffer[index + 2] = (this.cursorId.getHighBits() >> 16) & 0xff; + _buffer[index + 1] = (this.cursorId.getHighBits() >> 8) & 0xff; + _buffer[index] = this.cursorId.getHighBits() & 0xff; + index = index + 4; + + // Return buffer + return [_buffer]; + } +} + +/************************************************************** + * KILLCURSOR + **************************************************************/ +/** @internal */ +export class KillCursor { + ns: string; + requestId: number; + cursorIds: Long[]; + + constructor(ns: string, cursorIds: Long[]) { + this.ns = ns; + this.requestId = _requestId++; + this.cursorIds = cursorIds; + } + + // Uses a single allocated buffer for the process, avoiding multiple memory allocations + toBin(): Buffer[] { + const length = 4 + 4 + 4 * 4 + this.cursorIds.length * 8; + + // Create command buffer + let index = 0; + const _buffer = Buffer.alloc(length); + + // Write header information + // index = write32bit(index, _buffer, length); + _buffer[index + 3] = (length >> 24) & 0xff; + _buffer[index + 2] = (length >> 16) & 0xff; + _buffer[index + 1] = (length >> 8) & 0xff; + _buffer[index] = length & 0xff; + index = index + 4; + + // index = write32bit(index, _buffer, requestId); + _buffer[index + 3] = (this.requestId >> 24) & 0xff; + _buffer[index + 2] = (this.requestId >> 16) & 0xff; + _buffer[index + 1] = (this.requestId >> 8) & 0xff; + _buffer[index] = this.requestId & 0xff; + index = index + 4; + + // index = write32bit(index, _buffer, 0); + _buffer[index + 3] = (0 >> 24) & 0xff; + _buffer[index + 2] = (0 >> 16) & 0xff; + _buffer[index + 1] = (0 >> 8) & 0xff; + _buffer[index] = 0 & 0xff; + index = index + 4; + + // index = write32bit(index, _buffer, OP_KILL_CURSORS); + _buffer[index + 3] = (OP_KILL_CURSORS >> 24) & 0xff; + _buffer[index + 2] = (OP_KILL_CURSORS >> 16) & 0xff; + _buffer[index + 1] = (OP_KILL_CURSORS >> 8) & 0xff; + _buffer[index] = OP_KILL_CURSORS & 0xff; + index = index + 4; + + // index = write32bit(index, _buffer, 0); + _buffer[index + 3] = (0 >> 24) & 0xff; + _buffer[index + 2] = (0 >> 16) & 0xff; + _buffer[index + 1] = (0 >> 8) & 0xff; + _buffer[index] = 0 & 0xff; + index = index + 4; + + // Write batch size + // index = write32bit(index, _buffer, this.cursorIds.length); + _buffer[index + 3] = (this.cursorIds.length >> 24) & 0xff; + _buffer[index + 2] = (this.cursorIds.length >> 16) & 0xff; + _buffer[index + 1] = (this.cursorIds.length >> 8) & 0xff; + _buffer[index] = this.cursorIds.length & 0xff; + index = index + 4; + + // Write all the cursor ids into the array + for (let i = 0; i < this.cursorIds.length; i++) { + // Write cursor id + // index = write32bit(index, _buffer, cursorIds[i].getLowBits()); + _buffer[index + 3] = (this.cursorIds[i].getLowBits() >> 24) & 0xff; + _buffer[index + 2] = (this.cursorIds[i].getLowBits() >> 16) & 0xff; + _buffer[index + 1] = (this.cursorIds[i].getLowBits() >> 8) & 0xff; + _buffer[index] = this.cursorIds[i].getLowBits() & 0xff; + index = index + 4; + + // index = write32bit(index, _buffer, cursorIds[i].getHighBits()); + _buffer[index + 3] = (this.cursorIds[i].getHighBits() >> 24) & 0xff; + _buffer[index + 2] = (this.cursorIds[i].getHighBits() >> 16) & 0xff; + _buffer[index + 1] = (this.cursorIds[i].getHighBits() >> 8) & 0xff; + _buffer[index] = this.cursorIds[i].getHighBits() & 0xff; + index = index + 4; + } + + // Return buffer + return [_buffer]; + } +} + +/** @internal */ +export interface MessageHeader { + length: number; + requestId: number; + responseTo: number; + opCode: number; + fromCompressed?: boolean; +} + +/** @internal */ +export interface OpResponseOptions extends BSONSerializeOptions { + raw?: boolean; + documentsReturnedIn?: string | null; +} + +/** @internal */ +export class Response { + parsed: boolean; + raw: Buffer; + data: Buffer; + opts: OpResponseOptions; + length: number; + requestId: number; + responseTo: number; + opCode: number; + fromCompressed?: boolean; + responseFlags?: number; + cursorId?: Long; + startingFrom?: number; + numberReturned?: number; + documents: (Document | Buffer)[] = new Array(0); + cursorNotFound?: boolean; + queryFailure?: boolean; + shardConfigStale?: boolean; + awaitCapable?: boolean; + promoteLongs: boolean; + promoteValues: boolean; + promoteBuffers: boolean; + bsonRegExp?: boolean; + index?: number; + + constructor( + message: Buffer, + msgHeader: MessageHeader, + msgBody: Buffer, + opts?: OpResponseOptions + ) { + this.parsed = false; + this.raw = message; + this.data = msgBody; + this.opts = opts ?? { + promoteLongs: true, + promoteValues: true, + promoteBuffers: false, + bsonRegExp: false + }; + + // Read the message header + this.length = msgHeader.length; + this.requestId = msgHeader.requestId; + this.responseTo = msgHeader.responseTo; + this.opCode = msgHeader.opCode; + this.fromCompressed = msgHeader.fromCompressed; + + // Flag values + this.promoteLongs = typeof this.opts.promoteLongs === 'boolean' ? this.opts.promoteLongs : true; + this.promoteValues = + typeof this.opts.promoteValues === 'boolean' ? this.opts.promoteValues : true; + this.promoteBuffers = + typeof this.opts.promoteBuffers === 'boolean' ? this.opts.promoteBuffers : false; + this.bsonRegExp = typeof this.opts.bsonRegExp === 'boolean' ? this.opts.bsonRegExp : false; + } + + isParsed(): boolean { + return this.parsed; + } + + parse(options: OpResponseOptions): void { + // Don't parse again if not needed + if (this.parsed) return; + options = options ?? {}; + + // Allow the return of raw documents instead of parsing + const raw = options.raw || false; + const documentsReturnedIn = options.documentsReturnedIn || null; + const promoteLongs = options.promoteLongs ?? this.opts.promoteLongs; + const promoteValues = options.promoteValues ?? this.opts.promoteValues; + const promoteBuffers = options.promoteBuffers ?? this.opts.promoteBuffers; + const bsonRegExp = options.bsonRegExp ?? this.opts.bsonRegExp; + let bsonSize; + + // Set up the options + const _options: BSONSerializeOptions = { + promoteLongs, + promoteValues, + promoteBuffers, + bsonRegExp + }; + + // Position within OP_REPLY at which documents start + // (See https://docs.mongodb.com/manual/reference/mongodb-wire-protocol/#wire-op-reply) + this.index = 20; + + // Read the message body + this.responseFlags = this.data.readInt32LE(0); + this.cursorId = new BSON.Long(this.data.readInt32LE(4), this.data.readInt32LE(8)); + this.startingFrom = this.data.readInt32LE(12); + this.numberReturned = this.data.readInt32LE(16); + + // Preallocate document array + this.documents = new Array(this.numberReturned); + + this.cursorNotFound = (this.responseFlags & CURSOR_NOT_FOUND) !== 0; + this.queryFailure = (this.responseFlags & QUERY_FAILURE) !== 0; + this.shardConfigStale = (this.responseFlags & SHARD_CONFIG_STALE) !== 0; + this.awaitCapable = (this.responseFlags & AWAIT_CAPABLE) !== 0; + + // Parse Body + for (let i = 0; i < this.numberReturned; i++) { + bsonSize = + this.data[this.index] | + (this.data[this.index + 1] << 8) | + (this.data[this.index + 2] << 16) | + (this.data[this.index + 3] << 24); + + // If we have raw results specified slice the return document + if (raw) { + this.documents[i] = this.data.slice(this.index, this.index + bsonSize); + } else { + this.documents[i] = BSON.deserialize( + this.data.slice(this.index, this.index + bsonSize), + _options + ); + } + + // Adjust the index + this.index = this.index + bsonSize; + } + + if (this.documents.length === 1 && documentsReturnedIn != null && raw) { + const fieldsAsRaw: Document = {}; + fieldsAsRaw[documentsReturnedIn] = true; + _options.fieldsAsRaw = fieldsAsRaw; + + const doc = BSON.deserialize(this.documents[0] as Buffer, _options); + this.documents = [doc]; + } + + // Set parsed + this.parsed = true; + } +} + +// Implementation of OP_MSG spec: +// https://github.com/mongodb/specifications/blob/master/source/message/OP_MSG.rst +// +// struct Section { +// uint8 payloadType; +// union payload { +// document document; // payloadType == 0 +// struct sequence { // payloadType == 1 +// int32 size; +// cstring identifier; +// document* documents; +// }; +// }; +// }; + +// struct OP_MSG { +// struct MsgHeader { +// int32 messageLength; +// int32 requestID; +// int32 responseTo; +// int32 opCode = 2013; +// }; +// uint32 flagBits; +// Section+ sections; +// [uint32 checksum;] +// }; + +// Msg Flags +const OPTS_CHECKSUM_PRESENT = 1; +const OPTS_MORE_TO_COME = 2; +const OPTS_EXHAUST_ALLOWED = 1 << 16; + +/** @internal */ +export interface OpMsgOptions { + requestId: number; + serializeFunctions: boolean; + ignoreUndefined: boolean; + checkKeys: boolean; + maxBsonSize: number; + moreToCome: boolean; + exhaustAllowed: boolean; + readPreference: ReadPreference; +} + +/** @internal */ +export class Msg { + ns: string; + command: Document; + options: OpQueryOptions; + requestId: number; + serializeFunctions: boolean; + ignoreUndefined: boolean; + checkKeys: boolean; + maxBsonSize: number; + checksumPresent: boolean; + moreToCome: boolean; + exhaustAllowed: boolean; + + constructor(ns: string, command: Document, options: OpQueryOptions) { + // Basic options needed to be passed in + if (command == null) + throw new MongoInvalidArgumentError('Query document must be specified for query'); + + // Basic options + this.ns = ns; + this.command = command; + this.command.$db = databaseNamespace(ns); + + if (options.readPreference && options.readPreference.mode !== ReadPreference.PRIMARY) { + this.command.$readPreference = options.readPreference.toJSON(); + } + + // Ensure empty options + this.options = options ?? {}; + + // Additional options + this.requestId = options.requestId ? options.requestId : Msg.getRequestId(); + + // Serialization option + this.serializeFunctions = + typeof options.serializeFunctions === 'boolean' ? options.serializeFunctions : false; + this.ignoreUndefined = + typeof options.ignoreUndefined === 'boolean' ? options.ignoreUndefined : false; + this.checkKeys = typeof options.checkKeys === 'boolean' ? options.checkKeys : false; + this.maxBsonSize = options.maxBsonSize || 1024 * 1024 * 16; + + // flags + this.checksumPresent = false; + this.moreToCome = options.moreToCome || false; + this.exhaustAllowed = + typeof options.exhaustAllowed === 'boolean' ? options.exhaustAllowed : false; + } + + toBin(): Buffer[] { + const buffers: Buffer[] = []; + let flags = 0; + + if (this.checksumPresent) { + flags |= OPTS_CHECKSUM_PRESENT; + } + + if (this.moreToCome) { + flags |= OPTS_MORE_TO_COME; + } + + if (this.exhaustAllowed) { + flags |= OPTS_EXHAUST_ALLOWED; + } + + const header = Buffer.alloc( + 4 * 4 + // Header + 4 // Flags + ); + + buffers.push(header); + + let totalLength = header.length; + const command = this.command; + totalLength += this.makeDocumentSegment(buffers, command); + + header.writeInt32LE(totalLength, 0); // messageLength + header.writeInt32LE(this.requestId, 4); // requestID + header.writeInt32LE(0, 8); // responseTo + header.writeInt32LE(OP_MSG, 12); // opCode + header.writeUInt32LE(flags, 16); // flags + return buffers; + } + + makeDocumentSegment(buffers: Buffer[], document: Document): number { + const payloadTypeBuffer = Buffer.alloc(1); + payloadTypeBuffer[0] = 0; + + const documentBuffer = this.serializeBson(document); + buffers.push(payloadTypeBuffer); + buffers.push(documentBuffer); + + return payloadTypeBuffer.length + documentBuffer.length; + } + + serializeBson(document: Document): Buffer { + return BSON.serialize(document, { + checkKeys: this.checkKeys, + serializeFunctions: this.serializeFunctions, + ignoreUndefined: this.ignoreUndefined + }); + } + + static getRequestId(): number { + _requestId = (_requestId + 1) & 0x7fffffff; + return _requestId; + } +} + +/** @internal */ +export class BinMsg { + parsed: boolean; + raw: Buffer; + data: Buffer; + opts: OpResponseOptions; + length: number; + requestId: number; + responseTo: number; + opCode: number; + fromCompressed?: boolean; + responseFlags: number; + checksumPresent: boolean; + moreToCome: boolean; + exhaustAllowed: boolean; + promoteLongs: boolean; + promoteValues: boolean; + promoteBuffers: boolean; + bsonRegExp: boolean; + documents: (Document | Buffer)[]; + index?: number; + + constructor( + message: Buffer, + msgHeader: MessageHeader, + msgBody: Buffer, + opts?: OpResponseOptions + ) { + this.parsed = false; + this.raw = message; + this.data = msgBody; + this.opts = opts ?? { + promoteLongs: true, + promoteValues: true, + promoteBuffers: false, + bsonRegExp: false + }; + + // Read the message header + this.length = msgHeader.length; + this.requestId = msgHeader.requestId; + this.responseTo = msgHeader.responseTo; + this.opCode = msgHeader.opCode; + this.fromCompressed = msgHeader.fromCompressed; + + // Read response flags + this.responseFlags = msgBody.readInt32LE(0); + this.checksumPresent = (this.responseFlags & OPTS_CHECKSUM_PRESENT) !== 0; + this.moreToCome = (this.responseFlags & OPTS_MORE_TO_COME) !== 0; + this.exhaustAllowed = (this.responseFlags & OPTS_EXHAUST_ALLOWED) !== 0; + this.promoteLongs = typeof this.opts.promoteLongs === 'boolean' ? this.opts.promoteLongs : true; + this.promoteValues = + typeof this.opts.promoteValues === 'boolean' ? this.opts.promoteValues : true; + this.promoteBuffers = + typeof this.opts.promoteBuffers === 'boolean' ? this.opts.promoteBuffers : false; + this.bsonRegExp = typeof this.opts.bsonRegExp === 'boolean' ? this.opts.bsonRegExp : false; + + this.documents = []; + } + + isParsed(): boolean { + return this.parsed; + } + + parse(options: OpResponseOptions): void { + // Don't parse again if not needed + if (this.parsed) return; + options = options ?? {}; + + this.index = 4; + // Allow the return of raw documents instead of parsing + const raw = options.raw || false; + const documentsReturnedIn = options.documentsReturnedIn || null; + const promoteLongs = options.promoteLongs ?? this.opts.promoteLongs; + const promoteValues = options.promoteValues ?? this.opts.promoteValues; + const promoteBuffers = options.promoteBuffers ?? this.opts.promoteBuffers; + const bsonRegExp = options.bsonRegExp ?? this.opts.bsonRegExp; + const validation = this.parseBsonSerializationOptions(options); + + // Set up the options + const bsonOptions: BSONSerializeOptions = { + promoteLongs, + promoteValues, + promoteBuffers, + bsonRegExp, + validation + // Due to the strictness of the BSON libraries validation option we need this cast + } as BSONSerializeOptions & { validation: { utf8: { writeErrors: boolean } } }; + + while (this.index < this.data.length) { + const payloadType = this.data.readUInt8(this.index++); + if (payloadType === 0) { + const bsonSize = this.data.readUInt32LE(this.index); + const bin = this.data.slice(this.index, this.index + bsonSize); + this.documents.push(raw ? bin : BSON.deserialize(bin, bsonOptions)); + this.index += bsonSize; + } else if (payloadType === 1) { + // It was decided that no driver makes use of payload type 1 + + // TODO(NODE-3483): Replace with MongoDeprecationError + throw new MongoRuntimeError('OP_MSG Payload Type 1 detected unsupported protocol'); + } + } + + if (this.documents.length === 1 && documentsReturnedIn != null && raw) { + const fieldsAsRaw: Document = {}; + fieldsAsRaw[documentsReturnedIn] = true; + bsonOptions.fieldsAsRaw = fieldsAsRaw; + const doc = BSON.deserialize(this.documents[0] as Buffer, bsonOptions); + this.documents = [doc]; + } + + this.parsed = true; + } + + parseBsonSerializationOptions({ enableUtf8Validation }: BSONSerializeOptions): { + utf8: { writeErrors: false } | false; + } { + if (enableUtf8Validation === false) { + return { utf8: false }; + } + + return { utf8: { writeErrors: false } }; + } +} diff --git a/ts-ticket-office-service/node_modules/mongodb/src/cmap/connect.ts b/ts-ticket-office-service/node_modules/mongodb/src/cmap/connect.ts new file mode 100644 index 000000000..354e1043e --- /dev/null +++ b/ts-ticket-office-service/node_modules/mongodb/src/cmap/connect.ts @@ -0,0 +1,512 @@ +import type { Socket, SocketConnectOpts } from 'net'; +import * as net from 'net'; +import { SocksClient } from 'socks'; +import type { ConnectionOptions as TLSConnectionOpts, TLSSocket } from 'tls'; +import * as tls from 'tls'; + +import type { Document } from '../bson'; +import { Int32 } from '../bson'; +import { LEGACY_HELLO_COMMAND } from '../constants'; +import { + MongoCompatibilityError, + MongoError, + MongoErrorLabel, + MongoInvalidArgumentError, + MongoNetworkError, + MongoNetworkTimeoutError, + MongoRuntimeError, + MongoServerError, + needsRetryableWriteLabel +} from '../error'; +import { Callback, ClientMetadata, HostAddress, makeClientMetadata, ns } from '../utils'; +import { AuthContext, AuthProvider } from './auth/auth_provider'; +import { GSSAPI } from './auth/gssapi'; +import { MongoCR } from './auth/mongocr'; +import { MongoDBAWS } from './auth/mongodb_aws'; +import { Plain } from './auth/plain'; +import { AuthMechanism } from './auth/providers'; +import { ScramSHA1, ScramSHA256 } from './auth/scram'; +import { X509 } from './auth/x509'; +import { Connection, ConnectionOptions, CryptoConnection } from './connection'; +import { + MAX_SUPPORTED_SERVER_VERSION, + MAX_SUPPORTED_WIRE_VERSION, + MIN_SUPPORTED_SERVER_VERSION, + MIN_SUPPORTED_WIRE_VERSION +} from './wire_protocol/constants'; + +const AUTH_PROVIDERS = new Map([ + [AuthMechanism.MONGODB_AWS, new MongoDBAWS()], + [AuthMechanism.MONGODB_CR, new MongoCR()], + [AuthMechanism.MONGODB_GSSAPI, new GSSAPI()], + [AuthMechanism.MONGODB_PLAIN, new Plain()], + [AuthMechanism.MONGODB_SCRAM_SHA1, new ScramSHA1()], + [AuthMechanism.MONGODB_SCRAM_SHA256, new ScramSHA256()], + [AuthMechanism.MONGODB_X509, new X509()] +]); + +/** @public */ +export type Stream = Socket | TLSSocket; + +export function connect(options: ConnectionOptions, callback: Callback): void { + makeConnection({ ...options, existingSocket: undefined }, (err, socket) => { + if (err || !socket) { + return callback(err); + } + + let ConnectionType = options.connectionType ?? Connection; + if (options.autoEncrypter) { + ConnectionType = CryptoConnection; + } + performInitialHandshake(new ConnectionType(socket, options), options, callback); + }); +} + +function checkSupportedServer(hello: Document, options: ConnectionOptions) { + const serverVersionHighEnough = + hello && + (typeof hello.maxWireVersion === 'number' || hello.maxWireVersion instanceof Int32) && + hello.maxWireVersion >= MIN_SUPPORTED_WIRE_VERSION; + const serverVersionLowEnough = + hello && + (typeof hello.minWireVersion === 'number' || hello.minWireVersion instanceof Int32) && + hello.minWireVersion <= MAX_SUPPORTED_WIRE_VERSION; + + if (serverVersionHighEnough) { + if (serverVersionLowEnough) { + return null; + } + + const message = `Server at ${options.hostAddress} reports minimum wire version ${JSON.stringify( + hello.minWireVersion + )}, but this version of the Node.js Driver requires at most ${MAX_SUPPORTED_WIRE_VERSION} (MongoDB ${MAX_SUPPORTED_SERVER_VERSION})`; + return new MongoCompatibilityError(message); + } + + const message = `Server at ${options.hostAddress} reports maximum wire version ${ + JSON.stringify(hello.maxWireVersion) ?? 0 + }, but this version of the Node.js Driver requires at least ${MIN_SUPPORTED_WIRE_VERSION} (MongoDB ${MIN_SUPPORTED_SERVER_VERSION})`; + return new MongoCompatibilityError(message); +} + +function performInitialHandshake( + conn: Connection, + options: ConnectionOptions, + _callback: Callback +) { + const callback: Callback = function (err, ret) { + if (err && conn) { + conn.destroy(); + } + _callback(err, ret); + }; + + const credentials = options.credentials; + if (credentials) { + if ( + !(credentials.mechanism === AuthMechanism.MONGODB_DEFAULT) && + !AUTH_PROVIDERS.get(credentials.mechanism) + ) { + callback( + new MongoInvalidArgumentError(`AuthMechanism '${credentials.mechanism}' not supported`) + ); + return; + } + } + + const authContext = new AuthContext(conn, credentials, options); + prepareHandshakeDocument(authContext, (err, handshakeDoc) => { + if (err || !handshakeDoc) { + return callback(err); + } + + const handshakeOptions: Document = Object.assign({}, options); + if (typeof options.connectTimeoutMS === 'number') { + // The handshake technically is a monitoring check, so its socket timeout should be connectTimeoutMS + handshakeOptions.socketTimeoutMS = options.connectTimeoutMS; + } + + const start = new Date().getTime(); + conn.command(ns('admin.$cmd'), handshakeDoc, handshakeOptions, (err, response) => { + if (err) { + callback(err); + return; + } + + if (response?.ok === 0) { + callback(new MongoServerError(response)); + return; + } + + if (!('isWritablePrimary' in response)) { + // Provide hello-style response document. + response.isWritablePrimary = response[LEGACY_HELLO_COMMAND]; + } + + if (response.helloOk) { + conn.helloOk = true; + } + + const supportedServerErr = checkSupportedServer(response, options); + if (supportedServerErr) { + callback(supportedServerErr); + return; + } + + if (options.loadBalanced) { + if (!response.serviceId) { + return callback( + new MongoCompatibilityError( + 'Driver attempted to initialize in load balancing mode, ' + + 'but the server does not support this mode.' + ) + ); + } + } + + // NOTE: This is metadata attached to the connection while porting away from + // handshake being done in the `Server` class. Likely, it should be + // relocated, or at very least restructured. + conn.hello = response; + conn.lastHelloMS = new Date().getTime() - start; + + if (!response.arbiterOnly && credentials) { + // store the response on auth context + authContext.response = response; + + const resolvedCredentials = credentials.resolveAuthMechanism(response); + const provider = AUTH_PROVIDERS.get(resolvedCredentials.mechanism); + if (!provider) { + return callback( + new MongoInvalidArgumentError( + `No AuthProvider for ${resolvedCredentials.mechanism} defined.` + ) + ); + } + provider.auth(authContext, err => { + if (err) { + if (err instanceof MongoError) { + err.addErrorLabel(MongoErrorLabel.HandshakeError); + if (needsRetryableWriteLabel(err, response.maxWireVersion)) { + err.addErrorLabel(MongoErrorLabel.RetryableWriteError); + } + } + return callback(err); + } + callback(undefined, conn); + }); + + return; + } + + callback(undefined, conn); + }); + }); +} + +export interface HandshakeDocument extends Document { + /** + * @deprecated Use hello instead + */ + ismaster?: boolean; + hello?: boolean; + helloOk?: boolean; + client: ClientMetadata; + compression: string[]; + saslSupportedMechs?: string; + loadBalanced: boolean; +} + +function prepareHandshakeDocument(authContext: AuthContext, callback: Callback) { + const options = authContext.options; + const compressors = options.compressors ? options.compressors : []; + const { serverApi } = authContext.connection; + + const handshakeDoc: HandshakeDocument = { + [serverApi?.version ? 'hello' : LEGACY_HELLO_COMMAND]: true, + helloOk: true, + client: options.metadata || makeClientMetadata(options), + compression: compressors, + loadBalanced: options.loadBalanced + }; + + const credentials = authContext.credentials; + if (credentials) { + if (credentials.mechanism === AuthMechanism.MONGODB_DEFAULT && credentials.username) { + handshakeDoc.saslSupportedMechs = `${credentials.source}.${credentials.username}`; + + const provider = AUTH_PROVIDERS.get(AuthMechanism.MONGODB_SCRAM_SHA256); + if (!provider) { + // This auth mechanism is always present. + return callback( + new MongoInvalidArgumentError( + `No AuthProvider for ${AuthMechanism.MONGODB_SCRAM_SHA256} defined.` + ) + ); + } + return provider.prepare(handshakeDoc, authContext, callback); + } + const provider = AUTH_PROVIDERS.get(credentials.mechanism); + if (!provider) { + return callback( + new MongoInvalidArgumentError(`No AuthProvider for ${credentials.mechanism} defined.`) + ); + } + return provider.prepare(handshakeDoc, authContext, callback); + } + callback(undefined, handshakeDoc); +} + +/** @public */ +export const LEGAL_TLS_SOCKET_OPTIONS = [ + 'ALPNProtocols', + 'ca', + 'cert', + 'checkServerIdentity', + 'ciphers', + 'crl', + 'ecdhCurve', + 'key', + 'minDHSize', + 'passphrase', + 'pfx', + 'rejectUnauthorized', + 'secureContext', + 'secureProtocol', + 'servername', + 'session' +] as const; + +/** @public */ +export const LEGAL_TCP_SOCKET_OPTIONS = [ + 'family', + 'hints', + 'localAddress', + 'localPort', + 'lookup' +] as const; + +function parseConnectOptions(options: ConnectionOptions): SocketConnectOpts { + const hostAddress = options.hostAddress; + if (!hostAddress) throw new MongoInvalidArgumentError('Option "hostAddress" is required'); + + const result: Partial = {}; + for (const name of LEGAL_TCP_SOCKET_OPTIONS) { + if (options[name] != null) { + (result as Document)[name] = options[name]; + } + } + + if (typeof hostAddress.socketPath === 'string') { + result.path = hostAddress.socketPath; + return result as net.IpcNetConnectOpts; + } else if (typeof hostAddress.host === 'string') { + result.host = hostAddress.host; + result.port = hostAddress.port; + return result as net.TcpNetConnectOpts; + } else { + // This should never happen since we set up HostAddresses + // But if we don't throw here the socket could hang until timeout + // TODO(NODE-3483) + throw new MongoRuntimeError(`Unexpected HostAddress ${JSON.stringify(hostAddress)}`); + } +} + +type MakeConnectionOptions = ConnectionOptions & { existingSocket?: Stream }; + +function parseSslOptions(options: MakeConnectionOptions): TLSConnectionOpts { + const result: TLSConnectionOpts = parseConnectOptions(options); + // Merge in valid SSL options + for (const name of LEGAL_TLS_SOCKET_OPTIONS) { + if (options[name] != null) { + (result as Document)[name] = options[name]; + } + } + + if (options.existingSocket) { + result.socket = options.existingSocket; + } + + // Set default sni servername to be the same as host + if (result.servername == null && result.host && !net.isIP(result.host)) { + result.servername = result.host; + } + + return result; +} + +const SOCKET_ERROR_EVENT_LIST = ['error', 'close', 'timeout', 'parseError'] as const; +type ErrorHandlerEventName = typeof SOCKET_ERROR_EVENT_LIST[number] | 'cancel'; +const SOCKET_ERROR_EVENTS = new Set(SOCKET_ERROR_EVENT_LIST); + +function makeConnection(options: MakeConnectionOptions, _callback: Callback) { + const useTLS = options.tls ?? false; + const keepAlive = options.keepAlive ?? true; + const socketTimeoutMS = options.socketTimeoutMS ?? Reflect.get(options, 'socketTimeout') ?? 0; + const noDelay = options.noDelay ?? true; + const connectTimeoutMS = options.connectTimeoutMS ?? 30000; + const rejectUnauthorized = options.rejectUnauthorized ?? true; + const keepAliveInitialDelay = + ((options.keepAliveInitialDelay ?? 120000) > socketTimeoutMS + ? Math.round(socketTimeoutMS / 2) + : options.keepAliveInitialDelay) ?? 120000; + const existingSocket = options.existingSocket; + + let socket: Stream; + const callback: Callback = function (err, ret) { + if (err && socket) { + socket.destroy(); + } + + _callback(err, ret); + }; + + if (options.proxyHost != null) { + // Currently, only Socks5 is supported. + return makeSocks5Connection( + { + ...options, + connectTimeoutMS // Should always be present for Socks5 + }, + callback + ); + } + + if (useTLS) { + const tlsSocket = tls.connect(parseSslOptions(options)); + if (typeof tlsSocket.disableRenegotiation === 'function') { + tlsSocket.disableRenegotiation(); + } + socket = tlsSocket; + } else if (existingSocket) { + // In the TLS case, parseSslOptions() sets options.socket to existingSocket, + // so we only need to handle the non-TLS case here (where existingSocket + // gives us all we need out of the box). + socket = existingSocket; + } else { + socket = net.createConnection(parseConnectOptions(options)); + } + + socket.setKeepAlive(keepAlive, keepAliveInitialDelay); + socket.setTimeout(connectTimeoutMS); + socket.setNoDelay(noDelay); + + const connectEvent = useTLS ? 'secureConnect' : 'connect'; + let cancellationHandler: (err: Error) => void; + function errorHandler(eventName: ErrorHandlerEventName) { + return (err: Error) => { + SOCKET_ERROR_EVENTS.forEach(event => socket.removeAllListeners(event)); + if (cancellationHandler && options.cancellationToken) { + options.cancellationToken.removeListener('cancel', cancellationHandler); + } + + socket.removeListener(connectEvent, connectHandler); + callback(connectionFailureError(eventName, err)); + }; + } + + function connectHandler() { + SOCKET_ERROR_EVENTS.forEach(event => socket.removeAllListeners(event)); + if (cancellationHandler && options.cancellationToken) { + options.cancellationToken.removeListener('cancel', cancellationHandler); + } + + if ('authorizationError' in socket) { + if (socket.authorizationError && rejectUnauthorized) { + return callback(socket.authorizationError); + } + } + + socket.setTimeout(socketTimeoutMS); + callback(undefined, socket); + } + + SOCKET_ERROR_EVENTS.forEach(event => socket.once(event, errorHandler(event))); + if (options.cancellationToken) { + cancellationHandler = errorHandler('cancel'); + options.cancellationToken.once('cancel', cancellationHandler); + } + + if (existingSocket) { + process.nextTick(connectHandler); + } else { + socket.once(connectEvent, connectHandler); + } +} + +function makeSocks5Connection(options: MakeConnectionOptions, callback: Callback) { + const hostAddress = HostAddress.fromHostPort( + options.proxyHost ?? '', // proxyHost is guaranteed to set here + options.proxyPort ?? 1080 + ); + + // First, connect to the proxy server itself: + makeConnection( + { + ...options, + hostAddress, + tls: false, + proxyHost: undefined + }, + (err, rawSocket) => { + if (err) { + return callback(err); + } + + const destination = parseConnectOptions(options) as net.TcpNetConnectOpts; + if (typeof destination.host !== 'string' || typeof destination.port !== 'number') { + return callback( + new MongoInvalidArgumentError('Can only make Socks5 connections to TCP hosts') + ); + } + + // Then, establish the Socks5 proxy connection: + SocksClient.createConnection({ + existing_socket: rawSocket, + timeout: options.connectTimeoutMS, + command: 'connect', + destination: { + host: destination.host, + port: destination.port + }, + proxy: { + // host and port are ignored because we pass existing_socket + host: 'iLoveJavaScript', + port: 0, + type: 5, + userId: options.proxyUsername || undefined, + password: options.proxyPassword || undefined + } + }).then( + ({ socket }) => { + // Finally, now treat the resulting duplex stream as the + // socket over which we send and receive wire protocol messages: + makeConnection( + { + ...options, + existingSocket: socket, + proxyHost: undefined + }, + callback + ); + }, + error => callback(connectionFailureError('error', error)) + ); + } + ); +} + +function connectionFailureError(type: ErrorHandlerEventName, err: Error) { + switch (type) { + case 'error': + return new MongoNetworkError(err); + case 'timeout': + return new MongoNetworkTimeoutError('connection timed out'); + case 'close': + return new MongoNetworkError('connection closed'); + case 'cancel': + return new MongoNetworkError('connection establishment was cancelled'); + default: + return new MongoNetworkError('unknown network error'); + } +} diff --git a/ts-ticket-office-service/node_modules/mongodb/src/cmap/connection.ts b/ts-ticket-office-service/node_modules/mongodb/src/cmap/connection.ts new file mode 100644 index 000000000..6068479ae --- /dev/null +++ b/ts-ticket-office-service/node_modules/mongodb/src/cmap/connection.ts @@ -0,0 +1,863 @@ +import { setTimeout } from 'timers'; + +import { BSONSerializeOptions, Document, Long, ObjectId, pluckBSONSerializeOptions } from '../bson'; +import { + CLOSE, + CLUSTER_TIME_RECEIVED, + COMMAND_FAILED, + COMMAND_STARTED, + COMMAND_SUCCEEDED, + MESSAGE, + PINNED, + UNPINNED +} from '../constants'; +import type { AutoEncrypter } from '../deps'; +import { + MongoCompatibilityError, + MongoMissingDependencyError, + MongoNetworkError, + MongoNetworkTimeoutError, + MongoRuntimeError, + MongoServerError, + MongoWriteConcernError +} from '../error'; +import type { ServerApi, SupportedNodeConnectionOptions } from '../mongo_client'; +import { CancellationToken, TypedEventEmitter } from '../mongo_types'; +import type { ReadPreference, ReadPreferenceLike } from '../read_preference'; +import { applySession, ClientSession, updateSessionFromResponse } from '../sessions'; +import { + calculateDurationInMs, + Callback, + ClientMetadata, + HostAddress, + maxWireVersion, + MongoDBNamespace, + now, + uuidV4 +} from '../utils'; +import type { WriteConcern } from '../write_concern'; +import type { MongoCredentials } from './auth/mongo_credentials'; +import { + CommandFailedEvent, + CommandStartedEvent, + CommandSucceededEvent +} from './command_monitoring_events'; +import { + BinMsg, + GetMore, + KillCursor, + Msg, + Query, + Response, + WriteProtocolMessageType +} from './commands'; +import type { Stream } from './connect'; +import { MessageStream, OperationDescription } from './message_stream'; +import { StreamDescription, StreamDescriptionOptions } from './stream_description'; +import { applyCommonQueryOptions, getReadPreference, isSharded } from './wire_protocol/shared'; + +/** @internal */ +const kStream = Symbol('stream'); +/** @internal */ +const kQueue = Symbol('queue'); +/** @internal */ +const kMessageStream = Symbol('messageStream'); +/** @internal */ +const kGeneration = Symbol('generation'); +/** @internal */ +const kLastUseTime = Symbol('lastUseTime'); +/** @internal */ +const kClusterTime = Symbol('clusterTime'); +/** @internal */ +const kDescription = Symbol('description'); +/** @internal */ +const kHello = Symbol('hello'); +/** @internal */ +const kAutoEncrypter = Symbol('autoEncrypter'); +/** @internal */ +const kFullResult = Symbol('fullResult'); +/** @internal */ +const kDelayedTimeoutId = Symbol('delayedTimeoutId'); + +/** @internal */ +export interface QueryOptions extends BSONSerializeOptions { + readPreference: ReadPreference; + documentsReturnedIn?: string; + batchSize?: number; + limit?: number; + skip?: number; + projection?: Document; + tailable?: boolean; + awaitData?: boolean; + noCursorTimeout?: boolean; + /** @deprecated use `noCursorTimeout` instead */ + timeout?: boolean; + partial?: boolean; + oplogReplay?: boolean; +} + +/** @internal */ +export interface CommandOptions extends BSONSerializeOptions { + command?: boolean; + secondaryOk?: boolean; + /** Specify read preference if command supports it */ + readPreference?: ReadPreferenceLike; + raw?: boolean; + monitoring?: boolean; + [kFullResult]?: boolean; + socketTimeoutMS?: number; + /** Session to use for the operation */ + session?: ClientSession; + documentsReturnedIn?: string; + noResponse?: boolean; + omitReadPreference?: boolean; + + // TODO(NODE-2802): Currently the CommandOptions take a property willRetryWrite which is a hint + // from executeOperation that the txnNum should be applied to this command. + // Applying a session to a command should happen as part of command construction, + // most likely in the CommandOperation#executeCommand method, where we have access to + // the details we need to determine if a txnNum should also be applied. + willRetryWrite?: boolean; + + writeConcern?: WriteConcern; +} + +/** @internal */ +export interface GetMoreOptions extends CommandOptions { + batchSize?: number; + maxTimeMS?: number; + maxAwaitTimeMS?: number; + /** + * Comment to apply to the operation. + * + * In server versions pre-4.4, 'comment' must be string. A server + * error will be thrown if any other type is provided. + * + * In server versions 4.4 and above, 'comment' can be any valid BSON type. + */ + comment?: unknown; +} + +/** @public */ +export interface ProxyOptions { + proxyHost?: string; + proxyPort?: number; + proxyUsername?: string; + proxyPassword?: string; +} + +/** @public */ +export interface ConnectionOptions + extends SupportedNodeConnectionOptions, + StreamDescriptionOptions, + ProxyOptions { + // Internal creation info + id: number | ''; + generation: number; + hostAddress: HostAddress; + // Settings + autoEncrypter?: AutoEncrypter; + serverApi?: ServerApi; + monitorCommands: boolean; + /** @internal */ + connectionType?: typeof Connection; + credentials?: MongoCredentials; + connectTimeoutMS?: number; + tls: boolean; + keepAlive?: boolean; + keepAliveInitialDelay?: number; + noDelay?: boolean; + socketTimeoutMS?: number; + cancellationToken?: CancellationToken; + + metadata: ClientMetadata; +} + +/** @public */ +export interface DestroyOptions { + /** Force the destruction. */ + force?: boolean; +} + +/** @public */ +export type ConnectionEvents = { + commandStarted(event: CommandStartedEvent): void; + commandSucceeded(event: CommandSucceededEvent): void; + commandFailed(event: CommandFailedEvent): void; + clusterTimeReceived(clusterTime: Document): void; + close(): void; + message(message: any): void; + pinned(pinType: string): void; + unpinned(pinType: string): void; +}; + +/** @internal */ +export class Connection extends TypedEventEmitter { + id: number | ''; + address: string; + socketTimeoutMS: number; + monitorCommands: boolean; + closed: boolean; + destroyed: boolean; + lastHelloMS?: number; + serverApi?: ServerApi; + helloOk?: boolean; + + /**@internal */ + [kDelayedTimeoutId]: NodeJS.Timeout | null; + /** @internal */ + [kDescription]: StreamDescription; + /** @internal */ + [kGeneration]: number; + /** @internal */ + [kLastUseTime]: number; + /** @internal */ + [kQueue]: Map; + /** @internal */ + [kMessageStream]: MessageStream; + /** @internal */ + [kStream]: Stream; + /** @internal */ + [kHello]: Document | null; + /** @internal */ + [kClusterTime]: Document | null; + + /** @event */ + static readonly COMMAND_STARTED = COMMAND_STARTED; + /** @event */ + static readonly COMMAND_SUCCEEDED = COMMAND_SUCCEEDED; + /** @event */ + static readonly COMMAND_FAILED = COMMAND_FAILED; + /** @event */ + static readonly CLUSTER_TIME_RECEIVED = CLUSTER_TIME_RECEIVED; + /** @event */ + static readonly CLOSE = CLOSE; + /** @event */ + static readonly MESSAGE = MESSAGE; + /** @event */ + static readonly PINNED = PINNED; + /** @event */ + static readonly UNPINNED = UNPINNED; + + constructor(stream: Stream, options: ConnectionOptions) { + super(); + this.id = options.id; + this.address = streamIdentifier(stream, options); + this.socketTimeoutMS = options.socketTimeoutMS ?? 0; + this.monitorCommands = options.monitorCommands; + this.serverApi = options.serverApi; + this.closed = false; + this.destroyed = false; + this[kHello] = null; + this[kClusterTime] = null; + + this[kDescription] = new StreamDescription(this.address, options); + this[kGeneration] = options.generation; + this[kLastUseTime] = now(); + + // setup parser stream and message handling + this[kQueue] = new Map(); + this[kMessageStream] = new MessageStream({ + ...options, + maxBsonMessageSize: this.hello?.maxBsonMessageSize + }); + this[kStream] = stream; + + this[kDelayedTimeoutId] = null; + + this[kMessageStream].on('message', message => this.onMessage(message)); + this[kMessageStream].on('error', error => this.onError(error)); + this[kStream].on('close', () => this.onClose()); + this[kStream].on('timeout', () => this.onTimeout()); + this[kStream].on('error', () => { + /* ignore errors, listen to `close` instead */ + }); + + // hook the message stream up to the passed in stream + this[kStream].pipe(this[kMessageStream]); + this[kMessageStream].pipe(this[kStream]); + } + + get description(): StreamDescription { + return this[kDescription]; + } + + get hello(): Document | null { + return this[kHello]; + } + + // the `connect` method stores the result of the handshake hello on the connection + set hello(response: Document | null) { + this[kDescription].receiveResponse(response); + this[kDescription] = Object.freeze(this[kDescription]); + + // TODO: remove this, and only use the `StreamDescription` in the future + this[kHello] = response; + } + + // Set the whether the message stream is for a monitoring connection. + set isMonitoringConnection(value: boolean) { + this[kMessageStream].isMonitoringConnection = value; + } + + get isMonitoringConnection(): boolean { + return this[kMessageStream].isMonitoringConnection; + } + + get serviceId(): ObjectId | undefined { + return this.hello?.serviceId; + } + + get loadBalanced(): boolean { + return this.description.loadBalanced; + } + + get generation(): number { + return this[kGeneration] || 0; + } + + set generation(generation: number) { + this[kGeneration] = generation; + } + + get idleTime(): number { + return calculateDurationInMs(this[kLastUseTime]); + } + + get clusterTime(): Document | null { + return this[kClusterTime]; + } + + get stream(): Stream { + return this[kStream]; + } + + markAvailable(): void { + this[kLastUseTime] = now(); + } + + onError(error: Error) { + if (this.closed) { + return; + } + + this[kStream].destroy(error); + + this.closed = true; + + for (const op of this[kQueue].values()) { + op.cb(error); + } + + this[kQueue].clear(); + this.emit(Connection.CLOSE); + } + + onClose() { + if (this.closed) { + return; + } + + this.closed = true; + + const message = `connection ${this.id} to ${this.address} closed`; + for (const op of this[kQueue].values()) { + op.cb(new MongoNetworkError(message)); + } + + this[kQueue].clear(); + this.emit(Connection.CLOSE); + } + + onTimeout() { + if (this.closed) { + return; + } + + this[kDelayedTimeoutId] = setTimeout(() => { + this[kStream].destroy(); + + this.closed = true; + + const message = `connection ${this.id} to ${this.address} timed out`; + const beforeHandshake = this.hello == null; + for (const op of this[kQueue].values()) { + op.cb(new MongoNetworkTimeoutError(message, { beforeHandshake })); + } + + this[kQueue].clear(); + this.emit(Connection.CLOSE); + }, 1).unref(); // No need for this timer to hold the event loop open + } + + onMessage(message: BinMsg | Response) { + const delayedTimeoutId = this[kDelayedTimeoutId]; + if (delayedTimeoutId != null) { + clearTimeout(delayedTimeoutId); + this[kDelayedTimeoutId] = null; + } + + // always emit the message, in case we are streaming + this.emit('message', message); + const operationDescription = this[kQueue].get(message.responseTo); + if (!operationDescription) { + return; + } + + const callback = operationDescription.cb; + + // SERVER-45775: For exhaust responses we should be able to use the same requestId to + // track response, however the server currently synthetically produces remote requests + // making the `responseTo` change on each response + this[kQueue].delete(message.responseTo); + if ('moreToCome' in message && message.moreToCome) { + // requeue the callback for next synthetic request + this[kQueue].set(message.requestId, operationDescription); + } else if (operationDescription.socketTimeoutOverride) { + this[kStream].setTimeout(this.socketTimeoutMS); + } + + try { + // Pass in the entire description because it has BSON parsing options + message.parse(operationDescription); + } catch (err) { + // If this error is generated by our own code, it will already have the correct class applied + // if it is not, then it is coming from a catastrophic data parse failure or the BSON library + // in either case, it should not be wrapped + callback(err); + return; + } + + if (message.documents[0]) { + const document: Document = message.documents[0]; + const session = operationDescription.session; + if (session) { + updateSessionFromResponse(session, document); + } + + if (document.$clusterTime) { + this[kClusterTime] = document.$clusterTime; + this.emit(Connection.CLUSTER_TIME_RECEIVED, document.$clusterTime); + } + + if (operationDescription.command) { + if (document.writeConcernError) { + callback(new MongoWriteConcernError(document.writeConcernError, document)); + return; + } + + if (document.ok === 0 || document.$err || document.errmsg || document.code) { + callback(new MongoServerError(document)); + return; + } + } else { + // Pre 3.2 support + if (document.ok === 0 || document.$err || document.errmsg) { + callback(new MongoServerError(document)); + return; + } + } + } + + callback(undefined, operationDescription.fullResult ? message : message.documents[0]); + } + + destroy(options?: DestroyOptions, callback?: Callback): void { + if (typeof options === 'function') { + callback = options; + options = { force: false }; + } + + this.removeAllListeners(Connection.PINNED); + this.removeAllListeners(Connection.UNPINNED); + + options = Object.assign({ force: false }, options); + if (this[kStream] == null || this.destroyed) { + this.destroyed = true; + if (typeof callback === 'function') { + callback(); + } + + return; + } + + if (options.force) { + this[kStream].destroy(); + this.destroyed = true; + if (typeof callback === 'function') { + callback(); + } + + return; + } + + this[kStream].end(() => { + this.destroyed = true; + if (typeof callback === 'function') { + callback(); + } + }); + } + + command( + ns: MongoDBNamespace, + cmd: Document, + options: CommandOptions | undefined, + callback: Callback + ): void { + if (!(ns instanceof MongoDBNamespace)) { + // TODO(NODE-3483): Replace this with a MongoCommandError + throw new MongoRuntimeError('Must provide a MongoDBNamespace instance'); + } + + const readPreference = getReadPreference(cmd, options); + const shouldUseOpMsg = supportsOpMsg(this); + const session = options?.session; + + let clusterTime = this.clusterTime; + let finalCmd = Object.assign({}, cmd); + + if (this.serverApi) { + const { version, strict, deprecationErrors } = this.serverApi; + finalCmd.apiVersion = version; + if (strict != null) finalCmd.apiStrict = strict; + if (deprecationErrors != null) finalCmd.apiDeprecationErrors = deprecationErrors; + } + + if (hasSessionSupport(this) && session) { + if ( + session.clusterTime && + clusterTime && + session.clusterTime.clusterTime.greaterThan(clusterTime.clusterTime) + ) { + clusterTime = session.clusterTime; + } + + const err = applySession(session, finalCmd, options); + if (err) { + return callback(err); + } + } + + // if we have a known cluster time, gossip it + if (clusterTime) { + finalCmd.$clusterTime = clusterTime; + } + + if (isSharded(this) && !shouldUseOpMsg && readPreference && readPreference.mode !== 'primary') { + finalCmd = { + $query: finalCmd, + $readPreference: readPreference.toJSON() + }; + } + + const commandOptions: Document = Object.assign( + { + command: true, + numberToSkip: 0, + numberToReturn: -1, + checkKeys: false, + // This value is not overridable + secondaryOk: readPreference.secondaryOk() + }, + options + ); + + const cmdNs = `${ns.db}.$cmd`; + const message = shouldUseOpMsg + ? new Msg(cmdNs, finalCmd, commandOptions) + : new Query(cmdNs, finalCmd, commandOptions); + + try { + write(this, message, commandOptions, callback); + } catch (err) { + callback(err); + } + } + + getMore( + ns: MongoDBNamespace, + cursorId: Long, + options: GetMoreOptions, + callback: Callback + ): void { + const fullResult = !!options[kFullResult]; + const wireVersion = maxWireVersion(this); + if (!cursorId) { + // TODO(NODE-3483): Replace this with a MongoCommandError + callback(new MongoRuntimeError('Invalid internal cursor state, no known cursor id')); + return; + } + + if (wireVersion < 4) { + const getMoreOp = new GetMore(ns.toString(), cursorId, { numberToReturn: options.batchSize }); + const queryOptions = applyCommonQueryOptions( + {}, + Object.assign(options, { ...pluckBSONSerializeOptions(options) }) + ); + + queryOptions[kFullResult] = true; + queryOptions.command = true; + write(this, getMoreOp, queryOptions, (err, response) => { + if (fullResult) return callback(err, response); + if (err) return callback(err); + callback(undefined, { cursor: { id: response.cursorId, nextBatch: response.documents } }); + }); + + return; + } + + const getMoreCmd: Document = { + getMore: cursorId, + collection: ns.collection + }; + + if (typeof options.batchSize === 'number') { + getMoreCmd.batchSize = Math.abs(options.batchSize); + } + + if (typeof options.maxAwaitTimeMS === 'number') { + getMoreCmd.maxTimeMS = options.maxAwaitTimeMS; + } + // we check for undefined specifically here to allow falsy values + // eslint-disable-next-line no-restricted-syntax + if (options.comment !== undefined) { + getMoreCmd.comment = options.comment; + } + + const commandOptions = Object.assign( + { + returnFieldSelector: null, + documentsReturnedIn: 'nextBatch' + }, + options + ); + + this.command(ns, getMoreCmd, commandOptions, callback); + } + + killCursors( + ns: MongoDBNamespace, + cursorIds: Long[], + options: CommandOptions, + callback: Callback + ): void { + if (!cursorIds || !Array.isArray(cursorIds)) { + // TODO(NODE-3483): Replace this with a MongoCommandError + throw new MongoRuntimeError(`Invalid list of cursor ids provided: ${cursorIds}`); + } + + if (maxWireVersion(this) < 4) { + try { + write( + this, + new KillCursor(ns.toString(), cursorIds), + { noResponse: true, ...options }, + callback + ); + } catch (err) { + callback(err); + } + + return; + } + + this.command( + ns, + { killCursors: ns.collection, cursors: cursorIds }, + { [kFullResult]: true, ...options }, + (err, response) => { + if (err || !response) return callback(err); + if (response.cursorNotFound) { + return callback(new MongoNetworkError('cursor killed or timed out'), null); + } + + if (!Array.isArray(response.documents) || response.documents.length === 0) { + return callback( + // TODO(NODE-3483) + new MongoRuntimeError( + `invalid killCursors result returned for cursor id ${cursorIds[0]}` + ) + ); + } + + callback(undefined, response.documents[0]); + } + ); + } +} + +/** @internal */ +export class CryptoConnection extends Connection { + /** @internal */ + [kAutoEncrypter]?: AutoEncrypter; + + constructor(stream: Stream, options: ConnectionOptions) { + super(stream, options); + this[kAutoEncrypter] = options.autoEncrypter; + } + + /** @internal @override */ + override command( + ns: MongoDBNamespace, + cmd: Document, + options: CommandOptions, + callback: Callback + ): void { + const autoEncrypter = this[kAutoEncrypter]; + if (!autoEncrypter) { + return callback(new MongoMissingDependencyError('No AutoEncrypter available for encryption')); + } + + const serverWireVersion = maxWireVersion(this); + if (serverWireVersion === 0) { + // This means the initial handshake hasn't happened yet + return super.command(ns, cmd, options, callback); + } + + if (serverWireVersion < 8) { + callback( + new MongoCompatibilityError('Auto-encryption requires a minimum MongoDB version of 4.2') + ); + return; + } + + autoEncrypter.encrypt(ns.toString(), cmd, options, (err, encrypted) => { + if (err || encrypted == null) { + callback(err, null); + return; + } + super.command(ns, encrypted, options, (err, response) => { + if (err || response == null) { + callback(err, response); + return; + } + + autoEncrypter.decrypt(response, options, callback); + }); + }); + } +} + +/** @internal */ +export function hasSessionSupport(conn: Connection): boolean { + const description = conn.description; + return description.logicalSessionTimeoutMinutes != null || !!description.loadBalanced; +} + +function supportsOpMsg(conn: Connection) { + const description = conn.description; + if (description == null) { + return false; + } + + return maxWireVersion(conn) >= 6 && !description.__nodejs_mock_server__; +} + +function streamIdentifier(stream: Stream, options: ConnectionOptions): string { + if (options.proxyHost) { + // If proxy options are specified, the properties of `stream` itself + // will not accurately reflect what endpoint this is connected to. + return options.hostAddress.toString(); + } + + if (typeof stream.address === 'function') { + return `${stream.remoteAddress}:${stream.remotePort}`; + } + + return uuidV4().toString('hex'); +} + +function write( + conn: Connection, + command: WriteProtocolMessageType, + options: CommandOptions, + callback: Callback +) { + if (typeof options === 'function') { + callback = options; + } + + options = options ?? {}; + const operationDescription: OperationDescription = { + requestId: command.requestId, + cb: callback, + session: options.session, + fullResult: !!options[kFullResult], + noResponse: typeof options.noResponse === 'boolean' ? options.noResponse : false, + documentsReturnedIn: options.documentsReturnedIn, + command: !!options.command, + + // for BSON parsing + promoteLongs: typeof options.promoteLongs === 'boolean' ? options.promoteLongs : true, + promoteValues: typeof options.promoteValues === 'boolean' ? options.promoteValues : true, + promoteBuffers: typeof options.promoteBuffers === 'boolean' ? options.promoteBuffers : false, + bsonRegExp: typeof options.bsonRegExp === 'boolean' ? options.bsonRegExp : false, + enableUtf8Validation: + typeof options.enableUtf8Validation === 'boolean' ? options.enableUtf8Validation : true, + raw: typeof options.raw === 'boolean' ? options.raw : false, + started: 0 + }; + + if (conn[kDescription] && conn[kDescription].compressor) { + operationDescription.agreedCompressor = conn[kDescription].compressor; + + if (conn[kDescription].zlibCompressionLevel) { + operationDescription.zlibCompressionLevel = conn[kDescription].zlibCompressionLevel; + } + } + + if (typeof options.socketTimeoutMS === 'number') { + operationDescription.socketTimeoutOverride = true; + conn[kStream].setTimeout(options.socketTimeoutMS); + } + + // if command monitoring is enabled we need to modify the callback here + if (conn.monitorCommands) { + conn.emit(Connection.COMMAND_STARTED, new CommandStartedEvent(conn, command)); + + operationDescription.started = now(); + operationDescription.cb = (err, reply) => { + if (err) { + conn.emit( + Connection.COMMAND_FAILED, + new CommandFailedEvent(conn, command, err, operationDescription.started) + ); + } else { + if (reply && (reply.ok === 0 || reply.$err)) { + conn.emit( + Connection.COMMAND_FAILED, + new CommandFailedEvent(conn, command, reply, operationDescription.started) + ); + } else { + conn.emit( + Connection.COMMAND_SUCCEEDED, + new CommandSucceededEvent(conn, command, reply, operationDescription.started) + ); + } + } + + if (typeof callback === 'function') { + callback(err, reply); + } + }; + } + + if (!operationDescription.noResponse) { + conn[kQueue].set(operationDescription.requestId, operationDescription); + } + + try { + conn[kMessageStream].writeCommand(command, operationDescription); + } catch (e) { + if (!operationDescription.noResponse) { + conn[kQueue].delete(operationDescription.requestId); + operationDescription.cb(e); + return; + } + } + + if (operationDescription.noResponse) { + operationDescription.cb(); + } +} diff --git a/ts-ticket-office-service/node_modules/mongodb/src/cmap/connection_pool.ts b/ts-ticket-office-service/node_modules/mongodb/src/cmap/connection_pool.ts new file mode 100644 index 000000000..e8888ccc5 --- /dev/null +++ b/ts-ticket-office-service/node_modules/mongodb/src/cmap/connection_pool.ts @@ -0,0 +1,708 @@ +import Denque = require('denque'); +import { setTimeout } from 'timers'; + +import type { ObjectId } from '../bson'; +import { + APM_EVENTS, + CONNECTION_CHECK_OUT_FAILED, + CONNECTION_CHECK_OUT_STARTED, + CONNECTION_CHECKED_IN, + CONNECTION_CHECKED_OUT, + CONNECTION_CLOSED, + CONNECTION_CREATED, + CONNECTION_POOL_CLEARED, + CONNECTION_POOL_CLOSED, + CONNECTION_POOL_CREATED, + CONNECTION_READY +} from '../constants'; +import { MongoError, MongoInvalidArgumentError, MongoRuntimeError } from '../error'; +import { Logger } from '../logger'; +import { CancellationToken, TypedEventEmitter } from '../mongo_types'; +import { Callback, eachAsync, makeCounter } from '../utils'; +import { connect } from './connect'; +import { Connection, ConnectionEvents, ConnectionOptions } from './connection'; +import { + ConnectionCheckedInEvent, + ConnectionCheckedOutEvent, + ConnectionCheckOutFailedEvent, + ConnectionCheckOutStartedEvent, + ConnectionClosedEvent, + ConnectionCreatedEvent, + ConnectionPoolClearedEvent, + ConnectionPoolClosedEvent, + ConnectionPoolCreatedEvent, + ConnectionReadyEvent +} from './connection_pool_events'; +import { PoolClosedError, WaitQueueTimeoutError } from './errors'; +import { ConnectionPoolMetrics } from './metrics'; + +/** @internal */ +const kLogger = Symbol('logger'); +/** @internal */ +const kConnections = Symbol('connections'); +/** @internal */ +const kPending = Symbol('pending'); +/** @internal */ +const kCheckedOut = Symbol('checkedOut'); +/** @internal */ +const kMinPoolSizeTimer = Symbol('minPoolSizeTimer'); +/** @internal */ +const kGeneration = Symbol('generation'); +/** @internal */ +const kServiceGenerations = Symbol('serviceGenerations'); +/** @internal */ +const kConnectionCounter = Symbol('connectionCounter'); +/** @internal */ +const kCancellationToken = Symbol('cancellationToken'); +/** @internal */ +const kWaitQueue = Symbol('waitQueue'); +/** @internal */ +const kCancelled = Symbol('cancelled'); +/** @internal */ +const kMetrics = Symbol('metrics'); +/** @internal */ +const kProcessingWaitQueue = Symbol('processingWaitQueue'); + +/** @public */ +export interface ConnectionPoolOptions extends Omit { + /** The maximum number of connections that may be associated with a pool at a given time. This includes in use and available connections. */ + maxPoolSize: number; + /** The minimum number of connections that MUST exist at any moment in a single connection pool. */ + minPoolSize: number; + /** The maximum number of connections that may be in the process of being established concurrently by the connection pool. */ + maxConnecting: number; + /** The maximum amount of time a connection should remain idle in the connection pool before being marked idle. */ + maxIdleTimeMS: number; + /** The maximum amount of time operation execution should wait for a connection to become available. The default is 0 which means there is no limit. */ + waitQueueTimeoutMS: number; + /** If we are in load balancer mode. */ + loadBalanced: boolean; +} + +/** @internal */ +export interface WaitQueueMember { + callback: Callback; + timer?: NodeJS.Timeout; + [kCancelled]?: boolean; +} + +/** @public */ +export interface CloseOptions { + force?: boolean; +} + +/** @public */ +export type ConnectionPoolEvents = { + connectionPoolCreated(event: ConnectionPoolCreatedEvent): void; + connectionPoolClosed(event: ConnectionPoolClosedEvent): void; + connectionPoolCleared(event: ConnectionPoolClearedEvent): void; + connectionCreated(event: ConnectionCreatedEvent): void; + connectionReady(event: ConnectionReadyEvent): void; + connectionClosed(event: ConnectionClosedEvent): void; + connectionCheckOutStarted(event: ConnectionCheckOutStartedEvent): void; + connectionCheckOutFailed(event: ConnectionCheckOutFailedEvent): void; + connectionCheckedOut(event: ConnectionCheckedOutEvent): void; + connectionCheckedIn(event: ConnectionCheckedInEvent): void; +} & Omit; + +/** + * A pool of connections which dynamically resizes, and emit events related to pool activity + * @internal + */ +export class ConnectionPool extends TypedEventEmitter { + closed: boolean; + options: Readonly; + /** @internal */ + [kLogger]: Logger; + /** @internal */ + [kConnections]: Denque; + /** @internal */ + [kPending]: number; + /** @internal */ + [kCheckedOut]: number; + /** @internal */ + [kMinPoolSizeTimer]?: NodeJS.Timeout; + /** + * An integer representing the SDAM generation of the pool + * @internal + */ + [kGeneration]: number; + /** A map of generations to service ids + * @internal + */ + [kServiceGenerations]: Map; + /** @internal */ + [kConnectionCounter]: Generator; + /** @internal */ + [kCancellationToken]: CancellationToken; + /** @internal */ + [kWaitQueue]: Denque; + /** @internal */ + [kMetrics]: ConnectionPoolMetrics; + /** @internal */ + [kProcessingWaitQueue]: boolean; + + /** + * Emitted when the connection pool is created. + * @event + */ + static readonly CONNECTION_POOL_CREATED = CONNECTION_POOL_CREATED; + /** + * Emitted once when the connection pool is closed + * @event + */ + static readonly CONNECTION_POOL_CLOSED = CONNECTION_POOL_CLOSED; + /** + * Emitted each time the connection pool is cleared and it's generation incremented + * @event + */ + static readonly CONNECTION_POOL_CLEARED = CONNECTION_POOL_CLEARED; + /** + * Emitted when a connection is created. + * @event + */ + static readonly CONNECTION_CREATED = CONNECTION_CREATED; + /** + * Emitted when a connection becomes established, and is ready to use + * @event + */ + static readonly CONNECTION_READY = CONNECTION_READY; + /** + * Emitted when a connection is closed + * @event + */ + static readonly CONNECTION_CLOSED = CONNECTION_CLOSED; + /** + * Emitted when an attempt to check out a connection begins + * @event + */ + static readonly CONNECTION_CHECK_OUT_STARTED = CONNECTION_CHECK_OUT_STARTED; + /** + * Emitted when an attempt to check out a connection fails + * @event + */ + static readonly CONNECTION_CHECK_OUT_FAILED = CONNECTION_CHECK_OUT_FAILED; + /** + * Emitted each time a connection is successfully checked out of the connection pool + * @event + */ + static readonly CONNECTION_CHECKED_OUT = CONNECTION_CHECKED_OUT; + /** + * Emitted each time a connection is successfully checked into the connection pool + * @event + */ + static readonly CONNECTION_CHECKED_IN = CONNECTION_CHECKED_IN; + + /** @internal */ + constructor(options: ConnectionPoolOptions) { + super(); + + this.closed = false; + this.options = Object.freeze({ + ...options, + connectionType: Connection, + maxPoolSize: options.maxPoolSize ?? 100, + minPoolSize: options.minPoolSize ?? 0, + maxConnecting: options.maxConnecting ?? 2, + maxIdleTimeMS: options.maxIdleTimeMS ?? 0, + waitQueueTimeoutMS: options.waitQueueTimeoutMS ?? 0, + autoEncrypter: options.autoEncrypter, + metadata: options.metadata + }); + + if (this.options.minPoolSize > this.options.maxPoolSize) { + throw new MongoInvalidArgumentError( + 'Connection pool minimum size must not be greater than maximum pool size' + ); + } + + this[kLogger] = new Logger('ConnectionPool'); + this[kConnections] = new Denque(); + this[kPending] = 0; + this[kCheckedOut] = 0; + this[kMinPoolSizeTimer] = undefined; + this[kGeneration] = 0; + this[kServiceGenerations] = new Map(); + this[kConnectionCounter] = makeCounter(1); + this[kCancellationToken] = new CancellationToken(); + this[kCancellationToken].setMaxListeners(Infinity); + this[kWaitQueue] = new Denque(); + this[kMetrics] = new ConnectionPoolMetrics(); + this[kProcessingWaitQueue] = false; + + process.nextTick(() => { + this.emit(ConnectionPool.CONNECTION_POOL_CREATED, new ConnectionPoolCreatedEvent(this)); + ensureMinPoolSize(this); + }); + } + + /** The address of the endpoint the pool is connected to */ + get address(): string { + return this.options.hostAddress.toString(); + } + + /** An integer representing the SDAM generation of the pool */ + get generation(): number { + return this[kGeneration]; + } + + /** An integer expressing how many total connections (available + pending + in use) the pool currently has */ + get totalConnectionCount(): number { + return ( + this.availableConnectionCount + this.pendingConnectionCount + this.currentCheckedOutCount + ); + } + + /** An integer expressing how many connections are currently available in the pool. */ + get availableConnectionCount(): number { + return this[kConnections].length; + } + + get pendingConnectionCount(): number { + return this[kPending]; + } + + get currentCheckedOutCount(): number { + return this[kCheckedOut]; + } + + get waitQueueSize(): number { + return this[kWaitQueue].length; + } + + get loadBalanced(): boolean { + return this.options.loadBalanced; + } + + get serviceGenerations(): Map { + return this[kServiceGenerations]; + } + + /** + * Get the metrics information for the pool when a wait queue timeout occurs. + */ + private waitQueueErrorMetrics(): string { + return this[kMetrics].info(this.options.maxPoolSize); + } + + /** + * Check a connection out of this pool. The connection will continue to be tracked, but no reference to it + * will be held by the pool. This means that if a connection is checked out it MUST be checked back in or + * explicitly destroyed by the new owner. + */ + checkOut(callback: Callback): void { + this.emit( + ConnectionPool.CONNECTION_CHECK_OUT_STARTED, + new ConnectionCheckOutStartedEvent(this) + ); + + if (this.closed) { + this.emit( + ConnectionPool.CONNECTION_CHECK_OUT_FAILED, + new ConnectionCheckOutFailedEvent(this, 'poolClosed') + ); + callback(new PoolClosedError(this)); + return; + } + + const waitQueueMember: WaitQueueMember = { callback }; + const waitQueueTimeoutMS = this.options.waitQueueTimeoutMS; + if (waitQueueTimeoutMS) { + waitQueueMember.timer = setTimeout(() => { + waitQueueMember[kCancelled] = true; + waitQueueMember.timer = undefined; + + this.emit( + ConnectionPool.CONNECTION_CHECK_OUT_FAILED, + new ConnectionCheckOutFailedEvent(this, 'timeout') + ); + waitQueueMember.callback( + new WaitQueueTimeoutError( + this.loadBalanced + ? this.waitQueueErrorMetrics() + : 'Timed out while checking out a connection from connection pool', + this.address + ) + ); + }, waitQueueTimeoutMS); + } + + this[kWaitQueue].push(waitQueueMember); + process.nextTick(processWaitQueue, this); + } + + /** + * Check a connection into the pool. + * + * @param connection - The connection to check in + */ + checkIn(connection: Connection): void { + const poolClosed = this.closed; + const stale = connectionIsStale(this, connection); + const willDestroy = !!(poolClosed || stale || connection.closed); + + if (!willDestroy) { + connection.markAvailable(); + this[kConnections].unshift(connection); + } + + this[kCheckedOut]--; + this.emit(ConnectionPool.CONNECTION_CHECKED_IN, new ConnectionCheckedInEvent(this, connection)); + + if (willDestroy) { + const reason = connection.closed ? 'error' : poolClosed ? 'poolClosed' : 'stale'; + destroyConnection(this, connection, reason); + } + + process.nextTick(processWaitQueue, this); + } + + /** + * Clear the pool + * + * Pool reset is handled by incrementing the pool's generation count. Any existing connection of a + * previous generation will eventually be pruned during subsequent checkouts. + */ + clear(serviceId?: ObjectId): void { + if (this.loadBalanced && serviceId) { + const sid = serviceId.toHexString(); + const generation = this.serviceGenerations.get(sid); + // Only need to worry if the generation exists, since it should + // always be there but typescript needs the check. + if (generation == null) { + // TODO(NODE-3483) + throw new MongoRuntimeError('Service generations are required in load balancer mode.'); + } else { + // Increment the generation for the service id. + this.serviceGenerations.set(sid, generation + 1); + } + } else { + this[kGeneration] += 1; + } + + this.emit('connectionPoolCleared', new ConnectionPoolClearedEvent(this, serviceId)); + } + + /** Close the pool */ + close(callback: Callback): void; + close(options: CloseOptions, callback: Callback): void; + close(_options?: CloseOptions | Callback, _cb?: Callback): void { + let options = _options as CloseOptions; + const callback = (_cb ?? _options) as Callback; + if (typeof options === 'function') { + options = {}; + } + + options = Object.assign({ force: false }, options); + if (this.closed) { + return callback(); + } + + // immediately cancel any in-flight connections + this[kCancellationToken].emit('cancel'); + + // drain the wait queue + while (this.waitQueueSize) { + const waitQueueMember = this[kWaitQueue].pop(); + if (waitQueueMember) { + if (waitQueueMember.timer) { + clearTimeout(waitQueueMember.timer); + } + if (!waitQueueMember[kCancelled]) { + // TODO(NODE-3483): Replace with MongoConnectionPoolClosedError + waitQueueMember.callback(new MongoRuntimeError('Connection pool closed')); + } + } + } + + // clear the min pool size timer + const minPoolSizeTimer = this[kMinPoolSizeTimer]; + if (minPoolSizeTimer) { + clearTimeout(minPoolSizeTimer); + } + + // end the connection counter + if (typeof this[kConnectionCounter].return === 'function') { + this[kConnectionCounter].return(undefined); + } + + // mark the pool as closed immediately + this.closed = true; + eachAsync( + this[kConnections].toArray(), + (conn, cb) => { + this.emit( + ConnectionPool.CONNECTION_CLOSED, + new ConnectionClosedEvent(this, conn, 'poolClosed') + ); + conn.destroy(options, cb); + }, + err => { + this[kConnections].clear(); + this.emit(ConnectionPool.CONNECTION_POOL_CLOSED, new ConnectionPoolClosedEvent(this)); + callback(err); + } + ); + } + + /** + * Runs a lambda with an implicitly checked out connection, checking that connection back in when the lambda + * has completed by calling back. + * + * NOTE: please note the required signature of `fn` + * + * @remarks When in load balancer mode, connections can be pinned to cursors or transactions. + * In these cases we pass the connection in to this method to ensure it is used and a new + * connection is not checked out. + * + * @param conn - A pinned connection for use in load balancing mode. + * @param fn - A function which operates on a managed connection + * @param callback - The original callback + */ + withConnection( + conn: Connection | undefined, + fn: WithConnectionCallback, + callback?: Callback + ): void { + if (conn) { + // use the provided connection, and do _not_ check it in after execution + fn(undefined, conn, (fnErr, result) => { + if (typeof callback === 'function') { + if (fnErr) { + callback(fnErr); + } else { + callback(undefined, result); + } + } + }); + + return; + } + + this.checkOut((err, conn) => { + // don't callback with `err` here, we might want to act upon it inside `fn` + fn(err as MongoError, conn, (fnErr, result) => { + if (typeof callback === 'function') { + if (fnErr) { + callback(fnErr); + } else { + callback(undefined, result); + } + } + + if (conn) { + this.checkIn(conn); + } + }); + }); + } +} + +function ensureMinPoolSize(pool: ConnectionPool) { + const minPoolSize = pool.options.minPoolSize; + if (pool.closed || minPoolSize === 0) { + return; + } + + if ( + pool.totalConnectionCount < minPoolSize && + pool.pendingConnectionCount < pool.options.maxConnecting + ) { + // NOTE: ensureMinPoolSize should not try to get all the pending + // connection permits because that potentially delays the availability of + // the connection to a checkout request + createConnection(pool, (err, connection) => { + pool[kPending]--; + if (!err && connection) { + pool[kConnections].push(connection); + process.nextTick(processWaitQueue, pool); + } + pool[kMinPoolSizeTimer] = setTimeout(() => ensureMinPoolSize(pool), 10); + }); + } else { + pool[kMinPoolSizeTimer] = setTimeout(() => ensureMinPoolSize(pool), 100); + } +} + +function connectionIsStale(pool: ConnectionPool, connection: Connection) { + const serviceId = connection.serviceId; + if (pool.loadBalanced && serviceId) { + const sid = serviceId.toHexString(); + const generation = pool.serviceGenerations.get(sid); + return connection.generation !== generation; + } + + return connection.generation !== pool[kGeneration]; +} + +function connectionIsIdle(pool: ConnectionPool, connection: Connection) { + return !!(pool.options.maxIdleTimeMS && connection.idleTime > pool.options.maxIdleTimeMS); +} + +function createConnection(pool: ConnectionPool, callback: Callback) { + const connectOptions: ConnectionOptions = { + ...pool.options, + id: pool[kConnectionCounter].next().value, + generation: pool[kGeneration], + cancellationToken: pool[kCancellationToken] + }; + + pool[kPending]++; + // This is our version of a "virtual" no-I/O connection as the spec requires + pool.emit( + ConnectionPool.CONNECTION_CREATED, + new ConnectionCreatedEvent(pool, { id: connectOptions.id }) + ); + + connect(connectOptions, (err, connection) => { + if (err || !connection) { + pool[kLogger].debug(`connection attempt failed with error [${JSON.stringify(err)}]`); + callback(err); + return; + } + + // The pool might have closed since we started trying to create a connection + if (pool.closed) { + pool[kPending]--; + connection.destroy({ force: true }); + return; + } + + // forward all events from the connection to the pool + for (const event of [...APM_EVENTS, Connection.CLUSTER_TIME_RECEIVED]) { + connection.on(event, (e: any) => pool.emit(event, e)); + } + + if (pool.loadBalanced) { + connection.on(Connection.PINNED, pinType => pool[kMetrics].markPinned(pinType)); + connection.on(Connection.UNPINNED, pinType => pool[kMetrics].markUnpinned(pinType)); + + const serviceId = connection.serviceId; + if (serviceId) { + let generation; + const sid = serviceId.toHexString(); + if ((generation = pool.serviceGenerations.get(sid))) { + connection.generation = generation; + } else { + pool.serviceGenerations.set(sid, 0); + connection.generation = 0; + } + } + } + + connection.markAvailable(); + pool.emit(ConnectionPool.CONNECTION_READY, new ConnectionReadyEvent(pool, connection)); + + callback(undefined, connection); + return; + }); +} + +function destroyConnection(pool: ConnectionPool, connection: Connection, reason: string) { + pool.emit(ConnectionPool.CONNECTION_CLOSED, new ConnectionClosedEvent(pool, connection, reason)); + + // destroy the connection + process.nextTick(() => connection.destroy()); +} + +function processWaitQueue(pool: ConnectionPool) { + if (pool.closed || pool[kProcessingWaitQueue]) { + return; + } + + pool[kProcessingWaitQueue] = true; + while (pool.waitQueueSize) { + const waitQueueMember = pool[kWaitQueue].peekFront(); + if (!waitQueueMember) { + pool[kWaitQueue].shift(); + continue; + } + + if (waitQueueMember[kCancelled]) { + pool[kWaitQueue].shift(); + continue; + } + + if (!pool.availableConnectionCount) { + break; + } + + const connection = pool[kConnections].shift(); + if (!connection) { + break; + } + + const isStale = connectionIsStale(pool, connection); + const isIdle = connectionIsIdle(pool, connection); + if (!isStale && !isIdle && !connection.closed) { + pool[kCheckedOut]++; + pool.emit( + ConnectionPool.CONNECTION_CHECKED_OUT, + new ConnectionCheckedOutEvent(pool, connection) + ); + if (waitQueueMember.timer) { + clearTimeout(waitQueueMember.timer); + } + + pool[kWaitQueue].shift(); + waitQueueMember.callback(undefined, connection); + } else { + const reason = connection.closed ? 'error' : isStale ? 'stale' : 'idle'; + destroyConnection(pool, connection, reason); + } + } + + const { maxPoolSize, maxConnecting } = pool.options; + while ( + pool.waitQueueSize > 0 && + pool.pendingConnectionCount < maxConnecting && + (maxPoolSize === 0 || pool.totalConnectionCount < maxPoolSize) + ) { + const waitQueueMember = pool[kWaitQueue].shift(); + if (!waitQueueMember || waitQueueMember[kCancelled]) { + continue; + } + createConnection(pool, (err, connection) => { + pool[kPending]--; + if (waitQueueMember[kCancelled]) { + if (!err && connection) { + pool[kConnections].push(connection); + } + } else { + if (err) { + pool.emit( + ConnectionPool.CONNECTION_CHECK_OUT_FAILED, + new ConnectionCheckOutFailedEvent(pool, err) + ); + } else if (connection) { + pool[kCheckedOut]++; + pool.emit( + ConnectionPool.CONNECTION_CHECKED_OUT, + new ConnectionCheckedOutEvent(pool, connection) + ); + } + + if (waitQueueMember.timer) { + clearTimeout(waitQueueMember.timer); + } + waitQueueMember.callback(err, connection); + } + process.nextTick(processWaitQueue, pool); + }); + } + pool[kProcessingWaitQueue] = false; +} + +/** + * A callback provided to `withConnection` + * @internal + * + * @param error - An error instance representing the error during the execution. + * @param connection - The managed connection which was checked out of the pool. + * @param callback - A function to call back after connection management is complete + */ +export type WithConnectionCallback = ( + error: MongoError | undefined, + connection: Connection | undefined, + callback: Callback +) => void; diff --git a/ts-ticket-office-service/node_modules/mongodb/src/cmap/connection_pool_events.ts b/ts-ticket-office-service/node_modules/mongodb/src/cmap/connection_pool_events.ts new file mode 100644 index 000000000..a98dc25d7 --- /dev/null +++ b/ts-ticket-office-service/node_modules/mongodb/src/cmap/connection_pool_events.ts @@ -0,0 +1,179 @@ +import type { ObjectId } from '../bson'; +import type { AnyError } from '../error'; +import type { Connection } from './connection'; +import type { ConnectionPool, ConnectionPoolOptions } from './connection_pool'; + +/** + * The base export class for all monitoring events published from the connection pool + * @public + * @category Event + */ +export class ConnectionPoolMonitoringEvent { + /** A timestamp when the event was created */ + time: Date; + /** The address (host/port pair) of the pool */ + address: string; + + /** @internal */ + constructor(pool: ConnectionPool) { + this.time = new Date(); + this.address = pool.address; + } +} + +/** + * An event published when a connection pool is created + * @public + * @category Event + */ +export class ConnectionPoolCreatedEvent extends ConnectionPoolMonitoringEvent { + /** The options used to create this connection pool */ + options?: ConnectionPoolOptions; + + /** @internal */ + constructor(pool: ConnectionPool) { + super(pool); + this.options = pool.options; + } +} + +/** + * An event published when a connection pool is closed + * @public + * @category Event + */ +export class ConnectionPoolClosedEvent extends ConnectionPoolMonitoringEvent { + /** @internal */ + constructor(pool: ConnectionPool) { + super(pool); + } +} + +/** + * An event published when a connection pool creates a new connection + * @public + * @category Event + */ +export class ConnectionCreatedEvent extends ConnectionPoolMonitoringEvent { + /** A monotonically increasing, per-pool id for the newly created connection */ + connectionId: number | ''; + + /** @internal */ + constructor(pool: ConnectionPool, connection: { id: number | '' }) { + super(pool); + this.connectionId = connection.id; + } +} + +/** + * An event published when a connection is ready for use + * @public + * @category Event + */ +export class ConnectionReadyEvent extends ConnectionPoolMonitoringEvent { + /** The id of the connection */ + connectionId: number | ''; + + /** @internal */ + constructor(pool: ConnectionPool, connection: Connection) { + super(pool); + this.connectionId = connection.id; + } +} + +/** + * An event published when a connection is closed + * @public + * @category Event + */ +export class ConnectionClosedEvent extends ConnectionPoolMonitoringEvent { + /** The id of the connection */ + connectionId: number | ''; + /** The reason the connection was closed */ + reason: string; + serviceId?: ObjectId; + + /** @internal */ + constructor(pool: ConnectionPool, connection: Connection, reason: string) { + super(pool); + this.connectionId = connection.id; + this.reason = reason || 'unknown'; + this.serviceId = connection.serviceId; + } +} + +/** + * An event published when a request to check a connection out begins + * @public + * @category Event + */ +export class ConnectionCheckOutStartedEvent extends ConnectionPoolMonitoringEvent { + /** @internal */ + constructor(pool: ConnectionPool) { + super(pool); + } +} + +/** + * An event published when a request to check a connection out fails + * @public + * @category Event + */ +export class ConnectionCheckOutFailedEvent extends ConnectionPoolMonitoringEvent { + /** The reason the attempt to check out failed */ + reason: AnyError | string; + + /** @internal */ + constructor(pool: ConnectionPool, reason: AnyError | string) { + super(pool); + this.reason = reason; + } +} + +/** + * An event published when a connection is checked out of the connection pool + * @public + * @category Event + */ +export class ConnectionCheckedOutEvent extends ConnectionPoolMonitoringEvent { + /** The id of the connection */ + connectionId: number | ''; + + /** @internal */ + constructor(pool: ConnectionPool, connection: Connection) { + super(pool); + this.connectionId = connection.id; + } +} + +/** + * An event published when a connection is checked into the connection pool + * @public + * @category Event + */ +export class ConnectionCheckedInEvent extends ConnectionPoolMonitoringEvent { + /** The id of the connection */ + connectionId: number | ''; + + /** @internal */ + constructor(pool: ConnectionPool, connection: Connection) { + super(pool); + this.connectionId = connection.id; + } +} + +/** + * An event published when a connection pool is cleared + * @public + * @category Event + */ +export class ConnectionPoolClearedEvent extends ConnectionPoolMonitoringEvent { + /** @internal */ + serviceId?: ObjectId; + + /** @internal */ + constructor(pool: ConnectionPool, serviceId?: ObjectId) { + super(pool); + this.serviceId = serviceId; + } +} diff --git a/ts-ticket-office-service/node_modules/mongodb/src/cmap/errors.ts b/ts-ticket-office-service/node_modules/mongodb/src/cmap/errors.ts new file mode 100644 index 000000000..85e8dac79 --- /dev/null +++ b/ts-ticket-office-service/node_modules/mongodb/src/cmap/errors.ts @@ -0,0 +1,38 @@ +import { MongoDriverError } from '../error'; +import type { ConnectionPool } from './connection_pool'; + +/** + * An error indicating a connection pool is closed + * @category Error + */ +export class PoolClosedError extends MongoDriverError { + /** The address of the connection pool */ + address: string; + + constructor(pool: ConnectionPool) { + super('Attempted to check out a connection from closed connection pool'); + this.address = pool.address; + } + + override get name(): string { + return 'MongoPoolClosedError'; + } +} + +/** + * An error thrown when a request to check out a connection times out + * @category Error + */ +export class WaitQueueTimeoutError extends MongoDriverError { + /** The address of the connection pool */ + address: string; + + constructor(message: string, address: string) { + super(message); + this.address = address; + } + + override get name(): string { + return 'MongoWaitQueueTimeoutError'; + } +} diff --git a/ts-ticket-office-service/node_modules/mongodb/src/cmap/message_stream.ts b/ts-ticket-office-service/node_modules/mongodb/src/cmap/message_stream.ts new file mode 100644 index 000000000..542e35cf7 --- /dev/null +++ b/ts-ticket-office-service/node_modules/mongodb/src/cmap/message_stream.ts @@ -0,0 +1,243 @@ +import { Duplex, DuplexOptions } from 'stream'; + +import type { BSONSerializeOptions, Document } from '../bson'; +import { MongoDecompressionError, MongoParseError } from '../error'; +import type { ClientSession } from '../sessions'; +import { BufferPool, Callback } from '../utils'; +import { BinMsg, MessageHeader, Msg, Query, Response, WriteProtocolMessageType } from './commands'; +import { + compress, + Compressor, + CompressorName, + decompress, + uncompressibleCommands +} from './wire_protocol/compression'; +import { OP_COMPRESSED, OP_MSG } from './wire_protocol/constants'; + +const MESSAGE_HEADER_SIZE = 16; +const COMPRESSION_DETAILS_SIZE = 9; // originalOpcode + uncompressedSize, compressorID + +const kDefaultMaxBsonMessageSize = 1024 * 1024 * 16 * 4; +/** @internal */ +const kBuffer = Symbol('buffer'); + +/** @internal */ +export interface MessageStreamOptions extends DuplexOptions { + maxBsonMessageSize?: number; +} + +/** @internal */ +export interface OperationDescription extends BSONSerializeOptions { + started: number; + cb: Callback; + command: boolean; + documentsReturnedIn?: string; + fullResult: boolean; + noResponse: boolean; + raw: boolean; + requestId: number; + session?: ClientSession; + socketTimeoutOverride?: boolean; + agreedCompressor?: CompressorName; + zlibCompressionLevel?: number; + $clusterTime?: Document; +} + +/** + * A duplex stream that is capable of reading and writing raw wire protocol messages, with + * support for optional compression + * @internal + */ +export class MessageStream extends Duplex { + /** @internal */ + maxBsonMessageSize: number; + /** @internal */ + [kBuffer]: BufferPool; + /** @internal */ + isMonitoringConnection = false; + + constructor(options: MessageStreamOptions = {}) { + super(options); + this.maxBsonMessageSize = options.maxBsonMessageSize || kDefaultMaxBsonMessageSize; + this[kBuffer] = new BufferPool(); + } + + get buffer(): BufferPool { + return this[kBuffer]; + } + + override _write(chunk: Buffer, _: unknown, callback: Callback): void { + this[kBuffer].append(chunk); + processIncomingData(this, callback); + } + + override _read(/* size */): void { + // NOTE: This implementation is empty because we explicitly push data to be read + // when `writeMessage` is called. + return; + } + + writeCommand( + command: WriteProtocolMessageType, + operationDescription: OperationDescription + ): void { + // TODO: agreed compressor should live in `StreamDescription` + const compressorName: CompressorName = + operationDescription && operationDescription.agreedCompressor + ? operationDescription.agreedCompressor + : 'none'; + if (compressorName === 'none' || !canCompress(command)) { + const data = command.toBin(); + this.push(Array.isArray(data) ? Buffer.concat(data) : data); + return; + } + // otherwise, compress the message + const concatenatedOriginalCommandBuffer = Buffer.concat(command.toBin()); + const messageToBeCompressed = concatenatedOriginalCommandBuffer.slice(MESSAGE_HEADER_SIZE); + + // Extract information needed for OP_COMPRESSED from the uncompressed message + const originalCommandOpCode = concatenatedOriginalCommandBuffer.readInt32LE(12); + + // Compress the message body + compress({ options: operationDescription }, messageToBeCompressed, (err, compressedMessage) => { + if (err || !compressedMessage) { + operationDescription.cb(err); + return; + } + + // Create the msgHeader of OP_COMPRESSED + const msgHeader = Buffer.alloc(MESSAGE_HEADER_SIZE); + msgHeader.writeInt32LE( + MESSAGE_HEADER_SIZE + COMPRESSION_DETAILS_SIZE + compressedMessage.length, + 0 + ); // messageLength + msgHeader.writeInt32LE(command.requestId, 4); // requestID + msgHeader.writeInt32LE(0, 8); // responseTo (zero) + msgHeader.writeInt32LE(OP_COMPRESSED, 12); // opCode + + // Create the compression details of OP_COMPRESSED + const compressionDetails = Buffer.alloc(COMPRESSION_DETAILS_SIZE); + compressionDetails.writeInt32LE(originalCommandOpCode, 0); // originalOpcode + compressionDetails.writeInt32LE(messageToBeCompressed.length, 4); // Size of the uncompressed compressedMessage, excluding the MsgHeader + compressionDetails.writeUInt8(Compressor[compressorName], 8); // compressorID + this.push(Buffer.concat([msgHeader, compressionDetails, compressedMessage])); + }); + } +} + +// Return whether a command contains an uncompressible command term +// Will return true if command contains no uncompressible command terms +function canCompress(command: WriteProtocolMessageType) { + const commandDoc = command instanceof Msg ? command.command : (command as Query).query; + const commandName = Object.keys(commandDoc)[0]; + return !uncompressibleCommands.has(commandName); +} + +function processIncomingData(stream: MessageStream, callback: Callback) { + const buffer = stream[kBuffer]; + if (buffer.length < 4) { + callback(); + return; + } + + const sizeOfMessage = buffer.peek(4).readInt32LE(); + if (sizeOfMessage < 0) { + callback(new MongoParseError(`Invalid message size: ${sizeOfMessage}`)); + return; + } + + if (sizeOfMessage > stream.maxBsonMessageSize) { + callback( + new MongoParseError( + `Invalid message size: ${sizeOfMessage}, max allowed: ${stream.maxBsonMessageSize}` + ) + ); + return; + } + + if (sizeOfMessage > buffer.length) { + callback(); + return; + } + + const message = buffer.read(sizeOfMessage); + const messageHeader: MessageHeader = { + length: message.readInt32LE(0), + requestId: message.readInt32LE(4), + responseTo: message.readInt32LE(8), + opCode: message.readInt32LE(12) + }; + + const monitorHasAnotherHello = () => { + if (stream.isMonitoringConnection) { + // Can we read the next message size? + if (buffer.length >= 4) { + const sizeOfMessage = buffer.peek(4).readInt32LE(); + if (sizeOfMessage <= buffer.length) { + return true; + } + } + } + return false; + }; + + let ResponseType = messageHeader.opCode === OP_MSG ? BinMsg : Response; + if (messageHeader.opCode !== OP_COMPRESSED) { + const messageBody = message.slice(MESSAGE_HEADER_SIZE); + + // If we are a monitoring connection message stream and + // there is more in the buffer that can be read, skip processing since we + // want the last hello command response that is in the buffer. + if (monitorHasAnotherHello()) { + processIncomingData(stream, callback); + } else { + stream.emit('message', new ResponseType(message, messageHeader, messageBody)); + + if (buffer.length >= 4) { + processIncomingData(stream, callback); + } else { + callback(); + } + } + + return; + } + + messageHeader.fromCompressed = true; + messageHeader.opCode = message.readInt32LE(MESSAGE_HEADER_SIZE); + messageHeader.length = message.readInt32LE(MESSAGE_HEADER_SIZE + 4); + const compressorID: Compressor = message[MESSAGE_HEADER_SIZE + 8] as Compressor; + const compressedBuffer = message.slice(MESSAGE_HEADER_SIZE + 9); + + // recalculate based on wrapped opcode + ResponseType = messageHeader.opCode === OP_MSG ? BinMsg : Response; + decompress(compressorID, compressedBuffer, (err, messageBody) => { + if (err || !messageBody) { + callback(err); + return; + } + + if (messageBody.length !== messageHeader.length) { + callback( + new MongoDecompressionError('Message body and message header must be the same length') + ); + + return; + } + + // If we are a monitoring connection message stream and + // there is more in the buffer that can be read, skip processing since we + // want the last hello command response that is in the buffer. + if (monitorHasAnotherHello()) { + processIncomingData(stream, callback); + } else { + stream.emit('message', new ResponseType(message, messageHeader, messageBody)); + + if (buffer.length >= 4) { + processIncomingData(stream, callback); + } else { + callback(); + } + } + }); +} diff --git a/ts-ticket-office-service/node_modules/mongodb/src/cmap/metrics.ts b/ts-ticket-office-service/node_modules/mongodb/src/cmap/metrics.ts new file mode 100644 index 000000000..b825b5393 --- /dev/null +++ b/ts-ticket-office-service/node_modules/mongodb/src/cmap/metrics.ts @@ -0,0 +1,58 @@ +/** @internal */ +export class ConnectionPoolMetrics { + static readonly TXN = 'txn' as const; + static readonly CURSOR = 'cursor' as const; + static readonly OTHER = 'other' as const; + + txnConnections = 0; + cursorConnections = 0; + otherConnections = 0; + + /** + * Mark a connection as pinned for a specific operation. + */ + markPinned(pinType: string): void { + if (pinType === ConnectionPoolMetrics.TXN) { + this.txnConnections += 1; + } else if (pinType === ConnectionPoolMetrics.CURSOR) { + this.cursorConnections += 1; + } else { + this.otherConnections += 1; + } + } + + /** + * Unmark a connection as pinned for an operation. + */ + markUnpinned(pinType: string): void { + if (pinType === ConnectionPoolMetrics.TXN) { + this.txnConnections -= 1; + } else if (pinType === ConnectionPoolMetrics.CURSOR) { + this.cursorConnections -= 1; + } else { + this.otherConnections -= 1; + } + } + + /** + * Return information about the cmap metrics as a string. + */ + info(maxPoolSize: number): string { + return ( + 'Timed out while checking out a connection from connection pool: ' + + `maxPoolSize: ${maxPoolSize}, ` + + `connections in use by cursors: ${this.cursorConnections}, ` + + `connections in use by transactions: ${this.txnConnections}, ` + + `connections in use by other operations: ${this.otherConnections}` + ); + } + + /** + * Reset the metrics to the initial values. + */ + reset(): void { + this.txnConnections = 0; + this.cursorConnections = 0; + this.otherConnections = 0; + } +} diff --git a/ts-ticket-office-service/node_modules/mongodb/src/cmap/stream_description.ts b/ts-ticket-office-service/node_modules/mongodb/src/cmap/stream_description.ts new file mode 100644 index 000000000..c5fbec0f4 --- /dev/null +++ b/ts-ticket-office-service/node_modules/mongodb/src/cmap/stream_description.ts @@ -0,0 +1,76 @@ +import type { Document } from '../bson'; +import { ServerType } from '../sdam/common'; +import { parseServerType } from '../sdam/server_description'; +import type { CompressorName } from './wire_protocol/compression'; + +const RESPONSE_FIELDS = [ + 'minWireVersion', + 'maxWireVersion', + 'maxBsonObjectSize', + 'maxMessageSizeBytes', + 'maxWriteBatchSize', + 'logicalSessionTimeoutMinutes' +] as const; + +/** @public */ +export interface StreamDescriptionOptions { + compressors?: CompressorName[]; + logicalSessionTimeoutMinutes?: number; + loadBalanced: boolean; +} + +/** @public */ +export class StreamDescription { + address: string; + type: string; + minWireVersion?: number; + maxWireVersion?: number; + maxBsonObjectSize: number; + maxMessageSizeBytes: number; + maxWriteBatchSize: number; + compressors: CompressorName[]; + compressor?: CompressorName; + logicalSessionTimeoutMinutes?: number; + loadBalanced: boolean; + + __nodejs_mock_server__?: boolean; + + zlibCompressionLevel?: number; + + constructor(address: string, options?: StreamDescriptionOptions) { + this.address = address; + this.type = ServerType.Unknown; + this.minWireVersion = undefined; + this.maxWireVersion = undefined; + this.maxBsonObjectSize = 16777216; + this.maxMessageSizeBytes = 48000000; + this.maxWriteBatchSize = 100000; + this.logicalSessionTimeoutMinutes = options?.logicalSessionTimeoutMinutes; + this.loadBalanced = !!options?.loadBalanced; + this.compressors = + options && options.compressors && Array.isArray(options.compressors) + ? options.compressors + : []; + } + + receiveResponse(response: Document | null): void { + if (response == null) { + return; + } + this.type = parseServerType(response); + for (const field of RESPONSE_FIELDS) { + if (response[field] != null) { + this[field] = response[field]; + } + + // testing case + if ('__nodejs_mock_server__' in response) { + this.__nodejs_mock_server__ = response['__nodejs_mock_server__']; + } + } + + if (response.compression) { + this.compressor = this.compressors.filter(c => response.compression?.includes(c))[0]; + } + } +} diff --git a/ts-ticket-office-service/node_modules/mongodb/src/cmap/wire_protocol/compression.ts b/ts-ticket-office-service/node_modules/mongodb/src/cmap/wire_protocol/compression.ts new file mode 100644 index 000000000..68e1af545 --- /dev/null +++ b/ts-ticket-office-service/node_modules/mongodb/src/cmap/wire_protocol/compression.ts @@ -0,0 +1,130 @@ +import * as zlib from 'zlib'; + +import { LEGACY_HELLO_COMMAND } from '../../constants'; +import { PKG_VERSION, Snappy, ZStandard } from '../../deps'; +import { MongoDecompressionError, MongoInvalidArgumentError } from '../../error'; +import type { Callback } from '../../utils'; +import type { OperationDescription } from '../message_stream'; + +/** @public */ +export const Compressor = Object.freeze({ + none: 0, + snappy: 1, + zlib: 2, + zstd: 3 +} as const); + +/** @public */ +export type Compressor = typeof Compressor[CompressorName]; + +/** @public */ +export type CompressorName = keyof typeof Compressor; + +export const uncompressibleCommands = new Set([ + LEGACY_HELLO_COMMAND, + 'saslStart', + 'saslContinue', + 'getnonce', + 'authenticate', + 'createUser', + 'updateUser', + 'copydbSaslStart', + 'copydbgetnonce', + 'copydb' +]); + +const MAX_COMPRESSOR_ID = 3; +const ZSTD_COMPRESSION_LEVEL = 3; + +// Facilitate compressing a message using an agreed compressor +export function compress( + self: { options: OperationDescription & zlib.ZlibOptions }, + dataToBeCompressed: Buffer, + callback: Callback +): void { + const zlibOptions = {} as zlib.ZlibOptions; + switch (self.options.agreedCompressor) { + case 'snappy': { + if ('kModuleError' in Snappy) { + return callback(Snappy['kModuleError']); + } + + if (Snappy[PKG_VERSION].major <= 6) { + Snappy.compress(dataToBeCompressed, callback); + } else { + Snappy.compress(dataToBeCompressed).then( + buffer => callback(undefined, buffer), + error => callback(error) + ); + } + break; + } + case 'zlib': + // Determine zlibCompressionLevel + if (self.options.zlibCompressionLevel) { + zlibOptions.level = self.options.zlibCompressionLevel; + } + zlib.deflate(dataToBeCompressed, zlibOptions, callback as zlib.CompressCallback); + break; + case 'zstd': + if ('kModuleError' in ZStandard) { + return callback(ZStandard['kModuleError']); + } + ZStandard.compress(dataToBeCompressed, ZSTD_COMPRESSION_LEVEL).then( + buffer => callback(undefined, buffer), + error => callback(error) + ); + break; + default: + throw new MongoInvalidArgumentError( + `Unknown compressor ${self.options.agreedCompressor} failed to compress` + ); + } +} + +// Decompress a message using the given compressor +export function decompress( + compressorID: Compressor, + compressedData: Buffer, + callback: Callback +): void { + if (compressorID < 0 || compressorID > MAX_COMPRESSOR_ID) { + throw new MongoDecompressionError( + `Server sent message compressed using an unsupported compressor. (Received compressor ID ${compressorID})` + ); + } + + switch (compressorID) { + case Compressor.snappy: { + if ('kModuleError' in Snappy) { + return callback(Snappy['kModuleError']); + } + + if (Snappy[PKG_VERSION].major <= 6) { + Snappy.uncompress(compressedData, { asBuffer: true }, callback); + } else { + Snappy.uncompress(compressedData, { asBuffer: true }).then( + buffer => callback(undefined, buffer), + error => callback(error) + ); + } + break; + } + case Compressor.zstd: { + if ('kModuleError' in ZStandard) { + return callback(ZStandard['kModuleError']); + } + + ZStandard.decompress(compressedData).then( + buffer => callback(undefined, buffer), + error => callback(error) + ); + break; + } + case Compressor.zlib: + zlib.inflate(compressedData, callback as zlib.CompressCallback); + break; + default: + callback(undefined, compressedData); + } +} diff --git a/ts-ticket-office-service/node_modules/mongodb/src/cmap/wire_protocol/constants.ts b/ts-ticket-office-service/node_modules/mongodb/src/cmap/wire_protocol/constants.ts new file mode 100644 index 000000000..4d515a5e5 --- /dev/null +++ b/ts-ticket-office-service/node_modules/mongodb/src/cmap/wire_protocol/constants.ts @@ -0,0 +1,13 @@ +export const MIN_SUPPORTED_SERVER_VERSION = '3.6'; +export const MAX_SUPPORTED_SERVER_VERSION = '6.0'; +export const MIN_SUPPORTED_WIRE_VERSION = 6; +export const MAX_SUPPORTED_WIRE_VERSION = 17; +export const OP_REPLY = 1; +export const OP_UPDATE = 2001; +export const OP_INSERT = 2002; +export const OP_QUERY = 2004; +export const OP_GETMORE = 2005; +export const OP_DELETE = 2006; +export const OP_KILL_CURSORS = 2007; +export const OP_COMPRESSED = 2012; +export const OP_MSG = 2013; diff --git a/ts-ticket-office-service/node_modules/mongodb/src/cmap/wire_protocol/shared.ts b/ts-ticket-office-service/node_modules/mongodb/src/cmap/wire_protocol/shared.ts new file mode 100644 index 000000000..bc13ff6d8 --- /dev/null +++ b/ts-ticket-office-service/node_modules/mongodb/src/cmap/wire_protocol/shared.ts @@ -0,0 +1,76 @@ +import type { Document } from '../../bson'; +import { MongoInvalidArgumentError } from '../../error'; +import type { ReadPreferenceLike } from '../../read_preference'; +import { ReadPreference } from '../../read_preference'; +import { ServerType } from '../../sdam/common'; +import type { Server } from '../../sdam/server'; +import type { ServerDescription } from '../../sdam/server_description'; +import type { Topology } from '../../sdam/topology'; +import { TopologyDescription } from '../../sdam/topology_description'; +import type { OpQueryOptions } from '../commands'; +import type { CommandOptions, Connection } from '../connection'; + +export interface ReadPreferenceOption { + readPreference?: ReadPreferenceLike; +} + +export function getReadPreference(cmd: Document, options?: ReadPreferenceOption): ReadPreference { + // Default to command version of the readPreference + let readPreference = cmd.readPreference || ReadPreference.primary; + // If we have an option readPreference override the command one + if (options?.readPreference) { + readPreference = options.readPreference; + } + + if (typeof readPreference === 'string') { + readPreference = ReadPreference.fromString(readPreference); + } + + if (!(readPreference instanceof ReadPreference)) { + throw new MongoInvalidArgumentError( + 'Option "readPreference" must be a ReadPreference instance' + ); + } + + return readPreference; +} + +export function applyCommonQueryOptions( + queryOptions: OpQueryOptions, + options: CommandOptions +): CommandOptions { + Object.assign(queryOptions, { + raw: typeof options.raw === 'boolean' ? options.raw : false, + promoteLongs: typeof options.promoteLongs === 'boolean' ? options.promoteLongs : true, + promoteValues: typeof options.promoteValues === 'boolean' ? options.promoteValues : true, + promoteBuffers: typeof options.promoteBuffers === 'boolean' ? options.promoteBuffers : false, + bsonRegExp: typeof options.bsonRegExp === 'boolean' ? options.bsonRegExp : false, + enableUtf8Validation: + typeof options.enableUtf8Validation === 'boolean' ? options.enableUtf8Validation : true + }); + + if (options.session) { + queryOptions.session = options.session; + } + + return queryOptions; +} + +export function isSharded(topologyOrServer?: Topology | Server | Connection): boolean { + if (topologyOrServer == null) { + return false; + } + + if (topologyOrServer.description && topologyOrServer.description.type === ServerType.Mongos) { + return true; + } + + // NOTE: This is incredibly inefficient, and should be removed once command construction + // happens based on `Server` not `Topology`. + if (topologyOrServer.description && topologyOrServer.description instanceof TopologyDescription) { + const servers: ServerDescription[] = Array.from(topologyOrServer.description.servers.values()); + return servers.some((server: ServerDescription) => server.type === ServerType.Mongos); + } + + return false; +} diff --git a/ts-ticket-office-service/node_modules/mongodb/src/collection.ts b/ts-ticket-office-service/node_modules/mongodb/src/collection.ts new file mode 100644 index 000000000..7cfb5e41c --- /dev/null +++ b/ts-ticket-office-service/node_modules/mongodb/src/collection.ts @@ -0,0 +1,1700 @@ +import { BSONSerializeOptions, Document, resolveBSONOptions } from './bson'; +import type { AnyBulkWriteOperation, BulkWriteOptions, BulkWriteResult } from './bulk/common'; +import { OrderedBulkOperation } from './bulk/ordered'; +import { UnorderedBulkOperation } from './bulk/unordered'; +import { ChangeStream, ChangeStreamDocument, ChangeStreamOptions } from './change_stream'; +import { AggregationCursor } from './cursor/aggregation_cursor'; +import { FindCursor } from './cursor/find_cursor'; +import { ListIndexesCursor } from './cursor/list_indexes_cursor'; +import type { Db } from './db'; +import { MongoInvalidArgumentError } from './error'; +import type { Logger, LoggerOptions } from './logger'; +import type { PkFactory } from './mongo_client'; +import type { + Filter, + Flatten, + OptionalUnlessRequiredId, + TODO_NODE_3286, + UpdateFilter, + WithId, + WithoutId +} from './mongo_types'; +import type { AggregateOptions } from './operations/aggregate'; +import { BulkWriteOperation } from './operations/bulk_write'; +import type { IndexInformationOptions } from './operations/common_functions'; +import { CountOperation, CountOptions } from './operations/count'; +import { CountDocumentsOperation, CountDocumentsOptions } from './operations/count_documents'; +import { + DeleteManyOperation, + DeleteOneOperation, + DeleteOptions, + DeleteResult +} from './operations/delete'; +import { DistinctOperation, DistinctOptions } from './operations/distinct'; +import { DropCollectionOperation, DropCollectionOptions } from './operations/drop'; +import { + EstimatedDocumentCountOperation, + EstimatedDocumentCountOptions +} from './operations/estimated_document_count'; +import { executeOperation } from './operations/execute_operation'; +import type { FindOptions } from './operations/find'; +import { + FindOneAndDeleteOperation, + FindOneAndDeleteOptions, + FindOneAndReplaceOperation, + FindOneAndReplaceOptions, + FindOneAndUpdateOperation, + FindOneAndUpdateOptions +} from './operations/find_and_modify'; +import { + CreateIndexesOperation, + CreateIndexesOptions, + CreateIndexOperation, + DropIndexesOperation, + DropIndexesOptions, + DropIndexOperation, + IndexDescription, + IndexesOperation, + IndexExistsOperation, + IndexInformationOperation, + IndexSpecification, + ListIndexesOptions +} from './operations/indexes'; +import { + InsertManyOperation, + InsertManyResult, + InsertOneOperation, + InsertOneOptions, + InsertOneResult +} from './operations/insert'; +import { IsCappedOperation } from './operations/is_capped'; +import { + MapFunction, + MapReduceOperation, + MapReduceOptions, + ReduceFunction +} from './operations/map_reduce'; +import type { Hint, OperationOptions } from './operations/operation'; +import { OptionsOperation } from './operations/options_operation'; +import { RenameOperation, RenameOptions } from './operations/rename'; +import { CollStats, CollStatsOperation, CollStatsOptions } from './operations/stats'; +import { + ReplaceOneOperation, + ReplaceOptions, + UpdateManyOperation, + UpdateOneOperation, + UpdateOptions, + UpdateResult +} from './operations/update'; +import { ReadConcern, ReadConcernLike } from './read_concern'; +import { ReadPreference, ReadPreferenceLike } from './read_preference'; +import { + Callback, + checkCollectionName, + DEFAULT_PK_FACTORY, + emitWarningOnce, + MongoDBNamespace, + normalizeHintField, + resolveOptions +} from './utils'; +import { WriteConcern, WriteConcernOptions } from './write_concern'; + +/** @public */ +export interface ModifyResult { + value: WithId | null; + lastErrorObject?: Document; + ok: 0 | 1; +} + +/** @public */ +export interface CollectionOptions + extends BSONSerializeOptions, + WriteConcernOptions, + LoggerOptions { + /** + * @deprecated Use readPreference instead + */ + slaveOk?: boolean; + /** Specify a read concern for the collection. (only MongoDB 3.2 or higher supported) */ + readConcern?: ReadConcernLike; + /** The preferred read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST). */ + readPreference?: ReadPreferenceLike; +} + +/** @internal */ +export interface CollectionPrivate { + pkFactory: PkFactory; + db: Db; + options: any; + namespace: MongoDBNamespace; + readPreference?: ReadPreference; + bsonOptions: BSONSerializeOptions; + collectionHint?: Hint; + readConcern?: ReadConcern; + writeConcern?: WriteConcern; +} + +/** + * The **Collection** class is an internal class that embodies a MongoDB collection + * allowing for insert/update/remove/find and other command operation on that MongoDB collection. + * + * **COLLECTION Cannot directly be instantiated** + * @public + * + * @example + * ```js + * const MongoClient = require('mongodb').MongoClient; + * const test = require('assert'); + * // Connection url + * const url = 'mongodb://localhost:27017'; + * // Database Name + * const dbName = 'test'; + * // Connect using MongoClient + * MongoClient.connect(url, function(err, client) { + * // Create a collection we want to drop later + * const col = client.db(dbName).collection('createIndexExample1'); + * // Show that duplicate records got dropped + * col.find({}).toArray(function(err, items) { + * expect(err).to.not.exist; + * test.equal(4, items.length); + * client.close(); + * }); + * }); + * ``` + */ +export class Collection { + /** @internal */ + s: CollectionPrivate; + + /** + * Create a new Collection instance + * @internal + */ + constructor(db: Db, name: string, options?: CollectionOptions) { + checkCollectionName(name); + + // Internal state + this.s = { + db, + options, + namespace: new MongoDBNamespace(db.databaseName, name), + pkFactory: db.options?.pkFactory ?? DEFAULT_PK_FACTORY, + readPreference: ReadPreference.fromOptions(options), + bsonOptions: resolveBSONOptions(options, db), + readConcern: ReadConcern.fromOptions(options), + writeConcern: WriteConcern.fromOptions(options) + }; + } + + /** + * The name of the database this collection belongs to + */ + get dbName(): string { + return this.s.namespace.db; + } + + /** + * The name of this collection + */ + get collectionName(): string { + // eslint-disable-next-line @typescript-eslint/no-non-null-assertion + return this.s.namespace.collection!; + } + + /** + * The namespace of this collection, in the format `${this.dbName}.${this.collectionName}` + */ + get namespace(): string { + return this.s.namespace.toString(); + } + + /** + * The current readConcern of the collection. If not explicitly defined for + * this collection, will be inherited from the parent DB + */ + get readConcern(): ReadConcern | undefined { + if (this.s.readConcern == null) { + return this.s.db.readConcern; + } + return this.s.readConcern; + } + + /** + * The current readPreference of the collection. If not explicitly defined for + * this collection, will be inherited from the parent DB + */ + get readPreference(): ReadPreference | undefined { + if (this.s.readPreference == null) { + return this.s.db.readPreference; + } + + return this.s.readPreference; + } + + get bsonOptions(): BSONSerializeOptions { + return this.s.bsonOptions; + } + + /** + * The current writeConcern of the collection. If not explicitly defined for + * this collection, will be inherited from the parent DB + */ + get writeConcern(): WriteConcern | undefined { + if (this.s.writeConcern == null) { + return this.s.db.writeConcern; + } + return this.s.writeConcern; + } + + /** The current index hint for the collection */ + get hint(): Hint | undefined { + return this.s.collectionHint; + } + + set hint(v: Hint | undefined) { + this.s.collectionHint = normalizeHintField(v); + } + + /** + * Inserts a single document into MongoDB. If documents passed in do not contain the **_id** field, + * one will be added to each of the documents missing it by the driver, mutating the document. This behavior + * can be overridden by setting the **forceServerObjectId** flag. + * + * @param doc - The document to insert + * @param options - Optional settings for the command + * @param callback - An optional callback, a Promise will be returned if none is provided + */ + insertOne(doc: OptionalUnlessRequiredId): Promise>; + insertOne( + doc: OptionalUnlessRequiredId, + callback: Callback> + ): void; + insertOne( + doc: OptionalUnlessRequiredId, + options: InsertOneOptions + ): Promise>; + insertOne( + doc: OptionalUnlessRequiredId, + options: InsertOneOptions, + callback: Callback> + ): void; + insertOne( + doc: OptionalUnlessRequiredId, + options?: InsertOneOptions | Callback>, + callback?: Callback> + ): Promise> | void { + if (typeof options === 'function') { + callback = options; + options = {}; + } + + // CSFLE passes in { w: 'majority' } to ensure the lib works in both 3.x and 4.x + // we support that option style here only + if (options && Reflect.get(options, 'w')) { + options.writeConcern = WriteConcern.fromOptions(Reflect.get(options, 'w')); + } + + return executeOperation( + this.s.db.s.client, + new InsertOneOperation( + this as TODO_NODE_3286, + doc, + resolveOptions(this, options) + ) as TODO_NODE_3286, + callback + ); + } + + /** + * Inserts an array of documents into MongoDB. If documents passed in do not contain the **_id** field, + * one will be added to each of the documents missing it by the driver, mutating the document. This behavior + * can be overridden by setting the **forceServerObjectId** flag. + * + * @param docs - The documents to insert + * @param options - Optional settings for the command + * @param callback - An optional callback, a Promise will be returned if none is provided + */ + insertMany(docs: OptionalUnlessRequiredId[]): Promise>; + insertMany( + docs: OptionalUnlessRequiredId[], + callback: Callback> + ): void; + insertMany( + docs: OptionalUnlessRequiredId[], + options: BulkWriteOptions + ): Promise>; + insertMany( + docs: OptionalUnlessRequiredId[], + options: BulkWriteOptions, + callback: Callback> + ): void; + insertMany( + docs: OptionalUnlessRequiredId[], + options?: BulkWriteOptions | Callback>, + callback?: Callback> + ): Promise> | void { + if (typeof options === 'function') (callback = options), (options = {}); + options = options ? Object.assign({}, options) : { ordered: true }; + + return executeOperation( + this.s.db.s.client, + new InsertManyOperation( + this as TODO_NODE_3286, + docs, + resolveOptions(this, options) + ) as TODO_NODE_3286, + callback + ); + } + + /** + * Perform a bulkWrite operation without a fluent API + * + * Legal operation types are + * + * ```js + * { insertOne: { document: { a: 1 } } } + * + * { updateOne: { filter: {a:2}, update: {$set: {a:2}}, upsert:true } } + * + * { updateMany: { filter: {a:2}, update: {$set: {a:2}}, upsert:true } } + * + * { updateMany: { filter: {}, update: {$set: {"a.$[i].x": 5}}, arrayFilters: [{ "i.x": 5 }]} } + * + * { deleteOne: { filter: {c:1} } } + * + * { deleteMany: { filter: {c:1} } } + * + * { replaceOne: { filter: {c:3}, replacement: {c:4}, upsert:true} } + *``` + * Please note that raw operations are no longer accepted as of driver version 4.0. + * + * If documents passed in do not contain the **_id** field, + * one will be added to each of the documents missing it by the driver, mutating the document. This behavior + * can be overridden by setting the **forceServerObjectId** flag. + * + * @param operations - Bulk operations to perform + * @param options - Optional settings for the command + * @param callback - An optional callback, a Promise will be returned if none is provided + * @throws MongoDriverError if operations is not an array + */ + bulkWrite(operations: AnyBulkWriteOperation[]): Promise; + bulkWrite( + operations: AnyBulkWriteOperation[], + callback: Callback + ): void; + bulkWrite( + operations: AnyBulkWriteOperation[], + options: BulkWriteOptions + ): Promise; + bulkWrite( + operations: AnyBulkWriteOperation[], + options: BulkWriteOptions, + callback: Callback + ): void; + bulkWrite( + operations: AnyBulkWriteOperation[], + options?: BulkWriteOptions | Callback, + callback?: Callback + ): Promise | void { + if (typeof options === 'function') (callback = options), (options = {}); + options = options || { ordered: true }; + + if (!Array.isArray(operations)) { + throw new MongoInvalidArgumentError('Argument "operations" must be an array of documents'); + } + + return executeOperation( + this.s.db.s.client, + new BulkWriteOperation( + this as TODO_NODE_3286, + operations as TODO_NODE_3286, + resolveOptions(this, options) + ), + callback + ); + } + + /** + * Update a single document in a collection + * + * @param filter - The filter used to select the document to update + * @param update - The update operations to be applied to the document + * @param options - Optional settings for the command + * @param callback - An optional callback, a Promise will be returned if none is provided + */ + updateOne( + filter: Filter, + update: UpdateFilter | Partial + ): Promise; + updateOne( + filter: Filter, + update: UpdateFilter | Partial, + callback: Callback + ): void; + updateOne( + filter: Filter, + update: UpdateFilter | Partial, + options: UpdateOptions + ): Promise; + updateOne( + filter: Filter, + update: UpdateFilter | Partial, + options: UpdateOptions, + callback: Callback + ): void; + updateOne( + filter: Filter, + update: UpdateFilter | Partial, + options?: UpdateOptions | Callback, + callback?: Callback + ): Promise | void { + if (typeof options === 'function') (callback = options), (options = {}); + + return executeOperation( + this.s.db.s.client, + new UpdateOneOperation( + this as TODO_NODE_3286, + filter, + update, + resolveOptions(this, options) + ) as TODO_NODE_3286, + callback + ); + } + + /** + * Replace a document in a collection with another document + * + * @param filter - The filter used to select the document to replace + * @param replacement - The Document that replaces the matching document + * @param options - Optional settings for the command + * @param callback - An optional callback, a Promise will be returned if none is provided + */ + replaceOne( + filter: Filter, + replacement: WithoutId + ): Promise; + replaceOne( + filter: Filter, + replacement: WithoutId, + callback: Callback + ): void; + replaceOne( + filter: Filter, + replacement: WithoutId, + options: ReplaceOptions + ): Promise; + replaceOne( + filter: Filter, + replacement: WithoutId, + options: ReplaceOptions, + callback: Callback + ): void; + replaceOne( + filter: Filter, + replacement: WithoutId, + options?: ReplaceOptions | Callback, + callback?: Callback + ): Promise | void { + if (typeof options === 'function') (callback = options), (options = {}); + + return executeOperation( + this.s.db.s.client, + new ReplaceOneOperation( + this as TODO_NODE_3286, + filter, + replacement, + resolveOptions(this, options) + ), + callback + ); + } + + /** + * Update multiple documents in a collection + * + * @param filter - The filter used to select the documents to update + * @param update - The update operations to be applied to the documents + * @param options - Optional settings for the command + * @param callback - An optional callback, a Promise will be returned if none is provided + */ + updateMany( + filter: Filter, + update: UpdateFilter + ): Promise; + updateMany( + filter: Filter, + update: UpdateFilter, + callback: Callback + ): void; + updateMany( + filter: Filter, + update: UpdateFilter, + options: UpdateOptions + ): Promise; + updateMany( + filter: Filter, + update: UpdateFilter, + options: UpdateOptions, + callback: Callback + ): void; + updateMany( + filter: Filter, + update: UpdateFilter, + options?: UpdateOptions | Callback, + callback?: Callback + ): Promise | void { + if (typeof options === 'function') (callback = options), (options = {}); + + return executeOperation( + this.s.db.s.client, + new UpdateManyOperation( + this as TODO_NODE_3286, + filter, + update, + resolveOptions(this, options) + ), + callback + ); + } + + /** + * Delete a document from a collection + * + * @param filter - The filter used to select the document to remove + * @param options - Optional settings for the command + * @param callback - An optional callback, a Promise will be returned if none is provided + */ + deleteOne(filter: Filter): Promise; + deleteOne(filter: Filter, callback: Callback): void; + deleteOne(filter: Filter, options: DeleteOptions): Promise; + deleteOne( + filter: Filter, + options: DeleteOptions, + callback?: Callback + ): void; + deleteOne( + filter: Filter, + options?: DeleteOptions | Callback, + callback?: Callback + ): Promise | void { + if (typeof options === 'function') (callback = options), (options = {}); + + return executeOperation( + this.s.db.s.client, + new DeleteOneOperation(this as TODO_NODE_3286, filter, resolveOptions(this, options)), + callback + ); + } + + /** + * Delete multiple documents from a collection + * + * @param filter - The filter used to select the documents to remove + * @param options - Optional settings for the command + * @param callback - An optional callback, a Promise will be returned if none is provided + */ + deleteMany(filter: Filter): Promise; + deleteMany(filter: Filter, callback: Callback): void; + deleteMany(filter: Filter, options: DeleteOptions): Promise; + deleteMany( + filter: Filter, + options: DeleteOptions, + callback: Callback + ): void; + deleteMany( + filter: Filter, + options?: DeleteOptions | Callback, + callback?: Callback + ): Promise | void { + if (filter == null) { + filter = {}; + options = {}; + callback = undefined; + } else if (typeof filter === 'function') { + callback = filter as Callback; + filter = {}; + options = {}; + } else if (typeof options === 'function') { + callback = options; + options = {}; + } + + return executeOperation( + this.s.db.s.client, + new DeleteManyOperation(this as TODO_NODE_3286, filter, resolveOptions(this, options)), + callback + ); + } + + /** + * Rename the collection. + * + * @remarks + * This operation does not inherit options from the Db or MongoClient. + * + * @param newName - New name of of the collection. + * @param options - Optional settings for the command + * @param callback - An optional callback, a Promise will be returned if none is provided + */ + rename(newName: string): Promise; + rename(newName: string, callback: Callback): void; + rename(newName: string, options: RenameOptions): Promise; + rename(newName: string, options: RenameOptions, callback: Callback): void; + rename( + newName: string, + options?: RenameOptions | Callback, + callback?: Callback + ): Promise | void { + if (typeof options === 'function') (callback = options), (options = {}); + + // Intentionally, we do not inherit options from parent for this operation. + return executeOperation( + this.s.db.s.client, + new RenameOperation(this as TODO_NODE_3286, newName, { + ...options, + readPreference: ReadPreference.PRIMARY + }), + callback + ); + } + + /** + * Drop the collection from the database, removing it permanently. New accesses will create a new collection. + * + * @param options - Optional settings for the command + * @param callback - An optional callback, a Promise will be returned if none is provided + */ + drop(): Promise; + drop(callback: Callback): void; + drop(options: DropCollectionOptions): Promise; + drop(options: DropCollectionOptions, callback: Callback): void; + drop( + options?: DropCollectionOptions | Callback, + callback?: Callback + ): Promise | void { + if (typeof options === 'function') (callback = options), (options = {}); + options = options ?? {}; + + return executeOperation( + this.s.db.s.client, + new DropCollectionOperation(this.s.db, this.collectionName, options), + callback + ); + } + + /** + * Fetches the first document that matches the filter + * + * @param filter - Query for find Operation + * @param options - Optional settings for the command + * @param callback - An optional callback, a Promise will be returned if none is provided + */ + findOne(): Promise | null>; + findOne(callback: Callback | null>): void; + findOne(filter: Filter): Promise | null>; + findOne(filter: Filter, callback: Callback | null>): void; + findOne(filter: Filter, options: FindOptions): Promise | null>; + findOne( + filter: Filter, + options: FindOptions, + callback: Callback | null> + ): void; + + // allow an override of the schema. + findOne(): Promise; + findOne(callback: Callback): void; + findOne(filter: Filter): Promise; + findOne(filter: Filter, options?: FindOptions): Promise; + findOne( + filter: Filter, + options?: FindOptions, + callback?: Callback + ): void; + + findOne( + filter?: Filter | Callback | null>, + options?: FindOptions | Callback | null>, + callback?: Callback | null> + ): Promise | null> | void { + if (callback != null && typeof callback !== 'function') { + throw new MongoInvalidArgumentError( + 'Third parameter to `findOne()` must be a callback or undefined' + ); + } + + if (typeof filter === 'function') { + callback = filter; + filter = {}; + options = {}; + } + if (typeof options === 'function') { + callback = options; + options = {}; + } + + const finalFilter = filter ?? {}; + const finalOptions = options ?? {}; + return this.find(finalFilter, finalOptions).limit(-1).batchSize(1).next(callback); + } + + /** + * Creates a cursor for a filter that can be used to iterate over results from MongoDB + * + * @param filter - The filter predicate. If unspecified, then all documents in the collection will match the predicate + */ + find(): FindCursor>; + find(filter: Filter, options?: FindOptions): FindCursor>; + find(filter: Filter, options?: FindOptions): FindCursor; + find(filter?: Filter, options?: FindOptions): FindCursor> { + if (arguments.length > 2) { + throw new MongoInvalidArgumentError( + 'Method "collection.find()" accepts at most two arguments' + ); + } + if (typeof options === 'function') { + throw new MongoInvalidArgumentError('Argument "options" must not be function'); + } + + return new FindCursor>( + this.s.db.s.client, + this.s.namespace, + filter, + resolveOptions(this as TODO_NODE_3286, options) + ); + } + + /** + * Returns the options of the collection. + * + * @param options - Optional settings for the command + * @param callback - An optional callback, a Promise will be returned if none is provided + */ + options(): Promise; + options(callback: Callback): void; + options(options: OperationOptions): Promise; + options(options: OperationOptions, callback: Callback): void; + options( + options?: OperationOptions | Callback, + callback?: Callback + ): Promise | void { + if (typeof options === 'function') (callback = options), (options = {}); + + return executeOperation( + this.s.db.s.client, + new OptionsOperation(this as TODO_NODE_3286, resolveOptions(this, options)), + callback + ); + } + + /** + * Returns if the collection is a capped collection + * + * @param options - Optional settings for the command + * @param callback - An optional callback, a Promise will be returned if none is provided + */ + isCapped(): Promise; + isCapped(callback: Callback): void; + isCapped(options: OperationOptions): Promise; + isCapped(options: OperationOptions, callback: Callback): void; + isCapped( + options?: OperationOptions | Callback, + callback?: Callback + ): Promise | void { + if (typeof options === 'function') (callback = options), (options = {}); + + return executeOperation( + this.s.db.s.client, + new IsCappedOperation(this as TODO_NODE_3286, resolveOptions(this, options)), + callback + ); + } + + /** + * Creates an index on the db and collection collection. + * + * @param indexSpec - The field name or index specification to create an index for + * @param options - Optional settings for the command + * @param callback - An optional callback, a Promise will be returned if none is provided + * + * @example + * ```js + * const collection = client.db('foo').collection('bar'); + * + * await collection.createIndex({ a: 1, b: -1 }); + * + * // Alternate syntax for { c: 1, d: -1 } that ensures order of indexes + * await collection.createIndex([ [c, 1], [d, -1] ]); + * + * // Equivalent to { e: 1 } + * await collection.createIndex('e'); + * + * // Equivalent to { f: 1, g: 1 } + * await collection.createIndex(['f', 'g']) + * + * // Equivalent to { h: 1, i: -1 } + * await collection.createIndex([ { h: 1 }, { i: -1 } ]); + * + * // Equivalent to { j: 1, k: -1, l: 2d } + * await collection.createIndex(['j', ['k', -1], { l: '2d' }]) + * ``` + */ + createIndex(indexSpec: IndexSpecification): Promise; + createIndex(indexSpec: IndexSpecification, callback: Callback): void; + createIndex(indexSpec: IndexSpecification, options: CreateIndexesOptions): Promise; + createIndex( + indexSpec: IndexSpecification, + options: CreateIndexesOptions, + callback: Callback + ): void; + createIndex( + indexSpec: IndexSpecification, + options?: CreateIndexesOptions | Callback, + callback?: Callback + ): Promise | void { + if (typeof options === 'function') (callback = options), (options = {}); + + return executeOperation( + this.s.db.s.client, + new CreateIndexOperation( + this as TODO_NODE_3286, + this.collectionName, + indexSpec, + resolveOptions(this, options) + ), + callback + ); + } + + /** + * Creates multiple indexes in the collection, this method is only supported for + * MongoDB 2.6 or higher. Earlier version of MongoDB will throw a command not supported + * error. + * + * **Note**: Unlike {@link Collection#createIndex| createIndex}, this function takes in raw index specifications. + * Index specifications are defined {@link http://docs.mongodb.org/manual/reference/command/createIndexes/| here}. + * + * @param indexSpecs - An array of index specifications to be created + * @param options - Optional settings for the command + * @param callback - An optional callback, a Promise will be returned if none is provided + * + * @example + * ```js + * const collection = client.db('foo').collection('bar'); + * await collection.createIndexes([ + * // Simple index on field fizz + * { + * key: { fizz: 1 }, + * } + * // wildcard index + * { + * key: { '$**': 1 } + * }, + * // named index on darmok and jalad + * { + * key: { darmok: 1, jalad: -1 } + * name: 'tanagra' + * } + * ]); + * ``` + */ + createIndexes(indexSpecs: IndexDescription[]): Promise; + createIndexes(indexSpecs: IndexDescription[], callback: Callback): void; + createIndexes(indexSpecs: IndexDescription[], options: CreateIndexesOptions): Promise; + createIndexes( + indexSpecs: IndexDescription[], + options: CreateIndexesOptions, + callback: Callback + ): void; + createIndexes( + indexSpecs: IndexDescription[], + options?: CreateIndexesOptions | Callback, + callback?: Callback + ): Promise | void { + if (typeof options === 'function') (callback = options), (options = {}); + options = options ? Object.assign({}, options) : {}; + if (typeof options.maxTimeMS !== 'number') delete options.maxTimeMS; + + return executeOperation( + this.s.db.s.client, + new CreateIndexesOperation( + this as TODO_NODE_3286, + this.collectionName, + indexSpecs, + resolveOptions(this, options) + ), + callback + ); + } + + /** + * Drops an index from this collection. + * + * @param indexName - Name of the index to drop. + * @param options - Optional settings for the command + * @param callback - An optional callback, a Promise will be returned if none is provided + */ + dropIndex(indexName: string): Promise; + dropIndex(indexName: string, callback: Callback): void; + dropIndex(indexName: string, options: DropIndexesOptions): Promise; + dropIndex(indexName: string, options: DropIndexesOptions, callback: Callback): void; + dropIndex( + indexName: string, + options?: DropIndexesOptions | Callback, + callback?: Callback + ): Promise | void { + if (typeof options === 'function') (callback = options), (options = {}); + options = resolveOptions(this, options); + + // Run only against primary + options.readPreference = ReadPreference.primary; + + return executeOperation( + this.s.db.s.client, + new DropIndexOperation(this as TODO_NODE_3286, indexName, options), + callback + ); + } + + /** + * Drops all indexes from this collection. + * + * @param options - Optional settings for the command + * @param callback - An optional callback, a Promise will be returned if none is provided + */ + dropIndexes(): Promise; + dropIndexes(callback: Callback): void; + dropIndexes(options: DropIndexesOptions): Promise; + dropIndexes(options: DropIndexesOptions, callback: Callback): void; + dropIndexes( + options?: DropIndexesOptions | Callback, + callback?: Callback + ): Promise | void { + if (typeof options === 'function') (callback = options), (options = {}); + + return executeOperation( + this.s.db.s.client, + new DropIndexesOperation(this as TODO_NODE_3286, resolveOptions(this, options)), + callback + ); + } + + /** + * Get the list of all indexes information for the collection. + * + * @param options - Optional settings for the command + */ + listIndexes(options?: ListIndexesOptions): ListIndexesCursor { + return new ListIndexesCursor(this as TODO_NODE_3286, resolveOptions(this, options)); + } + + /** + * Checks if one or more indexes exist on the collection, fails on first non-existing index + * + * @param indexes - One or more index names to check. + * @param options - Optional settings for the command + * @param callback - An optional callback, a Promise will be returned if none is provided + */ + indexExists(indexes: string | string[]): Promise; + indexExists(indexes: string | string[], callback: Callback): void; + indexExists(indexes: string | string[], options: IndexInformationOptions): Promise; + indexExists( + indexes: string | string[], + options: IndexInformationOptions, + callback: Callback + ): void; + indexExists( + indexes: string | string[], + options?: IndexInformationOptions | Callback, + callback?: Callback + ): Promise | void { + if (typeof options === 'function') (callback = options), (options = {}); + + return executeOperation( + this.s.db.s.client, + new IndexExistsOperation(this as TODO_NODE_3286, indexes, resolveOptions(this, options)), + callback + ); + } + + /** + * Retrieves this collections index info. + * + * @param options - Optional settings for the command + * @param callback - An optional callback, a Promise will be returned if none is provided + */ + indexInformation(): Promise; + indexInformation(callback: Callback): void; + indexInformation(options: IndexInformationOptions): Promise; + indexInformation(options: IndexInformationOptions, callback: Callback): void; + indexInformation( + options?: IndexInformationOptions | Callback, + callback?: Callback + ): Promise | void { + if (typeof options === 'function') (callback = options), (options = {}); + + return executeOperation( + this.s.db.s.client, + new IndexInformationOperation(this.s.db, this.collectionName, resolveOptions(this, options)), + callback + ); + } + + /** + * Gets an estimate of the count of documents in a collection using collection metadata. + * This will always run a count command on all server versions. + * + * due to an oversight in versions 5.0.0-5.0.8 of MongoDB, the count command, + * which estimatedDocumentCount uses in its implementation, was not included in v1 of + * the Stable API, and so users of the Stable API with estimatedDocumentCount are + * recommended to upgrade their server version to 5.0.9+ or set apiStrict: false to avoid + * encountering errors. + * + * @see {@link https://www.mongodb.com/docs/manual/reference/command/count/#behavior|Count: Behavior} + * @param options - Optional settings for the command + * @param callback - An optional callback, a Promise will be returned if none is provided + */ + estimatedDocumentCount(): Promise; + estimatedDocumentCount(callback: Callback): void; + estimatedDocumentCount(options: EstimatedDocumentCountOptions): Promise; + estimatedDocumentCount(options: EstimatedDocumentCountOptions, callback: Callback): void; + estimatedDocumentCount( + options?: EstimatedDocumentCountOptions | Callback, + callback?: Callback + ): Promise | void { + if (typeof options === 'function') (callback = options), (options = {}); + return executeOperation( + this.s.db.s.client, + new EstimatedDocumentCountOperation(this as TODO_NODE_3286, resolveOptions(this, options)), + callback + ); + } + + /** + * Gets the number of documents matching the filter. + * For a fast count of the total documents in a collection see {@link Collection#estimatedDocumentCount| estimatedDocumentCount}. + * **Note**: When migrating from {@link Collection#count| count} to {@link Collection#countDocuments| countDocuments} + * the following query operators must be replaced: + * + * | Operator | Replacement | + * | -------- | ----------- | + * | `$where` | [`$expr`][1] | + * | `$near` | [`$geoWithin`][2] with [`$center`][3] | + * | `$nearSphere` | [`$geoWithin`][2] with [`$centerSphere`][4] | + * + * [1]: https://docs.mongodb.com/manual/reference/operator/query/expr/ + * [2]: https://docs.mongodb.com/manual/reference/operator/query/geoWithin/ + * [3]: https://docs.mongodb.com/manual/reference/operator/query/center/#op._S_center + * [4]: https://docs.mongodb.com/manual/reference/operator/query/centerSphere/#op._S_centerSphere + * + * @param filter - The filter for the count + * @param options - Optional settings for the command + * @param callback - An optional callback, a Promise will be returned if none is provided + * + * @see https://docs.mongodb.com/manual/reference/operator/query/expr/ + * @see https://docs.mongodb.com/manual/reference/operator/query/geoWithin/ + * @see https://docs.mongodb.com/manual/reference/operator/query/center/#op._S_center + * @see https://docs.mongodb.com/manual/reference/operator/query/centerSphere/#op._S_centerSphere + */ + countDocuments(): Promise; + countDocuments(callback: Callback): void; + countDocuments(filter: Filter): Promise; + countDocuments(callback: Callback): void; + countDocuments(filter: Filter, options: CountDocumentsOptions): Promise; + countDocuments( + filter: Filter, + options: CountDocumentsOptions, + callback: Callback + ): void; + countDocuments(filter: Filter, callback: Callback): void; + countDocuments( + filter?: Document | CountDocumentsOptions | Callback, + options?: CountDocumentsOptions | Callback, + callback?: Callback + ): Promise | void { + if (filter == null) { + (filter = {}), (options = {}), (callback = undefined); + } else if (typeof filter === 'function') { + (callback = filter as Callback), (filter = {}), (options = {}); + } else { + if (arguments.length === 2) { + if (typeof options === 'function') (callback = options), (options = {}); + } + } + + filter ??= {}; + return executeOperation( + this.s.db.s.client, + new CountDocumentsOperation( + this as TODO_NODE_3286, + filter, + resolveOptions(this, options as CountDocumentsOptions) + ), + callback + ); + } + + /** + * The distinct command returns a list of distinct values for the given key across a collection. + * + * @param key - Field of the document to find distinct values for + * @param filter - The filter for filtering the set of documents to which we apply the distinct filter. + * @param options - Optional settings for the command + * @param callback - An optional callback, a Promise will be returned if none is provided + */ + distinct>( + key: Key + ): Promise[Key]>>>; + distinct>( + key: Key, + callback: Callback[Key]>>> + ): void; + distinct>( + key: Key, + filter: Filter + ): Promise[Key]>>>; + distinct>( + key: Key, + filter: Filter, + callback: Callback[Key]>>> + ): void; + distinct>( + key: Key, + filter: Filter, + options: DistinctOptions + ): Promise[Key]>>>; + distinct>( + key: Key, + filter: Filter, + options: DistinctOptions, + callback: Callback[Key]>>> + ): void; + + // Embedded documents overload + distinct(key: string): Promise; + distinct(key: string, callback: Callback): void; + distinct(key: string, filter: Filter): Promise; + distinct(key: string, filter: Filter, callback: Callback): void; + distinct(key: string, filter: Filter, options: DistinctOptions): Promise; + distinct( + key: string, + filter: Filter, + options: DistinctOptions, + callback: Callback + ): void; + // Implementation + distinct>( + key: Key, + filter?: Filter | DistinctOptions | Callback, + options?: DistinctOptions | Callback, + callback?: Callback + ): Promise | void { + if (typeof filter === 'function') { + (callback = filter), (filter = {}), (options = {}); + } else { + if (arguments.length === 3 && typeof options === 'function') { + (callback = options), (options = {}); + } + } + + filter ??= {}; + return executeOperation( + this.s.db.s.client, + new DistinctOperation( + this as TODO_NODE_3286, + key as TODO_NODE_3286, + filter, + resolveOptions(this, options as DistinctOptions) + ), + callback + ); + } + + /** + * Retrieve all the indexes on the collection. + * + * @param options - Optional settings for the command + * @param callback - An optional callback, a Promise will be returned if none is provided + */ + indexes(): Promise; + indexes(callback: Callback): void; + indexes(options: IndexInformationOptions): Promise; + indexes(options: IndexInformationOptions, callback: Callback): void; + indexes( + options?: IndexInformationOptions | Callback, + callback?: Callback + ): Promise | void { + if (typeof options === 'function') (callback = options), (options = {}); + + return executeOperation( + this.s.db.s.client, + new IndexesOperation(this as TODO_NODE_3286, resolveOptions(this, options)), + callback + ); + } + + /** + * Get all the collection statistics. + * + * @param options - Optional settings for the command + * @param callback - An optional callback, a Promise will be returned if none is provided + */ + stats(): Promise; + stats(callback: Callback): void; + stats(options: CollStatsOptions): Promise; + stats(options: CollStatsOptions, callback: Callback): void; + stats( + options?: CollStatsOptions | Callback, + callback?: Callback + ): Promise | void { + if (typeof options === 'function') (callback = options), (options = {}); + options = options ?? {}; + + return executeOperation( + this.s.db.s.client, + new CollStatsOperation(this as TODO_NODE_3286, options), + callback + ); + } + + /** + * Find a document and delete it in one atomic operation. Requires a write lock for the duration of the operation. + * + * @param filter - The filter used to select the document to remove + * @param options - Optional settings for the command + * @param callback - An optional callback, a Promise will be returned if none is provided + */ + findOneAndDelete(filter: Filter): Promise>; + findOneAndDelete( + filter: Filter, + options: FindOneAndDeleteOptions + ): Promise>; + findOneAndDelete(filter: Filter, callback: Callback>): void; + findOneAndDelete( + filter: Filter, + options: FindOneAndDeleteOptions, + callback: Callback> + ): void; + findOneAndDelete( + filter: Filter, + options?: FindOneAndDeleteOptions | Callback>, + callback?: Callback> + ): Promise | void { + if (typeof options === 'function') (callback = options), (options = {}); + + return executeOperation( + this.s.db.s.client, + new FindOneAndDeleteOperation( + this as TODO_NODE_3286, + filter, + resolveOptions(this, options) + ) as TODO_NODE_3286, + callback + ); + } + + /** + * Find a document and replace it in one atomic operation. Requires a write lock for the duration of the operation. + * + * @param filter - The filter used to select the document to replace + * @param replacement - The Document that replaces the matching document + * @param options - Optional settings for the command + * @param callback - An optional callback, a Promise will be returned if none is provided + */ + findOneAndReplace( + filter: Filter, + replacement: WithoutId + ): Promise>; + findOneAndReplace( + filter: Filter, + replacement: WithoutId, + callback: Callback> + ): void; + findOneAndReplace( + filter: Filter, + replacement: WithoutId, + options: FindOneAndReplaceOptions + ): Promise>; + findOneAndReplace( + filter: Filter, + replacement: WithoutId, + options: FindOneAndReplaceOptions, + callback: Callback> + ): void; + findOneAndReplace( + filter: Filter, + replacement: WithoutId, + options?: FindOneAndReplaceOptions | Callback>, + callback?: Callback> + ): Promise> | void { + if (typeof options === 'function') (callback = options), (options = {}); + + return executeOperation( + this.s.db.s.client, + new FindOneAndReplaceOperation( + this as TODO_NODE_3286, + filter, + replacement, + resolveOptions(this, options) + ) as TODO_NODE_3286, + callback + ); + } + + /** + * Find a document and update it in one atomic operation. Requires a write lock for the duration of the operation. + * + * @param filter - The filter used to select the document to update + * @param update - Update operations to be performed on the document + * @param options - Optional settings for the command + * @param callback - An optional callback, a Promise will be returned if none is provided + */ + findOneAndUpdate( + filter: Filter, + update: UpdateFilter + ): Promise>; + findOneAndUpdate( + filter: Filter, + update: UpdateFilter, + callback: Callback> + ): void; + findOneAndUpdate( + filter: Filter, + update: UpdateFilter, + options: FindOneAndUpdateOptions + ): Promise>; + findOneAndUpdate( + filter: Filter, + update: UpdateFilter, + options: FindOneAndUpdateOptions, + callback: Callback> + ): void; + findOneAndUpdate( + filter: Filter, + update: UpdateFilter, + options?: FindOneAndUpdateOptions | Callback>, + callback?: Callback> + ): Promise> | void { + if (typeof options === 'function') (callback = options), (options = {}); + + return executeOperation( + this.s.db.s.client, + new FindOneAndUpdateOperation( + this as TODO_NODE_3286, + filter, + update, + resolveOptions(this, options) + ) as TODO_NODE_3286, + callback + ); + } + + /** + * Execute an aggregation framework pipeline against the collection, needs MongoDB \>= 2.2 + * + * @param pipeline - An array of aggregation pipelines to execute + * @param options - Optional settings for the command + */ + aggregate( + pipeline: Document[] = [], + options?: AggregateOptions + ): AggregationCursor { + if (arguments.length > 2) { + throw new MongoInvalidArgumentError( + 'Method "collection.aggregate()" accepts at most two arguments' + ); + } + if (!Array.isArray(pipeline)) { + throw new MongoInvalidArgumentError( + 'Argument "pipeline" must be an array of aggregation stages' + ); + } + if (typeof options === 'function') { + throw new MongoInvalidArgumentError('Argument "options" must not be function'); + } + + return new AggregationCursor( + this.s.db.s.client, + this.s.namespace, + pipeline, + resolveOptions(this, options) + ); + } + + /** + * Create a new Change Stream, watching for new changes (insertions, updates, replacements, deletions, and invalidations) in this collection. + * + * @remarks + * watch() accepts two generic arguments for distinct usecases: + * - The first is to override the schema that may be defined for this specific collection + * - The second is to override the shape of the change stream document entirely, if it is not provided the type will default to ChangeStreamDocument of the first argument + * @example + * By just providing the first argument I can type the change to be `ChangeStreamDocument<{ _id: number }>` + * ```ts + * collection.watch<{ _id: number }>() + * .on('change', change => console.log(change._id.toFixed(4))); + * ``` + * + * @example + * Passing a second argument provides a way to reflect the type changes caused by an advanced pipeline. + * Here, we are using a pipeline to have MongoDB filter for insert changes only and add a comment. + * No need start from scratch on the ChangeStreamInsertDocument type! + * By using an intersection we can save time and ensure defaults remain the same type! + * ```ts + * collection + * .watch & { comment: string }>([ + * { $addFields: { comment: 'big changes' } }, + * { $match: { operationType: 'insert' } } + * ]) + * .on('change', change => { + * change.comment.startsWith('big'); + * change.operationType === 'insert'; + * // No need to narrow in code because the generics did that for us! + * expectType(change.fullDocument); + * }); + * ``` + * + * @param pipeline - An array of {@link https://docs.mongodb.com/manual/reference/operator/aggregation-pipeline/|aggregation pipeline stages} through which to pass change stream documents. This allows for filtering (using $match) and manipulating the change stream documents. + * @param options - Optional settings for the command + * @typeParam TLocal - Type of the data being detected by the change stream + * @typeParam TChange - Type of the whole change stream document emitted + */ + watch>( + pipeline: Document[] = [], + options: ChangeStreamOptions = {} + ): ChangeStream { + // Allow optionally not specifying a pipeline + if (!Array.isArray(pipeline)) { + options = pipeline; + pipeline = []; + } + + return new ChangeStream(this, pipeline, resolveOptions(this, options)); + } + + /** + * Run Map Reduce across a collection. Be aware that the inline option for out will return an array of results not a collection. + * + * @deprecated collection.mapReduce is deprecated. Use the aggregation pipeline instead. Visit https://docs.mongodb.com/manual/reference/map-reduce-to-aggregation-pipeline for more information on how to translate map-reduce operations to the aggregation pipeline. + * @param map - The mapping function. + * @param reduce - The reduce function. + * @param options - Optional settings for the command + * @param callback - An optional callback, a Promise will be returned if none is provided + */ + mapReduce( + map: string | MapFunction, + reduce: string | ReduceFunction + ): Promise; + mapReduce( + map: string | MapFunction, + reduce: string | ReduceFunction, + callback: Callback + ): void; + mapReduce( + map: string | MapFunction, + reduce: string | ReduceFunction, + options: MapReduceOptions + ): Promise; + mapReduce( + map: string | MapFunction, + reduce: string | ReduceFunction, + options: MapReduceOptions, + callback: Callback + ): void; + mapReduce( + map: string | MapFunction, + reduce: string | ReduceFunction, + options?: MapReduceOptions | Callback, + callback?: Callback + ): Promise | void { + emitWarningOnce( + 'collection.mapReduce is deprecated. Use the aggregation pipeline instead. Visit https://docs.mongodb.com/manual/reference/map-reduce-to-aggregation-pipeline for more information on how to translate map-reduce operations to the aggregation pipeline.' + ); + if ('function' === typeof options) (callback = options), (options = {}); + // Out must always be defined (make sure we don't break weirdly on pre 1.8+ servers) + // TODO NODE-3339: Figure out if this is still necessary given we no longer officially support pre-1.8 + if (options?.out == null) { + throw new MongoInvalidArgumentError( + 'Option "out" must be defined, see mongodb docs for possible values' + ); + } + + if ('function' === typeof map) { + map = map.toString(); + } + + if ('function' === typeof reduce) { + reduce = reduce.toString(); + } + + if ('function' === typeof options.finalize) { + options.finalize = options.finalize.toString(); + } + + return executeOperation( + this.s.db.s.client, + new MapReduceOperation( + this as TODO_NODE_3286, + map, + reduce, + resolveOptions(this, options) as TODO_NODE_3286 + ), + callback + ); + } + + /** + * Initiate an Out of order batch write operation. All operations will be buffered into insert/update/remove commands executed out of order. + * + * @throws MongoNotConnectedError + * @remarks + * **NOTE:** MongoClient must be connected prior to calling this method due to a known limitation in this legacy implemenation. + * However, `collection.bulkWrite()` provides an equivalent API that does not require prior connecting. + */ + initializeUnorderedBulkOp(options?: BulkWriteOptions): UnorderedBulkOperation { + return new UnorderedBulkOperation(this as TODO_NODE_3286, resolveOptions(this, options)); + } + + /** + * Initiate an In order bulk write operation. Operations will be serially executed in the order they are added, creating a new operation for each switch in types. + * + * @throws MongoNotConnectedError + * @remarks + * **NOTE:** MongoClient must be connected prior to calling this method due to a known limitation in this legacy implemenation. + * However, `collection.bulkWrite()` provides an equivalent API that does not require prior connecting. + */ + initializeOrderedBulkOp(options?: BulkWriteOptions): OrderedBulkOperation { + return new OrderedBulkOperation(this as TODO_NODE_3286, resolveOptions(this, options)); + } + + /** Get the db scoped logger */ + getLogger(): Logger { + return this.s.db.s.logger; + } + + get logger(): Logger { + return this.s.db.s.logger; + } + + /** + * Inserts a single document or a an array of documents into MongoDB. If documents passed in do not contain the **_id** field, + * one will be added to each of the documents missing it by the driver, mutating the document. This behavior + * can be overridden by setting the **forceServerObjectId** flag. + * + * @deprecated Use insertOne, insertMany or bulkWrite instead. + * @param docs - The documents to insert + * @param options - Optional settings for the command + * @param callback - An optional callback, a Promise will be returned if none is provided + */ + insert( + docs: OptionalUnlessRequiredId[], + options: BulkWriteOptions, + callback: Callback> + ): Promise> | void { + emitWarningOnce( + 'collection.insert is deprecated. Use insertOne, insertMany or bulkWrite instead.' + ); + if (typeof options === 'function') (callback = options), (options = {}); + options = options || { ordered: false }; + docs = !Array.isArray(docs) ? [docs] : docs; + + if (options.keepGoing === true) { + options.ordered = false; + } + + return this.insertMany(docs, options, callback); + } + + /** + * Updates documents. + * + * @deprecated use updateOne, updateMany or bulkWrite + * @param selector - The selector for the update operation. + * @param update - The update operations to be applied to the documents + * @param options - Optional settings for the command + * @param callback - An optional callback, a Promise will be returned if none is provided + */ + update( + selector: Filter, + update: UpdateFilter, + options: UpdateOptions, + callback: Callback + ): Promise | void { + emitWarningOnce( + 'collection.update is deprecated. Use updateOne, updateMany, or bulkWrite instead.' + ); + if (typeof options === 'function') (callback = options), (options = {}); + options = options ?? {}; + + return this.updateMany(selector, update, options, callback); + } + + /** + * Remove documents. + * + * @deprecated use deleteOne, deleteMany or bulkWrite + * @param selector - The selector for the update operation. + * @param options - Optional settings for the command + * @param callback - An optional callback, a Promise will be returned if none is provided + */ + remove( + selector: Filter, + options: DeleteOptions, + callback: Callback + ): Promise | void { + emitWarningOnce( + 'collection.remove is deprecated. Use deleteOne, deleteMany, or bulkWrite instead.' + ); + if (typeof options === 'function') (callback = options), (options = {}); + options = options ?? {}; + + return this.deleteMany(selector, options, callback); + } + + /** + * An estimated count of matching documents in the db to a filter. + * + * **NOTE:** This method has been deprecated, since it does not provide an accurate count of the documents + * in a collection. To obtain an accurate count of documents in the collection, use {@link Collection#countDocuments| countDocuments}. + * To obtain an estimated count of all documents in the collection, use {@link Collection#estimatedDocumentCount| estimatedDocumentCount}. + * + * @deprecated use {@link Collection#countDocuments| countDocuments} or {@link Collection#estimatedDocumentCount| estimatedDocumentCount} instead + * + * @param filter - The filter for the count. + * @param options - Optional settings for the command + * @param callback - An optional callback, a Promise will be returned if none is provided + */ + count(): Promise; + count(callback: Callback): void; + count(filter: Filter): Promise; + count(filter: Filter, callback: Callback): void; + count(filter: Filter, options: CountOptions): Promise; + count( + filter: Filter, + options: CountOptions, + callback: Callback + ): Promise | void; + count( + filter?: Filter | CountOptions | Callback, + options?: CountOptions | Callback, + callback?: Callback + ): Promise | void { + if (typeof filter === 'function') { + (callback = filter), (filter = {}), (options = {}); + } else { + if (typeof options === 'function') (callback = options), (options = {}); + } + + filter ??= {}; + return executeOperation( + this.s.db.s.client, + new CountOperation( + MongoDBNamespace.fromString(this.namespace), + filter, + resolveOptions(this, options) + ), + callback + ); + } +} diff --git a/ts-ticket-office-service/node_modules/mongodb/src/connection_string.ts b/ts-ticket-office-service/node_modules/mongodb/src/connection_string.ts new file mode 100644 index 000000000..5b3d494a7 --- /dev/null +++ b/ts-ticket-office-service/node_modules/mongodb/src/connection_string.ts @@ -0,0 +1,1267 @@ +import * as dns from 'dns'; +import * as fs from 'fs'; +import ConnectionString from 'mongodb-connection-string-url'; +import { URLSearchParams } from 'url'; + +import type { Document } from './bson'; +import { MongoCredentials } from './cmap/auth/mongo_credentials'; +import { AUTH_MECHS_AUTH_SRC_EXTERNAL, AuthMechanism } from './cmap/auth/providers'; +import { Compressor, CompressorName } from './cmap/wire_protocol/compression'; +import { Encrypter } from './encrypter'; +import { MongoAPIError, MongoInvalidArgumentError, MongoParseError } from './error'; +import { Logger, LoggerLevel } from './logger'; +import { + DriverInfo, + MongoClient, + MongoClientOptions, + MongoOptions, + PkFactory, + ServerApi, + ServerApiVersion +} from './mongo_client'; +import { PromiseProvider } from './promise_provider'; +import { ReadConcern, ReadConcernLevel } from './read_concern'; +import { ReadPreference, ReadPreferenceMode } from './read_preference'; +import type { TagSet } from './sdam/server_description'; +import { + AnyOptions, + Callback, + DEFAULT_PK_FACTORY, + emitWarning, + emitWarningOnce, + HostAddress, + isRecord, + makeClientMetadata, + setDifference +} from './utils'; +import { W, WriteConcern } from './write_concern'; + +const VALID_TXT_RECORDS = ['authSource', 'replicaSet', 'loadBalanced']; + +const LB_SINGLE_HOST_ERROR = 'loadBalanced option only supported with a single host in the URI'; +const LB_REPLICA_SET_ERROR = 'loadBalanced option not supported with a replicaSet option'; +const LB_DIRECT_CONNECTION_ERROR = + 'loadBalanced option not supported when directConnection is provided'; + +/** + * Determines whether a provided address matches the provided parent domain in order + * to avoid certain attack vectors. + * + * @param srvAddress - The address to check against a domain + * @param parentDomain - The domain to check the provided address against + * @returns Whether the provided address matches the parent domain + */ +function matchesParentDomain(srvAddress: string, parentDomain: string): boolean { + const regex = /^.*?\./; + const srv = `.${srvAddress.replace(regex, '')}`; + const parent = `.${parentDomain.replace(regex, '')}`; + return srv.endsWith(parent); +} + +/** + * Lookup a `mongodb+srv` connection string, combine the parts and reparse it as a normal + * connection string. + * + * @param uri - The connection string to parse + * @param options - Optional user provided connection string options + */ +export function resolveSRVRecord(options: MongoOptions, callback: Callback): void { + if (typeof options.srvHost !== 'string') { + return callback(new MongoAPIError('Option "srvHost" must not be empty')); + } + + if (options.srvHost.split('.').length < 3) { + // TODO(NODE-3484): Replace with MongoConnectionStringError + return callback(new MongoAPIError('URI must include hostname, domain name, and tld')); + } + + // Resolve the SRV record and use the result as the list of hosts to connect to. + const lookupAddress = options.srvHost; + dns.resolveSrv(`_${options.srvServiceName}._tcp.${lookupAddress}`, (err, addresses) => { + if (err) return callback(err); + + if (addresses.length === 0) { + return callback(new MongoAPIError('No addresses found at host')); + } + + for (const { name } of addresses) { + if (!matchesParentDomain(name, lookupAddress)) { + return callback(new MongoAPIError('Server record does not share hostname with parent URI')); + } + } + + const hostAddresses = addresses.map(r => + HostAddress.fromString(`${r.name}:${r.port ?? 27017}`) + ); + + const lbError = validateLoadBalancedOptions(hostAddresses, options, true); + if (lbError) { + return callback(lbError); + } + + // Resolve TXT record and add options from there if they exist. + dns.resolveTxt(lookupAddress, (err, record) => { + if (err) { + if (err.code !== 'ENODATA' && err.code !== 'ENOTFOUND') { + return callback(err); + } + } else { + if (record.length > 1) { + return callback(new MongoParseError('Multiple text records not allowed')); + } + + const txtRecordOptions = new URLSearchParams(record[0].join('')); + const txtRecordOptionKeys = [...txtRecordOptions.keys()]; + if (txtRecordOptionKeys.some(key => !VALID_TXT_RECORDS.includes(key))) { + return callback( + new MongoParseError(`Text record may only set any of: ${VALID_TXT_RECORDS.join(', ')}`) + ); + } + + if (VALID_TXT_RECORDS.some(option => txtRecordOptions.get(option) === '')) { + return callback(new MongoParseError('Cannot have empty URI params in DNS TXT Record')); + } + + const source = txtRecordOptions.get('authSource') ?? undefined; + const replicaSet = txtRecordOptions.get('replicaSet') ?? undefined; + const loadBalanced = txtRecordOptions.get('loadBalanced') ?? undefined; + + if ( + !options.userSpecifiedAuthSource && + source && + options.credentials && + !AUTH_MECHS_AUTH_SRC_EXTERNAL.has(options.credentials.mechanism) + ) { + options.credentials = MongoCredentials.merge(options.credentials, { source }); + } + + if (!options.userSpecifiedReplicaSet && replicaSet) { + options.replicaSet = replicaSet; + } + + if (loadBalanced === 'true') { + options.loadBalanced = true; + } + + if (options.replicaSet && options.srvMaxHosts > 0) { + return callback(new MongoParseError('Cannot combine replicaSet option with srvMaxHosts')); + } + + const lbError = validateLoadBalancedOptions(hostAddresses, options, true); + if (lbError) { + return callback(lbError); + } + } + + callback(undefined, hostAddresses); + }); + }); +} + +/** + * Checks if TLS options are valid + * + * @param options - The options used for options parsing + * @throws MongoParseError if TLS options are invalid + */ +export function checkTLSOptions(options: AnyOptions): void { + if (!options) return; + const check = (a: string, b: string) => { + if (Reflect.has(options, a) && Reflect.has(options, b)) { + throw new MongoParseError(`The '${a}' option cannot be used with '${b}'`); + } + }; + check('tlsInsecure', 'tlsAllowInvalidCertificates'); + check('tlsInsecure', 'tlsAllowInvalidHostnames'); + check('tlsInsecure', 'tlsDisableCertificateRevocationCheck'); + check('tlsInsecure', 'tlsDisableOCSPEndpointCheck'); + check('tlsAllowInvalidCertificates', 'tlsDisableCertificateRevocationCheck'); + check('tlsAllowInvalidCertificates', 'tlsDisableOCSPEndpointCheck'); + check('tlsDisableCertificateRevocationCheck', 'tlsDisableOCSPEndpointCheck'); +} + +const TRUTHS = new Set(['true', 't', '1', 'y', 'yes']); +const FALSEHOODS = new Set(['false', 'f', '0', 'n', 'no', '-1']); +function getBoolean(name: string, value: unknown): boolean { + if (typeof value === 'boolean') return value; + const valueString = String(value).toLowerCase(); + if (TRUTHS.has(valueString)) { + if (valueString !== 'true') { + emitWarningOnce( + `deprecated value for ${name} : ${valueString} - please update to ${name} : true instead` + ); + } + return true; + } + if (FALSEHOODS.has(valueString)) { + if (valueString !== 'false') { + emitWarningOnce( + `deprecated value for ${name} : ${valueString} - please update to ${name} : false instead` + ); + } + return false; + } + throw new MongoParseError(`Expected ${name} to be stringified boolean value, got: ${value}`); +} + +function getInt(name: string, value: unknown): number { + if (typeof value === 'number') return Math.trunc(value); + const parsedValue = Number.parseInt(String(value), 10); + if (!Number.isNaN(parsedValue)) return parsedValue; + throw new MongoParseError(`Expected ${name} to be stringified int value, got: ${value}`); +} + +function getUint(name: string, value: unknown): number { + const parsedValue = getInt(name, value); + if (parsedValue < 0) { + throw new MongoParseError(`${name} can only be a positive int value, got: ${value}`); + } + return parsedValue; +} + +function* entriesFromString(value: string): Generator<[string, string]> { + const keyValuePairs = value.split(','); + for (const keyValue of keyValuePairs) { + const [key, value] = keyValue.split(':'); + if (value == null) { + throw new MongoParseError('Cannot have undefined values in key value pairs'); + } + + yield [key, value]; + } +} + +class CaseInsensitiveMap extends Map { + constructor(entries: Array<[string, any]> = []) { + super(entries.map(([k, v]) => [k.toLowerCase(), v])); + } + override has(k: string) { + return super.has(k.toLowerCase()); + } + override get(k: string) { + return super.get(k.toLowerCase()); + } + override set(k: string, v: any) { + return super.set(k.toLowerCase(), v); + } + override delete(k: string): boolean { + return super.delete(k.toLowerCase()); + } +} + +export function parseOptions( + uri: string, + mongoClient: MongoClient | MongoClientOptions | undefined = undefined, + options: MongoClientOptions = {} +): MongoOptions { + if (mongoClient != null && !(mongoClient instanceof MongoClient)) { + options = mongoClient; + mongoClient = undefined; + } + + const url = new ConnectionString(uri); + const { hosts, isSRV } = url; + + const mongoOptions = Object.create(null); + + // Feature flags + for (const flag of Object.getOwnPropertySymbols(options)) { + if (FEATURE_FLAGS.has(flag)) { + mongoOptions[flag] = options[flag]; + } + } + + mongoOptions.hosts = isSRV ? [] : hosts.map(HostAddress.fromString); + + const urlOptions = new CaseInsensitiveMap(); + + if (url.pathname !== '/' && url.pathname !== '') { + const dbName = decodeURIComponent( + url.pathname[0] === '/' ? url.pathname.slice(1) : url.pathname + ); + if (dbName) { + urlOptions.set('dbName', [dbName]); + } + } + + if (url.username !== '') { + const auth: Document = { + username: decodeURIComponent(url.username) + }; + + if (typeof url.password === 'string') { + auth.password = decodeURIComponent(url.password); + } + + urlOptions.set('auth', [auth]); + } + + for (const key of url.searchParams.keys()) { + const values = [...url.searchParams.getAll(key)]; + + if (values.includes('')) { + throw new MongoAPIError('URI cannot contain options with no value'); + } + + if (!urlOptions.has(key)) { + urlOptions.set(key, values); + } + } + + const objectOptions = new CaseInsensitiveMap( + Object.entries(options).filter(([, v]) => v != null) + ); + + // Validate options that can only be provided by one of uri or object + + if (urlOptions.has('serverApi')) { + throw new MongoParseError( + 'URI cannot contain `serverApi`, it can only be passed to the client' + ); + } + + if (objectOptions.has('loadBalanced')) { + throw new MongoParseError('loadBalanced is only a valid option in the URI'); + } + + // All option collection + + const allOptions = new CaseInsensitiveMap(); + + const allKeys = new Set([ + ...urlOptions.keys(), + ...objectOptions.keys(), + ...DEFAULT_OPTIONS.keys() + ]); + + for (const key of allKeys) { + const values = []; + const objectOptionValue = objectOptions.get(key); + if (objectOptionValue != null) { + values.push(objectOptionValue); + } + const urlValue = urlOptions.get(key); + if (urlValue != null) { + values.push(...urlValue); + } + const defaultOptionsValue = DEFAULT_OPTIONS.get(key); + if (defaultOptionsValue != null) { + values.push(defaultOptionsValue); + } + allOptions.set(key, values); + } + + if (allOptions.has('tlsCertificateKeyFile') && !allOptions.has('tlsCertificateFile')) { + allOptions.set('tlsCertificateFile', allOptions.get('tlsCertificateKeyFile')); + } + + if (allOptions.has('tls') || allOptions.has('ssl')) { + const tlsAndSslOpts = (allOptions.get('tls') || []) + .concat(allOptions.get('ssl') || []) + .map(getBoolean.bind(null, 'tls/ssl')); + if (new Set(tlsAndSslOpts).size !== 1) { + throw new MongoParseError('All values of tls/ssl must be the same.'); + } + } + + const unsupportedOptions = setDifference( + allKeys, + Array.from(Object.keys(OPTIONS)).map(s => s.toLowerCase()) + ); + if (unsupportedOptions.size !== 0) { + const optionWord = unsupportedOptions.size > 1 ? 'options' : 'option'; + const isOrAre = unsupportedOptions.size > 1 ? 'are' : 'is'; + throw new MongoParseError( + `${optionWord} ${Array.from(unsupportedOptions).join(', ')} ${isOrAre} not supported` + ); + } + + // Option parsing and setting + + for (const [key, descriptor] of Object.entries(OPTIONS)) { + const values = allOptions.get(key); + if (!values || values.length === 0) continue; + setOption(mongoOptions, key, descriptor, values); + } + + if (mongoOptions.credentials) { + const isGssapi = mongoOptions.credentials.mechanism === AuthMechanism.MONGODB_GSSAPI; + const isX509 = mongoOptions.credentials.mechanism === AuthMechanism.MONGODB_X509; + const isAws = mongoOptions.credentials.mechanism === AuthMechanism.MONGODB_AWS; + if ( + (isGssapi || isX509) && + allOptions.has('authSource') && + mongoOptions.credentials.source !== '$external' + ) { + // If authSource was explicitly given and its incorrect, we error + throw new MongoParseError( + `${mongoOptions.credentials} can only have authSource set to '$external'` + ); + } + + if (!(isGssapi || isX509 || isAws) && mongoOptions.dbName && !allOptions.has('authSource')) { + // inherit the dbName unless GSSAPI or X509, then silently ignore dbName + // and there was no specific authSource given + mongoOptions.credentials = MongoCredentials.merge(mongoOptions.credentials, { + source: mongoOptions.dbName + }); + } + + mongoOptions.credentials.validate(); + + // Check if the only auth related option provided was authSource, if so we can remove credentials + if ( + mongoOptions.credentials.password === '' && + mongoOptions.credentials.username === '' && + mongoOptions.credentials.mechanism === AuthMechanism.MONGODB_DEFAULT && + Object.keys(mongoOptions.credentials.mechanismProperties).length === 0 + ) { + delete mongoOptions.credentials; + } + } + + if (!mongoOptions.dbName) { + // dbName default is applied here because of the credential validation above + mongoOptions.dbName = 'test'; + } + + checkTLSOptions(mongoOptions); + + if (options.promiseLibrary) PromiseProvider.set(options.promiseLibrary); + + const lbError = validateLoadBalancedOptions(hosts, mongoOptions, isSRV); + if (lbError) { + throw lbError; + } + if (mongoClient && mongoOptions.autoEncryption) { + Encrypter.checkForMongoCrypt(); + mongoOptions.encrypter = new Encrypter(mongoClient, uri, options); + mongoOptions.autoEncrypter = mongoOptions.encrypter.autoEncrypter; + } + + // Potential SRV Overrides and SRV connection string validations + + mongoOptions.userSpecifiedAuthSource = + objectOptions.has('authSource') || urlOptions.has('authSource'); + mongoOptions.userSpecifiedReplicaSet = + objectOptions.has('replicaSet') || urlOptions.has('replicaSet'); + + if (isSRV) { + // SRV Record is resolved upon connecting + mongoOptions.srvHost = hosts[0]; + + if (mongoOptions.directConnection) { + throw new MongoAPIError('SRV URI does not support directConnection'); + } + + if (mongoOptions.srvMaxHosts > 0 && typeof mongoOptions.replicaSet === 'string') { + throw new MongoParseError('Cannot use srvMaxHosts option with replicaSet'); + } + + // SRV turns on TLS by default, but users can override and turn it off + const noUserSpecifiedTLS = !objectOptions.has('tls') && !urlOptions.has('tls'); + const noUserSpecifiedSSL = !objectOptions.has('ssl') && !urlOptions.has('ssl'); + if (noUserSpecifiedTLS && noUserSpecifiedSSL) { + mongoOptions.tls = true; + } + } else { + const userSpecifiedSrvOptions = + urlOptions.has('srvMaxHosts') || + objectOptions.has('srvMaxHosts') || + urlOptions.has('srvServiceName') || + objectOptions.has('srvServiceName'); + + if (userSpecifiedSrvOptions) { + throw new MongoParseError( + 'Cannot use srvMaxHosts or srvServiceName with a non-srv connection string' + ); + } + } + + if (mongoOptions.directConnection && mongoOptions.hosts.length !== 1) { + throw new MongoParseError('directConnection option requires exactly one host'); + } + + if ( + !mongoOptions.proxyHost && + (mongoOptions.proxyPort || mongoOptions.proxyUsername || mongoOptions.proxyPassword) + ) { + throw new MongoParseError('Must specify proxyHost if other proxy options are passed'); + } + + if ( + (mongoOptions.proxyUsername && !mongoOptions.proxyPassword) || + (!mongoOptions.proxyUsername && mongoOptions.proxyPassword) + ) { + throw new MongoParseError('Can only specify both of proxy username/password or neither'); + } + + const proxyOptions = ['proxyHost', 'proxyPort', 'proxyUsername', 'proxyPassword'].map( + key => urlOptions.get(key) ?? [] + ); + + if (proxyOptions.some(options => options.length > 1)) { + throw new MongoParseError( + 'Proxy options cannot be specified multiple times in the connection string' + ); + } + + return mongoOptions; +} + +function validateLoadBalancedOptions( + hosts: HostAddress[] | string[], + mongoOptions: MongoOptions, + isSrv: boolean +): MongoParseError | undefined { + if (mongoOptions.loadBalanced) { + if (hosts.length > 1) { + return new MongoParseError(LB_SINGLE_HOST_ERROR); + } + if (mongoOptions.replicaSet) { + return new MongoParseError(LB_REPLICA_SET_ERROR); + } + if (mongoOptions.directConnection) { + return new MongoParseError(LB_DIRECT_CONNECTION_ERROR); + } + + if (isSrv && mongoOptions.srvMaxHosts > 0) { + return new MongoParseError('Cannot limit srv hosts with loadBalanced enabled'); + } + } + return; +} + +function setOption( + mongoOptions: any, + key: string, + descriptor: OptionDescriptor, + values: unknown[] +) { + const { target, type, transform, deprecated } = descriptor; + const name = target ?? key; + + if (deprecated) { + const deprecatedMsg = typeof deprecated === 'string' ? `: ${deprecated}` : ''; + emitWarning(`${key} is a deprecated option${deprecatedMsg}`); + } + + switch (type) { + case 'boolean': + mongoOptions[name] = getBoolean(name, values[0]); + break; + case 'int': + mongoOptions[name] = getInt(name, values[0]); + break; + case 'uint': + mongoOptions[name] = getUint(name, values[0]); + break; + case 'string': + if (values[0] == null) { + break; + } + mongoOptions[name] = String(values[0]); + break; + case 'record': + if (!isRecord(values[0])) { + throw new MongoParseError(`${name} must be an object`); + } + mongoOptions[name] = values[0]; + break; + case 'any': + mongoOptions[name] = values[0]; + break; + default: { + if (!transform) { + throw new MongoParseError('Descriptors missing a type must define a transform'); + } + const transformValue = transform({ name, options: mongoOptions, values }); + mongoOptions[name] = transformValue; + break; + } + } +} + +interface OptionDescriptor { + target?: string; + type?: 'boolean' | 'int' | 'uint' | 'record' | 'string' | 'any'; + default?: any; + + deprecated?: boolean | string; + /** + * @param name - the original option name + * @param options - the options so far for resolution + * @param values - the possible values in precedence order + */ + transform?: (args: { name: string; options: MongoOptions; values: unknown[] }) => unknown; +} + +export const OPTIONS = { + appName: { + target: 'metadata', + transform({ options, values: [value] }): DriverInfo { + return makeClientMetadata({ ...options.driverInfo, appName: String(value) }); + } + }, + auth: { + target: 'credentials', + transform({ name, options, values: [value] }): MongoCredentials { + if (!isRecord(value, ['username', 'password'] as const)) { + throw new MongoParseError( + `${name} must be an object with 'username' and 'password' properties` + ); + } + return MongoCredentials.merge(options.credentials, { + username: value.username, + password: value.password + }); + } + }, + authMechanism: { + target: 'credentials', + transform({ options, values: [value] }): MongoCredentials { + const mechanisms = Object.values(AuthMechanism); + const [mechanism] = mechanisms.filter(m => m.match(RegExp(String.raw`\b${value}\b`, 'i'))); + if (!mechanism) { + throw new MongoParseError(`authMechanism one of ${mechanisms}, got ${value}`); + } + let source = options.credentials?.source; + if ( + mechanism === AuthMechanism.MONGODB_PLAIN || + AUTH_MECHS_AUTH_SRC_EXTERNAL.has(mechanism) + ) { + // some mechanisms have '$external' as the Auth Source + source = '$external'; + } + + let password = options.credentials?.password; + if (mechanism === AuthMechanism.MONGODB_X509 && password === '') { + password = undefined; + } + return MongoCredentials.merge(options.credentials, { + mechanism, + source, + password + }); + } + }, + authMechanismProperties: { + target: 'credentials', + transform({ options, values: [optionValue] }): MongoCredentials { + if (typeof optionValue === 'string') { + const mechanismProperties = Object.create(null); + + for (const [key, value] of entriesFromString(optionValue)) { + try { + mechanismProperties[key] = getBoolean(key, value); + } catch { + mechanismProperties[key] = value; + } + } + + return MongoCredentials.merge(options.credentials, { + mechanismProperties + }); + } + if (!isRecord(optionValue)) { + throw new MongoParseError('AuthMechanismProperties must be an object'); + } + return MongoCredentials.merge(options.credentials, { mechanismProperties: optionValue }); + } + }, + authSource: { + target: 'credentials', + transform({ options, values: [value] }): MongoCredentials { + const source = String(value); + return MongoCredentials.merge(options.credentials, { source }); + } + }, + autoEncryption: { + type: 'record' + }, + bsonRegExp: { + type: 'boolean' + }, + serverApi: { + target: 'serverApi', + transform({ values: [version] }): ServerApi { + const serverApiToValidate = + typeof version === 'string' ? ({ version } as ServerApi) : (version as ServerApi); + const versionToValidate = serverApiToValidate && serverApiToValidate.version; + if (!versionToValidate) { + throw new MongoParseError( + `Invalid \`serverApi\` property; must specify a version from the following enum: ["${Object.values( + ServerApiVersion + ).join('", "')}"]` + ); + } + if (!Object.values(ServerApiVersion).some(v => v === versionToValidate)) { + throw new MongoParseError( + `Invalid server API version=${versionToValidate}; must be in the following enum: ["${Object.values( + ServerApiVersion + ).join('", "')}"]` + ); + } + return serverApiToValidate; + } + }, + checkKeys: { + type: 'boolean' + }, + compressors: { + default: 'none', + target: 'compressors', + transform({ values }) { + const compressionList = new Set(); + for (const compVal of values as (CompressorName[] | string)[]) { + const compValArray = typeof compVal === 'string' ? compVal.split(',') : compVal; + if (!Array.isArray(compValArray)) { + throw new MongoInvalidArgumentError( + 'compressors must be an array or a comma-delimited list of strings' + ); + } + for (const c of compValArray) { + if (Object.keys(Compressor).includes(String(c))) { + compressionList.add(String(c)); + } else { + throw new MongoInvalidArgumentError( + `${c} is not a valid compression mechanism. Must be one of: ${Object.keys( + Compressor + )}.` + ); + } + } + } + return [...compressionList]; + } + }, + connectTimeoutMS: { + default: 30000, + type: 'uint' + }, + dbName: { + type: 'string' + }, + directConnection: { + default: false, + type: 'boolean' + }, + driverInfo: { + target: 'metadata', + default: makeClientMetadata(), + transform({ options, values: [value] }) { + if (!isRecord(value)) throw new MongoParseError('DriverInfo must be an object'); + return makeClientMetadata({ + driverInfo: value, + appName: options.metadata?.application?.name + }); + } + }, + enableUtf8Validation: { type: 'boolean', default: true }, + family: { + transform({ name, values: [value] }): 4 | 6 { + const transformValue = getInt(name, value); + if (transformValue === 4 || transformValue === 6) { + return transformValue; + } + throw new MongoParseError(`Option 'family' must be 4 or 6 got ${transformValue}.`); + } + }, + fieldsAsRaw: { + type: 'record' + }, + forceServerObjectId: { + default: false, + type: 'boolean' + }, + fsync: { + deprecated: 'Please use journal instead', + target: 'writeConcern', + transform({ name, options, values: [value] }): WriteConcern { + const wc = WriteConcern.fromOptions({ + writeConcern: { + ...options.writeConcern, + fsync: getBoolean(name, value) + } + }); + if (!wc) throw new MongoParseError(`Unable to make a writeConcern from fsync=${value}`); + return wc; + } + } as OptionDescriptor, + heartbeatFrequencyMS: { + default: 10000, + type: 'uint' + }, + ignoreUndefined: { + type: 'boolean' + }, + j: { + deprecated: 'Please use journal instead', + target: 'writeConcern', + transform({ name, options, values: [value] }): WriteConcern { + const wc = WriteConcern.fromOptions({ + writeConcern: { + ...options.writeConcern, + journal: getBoolean(name, value) + } + }); + if (!wc) throw new MongoParseError(`Unable to make a writeConcern from journal=${value}`); + return wc; + } + } as OptionDescriptor, + journal: { + target: 'writeConcern', + transform({ name, options, values: [value] }): WriteConcern { + const wc = WriteConcern.fromOptions({ + writeConcern: { + ...options.writeConcern, + journal: getBoolean(name, value) + } + }); + if (!wc) throw new MongoParseError(`Unable to make a writeConcern from journal=${value}`); + return wc; + } + }, + keepAlive: { + default: true, + type: 'boolean' + }, + keepAliveInitialDelay: { + default: 120000, + type: 'uint' + }, + loadBalanced: { + default: false, + type: 'boolean' + }, + localThresholdMS: { + default: 15, + type: 'uint' + }, + logger: { + default: new Logger('MongoClient'), + transform({ values: [value] }) { + if (value instanceof Logger) { + return value; + } + emitWarning('Alternative loggers might not be supported'); + // TODO: make Logger an interface that others can implement, make usage consistent in driver + // DRIVERS-1204 + return; + } + }, + loggerLevel: { + target: 'logger', + transform({ values: [value] }) { + return new Logger('MongoClient', { loggerLevel: value as LoggerLevel }); + } + }, + maxConnecting: { + default: 2, + transform({ name, values: [value] }): number { + const maxConnecting = getUint(name, value); + if (maxConnecting === 0) { + throw new MongoInvalidArgumentError('maxConnecting must be > 0 if specified'); + } + return maxConnecting; + } + }, + maxIdleTimeMS: { + default: 0, + type: 'uint' + }, + maxPoolSize: { + default: 100, + type: 'uint' + }, + maxStalenessSeconds: { + target: 'readPreference', + transform({ name, options, values: [value] }) { + const maxStalenessSeconds = getUint(name, value); + if (options.readPreference) { + return ReadPreference.fromOptions({ + readPreference: { ...options.readPreference, maxStalenessSeconds } + }); + } else { + return new ReadPreference('secondary', undefined, { maxStalenessSeconds }); + } + } + }, + minInternalBufferSize: { + type: 'uint' + }, + minPoolSize: { + default: 0, + type: 'uint' + }, + minHeartbeatFrequencyMS: { + default: 500, + type: 'uint' + }, + monitorCommands: { + default: false, + type: 'boolean' + }, + name: { + target: 'driverInfo', + transform({ values: [value], options }) { + return { ...options.driverInfo, name: String(value) }; + } + } as OptionDescriptor, + noDelay: { + default: true, + type: 'boolean' + }, + pkFactory: { + default: DEFAULT_PK_FACTORY, + transform({ values: [value] }): PkFactory { + if (isRecord(value, ['createPk'] as const) && typeof value.createPk === 'function') { + return value as PkFactory; + } + throw new MongoParseError( + `Option pkFactory must be an object with a createPk function, got ${value}` + ); + } + }, + promiseLibrary: { + deprecated: true, + type: 'any' + }, + promoteBuffers: { + type: 'boolean' + }, + promoteLongs: { + type: 'boolean' + }, + promoteValues: { + type: 'boolean' + }, + proxyHost: { + type: 'string' + }, + proxyPassword: { + type: 'string' + }, + proxyPort: { + type: 'uint' + }, + proxyUsername: { + type: 'string' + }, + raw: { + default: false, + type: 'boolean' + }, + readConcern: { + transform({ values: [value], options }) { + if (value instanceof ReadConcern || isRecord(value, ['level'] as const)) { + return ReadConcern.fromOptions({ ...options.readConcern, ...value } as any); + } + throw new MongoParseError(`ReadConcern must be an object, got ${JSON.stringify(value)}`); + } + }, + readConcernLevel: { + target: 'readConcern', + transform({ values: [level], options }) { + return ReadConcern.fromOptions({ + ...options.readConcern, + level: level as ReadConcernLevel + }); + } + }, + readPreference: { + default: ReadPreference.primary, + transform({ values: [value], options }) { + if (value instanceof ReadPreference) { + return ReadPreference.fromOptions({ + readPreference: { ...options.readPreference, ...value }, + ...value + } as any); + } + if (isRecord(value, ['mode'] as const)) { + const rp = ReadPreference.fromOptions({ + readPreference: { ...options.readPreference, ...value }, + ...value + } as any); + if (rp) return rp; + else throw new MongoParseError(`Cannot make read preference from ${JSON.stringify(value)}`); + } + if (typeof value === 'string') { + const rpOpts = { + hedge: options.readPreference?.hedge, + maxStalenessSeconds: options.readPreference?.maxStalenessSeconds + }; + return new ReadPreference( + value as ReadPreferenceMode, + options.readPreference?.tags, + rpOpts + ); + } + throw new MongoParseError(`Unknown ReadPreference value: ${value}`); + } + }, + readPreferenceTags: { + target: 'readPreference', + transform({ + values, + options + }: { + values: Array[]>; + options: MongoClientOptions; + }) { + const tags: Array> = Array.isArray(values[0]) + ? values[0] + : (values as Array); + const readPreferenceTags = []; + for (const tag of tags) { + const readPreferenceTag: TagSet = Object.create(null); + if (typeof tag === 'string') { + for (const [k, v] of entriesFromString(tag)) { + readPreferenceTag[k] = v; + } + } + if (isRecord(tag)) { + for (const [k, v] of Object.entries(tag)) { + readPreferenceTag[k] = v; + } + } + readPreferenceTags.push(readPreferenceTag); + } + return ReadPreference.fromOptions({ + readPreference: options.readPreference, + readPreferenceTags + }); + } + }, + replicaSet: { + type: 'string' + }, + retryReads: { + default: true, + type: 'boolean' + }, + retryWrites: { + default: true, + type: 'boolean' + }, + serializeFunctions: { + type: 'boolean' + }, + serverSelectionTimeoutMS: { + default: 30000, + type: 'uint' + }, + servername: { + type: 'string' + }, + socketTimeoutMS: { + default: 0, + type: 'uint' + }, + srvMaxHosts: { + type: 'uint', + default: 0 + }, + srvServiceName: { + type: 'string', + default: 'mongodb' + }, + ssl: { + target: 'tls', + type: 'boolean' + }, + sslCA: { + target: 'ca', + transform({ values: [value] }) { + return fs.readFileSync(String(value), { encoding: 'ascii' }); + } + }, + sslCRL: { + target: 'crl', + transform({ values: [value] }) { + return fs.readFileSync(String(value), { encoding: 'ascii' }); + } + }, + sslCert: { + target: 'cert', + transform({ values: [value] }) { + return fs.readFileSync(String(value), { encoding: 'ascii' }); + } + }, + sslKey: { + target: 'key', + transform({ values: [value] }) { + return fs.readFileSync(String(value), { encoding: 'ascii' }); + } + }, + sslPass: { + deprecated: true, + target: 'passphrase', + type: 'string' + }, + sslValidate: { + target: 'rejectUnauthorized', + type: 'boolean' + }, + tls: { + type: 'boolean' + }, + tlsAllowInvalidCertificates: { + target: 'rejectUnauthorized', + transform({ name, values: [value] }) { + // allowInvalidCertificates is the inverse of rejectUnauthorized + return !getBoolean(name, value); + } + }, + tlsAllowInvalidHostnames: { + target: 'checkServerIdentity', + transform({ name, values: [value] }) { + // tlsAllowInvalidHostnames means setting the checkServerIdentity function to a noop + return getBoolean(name, value) ? () => undefined : undefined; + } + }, + tlsCAFile: { + target: 'ca', + transform({ values: [value] }) { + return fs.readFileSync(String(value), { encoding: 'ascii' }); + } + }, + tlsCertificateFile: { + target: 'cert', + transform({ values: [value] }) { + return fs.readFileSync(String(value), { encoding: 'ascii' }); + } + }, + tlsCertificateKeyFile: { + target: 'key', + transform({ values: [value] }) { + return fs.readFileSync(String(value), { encoding: 'ascii' }); + } + }, + tlsCertificateKeyFilePassword: { + target: 'passphrase', + type: 'any' + }, + tlsInsecure: { + transform({ name, options, values: [value] }) { + const tlsInsecure = getBoolean(name, value); + if (tlsInsecure) { + options.checkServerIdentity = () => undefined; + options.rejectUnauthorized = false; + } else { + options.checkServerIdentity = options.tlsAllowInvalidHostnames + ? () => undefined + : undefined; + options.rejectUnauthorized = options.tlsAllowInvalidCertificates ? false : true; + } + return tlsInsecure; + } + }, + w: { + target: 'writeConcern', + transform({ values: [value], options }) { + return WriteConcern.fromOptions({ writeConcern: { ...options.writeConcern, w: value as W } }); + } + }, + waitQueueTimeoutMS: { + default: 0, + type: 'uint' + }, + writeConcern: { + target: 'writeConcern', + transform({ values: [value], options }) { + if (isRecord(value) || value instanceof WriteConcern) { + return WriteConcern.fromOptions({ + writeConcern: { + ...options.writeConcern, + ...value + } + }); + } else if (value === 'majority' || typeof value === 'number') { + return WriteConcern.fromOptions({ + writeConcern: { + ...options.writeConcern, + w: value + } + }); + } + + throw new MongoParseError(`Invalid WriteConcern cannot parse: ${JSON.stringify(value)}`); + } + } as OptionDescriptor, + wtimeout: { + deprecated: 'Please use wtimeoutMS instead', + target: 'writeConcern', + transform({ values: [value], options }) { + const wc = WriteConcern.fromOptions({ + writeConcern: { + ...options.writeConcern, + wtimeout: getUint('wtimeout', value) + } + }); + if (wc) return wc; + throw new MongoParseError(`Cannot make WriteConcern from wtimeout`); + } + } as OptionDescriptor, + wtimeoutMS: { + target: 'writeConcern', + transform({ values: [value], options }) { + const wc = WriteConcern.fromOptions({ + writeConcern: { + ...options.writeConcern, + wtimeoutMS: getUint('wtimeoutMS', value) + } + }); + if (wc) return wc; + throw new MongoParseError(`Cannot make WriteConcern from wtimeout`); + } + }, + zlibCompressionLevel: { + default: 0, + type: 'int' + }, + // Custom types for modifying core behavior + connectionType: { type: 'any' }, + srvPoller: { type: 'any' }, + // Accepted NodeJS Options + minDHSize: { type: 'any' }, + pskCallback: { type: 'any' }, + secureContext: { type: 'any' }, + enableTrace: { type: 'any' }, + requestCert: { type: 'any' }, + rejectUnauthorized: { type: 'any' }, + checkServerIdentity: { type: 'any' }, + ALPNProtocols: { type: 'any' }, + SNICallback: { type: 'any' }, + session: { type: 'any' }, + requestOCSP: { type: 'any' }, + localAddress: { type: 'any' }, + localPort: { type: 'any' }, + hints: { type: 'any' }, + lookup: { type: 'any' }, + ca: { type: 'any' }, + cert: { type: 'any' }, + ciphers: { type: 'any' }, + crl: { type: 'any' }, + ecdhCurve: { type: 'any' }, + key: { type: 'any' }, + passphrase: { type: 'any' }, + pfx: { type: 'any' }, + secureProtocol: { type: 'any' }, + index: { type: 'any' }, + // Legacy Options, these are unused but left here to avoid errors with CSFLE lib + useNewUrlParser: { type: 'boolean' } as OptionDescriptor, + useUnifiedTopology: { type: 'boolean' } as OptionDescriptor +} as Record; + +export const DEFAULT_OPTIONS = new CaseInsensitiveMap( + Object.entries(OPTIONS) + .filter(([, descriptor]) => descriptor.default != null) + .map(([k, d]) => [k, d.default]) +); + +/** + * Set of permitted feature flags + * @internal + */ +export const FEATURE_FLAGS = new Set([Symbol.for('@@mdb.skipPingOnConnect')]); diff --git a/ts-ticket-office-service/node_modules/mongodb/src/constants.ts b/ts-ticket-office-service/node_modules/mongodb/src/constants.ts new file mode 100644 index 000000000..2326e8d2c --- /dev/null +++ b/ts-ticket-office-service/node_modules/mongodb/src/constants.ts @@ -0,0 +1,134 @@ +export const SYSTEM_NAMESPACE_COLLECTION = 'system.namespaces'; +export const SYSTEM_INDEX_COLLECTION = 'system.indexes'; +export const SYSTEM_PROFILE_COLLECTION = 'system.profile'; +export const SYSTEM_USER_COLLECTION = 'system.users'; +export const SYSTEM_COMMAND_COLLECTION = '$cmd'; +export const SYSTEM_JS_COLLECTION = 'system.js'; + +// events +export const ERROR = 'error' as const; +export const TIMEOUT = 'timeout' as const; +export const CLOSE = 'close' as const; +export const OPEN = 'open' as const; +export const CONNECT = 'connect' as const; +export const CLOSED = 'closed' as const; +export const ENDED = 'ended' as const; +export const MESSAGE = 'message' as const; +export const PINNED = 'pinned' as const; +export const UNPINNED = 'unpinned' as const; +export const DESCRIPTION_RECEIVED = 'descriptionReceived'; +export const SERVER_OPENING = 'serverOpening' as const; +export const SERVER_CLOSED = 'serverClosed' as const; +export const SERVER_DESCRIPTION_CHANGED = 'serverDescriptionChanged' as const; +export const TOPOLOGY_OPENING = 'topologyOpening' as const; +export const TOPOLOGY_CLOSED = 'topologyClosed' as const; +export const TOPOLOGY_DESCRIPTION_CHANGED = 'topologyDescriptionChanged' as const; +export const CONNECTION_POOL_CREATED = 'connectionPoolCreated' as const; +export const CONNECTION_POOL_CLOSED = 'connectionPoolClosed' as const; +export const CONNECTION_POOL_CLEARED = 'connectionPoolCleared' as const; +export const CONNECTION_CREATED = 'connectionCreated' as const; +export const CONNECTION_READY = 'connectionReady' as const; +export const CONNECTION_CLOSED = 'connectionClosed' as const; +export const CONNECTION_CHECK_OUT_STARTED = 'connectionCheckOutStarted' as const; +export const CONNECTION_CHECK_OUT_FAILED = 'connectionCheckOutFailed' as const; +export const CONNECTION_CHECKED_OUT = 'connectionCheckedOut' as const; +export const CONNECTION_CHECKED_IN = 'connectionCheckedIn' as const; +export const CLUSTER_TIME_RECEIVED = 'clusterTimeReceived' as const; +export const COMMAND_STARTED = 'commandStarted' as const; +export const COMMAND_SUCCEEDED = 'commandSucceeded' as const; +export const COMMAND_FAILED = 'commandFailed' as const; +export const SERVER_HEARTBEAT_STARTED = 'serverHeartbeatStarted' as const; +export const SERVER_HEARTBEAT_SUCCEEDED = 'serverHeartbeatSucceeded' as const; +export const SERVER_HEARTBEAT_FAILED = 'serverHeartbeatFailed' as const; +export const RESPONSE = 'response' as const; +export const MORE = 'more' as const; +export const INIT = 'init' as const; +export const CHANGE = 'change' as const; +export const END = 'end' as const; +export const RESUME_TOKEN_CHANGED = 'resumeTokenChanged' as const; + +/** @public */ +export const HEARTBEAT_EVENTS = Object.freeze([ + SERVER_HEARTBEAT_STARTED, + SERVER_HEARTBEAT_SUCCEEDED, + SERVER_HEARTBEAT_FAILED +] as const); + +/** @public */ +export const CMAP_EVENTS = Object.freeze([ + CONNECTION_POOL_CREATED, + CONNECTION_POOL_CLOSED, + CONNECTION_CREATED, + CONNECTION_READY, + CONNECTION_CLOSED, + CONNECTION_CHECK_OUT_STARTED, + CONNECTION_CHECK_OUT_FAILED, + CONNECTION_CHECKED_OUT, + CONNECTION_CHECKED_IN, + CONNECTION_POOL_CLEARED +] as const); + +/** @public */ +export const TOPOLOGY_EVENTS = Object.freeze([ + SERVER_OPENING, + SERVER_CLOSED, + SERVER_DESCRIPTION_CHANGED, + TOPOLOGY_OPENING, + TOPOLOGY_CLOSED, + TOPOLOGY_DESCRIPTION_CHANGED, + ERROR, + TIMEOUT, + CLOSE +] as const); + +/** @public */ +export const APM_EVENTS = Object.freeze([ + COMMAND_STARTED, + COMMAND_SUCCEEDED, + COMMAND_FAILED +] as const); + +/** + * All events that we relay to the `Topology` + * @internal + */ +export const SERVER_RELAY_EVENTS = Object.freeze([ + SERVER_HEARTBEAT_STARTED, + SERVER_HEARTBEAT_SUCCEEDED, + SERVER_HEARTBEAT_FAILED, + COMMAND_STARTED, + COMMAND_SUCCEEDED, + COMMAND_FAILED, + ...CMAP_EVENTS +] as const); + +/** + * All events we listen to from `Server` instances, but do not forward to the client + * @internal + */ +export const LOCAL_SERVER_EVENTS = Object.freeze([ + CONNECT, + DESCRIPTION_RECEIVED, + CLOSED, + ENDED +] as const); + +/** @public */ +export const MONGO_CLIENT_EVENTS = Object.freeze([ + ...CMAP_EVENTS, + ...APM_EVENTS, + ...TOPOLOGY_EVENTS, + ...HEARTBEAT_EVENTS +] as const); + +/** + * @internal + * The legacy hello command that was deprecated in MongoDB 5.0. + */ +export const LEGACY_HELLO_COMMAND = 'ismaster'; + +/** + * @internal + * The legacy hello command that was deprecated in MongoDB 5.0. + */ +export const LEGACY_HELLO_COMMAND_CAMEL_CASE = 'isMaster'; diff --git a/ts-ticket-office-service/node_modules/mongodb/src/cursor/abstract_cursor.ts b/ts-ticket-office-service/node_modules/mongodb/src/cursor/abstract_cursor.ts new file mode 100644 index 000000000..bc41499b5 --- /dev/null +++ b/ts-ticket-office-service/node_modules/mongodb/src/cursor/abstract_cursor.ts @@ -0,0 +1,915 @@ +import { Readable, Transform } from 'stream'; + +import { BSONSerializeOptions, Document, Long, pluckBSONSerializeOptions } from '../bson'; +import { + AnyError, + MongoCursorExhaustedError, + MongoCursorInUseError, + MongoInvalidArgumentError, + MongoNetworkError, + MongoRuntimeError, + MongoTailableCursorError +} from '../error'; +import type { MongoClient } from '../mongo_client'; +import { TODO_NODE_3286, TypedEventEmitter } from '../mongo_types'; +import { executeOperation, ExecutionResult } from '../operations/execute_operation'; +import { GetMoreOperation } from '../operations/get_more'; +import { KillCursorsOperation } from '../operations/kill_cursors'; +import { ReadConcern, ReadConcernLike } from '../read_concern'; +import { ReadPreference, ReadPreferenceLike } from '../read_preference'; +import type { Server } from '../sdam/server'; +import { ClientSession, maybeClearPinnedConnection } from '../sessions'; +import { Callback, maybePromise, MongoDBNamespace, ns } from '../utils'; + +/** @internal */ +const kId = Symbol('id'); +/** @internal */ +const kDocuments = Symbol('documents'); +/** @internal */ +const kServer = Symbol('server'); +/** @internal */ +const kNamespace = Symbol('namespace'); +/** @internal */ +const kClient = Symbol('client'); +/** @internal */ +const kSession = Symbol('session'); +/** @internal */ +const kOptions = Symbol('options'); +/** @internal */ +const kTransform = Symbol('transform'); +/** @internal */ +const kInitialized = Symbol('initialized'); +/** @internal */ +const kClosed = Symbol('closed'); +/** @internal */ +const kKilled = Symbol('killed'); +/** @internal */ +const kInit = Symbol('kInit'); + +/** @public */ +export const CURSOR_FLAGS = [ + 'tailable', + 'oplogReplay', + 'noCursorTimeout', + 'awaitData', + 'exhaust', + 'partial' +] as const; + +/** @public + * @deprecated This interface is deprecated */ +export interface CursorCloseOptions { + /** Bypass calling killCursors when closing the cursor. */ + /** @deprecated the skipKillCursors option is deprecated */ + skipKillCursors?: boolean; +} + +/** @public */ +export interface CursorStreamOptions { + /** A transformation method applied to each document emitted by the stream */ + transform?(this: void, doc: Document): Document; +} + +/** @public */ +export type CursorFlag = typeof CURSOR_FLAGS[number]; + +/** @public */ +export interface AbstractCursorOptions extends BSONSerializeOptions { + session?: ClientSession; + readPreference?: ReadPreferenceLike; + readConcern?: ReadConcernLike; + batchSize?: number; + maxTimeMS?: number; + /** + * Comment to apply to the operation. + * + * In server versions pre-4.4, 'comment' must be string. A server + * error will be thrown if any other type is provided. + * + * In server versions 4.4 and above, 'comment' can be any valid BSON type. + */ + comment?: unknown; + tailable?: boolean; + awaitData?: boolean; + noCursorTimeout?: boolean; +} + +/** @internal */ +export type InternalAbstractCursorOptions = Omit & { + // resolved + readPreference: ReadPreference; + readConcern?: ReadConcern; + + // cursor flags, some are deprecated + oplogReplay?: boolean; + exhaust?: boolean; + partial?: boolean; +}; + +/** @public */ +export type AbstractCursorEvents = { + [AbstractCursor.CLOSE](): void; +}; + +/** @public */ +export abstract class AbstractCursor< + TSchema = any, + CursorEvents extends AbstractCursorEvents = AbstractCursorEvents +> extends TypedEventEmitter { + /** @internal */ + [kId]?: Long; + /** @internal */ + [kSession]: ClientSession; + /** @internal */ + [kServer]?: Server; + /** @internal */ + [kNamespace]: MongoDBNamespace; + /** @internal */ + [kDocuments]: TSchema[]; + /** @internal */ + [kClient]: MongoClient; + /** @internal */ + [kTransform]?: (doc: TSchema) => any; + /** @internal */ + [kInitialized]: boolean; + /** @internal */ + [kClosed]: boolean; + /** @internal */ + [kKilled]: boolean; + /** @internal */ + [kOptions]: InternalAbstractCursorOptions; + + /** @event */ + static readonly CLOSE = 'close' as const; + + /** @internal */ + constructor( + client: MongoClient, + namespace: MongoDBNamespace, + options: AbstractCursorOptions = {} + ) { + super(); + + if (!client.s.isMongoClient) { + throw new MongoRuntimeError('Cursor must be constructed with MongoClient'); + } + this[kClient] = client; + this[kNamespace] = namespace; + this[kDocuments] = []; // TODO: https://github.com/microsoft/TypeScript/issues/36230 + this[kInitialized] = false; + this[kClosed] = false; + this[kKilled] = false; + this[kOptions] = { + readPreference: + options.readPreference && options.readPreference instanceof ReadPreference + ? options.readPreference + : ReadPreference.primary, + ...pluckBSONSerializeOptions(options) + }; + + const readConcern = ReadConcern.fromOptions(options); + if (readConcern) { + this[kOptions].readConcern = readConcern; + } + + if (typeof options.batchSize === 'number') { + this[kOptions].batchSize = options.batchSize; + } + + // we check for undefined specifically here to allow falsy values + // eslint-disable-next-line no-restricted-syntax + if (options.comment !== undefined) { + this[kOptions].comment = options.comment; + } + + if (typeof options.maxTimeMS === 'number') { + this[kOptions].maxTimeMS = options.maxTimeMS; + } + + if (options.session instanceof ClientSession) { + this[kSession] = options.session; + } else { + this[kSession] = this[kClient].startSession({ owner: this, explicit: false }); + } + } + + get id(): Long | undefined { + return this[kId]; + } + + /** @internal */ + get client(): MongoClient { + return this[kClient]; + } + + /** @internal */ + get server(): Server | undefined { + return this[kServer]; + } + + get namespace(): MongoDBNamespace { + return this[kNamespace]; + } + + get readPreference(): ReadPreference { + return this[kOptions].readPreference; + } + + get readConcern(): ReadConcern | undefined { + return this[kOptions].readConcern; + } + + /** @internal */ + get session(): ClientSession { + return this[kSession]; + } + + set session(clientSession: ClientSession) { + this[kSession] = clientSession; + } + + /** @internal */ + get cursorOptions(): InternalAbstractCursorOptions { + return this[kOptions]; + } + + get closed(): boolean { + return this[kClosed]; + } + + get killed(): boolean { + return this[kKilled]; + } + + get loadBalanced(): boolean { + return !!this[kClient].topology?.loadBalanced; + } + + /** Returns current buffered documents length */ + bufferedCount(): number { + return this[kDocuments].length; + } + + /** Returns current buffered documents */ + readBufferedDocuments(number?: number): TSchema[] { + return this[kDocuments].splice(0, number ?? this[kDocuments].length); + } + + [Symbol.asyncIterator](): AsyncIterator { + return { + next: () => + this.next().then(value => + value != null ? { value, done: false } : { value: undefined, done: true } + ) + }; + } + + stream(options?: CursorStreamOptions): Readable & AsyncIterable { + if (options?.transform) { + const transform = options.transform; + const readable = new ReadableCursorStream(this); + + return readable.pipe( + new Transform({ + objectMode: true, + highWaterMark: 1, + transform(chunk, _, callback) { + try { + const transformed = transform(chunk); + callback(undefined, transformed); + } catch (err) { + callback(err); + } + } + }) + ); + } + + return new ReadableCursorStream(this); + } + + hasNext(): Promise; + hasNext(callback: Callback): void; + hasNext(callback?: Callback): Promise | void { + return maybePromise(callback, done => { + if (this[kId] === Long.ZERO) { + return done(undefined, false); + } + + if (this[kDocuments].length) { + return done(undefined, true); + } + + next(this, true, (err, doc) => { + if (err) return done(err); + + if (doc) { + this[kDocuments].unshift(doc); + done(undefined, true); + return; + } + + done(undefined, false); + }); + }); + } + + /** Get the next available document from the cursor, returns null if no more documents are available. */ + next(): Promise; + next(callback: Callback): void; + next(callback?: Callback): Promise | void; + next(callback?: Callback): Promise | void { + return maybePromise(callback, done => { + if (this[kId] === Long.ZERO) { + return done(new MongoCursorExhaustedError()); + } + + next(this, true, done); + }); + } + + /** + * Try to get the next available document from the cursor or `null` if an empty batch is returned + */ + tryNext(): Promise; + tryNext(callback: Callback): void; + tryNext(callback?: Callback): Promise | void { + return maybePromise(callback, done => { + if (this[kId] === Long.ZERO) { + return done(new MongoCursorExhaustedError()); + } + + next(this, false, done); + }); + } + + /** + * Iterates over all the documents for this cursor using the iterator, callback pattern. + * + * @param iterator - The iteration callback. + * @param callback - The end callback. + */ + forEach(iterator: (doc: TSchema) => boolean | void): Promise; + forEach(iterator: (doc: TSchema) => boolean | void, callback: Callback): void; + forEach( + iterator: (doc: TSchema) => boolean | void, + callback?: Callback + ): Promise | void { + if (typeof iterator !== 'function') { + throw new MongoInvalidArgumentError('Argument "iterator" must be a function'); + } + return maybePromise(callback, done => { + const transform = this[kTransform]; + const fetchDocs = () => { + next(this, true, (err, doc) => { + if (err || doc == null) return done(err); + let result; + // NOTE: no need to transform because `next` will do this automatically + try { + result = iterator(doc); // TODO(NODE-3283): Improve transform typing + } catch (error) { + return done(error); + } + + if (result === false) return done(); + + // these do need to be transformed since they are copying the rest of the batch + const internalDocs = this[kDocuments].splice(0, this[kDocuments].length); + for (let i = 0; i < internalDocs.length; ++i) { + try { + result = iterator( + (transform ? transform(internalDocs[i]) : internalDocs[i]) as TSchema // TODO(NODE-3283): Improve transform typing + ); + } catch (error) { + return done(error); + } + if (result === false) return done(); + } + + fetchDocs(); + }); + }; + + fetchDocs(); + }); + } + + close(): Promise; + close(callback: Callback): void; + /** + * @deprecated options argument is deprecated + */ + close(options: CursorCloseOptions): Promise; + /** + * @deprecated options argument is deprecated + */ + close(options: CursorCloseOptions, callback: Callback): void; + close(options?: CursorCloseOptions | Callback, callback?: Callback): Promise | void { + if (typeof options === 'function') (callback = options), (options = {}); + options = options ?? {}; + + const needsToEmitClosed = !this[kClosed]; + this[kClosed] = true; + + return maybePromise(callback, done => cleanupCursor(this, { needsToEmitClosed }, done)); + } + + /** + * Returns an array of documents. The caller is responsible for making sure that there + * is enough memory to store the results. Note that the array only contains partial + * results when this cursor had been previously accessed. In that case, + * cursor.rewind() can be used to reset the cursor. + * + * @param callback - The result callback. + */ + toArray(): Promise; + toArray(callback: Callback): void; + toArray(callback?: Callback): Promise | void { + return maybePromise(callback, done => { + const docs: TSchema[] = []; + const transform = this[kTransform]; + const fetchDocs = () => { + // NOTE: if we add a `nextBatch` then we should use it here + next(this, true, (err, doc) => { + if (err) return done(err); + if (doc == null) return done(undefined, docs); + + // NOTE: no need to transform because `next` will do this automatically + docs.push(doc); + + // these do need to be transformed since they are copying the rest of the batch + const internalDocs = ( + transform + ? this[kDocuments].splice(0, this[kDocuments].length).map(transform) + : this[kDocuments].splice(0, this[kDocuments].length) + ) as TSchema[]; // TODO(NODE-3283): Improve transform typing + + if (internalDocs) { + docs.push(...internalDocs); + } + + fetchDocs(); + }); + }; + + fetchDocs(); + }); + } + + /** + * Add a cursor flag to the cursor + * + * @param flag - The flag to set, must be one of following ['tailable', 'oplogReplay', 'noCursorTimeout', 'awaitData', 'partial' -. + * @param value - The flag boolean value. + */ + addCursorFlag(flag: CursorFlag, value: boolean): this { + assertUninitialized(this); + if (!CURSOR_FLAGS.includes(flag)) { + throw new MongoInvalidArgumentError(`Flag ${flag} is not one of ${CURSOR_FLAGS}`); + } + + if (typeof value !== 'boolean') { + throw new MongoInvalidArgumentError(`Flag ${flag} must be a boolean value`); + } + + this[kOptions][flag] = value; + return this; + } + + /** + * Map all documents using the provided function + * If there is a transform set on the cursor, that will be called first and the result passed to + * this function's transform. + * + * @remarks + * **Note for Typescript Users:** adding a transform changes the return type of the iteration of this cursor, + * it **does not** return a new instance of a cursor. This means when calling map, + * you should always assign the result to a new variable in order to get a correctly typed cursor variable. + * Take note of the following example: + * + * @example + * ```typescript + * const cursor: FindCursor = coll.find(); + * const mappedCursor: FindCursor = cursor.map(doc => Object.keys(doc).length); + * const keyCounts: number[] = await mappedCursor.toArray(); // cursor.toArray() still returns Document[] + * ``` + * @param transform - The mapping transformation method. + */ + map(transform: (doc: TSchema) => T): AbstractCursor { + assertUninitialized(this); + const oldTransform = this[kTransform] as (doc: TSchema) => TSchema; // TODO(NODE-3283): Improve transform typing + if (oldTransform) { + this[kTransform] = doc => { + return transform(oldTransform(doc)); + }; + } else { + this[kTransform] = transform; + } + + return this as unknown as AbstractCursor; + } + + /** + * Set the ReadPreference for the cursor. + * + * @param readPreference - The new read preference for the cursor. + */ + withReadPreference(readPreference: ReadPreferenceLike): this { + assertUninitialized(this); + if (readPreference instanceof ReadPreference) { + this[kOptions].readPreference = readPreference; + } else if (typeof readPreference === 'string') { + this[kOptions].readPreference = ReadPreference.fromString(readPreference); + } else { + throw new MongoInvalidArgumentError(`Invalid read preference: ${readPreference}`); + } + + return this; + } + + /** + * Set the ReadPreference for the cursor. + * + * @param readPreference - The new read preference for the cursor. + */ + withReadConcern(readConcern: ReadConcernLike): this { + assertUninitialized(this); + const resolvedReadConcern = ReadConcern.fromOptions({ readConcern }); + if (resolvedReadConcern) { + this[kOptions].readConcern = resolvedReadConcern; + } + + return this; + } + + /** + * Set a maxTimeMS on the cursor query, allowing for hard timeout limits on queries (Only supported on MongoDB 2.6 or higher) + * + * @param value - Number of milliseconds to wait before aborting the query. + */ + maxTimeMS(value: number): this { + assertUninitialized(this); + if (typeof value !== 'number') { + throw new MongoInvalidArgumentError('Argument for maxTimeMS must be a number'); + } + + this[kOptions].maxTimeMS = value; + return this; + } + + /** + * Set the batch size for the cursor. + * + * @param value - The number of documents to return per batch. See {@link https://docs.mongodb.com/manual/reference/command/find/|find command documentation}. + */ + batchSize(value: number): this { + assertUninitialized(this); + if (this[kOptions].tailable) { + throw new MongoTailableCursorError('Tailable cursor does not support batchSize'); + } + + if (typeof value !== 'number') { + throw new MongoInvalidArgumentError('Operation "batchSize" requires an integer'); + } + + this[kOptions].batchSize = value; + return this; + } + + /** + * Rewind this cursor to its uninitialized state. Any options that are present on the cursor will + * remain in effect. Iterating this cursor will cause new queries to be sent to the server, even + * if the resultant data has already been retrieved by this cursor. + */ + rewind(): void { + if (!this[kInitialized]) { + return; + } + + this[kId] = undefined; + this[kDocuments] = []; + this[kClosed] = false; + this[kKilled] = false; + this[kInitialized] = false; + + const session = this[kSession]; + if (session) { + // We only want to end this session if we created it, and it hasn't ended yet + if (session.explicit === false) { + if (!session.hasEnded) { + session.endSession().catch(() => null); + } + this[kSession] = this.client.startSession({ owner: this, explicit: false }); + } + } + } + + /** + * Returns a new uninitialized copy of this cursor, with options matching those that have been set on the current instance + */ + abstract clone(): AbstractCursor; + + /** @internal */ + abstract _initialize( + session: ClientSession | undefined, + callback: Callback + ): void; + + /** @internal */ + _getMore(batchSize: number, callback: Callback): void { + const cursorId = this[kId]; + const cursorNs = this[kNamespace]; + const server = this[kServer]; + + if (cursorId == null) { + callback(new MongoRuntimeError('Unable to iterate cursor with no id')); + return; + } + + if (server == null) { + callback(new MongoRuntimeError('Unable to iterate cursor without selected server')); + return; + } + + const getMoreOperation = new GetMoreOperation(cursorNs, cursorId, server, { + ...this[kOptions], + session: this[kSession], + batchSize + }); + + executeOperation(this[kClient], getMoreOperation, callback); + } + + /** + * @internal + * + * This function is exposed for the unified test runner's createChangeStream + * operation. We cannot refactor to use the abstract _initialize method without + * a significant refactor. + */ + [kInit](callback: Callback): void { + this._initialize(this[kSession], (err, state) => { + if (state) { + const response = state.response; + this[kServer] = state.server; + + if (response.cursor) { + this[kId] = + typeof response.cursor.id === 'number' + ? Long.fromNumber(response.cursor.id) + : response.cursor.id; + + if (response.cursor.ns) { + this[kNamespace] = ns(response.cursor.ns); + } + + this[kDocuments] = response.cursor.firstBatch; + } + + // When server responses return without a cursor document, we close this cursor + // and return the raw server response. This is often the case for explain commands + // for example + if (this[kId] == null) { + this[kId] = Long.ZERO; + // TODO(NODE-3286): ExecutionResult needs to accept a generic parameter + this[kDocuments] = [state.response as TODO_NODE_3286]; + } + } + + // the cursor is now initialized, even if an error occurred or it is dead + this[kInitialized] = true; + + if (err || cursorIsDead(this)) { + return cleanupCursor(this, { error: err }, () => callback(err, nextDocument(this))); + } + + callback(); + }); + } +} + +function nextDocument(cursor: AbstractCursor): T | null { + if (cursor[kDocuments] == null || !cursor[kDocuments].length) { + return null; + } + + const doc = cursor[kDocuments].shift(); + if (doc) { + const transform = cursor[kTransform]; + if (transform) { + return transform(doc) as T; + } + + return doc; + } + + return null; +} + +/** + * @param cursor - the cursor on which to call `next` + * @param blocking - a boolean indicating whether or not the cursor should `block` until data + * is available. Generally, this flag is set to `false` because if the getMore returns no documents, + * the cursor has been exhausted. In certain scenarios (ChangeStreams, tailable await cursors and + * `tryNext`, for example) blocking is necessary because a getMore returning no documents does + * not indicate the end of the cursor. + * @param callback - callback to return the result to the caller + * @returns + */ +export function next( + cursor: AbstractCursor, + blocking: boolean, + callback: Callback +): void { + const cursorId = cursor[kId]; + if (cursor.closed) { + return callback(undefined, null); + } + + if (cursor[kDocuments] && cursor[kDocuments].length) { + callback(undefined, nextDocument(cursor)); + return; + } + + if (cursorId == null) { + // All cursors must operate within a session, one must be made implicitly if not explicitly provided + cursor[kInit]((err, value) => { + if (err) return callback(err); + if (value) { + return callback(undefined, value); + } + return next(cursor, blocking, callback); + }); + + return; + } + + if (cursorIsDead(cursor)) { + return cleanupCursor(cursor, undefined, () => callback(undefined, null)); + } + + // otherwise need to call getMore + const batchSize = cursor[kOptions].batchSize || 1000; + cursor._getMore(batchSize, (err, response) => { + if (response) { + const cursorId = + typeof response.cursor.id === 'number' + ? Long.fromNumber(response.cursor.id) + : response.cursor.id; + + cursor[kDocuments] = response.cursor.nextBatch; + cursor[kId] = cursorId; + } + + if (err || cursorIsDead(cursor)) { + return cleanupCursor(cursor, { error: err }, () => callback(err, nextDocument(cursor))); + } + + if (cursor[kDocuments].length === 0 && blocking === false) { + return callback(undefined, null); + } + + next(cursor, blocking, callback); + }); +} + +function cursorIsDead(cursor: AbstractCursor): boolean { + const cursorId = cursor[kId]; + return !!cursorId && cursorId.isZero(); +} + +function cleanupCursor( + cursor: AbstractCursor, + options: { error?: AnyError | undefined; needsToEmitClosed?: boolean } | undefined, + callback: Callback +): void { + const cursorId = cursor[kId]; + const cursorNs = cursor[kNamespace]; + const server = cursor[kServer]; + const session = cursor[kSession]; + const error = options?.error; + const needsToEmitClosed = options?.needsToEmitClosed ?? cursor[kDocuments].length === 0; + + if (error) { + if (cursor.loadBalanced && error instanceof MongoNetworkError) { + return completeCleanup(); + } + } + + if (cursorId == null || server == null || cursorId.isZero() || cursorNs == null) { + if (needsToEmitClosed) { + cursor[kClosed] = true; + cursor[kId] = Long.ZERO; + cursor.emit(AbstractCursor.CLOSE); + } + + if (session) { + if (session.owner === cursor) { + return session.endSession({ error }, callback); + } + + if (!session.inTransaction()) { + maybeClearPinnedConnection(session, { error }); + } + } + + return callback(); + } + + function completeCleanup() { + if (session) { + if (session.owner === cursor) { + return session.endSession({ error }, () => { + cursor.emit(AbstractCursor.CLOSE); + callback(); + }); + } + + if (!session.inTransaction()) { + maybeClearPinnedConnection(session, { error }); + } + } + + cursor.emit(AbstractCursor.CLOSE); + return callback(); + } + + cursor[kKilled] = true; + + return executeOperation( + cursor[kClient], + new KillCursorsOperation(cursorId, cursorNs, server, { session }), + completeCleanup + ); +} + +/** @internal */ +export function assertUninitialized(cursor: AbstractCursor): void { + if (cursor[kInitialized]) { + throw new MongoCursorInUseError(); + } +} + +class ReadableCursorStream extends Readable { + private _cursor: AbstractCursor; + private _readInProgress = false; + + constructor(cursor: AbstractCursor) { + super({ + objectMode: true, + autoDestroy: false, + highWaterMark: 1 + }); + this._cursor = cursor; + } + + // eslint-disable-next-line @typescript-eslint/no-unused-vars + override _read(size: number): void { + if (!this._readInProgress) { + this._readInProgress = true; + this._readNext(); + } + } + + override _destroy(error: Error | null, callback: (error?: Error | null) => void): void { + this._cursor.close(err => process.nextTick(callback, err || error)); + } + + private _readNext() { + next(this._cursor, true, (err, result) => { + if (err) { + // NOTE: This is questionable, but we have a test backing the behavior. It seems the + // desired behavior is that a stream ends cleanly when a user explicitly closes + // a client during iteration. Alternatively, we could do the "right" thing and + // propagate the error message by removing this special case. + if (err.message.match(/server is closed/)) { + this._cursor.close().catch(() => null); + return this.push(null); + } + + // NOTE: This is also perhaps questionable. The rationale here is that these errors tend + // to be "operation interrupted", where a cursor has been closed but there is an + // active getMore in-flight. This used to check if the cursor was killed but once + // that changed to happen in cleanup legitimate errors would not destroy the + // stream. There are change streams test specifically test these cases. + if (err.message.match(/interrupted/)) { + return this.push(null); + } + + return this.destroy(err); + } + + if (result == null) { + this.push(null); + } else if (this.destroyed) { + this._cursor.close().catch(() => null); + } else { + if (this.push(result)) { + return this._readNext(); + } + + this._readInProgress = false; + } + }); + } +} diff --git a/ts-ticket-office-service/node_modules/mongodb/src/cursor/aggregation_cursor.ts b/ts-ticket-office-service/node_modules/mongodb/src/cursor/aggregation_cursor.ts new file mode 100644 index 000000000..350696ee4 --- /dev/null +++ b/ts-ticket-office-service/node_modules/mongodb/src/cursor/aggregation_cursor.ts @@ -0,0 +1,219 @@ +import type { Document } from '../bson'; +import type { ExplainVerbosityLike } from '../explain'; +import type { MongoClient } from '../mongo_client'; +import { AggregateOperation, AggregateOptions } from '../operations/aggregate'; +import { executeOperation, ExecutionResult } from '../operations/execute_operation'; +import type { ClientSession } from '../sessions'; +import type { Sort } from '../sort'; +import type { Callback, MongoDBNamespace } from '../utils'; +import { mergeOptions } from '../utils'; +import type { AbstractCursorOptions } from './abstract_cursor'; +import { AbstractCursor, assertUninitialized } from './abstract_cursor'; + +/** @public */ +export interface AggregationCursorOptions extends AbstractCursorOptions, AggregateOptions {} + +/** @internal */ +const kPipeline = Symbol('pipeline'); +/** @internal */ +const kOptions = Symbol('options'); + +/** + * The **AggregationCursor** class is an internal class that embodies an aggregation cursor on MongoDB + * allowing for iteration over the results returned from the underlying query. It supports + * one by one document iteration, conversion to an array or can be iterated as a Node 4.X + * or higher stream + * @public + */ +export class AggregationCursor extends AbstractCursor { + /** @internal */ + [kPipeline]: Document[]; + /** @internal */ + [kOptions]: AggregateOptions; + + /** @internal */ + constructor( + client: MongoClient, + namespace: MongoDBNamespace, + pipeline: Document[] = [], + options: AggregateOptions = {} + ) { + super(client, namespace, options); + + this[kPipeline] = pipeline; + this[kOptions] = options; + } + + get pipeline(): Document[] { + return this[kPipeline]; + } + + clone(): AggregationCursor { + const clonedOptions = mergeOptions({}, this[kOptions]); + delete clonedOptions.session; + return new AggregationCursor(this.client, this.namespace, this[kPipeline], { + ...clonedOptions + }); + } + + override map(transform: (doc: TSchema) => T): AggregationCursor { + return super.map(transform) as AggregationCursor; + } + + /** @internal */ + _initialize(session: ClientSession, callback: Callback): void { + const aggregateOperation = new AggregateOperation(this.namespace, this[kPipeline], { + ...this[kOptions], + ...this.cursorOptions, + session + }); + + executeOperation(this.client, aggregateOperation, (err, response) => { + if (err || response == null) return callback(err); + + // TODO: NODE-2882 + callback(undefined, { server: aggregateOperation.server, session, response }); + }); + } + + /** Execute the explain for the cursor */ + explain(): Promise; + explain(callback: Callback): void; + explain(verbosity: ExplainVerbosityLike): Promise; + explain( + verbosity?: ExplainVerbosityLike | Callback, + callback?: Callback + ): Promise | void { + if (typeof verbosity === 'function') (callback = verbosity), (verbosity = true); + if (verbosity == null) verbosity = true; + + return executeOperation( + this.client, + new AggregateOperation(this.namespace, this[kPipeline], { + ...this[kOptions], // NOTE: order matters here, we may need to refine this + ...this.cursorOptions, + explain: verbosity + }), + callback + ); + } + + /** Add a group stage to the aggregation pipeline */ + group($group: Document): AggregationCursor; + group($group: Document): this { + assertUninitialized(this); + this[kPipeline].push({ $group }); + return this; + } + + /** Add a limit stage to the aggregation pipeline */ + limit($limit: number): this { + assertUninitialized(this); + this[kPipeline].push({ $limit }); + return this; + } + + /** Add a match stage to the aggregation pipeline */ + match($match: Document): this { + assertUninitialized(this); + this[kPipeline].push({ $match }); + return this; + } + + /** Add an out stage to the aggregation pipeline */ + out($out: { db: string; coll: string } | string): this { + assertUninitialized(this); + this[kPipeline].push({ $out }); + return this; + } + + /** + * Add a project stage to the aggregation pipeline + * + * @remarks + * In order to strictly type this function you must provide an interface + * that represents the effect of your projection on the result documents. + * + * By default chaining a projection to your cursor changes the returned type to the generic {@link Document} type. + * You should specify a parameterized type to have assertions on your final results. + * + * @example + * ```typescript + * // Best way + * const docs: AggregationCursor<{ a: number }> = cursor.project<{ a: number }>({ _id: 0, a: true }); + * // Flexible way + * const docs: AggregationCursor = cursor.project({ _id: 0, a: true }); + * ``` + * + * @remarks + * In order to strictly type this function you must provide an interface + * that represents the effect of your projection on the result documents. + * + * **Note for Typescript Users:** adding a transform changes the return type of the iteration of this cursor, + * it **does not** return a new instance of a cursor. This means when calling project, + * you should always assign the result to a new variable in order to get a correctly typed cursor variable. + * Take note of the following example: + * + * @example + * ```typescript + * const cursor: AggregationCursor<{ a: number; b: string }> = coll.aggregate([]); + * const projectCursor = cursor.project<{ a: number }>({ _id: 0, a: true }); + * const aPropOnlyArray: {a: number}[] = await projectCursor.toArray(); + * + * // or always use chaining and save the final cursor + * + * const cursor = coll.aggregate().project<{ a: string }>({ + * _id: 0, + * a: { $convert: { input: '$a', to: 'string' } + * }}); + * ``` + */ + project($project: Document): AggregationCursor { + assertUninitialized(this); + this[kPipeline].push({ $project }); + return this as unknown as AggregationCursor; + } + + /** Add a lookup stage to the aggregation pipeline */ + lookup($lookup: Document): this { + assertUninitialized(this); + this[kPipeline].push({ $lookup }); + return this; + } + + /** Add a redact stage to the aggregation pipeline */ + redact($redact: Document): this { + assertUninitialized(this); + this[kPipeline].push({ $redact }); + return this; + } + + /** Add a skip stage to the aggregation pipeline */ + skip($skip: number): this { + assertUninitialized(this); + this[kPipeline].push({ $skip }); + return this; + } + + /** Add a sort stage to the aggregation pipeline */ + sort($sort: Sort): this { + assertUninitialized(this); + this[kPipeline].push({ $sort }); + return this; + } + + /** Add a unwind stage to the aggregation pipeline */ + unwind($unwind: Document | string): this { + assertUninitialized(this); + this[kPipeline].push({ $unwind }); + return this; + } + + // deprecated methods + /** @deprecated Add a geoNear stage to the aggregation pipeline */ + geoNear($geoNear: Document): this { + assertUninitialized(this); + this[kPipeline].push({ $geoNear }); + return this; + } +} diff --git a/ts-ticket-office-service/node_modules/mongodb/src/cursor/change_stream_cursor.ts b/ts-ticket-office-service/node_modules/mongodb/src/cursor/change_stream_cursor.ts new file mode 100644 index 000000000..b5a4ae463 --- /dev/null +++ b/ts-ticket-office-service/node_modules/mongodb/src/cursor/change_stream_cursor.ts @@ -0,0 +1,194 @@ +import type { Document, Long, Timestamp } from '../bson'; +import { + type ChangeStreamDocument, + type ChangeStreamEvents, + type OperationTime, + type ResumeToken, + ChangeStream +} from '../change_stream'; +import { INIT, RESPONSE } from '../constants'; +import type { MongoClient } from '../mongo_client'; +import type { TODO_NODE_3286 } from '../mongo_types'; +import { AggregateOperation } from '../operations/aggregate'; +import type { CollationOptions } from '../operations/command'; +import { type ExecutionResult, executeOperation } from '../operations/execute_operation'; +import type { ClientSession } from '../sessions'; +import { type Callback, type MongoDBNamespace, maxWireVersion } from '../utils'; +import { type AbstractCursorOptions, AbstractCursor } from './abstract_cursor'; + +/** @internal */ +export interface ChangeStreamCursorOptions extends AbstractCursorOptions { + startAtOperationTime?: OperationTime; + resumeAfter?: ResumeToken; + startAfter?: ResumeToken; + maxAwaitTimeMS?: number; + collation?: CollationOptions; + fullDocument?: string; +} + +/** @internal */ +export type ChangeStreamAggregateRawResult = { + $clusterTime: { clusterTime: Timestamp }; + cursor: { + postBatchResumeToken: ResumeToken; + ns: string; + id: number | Long; + } & ({ firstBatch: TChange[] } | { nextBatch: TChange[] }); + ok: 1; + operationTime: Timestamp; +}; + +/** @internal */ +export class ChangeStreamCursor< + TSchema extends Document = Document, + TChange extends Document = ChangeStreamDocument +> extends AbstractCursor { + _resumeToken: ResumeToken; + startAtOperationTime?: OperationTime; + hasReceived?: boolean; + resumeAfter: ResumeToken; + startAfter: ResumeToken; + options: ChangeStreamCursorOptions; + + postBatchResumeToken?: ResumeToken; + pipeline: Document[]; + + /** + * @internal + * + * used to determine change stream resumability + */ + maxWireVersion: number | undefined; + + constructor( + client: MongoClient, + namespace: MongoDBNamespace, + pipeline: Document[] = [], + options: ChangeStreamCursorOptions = {} + ) { + super(client, namespace, options); + + this.pipeline = pipeline; + this.options = options; + this._resumeToken = null; + this.startAtOperationTime = options.startAtOperationTime; + + if (options.startAfter) { + this.resumeToken = options.startAfter; + } else if (options.resumeAfter) { + this.resumeToken = options.resumeAfter; + } + } + + set resumeToken(token: ResumeToken) { + this._resumeToken = token; + this.emit(ChangeStream.RESUME_TOKEN_CHANGED, token); + } + + get resumeToken(): ResumeToken { + return this._resumeToken; + } + + get resumeOptions(): ChangeStreamCursorOptions { + const options: ChangeStreamCursorOptions = { + ...this.options + }; + + for (const key of ['resumeAfter', 'startAfter', 'startAtOperationTime'] as const) { + delete options[key]; + } + + if (this.resumeToken != null) { + if (this.options.startAfter && !this.hasReceived) { + options.startAfter = this.resumeToken; + } else { + options.resumeAfter = this.resumeToken; + } + } else if (this.startAtOperationTime != null && maxWireVersion(this.server) >= 7) { + options.startAtOperationTime = this.startAtOperationTime; + } + + return options; + } + + cacheResumeToken(resumeToken: ResumeToken): void { + if (this.bufferedCount() === 0 && this.postBatchResumeToken) { + this.resumeToken = this.postBatchResumeToken; + } else { + this.resumeToken = resumeToken; + } + this.hasReceived = true; + } + + _processBatch(response: ChangeStreamAggregateRawResult): void { + const cursor = response.cursor; + if (cursor.postBatchResumeToken) { + this.postBatchResumeToken = response.cursor.postBatchResumeToken; + + const batch = + 'firstBatch' in response.cursor ? response.cursor.firstBatch : response.cursor.nextBatch; + if (batch.length === 0) { + this.resumeToken = cursor.postBatchResumeToken; + } + } + } + + clone(): AbstractCursor { + return new ChangeStreamCursor(this.client, this.namespace, this.pipeline, { + ...this.cursorOptions + }); + } + + _initialize(session: ClientSession, callback: Callback): void { + const aggregateOperation = new AggregateOperation(this.namespace, this.pipeline, { + ...this.cursorOptions, + ...this.options, + session + }); + + executeOperation>( + session.client, + aggregateOperation, + (err, response) => { + if (err || response == null) { + return callback(err); + } + + const server = aggregateOperation.server; + this.maxWireVersion = maxWireVersion(server); + + if ( + this.startAtOperationTime == null && + this.resumeAfter == null && + this.startAfter == null && + this.maxWireVersion >= 7 + ) { + this.startAtOperationTime = response.operationTime; + } + + this._processBatch(response); + + this.emit(INIT, response); + this.emit(RESPONSE); + + // TODO: NODE-2882 + callback(undefined, { server, session, response }); + } + ); + } + + override _getMore(batchSize: number, callback: Callback): void { + super._getMore(batchSize, (err, response) => { + if (err) { + return callback(err); + } + + this.maxWireVersion = maxWireVersion(this.server); + this._processBatch(response as TODO_NODE_3286 as ChangeStreamAggregateRawResult); + + this.emit(ChangeStream.MORE, response); + this.emit(ChangeStream.RESPONSE); + callback(err, response); + }); + } +} diff --git a/ts-ticket-office-service/node_modules/mongodb/src/cursor/find_cursor.ts b/ts-ticket-office-service/node_modules/mongodb/src/cursor/find_cursor.ts new file mode 100644 index 000000000..8034bfd7c --- /dev/null +++ b/ts-ticket-office-service/node_modules/mongodb/src/cursor/find_cursor.ts @@ -0,0 +1,480 @@ +import type { Document } from '../bson'; +import { MongoInvalidArgumentError, MongoTailableCursorError } from '../error'; +import type { ExplainVerbosityLike } from '../explain'; +import type { MongoClient } from '../mongo_client'; +import type { CollationOptions } from '../operations/command'; +import { CountOperation, CountOptions } from '../operations/count'; +import { executeOperation, ExecutionResult } from '../operations/execute_operation'; +import { FindOperation, FindOptions } from '../operations/find'; +import type { Hint } from '../operations/operation'; +import type { ClientSession } from '../sessions'; +import { formatSort, Sort, SortDirection } from '../sort'; +import { Callback, emitWarningOnce, mergeOptions, MongoDBNamespace } from '../utils'; +import { AbstractCursor, assertUninitialized } from './abstract_cursor'; + +/** @internal */ +const kFilter = Symbol('filter'); +/** @internal */ +const kNumReturned = Symbol('numReturned'); +/** @internal */ +const kBuiltOptions = Symbol('builtOptions'); + +/** @public Flags allowed for cursor */ +export const FLAGS = [ + 'tailable', + 'oplogReplay', + 'noCursorTimeout', + 'awaitData', + 'exhaust', + 'partial' +] as const; + +/** @public */ +export class FindCursor extends AbstractCursor { + /** @internal */ + [kFilter]: Document; + /** @internal */ + [kNumReturned]?: number; + /** @internal */ + [kBuiltOptions]: FindOptions; + + /** @internal */ + constructor( + client: MongoClient, + namespace: MongoDBNamespace, + filter: Document | undefined, + options: FindOptions = {} + ) { + super(client, namespace, options); + + this[kFilter] = filter || {}; + this[kBuiltOptions] = options; + + if (options.sort != null) { + this[kBuiltOptions].sort = formatSort(options.sort); + } + } + + clone(): FindCursor { + const clonedOptions = mergeOptions({}, this[kBuiltOptions]); + delete clonedOptions.session; + return new FindCursor(this.client, this.namespace, this[kFilter], { + ...clonedOptions + }); + } + + override map(transform: (doc: TSchema) => T): FindCursor { + return super.map(transform) as FindCursor; + } + + /** @internal */ + _initialize(session: ClientSession, callback: Callback): void { + const findOperation = new FindOperation(undefined, this.namespace, this[kFilter], { + ...this[kBuiltOptions], // NOTE: order matters here, we may need to refine this + ...this.cursorOptions, + session + }); + + executeOperation(this.client, findOperation, (err, response) => { + if (err || response == null) return callback(err); + + // TODO: We only need this for legacy queries that do not support `limit`, maybe + // the value should only be saved in those cases. + if (response.cursor) { + this[kNumReturned] = response.cursor.firstBatch.length; + } else { + this[kNumReturned] = response.documents ? response.documents.length : 0; + } + + // TODO: NODE-2882 + callback(undefined, { server: findOperation.server, session, response }); + }); + } + + /** @internal */ + override _getMore(batchSize: number, callback: Callback): void { + // NOTE: this is to support client provided limits in pre-command servers + const numReturned = this[kNumReturned]; + if (numReturned) { + const limit = this[kBuiltOptions].limit; + batchSize = + limit && limit > 0 && numReturned + batchSize > limit ? limit - numReturned : batchSize; + + if (batchSize <= 0) { + return this.close(callback); + } + } + + super._getMore(batchSize, (err, response) => { + if (err) return callback(err); + + // TODO: wrap this in some logic to prevent it from happening if we don't need this support + if (response) { + this[kNumReturned] = this[kNumReturned] + response.cursor.nextBatch.length; + } + + callback(undefined, response); + }); + } + + /** + * Get the count of documents for this cursor + * @deprecated Use `collection.estimatedDocumentCount` or `collection.countDocuments` instead + */ + count(): Promise; + /** @deprecated Use `collection.estimatedDocumentCount` or `collection.countDocuments` instead */ + count(callback: Callback): void; + /** @deprecated Use `collection.estimatedDocumentCount` or `collection.countDocuments` instead */ + count(options: CountOptions): Promise; + /** @deprecated Use `collection.estimatedDocumentCount` or `collection.countDocuments` instead */ + count(options: CountOptions, callback: Callback): void; + count( + options?: CountOptions | Callback, + callback?: Callback + ): Promise | void { + emitWarningOnce( + 'cursor.count is deprecated and will be removed in the next major version, please use `collection.estimatedDocumentCount` or `collection.countDocuments` instead ' + ); + if (typeof options === 'boolean') { + throw new MongoInvalidArgumentError('Invalid first parameter to count'); + } + + if (typeof options === 'function') (callback = options), (options = {}); + options = options ?? {}; + + return executeOperation( + this.client, + new CountOperation(this.namespace, this[kFilter], { + ...this[kBuiltOptions], // NOTE: order matters here, we may need to refine this + ...this.cursorOptions, + ...options + }), + callback + ); + } + + /** Execute the explain for the cursor */ + explain(): Promise; + explain(callback: Callback): void; + explain(verbosity?: ExplainVerbosityLike): Promise; + explain( + verbosity?: ExplainVerbosityLike | Callback, + callback?: Callback + ): Promise | void { + if (typeof verbosity === 'function') (callback = verbosity), (verbosity = true); + if (verbosity == null) verbosity = true; + + return executeOperation( + this.client, + new FindOperation(undefined, this.namespace, this[kFilter], { + ...this[kBuiltOptions], // NOTE: order matters here, we may need to refine this + ...this.cursorOptions, + explain: verbosity + }), + callback + ); + } + + /** Set the cursor query */ + filter(filter: Document): this { + assertUninitialized(this); + this[kFilter] = filter; + return this; + } + + /** + * Set the cursor hint + * + * @param hint - If specified, then the query system will only consider plans using the hinted index. + */ + hint(hint: Hint): this { + assertUninitialized(this); + this[kBuiltOptions].hint = hint; + return this; + } + + /** + * Set the cursor min + * + * @param min - Specify a $min value to specify the inclusive lower bound for a specific index in order to constrain the results of find(). The $min specifies the lower bound for all keys of a specific index in order. + */ + min(min: Document): this { + assertUninitialized(this); + this[kBuiltOptions].min = min; + return this; + } + + /** + * Set the cursor max + * + * @param max - Specify a $max value to specify the exclusive upper bound for a specific index in order to constrain the results of find(). The $max specifies the upper bound for all keys of a specific index in order. + */ + max(max: Document): this { + assertUninitialized(this); + this[kBuiltOptions].max = max; + return this; + } + + /** + * Set the cursor returnKey. + * If set to true, modifies the cursor to only return the index field or fields for the results of the query, rather than documents. + * If set to true and the query does not use an index to perform the read operation, the returned documents will not contain any fields. + * + * @param value - the returnKey value. + */ + returnKey(value: boolean): this { + assertUninitialized(this); + this[kBuiltOptions].returnKey = value; + return this; + } + + /** + * Modifies the output of a query by adding a field $recordId to matching documents. $recordId is the internal key which uniquely identifies a document in a collection. + * + * @param value - The $showDiskLoc option has now been deprecated and replaced with the showRecordId field. $showDiskLoc will still be accepted for OP_QUERY stye find. + */ + showRecordId(value: boolean): this { + assertUninitialized(this); + this[kBuiltOptions].showRecordId = value; + return this; + } + + /** + * Add a query modifier to the cursor query + * + * @param name - The query modifier (must start with $, such as $orderby etc) + * @param value - The modifier value. + */ + addQueryModifier(name: string, value: string | boolean | number | Document): this { + assertUninitialized(this); + if (name[0] !== '$') { + throw new MongoInvalidArgumentError(`${name} is not a valid query modifier`); + } + + // Strip of the $ + const field = name.substr(1); + + // NOTE: consider some TS magic for this + switch (field) { + case 'comment': + this[kBuiltOptions].comment = value as string | Document; + break; + + case 'explain': + this[kBuiltOptions].explain = value as boolean; + break; + + case 'hint': + this[kBuiltOptions].hint = value as string | Document; + break; + + case 'max': + this[kBuiltOptions].max = value as Document; + break; + + case 'maxTimeMS': + this[kBuiltOptions].maxTimeMS = value as number; + break; + + case 'min': + this[kBuiltOptions].min = value as Document; + break; + + case 'orderby': + this[kBuiltOptions].sort = formatSort(value as string | Document); + break; + + case 'query': + this[kFilter] = value as Document; + break; + + case 'returnKey': + this[kBuiltOptions].returnKey = value as boolean; + break; + + case 'showDiskLoc': + this[kBuiltOptions].showRecordId = value as boolean; + break; + + default: + throw new MongoInvalidArgumentError(`Invalid query modifier: ${name}`); + } + + return this; + } + + /** + * Add a comment to the cursor query allowing for tracking the comment in the log. + * + * @param value - The comment attached to this query. + */ + comment(value: string): this { + assertUninitialized(this); + this[kBuiltOptions].comment = value; + return this; + } + + /** + * Set a maxAwaitTimeMS on a tailing cursor query to allow to customize the timeout value for the option awaitData (Only supported on MongoDB 3.2 or higher, ignored otherwise) + * + * @param value - Number of milliseconds to wait before aborting the tailed query. + */ + maxAwaitTimeMS(value: number): this { + assertUninitialized(this); + if (typeof value !== 'number') { + throw new MongoInvalidArgumentError('Argument for maxAwaitTimeMS must be a number'); + } + + this[kBuiltOptions].maxAwaitTimeMS = value; + return this; + } + + /** + * Set a maxTimeMS on the cursor query, allowing for hard timeout limits on queries (Only supported on MongoDB 2.6 or higher) + * + * @param value - Number of milliseconds to wait before aborting the query. + */ + override maxTimeMS(value: number): this { + assertUninitialized(this); + if (typeof value !== 'number') { + throw new MongoInvalidArgumentError('Argument for maxTimeMS must be a number'); + } + + this[kBuiltOptions].maxTimeMS = value; + return this; + } + + /** + * Add a project stage to the aggregation pipeline + * + * @remarks + * In order to strictly type this function you must provide an interface + * that represents the effect of your projection on the result documents. + * + * By default chaining a projection to your cursor changes the returned type to the generic + * {@link Document} type. + * You should specify a parameterized type to have assertions on your final results. + * + * @example + * ```typescript + * // Best way + * const docs: FindCursor<{ a: number }> = cursor.project<{ a: number }>({ _id: 0, a: true }); + * // Flexible way + * const docs: FindCursor = cursor.project({ _id: 0, a: true }); + * ``` + * + * @remarks + * + * **Note for Typescript Users:** adding a transform changes the return type of the iteration of this cursor, + * it **does not** return a new instance of a cursor. This means when calling project, + * you should always assign the result to a new variable in order to get a correctly typed cursor variable. + * Take note of the following example: + * + * @example + * ```typescript + * const cursor: FindCursor<{ a: number; b: string }> = coll.find(); + * const projectCursor = cursor.project<{ a: number }>({ _id: 0, a: true }); + * const aPropOnlyArray: {a: number}[] = await projectCursor.toArray(); + * + * // or always use chaining and save the final cursor + * + * const cursor = coll.find().project<{ a: string }>({ + * _id: 0, + * a: { $convert: { input: '$a', to: 'string' } + * }}); + * ``` + */ + project(value: Document): FindCursor { + assertUninitialized(this); + this[kBuiltOptions].projection = value; + return this as unknown as FindCursor; + } + + /** + * Sets the sort order of the cursor query. + * + * @param sort - The key or keys set for the sort. + * @param direction - The direction of the sorting (1 or -1). + */ + sort(sort: Sort | string, direction?: SortDirection): this { + assertUninitialized(this); + if (this[kBuiltOptions].tailable) { + throw new MongoTailableCursorError('Tailable cursor does not support sorting'); + } + + this[kBuiltOptions].sort = formatSort(sort, direction); + return this; + } + + /** + * Allows disk use for blocking sort operations exceeding 100MB memory. (MongoDB 3.2 or higher) + * + * @remarks + * {@link https://docs.mongodb.com/manual/reference/command/find/#find-cmd-allowdiskuse | find command allowDiskUse documentation} + */ + allowDiskUse(allow = true): this { + assertUninitialized(this); + + if (!this[kBuiltOptions].sort) { + throw new MongoInvalidArgumentError('Option "allowDiskUse" requires a sort specification'); + } + + // As of 6.0 the default is true. This allows users to get back to the old behaviour. + if (!allow) { + this[kBuiltOptions].allowDiskUse = false; + return this; + } + + this[kBuiltOptions].allowDiskUse = true; + return this; + } + + /** + * Set the collation options for the cursor. + * + * @param value - The cursor collation options (MongoDB 3.4 or higher) settings for update operation (see 3.4 documentation for available fields). + */ + collation(value: CollationOptions): this { + assertUninitialized(this); + this[kBuiltOptions].collation = value; + return this; + } + + /** + * Set the limit for the cursor. + * + * @param value - The limit for the cursor query. + */ + limit(value: number): this { + assertUninitialized(this); + if (this[kBuiltOptions].tailable) { + throw new MongoTailableCursorError('Tailable cursor does not support limit'); + } + + if (typeof value !== 'number') { + throw new MongoInvalidArgumentError('Operation "limit" requires an integer'); + } + + this[kBuiltOptions].limit = value; + return this; + } + + /** + * Set the skip for the cursor. + * + * @param value - The skip for the cursor query. + */ + skip(value: number): this { + assertUninitialized(this); + if (this[kBuiltOptions].tailable) { + throw new MongoTailableCursorError('Tailable cursor does not support skip'); + } + + if (typeof value !== 'number') { + throw new MongoInvalidArgumentError('Operation "skip" requires an integer'); + } + + this[kBuiltOptions].skip = value; + return this; + } +} diff --git a/ts-ticket-office-service/node_modules/mongodb/src/cursor/list_collections_cursor.ts b/ts-ticket-office-service/node_modules/mongodb/src/cursor/list_collections_cursor.ts new file mode 100644 index 000000000..460126be8 --- /dev/null +++ b/ts-ticket-office-service/node_modules/mongodb/src/cursor/list_collections_cursor.ts @@ -0,0 +1,52 @@ +import type { Document } from '../bson'; +import type { Db } from '../db'; +import { executeOperation, ExecutionResult } from '../operations/execute_operation'; +import { + CollectionInfo, + ListCollectionsOperation, + ListCollectionsOptions +} from '../operations/list_collections'; +import type { ClientSession } from '../sessions'; +import type { Callback } from '../utils'; +import { AbstractCursor } from './abstract_cursor'; + +/** @public */ +export class ListCollectionsCursor< + T extends Pick | CollectionInfo = + | Pick + | CollectionInfo +> extends AbstractCursor { + parent: Db; + filter: Document; + options?: ListCollectionsOptions; + + constructor(db: Db, filter: Document, options?: ListCollectionsOptions) { + super(db.s.client, db.s.namespace, options); + this.parent = db; + this.filter = filter; + this.options = options; + } + + clone(): ListCollectionsCursor { + return new ListCollectionsCursor(this.parent, this.filter, { + ...this.options, + ...this.cursorOptions + }); + } + + /** @internal */ + _initialize(session: ClientSession | undefined, callback: Callback): void { + const operation = new ListCollectionsOperation(this.parent, this.filter, { + ...this.cursorOptions, + ...this.options, + session + }); + + executeOperation(this.parent.s.client, operation, (err, response) => { + if (err || response == null) return callback(err); + + // TODO: NODE-2882 + callback(undefined, { server: operation.server, session, response }); + }); + } +} diff --git a/ts-ticket-office-service/node_modules/mongodb/src/cursor/list_indexes_cursor.ts b/ts-ticket-office-service/node_modules/mongodb/src/cursor/list_indexes_cursor.ts new file mode 100644 index 000000000..25336d84d --- /dev/null +++ b/ts-ticket-office-service/node_modules/mongodb/src/cursor/list_indexes_cursor.ts @@ -0,0 +1,41 @@ +import type { Collection } from '../collection'; +import { executeOperation, ExecutionResult } from '../operations/execute_operation'; +import { ListIndexesOperation, ListIndexesOptions } from '../operations/indexes'; +import type { ClientSession } from '../sessions'; +import type { Callback } from '../utils'; +import { AbstractCursor } from './abstract_cursor'; + +/** @public */ +export class ListIndexesCursor extends AbstractCursor { + parent: Collection; + options?: ListIndexesOptions; + + constructor(collection: Collection, options?: ListIndexesOptions) { + super(collection.s.db.s.client, collection.s.namespace, options); + this.parent = collection; + this.options = options; + } + + clone(): ListIndexesCursor { + return new ListIndexesCursor(this.parent, { + ...this.options, + ...this.cursorOptions + }); + } + + /** @internal */ + _initialize(session: ClientSession | undefined, callback: Callback): void { + const operation = new ListIndexesOperation(this.parent, { + ...this.cursorOptions, + ...this.options, + session + }); + + executeOperation(this.parent.s.db.s.client, operation, (err, response) => { + if (err || response == null) return callback(err); + + // TODO: NODE-2882 + callback(undefined, { server: operation.server, session, response }); + }); + } +} diff --git a/ts-ticket-office-service/node_modules/mongodb/src/db.ts b/ts-ticket-office-service/node_modules/mongodb/src/db.ts new file mode 100644 index 000000000..136390ac7 --- /dev/null +++ b/ts-ticket-office-service/node_modules/mongodb/src/db.ts @@ -0,0 +1,770 @@ +import { Admin } from './admin'; +import { BSONSerializeOptions, Document, resolveBSONOptions } from './bson'; +import { ChangeStream, ChangeStreamDocument, ChangeStreamOptions } from './change_stream'; +import { Collection, CollectionOptions } from './collection'; +import * as CONSTANTS from './constants'; +import { AggregationCursor } from './cursor/aggregation_cursor'; +import { ListCollectionsCursor } from './cursor/list_collections_cursor'; +import { MongoAPIError, MongoInvalidArgumentError } from './error'; +import { Logger, LoggerOptions } from './logger'; +import type { MongoClient, PkFactory } from './mongo_client'; +import type { TODO_NODE_3286 } from './mongo_types'; +import { AddUserOperation, AddUserOptions } from './operations/add_user'; +import type { AggregateOptions } from './operations/aggregate'; +import { CollectionsOperation } from './operations/collections'; +import type { IndexInformationOptions } from './operations/common_functions'; +import { CreateCollectionOperation, CreateCollectionOptions } from './operations/create_collection'; +import { + DropCollectionOperation, + DropCollectionOptions, + DropDatabaseOperation, + DropDatabaseOptions +} from './operations/drop'; +import { executeOperation } from './operations/execute_operation'; +import { + CreateIndexesOptions, + CreateIndexOperation, + IndexInformationOperation, + IndexSpecification +} from './operations/indexes'; +import type { CollectionInfo, ListCollectionsOptions } from './operations/list_collections'; +import { ProfilingLevelOperation, ProfilingLevelOptions } from './operations/profiling_level'; +import { RemoveUserOperation, RemoveUserOptions } from './operations/remove_user'; +import { RenameOperation, RenameOptions } from './operations/rename'; +import { RunCommandOperation, RunCommandOptions } from './operations/run_command'; +import { + ProfilingLevel, + SetProfilingLevelOperation, + SetProfilingLevelOptions +} from './operations/set_profiling_level'; +import { DbStatsOperation, DbStatsOptions } from './operations/stats'; +import { ReadConcern } from './read_concern'; +import { ReadPreference, ReadPreferenceLike } from './read_preference'; +import { + Callback, + DEFAULT_PK_FACTORY, + filterOptions, + getTopology, + MongoDBNamespace, + resolveOptions +} from './utils'; +import { WriteConcern, WriteConcernOptions } from './write_concern'; + +// Allowed parameters +const DB_OPTIONS_ALLOW_LIST = [ + 'writeConcern', + 'readPreference', + 'readPreferenceTags', + 'native_parser', + 'forceServerObjectId', + 'pkFactory', + 'serializeFunctions', + 'raw', + 'authSource', + 'ignoreUndefined', + 'readConcern', + 'retryMiliSeconds', + 'numberOfRetries', + 'loggerLevel', + 'logger', + 'promoteBuffers', + 'promoteLongs', + 'bsonRegExp', + 'enableUtf8Validation', + 'promoteValues', + 'compression', + 'retryWrites' +]; + +/** @internal */ +export interface DbPrivate { + client: MongoClient; + options?: DbOptions; + logger: Logger; + readPreference?: ReadPreference; + pkFactory: PkFactory; + readConcern?: ReadConcern; + bsonOptions: BSONSerializeOptions; + writeConcern?: WriteConcern; + namespace: MongoDBNamespace; +} + +/** @public */ +export interface DbOptions extends BSONSerializeOptions, WriteConcernOptions, LoggerOptions { + /** If the database authentication is dependent on another databaseName. */ + authSource?: string; + /** Force server to assign _id values instead of driver. */ + forceServerObjectId?: boolean; + /** The preferred read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST). */ + readPreference?: ReadPreferenceLike; + /** A primary key factory object for generation of custom _id keys. */ + pkFactory?: PkFactory; + /** Specify a read concern for the collection. (only MongoDB 3.2 or higher supported) */ + readConcern?: ReadConcern; + /** Should retry failed writes */ + retryWrites?: boolean; +} + +/** + * The **Db** class is a class that represents a MongoDB Database. + * @public + * + * @example + * ```js + * const { MongoClient } = require('mongodb'); + * // Connection url + * const url = 'mongodb://localhost:27017'; + * // Database Name + * const dbName = 'test'; + * // Connect using MongoClient + * MongoClient.connect(url, function(err, client) { + * // Select the database by name + * const testDb = client.db(dbName); + * client.close(); + * }); + * ``` + */ +export class Db { + /** @internal */ + s: DbPrivate; + + public static SYSTEM_NAMESPACE_COLLECTION = CONSTANTS.SYSTEM_NAMESPACE_COLLECTION; + public static SYSTEM_INDEX_COLLECTION = CONSTANTS.SYSTEM_INDEX_COLLECTION; + public static SYSTEM_PROFILE_COLLECTION = CONSTANTS.SYSTEM_PROFILE_COLLECTION; + public static SYSTEM_USER_COLLECTION = CONSTANTS.SYSTEM_USER_COLLECTION; + public static SYSTEM_COMMAND_COLLECTION = CONSTANTS.SYSTEM_COMMAND_COLLECTION; + public static SYSTEM_JS_COLLECTION = CONSTANTS.SYSTEM_JS_COLLECTION; + + /** + * Creates a new Db instance + * + * @param client - The MongoClient for the database. + * @param databaseName - The name of the database this instance represents. + * @param options - Optional settings for Db construction + */ + constructor(client: MongoClient, databaseName: string, options?: DbOptions) { + options = options ?? {}; + + // Filter the options + options = filterOptions(options, DB_OPTIONS_ALLOW_LIST); + + // Ensure we have a valid db name + validateDatabaseName(databaseName); + + // Internal state of the db object + this.s = { + // Client + client, + // Options + options, + // Logger instance + logger: new Logger('Db', options), + // Unpack read preference + readPreference: ReadPreference.fromOptions(options), + // Merge bson options + bsonOptions: resolveBSONOptions(options, client), + // Set up the primary key factory or fallback to ObjectId + pkFactory: options?.pkFactory ?? DEFAULT_PK_FACTORY, + // ReadConcern + readConcern: ReadConcern.fromOptions(options), + writeConcern: WriteConcern.fromOptions(options), + // Namespace + namespace: new MongoDBNamespace(databaseName) + }; + } + + get databaseName(): string { + return this.s.namespace.db; + } + + // Options + get options(): DbOptions | undefined { + return this.s.options; + } + + /** + * slaveOk specified + * @deprecated Use secondaryOk instead + */ + get slaveOk(): boolean { + return this.secondaryOk; + } + + /** + * Check if a secondary can be used (because the read preference is *not* set to primary) + */ + get secondaryOk(): boolean { + return this.s.readPreference?.preference !== 'primary' || false; + } + + get readConcern(): ReadConcern | undefined { + return this.s.readConcern; + } + + /** + * The current readPreference of the Db. If not explicitly defined for + * this Db, will be inherited from the parent MongoClient + */ + get readPreference(): ReadPreference { + if (this.s.readPreference == null) { + return this.s.client.readPreference; + } + + return this.s.readPreference; + } + + get bsonOptions(): BSONSerializeOptions { + return this.s.bsonOptions; + } + + // get the write Concern + get writeConcern(): WriteConcern | undefined { + return this.s.writeConcern; + } + + get namespace(): string { + return this.s.namespace.toString(); + } + + /** + * Create a new collection on a server with the specified options. Use this to create capped collections. + * More information about command options available at https://docs.mongodb.com/manual/reference/command/create/ + * + * @param name - The name of the collection to create + * @param options - Optional settings for the command + * @param callback - An optional callback, a Promise will be returned if none is provided + */ + createCollection( + name: string, + options?: CreateCollectionOptions + ): Promise>; + createCollection( + name: string, + callback: Callback> + ): void; + createCollection( + name: string, + options: CreateCollectionOptions | undefined, + callback: Callback> + ): void; + createCollection( + name: string, + options?: CreateCollectionOptions | Callback, + callback?: Callback + ): Promise> | void { + if (typeof options === 'function') (callback = options), (options = {}); + + return executeOperation( + this.s.client, + new CreateCollectionOperation(this, name, resolveOptions(this, options)) as TODO_NODE_3286, + callback + ) as TODO_NODE_3286; + } + + /** + * Execute a command + * + * @remarks + * This command does not inherit options from the MongoClient. + * + * @param command - The command to run + * @param options - Optional settings for the command + * @param callback - An optional callback, a Promise will be returned if none is provided + */ + command(command: Document): Promise; + command(command: Document, callback: Callback): void; + command(command: Document, options: RunCommandOptions): Promise; + command(command: Document, options: RunCommandOptions, callback: Callback): void; + command( + command: Document, + options?: RunCommandOptions | Callback, + callback?: Callback + ): Promise | void { + if (typeof options === 'function') (callback = options), (options = {}); + + // Intentionally, we do not inherit options from parent for this operation. + return executeOperation( + this.s.client, + new RunCommandOperation(this, command, options ?? {}), + callback + ); + } + + /** + * Execute an aggregation framework pipeline against the database, needs MongoDB \>= 3.6 + * + * @param pipeline - An array of aggregation stages to be executed + * @param options - Optional settings for the command + */ + aggregate( + pipeline: Document[] = [], + options?: AggregateOptions + ): AggregationCursor { + if (arguments.length > 2) { + throw new MongoInvalidArgumentError('Method "db.aggregate()" accepts at most two arguments'); + } + if (typeof pipeline === 'function') { + throw new MongoInvalidArgumentError('Argument "pipeline" must not be function'); + } + if (typeof options === 'function') { + throw new MongoInvalidArgumentError('Argument "options" must not be function'); + } + + return new AggregationCursor( + this.s.client, + this.s.namespace, + pipeline, + resolveOptions(this, options) + ); + } + + /** Return the Admin db instance */ + admin(): Admin { + return new Admin(this); + } + + /** + * Returns a reference to a MongoDB Collection. If it does not exist it will be created implicitly. + * + * @param name - the collection name we wish to access. + * @returns return the new Collection instance + */ + collection( + name: string, + options: CollectionOptions = {} + ): Collection { + if (typeof options === 'function') { + throw new MongoInvalidArgumentError('The callback form of this helper has been removed.'); + } + const finalOptions = resolveOptions(this, options); + return new Collection(this, name, finalOptions); + } + + /** + * Get all the db statistics. + * + * @param options - Optional settings for the command + * @param callback - An optional callback, a Promise will be returned if none is provided + */ + stats(): Promise; + stats(callback: Callback): void; + stats(options: DbStatsOptions): Promise; + stats(options: DbStatsOptions, callback: Callback): void; + stats( + options?: DbStatsOptions | Callback, + callback?: Callback + ): Promise | void { + if (typeof options === 'function') (callback = options), (options = {}); + return executeOperation( + this.s.client, + new DbStatsOperation(this, resolveOptions(this, options)), + callback + ); + } + + /** + * List all collections of this database with optional filter + * + * @param filter - Query to filter collections by + * @param options - Optional settings for the command + */ + listCollections( + filter: Document, + options: Exclude & { nameOnly: true } + ): ListCollectionsCursor>; + listCollections( + filter: Document, + options: Exclude & { nameOnly: false } + ): ListCollectionsCursor; + listCollections< + T extends Pick | CollectionInfo = + | Pick + | CollectionInfo + >(filter?: Document, options?: ListCollectionsOptions): ListCollectionsCursor; + listCollections< + T extends Pick | CollectionInfo = + | Pick + | CollectionInfo + >(filter: Document = {}, options: ListCollectionsOptions = {}): ListCollectionsCursor { + return new ListCollectionsCursor(this, filter, resolveOptions(this, options)); + } + + /** + * Rename a collection. + * + * @remarks + * This operation does not inherit options from the MongoClient. + * + * @param fromCollection - Name of current collection to rename + * @param toCollection - New name of of the collection + * @param options - Optional settings for the command + * @param callback - An optional callback, a Promise will be returned if none is provided + */ + renameCollection( + fromCollection: string, + toCollection: string + ): Promise>; + renameCollection( + fromCollection: string, + toCollection: string, + callback: Callback> + ): void; + renameCollection( + fromCollection: string, + toCollection: string, + options: RenameOptions + ): Promise>; + renameCollection( + fromCollection: string, + toCollection: string, + options: RenameOptions, + callback: Callback> + ): void; + renameCollection( + fromCollection: string, + toCollection: string, + options?: RenameOptions | Callback>, + callback?: Callback> + ): Promise> | void { + if (typeof options === 'function') (callback = options), (options = {}); + + // Intentionally, we do not inherit options from parent for this operation. + options = { ...options, readPreference: ReadPreference.PRIMARY }; + + // Add return new collection + options.new_collection = true; + + return executeOperation( + this.s.client, + new RenameOperation( + this.collection(fromCollection) as TODO_NODE_3286, + toCollection, + options + ) as TODO_NODE_3286, + callback + ); + } + + /** + * Drop a collection from the database, removing it permanently. New accesses will create a new collection. + * + * @param name - Name of collection to drop + * @param options - Optional settings for the command + * @param callback - An optional callback, a Promise will be returned if none is provided + */ + dropCollection(name: string): Promise; + dropCollection(name: string, callback: Callback): void; + dropCollection(name: string, options: DropCollectionOptions): Promise; + dropCollection(name: string, options: DropCollectionOptions, callback: Callback): void; + dropCollection( + name: string, + options?: DropCollectionOptions | Callback, + callback?: Callback + ): Promise | void { + if (typeof options === 'function') (callback = options), (options = {}); + + return executeOperation( + this.s.client, + new DropCollectionOperation(this, name, resolveOptions(this, options)), + callback + ); + } + + /** + * Drop a database, removing it permanently from the server. + * + * @param options - Optional settings for the command + * @param callback - An optional callback, a Promise will be returned if none is provided + */ + dropDatabase(): Promise; + dropDatabase(callback: Callback): void; + dropDatabase(options: DropDatabaseOptions): Promise; + dropDatabase(options: DropDatabaseOptions, callback: Callback): void; + dropDatabase( + options?: DropDatabaseOptions | Callback, + callback?: Callback + ): Promise | void { + if (typeof options === 'function') (callback = options), (options = {}); + + return executeOperation( + this.s.client, + new DropDatabaseOperation(this, resolveOptions(this, options)), + callback + ); + } + + /** + * Fetch all collections for the current db. + * + * @param options - Optional settings for the command + * @param callback - An optional callback, a Promise will be returned if none is provided + */ + collections(): Promise; + collections(callback: Callback): void; + collections(options: ListCollectionsOptions): Promise; + collections(options: ListCollectionsOptions, callback: Callback): void; + collections( + options?: ListCollectionsOptions | Callback, + callback?: Callback + ): Promise | void { + if (typeof options === 'function') (callback = options), (options = {}); + + return executeOperation( + this.s.client, + new CollectionsOperation(this, resolveOptions(this, options)), + callback + ); + } + + /** + * Creates an index on the db and collection. + * + * @param name - Name of the collection to create the index on. + * @param indexSpec - Specify the field to index, or an index specification + * @param options - Optional settings for the command + * @param callback - An optional callback, a Promise will be returned if none is provided + */ + createIndex(name: string, indexSpec: IndexSpecification): Promise; + createIndex(name: string, indexSpec: IndexSpecification, callback?: Callback): void; + createIndex( + name: string, + indexSpec: IndexSpecification, + options: CreateIndexesOptions + ): Promise; + createIndex( + name: string, + indexSpec: IndexSpecification, + options: CreateIndexesOptions, + callback: Callback + ): void; + createIndex( + name: string, + indexSpec: IndexSpecification, + options?: CreateIndexesOptions | Callback, + callback?: Callback + ): Promise | void { + if (typeof options === 'function') (callback = options), (options = {}); + + return executeOperation( + this.s.client, + new CreateIndexOperation(this, name, indexSpec, resolveOptions(this, options)), + callback + ); + } + + /** + * Add a user to the database + * + * @param username - The username for the new user + * @param password - An optional password for the new user + * @param options - Optional settings for the command + * @param callback - An optional callback, a Promise will be returned if none is provided + */ + addUser(username: string): Promise; + addUser(username: string, callback: Callback): void; + addUser(username: string, password: string): Promise; + addUser(username: string, password: string, callback: Callback): void; + addUser(username: string, options: AddUserOptions): Promise; + addUser(username: string, options: AddUserOptions, callback: Callback): void; + addUser(username: string, password: string, options: AddUserOptions): Promise; + addUser( + username: string, + password: string, + options: AddUserOptions, + callback: Callback + ): void; + addUser( + username: string, + password?: string | AddUserOptions | Callback, + options?: AddUserOptions | Callback, + callback?: Callback + ): Promise | void { + if (typeof password === 'function') { + (callback = password), (password = undefined), (options = {}); + } else if (typeof password !== 'string') { + if (typeof options === 'function') { + (callback = options), (options = password), (password = undefined); + } else { + (options = password), (callback = undefined), (password = undefined); + } + } else { + if (typeof options === 'function') (callback = options), (options = {}); + } + + return executeOperation( + this.s.client, + new AddUserOperation(this, username, password, resolveOptions(this, options)), + callback + ); + } + + /** + * Remove a user from a database + * + * @param username - The username to remove + * @param options - Optional settings for the command + * @param callback - An optional callback, a Promise will be returned if none is provided + */ + removeUser(username: string): Promise; + removeUser(username: string, callback: Callback): void; + removeUser(username: string, options: RemoveUserOptions): Promise; + removeUser(username: string, options: RemoveUserOptions, callback: Callback): void; + removeUser( + username: string, + options?: RemoveUserOptions | Callback, + callback?: Callback + ): Promise | void { + if (typeof options === 'function') (callback = options), (options = {}); + + return executeOperation( + this.s.client, + new RemoveUserOperation(this, username, resolveOptions(this, options)), + callback + ); + } + + /** + * Set the current profiling level of MongoDB + * + * @param level - The new profiling level (off, slow_only, all). + * @param options - Optional settings for the command + * @param callback - An optional callback, a Promise will be returned if none is provided + */ + setProfilingLevel(level: ProfilingLevel): Promise; + setProfilingLevel(level: ProfilingLevel, callback: Callback): void; + setProfilingLevel( + level: ProfilingLevel, + options: SetProfilingLevelOptions + ): Promise; + setProfilingLevel( + level: ProfilingLevel, + options: SetProfilingLevelOptions, + callback: Callback + ): void; + setProfilingLevel( + level: ProfilingLevel, + options?: SetProfilingLevelOptions | Callback, + callback?: Callback + ): Promise | void { + if (typeof options === 'function') (callback = options), (options = {}); + + return executeOperation( + this.s.client, + new SetProfilingLevelOperation(this, level, resolveOptions(this, options)), + callback + ); + } + + /** + * Retrieve the current profiling Level for MongoDB + * + * @param options - Optional settings for the command + * @param callback - An optional callback, a Promise will be returned if none is provided + */ + profilingLevel(): Promise; + profilingLevel(callback: Callback): void; + profilingLevel(options: ProfilingLevelOptions): Promise; + profilingLevel(options: ProfilingLevelOptions, callback: Callback): void; + profilingLevel( + options?: ProfilingLevelOptions | Callback, + callback?: Callback + ): Promise | void { + if (typeof options === 'function') (callback = options), (options = {}); + + return executeOperation( + this.s.client, + new ProfilingLevelOperation(this, resolveOptions(this, options)), + callback + ); + } + + /** + * Retrieves this collections index info. + * + * @param name - The name of the collection. + * @param options - Optional settings for the command + * @param callback - An optional callback, a Promise will be returned if none is provided + */ + indexInformation(name: string): Promise; + indexInformation(name: string, callback: Callback): void; + indexInformation(name: string, options: IndexInformationOptions): Promise; + indexInformation( + name: string, + options: IndexInformationOptions, + callback: Callback + ): void; + indexInformation( + name: string, + options?: IndexInformationOptions | Callback, + callback?: Callback + ): Promise | void { + if (typeof options === 'function') (callback = options), (options = {}); + + return executeOperation( + this.s.client, + new IndexInformationOperation(this, name, resolveOptions(this, options)), + callback + ); + } + + /** + * Unref all sockets + * @deprecated This function is deprecated and will be removed in the next major version. + */ + unref(): void { + getTopology(this).unref(); + } + + /** + * Create a new Change Stream, watching for new changes (insertions, updates, + * replacements, deletions, and invalidations) in this database. Will ignore all + * changes to system collections. + * + * @remarks + * watch() accepts two generic arguments for distinct usecases: + * - The first is to provide the schema that may be defined for all the collections within this database + * - The second is to override the shape of the change stream document entirely, if it is not provided the type will default to ChangeStreamDocument of the first argument + * + * @param pipeline - An array of {@link https://docs.mongodb.com/manual/reference/operator/aggregation-pipeline/|aggregation pipeline stages} through which to pass change stream documents. This allows for filtering (using $match) and manipulating the change stream documents. + * @param options - Optional settings for the command + * @typeParam TSchema - Type of the data being detected by the change stream + * @typeParam TChange - Type of the whole change stream document emitted + */ + watch< + TSchema extends Document = Document, + TChange extends Document = ChangeStreamDocument + >(pipeline: Document[] = [], options: ChangeStreamOptions = {}): ChangeStream { + // Allow optionally not specifying a pipeline + if (!Array.isArray(pipeline)) { + options = pipeline; + pipeline = []; + } + + return new ChangeStream(this, pipeline, resolveOptions(this, options)); + } + + /** Return the db logger */ + getLogger(): Logger { + return this.s.logger; + } + + get logger(): Logger { + return this.s.logger; + } +} + +// TODO(NODE-3484): Refactor into MongoDBNamespace +// Validate the database name +function validateDatabaseName(databaseName: string) { + if (typeof databaseName !== 'string') + throw new MongoInvalidArgumentError('Database name must be a string'); + if (databaseName.length === 0) + throw new MongoInvalidArgumentError('Database name cannot be the empty string'); + if (databaseName === '$external') return; + + const invalidChars = [' ', '.', '$', '/', '\\']; + for (let i = 0; i < invalidChars.length; i++) { + if (databaseName.indexOf(invalidChars[i]) !== -1) + throw new MongoAPIError(`database names cannot contain the character '${invalidChars[i]}'`); + } +} diff --git a/ts-ticket-office-service/node_modules/mongodb/src/deps.ts b/ts-ticket-office-service/node_modules/mongodb/src/deps.ts new file mode 100644 index 000000000..9201c30b2 --- /dev/null +++ b/ts-ticket-office-service/node_modules/mongodb/src/deps.ts @@ -0,0 +1,378 @@ +/* eslint-disable @typescript-eslint/no-var-requires */ +import type { deserialize, Document, serialize } from './bson'; +import type { ProxyOptions } from './cmap/connection'; +import { MongoMissingDependencyError } from './error'; +import type { MongoClient } from './mongo_client'; +import { Callback, parsePackageVersion } from './utils'; + +export const PKG_VERSION = Symbol('kPkgVersion'); + +function makeErrorModule(error: any) { + const props = error ? { kModuleError: error } : {}; + return new Proxy(props, { + get: (_: any, key: any) => { + if (key === 'kModuleError') { + return error; + } + throw error; + }, + set: () => { + throw error; + } + }); +} + +export let Kerberos: typeof import('kerberos') | { kModuleError: MongoMissingDependencyError } = + makeErrorModule( + new MongoMissingDependencyError( + 'Optional module `kerberos` not found. Please install it to enable kerberos authentication' + ) + ); + +try { + // Ensure you always wrap an optional require in the try block NODE-3199 + Kerberos = require('kerberos'); +} catch {} // eslint-disable-line + +export interface KerberosClient { + step(challenge: string): Promise; + step(challenge: string, callback: Callback): void; + wrap(challenge: string, options: { user: string }): Promise; + wrap(challenge: string, options: { user: string }, callback: Callback): void; + unwrap(challenge: string): Promise; + unwrap(challenge: string, callback: Callback): void; +} + +type ZStandardLib = { + /** + * Compress using zstd. + * @param buf - Buffer to be compressed. + */ + compress(buf: Buffer, level?: number): Promise; + + /** + * Decompress using zstd. + */ + decompress(buf: Buffer): Promise; +}; + +export let ZStandard: ZStandardLib | { kModuleError: MongoMissingDependencyError } = + makeErrorModule( + new MongoMissingDependencyError( + 'Optional module `@mongodb-js/zstd` not found. Please install it to enable zstd compression' + ) + ); + +try { + ZStandard = require('@mongodb-js/zstd'); +} catch {} // eslint-disable-line + +type SnappyLib = { + [PKG_VERSION]: { major: number; minor: number; patch: number }; + + /** + * - Snappy 6.x takes a callback and returns void + * - Snappy 7.x returns a promise + * + * In order to support both we must check the return value of the function + * @param buf - Buffer to be compressed + * @param callback - ONLY USED IN SNAPPY 6.x + */ + compress(buf: Buffer): Promise; + compress(buf: Buffer, callback: (error?: Error, buffer?: Buffer) => void): void; + + /** + * - Snappy 6.x takes a callback and returns void + * - Snappy 7.x returns a promise + * + * In order to support both we must check the return value of the function + * @param buf - Buffer to be compressed + * @param callback - ONLY USED IN SNAPPY 6.x + */ + uncompress(buf: Buffer, opt: { asBuffer: true }): Promise; + uncompress( + buf: Buffer, + opt: { asBuffer: true }, + callback: (error?: Error, buffer?: Buffer) => void + ): void; +}; + +export let Snappy: SnappyLib | { kModuleError: MongoMissingDependencyError } = makeErrorModule( + new MongoMissingDependencyError( + 'Optional module `snappy` not found. Please install it to enable snappy compression' + ) +); + +try { + // Ensure you always wrap an optional require in the try block NODE-3199 + Snappy = require('snappy'); + try { + (Snappy as any)[PKG_VERSION] = parsePackageVersion(require('snappy/package.json')); + } catch {} // eslint-disable-line +} catch {} // eslint-disable-line + +export let saslprep: typeof import('saslprep') | { kModuleError: MongoMissingDependencyError } = + makeErrorModule( + new MongoMissingDependencyError( + 'Optional module `saslprep` not found.' + + ' Please install it to enable Stringprep Profile for User Names and Passwords' + ) + ); + +try { + // Ensure you always wrap an optional require in the try block NODE-3199 + saslprep = require('saslprep'); +} catch {} // eslint-disable-line + +interface AWS4 { + /** + * Created these inline types to better assert future usage of this API + * @param options - options for request + * @param credentials - AWS credential details, sessionToken should be omitted entirely if its false-y + */ + sign( + this: void, + options: { + path: '/'; + body: string; + host: string; + method: 'POST'; + headers: { + 'Content-Type': 'application/x-www-form-urlencoded'; + 'Content-Length': number; + 'X-MongoDB-Server-Nonce': string; + 'X-MongoDB-GS2-CB-Flag': 'n'; + }; + service: string; + region: string; + }, + credentials: + | { + accessKeyId: string; + secretAccessKey: string; + sessionToken: string; + } + | { + accessKeyId: string; + secretAccessKey: string; + } + | undefined + ): { + headers: { + Authorization: string; + 'X-Amz-Date': string; + }; + }; +} + +export let aws4: AWS4 | { kModuleError: MongoMissingDependencyError } = makeErrorModule( + new MongoMissingDependencyError( + 'Optional module `aws4` not found. Please install it to enable AWS authentication' + ) +); + +try { + // Ensure you always wrap an optional require in the try block NODE-3199 + aws4 = require('aws4'); +} catch {} // eslint-disable-line + +/** @public */ +export const AutoEncryptionLoggerLevel = Object.freeze({ + FatalError: 0, + Error: 1, + Warning: 2, + Info: 3, + Trace: 4 +} as const); + +/** @public */ +export type AutoEncryptionLoggerLevel = + typeof AutoEncryptionLoggerLevel[keyof typeof AutoEncryptionLoggerLevel]; + +/** @public */ +export interface AutoEncryptionTlsOptions { + /** + * Specifies the location of a local .pem file that contains + * either the client's TLS/SSL certificate and key or only the + * client's TLS/SSL key when tlsCertificateFile is used to + * provide the certificate. + */ + tlsCertificateKeyFile?: string; + /** + * Specifies the password to de-crypt the tlsCertificateKeyFile. + */ + tlsCertificateKeyFilePassword?: string; + /** + * Specifies the location of a local .pem file that contains the + * root certificate chain from the Certificate Authority. + * This file is used to validate the certificate presented by the + * KMS provider. + */ + tlsCAFile?: string; +} + +/** @public */ +export interface AutoEncryptionOptions { + /** @internal */ + bson?: { serialize: typeof serialize; deserialize: typeof deserialize }; + /** @internal client for metadata lookups */ + metadataClient?: MongoClient; + /** A `MongoClient` used to fetch keys from a key vault */ + keyVaultClient?: MongoClient; + /** The namespace where keys are stored in the key vault */ + keyVaultNamespace?: string; + /** Configuration options that are used by specific KMS providers during key generation, encryption, and decryption. */ + kmsProviders?: { + /** Configuration options for using 'aws' as your KMS provider */ + aws?: { + /** The access key used for the AWS KMS provider */ + accessKeyId: string; + /** The secret access key used for the AWS KMS provider */ + secretAccessKey: string; + /** + * An optional AWS session token that will be used as the + * X-Amz-Security-Token header for AWS requests. + */ + sessionToken?: string; + }; + /** Configuration options for using 'local' as your KMS provider */ + local?: { + /** + * The master key used to encrypt/decrypt data keys. + * A 96-byte long Buffer or base64 encoded string. + */ + key: Buffer | string; + }; + /** Configuration options for using 'azure' as your KMS provider */ + azure?: { + /** The tenant ID identifies the organization for the account */ + tenantId: string; + /** The client ID to authenticate a registered application */ + clientId: string; + /** The client secret to authenticate a registered application */ + clientSecret: string; + /** + * If present, a host with optional port. E.g. "example.com" or "example.com:443". + * This is optional, and only needed if customer is using a non-commercial Azure instance + * (e.g. a government or China account, which use different URLs). + * Defaults to "login.microsoftonline.com" + */ + identityPlatformEndpoint?: string | undefined; + }; + /** Configuration options for using 'gcp' as your KMS provider */ + gcp?: { + /** The service account email to authenticate */ + email: string; + /** A PKCS#8 encrypted key. This can either be a base64 string or a binary representation */ + privateKey: string | Buffer; + /** + * If present, a host with optional port. E.g. "example.com" or "example.com:443". + * Defaults to "oauth2.googleapis.com" + */ + endpoint?: string | undefined; + }; + /** + * Configuration options for using 'kmip' as your KMS provider + */ + kmip?: { + /** + * The output endpoint string. + * The endpoint consists of a hostname and port separated by a colon. + * E.g. "example.com:123". A port is always present. + */ + endpoint?: string; + }; + }; + /** + * A map of namespaces to a local JSON schema for encryption + * + * **NOTE**: Supplying options.schemaMap provides more security than relying on JSON Schemas obtained from the server. + * It protects against a malicious server advertising a false JSON Schema, which could trick the client into sending decrypted data that should be encrypted. + * Schemas supplied in the schemaMap only apply to configuring automatic encryption for client side encryption. + * Other validation rules in the JSON schema will not be enforced by the driver and will result in an error. + */ + schemaMap?: Document; + /** @experimental Public Technical Preview: Supply a schema for the encrypted fields in the document */ + encryptedFieldsMap?: Document; + /** Allows the user to bypass auto encryption, maintaining implicit decryption */ + bypassAutoEncryption?: boolean; + /** @experimental Public Technical Preview: Allows users to bypass query analysis */ + bypassQueryAnalysis?: boolean; + options?: { + /** An optional hook to catch logging messages from the underlying encryption engine */ + logger?: (level: AutoEncryptionLoggerLevel, message: string) => void; + }; + extraOptions?: { + /** + * A local process the driver communicates with to determine how to encrypt values in a command. + * Defaults to "mongodb://%2Fvar%2Fmongocryptd.sock" if domain sockets are available or "mongodb://localhost:27020" otherwise + */ + mongocryptdURI?: string; + /** If true, autoEncryption will not attempt to spawn a mongocryptd before connecting */ + mongocryptdBypassSpawn?: boolean; + /** The path to the mongocryptd executable on the system */ + mongocryptdSpawnPath?: string; + /** Command line arguments to use when auto-spawning a mongocryptd */ + mongocryptdSpawnArgs?: string[]; + /** + * Full path to a MongoDB Crypt shared library to be used (instead of mongocryptd). + * + * This needs to be the path to the file itself, not a directory. + * It can be an absolute or relative path. If the path is relative and + * its first component is `$ORIGIN`, it will be replaced by the directory + * containing the mongodb-client-encryption native addon file. Otherwise, + * the path will be interpreted relative to the current working directory. + * + * Currently, loading different MongoDB Crypt shared library files from different + * MongoClients in the same process is not supported. + * + * If this option is provided and no MongoDB Crypt shared library could be loaded + * from the specified location, creating the MongoClient will fail. + * + * If this option is not provided and `cryptSharedLibRequired` is not specified, + * the AutoEncrypter will attempt to spawn and/or use mongocryptd according + * to the mongocryptd-specific `extraOptions` options. + * + * Specifying a path prevents mongocryptd from being used as a fallback. + * + * Requires the MongoDB Crypt shared library, available in MongoDB 6.0 or higher. + */ + cryptSharedLibPath?: string; + /** + * If specified, never use mongocryptd and instead fail when the MongoDB Crypt + * shared library could not be loaded. + * + * This is always true when `cryptSharedLibPath` is specified. + * + * Requires the MongoDB Crypt shared library, available in MongoDB 6.0 or higher. + */ + cryptSharedLibRequired?: boolean; + /** + * Search paths for a MongoDB Crypt shared library to be used (instead of mongocryptd) + * Only for driver testing! + * @internal + */ + cryptSharedLibSearchPaths?: string[]; + }; + proxyOptions?: ProxyOptions; + /** The TLS options to use connecting to the KMS provider */ + tlsOptions?: { + aws?: AutoEncryptionTlsOptions; + local?: AutoEncryptionTlsOptions; + azure?: AutoEncryptionTlsOptions; + gcp?: AutoEncryptionTlsOptions; + kmip?: AutoEncryptionTlsOptions; + }; +} + +/** @public */ +export interface AutoEncrypter { + // eslint-disable-next-line @typescript-eslint/no-misused-new + new (client: MongoClient, options: AutoEncryptionOptions): AutoEncrypter; + init(cb: Callback): void; + teardown(force: boolean, callback: Callback): void; + encrypt(ns: string, cmd: Document, options: any, callback: Callback): void; + decrypt(cmd: Document, options: any, callback: Callback): void; + /** @experimental */ + readonly cryptSharedLibVersionInfo: { version: bigint; versionStr: string } | null; +} diff --git a/ts-ticket-office-service/node_modules/mongodb/src/encrypter.ts b/ts-ticket-office-service/node_modules/mongodb/src/encrypter.ts new file mode 100644 index 000000000..316c44f9e --- /dev/null +++ b/ts-ticket-office-service/node_modules/mongodb/src/encrypter.ts @@ -0,0 +1,137 @@ +/* eslint-disable @typescript-eslint/no-var-requires */ +import { deserialize, serialize } from './bson'; +import { MONGO_CLIENT_EVENTS } from './constants'; +import type { AutoEncrypter, AutoEncryptionOptions } from './deps'; +import { MongoInvalidArgumentError, MongoMissingDependencyError } from './error'; +import { MongoClient, MongoClientOptions } from './mongo_client'; +import { Callback, getMongoDBClientEncryption } from './utils'; + +let AutoEncrypterClass: AutoEncrypter; + +/** @internal */ +const kInternalClient = Symbol('internalClient'); + +/** @internal */ +export interface EncrypterOptions { + autoEncryption: AutoEncryptionOptions; + maxPoolSize?: number; +} + +/** @internal */ +export class Encrypter { + [kInternalClient]: MongoClient | null; + bypassAutoEncryption: boolean; + needsConnecting: boolean; + autoEncrypter: AutoEncrypter; + + constructor(client: MongoClient, uri: string, options: MongoClientOptions) { + if (typeof options.autoEncryption !== 'object') { + throw new MongoInvalidArgumentError('Option "autoEncryption" must be specified'); + } + // initialize to null, if we call getInternalClient, we may set this it is important to not overwrite those function calls. + this[kInternalClient] = null; + + this.bypassAutoEncryption = !!options.autoEncryption.bypassAutoEncryption; + this.needsConnecting = false; + + if (options.maxPoolSize === 0 && options.autoEncryption.keyVaultClient == null) { + options.autoEncryption.keyVaultClient = client; + } else if (options.autoEncryption.keyVaultClient == null) { + options.autoEncryption.keyVaultClient = this.getInternalClient(client, uri, options); + } + + if (this.bypassAutoEncryption) { + options.autoEncryption.metadataClient = undefined; + } else if (options.maxPoolSize === 0) { + options.autoEncryption.metadataClient = client; + } else { + options.autoEncryption.metadataClient = this.getInternalClient(client, uri, options); + } + + if (options.proxyHost) { + options.autoEncryption.proxyOptions = { + proxyHost: options.proxyHost, + proxyPort: options.proxyPort, + proxyUsername: options.proxyUsername, + proxyPassword: options.proxyPassword + }; + } + + options.autoEncryption.bson = Object.create(null); + // eslint-disable-next-line @typescript-eslint/no-non-null-assertion + options.autoEncryption.bson!.serialize = serialize; + // eslint-disable-next-line @typescript-eslint/no-non-null-assertion + options.autoEncryption.bson!.deserialize = deserialize; + + this.autoEncrypter = new AutoEncrypterClass(client, options.autoEncryption); + } + + getInternalClient(client: MongoClient, uri: string, options: MongoClientOptions): MongoClient { + // TODO(NODE-4144): Remove new variable for type narrowing + let internalClient = this[kInternalClient]; + if (internalClient == null) { + const clonedOptions: MongoClientOptions = {}; + + for (const key of [ + ...Object.getOwnPropertyNames(options), + ...Object.getOwnPropertySymbols(options) + ] as string[]) { + if (['autoEncryption', 'minPoolSize', 'servers', 'caseTranslate', 'dbName'].includes(key)) + continue; + Reflect.set(clonedOptions, key, Reflect.get(options, key)); + } + + clonedOptions.minPoolSize = 0; + + internalClient = new MongoClient(uri, clonedOptions); + this[kInternalClient] = internalClient; + + for (const eventName of MONGO_CLIENT_EVENTS) { + for (const listener of client.listeners(eventName)) { + internalClient.on(eventName, listener); + } + } + + client.on('newListener', (eventName, listener) => { + internalClient?.on(eventName, listener); + }); + + this.needsConnecting = true; + } + return internalClient; + } + + connectInternalClient(callback: Callback): void { + // TODO(NODE-4144): Remove new variable for type narrowing + const internalClient = this[kInternalClient]; + if (this.needsConnecting && internalClient != null) { + this.needsConnecting = false; + return internalClient.connect(callback); + } + + return callback(); + } + + close(client: MongoClient, force: boolean, callback: Callback): void { + this.autoEncrypter.teardown(!!force, e => { + const internalClient = this[kInternalClient]; + if (internalClient != null && client !== internalClient) { + return internalClient.close(force, callback); + } + callback(e); + }); + } + + static checkForMongoCrypt(): void { + try { + // NOTE(NODE-3199): Ensure you always wrap an optional require in the try block + const mongodbClientEncryption = getMongoDBClientEncryption(); + AutoEncrypterClass = mongodbClientEncryption.extension(require('../lib/index')).AutoEncrypter; + } catch { + throw new MongoMissingDependencyError( + 'Auto-encryption requested, but the module is not installed. ' + + 'Please add `mongodb-client-encryption` as a dependency of your project' + ); + } + } +} diff --git a/ts-ticket-office-service/node_modules/mongodb/src/error.ts b/ts-ticket-office-service/node_modules/mongodb/src/error.ts new file mode 100644 index 000000000..7a788b923 --- /dev/null +++ b/ts-ticket-office-service/node_modules/mongodb/src/error.ts @@ -0,0 +1,924 @@ +import type { Document } from './bson'; +import type { TopologyVersion } from './sdam/server_description'; +import type { TopologyDescription } from './sdam/topology_description'; + +/** @public */ +export type AnyError = MongoError | Error; + +/** @internal */ +const kErrorLabels = Symbol('errorLabels'); + +/** + * @internal + * The legacy error message from the server that indicates the node is not a writable primary + * https://github.com/mongodb/specifications/blob/b07c26dc40d04ac20349f989db531c9845fdd755/source/server-discovery-and-monitoring/server-discovery-and-monitoring.rst#not-writable-primary-and-node-is-recovering + */ +export const LEGACY_NOT_WRITABLE_PRIMARY_ERROR_MESSAGE = new RegExp('not master', 'i'); + +/** + * @internal + * The legacy error message from the server that indicates the node is not a primary or secondary + * https://github.com/mongodb/specifications/blob/b07c26dc40d04ac20349f989db531c9845fdd755/source/server-discovery-and-monitoring/server-discovery-and-monitoring.rst#not-writable-primary-and-node-is-recovering + */ +export const LEGACY_NOT_PRIMARY_OR_SECONDARY_ERROR_MESSAGE = new RegExp( + 'not master or secondary', + 'i' +); + +/** + * @internal + * The error message from the server that indicates the node is recovering + * https://github.com/mongodb/specifications/blob/b07c26dc40d04ac20349f989db531c9845fdd755/source/server-discovery-and-monitoring/server-discovery-and-monitoring.rst#not-writable-primary-and-node-is-recovering + */ +export const NODE_IS_RECOVERING_ERROR_MESSAGE = new RegExp('node is recovering', 'i'); + +/** @internal MongoDB Error Codes */ +export const MONGODB_ERROR_CODES = Object.freeze({ + HostUnreachable: 6, + HostNotFound: 7, + NetworkTimeout: 89, + ShutdownInProgress: 91, + PrimarySteppedDown: 189, + ExceededTimeLimit: 262, + SocketException: 9001, + NotWritablePrimary: 10107, + InterruptedAtShutdown: 11600, + InterruptedDueToReplStateChange: 11602, + NotPrimaryNoSecondaryOk: 13435, + NotPrimaryOrSecondary: 13436, + StaleShardVersion: 63, + StaleEpoch: 150, + StaleConfig: 13388, + RetryChangeStream: 234, + FailedToSatisfyReadPreference: 133, + CursorNotFound: 43, + LegacyNotPrimary: 10058, + WriteConcernFailed: 64, + NamespaceNotFound: 26, + IllegalOperation: 20, + MaxTimeMSExpired: 50, + UnknownReplWriteConcern: 79, + UnsatisfiableWriteConcern: 100 +} as const); + +// From spec@https://github.com/mongodb/specifications/blob/f93d78191f3db2898a59013a7ed5650352ef6da8/source/change-streams/change-streams.rst#resumable-error +export const GET_MORE_RESUMABLE_CODES = new Set([ + MONGODB_ERROR_CODES.HostUnreachable, + MONGODB_ERROR_CODES.HostNotFound, + MONGODB_ERROR_CODES.NetworkTimeout, + MONGODB_ERROR_CODES.ShutdownInProgress, + MONGODB_ERROR_CODES.PrimarySteppedDown, + MONGODB_ERROR_CODES.ExceededTimeLimit, + MONGODB_ERROR_CODES.SocketException, + MONGODB_ERROR_CODES.NotWritablePrimary, + MONGODB_ERROR_CODES.InterruptedAtShutdown, + MONGODB_ERROR_CODES.InterruptedDueToReplStateChange, + MONGODB_ERROR_CODES.NotPrimaryNoSecondaryOk, + MONGODB_ERROR_CODES.NotPrimaryOrSecondary, + MONGODB_ERROR_CODES.StaleShardVersion, + MONGODB_ERROR_CODES.StaleEpoch, + MONGODB_ERROR_CODES.StaleConfig, + MONGODB_ERROR_CODES.RetryChangeStream, + MONGODB_ERROR_CODES.FailedToSatisfyReadPreference, + MONGODB_ERROR_CODES.CursorNotFound +]); + +/** @public */ +export const MongoErrorLabel = Object.freeze({ + RetryableWriteError: 'RetryableWriteError', + TransientTransactionError: 'TransientTransactionError', + UnknownTransactionCommitResult: 'UnknownTransactionCommitResult', + ResumableChangeStreamError: 'ResumableChangeStreamError', + HandshakeError: 'HandshakeError' +} as const); + +/** @public */ +export type MongoErrorLabel = typeof MongoErrorLabel[keyof typeof MongoErrorLabel]; + +/** @public */ +export interface ErrorDescription extends Document { + message?: string; + errmsg?: string; + $err?: string; + errorLabels?: string[]; + errInfo?: Document; +} + +/** + * @public + * @category Error + * + * @privateRemarks + * CSFLE has a dependency on this error, it uses the constructor with a string argument + */ +export class MongoError extends Error { + /** @internal */ + [kErrorLabels]: Set; + /** + * This is a number in MongoServerError and a string in MongoDriverError + * @privateRemarks + * Define the type override on the subclasses when we can use the override keyword + */ + code?: number | string; + topologyVersion?: TopologyVersion; + + constructor(message: string | Error) { + if (message instanceof Error) { + super(message.message); + } else { + super(message); + } + this[kErrorLabels] = new Set(); + } + + override get name(): string { + return 'MongoError'; + } + + /** Legacy name for server error responses */ + get errmsg(): string { + return this.message; + } + + /** + * Checks the error to see if it has an error label + * + * @param label - The error label to check for + * @returns returns true if the error has the provided error label + */ + hasErrorLabel(label: string): boolean { + return this[kErrorLabels].has(label); + } + + addErrorLabel(label: string): void { + this[kErrorLabels].add(label); + } + + get errorLabels(): string[] { + return Array.from(this[kErrorLabels]); + } +} + +/** + * An error coming from the mongo server + * + * @public + * @category Error + */ +export class MongoServerError extends MongoError { + codeName?: string; + writeConcernError?: Document; + errInfo?: Document; + ok?: number; + [key: string]: any; + + constructor(message: ErrorDescription) { + super(message.message || message.errmsg || message.$err || 'n/a'); + if (message.errorLabels) { + this[kErrorLabels] = new Set(message.errorLabels); + } + + for (const name in message) { + if (name !== 'errorLabels' && name !== 'errmsg' && name !== 'message') + this[name] = message[name]; + } + } + + override get name(): string { + return 'MongoServerError'; + } +} + +/** + * An error generated by the driver + * + * @public + * @category Error + */ +export class MongoDriverError extends MongoError { + constructor(message: string) { + super(message); + } + + override get name(): string { + return 'MongoDriverError'; + } +} + +/** + * An error generated when the driver API is used incorrectly + * + * @privateRemarks + * Should **never** be directly instantiated + * + * @public + * @category Error + */ + +export class MongoAPIError extends MongoDriverError { + constructor(message: string) { + super(message); + } + + override get name(): string { + return 'MongoAPIError'; + } +} + +/** + * An error generated when the driver encounters unexpected input + * or reaches an unexpected/invalid internal state + * + * @privateRemarks + * Should **never** be directly instantiated. + * + * @public + * @category Error + */ +export class MongoRuntimeError extends MongoDriverError { + constructor(message: string) { + super(message); + } + + override get name(): string { + return 'MongoRuntimeError'; + } +} + +/** + * An error generated when a batch command is re-executed after one of the commands in the batch + * has failed + * + * @public + * @category Error + */ +export class MongoBatchReExecutionError extends MongoAPIError { + constructor(message = 'This batch has already been executed, create new batch to execute') { + super(message); + } + + override get name(): string { + return 'MongoBatchReExecutionError'; + } +} + +/** + * An error generated when the driver fails to decompress + * data received from the server. + * + * @public + * @category Error + */ +export class MongoDecompressionError extends MongoRuntimeError { + constructor(message: string) { + super(message); + } + + override get name(): string { + return 'MongoDecompressionError'; + } +} + +/** + * An error thrown when the user attempts to operate on a database or collection through a MongoClient + * that has not yet successfully called the "connect" method + * + * @public + * @category Error + */ +export class MongoNotConnectedError extends MongoAPIError { + constructor(message: string) { + super(message); + } + + override get name(): string { + return 'MongoNotConnectedError'; + } +} + +/** + * An error generated when the user makes a mistake in the usage of transactions. + * (e.g. attempting to commit a transaction with a readPreference other than primary) + * + * @public + * @category Error + */ +export class MongoTransactionError extends MongoAPIError { + constructor(message: string) { + super(message); + } + + override get name(): string { + return 'MongoTransactionError'; + } +} + +/** + * An error generated when the user attempts to operate + * on a session that has expired or has been closed. + * + * @public + * @category Error + */ +export class MongoExpiredSessionError extends MongoAPIError { + constructor(message = 'Cannot use a session that has ended') { + super(message); + } + + override get name(): string { + return 'MongoExpiredSessionError'; + } +} + +/** + * A error generated when the user attempts to authenticate + * via Kerberos, but fails to connect to the Kerberos client. + * + * @public + * @category Error + */ +export class MongoKerberosError extends MongoRuntimeError { + constructor(message: string) { + super(message); + } + + override get name(): string { + return 'MongoKerberosError'; + } +} + +/** + * A error generated when the user attempts to authenticate + * via AWS, but fails + * + * @public + * @category Error + */ +export class MongoAWSError extends MongoRuntimeError { + constructor(message: string) { + super(message); + } + + override get name(): string { + return 'MongoAWSError'; + } +} + +/** + * An error generated when a ChangeStream operation fails to execute. + * + * @public + * @category Error + */ +export class MongoChangeStreamError extends MongoRuntimeError { + constructor(message: string) { + super(message); + } + + override get name(): string { + return 'MongoChangeStreamError'; + } +} + +/** + * An error thrown when the user calls a function or method not supported on a tailable cursor + * + * @public + * @category Error + */ +export class MongoTailableCursorError extends MongoAPIError { + constructor(message = 'Tailable cursor does not support this operation') { + super(message); + } + + override get name(): string { + return 'MongoTailableCursorError'; + } +} + +/** An error generated when a GridFSStream operation fails to execute. + * + * @public + * @category Error + */ +export class MongoGridFSStreamError extends MongoRuntimeError { + constructor(message: string) { + super(message); + } + + override get name(): string { + return 'MongoGridFSStreamError'; + } +} + +/** + * An error generated when a malformed or invalid chunk is + * encountered when reading from a GridFSStream. + * + * @public + * @category Error + */ +export class MongoGridFSChunkError extends MongoRuntimeError { + constructor(message: string) { + super(message); + } + + override get name(): string { + return 'MongoGridFSChunkError'; + } +} + +/** + * An error generated when a **parsable** unexpected response comes from the server. + * This is generally an error where the driver in a state expecting a certain behavior to occur in + * the next message from MongoDB but it receives something else. + * This error **does not** represent an issue with wire message formatting. + * + * #### Example + * When an operation fails, it is the driver's job to retry it. It must perform serverSelection + * again to make sure that it attempts the operation against a server in a good state. If server + * selection returns a server that does not support retryable operations, this error is used. + * This scenario is unlikely as retryable support would also have been determined on the first attempt + * but it is possible the state change could report a selectable server that does not support retries. + * + * @public + * @category Error + */ +export class MongoUnexpectedServerResponseError extends MongoRuntimeError { + constructor(message: string) { + super(message); + } + + override get name(): string { + return 'MongoUnexpectedServerResponseError'; + } +} + +/** + * An error thrown when the user attempts to add options to a cursor that has already been + * initialized + * + * @public + * @category Error + */ +export class MongoCursorInUseError extends MongoAPIError { + constructor(message = 'Cursor is already initialized') { + super(message); + } + + override get name(): string { + return 'MongoCursorInUseError'; + } +} + +/** + * An error generated when an attempt is made to operate + * on a closed/closing server. + * + * @public + * @category Error + */ +export class MongoServerClosedError extends MongoAPIError { + constructor(message = 'Server is closed') { + super(message); + } + + override get name(): string { + return 'MongoServerClosedError'; + } +} + +/** + * An error thrown when an attempt is made to read from a cursor that has been exhausted + * + * @public + * @category Error + */ +export class MongoCursorExhaustedError extends MongoAPIError { + constructor(message?: string) { + super(message || 'Cursor is exhausted'); + } + + override get name(): string { + return 'MongoCursorExhaustedError'; + } +} + +/** + * An error generated when an attempt is made to operate on a + * dropped, or otherwise unavailable, database. + * + * @public + * @category Error + */ +export class MongoTopologyClosedError extends MongoAPIError { + constructor(message = 'Topology is closed') { + super(message); + } + + override get name(): string { + return 'MongoTopologyClosedError'; + } +} + +/** @internal */ +const kBeforeHandshake = Symbol('beforeHandshake'); +export function isNetworkErrorBeforeHandshake(err: MongoNetworkError): boolean { + return err[kBeforeHandshake] === true; +} + +/** @public */ +export interface MongoNetworkErrorOptions { + /** Indicates the timeout happened before a connection handshake completed */ + beforeHandshake: boolean; +} + +/** + * An error indicating an issue with the network, including TCP errors and timeouts. + * @public + * @category Error + */ +export class MongoNetworkError extends MongoError { + /** @internal */ + [kBeforeHandshake]?: boolean; + + constructor(message: string | Error, options?: MongoNetworkErrorOptions) { + super(message); + + if (options && typeof options.beforeHandshake === 'boolean') { + this[kBeforeHandshake] = options.beforeHandshake; + } + } + + override get name(): string { + return 'MongoNetworkError'; + } +} + +/** + * An error indicating a network timeout occurred + * @public + * @category Error + * + * @privateRemarks + * CSFLE has a dependency on this error with an instanceof check + */ +export class MongoNetworkTimeoutError extends MongoNetworkError { + constructor(message: string, options?: MongoNetworkErrorOptions) { + super(message, options); + } + + override get name(): string { + return 'MongoNetworkTimeoutError'; + } +} + +/** + * An error used when attempting to parse a value (like a connection string) + * @public + * @category Error + */ +export class MongoParseError extends MongoDriverError { + constructor(message: string) { + super(message); + } + + override get name(): string { + return 'MongoParseError'; + } +} + +/** + * An error generated when the user supplies malformed or unexpected arguments + * or when a required argument or field is not provided. + * + * + * @public + * @category Error + */ +export class MongoInvalidArgumentError extends MongoAPIError { + constructor(message: string) { + super(message); + } + + override get name(): string { + return 'MongoInvalidArgumentError'; + } +} + +/** + * An error generated when a feature that is not enabled or allowed for the current server + * configuration is used + * + * + * @public + * @category Error + */ +export class MongoCompatibilityError extends MongoAPIError { + constructor(message: string) { + super(message); + } + + override get name(): string { + return 'MongoCompatibilityError'; + } +} + +/** + * An error generated when the user fails to provide authentication credentials before attempting + * to connect to a mongo server instance. + * + * + * @public + * @category Error + */ +export class MongoMissingCredentialsError extends MongoAPIError { + constructor(message: string) { + super(message); + } + + override get name(): string { + return 'MongoMissingCredentialsError'; + } +} + +/** + * An error generated when a required module or dependency is not present in the local environment + * + * @public + * @category Error + */ +export class MongoMissingDependencyError extends MongoAPIError { + constructor(message: string) { + super(message); + } + + override get name(): string { + return 'MongoMissingDependencyError'; + } +} +/** + * An error signifying a general system issue + * @public + * @category Error + */ +export class MongoSystemError extends MongoError { + /** An optional reason context, such as an error saved during flow of monitoring and selecting servers */ + reason?: TopologyDescription; + + constructor(message: string, reason: TopologyDescription) { + if (reason && reason.error) { + super(reason.error.message || reason.error); + } else { + super(message); + } + + if (reason) { + this.reason = reason; + } + + this.code = reason.error?.code; + } + + override get name(): string { + return 'MongoSystemError'; + } +} + +/** + * An error signifying a client-side server selection error + * @public + * @category Error + */ +export class MongoServerSelectionError extends MongoSystemError { + constructor(message: string, reason: TopologyDescription) { + super(message, reason); + } + + override get name(): string { + return 'MongoServerSelectionError'; + } +} + +function makeWriteConcernResultObject(input: any) { + const output = Object.assign({}, input); + + if (output.ok === 0) { + output.ok = 1; + delete output.errmsg; + delete output.code; + delete output.codeName; + } + + return output; +} + +/** + * An error thrown when the server reports a writeConcernError + * @public + * @category Error + */ +export class MongoWriteConcernError extends MongoServerError { + /** The result document (provided if ok: 1) */ + result?: Document; + + constructor(message: ErrorDescription, result?: Document) { + if (result && Array.isArray(result.errorLabels)) { + message.errorLabels = result.errorLabels; + } + + super(message); + this.errInfo = message.errInfo; + + if (result != null) { + this.result = makeWriteConcernResultObject(result); + } + } + + override get name(): string { + return 'MongoWriteConcernError'; + } +} + +// https://github.com/mongodb/specifications/blob/master/source/retryable-reads/retryable-reads.rst#retryable-error +const RETRYABLE_READ_ERROR_CODES = new Set([ + MONGODB_ERROR_CODES.HostUnreachable, + MONGODB_ERROR_CODES.HostNotFound, + MONGODB_ERROR_CODES.NetworkTimeout, + MONGODB_ERROR_CODES.ShutdownInProgress, + MONGODB_ERROR_CODES.PrimarySteppedDown, + MONGODB_ERROR_CODES.SocketException, + MONGODB_ERROR_CODES.NotWritablePrimary, + MONGODB_ERROR_CODES.InterruptedAtShutdown, + MONGODB_ERROR_CODES.InterruptedDueToReplStateChange, + MONGODB_ERROR_CODES.NotPrimaryNoSecondaryOk, + MONGODB_ERROR_CODES.NotPrimaryOrSecondary +]); + +// see: https://github.com/mongodb/specifications/blob/master/source/retryable-writes/retryable-writes.rst#terms +const RETRYABLE_WRITE_ERROR_CODES = new Set([ + ...RETRYABLE_READ_ERROR_CODES, + MONGODB_ERROR_CODES.ExceededTimeLimit +]); + +export function needsRetryableWriteLabel(error: Error, maxWireVersion: number): boolean { + // pre-4.4 server, then the driver adds an error label for every valid case + // execute operation will only inspect the label, code/message logic is handled here + if (error instanceof MongoNetworkError) { + return true; + } + + if (error instanceof MongoError) { + if ( + (maxWireVersion >= 9 || error.hasErrorLabel(MongoErrorLabel.RetryableWriteError)) && + !error.hasErrorLabel(MongoErrorLabel.HandshakeError) + ) { + // If we already have the error label no need to add it again. 4.4+ servers add the label. + // In the case where we have a handshake error, need to fall down to the logic checking + // the codes. + return false; + } + } + + if (error instanceof MongoWriteConcernError) { + return RETRYABLE_WRITE_ERROR_CODES.has(error.result?.code ?? error.code ?? 0); + } + + if (error instanceof MongoError && typeof error.code === 'number') { + return RETRYABLE_WRITE_ERROR_CODES.has(error.code); + } + + const isNotWritablePrimaryError = LEGACY_NOT_WRITABLE_PRIMARY_ERROR_MESSAGE.test(error.message); + if (isNotWritablePrimaryError) { + return true; + } + + const isNodeIsRecoveringError = NODE_IS_RECOVERING_ERROR_MESSAGE.test(error.message); + if (isNodeIsRecoveringError) { + return true; + } + + return false; +} + +export function isRetryableWriteError(error: MongoError): boolean { + return error.hasErrorLabel(MongoErrorLabel.RetryableWriteError); +} + +/** Determines whether an error is something the driver should attempt to retry */ +export function isRetryableReadError(error: MongoError): boolean { + const hasRetryableErrorCode = + typeof error.code === 'number' ? RETRYABLE_READ_ERROR_CODES.has(error.code) : false; + if (hasRetryableErrorCode) { + return true; + } + + if (error instanceof MongoNetworkError) { + return true; + } + + const isNotWritablePrimaryError = LEGACY_NOT_WRITABLE_PRIMARY_ERROR_MESSAGE.test(error.message); + if (isNotWritablePrimaryError) { + return true; + } + + const isNodeIsRecoveringError = NODE_IS_RECOVERING_ERROR_MESSAGE.test(error.message); + if (isNodeIsRecoveringError) { + return true; + } + + return false; +} + +const SDAM_RECOVERING_CODES = new Set([ + MONGODB_ERROR_CODES.ShutdownInProgress, + MONGODB_ERROR_CODES.PrimarySteppedDown, + MONGODB_ERROR_CODES.InterruptedAtShutdown, + MONGODB_ERROR_CODES.InterruptedDueToReplStateChange, + MONGODB_ERROR_CODES.NotPrimaryOrSecondary +]); + +const SDAM_NOT_PRIMARY_CODES = new Set([ + MONGODB_ERROR_CODES.NotWritablePrimary, + MONGODB_ERROR_CODES.NotPrimaryNoSecondaryOk, + MONGODB_ERROR_CODES.LegacyNotPrimary +]); + +const SDAM_NODE_SHUTTING_DOWN_ERROR_CODES = new Set([ + MONGODB_ERROR_CODES.InterruptedAtShutdown, + MONGODB_ERROR_CODES.ShutdownInProgress +]); + +function isRecoveringError(err: MongoError) { + if (typeof err.code === 'number') { + // If any error code exists, we ignore the error.message + return SDAM_RECOVERING_CODES.has(err.code); + } + + return ( + LEGACY_NOT_PRIMARY_OR_SECONDARY_ERROR_MESSAGE.test(err.message) || + NODE_IS_RECOVERING_ERROR_MESSAGE.test(err.message) + ); +} + +function isNotWritablePrimaryError(err: MongoError) { + if (typeof err.code === 'number') { + // If any error code exists, we ignore the error.message + return SDAM_NOT_PRIMARY_CODES.has(err.code); + } + + if (isRecoveringError(err)) { + return false; + } + + return LEGACY_NOT_WRITABLE_PRIMARY_ERROR_MESSAGE.test(err.message); +} + +export function isNodeShuttingDownError(err: MongoError): boolean { + return !!(typeof err.code === 'number' && SDAM_NODE_SHUTTING_DOWN_ERROR_CODES.has(err.code)); +} + +/** + * Determines whether SDAM can recover from a given error. If it cannot + * then the pool will be cleared, and server state will completely reset + * locally. + * + * @see https://github.com/mongodb/specifications/blob/master/source/server-discovery-and-monitoring/server-discovery-and-monitoring.rst#not-master-and-node-is-recovering + */ +export function isSDAMUnrecoverableError(error: MongoError): boolean { + // NOTE: null check is here for a strictly pre-CMAP world, a timeout or + // close event are considered unrecoverable + if (error instanceof MongoParseError || error == null) { + return true; + } + + return isRecoveringError(error) || isNotWritablePrimaryError(error); +} + +export function isNetworkTimeoutError(err: MongoError): err is MongoNetworkError { + return !!(err instanceof MongoNetworkError && err.message.match(/timed out/)); +} + +export function isResumableError(error?: Error, wireVersion?: number): boolean { + if (error == null || !(error instanceof MongoError)) { + return false; + } + + if (error instanceof MongoNetworkError) { + return true; + } + + if (wireVersion != null && wireVersion >= 9) { + // DRIVERS-1308: For 4.4 drivers running against 4.4 servers, drivers will add a special case to treat the CursorNotFound error code as resumable + if (error.code === MONGODB_ERROR_CODES.CursorNotFound) { + return true; + } + return error.hasErrorLabel(MongoErrorLabel.ResumableChangeStreamError); + } + + if (typeof error.code === 'number') { + return GET_MORE_RESUMABLE_CODES.has(error.code); + } + + return false; +} diff --git a/ts-ticket-office-service/node_modules/mongodb/src/explain.ts b/ts-ticket-office-service/node_modules/mongodb/src/explain.ts new file mode 100644 index 000000000..0d08e694a --- /dev/null +++ b/ts-ticket-office-service/node_modules/mongodb/src/explain.ts @@ -0,0 +1,52 @@ +import { MongoInvalidArgumentError } from './error'; + +/** @public */ +export const ExplainVerbosity = Object.freeze({ + queryPlanner: 'queryPlanner', + queryPlannerExtended: 'queryPlannerExtended', + executionStats: 'executionStats', + allPlansExecution: 'allPlansExecution' +} as const); + +/** @public */ +export type ExplainVerbosity = string; + +/** + * For backwards compatibility, true is interpreted as "allPlansExecution" + * and false as "queryPlanner". Prior to server version 3.6, aggregate() + * ignores the verbosity parameter and executes in "queryPlanner". + * @public + */ +export type ExplainVerbosityLike = ExplainVerbosity | boolean; + +/** @public */ +export interface ExplainOptions { + /** Specifies the verbosity mode for the explain output. */ + explain?: ExplainVerbosityLike; +} + +/** @internal */ +export class Explain { + verbosity: ExplainVerbosity; + + constructor(verbosity: ExplainVerbosityLike) { + if (typeof verbosity === 'boolean') { + this.verbosity = verbosity + ? ExplainVerbosity.allPlansExecution + : ExplainVerbosity.queryPlanner; + } else { + this.verbosity = verbosity; + } + } + + static fromOptions(options?: ExplainOptions): Explain | undefined { + if (options?.explain == null) return; + + const explain = options.explain; + if (typeof explain === 'boolean' || typeof explain === 'string') { + return new Explain(explain); + } + + throw new MongoInvalidArgumentError('Field "explain" must be a string or a boolean'); + } +} diff --git a/ts-ticket-office-service/node_modules/mongodb/src/gridfs/download.ts b/ts-ticket-office-service/node_modules/mongodb/src/gridfs/download.ts new file mode 100644 index 000000000..a13cdac39 --- /dev/null +++ b/ts-ticket-office-service/node_modules/mongodb/src/gridfs/download.ts @@ -0,0 +1,458 @@ +import { Readable } from 'stream'; + +import type { Document, ObjectId } from '../bson'; +import type { Collection } from '../collection'; +import type { FindCursor } from '../cursor/find_cursor'; +import { + MongoGridFSChunkError, + MongoGridFSStreamError, + MongoInvalidArgumentError, + MongoRuntimeError +} from '../error'; +import type { FindOptions } from '../operations/find'; +import type { ReadPreference } from '../read_preference'; +import type { Sort } from '../sort'; +import type { Callback } from '../utils'; +import type { GridFSChunk } from './upload'; + +/** @public */ +export interface GridFSBucketReadStreamOptions { + sort?: Sort; + skip?: number; + /** 0-based offset in bytes to start streaming from */ + start?: number; + /** 0-based offset in bytes to stop streaming before */ + end?: number; +} + +/** @public */ +export interface GridFSBucketReadStreamOptionsWithRevision extends GridFSBucketReadStreamOptions { + /** The revision number relative to the oldest file with the given filename. 0 + * gets you the oldest file, 1 gets you the 2nd oldest, -1 gets you the + * newest. */ + revision?: number; +} + +/** @public */ +export interface GridFSFile { + _id: ObjectId; + length: number; + chunkSize: number; + filename: string; + contentType?: string; + aliases?: string[]; + metadata?: Document; + uploadDate: Date; +} + +/** @internal */ +export interface GridFSBucketReadStreamPrivate { + bytesRead: number; + bytesToTrim: number; + bytesToSkip: number; + chunks: Collection; + cursor?: FindCursor; + expected: number; + files: Collection; + filter: Document; + init: boolean; + expectedEnd: number; + file?: GridFSFile; + options: { + sort?: Sort; + skip?: number; + start: number; + end: number; + }; + readPreference?: ReadPreference; +} + +/** + * A readable stream that enables you to read buffers from GridFS. + * + * Do not instantiate this class directly. Use `openDownloadStream()` instead. + * @public + */ +export class GridFSBucketReadStream extends Readable implements NodeJS.ReadableStream { + /** @internal */ + s: GridFSBucketReadStreamPrivate; + + /** + * An error occurred + * @event + */ + static readonly ERROR = 'error' as const; + /** + * Fires when the stream loaded the file document corresponding to the provided id. + * @event + */ + static readonly FILE = 'file' as const; + /** + * Emitted when a chunk of data is available to be consumed. + * @event + */ + static readonly DATA = 'data' as const; + /** + * Fired when the stream is exhausted (no more data events). + * @event + */ + static readonly END = 'end' as const; + /** + * Fired when the stream is exhausted and the underlying cursor is killed + * @event + */ + static readonly CLOSE = 'close' as const; + + /** @internal + * @param chunks - Handle for chunks collection + * @param files - Handle for files collection + * @param readPreference - The read preference to use + * @param filter - The filter to use to find the file document + */ + constructor( + chunks: Collection, + files: Collection, + readPreference: ReadPreference | undefined, + filter: Document, + options?: GridFSBucketReadStreamOptions + ) { + super(); + this.s = { + bytesToTrim: 0, + bytesToSkip: 0, + bytesRead: 0, + chunks, + expected: 0, + files, + filter, + init: false, + expectedEnd: 0, + options: { + start: 0, + end: 0, + ...options + }, + readPreference + }; + } + + /** + * Reads from the cursor and pushes to the stream. + * Private Impl, do not call directly + * @internal + */ + override _read(): void { + if (this.destroyed) return; + waitForFile(this, () => doRead(this)); + } + + /** + * Sets the 0-based offset in bytes to start streaming from. Throws + * an error if this stream has entered flowing mode + * (e.g. if you've already called `on('data')`) + * + * @param start - 0-based offset in bytes to start streaming from + */ + start(start = 0): this { + throwIfInitialized(this); + this.s.options.start = start; + return this; + } + + /** + * Sets the 0-based offset in bytes to start streaming from. Throws + * an error if this stream has entered flowing mode + * (e.g. if you've already called `on('data')`) + * + * @param end - Offset in bytes to stop reading at + */ + end(end = 0): this { + throwIfInitialized(this); + this.s.options.end = end; + return this; + } + + /** + * Marks this stream as aborted (will never push another `data` event) + * and kills the underlying cursor. Will emit the 'end' event, and then + * the 'close' event once the cursor is successfully killed. + * + * @param callback - called when the cursor is successfully closed or an error occurred. + */ + abort(callback?: Callback): void { + this.push(null); + this.destroyed = true; + if (this.s.cursor) { + this.s.cursor.close(error => { + this.emit(GridFSBucketReadStream.CLOSE); + callback && callback(error); + }); + } else { + if (!this.s.init) { + // If not initialized, fire close event because we will never + // get a cursor + this.emit(GridFSBucketReadStream.CLOSE); + } + callback && callback(); + } + } +} + +function throwIfInitialized(stream: GridFSBucketReadStream): void { + if (stream.s.init) { + throw new MongoGridFSStreamError('Options cannot be changed after the stream is initialized'); + } +} + +function doRead(stream: GridFSBucketReadStream): void { + if (stream.destroyed) return; + if (!stream.s.cursor) return; + if (!stream.s.file) return; + + stream.s.cursor.next((error, doc) => { + if (stream.destroyed) { + return; + } + if (error) { + stream.emit(GridFSBucketReadStream.ERROR, error); + return; + } + if (!doc) { + stream.push(null); + + process.nextTick(() => { + if (!stream.s.cursor) return; + stream.s.cursor.close(error => { + if (error) { + stream.emit(GridFSBucketReadStream.ERROR, error); + return; + } + + stream.emit(GridFSBucketReadStream.CLOSE); + }); + }); + + return; + } + + if (!stream.s.file) return; + + const bytesRemaining = stream.s.file.length - stream.s.bytesRead; + const expectedN = stream.s.expected++; + const expectedLength = Math.min(stream.s.file.chunkSize, bytesRemaining); + if (doc.n > expectedN) { + return stream.emit( + GridFSBucketReadStream.ERROR, + new MongoGridFSChunkError( + `ChunkIsMissing: Got unexpected n: ${doc.n}, expected: ${expectedN}` + ) + ); + } + + if (doc.n < expectedN) { + return stream.emit( + GridFSBucketReadStream.ERROR, + new MongoGridFSChunkError(`ExtraChunk: Got unexpected n: ${doc.n}, expected: ${expectedN}`) + ); + } + + let buf = Buffer.isBuffer(doc.data) ? doc.data : doc.data.buffer; + + if (buf.byteLength !== expectedLength) { + if (bytesRemaining <= 0) { + return stream.emit( + GridFSBucketReadStream.ERROR, + new MongoGridFSChunkError( + `ExtraChunk: Got unexpected n: ${doc.n}, expected file length ${stream.s.file.length} bytes but already read ${stream.s.bytesRead} bytes` + ) + ); + } + + return stream.emit( + GridFSBucketReadStream.ERROR, + new MongoGridFSChunkError( + `ChunkIsWrongSize: Got unexpected length: ${buf.byteLength}, expected: ${expectedLength}` + ) + ); + } + + stream.s.bytesRead += buf.byteLength; + + if (buf.byteLength === 0) { + return stream.push(null); + } + + let sliceStart = null; + let sliceEnd = null; + + if (stream.s.bytesToSkip != null) { + sliceStart = stream.s.bytesToSkip; + stream.s.bytesToSkip = 0; + } + + const atEndOfStream = expectedN === stream.s.expectedEnd - 1; + const bytesLeftToRead = stream.s.options.end - stream.s.bytesToSkip; + if (atEndOfStream && stream.s.bytesToTrim != null) { + sliceEnd = stream.s.file.chunkSize - stream.s.bytesToTrim; + } else if (stream.s.options.end && bytesLeftToRead < doc.data.byteLength) { + sliceEnd = bytesLeftToRead; + } + + if (sliceStart != null || sliceEnd != null) { + buf = buf.slice(sliceStart || 0, sliceEnd || buf.byteLength); + } + + stream.push(buf); + return; + }); +} + +function init(stream: GridFSBucketReadStream): void { + const findOneOptions: FindOptions = {}; + if (stream.s.readPreference) { + findOneOptions.readPreference = stream.s.readPreference; + } + if (stream.s.options && stream.s.options.sort) { + findOneOptions.sort = stream.s.options.sort; + } + if (stream.s.options && stream.s.options.skip) { + findOneOptions.skip = stream.s.options.skip; + } + + stream.s.files.findOne(stream.s.filter, findOneOptions, (error, doc) => { + if (error) { + return stream.emit(GridFSBucketReadStream.ERROR, error); + } + + if (!doc) { + const identifier = stream.s.filter._id + ? stream.s.filter._id.toString() + : stream.s.filter.filename; + const errmsg = `FileNotFound: file ${identifier} was not found`; + // TODO(NODE-3483) + const err = new MongoRuntimeError(errmsg); + err.code = 'ENOENT'; // TODO: NODE-3338 set property as part of constructor + return stream.emit(GridFSBucketReadStream.ERROR, err); + } + + // If document is empty, kill the stream immediately and don't + // execute any reads + if (doc.length <= 0) { + stream.push(null); + return; + } + + if (stream.destroyed) { + // If user destroys the stream before we have a cursor, wait + // until the query is done to say we're 'closed' because we can't + // cancel a query. + stream.emit(GridFSBucketReadStream.CLOSE); + return; + } + + try { + stream.s.bytesToSkip = handleStartOption(stream, doc, stream.s.options); + } catch (error) { + return stream.emit(GridFSBucketReadStream.ERROR, error); + } + + const filter: Document = { files_id: doc._id }; + + // Currently (MongoDB 3.4.4) skip function does not support the index, + // it needs to retrieve all the documents first and then skip them. (CS-25811) + // As work around we use $gte on the "n" field. + if (stream.s.options && stream.s.options.start != null) { + const skip = Math.floor(stream.s.options.start / doc.chunkSize); + if (skip > 0) { + filter['n'] = { $gte: skip }; + } + } + stream.s.cursor = stream.s.chunks.find(filter).sort({ n: 1 }); + + if (stream.s.readPreference) { + stream.s.cursor.withReadPreference(stream.s.readPreference); + } + + stream.s.expectedEnd = Math.ceil(doc.length / doc.chunkSize); + stream.s.file = doc as GridFSFile; + + try { + stream.s.bytesToTrim = handleEndOption(stream, doc, stream.s.cursor, stream.s.options); + } catch (error) { + return stream.emit(GridFSBucketReadStream.ERROR, error); + } + + stream.emit(GridFSBucketReadStream.FILE, doc); + return; + }); +} + +function waitForFile(stream: GridFSBucketReadStream, callback: Callback): void { + if (stream.s.file) { + return callback(); + } + + if (!stream.s.init) { + init(stream); + stream.s.init = true; + } + + stream.once('file', () => { + callback(); + }); +} + +function handleStartOption( + stream: GridFSBucketReadStream, + doc: Document, + options: GridFSBucketReadStreamOptions +): number { + if (options && options.start != null) { + if (options.start > doc.length) { + throw new MongoInvalidArgumentError( + `Stream start (${options.start}) must not be more than the length of the file (${doc.length})` + ); + } + if (options.start < 0) { + throw new MongoInvalidArgumentError(`Stream start (${options.start}) must not be negative`); + } + if (options.end != null && options.end < options.start) { + throw new MongoInvalidArgumentError( + `Stream start (${options.start}) must not be greater than stream end (${options.end})` + ); + } + + stream.s.bytesRead = Math.floor(options.start / doc.chunkSize) * doc.chunkSize; + stream.s.expected = Math.floor(options.start / doc.chunkSize); + + return options.start - stream.s.bytesRead; + } + throw new MongoInvalidArgumentError('Start option must be defined'); +} + +function handleEndOption( + stream: GridFSBucketReadStream, + doc: Document, + cursor: FindCursor, + options: GridFSBucketReadStreamOptions +) { + if (options && options.end != null) { + if (options.end > doc.length) { + throw new MongoInvalidArgumentError( + `Stream end (${options.end}) must not be more than the length of the file (${doc.length})` + ); + } + if (options.start == null || options.start < 0) { + throw new MongoInvalidArgumentError(`Stream end (${options.end}) must not be negative`); + } + + const start = options.start != null ? Math.floor(options.start / doc.chunkSize) : 0; + + cursor.limit(Math.ceil(options.end / doc.chunkSize) - start); + + stream.s.expectedEnd = Math.ceil(options.end / doc.chunkSize); + + return Math.ceil(options.end / doc.chunkSize) * doc.chunkSize - options.end; + } + throw new MongoInvalidArgumentError('End option must be defined'); +} diff --git a/ts-ticket-office-service/node_modules/mongodb/src/gridfs/index.ts b/ts-ticket-office-service/node_modules/mongodb/src/gridfs/index.ts new file mode 100644 index 000000000..a2a1c3dcc --- /dev/null +++ b/ts-ticket-office-service/node_modules/mongodb/src/gridfs/index.ts @@ -0,0 +1,257 @@ +import type { ObjectId } from '../bson'; +import type { Collection } from '../collection'; +import type { FindCursor } from '../cursor/find_cursor'; +import type { Db } from '../db'; +import { MongoRuntimeError } from '../error'; +import type { Logger } from '../logger'; +import { Filter, TypedEventEmitter } from '../mongo_types'; +import type { ReadPreference } from '../read_preference'; +import type { Sort } from '../sort'; +import { Callback, maybePromise } from '../utils'; +import { WriteConcern, WriteConcernOptions } from '../write_concern'; +import type { FindOptions } from './../operations/find'; +import { + GridFSBucketReadStream, + GridFSBucketReadStreamOptions, + GridFSBucketReadStreamOptionsWithRevision, + GridFSFile +} from './download'; +import { GridFSBucketWriteStream, GridFSBucketWriteStreamOptions, GridFSChunk } from './upload'; + +const DEFAULT_GRIDFS_BUCKET_OPTIONS: { + bucketName: string; + chunkSizeBytes: number; +} = { + bucketName: 'fs', + chunkSizeBytes: 255 * 1024 +}; + +/** @public */ +export interface GridFSBucketOptions extends WriteConcernOptions { + /** The 'files' and 'chunks' collections will be prefixed with the bucket name followed by a dot. */ + bucketName?: string; + /** Number of bytes stored in each chunk. Defaults to 255KB */ + chunkSizeBytes?: number; + /** Read preference to be passed to read operations */ + readPreference?: ReadPreference; +} + +/** @internal */ +export interface GridFSBucketPrivate { + db: Db; + options: { + bucketName: string; + chunkSizeBytes: number; + readPreference?: ReadPreference; + writeConcern: WriteConcern | undefined; + }; + _chunksCollection: Collection; + _filesCollection: Collection; + checkedIndexes: boolean; + calledOpenUploadStream: boolean; +} + +/** @public */ +export type GridFSBucketEvents = { + index(): void; +}; + +/** + * Constructor for a streaming GridFS interface + * @public + */ +export class GridFSBucket extends TypedEventEmitter { + /** @internal */ + s: GridFSBucketPrivate; + + /** + * When the first call to openUploadStream is made, the upload stream will + * check to see if it needs to create the proper indexes on the chunks and + * files collections. This event is fired either when 1) it determines that + * no index creation is necessary, 2) when it successfully creates the + * necessary indexes. + * @event + */ + static readonly INDEX = 'index' as const; + + constructor(db: Db, options?: GridFSBucketOptions) { + super(); + this.setMaxListeners(0); + const privateOptions = { + ...DEFAULT_GRIDFS_BUCKET_OPTIONS, + ...options, + writeConcern: WriteConcern.fromOptions(options) + }; + this.s = { + db, + options: privateOptions, + _chunksCollection: db.collection(privateOptions.bucketName + '.chunks'), + _filesCollection: db.collection(privateOptions.bucketName + '.files'), + checkedIndexes: false, + calledOpenUploadStream: false + }; + } + + /** + * Returns a writable stream (GridFSBucketWriteStream) for writing + * buffers to GridFS. The stream's 'id' property contains the resulting + * file's id. + * + * @param filename - The value of the 'filename' key in the files doc + * @param options - Optional settings. + */ + + openUploadStream( + filename: string, + options?: GridFSBucketWriteStreamOptions + ): GridFSBucketWriteStream { + return new GridFSBucketWriteStream(this, filename, options); + } + + /** + * Returns a writable stream (GridFSBucketWriteStream) for writing + * buffers to GridFS for a custom file id. The stream's 'id' property contains the resulting + * file's id. + */ + openUploadStreamWithId( + id: ObjectId, + filename: string, + options?: GridFSBucketWriteStreamOptions + ): GridFSBucketWriteStream { + return new GridFSBucketWriteStream(this, filename, { ...options, id }); + } + + /** Returns a readable stream (GridFSBucketReadStream) for streaming file data from GridFS. */ + openDownloadStream( + id: ObjectId, + options?: GridFSBucketReadStreamOptions + ): GridFSBucketReadStream { + return new GridFSBucketReadStream( + this.s._chunksCollection, + this.s._filesCollection, + this.s.options.readPreference, + { _id: id }, + options + ); + } + + /** + * Deletes a file with the given id + * + * @param id - The id of the file doc + */ + delete(id: ObjectId): Promise; + delete(id: ObjectId, callback: Callback): void; + delete(id: ObjectId, callback?: Callback): Promise | void { + return maybePromise(callback, callback => { + return this.s._filesCollection.deleteOne({ _id: id }, (error, res) => { + if (error) { + return callback(error); + } + + return this.s._chunksCollection.deleteMany({ files_id: id }, error => { + if (error) { + return callback(error); + } + + // Delete orphaned chunks before returning FileNotFound + if (!res?.deletedCount) { + // TODO(NODE-3483): Replace with more appropriate error + // Consider creating new error MongoGridFSFileNotFoundError + return callback(new MongoRuntimeError(`File not found for id ${id}`)); + } + + return callback(); + }); + }); + }); + } + + /** Convenience wrapper around find on the files collection */ + find(filter?: Filter, options?: FindOptions): FindCursor { + filter ??= {}; + options = options ?? {}; + return this.s._filesCollection.find(filter, options); + } + + /** + * Returns a readable stream (GridFSBucketReadStream) for streaming the + * file with the given name from GridFS. If there are multiple files with + * the same name, this will stream the most recent file with the given name + * (as determined by the `uploadDate` field). You can set the `revision` + * option to change this behavior. + */ + openDownloadStreamByName( + filename: string, + options?: GridFSBucketReadStreamOptionsWithRevision + ): GridFSBucketReadStream { + let sort: Sort = { uploadDate: -1 }; + let skip = undefined; + if (options && options.revision != null) { + if (options.revision >= 0) { + sort = { uploadDate: 1 }; + skip = options.revision; + } else { + skip = -options.revision - 1; + } + } + return new GridFSBucketReadStream( + this.s._chunksCollection, + this.s._filesCollection, + this.s.options.readPreference, + { filename }, + { ...options, sort, skip } + ); + } + + /** + * Renames the file with the given _id to the given string + * + * @param id - the id of the file to rename + * @param filename - new name for the file + */ + rename(id: ObjectId, filename: string): Promise; + rename(id: ObjectId, filename: string, callback: Callback): void; + rename(id: ObjectId, filename: string, callback?: Callback): Promise | void { + return maybePromise(callback, callback => { + const filter = { _id: id }; + const update = { $set: { filename } }; + return this.s._filesCollection.updateOne(filter, update, (error?, res?) => { + if (error) { + return callback(error); + } + + if (!res?.matchedCount) { + return callback(new MongoRuntimeError(`File with id ${id} not found`)); + } + + return callback(); + }); + }); + } + + /** Removes this bucket's files collection, followed by its chunks collection. */ + drop(): Promise; + drop(callback: Callback): void; + drop(callback?: Callback): Promise | void { + return maybePromise(callback, callback => { + return this.s._filesCollection.drop(error => { + if (error) { + return callback(error); + } + return this.s._chunksCollection.drop(error => { + if (error) { + return callback(error); + } + + return callback(); + }); + }); + }); + } + + /** Get the Db scoped logger. */ + getLogger(): Logger { + return this.s.db.s.logger; + } +} diff --git a/ts-ticket-office-service/node_modules/mongodb/src/gridfs/upload.ts b/ts-ticket-office-service/node_modules/mongodb/src/gridfs/upload.ts new file mode 100644 index 000000000..ae0d67899 --- /dev/null +++ b/ts-ticket-office-service/node_modules/mongodb/src/gridfs/upload.ts @@ -0,0 +1,566 @@ +import { Writable } from 'stream'; + +import type { Document } from '../bson'; +import { ObjectId } from '../bson'; +import type { Collection } from '../collection'; +import { AnyError, MongoAPIError, MONGODB_ERROR_CODES, MongoError } from '../error'; +import { Callback, maybePromise } from '../utils'; +import type { WriteConcernOptions } from '../write_concern'; +import { WriteConcern } from './../write_concern'; +import type { GridFSFile } from './download'; +import type { GridFSBucket } from './index'; + +/** @public */ +export interface GridFSChunk { + _id: ObjectId; + files_id: ObjectId; + n: number; + data: Buffer | Uint8Array; +} + +/** @public */ +export interface GridFSBucketWriteStreamOptions extends WriteConcernOptions { + /** Overwrite this bucket's chunkSizeBytes for this file */ + chunkSizeBytes?: number; + /** Custom file id for the GridFS file. */ + id?: ObjectId; + /** Object to store in the file document's `metadata` field */ + metadata?: Document; + /** String to store in the file document's `contentType` field */ + contentType?: string; + /** Array of strings to store in the file document's `aliases` field */ + aliases?: string[]; +} + +/** + * A writable stream that enables you to write buffers to GridFS. + * + * Do not instantiate this class directly. Use `openUploadStream()` instead. + * @public + */ +export class GridFSBucketWriteStream extends Writable implements NodeJS.WritableStream { + bucket: GridFSBucket; + chunks: Collection; + filename: string; + files: Collection; + options: GridFSBucketWriteStreamOptions; + done: boolean; + id: ObjectId; + chunkSizeBytes: number; + bufToStore: Buffer; + length: number; + n: number; + pos: number; + state: { + streamEnd: boolean; + outstandingRequests: number; + errored: boolean; + aborted: boolean; + }; + writeConcern?: WriteConcern; + + /** @event */ + static readonly CLOSE = 'close'; + /** @event */ + static readonly ERROR = 'error'; + /** + * `end()` was called and the write stream successfully wrote the file metadata and all the chunks to MongoDB. + * @event + */ + static readonly FINISH = 'finish'; + + /** @internal + * @param bucket - Handle for this stream's corresponding bucket + * @param filename - The value of the 'filename' key in the files doc + * @param options - Optional settings. + */ + constructor(bucket: GridFSBucket, filename: string, options?: GridFSBucketWriteStreamOptions) { + super(); + + options = options ?? {}; + this.bucket = bucket; + this.chunks = bucket.s._chunksCollection; + this.filename = filename; + this.files = bucket.s._filesCollection; + this.options = options; + this.writeConcern = WriteConcern.fromOptions(options) || bucket.s.options.writeConcern; + // Signals the write is all done + this.done = false; + + this.id = options.id ? options.id : new ObjectId(); + // properly inherit the default chunksize from parent + this.chunkSizeBytes = options.chunkSizeBytes || this.bucket.s.options.chunkSizeBytes; + this.bufToStore = Buffer.alloc(this.chunkSizeBytes); + this.length = 0; + this.n = 0; + this.pos = 0; + this.state = { + streamEnd: false, + outstandingRequests: 0, + errored: false, + aborted: false + }; + + if (!this.bucket.s.calledOpenUploadStream) { + this.bucket.s.calledOpenUploadStream = true; + + checkIndexes(this, () => { + this.bucket.s.checkedIndexes = true; + this.bucket.emit('index'); + }); + } + } + + /** + * Write a buffer to the stream. + * + * @param chunk - Buffer to write + * @param encodingOrCallback - Optional encoding for the buffer + * @param callback - Function to call when the chunk was added to the buffer, or if the entire chunk was persisted to MongoDB if this chunk caused a flush. + * @returns False if this write required flushing a chunk to MongoDB. True otherwise. + */ + override write(chunk: Buffer | string): boolean; + override write(chunk: Buffer | string, callback: Callback): boolean; + override write(chunk: Buffer | string, encoding: BufferEncoding | undefined): boolean; + override write( + chunk: Buffer | string, + encoding: BufferEncoding | undefined, + callback: Callback + ): boolean; + override write( + chunk: Buffer | string, + encodingOrCallback?: Callback | BufferEncoding, + callback?: Callback + ): boolean { + const encoding = typeof encodingOrCallback === 'function' ? undefined : encodingOrCallback; + callback = typeof encodingOrCallback === 'function' ? encodingOrCallback : callback; + return waitForIndexes(this, () => doWrite(this, chunk, encoding, callback)); + } + + // TODO(NODE-3405): Refactor this with maybePromise and MongoStreamClosedError + /** + * Places this write stream into an aborted state (all future writes fail) + * and deletes all chunks that have already been written. + * + * @param callback - called when chunks are successfully removed or error occurred + */ + abort(): Promise; + abort(callback: Callback): void; + abort(callback?: Callback): Promise | void { + return maybePromise(callback, callback => { + if (this.state.streamEnd) { + // TODO(NODE-3485): Replace with MongoGridFSStreamClosed + return callback(new MongoAPIError('Cannot abort a stream that has already completed')); + } + + if (this.state.aborted) { + // TODO(NODE-3485): Replace with MongoGridFSStreamClosed + return callback(new MongoAPIError('Cannot call abort() on a stream twice')); + } + + this.state.aborted = true; + this.chunks.deleteMany({ files_id: this.id }, error => callback(error)); + }); + } + + /** + * Tells the stream that no more data will be coming in. The stream will + * persist the remaining data to MongoDB, write the files document, and + * then emit a 'finish' event. + * + * @param chunk - Buffer to write + * @param encoding - Optional encoding for the buffer + * @param callback - Function to call when all files and chunks have been persisted to MongoDB + */ + override end(): this; + override end(chunk: Buffer): this; + override end(callback: Callback): this; + override end(chunk: Buffer, callback: Callback): this; + override end(chunk: Buffer, encoding: BufferEncoding): this; + override end( + chunk: Buffer, + encoding: BufferEncoding | undefined, + callback: Callback + ): this; + override end( + chunkOrCallback?: Buffer | Callback, + encodingOrCallback?: BufferEncoding | Callback, + callback?: Callback + ): this { + const chunk = typeof chunkOrCallback === 'function' ? undefined : chunkOrCallback; + const encoding = typeof encodingOrCallback === 'function' ? undefined : encodingOrCallback; + callback = + typeof chunkOrCallback === 'function' + ? chunkOrCallback + : typeof encodingOrCallback === 'function' + ? encodingOrCallback + : callback; + + if (this.state.streamEnd || checkAborted(this, callback)) return this; + + this.state.streamEnd = true; + + if (callback) { + this.once(GridFSBucketWriteStream.FINISH, (result: GridFSFile) => { + if (callback) callback(undefined, result); + }); + } + + if (!chunk) { + waitForIndexes(this, () => !!writeRemnant(this)); + return this; + } + + this.write(chunk, encoding, () => { + writeRemnant(this); + }); + + return this; + } +} + +function __handleError( + stream: GridFSBucketWriteStream, + error: AnyError, + callback?: Callback +): void { + if (stream.state.errored) { + return; + } + stream.state.errored = true; + if (callback) { + return callback(error); + } + stream.emit(GridFSBucketWriteStream.ERROR, error); +} + +function createChunkDoc(filesId: ObjectId, n: number, data: Buffer): GridFSChunk { + return { + _id: new ObjectId(), + files_id: filesId, + n, + data + }; +} + +function checkChunksIndex(stream: GridFSBucketWriteStream, callback: Callback): void { + stream.chunks.listIndexes().toArray((error?: AnyError, indexes?: Document[]) => { + let index: { files_id: number; n: number }; + if (error) { + // Collection doesn't exist so create index + if (error instanceof MongoError && error.code === MONGODB_ERROR_CODES.NamespaceNotFound) { + index = { files_id: 1, n: 1 }; + stream.chunks.createIndex(index, { background: false, unique: true }, error => { + if (error) { + return callback(error); + } + + callback(); + }); + return; + } + return callback(error); + } + + let hasChunksIndex = false; + if (indexes) { + indexes.forEach((index: Document) => { + if (index.key) { + const keys = Object.keys(index.key); + if (keys.length === 2 && index.key.files_id === 1 && index.key.n === 1) { + hasChunksIndex = true; + } + } + }); + } + + if (hasChunksIndex) { + callback(); + } else { + index = { files_id: 1, n: 1 }; + const writeConcernOptions = getWriteOptions(stream); + + stream.chunks.createIndex( + index, + { + ...writeConcernOptions, + background: true, + unique: true + }, + callback + ); + } + }); +} + +function checkDone(stream: GridFSBucketWriteStream, callback?: Callback): boolean { + if (stream.done) return true; + if (stream.state.streamEnd && stream.state.outstandingRequests === 0 && !stream.state.errored) { + // Set done so we do not trigger duplicate createFilesDoc + stream.done = true; + // Create a new files doc + const filesDoc = createFilesDoc( + stream.id, + stream.length, + stream.chunkSizeBytes, + stream.filename, + stream.options.contentType, + stream.options.aliases, + stream.options.metadata + ); + + if (checkAborted(stream, callback)) { + return false; + } + + stream.files.insertOne(filesDoc, getWriteOptions(stream), (error?: AnyError) => { + if (error) { + return __handleError(stream, error, callback); + } + stream.emit(GridFSBucketWriteStream.FINISH, filesDoc); + stream.emit(GridFSBucketWriteStream.CLOSE); + }); + + return true; + } + + return false; +} + +function checkIndexes(stream: GridFSBucketWriteStream, callback: Callback): void { + stream.files.findOne({}, { projection: { _id: 1 } }, (error, doc) => { + if (error) { + return callback(error); + } + if (doc) { + return callback(); + } + + stream.files.listIndexes().toArray((error?: AnyError, indexes?: Document) => { + let index: { filename: number; uploadDate: number }; + if (error) { + // Collection doesn't exist so create index + if (error instanceof MongoError && error.code === MONGODB_ERROR_CODES.NamespaceNotFound) { + index = { filename: 1, uploadDate: 1 }; + stream.files.createIndex(index, { background: false }, (error?: AnyError) => { + if (error) { + return callback(error); + } + + checkChunksIndex(stream, callback); + }); + return; + } + return callback(error); + } + + let hasFileIndex = false; + if (indexes) { + indexes.forEach((index: Document) => { + const keys = Object.keys(index.key); + if (keys.length === 2 && index.key.filename === 1 && index.key.uploadDate === 1) { + hasFileIndex = true; + } + }); + } + + if (hasFileIndex) { + checkChunksIndex(stream, callback); + } else { + index = { filename: 1, uploadDate: 1 }; + + const writeConcernOptions = getWriteOptions(stream); + + stream.files.createIndex( + index, + { + ...writeConcernOptions, + background: false + }, + (error?: AnyError) => { + if (error) { + return callback(error); + } + + checkChunksIndex(stream, callback); + } + ); + } + }); + }); +} + +function createFilesDoc( + _id: ObjectId, + length: number, + chunkSize: number, + filename: string, + contentType?: string, + aliases?: string[], + metadata?: Document +): GridFSFile { + const ret: GridFSFile = { + _id, + length, + chunkSize, + uploadDate: new Date(), + filename + }; + + if (contentType) { + ret.contentType = contentType; + } + + if (aliases) { + ret.aliases = aliases; + } + + if (metadata) { + ret.metadata = metadata; + } + + return ret; +} + +function doWrite( + stream: GridFSBucketWriteStream, + chunk: Buffer | string, + encoding?: BufferEncoding, + callback?: Callback +): boolean { + if (checkAborted(stream, callback)) { + return false; + } + + const inputBuf = Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk, encoding); + + stream.length += inputBuf.length; + + // Input is small enough to fit in our buffer + if (stream.pos + inputBuf.length < stream.chunkSizeBytes) { + inputBuf.copy(stream.bufToStore, stream.pos); + stream.pos += inputBuf.length; + + callback && callback(); + + // Note that we reverse the typical semantics of write's return value + // to be compatible with node's `.pipe()` function. + // True means client can keep writing. + return true; + } + + // Otherwise, buffer is too big for current chunk, so we need to flush + // to MongoDB. + let inputBufRemaining = inputBuf.length; + let spaceRemaining: number = stream.chunkSizeBytes - stream.pos; + let numToCopy = Math.min(spaceRemaining, inputBuf.length); + let outstandingRequests = 0; + while (inputBufRemaining > 0) { + const inputBufPos = inputBuf.length - inputBufRemaining; + inputBuf.copy(stream.bufToStore, stream.pos, inputBufPos, inputBufPos + numToCopy); + stream.pos += numToCopy; + spaceRemaining -= numToCopy; + let doc: GridFSChunk; + if (spaceRemaining === 0) { + doc = createChunkDoc(stream.id, stream.n, Buffer.from(stream.bufToStore)); + ++stream.state.outstandingRequests; + ++outstandingRequests; + + if (checkAborted(stream, callback)) { + return false; + } + + stream.chunks.insertOne(doc, getWriteOptions(stream), (error?: AnyError) => { + if (error) { + return __handleError(stream, error); + } + --stream.state.outstandingRequests; + --outstandingRequests; + + if (!outstandingRequests) { + stream.emit('drain', doc); + callback && callback(); + checkDone(stream); + } + }); + + spaceRemaining = stream.chunkSizeBytes; + stream.pos = 0; + ++stream.n; + } + inputBufRemaining -= numToCopy; + numToCopy = Math.min(spaceRemaining, inputBufRemaining); + } + + // Note that we reverse the typical semantics of write's return value + // to be compatible with node's `.pipe()` function. + // False means the client should wait for the 'drain' event. + return false; +} + +function getWriteOptions(stream: GridFSBucketWriteStream): WriteConcernOptions { + const obj: WriteConcernOptions = {}; + if (stream.writeConcern) { + obj.writeConcern = { + w: stream.writeConcern.w, + wtimeout: stream.writeConcern.wtimeout, + j: stream.writeConcern.j + }; + } + return obj; +} + +function waitForIndexes( + stream: GridFSBucketWriteStream, + callback: (res: boolean) => boolean +): boolean { + if (stream.bucket.s.checkedIndexes) { + return callback(false); + } + + stream.bucket.once('index', () => { + callback(true); + }); + + return true; +} + +function writeRemnant(stream: GridFSBucketWriteStream, callback?: Callback): boolean { + // Buffer is empty, so don't bother to insert + if (stream.pos === 0) { + return checkDone(stream, callback); + } + + ++stream.state.outstandingRequests; + + // Create a new buffer to make sure the buffer isn't bigger than it needs + // to be. + const remnant = Buffer.alloc(stream.pos); + stream.bufToStore.copy(remnant, 0, 0, stream.pos); + const doc = createChunkDoc(stream.id, stream.n, remnant); + + // If the stream was aborted, do not write remnant + if (checkAborted(stream, callback)) { + return false; + } + + stream.chunks.insertOne(doc, getWriteOptions(stream), (error?: AnyError) => { + if (error) { + return __handleError(stream, error); + } + --stream.state.outstandingRequests; + checkDone(stream); + }); + return true; +} + +function checkAborted(stream: GridFSBucketWriteStream, callback?: Callback): boolean { + if (stream.state.aborted) { + if (typeof callback === 'function') { + // TODO(NODE-3485): Replace with MongoGridFSStreamClosedError + callback(new MongoAPIError('Stream has been aborted')); + } + return true; + } + return false; +} diff --git a/ts-ticket-office-service/node_modules/mongodb/src/index.ts b/ts-ticket-office-service/node_modules/mongodb/src/index.ts new file mode 100644 index 000000000..4872a1c39 --- /dev/null +++ b/ts-ticket-office-service/node_modules/mongodb/src/index.ts @@ -0,0 +1,476 @@ +import { Admin } from './admin'; +import { ObjectId } from './bson'; +import { Collection } from './collection'; +import { AbstractCursor } from './cursor/abstract_cursor'; +import { AggregationCursor } from './cursor/aggregation_cursor'; +import { FindCursor } from './cursor/find_cursor'; +import { ListCollectionsCursor } from './cursor/list_collections_cursor'; +import { ListIndexesCursor } from './cursor/list_indexes_cursor'; +import { Db } from './db'; +import { GridFSBucket } from './gridfs'; +import { Logger } from './logger'; +import { MongoClient } from './mongo_client'; +import { CancellationToken } from './mongo_types'; +import { PromiseProvider } from './promise_provider'; + +export { + Binary, + BSONRegExp, + BSONSymbol, + Code, + DBRef, + Decimal128, + Double, + Int32, + Long, + Map, + MaxKey, + MinKey, + ObjectId, + Timestamp +} from './bson'; +export { ChangeStreamCursor } from './cursor/change_stream_cursor'; +/** + * @public + * @deprecated Please use `ObjectId` + */ +export const ObjectID = ObjectId; + +export { AnyBulkWriteOperation, BulkWriteOptions, MongoBulkWriteError } from './bulk/common'; +export { + MongoAPIError, + MongoAWSError, + MongoBatchReExecutionError, + MongoChangeStreamError, + MongoCompatibilityError, + MongoCursorExhaustedError, + MongoCursorInUseError, + MongoDecompressionError, + MongoDriverError, + MongoError, + MongoExpiredSessionError, + MongoGridFSChunkError, + MongoGridFSStreamError, + MongoInvalidArgumentError, + MongoKerberosError, + MongoMissingCredentialsError, + MongoMissingDependencyError, + MongoNetworkError, + MongoNetworkTimeoutError, + MongoNotConnectedError, + MongoParseError, + MongoRuntimeError, + MongoServerClosedError, + MongoServerError, + MongoServerSelectionError, + MongoSystemError, + MongoTailableCursorError, + MongoTopologyClosedError, + MongoTransactionError, + MongoUnexpectedServerResponseError, + MongoWriteConcernError +} from './error'; +export { + AbstractCursor, + // Actual driver classes exported + Admin, + AggregationCursor, + CancellationToken, + Collection, + Db, + FindCursor, + GridFSBucket, + ListCollectionsCursor, + ListIndexesCursor, + Logger, + MongoClient, + // Utils + PromiseProvider as Promise +}; + +// enums +export { BatchType } from './bulk/common'; +export { GSSAPICanonicalizationValue } from './cmap/auth/gssapi'; +export { AuthMechanism } from './cmap/auth/providers'; +export { Compressor } from './cmap/wire_protocol/compression'; +export { CURSOR_FLAGS } from './cursor/abstract_cursor'; +export { AutoEncryptionLoggerLevel } from './deps'; +export { MongoErrorLabel } from './error'; +export { ExplainVerbosity } from './explain'; +export { LoggerLevel } from './logger'; +export { ServerApiVersion } from './mongo_client'; +export { BSONType } from './mongo_types'; +export { ReturnDocument } from './operations/find_and_modify'; +export { ProfilingLevel } from './operations/set_profiling_level'; +export { ReadConcernLevel } from './read_concern'; +export { ReadPreferenceMode } from './read_preference'; +export { ServerType, TopologyType } from './sdam/common'; + +// Helper classes +export { ReadConcern } from './read_concern'; +export { ReadPreference } from './read_preference'; +export { WriteConcern } from './write_concern'; + +// events +export { + CommandFailedEvent, + CommandStartedEvent, + CommandSucceededEvent +} from './cmap/command_monitoring_events'; +export { + ConnectionCheckedInEvent, + ConnectionCheckedOutEvent, + ConnectionCheckOutFailedEvent, + ConnectionCheckOutStartedEvent, + ConnectionClosedEvent, + ConnectionCreatedEvent, + ConnectionPoolClearedEvent, + ConnectionPoolClosedEvent, + ConnectionPoolCreatedEvent, + ConnectionPoolMonitoringEvent, + ConnectionReadyEvent +} from './cmap/connection_pool_events'; +export { + ServerClosedEvent, + ServerDescriptionChangedEvent, + ServerHeartbeatFailedEvent, + ServerHeartbeatStartedEvent, + ServerHeartbeatSucceededEvent, + ServerOpeningEvent, + TopologyClosedEvent, + TopologyDescriptionChangedEvent, + TopologyOpeningEvent +} from './sdam/events'; +export { SrvPollingEvent } from './sdam/srv_polling'; + +// type only exports below, these are removed from emitted JS +export type { AdminPrivate } from './admin'; +export type { BSONSerializeOptions, Document } from './bson'; +export type { deserialize, serialize } from './bson'; +export type { + BulkResult, + BulkWriteOperationError, + BulkWriteResult, + DeleteManyModel, + DeleteOneModel, + InsertOneModel, + ReplaceOneModel, + UpdateManyModel, + UpdateOneModel, + WriteConcernError, + WriteError +} from './bulk/common'; +export type { + Batch, + BulkOperationBase, + BulkOperationPrivate, + FindOperators, + WriteConcernErrorData +} from './bulk/common'; +export type { OrderedBulkOperation } from './bulk/ordered'; +export type { UnorderedBulkOperation } from './bulk/unordered'; +export type { + ChangeStream, + ChangeStreamCollModDocument, + ChangeStreamCreateDocument, + ChangeStreamCreateIndexDocument, + ChangeStreamDeleteDocument, + ChangeStreamDocument, + ChangeStreamDocumentCollectionUUID, + ChangeStreamDocumentCommon, + ChangeStreamDocumentKey, + ChangeStreamDocumentOperationDescription, + ChangeStreamDropDatabaseDocument, + ChangeStreamDropDocument, + ChangeStreamDropIndexDocument, + ChangeStreamEvents, + ChangeStreamInsertDocument, + ChangeStreamInvalidateDocument, + ChangeStreamNameSpace, + ChangeStreamOptions, + ChangeStreamRefineCollectionShardKeyDocument, + ChangeStreamRenameDocument, + ChangeStreamReplaceDocument, + ChangeStreamReshardCollectionDocument, + ChangeStreamShardCollectionDocument, + ChangeStreamUpdateDocument, + OperationTime, + PipeOptions, + ResumeOptions, + ResumeToken, + UpdateDescription +} from './change_stream'; +export type { + AuthMechanismProperties, + MongoCredentials, + MongoCredentialsOptions +} from './cmap/auth/mongo_credentials'; +export type { + BinMsg, + GetMore, + KillCursor, + MessageHeader, + Msg, + OpGetMoreOptions, + OpMsgOptions, + OpQueryOptions, + OpResponseOptions, + Query, + Response, + WriteProtocolMessageType +} from './cmap/commands'; +export type { LEGAL_TCP_SOCKET_OPTIONS, LEGAL_TLS_SOCKET_OPTIONS, Stream } from './cmap/connect'; +export type { + CommandOptions, + Connection, + ConnectionEvents, + ConnectionOptions, + DestroyOptions, + GetMoreOptions, + ProxyOptions, + QueryOptions +} from './cmap/connection'; +export type { + CloseOptions, + ConnectionPool, + ConnectionPoolEvents, + ConnectionPoolOptions, + WaitQueueMember, + WithConnectionCallback +} from './cmap/connection_pool'; +export type { + MessageStream, + MessageStreamOptions, + OperationDescription +} from './cmap/message_stream'; +export type { ConnectionPoolMetrics } from './cmap/metrics'; +export type { StreamDescription, StreamDescriptionOptions } from './cmap/stream_description'; +export type { CompressorName } from './cmap/wire_protocol/compression'; +export type { CollectionOptions, CollectionPrivate, ModifyResult } from './collection'; +export type { MONGO_CLIENT_EVENTS } from './constants'; +export type { + AbstractCursorEvents, + AbstractCursorOptions, + CursorCloseOptions, + CursorFlag, + CursorStreamOptions +} from './cursor/abstract_cursor'; +export type { InternalAbstractCursorOptions } from './cursor/abstract_cursor'; +export type { AggregationCursorOptions } from './cursor/aggregation_cursor'; +export type { + ChangeStreamAggregateRawResult, + ChangeStreamCursorOptions +} from './cursor/change_stream_cursor'; +export type { DbOptions, DbPrivate } from './db'; +export type { AutoEncrypter, AutoEncryptionOptions, AutoEncryptionTlsOptions } from './deps'; +export type { Encrypter, EncrypterOptions } from './encrypter'; +export type { AnyError, ErrorDescription, MongoNetworkErrorOptions } from './error'; +export type { Explain, ExplainOptions, ExplainVerbosityLike } from './explain'; +export type { + GridFSBucketReadStream, + GridFSBucketReadStreamOptions, + GridFSBucketReadStreamOptionsWithRevision, + GridFSBucketReadStreamPrivate, + GridFSFile +} from './gridfs/download'; +export type { GridFSBucketEvents, GridFSBucketOptions, GridFSBucketPrivate } from './gridfs/index'; +export type { + GridFSBucketWriteStream, + GridFSBucketWriteStreamOptions, + GridFSChunk +} from './gridfs/upload'; +export type { LoggerFunction, LoggerOptions } from './logger'; +export type { + Auth, + DriverInfo, + MongoClientEvents, + MongoClientOptions, + MongoClientPrivate, + MongoOptions, + PkFactory, + ServerApi, + SupportedNodeConnectionOptions, + SupportedSocketOptions, + SupportedTLSConnectionOptions, + SupportedTLSSocketOptions, + WithSessionCallback +} from './mongo_client'; +export type { + CommonEvents, + EventsDescription, + GenericListener, + TypedEventEmitter +} from './mongo_types'; +export type { + AcceptedFields, + AddToSetOperators, + AlternativeType, + ArrayElement, + ArrayOperator, + BitwiseFilter, + BSONTypeAlias, + Condition, + EnhancedOmit, + Filter, + FilterOperations, + FilterOperators, + Flatten, + InferIdType, + IntegerType, + IsAny, + Join, + KeysOfAType, + KeysOfOtherType, + MatchKeysAndValues, + NestedPaths, + NestedPathsOfType, + NonObjectIdLikeDocument, + NotAcceptedFields, + NumericType, + OneOrMore, + OnlyFieldsOfType, + OptionalId, + OptionalUnlessRequiredId, + Projection, + ProjectionOperators, + PropertyType, + PullAllOperator, + PullOperator, + PushOperator, + RegExpOrString, + RootFilterOperators, + SchemaMember, + SetFields, + UpdateFilter, + WithId, + WithoutId +} from './mongo_types'; +export type { AddUserOptions, RoleSpecification } from './operations/add_user'; +export type { + AggregateOperation, + AggregateOptions, + DB_AGGREGATE_COLLECTION +} from './operations/aggregate'; +export type { + CollationOptions, + CommandOperation, + CommandOperationOptions, + OperationParent +} from './operations/command'; +export type { IndexInformationOptions } from './operations/common_functions'; +export type { CountOptions } from './operations/count'; +export type { CountDocumentsOptions } from './operations/count_documents'; +export type { + ClusteredCollectionOptions, + CreateCollectionOptions, + TimeSeriesCollectionOptions +} from './operations/create_collection'; +export type { DeleteOptions, DeleteResult, DeleteStatement } from './operations/delete'; +export type { DistinctOptions } from './operations/distinct'; +export type { DropCollectionOptions, DropDatabaseOptions } from './operations/drop'; +export type { EstimatedDocumentCountOptions } from './operations/estimated_document_count'; +export type { EvalOptions } from './operations/eval'; +export type { ExecutionResult } from './operations/execute_operation'; +export type { FindOptions } from './operations/find'; +export type { + FindOneAndDeleteOptions, + FindOneAndReplaceOptions, + FindOneAndUpdateOptions +} from './operations/find_and_modify'; +export type { + CreateIndexesOptions, + DropIndexesOptions, + IndexDescription, + IndexDirection, + IndexSpecification, + ListIndexesOptions +} from './operations/indexes'; +export type { InsertManyResult, InsertOneOptions, InsertOneResult } from './operations/insert'; +export type { CollectionInfo, ListCollectionsOptions } from './operations/list_collections'; +export type { ListDatabasesOptions, ListDatabasesResult } from './operations/list_databases'; +export type { + FinalizeFunction, + MapFunction, + MapReduceOptions, + ReduceFunction +} from './operations/map_reduce'; +export type { AbstractOperation, Hint, OperationOptions } from './operations/operation'; +export type { ProfilingLevelOptions } from './operations/profiling_level'; +export type { RemoveUserOptions } from './operations/remove_user'; +export type { RenameOptions } from './operations/rename'; +export type { RunCommandOptions } from './operations/run_command'; +export type { SetProfilingLevelOptions } from './operations/set_profiling_level'; +export type { + CollStats, + CollStatsOptions, + DbStatsOptions, + WiredTigerData +} from './operations/stats'; +export type { + ReplaceOptions, + UpdateOptions, + UpdateResult, + UpdateStatement +} from './operations/update'; +export type { ValidateCollectionOptions } from './operations/validate_collection'; +export type { ReadConcernLike } from './read_concern'; +export type { + HedgeOptions, + ReadPreferenceFromOptions, + ReadPreferenceLike, + ReadPreferenceLikeOptions, + ReadPreferenceOptions +} from './read_preference'; +export type { ClusterTime, TimerQueue } from './sdam/common'; +export type { + Monitor, + MonitorEvents, + MonitorOptions, + MonitorPrivate, + RTTPinger, + RTTPingerOptions +} from './sdam/monitor'; +export type { Server, ServerEvents, ServerOptions, ServerPrivate } from './sdam/server'; +export type { + ServerDescription, + ServerDescriptionOptions, + TagSet, + TopologyVersion +} from './sdam/server_description'; +export type { ServerSelector } from './sdam/server_selection'; +export type { SrvPoller, SrvPollerEvents, SrvPollerOptions } from './sdam/srv_polling'; +export type { + ConnectOptions, + SelectServerOptions, + ServerCapabilities, + ServerSelectionCallback, + ServerSelectionRequest, + Topology, + TopologyEvents, + TopologyOptions, + TopologyPrivate +} from './sdam/topology'; +export type { TopologyDescription, TopologyDescriptionOptions } from './sdam/topology_description'; +export type { + ClientSession, + ClientSessionEvents, + ClientSessionOptions, + EndSessionOptions, + ServerSession, + ServerSessionId, + ServerSessionPool, + WithTransactionCallback +} from './sessions'; +export type { Sort, SortDirection, SortDirectionForCmd, SortForCmd } from './sort'; +export type { Transaction, TransactionOptions, TxnState } from './transactions'; +export type { + BufferPool, + Callback, + ClientMetadata, + ClientMetadataOptions, + EventEmitterWithState, + HostAddress, + InterruptibleAsyncInterval, + MongoDBNamespace +} from './utils'; +export type { W, WriteConcernOptions, WriteConcernSettings } from './write_concern'; diff --git a/ts-ticket-office-service/node_modules/mongodb/src/logger.ts b/ts-ticket-office-service/node_modules/mongodb/src/logger.ts new file mode 100644 index 000000000..22609c868 --- /dev/null +++ b/ts-ticket-office-service/node_modules/mongodb/src/logger.ts @@ -0,0 +1,265 @@ +import { format } from 'util'; + +import { MongoInvalidArgumentError } from './error'; +import { enumToString } from './utils'; + +// Filters for classes +const classFilters: any = {}; +let filteredClasses: any = {}; +let level: LoggerLevel; + +// Save the process id +const pid = process.pid; + +// current logger +// eslint-disable-next-line no-console +let currentLogger: LoggerFunction = console.warn; + +/** @public */ +export const LoggerLevel = Object.freeze({ + ERROR: 'error', + WARN: 'warn', + INFO: 'info', + DEBUG: 'debug', + error: 'error', + warn: 'warn', + info: 'info', + debug: 'debug' +} as const); + +/** @public */ +export type LoggerLevel = typeof LoggerLevel[keyof typeof LoggerLevel]; + +/** @public */ +export type LoggerFunction = (message?: any, ...optionalParams: any[]) => void; + +/** @public */ +export interface LoggerOptions { + logger?: LoggerFunction; + loggerLevel?: LoggerLevel; +} + +/** + * @public + */ +export class Logger { + className: string; + + /** + * Creates a new Logger instance + * + * @param className - The Class name associated with the logging instance + * @param options - Optional logging settings + */ + constructor(className: string, options?: LoggerOptions) { + options = options ?? {}; + + // Current reference + this.className = className; + + // Current logger + if (!(options.logger instanceof Logger) && typeof options.logger === 'function') { + currentLogger = options.logger; + } + + // Set level of logging, default is error + if (options.loggerLevel) { + level = options.loggerLevel || LoggerLevel.ERROR; + } + + // Add all class names + if (filteredClasses[this.className] == null) { + classFilters[this.className] = true; + } + } + + /** + * Log a message at the debug level + * + * @param message - The message to log + * @param object - Additional meta data to log + */ + debug(message: string, object?: unknown): void { + if ( + this.isDebug() && + ((Object.keys(filteredClasses).length > 0 && filteredClasses[this.className]) || + (Object.keys(filteredClasses).length === 0 && classFilters[this.className])) + ) { + const dateTime = new Date().getTime(); + const msg = format('[%s-%s:%s] %s %s', 'DEBUG', this.className, pid, dateTime, message); + const state = { + type: LoggerLevel.DEBUG, + message, + className: this.className, + pid, + date: dateTime + } as any; + + if (object) state.meta = object; + currentLogger(msg, state); + } + } + + /** + * Log a message at the warn level + * + * @param message - The message to log + * @param object - Additional meta data to log + */ + warn(message: string, object?: unknown): void { + if ( + this.isWarn() && + ((Object.keys(filteredClasses).length > 0 && filteredClasses[this.className]) || + (Object.keys(filteredClasses).length === 0 && classFilters[this.className])) + ) { + const dateTime = new Date().getTime(); + const msg = format('[%s-%s:%s] %s %s', 'WARN', this.className, pid, dateTime, message); + const state = { + type: LoggerLevel.WARN, + message, + className: this.className, + pid, + date: dateTime + } as any; + + if (object) state.meta = object; + currentLogger(msg, state); + } + } + + /** + * Log a message at the info level + * + * @param message - The message to log + * @param object - Additional meta data to log + */ + info(message: string, object?: unknown): void { + if ( + this.isInfo() && + ((Object.keys(filteredClasses).length > 0 && filteredClasses[this.className]) || + (Object.keys(filteredClasses).length === 0 && classFilters[this.className])) + ) { + const dateTime = new Date().getTime(); + const msg = format('[%s-%s:%s] %s %s', 'INFO', this.className, pid, dateTime, message); + const state = { + type: LoggerLevel.INFO, + message, + className: this.className, + pid, + date: dateTime + } as any; + + if (object) state.meta = object; + currentLogger(msg, state); + } + } + + /** + * Log a message at the error level + * + * @param message - The message to log + * @param object - Additional meta data to log + */ + error(message: string, object?: unknown): void { + if ( + this.isError() && + ((Object.keys(filteredClasses).length > 0 && filteredClasses[this.className]) || + (Object.keys(filteredClasses).length === 0 && classFilters[this.className])) + ) { + const dateTime = new Date().getTime(); + const msg = format('[%s-%s:%s] %s %s', 'ERROR', this.className, pid, dateTime, message); + const state = { + type: LoggerLevel.ERROR, + message, + className: this.className, + pid, + date: dateTime + } as any; + + if (object) state.meta = object; + currentLogger(msg, state); + } + } + + /** Is the logger set at info level */ + isInfo(): boolean { + return level === LoggerLevel.INFO || level === LoggerLevel.DEBUG; + } + + /** Is the logger set at error level */ + isError(): boolean { + return level === LoggerLevel.ERROR || level === LoggerLevel.INFO || level === LoggerLevel.DEBUG; + } + + /** Is the logger set at error level */ + isWarn(): boolean { + return ( + level === LoggerLevel.ERROR || + level === LoggerLevel.WARN || + level === LoggerLevel.INFO || + level === LoggerLevel.DEBUG + ); + } + + /** Is the logger set at debug level */ + isDebug(): boolean { + return level === LoggerLevel.DEBUG; + } + + /** Resets the logger to default settings, error and no filtered classes */ + static reset(): void { + level = LoggerLevel.ERROR; + filteredClasses = {}; + } + + /** Get the current logger function */ + static currentLogger(): LoggerFunction { + return currentLogger; + } + + /** + * Set the current logger function + * + * @param logger - Custom logging function + */ + static setCurrentLogger(logger: LoggerFunction): void { + if (typeof logger !== 'function') { + throw new MongoInvalidArgumentError('Current logger must be a function'); + } + + currentLogger = logger; + } + + /** + * Filter log messages for a particular class + * + * @param type - The type of filter (currently only class) + * @param values - The filters to apply + */ + static filter(type: string, values: string[]): void { + if (type === 'class' && Array.isArray(values)) { + filteredClasses = {}; + values.forEach(x => (filteredClasses[x] = true)); + } + } + + /** + * Set the current log level + * + * @param newLevel - Set current log level (debug, warn, info, error) + */ + static setLevel(newLevel: LoggerLevel): void { + if ( + newLevel !== LoggerLevel.INFO && + newLevel !== LoggerLevel.ERROR && + newLevel !== LoggerLevel.DEBUG && + newLevel !== LoggerLevel.WARN + ) { + throw new MongoInvalidArgumentError( + `Argument "newLevel" should be one of ${enumToString(LoggerLevel)}` + ); + } + + level = newLevel; + } +} diff --git a/ts-ticket-office-service/node_modules/mongodb/src/mongo_client.ts b/ts-ticket-office-service/node_modules/mongodb/src/mongo_client.ts new file mode 100644 index 000000000..5c152e311 --- /dev/null +++ b/ts-ticket-office-service/node_modules/mongodb/src/mongo_client.ts @@ -0,0 +1,769 @@ +import type { TcpNetConnectOpts } from 'net'; +import type { ConnectionOptions as TLSConnectionOptions, TLSSocketOptions } from 'tls'; + +import { BSONSerializeOptions, Document, resolveBSONOptions } from './bson'; +import { ChangeStream, ChangeStreamDocument, ChangeStreamOptions } from './change_stream'; +import type { AuthMechanismProperties, MongoCredentials } from './cmap/auth/mongo_credentials'; +import type { AuthMechanism } from './cmap/auth/providers'; +import type { LEGAL_TCP_SOCKET_OPTIONS, LEGAL_TLS_SOCKET_OPTIONS } from './cmap/connect'; +import type { Connection } from './cmap/connection'; +import type { CompressorName } from './cmap/wire_protocol/compression'; +import { parseOptions } from './connection_string'; +import type { MONGO_CLIENT_EVENTS } from './constants'; +import { Db, DbOptions } from './db'; +import type { AutoEncrypter, AutoEncryptionOptions } from './deps'; +import type { Encrypter } from './encrypter'; +import { MongoInvalidArgumentError } from './error'; +import type { Logger, LoggerLevel } from './logger'; +import { TypedEventEmitter } from './mongo_types'; +import { connect } from './operations/connect'; +import { PromiseProvider } from './promise_provider'; +import type { ReadConcern, ReadConcernLevel, ReadConcernLike } from './read_concern'; +import { ReadPreference, ReadPreferenceMode } from './read_preference'; +import type { TagSet } from './sdam/server_description'; +import type { SrvPoller } from './sdam/srv_polling'; +import type { Topology, TopologyEvents } from './sdam/topology'; +import { ClientSession, ClientSessionOptions, ServerSessionPool } from './sessions'; +import { + Callback, + ClientMetadata, + HostAddress, + maybePromise, + MongoDBNamespace, + ns, + resolveOptions +} from './utils'; +import type { W, WriteConcern } from './write_concern'; + +/** @public */ +export const ServerApiVersion = Object.freeze({ + v1: '1' +} as const); + +/** @public */ +export type ServerApiVersion = typeof ServerApiVersion[keyof typeof ServerApiVersion]; + +/** @public */ +export interface ServerApi { + version: ServerApiVersion; + strict?: boolean; + deprecationErrors?: boolean; +} + +/** @public */ +export interface DriverInfo { + name?: string; + version?: string; + platform?: string; +} + +/** @public */ +export interface Auth { + /** The username for auth */ + username?: string; + /** The password for auth */ + password?: string; +} + +/** @public */ +export interface PkFactory { + createPk(): any; // TODO: when js-bson is typed, function should return some BSON type +} + +/** @public */ +export type SupportedTLSConnectionOptions = Pick< + TLSConnectionOptions, + Extract +>; + +/** @public */ +export type SupportedTLSSocketOptions = Pick< + TLSSocketOptions, + Extract +>; + +/** @public */ +export type SupportedSocketOptions = Pick< + TcpNetConnectOpts, + typeof LEGAL_TCP_SOCKET_OPTIONS[number] +>; + +/** @public */ +export type SupportedNodeConnectionOptions = SupportedTLSConnectionOptions & + SupportedTLSSocketOptions & + SupportedSocketOptions; + +/** + * Describes all possible URI query options for the mongo client + * @public + * @see https://docs.mongodb.com/manual/reference/connection-string + */ +export interface MongoClientOptions extends BSONSerializeOptions, SupportedNodeConnectionOptions { + /** Specifies the name of the replica set, if the mongod is a member of a replica set. */ + replicaSet?: string; + /** Enables or disables TLS/SSL for the connection. */ + tls?: boolean; + /** A boolean to enable or disables TLS/SSL for the connection. (The ssl option is equivalent to the tls option.) */ + ssl?: boolean; + /** Specifies the location of a local TLS Certificate */ + tlsCertificateFile?: string; + /** Specifies the location of a local .pem file that contains either the client's TLS/SSL certificate and key or only the client's TLS/SSL key when tlsCertificateFile is used to provide the certificate. */ + tlsCertificateKeyFile?: string; + /** Specifies the password to de-crypt the tlsCertificateKeyFile. */ + tlsCertificateKeyFilePassword?: string; + /** Specifies the location of a local .pem file that contains the root certificate chain from the Certificate Authority. This file is used to validate the certificate presented by the mongod/mongos instance. */ + tlsCAFile?: string; + /** Bypasses validation of the certificates presented by the mongod/mongos instance */ + tlsAllowInvalidCertificates?: boolean; + /** Disables hostname validation of the certificate presented by the mongod/mongos instance. */ + tlsAllowInvalidHostnames?: boolean; + /** Disables various certificate validations. */ + tlsInsecure?: boolean; + /** The time in milliseconds to attempt a connection before timing out. */ + connectTimeoutMS?: number; + /** The time in milliseconds to attempt a send or receive on a socket before the attempt times out. */ + socketTimeoutMS?: number; + /** An array or comma-delimited string of compressors to enable network compression for communication between this client and a mongod/mongos instance. */ + compressors?: CompressorName[] | string; + /** An integer that specifies the compression level if using zlib for network compression. */ + zlibCompressionLevel?: 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | undefined; + /** The maximum number of hosts to connect to when using an srv connection string, a setting of `0` means unlimited hosts */ + srvMaxHosts?: number; + /** + * Modifies the srv URI to look like: + * + * `_{srvServiceName}._tcp.{hostname}.{domainname}` + * + * Querying this DNS URI is expected to respond with SRV records + */ + srvServiceName?: string; + /** The maximum number of connections in the connection pool. */ + maxPoolSize?: number; + /** The minimum number of connections in the connection pool. */ + minPoolSize?: number; + /** The maximum number of connections that may be in the process of being established concurrently by the connection pool. */ + maxConnecting?: number; + /** The maximum number of milliseconds that a connection can remain idle in the pool before being removed and closed. */ + maxIdleTimeMS?: number; + /** The maximum time in milliseconds that a thread can wait for a connection to become available. */ + waitQueueTimeoutMS?: number; + /** Specify a read concern for the collection (only MongoDB 3.2 or higher supported) */ + readConcern?: ReadConcernLike; + /** The level of isolation */ + readConcernLevel?: ReadConcernLevel; + /** Specifies the read preferences for this connection */ + readPreference?: ReadPreferenceMode | ReadPreference; + /** Specifies, in seconds, how stale a secondary can be before the client stops using it for read operations. */ + maxStalenessSeconds?: number; + /** Specifies the tags document as a comma-separated list of colon-separated key-value pairs. */ + readPreferenceTags?: TagSet[]; + /** The auth settings for when connection to server. */ + auth?: Auth; + /** Specify the database name associated with the user’s credentials. */ + authSource?: string; + /** Specify the authentication mechanism that MongoDB will use to authenticate the connection. */ + authMechanism?: AuthMechanism; + /** Specify properties for the specified authMechanism as a comma-separated list of colon-separated key-value pairs. */ + authMechanismProperties?: AuthMechanismProperties; + /** The size (in milliseconds) of the latency window for selecting among multiple suitable MongoDB instances. */ + localThresholdMS?: number; + /** Specifies how long (in milliseconds) to block for server selection before throwing an exception. */ + serverSelectionTimeoutMS?: number; + /** heartbeatFrequencyMS controls when the driver checks the state of the MongoDB deployment. Specify the interval (in milliseconds) between checks, counted from the end of the previous check until the beginning of the next one. */ + heartbeatFrequencyMS?: number; + /** Sets the minimum heartbeat frequency. In the event that the driver has to frequently re-check a server's availability, it will wait at least this long since the previous check to avoid wasted effort. */ + minHeartbeatFrequencyMS?: number; + /** The name of the application that created this MongoClient instance. MongoDB 3.4 and newer will print this value in the server log upon establishing each connection. It is also recorded in the slow query log and profile collections */ + appName?: string; + /** Enables retryable reads. */ + retryReads?: boolean; + /** Enable retryable writes. */ + retryWrites?: boolean; + /** Allow a driver to force a Single topology type with a connection string containing one host */ + directConnection?: boolean; + /** Instruct the driver it is connecting to a load balancer fronting a mongos like service */ + loadBalanced?: boolean; + + /** The write concern w value */ + w?: W; + /** The write concern timeout */ + wtimeoutMS?: number; + /** The journal write concern */ + journal?: boolean; + + /** Validate mongod server certificate against Certificate Authority */ + sslValidate?: boolean; + /** SSL Certificate file path. */ + sslCA?: string; + /** SSL Certificate file path. */ + sslCert?: string; + /** SSL Key file file path. */ + sslKey?: string; + /** SSL Certificate pass phrase. */ + sslPass?: string; + /** SSL Certificate revocation list file path. */ + sslCRL?: string; + /** TCP Connection no delay */ + noDelay?: boolean; + /** TCP Connection keep alive enabled */ + keepAlive?: boolean; + /** The number of milliseconds to wait before initiating keepAlive on the TCP socket */ + keepAliveInitialDelay?: number; + /** Force server to assign `_id` values instead of driver */ + forceServerObjectId?: boolean; + /** Return document results as raw BSON buffers */ + raw?: boolean; + /** A primary key factory function for generation of custom `_id` keys */ + pkFactory?: PkFactory; + /** A Promise library class the application wishes to use such as Bluebird, must be ES6 compatible */ + promiseLibrary?: any; + /** The logging level */ + loggerLevel?: LoggerLevel; + /** Custom logger object */ + logger?: Logger; + /** Enable command monitoring for this client */ + monitorCommands?: boolean; + /** Server API version */ + serverApi?: ServerApi | ServerApiVersion; + /** + * Optionally enable client side auto encryption + * + * @remarks + * Automatic encryption is an enterprise only feature that only applies to operations on a collection. Automatic encryption is not supported for operations on a database or view, and operations that are not bypassed will result in error + * (see [libmongocrypt: Auto Encryption Allow-List](https://github.com/mongodb/specifications/blob/master/source/client-side-encryption/client-side-encryption.rst#libmongocrypt-auto-encryption-allow-list)). To bypass automatic encryption for all operations, set bypassAutoEncryption=true in AutoEncryptionOpts. + * + * Automatic encryption requires the authenticated user to have the [listCollections privilege action](https://docs.mongodb.com/manual/reference/command/listCollections/#dbcmd.listCollections). + * + * If a MongoClient with a limited connection pool size (i.e a non-zero maxPoolSize) is configured with AutoEncryptionOptions, a separate internal MongoClient is created if any of the following are true: + * - AutoEncryptionOptions.keyVaultClient is not passed. + * - AutoEncryptionOptions.bypassAutomaticEncryption is false. + * + * If an internal MongoClient is created, it is configured with the same options as the parent MongoClient except minPoolSize is set to 0 and AutoEncryptionOptions is omitted. + */ + autoEncryption?: AutoEncryptionOptions; + /** Allows a wrapping driver to amend the client metadata generated by the driver to include information about the wrapping driver */ + driverInfo?: DriverInfo; + /** Configures a Socks5 proxy host used for creating TCP connections. */ + proxyHost?: string; + /** Configures a Socks5 proxy port used for creating TCP connections. */ + proxyPort?: number; + /** Configures a Socks5 proxy username when the proxy in proxyHost requires username/password authentication. */ + proxyUsername?: string; + /** Configures a Socks5 proxy password when the proxy in proxyHost requires username/password authentication. */ + proxyPassword?: string; + + /** @internal */ + srvPoller?: SrvPoller; + /** @internal */ + connectionType?: typeof Connection; + + /** @internal */ + [featureFlag: symbol]: any; +} + +/** @public */ +export type WithSessionCallback = (session: ClientSession) => Promise; + +/** @internal */ +export interface MongoClientPrivate { + url: string; + bsonOptions: BSONSerializeOptions; + namespace: MongoDBNamespace; + hasBeenClosed: boolean; + /** + * We keep a reference to the sessions that are acquired from the pool. + * - used to track and close all sessions in client.close() (which is non-standard behavior) + * - used to notify the leak checker in our tests if test author forgot to clean up explicit sessions + */ + readonly activeSessions: Set; + readonly sessionPool: ServerSessionPool; + readonly options: MongoOptions; + readonly readConcern?: ReadConcern; + readonly writeConcern?: WriteConcern; + readonly readPreference: ReadPreference; + readonly logger: Logger; + readonly isMongoClient: true; +} + +/** @public */ +export type MongoClientEvents = Pick & { + // In previous versions the open event emitted a topology, in an effort to no longer + // expose internals but continue to expose this useful event API, it now emits a mongoClient + open(mongoClient: MongoClient): void; +}; + +/** @internal */ +const kOptions = Symbol('options'); + +/** + * The **MongoClient** class is a class that allows for making Connections to MongoDB. + * @public + * + * @remarks + * The programmatically provided options take precedence over the URI options. + * + * @example + * ```js + * // Connect using a MongoClient instance + * const MongoClient = require('mongodb').MongoClient; + * const test = require('assert'); + * // Connection url + * const url = 'mongodb://localhost:27017'; + * // Database Name + * const dbName = 'test'; + * // Connect using MongoClient + * const mongoClient = new MongoClient(url); + * mongoClient.connect(function(err, client) { + * const db = client.db(dbName); + * client.close(); + * }); + * ``` + * + * @example + * ```js + * // Connect using the MongoClient.connect static method + * const MongoClient = require('mongodb').MongoClient; + * const test = require('assert'); + * // Connection url + * const url = 'mongodb://localhost:27017'; + * // Database Name + * const dbName = 'test'; + * // Connect using MongoClient + * MongoClient.connect(url, function(err, client) { + * const db = client.db(dbName); + * client.close(); + * }); + * ``` + */ +export class MongoClient extends TypedEventEmitter { + /** @internal */ + s: MongoClientPrivate; + /** @internal */ + topology?: Topology; + + /** + * The consolidate, parsed, transformed and merged options. + * @internal + */ + [kOptions]: MongoOptions; + + constructor(url: string, options?: MongoClientOptions) { + super(); + + this[kOptions] = parseOptions(url, this, options); + + // eslint-disable-next-line @typescript-eslint/no-this-alias + const client = this; + + // The internal state + this.s = { + url, + bsonOptions: resolveBSONOptions(this[kOptions]), + namespace: ns('admin'), + hasBeenClosed: false, + sessionPool: new ServerSessionPool(this), + activeSessions: new Set(), + + get options() { + return client[kOptions]; + }, + get readConcern() { + return client[kOptions].readConcern; + }, + get writeConcern() { + return client[kOptions].writeConcern; + }, + get readPreference() { + return client[kOptions].readPreference; + }, + get logger() { + return client[kOptions].logger; + }, + get isMongoClient(): true { + return true; + } + }; + } + + get options(): Readonly { + return Object.freeze({ ...this[kOptions] }); + } + + get serverApi(): Readonly { + return this[kOptions].serverApi && Object.freeze({ ...this[kOptions].serverApi }); + } + /** + * Intended for APM use only + * @internal + */ + get monitorCommands(): boolean { + return this[kOptions].monitorCommands; + } + set monitorCommands(value: boolean) { + this[kOptions].monitorCommands = value; + } + + get autoEncrypter(): AutoEncrypter | undefined { + return this[kOptions].autoEncrypter; + } + + get readConcern(): ReadConcern | undefined { + return this.s.readConcern; + } + + get writeConcern(): WriteConcern | undefined { + return this.s.writeConcern; + } + + get readPreference(): ReadPreference { + return this.s.readPreference; + } + + get bsonOptions(): BSONSerializeOptions { + return this.s.bsonOptions; + } + + get logger(): Logger { + return this.s.logger; + } + + /** + * Connect to MongoDB using a url + * + * @see docs.mongodb.org/manual/reference/connection-string/ + */ + connect(): Promise; + connect(callback: Callback): void; + connect(callback?: Callback): Promise | void { + if (callback && typeof callback !== 'function') { + throw new MongoInvalidArgumentError('Method `connect` only accepts a callback'); + } + + return maybePromise(callback, cb => { + connect(this, this[kOptions], err => { + if (err) return cb(err); + cb(undefined, this); + }); + }); + } + + /** + * Close the db and its underlying connections + * + * @param force - Force close, emitting no events + * @param callback - An optional callback, a Promise will be returned if none is provided + */ + close(): Promise; + close(callback: Callback): void; + close(force: boolean): Promise; + close(force: boolean, callback: Callback): void; + close( + forceOrCallback?: boolean | Callback, + callback?: Callback + ): Promise | void { + // There's no way to set hasBeenClosed back to false + Object.defineProperty(this.s, 'hasBeenClosed', { + value: true, + enumerable: true, + configurable: false, + writable: false + }); + + if (typeof forceOrCallback === 'function') { + callback = forceOrCallback; + } + + const force = typeof forceOrCallback === 'boolean' ? forceOrCallback : false; + + return maybePromise(callback, callback => { + if (this.topology == null) { + // Do not connect just to end sessions + return callback(); + } + + const activeSessionEnds = Array.from(this.s.activeSessions, session => session.endSession()); + this.s.activeSessions.clear(); + + Promise.all(activeSessionEnds) + .then(() => { + const endSessions = Array.from(this.s.sessionPool.sessions, ({ id }) => id); + if (endSessions.length === 0) return; + return this.db('admin') + .command( + { endSessions }, + { readPreference: ReadPreference.primaryPreferred, noResponse: true } + ) + .catch(() => null); // outcome does not matter + }) + .then(() => { + if (this.topology == null) { + return callback(); + } + // clear out references to old topology + const topology = this.topology; + this.topology = undefined; + + return new Promise((resolve, reject) => { + topology.close({ force }, error => { + if (error) return reject(error); + const { encrypter } = this[kOptions]; + if (encrypter) { + return encrypter.close(this, force, error => { + if (error) return reject(error); + resolve(); + }); + } + resolve(); + }); + }); + }) + .then( + () => callback(), + error => callback(error) + ); + }); + } + + /** + * Create a new Db instance sharing the current socket connections. + * + * @param dbName - The name of the database we want to use. If not provided, use database name from connection string. + * @param options - Optional settings for Db construction + */ + db(dbName?: string, options?: DbOptions): Db { + options = options ?? {}; + + // Default to db from connection string if not provided + if (!dbName) { + dbName = this.options.dbName; + } + + // Copy the options and add out internal override of the not shared flag + const finalOptions = Object.assign({}, this[kOptions], options); + + // Return the db object + const db = new Db(this, dbName, finalOptions); + + // Return the database + return db; + } + + /** + * Connect to MongoDB using a url + * + * @remarks + * The programmatically provided options take precedence over the URI options. + * + * @see https://docs.mongodb.org/manual/reference/connection-string/ + */ + static connect(url: string): Promise; + static connect(url: string, callback: Callback): void; + static connect(url: string, options: MongoClientOptions): Promise; + static connect(url: string, options: MongoClientOptions, callback: Callback): void; + static connect( + url: string, + options?: MongoClientOptions | Callback, + callback?: Callback + ): Promise | void { + if (typeof options === 'function') (callback = options), (options = {}); + options = options ?? {}; + + try { + // Create client + const mongoClient = new MongoClient(url, options); + // Execute the connect method + if (callback) { + return mongoClient.connect(callback); + } else { + return mongoClient.connect(); + } + } catch (error) { + if (callback) return callback(error); + else return PromiseProvider.get().reject(error); + } + } + + /** Starts a new session on the server */ + startSession(): ClientSession; + startSession(options: ClientSessionOptions): ClientSession; + startSession(options?: ClientSessionOptions): ClientSession { + const session = new ClientSession( + this, + this.s.sessionPool, + { explicit: true, ...options }, + this[kOptions] + ); + this.s.activeSessions.add(session); + session.once('ended', () => { + this.s.activeSessions.delete(session); + }); + return session; + } + + /** + * Runs a given operation with an implicitly created session. The lifetime of the session + * will be handled without the need for user interaction. + * + * NOTE: presently the operation MUST return a Promise (either explicit or implicitly as an async function) + * + * @param options - Optional settings for the command + * @param callback - An callback to execute with an implicitly created session + */ + withSession(callback: WithSessionCallback): Promise; + withSession(options: ClientSessionOptions, callback: WithSessionCallback): Promise; + withSession( + optionsOrOperation?: ClientSessionOptions | WithSessionCallback, + callback?: WithSessionCallback + ): Promise { + const options = { + // Always define an owner + owner: Symbol(), + // If it's an object inherit the options + ...(typeof optionsOrOperation === 'object' ? optionsOrOperation : {}) + }; + + const withSessionCallback = + typeof optionsOrOperation === 'function' ? optionsOrOperation : callback; + + if (withSessionCallback == null) { + throw new MongoInvalidArgumentError('Missing required callback parameter'); + } + + const session = this.startSession(options); + const Promise = PromiseProvider.get(); + + return Promise.resolve() + .then(() => withSessionCallback(session)) + .then(() => { + // Do not return the result of callback + }) + .finally(() => { + session.endSession().catch(() => null); + }); + } + + /** + * Create a new Change Stream, watching for new changes (insertions, updates, + * replacements, deletions, and invalidations) in this cluster. Will ignore all + * changes to system collections, as well as the local, admin, and config databases. + * + * @remarks + * watch() accepts two generic arguments for distinct usecases: + * - The first is to provide the schema that may be defined for all the data within the current cluster + * - The second is to override the shape of the change stream document entirely, if it is not provided the type will default to ChangeStreamDocument of the first argument + * + * @param pipeline - An array of {@link https://docs.mongodb.com/manual/reference/operator/aggregation-pipeline/|aggregation pipeline stages} through which to pass change stream documents. This allows for filtering (using $match) and manipulating the change stream documents. + * @param options - Optional settings for the command + * @typeParam TSchema - Type of the data being detected by the change stream + * @typeParam TChange - Type of the whole change stream document emitted + */ + watch< + TSchema extends Document = Document, + TChange extends Document = ChangeStreamDocument + >(pipeline: Document[] = [], options: ChangeStreamOptions = {}): ChangeStream { + // Allow optionally not specifying a pipeline + if (!Array.isArray(pipeline)) { + options = pipeline; + pipeline = []; + } + + return new ChangeStream(this, pipeline, resolveOptions(this, options)); + } + + /** Return the mongo client logger */ + getLogger(): Logger { + return this.s.logger; + } +} + +/** + * Mongo Client Options + * @public + */ +export interface MongoOptions + extends Required< + Pick< + MongoClientOptions, + | 'autoEncryption' + | 'connectTimeoutMS' + | 'directConnection' + | 'driverInfo' + | 'forceServerObjectId' + | 'minHeartbeatFrequencyMS' + | 'heartbeatFrequencyMS' + | 'keepAlive' + | 'keepAliveInitialDelay' + | 'localThresholdMS' + | 'logger' + | 'maxConnecting' + | 'maxIdleTimeMS' + | 'maxPoolSize' + | 'minPoolSize' + | 'monitorCommands' + | 'noDelay' + | 'pkFactory' + | 'promiseLibrary' + | 'raw' + | 'replicaSet' + | 'retryReads' + | 'retryWrites' + | 'serverSelectionTimeoutMS' + | 'socketTimeoutMS' + | 'srvMaxHosts' + | 'srvServiceName' + | 'tlsAllowInvalidCertificates' + | 'tlsAllowInvalidHostnames' + | 'tlsInsecure' + | 'waitQueueTimeoutMS' + | 'zlibCompressionLevel' + > + >, + SupportedNodeConnectionOptions { + hosts: HostAddress[]; + srvHost?: string; + credentials?: MongoCredentials; + readPreference: ReadPreference; + readConcern: ReadConcern; + loadBalanced: boolean; + serverApi: ServerApi; + compressors: CompressorName[]; + writeConcern: WriteConcern; + dbName: string; + metadata: ClientMetadata; + autoEncrypter?: AutoEncrypter; + proxyHost?: string; + proxyPort?: number; + proxyUsername?: string; + proxyPassword?: string; + /** @internal */ + connectionType?: typeof Connection; + + /** @internal */ + encrypter: Encrypter; + /** @internal */ + userSpecifiedAuthSource: boolean; + /** @internal */ + userSpecifiedReplicaSet: boolean; + + /** + * # NOTE ABOUT TLS Options + * + * If set TLS enabled, equivalent to setting the ssl option. + * + * ### Additional options: + * + * | nodejs option | MongoDB equivalent | type | + * |:---------------------|--------------------------------------------------------- |:---------------------------------------| + * | `ca` | `sslCA`, `tlsCAFile` | `string \| Buffer \| Buffer[]` | + * | `crl` | `sslCRL` | `string \| Buffer \| Buffer[]` | + * | `cert` | `sslCert`, `tlsCertificateFile`, `tlsCertificateKeyFile` | `string \| Buffer \| Buffer[]` | + * | `key` | `sslKey`, `tlsCertificateKeyFile` | `string \| Buffer \| KeyObject[]` | + * | `passphrase` | `sslPass`, `tlsCertificateKeyFilePassword` | `string` | + * | `rejectUnauthorized` | `sslValidate` | `boolean` | + * + */ + tls: boolean; + + /** @internal */ + [featureFlag: symbol]: any; +} diff --git a/ts-ticket-office-service/node_modules/mongodb/src/mongo_types.ts b/ts-ticket-office-service/node_modules/mongodb/src/mongo_types.ts new file mode 100644 index 000000000..9891e0abf --- /dev/null +++ b/ts-ticket-office-service/node_modules/mongodb/src/mongo_types.ts @@ -0,0 +1,548 @@ +import type { ObjectIdLike } from 'bson'; +import { EventEmitter } from 'events'; + +import type { + Binary, + BSONRegExp, + Decimal128, + Document, + Double, + Int32, + Long, + ObjectId, + Timestamp +} from './bson'; +import type { Sort } from './sort'; + +/** @internal */ +export type TODO_NODE_3286 = any; + +/** Given an object shaped type, return the type of the _id field or default to ObjectId @public */ +export type InferIdType = TSchema extends { _id: infer IdType } + ? // user has defined a type for _id + Record extends IdType + ? never // explicitly forbid empty objects as the type of _id + : IdType + : TSchema extends { _id?: infer IdType } + ? // optional _id defined - return ObjectId | IdType + unknown extends IdType + ? ObjectId // infer the _id type as ObjectId if the type of _id is unknown + : IdType + : ObjectId; // user has not defined _id on schema + +/** Add an _id field to an object shaped type @public */ +export type WithId = EnhancedOmit & { _id: InferIdType }; + +/** + * Add an optional _id field to an object shaped type + * @public + */ +export type OptionalId = EnhancedOmit & { _id?: InferIdType }; + +/** + * Adds an optional _id field to an object shaped type, unless the _id field is requried on that type. + * In the case _id is required, this method continues to require_id. + * + * @public + * + * @privateRemarks + * `ObjectId extends TSchema['_id']` is a confusing ordering at first glance. Rather than ask + * `TSchema['_id'] extends ObjectId` which translated to "Is the _id property ObjectId?" + * we instead ask "Does ObjectId look like (have the same shape) as the _id?" + */ +export type OptionalUnlessRequiredId = TSchema extends { _id: any } + ? TSchema + : OptionalId; + +/** TypeScript Omit (Exclude to be specific) does not work for objects with an "any" indexed type, and breaks discriminated unions @public */ +export type EnhancedOmit = string extends keyof TRecordOrUnion + ? TRecordOrUnion // TRecordOrUnion has indexed type e.g. { _id: string; [k: string]: any; } or it is "any" + : TRecordOrUnion extends any + ? Pick> // discriminated unions + : never; + +/** Remove the _id field from an object shaped type @public */ +export type WithoutId = Omit; + +/** A MongoDB filter can be some portion of the schema or a set of operators @public */ +export type Filter = + | Partial + | ({ + [Property in Join>, '.'>]?: Condition< + PropertyType, Property> + >; + } & RootFilterOperators>); + +/** @public */ +export type Condition = AlternativeType | FilterOperators>; + +/** + * It is possible to search using alternative types in mongodb e.g. + * string types can be searched using a regex in mongo + * array types can be searched using their element type + * @public + */ +export type AlternativeType = T extends ReadonlyArray + ? T | RegExpOrString + : RegExpOrString; + +/** @public */ +export type RegExpOrString = T extends string ? BSONRegExp | RegExp | T : T; + +/** @public */ +export interface RootFilterOperators extends Document { + $and?: Filter[]; + $nor?: Filter[]; + $or?: Filter[]; + $text?: { + $search: string; + $language?: string; + $caseSensitive?: boolean; + $diacriticSensitive?: boolean; + }; + $where?: string | ((this: TSchema) => boolean); + $comment?: string | Document; +} + +/** + * @public + * A type that extends Document but forbids anything that "looks like" an object id. + */ +export type NonObjectIdLikeDocument = { + [key in keyof ObjectIdLike]?: never; +} & Document; + +/** @public */ +export interface FilterOperators extends NonObjectIdLikeDocument { + // Comparison + $eq?: TValue; + $gt?: TValue; + $gte?: TValue; + $in?: ReadonlyArray; + $lt?: TValue; + $lte?: TValue; + $ne?: TValue; + $nin?: ReadonlyArray; + // Logical + $not?: TValue extends string ? FilterOperators | RegExp : FilterOperators; + // Element + /** + * When `true`, `$exists` matches the documents that contain the field, + * including documents where the field value is null. + */ + $exists?: boolean; + $type?: BSONType | BSONTypeAlias; + // Evaluation + $expr?: Record; + $jsonSchema?: Record; + $mod?: TValue extends number ? [number, number] : never; + $regex?: TValue extends string ? RegExp | BSONRegExp | string : never; + $options?: TValue extends string ? string : never; + // Geospatial + $geoIntersects?: { $geometry: Document }; + $geoWithin?: Document; + $near?: Document; + $nearSphere?: Document; + $maxDistance?: number; + // Array + $all?: ReadonlyArray; + $elemMatch?: Document; + $size?: TValue extends ReadonlyArray ? number : never; + // Bitwise + $bitsAllClear?: BitwiseFilter; + $bitsAllSet?: BitwiseFilter; + $bitsAnyClear?: BitwiseFilter; + $bitsAnySet?: BitwiseFilter; + $rand?: Record; +} + +/** @public */ +export type BitwiseFilter = + | number /** numeric bit mask */ + | Binary /** BinData bit mask */ + | ReadonlyArray; /** `[ , , ... ]` */ + +/** @public */ +export const BSONType = Object.freeze({ + double: 1, + string: 2, + object: 3, + array: 4, + binData: 5, + undefined: 6, + objectId: 7, + bool: 8, + date: 9, + null: 10, + regex: 11, + dbPointer: 12, + javascript: 13, + symbol: 14, + javascriptWithScope: 15, + int: 16, + timestamp: 17, + long: 18, + decimal: 19, + minKey: -1, + maxKey: 127 +} as const); + +/** @public */ +export type BSONType = typeof BSONType[keyof typeof BSONType]; +/** @public */ +export type BSONTypeAlias = keyof typeof BSONType; + +/** + * @public + * Projection is flexible to permit the wide array of aggregation operators + * @deprecated since v4.1.0: Since projections support all aggregation operations we have no plans to narrow this type further + */ +// eslint-disable-next-line @typescript-eslint/no-unused-vars +export type Projection = Document; + +/** + * @public + * @deprecated since v4.1.0: Since projections support all aggregation operations we have no plans to narrow this type further + */ +export type ProjectionOperators = Document; + +/** @public */ +export type IsAny = true extends false & Type + ? ResultIfAny + : ResultIfNotAny; + +/** @public */ +export type Flatten = Type extends ReadonlyArray ? Item : Type; + +/** @public */ +export type ArrayElement = Type extends ReadonlyArray ? Item : never; + +/** @public */ +export type SchemaMember = { [P in keyof T]?: V } | { [key: string]: V }; + +/** @public */ +export type IntegerType = number | Int32 | Long; + +/** @public */ +export type NumericType = IntegerType | Decimal128 | Double; + +/** @public */ +export type FilterOperations = T extends Record + ? { [key in keyof T]?: FilterOperators } + : FilterOperators; + +/** @public */ +export type KeysOfAType = { + [key in keyof TSchema]: NonNullable extends Type ? key : never; +}[keyof TSchema]; + +/** @public */ +export type KeysOfOtherType = { + [key in keyof TSchema]: NonNullable extends Type ? never : key; +}[keyof TSchema]; + +/** @public */ +export type AcceptedFields = { + readonly [key in KeysOfAType]?: AssignableType; +}; + +/** It avoids using fields with not acceptable types @public */ +export type NotAcceptedFields = { + readonly [key in KeysOfOtherType]?: never; +}; + +/** @public */ +export type OnlyFieldsOfType = IsAny< + TSchema[keyof TSchema], + Record, + AcceptedFields & + NotAcceptedFields & + Record +>; + +/** @public */ +export type MatchKeysAndValues = Readonly< + { + [Property in Join, '.'>]?: PropertyType; + } & { + [Property in `${NestedPathsOfType}.$${`[${string}]` | ''}`]?: ArrayElement< + PropertyType + >; + } & { + [Property in `${NestedPathsOfType[]>}.$${ + | `[${string}]` + | ''}.${string}`]?: any; // Could be further narrowed + } +>; + +/** @public */ +export type AddToSetOperators = { + $each?: Array>; +}; + +/** @public */ +export type ArrayOperator = { + $each?: Array>; + $slice?: number; + $position?: number; + $sort?: Sort; +}; + +/** @public */ +export type SetFields = ({ + readonly [key in KeysOfAType | undefined>]?: + | OptionalId> + | AddToSetOperators>>>; +} & NotAcceptedFields | undefined>) & { + readonly [key: string]: AddToSetOperators | any; +}; + +/** @public */ +export type PushOperator = ({ + readonly [key in KeysOfAType>]?: + | Flatten + | ArrayOperator>>; +} & NotAcceptedFields>) & { + readonly [key: string]: ArrayOperator | any; +}; + +/** @public */ +export type PullOperator = ({ + readonly [key in KeysOfAType>]?: + | Partial> + | FilterOperations>; +} & NotAcceptedFields>) & { + readonly [key: string]: FilterOperators | any; +}; + +/** @public */ +export type PullAllOperator = ({ + readonly [key in KeysOfAType>]?: TSchema[key]; +} & NotAcceptedFields>) & { + readonly [key: string]: ReadonlyArray; +}; + +/** @public */ +export type UpdateFilter = { + $currentDate?: OnlyFieldsOfType< + TSchema, + Date | Timestamp, + true | { $type: 'date' | 'timestamp' } + >; + $inc?: OnlyFieldsOfType; + $min?: MatchKeysAndValues; + $max?: MatchKeysAndValues; + $mul?: OnlyFieldsOfType; + $rename?: Record; + $set?: MatchKeysAndValues; + $setOnInsert?: MatchKeysAndValues; + $unset?: OnlyFieldsOfType; + $addToSet?: SetFields; + $pop?: OnlyFieldsOfType, 1 | -1>; + $pull?: PullOperator; + $push?: PushOperator; + $pullAll?: PullAllOperator; + $bit?: OnlyFieldsOfType< + TSchema, + NumericType | undefined, + { and: IntegerType } | { or: IntegerType } | { xor: IntegerType } + >; +} & Document; + +/** @public */ +export type Nullable = AnyType | null | undefined; + +/** @public */ +export type OneOrMore = T | ReadonlyArray; + +/** @public */ +export type GenericListener = (...args: any[]) => void; + +/** + * Event description type + * @public + */ +export type EventsDescription = Record; + +/** @public */ +export type CommonEvents = 'newListener' | 'removeListener'; + +/** + * Typescript type safe event emitter + * @public + */ +export declare interface TypedEventEmitter extends EventEmitter { + addListener(event: EventKey, listener: Events[EventKey]): this; + addListener( + event: CommonEvents, + listener: (eventName: string | symbol, listener: GenericListener) => void + ): this; + addListener(event: string | symbol, listener: GenericListener): this; + + on(event: EventKey, listener: Events[EventKey]): this; + on( + event: CommonEvents, + listener: (eventName: string | symbol, listener: GenericListener) => void + ): this; + on(event: string | symbol, listener: GenericListener): this; + + once(event: EventKey, listener: Events[EventKey]): this; + once( + event: CommonEvents, + listener: (eventName: string | symbol, listener: GenericListener) => void + ): this; + once(event: string | symbol, listener: GenericListener): this; + + removeListener(event: EventKey, listener: Events[EventKey]): this; + removeListener( + event: CommonEvents, + listener: (eventName: string | symbol, listener: GenericListener) => void + ): this; + removeListener(event: string | symbol, listener: GenericListener): this; + + off(event: EventKey, listener: Events[EventKey]): this; + off( + event: CommonEvents, + listener: (eventName: string | symbol, listener: GenericListener) => void + ): this; + off(event: string | symbol, listener: GenericListener): this; + + removeAllListeners( + event?: EventKey | CommonEvents | symbol | string + ): this; + + listeners( + event: EventKey | CommonEvents | symbol | string + ): Events[EventKey][]; + + rawListeners( + event: EventKey | CommonEvents | symbol | string + ): Events[EventKey][]; + + emit( + event: EventKey | symbol, + ...args: Parameters + ): boolean; + + listenerCount( + type: EventKey | CommonEvents | symbol | string + ): number; + + prependListener(event: EventKey, listener: Events[EventKey]): this; + prependListener( + event: CommonEvents, + listener: (eventName: string | symbol, listener: GenericListener) => void + ): this; + prependListener(event: string | symbol, listener: GenericListener): this; + + prependOnceListener( + event: EventKey, + listener: Events[EventKey] + ): this; + prependOnceListener( + event: CommonEvents, + listener: (eventName: string | symbol, listener: GenericListener) => void + ): this; + prependOnceListener(event: string | symbol, listener: GenericListener): this; + + eventNames(): string[]; + getMaxListeners(): number; + setMaxListeners(n: number): this; +} + +/** + * Typescript type safe event emitter + * @public + */ +// eslint-disable-next-line @typescript-eslint/no-unused-vars +export class TypedEventEmitter extends EventEmitter {} + +/** @public */ +export class CancellationToken extends TypedEventEmitter<{ cancel(): void }> {} + +/** + * Helper types for dot-notation filter attributes + */ + +/** @public */ +export type Join = T extends [] + ? '' + : T extends [string | number] + ? `${T[0]}` + : T extends [string | number, ...infer R] + ? `${T[0]}${D}${Join}` + : string; + +/** @public */ +export type PropertyType = string extends Property + ? unknown + : Property extends keyof Type + ? Type[Property] + : Property extends `${number}` + ? Type extends ReadonlyArray + ? ArrayType + : unknown + : Property extends `${infer Key}.${infer Rest}` + ? Key extends `${number}` + ? Type extends ReadonlyArray + ? PropertyType + : unknown + : Key extends keyof Type + ? Type[Key] extends Map + ? MapType + : PropertyType + : unknown + : unknown; + +/** + * @public + * returns tuple of strings (keys to be joined on '.') that represent every path into a schema + * https://docs.mongodb.com/manual/tutorial/query-embedded-documents/ + */ +export type NestedPaths = Type extends + | string + | number + | boolean + | Date + | RegExp + | Buffer + | Uint8Array + | ((...args: any[]) => any) + | { _bsontype: string } + ? [] + : Type extends ReadonlyArray + ? [] | [number, ...NestedPaths] + : Type extends Map + ? [string] + : Type extends object + ? { + [Key in Extract]: Type[Key] extends Type // type of value extends the parent + ? [Key] + : // for a recursive union type, the child will never extend the parent type. + // but the parent will still extend the child + Type extends Type[Key] + ? [Key] + : Type[Key] extends ReadonlyArray // handling recursive types with arrays + ? Type extends ArrayType // is the type of the parent the same as the type of the array? + ? [Key] // yes, it's a recursive array type + : // for unions, the child type extends the parent + ArrayType extends Type + ? [Key] // we have a recursive array union + : // child is an array, but it's not a recursive array + [Key, ...NestedPaths] + : // child is not structured the same as the parent + [Key, ...NestedPaths]; + }[Extract] + : []; + +/** + * @public + * returns keys (strings) for every path into a schema with a value of type + * https://docs.mongodb.com/manual/tutorial/query-embedded-documents/ + */ +export type NestedPathsOfType = KeysOfAType< + { + [Property in Join, '.'>]: PropertyType; + }, + Type +>; diff --git a/ts-ticket-office-service/node_modules/mongodb/src/operations/add_user.ts b/ts-ticket-office-service/node_modules/mongodb/src/operations/add_user.ts new file mode 100644 index 000000000..3d0c08e79 --- /dev/null +++ b/ts-ticket-office-service/node_modules/mongodb/src/operations/add_user.ts @@ -0,0 +1,118 @@ +import * as crypto from 'crypto'; + +import type { Document } from '../bson'; +import type { Db } from '../db'; +import { MongoInvalidArgumentError } from '../error'; +import type { Server } from '../sdam/server'; +import type { ClientSession } from '../sessions'; +import { Callback, emitWarningOnce, getTopology } from '../utils'; +import { CommandOperation, CommandOperationOptions } from './command'; +import { Aspect, defineAspects } from './operation'; + +/** @public */ +export interface RoleSpecification { + /** + * A role grants privileges to perform sets of actions on defined resources. + * A given role applies to the database on which it is defined and can grant access down to a collection level of granularity. + */ + role: string; + /** The database this user's role should effect. */ + db: string; +} + +/** @public */ +export interface AddUserOptions extends CommandOperationOptions { + /** @deprecated Please use db.command('createUser', ...) instead for this option */ + digestPassword?: null; + /** Roles associated with the created user */ + roles?: string | string[] | RoleSpecification | RoleSpecification[]; + /** Custom data associated with the user (only Mongodb 2.6 or higher) */ + customData?: Document; +} + +/** @internal */ +export class AddUserOperation extends CommandOperation { + override options: AddUserOptions; + db: Db; + username: string; + password?: string; + + constructor(db: Db, username: string, password: string | undefined, options?: AddUserOptions) { + super(db, options); + + this.db = db; + this.username = username; + this.password = password; + this.options = options ?? {}; + } + + override execute( + server: Server, + session: ClientSession | undefined, + callback: Callback + ): void { + const db = this.db; + const username = this.username; + const password = this.password; + const options = this.options; + + // Error out if digestPassword set + if (options.digestPassword != null) { + return callback( + new MongoInvalidArgumentError( + 'Option "digestPassword" not supported via addUser, use db.command(...) instead' + ) + ); + } + + let roles; + if (!options.roles || (Array.isArray(options.roles) && options.roles.length === 0)) { + emitWarningOnce( + 'Creating a user without roles is deprecated. Defaults to "root" if db is "admin" or "dbOwner" otherwise' + ); + if (db.databaseName.toLowerCase() === 'admin') { + roles = ['root']; + } else { + roles = ['dbOwner']; + } + } else { + roles = Array.isArray(options.roles) ? options.roles : [options.roles]; + } + + let topology; + try { + topology = getTopology(db); + } catch (error) { + return callback(error); + } + + const digestPassword = topology.lastHello().maxWireVersion >= 7; + + let userPassword = password; + + if (!digestPassword) { + // Use node md5 generator + const md5 = crypto.createHash('md5'); + // Generate keys used for authentication + md5.update(`${username}:mongo:${password}`); + userPassword = md5.digest('hex'); + } + + // Build the command to execute + const command: Document = { + createUser: username, + customData: options.customData || {}, + roles: roles, + digestPassword + }; + + // No password + if (typeof password === 'string') { + command.pwd = userPassword; + } + + super.executeCommand(server, session, command, callback); + } +} + +defineAspects(AddUserOperation, [Aspect.WRITE_OPERATION]); diff --git a/ts-ticket-office-service/node_modules/mongodb/src/operations/aggregate.ts b/ts-ticket-office-service/node_modules/mongodb/src/operations/aggregate.ts new file mode 100644 index 000000000..1acc6ac62 --- /dev/null +++ b/ts-ticket-office-service/node_modules/mongodb/src/operations/aggregate.ts @@ -0,0 +1,144 @@ +import type { Document } from '../bson'; +import { MongoInvalidArgumentError } from '../error'; +import type { Server } from '../sdam/server'; +import type { ClientSession } from '../sessions'; +import { Callback, maxWireVersion, MongoDBNamespace } from '../utils'; +import { CollationOptions, CommandOperation, CommandOperationOptions } from './command'; +import { Aspect, defineAspects, Hint } from './operation'; + +/** @internal */ +export const DB_AGGREGATE_COLLECTION = 1 as const; +const MIN_WIRE_VERSION_$OUT_READ_CONCERN_SUPPORT = 8 as const; + +/** @public */ +export interface AggregateOptions extends CommandOperationOptions { + /** allowDiskUse lets the server know if it can use disk to store temporary results for the aggregation (requires mongodb 2.6 \>). */ + allowDiskUse?: boolean; + /** The number of documents to return per batch. See [aggregation documentation](https://docs.mongodb.com/manual/reference/command/aggregate). */ + batchSize?: number; + /** Allow driver to bypass schema validation in MongoDB 3.2 or higher. */ + bypassDocumentValidation?: boolean; + /** Return the query as cursor, on 2.6 \> it returns as a real cursor on pre 2.6 it returns as an emulated cursor. */ + cursor?: Document; + /** specifies a cumulative time limit in milliseconds for processing operations on the cursor. MongoDB interrupts the operation at the earliest following interrupt point. */ + maxTimeMS?: number; + /** The maximum amount of time for the server to wait on new documents to satisfy a tailable cursor query. */ + maxAwaitTimeMS?: number; + /** Specify collation. */ + collation?: CollationOptions; + /** Add an index selection hint to an aggregation command */ + hint?: Hint; + /** Map of parameter names and values that can be accessed using $$var (requires MongoDB 5.0). */ + let?: Document; + + out?: string; +} + +/** @internal */ +export class AggregateOperation extends CommandOperation { + override options: AggregateOptions; + target: string | typeof DB_AGGREGATE_COLLECTION; + pipeline: Document[]; + hasWriteStage: boolean; + + constructor(ns: MongoDBNamespace, pipeline: Document[], options?: AggregateOptions) { + super(undefined, { ...options, dbName: ns.db }); + + this.options = options ?? {}; + + // Covers when ns.collection is null, undefined or the empty string, use DB_AGGREGATE_COLLECTION + this.target = ns.collection || DB_AGGREGATE_COLLECTION; + + this.pipeline = pipeline; + + // determine if we have a write stage, override read preference if so + this.hasWriteStage = false; + if (typeof options?.out === 'string') { + this.pipeline = this.pipeline.concat({ $out: options.out }); + this.hasWriteStage = true; + } else if (pipeline.length > 0) { + const finalStage = pipeline[pipeline.length - 1]; + if (finalStage.$out || finalStage.$merge) { + this.hasWriteStage = true; + } + } + + if (this.hasWriteStage) { + this.trySecondaryWrite = true; + } + + if (this.explain && this.writeConcern) { + throw new MongoInvalidArgumentError( + 'Option "explain" cannot be used on an aggregate call with writeConcern' + ); + } + + if (options?.cursor != null && typeof options.cursor !== 'object') { + throw new MongoInvalidArgumentError('Cursor options must be an object'); + } + } + + override get canRetryRead(): boolean { + return !this.hasWriteStage; + } + + addToPipeline(stage: Document): void { + this.pipeline.push(stage); + } + + override execute( + server: Server, + session: ClientSession | undefined, + callback: Callback + ): void { + const options: AggregateOptions = this.options; + const serverWireVersion = maxWireVersion(server); + const command: Document = { aggregate: this.target, pipeline: this.pipeline }; + + if (this.hasWriteStage && serverWireVersion < MIN_WIRE_VERSION_$OUT_READ_CONCERN_SUPPORT) { + this.readConcern = undefined; + } + + if (serverWireVersion >= 5) { + if (this.hasWriteStage && this.writeConcern) { + Object.assign(command, { writeConcern: this.writeConcern }); + } + } + + if (options.bypassDocumentValidation === true) { + command.bypassDocumentValidation = options.bypassDocumentValidation; + } + + if (typeof options.allowDiskUse === 'boolean') { + command.allowDiskUse = options.allowDiskUse; + } + + if (options.hint) { + command.hint = options.hint; + } + + if (options.let) { + command.let = options.let; + } + + // we check for undefined specifically here to allow falsy values + // eslint-disable-next-line no-restricted-syntax + if (options.comment !== undefined) { + command.comment = options.comment; + } + + command.cursor = options.cursor || {}; + if (options.batchSize && !this.hasWriteStage) { + command.cursor.batchSize = options.batchSize; + } + + super.executeCommand(server, session, command, callback); + } +} + +defineAspects(AggregateOperation, [ + Aspect.READ_OPERATION, + Aspect.RETRYABLE, + Aspect.EXPLAINABLE, + Aspect.CURSOR_CREATING +]); diff --git a/ts-ticket-office-service/node_modules/mongodb/src/operations/bulk_write.ts b/ts-ticket-office-service/node_modules/mongodb/src/operations/bulk_write.ts new file mode 100644 index 000000000..627dc709a --- /dev/null +++ b/ts-ticket-office-service/node_modules/mongodb/src/operations/bulk_write.ts @@ -0,0 +1,67 @@ +import type { + AnyBulkWriteOperation, + BulkOperationBase, + BulkWriteOptions, + BulkWriteResult +} from '../bulk/common'; +import type { Collection } from '../collection'; +import type { Server } from '../sdam/server'; +import type { ClientSession } from '../sessions'; +import type { Callback } from '../utils'; +import { AbstractOperation, Aspect, defineAspects } from './operation'; + +/** @internal */ +export class BulkWriteOperation extends AbstractOperation { + override options: BulkWriteOptions; + collection: Collection; + operations: AnyBulkWriteOperation[]; + + constructor( + collection: Collection, + operations: AnyBulkWriteOperation[], + options: BulkWriteOptions + ) { + super(options); + this.options = options; + this.collection = collection; + this.operations = operations; + } + + override execute( + server: Server, + session: ClientSession | undefined, + callback: Callback + ): void { + const coll = this.collection; + const operations = this.operations; + const options = { ...this.options, ...this.bsonOptions, readPreference: this.readPreference }; + + // Create the bulk operation + const bulk: BulkOperationBase = + options.ordered === false + ? coll.initializeUnorderedBulkOp(options) + : coll.initializeOrderedBulkOp(options); + + // for each op go through and add to the bulk + try { + for (let i = 0; i < operations.length; i++) { + bulk.raw(operations[i]); + } + } catch (err) { + return callback(err); + } + + // Execute the bulk + bulk.execute({ ...options, session }, (err, r) => { + // We have connection level error + if (!r && err) { + return callback(err); + } + + // Return the results + callback(undefined, r); + }); + } +} + +defineAspects(BulkWriteOperation, [Aspect.WRITE_OPERATION]); diff --git a/ts-ticket-office-service/node_modules/mongodb/src/operations/collections.ts b/ts-ticket-office-service/node_modules/mongodb/src/operations/collections.ts new file mode 100644 index 000000000..8b314865a --- /dev/null +++ b/ts-ticket-office-service/node_modules/mongodb/src/operations/collections.ts @@ -0,0 +1,48 @@ +import { Collection } from '../collection'; +import type { Db } from '../db'; +import type { Server } from '../sdam/server'; +import type { ClientSession } from '../sessions'; +import type { Callback } from '../utils'; +import { AbstractOperation, OperationOptions } from './operation'; + +export interface CollectionsOptions extends OperationOptions { + nameOnly?: boolean; +} + +/** @internal */ +export class CollectionsOperation extends AbstractOperation { + override options: CollectionsOptions; + db: Db; + + constructor(db: Db, options: CollectionsOptions) { + super(options); + this.options = options; + this.db = db; + } + + override execute( + server: Server, + session: ClientSession | undefined, + callback: Callback + ): void { + const db = this.db; + + // Let's get the collection names + db.listCollections( + {}, + { ...this.options, nameOnly: true, readPreference: this.readPreference, session } + ).toArray((err, documents) => { + if (err || !documents) return callback(err); + // Filter collections removing any illegal ones + documents = documents.filter(doc => doc.name.indexOf('$') === -1); + + // Return the collection objects + callback( + undefined, + documents.map(d => { + return new Collection(db, d.name, db.s.options); + }) + ); + }); + } +} diff --git a/ts-ticket-office-service/node_modules/mongodb/src/operations/command.ts b/ts-ticket-office-service/node_modules/mongodb/src/operations/command.ts new file mode 100644 index 000000000..57186ab42 --- /dev/null +++ b/ts-ticket-office-service/node_modules/mongodb/src/operations/command.ts @@ -0,0 +1,193 @@ +import type { BSONSerializeOptions, Document } from '../bson'; +import { MongoCompatibilityError, MongoInvalidArgumentError } from '../error'; +import { Explain, ExplainOptions } from '../explain'; +import type { Logger } from '../logger'; +import { ReadConcern } from '../read_concern'; +import type { ReadPreference } from '../read_preference'; +import type { Server } from '../sdam/server'; +import { MIN_SECONDARY_WRITE_WIRE_VERSION } from '../sdam/server_selection'; +import type { ClientSession } from '../sessions'; +import { + Callback, + commandSupportsReadConcern, + decorateWithExplain, + maxWireVersion, + MongoDBNamespace +} from '../utils'; +import { WriteConcern, WriteConcernOptions } from '../write_concern'; +import type { ReadConcernLike } from './../read_concern'; +import { AbstractOperation, Aspect, OperationOptions } from './operation'; + +const SUPPORTS_WRITE_CONCERN_AND_COLLATION = 5; + +/** @public */ +export interface CollationOptions { + locale: string; + caseLevel?: boolean; + caseFirst?: string; + strength?: number; + numericOrdering?: boolean; + alternate?: string; + maxVariable?: string; + backwards?: boolean; + normalization?: boolean; +} + +/** @public */ +export interface CommandOperationOptions + extends OperationOptions, + WriteConcernOptions, + ExplainOptions { + /** @deprecated This option does nothing */ + fullResponse?: boolean; + /** Specify a read concern and level for the collection. (only MongoDB 3.2 or higher supported) */ + readConcern?: ReadConcernLike; + /** Collation */ + collation?: CollationOptions; + maxTimeMS?: number; + /** + * Comment to apply to the operation. + * + * In server versions pre-4.4, 'comment' must be string. A server + * error will be thrown if any other type is provided. + * + * In server versions 4.4 and above, 'comment' can be any valid BSON type. + */ + comment?: unknown; + /** Should retry failed writes */ + retryWrites?: boolean; + + // Admin command overrides. + dbName?: string; + authdb?: string; + noResponse?: boolean; +} + +/** @internal */ +export interface OperationParent { + s: { namespace: MongoDBNamespace }; + readConcern?: ReadConcern; + writeConcern?: WriteConcern; + readPreference?: ReadPreference; + logger?: Logger; + bsonOptions?: BSONSerializeOptions; +} + +/** @internal */ +export abstract class CommandOperation extends AbstractOperation { + override options: CommandOperationOptions; + readConcern?: ReadConcern; + writeConcern?: WriteConcern; + explain?: Explain; + logger?: Logger; + + constructor(parent?: OperationParent, options?: CommandOperationOptions) { + super(options); + this.options = options ?? {}; + + // NOTE: this was explicitly added for the add/remove user operations, it's likely + // something we'd want to reconsider. Perhaps those commands can use `Admin` + // as a parent? + const dbNameOverride = options?.dbName || options?.authdb; + if (dbNameOverride) { + this.ns = new MongoDBNamespace(dbNameOverride, '$cmd'); + } else { + this.ns = parent + ? parent.s.namespace.withCollection('$cmd') + : new MongoDBNamespace('admin', '$cmd'); + } + + this.readConcern = ReadConcern.fromOptions(options); + this.writeConcern = WriteConcern.fromOptions(options); + + // TODO(NODE-2056): make logger another "inheritable" property + if (parent && parent.logger) { + this.logger = parent.logger; + } + + if (this.hasAspect(Aspect.EXPLAINABLE)) { + this.explain = Explain.fromOptions(options); + } else if (options?.explain != null) { + throw new MongoInvalidArgumentError(`Option "explain" is not supported on this command`); + } + } + + override get canRetryWrite(): boolean { + if (this.hasAspect(Aspect.EXPLAINABLE)) { + return this.explain == null; + } + return true; + } + + abstract override execute( + server: Server, + session: ClientSession | undefined, + callback: Callback + ): void; + + executeCommand( + server: Server, + session: ClientSession | undefined, + cmd: Document, + callback: Callback + ): void { + // TODO: consider making this a non-enumerable property + this.server = server; + + const options = { + ...this.options, + ...this.bsonOptions, + readPreference: this.readPreference, + session + }; + + const serverWireVersion = maxWireVersion(server); + const inTransaction = this.session && this.session.inTransaction(); + + if (this.readConcern && commandSupportsReadConcern(cmd) && !inTransaction) { + Object.assign(cmd, { readConcern: this.readConcern }); + } + + if (this.trySecondaryWrite && serverWireVersion < MIN_SECONDARY_WRITE_WIRE_VERSION) { + options.omitReadPreference = true; + } + + if (options.collation && serverWireVersion < SUPPORTS_WRITE_CONCERN_AND_COLLATION) { + callback( + new MongoCompatibilityError( + `Server ${server.name}, which reports wire version ${serverWireVersion}, does not support collation` + ) + ); + return; + } + + if (this.writeConcern && this.hasAspect(Aspect.WRITE_OPERATION) && !inTransaction) { + Object.assign(cmd, { writeConcern: this.writeConcern }); + } + + if (serverWireVersion >= SUPPORTS_WRITE_CONCERN_AND_COLLATION) { + if ( + options.collation && + typeof options.collation === 'object' && + !this.hasAspect(Aspect.SKIP_COLLATION) + ) { + Object.assign(cmd, { collation: options.collation }); + } + } + + if (typeof options.maxTimeMS === 'number') { + cmd.maxTimeMS = options.maxTimeMS; + } + + if (this.hasAspect(Aspect.EXPLAINABLE) && this.explain) { + if (serverWireVersion < 6 && cmd.aggregate) { + // Prior to 3.6, with aggregate, verbosity is ignored, and we must pass in "explain: true" + cmd.explain = true; + } else { + cmd = decorateWithExplain(cmd, this.explain); + } + } + + server.command(this.ns, cmd, options, callback); + } +} diff --git a/ts-ticket-office-service/node_modules/mongodb/src/operations/common_functions.ts b/ts-ticket-office-service/node_modules/mongodb/src/operations/common_functions.ts new file mode 100644 index 000000000..a439aca7e --- /dev/null +++ b/ts-ticket-office-service/node_modules/mongodb/src/operations/common_functions.ts @@ -0,0 +1,102 @@ +import type { Document } from '../bson'; +import type { Collection } from '../collection'; +import type { Db } from '../db'; +import { MongoTopologyClosedError } from '../error'; +import type { ReadPreference } from '../read_preference'; +import type { ClientSession } from '../sessions'; +import { Callback, getTopology } from '../utils'; + +/** @public */ +export interface IndexInformationOptions { + full?: boolean; + readPreference?: ReadPreference; + session?: ClientSession; +} +/** + * Retrieves this collections index info. + * + * @param db - The Db instance on which to retrieve the index info. + * @param name - The name of the collection. + */ +export function indexInformation(db: Db, name: string, callback: Callback): void; +export function indexInformation( + db: Db, + name: string, + options: IndexInformationOptions, + callback?: Callback +): void; +export function indexInformation( + db: Db, + name: string, + _optionsOrCallback: IndexInformationOptions | Callback, + _callback?: Callback +): void { + let options = _optionsOrCallback as IndexInformationOptions; + let callback = _callback as Callback; + if ('function' === typeof _optionsOrCallback) { + callback = _optionsOrCallback; + options = {}; + } + // If we specified full information + const full = options.full == null ? false : options.full; + + let topology; + try { + topology = getTopology(db); + } catch (error) { + return callback(error); + } + + // Did the user destroy the topology + if (topology.isDestroyed()) return callback(new MongoTopologyClosedError()); + // Process all the results from the index command and collection + function processResults(indexes: any) { + // Contains all the information + const info: any = {}; + // Process all the indexes + for (let i = 0; i < indexes.length; i++) { + const index = indexes[i]; + // Let's unpack the object + info[index.name] = []; + for (const name in index.key) { + info[index.name].push([name, index.key[name]]); + } + } + + return info; + } + + // Get the list of indexes of the specified collection + db.collection(name) + .listIndexes(options) + .toArray((err, indexes) => { + if (err) return callback(err); + if (!Array.isArray(indexes)) return callback(undefined, []); + if (full) return callback(undefined, indexes); + callback(undefined, processResults(indexes)); + }); +} + +export function prepareDocs( + coll: Collection, + docs: Document[], + options: { forceServerObjectId?: boolean } +): Document[] { + const forceServerObjectId = + typeof options.forceServerObjectId === 'boolean' + ? options.forceServerObjectId + : coll.s.db.options?.forceServerObjectId; + + // no need to modify the docs if server sets the ObjectId + if (forceServerObjectId === true) { + return docs; + } + + return docs.map(doc => { + if (doc._id == null) { + doc._id = coll.s.pkFactory.createPk(); + } + + return doc; + }); +} diff --git a/ts-ticket-office-service/node_modules/mongodb/src/operations/connect.ts b/ts-ticket-office-service/node_modules/mongodb/src/operations/connect.ts new file mode 100644 index 000000000..a71e95867 --- /dev/null +++ b/ts-ticket-office-service/node_modules/mongodb/src/operations/connect.ts @@ -0,0 +1,107 @@ +import { resolveSRVRecord } from '../connection_string'; +import { MONGO_CLIENT_EVENTS } from '../constants'; +import { MongoInvalidArgumentError, MongoRuntimeError } from '../error'; +import type { MongoClient, MongoOptions } from '../mongo_client'; +import { Topology } from '../sdam/topology'; +import type { Callback } from '../utils'; + +export function connect( + mongoClient: MongoClient, + options: MongoOptions, + callback: Callback +): void { + if (!callback) { + throw new MongoInvalidArgumentError('Callback function must be provided'); + } + + // If a connection already been established, we can terminate early + if (mongoClient.topology && mongoClient.topology.isConnected()) { + return callback(undefined, mongoClient); + } + + const logger = mongoClient.logger; + const connectCallback: Callback = err => { + const warningMessage = + 'seed list contains no mongos proxies, replicaset connections requires ' + + 'the parameter replicaSet to be supplied in the URI or options object, ' + + 'mongodb://server:port/db?replicaSet=name'; + if (err && err.message === 'no mongos proxies found in seed list') { + if (logger.isWarn()) { + logger.warn(warningMessage); + } + + // Return a more specific error message for MongoClient.connect + // TODO(NODE-3483) + return callback(new MongoRuntimeError(warningMessage)); + } + + callback(err, mongoClient); + }; + + if (typeof options.srvHost === 'string') { + return resolveSRVRecord(options, (err, hosts) => { + if (err || !hosts) return callback(err); + for (const [index, host] of hosts.entries()) { + options.hosts[index] = host; + } + + return createTopology(mongoClient, options, connectCallback); + }); + } + + return createTopology(mongoClient, options, connectCallback); +} + +function createTopology( + mongoClient: MongoClient, + options: MongoOptions, + callback: Callback +) { + // Create the topology + const topology = new Topology(options.hosts, options); + // Events can be emitted before initialization is complete so we have to + // save the reference to the topology on the client ASAP if the event handlers need to access it + mongoClient.topology = topology; + topology.client = mongoClient; + + topology.once(Topology.OPEN, () => mongoClient.emit('open', mongoClient)); + + for (const event of MONGO_CLIENT_EVENTS) { + topology.on(event, (...args: any[]) => mongoClient.emit(event, ...(args as any))); + } + + // initialize CSFLE if requested + if (mongoClient.autoEncrypter) { + mongoClient.autoEncrypter.init(err => { + if (err) { + return callback(err); + } + + topology.connect(options, err => { + if (err) { + topology.close({ force: true }); + return callback(err); + } + + options.encrypter.connectInternalClient(error => { + if (error) return callback(error); + + callback(undefined, topology); + }); + }); + }); + + return; + } + + // otherwise connect normally + topology.connect(options, err => { + if (err) { + topology.close({ force: true }); + return callback(err); + } + + callback(undefined, topology); + return; + }); +} diff --git a/ts-ticket-office-service/node_modules/mongodb/src/operations/count.ts b/ts-ticket-office-service/node_modules/mongodb/src/operations/count.ts new file mode 100644 index 000000000..8d94b84ea --- /dev/null +++ b/ts-ticket-office-service/node_modules/mongodb/src/operations/count.ts @@ -0,0 +1,68 @@ +import type { Document } from '../bson'; +import type { Collection } from '../collection'; +import type { Server } from '../sdam/server'; +import type { ClientSession } from '../sessions'; +import type { Callback, MongoDBNamespace } from '../utils'; +import { CommandOperation, CommandOperationOptions } from './command'; +import { Aspect, defineAspects } from './operation'; + +/** @public */ +export interface CountOptions extends CommandOperationOptions { + /** The number of documents to skip. */ + skip?: number; + /** The maximum amounts to count before aborting. */ + limit?: number; + /** Number of milliseconds to wait before aborting the query. */ + maxTimeMS?: number; + /** An index name hint for the query. */ + hint?: string | Document; +} + +/** @internal */ +export class CountOperation extends CommandOperation { + override options: CountOptions; + collectionName?: string; + query: Document; + + constructor(namespace: MongoDBNamespace, filter: Document, options: CountOptions) { + super({ s: { namespace: namespace } } as unknown as Collection, options); + + this.options = options; + this.collectionName = namespace.collection; + this.query = filter; + } + + override execute( + server: Server, + session: ClientSession | undefined, + callback: Callback + ): void { + const options = this.options; + const cmd: Document = { + count: this.collectionName, + query: this.query + }; + + if (typeof options.limit === 'number') { + cmd.limit = options.limit; + } + + if (typeof options.skip === 'number') { + cmd.skip = options.skip; + } + + if (options.hint != null) { + cmd.hint = options.hint; + } + + if (typeof options.maxTimeMS === 'number') { + cmd.maxTimeMS = options.maxTimeMS; + } + + super.executeCommand(server, session, cmd, (err, result) => { + callback(err, result ? result.n : 0); + }); + } +} + +defineAspects(CountOperation, [Aspect.READ_OPERATION, Aspect.RETRYABLE]); diff --git a/ts-ticket-office-service/node_modules/mongodb/src/operations/count_documents.ts b/ts-ticket-office-service/node_modules/mongodb/src/operations/count_documents.ts new file mode 100644 index 000000000..c781329f2 --- /dev/null +++ b/ts-ticket-office-service/node_modules/mongodb/src/operations/count_documents.ts @@ -0,0 +1,57 @@ +import type { Document } from '../bson'; +import type { Collection } from '../collection'; +import type { Server } from '../sdam/server'; +import type { ClientSession } from '../sessions'; +import type { Callback } from '../utils'; +import { AggregateOperation, AggregateOptions } from './aggregate'; + +/** @public */ +export interface CountDocumentsOptions extends AggregateOptions { + /** The number of documents to skip. */ + skip?: number; + /** The maximum amounts to count before aborting. */ + limit?: number; +} + +/** @internal */ +export class CountDocumentsOperation extends AggregateOperation { + constructor(collection: Collection, query: Document, options: CountDocumentsOptions) { + const pipeline = []; + pipeline.push({ $match: query }); + + if (typeof options.skip === 'number') { + pipeline.push({ $skip: options.skip }); + } + + if (typeof options.limit === 'number') { + pipeline.push({ $limit: options.limit }); + } + + pipeline.push({ $group: { _id: 1, n: { $sum: 1 } } }); + + super(collection.s.namespace, pipeline, options); + } + + override execute( + server: Server, + session: ClientSession | undefined, + callback: Callback + ): void { + super.execute(server, session, (err, result) => { + if (err || !result) { + callback(err); + return; + } + + // NOTE: We're avoiding creating a cursor here to reduce the callstack. + const response = result as unknown as Document; + if (response.cursor == null || response.cursor.firstBatch == null) { + callback(undefined, 0); + return; + } + + const docs = response.cursor.firstBatch; + callback(undefined, docs.length ? docs[0].n : 0); + }); + } +} diff --git a/ts-ticket-office-service/node_modules/mongodb/src/operations/create_collection.ts b/ts-ticket-office-service/node_modules/mongodb/src/operations/create_collection.ts new file mode 100644 index 000000000..c3f094437 --- /dev/null +++ b/ts-ticket-office-service/node_modules/mongodb/src/operations/create_collection.ts @@ -0,0 +1,201 @@ +import type { Document } from '../bson'; +import { Collection } from '../collection'; +import type { Db } from '../db'; +import type { PkFactory } from '../mongo_client'; +import type { Server } from '../sdam/server'; +import type { ClientSession } from '../sessions'; +import type { Callback } from '../utils'; +import { CommandOperation, CommandOperationOptions } from './command'; +import { CreateIndexOperation } from './indexes'; +import { Aspect, defineAspects } from './operation'; + +const ILLEGAL_COMMAND_FIELDS = new Set([ + 'w', + 'wtimeout', + 'j', + 'fsync', + 'autoIndexId', + 'pkFactory', + 'raw', + 'readPreference', + 'session', + 'readConcern', + 'writeConcern', + 'raw', + 'fieldsAsRaw', + 'promoteLongs', + 'promoteValues', + 'promoteBuffers', + 'bsonRegExp', + 'serializeFunctions', + 'ignoreUndefined', + 'enableUtf8Validation' +]); + +/** @public + * Configuration options for timeseries collections + * @see https://docs.mongodb.com/manual/core/timeseries-collections/ + */ +export interface TimeSeriesCollectionOptions extends Document { + timeField: string; + metaField?: string; + granularity?: 'seconds' | 'minutes' | 'hours' | string; +} + +/** @public + * Configuration options for clustered collections + * TODO: NODE-4230 replace with normal manual link once it is on there. + * @see https://www.mongodb.com/docs/v5.3/core/clustered-collections/ + */ +export interface ClusteredCollectionOptions extends Document { + name?: string; + key: Document; + unique: boolean; +} + +/** @public */ +export interface CreateCollectionOptions extends CommandOperationOptions { + /** Returns an error if the collection does not exist */ + strict?: boolean; + /** Create a capped collection */ + capped?: boolean; + /** @deprecated Create an index on the _id field of the document, True by default on MongoDB 2.6 - 3.0 */ + autoIndexId?: boolean; + /** The size of the capped collection in bytes */ + size?: number; + /** The maximum number of documents in the capped collection */ + max?: number; + /** Available for the MMAPv1 storage engine only to set the usePowerOf2Sizes and the noPadding flag */ + flags?: number; + /** Allows users to specify configuration to the storage engine on a per-collection basis when creating a collection on MongoDB 3.0 or higher */ + storageEngine?: Document; + /** Allows users to specify validation rules or expressions for the collection. For more information, see Document Validation on MongoDB 3.2 or higher */ + validator?: Document; + /** Determines how strictly MongoDB applies the validation rules to existing documents during an update on MongoDB 3.2 or higher */ + validationLevel?: string; + /** Determines whether to error on invalid documents or just warn about the violations but allow invalid documents to be inserted on MongoDB 3.2 or higher */ + validationAction?: string; + /** Allows users to specify a default configuration for indexes when creating a collection on MongoDB 3.2 or higher */ + indexOptionDefaults?: Document; + /** The name of the source collection or view from which to create the view. The name is not the full namespace of the collection or view; i.e. does not include the database name and implies the same database as the view to create on MongoDB 3.4 or higher */ + viewOn?: string; + /** An array that consists of the aggregation pipeline stage. Creates the view by applying the specified pipeline to the viewOn collection or view on MongoDB 3.4 or higher */ + pipeline?: Document[]; + /** A primary key factory function for generation of custom _id keys. */ + pkFactory?: PkFactory; + /** A document specifying configuration options for timeseries collections. */ + timeseries?: TimeSeriesCollectionOptions; + /** A document specifying configuration options for clustered collections. For MongoDB 5.3 and above. */ + clusteredIndex?: ClusteredCollectionOptions; + /** The number of seconds after which a document in a timeseries or clustered collection expires. */ + expireAfterSeconds?: number; + /** @experimental */ + encryptedFields?: Document; + /** + * If set, enables pre-update and post-update document events to be included for any + * change streams that listen on this collection. + */ + changeStreamPreAndPostImages?: { enabled: boolean }; +} + +/** @internal */ +export class CreateCollectionOperation extends CommandOperation { + override options: CreateCollectionOptions; + db: Db; + name: string; + + constructor(db: Db, name: string, options: CreateCollectionOptions = {}) { + super(db, options); + + this.options = options; + this.db = db; + this.name = name; + } + + override execute( + server: Server, + session: ClientSession | undefined, + callback: Callback + ): void { + (async () => { + const db = this.db; + const name = this.name; + const options = this.options; + + const encryptedFields: Document | undefined = + options.encryptedFields ?? + db.s.client.options.autoEncryption?.encryptedFieldsMap?.[`${db.databaseName}.${name}`]; + + if (encryptedFields) { + // Create auxilliary collections for queryable encryption support. + const escCollection = encryptedFields.escCollection ?? `enxcol_.${name}.esc`; + const eccCollection = encryptedFields.eccCollection ?? `enxcol_.${name}.ecc`; + const ecocCollection = encryptedFields.ecocCollection ?? `enxcol_.${name}.ecoc`; + + for (const collectionName of [escCollection, eccCollection, ecocCollection]) { + const createOp = new CreateCollectionOperation(db, collectionName, { + clusteredIndex: { + key: { _id: 1 }, + unique: true + } + }); + await createOp.executeWithoutEncryptedFieldsCheck(server, session); + } + + if (!options.encryptedFields) { + this.options = { ...this.options, encryptedFields }; + } + } + + const coll = await this.executeWithoutEncryptedFieldsCheck(server, session); + + if (encryptedFields) { + // Create the required index for queryable encryption support. + const createIndexOp = new CreateIndexOperation(db, name, { __safeContent__: 1 }, {}); + await new Promise((resolve, reject) => { + createIndexOp.execute(server, session, err => (err ? reject(err) : resolve())); + }); + } + + return coll; + })().then( + coll => callback(undefined, coll), + err => callback(err) + ); + } + + private executeWithoutEncryptedFieldsCheck( + server: Server, + session: ClientSession | undefined + ): Promise { + return new Promise((resolve, reject) => { + const db = this.db; + const name = this.name; + const options = this.options; + + const done: Callback = err => { + if (err) { + return reject(err); + } + + resolve(new Collection(db, name, options)); + }; + + const cmd: Document = { create: name }; + for (const n in options) { + if ( + (options as any)[n] != null && + typeof (options as any)[n] !== 'function' && + !ILLEGAL_COMMAND_FIELDS.has(n) + ) { + cmd[n] = (options as any)[n]; + } + } + + // otherwise just execute the command + super.executeCommand(server, session, cmd, done); + }); + } +} + +defineAspects(CreateCollectionOperation, [Aspect.WRITE_OPERATION]); diff --git a/ts-ticket-office-service/node_modules/mongodb/src/operations/delete.ts b/ts-ticket-office-service/node_modules/mongodb/src/operations/delete.ts new file mode 100644 index 000000000..ccdfd1c80 --- /dev/null +++ b/ts-ticket-office-service/node_modules/mongodb/src/operations/delete.ts @@ -0,0 +1,194 @@ +import type { Document } from '../bson'; +import type { Collection } from '../collection'; +import { MongoCompatibilityError, MongoServerError } from '../error'; +import type { Server } from '../sdam/server'; +import type { ClientSession } from '../sessions'; +import { Callback, collationNotSupported, maxWireVersion, MongoDBNamespace } from '../utils'; +import type { WriteConcernOptions } from '../write_concern'; +import { CollationOptions, CommandOperation, CommandOperationOptions } from './command'; +import { Aspect, defineAspects, Hint } from './operation'; + +/** @public */ +export interface DeleteOptions extends CommandOperationOptions, WriteConcernOptions { + /** If true, when an insert fails, don't execute the remaining writes. If false, continue with remaining inserts when one fails. */ + ordered?: boolean; + /** Specifies the collation to use for the operation */ + collation?: CollationOptions; + /** Specify that the update query should only consider plans using the hinted index */ + hint?: string | Document; + /** Map of parameter names and values that can be accessed using $$var (requires MongoDB 5.0). */ + let?: Document; + + /** @deprecated use `removeOne` or `removeMany` to implicitly specify the limit */ + single?: boolean; +} + +/** @public */ +export interface DeleteResult { + /** Indicates whether this write result was acknowledged. If not, then all other members of this result will be undefined. */ + acknowledged: boolean; + /** The number of documents that were deleted */ + deletedCount: number; +} + +/** @public */ +export interface DeleteStatement { + /** The query that matches documents to delete. */ + q: Document; + /** The number of matching documents to delete. */ + limit: number; + /** Specifies the collation to use for the operation. */ + collation?: CollationOptions; + /** A document or string that specifies the index to use to support the query predicate. */ + hint?: Hint; +} + +/** @internal */ +export class DeleteOperation extends CommandOperation { + override options: DeleteOptions; + statements: DeleteStatement[]; + + constructor(ns: MongoDBNamespace, statements: DeleteStatement[], options: DeleteOptions) { + super(undefined, options); + this.options = options; + this.ns = ns; + this.statements = statements; + } + + override get canRetryWrite(): boolean { + if (super.canRetryWrite === false) { + return false; + } + + return this.statements.every(op => (op.limit != null ? op.limit > 0 : true)); + } + + override execute(server: Server, session: ClientSession | undefined, callback: Callback): void { + const options = this.options ?? {}; + const ordered = typeof options.ordered === 'boolean' ? options.ordered : true; + const command: Document = { + delete: this.ns.collection, + deletes: this.statements, + ordered + }; + + if (options.let) { + command.let = options.let; + } + + // we check for undefined specifically here to allow falsy values + // eslint-disable-next-line no-restricted-syntax + if (options.comment !== undefined) { + command.comment = options.comment; + } + + if (options.explain != null && maxWireVersion(server) < 3) { + return callback + ? callback( + new MongoCompatibilityError(`Server ${server.name} does not support explain on delete`) + ) + : undefined; + } + + const unacknowledgedWrite = this.writeConcern && this.writeConcern.w === 0; + if (unacknowledgedWrite || maxWireVersion(server) < 5) { + if (this.statements.find((o: Document) => o.hint)) { + callback(new MongoCompatibilityError(`Servers < 3.4 do not support hint on delete`)); + return; + } + } + + const statementWithCollation = this.statements.find(statement => !!statement.collation); + if (statementWithCollation && collationNotSupported(server, statementWithCollation)) { + callback(new MongoCompatibilityError(`Server ${server.name} does not support collation`)); + return; + } + + super.executeCommand(server, session, command, callback); + } +} + +export class DeleteOneOperation extends DeleteOperation { + constructor(collection: Collection, filter: Document, options: DeleteOptions) { + super(collection.s.namespace, [makeDeleteStatement(filter, { ...options, limit: 1 })], options); + } + + override execute( + server: Server, + session: ClientSession | undefined, + callback: Callback + ): void { + super.execute(server, session, (err, res) => { + if (err || res == null) return callback(err); + if (res.code) return callback(new MongoServerError(res)); + if (res.writeErrors) return callback(new MongoServerError(res.writeErrors[0])); + if (this.explain) return callback(undefined, res); + + callback(undefined, { + acknowledged: this.writeConcern?.w !== 0 ?? true, + deletedCount: res.n + }); + }); + } +} + +export class DeleteManyOperation extends DeleteOperation { + constructor(collection: Collection, filter: Document, options: DeleteOptions) { + super(collection.s.namespace, [makeDeleteStatement(filter, options)], options); + } + + override execute( + server: Server, + session: ClientSession | undefined, + callback: Callback + ): void { + super.execute(server, session, (err, res) => { + if (err || res == null) return callback(err); + if (res.code) return callback(new MongoServerError(res)); + if (res.writeErrors) return callback(new MongoServerError(res.writeErrors[0])); + if (this.explain) return callback(undefined, res); + + callback(undefined, { + acknowledged: this.writeConcern?.w !== 0 ?? true, + deletedCount: res.n + }); + }); + } +} + +export function makeDeleteStatement( + filter: Document, + options: DeleteOptions & { limit?: number } +): DeleteStatement { + const op: DeleteStatement = { + q: filter, + limit: typeof options.limit === 'number' ? options.limit : 0 + }; + + if (options.single === true) { + op.limit = 1; + } + + if (options.collation) { + op.collation = options.collation; + } + + if (options.hint) { + op.hint = options.hint; + } + + return op; +} + +defineAspects(DeleteOperation, [Aspect.RETRYABLE, Aspect.WRITE_OPERATION]); +defineAspects(DeleteOneOperation, [ + Aspect.RETRYABLE, + Aspect.WRITE_OPERATION, + Aspect.EXPLAINABLE, + Aspect.SKIP_COLLATION +]); +defineAspects(DeleteManyOperation, [ + Aspect.WRITE_OPERATION, + Aspect.EXPLAINABLE, + Aspect.SKIP_COLLATION +]); diff --git a/ts-ticket-office-service/node_modules/mongodb/src/operations/distinct.ts b/ts-ticket-office-service/node_modules/mongodb/src/operations/distinct.ts new file mode 100644 index 000000000..d006d3113 --- /dev/null +++ b/ts-ticket-office-service/node_modules/mongodb/src/operations/distinct.ts @@ -0,0 +1,92 @@ +import type { Document } from '../bson'; +import type { Collection } from '../collection'; +import { MongoCompatibilityError } from '../error'; +import type { Server } from '../sdam/server'; +import type { ClientSession } from '../sessions'; +import { Callback, decorateWithCollation, decorateWithReadConcern, maxWireVersion } from '../utils'; +import { CommandOperation, CommandOperationOptions } from './command'; +import { Aspect, defineAspects } from './operation'; + +/** @public */ +export type DistinctOptions = CommandOperationOptions; + +/** + * Return a list of distinct values for the given key across a collection. + * @internal + */ +export class DistinctOperation extends CommandOperation { + override options: DistinctOptions; + collection: Collection; + /** Field of the document to find distinct values for. */ + key: string; + /** The query for filtering the set of documents to which we apply the distinct filter. */ + query: Document; + + /** + * Construct a Distinct operation. + * + * @param collection - Collection instance. + * @param key - Field of the document to find distinct values for. + * @param query - The query for filtering the set of documents to which we apply the distinct filter. + * @param options - Optional settings. See Collection.prototype.distinct for a list of options. + */ + constructor(collection: Collection, key: string, query: Document, options?: DistinctOptions) { + super(collection, options); + + this.options = options ?? {}; + this.collection = collection; + this.key = key; + this.query = query; + } + + override execute( + server: Server, + session: ClientSession | undefined, + callback: Callback + ): void { + const coll = this.collection; + const key = this.key; + const query = this.query; + const options = this.options; + + // Distinct command + const cmd: Document = { + distinct: coll.collectionName, + key: key, + query: query + }; + + // Add maxTimeMS if defined + if (typeof options.maxTimeMS === 'number') { + cmd.maxTimeMS = options.maxTimeMS; + } + + // Do we have a readConcern specified + decorateWithReadConcern(cmd, coll, options); + + // Have we specified collation + try { + decorateWithCollation(cmd, coll, options); + } catch (err) { + return callback(err); + } + + if (this.explain && maxWireVersion(server) < 4) { + callback( + new MongoCompatibilityError(`Server ${server.name} does not support explain on distinct`) + ); + return; + } + + super.executeCommand(server, session, cmd, (err, result) => { + if (err) { + callback(err); + return; + } + + callback(undefined, this.explain ? result : result.values); + }); + } +} + +defineAspects(DistinctOperation, [Aspect.READ_OPERATION, Aspect.RETRYABLE, Aspect.EXPLAINABLE]); diff --git a/ts-ticket-office-service/node_modules/mongodb/src/operations/drop.ts b/ts-ticket-office-service/node_modules/mongodb/src/operations/drop.ts new file mode 100644 index 000000000..00f78e543 --- /dev/null +++ b/ts-ticket-office-service/node_modules/mongodb/src/operations/drop.ts @@ -0,0 +1,120 @@ +import type { Document } from '../bson'; +import type { Db } from '../db'; +import { MONGODB_ERROR_CODES, MongoServerError } from '../error'; +import type { Server } from '../sdam/server'; +import type { ClientSession } from '../sessions'; +import type { Callback } from '../utils'; +import { CommandOperation, CommandOperationOptions } from './command'; +import { Aspect, defineAspects } from './operation'; + +/** @public */ +export interface DropCollectionOptions extends CommandOperationOptions { + /** @experimental */ + encryptedFields?: Document; +} + +/** @internal */ +export class DropCollectionOperation extends CommandOperation { + override options: DropCollectionOptions; + db: Db; + name: string; + + constructor(db: Db, name: string, options: DropCollectionOptions = {}) { + super(db, options); + this.db = db; + this.options = options; + this.name = name; + } + + override execute( + server: Server, + session: ClientSession | undefined, + callback: Callback + ): void { + (async () => { + const db = this.db; + const options = this.options; + const name = this.name; + + const encryptedFieldsMap = db.s.client.options.autoEncryption?.encryptedFieldsMap; + let encryptedFields: Document | undefined = + options.encryptedFields ?? encryptedFieldsMap?.[`${db.databaseName}.${name}`]; + + if (!encryptedFields && encryptedFieldsMap) { + // If the MongoClient was configued with an encryptedFieldsMap, + // and no encryptedFields config was available in it or explicitly + // passed as an argument, the spec tells us to look one up using + // listCollections(). + const listCollectionsResult = await db + .listCollections({ name }, { nameOnly: false }) + .toArray(); + encryptedFields = listCollectionsResult?.[0]?.options?.encryptedFields; + } + + if (encryptedFields) { + const escCollection = encryptedFields.escCollection || `enxcol_.${name}.esc`; + const eccCollection = encryptedFields.eccCollection || `enxcol_.${name}.ecc`; + const ecocCollection = encryptedFields.ecocCollection || `enxcol_.${name}.ecoc`; + + for (const collectionName of [escCollection, eccCollection, ecocCollection]) { + // Drop auxilliary collections, ignoring potential NamespaceNotFound errors. + const dropOp = new DropCollectionOperation(db, collectionName); + try { + await dropOp.executeWithoutEncryptedFieldsCheck(server, session); + } catch (err) { + if ( + !(err instanceof MongoServerError) || + err.code !== MONGODB_ERROR_CODES.NamespaceNotFound + ) { + throw err; + } + } + } + } + + return await this.executeWithoutEncryptedFieldsCheck(server, session); + })().then( + result => callback(undefined, result), + err => callback(err) + ); + } + + private executeWithoutEncryptedFieldsCheck( + server: Server, + session: ClientSession | undefined + ): Promise { + return new Promise((resolve, reject) => { + super.executeCommand(server, session, { drop: this.name }, (err, result) => { + if (err) return reject(err); + resolve(!!result.ok); + }); + }); + } +} + +/** @public */ +export type DropDatabaseOptions = CommandOperationOptions; + +/** @internal */ +export class DropDatabaseOperation extends CommandOperation { + override options: DropDatabaseOptions; + + constructor(db: Db, options: DropDatabaseOptions) { + super(db, options); + this.options = options; + } + override execute( + server: Server, + session: ClientSession | undefined, + callback: Callback + ): void { + super.executeCommand(server, session, { dropDatabase: 1 }, (err, result) => { + if (err) return callback(err); + if (result.ok) return callback(undefined, true); + callback(undefined, false); + }); + } +} + +defineAspects(DropCollectionOperation, [Aspect.WRITE_OPERATION]); +defineAspects(DropDatabaseOperation, [Aspect.WRITE_OPERATION]); diff --git a/ts-ticket-office-service/node_modules/mongodb/src/operations/estimated_document_count.ts b/ts-ticket-office-service/node_modules/mongodb/src/operations/estimated_document_count.ts new file mode 100644 index 000000000..22b29deb9 --- /dev/null +++ b/ts-ticket-office-service/node_modules/mongodb/src/operations/estimated_document_count.ts @@ -0,0 +1,62 @@ +import type { Document } from '../bson'; +import type { Collection } from '../collection'; +import type { Server } from '../sdam/server'; +import type { ClientSession } from '../sessions'; +import type { Callback } from '../utils'; +import { CommandOperation, CommandOperationOptions } from './command'; +import { Aspect, defineAspects } from './operation'; + +/** @public */ +export interface EstimatedDocumentCountOptions extends CommandOperationOptions { + /** + * The maximum amount of time to allow the operation to run. + * + * This option is sent only if the caller explicitly provides a value. The default is to not send a value. + */ + maxTimeMS?: number; +} + +/** @internal */ +export class EstimatedDocumentCountOperation extends CommandOperation { + override options: EstimatedDocumentCountOptions; + collectionName: string; + + constructor(collection: Collection, options: EstimatedDocumentCountOptions = {}) { + super(collection, options); + this.options = options; + this.collectionName = collection.collectionName; + } + + override execute( + server: Server, + session: ClientSession | undefined, + callback: Callback + ): void { + const cmd: Document = { count: this.collectionName }; + + if (typeof this.options.maxTimeMS === 'number') { + cmd.maxTimeMS = this.options.maxTimeMS; + } + + // we check for undefined specifically here to allow falsy values + // eslint-disable-next-line no-restricted-syntax + if (this.options.comment !== undefined) { + cmd.comment = this.options.comment; + } + + super.executeCommand(server, session, cmd, (err, response) => { + if (err) { + callback(err); + return; + } + + callback(undefined, response?.n || 0); + }); + } +} + +defineAspects(EstimatedDocumentCountOperation, [ + Aspect.READ_OPERATION, + Aspect.RETRYABLE, + Aspect.CURSOR_CREATING +]); diff --git a/ts-ticket-office-service/node_modules/mongodb/src/operations/eval.ts b/ts-ticket-office-service/node_modules/mongodb/src/operations/eval.ts new file mode 100644 index 000000000..3c34c59d9 --- /dev/null +++ b/ts-ticket-office-service/node_modules/mongodb/src/operations/eval.ts @@ -0,0 +1,82 @@ +import { Code, Document } from '../bson'; +import type { Collection } from '../collection'; +import type { Db } from '../db'; +import { MongoServerError } from '../error'; +import { ReadPreference } from '../read_preference'; +import type { Server } from '../sdam/server'; +import type { ClientSession } from '../sessions'; +import type { Callback } from '../utils'; +import { CommandOperation, CommandOperationOptions } from './command'; + +/** @public */ +export interface EvalOptions extends CommandOperationOptions { + nolock?: boolean; +} + +/** @internal */ +export class EvalOperation extends CommandOperation { + override options: EvalOptions; + code: Code; + parameters?: Document | Document[]; + + constructor( + db: Db | Collection, + code: Code, + parameters?: Document | Document[], + options?: EvalOptions + ) { + super(db, options); + + this.options = options ?? {}; + this.code = code; + this.parameters = parameters; + // force primary read preference + Object.defineProperty(this, 'readPreference', { + value: ReadPreference.primary, + configurable: false, + writable: false + }); + } + + override execute( + server: Server, + session: ClientSession | undefined, + callback: Callback + ): void { + let finalCode = this.code; + let finalParameters: Document[] = []; + + // If not a code object translate to one + if (!(finalCode && (finalCode as unknown as { _bsontype: string })._bsontype === 'Code')) { + finalCode = new Code(finalCode as never); + } + + // Ensure the parameters are correct + if (this.parameters != null && typeof this.parameters !== 'function') { + finalParameters = Array.isArray(this.parameters) ? this.parameters : [this.parameters]; + } + + // Create execution selector + const cmd: Document = { $eval: finalCode, args: finalParameters }; + + // Check if the nolock parameter is passed in + if (this.options.nolock) { + cmd.nolock = this.options.nolock; + } + + // Execute the command + super.executeCommand(server, session, cmd, (err, result) => { + if (err) return callback(err); + if (result && result.ok === 1) { + return callback(undefined, result.retval); + } + + if (result) { + callback(new MongoServerError({ message: `eval failed: ${result.errmsg}` })); + return; + } + + callback(err, result); + }); + } +} diff --git a/ts-ticket-office-service/node_modules/mongodb/src/operations/execute_operation.ts b/ts-ticket-office-service/node_modules/mongodb/src/operations/execute_operation.ts new file mode 100644 index 000000000..54fc3b99d --- /dev/null +++ b/ts-ticket-office-service/node_modules/mongodb/src/operations/execute_operation.ts @@ -0,0 +1,298 @@ +import type { Document } from '../bson'; +import { + isRetryableReadError, + isRetryableWriteError, + MongoCompatibilityError, + MONGODB_ERROR_CODES, + MongoError, + MongoExpiredSessionError, + MongoNetworkError, + MongoNotConnectedError, + MongoRuntimeError, + MongoServerError, + MongoTransactionError, + MongoUnexpectedServerResponseError +} from '../error'; +import type { MongoClient } from '../mongo_client'; +import { ReadPreference } from '../read_preference'; +import type { Server } from '../sdam/server'; +import { + sameServerSelector, + secondaryWritableServerSelector, + ServerSelector +} from '../sdam/server_selection'; +import type { Topology } from '../sdam/topology'; +import type { ClientSession } from '../sessions'; +import { Callback, maybePromise, supportsRetryableWrites } from '../utils'; +import { AbstractOperation, Aspect } from './operation'; + +const MMAPv1_RETRY_WRITES_ERROR_CODE = MONGODB_ERROR_CODES.IllegalOperation; +const MMAPv1_RETRY_WRITES_ERROR_MESSAGE = + 'This MongoDB deployment does not support retryable writes. Please add retryWrites=false to your connection string.'; + +type ResultTypeFromOperation = TOperation extends AbstractOperation + ? K + : never; + +/** @internal */ +export interface ExecutionResult { + /** The server selected for the operation */ + server: Server; + /** The session used for this operation, may be implicitly created */ + session?: ClientSession; + /** The raw server response for the operation */ + response: Document; +} + +/** + * Executes the given operation with provided arguments. + * @internal + * + * @remarks + * This method reduces large amounts of duplication in the entire codebase by providing + * a single point for determining whether callbacks or promises should be used. Additionally + * it allows for a single point of entry to provide features such as implicit sessions, which + * are required by the Driver Sessions specification in the event that a ClientSession is + * not provided + * + * @param topology - The topology to execute this operation on + * @param operation - The operation to execute + * @param callback - The command result callback + */ +export function executeOperation< + T extends AbstractOperation, + TResult = ResultTypeFromOperation +>(client: MongoClient, operation: T): Promise; +export function executeOperation< + T extends AbstractOperation, + TResult = ResultTypeFromOperation +>(client: MongoClient, operation: T, callback: Callback): void; +export function executeOperation< + T extends AbstractOperation, + TResult = ResultTypeFromOperation +>(client: MongoClient, operation: T, callback?: Callback): Promise | void; +export function executeOperation< + T extends AbstractOperation, + TResult = ResultTypeFromOperation +>(client: MongoClient, operation: T, callback?: Callback): Promise | void { + if (!(operation instanceof AbstractOperation)) { + // TODO(NODE-3483): Extend MongoRuntimeError + throw new MongoRuntimeError('This method requires a valid operation instance'); + } + + return maybePromise(callback, callback => { + const topology = client.topology; + + if (topology == null) { + if (client.s.hasBeenClosed) { + return callback( + new MongoNotConnectedError('Client must be connected before running operations') + ); + } + client.s.options[Symbol.for('@@mdb.skipPingOnConnect')] = true; + return client.connect(error => { + delete client.s.options[Symbol.for('@@mdb.skipPingOnConnect')]; + if (error) { + return callback(error); + } + return executeOperation(client, operation, callback); + }); + } + + if (topology.shouldCheckForSessionSupport()) { + return topology.selectServer(ReadPreference.primaryPreferred, {}, err => { + if (err) return callback(err); + + executeOperation(client, operation, callback); + }); + } + + // The driver sessions spec mandates that we implicitly create sessions for operations + // that are not explicitly provided with a session. + let session = operation.session; + let owner: symbol | undefined; + if (topology.hasSessionSupport()) { + if (session == null) { + owner = Symbol(); + session = client.startSession({ owner, explicit: false }); + } else if (session.hasEnded) { + return callback(new MongoExpiredSessionError('Use of expired sessions is not permitted')); + } else if (session.snapshotEnabled && !topology.capabilities.supportsSnapshotReads) { + return callback(new MongoCompatibilityError('Snapshot reads require MongoDB 5.0 or later')); + } + } else { + // no session support + if (session && session.explicit) { + // If the user passed an explicit session and we are still, after server selection, + // trying to run against a topology that doesn't support sessions we error out. + return callback(new MongoCompatibilityError('Current topology does not support sessions')); + } else if (session && !session.explicit) { + // We do not have to worry about ending the session because the server session has not been acquired yet + delete operation.options.session; + operation.clearSession(); + session = undefined; + } + } + + try { + executeWithServerSelection(topology, session, operation, (error, result) => { + if (session?.owner != null && session.owner === owner) { + return session.endSession(endSessionError => callback(endSessionError ?? error, result)); + } + + callback(error, result); + }); + } catch (error) { + if (session?.owner != null && session.owner === owner) { + session.endSession().catch(() => null); + } + + throw error; + } + }); +} + +function executeWithServerSelection( + topology: Topology, + session: ClientSession | undefined, + operation: AbstractOperation, + callback: Callback +) { + const readPreference = operation.readPreference ?? ReadPreference.primary; + const inTransaction = !!session?.inTransaction(); + + if (inTransaction && !readPreference.equals(ReadPreference.primary)) { + return callback( + new MongoTransactionError( + `Read preference in a transaction must be primary, not: ${readPreference.mode}` + ) + ); + } + + if (session?.isPinned && session.transaction.isCommitted && !operation.bypassPinningCheck) { + session.unpin(); + } + + let selector: ReadPreference | ServerSelector; + + if (operation.hasAspect(Aspect.MUST_SELECT_SAME_SERVER)) { + // GetMore and KillCursor operations must always select the same server, but run through + // server selection to potentially force monitor checks if the server is + // in an unknown state. + selector = sameServerSelector(operation.server?.description); + } else if (operation.trySecondaryWrite) { + // If operation should try to write to secondary use the custom server selector + // otherwise provide the read preference. + selector = secondaryWritableServerSelector(topology.commonWireVersion, readPreference); + } else { + selector = readPreference; + } + + const serverSelectionOptions = { session }; + function retryOperation(originalError: MongoError) { + const isWriteOperation = operation.hasAspect(Aspect.WRITE_OPERATION); + const isReadOperation = operation.hasAspect(Aspect.READ_OPERATION); + + if (isWriteOperation && originalError.code === MMAPv1_RETRY_WRITES_ERROR_CODE) { + return callback( + new MongoServerError({ + message: MMAPv1_RETRY_WRITES_ERROR_MESSAGE, + errmsg: MMAPv1_RETRY_WRITES_ERROR_MESSAGE, + originalError + }) + ); + } + + if (isWriteOperation && !isRetryableWriteError(originalError)) { + return callback(originalError); + } + + if (isReadOperation && !isRetryableReadError(originalError)) { + return callback(originalError); + } + + if ( + originalError instanceof MongoNetworkError && + session?.isPinned && + !session.inTransaction() && + operation.hasAspect(Aspect.CURSOR_CREATING) + ) { + // If we have a cursor and the initial command fails with a network error, + // we can retry it on another connection. So we need to check it back in, clear the + // pool for the service id, and retry again. + session.unpin({ force: true, forceClear: true }); + } + + // select a new server, and attempt to retry the operation + topology.selectServer(selector, serverSelectionOptions, (error?: Error, server?: Server) => { + if (!error && isWriteOperation && !supportsRetryableWrites(server)) { + return callback( + new MongoUnexpectedServerResponseError( + 'Selected server does not support retryable writes' + ) + ); + } + + if (error || !server) { + return callback( + error ?? new MongoUnexpectedServerResponseError('Server selection failed without error') + ); + } + + operation.execute(server, session, callback); + }); + } + + if ( + readPreference && + !readPreference.equals(ReadPreference.primary) && + session?.inTransaction() + ) { + callback( + new MongoTransactionError( + `Read preference in a transaction must be primary, not: ${readPreference.mode}` + ) + ); + + return; + } + + // select a server, and execute the operation against it + topology.selectServer(selector, serverSelectionOptions, (error, server) => { + if (error || !server) { + return callback(error); + } + + if (session && operation.hasAspect(Aspect.RETRYABLE)) { + const willRetryRead = + topology.s.options.retryReads && !inTransaction && operation.canRetryRead; + + const willRetryWrite = + topology.s.options.retryWrites && + !inTransaction && + supportsRetryableWrites(server) && + operation.canRetryWrite; + + const hasReadAspect = operation.hasAspect(Aspect.READ_OPERATION); + const hasWriteAspect = operation.hasAspect(Aspect.WRITE_OPERATION); + + if ((hasReadAspect && willRetryRead) || (hasWriteAspect && willRetryWrite)) { + if (hasWriteAspect && willRetryWrite) { + operation.options.willRetryWrite = true; + session.incrementTransactionNumber(); + } + + return operation.execute(server, session, (error, result) => { + if (error instanceof MongoError) { + return retryOperation(error); + } else if (error) { + return callback(error); + } + callback(undefined, result); + }); + } + } + + return operation.execute(server, session, callback); + }); +} diff --git a/ts-ticket-office-service/node_modules/mongodb/src/operations/find.ts b/ts-ticket-office-service/node_modules/mongodb/src/operations/find.ts new file mode 100644 index 000000000..c52aa2cd9 --- /dev/null +++ b/ts-ticket-office-service/node_modules/mongodb/src/operations/find.ts @@ -0,0 +1,279 @@ +import type { Document } from '../bson'; +import type { Collection } from '../collection'; +import { MongoCompatibilityError, MongoInvalidArgumentError } from '../error'; +import { ReadConcern } from '../read_concern'; +import type { Server } from '../sdam/server'; +import type { ClientSession } from '../sessions'; +import { formatSort, Sort } from '../sort'; +import { + Callback, + decorateWithExplain, + maxWireVersion, + MongoDBNamespace, + normalizeHintField +} from '../utils'; +import { CollationOptions, CommandOperation, CommandOperationOptions } from './command'; +import { Aspect, defineAspects, Hint } from './operation'; + +/** + * @public + * @typeParam TSchema - Unused schema definition, deprecated usage, only specify `FindOptions` with no generic + */ +// eslint-disable-next-line @typescript-eslint/no-unused-vars +export interface FindOptions extends CommandOperationOptions { + /** Sets the limit of documents returned in the query. */ + limit?: number; + /** Set to sort the documents coming back from the query. Array of indexes, `[['a', 1]]` etc. */ + sort?: Sort; + /** The fields to return in the query. Object of fields to either include or exclude (one of, not both), `{'a':1, 'b': 1}` **or** `{'a': 0, 'b': 0}` */ + projection?: Document; + /** Set to skip N documents ahead in your query (useful for pagination). */ + skip?: number; + /** Tell the query to use specific indexes in the query. Object of indexes to use, `{'_id':1}` */ + hint?: Hint; + /** Specify if the cursor can timeout. */ + timeout?: boolean; + /** Specify if the cursor is tailable. */ + tailable?: boolean; + /** Specify if the cursor is a tailable-await cursor. Requires `tailable` to be true */ + awaitData?: boolean; + /** Set the batchSize for the getMoreCommand when iterating over the query results. */ + batchSize?: number; + /** If true, returns only the index keys in the resulting documents. */ + returnKey?: boolean; + /** The inclusive lower bound for a specific index */ + min?: Document; + /** The exclusive upper bound for a specific index */ + max?: Document; + /** Number of milliseconds to wait before aborting the query. */ + maxTimeMS?: number; + /** The maximum amount of time for the server to wait on new documents to satisfy a tailable cursor query. Requires `tailable` and `awaitData` to be true */ + maxAwaitTimeMS?: number; + /** The server normally times out idle cursors after an inactivity period (10 minutes) to prevent excess memory use. Set this option to prevent that. */ + noCursorTimeout?: boolean; + /** Specify collation (MongoDB 3.4 or higher) settings for update operation (see 3.4 documentation for available fields). */ + collation?: CollationOptions; + /** Allows disk use for blocking sort operations exceeding 100MB memory. (MongoDB 3.2 or higher) */ + allowDiskUse?: boolean; + /** Determines whether to close the cursor after the first batch. Defaults to false. */ + singleBatch?: boolean; + /** For queries against a sharded collection, allows the command (or subsequent getMore commands) to return partial results, rather than an error, if one or more queried shards are unavailable. */ + allowPartialResults?: boolean; + /** Determines whether to return the record identifier for each document. If true, adds a field $recordId to the returned documents. */ + showRecordId?: boolean; + /** Map of parameter names and values that can be accessed using $$var (requires MongoDB 5.0). */ + let?: Document; +} + +const SUPPORTS_WRITE_CONCERN_AND_COLLATION = 5; + +/** @internal */ +export class FindOperation extends CommandOperation { + override options: FindOptions; + filter: Document; + + constructor( + collection: Collection | undefined, + ns: MongoDBNamespace, + filter: Document = {}, + options: FindOptions = {} + ) { + super(collection, options); + + this.options = options; + this.ns = ns; + + if (typeof filter !== 'object' || Array.isArray(filter)) { + throw new MongoInvalidArgumentError('Query filter must be a plain object or ObjectId'); + } + + // If the filter is a buffer, validate that is a valid BSON document + if (Buffer.isBuffer(filter)) { + const objectSize = filter[0] | (filter[1] << 8) | (filter[2] << 16) | (filter[3] << 24); + if (objectSize !== filter.length) { + throw new MongoInvalidArgumentError( + `Query filter raw message size does not match message header size [${filter.length}] != [${objectSize}]` + ); + } + } + + // special case passing in an ObjectId as a filter + this.filter = filter != null && filter._bsontype === 'ObjectID' ? { _id: filter } : filter; + } + + override execute( + server: Server, + session: ClientSession | undefined, + callback: Callback + ): void { + this.server = server; + + const serverWireVersion = maxWireVersion(server); + const options = this.options; + if (options.allowDiskUse != null && serverWireVersion < 4) { + callback( + new MongoCompatibilityError('Option "allowDiskUse" is not supported on MongoDB < 3.2') + ); + return; + } + + if (options.collation && serverWireVersion < SUPPORTS_WRITE_CONCERN_AND_COLLATION) { + callback( + new MongoCompatibilityError( + `Server ${server.name}, which reports wire version ${serverWireVersion}, does not support collation` + ) + ); + + return; + } + + let findCommand = makeFindCommand(this.ns, this.filter, options); + if (this.explain) { + findCommand = decorateWithExplain(findCommand, this.explain); + } + + server.command( + this.ns, + findCommand, + { + ...this.options, + ...this.bsonOptions, + documentsReturnedIn: 'firstBatch', + session + }, + callback + ); + } +} + +function makeFindCommand(ns: MongoDBNamespace, filter: Document, options: FindOptions): Document { + const findCommand: Document = { + find: ns.collection, + filter + }; + + if (options.sort) { + findCommand.sort = formatSort(options.sort); + } + + if (options.projection) { + let projection = options.projection; + if (projection && Array.isArray(projection)) { + projection = projection.length + ? projection.reduce((result, field) => { + result[field] = 1; + return result; + }, {}) + : { _id: 1 }; + } + + findCommand.projection = projection; + } + + if (options.hint) { + findCommand.hint = normalizeHintField(options.hint); + } + + if (typeof options.skip === 'number') { + findCommand.skip = options.skip; + } + + if (typeof options.limit === 'number') { + if (options.limit < 0) { + findCommand.limit = -options.limit; + findCommand.singleBatch = true; + } else { + findCommand.limit = options.limit; + } + } + + if (typeof options.batchSize === 'number') { + if (options.batchSize < 0) { + if ( + options.limit && + options.limit !== 0 && + Math.abs(options.batchSize) < Math.abs(options.limit) + ) { + findCommand.limit = -options.batchSize; + } + + findCommand.singleBatch = true; + } else { + findCommand.batchSize = options.batchSize; + } + } + + if (typeof options.singleBatch === 'boolean') { + findCommand.singleBatch = options.singleBatch; + } + + // we check for undefined specifically here to allow falsy values + // eslint-disable-next-line no-restricted-syntax + if (options.comment !== undefined) { + findCommand.comment = options.comment; + } + + if (typeof options.maxTimeMS === 'number') { + findCommand.maxTimeMS = options.maxTimeMS; + } + + const readConcern = ReadConcern.fromOptions(options); + if (readConcern) { + findCommand.readConcern = readConcern.toJSON(); + } + + if (options.max) { + findCommand.max = options.max; + } + + if (options.min) { + findCommand.min = options.min; + } + + if (typeof options.returnKey === 'boolean') { + findCommand.returnKey = options.returnKey; + } + + if (typeof options.showRecordId === 'boolean') { + findCommand.showRecordId = options.showRecordId; + } + + if (typeof options.tailable === 'boolean') { + findCommand.tailable = options.tailable; + } + + if (typeof options.timeout === 'boolean') { + findCommand.noCursorTimeout = !options.timeout; + } else if (typeof options.noCursorTimeout === 'boolean') { + findCommand.noCursorTimeout = options.noCursorTimeout; + } + + if (typeof options.awaitData === 'boolean') { + findCommand.awaitData = options.awaitData; + } + + if (typeof options.allowPartialResults === 'boolean') { + findCommand.allowPartialResults = options.allowPartialResults; + } + + if (options.collation) { + findCommand.collation = options.collation; + } + + if (typeof options.allowDiskUse === 'boolean') { + findCommand.allowDiskUse = options.allowDiskUse; + } + + if (options.let) { + findCommand.let = options.let; + } + + return findCommand; +} + +defineAspects(FindOperation, [ + Aspect.READ_OPERATION, + Aspect.RETRYABLE, + Aspect.EXPLAINABLE, + Aspect.CURSOR_CREATING +]); diff --git a/ts-ticket-office-service/node_modules/mongodb/src/operations/find_and_modify.ts b/ts-ticket-office-service/node_modules/mongodb/src/operations/find_and_modify.ts new file mode 100644 index 000000000..12d7ba504 --- /dev/null +++ b/ts-ticket-office-service/node_modules/mongodb/src/operations/find_and_modify.ts @@ -0,0 +1,295 @@ +import type { Document } from '../bson'; +import type { Collection } from '../collection'; +import { MongoCompatibilityError, MongoInvalidArgumentError } from '../error'; +import { ReadPreference } from '../read_preference'; +import type { Server } from '../sdam/server'; +import type { ClientSession } from '../sessions'; +import { formatSort, Sort, SortForCmd } from '../sort'; +import { Callback, decorateWithCollation, hasAtomicOperators, maxWireVersion } from '../utils'; +import type { WriteConcern, WriteConcernSettings } from '../write_concern'; +import { CommandOperation, CommandOperationOptions } from './command'; +import { Aspect, defineAspects } from './operation'; + +/** @public */ +export const ReturnDocument = Object.freeze({ + BEFORE: 'before', + AFTER: 'after' +} as const); + +/** @public */ +export type ReturnDocument = typeof ReturnDocument[keyof typeof ReturnDocument]; + +/** @public */ +export interface FindOneAndDeleteOptions extends CommandOperationOptions { + /** An optional hint for query optimization. See the {@link https://docs.mongodb.com/manual/reference/command/update/#update-command-hint|update command} reference for more information.*/ + hint?: Document; + /** Limits the fields to return for all matching documents. */ + projection?: Document; + /** Determines which document the operation modifies if the query selects multiple documents. */ + sort?: Sort; + /** Map of parameter names and values that can be accessed using $$var (requires MongoDB 5.0). */ + let?: Document; +} + +/** @public */ +export interface FindOneAndReplaceOptions extends CommandOperationOptions { + /** Allow driver to bypass schema validation in MongoDB 3.2 or higher. */ + bypassDocumentValidation?: boolean; + /** An optional hint for query optimization. See the {@link https://docs.mongodb.com/manual/reference/command/update/#update-command-hint|update command} reference for more information.*/ + hint?: Document; + /** Limits the fields to return for all matching documents. */ + projection?: Document; + /** When set to 'after', returns the updated document rather than the original. The default is 'before'. */ + returnDocument?: ReturnDocument; + /** Determines which document the operation modifies if the query selects multiple documents. */ + sort?: Sort; + /** Upsert the document if it does not exist. */ + upsert?: boolean; + /** Map of parameter names and values that can be accessed using $$var (requires MongoDB 5.0). */ + let?: Document; +} + +/** @public */ +export interface FindOneAndUpdateOptions extends CommandOperationOptions { + /** Optional list of array filters referenced in filtered positional operators */ + arrayFilters?: Document[]; + /** Allow driver to bypass schema validation in MongoDB 3.2 or higher. */ + bypassDocumentValidation?: boolean; + /** An optional hint for query optimization. See the {@link https://docs.mongodb.com/manual/reference/command/update/#update-command-hint|update command} reference for more information.*/ + hint?: Document; + /** Limits the fields to return for all matching documents. */ + projection?: Document; + /** When set to 'after', returns the updated document rather than the original. The default is 'before'. */ + returnDocument?: ReturnDocument; + /** Determines which document the operation modifies if the query selects multiple documents. */ + sort?: Sort; + /** Upsert the document if it does not exist. */ + upsert?: boolean; + /** Map of parameter names and values that can be accessed using $$var (requires MongoDB 5.0). */ + let?: Document; +} + +/** @internal */ +interface FindAndModifyCmdBase { + remove: boolean; + new: boolean; + upsert: boolean; + update?: Document; + sort?: SortForCmd; + fields?: Document; + bypassDocumentValidation?: boolean; + arrayFilters?: Document[]; + maxTimeMS?: number; + let?: Document; + writeConcern?: WriteConcern | WriteConcernSettings; + /** + * Comment to apply to the operation. + * + * In server versions pre-4.4, 'comment' must be string. A server + * error will be thrown if any other type is provided. + * + * In server versions 4.4 and above, 'comment' can be any valid BSON type. + */ + comment?: unknown; +} + +function configureFindAndModifyCmdBaseUpdateOpts( + cmdBase: FindAndModifyCmdBase, + options: FindOneAndReplaceOptions | FindOneAndUpdateOptions +): FindAndModifyCmdBase { + cmdBase.new = options.returnDocument === ReturnDocument.AFTER; + cmdBase.upsert = options.upsert === true; + + if (options.bypassDocumentValidation === true) { + cmdBase.bypassDocumentValidation = options.bypassDocumentValidation; + } + return cmdBase; +} + +/** @internal */ +class FindAndModifyOperation extends CommandOperation { + override options: FindOneAndReplaceOptions | FindOneAndUpdateOptions | FindOneAndDeleteOptions; + cmdBase: FindAndModifyCmdBase; + collection: Collection; + query: Document; + doc?: Document; + + constructor( + collection: Collection, + query: Document, + options: FindOneAndReplaceOptions | FindOneAndUpdateOptions | FindOneAndDeleteOptions + ) { + super(collection, options); + this.options = options ?? {}; + this.cmdBase = { + remove: false, + new: false, + upsert: false + }; + + const sort = formatSort(options.sort); + if (sort) { + this.cmdBase.sort = sort; + } + + if (options.projection) { + this.cmdBase.fields = options.projection; + } + + if (options.maxTimeMS) { + this.cmdBase.maxTimeMS = options.maxTimeMS; + } + + // Decorate the findAndModify command with the write Concern + if (options.writeConcern) { + this.cmdBase.writeConcern = options.writeConcern; + } + + if (options.let) { + this.cmdBase.let = options.let; + } + + // we check for undefined specifically here to allow falsy values + // eslint-disable-next-line no-restricted-syntax + if (options.comment !== undefined) { + this.cmdBase.comment = options.comment; + } + + // force primary read preference + this.readPreference = ReadPreference.primary; + + this.collection = collection; + this.query = query; + } + + override execute( + server: Server, + session: ClientSession | undefined, + callback: Callback + ): void { + const coll = this.collection; + const query = this.query; + const options = { ...this.options, ...this.bsonOptions }; + + // Create findAndModify command object + const cmd: Document = { + findAndModify: coll.collectionName, + query: query, + ...this.cmdBase + }; + + // Have we specified collation + try { + decorateWithCollation(cmd, coll, options); + } catch (err) { + return callback(err); + } + + if (options.hint) { + // TODO: once this method becomes a CommandOperation we will have the server + // in place to check. + const unacknowledgedWrite = this.writeConcern?.w === 0; + if (unacknowledgedWrite || maxWireVersion(server) < 8) { + callback( + new MongoCompatibilityError( + 'The current topology does not support a hint on findAndModify commands' + ) + ); + + return; + } + + cmd.hint = options.hint; + } + + if (this.explain && maxWireVersion(server) < 4) { + callback( + new MongoCompatibilityError( + `Server ${server.name} does not support explain on findAndModify` + ) + ); + return; + } + + // Execute the command + super.executeCommand(server, session, cmd, (err, result) => { + if (err) return callback(err); + return callback(undefined, result); + }); + } +} + +/** @internal */ +export class FindOneAndDeleteOperation extends FindAndModifyOperation { + constructor(collection: Collection, filter: Document, options: FindOneAndDeleteOptions) { + // Basic validation + if (filter == null || typeof filter !== 'object') { + throw new MongoInvalidArgumentError('Argument "filter" must be an object'); + } + + super(collection, filter, options); + this.cmdBase.remove = true; + } +} + +/** @internal */ +export class FindOneAndReplaceOperation extends FindAndModifyOperation { + constructor( + collection: Collection, + filter: Document, + replacement: Document, + options: FindOneAndReplaceOptions + ) { + if (filter == null || typeof filter !== 'object') { + throw new MongoInvalidArgumentError('Argument "filter" must be an object'); + } + + if (replacement == null || typeof replacement !== 'object') { + throw new MongoInvalidArgumentError('Argument "replacement" must be an object'); + } + + if (hasAtomicOperators(replacement)) { + throw new MongoInvalidArgumentError('Replacement document must not contain atomic operators'); + } + + super(collection, filter, options); + this.cmdBase.update = replacement; + configureFindAndModifyCmdBaseUpdateOpts(this.cmdBase, options); + } +} + +/** @internal */ +export class FindOneAndUpdateOperation extends FindAndModifyOperation { + constructor( + collection: Collection, + filter: Document, + update: Document, + options: FindOneAndUpdateOptions + ) { + if (filter == null || typeof filter !== 'object') { + throw new MongoInvalidArgumentError('Argument "filter" must be an object'); + } + + if (update == null || typeof update !== 'object') { + throw new MongoInvalidArgumentError('Argument "update" must be an object'); + } + + if (!hasAtomicOperators(update)) { + throw new MongoInvalidArgumentError('Update document requires atomic operators'); + } + + super(collection, filter, options); + this.cmdBase.update = update; + configureFindAndModifyCmdBaseUpdateOpts(this.cmdBase, options); + + if (options.arrayFilters) { + this.cmdBase.arrayFilters = options.arrayFilters; + } + } +} + +defineAspects(FindAndModifyOperation, [ + Aspect.WRITE_OPERATION, + Aspect.RETRYABLE, + Aspect.EXPLAINABLE +]); diff --git a/ts-ticket-office-service/node_modules/mongodb/src/operations/get_more.ts b/ts-ticket-office-service/node_modules/mongodb/src/operations/get_more.ts new file mode 100644 index 000000000..bc3746edb --- /dev/null +++ b/ts-ticket-office-service/node_modules/mongodb/src/operations/get_more.ts @@ -0,0 +1,63 @@ +import type { Document, Long } from '../bson'; +import { MongoRuntimeError } from '../error'; +import type { Server } from '../sdam/server'; +import type { ClientSession } from '../sessions'; +import { Callback, maxWireVersion, MongoDBNamespace } from '../utils'; +import { AbstractOperation, Aspect, defineAspects, OperationOptions } from './operation'; + +/** + * @public + */ + +export interface GetMoreOptions extends OperationOptions { + /** Set the batchSize for the getMoreCommand when iterating over the query results. */ + batchSize?: number; + /** + * Comment to apply to the operation. + * + * getMore only supports 'comment' in server versions 4.4 and above. + */ + comment?: unknown; + /** Number of milliseconds to wait before aborting the query. */ + maxTimeMS?: number; +} + +/** @internal */ +export class GetMoreOperation extends AbstractOperation { + cursorId: Long; + override options: GetMoreOptions; + + constructor(ns: MongoDBNamespace, cursorId: Long, server: Server, options: GetMoreOptions = {}) { + super(options); + + this.options = options; + + // comment on getMore is only supported for server versions 4.4 and above + if (maxWireVersion(server) < 9) { + delete this.options.comment; + } + + this.ns = ns; + this.cursorId = cursorId; + this.server = server; + } + + /** + * Although there is a server already associated with the get more operation, the signature + * for execute passes a server so we will just use that one. + */ + override execute( + server: Server, + session: ClientSession | undefined, + callback: Callback + ): void { + if (server !== this.server) { + return callback( + new MongoRuntimeError('Getmore must run on the same server operation began on') + ); + } + server.getMore(this.ns, this.cursorId, this.options, callback); + } +} + +defineAspects(GetMoreOperation, [Aspect.READ_OPERATION, Aspect.MUST_SELECT_SAME_SERVER]); diff --git a/ts-ticket-office-service/node_modules/mongodb/src/operations/indexes.ts b/ts-ticket-office-service/node_modules/mongodb/src/operations/indexes.ts new file mode 100644 index 000000000..c979a64b7 --- /dev/null +++ b/ts-ticket-office-service/node_modules/mongodb/src/operations/indexes.ts @@ -0,0 +1,500 @@ +import type { Document } from '../bson'; +import type { Collection } from '../collection'; +import type { Db } from '../db'; +import { MongoCompatibilityError, MONGODB_ERROR_CODES, MongoServerError } from '../error'; +import type { OneOrMore } from '../mongo_types'; +import { ReadPreference } from '../read_preference'; +import type { Server } from '../sdam/server'; +import type { ClientSession } from '../sessions'; +import { Callback, maxWireVersion, MongoDBNamespace, parseIndexOptions } from '../utils'; +import { + CollationOptions, + CommandOperation, + CommandOperationOptions, + OperationParent +} from './command'; +import { indexInformation, IndexInformationOptions } from './common_functions'; +import { AbstractOperation, Aspect, defineAspects } from './operation'; + +const VALID_INDEX_OPTIONS = new Set([ + 'background', + 'unique', + 'name', + 'partialFilterExpression', + 'sparse', + 'hidden', + 'expireAfterSeconds', + 'storageEngine', + 'collation', + 'version', + + // text indexes + 'weights', + 'default_language', + 'language_override', + 'textIndexVersion', + + // 2d-sphere indexes + '2dsphereIndexVersion', + + // 2d indexes + 'bits', + 'min', + 'max', + + // geoHaystack Indexes + 'bucketSize', + + // wildcard indexes + 'wildcardProjection' +]); + +/** @public */ +export type IndexDirection = -1 | 1 | '2d' | '2dsphere' | 'text' | 'geoHaystack' | number; + +/** @public */ +export type IndexSpecification = OneOrMore< + | string + | [string, IndexDirection] + | { [key: string]: IndexDirection } + | [string, IndexDirection][] + | { [key: string]: IndexDirection }[] +>; + +/** @public */ +export interface IndexDescription + extends Pick< + CreateIndexesOptions, + | 'background' + | 'unique' + | 'partialFilterExpression' + | 'sparse' + | 'hidden' + | 'expireAfterSeconds' + | 'storageEngine' + | 'version' + | 'weights' + | 'default_language' + | 'language_override' + | 'textIndexVersion' + | '2dsphereIndexVersion' + | 'bits' + | 'min' + | 'max' + | 'bucketSize' + | 'wildcardProjection' + > { + collation?: CollationOptions; + name?: string; + key: Document; +} + +/** @public */ +export interface CreateIndexesOptions extends CommandOperationOptions { + /** Creates the index in the background, yielding whenever possible. */ + background?: boolean; + /** Creates an unique index. */ + unique?: boolean; + /** Override the autogenerated index name (useful if the resulting name is larger than 128 bytes) */ + name?: string; + /** Creates a partial index based on the given filter object (MongoDB 3.2 or higher) */ + partialFilterExpression?: Document; + /** Creates a sparse index. */ + sparse?: boolean; + /** Allows you to expire data on indexes applied to a data (MongoDB 2.2 or higher) */ + expireAfterSeconds?: number; + /** Allows users to configure the storage engine on a per-index basis when creating an index. (MongoDB 3.0 or higher) */ + storageEngine?: Document; + /** (MongoDB 4.4. or higher) Specifies how many data-bearing members of a replica set, including the primary, must complete the index builds successfully before the primary marks the indexes as ready. This option accepts the same values for the "w" field in a write concern plus "votingMembers", which indicates all voting data-bearing nodes. */ + commitQuorum?: number | string; + /** Specifies the index version number, either 0 or 1. */ + version?: number; + // text indexes + weights?: Document; + default_language?: string; + language_override?: string; + textIndexVersion?: number; + // 2d-sphere indexes + '2dsphereIndexVersion'?: number; + // 2d indexes + bits?: number; + /** For geospatial indexes set the lower bound for the co-ordinates. */ + min?: number; + /** For geospatial indexes set the high bound for the co-ordinates. */ + max?: number; + // geoHaystack Indexes + bucketSize?: number; + // wildcard indexes + wildcardProjection?: Document; + /** Specifies that the index should exist on the target collection but should not be used by the query planner when executing operations. (MongoDB 4.4 or higher) */ + hidden?: boolean; +} + +function makeIndexSpec(indexSpec: IndexSpecification, options: any): IndexDescription { + const indexParameters = parseIndexOptions(indexSpec); + + // Generate the index name + const name = typeof options.name === 'string' ? options.name : indexParameters.name; + + // Set up the index + const finalIndexSpec: Document = { name, key: indexParameters.fieldHash }; + + // merge valid index options into the index spec + for (const optionName in options) { + if (VALID_INDEX_OPTIONS.has(optionName)) { + finalIndexSpec[optionName] = options[optionName]; + } + } + + return finalIndexSpec as IndexDescription; +} + +/** @internal */ +export class IndexesOperation extends AbstractOperation { + override options: IndexInformationOptions; + collection: Collection; + + constructor(collection: Collection, options: IndexInformationOptions) { + super(options); + this.options = options; + this.collection = collection; + } + + override execute( + server: Server, + session: ClientSession | undefined, + callback: Callback + ): void { + const coll = this.collection; + const options = this.options; + + indexInformation( + coll.s.db, + coll.collectionName, + { full: true, ...options, readPreference: this.readPreference, session }, + callback + ); + } +} + +/** @internal */ +export class CreateIndexesOperation< + T extends string | string[] = string[] +> extends CommandOperation { + override options: CreateIndexesOptions; + collectionName: string; + indexes: IndexDescription[]; + + constructor( + parent: OperationParent, + collectionName: string, + indexes: IndexDescription[], + options?: CreateIndexesOptions + ) { + super(parent, options); + + this.options = options ?? {}; + this.collectionName = collectionName; + + this.indexes = indexes; + } + + override execute( + server: Server, + session: ClientSession | undefined, + callback: Callback + ): void { + const options = this.options; + const indexes = this.indexes; + + const serverWireVersion = maxWireVersion(server); + + // Ensure we generate the correct name if the parameter is not set + for (let i = 0; i < indexes.length; i++) { + // Did the user pass in a collation, check if our write server supports it + if (indexes[i].collation && serverWireVersion < 5) { + callback( + new MongoCompatibilityError( + `Server ${server.name}, which reports wire version ${serverWireVersion}, ` + + 'does not support collation' + ) + ); + return; + } + + if (indexes[i].name == null) { + const keys = []; + + for (const name in indexes[i].key) { + keys.push(`${name}_${indexes[i].key[name]}`); + } + + // Set the name + indexes[i].name = keys.join('_'); + } + } + + const cmd: Document = { createIndexes: this.collectionName, indexes }; + + if (options.commitQuorum != null) { + if (serverWireVersion < 9) { + callback( + new MongoCompatibilityError( + 'Option `commitQuorum` for `createIndexes` not supported on servers < 4.4' + ) + ); + return; + } + cmd.commitQuorum = options.commitQuorum; + } + + // collation is set on each index, it should not be defined at the root + this.options.collation = undefined; + + super.executeCommand(server, session, cmd, err => { + if (err) { + callback(err); + return; + } + + const indexNames = indexes.map(index => index.name || ''); + callback(undefined, indexNames as T); + }); + } +} + +/** @internal */ +export class CreateIndexOperation extends CreateIndexesOperation { + constructor( + parent: OperationParent, + collectionName: string, + indexSpec: IndexSpecification, + options?: CreateIndexesOptions + ) { + // createIndex can be called with a variety of styles: + // coll.createIndex('a'); + // coll.createIndex({ a: 1 }); + // coll.createIndex([['a', 1]]); + // createIndexes is always called with an array of index spec objects + + super(parent, collectionName, [makeIndexSpec(indexSpec, options)], options); + } + override execute( + server: Server, + session: ClientSession | undefined, + callback: Callback + ): void { + super.execute(server, session, (err, indexNames) => { + if (err || !indexNames) return callback(err); + return callback(undefined, indexNames[0]); + }); + } +} + +/** @internal */ +export class EnsureIndexOperation extends CreateIndexOperation { + db: Db; + + constructor( + db: Db, + collectionName: string, + indexSpec: IndexSpecification, + options?: CreateIndexesOptions + ) { + super(db, collectionName, indexSpec, options); + + this.readPreference = ReadPreference.primary; + this.db = db; + this.collectionName = collectionName; + } + + override execute(server: Server, session: ClientSession | undefined, callback: Callback): void { + const indexName = this.indexes[0].name; + const cursor = this.db.collection(this.collectionName).listIndexes({ session }); + cursor.toArray((err, indexes) => { + /// ignore "NamespaceNotFound" errors + if (err && (err as MongoServerError).code !== MONGODB_ERROR_CODES.NamespaceNotFound) { + return callback(err); + } + + if (indexes) { + indexes = Array.isArray(indexes) ? indexes : [indexes]; + if (indexes.some(index => index.name === indexName)) { + callback(undefined, indexName); + return; + } + } + + super.execute(server, session, callback); + }); + } +} + +/** @public */ +export type DropIndexesOptions = CommandOperationOptions; + +/** @internal */ +export class DropIndexOperation extends CommandOperation { + override options: DropIndexesOptions; + collection: Collection; + indexName: string; + + constructor(collection: Collection, indexName: string, options?: DropIndexesOptions) { + super(collection, options); + + this.options = options ?? {}; + this.collection = collection; + this.indexName = indexName; + } + + override execute( + server: Server, + session: ClientSession | undefined, + callback: Callback + ): void { + const cmd = { dropIndexes: this.collection.collectionName, index: this.indexName }; + super.executeCommand(server, session, cmd, callback); + } +} + +/** @internal */ +export class DropIndexesOperation extends DropIndexOperation { + constructor(collection: Collection, options: DropIndexesOptions) { + super(collection, '*', options); + } + + override execute(server: Server, session: ClientSession | undefined, callback: Callback): void { + super.execute(server, session, err => { + if (err) return callback(err, false); + callback(undefined, true); + }); + } +} + +/** @public */ +export interface ListIndexesOptions extends CommandOperationOptions { + /** The batchSize for the returned command cursor or if pre 2.8 the systems batch collection */ + batchSize?: number; +} + +/** @internal */ +export class ListIndexesOperation extends CommandOperation { + override options: ListIndexesOptions; + collectionNamespace: MongoDBNamespace; + + constructor(collection: Collection, options?: ListIndexesOptions) { + super(collection, options); + + this.options = options ?? {}; + this.collectionNamespace = collection.s.namespace; + } + + override execute( + server: Server, + session: ClientSession | undefined, + callback: Callback + ): void { + const serverWireVersion = maxWireVersion(server); + + const cursor = this.options.batchSize ? { batchSize: this.options.batchSize } : {}; + + const command: Document = { listIndexes: this.collectionNamespace.collection, cursor }; + + // we check for undefined specifically here to allow falsy values + // eslint-disable-next-line no-restricted-syntax + if (serverWireVersion >= 9 && this.options.comment !== undefined) { + command.comment = this.options.comment; + } + + super.executeCommand(server, session, command, callback); + } +} + +/** @internal */ +export class IndexExistsOperation extends AbstractOperation { + override options: IndexInformationOptions; + collection: Collection; + indexes: string | string[]; + + constructor( + collection: Collection, + indexes: string | string[], + options: IndexInformationOptions + ) { + super(options); + this.options = options; + this.collection = collection; + this.indexes = indexes; + } + + override execute( + server: Server, + session: ClientSession | undefined, + callback: Callback + ): void { + const coll = this.collection; + const indexes = this.indexes; + + indexInformation( + coll.s.db, + coll.collectionName, + { ...this.options, readPreference: this.readPreference, session }, + (err, indexInformation) => { + // If we have an error return + if (err != null) return callback(err); + // Let's check for the index names + if (!Array.isArray(indexes)) return callback(undefined, indexInformation[indexes] != null); + // Check in list of indexes + for (let i = 0; i < indexes.length; i++) { + if (indexInformation[indexes[i]] == null) { + return callback(undefined, false); + } + } + + // All keys found return true + return callback(undefined, true); + } + ); + } +} + +/** @internal */ +export class IndexInformationOperation extends AbstractOperation { + override options: IndexInformationOptions; + db: Db; + name: string; + + constructor(db: Db, name: string, options?: IndexInformationOptions) { + super(options); + this.options = options ?? {}; + this.db = db; + this.name = name; + } + + override execute( + server: Server, + session: ClientSession | undefined, + callback: Callback + ): void { + const db = this.db; + const name = this.name; + + indexInformation( + db, + name, + { ...this.options, readPreference: this.readPreference, session }, + callback + ); + } +} + +defineAspects(ListIndexesOperation, [ + Aspect.READ_OPERATION, + Aspect.RETRYABLE, + Aspect.CURSOR_CREATING +]); +defineAspects(CreateIndexesOperation, [Aspect.WRITE_OPERATION]); +defineAspects(CreateIndexOperation, [Aspect.WRITE_OPERATION]); +defineAspects(EnsureIndexOperation, [Aspect.WRITE_OPERATION]); +defineAspects(DropIndexOperation, [Aspect.WRITE_OPERATION]); +defineAspects(DropIndexesOperation, [Aspect.WRITE_OPERATION]); diff --git a/ts-ticket-office-service/node_modules/mongodb/src/operations/insert.ts b/ts-ticket-office-service/node_modules/mongodb/src/operations/insert.ts new file mode 100644 index 000000000..6475a5cfe --- /dev/null +++ b/ts-ticket-office-service/node_modules/mongodb/src/operations/insert.ts @@ -0,0 +1,158 @@ +import type { Document } from '../bson'; +import type { BulkWriteOptions } from '../bulk/common'; +import type { Collection } from '../collection'; +import { MongoInvalidArgumentError, MongoServerError } from '../error'; +import type { InferIdType } from '../mongo_types'; +import type { Server } from '../sdam/server'; +import type { ClientSession } from '../sessions'; +import type { Callback, MongoDBNamespace } from '../utils'; +import { WriteConcern } from '../write_concern'; +import { BulkWriteOperation } from './bulk_write'; +import { CommandOperation, CommandOperationOptions } from './command'; +import { prepareDocs } from './common_functions'; +import { AbstractOperation, Aspect, defineAspects } from './operation'; + +/** @internal */ +export class InsertOperation extends CommandOperation { + override options: BulkWriteOptions; + documents: Document[]; + + constructor(ns: MongoDBNamespace, documents: Document[], options: BulkWriteOptions) { + super(undefined, options); + this.options = { ...options, checkKeys: options.checkKeys ?? false }; + this.ns = ns; + this.documents = documents; + } + + override execute( + server: Server, + session: ClientSession | undefined, + callback: Callback + ): void { + const options = this.options ?? {}; + const ordered = typeof options.ordered === 'boolean' ? options.ordered : true; + const command: Document = { + insert: this.ns.collection, + documents: this.documents, + ordered + }; + + if (typeof options.bypassDocumentValidation === 'boolean') { + command.bypassDocumentValidation = options.bypassDocumentValidation; + } + + // we check for undefined specifically here to allow falsy values + // eslint-disable-next-line no-restricted-syntax + if (options.comment !== undefined) { + command.comment = options.comment; + } + + super.executeCommand(server, session, command, callback); + } +} + +/** @public */ +export interface InsertOneOptions extends CommandOperationOptions { + /** Allow driver to bypass schema validation in MongoDB 3.2 or higher. */ + bypassDocumentValidation?: boolean; + /** Force server to assign _id values instead of driver. */ + forceServerObjectId?: boolean; +} + +/** @public */ +export interface InsertOneResult { + /** Indicates whether this write result was acknowledged. If not, then all other members of this result will be undefined */ + acknowledged: boolean; + /** The identifier that was inserted. If the server generated the identifier, this value will be null as the driver does not have access to that data */ + insertedId: InferIdType; +} + +export class InsertOneOperation extends InsertOperation { + constructor(collection: Collection, doc: Document, options: InsertOneOptions) { + super(collection.s.namespace, prepareDocs(collection, [doc], options), options); + } + + override execute( + server: Server, + session: ClientSession | undefined, + callback: Callback + ): void { + super.execute(server, session, (err, res) => { + if (err || res == null) return callback(err); + if (res.code) return callback(new MongoServerError(res)); + if (res.writeErrors) { + // This should be a WriteError but we can't change it now because of error hierarchy + return callback(new MongoServerError(res.writeErrors[0])); + } + + callback(undefined, { + acknowledged: this.writeConcern?.w !== 0 ?? true, + insertedId: this.documents[0]._id + }); + }); + } +} + +/** @public */ +export interface InsertManyResult { + /** Indicates whether this write result was acknowledged. If not, then all other members of this result will be undefined */ + acknowledged: boolean; + /** The number of inserted documents for this operations */ + insertedCount: number; + /** Map of the index of the inserted document to the id of the inserted document */ + insertedIds: { [key: number]: InferIdType }; +} + +/** @internal */ +export class InsertManyOperation extends AbstractOperation { + override options: BulkWriteOptions; + collection: Collection; + docs: Document[]; + + constructor(collection: Collection, docs: Document[], options: BulkWriteOptions) { + super(options); + + if (!Array.isArray(docs)) { + throw new MongoInvalidArgumentError('Argument "docs" must be an array of documents'); + } + + this.options = options; + this.collection = collection; + this.docs = docs; + } + + override execute( + server: Server, + session: ClientSession | undefined, + callback: Callback + ): void { + const coll = this.collection; + const options = { ...this.options, ...this.bsonOptions, readPreference: this.readPreference }; + const writeConcern = WriteConcern.fromOptions(options); + const bulkWriteOperation = new BulkWriteOperation( + coll, + prepareDocs(coll, this.docs, options).map(document => ({ insertOne: { document } })), + options + ); + + bulkWriteOperation.execute(server, session, (err, res) => { + if (err || res == null) { + if (err && err.message === 'Operation must be an object with an operation key') { + err = new MongoInvalidArgumentError( + 'Collection.insertMany() cannot be called with an array that has null/undefined values' + ); + } + return callback(err); + } + callback(undefined, { + acknowledged: writeConcern?.w !== 0 ?? true, + insertedCount: res.insertedCount, + insertedIds: res.insertedIds + }); + }); + } +} + +defineAspects(InsertOperation, [Aspect.RETRYABLE, Aspect.WRITE_OPERATION]); +defineAspects(InsertOneOperation, [Aspect.RETRYABLE, Aspect.WRITE_OPERATION]); +defineAspects(InsertManyOperation, [Aspect.WRITE_OPERATION]); diff --git a/ts-ticket-office-service/node_modules/mongodb/src/operations/is_capped.ts b/ts-ticket-office-service/node_modules/mongodb/src/operations/is_capped.ts new file mode 100644 index 000000000..938c72f41 --- /dev/null +++ b/ts-ticket-office-service/node_modules/mongodb/src/operations/is_capped.ts @@ -0,0 +1,42 @@ +import type { Collection } from '../collection'; +import { MongoAPIError } from '../error'; +import type { Server } from '../sdam/server'; +import type { ClientSession } from '../sessions'; +import type { Callback } from '../utils'; +import { AbstractOperation, OperationOptions } from './operation'; + +/** @internal */ +export class IsCappedOperation extends AbstractOperation { + override options: OperationOptions; + collection: Collection; + + constructor(collection: Collection, options: OperationOptions) { + super(options); + this.options = options; + this.collection = collection; + } + + override execute( + server: Server, + session: ClientSession | undefined, + callback: Callback + ): void { + const coll = this.collection; + + coll.s.db + .listCollections( + { name: coll.collectionName }, + { ...this.options, nameOnly: false, readPreference: this.readPreference, session } + ) + .toArray((err, collections) => { + if (err || !collections) return callback(err); + if (collections.length === 0) { + // TODO(NODE-3485) + return callback(new MongoAPIError(`collection ${coll.namespace} not found`)); + } + + const collOptions = collections[0].options; + callback(undefined, !!(collOptions && collOptions.capped)); + }); + } +} diff --git a/ts-ticket-office-service/node_modules/mongodb/src/operations/kill_cursors.ts b/ts-ticket-office-service/node_modules/mongodb/src/operations/kill_cursors.ts new file mode 100644 index 000000000..3891a8efa --- /dev/null +++ b/ts-ticket-office-service/node_modules/mongodb/src/operations/kill_cursors.ts @@ -0,0 +1,27 @@ +import type { Long } from '../bson'; +import { MongoRuntimeError } from '../error'; +import type { Server } from '../sdam/server'; +import type { ClientSession } from '../sessions'; +import type { Callback, MongoDBNamespace } from '../utils'; +import { AbstractOperation, Aspect, defineAspects, OperationOptions } from './operation'; + +export class KillCursorsOperation extends AbstractOperation { + cursorId: Long; + constructor(cursorId: Long, ns: MongoDBNamespace, server: Server, options: OperationOptions) { + super(options); + this.ns = ns; + this.cursorId = cursorId; + this.server = server; + } + + execute(server: Server, session: ClientSession | undefined, callback: Callback): void { + if (server !== this.server) { + return callback( + new MongoRuntimeError('Killcursor must run on the same server operation began on') + ); + } + server.killCursors(this.ns, [this.cursorId], { session }, () => callback()); + } +} + +defineAspects(KillCursorsOperation, [Aspect.MUST_SELECT_SAME_SERVER]); diff --git a/ts-ticket-office-service/node_modules/mongodb/src/operations/list_collections.ts b/ts-ticket-office-service/node_modules/mongodb/src/operations/list_collections.ts new file mode 100644 index 000000000..ae1c15ec2 --- /dev/null +++ b/ts-ticket-office-service/node_modules/mongodb/src/operations/list_collections.ts @@ -0,0 +1,91 @@ +import type { Binary, Document } from '../bson'; +import type { Db } from '../db'; +import type { Server } from '../sdam/server'; +import type { ClientSession } from '../sessions'; +import { Callback, maxWireVersion } from '../utils'; +import { CommandOperation, CommandOperationOptions } from './command'; +import { Aspect, defineAspects } from './operation'; + +/** @public */ +export interface ListCollectionsOptions extends CommandOperationOptions { + /** Since 4.0: If true, will only return the collection name in the response, and will omit additional info */ + nameOnly?: boolean; + /** Since 4.0: If true and nameOnly is true, allows a user without the required privilege (i.e. listCollections action on the database) to run the command when access control is enforced. */ + authorizedCollections?: boolean; + /** The batchSize for the returned command cursor or if pre 2.8 the systems batch collection */ + batchSize?: number; +} + +/** @internal */ +export class ListCollectionsOperation extends CommandOperation { + override options: ListCollectionsOptions; + db: Db; + filter: Document; + nameOnly: boolean; + authorizedCollections: boolean; + batchSize?: number; + + constructor(db: Db, filter: Document, options?: ListCollectionsOptions) { + super(db, options); + + this.options = options ?? {}; + this.db = db; + this.filter = filter; + this.nameOnly = !!this.options.nameOnly; + this.authorizedCollections = !!this.options.authorizedCollections; + + if (typeof this.options.batchSize === 'number') { + this.batchSize = this.options.batchSize; + } + } + + override execute( + server: Server, + session: ClientSession | undefined, + callback: Callback + ): void { + return super.executeCommand( + server, + session, + this.generateCommand(maxWireVersion(server)), + callback + ); + } + + /* This is here for the purpose of unit testing the final command that gets sent. */ + generateCommand(wireVersion: number): Document { + const command: Document = { + listCollections: 1, + filter: this.filter, + cursor: this.batchSize ? { batchSize: this.batchSize } : {}, + nameOnly: this.nameOnly, + authorizedCollections: this.authorizedCollections + }; + + // we check for undefined specifically here to allow falsy values + // eslint-disable-next-line no-restricted-syntax + if (wireVersion >= 9 && this.options.comment !== undefined) { + command.comment = this.options.comment; + } + + return command; + } +} + +/** @public */ +export interface CollectionInfo extends Document { + name: string; + type?: string; + options?: Document; + info?: { + readOnly?: false; + uuid?: Binary; + }; + idIndex?: Document; +} + +defineAspects(ListCollectionsOperation, [ + Aspect.READ_OPERATION, + Aspect.RETRYABLE, + Aspect.CURSOR_CREATING +]); diff --git a/ts-ticket-office-service/node_modules/mongodb/src/operations/list_databases.ts b/ts-ticket-office-service/node_modules/mongodb/src/operations/list_databases.ts new file mode 100644 index 000000000..537c95290 --- /dev/null +++ b/ts-ticket-office-service/node_modules/mongodb/src/operations/list_databases.ts @@ -0,0 +1,65 @@ +import type { Document } from '../bson'; +import type { Db } from '../db'; +import type { Server } from '../sdam/server'; +import type { ClientSession } from '../sessions'; +import { Callback, maxWireVersion, MongoDBNamespace } from '../utils'; +import { CommandOperation, CommandOperationOptions } from './command'; +import { Aspect, defineAspects } from './operation'; + +/** @public */ +export interface ListDatabasesResult { + databases: ({ name: string; sizeOnDisk?: number; empty?: boolean } & Document)[]; + totalSize?: number; + totalSizeMb?: number; + ok: 1 | 0; +} + +/** @public */ +export interface ListDatabasesOptions extends CommandOperationOptions { + /** A query predicate that determines which databases are listed */ + filter?: Document; + /** A flag to indicate whether the command should return just the database names, or return both database names and size information */ + nameOnly?: boolean; + /** A flag that determines which databases are returned based on the user privileges when access control is enabled */ + authorizedDatabases?: boolean; +} + +/** @internal */ +export class ListDatabasesOperation extends CommandOperation { + override options: ListDatabasesOptions; + + constructor(db: Db, options?: ListDatabasesOptions) { + super(db, options); + this.options = options ?? {}; + this.ns = new MongoDBNamespace('admin', '$cmd'); + } + + override execute( + server: Server, + session: ClientSession | undefined, + callback: Callback + ): void { + const cmd: Document = { listDatabases: 1 }; + if (this.options.nameOnly) { + cmd.nameOnly = Number(cmd.nameOnly); + } + + if (this.options.filter) { + cmd.filter = this.options.filter; + } + + if (typeof this.options.authorizedDatabases === 'boolean') { + cmd.authorizedDatabases = this.options.authorizedDatabases; + } + + // we check for undefined specifically here to allow falsy values + // eslint-disable-next-line no-restricted-syntax + if (maxWireVersion(server) >= 9 && this.options.comment !== undefined) { + cmd.comment = this.options.comment; + } + + super.executeCommand(server, session, cmd, callback); + } +} + +defineAspects(ListDatabasesOperation, [Aspect.READ_OPERATION, Aspect.RETRYABLE]); diff --git a/ts-ticket-office-service/node_modules/mongodb/src/operations/map_reduce.ts b/ts-ticket-office-service/node_modules/mongodb/src/operations/map_reduce.ts new file mode 100644 index 000000000..f3134f45a --- /dev/null +++ b/ts-ticket-office-service/node_modules/mongodb/src/operations/map_reduce.ts @@ -0,0 +1,250 @@ +import type { ObjectId } from '../bson'; +import { Code, Document } from '../bson'; +import type { Collection } from '../collection'; +import { MongoCompatibilityError, MongoServerError } from '../error'; +import { ReadPreference, ReadPreferenceMode } from '../read_preference'; +import type { Server } from '../sdam/server'; +import type { ClientSession } from '../sessions'; +import type { Sort } from '../sort'; +import { + applyWriteConcern, + Callback, + decorateWithCollation, + decorateWithReadConcern, + isObject, + maxWireVersion +} from '../utils'; +import { CommandOperation, CommandOperationOptions } from './command'; +import { Aspect, defineAspects } from './operation'; + +const exclusionList = [ + 'explain', + 'readPreference', + 'readConcern', + 'session', + 'bypassDocumentValidation', + 'writeConcern', + 'raw', + 'fieldsAsRaw', + 'promoteLongs', + 'promoteValues', + 'promoteBuffers', + 'bsonRegExp', + 'serializeFunctions', + 'ignoreUndefined', + 'enableUtf8Validation', + 'scope' // this option is reformatted thus exclude the original +]; + +/** @public */ +export type MapFunction = (this: TSchema) => void; +/** @public */ +export type ReduceFunction = (key: TKey, values: TValue[]) => TValue; +/** @public */ +export type FinalizeFunction = ( + key: TKey, + reducedValue: TValue +) => TValue; + +/** @public */ +export interface MapReduceOptions + extends CommandOperationOptions { + /** Sets the output target for the map reduce job. */ + out?: 'inline' | { inline: 1 } | { replace: string } | { merge: string } | { reduce: string }; + /** Query filter object. */ + query?: Document; + /** Sorts the input objects using this key. Useful for optimization, like sorting by the emit key for fewer reduces. */ + sort?: Sort; + /** Number of objects to return from collection. */ + limit?: number; + /** Keep temporary data. */ + keeptemp?: boolean; + /** Finalize function. */ + finalize?: FinalizeFunction | string; + /** Can pass in variables that can be access from map/reduce/finalize. */ + scope?: Document; + /** It is possible to make the execution stay in JS. Provided in MongoDB \> 2.0.X. */ + jsMode?: boolean; + /** Provide statistics on job execution time. */ + verbose?: boolean; + /** Allow driver to bypass schema validation in MongoDB 3.2 or higher. */ + bypassDocumentValidation?: boolean; +} + +interface MapReduceStats { + processtime?: number; + counts?: number; + timing?: number; +} + +/** + * Run Map Reduce across a collection. Be aware that the inline option for out will return an array of results not a collection. + * @internal + */ +export class MapReduceOperation extends CommandOperation { + override options: MapReduceOptions; + collection: Collection; + /** The mapping function. */ + map: MapFunction | string; + /** The reduce function. */ + reduce: ReduceFunction | string; + + /** + * Constructs a MapReduce operation. + * + * @param collection - Collection instance. + * @param map - The mapping function. + * @param reduce - The reduce function. + * @param options - Optional settings. See Collection.prototype.mapReduce for a list of options. + */ + constructor( + collection: Collection, + map: MapFunction | string, + reduce: ReduceFunction | string, + options?: MapReduceOptions + ) { + super(collection, options); + + this.options = options ?? {}; + this.collection = collection; + this.map = map; + this.reduce = reduce; + } + + override execute( + server: Server, + session: ClientSession | undefined, + callback: Callback + ): void { + const coll = this.collection; + const map = this.map; + const reduce = this.reduce; + let options = this.options; + + const mapCommandHash: Document = { + mapReduce: coll.collectionName, + map: map, + reduce: reduce + }; + + if (options.scope) { + mapCommandHash.scope = processScope(options.scope); + } + + // Add any other options passed in + for (const n in options) { + // Only include if not in exclusion list + if (exclusionList.indexOf(n) === -1) { + mapCommandHash[n] = (options as any)[n]; + } + } + + options = Object.assign({}, options); + + // If we have a read preference and inline is not set as output fail hard + if ( + this.readPreference.mode === ReadPreferenceMode.primary && + options.out && + (options.out as any).inline !== 1 && + options.out !== 'inline' + ) { + // Force readPreference to primary + options.readPreference = ReadPreference.primary; + // Decorate command with writeConcern if supported + applyWriteConcern(mapCommandHash, { db: coll.s.db, collection: coll }, options); + } else { + decorateWithReadConcern(mapCommandHash, coll, options); + } + + // Is bypassDocumentValidation specified + if (options.bypassDocumentValidation === true) { + mapCommandHash.bypassDocumentValidation = options.bypassDocumentValidation; + } + + // Have we specified collation + try { + decorateWithCollation(mapCommandHash, coll, options); + } catch (err) { + return callback(err); + } + + if (this.explain && maxWireVersion(server) < 9) { + callback( + new MongoCompatibilityError(`Server ${server.name} does not support explain on mapReduce`) + ); + return; + } + + // Execute command + super.executeCommand(server, session, mapCommandHash, (err, result) => { + if (err) return callback(err); + // Check if we have an error + if (1 !== result.ok || result.err || result.errmsg) { + return callback(new MongoServerError(result)); + } + + // If an explain option was executed, don't process the server results + if (this.explain) return callback(undefined, result); + + // Create statistics value + const stats: MapReduceStats = {}; + if (result.timeMillis) stats['processtime'] = result.timeMillis; + if (result.counts) stats['counts'] = result.counts; + if (result.timing) stats['timing'] = result.timing; + + // invoked with inline? + if (result.results) { + // If we wish for no verbosity + if (options['verbose'] == null || !options['verbose']) { + return callback(undefined, result.results); + } + + return callback(undefined, { results: result.results, stats: stats }); + } + + // The returned collection + let collection = null; + + // If we have an object it's a different db + if (result.result != null && typeof result.result === 'object') { + const doc = result.result; + // Return a collection from another db + collection = coll.s.db.s.client.db(doc.db, coll.s.db.s.options).collection(doc.collection); + } else { + // Create a collection object that wraps the result collection + collection = coll.s.db.collection(result.result); + } + + // If we wish for no verbosity + if (options['verbose'] == null || !options['verbose']) { + return callback(err, collection); + } + + // Return stats as third set of values + callback(err, { collection, stats }); + }); + } +} + +/** Functions that are passed as scope args must be converted to Code instances. */ +function processScope(scope: Document | ObjectId) { + if (!isObject(scope) || (scope as any)._bsontype === 'ObjectID') { + return scope; + } + + const newScope: Document = {}; + + for (const key of Object.keys(scope)) { + if ('function' === typeof (scope as Document)[key]) { + newScope[key] = new Code(String((scope as Document)[key])); + } else if ((scope as Document)[key]._bsontype === 'Code') { + newScope[key] = (scope as Document)[key]; + } else { + newScope[key] = processScope((scope as Document)[key]); + } + } + + return newScope; +} + +defineAspects(MapReduceOperation, [Aspect.EXPLAINABLE]); diff --git a/ts-ticket-office-service/node_modules/mongodb/src/operations/operation.ts b/ts-ticket-office-service/node_modules/mongodb/src/operations/operation.ts new file mode 100644 index 000000000..0b5c52487 --- /dev/null +++ b/ts-ticket-office-service/node_modules/mongodb/src/operations/operation.ts @@ -0,0 +1,125 @@ +import { BSONSerializeOptions, Document, resolveBSONOptions } from '../bson'; +import { ReadPreference, ReadPreferenceLike } from '../read_preference'; +import type { Server } from '../sdam/server'; +import type { ClientSession } from '../sessions'; +import type { Callback, MongoDBNamespace } from '../utils'; + +export const Aspect = { + READ_OPERATION: Symbol('READ_OPERATION'), + WRITE_OPERATION: Symbol('WRITE_OPERATION'), + RETRYABLE: Symbol('RETRYABLE'), + EXPLAINABLE: Symbol('EXPLAINABLE'), + SKIP_COLLATION: Symbol('SKIP_COLLATION'), + CURSOR_CREATING: Symbol('CURSOR_CREATING'), + MUST_SELECT_SAME_SERVER: Symbol('MUST_SELECT_SAME_SERVER') +} as const; + +/** @public */ +export type Hint = string | Document; + +export interface OperationConstructor extends Function { + aspects?: Set; +} + +/** @public */ +export interface OperationOptions extends BSONSerializeOptions { + /** Specify ClientSession for this command */ + session?: ClientSession; + willRetryWrite?: boolean; + + /** The preferred read preference (ReadPreference.primary, ReadPreference.primary_preferred, ReadPreference.secondary, ReadPreference.secondary_preferred, ReadPreference.nearest). */ + readPreference?: ReadPreferenceLike; + + /** @internal Hints to `executeOperation` that this operation should not unpin on an ended transaction */ + bypassPinningCheck?: boolean; + omitReadPreference?: boolean; +} + +/** @internal */ +const kSession = Symbol('session'); + +/** + * This class acts as a parent class for any operation and is responsible for setting this.options, + * as well as setting and getting a session. + * Additionally, this class implements `hasAspect`, which determines whether an operation has + * a specific aspect. + * @internal + */ +export abstract class AbstractOperation { + ns!: MongoDBNamespace; + cmd!: Document; + readPreference: ReadPreference; + server!: Server; + bypassPinningCheck: boolean; + trySecondaryWrite: boolean; + + // BSON serialization options + bsonOptions?: BSONSerializeOptions; + + options: OperationOptions; + + [kSession]: ClientSession | undefined; + + constructor(options: OperationOptions = {}) { + this.readPreference = this.hasAspect(Aspect.WRITE_OPERATION) + ? ReadPreference.primary + : ReadPreference.fromOptions(options) ?? ReadPreference.primary; + + // Pull the BSON serialize options from the already-resolved options + this.bsonOptions = resolveBSONOptions(options); + + this[kSession] = options.session != null ? options.session : undefined; + + this.options = options; + this.bypassPinningCheck = !!options.bypassPinningCheck; + this.trySecondaryWrite = false; + } + + abstract execute( + server: Server, + session: ClientSession | undefined, + callback: Callback + ): void; + + hasAspect(aspect: symbol): boolean { + const ctor = this.constructor as OperationConstructor; + if (ctor.aspects == null) { + return false; + } + + return ctor.aspects.has(aspect); + } + + get session(): ClientSession | undefined { + return this[kSession]; + } + + clearSession() { + this[kSession] = undefined; + } + + get canRetryRead(): boolean { + return true; + } + + get canRetryWrite(): boolean { + return true; + } +} + +export function defineAspects( + operation: OperationConstructor, + aspects: symbol | symbol[] | Set +): Set { + if (!Array.isArray(aspects) && !(aspects instanceof Set)) { + aspects = [aspects]; + } + + aspects = new Set(aspects); + Object.defineProperty(operation, 'aspects', { + value: aspects, + writable: false + }); + + return aspects; +} diff --git a/ts-ticket-office-service/node_modules/mongodb/src/operations/options_operation.ts b/ts-ticket-office-service/node_modules/mongodb/src/operations/options_operation.ts new file mode 100644 index 000000000..27853d34e --- /dev/null +++ b/ts-ticket-office-service/node_modules/mongodb/src/operations/options_operation.ts @@ -0,0 +1,42 @@ +import type { Document } from '../bson'; +import type { Collection } from '../collection'; +import { MongoAPIError } from '../error'; +import type { Server } from '../sdam/server'; +import type { ClientSession } from '../sessions'; +import type { Callback } from '../utils'; +import { AbstractOperation, OperationOptions } from './operation'; + +/** @internal */ +export class OptionsOperation extends AbstractOperation { + override options: OperationOptions; + collection: Collection; + + constructor(collection: Collection, options: OperationOptions) { + super(options); + this.options = options; + this.collection = collection; + } + + override execute( + server: Server, + session: ClientSession | undefined, + callback: Callback + ): void { + const coll = this.collection; + + coll.s.db + .listCollections( + { name: coll.collectionName }, + { ...this.options, nameOnly: false, readPreference: this.readPreference, session } + ) + .toArray((err, collections) => { + if (err || !collections) return callback(err); + if (collections.length === 0) { + // TODO(NODE-3485) + return callback(new MongoAPIError(`collection ${coll.namespace} not found`)); + } + + callback(err, collections[0].options); + }); + } +} diff --git a/ts-ticket-office-service/node_modules/mongodb/src/operations/profiling_level.ts b/ts-ticket-office-service/node_modules/mongodb/src/operations/profiling_level.ts new file mode 100644 index 000000000..defe6b0d5 --- /dev/null +++ b/ts-ticket-office-service/node_modules/mongodb/src/operations/profiling_level.ts @@ -0,0 +1,39 @@ +import type { Db } from '../db'; +import { MongoRuntimeError } from '../error'; +import type { Server } from '../sdam/server'; +import type { ClientSession } from '../sessions'; +import type { Callback } from '../utils'; +import { CommandOperation, CommandOperationOptions } from './command'; + +/** @public */ +export type ProfilingLevelOptions = CommandOperationOptions; + +/** @internal */ +export class ProfilingLevelOperation extends CommandOperation { + override options: ProfilingLevelOptions; + + constructor(db: Db, options: ProfilingLevelOptions) { + super(db, options); + this.options = options; + } + + override execute( + server: Server, + session: ClientSession | undefined, + callback: Callback + ): void { + super.executeCommand(server, session, { profile: -1 }, (err, doc) => { + if (err == null && doc.ok === 1) { + const was = doc.was; + if (was === 0) return callback(undefined, 'off'); + if (was === 1) return callback(undefined, 'slow_only'); + if (was === 2) return callback(undefined, 'all'); + // TODO(NODE-3483) + return callback(new MongoRuntimeError(`Illegal profiling level value ${was}`)); + } else { + // TODO(NODE-3483): Consider MongoUnexpectedServerResponseError + err != null ? callback(err) : callback(new MongoRuntimeError('Error with profile command')); + } + }); + } +} diff --git a/ts-ticket-office-service/node_modules/mongodb/src/operations/remove_user.ts b/ts-ticket-office-service/node_modules/mongodb/src/operations/remove_user.ts new file mode 100644 index 000000000..f32c19c24 --- /dev/null +++ b/ts-ticket-office-service/node_modules/mongodb/src/operations/remove_user.ts @@ -0,0 +1,33 @@ +import type { Db } from '../db'; +import type { Server } from '../sdam/server'; +import type { ClientSession } from '../sessions'; +import type { Callback } from '../utils'; +import { CommandOperation, CommandOperationOptions } from './command'; +import { Aspect, defineAspects } from './operation'; + +/** @public */ +export type RemoveUserOptions = CommandOperationOptions; + +/** @internal */ +export class RemoveUserOperation extends CommandOperation { + override options: RemoveUserOptions; + username: string; + + constructor(db: Db, username: string, options: RemoveUserOptions) { + super(db, options); + this.options = options; + this.username = username; + } + + override execute( + server: Server, + session: ClientSession | undefined, + callback: Callback + ): void { + super.executeCommand(server, session, { dropUser: this.username }, err => { + callback(err, err ? false : true); + }); + } +} + +defineAspects(RemoveUserOperation, [Aspect.WRITE_OPERATION]); diff --git a/ts-ticket-office-service/node_modules/mongodb/src/operations/rename.ts b/ts-ticket-office-service/node_modules/mongodb/src/operations/rename.ts new file mode 100644 index 000000000..02e27a5bf --- /dev/null +++ b/ts-ticket-office-service/node_modules/mongodb/src/operations/rename.ts @@ -0,0 +1,67 @@ +import type { Document } from '../bson'; +import { Collection } from '../collection'; +import { MongoServerError } from '../error'; +import type { Server } from '../sdam/server'; +import type { ClientSession } from '../sessions'; +import { Callback, checkCollectionName } from '../utils'; +import type { CommandOperationOptions } from './command'; +import { Aspect, defineAspects } from './operation'; +import { RunAdminCommandOperation } from './run_command'; + +/** @public */ +export interface RenameOptions extends CommandOperationOptions { + /** Drop the target name collection if it previously exists. */ + dropTarget?: boolean; + /** Unclear */ + new_collection?: boolean; +} + +/** @internal */ +export class RenameOperation extends RunAdminCommandOperation { + override options: RenameOptions; + collection: Collection; + newName: string; + + constructor(collection: Collection, newName: string, options: RenameOptions) { + // Check the collection name + checkCollectionName(newName); + + // Build the command + const renameCollection = collection.namespace; + const toCollection = collection.s.namespace.withCollection(newName).toString(); + const dropTarget = typeof options.dropTarget === 'boolean' ? options.dropTarget : false; + const cmd = { renameCollection: renameCollection, to: toCollection, dropTarget: dropTarget }; + + super(collection, cmd, options); + this.options = options; + this.collection = collection; + this.newName = newName; + } + + override execute( + server: Server, + session: ClientSession | undefined, + callback: Callback + ): void { + const coll = this.collection; + + super.execute(server, session, (err, doc) => { + if (err) return callback(err); + // We have an error + if (doc?.errmsg) { + return callback(new MongoServerError(doc)); + } + + let newColl: Collection; + try { + newColl = new Collection(coll.s.db, this.newName, coll.s.options); + } catch (err) { + return callback(err); + } + + return callback(undefined, newColl); + }); + } +} + +defineAspects(RenameOperation, [Aspect.WRITE_OPERATION]); diff --git a/ts-ticket-office-service/node_modules/mongodb/src/operations/run_command.ts b/ts-ticket-office-service/node_modules/mongodb/src/operations/run_command.ts new file mode 100644 index 000000000..b92237a9a --- /dev/null +++ b/ts-ticket-office-service/node_modules/mongodb/src/operations/run_command.ts @@ -0,0 +1,36 @@ +import type { Document } from '../bson'; +import type { Server } from '../sdam/server'; +import type { ClientSession } from '../sessions'; +import { Callback, MongoDBNamespace } from '../utils'; +import { CommandOperation, CommandOperationOptions, OperationParent } from './command'; + +/** @public */ +export type RunCommandOptions = CommandOperationOptions; + +/** @internal */ +export class RunCommandOperation extends CommandOperation { + override options: RunCommandOptions; + command: Document; + + constructor(parent: OperationParent | undefined, command: Document, options?: RunCommandOptions) { + super(parent, options); + this.options = options ?? {}; + this.command = command; + } + + override execute( + server: Server, + session: ClientSession | undefined, + callback: Callback + ): void { + const command = this.command; + this.executeCommand(server, session, command, callback); + } +} + +export class RunAdminCommandOperation extends RunCommandOperation { + constructor(parent: OperationParent | undefined, command: Document, options?: RunCommandOptions) { + super(parent, command, options); + this.ns = new MongoDBNamespace('admin'); + } +} diff --git a/ts-ticket-office-service/node_modules/mongodb/src/operations/set_profiling_level.ts b/ts-ticket-office-service/node_modules/mongodb/src/operations/set_profiling_level.ts new file mode 100644 index 000000000..6fc8502dc --- /dev/null +++ b/ts-ticket-office-service/node_modules/mongodb/src/operations/set_profiling_level.ts @@ -0,0 +1,74 @@ +import type { Db } from '../db'; +import { MongoInvalidArgumentError, MongoRuntimeError } from '../error'; +import type { Server } from '../sdam/server'; +import type { ClientSession } from '../sessions'; +import type { Callback } from '../utils'; +import { enumToString } from '../utils'; +import { CommandOperation, CommandOperationOptions } from './command'; + +const levelValues = new Set(['off', 'slow_only', 'all']); + +/** @public */ +export const ProfilingLevel = Object.freeze({ + off: 'off', + slowOnly: 'slow_only', + all: 'all' +} as const); + +/** @public */ +export type ProfilingLevel = typeof ProfilingLevel[keyof typeof ProfilingLevel]; + +/** @public */ +export type SetProfilingLevelOptions = CommandOperationOptions; + +/** @internal */ +export class SetProfilingLevelOperation extends CommandOperation { + override options: SetProfilingLevelOptions; + level: ProfilingLevel; + profile: 0 | 1 | 2; + + constructor(db: Db, level: ProfilingLevel, options: SetProfilingLevelOptions) { + super(db, options); + this.options = options; + switch (level) { + case ProfilingLevel.off: + this.profile = 0; + break; + case ProfilingLevel.slowOnly: + this.profile = 1; + break; + case ProfilingLevel.all: + this.profile = 2; + break; + default: + this.profile = 0; + break; + } + + this.level = level; + } + + override execute( + server: Server, + session: ClientSession | undefined, + callback: Callback + ): void { + const level = this.level; + + if (!levelValues.has(level)) { + return callback( + new MongoInvalidArgumentError( + `Profiling level must be one of "${enumToString(ProfilingLevel)}"` + ) + ); + } + + // TODO(NODE-3483): Determine error to put here + super.executeCommand(server, session, { profile: this.profile }, (err, doc) => { + if (err == null && doc.ok === 1) return callback(undefined, level); + return err != null + ? callback(err) + : callback(new MongoRuntimeError('Error with profile command')); + }); + } +} diff --git a/ts-ticket-office-service/node_modules/mongodb/src/operations/stats.ts b/ts-ticket-office-service/node_modules/mongodb/src/operations/stats.ts new file mode 100644 index 000000000..b63a70de3 --- /dev/null +++ b/ts-ticket-office-service/node_modules/mongodb/src/operations/stats.ts @@ -0,0 +1,271 @@ +import type { Document } from '../bson'; +import type { Collection } from '../collection'; +import type { Db } from '../db'; +import type { Server } from '../sdam/server'; +import type { ClientSession } from '../sessions'; +import type { Callback } from '../utils'; +import { CommandOperation, CommandOperationOptions } from './command'; +import { Aspect, defineAspects } from './operation'; + +/** @public */ +export interface CollStatsOptions extends CommandOperationOptions { + /** Divide the returned sizes by scale value. */ + scale?: number; +} + +/** + * Get all the collection statistics. + * @internal + */ +export class CollStatsOperation extends CommandOperation { + override options: CollStatsOptions; + collectionName: string; + + /** + * Construct a Stats operation. + * + * @param collection - Collection instance + * @param options - Optional settings. See Collection.prototype.stats for a list of options. + */ + constructor(collection: Collection, options?: CollStatsOptions) { + super(collection, options); + this.options = options ?? {}; + this.collectionName = collection.collectionName; + } + + override execute( + server: Server, + session: ClientSession | undefined, + callback: Callback + ): void { + const command: Document = { collStats: this.collectionName }; + if (this.options.scale != null) { + command.scale = this.options.scale; + } + + super.executeCommand(server, session, command, callback); + } +} + +/** @public */ +export interface DbStatsOptions extends CommandOperationOptions { + /** Divide the returned sizes by scale value. */ + scale?: number; +} + +/** @internal */ +export class DbStatsOperation extends CommandOperation { + override options: DbStatsOptions; + + constructor(db: Db, options: DbStatsOptions) { + super(db, options); + this.options = options; + } + + override execute( + server: Server, + session: ClientSession | undefined, + callback: Callback + ): void { + const command: Document = { dbStats: true }; + if (this.options.scale != null) { + command.scale = this.options.scale; + } + + super.executeCommand(server, session, command, callback); + } +} + +/** + * @public + * @see https://docs.mongodb.org/manual/reference/command/collStats/ + */ +export interface CollStats extends Document { + /** Namespace */ + ns: string; + /** Number of documents */ + count: number; + /** Collection size in bytes */ + size: number; + /** Average object size in bytes */ + avgObjSize: number; + /** (Pre)allocated space for the collection in bytes */ + storageSize: number; + /** Number of extents (contiguously allocated chunks of datafile space) */ + numExtents: number; + /** Number of indexes */ + nindexes: number; + /** Size of the most recently created extent in bytes */ + lastExtentSize: number; + /** Padding can speed up updates if documents grow */ + paddingFactor: number; + /** A number that indicates the user-set flags on the collection. userFlags only appears when using the mmapv1 storage engine */ + userFlags?: number; + /** Total index size in bytes */ + totalIndexSize: number; + /** Size of specific indexes in bytes */ + indexSizes: { + _id_: number; + [index: string]: number; + }; + /** `true` if the collection is capped */ + capped: boolean; + /** The maximum number of documents that may be present in a capped collection */ + max: number; + /** The maximum size of a capped collection */ + maxSize: number; + /** This document contains data reported directly by the WiredTiger engine and other data for internal diagnostic use */ + wiredTiger?: WiredTigerData; + /** The fields in this document are the names of the indexes, while the values themselves are documents that contain statistics for the index provided by the storage engine */ + indexDetails?: any; + ok: number; + + /** The amount of storage available for reuse. The scale argument affects this value. */ + freeStorageSize?: number; + /** An array that contains the names of the indexes that are currently being built on the collection */ + indexBuilds?: number; + /** The sum of the storageSize and totalIndexSize. The scale argument affects this value */ + totalSize: number; + /** The scale value used by the command. */ + scaleFactor: number; +} + +/** @public */ +export interface WiredTigerData extends Document { + LSM: { + 'bloom filter false positives': number; + 'bloom filter hits': number; + 'bloom filter misses': number; + 'bloom filter pages evicted from cache': number; + 'bloom filter pages read into cache': number; + 'bloom filters in the LSM tree': number; + 'chunks in the LSM tree': number; + 'highest merge generation in the LSM tree': number; + 'queries that could have benefited from a Bloom filter that did not exist': number; + 'sleep for LSM checkpoint throttle': number; + 'sleep for LSM merge throttle': number; + 'total size of bloom filters': number; + } & Document; + 'block-manager': { + 'allocations requiring file extension': number; + 'blocks allocated': number; + 'blocks freed': number; + 'checkpoint size': number; + 'file allocation unit size': number; + 'file bytes available for reuse': number; + 'file magic number': number; + 'file major version number': number; + 'file size in bytes': number; + 'minor version number': number; + }; + btree: { + 'btree checkpoint generation': number; + 'column-store fixed-size leaf pages': number; + 'column-store internal pages': number; + 'column-store variable-size RLE encoded values': number; + 'column-store variable-size deleted values': number; + 'column-store variable-size leaf pages': number; + 'fixed-record size': number; + 'maximum internal page key size': number; + 'maximum internal page size': number; + 'maximum leaf page key size': number; + 'maximum leaf page size': number; + 'maximum leaf page value size': number; + 'maximum tree depth': number; + 'number of key/value pairs': number; + 'overflow pages': number; + 'pages rewritten by compaction': number; + 'row-store internal pages': number; + 'row-store leaf pages': number; + } & Document; + cache: { + 'bytes currently in the cache': number; + 'bytes read into cache': number; + 'bytes written from cache': number; + 'checkpoint blocked page eviction': number; + 'data source pages selected for eviction unable to be evicted': number; + 'hazard pointer blocked page eviction': number; + 'in-memory page passed criteria to be split': number; + 'in-memory page splits': number; + 'internal pages evicted': number; + 'internal pages split during eviction': number; + 'leaf pages split during eviction': number; + 'modified pages evicted': number; + 'overflow pages read into cache': number; + 'overflow values cached in memory': number; + 'page split during eviction deepened the tree': number; + 'page written requiring lookaside records': number; + 'pages read into cache': number; + 'pages read into cache requiring lookaside entries': number; + 'pages requested from the cache': number; + 'pages written from cache': number; + 'pages written requiring in-memory restoration': number; + 'tracked dirty bytes in the cache': number; + 'unmodified pages evicted': number; + } & Document; + cache_walk: { + 'Average difference between current eviction generation when the page was last considered': number; + 'Average on-disk page image size seen': number; + 'Clean pages currently in cache': number; + 'Current eviction generation': number; + 'Dirty pages currently in cache': number; + 'Entries in the root page': number; + 'Internal pages currently in cache': number; + 'Leaf pages currently in cache': number; + 'Maximum difference between current eviction generation when the page was last considered': number; + 'Maximum page size seen': number; + 'Minimum on-disk page image size seen': number; + 'On-disk page image sizes smaller than a single allocation unit': number; + 'Pages created in memory and never written': number; + 'Pages currently queued for eviction': number; + 'Pages that could not be queued for eviction': number; + 'Refs skipped during cache traversal': number; + 'Size of the root page': number; + 'Total number of pages currently in cache': number; + } & Document; + compression: { + 'compressed pages read': number; + 'compressed pages written': number; + 'page written failed to compress': number; + 'page written was too small to compress': number; + 'raw compression call failed, additional data available': number; + 'raw compression call failed, no additional data available': number; + 'raw compression call succeeded': number; + } & Document; + cursor: { + 'bulk-loaded cursor-insert calls': number; + 'create calls': number; + 'cursor-insert key and value bytes inserted': number; + 'cursor-remove key bytes removed': number; + 'cursor-update value bytes updated': number; + 'insert calls': number; + 'next calls': number; + 'prev calls': number; + 'remove calls': number; + 'reset calls': number; + 'restarted searches': number; + 'search calls': number; + 'search near calls': number; + 'truncate calls': number; + 'update calls': number; + }; + reconciliation: { + 'dictionary matches': number; + 'fast-path pages deleted': number; + 'internal page key bytes discarded using suffix compression': number; + 'internal page multi-block writes': number; + 'internal-page overflow keys': number; + 'leaf page key bytes discarded using prefix compression': number; + 'leaf page multi-block writes': number; + 'leaf-page overflow keys': number; + 'maximum blocks required for a page': number; + 'overflow values written': number; + 'page checksum matches': number; + 'page reconciliation calls': number; + 'page reconciliation calls for eviction': number; + 'pages deleted': number; + } & Document; +} + +defineAspects(CollStatsOperation, [Aspect.READ_OPERATION]); +defineAspects(DbStatsOperation, [Aspect.READ_OPERATION]); diff --git a/ts-ticket-office-service/node_modules/mongodb/src/operations/update.ts b/ts-ticket-office-service/node_modules/mongodb/src/operations/update.ts new file mode 100644 index 000000000..a389878a1 --- /dev/null +++ b/ts-ticket-office-service/node_modules/mongodb/src/operations/update.ts @@ -0,0 +1,334 @@ +import type { Document, ObjectId } from '../bson'; +import type { Collection } from '../collection'; +import { MongoCompatibilityError, MongoInvalidArgumentError, MongoServerError } from '../error'; +import type { Server } from '../sdam/server'; +import type { ClientSession } from '../sessions'; +import { + Callback, + collationNotSupported, + hasAtomicOperators, + maxWireVersion, + MongoDBNamespace +} from '../utils'; +import { CollationOptions, CommandOperation, CommandOperationOptions } from './command'; +import { Aspect, defineAspects, Hint } from './operation'; + +/** @public */ +export interface UpdateOptions extends CommandOperationOptions { + /** A set of filters specifying to which array elements an update should apply */ + arrayFilters?: Document[]; + /** If true, allows the write to opt-out of document level validation */ + bypassDocumentValidation?: boolean; + /** Specifies a collation */ + collation?: CollationOptions; + /** Specify that the update query should only consider plans using the hinted index */ + hint?: string | Document; + /** When true, creates a new document if no document matches the query */ + upsert?: boolean; + /** Map of parameter names and values that can be accessed using $$var (requires MongoDB 5.0). */ + let?: Document; +} + +/** @public */ +export interface UpdateResult { + /** Indicates whether this write result was acknowledged. If not, then all other members of this result will be undefined */ + acknowledged: boolean; + /** The number of documents that matched the filter */ + matchedCount: number; + /** The number of documents that were modified */ + modifiedCount: number; + /** The number of documents that were upserted */ + upsertedCount: number; + /** The identifier of the inserted document if an upsert took place */ + upsertedId: ObjectId; +} + +/** @public */ +export interface UpdateStatement { + /** The query that matches documents to update. */ + q: Document; + /** The modifications to apply. */ + u: Document | Document[]; + /** If true, perform an insert if no documents match the query. */ + upsert?: boolean; + /** If true, updates all documents that meet the query criteria. */ + multi?: boolean; + /** Specifies the collation to use for the operation. */ + collation?: CollationOptions; + /** An array of filter documents that determines which array elements to modify for an update operation on an array field. */ + arrayFilters?: Document[]; + /** A document or string that specifies the index to use to support the query predicate. */ + hint?: Hint; +} + +/** @internal */ +export class UpdateOperation extends CommandOperation { + override options: UpdateOptions & { ordered?: boolean }; + statements: UpdateStatement[]; + + constructor( + ns: MongoDBNamespace, + statements: UpdateStatement[], + options: UpdateOptions & { ordered?: boolean } + ) { + super(undefined, options); + this.options = options; + this.ns = ns; + + this.statements = statements; + } + + override get canRetryWrite(): boolean { + if (super.canRetryWrite === false) { + return false; + } + + return this.statements.every(op => op.multi == null || op.multi === false); + } + + override execute( + server: Server, + session: ClientSession | undefined, + callback: Callback + ): void { + const options = this.options ?? {}; + const ordered = typeof options.ordered === 'boolean' ? options.ordered : true; + const command: Document = { + update: this.ns.collection, + updates: this.statements, + ordered + }; + + if (typeof options.bypassDocumentValidation === 'boolean') { + command.bypassDocumentValidation = options.bypassDocumentValidation; + } + + if (options.let) { + command.let = options.let; + } + + // we check for undefined specifically here to allow falsy values + // eslint-disable-next-line no-restricted-syntax + if (options.comment !== undefined) { + command.comment = options.comment; + } + + const statementWithCollation = this.statements.find(statement => !!statement.collation); + if ( + collationNotSupported(server, options) || + (statementWithCollation && collationNotSupported(server, statementWithCollation)) + ) { + callback(new MongoCompatibilityError(`Server ${server.name} does not support collation`)); + return; + } + + const unacknowledgedWrite = this.writeConcern && this.writeConcern.w === 0; + if (unacknowledgedWrite || maxWireVersion(server) < 5) { + if (this.statements.find((o: Document) => o.hint)) { + callback(new MongoCompatibilityError(`Servers < 3.4 do not support hint on update`)); + return; + } + } + + if (this.explain && maxWireVersion(server) < 3) { + callback( + new MongoCompatibilityError(`Server ${server.name} does not support explain on update`) + ); + return; + } + + if (this.statements.some(statement => !!statement.arrayFilters) && maxWireVersion(server) < 6) { + callback( + new MongoCompatibilityError('Option "arrayFilters" is only supported on MongoDB 3.6+') + ); + return; + } + + super.executeCommand(server, session, command, callback); + } +} + +/** @internal */ +export class UpdateOneOperation extends UpdateOperation { + constructor(collection: Collection, filter: Document, update: Document, options: UpdateOptions) { + super( + collection.s.namespace, + [makeUpdateStatement(filter, update, { ...options, multi: false })], + options + ); + + if (!hasAtomicOperators(update)) { + throw new MongoInvalidArgumentError('Update document requires atomic operators'); + } + } + + override execute( + server: Server, + session: ClientSession | undefined, + callback: Callback + ): void { + super.execute(server, session, (err, res) => { + if (err || !res) return callback(err); + if (this.explain != null) return callback(undefined, res); + if (res.code) return callback(new MongoServerError(res)); + if (res.writeErrors) return callback(new MongoServerError(res.writeErrors[0])); + + callback(undefined, { + acknowledged: this.writeConcern?.w !== 0 ?? true, + modifiedCount: res.nModified != null ? res.nModified : res.n, + upsertedId: + Array.isArray(res.upserted) && res.upserted.length > 0 ? res.upserted[0]._id : null, + upsertedCount: Array.isArray(res.upserted) && res.upserted.length ? res.upserted.length : 0, + matchedCount: Array.isArray(res.upserted) && res.upserted.length > 0 ? 0 : res.n + }); + }); + } +} + +/** @internal */ +export class UpdateManyOperation extends UpdateOperation { + constructor(collection: Collection, filter: Document, update: Document, options: UpdateOptions) { + super( + collection.s.namespace, + [makeUpdateStatement(filter, update, { ...options, multi: true })], + options + ); + + if (!hasAtomicOperators(update)) { + throw new MongoInvalidArgumentError('Update document requires atomic operators'); + } + } + + override execute( + server: Server, + session: ClientSession | undefined, + callback: Callback + ): void { + super.execute(server, session, (err, res) => { + if (err || !res) return callback(err); + if (this.explain != null) return callback(undefined, res); + if (res.code) return callback(new MongoServerError(res)); + if (res.writeErrors) return callback(new MongoServerError(res.writeErrors[0])); + + callback(undefined, { + acknowledged: this.writeConcern?.w !== 0 ?? true, + modifiedCount: res.nModified != null ? res.nModified : res.n, + upsertedId: + Array.isArray(res.upserted) && res.upserted.length > 0 ? res.upserted[0]._id : null, + upsertedCount: Array.isArray(res.upserted) && res.upserted.length ? res.upserted.length : 0, + matchedCount: Array.isArray(res.upserted) && res.upserted.length > 0 ? 0 : res.n + }); + }); + } +} + +/** @public */ +export interface ReplaceOptions extends CommandOperationOptions { + /** If true, allows the write to opt-out of document level validation */ + bypassDocumentValidation?: boolean; + /** Specifies a collation */ + collation?: CollationOptions; + /** Specify that the update query should only consider plans using the hinted index */ + hint?: string | Document; + /** When true, creates a new document if no document matches the query */ + upsert?: boolean; + /** Map of parameter names and values that can be accessed using $$var (requires MongoDB 5.0). */ + let?: Document; +} + +/** @internal */ +export class ReplaceOneOperation extends UpdateOperation { + constructor( + collection: Collection, + filter: Document, + replacement: Document, + options: ReplaceOptions + ) { + super( + collection.s.namespace, + [makeUpdateStatement(filter, replacement, { ...options, multi: false })], + options + ); + + if (hasAtomicOperators(replacement)) { + throw new MongoInvalidArgumentError('Replacement document must not contain atomic operators'); + } + } + + override execute( + server: Server, + session: ClientSession | undefined, + callback: Callback + ): void { + super.execute(server, session, (err, res) => { + if (err || !res) return callback(err); + if (this.explain != null) return callback(undefined, res); + if (res.code) return callback(new MongoServerError(res)); + if (res.writeErrors) return callback(new MongoServerError(res.writeErrors[0])); + + callback(undefined, { + acknowledged: this.writeConcern?.w !== 0 ?? true, + modifiedCount: res.nModified != null ? res.nModified : res.n, + upsertedId: + Array.isArray(res.upserted) && res.upserted.length > 0 ? res.upserted[0]._id : null, + upsertedCount: Array.isArray(res.upserted) && res.upserted.length ? res.upserted.length : 0, + matchedCount: Array.isArray(res.upserted) && res.upserted.length > 0 ? 0 : res.n + }); + }); + } +} + +export function makeUpdateStatement( + filter: Document, + update: Document, + options: UpdateOptions & { multi?: boolean } +): UpdateStatement { + if (filter == null || typeof filter !== 'object') { + throw new MongoInvalidArgumentError('Selector must be a valid JavaScript object'); + } + + if (update == null || typeof update !== 'object') { + throw new MongoInvalidArgumentError('Document must be a valid JavaScript object'); + } + + const op: UpdateStatement = { q: filter, u: update }; + if (typeof options.upsert === 'boolean') { + op.upsert = options.upsert; + } + + if (options.multi) { + op.multi = options.multi; + } + + if (options.hint) { + op.hint = options.hint; + } + + if (options.arrayFilters) { + op.arrayFilters = options.arrayFilters; + } + + if (options.collation) { + op.collation = options.collation; + } + + return op; +} + +defineAspects(UpdateOperation, [Aspect.RETRYABLE, Aspect.WRITE_OPERATION, Aspect.SKIP_COLLATION]); +defineAspects(UpdateOneOperation, [ + Aspect.RETRYABLE, + Aspect.WRITE_OPERATION, + Aspect.EXPLAINABLE, + Aspect.SKIP_COLLATION +]); +defineAspects(UpdateManyOperation, [ + Aspect.WRITE_OPERATION, + Aspect.EXPLAINABLE, + Aspect.SKIP_COLLATION +]); +defineAspects(ReplaceOneOperation, [ + Aspect.RETRYABLE, + Aspect.WRITE_OPERATION, + Aspect.SKIP_COLLATION +]); diff --git a/ts-ticket-office-service/node_modules/mongodb/src/operations/validate_collection.ts b/ts-ticket-office-service/node_modules/mongodb/src/operations/validate_collection.ts new file mode 100644 index 000000000..ba6c85fad --- /dev/null +++ b/ts-ticket-office-service/node_modules/mongodb/src/operations/validate_collection.ts @@ -0,0 +1,59 @@ +import type { Admin } from '../admin'; +import type { Document } from '../bson'; +import { MongoRuntimeError } from '../error'; +import type { Server } from '../sdam/server'; +import type { ClientSession } from '../sessions'; +import type { Callback } from '../utils'; +import { CommandOperation, CommandOperationOptions } from './command'; + +/** @public */ +export interface ValidateCollectionOptions extends CommandOperationOptions { + /** Validates a collection in the background, without interrupting read or write traffic (only in MongoDB 4.4+) */ + background?: boolean; +} + +/** @internal */ +export class ValidateCollectionOperation extends CommandOperation { + override options: ValidateCollectionOptions; + collectionName: string; + command: Document; + + constructor(admin: Admin, collectionName: string, options: ValidateCollectionOptions) { + // Decorate command with extra options + const command: Document = { validate: collectionName }; + const keys = Object.keys(options); + for (let i = 0; i < keys.length; i++) { + if (Object.prototype.hasOwnProperty.call(options, keys[i]) && keys[i] !== 'session') { + command[keys[i]] = (options as Document)[keys[i]]; + } + } + + super(admin.s.db, options); + this.options = options; + this.command = command; + this.collectionName = collectionName; + } + + override execute( + server: Server, + session: ClientSession | undefined, + callback: Callback + ): void { + const collectionName = this.collectionName; + + super.executeCommand(server, session, this.command, (err, doc) => { + if (err != null) return callback(err); + + // TODO(NODE-3483): Replace these with MongoUnexpectedServerResponseError + if (doc.ok === 0) return callback(new MongoRuntimeError('Error with validate command')); + if (doc.result != null && typeof doc.result !== 'string') + return callback(new MongoRuntimeError('Error with validation data')); + if (doc.result != null && doc.result.match(/exception|corrupt/) != null) + return callback(new MongoRuntimeError(`Invalid collection ${collectionName}`)); + if (doc.valid != null && !doc.valid) + return callback(new MongoRuntimeError(`Invalid collection ${collectionName}`)); + + return callback(undefined, doc); + }); + } +} diff --git a/ts-ticket-office-service/node_modules/mongodb/src/promise_provider.ts b/ts-ticket-office-service/node_modules/mongodb/src/promise_provider.ts new file mode 100644 index 000000000..a6aeb548e --- /dev/null +++ b/ts-ticket-office-service/node_modules/mongodb/src/promise_provider.ts @@ -0,0 +1,41 @@ +import { MongoInvalidArgumentError } from './error'; + +/** @internal */ +const kPromise = Symbol('promise'); + +interface PromiseStore { + [kPromise]?: PromiseConstructor; +} + +const store: PromiseStore = { + [kPromise]: undefined +}; + +/** + * Global promise store allowing user-provided promises + * @public + */ +export class PromiseProvider { + /** Validates the passed in promise library */ + static validate(lib: unknown): lib is PromiseConstructor { + if (typeof lib !== 'function') + throw new MongoInvalidArgumentError(`Promise must be a function, got ${lib}`); + return !!lib; + } + + /** Sets the promise library */ + static set(lib: PromiseConstructor): void { + if (!PromiseProvider.validate(lib)) { + // validate + return; + } + store[kPromise] = lib; + } + + /** Get the stored promise library, or resolves passed in */ + static get(): PromiseConstructor { + return store[kPromise] as PromiseConstructor; + } +} + +PromiseProvider.set(global.Promise); diff --git a/ts-ticket-office-service/node_modules/mongodb/src/read_concern.ts b/ts-ticket-office-service/node_modules/mongodb/src/read_concern.ts new file mode 100644 index 000000000..09e39be56 --- /dev/null +++ b/ts-ticket-office-service/node_modules/mongodb/src/read_concern.ts @@ -0,0 +1,88 @@ +import type { Document } from './bson'; + +/** @public */ +export const ReadConcernLevel = Object.freeze({ + local: 'local', + majority: 'majority', + linearizable: 'linearizable', + available: 'available', + snapshot: 'snapshot' +} as const); + +/** @public */ +export type ReadConcernLevel = typeof ReadConcernLevel[keyof typeof ReadConcernLevel]; + +/** @public */ +export type ReadConcernLike = ReadConcern | { level: ReadConcernLevel } | ReadConcernLevel; + +/** + * The MongoDB ReadConcern, which allows for control of the consistency and isolation properties + * of the data read from replica sets and replica set shards. + * @public + * + * @see https://docs.mongodb.com/manual/reference/read-concern/index.html + */ +export class ReadConcern { + level: ReadConcernLevel | string; + + /** Constructs a ReadConcern from the read concern level.*/ + constructor(level: ReadConcernLevel) { + /** + * A spec test exists that allows level to be any string. + * "invalid readConcern with out stage" + * @see ./test/spec/crud/v2/aggregate-out-readConcern.json + * @see https://github.com/mongodb/specifications/blob/master/source/read-write-concern/read-write-concern.rst#unknown-levels-and-additional-options-for-string-based-readconcerns + */ + this.level = ReadConcernLevel[level] ?? level; + } + + /** + * Construct a ReadConcern given an options object. + * + * @param options - The options object from which to extract the write concern. + */ + static fromOptions(options?: { + readConcern?: ReadConcernLike; + level?: ReadConcernLevel; + }): ReadConcern | undefined { + if (options == null) { + return; + } + + if (options.readConcern) { + const { readConcern } = options; + if (readConcern instanceof ReadConcern) { + return readConcern; + } else if (typeof readConcern === 'string') { + return new ReadConcern(readConcern); + } else if ('level' in readConcern && readConcern.level) { + return new ReadConcern(readConcern.level); + } + } + + if (options.level) { + return new ReadConcern(options.level); + } + return; + } + + static get MAJORITY(): 'majority' { + return ReadConcernLevel.majority; + } + + static get AVAILABLE(): 'available' { + return ReadConcernLevel.available; + } + + static get LINEARIZABLE(): 'linearizable' { + return ReadConcernLevel.linearizable; + } + + static get SNAPSHOT(): 'snapshot' { + return ReadConcernLevel.snapshot; + } + + toJSON(): Document { + return { level: this.level }; + } +} diff --git a/ts-ticket-office-service/node_modules/mongodb/src/read_preference.ts b/ts-ticket-office-service/node_modules/mongodb/src/read_preference.ts new file mode 100644 index 000000000..8db0491bb --- /dev/null +++ b/ts-ticket-office-service/node_modules/mongodb/src/read_preference.ts @@ -0,0 +1,271 @@ +import type { Document } from './bson'; +import { MongoInvalidArgumentError } from './error'; +import type { TagSet } from './sdam/server_description'; +import type { ClientSession } from './sessions'; + +/** @public */ +export type ReadPreferenceLike = ReadPreference | ReadPreferenceMode; + +/** @public */ +export const ReadPreferenceMode = Object.freeze({ + primary: 'primary', + primaryPreferred: 'primaryPreferred', + secondary: 'secondary', + secondaryPreferred: 'secondaryPreferred', + nearest: 'nearest' +} as const); + +/** @public */ +export type ReadPreferenceMode = typeof ReadPreferenceMode[keyof typeof ReadPreferenceMode]; + +/** @public */ +export interface HedgeOptions { + /** Explicitly enable or disable hedged reads. */ + enabled?: boolean; +} + +/** @public */ +export interface ReadPreferenceOptions { + /** Max secondary read staleness in seconds, Minimum value is 90 seconds.*/ + maxStalenessSeconds?: number; + /** Server mode in which the same query is dispatched in parallel to multiple replica set members. */ + hedge?: HedgeOptions; +} + +/** @public */ +export interface ReadPreferenceLikeOptions extends ReadPreferenceOptions { + readPreference?: + | ReadPreferenceLike + | { + mode?: ReadPreferenceMode; + preference?: ReadPreferenceMode; + tags?: TagSet[]; + maxStalenessSeconds?: number; + }; +} + +/** @public */ +export interface ReadPreferenceFromOptions extends ReadPreferenceLikeOptions { + session?: ClientSession; + readPreferenceTags?: TagSet[]; + hedge?: HedgeOptions; +} + +/** + * The **ReadPreference** class is a class that represents a MongoDB ReadPreference and is + * used to construct connections. + * @public + * + * @see https://docs.mongodb.com/manual/core/read-preference/ + */ +export class ReadPreference { + mode: ReadPreferenceMode; + tags?: TagSet[]; + hedge?: HedgeOptions; + maxStalenessSeconds?: number; + minWireVersion?: number; + + public static PRIMARY = ReadPreferenceMode.primary; + public static PRIMARY_PREFERRED = ReadPreferenceMode.primaryPreferred; + public static SECONDARY = ReadPreferenceMode.secondary; + public static SECONDARY_PREFERRED = ReadPreferenceMode.secondaryPreferred; + public static NEAREST = ReadPreferenceMode.nearest; + + public static primary = new ReadPreference(ReadPreferenceMode.primary); + public static primaryPreferred = new ReadPreference(ReadPreferenceMode.primaryPreferred); + public static secondary = new ReadPreference(ReadPreferenceMode.secondary); + public static secondaryPreferred = new ReadPreference(ReadPreferenceMode.secondaryPreferred); + public static nearest = new ReadPreference(ReadPreferenceMode.nearest); + + /** + * @param mode - A string describing the read preference mode (primary|primaryPreferred|secondary|secondaryPreferred|nearest) + * @param tags - A tag set used to target reads to members with the specified tag(s). tagSet is not available if using read preference mode primary. + * @param options - Additional read preference options + */ + constructor(mode: ReadPreferenceMode, tags?: TagSet[], options?: ReadPreferenceOptions) { + if (!ReadPreference.isValid(mode)) { + throw new MongoInvalidArgumentError(`Invalid read preference mode ${JSON.stringify(mode)}`); + } + if (options == null && typeof tags === 'object' && !Array.isArray(tags)) { + options = tags; + tags = undefined; + } else if (tags && !Array.isArray(tags)) { + throw new MongoInvalidArgumentError('ReadPreference tags must be an array'); + } + + this.mode = mode; + this.tags = tags; + this.hedge = options?.hedge; + this.maxStalenessSeconds = undefined; + this.minWireVersion = undefined; + + options = options ?? {}; + if (options.maxStalenessSeconds != null) { + if (options.maxStalenessSeconds <= 0) { + throw new MongoInvalidArgumentError('maxStalenessSeconds must be a positive integer'); + } + + this.maxStalenessSeconds = options.maxStalenessSeconds; + + // NOTE: The minimum required wire version is 5 for this read preference. If the existing + // topology has a lower value then a MongoError will be thrown during server selection. + this.minWireVersion = 5; + } + + if (this.mode === ReadPreference.PRIMARY) { + if (this.tags && Array.isArray(this.tags) && this.tags.length > 0) { + throw new MongoInvalidArgumentError('Primary read preference cannot be combined with tags'); + } + + if (this.maxStalenessSeconds) { + throw new MongoInvalidArgumentError( + 'Primary read preference cannot be combined with maxStalenessSeconds' + ); + } + + if (this.hedge) { + throw new MongoInvalidArgumentError( + 'Primary read preference cannot be combined with hedge' + ); + } + } + } + + // Support the deprecated `preference` property introduced in the porcelain layer + get preference(): ReadPreferenceMode { + return this.mode; + } + + static fromString(mode: string): ReadPreference { + return new ReadPreference(mode as ReadPreferenceMode); + } + + /** + * Construct a ReadPreference given an options object. + * + * @param options - The options object from which to extract the read preference. + */ + static fromOptions(options?: ReadPreferenceFromOptions): ReadPreference | undefined { + if (!options) return; + const readPreference = + options.readPreference ?? options.session?.transaction.options.readPreference; + const readPreferenceTags = options.readPreferenceTags; + + if (readPreference == null) { + return; + } + + if (typeof readPreference === 'string') { + return new ReadPreference(readPreference as ReadPreferenceMode, readPreferenceTags, { + maxStalenessSeconds: options.maxStalenessSeconds, + hedge: options.hedge + }); + } else if (!(readPreference instanceof ReadPreference) && typeof readPreference === 'object') { + const mode = readPreference.mode || readPreference.preference; + if (mode && typeof mode === 'string') { + return new ReadPreference(mode, readPreference.tags ?? readPreferenceTags, { + maxStalenessSeconds: readPreference.maxStalenessSeconds, + hedge: options.hedge + }); + } + } + + if (readPreferenceTags) { + readPreference.tags = readPreferenceTags; + } + + return readPreference as ReadPreference; + } + + /** + * Replaces options.readPreference with a ReadPreference instance + */ + static translate(options: ReadPreferenceLikeOptions): ReadPreferenceLikeOptions { + if (options.readPreference == null) return options; + const r = options.readPreference; + + if (typeof r === 'string') { + options.readPreference = new ReadPreference(r as ReadPreferenceMode); + } else if (r && !(r instanceof ReadPreference) && typeof r === 'object') { + const mode = r.mode || r.preference; + if (mode && typeof mode === 'string') { + options.readPreference = new ReadPreference(mode, r.tags, { + maxStalenessSeconds: r.maxStalenessSeconds + }); + } + } else if (!(r instanceof ReadPreference)) { + throw new MongoInvalidArgumentError(`Invalid read preference: ${r}`); + } + + return options; + } + + /** + * Validate if a mode is legal + * + * @param mode - The string representing the read preference mode. + */ + static isValid(mode: string): boolean { + const VALID_MODES = new Set([ + ReadPreference.PRIMARY, + ReadPreference.PRIMARY_PREFERRED, + ReadPreference.SECONDARY, + ReadPreference.SECONDARY_PREFERRED, + ReadPreference.NEAREST, + null + ]); + + return VALID_MODES.has(mode as ReadPreferenceMode); + } + + /** + * Validate if a mode is legal + * + * @param mode - The string representing the read preference mode. + */ + isValid(mode?: string): boolean { + return ReadPreference.isValid(typeof mode === 'string' ? mode : this.mode); + } + + /** + * Indicates that this readPreference needs the "secondaryOk" bit when sent over the wire + * @deprecated Use secondaryOk instead + * @see https://docs.mongodb.com/manual/reference/mongodb-wire-protocol/#op-query + */ + slaveOk(): boolean { + return this.secondaryOk(); + } + + /** + * Indicates that this readPreference needs the "SecondaryOk" bit when sent over the wire + * @see https://docs.mongodb.com/manual/reference/mongodb-wire-protocol/#op-query + */ + secondaryOk(): boolean { + const NEEDS_SECONDARYOK = new Set([ + ReadPreference.PRIMARY_PREFERRED, + ReadPreference.SECONDARY, + ReadPreference.SECONDARY_PREFERRED, + ReadPreference.NEAREST + ]); + + return NEEDS_SECONDARYOK.has(this.mode); + } + + /** + * Check if the two ReadPreferences are equivalent + * + * @param readPreference - The read preference with which to check equality + */ + equals(readPreference: ReadPreference): boolean { + return readPreference.mode === this.mode; + } + + /** Return JSON representation */ + toJSON(): Document { + const readPreference = { mode: this.mode } as Document; + if (Array.isArray(this.tags)) readPreference.tags = this.tags; + if (this.maxStalenessSeconds) readPreference.maxStalenessSeconds = this.maxStalenessSeconds; + if (this.hedge) readPreference.hedge = this.hedge; + return readPreference; + } +} diff --git a/ts-ticket-office-service/node_modules/mongodb/src/sdam/common.ts b/ts-ticket-office-service/node_modules/mongodb/src/sdam/common.ts new file mode 100644 index 000000000..6738ad9eb --- /dev/null +++ b/ts-ticket-office-service/node_modules/mongodb/src/sdam/common.ts @@ -0,0 +1,77 @@ +import type { Binary, Long, Timestamp } from '../bson'; +import type { ClientSession } from '../sessions'; +import type { Topology } from './topology'; + +// shared state names +export const STATE_CLOSING = 'closing'; +export const STATE_CLOSED = 'closed'; +export const STATE_CONNECTING = 'connecting'; +export const STATE_CONNECTED = 'connected'; + +/** + * An enumeration of topology types we know about + * @public + */ +export const TopologyType = Object.freeze({ + Single: 'Single', + ReplicaSetNoPrimary: 'ReplicaSetNoPrimary', + ReplicaSetWithPrimary: 'ReplicaSetWithPrimary', + Sharded: 'Sharded', + Unknown: 'Unknown', + LoadBalanced: 'LoadBalanced' +} as const); + +/** @public */ +export type TopologyType = typeof TopologyType[keyof typeof TopologyType]; + +/** + * An enumeration of server types we know about + * @public + */ +export const ServerType = Object.freeze({ + Standalone: 'Standalone', + Mongos: 'Mongos', + PossiblePrimary: 'PossiblePrimary', + RSPrimary: 'RSPrimary', + RSSecondary: 'RSSecondary', + RSArbiter: 'RSArbiter', + RSOther: 'RSOther', + RSGhost: 'RSGhost', + Unknown: 'Unknown', + LoadBalancer: 'LoadBalancer' +} as const); + +/** @public */ +export type ServerType = typeof ServerType[keyof typeof ServerType]; + +/** @internal */ +export type TimerQueue = Set; + +/** @internal */ +export function drainTimerQueue(queue: TimerQueue): void { + queue.forEach(clearTimeout); + queue.clear(); +} + +/** @public */ +export interface ClusterTime { + clusterTime: Timestamp; + signature: { + hash: Binary; + keyId: Long; + }; +} + +/** Shared function to determine clusterTime for a given topology or session */ +export function _advanceClusterTime( + entity: Topology | ClientSession, + $clusterTime: ClusterTime +): void { + if (entity.clusterTime == null) { + entity.clusterTime = $clusterTime; + } else { + if ($clusterTime.clusterTime.greaterThan(entity.clusterTime.clusterTime)) { + entity.clusterTime = $clusterTime; + } + } +} diff --git a/ts-ticket-office-service/node_modules/mongodb/src/sdam/events.ts b/ts-ticket-office-service/node_modules/mongodb/src/sdam/events.ts new file mode 100644 index 000000000..c55eb0957 --- /dev/null +++ b/ts-ticket-office-service/node_modules/mongodb/src/sdam/events.ts @@ -0,0 +1,182 @@ +import type { Document } from '../bson'; +import type { ServerDescription } from './server_description'; +import type { TopologyDescription } from './topology_description'; + +/** + * Emitted when server description changes, but does NOT include changes to the RTT. + * @public + * @category Event + */ +export class ServerDescriptionChangedEvent { + /** A unique identifier for the topology */ + topologyId: number; + /** The address (host/port pair) of the server */ + address: string; + /** The previous server description */ + previousDescription: ServerDescription; + /** The new server description */ + newDescription: ServerDescription; + + /** @internal */ + constructor( + topologyId: number, + address: string, + previousDescription: ServerDescription, + newDescription: ServerDescription + ) { + this.topologyId = topologyId; + this.address = address; + this.previousDescription = previousDescription; + this.newDescription = newDescription; + } +} + +/** + * Emitted when server is initialized. + * @public + * @category Event + */ +export class ServerOpeningEvent { + /** A unique identifier for the topology */ + topologyId: number; + /** The address (host/port pair) of the server */ + address: string; + + /** @internal */ + constructor(topologyId: number, address: string) { + this.topologyId = topologyId; + this.address = address; + } +} + +/** + * Emitted when server is closed. + * @public + * @category Event + */ +export class ServerClosedEvent { + /** A unique identifier for the topology */ + topologyId: number; + /** The address (host/port pair) of the server */ + address: string; + + /** @internal */ + constructor(topologyId: number, address: string) { + this.topologyId = topologyId; + this.address = address; + } +} + +/** + * Emitted when topology description changes. + * @public + * @category Event + */ +export class TopologyDescriptionChangedEvent { + /** A unique identifier for the topology */ + topologyId: number; + /** The old topology description */ + previousDescription: TopologyDescription; + /** The new topology description */ + newDescription: TopologyDescription; + + /** @internal */ + constructor( + topologyId: number, + previousDescription: TopologyDescription, + newDescription: TopologyDescription + ) { + this.topologyId = topologyId; + this.previousDescription = previousDescription; + this.newDescription = newDescription; + } +} + +/** + * Emitted when topology is initialized. + * @public + * @category Event + */ +export class TopologyOpeningEvent { + /** A unique identifier for the topology */ + topologyId: number; + + /** @internal */ + constructor(topologyId: number) { + this.topologyId = topologyId; + } +} + +/** + * Emitted when topology is closed. + * @public + * @category Event + */ +export class TopologyClosedEvent { + /** A unique identifier for the topology */ + topologyId: number; + + /** @internal */ + constructor(topologyId: number) { + this.topologyId = topologyId; + } +} + +/** + * Emitted when the server monitor’s hello command is started - immediately before + * the hello command is serialized into raw BSON and written to the socket. + * + * @public + * @category Event + */ +export class ServerHeartbeatStartedEvent { + /** The connection id for the command */ + connectionId: string; + + /** @internal */ + constructor(connectionId: string) { + this.connectionId = connectionId; + } +} + +/** + * Emitted when the server monitor’s hello succeeds. + * @public + * @category Event + */ +export class ServerHeartbeatSucceededEvent { + /** The connection id for the command */ + connectionId: string; + /** The execution time of the event in ms */ + duration: number; + /** The command reply */ + reply: Document; + + /** @internal */ + constructor(connectionId: string, duration: number, reply: Document | null) { + this.connectionId = connectionId; + this.duration = duration; + this.reply = reply ?? {}; + } +} + +/** + * Emitted when the server monitor’s hello fails, either with an “ok: 0” or a socket exception. + * @public + * @category Event + */ +export class ServerHeartbeatFailedEvent { + /** The connection id for the command */ + connectionId: string; + /** The execution time of the event in ms */ + duration: number; + /** The command failure */ + failure: Error; + + /** @internal */ + constructor(connectionId: string, duration: number, failure: Error) { + this.connectionId = connectionId; + this.duration = duration; + this.failure = failure; + } +} diff --git a/ts-ticket-office-service/node_modules/mongodb/src/sdam/monitor.ts b/ts-ticket-office-service/node_modules/mongodb/src/sdam/monitor.ts new file mode 100644 index 000000000..cd1bc092f --- /dev/null +++ b/ts-ticket-office-service/node_modules/mongodb/src/sdam/monitor.ts @@ -0,0 +1,471 @@ +import { setTimeout } from 'timers'; + +import { Document, Long } from '../bson'; +import { connect } from '../cmap/connect'; +import { Connection, ConnectionOptions } from '../cmap/connection'; +import { LEGACY_HELLO_COMMAND } from '../constants'; +import { MongoNetworkError } from '../error'; +import { CancellationToken, TypedEventEmitter } from '../mongo_types'; +import type { Callback, InterruptibleAsyncInterval } from '../utils'; +import { + calculateDurationInMs, + EventEmitterWithState, + makeInterruptibleAsyncInterval, + makeStateMachine, + now, + ns +} from '../utils'; +import { ServerType, STATE_CLOSED, STATE_CLOSING } from './common'; +import { + ServerHeartbeatFailedEvent, + ServerHeartbeatStartedEvent, + ServerHeartbeatSucceededEvent +} from './events'; +import { Server } from './server'; +import type { TopologyVersion } from './server_description'; + +/** @internal */ +const kServer = Symbol('server'); +/** @internal */ +const kMonitorId = Symbol('monitorId'); +/** @internal */ +const kConnection = Symbol('connection'); +/** @internal */ +const kCancellationToken = Symbol('cancellationToken'); +/** @internal */ +const kRTTPinger = Symbol('rttPinger'); +/** @internal */ +const kRoundTripTime = Symbol('roundTripTime'); + +const STATE_IDLE = 'idle'; +const STATE_MONITORING = 'monitoring'; +const stateTransition = makeStateMachine({ + [STATE_CLOSING]: [STATE_CLOSING, STATE_IDLE, STATE_CLOSED], + [STATE_CLOSED]: [STATE_CLOSED, STATE_MONITORING], + [STATE_IDLE]: [STATE_IDLE, STATE_MONITORING, STATE_CLOSING], + [STATE_MONITORING]: [STATE_MONITORING, STATE_IDLE, STATE_CLOSING] +}); + +const INVALID_REQUEST_CHECK_STATES = new Set([STATE_CLOSING, STATE_CLOSED, STATE_MONITORING]); +function isInCloseState(monitor: Monitor) { + return monitor.s.state === STATE_CLOSED || monitor.s.state === STATE_CLOSING; +} + +/** @internal */ +export interface MonitorPrivate { + state: string; +} + +/** @public */ +export interface MonitorOptions + extends Omit { + connectTimeoutMS: number; + heartbeatFrequencyMS: number; + minHeartbeatFrequencyMS: number; +} + +/** @public */ +export type MonitorEvents = { + serverHeartbeatStarted(event: ServerHeartbeatStartedEvent): void; + serverHeartbeatSucceeded(event: ServerHeartbeatSucceededEvent): void; + serverHeartbeatFailed(event: ServerHeartbeatFailedEvent): void; + resetServer(error?: Error): void; + resetConnectionPool(): void; + close(): void; +} & EventEmitterWithState; + +/** @internal */ +export class Monitor extends TypedEventEmitter { + /** @internal */ + s: MonitorPrivate; + address: string; + options: Readonly< + Pick + >; + connectOptions: ConnectionOptions; + [kServer]: Server; + [kConnection]?: Connection; + [kCancellationToken]: CancellationToken; + /** @internal */ + [kMonitorId]?: InterruptibleAsyncInterval; + [kRTTPinger]?: RTTPinger; + + get connection(): Connection | undefined { + return this[kConnection]; + } + + constructor(server: Server, options: MonitorOptions) { + super(); + + this[kServer] = server; + this[kConnection] = undefined; + this[kCancellationToken] = new CancellationToken(); + this[kCancellationToken].setMaxListeners(Infinity); + this[kMonitorId] = undefined; + this.s = { + state: STATE_CLOSED + }; + + this.address = server.description.address; + this.options = Object.freeze({ + connectTimeoutMS: options.connectTimeoutMS ?? 10000, + heartbeatFrequencyMS: options.heartbeatFrequencyMS ?? 10000, + minHeartbeatFrequencyMS: options.minHeartbeatFrequencyMS ?? 500 + }); + + const cancellationToken = this[kCancellationToken]; + // TODO: refactor this to pull it directly from the pool, requires new ConnectionPool integration + const connectOptions = Object.assign( + { + id: '' as const, + generation: server.s.pool.generation, + connectionType: Connection, + cancellationToken, + hostAddress: server.description.hostAddress + }, + options, + // force BSON serialization options + { + raw: false, + promoteLongs: true, + promoteValues: true, + promoteBuffers: true + } + ); + + // ensure no authentication is used for monitoring + delete connectOptions.credentials; + if (connectOptions.autoEncrypter) { + delete connectOptions.autoEncrypter; + } + + this.connectOptions = Object.freeze(connectOptions); + } + + connect(): void { + if (this.s.state !== STATE_CLOSED) { + return; + } + + // start + const heartbeatFrequencyMS = this.options.heartbeatFrequencyMS; + const minHeartbeatFrequencyMS = this.options.minHeartbeatFrequencyMS; + this[kMonitorId] = makeInterruptibleAsyncInterval(monitorServer(this), { + interval: heartbeatFrequencyMS, + minInterval: minHeartbeatFrequencyMS, + immediate: true + }); + } + + requestCheck(): void { + if (INVALID_REQUEST_CHECK_STATES.has(this.s.state)) { + return; + } + + this[kMonitorId]?.wake(); + } + + reset(): void { + const topologyVersion = this[kServer].description.topologyVersion; + if (isInCloseState(this) || topologyVersion == null) { + return; + } + + stateTransition(this, STATE_CLOSING); + resetMonitorState(this); + + // restart monitor + stateTransition(this, STATE_IDLE); + + // restart monitoring + const heartbeatFrequencyMS = this.options.heartbeatFrequencyMS; + const minHeartbeatFrequencyMS = this.options.minHeartbeatFrequencyMS; + this[kMonitorId] = makeInterruptibleAsyncInterval(monitorServer(this), { + interval: heartbeatFrequencyMS, + minInterval: minHeartbeatFrequencyMS + }); + } + + close(): void { + if (isInCloseState(this)) { + return; + } + + stateTransition(this, STATE_CLOSING); + resetMonitorState(this); + + // close monitor + this.emit('close'); + stateTransition(this, STATE_CLOSED); + } +} + +function resetMonitorState(monitor: Monitor) { + monitor[kMonitorId]?.stop(); + monitor[kMonitorId] = undefined; + + monitor[kRTTPinger]?.close(); + monitor[kRTTPinger] = undefined; + + monitor[kCancellationToken].emit('cancel'); + + monitor[kConnection]?.destroy({ force: true }); + monitor[kConnection] = undefined; +} + +function checkServer(monitor: Monitor, callback: Callback) { + let start = now(); + monitor.emit(Server.SERVER_HEARTBEAT_STARTED, new ServerHeartbeatStartedEvent(monitor.address)); + + function failureHandler(err: Error) { + monitor[kConnection]?.destroy({ force: true }); + monitor[kConnection] = undefined; + + monitor.emit( + Server.SERVER_HEARTBEAT_FAILED, + new ServerHeartbeatFailedEvent(monitor.address, calculateDurationInMs(start), err) + ); + + monitor.emit('resetServer', err); + monitor.emit('resetConnectionPool'); + callback(err); + } + + const connection = monitor[kConnection]; + if (connection && !connection.closed) { + const { serverApi, helloOk } = connection; + const connectTimeoutMS = monitor.options.connectTimeoutMS; + const maxAwaitTimeMS = monitor.options.heartbeatFrequencyMS; + const topologyVersion = monitor[kServer].description.topologyVersion; + const isAwaitable = topologyVersion != null; + + const cmd = { + [serverApi?.version || helloOk ? 'hello' : LEGACY_HELLO_COMMAND]: true, + ...(isAwaitable && topologyVersion + ? { maxAwaitTimeMS, topologyVersion: makeTopologyVersion(topologyVersion) } + : {}) + }; + + const options = isAwaitable + ? { + socketTimeoutMS: connectTimeoutMS ? connectTimeoutMS + maxAwaitTimeMS : 0, + exhaustAllowed: true + } + : { socketTimeoutMS: connectTimeoutMS }; + + if (isAwaitable && monitor[kRTTPinger] == null) { + monitor[kRTTPinger] = new RTTPinger( + monitor[kCancellationToken], + Object.assign( + { heartbeatFrequencyMS: monitor.options.heartbeatFrequencyMS }, + monitor.connectOptions + ) + ); + } + + connection.command(ns('admin.$cmd'), cmd, options, (err, hello) => { + if (err) { + return failureHandler(err); + } + + if (!('isWritablePrimary' in hello)) { + // Provide hello-style response document. + hello.isWritablePrimary = hello[LEGACY_HELLO_COMMAND]; + } + + const rttPinger = monitor[kRTTPinger]; + const duration = + isAwaitable && rttPinger ? rttPinger.roundTripTime : calculateDurationInMs(start); + + monitor.emit( + Server.SERVER_HEARTBEAT_SUCCEEDED, + new ServerHeartbeatSucceededEvent(monitor.address, duration, hello) + ); + + // if we are using the streaming protocol then we immediately issue another `started` + // event, otherwise the "check" is complete and return to the main monitor loop + if (isAwaitable && hello.topologyVersion) { + monitor.emit( + Server.SERVER_HEARTBEAT_STARTED, + new ServerHeartbeatStartedEvent(monitor.address) + ); + start = now(); + } else { + monitor[kRTTPinger]?.close(); + monitor[kRTTPinger] = undefined; + + callback(undefined, hello); + } + }); + + return; + } + + // connecting does an implicit `hello` + connect(monitor.connectOptions, (err, conn) => { + if (err) { + monitor[kConnection] = undefined; + + // we already reset the connection pool on network errors in all cases + if (!(err instanceof MongoNetworkError)) { + monitor.emit('resetConnectionPool'); + } + + failureHandler(err); + return; + } + + if (conn) { + // Tell the connection that we are using the streaming protocol so that the + // connection's message stream will only read the last hello on the buffer. + conn.isMonitoringConnection = true; + + if (isInCloseState(monitor)) { + conn.destroy({ force: true }); + return; + } + + monitor[kConnection] = conn; + monitor.emit( + Server.SERVER_HEARTBEAT_SUCCEEDED, + new ServerHeartbeatSucceededEvent(monitor.address, calculateDurationInMs(start), conn.hello) + ); + + callback(undefined, conn.hello); + } + }); +} + +function monitorServer(monitor: Monitor) { + return (callback: Callback) => { + stateTransition(monitor, STATE_MONITORING); + function done() { + if (!isInCloseState(monitor)) { + stateTransition(monitor, STATE_IDLE); + } + + callback(); + } + + checkServer(monitor, (err, hello) => { + if (err) { + // otherwise an error occurred on initial discovery, also bail + if (monitor[kServer].description.type === ServerType.Unknown) { + monitor.emit('resetServer', err); + return done(); + } + } + + // if the check indicates streaming is supported, immediately reschedule monitoring + if (hello && hello.topologyVersion) { + setTimeout(() => { + if (!isInCloseState(monitor)) { + monitor[kMonitorId]?.wake(); + } + }, 0); + } + + done(); + }); + }; +} + +function makeTopologyVersion(tv: TopologyVersion) { + return { + processId: tv.processId, + // tests mock counter as just number, but in a real situation counter should always be a Long + counter: Long.isLong(tv.counter) ? tv.counter : Long.fromNumber(tv.counter) + }; +} + +/** @internal */ +export interface RTTPingerOptions extends ConnectionOptions { + heartbeatFrequencyMS: number; +} + +/** @internal */ +export class RTTPinger { + /** @internal */ + [kConnection]?: Connection; + /** @internal */ + [kCancellationToken]: CancellationToken; + /** @internal */ + [kRoundTripTime]: number; + /** @internal */ + [kMonitorId]: NodeJS.Timeout; + closed: boolean; + + constructor(cancellationToken: CancellationToken, options: RTTPingerOptions) { + this[kConnection] = undefined; + this[kCancellationToken] = cancellationToken; + this[kRoundTripTime] = 0; + this.closed = false; + + const heartbeatFrequencyMS = options.heartbeatFrequencyMS; + this[kMonitorId] = setTimeout(() => measureRoundTripTime(this, options), heartbeatFrequencyMS); + } + + get roundTripTime(): number { + return this[kRoundTripTime]; + } + + close(): void { + this.closed = true; + clearTimeout(this[kMonitorId]); + + this[kConnection]?.destroy({ force: true }); + this[kConnection] = undefined; + } +} + +function measureRoundTripTime(rttPinger: RTTPinger, options: RTTPingerOptions) { + const start = now(); + options.cancellationToken = rttPinger[kCancellationToken]; + const heartbeatFrequencyMS = options.heartbeatFrequencyMS; + + if (rttPinger.closed) { + return; + } + + function measureAndReschedule(conn?: Connection) { + if (rttPinger.closed) { + conn?.destroy({ force: true }); + return; + } + + if (rttPinger[kConnection] == null) { + rttPinger[kConnection] = conn; + } + + rttPinger[kRoundTripTime] = calculateDurationInMs(start); + rttPinger[kMonitorId] = setTimeout( + () => measureRoundTripTime(rttPinger, options), + heartbeatFrequencyMS + ); + } + + const connection = rttPinger[kConnection]; + if (connection == null) { + connect(options, (err, conn) => { + if (err) { + rttPinger[kConnection] = undefined; + rttPinger[kRoundTripTime] = 0; + return; + } + + measureAndReschedule(conn); + }); + + return; + } + + connection.command(ns('admin.$cmd'), { [LEGACY_HELLO_COMMAND]: 1 }, undefined, err => { + if (err) { + rttPinger[kConnection] = undefined; + rttPinger[kRoundTripTime] = 0; + return; + } + + measureAndReschedule(); + }); +} diff --git a/ts-ticket-office-service/node_modules/mongodb/src/sdam/server.ts b/ts-ticket-office-service/node_modules/mongodb/src/sdam/server.ts new file mode 100644 index 000000000..93c7be92a --- /dev/null +++ b/ts-ticket-office-service/node_modules/mongodb/src/sdam/server.ts @@ -0,0 +1,620 @@ +import type { Document, Long } from '../bson'; +import { CommandOptions, Connection, DestroyOptions, GetMoreOptions } from '../cmap/connection'; +import { + ConnectionPool, + ConnectionPoolEvents, + ConnectionPoolOptions +} from '../cmap/connection_pool'; +import { + APM_EVENTS, + CLOSED, + CMAP_EVENTS, + CONNECT, + DESCRIPTION_RECEIVED, + ENDED, + HEARTBEAT_EVENTS, + SERVER_HEARTBEAT_FAILED, + SERVER_HEARTBEAT_STARTED, + SERVER_HEARTBEAT_SUCCEEDED +} from '../constants'; +import type { AutoEncrypter } from '../deps'; +import { + isNetworkErrorBeforeHandshake, + isNodeShuttingDownError, + isSDAMUnrecoverableError, + MongoCompatibilityError, + MongoError, + MongoErrorLabel, + MongoInvalidArgumentError, + MongoNetworkError, + MongoNetworkTimeoutError, + MongoServerClosedError, + MongoUnexpectedServerResponseError, + needsRetryableWriteLabel +} from '../error'; +import { Logger } from '../logger'; +import type { ServerApi } from '../mongo_client'; +import { TypedEventEmitter } from '../mongo_types'; +import type { ClientSession } from '../sessions'; +import { isTransactionCommand } from '../transactions'; +import { + Callback, + collationNotSupported, + EventEmitterWithState, + makeStateMachine, + maxWireVersion, + MongoDBNamespace, + supportsRetryableWrites +} from '../utils'; +import { + ClusterTime, + STATE_CLOSED, + STATE_CLOSING, + STATE_CONNECTED, + STATE_CONNECTING, + TopologyType +} from './common'; +import type { + ServerHeartbeatFailedEvent, + ServerHeartbeatStartedEvent, + ServerHeartbeatSucceededEvent +} from './events'; +import { Monitor, MonitorOptions } from './monitor'; +import { compareTopologyVersion, ServerDescription } from './server_description'; +import type { Topology } from './topology'; + +const stateTransition = makeStateMachine({ + [STATE_CLOSED]: [STATE_CLOSED, STATE_CONNECTING], + [STATE_CONNECTING]: [STATE_CONNECTING, STATE_CLOSING, STATE_CONNECTED, STATE_CLOSED], + [STATE_CONNECTED]: [STATE_CONNECTED, STATE_CLOSING, STATE_CLOSED], + [STATE_CLOSING]: [STATE_CLOSING, STATE_CLOSED] +}); + +/** @internal */ +const kMonitor = Symbol('monitor'); + +/** @public */ +export type ServerOptions = Omit & + MonitorOptions; + +/** @internal */ +export interface ServerPrivate { + /** The server description for this server */ + description: ServerDescription; + /** A copy of the options used to construct this instance */ + options: ServerOptions; + /** A logger instance */ + logger: Logger; + /** The current state of the Server */ + state: string; + /** The topology this server is a part of */ + topology: Topology; + /** A connection pool for this server */ + pool: ConnectionPool; + /** MongoDB server API version */ + serverApi?: ServerApi; + /** A count of the operations currently running against the server. */ + operationCount: number; +} + +/** @public */ +export type ServerEvents = { + serverHeartbeatStarted(event: ServerHeartbeatStartedEvent): void; + serverHeartbeatSucceeded(event: ServerHeartbeatSucceededEvent): void; + serverHeartbeatFailed(event: ServerHeartbeatFailedEvent): void; + /** Top level MongoClient doesn't emit this so it is marked: @internal */ + connect(server: Server): void; + descriptionReceived(description: ServerDescription): void; + closed(): void; + ended(): void; +} & ConnectionPoolEvents & + EventEmitterWithState; + +/** @internal */ +export class Server extends TypedEventEmitter { + /** @internal */ + s: ServerPrivate; + serverApi?: ServerApi; + hello?: Document; + [kMonitor]: Monitor | null; + + /** @event */ + static readonly SERVER_HEARTBEAT_STARTED = SERVER_HEARTBEAT_STARTED; + /** @event */ + static readonly SERVER_HEARTBEAT_SUCCEEDED = SERVER_HEARTBEAT_SUCCEEDED; + /** @event */ + static readonly SERVER_HEARTBEAT_FAILED = SERVER_HEARTBEAT_FAILED; + /** @event */ + static readonly CONNECT = CONNECT; + /** @event */ + static readonly DESCRIPTION_RECEIVED = DESCRIPTION_RECEIVED; + /** @event */ + static readonly CLOSED = CLOSED; + /** @event */ + static readonly ENDED = ENDED; + + /** + * Create a server + */ + constructor(topology: Topology, description: ServerDescription, options: ServerOptions) { + super(); + + this.serverApi = options.serverApi; + + const poolOptions = { hostAddress: description.hostAddress, ...options }; + + this.s = { + description, + options, + logger: new Logger('Server'), + state: STATE_CLOSED, + topology, + pool: new ConnectionPool(poolOptions), + operationCount: 0 + }; + + for (const event of [...CMAP_EVENTS, ...APM_EVENTS]) { + this.s.pool.on(event, (e: any) => this.emit(event, e)); + } + + this.s.pool.on(Connection.CLUSTER_TIME_RECEIVED, (clusterTime: ClusterTime) => { + this.clusterTime = clusterTime; + }); + + if (this.loadBalanced) { + this[kMonitor] = null; + // monitoring is disabled in load balancing mode + return; + } + + // create the monitor + // TODO(NODE-4144): Remove new variable for type narrowing + const monitor = new Monitor(this, this.s.options); + this[kMonitor] = monitor; + + for (const event of HEARTBEAT_EVENTS) { + monitor.on(event, (e: any) => this.emit(event, e)); + } + + monitor.on('resetConnectionPool', () => { + this.s.pool.clear(); + }); + + monitor.on('resetServer', (error: MongoError) => markServerUnknown(this, error)); + monitor.on(Server.SERVER_HEARTBEAT_SUCCEEDED, (event: ServerHeartbeatSucceededEvent) => { + this.emit( + Server.DESCRIPTION_RECEIVED, + new ServerDescription(this.description.hostAddress, event.reply, { + roundTripTime: calculateRoundTripTime(this.description.roundTripTime, event.duration) + }) + ); + + if (this.s.state === STATE_CONNECTING) { + stateTransition(this, STATE_CONNECTED); + this.emit(Server.CONNECT, this); + } + }); + } + + get clusterTime(): ClusterTime | undefined { + return this.s.topology.clusterTime; + } + + set clusterTime(clusterTime: ClusterTime | undefined) { + this.s.topology.clusterTime = clusterTime; + } + + get description(): ServerDescription { + return this.s.description; + } + + get name(): string { + return this.s.description.address; + } + + get autoEncrypter(): AutoEncrypter | undefined { + if (this.s.options && this.s.options.autoEncrypter) { + return this.s.options.autoEncrypter; + } + return; + } + + get loadBalanced(): boolean { + return this.s.topology.description.type === TopologyType.LoadBalanced; + } + + /** + * Initiate server connect + */ + connect(): void { + if (this.s.state !== STATE_CLOSED) { + return; + } + + stateTransition(this, STATE_CONNECTING); + + // If in load balancer mode we automatically set the server to + // a load balancer. It never transitions out of this state and + // has no monitor. + if (!this.loadBalanced) { + this[kMonitor]?.connect(); + } else { + stateTransition(this, STATE_CONNECTED); + this.emit(Server.CONNECT, this); + } + } + + /** Destroy the server connection */ + destroy(options?: DestroyOptions, callback?: Callback): void { + if (typeof options === 'function') (callback = options), (options = {}); + options = Object.assign({}, { force: false }, options); + + if (this.s.state === STATE_CLOSED) { + if (typeof callback === 'function') { + callback(); + } + + return; + } + + stateTransition(this, STATE_CLOSING); + + if (!this.loadBalanced) { + this[kMonitor]?.close(); + } + + this.s.pool.close(options, err => { + stateTransition(this, STATE_CLOSED); + this.emit('closed'); + if (typeof callback === 'function') { + callback(err); + } + }); + } + + /** + * Immediately schedule monitoring of this server. If there already an attempt being made + * this will be a no-op. + */ + requestCheck(): void { + if (!this.loadBalanced) { + this[kMonitor]?.requestCheck(); + } + } + + /** + * Execute a command + * @internal + */ + command( + ns: MongoDBNamespace, + cmd: Document, + options: CommandOptions, + callback: Callback + ): void { + if (callback == null) { + throw new MongoInvalidArgumentError('Callback must be provided'); + } + + if (ns.db == null || typeof ns === 'string') { + throw new MongoInvalidArgumentError('Namespace must not be a string'); + } + + if (this.s.state === STATE_CLOSING || this.s.state === STATE_CLOSED) { + callback(new MongoServerClosedError()); + return; + } + + // Clone the options + const finalOptions = Object.assign({}, options, { wireProtocolCommand: false }); + + // There are cases where we need to flag the read preference not to get sent in + // the command, such as pre-5.0 servers attempting to perform an aggregate write + // with a non-primary read preference. In this case the effective read preference + // (primary) is not the same as the provided and must be removed completely. + if (finalOptions.omitReadPreference) { + delete finalOptions.readPreference; + } + + // error if collation not supported + if (collationNotSupported(this, cmd)) { + callback(new MongoCompatibilityError(`Server ${this.name} does not support collation`)); + return; + } + + const session = finalOptions.session; + const conn = session?.pinnedConnection; + + // NOTE: This is a hack! We can't retrieve the connections used for executing an operation + // (and prevent them from being checked back in) at the point of operation execution. + // This should be considered as part of the work for NODE-2882 + // NOTE: + // When incrementing operation count, it's important that we increment it before we + // attempt to check out a connection from the pool. This ensures that operations that + // are waiting for a connection are included in the operation count. Load balanced + // mode will only ever have a single server, so the operation count doesn't matter. + // Incrementing the operation count above the logic to handle load balanced mode would + // require special logic to decrement it again, or would double increment (the load + // balanced code makes a recursive call). Instead, we increment the count after this + // check. + if (this.loadBalanced && session && conn == null && isPinnableCommand(cmd, session)) { + this.s.pool.checkOut((err, checkedOut) => { + if (err || checkedOut == null) { + if (callback) return callback(err); + return; + } + + session.pin(checkedOut); + this.command(ns, cmd, finalOptions, callback); + }); + return; + } + + this.s.operationCount += 1; + + this.s.pool.withConnection( + conn, + (err, conn, cb) => { + if (err || !conn) { + this.s.operationCount -= 1; + markServerUnknown(this, err); + return cb(err); + } + + conn.command( + ns, + cmd, + finalOptions, + makeOperationHandler(this, conn, cmd, finalOptions, (error, response) => { + this.s.operationCount -= 1; + cb(error, response); + }) + ); + }, + callback + ); + } + + /** + * Execute a `getMore` against the server + * @internal + */ + getMore( + ns: MongoDBNamespace, + cursorId: Long, + options: GetMoreOptions, + callback: Callback + ): void { + if (this.s.state === STATE_CLOSING || this.s.state === STATE_CLOSED) { + callback(new MongoServerClosedError()); + return; + } + + this.s.operationCount += 1; + + this.s.pool.withConnection( + options.session?.pinnedConnection, + (err, conn, cb) => { + if (err || !conn) { + this.s.operationCount -= 1; + markServerUnknown(this, err); + return cb(err); + } + + conn.getMore( + ns, + cursorId, + options, + makeOperationHandler(this, conn, {}, options, (error, response) => { + this.s.operationCount -= 1; + cb(error, response); + }) + ); + }, + callback + ); + } + + /** + * Execute a `killCursors` command against the server + * @internal + */ + killCursors( + ns: MongoDBNamespace, + cursorIds: Long[], + options: CommandOptions, + callback?: Callback + ): void { + if (this.s.state === STATE_CLOSING || this.s.state === STATE_CLOSED) { + if (typeof callback === 'function') { + callback(new MongoServerClosedError()); + } + + return; + } + + this.s.operationCount += 1; + this.s.pool.withConnection( + options.session?.pinnedConnection, + (err, conn, cb) => { + if (err || !conn) { + this.s.operationCount -= 1; + markServerUnknown(this, err); + return cb(err); + } + + conn.killCursors( + ns, + cursorIds, + options, + makeOperationHandler(this, conn, {}, undefined, (error, response) => { + this.s.operationCount -= 1; + cb(error, response); + }) + ); + }, + callback + ); + } +} + +function calculateRoundTripTime(oldRtt: number, duration: number): number { + if (oldRtt === -1) { + return duration; + } + + const alpha = 0.2; + return alpha * duration + (1 - alpha) * oldRtt; +} + +function markServerUnknown(server: Server, error?: MongoError) { + // Load balancer servers can never be marked unknown. + if (server.loadBalanced) { + return; + } + + if (error instanceof MongoNetworkError && !(error instanceof MongoNetworkTimeoutError)) { + server[kMonitor]?.reset(); + } + + server.emit( + Server.DESCRIPTION_RECEIVED, + new ServerDescription(server.description.hostAddress, undefined, { + error, + topologyVersion: + error && error.topologyVersion ? error.topologyVersion : server.description.topologyVersion + }) + ); +} + +function isPinnableCommand(cmd: Document, session?: ClientSession): boolean { + if (session) { + return ( + session.inTransaction() || + 'aggregate' in cmd || + 'find' in cmd || + 'getMore' in cmd || + 'listCollections' in cmd || + 'listIndexes' in cmd + ); + } + + return false; +} + +function connectionIsStale(pool: ConnectionPool, connection: Connection) { + if (connection.serviceId) { + return ( + connection.generation !== pool.serviceGenerations.get(connection.serviceId.toHexString()) + ); + } + + return connection.generation !== pool.generation; +} + +function shouldHandleStateChangeError(server: Server, err: MongoError) { + const etv = err.topologyVersion; + const stv = server.description.topologyVersion; + return compareTopologyVersion(stv, etv) < 0; +} + +function inActiveTransaction(session: ClientSession | undefined, cmd: Document) { + return session && session.inTransaction() && !isTransactionCommand(cmd); +} + +/** this checks the retryWrites option passed down from the client options, it + * does not check if the server supports retryable writes */ +function isRetryableWritesEnabled(topology: Topology) { + return topology.s.options.retryWrites !== false; +} + +function makeOperationHandler( + server: Server, + connection: Connection, + cmd: Document, + options: CommandOptions | GetMoreOptions | undefined, + callback: Callback +): Callback { + const session = options?.session; + return function handleOperationResult(error, result) { + if (result != null) { + return callback(undefined, result); + } + + if (!error) { + return callback(new MongoUnexpectedServerResponseError('Empty response with no error')); + } + + if (!(error instanceof MongoError)) { + // Node.js or some other error we have not special handling for + return callback(error); + } + + if (connectionIsStale(server.s.pool, connection)) { + return callback(error); + } + + if (error instanceof MongoNetworkError) { + if (session && !session.hasEnded && session.serverSession) { + session.serverSession.isDirty = true; + } + + // inActiveTransaction check handles commit and abort. + if ( + inActiveTransaction(session, cmd) && + !error.hasErrorLabel(MongoErrorLabel.TransientTransactionError) + ) { + error.addErrorLabel(MongoErrorLabel.TransientTransactionError); + } + + if ( + (isRetryableWritesEnabled(server.s.topology) || isTransactionCommand(cmd)) && + supportsRetryableWrites(server) && + !inActiveTransaction(session, cmd) + ) { + error.addErrorLabel(MongoErrorLabel.RetryableWriteError); + } + + if (!(error instanceof MongoNetworkTimeoutError) || isNetworkErrorBeforeHandshake(error)) { + // In load balanced mode we never mark the server as unknown and always + // clear for the specific service id. + + server.s.pool.clear(connection.serviceId); + if (!server.loadBalanced) { + markServerUnknown(server, error); + } + } + } else { + if ( + (isRetryableWritesEnabled(server.s.topology) || isTransactionCommand(cmd)) && + needsRetryableWriteLabel(error, maxWireVersion(server)) && + !inActiveTransaction(session, cmd) + ) { + error.addErrorLabel(MongoErrorLabel.RetryableWriteError); + } + + if (isSDAMUnrecoverableError(error)) { + if (shouldHandleStateChangeError(server, error)) { + if (maxWireVersion(server) <= 7 || isNodeShuttingDownError(error)) { + server.s.pool.clear(connection.serviceId); + } + + if (!server.loadBalanced) { + markServerUnknown(server, error); + process.nextTick(() => server.requestCheck()); + } + } + } + } + + if ( + session && + session.isPinned && + error.hasErrorLabel(MongoErrorLabel.TransientTransactionError) + ) { + session.unpin({ force: true }); + } + + return callback(error); + }; +} diff --git a/ts-ticket-office-service/node_modules/mongodb/src/sdam/server_description.ts b/ts-ticket-office-service/node_modules/mongodb/src/sdam/server_description.ts new file mode 100644 index 000000000..5082c7cb3 --- /dev/null +++ b/ts-ticket-office-service/node_modules/mongodb/src/sdam/server_description.ts @@ -0,0 +1,272 @@ +import { Document, Long, ObjectId } from '../bson'; +import type { MongoError } from '../error'; +import { arrayStrictEqual, errorStrictEqual, HostAddress, now } from '../utils'; +import type { ClusterTime } from './common'; +import { ServerType } from './common'; + +const WRITABLE_SERVER_TYPES = new Set([ + ServerType.RSPrimary, + ServerType.Standalone, + ServerType.Mongos, + ServerType.LoadBalancer +]); + +const DATA_BEARING_SERVER_TYPES = new Set([ + ServerType.RSPrimary, + ServerType.RSSecondary, + ServerType.Mongos, + ServerType.Standalone, + ServerType.LoadBalancer +]); + +/** @public */ +export interface TopologyVersion { + processId: ObjectId; + counter: Long; +} + +/** @public */ +export type TagSet = { [key: string]: string }; + +/** @internal */ +export interface ServerDescriptionOptions { + /** An Error used for better reporting debugging */ + error?: MongoError; + + /** The round trip time to ping this server (in ms) */ + roundTripTime?: number; + + /** The topologyVersion */ + topologyVersion?: TopologyVersion; + + /** If the client is in load balancing mode. */ + loadBalanced?: boolean; +} + +/** + * The client's view of a single server, based on the most recent hello outcome. + * + * Internal type, not meant to be directly instantiated + * @public + */ +export class ServerDescription { + private _hostAddress: HostAddress; + address: string; + type: ServerType; + hosts: string[]; + passives: string[]; + arbiters: string[]; + tags: TagSet; + + error?: MongoError; + topologyVersion?: TopologyVersion; + minWireVersion: number; + maxWireVersion: number; + roundTripTime: number; + lastUpdateTime: number; + lastWriteDate: number; + + me?: string; + primary?: string; + setName?: string; + setVersion?: number; + electionId?: ObjectId; + logicalSessionTimeoutMinutes?: number; + + // NOTE: does this belong here? It seems we should gossip the cluster time at the CMAP level + $clusterTime?: ClusterTime; + + /** + * Create a ServerDescription + * @internal + * + * @param address - The address of the server + * @param hello - An optional hello response for this server + */ + constructor(address: HostAddress | string, hello?: Document, options?: ServerDescriptionOptions) { + if (typeof address === 'string') { + this._hostAddress = new HostAddress(address); + this.address = this._hostAddress.toString(); + } else { + this._hostAddress = address; + this.address = this._hostAddress.toString(); + } + this.type = parseServerType(hello, options); + this.hosts = hello?.hosts?.map((host: string) => host.toLowerCase()) ?? []; + this.passives = hello?.passives?.map((host: string) => host.toLowerCase()) ?? []; + this.arbiters = hello?.arbiters?.map((host: string) => host.toLowerCase()) ?? []; + this.tags = hello?.tags ?? {}; + this.minWireVersion = hello?.minWireVersion ?? 0; + this.maxWireVersion = hello?.maxWireVersion ?? 0; + this.roundTripTime = options?.roundTripTime ?? -1; + this.lastUpdateTime = now(); + this.lastWriteDate = hello?.lastWrite?.lastWriteDate ?? 0; + + if (options?.topologyVersion) { + this.topologyVersion = options.topologyVersion; + } else if (hello?.topologyVersion) { + this.topologyVersion = hello.topologyVersion; + } + + if (options?.error) { + this.error = options.error; + } + + if (hello?.primary) { + this.primary = hello.primary; + } + + if (hello?.me) { + this.me = hello.me.toLowerCase(); + } + + if (hello?.setName) { + this.setName = hello.setName; + } + + if (hello?.setVersion) { + this.setVersion = hello.setVersion; + } + + if (hello?.electionId) { + this.electionId = hello.electionId; + } + + if (hello?.logicalSessionTimeoutMinutes) { + this.logicalSessionTimeoutMinutes = hello.logicalSessionTimeoutMinutes; + } + + if (hello?.$clusterTime) { + this.$clusterTime = hello.$clusterTime; + } + } + + get hostAddress(): HostAddress { + if (this._hostAddress) return this._hostAddress; + else return new HostAddress(this.address); + } + + get allHosts(): string[] { + return this.hosts.concat(this.arbiters).concat(this.passives); + } + + /** Is this server available for reads*/ + get isReadable(): boolean { + return this.type === ServerType.RSSecondary || this.isWritable; + } + + /** Is this server data bearing */ + get isDataBearing(): boolean { + return DATA_BEARING_SERVER_TYPES.has(this.type); + } + + /** Is this server available for writes */ + get isWritable(): boolean { + return WRITABLE_SERVER_TYPES.has(this.type); + } + + get host(): string { + const chopLength = `:${this.port}`.length; + return this.address.slice(0, -chopLength); + } + + get port(): number { + const port = this.address.split(':').pop(); + return port ? Number.parseInt(port, 10) : 27017; + } + + /** + * Determines if another `ServerDescription` is equal to this one per the rules defined + * in the {@link https://github.com/mongodb/specifications/blob/master/source/server-discovery-and-monitoring/server-discovery-and-monitoring.rst#serverdescription|SDAM spec} + */ + equals(other: ServerDescription): boolean { + const topologyVersionsEqual = + this.topologyVersion === other.topologyVersion || + compareTopologyVersion(this.topologyVersion, other.topologyVersion) === 0; + + const electionIdsEqual: boolean = + this.electionId && other.electionId + ? other.electionId && this.electionId.equals(other.electionId) + : this.electionId === other.electionId; + + return ( + other != null && + errorStrictEqual(this.error, other.error) && + this.type === other.type && + this.minWireVersion === other.minWireVersion && + arrayStrictEqual(this.hosts, other.hosts) && + tagsStrictEqual(this.tags, other.tags) && + this.setName === other.setName && + this.setVersion === other.setVersion && + electionIdsEqual && + this.primary === other.primary && + this.logicalSessionTimeoutMinutes === other.logicalSessionTimeoutMinutes && + topologyVersionsEqual + ); + } +} + +// Parses a `hello` message and determines the server type +export function parseServerType(hello?: Document, options?: ServerDescriptionOptions): ServerType { + if (options?.loadBalanced) { + return ServerType.LoadBalancer; + } + + if (!hello || !hello.ok) { + return ServerType.Unknown; + } + + if (hello.isreplicaset) { + return ServerType.RSGhost; + } + + if (hello.msg && hello.msg === 'isdbgrid') { + return ServerType.Mongos; + } + + if (hello.setName) { + if (hello.hidden) { + return ServerType.RSOther; + } else if (hello.isWritablePrimary) { + return ServerType.RSPrimary; + } else if (hello.secondary) { + return ServerType.RSSecondary; + } else if (hello.arbiterOnly) { + return ServerType.RSArbiter; + } else { + return ServerType.RSOther; + } + } + + return ServerType.Standalone; +} + +function tagsStrictEqual(tags: TagSet, tags2: TagSet): boolean { + const tagsKeys = Object.keys(tags); + const tags2Keys = Object.keys(tags2); + + return ( + tagsKeys.length === tags2Keys.length && + tagsKeys.every((key: string) => tags2[key] === tags[key]) + ); +} + +/** + * Compares two topology versions. + * + * @returns A negative number if `lhs` is older than `rhs`; positive if `lhs` is newer than `rhs`; 0 if they are equivalent. + */ +export function compareTopologyVersion(lhs?: TopologyVersion, rhs?: TopologyVersion): number { + if (lhs == null || rhs == null) { + return -1; + } + + if (lhs.processId.equals(rhs.processId)) { + // tests mock counter as just number, but in a real situation counter should always be a Long + const lhsCounter = Long.isLong(lhs.counter) ? lhs.counter : Long.fromNumber(lhs.counter); + const rhsCounter = Long.isLong(rhs.counter) ? lhs.counter : Long.fromNumber(rhs.counter); + return lhsCounter.compare(rhsCounter); + } + + return -1; +} diff --git a/ts-ticket-office-service/node_modules/mongodb/src/sdam/server_selection.ts b/ts-ticket-office-service/node_modules/mongodb/src/sdam/server_selection.ts new file mode 100644 index 000000000..74bbd8918 --- /dev/null +++ b/ts-ticket-office-service/node_modules/mongodb/src/sdam/server_selection.ts @@ -0,0 +1,324 @@ +import { MongoCompatibilityError, MongoInvalidArgumentError } from '../error'; +import { ReadPreference } from '../read_preference'; +import { ServerType, TopologyType } from './common'; +import type { ServerDescription, TagSet } from './server_description'; +import type { TopologyDescription } from './topology_description'; + +// max staleness constants +const IDLE_WRITE_PERIOD = 10000; +const SMALLEST_MAX_STALENESS_SECONDS = 90; + +// Minimum version to try writes on secondaries. +export const MIN_SECONDARY_WRITE_WIRE_VERSION = 13; + +/** @public */ +export type ServerSelector = ( + topologyDescription: TopologyDescription, + servers: ServerDescription[] +) => ServerDescription[]; + +/** + * Returns a server selector that selects for writable servers + */ +export function writableServerSelector(): ServerSelector { + return ( + topologyDescription: TopologyDescription, + servers: ServerDescription[] + ): ServerDescription[] => + latencyWindowReducer( + topologyDescription, + servers.filter((s: ServerDescription) => s.isWritable) + ); +} + +/** + * The purpose of this selector is to select the same server, only + * if it is in a state that it can have commands sent to it. + */ +export function sameServerSelector(description?: ServerDescription): ServerSelector { + return ( + topologyDescription: TopologyDescription, + servers: ServerDescription[] + ): ServerDescription[] => { + if (!description) return []; + // Filter the servers to match the provided description only if + // the type is not unknown. + return servers.filter(sd => { + return sd.address === description.address && sd.type !== ServerType.Unknown; + }); + }; +} + +/** + * Returns a server selector that uses a read preference to select a + * server potentially for a write on a secondary. + */ +export function secondaryWritableServerSelector( + wireVersion?: number, + readPreference?: ReadPreference +): ServerSelector { + // If server version < 5.0, read preference always primary. + // If server version >= 5.0... + // - If read preference is supplied, use that. + // - If no read preference is supplied, use primary. + if ( + !readPreference || + !wireVersion || + (wireVersion && wireVersion < MIN_SECONDARY_WRITE_WIRE_VERSION) + ) { + return readPreferenceServerSelector(ReadPreference.primary); + } + return readPreferenceServerSelector(readPreference); +} + +/** + * Reduces the passed in array of servers by the rules of the "Max Staleness" specification + * found here: https://github.com/mongodb/specifications/blob/master/source/max-staleness/max-staleness.rst + * + * @param readPreference - The read preference providing max staleness guidance + * @param topologyDescription - The topology description + * @param servers - The list of server descriptions to be reduced + * @returns The list of servers that satisfy the requirements of max staleness + */ +function maxStalenessReducer( + readPreference: ReadPreference, + topologyDescription: TopologyDescription, + servers: ServerDescription[] +): ServerDescription[] { + if (readPreference.maxStalenessSeconds == null || readPreference.maxStalenessSeconds < 0) { + return servers; + } + + const maxStaleness = readPreference.maxStalenessSeconds; + const maxStalenessVariance = + (topologyDescription.heartbeatFrequencyMS + IDLE_WRITE_PERIOD) / 1000; + if (maxStaleness < maxStalenessVariance) { + throw new MongoInvalidArgumentError( + `Option "maxStalenessSeconds" must be at least ${maxStalenessVariance} seconds` + ); + } + + if (maxStaleness < SMALLEST_MAX_STALENESS_SECONDS) { + throw new MongoInvalidArgumentError( + `Option "maxStalenessSeconds" must be at least ${SMALLEST_MAX_STALENESS_SECONDS} seconds` + ); + } + + if (topologyDescription.type === TopologyType.ReplicaSetWithPrimary) { + const primary: ServerDescription = Array.from(topologyDescription.servers.values()).filter( + primaryFilter + )[0]; + + return servers.reduce((result: ServerDescription[], server: ServerDescription) => { + const stalenessMS = + server.lastUpdateTime - + server.lastWriteDate - + (primary.lastUpdateTime - primary.lastWriteDate) + + topologyDescription.heartbeatFrequencyMS; + + const staleness = stalenessMS / 1000; + const maxStalenessSeconds = readPreference.maxStalenessSeconds ?? 0; + if (staleness <= maxStalenessSeconds) { + result.push(server); + } + + return result; + }, []); + } + + if (topologyDescription.type === TopologyType.ReplicaSetNoPrimary) { + if (servers.length === 0) { + return servers; + } + + const sMax = servers.reduce((max: ServerDescription, s: ServerDescription) => + s.lastWriteDate > max.lastWriteDate ? s : max + ); + + return servers.reduce((result: ServerDescription[], server: ServerDescription) => { + const stalenessMS = + sMax.lastWriteDate - server.lastWriteDate + topologyDescription.heartbeatFrequencyMS; + + const staleness = stalenessMS / 1000; + const maxStalenessSeconds = readPreference.maxStalenessSeconds ?? 0; + if (staleness <= maxStalenessSeconds) { + result.push(server); + } + + return result; + }, []); + } + + return servers; +} + +/** + * Determines whether a server's tags match a given set of tags + * + * @param tagSet - The requested tag set to match + * @param serverTags - The server's tags + */ +function tagSetMatch(tagSet: TagSet, serverTags: TagSet) { + const keys = Object.keys(tagSet); + const serverTagKeys = Object.keys(serverTags); + for (let i = 0; i < keys.length; ++i) { + const key = keys[i]; + if (serverTagKeys.indexOf(key) === -1 || serverTags[key] !== tagSet[key]) { + return false; + } + } + + return true; +} + +/** + * Reduces a set of server descriptions based on tags requested by the read preference + * + * @param readPreference - The read preference providing the requested tags + * @param servers - The list of server descriptions to reduce + * @returns The list of servers matching the requested tags + */ +function tagSetReducer( + readPreference: ReadPreference, + servers: ServerDescription[] +): ServerDescription[] { + if ( + readPreference.tags == null || + (Array.isArray(readPreference.tags) && readPreference.tags.length === 0) + ) { + return servers; + } + + for (let i = 0; i < readPreference.tags.length; ++i) { + const tagSet = readPreference.tags[i]; + const serversMatchingTagset = servers.reduce( + (matched: ServerDescription[], server: ServerDescription) => { + if (tagSetMatch(tagSet, server.tags)) matched.push(server); + return matched; + }, + [] + ); + + if (serversMatchingTagset.length) { + return serversMatchingTagset; + } + } + + return []; +} + +/** + * Reduces a list of servers to ensure they fall within an acceptable latency window. This is + * further specified in the "Server Selection" specification, found here: + * https://github.com/mongodb/specifications/blob/master/source/server-selection/server-selection.rst + * + * @param topologyDescription - The topology description + * @param servers - The list of servers to reduce + * @returns The servers which fall within an acceptable latency window + */ +function latencyWindowReducer( + topologyDescription: TopologyDescription, + servers: ServerDescription[] +): ServerDescription[] { + const low = servers.reduce( + (min: number, server: ServerDescription) => + min === -1 ? server.roundTripTime : Math.min(server.roundTripTime, min), + -1 + ); + + const high = low + topologyDescription.localThresholdMS; + return servers.reduce((result: ServerDescription[], server: ServerDescription) => { + if (server.roundTripTime <= high && server.roundTripTime >= low) result.push(server); + return result; + }, []); +} + +// filters +function primaryFilter(server: ServerDescription): boolean { + return server.type === ServerType.RSPrimary; +} + +function secondaryFilter(server: ServerDescription): boolean { + return server.type === ServerType.RSSecondary; +} + +function nearestFilter(server: ServerDescription): boolean { + return server.type === ServerType.RSSecondary || server.type === ServerType.RSPrimary; +} + +function knownFilter(server: ServerDescription): boolean { + return server.type !== ServerType.Unknown; +} + +function loadBalancerFilter(server: ServerDescription): boolean { + return server.type === ServerType.LoadBalancer; +} + +/** + * Returns a function which selects servers based on a provided read preference + * + * @param readPreference - The read preference to select with + */ +export function readPreferenceServerSelector(readPreference: ReadPreference): ServerSelector { + if (!readPreference.isValid()) { + throw new MongoInvalidArgumentError('Invalid read preference specified'); + } + + return ( + topologyDescription: TopologyDescription, + servers: ServerDescription[] + ): ServerDescription[] => { + const commonWireVersion = topologyDescription.commonWireVersion; + if ( + commonWireVersion && + readPreference.minWireVersion && + readPreference.minWireVersion > commonWireVersion + ) { + throw new MongoCompatibilityError( + `Minimum wire version '${readPreference.minWireVersion}' required, but found '${commonWireVersion}'` + ); + } + + if (topologyDescription.type === TopologyType.LoadBalanced) { + return servers.filter(loadBalancerFilter); + } + + if (topologyDescription.type === TopologyType.Unknown) { + return []; + } + + if ( + topologyDescription.type === TopologyType.Single || + topologyDescription.type === TopologyType.Sharded + ) { + return latencyWindowReducer(topologyDescription, servers.filter(knownFilter)); + } + + const mode = readPreference.mode; + if (mode === ReadPreference.PRIMARY) { + return servers.filter(primaryFilter); + } + + if (mode === ReadPreference.PRIMARY_PREFERRED) { + const result = servers.filter(primaryFilter); + if (result.length) { + return result; + } + } + + const filter = mode === ReadPreference.NEAREST ? nearestFilter : secondaryFilter; + const selectedServers = latencyWindowReducer( + topologyDescription, + tagSetReducer( + readPreference, + maxStalenessReducer(readPreference, topologyDescription, servers.filter(filter)) + ) + ); + + if (mode === ReadPreference.SECONDARY_PREFERRED && selectedServers.length === 0) { + return servers.filter(primaryFilter); + } + + return selectedServers; + }; +} diff --git a/ts-ticket-office-service/node_modules/mongodb/src/sdam/srv_polling.ts b/ts-ticket-office-service/node_modules/mongodb/src/sdam/srv_polling.ts new file mode 100644 index 000000000..71ee20a47 --- /dev/null +++ b/ts-ticket-office-service/node_modules/mongodb/src/sdam/srv_polling.ts @@ -0,0 +1,165 @@ +import * as dns from 'dns'; +import { setTimeout } from 'timers'; + +import { MongoRuntimeError } from '../error'; +import { Logger, LoggerOptions } from '../logger'; +import { TypedEventEmitter } from '../mongo_types'; +import { HostAddress } from '../utils'; + +/** + * Determines whether a provided address matches the provided parent domain in order + * to avoid certain attack vectors. + * + * @param srvAddress - The address to check against a domain + * @param parentDomain - The domain to check the provided address against + * @returns Whether the provided address matches the parent domain + */ +function matchesParentDomain(srvAddress: string, parentDomain: string): boolean { + const regex = /^.*?\./; + const srv = `.${srvAddress.replace(regex, '')}`; + const parent = `.${parentDomain.replace(regex, '')}`; + return srv.endsWith(parent); +} + +/** + * @internal + * @category Event + */ +export class SrvPollingEvent { + srvRecords: dns.SrvRecord[]; + constructor(srvRecords: dns.SrvRecord[]) { + this.srvRecords = srvRecords; + } + + hostnames(): Set { + return new Set(this.srvRecords.map(r => HostAddress.fromSrvRecord(r).toString())); + } +} + +/** @internal */ +export interface SrvPollerOptions extends LoggerOptions { + srvServiceName: string; + srvMaxHosts: number; + srvHost: string; + heartbeatFrequencyMS: number; +} + +/** @internal */ +export type SrvPollerEvents = { + srvRecordDiscovery(event: SrvPollingEvent): void; +}; + +/** @internal */ +export class SrvPoller extends TypedEventEmitter { + srvHost: string; + rescanSrvIntervalMS: number; + heartbeatFrequencyMS: number; + logger: Logger; + haMode: boolean; + generation: number; + srvMaxHosts: number; + srvServiceName: string; + _timeout?: NodeJS.Timeout; + + /** @event */ + static readonly SRV_RECORD_DISCOVERY = 'srvRecordDiscovery' as const; + + constructor(options: SrvPollerOptions) { + super(); + + if (!options || !options.srvHost) { + throw new MongoRuntimeError('Options for SrvPoller must exist and include srvHost'); + } + + this.srvHost = options.srvHost; + this.srvMaxHosts = options.srvMaxHosts ?? 0; + this.srvServiceName = options.srvServiceName ?? 'mongodb'; + this.rescanSrvIntervalMS = 60000; + this.heartbeatFrequencyMS = options.heartbeatFrequencyMS ?? 10000; + this.logger = new Logger('srvPoller', options); + + this.haMode = false; + this.generation = 0; + + this._timeout = undefined; + } + + get srvAddress(): string { + return `_${this.srvServiceName}._tcp.${this.srvHost}`; + } + + get intervalMS(): number { + return this.haMode ? this.heartbeatFrequencyMS : this.rescanSrvIntervalMS; + } + + start(): void { + if (!this._timeout) { + this.schedule(); + } + } + + stop(): void { + if (this._timeout) { + clearTimeout(this._timeout); + this.generation += 1; + this._timeout = undefined; + } + } + + schedule(): void { + if (this._timeout) { + clearTimeout(this._timeout); + } + + this._timeout = setTimeout(() => this._poll(), this.intervalMS); + } + + success(srvRecords: dns.SrvRecord[]): void { + this.haMode = false; + this.schedule(); + this.emit(SrvPoller.SRV_RECORD_DISCOVERY, new SrvPollingEvent(srvRecords)); + } + + failure(message: string, obj?: NodeJS.ErrnoException): void { + this.logger.warn(message, obj); + this.haMode = true; + this.schedule(); + } + + parentDomainMismatch(srvRecord: dns.SrvRecord): void { + this.logger.warn( + `parent domain mismatch on SRV record (${srvRecord.name}:${srvRecord.port})`, + srvRecord + ); + } + + _poll(): void { + const generation = this.generation; + dns.resolveSrv(this.srvAddress, (err, srvRecords) => { + if (generation !== this.generation) { + return; + } + + if (err) { + this.failure('DNS error', err); + return; + } + + const finalAddresses: dns.SrvRecord[] = []; + for (const record of srvRecords) { + if (matchesParentDomain(record.name, this.srvHost)) { + finalAddresses.push(record); + } else { + this.parentDomainMismatch(record); + } + } + + if (!finalAddresses.length) { + this.failure('No valid addresses found at host'); + return; + } + + this.success(finalAddresses); + }); + } +} diff --git a/ts-ticket-office-service/node_modules/mongodb/src/sdam/topology.ts b/ts-ticket-office-service/node_modules/mongodb/src/sdam/topology.ts new file mode 100644 index 000000000..a3505bd7a --- /dev/null +++ b/ts-ticket-office-service/node_modules/mongodb/src/sdam/topology.ts @@ -0,0 +1,1007 @@ +import Denque = require('denque'); +import { setTimeout } from 'timers'; +import { promisify } from 'util'; + +import type { BSONSerializeOptions, Document } from '../bson'; +import { deserialize, serialize } from '../bson'; +import type { MongoCredentials } from '../cmap/auth/mongo_credentials'; +import type { ConnectionEvents, DestroyOptions } from '../cmap/connection'; +import type { CloseOptions, ConnectionPoolEvents } from '../cmap/connection_pool'; +import { DEFAULT_OPTIONS, FEATURE_FLAGS } from '../connection_string'; +import { + CLOSE, + CONNECT, + ERROR, + LOCAL_SERVER_EVENTS, + OPEN, + SERVER_CLOSED, + SERVER_DESCRIPTION_CHANGED, + SERVER_OPENING, + SERVER_RELAY_EVENTS, + TIMEOUT, + TOPOLOGY_CLOSED, + TOPOLOGY_DESCRIPTION_CHANGED, + TOPOLOGY_OPENING +} from '../constants'; +import { + MongoCompatibilityError, + MongoDriverError, + MongoRuntimeError, + MongoServerSelectionError, + MongoTopologyClosedError +} from '../error'; +import type { MongoClient, ServerApi } from '../mongo_client'; +import { TypedEventEmitter } from '../mongo_types'; +import { ReadPreference, ReadPreferenceLike } from '../read_preference'; +import type { ClientSession } from '../sessions'; +import type { Transaction } from '../transactions'; +import { + Callback, + ClientMetadata, + emitWarning, + EventEmitterWithState, + HostAddress, + makeStateMachine, + ns, + shuffle +} from '../utils'; +import { + _advanceClusterTime, + ClusterTime, + drainTimerQueue, + ServerType, + STATE_CLOSED, + STATE_CLOSING, + STATE_CONNECTED, + STATE_CONNECTING, + TimerQueue, + TopologyType +} from './common'; +import { + ServerClosedEvent, + ServerDescriptionChangedEvent, + ServerOpeningEvent, + TopologyClosedEvent, + TopologyDescriptionChangedEvent, + TopologyOpeningEvent +} from './events'; +import { Server, ServerEvents, ServerOptions } from './server'; +import { compareTopologyVersion, ServerDescription } from './server_description'; +import { readPreferenceServerSelector, ServerSelector } from './server_selection'; +import { SrvPoller, SrvPollingEvent } from './srv_polling'; +import { TopologyDescription } from './topology_description'; + +// Global state +let globalTopologyCounter = 0; + +const stateTransition = makeStateMachine({ + [STATE_CLOSED]: [STATE_CLOSED, STATE_CONNECTING], + [STATE_CONNECTING]: [STATE_CONNECTING, STATE_CLOSING, STATE_CONNECTED, STATE_CLOSED], + [STATE_CONNECTED]: [STATE_CONNECTED, STATE_CLOSING, STATE_CLOSED], + [STATE_CLOSING]: [STATE_CLOSING, STATE_CLOSED] +}); + +/** @internal */ +const kCancelled = Symbol('cancelled'); +/** @internal */ +const kWaitQueue = Symbol('waitQueue'); + +/** @internal */ +export type ServerSelectionCallback = Callback; + +/** @internal */ +export interface ServerSelectionRequest { + serverSelector: ServerSelector; + transaction?: Transaction; + callback: ServerSelectionCallback; + timer?: NodeJS.Timeout; + [kCancelled]?: boolean; +} + +/** @internal */ +export interface TopologyPrivate { + /** the id of this topology */ + id: number; + /** passed in options */ + options: TopologyOptions; + /** initial seedlist of servers to connect to */ + seedlist: HostAddress[]; + /** initial state */ + state: string; + /** the topology description */ + description: TopologyDescription; + serverSelectionTimeoutMS: number; + heartbeatFrequencyMS: number; + minHeartbeatFrequencyMS: number; + /** A map of server instances to normalized addresses */ + servers: Map; + credentials?: MongoCredentials; + clusterTime?: ClusterTime; + /** timers created for the initial connect to a server */ + connectionTimers: TimerQueue; + + /** related to srv polling */ + srvPoller?: SrvPoller; + detectShardedTopology: (event: TopologyDescriptionChangedEvent) => void; + detectSrvRecords: (event: SrvPollingEvent) => void; +} + +/** @public */ +export interface TopologyOptions extends BSONSerializeOptions, ServerOptions { + srvMaxHosts: number; + srvServiceName: string; + hosts: HostAddress[]; + retryWrites: boolean; + retryReads: boolean; + /** How long to block for server selection before throwing an error */ + serverSelectionTimeoutMS: number; + /** The name of the replica set to connect to */ + replicaSet?: string; + srvHost?: string; + /** @internal */ + srvPoller?: SrvPoller; + /** Indicates that a client should directly connect to a node without attempting to discover its topology type */ + directConnection: boolean; + loadBalanced: boolean; + metadata: ClientMetadata; + /** MongoDB server API version */ + serverApi?: ServerApi; + /** @internal */ + [featureFlag: symbol]: any; +} + +/** @public */ +export interface ConnectOptions { + readPreference?: ReadPreference; +} + +/** @public */ +export interface SelectServerOptions { + readPreference?: ReadPreferenceLike; + /** How long to block for server selection before throwing an error */ + serverSelectionTimeoutMS?: number; + session?: ClientSession; +} + +/** @public */ +export type TopologyEvents = { + /** Top level MongoClient doesn't emit this so it is marked: @internal */ + connect(topology: Topology): void; + serverOpening(event: ServerOpeningEvent): void; + serverClosed(event: ServerClosedEvent): void; + serverDescriptionChanged(event: ServerDescriptionChangedEvent): void; + topologyClosed(event: TopologyClosedEvent): void; + topologyOpening(event: TopologyOpeningEvent): void; + topologyDescriptionChanged(event: TopologyDescriptionChangedEvent): void; + error(error: Error): void; + /** @internal */ + open(topology: Topology): void; + close(): void; + timeout(): void; +} & Omit & + ConnectionPoolEvents & + ConnectionEvents & + EventEmitterWithState; +/** + * A container of server instances representing a connection to a MongoDB topology. + * @internal + */ +export class Topology extends TypedEventEmitter { + /** @internal */ + s: TopologyPrivate; + /** @internal */ + [kWaitQueue]: Denque; + /** @internal */ + hello?: Document; + /** @internal */ + _type?: string; + + client!: MongoClient; + + /** @event */ + static readonly SERVER_OPENING = SERVER_OPENING; + /** @event */ + static readonly SERVER_CLOSED = SERVER_CLOSED; + /** @event */ + static readonly SERVER_DESCRIPTION_CHANGED = SERVER_DESCRIPTION_CHANGED; + /** @event */ + static readonly TOPOLOGY_OPENING = TOPOLOGY_OPENING; + /** @event */ + static readonly TOPOLOGY_CLOSED = TOPOLOGY_CLOSED; + /** @event */ + static readonly TOPOLOGY_DESCRIPTION_CHANGED = TOPOLOGY_DESCRIPTION_CHANGED; + /** @event */ + static readonly ERROR = ERROR; + /** @event */ + static readonly OPEN = OPEN; + /** @event */ + static readonly CONNECT = CONNECT; + /** @event */ + static readonly CLOSE = CLOSE; + /** @event */ + static readonly TIMEOUT = TIMEOUT; + + /** + * @internal + * + * @privateRemarks + * mongodb-client-encryption's class ClientEncryption falls back to finding the bson lib + * defined on client.topology.bson, in order to maintain compatibility with any version + * of mongodb-client-encryption we keep a reference to serialize and deserialize here. + */ + bson: { serialize: typeof serialize; deserialize: typeof deserialize }; + + /** + * @param seedlist - a list of HostAddress instances to connect to + */ + constructor(seeds: string | string[] | HostAddress | HostAddress[], options: TopologyOptions) { + super(); + + // Legacy CSFLE support + this.bson = Object.create(null); + this.bson.serialize = serialize; + this.bson.deserialize = deserialize; + + // Options should only be undefined in tests, MongoClient will always have defined options + options = options ?? { + hosts: [HostAddress.fromString('localhost:27017')], + ...Object.fromEntries(DEFAULT_OPTIONS.entries()), + ...Object.fromEntries(FEATURE_FLAGS.entries()) + }; + + if (typeof seeds === 'string') { + seeds = [HostAddress.fromString(seeds)]; + } else if (!Array.isArray(seeds)) { + seeds = [seeds]; + } + + const seedlist: HostAddress[] = []; + for (const seed of seeds) { + if (typeof seed === 'string') { + seedlist.push(HostAddress.fromString(seed)); + } else if (seed instanceof HostAddress) { + seedlist.push(seed); + } else { + // FIXME(NODE-3483): May need to be a MongoParseError + throw new MongoRuntimeError(`Topology cannot be constructed from ${JSON.stringify(seed)}`); + } + } + + const topologyType = topologyTypeFromOptions(options); + const topologyId = globalTopologyCounter++; + + const selectedHosts = + options.srvMaxHosts == null || + options.srvMaxHosts === 0 || + options.srvMaxHosts >= seedlist.length + ? seedlist + : shuffle(seedlist, options.srvMaxHosts); + + const serverDescriptions = new Map(); + for (const hostAddress of selectedHosts) { + serverDescriptions.set(hostAddress.toString(), new ServerDescription(hostAddress)); + } + + this[kWaitQueue] = new Denque(); + this.s = { + // the id of this topology + id: topologyId, + // passed in options + options, + // initial seedlist of servers to connect to + seedlist, + // initial state + state: STATE_CLOSED, + // the topology description + description: new TopologyDescription( + topologyType, + serverDescriptions, + options.replicaSet, + undefined, + undefined, + undefined, + options + ), + serverSelectionTimeoutMS: options.serverSelectionTimeoutMS, + heartbeatFrequencyMS: options.heartbeatFrequencyMS, + minHeartbeatFrequencyMS: options.minHeartbeatFrequencyMS, + // a map of server instances to normalized addresses + servers: new Map(), + credentials: options?.credentials, + clusterTime: undefined, + + // timer management + connectionTimers: new Set(), + detectShardedTopology: ev => this.detectShardedTopology(ev), + detectSrvRecords: ev => this.detectSrvRecords(ev) + }; + + if (options.srvHost && !options.loadBalanced) { + this.s.srvPoller = + options.srvPoller ?? + new SrvPoller({ + heartbeatFrequencyMS: this.s.heartbeatFrequencyMS, + srvHost: options.srvHost, + srvMaxHosts: options.srvMaxHosts, + srvServiceName: options.srvServiceName + }); + + this.on(Topology.TOPOLOGY_DESCRIPTION_CHANGED, this.s.detectShardedTopology); + } + } + + private detectShardedTopology(event: TopologyDescriptionChangedEvent) { + const previousType = event.previousDescription.type; + const newType = event.newDescription.type; + + const transitionToSharded = + previousType !== TopologyType.Sharded && newType === TopologyType.Sharded; + const srvListeners = this.s.srvPoller?.listeners(SrvPoller.SRV_RECORD_DISCOVERY); + const listeningToSrvPolling = !!srvListeners?.includes(this.s.detectSrvRecords); + + if (transitionToSharded && !listeningToSrvPolling) { + this.s.srvPoller?.on(SrvPoller.SRV_RECORD_DISCOVERY, this.s.detectSrvRecords); + this.s.srvPoller?.start(); + } + } + + private detectSrvRecords(ev: SrvPollingEvent) { + const previousTopologyDescription = this.s.description; + this.s.description = this.s.description.updateFromSrvPollingEvent( + ev, + this.s.options.srvMaxHosts + ); + if (this.s.description === previousTopologyDescription) { + // Nothing changed, so return + return; + } + + updateServers(this); + + this.emit( + Topology.TOPOLOGY_DESCRIPTION_CHANGED, + new TopologyDescriptionChangedEvent( + this.s.id, + previousTopologyDescription, + this.s.description + ) + ); + } + + /** + * @returns A `TopologyDescription` for this topology + */ + get description(): TopologyDescription { + return this.s.description; + } + + get loadBalanced(): boolean { + return this.s.options.loadBalanced; + } + + get capabilities(): ServerCapabilities { + return new ServerCapabilities(this.lastHello()); + } + + /** Initiate server connect */ + connect(options?: ConnectOptions, callback?: Callback): void { + if (typeof options === 'function') (callback = options), (options = {}); + options = options ?? {}; + if (this.s.state === STATE_CONNECTED) { + if (typeof callback === 'function') { + callback(); + } + + return; + } + + stateTransition(this, STATE_CONNECTING); + + // emit SDAM monitoring events + this.emit(Topology.TOPOLOGY_OPENING, new TopologyOpeningEvent(this.s.id)); + + // emit an event for the topology change + this.emit( + Topology.TOPOLOGY_DESCRIPTION_CHANGED, + new TopologyDescriptionChangedEvent( + this.s.id, + new TopologyDescription(TopologyType.Unknown), // initial is always Unknown + this.s.description + ) + ); + + // connect all known servers, then attempt server selection to connect + const serverDescriptions = Array.from(this.s.description.servers.values()); + this.s.servers = new Map( + serverDescriptions.map(serverDescription => [ + serverDescription.address, + createAndConnectServer(this, serverDescription) + ]) + ); + + // In load balancer mode we need to fake a server description getting + // emitted from the monitor, since the monitor doesn't exist. + if (this.s.options.loadBalanced) { + for (const description of serverDescriptions) { + const newDescription = new ServerDescription(description.hostAddress, undefined, { + loadBalanced: this.s.options.loadBalanced + }); + this.serverUpdateHandler(newDescription); + } + } + + const exitWithError = (error: Error) => + callback ? callback(error) : this.emit(Topology.ERROR, error); + + const readPreference = options.readPreference ?? ReadPreference.primary; + this.selectServer(readPreferenceServerSelector(readPreference), options, (err, server) => { + if (err) { + return this.close({ force: false }, () => exitWithError(err)); + } + + // TODO: NODE-2471 + const skipPingOnConnect = this.s.options[Symbol.for('@@mdb.skipPingOnConnect')] === true; + if (!skipPingOnConnect && server && this.s.credentials) { + server.command(ns('admin.$cmd'), { ping: 1 }, {}, err => { + if (err) { + return exitWithError(err); + } + + stateTransition(this, STATE_CONNECTED); + this.emit(Topology.OPEN, this); + this.emit(Topology.CONNECT, this); + + callback?.(undefined, this); + }); + + return; + } + + stateTransition(this, STATE_CONNECTED); + this.emit(Topology.OPEN, this); + this.emit(Topology.CONNECT, this); + + callback?.(undefined, this); + }); + } + + /** Close this topology */ + close(options?: CloseOptions, callback?: Callback): void { + if (typeof options === 'function') { + callback = options; + options = {}; + } + + if (typeof options === 'boolean') { + options = { force: options }; + } + options = options ?? {}; + + if (this.s.state === STATE_CLOSED || this.s.state === STATE_CLOSING) { + return callback?.(); + } + + const destroyedServers = Array.from(this.s.servers.values(), server => { + return promisify(destroyServer)(server, this, options); + }); + + Promise.all(destroyedServers) + .then(() => { + this.s.servers.clear(); + + stateTransition(this, STATE_CLOSING); + + drainWaitQueue(this[kWaitQueue], new MongoTopologyClosedError()); + drainTimerQueue(this.s.connectionTimers); + + if (this.s.srvPoller) { + this.s.srvPoller.stop(); + this.s.srvPoller.removeListener(SrvPoller.SRV_RECORD_DISCOVERY, this.s.detectSrvRecords); + } + + this.removeListener(Topology.TOPOLOGY_DESCRIPTION_CHANGED, this.s.detectShardedTopology); + + stateTransition(this, STATE_CLOSED); + + // emit an event for close + this.emit(Topology.TOPOLOGY_CLOSED, new TopologyClosedEvent(this.s.id)); + }) + .finally(() => callback?.()); + } + + /** + * Selects a server according to the selection predicate provided + * + * @param selector - An optional selector to select servers by, defaults to a random selection within a latency window + * @param options - Optional settings related to server selection + * @param callback - The callback used to indicate success or failure + * @returns An instance of a `Server` meeting the criteria of the predicate provided + */ + selectServer( + selector: string | ReadPreference | ServerSelector, + options: SelectServerOptions, + callback: Callback + ): void { + let serverSelector; + if (typeof selector !== 'function') { + if (typeof selector === 'string') { + serverSelector = readPreferenceServerSelector(ReadPreference.fromString(selector)); + } else { + let readPreference; + if (selector instanceof ReadPreference) { + readPreference = selector; + } else { + ReadPreference.translate(options); + readPreference = options.readPreference || ReadPreference.primary; + } + + serverSelector = readPreferenceServerSelector(readPreference as ReadPreference); + } + } else { + serverSelector = selector; + } + + options = Object.assign( + {}, + { serverSelectionTimeoutMS: this.s.serverSelectionTimeoutMS }, + options + ); + + const isSharded = this.description.type === TopologyType.Sharded; + const session = options.session; + const transaction = session && session.transaction; + + if (isSharded && transaction && transaction.server) { + callback(undefined, transaction.server); + return; + } + + const waitQueueMember: ServerSelectionRequest = { + serverSelector, + transaction, + callback + }; + + const serverSelectionTimeoutMS = options.serverSelectionTimeoutMS; + if (serverSelectionTimeoutMS) { + waitQueueMember.timer = setTimeout(() => { + waitQueueMember[kCancelled] = true; + waitQueueMember.timer = undefined; + const timeoutError = new MongoServerSelectionError( + `Server selection timed out after ${serverSelectionTimeoutMS} ms`, + this.description + ); + + waitQueueMember.callback(timeoutError); + }, serverSelectionTimeoutMS); + } + + this[kWaitQueue].push(waitQueueMember); + processWaitQueue(this); + } + + // Sessions related methods + + /** + * @returns Whether the topology should initiate selection to determine session support + */ + shouldCheckForSessionSupport(): boolean { + if (this.description.type === TopologyType.Single) { + return !this.description.hasKnownServers; + } + + return !this.description.hasDataBearingServers; + } + + /** + * @returns Whether sessions are supported on the current topology + */ + hasSessionSupport(): boolean { + return this.loadBalanced || this.description.logicalSessionTimeoutMinutes != null; + } + + /** + * Update the internal TopologyDescription with a ServerDescription + * + * @param serverDescription - The server to update in the internal list of server descriptions + */ + serverUpdateHandler(serverDescription: ServerDescription): void { + if (!this.s.description.hasServer(serverDescription.address)) { + return; + } + + // ignore this server update if its from an outdated topologyVersion + if (isStaleServerDescription(this.s.description, serverDescription)) { + return; + } + + // these will be used for monitoring events later + const previousTopologyDescription = this.s.description; + const previousServerDescription = this.s.description.servers.get(serverDescription.address); + if (!previousServerDescription) { + return; + } + + // Driver Sessions Spec: "Whenever a driver receives a cluster time from + // a server it MUST compare it to the current highest seen cluster time + // for the deployment. If the new cluster time is higher than the + // highest seen cluster time it MUST become the new highest seen cluster + // time. Two cluster times are compared using only the BsonTimestamp + // value of the clusterTime embedded field." + const clusterTime = serverDescription.$clusterTime; + if (clusterTime) { + _advanceClusterTime(this, clusterTime); + } + + // If we already know all the information contained in this updated description, then + // we don't need to emit SDAM events, but still need to update the description, in order + // to keep client-tracked attributes like last update time and round trip time up to date + const equalDescriptions = + previousServerDescription && previousServerDescription.equals(serverDescription); + + // first update the TopologyDescription + this.s.description = this.s.description.update(serverDescription); + if (this.s.description.compatibilityError) { + this.emit(Topology.ERROR, new MongoCompatibilityError(this.s.description.compatibilityError)); + return; + } + + // emit monitoring events for this change + if (!equalDescriptions) { + const newDescription = this.s.description.servers.get(serverDescription.address); + if (newDescription) { + this.emit( + Topology.SERVER_DESCRIPTION_CHANGED, + new ServerDescriptionChangedEvent( + this.s.id, + serverDescription.address, + previousServerDescription, + newDescription + ) + ); + } + } + + // update server list from updated descriptions + updateServers(this, serverDescription); + + // attempt to resolve any outstanding server selection attempts + if (this[kWaitQueue].length > 0) { + processWaitQueue(this); + } + + if (!equalDescriptions) { + this.emit( + Topology.TOPOLOGY_DESCRIPTION_CHANGED, + new TopologyDescriptionChangedEvent( + this.s.id, + previousTopologyDescription, + this.s.description + ) + ); + } + } + + auth(credentials?: MongoCredentials, callback?: Callback): void { + if (typeof credentials === 'function') (callback = credentials), (credentials = undefined); + if (typeof callback === 'function') callback(undefined, true); + } + + get clientMetadata(): ClientMetadata { + return this.s.options.metadata; + } + + isConnected(): boolean { + return this.s.state === STATE_CONNECTED; + } + + isDestroyed(): boolean { + return this.s.state === STATE_CLOSED; + } + + /** + * @deprecated This function is deprecated and will be removed in the next major version. + */ + unref(): void { + emitWarning('`unref` is a noop and will be removed in the next major version'); + } + + // NOTE: There are many places in code where we explicitly check the last hello + // to do feature support detection. This should be done any other way, but for + // now we will just return the first hello seen, which should suffice. + lastHello(): Document { + const serverDescriptions = Array.from(this.description.servers.values()); + if (serverDescriptions.length === 0) return {}; + const sd = serverDescriptions.filter( + (sd: ServerDescription) => sd.type !== ServerType.Unknown + )[0]; + + const result = sd || { maxWireVersion: this.description.commonWireVersion }; + return result; + } + + get commonWireVersion(): number | undefined { + return this.description.commonWireVersion; + } + + get logicalSessionTimeoutMinutes(): number | undefined { + return this.description.logicalSessionTimeoutMinutes; + } + + get clusterTime(): ClusterTime | undefined { + return this.s.clusterTime; + } + + set clusterTime(clusterTime: ClusterTime | undefined) { + this.s.clusterTime = clusterTime; + } +} + +/** Destroys a server, and removes all event listeners from the instance */ +function destroyServer( + server: Server, + topology: Topology, + options?: DestroyOptions, + callback?: Callback +) { + options = options ?? {}; + for (const event of LOCAL_SERVER_EVENTS) { + server.removeAllListeners(event); + } + + server.destroy(options, () => { + topology.emit( + Topology.SERVER_CLOSED, + new ServerClosedEvent(topology.s.id, server.description.address) + ); + + for (const event of SERVER_RELAY_EVENTS) { + server.removeAllListeners(event); + } + if (typeof callback === 'function') { + callback(); + } + }); +} + +/** Predicts the TopologyType from options */ +function topologyTypeFromOptions(options?: TopologyOptions) { + if (options?.directConnection) { + return TopologyType.Single; + } + + if (options?.replicaSet) { + return TopologyType.ReplicaSetNoPrimary; + } + + if (options?.loadBalanced) { + return TopologyType.LoadBalanced; + } + + return TopologyType.Unknown; +} + +/** + * Creates new server instances and attempts to connect them + * + * @param topology - The topology that this server belongs to + * @param serverDescription - The description for the server to initialize and connect to + */ +function createAndConnectServer(topology: Topology, serverDescription: ServerDescription) { + topology.emit( + Topology.SERVER_OPENING, + new ServerOpeningEvent(topology.s.id, serverDescription.address) + ); + + const server = new Server(topology, serverDescription, topology.s.options); + for (const event of SERVER_RELAY_EVENTS) { + server.on(event, (e: any) => topology.emit(event, e)); + } + + server.on(Server.DESCRIPTION_RECEIVED, description => topology.serverUpdateHandler(description)); + + server.connect(); + return server; +} + +/** + * @param topology - Topology to update. + * @param incomingServerDescription - New server description. + */ +function updateServers(topology: Topology, incomingServerDescription?: ServerDescription) { + // update the internal server's description + if (incomingServerDescription && topology.s.servers.has(incomingServerDescription.address)) { + const server = topology.s.servers.get(incomingServerDescription.address); + if (server) { + server.s.description = incomingServerDescription; + } + } + + // add new servers for all descriptions we currently don't know about locally + for (const serverDescription of topology.description.servers.values()) { + if (!topology.s.servers.has(serverDescription.address)) { + const server = createAndConnectServer(topology, serverDescription); + topology.s.servers.set(serverDescription.address, server); + } + } + + // for all servers no longer known, remove their descriptions and destroy their instances + for (const entry of topology.s.servers) { + const serverAddress = entry[0]; + if (topology.description.hasServer(serverAddress)) { + continue; + } + + if (!topology.s.servers.has(serverAddress)) { + continue; + } + + const server = topology.s.servers.get(serverAddress); + topology.s.servers.delete(serverAddress); + + // prepare server for garbage collection + if (server) { + destroyServer(server, topology); + } + } +} + +function drainWaitQueue(queue: Denque, err?: MongoDriverError) { + while (queue.length) { + const waitQueueMember = queue.shift(); + if (!waitQueueMember) { + continue; + } + + if (waitQueueMember.timer) { + clearTimeout(waitQueueMember.timer); + } + + if (!waitQueueMember[kCancelled]) { + waitQueueMember.callback(err); + } + } +} + +function processWaitQueue(topology: Topology) { + if (topology.s.state === STATE_CLOSED) { + drainWaitQueue(topology[kWaitQueue], new MongoTopologyClosedError()); + return; + } + + const isSharded = topology.description.type === TopologyType.Sharded; + const serverDescriptions = Array.from(topology.description.servers.values()); + const membersToProcess = topology[kWaitQueue].length; + for (let i = 0; i < membersToProcess; ++i) { + const waitQueueMember = topology[kWaitQueue].shift(); + if (!waitQueueMember) { + continue; + } + + if (waitQueueMember[kCancelled]) { + continue; + } + + let selectedDescriptions; + try { + const serverSelector = waitQueueMember.serverSelector; + selectedDescriptions = serverSelector + ? serverSelector(topology.description, serverDescriptions) + : serverDescriptions; + } catch (e) { + if (waitQueueMember.timer) { + clearTimeout(waitQueueMember.timer); + } + + waitQueueMember.callback(e); + continue; + } + + let selectedServer; + if (selectedDescriptions.length === 0) { + topology[kWaitQueue].push(waitQueueMember); + continue; + } else if (selectedDescriptions.length === 1) { + selectedServer = topology.s.servers.get(selectedDescriptions[0].address); + } else { + // don't shuffle the array if there are only two elements + const descriptions = + selectedDescriptions.length === 2 ? selectedDescriptions : shuffle(selectedDescriptions, 2); + const server1 = topology.s.servers.get(descriptions[0].address); + const server2 = topology.s.servers.get(descriptions[1].address); + + selectedServer = + server1 && server2 && server1.s.operationCount < server2.s.operationCount + ? server1 + : server2; + } + + if (!selectedServer) { + waitQueueMember.callback( + new MongoServerSelectionError( + 'server selection returned a server description but the server was not found in the topology', + topology.description + ) + ); + return; + } + const transaction = waitQueueMember.transaction; + if (isSharded && transaction && transaction.isActive && selectedServer) { + transaction.pinServer(selectedServer); + } + + if (waitQueueMember.timer) { + clearTimeout(waitQueueMember.timer); + } + + waitQueueMember.callback(undefined, selectedServer); + } + + if (topology[kWaitQueue].length > 0) { + // ensure all server monitors attempt monitoring soon + for (const [, server] of topology.s.servers) { + process.nextTick(function scheduleServerCheck() { + return server.requestCheck(); + }); + } + } +} + +function isStaleServerDescription( + topologyDescription: TopologyDescription, + incomingServerDescription: ServerDescription +) { + const currentServerDescription = topologyDescription.servers.get( + incomingServerDescription.address + ); + const currentTopologyVersion = currentServerDescription?.topologyVersion; + return ( + compareTopologyVersion(currentTopologyVersion, incomingServerDescription.topologyVersion) > 0 + ); +} + +/** @public */ +export class ServerCapabilities { + maxWireVersion: number; + minWireVersion: number; + + constructor(hello: Document) { + this.minWireVersion = hello.minWireVersion || 0; + this.maxWireVersion = hello.maxWireVersion || 0; + } + + get hasAggregationCursor(): boolean { + return this.maxWireVersion >= 1; + } + + get hasWriteCommands(): boolean { + return this.maxWireVersion >= 2; + } + get hasTextSearch(): boolean { + return this.minWireVersion >= 0; + } + + get hasAuthCommands(): boolean { + return this.maxWireVersion >= 1; + } + + get hasListCollectionsCommand(): boolean { + return this.maxWireVersion >= 3; + } + + get hasListIndexesCommand(): boolean { + return this.maxWireVersion >= 3; + } + + get supportsSnapshotReads(): boolean { + return this.maxWireVersion >= 13; + } + + get commandsTakeWriteConcern(): boolean { + return this.maxWireVersion >= 5; + } + + get commandsTakeCollation(): boolean { + return this.maxWireVersion >= 5; + } +} diff --git a/ts-ticket-office-service/node_modules/mongodb/src/sdam/topology_description.ts b/ts-ticket-office-service/node_modules/mongodb/src/sdam/topology_description.ts new file mode 100644 index 000000000..34db44f0e --- /dev/null +++ b/ts-ticket-office-service/node_modules/mongodb/src/sdam/topology_description.ts @@ -0,0 +1,510 @@ +import type { Document, ObjectId } from '../bson'; +import * as WIRE_CONSTANTS from '../cmap/wire_protocol/constants'; +import { MongoError, MongoRuntimeError } from '../error'; +import { shuffle } from '../utils'; +import { ServerType, TopologyType } from './common'; +import { ServerDescription } from './server_description'; +import type { SrvPollingEvent } from './srv_polling'; + +// constants related to compatibility checks +const MIN_SUPPORTED_SERVER_VERSION = WIRE_CONSTANTS.MIN_SUPPORTED_SERVER_VERSION; +const MAX_SUPPORTED_SERVER_VERSION = WIRE_CONSTANTS.MAX_SUPPORTED_SERVER_VERSION; +const MIN_SUPPORTED_WIRE_VERSION = WIRE_CONSTANTS.MIN_SUPPORTED_WIRE_VERSION; +const MAX_SUPPORTED_WIRE_VERSION = WIRE_CONSTANTS.MAX_SUPPORTED_WIRE_VERSION; + +const MONGOS_OR_UNKNOWN = new Set([ServerType.Mongos, ServerType.Unknown]); +const MONGOS_OR_STANDALONE = new Set([ServerType.Mongos, ServerType.Standalone]); +const NON_PRIMARY_RS_MEMBERS = new Set([ + ServerType.RSSecondary, + ServerType.RSArbiter, + ServerType.RSOther +]); + +/** @public */ +export interface TopologyDescriptionOptions { + heartbeatFrequencyMS?: number; + localThresholdMS?: number; +} + +/** + * Representation of a deployment of servers + * @public + */ +export class TopologyDescription { + type: TopologyType; + setName?: string; + maxSetVersion?: number; + maxElectionId?: ObjectId; + servers: Map; + stale: boolean; + compatible: boolean; + compatibilityError?: string; + logicalSessionTimeoutMinutes?: number; + heartbeatFrequencyMS: number; + localThresholdMS: number; + commonWireVersion?: number; + + /** + * Create a TopologyDescription + */ + constructor( + topologyType: TopologyType, + serverDescriptions?: Map, + setName?: string, + maxSetVersion?: number, + maxElectionId?: ObjectId, + commonWireVersion?: number, + options?: TopologyDescriptionOptions + ) { + options = options ?? {}; + + this.type = topologyType ?? TopologyType.Unknown; + this.servers = serverDescriptions ?? new Map(); + this.stale = false; + this.compatible = true; + this.heartbeatFrequencyMS = options.heartbeatFrequencyMS ?? 0; + this.localThresholdMS = options.localThresholdMS ?? 15; + + if (setName) { + this.setName = setName; + } + + if (maxSetVersion) { + this.maxSetVersion = maxSetVersion; + } + + if (maxElectionId) { + this.maxElectionId = maxElectionId; + } + + if (commonWireVersion) { + this.commonWireVersion = commonWireVersion; + } + + // determine server compatibility + for (const serverDescription of this.servers.values()) { + // Load balancer mode is always compatible. + if ( + serverDescription.type === ServerType.Unknown || + serverDescription.type === ServerType.LoadBalancer + ) { + continue; + } + + if (serverDescription.minWireVersion > MAX_SUPPORTED_WIRE_VERSION) { + this.compatible = false; + this.compatibilityError = `Server at ${serverDescription.address} requires wire version ${serverDescription.minWireVersion}, but this version of the driver only supports up to ${MAX_SUPPORTED_WIRE_VERSION} (MongoDB ${MAX_SUPPORTED_SERVER_VERSION})`; + } + + if (serverDescription.maxWireVersion < MIN_SUPPORTED_WIRE_VERSION) { + this.compatible = false; + this.compatibilityError = `Server at ${serverDescription.address} reports wire version ${serverDescription.maxWireVersion}, but this version of the driver requires at least ${MIN_SUPPORTED_WIRE_VERSION} (MongoDB ${MIN_SUPPORTED_SERVER_VERSION}).`; + break; + } + } + + // Whenever a client updates the TopologyDescription from a hello response, it MUST set + // TopologyDescription.logicalSessionTimeoutMinutes to the smallest logicalSessionTimeoutMinutes + // value among ServerDescriptions of all data-bearing server types. If any have a null + // logicalSessionTimeoutMinutes, then TopologyDescription.logicalSessionTimeoutMinutes MUST be + // set to null. + this.logicalSessionTimeoutMinutes = undefined; + for (const [, server] of this.servers) { + if (server.isReadable) { + if (server.logicalSessionTimeoutMinutes == null) { + // If any of the servers have a null logicalSessionsTimeout, then the whole topology does + this.logicalSessionTimeoutMinutes = undefined; + break; + } + + if (this.logicalSessionTimeoutMinutes == null) { + // First server with a non null logicalSessionsTimeout + this.logicalSessionTimeoutMinutes = server.logicalSessionTimeoutMinutes; + continue; + } + + // Always select the smaller of the: + // current server logicalSessionsTimeout and the topologies logicalSessionsTimeout + this.logicalSessionTimeoutMinutes = Math.min( + this.logicalSessionTimeoutMinutes, + server.logicalSessionTimeoutMinutes + ); + } + } + } + + /** + * Returns a new TopologyDescription based on the SrvPollingEvent + * @internal + */ + updateFromSrvPollingEvent(ev: SrvPollingEvent, srvMaxHosts = 0): TopologyDescription { + /** The SRV addresses defines the set of addresses we should be using */ + const incomingHostnames = ev.hostnames(); + const currentHostnames = new Set(this.servers.keys()); + + const hostnamesToAdd = new Set(incomingHostnames); + const hostnamesToRemove = new Set(); + for (const hostname of currentHostnames) { + // filter hostnamesToAdd (made from incomingHostnames) down to what is *not* present in currentHostnames + hostnamesToAdd.delete(hostname); + if (!incomingHostnames.has(hostname)) { + // If the SRV Records no longer include this hostname + // we have to stop using it + hostnamesToRemove.add(hostname); + } + } + + if (hostnamesToAdd.size === 0 && hostnamesToRemove.size === 0) { + // No new hosts to add and none to remove + return this; + } + + const serverDescriptions = new Map(this.servers); + for (const removedHost of hostnamesToRemove) { + serverDescriptions.delete(removedHost); + } + + if (hostnamesToAdd.size > 0) { + if (srvMaxHosts === 0) { + // Add all! + for (const hostToAdd of hostnamesToAdd) { + serverDescriptions.set(hostToAdd, new ServerDescription(hostToAdd)); + } + } else if (serverDescriptions.size < srvMaxHosts) { + // Add only the amount needed to get us back to srvMaxHosts + const selectedHosts = shuffle(hostnamesToAdd, srvMaxHosts - serverDescriptions.size); + for (const selectedHostToAdd of selectedHosts) { + serverDescriptions.set(selectedHostToAdd, new ServerDescription(selectedHostToAdd)); + } + } + } + + return new TopologyDescription( + this.type, + serverDescriptions, + this.setName, + this.maxSetVersion, + this.maxElectionId, + this.commonWireVersion, + { heartbeatFrequencyMS: this.heartbeatFrequencyMS, localThresholdMS: this.localThresholdMS } + ); + } + + /** + * Returns a copy of this description updated with a given ServerDescription + * @internal + */ + update(serverDescription: ServerDescription): TopologyDescription { + const address = serverDescription.address; + + // potentially mutated values + let { type: topologyType, setName, maxSetVersion, maxElectionId, commonWireVersion } = this; + + if (serverDescription.setName && setName && serverDescription.setName !== setName) { + // TODO(NODE-4159): servers with an incorrect setName should be removed not marked Unknown + serverDescription = new ServerDescription(address, undefined); + } + + const serverType = serverDescription.type; + const serverDescriptions = new Map(this.servers); + + // update common wire version + if (serverDescription.maxWireVersion !== 0) { + if (commonWireVersion == null) { + commonWireVersion = serverDescription.maxWireVersion; + } else { + commonWireVersion = Math.min(commonWireVersion, serverDescription.maxWireVersion); + } + } + + // update the actual server description + serverDescriptions.set(address, serverDescription); + + if (topologyType === TopologyType.Single) { + // once we are defined as single, that never changes + return new TopologyDescription( + TopologyType.Single, + serverDescriptions, + setName, + maxSetVersion, + maxElectionId, + commonWireVersion, + { heartbeatFrequencyMS: this.heartbeatFrequencyMS, localThresholdMS: this.localThresholdMS } + ); + } + + if (topologyType === TopologyType.Unknown) { + if (serverType === ServerType.Standalone && this.servers.size !== 1) { + serverDescriptions.delete(address); + } else { + topologyType = topologyTypeForServerType(serverType); + } + } + + if (topologyType === TopologyType.Sharded) { + if (!MONGOS_OR_UNKNOWN.has(serverType)) { + serverDescriptions.delete(address); + } + } + + if (topologyType === TopologyType.ReplicaSetNoPrimary) { + if (MONGOS_OR_STANDALONE.has(serverType)) { + serverDescriptions.delete(address); + } + + if (serverType === ServerType.RSPrimary) { + const result = updateRsFromPrimary( + serverDescriptions, + serverDescription, + setName, + maxSetVersion, + maxElectionId + ); + + topologyType = result[0]; + setName = result[1]; + maxSetVersion = result[2]; + maxElectionId = result[3]; + } else if (NON_PRIMARY_RS_MEMBERS.has(serverType)) { + const result = updateRsNoPrimaryFromMember(serverDescriptions, serverDescription, setName); + topologyType = result[0]; + setName = result[1]; + } + } + + if (topologyType === TopologyType.ReplicaSetWithPrimary) { + if (MONGOS_OR_STANDALONE.has(serverType)) { + serverDescriptions.delete(address); + topologyType = checkHasPrimary(serverDescriptions); + } else if (serverType === ServerType.RSPrimary) { + const result = updateRsFromPrimary( + serverDescriptions, + serverDescription, + setName, + maxSetVersion, + maxElectionId + ); + + topologyType = result[0]; + setName = result[1]; + maxSetVersion = result[2]; + maxElectionId = result[3]; + } else if (NON_PRIMARY_RS_MEMBERS.has(serverType)) { + topologyType = updateRsWithPrimaryFromMember( + serverDescriptions, + serverDescription, + setName + ); + } else { + topologyType = checkHasPrimary(serverDescriptions); + } + } + + return new TopologyDescription( + topologyType, + serverDescriptions, + setName, + maxSetVersion, + maxElectionId, + commonWireVersion, + { heartbeatFrequencyMS: this.heartbeatFrequencyMS, localThresholdMS: this.localThresholdMS } + ); + } + + get error(): MongoError | undefined { + const descriptionsWithError = Array.from(this.servers.values()).filter( + (sd: ServerDescription) => sd.error + ); + + if (descriptionsWithError.length > 0) { + return descriptionsWithError[0].error; + } + return; + } + + /** + * Determines if the topology description has any known servers + */ + get hasKnownServers(): boolean { + return Array.from(this.servers.values()).some( + (sd: ServerDescription) => sd.type !== ServerType.Unknown + ); + } + + /** + * Determines if this topology description has a data-bearing server available. + */ + get hasDataBearingServers(): boolean { + return Array.from(this.servers.values()).some((sd: ServerDescription) => sd.isDataBearing); + } + + /** + * Determines if the topology has a definition for the provided address + * @internal + */ + hasServer(address: string): boolean { + return this.servers.has(address); + } +} + +function topologyTypeForServerType(serverType: ServerType): TopologyType { + switch (serverType) { + case ServerType.Standalone: + return TopologyType.Single; + case ServerType.Mongos: + return TopologyType.Sharded; + case ServerType.RSPrimary: + return TopologyType.ReplicaSetWithPrimary; + case ServerType.RSOther: + case ServerType.RSSecondary: + return TopologyType.ReplicaSetNoPrimary; + default: + return TopologyType.Unknown; + } +} + +// TODO: improve these docs when ObjectId is properly typed +function compareObjectId(oid1: Document, oid2: Document): number { + if (oid1 == null) { + return -1; + } + + if (oid2 == null) { + return 1; + } + + if (oid1.id instanceof Buffer && oid2.id instanceof Buffer) { + const oid1Buffer = oid1.id; + const oid2Buffer = oid2.id; + return oid1Buffer.compare(oid2Buffer); + } + + const oid1String = oid1.toString(); + const oid2String = oid2.toString(); + return oid1String.localeCompare(oid2String); +} + +function updateRsFromPrimary( + serverDescriptions: Map, + serverDescription: ServerDescription, + setName?: string, + maxSetVersion?: number, + maxElectionId?: ObjectId +): [TopologyType, string?, number?, ObjectId?] { + setName = setName || serverDescription.setName; + if (setName !== serverDescription.setName) { + serverDescriptions.delete(serverDescription.address); + return [checkHasPrimary(serverDescriptions), setName, maxSetVersion, maxElectionId]; + } + + const electionId = serverDescription.electionId ? serverDescription.electionId : null; + if (serverDescription.setVersion && electionId) { + if (maxSetVersion && maxElectionId) { + if ( + maxSetVersion > serverDescription.setVersion || + compareObjectId(maxElectionId, electionId) > 0 + ) { + // this primary is stale, we must remove it + serverDescriptions.set( + serverDescription.address, + new ServerDescription(serverDescription.address) + ); + + return [checkHasPrimary(serverDescriptions), setName, maxSetVersion, maxElectionId]; + } + } + + maxElectionId = serverDescription.electionId; + } + + if ( + serverDescription.setVersion != null && + (maxSetVersion == null || serverDescription.setVersion > maxSetVersion) + ) { + maxSetVersion = serverDescription.setVersion; + } + + // We've heard from the primary. Is it the same primary as before? + for (const [address, server] of serverDescriptions) { + if (server.type === ServerType.RSPrimary && server.address !== serverDescription.address) { + // Reset old primary's type to Unknown. + serverDescriptions.set(address, new ServerDescription(server.address)); + + // There can only be one primary + break; + } + } + + // Discover new hosts from this primary's response. + serverDescription.allHosts.forEach((address: string) => { + if (!serverDescriptions.has(address)) { + serverDescriptions.set(address, new ServerDescription(address)); + } + }); + + // Remove hosts not in the response. + const currentAddresses = Array.from(serverDescriptions.keys()); + const responseAddresses = serverDescription.allHosts; + currentAddresses + .filter((addr: string) => responseAddresses.indexOf(addr) === -1) + .forEach((address: string) => { + serverDescriptions.delete(address); + }); + + return [checkHasPrimary(serverDescriptions), setName, maxSetVersion, maxElectionId]; +} + +function updateRsWithPrimaryFromMember( + serverDescriptions: Map, + serverDescription: ServerDescription, + setName?: string +): TopologyType { + if (setName == null) { + // TODO(NODE-3483): should be an appropriate runtime error + throw new MongoRuntimeError('Argument "setName" is required if connected to a replica set'); + } + + if ( + setName !== serverDescription.setName || + (serverDescription.me && serverDescription.address !== serverDescription.me) + ) { + serverDescriptions.delete(serverDescription.address); + } + + return checkHasPrimary(serverDescriptions); +} + +function updateRsNoPrimaryFromMember( + serverDescriptions: Map, + serverDescription: ServerDescription, + setName?: string +): [TopologyType, string?] { + const topologyType = TopologyType.ReplicaSetNoPrimary; + setName = setName || serverDescription.setName; + if (setName !== serverDescription.setName) { + serverDescriptions.delete(serverDescription.address); + return [topologyType, setName]; + } + + serverDescription.allHosts.forEach((address: string) => { + if (!serverDescriptions.has(address)) { + serverDescriptions.set(address, new ServerDescription(address)); + } + }); + + if (serverDescription.me && serverDescription.address !== serverDescription.me) { + serverDescriptions.delete(serverDescription.address); + } + + return [topologyType, setName]; +} + +function checkHasPrimary(serverDescriptions: Map): TopologyType { + for (const serverDescription of serverDescriptions.values()) { + if (serverDescription.type === ServerType.RSPrimary) { + return TopologyType.ReplicaSetWithPrimary; + } + } + + return TopologyType.ReplicaSetNoPrimary; +} diff --git a/ts-ticket-office-service/node_modules/mongodb/src/sessions.ts b/ts-ticket-office-service/node_modules/mongodb/src/sessions.ts new file mode 100644 index 000000000..6265bd8b3 --- /dev/null +++ b/ts-ticket-office-service/node_modules/mongodb/src/sessions.ts @@ -0,0 +1,1074 @@ +import { Binary, Document, Long, Timestamp } from './bson'; +import type { CommandOptions, Connection } from './cmap/connection'; +import { ConnectionPoolMetrics } from './cmap/metrics'; +import { isSharded } from './cmap/wire_protocol/shared'; +import { PINNED, UNPINNED } from './constants'; +import type { AbstractCursor } from './cursor/abstract_cursor'; +import { + AnyError, + MongoAPIError, + MongoCompatibilityError, + MONGODB_ERROR_CODES, + MongoDriverError, + MongoError, + MongoErrorLabel, + MongoExpiredSessionError, + MongoInvalidArgumentError, + MongoRuntimeError, + MongoServerError, + MongoTransactionError, + MongoWriteConcernError +} from './error'; +import type { MongoClient, MongoOptions } from './mongo_client'; +import { TypedEventEmitter } from './mongo_types'; +import { executeOperation } from './operations/execute_operation'; +import { RunAdminCommandOperation } from './operations/run_command'; +import { PromiseProvider } from './promise_provider'; +import { ReadConcernLevel } from './read_concern'; +import { ReadPreference } from './read_preference'; +import { _advanceClusterTime, ClusterTime, TopologyType } from './sdam/common'; +import { isTransactionCommand, Transaction, TransactionOptions, TxnState } from './transactions'; +import { + calculateDurationInMs, + Callback, + commandSupportsReadConcern, + isPromiseLike, + maxWireVersion, + maybePromise, + now, + uuidV4 +} from './utils'; + +const minWireVersionForShardedTransactions = 8; + +/** @public */ +export interface ClientSessionOptions { + /** Whether causal consistency should be enabled on this session */ + causalConsistency?: boolean; + /** Whether all read operations should be read from the same snapshot for this session (NOTE: not compatible with `causalConsistency=true`) */ + snapshot?: boolean; + /** The default TransactionOptions to use for transactions started on this session. */ + defaultTransactionOptions?: TransactionOptions; + + /** @internal */ + owner?: symbol | AbstractCursor; + /** @internal */ + explicit?: boolean; + /** @internal */ + initialClusterTime?: ClusterTime; +} + +/** @public */ +export type WithTransactionCallback = (session: ClientSession) => Promise; + +/** @public */ +export type ClientSessionEvents = { + ended(session: ClientSession): void; +}; + +/** @internal */ +const kServerSession = Symbol('serverSession'); +/** @internal */ +const kSnapshotTime = Symbol('snapshotTime'); +/** @internal */ +const kSnapshotEnabled = Symbol('snapshotEnabled'); +/** @internal */ +const kPinnedConnection = Symbol('pinnedConnection'); +/** @internal Accumulates total number of increments to add to txnNumber when applying session to command */ +const kTxnNumberIncrement = Symbol('txnNumberIncrement'); + +/** @public */ +export interface EndSessionOptions { + /** + * An optional error which caused the call to end this session + * @internal + */ + error?: AnyError; + force?: boolean; + forceClear?: boolean; +} + +/** + * A class representing a client session on the server + * + * NOTE: not meant to be instantiated directly. + * @public + */ +export class ClientSession extends TypedEventEmitter { + /** @internal */ + client: MongoClient; + /** @internal */ + sessionPool: ServerSessionPool; + hasEnded: boolean; + clientOptions?: MongoOptions; + supports: { causalConsistency: boolean }; + clusterTime?: ClusterTime; + operationTime?: Timestamp; + explicit: boolean; + /** @internal */ + owner?: symbol | AbstractCursor; + defaultTransactionOptions: TransactionOptions; + transaction: Transaction; + /** @internal */ + [kServerSession]: ServerSession | null; + /** @internal */ + [kSnapshotTime]?: Timestamp; + /** @internal */ + [kSnapshotEnabled] = false; + /** @internal */ + [kPinnedConnection]?: Connection; + /** @internal */ + [kTxnNumberIncrement]: number; + + /** + * Create a client session. + * @internal + * @param client - The current client + * @param sessionPool - The server session pool (Internal Class) + * @param options - Optional settings + * @param clientOptions - Optional settings provided when creating a MongoClient + */ + constructor( + client: MongoClient, + sessionPool: ServerSessionPool, + options: ClientSessionOptions, + clientOptions?: MongoOptions + ) { + super(); + + if (client == null) { + // TODO(NODE-3483) + throw new MongoRuntimeError('ClientSession requires a MongoClient'); + } + + if (sessionPool == null || !(sessionPool instanceof ServerSessionPool)) { + // TODO(NODE-3483) + throw new MongoRuntimeError('ClientSession requires a ServerSessionPool'); + } + + options = options ?? {}; + + if (options.snapshot === true) { + this[kSnapshotEnabled] = true; + if (options.causalConsistency === true) { + throw new MongoInvalidArgumentError( + 'Properties "causalConsistency" and "snapshot" are mutually exclusive' + ); + } + } + + this.client = client; + this.sessionPool = sessionPool; + this.hasEnded = false; + this.clientOptions = clientOptions; + + this.explicit = !!options.explicit; + this[kServerSession] = this.explicit ? this.sessionPool.acquire() : null; + this[kTxnNumberIncrement] = 0; + + this.supports = { + causalConsistency: options.snapshot !== true && options.causalConsistency !== false + }; + + this.clusterTime = options.initialClusterTime; + + this.operationTime = undefined; + this.owner = options.owner; + this.defaultTransactionOptions = Object.assign({}, options.defaultTransactionOptions); + this.transaction = new Transaction(); + } + + /** The server id associated with this session */ + get id(): ServerSessionId | undefined { + return this[kServerSession]?.id; + } + + get serverSession(): ServerSession { + let serverSession = this[kServerSession]; + if (serverSession == null) { + if (this.explicit) { + throw new MongoRuntimeError('Unexpected null serverSession for an explicit session'); + } + if (this.hasEnded) { + throw new MongoRuntimeError('Unexpected null serverSession for an ended implicit session'); + } + serverSession = this.sessionPool.acquire(); + this[kServerSession] = serverSession; + } + return serverSession; + } + + /** Whether or not this session is configured for snapshot reads */ + get snapshotEnabled(): boolean { + return this[kSnapshotEnabled]; + } + + get loadBalanced(): boolean { + return this.client.topology?.description.type === TopologyType.LoadBalanced; + } + + /** @internal */ + get pinnedConnection(): Connection | undefined { + return this[kPinnedConnection]; + } + + /** @internal */ + pin(conn: Connection): void { + if (this[kPinnedConnection]) { + throw TypeError('Cannot pin multiple connections to the same session'); + } + + this[kPinnedConnection] = conn; + conn.emit( + PINNED, + this.inTransaction() ? ConnectionPoolMetrics.TXN : ConnectionPoolMetrics.CURSOR + ); + } + + /** @internal */ + unpin(options?: { force?: boolean; forceClear?: boolean; error?: AnyError }): void { + if (this.loadBalanced) { + return maybeClearPinnedConnection(this, options); + } + + this.transaction.unpinServer(); + } + + get isPinned(): boolean { + return this.loadBalanced ? !!this[kPinnedConnection] : this.transaction.isPinned; + } + + /** + * Ends this session on the server + * + * @param options - Optional settings. Currently reserved for future use + * @param callback - Optional callback for completion of this operation + */ + endSession(): Promise; + endSession(callback: Callback): void; + endSession(options: EndSessionOptions): Promise; + endSession(options: EndSessionOptions, callback: Callback): void; + endSession( + options?: EndSessionOptions | Callback, + callback?: Callback + ): void | Promise { + if (typeof options === 'function') (callback = options), (options = {}); + const finalOptions = { force: true, ...options }; + + return maybePromise(callback, done => { + if (this.hasEnded) { + maybeClearPinnedConnection(this, finalOptions); + return done(); + } + + const completeEndSession = () => { + maybeClearPinnedConnection(this, finalOptions); + + const serverSession = this[kServerSession]; + if (serverSession != null) { + // release the server session back to the pool + this.sessionPool.release(serverSession); + // Make sure a new serverSession never makes it onto this ClientSession + Object.defineProperty(this, kServerSession, { + value: ServerSession.clone(serverSession), + writable: false + }); + } + + // mark the session as ended, and emit a signal + this.hasEnded = true; + this.emit('ended', this); + + // spec indicates that we should ignore all errors for `endSessions` + done(); + }; + + if (this.inTransaction()) { + // If we've reached endSession and the transaction is still active + // by default we abort it + this.abortTransaction(err => { + if (err) return done(err); + completeEndSession(); + }); + + return; + } + + completeEndSession(); + }); + } + + /** + * Advances the operationTime for a ClientSession. + * + * @param operationTime - the `BSON.Timestamp` of the operation type it is desired to advance to + */ + advanceOperationTime(operationTime: Timestamp): void { + if (this.operationTime == null) { + this.operationTime = operationTime; + return; + } + + if (operationTime.greaterThan(this.operationTime)) { + this.operationTime = operationTime; + } + } + + /** + * Advances the clusterTime for a ClientSession to the provided clusterTime of another ClientSession + * + * @param clusterTime - the $clusterTime returned by the server from another session in the form of a document containing the `BSON.Timestamp` clusterTime and signature + */ + advanceClusterTime(clusterTime: ClusterTime): void { + if (!clusterTime || typeof clusterTime !== 'object') { + throw new MongoInvalidArgumentError('input cluster time must be an object'); + } + if (!clusterTime.clusterTime || clusterTime.clusterTime._bsontype !== 'Timestamp') { + throw new MongoInvalidArgumentError( + 'input cluster time "clusterTime" property must be a valid BSON Timestamp' + ); + } + if ( + !clusterTime.signature || + clusterTime.signature.hash?._bsontype !== 'Binary' || + (typeof clusterTime.signature.keyId !== 'number' && + clusterTime.signature.keyId?._bsontype !== 'Long') // apparently we decode the key to number? + ) { + throw new MongoInvalidArgumentError( + 'input cluster time must have a valid "signature" property with BSON Binary hash and BSON Long keyId' + ); + } + + _advanceClusterTime(this, clusterTime); + } + + /** + * Used to determine if this session equals another + * + * @param session - The session to compare to + */ + equals(session: ClientSession): boolean { + if (!(session instanceof ClientSession)) { + return false; + } + + if (this.id == null || session.id == null) { + return false; + } + + return this.id.id.buffer.equals(session.id.id.buffer); + } + + /** + * Increment the transaction number on the internal ServerSession + * + * @privateRemarks + * This helper increments a value stored on the client session that will be + * added to the serverSession's txnNumber upon applying it to a command. + * This is because the serverSession is lazily acquired after a connection is obtained + */ + incrementTransactionNumber(): void { + this[kTxnNumberIncrement] += 1; + } + + /** @returns whether this session is currently in a transaction or not */ + inTransaction(): boolean { + return this.transaction.isActive; + } + + /** + * Starts a new transaction with the given options. + * + * @param options - Options for the transaction + */ + startTransaction(options?: TransactionOptions): void { + if (this[kSnapshotEnabled]) { + throw new MongoCompatibilityError('Transactions are not allowed with snapshot sessions'); + } + + if (this.inTransaction()) { + throw new MongoTransactionError('Transaction already in progress'); + } + + if (this.isPinned && this.transaction.isCommitted) { + this.unpin(); + } + + const topologyMaxWireVersion = maxWireVersion(this.client.topology); + if ( + isSharded(this.client.topology) && + topologyMaxWireVersion != null && + topologyMaxWireVersion < minWireVersionForShardedTransactions + ) { + throw new MongoCompatibilityError( + 'Transactions are not supported on sharded clusters in MongoDB < 4.2.' + ); + } + + // increment txnNumber + this.incrementTransactionNumber(); + // create transaction state + this.transaction = new Transaction({ + readConcern: + options?.readConcern ?? + this.defaultTransactionOptions.readConcern ?? + this.clientOptions?.readConcern, + writeConcern: + options?.writeConcern ?? + this.defaultTransactionOptions.writeConcern ?? + this.clientOptions?.writeConcern, + readPreference: + options?.readPreference ?? + this.defaultTransactionOptions.readPreference ?? + this.clientOptions?.readPreference, + maxCommitTimeMS: options?.maxCommitTimeMS ?? this.defaultTransactionOptions.maxCommitTimeMS + }); + + this.transaction.transition(TxnState.STARTING_TRANSACTION); + } + + /** + * Commits the currently active transaction in this session. + * + * @param callback - An optional callback, a Promise will be returned if none is provided + */ + commitTransaction(): Promise; + commitTransaction(callback: Callback): void; + commitTransaction(callback?: Callback): Promise | void { + return maybePromise(callback, cb => endTransaction(this, 'commitTransaction', cb)); + } + + /** + * Aborts the currently active transaction in this session. + * + * @param callback - An optional callback, a Promise will be returned if none is provided + */ + abortTransaction(): Promise; + abortTransaction(callback: Callback): void; + abortTransaction(callback?: Callback): Promise | void { + return maybePromise(callback, cb => endTransaction(this, 'abortTransaction', cb)); + } + + /** + * This is here to ensure that ClientSession is never serialized to BSON. + */ + toBSON(): never { + throw new MongoRuntimeError('ClientSession cannot be serialized to BSON.'); + } + + /** + * Runs a provided callback within a transaction, retrying either the commitTransaction operation + * or entire transaction as needed (and when the error permits) to better ensure that + * the transaction can complete successfully. + * + * **IMPORTANT:** This method requires the user to return a Promise, and `await` all operations. + * Any callbacks that do not return a Promise will result in undefined behavior. + * + * @remarks + * This function: + * - Will return the command response from the final commitTransaction if every operation is successful (can be used as a truthy object) + * - Will return `undefined` if the transaction is explicitly aborted with `await session.abortTransaction()` + * - Will throw if one of the operations throws or `throw` statement is used inside the `withTransaction` callback + * + * Checkout a descriptive example here: + * @see https://www.mongodb.com/developer/quickstart/node-transactions/ + * + * @param fn - callback to run within a transaction + * @param options - optional settings for the transaction + * @returns A raw command response or undefined + */ + withTransaction( + fn: WithTransactionCallback, + options?: TransactionOptions + ): Promise { + const startTime = now(); + return attemptTransaction(this, startTime, fn, options); + } +} + +const MAX_WITH_TRANSACTION_TIMEOUT = 120000; +const NON_DETERMINISTIC_WRITE_CONCERN_ERRORS = new Set([ + 'CannotSatisfyWriteConcern', + 'UnknownReplWriteConcern', + 'UnsatisfiableWriteConcern' +]); + +function hasNotTimedOut(startTime: number, max: number) { + return calculateDurationInMs(startTime) < max; +} + +function isUnknownTransactionCommitResult(err: MongoError) { + const isNonDeterministicWriteConcernError = + err instanceof MongoServerError && + err.codeName && + NON_DETERMINISTIC_WRITE_CONCERN_ERRORS.has(err.codeName); + + return ( + isMaxTimeMSExpiredError(err) || + (!isNonDeterministicWriteConcernError && + err.code !== MONGODB_ERROR_CODES.UnsatisfiableWriteConcern && + err.code !== MONGODB_ERROR_CODES.UnknownReplWriteConcern) + ); +} + +export function maybeClearPinnedConnection( + session: ClientSession, + options?: EndSessionOptions +): void { + // unpin a connection if it has been pinned + const conn = session[kPinnedConnection]; + const error = options?.error; + + if ( + session.inTransaction() && + error && + error instanceof MongoError && + error.hasErrorLabel(MongoErrorLabel.TransientTransactionError) + ) { + return; + } + + const topology = session.client.topology; + // NOTE: the spec talks about what to do on a network error only, but the tests seem to + // to validate that we don't unpin on _all_ errors? + if (conn && topology != null) { + const servers = Array.from(topology.s.servers.values()); + const loadBalancer = servers[0]; + + if (options?.error == null || options?.force) { + loadBalancer.s.pool.checkIn(conn); + conn.emit( + UNPINNED, + session.transaction.state !== TxnState.NO_TRANSACTION + ? ConnectionPoolMetrics.TXN + : ConnectionPoolMetrics.CURSOR + ); + + if (options?.forceClear) { + loadBalancer.s.pool.clear(conn.serviceId); + } + } + + session[kPinnedConnection] = undefined; + } +} + +function isMaxTimeMSExpiredError(err: MongoError) { + if (err == null || !(err instanceof MongoServerError)) { + return false; + } + + return ( + err.code === MONGODB_ERROR_CODES.MaxTimeMSExpired || + (err.writeConcernError && err.writeConcernError.code === MONGODB_ERROR_CODES.MaxTimeMSExpired) + ); +} + +function attemptTransactionCommit( + session: ClientSession, + startTime: number, + fn: WithTransactionCallback, + options?: TransactionOptions +): Promise { + return session.commitTransaction().catch((err: MongoError) => { + if ( + err instanceof MongoError && + hasNotTimedOut(startTime, MAX_WITH_TRANSACTION_TIMEOUT) && + !isMaxTimeMSExpiredError(err) + ) { + if (err.hasErrorLabel(MongoErrorLabel.UnknownTransactionCommitResult)) { + return attemptTransactionCommit(session, startTime, fn, options); + } + + if (err.hasErrorLabel(MongoErrorLabel.TransientTransactionError)) { + return attemptTransaction(session, startTime, fn, options); + } + } + + throw err; + }); +} + +const USER_EXPLICIT_TXN_END_STATES = new Set([ + TxnState.NO_TRANSACTION, + TxnState.TRANSACTION_COMMITTED, + TxnState.TRANSACTION_ABORTED +]); + +function userExplicitlyEndedTransaction(session: ClientSession) { + return USER_EXPLICIT_TXN_END_STATES.has(session.transaction.state); +} + +function attemptTransaction( + session: ClientSession, + startTime: number, + fn: WithTransactionCallback, + options?: TransactionOptions +): Promise { + const Promise = PromiseProvider.get(); + session.startTransaction(options); + + let promise; + try { + promise = fn(session); + } catch (err) { + promise = Promise.reject(err); + } + + if (!isPromiseLike(promise)) { + session.abortTransaction().catch(() => null); + throw new MongoInvalidArgumentError( + 'Function provided to `withTransaction` must return a Promise' + ); + } + + return promise.then( + () => { + if (userExplicitlyEndedTransaction(session)) { + return; + } + + return attemptTransactionCommit(session, startTime, fn, options); + }, + err => { + function maybeRetryOrThrow(err: MongoError): Promise { + if ( + err instanceof MongoError && + err.hasErrorLabel(MongoErrorLabel.TransientTransactionError) && + hasNotTimedOut(startTime, MAX_WITH_TRANSACTION_TIMEOUT) + ) { + return attemptTransaction(session, startTime, fn, options); + } + + if (isMaxTimeMSExpiredError(err)) { + err.addErrorLabel(MongoErrorLabel.UnknownTransactionCommitResult); + } + + throw err; + } + + if (session.inTransaction()) { + return session.abortTransaction().then(() => maybeRetryOrThrow(err)); + } + + return maybeRetryOrThrow(err); + } + ); +} + +function endTransaction( + session: ClientSession, + commandName: 'abortTransaction' | 'commitTransaction', + callback: Callback +) { + // handle any initial problematic cases + const txnState = session.transaction.state; + + if (txnState === TxnState.NO_TRANSACTION) { + callback(new MongoTransactionError('No transaction started')); + return; + } + + if (commandName === 'commitTransaction') { + if ( + txnState === TxnState.STARTING_TRANSACTION || + txnState === TxnState.TRANSACTION_COMMITTED_EMPTY + ) { + // the transaction was never started, we can safely exit here + session.transaction.transition(TxnState.TRANSACTION_COMMITTED_EMPTY); + callback(); + return; + } + + if (txnState === TxnState.TRANSACTION_ABORTED) { + callback( + new MongoTransactionError('Cannot call commitTransaction after calling abortTransaction') + ); + return; + } + } else { + if (txnState === TxnState.STARTING_TRANSACTION) { + // the transaction was never started, we can safely exit here + session.transaction.transition(TxnState.TRANSACTION_ABORTED); + callback(); + return; + } + + if (txnState === TxnState.TRANSACTION_ABORTED) { + callback(new MongoTransactionError('Cannot call abortTransaction twice')); + return; + } + + if ( + txnState === TxnState.TRANSACTION_COMMITTED || + txnState === TxnState.TRANSACTION_COMMITTED_EMPTY + ) { + callback( + new MongoTransactionError('Cannot call abortTransaction after calling commitTransaction') + ); + return; + } + } + + // construct and send the command + const command: Document = { [commandName]: 1 }; + + // apply a writeConcern if specified + let writeConcern; + if (session.transaction.options.writeConcern) { + writeConcern = Object.assign({}, session.transaction.options.writeConcern); + } else if (session.clientOptions && session.clientOptions.writeConcern) { + writeConcern = { w: session.clientOptions.writeConcern.w }; + } + + if (txnState === TxnState.TRANSACTION_COMMITTED) { + writeConcern = Object.assign({ wtimeout: 10000 }, writeConcern, { w: 'majority' }); + } + + if (writeConcern) { + Object.assign(command, { writeConcern }); + } + + if (commandName === 'commitTransaction' && session.transaction.options.maxTimeMS) { + Object.assign(command, { maxTimeMS: session.transaction.options.maxTimeMS }); + } + + function commandHandler(error?: Error, result?: Document) { + if (commandName !== 'commitTransaction') { + session.transaction.transition(TxnState.TRANSACTION_ABORTED); + if (session.loadBalanced) { + maybeClearPinnedConnection(session, { force: false }); + } + + // The spec indicates that we should ignore all errors on `abortTransaction` + return callback(); + } + + session.transaction.transition(TxnState.TRANSACTION_COMMITTED); + if (error instanceof MongoError) { + if ( + error.hasErrorLabel(MongoErrorLabel.RetryableWriteError) || + error instanceof MongoWriteConcernError || + isMaxTimeMSExpiredError(error) + ) { + if (isUnknownTransactionCommitResult(error)) { + error.addErrorLabel(MongoErrorLabel.UnknownTransactionCommitResult); + + // per txns spec, must unpin session in this case + session.unpin({ error }); + } + } else if (error.hasErrorLabel(MongoErrorLabel.TransientTransactionError)) { + session.unpin({ error }); + } + } + + callback(error, result); + } + + if (session.transaction.recoveryToken) { + command.recoveryToken = session.transaction.recoveryToken; + } + + // send the command + executeOperation( + session.client, + new RunAdminCommandOperation(undefined, command, { + session, + readPreference: ReadPreference.primary, + bypassPinningCheck: true + }), + (error, result) => { + if (command.abortTransaction) { + // always unpin on abort regardless of command outcome + session.unpin(); + } + + if (error instanceof MongoError && error.hasErrorLabel(MongoErrorLabel.RetryableWriteError)) { + // SPEC-1185: apply majority write concern when retrying commitTransaction + if (command.commitTransaction) { + // per txns spec, must unpin session in this case + session.unpin({ force: true }); + + command.writeConcern = Object.assign({ wtimeout: 10000 }, command.writeConcern, { + w: 'majority' + }); + } + + return executeOperation( + session.client, + new RunAdminCommandOperation(undefined, command, { + session, + readPreference: ReadPreference.primary, + bypassPinningCheck: true + }), + commandHandler + ); + } + + commandHandler(error, result); + } + ); +} + +/** @public */ +export type ServerSessionId = { id: Binary }; + +/** + * Reflects the existence of a session on the server. Can be reused by the session pool. + * WARNING: not meant to be instantiated directly. For internal use only. + * @public + */ +export class ServerSession { + id: ServerSessionId; + lastUse: number; + txnNumber: number; + isDirty: boolean; + + /** @internal */ + constructor() { + this.id = { id: new Binary(uuidV4(), Binary.SUBTYPE_UUID) }; + this.lastUse = now(); + this.txnNumber = 0; + this.isDirty = false; + } + + /** + * Determines if the server session has timed out. + * + * @param sessionTimeoutMinutes - The server's "logicalSessionTimeoutMinutes" + */ + hasTimedOut(sessionTimeoutMinutes: number): boolean { + // Take the difference of the lastUse timestamp and now, which will result in a value in + // milliseconds, and then convert milliseconds to minutes to compare to `sessionTimeoutMinutes` + const idleTimeMinutes = Math.round( + ((calculateDurationInMs(this.lastUse) % 86400000) % 3600000) / 60000 + ); + + return idleTimeMinutes > sessionTimeoutMinutes - 1; + } + + /** + * @internal + * Cloning meant to keep a readable reference to the server session data + * after ClientSession has ended + */ + static clone(serverSession: ServerSession): Readonly { + const arrayBuffer = new ArrayBuffer(16); + const idBytes = Buffer.from(arrayBuffer); + idBytes.set(serverSession.id.id.buffer); + + const id = new Binary(idBytes, serverSession.id.id.sub_type); + + // Manual prototype construction to avoid modifying the constructor of this class + return Object.setPrototypeOf( + { + id: { id }, + lastUse: serverSession.lastUse, + txnNumber: serverSession.txnNumber, + isDirty: serverSession.isDirty + }, + ServerSession.prototype + ); + } +} + +/** + * Maintains a pool of Server Sessions. + * For internal use only + * @internal + */ +export class ServerSessionPool { + client: MongoClient; + sessions: ServerSession[]; + + constructor(client: MongoClient) { + if (client == null) { + throw new MongoRuntimeError('ServerSessionPool requires a MongoClient'); + } + + this.client = client; + this.sessions = []; + } + + /** + * Acquire a Server Session from the pool. + * Iterates through each session in the pool, removing any stale sessions + * along the way. The first non-stale session found is removed from the + * pool and returned. If no non-stale session is found, a new ServerSession is created. + */ + acquire(): ServerSession { + const sessionTimeoutMinutes = this.client.topology?.logicalSessionTimeoutMinutes ?? 10; + + let session: ServerSession | null = null; + + // Try to obtain from session pool + while (this.sessions.length > 0) { + const potentialSession = this.sessions.shift(); + if ( + potentialSession != null && + (!!this.client.topology?.loadBalanced || + !potentialSession.hasTimedOut(sessionTimeoutMinutes)) + ) { + session = potentialSession; + break; + } + } + + // If nothing valid came from the pool make a new one + if (session == null) { + session = new ServerSession(); + } + + return session; + } + + /** + * Release a session to the session pool + * Adds the session back to the session pool if the session has not timed out yet. + * This method also removes any stale sessions from the pool. + * + * @param session - The session to release to the pool + */ + release(session: ServerSession): void { + const sessionTimeoutMinutes = this.client.topology?.logicalSessionTimeoutMinutes ?? 10; + + if (this.client.topology?.loadBalanced && !sessionTimeoutMinutes) { + this.sessions.unshift(session); + } + + if (!sessionTimeoutMinutes) { + return; + } + + while (this.sessions.length) { + const pooledSession = this.sessions[this.sessions.length - 1]; + if (pooledSession.hasTimedOut(sessionTimeoutMinutes)) { + this.sessions.pop(); + } else { + break; + } + } + + if (!session.hasTimedOut(sessionTimeoutMinutes)) { + if (session.isDirty) { + return; + } + + // otherwise, readd this session to the session pool + this.sessions.unshift(session); + } + } +} + +/** + * Optionally decorate a command with sessions specific keys + * + * @param session - the session tracking transaction state + * @param command - the command to decorate + * @param options - Optional settings passed to calling operation + * + * @internal + */ +export function applySession( + session: ClientSession, + command: Document, + options: CommandOptions +): MongoDriverError | undefined { + if (session.hasEnded) { + return new MongoExpiredSessionError(); + } + + // May acquire serverSession here + const serverSession = session.serverSession; + if (serverSession == null) { + return new MongoRuntimeError('Unable to acquire server session'); + } + + if (options.writeConcern?.w === 0) { + if (session && session.explicit) { + // Error if user provided an explicit session to an unacknowledged write (SPEC-1019) + return new MongoAPIError('Cannot have explicit session with unacknowledged writes'); + } + return; + } + + // mark the last use of this session, and apply the `lsid` + serverSession.lastUse = now(); + command.lsid = serverSession.id; + + const inTxnOrTxnCommand = session.inTransaction() || isTransactionCommand(command); + const isRetryableWrite = !!options.willRetryWrite; + + if (isRetryableWrite || inTxnOrTxnCommand) { + serverSession.txnNumber += session[kTxnNumberIncrement]; + session[kTxnNumberIncrement] = 0; + command.txnNumber = Long.fromNumber(serverSession.txnNumber); + } + + if (!inTxnOrTxnCommand) { + if (session.transaction.state !== TxnState.NO_TRANSACTION) { + session.transaction.transition(TxnState.NO_TRANSACTION); + } + + if ( + session.supports.causalConsistency && + session.operationTime && + commandSupportsReadConcern(command, options) + ) { + command.readConcern = command.readConcern || {}; + Object.assign(command.readConcern, { afterClusterTime: session.operationTime }); + } else if (session[kSnapshotEnabled]) { + command.readConcern = command.readConcern || { level: ReadConcernLevel.snapshot }; + if (session[kSnapshotTime] != null) { + Object.assign(command.readConcern, { atClusterTime: session[kSnapshotTime] }); + } + } + + return; + } + + // now attempt to apply transaction-specific sessions data + + // `autocommit` must always be false to differentiate from retryable writes + command.autocommit = false; + + if (session.transaction.state === TxnState.STARTING_TRANSACTION) { + session.transaction.transition(TxnState.TRANSACTION_IN_PROGRESS); + command.startTransaction = true; + + const readConcern = + session.transaction.options.readConcern || session?.clientOptions?.readConcern; + if (readConcern) { + command.readConcern = readConcern; + } + + if (session.supports.causalConsistency && session.operationTime) { + command.readConcern = command.readConcern || {}; + Object.assign(command.readConcern, { afterClusterTime: session.operationTime }); + } + } + return; +} + +export function updateSessionFromResponse(session: ClientSession, document: Document): void { + if (document.$clusterTime) { + _advanceClusterTime(session, document.$clusterTime); + } + + if (document.operationTime && session && session.supports.causalConsistency) { + session.advanceOperationTime(document.operationTime); + } + + if (document.recoveryToken && session && session.inTransaction()) { + session.transaction._recoveryToken = document.recoveryToken; + } + + if (session?.[kSnapshotEnabled] && session[kSnapshotTime] == null) { + // find and aggregate commands return atClusterTime on the cursor + // distinct includes it in the response body + const atClusterTime = document.cursor?.atClusterTime || document.atClusterTime; + if (atClusterTime) { + session[kSnapshotTime] = atClusterTime; + } + } +} diff --git a/ts-ticket-office-service/node_modules/mongodb/src/sort.ts b/ts-ticket-office-service/node_modules/mongodb/src/sort.ts new file mode 100644 index 000000000..6b766b545 --- /dev/null +++ b/ts-ticket-office-service/node_modules/mongodb/src/sort.ts @@ -0,0 +1,132 @@ +import { MongoInvalidArgumentError } from './error'; + +/** @public */ +export type SortDirection = + | 1 + | -1 + | 'asc' + | 'desc' + | 'ascending' + | 'descending' + | { $meta: string }; + +/** @public */ +export type Sort = + | string + | Exclude + | string[] + | { [key: string]: SortDirection } + | Map + | [string, SortDirection][] + | [string, SortDirection]; + +/** Below stricter types were created for sort that correspond with type that the cmd takes */ + +/** @internal */ +export type SortDirectionForCmd = 1 | -1 | { $meta: string }; + +/** @internal */ +export type SortForCmd = Map; + +/** @internal */ +type SortPairForCmd = [string, SortDirectionForCmd]; + +/** @internal */ +function prepareDirection(direction: any = 1): SortDirectionForCmd { + const value = `${direction}`.toLowerCase(); + if (isMeta(direction)) return direction; + switch (value) { + case 'ascending': + case 'asc': + case '1': + return 1; + case 'descending': + case 'desc': + case '-1': + return -1; + default: + throw new MongoInvalidArgumentError(`Invalid sort direction: ${JSON.stringify(direction)}`); + } +} + +/** @internal */ +function isMeta(t: SortDirection): t is { $meta: string } { + return typeof t === 'object' && t != null && '$meta' in t && typeof t.$meta === 'string'; +} + +/** @internal */ +function isPair(t: Sort): t is [string, SortDirection] { + if (Array.isArray(t) && t.length === 2) { + try { + prepareDirection(t[1]); + return true; + } catch (e) { + return false; + } + } + return false; +} + +function isDeep(t: Sort): t is [string, SortDirection][] { + return Array.isArray(t) && Array.isArray(t[0]); +} + +function isMap(t: Sort): t is Map { + return t instanceof Map && t.size > 0; +} + +/** @internal */ +function pairToMap(v: [string, SortDirection]): SortForCmd { + return new Map([[`${v[0]}`, prepareDirection([v[1]])]]); +} + +/** @internal */ +function deepToMap(t: [string, SortDirection][]): SortForCmd { + const sortEntries: SortPairForCmd[] = t.map(([k, v]) => [`${k}`, prepareDirection(v)]); + return new Map(sortEntries); +} + +/** @internal */ +function stringsToMap(t: string[]): SortForCmd { + const sortEntries: SortPairForCmd[] = t.map(key => [`${key}`, 1]); + return new Map(sortEntries); +} + +/** @internal */ +function objectToMap(t: { [key: string]: SortDirection }): SortForCmd { + const sortEntries: SortPairForCmd[] = Object.entries(t).map(([k, v]) => [ + `${k}`, + prepareDirection(v) + ]); + return new Map(sortEntries); +} + +/** @internal */ +function mapToMap(t: Map): SortForCmd { + const sortEntries: SortPairForCmd[] = Array.from(t).map(([k, v]) => [ + `${k}`, + prepareDirection(v) + ]); + return new Map(sortEntries); +} + +/** converts a Sort type into a type that is valid for the server (SortForCmd) */ +export function formatSort( + sort: Sort | undefined, + direction?: SortDirection +): SortForCmd | undefined { + if (sort == null) return undefined; + if (typeof sort === 'string') return new Map([[sort, prepareDirection(direction)]]); + if (typeof sort !== 'object') { + throw new MongoInvalidArgumentError( + `Invalid sort format: ${JSON.stringify(sort)} Sort must be a valid object` + ); + } + if (!Array.isArray(sort)) { + return isMap(sort) ? mapToMap(sort) : Object.keys(sort).length ? objectToMap(sort) : undefined; + } + if (!sort.length) return undefined; + if (isDeep(sort)) return deepToMap(sort); + if (isPair(sort)) return pairToMap(sort); + return stringsToMap(sort); +} diff --git a/ts-ticket-office-service/node_modules/mongodb/src/transactions.ts b/ts-ticket-office-service/node_modules/mongodb/src/transactions.ts new file mode 100644 index 000000000..34d84403c --- /dev/null +++ b/ts-ticket-office-service/node_modules/mongodb/src/transactions.ts @@ -0,0 +1,187 @@ +import type { Document } from './bson'; +import { MongoRuntimeError, MongoTransactionError } from './error'; +import type { CommandOperationOptions } from './operations/command'; +import { ReadConcern, ReadConcernLike } from './read_concern'; +import { ReadPreference } from './read_preference'; +import type { Server } from './sdam/server'; +import { WriteConcern } from './write_concern'; + +/** @internal */ +export const TxnState = Object.freeze({ + NO_TRANSACTION: 'NO_TRANSACTION', + STARTING_TRANSACTION: 'STARTING_TRANSACTION', + TRANSACTION_IN_PROGRESS: 'TRANSACTION_IN_PROGRESS', + TRANSACTION_COMMITTED: 'TRANSACTION_COMMITTED', + TRANSACTION_COMMITTED_EMPTY: 'TRANSACTION_COMMITTED_EMPTY', + TRANSACTION_ABORTED: 'TRANSACTION_ABORTED' +} as const); + +/** @internal */ +export type TxnState = typeof TxnState[keyof typeof TxnState]; + +const stateMachine: { [state in TxnState]: TxnState[] } = { + [TxnState.NO_TRANSACTION]: [TxnState.NO_TRANSACTION, TxnState.STARTING_TRANSACTION], + [TxnState.STARTING_TRANSACTION]: [ + TxnState.TRANSACTION_IN_PROGRESS, + TxnState.TRANSACTION_COMMITTED, + TxnState.TRANSACTION_COMMITTED_EMPTY, + TxnState.TRANSACTION_ABORTED + ], + [TxnState.TRANSACTION_IN_PROGRESS]: [ + TxnState.TRANSACTION_IN_PROGRESS, + TxnState.TRANSACTION_COMMITTED, + TxnState.TRANSACTION_ABORTED + ], + [TxnState.TRANSACTION_COMMITTED]: [ + TxnState.TRANSACTION_COMMITTED, + TxnState.TRANSACTION_COMMITTED_EMPTY, + TxnState.STARTING_TRANSACTION, + TxnState.NO_TRANSACTION + ], + [TxnState.TRANSACTION_ABORTED]: [TxnState.STARTING_TRANSACTION, TxnState.NO_TRANSACTION], + [TxnState.TRANSACTION_COMMITTED_EMPTY]: [ + TxnState.TRANSACTION_COMMITTED_EMPTY, + TxnState.NO_TRANSACTION + ] +}; + +const ACTIVE_STATES: Set = new Set([ + TxnState.STARTING_TRANSACTION, + TxnState.TRANSACTION_IN_PROGRESS +]); + +const COMMITTED_STATES: Set = new Set([ + TxnState.TRANSACTION_COMMITTED, + TxnState.TRANSACTION_COMMITTED_EMPTY, + TxnState.TRANSACTION_ABORTED +]); + +/** + * Configuration options for a transaction. + * @public + */ +export interface TransactionOptions extends CommandOperationOptions { + // TODO(NODE-3344): These options use the proper class forms of these settings, it should accept the basic enum values too + /** A default read concern for commands in this transaction */ + readConcern?: ReadConcernLike; + /** A default writeConcern for commands in this transaction */ + writeConcern?: WriteConcern; + /** A default read preference for commands in this transaction */ + readPreference?: ReadPreference; + /** Specifies the maximum amount of time to allow a commit action on a transaction to run in milliseconds */ + maxCommitTimeMS?: number; +} + +/** + * @public + * A class maintaining state related to a server transaction. Internal Only + */ +export class Transaction { + /** @internal */ + state: TxnState; + options: TransactionOptions; + /** @internal */ + _pinnedServer?: Server; + /** @internal */ + _recoveryToken?: Document; + + /** Create a transaction @internal */ + constructor(options?: TransactionOptions) { + options = options ?? {}; + this.state = TxnState.NO_TRANSACTION; + this.options = {}; + + const writeConcern = WriteConcern.fromOptions(options); + if (writeConcern) { + if (writeConcern.w === 0) { + throw new MongoTransactionError('Transactions do not support unacknowledged write concern'); + } + + this.options.writeConcern = writeConcern; + } + + if (options.readConcern) { + this.options.readConcern = ReadConcern.fromOptions(options); + } + + if (options.readPreference) { + this.options.readPreference = ReadPreference.fromOptions(options); + } + + if (options.maxCommitTimeMS) { + this.options.maxTimeMS = options.maxCommitTimeMS; + } + + // TODO: This isn't technically necessary + this._pinnedServer = undefined; + this._recoveryToken = undefined; + } + + /** @internal */ + get server(): Server | undefined { + return this._pinnedServer; + } + + get recoveryToken(): Document | undefined { + return this._recoveryToken; + } + + get isPinned(): boolean { + return !!this.server; + } + + /** @returns Whether the transaction has started */ + get isStarting(): boolean { + return this.state === TxnState.STARTING_TRANSACTION; + } + + /** + * @returns Whether this session is presently in a transaction + */ + get isActive(): boolean { + return ACTIVE_STATES.has(this.state); + } + + get isCommitted(): boolean { + return COMMITTED_STATES.has(this.state); + } + /** + * Transition the transaction in the state machine + * @internal + * @param nextState - The new state to transition to + */ + transition(nextState: TxnState): void { + const nextStates = stateMachine[this.state]; + if (nextStates && nextStates.includes(nextState)) { + this.state = nextState; + if ( + this.state === TxnState.NO_TRANSACTION || + this.state === TxnState.STARTING_TRANSACTION || + this.state === TxnState.TRANSACTION_ABORTED + ) { + this.unpinServer(); + } + return; + } + + throw new MongoRuntimeError( + `Attempted illegal state transition from [${this.state}] to [${nextState}]` + ); + } + + /** @internal */ + pinServer(server: Server): void { + if (this.isActive) { + this._pinnedServer = server; + } + } + + /** @internal */ + unpinServer(): void { + this._pinnedServer = undefined; + } +} + +export function isTransactionCommand(command: Document): boolean { + return !!(command.commitTransaction || command.abortTransaction); +} diff --git a/ts-ticket-office-service/node_modules/mongodb/src/utils.ts b/ts-ticket-office-service/node_modules/mongodb/src/utils.ts new file mode 100644 index 000000000..b29adf822 --- /dev/null +++ b/ts-ticket-office-service/node_modules/mongodb/src/utils.ts @@ -0,0 +1,1432 @@ +import * as crypto from 'crypto'; +import type { SrvRecord } from 'dns'; +import * as os from 'os'; +import { setTimeout } from 'timers'; +import { URL } from 'url'; + +import { Document, ObjectId, resolveBSONOptions } from './bson'; +import type { Connection } from './cmap/connection'; +import { MAX_SUPPORTED_WIRE_VERSION } from './cmap/wire_protocol/constants'; +import type { Collection } from './collection'; +import { LEGACY_HELLO_COMMAND } from './constants'; +import type { AbstractCursor } from './cursor/abstract_cursor'; +import type { FindCursor } from './cursor/find_cursor'; +import type { Db } from './db'; +import { + AnyError, + MongoCompatibilityError, + MongoInvalidArgumentError, + MongoNotConnectedError, + MongoParseError, + MongoRuntimeError +} from './error'; +import type { Explain } from './explain'; +import type { MongoClient } from './mongo_client'; +import type { CommandOperationOptions, OperationParent } from './operations/command'; +import type { IndexDirection, IndexSpecification } from './operations/indexes'; +import type { Hint, OperationOptions } from './operations/operation'; +import { PromiseProvider } from './promise_provider'; +import { ReadConcern } from './read_concern'; +import { ReadPreference } from './read_preference'; +import { ServerType } from './sdam/common'; +import type { Server } from './sdam/server'; +import type { Topology } from './sdam/topology'; +import type { ClientSession } from './sessions'; +import { W, WriteConcern, WriteConcernOptions } from './write_concern'; + +/** + * MongoDB Driver style callback + * @public + */ +export type Callback = (error?: AnyError, result?: T) => void; + +export const MAX_JS_INT = Number.MAX_SAFE_INTEGER + 1; + +export type AnyOptions = Document; + +/** + * Throws if collectionName is not a valid mongodb collection namespace. + * @internal + */ +export function checkCollectionName(collectionName: string): void { + if ('string' !== typeof collectionName) { + throw new MongoInvalidArgumentError('Collection name must be a String'); + } + + if (!collectionName || collectionName.indexOf('..') !== -1) { + throw new MongoInvalidArgumentError('Collection names cannot be empty'); + } + + if ( + collectionName.indexOf('$') !== -1 && + collectionName.match(/((^\$cmd)|(oplog\.\$main))/) == null + ) { + // TODO(NODE-3483): Use MongoNamespace static method + throw new MongoInvalidArgumentError("Collection names must not contain '$'"); + } + + if (collectionName.match(/^\.|\.$/) != null) { + // TODO(NODE-3483): Use MongoNamespace static method + throw new MongoInvalidArgumentError("Collection names must not start or end with '.'"); + } + + // Validate that we are not passing 0x00 in the collection name + if (collectionName.indexOf('\x00') !== -1) { + // TODO(NODE-3483): Use MongoNamespace static method + throw new MongoInvalidArgumentError('Collection names cannot contain a null character'); + } +} + +/** + * Ensure Hint field is in a shape we expect: + * - object of index names mapping to 1 or -1 + * - just an index name + * @internal + */ +export function normalizeHintField(hint?: Hint): Hint | undefined { + let finalHint = undefined; + + if (typeof hint === 'string') { + finalHint = hint; + } else if (Array.isArray(hint)) { + finalHint = {}; + + hint.forEach(param => { + finalHint[param] = 1; + }); + } else if (hint != null && typeof hint === 'object') { + finalHint = {} as Document; + for (const name in hint) { + finalHint[name] = hint[name]; + } + } + + return finalHint; +} + +interface IndexOptions { + name: string; + keys?: string[]; + fieldHash: Document; +} + +/** + * Create an index specifier based on + * @internal + */ +export function parseIndexOptions(indexSpec: IndexSpecification): IndexOptions { + const fieldHash: { [key: string]: IndexDirection } = {}; + const indexes = []; + let keys; + + // Get all the fields accordingly + if ('string' === typeof indexSpec) { + // 'type' + indexes.push(indexSpec + '_' + 1); + fieldHash[indexSpec] = 1; + } else if (Array.isArray(indexSpec)) { + indexSpec.forEach((f: any) => { + if ('string' === typeof f) { + // [{location:'2d'}, 'type'] + indexes.push(f + '_' + 1); + fieldHash[f] = 1; + } else if (Array.isArray(f)) { + // [['location', '2d'],['type', 1]] + indexes.push(f[0] + '_' + (f[1] || 1)); + fieldHash[f[0]] = f[1] || 1; + } else if (isObject(f)) { + // [{location:'2d'}, {type:1}] + keys = Object.keys(f); + keys.forEach(k => { + indexes.push(k + '_' + (f as AnyOptions)[k]); + fieldHash[k] = (f as AnyOptions)[k]; + }); + } else { + // undefined (ignore) + } + }); + } else if (isObject(indexSpec)) { + // {location:'2d', type:1} + keys = Object.keys(indexSpec); + Object.entries(indexSpec).forEach(([key, value]) => { + indexes.push(key + '_' + value); + fieldHash[key] = value; + }); + } + + return { + name: indexes.join('_'), + keys: keys, + fieldHash: fieldHash + }; +} + +const TO_STRING = (object: unknown) => Object.prototype.toString.call(object); +/** + * Checks if arg is an Object: + * - **NOTE**: the check is based on the `[Symbol.toStringTag]() === 'Object'` + * @internal + */ + +export function isObject(arg: unknown): arg is object { + return '[object Object]' === TO_STRING(arg); +} + +/** @internal */ +export function mergeOptions(target: T, source: S): T & S { + return { ...target, ...source }; +} + +/** @internal */ +export function filterOptions(options: AnyOptions, names: ReadonlyArray): AnyOptions { + const filterOptions: AnyOptions = {}; + + for (const name in options) { + if (names.includes(name)) { + filterOptions[name] = options[name]; + } + } + + // Filtered options + return filterOptions; +} + +interface HasRetryableWrites { + retryWrites?: boolean; +} +/** + * Applies retryWrites: true to a command if retryWrites is set on the command's database. + * @internal + * + * @param target - The target command to which we will apply retryWrites. + * @param db - The database from which we can inherit a retryWrites value. + */ +export function applyRetryableWrites(target: T, db?: Db): T { + if (db && db.s.options?.retryWrites) { + target.retryWrites = true; + } + + return target; +} + +interface HasWriteConcern { + writeConcern?: WriteConcernOptions | WriteConcern | W; +} +/** + * Applies a write concern to a command based on well defined inheritance rules, optionally + * detecting support for the write concern in the first place. + * @internal + * + * @param target - the target command we will be applying the write concern to + * @param sources - sources where we can inherit default write concerns from + * @param options - optional settings passed into a command for write concern overrides + */ +export function applyWriteConcern( + target: T, + sources: { db?: Db; collection?: Collection }, + options?: OperationOptions & WriteConcernOptions +): T { + options = options ?? {}; + const db = sources.db; + const coll = sources.collection; + + if (options.session && options.session.inTransaction()) { + // writeConcern is not allowed within a multi-statement transaction + if (target.writeConcern) { + delete target.writeConcern; + } + + return target; + } + + const writeConcern = WriteConcern.fromOptions(options); + if (writeConcern) { + return Object.assign(target, { writeConcern }); + } + + if (coll && coll.writeConcern) { + return Object.assign(target, { writeConcern: Object.assign({}, coll.writeConcern) }); + } + + if (db && db.writeConcern) { + return Object.assign(target, { writeConcern: Object.assign({}, db.writeConcern) }); + } + + return target; +} + +/** + * Checks if a given value is a Promise + * + * @typeParam T - The result type of maybePromise + * @param maybePromise - An object that could be a promise + * @returns true if the provided value is a Promise + */ +export function isPromiseLike( + maybePromise?: PromiseLike | void +): maybePromise is Promise { + return !!maybePromise && typeof maybePromise.then === 'function'; +} + +/** + * Applies collation to a given command. + * @internal + * + * @param command - the command on which to apply collation + * @param target - target of command + * @param options - options containing collation settings + */ +export function decorateWithCollation( + command: Document, + target: MongoClient | Db | Collection, + options: AnyOptions +): void { + const capabilities = getTopology(target).capabilities; + if (options.collation && typeof options.collation === 'object') { + if (capabilities && capabilities.commandsTakeCollation) { + command.collation = options.collation; + } else { + throw new MongoCompatibilityError(`Current topology does not support collation`); + } + } +} + +/** + * Applies a read concern to a given command. + * @internal + * + * @param command - the command on which to apply the read concern + * @param coll - the parent collection of the operation calling this method + */ +export function decorateWithReadConcern( + command: Document, + coll: { s: { readConcern?: ReadConcern } }, + options?: OperationOptions +): void { + if (options && options.session && options.session.inTransaction()) { + return; + } + const readConcern = Object.assign({}, command.readConcern || {}); + if (coll.s.readConcern) { + Object.assign(readConcern, coll.s.readConcern); + } + + if (Object.keys(readConcern).length > 0) { + Object.assign(command, { readConcern: readConcern }); + } +} + +/** + * Applies an explain to a given command. + * @internal + * + * @param command - the command on which to apply the explain + * @param options - the options containing the explain verbosity + */ +export function decorateWithExplain(command: Document, explain: Explain): Document { + if (command.explain) { + return command; + } + + return { explain: command, verbosity: explain.verbosity }; +} + +/** + * @internal + */ +export type TopologyProvider = + | MongoClient + | ClientSession + | FindCursor + | AbstractCursor + | Collection + | Db; + +/** + * A helper function to get the topology from a given provider. Throws + * if the topology cannot be found. + * @throws MongoNotConnectedError + * @internal + */ +export function getTopology(provider: TopologyProvider): Topology { + // MongoClient or ClientSession or AbstractCursor + if ('topology' in provider && provider.topology) { + return provider.topology; + } else if ('s' in provider && 'client' in provider.s && provider.s.client.topology) { + return provider.s.client.topology; + } else if ('s' in provider && 'db' in provider.s && provider.s.db.s.client.topology) { + return provider.s.db.s.client.topology; + } + + throw new MongoNotConnectedError('MongoClient must be connected to perform this operation'); +} + +/** + * Default message handler for generating deprecation warnings. + * @internal + * + * @param name - function name + * @param option - option name + * @returns warning message + */ +export function defaultMsgHandler(name: string, option: string): string { + return `${name} option [${option}] is deprecated and will be removed in a later version.`; +} + +export interface DeprecateOptionsConfig { + /** function name */ + name: string; + /** options to deprecate */ + deprecatedOptions: string[]; + /** index of options object in function arguments array */ + optionsIndex: number; + /** optional custom message handler to generate warnings */ + msgHandler?(this: void, name: string, option: string): string; +} + +/** + * Deprecates a given function's options. + * @internal + * + * @param this - the bound class if this is a method + * @param config - configuration for deprecation + * @param fn - the target function of deprecation + * @returns modified function that warns once per deprecated option, and executes original function + */ +export function deprecateOptions( + this: unknown, + config: DeprecateOptionsConfig, + fn: (...args: any[]) => any +): any { + if ((process as any).noDeprecation === true) { + return fn; + } + + const msgHandler = config.msgHandler ? config.msgHandler : defaultMsgHandler; + + const optionsWarned = new Set(); + function deprecated(this: any, ...args: any[]) { + const options = args[config.optionsIndex] as AnyOptions; + + // ensure options is a valid, non-empty object, otherwise short-circuit + if (!isObject(options) || Object.keys(options).length === 0) { + return fn.bind(this)(...args); // call the function, no change + } + + // interrupt the function call with a warning + for (const deprecatedOption of config.deprecatedOptions) { + if (deprecatedOption in options && !optionsWarned.has(deprecatedOption)) { + optionsWarned.add(deprecatedOption); + const msg = msgHandler(config.name, deprecatedOption); + emitWarning(msg); + if (this && 'getLogger' in this) { + const logger = this.getLogger(); + if (logger) { + logger.warn(msg); + } + } + } + } + + return fn.bind(this)(...args); + } + + // These lines copied from https://github.com/nodejs/node/blob/25e5ae41688676a5fd29b2e2e7602168eee4ceb5/lib/internal/util.js#L73-L80 + // The wrapper will keep the same prototype as fn to maintain prototype chain + Object.setPrototypeOf(deprecated, fn); + if (fn.prototype) { + // Setting this (rather than using Object.setPrototype, as above) ensures + // that calling the unwrapped constructor gives an instanceof the wrapped + // constructor. + deprecated.prototype = fn.prototype; + } + + return deprecated; +} + +/** @internal */ +export function ns(ns: string): MongoDBNamespace { + return MongoDBNamespace.fromString(ns); +} + +/** @public */ +export class MongoDBNamespace { + db: string; + collection?: string; + /** + * Create a namespace object + * + * @param db - database name + * @param collection - collection name + */ + constructor(db: string, collection?: string) { + this.db = db; + this.collection = collection; + } + + toString(): string { + return this.collection ? `${this.db}.${this.collection}` : this.db; + } + + withCollection(collection: string): MongoDBNamespace { + return new MongoDBNamespace(this.db, collection); + } + + static fromString(namespace?: string): MongoDBNamespace { + if (!namespace) { + // TODO(NODE-3483): Replace with MongoNamespaceError + throw new MongoRuntimeError(`Cannot parse namespace from "${namespace}"`); + } + + const [db, ...collection] = namespace.split('.'); + return new MongoDBNamespace(db, collection.join('.')); + } +} + +/** @internal */ +export function* makeCounter(seed = 0): Generator { + let count = seed; + while (true) { + const newCount = count; + count += 1; + yield newCount; + } +} + +/** + * Helper function for either accepting a callback, or returning a promise + * @internal + * + * @param callback - The last function argument in exposed method, controls if a Promise is returned + * @param wrapper - A function that wraps the callback + * @returns Returns void if a callback is supplied, else returns a Promise. + */ +export function maybePromise( + callback: Callback | undefined, + wrapper: (fn: Callback) => void +): Promise | void { + const Promise = PromiseProvider.get(); + let result: Promise | void; + if (typeof callback !== 'function') { + result = new Promise((resolve, reject) => { + callback = (err, res) => { + if (err) return reject(err); + resolve(res); + }; + }); + } + + wrapper((err, res) => { + if (err != null) { + try { + // eslint-disable-next-line @typescript-eslint/no-non-null-assertion + callback!(err); + } catch (error) { + process.nextTick(() => { + throw error; + }); + } + + return; + } + + // eslint-disable-next-line @typescript-eslint/no-non-null-assertion + callback!(err, res); + }); + + return result; +} + +/** @internal */ +export function databaseNamespace(ns: string): string { + return ns.split('.')[0]; +} + +/** + * Synchronously Generate a UUIDv4 + * @internal + */ +export function uuidV4(): Buffer { + const result = crypto.randomBytes(16); + result[6] = (result[6] & 0x0f) | 0x40; + result[8] = (result[8] & 0x3f) | 0x80; + return result; +} + +/** + * A helper function for determining `maxWireVersion` between legacy and new topology instances + * @internal + */ +export function maxWireVersion(topologyOrServer?: Connection | Topology | Server): number { + if (topologyOrServer) { + if (topologyOrServer.loadBalanced) { + // Since we do not have a monitor, we assume the load balanced server is always + // pointed at the latest mongodb version. There is a risk that for on-prem + // deployments that don't upgrade immediately that this could alert to the + // application that a feature is avaiable that is actually not. + return MAX_SUPPORTED_WIRE_VERSION; + } + if (topologyOrServer.hello) { + return topologyOrServer.hello.maxWireVersion; + } + + if ('lastHello' in topologyOrServer && typeof topologyOrServer.lastHello === 'function') { + const lastHello = topologyOrServer.lastHello(); + if (lastHello) { + return lastHello.maxWireVersion; + } + } + + if ( + topologyOrServer.description && + 'maxWireVersion' in topologyOrServer.description && + topologyOrServer.description.maxWireVersion != null + ) { + return topologyOrServer.description.maxWireVersion; + } + } + + return 0; +} + +/** + * Checks that collation is supported by server. + * @internal + * + * @param server - to check against + * @param cmd - object where collation may be specified + */ +export function collationNotSupported(server: Server, cmd: Document): boolean { + return cmd && cmd.collation && maxWireVersion(server) < 5; +} + +/** + * Applies the function `eachFn` to each item in `arr`, in parallel. + * @internal + * + * @param arr - An array of items to asynchronously iterate over + * @param eachFn - A function to call on each item of the array. The callback signature is `(item, callback)`, where the callback indicates iteration is complete. + * @param callback - The callback called after every item has been iterated + */ +export function eachAsync( + arr: T[], + eachFn: (item: T, callback: (err?: AnyError) => void) => void, + callback: Callback +): void { + arr = arr || []; + + let idx = 0; + let awaiting = 0; + for (idx = 0; idx < arr.length; ++idx) { + awaiting++; + eachFn(arr[idx], eachCallback); + } + + if (awaiting === 0) { + callback(); + return; + } + + function eachCallback(err?: AnyError) { + awaiting--; + if (err) { + callback(err); + return; + } + + if (idx === arr.length && awaiting <= 0) { + callback(); + } + } +} + +/** @internal */ +export function eachAsyncSeries( + arr: T[], + eachFn: (item: T, callback: (err?: AnyError) => void) => void, + callback: Callback +): void { + arr = arr || []; + + let idx = 0; + let awaiting = arr.length; + if (awaiting === 0) { + callback(); + return; + } + + function eachCallback(err?: AnyError) { + idx++; + awaiting--; + if (err) { + callback(err); + return; + } + + if (idx === arr.length && awaiting <= 0) { + callback(); + return; + } + + eachFn(arr[idx], eachCallback); + } + + eachFn(arr[idx], eachCallback); +} + +/** @internal */ +export function arrayStrictEqual(arr: unknown[], arr2: unknown[]): boolean { + if (!Array.isArray(arr) || !Array.isArray(arr2)) { + return false; + } + + return arr.length === arr2.length && arr.every((elt, idx) => elt === arr2[idx]); +} + +/** @internal */ +export function errorStrictEqual(lhs?: AnyError, rhs?: AnyError): boolean { + if (lhs === rhs) { + return true; + } + + if (!lhs || !rhs) { + return lhs === rhs; + } + + if ((lhs == null && rhs != null) || (lhs != null && rhs == null)) { + return false; + } + + if (lhs.constructor.name !== rhs.constructor.name) { + return false; + } + + if (lhs.message !== rhs.message) { + return false; + } + + return true; +} + +interface StateTable { + [key: string]: string[]; +} +interface ObjectWithState { + s: { state: string }; + emit(event: 'stateChanged', state: string, newState: string): void; +} +interface StateTransitionFunction { + (target: ObjectWithState, newState: string): void; +} + +/** @public */ +export type EventEmitterWithState = { + /** @internal */ + stateChanged(previous: string, current: string): void; +}; + +/** @internal */ +export function makeStateMachine(stateTable: StateTable): StateTransitionFunction { + return function stateTransition(target, newState) { + const legalStates = stateTable[target.s.state]; + if (legalStates && legalStates.indexOf(newState) < 0) { + throw new MongoRuntimeError( + `illegal state transition from [${target.s.state}] => [${newState}], allowed: [${legalStates}]` + ); + } + + target.emit('stateChanged', target.s.state, newState); + target.s.state = newState; + }; +} + +/** @public */ +export interface ClientMetadata { + driver: { + name: string; + version: string; + }; + os: { + type: string; + name: NodeJS.Platform; + architecture: string; + version: string; + }; + platform: string; + version?: string; + application?: { + name: string; + }; +} + +/** @public */ +export interface ClientMetadataOptions { + driverInfo?: { + name?: string; + version?: string; + platform?: string; + }; + appName?: string; +} + +// eslint-disable-next-line @typescript-eslint/no-var-requires +const NODE_DRIVER_VERSION = require('../package.json').version; + +export function makeClientMetadata(options?: ClientMetadataOptions): ClientMetadata { + options = options ?? {}; + + const metadata: ClientMetadata = { + driver: { + name: 'nodejs', + version: NODE_DRIVER_VERSION + }, + os: { + type: os.type(), + name: process.platform, + architecture: process.arch, + version: os.release() + }, + platform: `Node.js ${process.version}, ${os.endianness()} (unified)` + }; + + // support optionally provided wrapping driver info + if (options.driverInfo) { + if (options.driverInfo.name) { + metadata.driver.name = `${metadata.driver.name}|${options.driverInfo.name}`; + } + + if (options.driverInfo.version) { + metadata.version = `${metadata.driver.version}|${options.driverInfo.version}`; + } + + if (options.driverInfo.platform) { + metadata.platform = `${metadata.platform}|${options.driverInfo.platform}`; + } + } + + if (options.appName) { + // MongoDB requires the appName not exceed a byte length of 128 + const buffer = Buffer.from(options.appName); + metadata.application = { + name: buffer.byteLength > 128 ? buffer.slice(0, 128).toString('utf8') : options.appName + }; + } + + return metadata; +} + +/** @internal */ +export function now(): number { + const hrtime = process.hrtime(); + return Math.floor(hrtime[0] * 1000 + hrtime[1] / 1000000); +} + +/** @internal */ +export function calculateDurationInMs(started: number): number { + if (typeof started !== 'number') { + throw new MongoInvalidArgumentError('Numeric value required to calculate duration'); + } + + const elapsed = now() - started; + return elapsed < 0 ? 0 : elapsed; +} + +export interface InterruptibleAsyncIntervalOptions { + /** The interval to execute a method on */ + interval: number; + /** A minimum interval that must elapse before the method is called */ + minInterval: number; + /** Whether the method should be called immediately when the interval is started */ + immediate: boolean; + + /** + * Only used for testing unreliable timer environments + * @internal + */ + clock: () => number; +} + +/** @internal */ +export interface InterruptibleAsyncInterval { + wake(): void; + stop(): void; +} + +/** + * Creates an interval timer which is able to be woken up sooner than + * the interval. The timer will also debounce multiple calls to wake + * ensuring that the function is only ever called once within a minimum + * interval window. + * @internal + * + * @param fn - An async function to run on an interval, must accept a `callback` as its only parameter + */ +export function makeInterruptibleAsyncInterval( + fn: (callback: Callback) => void, + options?: Partial +): InterruptibleAsyncInterval { + let timerId: NodeJS.Timeout | undefined; + let lastCallTime: number; + let cannotBeExpedited = false; + let stopped = false; + + options = options ?? {}; + const interval = options.interval || 1000; + const minInterval = options.minInterval || 500; + const immediate = typeof options.immediate === 'boolean' ? options.immediate : false; + const clock = typeof options.clock === 'function' ? options.clock : now; + + function wake() { + const currentTime = clock(); + const nextScheduledCallTime = lastCallTime + interval; + const timeUntilNextCall = nextScheduledCallTime - currentTime; + + // For the streaming protocol: there is nothing obviously stopping this + // interval from being woken up again while we are waiting "infinitely" + // for `fn` to be called again`. Since the function effectively + // never completes, the `timeUntilNextCall` will continue to grow + // negatively unbounded, so it will never trigger a reschedule here. + + // This is possible in virtualized environments like AWS Lambda where our + // clock is unreliable. In these cases the timer is "running" but never + // actually completes, so we want to execute immediately and then attempt + // to reschedule. + if (timeUntilNextCall < 0) { + executeAndReschedule(); + return; + } + + // debounce multiple calls to wake within the `minInterval` + if (cannotBeExpedited) { + return; + } + + // reschedule a call as soon as possible, ensuring the call never happens + // faster than the `minInterval` + if (timeUntilNextCall > minInterval) { + reschedule(minInterval); + cannotBeExpedited = true; + } + } + + function stop() { + stopped = true; + if (timerId) { + clearTimeout(timerId); + timerId = undefined; + } + + lastCallTime = 0; + cannotBeExpedited = false; + } + + function reschedule(ms?: number) { + if (stopped) return; + if (timerId) { + clearTimeout(timerId); + } + + timerId = setTimeout(executeAndReschedule, ms || interval); + } + + function executeAndReschedule() { + cannotBeExpedited = false; + lastCallTime = clock(); + + fn(err => { + if (err) throw err; + reschedule(interval); + }); + } + + if (immediate) { + executeAndReschedule(); + } else { + lastCallTime = clock(); + reschedule(undefined); + } + + return { wake, stop }; +} + +/** @internal */ +export function hasAtomicOperators(doc: Document | Document[]): boolean { + if (Array.isArray(doc)) { + for (const document of doc) { + if (hasAtomicOperators(document)) { + return true; + } + } + return false; + } + + const keys = Object.keys(doc); + return keys.length > 0 && keys[0][0] === '$'; +} + +/** + * Merge inherited properties from parent into options, prioritizing values from options, + * then values from parent. + * @internal + */ +export function resolveOptions( + parent: OperationParent | undefined, + options?: T +): T { + const result: T = Object.assign({}, options, resolveBSONOptions(options, parent)); + + // Users cannot pass a readConcern/writeConcern to operations in a transaction + const session = options?.session; + if (!session?.inTransaction()) { + const readConcern = ReadConcern.fromOptions(options) ?? parent?.readConcern; + if (readConcern) { + result.readConcern = readConcern; + } + + const writeConcern = WriteConcern.fromOptions(options) ?? parent?.writeConcern; + if (writeConcern) { + result.writeConcern = writeConcern; + } + } + + const readPreference = ReadPreference.fromOptions(options) ?? parent?.readPreference; + if (readPreference) { + result.readPreference = readPreference; + } + + return result; +} + +export function isSuperset(set: Set | any[], subset: Set | any[]): boolean { + set = Array.isArray(set) ? new Set(set) : set; + subset = Array.isArray(subset) ? new Set(subset) : subset; + for (const elem of subset) { + if (!set.has(elem)) { + return false; + } + } + return true; +} + +/** + * Checks if the document is a Hello request + * @internal + */ +export function isHello(doc: Document): boolean { + return doc[LEGACY_HELLO_COMMAND] || doc.hello ? true : false; +} + +/** Returns the items that are uniquely in setA */ +export function setDifference(setA: Iterable, setB: Iterable): Set { + const difference = new Set(setA); + for (const elem of setB) { + difference.delete(elem); + } + return difference; +} + +const HAS_OWN = (object: unknown, prop: string) => + Object.prototype.hasOwnProperty.call(object, prop); + +export function isRecord( + value: unknown, + requiredKeys: T +): value is Record; +export function isRecord(value: unknown): value is Record; +export function isRecord( + value: unknown, + requiredKeys: string[] | undefined = undefined +): value is Record { + if (!isObject(value)) { + return false; + } + + const ctor = (value as any).constructor; + if (ctor && ctor.prototype) { + if (!isObject(ctor.prototype)) { + return false; + } + + // Check to see if some method exists from the Object exists + if (!HAS_OWN(ctor.prototype, 'isPrototypeOf')) { + return false; + } + } + + if (requiredKeys) { + const keys = Object.keys(value as Record); + return isSuperset(keys, requiredKeys); + } + + return true; +} + +/** + * Make a deep copy of an object + * + * NOTE: This is not meant to be the perfect implementation of a deep copy, + * but instead something that is good enough for the purposes of + * command monitoring. + */ +export function deepCopy(value: T): T { + if (value == null) { + return value; + } else if (Array.isArray(value)) { + return value.map(item => deepCopy(item)) as unknown as T; + } else if (isRecord(value)) { + const res = {} as any; + for (const key in value) { + res[key] = deepCopy(value[key]); + } + return res; + } + + const ctor = (value as any).constructor; + if (ctor) { + switch (ctor.name.toLowerCase()) { + case 'date': + return new ctor(Number(value)); + case 'map': + return new Map(value as any) as unknown as T; + case 'set': + return new Set(value as any) as unknown as T; + case 'buffer': + return Buffer.from(value as unknown as Buffer) as unknown as T; + } + } + + return value; +} + +/** @internal */ +const kBuffers = Symbol('buffers'); +/** @internal */ +const kLength = Symbol('length'); + +/** + * A pool of Buffers which allow you to read them as if they were one + * @internal + */ +export class BufferPool { + [kBuffers]: Buffer[]; + [kLength]: number; + + constructor() { + this[kBuffers] = []; + this[kLength] = 0; + } + + get length(): number { + return this[kLength]; + } + + /** Adds a buffer to the internal buffer pool list */ + append(buffer: Buffer): void { + this[kBuffers].push(buffer); + this[kLength] += buffer.length; + } + + /** Returns the requested number of bytes without consuming them */ + peek(size: number): Buffer { + return this.read(size, false); + } + + /** Reads the requested number of bytes, optionally consuming them */ + read(size: number, consume = true): Buffer { + if (typeof size !== 'number' || size < 0) { + throw new MongoInvalidArgumentError('Argument "size" must be a non-negative number'); + } + + if (size > this[kLength]) { + return Buffer.alloc(0); + } + + let result: Buffer; + + // read the whole buffer + if (size === this.length) { + result = Buffer.concat(this[kBuffers]); + + if (consume) { + this[kBuffers] = []; + this[kLength] = 0; + } + } + + // size is within first buffer, no need to concat + else if (size <= this[kBuffers][0].length) { + result = this[kBuffers][0].slice(0, size); + if (consume) { + this[kBuffers][0] = this[kBuffers][0].slice(size); + this[kLength] -= size; + } + } + + // size is beyond first buffer, need to track and copy + else { + result = Buffer.allocUnsafe(size); + + let idx; + let offset = 0; + let bytesToCopy = size; + for (idx = 0; idx < this[kBuffers].length; ++idx) { + let bytesCopied; + if (bytesToCopy > this[kBuffers][idx].length) { + bytesCopied = this[kBuffers][idx].copy(result, offset, 0); + offset += bytesCopied; + } else { + bytesCopied = this[kBuffers][idx].copy(result, offset, 0, bytesToCopy); + if (consume) { + this[kBuffers][idx] = this[kBuffers][idx].slice(bytesCopied); + } + offset += bytesCopied; + break; + } + + bytesToCopy -= bytesCopied; + } + + // compact the internal buffer array + if (consume) { + this[kBuffers] = this[kBuffers].slice(idx); + this[kLength] -= size; + } + } + + return result; + } +} + +/** @public */ +export class HostAddress { + host; + port; + // Driver only works with unix socket path to connect + // SDAM operates only on tcp addresses + socketPath; + isIPv6; + + constructor(hostString: string) { + const escapedHost = hostString.split(' ').join('%20'); // escape spaces, for socket path hosts + const { hostname, port } = new URL(`mongodb://${escapedHost}`); + + if (hostname.endsWith('.sock')) { + // heuristically determine if we're working with a domain socket + this.socketPath = decodeURIComponent(hostname); + } else if (typeof hostname === 'string') { + this.isIPv6 = false; + + let normalized = decodeURIComponent(hostname).toLowerCase(); + if (normalized.startsWith('[') && normalized.endsWith(']')) { + this.isIPv6 = true; + normalized = normalized.substring(1, hostname.length - 1); + } + + this.host = normalized.toLowerCase(); + + if (typeof port === 'number') { + this.port = port; + } else if (typeof port === 'string' && port !== '') { + this.port = Number.parseInt(port, 10); + } else { + this.port = 27017; + } + + if (this.port === 0) { + throw new MongoParseError('Invalid port (zero) with hostname'); + } + } else { + throw new MongoInvalidArgumentError('Either socketPath or host must be defined.'); + } + Object.freeze(this); + } + + [Symbol.for('nodejs.util.inspect.custom')](): string { + return this.inspect(); + } + + inspect(): string { + return `new HostAddress('${this.toString(true)}')`; + } + + /** + * @param ipv6Brackets - optionally request ipv6 bracket notation required for connection strings + */ + toString(ipv6Brackets = false): string { + if (typeof this.host === 'string') { + if (this.isIPv6 && ipv6Brackets) { + return `[${this.host}]:${this.port}`; + } + return `${this.host}:${this.port}`; + } + return `${this.socketPath}`; + } + + static fromString(this: void, s: string): HostAddress { + return new HostAddress(s); + } + + static fromHostPort(host: string, port: number): HostAddress { + if (host.includes(':')) { + host = `[${host}]`; // IPv6 address + } + return HostAddress.fromString(`${host}:${port}`); + } + + static fromSrvRecord({ name, port }: SrvRecord): HostAddress { + return HostAddress.fromHostPort(name, port); + } +} + +export const DEFAULT_PK_FACTORY = { + // We prefer not to rely on ObjectId having a createPk method + createPk(): ObjectId { + return new ObjectId(); + } +}; + +/** + * When the driver used emitWarning the code will be equal to this. + * @public + * + * @example + * ```js + * process.on('warning', (warning) => { + * if (warning.code === MONGODB_WARNING_CODE) console.error('Ah an important warning! :)') + * }) + * ``` + */ +export const MONGODB_WARNING_CODE = 'MONGODB DRIVER' as const; + +/** @internal */ +export function emitWarning(message: string): void { + return process.emitWarning(message, { code: MONGODB_WARNING_CODE } as any); +} + +const emittedWarnings = new Set(); +/** + * Will emit a warning once for the duration of the application. + * Uses the message to identify if it has already been emitted + * so using string interpolation can cause multiple emits + * @internal + */ +export function emitWarningOnce(message: string): void { + if (!emittedWarnings.has(message)) { + emittedWarnings.add(message); + return emitWarning(message); + } +} + +/** + * Takes a JS object and joins the values into a string separated by ', ' + */ +export function enumToString(en: Record): string { + return Object.values(en).join(', '); +} + +/** + * Determine if a server supports retryable writes. + * + * @internal + */ +export function supportsRetryableWrites(server?: Server): boolean { + if (!server) { + return false; + } + + if (server.loadBalanced) { + // Loadbalanced topologies will always support retry writes + return true; + } + + if (server.description.logicalSessionTimeoutMinutes != null) { + // that supports sessions + if (server.description.type !== ServerType.Standalone) { + // and that is not a standalone + return true; + } + } + + return false; +} + +export function parsePackageVersion({ version }: { version: string }): { + major: number; + minor: number; + patch: number; +} { + const [major, minor, patch] = version.split('.').map((n: string) => Number.parseInt(n, 10)); + return { major, minor, patch }; +} + +/** + * Fisher–Yates Shuffle + * + * Reference: https://bost.ocks.org/mike/shuffle/ + * @param sequence - items to be shuffled + * @param limit - Defaults to `0`. If nonzero shuffle will slice the randomized array e.g, `.slice(0, limit)` otherwise will return the entire randomized array. + */ +export function shuffle(sequence: Iterable, limit = 0): Array { + const items = Array.from(sequence); // shallow copy in order to never shuffle the input + + if (limit > items.length) { + throw new MongoRuntimeError('Limit must be less than the number of items'); + } + + let remainingItemsToShuffle = items.length; + const lowerBound = limit % items.length === 0 ? 1 : items.length - limit; + while (remainingItemsToShuffle > lowerBound) { + // Pick a remaining element + const randomIndex = Math.floor(Math.random() * remainingItemsToShuffle); + remainingItemsToShuffle -= 1; + + // And swap it with the current element + const swapHold = items[remainingItemsToShuffle]; + items[remainingItemsToShuffle] = items[randomIndex]; + items[randomIndex] = swapHold; + } + + return limit % items.length === 0 ? items : items.slice(lowerBound); +} + +// TODO: this should be codified in command construction +// @see https://github.com/mongodb/specifications/blob/master/source/read-write-concern/read-write-concern.rst#read-concern +export function commandSupportsReadConcern(command: Document, options?: Document): boolean { + if (command.aggregate || command.count || command.distinct || command.find || command.geoNear) { + return true; + } + + if ( + command.mapReduce && + options && + options.out && + (options.out.inline === 1 || options.out === 'inline') + ) { + return true; + } + + return false; +} + +/** + * A utility function to get the instance of mongodb-client-encryption, if it exists. + * + * @throws MongoMissingDependencyError if mongodb-client-encryption isn't installed. + * @returns + */ +export function getMongoDBClientEncryption() { + let mongodbClientEncryption; + + // NOTE(NODE-4254): This is to get around the circular dependency between + // mongodb-client-encryption and the driver in the test scenarios. + if ( + typeof process.env.MONGODB_CLIENT_ENCRYPTION_OVERRIDE === 'string' && + process.env.MONGODB_CLIENT_ENCRYPTION_OVERRIDE.length > 0 + ) { + mongodbClientEncryption = require(process.env.MONGODB_CLIENT_ENCRYPTION_OVERRIDE); + } else { + mongodbClientEncryption = require('mongodb-client-encryption'); + } + + return mongodbClientEncryption; +} diff --git a/ts-ticket-office-service/node_modules/mongodb/src/write_concern.ts b/ts-ticket-office-service/node_modules/mongodb/src/write_concern.ts new file mode 100644 index 000000000..ebc77ebf6 --- /dev/null +++ b/ts-ticket-office-service/node_modules/mongodb/src/write_concern.ts @@ -0,0 +1,114 @@ +/** @public */ +export type W = number | 'majority'; + +/** @public */ +export interface WriteConcernOptions { + /** Write Concern as an object */ + writeConcern?: WriteConcern | WriteConcernSettings; +} + +/** @public */ +export interface WriteConcernSettings { + /** The write concern */ + w?: W; + /** The write concern timeout */ + wtimeoutMS?: number; + /** The journal write concern */ + journal?: boolean; + + // legacy options + /** The journal write concern */ + j?: boolean; + /** The write concern timeout */ + wtimeout?: number; + /** The file sync write concern */ + fsync?: boolean | 1; +} + +export const WRITE_CONCERN_KEYS = ['w', 'wtimeout', 'j', 'journal', 'fsync']; + +/** + * A MongoDB WriteConcern, which describes the level of acknowledgement + * requested from MongoDB for write operations. + * @public + * + * @see https://docs.mongodb.com/manual/reference/write-concern/ + */ +export class WriteConcern { + /** request acknowledgment that the write operation has propagated to a specified number of mongod instances or to mongod instances with specified tags. */ + w?: W; + /** specify a time limit to prevent write operations from blocking indefinitely */ + wtimeout?: number; + /** request acknowledgment that the write operation has been written to the on-disk journal */ + j?: boolean; + /** equivalent to the j option */ + fsync?: boolean | 1; + + /** + * Constructs a WriteConcern from the write concern properties. + * @param w - request acknowledgment that the write operation has propagated to a specified number of mongod instances or to mongod instances with specified tags. + * @param wtimeout - specify a time limit to prevent write operations from blocking indefinitely + * @param j - request acknowledgment that the write operation has been written to the on-disk journal + * @param fsync - equivalent to the j option + */ + constructor(w?: W, wtimeout?: number, j?: boolean, fsync?: boolean | 1) { + if (w != null) { + if (!Number.isNaN(Number(w))) { + this.w = Number(w); + } else { + this.w = w; + } + } + if (wtimeout != null) { + this.wtimeout = wtimeout; + } + if (j != null) { + this.j = j; + } + if (fsync != null) { + this.fsync = fsync; + } + } + + /** Construct a WriteConcern given an options object. */ + static fromOptions( + options?: WriteConcernOptions | WriteConcern | W, + inherit?: WriteConcernOptions | WriteConcern + ): WriteConcern | undefined { + if (options == null) return undefined; + inherit = inherit ?? {}; + let opts: WriteConcernSettings | WriteConcern | undefined; + if (typeof options === 'string' || typeof options === 'number') { + opts = { w: options }; + } else if (options instanceof WriteConcern) { + opts = options; + } else { + opts = options.writeConcern; + } + const parentOpts: WriteConcern | WriteConcernSettings | undefined = + inherit instanceof WriteConcern ? inherit : inherit.writeConcern; + + const { + w = undefined, + wtimeout = undefined, + j = undefined, + fsync = undefined, + journal = undefined, + wtimeoutMS = undefined + } = { + ...parentOpts, + ...opts + }; + if ( + w != null || + wtimeout != null || + wtimeoutMS != null || + j != null || + journal != null || + fsync != null + ) { + return new WriteConcern(w, wtimeout ?? wtimeoutMS, j ?? journal, fsync); + } + return undefined; + } +} diff --git a/ts-ticket-office-service/node_modules/mongodb/tsconfig.json b/ts-ticket-office-service/node_modules/mongodb/tsconfig.json new file mode 100644 index 000000000..a2724c494 --- /dev/null +++ b/ts-ticket-office-service/node_modules/mongodb/tsconfig.json @@ -0,0 +1,40 @@ +{ + "compilerOptions": { + "allowJs": false, + "checkJs": false, + "strict": true, + "alwaysStrict": true, + "target": "ES2019", + "module": "commonJS", + "moduleResolution": "node", + "skipLibCheck": true, + "lib": ["es2020"], + // We don't make use of tslib helpers, all syntax used is supported by target engine + "importHelpers": false, + "noEmitHelpers": true, + // Never emit error filled code + "noEmitOnError": true, + "outDir": "lib", + "importsNotUsedAsValues": "error", + // We want the sourcemaps in a separate file + "inlineSourceMap": false, + "sourceMap": true, + // API-Extractor uses declaration maps to report problems in source, no need to distribute + "declaration": true, + "declarationMap": true, + // we include sources in the release + "inlineSources": false, + // Prevents web types from being suggested by vscode. + "types": ["node"], + "forceConsistentCasingInFileNames": true, + "noImplicitOverride": true, + "noImplicitReturns": true, + // TODO(NODE-3659): Enable useUnknownInCatchVariables and add type assertions or remove unnecessary catch blocks + "useUnknownInCatchVariables": false + }, + "ts-node": { + "transpileOnly": true, + "compiler": "typescript-cached-transpile" + }, + "include": ["src/**/*"] +} diff --git a/ts-ticket-office-service/node_modules/mongodb/yarn.lock b/ts-ticket-office-service/node_modules/mongodb/yarn.lock deleted file mode 100644 index e9d0bed53..000000000 --- a/ts-ticket-office-service/node_modules/mongodb/yarn.lock +++ /dev/null @@ -1,3292 +0,0 @@ -# THIS IS AN AUTOGENERATED FILE. DO NOT EDIT THIS FILE DIRECTLY. -# yarn lockfile v1 - - -JSONStream@^1.0.7, JSONStream@^1.1.1: - version "1.3.1" - resolved "https://registry.yarnpkg.com/JSONStream/-/JSONStream-1.3.1.tgz#707f761e01dae9e16f1bcf93703b78c70966579a" - dependencies: - jsonparse "^1.2.0" - through ">=2.2.7 <3" - -acorn-jsx@^3.0.0: - version "3.0.1" - resolved "https://registry.yarnpkg.com/acorn-jsx/-/acorn-jsx-3.0.1.tgz#afdf9488fb1ecefc8348f6fb22f464e32a58b36b" - dependencies: - acorn "^3.0.4" - -acorn@^3.0.4: - version "3.3.0" - resolved "https://registry.yarnpkg.com/acorn/-/acorn-3.3.0.tgz#45e37fb39e8da3f25baee3ff5369e2bb5f22017a" - -acorn@^5.1.1: - version "5.1.2" - resolved "https://registry.yarnpkg.com/acorn/-/acorn-5.1.2.tgz#911cb53e036807cf0fa778dc5d370fbd864246d7" - -ajv-keywords@^1.0.0: - version "1.5.1" - resolved "https://registry.yarnpkg.com/ajv-keywords/-/ajv-keywords-1.5.1.tgz#314dd0a4b3368fad3dfcdc54ede6171b886daf3c" - -ajv@^4.7.0: - version "4.11.8" - resolved "https://registry.yarnpkg.com/ajv/-/ajv-4.11.8.tgz#82ffb02b29e662ae53bdc20af15947706739c536" - dependencies: - co "^4.6.0" - json-stable-stringify "^1.0.1" - -ajv@^5.1.0: - version "5.2.3" - resolved "https://registry.yarnpkg.com/ajv/-/ajv-5.2.3.tgz#c06f598778c44c6b161abafe3466b81ad1814ed2" - dependencies: - co "^4.6.0" - fast-deep-equal "^1.0.0" - json-schema-traverse "^0.3.0" - json-stable-stringify "^1.0.1" - -align-text@^0.1.1, align-text@^0.1.3: - version "0.1.4" - resolved "https://registry.yarnpkg.com/align-text/-/align-text-0.1.4.tgz#0cd90a561093f35d0a99256c22b7069433fad117" - dependencies: - kind-of "^3.0.2" - longest "^1.0.1" - repeat-string "^1.5.2" - -amdefine@>=0.0.4: - version "1.0.1" - resolved "https://registry.yarnpkg.com/amdefine/-/amdefine-1.0.1.tgz#4a5282ac164729e93619bcfd3ad151f817ce91f5" - -ampersand-events@^2.0.1: - version "2.0.2" - resolved "https://registry.yarnpkg.com/ampersand-events/-/ampersand-events-2.0.2.tgz#f402bc2e18305fabd995dbdcd3b7057bbdd7d347" - dependencies: - ampersand-version "^1.0.2" - lodash "^4.6.1" - -ampersand-state@^5.0.1: - version "5.0.2" - resolved "https://registry.yarnpkg.com/ampersand-state/-/ampersand-state-5.0.2.tgz#16830def866c644ecd21da8c8ba8717aa2b8d23c" - dependencies: - ampersand-events "^2.0.1" - ampersand-version "^1.0.0" - array-next "~0.0.1" - key-tree-store "^1.3.0" - lodash "^4.11.1" - -ampersand-version@^1.0.0, ampersand-version@^1.0.2: - version "1.0.2" - resolved "https://registry.yarnpkg.com/ampersand-version/-/ampersand-version-1.0.2.tgz#ff8f3d4ceac4d32ccd83f6bd6697397f7b59e2c0" - dependencies: - find-root "^0.1.1" - through2 "^0.6.3" - -ansi-escapes@^1.1.0: - version "1.4.0" - resolved "https://registry.yarnpkg.com/ansi-escapes/-/ansi-escapes-1.4.0.tgz#d3a8a83b319aa67793662b13e761c7911422306e" - -ansi-regex@^2.0.0: - version "2.1.1" - resolved "https://registry.yarnpkg.com/ansi-regex/-/ansi-regex-2.1.1.tgz#c3b33ab5ee360d86e0e628f0468ae7ef27d654df" - -ansi-regex@^3.0.0: - version "3.0.0" - resolved "https://registry.yarnpkg.com/ansi-regex/-/ansi-regex-3.0.0.tgz#ed0317c322064f79466c02966bddb605ab37d998" - -ansi-styles@^2.2.1: - version "2.2.1" - resolved "https://registry.yarnpkg.com/ansi-styles/-/ansi-styles-2.2.1.tgz#b432dd3358b634cf75e1e4664368240533c1ddbe" - -ansi@^0.3.0, ansi@~0.3.0: - version "0.3.1" - resolved "https://registry.yarnpkg.com/ansi/-/ansi-0.3.1.tgz#0c42d4fb17160d5a9af1e484bace1c66922c1b21" - -append-transform@^0.4.0: - version "0.4.0" - resolved "https://registry.yarnpkg.com/append-transform/-/append-transform-0.4.0.tgz#d76ebf8ca94d276e247a36bad44a4b74ab611991" - dependencies: - default-require-extensions "^1.0.0" - -archy@^1.0.0: - version "1.0.0" - resolved "https://registry.yarnpkg.com/archy/-/archy-1.0.0.tgz#f9c8c13757cc1dd7bc379ac77b2c62a5c2868c40" - -are-we-there-yet@~1.0.0: - version "1.0.6" - resolved "https://registry.yarnpkg.com/are-we-there-yet/-/are-we-there-yet-1.0.6.tgz#a2d28c93102aa6cc96245a26cb954de06ec53f0c" - dependencies: - delegates "^1.0.0" - readable-stream "^2.0.0 || ^1.1.13" - -argparse@^1.0.7: - version "1.0.9" - resolved "https://registry.yarnpkg.com/argparse/-/argparse-1.0.9.tgz#73d83bc263f86e97f8cc4f6bae1b0e90a7d22c86" - dependencies: - sprintf-js "~1.0.2" - -arr-diff@^2.0.0: - version "2.0.0" - resolved "https://registry.yarnpkg.com/arr-diff/-/arr-diff-2.0.0.tgz#8f3b827f955a8bd669697e4a4256ac3ceae356cf" - dependencies: - arr-flatten "^1.0.1" - -arr-flatten@^1.0.1: - version "1.1.0" - resolved "https://registry.yarnpkg.com/arr-flatten/-/arr-flatten-1.1.0.tgz#36048bbff4e7b47e136644316c99669ea5ae91f1" - -array-find-index@^1.0.1: - version "1.0.2" - resolved "https://registry.yarnpkg.com/array-find-index/-/array-find-index-1.0.2.tgz#df010aa1287e164bbda6f9723b0a96a1ec4187a1" - -array-next@~0.0.1: - version "0.0.1" - resolved "https://registry.yarnpkg.com/array-next/-/array-next-0.0.1.tgz#e5e4660a4c27fda8151ff7764275d00900062be1" - -array-union@^1.0.1: - version "1.0.2" - resolved "https://registry.yarnpkg.com/array-union/-/array-union-1.0.2.tgz#9a34410e4f4e3da23dea375be5be70f24778ec39" - dependencies: - array-uniq "^1.0.1" - -array-uniq@^1.0.1: - version "1.0.3" - resolved "https://registry.yarnpkg.com/array-uniq/-/array-uniq-1.0.3.tgz#af6ac877a25cc7f74e058894753858dfdb24fdb6" - -array-unique@^0.2.1: - version "0.2.1" - resolved "https://registry.yarnpkg.com/array-unique/-/array-unique-0.2.1.tgz#a1d97ccafcbc2625cc70fadceb36a50c58b01a53" - -arrify@^1.0.0, arrify@^1.0.1: - version "1.0.1" - resolved "https://registry.yarnpkg.com/arrify/-/arrify-1.0.1.tgz#898508da2226f380df904728456849c1501a4b0d" - -asn1@~0.2.3: - version "0.2.3" - resolved "https://registry.yarnpkg.com/asn1/-/asn1-0.2.3.tgz#dac8787713c9966849fc8180777ebe9c1ddf3b86" - -assert-plus@1.0.0, assert-plus@^1.0.0: - version "1.0.0" - resolved "https://registry.yarnpkg.com/assert-plus/-/assert-plus-1.0.0.tgz#f12e0f3c5d77b0b1cdd9146942e4e96c1e4dd525" - -assert-plus@^0.2.0: - version "0.2.0" - resolved "https://registry.yarnpkg.com/assert-plus/-/assert-plus-0.2.0.tgz#d74e1b87e7affc0db8aadb7021f3fe48101ab234" - -async@^1.4.0, async@^1.4.2, async@^1.5.0, async@~1.5.0: - version "1.5.2" - resolved "https://registry.yarnpkg.com/async/-/async-1.5.2.tgz#ec6a61ae56480c0c3cb241c95618e20892f9672a" - -async@~0.2.6: - version "0.2.10" - resolved "https://registry.yarnpkg.com/async/-/async-0.2.10.tgz#b6bbe0b0674b9d719708ca38de8c237cb526c3d1" - -async@~1.4.0: - version "1.4.2" - resolved "https://registry.yarnpkg.com/async/-/async-1.4.2.tgz#6c9edcb11ced4f0dd2f2d40db0d49a109c088aab" - -asynckit@^0.4.0: - version "0.4.0" - resolved "https://registry.yarnpkg.com/asynckit/-/asynckit-0.4.0.tgz#c79ed97f7f34cb8f2ba1bc9790bcc366474b4b79" - -aws-sign2@~0.6.0: - version "0.6.0" - resolved "https://registry.yarnpkg.com/aws-sign2/-/aws-sign2-0.6.0.tgz#14342dd38dbcc94d0e5b87d763cd63612c0e794f" - -aws-sign2@~0.7.0: - version "0.7.0" - resolved "https://registry.yarnpkg.com/aws-sign2/-/aws-sign2-0.7.0.tgz#b46e890934a9591f2d2f6f86d7e6a9f1b3fe76a8" - -aws4@^1.2.1, aws4@^1.6.0: - version "1.6.0" - resolved "https://registry.yarnpkg.com/aws4/-/aws4-1.6.0.tgz#83ef5ca860b2b32e4a0deedee8c771b9db57471e" - -babel-code-frame@^6.16.0, babel-code-frame@^6.26.0: - version "6.26.0" - resolved "https://registry.yarnpkg.com/babel-code-frame/-/babel-code-frame-6.26.0.tgz#63fd43f7dc1e3bb7ce35947db8fe369a3f58c74b" - dependencies: - chalk "^1.1.3" - esutils "^2.0.2" - js-tokens "^3.0.2" - -babel-core@^6.2.1, babel-core@^6.25.0, babel-core@^6.26.0: - version "6.26.0" - resolved "https://registry.yarnpkg.com/babel-core/-/babel-core-6.26.0.tgz#af32f78b31a6fcef119c87b0fd8d9753f03a0bb8" - dependencies: - babel-code-frame "^6.26.0" - babel-generator "^6.26.0" - babel-helpers "^6.24.1" - babel-messages "^6.23.0" - babel-register "^6.26.0" - babel-runtime "^6.26.0" - babel-template "^6.26.0" - babel-traverse "^6.26.0" - babel-types "^6.26.0" - babylon "^6.18.0" - convert-source-map "^1.5.0" - debug "^2.6.8" - json5 "^0.5.1" - lodash "^4.17.4" - minimatch "^3.0.4" - path-is-absolute "^1.0.1" - private "^0.1.7" - slash "^1.0.0" - source-map "^0.5.6" - -babel-generator@^6.18.0, babel-generator@^6.26.0: - version "6.26.0" - resolved "https://registry.yarnpkg.com/babel-generator/-/babel-generator-6.26.0.tgz#ac1ae20070b79f6e3ca1d3269613053774f20dc5" - dependencies: - babel-messages "^6.23.0" - babel-runtime "^6.26.0" - babel-types "^6.26.0" - detect-indent "^4.0.0" - jsesc "^1.3.0" - lodash "^4.17.4" - source-map "^0.5.6" - trim-right "^1.0.1" - -babel-helpers@^6.24.1: - version "6.24.1" - resolved "https://registry.yarnpkg.com/babel-helpers/-/babel-helpers-6.24.1.tgz#3471de9caec388e5c850e597e58a26ddf37602b2" - dependencies: - babel-runtime "^6.22.0" - babel-template "^6.24.1" - -babel-messages@^6.23.0: - version "6.23.0" - resolved "https://registry.yarnpkg.com/babel-messages/-/babel-messages-6.23.0.tgz#f3cdf4703858035b2a2951c6ec5edf6c62f2630e" - dependencies: - babel-runtime "^6.22.0" - -babel-polyfill@^6.2.0, babel-polyfill@^6.23.0: - version "6.26.0" - resolved "https://registry.yarnpkg.com/babel-polyfill/-/babel-polyfill-6.26.0.tgz#379937abc67d7895970adc621f284cd966cf2153" - dependencies: - babel-runtime "^6.26.0" - core-js "^2.5.0" - regenerator-runtime "^0.10.5" - -babel-register@^6.26.0: - version "6.26.0" - resolved "https://registry.yarnpkg.com/babel-register/-/babel-register-6.26.0.tgz#6ed021173e2fcb486d7acb45c6009a856f647071" - dependencies: - babel-core "^6.26.0" - babel-runtime "^6.26.0" - core-js "^2.5.0" - home-or-tmp "^2.0.0" - lodash "^4.17.4" - mkdirp "^0.5.1" - source-map-support "^0.4.15" - -babel-runtime@^6.22.0, babel-runtime@^6.26.0: - version "6.26.0" - resolved "https://registry.yarnpkg.com/babel-runtime/-/babel-runtime-6.26.0.tgz#965c7058668e82b55d7bfe04ff2337bc8b5647fe" - dependencies: - core-js "^2.4.0" - regenerator-runtime "^0.11.0" - -babel-template@^6.16.0, babel-template@^6.24.1, babel-template@^6.26.0: - version "6.26.0" - resolved "https://registry.yarnpkg.com/babel-template/-/babel-template-6.26.0.tgz#de03e2d16396b069f46dd9fff8521fb1a0e35e02" - dependencies: - babel-runtime "^6.26.0" - babel-traverse "^6.26.0" - babel-types "^6.26.0" - babylon "^6.18.0" - lodash "^4.17.4" - -babel-traverse@^6.18.0, babel-traverse@^6.26.0: - version "6.26.0" - resolved "https://registry.yarnpkg.com/babel-traverse/-/babel-traverse-6.26.0.tgz#46a9cbd7edcc62c8e5c064e2d2d8d0f4035766ee" - dependencies: - babel-code-frame "^6.26.0" - babel-messages "^6.23.0" - babel-runtime "^6.26.0" - babel-types "^6.26.0" - babylon "^6.18.0" - debug "^2.6.8" - globals "^9.18.0" - invariant "^2.2.2" - lodash "^4.17.4" - -babel-types@^6.18.0, babel-types@^6.26.0: - version "6.26.0" - resolved "https://registry.yarnpkg.com/babel-types/-/babel-types-6.26.0.tgz#a3b073f94ab49eb6fa55cd65227a334380632497" - dependencies: - babel-runtime "^6.26.0" - esutils "^2.0.2" - lodash "^4.17.4" - to-fast-properties "^1.0.3" - -babylon@^6.18.0: - version "6.18.0" - resolved "https://registry.yarnpkg.com/babylon/-/babylon-6.18.0.tgz#af2f3b88fa6f5c1e4c634d1a0f8eac4f55b395e3" - -balanced-match@^1.0.0: - version "1.0.0" - resolved "https://registry.yarnpkg.com/balanced-match/-/balanced-match-1.0.0.tgz#89b4d199ab2bee49de164ea02b89ce462d71b767" - -bcrypt-pbkdf@^1.0.0: - version "1.0.1" - resolved "https://registry.yarnpkg.com/bcrypt-pbkdf/-/bcrypt-pbkdf-1.0.1.tgz#63bc5dcb61331b92bc05fd528953c33462a06f8d" - dependencies: - tweetnacl "^0.14.3" - -betterbenchmarks@^0.1.0: - version "0.1.0" - resolved "https://registry.yarnpkg.com/betterbenchmarks/-/betterbenchmarks-0.1.0.tgz#c07ac937e215d3d7a91a460eefb039b7c9002e43" - dependencies: - babel-core "^6.2.1" - babel-polyfill "^6.2.0" - cli-table "^0.3.1" - co "^4.6.0" - colors "^1.1.2" - fast-stats "0.0.3" - table "^3.7.4" - -"binary@>= 0.3.0 < 1": - version "0.3.0" - resolved "https://registry.yarnpkg.com/binary/-/binary-0.3.0.tgz#9f60553bc5ce8c3386f3b553cff47462adecaa79" - dependencies: - buffers "~0.1.1" - chainsaw "~0.1.0" - -block-stream@*: - version "0.0.9" - resolved "https://registry.yarnpkg.com/block-stream/-/block-stream-0.0.9.tgz#13ebfe778a03205cfe03751481ebb4b3300c126a" - dependencies: - inherits "~2.0.0" - -bluebird@3.4.6: - version "3.4.6" - resolved "https://registry.yarnpkg.com/bluebird/-/bluebird-3.4.6.tgz#01da8d821d87813d158967e743d5fe6c62cf8c0f" - -bluebird@^3.5.0: - version "3.5.1" - resolved "https://registry.yarnpkg.com/bluebird/-/bluebird-3.5.1.tgz#d9551f9de98f1fcda1e683d17ee91a0602ee2eb9" - -bluebird@~2.9.34: - version "2.9.34" - resolved "https://registry.yarnpkg.com/bluebird/-/bluebird-2.9.34.tgz#2f7b4ec80216328a9fddebdf69c8d4942feff7d8" - -boolbase@~1.0.0: - version "1.0.0" - resolved "https://registry.yarnpkg.com/boolbase/-/boolbase-1.0.0.tgz#68dff5fbe60c51eb37725ea9e3ed310dcc1e776e" - -boom@2.x.x: - version "2.10.1" - resolved "https://registry.yarnpkg.com/boom/-/boom-2.10.1.tgz#39c8918ceff5799f83f9492a848f625add0c766f" - dependencies: - hoek "2.x.x" - -boom@4.x.x: - version "4.3.1" - resolved "https://registry.yarnpkg.com/boom/-/boom-4.3.1.tgz#4f8a3005cb4a7e3889f749030fd25b96e01d2e31" - dependencies: - hoek "4.x.x" - -boom@5.x.x: - version "5.2.0" - resolved "https://registry.yarnpkg.com/boom/-/boom-5.2.0.tgz#5dd9da6ee3a5f302077436290cb717d3f4a54e02" - dependencies: - hoek "4.x.x" - -brace-expansion@^1.1.7: - version "1.1.8" - resolved "https://registry.yarnpkg.com/brace-expansion/-/brace-expansion-1.1.8.tgz#c07b211c7c952ec1f8efd51a77ef0d1d3990a292" - dependencies: - balanced-match "^1.0.0" - concat-map "0.0.1" - -braces@^1.8.2: - version "1.8.5" - resolved "https://registry.yarnpkg.com/braces/-/braces-1.8.5.tgz#ba77962e12dff969d6b76711e914b737857bf6a7" - dependencies: - expand-range "^1.8.1" - preserve "^0.2.0" - repeat-element "^1.1.2" - -bson@^0.5.2: - version "0.5.7" - resolved "https://registry.yarnpkg.com/bson/-/bson-0.5.7.tgz#0d11fe0936c1fee029e11f7063f5d0ab2422ea3e" - -bson@latest, bson@~1.0.4: - version "1.0.4" - resolved "https://registry.yarnpkg.com/bson/-/bson-1.0.4.tgz#93c10d39eaa5b58415cbc4052f3e53e562b0b72c" - -buffer-shims@~1.0.0: - version "1.0.0" - resolved "https://registry.yarnpkg.com/buffer-shims/-/buffer-shims-1.0.0.tgz#9978ce317388c649ad8793028c3477ef044a8b51" - -buffers@~0.1.1: - version "0.1.1" - resolved "https://registry.yarnpkg.com/buffers/-/buffers-0.1.1.tgz#b24579c3bed4d6d396aeee6d9a8ae7f5482ab7bb" - -builtin-modules@^1.0.0: - version "1.1.1" - resolved "https://registry.yarnpkg.com/builtin-modules/-/builtin-modules-1.1.1.tgz#270f076c5a72c02f5b65a47df94c5fe3a278892f" - -caching-transform@^1.0.0: - version "1.0.1" - resolved "https://registry.yarnpkg.com/caching-transform/-/caching-transform-1.0.1.tgz#6dbdb2f20f8d8fbce79f3e94e9d1742dcdf5c0a1" - dependencies: - md5-hex "^1.2.0" - mkdirp "^0.5.1" - write-file-atomic "^1.1.4" - -caller-path@^0.1.0: - version "0.1.0" - resolved "https://registry.yarnpkg.com/caller-path/-/caller-path-0.1.0.tgz#94085ef63581ecd3daa92444a8fe94e82577751f" - dependencies: - callsites "^0.2.0" - -callsites@^0.2.0: - version "0.2.0" - resolved "https://registry.yarnpkg.com/callsites/-/callsites-0.2.0.tgz#afab96262910a7f33c19a5775825c69f34e350ca" - -camelcase-keys@^2.0.0: - version "2.1.0" - resolved "https://registry.yarnpkg.com/camelcase-keys/-/camelcase-keys-2.1.0.tgz#308beeaffdf28119051efa1d932213c91b8f92e7" - dependencies: - camelcase "^2.0.0" - map-obj "^1.0.0" - -camelcase@^1.0.2: - version "1.2.1" - resolved "https://registry.yarnpkg.com/camelcase/-/camelcase-1.2.1.tgz#9bb5304d2e0b56698b2c758b08a3eaa9daa58a39" - -camelcase@^2.0.0: - version "2.1.1" - resolved "https://registry.yarnpkg.com/camelcase/-/camelcase-2.1.1.tgz#7c1d16d679a1bbe59ca02cacecfb011e201f5a1f" - -camelcase@^3.0.0: - version "3.0.0" - resolved "https://registry.yarnpkg.com/camelcase/-/camelcase-3.0.0.tgz#32fc4b9fcdaf845fcdf7e73bb97cac2261f0ab0a" - -caseless@~0.11.0: - version "0.11.0" - resolved "https://registry.yarnpkg.com/caseless/-/caseless-0.11.0.tgz#715b96ea9841593cc33067923f5ec60ebda4f7d7" - -caseless@~0.12.0: - version "0.12.0" - resolved "https://registry.yarnpkg.com/caseless/-/caseless-0.12.0.tgz#1b681c21ff84033c826543090689420d187151dc" - -catharsis@~0.8.7: - version "0.8.9" - resolved "https://registry.yarnpkg.com/catharsis/-/catharsis-0.8.9.tgz#98cc890ca652dd2ef0e70b37925310ff9e90fc8b" - dependencies: - underscore-contrib "~0.3.0" - -center-align@^0.1.1: - version "0.1.3" - resolved "https://registry.yarnpkg.com/center-align/-/center-align-0.1.3.tgz#aa0d32629b6ee972200411cbd4461c907bc2b7ad" - dependencies: - align-text "^0.1.3" - lazy-cache "^1.0.3" - -chainsaw@~0.1.0: - version "0.1.0" - resolved "https://registry.yarnpkg.com/chainsaw/-/chainsaw-0.1.0.tgz#5eab50b28afe58074d0d58291388828b5e5fbc98" - dependencies: - traverse ">=0.3.0 <0.4" - -chalk@^1.0.0, chalk@^1.1.1, chalk@^1.1.3: - version "1.1.3" - resolved "https://registry.yarnpkg.com/chalk/-/chalk-1.1.3.tgz#a8115c55e4a702fe4d150abd3872822a7e09fc98" - dependencies: - ansi-styles "^2.2.1" - escape-string-regexp "^1.0.2" - has-ansi "^2.0.0" - strip-ansi "^3.0.0" - supports-color "^2.0.0" - -cheerio@^0.19.0: - version "0.19.0" - resolved "https://registry.yarnpkg.com/cheerio/-/cheerio-0.19.0.tgz#772e7015f2ee29965096d71ea4175b75ab354925" - dependencies: - css-select "~1.0.0" - dom-serializer "~0.1.0" - entities "~1.1.1" - htmlparser2 "~3.8.1" - lodash "^3.2.0" - -circular-json@^0.3.1: - version "0.3.3" - resolved "https://registry.yarnpkg.com/circular-json/-/circular-json-0.3.3.tgz#815c99ea84f6809529d2f45791bdf82711352d66" - -cli-cursor@^1.0.1: - version "1.0.2" - resolved "https://registry.yarnpkg.com/cli-cursor/-/cli-cursor-1.0.2.tgz#64da3f7d56a54412e59794bd62dc35295e8f2987" - dependencies: - restore-cursor "^1.0.1" - -cli-table@^0.3.1: - version "0.3.1" - resolved "https://registry.yarnpkg.com/cli-table/-/cli-table-0.3.1.tgz#f53b05266a8b1a0b934b3d0821e6e2dc5914ae23" - dependencies: - colors "1.0.3" - -cli-width@^2.0.0: - version "2.2.0" - resolved "https://registry.yarnpkg.com/cli-width/-/cli-width-2.2.0.tgz#ff19ede8a9a5e579324147b0c11f0fbcbabed639" - -cliui@^2.1.0: - version "2.1.0" - resolved "https://registry.yarnpkg.com/cliui/-/cliui-2.1.0.tgz#4b475760ff80264c762c3a1719032e91c7fea0d1" - dependencies: - center-align "^0.1.1" - right-align "^0.1.1" - wordwrap "0.0.2" - -cliui@^3.2.0: - version "3.2.0" - resolved "https://registry.yarnpkg.com/cliui/-/cliui-3.2.0.tgz#120601537a916d29940f934da3b48d585a39213d" - dependencies: - string-width "^1.0.1" - strip-ansi "^3.0.1" - wrap-ansi "^2.0.0" - -co@4.6.0, co@^4.6.0: - version "4.6.0" - resolved "https://registry.yarnpkg.com/co/-/co-4.6.0.tgz#6ea6bdf3d853ae54ccb8e47bfa0bf3f9031fb184" - -code-point-at@^1.0.0: - version "1.1.0" - resolved "https://registry.yarnpkg.com/code-point-at/-/code-point-at-1.1.0.tgz#0d070b4d043a5bea33a2f1a40e2edb3d9a4ccf77" - -colors@1.0.3: - version "1.0.3" - resolved "https://registry.yarnpkg.com/colors/-/colors-1.0.3.tgz#0433f44d809680fdeb60ed260f1b0c262e82a40b" - -colors@^1.1.2: - version "1.1.2" - resolved "https://registry.yarnpkg.com/colors/-/colors-1.1.2.tgz#168a4701756b6a7f51a12ce0c97bfa28c084ed63" - -combined-stream@^1.0.5, combined-stream@~1.0.5: - version "1.0.5" - resolved "https://registry.yarnpkg.com/combined-stream/-/combined-stream-1.0.5.tgz#938370a57b4a51dea2c77c15d5c5fdf895164009" - dependencies: - delayed-stream "~1.0.0" - -commander@^2.9.0: - version "2.11.0" - resolved "https://registry.yarnpkg.com/commander/-/commander-2.11.0.tgz#157152fd1e7a6c8d98a5b715cf376df928004563" - -commondir@^1.0.1: - version "1.0.1" - resolved "https://registry.yarnpkg.com/commondir/-/commondir-1.0.1.tgz#ddd800da0c66127393cca5950ea968a3aaf1253b" - -concat-map@0.0.1: - version "0.0.1" - resolved "https://registry.yarnpkg.com/concat-map/-/concat-map-0.0.1.tgz#d8a96bd77fd68df7793a73036a3ba0d5405d477b" - -concat-stream@^1.5.2: - version "1.6.0" - resolved "https://registry.yarnpkg.com/concat-stream/-/concat-stream-1.6.0.tgz#0aac662fd52be78964d5532f694784e70110acf7" - dependencies: - inherits "^2.0.3" - readable-stream "^2.2.2" - typedarray "^0.0.6" - -convert-source-map@^1.3.0, convert-source-map@^1.5.0: - version "1.5.0" - resolved "https://registry.yarnpkg.com/convert-source-map/-/convert-source-map-1.5.0.tgz#9acd70851c6d5dfdd93d9282e5edf94a03ff46b5" - -core-js@^2.4.0, core-js@^2.5.0: - version "2.5.1" - resolved "https://registry.yarnpkg.com/core-js/-/core-js-2.5.1.tgz#ae6874dc66937789b80754ff5428df66819ca50b" - -core-util-is@1.0.2, core-util-is@~1.0.0: - version "1.0.2" - resolved "https://registry.yarnpkg.com/core-util-is/-/core-util-is-1.0.2.tgz#b5fd54220aa2bc5ab57aab7140c940754503c1a7" - -coveralls@^2.11.6: - version "2.13.3" - resolved "https://registry.yarnpkg.com/coveralls/-/coveralls-2.13.3.tgz#9ad7c2ae527417f361e8b626483f48ee92dd2bc7" - dependencies: - js-yaml "3.6.1" - lcov-parse "0.0.10" - log-driver "1.2.5" - minimist "1.2.0" - request "2.79.0" - -cross-spawn@^4: - version "4.0.2" - resolved "https://registry.yarnpkg.com/cross-spawn/-/cross-spawn-4.0.2.tgz#7b9247621c23adfdd3856004a823cbe397424d41" - dependencies: - lru-cache "^4.0.1" - which "^1.2.9" - -cryptiles@2.x.x: - version "2.0.5" - resolved "https://registry.yarnpkg.com/cryptiles/-/cryptiles-2.0.5.tgz#3bdfecdc608147c1c67202fa291e7dca59eaa3b8" - dependencies: - boom "2.x.x" - -cryptiles@3.x.x: - version "3.1.2" - resolved "https://registry.yarnpkg.com/cryptiles/-/cryptiles-3.1.2.tgz#a89fbb220f5ce25ec56e8c4aa8a4fd7b5b0d29fe" - dependencies: - boom "5.x.x" - -css-select@~1.0.0: - version "1.0.0" - resolved "https://registry.yarnpkg.com/css-select/-/css-select-1.0.0.tgz#b1121ca51848dd264e2244d058cee254deeb44b0" - dependencies: - boolbase "~1.0.0" - css-what "1.0" - domutils "1.4" - nth-check "~1.0.0" - -css-what@1.0: - version "1.0.0" - resolved "https://registry.yarnpkg.com/css-what/-/css-what-1.0.0.tgz#d7cc2df45180666f99d2b14462639469e00f736c" - -currently-unhandled@^0.4.1: - version "0.4.1" - resolved "https://registry.yarnpkg.com/currently-unhandled/-/currently-unhandled-0.4.1.tgz#988df33feab191ef799a61369dd76c17adf957ea" - dependencies: - array-find-index "^1.0.1" - -d@1: - version "1.0.0" - resolved "https://registry.yarnpkg.com/d/-/d-1.0.0.tgz#754bb5bfe55451da69a58b94d45f4c5b0462d58f" - dependencies: - es5-ext "^0.10.9" - -dashdash@^1.12.0: - version "1.14.1" - resolved "https://registry.yarnpkg.com/dashdash/-/dashdash-1.14.1.tgz#853cfa0f7cbe2fed5de20326b8dd581035f6e2f0" - dependencies: - assert-plus "^1.0.0" - -debug@^2.1.1, debug@^2.1.3, debug@^2.2.0, debug@^2.6.3, debug@^2.6.8: - version "2.6.9" - resolved "https://registry.yarnpkg.com/debug/-/debug-2.6.9.tgz#5d128515df134ff327e90a4c93f4e077a536341f" - dependencies: - ms "2.0.0" - -debug@~2.2.0: - version "2.2.0" - resolved "https://registry.yarnpkg.com/debug/-/debug-2.2.0.tgz#f87057e995b1a1f6ae6a4960664137bc56f039da" - dependencies: - ms "0.7.1" - -decamelize@^1.0.0, decamelize@^1.1.1, decamelize@^1.1.2: - version "1.2.0" - resolved "https://registry.yarnpkg.com/decamelize/-/decamelize-1.2.0.tgz#f6534d15148269b20352e7bee26f501f9a191290" - -deep-is@~0.1.3: - version "0.1.3" - resolved "https://registry.yarnpkg.com/deep-is/-/deep-is-0.1.3.tgz#b369d6fb5dbc13eecf524f91b070feedc357cf34" - -default-require-extensions@^1.0.0: - version "1.0.0" - resolved "https://registry.yarnpkg.com/default-require-extensions/-/default-require-extensions-1.0.0.tgz#f37ea15d3e13ffd9b437d33e1a75b5fb97874cb8" - dependencies: - strip-bom "^2.0.0" - -del@^2.0.2: - version "2.2.2" - resolved "https://registry.yarnpkg.com/del/-/del-2.2.2.tgz#c12c981d067846c84bcaf862cff930d907ffd1a8" - dependencies: - globby "^5.0.0" - is-path-cwd "^1.0.0" - is-path-in-cwd "^1.0.0" - object-assign "^4.0.1" - pify "^2.0.0" - pinkie-promise "^2.0.0" - rimraf "^2.2.8" - -delayed-stream@~1.0.0: - version "1.0.0" - resolved "https://registry.yarnpkg.com/delayed-stream/-/delayed-stream-1.0.0.tgz#df3ae199acadfb7d440aaae0b29e2272b24ec619" - -delegates@^1.0.0: - version "1.0.0" - resolved "https://registry.yarnpkg.com/delegates/-/delegates-1.0.0.tgz#84c6e159b81904fdca59a0ef44cd870d31250f9a" - -detect-indent@^4.0.0: - version "4.0.0" - resolved "https://registry.yarnpkg.com/detect-indent/-/detect-indent-4.0.0.tgz#f76d064352cdf43a1cb6ce619c4ee3a9475de208" - dependencies: - repeating "^2.0.0" - -docopt@~0.6.2: - version "0.6.2" - resolved "https://registry.yarnpkg.com/docopt/-/docopt-0.6.2.tgz#b28e9e2220da5ec49f7ea5bb24a47787405eeb11" - -doctrine@^2.0.0: - version "2.0.0" - resolved "https://registry.yarnpkg.com/doctrine/-/doctrine-2.0.0.tgz#c73d8d2909d22291e1a007a395804da8b665fe63" - dependencies: - esutils "^2.0.2" - isarray "^1.0.0" - -dom-serializer@0, dom-serializer@~0.1.0: - version "0.1.0" - resolved "https://registry.yarnpkg.com/dom-serializer/-/dom-serializer-0.1.0.tgz#073c697546ce0780ce23be4a28e293e40bc30c82" - dependencies: - domelementtype "~1.1.1" - entities "~1.1.1" - -domelementtype@1: - version "1.3.0" - resolved "https://registry.yarnpkg.com/domelementtype/-/domelementtype-1.3.0.tgz#b17aed82e8ab59e52dd9c19b1756e0fc187204c2" - -domelementtype@~1.1.1: - version "1.1.3" - resolved "https://registry.yarnpkg.com/domelementtype/-/domelementtype-1.1.3.tgz#bd28773e2642881aec51544924299c5cd822185b" - -domhandler@2.3: - version "2.3.0" - resolved "https://registry.yarnpkg.com/domhandler/-/domhandler-2.3.0.tgz#2de59a0822d5027fabff6f032c2b25a2a8abe738" - dependencies: - domelementtype "1" - -domutils@1.4: - version "1.4.3" - resolved "https://registry.yarnpkg.com/domutils/-/domutils-1.4.3.tgz#0865513796c6b306031850e175516baf80b72a6f" - dependencies: - domelementtype "1" - -domutils@1.5: - version "1.5.1" - resolved "https://registry.yarnpkg.com/domutils/-/domutils-1.5.1.tgz#dcd8488a26f563d61079e48c9f7b7e32373682cf" - dependencies: - dom-serializer "0" - domelementtype "1" - -downcache@0.0.8: - version "0.0.8" - resolved "https://registry.yarnpkg.com/downcache/-/downcache-0.0.8.tgz#332320dde5806ea55d2e6d2ea674990bda4e8b75" - dependencies: - extend "2.0.x" - graceful-fs "2.0.3" - limiter "1.0.x" - mkdirp "~0.3.5" - npmlog "1.0.0" - request "^2.34.0" - -duplexer@~0.1.1: - version "0.1.1" - resolved "https://registry.yarnpkg.com/duplexer/-/duplexer-0.1.1.tgz#ace6ff808c1ce66b57d1ebf97977acb02334cfc1" - -ecc-jsbn@~0.1.1: - version "0.1.1" - resolved "https://registry.yarnpkg.com/ecc-jsbn/-/ecc-jsbn-0.1.1.tgz#0fc73a9ed5f0d53c38193398523ef7e543777505" - dependencies: - jsbn "~0.1.0" - -entities@1.0: - version "1.0.0" - resolved "https://registry.yarnpkg.com/entities/-/entities-1.0.0.tgz#b2987aa3821347fcde642b24fdfc9e4fb712bf26" - -entities@~1.1.1: - version "1.1.1" - resolved "https://registry.yarnpkg.com/entities/-/entities-1.1.1.tgz#6e5c2d0a5621b5dadaecef80b90edfb5cd7772f0" - -errno@^0.1.4: - version "0.1.4" - resolved "https://registry.yarnpkg.com/errno/-/errno-0.1.4.tgz#b896e23a9e5e8ba33871fc996abd3635fc9a1c7d" - dependencies: - prr "~0.0.0" - -error-ex@^1.2.0: - version "1.3.1" - resolved "https://registry.yarnpkg.com/error-ex/-/error-ex-1.3.1.tgz#f855a86ce61adc4e8621c3cda21e7a7612c3a8dc" - dependencies: - is-arrayish "^0.2.1" - -es5-ext@^0.10.14, es5-ext@^0.10.9, es5-ext@~0.10.14: - version "0.10.31" - resolved "https://registry.yarnpkg.com/es5-ext/-/es5-ext-0.10.31.tgz#7bb938c95a7f1b9f728092dc09c41edcc398eefe" - dependencies: - es6-iterator "~2.0.1" - es6-symbol "~3.1.1" - -es6-iterator@^2.0.1, es6-iterator@~2.0.1: - version "2.0.1" - resolved "https://registry.yarnpkg.com/es6-iterator/-/es6-iterator-2.0.1.tgz#8e319c9f0453bf575d374940a655920e59ca5512" - dependencies: - d "1" - es5-ext "^0.10.14" - es6-symbol "^3.1" - -es6-map@^0.1.3: - version "0.1.5" - resolved "https://registry.yarnpkg.com/es6-map/-/es6-map-0.1.5.tgz#9136e0503dcc06a301690f0bb14ff4e364e949f0" - dependencies: - d "1" - es5-ext "~0.10.14" - es6-iterator "~2.0.1" - es6-set "~0.1.5" - es6-symbol "~3.1.1" - event-emitter "~0.3.5" - -es6-promise@3.2.1: - version "3.2.1" - resolved "https://registry.yarnpkg.com/es6-promise/-/es6-promise-3.2.1.tgz#ec56233868032909207170c39448e24449dd1fc4" - -es6-set@~0.1.5: - version "0.1.5" - resolved "https://registry.yarnpkg.com/es6-set/-/es6-set-0.1.5.tgz#d2b3ec5d4d800ced818db538d28974db0a73ccb1" - dependencies: - d "1" - es5-ext "~0.10.14" - es6-iterator "~2.0.1" - es6-symbol "3.1.1" - event-emitter "~0.3.5" - -es6-symbol@3.1.1, es6-symbol@^3.1, es6-symbol@^3.1.1, es6-symbol@~3.1.1: - version "3.1.1" - resolved "https://registry.yarnpkg.com/es6-symbol/-/es6-symbol-3.1.1.tgz#bf00ef4fdab6ba1b46ecb7b629b4c7ed5715cc77" - dependencies: - d "1" - es5-ext "~0.10.14" - -es6-weak-map@^2.0.1: - version "2.0.2" - resolved "https://registry.yarnpkg.com/es6-weak-map/-/es6-weak-map-2.0.2.tgz#5e3ab32251ffd1538a1f8e5ffa1357772f92d96f" - dependencies: - d "1" - es5-ext "^0.10.14" - es6-iterator "^2.0.1" - es6-symbol "^3.1.1" - -escape-string-regexp@^1.0.2, escape-string-regexp@^1.0.5, escape-string-regexp@~1.0.3: - version "1.0.5" - resolved "https://registry.yarnpkg.com/escape-string-regexp/-/escape-string-regexp-1.0.5.tgz#1b61c0562190a8dff6ae3bb2cf0200ca130b86d4" - -escodegen@1.1.x: - version "1.1.0" - resolved "https://registry.yarnpkg.com/escodegen/-/escodegen-1.1.0.tgz#c663923f6e20aad48d0c0fa49f31c6d4f49360cf" - dependencies: - esprima "~1.0.4" - estraverse "~1.5.0" - esutils "~1.0.0" - optionalDependencies: - source-map "~0.1.30" - -escope@^3.6.0: - version "3.6.0" - resolved "https://registry.yarnpkg.com/escope/-/escope-3.6.0.tgz#e01975e812781a163a6dadfdd80398dc64c889c3" - dependencies: - es6-map "^0.1.3" - es6-weak-map "^2.0.1" - esrecurse "^4.1.0" - estraverse "^4.1.1" - -eslint@^3.8.1: - version "3.19.0" - resolved "https://registry.yarnpkg.com/eslint/-/eslint-3.19.0.tgz#c8fc6201c7f40dd08941b87c085767386a679acc" - dependencies: - babel-code-frame "^6.16.0" - chalk "^1.1.3" - concat-stream "^1.5.2" - debug "^2.1.1" - doctrine "^2.0.0" - escope "^3.6.0" - espree "^3.4.0" - esquery "^1.0.0" - estraverse "^4.2.0" - esutils "^2.0.2" - file-entry-cache "^2.0.0" - glob "^7.0.3" - globals "^9.14.0" - ignore "^3.2.0" - imurmurhash "^0.1.4" - inquirer "^0.12.0" - is-my-json-valid "^2.10.0" - is-resolvable "^1.0.0" - js-yaml "^3.5.1" - json-stable-stringify "^1.0.0" - levn "^0.3.0" - lodash "^4.0.0" - mkdirp "^0.5.0" - natural-compare "^1.4.0" - optionator "^0.8.2" - path-is-inside "^1.0.1" - pluralize "^1.2.1" - progress "^1.1.8" - require-uncached "^1.0.2" - shelljs "^0.7.5" - strip-bom "^3.0.0" - strip-json-comments "~2.0.1" - table "^3.7.8" - text-table "~0.2.0" - user-home "^2.0.0" - -espree@^3.4.0: - version "3.5.1" - resolved "https://registry.yarnpkg.com/espree/-/espree-3.5.1.tgz#0c988b8ab46db53100a1954ae4ba995ddd27d87e" - dependencies: - acorn "^5.1.1" - acorn-jsx "^3.0.0" - -espree@~2.2.3: - version "2.2.5" - resolved "https://registry.yarnpkg.com/espree/-/espree-2.2.5.tgz#df691b9310889402aeb29cc066708c56690b854b" - -esprima@1.0.x, esprima@~1.0.4: - version "1.0.4" - resolved "https://registry.yarnpkg.com/esprima/-/esprima-1.0.4.tgz#9f557e08fc3b4d26ece9dd34f8fbf476b62585ad" - -esprima@^2.6.0: - version "2.7.3" - resolved "https://registry.yarnpkg.com/esprima/-/esprima-2.7.3.tgz#96e3b70d5779f6ad49cd032673d1c312767ba581" - -esprima@^4.0.0: - version "4.0.0" - resolved "https://registry.yarnpkg.com/esprima/-/esprima-4.0.0.tgz#4499eddcd1110e0b218bacf2fa7f7f59f55ca804" - -esquery@^1.0.0: - version "1.0.0" - resolved "https://registry.yarnpkg.com/esquery/-/esquery-1.0.0.tgz#cfba8b57d7fba93f17298a8a006a04cda13d80fa" - dependencies: - estraverse "^4.0.0" - -esrecurse@^4.1.0: - version "4.2.0" - resolved "https://registry.yarnpkg.com/esrecurse/-/esrecurse-4.2.0.tgz#fa9568d98d3823f9a41d91e902dcab9ea6e5b163" - dependencies: - estraverse "^4.1.0" - object-assign "^4.0.1" - -estraverse@^4.0.0, estraverse@^4.1.0, estraverse@^4.1.1, estraverse@^4.2.0: - version "4.2.0" - resolved "https://registry.yarnpkg.com/estraverse/-/estraverse-4.2.0.tgz#0dee3fed31fcd469618ce7342099fc1afa0bdb13" - -estraverse@~1.5.0: - version "1.5.1" - resolved "https://registry.yarnpkg.com/estraverse/-/estraverse-1.5.1.tgz#867a3e8e58a9f84618afb6c2ddbcd916b7cbaf71" - -esutils@^2.0.2: - version "2.0.2" - resolved "https://registry.yarnpkg.com/esutils/-/esutils-2.0.2.tgz#0abf4f1caa5bcb1f7a9d8acc6dea4faaa04bac9b" - -esutils@~1.0.0: - version "1.0.0" - resolved "https://registry.yarnpkg.com/esutils/-/esutils-1.0.0.tgz#8151d358e20c8acc7fb745e7472c0025fe496570" - -event-emitter@~0.3.5: - version "0.3.5" - resolved "https://registry.yarnpkg.com/event-emitter/-/event-emitter-0.3.5.tgz#df8c69eef1647923c7157b9ce83840610b02cc39" - dependencies: - d "1" - es5-ext "~0.10.14" - -event-stream@^3.3.1, event-stream@^3.3.2: - version "3.3.4" - resolved "https://registry.yarnpkg.com/event-stream/-/event-stream-3.3.4.tgz#4ab4c9a0f5a54db9338b4c34d86bfce8f4b35571" - dependencies: - duplexer "~0.1.1" - from "~0" - map-stream "~0.1.0" - pause-stream "0.0.11" - split "0.3" - stream-combiner "~0.0.4" - through "~2.3.1" - -exit-hook@^1.0.0: - version "1.1.1" - resolved "https://registry.yarnpkg.com/exit-hook/-/exit-hook-1.1.1.tgz#f05ca233b48c05d54fff07765df8507e95c02ff8" - -expand-brackets@^0.1.4: - version "0.1.5" - resolved "https://registry.yarnpkg.com/expand-brackets/-/expand-brackets-0.1.5.tgz#df07284e342a807cd733ac5af72411e581d1177b" - dependencies: - is-posix-bracket "^0.1.0" - -expand-range@^1.8.1: - version "1.8.2" - resolved "https://registry.yarnpkg.com/expand-range/-/expand-range-1.8.2.tgz#a299effd335fe2721ebae8e257ec79644fc85337" - dependencies: - fill-range "^2.1.0" - -extend@2.0.x: - version "2.0.1" - resolved "https://registry.yarnpkg.com/extend/-/extend-2.0.1.tgz#1ee8010689e7395ff9448241c98652bc759a8260" - -extend@~3.0.0, extend@~3.0.1: - version "3.0.1" - resolved "https://registry.yarnpkg.com/extend/-/extend-3.0.1.tgz#a755ea7bc1adfcc5a31ce7e762dbaadc5e636444" - -extglob@^0.3.1: - version "0.3.2" - resolved "https://registry.yarnpkg.com/extglob/-/extglob-0.3.2.tgz#2e18ff3d2f49ab2765cec9023f011daa8d8349a1" - dependencies: - is-extglob "^1.0.0" - -extsprintf@1.3.0, extsprintf@^1.2.0: - version "1.3.0" - resolved "https://registry.yarnpkg.com/extsprintf/-/extsprintf-1.3.0.tgz#96918440e3041a7a414f8c52e3c574eb3c3e1e05" - -fast-deep-equal@^1.0.0: - version "1.0.0" - resolved "https://registry.yarnpkg.com/fast-deep-equal/-/fast-deep-equal-1.0.0.tgz#96256a3bc975595eb36d82e9929d060d893439ff" - -fast-levenshtein@~2.0.4: - version "2.0.6" - resolved "https://registry.yarnpkg.com/fast-levenshtein/-/fast-levenshtein-2.0.6.tgz#3d8a5c66883a16a30ca8643e851f19baa7797917" - -fast-stats@0.0.3: - version "0.0.3" - resolved "https://registry.yarnpkg.com/fast-stats/-/fast-stats-0.0.3.tgz#650af963c3ff85c496a3610f20d40cd4c164594d" - -figures@^1.3.5, figures@^1.4.0: - version "1.7.0" - resolved "https://registry.yarnpkg.com/figures/-/figures-1.7.0.tgz#cbe1e3affcf1cd44b80cadfed28dc793a9701d2e" - dependencies: - escape-string-regexp "^1.0.5" - object-assign "^4.1.0" - -file-entry-cache@^2.0.0: - version "2.0.0" - resolved "https://registry.yarnpkg.com/file-entry-cache/-/file-entry-cache-2.0.0.tgz#c392990c3e684783d838b8c84a45d8a048458361" - dependencies: - flat-cache "^1.2.1" - object-assign "^4.0.1" - -filename-regex@^2.0.0: - version "2.0.1" - resolved "https://registry.yarnpkg.com/filename-regex/-/filename-regex-2.0.1.tgz#c1c4b9bee3e09725ddb106b75c1e301fe2f18b26" - -fill-range@^2.1.0: - version "2.2.3" - resolved "https://registry.yarnpkg.com/fill-range/-/fill-range-2.2.3.tgz#50b77dfd7e469bc7492470963699fe7a8485a723" - dependencies: - is-number "^2.1.0" - isobject "^2.0.0" - randomatic "^1.1.3" - repeat-element "^1.1.2" - repeat-string "^1.5.2" - -find-cache-dir@^0.1.1: - version "0.1.1" - resolved "https://registry.yarnpkg.com/find-cache-dir/-/find-cache-dir-0.1.1.tgz#c8defae57c8a52a8a784f9e31c57c742e993a0b9" - dependencies: - commondir "^1.0.1" - mkdirp "^0.5.1" - pkg-dir "^1.0.0" - -find-root@^0.1.1: - version "0.1.2" - resolved "https://registry.yarnpkg.com/find-root/-/find-root-0.1.2.tgz#98d2267cff1916ccaf2743b3a0eea81d79d7dcd1" - -find-up@^1.0.0, find-up@^1.1.2: - version "1.1.2" - resolved "https://registry.yarnpkg.com/find-up/-/find-up-1.1.2.tgz#6b2e9822b1a2ce0a60ab64d610eccad53cb24d0f" - dependencies: - path-exists "^2.0.0" - pinkie-promise "^2.0.0" - -flat-cache@^1.2.1: - version "1.3.0" - resolved "https://registry.yarnpkg.com/flat-cache/-/flat-cache-1.3.0.tgz#d3030b32b38154f4e3b7e9c709f490f7ef97c481" - dependencies: - circular-json "^0.3.1" - del "^2.0.2" - graceful-fs "^4.1.2" - write "^0.2.1" - -for-in@^1.0.1: - version "1.0.2" - resolved "https://registry.yarnpkg.com/for-in/-/for-in-1.0.2.tgz#81068d295a8142ec0ac726c6e2200c30fb6d5e80" - -for-own@^0.1.4: - version "0.1.5" - resolved "https://registry.yarnpkg.com/for-own/-/for-own-0.1.5.tgz#5265c681a4f294dabbf17c9509b6763aa84510ce" - dependencies: - for-in "^1.0.1" - -foreground-child@^1.5.3, foreground-child@^1.5.6: - version "1.5.6" - resolved "https://registry.yarnpkg.com/foreground-child/-/foreground-child-1.5.6.tgz#4fd71ad2dfde96789b980a5c0a295937cb2f5ce9" - dependencies: - cross-spawn "^4" - signal-exit "^3.0.0" - -forever-agent@~0.6.1: - version "0.6.1" - resolved "https://registry.yarnpkg.com/forever-agent/-/forever-agent-0.6.1.tgz#fbc71f0c41adeb37f96c577ad1ed42d8fdacca91" - -form-data@~2.1.1: - version "2.1.4" - resolved "https://registry.yarnpkg.com/form-data/-/form-data-2.1.4.tgz#33c183acf193276ecaa98143a69e94bfee1750d1" - dependencies: - asynckit "^0.4.0" - combined-stream "^1.0.5" - mime-types "^2.1.12" - -form-data@~2.3.1: - version "2.3.1" - resolved "https://registry.yarnpkg.com/form-data/-/form-data-2.3.1.tgz#6fb94fbd71885306d73d15cc497fe4cc4ecd44bf" - dependencies: - asynckit "^0.4.0" - combined-stream "^1.0.5" - mime-types "^2.1.12" - -from@~0: - version "0.1.7" - resolved "https://registry.yarnpkg.com/from/-/from-0.1.7.tgz#83c60afc58b9c56997007ed1a768b3ab303a44fe" - -fs-extra@^0.22.1: - version "0.22.1" - resolved "https://registry.yarnpkg.com/fs-extra/-/fs-extra-0.22.1.tgz#5fd6f8049dc976ca19eb2355d658173cabcce056" - dependencies: - graceful-fs "^4.1.2" - jsonfile "^2.1.0" - rimraf "^2.2.8" - -fs-extra@~0.30.0: - version "0.30.0" - resolved "https://registry.yarnpkg.com/fs-extra/-/fs-extra-0.30.0.tgz#f233ffcc08d4da7d432daa449776989db1df93f0" - dependencies: - graceful-fs "^4.1.2" - jsonfile "^2.1.0" - klaw "^1.0.0" - path-is-absolute "^1.0.0" - rimraf "^2.2.8" - -fs.realpath@^1.0.0: - version "1.0.0" - resolved "https://registry.yarnpkg.com/fs.realpath/-/fs.realpath-1.0.0.tgz#1504ad2523158caa40db4a2787cb01411994ea4f" - -"fstream@>= 0.1.30 < 1": - version "0.1.31" - resolved "https://registry.yarnpkg.com/fstream/-/fstream-0.1.31.tgz#7337f058fbbbbefa8c9f561a28cab0849202c988" - dependencies: - graceful-fs "~3.0.2" - inherits "~2.0.0" - mkdirp "0.5" - rimraf "2" - -fstream@^1.0.2: - version "1.0.11" - resolved "https://registry.yarnpkg.com/fstream/-/fstream-1.0.11.tgz#5c1fb1f117477114f0632a0eb4b71b3cb0fd3171" - dependencies: - graceful-fs "^4.1.2" - inherits "~2.0.0" - mkdirp ">=0.5 0" - rimraf "2" - -gauge@~1.0.2: - version "1.0.2" - resolved "https://registry.yarnpkg.com/gauge/-/gauge-1.0.2.tgz#53e25965dfaf1c85be3a2a0633306a24a67dc2f9" - dependencies: - ansi "^0.3.0" - has-unicode "^1.0.0" - -generate-function@^2.0.0: - version "2.0.0" - resolved "https://registry.yarnpkg.com/generate-function/-/generate-function-2.0.0.tgz#6858fe7c0969b7d4e9093337647ac79f60dfbe74" - -generate-object-property@^1.1.0: - version "1.2.0" - resolved "https://registry.yarnpkg.com/generate-object-property/-/generate-object-property-1.2.0.tgz#9c0e1c40308ce804f4783618b937fa88f99d50d0" - dependencies: - is-property "^1.0.0" - -get-caller-file@^1.0.1: - version "1.0.2" - resolved "https://registry.yarnpkg.com/get-caller-file/-/get-caller-file-1.0.2.tgz#f702e63127e7e231c160a80c1554acb70d5047e5" - -get-mongodb-version@0.0.1: - version "0.0.1" - resolved "https://registry.yarnpkg.com/get-mongodb-version/-/get-mongodb-version-0.0.1.tgz#bc8aa433ba2fdd57fa33312dcf89f06f3a908caa" - dependencies: - debug "^2.2.0" - lodash.startswith "^3.0.1" - minimist "^1.1.1" - mongodb "^2.0.39" - which "^1.1.1" - -get-stdin@^4.0.1: - version "4.0.1" - resolved "https://registry.yarnpkg.com/get-stdin/-/get-stdin-4.0.1.tgz#b968c6b0a04384324902e8bf1a5df32579a450fe" - -getpass@^0.1.1: - version "0.1.7" - resolved "https://registry.yarnpkg.com/getpass/-/getpass-0.1.7.tgz#5eff8e3e684d569ae4cb2b1282604e8ba62149fa" - dependencies: - assert-plus "^1.0.0" - -gleak@0.5.0: - version "0.5.0" - resolved "https://registry.yarnpkg.com/gleak/-/gleak-0.5.0.tgz#9cd7694be50d6dbeb842021ed8160814c51faddf" - -glob-base@^0.3.0: - version "0.3.0" - resolved "https://registry.yarnpkg.com/glob-base/-/glob-base-0.3.0.tgz#dbb164f6221b1c0b1ccf82aea328b497df0ea3c4" - dependencies: - glob-parent "^2.0.0" - is-glob "^2.0.0" - -glob-parent@^2.0.0: - version "2.0.0" - resolved "https://registry.yarnpkg.com/glob-parent/-/glob-parent-2.0.0.tgz#81383d72db054fcccf5336daa902f182f6edbb28" - dependencies: - is-glob "^2.0.0" - -glob@^7.0.0, glob@^7.0.3, glob@^7.0.5, glob@^7.0.6: - version "7.1.2" - resolved "https://registry.yarnpkg.com/glob/-/glob-7.1.2.tgz#c19c9df9a028702d678612384a6552404c636d15" - dependencies: - fs.realpath "^1.0.0" - inflight "^1.0.4" - inherits "2" - minimatch "^3.0.4" - once "^1.3.0" - path-is-absolute "^1.0.0" - -globals@^9.14.0, globals@^9.18.0: - version "9.18.0" - resolved "https://registry.yarnpkg.com/globals/-/globals-9.18.0.tgz#aa3896b3e69b487f17e31ed2143d69a8e30c2d8a" - -globby@^5.0.0: - version "5.0.0" - resolved "https://registry.yarnpkg.com/globby/-/globby-5.0.0.tgz#ebd84667ca0dbb330b99bcfc68eac2bc54370e0d" - dependencies: - array-union "^1.0.1" - arrify "^1.0.0" - glob "^7.0.3" - object-assign "^4.0.1" - pify "^2.0.0" - pinkie-promise "^2.0.0" - -graceful-fs@2.0.3: - version "2.0.3" - resolved "https://registry.yarnpkg.com/graceful-fs/-/graceful-fs-2.0.3.tgz#7cd2cdb228a4a3f36e95efa6cc142de7d1a136d0" - -graceful-fs@^4.1.11, graceful-fs@^4.1.2, graceful-fs@^4.1.6, graceful-fs@^4.1.9: - version "4.1.11" - resolved "https://registry.yarnpkg.com/graceful-fs/-/graceful-fs-4.1.11.tgz#0e8bdfe4d1ddb8854d64e04ea7c00e2a026e5658" - -graceful-fs@~3.0.2: - version "3.0.11" - resolved "https://registry.yarnpkg.com/graceful-fs/-/graceful-fs-3.0.11.tgz#7613c778a1afea62f25c630a086d7f3acbbdd818" - dependencies: - natives "^1.1.0" - -handlebars@2.0.0-alpha.1: - version "2.0.0-alpha.1" - resolved "https://registry.yarnpkg.com/handlebars/-/handlebars-2.0.0-alpha.1.tgz#c4d149068c713de0afa7f45bbb88a2ca73715afd" - dependencies: - optimist "~0.3" - optionalDependencies: - uglify-js "~2.3" - -handlebars@^4.0.3: - version "4.0.10" - resolved "https://registry.yarnpkg.com/handlebars/-/handlebars-4.0.10.tgz#3d30c718b09a3d96f23ea4cc1f403c4d3ba9ff4f" - dependencies: - async "^1.4.0" - optimist "^0.6.1" - source-map "^0.4.4" - optionalDependencies: - uglify-js "^2.6" - -har-schema@^2.0.0: - version "2.0.0" - resolved "https://registry.yarnpkg.com/har-schema/-/har-schema-2.0.0.tgz#a94c2224ebcac04782a0d9035521f24735b7ec92" - -har-validator@~2.0.6: - version "2.0.6" - resolved "https://registry.yarnpkg.com/har-validator/-/har-validator-2.0.6.tgz#cdcbc08188265ad119b6a5a7c8ab70eecfb5d27d" - dependencies: - chalk "^1.1.1" - commander "^2.9.0" - is-my-json-valid "^2.12.4" - pinkie-promise "^2.0.0" - -har-validator@~5.0.3: - version "5.0.3" - resolved "https://registry.yarnpkg.com/har-validator/-/har-validator-5.0.3.tgz#ba402c266194f15956ef15e0fcf242993f6a7dfd" - dependencies: - ajv "^5.1.0" - har-schema "^2.0.0" - -has-ansi@^2.0.0: - version "2.0.0" - resolved "https://registry.yarnpkg.com/has-ansi/-/has-ansi-2.0.0.tgz#34f5049ce1ecdf2b0649af3ef24e45ed35416d91" - dependencies: - ansi-regex "^2.0.0" - -has-flag@^1.0.0: - version "1.0.0" - resolved "https://registry.yarnpkg.com/has-flag/-/has-flag-1.0.0.tgz#9d9e793165ce017a00f00418c43f942a7b1d11fa" - -has-unicode@^1.0.0: - version "1.0.1" - resolved "https://registry.yarnpkg.com/has-unicode/-/has-unicode-1.0.1.tgz#c46fceea053eb8ec789bffbba25fca52dfdcf38e" - -hawk@~3.1.3: - version "3.1.3" - resolved "https://registry.yarnpkg.com/hawk/-/hawk-3.1.3.tgz#078444bd7c1640b0fe540d2c9b73d59678e8e1c4" - dependencies: - boom "2.x.x" - cryptiles "2.x.x" - hoek "2.x.x" - sntp "1.x.x" - -hawk@~6.0.2: - version "6.0.2" - resolved "https://registry.yarnpkg.com/hawk/-/hawk-6.0.2.tgz#af4d914eb065f9b5ce4d9d11c1cb2126eecc3038" - dependencies: - boom "4.x.x" - cryptiles "3.x.x" - hoek "4.x.x" - sntp "2.x.x" - -hoek@2.x.x: - version "2.16.3" - resolved "https://registry.yarnpkg.com/hoek/-/hoek-2.16.3.tgz#20bb7403d3cea398e91dc4710a8ff1b8274a25ed" - -hoek@4.x.x: - version "4.2.0" - resolved "https://registry.yarnpkg.com/hoek/-/hoek-4.2.0.tgz#72d9d0754f7fe25ca2d01ad8f8f9a9449a89526d" - -home-or-tmp@^2.0.0: - version "2.0.0" - resolved "https://registry.yarnpkg.com/home-or-tmp/-/home-or-tmp-2.0.0.tgz#e36c3f2d2cae7d746a857e38d18d5f32a7882db8" - dependencies: - os-homedir "^1.0.0" - os-tmpdir "^1.0.1" - -hosted-git-info@^2.1.4: - version "2.5.0" - resolved "https://registry.yarnpkg.com/hosted-git-info/-/hosted-git-info-2.5.0.tgz#6d60e34b3abbc8313062c3b798ef8d901a07af3c" - -htmlparser2@~3.8.1: - version "3.8.3" - resolved "https://registry.yarnpkg.com/htmlparser2/-/htmlparser2-3.8.3.tgz#996c28b191516a8be86501a7d79757e5c70c1068" - dependencies: - domelementtype "1" - domhandler "2.3" - domutils "1.5" - entities "1.0" - readable-stream "1.1" - -http-signature@~1.1.0: - version "1.1.1" - resolved "https://registry.yarnpkg.com/http-signature/-/http-signature-1.1.1.tgz#df72e267066cd0ac67fb76adf8e134a8fbcf91bf" - dependencies: - assert-plus "^0.2.0" - jsprim "^1.2.2" - sshpk "^1.7.0" - -http-signature@~1.2.0: - version "1.2.0" - resolved "https://registry.yarnpkg.com/http-signature/-/http-signature-1.2.0.tgz#9aecd925114772f3d95b65a60abb8f7c18fbace1" - dependencies: - assert-plus "^1.0.0" - jsprim "^1.2.2" - sshpk "^1.7.0" - -ignore@^3.2.0: - version "3.3.5" - resolved "https://registry.yarnpkg.com/ignore/-/ignore-3.3.5.tgz#c4e715455f6073a8d7e5dae72d2fc9d71663dba6" - -imurmurhash@^0.1.4: - version "0.1.4" - resolved "https://registry.yarnpkg.com/imurmurhash/-/imurmurhash-0.1.4.tgz#9218b9b2b928a238b13dc4fb6b6d576f231453ea" - -indent-string@^2.1.0: - version "2.1.0" - resolved "https://registry.yarnpkg.com/indent-string/-/indent-string-2.1.0.tgz#8e2d48348742121b4a8218b7a137e9a52049dc80" - dependencies: - repeating "^2.0.0" - -inflight@^1.0.4: - version "1.0.6" - resolved "https://registry.yarnpkg.com/inflight/-/inflight-1.0.6.tgz#49bd6331d7d02d0c09bc910a1075ba8165b56df9" - dependencies: - once "^1.3.0" - wrappy "1" - -inherits@2, inherits@^2.0.3, inherits@~2.0.0, inherits@~2.0.1, inherits@~2.0.3: - version "2.0.3" - resolved "https://registry.yarnpkg.com/inherits/-/inherits-2.0.3.tgz#633c2c83e3da42a502f52466022480f4208261de" - -inquirer@^0.12.0: - version "0.12.0" - resolved "https://registry.yarnpkg.com/inquirer/-/inquirer-0.12.0.tgz#1ef2bfd63504df0bc75785fff8c2c41df12f077e" - dependencies: - ansi-escapes "^1.1.0" - ansi-regex "^2.0.0" - chalk "^1.0.0" - cli-cursor "^1.0.1" - cli-width "^2.0.0" - figures "^1.3.5" - lodash "^4.3.0" - readline2 "^1.0.1" - run-async "^0.1.0" - rx-lite "^3.1.2" - string-width "^1.0.1" - strip-ansi "^3.0.0" - through "^2.3.6" - -integra@0.1.8: - version "0.1.8" - resolved "https://registry.yarnpkg.com/integra/-/integra-0.1.8.tgz#8d5b8019f87ea3704e6c97da2c912e14ec3bece7" - dependencies: - escodegen "1.1.x" - esprima "1.0.x" - handlebars "2.0.0-alpha.1" - mkdirp latest - rimraf "2.2.6" - -interpret@^1.0.0: - version "1.0.4" - resolved "https://registry.yarnpkg.com/interpret/-/interpret-1.0.4.tgz#820cdd588b868ffb191a809506d6c9c8f212b1b0" - -invariant@^2.2.2: - version "2.2.2" - resolved "https://registry.yarnpkg.com/invariant/-/invariant-2.2.2.tgz#9e1f56ac0acdb6bf303306f338be3b204ae60360" - dependencies: - loose-envify "^1.0.0" - -invert-kv@^1.0.0: - version "1.0.0" - resolved "https://registry.yarnpkg.com/invert-kv/-/invert-kv-1.0.0.tgz#104a8e4aaca6d3d8cd157a8ef8bfab2d7a3ffdb6" - -is-arrayish@^0.2.1: - version "0.2.1" - resolved "https://registry.yarnpkg.com/is-arrayish/-/is-arrayish-0.2.1.tgz#77c99840527aa8ecb1a8ba697b80645a7a926a9d" - -is-buffer@^1.1.5: - version "1.1.5" - resolved "https://registry.yarnpkg.com/is-buffer/-/is-buffer-1.1.5.tgz#1f3b26ef613b214b88cbca23cc6c01d87961eecc" - -is-builtin-module@^1.0.0: - version "1.0.0" - resolved "https://registry.yarnpkg.com/is-builtin-module/-/is-builtin-module-1.0.0.tgz#540572d34f7ac3119f8f76c30cbc1b1e037affbe" - dependencies: - builtin-modules "^1.0.0" - -is-dotfile@^1.0.0: - version "1.0.3" - resolved "https://registry.yarnpkg.com/is-dotfile/-/is-dotfile-1.0.3.tgz#a6a2f32ffd2dfb04f5ca25ecd0f6b83cf798a1e1" - -is-equal-shallow@^0.1.3: - version "0.1.3" - resolved "https://registry.yarnpkg.com/is-equal-shallow/-/is-equal-shallow-0.1.3.tgz#2238098fc221de0bcfa5d9eac4c45d638aa1c534" - dependencies: - is-primitive "^2.0.0" - -is-extendable@^0.1.1: - version "0.1.1" - resolved "https://registry.yarnpkg.com/is-extendable/-/is-extendable-0.1.1.tgz#62b110e289a471418e3ec36a617d472e301dfc89" - -is-extglob@^1.0.0: - version "1.0.0" - resolved "https://registry.yarnpkg.com/is-extglob/-/is-extglob-1.0.0.tgz#ac468177c4943405a092fc8f29760c6ffc6206c0" - -is-finite@^1.0.0: - version "1.0.2" - resolved "https://registry.yarnpkg.com/is-finite/-/is-finite-1.0.2.tgz#cc6677695602be550ef11e8b4aa6305342b6d0aa" - dependencies: - number-is-nan "^1.0.0" - -is-fullwidth-code-point@^1.0.0: - version "1.0.0" - resolved "https://registry.yarnpkg.com/is-fullwidth-code-point/-/is-fullwidth-code-point-1.0.0.tgz#ef9e31386f031a7f0d643af82fde50c457ef00cb" - dependencies: - number-is-nan "^1.0.0" - -is-fullwidth-code-point@^2.0.0: - version "2.0.0" - resolved "https://registry.yarnpkg.com/is-fullwidth-code-point/-/is-fullwidth-code-point-2.0.0.tgz#a3b30a5c4f199183167aaab93beefae3ddfb654f" - -is-glob@^2.0.0, is-glob@^2.0.1: - version "2.0.1" - resolved "https://registry.yarnpkg.com/is-glob/-/is-glob-2.0.1.tgz#d096f926a3ded5600f3fdfd91198cb0888c2d863" - dependencies: - is-extglob "^1.0.0" - -is-my-json-valid@^2.10.0, is-my-json-valid@^2.12.4: - version "2.16.1" - resolved "https://registry.yarnpkg.com/is-my-json-valid/-/is-my-json-valid-2.16.1.tgz#5a846777e2c2620d1e69104e5d3a03b1f6088f11" - dependencies: - generate-function "^2.0.0" - generate-object-property "^1.1.0" - jsonpointer "^4.0.0" - xtend "^4.0.0" - -is-number@^2.1.0: - version "2.1.0" - resolved "https://registry.yarnpkg.com/is-number/-/is-number-2.1.0.tgz#01fcbbb393463a548f2f466cce16dece49db908f" - dependencies: - kind-of "^3.0.2" - -is-number@^3.0.0: - version "3.0.0" - resolved "https://registry.yarnpkg.com/is-number/-/is-number-3.0.0.tgz#24fd6201a4782cf50561c810276afc7d12d71195" - dependencies: - kind-of "^3.0.2" - -is-path-cwd@^1.0.0: - version "1.0.0" - resolved "https://registry.yarnpkg.com/is-path-cwd/-/is-path-cwd-1.0.0.tgz#d225ec23132e89edd38fda767472e62e65f1106d" - -is-path-in-cwd@^1.0.0: - version "1.0.0" - resolved "https://registry.yarnpkg.com/is-path-in-cwd/-/is-path-in-cwd-1.0.0.tgz#6477582b8214d602346094567003be8a9eac04dc" - dependencies: - is-path-inside "^1.0.0" - -is-path-inside@^1.0.0: - version "1.0.0" - resolved "https://registry.yarnpkg.com/is-path-inside/-/is-path-inside-1.0.0.tgz#fc06e5a1683fbda13de667aff717bbc10a48f37f" - dependencies: - path-is-inside "^1.0.1" - -is-posix-bracket@^0.1.0: - version "0.1.1" - resolved "https://registry.yarnpkg.com/is-posix-bracket/-/is-posix-bracket-0.1.1.tgz#3334dc79774368e92f016e6fbc0a88f5cd6e6bc4" - -is-primitive@^2.0.0: - version "2.0.0" - resolved "https://registry.yarnpkg.com/is-primitive/-/is-primitive-2.0.0.tgz#207bab91638499c07b2adf240a41a87210034575" - -is-property@^1.0.0: - version "1.0.2" - resolved "https://registry.yarnpkg.com/is-property/-/is-property-1.0.2.tgz#57fe1c4e48474edd65b09911f26b1cd4095dda84" - -is-resolvable@^1.0.0: - version "1.0.0" - resolved "https://registry.yarnpkg.com/is-resolvable/-/is-resolvable-1.0.0.tgz#8df57c61ea2e3c501408d100fb013cf8d6e0cc62" - dependencies: - tryit "^1.0.1" - -is-typedarray@~1.0.0: - version "1.0.0" - resolved "https://registry.yarnpkg.com/is-typedarray/-/is-typedarray-1.0.0.tgz#e479c80858df0c1b11ddda6940f96011fcda4a9a" - -is-utf8@^0.2.0: - version "0.2.1" - resolved "https://registry.yarnpkg.com/is-utf8/-/is-utf8-0.2.1.tgz#4b0da1442104d1b336340e80797e865cf39f7d72" - -isarray@0.0.1: - version "0.0.1" - resolved "https://registry.yarnpkg.com/isarray/-/isarray-0.0.1.tgz#8a18acfca9a8f4177e09abfc6038939b05d1eedf" - -isarray@1.0.0, isarray@^1.0.0, isarray@~1.0.0: - version "1.0.0" - resolved "https://registry.yarnpkg.com/isarray/-/isarray-1.0.0.tgz#bb935d48582cba168c06834957a54a3e07124f11" - -isexe@^2.0.0: - version "2.0.0" - resolved "https://registry.yarnpkg.com/isexe/-/isexe-2.0.0.tgz#e8fbf374dc556ff8947a10dcb0572d633f2cfa10" - -isobject@^2.0.0: - version "2.1.0" - resolved "https://registry.yarnpkg.com/isobject/-/isobject-2.1.0.tgz#f065561096a3f1da2ef46272f815c840d87e0c89" - dependencies: - isarray "1.0.0" - -isstream@~0.1.2: - version "0.1.2" - resolved "https://registry.yarnpkg.com/isstream/-/isstream-0.1.2.tgz#47e63f7af55afa6f92e1500e690eb8b8529c099a" - -istanbul-lib-coverage@^1.0.0, istanbul-lib-coverage@^1.1.1: - version "1.1.1" - resolved "https://registry.yarnpkg.com/istanbul-lib-coverage/-/istanbul-lib-coverage-1.1.1.tgz#73bfb998885299415c93d38a3e9adf784a77a9da" - -istanbul-lib-hook@^1.0.0-alpha.4: - version "1.0.7" - resolved "https://registry.yarnpkg.com/istanbul-lib-hook/-/istanbul-lib-hook-1.0.7.tgz#dd6607f03076578fe7d6f2a630cf143b49bacddc" - dependencies: - append-transform "^0.4.0" - -istanbul-lib-instrument@^1.2.0: - version "1.8.0" - resolved "https://registry.yarnpkg.com/istanbul-lib-instrument/-/istanbul-lib-instrument-1.8.0.tgz#66f6c9421cc9ec4704f76f2db084ba9078a2b532" - dependencies: - babel-generator "^6.18.0" - babel-template "^6.16.0" - babel-traverse "^6.18.0" - babel-types "^6.18.0" - babylon "^6.18.0" - istanbul-lib-coverage "^1.1.1" - semver "^5.3.0" - -istanbul-lib-report@^1.0.0-alpha.3: - version "1.1.1" - resolved "https://registry.yarnpkg.com/istanbul-lib-report/-/istanbul-lib-report-1.1.1.tgz#f0e55f56655ffa34222080b7a0cd4760e1405fc9" - dependencies: - istanbul-lib-coverage "^1.1.1" - mkdirp "^0.5.1" - path-parse "^1.0.5" - supports-color "^3.1.2" - -istanbul-lib-source-maps@^1.0.2: - version "1.2.1" - resolved "https://registry.yarnpkg.com/istanbul-lib-source-maps/-/istanbul-lib-source-maps-1.2.1.tgz#a6fe1acba8ce08eebc638e572e294d267008aa0c" - dependencies: - debug "^2.6.3" - istanbul-lib-coverage "^1.1.1" - mkdirp "^0.5.1" - rimraf "^2.6.1" - source-map "^0.5.3" - -istanbul-reports@^1.0.0: - version "1.1.2" - resolved "https://registry.yarnpkg.com/istanbul-reports/-/istanbul-reports-1.1.2.tgz#0fb2e3f6aa9922bd3ce45d05d8ab4d5e8e07bd4f" - dependencies: - handlebars "^4.0.3" - -js-tokens@^3.0.0, js-tokens@^3.0.2: - version "3.0.2" - resolved "https://registry.yarnpkg.com/js-tokens/-/js-tokens-3.0.2.tgz#9866df395102130e38f7f996bceb65443209c25b" - -js-yaml@3.6.1: - version "3.6.1" - resolved "https://registry.yarnpkg.com/js-yaml/-/js-yaml-3.6.1.tgz#6e5fe67d8b205ce4d22fad05b7781e8dadcc4b30" - dependencies: - argparse "^1.0.7" - esprima "^2.6.0" - -js-yaml@^3.5.1: - version "3.10.0" - resolved "https://registry.yarnpkg.com/js-yaml/-/js-yaml-3.10.0.tgz#2e78441646bd4682e963f22b6e92823c309c62dc" - dependencies: - argparse "^1.0.7" - esprima "^4.0.0" - -js2xmlparser@~1.0.0: - version "1.0.0" - resolved "https://registry.yarnpkg.com/js2xmlparser/-/js2xmlparser-1.0.0.tgz#5a170f2e8d6476ce45405e04823242513782fe30" - -jsbn@~0.1.0: - version "0.1.1" - resolved "https://registry.yarnpkg.com/jsbn/-/jsbn-0.1.1.tgz#a5e654c2e5a2deb5f201d96cefbca80c0ef2f513" - -jsdoc@3.4.0: - version "3.4.0" - resolved "https://registry.yarnpkg.com/jsdoc/-/jsdoc-3.4.0.tgz#341cdb06e44a113d9541efd212c95a488064e9ee" - dependencies: - async "~1.4.0" - bluebird "~2.9.34" - catharsis "~0.8.7" - escape-string-regexp "~1.0.3" - espree "~2.2.3" - js2xmlparser "~1.0.0" - marked "~0.3.4" - requizzle "~0.2.0" - strip-json-comments "~1.0.2" - taffydb "https://github.com/hegemonic/taffydb/tarball/7d100bcee0e997ee4977e273cdce60bd8933050e" - underscore "~1.8.3" - wrench "~1.5.8" - -jsesc@^1.3.0: - version "1.3.0" - resolved "https://registry.yarnpkg.com/jsesc/-/jsesc-1.3.0.tgz#46c3fec8c1892b12b0833db9bc7622176dbab34b" - -json-schema-traverse@^0.3.0: - version "0.3.1" - resolved "https://registry.yarnpkg.com/json-schema-traverse/-/json-schema-traverse-0.3.1.tgz#349a6d44c53a51de89b40805c5d5e59b417d3340" - -json-schema@0.2.3: - version "0.2.3" - resolved "https://registry.yarnpkg.com/json-schema/-/json-schema-0.2.3.tgz#b480c892e59a2f05954ce727bd3f2a4e882f9e13" - -json-stable-stringify@^1.0.0, json-stable-stringify@^1.0.1: - version "1.0.1" - resolved "https://registry.yarnpkg.com/json-stable-stringify/-/json-stable-stringify-1.0.1.tgz#9a759d39c5f2ff503fd5300646ed445f88c4f9af" - dependencies: - jsonify "~0.0.0" - -json-stringify-safe@~5.0.1: - version "5.0.1" - resolved "https://registry.yarnpkg.com/json-stringify-safe/-/json-stringify-safe-5.0.1.tgz#1296a2d58fd45f19a0f6ce01d65701e2c735b6eb" - -json5@^0.5.1: - version "0.5.1" - resolved "https://registry.yarnpkg.com/json5/-/json5-0.5.1.tgz#1eade7acc012034ad84e2396767ead9fa5495821" - -jsonfile@^2.1.0: - version "2.4.0" - resolved "https://registry.yarnpkg.com/jsonfile/-/jsonfile-2.4.0.tgz#3736a2b428b87bbda0cc83b53fa3d633a35c2ae8" - optionalDependencies: - graceful-fs "^4.1.6" - -jsonify@~0.0.0: - version "0.0.0" - resolved "https://registry.yarnpkg.com/jsonify/-/jsonify-0.0.0.tgz#2c74b6ee41d93ca51b7b5aaee8f503631d252a73" - -jsonparse@^1.2.0: - version "1.3.1" - resolved "https://registry.yarnpkg.com/jsonparse/-/jsonparse-1.3.1.tgz#3f4dae4a91fac315f71062f8521cc239f1366280" - -jsonpointer@^4.0.0: - version "4.0.1" - resolved "https://registry.yarnpkg.com/jsonpointer/-/jsonpointer-4.0.1.tgz#4fd92cb34e0e9db3c89c8622ecf51f9b978c6cb9" - -jsprim@^1.2.2: - version "1.4.1" - resolved "https://registry.yarnpkg.com/jsprim/-/jsprim-1.4.1.tgz#313e66bc1e5cc06e438bc1b7499c2e5c56acb6a2" - dependencies: - assert-plus "1.0.0" - extsprintf "1.3.0" - json-schema "0.2.3" - verror "1.10.0" - -kerberos@^0.0.23: - version "0.0.23" - resolved "https://registry.yarnpkg.com/kerberos/-/kerberos-0.0.23.tgz#6aa46afdb9786c6919388cc5b408f012c71f0fd1" - dependencies: - nan "~2.5.1" - -key-tree-store@^1.3.0: - version "1.3.0" - resolved "https://registry.yarnpkg.com/key-tree-store/-/key-tree-store-1.3.0.tgz#5ea29afc2529a425938437d6955b714ce6a9791f" - -kind-of@^3.0.2: - version "3.2.2" - resolved "https://registry.yarnpkg.com/kind-of/-/kind-of-3.2.2.tgz#31ea21a734bab9bbb0f32466d893aea51e4a3c64" - dependencies: - is-buffer "^1.1.5" - -kind-of@^4.0.0: - version "4.0.0" - resolved "https://registry.yarnpkg.com/kind-of/-/kind-of-4.0.0.tgz#20813df3d712928b207378691a45066fae72dd57" - dependencies: - is-buffer "^1.1.5" - -klaw@^1.0.0: - version "1.3.1" - resolved "https://registry.yarnpkg.com/klaw/-/klaw-1.3.1.tgz#4088433b46b3b1ba259d78785d8e96f73ba02439" - optionalDependencies: - graceful-fs "^4.1.9" - -lazy-cache@^1.0.3: - version "1.0.4" - resolved "https://registry.yarnpkg.com/lazy-cache/-/lazy-cache-1.0.4.tgz#a1d78fc3a50474cb80845d3b3b6e1da49a446e8e" - -lcid@^1.0.0: - version "1.0.0" - resolved "https://registry.yarnpkg.com/lcid/-/lcid-1.0.0.tgz#308accafa0bc483a3867b4b6f2b9506251d1b835" - dependencies: - invert-kv "^1.0.0" - -lcov-parse@0.0.10: - version "0.0.10" - resolved "https://registry.yarnpkg.com/lcov-parse/-/lcov-parse-0.0.10.tgz#1b0b8ff9ac9c7889250582b70b71315d9da6d9a3" - -ldjson-stream@^1.2.1: - version "1.2.1" - resolved "https://registry.yarnpkg.com/ldjson-stream/-/ldjson-stream-1.2.1.tgz#91beceda5ac4ed2b17e649fb777e7abfa0189c2b" - dependencies: - split2 "^0.2.1" - through2 "^0.6.1" - -levn@^0.3.0, levn@~0.3.0: - version "0.3.0" - resolved "https://registry.yarnpkg.com/levn/-/levn-0.3.0.tgz#3b09924edf9f083c0490fdd4c0bc4421e04764ee" - dependencies: - prelude-ls "~1.1.2" - type-check "~0.3.2" - -limiter@1.0.x: - version "1.0.5" - resolved "https://registry.yarnpkg.com/limiter/-/limiter-1.0.5.tgz#9630b2a0d3bad63203f96e3d96f32f83d442dfc8" - -load-json-file@^1.0.0: - version "1.1.0" - resolved "https://registry.yarnpkg.com/load-json-file/-/load-json-file-1.1.0.tgz#956905708d58b4bab4c2261b04f59f31c99374c0" - dependencies: - graceful-fs "^4.1.2" - parse-json "^2.2.0" - pify "^2.0.0" - pinkie-promise "^2.0.0" - strip-bom "^2.0.0" - -lodash._arrayeach@^3.0.0: - version "3.0.0" - resolved "https://registry.yarnpkg.com/lodash._arrayeach/-/lodash._arrayeach-3.0.0.tgz#bab156b2a90d3f1bbd5c653403349e5e5933ef9e" - -lodash._baseassign@^3.0.0: - version "3.2.0" - resolved "https://registry.yarnpkg.com/lodash._baseassign/-/lodash._baseassign-3.2.0.tgz#8c38a099500f215ad09e59f1722fd0c52bfe0a4e" - dependencies: - lodash._basecopy "^3.0.0" - lodash.keys "^3.0.0" - -lodash._basecallback@^3.0.0: - version "3.3.1" - resolved "https://registry.yarnpkg.com/lodash._basecallback/-/lodash._basecallback-3.3.1.tgz#b7b2bb43dc2160424a21ccf26c57e443772a8e27" - dependencies: - lodash._baseisequal "^3.0.0" - lodash._bindcallback "^3.0.0" - lodash.isarray "^3.0.0" - lodash.pairs "^3.0.0" - -lodash._basecopy@^3.0.0: - version "3.0.1" - resolved "https://registry.yarnpkg.com/lodash._basecopy/-/lodash._basecopy-3.0.1.tgz#8da0e6a876cf344c0ad8a54882111dd3c5c7ca36" - -lodash._basecreate@^3.0.0: - version "3.0.3" - resolved "https://registry.yarnpkg.com/lodash._basecreate/-/lodash._basecreate-3.0.3.tgz#1bc661614daa7fc311b7d03bf16806a0213cf821" - -lodash._basefor@^3.0.0: - version "3.0.3" - resolved "https://registry.yarnpkg.com/lodash._basefor/-/lodash._basefor-3.0.3.tgz#7550b4e9218ef09fad24343b612021c79b4c20c2" - -lodash._baseisequal@^3.0.0: - version "3.0.7" - resolved "https://registry.yarnpkg.com/lodash._baseisequal/-/lodash._baseisequal-3.0.7.tgz#d8025f76339d29342767dcc887ce5cb95a5b51f1" - dependencies: - lodash.isarray "^3.0.0" - lodash.istypedarray "^3.0.0" - lodash.keys "^3.0.0" - -lodash._bindcallback@^3.0.0: - version "3.0.1" - resolved "https://registry.yarnpkg.com/lodash._bindcallback/-/lodash._bindcallback-3.0.1.tgz#e531c27644cf8b57a99e17ed95b35c748789392e" - -lodash._createassigner@^3.0.0: - version "3.1.1" - resolved "https://registry.yarnpkg.com/lodash._createassigner/-/lodash._createassigner-3.1.1.tgz#838a5bae2fdaca63ac22dee8e19fa4e6d6970b11" - dependencies: - lodash._bindcallback "^3.0.0" - lodash._isiterateecall "^3.0.0" - lodash.restparam "^3.0.0" - -lodash._getnative@^3.0.0: - version "3.9.1" - resolved "https://registry.yarnpkg.com/lodash._getnative/-/lodash._getnative-3.9.1.tgz#570bc7dede46d61cdcde687d65d3eecbaa3aaff5" - -lodash._isiterateecall@^3.0.0: - version "3.0.9" - resolved "https://registry.yarnpkg.com/lodash._isiterateecall/-/lodash._isiterateecall-3.0.9.tgz#5203ad7ba425fae842460e696db9cf3e6aac057c" - -lodash._root@^3.0.0: - version "3.0.1" - resolved "https://registry.yarnpkg.com/lodash._root/-/lodash._root-3.0.1.tgz#fba1c4524c19ee9a5f8136b4609f017cf4ded692" - -lodash.assign@^3.0.0: - version "3.2.0" - resolved "https://registry.yarnpkg.com/lodash.assign/-/lodash.assign-3.2.0.tgz#3ce9f0234b4b2223e296b8fa0ac1fee8ebca64fa" - dependencies: - lodash._baseassign "^3.0.0" - lodash._createassigner "^3.0.0" - lodash.keys "^3.0.0" - -lodash.defaults@^3.1.2: - version "3.1.2" - resolved "https://registry.yarnpkg.com/lodash.defaults/-/lodash.defaults-3.1.2.tgz#c7308b18dbf8bc9372d701a73493c61192bd2e2c" - dependencies: - lodash.assign "^3.0.0" - lodash.restparam "^3.0.0" - -lodash.defaults@^4.0.0: - version "4.2.0" - resolved "https://registry.yarnpkg.com/lodash.defaults/-/lodash.defaults-4.2.0.tgz#d09178716ffea4dde9e5fb7b37f6f0802274580c" - -lodash.difference@^4.1.1: - version "4.5.0" - resolved "https://registry.yarnpkg.com/lodash.difference/-/lodash.difference-4.5.0.tgz#9ccb4e505d486b91651345772885a2df27fd017c" - -lodash.isarguments@^3.0.0: - version "3.1.0" - resolved "https://registry.yarnpkg.com/lodash.isarguments/-/lodash.isarguments-3.1.0.tgz#2f573d85c6a24289ff00663b491c1d338ff3458a" - -lodash.isarray@^3.0.0: - version "3.0.4" - resolved "https://registry.yarnpkg.com/lodash.isarray/-/lodash.isarray-3.0.4.tgz#79e4eb88c36a8122af86f844aa9bcd851b5fbb55" - -lodash.isfunction@^3.0.0, lodash.isfunction@^3.0.6: - version "3.0.8" - resolved "https://registry.yarnpkg.com/lodash.isfunction/-/lodash.isfunction-3.0.8.tgz#4db709fc81bc4a8fd7127a458a5346c5cdce2c6b" - -lodash.istypedarray@^3.0.0: - version "3.0.6" - resolved "https://registry.yarnpkg.com/lodash.istypedarray/-/lodash.istypedarray-3.0.6.tgz#c9a477498607501d8e8494d283b87c39281cef62" - -lodash.keys@^3.0.0: - version "3.1.2" - resolved "https://registry.yarnpkg.com/lodash.keys/-/lodash.keys-3.1.2.tgz#4dbc0472b156be50a0b286855d1bd0b0c656098a" - dependencies: - lodash._getnative "^3.0.0" - lodash.isarguments "^3.0.0" - lodash.isarray "^3.0.0" - -lodash.pairs@^3.0.0: - version "3.0.1" - resolved "https://registry.yarnpkg.com/lodash.pairs/-/lodash.pairs-3.0.1.tgz#bbe08d5786eeeaa09a15c91ebf0dcb7d2be326a9" - dependencies: - lodash.keys "^3.0.0" - -lodash.restparam@^3.0.0: - version "3.6.1" - resolved "https://registry.yarnpkg.com/lodash.restparam/-/lodash.restparam-3.6.1.tgz#936a4e309ef330a7645ed4145986c85ae5b20805" - -lodash.startswith@^3.0.1: - version "3.2.0" - resolved "https://registry.yarnpkg.com/lodash.startswith/-/lodash.startswith-3.2.0.tgz#fc2e1ed2c6df8c777117632e87fe4a9181d483fb" - dependencies: - lodash._root "^3.0.0" - -lodash.transform@^3.0.4: - version "3.0.4" - resolved "https://registry.yarnpkg.com/lodash.transform/-/lodash.transform-3.0.4.tgz#8ebe53fbae15857ade36eca67fc559b78bb3ebe9" - dependencies: - lodash._arrayeach "^3.0.0" - lodash._basecallback "^3.0.0" - lodash._basecreate "^3.0.0" - lodash._basefor "^3.0.0" - lodash.isarray "^3.0.0" - lodash.isfunction "^3.0.0" - lodash.istypedarray "^3.0.0" - lodash.keys "^3.0.0" - -lodash@^3.2.0: - version "3.10.1" - resolved "https://registry.yarnpkg.com/lodash/-/lodash-3.10.1.tgz#5bf45e8e49ba4189e17d482789dfd15bd140b7b6" - -lodash@^4.0.0, lodash@^4.11.1, lodash@^4.17.4, lodash@^4.3.0, lodash@^4.6.1: - version "4.17.4" - resolved "https://registry.yarnpkg.com/lodash/-/lodash-4.17.4.tgz#78203a4d1c328ae1d86dca6460e369b57f4055ae" - -log-driver@1.2.5: - version "1.2.5" - resolved "https://registry.yarnpkg.com/log-driver/-/log-driver-1.2.5.tgz#7ae4ec257302fd790d557cb10c97100d857b0056" - -longest@^1.0.1: - version "1.0.1" - resolved "https://registry.yarnpkg.com/longest/-/longest-1.0.1.tgz#30a0b2da38f73770e8294a0d22e6625ed77d0097" - -loose-envify@^1.0.0: - version "1.3.1" - resolved "https://registry.yarnpkg.com/loose-envify/-/loose-envify-1.3.1.tgz#d1a8ad33fa9ce0e713d65fdd0ac8b748d478c848" - dependencies: - js-tokens "^3.0.0" - -loud-rejection@^1.0.0: - version "1.6.0" - resolved "https://registry.yarnpkg.com/loud-rejection/-/loud-rejection-1.6.0.tgz#5b46f80147edee578870f086d04821cf998e551f" - dependencies: - currently-unhandled "^0.4.1" - signal-exit "^3.0.0" - -lru-cache@^4.0.1: - version "4.1.1" - resolved "https://registry.yarnpkg.com/lru-cache/-/lru-cache-4.1.1.tgz#622e32e82488b49279114a4f9ecf45e7cd6bba55" - dependencies: - pseudomap "^1.0.2" - yallist "^2.1.2" - -map-obj@^1.0.0, map-obj@^1.0.1: - version "1.0.1" - resolved "https://registry.yarnpkg.com/map-obj/-/map-obj-1.0.1.tgz#d933ceb9205d82bdcf4886f6742bdc2b4dea146d" - -map-stream@~0.1.0: - version "0.1.0" - resolved "https://registry.yarnpkg.com/map-stream/-/map-stream-0.1.0.tgz#e56aa94c4c8055a16404a0674b78f215f7c8e194" - -marked@~0.3.4: - version "0.3.6" - resolved "https://registry.yarnpkg.com/marked/-/marked-0.3.6.tgz#b2c6c618fccece4ef86c4fc6cb8a7cbf5aeda8d7" - -"match-stream@>= 0.0.2 < 1": - version "0.0.2" - resolved "https://registry.yarnpkg.com/match-stream/-/match-stream-0.0.2.tgz#99eb050093b34dffade421b9ac0b410a9cfa17cf" - dependencies: - buffers "~0.1.1" - readable-stream "~1.0.0" - -md5-hex@^1.2.0: - version "1.3.0" - resolved "https://registry.yarnpkg.com/md5-hex/-/md5-hex-1.3.0.tgz#d2c4afe983c4370662179b8cad145219135046c4" - dependencies: - md5-o-matic "^0.1.1" - -md5-o-matic@^0.1.1: - version "0.1.1" - resolved "https://registry.yarnpkg.com/md5-o-matic/-/md5-o-matic-0.1.1.tgz#822bccd65e117c514fab176b25945d54100a03c3" - -meow@^3.1.0: - version "3.7.0" - resolved "https://registry.yarnpkg.com/meow/-/meow-3.7.0.tgz#72cb668b425228290abbfa856892587308a801fb" - dependencies: - camelcase-keys "^2.0.0" - decamelize "^1.1.2" - loud-rejection "^1.0.0" - map-obj "^1.0.1" - minimist "^1.1.3" - normalize-package-data "^2.3.4" - object-assign "^4.0.1" - read-pkg-up "^1.0.1" - redent "^1.0.0" - trim-newlines "^1.0.0" - -micromatch@^2.3.11: - version "2.3.11" - resolved "https://registry.yarnpkg.com/micromatch/-/micromatch-2.3.11.tgz#86677c97d1720b363431d04d0d15293bd38c1565" - dependencies: - arr-diff "^2.0.0" - array-unique "^0.2.1" - braces "^1.8.2" - expand-brackets "^0.1.4" - extglob "^0.3.1" - filename-regex "^2.0.0" - is-extglob "^1.0.0" - is-glob "^2.0.1" - kind-of "^3.0.2" - normalize-path "^2.0.1" - object.omit "^2.0.0" - parse-glob "^3.0.4" - regex-cache "^0.4.2" - -mime-db@~1.30.0: - version "1.30.0" - resolved "https://registry.yarnpkg.com/mime-db/-/mime-db-1.30.0.tgz#74c643da2dd9d6a45399963465b26d5ca7d71f01" - -mime-types@^2.1.12, mime-types@~2.1.17, mime-types@~2.1.7: - version "2.1.17" - resolved "https://registry.yarnpkg.com/mime-types/-/mime-types-2.1.17.tgz#09d7a393f03e995a79f8af857b70a9e0ab16557a" - dependencies: - mime-db "~1.30.0" - -minimatch@^3.0.4: - version "3.0.4" - resolved "https://registry.yarnpkg.com/minimatch/-/minimatch-3.0.4.tgz#5166e286457f03306064be5497e8dbb0c3d32083" - dependencies: - brace-expansion "^1.1.7" - -minimist@0.0.8: - version "0.0.8" - resolved "https://registry.yarnpkg.com/minimist/-/minimist-0.0.8.tgz#857fcabfc3397d2625b8228262e86aa7a011b05d" - -minimist@1.2.0, minimist@^1.1.0, minimist@^1.1.1, minimist@^1.1.3, minimist@^1.2.0: - version "1.2.0" - resolved "https://registry.yarnpkg.com/minimist/-/minimist-1.2.0.tgz#a35008b20f41383eec1fb914f4cd5df79a264284" - -minimist@~0.0.1: - version "0.0.10" - resolved "https://registry.yarnpkg.com/minimist/-/minimist-0.0.10.tgz#de3f98543dbf96082be48ad1a0c7cda836301dcf" - -mkdirp@0.5, "mkdirp@>=0.5 0", mkdirp@^0.5.0, mkdirp@^0.5.1, mkdirp@latest: - version "0.5.1" - resolved "https://registry.yarnpkg.com/mkdirp/-/mkdirp-0.5.1.tgz#30057438eac6cf7f8c4767f38648d6697d75c903" - dependencies: - minimist "0.0.8" - -mkdirp@~0.3.5: - version "0.3.5" - resolved "https://registry.yarnpkg.com/mkdirp/-/mkdirp-0.3.5.tgz#de3e5f8961c88c787ee1368df849ac4413eca8d7" - -moment@^2.10.6: - version "2.19.1" - resolved "https://registry.yarnpkg.com/moment/-/moment-2.19.1.tgz#56da1a2d1cbf01d38b7e1afc31c10bcfa1929167" - -mongodb-core@2.1.16: - version "2.1.16" - resolved "https://registry.yarnpkg.com/mongodb-core/-/mongodb-core-2.1.16.tgz#5dc20a48b1f0a2515fd57daaea2c4853467454e0" - dependencies: - bson "~1.0.4" - require_optional "~1.0.0" - -mongodb-core@2.1.17, mongodb-core@^2.1.12: - version "2.1.17" - resolved "https://registry.yarnpkg.com/mongodb-core/-/mongodb-core-2.1.17.tgz#a418b337a14a14990fb510b923dee6a813173df8" - dependencies: - bson "~1.0.4" - require_optional "~1.0.0" - -mongodb-download-url@^0.1.10: - version "0.1.10" - resolved "https://registry.yarnpkg.com/mongodb-download-url/-/mongodb-download-url-0.1.10.tgz#a7047eec95001de9f4df39f7e4030dc87eb3f806" - dependencies: - async "^1.5.0" - debug "^2.2.0" - lodash.defaults "^4.0.0" - minimist "^1.2.0" - mongodb-version-list "^0.0.3" - request "^2.65.0" - semver "^5.0.3" - -mongodb-extended-json@1.7.1: - version "1.7.1" - resolved "https://registry.yarnpkg.com/mongodb-extended-json/-/mongodb-extended-json-1.7.1.tgz#457ec1fe3582eb1c70c4c12a979d831c01344812" - dependencies: - JSONStream "^1.1.1" - async "^1.4.2" - bson "^0.5.2" - event-stream "^3.3.1" - lodash.isfunction "^3.0.6" - lodash.transform "^3.0.4" - moment "^2.10.6" - raf "^3.1.0" - -mongodb-topology-manager@1.0.x: - version "1.0.13" - resolved "https://registry.yarnpkg.com/mongodb-topology-manager/-/mongodb-topology-manager-1.0.13.tgz#053577386c587d2cfcc1cc45a0567b93b0f8710b" - dependencies: - babel-core "^6.25.0" - babel-polyfill "^6.23.0" - bluebird "^3.5.0" - co "^4.6.0" - kerberos "^0.0.23" - mkdirp "^0.5.1" - mongodb-core "^2.1.12" - rimraf "^2.6.1" - -mongodb-version-list@0.0.3, mongodb-version-list@^0.0.3: - version "0.0.3" - resolved "https://registry.yarnpkg.com/mongodb-version-list/-/mongodb-version-list-0.0.3.tgz#bbb261861f041fcfc5bc72b5fe2681788bd52cef" - dependencies: - cheerio "^0.19.0" - debug "^2.2.0" - downcache "0.0.8" - fs-extra "^0.22.1" - minimist "^1.1.1" - semver "^5.0.1" - -mongodb-version-manager@christkv/mongodb-version-manager#master: - version "1.0.7" - resolved "https://codeload.github.com/christkv/mongodb-version-manager/tar.gz/3ea7c20925d6a0b3a9243d341d3c69abf95e66b6" - dependencies: - ampersand-state "^5.0.1" - async "~1.5.0" - chalk "^1.1.1" - debug "~2.2.0" - docopt "~0.6.2" - figures "^1.4.0" - fs-extra "~0.30.0" - get-mongodb-version "0.0.1" - lodash.defaults "^3.1.2" - lodash.difference "^4.1.1" - mongodb-download-url "^0.1.10" - mongodb-version-list "0.0.3" - nugget "^2.0.0" - semver "~5.1.0" - tar "~2.2.1" - tildify "~1.2.0" - untildify "~2.1.0" - unzip "^0.1.11" - -mongodb@^2.0.39: - version "2.2.32" - resolved "https://registry.yarnpkg.com/mongodb/-/mongodb-2.2.32.tgz#620eaaa1995fb457c4ef7054e5f560257a697e58" - dependencies: - es6-promise "3.2.1" - mongodb-core "2.1.16" - readable-stream "2.2.7" - -ms@0.7.1: - version "0.7.1" - resolved "https://registry.yarnpkg.com/ms/-/ms-0.7.1.tgz#9cd13c03adbff25b65effde7ce864ee952017098" - -ms@2.0.0: - version "2.0.0" - resolved "https://registry.yarnpkg.com/ms/-/ms-2.0.0.tgz#5608aeadfc00be6c2901df5f9861788de0d597c8" - -mute-stream@0.0.5: - version "0.0.5" - resolved "https://registry.yarnpkg.com/mute-stream/-/mute-stream-0.0.5.tgz#8fbfabb0a98a253d3184331f9e8deb7372fac6c0" - -nan@~2.5.1: - version "2.5.1" - resolved "https://registry.yarnpkg.com/nan/-/nan-2.5.1.tgz#d5b01691253326a97a2bbee9e61c55d8d60351e2" - -natives@^1.1.0: - version "1.1.0" - resolved "https://registry.yarnpkg.com/natives/-/natives-1.1.0.tgz#e9ff841418a6b2ec7a495e939984f78f163e6e31" - -natural-compare@^1.4.0: - version "1.4.0" - resolved "https://registry.yarnpkg.com/natural-compare/-/natural-compare-1.4.0.tgz#4abebfeed7541f2c27acfb29bdbbd15c8d5ba4f7" - -normalize-package-data@^2.3.2, normalize-package-data@^2.3.4: - version "2.4.0" - resolved "https://registry.yarnpkg.com/normalize-package-data/-/normalize-package-data-2.4.0.tgz#12f95a307d58352075a04907b84ac8be98ac012f" - dependencies: - hosted-git-info "^2.1.4" - is-builtin-module "^1.0.0" - semver "2 || 3 || 4 || 5" - validate-npm-package-license "^3.0.1" - -normalize-path@^2.0.1: - version "2.1.1" - resolved "https://registry.yarnpkg.com/normalize-path/-/normalize-path-2.1.1.tgz#1ab28b556e198363a8c1a6f7e6fa20137fe6aed9" - dependencies: - remove-trailing-separator "^1.0.1" - -npmlog@1.0.0: - version "1.0.0" - resolved "https://registry.yarnpkg.com/npmlog/-/npmlog-1.0.0.tgz#ed2f290b60316887c39e0da9f09f8d13847cef0f" - dependencies: - ansi "~0.3.0" - are-we-there-yet "~1.0.0" - gauge "~1.0.2" - -nth-check@~1.0.0: - version "1.0.1" - resolved "https://registry.yarnpkg.com/nth-check/-/nth-check-1.0.1.tgz#9929acdf628fc2c41098deab82ac580cf149aae4" - dependencies: - boolbase "~1.0.0" - -nugget@^2.0.0: - version "2.0.1" - resolved "https://registry.yarnpkg.com/nugget/-/nugget-2.0.1.tgz#201095a487e1ad36081b3432fa3cada4f8d071b0" - dependencies: - debug "^2.1.3" - minimist "^1.1.0" - pretty-bytes "^1.0.2" - progress-stream "^1.1.0" - request "^2.45.0" - single-line-log "^1.1.2" - throttleit "0.0.2" - -number-is-nan@^1.0.0: - version "1.0.1" - resolved "https://registry.yarnpkg.com/number-is-nan/-/number-is-nan-1.0.1.tgz#097b602b53422a522c1afb8790318336941a011d" - -nyc@^8.1.0: - version "8.4.0" - resolved "https://registry.yarnpkg.com/nyc/-/nyc-8.4.0.tgz#660371c807caef0427fb9b0948f74180624ea6e4" - dependencies: - archy "^1.0.0" - arrify "^1.0.1" - caching-transform "^1.0.0" - convert-source-map "^1.3.0" - default-require-extensions "^1.0.0" - find-cache-dir "^0.1.1" - find-up "^1.1.2" - foreground-child "^1.5.3" - glob "^7.0.6" - istanbul-lib-coverage "^1.0.0" - istanbul-lib-hook "^1.0.0-alpha.4" - istanbul-lib-instrument "^1.2.0" - istanbul-lib-report "^1.0.0-alpha.3" - istanbul-lib-source-maps "^1.0.2" - istanbul-reports "^1.0.0" - md5-hex "^1.2.0" - micromatch "^2.3.11" - mkdirp "^0.5.0" - resolve-from "^2.0.0" - rimraf "^2.5.4" - signal-exit "^3.0.1" - spawn-wrap "^1.2.4" - test-exclude "^2.1.3" - yargs "^6.0.0" - yargs-parser "^4.0.2" - -oauth-sign@~0.8.1, oauth-sign@~0.8.2: - version "0.8.2" - resolved "https://registry.yarnpkg.com/oauth-sign/-/oauth-sign-0.8.2.tgz#46a6ab7f0aead8deae9ec0565780b7d4efeb9d43" - -object-assign@^4.0.1, object-assign@^4.1.0: - version "4.1.1" - resolved "https://registry.yarnpkg.com/object-assign/-/object-assign-4.1.1.tgz#2109adc7965887cfc05cbbd442cac8bfbb360863" - -object-keys@~0.4.0: - version "0.4.0" - resolved "https://registry.yarnpkg.com/object-keys/-/object-keys-0.4.0.tgz#28a6aae7428dd2c3a92f3d95f21335dd204e0336" - -object.omit@^2.0.0: - version "2.0.1" - resolved "https://registry.yarnpkg.com/object.omit/-/object.omit-2.0.1.tgz#1a9c744829f39dbb858c76ca3579ae2a54ebd1fa" - dependencies: - for-own "^0.1.4" - is-extendable "^0.1.1" - -once@^1.3.0: - version "1.4.0" - resolved "https://registry.yarnpkg.com/once/-/once-1.4.0.tgz#583b1aa775961d4b113ac17d9c50baef9dd76bd1" - dependencies: - wrappy "1" - -onetime@^1.0.0: - version "1.1.0" - resolved "https://registry.yarnpkg.com/onetime/-/onetime-1.1.0.tgz#a1f7838f8314c516f05ecefcbc4ccfe04b4ed789" - -optimist@0.6.1, optimist@^0.6.1: - version "0.6.1" - resolved "https://registry.yarnpkg.com/optimist/-/optimist-0.6.1.tgz#da3ea74686fa21a19a111c326e90eb15a0196686" - dependencies: - minimist "~0.0.1" - wordwrap "~0.0.2" - -optimist@~0.3, optimist@~0.3.5: - version "0.3.7" - resolved "https://registry.yarnpkg.com/optimist/-/optimist-0.3.7.tgz#c90941ad59e4273328923074d2cf2e7cbc6ec0d9" - dependencies: - wordwrap "~0.0.2" - -optionator@^0.8.2: - version "0.8.2" - resolved "https://registry.yarnpkg.com/optionator/-/optionator-0.8.2.tgz#364c5e409d3f4d6301d6c0b4c05bba50180aeb64" - dependencies: - deep-is "~0.1.3" - fast-levenshtein "~2.0.4" - levn "~0.3.0" - prelude-ls "~1.1.2" - type-check "~0.3.2" - wordwrap "~1.0.0" - -os-homedir@^1.0.0, os-homedir@^1.0.1: - version "1.0.2" - resolved "https://registry.yarnpkg.com/os-homedir/-/os-homedir-1.0.2.tgz#ffbc4988336e0e833de0c168c7ef152121aa7fb3" - -os-locale@^1.4.0: - version "1.4.0" - resolved "https://registry.yarnpkg.com/os-locale/-/os-locale-1.4.0.tgz#20f9f17ae29ed345e8bde583b13d2009803c14d9" - dependencies: - lcid "^1.0.0" - -os-tmpdir@^1.0.1: - version "1.0.2" - resolved "https://registry.yarnpkg.com/os-tmpdir/-/os-tmpdir-1.0.2.tgz#bbe67406c79aa85c5cfec766fe5734555dfa1274" - -"over@>= 0.0.5 < 1": - version "0.0.5" - resolved "https://registry.yarnpkg.com/over/-/over-0.0.5.tgz#f29852e70fd7e25f360e013a8ec44c82aedb5708" - -parse-glob@^3.0.4: - version "3.0.4" - resolved "https://registry.yarnpkg.com/parse-glob/-/parse-glob-3.0.4.tgz#b2c376cfb11f35513badd173ef0bb6e3a388391c" - dependencies: - glob-base "^0.3.0" - is-dotfile "^1.0.0" - is-extglob "^1.0.0" - is-glob "^2.0.0" - -parse-json@^2.2.0: - version "2.2.0" - resolved "https://registry.yarnpkg.com/parse-json/-/parse-json-2.2.0.tgz#f480f40434ef80741f8469099f8dea18f55a4dc9" - dependencies: - error-ex "^1.2.0" - -path-exists@^2.0.0: - version "2.1.0" - resolved "https://registry.yarnpkg.com/path-exists/-/path-exists-2.1.0.tgz#0feb6c64f0fc518d9a754dd5efb62c7022761f4b" - dependencies: - pinkie-promise "^2.0.0" - -path-is-absolute@^1.0.0, path-is-absolute@^1.0.1: - version "1.0.1" - resolved "https://registry.yarnpkg.com/path-is-absolute/-/path-is-absolute-1.0.1.tgz#174b9268735534ffbc7ace6bf53a5a9e1b5c5f5f" - -path-is-inside@^1.0.1: - version "1.0.2" - resolved "https://registry.yarnpkg.com/path-is-inside/-/path-is-inside-1.0.2.tgz#365417dede44430d1c11af61027facf074bdfc53" - -path-parse@^1.0.5: - version "1.0.5" - resolved "https://registry.yarnpkg.com/path-parse/-/path-parse-1.0.5.tgz#3c1adf871ea9cd6c9431b6ea2bd74a0ff055c4c1" - -path-type@^1.0.0: - version "1.1.0" - resolved "https://registry.yarnpkg.com/path-type/-/path-type-1.1.0.tgz#59c44f7ee491da704da415da5a4070ba4f8fe441" - dependencies: - graceful-fs "^4.1.2" - pify "^2.0.0" - pinkie-promise "^2.0.0" - -pause-stream@0.0.11: - version "0.0.11" - resolved "https://registry.yarnpkg.com/pause-stream/-/pause-stream-0.0.11.tgz#fe5a34b0cbce12b5aa6a2b403ee2e73b602f1445" - dependencies: - through "~2.3" - -performance-now@^2.1.0: - version "2.1.0" - resolved "https://registry.yarnpkg.com/performance-now/-/performance-now-2.1.0.tgz#6309f4e0e5fa913ec1c69307ae364b4b377c9e7b" - -pify@^2.0.0: - version "2.3.0" - resolved "https://registry.yarnpkg.com/pify/-/pify-2.3.0.tgz#ed141a6ac043a849ea588498e7dca8b15330e90c" - -pinkie-promise@^2.0.0: - version "2.0.1" - resolved "https://registry.yarnpkg.com/pinkie-promise/-/pinkie-promise-2.0.1.tgz#2135d6dfa7a358c069ac9b178776288228450ffa" - dependencies: - pinkie "^2.0.0" - -pinkie@^2.0.0: - version "2.0.4" - resolved "https://registry.yarnpkg.com/pinkie/-/pinkie-2.0.4.tgz#72556b80cfa0d48a974e80e77248e80ed4f7f870" - -pkg-dir@^1.0.0: - version "1.0.0" - resolved "https://registry.yarnpkg.com/pkg-dir/-/pkg-dir-1.0.0.tgz#7a4b508a8d5bb2d629d447056ff4e9c9314cf3d4" - dependencies: - find-up "^1.0.0" - -pluralize@^1.2.1: - version "1.2.1" - resolved "https://registry.yarnpkg.com/pluralize/-/pluralize-1.2.1.tgz#d1a21483fd22bb41e58a12fa3421823140897c45" - -prelude-ls@~1.1.2: - version "1.1.2" - resolved "https://registry.yarnpkg.com/prelude-ls/-/prelude-ls-1.1.2.tgz#21932a549f5e52ffd9a827f570e04be62a97da54" - -preserve@^0.2.0: - version "0.2.0" - resolved "https://registry.yarnpkg.com/preserve/-/preserve-0.2.0.tgz#815ed1f6ebc65926f865b310c0713bcb3315ce4b" - -pretty-bytes@^1.0.2: - version "1.0.4" - resolved "https://registry.yarnpkg.com/pretty-bytes/-/pretty-bytes-1.0.4.tgz#0a22e8210609ad35542f8c8d5d2159aff0751c84" - dependencies: - get-stdin "^4.0.1" - meow "^3.1.0" - -private@^0.1.7: - version "0.1.7" - resolved "https://registry.yarnpkg.com/private/-/private-0.1.7.tgz#68ce5e8a1ef0a23bb570cc28537b5332aba63ef1" - -process-nextick-args@~1.0.6: - version "1.0.7" - resolved "https://registry.yarnpkg.com/process-nextick-args/-/process-nextick-args-1.0.7.tgz#150e20b756590ad3f91093f25a4f2ad8bff30ba3" - -progress-stream@^1.1.0: - version "1.2.0" - resolved "https://registry.yarnpkg.com/progress-stream/-/progress-stream-1.2.0.tgz#2cd3cfea33ba3a89c9c121ec3347abe9ab125f77" - dependencies: - speedometer "~0.1.2" - through2 "~0.2.3" - -progress@^1.1.8: - version "1.1.8" - resolved "https://registry.yarnpkg.com/progress/-/progress-1.1.8.tgz#e260c78f6161cdd9b0e56cc3e0a85de17c7a57be" - -prr@~0.0.0: - version "0.0.0" - resolved "https://registry.yarnpkg.com/prr/-/prr-0.0.0.tgz#1a84b85908325501411853d0081ee3fa86e2926a" - -pseudomap@^1.0.2: - version "1.0.2" - resolved "https://registry.yarnpkg.com/pseudomap/-/pseudomap-1.0.2.tgz#f052a28da70e618917ef0a8ac34c1ae5a68286b3" - -"pullstream@>= 0.4.1 < 1": - version "0.4.1" - resolved "https://registry.yarnpkg.com/pullstream/-/pullstream-0.4.1.tgz#d6fb3bf5aed697e831150eb1002c25a3f8ae1314" - dependencies: - over ">= 0.0.5 < 1" - readable-stream "~1.0.31" - setimmediate ">= 1.0.2 < 2" - slice-stream ">= 1.0.0 < 2" - -punycode@^1.4.1: - version "1.4.1" - resolved "https://registry.yarnpkg.com/punycode/-/punycode-1.4.1.tgz#c0d5a63b2718800ad8e1eb0fa5269c84dd41845e" - -qs@~6.3.0: - version "6.3.2" - resolved "https://registry.yarnpkg.com/qs/-/qs-6.3.2.tgz#e75bd5f6e268122a2a0e0bda630b2550c166502c" - -qs@~6.5.1: - version "6.5.1" - resolved "https://registry.yarnpkg.com/qs/-/qs-6.5.1.tgz#349cdf6eef89ec45c12d7d5eb3fc0c870343a6d8" - -raf@^3.1.0: - version "3.4.0" - resolved "https://registry.yarnpkg.com/raf/-/raf-3.4.0.tgz#a28876881b4bc2ca9117d4138163ddb80f781575" - dependencies: - performance-now "^2.1.0" - -randomatic@^1.1.3: - version "1.1.7" - resolved "https://registry.yarnpkg.com/randomatic/-/randomatic-1.1.7.tgz#c7abe9cc8b87c0baa876b19fde83fd464797e38c" - dependencies: - is-number "^3.0.0" - kind-of "^4.0.0" - -read-pkg-up@^1.0.1: - version "1.0.1" - resolved "https://registry.yarnpkg.com/read-pkg-up/-/read-pkg-up-1.0.1.tgz#9d63c13276c065918d57f002a57f40a1b643fb02" - dependencies: - find-up "^1.0.0" - read-pkg "^1.0.0" - -read-pkg@^1.0.0: - version "1.1.0" - resolved "https://registry.yarnpkg.com/read-pkg/-/read-pkg-1.1.0.tgz#f5ffaa5ecd29cb31c0474bca7d756b6bb29e3f28" - dependencies: - load-json-file "^1.0.0" - normalize-package-data "^2.3.2" - path-type "^1.0.0" - -readable-stream@1.1: - version "1.1.13" - resolved "https://registry.yarnpkg.com/readable-stream/-/readable-stream-1.1.13.tgz#f6eef764f514c89e2b9e23146a75ba106756d23e" - dependencies: - core-util-is "~1.0.0" - inherits "~2.0.1" - isarray "0.0.1" - string_decoder "~0.10.x" - -readable-stream@2.2.7: - version "2.2.7" - resolved "https://registry.yarnpkg.com/readable-stream/-/readable-stream-2.2.7.tgz#07057acbe2467b22042d36f98c5ad507054e95b1" - dependencies: - buffer-shims "~1.0.0" - core-util-is "~1.0.0" - inherits "~2.0.1" - isarray "~1.0.0" - process-nextick-args "~1.0.6" - string_decoder "~1.0.0" - util-deprecate "~1.0.1" - -"readable-stream@>=1.0.33-1 <1.1.0-0", readable-stream@~1.0.0, readable-stream@~1.0.31: - version "1.0.34" - resolved "https://registry.yarnpkg.com/readable-stream/-/readable-stream-1.0.34.tgz#125820e34bc842d2f2aaafafe4c2916ee32c157c" - dependencies: - core-util-is "~1.0.0" - inherits "~2.0.1" - isarray "0.0.1" - string_decoder "~0.10.x" - -"readable-stream@^2.0.0 || ^1.1.13", readable-stream@^2.2.2: - version "2.3.3" - resolved "https://registry.yarnpkg.com/readable-stream/-/readable-stream-2.3.3.tgz#368f2512d79f9d46fdfc71349ae7878bbc1eb95c" - dependencies: - core-util-is "~1.0.0" - inherits "~2.0.3" - isarray "~1.0.0" - process-nextick-args "~1.0.6" - safe-buffer "~5.1.1" - string_decoder "~1.0.3" - util-deprecate "~1.0.1" - -readable-stream@~1.1.9: - version "1.1.14" - resolved "https://registry.yarnpkg.com/readable-stream/-/readable-stream-1.1.14.tgz#7cf4c54ef648e3813084c636dd2079e166c081d9" - dependencies: - core-util-is "~1.0.0" - inherits "~2.0.1" - isarray "0.0.1" - string_decoder "~0.10.x" - -readline2@^1.0.1: - version "1.0.1" - resolved "https://registry.yarnpkg.com/readline2/-/readline2-1.0.1.tgz#41059608ffc154757b715d9989d199ffbf372e35" - dependencies: - code-point-at "^1.0.0" - is-fullwidth-code-point "^1.0.0" - mute-stream "0.0.5" - -rechoir@^0.6.2: - version "0.6.2" - resolved "https://registry.yarnpkg.com/rechoir/-/rechoir-0.6.2.tgz#85204b54dba82d5742e28c96756ef43af50e3384" - dependencies: - resolve "^1.1.6" - -redent@^1.0.0: - version "1.0.0" - resolved "https://registry.yarnpkg.com/redent/-/redent-1.0.0.tgz#cf916ab1fd5f1f16dfb20822dd6ec7f730c2afde" - dependencies: - indent-string "^2.1.0" - strip-indent "^1.0.1" - -regenerator-runtime@^0.10.5: - version "0.10.5" - resolved "https://registry.yarnpkg.com/regenerator-runtime/-/regenerator-runtime-0.10.5.tgz#336c3efc1220adcedda2c9fab67b5a7955a33658" - -regenerator-runtime@^0.11.0: - version "0.11.0" - resolved "https://registry.yarnpkg.com/regenerator-runtime/-/regenerator-runtime-0.11.0.tgz#7e54fe5b5ccd5d6624ea6255c3473be090b802e1" - -regex-cache@^0.4.2: - version "0.4.4" - resolved "https://registry.yarnpkg.com/regex-cache/-/regex-cache-0.4.4.tgz#75bdc58a2a1496cec48a12835bc54c8d562336dd" - dependencies: - is-equal-shallow "^0.1.3" - -remove-trailing-separator@^1.0.1: - version "1.1.0" - resolved "https://registry.yarnpkg.com/remove-trailing-separator/-/remove-trailing-separator-1.1.0.tgz#c24bce2a283adad5bc3f58e0d48249b92379d8ef" - -repeat-element@^1.1.2: - version "1.1.2" - resolved "https://registry.yarnpkg.com/repeat-element/-/repeat-element-1.1.2.tgz#ef089a178d1483baae4d93eb98b4f9e4e11d990a" - -repeat-string@^1.5.2: - version "1.6.1" - resolved "https://registry.yarnpkg.com/repeat-string/-/repeat-string-1.6.1.tgz#8dcae470e1c88abc2d600fff4a776286da75e637" - -repeating@^2.0.0: - version "2.0.1" - resolved "https://registry.yarnpkg.com/repeating/-/repeating-2.0.1.tgz#5214c53a926d3552707527fbab415dbc08d06dda" - dependencies: - is-finite "^1.0.0" - -request@2.79.0: - version "2.79.0" - resolved "https://registry.yarnpkg.com/request/-/request-2.79.0.tgz#4dfe5bf6be8b8cdc37fcf93e04b65577722710de" - dependencies: - aws-sign2 "~0.6.0" - aws4 "^1.2.1" - caseless "~0.11.0" - combined-stream "~1.0.5" - extend "~3.0.0" - forever-agent "~0.6.1" - form-data "~2.1.1" - har-validator "~2.0.6" - hawk "~3.1.3" - http-signature "~1.1.0" - is-typedarray "~1.0.0" - isstream "~0.1.2" - json-stringify-safe "~5.0.1" - mime-types "~2.1.7" - oauth-sign "~0.8.1" - qs "~6.3.0" - stringstream "~0.0.4" - tough-cookie "~2.3.0" - tunnel-agent "~0.4.1" - uuid "^3.0.0" - -request@^2.34.0, request@^2.45.0, request@^2.65.0: - version "2.83.0" - resolved "https://registry.yarnpkg.com/request/-/request-2.83.0.tgz#ca0b65da02ed62935887808e6f510381034e3356" - dependencies: - aws-sign2 "~0.7.0" - aws4 "^1.6.0" - caseless "~0.12.0" - combined-stream "~1.0.5" - extend "~3.0.1" - forever-agent "~0.6.1" - form-data "~2.3.1" - har-validator "~5.0.3" - hawk "~6.0.2" - http-signature "~1.2.0" - is-typedarray "~1.0.0" - isstream "~0.1.2" - json-stringify-safe "~5.0.1" - mime-types "~2.1.17" - oauth-sign "~0.8.2" - performance-now "^2.1.0" - qs "~6.5.1" - safe-buffer "^5.1.1" - stringstream "~0.0.5" - tough-cookie "~2.3.3" - tunnel-agent "^0.6.0" - uuid "^3.1.0" - -require-directory@^2.1.1: - version "2.1.1" - resolved "https://registry.yarnpkg.com/require-directory/-/require-directory-2.1.1.tgz#8c64ad5fd30dab1c976e2344ffe7f792a6a6df42" - -require-main-filename@^1.0.1: - version "1.0.1" - resolved "https://registry.yarnpkg.com/require-main-filename/-/require-main-filename-1.0.1.tgz#97f717b69d48784f5f526a6c5aa8ffdda055a4d1" - -require-uncached@^1.0.2: - version "1.0.3" - resolved "https://registry.yarnpkg.com/require-uncached/-/require-uncached-1.0.3.tgz#4e0d56d6c9662fd31e43011c4b95aa49955421d3" - dependencies: - caller-path "^0.1.0" - resolve-from "^1.0.0" - -require_optional@~1.0.0: - version "1.0.1" - resolved "https://registry.yarnpkg.com/require_optional/-/require_optional-1.0.1.tgz#4cf35a4247f64ca3df8c2ef208cc494b1ca8fc2e" - dependencies: - resolve-from "^2.0.0" - semver "^5.1.0" - -requizzle@~0.2.0: - version "0.2.1" - resolved "https://registry.yarnpkg.com/requizzle/-/requizzle-0.2.1.tgz#6943c3530c4d9a7e46f1cddd51c158fc670cdbde" - dependencies: - underscore "~1.6.0" - -resolve-from@^1.0.0: - version "1.0.1" - resolved "https://registry.yarnpkg.com/resolve-from/-/resolve-from-1.0.1.tgz#26cbfe935d1aeeeabb29bc3fe5aeb01e93d44226" - -resolve-from@^2.0.0: - version "2.0.0" - resolved "https://registry.yarnpkg.com/resolve-from/-/resolve-from-2.0.0.tgz#9480ab20e94ffa1d9e80a804c7ea147611966b57" - -resolve@^1.1.6: - version "1.4.0" - resolved "https://registry.yarnpkg.com/resolve/-/resolve-1.4.0.tgz#a75be01c53da25d934a98ebd0e4c4a7312f92a86" - dependencies: - path-parse "^1.0.5" - -restore-cursor@^1.0.1: - version "1.0.1" - resolved "https://registry.yarnpkg.com/restore-cursor/-/restore-cursor-1.0.1.tgz#34661f46886327fed2991479152252df92daa541" - dependencies: - exit-hook "^1.0.0" - onetime "^1.0.0" - -right-align@^0.1.1: - version "0.1.3" - resolved "https://registry.yarnpkg.com/right-align/-/right-align-0.1.3.tgz#61339b722fe6a3515689210d24e14c96148613ef" - dependencies: - align-text "^0.1.1" - -rimraf@2, rimraf@^2.2.8, rimraf@^2.3.3, rimraf@^2.5.4, rimraf@^2.6.1: - version "2.6.2" - resolved "https://registry.yarnpkg.com/rimraf/-/rimraf-2.6.2.tgz#2ed8150d24a16ea8651e6d6ef0f47c4158ce7a36" - dependencies: - glob "^7.0.5" - -rimraf@2.2.6: - version "2.2.6" - resolved "https://registry.yarnpkg.com/rimraf/-/rimraf-2.2.6.tgz#c59597569b14d956ad29cacc42bdddf5f0ea4f4c" - -rimraf@2.5.4: - version "2.5.4" - resolved "https://registry.yarnpkg.com/rimraf/-/rimraf-2.5.4.tgz#96800093cbf1a0c86bd95b4625467535c29dfa04" - dependencies: - glob "^7.0.5" - -run-async@^0.1.0: - version "0.1.0" - resolved "https://registry.yarnpkg.com/run-async/-/run-async-0.1.0.tgz#c8ad4a5e110661e402a7d21b530e009f25f8e389" - dependencies: - once "^1.3.0" - -rx-lite@^3.1.2: - version "3.1.2" - resolved "https://registry.yarnpkg.com/rx-lite/-/rx-lite-3.1.2.tgz#19ce502ca572665f3b647b10939f97fd1615f102" - -safe-buffer@^5.0.1, safe-buffer@^5.1.1, safe-buffer@~5.1.0, safe-buffer@~5.1.1: - version "5.1.1" - resolved "https://registry.yarnpkg.com/safe-buffer/-/safe-buffer-5.1.1.tgz#893312af69b2123def71f57889001671eeb2c853" - -"semver@2 || 3 || 4 || 5", semver@^5.0.1, semver@^5.0.3, semver@^5.1.0, semver@^5.3.0: - version "5.4.1" - resolved "https://registry.yarnpkg.com/semver/-/semver-5.4.1.tgz#e059c09d8571f0540823733433505d3a2f00b18e" - -semver@5.3.0: - version "5.3.0" - resolved "https://registry.yarnpkg.com/semver/-/semver-5.3.0.tgz#9b2ce5d3de02d17c6012ad326aa6b4d0cf54f94f" - -semver@~5.1.0: - version "5.1.1" - resolved "https://registry.yarnpkg.com/semver/-/semver-5.1.1.tgz#a3292a373e6f3e0798da0b20641b9a9c5bc47e19" - -set-blocking@^2.0.0: - version "2.0.0" - resolved "https://registry.yarnpkg.com/set-blocking/-/set-blocking-2.0.0.tgz#045f9782d011ae9a6803ddd382b24392b3d890f7" - -"setimmediate@>= 1.0.1 < 2", "setimmediate@>= 1.0.2 < 2": - version "1.0.5" - resolved "https://registry.yarnpkg.com/setimmediate/-/setimmediate-1.0.5.tgz#290cbb232e306942d7d7ea9b83732ab7856f8285" - -shelljs@^0.7.5: - version "0.7.8" - resolved "https://registry.yarnpkg.com/shelljs/-/shelljs-0.7.8.tgz#decbcf874b0d1e5fb72e14b164a9683048e9acb3" - dependencies: - glob "^7.0.0" - interpret "^1.0.0" - rechoir "^0.6.2" - -signal-exit@^3.0.0, signal-exit@^3.0.1, signal-exit@^3.0.2: - version "3.0.2" - resolved "https://registry.yarnpkg.com/signal-exit/-/signal-exit-3.0.2.tgz#b5fdc08f1287ea1178628e415e25132b73646c6d" - -single-line-log@^1.1.2: - version "1.1.2" - resolved "https://registry.yarnpkg.com/single-line-log/-/single-line-log-1.1.2.tgz#c2f83f273a3e1a16edb0995661da0ed5ef033364" - dependencies: - string-width "^1.0.1" - -slash@^1.0.0: - version "1.0.0" - resolved "https://registry.yarnpkg.com/slash/-/slash-1.0.0.tgz#c41f2f6c39fc16d1cd17ad4b5d896114ae470d55" - -slice-ansi@0.0.4: - version "0.0.4" - resolved "https://registry.yarnpkg.com/slice-ansi/-/slice-ansi-0.0.4.tgz#edbf8903f66f7ce2f8eafd6ceed65e264c831b35" - -"slice-stream@>= 1.0.0 < 2": - version "1.0.0" - resolved "https://registry.yarnpkg.com/slice-stream/-/slice-stream-1.0.0.tgz#5b33bd66f013b1a7f86460b03d463dec39ad3ea0" - dependencies: - readable-stream "~1.0.31" - -slide@^1.1.5: - version "1.1.6" - resolved "https://registry.yarnpkg.com/slide/-/slide-1.1.6.tgz#56eb027d65b4d2dce6cb2e2d32c4d4afc9e1d707" - -sntp@1.x.x: - version "1.0.9" - resolved "https://registry.yarnpkg.com/sntp/-/sntp-1.0.9.tgz#6541184cc90aeea6c6e7b35e2659082443c66198" - dependencies: - hoek "2.x.x" - -sntp@2.x.x: - version "2.0.2" - resolved "https://registry.yarnpkg.com/sntp/-/sntp-2.0.2.tgz#5064110f0af85f7cfdb7d6b67a40028ce52b4b2b" - dependencies: - hoek "4.x.x" - -source-map-support@^0.4.15: - version "0.4.18" - resolved "https://registry.yarnpkg.com/source-map-support/-/source-map-support-0.4.18.tgz#0286a6de8be42641338594e97ccea75f0a2c585f" - dependencies: - source-map "^0.5.6" - -source-map@^0.4.4: - version "0.4.4" - resolved "https://registry.yarnpkg.com/source-map/-/source-map-0.4.4.tgz#eba4f5da9c0dc999de68032d8b4f76173652036b" - dependencies: - amdefine ">=0.0.4" - -source-map@^0.5.3, source-map@^0.5.6, source-map@~0.5.1: - version "0.5.7" - resolved "https://registry.yarnpkg.com/source-map/-/source-map-0.5.7.tgz#8a039d2d1021d22d1ea14c80d8ea468ba2ef3fcc" - -source-map@~0.1.30, source-map@~0.1.7: - version "0.1.43" - resolved "https://registry.yarnpkg.com/source-map/-/source-map-0.1.43.tgz#c24bc146ca517c1471f5dacbe2571b2b7f9e3346" - dependencies: - amdefine ">=0.0.4" - -spawn-wrap@^1.2.4: - version "1.3.8" - resolved "https://registry.yarnpkg.com/spawn-wrap/-/spawn-wrap-1.3.8.tgz#fa2a79b990cbb0bb0018dca6748d88367b19ec31" - dependencies: - foreground-child "^1.5.6" - mkdirp "^0.5.0" - os-homedir "^1.0.1" - rimraf "^2.3.3" - signal-exit "^3.0.2" - which "^1.2.4" - -spdx-correct@~1.0.0: - version "1.0.2" - resolved "https://registry.yarnpkg.com/spdx-correct/-/spdx-correct-1.0.2.tgz#4b3073d933ff51f3912f03ac5519498a4150db40" - dependencies: - spdx-license-ids "^1.0.2" - -spdx-expression-parse@~1.0.0: - version "1.0.4" - resolved "https://registry.yarnpkg.com/spdx-expression-parse/-/spdx-expression-parse-1.0.4.tgz#9bdf2f20e1f40ed447fbe273266191fced51626c" - -spdx-license-ids@^1.0.2: - version "1.2.2" - resolved "https://registry.yarnpkg.com/spdx-license-ids/-/spdx-license-ids-1.2.2.tgz#c9df7a3424594ade6bd11900d596696dc06bac57" - -speedometer@~0.1.2: - version "0.1.4" - resolved "https://registry.yarnpkg.com/speedometer/-/speedometer-0.1.4.tgz#9876dbd2a169d3115402d48e6ea6329c8816a50d" - -split2@^0.2.1: - version "0.2.1" - resolved "https://registry.yarnpkg.com/split2/-/split2-0.2.1.tgz#02ddac9adc03ec0bb78c1282ec079ca6e85ae900" - dependencies: - through2 "~0.6.1" - -split@0.3: - version "0.3.3" - resolved "https://registry.yarnpkg.com/split/-/split-0.3.3.tgz#cd0eea5e63a211dfff7eb0f091c4133e2d0dd28f" - dependencies: - through "2" - -sprintf-js@~1.0.2: - version "1.0.3" - resolved "https://registry.yarnpkg.com/sprintf-js/-/sprintf-js-1.0.3.tgz#04e6926f662895354f3dd015203633b857297e2c" - -sshpk@^1.7.0: - version "1.13.1" - resolved "https://registry.yarnpkg.com/sshpk/-/sshpk-1.13.1.tgz#512df6da6287144316dc4c18fe1cf1d940739be3" - dependencies: - asn1 "~0.2.3" - assert-plus "^1.0.0" - dashdash "^1.12.0" - getpass "^0.1.1" - optionalDependencies: - bcrypt-pbkdf "^1.0.0" - ecc-jsbn "~0.1.1" - jsbn "~0.1.0" - tweetnacl "~0.14.0" - -stream-combiner@~0.0.4: - version "0.0.4" - resolved "https://registry.yarnpkg.com/stream-combiner/-/stream-combiner-0.0.4.tgz#4d5e433c185261dde623ca3f44c586bcf5c4ad14" - dependencies: - duplexer "~0.1.1" - -string-width@^1.0.1, string-width@^1.0.2: - version "1.0.2" - resolved "https://registry.yarnpkg.com/string-width/-/string-width-1.0.2.tgz#118bdf5b8cdc51a2a7e70d211e07e2b0b9b107d3" - dependencies: - code-point-at "^1.0.0" - is-fullwidth-code-point "^1.0.0" - strip-ansi "^3.0.0" - -string-width@^2.0.0: - version "2.1.1" - resolved "https://registry.yarnpkg.com/string-width/-/string-width-2.1.1.tgz#ab93f27a8dc13d28cac815c462143a6d9012ae9e" - dependencies: - is-fullwidth-code-point "^2.0.0" - strip-ansi "^4.0.0" - -string_decoder@~0.10.x: - version "0.10.31" - resolved "https://registry.yarnpkg.com/string_decoder/-/string_decoder-0.10.31.tgz#62e203bc41766c6c28c9fc84301dab1c5310fa94" - -string_decoder@~1.0.0, string_decoder@~1.0.3: - version "1.0.3" - resolved "https://registry.yarnpkg.com/string_decoder/-/string_decoder-1.0.3.tgz#0fc67d7c141825de94282dd536bec6b9bce860ab" - dependencies: - safe-buffer "~5.1.0" - -stringstream@~0.0.4, stringstream@~0.0.5: - version "0.0.5" - resolved "https://registry.yarnpkg.com/stringstream/-/stringstream-0.0.5.tgz#4e484cd4de5a0bbbee18e46307710a8a81621878" - -strip-ansi@^3.0.0, strip-ansi@^3.0.1: - version "3.0.1" - resolved "https://registry.yarnpkg.com/strip-ansi/-/strip-ansi-3.0.1.tgz#6a385fb8853d952d5ff05d0e8aaf94278dc63dcf" - dependencies: - ansi-regex "^2.0.0" - -strip-ansi@^4.0.0: - version "4.0.0" - resolved "https://registry.yarnpkg.com/strip-ansi/-/strip-ansi-4.0.0.tgz#a8479022eb1ac368a871389b635262c505ee368f" - dependencies: - ansi-regex "^3.0.0" - -strip-bom@^2.0.0: - version "2.0.0" - resolved "https://registry.yarnpkg.com/strip-bom/-/strip-bom-2.0.0.tgz#6219a85616520491f35788bdbf1447a99c7e6b0e" - dependencies: - is-utf8 "^0.2.0" - -strip-bom@^3.0.0: - version "3.0.0" - resolved "https://registry.yarnpkg.com/strip-bom/-/strip-bom-3.0.0.tgz#2334c18e9c759f7bdd56fdef7e9ae3d588e68ed3" - -strip-indent@^1.0.1: - version "1.0.1" - resolved "https://registry.yarnpkg.com/strip-indent/-/strip-indent-1.0.1.tgz#0c7962a6adefa7bbd4ac366460a638552ae1a0a2" - dependencies: - get-stdin "^4.0.1" - -strip-json-comments@~1.0.2: - version "1.0.4" - resolved "https://registry.yarnpkg.com/strip-json-comments/-/strip-json-comments-1.0.4.tgz#1e15fbcac97d3ee99bf2d73b4c656b082bbafb91" - -strip-json-comments@~2.0.1: - version "2.0.1" - resolved "https://registry.yarnpkg.com/strip-json-comments/-/strip-json-comments-2.0.1.tgz#3c531942e908c2697c0ec344858c286c7ca0a60a" - -supports-color@^2.0.0: - version "2.0.0" - resolved "https://registry.yarnpkg.com/supports-color/-/supports-color-2.0.0.tgz#535d045ce6b6363fa40117084629995e9df324c7" - -supports-color@^3.1.2: - version "3.2.3" - resolved "https://registry.yarnpkg.com/supports-color/-/supports-color-3.2.3.tgz#65ac0504b3954171d8a64946b2ae3cbb8a5f54f6" - dependencies: - has-flag "^1.0.0" - -table@^3.7.4, table@^3.7.8: - version "3.8.3" - resolved "https://registry.yarnpkg.com/table/-/table-3.8.3.tgz#2bbc542f0fda9861a755d3947fefd8b3f513855f" - dependencies: - ajv "^4.7.0" - ajv-keywords "^1.0.0" - chalk "^1.1.1" - lodash "^4.0.0" - slice-ansi "0.0.4" - string-width "^2.0.0" - -"taffydb@https://github.com/hegemonic/taffydb/tarball/7d100bcee0e997ee4977e273cdce60bd8933050e": - version "2.6.2" - resolved "https://github.com/hegemonic/taffydb/tarball/7d100bcee0e997ee4977e273cdce60bd8933050e#3c549d2f5712d7d1d109ad6bb1a4084f1b7add4e" - -tar@~2.2.1: - version "2.2.1" - resolved "https://registry.yarnpkg.com/tar/-/tar-2.2.1.tgz#8e4d2a256c0e2185c6b18ad694aec968b83cb1d1" - dependencies: - block-stream "*" - fstream "^1.0.2" - inherits "2" - -test-exclude@^2.1.3: - version "2.1.3" - resolved "https://registry.yarnpkg.com/test-exclude/-/test-exclude-2.1.3.tgz#a8d8968e1da83266f9864f2852c55e220f06434a" - dependencies: - arrify "^1.0.1" - micromatch "^2.3.11" - object-assign "^4.1.0" - read-pkg-up "^1.0.1" - require-main-filename "^1.0.1" - -text-table@~0.2.0: - version "0.2.0" - resolved "https://registry.yarnpkg.com/text-table/-/text-table-0.2.0.tgz#7f5ee823ae805207c00af2df4a84ec3fcfa570b4" - -throttleit@0.0.2: - version "0.0.2" - resolved "https://registry.yarnpkg.com/throttleit/-/throttleit-0.0.2.tgz#cfedf88e60c00dd9697b61fdd2a8343a9b680eaf" - -through2@^0.6.1, through2@^0.6.3, through2@~0.6.1: - version "0.6.5" - resolved "https://registry.yarnpkg.com/through2/-/through2-0.6.5.tgz#41ab9c67b29d57209071410e1d7a7a968cd3ad48" - dependencies: - readable-stream ">=1.0.33-1 <1.1.0-0" - xtend ">=4.0.0 <4.1.0-0" - -through2@~0.2.3: - version "0.2.3" - resolved "https://registry.yarnpkg.com/through2/-/through2-0.2.3.tgz#eb3284da4ea311b6cc8ace3653748a52abf25a3f" - dependencies: - readable-stream "~1.1.9" - xtend "~2.1.1" - -through@2, "through@>=2.2.7 <3", through@^2.3.6, through@~2.3, through@~2.3.1: - version "2.3.8" - resolved "https://registry.yarnpkg.com/through/-/through-2.3.8.tgz#0dd4c9ffaabc357960b1b724115d7e0e86a2e1f5" - -tildify@~1.2.0: - version "1.2.0" - resolved "https://registry.yarnpkg.com/tildify/-/tildify-1.2.0.tgz#dcec03f55dca9b7aa3e5b04f21817eb56e63588a" - dependencies: - os-homedir "^1.0.0" - -to-fast-properties@^1.0.3: - version "1.0.3" - resolved "https://registry.yarnpkg.com/to-fast-properties/-/to-fast-properties-1.0.3.tgz#b83571fa4d8c25b82e231b06e3a3055de4ca1a47" - -tough-cookie@~2.3.0, tough-cookie@~2.3.3: - version "2.3.3" - resolved "https://registry.yarnpkg.com/tough-cookie/-/tough-cookie-2.3.3.tgz#0b618a5565b6dea90bf3425d04d55edc475a7561" - dependencies: - punycode "^1.4.1" - -"traverse@>=0.3.0 <0.4": - version "0.3.9" - resolved "https://registry.yarnpkg.com/traverse/-/traverse-0.3.9.tgz#717b8f220cc0bb7b44e40514c22b2e8bbc70d8b9" - -trim-newlines@^1.0.0: - version "1.0.0" - resolved "https://registry.yarnpkg.com/trim-newlines/-/trim-newlines-1.0.0.tgz#5887966bb582a4503a41eb524f7d35011815a613" - -trim-right@^1.0.1: - version "1.0.1" - resolved "https://registry.yarnpkg.com/trim-right/-/trim-right-1.0.1.tgz#cb2e1203067e0c8de1f614094b9fe45704ea6003" - -tryit@^1.0.1: - version "1.0.3" - resolved "https://registry.yarnpkg.com/tryit/-/tryit-1.0.3.tgz#393be730a9446fd1ead6da59a014308f36c289cb" - -tunnel-agent@^0.6.0: - version "0.6.0" - resolved "https://registry.yarnpkg.com/tunnel-agent/-/tunnel-agent-0.6.0.tgz#27a5dea06b36b04a0a9966774b290868f0fc40fd" - dependencies: - safe-buffer "^5.0.1" - -tunnel-agent@~0.4.1: - version "0.4.3" - resolved "https://registry.yarnpkg.com/tunnel-agent/-/tunnel-agent-0.4.3.tgz#6373db76909fe570e08d73583365ed828a74eeeb" - -tweetnacl@^0.14.3, tweetnacl@~0.14.0: - version "0.14.5" - resolved "https://registry.yarnpkg.com/tweetnacl/-/tweetnacl-0.14.5.tgz#5ae68177f192d4456269d108afa93ff8743f4f64" - -type-check@~0.3.2: - version "0.3.2" - resolved "https://registry.yarnpkg.com/type-check/-/type-check-0.3.2.tgz#5884cab512cf1d355e3fb784f30804b2b520db72" - dependencies: - prelude-ls "~1.1.2" - -typedarray@^0.0.6: - version "0.0.6" - resolved "https://registry.yarnpkg.com/typedarray/-/typedarray-0.0.6.tgz#867ac74e3864187b1d3d47d996a78ec5c8830777" - -uglify-js@^2.6: - version "2.8.29" - resolved "https://registry.yarnpkg.com/uglify-js/-/uglify-js-2.8.29.tgz#29c5733148057bb4e1f75df35b7a9cb72e6a59dd" - dependencies: - source-map "~0.5.1" - yargs "~3.10.0" - optionalDependencies: - uglify-to-browserify "~1.0.0" - -uglify-js@~2.3: - version "2.3.6" - resolved "https://registry.yarnpkg.com/uglify-js/-/uglify-js-2.3.6.tgz#fa0984770b428b7a9b2a8058f46355d14fef211a" - dependencies: - async "~0.2.6" - optimist "~0.3.5" - source-map "~0.1.7" - -uglify-to-browserify@~1.0.0: - version "1.0.2" - resolved "https://registry.yarnpkg.com/uglify-to-browserify/-/uglify-to-browserify-1.0.2.tgz#6e0924d6bda6b5afe349e39a6d632850a0f882b7" - -underscore-contrib@~0.3.0: - version "0.3.0" - resolved "https://registry.yarnpkg.com/underscore-contrib/-/underscore-contrib-0.3.0.tgz#665b66c24783f8fa2b18c9f8cbb0e2c7d48c26c7" - dependencies: - underscore "1.6.0" - -underscore@1.6.0, underscore@~1.6.0: - version "1.6.0" - resolved "https://registry.yarnpkg.com/underscore/-/underscore-1.6.0.tgz#8b38b10cacdef63337b8b24e4ff86d45aea529a8" - -underscore@~1.8.3: - version "1.8.3" - resolved "https://registry.yarnpkg.com/underscore/-/underscore-1.8.3.tgz#4f3fb53b106e6097fcf9cb4109f2a5e9bdfa5022" - -untildify@~2.1.0: - version "2.1.0" - resolved "https://registry.yarnpkg.com/untildify/-/untildify-2.1.0.tgz#17eb2807987f76952e9c0485fc311d06a826a2e0" - dependencies: - os-homedir "^1.0.0" - -unzip@^0.1.11: - version "0.1.11" - resolved "https://registry.yarnpkg.com/unzip/-/unzip-0.1.11.tgz#89749c63b058d7d90d619f86b98aa1535d3b97f0" - dependencies: - binary ">= 0.3.0 < 1" - fstream ">= 0.1.30 < 1" - match-stream ">= 0.0.2 < 1" - pullstream ">= 0.4.1 < 1" - readable-stream "~1.0.31" - setimmediate ">= 1.0.1 < 2" - -user-home@^2.0.0: - version "2.0.0" - resolved "https://registry.yarnpkg.com/user-home/-/user-home-2.0.0.tgz#9c70bfd8169bc1dcbf48604e0f04b8b49cde9e9f" - dependencies: - os-homedir "^1.0.0" - -util-deprecate@~1.0.1: - version "1.0.2" - resolved "https://registry.yarnpkg.com/util-deprecate/-/util-deprecate-1.0.2.tgz#450d4dc9fa70de732762fbd2d4a28981419a0ccf" - -uuid@^3.0.0, uuid@^3.1.0: - version "3.1.0" - resolved "https://registry.yarnpkg.com/uuid/-/uuid-3.1.0.tgz#3dd3d3e790abc24d7b0d3a034ffababe28ebbc04" - -validate-npm-package-license@^3.0.1: - version "3.0.1" - resolved "https://registry.yarnpkg.com/validate-npm-package-license/-/validate-npm-package-license-3.0.1.tgz#2804babe712ad3379459acfbe24746ab2c303fbc" - dependencies: - spdx-correct "~1.0.0" - spdx-expression-parse "~1.0.0" - -verror@1.10.0: - version "1.10.0" - resolved "https://registry.yarnpkg.com/verror/-/verror-1.10.0.tgz#3a105ca17053af55d6e270c1f8288682e18da400" - dependencies: - assert-plus "^1.0.0" - core-util-is "1.0.2" - extsprintf "^1.2.0" - -which-module@^1.0.0: - version "1.0.0" - resolved "https://registry.yarnpkg.com/which-module/-/which-module-1.0.0.tgz#bba63ca861948994ff307736089e3b96026c2a4f" - -which@^1.1.1, which@^1.2.4, which@^1.2.9: - version "1.3.0" - resolved "https://registry.yarnpkg.com/which/-/which-1.3.0.tgz#ff04bdfc010ee547d780bec38e1ac1c2777d253a" - dependencies: - isexe "^2.0.0" - -window-size@0.1.0: - version "0.1.0" - resolved "https://registry.yarnpkg.com/window-size/-/window-size-0.1.0.tgz#5438cd2ea93b202efa3a19fe8887aee7c94f9c9d" - -wordwrap@0.0.2: - version "0.0.2" - resolved "https://registry.yarnpkg.com/wordwrap/-/wordwrap-0.0.2.tgz#b79669bb42ecb409f83d583cad52ca17eaa1643f" - -wordwrap@~0.0.2: - version "0.0.3" - resolved "https://registry.yarnpkg.com/wordwrap/-/wordwrap-0.0.3.tgz#a3d5da6cd5c0bc0008d37234bbaf1bed63059107" - -wordwrap@~1.0.0: - version "1.0.0" - resolved "https://registry.yarnpkg.com/wordwrap/-/wordwrap-1.0.0.tgz#27584810891456a4171c8d0226441ade90cbcaeb" - -worker-farm@^1.3.1: - version "1.5.0" - resolved "https://registry.yarnpkg.com/worker-farm/-/worker-farm-1.5.0.tgz#adfdf0cd40581465ed0a1f648f9735722afd5c8d" - dependencies: - errno "^0.1.4" - xtend "^4.0.1" - -wrap-ansi@^2.0.0: - version "2.1.0" - resolved "https://registry.yarnpkg.com/wrap-ansi/-/wrap-ansi-2.1.0.tgz#d8fc3d284dd05794fe84973caecdd1cf824fdd85" - dependencies: - string-width "^1.0.1" - strip-ansi "^3.0.1" - -wrappy@1: - version "1.0.2" - resolved "https://registry.yarnpkg.com/wrappy/-/wrappy-1.0.2.tgz#b5243d8f3ec1aa35f1364605bc0d1036e30ab69f" - -wrench@~1.5.8: - version "1.5.9" - resolved "https://registry.yarnpkg.com/wrench/-/wrench-1.5.9.tgz#411691c63a9b2531b1700267279bdeca23b2142a" - -write-file-atomic@^1.1.4: - version "1.3.4" - resolved "https://registry.yarnpkg.com/write-file-atomic/-/write-file-atomic-1.3.4.tgz#f807a4f0b1d9e913ae7a48112e6cc3af1991b45f" - dependencies: - graceful-fs "^4.1.11" - imurmurhash "^0.1.4" - slide "^1.1.5" - -write@^0.2.1: - version "0.2.1" - resolved "https://registry.yarnpkg.com/write/-/write-0.2.1.tgz#5fc03828e264cea3fe91455476f7a3c566cb0757" - dependencies: - mkdirp "^0.5.1" - -"xtend@>=4.0.0 <4.1.0-0", xtend@^4.0.0, xtend@^4.0.1: - version "4.0.1" - resolved "https://registry.yarnpkg.com/xtend/-/xtend-4.0.1.tgz#a5c6d532be656e23db820efb943a1f04998d63af" - -xtend@~2.1.1: - version "2.1.2" - resolved "https://registry.yarnpkg.com/xtend/-/xtend-2.1.2.tgz#6efecc2a4dad8e6962c4901b337ce7ba87b5d28b" - dependencies: - object-keys "~0.4.0" - -y18n@^3.2.1: - version "3.2.1" - resolved "https://registry.yarnpkg.com/y18n/-/y18n-3.2.1.tgz#6d15fba884c08679c0d77e88e7759e811e07fa41" - -yallist@^2.1.2: - version "2.1.2" - resolved "https://registry.yarnpkg.com/yallist/-/yallist-2.1.2.tgz#1c11f9218f076089a47dd512f93c6699a6a81d52" - -yargs-parser@^4.0.2, yargs-parser@^4.2.0: - version "4.2.1" - resolved "https://registry.yarnpkg.com/yargs-parser/-/yargs-parser-4.2.1.tgz#29cceac0dc4f03c6c87b4a9f217dd18c9f74871c" - dependencies: - camelcase "^3.0.0" - -yargs@^6.0.0: - version "6.6.0" - resolved "https://registry.yarnpkg.com/yargs/-/yargs-6.6.0.tgz#782ec21ef403345f830a808ca3d513af56065208" - dependencies: - camelcase "^3.0.0" - cliui "^3.2.0" - decamelize "^1.1.1" - get-caller-file "^1.0.1" - os-locale "^1.4.0" - read-pkg-up "^1.0.1" - require-directory "^2.1.1" - require-main-filename "^1.0.1" - set-blocking "^2.0.0" - string-width "^1.0.2" - which-module "^1.0.0" - y18n "^3.2.1" - yargs-parser "^4.2.0" - -yargs@~3.10.0: - version "3.10.0" - resolved "https://registry.yarnpkg.com/yargs/-/yargs-3.10.0.tgz#f7ee7bd857dd7c1d2d38c0e74efbd681d1431fd1" - dependencies: - camelcase "^1.0.2" - cliui "^2.1.0" - decamelize "^1.0.0" - window-size "0.1.0" diff --git a/ts-ticket-office-service/node_modules/morgan/HISTORY.md b/ts-ticket-office-service/node_modules/morgan/HISTORY.md index e15203268..638457b15 100644 --- a/ts-ticket-office-service/node_modules/morgan/HISTORY.md +++ b/ts-ticket-office-service/node_modules/morgan/HISTORY.md @@ -1,3 +1,10 @@ +1.9.1 / 2018-09-10 +================== + + * Fix using special characters in format + * deps: depd@~1.1.2 + - perf: remove argument reassignment + 1.9.0 / 2017-09-26 ================== diff --git a/ts-ticket-office-service/node_modules/morgan/README.md b/ts-ticket-office-service/node_modules/morgan/README.md index ce00d6233..ba8b256aa 100644 --- a/ts-ticket-office-service/node_modules/morgan/README.md +++ b/ts-ticket-office-service/node_modules/morgan/README.md @@ -4,7 +4,6 @@ [![NPM Downloads][downloads-image]][downloads-url] [![Build Status][travis-image]][travis-url] [![Test Coverage][coveralls-image]][coveralls-url] -[![Gratipay][gratipay-image]][gratipay-url] HTTP request logger middleware for node.js @@ -188,11 +187,13 @@ The user authenticated as part of Basic auth for the request. ##### :req[header] -The given `header` of the request. +The given `header` of the request. If the header is not present, the +value will be displayed as `"-"` in the log. ##### :res[header] -The given `header` of the response. +The given `header` of the response. If the header is not present, the +value will be displayed as `"-"` in the log. ##### :response-time[digits] @@ -293,10 +294,10 @@ var path = require('path') var app = express() // create a write stream (in append mode) -var accessLogStream = fs.createWriteStream(path.join(__dirname, 'access.log'), {flags: 'a'}) +var accessLogStream = fs.createWriteStream(path.join(__dirname, 'access.log'), { flags: 'a' }) // setup the logger -app.use(morgan('combined', {stream: accessLogStream})) +app.use(morgan('combined', { stream: accessLogStream })) app.get('/', function (req, res) { res.send('hello, world!') @@ -329,7 +330,7 @@ var accessLogStream = rfs('access.log', { }) // setup the logger -app.use(morgan('combined', {stream: accessLogStream})) +app.use(morgan('combined', { stream: accessLogStream })) app.get('/', function (req, res) { res.send('hello, world!') @@ -363,7 +364,7 @@ app.use(morgan('dev', { // log all requests to access.log app.use(morgan('common', { - stream: fs.createWriteStream(path.join(__dirname, 'access.log'), {flags: 'a'}) + stream: fs.createWriteStream(path.join(__dirname, 'access.log'), { flags: 'a' }) })) app.get('/', function (req, res) { @@ -411,5 +412,3 @@ function assignId (req, res, next) { [coveralls-url]: https://coveralls.io/r/expressjs/morgan?branch=master [downloads-image]: https://img.shields.io/npm/dm/morgan.svg [downloads-url]: https://npmjs.org/package/morgan -[gratipay-image]: https://img.shields.io/gratipay/dougwilson.svg -[gratipay-url]: https://www.gratipay.com/dougwilson/ diff --git a/ts-ticket-office-service/node_modules/morgan/index.js b/ts-ticket-office-service/node_modules/morgan/index.js index 7b6dadaa1..703e19226 100644 --- a/ts-ticket-office-service/node_modules/morgan/index.js +++ b/ts-ticket-office-service/node_modules/morgan/index.js @@ -189,9 +189,9 @@ morgan.format('dev', function developmentFormatLine (tokens, req, res) { // get status color var color = status >= 500 ? 31 // red : status >= 400 ? 33 // yellow - : status >= 300 ? 36 // cyan - : status >= 200 ? 32 // green - : 0 // no color + : status >= 300 ? 36 // cyan + : status >= 200 ? 32 // green + : 0 // no color // get colored function var fn = developmentFormatLine[color] @@ -375,8 +375,8 @@ function compile (format) { throw new TypeError('argument format must be a string') } - var fmt = format.replace(/"/g, '\\"') - var js = ' "use strict"\n return "' + fmt.replace(/:([-\w]{2,})(?:\[([^\]]+)\])?/g, function (_, name, arg) { + var fmt = String(JSON.stringify(format)) + var js = ' "use strict"\n return ' + fmt.replace(/:([-\w]{2,})(?:\[([^\]]+)\])?/g, function (_, name, arg) { var tokenArguments = 'req, res' var tokenFunction = 'tokens[' + String(JSON.stringify(name)) + ']' @@ -385,7 +385,7 @@ function compile (format) { } return '" +\n (' + tokenFunction + '(' + tokenArguments + ') || "-") + "' - }) + '"' + }) // eslint-disable-next-line no-new-func return new Function('tokens, req, res', js) diff --git a/ts-ticket-office-service/node_modules/morgan/node_modules/depd/History.md b/ts-ticket-office-service/node_modules/morgan/node_modules/depd/History.md new file mode 100644 index 000000000..507ecb8de --- /dev/null +++ b/ts-ticket-office-service/node_modules/morgan/node_modules/depd/History.md @@ -0,0 +1,96 @@ +1.1.2 / 2018-01-11 +================== + + * perf: remove argument reassignment + * Support Node.js 0.6 to 9.x + +1.1.1 / 2017-07-27 +================== + + * Remove unnecessary `Buffer` loading + * Support Node.js 0.6 to 8.x + +1.1.0 / 2015-09-14 +================== + + * Enable strict mode in more places + * Support io.js 3.x + * Support io.js 2.x + * Support web browser loading + - Requires bundler like Browserify or webpack + +1.0.1 / 2015-04-07 +================== + + * Fix `TypeError`s when under `'use strict'` code + * Fix useless type name on auto-generated messages + * Support io.js 1.x + * Support Node.js 0.12 + +1.0.0 / 2014-09-17 +================== + + * No changes + +0.4.5 / 2014-09-09 +================== + + * Improve call speed to functions using the function wrapper + * Support Node.js 0.6 + +0.4.4 / 2014-07-27 +================== + + * Work-around v8 generating empty stack traces + +0.4.3 / 2014-07-26 +================== + + * Fix exception when global `Error.stackTraceLimit` is too low + +0.4.2 / 2014-07-19 +================== + + * Correct call site for wrapped functions and properties + +0.4.1 / 2014-07-19 +================== + + * Improve automatic message generation for function properties + +0.4.0 / 2014-07-19 +================== + + * Add `TRACE_DEPRECATION` environment variable + * Remove non-standard grey color from color output + * Support `--no-deprecation` argument + * Support `--trace-deprecation` argument + * Support `deprecate.property(fn, prop, message)` + +0.3.0 / 2014-06-16 +================== + + * Add `NO_DEPRECATION` environment variable + +0.2.0 / 2014-06-15 +================== + + * Add `deprecate.property(obj, prop, message)` + * Remove `supports-color` dependency for node.js 0.8 + +0.1.0 / 2014-06-15 +================== + + * Add `deprecate.function(fn, message)` + * Add `process.on('deprecation', fn)` emitter + * Automatically generate message when omitted from `deprecate()` + +0.0.1 / 2014-06-15 +================== + + * Fix warning for dynamic calls at singe call site + +0.0.0 / 2014-06-15 +================== + + * Initial implementation diff --git a/ts-ticket-office-service/node_modules/morgan/node_modules/depd/LICENSE b/ts-ticket-office-service/node_modules/morgan/node_modules/depd/LICENSE new file mode 100644 index 000000000..84441fbb5 --- /dev/null +++ b/ts-ticket-office-service/node_modules/morgan/node_modules/depd/LICENSE @@ -0,0 +1,22 @@ +(The MIT License) + +Copyright (c) 2014-2017 Douglas Christopher Wilson + +Permission is hereby granted, free of charge, to any person obtaining +a copy of this software and associated documentation files (the +'Software'), to deal in the Software without restriction, including +without limitation the rights to use, copy, modify, merge, publish, +distribute, sublicense, and/or sell copies of the Software, and to +permit persons to whom the Software is furnished to do so, subject to +the following conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. +IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY +CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, +TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE +SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/ts-ticket-office-service/node_modules/morgan/node_modules/depd/Readme.md b/ts-ticket-office-service/node_modules/morgan/node_modules/depd/Readme.md new file mode 100644 index 000000000..779067020 --- /dev/null +++ b/ts-ticket-office-service/node_modules/morgan/node_modules/depd/Readme.md @@ -0,0 +1,280 @@ +# depd + +[![NPM Version][npm-version-image]][npm-url] +[![NPM Downloads][npm-downloads-image]][npm-url] +[![Node.js Version][node-image]][node-url] +[![Linux Build][travis-image]][travis-url] +[![Windows Build][appveyor-image]][appveyor-url] +[![Coverage Status][coveralls-image]][coveralls-url] + +Deprecate all the things + +> With great modules comes great responsibility; mark things deprecated! + +## Install + +This module is installed directly using `npm`: + +```sh +$ npm install depd +``` + +This module can also be bundled with systems like +[Browserify](http://browserify.org/) or [webpack](https://webpack.github.io/), +though by default this module will alter it's API to no longer display or +track deprecations. + +## API + + + +```js +var deprecate = require('depd')('my-module') +``` + +This library allows you to display deprecation messages to your users. +This library goes above and beyond with deprecation warnings by +introspection of the call stack (but only the bits that it is interested +in). + +Instead of just warning on the first invocation of a deprecated +function and never again, this module will warn on the first invocation +of a deprecated function per unique call site, making it ideal to alert +users of all deprecated uses across the code base, rather than just +whatever happens to execute first. + +The deprecation warnings from this module also include the file and line +information for the call into the module that the deprecated function was +in. + +**NOTE** this library has a similar interface to the `debug` module, and +this module uses the calling file to get the boundary for the call stacks, +so you should always create a new `deprecate` object in each file and not +within some central file. + +### depd(namespace) + +Create a new deprecate function that uses the given namespace name in the +messages and will display the call site prior to the stack entering the +file this function was called from. It is highly suggested you use the +name of your module as the namespace. + +### deprecate(message) + +Call this function from deprecated code to display a deprecation message. +This message will appear once per unique caller site. Caller site is the +first call site in the stack in a different file from the caller of this +function. + +If the message is omitted, a message is generated for you based on the site +of the `deprecate()` call and will display the name of the function called, +similar to the name displayed in a stack trace. + +### deprecate.function(fn, message) + +Call this function to wrap a given function in a deprecation message on any +call to the function. An optional message can be supplied to provide a custom +message. + +### deprecate.property(obj, prop, message) + +Call this function to wrap a given property on object in a deprecation message +on any accessing or setting of the property. An optional message can be supplied +to provide a custom message. + +The method must be called on the object where the property belongs (not +inherited from the prototype). + +If the property is a data descriptor, it will be converted to an accessor +descriptor in order to display the deprecation message. + +### process.on('deprecation', fn) + +This module will allow easy capturing of deprecation errors by emitting the +errors as the type "deprecation" on the global `process`. If there are no +listeners for this type, the errors are written to STDERR as normal, but if +there are any listeners, nothing will be written to STDERR and instead only +emitted. From there, you can write the errors in a different format or to a +logging source. + +The error represents the deprecation and is emitted only once with the same +rules as writing to STDERR. The error has the following properties: + + - `message` - This is the message given by the library + - `name` - This is always `'DeprecationError'` + - `namespace` - This is the namespace the deprecation came from + - `stack` - This is the stack of the call to the deprecated thing + +Example `error.stack` output: + +``` +DeprecationError: my-cool-module deprecated oldfunction + at Object. ([eval]-wrapper:6:22) + at Module._compile (module.js:456:26) + at evalScript (node.js:532:25) + at startup (node.js:80:7) + at node.js:902:3 +``` + +### process.env.NO_DEPRECATION + +As a user of modules that are deprecated, the environment variable `NO_DEPRECATION` +is provided as a quick solution to silencing deprecation warnings from being +output. The format of this is similar to that of `DEBUG`: + +```sh +$ NO_DEPRECATION=my-module,othermod node app.js +``` + +This will suppress deprecations from being output for "my-module" and "othermod". +The value is a list of comma-separated namespaces. To suppress every warning +across all namespaces, use the value `*` for a namespace. + +Providing the argument `--no-deprecation` to the `node` executable will suppress +all deprecations (only available in Node.js 0.8 or higher). + +**NOTE** This will not suppress the deperecations given to any "deprecation" +event listeners, just the output to STDERR. + +### process.env.TRACE_DEPRECATION + +As a user of modules that are deprecated, the environment variable `TRACE_DEPRECATION` +is provided as a solution to getting more detailed location information in deprecation +warnings by including the entire stack trace. The format of this is the same as +`NO_DEPRECATION`: + +```sh +$ TRACE_DEPRECATION=my-module,othermod node app.js +``` + +This will include stack traces for deprecations being output for "my-module" and +"othermod". The value is a list of comma-separated namespaces. To trace every +warning across all namespaces, use the value `*` for a namespace. + +Providing the argument `--trace-deprecation` to the `node` executable will trace +all deprecations (only available in Node.js 0.8 or higher). + +**NOTE** This will not trace the deperecations silenced by `NO_DEPRECATION`. + +## Display + +![message](files/message.png) + +When a user calls a function in your library that you mark deprecated, they +will see the following written to STDERR (in the given colors, similar colors +and layout to the `debug` module): + +``` +bright cyan bright yellow +| | reset cyan +| | | | +▼ ▼ ▼ ▼ +my-cool-module deprecated oldfunction [eval]-wrapper:6:22 +▲ ▲ ▲ ▲ +| | | | +namespace | | location of mycoolmod.oldfunction() call + | deprecation message + the word "deprecated" +``` + +If the user redirects their STDERR to a file or somewhere that does not support +colors, they see (similar layout to the `debug` module): + +``` +Sun, 15 Jun 2014 05:21:37 GMT my-cool-module deprecated oldfunction at [eval]-wrapper:6:22 +▲ ▲ ▲ ▲ ▲ +| | | | | +timestamp of message namespace | | location of mycoolmod.oldfunction() call + | deprecation message + the word "deprecated" +``` + +## Examples + +### Deprecating all calls to a function + +This will display a deprecated message about "oldfunction" being deprecated +from "my-module" on STDERR. + +```js +var deprecate = require('depd')('my-cool-module') + +// message automatically derived from function name +// Object.oldfunction +exports.oldfunction = deprecate.function(function oldfunction () { + // all calls to function are deprecated +}) + +// specific message +exports.oldfunction = deprecate.function(function () { + // all calls to function are deprecated +}, 'oldfunction') +``` + +### Conditionally deprecating a function call + +This will display a deprecated message about "weirdfunction" being deprecated +from "my-module" on STDERR when called with less than 2 arguments. + +```js +var deprecate = require('depd')('my-cool-module') + +exports.weirdfunction = function () { + if (arguments.length < 2) { + // calls with 0 or 1 args are deprecated + deprecate('weirdfunction args < 2') + } +} +``` + +When calling `deprecate` as a function, the warning is counted per call site +within your own module, so you can display different deprecations depending +on different situations and the users will still get all the warnings: + +```js +var deprecate = require('depd')('my-cool-module') + +exports.weirdfunction = function () { + if (arguments.length < 2) { + // calls with 0 or 1 args are deprecated + deprecate('weirdfunction args < 2') + } else if (typeof arguments[0] !== 'string') { + // calls with non-string first argument are deprecated + deprecate('weirdfunction non-string first arg') + } +} +``` + +### Deprecating property access + +This will display a deprecated message about "oldprop" being deprecated +from "my-module" on STDERR when accessed. A deprecation will be displayed +when setting the value and when getting the value. + +```js +var deprecate = require('depd')('my-cool-module') + +exports.oldprop = 'something' + +// message automatically derives from property name +deprecate.property(exports, 'oldprop') + +// explicit message +deprecate.property(exports, 'oldprop', 'oldprop >= 0.10') +``` + +## License + +[MIT](LICENSE) + +[npm-version-image]: https://img.shields.io/npm/v/depd.svg +[npm-downloads-image]: https://img.shields.io/npm/dm/depd.svg +[npm-url]: https://npmjs.org/package/depd +[travis-image]: https://img.shields.io/travis/dougwilson/nodejs-depd/master.svg?label=linux +[travis-url]: https://travis-ci.org/dougwilson/nodejs-depd +[appveyor-image]: https://img.shields.io/appveyor/ci/dougwilson/nodejs-depd/master.svg?label=windows +[appveyor-url]: https://ci.appveyor.com/project/dougwilson/nodejs-depd +[coveralls-image]: https://img.shields.io/coveralls/dougwilson/nodejs-depd/master.svg +[coveralls-url]: https://coveralls.io/r/dougwilson/nodejs-depd?branch=master +[node-image]: https://img.shields.io/node/v/depd.svg +[node-url]: https://nodejs.org/en/download/ diff --git a/ts-ticket-office-service/node_modules/morgan/node_modules/depd/index.js b/ts-ticket-office-service/node_modules/morgan/node_modules/depd/index.js new file mode 100644 index 000000000..d758d3c8f --- /dev/null +++ b/ts-ticket-office-service/node_modules/morgan/node_modules/depd/index.js @@ -0,0 +1,522 @@ +/*! + * depd + * Copyright(c) 2014-2017 Douglas Christopher Wilson + * MIT Licensed + */ + +/** + * Module dependencies. + */ + +var callSiteToString = require('./lib/compat').callSiteToString +var eventListenerCount = require('./lib/compat').eventListenerCount +var relative = require('path').relative + +/** + * Module exports. + */ + +module.exports = depd + +/** + * Get the path to base files on. + */ + +var basePath = process.cwd() + +/** + * Determine if namespace is contained in the string. + */ + +function containsNamespace (str, namespace) { + var vals = str.split(/[ ,]+/) + var ns = String(namespace).toLowerCase() + + for (var i = 0; i < vals.length; i++) { + var val = vals[i] + + // namespace contained + if (val && (val === '*' || val.toLowerCase() === ns)) { + return true + } + } + + return false +} + +/** + * Convert a data descriptor to accessor descriptor. + */ + +function convertDataDescriptorToAccessor (obj, prop, message) { + var descriptor = Object.getOwnPropertyDescriptor(obj, prop) + var value = descriptor.value + + descriptor.get = function getter () { return value } + + if (descriptor.writable) { + descriptor.set = function setter (val) { return (value = val) } + } + + delete descriptor.value + delete descriptor.writable + + Object.defineProperty(obj, prop, descriptor) + + return descriptor +} + +/** + * Create arguments string to keep arity. + */ + +function createArgumentsString (arity) { + var str = '' + + for (var i = 0; i < arity; i++) { + str += ', arg' + i + } + + return str.substr(2) +} + +/** + * Create stack string from stack. + */ + +function createStackString (stack) { + var str = this.name + ': ' + this.namespace + + if (this.message) { + str += ' deprecated ' + this.message + } + + for (var i = 0; i < stack.length; i++) { + str += '\n at ' + callSiteToString(stack[i]) + } + + return str +} + +/** + * Create deprecate for namespace in caller. + */ + +function depd (namespace) { + if (!namespace) { + throw new TypeError('argument namespace is required') + } + + var stack = getStack() + var site = callSiteLocation(stack[1]) + var file = site[0] + + function deprecate (message) { + // call to self as log + log.call(deprecate, message) + } + + deprecate._file = file + deprecate._ignored = isignored(namespace) + deprecate._namespace = namespace + deprecate._traced = istraced(namespace) + deprecate._warned = Object.create(null) + + deprecate.function = wrapfunction + deprecate.property = wrapproperty + + return deprecate +} + +/** + * Determine if namespace is ignored. + */ + +function isignored (namespace) { + /* istanbul ignore next: tested in a child processs */ + if (process.noDeprecation) { + // --no-deprecation support + return true + } + + var str = process.env.NO_DEPRECATION || '' + + // namespace ignored + return containsNamespace(str, namespace) +} + +/** + * Determine if namespace is traced. + */ + +function istraced (namespace) { + /* istanbul ignore next: tested in a child processs */ + if (process.traceDeprecation) { + // --trace-deprecation support + return true + } + + var str = process.env.TRACE_DEPRECATION || '' + + // namespace traced + return containsNamespace(str, namespace) +} + +/** + * Display deprecation message. + */ + +function log (message, site) { + var haslisteners = eventListenerCount(process, 'deprecation') !== 0 + + // abort early if no destination + if (!haslisteners && this._ignored) { + return + } + + var caller + var callFile + var callSite + var depSite + var i = 0 + var seen = false + var stack = getStack() + var file = this._file + + if (site) { + // provided site + depSite = site + callSite = callSiteLocation(stack[1]) + callSite.name = depSite.name + file = callSite[0] + } else { + // get call site + i = 2 + depSite = callSiteLocation(stack[i]) + callSite = depSite + } + + // get caller of deprecated thing in relation to file + for (; i < stack.length; i++) { + caller = callSiteLocation(stack[i]) + callFile = caller[0] + + if (callFile === file) { + seen = true + } else if (callFile === this._file) { + file = this._file + } else if (seen) { + break + } + } + + var key = caller + ? depSite.join(':') + '__' + caller.join(':') + : undefined + + if (key !== undefined && key in this._warned) { + // already warned + return + } + + this._warned[key] = true + + // generate automatic message from call site + var msg = message + if (!msg) { + msg = callSite === depSite || !callSite.name + ? defaultMessage(depSite) + : defaultMessage(callSite) + } + + // emit deprecation if listeners exist + if (haslisteners) { + var err = DeprecationError(this._namespace, msg, stack.slice(i)) + process.emit('deprecation', err) + return + } + + // format and write message + var format = process.stderr.isTTY + ? formatColor + : formatPlain + var output = format.call(this, msg, caller, stack.slice(i)) + process.stderr.write(output + '\n', 'utf8') +} + +/** + * Get call site location as array. + */ + +function callSiteLocation (callSite) { + var file = callSite.getFileName() || '' + var line = callSite.getLineNumber() + var colm = callSite.getColumnNumber() + + if (callSite.isEval()) { + file = callSite.getEvalOrigin() + ', ' + file + } + + var site = [file, line, colm] + + site.callSite = callSite + site.name = callSite.getFunctionName() + + return site +} + +/** + * Generate a default message from the site. + */ + +function defaultMessage (site) { + var callSite = site.callSite + var funcName = site.name + + // make useful anonymous name + if (!funcName) { + funcName = '' + } + + var context = callSite.getThis() + var typeName = context && callSite.getTypeName() + + // ignore useless type name + if (typeName === 'Object') { + typeName = undefined + } + + // make useful type name + if (typeName === 'Function') { + typeName = context.name || typeName + } + + return typeName && callSite.getMethodName() + ? typeName + '.' + funcName + : funcName +} + +/** + * Format deprecation message without color. + */ + +function formatPlain (msg, caller, stack) { + var timestamp = new Date().toUTCString() + + var formatted = timestamp + + ' ' + this._namespace + + ' deprecated ' + msg + + // add stack trace + if (this._traced) { + for (var i = 0; i < stack.length; i++) { + formatted += '\n at ' + callSiteToString(stack[i]) + } + + return formatted + } + + if (caller) { + formatted += ' at ' + formatLocation(caller) + } + + return formatted +} + +/** + * Format deprecation message with color. + */ + +function formatColor (msg, caller, stack) { + var formatted = '\x1b[36;1m' + this._namespace + '\x1b[22;39m' + // bold cyan + ' \x1b[33;1mdeprecated\x1b[22;39m' + // bold yellow + ' \x1b[0m' + msg + '\x1b[39m' // reset + + // add stack trace + if (this._traced) { + for (var i = 0; i < stack.length; i++) { + formatted += '\n \x1b[36mat ' + callSiteToString(stack[i]) + '\x1b[39m' // cyan + } + + return formatted + } + + if (caller) { + formatted += ' \x1b[36m' + formatLocation(caller) + '\x1b[39m' // cyan + } + + return formatted +} + +/** + * Format call site location. + */ + +function formatLocation (callSite) { + return relative(basePath, callSite[0]) + + ':' + callSite[1] + + ':' + callSite[2] +} + +/** + * Get the stack as array of call sites. + */ + +function getStack () { + var limit = Error.stackTraceLimit + var obj = {} + var prep = Error.prepareStackTrace + + Error.prepareStackTrace = prepareObjectStackTrace + Error.stackTraceLimit = Math.max(10, limit) + + // capture the stack + Error.captureStackTrace(obj) + + // slice this function off the top + var stack = obj.stack.slice(1) + + Error.prepareStackTrace = prep + Error.stackTraceLimit = limit + + return stack +} + +/** + * Capture call site stack from v8. + */ + +function prepareObjectStackTrace (obj, stack) { + return stack +} + +/** + * Return a wrapped function in a deprecation message. + */ + +function wrapfunction (fn, message) { + if (typeof fn !== 'function') { + throw new TypeError('argument fn must be a function') + } + + var args = createArgumentsString(fn.length) + var deprecate = this // eslint-disable-line no-unused-vars + var stack = getStack() + var site = callSiteLocation(stack[1]) + + site.name = fn.name + + // eslint-disable-next-line no-eval + var deprecatedfn = eval('(function (' + args + ') {\n' + + '"use strict"\n' + + 'log.call(deprecate, message, site)\n' + + 'return fn.apply(this, arguments)\n' + + '})') + + return deprecatedfn +} + +/** + * Wrap property in a deprecation message. + */ + +function wrapproperty (obj, prop, message) { + if (!obj || (typeof obj !== 'object' && typeof obj !== 'function')) { + throw new TypeError('argument obj must be object') + } + + var descriptor = Object.getOwnPropertyDescriptor(obj, prop) + + if (!descriptor) { + throw new TypeError('must call property on owner object') + } + + if (!descriptor.configurable) { + throw new TypeError('property must be configurable') + } + + var deprecate = this + var stack = getStack() + var site = callSiteLocation(stack[1]) + + // set site name + site.name = prop + + // convert data descriptor + if ('value' in descriptor) { + descriptor = convertDataDescriptorToAccessor(obj, prop, message) + } + + var get = descriptor.get + var set = descriptor.set + + // wrap getter + if (typeof get === 'function') { + descriptor.get = function getter () { + log.call(deprecate, message, site) + return get.apply(this, arguments) + } + } + + // wrap setter + if (typeof set === 'function') { + descriptor.set = function setter () { + log.call(deprecate, message, site) + return set.apply(this, arguments) + } + } + + Object.defineProperty(obj, prop, descriptor) +} + +/** + * Create DeprecationError for deprecation + */ + +function DeprecationError (namespace, message, stack) { + var error = new Error() + var stackString + + Object.defineProperty(error, 'constructor', { + value: DeprecationError + }) + + Object.defineProperty(error, 'message', { + configurable: true, + enumerable: false, + value: message, + writable: true + }) + + Object.defineProperty(error, 'name', { + enumerable: false, + configurable: true, + value: 'DeprecationError', + writable: true + }) + + Object.defineProperty(error, 'namespace', { + configurable: true, + enumerable: false, + value: namespace, + writable: true + }) + + Object.defineProperty(error, 'stack', { + configurable: true, + enumerable: false, + get: function () { + if (stackString !== undefined) { + return stackString + } + + // prepare stack trace + return (stackString = createStackString.call(this, stack)) + }, + set: function setter (val) { + stackString = val + } + }) + + return error +} diff --git a/ts-ticket-office-service/node_modules/morgan/node_modules/depd/lib/browser/index.js b/ts-ticket-office-service/node_modules/morgan/node_modules/depd/lib/browser/index.js new file mode 100644 index 000000000..6be45cc20 --- /dev/null +++ b/ts-ticket-office-service/node_modules/morgan/node_modules/depd/lib/browser/index.js @@ -0,0 +1,77 @@ +/*! + * depd + * Copyright(c) 2015 Douglas Christopher Wilson + * MIT Licensed + */ + +'use strict' + +/** + * Module exports. + * @public + */ + +module.exports = depd + +/** + * Create deprecate for namespace in caller. + */ + +function depd (namespace) { + if (!namespace) { + throw new TypeError('argument namespace is required') + } + + function deprecate (message) { + // no-op in browser + } + + deprecate._file = undefined + deprecate._ignored = true + deprecate._namespace = namespace + deprecate._traced = false + deprecate._warned = Object.create(null) + + deprecate.function = wrapfunction + deprecate.property = wrapproperty + + return deprecate +} + +/** + * Return a wrapped function in a deprecation message. + * + * This is a no-op version of the wrapper, which does nothing but call + * validation. + */ + +function wrapfunction (fn, message) { + if (typeof fn !== 'function') { + throw new TypeError('argument fn must be a function') + } + + return fn +} + +/** + * Wrap property in a deprecation message. + * + * This is a no-op version of the wrapper, which does nothing but call + * validation. + */ + +function wrapproperty (obj, prop, message) { + if (!obj || (typeof obj !== 'object' && typeof obj !== 'function')) { + throw new TypeError('argument obj must be object') + } + + var descriptor = Object.getOwnPropertyDescriptor(obj, prop) + + if (!descriptor) { + throw new TypeError('must call property on owner object') + } + + if (!descriptor.configurable) { + throw new TypeError('property must be configurable') + } +} diff --git a/ts-ticket-office-service/node_modules/morgan/node_modules/depd/lib/compat/callsite-tostring.js b/ts-ticket-office-service/node_modules/morgan/node_modules/depd/lib/compat/callsite-tostring.js new file mode 100644 index 000000000..73186dc64 --- /dev/null +++ b/ts-ticket-office-service/node_modules/morgan/node_modules/depd/lib/compat/callsite-tostring.js @@ -0,0 +1,103 @@ +/*! + * depd + * Copyright(c) 2014 Douglas Christopher Wilson + * MIT Licensed + */ + +'use strict' + +/** + * Module exports. + */ + +module.exports = callSiteToString + +/** + * Format a CallSite file location to a string. + */ + +function callSiteFileLocation (callSite) { + var fileName + var fileLocation = '' + + if (callSite.isNative()) { + fileLocation = 'native' + } else if (callSite.isEval()) { + fileName = callSite.getScriptNameOrSourceURL() + if (!fileName) { + fileLocation = callSite.getEvalOrigin() + } + } else { + fileName = callSite.getFileName() + } + + if (fileName) { + fileLocation += fileName + + var lineNumber = callSite.getLineNumber() + if (lineNumber != null) { + fileLocation += ':' + lineNumber + + var columnNumber = callSite.getColumnNumber() + if (columnNumber) { + fileLocation += ':' + columnNumber + } + } + } + + return fileLocation || 'unknown source' +} + +/** + * Format a CallSite to a string. + */ + +function callSiteToString (callSite) { + var addSuffix = true + var fileLocation = callSiteFileLocation(callSite) + var functionName = callSite.getFunctionName() + var isConstructor = callSite.isConstructor() + var isMethodCall = !(callSite.isToplevel() || isConstructor) + var line = '' + + if (isMethodCall) { + var methodName = callSite.getMethodName() + var typeName = getConstructorName(callSite) + + if (functionName) { + if (typeName && functionName.indexOf(typeName) !== 0) { + line += typeName + '.' + } + + line += functionName + + if (methodName && functionName.lastIndexOf('.' + methodName) !== functionName.length - methodName.length - 1) { + line += ' [as ' + methodName + ']' + } + } else { + line += typeName + '.' + (methodName || '') + } + } else if (isConstructor) { + line += 'new ' + (functionName || '') + } else if (functionName) { + line += functionName + } else { + addSuffix = false + line += fileLocation + } + + if (addSuffix) { + line += ' (' + fileLocation + ')' + } + + return line +} + +/** + * Get constructor name of reviver. + */ + +function getConstructorName (obj) { + var receiver = obj.receiver + return (receiver.constructor && receiver.constructor.name) || null +} diff --git a/ts-ticket-office-service/node_modules/morgan/node_modules/depd/lib/compat/event-listener-count.js b/ts-ticket-office-service/node_modules/morgan/node_modules/depd/lib/compat/event-listener-count.js new file mode 100644 index 000000000..3a8925d13 --- /dev/null +++ b/ts-ticket-office-service/node_modules/morgan/node_modules/depd/lib/compat/event-listener-count.js @@ -0,0 +1,22 @@ +/*! + * depd + * Copyright(c) 2015 Douglas Christopher Wilson + * MIT Licensed + */ + +'use strict' + +/** + * Module exports. + * @public + */ + +module.exports = eventListenerCount + +/** + * Get the count of listeners on an event emitter of a specific type. + */ + +function eventListenerCount (emitter, type) { + return emitter.listeners(type).length +} diff --git a/ts-ticket-office-service/node_modules/morgan/node_modules/depd/lib/compat/index.js b/ts-ticket-office-service/node_modules/morgan/node_modules/depd/lib/compat/index.js new file mode 100644 index 000000000..955b3336b --- /dev/null +++ b/ts-ticket-office-service/node_modules/morgan/node_modules/depd/lib/compat/index.js @@ -0,0 +1,79 @@ +/*! + * depd + * Copyright(c) 2014-2015 Douglas Christopher Wilson + * MIT Licensed + */ + +'use strict' + +/** + * Module dependencies. + * @private + */ + +var EventEmitter = require('events').EventEmitter + +/** + * Module exports. + * @public + */ + +lazyProperty(module.exports, 'callSiteToString', function callSiteToString () { + var limit = Error.stackTraceLimit + var obj = {} + var prep = Error.prepareStackTrace + + function prepareObjectStackTrace (obj, stack) { + return stack + } + + Error.prepareStackTrace = prepareObjectStackTrace + Error.stackTraceLimit = 2 + + // capture the stack + Error.captureStackTrace(obj) + + // slice the stack + var stack = obj.stack.slice() + + Error.prepareStackTrace = prep + Error.stackTraceLimit = limit + + return stack[0].toString ? toString : require('./callsite-tostring') +}) + +lazyProperty(module.exports, 'eventListenerCount', function eventListenerCount () { + return EventEmitter.listenerCount || require('./event-listener-count') +}) + +/** + * Define a lazy property. + */ + +function lazyProperty (obj, prop, getter) { + function get () { + var val = getter() + + Object.defineProperty(obj, prop, { + configurable: true, + enumerable: true, + value: val + }) + + return val + } + + Object.defineProperty(obj, prop, { + configurable: true, + enumerable: true, + get: get + }) +} + +/** + * Call toString() on the obj + */ + +function toString (obj) { + return obj.toString() +} diff --git a/ts-ticket-office-service/node_modules/morgan/node_modules/depd/package.json b/ts-ticket-office-service/node_modules/morgan/node_modules/depd/package.json new file mode 100644 index 000000000..5e3c86321 --- /dev/null +++ b/ts-ticket-office-service/node_modules/morgan/node_modules/depd/package.json @@ -0,0 +1,41 @@ +{ + "name": "depd", + "description": "Deprecate all the things", + "version": "1.1.2", + "author": "Douglas Christopher Wilson ", + "license": "MIT", + "keywords": [ + "deprecate", + "deprecated" + ], + "repository": "dougwilson/nodejs-depd", + "browser": "lib/browser/index.js", + "devDependencies": { + "benchmark": "2.1.4", + "beautify-benchmark": "0.2.4", + "eslint": "3.19.0", + "eslint-config-standard": "7.1.0", + "eslint-plugin-markdown": "1.0.0-beta.7", + "eslint-plugin-promise": "3.6.0", + "eslint-plugin-standard": "3.0.1", + "istanbul": "0.4.5", + "mocha": "~1.21.5" + }, + "files": [ + "lib/", + "History.md", + "LICENSE", + "index.js", + "Readme.md" + ], + "engines": { + "node": ">= 0.6" + }, + "scripts": { + "bench": "node benchmark/index.js", + "lint": "eslint --plugin markdown --ext js,md .", + "test": "mocha --reporter spec --bail test/", + "test-ci": "istanbul cover node_modules/mocha/bin/_mocha --report lcovonly -- --reporter spec --no-exit test/", + "test-cov": "istanbul cover node_modules/mocha/bin/_mocha -- --reporter dot test/" + } +} diff --git a/ts-ticket-office-service/node_modules/morgan/package.json b/ts-ticket-office-service/node_modules/morgan/package.json index 28a2f0304..c90cf7769 100644 --- a/ts-ticket-office-service/node_modules/morgan/package.json +++ b/ts-ticket-office-service/node_modules/morgan/package.json @@ -1,126 +1,52 @@ { - "_args": [ - [ - { - "raw": "morgan@~1.9.0", - "scope": null, - "escapedName": "morgan", - "name": "morgan", - "rawSpec": "~1.9.0", - "spec": ">=1.9.0 <1.10.0", - "type": "range" - }, - "F:\\gitwork\\workspace_microservices\\ts-ticket-office-service" - ] - ], - "_from": "morgan@>=1.9.0 <1.10.0", - "_id": "morgan@1.9.0", - "_inCache": true, - "_location": "/morgan", - "_nodeVersion": "6.11.1", - "_npmOperationalInternal": { - "host": "s3://npm-registry-packages", - "tmp": "tmp/morgan-1.9.0.tgz_1506479941546_0.9185023584868759" - }, - "_npmUser": { - "name": "dougwilson", - "email": "doug@somethingdoug.com" - }, - "_npmVersion": "3.10.10", - "_phantomChildren": {}, - "_requested": { - "raw": "morgan@~1.9.0", - "scope": null, - "escapedName": "morgan", - "name": "morgan", - "rawSpec": "~1.9.0", - "spec": ">=1.9.0 <1.10.0", - "type": "range" - }, - "_requiredBy": [ - "/" - ], - "_resolved": "https://registry.npmjs.org/morgan/-/morgan-1.9.0.tgz", - "_shasum": "d01fa6c65859b76fcf31b3cb53a3821a311d8051", - "_shrinkwrap": null, - "_spec": "morgan@~1.9.0", - "_where": "F:\\gitwork\\workspace_microservices\\ts-ticket-office-service", - "bugs": { - "url": "https://github.com/expressjs/morgan/issues" - }, + "name": "morgan", + "description": "HTTP request logger middleware for node.js", + "version": "1.9.1", "contributors": [ - { - "name": "Douglas Christopher Wilson", - "email": "doug@somethingdoug.com" - }, - { - "name": "Jonathan Ong", - "email": "me@jongleberry.com", - "url": "http://jongleberry.com" - } + "Douglas Christopher Wilson ", + "Jonathan Ong (http://jongleberry.com)" ], + "license": "MIT", + "keywords": [ + "express", + "http", + "logger", + "middleware" + ], + "repository": "expressjs/morgan", "dependencies": { "basic-auth": "~2.0.0", "debug": "2.6.9", - "depd": "~1.1.1", + "depd": "~1.1.2", "on-finished": "~2.3.0", "on-headers": "~1.0.1" }, - "description": "HTTP request logger middleware for node.js", "devDependencies": { - "eslint": "3.19.0", - "eslint-config-standard": "10.2.1", - "eslint-plugin-import": "2.7.0", + "eslint": "5.5.0", + "eslint-config-standard": "12.0.0", + "eslint-plugin-import": "2.14.0", "eslint-plugin-markdown": "1.0.0-beta.6", - "eslint-plugin-node": "5.1.1", - "eslint-plugin-promise": "3.5.0", - "eslint-plugin-standard": "3.0.1", + "eslint-plugin-node": "7.0.1", + "eslint-plugin-promise": "4.0.1", + "eslint-plugin-standard": "4.0.0", "istanbul": "0.4.5", "mocha": "2.5.3", "split": "1.0.1", "supertest": "1.1.0" }, - "directories": {}, - "dist": { - "shasum": "d01fa6c65859b76fcf31b3cb53a3821a311d8051", - "tarball": "https://registry.npmjs.org/morgan/-/morgan-1.9.0.tgz" - }, - "engines": { - "node": ">= 0.8.0" - }, "files": [ "LICENSE", "HISTORY.md", "README.md", "index.js" ], - "gitHead": "4def0fa6d4ac703dc5c76f901e997af667a27d65", - "homepage": "https://github.com/expressjs/morgan#readme", - "keywords": [ - "express", - "http", - "logger", - "middleware" - ], - "license": "MIT", - "maintainers": [ - { - "name": "dougwilson", - "email": "doug@somethingdoug.com" - } - ], - "name": "morgan", - "optionalDependencies": {}, - "readme": "ERROR: No README data found!", - "repository": { - "type": "git", - "url": "git+https://github.com/expressjs/morgan.git" + "engines": { + "node": ">= 0.8.0" }, "scripts": { "lint": "eslint --plugin markdown --ext js,md .", "test": "mocha --check-leaks --reporter spec --bail", "test-cov": "istanbul cover node_modules/mocha/bin/_mocha -- --check-leaks --reporter dot", "test-travis": "istanbul cover node_modules/mocha/bin/_mocha --report lcovonly -- --check-leaks --reporter spec" - }, - "version": "1.9.0" + } } diff --git a/ts-ticket-office-service/node_modules/mysql/Changes.md b/ts-ticket-office-service/node_modules/mysql/Changes.md new file mode 100644 index 000000000..73e549c8d --- /dev/null +++ b/ts-ticket-office-service/node_modules/mysql/Changes.md @@ -0,0 +1,569 @@ +# Changes + +This file is a manually maintained list of changes for each release. Feel free +to add your changes here when sending pull requests. Also send corrections if +you spot any mistakes. + +## v2.18.1 (2020-01-23) + +* Fix Amazon RDS profile for yaSSL MySQL servers with 2019 CA #2292 + +## v2.18.0 (2020-01-21) + +* Add `localInfile` option to control `LOAD DATA LOCAL INFILE` +* Add new Amazon RDS Root 2019 CA to Amazon RDS SSL profile #2280 +* Add new error codes up to MySQL 5.7.29 +* Fix early detection of bad callback to `connection.query` +* Support Node.js 12.x #2211 +* Support Node.js 13.x +* Support non-enumerable properties in object argument to `connection.query` #2253 +* Update `bignumber.js` to 9.0.0 +* Update `readable-stream` to 2.3.7 + +## v2.17.1 (2019-04-18) + +* Update `bignumber.js` to 7.2.1 #2206 + - Fix npm deprecation warning + +## v2.17.0 (2019-04-17) + +* Add reverse type lookup for small performance gain #2170 +* Fix `connection.threadId` missing on handshake failure +* Fix duplicate packet name in debug output +* Fix no password support for old password protocol +* Remove special case for handshake in determine packet code +* Small performance improvement starting command sequence +* Support auth switch in change user flow #1776 +* Support Node.js 11.x +* Update `bignumber.js` to 6.0.0 + +## v2.16.0 (2018-07-17) + +* Add Amazon RDS GovCloud SSL certificates #1876 +* Add new error codes up to MySQL 5.7.21 +* Include connection ID in debug output +* Support Node.js 9.x +* Support Node.js 10.x #2003 #2024 #2026 #2034 +* Update Amazon RDS SSL certificates +* Update `bignumber.js` to 4.1.0 +* Update `readable-stream` to 2.3.6 +* Update `sqlstring` to 2.3.1 + - Fix incorrectly replacing non-placeholders in SQL + +## v2.15.0 (2017-10-05) + +* Add new Amazon RDS ca-central-1 certificate CA to Amazon RDS SSL profile #1809 +* Add new error codes up to MySQL 5.7.19 +* Add `mysql.raw()` to generate pre-escaped values #877 #1821 +* Fix "changedRows" to work on non-English servers #1819 +* Fix error when server sends RST on `QUIT` #1811 +* Fix typo in insecure auth error message +* Support `mysql_native_password` auth switch request for Azure #1396 #1729 #1730 +* Update `sqlstring` to 2.3.0 + - Add `.toSqlString()` escape overriding + - Small performance improvement on `escapeId` +* Update `bignumber.js` to 4.0.4 + +## v2.14.1 (2017-08-01) + +* Fix holding first closure for lifetime of connection #1785 + +## v2.14.0 (2017-07-25) + +* Add new Amazon RDS ap-south-1 certificate CA to Amazon RDS SSL profile #1780 +* Add new Amazon RDS eu-west-2 certificate CA to Amazon RDS SSL profile #1770 +* Add `sql` property to query `Error` objects #1462 #1628 #1629 +* Add `sqlMessage` property to `Error` objects #1714 +* Fix the MySQL 5.7.17 error codes +* Support Node.js 8.x +* Update `bignumber.js` to 4.0.2 +* Update `readable-stream` to 2.3.3 +* Use `safe-buffer` for improved Buffer API + +## v2.13.0 (2017-01-24) + +* Accept regular expression as pool cluster pattern #1572 +* Accept wildcard anywhere in pool cluster pattern #1570 +* Add `acquire` and `release` events to `Pool` for tracking #1366 #1449 #1528 #1625 +* Add new error codes up to MySQL 5.7.17 +* Fix edge cases when determing Query result packets #1547 +* Fix memory leak when using long-running domains #1619 #1620 +* Remove unnecessary buffer copies when receiving large packets +* Update `bignumber.js` to 3.1.2 +* Use a simple buffer list to improve performance #566 #1590 + +## v2.12.0 (2016-11-02) + +* Accept array of type names to `dateStrings` option #605 #1481 +* Add `query` method to `PoolNamespace` #1256 #1505 #1506 + - Used as `cluster.of(...).query(...)` +* Add new error codes up to MySQL 5.7.16 +* Fix edge cases writing certain length coded values +* Fix typo in `HANDSHAKE_NO_SSL_SUPPORT` error message #1534 +* Support Node.js 7.x +* Update `bignumber.js` to 2.4.0 +* Update `sqlstring` to 2.2.0 + - Accept numbers and other value types in `escapeId` + - Escape invalid `Date` objects as `NULL` + - Run `buffer.toString()` through escaping + +## v2.11.1 (2016-06-07) + +* Fix writing truncated packets starting with large string/buffer #1438 + +## v2.11.0 (2016-06-06) + +* Add `POOL_CLOSED` code to "Pool is closed." error +* Add `POOL_CONNLIMIT` code to "No connections available." error #1332 +* Bind underlying connections in pool to same domain as pool #1242 +* Bind underlying socket to same domain as connection #1243 +* Fix allocation errors receiving many result rows #918 #1265 #1324 #1415 +* Fix edge cases constructing long stack traces #1387 +* Fix handshake inactivity timeout on Node.js v4.2.0 #1223 #1236 #1239 #1240 #1241 #1252 +* Fix Query stream to emit close after ending #1349 #1350 +* Fix type cast for BIGINT columns when number is negative #1376 +* Performance improvements for array/object escaping in SqlString #1331 +* Performance improvements for formatting in SqlString #1431 +* Performance improvements for string escaping in SqlString #1390 +* Performance improvements for writing packets to network +* Support Node.js 6.x +* Update `bignumber.js` to 2.3.0 +* Update `readable-stream` to 1.1.14 +* Use the `sqlstring` module for SQL escaping and formatting + +## v2.10.2 (2016-01-12) + +* Fix exception/hang from certain SSL connection errors #1153 +* Update `bignumber.js` to 2.1.4 + +## v2.10.1 (2016-01-11) + +* Add new Amazon RDS ap-northeast-2 certificate CA to Amazon RDS SSL profile #1329 + +## v2.10.0 (2015-12-15) + +* Add new error codes up to MySQL 5.7.9 #1294 +* Add new JSON type constant #1295 +* Add types for fractional seconds support +* Fix `connection.destroy()` on pool connection creating sequences #1291 +* Fix error code 139 `HA_ERR_TO_BIG_ROW` to be `HA_ERR_TOO_BIG_ROW` +* Fix error when call site error is missing stack #1179 +* Fix reading password from MySQL URL that has bare colon #1278 +* Handle MySQL servers not closing TCP connection after QUIT -> OK exchange #1277 +* Minor SqlString Date to string performance improvement #1233 +* Support Node.js 4.x +* Support Node.js 5.x +* Update `bignumber.js` to 2.1.2 + +## v2.9.0 (2015-08-19) + +* Accept the `ciphers` property in connection `ssl` option #1185 +* Fix bad timezone conversion from `Date` to string for certain times #1045 #1155 + +## v2.8.0 (2015-07-13) + +* Add `connect` event to `Connection` #1129 +* Default `timeout` for `connection.end` to 30 seconds #1057 +* Fix a sync callback when sequence enqueue fails #1147 +* Provide static require analysis +* Re-use connection from pool after `conn.changeUser` is used #837 #1088 + +## v2.7.0 (2015-05-27) + +* Destroy/end connections removed from the pool on error +* Delay implied connect until after `.query` argument validation +* Do not remove connections with non-fatal errors from the pool +* Error early if `callback` argument to `.query` is not a function #1060 +* Lazy-load modules from many entry point; reduced memory use + +## v2.6.2 (2015-04-14) + +* Fix `Connection.createQuery` for no SQL #1058 +* Update `bignumber.js` to 2.0.7 + +## v2.6.1 (2015-03-26) + +* Update `bignumber.js` to 2.0.5 #1037 #1038 + +## v2.6.0 (2015-03-24) + +* Add `poolCluster.remove` to remove pools from the cluster #1006 #1007 +* Add optional callback to `poolCluster.end` +* Add `restoreNodeTimeout` option to `PoolCluster` #880 #906 +* Fix LOAD DATA INFILE handling in multiple statements #1036 +* Fix `poolCluster.add` to throw if `PoolCluster` has been closed +* Fix `poolCluster.add` to throw if `id` already defined +* Fix un-catchable error from `PoolCluster` when MySQL server offline #1033 +* Improve speed formatting SQL #1019 +* Support io.js + +## v2.5.5 (2015-02-23) + +* Store SSL presets in JS instead of JSON #959 +* Support Node.js 0.12 +* Update Amazon RDS SSL certificates #1001 + +## v2.5.4 (2014-12-16) + +* Fix error if falsy error thrown in callback handler #960 +* Fix various error code strings #954 + +## v2.5.3 (2014-11-06) + +* Fix `pool.query` streaming interface not emitting connection errors #941 + +## v2.5.2 (2014-10-10) + +* Fix receiving large text fields #922 + +## v2.5.1 (2014-09-22) + +* Fix `pool.end` race conditions #915 +* Fix `pool.getConnection` race conditions + +## v2.5.0 (2014-09-07) + +* Add code `POOL_ENQUEUELIMIT` to error reaching `queueLimit` +* Add `enqueue` event to pool #716 +* Add `enqueue` event to protocol and connection #381 +* Blacklist unsupported connection flags #881 +* Make only column names enumerable in `RowDataPacket` #549 #895 +* Support Node.js 0.6 #718 + +## v2.4.3 (2014-08-25) + +* Fix `pool.query` to use `typeCast` configuration + +## v2.4.2 (2014-08-03) + +* Fix incorrect sequence packet errors to be catchable #867 +* Fix stray protocol packet errors to be catchable #867 +* Fix timing of fatal protocol errors bubbling to user #879 + +## v2.4.1 (2014-07-17) + +* Fix `pool.query` not invoking callback on connection error #872 + +## v2.4.0 (2014-07-13) + +* Add code `POOL_NOEXIST` in PoolCluster error #846 +* Add `acquireTimeout` pool option to specify a timeout for acquiring a connection #821 #854 +* Add `connection.escapeId` +* Add `pool.escapeId` +* Add `timeout` option to all sequences #855 #863 +* Default `connectTimeout` to 10 seconds +* Fix domain binding with `conn.connect` +* Fix `packet.default` to actually be a string +* Fix `PARSER_*` errors to be catchable +* Fix `PROTOCOL_PACKETS_OUT_OF_ORDER` error to be catchable #844 +* Include packets that failed parsing under `debug` +* Return `Query` object from `pool.query` like `conn.query` #830 +* Use `EventEmitter.listenerCount` when possible for faster counting + +## v2.3.2 (2014-05-29) + +* Fix pool leaking connections after `conn.changeUser` #833 + +## v2.3.1 (2014-05-26) + +* Add database errors to error constants +* Add global errors to error constants +* Throw when calling `conn.release` multiple times #824 #827 +* Update known error codes + +## v2.3.0 (2014-05-16) + +* Accept MySQL charset (like `UTF8` or `UTF8MB4`) in `charset` option #808 +* Accept pool options in connection string to `mysql.createPool` #811 +* Clone connection config for new pool connections +* Default `connectTimeout` to 2 minutes +* Reject unauthorized SSL connections (use `ssl.rejectUnauthorized` to override) #816 +* Return last error when PoolCluster exhausts connection retries #818 +* Remove connection from pool after `conn.changeUser` is released #806 +* Throw on unknown SSL profile name #817 +* User newer TLS functions when available #809 + +## v2.2.0 (2014-04-27) + +* Use indexOf instead of for loops removing conn from pool #611 +* Make callback to `pool.query` optional like `conn.query` #585 +* Prevent enqueuing sequences after fatal error #400 +* Fix geometry parser for empty fields #742 +* Accept lower-case charset option +* Throw on unknown charset option #789 +* Update known charsets +* Remove console.warn from PoolCluster #744 +* Fix `pool.end` to handle queued connections #797 +* Fix `pool.releaseConnection` to keep connection queue flowing #797 +* Fix SSL handshake error to be catchable #800 +* Add `connection.threadId` to get MySQL connection ID #602 +* Ensure `pool.getConnection` retrieves good connections #434 #557 #778 +* Fix pool cluster wildcard matching #627 +* Pass query values through to `SqlString.format` #590 + +## v2.1.1 (2014-03-13) + +* fix authentication w/password failure for node.js 0.10.5 #746 #752 +* fix authentication w/password TypeError exception for node.js 0.10.0-0.10.4 #747 +* fix specifying `values` in `conn.query({...}).on(...)` pattern #755 +* fix long stack trace to include the `pool.query(...)` call #715 + +## v2.1.0 (2014-02-20) + +* crypto.createHash fix for node.js < 11 #735 +* Add `connectTimeout` option to specify a timeout for establishing a connection #726 +* SSL support #481 + +## v2.0.1 + +* internal parser speed improvement #702 +* domains support +* 'trace' connection option to control if long stack traces are generated #713 #710 #439 + +## v2.0.0 (2014-01-09) + +* stream improvements: + - node 0.8 support #692 + - Emit 'close' events from query streams #688 +* encoding fix in streaming LOAD DATA LOCAL INFILE #670 +* Doc improvements + +## v2.0.0-rc2 (2013-12-07) + +* Streaming LOAD DATA LOCAL INFILE #668 +* Doc improvements + +## v2.0.0-rc1 (2013-11-30) + +* Transaction support +* Expose SqlString.format as mysql.format() +* Many bug fixes +* Better support for dates in local time zone +* Doc improvements + +## v2.0.0-alpha9 (2013-08-27) + +* Add query to pool to execute queries directly using the pool +* Add `sqlState` property to `Error` objects #556 +* Pool option to set queue limit +* Pool sends 'connection' event when it opens a new connection +* Added stringifyObjects option to treat input as strings rather than objects (#501) +* Support for poolClusters +* Datetime improvements +* Bug fixes + +## v2.0.0-alpha8 (2013-04-30) + +* Switch to old mode for Streams 2 (Node.js v 0.10.x) +* Add stream method to Query Wraps events from the query object into a node v0.10.x Readable stream +* DECIMAL should also be treated as big number +* Removed slow unnecessary stack access +* Added charsets +* Added bigNumberStrings option for forcing BIGINT columns as strings +* Changes date parsing to return String if not a valid JS Date +* Adds support for ?? escape sequence to escape identifiers +* Changes Auth.token() to force password to be in binary, not utf8 (#378) +* Restrict debugging by packet types +* Add 'multipleStatements' option tracking to ConnectionConfig. Fixes GH-408 +* Changes Pool to handle 'error' events and dispose connection +* Allows db.query({ sql: "..." }, [ val1, ... ], cb); (#390) +* Improved documentation +* Bug fixes + +## v2.0.0-alpha7 (2013-02-03) + +* Add connection pooling (#351) + +## v2.0.0-alpha6 (2013-01-31) + +* Add supportBigNumbers option (#381, #382) +* Accept prebuilt Query object in connection.query +* Bug fixes + +## v2.0.0-alpha5 (2012-12-03) + +* Add mysql.escapeId to escape identifiers (closes #342) +* Allow custom escaping mode (config.queryFormat) +* Convert DATE columns to configured timezone instead of UTC (#332) +* Convert LONGLONG and NEWDECIMAL to numbers (#333) +* Fix Connection.escape() (fixes #330) +* Changed Readme ambiguity about custom type cast fallback +* Change typeCast to receive Connection instead of Connection.config.timezone +* Fix drain event having useless err parameter +* Add Connection.statistics() back from v0.9 +* Add Connection.ping() back from v0.9 + +## v2.0.0-alpha4 (2012-10-03) + +* Fix some OOB errors on resume() +* Fix quick pause() / resume() usage +* Properly parse host denied / similar errors +* Add Connection.ChangeUser functionality +* Make sure changeUser errors are fatal +* Enable formatting nested arrays for bulk inserts +* Add Connection.escape functionality +* Renamed 'close' to 'end' event +* Return parsed object instead of Buffer for GEOMETRY types +* Allow nestTables inline (using a string instead of a boolean) +* Check for ZEROFILL_FLAG and format number accordingly +* Add timezone support (default: local) +* Add custom typeCast functionality +* Export mysql column types +* Add connection flags functionality (#237) +* Exports drain event when queue finishes processing (#272, #271, #306) + +## v2.0.0-alpha3 (2012-06-12) + +* Implement support for `LOAD DATA LOCAL INFILE` queries (#182). +* Support OLD\_PASSWORD() accounts like 0.9.x did. You should still upgrade any + user accounts in your your MySQL user table that has short (16 byte) Password + values. Connecting to those accounts is not secure. (#204) +* Ignore function values when escaping objects, allows to use RowDataPacket + objects as query arguments. (Alex Gorbatchev, #213) +* Handle initial error packets from server such as `ER_HOST_NOT_PRIVILEGED`. +* Treat `utf8\_bin` as a String, not Buffer. (#214) +* Handle empty strings in first row column value. (#222) +* Honor Connection#nestTables setting for queries. (#221) +* Remove `CLIENT_INTERACTIVE` flag from config. Improves #225. +* Improve docs for connections settings. +* Implement url string support for Connection configs. + +## v2.0.0-alpha2 (2012-05-31) + +* Specify escaping before for NaN / Infinity (they are as unquoted constants). +* Support for unix domain socket connections (use: {socketPath: '...'}). +* Fix type casting for NULL values for Date/Number fields +* Add `fields` argument to `query()` as well as `'fields'` event. This is + similar to what was available in 0.9.x. +* Support connecting to the sphinx searchd daemon as well as MariaDB (#199). +* Implement long stack trace support, will be removed / disabled if the node + core ever supports it natively. +* Implement `nestTables` option for queries, allows fetching JOIN result sets + with overlapping column names. +* Fix ? placeholder mechanism for values containing '?' characters (#205). +* Detect when `connect()` is called more than once on a connection and provide + the user with a good error message for it (#204). +* Switch to `UTF8_GENERAL_CI` (previously `UTF8_UNICODE_CI`) as the default + charset for all connections to avoid strange MySQL performance issues (#200), + and also make the charset user configurable. +* Fix BLOB type casting for `TINY_BLOB`, `MEDIUM_BLOB` and `LONG_BLOB`. +* Add support for sending and receiving large (> 16 MB) packets. + +## v2.0.0-alpha (2012-05-15) + +This release is a rewrite. You should carefully test your application after +upgrading to avoid problems. This release features many improvements, most +importantly: + +* ~5x faster than v0.9.x for parsing query results +* Support for pause() / resume() (for streaming rows) +* Support for multiple statement queries +* Support for stored procedures +* Support for transactions +* Support for binary columns (as blobs) +* Consistent & well documented error handling +* A new Connection class that has well defined semantics (unlike the old Client class). +* Convenient escaping of objects / arrays that allows for simpler query construction +* A significantly simpler code base +* Many bug fixes & other small improvements (Closed 62 out of 66 GitHub issues) + +Below are a few notes on the upgrade process itself: + +The first thing you will run into is that the old `Client` class is gone and +has been replaced with a less ambitious `Connection` class. So instead of +`mysql.createClient()`, you now have to: + +```js +var mysql = require('mysql'); +var connection = mysql.createConnection({ + host : 'localhost', + user : 'me', + password : 'secret', +}); + +connection.query('SELECT 1', function(err, rows) { + if (err) throw err; + + console.log('Query result: ', rows); +}); + +connection.end(); +``` + +The new `Connection` class does not try to handle re-connects, please study the +`Server disconnects` section in the new Readme. + +Other than that, the interface has stayed very similar. Here are a few things +to check out so: + +* BIGINT's are now cast into strings +* Binary data is now cast to buffers +* The `'row'` event on the `Query` object is now called `'result'` and will + also be emitted for queries that produce an OK/Error response. +* Error handling is consistently defined now, check the Readme +* Escaping has become more powerful which may break your code if you are + currently using objects to fill query placeholders. +* Connections can now be established explicitly again, so you may wish to do so + if you want to handle connection errors specifically. + +That should be most of it, if you run into anything else, please send a patch +or open an issue to improve this document. + +## v0.9.6 (2012-03-12) + +* Escape array values so they produce sql arrays (Roger Castells, Colin Smith) +* docs: mention mysql transaction stop gap solution (Blake Miner) +* docs: Mention affectedRows in FAQ (Michael Baldwin) + +## v0.9.5 (2011-11-26) + +* Fix #142 Driver stalls upon reconnect attempt that's immediately closed +* Add travis build +* Switch to urun as a test runner +* Switch to utest for unit tests +* Remove fast-or-slow dependency for tests +* Split integration tests into individual files again + +## v0.9.4 (2011-08-31) + +* Expose package.json as `mysql.PACKAGE` (#104) + +## v0.9.3 (2011-08-22) + +* Set default `client.user` to root +* Fix #91: Client#format should not mutate params array +* Fix #94: TypeError in client.js +* Parse decimals as string (vadimg) + +## v0.9.2 (2011-08-07) + +* The underlaying socket connection is now managed implicitly rather than explicitly. +* Check the [upgrading guide][] for a full list of changes. + +## v0.9.1 (2011-02-20) + +* Fix issue #49 / `client.escape()` throwing exceptions on objects. (Nick Payne) +* Drop < v0.4.x compatibility. From now on you need node v0.4.x to use this module. + +## Older releases + +These releases were done before maintaining this file: + +* [v0.9.0](https://github.com/mysqljs/mysql/compare/v0.8.0...v0.9.0) + (2011-01-04) +* [v0.8.0](https://github.com/mysqljs/mysql/compare/v0.7.0...v0.8.0) + (2010-10-30) +* [v0.7.0](https://github.com/mysqljs/mysql/compare/v0.6.0...v0.7.0) + (2010-10-14) +* [v0.6.0](https://github.com/mysqljs/mysql/compare/v0.5.0...v0.6.0) + (2010-09-28) +* [v0.5.0](https://github.com/mysqljs/mysql/compare/v0.4.0...v0.5.0) + (2010-09-17) +* [v0.4.0](https://github.com/mysqljs/mysql/compare/v0.3.0...v0.4.0) + (2010-09-02) +* [v0.3.0](https://github.com/mysqljs/mysql/compare/v0.2.0...v0.3.0) + (2010-08-25) +* [v0.2.0](https://github.com/mysqljs/mysql/compare/v0.1.0...v0.2.0) + (2010-08-22) +* [v0.1.0](https://github.com/mysqljs/mysql/commits/v0.1.0) + (2010-08-22) diff --git a/ts-ticket-office-service/node_modules/mysql/License b/ts-ticket-office-service/node_modules/mysql/License new file mode 100644 index 000000000..c7ff12a2f --- /dev/null +++ b/ts-ticket-office-service/node_modules/mysql/License @@ -0,0 +1,19 @@ +Copyright (c) 2012 Felix Geisendörfer (felix@debuggable.com) and contributors + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated documentation files (the "Software"), to deal + in the Software without restriction, including without limitation the rights + to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + copies of the Software, and to permit persons to whom the Software is + furnished to do so, subject to the following conditions: + + The above copyright notice and this permission notice shall be included in + all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + THE SOFTWARE. diff --git a/ts-ticket-office-service/node_modules/mysql/Readme.md b/ts-ticket-office-service/node_modules/mysql/Readme.md new file mode 100644 index 000000000..d7c9aa20c --- /dev/null +++ b/ts-ticket-office-service/node_modules/mysql/Readme.md @@ -0,0 +1,1548 @@ +# mysql + +[![NPM Version][npm-version-image]][npm-url] +[![NPM Downloads][npm-downloads-image]][npm-url] +[![Node.js Version][node-image]][node-url] +[![Linux Build][travis-image]][travis-url] +[![Windows Build][appveyor-image]][appveyor-url] +[![Test Coverage][coveralls-image]][coveralls-url] + +## Table of Contents + +- [Install](#install) +- [Introduction](#introduction) +- [Contributors](#contributors) +- [Sponsors](#sponsors) +- [Community](#community) +- [Establishing connections](#establishing-connections) +- [Connection options](#connection-options) + - [SSL options](#ssl-options) + - [Connection flags](#connection-flags) +- [Terminating connections](#terminating-connections) +- [Pooling connections](#pooling-connections) +- [Pool options](#pool-options) +- [Pool events](#pool-events) + - [acquire](#acquire) + - [connection](#connection) + - [enqueue](#enqueue) + - [release](#release) +- [Closing all the connections in a pool](#closing-all-the-connections-in-a-pool) +- [PoolCluster](#poolcluster) + - [PoolCluster options](#poolcluster-options) +- [Switching users and altering connection state](#switching-users-and-altering-connection-state) +- [Server disconnects](#server-disconnects) +- [Performing queries](#performing-queries) +- [Escaping query values](#escaping-query-values) +- [Escaping query identifiers](#escaping-query-identifiers) + - [Preparing Queries](#preparing-queries) + - [Custom format](#custom-format) +- [Getting the id of an inserted row](#getting-the-id-of-an-inserted-row) +- [Getting the number of affected rows](#getting-the-number-of-affected-rows) +- [Getting the number of changed rows](#getting-the-number-of-changed-rows) +- [Getting the connection ID](#getting-the-connection-id) +- [Executing queries in parallel](#executing-queries-in-parallel) +- [Streaming query rows](#streaming-query-rows) + - [Piping results with Streams](#piping-results-with-streams) +- [Multiple statement queries](#multiple-statement-queries) +- [Stored procedures](#stored-procedures) +- [Joins with overlapping column names](#joins-with-overlapping-column-names) +- [Transactions](#transactions) +- [Ping](#ping) +- [Timeouts](#timeouts) +- [Error handling](#error-handling) +- [Exception Safety](#exception-safety) +- [Type casting](#type-casting) + - [Number](#number) + - [Date](#date) + - [Buffer](#buffer) + - [String](#string) + - [Custom type casting](#custom-type-casting) +- [Debugging and reporting problems](#debugging-and-reporting-problems) +- [Security issues](#security-issues) +- [Contributing](#contributing) +- [Running tests](#running-tests) + - [Running unit tests](#running-unit-tests) + - [Running integration tests](#running-integration-tests) +- [Todo](#todo) + +## Install + +This is a [Node.js](https://nodejs.org/en/) module available through the +[npm registry](https://www.npmjs.com/). + +Before installing, [download and install Node.js](https://nodejs.org/en/download/). +Node.js 0.6 or higher is required. + +Installation is done using the +[`npm install` command](https://docs.npmjs.com/getting-started/installing-npm-packages-locally): + +```sh +$ npm install mysql +``` + +For information about the previous 0.9.x releases, visit the [v0.9 branch][]. + +Sometimes I may also ask you to install the latest version from Github to check +if a bugfix is working. In this case, please do: + +```sh +$ npm install mysqljs/mysql +``` + +[v0.9 branch]: https://github.com/mysqljs/mysql/tree/v0.9 + +## Introduction + +This is a node.js driver for mysql. It is written in JavaScript, does not +require compiling, and is 100% MIT licensed. + +Here is an example on how to use it: + +```js +var mysql = require('mysql'); +var connection = mysql.createConnection({ + host : 'localhost', + user : 'me', + password : 'secret', + database : 'my_db' +}); + +connection.connect(); + +connection.query('SELECT 1 + 1 AS solution', function (error, results, fields) { + if (error) throw error; + console.log('The solution is: ', results[0].solution); +}); + +connection.end(); +``` + +From this example, you can learn the following: + +* Every method you invoke on a connection is queued and executed in sequence. +* Closing the connection is done using `end()` which makes sure all remaining + queries are executed before sending a quit packet to the mysql server. + +## Contributors + +Thanks goes to the people who have contributed code to this module, see the +[GitHub Contributors page][]. + +[GitHub Contributors page]: https://github.com/mysqljs/mysql/graphs/contributors + +Additionally I'd like to thank the following people: + +* [Andrey Hristov][] (Oracle) - for helping me with protocol questions. +* [Ulf Wendel][] (Oracle) - for helping me with protocol questions. + +[Ulf Wendel]: http://blog.ulf-wendel.de/ +[Andrey Hristov]: http://andrey.hristov.com/ + +## Sponsors + +The following companies have supported this project financially, allowing me to +spend more time on it (ordered by time of contribution): + +* [Transloadit](http://transloadit.com) (my startup, we do file uploading & + video encoding as a service, check it out) +* [Joyent](http://www.joyent.com/) +* [pinkbike.com](http://pinkbike.com/) +* [Holiday Extras](http://www.holidayextras.co.uk/) (they are [hiring](http://join.holidayextras.co.uk/)) +* [Newscope](http://newscope.com/) (they are [hiring](https://newscope.com/unternehmen/jobs/)) + +## Community + +If you'd like to discuss this module, or ask questions about it, please use one +of the following: + +* **Mailing list**: https://groups.google.com/forum/#!forum/node-mysql +* **IRC Channel**: #node.js (on freenode.net, I pay attention to any message + including the term `mysql`) + +## Establishing connections + +The recommended way to establish a connection is this: + +```js +var mysql = require('mysql'); +var connection = mysql.createConnection({ + host : 'example.org', + user : 'bob', + password : 'secret' +}); + +connection.connect(function(err) { + if (err) { + console.error('error connecting: ' + err.stack); + return; + } + + console.log('connected as id ' + connection.threadId); +}); +``` + +However, a connection can also be implicitly established by invoking a query: + +```js +var mysql = require('mysql'); +var connection = mysql.createConnection(...); + +connection.query('SELECT 1', function (error, results, fields) { + if (error) throw error; + // connected! +}); +``` + +Depending on how you like to handle your errors, either method may be +appropriate. Any type of connection error (handshake or network) is considered +a fatal error, see the [Error Handling](#error-handling) section for more +information. + +## Connection options + +When establishing a connection, you can set the following options: + +* `host`: The hostname of the database you are connecting to. (Default: + `localhost`) +* `port`: The port number to connect to. (Default: `3306`) +* `localAddress`: The source IP address to use for TCP connection. (Optional) +* `socketPath`: The path to a unix domain socket to connect to. When used `host` + and `port` are ignored. +* `user`: The MySQL user to authenticate as. +* `password`: The password of that MySQL user. +* `database`: Name of the database to use for this connection (Optional). +* `charset`: The charset for the connection. This is called "collation" in the SQL-level + of MySQL (like `utf8_general_ci`). If a SQL-level charset is specified (like `utf8mb4`) + then the default collation for that charset is used. (Default: `'UTF8_GENERAL_CI'`) +* `timezone`: The timezone configured on the MySQL server. This is used to type cast server date/time values to JavaScript `Date` object and vice versa. This can be `'local'`, `'Z'`, or an offset in the form `+HH:MM` or `-HH:MM`. (Default: `'local'`) +* `connectTimeout`: The milliseconds before a timeout occurs during the initial connection + to the MySQL server. (Default: `10000`) +* `stringifyObjects`: Stringify objects instead of converting to values. See +issue [#501](https://github.com/mysqljs/mysql/issues/501). (Default: `false`) +* `insecureAuth`: Allow connecting to MySQL instances that ask for the old + (insecure) authentication method. (Default: `false`) +* `typeCast`: Determines if column values should be converted to native + JavaScript types. (Default: `true`) +* `queryFormat`: A custom query format function. See [Custom format](#custom-format). +* `supportBigNumbers`: When dealing with big numbers (BIGINT and DECIMAL columns) in the database, + you should enable this option (Default: `false`). +* `bigNumberStrings`: Enabling both `supportBigNumbers` and `bigNumberStrings` forces big numbers + (BIGINT and DECIMAL columns) to be always returned as JavaScript String objects (Default: `false`). + Enabling `supportBigNumbers` but leaving `bigNumberStrings` disabled will return big numbers as String + objects only when they cannot be accurately represented with [JavaScript Number objects] (http://ecma262-5.com/ELS5_HTML.htm#Section_8.5) + (which happens when they exceed the [-2^53, +2^53] range), otherwise they will be returned as + Number objects. This option is ignored if `supportBigNumbers` is disabled. +* `dateStrings`: Force date types (TIMESTAMP, DATETIME, DATE) to be returned as strings rather than + inflated into JavaScript Date objects. Can be `true`/`false` or an array of type names to keep as + strings. (Default: `false`) +* `debug`: Prints protocol details to stdout. Can be `true`/`false` or an array of packet type names + that should be printed. (Default: `false`) +* `trace`: Generates stack traces on `Error` to include call site of library + entrance ("long stack traces"). Slight performance penalty for most calls. + (Default: `true`) +* `localInfile`: Allow `LOAD DATA INFILE` to use the `LOCAL` modifier. (Default: `true`) +* `multipleStatements`: Allow multiple mysql statements per query. Be careful + with this, it could increase the scope of SQL injection attacks. (Default: `false`) +* `flags`: List of connection flags to use other than the default ones. It is + also possible to blacklist default ones. For more information, check + [Connection Flags](#connection-flags). +* `ssl`: object with ssl parameters or a string containing name of ssl profile. See [SSL options](#ssl-options). + + +In addition to passing these options as an object, you can also use a url +string. For example: + +```js +var connection = mysql.createConnection('mysql://user:pass@host/db?debug=true&charset=BIG5_CHINESE_CI&timezone=-0700'); +``` + +Note: The query values are first attempted to be parsed as JSON, and if that +fails assumed to be plaintext strings. + +### SSL options + +The `ssl` option in the connection options takes a string or an object. When given a string, +it uses one of the predefined SSL profiles included. The following profiles are included: + +* `"Amazon RDS"`: this profile is for connecting to an Amazon RDS server and contains the + certificates from https://rds.amazonaws.com/doc/rds-ssl-ca-cert.pem and + https://s3.amazonaws.com/rds-downloads/rds-combined-ca-bundle.pem + +When connecting to other servers, you will need to provide an object of options, in the +same format as [tls.createSecureContext](https://nodejs.org/api/tls.html#tls_tls_createsecurecontext_options). +Please note the arguments expect a string of the certificate, not a file name to the +certificate. Here is a simple example: + +```js +var connection = mysql.createConnection({ + host : 'localhost', + ssl : { + ca : fs.readFileSync(__dirname + '/mysql-ca.crt') + } +}); +``` + +You can also connect to a MySQL server without properly providing the appropriate +CA to trust. _You should not do this_. + +```js +var connection = mysql.createConnection({ + host : 'localhost', + ssl : { + // DO NOT DO THIS + // set up your ca correctly to trust the connection + rejectUnauthorized: false + } +}); +``` + +### Connection flags + +If, for any reason, you would like to change the default connection flags, you +can use the connection option `flags`. Pass a string with a comma separated list +of items to add to the default flags. If you don't want a default flag to be used +prepend the flag with a minus sign. To add a flag that is not in the default list, +just write the flag name, or prefix it with a plus (case insensitive). + +```js +var connection = mysql.createConnection({ + // disable FOUND_ROWS flag, enable IGNORE_SPACE flag + flags: '-FOUND_ROWS,IGNORE_SPACE' +}); +``` + +The following flags are available: + +- `COMPRESS` - Enable protocol compression. This feature is not currently supported + by the Node.js implementation so cannot be turned on. (Default off) +- `CONNECT_WITH_DB` - Ability to specify the database on connection. (Default on) +- `FOUND_ROWS` - Send the found rows instead of the affected rows as `affectedRows`. + (Default on) +- `IGNORE_SIGPIPE` - Don't issue SIGPIPE if network failures. This flag has no effect + on this Node.js implementation. (Default on) +- `IGNORE_SPACE` - Let the parser ignore spaces before the `(` in queries. (Default on) +- `INTERACTIVE` - Indicates to the MySQL server this is an "interactive" client. This + will use the interactive timeouts on the MySQL server and report as interactive in + the process list. (Default off) +- `LOCAL_FILES` - Can use `LOAD DATA LOCAL`. This flag is controlled by the connection + option `localInfile`. (Default on) +- `LONG_FLAG` - Longer flags in Protocol::ColumnDefinition320. (Default on) +- `LONG_PASSWORD` - Use the improved version of Old Password Authentication. + (Default on) +- `MULTI_RESULTS` - Can handle multiple resultsets for queries. (Default on) +- `MULTI_STATEMENTS` - The client may send multiple statement per query or + statement prepare (separated by `;`). This flag is controlled by the connection + option `multipleStatements`. (Default off) +- `NO_SCHEMA` +- `ODBC` Special handling of ODBC behaviour. This flag has no effect on this Node.js + implementation. (Default on) +- `PLUGIN_AUTH` - Uses the plugin authentication mechanism when connecting to the + MySQL server. This feature is not currently supported by the Node.js implementation + so cannot be turned on. (Default off) +- `PROTOCOL_41` - Uses the 4.1 protocol. (Default on) +- `PS_MULTI_RESULTS` - Can handle multiple resultsets for execute. (Default on) +- `REMEMBER_OPTIONS` - This is specific to the C client, and has no effect on this + Node.js implementation. (Default off) +- `RESERVED` - Old flag for the 4.1 protocol. (Default on) +- `SECURE_CONNECTION` - Support native 4.1 authentication. (Default on) +- `SSL` - Use SSL after handshake to encrypt data in transport. This feature is + controlled though the `ssl` connection option, so the flag has no effect. + (Default off) +- `SSL_VERIFY_SERVER_CERT` - Verify the server certificate during SSL set up. This + feature is controlled though the `ssl.rejectUnauthorized` connection option, so + the flag has no effect. (Default off) +- `TRANSACTIONS` - Asks for the transaction status flags. (Default on) + +## Terminating connections + +There are two ways to end a connection. Terminating a connection gracefully is +done by calling the `end()` method: + +```js +connection.end(function(err) { + // The connection is terminated now +}); +``` + +This will make sure all previously enqueued queries are still before sending a +`COM_QUIT` packet to the MySQL server. If a fatal error occurs before the +`COM_QUIT` packet can be sent, an `err` argument will be provided to the +callback, but the connection will be terminated regardless of that. + +An alternative way to end the connection is to call the `destroy()` method. +This will cause an immediate termination of the underlying socket. +Additionally `destroy()` guarantees that no more events or callbacks will be +triggered for the connection. + +```js +connection.destroy(); +``` + +Unlike `end()` the `destroy()` method does not take a callback argument. + +## Pooling connections + +Rather than creating and managing connections one-by-one, this module also +provides built-in connection pooling using `mysql.createPool(config)`. +[Read more about connection pooling](https://en.wikipedia.org/wiki/Connection_pool). + +Create a pool and use it directly: + +```js +var mysql = require('mysql'); +var pool = mysql.createPool({ + connectionLimit : 10, + host : 'example.org', + user : 'bob', + password : 'secret', + database : 'my_db' +}); + +pool.query('SELECT 1 + 1 AS solution', function (error, results, fields) { + if (error) throw error; + console.log('The solution is: ', results[0].solution); +}); +``` + +This is a shortcut for the `pool.getConnection()` -> `connection.query()` -> +`connection.release()` code flow. Using `pool.getConnection()` is useful to +share connection state for subsequent queries. This is because two calls to +`pool.query()` may use two different connections and run in parallel. This is +the basic structure: + +```js +var mysql = require('mysql'); +var pool = mysql.createPool(...); + +pool.getConnection(function(err, connection) { + if (err) throw err; // not connected! + + // Use the connection + connection.query('SELECT something FROM sometable', function (error, results, fields) { + // When done with the connection, release it. + connection.release(); + + // Handle error after the release. + if (error) throw error; + + // Don't use the connection here, it has been returned to the pool. + }); +}); +``` + +If you would like to close the connection and remove it from the pool, use +`connection.destroy()` instead. The pool will create a new connection the next +time one is needed. + +Connections are lazily created by the pool. If you configure the pool to allow +up to 100 connections, but only ever use 5 simultaneously, only 5 connections +will be made. Connections are also cycled round-robin style, with connections +being taken from the top of the pool and returning to the bottom. + +When a previous connection is retrieved from the pool, a ping packet is sent +to the server to check if the connection is still good. + +## Pool options + +Pools accept all the same [options as a connection](#connection-options). +When creating a new connection, the options are simply passed to the connection +constructor. In addition to those options pools accept a few extras: + +* `acquireTimeout`: The milliseconds before a timeout occurs during the connection + acquisition. This is slightly different from `connectTimeout`, because acquiring + a pool connection does not always involve making a connection. If a connection + request is queued, the time the request spends in the queue does not count + towards this timeout. (Default: `10000`) +* `waitForConnections`: Determines the pool's action when no connections are + available and the limit has been reached. If `true`, the pool will queue the + connection request and call it when one becomes available. If `false`, the + pool will immediately call back with an error. (Default: `true`) +* `connectionLimit`: The maximum number of connections to create at once. + (Default: `10`) +* `queueLimit`: The maximum number of connection requests the pool will queue + before returning an error from `getConnection`. If set to `0`, there is no + limit to the number of queued connection requests. (Default: `0`) + +## Pool events + +### acquire + +The pool will emit an `acquire` event when a connection is acquired from the pool. +This is called after all acquiring activity has been performed on the connection, +right before the connection is handed to the callback of the acquiring code. + +```js +pool.on('acquire', function (connection) { + console.log('Connection %d acquired', connection.threadId); +}); +``` + +### connection + +The pool will emit a `connection` event when a new connection is made within the pool. +If you need to set session variables on the connection before it gets used, you can +listen to the `connection` event. + +```js +pool.on('connection', function (connection) { + connection.query('SET SESSION auto_increment_increment=1') +}); +``` + +### enqueue + +The pool will emit an `enqueue` event when a callback has been queued to wait for +an available connection. + +```js +pool.on('enqueue', function () { + console.log('Waiting for available connection slot'); +}); +``` + +### release + +The pool will emit a `release` event when a connection is released back to the +pool. This is called after all release activity has been performed on the connection, +so the connection will be listed as free at the time of the event. + +```js +pool.on('release', function (connection) { + console.log('Connection %d released', connection.threadId); +}); +``` + +## Closing all the connections in a pool + +When you are done using the pool, you have to end all the connections or the +Node.js event loop will stay active until the connections are closed by the +MySQL server. This is typically done if the pool is used in a script or when +trying to gracefully shutdown a server. To end all the connections in the +pool, use the `end` method on the pool: + +```js +pool.end(function (err) { + // all connections in the pool have ended +}); +``` + +The `end` method takes an _optional_ callback that you can use to know when +all the connections are ended. + +**Once `pool.end` is called, `pool.getConnection` and other operations +can no longer be performed.** Wait until all connections in the pool are +released before calling `pool.end`. If you use the shortcut method +`pool.query`, in place of `pool.getConnection` → `connection.query` → +`connection.release`, wait until it completes. + +`pool.end` calls `connection.end` on every active connection in the pool. +This queues a `QUIT` packet on the connection and sets a flag to prevent +`pool.getConnection` from creating new connections. All commands / queries +already in progress will complete, but new commands won't execute. + +## PoolCluster + +PoolCluster provides multiple hosts connection. (group & retry & selector) + +```js +// create +var poolCluster = mysql.createPoolCluster(); + +// add configurations (the config is a pool config object) +poolCluster.add(config); // add configuration with automatic name +poolCluster.add('MASTER', masterConfig); // add a named configuration +poolCluster.add('SLAVE1', slave1Config); +poolCluster.add('SLAVE2', slave2Config); + +// remove configurations +poolCluster.remove('SLAVE2'); // By nodeId +poolCluster.remove('SLAVE*'); // By target group : SLAVE1-2 + +// Target Group : ALL(anonymous, MASTER, SLAVE1-2), Selector : round-robin(default) +poolCluster.getConnection(function (err, connection) {}); + +// Target Group : MASTER, Selector : round-robin +poolCluster.getConnection('MASTER', function (err, connection) {}); + +// Target Group : SLAVE1-2, Selector : order +// If can't connect to SLAVE1, return SLAVE2. (remove SLAVE1 in the cluster) +poolCluster.on('remove', function (nodeId) { + console.log('REMOVED NODE : ' + nodeId); // nodeId = SLAVE1 +}); + +// A pattern can be passed with * as wildcard +poolCluster.getConnection('SLAVE*', 'ORDER', function (err, connection) {}); + +// The pattern can also be a regular expression +poolCluster.getConnection(/^SLAVE[12]$/, function (err, connection) {}); + +// of namespace : of(pattern, selector) +poolCluster.of('*').getConnection(function (err, connection) {}); + +var pool = poolCluster.of('SLAVE*', 'RANDOM'); +pool.getConnection(function (err, connection) {}); +pool.getConnection(function (err, connection) {}); +pool.query(function (error, results, fields) {}); + +// close all connections +poolCluster.end(function (err) { + // all connections in the pool cluster have ended +}); +``` + +### PoolCluster options + +* `canRetry`: If `true`, `PoolCluster` will attempt to reconnect when connection fails. (Default: `true`) +* `removeNodeErrorCount`: If connection fails, node's `errorCount` increases. + When `errorCount` is greater than `removeNodeErrorCount`, remove a node in the `PoolCluster`. (Default: `5`) +* `restoreNodeTimeout`: If connection fails, specifies the number of milliseconds + before another connection attempt will be made. If set to `0`, then node will be + removed instead and never re-used. (Default: `0`) +* `defaultSelector`: The default selector. (Default: `RR`) + * `RR`: Select one alternately. (Round-Robin) + * `RANDOM`: Select the node by random function. + * `ORDER`: Select the first node available unconditionally. + +```js +var clusterConfig = { + removeNodeErrorCount: 1, // Remove the node immediately when connection fails. + defaultSelector: 'ORDER' +}; + +var poolCluster = mysql.createPoolCluster(clusterConfig); +``` + +## Switching users and altering connection state + +MySQL offers a changeUser command that allows you to alter the current user and +other aspects of the connection without shutting down the underlying socket: + +```js +connection.changeUser({user : 'john'}, function(err) { + if (err) throw err; +}); +``` + +The available options for this feature are: + +* `user`: The name of the new user (defaults to the previous one). +* `password`: The password of the new user (defaults to the previous one). +* `charset`: The new charset (defaults to the previous one). +* `database`: The new database (defaults to the previous one). + +A sometimes useful side effect of this functionality is that this function also +resets any connection state (variables, transactions, etc.). + +Errors encountered during this operation are treated as fatal connection errors +by this module. + +## Server disconnects + +You may lose the connection to a MySQL server due to network problems, the +server timing you out, the server being restarted, or crashing. All of these +events are considered fatal errors, and will have the `err.code = +'PROTOCOL_CONNECTION_LOST'`. See the [Error Handling](#error-handling) section +for more information. + +Re-connecting a connection is done by establishing a new connection. Once +terminated, an existing connection object cannot be re-connected by design. + +With Pool, disconnected connections will be removed from the pool freeing up +space for a new connection to be created on the next getConnection call. + +With PoolCluster, disconnected connections will count as errors against the +related node, incrementing the error code for that node. Once there are more than +`removeNodeErrorCount` errors on a given node, it is removed from the cluster. +When this occurs, the PoolCluster may emit a `POOL_NONEONLINE` error if there are +no longer any matching nodes for the pattern. The `restoreNodeTimeout` config can +be set to restore offline nodes after a given timeout. + +## Performing queries + +The most basic way to perform a query is to call the `.query()` method on an object +(like a `Connection`, `Pool`, or `PoolNamespace` instance). + +The simplest form of .`query()` is `.query(sqlString, callback)`, where a SQL string +is the first argument and the second is a callback: + +```js +connection.query('SELECT * FROM `books` WHERE `author` = "David"', function (error, results, fields) { + // error will be an Error if one occurred during the query + // results will contain the results of the query + // fields will contain information about the returned results fields (if any) +}); +``` + +The second form `.query(sqlString, values, callback)` comes when using +placeholder values (see [escaping query values](#escaping-query-values)): + +```js +connection.query('SELECT * FROM `books` WHERE `author` = ?', ['David'], function (error, results, fields) { + // error will be an Error if one occurred during the query + // results will contain the results of the query + // fields will contain information about the returned results fields (if any) +}); +``` + +The third form `.query(options, callback)` comes when using various advanced +options on the query, like [escaping query values](#escaping-query-values), +[joins with overlapping column names](#joins-with-overlapping-column-names), +[timeouts](#timeout), and [type casting](#type-casting). + +```js +connection.query({ + sql: 'SELECT * FROM `books` WHERE `author` = ?', + timeout: 40000, // 40s + values: ['David'] +}, function (error, results, fields) { + // error will be an Error if one occurred during the query + // results will contain the results of the query + // fields will contain information about the returned results fields (if any) +}); +``` + +Note that a combination of the second and third forms can be used where the +placeholder values are passed as an argument and not in the options object. +The `values` argument will override the `values` in the option object. + +```js +connection.query({ + sql: 'SELECT * FROM `books` WHERE `author` = ?', + timeout: 40000, // 40s + }, + ['David'], + function (error, results, fields) { + // error will be an Error if one occurred during the query + // results will contain the results of the query + // fields will contain information about the returned results fields (if any) + } +); +``` + +If the query only has a single replacement character (`?`), and the value is +not `null`, `undefined`, or an array, it can be passed directly as the second +argument to `.query`: + +```js +connection.query( + 'SELECT * FROM `books` WHERE `author` = ?', + 'David', + function (error, results, fields) { + // error will be an Error if one occurred during the query + // results will contain the results of the query + // fields will contain information about the returned results fields (if any) + } +); +``` + +## Escaping query values + +**Caution** These methods of escaping values only works when the +[NO_BACKSLASH_ESCAPES](https://dev.mysql.com/doc/refman/5.7/en/sql-mode.html#sqlmode_no_backslash_escapes) +SQL mode is disabled (which is the default state for MySQL servers). + +In order to avoid SQL Injection attacks, you should always escape any user +provided data before using it inside a SQL query. You can do so using the +`mysql.escape()`, `connection.escape()` or `pool.escape()` methods: + +```js +var userId = 'some user provided value'; +var sql = 'SELECT * FROM users WHERE id = ' + connection.escape(userId); +connection.query(sql, function (error, results, fields) { + if (error) throw error; + // ... +}); +``` + +Alternatively, you can use `?` characters as placeholders for values you would +like to have escaped like this: + +```js +connection.query('SELECT * FROM users WHERE id = ?', [userId], function (error, results, fields) { + if (error) throw error; + // ... +}); +``` + +Multiple placeholders are mapped to values in the same order as passed. For example, +in the following query `foo` equals `a`, `bar` equals `b`, `baz` equals `c`, and +`id` will be `userId`: + +```js +connection.query('UPDATE users SET foo = ?, bar = ?, baz = ? WHERE id = ?', ['a', 'b', 'c', userId], function (error, results, fields) { + if (error) throw error; + // ... +}); +``` + +This looks similar to prepared statements in MySQL, however it really just uses +the same `connection.escape()` method internally. + +**Caution** This also differs from prepared statements in that all `?` are +replaced, even those contained in comments and strings. + +Different value types are escaped differently, here is how: + +* Numbers are left untouched +* Booleans are converted to `true` / `false` +* Date objects are converted to `'YYYY-mm-dd HH:ii:ss'` strings +* Buffers are converted to hex strings, e.g. `X'0fa5'` +* Strings are safely escaped +* Arrays are turned into list, e.g. `['a', 'b']` turns into `'a', 'b'` +* Nested arrays are turned into grouped lists (for bulk inserts), e.g. `[['a', + 'b'], ['c', 'd']]` turns into `('a', 'b'), ('c', 'd')` +* Objects that have a `toSqlString` method will have `.toSqlString()` called + and the returned value is used as the raw SQL. +* Objects are turned into `key = 'val'` pairs for each enumerable property on + the object. If the property's value is a function, it is skipped; if the + property's value is an object, toString() is called on it and the returned + value is used. +* `undefined` / `null` are converted to `NULL` +* `NaN` / `Infinity` are left as-is. MySQL does not support these, and trying + to insert them as values will trigger MySQL errors until they implement + support. + +This escaping allows you to do neat things like this: + +```js +var post = {id: 1, title: 'Hello MySQL'}; +var query = connection.query('INSERT INTO posts SET ?', post, function (error, results, fields) { + if (error) throw error; + // Neat! +}); +console.log(query.sql); // INSERT INTO posts SET `id` = 1, `title` = 'Hello MySQL' +``` + +And the `toSqlString` method allows you to form complex queries with functions: + +```js +var CURRENT_TIMESTAMP = { toSqlString: function() { return 'CURRENT_TIMESTAMP()'; } }; +var sql = mysql.format('UPDATE posts SET modified = ? WHERE id = ?', [CURRENT_TIMESTAMP, 42]); +console.log(sql); // UPDATE posts SET modified = CURRENT_TIMESTAMP() WHERE id = 42 +``` + +To generate objects with a `toSqlString` method, the `mysql.raw()` method can +be used. This creates an object that will be left un-touched when using in a `?` +placeholder, useful for using functions as dynamic values: + +**Caution** The string provided to `mysql.raw()` will skip all escaping +functions when used, so be careful when passing in unvalidated input. + +```js +var CURRENT_TIMESTAMP = mysql.raw('CURRENT_TIMESTAMP()'); +var sql = mysql.format('UPDATE posts SET modified = ? WHERE id = ?', [CURRENT_TIMESTAMP, 42]); +console.log(sql); // UPDATE posts SET modified = CURRENT_TIMESTAMP() WHERE id = 42 +``` + +If you feel the need to escape queries by yourself, you can also use the escaping +function directly: + +```js +var query = "SELECT * FROM posts WHERE title=" + mysql.escape("Hello MySQL"); + +console.log(query); // SELECT * FROM posts WHERE title='Hello MySQL' +``` + +## Escaping query identifiers + +If you can't trust an SQL identifier (database / table / column name) because it is +provided by a user, you should escape it with `mysql.escapeId(identifier)`, +`connection.escapeId(identifier)` or `pool.escapeId(identifier)` like this: + +```js +var sorter = 'date'; +var sql = 'SELECT * FROM posts ORDER BY ' + connection.escapeId(sorter); +connection.query(sql, function (error, results, fields) { + if (error) throw error; + // ... +}); +``` + +It also supports adding qualified identifiers. It will escape both parts. + +```js +var sorter = 'date'; +var sql = 'SELECT * FROM posts ORDER BY ' + connection.escapeId('posts.' + sorter); +// -> SELECT * FROM posts ORDER BY `posts`.`date` +``` + +If you do not want to treat `.` as qualified identifiers, you can set the second +argument to `true` in order to keep the string as a literal identifier: + +```js +var sorter = 'date.2'; +var sql = 'SELECT * FROM posts ORDER BY ' + connection.escapeId(sorter, true); +// -> SELECT * FROM posts ORDER BY `date.2` +``` + +Alternatively, you can use `??` characters as placeholders for identifiers you would +like to have escaped like this: + +```js +var userId = 1; +var columns = ['username', 'email']; +var query = connection.query('SELECT ?? FROM ?? WHERE id = ?', [columns, 'users', userId], function (error, results, fields) { + if (error) throw error; + // ... +}); + +console.log(query.sql); // SELECT `username`, `email` FROM `users` WHERE id = 1 +``` +**Please note that this last character sequence is experimental and syntax might change** + +When you pass an Object to `.escape()` or `.query()`, `.escapeId()` is used to avoid SQL injection in object keys. + +### Preparing Queries + +You can use mysql.format to prepare a query with multiple insertion points, utilizing the proper escaping for ids and values. A simple example of this follows: + +```js +var sql = "SELECT * FROM ?? WHERE ?? = ?"; +var inserts = ['users', 'id', userId]; +sql = mysql.format(sql, inserts); +``` + +Following this you then have a valid, escaped query that you can then send to the database safely. This is useful if you are looking to prepare the query before actually sending it to the database. As mysql.format is exposed from SqlString.format you also have the option (but are not required) to pass in stringifyObject and timezone, allowing you provide a custom means of turning objects into strings, as well as a location-specific/timezone-aware Date. + +### Custom format + +If you prefer to have another type of query escape format, there's a connection configuration option you can use to define a custom format function. You can access the connection object if you want to use the built-in `.escape()` or any other connection function. + +Here's an example of how to implement another format: + +```js +connection.config.queryFormat = function (query, values) { + if (!values) return query; + return query.replace(/\:(\w+)/g, function (txt, key) { + if (values.hasOwnProperty(key)) { + return this.escape(values[key]); + } + return txt; + }.bind(this)); +}; + +connection.query("UPDATE posts SET title = :title", { title: "Hello MySQL" }); +``` + +## Getting the id of an inserted row + +If you are inserting a row into a table with an auto increment primary key, you +can retrieve the insert id like this: + +```js +connection.query('INSERT INTO posts SET ?', {title: 'test'}, function (error, results, fields) { + if (error) throw error; + console.log(results.insertId); +}); +``` + +When dealing with big numbers (above JavaScript Number precision limit), you should +consider enabling `supportBigNumbers` option to be able to read the insert id as a +string, otherwise it will throw an error. + +This option is also required when fetching big numbers from the database, otherwise +you will get values rounded to hundreds or thousands due to the precision limit. + +## Getting the number of affected rows + +You can get the number of affected rows from an insert, update or delete statement. + +```js +connection.query('DELETE FROM posts WHERE title = "wrong"', function (error, results, fields) { + if (error) throw error; + console.log('deleted ' + results.affectedRows + ' rows'); +}) +``` + +## Getting the number of changed rows + +You can get the number of changed rows from an update statement. + +"changedRows" differs from "affectedRows" in that it does not count updated rows +whose values were not changed. + +```js +connection.query('UPDATE posts SET ...', function (error, results, fields) { + if (error) throw error; + console.log('changed ' + results.changedRows + ' rows'); +}) +``` + +## Getting the connection ID + +You can get the MySQL connection ID ("thread ID") of a given connection using the `threadId` +property. + +```js +connection.connect(function(err) { + if (err) throw err; + console.log('connected as id ' + connection.threadId); +}); +``` + +## Executing queries in parallel + +The MySQL protocol is sequential, this means that you need multiple connections +to execute queries in parallel. You can use a Pool to manage connections, one +simple approach is to create one connection per incoming http request. + +## Streaming query rows + +Sometimes you may want to select large quantities of rows and process each of +them as they are received. This can be done like this: + +```js +var query = connection.query('SELECT * FROM posts'); +query + .on('error', function(err) { + // Handle error, an 'end' event will be emitted after this as well + }) + .on('fields', function(fields) { + // the field packets for the rows to follow + }) + .on('result', function(row) { + // Pausing the connnection is useful if your processing involves I/O + connection.pause(); + + processRow(row, function() { + connection.resume(); + }); + }) + .on('end', function() { + // all rows have been received + }); +``` + +Please note a few things about the example above: + +* Usually you will want to receive a certain amount of rows before starting to + throttle the connection using `pause()`. This number will depend on the + amount and size of your rows. +* `pause()` / `resume()` operate on the underlying socket and parser. You are + guaranteed that no more `'result'` events will fire after calling `pause()`. +* You MUST NOT provide a callback to the `query()` method when streaming rows. +* The `'result'` event will fire for both rows as well as OK packets + confirming the success of a INSERT/UPDATE query. +* It is very important not to leave the result paused too long, or you may + encounter `Error: Connection lost: The server closed the connection.` + The time limit for this is determined by the + [net_write_timeout setting](https://dev.mysql.com/doc/refman/5.5/en/server-system-variables.html#sysvar_net_write_timeout) + on your MySQL server. + +Additionally you may be interested to know that it is currently not possible to +stream individual row columns, they will always be buffered up entirely. If you +have a good use case for streaming large fields to and from MySQL, I'd love to +get your thoughts and contributions on this. + +### Piping results with Streams + +The query object provides a convenience method `.stream([options])` that wraps +query events into a [Readable Stream](http://nodejs.org/api/stream.html#stream_class_stream_readable) +object. This stream can easily be piped downstream and provides automatic +pause/resume, based on downstream congestion and the optional `highWaterMark`. +The `objectMode` parameter of the stream is set to `true` and cannot be changed +(if you need a byte stream, you will need to use a transform stream, like +[objstream](https://www.npmjs.com/package/objstream) for example). + +For example, piping query results into another stream (with a max buffer of 5 +objects) is simply: + +```js +connection.query('SELECT * FROM posts') + .stream({highWaterMark: 5}) + .pipe(...); +``` + +## Multiple statement queries + +Support for multiple statements is disabled for security reasons (it allows for +SQL injection attacks if values are not properly escaped). To use this feature +you have to enable it for your connection: + +```js +var connection = mysql.createConnection({multipleStatements: true}); +``` + +Once enabled, you can execute multiple statement queries like any other query: + +```js +connection.query('SELECT 1; SELECT 2', function (error, results, fields) { + if (error) throw error; + // `results` is an array with one element for every statement in the query: + console.log(results[0]); // [{1: 1}] + console.log(results[1]); // [{2: 2}] +}); +``` + +Additionally you can also stream the results of multiple statement queries: + +```js +var query = connection.query('SELECT 1; SELECT 2'); + +query + .on('fields', function(fields, index) { + // the fields for the result rows that follow + }) + .on('result', function(row, index) { + // index refers to the statement this result belongs to (starts at 0) + }); +``` + +If one of the statements in your query causes an error, the resulting Error +object contains a `err.index` property which tells you which statement caused +it. MySQL will also stop executing any remaining statements when an error +occurs. + +Please note that the interface for streaming multiple statement queries is +experimental and I am looking forward to feedback on it. + +## Stored procedures + +You can call stored procedures from your queries as with any other mysql driver. +If the stored procedure produces several result sets, they are exposed to you +the same way as the results for multiple statement queries. + +## Joins with overlapping column names + +When executing joins, you are likely to get result sets with overlapping column +names. + +By default, node-mysql will overwrite colliding column names in the +order the columns are received from MySQL, causing some of the received values +to be unavailable. + +However, you can also specify that you want your columns to be nested below +the table name like this: + +```js +var options = {sql: '...', nestTables: true}; +connection.query(options, function (error, results, fields) { + if (error) throw error; + /* results will be an array like this now: + [{ + table1: { + fieldA: '...', + fieldB: '...', + }, + table2: { + fieldA: '...', + fieldB: '...', + }, + }, ...] + */ +}); +``` + +Or use a string separator to have your results merged. + +```js +var options = {sql: '...', nestTables: '_'}; +connection.query(options, function (error, results, fields) { + if (error) throw error; + /* results will be an array like this now: + [{ + table1_fieldA: '...', + table1_fieldB: '...', + table2_fieldA: '...', + table2_fieldB: '...', + }, ...] + */ +}); +``` + +## Transactions + +Simple transaction support is available at the connection level: + +```js +connection.beginTransaction(function(err) { + if (err) { throw err; } + connection.query('INSERT INTO posts SET title=?', title, function (error, results, fields) { + if (error) { + return connection.rollback(function() { + throw error; + }); + } + + var log = 'Post ' + results.insertId + ' added'; + + connection.query('INSERT INTO log SET data=?', log, function (error, results, fields) { + if (error) { + return connection.rollback(function() { + throw error; + }); + } + connection.commit(function(err) { + if (err) { + return connection.rollback(function() { + throw err; + }); + } + console.log('success!'); + }); + }); + }); +}); +``` +Please note that beginTransaction(), commit() and rollback() are simply convenience +functions that execute the START TRANSACTION, COMMIT, and ROLLBACK commands respectively. +It is important to understand that many commands in MySQL can cause an implicit commit, +as described [in the MySQL documentation](http://dev.mysql.com/doc/refman/5.5/en/implicit-commit.html) + +## Ping + +A ping packet can be sent over a connection using the `connection.ping` method. This +method will send a ping packet to the server and when the server responds, the callback +will fire. If an error occurred, the callback will fire with an error argument. + +```js +connection.ping(function (err) { + if (err) throw err; + console.log('Server responded to ping'); +}) +``` + +## Timeouts + +Every operation takes an optional inactivity timeout option. This allows you to +specify appropriate timeouts for operations. It is important to note that these +timeouts are not part of the MySQL protocol, and rather timeout operations through +the client. This means that when a timeout is reached, the connection it occurred +on will be destroyed and no further operations can be performed. + +```js +// Kill query after 60s +connection.query({sql: 'SELECT COUNT(*) AS count FROM big_table', timeout: 60000}, function (error, results, fields) { + if (error && error.code === 'PROTOCOL_SEQUENCE_TIMEOUT') { + throw new Error('too long to count table rows!'); + } + + if (error) { + throw error; + } + + console.log(results[0].count + ' rows'); +}); +``` + +## Error handling + +This module comes with a consistent approach to error handling that you should +review carefully in order to write solid applications. + +Most errors created by this module are instances of the JavaScript [Error][] +object. Additionally they typically come with two extra properties: + +* `err.code`: String, contains the MySQL server error symbol if the error is + a [MySQL server error][] (e.g. `'ER_ACCESS_DENIED_ERROR'`), a Node.js error + code if it is a Node.js error (e.g. `'ECONNREFUSED'`), or an internal error + code (e.g. `'PROTOCOL_CONNECTION_LOST'`). +* `err.errno`: Number, contains the MySQL server error number. Only populated + from [MySQL server error][]. +* `err.fatal`: Boolean, indicating if this error is terminal to the connection + object. If the error is not from a MySQL protocol operation, this property + will not be defined. +* `err.sql`: String, contains the full SQL of the failed query. This can be + useful when using a higher level interface like an ORM that is generating + the queries. +* `err.sqlState`: String, contains the five-character SQLSTATE value. Only populated from [MySQL server error][]. +* `err.sqlMessage`: String, contains the message string that provides a + textual description of the error. Only populated from [MySQL server error][]. + +[Error]: https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Error +[MySQL server error]: https://dev.mysql.com/doc/refman/5.5/en/server-error-reference.html + +Fatal errors are propagated to *all* pending callbacks. In the example below, a +fatal error is triggered by trying to connect to an invalid port. Therefore the +error object is propagated to both pending callbacks: + +```js +var connection = require('mysql').createConnection({ + port: 84943, // WRONG PORT +}); + +connection.connect(function(err) { + console.log(err.code); // 'ECONNREFUSED' + console.log(err.fatal); // true +}); + +connection.query('SELECT 1', function (error, results, fields) { + console.log(error.code); // 'ECONNREFUSED' + console.log(error.fatal); // true +}); +``` + +Normal errors however are only delegated to the callback they belong to. So in +the example below, only the first callback receives an error, the second query +works as expected: + +```js +connection.query('USE name_of_db_that_does_not_exist', function (error, results, fields) { + console.log(error.code); // 'ER_BAD_DB_ERROR' +}); + +connection.query('SELECT 1', function (error, results, fields) { + console.log(error); // null + console.log(results.length); // 1 +}); +``` + +Last but not least: If a fatal errors occurs and there are no pending +callbacks, or a normal error occurs which has no callback belonging to it, the +error is emitted as an `'error'` event on the connection object. This is +demonstrated in the example below: + +```js +connection.on('error', function(err) { + console.log(err.code); // 'ER_BAD_DB_ERROR' +}); + +connection.query('USE name_of_db_that_does_not_exist'); +``` + +Note: `'error'` events are special in node. If they occur without an attached +listener, a stack trace is printed and your process is killed. + +**tl;dr:** This module does not want you to deal with silent failures. You +should always provide callbacks to your method calls. If you want to ignore +this advice and suppress unhandled errors, you can do this: + +```js +// I am Chuck Norris: +connection.on('error', function() {}); +``` + +## Exception Safety + +This module is exception safe. That means you can continue to use it, even if +one of your callback functions throws an error which you're catching using +'uncaughtException' or a domain. + +## Type casting + +For your convenience, this driver will cast mysql types into native JavaScript +types by default. The following mappings exist: + +### Number + +* TINYINT +* SMALLINT +* INT +* MEDIUMINT +* YEAR +* FLOAT +* DOUBLE + +### Date + +* TIMESTAMP +* DATE +* DATETIME + +### Buffer + +* TINYBLOB +* MEDIUMBLOB +* LONGBLOB +* BLOB +* BINARY +* VARBINARY +* BIT (last byte will be filled with 0 bits as necessary) + +### String + +**Note** text in the binary character set is returned as `Buffer`, rather +than a string. + +* CHAR +* VARCHAR +* TINYTEXT +* MEDIUMTEXT +* LONGTEXT +* TEXT +* ENUM +* SET +* DECIMAL (may exceed float precision) +* BIGINT (may exceed float precision) +* TIME (could be mapped to Date, but what date would be set?) +* GEOMETRY (never used those, get in touch if you do) + +It is not recommended (and may go away / change in the future) to disable type +casting, but you can currently do so on either the connection: + +```js +var connection = require('mysql').createConnection({typeCast: false}); +``` + +Or on the query level: + +```js +var options = {sql: '...', typeCast: false}; +var query = connection.query(options, function (error, results, fields) { + if (error) throw error; + // ... +}); +``` + +### Custom type casting + +You can also pass a function and handle type casting yourself. You're given some +column information like database, table and name and also type and length. If you +just want to apply a custom type casting to a specific type you can do it and then +fallback to the default. + +The function is provided two arguments `field` and `next` and is expected to +return the value for the given field by invoking the parser functions through +the `field` object. + +The `field` argument is a `Field` object and contains data about the field that +need to be parsed. The following are some of the properties on a `Field` object: + + * `db` - a string of the database the field came from. + * `table` - a string of the table the field came from. + * `name` - a string of the field name. + * `type` - a string of the field type in all caps. + * `length` - a number of the field length, as given by the database. + +The `next` argument is a `function` that, when called, will return the default +type conversion for the given field. + +When getting the field data, the following helper methods are present on the +`field` object: + + * `.string()` - parse the field into a string. + * `.buffer()` - parse the field into a `Buffer`. + * `.geometry()` - parse the field as a geometry value. + +The MySQL protocol is a text-based protocol. This means that over the wire, all +field types are represented as a string, which is why only string-like functions +are available on the `field` object. Based on the type information (like `INT`), +the type cast should convert the string field into a different JavaScript type +(like a `number`). + +Here's an example of converting `TINYINT(1)` to boolean: + +```js +connection = mysql.createConnection({ + typeCast: function (field, next) { + if (field.type === 'TINY' && field.length === 1) { + return (field.string() === '1'); // 1 = true, 0 = false + } else { + return next(); + } + } +}); +``` + +__WARNING: YOU MUST INVOKE the parser using one of these three field functions +in your custom typeCast callback. They can only be called once.__ + +## Debugging and reporting problems + +If you are running into problems, one thing that may help is enabling the +`debug` mode for the connection: + +```js +var connection = mysql.createConnection({debug: true}); +``` + +This will print all incoming and outgoing packets on stdout. You can also restrict debugging to +packet types by passing an array of types to debug: + +```js +var connection = mysql.createConnection({debug: ['ComQueryPacket', 'RowDataPacket']}); +``` + +to restrict debugging to the query and data packets. + +If that does not help, feel free to open a GitHub issue. A good GitHub issue +will have: + +* The minimal amount of code required to reproduce the problem (if possible) +* As much debugging output and information about your environment (mysql + version, node version, os, etc.) as you can gather. + +## Security issues + +Security issues should not be first reported through GitHub or another public +forum, but kept private in order for the collaborators to assess the report +and either (a) devise a fix and plan a release date or (b) assert that it is +not a security issue (in which case it can be posted in a public forum, like +a GitHub issue). + +The primary private forum is email, either by emailing the module's author or +opening a GitHub issue simply asking to whom a security issues should be +addressed to without disclosing the issue or type of issue. + +An ideal report would include a clear indication of what the security issue is +and how it would be exploited, ideally with an accompanying proof of concept +("PoC") for collaborators to work against and validate potentional fixes against. + +## Contributing + +This project welcomes contributions from the community. Contributions are +accepted using GitHub pull requests. If you're not familiar with making +GitHub pull requests, please refer to the +[GitHub documentation "Creating a pull request"](https://help.github.com/articles/creating-a-pull-request/). + +For a good pull request, we ask you provide the following: + +1. Try to include a clear description of your pull request in the description. + It should include the basic "what" and "why"s for the request. +2. The tests should pass as best as you can. See the [Running tests](#running-tests) + section on how to run the different tests. GitHub will automatically run + the tests as well, to act as a safety net. +3. The pull request should include tests for the change. A new feature should + have tests for the new feature and bug fixes should include a test that fails + without the corresponding code change and passes after they are applied. + The command `npm run test-cov` will generate a `coverage/` folder that + contains HTML pages of the code coverage, to better understand if everything + you're adding is being tested. +4. If the pull request is a new feature, please be sure to include all + appropriate documentation additions in the `Readme.md` file as well. +5. To help ensure that your code is similar in style to the existing code, + run the command `npm run lint` and fix any displayed issues. + +## Running tests + +The test suite is split into two parts: unit tests and integration tests. +The unit tests run on any machine while the integration tests require a +MySQL server instance to be setup. + +### Running unit tests + +```sh +$ FILTER=unit npm test +``` + +### Running integration tests + +Set the environment variables `MYSQL_DATABASE`, `MYSQL_HOST`, `MYSQL_PORT`, +`MYSQL_USER` and `MYSQL_PASSWORD`. `MYSQL_SOCKET` can also be used in place +of `MYSQL_HOST` and `MYSQL_PORT` to connect over a UNIX socket. Then run +`npm test`. + +For example, if you have an installation of mysql running on localhost:3306 +and no password set for the `root` user, run: + +```sh +$ mysql -u root -e "CREATE DATABASE IF NOT EXISTS node_mysql_test" +$ MYSQL_HOST=localhost MYSQL_PORT=3306 MYSQL_DATABASE=node_mysql_test MYSQL_USER=root MYSQL_PASSWORD= FILTER=integration npm test +``` + +## Todo + +* Prepared statements +* Support for encodings other than UTF-8 / ASCII + +[appveyor-image]: https://badgen.net/appveyor/ci/dougwilson/node-mysql/master?label=windows +[appveyor-url]: https://ci.appveyor.com/project/dougwilson/node-mysql +[coveralls-image]: https://badgen.net/coveralls/c/github/mysqljs/mysql/master +[coveralls-url]: https://coveralls.io/r/mysqljs/mysql?branch=master +[node-image]: https://badgen.net/npm/node/mysql +[node-url]: https://nodejs.org/en/download +[npm-downloads-image]: https://badgen.net/npm/dm/mysql +[npm-url]: https://npmjs.org/package/mysql +[npm-version-image]: https://badgen.net/npm/v/mysql +[travis-image]: https://badgen.net/travis/mysqljs/mysql/master +[travis-url]: https://travis-ci.org/mysqljs/mysql diff --git a/ts-ticket-office-service/node_modules/mysql/index.js b/ts-ticket-office-service/node_modules/mysql/index.js new file mode 100644 index 000000000..72624076b --- /dev/null +++ b/ts-ticket-office-service/node_modules/mysql/index.js @@ -0,0 +1,161 @@ +var Classes = Object.create(null); + +/** + * Create a new Connection instance. + * @param {object|string} config Configuration or connection string for new MySQL connection + * @return {Connection} A new MySQL connection + * @public + */ +exports.createConnection = function createConnection(config) { + var Connection = loadClass('Connection'); + var ConnectionConfig = loadClass('ConnectionConfig'); + + return new Connection({config: new ConnectionConfig(config)}); +}; + +/** + * Create a new Pool instance. + * @param {object|string} config Configuration or connection string for new MySQL connections + * @return {Pool} A new MySQL pool + * @public + */ +exports.createPool = function createPool(config) { + var Pool = loadClass('Pool'); + var PoolConfig = loadClass('PoolConfig'); + + return new Pool({config: new PoolConfig(config)}); +}; + +/** + * Create a new PoolCluster instance. + * @param {object} [config] Configuration for pool cluster + * @return {PoolCluster} New MySQL pool cluster + * @public + */ +exports.createPoolCluster = function createPoolCluster(config) { + var PoolCluster = loadClass('PoolCluster'); + + return new PoolCluster(config); +}; + +/** + * Create a new Query instance. + * @param {string} sql The SQL for the query + * @param {array} [values] Any values to insert into placeholders in sql + * @param {function} [callback] The callback to use when query is complete + * @return {Query} New query object + * @public + */ +exports.createQuery = function createQuery(sql, values, callback) { + var Connection = loadClass('Connection'); + + return Connection.createQuery(sql, values, callback); +}; + +/** + * Escape a value for SQL. + * @param {*} value The value to escape + * @param {boolean} [stringifyObjects=false] Setting if objects should be stringified + * @param {string} [timeZone=local] Setting for time zone to use for Date conversion + * @return {string} Escaped string value + * @public + */ +exports.escape = function escape(value, stringifyObjects, timeZone) { + var SqlString = loadClass('SqlString'); + + return SqlString.escape(value, stringifyObjects, timeZone); +}; + +/** + * Escape an identifier for SQL. + * @param {*} value The value to escape + * @param {boolean} [forbidQualified=false] Setting to treat '.' as part of identifier + * @return {string} Escaped string value + * @public + */ +exports.escapeId = function escapeId(value, forbidQualified) { + var SqlString = loadClass('SqlString'); + + return SqlString.escapeId(value, forbidQualified); +}; + +/** + * Format SQL and replacement values into a SQL string. + * @param {string} sql The SQL for the query + * @param {array} [values] Any values to insert into placeholders in sql + * @param {boolean} [stringifyObjects=false] Setting if objects should be stringified + * @param {string} [timeZone=local] Setting for time zone to use for Date conversion + * @return {string} Formatted SQL string + * @public + */ +exports.format = function format(sql, values, stringifyObjects, timeZone) { + var SqlString = loadClass('SqlString'); + + return SqlString.format(sql, values, stringifyObjects, timeZone); +}; + +/** + * Wrap raw SQL strings from escape overriding. + * @param {string} sql The raw SQL + * @return {object} Wrapped object + * @public + */ +exports.raw = function raw(sql) { + var SqlString = loadClass('SqlString'); + + return SqlString.raw(sql); +}; + +/** + * The type constants. + * @public + */ +Object.defineProperty(exports, 'Types', { + get: loadClass.bind(null, 'Types') +}); + +/** + * Load the given class. + * @param {string} className Name of class to default + * @return {function|object} Class constructor or exports + * @private + */ +function loadClass(className) { + var Class = Classes[className]; + + if (Class !== undefined) { + return Class; + } + + // This uses a switch for static require analysis + switch (className) { + case 'Connection': + Class = require('./lib/Connection'); + break; + case 'ConnectionConfig': + Class = require('./lib/ConnectionConfig'); + break; + case 'Pool': + Class = require('./lib/Pool'); + break; + case 'PoolCluster': + Class = require('./lib/PoolCluster'); + break; + case 'PoolConfig': + Class = require('./lib/PoolConfig'); + break; + case 'SqlString': + Class = require('./lib/protocol/SqlString'); + break; + case 'Types': + Class = require('./lib/protocol/constants/types'); + break; + default: + throw new Error('Cannot find class \'' + className + '\''); + } + + // Store to prevent invoking require() + Classes[className] = Class; + + return Class; +} diff --git a/ts-ticket-office-service/node_modules/mysql/lib/Connection.js b/ts-ticket-office-service/node_modules/mysql/lib/Connection.js new file mode 100644 index 000000000..6802255dd --- /dev/null +++ b/ts-ticket-office-service/node_modules/mysql/lib/Connection.js @@ -0,0 +1,529 @@ +var Crypto = require('crypto'); +var Events = require('events'); +var Net = require('net'); +var tls = require('tls'); +var ConnectionConfig = require('./ConnectionConfig'); +var Protocol = require('./protocol/Protocol'); +var SqlString = require('./protocol/SqlString'); +var Query = require('./protocol/sequences/Query'); +var Util = require('util'); + +module.exports = Connection; +Util.inherits(Connection, Events.EventEmitter); +function Connection(options) { + Events.EventEmitter.call(this); + + this.config = options.config; + + this._socket = options.socket; + this._protocol = new Protocol({config: this.config, connection: this}); + this._connectCalled = false; + this.state = 'disconnected'; + this.threadId = null; +} + +Connection.createQuery = function createQuery(sql, values, callback) { + if (sql instanceof Query) { + return sql; + } + + var cb = callback; + var options = {}; + + if (typeof sql === 'function') { + cb = sql; + } else if (typeof sql === 'object') { + options = Object.create(sql); + + if (typeof values === 'function') { + cb = values; + } else if (values !== undefined) { + Object.defineProperty(options, 'values', { value: values }); + } + } else { + options.sql = sql; + + if (typeof values === 'function') { + cb = values; + } else if (values !== undefined) { + options.values = values; + } + } + + if (cb !== undefined) { + cb = wrapCallbackInDomain(null, cb); + + if (cb === undefined) { + throw new TypeError('argument callback must be a function when provided'); + } + } + + return new Query(options, cb); +}; + +Connection.prototype.connect = function connect(options, callback) { + if (!callback && typeof options === 'function') { + callback = options; + options = {}; + } + + if (!this._connectCalled) { + this._connectCalled = true; + + // Connect either via a UNIX domain socket or a TCP socket. + this._socket = (this.config.socketPath) + ? Net.createConnection(this.config.socketPath) + : Net.createConnection(this.config.port, this.config.host); + + // Connect socket to connection domain + if (Events.usingDomains) { + this._socket.domain = this.domain; + } + + var connection = this; + this._protocol.on('data', function(data) { + connection._socket.write(data); + }); + this._socket.on('data', wrapToDomain(connection, function (data) { + connection._protocol.write(data); + })); + this._protocol.on('end', function() { + connection._socket.end(); + }); + this._socket.on('end', wrapToDomain(connection, function () { + connection._protocol.end(); + })); + + this._socket.on('error', this._handleNetworkError.bind(this)); + this._socket.on('connect', this._handleProtocolConnect.bind(this)); + this._protocol.on('handshake', this._handleProtocolHandshake.bind(this)); + this._protocol.on('initialize', this._handleProtocolInitialize.bind(this)); + this._protocol.on('unhandledError', this._handleProtocolError.bind(this)); + this._protocol.on('drain', this._handleProtocolDrain.bind(this)); + this._protocol.on('end', this._handleProtocolEnd.bind(this)); + this._protocol.on('enqueue', this._handleProtocolEnqueue.bind(this)); + + if (this.config.connectTimeout) { + var handleConnectTimeout = this._handleConnectTimeout.bind(this); + + this._socket.setTimeout(this.config.connectTimeout, handleConnectTimeout); + this._socket.once('connect', function() { + this.setTimeout(0, handleConnectTimeout); + }); + } + } + + this._protocol.handshake(options, wrapCallbackInDomain(this, callback)); +}; + +Connection.prototype.changeUser = function changeUser(options, callback) { + if (!callback && typeof options === 'function') { + callback = options; + options = {}; + } + + this._implyConnect(); + + var charsetNumber = (options.charset) + ? ConnectionConfig.getCharsetNumber(options.charset) + : this.config.charsetNumber; + + return this._protocol.changeUser({ + user : options.user || this.config.user, + password : options.password || this.config.password, + database : options.database || this.config.database, + timeout : options.timeout, + charsetNumber : charsetNumber, + currentConfig : this.config + }, wrapCallbackInDomain(this, callback)); +}; + +Connection.prototype.beginTransaction = function beginTransaction(options, callback) { + if (!callback && typeof options === 'function') { + callback = options; + options = {}; + } + + options = options || {}; + options.sql = 'START TRANSACTION'; + options.values = null; + + return this.query(options, callback); +}; + +Connection.prototype.commit = function commit(options, callback) { + if (!callback && typeof options === 'function') { + callback = options; + options = {}; + } + + options = options || {}; + options.sql = 'COMMIT'; + options.values = null; + + return this.query(options, callback); +}; + +Connection.prototype.rollback = function rollback(options, callback) { + if (!callback && typeof options === 'function') { + callback = options; + options = {}; + } + + options = options || {}; + options.sql = 'ROLLBACK'; + options.values = null; + + return this.query(options, callback); +}; + +Connection.prototype.query = function query(sql, values, cb) { + var query = Connection.createQuery(sql, values, cb); + query._connection = this; + + if (!(typeof sql === 'object' && 'typeCast' in sql)) { + query.typeCast = this.config.typeCast; + } + + if (query.sql) { + query.sql = this.format(query.sql, query.values); + } + + if (query._callback) { + query._callback = wrapCallbackInDomain(this, query._callback); + } + + this._implyConnect(); + + return this._protocol._enqueue(query); +}; + +Connection.prototype.ping = function ping(options, callback) { + if (!callback && typeof options === 'function') { + callback = options; + options = {}; + } + + this._implyConnect(); + this._protocol.ping(options, wrapCallbackInDomain(this, callback)); +}; + +Connection.prototype.statistics = function statistics(options, callback) { + if (!callback && typeof options === 'function') { + callback = options; + options = {}; + } + + this._implyConnect(); + this._protocol.stats(options, wrapCallbackInDomain(this, callback)); +}; + +Connection.prototype.end = function end(options, callback) { + var cb = callback; + var opts = options; + + if (!callback && typeof options === 'function') { + cb = options; + opts = null; + } + + // create custom options reference + opts = Object.create(opts || null); + + if (opts.timeout === undefined) { + // default timeout of 30 seconds + opts.timeout = 30000; + } + + this._implyConnect(); + this._protocol.quit(opts, wrapCallbackInDomain(this, cb)); +}; + +Connection.prototype.destroy = function() { + this.state = 'disconnected'; + this._implyConnect(); + this._socket.destroy(); + this._protocol.destroy(); +}; + +Connection.prototype.pause = function() { + this._socket.pause(); + this._protocol.pause(); +}; + +Connection.prototype.resume = function() { + this._socket.resume(); + this._protocol.resume(); +}; + +Connection.prototype.escape = function(value) { + return SqlString.escape(value, false, this.config.timezone); +}; + +Connection.prototype.escapeId = function escapeId(value) { + return SqlString.escapeId(value, false); +}; + +Connection.prototype.format = function(sql, values) { + if (typeof this.config.queryFormat === 'function') { + return this.config.queryFormat.call(this, sql, values, this.config.timezone); + } + return SqlString.format(sql, values, this.config.stringifyObjects, this.config.timezone); +}; + +if (tls.TLSSocket) { + // 0.11+ environment + Connection.prototype._startTLS = function _startTLS(onSecure) { + var connection = this; + + createSecureContext(this.config, function (err, secureContext) { + if (err) { + onSecure(err); + return; + } + + // "unpipe" + connection._socket.removeAllListeners('data'); + connection._protocol.removeAllListeners('data'); + + // socket <-> encrypted + var rejectUnauthorized = connection.config.ssl.rejectUnauthorized; + var secureEstablished = false; + var secureSocket = new tls.TLSSocket(connection._socket, { + rejectUnauthorized : rejectUnauthorized, + requestCert : true, + secureContext : secureContext, + isServer : false + }); + + // error handler for secure socket + secureSocket.on('_tlsError', function(err) { + if (secureEstablished) { + connection._handleNetworkError(err); + } else { + onSecure(err); + } + }); + + // cleartext <-> protocol + secureSocket.pipe(connection._protocol); + connection._protocol.on('data', function(data) { + secureSocket.write(data); + }); + + secureSocket.on('secure', function() { + secureEstablished = true; + + onSecure(rejectUnauthorized ? this.ssl.verifyError() : null); + }); + + // start TLS communications + secureSocket._start(); + }); + }; +} else { + // pre-0.11 environment + Connection.prototype._startTLS = function _startTLS(onSecure) { + // before TLS: + // _socket <-> _protocol + // after: + // _socket <-> securePair.encrypted <-> securePair.cleartext <-> _protocol + + var connection = this; + var credentials = Crypto.createCredentials({ + ca : this.config.ssl.ca, + cert : this.config.ssl.cert, + ciphers : this.config.ssl.ciphers, + key : this.config.ssl.key, + passphrase : this.config.ssl.passphrase + }); + + var rejectUnauthorized = this.config.ssl.rejectUnauthorized; + var secureEstablished = false; + var securePair = tls.createSecurePair(credentials, false, true, rejectUnauthorized); + + // error handler for secure pair + securePair.on('error', function(err) { + if (secureEstablished) { + connection._handleNetworkError(err); + } else { + onSecure(err); + } + }); + + // "unpipe" + this._socket.removeAllListeners('data'); + this._protocol.removeAllListeners('data'); + + // socket <-> encrypted + securePair.encrypted.pipe(this._socket); + this._socket.on('data', function(data) { + securePair.encrypted.write(data); + }); + + // cleartext <-> protocol + securePair.cleartext.pipe(this._protocol); + this._protocol.on('data', function(data) { + securePair.cleartext.write(data); + }); + + // secure established + securePair.on('secure', function() { + secureEstablished = true; + + if (!rejectUnauthorized) { + onSecure(); + return; + } + + var verifyError = this.ssl.verifyError(); + var err = verifyError; + + // node.js 0.6 support + if (typeof err === 'string') { + err = new Error(verifyError); + err.code = verifyError; + } + + onSecure(err); + }); + + // node.js 0.8 bug + securePair._cycle = securePair.cycle; + securePair.cycle = function cycle() { + if (this.ssl && this.ssl.error) { + this.error(); + } + + return this._cycle.apply(this, arguments); + }; + }; +} + +Connection.prototype._handleConnectTimeout = function() { + if (this._socket) { + this._socket.setTimeout(0); + this._socket.destroy(); + } + + var err = new Error('connect ETIMEDOUT'); + err.errorno = 'ETIMEDOUT'; + err.code = 'ETIMEDOUT'; + err.syscall = 'connect'; + + this._handleNetworkError(err); +}; + +Connection.prototype._handleNetworkError = function(err) { + this._protocol.handleNetworkError(err); +}; + +Connection.prototype._handleProtocolError = function(err) { + this.state = 'protocol_error'; + this.emit('error', err); +}; + +Connection.prototype._handleProtocolDrain = function() { + this.emit('drain'); +}; + +Connection.prototype._handleProtocolConnect = function() { + this.state = 'connected'; + this.emit('connect'); +}; + +Connection.prototype._handleProtocolHandshake = function _handleProtocolHandshake() { + this.state = 'authenticated'; +}; + +Connection.prototype._handleProtocolInitialize = function _handleProtocolInitialize(packet) { + this.threadId = packet.threadId; +}; + +Connection.prototype._handleProtocolEnd = function(err) { + this.state = 'disconnected'; + this.emit('end', err); +}; + +Connection.prototype._handleProtocolEnqueue = function _handleProtocolEnqueue(sequence) { + this.emit('enqueue', sequence); +}; + +Connection.prototype._implyConnect = function() { + if (!this._connectCalled) { + this.connect(); + } +}; + +function createSecureContext (config, cb) { + var context = null; + var error = null; + + try { + context = tls.createSecureContext({ + ca : config.ssl.ca, + cert : config.ssl.cert, + ciphers : config.ssl.ciphers, + key : config.ssl.key, + passphrase : config.ssl.passphrase + }); + } catch (err) { + error = err; + } + + cb(error, context); +} + +function unwrapFromDomain(fn) { + return function () { + var domains = []; + var ret; + + while (process.domain) { + domains.shift(process.domain); + process.domain.exit(); + } + + try { + ret = fn.apply(this, arguments); + } finally { + for (var i = 0; i < domains.length; i++) { + domains[i].enter(); + } + } + + return ret; + }; +} + +function wrapCallbackInDomain(ee, fn) { + if (typeof fn !== 'function') { + return undefined; + } + + if (fn.domain) { + return fn; + } + + var domain = process.domain; + + if (domain) { + return domain.bind(fn); + } else if (ee) { + return unwrapFromDomain(wrapToDomain(ee, fn)); + } else { + return fn; + } +} + +function wrapToDomain(ee, fn) { + return function () { + if (Events.usingDomains && ee.domain) { + ee.domain.enter(); + fn.apply(this, arguments); + ee.domain.exit(); + } else { + fn.apply(this, arguments); + } + }; +} diff --git a/ts-ticket-office-service/node_modules/mysql/lib/ConnectionConfig.js b/ts-ticket-office-service/node_modules/mysql/lib/ConnectionConfig.js new file mode 100644 index 000000000..06f4399c5 --- /dev/null +++ b/ts-ticket-office-service/node_modules/mysql/lib/ConnectionConfig.js @@ -0,0 +1,209 @@ +var urlParse = require('url').parse; +var ClientConstants = require('./protocol/constants/client'); +var Charsets = require('./protocol/constants/charsets'); +var SSLProfiles = null; + +module.exports = ConnectionConfig; +function ConnectionConfig(options) { + if (typeof options === 'string') { + options = ConnectionConfig.parseUrl(options); + } + + this.host = options.host || 'localhost'; + this.port = options.port || 3306; + this.localAddress = options.localAddress; + this.socketPath = options.socketPath; + this.user = options.user || undefined; + this.password = options.password || undefined; + this.database = options.database; + this.connectTimeout = (options.connectTimeout === undefined) + ? (10 * 1000) + : options.connectTimeout; + this.insecureAuth = options.insecureAuth || false; + this.supportBigNumbers = options.supportBigNumbers || false; + this.bigNumberStrings = options.bigNumberStrings || false; + this.dateStrings = options.dateStrings || false; + this.debug = options.debug; + this.trace = options.trace !== false; + this.stringifyObjects = options.stringifyObjects || false; + this.timezone = options.timezone || 'local'; + this.flags = options.flags || ''; + this.queryFormat = options.queryFormat; + this.pool = options.pool || undefined; + this.ssl = (typeof options.ssl === 'string') + ? ConnectionConfig.getSSLProfile(options.ssl) + : (options.ssl || false); + this.localInfile = (options.localInfile === undefined) + ? true + : options.localInfile; + this.multipleStatements = options.multipleStatements || false; + this.typeCast = (options.typeCast === undefined) + ? true + : options.typeCast; + + if (this.timezone[0] === ' ') { + // "+" is a url encoded char for space so it + // gets translated to space when giving a + // connection string.. + this.timezone = '+' + this.timezone.substr(1); + } + + if (this.ssl) { + // Default rejectUnauthorized to true + this.ssl.rejectUnauthorized = this.ssl.rejectUnauthorized !== false; + } + + this.maxPacketSize = 0; + this.charsetNumber = (options.charset) + ? ConnectionConfig.getCharsetNumber(options.charset) + : options.charsetNumber || Charsets.UTF8_GENERAL_CI; + + // Set the client flags + var defaultFlags = ConnectionConfig.getDefaultFlags(options); + this.clientFlags = ConnectionConfig.mergeFlags(defaultFlags, options.flags); +} + +ConnectionConfig.mergeFlags = function mergeFlags(defaultFlags, userFlags) { + var allFlags = ConnectionConfig.parseFlagList(defaultFlags); + var newFlags = ConnectionConfig.parseFlagList(userFlags); + + // Merge the new flags + for (var flag in newFlags) { + if (allFlags[flag] !== false) { + allFlags[flag] = newFlags[flag]; + } + } + + // Build flags + var flags = 0x0; + for (var flag in allFlags) { + if (allFlags[flag]) { + // TODO: Throw here on some future release + flags |= ClientConstants['CLIENT_' + flag] || 0x0; + } + } + + return flags; +}; + +ConnectionConfig.getCharsetNumber = function getCharsetNumber(charset) { + var num = Charsets[charset.toUpperCase()]; + + if (num === undefined) { + throw new TypeError('Unknown charset \'' + charset + '\''); + } + + return num; +}; + +ConnectionConfig.getDefaultFlags = function getDefaultFlags(options) { + var defaultFlags = [ + '-COMPRESS', // Compression protocol *NOT* supported + '-CONNECT_ATTRS', // Does *NOT* send connection attributes in Protocol::HandshakeResponse41 + '+CONNECT_WITH_DB', // One can specify db on connect in Handshake Response Packet + '+FOUND_ROWS', // Send found rows instead of affected rows + '+IGNORE_SIGPIPE', // Don't issue SIGPIPE if network failures + '+IGNORE_SPACE', // Let the parser ignore spaces before '(' + '+LOCAL_FILES', // Can use LOAD DATA LOCAL + '+LONG_FLAG', // Longer flags in Protocol::ColumnDefinition320 + '+LONG_PASSWORD', // Use the improved version of Old Password Authentication + '+MULTI_RESULTS', // Can handle multiple resultsets for COM_QUERY + '+ODBC', // Special handling of ODBC behaviour + '-PLUGIN_AUTH', // Does *NOT* support auth plugins + '+PROTOCOL_41', // Uses the 4.1 protocol + '+PS_MULTI_RESULTS', // Can handle multiple resultsets for COM_STMT_EXECUTE + '+RESERVED', // Unused + '+SECURE_CONNECTION', // Supports Authentication::Native41 + '+TRANSACTIONS' // Expects status flags + ]; + + if (options && options.localInfile !== undefined && !options.localInfile) { + // Disable LOCAL modifier for LOAD DATA INFILE + defaultFlags.push('-LOCAL_FILES'); + } + + if (options && options.multipleStatements) { + // May send multiple statements per COM_QUERY and COM_STMT_PREPARE + defaultFlags.push('+MULTI_STATEMENTS'); + } + + return defaultFlags; +}; + +ConnectionConfig.getSSLProfile = function getSSLProfile(name) { + if (!SSLProfiles) { + SSLProfiles = require('./protocol/constants/ssl_profiles'); + } + + var ssl = SSLProfiles[name]; + + if (ssl === undefined) { + throw new TypeError('Unknown SSL profile \'' + name + '\''); + } + + return ssl; +}; + +ConnectionConfig.parseFlagList = function parseFlagList(flagList) { + var allFlags = Object.create(null); + + if (!flagList) { + return allFlags; + } + + var flags = !Array.isArray(flagList) + ? String(flagList || '').toUpperCase().split(/\s*,+\s*/) + : flagList; + + for (var i = 0; i < flags.length; i++) { + var flag = flags[i]; + var offset = 1; + var state = flag[0]; + + if (state === undefined) { + // TODO: throw here on some future release + continue; + } + + if (state !== '-' && state !== '+') { + offset = 0; + state = '+'; + } + + allFlags[flag.substr(offset)] = state === '+'; + } + + return allFlags; +}; + +ConnectionConfig.parseUrl = function(url) { + url = urlParse(url, true); + + var options = { + host : url.hostname, + port : url.port, + database : url.pathname.substr(1) + }; + + if (url.auth) { + var auth = url.auth.split(':'); + options.user = auth.shift(); + options.password = auth.join(':'); + } + + if (url.query) { + for (var key in url.query) { + var value = url.query[key]; + + try { + // Try to parse this as a JSON expression first + options[key] = JSON.parse(value); + } catch (err) { + // Otherwise assume it is a plain string + options[key] = value; + } + } + } + + return options; +}; diff --git a/ts-ticket-office-service/node_modules/mysql/lib/Pool.js b/ts-ticket-office-service/node_modules/mysql/lib/Pool.js new file mode 100644 index 000000000..87a40114a --- /dev/null +++ b/ts-ticket-office-service/node_modules/mysql/lib/Pool.js @@ -0,0 +1,294 @@ +var mysql = require('../'); +var Connection = require('./Connection'); +var EventEmitter = require('events').EventEmitter; +var Util = require('util'); +var PoolConnection = require('./PoolConnection'); + +module.exports = Pool; + +Util.inherits(Pool, EventEmitter); +function Pool(options) { + EventEmitter.call(this); + this.config = options.config; + this.config.connectionConfig.pool = this; + + this._acquiringConnections = []; + this._allConnections = []; + this._freeConnections = []; + this._connectionQueue = []; + this._closed = false; +} + +Pool.prototype.getConnection = function (cb) { + + if (this._closed) { + var err = new Error('Pool is closed.'); + err.code = 'POOL_CLOSED'; + process.nextTick(function () { + cb(err); + }); + return; + } + + var connection; + var pool = this; + + if (this._freeConnections.length > 0) { + connection = this._freeConnections.shift(); + this.acquireConnection(connection, cb); + return; + } + + if (this.config.connectionLimit === 0 || this._allConnections.length < this.config.connectionLimit) { + connection = new PoolConnection(this, { config: this.config.newConnectionConfig() }); + + this._acquiringConnections.push(connection); + this._allConnections.push(connection); + + connection.connect({timeout: this.config.acquireTimeout}, function onConnect(err) { + spliceConnection(pool._acquiringConnections, connection); + + if (pool._closed) { + err = new Error('Pool is closed.'); + err.code = 'POOL_CLOSED'; + } + + if (err) { + pool._purgeConnection(connection); + cb(err); + return; + } + + pool.emit('connection', connection); + pool.emit('acquire', connection); + cb(null, connection); + }); + return; + } + + if (!this.config.waitForConnections) { + process.nextTick(function(){ + var err = new Error('No connections available.'); + err.code = 'POOL_CONNLIMIT'; + cb(err); + }); + return; + } + + this._enqueueCallback(cb); +}; + +Pool.prototype.acquireConnection = function acquireConnection(connection, cb) { + if (connection._pool !== this) { + throw new Error('Connection acquired from wrong pool.'); + } + + var changeUser = this._needsChangeUser(connection); + var pool = this; + + this._acquiringConnections.push(connection); + + function onOperationComplete(err) { + spliceConnection(pool._acquiringConnections, connection); + + if (pool._closed) { + err = new Error('Pool is closed.'); + err.code = 'POOL_CLOSED'; + } + + if (err) { + pool._connectionQueue.unshift(cb); + pool._purgeConnection(connection); + return; + } + + if (changeUser) { + pool.emit('connection', connection); + } + + pool.emit('acquire', connection); + cb(null, connection); + } + + if (changeUser) { + // restore user back to pool configuration + connection.config = this.config.newConnectionConfig(); + connection.changeUser({timeout: this.config.acquireTimeout}, onOperationComplete); + } else { + // ping connection + connection.ping({timeout: this.config.acquireTimeout}, onOperationComplete); + } +}; + +Pool.prototype.releaseConnection = function releaseConnection(connection) { + + if (this._acquiringConnections.indexOf(connection) !== -1) { + // connection is being acquired + return; + } + + if (connection._pool) { + if (connection._pool !== this) { + throw new Error('Connection released to wrong pool'); + } + + if (this._freeConnections.indexOf(connection) !== -1) { + // connection already in free connection pool + // this won't catch all double-release cases + throw new Error('Connection already released'); + } else { + // add connection to end of free queue + this._freeConnections.push(connection); + this.emit('release', connection); + } + } + + if (this._closed) { + // empty the connection queue + this._connectionQueue.splice(0).forEach(function (cb) { + var err = new Error('Pool is closed.'); + err.code = 'POOL_CLOSED'; + process.nextTick(function () { + cb(err); + }); + }); + } else if (this._connectionQueue.length) { + // get connection with next waiting callback + this.getConnection(this._connectionQueue.shift()); + } +}; + +Pool.prototype.end = function (cb) { + this._closed = true; + + if (typeof cb !== 'function') { + cb = function (err) { + if (err) throw err; + }; + } + + var calledBack = false; + var waitingClose = 0; + + function onEnd(err) { + if (!calledBack && (err || --waitingClose <= 0)) { + calledBack = true; + cb(err); + } + } + + while (this._allConnections.length !== 0) { + waitingClose++; + this._purgeConnection(this._allConnections[0], onEnd); + } + + if (waitingClose === 0) { + process.nextTick(onEnd); + } +}; + +Pool.prototype.query = function (sql, values, cb) { + var query = Connection.createQuery(sql, values, cb); + + if (!(typeof sql === 'object' && 'typeCast' in sql)) { + query.typeCast = this.config.connectionConfig.typeCast; + } + + if (this.config.connectionConfig.trace) { + // Long stack trace support + query._callSite = new Error(); + } + + this.getConnection(function (err, conn) { + if (err) { + query.on('error', function () {}); + query.end(err); + return; + } + + // Release connection based off event + query.once('end', function() { + conn.release(); + }); + + conn.query(query); + }); + + return query; +}; + +Pool.prototype._enqueueCallback = function _enqueueCallback(callback) { + + if (this.config.queueLimit && this._connectionQueue.length >= this.config.queueLimit) { + process.nextTick(function () { + var err = new Error('Queue limit reached.'); + err.code = 'POOL_ENQUEUELIMIT'; + callback(err); + }); + return; + } + + // Bind to domain, as dequeue will likely occur in a different domain + var cb = process.domain + ? process.domain.bind(callback) + : callback; + + this._connectionQueue.push(cb); + this.emit('enqueue'); +}; + +Pool.prototype._needsChangeUser = function _needsChangeUser(connection) { + var connConfig = connection.config; + var poolConfig = this.config.connectionConfig; + + // check if changeUser values are different + return connConfig.user !== poolConfig.user + || connConfig.database !== poolConfig.database + || connConfig.password !== poolConfig.password + || connConfig.charsetNumber !== poolConfig.charsetNumber; +}; + +Pool.prototype._purgeConnection = function _purgeConnection(connection, callback) { + var cb = callback || function () {}; + + if (connection.state === 'disconnected') { + connection.destroy(); + } + + this._removeConnection(connection); + + if (connection.state !== 'disconnected' && !connection._protocol._quitSequence) { + connection._realEnd(cb); + return; + } + + process.nextTick(cb); +}; + +Pool.prototype._removeConnection = function(connection) { + connection._pool = null; + + // Remove connection from all connections + spliceConnection(this._allConnections, connection); + + // Remove connection from free connections + spliceConnection(this._freeConnections, connection); + + this.releaseConnection(connection); +}; + +Pool.prototype.escape = function(value) { + return mysql.escape(value, this.config.connectionConfig.stringifyObjects, this.config.connectionConfig.timezone); +}; + +Pool.prototype.escapeId = function escapeId(value) { + return mysql.escapeId(value, false); +}; + +function spliceConnection(array, connection) { + var index; + if ((index = array.indexOf(connection)) !== -1) { + // Remove connection from all connections + array.splice(index, 1); + } +} diff --git a/ts-ticket-office-service/node_modules/mysql/lib/PoolCluster.js b/ts-ticket-office-service/node_modules/mysql/lib/PoolCluster.js new file mode 100644 index 000000000..d0aed2c75 --- /dev/null +++ b/ts-ticket-office-service/node_modules/mysql/lib/PoolCluster.js @@ -0,0 +1,288 @@ +var Pool = require('./Pool'); +var PoolConfig = require('./PoolConfig'); +var PoolNamespace = require('./PoolNamespace'); +var PoolSelector = require('./PoolSelector'); +var Util = require('util'); +var EventEmitter = require('events').EventEmitter; + +module.exports = PoolCluster; + +/** + * PoolCluster + * @constructor + * @param {object} [config] The pool cluster configuration + * @public + */ +function PoolCluster(config) { + EventEmitter.call(this); + + config = config || {}; + this._canRetry = typeof config.canRetry === 'undefined' ? true : config.canRetry; + this._defaultSelector = config.defaultSelector || 'RR'; + this._removeNodeErrorCount = config.removeNodeErrorCount || 5; + this._restoreNodeTimeout = config.restoreNodeTimeout || 0; + + this._closed = false; + this._findCaches = Object.create(null); + this._lastId = 0; + this._namespaces = Object.create(null); + this._nodes = Object.create(null); +} + +Util.inherits(PoolCluster, EventEmitter); + +PoolCluster.prototype.add = function add(id, config) { + if (this._closed) { + throw new Error('PoolCluster is closed.'); + } + + var nodeId = typeof id === 'object' + ? 'CLUSTER::' + (++this._lastId) + : String(id); + + if (this._nodes[nodeId] !== undefined) { + throw new Error('Node ID "' + nodeId + '" is already defined in PoolCluster.'); + } + + var poolConfig = typeof id !== 'object' + ? new PoolConfig(config) + : new PoolConfig(id); + + this._nodes[nodeId] = { + id : nodeId, + errorCount : 0, + pool : new Pool({config: poolConfig}), + _offlineUntil : 0 + }; + + this._clearFindCaches(); +}; + +PoolCluster.prototype.end = function end(callback) { + var cb = callback !== undefined + ? callback + : _cb; + + if (typeof cb !== 'function') { + throw TypeError('callback argument must be a function'); + } + + if (this._closed) { + process.nextTick(cb); + return; + } + + this._closed = true; + + var calledBack = false; + var nodeIds = Object.keys(this._nodes); + var waitingClose = 0; + + function onEnd(err) { + if (!calledBack && (err || --waitingClose <= 0)) { + calledBack = true; + cb(err); + } + } + + for (var i = 0; i < nodeIds.length; i++) { + var nodeId = nodeIds[i]; + var node = this._nodes[nodeId]; + + waitingClose++; + node.pool.end(onEnd); + } + + if (waitingClose === 0) { + process.nextTick(onEnd); + } +}; + +PoolCluster.prototype.of = function(pattern, selector) { + pattern = pattern || '*'; + + selector = selector || this._defaultSelector; + selector = selector.toUpperCase(); + if (typeof PoolSelector[selector] === 'undefined') { + selector = this._defaultSelector; + } + + var key = pattern + selector; + + if (typeof this._namespaces[key] === 'undefined') { + this._namespaces[key] = new PoolNamespace(this, pattern, selector); + } + + return this._namespaces[key]; +}; + +PoolCluster.prototype.remove = function remove(pattern) { + var foundNodeIds = this._findNodeIds(pattern, true); + + for (var i = 0; i < foundNodeIds.length; i++) { + var node = this._getNode(foundNodeIds[i]); + + if (node) { + this._removeNode(node); + } + } +}; + +PoolCluster.prototype.getConnection = function(pattern, selector, cb) { + var namespace; + if (typeof pattern === 'function') { + cb = pattern; + namespace = this.of(); + } else { + if (typeof selector === 'function') { + cb = selector; + selector = this._defaultSelector; + } + + namespace = this.of(pattern, selector); + } + + namespace.getConnection(cb); +}; + +PoolCluster.prototype._clearFindCaches = function _clearFindCaches() { + this._findCaches = Object.create(null); +}; + +PoolCluster.prototype._decreaseErrorCount = function _decreaseErrorCount(node) { + var errorCount = node.errorCount; + + if (errorCount > this._removeNodeErrorCount) { + errorCount = this._removeNodeErrorCount; + } + + if (errorCount < 1) { + errorCount = 1; + } + + node.errorCount = errorCount - 1; + + if (node._offlineUntil) { + node._offlineUntil = 0; + this.emit('online', node.id); + } +}; + +PoolCluster.prototype._findNodeIds = function _findNodeIds(pattern, includeOffline) { + var currentTime = 0; + var foundNodeIds = this._findCaches[pattern]; + + if (foundNodeIds === undefined) { + var expression = patternRegExp(pattern); + var nodeIds = Object.keys(this._nodes); + + foundNodeIds = nodeIds.filter(function (id) { + return id.match(expression); + }); + + this._findCaches[pattern] = foundNodeIds; + } + + if (includeOffline) { + return foundNodeIds; + } + + return foundNodeIds.filter(function (nodeId) { + var node = this._getNode(nodeId); + + if (!node._offlineUntil) { + return true; + } + + if (!currentTime) { + currentTime = getMonotonicMilliseconds(); + } + + return node._offlineUntil <= currentTime; + }, this); +}; + +PoolCluster.prototype._getNode = function _getNode(id) { + return this._nodes[id] || null; +}; + +PoolCluster.prototype._increaseErrorCount = function _increaseErrorCount(node) { + var errorCount = ++node.errorCount; + + if (this._removeNodeErrorCount > errorCount) { + return; + } + + if (this._restoreNodeTimeout > 0) { + node._offlineUntil = getMonotonicMilliseconds() + this._restoreNodeTimeout; + this.emit('offline', node.id); + return; + } + + this._removeNode(node); + this.emit('remove', node.id); +}; + +PoolCluster.prototype._getConnection = function(node, cb) { + var self = this; + + node.pool.getConnection(function (err, connection) { + if (err) { + self._increaseErrorCount(node); + cb(err); + return; + } else { + self._decreaseErrorCount(node); + } + + connection._clusterId = node.id; + + cb(null, connection); + }); +}; + +PoolCluster.prototype._removeNode = function _removeNode(node) { + delete this._nodes[node.id]; + + this._clearFindCaches(); + + node.pool.end(_noop); +}; + +function getMonotonicMilliseconds() { + var ms; + + if (typeof process.hrtime === 'function') { + ms = process.hrtime(); + ms = ms[0] * 1e3 + ms[1] * 1e-6; + } else { + ms = process.uptime() * 1000; + } + + return Math.floor(ms); +} + +function isRegExp(val) { + return typeof val === 'object' + && Object.prototype.toString.call(val) === '[object RegExp]'; +} + +function patternRegExp(pattern) { + if (isRegExp(pattern)) { + return pattern; + } + + var source = pattern + .replace(/([.+?^=!:${}()|\[\]\/\\])/g, '\\$1') + .replace(/\*/g, '.*'); + + return new RegExp('^' + source + '$'); +} + +function _cb(err) { + if (err) { + throw err; + } +} + +function _noop() {} diff --git a/ts-ticket-office-service/node_modules/mysql/lib/PoolConfig.js b/ts-ticket-office-service/node_modules/mysql/lib/PoolConfig.js new file mode 100644 index 000000000..8c5017a27 --- /dev/null +++ b/ts-ticket-office-service/node_modules/mysql/lib/PoolConfig.js @@ -0,0 +1,32 @@ + +var ConnectionConfig = require('./ConnectionConfig'); + +module.exports = PoolConfig; +function PoolConfig(options) { + if (typeof options === 'string') { + options = ConnectionConfig.parseUrl(options); + } + + this.acquireTimeout = (options.acquireTimeout === undefined) + ? 10 * 1000 + : Number(options.acquireTimeout); + this.connectionConfig = new ConnectionConfig(options); + this.waitForConnections = (options.waitForConnections === undefined) + ? true + : Boolean(options.waitForConnections); + this.connectionLimit = (options.connectionLimit === undefined) + ? 10 + : Number(options.connectionLimit); + this.queueLimit = (options.queueLimit === undefined) + ? 0 + : Number(options.queueLimit); +} + +PoolConfig.prototype.newConnectionConfig = function newConnectionConfig() { + var connectionConfig = new ConnectionConfig(this.connectionConfig); + + connectionConfig.clientFlags = this.connectionConfig.clientFlags; + connectionConfig.maxPacketSize = this.connectionConfig.maxPacketSize; + + return connectionConfig; +}; diff --git a/ts-ticket-office-service/node_modules/mysql/lib/PoolConnection.js b/ts-ticket-office-service/node_modules/mysql/lib/PoolConnection.js new file mode 100644 index 000000000..064c99d32 --- /dev/null +++ b/ts-ticket-office-service/node_modules/mysql/lib/PoolConnection.js @@ -0,0 +1,65 @@ +var inherits = require('util').inherits; +var Connection = require('./Connection'); +var Events = require('events'); + +module.exports = PoolConnection; +inherits(PoolConnection, Connection); + +function PoolConnection(pool, options) { + Connection.call(this, options); + this._pool = pool; + + // Bind connection to pool domain + if (Events.usingDomains) { + this.domain = pool.domain; + } + + // When a fatal error occurs the connection's protocol ends, which will cause + // the connection to end as well, thus we only need to watch for the end event + // and we will be notified of disconnects. + this.on('end', this._removeFromPool); + this.on('error', function (err) { + if (err.fatal) { + this._removeFromPool(); + } + }); +} + +PoolConnection.prototype.release = function release() { + var pool = this._pool; + + if (!pool || pool._closed) { + return undefined; + } + + return pool.releaseConnection(this); +}; + +// TODO: Remove this when we are removing PoolConnection#end +PoolConnection.prototype._realEnd = Connection.prototype.end; + +PoolConnection.prototype.end = function () { + console.warn( + 'Calling conn.end() to release a pooled connection is ' + + 'deprecated. In next version calling conn.end() will be ' + + 'restored to default conn.end() behavior. Use ' + + 'conn.release() instead.' + ); + this.release(); +}; + +PoolConnection.prototype.destroy = function () { + Connection.prototype.destroy.apply(this, arguments); + this._removeFromPool(this); +}; + +PoolConnection.prototype._removeFromPool = function _removeFromPool() { + if (!this._pool || this._pool._closed) { + return; + } + + var pool = this._pool; + this._pool = null; + + pool._purgeConnection(this); +}; diff --git a/ts-ticket-office-service/node_modules/mysql/lib/PoolNamespace.js b/ts-ticket-office-service/node_modules/mysql/lib/PoolNamespace.js new file mode 100644 index 000000000..d3ea7860f --- /dev/null +++ b/ts-ticket-office-service/node_modules/mysql/lib/PoolNamespace.js @@ -0,0 +1,136 @@ +var Connection = require('./Connection'); +var PoolSelector = require('./PoolSelector'); + +module.exports = PoolNamespace; + +/** + * PoolNamespace + * @constructor + * @param {PoolCluster} cluster The parent cluster for the namespace + * @param {string} pattern The selection pattern to use + * @param {string} selector The selector name to use + * @public + */ +function PoolNamespace(cluster, pattern, selector) { + this._cluster = cluster; + this._pattern = pattern; + this._selector = new PoolSelector[selector](); +} + +PoolNamespace.prototype.getConnection = function(cb) { + var clusterNode = this._getClusterNode(); + var cluster = this._cluster; + var namespace = this; + + if (clusterNode === null) { + var err = null; + + if (this._cluster._findNodeIds(this._pattern, true).length !== 0) { + err = new Error('Pool does not have online node.'); + err.code = 'POOL_NONEONLINE'; + } else { + err = new Error('Pool does not exist.'); + err.code = 'POOL_NOEXIST'; + } + + cb(err); + return; + } + + cluster._getConnection(clusterNode, function(err, connection) { + var retry = err && cluster._canRetry + && cluster._findNodeIds(namespace._pattern).length !== 0; + + if (retry) { + namespace.getConnection(cb); + return; + } + + if (err) { + cb(err); + return; + } + + cb(null, connection); + }); +}; + +PoolNamespace.prototype.query = function (sql, values, cb) { + var cluster = this._cluster; + var clusterNode = this._getClusterNode(); + var query = Connection.createQuery(sql, values, cb); + var namespace = this; + + if (clusterNode === null) { + var err = null; + + if (this._cluster._findNodeIds(this._pattern, true).length !== 0) { + err = new Error('Pool does not have online node.'); + err.code = 'POOL_NONEONLINE'; + } else { + err = new Error('Pool does not exist.'); + err.code = 'POOL_NOEXIST'; + } + + process.nextTick(function () { + query.on('error', function () {}); + query.end(err); + }); + return query; + } + + if (!(typeof sql === 'object' && 'typeCast' in sql)) { + query.typeCast = clusterNode.pool.config.connectionConfig.typeCast; + } + + if (clusterNode.pool.config.connectionConfig.trace) { + // Long stack trace support + query._callSite = new Error(); + } + + cluster._getConnection(clusterNode, function (err, conn) { + var retry = err && cluster._canRetry + && cluster._findNodeIds(namespace._pattern).length !== 0; + + if (retry) { + namespace.query(query); + return; + } + + if (err) { + query.on('error', function () {}); + query.end(err); + return; + } + + // Release connection based off event + query.once('end', function() { + conn.release(); + }); + + conn.query(query); + }); + + return query; +}; + +PoolNamespace.prototype._getClusterNode = function _getClusterNode() { + var foundNodeIds = this._cluster._findNodeIds(this._pattern); + var nodeId; + + switch (foundNodeIds.length) { + case 0: + nodeId = null; + break; + case 1: + nodeId = foundNodeIds[0]; + break; + default: + nodeId = this._selector(foundNodeIds); + break; + } + + return nodeId !== null + ? this._cluster._getNode(nodeId) + : null; +}; diff --git a/ts-ticket-office-service/node_modules/mysql/lib/PoolSelector.js b/ts-ticket-office-service/node_modules/mysql/lib/PoolSelector.js new file mode 100644 index 000000000..9a3c455f2 --- /dev/null +++ b/ts-ticket-office-service/node_modules/mysql/lib/PoolSelector.js @@ -0,0 +1,31 @@ + +/** + * PoolSelector + */ +var PoolSelector = module.exports = {}; + +PoolSelector.RR = function PoolSelectorRoundRobin() { + var index = 0; + + return function(clusterIds) { + if (index >= clusterIds.length) { + index = 0; + } + + var clusterId = clusterIds[index++]; + + return clusterId; + }; +}; + +PoolSelector.RANDOM = function PoolSelectorRandom() { + return function(clusterIds) { + return clusterIds[Math.floor(Math.random() * clusterIds.length)]; + }; +}; + +PoolSelector.ORDER = function PoolSelectorOrder() { + return function(clusterIds) { + return clusterIds[0]; + }; +}; diff --git a/ts-ticket-office-service/node_modules/mysql/lib/protocol/Auth.js b/ts-ticket-office-service/node_modules/mysql/lib/protocol/Auth.js new file mode 100644 index 000000000..a1033d1b9 --- /dev/null +++ b/ts-ticket-office-service/node_modules/mysql/lib/protocol/Auth.js @@ -0,0 +1,168 @@ +var Buffer = require('safe-buffer').Buffer; +var Crypto = require('crypto'); +var Auth = exports; + +function auth(name, data, options) { + options = options || {}; + + switch (name) { + case 'mysql_native_password': + return Auth.token(options.password, data.slice(0, 20)); + default: + return undefined; + } +} +Auth.auth = auth; + +function sha1(msg) { + var hash = Crypto.createHash('sha1'); + hash.update(msg, 'binary'); + return hash.digest('binary'); +} +Auth.sha1 = sha1; + +function xor(a, b) { + a = Buffer.from(a, 'binary'); + b = Buffer.from(b, 'binary'); + var result = Buffer.allocUnsafe(a.length); + for (var i = 0; i < a.length; i++) { + result[i] = (a[i] ^ b[i]); + } + return result; +} +Auth.xor = xor; + +Auth.token = function(password, scramble) { + if (!password) { + return Buffer.alloc(0); + } + + // password must be in binary format, not utf8 + var stage1 = sha1((Buffer.from(password, 'utf8')).toString('binary')); + var stage2 = sha1(stage1); + var stage3 = sha1(scramble.toString('binary') + stage2); + return xor(stage3, stage1); +}; + +// This is a port of sql/password.c:hash_password which needs to be used for +// pre-4.1 passwords. +Auth.hashPassword = function(password) { + var nr = [0x5030, 0x5735]; + var add = 7; + var nr2 = [0x1234, 0x5671]; + var result = Buffer.alloc(8); + + if (typeof password === 'string'){ + password = Buffer.from(password); + } + + for (var i = 0; i < password.length; i++) { + var c = password[i]; + if (c === 32 || c === 9) { + // skip space in password + continue; + } + + // nr^= (((nr & 63)+add)*c)+ (nr << 8); + // nr = xor(nr, add(mul(add(and(nr, 63), add), c), shl(nr, 8))) + nr = this.xor32(nr, this.add32(this.mul32(this.add32(this.and32(nr, [0, 63]), [0, add]), [0, c]), this.shl32(nr, 8))); + + // nr2+=(nr2 << 8) ^ nr; + // nr2 = add(nr2, xor(shl(nr2, 8), nr)) + nr2 = this.add32(nr2, this.xor32(this.shl32(nr2, 8), nr)); + + // add+=tmp; + add += c; + } + + this.int31Write(result, nr, 0); + this.int31Write(result, nr2, 4); + + return result; +}; + +Auth.randomInit = function(seed1, seed2) { + return { + max_value : 0x3FFFFFFF, + max_value_dbl : 0x3FFFFFFF, + seed1 : seed1 % 0x3FFFFFFF, + seed2 : seed2 % 0x3FFFFFFF + }; +}; + +Auth.myRnd = function(r){ + r.seed1 = (r.seed1 * 3 + r.seed2) % r.max_value; + r.seed2 = (r.seed1 + r.seed2 + 33) % r.max_value; + + return r.seed1 / r.max_value_dbl; +}; + +Auth.scramble323 = function(message, password) { + if (!password) { + return Buffer.alloc(0); + } + + var to = Buffer.allocUnsafe(8); + var hashPass = this.hashPassword(password); + var hashMessage = this.hashPassword(message.slice(0, 8)); + var seed1 = this.int32Read(hashPass, 0) ^ this.int32Read(hashMessage, 0); + var seed2 = this.int32Read(hashPass, 4) ^ this.int32Read(hashMessage, 4); + var r = this.randomInit(seed1, seed2); + + for (var i = 0; i < 8; i++){ + to[i] = Math.floor(this.myRnd(r) * 31) + 64; + } + var extra = (Math.floor(this.myRnd(r) * 31)); + + for (var i = 0; i < 8; i++){ + to[i] ^= extra; + } + + return to; +}; + +Auth.xor32 = function(a, b){ + return [a[0] ^ b[0], a[1] ^ b[1]]; +}; + +Auth.add32 = function(a, b){ + var w1 = a[1] + b[1]; + var w2 = a[0] + b[0] + ((w1 & 0xFFFF0000) >> 16); + + return [w2 & 0xFFFF, w1 & 0xFFFF]; +}; + +Auth.mul32 = function(a, b){ + // based on this example of multiplying 32b ints using 16b + // http://www.dsprelated.com/showmessage/89790/1.php + var w1 = a[1] * b[1]; + var w2 = (((a[1] * b[1]) >> 16) & 0xFFFF) + ((a[0] * b[1]) & 0xFFFF) + (a[1] * b[0] & 0xFFFF); + + return [w2 & 0xFFFF, w1 & 0xFFFF]; +}; + +Auth.and32 = function(a, b){ + return [a[0] & b[0], a[1] & b[1]]; +}; + +Auth.shl32 = function(a, b){ + // assume b is 16 or less + var w1 = a[1] << b; + var w2 = (a[0] << b) | ((w1 & 0xFFFF0000) >> 16); + + return [w2 & 0xFFFF, w1 & 0xFFFF]; +}; + +Auth.int31Write = function(buffer, number, offset) { + buffer[offset] = (number[0] >> 8) & 0x7F; + buffer[offset + 1] = (number[0]) & 0xFF; + buffer[offset + 2] = (number[1] >> 8) & 0xFF; + buffer[offset + 3] = (number[1]) & 0xFF; +}; + +Auth.int32Read = function(buffer, offset){ + return (buffer[offset] << 24) + + (buffer[offset + 1] << 16) + + (buffer[offset + 2] << 8) + + (buffer[offset + 3]); +}; diff --git a/ts-ticket-office-service/node_modules/mysql/lib/protocol/BufferList.js b/ts-ticket-office-service/node_modules/mysql/lib/protocol/BufferList.js new file mode 100644 index 000000000..3cd01926a --- /dev/null +++ b/ts-ticket-office-service/node_modules/mysql/lib/protocol/BufferList.js @@ -0,0 +1,25 @@ + +module.exports = BufferList; +function BufferList() { + this.bufs = []; + this.size = 0; +} + +BufferList.prototype.shift = function shift() { + var buf = this.bufs.shift(); + + if (buf) { + this.size -= buf.length; + } + + return buf; +}; + +BufferList.prototype.push = function push(buf) { + if (!buf || !buf.length) { + return; + } + + this.bufs.push(buf); + this.size += buf.length; +}; diff --git a/ts-ticket-office-service/node_modules/mysql/lib/protocol/PacketHeader.js b/ts-ticket-office-service/node_modules/mysql/lib/protocol/PacketHeader.js new file mode 100644 index 000000000..1bb282e4b --- /dev/null +++ b/ts-ticket-office-service/node_modules/mysql/lib/protocol/PacketHeader.js @@ -0,0 +1,5 @@ +module.exports = PacketHeader; +function PacketHeader(length, number) { + this.length = length; + this.number = number; +} diff --git a/ts-ticket-office-service/node_modules/mysql/lib/protocol/PacketWriter.js b/ts-ticket-office-service/node_modules/mysql/lib/protocol/PacketWriter.js new file mode 100644 index 000000000..4d0afd2af --- /dev/null +++ b/ts-ticket-office-service/node_modules/mysql/lib/protocol/PacketWriter.js @@ -0,0 +1,211 @@ +var BIT_16 = Math.pow(2, 16); +var BIT_24 = Math.pow(2, 24); +var BUFFER_ALLOC_SIZE = Math.pow(2, 8); +// The maximum precision JS Numbers can hold precisely +// Don't panic: Good enough to represent byte values up to 8192 TB +var IEEE_754_BINARY_64_PRECISION = Math.pow(2, 53); +var MAX_PACKET_LENGTH = Math.pow(2, 24) - 1; +var Buffer = require('safe-buffer').Buffer; + +module.exports = PacketWriter; +function PacketWriter() { + this._buffer = null; + this._offset = 0; +} + +PacketWriter.prototype.toBuffer = function toBuffer(parser) { + if (!this._buffer) { + this._buffer = Buffer.alloc(0); + this._offset = 0; + } + + var buffer = this._buffer; + var length = this._offset; + var packets = Math.floor(length / MAX_PACKET_LENGTH) + 1; + + this._buffer = Buffer.allocUnsafe(length + packets * 4); + this._offset = 0; + + for (var packet = 0; packet < packets; packet++) { + var isLast = (packet + 1 === packets); + var packetLength = (isLast) + ? length % MAX_PACKET_LENGTH + : MAX_PACKET_LENGTH; + + var packetNumber = parser.incrementPacketNumber(); + + this.writeUnsignedNumber(3, packetLength); + this.writeUnsignedNumber(1, packetNumber); + + var start = packet * MAX_PACKET_LENGTH; + var end = start + packetLength; + + this.writeBuffer(buffer.slice(start, end)); + } + + return this._buffer; +}; + +PacketWriter.prototype.writeUnsignedNumber = function(bytes, value) { + this._allocate(bytes); + + for (var i = 0; i < bytes; i++) { + this._buffer[this._offset++] = (value >> (i * 8)) & 0xff; + } +}; + +PacketWriter.prototype.writeFiller = function(bytes) { + this._allocate(bytes); + + for (var i = 0; i < bytes; i++) { + this._buffer[this._offset++] = 0x00; + } +}; + +PacketWriter.prototype.writeNullTerminatedString = function(value, encoding) { + // Typecast undefined into '' and numbers into strings + value = value || ''; + value = value + ''; + + var bytes = Buffer.byteLength(value, encoding || 'utf-8') + 1; + this._allocate(bytes); + + this._buffer.write(value, this._offset, encoding); + this._buffer[this._offset + bytes - 1] = 0x00; + + this._offset += bytes; +}; + +PacketWriter.prototype.writeString = function(value) { + // Typecast undefined into '' and numbers into strings + value = value || ''; + value = value + ''; + + var bytes = Buffer.byteLength(value, 'utf-8'); + this._allocate(bytes); + + this._buffer.write(value, this._offset, 'utf-8'); + + this._offset += bytes; +}; + +PacketWriter.prototype.writeBuffer = function(value) { + var bytes = value.length; + + this._allocate(bytes); + value.copy(this._buffer, this._offset); + this._offset += bytes; +}; + +PacketWriter.prototype.writeLengthCodedNumber = function(value) { + if (value === null) { + this._allocate(1); + this._buffer[this._offset++] = 251; + return; + } + + if (value <= 250) { + this._allocate(1); + this._buffer[this._offset++] = value; + return; + } + + if (value > IEEE_754_BINARY_64_PRECISION) { + throw new Error( + 'writeLengthCodedNumber: JS precision range exceeded, your ' + + 'number is > 53 bit: "' + value + '"' + ); + } + + if (value < BIT_16) { + this._allocate(3); + this._buffer[this._offset++] = 252; + } else if (value < BIT_24) { + this._allocate(4); + this._buffer[this._offset++] = 253; + } else { + this._allocate(9); + this._buffer[this._offset++] = 254; + } + + // 16 Bit + this._buffer[this._offset++] = value & 0xff; + this._buffer[this._offset++] = (value >> 8) & 0xff; + + if (value < BIT_16) { + return; + } + + // 24 Bit + this._buffer[this._offset++] = (value >> 16) & 0xff; + + if (value < BIT_24) { + return; + } + + this._buffer[this._offset++] = (value >> 24) & 0xff; + + // Hack: Get the most significant 32 bit (JS bitwise operators are 32 bit) + value = value.toString(2); + value = value.substr(0, value.length - 32); + value = parseInt(value, 2); + + this._buffer[this._offset++] = value & 0xff; + this._buffer[this._offset++] = (value >> 8) & 0xff; + this._buffer[this._offset++] = (value >> 16) & 0xff; + + // Set last byte to 0, as we can only support 53 bits in JS (see above) + this._buffer[this._offset++] = 0; +}; + +PacketWriter.prototype.writeLengthCodedBuffer = function(value) { + var bytes = value.length; + this.writeLengthCodedNumber(bytes); + this.writeBuffer(value); +}; + +PacketWriter.prototype.writeNullTerminatedBuffer = function(value) { + this.writeBuffer(value); + this.writeFiller(1); // 0x00 terminator +}; + +PacketWriter.prototype.writeLengthCodedString = function(value) { + if (value === null) { + this.writeLengthCodedNumber(null); + return; + } + + value = (value === undefined) + ? '' + : String(value); + + var bytes = Buffer.byteLength(value, 'utf-8'); + this.writeLengthCodedNumber(bytes); + + if (!bytes) { + return; + } + + this._allocate(bytes); + this._buffer.write(value, this._offset, 'utf-8'); + this._offset += bytes; +}; + +PacketWriter.prototype._allocate = function _allocate(bytes) { + if (!this._buffer) { + this._buffer = Buffer.alloc(Math.max(BUFFER_ALLOC_SIZE, bytes)); + this._offset = 0; + return; + } + + var bytesRemaining = this._buffer.length - this._offset; + if (bytesRemaining >= bytes) { + return; + } + + var newSize = this._buffer.length + Math.max(BUFFER_ALLOC_SIZE, bytes); + var oldBuffer = this._buffer; + + this._buffer = Buffer.alloc(newSize); + oldBuffer.copy(this._buffer); +}; diff --git a/ts-ticket-office-service/node_modules/mysql/lib/protocol/Parser.js b/ts-ticket-office-service/node_modules/mysql/lib/protocol/Parser.js new file mode 100644 index 000000000..e72555f2e --- /dev/null +++ b/ts-ticket-office-service/node_modules/mysql/lib/protocol/Parser.js @@ -0,0 +1,491 @@ +var PacketHeader = require('./PacketHeader'); +var BigNumber = require('bignumber.js'); +var Buffer = require('safe-buffer').Buffer; +var BufferList = require('./BufferList'); + +var MAX_PACKET_LENGTH = Math.pow(2, 24) - 1; +var MUL_32BIT = Math.pow(2, 32); +var PACKET_HEADER_LENGTH = 4; + +module.exports = Parser; +function Parser(options) { + options = options || {}; + + this._supportBigNumbers = options.config && options.config.supportBigNumbers; + this._buffer = Buffer.alloc(0); + this._nextBuffers = new BufferList(); + this._longPacketBuffers = new BufferList(); + this._offset = 0; + this._packetEnd = null; + this._packetHeader = null; + this._packetOffset = null; + this._onError = options.onError || function(err) { throw err; }; + this._onPacket = options.onPacket || function() {}; + this._nextPacketNumber = 0; + this._encoding = 'utf-8'; + this._paused = false; +} + +Parser.prototype.write = function write(chunk) { + this._nextBuffers.push(chunk); + + while (!this._paused) { + var packetHeader = this._tryReadPacketHeader(); + + if (!packetHeader) { + break; + } + + if (!this._combineNextBuffers(packetHeader.length)) { + break; + } + + this._parsePacket(packetHeader); + } +}; + +Parser.prototype.append = function append(chunk) { + if (!chunk || chunk.length === 0) { + return; + } + + // Calculate slice ranges + var sliceEnd = this._buffer.length; + var sliceStart = this._packetOffset === null + ? this._offset + : this._packetOffset; + var sliceLength = sliceEnd - sliceStart; + + // Get chunk data + var buffer = null; + var chunks = !(chunk instanceof Array || Array.isArray(chunk)) ? [chunk] : chunk; + var length = 0; + var offset = 0; + + for (var i = 0; i < chunks.length; i++) { + length += chunks[i].length; + } + + if (sliceLength !== 0) { + // Create a new Buffer + buffer = Buffer.allocUnsafe(sliceLength + length); + offset = 0; + + // Copy data slice + offset += this._buffer.copy(buffer, 0, sliceStart, sliceEnd); + + // Copy chunks + for (var i = 0; i < chunks.length; i++) { + offset += chunks[i].copy(buffer, offset); + } + } else if (chunks.length > 1) { + // Create a new Buffer + buffer = Buffer.allocUnsafe(length); + offset = 0; + + // Copy chunks + for (var i = 0; i < chunks.length; i++) { + offset += chunks[i].copy(buffer, offset); + } + } else { + // Buffer is the only chunk + buffer = chunks[0]; + } + + // Adjust data-tracking pointers + this._buffer = buffer; + this._offset = this._offset - sliceStart; + this._packetEnd = this._packetEnd !== null + ? this._packetEnd - sliceStart + : null; + this._packetOffset = this._packetOffset !== null + ? this._packetOffset - sliceStart + : null; +}; + +Parser.prototype.pause = function() { + this._paused = true; +}; + +Parser.prototype.resume = function() { + this._paused = false; + + // nextTick() to avoid entering write() multiple times within the same stack + // which would cause problems as write manipulates the state of the object. + process.nextTick(this.write.bind(this)); +}; + +Parser.prototype.peak = function peak(offset) { + return this._buffer[this._offset + (offset >>> 0)]; +}; + +Parser.prototype.parseUnsignedNumber = function parseUnsignedNumber(bytes) { + if (bytes === 1) { + return this._buffer[this._offset++]; + } + + var buffer = this._buffer; + var offset = this._offset + bytes - 1; + var value = 0; + + if (bytes > 4) { + var err = new Error('parseUnsignedNumber: Supports only up to 4 bytes'); + err.offset = (this._offset - this._packetOffset - 1); + err.code = 'PARSER_UNSIGNED_TOO_LONG'; + throw err; + } + + while (offset >= this._offset) { + value = ((value << 8) | buffer[offset]) >>> 0; + offset--; + } + + this._offset += bytes; + + return value; +}; + +Parser.prototype.parseLengthCodedString = function() { + var length = this.parseLengthCodedNumber(); + + if (length === null) { + return null; + } + + return this.parseString(length); +}; + +Parser.prototype.parseLengthCodedBuffer = function() { + var length = this.parseLengthCodedNumber(); + + if (length === null) { + return null; + } + + return this.parseBuffer(length); +}; + +Parser.prototype.parseLengthCodedNumber = function parseLengthCodedNumber() { + if (this._offset >= this._buffer.length) { + var err = new Error('Parser: read past end'); + err.offset = (this._offset - this._packetOffset); + err.code = 'PARSER_READ_PAST_END'; + throw err; + } + + var bits = this._buffer[this._offset++]; + + if (bits <= 250) { + return bits; + } + + switch (bits) { + case 251: + return null; + case 252: + return this.parseUnsignedNumber(2); + case 253: + return this.parseUnsignedNumber(3); + case 254: + break; + default: + var err = new Error('Unexpected first byte' + (bits ? ': 0x' + bits.toString(16) : '')); + err.offset = (this._offset - this._packetOffset - 1); + err.code = 'PARSER_BAD_LENGTH_BYTE'; + throw err; + } + + var low = this.parseUnsignedNumber(4); + var high = this.parseUnsignedNumber(4); + var value; + + if (high >>> 21) { + value = BigNumber(MUL_32BIT).times(high).plus(low).toString(); + + if (this._supportBigNumbers) { + return value; + } + + var err = new Error( + 'parseLengthCodedNumber: JS precision range exceeded, ' + + 'number is >= 53 bit: "' + value + '"' + ); + err.offset = (this._offset - this._packetOffset - 8); + err.code = 'PARSER_JS_PRECISION_RANGE_EXCEEDED'; + throw err; + } + + value = low + (MUL_32BIT * high); + + return value; +}; + +Parser.prototype.parseFiller = function(length) { + return this.parseBuffer(length); +}; + +Parser.prototype.parseNullTerminatedBuffer = function() { + var end = this._nullByteOffset(); + var value = this._buffer.slice(this._offset, end); + this._offset = end + 1; + + return value; +}; + +Parser.prototype.parseNullTerminatedString = function() { + var end = this._nullByteOffset(); + var value = this._buffer.toString(this._encoding, this._offset, end); + this._offset = end + 1; + + return value; +}; + +Parser.prototype._nullByteOffset = function() { + var offset = this._offset; + + while (this._buffer[offset] !== 0x00) { + offset++; + + if (offset >= this._buffer.length) { + var err = new Error('Offset of null terminated string not found.'); + err.offset = (this._offset - this._packetOffset); + err.code = 'PARSER_MISSING_NULL_BYTE'; + throw err; + } + } + + return offset; +}; + +Parser.prototype.parsePacketTerminatedBuffer = function parsePacketTerminatedBuffer() { + var length = this._packetEnd - this._offset; + return this.parseBuffer(length); +}; + +Parser.prototype.parsePacketTerminatedString = function() { + var length = this._packetEnd - this._offset; + return this.parseString(length); +}; + +Parser.prototype.parseBuffer = function(length) { + var response = Buffer.alloc(length); + this._buffer.copy(response, 0, this._offset, this._offset + length); + + this._offset += length; + return response; +}; + +Parser.prototype.parseString = function(length) { + var offset = this._offset; + var end = offset + length; + var value = this._buffer.toString(this._encoding, offset, end); + + this._offset = end; + return value; +}; + +Parser.prototype.parseGeometryValue = function() { + var buffer = this.parseLengthCodedBuffer(); + var offset = 4; + + if (buffer === null || !buffer.length) { + return null; + } + + function parseGeometry() { + var result = null; + var byteOrder = buffer.readUInt8(offset); offset += 1; + var wkbType = byteOrder ? buffer.readUInt32LE(offset) : buffer.readUInt32BE(offset); offset += 4; + switch (wkbType) { + case 1: // WKBPoint + var x = byteOrder ? buffer.readDoubleLE(offset) : buffer.readDoubleBE(offset); offset += 8; + var y = byteOrder ? buffer.readDoubleLE(offset) : buffer.readDoubleBE(offset); offset += 8; + result = {x: x, y: y}; + break; + case 2: // WKBLineString + var numPoints = byteOrder ? buffer.readUInt32LE(offset) : buffer.readUInt32BE(offset); offset += 4; + result = []; + for (var i = numPoints; i > 0; i--) { + var x = byteOrder ? buffer.readDoubleLE(offset) : buffer.readDoubleBE(offset); offset += 8; + var y = byteOrder ? buffer.readDoubleLE(offset) : buffer.readDoubleBE(offset); offset += 8; + result.push({x: x, y: y}); + } + break; + case 3: // WKBPolygon + var numRings = byteOrder ? buffer.readUInt32LE(offset) : buffer.readUInt32BE(offset); offset += 4; + result = []; + for (var i = numRings; i > 0; i--) { + var numPoints = byteOrder ? buffer.readUInt32LE(offset) : buffer.readUInt32BE(offset); offset += 4; + var line = []; + for (var j = numPoints; j > 0; j--) { + var x = byteOrder ? buffer.readDoubleLE(offset) : buffer.readDoubleBE(offset); offset += 8; + var y = byteOrder ? buffer.readDoubleLE(offset) : buffer.readDoubleBE(offset); offset += 8; + line.push({x: x, y: y}); + } + result.push(line); + } + break; + case 4: // WKBMultiPoint + case 5: // WKBMultiLineString + case 6: // WKBMultiPolygon + case 7: // WKBGeometryCollection + var num = byteOrder ? buffer.readUInt32LE(offset) : buffer.readUInt32BE(offset); offset += 4; + var result = []; + for (var i = num; i > 0; i--) { + result.push(parseGeometry()); + } + break; + } + return result; + } + return parseGeometry(); +}; + +Parser.prototype.reachedPacketEnd = function() { + return this._offset === this._packetEnd; +}; + +Parser.prototype.incrementPacketNumber = function() { + var currentPacketNumber = this._nextPacketNumber; + this._nextPacketNumber = (this._nextPacketNumber + 1) % 256; + + return currentPacketNumber; +}; + +Parser.prototype.resetPacketNumber = function() { + this._nextPacketNumber = 0; +}; + +Parser.prototype.packetLength = function packetLength() { + if (!this._packetHeader) { + return null; + } + + return this._packetHeader.length + this._longPacketBuffers.size; +}; + +Parser.prototype._combineNextBuffers = function _combineNextBuffers(bytes) { + var length = this._buffer.length - this._offset; + + if (length >= bytes) { + return true; + } + + if ((length + this._nextBuffers.size) < bytes) { + return false; + } + + var buffers = []; + var bytesNeeded = bytes - length; + + while (bytesNeeded > 0) { + var buffer = this._nextBuffers.shift(); + buffers.push(buffer); + bytesNeeded -= buffer.length; + } + + this.append(buffers); + return true; +}; + +Parser.prototype._combineLongPacketBuffers = function _combineLongPacketBuffers() { + if (!this._longPacketBuffers.size) { + return; + } + + // Calculate bytes + var remainingBytes = this._buffer.length - this._offset; + var trailingPacketBytes = this._buffer.length - this._packetEnd; + + // Create buffer + var buf = null; + var buffer = Buffer.allocUnsafe(remainingBytes + this._longPacketBuffers.size); + var offset = 0; + + // Copy long buffers + while ((buf = this._longPacketBuffers.shift())) { + offset += buf.copy(buffer, offset); + } + + // Copy remaining bytes + this._buffer.copy(buffer, offset, this._offset); + + this._buffer = buffer; + this._offset = 0; + this._packetEnd = this._buffer.length - trailingPacketBytes; + this._packetOffset = 0; +}; + +Parser.prototype._parsePacket = function _parsePacket(packetHeader) { + this._packetEnd = this._offset + packetHeader.length; + this._packetOffset = this._offset; + + if (packetHeader.length === MAX_PACKET_LENGTH) { + this._longPacketBuffers.push(this._buffer.slice(this._packetOffset, this._packetEnd)); + this._advanceToNextPacket(); + return; + } + + this._combineLongPacketBuffers(); + + var hadException = true; + try { + this._onPacket(packetHeader); + hadException = false; + } catch (err) { + if (!err || typeof err.code !== 'string' || err.code.substr(0, 7) !== 'PARSER_') { + throw err; // Rethrow non-MySQL errors + } + + // Pass down parser errors + this._onError(err); + hadException = false; + } finally { + this._advanceToNextPacket(); + + // If there was an exception, the parser while loop will be broken out + // of after the finally block. So schedule a blank write to re-enter it + // to continue parsing any bytes that may already have been received. + if (hadException) { + process.nextTick(this.write.bind(this)); + } + } +}; + +Parser.prototype._tryReadPacketHeader = function _tryReadPacketHeader() { + if (this._packetHeader) { + return this._packetHeader; + } + + if (!this._combineNextBuffers(PACKET_HEADER_LENGTH)) { + return null; + } + + this._packetHeader = new PacketHeader( + this.parseUnsignedNumber(3), + this.parseUnsignedNumber(1) + ); + + if (this._packetHeader.number !== this._nextPacketNumber) { + var err = new Error( + 'Packets out of order. Got: ' + this._packetHeader.number + ' ' + + 'Expected: ' + this._nextPacketNumber + ); + + err.code = 'PROTOCOL_PACKETS_OUT_OF_ORDER'; + err.fatal = true; + + this._onError(err); + } + + this.incrementPacketNumber(); + + return this._packetHeader; +}; + +Parser.prototype._advanceToNextPacket = function() { + this._offset = this._packetEnd; + this._packetHeader = null; + this._packetEnd = null; + this._packetOffset = null; +}; diff --git a/ts-ticket-office-service/node_modules/mysql/lib/protocol/Protocol.js b/ts-ticket-office-service/node_modules/mysql/lib/protocol/Protocol.js new file mode 100644 index 000000000..ab371059b --- /dev/null +++ b/ts-ticket-office-service/node_modules/mysql/lib/protocol/Protocol.js @@ -0,0 +1,463 @@ +var Parser = require('./Parser'); +var Sequences = require('./sequences'); +var Packets = require('./packets'); +var Stream = require('stream').Stream; +var Util = require('util'); +var PacketWriter = require('./PacketWriter'); + +module.exports = Protocol; +Util.inherits(Protocol, Stream); +function Protocol(options) { + Stream.call(this); + + options = options || {}; + + this.readable = true; + this.writable = true; + + this._config = options.config || {}; + this._connection = options.connection; + this._callback = null; + this._fatalError = null; + this._quitSequence = null; + this._handshake = false; + this._handshaked = false; + this._ended = false; + this._destroyed = false; + this._queue = []; + this._handshakeInitializationPacket = null; + + this._parser = new Parser({ + onError : this.handleParserError.bind(this), + onPacket : this._parsePacket.bind(this), + config : this._config + }); +} + +Protocol.prototype.write = function(buffer) { + this._parser.write(buffer); + return true; +}; + +Protocol.prototype.handshake = function handshake(options, callback) { + if (typeof options === 'function') { + callback = options; + options = {}; + } + + options = options || {}; + options.config = this._config; + + var sequence = this._enqueue(new Sequences.Handshake(options, callback)); + + this._handshake = true; + + return sequence; +}; + +Protocol.prototype.query = function query(options, callback) { + return this._enqueue(new Sequences.Query(options, callback)); +}; + +Protocol.prototype.changeUser = function changeUser(options, callback) { + return this._enqueue(new Sequences.ChangeUser(options, callback)); +}; + +Protocol.prototype.ping = function ping(options, callback) { + if (typeof options === 'function') { + callback = options; + options = {}; + } + + return this._enqueue(new Sequences.Ping(options, callback)); +}; + +Protocol.prototype.stats = function stats(options, callback) { + if (typeof options === 'function') { + callback = options; + options = {}; + } + + return this._enqueue(new Sequences.Statistics(options, callback)); +}; + +Protocol.prototype.quit = function quit(options, callback) { + if (typeof options === 'function') { + callback = options; + options = {}; + } + + var self = this; + var sequence = this._enqueue(new Sequences.Quit(options, callback)); + + sequence.on('end', function () { + self.end(); + }); + + return this._quitSequence = sequence; +}; + +Protocol.prototype.end = function() { + if (this._ended) { + return; + } + this._ended = true; + + if (this._quitSequence && (this._quitSequence._ended || this._queue[0] === this._quitSequence)) { + this._quitSequence.end(); + this.emit('end'); + return; + } + + var err = new Error('Connection lost: The server closed the connection.'); + err.fatal = true; + err.code = 'PROTOCOL_CONNECTION_LOST'; + + this._delegateError(err); +}; + +Protocol.prototype.pause = function() { + this._parser.pause(); + // Since there is a file stream in query, we must transmit pause/resume event to current sequence. + var seq = this._queue[0]; + if (seq && seq.emit) { + seq.emit('pause'); + } +}; + +Protocol.prototype.resume = function() { + this._parser.resume(); + // Since there is a file stream in query, we must transmit pause/resume event to current sequence. + var seq = this._queue[0]; + if (seq && seq.emit) { + seq.emit('resume'); + } +}; + +Protocol.prototype._enqueue = function(sequence) { + if (!this._validateEnqueue(sequence)) { + return sequence; + } + + if (this._config.trace) { + // Long stack trace support + sequence._callSite = sequence._callSite || new Error(); + } + + this._queue.push(sequence); + this.emit('enqueue', sequence); + + var self = this; + sequence + .on('error', function(err) { + self._delegateError(err, sequence); + }) + .on('packet', function(packet) { + sequence._timer.active(); + self._emitPacket(packet); + }) + .on('timeout', function() { + var err = new Error(sequence.constructor.name + ' inactivity timeout'); + + err.code = 'PROTOCOL_SEQUENCE_TIMEOUT'; + err.fatal = true; + err.timeout = sequence._timeout; + + self._delegateError(err, sequence); + }); + + if (sequence.constructor === Sequences.Handshake) { + sequence.on('start-tls', function () { + sequence._timer.active(); + self._connection._startTLS(function(err) { + if (err) { + // SSL negotiation error are fatal + err.code = 'HANDSHAKE_SSL_ERROR'; + err.fatal = true; + sequence.end(err); + return; + } + + sequence._timer.active(); + sequence._tlsUpgradeCompleteHandler(); + }); + }); + + sequence.on('end', function () { + self._handshaked = true; + + if (!self._fatalError) { + self.emit('handshake', self._handshakeInitializationPacket); + } + }); + } + + sequence.on('end', function () { + self._dequeue(sequence); + }); + + if (this._queue.length === 1) { + this._parser.resetPacketNumber(); + this._startSequence(sequence); + } + + return sequence; +}; + +Protocol.prototype._validateEnqueue = function _validateEnqueue(sequence) { + var err; + var prefix = 'Cannot enqueue ' + sequence.constructor.name; + + if (this._fatalError) { + err = new Error(prefix + ' after fatal error.'); + err.code = 'PROTOCOL_ENQUEUE_AFTER_FATAL_ERROR'; + } else if (this._quitSequence) { + err = new Error(prefix + ' after invoking quit.'); + err.code = 'PROTOCOL_ENQUEUE_AFTER_QUIT'; + } else if (this._destroyed) { + err = new Error(prefix + ' after being destroyed.'); + err.code = 'PROTOCOL_ENQUEUE_AFTER_DESTROY'; + } else if ((this._handshake || this._handshaked) && sequence.constructor === Sequences.Handshake) { + err = new Error(prefix + ' after already enqueuing a Handshake.'); + err.code = 'PROTOCOL_ENQUEUE_HANDSHAKE_TWICE'; + } else { + return true; + } + + var self = this; + err.fatal = false; + + // add error handler + sequence.on('error', function (err) { + self._delegateError(err, sequence); + }); + + process.nextTick(function () { + sequence.end(err); + }); + + return false; +}; + +Protocol.prototype._parsePacket = function() { + var sequence = this._queue[0]; + + if (!sequence) { + var err = new Error('Received packet with no active sequence.'); + err.code = 'PROTOCOL_STRAY_PACKET'; + err.fatal = true; + + this._delegateError(err); + return; + } + + var Packet = this._determinePacket(sequence); + var packet = new Packet({protocol41: this._config.protocol41}); + var packetName = Packet.name; + + // Special case: Faster dispatch, and parsing done inside sequence + if (Packet === Packets.RowDataPacket) { + sequence.RowDataPacket(packet, this._parser, this._connection); + + if (this._config.debug) { + this._debugPacket(true, packet); + } + + return; + } + + if (this._config.debug) { + this._parsePacketDebug(packet); + } else { + packet.parse(this._parser); + } + + if (Packet === Packets.HandshakeInitializationPacket) { + this._handshakeInitializationPacket = packet; + this.emit('initialize', packet); + } + + sequence._timer.active(); + + if (!sequence[packetName]) { + var err = new Error('Received packet in the wrong sequence.'); + err.code = 'PROTOCOL_INCORRECT_PACKET_SEQUENCE'; + err.fatal = true; + + this._delegateError(err); + return; + } + + sequence[packetName](packet); +}; + +Protocol.prototype._parsePacketDebug = function _parsePacketDebug(packet) { + try { + packet.parse(this._parser); + } finally { + this._debugPacket(true, packet); + } +}; + +Protocol.prototype._emitPacket = function(packet) { + var packetWriter = new PacketWriter(); + packet.write(packetWriter); + this.emit('data', packetWriter.toBuffer(this._parser)); + + if (this._config.debug) { + this._debugPacket(false, packet); + } +}; + +Protocol.prototype._determinePacket = function(sequence) { + var firstByte = this._parser.peak(); + + if (sequence.determinePacket) { + var Packet = sequence.determinePacket(firstByte, this._parser); + if (Packet) { + return Packet; + } + } + + switch (firstByte) { + case 0x00: return Packets.OkPacket; + case 0xfe: return Packets.EofPacket; + case 0xff: return Packets.ErrorPacket; + } + + throw new Error('Could not determine packet, firstByte = ' + firstByte); +}; + +Protocol.prototype._dequeue = function(sequence) { + sequence._timer.stop(); + + // No point in advancing the queue, we are dead + if (this._fatalError) { + return; + } + + this._queue.shift(); + + var sequence = this._queue[0]; + if (!sequence) { + this.emit('drain'); + return; + } + + this._parser.resetPacketNumber(); + + this._startSequence(sequence); +}; + +Protocol.prototype._startSequence = function(sequence) { + if (sequence._timeout > 0 && isFinite(sequence._timeout)) { + sequence._timer.start(sequence._timeout); + } + + if (sequence.constructor === Sequences.ChangeUser) { + sequence.start(this._handshakeInitializationPacket); + } else { + sequence.start(); + } +}; + +Protocol.prototype.handleNetworkError = function(err) { + err.fatal = true; + + var sequence = this._queue[0]; + if (sequence) { + sequence.end(err); + } else { + this._delegateError(err); + } +}; + +Protocol.prototype.handleParserError = function handleParserError(err) { + var sequence = this._queue[0]; + if (sequence) { + sequence.end(err); + } else { + this._delegateError(err); + } +}; + +Protocol.prototype._delegateError = function(err, sequence) { + // Stop delegating errors after the first fatal error + if (this._fatalError) { + return; + } + + if (err.fatal) { + this._fatalError = err; + } + + if (this._shouldErrorBubbleUp(err, sequence)) { + // Can't use regular 'error' event here as that always destroys the pipe + // between socket and protocol which is not what we want (unless the + // exception was fatal). + this.emit('unhandledError', err); + } else if (err.fatal) { + // Send fatal error to all sequences in the queue + var queue = this._queue; + process.nextTick(function () { + queue.forEach(function (sequence) { + sequence.end(err); + }); + queue.length = 0; + }); + } + + // Make sure the stream we are piping to is getting closed + if (err.fatal) { + this.emit('end', err); + } +}; + +Protocol.prototype._shouldErrorBubbleUp = function(err, sequence) { + if (sequence) { + if (sequence.hasErrorHandler()) { + return false; + } else if (!err.fatal) { + return true; + } + } + + return (err.fatal && !this._hasPendingErrorHandlers()); +}; + +Protocol.prototype._hasPendingErrorHandlers = function() { + return this._queue.some(function(sequence) { + return sequence.hasErrorHandler(); + }); +}; + +Protocol.prototype.destroy = function() { + this._destroyed = true; + this._parser.pause(); + + if (this._connection.state !== 'disconnected') { + if (!this._ended) { + this.end(); + } + } +}; + +Protocol.prototype._debugPacket = function(incoming, packet) { + var connection = this._connection; + var direction = incoming + ? '<--' + : '-->'; + var packetName = packet.constructor.name; + var threadId = connection && connection.threadId !== null + ? ' (' + connection.threadId + ')' + : ''; + + // check for debug packet restriction + if (Array.isArray(this._config.debug) && this._config.debug.indexOf(packetName) === -1) { + return; + } + + var packetPayload = Util.inspect(packet).replace(/^[^{]+/, ''); + + console.log('%s%s %s %s\n', direction, threadId, packetName, packetPayload); +}; diff --git a/ts-ticket-office-service/node_modules/mysql/lib/protocol/ResultSet.js b/ts-ticket-office-service/node_modules/mysql/lib/protocol/ResultSet.js new file mode 100644 index 000000000..f58d74fb2 --- /dev/null +++ b/ts-ticket-office-service/node_modules/mysql/lib/protocol/ResultSet.js @@ -0,0 +1,7 @@ +module.exports = ResultSet; +function ResultSet(resultSetHeaderPacket) { + this.resultSetHeaderPacket = resultSetHeaderPacket; + this.fieldPackets = []; + this.eofPackets = []; + this.rows = []; +} diff --git a/ts-ticket-office-service/node_modules/mysql/lib/protocol/SqlString.js b/ts-ticket-office-service/node_modules/mysql/lib/protocol/SqlString.js new file mode 100644 index 000000000..30c63d82e --- /dev/null +++ b/ts-ticket-office-service/node_modules/mysql/lib/protocol/SqlString.js @@ -0,0 +1 @@ +module.exports = require('sqlstring'); diff --git a/ts-ticket-office-service/node_modules/mysql/lib/protocol/Timer.js b/ts-ticket-office-service/node_modules/mysql/lib/protocol/Timer.js new file mode 100644 index 000000000..45ed0292f --- /dev/null +++ b/ts-ticket-office-service/node_modules/mysql/lib/protocol/Timer.js @@ -0,0 +1,33 @@ +var Timers = require('timers'); + +module.exports = Timer; +function Timer(object) { + this._object = object; + this._timeout = null; +} + +Timer.prototype.active = function active() { + if (this._timeout) { + if (this._timeout.refresh) { + this._timeout.refresh(); + } else { + Timers.active(this._timeout); + } + } +}; + +Timer.prototype.start = function start(msecs) { + this.stop(); + this._timeout = Timers.setTimeout(this._onTimeout.bind(this), msecs); +}; + +Timer.prototype.stop = function stop() { + if (this._timeout) { + Timers.clearTimeout(this._timeout); + this._timeout = null; + } +}; + +Timer.prototype._onTimeout = function _onTimeout() { + return this._object._onTimeout(); +}; diff --git a/ts-ticket-office-service/node_modules/mysql/lib/protocol/constants/charsets.js b/ts-ticket-office-service/node_modules/mysql/lib/protocol/constants/charsets.js new file mode 100644 index 000000000..98b88eac1 --- /dev/null +++ b/ts-ticket-office-service/node_modules/mysql/lib/protocol/constants/charsets.js @@ -0,0 +1,262 @@ +exports.BIG5_CHINESE_CI = 1; +exports.LATIN2_CZECH_CS = 2; +exports.DEC8_SWEDISH_CI = 3; +exports.CP850_GENERAL_CI = 4; +exports.LATIN1_GERMAN1_CI = 5; +exports.HP8_ENGLISH_CI = 6; +exports.KOI8R_GENERAL_CI = 7; +exports.LATIN1_SWEDISH_CI = 8; +exports.LATIN2_GENERAL_CI = 9; +exports.SWE7_SWEDISH_CI = 10; +exports.ASCII_GENERAL_CI = 11; +exports.UJIS_JAPANESE_CI = 12; +exports.SJIS_JAPANESE_CI = 13; +exports.CP1251_BULGARIAN_CI = 14; +exports.LATIN1_DANISH_CI = 15; +exports.HEBREW_GENERAL_CI = 16; +exports.TIS620_THAI_CI = 18; +exports.EUCKR_KOREAN_CI = 19; +exports.LATIN7_ESTONIAN_CS = 20; +exports.LATIN2_HUNGARIAN_CI = 21; +exports.KOI8U_GENERAL_CI = 22; +exports.CP1251_UKRAINIAN_CI = 23; +exports.GB2312_CHINESE_CI = 24; +exports.GREEK_GENERAL_CI = 25; +exports.CP1250_GENERAL_CI = 26; +exports.LATIN2_CROATIAN_CI = 27; +exports.GBK_CHINESE_CI = 28; +exports.CP1257_LITHUANIAN_CI = 29; +exports.LATIN5_TURKISH_CI = 30; +exports.LATIN1_GERMAN2_CI = 31; +exports.ARMSCII8_GENERAL_CI = 32; +exports.UTF8_GENERAL_CI = 33; +exports.CP1250_CZECH_CS = 34; +exports.UCS2_GENERAL_CI = 35; +exports.CP866_GENERAL_CI = 36; +exports.KEYBCS2_GENERAL_CI = 37; +exports.MACCE_GENERAL_CI = 38; +exports.MACROMAN_GENERAL_CI = 39; +exports.CP852_GENERAL_CI = 40; +exports.LATIN7_GENERAL_CI = 41; +exports.LATIN7_GENERAL_CS = 42; +exports.MACCE_BIN = 43; +exports.CP1250_CROATIAN_CI = 44; +exports.UTF8MB4_GENERAL_CI = 45; +exports.UTF8MB4_BIN = 46; +exports.LATIN1_BIN = 47; +exports.LATIN1_GENERAL_CI = 48; +exports.LATIN1_GENERAL_CS = 49; +exports.CP1251_BIN = 50; +exports.CP1251_GENERAL_CI = 51; +exports.CP1251_GENERAL_CS = 52; +exports.MACROMAN_BIN = 53; +exports.UTF16_GENERAL_CI = 54; +exports.UTF16_BIN = 55; +exports.UTF16LE_GENERAL_CI = 56; +exports.CP1256_GENERAL_CI = 57; +exports.CP1257_BIN = 58; +exports.CP1257_GENERAL_CI = 59; +exports.UTF32_GENERAL_CI = 60; +exports.UTF32_BIN = 61; +exports.UTF16LE_BIN = 62; +exports.BINARY = 63; +exports.ARMSCII8_BIN = 64; +exports.ASCII_BIN = 65; +exports.CP1250_BIN = 66; +exports.CP1256_BIN = 67; +exports.CP866_BIN = 68; +exports.DEC8_BIN = 69; +exports.GREEK_BIN = 70; +exports.HEBREW_BIN = 71; +exports.HP8_BIN = 72; +exports.KEYBCS2_BIN = 73; +exports.KOI8R_BIN = 74; +exports.KOI8U_BIN = 75; +exports.LATIN2_BIN = 77; +exports.LATIN5_BIN = 78; +exports.LATIN7_BIN = 79; +exports.CP850_BIN = 80; +exports.CP852_BIN = 81; +exports.SWE7_BIN = 82; +exports.UTF8_BIN = 83; +exports.BIG5_BIN = 84; +exports.EUCKR_BIN = 85; +exports.GB2312_BIN = 86; +exports.GBK_BIN = 87; +exports.SJIS_BIN = 88; +exports.TIS620_BIN = 89; +exports.UCS2_BIN = 90; +exports.UJIS_BIN = 91; +exports.GEOSTD8_GENERAL_CI = 92; +exports.GEOSTD8_BIN = 93; +exports.LATIN1_SPANISH_CI = 94; +exports.CP932_JAPANESE_CI = 95; +exports.CP932_BIN = 96; +exports.EUCJPMS_JAPANESE_CI = 97; +exports.EUCJPMS_BIN = 98; +exports.CP1250_POLISH_CI = 99; +exports.UTF16_UNICODE_CI = 101; +exports.UTF16_ICELANDIC_CI = 102; +exports.UTF16_LATVIAN_CI = 103; +exports.UTF16_ROMANIAN_CI = 104; +exports.UTF16_SLOVENIAN_CI = 105; +exports.UTF16_POLISH_CI = 106; +exports.UTF16_ESTONIAN_CI = 107; +exports.UTF16_SPANISH_CI = 108; +exports.UTF16_SWEDISH_CI = 109; +exports.UTF16_TURKISH_CI = 110; +exports.UTF16_CZECH_CI = 111; +exports.UTF16_DANISH_CI = 112; +exports.UTF16_LITHUANIAN_CI = 113; +exports.UTF16_SLOVAK_CI = 114; +exports.UTF16_SPANISH2_CI = 115; +exports.UTF16_ROMAN_CI = 116; +exports.UTF16_PERSIAN_CI = 117; +exports.UTF16_ESPERANTO_CI = 118; +exports.UTF16_HUNGARIAN_CI = 119; +exports.UTF16_SINHALA_CI = 120; +exports.UTF16_GERMAN2_CI = 121; +exports.UTF16_CROATIAN_MYSQL561_CI = 122; +exports.UTF16_UNICODE_520_CI = 123; +exports.UTF16_VIETNAMESE_CI = 124; +exports.UCS2_UNICODE_CI = 128; +exports.UCS2_ICELANDIC_CI = 129; +exports.UCS2_LATVIAN_CI = 130; +exports.UCS2_ROMANIAN_CI = 131; +exports.UCS2_SLOVENIAN_CI = 132; +exports.UCS2_POLISH_CI = 133; +exports.UCS2_ESTONIAN_CI = 134; +exports.UCS2_SPANISH_CI = 135; +exports.UCS2_SWEDISH_CI = 136; +exports.UCS2_TURKISH_CI = 137; +exports.UCS2_CZECH_CI = 138; +exports.UCS2_DANISH_CI = 139; +exports.UCS2_LITHUANIAN_CI = 140; +exports.UCS2_SLOVAK_CI = 141; +exports.UCS2_SPANISH2_CI = 142; +exports.UCS2_ROMAN_CI = 143; +exports.UCS2_PERSIAN_CI = 144; +exports.UCS2_ESPERANTO_CI = 145; +exports.UCS2_HUNGARIAN_CI = 146; +exports.UCS2_SINHALA_CI = 147; +exports.UCS2_GERMAN2_CI = 148; +exports.UCS2_CROATIAN_MYSQL561_CI = 149; +exports.UCS2_UNICODE_520_CI = 150; +exports.UCS2_VIETNAMESE_CI = 151; +exports.UCS2_GENERAL_MYSQL500_CI = 159; +exports.UTF32_UNICODE_CI = 160; +exports.UTF32_ICELANDIC_CI = 161; +exports.UTF32_LATVIAN_CI = 162; +exports.UTF32_ROMANIAN_CI = 163; +exports.UTF32_SLOVENIAN_CI = 164; +exports.UTF32_POLISH_CI = 165; +exports.UTF32_ESTONIAN_CI = 166; +exports.UTF32_SPANISH_CI = 167; +exports.UTF32_SWEDISH_CI = 168; +exports.UTF32_TURKISH_CI = 169; +exports.UTF32_CZECH_CI = 170; +exports.UTF32_DANISH_CI = 171; +exports.UTF32_LITHUANIAN_CI = 172; +exports.UTF32_SLOVAK_CI = 173; +exports.UTF32_SPANISH2_CI = 174; +exports.UTF32_ROMAN_CI = 175; +exports.UTF32_PERSIAN_CI = 176; +exports.UTF32_ESPERANTO_CI = 177; +exports.UTF32_HUNGARIAN_CI = 178; +exports.UTF32_SINHALA_CI = 179; +exports.UTF32_GERMAN2_CI = 180; +exports.UTF32_CROATIAN_MYSQL561_CI = 181; +exports.UTF32_UNICODE_520_CI = 182; +exports.UTF32_VIETNAMESE_CI = 183; +exports.UTF8_UNICODE_CI = 192; +exports.UTF8_ICELANDIC_CI = 193; +exports.UTF8_LATVIAN_CI = 194; +exports.UTF8_ROMANIAN_CI = 195; +exports.UTF8_SLOVENIAN_CI = 196; +exports.UTF8_POLISH_CI = 197; +exports.UTF8_ESTONIAN_CI = 198; +exports.UTF8_SPANISH_CI = 199; +exports.UTF8_SWEDISH_CI = 200; +exports.UTF8_TURKISH_CI = 201; +exports.UTF8_CZECH_CI = 202; +exports.UTF8_DANISH_CI = 203; +exports.UTF8_LITHUANIAN_CI = 204; +exports.UTF8_SLOVAK_CI = 205; +exports.UTF8_SPANISH2_CI = 206; +exports.UTF8_ROMAN_CI = 207; +exports.UTF8_PERSIAN_CI = 208; +exports.UTF8_ESPERANTO_CI = 209; +exports.UTF8_HUNGARIAN_CI = 210; +exports.UTF8_SINHALA_CI = 211; +exports.UTF8_GERMAN2_CI = 212; +exports.UTF8_CROATIAN_MYSQL561_CI = 213; +exports.UTF8_UNICODE_520_CI = 214; +exports.UTF8_VIETNAMESE_CI = 215; +exports.UTF8_GENERAL_MYSQL500_CI = 223; +exports.UTF8MB4_UNICODE_CI = 224; +exports.UTF8MB4_ICELANDIC_CI = 225; +exports.UTF8MB4_LATVIAN_CI = 226; +exports.UTF8MB4_ROMANIAN_CI = 227; +exports.UTF8MB4_SLOVENIAN_CI = 228; +exports.UTF8MB4_POLISH_CI = 229; +exports.UTF8MB4_ESTONIAN_CI = 230; +exports.UTF8MB4_SPANISH_CI = 231; +exports.UTF8MB4_SWEDISH_CI = 232; +exports.UTF8MB4_TURKISH_CI = 233; +exports.UTF8MB4_CZECH_CI = 234; +exports.UTF8MB4_DANISH_CI = 235; +exports.UTF8MB4_LITHUANIAN_CI = 236; +exports.UTF8MB4_SLOVAK_CI = 237; +exports.UTF8MB4_SPANISH2_CI = 238; +exports.UTF8MB4_ROMAN_CI = 239; +exports.UTF8MB4_PERSIAN_CI = 240; +exports.UTF8MB4_ESPERANTO_CI = 241; +exports.UTF8MB4_HUNGARIAN_CI = 242; +exports.UTF8MB4_SINHALA_CI = 243; +exports.UTF8MB4_GERMAN2_CI = 244; +exports.UTF8MB4_CROATIAN_MYSQL561_CI = 245; +exports.UTF8MB4_UNICODE_520_CI = 246; +exports.UTF8MB4_VIETNAMESE_CI = 247; +exports.UTF8_GENERAL50_CI = 253; + +// short aliases +exports.ARMSCII8 = exports.ARMSCII8_GENERAL_CI; +exports.ASCII = exports.ASCII_GENERAL_CI; +exports.BIG5 = exports.BIG5_CHINESE_CI; +exports.BINARY = exports.BINARY; +exports.CP1250 = exports.CP1250_GENERAL_CI; +exports.CP1251 = exports.CP1251_GENERAL_CI; +exports.CP1256 = exports.CP1256_GENERAL_CI; +exports.CP1257 = exports.CP1257_GENERAL_CI; +exports.CP866 = exports.CP866_GENERAL_CI; +exports.CP850 = exports.CP850_GENERAL_CI; +exports.CP852 = exports.CP852_GENERAL_CI; +exports.CP932 = exports.CP932_JAPANESE_CI; +exports.DEC8 = exports.DEC8_SWEDISH_CI; +exports.EUCJPMS = exports.EUCJPMS_JAPANESE_CI; +exports.EUCKR = exports.EUCKR_KOREAN_CI; +exports.GB2312 = exports.GB2312_CHINESE_CI; +exports.GBK = exports.GBK_CHINESE_CI; +exports.GEOSTD8 = exports.GEOSTD8_GENERAL_CI; +exports.GREEK = exports.GREEK_GENERAL_CI; +exports.HEBREW = exports.HEBREW_GENERAL_CI; +exports.HP8 = exports.HP8_ENGLISH_CI; +exports.KEYBCS2 = exports.KEYBCS2_GENERAL_CI; +exports.KOI8R = exports.KOI8R_GENERAL_CI; +exports.KOI8U = exports.KOI8U_GENERAL_CI; +exports.LATIN1 = exports.LATIN1_SWEDISH_CI; +exports.LATIN2 = exports.LATIN2_GENERAL_CI; +exports.LATIN5 = exports.LATIN5_TURKISH_CI; +exports.LATIN7 = exports.LATIN7_GENERAL_CI; +exports.MACCE = exports.MACCE_GENERAL_CI; +exports.MACROMAN = exports.MACROMAN_GENERAL_CI; +exports.SJIS = exports.SJIS_JAPANESE_CI; +exports.SWE7 = exports.SWE7_SWEDISH_CI; +exports.TIS620 = exports.TIS620_THAI_CI; +exports.UCS2 = exports.UCS2_GENERAL_CI; +exports.UJIS = exports.UJIS_JAPANESE_CI; +exports.UTF16 = exports.UTF16_GENERAL_CI; +exports.UTF16LE = exports.UTF16LE_GENERAL_CI; +exports.UTF8 = exports.UTF8_GENERAL_CI; +exports.UTF8MB4 = exports.UTF8MB4_GENERAL_CI; +exports.UTF32 = exports.UTF32_GENERAL_CI; diff --git a/ts-ticket-office-service/node_modules/mysql/lib/protocol/constants/client.js b/ts-ticket-office-service/node_modules/mysql/lib/protocol/constants/client.js new file mode 100644 index 000000000..59aadc609 --- /dev/null +++ b/ts-ticket-office-service/node_modules/mysql/lib/protocol/constants/client.js @@ -0,0 +1,26 @@ +// Manually extracted from mysql-5.5.23/include/mysql_com.h +exports.CLIENT_LONG_PASSWORD = 1; /* new more secure passwords */ +exports.CLIENT_FOUND_ROWS = 2; /* Found instead of affected rows */ +exports.CLIENT_LONG_FLAG = 4; /* Get all column flags */ +exports.CLIENT_CONNECT_WITH_DB = 8; /* One can specify db on connect */ +exports.CLIENT_NO_SCHEMA = 16; /* Don't allow database.table.column */ +exports.CLIENT_COMPRESS = 32; /* Can use compression protocol */ +exports.CLIENT_ODBC = 64; /* Odbc client */ +exports.CLIENT_LOCAL_FILES = 128; /* Can use LOAD DATA LOCAL */ +exports.CLIENT_IGNORE_SPACE = 256; /* Ignore spaces before '(' */ +exports.CLIENT_PROTOCOL_41 = 512; /* New 4.1 protocol */ +exports.CLIENT_INTERACTIVE = 1024; /* This is an interactive client */ +exports.CLIENT_SSL = 2048; /* Switch to SSL after handshake */ +exports.CLIENT_IGNORE_SIGPIPE = 4096; /* IGNORE sigpipes */ +exports.CLIENT_TRANSACTIONS = 8192; /* Client knows about transactions */ +exports.CLIENT_RESERVED = 16384; /* Old flag for 4.1 protocol */ +exports.CLIENT_SECURE_CONNECTION = 32768; /* New 4.1 authentication */ + +exports.CLIENT_MULTI_STATEMENTS = 65536; /* Enable/disable multi-stmt support */ +exports.CLIENT_MULTI_RESULTS = 131072; /* Enable/disable multi-results */ +exports.CLIENT_PS_MULTI_RESULTS = 262144; /* Multi-results in PS-protocol */ + +exports.CLIENT_PLUGIN_AUTH = 524288; /* Client supports plugin authentication */ + +exports.CLIENT_SSL_VERIFY_SERVER_CERT = 1073741824; +exports.CLIENT_REMEMBER_OPTIONS = 2147483648; diff --git a/ts-ticket-office-service/node_modules/mysql/lib/protocol/constants/errors.js b/ts-ticket-office-service/node_modules/mysql/lib/protocol/constants/errors.js new file mode 100644 index 000000000..e75774183 --- /dev/null +++ b/ts-ticket-office-service/node_modules/mysql/lib/protocol/constants/errors.js @@ -0,0 +1,2476 @@ +/** + * MySQL error constants + * + * Extracted from version 5.7.29 + * + * !! Generated by generate-error-constants.js, do not modify by hand !! + */ + +exports.EE_CANTCREATEFILE = 1; +exports.EE_READ = 2; +exports.EE_WRITE = 3; +exports.EE_BADCLOSE = 4; +exports.EE_OUTOFMEMORY = 5; +exports.EE_DELETE = 6; +exports.EE_LINK = 7; +exports.EE_EOFERR = 9; +exports.EE_CANTLOCK = 10; +exports.EE_CANTUNLOCK = 11; +exports.EE_DIR = 12; +exports.EE_STAT = 13; +exports.EE_CANT_CHSIZE = 14; +exports.EE_CANT_OPEN_STREAM = 15; +exports.EE_GETWD = 16; +exports.EE_SETWD = 17; +exports.EE_LINK_WARNING = 18; +exports.EE_OPEN_WARNING = 19; +exports.EE_DISK_FULL = 20; +exports.EE_CANT_MKDIR = 21; +exports.EE_UNKNOWN_CHARSET = 22; +exports.EE_OUT_OF_FILERESOURCES = 23; +exports.EE_CANT_READLINK = 24; +exports.EE_CANT_SYMLINK = 25; +exports.EE_REALPATH = 26; +exports.EE_SYNC = 27; +exports.EE_UNKNOWN_COLLATION = 28; +exports.EE_FILENOTFOUND = 29; +exports.EE_FILE_NOT_CLOSED = 30; +exports.EE_CHANGE_OWNERSHIP = 31; +exports.EE_CHANGE_PERMISSIONS = 32; +exports.EE_CANT_SEEK = 33; +exports.EE_CAPACITY_EXCEEDED = 34; +exports.HA_ERR_KEY_NOT_FOUND = 120; +exports.HA_ERR_FOUND_DUPP_KEY = 121; +exports.HA_ERR_INTERNAL_ERROR = 122; +exports.HA_ERR_RECORD_CHANGED = 123; +exports.HA_ERR_WRONG_INDEX = 124; +exports.HA_ERR_CRASHED = 126; +exports.HA_ERR_WRONG_IN_RECORD = 127; +exports.HA_ERR_OUT_OF_MEM = 128; +exports.HA_ERR_NOT_A_TABLE = 130; +exports.HA_ERR_WRONG_COMMAND = 131; +exports.HA_ERR_OLD_FILE = 132; +exports.HA_ERR_NO_ACTIVE_RECORD = 133; +exports.HA_ERR_RECORD_DELETED = 134; +exports.HA_ERR_RECORD_FILE_FULL = 135; +exports.HA_ERR_INDEX_FILE_FULL = 136; +exports.HA_ERR_END_OF_FILE = 137; +exports.HA_ERR_UNSUPPORTED = 138; +exports.HA_ERR_TOO_BIG_ROW = 139; +exports.HA_WRONG_CREATE_OPTION = 140; +exports.HA_ERR_FOUND_DUPP_UNIQUE = 141; +exports.HA_ERR_UNKNOWN_CHARSET = 142; +exports.HA_ERR_WRONG_MRG_TABLE_DEF = 143; +exports.HA_ERR_CRASHED_ON_REPAIR = 144; +exports.HA_ERR_CRASHED_ON_USAGE = 145; +exports.HA_ERR_LOCK_WAIT_TIMEOUT = 146; +exports.HA_ERR_LOCK_TABLE_FULL = 147; +exports.HA_ERR_READ_ONLY_TRANSACTION = 148; +exports.HA_ERR_LOCK_DEADLOCK = 149; +exports.HA_ERR_CANNOT_ADD_FOREIGN = 150; +exports.HA_ERR_NO_REFERENCED_ROW = 151; +exports.HA_ERR_ROW_IS_REFERENCED = 152; +exports.HA_ERR_NO_SAVEPOINT = 153; +exports.HA_ERR_NON_UNIQUE_BLOCK_SIZE = 154; +exports.HA_ERR_NO_SUCH_TABLE = 155; +exports.HA_ERR_TABLE_EXIST = 156; +exports.HA_ERR_NO_CONNECTION = 157; +exports.HA_ERR_NULL_IN_SPATIAL = 158; +exports.HA_ERR_TABLE_DEF_CHANGED = 159; +exports.HA_ERR_NO_PARTITION_FOUND = 160; +exports.HA_ERR_RBR_LOGGING_FAILED = 161; +exports.HA_ERR_DROP_INDEX_FK = 162; +exports.HA_ERR_FOREIGN_DUPLICATE_KEY = 163; +exports.HA_ERR_TABLE_NEEDS_UPGRADE = 164; +exports.HA_ERR_TABLE_READONLY = 165; +exports.HA_ERR_AUTOINC_READ_FAILED = 166; +exports.HA_ERR_AUTOINC_ERANGE = 167; +exports.HA_ERR_GENERIC = 168; +exports.HA_ERR_RECORD_IS_THE_SAME = 169; +exports.HA_ERR_LOGGING_IMPOSSIBLE = 170; +exports.HA_ERR_CORRUPT_EVENT = 171; +exports.HA_ERR_NEW_FILE = 172; +exports.HA_ERR_ROWS_EVENT_APPLY = 173; +exports.HA_ERR_INITIALIZATION = 174; +exports.HA_ERR_FILE_TOO_SHORT = 175; +exports.HA_ERR_WRONG_CRC = 176; +exports.HA_ERR_TOO_MANY_CONCURRENT_TRXS = 177; +exports.HA_ERR_NOT_IN_LOCK_PARTITIONS = 178; +exports.HA_ERR_INDEX_COL_TOO_LONG = 179; +exports.HA_ERR_INDEX_CORRUPT = 180; +exports.HA_ERR_UNDO_REC_TOO_BIG = 181; +exports.HA_FTS_INVALID_DOCID = 182; +exports.HA_ERR_TABLE_IN_FK_CHECK = 183; +exports.HA_ERR_TABLESPACE_EXISTS = 184; +exports.HA_ERR_TOO_MANY_FIELDS = 185; +exports.HA_ERR_ROW_IN_WRONG_PARTITION = 186; +exports.HA_ERR_INNODB_READ_ONLY = 187; +exports.HA_ERR_FTS_EXCEED_RESULT_CACHE_LIMIT = 188; +exports.HA_ERR_TEMP_FILE_WRITE_FAILURE = 189; +exports.HA_ERR_INNODB_FORCED_RECOVERY = 190; +exports.HA_ERR_FTS_TOO_MANY_WORDS_IN_PHRASE = 191; +exports.HA_ERR_FK_DEPTH_EXCEEDED = 192; +exports.HA_MISSING_CREATE_OPTION = 193; +exports.HA_ERR_SE_OUT_OF_MEMORY = 194; +exports.HA_ERR_TABLE_CORRUPT = 195; +exports.HA_ERR_QUERY_INTERRUPTED = 196; +exports.HA_ERR_TABLESPACE_MISSING = 197; +exports.HA_ERR_TABLESPACE_IS_NOT_EMPTY = 198; +exports.HA_ERR_WRONG_FILE_NAME = 199; +exports.HA_ERR_NOT_ALLOWED_COMMAND = 200; +exports.HA_ERR_COMPUTE_FAILED = 201; +exports.ER_HASHCHK = 1000; +exports.ER_NISAMCHK = 1001; +exports.ER_NO = 1002; +exports.ER_YES = 1003; +exports.ER_CANT_CREATE_FILE = 1004; +exports.ER_CANT_CREATE_TABLE = 1005; +exports.ER_CANT_CREATE_DB = 1006; +exports.ER_DB_CREATE_EXISTS = 1007; +exports.ER_DB_DROP_EXISTS = 1008; +exports.ER_DB_DROP_DELETE = 1009; +exports.ER_DB_DROP_RMDIR = 1010; +exports.ER_CANT_DELETE_FILE = 1011; +exports.ER_CANT_FIND_SYSTEM_REC = 1012; +exports.ER_CANT_GET_STAT = 1013; +exports.ER_CANT_GET_WD = 1014; +exports.ER_CANT_LOCK = 1015; +exports.ER_CANT_OPEN_FILE = 1016; +exports.ER_FILE_NOT_FOUND = 1017; +exports.ER_CANT_READ_DIR = 1018; +exports.ER_CANT_SET_WD = 1019; +exports.ER_CHECKREAD = 1020; +exports.ER_DISK_FULL = 1021; +exports.ER_DUP_KEY = 1022; +exports.ER_ERROR_ON_CLOSE = 1023; +exports.ER_ERROR_ON_READ = 1024; +exports.ER_ERROR_ON_RENAME = 1025; +exports.ER_ERROR_ON_WRITE = 1026; +exports.ER_FILE_USED = 1027; +exports.ER_FILSORT_ABORT = 1028; +exports.ER_FORM_NOT_FOUND = 1029; +exports.ER_GET_ERRNO = 1030; +exports.ER_ILLEGAL_HA = 1031; +exports.ER_KEY_NOT_FOUND = 1032; +exports.ER_NOT_FORM_FILE = 1033; +exports.ER_NOT_KEYFILE = 1034; +exports.ER_OLD_KEYFILE = 1035; +exports.ER_OPEN_AS_READONLY = 1036; +exports.ER_OUTOFMEMORY = 1037; +exports.ER_OUT_OF_SORTMEMORY = 1038; +exports.ER_UNEXPECTED_EOF = 1039; +exports.ER_CON_COUNT_ERROR = 1040; +exports.ER_OUT_OF_RESOURCES = 1041; +exports.ER_BAD_HOST_ERROR = 1042; +exports.ER_HANDSHAKE_ERROR = 1043; +exports.ER_DBACCESS_DENIED_ERROR = 1044; +exports.ER_ACCESS_DENIED_ERROR = 1045; +exports.ER_NO_DB_ERROR = 1046; +exports.ER_UNKNOWN_COM_ERROR = 1047; +exports.ER_BAD_NULL_ERROR = 1048; +exports.ER_BAD_DB_ERROR = 1049; +exports.ER_TABLE_EXISTS_ERROR = 1050; +exports.ER_BAD_TABLE_ERROR = 1051; +exports.ER_NON_UNIQ_ERROR = 1052; +exports.ER_SERVER_SHUTDOWN = 1053; +exports.ER_BAD_FIELD_ERROR = 1054; +exports.ER_WRONG_FIELD_WITH_GROUP = 1055; +exports.ER_WRONG_GROUP_FIELD = 1056; +exports.ER_WRONG_SUM_SELECT = 1057; +exports.ER_WRONG_VALUE_COUNT = 1058; +exports.ER_TOO_LONG_IDENT = 1059; +exports.ER_DUP_FIELDNAME = 1060; +exports.ER_DUP_KEYNAME = 1061; +exports.ER_DUP_ENTRY = 1062; +exports.ER_WRONG_FIELD_SPEC = 1063; +exports.ER_PARSE_ERROR = 1064; +exports.ER_EMPTY_QUERY = 1065; +exports.ER_NONUNIQ_TABLE = 1066; +exports.ER_INVALID_DEFAULT = 1067; +exports.ER_MULTIPLE_PRI_KEY = 1068; +exports.ER_TOO_MANY_KEYS = 1069; +exports.ER_TOO_MANY_KEY_PARTS = 1070; +exports.ER_TOO_LONG_KEY = 1071; +exports.ER_KEY_COLUMN_DOES_NOT_EXITS = 1072; +exports.ER_BLOB_USED_AS_KEY = 1073; +exports.ER_TOO_BIG_FIELDLENGTH = 1074; +exports.ER_WRONG_AUTO_KEY = 1075; +exports.ER_READY = 1076; +exports.ER_NORMAL_SHUTDOWN = 1077; +exports.ER_GOT_SIGNAL = 1078; +exports.ER_SHUTDOWN_COMPLETE = 1079; +exports.ER_FORCING_CLOSE = 1080; +exports.ER_IPSOCK_ERROR = 1081; +exports.ER_NO_SUCH_INDEX = 1082; +exports.ER_WRONG_FIELD_TERMINATORS = 1083; +exports.ER_BLOBS_AND_NO_TERMINATED = 1084; +exports.ER_TEXTFILE_NOT_READABLE = 1085; +exports.ER_FILE_EXISTS_ERROR = 1086; +exports.ER_LOAD_INFO = 1087; +exports.ER_ALTER_INFO = 1088; +exports.ER_WRONG_SUB_KEY = 1089; +exports.ER_CANT_REMOVE_ALL_FIELDS = 1090; +exports.ER_CANT_DROP_FIELD_OR_KEY = 1091; +exports.ER_INSERT_INFO = 1092; +exports.ER_UPDATE_TABLE_USED = 1093; +exports.ER_NO_SUCH_THREAD = 1094; +exports.ER_KILL_DENIED_ERROR = 1095; +exports.ER_NO_TABLES_USED = 1096; +exports.ER_TOO_BIG_SET = 1097; +exports.ER_NO_UNIQUE_LOGFILE = 1098; +exports.ER_TABLE_NOT_LOCKED_FOR_WRITE = 1099; +exports.ER_TABLE_NOT_LOCKED = 1100; +exports.ER_BLOB_CANT_HAVE_DEFAULT = 1101; +exports.ER_WRONG_DB_NAME = 1102; +exports.ER_WRONG_TABLE_NAME = 1103; +exports.ER_TOO_BIG_SELECT = 1104; +exports.ER_UNKNOWN_ERROR = 1105; +exports.ER_UNKNOWN_PROCEDURE = 1106; +exports.ER_WRONG_PARAMCOUNT_TO_PROCEDURE = 1107; +exports.ER_WRONG_PARAMETERS_TO_PROCEDURE = 1108; +exports.ER_UNKNOWN_TABLE = 1109; +exports.ER_FIELD_SPECIFIED_TWICE = 1110; +exports.ER_INVALID_GROUP_FUNC_USE = 1111; +exports.ER_UNSUPPORTED_EXTENSION = 1112; +exports.ER_TABLE_MUST_HAVE_COLUMNS = 1113; +exports.ER_RECORD_FILE_FULL = 1114; +exports.ER_UNKNOWN_CHARACTER_SET = 1115; +exports.ER_TOO_MANY_TABLES = 1116; +exports.ER_TOO_MANY_FIELDS = 1117; +exports.ER_TOO_BIG_ROWSIZE = 1118; +exports.ER_STACK_OVERRUN = 1119; +exports.ER_WRONG_OUTER_JOIN = 1120; +exports.ER_NULL_COLUMN_IN_INDEX = 1121; +exports.ER_CANT_FIND_UDF = 1122; +exports.ER_CANT_INITIALIZE_UDF = 1123; +exports.ER_UDF_NO_PATHS = 1124; +exports.ER_UDF_EXISTS = 1125; +exports.ER_CANT_OPEN_LIBRARY = 1126; +exports.ER_CANT_FIND_DL_ENTRY = 1127; +exports.ER_FUNCTION_NOT_DEFINED = 1128; +exports.ER_HOST_IS_BLOCKED = 1129; +exports.ER_HOST_NOT_PRIVILEGED = 1130; +exports.ER_PASSWORD_ANONYMOUS_USER = 1131; +exports.ER_PASSWORD_NOT_ALLOWED = 1132; +exports.ER_PASSWORD_NO_MATCH = 1133; +exports.ER_UPDATE_INFO = 1134; +exports.ER_CANT_CREATE_THREAD = 1135; +exports.ER_WRONG_VALUE_COUNT_ON_ROW = 1136; +exports.ER_CANT_REOPEN_TABLE = 1137; +exports.ER_INVALID_USE_OF_NULL = 1138; +exports.ER_REGEXP_ERROR = 1139; +exports.ER_MIX_OF_GROUP_FUNC_AND_FIELDS = 1140; +exports.ER_NONEXISTING_GRANT = 1141; +exports.ER_TABLEACCESS_DENIED_ERROR = 1142; +exports.ER_COLUMNACCESS_DENIED_ERROR = 1143; +exports.ER_ILLEGAL_GRANT_FOR_TABLE = 1144; +exports.ER_GRANT_WRONG_HOST_OR_USER = 1145; +exports.ER_NO_SUCH_TABLE = 1146; +exports.ER_NONEXISTING_TABLE_GRANT = 1147; +exports.ER_NOT_ALLOWED_COMMAND = 1148; +exports.ER_SYNTAX_ERROR = 1149; +exports.ER_DELAYED_CANT_CHANGE_LOCK = 1150; +exports.ER_TOO_MANY_DELAYED_THREADS = 1151; +exports.ER_ABORTING_CONNECTION = 1152; +exports.ER_NET_PACKET_TOO_LARGE = 1153; +exports.ER_NET_READ_ERROR_FROM_PIPE = 1154; +exports.ER_NET_FCNTL_ERROR = 1155; +exports.ER_NET_PACKETS_OUT_OF_ORDER = 1156; +exports.ER_NET_UNCOMPRESS_ERROR = 1157; +exports.ER_NET_READ_ERROR = 1158; +exports.ER_NET_READ_INTERRUPTED = 1159; +exports.ER_NET_ERROR_ON_WRITE = 1160; +exports.ER_NET_WRITE_INTERRUPTED = 1161; +exports.ER_TOO_LONG_STRING = 1162; +exports.ER_TABLE_CANT_HANDLE_BLOB = 1163; +exports.ER_TABLE_CANT_HANDLE_AUTO_INCREMENT = 1164; +exports.ER_DELAYED_INSERT_TABLE_LOCKED = 1165; +exports.ER_WRONG_COLUMN_NAME = 1166; +exports.ER_WRONG_KEY_COLUMN = 1167; +exports.ER_WRONG_MRG_TABLE = 1168; +exports.ER_DUP_UNIQUE = 1169; +exports.ER_BLOB_KEY_WITHOUT_LENGTH = 1170; +exports.ER_PRIMARY_CANT_HAVE_NULL = 1171; +exports.ER_TOO_MANY_ROWS = 1172; +exports.ER_REQUIRES_PRIMARY_KEY = 1173; +exports.ER_NO_RAID_COMPILED = 1174; +exports.ER_UPDATE_WITHOUT_KEY_IN_SAFE_MODE = 1175; +exports.ER_KEY_DOES_NOT_EXITS = 1176; +exports.ER_CHECK_NO_SUCH_TABLE = 1177; +exports.ER_CHECK_NOT_IMPLEMENTED = 1178; +exports.ER_CANT_DO_THIS_DURING_AN_TRANSACTION = 1179; +exports.ER_ERROR_DURING_COMMIT = 1180; +exports.ER_ERROR_DURING_ROLLBACK = 1181; +exports.ER_ERROR_DURING_FLUSH_LOGS = 1182; +exports.ER_ERROR_DURING_CHECKPOINT = 1183; +exports.ER_NEW_ABORTING_CONNECTION = 1184; +exports.ER_DUMP_NOT_IMPLEMENTED = 1185; +exports.ER_FLUSH_MASTER_BINLOG_CLOSED = 1186; +exports.ER_INDEX_REBUILD = 1187; +exports.ER_MASTER = 1188; +exports.ER_MASTER_NET_READ = 1189; +exports.ER_MASTER_NET_WRITE = 1190; +exports.ER_FT_MATCHING_KEY_NOT_FOUND = 1191; +exports.ER_LOCK_OR_ACTIVE_TRANSACTION = 1192; +exports.ER_UNKNOWN_SYSTEM_VARIABLE = 1193; +exports.ER_CRASHED_ON_USAGE = 1194; +exports.ER_CRASHED_ON_REPAIR = 1195; +exports.ER_WARNING_NOT_COMPLETE_ROLLBACK = 1196; +exports.ER_TRANS_CACHE_FULL = 1197; +exports.ER_SLAVE_MUST_STOP = 1198; +exports.ER_SLAVE_NOT_RUNNING = 1199; +exports.ER_BAD_SLAVE = 1200; +exports.ER_MASTER_INFO = 1201; +exports.ER_SLAVE_THREAD = 1202; +exports.ER_TOO_MANY_USER_CONNECTIONS = 1203; +exports.ER_SET_CONSTANTS_ONLY = 1204; +exports.ER_LOCK_WAIT_TIMEOUT = 1205; +exports.ER_LOCK_TABLE_FULL = 1206; +exports.ER_READ_ONLY_TRANSACTION = 1207; +exports.ER_DROP_DB_WITH_READ_LOCK = 1208; +exports.ER_CREATE_DB_WITH_READ_LOCK = 1209; +exports.ER_WRONG_ARGUMENTS = 1210; +exports.ER_NO_PERMISSION_TO_CREATE_USER = 1211; +exports.ER_UNION_TABLES_IN_DIFFERENT_DIR = 1212; +exports.ER_LOCK_DEADLOCK = 1213; +exports.ER_TABLE_CANT_HANDLE_FT = 1214; +exports.ER_CANNOT_ADD_FOREIGN = 1215; +exports.ER_NO_REFERENCED_ROW = 1216; +exports.ER_ROW_IS_REFERENCED = 1217; +exports.ER_CONNECT_TO_MASTER = 1218; +exports.ER_QUERY_ON_MASTER = 1219; +exports.ER_ERROR_WHEN_EXECUTING_COMMAND = 1220; +exports.ER_WRONG_USAGE = 1221; +exports.ER_WRONG_NUMBER_OF_COLUMNS_IN_SELECT = 1222; +exports.ER_CANT_UPDATE_WITH_READLOCK = 1223; +exports.ER_MIXING_NOT_ALLOWED = 1224; +exports.ER_DUP_ARGUMENT = 1225; +exports.ER_USER_LIMIT_REACHED = 1226; +exports.ER_SPECIFIC_ACCESS_DENIED_ERROR = 1227; +exports.ER_LOCAL_VARIABLE = 1228; +exports.ER_GLOBAL_VARIABLE = 1229; +exports.ER_NO_DEFAULT = 1230; +exports.ER_WRONG_VALUE_FOR_VAR = 1231; +exports.ER_WRONG_TYPE_FOR_VAR = 1232; +exports.ER_VAR_CANT_BE_READ = 1233; +exports.ER_CANT_USE_OPTION_HERE = 1234; +exports.ER_NOT_SUPPORTED_YET = 1235; +exports.ER_MASTER_FATAL_ERROR_READING_BINLOG = 1236; +exports.ER_SLAVE_IGNORED_TABLE = 1237; +exports.ER_INCORRECT_GLOBAL_LOCAL_VAR = 1238; +exports.ER_WRONG_FK_DEF = 1239; +exports.ER_KEY_REF_DO_NOT_MATCH_TABLE_REF = 1240; +exports.ER_OPERAND_COLUMNS = 1241; +exports.ER_SUBQUERY_NO_1_ROW = 1242; +exports.ER_UNKNOWN_STMT_HANDLER = 1243; +exports.ER_CORRUPT_HELP_DB = 1244; +exports.ER_CYCLIC_REFERENCE = 1245; +exports.ER_AUTO_CONVERT = 1246; +exports.ER_ILLEGAL_REFERENCE = 1247; +exports.ER_DERIVED_MUST_HAVE_ALIAS = 1248; +exports.ER_SELECT_REDUCED = 1249; +exports.ER_TABLENAME_NOT_ALLOWED_HERE = 1250; +exports.ER_NOT_SUPPORTED_AUTH_MODE = 1251; +exports.ER_SPATIAL_CANT_HAVE_NULL = 1252; +exports.ER_COLLATION_CHARSET_MISMATCH = 1253; +exports.ER_SLAVE_WAS_RUNNING = 1254; +exports.ER_SLAVE_WAS_NOT_RUNNING = 1255; +exports.ER_TOO_BIG_FOR_UNCOMPRESS = 1256; +exports.ER_ZLIB_Z_MEM_ERROR = 1257; +exports.ER_ZLIB_Z_BUF_ERROR = 1258; +exports.ER_ZLIB_Z_DATA_ERROR = 1259; +exports.ER_CUT_VALUE_GROUP_CONCAT = 1260; +exports.ER_WARN_TOO_FEW_RECORDS = 1261; +exports.ER_WARN_TOO_MANY_RECORDS = 1262; +exports.ER_WARN_NULL_TO_NOTNULL = 1263; +exports.ER_WARN_DATA_OUT_OF_RANGE = 1264; +exports.WARN_DATA_TRUNCATED = 1265; +exports.ER_WARN_USING_OTHER_HANDLER = 1266; +exports.ER_CANT_AGGREGATE_2COLLATIONS = 1267; +exports.ER_DROP_USER = 1268; +exports.ER_REVOKE_GRANTS = 1269; +exports.ER_CANT_AGGREGATE_3COLLATIONS = 1270; +exports.ER_CANT_AGGREGATE_NCOLLATIONS = 1271; +exports.ER_VARIABLE_IS_NOT_STRUCT = 1272; +exports.ER_UNKNOWN_COLLATION = 1273; +exports.ER_SLAVE_IGNORED_SSL_PARAMS = 1274; +exports.ER_SERVER_IS_IN_SECURE_AUTH_MODE = 1275; +exports.ER_WARN_FIELD_RESOLVED = 1276; +exports.ER_BAD_SLAVE_UNTIL_COND = 1277; +exports.ER_MISSING_SKIP_SLAVE = 1278; +exports.ER_UNTIL_COND_IGNORED = 1279; +exports.ER_WRONG_NAME_FOR_INDEX = 1280; +exports.ER_WRONG_NAME_FOR_CATALOG = 1281; +exports.ER_WARN_QC_RESIZE = 1282; +exports.ER_BAD_FT_COLUMN = 1283; +exports.ER_UNKNOWN_KEY_CACHE = 1284; +exports.ER_WARN_HOSTNAME_WONT_WORK = 1285; +exports.ER_UNKNOWN_STORAGE_ENGINE = 1286; +exports.ER_WARN_DEPRECATED_SYNTAX = 1287; +exports.ER_NON_UPDATABLE_TABLE = 1288; +exports.ER_FEATURE_DISABLED = 1289; +exports.ER_OPTION_PREVENTS_STATEMENT = 1290; +exports.ER_DUPLICATED_VALUE_IN_TYPE = 1291; +exports.ER_TRUNCATED_WRONG_VALUE = 1292; +exports.ER_TOO_MUCH_AUTO_TIMESTAMP_COLS = 1293; +exports.ER_INVALID_ON_UPDATE = 1294; +exports.ER_UNSUPPORTED_PS = 1295; +exports.ER_GET_ERRMSG = 1296; +exports.ER_GET_TEMPORARY_ERRMSG = 1297; +exports.ER_UNKNOWN_TIME_ZONE = 1298; +exports.ER_WARN_INVALID_TIMESTAMP = 1299; +exports.ER_INVALID_CHARACTER_STRING = 1300; +exports.ER_WARN_ALLOWED_PACKET_OVERFLOWED = 1301; +exports.ER_CONFLICTING_DECLARATIONS = 1302; +exports.ER_SP_NO_RECURSIVE_CREATE = 1303; +exports.ER_SP_ALREADY_EXISTS = 1304; +exports.ER_SP_DOES_NOT_EXIST = 1305; +exports.ER_SP_DROP_FAILED = 1306; +exports.ER_SP_STORE_FAILED = 1307; +exports.ER_SP_LILABEL_MISMATCH = 1308; +exports.ER_SP_LABEL_REDEFINE = 1309; +exports.ER_SP_LABEL_MISMATCH = 1310; +exports.ER_SP_UNINIT_VAR = 1311; +exports.ER_SP_BADSELECT = 1312; +exports.ER_SP_BADRETURN = 1313; +exports.ER_SP_BADSTATEMENT = 1314; +exports.ER_UPDATE_LOG_DEPRECATED_IGNORED = 1315; +exports.ER_UPDATE_LOG_DEPRECATED_TRANSLATED = 1316; +exports.ER_QUERY_INTERRUPTED = 1317; +exports.ER_SP_WRONG_NO_OF_ARGS = 1318; +exports.ER_SP_COND_MISMATCH = 1319; +exports.ER_SP_NORETURN = 1320; +exports.ER_SP_NORETURNEND = 1321; +exports.ER_SP_BAD_CURSOR_QUERY = 1322; +exports.ER_SP_BAD_CURSOR_SELECT = 1323; +exports.ER_SP_CURSOR_MISMATCH = 1324; +exports.ER_SP_CURSOR_ALREADY_OPEN = 1325; +exports.ER_SP_CURSOR_NOT_OPEN = 1326; +exports.ER_SP_UNDECLARED_VAR = 1327; +exports.ER_SP_WRONG_NO_OF_FETCH_ARGS = 1328; +exports.ER_SP_FETCH_NO_DATA = 1329; +exports.ER_SP_DUP_PARAM = 1330; +exports.ER_SP_DUP_VAR = 1331; +exports.ER_SP_DUP_COND = 1332; +exports.ER_SP_DUP_CURS = 1333; +exports.ER_SP_CANT_ALTER = 1334; +exports.ER_SP_SUBSELECT_NYI = 1335; +exports.ER_STMT_NOT_ALLOWED_IN_SF_OR_TRG = 1336; +exports.ER_SP_VARCOND_AFTER_CURSHNDLR = 1337; +exports.ER_SP_CURSOR_AFTER_HANDLER = 1338; +exports.ER_SP_CASE_NOT_FOUND = 1339; +exports.ER_FPARSER_TOO_BIG_FILE = 1340; +exports.ER_FPARSER_BAD_HEADER = 1341; +exports.ER_FPARSER_EOF_IN_COMMENT = 1342; +exports.ER_FPARSER_ERROR_IN_PARAMETER = 1343; +exports.ER_FPARSER_EOF_IN_UNKNOWN_PARAMETER = 1344; +exports.ER_VIEW_NO_EXPLAIN = 1345; +exports.ER_FRM_UNKNOWN_TYPE = 1346; +exports.ER_WRONG_OBJECT = 1347; +exports.ER_NONUPDATEABLE_COLUMN = 1348; +exports.ER_VIEW_SELECT_DERIVED = 1349; +exports.ER_VIEW_SELECT_CLAUSE = 1350; +exports.ER_VIEW_SELECT_VARIABLE = 1351; +exports.ER_VIEW_SELECT_TMPTABLE = 1352; +exports.ER_VIEW_WRONG_LIST = 1353; +exports.ER_WARN_VIEW_MERGE = 1354; +exports.ER_WARN_VIEW_WITHOUT_KEY = 1355; +exports.ER_VIEW_INVALID = 1356; +exports.ER_SP_NO_DROP_SP = 1357; +exports.ER_SP_GOTO_IN_HNDLR = 1358; +exports.ER_TRG_ALREADY_EXISTS = 1359; +exports.ER_TRG_DOES_NOT_EXIST = 1360; +exports.ER_TRG_ON_VIEW_OR_TEMP_TABLE = 1361; +exports.ER_TRG_CANT_CHANGE_ROW = 1362; +exports.ER_TRG_NO_SUCH_ROW_IN_TRG = 1363; +exports.ER_NO_DEFAULT_FOR_FIELD = 1364; +exports.ER_DIVISION_BY_ZERO = 1365; +exports.ER_TRUNCATED_WRONG_VALUE_FOR_FIELD = 1366; +exports.ER_ILLEGAL_VALUE_FOR_TYPE = 1367; +exports.ER_VIEW_NONUPD_CHECK = 1368; +exports.ER_VIEW_CHECK_FAILED = 1369; +exports.ER_PROCACCESS_DENIED_ERROR = 1370; +exports.ER_RELAY_LOG_FAIL = 1371; +exports.ER_PASSWD_LENGTH = 1372; +exports.ER_UNKNOWN_TARGET_BINLOG = 1373; +exports.ER_IO_ERR_LOG_INDEX_READ = 1374; +exports.ER_BINLOG_PURGE_PROHIBITED = 1375; +exports.ER_FSEEK_FAIL = 1376; +exports.ER_BINLOG_PURGE_FATAL_ERR = 1377; +exports.ER_LOG_IN_USE = 1378; +exports.ER_LOG_PURGE_UNKNOWN_ERR = 1379; +exports.ER_RELAY_LOG_INIT = 1380; +exports.ER_NO_BINARY_LOGGING = 1381; +exports.ER_RESERVED_SYNTAX = 1382; +exports.ER_WSAS_FAILED = 1383; +exports.ER_DIFF_GROUPS_PROC = 1384; +exports.ER_NO_GROUP_FOR_PROC = 1385; +exports.ER_ORDER_WITH_PROC = 1386; +exports.ER_LOGGING_PROHIBIT_CHANGING_OF = 1387; +exports.ER_NO_FILE_MAPPING = 1388; +exports.ER_WRONG_MAGIC = 1389; +exports.ER_PS_MANY_PARAM = 1390; +exports.ER_KEY_PART_0 = 1391; +exports.ER_VIEW_CHECKSUM = 1392; +exports.ER_VIEW_MULTIUPDATE = 1393; +exports.ER_VIEW_NO_INSERT_FIELD_LIST = 1394; +exports.ER_VIEW_DELETE_MERGE_VIEW = 1395; +exports.ER_CANNOT_USER = 1396; +exports.ER_XAER_NOTA = 1397; +exports.ER_XAER_INVAL = 1398; +exports.ER_XAER_RMFAIL = 1399; +exports.ER_XAER_OUTSIDE = 1400; +exports.ER_XAER_RMERR = 1401; +exports.ER_XA_RBROLLBACK = 1402; +exports.ER_NONEXISTING_PROC_GRANT = 1403; +exports.ER_PROC_AUTO_GRANT_FAIL = 1404; +exports.ER_PROC_AUTO_REVOKE_FAIL = 1405; +exports.ER_DATA_TOO_LONG = 1406; +exports.ER_SP_BAD_SQLSTATE = 1407; +exports.ER_STARTUP = 1408; +exports.ER_LOAD_FROM_FIXED_SIZE_ROWS_TO_VAR = 1409; +exports.ER_CANT_CREATE_USER_WITH_GRANT = 1410; +exports.ER_WRONG_VALUE_FOR_TYPE = 1411; +exports.ER_TABLE_DEF_CHANGED = 1412; +exports.ER_SP_DUP_HANDLER = 1413; +exports.ER_SP_NOT_VAR_ARG = 1414; +exports.ER_SP_NO_RETSET = 1415; +exports.ER_CANT_CREATE_GEOMETRY_OBJECT = 1416; +exports.ER_FAILED_ROUTINE_BREAK_BINLOG = 1417; +exports.ER_BINLOG_UNSAFE_ROUTINE = 1418; +exports.ER_BINLOG_CREATE_ROUTINE_NEED_SUPER = 1419; +exports.ER_EXEC_STMT_WITH_OPEN_CURSOR = 1420; +exports.ER_STMT_HAS_NO_OPEN_CURSOR = 1421; +exports.ER_COMMIT_NOT_ALLOWED_IN_SF_OR_TRG = 1422; +exports.ER_NO_DEFAULT_FOR_VIEW_FIELD = 1423; +exports.ER_SP_NO_RECURSION = 1424; +exports.ER_TOO_BIG_SCALE = 1425; +exports.ER_TOO_BIG_PRECISION = 1426; +exports.ER_M_BIGGER_THAN_D = 1427; +exports.ER_WRONG_LOCK_OF_SYSTEM_TABLE = 1428; +exports.ER_CONNECT_TO_FOREIGN_DATA_SOURCE = 1429; +exports.ER_QUERY_ON_FOREIGN_DATA_SOURCE = 1430; +exports.ER_FOREIGN_DATA_SOURCE_DOESNT_EXIST = 1431; +exports.ER_FOREIGN_DATA_STRING_INVALID_CANT_CREATE = 1432; +exports.ER_FOREIGN_DATA_STRING_INVALID = 1433; +exports.ER_CANT_CREATE_FEDERATED_TABLE = 1434; +exports.ER_TRG_IN_WRONG_SCHEMA = 1435; +exports.ER_STACK_OVERRUN_NEED_MORE = 1436; +exports.ER_TOO_LONG_BODY = 1437; +exports.ER_WARN_CANT_DROP_DEFAULT_KEYCACHE = 1438; +exports.ER_TOO_BIG_DISPLAYWIDTH = 1439; +exports.ER_XAER_DUPID = 1440; +exports.ER_DATETIME_FUNCTION_OVERFLOW = 1441; +exports.ER_CANT_UPDATE_USED_TABLE_IN_SF_OR_TRG = 1442; +exports.ER_VIEW_PREVENT_UPDATE = 1443; +exports.ER_PS_NO_RECURSION = 1444; +exports.ER_SP_CANT_SET_AUTOCOMMIT = 1445; +exports.ER_MALFORMED_DEFINER = 1446; +exports.ER_VIEW_FRM_NO_USER = 1447; +exports.ER_VIEW_OTHER_USER = 1448; +exports.ER_NO_SUCH_USER = 1449; +exports.ER_FORBID_SCHEMA_CHANGE = 1450; +exports.ER_ROW_IS_REFERENCED_2 = 1451; +exports.ER_NO_REFERENCED_ROW_2 = 1452; +exports.ER_SP_BAD_VAR_SHADOW = 1453; +exports.ER_TRG_NO_DEFINER = 1454; +exports.ER_OLD_FILE_FORMAT = 1455; +exports.ER_SP_RECURSION_LIMIT = 1456; +exports.ER_SP_PROC_TABLE_CORRUPT = 1457; +exports.ER_SP_WRONG_NAME = 1458; +exports.ER_TABLE_NEEDS_UPGRADE = 1459; +exports.ER_SP_NO_AGGREGATE = 1460; +exports.ER_MAX_PREPARED_STMT_COUNT_REACHED = 1461; +exports.ER_VIEW_RECURSIVE = 1462; +exports.ER_NON_GROUPING_FIELD_USED = 1463; +exports.ER_TABLE_CANT_HANDLE_SPKEYS = 1464; +exports.ER_NO_TRIGGERS_ON_SYSTEM_SCHEMA = 1465; +exports.ER_REMOVED_SPACES = 1466; +exports.ER_AUTOINC_READ_FAILED = 1467; +exports.ER_USERNAME = 1468; +exports.ER_HOSTNAME = 1469; +exports.ER_WRONG_STRING_LENGTH = 1470; +exports.ER_NON_INSERTABLE_TABLE = 1471; +exports.ER_ADMIN_WRONG_MRG_TABLE = 1472; +exports.ER_TOO_HIGH_LEVEL_OF_NESTING_FOR_SELECT = 1473; +exports.ER_NAME_BECOMES_EMPTY = 1474; +exports.ER_AMBIGUOUS_FIELD_TERM = 1475; +exports.ER_FOREIGN_SERVER_EXISTS = 1476; +exports.ER_FOREIGN_SERVER_DOESNT_EXIST = 1477; +exports.ER_ILLEGAL_HA_CREATE_OPTION = 1478; +exports.ER_PARTITION_REQUIRES_VALUES_ERROR = 1479; +exports.ER_PARTITION_WRONG_VALUES_ERROR = 1480; +exports.ER_PARTITION_MAXVALUE_ERROR = 1481; +exports.ER_PARTITION_SUBPARTITION_ERROR = 1482; +exports.ER_PARTITION_SUBPART_MIX_ERROR = 1483; +exports.ER_PARTITION_WRONG_NO_PART_ERROR = 1484; +exports.ER_PARTITION_WRONG_NO_SUBPART_ERROR = 1485; +exports.ER_WRONG_EXPR_IN_PARTITION_FUNC_ERROR = 1486; +exports.ER_NO_CONST_EXPR_IN_RANGE_OR_LIST_ERROR = 1487; +exports.ER_FIELD_NOT_FOUND_PART_ERROR = 1488; +exports.ER_LIST_OF_FIELDS_ONLY_IN_HASH_ERROR = 1489; +exports.ER_INCONSISTENT_PARTITION_INFO_ERROR = 1490; +exports.ER_PARTITION_FUNC_NOT_ALLOWED_ERROR = 1491; +exports.ER_PARTITIONS_MUST_BE_DEFINED_ERROR = 1492; +exports.ER_RANGE_NOT_INCREASING_ERROR = 1493; +exports.ER_INCONSISTENT_TYPE_OF_FUNCTIONS_ERROR = 1494; +exports.ER_MULTIPLE_DEF_CONST_IN_LIST_PART_ERROR = 1495; +exports.ER_PARTITION_ENTRY_ERROR = 1496; +exports.ER_MIX_HANDLER_ERROR = 1497; +exports.ER_PARTITION_NOT_DEFINED_ERROR = 1498; +exports.ER_TOO_MANY_PARTITIONS_ERROR = 1499; +exports.ER_SUBPARTITION_ERROR = 1500; +exports.ER_CANT_CREATE_HANDLER_FILE = 1501; +exports.ER_BLOB_FIELD_IN_PART_FUNC_ERROR = 1502; +exports.ER_UNIQUE_KEY_NEED_ALL_FIELDS_IN_PF = 1503; +exports.ER_NO_PARTS_ERROR = 1504; +exports.ER_PARTITION_MGMT_ON_NONPARTITIONED = 1505; +exports.ER_FOREIGN_KEY_ON_PARTITIONED = 1506; +exports.ER_DROP_PARTITION_NON_EXISTENT = 1507; +exports.ER_DROP_LAST_PARTITION = 1508; +exports.ER_COALESCE_ONLY_ON_HASH_PARTITION = 1509; +exports.ER_REORG_HASH_ONLY_ON_SAME_NO = 1510; +exports.ER_REORG_NO_PARAM_ERROR = 1511; +exports.ER_ONLY_ON_RANGE_LIST_PARTITION = 1512; +exports.ER_ADD_PARTITION_SUBPART_ERROR = 1513; +exports.ER_ADD_PARTITION_NO_NEW_PARTITION = 1514; +exports.ER_COALESCE_PARTITION_NO_PARTITION = 1515; +exports.ER_REORG_PARTITION_NOT_EXIST = 1516; +exports.ER_SAME_NAME_PARTITION = 1517; +exports.ER_NO_BINLOG_ERROR = 1518; +exports.ER_CONSECUTIVE_REORG_PARTITIONS = 1519; +exports.ER_REORG_OUTSIDE_RANGE = 1520; +exports.ER_PARTITION_FUNCTION_FAILURE = 1521; +exports.ER_PART_STATE_ERROR = 1522; +exports.ER_LIMITED_PART_RANGE = 1523; +exports.ER_PLUGIN_IS_NOT_LOADED = 1524; +exports.ER_WRONG_VALUE = 1525; +exports.ER_NO_PARTITION_FOR_GIVEN_VALUE = 1526; +exports.ER_FILEGROUP_OPTION_ONLY_ONCE = 1527; +exports.ER_CREATE_FILEGROUP_FAILED = 1528; +exports.ER_DROP_FILEGROUP_FAILED = 1529; +exports.ER_TABLESPACE_AUTO_EXTEND_ERROR = 1530; +exports.ER_WRONG_SIZE_NUMBER = 1531; +exports.ER_SIZE_OVERFLOW_ERROR = 1532; +exports.ER_ALTER_FILEGROUP_FAILED = 1533; +exports.ER_BINLOG_ROW_LOGGING_FAILED = 1534; +exports.ER_BINLOG_ROW_WRONG_TABLE_DEF = 1535; +exports.ER_BINLOG_ROW_RBR_TO_SBR = 1536; +exports.ER_EVENT_ALREADY_EXISTS = 1537; +exports.ER_EVENT_STORE_FAILED = 1538; +exports.ER_EVENT_DOES_NOT_EXIST = 1539; +exports.ER_EVENT_CANT_ALTER = 1540; +exports.ER_EVENT_DROP_FAILED = 1541; +exports.ER_EVENT_INTERVAL_NOT_POSITIVE_OR_TOO_BIG = 1542; +exports.ER_EVENT_ENDS_BEFORE_STARTS = 1543; +exports.ER_EVENT_EXEC_TIME_IN_THE_PAST = 1544; +exports.ER_EVENT_OPEN_TABLE_FAILED = 1545; +exports.ER_EVENT_NEITHER_M_EXPR_NOR_M_AT = 1546; +exports.ER_COL_COUNT_DOESNT_MATCH_CORRUPTED = 1547; +exports.ER_CANNOT_LOAD_FROM_TABLE = 1548; +exports.ER_EVENT_CANNOT_DELETE = 1549; +exports.ER_EVENT_COMPILE_ERROR = 1550; +exports.ER_EVENT_SAME_NAME = 1551; +exports.ER_EVENT_DATA_TOO_LONG = 1552; +exports.ER_DROP_INDEX_FK = 1553; +exports.ER_WARN_DEPRECATED_SYNTAX_WITH_VER = 1554; +exports.ER_CANT_WRITE_LOCK_LOG_TABLE = 1555; +exports.ER_CANT_LOCK_LOG_TABLE = 1556; +exports.ER_FOREIGN_DUPLICATE_KEY = 1557; +exports.ER_COL_COUNT_DOESNT_MATCH_PLEASE_UPDATE = 1558; +exports.ER_TEMP_TABLE_PREVENTS_SWITCH_OUT_OF_RBR = 1559; +exports.ER_STORED_FUNCTION_PREVENTS_SWITCH_BINLOG_FORMAT = 1560; +exports.ER_NDB_CANT_SWITCH_BINLOG_FORMAT = 1561; +exports.ER_PARTITION_NO_TEMPORARY = 1562; +exports.ER_PARTITION_CONST_DOMAIN_ERROR = 1563; +exports.ER_PARTITION_FUNCTION_IS_NOT_ALLOWED = 1564; +exports.ER_DDL_LOG_ERROR = 1565; +exports.ER_NULL_IN_VALUES_LESS_THAN = 1566; +exports.ER_WRONG_PARTITION_NAME = 1567; +exports.ER_CANT_CHANGE_TX_CHARACTERISTICS = 1568; +exports.ER_DUP_ENTRY_AUTOINCREMENT_CASE = 1569; +exports.ER_EVENT_MODIFY_QUEUE_ERROR = 1570; +exports.ER_EVENT_SET_VAR_ERROR = 1571; +exports.ER_PARTITION_MERGE_ERROR = 1572; +exports.ER_CANT_ACTIVATE_LOG = 1573; +exports.ER_RBR_NOT_AVAILABLE = 1574; +exports.ER_BASE64_DECODE_ERROR = 1575; +exports.ER_EVENT_RECURSION_FORBIDDEN = 1576; +exports.ER_EVENTS_DB_ERROR = 1577; +exports.ER_ONLY_INTEGERS_ALLOWED = 1578; +exports.ER_UNSUPORTED_LOG_ENGINE = 1579; +exports.ER_BAD_LOG_STATEMENT = 1580; +exports.ER_CANT_RENAME_LOG_TABLE = 1581; +exports.ER_WRONG_PARAMCOUNT_TO_NATIVE_FCT = 1582; +exports.ER_WRONG_PARAMETERS_TO_NATIVE_FCT = 1583; +exports.ER_WRONG_PARAMETERS_TO_STORED_FCT = 1584; +exports.ER_NATIVE_FCT_NAME_COLLISION = 1585; +exports.ER_DUP_ENTRY_WITH_KEY_NAME = 1586; +exports.ER_BINLOG_PURGE_EMFILE = 1587; +exports.ER_EVENT_CANNOT_CREATE_IN_THE_PAST = 1588; +exports.ER_EVENT_CANNOT_ALTER_IN_THE_PAST = 1589; +exports.ER_SLAVE_INCIDENT = 1590; +exports.ER_NO_PARTITION_FOR_GIVEN_VALUE_SILENT = 1591; +exports.ER_BINLOG_UNSAFE_STATEMENT = 1592; +exports.ER_SLAVE_FATAL_ERROR = 1593; +exports.ER_SLAVE_RELAY_LOG_READ_FAILURE = 1594; +exports.ER_SLAVE_RELAY_LOG_WRITE_FAILURE = 1595; +exports.ER_SLAVE_CREATE_EVENT_FAILURE = 1596; +exports.ER_SLAVE_MASTER_COM_FAILURE = 1597; +exports.ER_BINLOG_LOGGING_IMPOSSIBLE = 1598; +exports.ER_VIEW_NO_CREATION_CTX = 1599; +exports.ER_VIEW_INVALID_CREATION_CTX = 1600; +exports.ER_SR_INVALID_CREATION_CTX = 1601; +exports.ER_TRG_CORRUPTED_FILE = 1602; +exports.ER_TRG_NO_CREATION_CTX = 1603; +exports.ER_TRG_INVALID_CREATION_CTX = 1604; +exports.ER_EVENT_INVALID_CREATION_CTX = 1605; +exports.ER_TRG_CANT_OPEN_TABLE = 1606; +exports.ER_CANT_CREATE_SROUTINE = 1607; +exports.ER_NEVER_USED = 1608; +exports.ER_NO_FORMAT_DESCRIPTION_EVENT_BEFORE_BINLOG_STATEMENT = 1609; +exports.ER_SLAVE_CORRUPT_EVENT = 1610; +exports.ER_LOAD_DATA_INVALID_COLUMN = 1611; +exports.ER_LOG_PURGE_NO_FILE = 1612; +exports.ER_XA_RBTIMEOUT = 1613; +exports.ER_XA_RBDEADLOCK = 1614; +exports.ER_NEED_REPREPARE = 1615; +exports.ER_DELAYED_NOT_SUPPORTED = 1616; +exports.WARN_NO_MASTER_INFO = 1617; +exports.WARN_OPTION_IGNORED = 1618; +exports.ER_PLUGIN_DELETE_BUILTIN = 1619; +exports.WARN_PLUGIN_BUSY = 1620; +exports.ER_VARIABLE_IS_READONLY = 1621; +exports.ER_WARN_ENGINE_TRANSACTION_ROLLBACK = 1622; +exports.ER_SLAVE_HEARTBEAT_FAILURE = 1623; +exports.ER_SLAVE_HEARTBEAT_VALUE_OUT_OF_RANGE = 1624; +exports.ER_NDB_REPLICATION_SCHEMA_ERROR = 1625; +exports.ER_CONFLICT_FN_PARSE_ERROR = 1626; +exports.ER_EXCEPTIONS_WRITE_ERROR = 1627; +exports.ER_TOO_LONG_TABLE_COMMENT = 1628; +exports.ER_TOO_LONG_FIELD_COMMENT = 1629; +exports.ER_FUNC_INEXISTENT_NAME_COLLISION = 1630; +exports.ER_DATABASE_NAME = 1631; +exports.ER_TABLE_NAME = 1632; +exports.ER_PARTITION_NAME = 1633; +exports.ER_SUBPARTITION_NAME = 1634; +exports.ER_TEMPORARY_NAME = 1635; +exports.ER_RENAMED_NAME = 1636; +exports.ER_TOO_MANY_CONCURRENT_TRXS = 1637; +exports.WARN_NON_ASCII_SEPARATOR_NOT_IMPLEMENTED = 1638; +exports.ER_DEBUG_SYNC_TIMEOUT = 1639; +exports.ER_DEBUG_SYNC_HIT_LIMIT = 1640; +exports.ER_DUP_SIGNAL_SET = 1641; +exports.ER_SIGNAL_WARN = 1642; +exports.ER_SIGNAL_NOT_FOUND = 1643; +exports.ER_SIGNAL_EXCEPTION = 1644; +exports.ER_RESIGNAL_WITHOUT_ACTIVE_HANDLER = 1645; +exports.ER_SIGNAL_BAD_CONDITION_TYPE = 1646; +exports.WARN_COND_ITEM_TRUNCATED = 1647; +exports.ER_COND_ITEM_TOO_LONG = 1648; +exports.ER_UNKNOWN_LOCALE = 1649; +exports.ER_SLAVE_IGNORE_SERVER_IDS = 1650; +exports.ER_QUERY_CACHE_DISABLED = 1651; +exports.ER_SAME_NAME_PARTITION_FIELD = 1652; +exports.ER_PARTITION_COLUMN_LIST_ERROR = 1653; +exports.ER_WRONG_TYPE_COLUMN_VALUE_ERROR = 1654; +exports.ER_TOO_MANY_PARTITION_FUNC_FIELDS_ERROR = 1655; +exports.ER_MAXVALUE_IN_VALUES_IN = 1656; +exports.ER_TOO_MANY_VALUES_ERROR = 1657; +exports.ER_ROW_SINGLE_PARTITION_FIELD_ERROR = 1658; +exports.ER_FIELD_TYPE_NOT_ALLOWED_AS_PARTITION_FIELD = 1659; +exports.ER_PARTITION_FIELDS_TOO_LONG = 1660; +exports.ER_BINLOG_ROW_ENGINE_AND_STMT_ENGINE = 1661; +exports.ER_BINLOG_ROW_MODE_AND_STMT_ENGINE = 1662; +exports.ER_BINLOG_UNSAFE_AND_STMT_ENGINE = 1663; +exports.ER_BINLOG_ROW_INJECTION_AND_STMT_ENGINE = 1664; +exports.ER_BINLOG_STMT_MODE_AND_ROW_ENGINE = 1665; +exports.ER_BINLOG_ROW_INJECTION_AND_STMT_MODE = 1666; +exports.ER_BINLOG_MULTIPLE_ENGINES_AND_SELF_LOGGING_ENGINE = 1667; +exports.ER_BINLOG_UNSAFE_LIMIT = 1668; +exports.ER_BINLOG_UNSAFE_INSERT_DELAYED = 1669; +exports.ER_BINLOG_UNSAFE_SYSTEM_TABLE = 1670; +exports.ER_BINLOG_UNSAFE_AUTOINC_COLUMNS = 1671; +exports.ER_BINLOG_UNSAFE_UDF = 1672; +exports.ER_BINLOG_UNSAFE_SYSTEM_VARIABLE = 1673; +exports.ER_BINLOG_UNSAFE_SYSTEM_FUNCTION = 1674; +exports.ER_BINLOG_UNSAFE_NONTRANS_AFTER_TRANS = 1675; +exports.ER_MESSAGE_AND_STATEMENT = 1676; +exports.ER_SLAVE_CONVERSION_FAILED = 1677; +exports.ER_SLAVE_CANT_CREATE_CONVERSION = 1678; +exports.ER_INSIDE_TRANSACTION_PREVENTS_SWITCH_BINLOG_FORMAT = 1679; +exports.ER_PATH_LENGTH = 1680; +exports.ER_WARN_DEPRECATED_SYNTAX_NO_REPLACEMENT = 1681; +exports.ER_WRONG_NATIVE_TABLE_STRUCTURE = 1682; +exports.ER_WRONG_PERFSCHEMA_USAGE = 1683; +exports.ER_WARN_I_S_SKIPPED_TABLE = 1684; +exports.ER_INSIDE_TRANSACTION_PREVENTS_SWITCH_BINLOG_DIRECT = 1685; +exports.ER_STORED_FUNCTION_PREVENTS_SWITCH_BINLOG_DIRECT = 1686; +exports.ER_SPATIAL_MUST_HAVE_GEOM_COL = 1687; +exports.ER_TOO_LONG_INDEX_COMMENT = 1688; +exports.ER_LOCK_ABORTED = 1689; +exports.ER_DATA_OUT_OF_RANGE = 1690; +exports.ER_WRONG_SPVAR_TYPE_IN_LIMIT = 1691; +exports.ER_BINLOG_UNSAFE_MULTIPLE_ENGINES_AND_SELF_LOGGING_ENGINE = 1692; +exports.ER_BINLOG_UNSAFE_MIXED_STATEMENT = 1693; +exports.ER_INSIDE_TRANSACTION_PREVENTS_SWITCH_SQL_LOG_BIN = 1694; +exports.ER_STORED_FUNCTION_PREVENTS_SWITCH_SQL_LOG_BIN = 1695; +exports.ER_FAILED_READ_FROM_PAR_FILE = 1696; +exports.ER_VALUES_IS_NOT_INT_TYPE_ERROR = 1697; +exports.ER_ACCESS_DENIED_NO_PASSWORD_ERROR = 1698; +exports.ER_SET_PASSWORD_AUTH_PLUGIN = 1699; +exports.ER_GRANT_PLUGIN_USER_EXISTS = 1700; +exports.ER_TRUNCATE_ILLEGAL_FK = 1701; +exports.ER_PLUGIN_IS_PERMANENT = 1702; +exports.ER_SLAVE_HEARTBEAT_VALUE_OUT_OF_RANGE_MIN = 1703; +exports.ER_SLAVE_HEARTBEAT_VALUE_OUT_OF_RANGE_MAX = 1704; +exports.ER_STMT_CACHE_FULL = 1705; +exports.ER_MULTI_UPDATE_KEY_CONFLICT = 1706; +exports.ER_TABLE_NEEDS_REBUILD = 1707; +exports.WARN_OPTION_BELOW_LIMIT = 1708; +exports.ER_INDEX_COLUMN_TOO_LONG = 1709; +exports.ER_ERROR_IN_TRIGGER_BODY = 1710; +exports.ER_ERROR_IN_UNKNOWN_TRIGGER_BODY = 1711; +exports.ER_INDEX_CORRUPT = 1712; +exports.ER_UNDO_RECORD_TOO_BIG = 1713; +exports.ER_BINLOG_UNSAFE_INSERT_IGNORE_SELECT = 1714; +exports.ER_BINLOG_UNSAFE_INSERT_SELECT_UPDATE = 1715; +exports.ER_BINLOG_UNSAFE_REPLACE_SELECT = 1716; +exports.ER_BINLOG_UNSAFE_CREATE_IGNORE_SELECT = 1717; +exports.ER_BINLOG_UNSAFE_CREATE_REPLACE_SELECT = 1718; +exports.ER_BINLOG_UNSAFE_UPDATE_IGNORE = 1719; +exports.ER_PLUGIN_NO_UNINSTALL = 1720; +exports.ER_PLUGIN_NO_INSTALL = 1721; +exports.ER_BINLOG_UNSAFE_WRITE_AUTOINC_SELECT = 1722; +exports.ER_BINLOG_UNSAFE_CREATE_SELECT_AUTOINC = 1723; +exports.ER_BINLOG_UNSAFE_INSERT_TWO_KEYS = 1724; +exports.ER_TABLE_IN_FK_CHECK = 1725; +exports.ER_UNSUPPORTED_ENGINE = 1726; +exports.ER_BINLOG_UNSAFE_AUTOINC_NOT_FIRST = 1727; +exports.ER_CANNOT_LOAD_FROM_TABLE_V2 = 1728; +exports.ER_MASTER_DELAY_VALUE_OUT_OF_RANGE = 1729; +exports.ER_ONLY_FD_AND_RBR_EVENTS_ALLOWED_IN_BINLOG_STATEMENT = 1730; +exports.ER_PARTITION_EXCHANGE_DIFFERENT_OPTION = 1731; +exports.ER_PARTITION_EXCHANGE_PART_TABLE = 1732; +exports.ER_PARTITION_EXCHANGE_TEMP_TABLE = 1733; +exports.ER_PARTITION_INSTEAD_OF_SUBPARTITION = 1734; +exports.ER_UNKNOWN_PARTITION = 1735; +exports.ER_TABLES_DIFFERENT_METADATA = 1736; +exports.ER_ROW_DOES_NOT_MATCH_PARTITION = 1737; +exports.ER_BINLOG_CACHE_SIZE_GREATER_THAN_MAX = 1738; +exports.ER_WARN_INDEX_NOT_APPLICABLE = 1739; +exports.ER_PARTITION_EXCHANGE_FOREIGN_KEY = 1740; +exports.ER_NO_SUCH_KEY_VALUE = 1741; +exports.ER_RPL_INFO_DATA_TOO_LONG = 1742; +exports.ER_NETWORK_READ_EVENT_CHECKSUM_FAILURE = 1743; +exports.ER_BINLOG_READ_EVENT_CHECKSUM_FAILURE = 1744; +exports.ER_BINLOG_STMT_CACHE_SIZE_GREATER_THAN_MAX = 1745; +exports.ER_CANT_UPDATE_TABLE_IN_CREATE_TABLE_SELECT = 1746; +exports.ER_PARTITION_CLAUSE_ON_NONPARTITIONED = 1747; +exports.ER_ROW_DOES_NOT_MATCH_GIVEN_PARTITION_SET = 1748; +exports.ER_NO_SUCH_PARTITION = 1749; +exports.ER_CHANGE_RPL_INFO_REPOSITORY_FAILURE = 1750; +exports.ER_WARNING_NOT_COMPLETE_ROLLBACK_WITH_CREATED_TEMP_TABLE = 1751; +exports.ER_WARNING_NOT_COMPLETE_ROLLBACK_WITH_DROPPED_TEMP_TABLE = 1752; +exports.ER_MTS_FEATURE_IS_NOT_SUPPORTED = 1753; +exports.ER_MTS_UPDATED_DBS_GREATER_MAX = 1754; +exports.ER_MTS_CANT_PARALLEL = 1755; +exports.ER_MTS_INCONSISTENT_DATA = 1756; +exports.ER_FULLTEXT_NOT_SUPPORTED_WITH_PARTITIONING = 1757; +exports.ER_DA_INVALID_CONDITION_NUMBER = 1758; +exports.ER_INSECURE_PLAIN_TEXT = 1759; +exports.ER_INSECURE_CHANGE_MASTER = 1760; +exports.ER_FOREIGN_DUPLICATE_KEY_WITH_CHILD_INFO = 1761; +exports.ER_FOREIGN_DUPLICATE_KEY_WITHOUT_CHILD_INFO = 1762; +exports.ER_SQLTHREAD_WITH_SECURE_SLAVE = 1763; +exports.ER_TABLE_HAS_NO_FT = 1764; +exports.ER_VARIABLE_NOT_SETTABLE_IN_SF_OR_TRIGGER = 1765; +exports.ER_VARIABLE_NOT_SETTABLE_IN_TRANSACTION = 1766; +exports.ER_GTID_NEXT_IS_NOT_IN_GTID_NEXT_LIST = 1767; +exports.ER_CANT_CHANGE_GTID_NEXT_IN_TRANSACTION = 1768; +exports.ER_SET_STATEMENT_CANNOT_INVOKE_FUNCTION = 1769; +exports.ER_GTID_NEXT_CANT_BE_AUTOMATIC_IF_GTID_NEXT_LIST_IS_NON_NULL = 1770; +exports.ER_SKIPPING_LOGGED_TRANSACTION = 1771; +exports.ER_MALFORMED_GTID_SET_SPECIFICATION = 1772; +exports.ER_MALFORMED_GTID_SET_ENCODING = 1773; +exports.ER_MALFORMED_GTID_SPECIFICATION = 1774; +exports.ER_GNO_EXHAUSTED = 1775; +exports.ER_BAD_SLAVE_AUTO_POSITION = 1776; +exports.ER_AUTO_POSITION_REQUIRES_GTID_MODE_NOT_OFF = 1777; +exports.ER_CANT_DO_IMPLICIT_COMMIT_IN_TRX_WHEN_GTID_NEXT_IS_SET = 1778; +exports.ER_GTID_MODE_ON_REQUIRES_ENFORCE_GTID_CONSISTENCY_ON = 1779; +exports.ER_GTID_MODE_REQUIRES_BINLOG = 1780; +exports.ER_CANT_SET_GTID_NEXT_TO_GTID_WHEN_GTID_MODE_IS_OFF = 1781; +exports.ER_CANT_SET_GTID_NEXT_TO_ANONYMOUS_WHEN_GTID_MODE_IS_ON = 1782; +exports.ER_CANT_SET_GTID_NEXT_LIST_TO_NON_NULL_WHEN_GTID_MODE_IS_OFF = 1783; +exports.ER_FOUND_GTID_EVENT_WHEN_GTID_MODE_IS_OFF = 1784; +exports.ER_GTID_UNSAFE_NON_TRANSACTIONAL_TABLE = 1785; +exports.ER_GTID_UNSAFE_CREATE_SELECT = 1786; +exports.ER_GTID_UNSAFE_CREATE_DROP_TEMPORARY_TABLE_IN_TRANSACTION = 1787; +exports.ER_GTID_MODE_CAN_ONLY_CHANGE_ONE_STEP_AT_A_TIME = 1788; +exports.ER_MASTER_HAS_PURGED_REQUIRED_GTIDS = 1789; +exports.ER_CANT_SET_GTID_NEXT_WHEN_OWNING_GTID = 1790; +exports.ER_UNKNOWN_EXPLAIN_FORMAT = 1791; +exports.ER_CANT_EXECUTE_IN_READ_ONLY_TRANSACTION = 1792; +exports.ER_TOO_LONG_TABLE_PARTITION_COMMENT = 1793; +exports.ER_SLAVE_CONFIGURATION = 1794; +exports.ER_INNODB_FT_LIMIT = 1795; +exports.ER_INNODB_NO_FT_TEMP_TABLE = 1796; +exports.ER_INNODB_FT_WRONG_DOCID_COLUMN = 1797; +exports.ER_INNODB_FT_WRONG_DOCID_INDEX = 1798; +exports.ER_INNODB_ONLINE_LOG_TOO_BIG = 1799; +exports.ER_UNKNOWN_ALTER_ALGORITHM = 1800; +exports.ER_UNKNOWN_ALTER_LOCK = 1801; +exports.ER_MTS_CHANGE_MASTER_CANT_RUN_WITH_GAPS = 1802; +exports.ER_MTS_RECOVERY_FAILURE = 1803; +exports.ER_MTS_RESET_WORKERS = 1804; +exports.ER_COL_COUNT_DOESNT_MATCH_CORRUPTED_V2 = 1805; +exports.ER_SLAVE_SILENT_RETRY_TRANSACTION = 1806; +exports.ER_DISCARD_FK_CHECKS_RUNNING = 1807; +exports.ER_TABLE_SCHEMA_MISMATCH = 1808; +exports.ER_TABLE_IN_SYSTEM_TABLESPACE = 1809; +exports.ER_IO_READ_ERROR = 1810; +exports.ER_IO_WRITE_ERROR = 1811; +exports.ER_TABLESPACE_MISSING = 1812; +exports.ER_TABLESPACE_EXISTS = 1813; +exports.ER_TABLESPACE_DISCARDED = 1814; +exports.ER_INTERNAL_ERROR = 1815; +exports.ER_INNODB_IMPORT_ERROR = 1816; +exports.ER_INNODB_INDEX_CORRUPT = 1817; +exports.ER_INVALID_YEAR_COLUMN_LENGTH = 1818; +exports.ER_NOT_VALID_PASSWORD = 1819; +exports.ER_MUST_CHANGE_PASSWORD = 1820; +exports.ER_FK_NO_INDEX_CHILD = 1821; +exports.ER_FK_NO_INDEX_PARENT = 1822; +exports.ER_FK_FAIL_ADD_SYSTEM = 1823; +exports.ER_FK_CANNOT_OPEN_PARENT = 1824; +exports.ER_FK_INCORRECT_OPTION = 1825; +exports.ER_FK_DUP_NAME = 1826; +exports.ER_PASSWORD_FORMAT = 1827; +exports.ER_FK_COLUMN_CANNOT_DROP = 1828; +exports.ER_FK_COLUMN_CANNOT_DROP_CHILD = 1829; +exports.ER_FK_COLUMN_NOT_NULL = 1830; +exports.ER_DUP_INDEX = 1831; +exports.ER_FK_COLUMN_CANNOT_CHANGE = 1832; +exports.ER_FK_COLUMN_CANNOT_CHANGE_CHILD = 1833; +exports.ER_FK_CANNOT_DELETE_PARENT = 1834; +exports.ER_MALFORMED_PACKET = 1835; +exports.ER_READ_ONLY_MODE = 1836; +exports.ER_GTID_NEXT_TYPE_UNDEFINED_GROUP = 1837; +exports.ER_VARIABLE_NOT_SETTABLE_IN_SP = 1838; +exports.ER_CANT_SET_GTID_PURGED_WHEN_GTID_MODE_IS_OFF = 1839; +exports.ER_CANT_SET_GTID_PURGED_WHEN_GTID_EXECUTED_IS_NOT_EMPTY = 1840; +exports.ER_CANT_SET_GTID_PURGED_WHEN_OWNED_GTIDS_IS_NOT_EMPTY = 1841; +exports.ER_GTID_PURGED_WAS_CHANGED = 1842; +exports.ER_GTID_EXECUTED_WAS_CHANGED = 1843; +exports.ER_BINLOG_STMT_MODE_AND_NO_REPL_TABLES = 1844; +exports.ER_ALTER_OPERATION_NOT_SUPPORTED = 1845; +exports.ER_ALTER_OPERATION_NOT_SUPPORTED_REASON = 1846; +exports.ER_ALTER_OPERATION_NOT_SUPPORTED_REASON_COPY = 1847; +exports.ER_ALTER_OPERATION_NOT_SUPPORTED_REASON_PARTITION = 1848; +exports.ER_ALTER_OPERATION_NOT_SUPPORTED_REASON_FK_RENAME = 1849; +exports.ER_ALTER_OPERATION_NOT_SUPPORTED_REASON_COLUMN_TYPE = 1850; +exports.ER_ALTER_OPERATION_NOT_SUPPORTED_REASON_FK_CHECK = 1851; +exports.ER_ALTER_OPERATION_NOT_SUPPORTED_REASON_IGNORE = 1852; +exports.ER_ALTER_OPERATION_NOT_SUPPORTED_REASON_NOPK = 1853; +exports.ER_ALTER_OPERATION_NOT_SUPPORTED_REASON_AUTOINC = 1854; +exports.ER_ALTER_OPERATION_NOT_SUPPORTED_REASON_HIDDEN_FTS = 1855; +exports.ER_ALTER_OPERATION_NOT_SUPPORTED_REASON_CHANGE_FTS = 1856; +exports.ER_ALTER_OPERATION_NOT_SUPPORTED_REASON_FTS = 1857; +exports.ER_SQL_SLAVE_SKIP_COUNTER_NOT_SETTABLE_IN_GTID_MODE = 1858; +exports.ER_DUP_UNKNOWN_IN_INDEX = 1859; +exports.ER_IDENT_CAUSES_TOO_LONG_PATH = 1860; +exports.ER_ALTER_OPERATION_NOT_SUPPORTED_REASON_NOT_NULL = 1861; +exports.ER_MUST_CHANGE_PASSWORD_LOGIN = 1862; +exports.ER_ROW_IN_WRONG_PARTITION = 1863; +exports.ER_MTS_EVENT_BIGGER_PENDING_JOBS_SIZE_MAX = 1864; +exports.ER_INNODB_NO_FT_USES_PARSER = 1865; +exports.ER_BINLOG_LOGICAL_CORRUPTION = 1866; +exports.ER_WARN_PURGE_LOG_IN_USE = 1867; +exports.ER_WARN_PURGE_LOG_IS_ACTIVE = 1868; +exports.ER_AUTO_INCREMENT_CONFLICT = 1869; +exports.WARN_ON_BLOCKHOLE_IN_RBR = 1870; +exports.ER_SLAVE_MI_INIT_REPOSITORY = 1871; +exports.ER_SLAVE_RLI_INIT_REPOSITORY = 1872; +exports.ER_ACCESS_DENIED_CHANGE_USER_ERROR = 1873; +exports.ER_INNODB_READ_ONLY = 1874; +exports.ER_STOP_SLAVE_SQL_THREAD_TIMEOUT = 1875; +exports.ER_STOP_SLAVE_IO_THREAD_TIMEOUT = 1876; +exports.ER_TABLE_CORRUPT = 1877; +exports.ER_TEMP_FILE_WRITE_FAILURE = 1878; +exports.ER_INNODB_FT_AUX_NOT_HEX_ID = 1879; +exports.ER_OLD_TEMPORALS_UPGRADED = 1880; +exports.ER_INNODB_FORCED_RECOVERY = 1881; +exports.ER_AES_INVALID_IV = 1882; +exports.ER_PLUGIN_CANNOT_BE_UNINSTALLED = 1883; +exports.ER_GTID_UNSAFE_BINLOG_SPLITTABLE_STATEMENT_AND_GTID_GROUP = 1884; +exports.ER_SLAVE_HAS_MORE_GTIDS_THAN_MASTER = 1885; +exports.ER_MISSING_KEY = 1886; +exports.WARN_NAMED_PIPE_ACCESS_EVERYONE = 1887; +exports.ER_FOUND_MISSING_GTIDS = 1888; +exports.ER_FILE_CORRUPT = 3000; +exports.ER_ERROR_ON_MASTER = 3001; +exports.ER_INCONSISTENT_ERROR = 3002; +exports.ER_STORAGE_ENGINE_NOT_LOADED = 3003; +exports.ER_GET_STACKED_DA_WITHOUT_ACTIVE_HANDLER = 3004; +exports.ER_WARN_LEGACY_SYNTAX_CONVERTED = 3005; +exports.ER_BINLOG_UNSAFE_FULLTEXT_PLUGIN = 3006; +exports.ER_CANNOT_DISCARD_TEMPORARY_TABLE = 3007; +exports.ER_FK_DEPTH_EXCEEDED = 3008; +exports.ER_COL_COUNT_DOESNT_MATCH_PLEASE_UPDATE_V2 = 3009; +exports.ER_WARN_TRIGGER_DOESNT_HAVE_CREATED = 3010; +exports.ER_REFERENCED_TRG_DOES_NOT_EXIST = 3011; +exports.ER_EXPLAIN_NOT_SUPPORTED = 3012; +exports.ER_INVALID_FIELD_SIZE = 3013; +exports.ER_MISSING_HA_CREATE_OPTION = 3014; +exports.ER_ENGINE_OUT_OF_MEMORY = 3015; +exports.ER_PASSWORD_EXPIRE_ANONYMOUS_USER = 3016; +exports.ER_SLAVE_SQL_THREAD_MUST_STOP = 3017; +exports.ER_NO_FT_MATERIALIZED_SUBQUERY = 3018; +exports.ER_INNODB_UNDO_LOG_FULL = 3019; +exports.ER_INVALID_ARGUMENT_FOR_LOGARITHM = 3020; +exports.ER_SLAVE_CHANNEL_IO_THREAD_MUST_STOP = 3021; +exports.ER_WARN_OPEN_TEMP_TABLES_MUST_BE_ZERO = 3022; +exports.ER_WARN_ONLY_MASTER_LOG_FILE_NO_POS = 3023; +exports.ER_QUERY_TIMEOUT = 3024; +exports.ER_NON_RO_SELECT_DISABLE_TIMER = 3025; +exports.ER_DUP_LIST_ENTRY = 3026; +exports.ER_SQL_MODE_NO_EFFECT = 3027; +exports.ER_AGGREGATE_ORDER_FOR_UNION = 3028; +exports.ER_AGGREGATE_ORDER_NON_AGG_QUERY = 3029; +exports.ER_SLAVE_WORKER_STOPPED_PREVIOUS_THD_ERROR = 3030; +exports.ER_DONT_SUPPORT_SLAVE_PRESERVE_COMMIT_ORDER = 3031; +exports.ER_SERVER_OFFLINE_MODE = 3032; +exports.ER_GIS_DIFFERENT_SRIDS = 3033; +exports.ER_GIS_UNSUPPORTED_ARGUMENT = 3034; +exports.ER_GIS_UNKNOWN_ERROR = 3035; +exports.ER_GIS_UNKNOWN_EXCEPTION = 3036; +exports.ER_GIS_INVALID_DATA = 3037; +exports.ER_BOOST_GEOMETRY_EMPTY_INPUT_EXCEPTION = 3038; +exports.ER_BOOST_GEOMETRY_CENTROID_EXCEPTION = 3039; +exports.ER_BOOST_GEOMETRY_OVERLAY_INVALID_INPUT_EXCEPTION = 3040; +exports.ER_BOOST_GEOMETRY_TURN_INFO_EXCEPTION = 3041; +exports.ER_BOOST_GEOMETRY_SELF_INTERSECTION_POINT_EXCEPTION = 3042; +exports.ER_BOOST_GEOMETRY_UNKNOWN_EXCEPTION = 3043; +exports.ER_STD_BAD_ALLOC_ERROR = 3044; +exports.ER_STD_DOMAIN_ERROR = 3045; +exports.ER_STD_LENGTH_ERROR = 3046; +exports.ER_STD_INVALID_ARGUMENT = 3047; +exports.ER_STD_OUT_OF_RANGE_ERROR = 3048; +exports.ER_STD_OVERFLOW_ERROR = 3049; +exports.ER_STD_RANGE_ERROR = 3050; +exports.ER_STD_UNDERFLOW_ERROR = 3051; +exports.ER_STD_LOGIC_ERROR = 3052; +exports.ER_STD_RUNTIME_ERROR = 3053; +exports.ER_STD_UNKNOWN_EXCEPTION = 3054; +exports.ER_GIS_DATA_WRONG_ENDIANESS = 3055; +exports.ER_CHANGE_MASTER_PASSWORD_LENGTH = 3056; +exports.ER_USER_LOCK_WRONG_NAME = 3057; +exports.ER_USER_LOCK_DEADLOCK = 3058; +exports.ER_REPLACE_INACCESSIBLE_ROWS = 3059; +exports.ER_ALTER_OPERATION_NOT_SUPPORTED_REASON_GIS = 3060; +exports.ER_ILLEGAL_USER_VAR = 3061; +exports.ER_GTID_MODE_OFF = 3062; +exports.ER_UNSUPPORTED_BY_REPLICATION_THREAD = 3063; +exports.ER_INCORRECT_TYPE = 3064; +exports.ER_FIELD_IN_ORDER_NOT_SELECT = 3065; +exports.ER_AGGREGATE_IN_ORDER_NOT_SELECT = 3066; +exports.ER_INVALID_RPL_WILD_TABLE_FILTER_PATTERN = 3067; +exports.ER_NET_OK_PACKET_TOO_LARGE = 3068; +exports.ER_INVALID_JSON_DATA = 3069; +exports.ER_INVALID_GEOJSON_MISSING_MEMBER = 3070; +exports.ER_INVALID_GEOJSON_WRONG_TYPE = 3071; +exports.ER_INVALID_GEOJSON_UNSPECIFIED = 3072; +exports.ER_DIMENSION_UNSUPPORTED = 3073; +exports.ER_SLAVE_CHANNEL_DOES_NOT_EXIST = 3074; +exports.ER_SLAVE_MULTIPLE_CHANNELS_HOST_PORT = 3075; +exports.ER_SLAVE_CHANNEL_NAME_INVALID_OR_TOO_LONG = 3076; +exports.ER_SLAVE_NEW_CHANNEL_WRONG_REPOSITORY = 3077; +exports.ER_SLAVE_CHANNEL_DELETE = 3078; +exports.ER_SLAVE_MULTIPLE_CHANNELS_CMD = 3079; +exports.ER_SLAVE_MAX_CHANNELS_EXCEEDED = 3080; +exports.ER_SLAVE_CHANNEL_MUST_STOP = 3081; +exports.ER_SLAVE_CHANNEL_NOT_RUNNING = 3082; +exports.ER_SLAVE_CHANNEL_WAS_RUNNING = 3083; +exports.ER_SLAVE_CHANNEL_WAS_NOT_RUNNING = 3084; +exports.ER_SLAVE_CHANNEL_SQL_THREAD_MUST_STOP = 3085; +exports.ER_SLAVE_CHANNEL_SQL_SKIP_COUNTER = 3086; +exports.ER_WRONG_FIELD_WITH_GROUP_V2 = 3087; +exports.ER_MIX_OF_GROUP_FUNC_AND_FIELDS_V2 = 3088; +exports.ER_WARN_DEPRECATED_SYSVAR_UPDATE = 3089; +exports.ER_WARN_DEPRECATED_SQLMODE = 3090; +exports.ER_CANNOT_LOG_PARTIAL_DROP_DATABASE_WITH_GTID = 3091; +exports.ER_GROUP_REPLICATION_CONFIGURATION = 3092; +exports.ER_GROUP_REPLICATION_RUNNING = 3093; +exports.ER_GROUP_REPLICATION_APPLIER_INIT_ERROR = 3094; +exports.ER_GROUP_REPLICATION_STOP_APPLIER_THREAD_TIMEOUT = 3095; +exports.ER_GROUP_REPLICATION_COMMUNICATION_LAYER_SESSION_ERROR = 3096; +exports.ER_GROUP_REPLICATION_COMMUNICATION_LAYER_JOIN_ERROR = 3097; +exports.ER_BEFORE_DML_VALIDATION_ERROR = 3098; +exports.ER_PREVENTS_VARIABLE_WITHOUT_RBR = 3099; +exports.ER_RUN_HOOK_ERROR = 3100; +exports.ER_TRANSACTION_ROLLBACK_DURING_COMMIT = 3101; +exports.ER_GENERATED_COLUMN_FUNCTION_IS_NOT_ALLOWED = 3102; +exports.ER_UNSUPPORTED_ALTER_INPLACE_ON_VIRTUAL_COLUMN = 3103; +exports.ER_WRONG_FK_OPTION_FOR_GENERATED_COLUMN = 3104; +exports.ER_NON_DEFAULT_VALUE_FOR_GENERATED_COLUMN = 3105; +exports.ER_UNSUPPORTED_ACTION_ON_GENERATED_COLUMN = 3106; +exports.ER_GENERATED_COLUMN_NON_PRIOR = 3107; +exports.ER_DEPENDENT_BY_GENERATED_COLUMN = 3108; +exports.ER_GENERATED_COLUMN_REF_AUTO_INC = 3109; +exports.ER_FEATURE_NOT_AVAILABLE = 3110; +exports.ER_CANT_SET_GTID_MODE = 3111; +exports.ER_CANT_USE_AUTO_POSITION_WITH_GTID_MODE_OFF = 3112; +exports.ER_CANT_REPLICATE_ANONYMOUS_WITH_AUTO_POSITION = 3113; +exports.ER_CANT_REPLICATE_ANONYMOUS_WITH_GTID_MODE_ON = 3114; +exports.ER_CANT_REPLICATE_GTID_WITH_GTID_MODE_OFF = 3115; +exports.ER_CANT_SET_ENFORCE_GTID_CONSISTENCY_ON_WITH_ONGOING_GTID_VIOLATING_TRANSACTIONS = 3116; +exports.ER_SET_ENFORCE_GTID_CONSISTENCY_WARN_WITH_ONGOING_GTID_VIOLATING_TRANSACTIONS = 3117; +exports.ER_ACCOUNT_HAS_BEEN_LOCKED = 3118; +exports.ER_WRONG_TABLESPACE_NAME = 3119; +exports.ER_TABLESPACE_IS_NOT_EMPTY = 3120; +exports.ER_WRONG_FILE_NAME = 3121; +exports.ER_BOOST_GEOMETRY_INCONSISTENT_TURNS_EXCEPTION = 3122; +exports.ER_WARN_OPTIMIZER_HINT_SYNTAX_ERROR = 3123; +exports.ER_WARN_BAD_MAX_EXECUTION_TIME = 3124; +exports.ER_WARN_UNSUPPORTED_MAX_EXECUTION_TIME = 3125; +exports.ER_WARN_CONFLICTING_HINT = 3126; +exports.ER_WARN_UNKNOWN_QB_NAME = 3127; +exports.ER_UNRESOLVED_HINT_NAME = 3128; +exports.ER_WARN_ON_MODIFYING_GTID_EXECUTED_TABLE = 3129; +exports.ER_PLUGGABLE_PROTOCOL_COMMAND_NOT_SUPPORTED = 3130; +exports.ER_LOCKING_SERVICE_WRONG_NAME = 3131; +exports.ER_LOCKING_SERVICE_DEADLOCK = 3132; +exports.ER_LOCKING_SERVICE_TIMEOUT = 3133; +exports.ER_GIS_MAX_POINTS_IN_GEOMETRY_OVERFLOWED = 3134; +exports.ER_SQL_MODE_MERGED = 3135; +exports.ER_VTOKEN_PLUGIN_TOKEN_MISMATCH = 3136; +exports.ER_VTOKEN_PLUGIN_TOKEN_NOT_FOUND = 3137; +exports.ER_CANT_SET_VARIABLE_WHEN_OWNING_GTID = 3138; +exports.ER_SLAVE_CHANNEL_OPERATION_NOT_ALLOWED = 3139; +exports.ER_INVALID_JSON_TEXT = 3140; +exports.ER_INVALID_JSON_TEXT_IN_PARAM = 3141; +exports.ER_INVALID_JSON_BINARY_DATA = 3142; +exports.ER_INVALID_JSON_PATH = 3143; +exports.ER_INVALID_JSON_CHARSET = 3144; +exports.ER_INVALID_JSON_CHARSET_IN_FUNCTION = 3145; +exports.ER_INVALID_TYPE_FOR_JSON = 3146; +exports.ER_INVALID_CAST_TO_JSON = 3147; +exports.ER_INVALID_JSON_PATH_CHARSET = 3148; +exports.ER_INVALID_JSON_PATH_WILDCARD = 3149; +exports.ER_JSON_VALUE_TOO_BIG = 3150; +exports.ER_JSON_KEY_TOO_BIG = 3151; +exports.ER_JSON_USED_AS_KEY = 3152; +exports.ER_JSON_VACUOUS_PATH = 3153; +exports.ER_JSON_BAD_ONE_OR_ALL_ARG = 3154; +exports.ER_NUMERIC_JSON_VALUE_OUT_OF_RANGE = 3155; +exports.ER_INVALID_JSON_VALUE_FOR_CAST = 3156; +exports.ER_JSON_DOCUMENT_TOO_DEEP = 3157; +exports.ER_JSON_DOCUMENT_NULL_KEY = 3158; +exports.ER_SECURE_TRANSPORT_REQUIRED = 3159; +exports.ER_NO_SECURE_TRANSPORTS_CONFIGURED = 3160; +exports.ER_DISABLED_STORAGE_ENGINE = 3161; +exports.ER_USER_DOES_NOT_EXIST = 3162; +exports.ER_USER_ALREADY_EXISTS = 3163; +exports.ER_AUDIT_API_ABORT = 3164; +exports.ER_INVALID_JSON_PATH_ARRAY_CELL = 3165; +exports.ER_BUFPOOL_RESIZE_INPROGRESS = 3166; +exports.ER_FEATURE_DISABLED_SEE_DOC = 3167; +exports.ER_SERVER_ISNT_AVAILABLE = 3168; +exports.ER_SESSION_WAS_KILLED = 3169; +exports.ER_CAPACITY_EXCEEDED = 3170; +exports.ER_CAPACITY_EXCEEDED_IN_RANGE_OPTIMIZER = 3171; +exports.ER_TABLE_NEEDS_UPG_PART = 3172; +exports.ER_CANT_WAIT_FOR_EXECUTED_GTID_SET_WHILE_OWNING_A_GTID = 3173; +exports.ER_CANNOT_ADD_FOREIGN_BASE_COL_VIRTUAL = 3174; +exports.ER_CANNOT_CREATE_VIRTUAL_INDEX_CONSTRAINT = 3175; +exports.ER_ERROR_ON_MODIFYING_GTID_EXECUTED_TABLE = 3176; +exports.ER_LOCK_REFUSED_BY_ENGINE = 3177; +exports.ER_UNSUPPORTED_ALTER_ONLINE_ON_VIRTUAL_COLUMN = 3178; +exports.ER_MASTER_KEY_ROTATION_NOT_SUPPORTED_BY_SE = 3179; +exports.ER_MASTER_KEY_ROTATION_ERROR_BY_SE = 3180; +exports.ER_MASTER_KEY_ROTATION_BINLOG_FAILED = 3181; +exports.ER_MASTER_KEY_ROTATION_SE_UNAVAILABLE = 3182; +exports.ER_TABLESPACE_CANNOT_ENCRYPT = 3183; +exports.ER_INVALID_ENCRYPTION_OPTION = 3184; +exports.ER_CANNOT_FIND_KEY_IN_KEYRING = 3185; +exports.ER_CAPACITY_EXCEEDED_IN_PARSER = 3186; +exports.ER_UNSUPPORTED_ALTER_ENCRYPTION_INPLACE = 3187; +exports.ER_KEYRING_UDF_KEYRING_SERVICE_ERROR = 3188; +exports.ER_USER_COLUMN_OLD_LENGTH = 3189; +exports.ER_CANT_RESET_MASTER = 3190; +exports.ER_GROUP_REPLICATION_MAX_GROUP_SIZE = 3191; +exports.ER_CANNOT_ADD_FOREIGN_BASE_COL_STORED = 3192; +exports.ER_TABLE_REFERENCED = 3193; +exports.ER_PARTITION_ENGINE_DEPRECATED_FOR_TABLE = 3194; +exports.ER_WARN_USING_GEOMFROMWKB_TO_SET_SRID_ZERO = 3195; +exports.ER_WARN_USING_GEOMFROMWKB_TO_SET_SRID = 3196; +exports.ER_XA_RETRY = 3197; +exports.ER_KEYRING_AWS_UDF_AWS_KMS_ERROR = 3198; +exports.ER_BINLOG_UNSAFE_XA = 3199; +exports.ER_UDF_ERROR = 3200; +exports.ER_KEYRING_MIGRATION_FAILURE = 3201; +exports.ER_KEYRING_ACCESS_DENIED_ERROR = 3202; +exports.ER_KEYRING_MIGRATION_STATUS = 3203; +exports.ER_PLUGIN_FAILED_TO_OPEN_TABLES = 3204; +exports.ER_PLUGIN_FAILED_TO_OPEN_TABLE = 3205; +exports.ER_AUDIT_LOG_NO_KEYRING_PLUGIN_INSTALLED = 3206; +exports.ER_AUDIT_LOG_ENCRYPTION_PASSWORD_HAS_NOT_BEEN_SET = 3207; +exports.ER_AUDIT_LOG_COULD_NOT_CREATE_AES_KEY = 3208; +exports.ER_AUDIT_LOG_ENCRYPTION_PASSWORD_CANNOT_BE_FETCHED = 3209; +exports.ER_AUDIT_LOG_JSON_FILTERING_NOT_ENABLED = 3210; +exports.ER_AUDIT_LOG_UDF_INSUFFICIENT_PRIVILEGE = 3211; +exports.ER_AUDIT_LOG_SUPER_PRIVILEGE_REQUIRED = 3212; +exports.ER_COULD_NOT_REINITIALIZE_AUDIT_LOG_FILTERS = 3213; +exports.ER_AUDIT_LOG_UDF_INVALID_ARGUMENT_TYPE = 3214; +exports.ER_AUDIT_LOG_UDF_INVALID_ARGUMENT_COUNT = 3215; +exports.ER_AUDIT_LOG_HAS_NOT_BEEN_INSTALLED = 3216; +exports.ER_AUDIT_LOG_UDF_READ_INVALID_MAX_ARRAY_LENGTH_ARG_TYPE = 3217; +exports.ER_AUDIT_LOG_UDF_READ_INVALID_MAX_ARRAY_LENGTH_ARG_VALUE = 3218; +exports.ER_AUDIT_LOG_JSON_FILTER_PARSING_ERROR = 3219; +exports.ER_AUDIT_LOG_JSON_FILTER_NAME_CANNOT_BE_EMPTY = 3220; +exports.ER_AUDIT_LOG_JSON_USER_NAME_CANNOT_BE_EMPTY = 3221; +exports.ER_AUDIT_LOG_JSON_FILTER_DOES_NOT_EXISTS = 3222; +exports.ER_AUDIT_LOG_USER_FIRST_CHARACTER_MUST_BE_ALPHANUMERIC = 3223; +exports.ER_AUDIT_LOG_USER_NAME_INVALID_CHARACTER = 3224; +exports.ER_AUDIT_LOG_HOST_NAME_INVALID_CHARACTER = 3225; +exports.WARN_DEPRECATED_MAXDB_SQL_MODE_FOR_TIMESTAMP = 3226; +exports.ER_XA_REPLICATION_FILTERS = 3227; +exports.ER_CANT_OPEN_ERROR_LOG = 3228; +exports.ER_GROUPING_ON_TIMESTAMP_IN_DST = 3229; +exports.ER_CANT_START_SERVER_NAMED_PIPE = 3230; + +// Lookup-by-number table +exports[1] = 'EE_CANTCREATEFILE'; +exports[2] = 'EE_READ'; +exports[3] = 'EE_WRITE'; +exports[4] = 'EE_BADCLOSE'; +exports[5] = 'EE_OUTOFMEMORY'; +exports[6] = 'EE_DELETE'; +exports[7] = 'EE_LINK'; +exports[9] = 'EE_EOFERR'; +exports[10] = 'EE_CANTLOCK'; +exports[11] = 'EE_CANTUNLOCK'; +exports[12] = 'EE_DIR'; +exports[13] = 'EE_STAT'; +exports[14] = 'EE_CANT_CHSIZE'; +exports[15] = 'EE_CANT_OPEN_STREAM'; +exports[16] = 'EE_GETWD'; +exports[17] = 'EE_SETWD'; +exports[18] = 'EE_LINK_WARNING'; +exports[19] = 'EE_OPEN_WARNING'; +exports[20] = 'EE_DISK_FULL'; +exports[21] = 'EE_CANT_MKDIR'; +exports[22] = 'EE_UNKNOWN_CHARSET'; +exports[23] = 'EE_OUT_OF_FILERESOURCES'; +exports[24] = 'EE_CANT_READLINK'; +exports[25] = 'EE_CANT_SYMLINK'; +exports[26] = 'EE_REALPATH'; +exports[27] = 'EE_SYNC'; +exports[28] = 'EE_UNKNOWN_COLLATION'; +exports[29] = 'EE_FILENOTFOUND'; +exports[30] = 'EE_FILE_NOT_CLOSED'; +exports[31] = 'EE_CHANGE_OWNERSHIP'; +exports[32] = 'EE_CHANGE_PERMISSIONS'; +exports[33] = 'EE_CANT_SEEK'; +exports[34] = 'EE_CAPACITY_EXCEEDED'; +exports[120] = 'HA_ERR_KEY_NOT_FOUND'; +exports[121] = 'HA_ERR_FOUND_DUPP_KEY'; +exports[122] = 'HA_ERR_INTERNAL_ERROR'; +exports[123] = 'HA_ERR_RECORD_CHANGED'; +exports[124] = 'HA_ERR_WRONG_INDEX'; +exports[126] = 'HA_ERR_CRASHED'; +exports[127] = 'HA_ERR_WRONG_IN_RECORD'; +exports[128] = 'HA_ERR_OUT_OF_MEM'; +exports[130] = 'HA_ERR_NOT_A_TABLE'; +exports[131] = 'HA_ERR_WRONG_COMMAND'; +exports[132] = 'HA_ERR_OLD_FILE'; +exports[133] = 'HA_ERR_NO_ACTIVE_RECORD'; +exports[134] = 'HA_ERR_RECORD_DELETED'; +exports[135] = 'HA_ERR_RECORD_FILE_FULL'; +exports[136] = 'HA_ERR_INDEX_FILE_FULL'; +exports[137] = 'HA_ERR_END_OF_FILE'; +exports[138] = 'HA_ERR_UNSUPPORTED'; +exports[139] = 'HA_ERR_TOO_BIG_ROW'; +exports[140] = 'HA_WRONG_CREATE_OPTION'; +exports[141] = 'HA_ERR_FOUND_DUPP_UNIQUE'; +exports[142] = 'HA_ERR_UNKNOWN_CHARSET'; +exports[143] = 'HA_ERR_WRONG_MRG_TABLE_DEF'; +exports[144] = 'HA_ERR_CRASHED_ON_REPAIR'; +exports[145] = 'HA_ERR_CRASHED_ON_USAGE'; +exports[146] = 'HA_ERR_LOCK_WAIT_TIMEOUT'; +exports[147] = 'HA_ERR_LOCK_TABLE_FULL'; +exports[148] = 'HA_ERR_READ_ONLY_TRANSACTION'; +exports[149] = 'HA_ERR_LOCK_DEADLOCK'; +exports[150] = 'HA_ERR_CANNOT_ADD_FOREIGN'; +exports[151] = 'HA_ERR_NO_REFERENCED_ROW'; +exports[152] = 'HA_ERR_ROW_IS_REFERENCED'; +exports[153] = 'HA_ERR_NO_SAVEPOINT'; +exports[154] = 'HA_ERR_NON_UNIQUE_BLOCK_SIZE'; +exports[155] = 'HA_ERR_NO_SUCH_TABLE'; +exports[156] = 'HA_ERR_TABLE_EXIST'; +exports[157] = 'HA_ERR_NO_CONNECTION'; +exports[158] = 'HA_ERR_NULL_IN_SPATIAL'; +exports[159] = 'HA_ERR_TABLE_DEF_CHANGED'; +exports[160] = 'HA_ERR_NO_PARTITION_FOUND'; +exports[161] = 'HA_ERR_RBR_LOGGING_FAILED'; +exports[162] = 'HA_ERR_DROP_INDEX_FK'; +exports[163] = 'HA_ERR_FOREIGN_DUPLICATE_KEY'; +exports[164] = 'HA_ERR_TABLE_NEEDS_UPGRADE'; +exports[165] = 'HA_ERR_TABLE_READONLY'; +exports[166] = 'HA_ERR_AUTOINC_READ_FAILED'; +exports[167] = 'HA_ERR_AUTOINC_ERANGE'; +exports[168] = 'HA_ERR_GENERIC'; +exports[169] = 'HA_ERR_RECORD_IS_THE_SAME'; +exports[170] = 'HA_ERR_LOGGING_IMPOSSIBLE'; +exports[171] = 'HA_ERR_CORRUPT_EVENT'; +exports[172] = 'HA_ERR_NEW_FILE'; +exports[173] = 'HA_ERR_ROWS_EVENT_APPLY'; +exports[174] = 'HA_ERR_INITIALIZATION'; +exports[175] = 'HA_ERR_FILE_TOO_SHORT'; +exports[176] = 'HA_ERR_WRONG_CRC'; +exports[177] = 'HA_ERR_TOO_MANY_CONCURRENT_TRXS'; +exports[178] = 'HA_ERR_NOT_IN_LOCK_PARTITIONS'; +exports[179] = 'HA_ERR_INDEX_COL_TOO_LONG'; +exports[180] = 'HA_ERR_INDEX_CORRUPT'; +exports[181] = 'HA_ERR_UNDO_REC_TOO_BIG'; +exports[182] = 'HA_FTS_INVALID_DOCID'; +exports[183] = 'HA_ERR_TABLE_IN_FK_CHECK'; +exports[184] = 'HA_ERR_TABLESPACE_EXISTS'; +exports[185] = 'HA_ERR_TOO_MANY_FIELDS'; +exports[186] = 'HA_ERR_ROW_IN_WRONG_PARTITION'; +exports[187] = 'HA_ERR_INNODB_READ_ONLY'; +exports[188] = 'HA_ERR_FTS_EXCEED_RESULT_CACHE_LIMIT'; +exports[189] = 'HA_ERR_TEMP_FILE_WRITE_FAILURE'; +exports[190] = 'HA_ERR_INNODB_FORCED_RECOVERY'; +exports[191] = 'HA_ERR_FTS_TOO_MANY_WORDS_IN_PHRASE'; +exports[192] = 'HA_ERR_FK_DEPTH_EXCEEDED'; +exports[193] = 'HA_MISSING_CREATE_OPTION'; +exports[194] = 'HA_ERR_SE_OUT_OF_MEMORY'; +exports[195] = 'HA_ERR_TABLE_CORRUPT'; +exports[196] = 'HA_ERR_QUERY_INTERRUPTED'; +exports[197] = 'HA_ERR_TABLESPACE_MISSING'; +exports[198] = 'HA_ERR_TABLESPACE_IS_NOT_EMPTY'; +exports[199] = 'HA_ERR_WRONG_FILE_NAME'; +exports[200] = 'HA_ERR_NOT_ALLOWED_COMMAND'; +exports[201] = 'HA_ERR_COMPUTE_FAILED'; +exports[1000] = 'ER_HASHCHK'; +exports[1001] = 'ER_NISAMCHK'; +exports[1002] = 'ER_NO'; +exports[1003] = 'ER_YES'; +exports[1004] = 'ER_CANT_CREATE_FILE'; +exports[1005] = 'ER_CANT_CREATE_TABLE'; +exports[1006] = 'ER_CANT_CREATE_DB'; +exports[1007] = 'ER_DB_CREATE_EXISTS'; +exports[1008] = 'ER_DB_DROP_EXISTS'; +exports[1009] = 'ER_DB_DROP_DELETE'; +exports[1010] = 'ER_DB_DROP_RMDIR'; +exports[1011] = 'ER_CANT_DELETE_FILE'; +exports[1012] = 'ER_CANT_FIND_SYSTEM_REC'; +exports[1013] = 'ER_CANT_GET_STAT'; +exports[1014] = 'ER_CANT_GET_WD'; +exports[1015] = 'ER_CANT_LOCK'; +exports[1016] = 'ER_CANT_OPEN_FILE'; +exports[1017] = 'ER_FILE_NOT_FOUND'; +exports[1018] = 'ER_CANT_READ_DIR'; +exports[1019] = 'ER_CANT_SET_WD'; +exports[1020] = 'ER_CHECKREAD'; +exports[1021] = 'ER_DISK_FULL'; +exports[1022] = 'ER_DUP_KEY'; +exports[1023] = 'ER_ERROR_ON_CLOSE'; +exports[1024] = 'ER_ERROR_ON_READ'; +exports[1025] = 'ER_ERROR_ON_RENAME'; +exports[1026] = 'ER_ERROR_ON_WRITE'; +exports[1027] = 'ER_FILE_USED'; +exports[1028] = 'ER_FILSORT_ABORT'; +exports[1029] = 'ER_FORM_NOT_FOUND'; +exports[1030] = 'ER_GET_ERRNO'; +exports[1031] = 'ER_ILLEGAL_HA'; +exports[1032] = 'ER_KEY_NOT_FOUND'; +exports[1033] = 'ER_NOT_FORM_FILE'; +exports[1034] = 'ER_NOT_KEYFILE'; +exports[1035] = 'ER_OLD_KEYFILE'; +exports[1036] = 'ER_OPEN_AS_READONLY'; +exports[1037] = 'ER_OUTOFMEMORY'; +exports[1038] = 'ER_OUT_OF_SORTMEMORY'; +exports[1039] = 'ER_UNEXPECTED_EOF'; +exports[1040] = 'ER_CON_COUNT_ERROR'; +exports[1041] = 'ER_OUT_OF_RESOURCES'; +exports[1042] = 'ER_BAD_HOST_ERROR'; +exports[1043] = 'ER_HANDSHAKE_ERROR'; +exports[1044] = 'ER_DBACCESS_DENIED_ERROR'; +exports[1045] = 'ER_ACCESS_DENIED_ERROR'; +exports[1046] = 'ER_NO_DB_ERROR'; +exports[1047] = 'ER_UNKNOWN_COM_ERROR'; +exports[1048] = 'ER_BAD_NULL_ERROR'; +exports[1049] = 'ER_BAD_DB_ERROR'; +exports[1050] = 'ER_TABLE_EXISTS_ERROR'; +exports[1051] = 'ER_BAD_TABLE_ERROR'; +exports[1052] = 'ER_NON_UNIQ_ERROR'; +exports[1053] = 'ER_SERVER_SHUTDOWN'; +exports[1054] = 'ER_BAD_FIELD_ERROR'; +exports[1055] = 'ER_WRONG_FIELD_WITH_GROUP'; +exports[1056] = 'ER_WRONG_GROUP_FIELD'; +exports[1057] = 'ER_WRONG_SUM_SELECT'; +exports[1058] = 'ER_WRONG_VALUE_COUNT'; +exports[1059] = 'ER_TOO_LONG_IDENT'; +exports[1060] = 'ER_DUP_FIELDNAME'; +exports[1061] = 'ER_DUP_KEYNAME'; +exports[1062] = 'ER_DUP_ENTRY'; +exports[1063] = 'ER_WRONG_FIELD_SPEC'; +exports[1064] = 'ER_PARSE_ERROR'; +exports[1065] = 'ER_EMPTY_QUERY'; +exports[1066] = 'ER_NONUNIQ_TABLE'; +exports[1067] = 'ER_INVALID_DEFAULT'; +exports[1068] = 'ER_MULTIPLE_PRI_KEY'; +exports[1069] = 'ER_TOO_MANY_KEYS'; +exports[1070] = 'ER_TOO_MANY_KEY_PARTS'; +exports[1071] = 'ER_TOO_LONG_KEY'; +exports[1072] = 'ER_KEY_COLUMN_DOES_NOT_EXITS'; +exports[1073] = 'ER_BLOB_USED_AS_KEY'; +exports[1074] = 'ER_TOO_BIG_FIELDLENGTH'; +exports[1075] = 'ER_WRONG_AUTO_KEY'; +exports[1076] = 'ER_READY'; +exports[1077] = 'ER_NORMAL_SHUTDOWN'; +exports[1078] = 'ER_GOT_SIGNAL'; +exports[1079] = 'ER_SHUTDOWN_COMPLETE'; +exports[1080] = 'ER_FORCING_CLOSE'; +exports[1081] = 'ER_IPSOCK_ERROR'; +exports[1082] = 'ER_NO_SUCH_INDEX'; +exports[1083] = 'ER_WRONG_FIELD_TERMINATORS'; +exports[1084] = 'ER_BLOBS_AND_NO_TERMINATED'; +exports[1085] = 'ER_TEXTFILE_NOT_READABLE'; +exports[1086] = 'ER_FILE_EXISTS_ERROR'; +exports[1087] = 'ER_LOAD_INFO'; +exports[1088] = 'ER_ALTER_INFO'; +exports[1089] = 'ER_WRONG_SUB_KEY'; +exports[1090] = 'ER_CANT_REMOVE_ALL_FIELDS'; +exports[1091] = 'ER_CANT_DROP_FIELD_OR_KEY'; +exports[1092] = 'ER_INSERT_INFO'; +exports[1093] = 'ER_UPDATE_TABLE_USED'; +exports[1094] = 'ER_NO_SUCH_THREAD'; +exports[1095] = 'ER_KILL_DENIED_ERROR'; +exports[1096] = 'ER_NO_TABLES_USED'; +exports[1097] = 'ER_TOO_BIG_SET'; +exports[1098] = 'ER_NO_UNIQUE_LOGFILE'; +exports[1099] = 'ER_TABLE_NOT_LOCKED_FOR_WRITE'; +exports[1100] = 'ER_TABLE_NOT_LOCKED'; +exports[1101] = 'ER_BLOB_CANT_HAVE_DEFAULT'; +exports[1102] = 'ER_WRONG_DB_NAME'; +exports[1103] = 'ER_WRONG_TABLE_NAME'; +exports[1104] = 'ER_TOO_BIG_SELECT'; +exports[1105] = 'ER_UNKNOWN_ERROR'; +exports[1106] = 'ER_UNKNOWN_PROCEDURE'; +exports[1107] = 'ER_WRONG_PARAMCOUNT_TO_PROCEDURE'; +exports[1108] = 'ER_WRONG_PARAMETERS_TO_PROCEDURE'; +exports[1109] = 'ER_UNKNOWN_TABLE'; +exports[1110] = 'ER_FIELD_SPECIFIED_TWICE'; +exports[1111] = 'ER_INVALID_GROUP_FUNC_USE'; +exports[1112] = 'ER_UNSUPPORTED_EXTENSION'; +exports[1113] = 'ER_TABLE_MUST_HAVE_COLUMNS'; +exports[1114] = 'ER_RECORD_FILE_FULL'; +exports[1115] = 'ER_UNKNOWN_CHARACTER_SET'; +exports[1116] = 'ER_TOO_MANY_TABLES'; +exports[1117] = 'ER_TOO_MANY_FIELDS'; +exports[1118] = 'ER_TOO_BIG_ROWSIZE'; +exports[1119] = 'ER_STACK_OVERRUN'; +exports[1120] = 'ER_WRONG_OUTER_JOIN'; +exports[1121] = 'ER_NULL_COLUMN_IN_INDEX'; +exports[1122] = 'ER_CANT_FIND_UDF'; +exports[1123] = 'ER_CANT_INITIALIZE_UDF'; +exports[1124] = 'ER_UDF_NO_PATHS'; +exports[1125] = 'ER_UDF_EXISTS'; +exports[1126] = 'ER_CANT_OPEN_LIBRARY'; +exports[1127] = 'ER_CANT_FIND_DL_ENTRY'; +exports[1128] = 'ER_FUNCTION_NOT_DEFINED'; +exports[1129] = 'ER_HOST_IS_BLOCKED'; +exports[1130] = 'ER_HOST_NOT_PRIVILEGED'; +exports[1131] = 'ER_PASSWORD_ANONYMOUS_USER'; +exports[1132] = 'ER_PASSWORD_NOT_ALLOWED'; +exports[1133] = 'ER_PASSWORD_NO_MATCH'; +exports[1134] = 'ER_UPDATE_INFO'; +exports[1135] = 'ER_CANT_CREATE_THREAD'; +exports[1136] = 'ER_WRONG_VALUE_COUNT_ON_ROW'; +exports[1137] = 'ER_CANT_REOPEN_TABLE'; +exports[1138] = 'ER_INVALID_USE_OF_NULL'; +exports[1139] = 'ER_REGEXP_ERROR'; +exports[1140] = 'ER_MIX_OF_GROUP_FUNC_AND_FIELDS'; +exports[1141] = 'ER_NONEXISTING_GRANT'; +exports[1142] = 'ER_TABLEACCESS_DENIED_ERROR'; +exports[1143] = 'ER_COLUMNACCESS_DENIED_ERROR'; +exports[1144] = 'ER_ILLEGAL_GRANT_FOR_TABLE'; +exports[1145] = 'ER_GRANT_WRONG_HOST_OR_USER'; +exports[1146] = 'ER_NO_SUCH_TABLE'; +exports[1147] = 'ER_NONEXISTING_TABLE_GRANT'; +exports[1148] = 'ER_NOT_ALLOWED_COMMAND'; +exports[1149] = 'ER_SYNTAX_ERROR'; +exports[1150] = 'ER_DELAYED_CANT_CHANGE_LOCK'; +exports[1151] = 'ER_TOO_MANY_DELAYED_THREADS'; +exports[1152] = 'ER_ABORTING_CONNECTION'; +exports[1153] = 'ER_NET_PACKET_TOO_LARGE'; +exports[1154] = 'ER_NET_READ_ERROR_FROM_PIPE'; +exports[1155] = 'ER_NET_FCNTL_ERROR'; +exports[1156] = 'ER_NET_PACKETS_OUT_OF_ORDER'; +exports[1157] = 'ER_NET_UNCOMPRESS_ERROR'; +exports[1158] = 'ER_NET_READ_ERROR'; +exports[1159] = 'ER_NET_READ_INTERRUPTED'; +exports[1160] = 'ER_NET_ERROR_ON_WRITE'; +exports[1161] = 'ER_NET_WRITE_INTERRUPTED'; +exports[1162] = 'ER_TOO_LONG_STRING'; +exports[1163] = 'ER_TABLE_CANT_HANDLE_BLOB'; +exports[1164] = 'ER_TABLE_CANT_HANDLE_AUTO_INCREMENT'; +exports[1165] = 'ER_DELAYED_INSERT_TABLE_LOCKED'; +exports[1166] = 'ER_WRONG_COLUMN_NAME'; +exports[1167] = 'ER_WRONG_KEY_COLUMN'; +exports[1168] = 'ER_WRONG_MRG_TABLE'; +exports[1169] = 'ER_DUP_UNIQUE'; +exports[1170] = 'ER_BLOB_KEY_WITHOUT_LENGTH'; +exports[1171] = 'ER_PRIMARY_CANT_HAVE_NULL'; +exports[1172] = 'ER_TOO_MANY_ROWS'; +exports[1173] = 'ER_REQUIRES_PRIMARY_KEY'; +exports[1174] = 'ER_NO_RAID_COMPILED'; +exports[1175] = 'ER_UPDATE_WITHOUT_KEY_IN_SAFE_MODE'; +exports[1176] = 'ER_KEY_DOES_NOT_EXITS'; +exports[1177] = 'ER_CHECK_NO_SUCH_TABLE'; +exports[1178] = 'ER_CHECK_NOT_IMPLEMENTED'; +exports[1179] = 'ER_CANT_DO_THIS_DURING_AN_TRANSACTION'; +exports[1180] = 'ER_ERROR_DURING_COMMIT'; +exports[1181] = 'ER_ERROR_DURING_ROLLBACK'; +exports[1182] = 'ER_ERROR_DURING_FLUSH_LOGS'; +exports[1183] = 'ER_ERROR_DURING_CHECKPOINT'; +exports[1184] = 'ER_NEW_ABORTING_CONNECTION'; +exports[1185] = 'ER_DUMP_NOT_IMPLEMENTED'; +exports[1186] = 'ER_FLUSH_MASTER_BINLOG_CLOSED'; +exports[1187] = 'ER_INDEX_REBUILD'; +exports[1188] = 'ER_MASTER'; +exports[1189] = 'ER_MASTER_NET_READ'; +exports[1190] = 'ER_MASTER_NET_WRITE'; +exports[1191] = 'ER_FT_MATCHING_KEY_NOT_FOUND'; +exports[1192] = 'ER_LOCK_OR_ACTIVE_TRANSACTION'; +exports[1193] = 'ER_UNKNOWN_SYSTEM_VARIABLE'; +exports[1194] = 'ER_CRASHED_ON_USAGE'; +exports[1195] = 'ER_CRASHED_ON_REPAIR'; +exports[1196] = 'ER_WARNING_NOT_COMPLETE_ROLLBACK'; +exports[1197] = 'ER_TRANS_CACHE_FULL'; +exports[1198] = 'ER_SLAVE_MUST_STOP'; +exports[1199] = 'ER_SLAVE_NOT_RUNNING'; +exports[1200] = 'ER_BAD_SLAVE'; +exports[1201] = 'ER_MASTER_INFO'; +exports[1202] = 'ER_SLAVE_THREAD'; +exports[1203] = 'ER_TOO_MANY_USER_CONNECTIONS'; +exports[1204] = 'ER_SET_CONSTANTS_ONLY'; +exports[1205] = 'ER_LOCK_WAIT_TIMEOUT'; +exports[1206] = 'ER_LOCK_TABLE_FULL'; +exports[1207] = 'ER_READ_ONLY_TRANSACTION'; +exports[1208] = 'ER_DROP_DB_WITH_READ_LOCK'; +exports[1209] = 'ER_CREATE_DB_WITH_READ_LOCK'; +exports[1210] = 'ER_WRONG_ARGUMENTS'; +exports[1211] = 'ER_NO_PERMISSION_TO_CREATE_USER'; +exports[1212] = 'ER_UNION_TABLES_IN_DIFFERENT_DIR'; +exports[1213] = 'ER_LOCK_DEADLOCK'; +exports[1214] = 'ER_TABLE_CANT_HANDLE_FT'; +exports[1215] = 'ER_CANNOT_ADD_FOREIGN'; +exports[1216] = 'ER_NO_REFERENCED_ROW'; +exports[1217] = 'ER_ROW_IS_REFERENCED'; +exports[1218] = 'ER_CONNECT_TO_MASTER'; +exports[1219] = 'ER_QUERY_ON_MASTER'; +exports[1220] = 'ER_ERROR_WHEN_EXECUTING_COMMAND'; +exports[1221] = 'ER_WRONG_USAGE'; +exports[1222] = 'ER_WRONG_NUMBER_OF_COLUMNS_IN_SELECT'; +exports[1223] = 'ER_CANT_UPDATE_WITH_READLOCK'; +exports[1224] = 'ER_MIXING_NOT_ALLOWED'; +exports[1225] = 'ER_DUP_ARGUMENT'; +exports[1226] = 'ER_USER_LIMIT_REACHED'; +exports[1227] = 'ER_SPECIFIC_ACCESS_DENIED_ERROR'; +exports[1228] = 'ER_LOCAL_VARIABLE'; +exports[1229] = 'ER_GLOBAL_VARIABLE'; +exports[1230] = 'ER_NO_DEFAULT'; +exports[1231] = 'ER_WRONG_VALUE_FOR_VAR'; +exports[1232] = 'ER_WRONG_TYPE_FOR_VAR'; +exports[1233] = 'ER_VAR_CANT_BE_READ'; +exports[1234] = 'ER_CANT_USE_OPTION_HERE'; +exports[1235] = 'ER_NOT_SUPPORTED_YET'; +exports[1236] = 'ER_MASTER_FATAL_ERROR_READING_BINLOG'; +exports[1237] = 'ER_SLAVE_IGNORED_TABLE'; +exports[1238] = 'ER_INCORRECT_GLOBAL_LOCAL_VAR'; +exports[1239] = 'ER_WRONG_FK_DEF'; +exports[1240] = 'ER_KEY_REF_DO_NOT_MATCH_TABLE_REF'; +exports[1241] = 'ER_OPERAND_COLUMNS'; +exports[1242] = 'ER_SUBQUERY_NO_1_ROW'; +exports[1243] = 'ER_UNKNOWN_STMT_HANDLER'; +exports[1244] = 'ER_CORRUPT_HELP_DB'; +exports[1245] = 'ER_CYCLIC_REFERENCE'; +exports[1246] = 'ER_AUTO_CONVERT'; +exports[1247] = 'ER_ILLEGAL_REFERENCE'; +exports[1248] = 'ER_DERIVED_MUST_HAVE_ALIAS'; +exports[1249] = 'ER_SELECT_REDUCED'; +exports[1250] = 'ER_TABLENAME_NOT_ALLOWED_HERE'; +exports[1251] = 'ER_NOT_SUPPORTED_AUTH_MODE'; +exports[1252] = 'ER_SPATIAL_CANT_HAVE_NULL'; +exports[1253] = 'ER_COLLATION_CHARSET_MISMATCH'; +exports[1254] = 'ER_SLAVE_WAS_RUNNING'; +exports[1255] = 'ER_SLAVE_WAS_NOT_RUNNING'; +exports[1256] = 'ER_TOO_BIG_FOR_UNCOMPRESS'; +exports[1257] = 'ER_ZLIB_Z_MEM_ERROR'; +exports[1258] = 'ER_ZLIB_Z_BUF_ERROR'; +exports[1259] = 'ER_ZLIB_Z_DATA_ERROR'; +exports[1260] = 'ER_CUT_VALUE_GROUP_CONCAT'; +exports[1261] = 'ER_WARN_TOO_FEW_RECORDS'; +exports[1262] = 'ER_WARN_TOO_MANY_RECORDS'; +exports[1263] = 'ER_WARN_NULL_TO_NOTNULL'; +exports[1264] = 'ER_WARN_DATA_OUT_OF_RANGE'; +exports[1265] = 'WARN_DATA_TRUNCATED'; +exports[1266] = 'ER_WARN_USING_OTHER_HANDLER'; +exports[1267] = 'ER_CANT_AGGREGATE_2COLLATIONS'; +exports[1268] = 'ER_DROP_USER'; +exports[1269] = 'ER_REVOKE_GRANTS'; +exports[1270] = 'ER_CANT_AGGREGATE_3COLLATIONS'; +exports[1271] = 'ER_CANT_AGGREGATE_NCOLLATIONS'; +exports[1272] = 'ER_VARIABLE_IS_NOT_STRUCT'; +exports[1273] = 'ER_UNKNOWN_COLLATION'; +exports[1274] = 'ER_SLAVE_IGNORED_SSL_PARAMS'; +exports[1275] = 'ER_SERVER_IS_IN_SECURE_AUTH_MODE'; +exports[1276] = 'ER_WARN_FIELD_RESOLVED'; +exports[1277] = 'ER_BAD_SLAVE_UNTIL_COND'; +exports[1278] = 'ER_MISSING_SKIP_SLAVE'; +exports[1279] = 'ER_UNTIL_COND_IGNORED'; +exports[1280] = 'ER_WRONG_NAME_FOR_INDEX'; +exports[1281] = 'ER_WRONG_NAME_FOR_CATALOG'; +exports[1282] = 'ER_WARN_QC_RESIZE'; +exports[1283] = 'ER_BAD_FT_COLUMN'; +exports[1284] = 'ER_UNKNOWN_KEY_CACHE'; +exports[1285] = 'ER_WARN_HOSTNAME_WONT_WORK'; +exports[1286] = 'ER_UNKNOWN_STORAGE_ENGINE'; +exports[1287] = 'ER_WARN_DEPRECATED_SYNTAX'; +exports[1288] = 'ER_NON_UPDATABLE_TABLE'; +exports[1289] = 'ER_FEATURE_DISABLED'; +exports[1290] = 'ER_OPTION_PREVENTS_STATEMENT'; +exports[1291] = 'ER_DUPLICATED_VALUE_IN_TYPE'; +exports[1292] = 'ER_TRUNCATED_WRONG_VALUE'; +exports[1293] = 'ER_TOO_MUCH_AUTO_TIMESTAMP_COLS'; +exports[1294] = 'ER_INVALID_ON_UPDATE'; +exports[1295] = 'ER_UNSUPPORTED_PS'; +exports[1296] = 'ER_GET_ERRMSG'; +exports[1297] = 'ER_GET_TEMPORARY_ERRMSG'; +exports[1298] = 'ER_UNKNOWN_TIME_ZONE'; +exports[1299] = 'ER_WARN_INVALID_TIMESTAMP'; +exports[1300] = 'ER_INVALID_CHARACTER_STRING'; +exports[1301] = 'ER_WARN_ALLOWED_PACKET_OVERFLOWED'; +exports[1302] = 'ER_CONFLICTING_DECLARATIONS'; +exports[1303] = 'ER_SP_NO_RECURSIVE_CREATE'; +exports[1304] = 'ER_SP_ALREADY_EXISTS'; +exports[1305] = 'ER_SP_DOES_NOT_EXIST'; +exports[1306] = 'ER_SP_DROP_FAILED'; +exports[1307] = 'ER_SP_STORE_FAILED'; +exports[1308] = 'ER_SP_LILABEL_MISMATCH'; +exports[1309] = 'ER_SP_LABEL_REDEFINE'; +exports[1310] = 'ER_SP_LABEL_MISMATCH'; +exports[1311] = 'ER_SP_UNINIT_VAR'; +exports[1312] = 'ER_SP_BADSELECT'; +exports[1313] = 'ER_SP_BADRETURN'; +exports[1314] = 'ER_SP_BADSTATEMENT'; +exports[1315] = 'ER_UPDATE_LOG_DEPRECATED_IGNORED'; +exports[1316] = 'ER_UPDATE_LOG_DEPRECATED_TRANSLATED'; +exports[1317] = 'ER_QUERY_INTERRUPTED'; +exports[1318] = 'ER_SP_WRONG_NO_OF_ARGS'; +exports[1319] = 'ER_SP_COND_MISMATCH'; +exports[1320] = 'ER_SP_NORETURN'; +exports[1321] = 'ER_SP_NORETURNEND'; +exports[1322] = 'ER_SP_BAD_CURSOR_QUERY'; +exports[1323] = 'ER_SP_BAD_CURSOR_SELECT'; +exports[1324] = 'ER_SP_CURSOR_MISMATCH'; +exports[1325] = 'ER_SP_CURSOR_ALREADY_OPEN'; +exports[1326] = 'ER_SP_CURSOR_NOT_OPEN'; +exports[1327] = 'ER_SP_UNDECLARED_VAR'; +exports[1328] = 'ER_SP_WRONG_NO_OF_FETCH_ARGS'; +exports[1329] = 'ER_SP_FETCH_NO_DATA'; +exports[1330] = 'ER_SP_DUP_PARAM'; +exports[1331] = 'ER_SP_DUP_VAR'; +exports[1332] = 'ER_SP_DUP_COND'; +exports[1333] = 'ER_SP_DUP_CURS'; +exports[1334] = 'ER_SP_CANT_ALTER'; +exports[1335] = 'ER_SP_SUBSELECT_NYI'; +exports[1336] = 'ER_STMT_NOT_ALLOWED_IN_SF_OR_TRG'; +exports[1337] = 'ER_SP_VARCOND_AFTER_CURSHNDLR'; +exports[1338] = 'ER_SP_CURSOR_AFTER_HANDLER'; +exports[1339] = 'ER_SP_CASE_NOT_FOUND'; +exports[1340] = 'ER_FPARSER_TOO_BIG_FILE'; +exports[1341] = 'ER_FPARSER_BAD_HEADER'; +exports[1342] = 'ER_FPARSER_EOF_IN_COMMENT'; +exports[1343] = 'ER_FPARSER_ERROR_IN_PARAMETER'; +exports[1344] = 'ER_FPARSER_EOF_IN_UNKNOWN_PARAMETER'; +exports[1345] = 'ER_VIEW_NO_EXPLAIN'; +exports[1346] = 'ER_FRM_UNKNOWN_TYPE'; +exports[1347] = 'ER_WRONG_OBJECT'; +exports[1348] = 'ER_NONUPDATEABLE_COLUMN'; +exports[1349] = 'ER_VIEW_SELECT_DERIVED'; +exports[1350] = 'ER_VIEW_SELECT_CLAUSE'; +exports[1351] = 'ER_VIEW_SELECT_VARIABLE'; +exports[1352] = 'ER_VIEW_SELECT_TMPTABLE'; +exports[1353] = 'ER_VIEW_WRONG_LIST'; +exports[1354] = 'ER_WARN_VIEW_MERGE'; +exports[1355] = 'ER_WARN_VIEW_WITHOUT_KEY'; +exports[1356] = 'ER_VIEW_INVALID'; +exports[1357] = 'ER_SP_NO_DROP_SP'; +exports[1358] = 'ER_SP_GOTO_IN_HNDLR'; +exports[1359] = 'ER_TRG_ALREADY_EXISTS'; +exports[1360] = 'ER_TRG_DOES_NOT_EXIST'; +exports[1361] = 'ER_TRG_ON_VIEW_OR_TEMP_TABLE'; +exports[1362] = 'ER_TRG_CANT_CHANGE_ROW'; +exports[1363] = 'ER_TRG_NO_SUCH_ROW_IN_TRG'; +exports[1364] = 'ER_NO_DEFAULT_FOR_FIELD'; +exports[1365] = 'ER_DIVISION_BY_ZERO'; +exports[1366] = 'ER_TRUNCATED_WRONG_VALUE_FOR_FIELD'; +exports[1367] = 'ER_ILLEGAL_VALUE_FOR_TYPE'; +exports[1368] = 'ER_VIEW_NONUPD_CHECK'; +exports[1369] = 'ER_VIEW_CHECK_FAILED'; +exports[1370] = 'ER_PROCACCESS_DENIED_ERROR'; +exports[1371] = 'ER_RELAY_LOG_FAIL'; +exports[1372] = 'ER_PASSWD_LENGTH'; +exports[1373] = 'ER_UNKNOWN_TARGET_BINLOG'; +exports[1374] = 'ER_IO_ERR_LOG_INDEX_READ'; +exports[1375] = 'ER_BINLOG_PURGE_PROHIBITED'; +exports[1376] = 'ER_FSEEK_FAIL'; +exports[1377] = 'ER_BINLOG_PURGE_FATAL_ERR'; +exports[1378] = 'ER_LOG_IN_USE'; +exports[1379] = 'ER_LOG_PURGE_UNKNOWN_ERR'; +exports[1380] = 'ER_RELAY_LOG_INIT'; +exports[1381] = 'ER_NO_BINARY_LOGGING'; +exports[1382] = 'ER_RESERVED_SYNTAX'; +exports[1383] = 'ER_WSAS_FAILED'; +exports[1384] = 'ER_DIFF_GROUPS_PROC'; +exports[1385] = 'ER_NO_GROUP_FOR_PROC'; +exports[1386] = 'ER_ORDER_WITH_PROC'; +exports[1387] = 'ER_LOGGING_PROHIBIT_CHANGING_OF'; +exports[1388] = 'ER_NO_FILE_MAPPING'; +exports[1389] = 'ER_WRONG_MAGIC'; +exports[1390] = 'ER_PS_MANY_PARAM'; +exports[1391] = 'ER_KEY_PART_0'; +exports[1392] = 'ER_VIEW_CHECKSUM'; +exports[1393] = 'ER_VIEW_MULTIUPDATE'; +exports[1394] = 'ER_VIEW_NO_INSERT_FIELD_LIST'; +exports[1395] = 'ER_VIEW_DELETE_MERGE_VIEW'; +exports[1396] = 'ER_CANNOT_USER'; +exports[1397] = 'ER_XAER_NOTA'; +exports[1398] = 'ER_XAER_INVAL'; +exports[1399] = 'ER_XAER_RMFAIL'; +exports[1400] = 'ER_XAER_OUTSIDE'; +exports[1401] = 'ER_XAER_RMERR'; +exports[1402] = 'ER_XA_RBROLLBACK'; +exports[1403] = 'ER_NONEXISTING_PROC_GRANT'; +exports[1404] = 'ER_PROC_AUTO_GRANT_FAIL'; +exports[1405] = 'ER_PROC_AUTO_REVOKE_FAIL'; +exports[1406] = 'ER_DATA_TOO_LONG'; +exports[1407] = 'ER_SP_BAD_SQLSTATE'; +exports[1408] = 'ER_STARTUP'; +exports[1409] = 'ER_LOAD_FROM_FIXED_SIZE_ROWS_TO_VAR'; +exports[1410] = 'ER_CANT_CREATE_USER_WITH_GRANT'; +exports[1411] = 'ER_WRONG_VALUE_FOR_TYPE'; +exports[1412] = 'ER_TABLE_DEF_CHANGED'; +exports[1413] = 'ER_SP_DUP_HANDLER'; +exports[1414] = 'ER_SP_NOT_VAR_ARG'; +exports[1415] = 'ER_SP_NO_RETSET'; +exports[1416] = 'ER_CANT_CREATE_GEOMETRY_OBJECT'; +exports[1417] = 'ER_FAILED_ROUTINE_BREAK_BINLOG'; +exports[1418] = 'ER_BINLOG_UNSAFE_ROUTINE'; +exports[1419] = 'ER_BINLOG_CREATE_ROUTINE_NEED_SUPER'; +exports[1420] = 'ER_EXEC_STMT_WITH_OPEN_CURSOR'; +exports[1421] = 'ER_STMT_HAS_NO_OPEN_CURSOR'; +exports[1422] = 'ER_COMMIT_NOT_ALLOWED_IN_SF_OR_TRG'; +exports[1423] = 'ER_NO_DEFAULT_FOR_VIEW_FIELD'; +exports[1424] = 'ER_SP_NO_RECURSION'; +exports[1425] = 'ER_TOO_BIG_SCALE'; +exports[1426] = 'ER_TOO_BIG_PRECISION'; +exports[1427] = 'ER_M_BIGGER_THAN_D'; +exports[1428] = 'ER_WRONG_LOCK_OF_SYSTEM_TABLE'; +exports[1429] = 'ER_CONNECT_TO_FOREIGN_DATA_SOURCE'; +exports[1430] = 'ER_QUERY_ON_FOREIGN_DATA_SOURCE'; +exports[1431] = 'ER_FOREIGN_DATA_SOURCE_DOESNT_EXIST'; +exports[1432] = 'ER_FOREIGN_DATA_STRING_INVALID_CANT_CREATE'; +exports[1433] = 'ER_FOREIGN_DATA_STRING_INVALID'; +exports[1434] = 'ER_CANT_CREATE_FEDERATED_TABLE'; +exports[1435] = 'ER_TRG_IN_WRONG_SCHEMA'; +exports[1436] = 'ER_STACK_OVERRUN_NEED_MORE'; +exports[1437] = 'ER_TOO_LONG_BODY'; +exports[1438] = 'ER_WARN_CANT_DROP_DEFAULT_KEYCACHE'; +exports[1439] = 'ER_TOO_BIG_DISPLAYWIDTH'; +exports[1440] = 'ER_XAER_DUPID'; +exports[1441] = 'ER_DATETIME_FUNCTION_OVERFLOW'; +exports[1442] = 'ER_CANT_UPDATE_USED_TABLE_IN_SF_OR_TRG'; +exports[1443] = 'ER_VIEW_PREVENT_UPDATE'; +exports[1444] = 'ER_PS_NO_RECURSION'; +exports[1445] = 'ER_SP_CANT_SET_AUTOCOMMIT'; +exports[1446] = 'ER_MALFORMED_DEFINER'; +exports[1447] = 'ER_VIEW_FRM_NO_USER'; +exports[1448] = 'ER_VIEW_OTHER_USER'; +exports[1449] = 'ER_NO_SUCH_USER'; +exports[1450] = 'ER_FORBID_SCHEMA_CHANGE'; +exports[1451] = 'ER_ROW_IS_REFERENCED_2'; +exports[1452] = 'ER_NO_REFERENCED_ROW_2'; +exports[1453] = 'ER_SP_BAD_VAR_SHADOW'; +exports[1454] = 'ER_TRG_NO_DEFINER'; +exports[1455] = 'ER_OLD_FILE_FORMAT'; +exports[1456] = 'ER_SP_RECURSION_LIMIT'; +exports[1457] = 'ER_SP_PROC_TABLE_CORRUPT'; +exports[1458] = 'ER_SP_WRONG_NAME'; +exports[1459] = 'ER_TABLE_NEEDS_UPGRADE'; +exports[1460] = 'ER_SP_NO_AGGREGATE'; +exports[1461] = 'ER_MAX_PREPARED_STMT_COUNT_REACHED'; +exports[1462] = 'ER_VIEW_RECURSIVE'; +exports[1463] = 'ER_NON_GROUPING_FIELD_USED'; +exports[1464] = 'ER_TABLE_CANT_HANDLE_SPKEYS'; +exports[1465] = 'ER_NO_TRIGGERS_ON_SYSTEM_SCHEMA'; +exports[1466] = 'ER_REMOVED_SPACES'; +exports[1467] = 'ER_AUTOINC_READ_FAILED'; +exports[1468] = 'ER_USERNAME'; +exports[1469] = 'ER_HOSTNAME'; +exports[1470] = 'ER_WRONG_STRING_LENGTH'; +exports[1471] = 'ER_NON_INSERTABLE_TABLE'; +exports[1472] = 'ER_ADMIN_WRONG_MRG_TABLE'; +exports[1473] = 'ER_TOO_HIGH_LEVEL_OF_NESTING_FOR_SELECT'; +exports[1474] = 'ER_NAME_BECOMES_EMPTY'; +exports[1475] = 'ER_AMBIGUOUS_FIELD_TERM'; +exports[1476] = 'ER_FOREIGN_SERVER_EXISTS'; +exports[1477] = 'ER_FOREIGN_SERVER_DOESNT_EXIST'; +exports[1478] = 'ER_ILLEGAL_HA_CREATE_OPTION'; +exports[1479] = 'ER_PARTITION_REQUIRES_VALUES_ERROR'; +exports[1480] = 'ER_PARTITION_WRONG_VALUES_ERROR'; +exports[1481] = 'ER_PARTITION_MAXVALUE_ERROR'; +exports[1482] = 'ER_PARTITION_SUBPARTITION_ERROR'; +exports[1483] = 'ER_PARTITION_SUBPART_MIX_ERROR'; +exports[1484] = 'ER_PARTITION_WRONG_NO_PART_ERROR'; +exports[1485] = 'ER_PARTITION_WRONG_NO_SUBPART_ERROR'; +exports[1486] = 'ER_WRONG_EXPR_IN_PARTITION_FUNC_ERROR'; +exports[1487] = 'ER_NO_CONST_EXPR_IN_RANGE_OR_LIST_ERROR'; +exports[1488] = 'ER_FIELD_NOT_FOUND_PART_ERROR'; +exports[1489] = 'ER_LIST_OF_FIELDS_ONLY_IN_HASH_ERROR'; +exports[1490] = 'ER_INCONSISTENT_PARTITION_INFO_ERROR'; +exports[1491] = 'ER_PARTITION_FUNC_NOT_ALLOWED_ERROR'; +exports[1492] = 'ER_PARTITIONS_MUST_BE_DEFINED_ERROR'; +exports[1493] = 'ER_RANGE_NOT_INCREASING_ERROR'; +exports[1494] = 'ER_INCONSISTENT_TYPE_OF_FUNCTIONS_ERROR'; +exports[1495] = 'ER_MULTIPLE_DEF_CONST_IN_LIST_PART_ERROR'; +exports[1496] = 'ER_PARTITION_ENTRY_ERROR'; +exports[1497] = 'ER_MIX_HANDLER_ERROR'; +exports[1498] = 'ER_PARTITION_NOT_DEFINED_ERROR'; +exports[1499] = 'ER_TOO_MANY_PARTITIONS_ERROR'; +exports[1500] = 'ER_SUBPARTITION_ERROR'; +exports[1501] = 'ER_CANT_CREATE_HANDLER_FILE'; +exports[1502] = 'ER_BLOB_FIELD_IN_PART_FUNC_ERROR'; +exports[1503] = 'ER_UNIQUE_KEY_NEED_ALL_FIELDS_IN_PF'; +exports[1504] = 'ER_NO_PARTS_ERROR'; +exports[1505] = 'ER_PARTITION_MGMT_ON_NONPARTITIONED'; +exports[1506] = 'ER_FOREIGN_KEY_ON_PARTITIONED'; +exports[1507] = 'ER_DROP_PARTITION_NON_EXISTENT'; +exports[1508] = 'ER_DROP_LAST_PARTITION'; +exports[1509] = 'ER_COALESCE_ONLY_ON_HASH_PARTITION'; +exports[1510] = 'ER_REORG_HASH_ONLY_ON_SAME_NO'; +exports[1511] = 'ER_REORG_NO_PARAM_ERROR'; +exports[1512] = 'ER_ONLY_ON_RANGE_LIST_PARTITION'; +exports[1513] = 'ER_ADD_PARTITION_SUBPART_ERROR'; +exports[1514] = 'ER_ADD_PARTITION_NO_NEW_PARTITION'; +exports[1515] = 'ER_COALESCE_PARTITION_NO_PARTITION'; +exports[1516] = 'ER_REORG_PARTITION_NOT_EXIST'; +exports[1517] = 'ER_SAME_NAME_PARTITION'; +exports[1518] = 'ER_NO_BINLOG_ERROR'; +exports[1519] = 'ER_CONSECUTIVE_REORG_PARTITIONS'; +exports[1520] = 'ER_REORG_OUTSIDE_RANGE'; +exports[1521] = 'ER_PARTITION_FUNCTION_FAILURE'; +exports[1522] = 'ER_PART_STATE_ERROR'; +exports[1523] = 'ER_LIMITED_PART_RANGE'; +exports[1524] = 'ER_PLUGIN_IS_NOT_LOADED'; +exports[1525] = 'ER_WRONG_VALUE'; +exports[1526] = 'ER_NO_PARTITION_FOR_GIVEN_VALUE'; +exports[1527] = 'ER_FILEGROUP_OPTION_ONLY_ONCE'; +exports[1528] = 'ER_CREATE_FILEGROUP_FAILED'; +exports[1529] = 'ER_DROP_FILEGROUP_FAILED'; +exports[1530] = 'ER_TABLESPACE_AUTO_EXTEND_ERROR'; +exports[1531] = 'ER_WRONG_SIZE_NUMBER'; +exports[1532] = 'ER_SIZE_OVERFLOW_ERROR'; +exports[1533] = 'ER_ALTER_FILEGROUP_FAILED'; +exports[1534] = 'ER_BINLOG_ROW_LOGGING_FAILED'; +exports[1535] = 'ER_BINLOG_ROW_WRONG_TABLE_DEF'; +exports[1536] = 'ER_BINLOG_ROW_RBR_TO_SBR'; +exports[1537] = 'ER_EVENT_ALREADY_EXISTS'; +exports[1538] = 'ER_EVENT_STORE_FAILED'; +exports[1539] = 'ER_EVENT_DOES_NOT_EXIST'; +exports[1540] = 'ER_EVENT_CANT_ALTER'; +exports[1541] = 'ER_EVENT_DROP_FAILED'; +exports[1542] = 'ER_EVENT_INTERVAL_NOT_POSITIVE_OR_TOO_BIG'; +exports[1543] = 'ER_EVENT_ENDS_BEFORE_STARTS'; +exports[1544] = 'ER_EVENT_EXEC_TIME_IN_THE_PAST'; +exports[1545] = 'ER_EVENT_OPEN_TABLE_FAILED'; +exports[1546] = 'ER_EVENT_NEITHER_M_EXPR_NOR_M_AT'; +exports[1547] = 'ER_COL_COUNT_DOESNT_MATCH_CORRUPTED'; +exports[1548] = 'ER_CANNOT_LOAD_FROM_TABLE'; +exports[1549] = 'ER_EVENT_CANNOT_DELETE'; +exports[1550] = 'ER_EVENT_COMPILE_ERROR'; +exports[1551] = 'ER_EVENT_SAME_NAME'; +exports[1552] = 'ER_EVENT_DATA_TOO_LONG'; +exports[1553] = 'ER_DROP_INDEX_FK'; +exports[1554] = 'ER_WARN_DEPRECATED_SYNTAX_WITH_VER'; +exports[1555] = 'ER_CANT_WRITE_LOCK_LOG_TABLE'; +exports[1556] = 'ER_CANT_LOCK_LOG_TABLE'; +exports[1557] = 'ER_FOREIGN_DUPLICATE_KEY'; +exports[1558] = 'ER_COL_COUNT_DOESNT_MATCH_PLEASE_UPDATE'; +exports[1559] = 'ER_TEMP_TABLE_PREVENTS_SWITCH_OUT_OF_RBR'; +exports[1560] = 'ER_STORED_FUNCTION_PREVENTS_SWITCH_BINLOG_FORMAT'; +exports[1561] = 'ER_NDB_CANT_SWITCH_BINLOG_FORMAT'; +exports[1562] = 'ER_PARTITION_NO_TEMPORARY'; +exports[1563] = 'ER_PARTITION_CONST_DOMAIN_ERROR'; +exports[1564] = 'ER_PARTITION_FUNCTION_IS_NOT_ALLOWED'; +exports[1565] = 'ER_DDL_LOG_ERROR'; +exports[1566] = 'ER_NULL_IN_VALUES_LESS_THAN'; +exports[1567] = 'ER_WRONG_PARTITION_NAME'; +exports[1568] = 'ER_CANT_CHANGE_TX_CHARACTERISTICS'; +exports[1569] = 'ER_DUP_ENTRY_AUTOINCREMENT_CASE'; +exports[1570] = 'ER_EVENT_MODIFY_QUEUE_ERROR'; +exports[1571] = 'ER_EVENT_SET_VAR_ERROR'; +exports[1572] = 'ER_PARTITION_MERGE_ERROR'; +exports[1573] = 'ER_CANT_ACTIVATE_LOG'; +exports[1574] = 'ER_RBR_NOT_AVAILABLE'; +exports[1575] = 'ER_BASE64_DECODE_ERROR'; +exports[1576] = 'ER_EVENT_RECURSION_FORBIDDEN'; +exports[1577] = 'ER_EVENTS_DB_ERROR'; +exports[1578] = 'ER_ONLY_INTEGERS_ALLOWED'; +exports[1579] = 'ER_UNSUPORTED_LOG_ENGINE'; +exports[1580] = 'ER_BAD_LOG_STATEMENT'; +exports[1581] = 'ER_CANT_RENAME_LOG_TABLE'; +exports[1582] = 'ER_WRONG_PARAMCOUNT_TO_NATIVE_FCT'; +exports[1583] = 'ER_WRONG_PARAMETERS_TO_NATIVE_FCT'; +exports[1584] = 'ER_WRONG_PARAMETERS_TO_STORED_FCT'; +exports[1585] = 'ER_NATIVE_FCT_NAME_COLLISION'; +exports[1586] = 'ER_DUP_ENTRY_WITH_KEY_NAME'; +exports[1587] = 'ER_BINLOG_PURGE_EMFILE'; +exports[1588] = 'ER_EVENT_CANNOT_CREATE_IN_THE_PAST'; +exports[1589] = 'ER_EVENT_CANNOT_ALTER_IN_THE_PAST'; +exports[1590] = 'ER_SLAVE_INCIDENT'; +exports[1591] = 'ER_NO_PARTITION_FOR_GIVEN_VALUE_SILENT'; +exports[1592] = 'ER_BINLOG_UNSAFE_STATEMENT'; +exports[1593] = 'ER_SLAVE_FATAL_ERROR'; +exports[1594] = 'ER_SLAVE_RELAY_LOG_READ_FAILURE'; +exports[1595] = 'ER_SLAVE_RELAY_LOG_WRITE_FAILURE'; +exports[1596] = 'ER_SLAVE_CREATE_EVENT_FAILURE'; +exports[1597] = 'ER_SLAVE_MASTER_COM_FAILURE'; +exports[1598] = 'ER_BINLOG_LOGGING_IMPOSSIBLE'; +exports[1599] = 'ER_VIEW_NO_CREATION_CTX'; +exports[1600] = 'ER_VIEW_INVALID_CREATION_CTX'; +exports[1601] = 'ER_SR_INVALID_CREATION_CTX'; +exports[1602] = 'ER_TRG_CORRUPTED_FILE'; +exports[1603] = 'ER_TRG_NO_CREATION_CTX'; +exports[1604] = 'ER_TRG_INVALID_CREATION_CTX'; +exports[1605] = 'ER_EVENT_INVALID_CREATION_CTX'; +exports[1606] = 'ER_TRG_CANT_OPEN_TABLE'; +exports[1607] = 'ER_CANT_CREATE_SROUTINE'; +exports[1608] = 'ER_NEVER_USED'; +exports[1609] = 'ER_NO_FORMAT_DESCRIPTION_EVENT_BEFORE_BINLOG_STATEMENT'; +exports[1610] = 'ER_SLAVE_CORRUPT_EVENT'; +exports[1611] = 'ER_LOAD_DATA_INVALID_COLUMN'; +exports[1612] = 'ER_LOG_PURGE_NO_FILE'; +exports[1613] = 'ER_XA_RBTIMEOUT'; +exports[1614] = 'ER_XA_RBDEADLOCK'; +exports[1615] = 'ER_NEED_REPREPARE'; +exports[1616] = 'ER_DELAYED_NOT_SUPPORTED'; +exports[1617] = 'WARN_NO_MASTER_INFO'; +exports[1618] = 'WARN_OPTION_IGNORED'; +exports[1619] = 'ER_PLUGIN_DELETE_BUILTIN'; +exports[1620] = 'WARN_PLUGIN_BUSY'; +exports[1621] = 'ER_VARIABLE_IS_READONLY'; +exports[1622] = 'ER_WARN_ENGINE_TRANSACTION_ROLLBACK'; +exports[1623] = 'ER_SLAVE_HEARTBEAT_FAILURE'; +exports[1624] = 'ER_SLAVE_HEARTBEAT_VALUE_OUT_OF_RANGE'; +exports[1625] = 'ER_NDB_REPLICATION_SCHEMA_ERROR'; +exports[1626] = 'ER_CONFLICT_FN_PARSE_ERROR'; +exports[1627] = 'ER_EXCEPTIONS_WRITE_ERROR'; +exports[1628] = 'ER_TOO_LONG_TABLE_COMMENT'; +exports[1629] = 'ER_TOO_LONG_FIELD_COMMENT'; +exports[1630] = 'ER_FUNC_INEXISTENT_NAME_COLLISION'; +exports[1631] = 'ER_DATABASE_NAME'; +exports[1632] = 'ER_TABLE_NAME'; +exports[1633] = 'ER_PARTITION_NAME'; +exports[1634] = 'ER_SUBPARTITION_NAME'; +exports[1635] = 'ER_TEMPORARY_NAME'; +exports[1636] = 'ER_RENAMED_NAME'; +exports[1637] = 'ER_TOO_MANY_CONCURRENT_TRXS'; +exports[1638] = 'WARN_NON_ASCII_SEPARATOR_NOT_IMPLEMENTED'; +exports[1639] = 'ER_DEBUG_SYNC_TIMEOUT'; +exports[1640] = 'ER_DEBUG_SYNC_HIT_LIMIT'; +exports[1641] = 'ER_DUP_SIGNAL_SET'; +exports[1642] = 'ER_SIGNAL_WARN'; +exports[1643] = 'ER_SIGNAL_NOT_FOUND'; +exports[1644] = 'ER_SIGNAL_EXCEPTION'; +exports[1645] = 'ER_RESIGNAL_WITHOUT_ACTIVE_HANDLER'; +exports[1646] = 'ER_SIGNAL_BAD_CONDITION_TYPE'; +exports[1647] = 'WARN_COND_ITEM_TRUNCATED'; +exports[1648] = 'ER_COND_ITEM_TOO_LONG'; +exports[1649] = 'ER_UNKNOWN_LOCALE'; +exports[1650] = 'ER_SLAVE_IGNORE_SERVER_IDS'; +exports[1651] = 'ER_QUERY_CACHE_DISABLED'; +exports[1652] = 'ER_SAME_NAME_PARTITION_FIELD'; +exports[1653] = 'ER_PARTITION_COLUMN_LIST_ERROR'; +exports[1654] = 'ER_WRONG_TYPE_COLUMN_VALUE_ERROR'; +exports[1655] = 'ER_TOO_MANY_PARTITION_FUNC_FIELDS_ERROR'; +exports[1656] = 'ER_MAXVALUE_IN_VALUES_IN'; +exports[1657] = 'ER_TOO_MANY_VALUES_ERROR'; +exports[1658] = 'ER_ROW_SINGLE_PARTITION_FIELD_ERROR'; +exports[1659] = 'ER_FIELD_TYPE_NOT_ALLOWED_AS_PARTITION_FIELD'; +exports[1660] = 'ER_PARTITION_FIELDS_TOO_LONG'; +exports[1661] = 'ER_BINLOG_ROW_ENGINE_AND_STMT_ENGINE'; +exports[1662] = 'ER_BINLOG_ROW_MODE_AND_STMT_ENGINE'; +exports[1663] = 'ER_BINLOG_UNSAFE_AND_STMT_ENGINE'; +exports[1664] = 'ER_BINLOG_ROW_INJECTION_AND_STMT_ENGINE'; +exports[1665] = 'ER_BINLOG_STMT_MODE_AND_ROW_ENGINE'; +exports[1666] = 'ER_BINLOG_ROW_INJECTION_AND_STMT_MODE'; +exports[1667] = 'ER_BINLOG_MULTIPLE_ENGINES_AND_SELF_LOGGING_ENGINE'; +exports[1668] = 'ER_BINLOG_UNSAFE_LIMIT'; +exports[1669] = 'ER_BINLOG_UNSAFE_INSERT_DELAYED'; +exports[1670] = 'ER_BINLOG_UNSAFE_SYSTEM_TABLE'; +exports[1671] = 'ER_BINLOG_UNSAFE_AUTOINC_COLUMNS'; +exports[1672] = 'ER_BINLOG_UNSAFE_UDF'; +exports[1673] = 'ER_BINLOG_UNSAFE_SYSTEM_VARIABLE'; +exports[1674] = 'ER_BINLOG_UNSAFE_SYSTEM_FUNCTION'; +exports[1675] = 'ER_BINLOG_UNSAFE_NONTRANS_AFTER_TRANS'; +exports[1676] = 'ER_MESSAGE_AND_STATEMENT'; +exports[1677] = 'ER_SLAVE_CONVERSION_FAILED'; +exports[1678] = 'ER_SLAVE_CANT_CREATE_CONVERSION'; +exports[1679] = 'ER_INSIDE_TRANSACTION_PREVENTS_SWITCH_BINLOG_FORMAT'; +exports[1680] = 'ER_PATH_LENGTH'; +exports[1681] = 'ER_WARN_DEPRECATED_SYNTAX_NO_REPLACEMENT'; +exports[1682] = 'ER_WRONG_NATIVE_TABLE_STRUCTURE'; +exports[1683] = 'ER_WRONG_PERFSCHEMA_USAGE'; +exports[1684] = 'ER_WARN_I_S_SKIPPED_TABLE'; +exports[1685] = 'ER_INSIDE_TRANSACTION_PREVENTS_SWITCH_BINLOG_DIRECT'; +exports[1686] = 'ER_STORED_FUNCTION_PREVENTS_SWITCH_BINLOG_DIRECT'; +exports[1687] = 'ER_SPATIAL_MUST_HAVE_GEOM_COL'; +exports[1688] = 'ER_TOO_LONG_INDEX_COMMENT'; +exports[1689] = 'ER_LOCK_ABORTED'; +exports[1690] = 'ER_DATA_OUT_OF_RANGE'; +exports[1691] = 'ER_WRONG_SPVAR_TYPE_IN_LIMIT'; +exports[1692] = 'ER_BINLOG_UNSAFE_MULTIPLE_ENGINES_AND_SELF_LOGGING_ENGINE'; +exports[1693] = 'ER_BINLOG_UNSAFE_MIXED_STATEMENT'; +exports[1694] = 'ER_INSIDE_TRANSACTION_PREVENTS_SWITCH_SQL_LOG_BIN'; +exports[1695] = 'ER_STORED_FUNCTION_PREVENTS_SWITCH_SQL_LOG_BIN'; +exports[1696] = 'ER_FAILED_READ_FROM_PAR_FILE'; +exports[1697] = 'ER_VALUES_IS_NOT_INT_TYPE_ERROR'; +exports[1698] = 'ER_ACCESS_DENIED_NO_PASSWORD_ERROR'; +exports[1699] = 'ER_SET_PASSWORD_AUTH_PLUGIN'; +exports[1700] = 'ER_GRANT_PLUGIN_USER_EXISTS'; +exports[1701] = 'ER_TRUNCATE_ILLEGAL_FK'; +exports[1702] = 'ER_PLUGIN_IS_PERMANENT'; +exports[1703] = 'ER_SLAVE_HEARTBEAT_VALUE_OUT_OF_RANGE_MIN'; +exports[1704] = 'ER_SLAVE_HEARTBEAT_VALUE_OUT_OF_RANGE_MAX'; +exports[1705] = 'ER_STMT_CACHE_FULL'; +exports[1706] = 'ER_MULTI_UPDATE_KEY_CONFLICT'; +exports[1707] = 'ER_TABLE_NEEDS_REBUILD'; +exports[1708] = 'WARN_OPTION_BELOW_LIMIT'; +exports[1709] = 'ER_INDEX_COLUMN_TOO_LONG'; +exports[1710] = 'ER_ERROR_IN_TRIGGER_BODY'; +exports[1711] = 'ER_ERROR_IN_UNKNOWN_TRIGGER_BODY'; +exports[1712] = 'ER_INDEX_CORRUPT'; +exports[1713] = 'ER_UNDO_RECORD_TOO_BIG'; +exports[1714] = 'ER_BINLOG_UNSAFE_INSERT_IGNORE_SELECT'; +exports[1715] = 'ER_BINLOG_UNSAFE_INSERT_SELECT_UPDATE'; +exports[1716] = 'ER_BINLOG_UNSAFE_REPLACE_SELECT'; +exports[1717] = 'ER_BINLOG_UNSAFE_CREATE_IGNORE_SELECT'; +exports[1718] = 'ER_BINLOG_UNSAFE_CREATE_REPLACE_SELECT'; +exports[1719] = 'ER_BINLOG_UNSAFE_UPDATE_IGNORE'; +exports[1720] = 'ER_PLUGIN_NO_UNINSTALL'; +exports[1721] = 'ER_PLUGIN_NO_INSTALL'; +exports[1722] = 'ER_BINLOG_UNSAFE_WRITE_AUTOINC_SELECT'; +exports[1723] = 'ER_BINLOG_UNSAFE_CREATE_SELECT_AUTOINC'; +exports[1724] = 'ER_BINLOG_UNSAFE_INSERT_TWO_KEYS'; +exports[1725] = 'ER_TABLE_IN_FK_CHECK'; +exports[1726] = 'ER_UNSUPPORTED_ENGINE'; +exports[1727] = 'ER_BINLOG_UNSAFE_AUTOINC_NOT_FIRST'; +exports[1728] = 'ER_CANNOT_LOAD_FROM_TABLE_V2'; +exports[1729] = 'ER_MASTER_DELAY_VALUE_OUT_OF_RANGE'; +exports[1730] = 'ER_ONLY_FD_AND_RBR_EVENTS_ALLOWED_IN_BINLOG_STATEMENT'; +exports[1731] = 'ER_PARTITION_EXCHANGE_DIFFERENT_OPTION'; +exports[1732] = 'ER_PARTITION_EXCHANGE_PART_TABLE'; +exports[1733] = 'ER_PARTITION_EXCHANGE_TEMP_TABLE'; +exports[1734] = 'ER_PARTITION_INSTEAD_OF_SUBPARTITION'; +exports[1735] = 'ER_UNKNOWN_PARTITION'; +exports[1736] = 'ER_TABLES_DIFFERENT_METADATA'; +exports[1737] = 'ER_ROW_DOES_NOT_MATCH_PARTITION'; +exports[1738] = 'ER_BINLOG_CACHE_SIZE_GREATER_THAN_MAX'; +exports[1739] = 'ER_WARN_INDEX_NOT_APPLICABLE'; +exports[1740] = 'ER_PARTITION_EXCHANGE_FOREIGN_KEY'; +exports[1741] = 'ER_NO_SUCH_KEY_VALUE'; +exports[1742] = 'ER_RPL_INFO_DATA_TOO_LONG'; +exports[1743] = 'ER_NETWORK_READ_EVENT_CHECKSUM_FAILURE'; +exports[1744] = 'ER_BINLOG_READ_EVENT_CHECKSUM_FAILURE'; +exports[1745] = 'ER_BINLOG_STMT_CACHE_SIZE_GREATER_THAN_MAX'; +exports[1746] = 'ER_CANT_UPDATE_TABLE_IN_CREATE_TABLE_SELECT'; +exports[1747] = 'ER_PARTITION_CLAUSE_ON_NONPARTITIONED'; +exports[1748] = 'ER_ROW_DOES_NOT_MATCH_GIVEN_PARTITION_SET'; +exports[1749] = 'ER_NO_SUCH_PARTITION'; +exports[1750] = 'ER_CHANGE_RPL_INFO_REPOSITORY_FAILURE'; +exports[1751] = 'ER_WARNING_NOT_COMPLETE_ROLLBACK_WITH_CREATED_TEMP_TABLE'; +exports[1752] = 'ER_WARNING_NOT_COMPLETE_ROLLBACK_WITH_DROPPED_TEMP_TABLE'; +exports[1753] = 'ER_MTS_FEATURE_IS_NOT_SUPPORTED'; +exports[1754] = 'ER_MTS_UPDATED_DBS_GREATER_MAX'; +exports[1755] = 'ER_MTS_CANT_PARALLEL'; +exports[1756] = 'ER_MTS_INCONSISTENT_DATA'; +exports[1757] = 'ER_FULLTEXT_NOT_SUPPORTED_WITH_PARTITIONING'; +exports[1758] = 'ER_DA_INVALID_CONDITION_NUMBER'; +exports[1759] = 'ER_INSECURE_PLAIN_TEXT'; +exports[1760] = 'ER_INSECURE_CHANGE_MASTER'; +exports[1761] = 'ER_FOREIGN_DUPLICATE_KEY_WITH_CHILD_INFO'; +exports[1762] = 'ER_FOREIGN_DUPLICATE_KEY_WITHOUT_CHILD_INFO'; +exports[1763] = 'ER_SQLTHREAD_WITH_SECURE_SLAVE'; +exports[1764] = 'ER_TABLE_HAS_NO_FT'; +exports[1765] = 'ER_VARIABLE_NOT_SETTABLE_IN_SF_OR_TRIGGER'; +exports[1766] = 'ER_VARIABLE_NOT_SETTABLE_IN_TRANSACTION'; +exports[1767] = 'ER_GTID_NEXT_IS_NOT_IN_GTID_NEXT_LIST'; +exports[1768] = 'ER_CANT_CHANGE_GTID_NEXT_IN_TRANSACTION'; +exports[1769] = 'ER_SET_STATEMENT_CANNOT_INVOKE_FUNCTION'; +exports[1770] = 'ER_GTID_NEXT_CANT_BE_AUTOMATIC_IF_GTID_NEXT_LIST_IS_NON_NULL'; +exports[1771] = 'ER_SKIPPING_LOGGED_TRANSACTION'; +exports[1772] = 'ER_MALFORMED_GTID_SET_SPECIFICATION'; +exports[1773] = 'ER_MALFORMED_GTID_SET_ENCODING'; +exports[1774] = 'ER_MALFORMED_GTID_SPECIFICATION'; +exports[1775] = 'ER_GNO_EXHAUSTED'; +exports[1776] = 'ER_BAD_SLAVE_AUTO_POSITION'; +exports[1777] = 'ER_AUTO_POSITION_REQUIRES_GTID_MODE_NOT_OFF'; +exports[1778] = 'ER_CANT_DO_IMPLICIT_COMMIT_IN_TRX_WHEN_GTID_NEXT_IS_SET'; +exports[1779] = 'ER_GTID_MODE_ON_REQUIRES_ENFORCE_GTID_CONSISTENCY_ON'; +exports[1780] = 'ER_GTID_MODE_REQUIRES_BINLOG'; +exports[1781] = 'ER_CANT_SET_GTID_NEXT_TO_GTID_WHEN_GTID_MODE_IS_OFF'; +exports[1782] = 'ER_CANT_SET_GTID_NEXT_TO_ANONYMOUS_WHEN_GTID_MODE_IS_ON'; +exports[1783] = 'ER_CANT_SET_GTID_NEXT_LIST_TO_NON_NULL_WHEN_GTID_MODE_IS_OFF'; +exports[1784] = 'ER_FOUND_GTID_EVENT_WHEN_GTID_MODE_IS_OFF'; +exports[1785] = 'ER_GTID_UNSAFE_NON_TRANSACTIONAL_TABLE'; +exports[1786] = 'ER_GTID_UNSAFE_CREATE_SELECT'; +exports[1787] = 'ER_GTID_UNSAFE_CREATE_DROP_TEMPORARY_TABLE_IN_TRANSACTION'; +exports[1788] = 'ER_GTID_MODE_CAN_ONLY_CHANGE_ONE_STEP_AT_A_TIME'; +exports[1789] = 'ER_MASTER_HAS_PURGED_REQUIRED_GTIDS'; +exports[1790] = 'ER_CANT_SET_GTID_NEXT_WHEN_OWNING_GTID'; +exports[1791] = 'ER_UNKNOWN_EXPLAIN_FORMAT'; +exports[1792] = 'ER_CANT_EXECUTE_IN_READ_ONLY_TRANSACTION'; +exports[1793] = 'ER_TOO_LONG_TABLE_PARTITION_COMMENT'; +exports[1794] = 'ER_SLAVE_CONFIGURATION'; +exports[1795] = 'ER_INNODB_FT_LIMIT'; +exports[1796] = 'ER_INNODB_NO_FT_TEMP_TABLE'; +exports[1797] = 'ER_INNODB_FT_WRONG_DOCID_COLUMN'; +exports[1798] = 'ER_INNODB_FT_WRONG_DOCID_INDEX'; +exports[1799] = 'ER_INNODB_ONLINE_LOG_TOO_BIG'; +exports[1800] = 'ER_UNKNOWN_ALTER_ALGORITHM'; +exports[1801] = 'ER_UNKNOWN_ALTER_LOCK'; +exports[1802] = 'ER_MTS_CHANGE_MASTER_CANT_RUN_WITH_GAPS'; +exports[1803] = 'ER_MTS_RECOVERY_FAILURE'; +exports[1804] = 'ER_MTS_RESET_WORKERS'; +exports[1805] = 'ER_COL_COUNT_DOESNT_MATCH_CORRUPTED_V2'; +exports[1806] = 'ER_SLAVE_SILENT_RETRY_TRANSACTION'; +exports[1807] = 'ER_DISCARD_FK_CHECKS_RUNNING'; +exports[1808] = 'ER_TABLE_SCHEMA_MISMATCH'; +exports[1809] = 'ER_TABLE_IN_SYSTEM_TABLESPACE'; +exports[1810] = 'ER_IO_READ_ERROR'; +exports[1811] = 'ER_IO_WRITE_ERROR'; +exports[1812] = 'ER_TABLESPACE_MISSING'; +exports[1813] = 'ER_TABLESPACE_EXISTS'; +exports[1814] = 'ER_TABLESPACE_DISCARDED'; +exports[1815] = 'ER_INTERNAL_ERROR'; +exports[1816] = 'ER_INNODB_IMPORT_ERROR'; +exports[1817] = 'ER_INNODB_INDEX_CORRUPT'; +exports[1818] = 'ER_INVALID_YEAR_COLUMN_LENGTH'; +exports[1819] = 'ER_NOT_VALID_PASSWORD'; +exports[1820] = 'ER_MUST_CHANGE_PASSWORD'; +exports[1821] = 'ER_FK_NO_INDEX_CHILD'; +exports[1822] = 'ER_FK_NO_INDEX_PARENT'; +exports[1823] = 'ER_FK_FAIL_ADD_SYSTEM'; +exports[1824] = 'ER_FK_CANNOT_OPEN_PARENT'; +exports[1825] = 'ER_FK_INCORRECT_OPTION'; +exports[1826] = 'ER_FK_DUP_NAME'; +exports[1827] = 'ER_PASSWORD_FORMAT'; +exports[1828] = 'ER_FK_COLUMN_CANNOT_DROP'; +exports[1829] = 'ER_FK_COLUMN_CANNOT_DROP_CHILD'; +exports[1830] = 'ER_FK_COLUMN_NOT_NULL'; +exports[1831] = 'ER_DUP_INDEX'; +exports[1832] = 'ER_FK_COLUMN_CANNOT_CHANGE'; +exports[1833] = 'ER_FK_COLUMN_CANNOT_CHANGE_CHILD'; +exports[1834] = 'ER_FK_CANNOT_DELETE_PARENT'; +exports[1835] = 'ER_MALFORMED_PACKET'; +exports[1836] = 'ER_READ_ONLY_MODE'; +exports[1837] = 'ER_GTID_NEXT_TYPE_UNDEFINED_GROUP'; +exports[1838] = 'ER_VARIABLE_NOT_SETTABLE_IN_SP'; +exports[1839] = 'ER_CANT_SET_GTID_PURGED_WHEN_GTID_MODE_IS_OFF'; +exports[1840] = 'ER_CANT_SET_GTID_PURGED_WHEN_GTID_EXECUTED_IS_NOT_EMPTY'; +exports[1841] = 'ER_CANT_SET_GTID_PURGED_WHEN_OWNED_GTIDS_IS_NOT_EMPTY'; +exports[1842] = 'ER_GTID_PURGED_WAS_CHANGED'; +exports[1843] = 'ER_GTID_EXECUTED_WAS_CHANGED'; +exports[1844] = 'ER_BINLOG_STMT_MODE_AND_NO_REPL_TABLES'; +exports[1845] = 'ER_ALTER_OPERATION_NOT_SUPPORTED'; +exports[1846] = 'ER_ALTER_OPERATION_NOT_SUPPORTED_REASON'; +exports[1847] = 'ER_ALTER_OPERATION_NOT_SUPPORTED_REASON_COPY'; +exports[1848] = 'ER_ALTER_OPERATION_NOT_SUPPORTED_REASON_PARTITION'; +exports[1849] = 'ER_ALTER_OPERATION_NOT_SUPPORTED_REASON_FK_RENAME'; +exports[1850] = 'ER_ALTER_OPERATION_NOT_SUPPORTED_REASON_COLUMN_TYPE'; +exports[1851] = 'ER_ALTER_OPERATION_NOT_SUPPORTED_REASON_FK_CHECK'; +exports[1852] = 'ER_ALTER_OPERATION_NOT_SUPPORTED_REASON_IGNORE'; +exports[1853] = 'ER_ALTER_OPERATION_NOT_SUPPORTED_REASON_NOPK'; +exports[1854] = 'ER_ALTER_OPERATION_NOT_SUPPORTED_REASON_AUTOINC'; +exports[1855] = 'ER_ALTER_OPERATION_NOT_SUPPORTED_REASON_HIDDEN_FTS'; +exports[1856] = 'ER_ALTER_OPERATION_NOT_SUPPORTED_REASON_CHANGE_FTS'; +exports[1857] = 'ER_ALTER_OPERATION_NOT_SUPPORTED_REASON_FTS'; +exports[1858] = 'ER_SQL_SLAVE_SKIP_COUNTER_NOT_SETTABLE_IN_GTID_MODE'; +exports[1859] = 'ER_DUP_UNKNOWN_IN_INDEX'; +exports[1860] = 'ER_IDENT_CAUSES_TOO_LONG_PATH'; +exports[1861] = 'ER_ALTER_OPERATION_NOT_SUPPORTED_REASON_NOT_NULL'; +exports[1862] = 'ER_MUST_CHANGE_PASSWORD_LOGIN'; +exports[1863] = 'ER_ROW_IN_WRONG_PARTITION'; +exports[1864] = 'ER_MTS_EVENT_BIGGER_PENDING_JOBS_SIZE_MAX'; +exports[1865] = 'ER_INNODB_NO_FT_USES_PARSER'; +exports[1866] = 'ER_BINLOG_LOGICAL_CORRUPTION'; +exports[1867] = 'ER_WARN_PURGE_LOG_IN_USE'; +exports[1868] = 'ER_WARN_PURGE_LOG_IS_ACTIVE'; +exports[1869] = 'ER_AUTO_INCREMENT_CONFLICT'; +exports[1870] = 'WARN_ON_BLOCKHOLE_IN_RBR'; +exports[1871] = 'ER_SLAVE_MI_INIT_REPOSITORY'; +exports[1872] = 'ER_SLAVE_RLI_INIT_REPOSITORY'; +exports[1873] = 'ER_ACCESS_DENIED_CHANGE_USER_ERROR'; +exports[1874] = 'ER_INNODB_READ_ONLY'; +exports[1875] = 'ER_STOP_SLAVE_SQL_THREAD_TIMEOUT'; +exports[1876] = 'ER_STOP_SLAVE_IO_THREAD_TIMEOUT'; +exports[1877] = 'ER_TABLE_CORRUPT'; +exports[1878] = 'ER_TEMP_FILE_WRITE_FAILURE'; +exports[1879] = 'ER_INNODB_FT_AUX_NOT_HEX_ID'; +exports[1880] = 'ER_OLD_TEMPORALS_UPGRADED'; +exports[1881] = 'ER_INNODB_FORCED_RECOVERY'; +exports[1882] = 'ER_AES_INVALID_IV'; +exports[1883] = 'ER_PLUGIN_CANNOT_BE_UNINSTALLED'; +exports[1884] = 'ER_GTID_UNSAFE_BINLOG_SPLITTABLE_STATEMENT_AND_GTID_GROUP'; +exports[1885] = 'ER_SLAVE_HAS_MORE_GTIDS_THAN_MASTER'; +exports[1886] = 'ER_MISSING_KEY'; +exports[1887] = 'WARN_NAMED_PIPE_ACCESS_EVERYONE'; +exports[1888] = 'ER_FOUND_MISSING_GTIDS'; +exports[3000] = 'ER_FILE_CORRUPT'; +exports[3001] = 'ER_ERROR_ON_MASTER'; +exports[3002] = 'ER_INCONSISTENT_ERROR'; +exports[3003] = 'ER_STORAGE_ENGINE_NOT_LOADED'; +exports[3004] = 'ER_GET_STACKED_DA_WITHOUT_ACTIVE_HANDLER'; +exports[3005] = 'ER_WARN_LEGACY_SYNTAX_CONVERTED'; +exports[3006] = 'ER_BINLOG_UNSAFE_FULLTEXT_PLUGIN'; +exports[3007] = 'ER_CANNOT_DISCARD_TEMPORARY_TABLE'; +exports[3008] = 'ER_FK_DEPTH_EXCEEDED'; +exports[3009] = 'ER_COL_COUNT_DOESNT_MATCH_PLEASE_UPDATE_V2'; +exports[3010] = 'ER_WARN_TRIGGER_DOESNT_HAVE_CREATED'; +exports[3011] = 'ER_REFERENCED_TRG_DOES_NOT_EXIST'; +exports[3012] = 'ER_EXPLAIN_NOT_SUPPORTED'; +exports[3013] = 'ER_INVALID_FIELD_SIZE'; +exports[3014] = 'ER_MISSING_HA_CREATE_OPTION'; +exports[3015] = 'ER_ENGINE_OUT_OF_MEMORY'; +exports[3016] = 'ER_PASSWORD_EXPIRE_ANONYMOUS_USER'; +exports[3017] = 'ER_SLAVE_SQL_THREAD_MUST_STOP'; +exports[3018] = 'ER_NO_FT_MATERIALIZED_SUBQUERY'; +exports[3019] = 'ER_INNODB_UNDO_LOG_FULL'; +exports[3020] = 'ER_INVALID_ARGUMENT_FOR_LOGARITHM'; +exports[3021] = 'ER_SLAVE_CHANNEL_IO_THREAD_MUST_STOP'; +exports[3022] = 'ER_WARN_OPEN_TEMP_TABLES_MUST_BE_ZERO'; +exports[3023] = 'ER_WARN_ONLY_MASTER_LOG_FILE_NO_POS'; +exports[3024] = 'ER_QUERY_TIMEOUT'; +exports[3025] = 'ER_NON_RO_SELECT_DISABLE_TIMER'; +exports[3026] = 'ER_DUP_LIST_ENTRY'; +exports[3027] = 'ER_SQL_MODE_NO_EFFECT'; +exports[3028] = 'ER_AGGREGATE_ORDER_FOR_UNION'; +exports[3029] = 'ER_AGGREGATE_ORDER_NON_AGG_QUERY'; +exports[3030] = 'ER_SLAVE_WORKER_STOPPED_PREVIOUS_THD_ERROR'; +exports[3031] = 'ER_DONT_SUPPORT_SLAVE_PRESERVE_COMMIT_ORDER'; +exports[3032] = 'ER_SERVER_OFFLINE_MODE'; +exports[3033] = 'ER_GIS_DIFFERENT_SRIDS'; +exports[3034] = 'ER_GIS_UNSUPPORTED_ARGUMENT'; +exports[3035] = 'ER_GIS_UNKNOWN_ERROR'; +exports[3036] = 'ER_GIS_UNKNOWN_EXCEPTION'; +exports[3037] = 'ER_GIS_INVALID_DATA'; +exports[3038] = 'ER_BOOST_GEOMETRY_EMPTY_INPUT_EXCEPTION'; +exports[3039] = 'ER_BOOST_GEOMETRY_CENTROID_EXCEPTION'; +exports[3040] = 'ER_BOOST_GEOMETRY_OVERLAY_INVALID_INPUT_EXCEPTION'; +exports[3041] = 'ER_BOOST_GEOMETRY_TURN_INFO_EXCEPTION'; +exports[3042] = 'ER_BOOST_GEOMETRY_SELF_INTERSECTION_POINT_EXCEPTION'; +exports[3043] = 'ER_BOOST_GEOMETRY_UNKNOWN_EXCEPTION'; +exports[3044] = 'ER_STD_BAD_ALLOC_ERROR'; +exports[3045] = 'ER_STD_DOMAIN_ERROR'; +exports[3046] = 'ER_STD_LENGTH_ERROR'; +exports[3047] = 'ER_STD_INVALID_ARGUMENT'; +exports[3048] = 'ER_STD_OUT_OF_RANGE_ERROR'; +exports[3049] = 'ER_STD_OVERFLOW_ERROR'; +exports[3050] = 'ER_STD_RANGE_ERROR'; +exports[3051] = 'ER_STD_UNDERFLOW_ERROR'; +exports[3052] = 'ER_STD_LOGIC_ERROR'; +exports[3053] = 'ER_STD_RUNTIME_ERROR'; +exports[3054] = 'ER_STD_UNKNOWN_EXCEPTION'; +exports[3055] = 'ER_GIS_DATA_WRONG_ENDIANESS'; +exports[3056] = 'ER_CHANGE_MASTER_PASSWORD_LENGTH'; +exports[3057] = 'ER_USER_LOCK_WRONG_NAME'; +exports[3058] = 'ER_USER_LOCK_DEADLOCK'; +exports[3059] = 'ER_REPLACE_INACCESSIBLE_ROWS'; +exports[3060] = 'ER_ALTER_OPERATION_NOT_SUPPORTED_REASON_GIS'; +exports[3061] = 'ER_ILLEGAL_USER_VAR'; +exports[3062] = 'ER_GTID_MODE_OFF'; +exports[3063] = 'ER_UNSUPPORTED_BY_REPLICATION_THREAD'; +exports[3064] = 'ER_INCORRECT_TYPE'; +exports[3065] = 'ER_FIELD_IN_ORDER_NOT_SELECT'; +exports[3066] = 'ER_AGGREGATE_IN_ORDER_NOT_SELECT'; +exports[3067] = 'ER_INVALID_RPL_WILD_TABLE_FILTER_PATTERN'; +exports[3068] = 'ER_NET_OK_PACKET_TOO_LARGE'; +exports[3069] = 'ER_INVALID_JSON_DATA'; +exports[3070] = 'ER_INVALID_GEOJSON_MISSING_MEMBER'; +exports[3071] = 'ER_INVALID_GEOJSON_WRONG_TYPE'; +exports[3072] = 'ER_INVALID_GEOJSON_UNSPECIFIED'; +exports[3073] = 'ER_DIMENSION_UNSUPPORTED'; +exports[3074] = 'ER_SLAVE_CHANNEL_DOES_NOT_EXIST'; +exports[3075] = 'ER_SLAVE_MULTIPLE_CHANNELS_HOST_PORT'; +exports[3076] = 'ER_SLAVE_CHANNEL_NAME_INVALID_OR_TOO_LONG'; +exports[3077] = 'ER_SLAVE_NEW_CHANNEL_WRONG_REPOSITORY'; +exports[3078] = 'ER_SLAVE_CHANNEL_DELETE'; +exports[3079] = 'ER_SLAVE_MULTIPLE_CHANNELS_CMD'; +exports[3080] = 'ER_SLAVE_MAX_CHANNELS_EXCEEDED'; +exports[3081] = 'ER_SLAVE_CHANNEL_MUST_STOP'; +exports[3082] = 'ER_SLAVE_CHANNEL_NOT_RUNNING'; +exports[3083] = 'ER_SLAVE_CHANNEL_WAS_RUNNING'; +exports[3084] = 'ER_SLAVE_CHANNEL_WAS_NOT_RUNNING'; +exports[3085] = 'ER_SLAVE_CHANNEL_SQL_THREAD_MUST_STOP'; +exports[3086] = 'ER_SLAVE_CHANNEL_SQL_SKIP_COUNTER'; +exports[3087] = 'ER_WRONG_FIELD_WITH_GROUP_V2'; +exports[3088] = 'ER_MIX_OF_GROUP_FUNC_AND_FIELDS_V2'; +exports[3089] = 'ER_WARN_DEPRECATED_SYSVAR_UPDATE'; +exports[3090] = 'ER_WARN_DEPRECATED_SQLMODE'; +exports[3091] = 'ER_CANNOT_LOG_PARTIAL_DROP_DATABASE_WITH_GTID'; +exports[3092] = 'ER_GROUP_REPLICATION_CONFIGURATION'; +exports[3093] = 'ER_GROUP_REPLICATION_RUNNING'; +exports[3094] = 'ER_GROUP_REPLICATION_APPLIER_INIT_ERROR'; +exports[3095] = 'ER_GROUP_REPLICATION_STOP_APPLIER_THREAD_TIMEOUT'; +exports[3096] = 'ER_GROUP_REPLICATION_COMMUNICATION_LAYER_SESSION_ERROR'; +exports[3097] = 'ER_GROUP_REPLICATION_COMMUNICATION_LAYER_JOIN_ERROR'; +exports[3098] = 'ER_BEFORE_DML_VALIDATION_ERROR'; +exports[3099] = 'ER_PREVENTS_VARIABLE_WITHOUT_RBR'; +exports[3100] = 'ER_RUN_HOOK_ERROR'; +exports[3101] = 'ER_TRANSACTION_ROLLBACK_DURING_COMMIT'; +exports[3102] = 'ER_GENERATED_COLUMN_FUNCTION_IS_NOT_ALLOWED'; +exports[3103] = 'ER_UNSUPPORTED_ALTER_INPLACE_ON_VIRTUAL_COLUMN'; +exports[3104] = 'ER_WRONG_FK_OPTION_FOR_GENERATED_COLUMN'; +exports[3105] = 'ER_NON_DEFAULT_VALUE_FOR_GENERATED_COLUMN'; +exports[3106] = 'ER_UNSUPPORTED_ACTION_ON_GENERATED_COLUMN'; +exports[3107] = 'ER_GENERATED_COLUMN_NON_PRIOR'; +exports[3108] = 'ER_DEPENDENT_BY_GENERATED_COLUMN'; +exports[3109] = 'ER_GENERATED_COLUMN_REF_AUTO_INC'; +exports[3110] = 'ER_FEATURE_NOT_AVAILABLE'; +exports[3111] = 'ER_CANT_SET_GTID_MODE'; +exports[3112] = 'ER_CANT_USE_AUTO_POSITION_WITH_GTID_MODE_OFF'; +exports[3113] = 'ER_CANT_REPLICATE_ANONYMOUS_WITH_AUTO_POSITION'; +exports[3114] = 'ER_CANT_REPLICATE_ANONYMOUS_WITH_GTID_MODE_ON'; +exports[3115] = 'ER_CANT_REPLICATE_GTID_WITH_GTID_MODE_OFF'; +exports[3116] = 'ER_CANT_SET_ENFORCE_GTID_CONSISTENCY_ON_WITH_ONGOING_GTID_VIOLATING_TRANSACTIONS'; +exports[3117] = 'ER_SET_ENFORCE_GTID_CONSISTENCY_WARN_WITH_ONGOING_GTID_VIOLATING_TRANSACTIONS'; +exports[3118] = 'ER_ACCOUNT_HAS_BEEN_LOCKED'; +exports[3119] = 'ER_WRONG_TABLESPACE_NAME'; +exports[3120] = 'ER_TABLESPACE_IS_NOT_EMPTY'; +exports[3121] = 'ER_WRONG_FILE_NAME'; +exports[3122] = 'ER_BOOST_GEOMETRY_INCONSISTENT_TURNS_EXCEPTION'; +exports[3123] = 'ER_WARN_OPTIMIZER_HINT_SYNTAX_ERROR'; +exports[3124] = 'ER_WARN_BAD_MAX_EXECUTION_TIME'; +exports[3125] = 'ER_WARN_UNSUPPORTED_MAX_EXECUTION_TIME'; +exports[3126] = 'ER_WARN_CONFLICTING_HINT'; +exports[3127] = 'ER_WARN_UNKNOWN_QB_NAME'; +exports[3128] = 'ER_UNRESOLVED_HINT_NAME'; +exports[3129] = 'ER_WARN_ON_MODIFYING_GTID_EXECUTED_TABLE'; +exports[3130] = 'ER_PLUGGABLE_PROTOCOL_COMMAND_NOT_SUPPORTED'; +exports[3131] = 'ER_LOCKING_SERVICE_WRONG_NAME'; +exports[3132] = 'ER_LOCKING_SERVICE_DEADLOCK'; +exports[3133] = 'ER_LOCKING_SERVICE_TIMEOUT'; +exports[3134] = 'ER_GIS_MAX_POINTS_IN_GEOMETRY_OVERFLOWED'; +exports[3135] = 'ER_SQL_MODE_MERGED'; +exports[3136] = 'ER_VTOKEN_PLUGIN_TOKEN_MISMATCH'; +exports[3137] = 'ER_VTOKEN_PLUGIN_TOKEN_NOT_FOUND'; +exports[3138] = 'ER_CANT_SET_VARIABLE_WHEN_OWNING_GTID'; +exports[3139] = 'ER_SLAVE_CHANNEL_OPERATION_NOT_ALLOWED'; +exports[3140] = 'ER_INVALID_JSON_TEXT'; +exports[3141] = 'ER_INVALID_JSON_TEXT_IN_PARAM'; +exports[3142] = 'ER_INVALID_JSON_BINARY_DATA'; +exports[3143] = 'ER_INVALID_JSON_PATH'; +exports[3144] = 'ER_INVALID_JSON_CHARSET'; +exports[3145] = 'ER_INVALID_JSON_CHARSET_IN_FUNCTION'; +exports[3146] = 'ER_INVALID_TYPE_FOR_JSON'; +exports[3147] = 'ER_INVALID_CAST_TO_JSON'; +exports[3148] = 'ER_INVALID_JSON_PATH_CHARSET'; +exports[3149] = 'ER_INVALID_JSON_PATH_WILDCARD'; +exports[3150] = 'ER_JSON_VALUE_TOO_BIG'; +exports[3151] = 'ER_JSON_KEY_TOO_BIG'; +exports[3152] = 'ER_JSON_USED_AS_KEY'; +exports[3153] = 'ER_JSON_VACUOUS_PATH'; +exports[3154] = 'ER_JSON_BAD_ONE_OR_ALL_ARG'; +exports[3155] = 'ER_NUMERIC_JSON_VALUE_OUT_OF_RANGE'; +exports[3156] = 'ER_INVALID_JSON_VALUE_FOR_CAST'; +exports[3157] = 'ER_JSON_DOCUMENT_TOO_DEEP'; +exports[3158] = 'ER_JSON_DOCUMENT_NULL_KEY'; +exports[3159] = 'ER_SECURE_TRANSPORT_REQUIRED'; +exports[3160] = 'ER_NO_SECURE_TRANSPORTS_CONFIGURED'; +exports[3161] = 'ER_DISABLED_STORAGE_ENGINE'; +exports[3162] = 'ER_USER_DOES_NOT_EXIST'; +exports[3163] = 'ER_USER_ALREADY_EXISTS'; +exports[3164] = 'ER_AUDIT_API_ABORT'; +exports[3165] = 'ER_INVALID_JSON_PATH_ARRAY_CELL'; +exports[3166] = 'ER_BUFPOOL_RESIZE_INPROGRESS'; +exports[3167] = 'ER_FEATURE_DISABLED_SEE_DOC'; +exports[3168] = 'ER_SERVER_ISNT_AVAILABLE'; +exports[3169] = 'ER_SESSION_WAS_KILLED'; +exports[3170] = 'ER_CAPACITY_EXCEEDED'; +exports[3171] = 'ER_CAPACITY_EXCEEDED_IN_RANGE_OPTIMIZER'; +exports[3172] = 'ER_TABLE_NEEDS_UPG_PART'; +exports[3173] = 'ER_CANT_WAIT_FOR_EXECUTED_GTID_SET_WHILE_OWNING_A_GTID'; +exports[3174] = 'ER_CANNOT_ADD_FOREIGN_BASE_COL_VIRTUAL'; +exports[3175] = 'ER_CANNOT_CREATE_VIRTUAL_INDEX_CONSTRAINT'; +exports[3176] = 'ER_ERROR_ON_MODIFYING_GTID_EXECUTED_TABLE'; +exports[3177] = 'ER_LOCK_REFUSED_BY_ENGINE'; +exports[3178] = 'ER_UNSUPPORTED_ALTER_ONLINE_ON_VIRTUAL_COLUMN'; +exports[3179] = 'ER_MASTER_KEY_ROTATION_NOT_SUPPORTED_BY_SE'; +exports[3180] = 'ER_MASTER_KEY_ROTATION_ERROR_BY_SE'; +exports[3181] = 'ER_MASTER_KEY_ROTATION_BINLOG_FAILED'; +exports[3182] = 'ER_MASTER_KEY_ROTATION_SE_UNAVAILABLE'; +exports[3183] = 'ER_TABLESPACE_CANNOT_ENCRYPT'; +exports[3184] = 'ER_INVALID_ENCRYPTION_OPTION'; +exports[3185] = 'ER_CANNOT_FIND_KEY_IN_KEYRING'; +exports[3186] = 'ER_CAPACITY_EXCEEDED_IN_PARSER'; +exports[3187] = 'ER_UNSUPPORTED_ALTER_ENCRYPTION_INPLACE'; +exports[3188] = 'ER_KEYRING_UDF_KEYRING_SERVICE_ERROR'; +exports[3189] = 'ER_USER_COLUMN_OLD_LENGTH'; +exports[3190] = 'ER_CANT_RESET_MASTER'; +exports[3191] = 'ER_GROUP_REPLICATION_MAX_GROUP_SIZE'; +exports[3192] = 'ER_CANNOT_ADD_FOREIGN_BASE_COL_STORED'; +exports[3193] = 'ER_TABLE_REFERENCED'; +exports[3194] = 'ER_PARTITION_ENGINE_DEPRECATED_FOR_TABLE'; +exports[3195] = 'ER_WARN_USING_GEOMFROMWKB_TO_SET_SRID_ZERO'; +exports[3196] = 'ER_WARN_USING_GEOMFROMWKB_TO_SET_SRID'; +exports[3197] = 'ER_XA_RETRY'; +exports[3198] = 'ER_KEYRING_AWS_UDF_AWS_KMS_ERROR'; +exports[3199] = 'ER_BINLOG_UNSAFE_XA'; +exports[3200] = 'ER_UDF_ERROR'; +exports[3201] = 'ER_KEYRING_MIGRATION_FAILURE'; +exports[3202] = 'ER_KEYRING_ACCESS_DENIED_ERROR'; +exports[3203] = 'ER_KEYRING_MIGRATION_STATUS'; +exports[3204] = 'ER_PLUGIN_FAILED_TO_OPEN_TABLES'; +exports[3205] = 'ER_PLUGIN_FAILED_TO_OPEN_TABLE'; +exports[3206] = 'ER_AUDIT_LOG_NO_KEYRING_PLUGIN_INSTALLED'; +exports[3207] = 'ER_AUDIT_LOG_ENCRYPTION_PASSWORD_HAS_NOT_BEEN_SET'; +exports[3208] = 'ER_AUDIT_LOG_COULD_NOT_CREATE_AES_KEY'; +exports[3209] = 'ER_AUDIT_LOG_ENCRYPTION_PASSWORD_CANNOT_BE_FETCHED'; +exports[3210] = 'ER_AUDIT_LOG_JSON_FILTERING_NOT_ENABLED'; +exports[3211] = 'ER_AUDIT_LOG_UDF_INSUFFICIENT_PRIVILEGE'; +exports[3212] = 'ER_AUDIT_LOG_SUPER_PRIVILEGE_REQUIRED'; +exports[3213] = 'ER_COULD_NOT_REINITIALIZE_AUDIT_LOG_FILTERS'; +exports[3214] = 'ER_AUDIT_LOG_UDF_INVALID_ARGUMENT_TYPE'; +exports[3215] = 'ER_AUDIT_LOG_UDF_INVALID_ARGUMENT_COUNT'; +exports[3216] = 'ER_AUDIT_LOG_HAS_NOT_BEEN_INSTALLED'; +exports[3217] = 'ER_AUDIT_LOG_UDF_READ_INVALID_MAX_ARRAY_LENGTH_ARG_TYPE'; +exports[3218] = 'ER_AUDIT_LOG_UDF_READ_INVALID_MAX_ARRAY_LENGTH_ARG_VALUE'; +exports[3219] = 'ER_AUDIT_LOG_JSON_FILTER_PARSING_ERROR'; +exports[3220] = 'ER_AUDIT_LOG_JSON_FILTER_NAME_CANNOT_BE_EMPTY'; +exports[3221] = 'ER_AUDIT_LOG_JSON_USER_NAME_CANNOT_BE_EMPTY'; +exports[3222] = 'ER_AUDIT_LOG_JSON_FILTER_DOES_NOT_EXISTS'; +exports[3223] = 'ER_AUDIT_LOG_USER_FIRST_CHARACTER_MUST_BE_ALPHANUMERIC'; +exports[3224] = 'ER_AUDIT_LOG_USER_NAME_INVALID_CHARACTER'; +exports[3225] = 'ER_AUDIT_LOG_HOST_NAME_INVALID_CHARACTER'; +exports[3226] = 'WARN_DEPRECATED_MAXDB_SQL_MODE_FOR_TIMESTAMP'; +exports[3227] = 'ER_XA_REPLICATION_FILTERS'; +exports[3228] = 'ER_CANT_OPEN_ERROR_LOG'; +exports[3229] = 'ER_GROUPING_ON_TIMESTAMP_IN_DST'; +exports[3230] = 'ER_CANT_START_SERVER_NAMED_PIPE'; diff --git a/ts-ticket-office-service/node_modules/mysql/lib/protocol/constants/field_flags.js b/ts-ticket-office-service/node_modules/mysql/lib/protocol/constants/field_flags.js new file mode 100644 index 000000000..c698da51b --- /dev/null +++ b/ts-ticket-office-service/node_modules/mysql/lib/protocol/constants/field_flags.js @@ -0,0 +1,18 @@ +// Manually extracted from mysql-5.5.23/include/mysql_com.h +exports.NOT_NULL_FLAG = 1; /* Field can't be NULL */ +exports.PRI_KEY_FLAG = 2; /* Field is part of a primary key */ +exports.UNIQUE_KEY_FLAG = 4; /* Field is part of a unique key */ +exports.MULTIPLE_KEY_FLAG = 8; /* Field is part of a key */ +exports.BLOB_FLAG = 16; /* Field is a blob */ +exports.UNSIGNED_FLAG = 32; /* Field is unsigned */ +exports.ZEROFILL_FLAG = 64; /* Field is zerofill */ +exports.BINARY_FLAG = 128; /* Field is binary */ + +/* The following are only sent to new clients */ +exports.ENUM_FLAG = 256; /* field is an enum */ +exports.AUTO_INCREMENT_FLAG = 512; /* field is a autoincrement field */ +exports.TIMESTAMP_FLAG = 1024; /* Field is a timestamp */ +exports.SET_FLAG = 2048; /* field is a set */ +exports.NO_DEFAULT_VALUE_FLAG = 4096; /* Field doesn't have default value */ +exports.ON_UPDATE_NOW_FLAG = 8192; /* Field is set to NOW on UPDATE */ +exports.NUM_FLAG = 32768; /* Field is num (for clients) */ diff --git a/ts-ticket-office-service/node_modules/mysql/lib/protocol/constants/server_status.js b/ts-ticket-office-service/node_modules/mysql/lib/protocol/constants/server_status.js new file mode 100644 index 000000000..48880c370 --- /dev/null +++ b/ts-ticket-office-service/node_modules/mysql/lib/protocol/constants/server_status.js @@ -0,0 +1,39 @@ +// Manually extracted from mysql-5.5.23/include/mysql_com.h + +/** + Is raised when a multi-statement transaction + has been started, either explicitly, by means + of BEGIN or COMMIT AND CHAIN, or + implicitly, by the first transactional + statement, when autocommit=off. +*/ +exports.SERVER_STATUS_IN_TRANS = 1; +exports.SERVER_STATUS_AUTOCOMMIT = 2; /* Server in auto_commit mode */ +exports.SERVER_MORE_RESULTS_EXISTS = 8; /* Multi query - next query exists */ +exports.SERVER_QUERY_NO_GOOD_INDEX_USED = 16; +exports.SERVER_QUERY_NO_INDEX_USED = 32; +/** + The server was able to fulfill the clients request and opened a + read-only non-scrollable cursor for a query. This flag comes + in reply to COM_STMT_EXECUTE and COM_STMT_FETCH commands. +*/ +exports.SERVER_STATUS_CURSOR_EXISTS = 64; +/** + This flag is sent when a read-only cursor is exhausted, in reply to + COM_STMT_FETCH command. +*/ +exports.SERVER_STATUS_LAST_ROW_SENT = 128; +exports.SERVER_STATUS_DB_DROPPED = 256; /* A database was dropped */ +exports.SERVER_STATUS_NO_BACKSLASH_ESCAPES = 512; +/** + Sent to the client if after a prepared statement reprepare + we discovered that the new statement returns a different + number of result set columns. +*/ +exports.SERVER_STATUS_METADATA_CHANGED = 1024; +exports.SERVER_QUERY_WAS_SLOW = 2048; + +/** + To mark ResultSet containing output parameter values. +*/ +exports.SERVER_PS_OUT_PARAMS = 4096; diff --git a/ts-ticket-office-service/node_modules/mysql/lib/protocol/constants/ssl_profiles.js b/ts-ticket-office-service/node_modules/mysql/lib/protocol/constants/ssl_profiles.js new file mode 100644 index 000000000..bec1864f3 --- /dev/null +++ b/ts-ticket-office-service/node_modules/mysql/lib/protocol/constants/ssl_profiles.js @@ -0,0 +1,1480 @@ +// Certificates for Amazon RDS +exports['Amazon RDS'] = { + ca: [ + /** + * Amazon RDS global certificate 2010 to 2015 + * + * CN = aws.amazon.com/rds/ + * OU = RDS + * O = Amazon.com + * L = Seattle + * ST = Washington + * C = US + * P = 2010-04-05T22:44:31Z/2015-04-04T22:41:31Z + * F = 7F:09:8D:A5:7D:BB:A6:E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GoEoMAwGA1UdEwQFMAMBAf8wDQYJKoZIhvcNAQEFBQADgYEAvguZy/BDT66x\n' + + 'GfgnJlyQwnFSeVLQm9u/FIvz4huGjbq9dqnD6h/Gm56QPFdyMEyDiZWaqY6V08lY\n' + + 'LTBNb4kcIc9/6pc0/ojKciP5QJRm6OiZ4vgG05nF4fYjhU7WClUx7cxq1fKjNc2J\n' + + 'UCmmYqgiVkAGWRETVo+byOSDZ4swb10=\n' + + '-----END CERTIFICATE-----\n', + + /** + * Amazon RDS global root CA 2015 to 2020 + * + * CN = Amazon RDS Root CA + * OU = Amazon RDS + * O = Amazon Web Services, Inc. + * L = Seattle + * ST = Washington + * C = US + * P = 2015-02-05T09:11:31Z/2020-03-05T09:11:31Z + * F = E8:11:88:56:E7:A7:CE:3E:5E:DC:9A:31:25:1B:93:AC:DC:43:CE:B0 + */ + '-----BEGIN CERTIFICATE-----\n' + + 'MIID9DCCAtygAwIBAgIBQjANBgkqhkiG9w0BAQUFADCBijELMAkGA1UEBhMCVVMx\n' + + 'EzARBgNVBAgMCldhc2hpbmd0b24xEDAOBgNVBAcMB1NlYXR0bGUxIjAgBgNVBAoM\n' + + 'GUFtYXpvbiBXZWIgU2VydmljZXMsIEluYy4xEzARBgNVBAsMCkFtYXpvbiBSRFMx\n' + + 'GzAZBgNVBAMMEkFtYXpvbiBSRFMgUm9vdCBDQTAeFw0xNTAyMDUwOTExMzFaFw0y\n' + + 'MDAzMDUwOTExMzFaMIGKMQswCQYDVQQGEwJVUzETMBEGA1UECAwKV2FzaGluZ3Rv\n' + + 'bjEQMA4GA1UEBwwHU2VhdHRsZTEiMCAGA1UECgwZQW1hem9uIFdlYiBTZXJ2aWNl\n' + + 'cywgSW5jLjETMBEGA1UECwwKQW1hem9uIFJEUzEbMBkGA1UEAwwSQW1hem9uIFJE\n' + + 'UyBSb290IENBMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAuD8nrZ8V\n' + + 'u+VA8yVlUipCZIKPTDcOILYpUe8Tct0YeQQr0uyl018StdBsa3CjBgvwpDRq1HgF\n' + + 'Ji2N3+39+shCNspQeE6aYU+BHXhKhIIStt3r7gl/4NqYiDDMWKHxHq0nsGDFfArf\n' + + 'AOcjZdJagOMqb3fF46flc8k2E7THTm9Sz4L7RY1WdABMuurpICLFE3oHcGdapOb9\n' + + 'T53pQR+xpHW9atkcf3pf7gbO0rlKVSIoUenBlZipUlp1VZl/OD/E+TtRhDDNdI2J\n' + + 'P/DSMM3aEsq6ZQkfbz/Ilml+Lx3tJYXUDmp+ZjzMPLk/+3beT8EhrwtcG3VPpvwp\n' + + 'BIOqsqVVTvw/CwIDAQABo2MwYTAOBgNVHQ8BAf8EBAMCAQYwDwYDVR0TAQH/BAUw\n' + + 'AwEB/zAdBgNVHQ4EFgQUTgLurD72FchM7Sz1BcGPnIQISYMwHwYDVR0jBBgwFoAU\n' + + 'TgLurD72FchM7Sz1BcGPnIQISYMwDQYJKoZIhvcNAQEFBQADggEBAHZcgIio8pAm\n' + + 'MjHD5cl6wKjXxScXKtXygWH2BoDMYBJF9yfyKO2jEFxYKbHePpnXB1R04zJSWAw5\n' + + '2EUuDI1pSBh9BA82/5PkuNlNeSTB3dXDD2PEPdzVWbSKvUB8ZdooV+2vngL0Zm4r\n' + + '47QPyd18yPHrRIbtBtHR/6CwKevLZ394zgExqhnekYKIqqEX41xsUV0Gm6x4vpjf\n' + + '2u6O/+YE2U+qyyxHE5Wd5oqde0oo9UUpFETJPVb6Q2cEeQib8PBAyi0i6KnF+kIV\n' + + 'A9dY7IHSubtCK/i8wxMVqfd5GtbA8mmpeJFwnDvm9rBEsHybl08qlax9syEwsUYr\n' + + '/40NawZfTUU=\n' + + '-----END CERTIFICATE-----\n', + + /** + * Amazon RDS global root CA 2019 to 2024 + * + * CN = Amazon RDS Root 2019 CA + * OU = Amazon RDS + * O = Amazon Web Services, Inc. + * L = Seattle + * ST = Washington + * C = US + * P = 2019-08-22T17:08:50Z/2024-08-22T17:08:50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8BAf8E\n' + + 'BAMCAQYwDwYDVR0TAQH/BAUwAwEB/zAdBgNVHQ4EFgQUc19g2LzLA5j0Kxc0LjZa\n' + + 'pmD/vB8wHwYDVR0jBBgwFoAUc19g2LzLA5j0Kxc0LjZapmD/vB8wDQYJKoZIhvcN\n' + + 'AQELBQADggEBAHAG7WTmyjzPRIM85rVj+fWHsLIvqpw6DObIjMWokpliCeMINZFV\n' + + 'ynfgBKsf1ExwbvJNzYFXW6dihnguDG9VMPpi2up/ctQTN8tm9nDKOy08uNZoofMc\n' + + 'NUZxKCEkVKZv+IL4oHoeayt8egtv3ujJM6V14AstMQ6SwvwvA93EP/Ug2e4WAXHu\n' + + 'cbI1NAbUgVDqp+DRdfvZkgYKryjTWd/0+1fS8X1bBZVWzl7eirNVnHbSH2ZDpNuY\n' + + '0SBd8dj5F6ld3t58ydZbrTHze7JJOd8ijySAp4/kiu9UfZWuTPABzDa/DSdz9Dk/\n' + + 'zPW4CXXvhLmE02TA9/HeCw3KEHIwicNuEfw=\n' + + '-----END CERTIFICATE-----\n', + + /** + * Amazon RDS ap-northeast-1 certificate CA 2015 to 2020 + * + * CN = Amazon RDS ap-northeast-1 CA + * OU = Amazon RDS + * O = Amazon Web Services, Inc. + * L = Seattle + * ST = Washington + * C = US + * P = 2015-02-05T22:03:06Z/2020-03-05T22:03:06Z + * F = 4B:2D:8A:E0:C1:A3:A9:AF:A7:BB:65:0C:5A:16:8A:39:3C:03:F2:C5 + */ + '-----BEGIN CERTIFICATE-----\n' + + 'MIIEATCCAumgAwIBAgIBRDANBgkqhkiG9w0BAQUFADCBijELMAkGA1UEBhMCVVMx\n' + + 'EzARBgNVBAgMCldhc2hpbmd0b24xEDAOBgNVBAcMB1NlYXR0bGUxIjAgBgNVBAoM\n' + + 'GUFtYXpvbiBXZWIgU2VydmljZXMsIEluYy4xEzARBgNVBAsMCkFtYXpvbiBSRFMx\n' + + 'GzAZBgNVBAMMEkFtYXpvbiBSRFMgUm9vdCBDQTAeFw0x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duf1KgaiVx1PEyJjC6r\n' + + 'M+Ru+A0eM+jJ7uCjUoZKcpX8xkj4nmSnz9NMPog3wdOSB9cAW7XIc5mHa656wr7I\n' + + 'WJxVcYNHTXIjCcng2zMKd1aCcl2KSFfy56sRfT7J5Wp69QSr+jq8KM55gw8uqAwi\n' + + 'VPrXn2899T1rcTtFYFP16WXjGuc0\n' + + '-----END CERTIFICATE-----\n', + + /** + * Amazon RDS ap-northeast-2 certificate CA 2015 to 2020 + * + * CN = Amazon RDS ap-northeast-2 CA + * OU = Amazon RDS + * O = Amazon Web Services, Inc. + * L = Seattle + * ST = Washington + * C = US + * P = 2015-11-06T00:05:46Z/2020-03-05T00:05:46Z + * F = 77:D9:33:4E:CE:56:FC:42:7B:29:57:8D:67:59:ED:29:4E:18:CB:6B + */ + '-----BEGIN CERTIFICATE-----\n' + + 'MIIEATCCAumgAwIBAgIBTDANBgkqhkiG9w0BAQUFADCBijELMAkGA1UEBhMCVVMx\n' + + 'EzARBgNVBAgMCldhc2hpbmd0b24xEDAOBgNVBAcMB1NlYXR0bGUxIjAgBgNVBAoM\n' + + 'GUFtYXpvbiBXZWIgU2VydmljZXMsIEluYy4xEzARBgNVBAsMCkFtYXpvbiBSRFMx\n' + + 'GzAZBgNVBAMMEkFtYXpvbiBSRFMgUm9vdCBDQTAeFw0xNTExMDYwMDA1NDZaFw0y\n' + + 'MDAzMDUwMDA1NDZaMIGUMQswCQYDVQQGEwJVUzETMBEGA1UECAwKV2FzaGluZ3Rv\n' + + 'bjEQMA4GA1UEBwwHU2VhdHRsZTEiMCAGA1UECgwZQW1hem9uIFdlYiBTZXJ2aWNl\n' + + 'cywgSW5jLjETMBEGA1UECwwKQW1hem9uIFJEUzElMCMGA1UEAwwcQW1hem9uIFJE\n' + + 'UyBhcC1ub3J0aGVhc3QtMiBDQTCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoC\n' + + 'ggEBAKSwd+RVUzTRH0FgnbwoTK8TMm/zMT4+2BvALpAUe6YXbkisg2goycWuuWLg\n' + + 'jOpFBB3GtyvXZnkqi7MkDWUmj1a2kf8l2oLyoaZ+Hm9x/sV+IJzOqPvj1XVUGjP6\n' + + 'yYYnPJmUYqvZeI7fEkIGdFkP2m4/sgsSGsFvpD9FK1bL1Kx2UDpYX0kHTtr18Zm/\n' + + '1oN6irqWALSmXMDydb8hE0FB2A1VFyeKE6PnoDj/Y5cPHwPPdEi6/3gkDkSaOG30\n' + + 'rWeQfL3pOcKqzbHaWTxMphd0DSL/quZ64Nr+Ly65Q5PRcTrtr55ekOUziuqXwk+o\n' + + '9QpACMwcJ7ROqOznZTqTzSFVXFECAwEAAaNmMGQwDgYDVR0PAQH/BAQDAgEGMBIG\n' + + 'A1UdEwEB/wQIMAYBAf8CAQAwHQYDVR0OBBYEFM6Nox/QWbhzWVvzoJ/y0kGpNPK+\n' + + 'MB8GA1UdIwQYMBaAFE4C7qw+9hXITO0s9QXBj5yECEmDMA0GCSqGSIb3DQEBBQUA\n' + + 'A4IBAQCTkWBqNvyRf3Y/W21DwFx3oT/AIWrHt0BdGZO34tavummXemTH9LZ/mqv9\n' + + 'aljt6ZuDtf5DEQjdsAwXMsyo03ffnP7doWm8iaF1+Mui77ot0TmTsP/deyGwukvJ\n' + + 'tkxX8bZjDh+EaNauWKr+CYnniNxCQLfFtXYJsfOdVBzK3xNL+Z3ucOQRhr2helWc\n' + + 'CDQgwfhP1+3pRVKqHvWCPC4R3fT7RZHuRmZ38kndv476GxRntejh+ePffif78bFI\n' + + '3rIZCPBGobrrUMycafSbyXteoGca/kA+/IqrAPlk0pWQ4aEL0yTWN2h2dnjoD7oX\n' + + 'byIuL/g9AGRh97+ssn7D6bDRPTbW\n' + + '-----END CERTIFICATE-----\n', + + /** + * Amazon RDS ap-southeast-1 certificate CA 2015 to 2020 + * + * CN = Amazon RDS ap-southeast-1 CA + * OU = Amazon RDS + * O = Amazon Web Services, Inc. + * L = Seattle + * ST = Washington + * C = US + * P = 2015-02-05T22:03:19Z/2020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PAQH/BAQDAgEGMBIG\n' + + 'A1UdEwEB/wQIMAYBAf8CAQAwHQYDVR0OBBYEFAu93/4k5xbWOsgdCdn+/KdiRuit\n' + + 'MB8GA1UdIwQYMBaAFE4C7qw+9hXITO0s9QXBj5yECEmDMA0GCSqGSIb3DQEBBQUA\n' + + 'A4IBAQBlcjSyscpPjf5+MgzMuAsCxByqUt+WFspwcMCpwdaBeHOPSQrXNqX2Sk6P\n' + + 'kth6oCivA64trWo8tFMvPYlUA1FYVD5WpN0kCK+P5pD4KHlaDsXhuhClJzp/OP8t\n' + + 'pOyUr5109RHLxqoKB5J5m1XA7rgcFjnMxwBSWFe3/4uMk/+4T53YfCVXuc6QV3i7\n' + + 'I/2LAJwFf//pTtt6fZenYfCsahnr2nvrNRNyAxcfvGZ/4Opn/mJtR6R/AjvQZHiR\n' + + 'bkRNKF2GW0ueK5W4FkZVZVhhX9xh1Aj2Ollb+lbOqADaVj+AT3PoJPZ3MPQHKCXm\n' + + 'xwG0LOLlRr/TfD6li1AfOVTAJXv9\n' + + '-----END CERTIFICATE-----\n', + + /** + * Amazon RDS ap-southeast-2 certificate CA 2015 to 2020 + * + * CN = Amazon RDS ap-southeast-2 CA + * OU = Amazon RDS + * O = Amazon Web Services, Inc. + * L = Seattle + * ST = Washington + * C = US + * P = 2015-02-05T22:03:24Z/2020-03-05T22:03:24Z + * F = 20:D9:A8:82:23:AB:B9:E5:C5:24:10:D3:4D:0F:3D:B1:31:DF:E5:14 + */ + '-----BEGIN CERTIFICATE-----\n' + + 'MIIEATCCAumgAwIBAgIBRjANBgkqhkiG9w0BAQUFADCBijELMAkGA1UEBhMCVVMx\n' + + 'EzARBgNVBAgMCldhc2hpbmd0b24xEDAOBgNVBAcMB1NlYXR0bGUxIjAgBgNVBAoM\n' + + 'GUFtYXpvbiBXZWIgU2VydmljZXMsIEluYy4xEzARBgNVBAsMCkFtYXpvbiBSRFMx\n' + + 'GzAZBgNVBAMMEkFtYXpvbiBSRFMgUm9vdCBDQ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icos9LQxVtJ0XA4ieG1E7z\n' + + 'zJr+6t80wmzxvkInSaWP3xNJK9azVRTrgQZQlvkbpDbExl4mNTG66VD3bAp6t3Wa\n' + + 'B49//uDdfZmPkqqbX+hsxp160OH0rxJppwO3Bh869PkDnaPEd/Pxw7PawC+li0gi\n' + + 'NRV8iCEx85aFxcyOhqn0WZOasxee\n' + + '-----END CERTIFICATE-----\n', + + /** + * Amazon RDS eu-central-1 certificate CA 2015 to 2020 + * + * CN = Amazon RDS eu-central-1 CA + * OU = Amazon RDS + * O = Amazon Web Services, Inc. + * L = Seattle + * ST = Washington + * C = US + * P = 2015-02-05T22:03:31Z/2020-03-05T22:03:31Z + * F = 94:B4:DF:B9:6D:7E:F7:C3:B7:BF:51:E9:A6:B7:44:A0:D0:82:11:84 + */ + '-----BEGIN CERTIFICATE-----\n' + + 'MIID/zCCAuegAwIBAgIBRzANBgkqhkiG9w0BAQUFADCBijELMAkGA1UEBhMCVVMx\n' + + 'EzARBgNVBAgMCldhc2hpbmd0b24xEDAOBgNVBAcMB1NlYXR0bGUxIjAgBgNVBAoM\n' + + 'GUFtYXpvbiBXZWIgU2VydmljZXMsIEluYy4xEzARBgNVBAsMCkFtYXpvbiBSRFMx\n' + + 'GzAZBgNVBAMMEkFtYXpvbiBSRFMgUm9vdCBDQTAeFw0xNTAyMDUyMjAzMzFaFw0y\n' + + 'MDAzMDUyMjAzMzFaMIGSMQswCQYDVQQGEwJVUzETMBEGA1UECAwKV2FzaGluZ3Rv\n' + + 'bjEQMA4GA1UEBwwHU2VhdHRsZTEiMCAGA1UECgwZQW1hem9uIFdlYiBTZXJ2aWNl\n' + + 'cywgSW5jLjETMBEGA1UECwwKQW1hem9uIFJEUzEjMCEGA1UEAwwaQW1hem9uIFJE\n' + + 'UyBldS1jZW50cmFsLTEgQ0EwggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIB\n' + + 'AQDFtP2dhSLuaPOI4ZrrPWsK4OY9ocQBp3yApH1KJYmI9wpQKZG/KCH2E6Oo7JAw\n' + + 'QORU519r033T+FO2Z7pFPlmz1yrxGXyHpJs8ySx3Yo5S8ncDCdZJCLmtPiq/hahg\n' + + '5/0ffexMFUCQaYicFZsrJ/cStdxUV+tSw2JQLD7UxS9J97LQWUPyyG+ZrjYVTVq+\n' + + 'zudnFmNSe4QoecXMhAFTGJFQXxP7nhSL9Ao5FGgdXy7/JWeWdQIAj8ku6cBDKPa6\n' + + 'Y6kP+ak+In+Lye8z9qsCD/afUozfWjPR2aA4JoIZVF8dNRShIMo8l0XfgfM2q0+n\n' + + 'ApZWZ+BjhIO5XuoUgHS3D2YFAgMBAAGjZjBkMA4GA1UdDwEB/wQEAwIBBjASBgNV\n' + + 'HRMBAf8ECDAGAQH/AgEAMB0GA1UdDgQWBBRm4GsWIA/M6q+tK8WGHWDGh2gcyTAf\n' + + 'BgNVHSMEGDAWgBROAu6sPvYVyEztLPUFwY+chAhJgzANBgkqhkiG9w0BAQUFAAOC\n' + + 'AQEAHpMmeVQNqcxgfQdbDIi5UIy+E7zZykmtAygN1XQrvga9nXTis4kOTN6g5/+g\n' + + 'HCx7jIXeNJzAbvg8XFqBN84Quqgpl/tQkbpco9Jh1HDs558D5NnZQxNqH5qXQ3Mm\n' + + 'uPgCw0pYcPOa7bhs07i+MdVwPBsX27CFDtsgAIru8HvKxY1oTZrWnyIRo93tt/pk\n' + + 'WuItVMVHjaQZVfTCow0aDUbte6Vlw82KjUFq+n2NMSCJDiDKsDDHT6BJc4AJHIq3\n' + + '/4Z52MSC9KMr0yAaaoWfW/yMEj9LliQauAgwVjArF4q78rxpfKTG9Rfd8U1BZANP\n' + + '7FrFMN0ThjfA1IvmOYcgskY5bQ==\n' + + '-----END CERTIFICATE-----\n', + + /** + * Amazon RDS eu-west-1 certificate CA 2015 to 2020 + * + * CN = Amazon RDS eu-west-1 CA + * OU = Amazon RDS + * O = Amazon Web Services, Inc. + * L = Seattle + * ST = Washington + * C = US + * P = 2015-02-05T22:03:35Z/2020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B/wQEAwIBBjASBgNVHRMB\n' + + 'Af8ECDAGAQH/AgEAMB0GA1UdDgQWBBTebg//h2oeXbZjQ4uuoiuLYzuiPDAfBgNV\n' + + 'HSMEGDAWgBROAu6sPvYVyEztLPUFwY+chAhJgzANBgkqhkiG9w0BAQUFAAOCAQEA\n' + + 'TikPaGeZasTPw+4RBemlsyPAjtFFQLo7ddaFdORLgdEysVf8aBqndvbA6MT/v4lj\n' + + 'GtEtUdF59ZcbWOrVm+fBZ2h/jYJ59dYF/xzb09nyRbdMSzB9+mkSsnOMqluq5y8o\n' + + 'DY/PfP2vGhEg/2ZncRC7nlQU1Dm8F4lFWEiQ2fi7O1cW852Vmbq61RIfcYsH/9Ma\n' + + 'kpgk10VZ75b8m3UhmpZ/2uRY+JEHImH5WpcTJ7wNiPNJsciZMznGtrgOnPzYco8L\n' + + 'cDleOASIZifNMQi9PKOJKvi0ITz0B/imr8KBsW0YjZVJ54HMa7W1lwugSM7aMAs+\n' + + 'E3Sd5lS+SHwWaOCHwhOEVA==\n' + + '-----END CERTIFICATE-----\n', + + /** + * Amazon RDS sa-east-1 certificate CA 2015 to 2020 + * + * CN = Amazon RDS sa-east-1 CA + * OU = Amazon RDS + * O = Amazon Web Services, Inc. + * L = Seattle + * ST = Washington + * C = US + * P = 2015-02-05T22:03:40Z/2020-03-05T22:03:40Z + * F = 32:10:3D:FA:6D:42:F5:35:98:40:15:F4:4C:74:74:27:CB:CE:D4:B5 + */ + '-----BEGIN CERTIFICATE-----\n' + + 'MIID/DCCAuSgAwIBAgIBSTANBgkqhkiG9w0BAQUFADCBijELMAkGA1UEBhMCVVMx\n' + + 'EzARBgNVBAgMCldhc2hpbmd0b24xEDAOBgNVBAcMB1NlYXR0bGUxIjAgBgNVBAoM\n' + + 'GUFtYXpvbiBXZWIgU2VydmljZXMsIEluYy4xEzARBgNVBAsMCkFtYXpvbiBSRFMx\n' + + 'GzAZBgNVBAMMEkFtYXpvbiBSRFMgUm9vdCBDQTAeFw0xNTA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gZ9noKwgHvoE4dsrI0\n' + + 'KZYco6DlP/brASfHTPa2puBLN9McK3v+h0JaSqqm5Ro2Bh56tZkQh8AWy/miuDuK\n' + + '3+hNEVdxosxlkM1TPa1DGj0EzzK0yoeerXuH2HX7LlCrrxf6/wdKnjR12PMrLQ4A\n' + + 'pCqkcWw894z6bV9MAvKe6A==\n' + + '-----END CERTIFICATE-----\n', + + /** + * Amazon RDS us-east-1 certificate CA 2015 to 2020 + * + * CN = Amazon RDS us-east-1 CA + * OU = Amazon RDS + * O = Amazon Web Services, Inc. + * L = Seattle + * ST = Washington + * C = US + * P = 2015-02-05T21:54:04Z/2020-03-05T21:54:04Z + * F = 34:47:8A:90:8A:83:AE:45:DC:B6:16:76:D2:35:EC:E9:75:C6:2C:63 + */ + '-----BEGIN CERTIFICATE-----\n' + + 'MIID/DCCAuSgAwIBAgIBQzANBgkqhkiG9w0BAQUFADCBijELMAkGA1UEBhMCVVMx\n' + + 'EzARBgNVBAgMCldhc2hpbmd0b24xEDAOBgNVBAcMB1NlYXR0bGUxIjAgBgNVBAoM\n' + + 'GUFtYXpvbiBXZWIgU2VydmljZXMsIEluYy4xEzARBgNVBAsMCkFtYXpvbiBSRFMx\n' + + 'GzAZBgNVBAMMEkFtYXpvbiBSRFMgUm9vdCBDQTAeFw0xNTAyMDUyMTU0MDRaFw0y\n' + + 'MDAzMDUyMTU0MDRaMIGPMQswCQYDVQQGEwJVUzETMBEGA1UECAwKV2FzaGluZ3Rv\n' + + 'bjEQMA4GA1UEBwwHU2VhdHRsZTEiMCAGA1UECgwZQW1hem9uIFdlYiBTZXJ2aWNl\n' + + 'cywgSW5jLjETMBEGA1UECwwKQW1hem9uIFJEUzEgMB4GA1UEAwwXQW1hem9uIFJE\n' + + 'UyB1cy1lYXN0LTEgQ0EwggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQDI\n' + + 'UIuwh8NusKHk1SqPXcP7OqxY3S/M2ZyQWD3w7Bfihpyyy/fc1w0/suIpX3kbMhAV\n' + + '2ESwged2/2zSx4pVnjp/493r4luhSqQYzru78TuPt9bhJIJ51WXunZW2SWkisSaf\n' + + 'USYUzVN9ezR/bjXTumSUQaLIouJt3OHLX49s+3NAbUyOI8EdvgBQWD68H1epsC0n\n' + + 'CI5s+pIktyOZ59c4DCDLQcXErQ+tNbDC++oct1ANd/q8p9URonYwGCGOBy7sbCYq\n' + + '9eVHh1Iy2M+SNXddVOGw5EuruvHoCIQyOz5Lz4zSuZA9dRbrfztNOpezCNYu6NKM\n' + + 'n+hzcvdiyxv77uNm8EaxAgMBAAGjZjBkMA4GA1UdDwEB/wQEAwIBBjASBgNVHRMB\n' + + 'Af8ECDAGAQH/AgEAMB0GA1UdDgQWBBQSQG3TmMe6Sa3KufaPBa72v4QFDzAfBgNV\n' + + 'HSMEGDAWgBROAu6sPvYVyEztLPUFwY+chAhJgzANBgkqhkiG9w0BAQUFAAOCAQEA\n' + + 'L/mOZfB3187xTmjOHMqN2G2oSKHBKiQLM9uv8+97qT+XR+TVsBT6b3yoPpMAGhHA\n' + + 'Pc7nxAF5gPpuzatx0OTLPcmYucFmfqT/1qA5WlgCnMNtczyNMH97lKFTNV7Njtek\n' + + 'jWEzAEQSyEWrkNpNlC4j6kMYyPzVXQeXUeZTgJ9FNnVZqmvfjip2N22tawMjrCn5\n' + + '7KN/zN65EwY2oO9XsaTwwWmBu3NrDdMbzJnbxoWcFWj4RBwanR1XjQOVNhDwmCOl\n' + + '/1Et13b8CPyj69PC8BOVU6cfTSx8WUVy0qvYOKHNY9Bqa5BDnIL3IVmUkeTlM1mt\n' + + 'enRpyBj+Bk9rh/ICdiRKmA==\n' + + '-----END CERTIFICATE-----\n', + + /** + * Amazon RDS us-west-1 certificate CA 2015 to 2020 + * + * CN = Amazon RDS us-west-1 CA + * OU = Amazon RDS + * O = Amazon Web Services, Inc. + * L = Seattle + * ST = Washington + * C = US + * P = 2015-02-05T22:03:45Z/2020-03-05T22:03:45Z + * F = EF:94:2F:E3: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+ + 'Af8ECDAGAQH/AgEAMB0GA1UdDgQWBBS0nw/tFR9bCjgqWTPJkyy4oOD8bzAfBgNV\n' + + 'HSMEGDAWgBROAu6sPvYVyEztLPUFwY+chAhJgzANBgkqhkiG9w0BAQUFAAOCAQEA\n' + + 'CXGAY3feAak6lHdqj6+YWjy6yyUnLK37bRxZDsyDVXrPRQaXRzPTzx79jvDwEb/H\n' + + 'Q/bdQ7zQRWqJcbivQlwhuPJ4kWPUZgSt3JUUuqkMsDzsvj/bwIjlrEFDOdHGh0mi\n' + + 'eVIngFEjUXjMh+5aHPEF9BlQnB8LfVtKj18e15UDTXFa+xJPFxUR7wDzCfo4WI1m\n' + + 'sUMG4q1FkGAZgsoyFPZfF8IVvgCuGdR8z30VWKklFxttlK0eGLlPAyIO0CQxPQlo\n' + + 'saNJrHf4tLOgZIWk+LpDhNd9Et5EzvJ3aURUsKY4pISPPF5WdvM9OE59bERwUErd\n' + + 'nuOuQWQeeadMceZnauRzJQ==\n' + + '-----END CERTIFICATE-----\n', + + /** + * Amazon RDS us-west-2 certificate CA 2015 to 2020 + * + * CN = Amazon RDS us-west-2 CA + * OU = Amazon RDS + * O = Amazon Web Services, Inc. + * L = Seattle + * ST = Washington + * C = US + * P = 2015-02-05T22:03:50Z/2020-03-05T22:03:50Z + * F = 94:2C:A8:B0:23:48:17:F0:CD:2F:19:7F:C1:E0:21:7C:65:79:13:3A + */ + '-----BEGIN CERTIFICATE-----\n' + + 'MIID/DCCAuSgAwIBAgIBSzANBgkqhkiG9w0BAQUFADCBijELMAkGA1UEBhMCVVMx\n' + + 'EzARBgNVBAgMCldhc2hpbmd0b24xEDAOBgNVBAcMB1NlYXR0bGUxIjAgBgNVBAoM\n' + + 'GUFtYXpvbiBXZWIgU2VydmljZXMsIEluYy4xEzARBgNVBAsMCkFtYXpvbiBSRFMx\n' + + 'GzAZBgNVBAMMEkFtYXpvbiBSRFMgUm9vdCBDQTAeFw0xNTAyMDUyMjAzNTBaFw0y\n' + + 'MD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Mb0QME981kGRzc2WhgP71YS2hHd1kXtsoYP1yTu4vThSKsoN4bkiHsaC1cRkLoy\n' + + '0fFA4wpB3WloMEvCDaUvvH1LZlBXTNlwi9KtcwD4tDxkkBt4tQczKLGpQ/nF/W9n\n' + + '8YDWk3IIc1sd0bkZqoau2Q==\n' + + '-----END CERTIFICATE-----\n', + + /** + * Amazon RDS ap-south-1 certificate CA 2016 to 2020 + * + * CN = Amazon RDS ap-south-1 CA + * OU = Amazon RDS + * O = Amazon Web Services, Inc. + * L = Seattle + * ST = Washington + * C = US + * P = 2016-05-03T21:29:22Z/2020-03-05T21:29:22Z + * F = F3:A3:C2:52:D9:82:20:AC:8C:62:31:2A:8C:AD:5D:7B:1C:31:F1:DD + */ + '-----BEGIN CERTIFICATE-----\n' + + 'MIID/TCCAuWgAwIBAgIBTTANBgkqhkiG9w0BAQsFADCBijELMAkGA1UEBhMCVVMx\n' + + 'EzARBgNVBAgMCldhc2hpbmd0b24xEDAOBgNVBAcMB1NlYXR0bGUxIjAgBgNVBAoM\n' + + 'GUFtYXpvbiBXZWIgU2VydmljZXMsIEluYy4xEzARBgNVBAsMCkFtYXpvbiBSRFMx\n' + + 'GzAZBgNVBAMMEkFtYXpvbiBSRFMgUm9vdCBDQTAeFw0xNjA1MDMyMTI5MjJaFw0y\n' + + 'MDAzMDUyMTI5MjJaMIGQMQswCQYDVQQGEwJVUzETMBEGA1UECAwKV2FzaGluZ3Rv\n' + + 'bjEQMA4GA1UEBwwHU2VhdHRsZTEiMCAGA1UECgwZQW1hem9uIFdlYiBTZXJ2aWNl\n' + + 'cywgSW5jLjETMBEGA1UECwwKQW1hem9uIFJEUzEhMB8GA1UEAwwYQW1hem9uIFJE\n' + + 'UyBhcC1zb3V0aC0xIENBMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEA\n' + + '06eWGLE0TeqL9kyWOLkS8q0fXO97z+xyBV3DKSB2lg2GkgBz3B98MkmkeB0SZy3G\n' + + 'Ce4uCpCPbFKiFEdiUclOlhZsrBuCeaimxLM3Ig2wuenElO/7TqgaYHYUbT3d+VQW\n' + + 'GUbLn5GRZJZe1OAClYdOWm7A1CKpuo+cVV1vxbY2nGUQSJPpVn2sT9gnwvjdE60U\n' + + 'JGYU/RLCTm8zmZBvlWaNIeKDnreIc4rKn6gUnJ2cQn1ryCVleEeyc3xjYDSrjgdn\n' + + 'FLYGcp9mphqVT0byeQMOk0c7RHpxrCSA0V5V6/CreFV2LteK50qcDQzDSM18vWP/\n' + + 'p09FoN8O7QrtOeZJzH/lmwIDAQABo2YwZDAOBgNVHQ8BAf8EBAMCAQYwEgYDVR0T\n' + + 'AQH/BAgwBgEB/wIBADAdBgNVHQ4EFgQU2i83QHuEl/d0keXF+69HNJph7cMwHwYD\n' + + 'VR0jBBgwFoAUTgLurD72FchM7Sz1BcGPnIQISYMwDQYJKoZIhvcNAQELBQADggEB\n' + + 'ACqnH2VjApoDqoSQOky52QBwsGaj+xWYHW5Gm7EvCqvQuhWMkeBuD6YJmMvNyA9G\n' + + 'I2lh6/o+sUk/RIsbYbxPRdhNPTOgDR9zsNRw6qxaHztq/CEC+mxDCLa3O1hHBaDV\n' + + 'BmB3nCZb93BvO0EQSEk7aytKq/f+sjyxqOcs385gintdHGU9uM7gTZHnU9vByJsm\n' + + '/TL07Miq67X0NlhIoo3jAk+xHaeKJdxdKATQp0448P5cY20q4b8aMk1twcNaMvCP\n' + + 'dG4M5doaoUA8OQ/0ukLLae/LBxLeTw04q1/a2SyFaVUX2Twbb1S3xVWwLA8vsyGr\n' + + 'igXx7B5GgP+IHb6DTjPJAi0=\n' + + '-----END CERTIFICATE-----\n', + + /** + * Amazon RDS us-east-2 certificate CA 2016 to 2020 + * + * CN = Amazon RDS us-east-2 CA + * OU = Amazon RDS + * O = Amazon Web Services, Inc. + * L = Seattle + * ST = Washington + * C = US + * P = 2016-08-11T19:58:45Z/2020-03-05T19:58:45Z + * F = 9B:78:E3:64:7F:74:BC:B2:52:18:CF:13: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gQWBBSAHQzUYYZbepwKEMvGdHp8wzHnfDAfBgNV\n' + + 'HSMEGDAWgBROAu6sPvYVyEztLPUFwY+chAhJgzANBgkqhkiG9w0BAQsFAAOCAQEA\n' + + 'MbaEzSYZ+aZeTBxf8yi0ta8K4RdwEJsEmP6IhFFQHYUtva2Cynl4Q9tZg3RMsybT\n' + + '9mlnSQQlbN/wqIIXbkrcgFcHoXG9Odm/bDtUwwwDaiEhXVfeQom3G77QHOWMTCGK\n' + + 'qadwuh5msrb17JdXZoXr4PYHDKP7j0ONfAyFNER2+uecblHfRSpVq5UeF3L6ZJb8\n' + + 'fSw/GtAV6an+/0r+Qm+PiI2H5XuZ4GmRJYnGMhqWhBYrY7p3jtVnKcsh39wgfUnW\n' + + 'AvZEZG/yhFyAZW0Essa39LiL5VSq14Y1DOj0wgnhSY/9WHxaAo1HB1T9OeZknYbD\n' + + 'fl/EGSZ0TEvZkENrXcPlVA==\n' + + '-----END CERTIFICATE-----\n', + + /** + * Amazon RDS ca-central-1 certificate CA 2016 to 2020 + * + * CN = Amazon RDS ca-central-1 CA + * OU = Amazon RDS + * O = Amazon Web Services, Inc. + * L = Seattle + * ST = Washington + * C = US + * P = 2016-09-15T00:10:11Z/2020-03-05T00:10:11Z + * F = D7:E0:16:AB:8A:0B:63:9F:67:1F:16:87:42:F4:0A:EE:73:A6:FC:04 + */ + '-----BEGIN CERTIFICATE-----\n' + + 'MIID/zCCAuegAwIBAgIBTzANBgkqhkiG9w0BAQsFADCBijELMAkGA1UEBhMCVVMx\n' + + 'EzARBgNVBAgMCldhc2hpbmd0b24xEDAOBgNVBAcMB1NlYXR0bGUxIjAgBgNVBAoM\n' + + 'GUFtYXpvbiBXZWIgU2VydmljZXMsIEluYy4xEzARBgNVBAsMCkFtYXpvbiBSRFMx\n' + + 'GzAZBgNVBAMMEkFtYXpvbiBSRFMgUm9vdCBDQTAeFw0xNjA5MTUwMDEwMTFaFw0y\n' + + 'MDAzMDUwMDEwMTFaMIGSMQswCQY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KYkP4LLJxtj07DSzG8kuRWb9B47uqUD+eKDIyjfjbnzGtd9HqqzYFau7EX3HVD9\n' + + '9Qhnjl7bTZ6YfAEZ3nH2t3Vc0z76XfGh47rd0pNRhMV+xpok75asKf/lNh5mcUrr\n' + + 'VKwflyMkQpSbDCmcdJ90N2xEXQ==\n' + + '-----END CERTIFICATE-----\n', + + /** + * Amazon RDS eu-west-2 certificate CA 2016 to 2020 + * + * CN = Amazon RDS eu-west-2 CA + * OU = Amazon RDS + * O = Amazon Web Services, Inc. + * L = Seattle + * ST = Washington + * C = US + * P = 2016-10-10T17:44:42Z/2020-03-05T17:44:42Z + * F = 47:79:51:9F:FF:07:D3:F4:27:D3:AB:64:56:7F:00:45:BB:84:C1:71 + */ + '-----BEGIN CERTIFICATE-----\n' + + 'MIID/DCCAuSgAwIBAgIBUDANBgkqhkiG9w0BAQsFADCBijELMAkGA1UEBhMCVVMx\n' + + 'EzARBgNVBAgMCldhc2hpbmd0b24xEDAOBgNVBAcMB1NlYXR0bGUxIjAgBgNVBAoM\n' + + 'GUFtYXpvbiBXZWIgU2VydmljZXMsIEluYy4xEzARBgNVBAsMCkFtYXpvbiBSRFMx\n' + + 'GzAZBgNVBAMMEkFtYXpvbiBSRFMgUm9vdCBDQTAeFw0xNjEwMTAxNzQ0NDJaFw0y\n' + + 'MDAzMDUxNzQ0NDJaMIGPMQswCQYDVQQGEwJVUzETMBEGA1UECAwKV2FzaGluZ3Rv\n' + + 'bjEQMA4GA1UEBwwHU2VhdHRsZTEiMCAGA1UECgwZQW1hem9uIFdlYiBTZXJ2aWNl\n' + + 'cywgSW5jLjETMBEGA1UECwwKQW1hem9uIFJEUzEgMB4GA1UEAwwXQW1hem9uIFJE\n' + + 'UyBldS13ZXN0LTIgQ0EwggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQDO\n' + + 'cttLJfubB4XMMIGWNfJISkIdCMGJyOzLiMJaiWB5GYoXKhEl7YGotpy0qklwW3BQ\n' + + 'a0fmVdcCLX+dIuVQ9iFK+ZcK7zwm7HtdDTCHOCKeOh2IcnU4c/VIokFi6Gn8udM6\n' + + 'N/Zi5M5OGpVwLVALQU7Yctsn3c95el6MdVx6mJiIPVu7tCVZn88Z2koBQ2gq9P4O\n' + + 'Sb249SHFqOb03lYDsaqy1NDsznEOhaRBw7DPJFpvmw1lA3/Y6qrExRI06H2VYR2i\n' + + '7qxwDV50N58fs10n7Ye1IOxTVJsgEA7X6EkRRXqYaM39Z76R894548WHfwXWjUsi\n' + + 'MEX0RS0/t1GmnUQjvevDAgMBAAGjZjBkMA4GA1UdDwEB/wQEAwIBBjASBgNVHRMB\n' + + 'Af8ECDAGAQH/AgEAMB0GA1UdDgQWBBQBxmcuRSxERYCtNnSr5xNfySokHjAfBgNV\n' + + 'HSMEGDAWgBROAu6sPvYVyEztLPUFwY+chAhJgzANBgkqhkiG9w0BAQsFAAOCAQEA\n' + + 'UyCUQjsF3nUAABjfEZmpksTuUo07aT3KGYt+EMMFdejnBQ0+2lJJFGtT+CDAk1SD\n' + + 'RSgfEBon5vvKEtlnTf9a3pv8WXOAkhfxnryr9FH6NiB8obISHNQNPHn0ljT2/T+I\n' + + 'Y6ytfRvKHa0cu3V0NXbJm2B4KEOt4QCDiFxUIX9z6eB4Kditwu05OgQh6KcogOiP\n' + + 'JesWxBMXXGoDC1rIYTFO7szwDyOHlCcVXJDNsTJhc32oDWYdeIbW7o/5I+aQsrXZ\n' + + 'C96HykZcgWzz6sElrQxUaT3IoMw/5nmw4uWKKnZnxgI9bY4fpQwMeBZ96iHfFxvH\n' + + 'mqfEEuC7uUoPofXdBp2ObQ==\n' + + '-----END CERTIFICATE-----\n', + + /** + * Amazon RDS us-gov-west-1 CA 2017 to 2022 + * + * CN = Amazon RDS us-gov-west-1 CA + * OU = Amazon RDS + * O = Amazon Web Services, Inc. + * L = Seattle + * ST = Washington + * C = US + * P = 2017-05-19T22:31:19Z/2022-05-18T12:00:00Z + * F = 77:55:8C:C4:5E:71:1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'BAQDAgEGMBIGA1UdEwEB/wQIMAYBAf8CAQAwHQYDVR0OBBYEFEG7+br8KkvwPd5g\n' + + '71Rvh2stclJbMB8GA1UdIwQYMBaAFEkQz6S4NS5lOYKcDjBSuCcVpdzjMA0GCSqG\n' + + 'SIb3DQEBCwUAA4IBAQBMA327u5ABmhX+aPxljoIbxnydmAFWxW6wNp5+rZrvPig8\n' + + 'zDRqGQWWr7wWOIjfcWugSElYtf/m9KZHG/Z6+NG7nAoUrdcd1h/IQhb+lFQ2b5g9\n' + + 'sVzQv/H2JNkfZA8fL/Ko/Tm/f9tcqe0zrGCtT+5u0Nvz35Wl8CEUKLloS5xEb3k5\n' + + '7D9IhG3fsE3vHWlWrGCk1cKry3j12wdPG5cUsug0vt34u6rdhP+FsM0tHI15Kjch\n' + + 'RuUCvyQecy2ZFNAa3jmd5ycNdL63RWe8oayRBpQBxPPCbHfILxGZEdJbCH9aJ2D/\n' + + 'l8oHIDnvOLdv7/cBjyYuvmprgPtu3QEkbre5Hln/\n' + + '-----END CERTIFICATE-----\n', + + /** + * Amazon RDS eu-west-3 certificate CA 2017 to 2020 + * + * CN = Amazon RDS eu-west-3 CA + * OU = Amazon RDS + * O = Amazon Web Services, Inc. + * L = Seattle + * ST = Washington + * C = US + * P = 2017-08-25T21:39:26Z/2020-03-05T21:39:26Z + * F = FD:35:A7:84:60:68:98:00:12:54:ED:34:26:8C:66:0F:72:DD:B2:F4 + */ + '-----BEGIN CERTIFICATE-----\n' + + 'MIID/DCCAuSgAwIBAgIBUTANBgkqhkiG9w0BAQsFADCBijELMAkGA1UEBhMCVVMx\n' + + 'EzARBgNVBAgMCldhc2hpbmd0b24xEDAOBgNVBAcMB1NlYXR0bGUxIjAgBgNVBAoM\n' + + 'GUFtYXpvbiBXZWIgU2VydmljZXMsIEluYy4xEzARBgNVBAsMCkFtYXpvbiBSRFMx\n' + + 'GzAZBgNVBAMMEkFtYXpvbiBSRFMgUm9vdCBDQTAeFw0xNzA4MjUyMTM5Mj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IvlVMa4x0Tz0\n' + + 'A4fklaawryngzeEjuW6zOiYCzjZtPlP8Fw0SpzppJ8VpQfrZ751RDo4yudmPqoPK\n' + + '5EUe36L8U+oYBXnC5TlYs9bpVv9o5wJQI5qA9oQE2eFWxF1E0AyZ4V5sgGUBStaX\n' + + 'BjDDWul0wSo7rt1Tq7XpnA==\n' + + '-----END CERTIFICATE-----\n', + + /** + * Amazon RDS ap-northeast-3 certificate CA 2017 to 2020 + * + * CN = Amazon RDS ap-northeast-3 CA + * OU = Amazon RDS + * O = Amazon Web Services, Inc. + * L = Seattle + * ST = Washington + * C = US + * P = 2017-12-01T00:55:42Z/2020-03-05T00:55:42Z + * F = C0:C7:D4:B3:91:40:A0:77:43:28:BF:AF:77:57:DF:FD:98:FB:10:3F + */ + '-----BEGIN CERTIFICATE-----\n' + + 'MIIEATCCAumgAwIBAgIBTjANBgkqhkiG9w0BAQUFADCBijELMAkGA1UEBhMCVVMx\n' + + 'EzARBgNVBAgMCldhc2hpbmd0b24xEDAOBgNVBAcMB1NlYXR0bGUxIjAgBgNVBAoM\n' + + 'GUFtYXpvbiBXZWIgU2VydmljZXMsIEluYy4xEzARBgNVBAsMCkFtYXpvbiBSRFMx\n' + + 'GzAZBgNVBAMMEkFtYXpvbiBSRFMgUm9vdCBDQTAeFw0xNzEyMDEwMDU1NDJaFw0y\n' + + 'MDAzMDUwMDU1NDJaMIGUMQswCQYDVQQGEwJVUzETMBEGA1UECAwKV2FzaGluZ3Rv\n' + + 'bjEQMA4GA1UEBwwHU2VhdHRsZTEiMCAGA1UECgwZQW1hem9uIFdlYiBTZXJ2aWNl\n' + + 'cywgSW5jLjETMBEGA1UECwwKQW1hem9uIFJEUzElMCMGA1UEAwwcQW1hem9uIFJE\n' + + 'UyBhcC1ub3J0aGVhc3QtMyBDQTCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoC\n' + + 'ggEBAMZtQNnm/XT19mTa10ftHLzg5UhajoI65JHv4TQNdGXdsv+CQdGYU49BJ9Eu\n' + + '3bYgiEtTzR2lQe9zGMvtuJobLhOWuavzp7IixoIQcHkFHN6wJ1CvqrxgvJfBq6Hy\n' + + 'EuCDCiU+PPDLUNA6XM6Qx3IpHd1wrJkjRB80dhmMSpxmRmx849uFafhN+P1QybsM\n' + + 'TI0o48VON2+vj+mNuQTyLMMP8D4odSQHjaoG+zyJfJGZeAyqQyoOUOFEyQaHC3TT\n' + + '3IDSNCQlpxb9LerbCoKu79WFBBq3CS5cYpg8/fsnV2CniRBFFUumBt5z4dhw9RJU\n' + + 'qlUXXO1ZyzpGd+c5v6FtrfXtnIUCAwEAAaNmMGQwDgYDVR0PAQH/BAQDAgEGMBIG\n' + + 'A1UdEwEB/wQIMAYBAf8CAQAwHQYDVR0OBBYEFETv7ELNplYy/xTeIOInl6nzeiHg\n' + + 'MB8GA1UdIwQYMBaAFE4C7qw+9hXITO0s9QXBj5yECEmDMA0GCSqGSIb3DQEBBQUA\n' + + 'A4IBAQCpKxOQcd0tEKb3OtsOY8q/MPwTyustGk2Rt7t9G68idADp8IytB7M0SDRo\n' + + 'wWZqynEq7orQVKdVOanhEWksNDzGp0+FPAf/KpVvdYCd7ru3+iI+V4ZEp2JFdjuZ\n' + + 'Zz0PIjS6AgsZqE5Ri1J+NmfmjGZCPhsHnGZiBaenX6K5VRwwwmLN6xtoqrrfR5zL\n' + + 'QfBeeZNJG6KiM3R/DxJ5rAa6Fz+acrhJ60L7HprhB7SFtj1RCijau3+ZwiGmUOMr\n' + + 'yKlMv+VgmzSw7o4Hbxy1WVrA6zQsTHHSGf+vkQn2PHvnFMUEu/ZLbTDYFNmTLK91\n' + + 'K6o4nMsEvhBKgo4z7H1EqqxXhvN2\n' + + '-----END CERTIFICATE-----\n', + + /** + * Amazon RDS GovCloud Root CA 2017 to 2022 + * + * CN = Amazon RDS GovCloud Root CA + * OU = Amazon RDS + * O = Amazon Web Services, Inc. + * L = Seattle + * ST = Washington + * C = US + * P = 2017-05-19T22:29:11Z/2022-05-18T22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BAAGjYzBhMA4G\n' + + 'A1UdDwEB/wQEAwIBBjAPBgNVHRMBAf8EBTADAQH/MB0GA1UdDgQWBBRJEM+kuDUu\n' + + 'ZTmCnA4wUrgnFaXc4zAfBgNVHSMEGDAWgBRJEM+kuDUuZTmCnA4wUrgnFaXc4zAN\n' + + 'BgkqhkiG9w0BAQsFAAOCAQEAcfA7uirXsNZyI2j4AJFVtOTKOZlQwqbyNducnmlg\n' + + '/5nug9fAkwM4AgvF5bBOD1Hw6khdsccMwIj+1S7wpL+EYb/nSc8G0qe1p/9lZ/mZ\n' + + 'ff5g4JOa26lLuCrZDqAk4TzYnt6sQKfa5ZXVUUn0BK3okhiXS0i+NloMyaBCL7vk\n' + + 'kDwkHwEqflRKfZ9/oFTcCfoiHPA7AdBtaPVr0/Kj9L7k+ouz122huqG5KqX0Zpo8\n' + + 'S0IGvcd2FZjNSNPttNAK7YuBVsZ0m2nIH1SLp//00v7yAHIgytQwwB17PBcp4NXD\n' + + 'pCfTa27ng9mMMC2YLqWQpW4TkqjDin2ZC+5X/mbrjzTvVg==\n' + + '-----END CERTIFICATE-----\n', + + /** + * Amazon RDS ap-east-1 certificate CA 2019 to 2022 + * + * CN = Amazon RDS ap-east-1 CA + * OU = Amazon RDS + * O = Amazon Web Services, Inc. + * L = Seattle + * ST = Washington + * C = US + * P = 2019-02-17T02:47:00Z/2022-06-01T12:00:00Z + * F = BC:F8:70:75:1F:93:3F:A7:82:86:67:63:A8:86:1F:A4:E8:07:CE:06 + */ + '-----BEGIN CERTIFICATE-----\n' + + 'MIIEBzCCAu+gAwIBAgICEAAwDQYJKoZIhvcNAQELBQAwgZQxCzAJBgNVBAYTAlVT\n' + + 'MRAwDgYDVQQHDAdTZWF0dGxlMRMwEQYDVQQIDApXYXNoaW5ndG9uMSIwIAYDVQQK\n' + + 'DBlBbWF6b24gV2ViIFNlcnZpY2VzLCBJbmMuMRMwEQYDVQQLDApBbWF6b24gUkRT\n' + + 'MSUwIwYDVQQDDBxBbWF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VQy7vzeFku/SisKwX0Lov1oHD4MVhJoHbUJYkmAjxorcIHORvh\n' + + 'I3Vj5XrgDWtLDPL8/Id/roul/L+WX5ir+PGScKBfQIIN2lWdZoqdsx8YWqhm/ikL\n' + + 'C6qNieSwcvWL7C03ri0DefTQMY54r5wP33QU5hJ71JoaZI3YTeT0Nf+NRL4hM++w\n' + + 'Q0veeNzBQXg1f/JxfeA39IDIX1kiCf71tGlT\n' + + '-----END CERTIFICATE-----\n', + + /** + * Amazon RDS ap-northeast-1 certificate CA 2019 to 2024 + * + * CN = Amazon RDS ap-northeast-1 2019 CA + * OU = Amazon RDS + * O = Amazon Web Services, Inc. + * L = Seattle + * ST = Washington + * C = US + * P = 2019-09-18T16:56:20Z/2024-08-22T17:08:50Z + * F = 47:A3:F9:20:64:5C:9F:9D:48:8C:7D:E6:0B:86:D6:05:13:00:16:A1 + */ + '-----BEGIN CERTIFICATE-----\n' + + 'MIIEDDCCAvSgAwIBAgICcEUwDQYJKoZIhvcNAQELBQAwgY8xCzAJBgNVBAYTAlVT\n' + + 'MRAwDgYDVQQHDAdTZWF0dGxlMRMwEQYDVQQIDApXYXNoaW5ndG9uMSIwIAYDVQQK\n' + + 'DBlBbWF6b24gV2ViIFNlcnZpY2VzLCBJbmMuMRMwEQYDVQQLDApBbWF6b24gUkRT\n' + + 'MSAwHgYDVQQDDBdBbWF6b24gUkRTIFJvb3QgMjAxOSBDQTAeFw0xOTA5MTgxNjU2\n' + + 'MjBaFw0yNDA4MjIxNzA4NTBaMIGZMQswCQYDVQQGEwJVUzETMBEGA1UECAwKV2Fz\n' + + 'aGluZ3RvbjEQMA4GA1UEBwwHU2VhdHRsZTEiMCAGA1UECgwZQW1hem9uIFdlYiBT\n' + + 'ZXJ2aWNlcywgSW5jLjETMBEGA1UECwwKQW1hem9uIFJEUzEqMCgGA1UEAwwhQW1h\n' + + 'em9uIFJEUyBhcC1ub3J0aGVhc3QtMSAyMDE5IENBMIIBIjANBgkqhkiG9w0BAQEF\n' + + 'AAOCAQ8AMIIBCgKCAQEAndtkldmHtk4TVQAyqhAvtEHSMb6pLhyKrIFved1WO3S7\n' + + '+I+bWwv9b2W/ljJxLq9kdT43bhvzonNtI4a1LAohS6bqyirmk8sFfsWT3akb+4Sx\n' + + '1sjc8Ovc9eqIWJCrUiSvv7+cS7ZTA9AgM1PxvHcsqrcUXiK3Jd/Dax9jdZE1e15s\n' + + 'BEhb2OEPE+tClFZ+soj8h8Pl2Clo5OAppEzYI4LmFKtp1X/BOf62k4jviXuCSst3\n' + + 'UnRJzE/CXtjmN6oZySVWSe0rQYuyqRl6//9nK40cfGKyxVnimB8XrrcxUN743Vud\n' + + 'QQVU0Esm8OVTX013mXWQXJHP2c0aKkog8LOga0vobQIDAQABo2YwZDAOBgNVHQ8B\n' + + 'Af8EBAMCAQYwEgYDVR0TAQH/BAgwBgEB/wIBADAdBgNVHQ4EFgQULmoOS1mFSjj+\n' + + 'snUPx4DgS3SkLFYwHwYDVR0jBBgwFoAUc19g2LzLA5j0Kxc0LjZapmD/vB8wDQYJ\n' + + 'KoZIhvcNAQELBQADggEBAAkVL2P1M2/G9GM3DANVAqYOwmX0Xk58YBHQu6iiQg4j\n' + + 'b4Ky/qsZIsgT7YBsZA4AOcPKQFgGTWhe9pvhmXqoN3RYltN8Vn7TbUm/ZVDoMsrM\n' + + 'gwv0+TKxW1/u7s8cXYfHPiTzVSJuOogHx99kBW6b2f99GbP7O1Sv3sLq4j6lVvBX\n' + + 'Fiacf5LAWC925nvlTzLlBgIc3O9xDtFeAGtZcEtxZJ4fnGXiqEnN4539+nqzIyYq\n' + + 'nvlgCzyvcfRAxwltrJHuuRu6Maw5AGcd2Y0saMhqOVq9KYKFKuD/927BTrbd2JVf\n' + + '2sGWyuPZPCk3gq+5pCjbD0c6DkhcMGI6WwxvM5V/zSM=\n' + + '-----END CERTIFICATE-----\n', + + /** + * Amazon RDS ap-northeast-2 certificate CA 2019 to 2024 + * + * CN = Amazon RDS ap-northeast-2 2019 CA + * OU = Amazon RDS + * O = Amazon Web Services, Inc. + * L = Seattle + * ST = Washington + * C = US + * P = 2019-09-10T17:46:21Z/2024-08-22T17:08:50Z + * F = 8E:1C:70:C1:64:BD:FC:F9:93:9B:A2:67:CA:CF:52:F0:E1:F7:B4:F0 + */ + '-----BEGIN CERTIFICATE-----\n' + + 'MIIEDDCCAvSgAwIBAgICOFAwDQYJKoZIhvcNAQELBQAwgY8xCzAJBgNVBAYTAlVT\n' + + 'MRAwDgYDVQQHDAdTZWF0dGxlMRMwEQYDVQQIDApXYXNoaW5ndG9uMSIwIAYDVQQK\n' + + 'DBlBbWF6b24gV2ViIFNlcnZpY2VzLCBJbmMuMRMwEQYDVQQLDApBbWF6b24gUkRT\n' + + 'MSAwHgYDVQQDDBdBbWF6b24gUkRTIFJvb3QgMjAxOSBDQTAeFw0xOTA5MTAxNzQ2\n' + + 'MjFaFw0yNDA4MjIxNzA4NTBaMIGZMQswCQYDVQQGEwJVUzETMBEGA1UECAwKV2Fz\n' + + 'aGluZ3RvbjEQMA4GA1UEBwwHU2VhdHRsZTEiMCAGA1UECgwZQW1hem9uIFdlYiBT\n' + + 'ZXJ2aWNlcywgSW5jLjETMBEGA1UECwwKQW1hem9uIFJEUzEqMCgGA1UEAwwhQW1h\n' + + 'em9uIFJEUyBhcC1ub3J0aGVhc3QtMiAyMDE5IENBMIIBIjANBgkqhkiG9w0BAQEF\n' + + 'AAOCAQ8AMIIBCgKCAQEAzU72e6XbaJbi4HjJoRNjKxzUEuChKQIt7k3CWzNnmjc5\n' + + '8I1MjCpa2W1iw1BYVysXSNSsLOtUsfvBZxi/1uyMn5ZCaf9aeoA9UsSkFSZBjOCN\n' + + 'DpKPCmfV1zcEOvJz26+1m8WDg+8Oa60QV0ou2AU1tYcw98fOQjcAES0JXXB80P2s\n' + + '3UfkNcnDz+l4k7j4SllhFPhH6BQ4lD2NiFAP4HwoG6FeJUn45EPjzrydxjq6v5Fc\n' + + 'cQ8rGuHADVXotDbEhaYhNjIrsPL+puhjWfhJjheEw8c4whRZNp6gJ/b6WEes/ZhZ\n' + + 'h32DwsDsZw0BfRDUMgUn8TdecNexHUw8vQWeC181hwIDAQABo2YwZDAOBgNVHQ8B\n' + + 'Af8EBAMCAQYwEgYDVR0TAQH/BAgwBgEB/wIBADAdBgNVHQ4EFgQUwW9bWgkWkr0U\n' + + 'lrOsq2kvIdrECDgwHwYDVR0jBBgwFoAUc19g2LzLA5j0Kxc0LjZapmD/vB8wDQYJ\n' + + 'KoZIhvcNAQELBQADggEBAEugF0Gj7HVhX0ehPZoGRYRt3PBuI2YjfrrJRTZ9X5wc\n' + + '9T8oHmw07mHmNy1qqWvooNJg09bDGfB0k5goC2emDiIiGfc/kvMLI7u+eQOoMKj6\n' + + 'mkfCncyRN3ty08Po45vTLBFZGUvtQmjM6yKewc4sXiASSBmQUpsMbiHRCL72M5qV\n' + + 'obcJOjGcIdDTmV1BHdWT+XcjynsGjUqOvQWWhhLPrn4jWe6Xuxll75qlrpn3IrIx\n' + + 'CRBv/5r7qbcQJPOgwQsyK4kv9Ly8g7YT1/vYBlR3cRsYQjccw5ceWUj2DrMVWhJ4\n' + + 'prf+E3Aa4vYmLLOUUvKnDQ1k3RGNu56V0tonsQbfsaM=\n' + + '-----END CERTIFICATE-----\n', + + /** + * Amazon RDS ap-northeast-3 certificate CA 2019 to 2024 + * + * CN = Amazon RDS ap-northeast-3 2019 CA + * OU = Amazon RDS + * O = Amazon Web Services, Inc. + * L = Seattle + * ST = Washington + * C = US + * P = 2019-09-17T20:05:29Z/2024-08-22T17:08:50Z + * F = D1:08:B1:40:6D:6C:80:8E:F4:C1:2C:8A:1F:66:17:01:54:CD:1A:4E + */ + '-----BEGIN CERTIFICATE-----\n' + + 'MIIEDDCCAvSgAwIBAgICOYIwDQYJKoZIhvcNAQELBQAwgY8xCzAJBgNVBAYTAlVT\n' + + 'MRAwDgYDVQQHDAdTZWF0dGxlMRMwEQYDVQQIDApXYXNoaW5ndG9uMSIwIAYDVQQK\n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mXS+w\n' + + 'G0zh4v2hBZOf91l1EO0rwFD7+fxoI6hzQfMxIczh875T6vUXePKVOCOKI5wCrDad\n' + + 'zQbVqbFbdhsBjF4aUilOdtw2qjjs9JwPuB0VXN4/jY7m21oKEOcnpe36+7OiSPjN\n' + + 'xngYewCXKrSRqoj3mw+0w/+exYj3Wsush7uFssX18av78G+ehKPIVDXptOCP/N7W\n' + + '8iKVNeQ2QGTnu2fzWsGUSvMGyM7yqT+h1ILaT//yQS8er511aHMLc142bD4D9VSy\n' + + 'DgactwPDTShK/PXqhvNey9v/sKXm4XatZvwcc8KYlW4=\n' + + '-----END CERTIFICATE-----\n', + + /** + * Amazon RDS ap-south-1 certificate CA 2019 to 2024 + * + * CN = Amazon RDS ap-south-1 2019 CA + * OU = Amazon RDS + * O = Amazon Web Services, Inc. + * L = Seattle + * ST = Washington + * C = US + * P = 2019-09-04T17:13:04Z/2024-08-22T17:08:50Z + * F = D6:AD:45:A9:54:36:E4:BA:9C:B7:9B:06:8C:0C:CD:CC:1E:81:B5:00 + */ + '-----BEGIN CERTIFICATE-----\n' + + 'MIIECDCCAvCgAwIBAgICVIYwDQYJKoZIhvcNAQELBQAwgY8xCzAJBgNVBAYTAlVT\n' + + 'MRAwDgYDVQQHDAdTZWF0dGxlMRMwEQYDVQQIDApXYXNoaW5ndG9uMSIwIAYDVQQK\n' + + 'DBlBbWF6b24gV2ViIFNlcnZpY2VzLCBJbmMuMRMwEQYDVQQLDApBbWF6b24gUkRT\n' + + 'MSAwHgYDVQQDDBdBbWF6b24gUkRTIFJvb3QgMjAxOSBDQTAeFw0xOTA5MDQxNzEz\n' + + 'MDRaFw0yNDA4MjIxNzA4NTBaMIGVMQswCQYDVQQGEwJVUzETMBEGA1UECAwKV2Fz\n' + + 'aGluZ3RvbjEQMA4GA1UEBwwHU2VhdHRsZTEiMCAGA1UECgwZQW1hem9uIFdlYiBT\n' + + 'ZXJ2aWNlcywgSW5jLjETMBEGA1UECwwKQW1hem9uIFJEUzEm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n' + + '-----END CERTIFICATE-----\n', + + /** + * Amazon RDS ap-southeast-1 certificate CA 2019 to 2024 + * + * CN = Amazon RDS ap-southeast-1 2019 CA + * OU = Amazon RDS + * O = Amazon Web Services, Inc. + * L = Seattle + * ST = Washington + * C = US + * P = 2019-09-13T20:11:42Z/2024-08-22T17:08:50Z + * F = 0D:20:FB:91:DE:BE:D2:CF:F3:F8:F8:43:AF:68:C6:03:76:F3:DD:B8 + */ + '-----BEGIN CERTIFICATE-----\n' + + 'MIIEDDCCAvSgAwIBAgICY4kwDQYJKoZIhvcNAQELBQAwgY8xCzAJBgNVBAYTAlVT\n' + + 'MRAwDgYDVQQHDAdTZWF0dGxlMRMwEQYDVQQIDApXYXNoaW5ndG9uMSIwIAYDVQQK\n' + + 'DBlBbWF6b24gV2ViIFNlcnZpY2VzLCBJbmMuMRMwEQYDVQQLDApBbWF6b24gUkRT\n' + + 'MSAwHgYDVQQDDBdBbWF6b24gUkRTIFJvb3QgMjAxOSBDQTAeFw0xOTA5MTMyMDEx\n' + + 'NDJaFw0yNDA4MjIxNzA4NTBaMIGZMQswCQYDVQQGEwJVUzETMBEGA1UECAwKV2Fz\n' + + 'aGluZ3RvbjEQMA4GA1UEBwwHU2VhdHRsZTEiMCAGA1UECgwZQW1hem9uIFdlYiBT\n' + + 'ZXJ2aWNlcywgSW5jLjETMBEGA1UECwwKQW1hem9uIFJEUzEqMCgGA1UEAwwhQW1h\n' + + 'em9uIFJEUyBhcC1zb3V0aGVhc3QtMSAyMDE5IENBMIIBIjANBgkqhkiG9w0BAQEF\n' + + 'AAOCAQ8AMIIBCgKCAQEAr5u9OuLL/OF/fBNUX2kINJLzFl4DnmrhnLuSeSnBPgbb\n' + + 'qddjf5EFFJBfv7IYiIWEFPDbDG5hoBwgMup5bZDbas+ZTJTotnnxVJTQ6wlhTmns\n' + + 'eHECcg2pqGIKGrxZfbQhlj08/4nNAPvyYCTS0bEcmQ1emuDPyvJBYDDLDU6AbCB5\n' + + '6Z7YKFQPTiCBblvvNzchjLWF9IpkqiTsPHiEt21sAdABxj9ityStV3ja/W9BfgxH\n' + + 'wzABSTAQT6FbDwmQMo7dcFOPRX+hewQSic2Rn1XYjmNYzgEHisdUsH7eeXREAcTw\n' + + '61TRvaLH8AiOWBnTEJXPAe6wYfrcSd1pD0MXpoB62wIDAQABo2YwZDAOBgNVHQ8B\n' + + 'Af8EBAMCAQYwEgYDVR0TAQH/BAgwBgEB/wIBADAdBgNVHQ4EFgQUytwMiomQOgX5\n' + + 'Ichd+2lDWRUhkikwHwYDVR0jBBgwFoAUc19g2LzLA5j0Kxc0LjZapmD/vB8wDQYJ\n' + + 'KoZIhvcNAQELBQADggEBACf6lRDpfCD7BFRqiWM45hqIzffIaysmVfr+Jr+fBTjP\n' + + 'uYe/ba1omSrNGG23bOcT9LJ8hkQJ9d+FxUwYyICQNWOy6ejicm4z0C3VhphbTPqj\n' + + 'yjpt9nG56IAcV8BcRJh4o/2IfLNzC/dVuYJV8wj7XzwlvjysenwdrJCoLadkTr1h\n' + + 'eIdG6Le07sB9IxrGJL9e04afk37h7c8ESGSE4E+oS4JQEi3ATq8ne1B9DQ9SasXi\n' + + 'IRmhNAaISDzOPdyLXi9N9V9Lwe/DHcja7hgLGYx3UqfjhLhOKwp8HtoZORixAmOI\n' + + 'HfILgNmwyugAbuZoCazSKKBhQ0wgO0WZ66ZKTMG8Oho=\n' + + '-----END CERTIFICATE-----\n', + + /** + * Amazon RDS ap-southeast-2 certificate CA 2019 to 2024 + * + * CN = Amazon RDS ap-southeast-2 2019 CA + * OU = Amazon RDS + * O = Amazon Web Services, Inc. + * L = Seattle + * ST = Washington + * C = US + * P = 2019-09-16T19:53:47Z/2024-08-22T17:08:50Z + * F = D5:D4:51:83:D9:A3:AC:47:B0:0A:5A:77:D8:A0:79:A9:6A:3F:6D:96 + */ + '-----BEGIN CERTIFICATE-----\n' + + 'MIIEDDCCAvSgAwIBAgICEkYwDQYJKoZIhvcNAQELBQAwgY8xCzAJBgNVBAY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B8wDQYJ\n' + + 'KoZIhvcNAQELBQADggEBAAR6a2meCZuXO2TF9bGqKGtZmaah4pH2ETcEVUjkvXVz\n' + + 'sl+ZKbYjrun+VkcMGGKLUjS812e7eDF726ptoku9/PZZIxlJB0isC/0OyixI8N4M\n' + + 'NsEyvp52XN9QundTjkl362bomPnHAApeU0mRbMDRR2JdT70u6yAzGLGsUwMkoNnw\n' + + '1VR4XKhXHYGWo7KMvFrZ1KcjWhubxLHxZWXRulPVtGmyWg/MvE6KF+2XMLhojhUL\n' + + '+9jB3Fpn53s6KMx5tVq1x8PukHmowcZuAF8k+W4gk8Y68wIwynrdZrKRyRv6CVtR\n' + + 'FZ8DeJgoNZT3y/GT254VqMxxfuy2Ccb/RInd16tEvVk=\n' + + '-----END CERTIFICATE-----\n', + + /** + * Amazon RDS ca-central-1 certificate CA 2019 to 2024 + * + * CN = Amazon RDS ca-central-1 2019 CA + * OU = Amazon RDS + * O = Amazon Web Services, Inc. + * L = Seattle + * ST = Washington + * C = US + * P = 2019-09-10T20:52:25Z/2024-08-22T17:08:50Z + * F = A1:03:46:F2:BB:29:BF:4F:EC:04:7E:82:9A:A6:C0:11:4D:AB:82:25 + */ + '-----BEGIN CERTIFICATE-----\n' + + 'MIIECjCCAvKgAwIBAgICEzUwDQYJKoZIhvcNAQELBQAwgY8xCzAJBgNVBAYTAlVT\n' + + 'MRAwDgYDVQQHDAdTZWF0dGxlMRMwEQYDVQQIDApXYXNoaW5ndG9uMSIwIAYDVQQK\n' + + 'DBlBbWF6b24gV2ViIFNlcnZpY2VzLCBJbmMuMRMwEQYDVQQLDApBbWF6b24gUkRT\n' + + 'MSAwHgYDVQQDDBdBbWF6b24gUkRTIFJvb3QgMjAxOSBDQTAeFw0xOTA5MTAyMDUy\n' + + 'MjVaFw0yNDA4MjIxNzA4NTBaMIGXMQswCQYDVQQGEwJVUzETMBEGA1UECAwKV2Fz\n' + + 'aGluZ3RvbjEQMA4GA1UEBwwHU2VhdHRsZTEiMCAGA1U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Uy67AnhjGx7jw/0YPPxopEj6x\n' + + 'JXP8j0sJbcT9K/9/fPVLNT25RvQ/93T2+IQL4Ca2\n' + + '-----END CERTIFICATE-----\n', + + /** + * Amazon RDS eu-central-1 certificate CA 2019 to 2024 + * + * CN = Amazon RDS eu-central-1 2019 CA + * OU = Amazon RDS + * O = Amazon Web Services, Inc. + * L = Seattle + * ST = Washington + * C = US + * P = 2019-09-11T19:36:20Z/2024-08-22T17:08:50Z + * F = 53:46:18:4A:42:65:A2:8C:5F:5B:0A:AD:E2:2C:80:E5:E6:8A:6D:2F + */ + '-----BEGIN CERTIFICATE-----\n' + + 'MIIECjCCAvKgAwIBAgICV2YwDQYJKoZIhvcNAQELBQAwgY8xCzAJBgNVBAYTAlVT\n' + + 'MRAwDgYDVQQHDAdTZWF0dGxlMRMwEQYDVQQIDApXYXNoaW5ndG9uMSIwIAYDVQQK\n' + + 'DBlBbWF6b24gV2ViIFNlcnZpY2VzLCBJbmMuMRMwEQYDVQQLDApBbWF6b24gUkRT\n' + + 'MSAwHgYDVQQDDBdBbWF6b24gUkRTIFJvb3QgMjAxOSBDQTAeFw0xOTA5MTExOTM2\n' + + 'MjBaFw0yNDA4MjIxNzA4NTBaMIGXMQswCQYDVQQGEwJVUzETMBEGA1UECAwKV2Fz\n' + + 'aGluZ3RvbjEQMA4GA1UEBwwHU2VhdHRsZTEiMCAGA1UECgwZQW1hem9uIFdlYiBT\n' + + 'ZXJ2aWNlcywgSW5jLjETMBEGA1UECwwKQW1hem9uIFJEUzEoMCYGA1UEAwwfQW1h\n' + + 'em9uIFJEUyBldS1jZW50cmFsLTEgMjAxOSBDQTCCASIwDQYJKoZIhvcNAQEBBQAD\n' + + 'ggEPADCCAQoCggEBAMEx54X2pHVv86APA0RWqxxRNmdkhAyp2R1cFWumKQRofoFv\n' + + 'n+SPXdkpIINpMuEIGJANozdiEz7SPsrAf8WHyD93j/ZxrdQftRcIGH41xasetKGl\n' + + 'I67uans8d+pgJgBKGb/Z+B5m+UsIuEVekpvgpwKtmmaLFC/NCGuSsJoFsRqoa6Gh\n' + + 'm34W6yJoY87UatddCqLY4IIXaBFsgK9Q/wYzYLbnWM6ZZvhJ52VMtdhcdzeTHNW0\n' + + '5LGuXJOF7Ahb4JkEhoo6TS2c0NxB4l4MBfBPgti+O7WjR3FfZHpt18A6Zkq6A2u6\n' + + 'D/oTSL6c9/3sAaFTFgMyL3wHb2YlW0BPiljZIqECAwEAAaNmMGQwDgYDVR0PAQH/\n' + + 'BAQDAgEGMBIGA1UdEwEB/wQIMAYBAf8CAQAwHQYDVR0OBBYEFOcAToAc6skWffJa\n' + + 'TnreaswAfrbcMB8GA1UdIwQYMBaAFHNfYNi8ywOY9CsXNC42WqZg/7wfMA0GCSqG\n' + + 'SIb3DQEBCwUAA4IBAQA1d0Whc1QtspK496mFWfFEQNegLh0a9GWYlJm+Htcj5Nxt\n' + + 'DAIGXb+8xrtOZFHmYP7VLCT5Zd2C+XytqseK/+s07iAr0/EPF+O2qcyQWMN5KhgE\n' + + 'cXw2SwuP9FPV3i+YAm11PBVeenrmzuk9NrdHQ7TxU4v7VGhcsd2C++0EisrmquWH\n' + + 'mgIfmVDGxphwoES52cY6t3fbnXmTkvENvR+h3rj+fUiSz0aSo+XZUGHPgvuEKM/W\n' + + 'CBD9Smc9CBoBgvy7BgHRgRUmwtABZHFUIEjHI5rIr7ZvYn+6A0O6sogRfvVYtWFc\n' + + 'qpyrW1YX8mD0VlJ8fGKM3G+aCOsiiPKDV/Uafrm+\n' + + '-----END CERTIFICATE-----\n', + + /** + * Amazon RDS eu-north-1 certificate CA 2019 to 2024 + * + * CN = Amazon RDS eu-north-1 2019 CA + * OU = Amazon RDS + * O = Amazon Web Services, Inc. + * L = Seattle + * ST = Washington + * C = US + * P = 2019-09-12T18:19:44Z/2024-08-22T17:08:50Z + * F = D0:CA:9C:6E:47:4C:4F:DB:85:28:03:4A:60:AC:14:E0:E6:DF:D4:42 + */ + '-----BEGIN CERTIFICATE-----\n' + + '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lc0PogzTAfBgNVHSMEGDAWgBRzX2DYvMsDmPQrFzQuNlqmYP+8HzANBgkqhkiG\n' + + '9w0BAQsFAAOCAQEAKJD4xVzSf4zSGTBJrmamo86jl1NHQxXUApAZuBZEc8tqC6TI\n' + + 'T5CeoSr9CMuVC8grYyBjXblC4OsM5NMvmsrXl/u5C9dEwtBFjo8mm53rOOIm1fxl\n' + + 'I1oYB/9mtO9ANWjkykuLzWeBlqDT/i7ckaKwalhLODsRDO73vRhYNjsIUGloNsKe\n' + + 'pxw3dzHwAZx4upSdEVG4RGCZ1D0LJ4Gw40OfD69hfkDfRVVxKGrbEzqxXRvovmDc\n' + + 'tKLdYZO/6REoca36v4BlgIs1CbUXJGLSXUwtg7YXGLSVBJ/U0+22iGJmBSNcoyUN\n' + + 'cjPFD9JQEhDDIYYKSGzIYpvslvGc4T5ISXFiuQ==\n' + + '-----END CERTIFICATE-----\n', + + /** + * Amazon RDS eu-west-1 certificate CA 2019 to 2024 + * + * CN = Amazon RDS eu-west-1 2019 CA + * OU = Amazon RDS + * O = Amazon Web Services, Inc. + * L = Seattle + * ST = Washington + * C = US + * P = 2019-09-11T17:31:48Z/2024-08-22T17:08:50Z + * F = 2D:1A:A6:3E:0D:EB:D6:26:03:3E:A1:8A:0A:DF:14:80:78:EC:B6:63 + */ + '-----BEGIN CERTIFICATE-----\n' + + 'MIIEBzCCAu+gAwIBAgICYpgwDQYJKoZIhvcNAQELBQAwgY8xCzAJBgNVBAYTAlVT\n' + + 'MRAwDgYDVQQHDAdTZWF0dGxlMRMwEQYDVQQIDApXYXNoaW5ndG9uMSIwIAYDVQQK\n' + + 'DBlBbWF6b24gV2ViIFNlcnZpY2VzLCBJbmMuMRMwEQYDVQQLDApBbWF6b24gUkRT\n' + + 'MSAwHgYDVQQDDBdBbWF6b24gUkRTIFJvb3QgMjAxOSBDQTAeFw0xOTA5MTExNzMx\n' + + 'NDhaFw0yNDA4MjIxNzA4NTBaMIGUMQswCQYDVQQGEwJVUzETMBE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3JpbhnYiK+9\n' + + 'nRKd4uWl62KRZjGkfMbmsqZpj2fdSWMY1UGyN1k+kDmCSWYdrTRDP0xjtIocwg+A\n' + + 'J116n4hV/5mbA0BaPiS2krtv17YAeHABZcvz\n' + + '-----END CERTIFICATE-----\n', + + /** + * Amazon RDS eu-west-2 certificate CA 2019 to 2024 + * + * CN = Amazon RDS eu-west-2 2019 CA + * OU = Amazon RDS + * O = Amazon Web Services, Inc. + * L = Seattle + * ST = Washington + * C = US + * P = 2019-09-12T21:32:32Z/2024-08-22T17:08:50Z + * F = 60:65:44:F4:74:6E:2E:29:50:19:38:7C:4B:BE:18:B9:5B:D4:CD:23 + */ + '-----BEGIN CERTIFICATE-----\n' + + 'MIIEBzCCAu+gAwIBAgICZIEwDQYJKoZIhvcNAQELBQAwgY8xCzAJBgNVBAYTAlVT\n' + + 'MRAwDgYDVQQHDAdTZWF0dGxlMRMwEQYDVQQIDApXYXNoaW5ndG9uMSIwIAYDVQQK\n' + + 'DBlBbWF6b24gV2ViIFNlcnZpY2VzLCBJbmMuMRMwEQYDVQQLDApBbWF6b24gUkRT\n' + + 'MSAwHgYDVQQDDBdBbWF6b24gUkRTIFJvb3QgMjAxOSBDQTAeFw0xOTA5MTIyMTMy\n' + + 'MzJaFw0yNDA4MjIxNzA4NTBaMIGUMQswCQYDVQQGEwJVUzETMBEGA1UECAwKV2Fz\n' + + 'aGluZ3RvbjEQMA4GA1UEBwwHU2VhdHRsZTEiMCAGA1UECgwZQW1hem9uIFdlYiBT\n' + + 'ZXJ2aWNlcywgSW5jLjETMBEGA1UECwwKQW1hem9uIFJEUzElMCMGA1UEAwwcQW1h\n' + + 'em9uIFJEUyBldS13ZXN0LTIgMjAxOSBDQTCCASIwDQYJKoZIhvcNAQEBBQADggEP\n' + + 'ADCCAQoCggEBALGiwqjiF7xIjT0Sx7zB3764K2T2a1DHnAxEOr+/EIftWKxWzT3u\n' + + 'PFwS2eEZcnKqSdRQ+vRzonLBeNLO4z8aLjQnNbkizZMBuXGm4BqRm1Kgq3nlLDQn\n' + + '7YqdijOq54SpShvR/8zsO4sgMDMmHIYAJJOJqBdaus2smRt0NobIKc0liy7759KB\n' + + '6kmQ47Gg+kfIwxrQA5zlvPLeQImxSoPi9LdbRoKvu7Iot7SOa+jGhVBh3VdqndJX\n' + + '7tm/saj4NE375csmMETFLAOXjat7zViMRwVorX4V6AzEg1vkzxXpA9N7qywWIT5Y\n' + + 'fYaq5M8i6vvLg0CzrH9fHORtnkdjdu1y+0MCAwEAAaNmMGQwDgYDVR0PAQH/BAQD\n' + + 'AgEGMBIGA1UdEwEB/wQIMAYBAf8CAQAwHQYDVR0OBBYEFFOhOx1yt3Z7mvGB9jBv\n' + + '2ymdZwiOMB8GA1UdIwQYMBaAFHNfYNi8ywOY9CsXNC42WqZg/7wfMA0GCSqGSIb3\n' + + 'DQEBCwUAA4IBAQBehqY36UGDvPVU9+vtaYGr38dBbp+LzkjZzHwKT1XJSSUc2wqM\n' + + 'hnCIQKilonrTIvP1vmkQi8qHPvDRtBZKqvz/AErW/ZwQdZzqYNFd+BmOXaeZWV0Q\n' + + 'oHtDzXmcwtP8aUQpxN0e1xkWb1E80qoy+0uuRqb/50b/R4Q5qqSfJhkn6z8nwB10\n' + + '7RjLtJPrK8igxdpr3tGUzfAOyiPrIDncY7UJaL84GFp7WWAkH0WG3H8Y8DRcRXOU\n' + + 'mqDxDLUP3rNuow3jnGxiUY+gGX5OqaZg4f4P6QzOSmeQYs6nLpH0PiN00+oS1BbD\n' + + 'bpWdZEttILPI+vAYkU4QuBKKDjJL6HbSd+cn\n' + + '-----END CERTIFICATE-----\n', + + /** + * Amazon RDS eu-west-3 certificate CA 2019 to 2024 + * + * CN = Amazon RDS eu-west-3 2019 CA + * OU = Amazon RDS + * O = Amazon Web Services, Inc. + * L = Seattle + * ST = Washington + * C = US + * P = 2019-09-18T17:03:15Z/2024-08-22T17:08:50Z + * F = 6F:79:56:B0:74:9C:C6:3E:3B:50:26:C8:51:55:08:F0:B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HQYDVR0OBBYEFLfhrbrO5exkCVgxW0x3\n' + + 'Y2mAi8lNMB8GA1UdIwQYMBaAFHNfYNi8ywOY9CsXNC42WqZg/7wfMA0GCSqGSIb3\n' + + 'DQEBCwUAA4IBAQAigQ5VBNGyw+OZFXwxeJEAUYaXVoP/qrhTOJ6mCE2DXUVEoJeV\n' + + 'SxScy/TlFA9tJXqmit8JH8VQ/xDL4ubBfeMFAIAo4WzNWDVoeVMqphVEcDWBHsI1\n' + + 'AETWzfsapRS9yQekOMmxg63d/nV8xewIl8aNVTHdHYXMqhhik47VrmaVEok1UQb3\n' + + 'O971RadLXIEbVd9tjY5bMEHm89JsZDnDEw1hQXBb67Elu64OOxoKaHBgUH8AZn/2\n' + + 'zFsL1ynNUjOhCSAA15pgd1vjwc0YsBbAEBPcHBWYBEyME6NLNarjOzBl4FMtATSF\n' + + 'wWCKRGkvqN8oxYhwR2jf2rR5Mu4DWkK5Q8Ep\n' + + '-----END CERTIFICATE-----\n', + + /** + * Amazon RDS me-south-1 certificate CA 2019 to 2024 + * + * CN = Amazon RDS me-south-1 Root CA + * OU = Amazon RDS + * O = Amazon Web Services, Inc. + * L = Seattle + * ST = Washington + * C = US + * P = 2019-05-10T21:48:27Z/2024-05-08T21:48:27Z + * F = 8A:69:D7:00:FB:5D:62:9C:B0:D1:75:6F:B7:B6:38:AA:76:C4:BD:1F + */ + '-----BEGIN CERTIFICATE-----\n' + + 'MIIEEjCCAvqgAwIBAgIJANew34ehz5l8MA0GCSqGSIb3DQEBCwUAMIGVMQswCQYD\n' + + 'VQQGEwJVUzEQMA4GA1UEBwwHU2VhdHRsZTETMBEGA1UECAwKV2FzaGluZ3RvbjEi\n' + + 'MCAGA1UECgwZQW1hem9uIFdlYiBTZXJ2aWNlcywgSW5jLjETMBEGA1UECwwKQW1h\n' + + 'em9uIFJEUzEmMCQGA1UEAwwdQW1hem9uIFJEUyBtZS1zb3V0aC0xIFJvb3QgQ0Ew\n' + + 'HhcNMTkwNTEwMjE0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pUDMSrAMDUyO6DyBdZH5ryRMAs3lGtsmkkNUrso\n' + + 'aTW6R05681Z0mvkRdb+cdXtKOSuDZPoe2wJJIaz3IlNQNSrB5TImMYgmt6iAsFhv\n' + + '3vfTSTKrZDNTJn4ybG6pq1zWExoXsktZPylJly6R3RBwV6nwqBM=\n' + + '-----END CERTIFICATE-----\n', + + /** + * Amazon RDS sa-east-1 certificate CA 2019 to 2024 + * + * CN = Amazon RDS sa-east-1 2019 CA + * OU = Amazon RDS + * O = Amazon Web Services, Inc. + * L = Seattle + * ST = Washington + * C = US + * P = 2019-09-05T18:46:29Z/2024-08-22T17:08:50Z + * F = 8C:34:0F:AA:FB:10:80:9C:05:CE:D7:BF:0B:12:4D:07:42:39:74:7A + */ + '-----BEGIN CERTIFICATE-----\n' + + 'MIIEBzCCAu+gAwIBAgICQ2QwDQYJKoZIhvcNAQELBQAwgY8xCzAJBgNVBAYTAlVT\n' + + 'MRAwDgYDVQQHDAdTZWF0dGxlMRMwEQYDVQQIDApXYXNoaW5ndG9uMSIwIAYDVQQK\n' + + 'DBlBbWF6b24gV2ViIFNlcnZpY2VzLCBJbmMuMRMwEQYDVQQLDApBbWF6b24gUkRT\n' + + 'MSAwHgYDVQQDDBdBbWF6b24gUkRTIFJvb3QgMjAxOSBDQTAeFw0xOTA5MDUxODQ2\n' + + 'MjlaFw0yNDA4MjIxNzA4NTBaMIGUMQswCQYDVQQGEwJVUzETMBEGA1UECAwKV2Fz\n' + + 'aGluZ3RvbjEQMA4GA1UEBwwHU2VhdHRsZTEiMCAGA1UECgwZQW1hem9uIFdlYiBT\n' + + 'ZXJ2aWNlcywgSW5jLjETMBEGA1UECwwKQW1hem9uIFJEUzElMCMGA1UEAwwcQW1h\n' + + 'em9uIFJEUyBzYS1lYXN0LTEgMjAxOSBDQTCCASIwDQYJKoZIhvcNAQEBBQADggEP\n' + + 'ADCCAQoCggEBAMMvR+ReRnOzqJzoaPipNTt1Z2VA968jlN1+SYKUrYM3No+Vpz0H\n' + + 'M6Tn0oYB66ByVsXiGc28ulsqX1HbHsxqDPwvQTKvO7SrmDokoAkjJgLocOLUAeld\n' + + '5AwvUjxGRP6yY90NV7X786MpnYb2Il9DIIaV9HjCmPt+rjy2CZjS0UjPjCKNfB8J\n' + + 'bFjgW6GGscjeyGb/zFwcom5p4j0rLydbNaOr9wOyQrtt3ZQWLYGY9Zees/b8pmcc\n' + + 'Jt+7jstZ2UMV32OO/kIsJ4rMUn2r/uxccPwAc1IDeRSSxOrnFKhW3Cu69iB3bHp7\n' + + 'JbawY12g7zshE4I14sHjv3QoXASoXjx4xgMCAwEAAaNmMGQwDgYDVR0PAQH/BAQD\n' + + 'AgEGMBIGA1UdEwEB/wQIMAYBAf8CAQAwHQYDVR0OBBYEFI1Fc/Ql2jx+oJPgBVYq\n' + + 'ccgP0pQ8MB8GA1UdIwQYMBaAFHNfYNi8ywOY9CsXNC42WqZg/7wfMA0GCSqGSIb3\n' + + 'DQEBCwUAA4IBAQB4VVVabVp70myuYuZ3vltQIWqSUMhkaTzehMgGcHjMf9iLoZ/I\n' + + '93KiFUSGnek5cRePyS9wcpp0fcBT3FvkjpUdCjVtdttJgZFhBxgTd8y26ImdDDMR\n' + + '4+BUuhI5msvjL08f+Vkkpu1GQcGmyFVPFOy/UY8iefu+QyUuiBUnUuEDd49Hw0Fn\n' + + '/kIPII6Vj82a2mWV/Q8e+rgN8dIRksRjKI03DEoP8lhPlsOkhdwU6Uz9Vu6NOB2Q\n' + + 'Ls1kbcxAc7cFSyRVJEhh12Sz9d0q/CQSTFsVJKOjSNQBQfVnLz1GwO/IieUEAr4C\n' + + 'jkTntH0r1LX5b/GwN4R887LvjAEdTbg1his7\n' + + '-----END CERTIFICATE-----\n', + + /** + * Amazon RDS us-east-1 certificate CA 2019 to 2024 + * + * CN = Amazon RDS us-east-1 2019 CA + * OU = Amazon RDS + * O = Amazon Web Services, Inc. + * L = Seattle + * ST = Washington + * C = US + * P = 2019-09-19T18:16:53Z/2024-08-22T17:08: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H/BAQD\n' + + 'AgEGMBIGA1UdEwEB/wQIMAYBAf8CAQAwHQYDVR0OBBYEFPqhoWZcrVY9mU7tuemR\n' + + 'RBnQIj1jMB8GA1UdIwQYMBaAFHNfYNi8ywOY9CsXNC42WqZg/7wfMA0GCSqGSIb3\n' + + 'DQEBCwUAA4IBAQB6zOLZ+YINEs72heHIWlPZ8c6WY8MDU+Be5w1M+BK2kpcVhCUK\n' + + 'PJO4nMXpgamEX8DIiaO7emsunwJzMSvavSPRnxXXTKIc0i/g1EbiDjnYX9d85DkC\n' + + 'E1LaAUCmCZBVi9fIe0H2r9whIh4uLWZA41oMnJx/MOmo3XyMfQoWcqaSFlMqfZM4\n' + + '0rNoB/tdHLNuV4eIdaw2mlHxdWDtF4oH+HFm+2cVBUVC1jXKrFv/euRVtsTT+A6i\n' + + 'h2XBHKxQ1Y4HgAn0jACP2QSPEmuoQEIa57bEKEcZsBR8SDY6ZdTd2HLRIApcCOSF\n' + + 'MRM8CKLeF658I0XgF8D5EsYoKPsA+74Z+jDH\n' + + '-----END CERTIFICATE-----\n', + + /** + * Amazon RDS us-east-2 certificate CA 2019 to 2024 + * + * CN = Amazon RDS us-east-2 2019 CA + * OU = Amazon RDS + * O = Amazon Web Services, Inc. + * L = Seattle + * ST = Washington + * C = US + * P = 2019-09-13T17:06:41Z/2024-08-22T17:08:50Z + * F = E9:FE:27:2A:A0:0F:CE:DF:AD:51:03:A6:94:F7:1F:6F:BD:1E:28:D3 + */ + '-----BEGIN CERTIFICATE-----\n' + + 'MIIECDCCAvCgAwIBAgIDAIVCMA0GCSqGSIb3DQEBCwUAMIGPMQswCQYDVQQGEwJV\n' + + 'UzEQMA4GA1UEBwwHU2VhdHRsZTETMBEGA1UECAwKV2FzaGluZ3RvbjEiMCAGA1UE\n' + + 'CgwZQW1hem9uIFdlYiBTZXJ2aWNlcywgSW5jLjETMBEGA1UECwwKQW1hem9uIFJE\n' + + 'UzEgMB4GA1UEAwwXQW1hem9uIFJEUyBSb290ID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BqbGpeCtt3Hh/26tgx0rorPLw90A2\n' + + 'V8QSkZJjlcKkLa58N5CMM8Xz8KLWg3MZeT4DmlUXVCukqK2RGuP2L+aME8dOxqNv\n' + + 'OnOz1zrL5mR2iJoDpk8+VE/eBDmJX40IJk6jBjWoxAO/RXq+vBozuF5YHN1ujE92\n' + + 'tO8HItgTp37XT8bJBAiAnt5mxw+NLSqtxk2QdQ==\n' + + '-----END CERTIFICATE-----\n', + + /** + * Amazon RDS us-west-1 certificate CA 2019 to 2024 + * + * CN = Amazon RDS us-west-1 2019 CA + * OU = Amazon RDS + * O = Amazon Web Services, Inc. + * L = Seattle + * ST = Washington + * C = US + * P = 2019-09-06T17:40:21Z/2024-08-22T17:08:50Z + * F = 1C:9F:DF:84:E6:13:32:F3:91:12:2D:0D:A5:9A:16:5D:AC:DC:E8:93 + */ + '-----BEGIN CERTIFICATE-----\n' + + 'MIIECDCCAvCgAwIBAgIDAIkHMA0GCSqGSIb3DQEBCwUAMIGPMQswCQYDVQQGEwJV\n' + + 'UzEQMA4GA1UEBwwHU2VhdHRsZTETMBEGA1UECAwKV2FzaGluZ3RvbjEiMCAGA1UE\n' + + 'CgwZQW1hem9uIFdlYiBTZXJ2aWNlcywgSW5jLjETMBEGA1UECwwKQW1hem9uIFJE\n' + + 'UzEgMB4GA1UEAwwXQW1hem9uIFJEUyBSb290IDIwMTkgQ0EwHhcNMTkwOTA2MTc0\n' + + 'MDIxWhcNMjQwODIyMTcwODUwWjCBlDELMAkGA1UEBhMCVVMxEzARBgNVBAgMCldh\n' + + 'c2hpbmd0b24xEDAOBgNVBAcMB1NlYXR0bGUxIjAgBgNVBAoMGUFtYXpvbiBXZWIg\n' + + 'U2VydmljZXMsIEluYy4xEzARBgNVBAsMCkFtYXpvbiBSRFMxJTAjBgNVBAMMHEFt\n' + + 'YXpvbiBSRFMgdXMtd2VzdC0xIDIwMTkgQ0EwggEiMA0GCSqGSIb3DQEBAQUAA4IB\n' + + 'DwAwggEKAoIBAQDD2yzbbAl77OofTghDMEf624OvU0eS9O+lsdO0QlbfUfWa1Kd6\n' + + '0WkgjkLZGfSRxEHMCnrv4UPBSK/Qwn6FTjkDLgemhqBtAnplN4VsoDL+BkRX4Wwq\n' + + '/dSQJE2b+0hm9w9UMVGFDEq1TMotGGTD2B71eh9HEKzKhGzqiNeGsiX4VV+LJzdH\n' + + 'uM23eGisNqmd4iJV0zcAZ+Gbh2zK6fqTOCvXtm7Idccv8vZZnyk1FiWl3NR4WAgK\n' + + 'AkvWTIoFU3Mt7dIXKKClVmvssG8WHCkd3Xcb4FHy/G756UZcq67gMMTX/9fOFM/v\n' + + 'l5C0+CHl33Yig1vIDZd+fXV1KZD84dEJfEvHAgMBAAGjZjBkMA4GA1UdDwEB/wQE\n' + + 'AwIBBjASBgNVHRMBAf8ECDAGAQH/AgEAMB0GA1UdDgQWBBR+ap20kO/6A7pPxo3+\n' + + 'T3CfqZpQWjAfBgNVHSMEGDAWgBRzX2DYvMsDmPQrFzQuNlqmYP+8HzANBgkqhkiG\n' + + '9w0BAQsFAAOCAQEAHCJky2tPjPttlDM/RIqExupBkNrnSYnOK4kr9xJ3sl8UF2DA\n' + + 'PAnYsjXp3rfcjN/k/FVOhxwzi3cXJF/2Tjj39Bm/OEfYTOJDNYtBwB0VVH4ffa/6\n' + + 'tZl87jaIkrxJcreeeHqYMnIxeN0b/kliyA+a5L2Yb0VPjt9INq34QDc1v74FNZ17\n' + + '4z8nr1nzg4xsOWu0Dbjo966lm4nOYIGBRGOKEkHZRZ4mEiMgr3YLkv8gSmeitx57\n' + + 'Z6dVemNtUic/LVo5Iqw4n3TBS0iF2C1Q1xT/s3h+0SXZlfOWttzSluDvoMv5PvCd\n' + + 'pFjNn+aXLAALoihL1MJSsxydtsLjOBro5eK0Vw==\n' + + '-----END CERTIFICATE-----\n', + + /** + * Amazon RDS us-west-2 certificate CA 2019 to 2024 + * + * CN = Amazon RDS us-west-2 2019 CA + * OU = Amazon RDS + * O = Amazon Web Services, Inc. + * L = Seattle + * ST = Washington + * C = US + * P = 2019-09-16T18:21:15Z/2024-08-22T17:08:50Z + * F = C8:DE:1D:13:AD:35:9B:3D:EA:18:2A:DC:B4:79:6D:22:47:75:3C:4A + */ + '-----BEGIN CERTIFICATE-----\n' + + 'MIIEBzCCAu+gAwIBAgICUYkwDQYJKoZIhvcNAQELBQAwgY8xCzAJBgNVBAYTAlVT\n' + + 'MRAwDgYDVQQHDAdTZWF0dGxlMRMwEQYDVQQIDApXYXNoaW5ndG9uMSIwIAYDVQQK\n' + + 'DBlBbWF6b24gV2ViIFNlcnZpY2VzLCBJbmMuMRMwEQYDVQQLDApBbWF6b24gUkRT\n' + + 'MSAwHgYDVQQDDBdBbWF6b24gUkRTIFJvb3QgMjAxOSBDQTAeFw0xOTA5MTYxODIx\n' + + 'MTVaFw0yNDA4MjIxNzA4NTBaMIGUMQswCQYDVQQGEwJVUzETMBEGA1UECAwKV2Fz\n' + + 'aGluZ3RvbjEQMA4GA1UEBwwHU2VhdHRsZTEiMCAGA1UECgwZQW1hem9uIFdlYiBT\n' + + 'ZXJ2aWNlcywgSW5jLjETMBEGA1UECwwKQW1hem9uIFJEUzElMCMGA1UEAwwcQW1h\n' + + 'em9uIFJEUyB1cy13ZXN0LTIgMjAxOSBDQTCCASIwDQYJKoZIhvcNAQEBBQADggEP\n' + + 'ADCCAQoCggEBANCEZBZyu6yJQFZBJmSUZfSZd3Ui2gitczMKC4FLr0QzkbxY+cLa\n' + + 'uVONIOrPt4Rwi+3h/UdnUg917xao3S53XDf1TDMFEYp4U8EFPXqCn/GXBIWlU86P\n' + + 'PvBN+gzw3nS+aco7WXb+woTouvFVkk8FGU7J532llW8o/9ydQyDIMtdIkKTuMfho\n' + + 'OiNHSaNc+QXQ32TgvM9A/6q7ksUoNXGCP8hDOkSZ/YOLiI5TcdLh/aWj00ziL5bj\n' + + 'pvytiMZkilnc9dLY9QhRNr0vGqL0xjmWdoEXz9/OwjmCihHqJq+20MJPsvFm7D6a\n' + + '2NKybR9U+ddrjb8/iyLOjURUZnj5O+2+OPcCAwEAAaNmMGQwDgYDVR0PAQH/BAQD\n' + + 'AgEGMBIGA1UdEwEB/wQIMAYBAf8CAQAwHQYDVR0OBBYEFEBxMBdv81xuzqcK5TVu\n' + + 'pHj+Aor8MB8GA1UdIwQYMBaAFHNfYNi8ywOY9CsXNC42WqZg/7wfMA0GCSqGSIb3\n' + + 'DQEBCwUAA4IBAQBZkfiVqGoJjBI37aTlLOSjLcjI75L5wBrwO39q+B4cwcmpj58P\n' + + '3sivv+jhYfAGEbQnGRzjuFoyPzWnZ1DesRExX+wrmHsLLQbF2kVjLZhEJMHF9eB7\n' + + 'GZlTPdTzHErcnuXkwA/OqyXMpj9aghcQFuhCNguEfnROY9sAoK2PTfnTz9NJHL+Q\n' + + 'UpDLEJEUfc0GZMVWYhahc0x38ZnSY2SKacIPECQrTI0KpqZv/P+ijCEcMD9xmYEb\n' + + 'jL4en+XKS1uJpw5fIU5Sj0MxhdGstH6S84iAE5J3GM3XHklGSFwwqPYvuTXvANH6\n' + + 'uboynxRgSae59jIlAK6Jrr6GWMwQRbgcaAlW\n' + + '-----END CERTIFICATE-----\n' + ] +}; diff --git a/ts-ticket-office-service/node_modules/mysql/lib/protocol/constants/types.js b/ts-ticket-office-service/node_modules/mysql/lib/protocol/constants/types.js new file mode 100644 index 000000000..a33cd502c --- /dev/null +++ b/ts-ticket-office-service/node_modules/mysql/lib/protocol/constants/types.js @@ -0,0 +1,72 @@ +/** + * MySQL type constants + * + * Extracted from version 5.7.29 + * + * !! Generated by generate-type-constants.js, do not modify by hand !! + */ + +exports.DECIMAL = 0; +exports.TINY = 1; +exports.SHORT = 2; +exports.LONG = 3; +exports.FLOAT = 4; +exports.DOUBLE = 5; +exports.NULL = 6; +exports.TIMESTAMP = 7; +exports.LONGLONG = 8; +exports.INT24 = 9; +exports.DATE = 10; +exports.TIME = 11; +exports.DATETIME = 12; +exports.YEAR = 13; +exports.NEWDATE = 14; +exports.VARCHAR = 15; +exports.BIT = 16; +exports.TIMESTAMP2 = 17; +exports.DATETIME2 = 18; +exports.TIME2 = 19; +exports.JSON = 245; +exports.NEWDECIMAL = 246; +exports.ENUM = 247; +exports.SET = 248; +exports.TINY_BLOB = 249; +exports.MEDIUM_BLOB = 250; +exports.LONG_BLOB = 251; +exports.BLOB = 252; +exports.VAR_STRING = 253; +exports.STRING = 254; +exports.GEOMETRY = 255; + +// Lookup-by-number table +exports[0] = 'DECIMAL'; +exports[1] = 'TINY'; +exports[2] = 'SHORT'; +exports[3] = 'LONG'; +exports[4] = 'FLOAT'; +exports[5] = 'DOUBLE'; +exports[6] = 'NULL'; +exports[7] = 'TIMESTAMP'; +exports[8] = 'LONGLONG'; +exports[9] = 'INT24'; +exports[10] = 'DATE'; +exports[11] = 'TIME'; +exports[12] = 'DATETIME'; +exports[13] = 'YEAR'; +exports[14] = 'NEWDATE'; +exports[15] = 'VARCHAR'; +exports[16] = 'BIT'; +exports[17] = 'TIMESTAMP2'; +exports[18] = 'DATETIME2'; +exports[19] = 'TIME2'; +exports[245] = 'JSON'; +exports[246] = 'NEWDECIMAL'; +exports[247] = 'ENUM'; +exports[248] = 'SET'; +exports[249] = 'TINY_BLOB'; +exports[250] = 'MEDIUM_BLOB'; +exports[251] = 'LONG_BLOB'; +exports[252] = 'BLOB'; +exports[253] = 'VAR_STRING'; +exports[254] = 'STRING'; +exports[255] = 'GEOMETRY'; diff --git a/ts-ticket-office-service/node_modules/mysql/lib/protocol/packets/AuthSwitchRequestPacket.js b/ts-ticket-office-service/node_modules/mysql/lib/protocol/packets/AuthSwitchRequestPacket.js new file mode 100644 index 000000000..c74e6ec23 --- /dev/null +++ b/ts-ticket-office-service/node_modules/mysql/lib/protocol/packets/AuthSwitchRequestPacket.js @@ -0,0 +1,20 @@ +module.exports = AuthSwitchRequestPacket; +function AuthSwitchRequestPacket(options) { + options = options || {}; + + this.status = 0xfe; + this.authMethodName = options.authMethodName; + this.authMethodData = options.authMethodData; +} + +AuthSwitchRequestPacket.prototype.parse = function parse(parser) { + this.status = parser.parseUnsignedNumber(1); + this.authMethodName = parser.parseNullTerminatedString(); + this.authMethodData = parser.parsePacketTerminatedBuffer(); +}; + +AuthSwitchRequestPacket.prototype.write = function write(writer) { + writer.writeUnsignedNumber(1, this.status); + writer.writeNullTerminatedString(this.authMethodName); + writer.writeBuffer(this.authMethodData); +}; diff --git a/ts-ticket-office-service/node_modules/mysql/lib/protocol/packets/AuthSwitchResponsePacket.js b/ts-ticket-office-service/node_modules/mysql/lib/protocol/packets/AuthSwitchResponsePacket.js new file mode 100644 index 000000000..488abbd03 --- /dev/null +++ b/ts-ticket-office-service/node_modules/mysql/lib/protocol/packets/AuthSwitchResponsePacket.js @@ -0,0 +1,14 @@ +module.exports = AuthSwitchResponsePacket; +function AuthSwitchResponsePacket(options) { + options = options || {}; + + this.data = options.data; +} + +AuthSwitchResponsePacket.prototype.parse = function parse(parser) { + this.data = parser.parsePacketTerminatedBuffer(); +}; + +AuthSwitchResponsePacket.prototype.write = function write(writer) { + writer.writeBuffer(this.data); +}; diff --git a/ts-ticket-office-service/node_modules/mysql/lib/protocol/packets/ClientAuthenticationPacket.js b/ts-ticket-office-service/node_modules/mysql/lib/protocol/packets/ClientAuthenticationPacket.js new file mode 100644 index 000000000..595db77a0 --- /dev/null +++ b/ts-ticket-office-service/node_modules/mysql/lib/protocol/packets/ClientAuthenticationPacket.js @@ -0,0 +1,54 @@ +var Buffer = require('safe-buffer').Buffer; + +module.exports = ClientAuthenticationPacket; +function ClientAuthenticationPacket(options) { + options = options || {}; + + this.clientFlags = options.clientFlags; + this.maxPacketSize = options.maxPacketSize; + this.charsetNumber = options.charsetNumber; + this.filler = undefined; + this.user = options.user; + this.scrambleBuff = options.scrambleBuff; + this.database = options.database; + this.protocol41 = options.protocol41; +} + +ClientAuthenticationPacket.prototype.parse = function(parser) { + if (this.protocol41) { + this.clientFlags = parser.parseUnsignedNumber(4); + this.maxPacketSize = parser.parseUnsignedNumber(4); + this.charsetNumber = parser.parseUnsignedNumber(1); + this.filler = parser.parseFiller(23); + this.user = parser.parseNullTerminatedString(); + this.scrambleBuff = parser.parseLengthCodedBuffer(); + this.database = parser.parseNullTerminatedString(); + } else { + this.clientFlags = parser.parseUnsignedNumber(2); + this.maxPacketSize = parser.parseUnsignedNumber(3); + this.user = parser.parseNullTerminatedString(); + this.scrambleBuff = parser.parseBuffer(8); + this.database = parser.parseLengthCodedBuffer(); + } +}; + +ClientAuthenticationPacket.prototype.write = function(writer) { + if (this.protocol41) { + writer.writeUnsignedNumber(4, this.clientFlags); + writer.writeUnsignedNumber(4, this.maxPacketSize); + writer.writeUnsignedNumber(1, this.charsetNumber); + writer.writeFiller(23); + writer.writeNullTerminatedString(this.user); + writer.writeLengthCodedBuffer(this.scrambleBuff); + writer.writeNullTerminatedString(this.database); + } else { + writer.writeUnsignedNumber(2, this.clientFlags); + writer.writeUnsignedNumber(3, this.maxPacketSize); + writer.writeNullTerminatedString(this.user); + writer.writeBuffer(this.scrambleBuff); + if (this.database && this.database.length) { + writer.writeFiller(1); + writer.writeBuffer(Buffer.from(this.database)); + } + } +}; diff --git a/ts-ticket-office-service/node_modules/mysql/lib/protocol/packets/ComChangeUserPacket.js b/ts-ticket-office-service/node_modules/mysql/lib/protocol/packets/ComChangeUserPacket.js new file mode 100644 index 000000000..327884235 --- /dev/null +++ b/ts-ticket-office-service/node_modules/mysql/lib/protocol/packets/ComChangeUserPacket.js @@ -0,0 +1,26 @@ +module.exports = ComChangeUserPacket; +function ComChangeUserPacket(options) { + options = options || {}; + + this.command = 0x11; + this.user = options.user; + this.scrambleBuff = options.scrambleBuff; + this.database = options.database; + this.charsetNumber = options.charsetNumber; +} + +ComChangeUserPacket.prototype.parse = function(parser) { + this.command = parser.parseUnsignedNumber(1); + this.user = parser.parseNullTerminatedString(); + this.scrambleBuff = parser.parseLengthCodedBuffer(); + this.database = parser.parseNullTerminatedString(); + this.charsetNumber = parser.parseUnsignedNumber(1); +}; + +ComChangeUserPacket.prototype.write = function(writer) { + writer.writeUnsignedNumber(1, this.command); + writer.writeNullTerminatedString(this.user); + writer.writeLengthCodedBuffer(this.scrambleBuff); + writer.writeNullTerminatedString(this.database); + writer.writeUnsignedNumber(2, this.charsetNumber); +}; diff --git a/ts-ticket-office-service/node_modules/mysql/lib/protocol/packets/ComPingPacket.js b/ts-ticket-office-service/node_modules/mysql/lib/protocol/packets/ComPingPacket.js new file mode 100644 index 000000000..dd332c93c --- /dev/null +++ b/ts-ticket-office-service/node_modules/mysql/lib/protocol/packets/ComPingPacket.js @@ -0,0 +1,12 @@ +module.exports = ComPingPacket; +function ComPingPacket() { + this.command = 0x0e; +} + +ComPingPacket.prototype.write = function(writer) { + writer.writeUnsignedNumber(1, this.command); +}; + +ComPingPacket.prototype.parse = function(parser) { + this.command = parser.parseUnsignedNumber(1); +}; diff --git a/ts-ticket-office-service/node_modules/mysql/lib/protocol/packets/ComQueryPacket.js b/ts-ticket-office-service/node_modules/mysql/lib/protocol/packets/ComQueryPacket.js new file mode 100644 index 000000000..7ac191fd0 --- /dev/null +++ b/ts-ticket-office-service/node_modules/mysql/lib/protocol/packets/ComQueryPacket.js @@ -0,0 +1,15 @@ +module.exports = ComQueryPacket; +function ComQueryPacket(sql) { + this.command = 0x03; + this.sql = sql; +} + +ComQueryPacket.prototype.write = function(writer) { + writer.writeUnsignedNumber(1, this.command); + writer.writeString(this.sql); +}; + +ComQueryPacket.prototype.parse = function(parser) { + this.command = parser.parseUnsignedNumber(1); + this.sql = parser.parsePacketTerminatedString(); +}; diff --git a/ts-ticket-office-service/node_modules/mysql/lib/protocol/packets/ComQuitPacket.js b/ts-ticket-office-service/node_modules/mysql/lib/protocol/packets/ComQuitPacket.js new file mode 100644 index 000000000..1104061cb --- /dev/null +++ b/ts-ticket-office-service/node_modules/mysql/lib/protocol/packets/ComQuitPacket.js @@ -0,0 +1,12 @@ +module.exports = ComQuitPacket; +function ComQuitPacket() { + this.command = 0x01; +} + +ComQuitPacket.prototype.parse = function parse(parser) { + this.command = parser.parseUnsignedNumber(1); +}; + +ComQuitPacket.prototype.write = function write(writer) { + writer.writeUnsignedNumber(1, this.command); +}; diff --git a/ts-ticket-office-service/node_modules/mysql/lib/protocol/packets/ComStatisticsPacket.js b/ts-ticket-office-service/node_modules/mysql/lib/protocol/packets/ComStatisticsPacket.js new file mode 100644 index 000000000..5e3913e15 --- /dev/null +++ b/ts-ticket-office-service/node_modules/mysql/lib/protocol/packets/ComStatisticsPacket.js @@ -0,0 +1,12 @@ +module.exports = ComStatisticsPacket; +function ComStatisticsPacket() { + this.command = 0x09; +} + +ComStatisticsPacket.prototype.write = function(writer) { + writer.writeUnsignedNumber(1, this.command); +}; + +ComStatisticsPacket.prototype.parse = function(parser) { + this.command = parser.parseUnsignedNumber(1); +}; diff --git a/ts-ticket-office-service/node_modules/mysql/lib/protocol/packets/EmptyPacket.js b/ts-ticket-office-service/node_modules/mysql/lib/protocol/packets/EmptyPacket.js new file mode 100644 index 000000000..27dd68604 --- /dev/null +++ b/ts-ticket-office-service/node_modules/mysql/lib/protocol/packets/EmptyPacket.js @@ -0,0 +1,9 @@ +module.exports = EmptyPacket; +function EmptyPacket() { +} + +EmptyPacket.prototype.parse = function parse() { +}; + +EmptyPacket.prototype.write = function write() { +}; diff --git a/ts-ticket-office-service/node_modules/mysql/lib/protocol/packets/EofPacket.js b/ts-ticket-office-service/node_modules/mysql/lib/protocol/packets/EofPacket.js new file mode 100644 index 000000000..b80ca5ef2 --- /dev/null +++ b/ts-ticket-office-service/node_modules/mysql/lib/protocol/packets/EofPacket.js @@ -0,0 +1,25 @@ +module.exports = EofPacket; +function EofPacket(options) { + options = options || {}; + + this.fieldCount = undefined; + this.warningCount = options.warningCount; + this.serverStatus = options.serverStatus; + this.protocol41 = options.protocol41; +} + +EofPacket.prototype.parse = function(parser) { + this.fieldCount = parser.parseUnsignedNumber(1); + if (this.protocol41) { + this.warningCount = parser.parseUnsignedNumber(2); + this.serverStatus = parser.parseUnsignedNumber(2); + } +}; + +EofPacket.prototype.write = function(writer) { + writer.writeUnsignedNumber(1, 0xfe); + if (this.protocol41) { + writer.writeUnsignedNumber(2, this.warningCount); + writer.writeUnsignedNumber(2, this.serverStatus); + } +}; diff --git a/ts-ticket-office-service/node_modules/mysql/lib/protocol/packets/ErrorPacket.js b/ts-ticket-office-service/node_modules/mysql/lib/protocol/packets/ErrorPacket.js new file mode 100644 index 000000000..e03de00ce --- /dev/null +++ b/ts-ticket-office-service/node_modules/mysql/lib/protocol/packets/ErrorPacket.js @@ -0,0 +1,35 @@ +module.exports = ErrorPacket; +function ErrorPacket(options) { + options = options || {}; + + this.fieldCount = options.fieldCount; + this.errno = options.errno; + this.sqlStateMarker = options.sqlStateMarker; + this.sqlState = options.sqlState; + this.message = options.message; +} + +ErrorPacket.prototype.parse = function(parser) { + this.fieldCount = parser.parseUnsignedNumber(1); + this.errno = parser.parseUnsignedNumber(2); + + // sqlStateMarker ('#' = 0x23) indicates error packet format + if (parser.peak() === 0x23) { + this.sqlStateMarker = parser.parseString(1); + this.sqlState = parser.parseString(5); + } + + this.message = parser.parsePacketTerminatedString(); +}; + +ErrorPacket.prototype.write = function(writer) { + writer.writeUnsignedNumber(1, 0xff); + writer.writeUnsignedNumber(2, this.errno); + + if (this.sqlStateMarker) { + writer.writeString(this.sqlStateMarker); + writer.writeString(this.sqlState); + } + + writer.writeString(this.message); +}; diff --git a/ts-ticket-office-service/node_modules/mysql/lib/protocol/packets/Field.js b/ts-ticket-office-service/node_modules/mysql/lib/protocol/packets/Field.js new file mode 100644 index 000000000..a5d58edb6 --- /dev/null +++ b/ts-ticket-office-service/node_modules/mysql/lib/protocol/packets/Field.js @@ -0,0 +1,26 @@ +var Types = require('../constants/types'); + +module.exports = Field; +function Field(options) { + options = options || {}; + + this.parser = options.parser; + this.packet = options.packet; + this.db = options.packet.db; + this.table = options.packet.table; + this.name = options.packet.name; + this.type = Types[options.packet.type]; + this.length = options.packet.length; +} + +Field.prototype.string = function () { + return this.parser.parseLengthCodedString(); +}; + +Field.prototype.buffer = function () { + return this.parser.parseLengthCodedBuffer(); +}; + +Field.prototype.geometry = function () { + return this.parser.parseGeometryValue(); +}; diff --git a/ts-ticket-office-service/node_modules/mysql/lib/protocol/packets/FieldPacket.js b/ts-ticket-office-service/node_modules/mysql/lib/protocol/packets/FieldPacket.js new file mode 100644 index 000000000..12cfed10c --- /dev/null +++ b/ts-ticket-office-service/node_modules/mysql/lib/protocol/packets/FieldPacket.js @@ -0,0 +1,93 @@ +module.exports = FieldPacket; +function FieldPacket(options) { + options = options || {}; + + this.catalog = options.catalog; + this.db = options.db; + this.table = options.table; + this.orgTable = options.orgTable; + this.name = options.name; + this.orgName = options.orgName; + this.charsetNr = options.charsetNr; + this.length = options.length; + this.type = options.type; + this.flags = options.flags; + this.decimals = options.decimals; + this.default = options.default; + this.zeroFill = options.zeroFill; + this.protocol41 = options.protocol41; +} + +FieldPacket.prototype.parse = function(parser) { + if (this.protocol41) { + this.catalog = parser.parseLengthCodedString(); + this.db = parser.parseLengthCodedString(); + this.table = parser.parseLengthCodedString(); + this.orgTable = parser.parseLengthCodedString(); + this.name = parser.parseLengthCodedString(); + this.orgName = parser.parseLengthCodedString(); + + if (parser.parseLengthCodedNumber() !== 0x0c) { + var err = new TypeError('Received invalid field length'); + err.code = 'PARSER_INVALID_FIELD_LENGTH'; + throw err; + } + + this.charsetNr = parser.parseUnsignedNumber(2); + this.length = parser.parseUnsignedNumber(4); + this.type = parser.parseUnsignedNumber(1); + this.flags = parser.parseUnsignedNumber(2); + this.decimals = parser.parseUnsignedNumber(1); + + var filler = parser.parseBuffer(2); + if (filler[0] !== 0x0 || filler[1] !== 0x0) { + var err = new TypeError('Received invalid filler'); + err.code = 'PARSER_INVALID_FILLER'; + throw err; + } + + // parsed flags + this.zeroFill = (this.flags & 0x0040 ? true : false); + + if (parser.reachedPacketEnd()) { + return; + } + + this.default = parser.parseLengthCodedString(); + } else { + this.table = parser.parseLengthCodedString(); + this.name = parser.parseLengthCodedString(); + this.length = parser.parseUnsignedNumber(parser.parseUnsignedNumber(1)); + this.type = parser.parseUnsignedNumber(parser.parseUnsignedNumber(1)); + } +}; + +FieldPacket.prototype.write = function(writer) { + if (this.protocol41) { + writer.writeLengthCodedString(this.catalog); + writer.writeLengthCodedString(this.db); + writer.writeLengthCodedString(this.table); + writer.writeLengthCodedString(this.orgTable); + writer.writeLengthCodedString(this.name); + writer.writeLengthCodedString(this.orgName); + + writer.writeLengthCodedNumber(0x0c); + writer.writeUnsignedNumber(2, this.charsetNr || 0); + writer.writeUnsignedNumber(4, this.length || 0); + writer.writeUnsignedNumber(1, this.type || 0); + writer.writeUnsignedNumber(2, this.flags || 0); + writer.writeUnsignedNumber(1, this.decimals || 0); + writer.writeFiller(2); + + if (this.default !== undefined) { + writer.writeLengthCodedString(this.default); + } + } else { + writer.writeLengthCodedString(this.table); + writer.writeLengthCodedString(this.name); + writer.writeUnsignedNumber(1, 0x01); + writer.writeUnsignedNumber(1, this.length); + writer.writeUnsignedNumber(1, 0x01); + writer.writeUnsignedNumber(1, this.type); + } +}; diff --git a/ts-ticket-office-service/node_modules/mysql/lib/protocol/packets/HandshakeInitializationPacket.js b/ts-ticket-office-service/node_modules/mysql/lib/protocol/packets/HandshakeInitializationPacket.js new file mode 100644 index 000000000..b2510633b --- /dev/null +++ b/ts-ticket-office-service/node_modules/mysql/lib/protocol/packets/HandshakeInitializationPacket.js @@ -0,0 +1,103 @@ +var Buffer = require('safe-buffer').Buffer; +var Client = require('../constants/client'); + +module.exports = HandshakeInitializationPacket; +function HandshakeInitializationPacket(options) { + options = options || {}; + + this.protocolVersion = options.protocolVersion; + this.serverVersion = options.serverVersion; + this.threadId = options.threadId; + this.scrambleBuff1 = options.scrambleBuff1; + this.filler1 = options.filler1; + this.serverCapabilities1 = options.serverCapabilities1; + this.serverLanguage = options.serverLanguage; + this.serverStatus = options.serverStatus; + this.serverCapabilities2 = options.serverCapabilities2; + this.scrambleLength = options.scrambleLength; + this.filler2 = options.filler2; + this.scrambleBuff2 = options.scrambleBuff2; + this.filler3 = options.filler3; + this.pluginData = options.pluginData; + this.protocol41 = options.protocol41; + + if (this.protocol41) { + // force set the bit in serverCapabilities1 + this.serverCapabilities1 |= Client.CLIENT_PROTOCOL_41; + } +} + +HandshakeInitializationPacket.prototype.parse = function(parser) { + this.protocolVersion = parser.parseUnsignedNumber(1); + this.serverVersion = parser.parseNullTerminatedString(); + this.threadId = parser.parseUnsignedNumber(4); + this.scrambleBuff1 = parser.parseBuffer(8); + this.filler1 = parser.parseFiller(1); + this.serverCapabilities1 = parser.parseUnsignedNumber(2); + this.serverLanguage = parser.parseUnsignedNumber(1); + this.serverStatus = parser.parseUnsignedNumber(2); + + this.protocol41 = (this.serverCapabilities1 & (1 << 9)) > 0; + + if (this.protocol41) { + this.serverCapabilities2 = parser.parseUnsignedNumber(2); + this.scrambleLength = parser.parseUnsignedNumber(1); + this.filler2 = parser.parseFiller(10); + // scrambleBuff2 should be 0x00 terminated, but sphinx does not do this + // so we assume scrambleBuff2 to be 12 byte and treat the next byte as a + // filler byte. + this.scrambleBuff2 = parser.parseBuffer(12); + this.filler3 = parser.parseFiller(1); + } else { + this.filler2 = parser.parseFiller(13); + } + + if (parser.reachedPacketEnd()) { + return; + } + + // According to the docs this should be 0x00 terminated, but MariaDB does + // not do this, so we assume this string to be packet terminated. + this.pluginData = parser.parsePacketTerminatedString(); + + // However, if there is a trailing '\0', strip it + var lastChar = this.pluginData.length - 1; + if (this.pluginData[lastChar] === '\0') { + this.pluginData = this.pluginData.substr(0, lastChar); + } +}; + +HandshakeInitializationPacket.prototype.write = function(writer) { + writer.writeUnsignedNumber(1, this.protocolVersion); + writer.writeNullTerminatedString(this.serverVersion); + writer.writeUnsignedNumber(4, this.threadId); + writer.writeBuffer(this.scrambleBuff1); + writer.writeFiller(1); + writer.writeUnsignedNumber(2, this.serverCapabilities1); + writer.writeUnsignedNumber(1, this.serverLanguage); + writer.writeUnsignedNumber(2, this.serverStatus); + if (this.protocol41) { + writer.writeUnsignedNumber(2, this.serverCapabilities2); + writer.writeUnsignedNumber(1, this.scrambleLength); + writer.writeFiller(10); + } + writer.writeNullTerminatedBuffer(this.scrambleBuff2); + + if (this.pluginData !== undefined) { + writer.writeNullTerminatedString(this.pluginData); + } +}; + +HandshakeInitializationPacket.prototype.scrambleBuff = function() { + var buffer = null; + + if (typeof this.scrambleBuff2 === 'undefined') { + buffer = Buffer.from(this.scrambleBuff1); + } else { + buffer = Buffer.allocUnsafe(this.scrambleBuff1.length + this.scrambleBuff2.length); + this.scrambleBuff1.copy(buffer, 0); + this.scrambleBuff2.copy(buffer, this.scrambleBuff1.length); + } + + return buffer; +}; diff --git a/ts-ticket-office-service/node_modules/mysql/lib/protocol/packets/LocalDataFilePacket.js b/ts-ticket-office-service/node_modules/mysql/lib/protocol/packets/LocalDataFilePacket.js new file mode 100644 index 000000000..af7aaa045 --- /dev/null +++ b/ts-ticket-office-service/node_modules/mysql/lib/protocol/packets/LocalDataFilePacket.js @@ -0,0 +1,15 @@ +module.exports = LocalDataFilePacket; + +/** + * Create a new LocalDataFilePacket + * @constructor + * @param {Buffer} data The data contents of the packet + * @public + */ +function LocalDataFilePacket(data) { + this.data = data; +} + +LocalDataFilePacket.prototype.write = function(writer) { + writer.writeBuffer(this.data); +}; diff --git a/ts-ticket-office-service/node_modules/mysql/lib/protocol/packets/LocalInfileRequestPacket.js b/ts-ticket-office-service/node_modules/mysql/lib/protocol/packets/LocalInfileRequestPacket.js new file mode 100644 index 000000000..b1f68bab4 --- /dev/null +++ b/ts-ticket-office-service/node_modules/mysql/lib/protocol/packets/LocalInfileRequestPacket.js @@ -0,0 +1,21 @@ +module.exports = LocalInfileRequestPacket; +function LocalInfileRequestPacket(options) { + options = options || {}; + + this.filename = options.filename; +} + +LocalInfileRequestPacket.prototype.parse = function parse(parser) { + if (parser.parseLengthCodedNumber() !== null) { + var err = new TypeError('Received invalid field length'); + err.code = 'PARSER_INVALID_FIELD_LENGTH'; + throw err; + } + + this.filename = parser.parsePacketTerminatedString(); +}; + +LocalInfileRequestPacket.prototype.write = function write(writer) { + writer.writeLengthCodedNumber(null); + writer.writeString(this.filename); +}; diff --git a/ts-ticket-office-service/node_modules/mysql/lib/protocol/packets/OkPacket.js b/ts-ticket-office-service/node_modules/mysql/lib/protocol/packets/OkPacket.js new file mode 100644 index 000000000..7caf3b0e7 --- /dev/null +++ b/ts-ticket-office-service/node_modules/mysql/lib/protocol/packets/OkPacket.js @@ -0,0 +1,44 @@ + +// Language-neutral expression to match ER_UPDATE_INFO +var ER_UPDATE_INFO_REGEXP = /^[^:0-9]+: [0-9]+[^:0-9]+: ([0-9]+)[^:0-9]+: [0-9]+[^:0-9]*$/; + +module.exports = OkPacket; +function OkPacket(options) { + options = options || {}; + + this.fieldCount = undefined; + this.affectedRows = undefined; + this.insertId = undefined; + this.serverStatus = undefined; + this.warningCount = undefined; + this.message = undefined; + this.protocol41 = options.protocol41; +} + +OkPacket.prototype.parse = function(parser) { + this.fieldCount = parser.parseUnsignedNumber(1); + this.affectedRows = parser.parseLengthCodedNumber(); + this.insertId = parser.parseLengthCodedNumber(); + if (this.protocol41) { + this.serverStatus = parser.parseUnsignedNumber(2); + this.warningCount = parser.parseUnsignedNumber(2); + } + this.message = parser.parsePacketTerminatedString(); + this.changedRows = 0; + + var m = ER_UPDATE_INFO_REGEXP.exec(this.message); + if (m !== null) { + this.changedRows = parseInt(m[1], 10); + } +}; + +OkPacket.prototype.write = function(writer) { + writer.writeUnsignedNumber(1, 0x00); + writer.writeLengthCodedNumber(this.affectedRows || 0); + writer.writeLengthCodedNumber(this.insertId || 0); + if (this.protocol41) { + writer.writeUnsignedNumber(2, this.serverStatus || 0); + writer.writeUnsignedNumber(2, this.warningCount || 0); + } + writer.writeString(this.message); +}; diff --git a/ts-ticket-office-service/node_modules/mysql/lib/protocol/packets/OldPasswordPacket.js b/ts-ticket-office-service/node_modules/mysql/lib/protocol/packets/OldPasswordPacket.js new file mode 100644 index 000000000..a72951021 --- /dev/null +++ b/ts-ticket-office-service/node_modules/mysql/lib/protocol/packets/OldPasswordPacket.js @@ -0,0 +1,14 @@ +module.exports = OldPasswordPacket; +function OldPasswordPacket(options) { + options = options || {}; + + this.scrambleBuff = options.scrambleBuff; +} + +OldPasswordPacket.prototype.parse = function(parser) { + this.scrambleBuff = parser.parsePacketTerminatedBuffer(); +}; + +OldPasswordPacket.prototype.write = function(writer) { + writer.writeBuffer(this.scrambleBuff); +}; diff --git a/ts-ticket-office-service/node_modules/mysql/lib/protocol/packets/ResultSetHeaderPacket.js b/ts-ticket-office-service/node_modules/mysql/lib/protocol/packets/ResultSetHeaderPacket.js new file mode 100644 index 000000000..a097ea1f2 --- /dev/null +++ b/ts-ticket-office-service/node_modules/mysql/lib/protocol/packets/ResultSetHeaderPacket.js @@ -0,0 +1,14 @@ +module.exports = ResultSetHeaderPacket; +function ResultSetHeaderPacket(options) { + options = options || {}; + + this.fieldCount = options.fieldCount; +} + +ResultSetHeaderPacket.prototype.parse = function(parser) { + this.fieldCount = parser.parseLengthCodedNumber(); +}; + +ResultSetHeaderPacket.prototype.write = function(writer) { + writer.writeLengthCodedNumber(this.fieldCount); +}; diff --git a/ts-ticket-office-service/node_modules/mysql/lib/protocol/packets/RowDataPacket.js b/ts-ticket-office-service/node_modules/mysql/lib/protocol/packets/RowDataPacket.js new file mode 100644 index 000000000..b8ec4b895 --- /dev/null +++ b/ts-ticket-office-service/node_modules/mysql/lib/protocol/packets/RowDataPacket.js @@ -0,0 +1,130 @@ +var Types = require('../constants/types'); +var Charsets = require('../constants/charsets'); +var Field = require('./Field'); +var IEEE_754_BINARY_64_PRECISION = Math.pow(2, 53); + +module.exports = RowDataPacket; +function RowDataPacket() { +} + +Object.defineProperty(RowDataPacket.prototype, 'parse', { + configurable : true, + enumerable : false, + value : parse +}); + +Object.defineProperty(RowDataPacket.prototype, '_typeCast', { + configurable : true, + enumerable : false, + value : typeCast +}); + +function parse(parser, fieldPackets, typeCast, nestTables, connection) { + var self = this; + var next = function () { + return self._typeCast(fieldPacket, parser, connection.config.timezone, connection.config.supportBigNumbers, connection.config.bigNumberStrings, connection.config.dateStrings); + }; + + for (var i = 0; i < fieldPackets.length; i++) { + var fieldPacket = fieldPackets[i]; + var value; + + if (typeof typeCast === 'function') { + value = typeCast.apply(connection, [ new Field({ packet: fieldPacket, parser: parser }), next ]); + } else { + value = (typeCast) + ? this._typeCast(fieldPacket, parser, connection.config.timezone, connection.config.supportBigNumbers, connection.config.bigNumberStrings, connection.config.dateStrings) + : ( (fieldPacket.charsetNr === Charsets.BINARY) + ? parser.parseLengthCodedBuffer() + : parser.parseLengthCodedString() ); + } + + if (typeof nestTables === 'string' && nestTables.length) { + this[fieldPacket.table + nestTables + fieldPacket.name] = value; + } else if (nestTables) { + this[fieldPacket.table] = this[fieldPacket.table] || {}; + this[fieldPacket.table][fieldPacket.name] = value; + } else { + this[fieldPacket.name] = value; + } + } +} + +function typeCast(field, parser, timeZone, supportBigNumbers, bigNumberStrings, dateStrings) { + var numberString; + + switch (field.type) { + case Types.TIMESTAMP: + case Types.TIMESTAMP2: + case Types.DATE: + case Types.DATETIME: + case Types.DATETIME2: + case Types.NEWDATE: + var dateString = parser.parseLengthCodedString(); + + if (typeMatch(field.type, dateStrings)) { + return dateString; + } + + if (dateString === null) { + return null; + } + + var originalString = dateString; + if (field.type === Types.DATE) { + dateString += ' 00:00:00'; + } + + if (timeZone !== 'local') { + dateString += ' ' + timeZone; + } + + var dt = new Date(dateString); + if (isNaN(dt.getTime())) { + return originalString; + } + + return dt; + case Types.TINY: + case Types.SHORT: + case Types.LONG: + case Types.INT24: + case Types.YEAR: + case Types.FLOAT: + case Types.DOUBLE: + numberString = parser.parseLengthCodedString(); + return (numberString === null || (field.zeroFill && numberString[0] === '0')) + ? numberString : Number(numberString); + case Types.NEWDECIMAL: + case Types.LONGLONG: + numberString = parser.parseLengthCodedString(); + return (numberString === null || (field.zeroFill && numberString[0] === '0')) + ? numberString + : ((supportBigNumbers && (bigNumberStrings || (Number(numberString) >= IEEE_754_BINARY_64_PRECISION) || Number(numberString) <= -IEEE_754_BINARY_64_PRECISION)) + ? numberString + : Number(numberString)); + case Types.BIT: + return parser.parseLengthCodedBuffer(); + case Types.STRING: + case Types.VAR_STRING: + case Types.TINY_BLOB: + case Types.MEDIUM_BLOB: + case Types.LONG_BLOB: + case Types.BLOB: + return (field.charsetNr === Charsets.BINARY) + ? parser.parseLengthCodedBuffer() + : parser.parseLengthCodedString(); + case Types.GEOMETRY: + return parser.parseGeometryValue(); + default: + return parser.parseLengthCodedString(); + } +} + +function typeMatch(type, list) { + if (Array.isArray(list)) { + return list.indexOf(Types[type]) !== -1; + } else { + return Boolean(list); + } +} diff --git a/ts-ticket-office-service/node_modules/mysql/lib/protocol/packets/SSLRequestPacket.js b/ts-ticket-office-service/node_modules/mysql/lib/protocol/packets/SSLRequestPacket.js new file mode 100644 index 000000000..a57cfc1a1 --- /dev/null +++ b/ts-ticket-office-service/node_modules/mysql/lib/protocol/packets/SSLRequestPacket.js @@ -0,0 +1,27 @@ +// http://dev.mysql.com/doc/internals/en/ssl.html +// http://dev.mysql.com/doc/internals/en/connection-phase-packets.html#packet-Protocol::SSLRequest + +var ClientConstants = require('../constants/client'); + +module.exports = SSLRequestPacket; + +function SSLRequestPacket(options) { + options = options || {}; + this.clientFlags = options.clientFlags | ClientConstants.CLIENT_SSL; + this.maxPacketSize = options.maxPacketSize; + this.charsetNumber = options.charsetNumber; +} + +SSLRequestPacket.prototype.parse = function(parser) { + // TODO: check SSLRequest packet v41 vs pre v41 + this.clientFlags = parser.parseUnsignedNumber(4); + this.maxPacketSize = parser.parseUnsignedNumber(4); + this.charsetNumber = parser.parseUnsignedNumber(1); +}; + +SSLRequestPacket.prototype.write = function(writer) { + writer.writeUnsignedNumber(4, this.clientFlags); + writer.writeUnsignedNumber(4, this.maxPacketSize); + writer.writeUnsignedNumber(1, this.charsetNumber); + writer.writeFiller(23); +}; diff --git a/ts-ticket-office-service/node_modules/mysql/lib/protocol/packets/StatisticsPacket.js b/ts-ticket-office-service/node_modules/mysql/lib/protocol/packets/StatisticsPacket.js new file mode 100644 index 000000000..5f70b3ba7 --- /dev/null +++ b/ts-ticket-office-service/node_modules/mysql/lib/protocol/packets/StatisticsPacket.js @@ -0,0 +1,20 @@ +module.exports = StatisticsPacket; +function StatisticsPacket() { + this.message = undefined; +} + +StatisticsPacket.prototype.parse = function(parser) { + this.message = parser.parsePacketTerminatedString(); + + var items = this.message.split(/\s\s/); + for (var i = 0; i < items.length; i++) { + var m = items[i].match(/^(.+)\:\s+(.+)$/); + if (m !== null) { + this[m[1].toLowerCase().replace(/\s/g, '_')] = Number(m[2]); + } + } +}; + +StatisticsPacket.prototype.write = function(writer) { + writer.writeString(this.message); +}; diff --git a/ts-ticket-office-service/node_modules/mysql/lib/protocol/packets/UseOldPasswordPacket.js b/ts-ticket-office-service/node_modules/mysql/lib/protocol/packets/UseOldPasswordPacket.js new file mode 100644 index 000000000..d73bf4459 --- /dev/null +++ b/ts-ticket-office-service/node_modules/mysql/lib/protocol/packets/UseOldPasswordPacket.js @@ -0,0 +1,14 @@ +module.exports = UseOldPasswordPacket; +function UseOldPasswordPacket(options) { + options = options || {}; + + this.firstByte = options.firstByte || 0xfe; +} + +UseOldPasswordPacket.prototype.parse = function(parser) { + this.firstByte = parser.parseUnsignedNumber(1); +}; + +UseOldPasswordPacket.prototype.write = function(writer) { + writer.writeUnsignedNumber(1, this.firstByte); +}; diff --git a/ts-ticket-office-service/node_modules/mysql/lib/protocol/packets/index.js b/ts-ticket-office-service/node_modules/mysql/lib/protocol/packets/index.js new file mode 100644 index 000000000..5e9352457 --- /dev/null +++ b/ts-ticket-office-service/node_modules/mysql/lib/protocol/packets/index.js @@ -0,0 +1,23 @@ +exports.AuthSwitchRequestPacket = require('./AuthSwitchRequestPacket'); +exports.AuthSwitchResponsePacket = require('./AuthSwitchResponsePacket'); +exports.ClientAuthenticationPacket = require('./ClientAuthenticationPacket'); +exports.ComChangeUserPacket = require('./ComChangeUserPacket'); +exports.ComPingPacket = require('./ComPingPacket'); +exports.ComQueryPacket = require('./ComQueryPacket'); +exports.ComQuitPacket = require('./ComQuitPacket'); +exports.ComStatisticsPacket = require('./ComStatisticsPacket'); +exports.EmptyPacket = require('./EmptyPacket'); +exports.EofPacket = require('./EofPacket'); +exports.ErrorPacket = require('./ErrorPacket'); +exports.Field = require('./Field'); +exports.FieldPacket = require('./FieldPacket'); +exports.HandshakeInitializationPacket = require('./HandshakeInitializationPacket'); +exports.LocalDataFilePacket = require('./LocalDataFilePacket'); +exports.LocalInfileRequestPacket = require('./LocalInfileRequestPacket'); +exports.OkPacket = require('./OkPacket'); +exports.OldPasswordPacket = require('./OldPasswordPacket'); +exports.ResultSetHeaderPacket = require('./ResultSetHeaderPacket'); +exports.RowDataPacket = require('./RowDataPacket'); +exports.SSLRequestPacket = require('./SSLRequestPacket'); +exports.StatisticsPacket = require('./StatisticsPacket'); +exports.UseOldPasswordPacket = require('./UseOldPasswordPacket'); diff --git a/ts-ticket-office-service/node_modules/mysql/lib/protocol/sequences/ChangeUser.js b/ts-ticket-office-service/node_modules/mysql/lib/protocol/sequences/ChangeUser.js new file mode 100644 index 000000000..e1cc1fbc3 --- /dev/null +++ b/ts-ticket-office-service/node_modules/mysql/lib/protocol/sequences/ChangeUser.js @@ -0,0 +1,67 @@ +var Sequence = require('./Sequence'); +var Util = require('util'); +var Packets = require('../packets'); +var Auth = require('../Auth'); + +module.exports = ChangeUser; +Util.inherits(ChangeUser, Sequence); +function ChangeUser(options, callback) { + Sequence.call(this, options, callback); + + this._user = options.user; + this._password = options.password; + this._database = options.database; + this._charsetNumber = options.charsetNumber; + this._currentConfig = options.currentConfig; +} + +ChangeUser.prototype.determinePacket = function determinePacket(firstByte) { + switch (firstByte) { + case 0xfe: return Packets.AuthSwitchRequestPacket; + case 0xff: return Packets.ErrorPacket; + default: return undefined; + } +}; + +ChangeUser.prototype.start = function(handshakeInitializationPacket) { + var scrambleBuff = handshakeInitializationPacket.scrambleBuff(); + scrambleBuff = Auth.token(this._password, scrambleBuff); + + var packet = new Packets.ComChangeUserPacket({ + user : this._user, + scrambleBuff : scrambleBuff, + database : this._database, + charsetNumber : this._charsetNumber + }); + + this._currentConfig.user = this._user; + this._currentConfig.password = this._password; + this._currentConfig.database = this._database; + this._currentConfig.charsetNumber = this._charsetNumber; + + this.emit('packet', packet); +}; + +ChangeUser.prototype['AuthSwitchRequestPacket'] = function (packet) { + var name = packet.authMethodName; + var data = Auth.auth(name, packet.authMethodData, { + password: this._password + }); + + if (data !== undefined) { + this.emit('packet', new Packets.AuthSwitchResponsePacket({ + data: data + })); + } else { + var err = new Error('MySQL is requesting the ' + name + ' authentication method, which is not supported.'); + err.code = 'UNSUPPORTED_AUTH_METHOD'; + err.fatal = true; + this.end(err); + } +}; + +ChangeUser.prototype['ErrorPacket'] = function(packet) { + var err = this._packetToError(packet); + err.fatal = true; + this.end(err); +}; diff --git a/ts-ticket-office-service/node_modules/mysql/lib/protocol/sequences/Handshake.js b/ts-ticket-office-service/node_modules/mysql/lib/protocol/sequences/Handshake.js new file mode 100644 index 000000000..8fad0fcf3 --- /dev/null +++ b/ts-ticket-office-service/node_modules/mysql/lib/protocol/sequences/Handshake.js @@ -0,0 +1,126 @@ +var Sequence = require('./Sequence'); +var Util = require('util'); +var Packets = require('../packets'); +var Auth = require('../Auth'); +var ClientConstants = require('../constants/client'); + +module.exports = Handshake; +Util.inherits(Handshake, Sequence); +function Handshake(options, callback) { + Sequence.call(this, options, callback); + + options = options || {}; + + this._config = options.config; + this._handshakeInitializationPacket = null; +} + +Handshake.prototype.determinePacket = function determinePacket(firstByte, parser) { + if (firstByte === 0xff) { + return Packets.ErrorPacket; + } + + if (!this._handshakeInitializationPacket) { + return Packets.HandshakeInitializationPacket; + } + + if (firstByte === 0xfe) { + return (parser.packetLength() === 1) + ? Packets.UseOldPasswordPacket + : Packets.AuthSwitchRequestPacket; + } + + return undefined; +}; + +Handshake.prototype['AuthSwitchRequestPacket'] = function (packet) { + var name = packet.authMethodName; + var data = Auth.auth(name, packet.authMethodData, { + password: this._config.password + }); + + if (data !== undefined) { + this.emit('packet', new Packets.AuthSwitchResponsePacket({ + data: data + })); + } else { + var err = new Error('MySQL is requesting the ' + name + ' authentication method, which is not supported.'); + err.code = 'UNSUPPORTED_AUTH_METHOD'; + err.fatal = true; + this.end(err); + } +}; + +Handshake.prototype['HandshakeInitializationPacket'] = function(packet) { + this._handshakeInitializationPacket = packet; + + this._config.protocol41 = packet.protocol41; + + var serverSSLSupport = packet.serverCapabilities1 & ClientConstants.CLIENT_SSL; + + if (this._config.ssl) { + if (!serverSSLSupport) { + var err = new Error('Server does not support secure connection'); + + err.code = 'HANDSHAKE_NO_SSL_SUPPORT'; + err.fatal = true; + + this.end(err); + return; + } + + this._config.clientFlags |= ClientConstants.CLIENT_SSL; + this.emit('packet', new Packets.SSLRequestPacket({ + clientFlags : this._config.clientFlags, + maxPacketSize : this._config.maxPacketSize, + charsetNumber : this._config.charsetNumber + })); + this.emit('start-tls'); + } else { + this._sendCredentials(); + } +}; + +Handshake.prototype._tlsUpgradeCompleteHandler = function() { + this._sendCredentials(); +}; + +Handshake.prototype._sendCredentials = function() { + var packet = this._handshakeInitializationPacket; + this.emit('packet', new Packets.ClientAuthenticationPacket({ + clientFlags : this._config.clientFlags, + maxPacketSize : this._config.maxPacketSize, + charsetNumber : this._config.charsetNumber, + user : this._config.user, + database : this._config.database, + protocol41 : packet.protocol41, + scrambleBuff : (packet.protocol41) + ? Auth.token(this._config.password, packet.scrambleBuff()) + : Auth.scramble323(packet.scrambleBuff(), this._config.password) + })); +}; + +Handshake.prototype['UseOldPasswordPacket'] = function() { + if (!this._config.insecureAuth) { + var err = new Error( + 'MySQL server is requesting the old and insecure pre-4.1 auth mechanism. ' + + 'Upgrade the user password or use the {insecureAuth: true} option.' + ); + + err.code = 'HANDSHAKE_INSECURE_AUTH'; + err.fatal = true; + + this.end(err); + return; + } + + this.emit('packet', new Packets.OldPasswordPacket({ + scrambleBuff: Auth.scramble323(this._handshakeInitializationPacket.scrambleBuff(), this._config.password) + })); +}; + +Handshake.prototype['ErrorPacket'] = function(packet) { + var err = this._packetToError(packet, true); + err.fatal = true; + this.end(err); +}; diff --git a/ts-ticket-office-service/node_modules/mysql/lib/protocol/sequences/Ping.js b/ts-ticket-office-service/node_modules/mysql/lib/protocol/sequences/Ping.js new file mode 100644 index 000000000..230f3c1ab --- /dev/null +++ b/ts-ticket-office-service/node_modules/mysql/lib/protocol/sequences/Ping.js @@ -0,0 +1,19 @@ +var Sequence = require('./Sequence'); +var Util = require('util'); +var Packets = require('../packets'); + +module.exports = Ping; +Util.inherits(Ping, Sequence); + +function Ping(options, callback) { + if (!callback && typeof options === 'function') { + callback = options; + options = {}; + } + + Sequence.call(this, options, callback); +} + +Ping.prototype.start = function() { + this.emit('packet', new Packets.ComPingPacket()); +}; diff --git a/ts-ticket-office-service/node_modules/mysql/lib/protocol/sequences/Query.js b/ts-ticket-office-service/node_modules/mysql/lib/protocol/sequences/Query.js new file mode 100644 index 000000000..b7632959b --- /dev/null +++ b/ts-ticket-office-service/node_modules/mysql/lib/protocol/sequences/Query.js @@ -0,0 +1,228 @@ +var ClientConstants = require('../constants/client'); +var fs = require('fs'); +var Packets = require('../packets'); +var ResultSet = require('../ResultSet'); +var Sequence = require('./Sequence'); +var ServerStatus = require('../constants/server_status'); +var Readable = require('readable-stream'); +var Util = require('util'); + +module.exports = Query; +Util.inherits(Query, Sequence); +function Query(options, callback) { + Sequence.call(this, options, callback); + + this.sql = options.sql; + this.values = options.values; + this.typeCast = (options.typeCast === undefined) + ? true + : options.typeCast; + this.nestTables = options.nestTables || false; + + this._resultSet = null; + this._results = []; + this._fields = []; + this._index = 0; + this._loadError = null; +} + +Query.prototype.start = function() { + this.emit('packet', new Packets.ComQueryPacket(this.sql)); +}; + +Query.prototype.determinePacket = function determinePacket(byte, parser) { + var resultSet = this._resultSet; + + if (!resultSet) { + switch (byte) { + case 0x00: return Packets.OkPacket; + case 0xfb: return Packets.LocalInfileRequestPacket; + case 0xff: return Packets.ErrorPacket; + default: return Packets.ResultSetHeaderPacket; + } + } + + if (resultSet.eofPackets.length === 0) { + return (resultSet.fieldPackets.length < resultSet.resultSetHeaderPacket.fieldCount) + ? Packets.FieldPacket + : Packets.EofPacket; + } + + if (byte === 0xff) { + return Packets.ErrorPacket; + } + + if (byte === 0xfe && parser.packetLength() < 9) { + return Packets.EofPacket; + } + + return Packets.RowDataPacket; +}; + +Query.prototype['OkPacket'] = function(packet) { + // try...finally for exception safety + try { + if (!this._callback) { + this.emit('result', packet, this._index); + } else { + this._results.push(packet); + this._fields.push(undefined); + } + } finally { + this._index++; + this._resultSet = null; + this._handleFinalResultPacket(packet); + } +}; + +Query.prototype['ErrorPacket'] = function(packet) { + var err = this._packetToError(packet); + + var results = (this._results.length > 0) + ? this._results + : undefined; + + var fields = (this._fields.length > 0) + ? this._fields + : undefined; + + err.index = this._index; + err.sql = this.sql; + + this.end(err, results, fields); +}; + +Query.prototype['LocalInfileRequestPacket'] = function(packet) { + if (this._connection.config.clientFlags & ClientConstants.CLIENT_LOCAL_FILES) { + this._sendLocalDataFile(packet.filename); + } else { + this._loadError = new Error('Load local files command is disabled'); + this._loadError.code = 'LOCAL_FILES_DISABLED'; + this._loadError.fatal = false; + + this.emit('packet', new Packets.EmptyPacket()); + } +}; + +Query.prototype['ResultSetHeaderPacket'] = function(packet) { + this._resultSet = new ResultSet(packet); +}; + +Query.prototype['FieldPacket'] = function(packet) { + this._resultSet.fieldPackets.push(packet); +}; + +Query.prototype['EofPacket'] = function(packet) { + this._resultSet.eofPackets.push(packet); + + if (this._resultSet.eofPackets.length === 1 && !this._callback) { + this.emit('fields', this._resultSet.fieldPackets, this._index); + } + + if (this._resultSet.eofPackets.length !== 2) { + return; + } + + if (this._callback) { + this._results.push(this._resultSet.rows); + this._fields.push(this._resultSet.fieldPackets); + } + + this._index++; + this._resultSet = null; + this._handleFinalResultPacket(packet); +}; + +Query.prototype._handleFinalResultPacket = function(packet) { + if (packet.serverStatus & ServerStatus.SERVER_MORE_RESULTS_EXISTS) { + return; + } + + var results = (this._results.length > 1) + ? this._results + : this._results[0]; + + var fields = (this._fields.length > 1) + ? this._fields + : this._fields[0]; + + this.end(this._loadError, results, fields); +}; + +Query.prototype['RowDataPacket'] = function(packet, parser, connection) { + packet.parse(parser, this._resultSet.fieldPackets, this.typeCast, this.nestTables, connection); + + if (this._callback) { + this._resultSet.rows.push(packet); + } else { + this.emit('result', packet, this._index); + } +}; + +Query.prototype._sendLocalDataFile = function(path) { + var self = this; + var localStream = fs.createReadStream(path, { + flag : 'r', + encoding : null, + autoClose : true + }); + + this.on('pause', function () { + localStream.pause(); + }); + + this.on('resume', function () { + localStream.resume(); + }); + + localStream.on('data', function (data) { + self.emit('packet', new Packets.LocalDataFilePacket(data)); + }); + + localStream.on('error', function (err) { + self._loadError = err; + localStream.emit('end'); + }); + + localStream.on('end', function () { + self.emit('packet', new Packets.EmptyPacket()); + }); +}; + +Query.prototype.stream = function(options) { + var self = this; + + options = options || {}; + options.objectMode = true; + + var stream = new Readable(options); + + stream._read = function() { + self._connection && self._connection.resume(); + }; + + stream.once('end', function() { + process.nextTick(function () { + stream.emit('close'); + }); + }); + + this.on('result', function(row, i) { + if (!stream.push(row)) self._connection.pause(); + stream.emit('result', row, i); // replicate old emitter + }); + + this.on('error', function(err) { + stream.emit('error', err); // Pass on any errors + }); + + this.on('end', function() { + stream.push(null); // pushing null, indicating EOF + }); + + this.on('fields', function(fields, i) { + stream.emit('fields', fields, i); // replicate old emitter + }); + + return stream; +}; diff --git a/ts-ticket-office-service/node_modules/mysql/lib/protocol/sequences/Quit.js b/ts-ticket-office-service/node_modules/mysql/lib/protocol/sequences/Quit.js new file mode 100644 index 000000000..3c34c5820 --- /dev/null +++ b/ts-ticket-office-service/node_modules/mysql/lib/protocol/sequences/Quit.js @@ -0,0 +1,40 @@ +var Sequence = require('./Sequence'); +var Util = require('util'); +var Packets = require('../packets'); + +module.exports = Quit; +Util.inherits(Quit, Sequence); +function Quit(options, callback) { + if (!callback && typeof options === 'function') { + callback = options; + options = {}; + } + + Sequence.call(this, options, callback); + + this._started = false; +} + +Quit.prototype.end = function end(err) { + if (this._ended) { + return; + } + + if (!this._started) { + Sequence.prototype.end.call(this, err); + return; + } + + if (err && err.code === 'ECONNRESET' && err.syscall === 'read') { + // Ignore read errors after packet sent + Sequence.prototype.end.call(this); + return; + } + + Sequence.prototype.end.call(this, err); +}; + +Quit.prototype.start = function() { + this._started = true; + this.emit('packet', new Packets.ComQuitPacket()); +}; diff --git a/ts-ticket-office-service/node_modules/mysql/lib/protocol/sequences/Sequence.js b/ts-ticket-office-service/node_modules/mysql/lib/protocol/sequences/Sequence.js new file mode 100644 index 000000000..de82dc270 --- /dev/null +++ b/ts-ticket-office-service/node_modules/mysql/lib/protocol/sequences/Sequence.js @@ -0,0 +1,125 @@ +var Util = require('util'); +var EventEmitter = require('events').EventEmitter; +var Packets = require('../packets'); +var ErrorConstants = require('../constants/errors'); +var Timer = require('../Timer'); + +// istanbul ignore next: Node.js < 0.10 not covered +var listenerCount = EventEmitter.listenerCount + || function(emitter, type){ return emitter.listeners(type).length; }; + +var LONG_STACK_DELIMITER = '\n --------------------\n'; + +module.exports = Sequence; +Util.inherits(Sequence, EventEmitter); +function Sequence(options, callback) { + if (typeof options === 'function') { + callback = options; + options = {}; + } + + EventEmitter.call(this); + + options = options || {}; + + this._callback = callback; + this._callSite = null; + this._ended = false; + this._timeout = options.timeout; + this._timer = new Timer(this); +} + +Sequence.determinePacket = function(byte) { + switch (byte) { + case 0x00: return Packets.OkPacket; + case 0xfe: return Packets.EofPacket; + case 0xff: return Packets.ErrorPacket; + default: return undefined; + } +}; + +Sequence.prototype.hasErrorHandler = function() { + return Boolean(this._callback) || listenerCount(this, 'error') > 1; +}; + +Sequence.prototype._packetToError = function(packet) { + var code = ErrorConstants[packet.errno] || 'UNKNOWN_CODE_PLEASE_REPORT'; + var err = new Error(code + ': ' + packet.message); + err.code = code; + err.errno = packet.errno; + + err.sqlMessage = packet.message; + err.sqlState = packet.sqlState; + + return err; +}; + +Sequence.prototype.end = function(err) { + if (this._ended) { + return; + } + + this._ended = true; + + if (err) { + this._addLongStackTrace(err); + } + + // Without this we are leaking memory. This problem was introduced in + // 8189925374e7ce3819bbe88b64c7b15abac96b16. I suspect that the error object + // causes a cyclic reference that the GC does not detect properly, but I was + // unable to produce a standalone version of this leak. This would be a great + // challenge for somebody interested in difficult problems : )! + this._callSite = null; + + // try...finally for exception safety + try { + if (err) { + this.emit('error', err); + } + } finally { + try { + if (this._callback) { + this._callback.apply(this, arguments); + } + } finally { + this.emit('end'); + } + } +}; + +Sequence.prototype['OkPacket'] = function(packet) { + this.end(null, packet); +}; + +Sequence.prototype['ErrorPacket'] = function(packet) { + this.end(this._packetToError(packet)); +}; + +// Implemented by child classes +Sequence.prototype.start = function() {}; + +Sequence.prototype._addLongStackTrace = function _addLongStackTrace(err) { + var callSiteStack = this._callSite && this._callSite.stack; + + if (!callSiteStack || typeof callSiteStack !== 'string') { + // No recorded call site + return; + } + + if (err.stack.indexOf(LONG_STACK_DELIMITER) !== -1) { + // Error stack already looks long + return; + } + + var index = callSiteStack.indexOf('\n'); + + if (index !== -1) { + // Append recorded call site + err.stack += LONG_STACK_DELIMITER + callSiteStack.substr(index + 1); + } +}; + +Sequence.prototype._onTimeout = function _onTimeout() { + this.emit('timeout'); +}; diff --git a/ts-ticket-office-service/node_modules/mysql/lib/protocol/sequences/Statistics.js b/ts-ticket-office-service/node_modules/mysql/lib/protocol/sequences/Statistics.js new file mode 100644 index 000000000..c75b5d936 --- /dev/null +++ b/ts-ticket-office-service/node_modules/mysql/lib/protocol/sequences/Statistics.js @@ -0,0 +1,30 @@ +var Sequence = require('./Sequence'); +var Util = require('util'); +var Packets = require('../packets'); + +module.exports = Statistics; +Util.inherits(Statistics, Sequence); +function Statistics(options, callback) { + if (!callback && typeof options === 'function') { + callback = options; + options = {}; + } + + Sequence.call(this, options, callback); +} + +Statistics.prototype.start = function() { + this.emit('packet', new Packets.ComStatisticsPacket()); +}; + +Statistics.prototype['StatisticsPacket'] = function (packet) { + this.end(null, packet); +}; + +Statistics.prototype.determinePacket = function determinePacket(firstByte) { + if (firstByte === 0x55) { + return Packets.StatisticsPacket; + } + + return undefined; +}; diff --git a/ts-ticket-office-service/node_modules/mysql/lib/protocol/sequences/index.js b/ts-ticket-office-service/node_modules/mysql/lib/protocol/sequences/index.js new file mode 100644 index 000000000..0eae5ce63 --- /dev/null +++ b/ts-ticket-office-service/node_modules/mysql/lib/protocol/sequences/index.js @@ -0,0 +1,7 @@ +exports.ChangeUser = require('./ChangeUser'); +exports.Handshake = require('./Handshake'); +exports.Ping = require('./Ping'); +exports.Query = require('./Query'); +exports.Quit = require('./Quit'); +exports.Sequence = require('./Sequence'); +exports.Statistics = require('./Statistics'); diff --git a/ts-ticket-office-service/node_modules/process-nextick-args/index.js b/ts-ticket-office-service/node_modules/mysql/node_modules/process-nextick-args/index.js similarity index 87% rename from ts-ticket-office-service/node_modules/process-nextick-args/index.js rename to ts-ticket-office-service/node_modules/mysql/node_modules/process-nextick-args/index.js index a4f40f845..3eecf1148 100644 --- a/ts-ticket-office-service/node_modules/process-nextick-args/index.js +++ b/ts-ticket-office-service/node_modules/mysql/node_modules/process-nextick-args/index.js @@ -1,11 +1,12 @@ 'use strict'; -if (!process.version || +if (typeof process === 'undefined' || + !process.version || process.version.indexOf('v0.') === 0 || process.version.indexOf('v1.') === 0 && process.version.indexOf('v1.8.') !== 0) { - module.exports = nextTick; + module.exports = { nextTick: nextTick }; } else { - module.exports = process.nextTick; + module.exports = process } function nextTick(fn, arg1, arg2, arg3) { @@ -41,3 +42,4 @@ function nextTick(fn, arg1, arg2, arg3) { }); } } + diff --git a/ts-ticket-office-service/node_modules/process-nextick-args/license.md b/ts-ticket-office-service/node_modules/mysql/node_modules/process-nextick-args/license.md similarity index 100% rename from ts-ticket-office-service/node_modules/process-nextick-args/license.md rename to ts-ticket-office-service/node_modules/mysql/node_modules/process-nextick-args/license.md diff --git a/ts-ticket-office-service/node_modules/mysql/node_modules/process-nextick-args/package.json b/ts-ticket-office-service/node_modules/mysql/node_modules/process-nextick-args/package.json new file mode 100644 index 000000000..6070b723f --- /dev/null +++ b/ts-ticket-office-service/node_modules/mysql/node_modules/process-nextick-args/package.json @@ -0,0 +1,25 @@ +{ + "name": "process-nextick-args", + "version": "2.0.1", + "description": "process.nextTick but always with args", + "main": "index.js", + "files": [ + "index.js" + ], + "scripts": { + "test": "node test.js" + }, + "repository": { + "type": "git", + "url": "https://github.com/calvinmetcalf/process-nextick-args.git" + }, + "author": "", + "license": "MIT", + "bugs": { + "url": "https://github.com/calvinmetcalf/process-nextick-args/issues" + }, + "homepage": "https://github.com/calvinmetcalf/process-nextick-args", + "devDependencies": { + "tap": "~0.2.6" + } +} diff --git a/ts-ticket-office-service/node_modules/process-nextick-args/readme.md b/ts-ticket-office-service/node_modules/mysql/node_modules/process-nextick-args/readme.md similarity index 82% rename from ts-ticket-office-service/node_modules/process-nextick-args/readme.md rename to ts-ticket-office-service/node_modules/mysql/node_modules/process-nextick-args/readme.md index 78e7cfaeb..ecb432c9b 100644 --- a/ts-ticket-office-service/node_modules/process-nextick-args/readme.md +++ b/ts-ticket-office-service/node_modules/mysql/node_modules/process-nextick-args/readme.md @@ -10,9 +10,9 @@ npm install --save process-nextick-args Always be able to pass arguments to process.nextTick, no matter the platform ```js -var nextTick = require('process-nextick-args'); +var pna = require('process-nextick-args'); -nextTick(function (a, b, c) { +pna.nextTick(function (a, b, c) { console.log(a, b, c); }, 'step', 3, 'profit'); ``` diff --git a/ts-ticket-office-service/node_modules/readable-stream/CONTRIBUTING.md b/ts-ticket-office-service/node_modules/mysql/node_modules/readable-stream/CONTRIBUTING.md similarity index 100% rename from ts-ticket-office-service/node_modules/readable-stream/CONTRIBUTING.md rename to ts-ticket-office-service/node_modules/mysql/node_modules/readable-stream/CONTRIBUTING.md diff --git a/ts-ticket-office-service/node_modules/readable-stream/GOVERNANCE.md b/ts-ticket-office-service/node_modules/mysql/node_modules/readable-stream/GOVERNANCE.md similarity index 100% rename from ts-ticket-office-service/node_modules/readable-stream/GOVERNANCE.md rename to ts-ticket-office-service/node_modules/mysql/node_modules/readable-stream/GOVERNANCE.md diff --git a/ts-ticket-office-service/node_modules/readable-stream/LICENSE b/ts-ticket-office-service/node_modules/mysql/node_modules/readable-stream/LICENSE similarity index 100% rename from ts-ticket-office-service/node_modules/readable-stream/LICENSE rename to ts-ticket-office-service/node_modules/mysql/node_modules/readable-stream/LICENSE diff --git a/ts-ticket-office-service/node_modules/readable-stream/README.md b/ts-ticket-office-service/node_modules/mysql/node_modules/readable-stream/README.md similarity index 89% rename from ts-ticket-office-service/node_modules/readable-stream/README.md rename to ts-ticket-office-service/node_modules/mysql/node_modules/readable-stream/README.md index ff75b0d79..23fe3f3e3 100644 --- a/ts-ticket-office-service/node_modules/readable-stream/README.md +++ b/ts-ticket-office-service/node_modules/mysql/node_modules/readable-stream/README.md @@ -1,6 +1,6 @@ # readable-stream -***Node-core v7.0.0 streams for userland*** [![Build Status](https://travis-ci.org/nodejs/readable-stream.svg?branch=master)](https://travis-ci.org/nodejs/readable-stream) +***Node-core v8.11.1 streams for userland*** [![Build Status](https://travis-ci.org/nodejs/readable-stream.svg?branch=master)](https://travis-ci.org/nodejs/readable-stream) [![NPM](https://nodei.co/npm/readable-stream.png?downloads=true&downloadRank=true)](https://nodei.co/npm/readable-stream/) @@ -18,7 +18,7 @@ npm install --save readable-stream This package is a mirror of the Streams2 and Streams3 implementations in Node-core. -Full documentation may be found on the [Node.js website](https://nodejs.org/dist/v7.7.3/docs/api/). +Full documentation may be found on the [Node.js website](https://nodejs.org/dist/v8.11.1/docs/api/stream.html). If you want to guarantee a stable streams base, regardless of what version of Node you, or the users of your libraries are using, use **readable-stream** *only* and avoid the *"stream"* module in Node-core, for background see [this blogpost](http://r.va.gg/2014/06/why-i-dont-use-nodes-core-stream-module.html). @@ -55,3 +55,4 @@ Node.js. The responsibilities of the Streams Working Group include: * **Domenic Denicola** ([@domenic](https://github.com/domenic)) <d@domenic.me> * **Matteo Collina** ([@mcollina](https://github.com/mcollina)) <matteo.collina@gmail.com> - Release GPG key: 3ABC01543F22DD2239285CDD818674489FBC127E +* **Irina Shestak** ([@lrlna](https://github.com/lrlna)) <shestak.irina@gmail.com> diff --git a/ts-ticket-office-service/node_modules/readable-stream/doc/wg-meetings/2015-01-30.md b/ts-ticket-office-service/node_modules/mysql/node_modules/readable-stream/doc/wg-meetings/2015-01-30.md similarity index 100% rename from ts-ticket-office-service/node_modules/readable-stream/doc/wg-meetings/2015-01-30.md rename to ts-ticket-office-service/node_modules/mysql/node_modules/readable-stream/doc/wg-meetings/2015-01-30.md diff --git a/ts-ticket-office-service/node_modules/readable-stream/duplex-browser.js b/ts-ticket-office-service/node_modules/mysql/node_modules/readable-stream/duplex-browser.js similarity index 100% rename from ts-ticket-office-service/node_modules/readable-stream/duplex-browser.js rename to ts-ticket-office-service/node_modules/mysql/node_modules/readable-stream/duplex-browser.js diff --git a/ts-ticket-office-service/node_modules/readable-stream/duplex.js b/ts-ticket-office-service/node_modules/mysql/node_modules/readable-stream/duplex.js similarity index 100% rename from ts-ticket-office-service/node_modules/readable-stream/duplex.js rename to ts-ticket-office-service/node_modules/mysql/node_modules/readable-stream/duplex.js diff --git a/ts-ticket-office-service/node_modules/mysql/node_modules/readable-stream/lib/_stream_duplex.js b/ts-ticket-office-service/node_modules/mysql/node_modules/readable-stream/lib/_stream_duplex.js new file mode 100644 index 000000000..57003c32d --- /dev/null +++ b/ts-ticket-office-service/node_modules/mysql/node_modules/readable-stream/lib/_stream_duplex.js @@ -0,0 +1,131 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +// a duplex stream is just a stream that is both readable and writable. +// Since JS doesn't have multiple prototypal inheritance, this class +// prototypally inherits from Readable, and then parasitically from +// Writable. + +'use strict'; + +/**/ + +var pna = require('process-nextick-args'); +/**/ + +/**/ +var objectKeys = Object.keys || function (obj) { + var keys = []; + for (var key in obj) { + keys.push(key); + }return keys; +}; +/**/ + +module.exports = Duplex; + +/**/ +var util = Object.create(require('core-util-is')); +util.inherits = require('inherits'); +/**/ + +var Readable = require('./_stream_readable'); +var Writable = require('./_stream_writable'); + +util.inherits(Duplex, Readable); + +{ + // avoid scope creep, the keys array can then be collected + var keys = objectKeys(Writable.prototype); + for (var v = 0; v < keys.length; v++) { + var method = keys[v]; + if (!Duplex.prototype[method]) Duplex.prototype[method] = Writable.prototype[method]; + } +} + +function Duplex(options) { + if (!(this instanceof Duplex)) return new Duplex(options); + + Readable.call(this, options); + Writable.call(this, options); + + if (options && options.readable === false) this.readable = false; + + if (options && options.writable === false) this.writable = false; + + this.allowHalfOpen = true; + if (options && options.allowHalfOpen === false) this.allowHalfOpen = false; + + this.once('end', onend); +} + +Object.defineProperty(Duplex.prototype, 'writableHighWaterMark', { + // making it explicit this property is not enumerable + // because otherwise some prototype manipulation in + // userland will fail + enumerable: false, + get: function () { + return this._writableState.highWaterMark; + } +}); + +// the no-half-open enforcer +function onend() { + // if we allow half-open state, or if the writable side ended, + // then we're ok. + if (this.allowHalfOpen || this._writableState.ended) return; + + // no more data can be written. + // But allow more writes to happen in this tick. + pna.nextTick(onEndNT, this); +} + +function onEndNT(self) { + self.end(); +} + +Object.defineProperty(Duplex.prototype, 'destroyed', { + get: function () { + if (this._readableState === undefined || this._writableState === undefined) { + return false; + } + return this._readableState.destroyed && this._writableState.destroyed; + }, + set: function (value) { + // we ignore the value if the stream + // has not been initialized yet + if (this._readableState === undefined || this._writableState === undefined) { + return; + } + + // backward compatibility, the user is explicitly + // managing destroyed + this._readableState.destroyed = value; + this._writableState.destroyed = value; + } +}); + +Duplex.prototype._destroy = function (err, cb) { + this.push(null); + this.end(); + + pna.nextTick(cb, err); +}; \ No newline at end of file diff --git a/ts-ticket-office-service/node_modules/mysql/node_modules/readable-stream/lib/_stream_passthrough.js b/ts-ticket-office-service/node_modules/mysql/node_modules/readable-stream/lib/_stream_passthrough.js new file mode 100644 index 000000000..612edb4d8 --- /dev/null +++ b/ts-ticket-office-service/node_modules/mysql/node_modules/readable-stream/lib/_stream_passthrough.js @@ -0,0 +1,47 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +// a passthrough stream. +// basically just the most minimal sort of Transform stream. +// Every written chunk gets output as-is. + +'use strict'; + +module.exports = PassThrough; + +var Transform = require('./_stream_transform'); + +/**/ +var util = Object.create(require('core-util-is')); +util.inherits = require('inherits'); +/**/ + +util.inherits(PassThrough, Transform); + +function PassThrough(options) { + if (!(this instanceof PassThrough)) return new PassThrough(options); + + Transform.call(this, options); +} + +PassThrough.prototype._transform = function (chunk, encoding, cb) { + cb(null, chunk); +}; \ No newline at end of file diff --git a/ts-ticket-office-service/node_modules/readable-stream/lib/_stream_readable.js b/ts-ticket-office-service/node_modules/mysql/node_modules/readable-stream/lib/_stream_readable.js similarity index 75% rename from ts-ticket-office-service/node_modules/readable-stream/lib/_stream_readable.js rename to ts-ticket-office-service/node_modules/mysql/node_modules/readable-stream/lib/_stream_readable.js index 13b5a7474..0f807646b 100644 --- a/ts-ticket-office-service/node_modules/readable-stream/lib/_stream_readable.js +++ b/ts-ticket-office-service/node_modules/mysql/node_modules/readable-stream/lib/_stream_readable.js @@ -1,11 +1,33 @@ -'use strict'; +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. -module.exports = Readable; +'use strict'; /**/ -var processNextTick = require('process-nextick-args'); + +var pna = require('process-nextick-args'); /**/ +module.exports = Readable; + /**/ var isArray = require('isarray'); /**/ @@ -25,23 +47,24 @@ var EElistenerCount = function (emitter, type) { /**/ /**/ -var Stream; -(function () { - try { - Stream = require('st' + 'ream'); - } catch (_) {} finally { - if (!Stream) Stream = require('events').EventEmitter; - } -})(); +var Stream = require('./internal/streams/stream'); /**/ -var Buffer = require('buffer').Buffer; /**/ -var bufferShim = require('buffer-shims'); + +var Buffer = require('safe-buffer').Buffer; +var OurUint8Array = global.Uint8Array || function () {}; +function _uint8ArrayToBuffer(chunk) { + return Buffer.from(chunk); +} +function _isUint8Array(obj) { + return Buffer.isBuffer(obj) || obj instanceof OurUint8Array; +} + /**/ /**/ -var util = require('core-util-is'); +var util = Object.create(require('core-util-is')); util.inherits = require('inherits'); /**/ @@ -56,22 +79,23 @@ if (debugUtil && debugUtil.debuglog) { /**/ var BufferList = require('./internal/streams/BufferList'); +var destroyImpl = require('./internal/streams/destroy'); var StringDecoder; util.inherits(Readable, Stream); +var kProxyEvents = ['error', 'close', 'destroy', 'pause', 'resume']; + function prependListener(emitter, event, fn) { // Sadly this is not cacheable as some libraries bundle their own // event emitter implementation with them. - if (typeof emitter.prependListener === 'function') { - return emitter.prependListener(event, fn); - } else { - // This is a hack to make sure that our error handler is attached before any - // userland ones. NEVER DO THIS. This is here only because this code needs - // to continue to work with older versions of Node.js that do not include - // the prependListener() method. The goal is to eventually remove this hack. - if (!emitter._events || !emitter._events[event]) emitter.on(event, fn);else if (isArray(emitter._events[event])) emitter._events[event].unshift(fn);else emitter._events[event] = [fn, emitter._events[event]]; - } + if (typeof emitter.prependListener === 'function') return emitter.prependListener(event, fn); + + // This is a hack to make sure that our error handler is attached before any + // userland ones. NEVER DO THIS. This is here only because this code needs + // to continue to work with older versions of Node.js that do not include + // the prependListener() method. The goal is to eventually remove this hack. + if (!emitter._events || !emitter._events[event]) emitter.on(event, fn);else if (isArray(emitter._events[event])) emitter._events[event].unshift(fn);else emitter._events[event] = [fn, emitter._events[event]]; } function ReadableState(options, stream) { @@ -79,20 +103,29 @@ function ReadableState(options, stream) { options = options || {}; + // Duplex streams are both readable and writable, but share + // the same options object. + // However, some cases require setting options to different + // values for the readable and the writable sides of the duplex stream. + // These options can be provided separately as readableXXX and writableXXX. + var isDuplex = stream instanceof Duplex; + // object stream flag. Used to make read(n) ignore n and to // make all the buffer merging and length checks go away this.objectMode = !!options.objectMode; - if (stream instanceof Duplex) this.objectMode = this.objectMode || !!options.readableObjectMode; + if (isDuplex) this.objectMode = this.objectMode || !!options.readableObjectMode; // the point at which it stops calling _read() to fill the buffer // Note: 0 is a valid value, means "don't call _read preemptively ever" var hwm = options.highWaterMark; + var readableHwm = options.readableHighWaterMark; var defaultHwm = this.objectMode ? 16 : 16 * 1024; - this.highWaterMark = hwm || hwm === 0 ? hwm : defaultHwm; + + if (hwm || hwm === 0) this.highWaterMark = hwm;else if (isDuplex && (readableHwm || readableHwm === 0)) this.highWaterMark = readableHwm;else this.highWaterMark = defaultHwm; // cast to ints. - this.highWaterMark = ~~this.highWaterMark; + this.highWaterMark = Math.floor(this.highWaterMark); // A linked list is used to store data chunks instead of an array because the // linked list can remove elements from the beginning faster than @@ -106,10 +139,10 @@ function ReadableState(options, stream) { this.endEmitted = false; this.reading = false; - // a flag to be able to tell if the onwrite cb is called immediately, - // or on a later tick. We set this to true at first, because any - // actions that shouldn't happen until "later" should generally also - // not happen before the first write call. + // a flag to be able to tell if the event 'readable'/'data' is emitted + // immediately, or on a later tick. We set this to true at first, because + // any actions that shouldn't happen until "later" should generally also + // not happen before the first read call. this.sync = true; // whenever we return null, then we set a flag to say @@ -119,15 +152,14 @@ function ReadableState(options, stream) { this.readableListening = false; this.resumeScheduled = false; + // has it been destroyed + this.destroyed = false; + // Crypto is kind of old and crusty. Historically, its default string // encoding is 'binary' so we have to make this configurable. // Everything else in the universe uses 'utf8', though. this.defaultEncoding = options.defaultEncoding || 'utf8'; - // when piping, we only care about 'readable' events that happen - // after read()ing all the bytes and not getting any pushback. - this.ranOut = false; - // the number of writers that are awaiting a drain event in .pipe()s this.awaitDrain = 0; @@ -153,87 +185,129 @@ function Readable(options) { // legacy this.readable = true; - if (options && typeof options.read === 'function') this._read = options.read; + if (options) { + if (typeof options.read === 'function') this._read = options.read; + + if (typeof options.destroy === 'function') this._destroy = options.destroy; + } Stream.call(this); } +Object.defineProperty(Readable.prototype, 'destroyed', { + get: function () { + if (this._readableState === undefined) { + return false; + } + return this._readableState.destroyed; + }, + set: function (value) { + // we ignore the value if the stream + // has not been initialized yet + if (!this._readableState) { + return; + } + + // backward compatibility, the user is explicitly + // managing destroyed + this._readableState.destroyed = value; + } +}); + +Readable.prototype.destroy = destroyImpl.destroy; +Readable.prototype._undestroy = destroyImpl.undestroy; +Readable.prototype._destroy = function (err, cb) { + this.push(null); + cb(err); +}; + // Manually shove something into the read() buffer. // This returns true if the highWaterMark has not been hit yet, // similar to how Writable.write() returns true if you should // write() some more. Readable.prototype.push = function (chunk, encoding) { var state = this._readableState; - - if (!state.objectMode && typeof chunk === 'string') { - encoding = encoding || state.defaultEncoding; - if (encoding !== state.encoding) { - chunk = bufferShim.from(chunk, encoding); - encoding = ''; + var skipChunkCheck; + + if (!state.objectMode) { + if (typeof chunk === 'string') { + encoding = encoding || state.defaultEncoding; + if (encoding !== state.encoding) { + chunk = Buffer.from(chunk, encoding); + encoding = ''; + } + skipChunkCheck = true; } + } else { + skipChunkCheck = true; } - return readableAddChunk(this, state, chunk, encoding, false); + return readableAddChunk(this, chunk, encoding, false, skipChunkCheck); }; // Unshift should *always* be something directly out of read() Readable.prototype.unshift = function (chunk) { - var state = this._readableState; - return readableAddChunk(this, state, chunk, '', true); + return readableAddChunk(this, chunk, null, true, false); }; -Readable.prototype.isPaused = function () { - return this._readableState.flowing === false; -}; - -function readableAddChunk(stream, state, chunk, encoding, addToFront) { - var er = chunkInvalid(state, chunk); - if (er) { - stream.emit('error', er); - } else if (chunk === null) { +function readableAddChunk(stream, chunk, encoding, addToFront, skipChunkCheck) { + var state = stream._readableState; + if (chunk === null) { state.reading = false; onEofChunk(stream, state); - } else if (state.objectMode || chunk && chunk.length > 0) { - if (state.ended && !addToFront) { - var e = new Error('stream.push() after EOF'); - stream.emit('error', e); - } else if (state.endEmitted && addToFront) { - var _e = new Error('stream.unshift() after end event'); - stream.emit('error', _e); - } else { - var skipAdd; - if (state.decoder && !addToFront && !encoding) { - chunk = state.decoder.write(chunk); - skipAdd = !state.objectMode && chunk.length === 0; + } else { + var er; + if (!skipChunkCheck) er = chunkInvalid(state, chunk); + if (er) { + stream.emit('error', er); + } else if (state.objectMode || chunk && chunk.length > 0) { + if (typeof chunk !== 'string' && !state.objectMode && Object.getPrototypeOf(chunk) !== Buffer.prototype) { + chunk = _uint8ArrayToBuffer(chunk); } - if (!addToFront) state.reading = false; - - // Don't add to the buffer if we've decoded to an empty string chunk and - // we're not in object mode - if (!skipAdd) { - // if we want the data now, just emit it. - if (state.flowing && state.length === 0 && !state.sync) { - stream.emit('data', chunk); - stream.read(0); + if (addToFront) { + if (state.endEmitted) stream.emit('error', new Error('stream.unshift() after end event'));else addChunk(stream, state, chunk, true); + } else if (state.ended) { + stream.emit('error', new Error('stream.push() after EOF')); + } else { + state.reading = false; + if (state.decoder && !encoding) { + chunk = state.decoder.write(chunk); + if (state.objectMode || chunk.length !== 0) addChunk(stream, state, chunk, false);else maybeReadMore(stream, state); } else { - // update the buffer info. - state.length += state.objectMode ? 1 : chunk.length; - if (addToFront) state.buffer.unshift(chunk);else state.buffer.push(chunk); - - if (state.needReadable) emitReadable(stream); + addChunk(stream, state, chunk, false); } } - - maybeReadMore(stream, state); + } else if (!addToFront) { + state.reading = false; } - } else if (!addToFront) { - state.reading = false; } return needMoreData(state); } +function addChunk(stream, state, chunk, addToFront) { + if (state.flowing && state.length === 0 && !state.sync) { + stream.emit('data', chunk); + stream.read(0); + } else { + // update the buffer info. + state.length += state.objectMode ? 1 : chunk.length; + if (addToFront) state.buffer.unshift(chunk);else state.buffer.push(chunk); + + if (state.needReadable) emitReadable(stream); + } + maybeReadMore(stream, state); +} + +function chunkInvalid(state, chunk) { + var er; + if (!_isUint8Array(chunk) && typeof chunk !== 'string' && chunk !== undefined && !state.objectMode) { + er = new TypeError('Invalid non-string/buffer chunk'); + } + return er; +} + // if it's past the high water mark, we can push in some more. // Also, if we have no data yet, we can stand some // more bytes. This is to work around cases where hwm=0, @@ -245,6 +319,10 @@ function needMoreData(state) { return !state.ended && (state.needReadable || state.length < state.highWaterMark || state.length === 0); } +Readable.prototype.isPaused = function () { + return this._readableState.flowing === false; +}; + // backwards compatibility. Readable.prototype.setEncoding = function (enc) { if (!StringDecoder) StringDecoder = require('string_decoder/').StringDecoder; @@ -393,14 +471,6 @@ Readable.prototype.read = function (n) { return ret; }; -function chunkInvalid(state, chunk) { - var er = null; - if (!Buffer.isBuffer(chunk) && typeof chunk !== 'string' && chunk !== null && chunk !== undefined && !state.objectMode) { - er = new TypeError('Invalid non-string/buffer chunk'); - } - return er; -} - function onEofChunk(stream, state) { if (state.ended) return; if (state.decoder) { @@ -425,7 +495,7 @@ function emitReadable(stream) { if (!state.emittedReadable) { debug('emitReadable', state.flowing); state.emittedReadable = true; - if (state.sync) processNextTick(emitReadable_, stream);else emitReadable_(stream); + if (state.sync) pna.nextTick(emitReadable_, stream);else emitReadable_(stream); } } @@ -444,7 +514,7 @@ function emitReadable_(stream) { function maybeReadMore(stream, state) { if (!state.readingMore) { state.readingMore = true; - processNextTick(maybeReadMore_, stream, state); + pna.nextTick(maybeReadMore_, stream, state); } } @@ -488,14 +558,17 @@ Readable.prototype.pipe = function (dest, pipeOpts) { var doEnd = (!pipeOpts || pipeOpts.end !== false) && dest !== process.stdout && dest !== process.stderr; - var endFn = doEnd ? onend : cleanup; - if (state.endEmitted) processNextTick(endFn);else src.once('end', endFn); + var endFn = doEnd ? onend : unpipe; + if (state.endEmitted) pna.nextTick(endFn);else src.once('end', endFn); dest.on('unpipe', onunpipe); - function onunpipe(readable) { + function onunpipe(readable, unpipeInfo) { debug('onunpipe'); if (readable === src) { - cleanup(); + if (unpipeInfo && unpipeInfo.hasUnpiped === false) { + unpipeInfo.hasUnpiped = true; + cleanup(); + } } } @@ -521,7 +594,7 @@ Readable.prototype.pipe = function (dest, pipeOpts) { dest.removeListener('error', onerror); dest.removeListener('unpipe', onunpipe); src.removeListener('end', onend); - src.removeListener('end', cleanup); + src.removeListener('end', unpipe); src.removeListener('data', ondata); cleanedUp = true; @@ -614,6 +687,7 @@ function pipeOnDrain(src) { Readable.prototype.unpipe = function (dest) { var state = this._readableState; + var unpipeInfo = { hasUnpiped: false }; // if we're not piping anywhere, then do nothing. if (state.pipesCount === 0) return this; @@ -629,7 +703,7 @@ Readable.prototype.unpipe = function (dest) { state.pipes = null; state.pipesCount = 0; state.flowing = false; - if (dest) dest.emit('unpipe', this); + if (dest) dest.emit('unpipe', this, unpipeInfo); return this; } @@ -644,7 +718,7 @@ Readable.prototype.unpipe = function (dest) { state.flowing = false; for (var i = 0; i < len; i++) { - dests[i].emit('unpipe', this); + dests[i].emit('unpipe', this, unpipeInfo); }return this; } @@ -656,7 +730,7 @@ Readable.prototype.unpipe = function (dest) { state.pipesCount -= 1; if (state.pipesCount === 1) state.pipes = state.pipes[0]; - dest.emit('unpipe', this); + dest.emit('unpipe', this, unpipeInfo); return this; }; @@ -675,9 +749,9 @@ Readable.prototype.on = function (ev, fn) { state.readableListening = state.needReadable = true; state.emittedReadable = false; if (!state.reading) { - processNextTick(nReadingNextTick, this); + pna.nextTick(nReadingNextTick, this); } else if (state.length) { - emitReadable(this, state); + emitReadable(this); } } } @@ -706,7 +780,7 @@ Readable.prototype.resume = function () { function resume(stream, state) { if (!state.resumeScheduled) { state.resumeScheduled = true; - processNextTick(resume_, stream, state); + pna.nextTick(resume_, stream, state); } } @@ -743,18 +817,19 @@ function flow(stream) { // This is *not* part of the readable stream interface. // It is an ugly unfortunate mess of history. Readable.prototype.wrap = function (stream) { + var _this = this; + var state = this._readableState; var paused = false; - var self = this; stream.on('end', function () { debug('wrapped end'); if (state.decoder && !state.ended) { var chunk = state.decoder.end(); - if (chunk && chunk.length) self.push(chunk); + if (chunk && chunk.length) _this.push(chunk); } - self.push(null); + _this.push(null); }); stream.on('data', function (chunk) { @@ -764,7 +839,7 @@ Readable.prototype.wrap = function (stream) { // don't skip over falsy values in objectMode if (state.objectMode && (chunk === null || chunk === undefined)) return;else if (!state.objectMode && (!chunk || !chunk.length)) return; - var ret = self.push(chunk); + var ret = _this.push(chunk); if (!ret) { paused = true; stream.pause(); @@ -784,14 +859,13 @@ Readable.prototype.wrap = function (stream) { } // proxy certain important events. - var events = ['error', 'close', 'destroy', 'pause', 'resume']; - forEach(events, function (ev) { - stream.on(ev, self.emit.bind(self, ev)); - }); + for (var n = 0; n < kProxyEvents.length; n++) { + stream.on(kProxyEvents[n], this.emit.bind(this, kProxyEvents[n])); + } // when we try to consume some more bytes, simply unpause the // underlying stream. - self._read = function (n) { + this._read = function (n) { debug('wrapped _read', n); if (paused) { paused = false; @@ -799,9 +873,19 @@ Readable.prototype.wrap = function (stream) { } }; - return self; + return this; }; +Object.defineProperty(Readable.prototype, 'readableHighWaterMark', { + // making it explicit this property is not enumerable + // because otherwise some prototype manipulation in + // userland will fail + enumerable: false, + get: function () { + return this._readableState.highWaterMark; + } +}); + // exposed for testing purposes only. Readable._fromList = fromList; @@ -879,7 +963,7 @@ function copyFromBufferString(n, list) { // This function is designed to be inlinable, so please take care when making // changes to the function body. function copyFromBuffer(n, list) { - var ret = bufferShim.allocUnsafe(n); + var ret = Buffer.allocUnsafe(n); var p = list.head; var c = 1; p.data.copy(ret); @@ -914,7 +998,7 @@ function endReadable(stream) { if (!state.endEmitted) { state.ended = true; - processNextTick(endReadableNT, state, stream); + pna.nextTick(endReadableNT, state, stream); } } @@ -927,12 +1011,6 @@ function endReadableNT(state, stream) { } } -function forEach(xs, f) { - for (var i = 0, l = xs.length; i < l; i++) { - f(xs[i], i); - } -} - function indexOf(xs, x) { for (var i = 0, l = xs.length; i < l; i++) { if (xs[i] === x) return i; diff --git a/ts-ticket-office-service/node_modules/readable-stream/lib/_stream_transform.js b/ts-ticket-office-service/node_modules/mysql/node_modules/readable-stream/lib/_stream_transform.js similarity index 68% rename from ts-ticket-office-service/node_modules/readable-stream/lib/_stream_transform.js rename to ts-ticket-office-service/node_modules/mysql/node_modules/readable-stream/lib/_stream_transform.js index cd2583207..fcfc105af 100644 --- a/ts-ticket-office-service/node_modules/readable-stream/lib/_stream_transform.js +++ b/ts-ticket-office-service/node_modules/mysql/node_modules/readable-stream/lib/_stream_transform.js @@ -1,3 +1,24 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + // a transform stream is a readable/writable stream where you do // something with the data. Sometimes it's called a "filter", // but that's not a great name for it, since that implies a thing where @@ -47,43 +68,34 @@ module.exports = Transform; var Duplex = require('./_stream_duplex'); /**/ -var util = require('core-util-is'); +var util = Object.create(require('core-util-is')); util.inherits = require('inherits'); /**/ util.inherits(Transform, Duplex); -function TransformState(stream) { - this.afterTransform = function (er, data) { - return afterTransform(stream, er, data); - }; - - this.needTransform = false; - this.transforming = false; - this.writecb = null; - this.writechunk = null; - this.writeencoding = null; -} - -function afterTransform(stream, er, data) { - var ts = stream._transformState; +function afterTransform(er, data) { + var ts = this._transformState; ts.transforming = false; var cb = ts.writecb; - if (!cb) return stream.emit('error', new Error('no writecb in Transform class')); + if (!cb) { + return this.emit('error', new Error('write callback called multiple times')); + } ts.writechunk = null; ts.writecb = null; - if (data !== null && data !== undefined) stream.push(data); + if (data != null) // single equals check for both `null` and `undefined` + this.push(data); cb(er); - var rs = stream._readableState; + var rs = this._readableState; rs.reading = false; if (rs.needReadable || rs.length < rs.highWaterMark) { - stream._read(rs.highWaterMark); + this._read(rs.highWaterMark); } } @@ -92,9 +104,14 @@ function Transform(options) { Duplex.call(this, options); - this._transformState = new TransformState(this); - - var stream = this; + this._transformState = { + afterTransform: afterTransform.bind(this), + needTransform: false, + transforming: false, + writecb: null, + writechunk: null, + writeencoding: null + }; // start out asking for a readable event once data is transformed. this._readableState.needReadable = true; @@ -111,11 +128,19 @@ function Transform(options) { } // When the writable side finishes, then flush out anything remaining. - this.once('prefinish', function () { - if (typeof this._flush === 'function') this._flush(function (er, data) { - done(stream, er, data); - });else done(stream); - }); + this.on('prefinish', prefinish); +} + +function prefinish() { + var _this = this; + + if (typeof this._flush === 'function') { + this._flush(function (er, data) { + done(_this, er, data); + }); + } else { + done(this, null, null); + } } Transform.prototype.push = function (chunk, encoding) { @@ -164,19 +189,26 @@ Transform.prototype._read = function (n) { } }; +Transform.prototype._destroy = function (err, cb) { + var _this2 = this; + + Duplex.prototype._destroy.call(this, err, function (err2) { + cb(err2); + _this2.emit('close'); + }); +}; + function done(stream, er, data) { if (er) return stream.emit('error', er); - if (data !== null && data !== undefined) stream.push(data); + if (data != null) // single equals check for both `null` and `undefined` + stream.push(data); // if there's nothing in the write buffer, then that means // that nothing more will ever be provided - var ws = stream._writableState; - var ts = stream._transformState; - - if (ws.length) throw new Error('Calling transform done when ws.length != 0'); + if (stream._writableState.length) throw new Error('Calling transform done when ws.length != 0'); - if (ts.transforming) throw new Error('Calling transform done when still transforming'); + if (stream._transformState.transforming) throw new Error('Calling transform done when still transforming'); return stream.push(null); } \ No newline at end of file diff --git a/ts-ticket-office-service/node_modules/readable-stream/lib/_stream_writable.js b/ts-ticket-office-service/node_modules/mysql/node_modules/readable-stream/lib/_stream_writable.js similarity index 70% rename from ts-ticket-office-service/node_modules/readable-stream/lib/_stream_writable.js rename to ts-ticket-office-service/node_modules/mysql/node_modules/readable-stream/lib/_stream_writable.js index 575beb3c4..b0b02200c 100644 --- a/ts-ticket-office-service/node_modules/readable-stream/lib/_stream_writable.js +++ b/ts-ticket-office-service/node_modules/mysql/node_modules/readable-stream/lib/_stream_writable.js @@ -1,17 +1,60 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + // A bit simpler than readable streams. // Implement an async ._write(chunk, encoding, cb), and it'll handle all // the drain event emission and buffering. 'use strict'; -module.exports = Writable; - /**/ -var processNextTick = require('process-nextick-args'); + +var pna = require('process-nextick-args'); /**/ +module.exports = Writable; + +/* */ +function WriteReq(chunk, encoding, cb) { + this.chunk = chunk; + this.encoding = encoding; + this.callback = cb; + this.next = null; +} + +// It seems a linked list but it is not +// there will be only 2 of these for each stream +function CorkedRequest(state) { + var _this = this; + + this.next = null; + this.entry = null; + this.finish = function () { + onCorkedFinish(_this, state); + }; +} +/* */ + /**/ -var asyncWrite = !process.browser && ['v0.10', 'v0.9.'].indexOf(process.version.slice(0, 5)) > -1 ? setImmediate : processNextTick; +var asyncWrite = !process.browser && ['v0.10', 'v0.9.'].indexOf(process.version.slice(0, 5)) > -1 ? setImmediate : pna.nextTick; /**/ /**/ @@ -21,7 +64,7 @@ var Duplex; Writable.WritableState = WritableState; /**/ -var util = require('core-util-is'); +var util = Object.create(require('core-util-is')); util.inherits = require('inherits'); /**/ @@ -32,52 +75,60 @@ var internalUtil = { /**/ /**/ -var Stream; -(function () { - try { - Stream = require('st' + 'ream'); - } catch (_) {} finally { - if (!Stream) Stream = require('events').EventEmitter; - } -})(); +var Stream = require('./internal/streams/stream'); /**/ -var Buffer = require('buffer').Buffer; /**/ -var bufferShim = require('buffer-shims'); + +var Buffer = require('safe-buffer').Buffer; +var OurUint8Array = global.Uint8Array || function () {}; +function _uint8ArrayToBuffer(chunk) { + return Buffer.from(chunk); +} +function _isUint8Array(obj) { + return Buffer.isBuffer(obj) || obj instanceof OurUint8Array; +} + /**/ +var destroyImpl = require('./internal/streams/destroy'); + util.inherits(Writable, Stream); function nop() {} -function WriteReq(chunk, encoding, cb) { - this.chunk = chunk; - this.encoding = encoding; - this.callback = cb; - this.next = null; -} - function WritableState(options, stream) { Duplex = Duplex || require('./_stream_duplex'); options = options || {}; + // Duplex streams are both readable and writable, but share + // the same options object. + // However, some cases require setting options to different + // values for the readable and the writable sides of the duplex stream. + // These options can be provided separately as readableXXX and writableXXX. + var isDuplex = stream instanceof Duplex; + // object stream flag to indicate whether or not this stream // contains buffers or objects. this.objectMode = !!options.objectMode; - if (stream instanceof Duplex) this.objectMode = this.objectMode || !!options.writableObjectMode; + if (isDuplex) this.objectMode = this.objectMode || !!options.writableObjectMode; // the point at which write() starts returning false // Note: 0 is a valid value, means that we always return false if // the entire buffer is not flushed immediately on write() var hwm = options.highWaterMark; + var writableHwm = options.writableHighWaterMark; var defaultHwm = this.objectMode ? 16 : 16 * 1024; - this.highWaterMark = hwm || hwm === 0 ? hwm : defaultHwm; + + if (hwm || hwm === 0) this.highWaterMark = hwm;else if (isDuplex && (writableHwm || writableHwm === 0)) this.highWaterMark = writableHwm;else this.highWaterMark = defaultHwm; // cast to ints. - this.highWaterMark = ~~this.highWaterMark; + this.highWaterMark = Math.floor(this.highWaterMark); + + // if _final has been called + this.finalCalled = false; // drain event flag. this.needDrain = false; @@ -88,6 +139,9 @@ function WritableState(options, stream) { // when 'finish' is emitted this.finished = false; + // has it been destroyed + this.destroyed = false; + // should we decode strings into buffers before passing to _write? // this is here so that some node-core streams can optimize string // handling at a lower level. @@ -169,7 +223,7 @@ WritableState.prototype.getBuffer = function getBuffer() { Object.defineProperty(WritableState.prototype, 'buffer', { get: internalUtil.deprecate(function () { return this.getBuffer(); - }, '_writableState.buffer is deprecated. Use _writableState.getBuffer ' + 'instead.') + }, '_writableState.buffer is deprecated. Use _writableState.getBuffer ' + 'instead.', 'DEP0003') }); } catch (_) {} })(); @@ -182,6 +236,7 @@ if (typeof Symbol === 'function' && Symbol.hasInstance && typeof Function.protot Object.defineProperty(Writable, Symbol.hasInstance, { value: function (object) { if (realHasInstance.call(this, object)) return true; + if (this !== Writable) return false; return object && object._writableState instanceof WritableState; } @@ -215,6 +270,10 @@ function Writable(options) { if (typeof options.write === 'function') this._write = options.write; if (typeof options.writev === 'function') this._writev = options.writev; + + if (typeof options.destroy === 'function') this._destroy = options.destroy; + + if (typeof options.final === 'function') this._final = options.final; } Stream.call(this); @@ -229,7 +288,7 @@ function writeAfterEnd(stream, cb) { var er = new Error('write after end'); // TODO: defer error events consistently everywhere, not just the cb stream.emit('error', er); - processNextTick(cb, er); + pna.nextTick(cb, er); } // Checks that a user-supplied chunk is valid, especially for the particular @@ -246,7 +305,7 @@ function validChunk(stream, state, chunk, cb) { } if (er) { stream.emit('error', er); - processNextTick(cb, er); + pna.nextTick(cb, er); valid = false; } return valid; @@ -255,7 +314,11 @@ function validChunk(stream, state, chunk, cb) { Writable.prototype.write = function (chunk, encoding, cb) { var state = this._writableState; var ret = false; - var isBuf = Buffer.isBuffer(chunk); + var isBuf = !state.objectMode && _isUint8Array(chunk); + + if (isBuf && !Buffer.isBuffer(chunk)) { + chunk = _uint8ArrayToBuffer(chunk); + } if (typeof encoding === 'function') { cb = encoding; @@ -300,18 +363,32 @@ Writable.prototype.setDefaultEncoding = function setDefaultEncoding(encoding) { function decodeChunk(state, chunk, encoding) { if (!state.objectMode && state.decodeStrings !== false && typeof chunk === 'string') { - chunk = bufferShim.from(chunk, encoding); + chunk = Buffer.from(chunk, encoding); } return chunk; } +Object.defineProperty(Writable.prototype, 'writableHighWaterMark', { + // making it explicit this property is not enumerable + // because otherwise some prototype manipulation in + // userland will fail + enumerable: false, + get: function () { + return this._writableState.highWaterMark; + } +}); + // if we're already writing something, then just put this // in the queue, and wait our turn. Otherwise, call _write // If we return false, then we need a drain event, so set that flag. function writeOrBuffer(stream, state, isBuf, chunk, encoding, cb) { if (!isBuf) { - chunk = decodeChunk(state, chunk, encoding); - if (Buffer.isBuffer(chunk)) encoding = 'buffer'; + var newChunk = decodeChunk(state, chunk, encoding); + if (chunk !== newChunk) { + isBuf = true; + encoding = 'buffer'; + chunk = newChunk; + } } var len = state.objectMode ? 1 : chunk.length; @@ -323,7 +400,13 @@ function writeOrBuffer(stream, state, isBuf, chunk, encoding, cb) { if (state.writing || state.corked) { var last = state.lastBufferedRequest; - state.lastBufferedRequest = new WriteReq(chunk, encoding, cb); + state.lastBufferedRequest = { + chunk: chunk, + encoding: encoding, + isBuf: isBuf, + callback: cb, + next: null + }; if (last) { last.next = state.lastBufferedRequest; } else { @@ -348,10 +431,26 @@ function doWrite(stream, state, writev, len, chunk, encoding, cb) { function onwriteError(stream, state, sync, er, cb) { --state.pendingcb; - if (sync) processNextTick(cb, er);else cb(er); - stream._writableState.errorEmitted = true; - stream.emit('error', er); + if (sync) { + // defer the callback if we are being called synchronously + // to avoid piling up things on the stack + pna.nextTick(cb, er); + // this can emit finish, and it will always happen + // after error + pna.nextTick(finishMaybe, stream, state); + stream._writableState.errorEmitted = true; + stream.emit('error', er); + } else { + // the caller expect this to happen before if + // it is async + cb(er); + stream._writableState.errorEmitted = true; + stream.emit('error', er); + // this can emit finish, but finish must + // always follow error + finishMaybe(stream, state); + } } function onwriteStateUpdate(state) { @@ -416,11 +515,14 @@ function clearBuffer(stream, state) { holder.entry = entry; var count = 0; + var allBuffers = true; while (entry) { buffer[count] = entry; + if (!entry.isBuf) allBuffers = false; entry = entry.next; count += 1; } + buffer.allBuffers = allBuffers; doWrite(stream, state, true, state.length, buffer, '', holder.finish); @@ -434,6 +536,7 @@ function clearBuffer(stream, state) { } else { state.corkedRequestsFree = new CorkedRequest(state); } + state.bufferedRequestCount = 0; } else { // Slow case, write chunks one-by-one while (entry) { @@ -444,6 +547,7 @@ function clearBuffer(stream, state) { doWrite(stream, state, false, len, chunk, encoding, cb); entry = entry.next; + state.bufferedRequestCount--; // if we didn't call the onwrite immediately, then // it means that we need to wait until it does. // also, that means that the chunk and cb are currently @@ -456,7 +560,6 @@ function clearBuffer(stream, state) { if (entry === null) state.lastBufferedRequest = null; } - state.bufferedRequestCount = 0; state.bufferedRequest = entry; state.bufferProcessing = false; } @@ -494,23 +597,37 @@ Writable.prototype.end = function (chunk, encoding, cb) { function needFinish(state) { return state.ending && state.length === 0 && state.bufferedRequest === null && !state.finished && !state.writing; } - -function prefinish(stream, state) { - if (!state.prefinished) { +function callFinal(stream, state) { + stream._final(function (err) { + state.pendingcb--; + if (err) { + stream.emit('error', err); + } state.prefinished = true; stream.emit('prefinish'); + finishMaybe(stream, state); + }); +} +function prefinish(stream, state) { + if (!state.prefinished && !state.finalCalled) { + if (typeof stream._final === 'function') { + state.pendingcb++; + state.finalCalled = true; + pna.nextTick(callFinal, stream, state); + } else { + state.prefinished = true; + stream.emit('prefinish'); + } } } function finishMaybe(stream, state) { var need = needFinish(state); if (need) { + prefinish(stream, state); if (state.pendingcb === 0) { - prefinish(stream, state); state.finished = true; stream.emit('finish'); - } else { - prefinish(stream, state); } } return need; @@ -520,32 +637,51 @@ function endWritable(stream, state, cb) { state.ending = true; finishMaybe(stream, state); if (cb) { - if (state.finished) processNextTick(cb);else stream.once('finish', cb); + if (state.finished) pna.nextTick(cb);else stream.once('finish', cb); } state.ended = true; stream.writable = false; } -// It seems a linked list but it is not -// there will be only 2 of these for each stream -function CorkedRequest(state) { - var _this = this; +function onCorkedFinish(corkReq, state, err) { + var entry = corkReq.entry; + corkReq.entry = null; + while (entry) { + var cb = entry.callback; + state.pendingcb--; + cb(err); + entry = entry.next; + } + if (state.corkedRequestsFree) { + state.corkedRequestsFree.next = corkReq; + } else { + state.corkedRequestsFree = corkReq; + } +} - this.next = null; - this.entry = null; - this.finish = function (err) { - var entry = _this.entry; - _this.entry = null; - while (entry) { - var cb = entry.callback; - state.pendingcb--; - cb(err); - entry = entry.next; +Object.defineProperty(Writable.prototype, 'destroyed', { + get: function () { + if (this._writableState === undefined) { + return false; } - if (state.corkedRequestsFree) { - state.corkedRequestsFree.next = _this; - } else { - state.corkedRequestsFree = _this; + return this._writableState.destroyed; + }, + set: function (value) { + // we ignore the value if the stream + // has not been initialized yet + if (!this._writableState) { + return; } - }; -} \ No newline at end of file + + // backward compatibility, the user is explicitly + // managing destroyed + this._writableState.destroyed = value; + } +}); + +Writable.prototype.destroy = destroyImpl.destroy; +Writable.prototype._undestroy = destroyImpl.undestroy; +Writable.prototype._destroy = function (err, cb) { + this.end(); + cb(err); +}; \ No newline at end of file diff --git a/ts-ticket-office-service/node_modules/mysql/node_modules/readable-stream/lib/internal/streams/BufferList.js b/ts-ticket-office-service/node_modules/mysql/node_modules/readable-stream/lib/internal/streams/BufferList.js new file mode 100644 index 000000000..aefc68bd9 --- /dev/null +++ b/ts-ticket-office-service/node_modules/mysql/node_modules/readable-stream/lib/internal/streams/BufferList.js @@ -0,0 +1,79 @@ +'use strict'; + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +var Buffer = require('safe-buffer').Buffer; +var util = require('util'); + +function copyBuffer(src, target, offset) { + src.copy(target, offset); +} + +module.exports = function () { + function BufferList() { + _classCallCheck(this, BufferList); + + this.head = null; + this.tail = null; + this.length = 0; + } + + BufferList.prototype.push = function push(v) { + var entry = { data: v, next: null }; + if (this.length > 0) this.tail.next = entry;else this.head = entry; + this.tail = entry; + ++this.length; + }; + + BufferList.prototype.unshift = function unshift(v) { + var entry = { data: v, next: this.head }; + if (this.length === 0) this.tail = entry; + this.head = entry; + ++this.length; + }; + + BufferList.prototype.shift = function shift() { + if (this.length === 0) return; + var ret = this.head.data; + if (this.length === 1) this.head = this.tail = null;else this.head = this.head.next; + --this.length; + return ret; + }; + + BufferList.prototype.clear = function clear() { + this.head = this.tail = null; + this.length = 0; + }; + + BufferList.prototype.join = function join(s) { + if (this.length === 0) return ''; + var p = this.head; + var ret = '' + p.data; + while (p = p.next) { + ret += s + p.data; + }return ret; + }; + + BufferList.prototype.concat = function concat(n) { + if (this.length === 0) return Buffer.alloc(0); + if (this.length === 1) return this.head.data; + var ret = Buffer.allocUnsafe(n >>> 0); + var p = this.head; + var i = 0; + while (p) { + copyBuffer(p.data, ret, i); + i += p.data.length; + p = p.next; + } + return ret; + }; + + return BufferList; +}(); + +if (util && util.inspect && util.inspect.custom) { + module.exports.prototype[util.inspect.custom] = function () { + var obj = util.inspect({ length: this.length }); + return this.constructor.name + ' ' + obj; + }; +} \ No newline at end of file diff --git a/ts-ticket-office-service/node_modules/mysql/node_modules/readable-stream/lib/internal/streams/destroy.js b/ts-ticket-office-service/node_modules/mysql/node_modules/readable-stream/lib/internal/streams/destroy.js new file mode 100644 index 000000000..5a0a0d88c --- /dev/null +++ b/ts-ticket-office-service/node_modules/mysql/node_modules/readable-stream/lib/internal/streams/destroy.js @@ -0,0 +1,74 @@ +'use strict'; + +/**/ + +var pna = require('process-nextick-args'); +/**/ + +// undocumented cb() API, needed for core, not for public API +function destroy(err, cb) { + var _this = this; + + var readableDestroyed = this._readableState && this._readableState.destroyed; + var writableDestroyed = this._writableState && this._writableState.destroyed; + + if (readableDestroyed || writableDestroyed) { + if (cb) { + cb(err); + } else if (err && (!this._writableState || !this._writableState.errorEmitted)) { + pna.nextTick(emitErrorNT, this, err); + } + return this; + } + + // we set destroyed to true before firing error callbacks in order + // to make it re-entrance safe in case destroy() is called within callbacks + + if (this._readableState) { + this._readableState.destroyed = true; + } + + // if this is a duplex stream mark the writable part as destroyed as well + if (this._writableState) { + this._writableState.destroyed = true; + } + + this._destroy(err || null, function (err) { + if (!cb && err) { + pna.nextTick(emitErrorNT, _this, err); + if (_this._writableState) { + _this._writableState.errorEmitted = true; + } + } else if (cb) { + cb(err); + } + }); + + return this; +} + +function undestroy() { + if (this._readableState) { + this._readableState.destroyed = false; + this._readableState.reading = false; + this._readableState.ended = false; + this._readableState.endEmitted = false; + } + + if (this._writableState) { + this._writableState.destroyed = false; + this._writableState.ended = false; + this._writableState.ending = false; + this._writableState.finished = false; + this._writableState.errorEmitted = false; + } +} + +function emitErrorNT(self, err) { + self.emit('error', err); +} + +module.exports = { + destroy: destroy, + undestroy: undestroy +}; \ No newline at end of file diff --git a/ts-ticket-office-service/node_modules/mysql/node_modules/readable-stream/lib/internal/streams/stream-browser.js b/ts-ticket-office-service/node_modules/mysql/node_modules/readable-stream/lib/internal/streams/stream-browser.js new file mode 100644 index 000000000..9332a3fda --- /dev/null +++ b/ts-ticket-office-service/node_modules/mysql/node_modules/readable-stream/lib/internal/streams/stream-browser.js @@ -0,0 +1 @@ +module.exports = require('events').EventEmitter; diff --git a/ts-ticket-office-service/node_modules/mysql/node_modules/readable-stream/lib/internal/streams/stream.js b/ts-ticket-office-service/node_modules/mysql/node_modules/readable-stream/lib/internal/streams/stream.js new file mode 100644 index 000000000..ce2ad5b6e --- /dev/null +++ b/ts-ticket-office-service/node_modules/mysql/node_modules/readable-stream/lib/internal/streams/stream.js @@ -0,0 +1 @@ +module.exports = require('stream'); diff --git a/ts-ticket-office-service/node_modules/mysql/node_modules/readable-stream/package.json b/ts-ticket-office-service/node_modules/mysql/node_modules/readable-stream/package.json new file mode 100644 index 000000000..2afa6fbd8 --- /dev/null +++ b/ts-ticket-office-service/node_modules/mysql/node_modules/readable-stream/package.json @@ -0,0 +1,52 @@ +{ + "name": "readable-stream", + "version": "2.3.7", + "description": "Streams3, a user-land copy of the stream library from Node.js", + "main": "readable.js", + "dependencies": { + "core-util-is": "~1.0.0", + "inherits": "~2.0.3", + "isarray": "~1.0.0", + "process-nextick-args": "~2.0.0", + "safe-buffer": "~5.1.1", + "string_decoder": "~1.1.1", + "util-deprecate": "~1.0.1" + }, + "devDependencies": { + "assert": "^1.4.0", + "babel-polyfill": "^6.9.1", + "buffer": "^4.9.0", + "lolex": "^2.3.2", + "nyc": "^6.4.0", + "tap": "^0.7.0", + "tape": "^4.8.0" + }, + "scripts": { + "test": "tap test/parallel/*.js test/ours/*.js && node test/verify-dependencies.js", + "ci": "tap test/parallel/*.js test/ours/*.js --tap | tee test.tap && node test/verify-dependencies.js", + "cover": "nyc npm test", + "report": "nyc report --reporter=lcov" + }, + "repository": { + "type": "git", + "url": "git://github.com/nodejs/readable-stream" + }, + "keywords": [ + "readable", + "stream", + "pipe" + ], + "browser": { + "util": false, + "./readable.js": "./readable-browser.js", + "./writable.js": "./writable-browser.js", + "./duplex.js": "./duplex-browser.js", + "./lib/internal/streams/stream.js": "./lib/internal/streams/stream-browser.js" + }, + "nyc": { + "include": [ + "lib/**.js" + ] + }, + "license": "MIT" +} diff --git a/ts-ticket-office-service/node_modules/readable-stream/passthrough.js b/ts-ticket-office-service/node_modules/mysql/node_modules/readable-stream/passthrough.js similarity index 100% rename from ts-ticket-office-service/node_modules/readable-stream/passthrough.js rename to ts-ticket-office-service/node_modules/mysql/node_modules/readable-stream/passthrough.js diff --git a/ts-ticket-office-service/node_modules/readable-stream/readable-browser.js b/ts-ticket-office-service/node_modules/mysql/node_modules/readable-stream/readable-browser.js similarity index 100% rename from ts-ticket-office-service/node_modules/readable-stream/readable-browser.js rename to ts-ticket-office-service/node_modules/mysql/node_modules/readable-stream/readable-browser.js diff --git a/ts-ticket-office-service/node_modules/readable-stream/readable.js b/ts-ticket-office-service/node_modules/mysql/node_modules/readable-stream/readable.js similarity index 100% rename from ts-ticket-office-service/node_modules/readable-stream/readable.js rename to ts-ticket-office-service/node_modules/mysql/node_modules/readable-stream/readable.js diff --git a/ts-ticket-office-service/node_modules/readable-stream/transform.js b/ts-ticket-office-service/node_modules/mysql/node_modules/readable-stream/transform.js similarity index 100% rename from ts-ticket-office-service/node_modules/readable-stream/transform.js rename to ts-ticket-office-service/node_modules/mysql/node_modules/readable-stream/transform.js diff --git a/ts-ticket-office-service/node_modules/readable-stream/writable-browser.js b/ts-ticket-office-service/node_modules/mysql/node_modules/readable-stream/writable-browser.js similarity index 100% rename from ts-ticket-office-service/node_modules/readable-stream/writable-browser.js rename to ts-ticket-office-service/node_modules/mysql/node_modules/readable-stream/writable-browser.js diff --git a/ts-ticket-office-service/node_modules/readable-stream/writable.js b/ts-ticket-office-service/node_modules/mysql/node_modules/readable-stream/writable.js similarity index 83% rename from ts-ticket-office-service/node_modules/readable-stream/writable.js rename to ts-ticket-office-service/node_modules/mysql/node_modules/readable-stream/writable.js index 634ddcbe1..3211a6f80 100644 --- a/ts-ticket-office-service/node_modules/readable-stream/writable.js +++ b/ts-ticket-office-service/node_modules/mysql/node_modules/readable-stream/writable.js @@ -3,6 +3,6 @@ var Writable = require("./lib/_stream_writable.js") if (process.env.READABLE_STREAM === 'disable') { module.exports = Stream && Stream.Writable || Writable +} else { + module.exports = Writable } - -module.exports = Writable diff --git a/ts-ticket-office-service/node_modules/mysql/node_modules/safe-buffer/LICENSE b/ts-ticket-office-service/node_modules/mysql/node_modules/safe-buffer/LICENSE new file mode 100644 index 000000000..0c068ceec --- /dev/null +++ b/ts-ticket-office-service/node_modules/mysql/node_modules/safe-buffer/LICENSE @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) Feross Aboukhadijeh + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. diff --git a/ts-ticket-office-service/node_modules/mysql/node_modules/safe-buffer/README.md b/ts-ticket-office-service/node_modules/mysql/node_modules/safe-buffer/README.md new file mode 100644 index 000000000..e9a81afd0 --- /dev/null +++ b/ts-ticket-office-service/node_modules/mysql/node_modules/safe-buffer/README.md @@ -0,0 +1,584 @@ +# safe-buffer [![travis][travis-image]][travis-url] [![npm][npm-image]][npm-url] [![downloads][downloads-image]][downloads-url] [![javascript style guide][standard-image]][standard-url] + +[travis-image]: https://img.shields.io/travis/feross/safe-buffer/master.svg +[travis-url]: https://travis-ci.org/feross/safe-buffer +[npm-image]: https://img.shields.io/npm/v/safe-buffer.svg +[npm-url]: https://npmjs.org/package/safe-buffer +[downloads-image]: https://img.shields.io/npm/dm/safe-buffer.svg +[downloads-url]: https://npmjs.org/package/safe-buffer +[standard-image]: https://img.shields.io/badge/code_style-standard-brightgreen.svg +[standard-url]: https://standardjs.com + +#### Safer Node.js Buffer API + +**Use the new Node.js Buffer APIs (`Buffer.from`, `Buffer.alloc`, +`Buffer.allocUnsafe`, `Buffer.allocUnsafeSlow`) in all versions of Node.js.** + +**Uses the built-in implementation when available.** + +## install + +``` +npm install safe-buffer +``` + +## usage + +The goal of this package is to provide a safe replacement for the node.js `Buffer`. + +It's a drop-in replacement for `Buffer`. You can use it by adding one `require` line to +the top of your node.js modules: + +```js +var Buffer = require('safe-buffer').Buffer + +// Existing buffer code will continue to work without issues: + +new Buffer('hey', 'utf8') +new Buffer([1, 2, 3], 'utf8') +new Buffer(obj) +new Buffer(16) // create an uninitialized buffer (potentially unsafe) + +// But you can use these new explicit APIs to make clear what you want: + +Buffer.from('hey', 'utf8') // convert from many types to a Buffer +Buffer.alloc(16) // create a zero-filled buffer (safe) +Buffer.allocUnsafe(16) // create an uninitialized buffer (potentially unsafe) +``` + +## api + +### Class Method: Buffer.from(array) + + +* `array` {Array} + +Allocates a new `Buffer` using an `array` of octets. + +```js +const buf = Buffer.from([0x62,0x75,0x66,0x66,0x65,0x72]); + // creates a new Buffer containing ASCII bytes + // ['b','u','f','f','e','r'] +``` + +A `TypeError` will be thrown if `array` is not an `Array`. + +### Class Method: Buffer.from(arrayBuffer[, byteOffset[, length]]) + + +* `arrayBuffer` {ArrayBuffer} The `.buffer` property of a `TypedArray` or + a `new ArrayBuffer()` +* `byteOffset` {Number} Default: `0` +* `length` {Number} Default: `arrayBuffer.length - byteOffset` + +When passed a reference to the `.buffer` property of a `TypedArray` instance, +the newly created `Buffer` will share the same allocated memory as the +TypedArray. + +```js +const arr = new Uint16Array(2); +arr[0] = 5000; +arr[1] = 4000; + +const buf = Buffer.from(arr.buffer); // shares the memory with arr; + +console.log(buf); + // Prints: + +// changing the TypedArray changes the Buffer also +arr[1] = 6000; + +console.log(buf); + // Prints: +``` + +The optional `byteOffset` and `length` arguments specify a memory range within +the `arrayBuffer` that will be shared by the `Buffer`. + +```js +const ab = new ArrayBuffer(10); +const buf = Buffer.from(ab, 0, 2); +console.log(buf.length); + // Prints: 2 +``` + +A `TypeError` will be thrown if `arrayBuffer` is not an `ArrayBuffer`. + +### Class Method: Buffer.from(buffer) + + +* `buffer` {Buffer} + +Copies the passed `buffer` data onto a new `Buffer` instance. + +```js +const buf1 = Buffer.from('buffer'); +const buf2 = Buffer.from(buf1); + +buf1[0] = 0x61; +console.log(buf1.toString()); + // 'auffer' +console.log(buf2.toString()); + // 'buffer' (copy is not changed) +``` + +A `TypeError` will be thrown if `buffer` is not a `Buffer`. + +### Class Method: Buffer.from(str[, encoding]) + + +* `str` {String} String to encode. +* `encoding` {String} Encoding to use, Default: `'utf8'` + +Creates a new `Buffer` containing the given JavaScript string `str`. If +provided, the `encoding` parameter identifies the character encoding. +If not provided, `encoding` defaults to `'utf8'`. + +```js +const buf1 = Buffer.from('this is a tést'); +console.log(buf1.toString()); + // prints: this is a tést +console.log(buf1.toString('ascii')); + // prints: this is a tC)st + +const buf2 = Buffer.from('7468697320697320612074c3a97374', 'hex'); +console.log(buf2.toString()); + // prints: this is a tést +``` + +A `TypeError` will be thrown if `str` is not a string. + +### Class Method: Buffer.alloc(size[, fill[, encoding]]) + + +* `size` {Number} +* `fill` {Value} Default: `undefined` +* `encoding` {String} Default: `utf8` + +Allocates a new `Buffer` of `size` bytes. If `fill` is `undefined`, the +`Buffer` will be *zero-filled*. + +```js +const buf = Buffer.alloc(5); +console.log(buf); + // +``` + +The `size` must be less than or equal to the value of +`require('buffer').kMaxLength` (on 64-bit architectures, `kMaxLength` is +`(2^31)-1`). Otherwise, a [`RangeError`][] is thrown. A zero-length Buffer will +be created if a `size` less than or equal to 0 is specified. + +If `fill` is specified, the allocated `Buffer` will be initialized by calling +`buf.fill(fill)`. See [`buf.fill()`][] for more information. + +```js +const buf = Buffer.alloc(5, 'a'); +console.log(buf); + // +``` + +If both `fill` and `encoding` are specified, the allocated `Buffer` will be +initialized by calling `buf.fill(fill, encoding)`. For example: + +```js +const buf = Buffer.alloc(11, 'aGVsbG8gd29ybGQ=', 'base64'); +console.log(buf); + // +``` + +Calling `Buffer.alloc(size)` can be significantly slower than the alternative +`Buffer.allocUnsafe(size)` but ensures that the newly created `Buffer` instance +contents will *never contain sensitive data*. + +A `TypeError` will be thrown if `size` is not a number. + +### Class Method: Buffer.allocUnsafe(size) + + +* `size` {Number} + +Allocates a new *non-zero-filled* `Buffer` of `size` bytes. The `size` must +be less than or equal to the value of `require('buffer').kMaxLength` (on 64-bit +architectures, `kMaxLength` is `(2^31)-1`). Otherwise, a [`RangeError`][] is +thrown. A zero-length Buffer will be created if a `size` less than or equal to +0 is specified. + +The underlying memory for `Buffer` instances created in this way is *not +initialized*. The contents of the newly created `Buffer` are unknown and +*may contain sensitive data*. Use [`buf.fill(0)`][] to initialize such +`Buffer` instances to zeroes. + +```js +const buf = Buffer.allocUnsafe(5); +console.log(buf); + // + // (octets will be different, every time) +buf.fill(0); +console.log(buf); + // +``` + +A `TypeError` will be thrown if `size` is not a number. + +Note that the `Buffer` module pre-allocates an internal `Buffer` instance of +size `Buffer.poolSize` that is used as a pool for the fast allocation of new +`Buffer` instances created using `Buffer.allocUnsafe(size)` (and the deprecated +`new Buffer(size)` constructor) only when `size` is less than or equal to +`Buffer.poolSize >> 1` (floor of `Buffer.poolSize` divided by two). The default +value of `Buffer.poolSize` is `8192` but can be modified. + +Use of this pre-allocated internal memory pool is a key difference between +calling `Buffer.alloc(size, fill)` vs. `Buffer.allocUnsafe(size).fill(fill)`. +Specifically, `Buffer.alloc(size, fill)` will *never* use the internal Buffer +pool, while `Buffer.allocUnsafe(size).fill(fill)` *will* use the internal +Buffer pool if `size` is less than or equal to half `Buffer.poolSize`. The +difference is subtle but can be important when an application requires the +additional performance that `Buffer.allocUnsafe(size)` provides. + +### Class Method: Buffer.allocUnsafeSlow(size) + + +* `size` {Number} + +Allocates a new *non-zero-filled* and non-pooled `Buffer` of `size` bytes. The +`size` must be less than or equal to the value of +`require('buffer').kMaxLength` (on 64-bit architectures, `kMaxLength` is +`(2^31)-1`). Otherwise, a [`RangeError`][] is thrown. A zero-length Buffer will +be created if a `size` less than or equal to 0 is specified. + +The underlying memory for `Buffer` instances created in this way is *not +initialized*. The contents of the newly created `Buffer` are unknown and +*may contain sensitive data*. Use [`buf.fill(0)`][] to initialize such +`Buffer` instances to zeroes. + +When using `Buffer.allocUnsafe()` to allocate new `Buffer` instances, +allocations under 4KB are, by default, sliced from a single pre-allocated +`Buffer`. This allows applications to avoid the garbage collection overhead of +creating many individually allocated Buffers. This approach improves both +performance and memory usage by eliminating the need to track and cleanup as +many `Persistent` objects. + +However, in the case where a developer may need to retain a small chunk of +memory from a pool for an indeterminate amount of time, it may be appropriate +to create an un-pooled Buffer instance using `Buffer.allocUnsafeSlow()` then +copy out the relevant bits. + +```js +// need to keep around a few small chunks of memory +const store = []; + +socket.on('readable', () => { + const data = socket.read(); + // allocate for retained data + const sb = Buffer.allocUnsafeSlow(10); + // copy the data into the new allocation + data.copy(sb, 0, 0, 10); + store.push(sb); +}); +``` + +Use of `Buffer.allocUnsafeSlow()` should be used only as a last resort *after* +a developer has observed undue memory retention in their applications. + +A `TypeError` will be thrown if `size` is not a number. + +### All the Rest + +The rest of the `Buffer` API is exactly the same as in node.js. +[See the docs](https://nodejs.org/api/buffer.html). + + +## Related links + +- [Node.js issue: Buffer(number) is unsafe](https://github.com/nodejs/node/issues/4660) +- [Node.js Enhancement Proposal: Buffer.from/Buffer.alloc/Buffer.zalloc/Buffer() soft-deprecate](https://github.com/nodejs/node-eps/pull/4) + +## Why is `Buffer` unsafe? + +Today, the node.js `Buffer` constructor is overloaded to handle many different argument +types like `String`, `Array`, `Object`, `TypedArrayView` (`Uint8Array`, etc.), +`ArrayBuffer`, and also `Number`. + +The API is optimized for convenience: you can throw any type at it, and it will try to do +what you want. + +Because the Buffer constructor is so powerful, you often see code like this: + +```js +// Convert UTF-8 strings to hex +function toHex (str) { + return new Buffer(str).toString('hex') +} +``` + +***But what happens if `toHex` is called with a `Number` argument?*** + +### Remote Memory Disclosure + +If an attacker can make your program call the `Buffer` constructor with a `Number` +argument, then they can make it allocate uninitialized memory from the node.js process. +This could potentially disclose TLS private keys, user data, or database passwords. + +When the `Buffer` constructor is passed a `Number` argument, it returns an +**UNINITIALIZED** block of memory of the specified `size`. When you create a `Buffer` like +this, you **MUST** overwrite the contents before returning it to the user. + +From the [node.js docs](https://nodejs.org/api/buffer.html#buffer_new_buffer_size): + +> `new Buffer(size)` +> +> - `size` Number +> +> The underlying memory for `Buffer` instances created in this way is not initialized. +> **The contents of a newly created `Buffer` are unknown and could contain sensitive +> data.** Use `buf.fill(0)` to initialize a Buffer to zeroes. + +(Emphasis our own.) + +Whenever the programmer intended to create an uninitialized `Buffer` you often see code +like this: + +```js +var buf = new Buffer(16) + +// Immediately overwrite the uninitialized buffer with data from another buffer +for (var i = 0; i < buf.length; i++) { + buf[i] = otherBuf[i] +} +``` + + +### Would this ever be a problem in real code? + +Yes. It's surprisingly common to forget to check the type of your variables in a +dynamically-typed language like JavaScript. + +Usually the consequences of assuming the wrong type is that your program crashes with an +uncaught exception. But the failure mode for forgetting to check the type of arguments to +the `Buffer` constructor is more catastrophic. + +Here's an example of a vulnerable service that takes a JSON payload and converts it to +hex: + +```js +// Take a JSON payload {str: "some string"} and convert it to hex +var server = http.createServer(function (req, res) { + var data = '' + req.setEncoding('utf8') + req.on('data', function (chunk) { + data += chunk + }) + req.on('end', function () { + var body = JSON.parse(data) + res.end(new Buffer(body.str).toString('hex')) + }) +}) + +server.listen(8080) +``` + +In this example, an http client just has to send: + +```json +{ + "str": 1000 +} +``` + +and it will get back 1,000 bytes of uninitialized memory from the server. + +This is a very serious bug. It's similar in severity to the +[the Heartbleed bug](http://heartbleed.com/) that allowed disclosure of OpenSSL process +memory by remote attackers. + + +### Which real-world packages were vulnerable? + +#### [`bittorrent-dht`](https://www.npmjs.com/package/bittorrent-dht) + +[Mathias Buus](https://github.com/mafintosh) and I +([Feross Aboukhadijeh](http://feross.org/)) found this issue in one of our own packages, +[`bittorrent-dht`](https://www.npmjs.com/package/bittorrent-dht). The bug would allow +anyone on the internet to send a series of messages to a user of `bittorrent-dht` and get +them to reveal 20 bytes at a time of uninitialized memory from the node.js process. + +Here's +[the commit](https://github.com/feross/bittorrent-dht/commit/6c7da04025d5633699800a99ec3fbadf70ad35b8) +that fixed it. We released a new fixed version, created a +[Node Security Project disclosure](https://nodesecurity.io/advisories/68), and deprecated all +vulnerable versions on npm so users will get a warning to upgrade to a newer version. + +#### [`ws`](https://www.npmjs.com/package/ws) + +That got us wondering if there were other vulnerable packages. Sure enough, within a short +period of time, we found the same issue in [`ws`](https://www.npmjs.com/package/ws), the +most popular WebSocket implementation in node.js. + +If certain APIs were called with `Number` parameters instead of `String` or `Buffer` as +expected, then uninitialized server memory would be disclosed to the remote peer. + +These were the vulnerable methods: + +```js +socket.send(number) +socket.ping(number) +socket.pong(number) +``` + +Here's a vulnerable socket server with some echo functionality: + +```js +server.on('connection', function (socket) { + socket.on('message', function (message) { + message = JSON.parse(message) + if (message.type === 'echo') { + socket.send(message.data) // send back the user's message + } + }) +}) +``` + +`socket.send(number)` called on the server, will disclose server memory. + +Here's [the release](https://github.com/websockets/ws/releases/tag/1.0.1) where the issue +was fixed, with a more detailed explanation. Props to +[Arnout Kazemier](https://github.com/3rd-Eden) for the quick fix. Here's the +[Node Security Project disclosure](https://nodesecurity.io/advisories/67). + + +### What's the solution? + +It's important that node.js offers a fast way to get memory otherwise performance-critical +applications would needlessly get a lot slower. + +But we need a better way to *signal our intent* as programmers. **When we want +uninitialized memory, we should request it explicitly.** + +Sensitive functionality should not be packed into a developer-friendly API that loosely +accepts many different types. This type of API encourages the lazy practice of passing +variables in without checking the type very carefully. + +#### A new API: `Buffer.allocUnsafe(number)` + +The functionality of creating buffers with uninitialized memory should be part of another +API. We propose `Buffer.allocUnsafe(number)`. This way, it's not part of an API that +frequently gets user input of all sorts of different types passed into it. + +```js +var buf = Buffer.allocUnsafe(16) // careful, uninitialized memory! + +// Immediately overwrite the uninitialized buffer with data from another buffer +for (var i = 0; i < buf.length; i++) { + buf[i] = otherBuf[i] +} +``` + + +### How do we fix node.js core? + +We sent [a PR to node.js core](https://github.com/nodejs/node/pull/4514) (merged as +`semver-major`) which defends against one case: + +```js +var str = 16 +new Buffer(str, 'utf8') +``` + +In this situation, it's implied that the programmer intended the first argument to be a +string, since they passed an encoding as a second argument. Today, node.js will allocate +uninitialized memory in the case of `new Buffer(number, encoding)`, which is probably not +what the programmer intended. + +But this is only a partial solution, since if the programmer does `new Buffer(variable)` +(without an `encoding` parameter) there's no way to know what they intended. If `variable` +is sometimes a number, then uninitialized memory will sometimes be returned. + +### What's the real long-term fix? + +We could deprecate and remove `new Buffer(number)` and use `Buffer.allocUnsafe(number)` when +we need uninitialized memory. But that would break 1000s of packages. + +~~We believe the best solution is to:~~ + +~~1. Change `new Buffer(number)` to return safe, zeroed-out memory~~ + +~~2. Create a new API for creating uninitialized Buffers. We propose: `Buffer.allocUnsafe(number)`~~ + +#### Update + +We now support adding three new APIs: + +- `Buffer.from(value)` - convert from any type to a buffer +- `Buffer.alloc(size)` - create a zero-filled buffer +- `Buffer.allocUnsafe(size)` - create an uninitialized buffer with given size + +This solves the core problem that affected `ws` and `bittorrent-dht` which is +`Buffer(variable)` getting tricked into taking a number argument. + +This way, existing code continues working and the impact on the npm ecosystem will be +minimal. Over time, npm maintainers can migrate performance-critical code to use +`Buffer.allocUnsafe(number)` instead of `new Buffer(number)`. + + +### Conclusion + +We think there's a serious design issue with the `Buffer` API as it exists today. It +promotes insecure software by putting high-risk functionality into a convenient API +with friendly "developer ergonomics". + +This wasn't merely a theoretical exercise because we found the issue in some of the +most popular npm packages. + +Fortunately, there's an easy fix that can be applied today. Use `safe-buffer` in place of +`buffer`. + +```js +var Buffer = require('safe-buffer').Buffer +``` + +Eventually, we hope that node.js core can switch to this new, safer behavior. We believe +the impact on the ecosystem would be minimal since it's not a breaking change. +Well-maintained, popular packages would be updated to use `Buffer.alloc` quickly, while +older, insecure packages would magically become safe from this attack vector. + + +## links + +- [Node.js PR: buffer: throw if both length and enc are passed](https://github.com/nodejs/node/pull/4514) +- [Node Security Project disclosure for `ws`](https://nodesecurity.io/advisories/67) +- [Node Security Project disclosure for`bittorrent-dht`](https://nodesecurity.io/advisories/68) + + +## credit + +The original issues in `bittorrent-dht` +([disclosure](https://nodesecurity.io/advisories/68)) and +`ws` ([disclosure](https://nodesecurity.io/advisories/67)) were discovered by +[Mathias Buus](https://github.com/mafintosh) and +[Feross Aboukhadijeh](http://feross.org/). + +Thanks to [Adam Baldwin](https://github.com/evilpacket) for helping disclose these issues +and for his work running the [Node Security Project](https://nodesecurity.io/). + +Thanks to [John Hiesey](https://github.com/jhiesey) for proofreading this README and +auditing the code. + + +## license + +MIT. Copyright (C) [Feross Aboukhadijeh](http://feross.org) diff --git a/ts-ticket-office-service/node_modules/mysql/node_modules/safe-buffer/index.d.ts b/ts-ticket-office-service/node_modules/mysql/node_modules/safe-buffer/index.d.ts new file mode 100644 index 000000000..e9fed809a --- /dev/null +++ b/ts-ticket-office-service/node_modules/mysql/node_modules/safe-buffer/index.d.ts @@ -0,0 +1,187 @@ +declare module "safe-buffer" { + export class Buffer { + length: number + write(string: string, offset?: number, length?: number, encoding?: string): number; + toString(encoding?: string, start?: number, end?: number): string; + toJSON(): { type: 'Buffer', data: any[] }; + equals(otherBuffer: Buffer): boolean; + compare(otherBuffer: Buffer, targetStart?: number, targetEnd?: number, sourceStart?: number, sourceEnd?: number): number; + copy(targetBuffer: Buffer, targetStart?: number, sourceStart?: number, sourceEnd?: number): number; + slice(start?: number, end?: number): Buffer; + writeUIntLE(value: number, offset: number, byteLength: number, noAssert?: boolean): number; + writeUIntBE(value: number, offset: number, byteLength: number, noAssert?: boolean): number; + writeIntLE(value: number, offset: number, byteLength: number, noAssert?: boolean): number; + writeIntBE(value: number, offset: number, byteLength: number, noAssert?: boolean): number; + readUIntLE(offset: number, byteLength: number, noAssert?: boolean): number; + readUIntBE(offset: number, byteLength: number, noAssert?: boolean): number; + readIntLE(offset: number, byteLength: number, noAssert?: boolean): number; + readIntBE(offset: number, byteLength: number, noAssert?: boolean): number; + readUInt8(offset: number, noAssert?: boolean): number; + readUInt16LE(offset: number, noAssert?: boolean): number; + readUInt16BE(offset: number, noAssert?: boolean): number; + readUInt32LE(offset: number, noAssert?: boolean): number; + readUInt32BE(offset: number, noAssert?: boolean): number; + readInt8(offset: number, noAssert?: boolean): number; + readInt16LE(offset: number, noAssert?: boolean): number; + readInt16BE(offset: number, noAssert?: boolean): number; + readInt32LE(offset: number, noAssert?: boolean): number; + readInt32BE(offset: number, noAssert?: boolean): number; + readFloatLE(offset: number, noAssert?: boolean): number; + readFloatBE(offset: number, noAssert?: boolean): number; + readDoubleLE(offset: number, noAssert?: boolean): number; + readDoubleBE(offset: number, noAssert?: boolean): number; + swap16(): Buffer; + swap32(): Buffer; + swap64(): Buffer; + writeUInt8(value: number, offset: number, noAssert?: boolean): number; + writeUInt16LE(value: number, offset: number, noAssert?: boolean): number; + writeUInt16BE(value: number, offset: number, noAssert?: boolean): number; + writeUInt32LE(value: number, offset: number, noAssert?: boolean): number; + writeUInt32BE(value: number, offset: number, noAssert?: boolean): number; + writeInt8(value: number, offset: number, noAssert?: boolean): number; + writeInt16LE(value: number, offset: number, noAssert?: boolean): number; + writeInt16BE(value: number, offset: number, noAssert?: boolean): number; + writeInt32LE(value: number, offset: number, noAssert?: boolean): number; + writeInt32BE(value: number, offset: number, noAssert?: boolean): number; + writeFloatLE(value: number, offset: number, noAssert?: boolean): number; + writeFloatBE(value: number, offset: number, noAssert?: boolean): number; + writeDoubleLE(value: number, offset: number, noAssert?: boolean): number; + writeDoubleBE(value: number, offset: number, noAssert?: boolean): number; + fill(value: any, offset?: number, end?: number): this; + indexOf(value: string | number | Buffer, byteOffset?: number, encoding?: string): number; + lastIndexOf(value: string | number | Buffer, byteOffset?: number, encoding?: string): number; + includes(value: string | number | Buffer, byteOffset?: number, encoding?: string): boolean; + + /** + * Allocates a new buffer containing the given {str}. + * + * @param str String to store in buffer. + * @param encoding encoding to use, optional. Default is 'utf8' + */ + constructor (str: string, encoding?: string); + /** + * Allocates a new buffer of {size} octets. + * + * @param size count of octets to allocate. + */ + constructor (size: number); + /** + * Allocates a new buffer containing the given {array} of octets. + * + * @param array The octets to store. + */ + constructor (array: Uint8Array); + /** + * Produces a Buffer backed by the same allocated memory as + * the given {ArrayBuffer}. + * + * + * @param arrayBuffer The ArrayBuffer with which to share memory. + */ + constructor (arrayBuffer: ArrayBuffer); + /** + * Allocates a new buffer containing the given {array} of octets. + * + * @param array The octets to store. + */ + constructor (array: any[]); + /** + * Copies the passed {buffer} data onto a new {Buffer} instance. + * + * @param buffer The buffer to copy. + */ + constructor (buffer: Buffer); + prototype: Buffer; + /** + * Allocates a new Buffer using an {array} of octets. + * + * @param array + */ + static from(array: any[]): Buffer; + /** + * When passed a reference to the .buffer property of a TypedArray instance, + * the newly created Buffer will share the same allocated memory as the TypedArray. + * The optional {byteOffset} and {length} arguments specify a memory range + * within the {arrayBuffer} that will be shared by the Buffer. + * + * @param arrayBuffer The .buffer property of a TypedArray or a new ArrayBuffer() + * @param byteOffset + * @param length + */ + static from(arrayBuffer: ArrayBuffer, byteOffset?: number, length?: number): Buffer; + /** + * Copies the passed {buffer} data onto a new Buffer instance. + * + * @param buffer + */ + static from(buffer: Buffer): Buffer; + /** + * Creates a new Buffer containing the given JavaScript string {str}. + * If provided, the {encoding} parameter identifies the character encoding. + * If not provided, {encoding} defaults to 'utf8'. + * + * @param str + */ + static from(str: string, encoding?: string): Buffer; + /** + * Returns true if {obj} is a Buffer + * + * @param obj object to test. + */ + static isBuffer(obj: any): obj is Buffer; + /** + * Returns true if {encoding} is a valid encoding argument. + * Valid string encodings in Node 0.12: 'ascii'|'utf8'|'utf16le'|'ucs2'(alias of 'utf16le')|'base64'|'binary'(deprecated)|'hex' + * + * @param encoding string to test. + */ + static isEncoding(encoding: string): boolean; + /** + * Gives the actual byte length of a string. encoding defaults to 'utf8'. + * This is not the same as String.prototype.length since that returns the number of characters in a string. + * + * @param string string to test. + * @param encoding encoding used to evaluate (defaults to 'utf8') + */ + static byteLength(string: string, encoding?: string): number; + /** + * Returns a buffer which is the result of concatenating all the buffers in the list together. + * + * If the list has no items, or if the totalLength is 0, then it returns a zero-length buffer. + * If the list has exactly one item, then the first item of the list is returned. + * If the list has more than one item, then a new Buffer is created. + * + * @param list An array of Buffer objects to concatenate + * @param totalLength Total length of the buffers when concatenated. + * If totalLength is not provided, it is read from the buffers in the list. However, this adds an additional loop to the function, so it is faster to provide the length explicitly. + */ + static concat(list: Buffer[], totalLength?: number): Buffer; + /** + * The same as buf1.compare(buf2). + */ + static compare(buf1: Buffer, buf2: Buffer): number; + /** + * Allocates a new buffer of {size} octets. + * + * @param size count of octets to allocate. + * @param fill if specified, buffer will be initialized by calling buf.fill(fill). + * If parameter is omitted, buffer will be filled with zeros. + * @param encoding encoding used for call to buf.fill while initalizing + */ + static alloc(size: number, fill?: string | Buffer | number, encoding?: string): Buffer; + /** + * Allocates a new buffer of {size} octets, leaving memory not initialized, so the contents + * of the newly created Buffer are unknown and may contain sensitive data. + * + * @param size count of octets to allocate + */ + static allocUnsafe(size: number): Buffer; + /** + * Allocates a new non-pooled buffer of {size} octets, leaving memory not initialized, so the contents + * of the newly created Buffer are unknown and may contain sensitive data. + * + * @param size count of octets to allocate + */ + static allocUnsafeSlow(size: number): Buffer; + } +} \ No newline at end of file diff --git a/ts-ticket-office-service/node_modules/mysql/node_modules/safe-buffer/index.js b/ts-ticket-office-service/node_modules/mysql/node_modules/safe-buffer/index.js new file mode 100644 index 000000000..22438dabb --- /dev/null +++ b/ts-ticket-office-service/node_modules/mysql/node_modules/safe-buffer/index.js @@ -0,0 +1,62 @@ +/* eslint-disable node/no-deprecated-api */ +var buffer = require('buffer') +var Buffer = buffer.Buffer + +// alternative to using Object.keys for old browsers +function copyProps (src, dst) { + for (var key in src) { + dst[key] = src[key] + } +} +if (Buffer.from && Buffer.alloc && Buffer.allocUnsafe && Buffer.allocUnsafeSlow) { + module.exports = buffer +} else { + // Copy properties from require('buffer') + copyProps(buffer, exports) + exports.Buffer = SafeBuffer +} + +function SafeBuffer (arg, encodingOrOffset, length) { + return Buffer(arg, encodingOrOffset, length) +} + +// Copy static methods from Buffer +copyProps(Buffer, SafeBuffer) + +SafeBuffer.from = function (arg, encodingOrOffset, length) { + if (typeof arg === 'number') { + throw new TypeError('Argument must not be a number') + } + return Buffer(arg, encodingOrOffset, length) +} + +SafeBuffer.alloc = function (size, fill, encoding) { + if (typeof size !== 'number') { + throw new TypeError('Argument must be a number') + } + var buf = Buffer(size) + if (fill !== undefined) { + if (typeof encoding === 'string') { + buf.fill(fill, encoding) + } else { + buf.fill(fill) + } + } else { + buf.fill(0) + } + return buf +} + +SafeBuffer.allocUnsafe = function (size) { + if (typeof size !== 'number') { + throw new TypeError('Argument must be a number') + } + return Buffer(size) +} + +SafeBuffer.allocUnsafeSlow = function (size) { + if (typeof size !== 'number') { + throw new TypeError('Argument must be a number') + } + return buffer.SlowBuffer(size) +} diff --git a/ts-ticket-office-service/node_modules/mysql/node_modules/safe-buffer/package.json b/ts-ticket-office-service/node_modules/mysql/node_modules/safe-buffer/package.json new file mode 100644 index 000000000..623fbc3f6 --- /dev/null +++ b/ts-ticket-office-service/node_modules/mysql/node_modules/safe-buffer/package.json @@ -0,0 +1,37 @@ +{ + "name": "safe-buffer", + "description": "Safer Node.js Buffer API", + "version": "5.1.2", + "author": { + "name": "Feross Aboukhadijeh", + "email": "feross@feross.org", + "url": "http://feross.org" + }, + "bugs": { + "url": "https://github.com/feross/safe-buffer/issues" + }, + "devDependencies": { + "standard": "*", + "tape": "^4.0.0" + }, + "homepage": "https://github.com/feross/safe-buffer", + "keywords": [ + "buffer", + "buffer allocate", + "node security", + "safe", + "safe-buffer", + "security", + "uninitialized" + ], + "license": "MIT", + "main": "index.js", + "types": "index.d.ts", + "repository": { + "type": "git", + "url": "git://github.com/feross/safe-buffer.git" + }, + "scripts": { + "test": "standard && tape test/*.js" + } +} diff --git a/ts-ticket-office-service/node_modules/string_decoder/LICENSE b/ts-ticket-office-service/node_modules/mysql/node_modules/string_decoder/LICENSE similarity index 100% rename from ts-ticket-office-service/node_modules/string_decoder/LICENSE rename to ts-ticket-office-service/node_modules/mysql/node_modules/string_decoder/LICENSE diff --git a/ts-ticket-office-service/node_modules/mysql/node_modules/string_decoder/README.md b/ts-ticket-office-service/node_modules/mysql/node_modules/string_decoder/README.md new file mode 100644 index 000000000..5fd58315e --- /dev/null +++ b/ts-ticket-office-service/node_modules/mysql/node_modules/string_decoder/README.md @@ -0,0 +1,47 @@ +# string_decoder + +***Node-core v8.9.4 string_decoder for userland*** + + +[![NPM](https://nodei.co/npm/string_decoder.png?downloads=true&downloadRank=true)](https://nodei.co/npm/string_decoder/) +[![NPM](https://nodei.co/npm-dl/string_decoder.png?&months=6&height=3)](https://nodei.co/npm/string_decoder/) + + +```bash +npm install --save string_decoder +``` + +***Node-core string_decoder for userland*** + +This package is a mirror of the string_decoder implementation in Node-core. + +Full documentation may be found on the [Node.js website](https://nodejs.org/dist/v8.9.4/docs/api/). + +As of version 1.0.0 **string_decoder** uses semantic versioning. + +## Previous versions + +Previous version numbers match the versions found in Node core, e.g. 0.10.24 matches Node 0.10.24, likewise 0.11.10 matches Node 0.11.10. + +## Update + +The *build/* directory contains a build script that will scrape the source from the [nodejs/node](https://github.com/nodejs/node) repo given a specific Node version. + +## Streams Working Group + +`string_decoder` is maintained by the Streams Working Group, which +oversees the development and maintenance of the Streams API within +Node.js. The responsibilities of the Streams Working Group include: + +* Addressing stream issues on the Node.js issue tracker. +* Authoring and editing stream documentation within the Node.js project. +* Reviewing changes to stream subclasses within the Node.js project. +* Redirecting changes to streams from the Node.js project to this + project. +* Assisting in the implementation of stream providers within Node.js. +* Recommending versions of `readable-stream` to be included in Node.js. +* Messaging about the future of streams to give the community advance + notice of changes. + +See [readable-stream](https://github.com/nodejs/readable-stream) for +more details. diff --git a/ts-ticket-office-service/node_modules/string_decoder/lib/string_decoder.js b/ts-ticket-office-service/node_modules/mysql/node_modules/string_decoder/lib/string_decoder.js similarity index 82% rename from ts-ticket-office-service/node_modules/string_decoder/lib/string_decoder.js rename to ts-ticket-office-service/node_modules/mysql/node_modules/string_decoder/lib/string_decoder.js index 26fb94c34..2e89e63f7 100644 --- a/ts-ticket-office-service/node_modules/string_decoder/lib/string_decoder.js +++ b/ts-ticket-office-service/node_modules/mysql/node_modules/string_decoder/lib/string_decoder.js @@ -1,6 +1,30 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + 'use strict'; +/**/ + var Buffer = require('safe-buffer').Buffer; +/**/ var isEncoding = Buffer.isEncoding || function (encoding) { encoding = '' + encoding; @@ -112,10 +136,10 @@ StringDecoder.prototype.fillLast = function (buf) { }; // Checks the type of a UTF-8 byte, whether it's ASCII, a leading byte, or a -// continuation byte. +// continuation byte. If an invalid byte is detected, -2 is returned. function utf8CheckByte(byte) { if (byte <= 0x7F) return 0;else if (byte >> 5 === 0x06) return 2;else if (byte >> 4 === 0x0E) return 3;else if (byte >> 3 === 0x1E) return 4; - return -1; + return byte >> 6 === 0x02 ? -1 : -2; } // Checks at most 3 bytes at the end of a Buffer in order to detect an @@ -129,13 +153,13 @@ function utf8CheckIncomplete(self, buf, i) { if (nb > 0) self.lastNeed = nb - 1; return nb; } - if (--j < i) return 0; + if (--j < i || nb === -2) return 0; nb = utf8CheckByte(buf[j]); if (nb >= 0) { if (nb > 0) self.lastNeed = nb - 2; return nb; } - if (--j < i) return 0; + if (--j < i || nb === -2) return 0; nb = utf8CheckByte(buf[j]); if (nb >= 0) { if (nb > 0) { @@ -149,7 +173,7 @@ function utf8CheckIncomplete(self, buf, i) { // Validates as many continuation bytes for a multi-byte UTF-8 character as // needed or are available. If we see a non-continuation byte where we expect // one, we "replace" the validated continuation bytes we've seen so far with -// UTF-8 replacement characters ('\ufffd'), to match v8's UTF-8 decoding +// a single UTF-8 replacement character ('\ufffd'), to match v8's UTF-8 decoding // behavior. The continuation byte check is included three times in the case // where all of the continuation bytes for a character exist in the same buffer. // It is also done this way as a slight performance increase instead of using a @@ -157,17 +181,17 @@ function utf8CheckIncomplete(self, buf, i) { function utf8CheckExtraBytes(self, buf, p) { if ((buf[0] & 0xC0) !== 0x80) { self.lastNeed = 0; - return '\ufffd'.repeat(p); + return '\ufffd'; } if (self.lastNeed > 1 && buf.length > 1) { if ((buf[1] & 0xC0) !== 0x80) { self.lastNeed = 1; - return '\ufffd'.repeat(p + 1); + return '\ufffd'; } if (self.lastNeed > 2 && buf.length > 2) { if ((buf[2] & 0xC0) !== 0x80) { self.lastNeed = 2; - return '\ufffd'.repeat(p + 2); + return '\ufffd'; } } } @@ -198,11 +222,11 @@ function utf8Text(buf, i) { return buf.toString('utf8', i, end); } -// For UTF-8, a replacement character for each buffered byte of a (partial) -// character needs to be added to the output. +// For UTF-8, a replacement character is added when ending on a partial +// character. function utf8End(buf) { var r = buf && buf.length ? this.write(buf) : ''; - if (this.lastNeed) return r + '\ufffd'.repeat(this.lastTotal - this.lastNeed); + if (this.lastNeed) return r + '\ufffd'; return r; } diff --git a/ts-ticket-office-service/node_modules/mysql/node_modules/string_decoder/package.json b/ts-ticket-office-service/node_modules/mysql/node_modules/string_decoder/package.json new file mode 100644 index 000000000..518c3eb9f --- /dev/null +++ b/ts-ticket-office-service/node_modules/mysql/node_modules/string_decoder/package.json @@ -0,0 +1,31 @@ +{ + "name": "string_decoder", + "version": "1.1.1", + "description": "The string_decoder module from Node core", + "main": "lib/string_decoder.js", + "dependencies": { + "safe-buffer": "~5.1.0" + }, + "devDependencies": { + "babel-polyfill": "^6.23.0", + "core-util-is": "^1.0.2", + "inherits": "^2.0.3", + "tap": "~0.4.8" + }, + "scripts": { + "test": "tap test/parallel/*.js && node test/verify-dependencies", + "ci": "tap test/parallel/*.js test/ours/*.js --tap | tee test.tap && node test/verify-dependencies.js" + }, + "repository": { + "type": "git", + "url": "git://github.com/nodejs/string_decoder.git" + }, + "homepage": "https://github.com/nodejs/string_decoder", + "keywords": [ + "string", + "decoder", + "browser", + "browserify" + ], + "license": "MIT" +} diff --git a/ts-ticket-office-service/node_modules/mysql/package.json b/ts-ticket-office-service/node_modules/mysql/package.json new file mode 100644 index 000000000..7ed9d55bb --- /dev/null +++ b/ts-ticket-office-service/node_modules/mysql/package.json @@ -0,0 +1,46 @@ +{ + "name": "mysql", + "description": "A node.js driver for mysql. It is written in JavaScript, does not require compiling, and is 100% MIT licensed.", + "version": "2.18.1", + "license": "MIT", + "author": "Felix Geisendörfer (http://debuggable.com/)", + "contributors": [ + "Andrey Sidorov ", + "Bradley Grainger ", + "Douglas Christopher Wilson ", + "Diogo Resende ", + "Nathan Woltman " + ], + "repository": "mysqljs/mysql", + "dependencies": { + "bignumber.js": "9.0.0", + "readable-stream": "2.3.7", + "safe-buffer": "5.1.2", + "sqlstring": "2.3.1" + }, + "devDependencies": { + "after": "0.8.2", + "eslint": "5.16.0", + "seedrandom": "3.0.5", + "timezone-mock": "0.0.7", + "urun": "0.0.8", + "utest": "0.0.8" + }, + "files": [ + "lib/", + "Changes.md", + "License", + "Readme.md", + "index.js" + ], + "engines": { + "node": ">= 0.6" + }, + "scripts": { + "lint": "eslint . && node tool/lint-readme.js", + "test": "node test/run.js", + "test-ci": "node tool/install-nyc.js --nyc-optional --reporter=text -- npm test", + "test-cov": "node tool/install-nyc.js --reporter=html --reporter=text -- npm test", + "version": "node tool/version-changes.js && git add Changes.md" + } +} diff --git a/ts-ticket-office-service/node_modules/process-nextick-args/.travis.yml b/ts-ticket-office-service/node_modules/process-nextick-args/.travis.yml deleted file mode 100644 index 36201b100..000000000 --- a/ts-ticket-office-service/node_modules/process-nextick-args/.travis.yml +++ /dev/null @@ -1,12 +0,0 @@ -language: node_js -node_js: - - "0.8" - - "0.10" - - "0.11" - - "0.12" - - "1.7.1" - - 1 - - 2 - - 3 - - 4 - - 5 diff --git a/ts-ticket-office-service/node_modules/process-nextick-args/package.json b/ts-ticket-office-service/node_modules/process-nextick-args/package.json deleted file mode 100644 index bbeb9dce3..000000000 --- a/ts-ticket-office-service/node_modules/process-nextick-args/package.json +++ /dev/null @@ -1,83 +0,0 @@ -{ - "_args": [ - [ - { - "raw": "process-nextick-args@~1.0.6", - "scope": null, - "escapedName": "process-nextick-args", - "name": "process-nextick-args", - "rawSpec": "~1.0.6", - "spec": ">=1.0.6 <1.1.0", - "type": "range" - }, - "F:\\gitwork\\workspace_microservices\\ts-ticket-office-service\\node_modules\\readable-stream" - ] - ], - "_from": "process-nextick-args@>=1.0.6 <1.1.0", - "_id": "process-nextick-args@1.0.7", - "_inCache": true, - "_location": "/process-nextick-args", - "_nodeVersion": "5.11.0", - "_npmOperationalInternal": { - "host": "packages-12-west.internal.npmjs.com", - "tmp": "tmp/process-nextick-args-1.0.7.tgz_1462394251778_0.36989671061746776" - }, - "_npmUser": { - "name": "cwmma", - "email": "calvin.metcalf@gmail.com" - }, - "_npmVersion": "3.8.6", - "_phantomChildren": {}, - "_requested": { - "raw": "process-nextick-args@~1.0.6", - "scope": null, - "escapedName": "process-nextick-args", - "name": "process-nextick-args", - "rawSpec": "~1.0.6", - "spec": ">=1.0.6 <1.1.0", - "type": "range" - }, - "_requiredBy": [ - "/readable-stream" - ], - "_resolved": "https://registry.npmjs.org/process-nextick-args/-/process-nextick-args-1.0.7.tgz", - "_shasum": "150e20b756590ad3f91093f25a4f2ad8bff30ba3", - "_shrinkwrap": null, - "_spec": "process-nextick-args@~1.0.6", - "_where": "F:\\gitwork\\workspace_microservices\\ts-ticket-office-service\\node_modules\\readable-stream", - "author": "", - "bugs": { - "url": "https://github.com/calvinmetcalf/process-nextick-args/issues" - }, - "dependencies": {}, - "description": "process.nextTick but always with args", - "devDependencies": { - "tap": "~0.2.6" - }, - "directories": {}, - "dist": { - "shasum": "150e20b756590ad3f91093f25a4f2ad8bff30ba3", - "tarball": "https://registry.npmjs.org/process-nextick-args/-/process-nextick-args-1.0.7.tgz" - }, - "gitHead": "5c00899ab01dd32f93ad4b5743da33da91404f39", - "homepage": "https://github.com/calvinmetcalf/process-nextick-args", - "license": "MIT", - "main": "index.js", - "maintainers": [ - { - "name": "cwmma", - "email": "calvin.metcalf@gmail.com" - } - ], - "name": "process-nextick-args", - "optionalDependencies": {}, - "readme": "ERROR: No README data found!", - "repository": { - "type": "git", - "url": "git+https://github.com/calvinmetcalf/process-nextick-args.git" - }, - "scripts": { - "test": "node test.js" - }, - "version": "1.0.7" -} diff --git a/ts-ticket-office-service/node_modules/process-nextick-args/test.js b/ts-ticket-office-service/node_modules/process-nextick-args/test.js deleted file mode 100644 index ef1572158..000000000 --- a/ts-ticket-office-service/node_modules/process-nextick-args/test.js +++ /dev/null @@ -1,24 +0,0 @@ -var test = require("tap").test; -var nextTick = require('./'); - -test('should work', function (t) { - t.plan(5); - nextTick(function (a) { - t.ok(a); - nextTick(function (thing) { - t.equals(thing, 7); - }, 7); - }, true); - nextTick(function (a, b, c) { - t.equals(a, 'step'); - t.equals(b, 3); - t.equals(c, 'profit'); - }, 'step', 3, 'profit'); -}); - -test('correct number of arguments', function (t) { - t.plan(1); - nextTick(function () { - t.equals(2, arguments.length, 'correct number'); - }, 1, 2); -}); diff --git a/ts-ticket-office-service/node_modules/punycode/LICENSE-MIT.txt b/ts-ticket-office-service/node_modules/punycode/LICENSE-MIT.txt new file mode 100644 index 000000000..a41e0a7ef --- /dev/null +++ b/ts-ticket-office-service/node_modules/punycode/LICENSE-MIT.txt @@ -0,0 +1,20 @@ +Copyright Mathias Bynens + +Permission is hereby granted, free of charge, to any person obtaining +a copy of this software and associated documentation files (the +"Software"), to deal in the Software without restriction, including +without limitation the rights to use, copy, modify, merge, publish, +distribute, sublicense, and/or sell copies of the Software, and to +permit persons to whom the Software is furnished to do so, subject to +the following conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE +LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION +OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION +WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/ts-ticket-office-service/node_modules/punycode/README.md b/ts-ticket-office-service/node_modules/punycode/README.md new file mode 100644 index 000000000..ee2f9d633 --- /dev/null +++ b/ts-ticket-office-service/node_modules/punycode/README.md @@ -0,0 +1,122 @@ +# Punycode.js [![Build status](https://travis-ci.org/bestiejs/punycode.js.svg?branch=master)](https://travis-ci.org/bestiejs/punycode.js) [![Code coverage status](http://img.shields.io/codecov/c/github/bestiejs/punycode.js.svg)](https://codecov.io/gh/bestiejs/punycode.js) [![Dependency status](https://gemnasium.com/bestiejs/punycode.js.svg)](https://gemnasium.com/bestiejs/punycode.js) + +Punycode.js is a robust Punycode converter that fully complies to [RFC 3492](https://tools.ietf.org/html/rfc3492) and [RFC 5891](https://tools.ietf.org/html/rfc5891). + +This JavaScript library is the result of comparing, optimizing and documenting different open-source implementations of the Punycode algorithm: + +* [The C example code from RFC 3492](https://tools.ietf.org/html/rfc3492#appendix-C) +* [`punycode.c` by _Markus W. Scherer_ (IBM)](http://opensource.apple.com/source/ICU/ICU-400.42/icuSources/common/punycode.c) +* [`punycode.c` by _Ben Noordhuis_](https://github.com/bnoordhuis/punycode/blob/master/punycode.c) +* [JavaScript implementation by _some_](http://stackoverflow.com/questions/183485/can-anyone-recommend-a-good-free-javascript-for-punycode-to-unicode-conversion/301287#301287) +* [`punycode.js` by _Ben Noordhuis_](https://github.com/joyent/node/blob/426298c8c1c0d5b5224ac3658c41e7c2a3fe9377/lib/punycode.js) (note: [not fully compliant](https://github.com/joyent/node/issues/2072)) + +This project was [bundled](https://github.com/joyent/node/blob/master/lib/punycode.js) with Node.js from [v0.6.2+](https://github.com/joyent/node/compare/975f1930b1...61e796decc) until [v7](https://github.com/nodejs/node/pull/7941) (soft-deprecated). + +The current version supports recent versions of Node.js only. It provides a CommonJS module and an ES6 module. For the old version that offers the same functionality with broader support, including Rhino, Ringo, Narwhal, and web browsers, see [v1.4.1](https://github.com/bestiejs/punycode.js/releases/tag/v1.4.1). + +## Installation + +Via [npm](https://www.npmjs.com/): + +```bash +npm install punycode --save +``` + +In [Node.js](https://nodejs.org/): + +```js +const punycode = require('punycode'); +``` + +## API + +### `punycode.decode(string)` + +Converts a Punycode string of ASCII symbols to a string of Unicode symbols. + +```js +// decode domain name parts +punycode.decode('maana-pta'); // 'mañana' +punycode.decode('--dqo34k'); // '☃-⌘' +``` + +### `punycode.encode(string)` + +Converts a string of Unicode symbols to a Punycode string of ASCII symbols. + +```js +// encode domain name parts +punycode.encode('mañana'); // 'maana-pta' +punycode.encode('☃-⌘'); // '--dqo34k' +``` + +### `punycode.toUnicode(input)` + +Converts a Punycode string representing a domain name or an email address to Unicode. Only the Punycoded parts of the input will be converted, i.e. it doesn’t matter if you call it on a string that has already been converted to Unicode. + +```js +// decode domain names +punycode.toUnicode('xn--maana-pta.com'); +// → 'mañana.com' +punycode.toUnicode('xn----dqo34k.com'); +// → '☃-⌘.com' + +// decode email addresses +punycode.toUnicode('джумла@xn--p-8sbkgc5ag7bhce.xn--ba-lmcq'); +// → 'джумла@джpумлатест.bрфa' +``` + +### `punycode.toASCII(input)` + +Converts a lowercased Unicode string representing a domain name or an email address to Punycode. Only the non-ASCII parts of the input will be converted, i.e. it doesn’t matter if you call it with a domain that’s already in ASCII. + +```js +// encode domain names +punycode.toASCII('mañana.com'); +// → 'xn--maana-pta.com' +punycode.toASCII('☃-⌘.com'); +// → 'xn----dqo34k.com' + +// encode email addresses +punycode.toASCII('джумла@джpумлатест.bрфa'); +// → 'джумла@xn--p-8sbkgc5ag7bhce.xn--ba-lmcq' +``` + +### `punycode.ucs2` + +#### `punycode.ucs2.decode(string)` + +Creates an array containing the numeric code point values of each Unicode symbol in the string. While [JavaScript uses UCS-2 internally](https://mathiasbynens.be/notes/javascript-encoding), this function will convert a pair of surrogate halves (each of which UCS-2 exposes as separate characters) into a single code point, matching UTF-16. + +```js +punycode.ucs2.decode('abc'); +// → [0x61, 0x62, 0x63] +// surrogate pair for U+1D306 TETRAGRAM FOR CENTRE: +punycode.ucs2.decode('\uD834\uDF06'); +// → [0x1D306] +``` + +#### `punycode.ucs2.encode(codePoints)` + +Creates a string based on an array of numeric code point values. + +```js +punycode.ucs2.encode([0x61, 0x62, 0x63]); +// → 'abc' +punycode.ucs2.encode([0x1D306]); +// → '\uD834\uDF06' +``` + +### `punycode.version` + +A string representing the current Punycode.js version number. + +## Author + +| [![twitter/mathias](https://gravatar.com/avatar/24e08a9ea84deb17ae121074d0f17125?s=70)](https://twitter.com/mathias "Follow @mathias on Twitter") | +|---| +| [Mathias Bynens](https://mathiasbynens.be/) | + +## License + +Punycode.js is available under the [MIT](https://mths.be/mit) license. diff --git a/ts-ticket-office-service/node_modules/punycode/package.json b/ts-ticket-office-service/node_modules/punycode/package.json new file mode 100644 index 000000000..9202ccf8c --- /dev/null +++ b/ts-ticket-office-service/node_modules/punycode/package.json @@ -0,0 +1,58 @@ +{ + "name": "punycode", + "version": "2.1.1", + "description": "A robust Punycode converter that fully complies to RFC 3492 and RFC 5891, and works on nearly all JavaScript platforms.", + "homepage": "https://mths.be/punycode", + "main": "punycode.js", + "jsnext:main": "punycode.es6.js", + "module": "punycode.es6.js", + "engines": { + "node": ">=6" + }, + "keywords": [ + "punycode", + "unicode", + "idn", + "idna", + "dns", + "url", + "domain" + ], + "license": "MIT", + "author": { + "name": "Mathias Bynens", + "url": "https://mathiasbynens.be/" + }, + "contributors": [ + { + "name": "Mathias Bynens", + "url": "https://mathiasbynens.be/" + } + ], + "repository": { + "type": "git", + "url": "https://github.com/bestiejs/punycode.js.git" + }, + "bugs": "https://github.com/bestiejs/punycode.js/issues", + "files": [ + "LICENSE-MIT.txt", + "punycode.js", + "punycode.es6.js" + ], + "scripts": { + "test": "mocha tests", + "prepublish": "node scripts/prepublish.js" + }, + "devDependencies": { + "codecov": "^1.0.1", + "istanbul": "^0.4.1", + "mocha": "^2.5.3" + }, + "jspm": { + "map": { + "./punycode.js": { + "node": "@node/punycode" + } + } + } +} diff --git a/ts-ticket-office-service/node_modules/punycode/punycode.es6.js b/ts-ticket-office-service/node_modules/punycode/punycode.es6.js new file mode 100644 index 000000000..4610bc9eb --- /dev/null +++ b/ts-ticket-office-service/node_modules/punycode/punycode.es6.js @@ -0,0 +1,441 @@ +'use strict'; + +/** Highest positive signed 32-bit float value */ +const maxInt = 2147483647; // aka. 0x7FFFFFFF or 2^31-1 + +/** Bootstring parameters */ +const base = 36; +const tMin = 1; +const tMax = 26; +const skew = 38; +const damp = 700; +const initialBias = 72; +const initialN = 128; // 0x80 +const delimiter = '-'; // '\x2D' + +/** Regular expressions */ +const regexPunycode = /^xn--/; +const regexNonASCII = /[^\0-\x7E]/; // non-ASCII chars +const regexSeparators = /[\x2E\u3002\uFF0E\uFF61]/g; // RFC 3490 separators + +/** Error messages */ +const errors = { + 'overflow': 'Overflow: input needs wider integers to process', + 'not-basic': 'Illegal input >= 0x80 (not a basic code point)', + 'invalid-input': 'Invalid input' +}; + +/** Convenience shortcuts */ +const baseMinusTMin = base - tMin; +const floor = Math.floor; +const stringFromCharCode = String.fromCharCode; + +/*--------------------------------------------------------------------------*/ + +/** + * A generic error utility function. + * @private + * @param {String} type The error type. + * @returns {Error} Throws a `RangeError` with the applicable error message. + */ +function error(type) { + throw new RangeError(errors[type]); +} + +/** + * A generic `Array#map` utility function. + * @private + * @param {Array} array The array to iterate over. + * @param {Function} callback The function that gets called for every array + * item. + * @returns {Array} A new array of values returned by the callback function. + */ +function map(array, fn) { + const result = []; + let length = array.length; + while (length--) { + result[length] = fn(array[length]); + } + return result; +} + +/** + * A simple `Array#map`-like wrapper to work with domain name strings or email + * addresses. + * @private + * @param {String} domain The domain name or email address. + * @param {Function} callback The function that gets called for every + * character. + * @returns {Array} A new string of characters returned by the callback + * function. + */ +function mapDomain(string, fn) { + const parts = string.split('@'); + let result = ''; + if (parts.length > 1) { + // In email addresses, only the domain name should be punycoded. Leave + // the local part (i.e. everything up to `@`) intact. + result = parts[0] + '@'; + string = parts[1]; + } + // Avoid `split(regex)` for IE8 compatibility. See #17. + string = string.replace(regexSeparators, '\x2E'); + const labels = string.split('.'); + const encoded = map(labels, fn).join('.'); + return result + encoded; +} + +/** + * Creates an array containing the numeric code points of each Unicode + * character in the string. While JavaScript uses UCS-2 internally, + * this function will convert a pair of surrogate halves (each of which + * UCS-2 exposes as separate characters) into a single code point, + * matching UTF-16. + * @see `punycode.ucs2.encode` + * @see + * @memberOf punycode.ucs2 + * @name decode + * @param {String} string The Unicode input string (UCS-2). + * @returns {Array} The new array of code points. + */ +function ucs2decode(string) { + const output = []; + let counter = 0; + const length = string.length; + while (counter < length) { + const value = string.charCodeAt(counter++); + if (value >= 0xD800 && value <= 0xDBFF && counter < length) { + // It's a high surrogate, and there is a next character. + const extra = string.charCodeAt(counter++); + if ((extra & 0xFC00) == 0xDC00) { // Low surrogate. + output.push(((value & 0x3FF) << 10) + (extra & 0x3FF) + 0x10000); + } else { + // It's an unmatched surrogate; only append this code unit, in case the + // next code unit is the high surrogate of a surrogate pair. + output.push(value); + counter--; + } + } else { + output.push(value); + } + } + return output; +} + +/** + * Creates a string based on an array of numeric code points. + * @see `punycode.ucs2.decode` + * @memberOf punycode.ucs2 + * @name encode + * @param {Array} codePoints The array of numeric code points. + * @returns {String} The new Unicode string (UCS-2). + */ +const ucs2encode = array => String.fromCodePoint(...array); + +/** + * Converts a basic code point into a digit/integer. + * @see `digitToBasic()` + * @private + * @param {Number} codePoint The basic numeric code point value. + * @returns {Number} The numeric value of a basic code point (for use in + * representing integers) in the range `0` to `base - 1`, or `base` if + * the code point does not represent a value. + */ +const basicToDigit = function(codePoint) { + if (codePoint - 0x30 < 0x0A) { + return codePoint - 0x16; + } + if (codePoint - 0x41 < 0x1A) { + return codePoint - 0x41; + } + if (codePoint - 0x61 < 0x1A) { + return codePoint - 0x61; + } + return base; +}; + +/** + * Converts a digit/integer into a basic code point. + * @see `basicToDigit()` + * @private + * @param {Number} digit The numeric value of a basic code point. + * @returns {Number} The basic code point whose value (when used for + * representing integers) is `digit`, which needs to be in the range + * `0` to `base - 1`. If `flag` is non-zero, the uppercase form is + * used; else, the lowercase form is used. The behavior is undefined + * if `flag` is non-zero and `digit` has no uppercase form. + */ +const digitToBasic = function(digit, flag) { + // 0..25 map to ASCII a..z or A..Z + // 26..35 map to ASCII 0..9 + return digit + 22 + 75 * (digit < 26) - ((flag != 0) << 5); +}; + +/** + * Bias adaptation function as per section 3.4 of RFC 3492. + * https://tools.ietf.org/html/rfc3492#section-3.4 + * @private + */ +const adapt = function(delta, numPoints, firstTime) { + let k = 0; + delta = firstTime ? floor(delta / damp) : delta >> 1; + delta += floor(delta / numPoints); + for (/* no initialization */; delta > baseMinusTMin * tMax >> 1; k += base) { + delta = floor(delta / baseMinusTMin); + } + return floor(k + (baseMinusTMin + 1) * delta / (delta + skew)); +}; + +/** + * Converts a Punycode string of ASCII-only symbols to a string of Unicode + * symbols. + * @memberOf punycode + * @param {String} input The Punycode string of ASCII-only symbols. + * @returns {String} The resulting string of Unicode symbols. + */ +const decode = function(input) { + // Don't use UCS-2. + const output = []; + const inputLength = input.length; + let i = 0; + let n = initialN; + let bias = initialBias; + + // Handle the basic code points: let `basic` be the number of input code + // points before the last delimiter, or `0` if there is none, then copy + // the first basic code points to the output. + + let basic = input.lastIndexOf(delimiter); + if (basic < 0) { + basic = 0; + } + + for (let j = 0; j < basic; ++j) { + // if it's not a basic code point + if (input.charCodeAt(j) >= 0x80) { + error('not-basic'); + } + output.push(input.charCodeAt(j)); + } + + // Main decoding loop: start just after the last delimiter if any basic code + // points were copied; start at the beginning otherwise. + + for (let index = basic > 0 ? basic + 1 : 0; index < inputLength; /* no final expression */) { + + // `index` is the index of the next character to be consumed. + // Decode a generalized variable-length integer into `delta`, + // which gets added to `i`. The overflow checking is easier + // if we increase `i` as we go, then subtract off its starting + // value at the end to obtain `delta`. + let oldi = i; + for (let w = 1, k = base; /* no condition */; k += base) { + + if (index >= inputLength) { + error('invalid-input'); + } + + const digit = basicToDigit(input.charCodeAt(index++)); + + if (digit >= base || digit > floor((maxInt - i) / w)) { + error('overflow'); + } + + i += digit * w; + const t = k <= bias ? tMin : (k >= bias + tMax ? tMax : k - bias); + + if (digit < t) { + break; + } + + const baseMinusT = base - t; + if (w > floor(maxInt / baseMinusT)) { + error('overflow'); + } + + w *= baseMinusT; + + } + + const out = output.length + 1; + bias = adapt(i - oldi, out, oldi == 0); + + // `i` was supposed to wrap around from `out` to `0`, + // incrementing `n` each time, so we'll fix that now: + if (floor(i / out) > maxInt - n) { + error('overflow'); + } + + n += floor(i / out); + i %= out; + + // Insert `n` at position `i` of the output. + output.splice(i++, 0, n); + + } + + return String.fromCodePoint(...output); +}; + +/** + * Converts a string of Unicode symbols (e.g. a domain name label) to a + * Punycode string of ASCII-only symbols. + * @memberOf punycode + * @param {String} input The string of Unicode symbols. + * @returns {String} The resulting Punycode string of ASCII-only symbols. + */ +const encode = function(input) { + const output = []; + + // Convert the input in UCS-2 to an array of Unicode code points. + input = ucs2decode(input); + + // Cache the length. + let inputLength = input.length; + + // Initialize the state. + let n = initialN; + let delta = 0; + let bias = initialBias; + + // Handle the basic code points. + for (const currentValue of input) { + if (currentValue < 0x80) { + output.push(stringFromCharCode(currentValue)); + } + } + + let basicLength = output.length; + let handledCPCount = basicLength; + + // `handledCPCount` is the number of code points that have been handled; + // `basicLength` is the number of basic code points. + + // Finish the basic string with a delimiter unless it's empty. + if (basicLength) { + output.push(delimiter); + } + + // Main encoding loop: + while (handledCPCount < inputLength) { + + // All non-basic code points < n have been handled already. Find the next + // larger one: + let m = maxInt; + for (const currentValue of input) { + if (currentValue >= n && currentValue < m) { + m = currentValue; + } + } + + // Increase `delta` enough to advance the decoder's state to , + // but guard against overflow. + const handledCPCountPlusOne = handledCPCount + 1; + if (m - n > floor((maxInt - delta) / handledCPCountPlusOne)) { + error('overflow'); + } + + delta += (m - n) * handledCPCountPlusOne; + n = m; + + for (const currentValue of input) { + if (currentValue < n && ++delta > maxInt) { + error('overflow'); + } + if (currentValue == n) { + // Represent delta as a generalized variable-length integer. + let q = delta; + for (let k = base; /* no condition */; k += base) { + const t = k <= bias ? tMin : (k >= bias + tMax ? tMax : k - bias); + if (q < t) { + break; + } + const qMinusT = q - t; + const baseMinusT = base - t; + output.push( + stringFromCharCode(digitToBasic(t + qMinusT % baseMinusT, 0)) + ); + q = floor(qMinusT / baseMinusT); + } + + output.push(stringFromCharCode(digitToBasic(q, 0))); + bias = adapt(delta, handledCPCountPlusOne, handledCPCount == basicLength); + delta = 0; + ++handledCPCount; + } + } + + ++delta; + ++n; + + } + return output.join(''); +}; + +/** + * Converts a Punycode string representing a domain name or an email address + * to Unicode. Only the Punycoded parts of the input will be converted, i.e. + * it doesn't matter if you call it on a string that has already been + * converted to Unicode. + * @memberOf punycode + * @param {String} input The Punycoded domain name or email address to + * convert to Unicode. + * @returns {String} The Unicode representation of the given Punycode + * string. + */ +const toUnicode = function(input) { + return mapDomain(input, function(string) { + return regexPunycode.test(string) + ? decode(string.slice(4).toLowerCase()) + : string; + }); +}; + +/** + * Converts a Unicode string representing a domain name or an email address to + * Punycode. Only the non-ASCII parts of the domain name will be converted, + * i.e. it doesn't matter if you call it with a domain that's already in + * ASCII. + * @memberOf punycode + * @param {String} input The domain name or email address to convert, as a + * Unicode string. + * @returns {String} The Punycode representation of the given domain name or + * email address. + */ +const toASCII = function(input) { + return mapDomain(input, function(string) { + return regexNonASCII.test(string) + ? 'xn--' + encode(string) + : string; + }); +}; + +/*--------------------------------------------------------------------------*/ + +/** Define the public API */ +const punycode = { + /** + * A string representing the current Punycode.js version number. + * @memberOf punycode + * @type String + */ + 'version': '2.1.0', + /** + * An object of methods to convert from JavaScript's internal character + * representation (UCS-2) to Unicode code points, and back. + * @see + * @memberOf punycode + * @type Object + */ + 'ucs2': { + 'decode': ucs2decode, + 'encode': ucs2encode + }, + 'decode': decode, + 'encode': encode, + 'toASCII': toASCII, + 'toUnicode': toUnicode +}; + +export { ucs2decode, ucs2encode, decode, encode, toASCII, toUnicode }; +export default punycode; diff --git a/ts-ticket-office-service/node_modules/punycode/punycode.js b/ts-ticket-office-service/node_modules/punycode/punycode.js new file mode 100644 index 000000000..ea61fd0d3 --- /dev/null +++ b/ts-ticket-office-service/node_modules/punycode/punycode.js @@ -0,0 +1,440 @@ +'use strict'; + +/** Highest positive signed 32-bit float value */ +const maxInt = 2147483647; // aka. 0x7FFFFFFF or 2^31-1 + +/** Bootstring parameters */ +const base = 36; +const tMin = 1; +const tMax = 26; +const skew = 38; +const damp = 700; +const initialBias = 72; +const initialN = 128; // 0x80 +const delimiter = '-'; // '\x2D' + +/** Regular expressions */ +const regexPunycode = /^xn--/; +const regexNonASCII = /[^\0-\x7E]/; // non-ASCII chars +const regexSeparators = /[\x2E\u3002\uFF0E\uFF61]/g; // RFC 3490 separators + +/** Error messages */ +const errors = { + 'overflow': 'Overflow: input needs wider integers to process', + 'not-basic': 'Illegal input >= 0x80 (not a basic code point)', + 'invalid-input': 'Invalid input' +}; + +/** Convenience shortcuts */ +const baseMinusTMin = base - tMin; +const floor = Math.floor; +const stringFromCharCode = String.fromCharCode; + +/*--------------------------------------------------------------------------*/ + +/** + * A generic error utility function. + * @private + * @param {String} type The error type. + * @returns {Error} Throws a `RangeError` with the applicable error message. + */ +function error(type) { + throw new RangeError(errors[type]); +} + +/** + * A generic `Array#map` utility function. + * @private + * @param {Array} array The array to iterate over. + * @param {Function} callback The function that gets called for every array + * item. + * @returns {Array} A new array of values returned by the callback function. + */ +function map(array, fn) { + const result = []; + let length = array.length; + while (length--) { + result[length] = fn(array[length]); + } + return result; +} + +/** + * A simple `Array#map`-like wrapper to work with domain name strings or email + * addresses. + * @private + * @param {String} domain The domain name or email address. + * @param {Function} callback The function that gets called for every + * character. + * @returns {Array} A new string of characters returned by the callback + * function. + */ +function mapDomain(string, fn) { + const parts = string.split('@'); + let result = ''; + if (parts.length > 1) { + // In email addresses, only the domain name should be punycoded. Leave + // the local part (i.e. everything up to `@`) intact. + result = parts[0] + '@'; + string = parts[1]; + } + // Avoid `split(regex)` for IE8 compatibility. See #17. + string = string.replace(regexSeparators, '\x2E'); + const labels = string.split('.'); + const encoded = map(labels, fn).join('.'); + return result + encoded; +} + +/** + * Creates an array containing the numeric code points of each Unicode + * character in the string. While JavaScript uses UCS-2 internally, + * this function will convert a pair of surrogate halves (each of which + * UCS-2 exposes as separate characters) into a single code point, + * matching UTF-16. + * @see `punycode.ucs2.encode` + * @see + * @memberOf punycode.ucs2 + * @name decode + * @param {String} string The Unicode input string (UCS-2). + * @returns {Array} The new array of code points. + */ +function ucs2decode(string) { + const output = []; + let counter = 0; + const length = string.length; + while (counter < length) { + const value = string.charCodeAt(counter++); + if (value >= 0xD800 && value <= 0xDBFF && counter < length) { + // It's a high surrogate, and there is a next character. + const extra = string.charCodeAt(counter++); + if ((extra & 0xFC00) == 0xDC00) { // Low surrogate. + output.push(((value & 0x3FF) << 10) + (extra & 0x3FF) + 0x10000); + } else { + // It's an unmatched surrogate; only append this code unit, in case the + // next code unit is the high surrogate of a surrogate pair. + output.push(value); + counter--; + } + } else { + output.push(value); + } + } + return output; +} + +/** + * Creates a string based on an array of numeric code points. + * @see `punycode.ucs2.decode` + * @memberOf punycode.ucs2 + * @name encode + * @param {Array} codePoints The array of numeric code points. + * @returns {String} The new Unicode string (UCS-2). + */ +const ucs2encode = array => String.fromCodePoint(...array); + +/** + * Converts a basic code point into a digit/integer. + * @see `digitToBasic()` + * @private + * @param {Number} codePoint The basic numeric code point value. + * @returns {Number} The numeric value of a basic code point (for use in + * representing integers) in the range `0` to `base - 1`, or `base` if + * the code point does not represent a value. + */ +const basicToDigit = function(codePoint) { + if (codePoint - 0x30 < 0x0A) { + return codePoint - 0x16; + } + if (codePoint - 0x41 < 0x1A) { + return codePoint - 0x41; + } + if (codePoint - 0x61 < 0x1A) { + return codePoint - 0x61; + } + return base; +}; + +/** + * Converts a digit/integer into a basic code point. + * @see `basicToDigit()` + * @private + * @param {Number} digit The numeric value of a basic code point. + * @returns {Number} The basic code point whose value (when used for + * representing integers) is `digit`, which needs to be in the range + * `0` to `base - 1`. If `flag` is non-zero, the uppercase form is + * used; else, the lowercase form is used. The behavior is undefined + * if `flag` is non-zero and `digit` has no uppercase form. + */ +const digitToBasic = function(digit, flag) { + // 0..25 map to ASCII a..z or A..Z + // 26..35 map to ASCII 0..9 + return digit + 22 + 75 * (digit < 26) - ((flag != 0) << 5); +}; + +/** + * Bias adaptation function as per section 3.4 of RFC 3492. + * https://tools.ietf.org/html/rfc3492#section-3.4 + * @private + */ +const adapt = function(delta, numPoints, firstTime) { + let k = 0; + delta = firstTime ? floor(delta / damp) : delta >> 1; + delta += floor(delta / numPoints); + for (/* no initialization */; delta > baseMinusTMin * tMax >> 1; k += base) { + delta = floor(delta / baseMinusTMin); + } + return floor(k + (baseMinusTMin + 1) * delta / (delta + skew)); +}; + +/** + * Converts a Punycode string of ASCII-only symbols to a string of Unicode + * symbols. + * @memberOf punycode + * @param {String} input The Punycode string of ASCII-only symbols. + * @returns {String} The resulting string of Unicode symbols. + */ +const decode = function(input) { + // Don't use UCS-2. + const output = []; + const inputLength = input.length; + let i = 0; + let n = initialN; + let bias = initialBias; + + // Handle the basic code points: let `basic` be the number of input code + // points before the last delimiter, or `0` if there is none, then copy + // the first basic code points to the output. + + let basic = input.lastIndexOf(delimiter); + if (basic < 0) { + basic = 0; + } + + for (let j = 0; j < basic; ++j) { + // if it's not a basic code point + if (input.charCodeAt(j) >= 0x80) { + error('not-basic'); + } + output.push(input.charCodeAt(j)); + } + + // Main decoding loop: start just after the last delimiter if any basic code + // points were copied; start at the beginning otherwise. + + for (let index = basic > 0 ? basic + 1 : 0; index < inputLength; /* no final expression */) { + + // `index` is the index of the next character to be consumed. + // Decode a generalized variable-length integer into `delta`, + // which gets added to `i`. The overflow checking is easier + // if we increase `i` as we go, then subtract off its starting + // value at the end to obtain `delta`. + let oldi = i; + for (let w = 1, k = base; /* no condition */; k += base) { + + if (index >= inputLength) { + error('invalid-input'); + } + + const digit = basicToDigit(input.charCodeAt(index++)); + + if (digit >= base || digit > floor((maxInt - i) / w)) { + error('overflow'); + } + + i += digit * w; + const t = k <= bias ? tMin : (k >= bias + tMax ? tMax : k - bias); + + if (digit < t) { + break; + } + + const baseMinusT = base - t; + if (w > floor(maxInt / baseMinusT)) { + error('overflow'); + } + + w *= baseMinusT; + + } + + const out = output.length + 1; + bias = adapt(i - oldi, out, oldi == 0); + + // `i` was supposed to wrap around from `out` to `0`, + // incrementing `n` each time, so we'll fix that now: + if (floor(i / out) > maxInt - n) { + error('overflow'); + } + + n += floor(i / out); + i %= out; + + // Insert `n` at position `i` of the output. + output.splice(i++, 0, n); + + } + + return String.fromCodePoint(...output); +}; + +/** + * Converts a string of Unicode symbols (e.g. a domain name label) to a + * Punycode string of ASCII-only symbols. + * @memberOf punycode + * @param {String} input The string of Unicode symbols. + * @returns {String} The resulting Punycode string of ASCII-only symbols. + */ +const encode = function(input) { + const output = []; + + // Convert the input in UCS-2 to an array of Unicode code points. + input = ucs2decode(input); + + // Cache the length. + let inputLength = input.length; + + // Initialize the state. + let n = initialN; + let delta = 0; + let bias = initialBias; + + // Handle the basic code points. + for (const currentValue of input) { + if (currentValue < 0x80) { + output.push(stringFromCharCode(currentValue)); + } + } + + let basicLength = output.length; + let handledCPCount = basicLength; + + // `handledCPCount` is the number of code points that have been handled; + // `basicLength` is the number of basic code points. + + // Finish the basic string with a delimiter unless it's empty. + if (basicLength) { + output.push(delimiter); + } + + // Main encoding loop: + while (handledCPCount < inputLength) { + + // All non-basic code points < n have been handled already. Find the next + // larger one: + let m = maxInt; + for (const currentValue of input) { + if (currentValue >= n && currentValue < m) { + m = currentValue; + } + } + + // Increase `delta` enough to advance the decoder's state to , + // but guard against overflow. + const handledCPCountPlusOne = handledCPCount + 1; + if (m - n > floor((maxInt - delta) / handledCPCountPlusOne)) { + error('overflow'); + } + + delta += (m - n) * handledCPCountPlusOne; + n = m; + + for (const currentValue of input) { + if (currentValue < n && ++delta > maxInt) { + error('overflow'); + } + if (currentValue == n) { + // Represent delta as a generalized variable-length integer. + let q = delta; + for (let k = base; /* no condition */; k += base) { + const t = k <= bias ? tMin : (k >= bias + tMax ? tMax : k - bias); + if (q < t) { + break; + } + const qMinusT = q - t; + const baseMinusT = base - t; + output.push( + stringFromCharCode(digitToBasic(t + qMinusT % baseMinusT, 0)) + ); + q = floor(qMinusT / baseMinusT); + } + + output.push(stringFromCharCode(digitToBasic(q, 0))); + bias = adapt(delta, handledCPCountPlusOne, handledCPCount == basicLength); + delta = 0; + ++handledCPCount; + } + } + + ++delta; + ++n; + + } + return output.join(''); +}; + +/** + * Converts a Punycode string representing a domain name or an email address + * to Unicode. Only the Punycoded parts of the input will be converted, i.e. + * it doesn't matter if you call it on a string that has already been + * converted to Unicode. + * @memberOf punycode + * @param {String} input The Punycoded domain name or email address to + * convert to Unicode. + * @returns {String} The Unicode representation of the given Punycode + * string. + */ +const toUnicode = function(input) { + return mapDomain(input, function(string) { + return regexPunycode.test(string) + ? decode(string.slice(4).toLowerCase()) + : string; + }); +}; + +/** + * Converts a Unicode string representing a domain name or an email address to + * Punycode. Only the non-ASCII parts of the domain name will be converted, + * i.e. it doesn't matter if you call it with a domain that's already in + * ASCII. + * @memberOf punycode + * @param {String} input The domain name or email address to convert, as a + * Unicode string. + * @returns {String} The Punycode representation of the given domain name or + * email address. + */ +const toASCII = function(input) { + return mapDomain(input, function(string) { + return regexNonASCII.test(string) + ? 'xn--' + encode(string) + : string; + }); +}; + +/*--------------------------------------------------------------------------*/ + +/** Define the public API */ +const punycode = { + /** + * A string representing the current Punycode.js version number. + * @memberOf punycode + * @type String + */ + 'version': '2.1.0', + /** + * An object of methods to convert from JavaScript's internal character + * representation (UCS-2) to Unicode code points, and back. + * @see + * @memberOf punycode + * @type Object + */ + 'ucs2': { + 'decode': ucs2decode, + 'encode': ucs2encode + }, + 'decode': decode, + 'encode': encode, + 'toASCII': toASCII, + 'toUnicode': toUnicode +}; + +module.exports = punycode; diff --git a/ts-ticket-office-service/node_modules/readable-stream/.npmignore b/ts-ticket-office-service/node_modules/readable-stream/.npmignore deleted file mode 100644 index 6d270c6cc..000000000 --- a/ts-ticket-office-service/node_modules/readable-stream/.npmignore +++ /dev/null @@ -1,9 +0,0 @@ -build/ -test/ -examples/ -fs.js -zlib.js -.zuul.yml -.nyc_output -coverage -docs/ diff --git a/ts-ticket-office-service/node_modules/readable-stream/.travis.yml b/ts-ticket-office-service/node_modules/readable-stream/.travis.yml deleted file mode 100644 index 76b4b0cfc..000000000 --- a/ts-ticket-office-service/node_modules/readable-stream/.travis.yml +++ /dev/null @@ -1,49 +0,0 @@ -sudo: false -language: node_js -before_install: - - npm install -g npm@2 - - npm install -g npm -notifications: - email: false -matrix: - fast_finish: true - include: - - node_js: '0.8' - env: TASK=test - - node_js: '0.10' - env: TASK=test - - node_js: '0.11' - env: TASK=test - - node_js: '0.12' - env: TASK=test - - node_js: 1 - env: TASK=test - - node_js: 2 - env: TASK=test - - node_js: 3 - env: TASK=test - - node_js: 4 - env: TASK=test - - node_js: 5 - env: TASK=test - - node_js: 6 - env: TASK=test - - node_js: 7 - env: TASK=test - - node_js: 5 - env: TASK=browser BROWSER_NAME=ie BROWSER_VERSION="9..latest" - - node_js: 5 - env: TASK=browser BROWSER_NAME=opera BROWSER_VERSION="11..latest" - - node_js: 5 - env: TASK=browser BROWSER_NAME=chrome BROWSER_VERSION="-3..latest" - - node_js: 5 - env: TASK=browser BROWSER_NAME=firefox BROWSER_VERSION="-3..latest" - - node_js: 5 - env: TASK=browser BROWSER_NAME=safari BROWSER_VERSION="5..latest" - - node_js: 5 - env: TASK=browser BROWSER_NAME=microsoftedge BROWSER_VERSION=latest -script: "npm run $TASK" -env: - global: - - secure: rE2Vvo7vnjabYNULNyLFxOyt98BoJexDqsiOnfiD6kLYYsiQGfr/sbZkPMOFm9qfQG7pjqx+zZWZjGSswhTt+626C0t/njXqug7Yps4c3dFblzGfreQHp7wNX5TFsvrxd6dAowVasMp61sJcRnB2w8cUzoe3RAYUDHyiHktwqMc= - - secure: g9YINaKAdMatsJ28G9jCGbSaguXCyxSTy+pBO6Ch0Cf57ZLOTka3HqDj8p3nV28LUIHZ3ut5WO43CeYKwt4AUtLpBS3a0dndHdY6D83uY6b2qh5hXlrcbeQTq2cvw2y95F7hm4D1kwrgZ7ViqaKggRcEupAL69YbJnxeUDKWEdI= diff --git a/ts-ticket-office-service/node_modules/readable-stream/lib/_stream_duplex.js b/ts-ticket-office-service/node_modules/readable-stream/lib/_stream_duplex.js deleted file mode 100644 index 736693b84..000000000 --- a/ts-ticket-office-service/node_modules/readable-stream/lib/_stream_duplex.js +++ /dev/null @@ -1,75 +0,0 @@ -// a duplex stream is just a stream that is both readable and writable. -// Since JS doesn't have multiple prototypal inheritance, this class -// prototypally inherits from Readable, and then parasitically from -// Writable. - -'use strict'; - -/**/ - -var objectKeys = Object.keys || function (obj) { - var keys = []; - for (var key in obj) { - keys.push(key); - }return keys; -}; -/**/ - -module.exports = Duplex; - -/**/ -var processNextTick = require('process-nextick-args'); -/**/ - -/**/ -var util = require('core-util-is'); -util.inherits = require('inherits'); -/**/ - -var Readable = require('./_stream_readable'); -var Writable = require('./_stream_writable'); - -util.inherits(Duplex, Readable); - -var keys = objectKeys(Writable.prototype); -for (var v = 0; v < keys.length; v++) { - var method = keys[v]; - if (!Duplex.prototype[method]) Duplex.prototype[method] = Writable.prototype[method]; -} - -function Duplex(options) { - if (!(this instanceof Duplex)) return new Duplex(options); - - Readable.call(this, options); - Writable.call(this, options); - - if (options && options.readable === false) this.readable = false; - - if (options && options.writable === false) this.writable = false; - - this.allowHalfOpen = true; - if (options && options.allowHalfOpen === false) this.allowHalfOpen = false; - - this.once('end', onend); -} - -// the no-half-open enforcer -function onend() { - // if we allow half-open state, or if the writable side ended, - // then we're ok. - if (this.allowHalfOpen || this._writableState.ended) return; - - // no more data can be written. - // But allow more writes to happen in this tick. - processNextTick(onEndNT, this); -} - -function onEndNT(self) { - self.end(); -} - -function forEach(xs, f) { - for (var i = 0, l = xs.length; i < l; i++) { - f(xs[i], i); - } -} \ No newline at end of file diff --git a/ts-ticket-office-service/node_modules/readable-stream/lib/_stream_passthrough.js b/ts-ticket-office-service/node_modules/readable-stream/lib/_stream_passthrough.js deleted file mode 100644 index d06f71f18..000000000 --- a/ts-ticket-office-service/node_modules/readable-stream/lib/_stream_passthrough.js +++ /dev/null @@ -1,26 +0,0 @@ -// a passthrough stream. -// basically just the most minimal sort of Transform stream. -// Every written chunk gets output as-is. - -'use strict'; - -module.exports = PassThrough; - -var Transform = require('./_stream_transform'); - -/**/ -var util = require('core-util-is'); -util.inherits = require('inherits'); -/**/ - -util.inherits(PassThrough, Transform); - -function PassThrough(options) { - if (!(this instanceof PassThrough)) return new PassThrough(options); - - Transform.call(this, options); -} - -PassThrough.prototype._transform = function (chunk, encoding, cb) { - cb(null, chunk); -}; \ No newline at end of file diff --git a/ts-ticket-office-service/node_modules/readable-stream/lib/internal/streams/BufferList.js b/ts-ticket-office-service/node_modules/readable-stream/lib/internal/streams/BufferList.js deleted file mode 100644 index e4bfcf02d..000000000 --- a/ts-ticket-office-service/node_modules/readable-stream/lib/internal/streams/BufferList.js +++ /dev/null @@ -1,64 +0,0 @@ -'use strict'; - -var Buffer = require('buffer').Buffer; -/**/ -var bufferShim = require('buffer-shims'); -/**/ - -module.exports = BufferList; - -function BufferList() { - this.head = null; - this.tail = null; - this.length = 0; -} - -BufferList.prototype.push = function (v) { - var entry = { data: v, next: null }; - if (this.length > 0) this.tail.next = entry;else this.head = entry; - this.tail = entry; - ++this.length; -}; - -BufferList.prototype.unshift = function (v) { - var entry = { data: v, next: this.head }; - if (this.length === 0) this.tail = entry; - this.head = entry; - ++this.length; -}; - -BufferList.prototype.shift = function () { - if (this.length === 0) return; - var ret = this.head.data; - if (this.length === 1) this.head = this.tail = null;else this.head = this.head.next; - --this.length; - return ret; -}; - -BufferList.prototype.clear = function () { - this.head = this.tail = null; - this.length = 0; -}; - -BufferList.prototype.join = function (s) { - if (this.length === 0) return ''; - var p = this.head; - var ret = '' + p.data; - while (p = p.next) { - ret += s + p.data; - }return ret; -}; - -BufferList.prototype.concat = function (n) { - if (this.length === 0) return bufferShim.alloc(0); - if (this.length === 1) return this.head.data; - var ret = bufferShim.allocUnsafe(n >>> 0); - var p = this.head; - var i = 0; - while (p) { - p.data.copy(ret, i); - i += p.data.length; - p = p.next; - } - return ret; -}; \ No newline at end of file diff --git a/ts-ticket-office-service/node_modules/readable-stream/package.json b/ts-ticket-office-service/node_modules/readable-stream/package.json deleted file mode 100644 index e7657910b..000000000 --- a/ts-ticket-office-service/node_modules/readable-stream/package.json +++ /dev/null @@ -1,136 +0,0 @@ -{ - "_args": [ - [ - { - "raw": "readable-stream@2.2.7", - "scope": null, - "escapedName": "readable-stream", - "name": "readable-stream", - "rawSpec": "2.2.7", - "spec": "2.2.7", - "type": "version" - }, - "F:\\gitwork\\workspace_microservices\\ts-ticket-office-service\\node_modules\\mongodb" - ] - ], - "_from": "readable-stream@2.2.7", - "_id": "readable-stream@2.2.7", - "_inCache": true, - "_location": "/readable-stream", - "_nodeVersion": "6.10.1", - "_npmOperationalInternal": { - "host": "packages-12-west.internal.npmjs.com", - "tmp": "tmp/readable-stream-2.2.7.tgz_1491551100653_0.5321758626960218" - }, - "_npmUser": { - "name": "matteo.collina", - "email": "hello@matteocollina.com" - }, - "_npmVersion": "3.10.10", - "_phantomChildren": {}, - "_requested": { - "raw": "readable-stream@2.2.7", - "scope": null, - "escapedName": "readable-stream", - "name": "readable-stream", - "rawSpec": "2.2.7", - "spec": "2.2.7", - "type": "version" - }, - "_requiredBy": [ - "/mongodb" - ], - "_resolved": "https://registry.npmjs.org/readable-stream/-/readable-stream-2.2.7.tgz", - "_shasum": "07057acbe2467b22042d36f98c5ad507054e95b1", - "_shrinkwrap": null, - "_spec": "readable-stream@2.2.7", - "_where": "F:\\gitwork\\workspace_microservices\\ts-ticket-office-service\\node_modules\\mongodb", - "browser": { - "util": false, - "./readable.js": "./readable-browser.js", - "./writable.js": "./writable-browser.js", - "./duplex.js": "./duplex-browser.js" - }, - "bugs": { - "url": "https://github.com/nodejs/readable-stream/issues" - }, - "dependencies": { - "buffer-shims": "~1.0.0", - "core-util-is": "~1.0.0", - "inherits": "~2.0.1", - "isarray": "~1.0.0", - "process-nextick-args": "~1.0.6", - "string_decoder": "~1.0.0", - "util-deprecate": "~1.0.1" - }, - "description": "Streams3, a user-land copy of the stream library from Node.js", - "devDependencies": { - "assert": "~1.4.0", - "babel-polyfill": "^6.9.1", - "buffer": "^4.9.0", - "nyc": "^6.4.0", - "tap": "~0.7.1", - "tape": "~4.5.1", - "zuul": "~3.10.0" - }, - "directories": {}, - "dist": { - "shasum": "07057acbe2467b22042d36f98c5ad507054e95b1", - "tarball": "https://registry.npmjs.org/readable-stream/-/readable-stream-2.2.7.tgz" - }, - "gitHead": "847d79ea060d512ddd07f5e246c12a38520da308", - "homepage": "https://github.com/nodejs/readable-stream#readme", - "keywords": [ - "readable", - "stream", - "pipe" - ], - "license": "MIT", - "main": "readable.js", - "maintainers": [ - { - "name": "cwmma", - "email": "calvin.metcalf@gmail.com" - }, - { - "name": "isaacs", - "email": "i@izs.me" - }, - { - "name": "matteo.collina", - "email": "hello@matteocollina.com" - }, - { - "name": "rvagg", - "email": "rod@vagg.org" - }, - { - "name": "tootallnate", - "email": "nathan@tootallnate.net" - } - ], - "name": "readable-stream", - "nyc": { - "include": [ - "lib/**.js" - ] - }, - "optionalDependencies": {}, - "react-native": { - "stream": false - }, - "readme": "ERROR: No README data found!", - "repository": { - "type": "git", - "url": "git://github.com/nodejs/readable-stream.git" - }, - "scripts": { - "browser": "npm run write-zuul && zuul --browser-retries 2 -- test/browser.js", - "cover": "nyc npm test", - "local": "zuul --local 3000 --no-coverage -- test/browser.js", - "report": "nyc report --reporter=lcov", - "test": "tap test/parallel/*.js test/ours/*.js", - "write-zuul": "printf \"ui: tape\nbrowsers:\n - name: $BROWSER_NAME\n version: $BROWSER_VERSION\n\">.zuul.yml" - }, - "version": "2.2.7" -} diff --git a/ts-ticket-office-service/node_modules/require_optional/.npmignore b/ts-ticket-office-service/node_modules/require_optional/.npmignore deleted file mode 100644 index e920c1671..000000000 --- a/ts-ticket-office-service/node_modules/require_optional/.npmignore +++ /dev/null @@ -1,33 +0,0 @@ -# Logs -logs -*.log -npm-debug.log* - -# Runtime data -pids -*.pid -*.seed - -# Directory for instrumented libs generated by jscoverage/JSCover -lib-cov - -# Coverage directory used by tools like istanbul -coverage - -# Grunt intermediate storage (http://gruntjs.com/creating-plugins#storing-task-files) -.grunt - -# node-waf configuration -.lock-wscript - -# Compiled binary addons (http://nodejs.org/api/addons.html) -build/Release - -# Dependency directory -node_modules - -# Optional npm cache directory -.npm - -# Optional REPL history -.node_repl_history diff --git a/ts-ticket-office-service/node_modules/require_optional/.travis.yml b/ts-ticket-office-service/node_modules/require_optional/.travis.yml deleted file mode 100644 index 72903c34a..000000000 --- a/ts-ticket-office-service/node_modules/require_optional/.travis.yml +++ /dev/null @@ -1,9 +0,0 @@ -language: node_js -node_js: - - "0.10" - - "0.12" - - "4" - - "6" - - "7" - - "8" -sudo: false diff --git a/ts-ticket-office-service/node_modules/require_optional/HISTORY.md b/ts-ticket-office-service/node_modules/require_optional/HISTORY.md deleted file mode 100644 index 7bee02fc0..000000000 --- a/ts-ticket-office-service/node_modules/require_optional/HISTORY.md +++ /dev/null @@ -1,7 +0,0 @@ -1.0.1 03-02-2016 -================ -* Fix dependency resolution issue when a component in peerOptionalDependencies is installed at the level of the module declaring in peerOptionalDependencies. - -1.0.0 03-02-2016 -================ -* Initial release allowing us to optionally resolve dependencies in the package.json file under the peerOptionalDependencies tag. \ No newline at end of file diff --git a/ts-ticket-office-service/node_modules/require_optional/README.md b/ts-ticket-office-service/node_modules/require_optional/README.md deleted file mode 100644 index c0323f065..000000000 --- a/ts-ticket-office-service/node_modules/require_optional/README.md +++ /dev/null @@ -1,2 +0,0 @@ -# require_optional -Work around the problem that we do not have a optionalPeerDependencies concept in node.js making it a hassle to optionally include native modules diff --git a/ts-ticket-office-service/node_modules/require_optional/index.js b/ts-ticket-office-service/node_modules/require_optional/index.js deleted file mode 100644 index 3710319fe..000000000 --- a/ts-ticket-office-service/node_modules/require_optional/index.js +++ /dev/null @@ -1,128 +0,0 @@ -var path = require('path'), - fs = require('fs'), - f = require('util').format, - resolveFrom = require('resolve-from'), - semver = require('semver'); - -var exists = fs.existsSync || path.existsSync; - -// Find the location of a package.json file near or above the given location -var find_package_json = function(location) { - var found = false; - - while(!found) { - if (exists(location + '/package.json')) { - found = location; - } else if (location !== '/') { - location = path.dirname(location); - } else { - return false; - } - } - - return location; -} - -// Find the package.json object of the module closest up the module call tree that contains name in that module's peerOptionalDependencies -var find_package_json_with_name = function(name) { - // Walk up the module call tree until we find a module containing name in its peerOptionalDependencies - var currentModule = module; - var found = false; - while (currentModule) { - // Check currentModule has a package.json - location = currentModule.filename; - var location = find_package_json(location) - if (!location) { - currentModule = currentModule.parent; - continue; - } - - // Read the package.json file - var object = JSON.parse(fs.readFileSync(f('%s/package.json', location))); - // Is the name defined by interal file references - var parts = name.split(/\//); - - // Check whether this package.json contains peerOptionalDependencies containing the name we're searching for - if (!object.peerOptionalDependencies || (object.peerOptionalDependencies && !object.peerOptionalDependencies[parts[0]])) { - currentModule = currentModule.parent; - continue; - } - found = true; - break; - } - - // Check whether name has been found in currentModule's peerOptionalDependencies - if (!found) { - throw new Error(f('no optional dependency [%s] defined in peerOptionalDependencies in any package.json', parts[0])); - } - - return { - object: object, - parts: parts - } -} - -var require_optional = function(name, options) { - options = options || {}; - options.strict = typeof options.strict == 'boolean' ? options.strict : true; - - var res = find_package_json_with_name(name) - var object = res.object; - var parts = res.parts; - - // Unpack the expected version - var expectedVersions = object.peerOptionalDependencies[parts[0]]; - // The resolved package - var moduleEntry = undefined; - // Module file - var moduleEntryFile = name; - - try { - // Validate if it's possible to read the module - moduleEntry = require(moduleEntryFile); - } catch(err) { - // Attempt to resolve in top level package - try { - // Get the module entry file - moduleEntryFile = resolveFrom(process.cwd(), name); - if(moduleEntryFile == null) return undefined; - // Attempt to resolve the module - moduleEntry = require(moduleEntryFile); - } catch(err) { - if(err.code === 'MODULE_NOT_FOUND') return undefined; - } - } - - // Resolve the location of the module's package.json file - var location = find_package_json(require.resolve(moduleEntryFile)); - if(!location) { - throw new Error('package.json can not be located'); - } - - // Read the module file - var dependentOnModule = JSON.parse(fs.readFileSync(f('%s/package.json', location))); - // Get the version - var version = dependentOnModule.version; - // Validate if the found module satisfies the version id - if(semver.satisfies(version, expectedVersions) == false - && options.strict) { - var error = new Error(f('optional dependency [%s] found but version [%s] did not satisfy constraint [%s]', parts[0], version, expectedVersions)); - error.code = 'OPTIONAL_MODULE_NOT_FOUND'; - throw error; - } - - // Satifies the module requirement - return moduleEntry; -} - -require_optional.exists = function(name) { - try { - var m = require_optional(name); - if(m === undefined) return false; - return true; - } catch(err) { - return false; - } -} - -module.exports = require_optional; diff --git a/ts-ticket-office-service/node_modules/require_optional/package.json b/ts-ticket-office-service/node_modules/require_optional/package.json deleted file mode 100644 index 04f48b962..000000000 --- a/ts-ticket-office-service/node_modules/require_optional/package.json +++ /dev/null @@ -1,103 +0,0 @@ -{ - "_args": [ - [ - { - "raw": "require_optional@~1.0.0", - "scope": null, - "escapedName": "require_optional", - "name": "require_optional", - "rawSpec": "~1.0.0", - "spec": ">=1.0.0 <1.1.0", - "type": "range" - }, - "F:\\gitwork\\workspace_microservices\\ts-ticket-office-service\\node_modules\\mongodb-core" - ] - ], - "_from": "require_optional@>=1.0.0 <1.1.0", - "_id": "require_optional@1.0.1", - "_inCache": true, - "_location": "/require_optional", - "_nodeVersion": "8.1.0", - "_npmOperationalInternal": { - "host": "s3://npm-registry-packages", - "tmp": "tmp/require_optional-1.0.1.tgz_1497424160858_0.9788372260518372" - }, - "_npmUser": { - "name": "christkv", - "email": "christkv@gmail.com" - }, - "_npmVersion": "5.0.3", - "_phantomChildren": {}, - "_requested": { - "raw": "require_optional@~1.0.0", - "scope": null, - "escapedName": "require_optional", - "name": "require_optional", - "rawSpec": "~1.0.0", - "spec": ">=1.0.0 <1.1.0", - "type": "range" - }, - "_requiredBy": [ - "/mongodb-core" - ], - "_resolved": "https://registry.npmjs.org/require_optional/-/require_optional-1.0.1.tgz", - "_shasum": "4cf35a4247f64ca3df8c2ef208cc494b1ca8fc2e", - "_shrinkwrap": null, - "_spec": "require_optional@~1.0.0", - "_where": "F:\\gitwork\\workspace_microservices\\ts-ticket-office-service\\node_modules\\mongodb-core", - "author": { - "name": "Christian Kvalheim Amor" - }, - "bugs": { - "url": "https://github.com/christkv/require_optional/issues" - }, - "dependencies": { - "resolve-from": "^2.0.0", - "semver": "^5.1.0" - }, - "description": "Allows you declare optionalPeerDependencies that can be satisfied by the top level module but ignored if they are not.", - "devDependencies": { - "bson": "0.4.21", - "co": "4.6.0", - "es6-promise": "^3.0.2", - "mocha": "^2.4.5" - }, - "directories": {}, - "dist": { - "integrity": "sha512-qhM/y57enGWHAe3v/NcwML6a3/vfESLe/sGM2dII+gEO0BpKRUkWZow/tyloNqJyN6kXSl3RyyM8Ll5D/sJP8g==", - "shasum": "4cf35a4247f64ca3df8c2ef208cc494b1ca8fc2e", - "tarball": "https://registry.npmjs.org/require_optional/-/require_optional-1.0.1.tgz" - }, - "gitHead": "4e10f508d3d27ae4f967b0ab48dcb869bc9b6727", - "homepage": "https://github.com/christkv/require_optional", - "keywords": [ - "optional", - "require", - "optionalPeerDependencies" - ], - "license": "Apache-2.0", - "main": "index.js", - "maintainers": [ - { - "name": "christkv", - "email": "christkv@gmail.com" - } - ], - "name": "require_optional", - "optionalDependencies": {}, - "peerOptionalDependencies": { - "co": ">=5.6.0", - "es6-promise": "^3.0.2", - "es6-promise2": "^4.0.2", - "bson": "0.4.21" - }, - "readme": "ERROR: No README data found!", - "repository": { - "type": "git", - "url": "git+https://github.com/christkv/require_optional.git" - }, - "scripts": { - "test": "mocha" - }, - "version": "1.0.1" -} diff --git a/ts-ticket-office-service/node_modules/require_optional/test/nestedTest/index.js b/ts-ticket-office-service/node_modules/require_optional/test/nestedTest/index.js deleted file mode 100644 index 76de2ab4c..000000000 --- a/ts-ticket-office-service/node_modules/require_optional/test/nestedTest/index.js +++ /dev/null @@ -1,8 +0,0 @@ -var require_optional = require('../../') - -function findPackage(packageName) { - var pkg = require_optional(packageName); - return pkg; -} - -module.exports.findPackage = findPackage diff --git a/ts-ticket-office-service/node_modules/require_optional/test/nestedTest/package.json b/ts-ticket-office-service/node_modules/require_optional/test/nestedTest/package.json deleted file mode 100644 index 4c456a6bf..000000000 --- a/ts-ticket-office-service/node_modules/require_optional/test/nestedTest/package.json +++ /dev/null @@ -1,11 +0,0 @@ -{ - "name": "nestedtest", - "version": "1.0.0", - "description": "A dummy package that facilitates testing that require_optional correctly walks up the module call stack", - "main": "index.js", - "scripts": { - "test": "echo \"Error: no test specified\" && exit 1" - }, - "author": "Sebastian Hallum Clarke", - "license": "ISC" -} diff --git a/ts-ticket-office-service/node_modules/require_optional/test/require_optional_tests.js b/ts-ticket-office-service/node_modules/require_optional/test/require_optional_tests.js deleted file mode 100644 index c9cc2a361..000000000 --- a/ts-ticket-office-service/node_modules/require_optional/test/require_optional_tests.js +++ /dev/null @@ -1,59 +0,0 @@ -var assert = require('assert'), - require_optional = require('../'), - nestedTest = require('./nestedTest'); - -describe('Require Optional', function() { - describe('top level require', function() { - it('should correctly require co library', function() { - var promise = require_optional('es6-promise'); - assert.ok(promise); - }); - - it('should fail to require es6-promise library', function() { - try { - require_optional('co'); - } catch(e) { - assert.equal('OPTIONAL_MODULE_NOT_FOUND', e.code); - return; - } - - assert.ok(false); - }); - - it('should ignore optional library not defined', function() { - assert.equal(undefined, require_optional('es6-promise2')); - }); - }); - - describe('internal module file require', function() { - it('should correctly require co library', function() { - var Long = require_optional('bson/lib/bson/long.js'); - assert.ok(Long); - }); - }); - - describe('top level resolve', function() { - it('should correctly use exists method', function() { - assert.equal(false, require_optional.exists('co')); - assert.equal(true, require_optional.exists('es6-promise')); - assert.equal(true, require_optional.exists('bson/lib/bson/long.js')); - assert.equal(false, require_optional.exists('es6-promise2')); - }); - }); - - describe('require_optional inside dependencies', function() { - it('should correctly walk up module call stack searching for peerOptionalDependencies', function() { - assert.ok(nestedTest.findPackage('bson')) - }); - it('should return null when a package is defined in top-level package.json but not installed', function() { - assert.equal(null, nestedTest.findPackage('es6-promise2')) - }); - it('should error when searching for an optional dependency that is not defined in any ancestor package.json', function() { - try { - nestedTest.findPackage('bison') - } catch (err) { - assert.equal(err.message, 'no optional dependency [bison] defined in peerOptionalDependencies in any package.json') - } - }) - }); -}); diff --git a/ts-ticket-office-service/node_modules/resolve-from/index.js b/ts-ticket-office-service/node_modules/resolve-from/index.js deleted file mode 100644 index 434159f17..000000000 --- a/ts-ticket-office-service/node_modules/resolve-from/index.js +++ /dev/null @@ -1,23 +0,0 @@ -'use strict'; -var path = require('path'); -var Module = require('module'); - -module.exports = function (fromDir, moduleId) { - if (typeof fromDir !== 'string' || typeof moduleId !== 'string') { - throw new TypeError('Expected `fromDir` and `moduleId` to be a string'); - } - - fromDir = path.resolve(fromDir); - - var fromFile = path.join(fromDir, 'noop.js'); - - try { - return Module._resolveFilename(moduleId, { - id: fromFile, - filename: fromFile, - paths: Module._nodeModulePaths(fromDir) - }); - } catch (err) { - return null; - } -}; diff --git a/ts-ticket-office-service/node_modules/resolve-from/package.json b/ts-ticket-office-service/node_modules/resolve-from/package.json deleted file mode 100644 index 5873ed213..000000000 --- a/ts-ticket-office-service/node_modules/resolve-from/package.json +++ /dev/null @@ -1,98 +0,0 @@ -{ - "_args": [ - [ - { - "raw": "resolve-from@^2.0.0", - "scope": null, - "escapedName": "resolve-from", - "name": "resolve-from", - "rawSpec": "^2.0.0", - "spec": ">=2.0.0 <3.0.0", - "type": "range" - }, - "F:\\gitwork\\workspace_microservices\\ts-ticket-office-service\\node_modules\\require_optional" - ] - ], - "_from": "resolve-from@>=2.0.0 <3.0.0", - "_id": "resolve-from@2.0.0", - "_inCache": true, - "_location": "/resolve-from", - "_nodeVersion": "4.2.1", - "_npmUser": { - "name": "sindresorhus", - "email": "sindresorhus@gmail.com" - }, - "_npmVersion": "2.14.7", - "_phantomChildren": {}, - "_requested": { - "raw": "resolve-from@^2.0.0", - "scope": null, - "escapedName": "resolve-from", - "name": "resolve-from", - "rawSpec": "^2.0.0", - "spec": ">=2.0.0 <3.0.0", - "type": "range" - }, - "_requiredBy": [ - "/require_optional" - ], - "_resolved": "https://registry.npmjs.org/resolve-from/-/resolve-from-2.0.0.tgz", - "_shasum": "9480ab20e94ffa1d9e80a804c7ea147611966b57", - "_shrinkwrap": null, - "_spec": "resolve-from@^2.0.0", - "_where": "F:\\gitwork\\workspace_microservices\\ts-ticket-office-service\\node_modules\\require_optional", - "author": { - "name": "Sindre Sorhus", - "email": "sindresorhus@gmail.com", - "url": "sindresorhus.com" - }, - "bugs": { - "url": "https://github.com/sindresorhus/resolve-from/issues" - }, - "dependencies": {}, - "description": "Resolve the path of a module like require.resolve() but from a given path", - "devDependencies": { - "ava": "*", - "xo": "*" - }, - "directories": {}, - "dist": { - "shasum": "9480ab20e94ffa1d9e80a804c7ea147611966b57", - "tarball": "https://registry.npmjs.org/resolve-from/-/resolve-from-2.0.0.tgz" - }, - "engines": { - "node": ">=0.10.0" - }, - "files": [ - "index.js" - ], - "gitHead": "583e0f8df06e1bc4d1c96d8d4f2484c745f522c3", - "homepage": "https://github.com/sindresorhus/resolve-from", - "keywords": [ - "require", - "resolve", - "path", - "module", - "from", - "like", - "path" - ], - "license": "MIT", - "maintainers": [ - { - "name": "sindresorhus", - "email": "sindresorhus@gmail.com" - } - ], - "name": "resolve-from", - "optionalDependencies": {}, - "readme": "ERROR: No README data found!", - "repository": { - "type": "git", - "url": "git+https://github.com/sindresorhus/resolve-from.git" - }, - "scripts": { - "test": "xo && ava" - }, - "version": "2.0.0" -} diff --git a/ts-ticket-office-service/node_modules/resolve-from/readme.md b/ts-ticket-office-service/node_modules/resolve-from/readme.md deleted file mode 100644 index bb4ca91e8..000000000 --- a/ts-ticket-office-service/node_modules/resolve-from/readme.md +++ /dev/null @@ -1,58 +0,0 @@ -# resolve-from [![Build Status](https://travis-ci.org/sindresorhus/resolve-from.svg?branch=master)](https://travis-ci.org/sindresorhus/resolve-from) - -> Resolve the path of a module like [`require.resolve()`](http://nodejs.org/api/globals.html#globals_require_resolve) but from a given path - -Unlike `require.resolve()` it returns `null` instead of throwing when the module can't be found. - - -## Install - -``` -$ npm install --save resolve-from -``` - - -## Usage - -```js -const resolveFrom = require('resolve-from'); - -// there's a file at `./foo/bar.js` - -resolveFrom('foo', './bar'); -//=> '/Users/sindresorhus/dev/test/foo/bar.js' -``` - - -## API - -### resolveFrom(fromDir, moduleId) - -#### fromDir - -Type: `string` - -Directory to resolve from. - -#### moduleId - -Type: `string` - -What you would use in `require()`. - - -## Tip - -Create a partial using a bound function if you want to require from the same `fromDir` multiple times: - -```js -const resolveFromFoo = resolveFrom.bind(null, 'foo'); - -resolveFromFoo('./bar'); -resolveFromFoo('./baz'); -``` - - -## License - -MIT © [Sindre Sorhus](http://sindresorhus.com) diff --git a/ts-ticket-office-service/node_modules/saslprep/.editorconfig b/ts-ticket-office-service/node_modules/saslprep/.editorconfig new file mode 100644 index 000000000..d1d8a4176 --- /dev/null +++ b/ts-ticket-office-service/node_modules/saslprep/.editorconfig @@ -0,0 +1,10 @@ +# http://editorconfig.org +root = true + +[*] +indent_style = space +indent_size = 2 +end_of_line = lf +charset = utf-8 +trim_trailing_whitespace = true +insert_final_newline = true diff --git a/ts-ticket-office-service/node_modules/saslprep/.gitattributes b/ts-ticket-office-service/node_modules/saslprep/.gitattributes new file mode 100644 index 000000000..3ba45360c --- /dev/null +++ b/ts-ticket-office-service/node_modules/saslprep/.gitattributes @@ -0,0 +1 @@ +*.mem binary diff --git a/ts-ticket-office-service/node_modules/saslprep/CHANGELOG.md b/ts-ticket-office-service/node_modules/saslprep/CHANGELOG.md new file mode 100644 index 000000000..779807877 --- /dev/null +++ b/ts-ticket-office-service/node_modules/saslprep/CHANGELOG.md @@ -0,0 +1,19 @@ +# Change Log +All notable changes to the "saslprep" package will be documented in this file. + +## [1.0.3] - 2019-05-01 + +- Correctly get code points >U+FFFF ([#5](https://github.com/reklatsmasters/saslprep/pull/5)) +- Fix perfomance downgrades from [#5](https://github.com/reklatsmasters/saslprep/pull/5). + +## [1.0.2] - 2018-09-13 + +- Reduced initialization time ([#3](https://github.com/reklatsmasters/saslprep/issues/3)) + +## [1.0.1] - 2018-06-20 + +- Reduced stack overhead of range creation ([#2](https://github.com/reklatsmasters/saslprep/pull/2)) + +## [1.0.0] - 2017-06-21 + +- First release diff --git a/ts-ticket-office-service/node_modules/saslprep/LICENSE b/ts-ticket-office-service/node_modules/saslprep/LICENSE new file mode 100644 index 000000000..481c7a50f --- /dev/null +++ b/ts-ticket-office-service/node_modules/saslprep/LICENSE @@ -0,0 +1,22 @@ +Copyright (c) 2014 Dmitry Tsvettsikh + +Permission is hereby granted, free of charge, to any person +obtaining a copy of this software and associated documentation +files (the "Software"), to deal in the Software without +restriction, including without limitation the rights to use, +copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the +Software is furnished to do so, subject to the following +conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES +OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT +HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, +WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR +OTHER DEALINGS IN THE SOFTWARE. \ No newline at end of file diff --git a/ts-ticket-office-service/node_modules/saslprep/code-points.mem b/ts-ticket-office-service/node_modules/saslprep/code-points.mem new file mode 100644 index 0000000000000000000000000000000000000000..4781b066802688bdf954d2e89bcfac967db29c09 GIT binary patch literal 419864 zcmeI*O^9Si9RTop)4e+(t{DX(dsufSM8xBQfdsOo2lf&{@FWO&5cZ;Y@FWHe%nKV~ z@sxvzw;c53DIgdRk!c;t<{;##B4%51h#=^gL^8Y6+hx^z-92x{*9;3Umv`GA&vUy%enler!HTQKkA3&c=OSJMn7j|JGjl-d;Iey^#7>ZH0(RWYm^YJNA>kJ59aOu`p6X{MHRe9bu8cD2oYvN=9*ybv z%TyjdGTZ46aN&^<{xI6U)O2~U(!G+Yl0gPYRjbu8Wx~a<(#z+pIGvPkC#O7E&NgnV zIeue)&FW_ULfI&__U^^i@bTrer0O33=x2+%W4?Qo^)pjbsxinkv-K<<-Z9O6ZEyaQ zcB_@u#{%W}q9N0;ypzw%<*<}a^^Ob|R8?1xx0U*l{Mfi-J@SG5+xHJnzAqkVA73p) zfWWZ=`LSE4W4mY|K!5-N0t5&UATSizd-XW}{r>FO4Bx#OzCAE{nLD@VvjcA?1PBnA ze}O7c;{B8P-)Ji&@Gu01QMDYyI+%*sOCglv+~@Yqqm#Pz_SKwJ*n6ekt-IE7xb$i{ z#vJ7-%1?!2rG0Ri^X0*sx?FU--CIQw%Y*Zsb~)W#QAMFvj~+Qsr{Zh=QgU=xwFC$d zAV7cs0RjXF5FkK+009C72oNAZfB*pkrx2*aLB}2IZvhtFBipAEvDq7W9J^}&<>l~& z=Z6hT7u&hviF4icy{;$Z#$Rfh)bDEDcnTt22oNAJj{^NkPm$UP5FkK+009C72oNAZ zfB*pk1PBlya5e=N=WpRu-1tFH?r+Uep=aLS_2t}!1M%`E=_N&nH;IH{&FT4 zVA2E#5FkK+009C72oNAZfB*pk1PBlyK!5-N0tDtqVE;Gx53TDIQTIm zIQs(S*`MN>nqk~d)2W{+PVszkrlxK(QxGVpFoq#!SYT-_Rh1zb5B|v}x z0RjXF5FkK+009C72oNAZfB*pk1PBlyK!5;&ITaB9pVN)CECK`w5FkK+009C72oNAZ zfB*pk1PBlyK!5-N0t5&USSSJU|ApFaizPsS009C72oNAZfB*pk1PBlyK!5-N0t5&U zAV7csfjJcr|DV&1wJZVz2oNAZfB*pk1PBlyK!5-N0t5&UAV7cs0RjXF5LhUI)_PiQ zY@~%+y~PqBK!5-N0t5&UAV7cs0RjXF5FkK+009C72oNAZfB=E{5NI_*|FQ%K5FkK+ z009C72oNAZfB*pk1PBlyK!5-N0t5&UAV7e?Yzp*ebJ}K2fB*pk1PBlyK!5-N0t5&U zAV7cs0RjXF5FkK+009C72s8ykSewfEzdsXvos!llv!K)XN+!bACMEW{kJW7s~i{EW^`xUX5|{=UXrRtoY&_gwz< zRvE$%TJf3i_%h&Xxb|Z>^W9wXR6Vl#j!mc_rtE>35?{Z6IbwcGK;>nSRoF zHt&;$O2P80zs-^hqp)?4qhw2`7#YP=_?Tw>wDeltgbe?$_^GM=@ z?HoDm9erzgM=HMNFC|BJRZD;X0RjXF5FkK+009C72oNAZfB*pk1PBlya0-DOe>pzY z-vZ3vILv9#>4l5=+gV#xaVim;YNYBg{{HIj=YJUg^!l*j-g~>b;hnpk&0)>Sr{)*n zj_ut&1&%HR2oRWKfn%Q^H4q>`fB*pk1PBlyK!5-N0t5&UAVA>E3Jm7>U0X{dK!5-N z0t5&U__zX7c= character.codePointAt(0); +const first = x => x[0]; +const last = x => x[x.length - 1]; + +/** + * Convert provided string into an array of Unicode Code Points. + * Based on https://stackoverflow.com/a/21409165/1556249 + * and https://www.npmjs.com/package/code-point-at. + * @param {string} input + * @returns {number[]} + */ +function toCodePoints(input) { + const codepoints = []; + const size = input.length; + + for (let i = 0; i < size; i += 1) { + const before = input.charCodeAt(i); + + if (before >= 0xd800 && before <= 0xdbff && size > i + 1) { + const next = input.charCodeAt(i + 1); + + if (next >= 0xdc00 && next <= 0xdfff) { + codepoints.push((before - 0xd800) * 0x400 + next - 0xdc00 + 0x10000); + i += 1; + continue; + } + } + + codepoints.push(before); + } + + return codepoints; +} + +/** + * SASLprep. + * @param {string} input + * @param {Object} opts + * @param {boolean} opts.allowUnassigned + * @returns {string} + */ +function saslprep(input, opts = {}) { + if (typeof input !== 'string') { + throw new TypeError('Expected string.'); + } + + if (input.length === 0) { + return ''; + } + + // 1. Map + const mapped_input = toCodePoints(input) + // 1.1 mapping to space + .map(character => (mapping2space.get(character) ? 0x20 : character)) + // 1.2 mapping to nothing + .filter(character => !mapping2nothing.get(character)); + + // 2. Normalize + const normalized_input = String.fromCodePoint + .apply(null, mapped_input) + .normalize('NFKC'); + + const normalized_map = toCodePoints(normalized_input); + + // 3. Prohibit + const hasProhibited = normalized_map.some(character => + prohibited_characters.get(character) + ); + + if (hasProhibited) { + throw new Error( + 'Prohibited character, see https://tools.ietf.org/html/rfc4013#section-2.3' + ); + } + + // Unassigned Code Points + if (opts.allowUnassigned !== true) { + const hasUnassigned = normalized_map.some(character => + unassigned_code_points.get(character) + ); + + if (hasUnassigned) { + throw new Error( + 'Unassigned code point, see https://tools.ietf.org/html/rfc4013#section-2.5' + ); + } + } + + // 4. check bidi + + const hasBidiRAL = normalized_map.some(character => + bidirectional_r_al.get(character) + ); + + const hasBidiL = normalized_map.some(character => + bidirectional_l.get(character) + ); + + // 4.1 If a string contains any RandALCat character, the string MUST NOT + // contain any LCat character. + if (hasBidiRAL && hasBidiL) { + throw new Error( + 'String must not contain RandALCat and LCat at the same time,' + + ' see https://tools.ietf.org/html/rfc3454#section-6' + ); + } + + /** + * 4.2 If a string contains any RandALCat character, a RandALCat + * character MUST be the first character of the string, and a + * RandALCat character MUST be the last character of the string. + */ + + const isFirstBidiRAL = bidirectional_r_al.get( + getCodePoint(first(normalized_input)) + ); + const isLastBidiRAL = bidirectional_r_al.get( + getCodePoint(last(normalized_input)) + ); + + if (hasBidiRAL && !(isFirstBidiRAL && isLastBidiRAL)) { + throw new Error( + 'Bidirectional RandALCat character must be the first and the last' + + ' character of the string, see https://tools.ietf.org/html/rfc3454#section-6' + ); + } + + return normalized_input; +} diff --git a/ts-ticket-office-service/node_modules/saslprep/lib/code-points.js b/ts-ticket-office-service/node_modules/saslprep/lib/code-points.js new file mode 100644 index 000000000..222182c83 --- /dev/null +++ b/ts-ticket-office-service/node_modules/saslprep/lib/code-points.js @@ -0,0 +1,996 @@ +'use strict'; + +const { range } = require('./util'); + +/** + * A.1 Unassigned code points in Unicode 3.2 + * @link https://tools.ietf.org/html/rfc3454#appendix-A.1 + */ +const unassigned_code_points = new Set([ + 0x0221, + ...range(0x0234, 0x024f), + ...range(0x02ae, 0x02af), + ...range(0x02ef, 0x02ff), + ...range(0x0350, 0x035f), + ...range(0x0370, 0x0373), + ...range(0x0376, 0x0379), + ...range(0x037b, 0x037d), + ...range(0x037f, 0x0383), + 0x038b, + 0x038d, + 0x03a2, + 0x03cf, + ...range(0x03f7, 0x03ff), + 0x0487, + 0x04cf, + ...range(0x04f6, 0x04f7), + ...range(0x04fa, 0x04ff), + ...range(0x0510, 0x0530), + ...range(0x0557, 0x0558), + 0x0560, + 0x0588, + ...range(0x058b, 0x0590), + 0x05a2, + 0x05ba, + ...range(0x05c5, 0x05cf), + ...range(0x05eb, 0x05ef), + ...range(0x05f5, 0x060b), + ...range(0x060d, 0x061a), + ...range(0x061c, 0x061e), + 0x0620, + ...range(0x063b, 0x063f), + ...range(0x0656, 0x065f), + ...range(0x06ee, 0x06ef), + 0x06ff, + 0x070e, + ...range(0x072d, 0x072f), + ...range(0x074b, 0x077f), + ...range(0x07b2, 0x0900), + 0x0904, + ...range(0x093a, 0x093b), + ...range(0x094e, 0x094f), + ...range(0x0955, 0x0957), + ...range(0x0971, 0x0980), + 0x0984, + ...range(0x098d, 0x098e), + ...range(0x0991, 0x0992), + 0x09a9, + 0x09b1, + ...range(0x09b3, 0x09b5), + ...range(0x09ba, 0x09bb), + 0x09bd, + ...range(0x09c5, 0x09c6), + ...range(0x09c9, 0x09ca), + ...range(0x09ce, 0x09d6), + ...range(0x09d8, 0x09db), + 0x09de, + ...range(0x09e4, 0x09e5), + ...range(0x09fb, 0x0a01), + ...range(0x0a03, 0x0a04), + ...range(0x0a0b, 0x0a0e), + ...range(0x0a11, 0x0a12), + 0x0a29, + 0x0a31, + 0x0a34, + 0x0a37, + ...range(0x0a3a, 0x0a3b), + 0x0a3d, + ...range(0x0a43, 0x0a46), + ...range(0x0a49, 0x0a4a), + ...range(0x0a4e, 0x0a58), + 0x0a5d, + ...range(0x0a5f, 0x0a65), + ...range(0x0a75, 0x0a80), + 0x0a84, + 0x0a8c, + 0x0a8e, + 0x0a92, + 0x0aa9, + 0x0ab1, + 0x0ab4, + ...range(0x0aba, 0x0abb), + 0x0ac6, + 0x0aca, + ...range(0x0ace, 0x0acf), + ...range(0x0ad1, 0x0adf), + ...range(0x0ae1, 0x0ae5), + ...range(0x0af0, 0x0b00), + 0x0b04, + ...range(0x0b0d, 0x0b0e), + ...range(0x0b11, 0x0b12), + 0x0b29, + 0x0b31, + ...range(0x0b34, 0x0b35), + ...range(0x0b3a, 0x0b3b), + ...range(0x0b44, 0x0b46), + ...range(0x0b49, 0x0b4a), + ...range(0x0b4e, 0x0b55), + ...range(0x0b58, 0x0b5b), + 0x0b5e, + ...range(0x0b62, 0x0b65), + ...range(0x0b71, 0x0b81), + 0x0b84, + ...range(0x0b8b, 0x0b8d), + 0x0b91, + ...range(0x0b96, 0x0b98), + 0x0b9b, + 0x0b9d, + ...range(0x0ba0, 0x0ba2), + ...range(0x0ba5, 0x0ba7), + ...range(0x0bab, 0x0bad), + 0x0bb6, + ...range(0x0bba, 0x0bbd), + ...range(0x0bc3, 0x0bc5), + 0x0bc9, + ...range(0x0bce, 0x0bd6), + ...range(0x0bd8, 0x0be6), + ...range(0x0bf3, 0x0c00), + 0x0c04, + 0x0c0d, + 0x0c11, + 0x0c29, + 0x0c34, + ...range(0x0c3a, 0x0c3d), + 0x0c45, + 0x0c49, + ...range(0x0c4e, 0x0c54), + ...range(0x0c57, 0x0c5f), + ...range(0x0c62, 0x0c65), + ...range(0x0c70, 0x0c81), + 0x0c84, + 0x0c8d, + 0x0c91, + 0x0ca9, + 0x0cb4, + ...range(0x0cba, 0x0cbd), + 0x0cc5, + 0x0cc9, + ...range(0x0cce, 0x0cd4), + ...range(0x0cd7, 0x0cdd), + 0x0cdf, + ...range(0x0ce2, 0x0ce5), + ...range(0x0cf0, 0x0d01), + 0x0d04, + 0x0d0d, + 0x0d11, + 0x0d29, + ...range(0x0d3a, 0x0d3d), + ...range(0x0d44, 0x0d45), + 0x0d49, + ...range(0x0d4e, 0x0d56), + ...range(0x0d58, 0x0d5f), + ...range(0x0d62, 0x0d65), + ...range(0x0d70, 0x0d81), + 0x0d84, + ...range(0x0d97, 0x0d99), + 0x0db2, + 0x0dbc, + ...range(0x0dbe, 0x0dbf), + ...range(0x0dc7, 0x0dc9), + ...range(0x0dcb, 0x0dce), + 0x0dd5, + 0x0dd7, + ...range(0x0de0, 0x0df1), + ...range(0x0df5, 0x0e00), + ...range(0x0e3b, 0x0e3e), + ...range(0x0e5c, 0x0e80), + 0x0e83, + ...range(0x0e85, 0x0e86), + 0x0e89, + ...range(0x0e8b, 0x0e8c), + ...range(0x0e8e, 0x0e93), + 0x0e98, + 0x0ea0, + 0x0ea4, + 0x0ea6, + ...range(0x0ea8, 0x0ea9), + 0x0eac, + 0x0eba, + ...range(0x0ebe, 0x0ebf), + 0x0ec5, + 0x0ec7, + ...range(0x0ece, 0x0ecf), + ...range(0x0eda, 0x0edb), + ...range(0x0ede, 0x0eff), + 0x0f48, + ...range(0x0f6b, 0x0f70), + ...range(0x0f8c, 0x0f8f), + 0x0f98, + 0x0fbd, + ...range(0x0fcd, 0x0fce), + ...range(0x0fd0, 0x0fff), + 0x1022, + 0x1028, + 0x102b, + ...range(0x1033, 0x1035), + ...range(0x103a, 0x103f), + ...range(0x105a, 0x109f), + ...range(0x10c6, 0x10cf), + ...range(0x10f9, 0x10fa), + ...range(0x10fc, 0x10ff), + ...range(0x115a, 0x115e), + ...range(0x11a3, 0x11a7), + ...range(0x11fa, 0x11ff), + 0x1207, + 0x1247, + 0x1249, + ...range(0x124e, 0x124f), + 0x1257, + 0x1259, + ...range(0x125e, 0x125f), + 0x1287, + 0x1289, + ...range(0x128e, 0x128f), + 0x12af, + 0x12b1, + ...range(0x12b6, 0x12b7), + 0x12bf, + 0x12c1, + ...range(0x12c6, 0x12c7), + 0x12cf, + 0x12d7, + 0x12ef, + 0x130f, + 0x1311, + ...range(0x1316, 0x1317), + 0x131f, + 0x1347, + ...range(0x135b, 0x1360), + ...range(0x137d, 0x139f), + ...range(0x13f5, 0x1400), + ...range(0x1677, 0x167f), + ...range(0x169d, 0x169f), + ...range(0x16f1, 0x16ff), + 0x170d, + ...range(0x1715, 0x171f), + ...range(0x1737, 0x173f), + ...range(0x1754, 0x175f), + 0x176d, + 0x1771, + ...range(0x1774, 0x177f), + ...range(0x17dd, 0x17df), + ...range(0x17ea, 0x17ff), + 0x180f, + ...range(0x181a, 0x181f), + ...range(0x1878, 0x187f), + ...range(0x18aa, 0x1dff), + ...range(0x1e9c, 0x1e9f), + ...range(0x1efa, 0x1eff), + ...range(0x1f16, 0x1f17), + ...range(0x1f1e, 0x1f1f), + ...range(0x1f46, 0x1f47), + ...range(0x1f4e, 0x1f4f), + 0x1f58, + 0x1f5a, + 0x1f5c, + 0x1f5e, + ...range(0x1f7e, 0x1f7f), + 0x1fb5, + 0x1fc5, + ...range(0x1fd4, 0x1fd5), + 0x1fdc, + ...range(0x1ff0, 0x1ff1), + 0x1ff5, + 0x1fff, + ...range(0x2053, 0x2056), + ...range(0x2058, 0x205e), + ...range(0x2064, 0x2069), + ...range(0x2072, 0x2073), + ...range(0x208f, 0x209f), + ...range(0x20b2, 0x20cf), + ...range(0x20eb, 0x20ff), + ...range(0x213b, 0x213c), + ...range(0x214c, 0x2152), + ...range(0x2184, 0x218f), + ...range(0x23cf, 0x23ff), + ...range(0x2427, 0x243f), + ...range(0x244b, 0x245f), + 0x24ff, + ...range(0x2614, 0x2615), + 0x2618, + ...range(0x267e, 0x267f), + ...range(0x268a, 0x2700), + 0x2705, + ...range(0x270a, 0x270b), + 0x2728, + 0x274c, + 0x274e, + ...range(0x2753, 0x2755), + 0x2757, + ...range(0x275f, 0x2760), + ...range(0x2795, 0x2797), + 0x27b0, + ...range(0x27bf, 0x27cf), + ...range(0x27ec, 0x27ef), + ...range(0x2b00, 0x2e7f), + 0x2e9a, + ...range(0x2ef4, 0x2eff), + ...range(0x2fd6, 0x2fef), + ...range(0x2ffc, 0x2fff), + 0x3040, + ...range(0x3097, 0x3098), + ...range(0x3100, 0x3104), + ...range(0x312d, 0x3130), + 0x318f, + ...range(0x31b8, 0x31ef), + ...range(0x321d, 0x321f), + ...range(0x3244, 0x3250), + ...range(0x327c, 0x327e), + ...range(0x32cc, 0x32cf), + 0x32ff, + ...range(0x3377, 0x337a), + ...range(0x33de, 0x33df), + 0x33ff, + ...range(0x4db6, 0x4dff), + ...range(0x9fa6, 0x9fff), + ...range(0xa48d, 0xa48f), + ...range(0xa4c7, 0xabff), + ...range(0xd7a4, 0xd7ff), + ...range(0xfa2e, 0xfa2f), + ...range(0xfa6b, 0xfaff), + ...range(0xfb07, 0xfb12), + ...range(0xfb18, 0xfb1c), + 0xfb37, + 0xfb3d, + 0xfb3f, + 0xfb42, + 0xfb45, + ...range(0xfbb2, 0xfbd2), + ...range(0xfd40, 0xfd4f), + ...range(0xfd90, 0xfd91), + ...range(0xfdc8, 0xfdcf), + ...range(0xfdfd, 0xfdff), + ...range(0xfe10, 0xfe1f), + ...range(0xfe24, 0xfe2f), + ...range(0xfe47, 0xfe48), + 0xfe53, + 0xfe67, + ...range(0xfe6c, 0xfe6f), + 0xfe75, + ...range(0xfefd, 0xfefe), + 0xff00, + ...range(0xffbf, 0xffc1), + ...range(0xffc8, 0xffc9), + ...range(0xffd0, 0xffd1), + ...range(0xffd8, 0xffd9), + ...range(0xffdd, 0xffdf), + 0xffe7, + ...range(0xffef, 0xfff8), + ...range(0x10000, 0x102ff), + 0x1031f, + ...range(0x10324, 0x1032f), + ...range(0x1034b, 0x103ff), + ...range(0x10426, 0x10427), + ...range(0x1044e, 0x1cfff), + ...range(0x1d0f6, 0x1d0ff), + ...range(0x1d127, 0x1d129), + ...range(0x1d1de, 0x1d3ff), + 0x1d455, + 0x1d49d, + ...range(0x1d4a0, 0x1d4a1), + ...range(0x1d4a3, 0x1d4a4), + ...range(0x1d4a7, 0x1d4a8), + 0x1d4ad, + 0x1d4ba, + 0x1d4bc, + 0x1d4c1, + 0x1d4c4, + 0x1d506, + ...range(0x1d50b, 0x1d50c), + 0x1d515, + 0x1d51d, + 0x1d53a, + 0x1d53f, + 0x1d545, + ...range(0x1d547, 0x1d549), + 0x1d551, + ...range(0x1d6a4, 0x1d6a7), + ...range(0x1d7ca, 0x1d7cd), + ...range(0x1d800, 0x1fffd), + ...range(0x2a6d7, 0x2f7ff), + ...range(0x2fa1e, 0x2fffd), + ...range(0x30000, 0x3fffd), + ...range(0x40000, 0x4fffd), + ...range(0x50000, 0x5fffd), + ...range(0x60000, 0x6fffd), + ...range(0x70000, 0x7fffd), + ...range(0x80000, 0x8fffd), + ...range(0x90000, 0x9fffd), + ...range(0xa0000, 0xafffd), + ...range(0xb0000, 0xbfffd), + ...range(0xc0000, 0xcfffd), + ...range(0xd0000, 0xdfffd), + 0xe0000, + ...range(0xe0002, 0xe001f), + ...range(0xe0080, 0xefffd), +]); + +/** + * B.1 Commonly mapped to nothing + * @link https://tools.ietf.org/html/rfc3454#appendix-B.1 + */ +const commonly_mapped_to_nothing = new Set([ + 0x00ad, + 0x034f, + 0x1806, + 0x180b, + 0x180c, + 0x180d, + 0x200b, + 0x200c, + 0x200d, + 0x2060, + 0xfe00, + 0xfe01, + 0xfe02, + 0xfe03, + 0xfe04, + 0xfe05, + 0xfe06, + 0xfe07, + 0xfe08, + 0xfe09, + 0xfe0a, + 0xfe0b, + 0xfe0c, + 0xfe0d, + 0xfe0e, + 0xfe0f, + 0xfeff, +]); + +/** + * C.1.2 Non-ASCII space characters + * @link https://tools.ietf.org/html/rfc3454#appendix-C.1.2 + */ +const non_ASCII_space_characters = new Set([ + 0x00a0 /* NO-BREAK SPACE */, + 0x1680 /* OGHAM SPACE MARK */, + 0x2000 /* EN QUAD */, + 0x2001 /* EM QUAD */, + 0x2002 /* EN SPACE */, + 0x2003 /* EM SPACE */, + 0x2004 /* THREE-PER-EM SPACE */, + 0x2005 /* FOUR-PER-EM SPACE */, + 0x2006 /* SIX-PER-EM SPACE */, + 0x2007 /* FIGURE SPACE */, + 0x2008 /* PUNCTUATION SPACE */, + 0x2009 /* THIN SPACE */, + 0x200a /* HAIR SPACE */, + 0x200b /* ZERO WIDTH SPACE */, + 0x202f /* NARROW NO-BREAK SPACE */, + 0x205f /* MEDIUM MATHEMATICAL SPACE */, + 0x3000 /* IDEOGRAPHIC SPACE */, +]); + +/** + * 2.3. Prohibited Output + * @type {Set} + */ +const prohibited_characters = new Set([ + ...non_ASCII_space_characters, + + /** + * C.2.1 ASCII control characters + * @link https://tools.ietf.org/html/rfc3454#appendix-C.2.1 + */ + ...range(0, 0x001f) /* [CONTROL CHARACTERS] */, + 0x007f /* DELETE */, + + /** + * C.2.2 Non-ASCII control characters + * @link https://tools.ietf.org/html/rfc3454#appendix-C.2.2 + */ + ...range(0x0080, 0x009f) /* [CONTROL CHARACTERS] */, + 0x06dd /* ARABIC END OF AYAH */, + 0x070f /* SYRIAC ABBREVIATION MARK */, + 0x180e /* MONGOLIAN VOWEL SEPARATOR */, + 0x200c /* ZERO WIDTH NON-JOINER */, + 0x200d /* ZERO WIDTH JOINER */, + 0x2028 /* LINE SEPARATOR */, + 0x2029 /* PARAGRAPH SEPARATOR */, + 0x2060 /* WORD JOINER */, + 0x2061 /* FUNCTION APPLICATION */, + 0x2062 /* INVISIBLE TIMES */, + 0x2063 /* INVISIBLE SEPARATOR */, + ...range(0x206a, 0x206f) /* [CONTROL CHARACTERS] */, + 0xfeff /* ZERO WIDTH NO-BREAK SPACE */, + ...range(0xfff9, 0xfffc) /* [CONTROL CHARACTERS] */, + ...range(0x1d173, 0x1d17a) /* [MUSICAL CONTROL CHARACTERS] */, + + /** + * C.3 Private use + * @link https://tools.ietf.org/html/rfc3454#appendix-C.3 + */ + ...range(0xe000, 0xf8ff) /* [PRIVATE USE, PLANE 0] */, + ...range(0xf0000, 0xffffd) /* [PRIVATE USE, PLANE 15] */, + ...range(0x100000, 0x10fffd) /* [PRIVATE USE, PLANE 16] */, + + /** + * C.4 Non-character code points + * @link https://tools.ietf.org/html/rfc3454#appendix-C.4 + */ + ...range(0xfdd0, 0xfdef) /* [NONCHARACTER CODE POINTS] */, + ...range(0xfffe, 0xffff) /* [NONCHARACTER CODE POINTS] */, + ...range(0x1fffe, 0x1ffff) /* [NONCHARACTER CODE POINTS] */, + ...range(0x2fffe, 0x2ffff) /* [NONCHARACTER CODE POINTS] */, + ...range(0x3fffe, 0x3ffff) /* [NONCHARACTER CODE POINTS] */, + ...range(0x4fffe, 0x4ffff) /* [NONCHARACTER CODE POINTS] */, + ...range(0x5fffe, 0x5ffff) /* [NONCHARACTER CODE POINTS] */, + ...range(0x6fffe, 0x6ffff) /* [NONCHARACTER CODE POINTS] */, + ...range(0x7fffe, 0x7ffff) /* [NONCHARACTER CODE POINTS] */, + ...range(0x8fffe, 0x8ffff) /* [NONCHARACTER CODE POINTS] */, + ...range(0x9fffe, 0x9ffff) /* [NONCHARACTER CODE POINTS] */, + ...range(0xafffe, 0xaffff) /* [NONCHARACTER CODE POINTS] */, + ...range(0xbfffe, 0xbffff) /* [NONCHARACTER CODE POINTS] */, + ...range(0xcfffe, 0xcffff) /* [NONCHARACTER CODE POINTS] */, + ...range(0xdfffe, 0xdffff) /* [NONCHARACTER CODE POINTS] */, + ...range(0xefffe, 0xeffff) /* [NONCHARACTER CODE POINTS] */, + ...range(0x10fffe, 0x10ffff) /* [NONCHARACTER CODE POINTS] */, + + /** + * C.5 Surrogate codes + * @link https://tools.ietf.org/html/rfc3454#appendix-C.5 + */ + ...range(0xd800, 0xdfff), + + /** + * C.6 Inappropriate for plain text + * @link https://tools.ietf.org/html/rfc3454#appendix-C.6 + */ + 0xfff9 /* INTERLINEAR ANNOTATION ANCHOR */, + 0xfffa /* INTERLINEAR ANNOTATION SEPARATOR */, + 0xfffb /* INTERLINEAR ANNOTATION TERMINATOR */, + 0xfffc /* OBJECT REPLACEMENT CHARACTER */, + 0xfffd /* REPLACEMENT CHARACTER */, + + /** + * C.7 Inappropriate for canonical representation + * @link https://tools.ietf.org/html/rfc3454#appendix-C.7 + */ + ...range(0x2ff0, 0x2ffb) /* [IDEOGRAPHIC DESCRIPTION CHARACTERS] */, + + /** + * C.8 Change display properties or are deprecated + * @link https://tools.ietf.org/html/rfc3454#appendix-C.8 + */ + 0x0340 /* COMBINING GRAVE TONE MARK */, + 0x0341 /* COMBINING ACUTE TONE MARK */, + 0x200e /* LEFT-TO-RIGHT MARK */, + 0x200f /* RIGHT-TO-LEFT MARK */, + 0x202a /* LEFT-TO-RIGHT EMBEDDING */, + 0x202b /* RIGHT-TO-LEFT EMBEDDING */, + 0x202c /* POP DIRECTIONAL FORMATTING */, + 0x202d /* LEFT-TO-RIGHT OVERRIDE */, + 0x202e /* RIGHT-TO-LEFT OVERRIDE */, + 0x206a /* INHIBIT SYMMETRIC SWAPPING */, + 0x206b /* ACTIVATE SYMMETRIC SWAPPING */, + 0x206c /* INHIBIT ARABIC FORM SHAPING */, + 0x206d /* ACTIVATE ARABIC FORM SHAPING */, + 0x206e /* NATIONAL DIGIT SHAPES */, + 0x206f /* NOMINAL DIGIT SHAPES */, + + /** + * C.9 Tagging characters + * @link https://tools.ietf.org/html/rfc3454#appendix-C.9 + */ + 0xe0001 /* LANGUAGE TAG */, + ...range(0xe0020, 0xe007f) /* [TAGGING CHARACTERS] */, +]); + +/** + * D.1 Characters with bidirectional property "R" or "AL" + * @link https://tools.ietf.org/html/rfc3454#appendix-D.1 + */ +const bidirectional_r_al = new Set([ + 0x05be, + 0x05c0, + 0x05c3, + ...range(0x05d0, 0x05ea), + ...range(0x05f0, 0x05f4), + 0x061b, + 0x061f, + ...range(0x0621, 0x063a), + ...range(0x0640, 0x064a), + ...range(0x066d, 0x066f), + ...range(0x0671, 0x06d5), + 0x06dd, + ...range(0x06e5, 0x06e6), + ...range(0x06fa, 0x06fe), + ...range(0x0700, 0x070d), + 0x0710, + ...range(0x0712, 0x072c), + ...range(0x0780, 0x07a5), + 0x07b1, + 0x200f, + 0xfb1d, + ...range(0xfb1f, 0xfb28), + ...range(0xfb2a, 0xfb36), + ...range(0xfb38, 0xfb3c), + 0xfb3e, + ...range(0xfb40, 0xfb41), + ...range(0xfb43, 0xfb44), + ...range(0xfb46, 0xfbb1), + ...range(0xfbd3, 0xfd3d), + ...range(0xfd50, 0xfd8f), + ...range(0xfd92, 0xfdc7), + ...range(0xfdf0, 0xfdfc), + ...range(0xfe70, 0xfe74), + ...range(0xfe76, 0xfefc), +]); + +/** + * D.2 Characters with bidirectional property "L" + * @link https://tools.ietf.org/html/rfc3454#appendix-D.2 + */ +const bidirectional_l = new Set([ + ...range(0x0041, 0x005a), + ...range(0x0061, 0x007a), + 0x00aa, + 0x00b5, + 0x00ba, + ...range(0x00c0, 0x00d6), + ...range(0x00d8, 0x00f6), + ...range(0x00f8, 0x0220), + ...range(0x0222, 0x0233), + ...range(0x0250, 0x02ad), + ...range(0x02b0, 0x02b8), + ...range(0x02bb, 0x02c1), + ...range(0x02d0, 0x02d1), + ...range(0x02e0, 0x02e4), + 0x02ee, + 0x037a, + 0x0386, + ...range(0x0388, 0x038a), + 0x038c, + ...range(0x038e, 0x03a1), + ...range(0x03a3, 0x03ce), + ...range(0x03d0, 0x03f5), + ...range(0x0400, 0x0482), + ...range(0x048a, 0x04ce), + ...range(0x04d0, 0x04f5), + ...range(0x04f8, 0x04f9), + ...range(0x0500, 0x050f), + ...range(0x0531, 0x0556), + ...range(0x0559, 0x055f), + ...range(0x0561, 0x0587), + 0x0589, + 0x0903, + ...range(0x0905, 0x0939), + ...range(0x093d, 0x0940), + ...range(0x0949, 0x094c), + 0x0950, + ...range(0x0958, 0x0961), + ...range(0x0964, 0x0970), + ...range(0x0982, 0x0983), + ...range(0x0985, 0x098c), + ...range(0x098f, 0x0990), + ...range(0x0993, 0x09a8), + ...range(0x09aa, 0x09b0), + 0x09b2, + ...range(0x09b6, 0x09b9), + ...range(0x09be, 0x09c0), + ...range(0x09c7, 0x09c8), + ...range(0x09cb, 0x09cc), + 0x09d7, + ...range(0x09dc, 0x09dd), + ...range(0x09df, 0x09e1), + ...range(0x09e6, 0x09f1), + ...range(0x09f4, 0x09fa), + ...range(0x0a05, 0x0a0a), + ...range(0x0a0f, 0x0a10), + ...range(0x0a13, 0x0a28), + ...range(0x0a2a, 0x0a30), + ...range(0x0a32, 0x0a33), + ...range(0x0a35, 0x0a36), + ...range(0x0a38, 0x0a39), + ...range(0x0a3e, 0x0a40), + ...range(0x0a59, 0x0a5c), + 0x0a5e, + ...range(0x0a66, 0x0a6f), + ...range(0x0a72, 0x0a74), + 0x0a83, + ...range(0x0a85, 0x0a8b), + 0x0a8d, + ...range(0x0a8f, 0x0a91), + ...range(0x0a93, 0x0aa8), + ...range(0x0aaa, 0x0ab0), + ...range(0x0ab2, 0x0ab3), + ...range(0x0ab5, 0x0ab9), + ...range(0x0abd, 0x0ac0), + 0x0ac9, + ...range(0x0acb, 0x0acc), + 0x0ad0, + 0x0ae0, + ...range(0x0ae6, 0x0aef), + ...range(0x0b02, 0x0b03), + ...range(0x0b05, 0x0b0c), + ...range(0x0b0f, 0x0b10), + ...range(0x0b13, 0x0b28), + ...range(0x0b2a, 0x0b30), + ...range(0x0b32, 0x0b33), + ...range(0x0b36, 0x0b39), + ...range(0x0b3d, 0x0b3e), + 0x0b40, + ...range(0x0b47, 0x0b48), + ...range(0x0b4b, 0x0b4c), + 0x0b57, + ...range(0x0b5c, 0x0b5d), + ...range(0x0b5f, 0x0b61), + ...range(0x0b66, 0x0b70), + 0x0b83, + ...range(0x0b85, 0x0b8a), + ...range(0x0b8e, 0x0b90), + ...range(0x0b92, 0x0b95), + ...range(0x0b99, 0x0b9a), + 0x0b9c, + ...range(0x0b9e, 0x0b9f), + ...range(0x0ba3, 0x0ba4), + ...range(0x0ba8, 0x0baa), + ...range(0x0bae, 0x0bb5), + ...range(0x0bb7, 0x0bb9), + ...range(0x0bbe, 0x0bbf), + ...range(0x0bc1, 0x0bc2), + ...range(0x0bc6, 0x0bc8), + ...range(0x0bca, 0x0bcc), + 0x0bd7, + ...range(0x0be7, 0x0bf2), + ...range(0x0c01, 0x0c03), + ...range(0x0c05, 0x0c0c), + ...range(0x0c0e, 0x0c10), + ...range(0x0c12, 0x0c28), + ...range(0x0c2a, 0x0c33), + ...range(0x0c35, 0x0c39), + ...range(0x0c41, 0x0c44), + ...range(0x0c60, 0x0c61), + ...range(0x0c66, 0x0c6f), + ...range(0x0c82, 0x0c83), + ...range(0x0c85, 0x0c8c), + ...range(0x0c8e, 0x0c90), + ...range(0x0c92, 0x0ca8), + ...range(0x0caa, 0x0cb3), + ...range(0x0cb5, 0x0cb9), + 0x0cbe, + ...range(0x0cc0, 0x0cc4), + ...range(0x0cc7, 0x0cc8), + ...range(0x0cca, 0x0ccb), + ...range(0x0cd5, 0x0cd6), + 0x0cde, + ...range(0x0ce0, 0x0ce1), + ...range(0x0ce6, 0x0cef), + ...range(0x0d02, 0x0d03), + ...range(0x0d05, 0x0d0c), + ...range(0x0d0e, 0x0d10), + ...range(0x0d12, 0x0d28), + ...range(0x0d2a, 0x0d39), + ...range(0x0d3e, 0x0d40), + ...range(0x0d46, 0x0d48), + ...range(0x0d4a, 0x0d4c), + 0x0d57, + ...range(0x0d60, 0x0d61), + ...range(0x0d66, 0x0d6f), + ...range(0x0d82, 0x0d83), + ...range(0x0d85, 0x0d96), + ...range(0x0d9a, 0x0db1), + ...range(0x0db3, 0x0dbb), + 0x0dbd, + ...range(0x0dc0, 0x0dc6), + ...range(0x0dcf, 0x0dd1), + ...range(0x0dd8, 0x0ddf), + ...range(0x0df2, 0x0df4), + ...range(0x0e01, 0x0e30), + ...range(0x0e32, 0x0e33), + ...range(0x0e40, 0x0e46), + ...range(0x0e4f, 0x0e5b), + ...range(0x0e81, 0x0e82), + 0x0e84, + ...range(0x0e87, 0x0e88), + 0x0e8a, + 0x0e8d, + ...range(0x0e94, 0x0e97), + ...range(0x0e99, 0x0e9f), + ...range(0x0ea1, 0x0ea3), + 0x0ea5, + 0x0ea7, + ...range(0x0eaa, 0x0eab), + ...range(0x0ead, 0x0eb0), + ...range(0x0eb2, 0x0eb3), + 0x0ebd, + ...range(0x0ec0, 0x0ec4), + 0x0ec6, + ...range(0x0ed0, 0x0ed9), + ...range(0x0edc, 0x0edd), + ...range(0x0f00, 0x0f17), + ...range(0x0f1a, 0x0f34), + 0x0f36, + 0x0f38, + ...range(0x0f3e, 0x0f47), + ...range(0x0f49, 0x0f6a), + 0x0f7f, + 0x0f85, + ...range(0x0f88, 0x0f8b), + ...range(0x0fbe, 0x0fc5), + ...range(0x0fc7, 0x0fcc), + 0x0fcf, + ...range(0x1000, 0x1021), + ...range(0x1023, 0x1027), + ...range(0x1029, 0x102a), + 0x102c, + 0x1031, + 0x1038, + ...range(0x1040, 0x1057), + ...range(0x10a0, 0x10c5), + ...range(0x10d0, 0x10f8), + 0x10fb, + ...range(0x1100, 0x1159), + ...range(0x115f, 0x11a2), + ...range(0x11a8, 0x11f9), + ...range(0x1200, 0x1206), + ...range(0x1208, 0x1246), + 0x1248, + ...range(0x124a, 0x124d), + ...range(0x1250, 0x1256), + 0x1258, + ...range(0x125a, 0x125d), + ...range(0x1260, 0x1286), + 0x1288, + ...range(0x128a, 0x128d), + ...range(0x1290, 0x12ae), + 0x12b0, + ...range(0x12b2, 0x12b5), + ...range(0x12b8, 0x12be), + 0x12c0, + ...range(0x12c2, 0x12c5), + ...range(0x12c8, 0x12ce), + ...range(0x12d0, 0x12d6), + ...range(0x12d8, 0x12ee), + ...range(0x12f0, 0x130e), + 0x1310, + ...range(0x1312, 0x1315), + ...range(0x1318, 0x131e), + ...range(0x1320, 0x1346), + ...range(0x1348, 0x135a), + ...range(0x1361, 0x137c), + ...range(0x13a0, 0x13f4), + ...range(0x1401, 0x1676), + ...range(0x1681, 0x169a), + ...range(0x16a0, 0x16f0), + ...range(0x1700, 0x170c), + ...range(0x170e, 0x1711), + ...range(0x1720, 0x1731), + ...range(0x1735, 0x1736), + ...range(0x1740, 0x1751), + ...range(0x1760, 0x176c), + ...range(0x176e, 0x1770), + ...range(0x1780, 0x17b6), + ...range(0x17be, 0x17c5), + ...range(0x17c7, 0x17c8), + ...range(0x17d4, 0x17da), + 0x17dc, + ...range(0x17e0, 0x17e9), + ...range(0x1810, 0x1819), + ...range(0x1820, 0x1877), + ...range(0x1880, 0x18a8), + ...range(0x1e00, 0x1e9b), + ...range(0x1ea0, 0x1ef9), + ...range(0x1f00, 0x1f15), + ...range(0x1f18, 0x1f1d), + ...range(0x1f20, 0x1f45), + ...range(0x1f48, 0x1f4d), + ...range(0x1f50, 0x1f57), + 0x1f59, + 0x1f5b, + 0x1f5d, + ...range(0x1f5f, 0x1f7d), + ...range(0x1f80, 0x1fb4), + ...range(0x1fb6, 0x1fbc), + 0x1fbe, + ...range(0x1fc2, 0x1fc4), + ...range(0x1fc6, 0x1fcc), + ...range(0x1fd0, 0x1fd3), + ...range(0x1fd6, 0x1fdb), + ...range(0x1fe0, 0x1fec), + ...range(0x1ff2, 0x1ff4), + ...range(0x1ff6, 0x1ffc), + 0x200e, + 0x2071, + 0x207f, + 0x2102, + 0x2107, + ...range(0x210a, 0x2113), + 0x2115, + ...range(0x2119, 0x211d), + 0x2124, + 0x2126, + 0x2128, + ...range(0x212a, 0x212d), + ...range(0x212f, 0x2131), + ...range(0x2133, 0x2139), + ...range(0x213d, 0x213f), + ...range(0x2145, 0x2149), + ...range(0x2160, 0x2183), + ...range(0x2336, 0x237a), + 0x2395, + ...range(0x249c, 0x24e9), + ...range(0x3005, 0x3007), + ...range(0x3021, 0x3029), + ...range(0x3031, 0x3035), + ...range(0x3038, 0x303c), + ...range(0x3041, 0x3096), + ...range(0x309d, 0x309f), + ...range(0x30a1, 0x30fa), + ...range(0x30fc, 0x30ff), + ...range(0x3105, 0x312c), + ...range(0x3131, 0x318e), + ...range(0x3190, 0x31b7), + ...range(0x31f0, 0x321c), + ...range(0x3220, 0x3243), + ...range(0x3260, 0x327b), + ...range(0x327f, 0x32b0), + ...range(0x32c0, 0x32cb), + ...range(0x32d0, 0x32fe), + ...range(0x3300, 0x3376), + ...range(0x337b, 0x33dd), + ...range(0x33e0, 0x33fe), + ...range(0x3400, 0x4db5), + ...range(0x4e00, 0x9fa5), + ...range(0xa000, 0xa48c), + ...range(0xac00, 0xd7a3), + ...range(0xd800, 0xfa2d), + ...range(0xfa30, 0xfa6a), + ...range(0xfb00, 0xfb06), + ...range(0xfb13, 0xfb17), + ...range(0xff21, 0xff3a), + ...range(0xff41, 0xff5a), + ...range(0xff66, 0xffbe), + ...range(0xffc2, 0xffc7), + ...range(0xffca, 0xffcf), + ...range(0xffd2, 0xffd7), + ...range(0xffda, 0xffdc), + ...range(0x10300, 0x1031e), + ...range(0x10320, 0x10323), + ...range(0x10330, 0x1034a), + ...range(0x10400, 0x10425), + ...range(0x10428, 0x1044d), + ...range(0x1d000, 0x1d0f5), + ...range(0x1d100, 0x1d126), + ...range(0x1d12a, 0x1d166), + ...range(0x1d16a, 0x1d172), + ...range(0x1d183, 0x1d184), + ...range(0x1d18c, 0x1d1a9), + ...range(0x1d1ae, 0x1d1dd), + ...range(0x1d400, 0x1d454), + ...range(0x1d456, 0x1d49c), + ...range(0x1d49e, 0x1d49f), + 0x1d4a2, + ...range(0x1d4a5, 0x1d4a6), + ...range(0x1d4a9, 0x1d4ac), + ...range(0x1d4ae, 0x1d4b9), + 0x1d4bb, + ...range(0x1d4bd, 0x1d4c0), + ...range(0x1d4c2, 0x1d4c3), + ...range(0x1d4c5, 0x1d505), + ...range(0x1d507, 0x1d50a), + ...range(0x1d50d, 0x1d514), + ...range(0x1d516, 0x1d51c), + ...range(0x1d51e, 0x1d539), + ...range(0x1d53b, 0x1d53e), + ...range(0x1d540, 0x1d544), + 0x1d546, + ...range(0x1d54a, 0x1d550), + ...range(0x1d552, 0x1d6a3), + ...range(0x1d6a8, 0x1d7c9), + ...range(0x20000, 0x2a6d6), + ...range(0x2f800, 0x2fa1d), + ...range(0xf0000, 0xffffd), + ...range(0x100000, 0x10fffd), +]); + +module.exports = { + unassigned_code_points, + commonly_mapped_to_nothing, + non_ASCII_space_characters, + prohibited_characters, + bidirectional_r_al, + bidirectional_l, +}; diff --git a/ts-ticket-office-service/node_modules/saslprep/lib/memory-code-points.js b/ts-ticket-office-service/node_modules/saslprep/lib/memory-code-points.js new file mode 100644 index 000000000..cb0289c87 --- /dev/null +++ b/ts-ticket-office-service/node_modules/saslprep/lib/memory-code-points.js @@ -0,0 +1,39 @@ +'use strict'; + +const fs = require('fs'); +const path = require('path'); +const bitfield = require('sparse-bitfield'); + +/* eslint-disable-next-line security/detect-non-literal-fs-filename */ +const memory = fs.readFileSync(path.resolve(__dirname, '../code-points.mem')); +let offset = 0; + +/** + * Loads each code points sequence from buffer. + * @returns {bitfield} + */ +function read() { + const size = memory.readUInt32BE(offset); + offset += 4; + + const codepoints = memory.slice(offset, offset + size); + offset += size; + + return bitfield({ buffer: codepoints }); +} + +const unassigned_code_points = read(); +const commonly_mapped_to_nothing = read(); +const non_ASCII_space_characters = read(); +const prohibited_characters = read(); +const bidirectional_r_al = read(); +const bidirectional_l = read(); + +module.exports = { + unassigned_code_points, + commonly_mapped_to_nothing, + non_ASCII_space_characters, + prohibited_characters, + bidirectional_r_al, + bidirectional_l, +}; diff --git a/ts-ticket-office-service/node_modules/saslprep/lib/util.js b/ts-ticket-office-service/node_modules/saslprep/lib/util.js new file mode 100644 index 000000000..506bdc992 --- /dev/null +++ b/ts-ticket-office-service/node_modules/saslprep/lib/util.js @@ -0,0 +1,21 @@ +'use strict'; + +/** + * Create an array of numbers. + * @param {number} from + * @param {number} to + * @returns {number[]} + */ +function range(from, to) { + // TODO: make this inlined. + const list = new Array(to - from + 1); + + for (let i = 0; i < list.length; i += 1) { + list[i] = from + i; + } + return list; +} + +module.exports = { + range, +}; diff --git a/ts-ticket-office-service/node_modules/saslprep/package.json b/ts-ticket-office-service/node_modules/saslprep/package.json new file mode 100644 index 000000000..23c35627b --- /dev/null +++ b/ts-ticket-office-service/node_modules/saslprep/package.json @@ -0,0 +1,72 @@ +{ + "name": "saslprep", + "version": "1.0.3", + "description": "SASLprep: Stringprep Profile for User Names and Passwords, rfc4013.", + "main": "index.js", + "scripts": { + "test": "npm run lint && npm run unit-test", + "lint": "npx eslint --quiet .", + "unit-test": "npx jest", + "gen-code-points": "node generate-code-points.js > code-points.mem" + }, + "repository": { + "type": "git", + "url": "git+https://github.com/reklatsmasters/saslprep.git" + }, + "keywords": [ + "sasl", + "saslprep", + "stringprep", + "rfc4013", + "4013" + ], + "author": "Dmitry Tsvettsikh ", + "license": "MIT", + "bugs": { + "url": "https://github.com/reklatsmasters/saslprep/issues" + }, + "engines": { + "node": ">=6" + }, + "homepage": "https://github.com/reklatsmasters/saslprep#readme", + "devDependencies": { + "@nodertc/eslint-config": "^0.2.1", + "eslint": "^5.16.0", + "jest": "^23.6.0", + "prettier": "^1.14.3" + }, + "dependencies": { + "sparse-bitfield": "^3.0.3" + }, + "eslintConfig": { + "extends": "@nodertc", + "rules": { + "camelcase": "off", + "no-continue": "off" + }, + "overrides": [ + { + "files": [ + "test/*.js" + ], + "env": { + "jest": true + }, + "rules": { + "require-jsdoc": "off" + } + } + ] + }, + "jest": { + "modulePaths": [ + "" + ], + "testMatch": [ + "**/test/*.js" + ], + "testPathIgnorePatterns": [ + "/node_modules/" + ] + } +} diff --git a/ts-ticket-office-service/node_modules/saslprep/readme.md b/ts-ticket-office-service/node_modules/saslprep/readme.md new file mode 100644 index 000000000..8ff3d70d7 --- /dev/null +++ b/ts-ticket-office-service/node_modules/saslprep/readme.md @@ -0,0 +1,31 @@ +# saslprep +[![Build Status](https://travis-ci.org/reklatsmasters/saslprep.svg?branch=master)](https://travis-ci.org/reklatsmasters/saslprep) +[![npm](https://img.shields.io/npm/v/saslprep.svg)](https://npmjs.org/package/saslprep) +[![node](https://img.shields.io/node/v/saslprep.svg)](https://npmjs.org/package/saslprep) +[![license](https://img.shields.io/npm/l/saslprep.svg)](https://npmjs.org/package/saslprep) +[![downloads](https://img.shields.io/npm/dm/saslprep.svg)](https://npmjs.org/package/saslprep) + +Stringprep Profile for User Names and Passwords, [rfc4013](https://tools.ietf.org/html/rfc4013) + +### Usage + +```js +const saslprep = require('saslprep') + +saslprep('password\u00AD') // password +saslprep('password\u0007') // Error: prohibited character +``` + +### API + +##### `saslprep(input: String, opts: Options): String` + +Normalize user name or password. + +##### `Options.allowUnassigned: bool` + +A special behavior for unassigned code points, see https://tools.ietf.org/html/rfc4013#section-2.5. Disabled by default. + +## License + +MIT, 2017-2019 (c) Dmitriy Tsvettsikh diff --git a/ts-ticket-office-service/node_modules/saslprep/test/index.js b/ts-ticket-office-service/node_modules/saslprep/test/index.js new file mode 100644 index 000000000..80c71af5e --- /dev/null +++ b/ts-ticket-office-service/node_modules/saslprep/test/index.js @@ -0,0 +1,76 @@ +'use strict'; + +const saslprep = require('..'); + +const chr = String.fromCodePoint; + +test('should work with liatin letters', () => { + const str = 'user'; + expect(saslprep(str)).toEqual(str); +}); + +test('should work be case preserved', () => { + const str = 'USER'; + expect(saslprep(str)).toEqual(str); +}); + +test('should work with high code points (> U+FFFF)', () => { + const str = '\uD83D\uDE00'; + expect(saslprep(str, { allowUnassigned: true })).toEqual(str); +}); + +test('should remove `mapped to nothing` characters', () => { + expect(saslprep('I\u00ADX')).toEqual('IX'); +}); + +test('should replace `Non-ASCII space characters` with space', () => { + expect(saslprep('a\u00A0b')).toEqual('a\u0020b'); +}); + +test('should normalize as NFKC', () => { + expect(saslprep('\u00AA')).toEqual('a'); + expect(saslprep('\u2168')).toEqual('IX'); +}); + +test('should throws when prohibited characters', () => { + // C.2.1 ASCII control characters + expect(() => saslprep('a\u007Fb')).toThrow(); + + // C.2.2 Non-ASCII control characters + expect(() => saslprep('a\u06DDb')).toThrow(); + + // C.3 Private use + expect(() => saslprep('a\uE000b')).toThrow(); + + // C.4 Non-character code points + expect(() => saslprep(`a${chr(0x1fffe)}b`)).toThrow(); + + // C.5 Surrogate codes + expect(() => saslprep('a\uD800b')).toThrow(); + + // C.6 Inappropriate for plain text + expect(() => saslprep('a\uFFF9b')).toThrow(); + + // C.7 Inappropriate for canonical representation + expect(() => saslprep('a\u2FF0b')).toThrow(); + + // C.8 Change display properties or are deprecated + expect(() => saslprep('a\u200Eb')).toThrow(); + + // C.9 Tagging characters + expect(() => saslprep(`a${chr(0xe0001)}b`)).toThrow(); +}); + +test('should not containt RandALCat and LCat bidi', () => { + expect(() => saslprep('a\u06DD\u00AAb')).toThrow(); +}); + +test('RandALCat should be first and last', () => { + expect(() => saslprep('\u0627\u0031\u0628')).not.toThrow(); + expect(() => saslprep('\u0627\u0031')).toThrow(); +}); + +test('should handle unassigned code points', () => { + expect(() => saslprep('a\u0487')).toThrow(); + expect(() => saslprep('a\u0487', { allowUnassigned: true })).not.toThrow(); +}); diff --git a/ts-ticket-office-service/node_modules/saslprep/test/util.js b/ts-ticket-office-service/node_modules/saslprep/test/util.js new file mode 100644 index 000000000..355db3f85 --- /dev/null +++ b/ts-ticket-office-service/node_modules/saslprep/test/util.js @@ -0,0 +1,16 @@ +'use strict'; + +const { setFlagsFromString } = require('v8'); +const { range } = require('../lib/util'); + +// 984 by default. +setFlagsFromString('--stack_size=500'); + +test('should work', () => { + const list = range(1, 3); + expect(list).toEqual([1, 2, 3]); +}); + +test('should work for large ranges', () => { + expect(() => range(1, 1e6)).not.toThrow(); +}); diff --git a/ts-ticket-office-service/node_modules/semver/LICENSE b/ts-ticket-office-service/node_modules/semver/LICENSE deleted file mode 100644 index 19129e315..000000000 --- a/ts-ticket-office-service/node_modules/semver/LICENSE +++ /dev/null @@ -1,15 +0,0 @@ -The ISC License - -Copyright (c) Isaac Z. Schlueter and Contributors - -Permission to use, copy, modify, and/or distribute this software for any -purpose with or without fee is hereby granted, provided that the above -copyright notice and this permission notice appear in all copies. - -THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES -WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF -MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR -ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES -WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN -ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR -IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. diff --git a/ts-ticket-office-service/node_modules/semver/README.md b/ts-ticket-office-service/node_modules/semver/README.md deleted file mode 100644 index fd5151ab3..000000000 --- a/ts-ticket-office-service/node_modules/semver/README.md +++ /dev/null @@ -1,366 +0,0 @@ -semver(1) -- The semantic versioner for npm -=========================================== - -## Install - -```bash -npm install --save semver -```` - -## Usage - -As a node module: - -```js -const semver = require('semver') - -semver.valid('1.2.3') // '1.2.3' -semver.valid('a.b.c') // null -semver.clean(' =v1.2.3 ') // '1.2.3' -semver.satisfies('1.2.3', '1.x || >=2.5.0 || 5.0.0 - 7.2.3') // true -semver.gt('1.2.3', '9.8.7') // false -semver.lt('1.2.3', '9.8.7') // true -``` - -As a command-line utility: - -``` -$ semver -h - -SemVer 5.3.0 - -A JavaScript implementation of the http://semver.org/ specification -Copyright Isaac Z. Schlueter - -Usage: semver [options] [ [...]] -Prints valid versions sorted by SemVer precedence - -Options: --r --range - Print versions that match the specified range. - --i --increment [] - Increment a version by the specified level. Level can - be one of: major, minor, patch, premajor, preminor, - prepatch, or prerelease. Default level is 'patch'. - Only one version may be specified. - ---preid - Identifier to be used to prefix premajor, preminor, - prepatch or prerelease version increments. - --l --loose - Interpret versions and ranges loosely - -Program exits successfully if any valid version satisfies -all supplied ranges, and prints all satisfying versions. - -If no satisfying versions are found, then exits failure. - -Versions are printed in ascending order, so supplying -multiple versions to the utility will just sort them. -``` - -## Versions - -A "version" is described by the `v2.0.0` specification found at -. - -A leading `"="` or `"v"` character is stripped off and ignored. - -## Ranges - -A `version range` is a set of `comparators` which specify versions -that satisfy the range. - -A `comparator` is composed of an `operator` and a `version`. The set -of primitive `operators` is: - -* `<` Less than -* `<=` Less than or equal to -* `>` Greater than -* `>=` Greater than or equal to -* `=` Equal. If no operator is specified, then equality is assumed, - so this operator is optional, but MAY be included. - -For example, the comparator `>=1.2.7` would match the versions -`1.2.7`, `1.2.8`, `2.5.3`, and `1.3.9`, but not the versions `1.2.6` -or `1.1.0`. - -Comparators can be joined by whitespace to form a `comparator set`, -which is satisfied by the **intersection** of all of the comparators -it includes. - -A range is composed of one or more comparator sets, joined by `||`. A -version matches a range if and only if every comparator in at least -one of the `||`-separated comparator sets is satisfied by the version. - -For example, the range `>=1.2.7 <1.3.0` would match the versions -`1.2.7`, `1.2.8`, and `1.2.99`, but not the versions `1.2.6`, `1.3.0`, -or `1.1.0`. - -The range `1.2.7 || >=1.2.9 <2.0.0` would match the versions `1.2.7`, -`1.2.9`, and `1.4.6`, but not the versions `1.2.8` or `2.0.0`. - -### Prerelease Tags - -If a version has a prerelease tag (for example, `1.2.3-alpha.3`) then -it will only be allowed to satisfy comparator sets if at least one -comparator with the same `[major, minor, patch]` tuple also has a -prerelease tag. - -For example, the range `>1.2.3-alpha.3` would be allowed to match the -version `1.2.3-alpha.7`, but it would *not* be satisfied by -`3.4.5-alpha.9`, even though `3.4.5-alpha.9` is technically "greater -than" `1.2.3-alpha.3` according to the SemVer sort rules. The version -range only accepts prerelease tags on the `1.2.3` version. The -version `3.4.5` *would* satisfy the range, because it does not have a -prerelease flag, and `3.4.5` is greater than `1.2.3-alpha.7`. - -The purpose for this behavior is twofold. First, prerelease versions -frequently are updated very quickly, and contain many breaking changes -that are (by the author's design) not yet fit for public consumption. -Therefore, by default, they are excluded from range matching -semantics. - -Second, a user who has opted into using a prerelease version has -clearly indicated the intent to use *that specific* set of -alpha/beta/rc versions. By including a prerelease tag in the range, -the user is indicating that they are aware of the risk. However, it -is still not appropriate to assume that they have opted into taking a -similar risk on the *next* set of prerelease versions. - -#### Prerelease Identifiers - -The method `.inc` takes an additional `identifier` string argument that -will append the value of the string as a prerelease identifier: - -```javascript -semver.inc('1.2.3', 'prerelease', 'beta') -// '1.2.4-beta.0' -``` - -command-line example: - -```bash -$ semver 1.2.3 -i prerelease --preid beta -1.2.4-beta.0 -``` - -Which then can be used to increment further: - -```bash -$ semver 1.2.4-beta.0 -i prerelease -1.2.4-beta.1 -``` - -### Advanced Range Syntax - -Advanced range syntax desugars to primitive comparators in -deterministic ways. - -Advanced ranges may be combined in the same way as primitive -comparators using white space or `||`. - -#### Hyphen Ranges `X.Y.Z - A.B.C` - -Specifies an inclusive set. - -* `1.2.3 - 2.3.4` := `>=1.2.3 <=2.3.4` - -If a partial version is provided as the first version in the inclusive -range, then the missing pieces are replaced with zeroes. - -* `1.2 - 2.3.4` := `>=1.2.0 <=2.3.4` - -If a partial version is provided as the second version in the -inclusive range, then all versions that start with the supplied parts -of the tuple are accepted, but nothing that would be greater than the -provided tuple parts. - -* `1.2.3 - 2.3` := `>=1.2.3 <2.4.0` -* `1.2.3 - 2` := `>=1.2.3 <3.0.0` - -#### X-Ranges `1.2.x` `1.X` `1.2.*` `*` - -Any of `X`, `x`, or `*` may be used to "stand in" for one of the -numeric values in the `[major, minor, patch]` tuple. - -* `*` := `>=0.0.0` (Any version satisfies) -* `1.x` := `>=1.0.0 <2.0.0` (Matching major version) -* `1.2.x` := `>=1.2.0 <1.3.0` (Matching major and minor versions) - -A partial version range is treated as an X-Range, so the special -character is in fact optional. - -* `""` (empty string) := `*` := `>=0.0.0` -* `1` := `1.x.x` := `>=1.0.0 <2.0.0` -* `1.2` := `1.2.x` := `>=1.2.0 <1.3.0` - -#### Tilde Ranges `~1.2.3` `~1.2` `~1` - -Allows patch-level changes if a minor version is specified on the -comparator. Allows minor-level changes if not. - -* `~1.2.3` := `>=1.2.3 <1.(2+1).0` := `>=1.2.3 <1.3.0` -* `~1.2` := `>=1.2.0 <1.(2+1).0` := `>=1.2.0 <1.3.0` (Same as `1.2.x`) -* `~1` := `>=1.0.0 <(1+1).0.0` := `>=1.0.0 <2.0.0` (Same as `1.x`) -* `~0.2.3` := `>=0.2.3 <0.(2+1).0` := `>=0.2.3 <0.3.0` -* `~0.2` := `>=0.2.0 <0.(2+1).0` := `>=0.2.0 <0.3.0` (Same as `0.2.x`) -* `~0` := `>=0.0.0 <(0+1).0.0` := `>=0.0.0 <1.0.0` (Same as `0.x`) -* `~1.2.3-beta.2` := `>=1.2.3-beta.2 <1.3.0` Note that prereleases in - the `1.2.3` version will be allowed, if they are greater than or - equal to `beta.2`. So, `1.2.3-beta.4` would be allowed, but - `1.2.4-beta.2` would not, because it is a prerelease of a - different `[major, minor, patch]` tuple. - -#### Caret Ranges `^1.2.3` `^0.2.5` `^0.0.4` - -Allows changes that do not modify the left-most non-zero digit in the -`[major, minor, patch]` tuple. In other words, this allows patch and -minor updates for versions `1.0.0` and above, patch updates for -versions `0.X >=0.1.0`, and *no* updates for versions `0.0.X`. - -Many authors treat a `0.x` version as if the `x` were the major -"breaking-change" indicator. - -Caret ranges are ideal when an author may make breaking changes -between `0.2.4` and `0.3.0` releases, which is a common practice. -However, it presumes that there will *not* be breaking changes between -`0.2.4` and `0.2.5`. It allows for changes that are presumed to be -additive (but non-breaking), according to commonly observed practices. - -* `^1.2.3` := `>=1.2.3 <2.0.0` -* `^0.2.3` := `>=0.2.3 <0.3.0` -* `^0.0.3` := `>=0.0.3 <0.0.4` -* `^1.2.3-beta.2` := `>=1.2.3-beta.2 <2.0.0` Note that prereleases in - the `1.2.3` version will be allowed, if they are greater than or - equal to `beta.2`. So, `1.2.3-beta.4` would be allowed, but - `1.2.4-beta.2` would not, because it is a prerelease of a - different `[major, minor, patch]` tuple. -* `^0.0.3-beta` := `>=0.0.3-beta <0.0.4` Note that prereleases in the - `0.0.3` version *only* will be allowed, if they are greater than or - equal to `beta`. So, `0.0.3-pr.2` would be allowed. - -When parsing caret ranges, a missing `patch` value desugars to the -number `0`, but will allow flexibility within that value, even if the -major and minor versions are both `0`. - -* `^1.2.x` := `>=1.2.0 <2.0.0` -* `^0.0.x` := `>=0.0.0 <0.1.0` -* `^0.0` := `>=0.0.0 <0.1.0` - -A missing `minor` and `patch` values will desugar to zero, but also -allow flexibility within those values, even if the major version is -zero. - -* `^1.x` := `>=1.0.0 <2.0.0` -* `^0.x` := `>=0.0.0 <1.0.0` - -### Range Grammar - -Putting all this together, here is a Backus-Naur grammar for ranges, -for the benefit of parser authors: - -```bnf -range-set ::= range ( logical-or range ) * -logical-or ::= ( ' ' ) * '||' ( ' ' ) * -range ::= hyphen | simple ( ' ' simple ) * | '' -hyphen ::= partial ' - ' partial -simple ::= primitive | partial | tilde | caret -primitive ::= ( '<' | '>' | '>=' | '<=' | '=' | ) partial -partial ::= xr ( '.' xr ( '.' xr qualifier ? )? )? -xr ::= 'x' | 'X' | '*' | nr -nr ::= '0' | ['1'-'9'] ( ['0'-'9'] ) * -tilde ::= '~' partial -caret ::= '^' partial -qualifier ::= ( '-' pre )? ( '+' build )? -pre ::= parts -build ::= parts -parts ::= part ( '.' part ) * -part ::= nr | [-0-9A-Za-z]+ -``` - -## Functions - -All methods and classes take a final `loose` boolean argument that, if -true, will be more forgiving about not-quite-valid semver strings. -The resulting output will always be 100% strict, of course. - -Strict-mode Comparators and Ranges will be strict about the SemVer -strings that they parse. - -* `valid(v)`: Return the parsed version, or null if it's not valid. -* `inc(v, release)`: Return the version incremented by the release - type (`major`, `premajor`, `minor`, `preminor`, `patch`, - `prepatch`, or `prerelease`), or null if it's not valid - * `premajor` in one call will bump the version up to the next major - version and down to a prerelease of that major version. - `preminor`, and `prepatch` work the same way. - * If called from a non-prerelease version, the `prerelease` will work the - same as `prepatch`. It increments the patch version, then makes a - prerelease. If the input version is already a prerelease it simply - increments it. -* `prerelease(v)`: Returns an array of prerelease components, or null - if none exist. Example: `prerelease('1.2.3-alpha.1') -> ['alpha', 1]` -* `major(v)`: Return the major version number. -* `minor(v)`: Return the minor version number. -* `patch(v)`: Return the patch version number. -* `intersects(r1, r2, loose)`: Return true if the two supplied ranges - or comparators intersect. - -### Comparison - -* `gt(v1, v2)`: `v1 > v2` -* `gte(v1, v2)`: `v1 >= v2` -* `lt(v1, v2)`: `v1 < v2` -* `lte(v1, v2)`: `v1 <= v2` -* `eq(v1, v2)`: `v1 == v2` This is true if they're logically equivalent, - even if they're not the exact same string. You already know how to - compare strings. -* `neq(v1, v2)`: `v1 != v2` The opposite of `eq`. -* `cmp(v1, comparator, v2)`: Pass in a comparison string, and it'll call - the corresponding function above. `"==="` and `"!=="` do simple - string comparison, but are included for completeness. Throws if an - invalid comparison string is provided. -* `compare(v1, v2)`: Return `0` if `v1 == v2`, or `1` if `v1` is greater, or `-1` if - `v2` is greater. Sorts in ascending order if passed to `Array.sort()`. -* `rcompare(v1, v2)`: The reverse of compare. Sorts an array of versions - in descending order when passed to `Array.sort()`. -* `diff(v1, v2)`: Returns difference between two versions by the release type - (`major`, `premajor`, `minor`, `preminor`, `patch`, `prepatch`, or `prerelease`), - or null if the versions are the same. - -### Comparators - -* `intersects(comparator)`: Return true if the comparators intersect - -### Ranges - -* `validRange(range)`: Return the valid range or null if it's not valid -* `satisfies(version, range)`: Return true if the version satisfies the - range. -* `maxSatisfying(versions, range)`: Return the highest version in the list - that satisfies the range, or `null` if none of them do. -* `minSatisfying(versions, range)`: Return the lowest version in the list - that satisfies the range, or `null` if none of them do. -* `gtr(version, range)`: Return `true` if version is greater than all the - versions possible in the range. -* `ltr(version, range)`: Return `true` if version is less than all the - versions possible in the range. -* `outside(version, range, hilo)`: Return true if the version is outside - the bounds of the range in either the high or low direction. The - `hilo` argument must be either the string `'>'` or `'<'`. (This is - the function called by `gtr` and `ltr`.) -* `intersects(range)`: Return true if any of the ranges comparators intersect - -Note that, since ranges may be non-contiguous, a version might not be -greater than a range, less than a range, *or* satisfy a range! For -example, the range `1.2 <1.2.9 || >2.0.0` would have a hole from `1.2.9` -until `2.0.0`, so the version `1.2.10` would not be greater than the -range (because `2.0.1` satisfies, which is higher), nor less than the -range (since `1.2.8` satisfies, which is lower), and it also does not -satisfy the range. - -If you want to know if a version satisfies or does not satisfy a -range, use the `satisfies(version, range)` function. diff --git a/ts-ticket-office-service/node_modules/semver/bin/semver b/ts-ticket-office-service/node_modules/semver/bin/semver deleted file mode 100644 index c5f2e857e..000000000 --- a/ts-ticket-office-service/node_modules/semver/bin/semver +++ /dev/null @@ -1,133 +0,0 @@ -#!/usr/bin/env node -// Standalone semver comparison program. -// Exits successfully and prints matching version(s) if -// any supplied version is valid and passes all tests. - -var argv = process.argv.slice(2) - , versions = [] - , range = [] - , gt = [] - , lt = [] - , eq = [] - , inc = null - , version = require("../package.json").version - , loose = false - , identifier = undefined - , semver = require("../semver") - , reverse = false - -main() - -function main () { - if (!argv.length) return help() - while (argv.length) { - var a = argv.shift() - var i = a.indexOf('=') - if (i !== -1) { - a = a.slice(0, i) - argv.unshift(a.slice(i + 1)) - } - switch (a) { - case "-rv": case "-rev": case "--rev": case "--reverse": - reverse = true - break - case "-l": case "--loose": - loose = true - break - case "-v": case "--version": - versions.push(argv.shift()) - break - case "-i": case "--inc": case "--increment": - switch (argv[0]) { - case "major": case "minor": case "patch": case "prerelease": - case "premajor": case "preminor": case "prepatch": - inc = argv.shift() - break - default: - inc = "patch" - break - } - break - case "--preid": - identifier = argv.shift() - break - case "-r": case "--range": - range.push(argv.shift()) - break - case "-h": case "--help": case "-?": - return help() - default: - versions.push(a) - break - } - } - - versions = versions.filter(function (v) { - return semver.valid(v, loose) - }) - if (!versions.length) return fail() - if (inc && (versions.length !== 1 || range.length)) - return failInc() - - for (var i = 0, l = range.length; i < l ; i ++) { - versions = versions.filter(function (v) { - return semver.satisfies(v, range[i], loose) - }) - if (!versions.length) return fail() - } - return success(versions) -} - -function failInc () { - console.error("--inc can only be used on a single version with no range") - fail() -} - -function fail () { process.exit(1) } - -function success () { - var compare = reverse ? "rcompare" : "compare" - versions.sort(function (a, b) { - return semver[compare](a, b, loose) - }).map(function (v) { - return semver.clean(v, loose) - }).map(function (v) { - return inc ? semver.inc(v, inc, loose, identifier) : v - }).forEach(function (v,i,_) { console.log(v) }) -} - -function help () { - console.log(["SemVer " + version - ,"" - ,"A JavaScript implementation of the http://semver.org/ specification" - ,"Copyright Isaac Z. Schlueter" - ,"" - ,"Usage: semver [options] [ [...]]" - ,"Prints valid versions sorted by SemVer precedence" - ,"" - ,"Options:" - ,"-r --range " - ," Print versions that match the specified range." - ,"" - ,"-i --increment []" - ," Increment a version by the specified level. Level can" - ," be one of: major, minor, patch, premajor, preminor," - ," prepatch, or prerelease. Default level is 'patch'." - ," Only one version may be specified." - ,"" - ,"--preid " - ," Identifier to be used to prefix premajor, preminor," - ," prepatch or prerelease version increments." - ,"" - ,"-l --loose" - ," Interpret versions and ranges loosely" - ,"" - ,"Program exits successfully if any valid version satisfies" - ,"all supplied ranges, and prints all satisfying versions." - ,"" - ,"If no satisfying versions are found, then exits failure." - ,"" - ,"Versions are printed in ascending order, so supplying" - ,"multiple versions to the utility will just sort them." - ].join("\n")) -} diff --git a/ts-ticket-office-service/node_modules/semver/package.json b/ts-ticket-office-service/node_modules/semver/package.json deleted file mode 100644 index 1706a4af0..000000000 --- a/ts-ticket-office-service/node_modules/semver/package.json +++ /dev/null @@ -1,95 +0,0 @@ -{ - "_args": [ - [ - { - "raw": "semver@^5.1.0", - "scope": null, - "escapedName": "semver", - "name": "semver", - "rawSpec": "^5.1.0", - "spec": ">=5.1.0 <6.0.0", - "type": "range" - }, - "F:\\gitwork\\workspace_microservices\\ts-ticket-office-service\\node_modules\\require_optional" - ] - ], - "_from": "semver@>=5.1.0 <6.0.0", - "_id": "semver@5.4.1", - "_inCache": true, - "_location": "/semver", - "_nodeVersion": "8.2.1", - "_npmOperationalInternal": { - "host": "s3://npm-registry-packages", - "tmp": "tmp/semver-5.4.1.tgz_1500922107643_0.5125251261051744" - }, - "_npmUser": { - "name": "isaacs", - "email": "i@izs.me" - }, - "_npmVersion": "5.3.0", - "_phantomChildren": {}, - "_requested": { - "raw": "semver@^5.1.0", - "scope": null, - "escapedName": "semver", - "name": "semver", - "rawSpec": "^5.1.0", - "spec": ">=5.1.0 <6.0.0", - "type": "range" - }, - "_requiredBy": [ - "/require_optional" - ], - "_resolved": "https://registry.npmjs.org/semver/-/semver-5.4.1.tgz", - "_shasum": "e059c09d8571f0540823733433505d3a2f00b18e", - "_shrinkwrap": null, - "_spec": "semver@^5.1.0", - "_where": "F:\\gitwork\\workspace_microservices\\ts-ticket-office-service\\node_modules\\require_optional", - "bin": { - "semver": "./bin/semver" - }, - "bugs": { - "url": "https://github.com/npm/node-semver/issues" - }, - "dependencies": {}, - "description": "The semantic version parser used by npm.", - "devDependencies": { - "tap": "^10.7.0" - }, - "directories": {}, - "dist": { - "integrity": "sha512-WfG/X9+oATh81XtllIo/I8gOiY9EXRdv1cQdyykeXK17YcUW3EXUAi2To4pcH6nZtJPr7ZOpM5OMyWJZm+8Rsg==", - "shasum": "e059c09d8571f0540823733433505d3a2f00b18e", - "tarball": "https://registry.npmjs.org/semver/-/semver-5.4.1.tgz" - }, - "files": [ - "bin", - "range.bnf", - "semver.js" - ], - "gitHead": "0877c942a6af00edcda5c16fdd934684e1b20a1c", - "homepage": "https://github.com/npm/node-semver#readme", - "license": "ISC", - "main": "semver.js", - "maintainers": [ - { - "name": "isaacs", - "email": "i@izs.me" - }, - { - "name": "othiym23", - "email": "ogd@aoaioxxysz.net" - } - ], - "name": "semver", - "optionalDependencies": {}, - "readme": "ERROR: No README data found!", - "repository": { - "type": "git", - "url": "git+https://github.com/npm/node-semver.git" - }, - "scripts": { - "test": "tap test/*.js --cov -J" - }, - "version": "5.4.1" -} diff --git a/ts-ticket-office-service/node_modules/semver/range.bnf b/ts-ticket-office-service/node_modules/semver/range.bnf deleted file mode 100644 index 25ebd5c83..000000000 --- a/ts-ticket-office-service/node_modules/semver/range.bnf +++ /dev/null @@ -1,16 +0,0 @@ -range-set ::= range ( logical-or range ) * -logical-or ::= ( ' ' ) * '||' ( ' ' ) * -range ::= hyphen | simple ( ' ' simple ) * | '' -hyphen ::= partial ' - ' partial -simple ::= primitive | partial | tilde | caret -primitive ::= ( '<' | '>' | '>=' | '<=' | '=' | ) partial -partial ::= xr ( '.' xr ( '.' xr qualifier ? )? )? -xr ::= 'x' | 'X' | '*' | nr -nr ::= '0' | ['1'-'9'] ( ['0'-'9'] ) * -tilde ::= '~' partial -caret ::= '^' partial -qualifier ::= ( '-' pre )? ( '+' build )? -pre ::= parts -build ::= parts -parts ::= part ( '.' part ) * -part ::= nr | [-0-9A-Za-z]+ diff --git a/ts-ticket-office-service/node_modules/semver/semver.js b/ts-ticket-office-service/node_modules/semver/semver.js deleted file mode 100644 index 389cb4467..000000000 --- a/ts-ticket-office-service/node_modules/semver/semver.js +++ /dev/null @@ -1,1296 +0,0 @@ -exports = module.exports = SemVer; - -// The debug function is excluded entirely from the minified version. -/* nomin */ var debug; -/* nomin */ if (typeof process === 'object' && - /* nomin */ process.env && - /* nomin */ process.env.NODE_DEBUG && - /* nomin */ /\bsemver\b/i.test(process.env.NODE_DEBUG)) - /* nomin */ debug = function() { - /* nomin */ var args = Array.prototype.slice.call(arguments, 0); - /* nomin */ args.unshift('SEMVER'); - /* nomin */ console.log.apply(console, args); - /* nomin */ }; -/* nomin */ else - /* nomin */ debug = function() {}; - -// Note: this is the semver.org version of the spec that it implements -// Not necessarily the package version of this code. -exports.SEMVER_SPEC_VERSION = '2.0.0'; - -var MAX_LENGTH = 256; -var MAX_SAFE_INTEGER = Number.MAX_SAFE_INTEGER || 9007199254740991; - -// The actual regexps go on exports.re -var re = exports.re = []; -var src = exports.src = []; -var R = 0; - -// The following Regular Expressions can be used for tokenizing, -// validating, and parsing SemVer version strings. - -// ## Numeric Identifier -// A single `0`, or a non-zero digit followed by zero or more digits. - -var NUMERICIDENTIFIER = R++; -src[NUMERICIDENTIFIER] = '0|[1-9]\\d*'; -var NUMERICIDENTIFIERLOOSE = R++; -src[NUMERICIDENTIFIERLOOSE] = '[0-9]+'; - - -// ## Non-numeric Identifier -// Zero or more digits, followed by a letter or hyphen, and then zero or -// more letters, digits, or hyphens. - -var NONNUMERICIDENTIFIER = R++; -src[NONNUMERICIDENTIFIER] = '\\d*[a-zA-Z-][a-zA-Z0-9-]*'; - - -// ## Main Version -// Three dot-separated numeric identifiers. - -var MAINVERSION = R++; -src[MAINVERSION] = '(' + src[NUMERICIDENTIFIER] + ')\\.' + - '(' + src[NUMERICIDENTIFIER] + ')\\.' + - '(' + src[NUMERICIDENTIFIER] + ')'; - -var MAINVERSIONLOOSE = R++; -src[MAINVERSIONLOOSE] = '(' + src[NUMERICIDENTIFIERLOOSE] + ')\\.' + - '(' + src[NUMERICIDENTIFIERLOOSE] + ')\\.' + - '(' + src[NUMERICIDENTIFIERLOOSE] + ')'; - -// ## Pre-release Version Identifier -// A numeric identifier, or a non-numeric identifier. - -var PRERELEASEIDENTIFIER = R++; -src[PRERELEASEIDENTIFIER] = '(?:' + src[NUMERICIDENTIFIER] + - '|' + src[NONNUMERICIDENTIFIER] + ')'; - -var PRERELEASEIDENTIFIERLOOSE = R++; -src[PRERELEASEIDENTIFIERLOOSE] = '(?:' + src[NUMERICIDENTIFIERLOOSE] + - '|' + src[NONNUMERICIDENTIFIER] + ')'; - - -// ## Pre-release Version -// Hyphen, followed by one or more dot-separated pre-release version -// identifiers. - -var PRERELEASE = R++; -src[PRERELEASE] = '(?:-(' + src[PRERELEASEIDENTIFIER] + - '(?:\\.' + src[PRERELEASEIDENTIFIER] + ')*))'; - -var PRERELEASELOOSE = R++; -src[PRERELEASELOOSE] = '(?:-?(' + src[PRERELEASEIDENTIFIERLOOSE] + - '(?:\\.' + src[PRERELEASEIDENTIFIERLOOSE] + ')*))'; - -// ## Build Metadata Identifier -// Any combination of digits, letters, or hyphens. - -var BUILDIDENTIFIER = R++; -src[BUILDIDENTIFIER] = '[0-9A-Za-z-]+'; - -// ## Build Metadata -// Plus sign, followed by one or more period-separated build metadata -// identifiers. - -var BUILD = R++; -src[BUILD] = '(?:\\+(' + src[BUILDIDENTIFIER] + - '(?:\\.' + src[BUILDIDENTIFIER] + ')*))'; - - -// ## Full Version String -// A main version, followed optionally by a pre-release version and -// build metadata. - -// Note that the only major, minor, patch, and pre-release sections of -// the version string are capturing groups. The build metadata is not a -// capturing group, because it should not ever be used in version -// comparison. - -var FULL = R++; -var FULLPLAIN = 'v?' + src[MAINVERSION] + - src[PRERELEASE] + '?' + - src[BUILD] + '?'; - -src[FULL] = '^' + FULLPLAIN + '$'; - -// like full, but allows v1.2.3 and =1.2.3, which people do sometimes. -// also, 1.0.0alpha1 (prerelease without the hyphen) which is pretty -// common in the npm registry. -var LOOSEPLAIN = '[v=\\s]*' + src[MAINVERSIONLOOSE] + - src[PRERELEASELOOSE] + '?' + - src[BUILD] + '?'; - -var LOOSE = R++; -src[LOOSE] = '^' + LOOSEPLAIN + '$'; - -var GTLT = R++; -src[GTLT] = '((?:<|>)?=?)'; - -// Something like "2.*" or "1.2.x". -// Note that "x.x" is a valid xRange identifer, meaning "any version" -// Only the first item is strictly required. -var XRANGEIDENTIFIERLOOSE = R++; -src[XRANGEIDENTIFIERLOOSE] = src[NUMERICIDENTIFIERLOOSE] + '|x|X|\\*'; -var XRANGEIDENTIFIER = R++; -src[XRANGEIDENTIFIER] = src[NUMERICIDENTIFIER] + '|x|X|\\*'; - -var XRANGEPLAIN = R++; -src[XRANGEPLAIN] = '[v=\\s]*(' + src[XRANGEIDENTIFIER] + ')' + - '(?:\\.(' + src[XRANGEIDENTIFIER] + ')' + - '(?:\\.(' + src[XRANGEIDENTIFIER] + ')' + - '(?:' + src[PRERELEASE] + ')?' + - src[BUILD] + '?' + - ')?)?'; - -var XRANGEPLAINLOOSE = R++; -src[XRANGEPLAINLOOSE] = '[v=\\s]*(' + src[XRANGEIDENTIFIERLOOSE] + ')' + - '(?:\\.(' + src[XRANGEIDENTIFIERLOOSE] + ')' + - '(?:\\.(' + src[XRANGEIDENTIFIERLOOSE] + ')' + - '(?:' + src[PRERELEASELOOSE] + ')?' + - src[BUILD] + '?' + - ')?)?'; - -var XRANGE = R++; -src[XRANGE] = '^' + src[GTLT] + '\\s*' + src[XRANGEPLAIN] + '$'; -var XRANGELOOSE = R++; -src[XRANGELOOSE] = '^' + src[GTLT] + '\\s*' + src[XRANGEPLAINLOOSE] + '$'; - -// Tilde ranges. -// Meaning is "reasonably at or greater than" -var LONETILDE = R++; -src[LONETILDE] = '(?:~>?)'; - -var TILDETRIM = R++; -src[TILDETRIM] = '(\\s*)' + src[LONETILDE] + '\\s+'; -re[TILDETRIM] = new RegExp(src[TILDETRIM], 'g'); -var tildeTrimReplace = '$1~'; - -var TILDE = R++; -src[TILDE] = '^' + src[LONETILDE] + src[XRANGEPLAIN] + '$'; -var TILDELOOSE = R++; -src[TILDELOOSE] = '^' + src[LONETILDE] + src[XRANGEPLAINLOOSE] + '$'; - -// Caret ranges. -// Meaning is "at least and backwards compatible with" -var LONECARET = R++; -src[LONECARET] = '(?:\\^)'; - -var CARETTRIM = R++; -src[CARETTRIM] = '(\\s*)' + src[LONECARET] + '\\s+'; -re[CARETTRIM] = new RegExp(src[CARETTRIM], 'g'); -var caretTrimReplace = '$1^'; - -var CARET = R++; -src[CARET] = '^' + src[LONECARET] + src[XRANGEPLAIN] + '$'; -var CARETLOOSE = R++; -src[CARETLOOSE] = '^' + src[LONECARET] + src[XRANGEPLAINLOOSE] + '$'; - -// A simple gt/lt/eq thing, or just "" to indicate "any version" -var COMPARATORLOOSE = R++; -src[COMPARATORLOOSE] = '^' + src[GTLT] + '\\s*(' + LOOSEPLAIN + ')$|^$'; -var COMPARATOR = R++; -src[COMPARATOR] = '^' + src[GTLT] + '\\s*(' + FULLPLAIN + ')$|^$'; - - -// An expression to strip any whitespace between the gtlt and the thing -// it modifies, so that `> 1.2.3` ==> `>1.2.3` -var COMPARATORTRIM = R++; -src[COMPARATORTRIM] = '(\\s*)' + src[GTLT] + - '\\s*(' + LOOSEPLAIN + '|' + src[XRANGEPLAIN] + ')'; - -// this one has to use the /g flag -re[COMPARATORTRIM] = new RegExp(src[COMPARATORTRIM], 'g'); -var comparatorTrimReplace = '$1$2$3'; - - -// Something like `1.2.3 - 1.2.4` -// Note that these all use the loose form, because they'll be -// checked against either the strict or loose comparator form -// later. -var HYPHENRANGE = R++; -src[HYPHENRANGE] = '^\\s*(' + src[XRANGEPLAIN] + ')' + - '\\s+-\\s+' + - '(' + src[XRANGEPLAIN] + ')' + - '\\s*$'; - -var HYPHENRANGELOOSE = R++; -src[HYPHENRANGELOOSE] = '^\\s*(' + src[XRANGEPLAINLOOSE] + ')' + - '\\s+-\\s+' + - '(' + src[XRANGEPLAINLOOSE] + ')' + - '\\s*$'; - -// Star ranges basically just allow anything at all. -var STAR = R++; -src[STAR] = '(<|>)?=?\\s*\\*'; - -// Compile to actual regexp objects. -// All are flag-free, unless they were created above with a flag. -for (var i = 0; i < R; i++) { - debug(i, src[i]); - if (!re[i]) - re[i] = new RegExp(src[i]); -} - -exports.parse = parse; -function parse(version, loose) { - if (version instanceof SemVer) - return version; - - if (typeof version !== 'string') - return null; - - if (version.length > MAX_LENGTH) - return null; - - var r = loose ? re[LOOSE] : re[FULL]; - if (!r.test(version)) - return null; - - try { - return new SemVer(version, loose); - } catch (er) { - return null; - } -} - -exports.valid = valid; -function valid(version, loose) { - var v = parse(version, loose); - return v ? v.version : null; -} - - -exports.clean = clean; -function clean(version, loose) { - var s = parse(version.trim().replace(/^[=v]+/, ''), loose); - return s ? s.version : null; -} - -exports.SemVer = SemVer; - -function SemVer(version, loose) { - if (version instanceof SemVer) { - if (version.loose === loose) - return version; - else - version = version.version; - } else if (typeof version !== 'string') { - throw new TypeError('Invalid Version: ' + version); - } - - if (version.length > MAX_LENGTH) - throw new TypeError('version is longer than ' + MAX_LENGTH + ' characters') - - if (!(this instanceof SemVer)) - return new SemVer(version, loose); - - debug('SemVer', version, loose); - this.loose = loose; - var m = version.trim().match(loose ? re[LOOSE] : re[FULL]); - - if (!m) - throw new TypeError('Invalid Version: ' + version); - - this.raw = version; - - // these are actually numbers - this.major = +m[1]; - this.minor = +m[2]; - this.patch = +m[3]; - - if (this.major > MAX_SAFE_INTEGER || this.major < 0) - throw new TypeError('Invalid major version') - - if (this.minor > MAX_SAFE_INTEGER || this.minor < 0) - throw new TypeError('Invalid minor version') - - if (this.patch > MAX_SAFE_INTEGER || this.patch < 0) - throw new TypeError('Invalid patch version') - - // numberify any prerelease numeric ids - if (!m[4]) - this.prerelease = []; - else - this.prerelease = m[4].split('.').map(function(id) { - if (/^[0-9]+$/.test(id)) { - var num = +id; - if (num >= 0 && num < MAX_SAFE_INTEGER) - return num; - } - return id; - }); - - this.build = m[5] ? m[5].split('.') : []; - this.format(); -} - -SemVer.prototype.format = function() { - this.version = this.major + '.' + this.minor + '.' + this.patch; - if (this.prerelease.length) - this.version += '-' + this.prerelease.join('.'); - return this.version; -}; - -SemVer.prototype.toString = function() { - return this.version; -}; - -SemVer.prototype.compare = function(other) { - debug('SemVer.compare', this.version, this.loose, other); - if (!(other instanceof SemVer)) - other = new SemVer(other, this.loose); - - return this.compareMain(other) || this.comparePre(other); -}; - -SemVer.prototype.compareMain = function(other) { - if (!(other instanceof SemVer)) - other = new SemVer(other, this.loose); - - return compareIdentifiers(this.major, other.major) || - compareIdentifiers(this.minor, other.minor) || - compareIdentifiers(this.patch, other.patch); -}; - -SemVer.prototype.comparePre = function(other) { - if (!(other instanceof SemVer)) - other = new SemVer(other, this.loose); - - // NOT having a prerelease is > having one - if (this.prerelease.length && !other.prerelease.length) - return -1; - else if (!this.prerelease.length && other.prerelease.length) - return 1; - else if (!this.prerelease.length && !other.prerelease.length) - return 0; - - var i = 0; - do { - var a = this.prerelease[i]; - var b = other.prerelease[i]; - debug('prerelease compare', i, a, b); - if (a === undefined && b === undefined) - return 0; - else if (b === undefined) - return 1; - else if (a === undefined) - return -1; - else if (a === b) - continue; - else - return compareIdentifiers(a, b); - } while (++i); -}; - -// preminor will bump the version up to the next minor release, and immediately -// down to pre-release. premajor and prepatch work the same way. -SemVer.prototype.inc = function(release, identifier) { - switch (release) { - case 'premajor': - this.prerelease.length = 0; - this.patch = 0; - this.minor = 0; - this.major++; - this.inc('pre', identifier); - break; - case 'preminor': - this.prerelease.length = 0; - this.patch = 0; - this.minor++; - this.inc('pre', identifier); - break; - case 'prepatch': - // If this is already a prerelease, it will bump to the next version - // drop any prereleases that might already exist, since they are not - // relevant at this point. - this.prerelease.length = 0; - this.inc('patch', identifier); - this.inc('pre', identifier); - break; - // If the input is a non-prerelease version, this acts the same as - // prepatch. - case 'prerelease': - if (this.prerelease.length === 0) - this.inc('patch', identifier); - this.inc('pre', identifier); - break; - - case 'major': - // If this is a pre-major version, bump up to the same major version. - // Otherwise increment major. - // 1.0.0-5 bumps to 1.0.0 - // 1.1.0 bumps to 2.0.0 - if (this.minor !== 0 || this.patch !== 0 || this.prerelease.length === 0) - this.major++; - this.minor = 0; - this.patch = 0; - this.prerelease = []; - break; - case 'minor': - // If this is a pre-minor version, bump up to the same minor version. - // Otherwise increment minor. - // 1.2.0-5 bumps to 1.2.0 - // 1.2.1 bumps to 1.3.0 - if (this.patch !== 0 || this.prerelease.length === 0) - this.minor++; - this.patch = 0; - this.prerelease = []; - break; - case 'patch': - // If this is not a pre-release version, it will increment the patch. - // If it is a pre-release it will bump up to the same patch version. - // 1.2.0-5 patches to 1.2.0 - // 1.2.0 patches to 1.2.1 - if (this.prerelease.length === 0) - this.patch++; - this.prerelease = []; - break; - // This probably shouldn't be used publicly. - // 1.0.0 "pre" would become 1.0.0-0 which is the wrong direction. - case 'pre': - if (this.prerelease.length === 0) - this.prerelease = [0]; - else { - var i = this.prerelease.length; - while (--i >= 0) { - if (typeof this.prerelease[i] === 'number') { - this.prerelease[i]++; - i = -2; - } - } - if (i === -1) // didn't increment anything - this.prerelease.push(0); - } - if (identifier) { - // 1.2.0-beta.1 bumps to 1.2.0-beta.2, - // 1.2.0-beta.fooblz or 1.2.0-beta bumps to 1.2.0-beta.0 - if (this.prerelease[0] === identifier) { - if (isNaN(this.prerelease[1])) - this.prerelease = [identifier, 0]; - } else - this.prerelease = [identifier, 0]; - } - break; - - default: - throw new Error('invalid increment argument: ' + release); - } - this.format(); - this.raw = this.version; - return this; -}; - -exports.inc = inc; -function inc(version, release, loose, identifier) { - if (typeof(loose) === 'string') { - identifier = loose; - loose = undefined; - } - - try { - return new SemVer(version, loose).inc(release, identifier).version; - } catch (er) { - return null; - } -} - -exports.diff = diff; -function diff(version1, version2) { - if (eq(version1, version2)) { - return null; - } else { - var v1 = parse(version1); - var v2 = parse(version2); - if (v1.prerelease.length || v2.prerelease.length) { - for (var key in v1) { - if (key === 'major' || key === 'minor' || key === 'patch') { - if (v1[key] !== v2[key]) { - return 'pre'+key; - } - } - } - return 'prerelease'; - } - for (var key in v1) { - if (key === 'major' || key === 'minor' || key === 'patch') { - if (v1[key] !== v2[key]) { - return key; - } - } - } - } -} - -exports.compareIdentifiers = compareIdentifiers; - -var numeric = /^[0-9]+$/; -function compareIdentifiers(a, b) { - var anum = numeric.test(a); - var bnum = numeric.test(b); - - if (anum && bnum) { - a = +a; - b = +b; - } - - return (anum && !bnum) ? -1 : - (bnum && !anum) ? 1 : - a < b ? -1 : - a > b ? 1 : - 0; -} - -exports.rcompareIdentifiers = rcompareIdentifiers; -function rcompareIdentifiers(a, b) { - return compareIdentifiers(b, a); -} - -exports.major = major; -function major(a, loose) { - return new SemVer(a, loose).major; -} - -exports.minor = minor; -function minor(a, loose) { - return new SemVer(a, loose).minor; -} - -exports.patch = patch; -function patch(a, loose) { - return new SemVer(a, loose).patch; -} - -exports.compare = compare; -function compare(a, b, loose) { - return new SemVer(a, loose).compare(new SemVer(b, loose)); -} - -exports.compareLoose = compareLoose; -function compareLoose(a, b) { - return compare(a, b, true); -} - -exports.rcompare = rcompare; -function rcompare(a, b, loose) { - return compare(b, a, loose); -} - -exports.sort = sort; -function sort(list, loose) { - return list.sort(function(a, b) { - return exports.compare(a, b, loose); - }); -} - -exports.rsort = rsort; -function rsort(list, loose) { - return list.sort(function(a, b) { - return exports.rcompare(a, b, loose); - }); -} - -exports.gt = gt; -function gt(a, b, loose) { - return compare(a, b, loose) > 0; -} - -exports.lt = lt; -function lt(a, b, loose) { - return compare(a, b, loose) < 0; -} - -exports.eq = eq; -function eq(a, b, loose) { - return compare(a, b, loose) === 0; -} - -exports.neq = neq; -function neq(a, b, loose) { - return compare(a, b, loose) !== 0; -} - -exports.gte = gte; -function gte(a, b, loose) { - return compare(a, b, loose) >= 0; -} - -exports.lte = lte; -function lte(a, b, loose) { - return compare(a, b, loose) <= 0; -} - -exports.cmp = cmp; -function cmp(a, op, b, loose) { - var ret; - switch (op) { - case '===': - if (typeof a === 'object') a = a.version; - if (typeof b === 'object') b = b.version; - ret = a === b; - break; - case '!==': - if (typeof a === 'object') a = a.version; - if (typeof b === 'object') b = b.version; - ret = a !== b; - break; - case '': case '=': case '==': ret = eq(a, b, loose); break; - case '!=': ret = neq(a, b, loose); break; - case '>': ret = gt(a, b, loose); break; - case '>=': ret = gte(a, b, loose); break; - case '<': ret = lt(a, b, loose); break; - case '<=': ret = lte(a, b, loose); break; - default: throw new TypeError('Invalid operator: ' + op); - } - return ret; -} - -exports.Comparator = Comparator; -function Comparator(comp, loose) { - if (comp instanceof Comparator) { - if (comp.loose === loose) - return comp; - else - comp = comp.value; - } - - if (!(this instanceof Comparator)) - return new Comparator(comp, loose); - - debug('comparator', comp, loose); - this.loose = loose; - this.parse(comp); - - if (this.semver === ANY) - this.value = ''; - else - this.value = this.operator + this.semver.version; - - debug('comp', this); -} - -var ANY = {}; -Comparator.prototype.parse = function(comp) { - var r = this.loose ? re[COMPARATORLOOSE] : re[COMPARATOR]; - var m = comp.match(r); - - if (!m) - throw new TypeError('Invalid comparator: ' + comp); - - this.operator = m[1]; - if (this.operator === '=') - this.operator = ''; - - // if it literally is just '>' or '' then allow anything. - if (!m[2]) - this.semver = ANY; - else - this.semver = new SemVer(m[2], this.loose); -}; - -Comparator.prototype.toString = function() { - return this.value; -}; - -Comparator.prototype.test = function(version) { - debug('Comparator.test', version, this.loose); - - if (this.semver === ANY) - return true; - - if (typeof version === 'string') - version = new SemVer(version, this.loose); - - return cmp(version, this.operator, this.semver, this.loose); -}; - -Comparator.prototype.intersects = function(comp, loose) { - if (!(comp instanceof Comparator)) { - throw new TypeError('a Comparator is required'); - } - - var rangeTmp; - - if (this.operator === '') { - rangeTmp = new Range(comp.value, loose); - return satisfies(this.value, rangeTmp, loose); - } else if (comp.operator === '') { - rangeTmp = new Range(this.value, loose); - return satisfies(comp.semver, rangeTmp, loose); - } - - var sameDirectionIncreasing = - (this.operator === '>=' || this.operator === '>') && - (comp.operator === '>=' || comp.operator === '>'); - var sameDirectionDecreasing = - (this.operator === '<=' || this.operator === '<') && - (comp.operator === '<=' || comp.operator === '<'); - var sameSemVer = this.semver.version === comp.semver.version; - var differentDirectionsInclusive = - (this.operator === '>=' || this.operator === '<=') && - (comp.operator === '>=' || comp.operator === '<='); - var oppositeDirectionsLessThan = - cmp(this.semver, '<', comp.semver, loose) && - ((this.operator === '>=' || this.operator === '>') && - (comp.operator === '<=' || comp.operator === '<')); - var oppositeDirectionsGreaterThan = - cmp(this.semver, '>', comp.semver, loose) && - ((this.operator === '<=' || this.operator === '<') && - (comp.operator === '>=' || comp.operator === '>')); - - return sameDirectionIncreasing || sameDirectionDecreasing || - (sameSemVer && differentDirectionsInclusive) || - oppositeDirectionsLessThan || oppositeDirectionsGreaterThan; -}; - - -exports.Range = Range; -function Range(range, loose) { - if (range instanceof Range) { - if (range.loose === loose) { - return range; - } else { - return new Range(range.raw, loose); - } - } - - if (range instanceof Comparator) { - return new Range(range.value, loose); - } - - if (!(this instanceof Range)) - return new Range(range, loose); - - this.loose = loose; - - // First, split based on boolean or || - this.raw = range; - this.set = range.split(/\s*\|\|\s*/).map(function(range) { - return this.parseRange(range.trim()); - }, this).filter(function(c) { - // throw out any that are not relevant for whatever reason - return c.length; - }); - - if (!this.set.length) { - throw new TypeError('Invalid SemVer Range: ' + range); - } - - this.format(); -} - -Range.prototype.format = function() { - this.range = this.set.map(function(comps) { - return comps.join(' ').trim(); - }).join('||').trim(); - return this.range; -}; - -Range.prototype.toString = function() { - return this.range; -}; - -Range.prototype.parseRange = function(range) { - var loose = this.loose; - range = range.trim(); - debug('range', range, loose); - // `1.2.3 - 1.2.4` => `>=1.2.3 <=1.2.4` - var hr = loose ? re[HYPHENRANGELOOSE] : re[HYPHENRANGE]; - range = range.replace(hr, hyphenReplace); - debug('hyphen replace', range); - // `> 1.2.3 < 1.2.5` => `>1.2.3 <1.2.5` - range = range.replace(re[COMPARATORTRIM], comparatorTrimReplace); - debug('comparator trim', range, re[COMPARATORTRIM]); - - // `~ 1.2.3` => `~1.2.3` - range = range.replace(re[TILDETRIM], tildeTrimReplace); - - // `^ 1.2.3` => `^1.2.3` - range = range.replace(re[CARETTRIM], caretTrimReplace); - - // normalize spaces - range = range.split(/\s+/).join(' '); - - // At this point, the range is completely trimmed and - // ready to be split into comparators. - - var compRe = loose ? re[COMPARATORLOOSE] : re[COMPARATOR]; - var set = range.split(' ').map(function(comp) { - return parseComparator(comp, loose); - }).join(' ').split(/\s+/); - if (this.loose) { - // in loose mode, throw out any that are not valid comparators - set = set.filter(function(comp) { - return !!comp.match(compRe); - }); - } - set = set.map(function(comp) { - return new Comparator(comp, loose); - }); - - return set; -}; - -Range.prototype.intersects = function(range, loose) { - if (!(range instanceof Range)) { - throw new TypeError('a Range is required'); - } - - return this.set.some(function(thisComparators) { - return thisComparators.every(function(thisComparator) { - return range.set.some(function(rangeComparators) { - return rangeComparators.every(function(rangeComparator) { - return thisComparator.intersects(rangeComparator, loose); - }); - }); - }); - }); -}; - -// Mostly just for testing and legacy API reasons -exports.toComparators = toComparators; -function toComparators(range, loose) { - return new Range(range, loose).set.map(function(comp) { - return comp.map(function(c) { - return c.value; - }).join(' ').trim().split(' '); - }); -} - -// comprised of xranges, tildes, stars, and gtlt's at this point. -// already replaced the hyphen ranges -// turn into a set of JUST comparators. -function parseComparator(comp, loose) { - debug('comp', comp); - comp = replaceCarets(comp, loose); - debug('caret', comp); - comp = replaceTildes(comp, loose); - debug('tildes', comp); - comp = replaceXRanges(comp, loose); - debug('xrange', comp); - comp = replaceStars(comp, loose); - debug('stars', comp); - return comp; -} - -function isX(id) { - return !id || id.toLowerCase() === 'x' || id === '*'; -} - -// ~, ~> --> * (any, kinda silly) -// ~2, ~2.x, ~2.x.x, ~>2, ~>2.x ~>2.x.x --> >=2.0.0 <3.0.0 -// ~2.0, ~2.0.x, ~>2.0, ~>2.0.x --> >=2.0.0 <2.1.0 -// ~1.2, ~1.2.x, ~>1.2, ~>1.2.x --> >=1.2.0 <1.3.0 -// ~1.2.3, ~>1.2.3 --> >=1.2.3 <1.3.0 -// ~1.2.0, ~>1.2.0 --> >=1.2.0 <1.3.0 -function replaceTildes(comp, loose) { - return comp.trim().split(/\s+/).map(function(comp) { - return replaceTilde(comp, loose); - }).join(' '); -} - -function replaceTilde(comp, loose) { - var r = loose ? re[TILDELOOSE] : re[TILDE]; - return comp.replace(r, function(_, M, m, p, pr) { - debug('tilde', comp, _, M, m, p, pr); - var ret; - - if (isX(M)) - ret = ''; - else if (isX(m)) - ret = '>=' + M + '.0.0 <' + (+M + 1) + '.0.0'; - else if (isX(p)) - // ~1.2 == >=1.2.0 <1.3.0 - ret = '>=' + M + '.' + m + '.0 <' + M + '.' + (+m + 1) + '.0'; - else if (pr) { - debug('replaceTilde pr', pr); - if (pr.charAt(0) !== '-') - pr = '-' + pr; - ret = '>=' + M + '.' + m + '.' + p + pr + - ' <' + M + '.' + (+m + 1) + '.0'; - } else - // ~1.2.3 == >=1.2.3 <1.3.0 - ret = '>=' + M + '.' + m + '.' + p + - ' <' + M + '.' + (+m + 1) + '.0'; - - debug('tilde return', ret); - return ret; - }); -} - -// ^ --> * (any, kinda silly) -// ^2, ^2.x, ^2.x.x --> >=2.0.0 <3.0.0 -// ^2.0, ^2.0.x --> >=2.0.0 <3.0.0 -// ^1.2, ^1.2.x --> >=1.2.0 <2.0.0 -// ^1.2.3 --> >=1.2.3 <2.0.0 -// ^1.2.0 --> >=1.2.0 <2.0.0 -function replaceCarets(comp, loose) { - return comp.trim().split(/\s+/).map(function(comp) { - return replaceCaret(comp, loose); - }).join(' '); -} - -function replaceCaret(comp, loose) { - debug('caret', comp, loose); - var r = loose ? re[CARETLOOSE] : re[CARET]; - return comp.replace(r, function(_, M, m, p, pr) { - debug('caret', comp, _, M, m, p, pr); - var ret; - - if (isX(M)) - ret = ''; - else if (isX(m)) - ret = '>=' + M + '.0.0 <' + (+M + 1) + '.0.0'; - else if (isX(p)) { - if (M === '0') - ret = '>=' + M + '.' + m + '.0 <' + M + '.' + (+m + 1) + '.0'; - else - ret = '>=' + M + '.' + m + '.0 <' + (+M + 1) + '.0.0'; - } else if (pr) { - debug('replaceCaret pr', pr); - if (pr.charAt(0) !== '-') - pr = '-' + pr; - if (M === '0') { - if (m === '0') - ret = '>=' + M + '.' + m + '.' + p + pr + - ' <' + M + '.' + m + '.' + (+p + 1); - else - ret = '>=' + M + '.' + m + '.' + p + pr + - ' <' + M + '.' + (+m + 1) + '.0'; - } else - ret = '>=' + M + '.' + m + '.' + p + pr + - ' <' + (+M + 1) + '.0.0'; - } else { - debug('no pr'); - if (M === '0') { - if (m === '0') - ret = '>=' + M + '.' + m + '.' + p + - ' <' + M + '.' + m + '.' + (+p + 1); - else - ret = '>=' + M + '.' + m + '.' + p + - ' <' + M + '.' + (+m + 1) + '.0'; - } else - ret = '>=' + M + '.' + m + '.' + p + - ' <' + (+M + 1) + '.0.0'; - } - - debug('caret return', ret); - return ret; - }); -} - -function replaceXRanges(comp, loose) { - debug('replaceXRanges', comp, loose); - return comp.split(/\s+/).map(function(comp) { - return replaceXRange(comp, loose); - }).join(' '); -} - -function replaceXRange(comp, loose) { - comp = comp.trim(); - var r = loose ? re[XRANGELOOSE] : re[XRANGE]; - return comp.replace(r, function(ret, gtlt, M, m, p, pr) { - debug('xRange', comp, ret, gtlt, M, m, p, pr); - var xM = isX(M); - var xm = xM || isX(m); - var xp = xm || isX(p); - var anyX = xp; - - if (gtlt === '=' && anyX) - gtlt = ''; - - if (xM) { - if (gtlt === '>' || gtlt === '<') { - // nothing is allowed - ret = '<0.0.0'; - } else { - // nothing is forbidden - ret = '*'; - } - } else if (gtlt && anyX) { - // replace X with 0 - if (xm) - m = 0; - if (xp) - p = 0; - - if (gtlt === '>') { - // >1 => >=2.0.0 - // >1.2 => >=1.3.0 - // >1.2.3 => >= 1.2.4 - gtlt = '>='; - if (xm) { - M = +M + 1; - m = 0; - p = 0; - } else if (xp) { - m = +m + 1; - p = 0; - } - } else if (gtlt === '<=') { - // <=0.7.x is actually <0.8.0, since any 0.7.x should - // pass. Similarly, <=7.x is actually <8.0.0, etc. - gtlt = '<'; - if (xm) - M = +M + 1; - else - m = +m + 1; - } - - ret = gtlt + M + '.' + m + '.' + p; - } else if (xm) { - ret = '>=' + M + '.0.0 <' + (+M + 1) + '.0.0'; - } else if (xp) { - ret = '>=' + M + '.' + m + '.0 <' + M + '.' + (+m + 1) + '.0'; - } - - debug('xRange return', ret); - - return ret; - }); -} - -// Because * is AND-ed with everything else in the comparator, -// and '' means "any version", just remove the *s entirely. -function replaceStars(comp, loose) { - debug('replaceStars', comp, loose); - // Looseness is ignored here. star is always as loose as it gets! - return comp.trim().replace(re[STAR], ''); -} - -// This function is passed to string.replace(re[HYPHENRANGE]) -// M, m, patch, prerelease, build -// 1.2 - 3.4.5 => >=1.2.0 <=3.4.5 -// 1.2.3 - 3.4 => >=1.2.0 <3.5.0 Any 3.4.x will do -// 1.2 - 3.4 => >=1.2.0 <3.5.0 -function hyphenReplace($0, - from, fM, fm, fp, fpr, fb, - to, tM, tm, tp, tpr, tb) { - - if (isX(fM)) - from = ''; - else if (isX(fm)) - from = '>=' + fM + '.0.0'; - else if (isX(fp)) - from = '>=' + fM + '.' + fm + '.0'; - else - from = '>=' + from; - - if (isX(tM)) - to = ''; - else if (isX(tm)) - to = '<' + (+tM + 1) + '.0.0'; - else if (isX(tp)) - to = '<' + tM + '.' + (+tm + 1) + '.0'; - else if (tpr) - to = '<=' + tM + '.' + tm + '.' + tp + '-' + tpr; - else - to = '<=' + to; - - return (from + ' ' + to).trim(); -} - - -// if ANY of the sets match ALL of its comparators, then pass -Range.prototype.test = function(version) { - if (!version) - return false; - - if (typeof version === 'string') - version = new SemVer(version, this.loose); - - for (var i = 0; i < this.set.length; i++) { - if (testSet(this.set[i], version)) - return true; - } - return false; -}; - -function testSet(set, version) { - for (var i = 0; i < set.length; i++) { - if (!set[i].test(version)) - return false; - } - - if (version.prerelease.length) { - // Find the set of versions that are allowed to have prereleases - // For example, ^1.2.3-pr.1 desugars to >=1.2.3-pr.1 <2.0.0 - // That should allow `1.2.3-pr.2` to pass. - // However, `1.2.4-alpha.notready` should NOT be allowed, - // even though it's within the range set by the comparators. - for (var i = 0; i < set.length; i++) { - debug(set[i].semver); - if (set[i].semver === ANY) - continue; - - if (set[i].semver.prerelease.length > 0) { - var allowed = set[i].semver; - if (allowed.major === version.major && - allowed.minor === version.minor && - allowed.patch === version.patch) - return true; - } - } - - // Version has a -pre, but it's not one of the ones we like. - return false; - } - - return true; -} - -exports.satisfies = satisfies; -function satisfies(version, range, loose) { - try { - range = new Range(range, loose); - } catch (er) { - return false; - } - return range.test(version); -} - -exports.maxSatisfying = maxSatisfying; -function maxSatisfying(versions, range, loose) { - var max = null; - var maxSV = null; - try { - var rangeObj = new Range(range, loose); - } catch (er) { - return null; - } - versions.forEach(function (v) { - if (rangeObj.test(v)) { // satisfies(v, range, loose) - if (!max || maxSV.compare(v) === -1) { // compare(max, v, true) - max = v; - maxSV = new SemVer(max, loose); - } - } - }) - return max; -} - -exports.minSatisfying = minSatisfying; -function minSatisfying(versions, range, loose) { - var min = null; - var minSV = null; - try { - var rangeObj = new Range(range, loose); - } catch (er) { - return null; - } - versions.forEach(function (v) { - if (rangeObj.test(v)) { // satisfies(v, range, loose) - if (!min || minSV.compare(v) === 1) { // compare(min, v, true) - min = v; - minSV = new SemVer(min, loose); - } - } - }) - return min; -} - -exports.validRange = validRange; -function validRange(range, loose) { - try { - // Return '*' instead of '' so that truthiness works. - // This will throw if it's invalid anyway - return new Range(range, loose).range || '*'; - } catch (er) { - return null; - } -} - -// Determine if version is less than all the versions possible in the range -exports.ltr = ltr; -function ltr(version, range, loose) { - return outside(version, range, '<', loose); -} - -// Determine if version is greater than all the versions possible in the range. -exports.gtr = gtr; -function gtr(version, range, loose) { - return outside(version, range, '>', loose); -} - -exports.outside = outside; -function outside(version, range, hilo, loose) { - version = new SemVer(version, loose); - range = new Range(range, loose); - - var gtfn, ltefn, ltfn, comp, ecomp; - switch (hilo) { - case '>': - gtfn = gt; - ltefn = lte; - ltfn = lt; - comp = '>'; - ecomp = '>='; - break; - case '<': - gtfn = lt; - ltefn = gte; - ltfn = gt; - comp = '<'; - ecomp = '<='; - break; - default: - throw new TypeError('Must provide a hilo val of "<" or ">"'); - } - - // If it satisifes the range it is not outside - if (satisfies(version, range, loose)) { - return false; - } - - // From now on, variable terms are as if we're in "gtr" mode. - // but note that everything is flipped for the "ltr" function. - - for (var i = 0; i < range.set.length; ++i) { - var comparators = range.set[i]; - - var high = null; - var low = null; - - comparators.forEach(function(comparator) { - if (comparator.semver === ANY) { - comparator = new Comparator('>=0.0.0') - } - high = high || comparator; - low = low || comparator; - if (gtfn(comparator.semver, high.semver, loose)) { - high = comparator; - } else if (ltfn(comparator.semver, low.semver, loose)) { - low = comparator; - } - }); - - // If the edge version comparator has a operator then our version - // isn't outside it - if (high.operator === comp || high.operator === ecomp) { - return false; - } - - // If the lowest version comparator has an operator and our version - // is less than it then it isn't higher than the range - if ((!low.operator || low.operator === comp) && - ltefn(version, low.semver)) { - return false; - } else if (low.operator === ecomp && ltfn(version, low.semver)) { - return false; - } - } - return true; -} - -exports.prerelease = prerelease; -function prerelease(version, loose) { - var parsed = parse(version, loose); - return (parsed && parsed.prerelease.length) ? parsed.prerelease : null; -} - -exports.intersects = intersects; -function intersects(r1, r2, loose) { - r1 = new Range(r1, loose) - r2 = new Range(r2, loose) - return r1.intersects(r2) -} diff --git a/ts-ticket-office-service/node_modules/smart-buffer/LICENSE b/ts-ticket-office-service/node_modules/smart-buffer/LICENSE new file mode 100644 index 000000000..aab5771a9 --- /dev/null +++ b/ts-ticket-office-service/node_modules/smart-buffer/LICENSE @@ -0,0 +1,20 @@ +The MIT License (MIT) + +Copyright (c) 2013-2017 Josh Glazebrook + +Permission is hereby granted, free of charge, to any person obtaining a copy of +this software and associated documentation files (the "Software"), to deal in +the Software without restriction, including without limitation the rights to +use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of +the Software, and to permit persons to whom the Software is furnished to do so, +subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS +FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR +COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER +IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN +CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/ts-ticket-office-service/node_modules/smart-buffer/README.md b/ts-ticket-office-service/node_modules/smart-buffer/README.md new file mode 100644 index 000000000..6e498288e --- /dev/null +++ b/ts-ticket-office-service/node_modules/smart-buffer/README.md @@ -0,0 +1,633 @@ +smart-buffer [![Build Status](https://travis-ci.org/JoshGlazebrook/smart-buffer.svg?branch=master)](https://travis-ci.org/JoshGlazebrook/smart-buffer) [![Coverage Status](https://coveralls.io/repos/github/JoshGlazebrook/smart-buffer/badge.svg?branch=master)](https://coveralls.io/github/JoshGlazebrook/smart-buffer?branch=master) +============= + +smart-buffer is a Buffer wrapper that adds automatic read & write offset tracking, string operations, data insertions, and more. + +![stats](https://nodei.co/npm/smart-buffer.png?downloads=true&downloadRank=true&stars=true "stats") + +**Key Features**: +* Proxies all of the Buffer write and read functions +* Keeps track of read and write offsets automatically +* Grows the internal Buffer as needed +* Useful string operations. (Null terminating strings) +* Allows for inserting values at specific points in the Buffer +* Built in TypeScript +* Type Definitions Provided +* Browser Support (using Webpack/Browserify) +* Full test coverage + +**Requirements**: +* Node v4.0+ is supported at this time. (Versions prior to 2.0 will work on node 0.10) + + + +## Breaking Changes in v4.0 + +* Old constructor patterns have been completely removed. It's now required to use the SmartBuffer.fromXXX() factory constructors. +* rewind(), skip(), moveTo() have been removed. (see [offsets](#offsets)) +* Internal private properties are now prefixed with underscores (_) +* **All** writeXXX() methods that are given an offset will now **overwrite data** instead of insert. (see [write vs insert](#write-vs-insert)) +* insertXXX() methods have been added for when you want to insert data at a specific offset (this replaces the old behavior of writeXXX() when an offset was provided) + + +## Looking for v3 docs? + +Legacy documentation for version 3 and prior can be found [here](https://github.com/JoshGlazebrook/smart-buffer/blob/master/docs/README_v3.md). + +## Installing: + +`yarn add smart-buffer` + +or + +`npm install smart-buffer` + +Note: The published NPM package includes the built javascript library. +If you cloned this repo and wish to build the library manually use: + +`npm run build` + +## Using smart-buffer + +```javascript +// Javascript +const SmartBuffer = require('smart-buffer').SmartBuffer; + +// Typescript +import { SmartBuffer, SmartBufferOptions} from 'smart-buffer'; +``` + +### Simple Example + +Building a packet that uses the following protocol specification: + +`[PacketType:2][PacketLength:2][Data:XX]` + +To build this packet using the vanilla Buffer class, you would have to count up the length of the data payload beforehand. You would also need to keep track of the current "cursor" position in your Buffer so you write everything in the right places. With smart-buffer you don't have to do either of those things. + +```javascript +function createLoginPacket(username, password, age, country) { + const packet = new SmartBuffer(); + packet.writeUInt16LE(0x0060); // Some packet type + packet.writeStringNT(username); + packet.writeStringNT(password); + packet.writeUInt8(age); + packet.writeStringNT(country); + packet.insertUInt16LE(packet.length - 2, 2); + + return packet.toBuffer(); +} +``` +With the above function, you now can do this: +```javascript +const login = createLoginPacket("Josh", "secret123", 22, "United States"); + +// +``` +Notice that the `[PacketLength:2]` value (1e 00) was inserted at position 2. + +Reading back the packet we created above is just as easy: +```javascript + +const reader = SmartBuffer.fromBuffer(login); + +const logininfo = { + packetType: reader.readUInt16LE(), + packetLength: reader.readUInt16LE(), + username: reader.readStringNT(), + password: reader.readStringNT(), + age: reader.readUInt8(), + country: reader.readStringNT() +}; + +/* +{ + packetType: 96, (0x0060) + packetLength: 30, + username: 'Josh', + password: 'secret123', + age: 22, + country: 'United States' +} +*/ +``` + + +## Write vs Insert +In prior versions of SmartBuffer, .writeXXX(value, offset) calls would insert data when an offset was provided. In version 4, this will now overwrite the data at the offset position. To insert data there are now corresponding .insertXXX(value, offset) methods. + +**SmartBuffer v3**: +```javascript +const buff = SmartBuffer.fromBuffer(new Buffer([1,2,3,4,5,6])); +buff.writeInt8(7, 2); +console.log(buff.toBuffer()) + +// +``` + +**SmartBuffer v4**: +```javascript +const buff = SmartBuffer.fromBuffer(new Buffer([1,2,3,4,5,6])); +buff.writeInt8(7, 2); +console.log(buff.toBuffer()); + +// +``` + +To insert you instead should use: +```javascript +const buff = SmartBuffer.fromBuffer(new Buffer([1,2,3,4,5,6])); +buff.insertInt8(7, 2); +console.log(buff.toBuffer()); + +// +``` + +**Note:** Insert/Writing to a position beyond the currently tracked internal Buffer will zero pad to your offset. + +## Constructing a smart-buffer + +There are a few different ways to construct a SmartBuffer instance. + +```javascript +// Creating SmartBuffer from existing Buffer +const buff = SmartBuffer.fromBuffer(buffer); // Creates instance from buffer. (Uses default utf8 encoding) +const buff = SmartBuffer.fromBuffer(buffer, 'ascii'); // Creates instance from buffer with ascii encoding for strings. + +// Creating SmartBuffer with specified internal Buffer size. (Note: this is not a hard cap, the internal buffer will grow as needed). +const buff = SmartBuffer.fromSize(1024); // Creates instance with internal Buffer size of 1024. +const buff = SmartBuffer.fromSize(1024, 'utf8'); // Creates instance with internal Buffer size of 1024, and utf8 encoding for strings. + +// Creating SmartBuffer with options object. This one specifies size and encoding. +const buff = SmartBuffer.fromOptions({ + size: 1024, + encoding: 'ascii' +}); + +// Creating SmartBuffer with options object. This one specified an existing Buffer. +const buff = SmartBuffer.fromOptions({ + buff: buffer +}); + +// Creating SmartBuffer from a string. +const buff = SmartBuffer.fromBuffer(Buffer.from('some string', 'utf8')); + +// Just want a regular SmartBuffer with all default options? +const buff = new SmartBuffer(); +``` + +# Api Reference: + +**Note:** SmartBuffer is fully documented with Typescript definitions as well as jsdocs so your favorite editor/IDE will have intellisense. + +**Table of Contents** + +1. [Constructing](#constructing) +2. **Numbers** + 1. [Integers](#integers) + 2. [Floating Points](#floating-point-numbers) +3. **Strings** + 1. [Strings](#strings) + 2. [Null Terminated Strings](#null-terminated-strings) +4. [Buffers](#buffers) +5. [Offsets](#offsets) +6. [Other](#other) + + +## Constructing + +### constructor() +### constructor([options]) +- ```options``` *{SmartBufferOptions}* An optional options object to construct a SmartBuffer with. + +Examples: +```javascript +const buff = new SmartBuffer(); +const buff = new SmartBuffer({ + size: 1024, + encoding: 'ascii' +}); +``` + +### Class Method: fromBuffer(buffer[, encoding]) +- ```buffer``` *{Buffer}* The Buffer instance to wrap. +- ```encoding``` *{string}* The string encoding to use. ```Default: 'utf8'``` + +Examples: +```javascript +const someBuffer = Buffer.from('some string'); +const buff = SmartBuffer.fromBuffer(someBuffer); // Defaults to utf8 +const buff = SmartBuffer.fromBuffer(someBuffer, 'ascii'); +``` + +### Class Method: fromSize(size[, encoding]) +- ```size``` *{number}* The size to initialize the internal Buffer. +- ```encoding``` *{string}* The string encoding to use. ```Default: 'utf8'``` + +Examples: +```javascript +const buff = SmartBuffer.fromSize(1024); // Defaults to utf8 +const buff = SmartBuffer.fromSize(1024, 'ascii'); +``` + +### Class Method: fromOptions(options) +- ```options``` *{SmartBufferOptions}* The Buffer instance to wrap. + +```typescript +interface SmartBufferOptions { + encoding?: BufferEncoding; // Defaults to utf8 + size?: number; // Defaults to 4096 + buff?: Buffer; +} +``` + +Examples: +```javascript +const buff = SmartBuffer.fromOptions({ + size: 1024 +}; +const buff = SmartBuffer.fromOptions({ + size: 1024, + encoding: 'utf8' +}); +const buff = SmartBuffer.fromOptions({ + encoding: 'utf8' +}); + +const someBuff = Buffer.from('some string', 'utf8'); +const buff = SmartBuffer.fromOptions({ + buffer: someBuff, + encoding: 'utf8' +}); +``` + +## Integers + +### buff.readInt8([offset]) +### buff.readUInt8([offset]) +- ```offset``` *{number}* Optional position to start reading data from. **Default**: ```Auto managed offset``` +- Returns *{number}* + +Read a Int8 value. + +### buff.readInt16BE([offset]) +### buff.readInt16LE([offset]) +### buff.readUInt16BE([offset]) +### buff.readUInt16LE([offset]) +- ```offset``` *{number}* Optional position to start reading data from. **Default**: ```Auto managed offset``` +- Returns *{number}* + +Read a 16 bit integer value. + +### buff.readInt32BE([offset]) +### buff.readInt32LE([offset]) +### buff.readUInt32BE([offset]) +### buff.readUInt32LE([offset]) +- ```offset``` *{number}* Optional position to start reading data from. **Default**: ```Auto managed offset``` +- Returns *{number}* + +Read a 32 bit integer value. + + +### buff.writeInt8(value[, offset]) +### buff.writeUInt8(value[, offset]) +- ```value``` *{number}* The value to write. +- ```offset``` *{number}* An optional offset to write this value to. **Default:** ```Auto managed offset``` +- Returns *{this}* + +Write a Int8 value. + +### buff.insertInt8(value, offset) +### buff.insertUInt8(value, offset) +- ```value``` *{number}* The value to insert. +- ```offset``` *{number}* The offset to insert this data at. +- Returns *{this}* + +Insert a Int8 value. + + +### buff.writeInt16BE(value[, offset]) +### buff.writeInt16LE(value[, offset]) +### buff.writeUInt16BE(value[, offset]) +### buff.writeUInt16LE(value[, offset]) +- ```value``` *{number}* The value to write. +- ```offset``` *{number}* An optional offset to write this value to. **Default:** ```Auto managed offset``` +- Returns *{this}* + +Write a 16 bit integer value. + +### buff.insertInt16BE(value, offset) +### buff.insertInt16LE(value, offset) +### buff.insertUInt16BE(value, offset) +### buff.insertUInt16LE(value, offset) +- ```value``` *{number}* The value to insert. +- ```offset``` *{number}* The offset to insert this data at. +- Returns *{this}* + +Insert a 16 bit integer value. + + +### buff.writeInt32BE(value[, offset]) +### buff.writeInt32LE(value[, offset]) +### buff.writeUInt32BE(value[, offset]) +### buff.writeUInt32LE(value[, offset]) +- ```value``` *{number}* The value to write. +- ```offset``` *{number}* An optional offset to write this value to. **Default:** ```Auto managed offset``` +- Returns *{this}* + +Write a 32 bit integer value. + +### buff.insertInt32BE(value, offset) +### buff.insertInt32LE(value, offset) +### buff.insertUInt32BE(value, offset) +### buff.nsertUInt32LE(value, offset) +- ```value``` *{number}* The value to insert. +- ```offset``` *{number}* The offset to insert this data at. +- Returns *{this}* + +Insert a 32 bit integer value. + + +## Floating Point Numbers + +### buff.readFloatBE([offset]) +### buff.readFloatLE([offset]) +- ```offset``` *{number}* Optional position to start reading data from. **Default**: ```Auto managed offset``` +- Returns *{number}* + +Read a Float value. + +### buff.readDoubleBE([offset]) +### buff.readDoubleLE([offset]) +- ```offset``` *{number}* Optional position to start reading data from. **Default**: ```Auto managed offset``` +- Returns *{number}* + +Read a Double value. + + +### buff.writeFloatBE(value[, offset]) +### buff.writeFloatLE(value[, offset]) +- ```value``` *{number}* The value to write. +- ```offset``` *{number}* An optional offset to write this value to. **Default:** ```Auto managed offset``` +- Returns *{this}* + +Write a Float value. + +### buff.insertFloatBE(value, offset) +### buff.insertFloatLE(value, offset) +- ```value``` *{number}* The value to insert. +- ```offset``` *{number}* The offset to insert this data at. +- Returns *{this}* + +Insert a Float value. + + +### buff.writeDoubleBE(value[, offset]) +### buff.writeDoubleLE(value[, offset]) +- ```value``` *{number}* The value to write. +- ```offset``` *{number}* An optional offset to write this value to. **Default:** ```Auto managed offset``` +- Returns *{this}* + +Write a Double value. + +### buff.insertDoubleBE(value, offset) +### buff.insertDoubleLE(value, offset) +- ```value``` *{number}* The value to insert. +- ```offset``` *{number}* The offset to insert this data at. +- Returns *{this}* + +Insert a Double value. + +## Strings + +### buff.readString() +### buff.readString(size[, encoding]) +### buff.readString(encoding) +- ```size``` *{number}* The number of bytes to read. **Default:** ```Reads to the end of the Buffer.``` +- ```encoding``` *{string}* The string encoding to use. **Default:** ```utf8```. + +Read a string value. + +Examples: +```javascript +const buff = SmartBuffer.fromBuffer(Buffer.from('hello there', 'utf8')); +buff.readString(); // 'hello there' +buff.readString(2); // 'he' +buff.readString(2, 'utf8'); // 'he' +buff.readString('utf8'); // 'hello there' +``` + +### buff.writeString(value) +### buff.writeString(value[, offset]) +### buff.writeString(value[, encoding]) +### buff.writeString(value[, offset[, encoding]]) +- ```value``` *{string}* The string value to write. +- ```offset``` *{number}* The offset to write this value to. **Default:** ```Auto managed offset``` +- ```encoding``` *{string}* An optional string encoding to use. **Default:** ```utf8``` + +Write a string value. + +Examples: +```javascript +buff.writeString('hello'); // Auto managed offset +buff.writeString('hello', 2); +buff.writeString('hello', 'utf8') // Auto managed offset +buff.writeString('hello', 2, 'utf8'); +``` + +### buff.insertString(value, offset[, encoding]) +- ```value``` *{string}* The string value to write. +- ```offset``` *{number}* The offset to write this value to. +- ```encoding``` *{string}* An optional string encoding to use. **Default:** ```utf8``` + +Insert a string value. + +Examples: +```javascript +buff.insertString('hello', 2); +buff.insertString('hello', 2, 'utf8'); +``` + +## Null Terminated Strings + +### buff.readStringNT() +### buff.readStringNT(encoding) +- ```encoding``` *{string}* The string encoding to use. **Default:** ```utf8```. + +Read a null terminated string value. (If a null is not found, it will read to the end of the Buffer). + +Examples: +```javascript +const buff = SmartBuffer.fromBuffer(Buffer.from('hello\0 there', 'utf8')); +buff.readStringNT(); // 'hello' + +// If we called this again: +buff.readStringNT(); // ' there' +``` + +### buff.writeStringNT(value) +### buff.writeStringNT(value[, offset]) +### buff.writeStringNT(value[, encoding]) +### buff.writeStringNT(value[, offset[, encoding]]) +- ```value``` *{string}* The string value to write. +- ```offset``` *{number}* The offset to write this value to. **Default:** ```Auto managed offset``` +- ```encoding``` *{string}* An optional string encoding to use. **Default:** ```utf8``` + +Write a null terminated string value. + +Examples: +```javascript +buff.writeStringNT('hello'); // Auto managed offset +buff.writeStringNT('hello', 2); // +buff.writeStringNT('hello', 'utf8') // Auto managed offset +buff.writeStringNT('hello', 2, 'utf8'); +``` + +### buff.insertStringNT(value, offset[, encoding]) +- ```value``` *{string}* The string value to write. +- ```offset``` *{number}* The offset to write this value to. +- ```encoding``` *{string}* An optional string encoding to use. **Default:** ```utf8``` + +Insert a null terminated string value. + +Examples: +```javascript +buff.insertStringNT('hello', 2); +buff.insertStringNT('hello', 2, 'utf8'); +``` + +## Buffers + +### buff.readBuffer([length]) +- ```length``` *{number}* The number of bytes to read into a Buffer. **Default:** ```Reads to the end of the Buffer``` + +Read a Buffer of a specified size. + +### buff.writeBuffer(value[, offset]) +- ```value``` *{Buffer}* The buffer value to write. +- ```offset``` *{number}* An optional offset to write the value to. **Default:** ```Auto managed offset``` + +### buff.insertBuffer(value, offset) +- ```value``` *{Buffer}* The buffer value to write. +- ```offset``` *{number}* The offset to write the value to. + + +### buff.readBufferNT() + +Read a null terminated Buffer. + +### buff.writeBufferNT(value[, offset]) +- ```value``` *{Buffer}* The buffer value to write. +- ```offset``` *{number}* An optional offset to write the value to. **Default:** ```Auto managed offset``` + +Write a null terminated Buffer. + + +### buff.insertBufferNT(value, offset) +- ```value``` *{Buffer}* The buffer value to write. +- ```offset``` *{number}* The offset to write the value to. + +Insert a null terminated Buffer. + + +## Offsets + +### buff.readOffset +### buff.readOffset(offset) +- ```offset``` *{number}* The new read offset value to set. +- Returns: ```The current read offset``` + +Gets or sets the current read offset. + +Examples: +```javascript +const currentOffset = buff.readOffset; // 5 + +buff.readOffset = 10; + +console.log(buff.readOffset) // 10 +``` + +### buff.writeOffset +### buff.writeOffset(offset) +- ```offset``` *{number}* The new write offset value to set. +- Returns: ```The current write offset``` + +Gets or sets the current write offset. + +Examples: +```javascript +const currentOffset = buff.writeOffset; // 5 + +buff.writeOffset = 10; + +console.log(buff.writeOffset) // 10 +``` + +### buff.encoding +### buff.encoding(encoding) +- ```encoding``` *{string}* The new string encoding to set. +- Returns: ```The current string encoding``` + +Gets or sets the current string encoding. + +Examples: +```javascript +const currentEncoding = buff.encoding; // 'utf8' + +buff.encoding = 'ascii'; + +console.log(buff.encoding) // 'ascii' +``` + +## Other + +### buff.clear() + +Clear and resets the SmartBuffer instance. + +### buff.remaining() +- Returns ```Remaining data left to be read``` + +Gets the number of remaining bytes to be read. + + +### buff.internalBuffer +- Returns: *{Buffer}* + +Gets the internally managed Buffer (Includes unmanaged data). + +Examples: +```javascript +const buff = SmartBuffer.fromSize(16); +buff.writeString('hello'); +console.log(buff.InternalBuffer); // +``` + +### buff.toBuffer() +- Returns: *{Buffer}* + +Gets a sliced Buffer instance of the internally managed Buffer. (Only includes managed data) + +Examples: +```javascript +const buff = SmartBuffer.fromSize(16); +buff.writeString('hello'); +console.log(buff.toBuffer()); // +``` + +### buff.toString([encoding]) +- ```encoding``` *{string}* The string encoding to use when converting to a string. **Default:** ```utf8``` +- Returns *{string}* + +Gets a string representation of all data in the SmartBuffer. + +### buff.destroy() + +Destroys the SmartBuffer instance. + + + +## License + +This work is licensed under the [MIT license](http://en.wikipedia.org/wiki/MIT_License). diff --git a/ts-ticket-office-service/node_modules/smart-buffer/build/smartbuffer.js b/ts-ticket-office-service/node_modules/smart-buffer/build/smartbuffer.js new file mode 100644 index 000000000..5353ae11d --- /dev/null +++ b/ts-ticket-office-service/node_modules/smart-buffer/build/smartbuffer.js @@ -0,0 +1,1233 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +const utils_1 = require("./utils"); +// The default Buffer size if one is not provided. +const DEFAULT_SMARTBUFFER_SIZE = 4096; +// The default string encoding to use for reading/writing strings. +const DEFAULT_SMARTBUFFER_ENCODING = 'utf8'; +class SmartBuffer { + /** + * Creates a new SmartBuffer instance. + * + * @param options { SmartBufferOptions } The SmartBufferOptions to apply to this instance. + */ + constructor(options) { + this.length = 0; + this._encoding = DEFAULT_SMARTBUFFER_ENCODING; + this._writeOffset = 0; + this._readOffset = 0; + if (SmartBuffer.isSmartBufferOptions(options)) { + // Checks for encoding + if (options.encoding) { + utils_1.checkEncoding(options.encoding); + this._encoding = options.encoding; + } + // Checks for initial size length + if (options.size) { + if (utils_1.isFiniteInteger(options.size) && options.size > 0) { + this._buff = Buffer.allocUnsafe(options.size); + } + else { + throw new Error(utils_1.ERRORS.INVALID_SMARTBUFFER_SIZE); + } + // Check for initial Buffer + } + else if (options.buff) { + if (Buffer.isBuffer(options.buff)) { + this._buff = options.buff; + this.length = options.buff.length; + } + else { + throw new Error(utils_1.ERRORS.INVALID_SMARTBUFFER_BUFFER); + } + } + else { + this._buff = Buffer.allocUnsafe(DEFAULT_SMARTBUFFER_SIZE); + } + } + else { + // If something was passed but it's not a SmartBufferOptions object + if (typeof options !== 'undefined') { + throw new Error(utils_1.ERRORS.INVALID_SMARTBUFFER_OBJECT); + } + // Otherwise default to sane options + this._buff = Buffer.allocUnsafe(DEFAULT_SMARTBUFFER_SIZE); + } + } + /** + * Creates a new SmartBuffer instance with the provided internal Buffer size and optional encoding. + * + * @param size { Number } The size of the internal Buffer. + * @param encoding { String } The BufferEncoding to use for strings. + * + * @return { SmartBuffer } + */ + static fromSize(size, encoding) { + return new this({ + size: size, + encoding: encoding + }); + } + /** + * Creates a new SmartBuffer instance with the provided Buffer and optional encoding. + * + * @param buffer { Buffer } The Buffer to use as the internal Buffer value. + * @param encoding { String } The BufferEncoding to use for strings. + * + * @return { SmartBuffer } + */ + static fromBuffer(buff, encoding) { + return new this({ + buff: buff, + encoding: encoding + }); + } + /** + * Creates a new SmartBuffer instance with the provided SmartBufferOptions options. + * + * @param options { SmartBufferOptions } The options to use when creating the SmartBuffer instance. + */ + static fromOptions(options) { + return new this(options); + } + /** + * Type checking function that determines if an object is a SmartBufferOptions object. + */ + static isSmartBufferOptions(options) { + const castOptions = options; + return (castOptions && + (castOptions.encoding !== undefined || castOptions.size !== undefined || castOptions.buff !== undefined)); + } + // Signed integers + /** + * Reads an Int8 value from the current read position or an optionally provided offset. + * + * @param offset { Number } The offset to read data from (optional) + * @return { Number } + */ + readInt8(offset) { + return this._readNumberValue(Buffer.prototype.readInt8, 1, offset); + } + /** + * Reads an Int16BE value from the current read position or an optionally provided offset. + * + * @param offset { Number } The offset to read data from (optional) + * @return { Number } + */ + readInt16BE(offset) { + return this._readNumberValue(Buffer.prototype.readInt16BE, 2, offset); + } + /** + * Reads an Int16LE value from the current read position or an optionally provided offset. + * + * @param offset { Number } The offset to read data from (optional) + * @return { Number } + */ + readInt16LE(offset) { + return this._readNumberValue(Buffer.prototype.readInt16LE, 2, offset); + } + /** + * Reads an Int32BE value from the current read position or an optionally provided offset. + * + * @param offset { Number } The offset to read data from (optional) + * @return { Number } + */ + readInt32BE(offset) { + return this._readNumberValue(Buffer.prototype.readInt32BE, 4, offset); + } + /** + * Reads an Int32LE value from the current read position or an optionally provided offset. + * + * @param offset { Number } The offset to read data from (optional) + * @return { Number } + */ + readInt32LE(offset) { + return this._readNumberValue(Buffer.prototype.readInt32LE, 4, offset); + } + /** + * Reads a BigInt64BE value from the current read position or an optionally provided offset. + * + * @param offset { Number } The offset to read data from (optional) + * @return { BigInt } + */ + readBigInt64BE(offset) { + utils_1.bigIntAndBufferInt64Check('readBigInt64BE'); + return this._readNumberValue(Buffer.prototype.readBigInt64BE, 8, offset); + } + /** + * Reads a BigInt64LE value from the current read position or an optionally provided offset. + * + * @param offset { Number } The offset to read data from (optional) + * @return { BigInt } + */ + readBigInt64LE(offset) { + utils_1.bigIntAndBufferInt64Check('readBigInt64LE'); + return this._readNumberValue(Buffer.prototype.readBigInt64LE, 8, offset); + } + /** + * Writes an Int8 value to the current write position (or at optional offset). + * + * @param value { Number } The value to write. + * @param offset { Number } The offset to write the value at. + * + * @return this + */ + writeInt8(value, offset) { + this._writeNumberValue(Buffer.prototype.writeInt8, 1, value, offset); + return this; + } + /** + * Inserts an Int8 value at the given offset value. + * + * @param value { Number } The value to insert. + * @param offset { Number } The offset to insert the value at. + * + * @return this + */ + insertInt8(value, offset) { + return this._insertNumberValue(Buffer.prototype.writeInt8, 1, value, offset); + } + /** + * Writes an Int16BE value to the current write position (or at optional offset). + * + * @param value { Number } The value to write. + * @param offset { Number } The offset to write the value at. + * + * @return this + */ + writeInt16BE(value, offset) { + return this._writeNumberValue(Buffer.prototype.writeInt16BE, 2, value, offset); + } + /** + * Inserts an Int16BE value at the given offset value. + * + * @param value { Number } The value to insert. + * @param offset { Number } The offset to insert the value at. + * + * @return this + */ + insertInt16BE(value, offset) { + return this._insertNumberValue(Buffer.prototype.writeInt16BE, 2, value, offset); + } + /** + * Writes an Int16LE value to the current write position (or at optional offset). + * + * @param value { Number } The value to write. + * @param offset { Number } The offset to write the value at. + * + * @return this + */ + writeInt16LE(value, offset) { + return this._writeNumberValue(Buffer.prototype.writeInt16LE, 2, value, offset); + } + /** + * Inserts an Int16LE value at the given offset value. + * + * @param value { Number } The value to insert. + * @param offset { Number } The offset to insert the value at. + * + * @return this + */ + insertInt16LE(value, offset) { + return this._insertNumberValue(Buffer.prototype.writeInt16LE, 2, value, offset); + } + /** + * Writes an Int32BE value to the current write position (or at optional offset). + * + * @param value { Number } The value to write. + * @param offset { Number } The offset to write the value at. + * + * @return this + */ + writeInt32BE(value, offset) { + return this._writeNumberValue(Buffer.prototype.writeInt32BE, 4, value, offset); + } + /** + * Inserts an Int32BE value at the given offset value. + * + * @param value { Number } The value to insert. + * @param offset { Number } The offset to insert the value at. + * + * @return this + */ + insertInt32BE(value, offset) { + return this._insertNumberValue(Buffer.prototype.writeInt32BE, 4, value, offset); + } + /** + * Writes an Int32LE value to the current write position (or at optional offset). + * + * @param value { Number } The value to write. + * @param offset { Number } The offset to write the value at. + * + * @return this + */ + writeInt32LE(value, offset) { + return this._writeNumberValue(Buffer.prototype.writeInt32LE, 4, value, offset); + } + /** + * Inserts an Int32LE value at the given offset value. + * + * @param value { Number } The value to insert. + * @param offset { Number } The offset to insert the value at. + * + * @return this + */ + insertInt32LE(value, offset) { + return this._insertNumberValue(Buffer.prototype.writeInt32LE, 4, value, offset); + } + /** + * Writes a BigInt64BE value to the current write position (or at optional offset). + * + * @param value { BigInt } The value to write. + * @param offset { Number } The offset to write the value at. + * + * @return this + */ + writeBigInt64BE(value, offset) { + utils_1.bigIntAndBufferInt64Check('writeBigInt64BE'); + return this._writeNumberValue(Buffer.prototype.writeBigInt64BE, 8, value, offset); + } + /** + * Inserts a BigInt64BE value at the given offset value. + * + * @param value { BigInt } The value to insert. + * @param offset { Number } The offset to insert the value at. + * + * @return this + */ + insertBigInt64BE(value, offset) { + utils_1.bigIntAndBufferInt64Check('writeBigInt64BE'); + return this._insertNumberValue(Buffer.prototype.writeBigInt64BE, 8, value, offset); + } + /** + * Writes a BigInt64LE value to the current write position (or at optional offset). + * + * @param value { BigInt } The value to write. + * @param offset { Number } The offset to write the value at. + * + * @return this + */ + writeBigInt64LE(value, offset) { + utils_1.bigIntAndBufferInt64Check('writeBigInt64LE'); + return this._writeNumberValue(Buffer.prototype.writeBigInt64LE, 8, value, offset); + } + /** + * Inserts a Int64LE value at the given offset value. + * + * @param value { BigInt } The value to insert. + * @param offset { Number } The offset to insert the value at. + * + * @return this + */ + insertBigInt64LE(value, offset) { + utils_1.bigIntAndBufferInt64Check('writeBigInt64LE'); + return this._insertNumberValue(Buffer.prototype.writeBigInt64LE, 8, value, offset); + } + // Unsigned Integers + /** + * Reads an UInt8 value from the current read position or an optionally provided offset. + * + * @param offset { Number } The offset to read data from (optional) + * @return { Number } + */ + readUInt8(offset) { + return this._readNumberValue(Buffer.prototype.readUInt8, 1, offset); + } + /** + * Reads an UInt16BE value from the current read position or an optionally provided offset. + * + * @param offset { Number } The offset to read data from (optional) + * @return { Number } + */ + readUInt16BE(offset) { + return this._readNumberValue(Buffer.prototype.readUInt16BE, 2, offset); + } + /** + * Reads an UInt16LE value from the current read position or an optionally provided offset. + * + * @param offset { Number } The offset to read data from (optional) + * @return { Number } + */ + readUInt16LE(offset) { + return this._readNumberValue(Buffer.prototype.readUInt16LE, 2, offset); + } + /** + * Reads an UInt32BE value from the current read position or an optionally provided offset. + * + * @param offset { Number } The offset to read data from (optional) + * @return { Number } + */ + readUInt32BE(offset) { + return this._readNumberValue(Buffer.prototype.readUInt32BE, 4, offset); + } + /** + * Reads an UInt32LE value from the current read position or an optionally provided offset. + * + * @param offset { Number } The offset to read data from (optional) + * @return { Number } + */ + readUInt32LE(offset) { + return this._readNumberValue(Buffer.prototype.readUInt32LE, 4, offset); + } + /** + * Reads a BigUInt64BE value from the current read position or an optionally provided offset. + * + * @param offset { Number } The offset to read data from (optional) + * @return { BigInt } + */ + readBigUInt64BE(offset) { + utils_1.bigIntAndBufferInt64Check('readBigUInt64BE'); + return this._readNumberValue(Buffer.prototype.readBigUInt64BE, 8, offset); + } + /** + * Reads a BigUInt64LE value from the current read position or an optionally provided offset. + * + * @param offset { Number } The offset to read data from (optional) + * @return { BigInt } + */ + readBigUInt64LE(offset) { + utils_1.bigIntAndBufferInt64Check('readBigUInt64LE'); + return this._readNumberValue(Buffer.prototype.readBigUInt64LE, 8, offset); + } + /** + * Writes an UInt8 value to the current write position (or at optional offset). + * + * @param value { Number } The value to write. + * @param offset { Number } The offset to write the value at. + * + * @return this + */ + writeUInt8(value, offset) { + return this._writeNumberValue(Buffer.prototype.writeUInt8, 1, value, offset); + } + /** + * Inserts an UInt8 value at the given offset value. + * + * @param value { Number } The value to insert. + * @param offset { Number } The offset to insert the value at. + * + * @return this + */ + insertUInt8(value, offset) { + return this._insertNumberValue(Buffer.prototype.writeUInt8, 1, value, offset); + } + /** + * Writes an UInt16BE value to the current write position (or at optional offset). + * + * @param value { Number } The value to write. + * @param offset { Number } The offset to write the value at. + * + * @return this + */ + writeUInt16BE(value, offset) { + return this._writeNumberValue(Buffer.prototype.writeUInt16BE, 2, value, offset); + } + /** + * Inserts an UInt16BE value at the given offset value. + * + * @param value { Number } The value to insert. + * @param offset { Number } The offset to insert the value at. + * + * @return this + */ + insertUInt16BE(value, offset) { + return this._insertNumberValue(Buffer.prototype.writeUInt16BE, 2, value, offset); + } + /** + * Writes an UInt16LE value to the current write position (or at optional offset). + * + * @param value { Number } The value to write. + * @param offset { Number } The offset to write the value at. + * + * @return this + */ + writeUInt16LE(value, offset) { + return this._writeNumberValue(Buffer.prototype.writeUInt16LE, 2, value, offset); + } + /** + * Inserts an UInt16LE value at the given offset value. + * + * @param value { Number } The value to insert. + * @param offset { Number } The offset to insert the value at. + * + * @return this + */ + insertUInt16LE(value, offset) { + return this._insertNumberValue(Buffer.prototype.writeUInt16LE, 2, value, offset); + } + /** + * Writes an UInt32BE value to the current write position (or at optional offset). + * + * @param value { Number } The value to write. + * @param offset { Number } The offset to write the value at. + * + * @return this + */ + writeUInt32BE(value, offset) { + return this._writeNumberValue(Buffer.prototype.writeUInt32BE, 4, value, offset); + } + /** + * Inserts an UInt32BE value at the given offset value. + * + * @param value { Number } The value to insert. + * @param offset { Number } The offset to insert the value at. + * + * @return this + */ + insertUInt32BE(value, offset) { + return this._insertNumberValue(Buffer.prototype.writeUInt32BE, 4, value, offset); + } + /** + * Writes an UInt32LE value to the current write position (or at optional offset). + * + * @param value { Number } The value to write. + * @param offset { Number } The offset to write the value at. + * + * @return this + */ + writeUInt32LE(value, offset) { + return this._writeNumberValue(Buffer.prototype.writeUInt32LE, 4, value, offset); + } + /** + * Inserts an UInt32LE value at the given offset value. + * + * @param value { Number } The value to insert. + * @param offset { Number } The offset to insert the value at. + * + * @return this + */ + insertUInt32LE(value, offset) { + return this._insertNumberValue(Buffer.prototype.writeUInt32LE, 4, value, offset); + } + /** + * Writes a BigUInt64BE value to the current write position (or at optional offset). + * + * @param value { Number } The value to write. + * @param offset { Number } The offset to write the value at. + * + * @return this + */ + writeBigUInt64BE(value, offset) { + utils_1.bigIntAndBufferInt64Check('writeBigUInt64BE'); + return this._writeNumberValue(Buffer.prototype.writeBigUInt64BE, 8, value, offset); + } + /** + * Inserts a BigUInt64BE value at the given offset value. + * + * @param value { Number } The value to insert. + * @param offset { Number } The offset to insert the value at. + * + * @return this + */ + insertBigUInt64BE(value, offset) { + utils_1.bigIntAndBufferInt64Check('writeBigUInt64BE'); + return this._insertNumberValue(Buffer.prototype.writeBigUInt64BE, 8, value, offset); + } + /** + * Writes a BigUInt64LE value to the current write position (or at optional offset). + * + * @param value { Number } The value to write. + * @param offset { Number } The offset to write the value at. + * + * @return this + */ + writeBigUInt64LE(value, offset) { + utils_1.bigIntAndBufferInt64Check('writeBigUInt64LE'); + return this._writeNumberValue(Buffer.prototype.writeBigUInt64LE, 8, value, offset); + } + /** + * Inserts a BigUInt64LE value at the given offset value. + * + * @param value { Number } The value to insert. + * @param offset { Number } The offset to insert the value at. + * + * @return this + */ + insertBigUInt64LE(value, offset) { + utils_1.bigIntAndBufferInt64Check('writeBigUInt64LE'); + return this._insertNumberValue(Buffer.prototype.writeBigUInt64LE, 8, value, offset); + } + // Floating Point + /** + * Reads an FloatBE value from the current read position or an optionally provided offset. + * + * @param offset { Number } The offset to read data from (optional) + * @return { Number } + */ + readFloatBE(offset) { + return this._readNumberValue(Buffer.prototype.readFloatBE, 4, offset); + } + /** + * Reads an FloatLE value from the current read position or an optionally provided offset. + * + * @param offset { Number } The offset to read data from (optional) + * @return { Number } + */ + readFloatLE(offset) { + return this._readNumberValue(Buffer.prototype.readFloatLE, 4, offset); + } + /** + * Writes a FloatBE value to the current write position (or at optional offset). + * + * @param value { Number } The value to write. + * @param offset { Number } The offset to write the value at. + * + * @return this + */ + writeFloatBE(value, offset) { + return this._writeNumberValue(Buffer.prototype.writeFloatBE, 4, value, offset); + } + /** + * Inserts a FloatBE value at the given offset value. + * + * @param value { Number } The value to insert. + * @param offset { Number } The offset to insert the value at. + * + * @return this + */ + insertFloatBE(value, offset) { + return this._insertNumberValue(Buffer.prototype.writeFloatBE, 4, value, offset); + } + /** + * Writes a FloatLE value to the current write position (or at optional offset). + * + * @param value { Number } The value to write. + * @param offset { Number } The offset to write the value at. + * + * @return this + */ + writeFloatLE(value, offset) { + return this._writeNumberValue(Buffer.prototype.writeFloatLE, 4, value, offset); + } + /** + * Inserts a FloatLE value at the given offset value. + * + * @param value { Number } The value to insert. + * @param offset { Number } The offset to insert the value at. + * + * @return this + */ + insertFloatLE(value, offset) { + return this._insertNumberValue(Buffer.prototype.writeFloatLE, 4, value, offset); + } + // Double Floating Point + /** + * Reads an DoublEBE value from the current read position or an optionally provided offset. + * + * @param offset { Number } The offset to read data from (optional) + * @return { Number } + */ + readDoubleBE(offset) { + return this._readNumberValue(Buffer.prototype.readDoubleBE, 8, offset); + } + /** + * Reads an DoubleLE value from the current read position or an optionally provided offset. + * + * @param offset { Number } The offset to read data from (optional) + * @return { Number } + */ + readDoubleLE(offset) { + return this._readNumberValue(Buffer.prototype.readDoubleLE, 8, offset); + } + /** + * Writes a DoubleBE value to the current write position (or at optional offset). + * + * @param value { Number } The value to write. + * @param offset { Number } The offset to write the value at. + * + * @return this + */ + writeDoubleBE(value, offset) { + return this._writeNumberValue(Buffer.prototype.writeDoubleBE, 8, value, offset); + } + /** + * Inserts a DoubleBE value at the given offset value. + * + * @param value { Number } The value to insert. + * @param offset { Number } The offset to insert the value at. + * + * @return this + */ + insertDoubleBE(value, offset) { + return this._insertNumberValue(Buffer.prototype.writeDoubleBE, 8, value, offset); + } + /** + * Writes a DoubleLE value to the current write position (or at optional offset). + * + * @param value { Number } The value to write. + * @param offset { Number } The offset to write the value at. + * + * @return this + */ + writeDoubleLE(value, offset) { + return this._writeNumberValue(Buffer.prototype.writeDoubleLE, 8, value, offset); + } + /** + * Inserts a DoubleLE value at the given offset value. + * + * @param value { Number } The value to insert. + * @param offset { Number } The offset to insert the value at. + * + * @return this + */ + insertDoubleLE(value, offset) { + return this._insertNumberValue(Buffer.prototype.writeDoubleLE, 8, value, offset); + } + // Strings + /** + * Reads a String from the current read position. + * + * @param arg1 { Number | String } The number of bytes to read as a String, or the BufferEncoding to use for + * the string (Defaults to instance level encoding). + * @param encoding { String } The BufferEncoding to use for the string (Defaults to instance level encoding). + * + * @return { String } + */ + readString(arg1, encoding) { + let lengthVal; + // Length provided + if (typeof arg1 === 'number') { + utils_1.checkLengthValue(arg1); + lengthVal = Math.min(arg1, this.length - this._readOffset); + } + else { + encoding = arg1; + lengthVal = this.length - this._readOffset; + } + // Check encoding + if (typeof encoding !== 'undefined') { + utils_1.checkEncoding(encoding); + } + const value = this._buff.slice(this._readOffset, this._readOffset + lengthVal).toString(encoding || this._encoding); + this._readOffset += lengthVal; + return value; + } + /** + * Inserts a String + * + * @param value { String } The String value to insert. + * @param offset { Number } The offset to insert the string at. + * @param encoding { String } The BufferEncoding to use for writing strings (defaults to instance encoding). + * + * @return this + */ + insertString(value, offset, encoding) { + utils_1.checkOffsetValue(offset); + return this._handleString(value, true, offset, encoding); + } + /** + * Writes a String + * + * @param value { String } The String value to write. + * @param arg2 { Number | String } The offset to write the string at, or the BufferEncoding to use. + * @param encoding { String } The BufferEncoding to use for writing strings (defaults to instance encoding). + * + * @return this + */ + writeString(value, arg2, encoding) { + return this._handleString(value, false, arg2, encoding); + } + /** + * Reads a null-terminated String from the current read position. + * + * @param encoding { String } The BufferEncoding to use for the string (Defaults to instance level encoding). + * + * @return { String } + */ + readStringNT(encoding) { + if (typeof encoding !== 'undefined') { + utils_1.checkEncoding(encoding); + } + // Set null character position to the end SmartBuffer instance. + let nullPos = this.length; + // Find next null character (if one is not found, default from above is used) + for (let i = this._readOffset; i < this.length; i++) { + if (this._buff[i] === 0x00) { + nullPos = i; + break; + } + } + // Read string value + const value = this._buff.slice(this._readOffset, nullPos); + // Increment internal Buffer read offset + this._readOffset = nullPos + 1; + return value.toString(encoding || this._encoding); + } + /** + * Inserts a null-terminated String. + * + * @param value { String } The String value to write. + * @param arg2 { Number | String } The offset to write the string to, or the BufferEncoding to use. + * @param encoding { String } The BufferEncoding to use for writing strings (defaults to instance encoding). + * + * @return this + */ + insertStringNT(value, offset, encoding) { + utils_1.checkOffsetValue(offset); + // Write Values + this.insertString(value, offset, encoding); + this.insertUInt8(0x00, offset + value.length); + return this; + } + /** + * Writes a null-terminated String. + * + * @param value { String } The String value to write. + * @param arg2 { Number | String } The offset to write the string to, or the BufferEncoding to use. + * @param encoding { String } The BufferEncoding to use for writing strings (defaults to instance encoding). + * + * @return this + */ + writeStringNT(value, arg2, encoding) { + // Write Values + this.writeString(value, arg2, encoding); + this.writeUInt8(0x00, typeof arg2 === 'number' ? arg2 + value.length : this.writeOffset); + return this; + } + // Buffers + /** + * Reads a Buffer from the internal read position. + * + * @param length { Number } The length of data to read as a Buffer. + * + * @return { Buffer } + */ + readBuffer(length) { + if (typeof length !== 'undefined') { + utils_1.checkLengthValue(length); + } + const lengthVal = typeof length === 'number' ? length : this.length; + const endPoint = Math.min(this.length, this._readOffset + lengthVal); + // Read buffer value + const value = this._buff.slice(this._readOffset, endPoint); + // Increment internal Buffer read offset + this._readOffset = endPoint; + return value; + } + /** + * Writes a Buffer to the current write position. + * + * @param value { Buffer } The Buffer to write. + * @param offset { Number } The offset to write the Buffer to. + * + * @return this + */ + insertBuffer(value, offset) { + utils_1.checkOffsetValue(offset); + return this._handleBuffer(value, true, offset); + } + /** + * Writes a Buffer to the current write position. + * + * @param value { Buffer } The Buffer to write. + * @param offset { Number } The offset to write the Buffer to. + * + * @return this + */ + writeBuffer(value, offset) { + return this._handleBuffer(value, false, offset); + } + /** + * Reads a null-terminated Buffer from the current read poisiton. + * + * @return { Buffer } + */ + readBufferNT() { + // Set null character position to the end SmartBuffer instance. + let nullPos = this.length; + // Find next null character (if one is not found, default from above is used) + for (let i = this._readOffset; i < this.length; i++) { + if (this._buff[i] === 0x00) { + nullPos = i; + break; + } + } + // Read value + const value = this._buff.slice(this._readOffset, nullPos); + // Increment internal Buffer read offset + this._readOffset = nullPos + 1; + return value; + } + /** + * Inserts a null-terminated Buffer. + * + * @param value { Buffer } The Buffer to write. + * @param offset { Number } The offset to write the Buffer to. + * + * @return this + */ + insertBufferNT(value, offset) { + utils_1.checkOffsetValue(offset); + // Write Values + this.insertBuffer(value, offset); + this.insertUInt8(0x00, offset + value.length); + return this; + } + /** + * Writes a null-terminated Buffer. + * + * @param value { Buffer } The Buffer to write. + * @param offset { Number } The offset to write the Buffer to. + * + * @return this + */ + writeBufferNT(value, offset) { + // Checks for valid numberic value; + if (typeof offset !== 'undefined') { + utils_1.checkOffsetValue(offset); + } + // Write Values + this.writeBuffer(value, offset); + this.writeUInt8(0x00, typeof offset === 'number' ? offset + value.length : this._writeOffset); + return this; + } + /** + * Clears the SmartBuffer instance to its original empty state. + */ + clear() { + this._writeOffset = 0; + this._readOffset = 0; + this.length = 0; + return this; + } + /** + * Gets the remaining data left to be read from the SmartBuffer instance. + * + * @return { Number } + */ + remaining() { + return this.length - this._readOffset; + } + /** + * Gets the current read offset value of the SmartBuffer instance. + * + * @return { Number } + */ + get readOffset() { + return this._readOffset; + } + /** + * Sets the read offset value of the SmartBuffer instance. + * + * @param offset { Number } - The offset value to set. + */ + set readOffset(offset) { + utils_1.checkOffsetValue(offset); + // Check for bounds. + utils_1.checkTargetOffset(offset, this); + this._readOffset = offset; + } + /** + * Gets the current write offset value of the SmartBuffer instance. + * + * @return { Number } + */ + get writeOffset() { + return this._writeOffset; + } + /** + * Sets the write offset value of the SmartBuffer instance. + * + * @param offset { Number } - The offset value to set. + */ + set writeOffset(offset) { + utils_1.checkOffsetValue(offset); + // Check for bounds. + utils_1.checkTargetOffset(offset, this); + this._writeOffset = offset; + } + /** + * Gets the currently set string encoding of the SmartBuffer instance. + * + * @return { BufferEncoding } The string Buffer encoding currently set. + */ + get encoding() { + return this._encoding; + } + /** + * Sets the string encoding of the SmartBuffer instance. + * + * @param encoding { BufferEncoding } The string Buffer encoding to set. + */ + set encoding(encoding) { + utils_1.checkEncoding(encoding); + this._encoding = encoding; + } + /** + * Gets the underlying internal Buffer. (This includes unmanaged data in the Buffer) + * + * @return { Buffer } The Buffer value. + */ + get internalBuffer() { + return this._buff; + } + /** + * Gets the value of the internal managed Buffer (Includes managed data only) + * + * @param { Buffer } + */ + toBuffer() { + return this._buff.slice(0, this.length); + } + /** + * Gets the String value of the internal managed Buffer + * + * @param encoding { String } The BufferEncoding to display the Buffer as (defaults to instance level encoding). + */ + toString(encoding) { + const encodingVal = typeof encoding === 'string' ? encoding : this._encoding; + // Check for invalid encoding. + utils_1.checkEncoding(encodingVal); + return this._buff.toString(encodingVal, 0, this.length); + } + /** + * Destroys the SmartBuffer instance. + */ + destroy() { + this.clear(); + return this; + } + /** + * Handles inserting and writing strings. + * + * @param value { String } The String value to insert. + * @param isInsert { Boolean } True if inserting a string, false if writing. + * @param arg2 { Number | String } The offset to insert the string at, or the BufferEncoding to use. + * @param encoding { String } The BufferEncoding to use for writing strings (defaults to instance encoding). + */ + _handleString(value, isInsert, arg3, encoding) { + let offsetVal = this._writeOffset; + let encodingVal = this._encoding; + // Check for offset + if (typeof arg3 === 'number') { + offsetVal = arg3; + // Check for encoding + } + else if (typeof arg3 === 'string') { + utils_1.checkEncoding(arg3); + encodingVal = arg3; + } + // Check for encoding (third param) + if (typeof encoding === 'string') { + utils_1.checkEncoding(encoding); + encodingVal = encoding; + } + // Calculate bytelength of string. + const byteLength = Buffer.byteLength(value, encodingVal); + // Ensure there is enough internal Buffer capacity. + if (isInsert) { + this.ensureInsertable(byteLength, offsetVal); + } + else { + this._ensureWriteable(byteLength, offsetVal); + } + // Write value + this._buff.write(value, offsetVal, byteLength, encodingVal); + // Increment internal Buffer write offset; + if (isInsert) { + this._writeOffset += byteLength; + } + else { + // If an offset was given, check to see if we wrote beyond the current writeOffset. + if (typeof arg3 === 'number') { + this._writeOffset = Math.max(this._writeOffset, offsetVal + byteLength); + } + else { + // If no offset was given, we wrote to the end of the SmartBuffer so increment writeOffset. + this._writeOffset += byteLength; + } + } + return this; + } + /** + * Handles writing or insert of a Buffer. + * + * @param value { Buffer } The Buffer to write. + * @param offset { Number } The offset to write the Buffer to. + */ + _handleBuffer(value, isInsert, offset) { + const offsetVal = typeof offset === 'number' ? offset : this._writeOffset; + // Ensure there is enough internal Buffer capacity. + if (isInsert) { + this.ensureInsertable(value.length, offsetVal); + } + else { + this._ensureWriteable(value.length, offsetVal); + } + // Write buffer value + value.copy(this._buff, offsetVal); + // Increment internal Buffer write offset; + if (isInsert) { + this._writeOffset += value.length; + } + else { + // If an offset was given, check to see if we wrote beyond the current writeOffset. + if (typeof offset === 'number') { + this._writeOffset = Math.max(this._writeOffset, offsetVal + value.length); + } + else { + // If no offset was given, we wrote to the end of the SmartBuffer so increment writeOffset. + this._writeOffset += value.length; + } + } + return this; + } + /** + * Ensures that the internal Buffer is large enough to read data. + * + * @param length { Number } The length of the data that needs to be read. + * @param offset { Number } The offset of the data that needs to be read. + */ + ensureReadable(length, offset) { + // Offset value defaults to managed read offset. + let offsetVal = this._readOffset; + // If an offset was provided, use it. + if (typeof offset !== 'undefined') { + // Checks for valid numberic value; + utils_1.checkOffsetValue(offset); + // Overide with custom offset. + offsetVal = offset; + } + // Checks if offset is below zero, or the offset+length offset is beyond the total length of the managed data. + if (offsetVal < 0 || offsetVal + length > this.length) { + throw new Error(utils_1.ERRORS.INVALID_READ_BEYOND_BOUNDS); + } + } + /** + * Ensures that the internal Buffer is large enough to insert data. + * + * @param dataLength { Number } The length of the data that needs to be written. + * @param offset { Number } The offset of the data to be written. + */ + ensureInsertable(dataLength, offset) { + // Checks for valid numberic value; + utils_1.checkOffsetValue(offset); + // Ensure there is enough internal Buffer capacity. + this._ensureCapacity(this.length + dataLength); + // If an offset was provided and its not the very end of the buffer, copy data into appropriate location in regards to the offset. + if (offset < this.length) { + this._buff.copy(this._buff, offset + dataLength, offset, this._buff.length); + } + // Adjust tracked smart buffer length + if (offset + dataLength > this.length) { + this.length = offset + dataLength; + } + else { + this.length += dataLength; + } + } + /** + * Ensures that the internal Buffer is large enough to write data. + * + * @param dataLength { Number } The length of the data that needs to be written. + * @param offset { Number } The offset of the data to be written (defaults to writeOffset). + */ + _ensureWriteable(dataLength, offset) { + const offsetVal = typeof offset === 'number' ? offset : this._writeOffset; + // Ensure enough capacity to write data. + this._ensureCapacity(offsetVal + dataLength); + // Adjust SmartBuffer length (if offset + length is larger than managed length, adjust length) + if (offsetVal + dataLength > this.length) { + this.length = offsetVal + dataLength; + } + } + /** + * Ensures that the internal Buffer is large enough to write at least the given amount of data. + * + * @param minLength { Number } The minimum length of the data needs to be written. + */ + _ensureCapacity(minLength) { + const oldLength = this._buff.length; + if (minLength > oldLength) { + let data = this._buff; + let newLength = (oldLength * 3) / 2 + 1; + if (newLength < minLength) { + newLength = minLength; + } + this._buff = Buffer.allocUnsafe(newLength); + data.copy(this._buff, 0, 0, oldLength); + } + } + /** + * Reads a numeric number value using the provided function. + * + * @typeparam T { number | bigint } The type of the value to be read + * + * @param func { Function(offset: number) => number } The function to read data on the internal Buffer with. + * @param byteSize { Number } The number of bytes read. + * @param offset { Number } The offset to read from (optional). When this is not provided, the managed readOffset is used instead. + * + * @returns { T } the number value + */ + _readNumberValue(func, byteSize, offset) { + this.ensureReadable(byteSize, offset); + // Call Buffer.readXXXX(); + const value = func.call(this._buff, typeof offset === 'number' ? offset : this._readOffset); + // Adjust internal read offset if an optional read offset was not provided. + if (typeof offset === 'undefined') { + this._readOffset += byteSize; + } + return value; + } + /** + * Inserts a numeric number value based on the given offset and value. + * + * @typeparam T { number | bigint } The type of the value to be written + * + * @param func { Function(offset: T, offset?) => number} The function to write data on the internal Buffer with. + * @param byteSize { Number } The number of bytes written. + * @param value { T } The number value to write. + * @param offset { Number } the offset to write the number at (REQUIRED). + * + * @returns SmartBuffer this buffer + */ + _insertNumberValue(func, byteSize, value, offset) { + // Check for invalid offset values. + utils_1.checkOffsetValue(offset); + // Ensure there is enough internal Buffer capacity. (raw offset is passed) + this.ensureInsertable(byteSize, offset); + // Call buffer.writeXXXX(); + func.call(this._buff, value, offset); + // Adjusts internally managed write offset. + this._writeOffset += byteSize; + return this; + } + /** + * Writes a numeric number value based on the given offset and value. + * + * @typeparam T { number | bigint } The type of the value to be written + * + * @param func { Function(offset: T, offset?) => number} The function to write data on the internal Buffer with. + * @param byteSize { Number } The number of bytes written. + * @param value { T } The number value to write. + * @param offset { Number } the offset to write the number at (REQUIRED). + * + * @returns SmartBuffer this buffer + */ + _writeNumberValue(func, byteSize, value, offset) { + // If an offset was provided, validate it. + if (typeof offset === 'number') { + // Check if we're writing beyond the bounds of the managed data. + if (offset < 0) { + throw new Error(utils_1.ERRORS.INVALID_WRITE_BEYOND_BOUNDS); + } + utils_1.checkOffsetValue(offset); + } + // Default to writeOffset if no offset value was given. + const offsetVal = typeof offset === 'number' ? offset : this._writeOffset; + // Ensure there is enough internal Buffer capacity. (raw offset is passed) + this._ensureWriteable(byteSize, offsetVal); + func.call(this._buff, value, offsetVal); + // If an offset was given, check to see if we wrote beyond the current writeOffset. + if (typeof offset === 'number') { + this._writeOffset = Math.max(this._writeOffset, offsetVal + byteSize); + } + else { + // If no numeric offset was given, we wrote to the end of the SmartBuffer so increment writeOffset. + this._writeOffset += byteSize; + } + return this; + } +} +exports.SmartBuffer = SmartBuffer; +//# sourceMappingURL=smartbuffer.js.map \ No newline at end of file diff --git a/ts-ticket-office-service/node_modules/smart-buffer/build/smartbuffer.js.map b/ts-ticket-office-service/node_modules/smart-buffer/build/smartbuffer.js.map new file mode 100644 index 000000000..37f0d6e16 --- /dev/null +++ b/ts-ticket-office-service/node_modules/smart-buffer/build/smartbuffer.js.map @@ -0,0 +1 @@ +{"version":3,"file":"smartbuffer.js","sourceRoot":"","sources":["../src/smartbuffer.ts"],"names":[],"mappings":";;AAAA,mCAGiB;AAcjB,kDAAkD;AAClD,MAAM,wBAAwB,GAAW,IAAI,CAAC;AAE9C,kEAAkE;AAClE,MAAM,4BAA4B,GAAmB,MAAM,CAAC;AAE5D,MAAM,WAAW;IAQf;;;;OAIG;IACH,YAAY,OAA4B;QAZjC,WAAM,GAAW,CAAC,CAAC;QAElB,cAAS,GAAmB,4BAA4B,CAAC;QAEzD,iBAAY,GAAW,CAAC,CAAC;QACzB,gBAAW,GAAW,CAAC,CAAC;QAQ9B,IAAI,WAAW,CAAC,oBAAoB,CAAC,OAAO,CAAC,EAAE;YAC7C,sBAAsB;YACtB,IAAI,OAAO,CAAC,QAAQ,EAAE;gBACpB,qBAAa,CAAC,OAAO,CAAC,QAAQ,CAAC,CAAC;gBAChC,IAAI,CAAC,SAAS,GAAG,OAAO,CAAC,QAAQ,CAAC;aACnC;YAED,iCAAiC;YACjC,IAAI,OAAO,CAAC,IAAI,EAAE;gBAChB,IAAI,uBAAe,CAAC,OAAO,CAAC,IAAI,CAAC,IAAI,OAAO,CAAC,IAAI,GAAG,CAAC,EAAE;oBACrD,IAAI,CAAC,KAAK,GAAG,MAAM,CAAC,WAAW,CAAC,OAAO,CAAC,IAAI,CAAC,CAAC;iBAC/C;qBAAM;oBACL,MAAM,IAAI,KAAK,CAAC,cAAM,CAAC,wBAAwB,CAAC,CAAC;iBAClD;gBACD,2BAA2B;aAC5B;iBAAM,IAAI,OAAO,CAAC,IAAI,EAAE;gBACvB,IAAI,MAAM,CAAC,QAAQ,CAAC,OAAO,CAAC,IAAI,CAAC,EAAE;oBACjC,IAAI,CAAC,KAAK,GAAG,OAAO,CAAC,IAAI,CAAC;oBAC1B,IAAI,CAAC,MAAM,GAAG,OAAO,CAAC,IAAI,CAAC,MAAM,CAAC;iB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C,YAAY,IAAI,QAAQ,CAAC;SAC/B;QAED,OAAO,IAAI,CAAC;IACd,CAAC;CACF;AAE4B,kCAAW"} \ No newline at end of file diff --git a/ts-ticket-office-service/node_modules/smart-buffer/build/utils.js b/ts-ticket-office-service/node_modules/smart-buffer/build/utils.js new file mode 100644 index 000000000..6d5598123 --- /dev/null +++ b/ts-ticket-office-service/node_modules/smart-buffer/build/utils.js @@ -0,0 +1,108 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +const buffer_1 = require("buffer"); +/** + * Error strings + */ +const ERRORS = { + INVALID_ENCODING: 'Invalid encoding provided. Please specify a valid encoding the internal Node.js Buffer supports.', + INVALID_SMARTBUFFER_SIZE: 'Invalid size provided. Size must be a valid integer greater than zero.', + INVALID_SMARTBUFFER_BUFFER: 'Invalid Buffer provided in SmartBufferOptions.', + INVALID_SMARTBUFFER_OBJECT: 'Invalid SmartBufferOptions object supplied to SmartBuffer constructor or factory methods.', + INVALID_OFFSET: 'An invalid offset value was provided.', + INVALID_OFFSET_NON_NUMBER: 'An invalid offset value was provided. A numeric value is required.', + INVALID_LENGTH: 'An invalid length value was provided.', + INVALID_LENGTH_NON_NUMBER: 'An invalid length value was provived. A numeric value is required.', + INVALID_TARGET_OFFSET: 'Target offset is beyond the bounds of the internal SmartBuffer data.', + INVALID_TARGET_LENGTH: 'Specified length value moves cursor beyong the bounds of the internal SmartBuffer data.', + INVALID_READ_BEYOND_BOUNDS: 'Attempted to read beyond the bounds of the managed data.', + INVALID_WRITE_BEYOND_BOUNDS: 'Attempted to write beyond the bounds of the managed data.' +}; +exports.ERRORS = ERRORS; +/** + * Checks if a given encoding is a valid Buffer encoding. (Throws an exception if check fails) + * + * @param { String } encoding The encoding string to check. + */ +function checkEncoding(encoding) { + if (!buffer_1.Buffer.isEncoding(encoding)) { + throw new Error(ERRORS.INVALID_ENCODING); + } +} +exports.checkEncoding = checkEncoding; +/** + * Checks if a given number is a finite integer. (Throws an exception if check fails) + * + * @param { Number } value The number value to check. + */ +function isFiniteInteger(value) { + return typeof value === 'number' && isFinite(value) && isInteger(value); +} +exports.isFiniteInteger = isFiniteInteger; +/** + * Checks if an offset/length value is valid. (Throws an exception if check fails) + * + * @param value The value to check. + * @param offset True if checking an offset, false if checking a length. + */ +function checkOffsetOrLengthValue(value, offset) { + if (typeof value === 'number') { + // Check for non finite/non integers + if (!isFiniteInteger(value) || value < 0) { + throw new Error(offset ? ERRORS.INVALID_OFFSET : ERRORS.INVALID_LENGTH); + } + } + else { + throw new Error(offset ? ERRORS.INVALID_OFFSET_NON_NUMBER : ERRORS.INVALID_LENGTH_NON_NUMBER); + } +} +/** + * Checks if a length value is valid. (Throws an exception if check fails) + * + * @param { Number } length The value to check. + */ +function checkLengthValue(length) { + checkOffsetOrLengthValue(length, false); +} +exports.checkLengthValue = checkLengthValue; +/** + * Checks if a offset value is valid. (Throws an exception if check fails) + * + * @param { Number } offset The value to check. + */ +function checkOffsetValue(offset) { + checkOffsetOrLengthValue(offset, true); +} +exports.checkOffsetValue = checkOffsetValue; +/** + * Checks if a target offset value is out of bounds. (Throws an exception if check fails) + * + * @param { Number } offset The offset value to check. + * @param { SmartBuffer } buff The SmartBuffer instance to check against. + */ +function checkTargetOffset(offset, buff) { + if (offset < 0 || offset > buff.length) { + throw new Error(ERRORS.INVALID_TARGET_OFFSET); + } +} +exports.checkTargetOffset = checkTargetOffset; +/** + * Determines whether a given number is a integer. + * @param value The number to check. + */ +function isInteger(value) { + return typeof value === 'number' && isFinite(value) && Math.floor(value) === value; +} +/** + * Throws if Node.js version is too low to support bigint + */ +function bigIntAndBufferInt64Check(bufferMethod) { + if (typeof BigInt === 'undefined') { + throw new Error('Platform does not support JS BigInt type.'); + } + if (typeof buffer_1.Buffer.prototype[bufferMethod] === 'undefined') { + throw new Error(`Platform does not support Buffer.prototype.${bufferMethod}.`); + } +} +exports.bigIntAndBufferInt64Check = bigIntAndBufferInt64Check; +//# sourceMappingURL=utils.js.map \ No newline at end of file diff --git a/ts-ticket-office-service/node_modules/smart-buffer/build/utils.js.map b/ts-ticket-office-service/node_modules/smart-buffer/build/utils.js.map new file mode 100644 index 000000000..fc7388d3b --- /dev/null +++ b/ts-ticket-office-service/node_modules/smart-buffer/build/utils.js.map @@ -0,0 +1 @@ +{"version":3,"file":"utils.js","sourceRoot":"","sources":["../src/utils.ts"],"names":[],"mappings":";;AACA,mCAAgC;AAEhC;;GAEG;AACH,MAAM,MAAM,GAAG;IACb,gBAAgB,EAAE,kGAAkG;IACpH,wBAAwB,EAAE,wEAAwE;IAClG,0BAA0B,EAAE,gDAAgD;IAC5E,0BAA0B,EAAE,2FAA2F;IACvH,cAAc,EAAE,uCAAuC;IACvD,yBAAyB,EAAE,oEAAoE;IAC/F,cAAc,EAAE,uCAAuC;IACvD,yBAAyB,EAAE,oEAAoE;IAC/F,qBAAqB,EAAE,sEAAsE;IAC7F,qBAAqB,EAAE,yFAAyF;IAChH,0BAA0B,EAAE,0DAA0D;IACtF,2BAA2B,EAAE,2DAA2D;CACzF,CAAC;AAuGA,wBAAM;AArGR;;;;GAIG;AACH,SAAS,aAAa,CAAC,QAAwB;IAC7C,IAAI,CAAC,eAAM,CAAC,UAAU,CAAC,QAAQ,CAAC,EAAE;QAChC,MAAM,IAAI,KAAK,CAAC,MAAM,CAAC,gBAAgB,CAAC,CAAC;KAC1C;AACH,CAAC;AA4F0B,sCAAa;AA1FxC;;;;GAIG;AACH,SAAS,eAAe,CAAC,KAAa;IACpC,OAAO,OAAO,KAAK,KAAK,QAAQ,IAAI,QAAQ,CAAC,KAAK,CAAC,IAAI,SAAS,CAAC,KAAK,CAAC,CAAC;AAC1E,CAAC;AAmFS,0CAAe;AAjFzB;;;;;GAKG;AACH,SAAS,wBAAwB,CAAC,KAAU,EAAE,MAAe;IAC3D,IAAI,OAAO,KAAK,KAAK,QAAQ,EAAE;QAC7B,oCAAoC;QACpC,IAAI,CAAC,eAAe,CAAC,KAAK,CAAC,IAAI,KAAK,GAAG,CAAC,EAAE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AAC;KAChF;AACH,CAAC;AAIsC,8DAAyB"} \ No newline at end of file diff --git a/ts-ticket-office-service/node_modules/smart-buffer/docs/CHANGELOG.md b/ts-ticket-office-service/node_modules/smart-buffer/docs/CHANGELOG.md new file mode 100644 index 000000000..1199a4d6d --- /dev/null +++ b/ts-ticket-office-service/node_modules/smart-buffer/docs/CHANGELOG.md @@ -0,0 +1,70 @@ +# Change Log +## 4.1.0 +> Released 07/24/2019 +* Adds int64 support for node v12+ +* Drops support for node v4 + +## 4.0 +> Released 10/21/2017 +* Major breaking changes arriving in v4. + +### New Features +* Ability to read data from a specific offset. ex: readInt8(5) +* Ability to write over data when an offset is given (see breaking changes) ex: writeInt8(5, 0); +* Ability to set internal read and write offsets. + + + +### Breaking Changes + +* Old constructor patterns have been completely removed. It's now required to use the SmartBuffer.fromXXX() factory constructors. Read more on the v4 docs. +* rewind(), skip(), moveTo() have been removed. +* Internal private properties are now prefixed with underscores (_). +* **All** writeXXX() methods that are given an offset will now **overwrite data** instead of insert +* insertXXX() methods have been added for when you want to insert data at a specific offset (this replaces the old behavior of writeXXX() when an offset was provided) + + +### Other Changes +* Standardizd error messaging +* Standardized offset/length bounds and sanity checking +* General overall cleanup of code. + +## 3.0.3 +> Released 02/19/2017 +* Adds missing type definitions for some internal functions. + +## 3.0.2 +> Released 02/17/2017 + +### Bug Fixes +* Fixes a bug where using readString with a length of zero resulted in reading the remaining data instead of returning an empty string. (Fixed by Seldszar) + +## 3.0.1 +> Released 02/15/2017 + +### Bug Fixes +* Fixes a bug leftover from the TypeScript refactor where .readIntXXX() resulted in .readUIntXXX() being called by mistake. + +## 3.0 +> Released 02/12/2017 + +### Bug Fixes +* readUIntXXXX() methods will now throw an exception if they attempt to read beyond the bounds of the valid buffer data available. + * **Note** This is technically a breaking change, so version is bumped to 3.x. + +## 2.0 +> Relased 01/30/2017 + +### New Features: + +* Entire package re-written in TypeScript (2.1) +* Backwards compatibility is preserved for now +* New factory methods for creating SmartBuffer instances + * SmartBuffer.fromSize() + * SmartBuffer.fromBuffer() + * SmartBuffer.fromOptions() +* New SmartBufferOptions constructor options +* Added additional tests + +### Bug Fixes: +* Fixes a bug where reading null terminated strings may result in an exception. diff --git a/ts-ticket-office-service/node_modules/smart-buffer/docs/README_v3.md b/ts-ticket-office-service/node_modules/smart-buffer/docs/README_v3.md new file mode 100644 index 000000000..b7c48b8b5 --- /dev/null +++ b/ts-ticket-office-service/node_modules/smart-buffer/docs/README_v3.md @@ -0,0 +1,367 @@ +smart-buffer [![Build Status](https://travis-ci.org/JoshGlazebrook/smart-buffer.svg?branch=master)](https://travis-ci.org/JoshGlazebrook/smart-buffer) [![Coverage Status](https://coveralls.io/repos/github/JoshGlazebrook/smart-buffer/badge.svg?branch=master)](https://coveralls.io/github/JoshGlazebrook/smart-buffer?branch=master) +============= + +smart-buffer is a light Buffer wrapper that takes away the need to keep track of what position to read and write data to and from the underlying Buffer. It also adds null terminating string operations and **grows** as you add more data. + +![stats](https://nodei.co/npm/smart-buffer.png?downloads=true&downloadRank=true&stars=true "stats") + +### What it's useful for: + +I created smart-buffer because I wanted to simplify the process of using Buffer for building and reading network packets to send over a socket. Rather than having to keep track of which position I need to write a UInt16 to after adding a string of variable length, I simply don't have to. + +Key Features: +* Proxies all of the Buffer write and read functions. +* Keeps track of read and write positions for you. +* Grows the internal Buffer as you add data to it. +* Useful string operations. (Null terminating strings) +* Allows for inserting values at specific points in the internal Buffer. +* Built in TypeScript +* Type Definitions Provided + +Requirements: +* Node v4.0+ is supported at this time. (Versions prior to 2.0 will work on node 0.10) + + +#### Note: +smart-buffer can be used for writing to an underlying buffer as well as reading from it. It however does not function correctly if you're mixing both read and write operations with each other. + +## Breaking Changes with 2.0 +The latest version (2.0+) is written in TypeScript, and are compiled to ES6 Javascript. This means the earliest Node.js it supports will be 4.x (in strict mode.) If you're using version 6 and above it will work without any issues. From an API standpoint, 2.0 is backwards compatible. The only difference is SmartBuffer is not exported directly as the root module. + +## Breaking Changes with 3.0 +Starting with 3.0, if any of the readIntXXXX() methods are called and the requested data is larger than the bounds of the internally managed valid buffer data, an exception will now be thrown. + +## Installing: + +`npm install smart-buffer` + +or + +`yarn add smart-buffer` + +Note: The published NPM package includes the built javascript library. +If you cloned this repo and wish to build the library manually use: + +`tsc -p ./` + +## Using smart-buffer + +### Example + +Say you were building a packet that had to conform to the following protocol: + +`[PacketType:2][PacketLength:2][Data:XX]` + +To build this packet using the vanilla Buffer class, you would have to count up the length of the data payload beforehand. You would also need to keep track of the current "cursor" position in your Buffer so you write everything in the right places. With smart-buffer you don't have to do either of those things. + +```javascript +// 1.x (javascript) +var SmartBuffer = require('smart-buffer'); + +// 1.x (typescript) +import SmartBuffer = require('smart-buffer'); + +// 2.x+ (javascript) +const SmartBuffer = require('smart-buffer').SmartBuffer; + +// 2.x+ (typescript) +import { SmartBuffer, SmartBufferOptions} from 'smart-buffer'; + +function createLoginPacket(username, password, age, country) { + let packet = new SmartBuffer(); + packet.writeUInt16LE(0x0060); // Login Packet Type/ID + packet.writeStringNT(username); + packet.writeStringNT(password); + packet.writeUInt8(age); + packet.writeStringNT(country); + packet.writeUInt16LE(packet.length - 2, 2); + + return packet.toBuffer(); +} +``` +With the above function, you now can do this: +```javascript +let login = createLoginPacket("Josh", "secret123", 22, "United States"); + +// +``` +Notice that the `[PacketLength:2]` part of the packet was inserted after we had added everything else, and as shown in the Buffer dump above, is in the correct location along with everything else. + +Reading back the packet we created above is just as easy: +```javascript + +let reader = SmartBuffer.fromBuffer(login); + +let logininfo = { + packetType: reader.readUInt16LE(), + packetLength: reader.readUInt16LE(), + username: reader.readStringNT(), + password: reader.readStringNT(), + age: reader.readUInt8(), + country: reader.readStringNT() +}; + +/* +{ + packetType: 96, (0x0060) + packetLength: 30, + username: 'Josh', + password: 'secret123', + age: 22, + country: 'United States' +}; +*/ +``` + +# Api Reference: + +### Constructing a smart-buffer + +smart-buffer has a few different ways to construct an instance. Starting with version 2.0, the following factory methods are preffered. + +```javascript +let SmartBuffer = require('smart-buffer'); + +// Creating SmartBuffer from existing Buffer +let buff = SmartBuffer.fromBuffer(buffer); // Creates instance from buffer. (Uses default utf8 encoding) +let buff = SmartBuffer.fromBuffer(buffer, 'ascii'); // Creates instance from buffer with ascii encoding for Strings. + +// Creating SmartBuffer with specified internal Buffer size. +let buff = SmartBuffer.fromSize(1024); // Creates instance with internal Buffer size of 1024. +let buff = SmartBuffer.fromSize(1024, 'utf8'); // Creates instance with intenral Buffer size of 1024, and utf8 encoding. + +// Creating SmartBuffer with options object. This one specifies size and encoding. +let buff = SmartBuffer.fromOptions({ + size: 1024, + encoding: 'ascii' +}); + +// Creating SmartBuffer with options object. This one specified an existing Buffer. +let buff = SmartBuffer.fromOptions({ + buff: buffer +}); + +// Just want a regular SmartBuffer with all default options? +let buff = new SmartBuffer(); +``` + +## Backwards Compatibility: + +All constructors used prior to 2.0 still are supported. However it's not recommended to use these. + +```javascript +let writer = new SmartBuffer(); // Defaults to utf8, 4096 length internal Buffer. +let writer = new SmartBuffer(1024); // Defaults to utf8, 1024 length internal Buffer. +let writer = new SmartBuffer('ascii'); // Sets to ascii encoding, 4096 length internal buffer. +let writer = new SmartBuffer(1024, 'ascii'); // Sets to ascii encoding, 1024 length internal buffer. +``` + +## Reading Data + +smart-buffer supports all of the common read functions you will find in the vanilla Buffer class. The only difference is, you do not need to specify which location to start reading from. This is possible because as you read data out of a smart-buffer, it automatically progresses an internal read offset/position to know where to pick up from on the next read. + +## Reading Numeric Values + +When numeric values, you simply need to call the function you want, and the data is returned. + +Supported Operations: +* readInt8 +* readInt16BE +* readInt16LE +* readInt32BE +* readInt32LE +* readBigInt64LE +* readBigInt64BE +* readUInt8 +* readUInt16BE +* readUInt16LE +* readUInt32BE +* readUInt32LE +* readBigUInt64LE +* readBigUInt64BE +* readFloatBE +* readFloatLE +* readDoubleBE +* readDoubleLE + +```javascript +let reader = new SmartBuffer(somebuffer); +let num = reader.readInt8(); +``` + +## Reading String Values + +When reading String values, you can either choose to read a null terminated string, or a string of a specified length. + +### SmartBuffer.readStringNT( [encoding] ) +> `String` **String encoding to use** - Defaults to the encoding set in the constructor. + +returns `String` + +> Note: When readStringNT is called and there is no null character found, smart-buffer will read to the end of the internal Buffer. + +### SmartBuffer.readString( [length] ) +### SmartBuffer.readString( [encoding] ) +### SmartBuffer.readString( [length], [encoding] ) +> `Number` **Length of the string to read** + +> `String` **String encoding to use** - Defaults to the encoding set in the constructor, or utf8. + +returns `String` + +> Note: When readString is called without a specified length, smart-buffer will read to the end of the internal Buffer. + + + +## Reading Buffer Values + +### SmartBuffer.readBuffer( length ) +> `Number` **Length of data to read into a Buffer** + +returns `Buffer` + +> Note: This function uses `slice` to retrieve the Buffer. + + +### SmartBuffer.readBufferNT() + +returns `Buffer` + +> Note: This reads the next sequence of bytes in the buffer until a null (0x00) value is found. (Null terminated buffer) +> Note: This function uses `slice` to retrieve the Buffer. + + +## Writing Data + +smart-buffer supports all of the common write functions you will find in the vanilla Buffer class. The only difference is, you do not need to specify which location to write to in your Buffer by default. You do however have the option of **inserting** a piece of data into your smart-buffer at a given location. + + +## Writing Numeric Values + + +For numeric values, you simply need to call the function you want, and the data is written at the end of the internal Buffer's current write position. You can specify a offset/position to **insert** the given value at, but keep in mind this does not override data at the given position. This feature also does not work properly when inserting a value beyond the current internal length of the smart-buffer (length being the .length property of the smart-buffer instance you're writing to) + +Supported Operations: +* writeInt8 +* writeInt16BE +* writeInt16LE +* writeInt32BE +* writeInt32LE +* writeBigInt64BE +* writeBigInt64LE +* writeUInt8 +* writeUInt16BE +* writeUInt16LE +* writeUInt32BE +* writeUInt32LE +* writeBigUInt64BE +* writeBigUInt64LE +* writeFloatBE +* writeFloatLE +* writeDoubleBE +* writeDoubleLE + +The following signature is the same for all the above functions: + +### SmartBuffer.writeInt8( value, [offset] ) +> `Number` **A valid Int8 number** + +> `Number` **The position to insert this value at** + +returns this + +> Note: All write operations return `this` to allow for chaining. + +## Writing String Values + +When reading String values, you can either choose to write a null terminated string, or a non null terminated string. + +### SmartBuffer.writeStringNT( value, [offset], [encoding] ) +### SmartBuffer.writeStringNT( value, [offset] ) +### SmartBuffer.writeStringNT( value, [encoding] ) +> `String` **String value to write** + +> `Number` **The position to insert this String at** + +> `String` **The String encoding to use.** - Defaults to the encoding set in the constructor, or utf8. + +returns this + +### SmartBuffer.writeString( value, [offset], [encoding] ) +### SmartBuffer.writeString( value, [offset] ) +### SmartBuffer.writeString( value, [encoding] ) +> `String` **String value to write** + +> `Number` **The position to insert this String at** + +> `String` **The String encoding to use** - Defaults to the encoding set in the constructor, or utf8. + +returns this + + +## Writing Buffer Values + +### SmartBuffer.writeBuffer( value, [offset] ) +> `Buffer` **Buffer value to write** + +> `Number` **The position to insert this Buffer's content at** + +returns this + +### SmartBuffer.writeBufferNT( value, [offset] ) +> `Buffer` **Buffer value to write** + +> `Number` **The position to insert this Buffer's content at** + +returns this + + +## Utility Functions + +### SmartBuffer.clear() +Resets the SmartBuffer to its default state where it can be reused for reading or writing. + +### SmartBuffer.remaining() + +returns `Number` The amount of data left to read based on the current read Position. + +### SmartBuffer.skip( value ) +> `Number` **The amount of bytes to skip ahead** + +Skips the read position ahead by the given value. + +returns this + +### SmartBuffer.rewind( value ) +> `Number` **The amount of bytes to reward backwards** + +Rewinds the read position backwards by the given value. + +returns this + +### SmartBuffer.moveTo( position ) +> `Number` **The point to skip the read position to** + +Moves the read position to the given point. +returns this + +### SmartBuffer.toBuffer() + +returns `Buffer` A Buffer containing the contents of the internal Buffer. + +> Note: This uses the slice function. + +### SmartBuffer.toString( [encoding] ) +> `String` **The String encoding to use** - Defaults to the encoding set in the constructor, or utf8. + +returns `String` The internal Buffer in String representation. + +## Properties + +### SmartBuffer.length + +returns `Number` **The length of the data that is being tracked in the internal Buffer** - Does NOT return the absolute length of the internal Buffer being written to. + +## License + +This work is licensed under the [MIT license](http://en.wikipedia.org/wiki/MIT_License). \ No newline at end of file diff --git a/ts-ticket-office-service/node_modules/smart-buffer/docs/ROADMAP.md b/ts-ticket-office-service/node_modules/smart-buffer/docs/ROADMAP.md new file mode 100644 index 000000000..e69de29bb diff --git a/ts-ticket-office-service/node_modules/smart-buffer/package.json b/ts-ticket-office-service/node_modules/smart-buffer/package.json new file mode 100644 index 000000000..2f326f248 --- /dev/null +++ b/ts-ticket-office-service/node_modules/smart-buffer/package.json @@ -0,0 +1,79 @@ +{ + "name": "smart-buffer", + "version": "4.2.0", + "description": "smart-buffer is a Buffer wrapper that adds automatic read & write offset tracking, string operations, data insertions, and more.", + "main": "build/smartbuffer.js", + "contributors": ["syvita"], + "homepage": "https://github.com/JoshGlazebrook/smart-buffer/", + "repository": { + "type": "git", + "url": "https://github.com/JoshGlazebrook/smart-buffer.git" + }, + "bugs": { + "url": "https://github.com/JoshGlazebrook/smart-buffer/issues" + }, + "keywords": [ + "buffer", + "smart", + "packet", + "serialize", + "network", + "cursor", + "simple" + ], + "engines": { + "node": ">= 6.0.0", + "npm": ">= 3.0.0" + }, + "author": "Josh Glazebrook", + "license": "MIT", + "readmeFilename": "README.md", + "devDependencies": { + "@types/chai": "4.1.7", + "@types/mocha": "5.2.7", + "@types/node": "^12.0.0", + "chai": "4.2.0", + "coveralls": "3.0.5", + "istanbul": "^0.4.5", + "mocha": "6.2.0", + "mocha-lcov-reporter": "^1.3.0", + "nyc": "14.1.1", + "source-map-support": "0.5.12", + "ts-node": "8.3.0", + "tslint": "5.18.0", + "typescript": "^3.2.1" + }, + "typings": "typings/smartbuffer.d.ts", + "dependencies": {}, + "scripts": { + "prepublish": "npm install -g typescript && npm run build", + "test": "NODE_ENV=test mocha --recursive --require ts-node/register test/**/*.ts", + "coverage": "NODE_ENV=test nyc npm test", + "coveralls": "NODE_ENV=test nyc npm test && nyc report --reporter=text-lcov | coveralls", + "lint": "tslint --type-check --project tsconfig.json 'src/**/*.ts'", + "build": "tsc -p ./" + }, + "nyc": { + "extension": [ + ".ts", + ".tsx" + ], + "include": [ + "src/*.ts", + "src/**/*.ts" + ], + "exclude": [ + "**.*.d.ts", + "node_modules", + "typings" + ], + "require": [ + "ts-node/register" + ], + "reporter": [ + "json", + "html" + ], + "all": true + } +} diff --git a/ts-ticket-office-service/node_modules/socks/.eslintrc.cjs b/ts-ticket-office-service/node_modules/socks/.eslintrc.cjs new file mode 100644 index 000000000..cc5d089e6 --- /dev/null +++ b/ts-ticket-office-service/node_modules/socks/.eslintrc.cjs @@ -0,0 +1,11 @@ +module.exports = { + root: true, + parser: '@typescript-eslint/parser', + plugins: [ + '@typescript-eslint', + ], + extends: [ + 'eslint:recommended', + 'plugin:@typescript-eslint/recommended', + ], +}; \ No newline at end of file diff --git a/ts-ticket-office-service/node_modules/socks/LICENSE b/ts-ticket-office-service/node_modules/socks/LICENSE new file mode 100644 index 000000000..b2442a9e7 --- /dev/null +++ b/ts-ticket-office-service/node_modules/socks/LICENSE @@ -0,0 +1,20 @@ +The MIT License (MIT) + +Copyright (c) 2013 Josh Glazebrook + +Permission is hereby granted, free of charge, to any person obtaining a copy of +this software and associated documentation files (the "Software"), to deal in +the Software without restriction, including without limitation the rights to +use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of +the Software, and to permit persons to whom the Software is furnished to do so, +subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS +FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR +COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER +IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN +CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/ts-ticket-office-service/node_modules/socks/README.md b/ts-ticket-office-service/node_modules/socks/README.md new file mode 100644 index 000000000..b796220c6 --- /dev/null +++ b/ts-ticket-office-service/node_modules/socks/README.md @@ -0,0 +1,686 @@ +# socks [![Build Status](https://travis-ci.org/JoshGlazebrook/socks.svg?branch=master)](https://travis-ci.org/JoshGlazebrook/socks) [![Coverage Status](https://coveralls.io/repos/github/JoshGlazebrook/socks/badge.svg?branch=master)](https://coveralls.io/github/JoshGlazebrook/socks?branch=v2) + +Fully featured SOCKS proxy client supporting SOCKSv4, SOCKSv4a, and SOCKSv5. Includes Bind and Associate functionality. + +> Looking for Node.js agent? Check [node-socks-proxy-agent](https://github.com/TooTallNate/node-socks-proxy-agent). + +### Features + +* Supports SOCKS v4, v4a, v5, and v5h protocols. +* Supports the CONNECT, BIND, and ASSOCIATE commands. +* Supports callbacks, promises, and events for proxy connection creation async flow control. +* Supports proxy chaining (CONNECT only). +* Supports user/password authentication. +* Supports custom authentication. +* Built in UDP frame creation & parse functions. +* Created with TypeScript, type definitions are provided. + +### Requirements + +* Node.js v10.0+ (Please use [v1](https://github.com/JoshGlazebrook/socks/tree/82d83923ad960693d8b774cafe17443ded7ed584) for older versions of Node.js) + +### Looking for v1? +* Docs for v1 are available [here](https://github.com/JoshGlazebrook/socks/tree/82d83923ad960693d8b774cafe17443ded7ed584) + +## Installation + +`yarn add socks` + +or + +`npm install --save socks` + +## Usage + +```typescript +// TypeScript +import { SocksClient, SocksClientOptions, SocksClientChainOptions } from 'socks'; + +// ES6 JavaScript +import { SocksClient } from 'socks'; + +// Legacy JavaScript +const SocksClient = require('socks').SocksClient; +``` + +## Quick Start Example + +Connect to github.com (192.30.253.113) on port 80, using a SOCKS proxy. + +```javascript +const options = { + proxy: { + host: '159.203.75.200', // ipv4 or ipv6 or hostname + port: 1080, + type: 5 // Proxy version (4 or 5) + }, + + command: 'connect', // SOCKS command (createConnection factory function only supports the connect command) + + destination: { + host: '192.30.253.113', // github.com (hostname lookups are supported with SOCKS v4a and 5) + port: 80 + } +}; + +// Async/Await +try { + const info = await SocksClient.createConnection(options); + + console.log(info.socket); + // (this is a raw net.Socket that is established to the destination host through the given proxy server) +} catch (err) { + // Handle errors +} + +// Promises +SocksClient.createConnection(options) +.then(info => { + console.log(info.socket); + // (this is a raw net.Socket that is established to the destination host through the given proxy server) +}) +.catch(err => { + // Handle errors +}); + +// Callbacks +SocksClient.createConnection(options, (err, info) => { + if (!err) { + console.log(info.socket); + // (this is a raw net.Socket that is established to the destination host through the given proxy server) + } else { + // Handle errors + } +}); +``` + +## Chaining Proxies + +**Note:** Chaining is only supported when using the SOCKS connect command, and chaining can only be done through the special factory chaining function. + +This example makes a proxy chain through two SOCKS proxies to ip-api.com. Once the connection to the destination is established it sends an HTTP request to get a JSON response that returns ip info for the requesting ip. + +```javascript +const options = { + destination: { + host: 'ip-api.com', // host names are supported with SOCKS v4a and SOCKS v5. + port: 80 + }, + command: 'connect', // Only the connect command is supported when chaining proxies. + proxies: [ // The chain order is the order in the proxies array, meaning the last proxy will establish a connection to the destination. + { + host: '159.203.75.235', // ipv4, ipv6, or hostname + port: 1081, + type: 5 + }, + { + host: '104.131.124.203', // ipv4, ipv6, or hostname + port: 1081, + type: 5 + } + ] +} + +// Async/Await +try { + const info = await SocksClient.createConnectionChain(options); + + console.log(info.socket); + // (this is a raw net.Socket that is established to the destination host through the given proxy servers) + + console.log(info.socket.remoteAddress) // The remote address of the returned socket is the first proxy in the chain. + // 159.203.75.235 + + info.socket.write('GET /json HTTP/1.1\nHost: ip-api.com\n\n'); + info.socket.on('data', (data) => { + console.log(data.toString()); // ip-api.com sees that the last proxy in the chain (104.131.124.203) is connected to it. + /* + HTTP/1.1 200 OK + Access-Control-Allow-Origin: * + Content-Type: application/json; charset=utf-8 + Date: Sun, 24 Dec 2017 03:47:51 GMT + Content-Length: 300 + + { + "as":"AS14061 Digital Ocean, Inc.", + "city":"Clifton", + "country":"United States", + "countryCode":"US", + "isp":"Digital Ocean", + "lat":40.8326, + "lon":-74.1307, + "org":"Digital Ocean", + "query":"104.131.124.203", + "region":"NJ", + "regionName":"New Jersey", + "status":"success", + "timezone":"America/New_York", + "zip":"07014" + } + */ + }); +} catch (err) { + // Handle errors +} + +// Promises +SocksClient.createConnectionChain(options) +.then(info => { + console.log(info.socket); + // (this is a raw net.Socket that is established to the destination host through the given proxy server) + + console.log(info.socket.remoteAddress) // The remote address of the returned socket is the first proxy in the chain. + // 159.203.75.235 + + info.socket.write('GET /json HTTP/1.1\nHost: ip-api.com\n\n'); + info.socket.on('data', (data) => { + console.log(data.toString()); // ip-api.com sees that the last proxy in the chain (104.131.124.203) is connected to it. + /* + HTTP/1.1 200 OK + Access-Control-Allow-Origin: * + Content-Type: application/json; charset=utf-8 + Date: Sun, 24 Dec 2017 03:47:51 GMT + Content-Length: 300 + + { + "as":"AS14061 Digital Ocean, Inc.", + "city":"Clifton", + "country":"United States", + "countryCode":"US", + "isp":"Digital Ocean", + "lat":40.8326, + "lon":-74.1307, + "org":"Digital Ocean", + "query":"104.131.124.203", + "region":"NJ", + "regionName":"New Jersey", + "status":"success", + "timezone":"America/New_York", + "zip":"07014" + } + */ + }); +}) +.catch(err => { + // Handle errors +}); + +// Callbacks +SocksClient.createConnectionChain(options, (err, info) => { + if (!err) { + console.log(info.socket); + // (this is a raw net.Socket that is established to the destination host through the given proxy server) + + console.log(info.socket.remoteAddress) // The remote address of the returned socket is the first proxy in the chain. + // 159.203.75.235 + + info.socket.write('GET /json HTTP/1.1\nHost: ip-api.com\n\n'); + info.socket.on('data', (data) => { + console.log(data.toString()); // ip-api.com sees that the last proxy in the chain (104.131.124.203) is connected to it. + /* + HTTP/1.1 200 OK + Access-Control-Allow-Origin: * + Content-Type: application/json; charset=utf-8 + Date: Sun, 24 Dec 2017 03:47:51 GMT + Content-Length: 300 + + { + "as":"AS14061 Digital Ocean, Inc.", + "city":"Clifton", + "country":"United States", + "countryCode":"US", + "isp":"Digital Ocean", + "lat":40.8326, + "lon":-74.1307, + "org":"Digital Ocean", + "query":"104.131.124.203", + "region":"NJ", + "regionName":"New Jersey", + "status":"success", + "timezone":"America/New_York", + "zip":"07014" + } + */ + }); + } else { + // Handle errors + } +}); +``` + +## Bind Example (TCP Relay) + +When the bind command is sent to a SOCKS v4/v5 proxy server, the proxy server starts listening on a new TCP port and the proxy relays then remote host information back to the client. When another remote client connects to the proxy server on this port the SOCKS proxy sends a notification that an incoming connection has been accepted to the initial client and a full duplex stream is now established to the initial client and the client that connected to that special port. + +```javascript +const options = { + proxy: { + host: '159.203.75.235', // ipv4, ipv6, or hostname + port: 1081, + type: 5 + }, + + command: 'bind', + + // When using BIND, the destination should be the remote client that is expected to connect to the SOCKS proxy. Using 0.0.0.0 makes the Proxy accept any incoming connection on that port. + destination: { + host: '0.0.0.0', + port: 0 + } +}; + +// Creates a new SocksClient instance. +const client = new SocksClient(options); + +// When the SOCKS proxy has bound a new port and started listening, this event is fired. +client.on('bound', info => { + console.log(info.remoteHost); + /* + { + host: "159.203.75.235", + port: 57362 + } + */ +}); + +// When a client connects to the newly bound port on the SOCKS proxy, this event is fired. +client.on('established', info => { + // info.remoteHost is the remote address of the client that connected to the SOCKS proxy. + console.log(info.remoteHost); + /* + host: 67.171.34.23, + port: 49823 + */ + + console.log(info.socket); + // (This is a raw net.Socket that is a connection between the initial client and the remote client that connected to the proxy) + + // Handle received data... + info.socket.on('data', data => { + console.log('recv', data); + }); +}); + +// An error occurred trying to establish this SOCKS connection. +client.on('error', err => { + console.error(err); +}); + +// Start connection to proxy +client.connect(); +``` + +## Associate Example (UDP Relay) + +When the associate command is sent to a SOCKS v5 proxy server, it sets up a UDP relay that allows the client to send UDP packets to a remote host through the proxy server, and also receive UDP packet responses back through the proxy server. + +```javascript +const options = { + proxy: { + host: '159.203.75.235', // ipv4, ipv6, or hostname + port: 1081, + type: 5 + }, + + command: 'associate', + + // When using associate, the destination should be the remote client that is expected to send UDP packets to the proxy server to be forwarded. This should be your local ip, or optionally the wildcard address (0.0.0.0) UDP Client <-> Proxy <-> UDP Client + destination: { + host: '0.0.0.0', + port: 0 + } +}; + +// Create a local UDP socket for sending packets to the proxy. +const udpSocket = dgram.createSocket('udp4'); +udpSocket.bind(); + +// Listen for incoming UDP packets from the proxy server. +udpSocket.on('message', (message, rinfo) => { + console.log(SocksClient.parseUDPFrame(message)); + /* + { frameNumber: 0, + remoteHost: { host: '165.227.108.231', port: 4444 }, // The remote host that replied with a UDP packet + data: // The data + } + */ +}); + +let client = new SocksClient(associateOptions); + +// When the UDP relay is established, this event is fired and includes the UDP relay port to send data to on the proxy server. +client.on('established', info => { + console.log(info.remoteHost); + /* + { + host: '159.203.75.235', + port: 44711 + } + */ + + // Send 'hello' to 165.227.108.231:4444 + const packet = SocksClient.createUDPFrame({ + remoteHost: { host: '165.227.108.231', port: 4444 }, + data: Buffer.from(line) + }); + udpSocket.send(packet, info.remoteHost.port, info.remoteHost.host); +}); + +// Start connection +client.connect(); +``` + +**Note:** The associate TCP connection to the proxy must remain open for the UDP relay to work. + +## Additional Examples + +[Documentation](docs/index.md) + + +## Migrating from v1 + +Looking for a guide to migrate from v1? Look [here](docs/migratingFromV1.md) + +## Api Reference: + +**Note:** socks includes full TypeScript definitions. These can even be used without using TypeScript as most IDEs (such as VS Code) will use these type definition files for auto completion intellisense even in JavaScript files. + +* Class: SocksClient + * [new SocksClient(options[, callback])](#new-socksclientoptions) + * [Class Method: SocksClient.createConnection(options[, callback])](#class-method-socksclientcreateconnectionoptions-callback) + * [Class Method: SocksClient.createConnectionChain(options[, callback])](#class-method-socksclientcreateconnectionchainoptions-callback) + * [Class Method: SocksClient.createUDPFrame(options)](#class-method-socksclientcreateudpframedetails) + * [Class Method: SocksClient.parseUDPFrame(data)](#class-method-socksclientparseudpframedata) + * [Event: 'error'](#event-error) + * [Event: 'bound'](#event-bound) + * [Event: 'established'](#event-established) + * [client.connect()](#clientconnect) + * [client.socksClientOptions](#clientconnect) + +### SocksClient + +SocksClient establishes SOCKS proxy connections to remote destination hosts. These proxy connections are fully transparent to the server and once established act as full duplex streams. SOCKS v4, v4a, v5, and v5h are supported, as well as the connect, bind, and associate commands. + +SocksClient supports creating connections using callbacks, promises, and async/await flow control using two static factory functions createConnection and createConnectionChain. It also internally extends EventEmitter which results in allowing event handling based async flow control. + +**SOCKS Compatibility Table** + +Note: When using 4a please specify type: 4, and when using 5h please specify type 5. + +| Socks Version | TCP | UDP | IPv4 | IPv6 | Hostname | +| --- | :---: | :---: | :---: | :---: | :---: | +| SOCKS v4 | ✅ | ❌ | ✅ | ❌ | ❌ | +| SOCKS v4a | ✅ | ❌ | ✅ | ❌ | ✅ | +| SOCKS v5 (includes v5h) | ✅ | ✅ | ✅ | ✅ | ✅ | + +### new SocksClient(options) + +* ```options``` {SocksClientOptions} - An object describing the SOCKS proxy to use, the command to send and establish, and the destination host to connect to. + +### SocksClientOptions + +```typescript +{ + proxy: { + host: '159.203.75.200', // ipv4, ipv6, or hostname + port: 1080, + type: 5, // Proxy version (4 or 5). For v4a use 4, for v5h use 5. + + // Optional fields + userId: 'some username', // Used for SOCKS4 userId auth, and SOCKS5 user/pass auth in conjunction with password. + password: 'some password', // Used in conjunction with userId for user/pass auth for SOCKS5 proxies. + custom_auth_method: 0x80, // If using a custom auth method, specify the type here. If this is set, ALL other custom_auth_*** options must be set as well. + custom_auth_request_handler: async () =>. { + // This will be called when it's time to send the custom auth handshake. You must return a Buffer containing the data to send as your authentication. + return Buffer.from([0x01,0x02,0x03]); + }, + // This is the expected size (bytes) of the custom auth response from the proxy server. + custom_auth_response_size: 2, + // This is called when the auth response is received. The received packet is passed in as a Buffer, and you must return a boolean indicating the response from the server said your custom auth was successful or failed. + custom_auth_response_handler: async (data) => { + return data[1] === 0x00; + } + }, + + command: 'connect', // connect, bind, associate + + destination: { + host: '192.30.253.113', // ipv4, ipv6, hostname. Hostnames work with v4a and v5. + port: 80 + }, + + // Optional fields + timeout: 30000, // How long to wait to establish a proxy connection. (defaults to 30 seconds) + + set_tcp_nodelay: true // If true, will turn on the underlying sockets TCP_NODELAY option. +} +``` + +### Class Method: SocksClient.createConnection(options[, callback]) +* ```options``` { SocksClientOptions } - An object describing the SOCKS proxy to use, the command to send and establish, and the destination host to connect to. +* ```callback``` { Function } - Optional callback function that is called when the proxy connection is established, or an error occurs. +* ```returns``` { Promise } - A Promise is returned that is resolved when the proxy connection is established, or rejected when an error occurs. + +Creates a new proxy connection through the given proxy to the given destination host. This factory function supports callbacks and promises for async flow control. + +**Note:** If a callback function is provided, the promise will always resolve regardless of an error occurring. Please be sure to exclusively use either promises or callbacks when using this factory function. + +```typescript +const options = { + proxy: { + host: '159.203.75.200', // ipv4, ipv6, or hostname + port: 1080, + type: 5 // Proxy version (4 or 5) + }, + + command: 'connect', // connect, bind, associate + + destination: { + host: '192.30.253.113', // ipv4, ipv6, or hostname + port: 80 + } +} + +// Await/Async (uses a Promise) +try { + const info = await SocksClient.createConnection(options); + console.log(info); + /* + { + socket: , // Raw net.Socket + } + */ + / (this is a raw net.Socket that is established to the destination host through the given proxy server) + +} catch (err) { + // Handle error... +} + +// Promise +SocksClient.createConnection(options) +.then(info => { + console.log(info); + /* + { + socket: , // Raw net.Socket + } + */ +}) +.catch(err => { + // Handle error... +}); + +// Callback +SocksClient.createConnection(options, (err, info) => { + if (!err) { + console.log(info); + /* + { + socket: , // Raw net.Socket + } + */ + } else { + // Handle error... + } +}); +``` + +### Class Method: SocksClient.createConnectionChain(options[, callback]) +* ```options``` { SocksClientChainOptions } - An object describing a list of SOCKS proxies to use, the command to send and establish, and the destination host to connect to. +* ```callback``` { Function } - Optional callback function that is called when the proxy connection chain is established, or an error occurs. +* ```returns``` { Promise } - A Promise is returned that is resolved when the proxy connection chain is established, or rejected when an error occurs. + +Creates a new proxy connection chain through a list of at least two SOCKS proxies to the given destination host. This factory method supports callbacks and promises for async flow control. + +**Note:** If a callback function is provided, the promise will always resolve regardless of an error occurring. Please be sure to exclusively use either promises or callbacks when using this factory function. + +**Note:** At least two proxies must be provided for the chain to be established. + +```typescript +const options = { + proxies: [ // The chain order is the order in the proxies array, meaning the last proxy will establish a connection to the destination. + { + host: '159.203.75.235', // ipv4, ipv6, or hostname + port: 1081, + type: 5 + }, + { + host: '104.131.124.203', // ipv4, ipv6, or hostname + port: 1081, + type: 5 + } + ] + + command: 'connect', // Only connect is supported in chaining mode. + + destination: { + host: '192.30.253.113', // ipv4, ipv6, hostname + port: 80 + } +} +``` + +### Class Method: SocksClient.createUDPFrame(details) +* ```details``` { SocksUDPFrameDetails } - An object containing the remote host, frame number, and frame data to use when creating a SOCKS UDP frame packet. +* ```returns``` { Buffer } - A Buffer containing all of the UDP frame data. + +Creates a SOCKS UDP frame relay packet that is sent and received via a SOCKS proxy when using the associate command for UDP packet forwarding. + +**SocksUDPFrameDetails** + +```typescript +{ + frameNumber: 0, // The frame number (used for breaking up larger packets) + + remoteHost: { // The remote host to have the proxy send data to, or the remote host that send this data. + host: '1.2.3.4', + port: 1234 + }, + + data: // A Buffer instance of data to include in the packet (actual data sent to the remote host) +} +interface SocksUDPFrameDetails { + // The frame number of the packet. + frameNumber?: number; + + // The remote host. + remoteHost: SocksRemoteHost; + + // The packet data. + data: Buffer; +} +``` + +### Class Method: SocksClient.parseUDPFrame(data) +* ```data``` { Buffer } - A Buffer instance containing SOCKS UDP frame data to parse. +* ```returns``` { SocksUDPFrameDetails } - An object containing the remote host, frame number, and frame data of the SOCKS UDP frame. + +```typescript +const frame = SocksClient.parseUDPFrame(data); +console.log(frame); +/* +{ + frameNumber: 0, + remoteHost: { + host: '1.2.3.4', + port: 1234 + }, + data: +} +*/ +``` + +Parses a Buffer instance and returns the parsed SocksUDPFrameDetails object. + +## Event: 'error' +* ```err``` { SocksClientError } - An Error object containing an error message and the original SocksClientOptions. + +This event is emitted if an error occurs when trying to establish the proxy connection. + +## Event: 'bound' +* ```info``` { SocksClientBoundEvent } An object containing a Socket and SocksRemoteHost info. + +This event is emitted when using the BIND command on a remote SOCKS proxy server. This event indicates the proxy server is now listening for incoming connections on a specified port. + +**SocksClientBoundEvent** +```typescript +{ + socket: net.Socket, // The underlying raw Socket + remoteHost: { + host: '1.2.3.4', // The remote host that is listening (usually the proxy itself) + port: 4444 // The remote port the proxy is listening on for incoming connections (when using BIND). + } +} +``` + +## Event: 'established' +* ```info``` { SocksClientEstablishedEvent } An object containing a Socket and SocksRemoteHost info. + +This event is emitted when the following conditions are met: +1. When using the CONNECT command, and a proxy connection has been established to the remote host. +2. When using the BIND command, and an incoming connection has been accepted by the proxy and a TCP relay has been established. +3. When using the ASSOCIATE command, and a UDP relay has been established. + +When using BIND, 'bound' is first emitted to indicate the SOCKS server is waiting for an incoming connection, and provides the remote port the SOCKS server is listening on. + +When using ASSOCIATE, 'established' is emitted with the remote UDP port the SOCKS server is accepting UDP frame packets on. + +**SocksClientEstablishedEvent** +```typescript +{ + socket: net.Socket, // The underlying raw Socket + remoteHost: { + host: '1.2.3.4', // The remote host that is listening (usually the proxy itself) + port: 52738 // The remote port the proxy is listening on for incoming connections (when using BIND). + } +} +``` + +## client.connect() + +Starts connecting to the remote SOCKS proxy server to establish a proxy connection to the destination host. + +## client.socksClientOptions +* ```returns``` { SocksClientOptions } The options that were passed to the SocksClient. + +Gets the options that were passed to the SocksClient when it was created. + + +**SocksClientError** +```typescript +{ // Subclassed from Error. + message: 'An error has occurred', + options: { + // SocksClientOptions + } +} +``` + +# Further Reading: + +Please read the SOCKS 5 specifications for more information on how to use BIND and Associate. +http://www.ietf.org/rfc/rfc1928.txt + +# License + +This work is licensed under the [MIT license](http://en.wikipedia.org/wiki/MIT_License). diff --git a/ts-ticket-office-service/node_modules/socks/build/client/socksclient.js b/ts-ticket-office-service/node_modules/socks/build/client/socksclient.js new file mode 100644 index 000000000..05da4baa4 --- /dev/null +++ b/ts-ticket-office-service/node_modules/socks/build/client/socksclient.js @@ -0,0 +1,795 @@ +"use strict"; +var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } + function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); +}; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.SocksClientError = exports.SocksClient = void 0; +const events_1 = require("events"); +const net = require("net"); +const ip = require("ip"); +const smart_buffer_1 = require("smart-buffer"); +const constants_1 = require("../common/constants"); +const helpers_1 = require("../common/helpers"); +const receivebuffer_1 = require("../common/receivebuffer"); +const util_1 = require("../common/util"); +Object.defineProperty(exports, "SocksClientError", { enumerable: true, get: function () { return util_1.SocksClientError; } }); +class SocksClient extends events_1.EventEmitter { + constructor(options) { + super(); + this.options = Object.assign({}, options); + // Validate SocksClientOptions + (0, helpers_1.validateSocksClientOptions)(options); + // Default state + this.setState(constants_1.SocksClientState.Created); + } + /** + * Creates a new SOCKS connection. + * + * Note: Supports callbacks and promises. Only supports the connect command. + * @param options { SocksClientOptions } Options. + * @param callback { Function } An optional callback function. + * @returns { Promise } + */ + static createConnection(options, callback) { + return new Promise((resolve, reject) => { + // Validate SocksClientOptions + try { + (0, helpers_1.validateSocksClientOptions)(options, ['connect']); + } + catch (err) { + if (typeof callback === 'function') { + callback(err); + // eslint-disable-next-line @typescript-eslint/no-explicit-any + return resolve(err); // Resolves pending promise (prevents memory leaks). + } + else { + return reject(err); + } + } + const client = new SocksClient(options); + client.connect(options.existing_socket); + client.once('established', (info) => { + client.removeAllListeners(); + if (typeof callback === 'function') { + callback(null, info); + resolve(info); // Resolves pending promise (prevents memory leaks). + } + else { + resolve(info); + } + }); + // Error occurred, failed to establish connection. + client.once('error', (err) => { + client.removeAllListeners(); + if (typeof callback === 'function') { + callback(err); + // eslint-disable-next-line @typescript-eslint/no-explicit-any + resolve(err); // Resolves pending promise (prevents memory leaks). + } + else { + reject(err); + } + }); + }); + } + /** + * Creates a new SOCKS connection chain to a destination host through 2 or more SOCKS proxies. + * + * Note: Supports callbacks and promises. Only supports the connect method. + * Note: Implemented via createConnection() factory function. + * @param options { SocksClientChainOptions } Options + * @param callback { Function } An optional callback function. + * @returns { Promise } + */ + static createConnectionChain(options, callback) { + // eslint-disable-next-line no-async-promise-executor + return new Promise((resolve, reject) => __awaiter(this, void 0, void 0, function* () { + // Validate SocksClientChainOptions + try { + (0, helpers_1.validateSocksClientChainOptions)(options); + } + catch (err) { + if (typeof callback === 'function') { + callback(err); + // eslint-disable-next-line @typescript-eslint/no-explicit-any + return resolve(err); // Resolves pending promise (prevents memory leaks). + } + else { + return reject(err); + } + } + let sock; + // Shuffle proxies + if (options.randomizeChain) { + (0, util_1.shuffleArray)(options.proxies); + } + try { + for (let i = 0; i < options.proxies.length; i++) { + const nextProxy = options.proxies[i]; + // If we've reached the last proxy in the chain, the destination is the actual destination, otherwise it's the next proxy. + const nextDestination = i === options.proxies.length - 1 + ? options.destination + : { + host: options.proxies[i + 1].host || + options.proxies[i + 1].ipaddress, + port: options.proxies[i + 1].port, + }; + // Creates the next connection in the chain. + const result = yield SocksClient.createConnection({ + command: 'connect', + proxy: nextProxy, + destination: nextDestination, + // Initial connection ignores this as sock is undefined. Subsequent connections re-use the first proxy socket to form a chain. + }); + // If sock is undefined, assign it here. + if (!sock) { + sock = result.socket; + } + } + if (typeof callback === 'function') { + callback(null, { socket: sock }); + resolve({ socket: sock }); // Resolves pending promise (prevents memory leaks). + } + else { + resolve({ socket: sock }); + } + } + catch (err) { + if (typeof callback === 'function') { + callback(err); + // eslint-disable-next-line @typescript-eslint/no-explicit-any + resolve(err); // Resolves pending promise (prevents memory leaks). + } + else { + reject(err); + } + } + })); + } + /** + * Creates a SOCKS UDP Frame. + * @param options + */ + static createUDPFrame(options) { + const buff = new smart_buffer_1.SmartBuffer(); + buff.writeUInt16BE(0); + buff.writeUInt8(options.frameNumber || 0); + // IPv4/IPv6/Hostname + if (net.isIPv4(options.remoteHost.host)) { + buff.writeUInt8(constants_1.Socks5HostType.IPv4); + buff.writeUInt32BE(ip.toLong(options.remoteHost.host)); + } + else if (net.isIPv6(options.remoteHost.host)) { + buff.writeUInt8(constants_1.Socks5HostType.IPv6); + buff.writeBuffer(ip.toBuffer(options.remoteHost.host)); + } + else { + buff.writeUInt8(constants_1.Socks5HostType.Hostname); + buff.writeUInt8(Buffer.byteLength(options.remoteHost.host)); + buff.writeString(options.remoteHost.host); + } + // Port + buff.writeUInt16BE(options.remoteHost.port); + // Data + buff.writeBuffer(options.data); + return buff.toBuffer(); + } + /** + * Parses a SOCKS UDP frame. + * @param data + */ + static parseUDPFrame(data) { + const buff = smart_buffer_1.SmartBuffer.fromBuffer(data); + buff.readOffset = 2; + const frameNumber = buff.readUInt8(); + const hostType = buff.readUInt8(); + let remoteHost; + if (hostType === constants_1.Socks5HostType.IPv4) { + remoteHost = ip.fromLong(buff.readUInt32BE()); + } + else if (hostType === constants_1.Socks5HostType.IPv6) { + remoteHost = ip.toString(buff.readBuffer(16)); + } + else { + remoteHost = buff.readString(buff.readUInt8()); + } + const remotePort = buff.readUInt16BE(); + return { + frameNumber, + remoteHost: { + host: remoteHost, + port: remotePort, + }, + data: buff.readBuffer(), + }; + } + /** + * Internal state setter. If the SocksClient is in an error state, it cannot be changed to a non error state. + */ + setState(newState) { + if (this.state !== constants_1.SocksClientState.Error) { + this.state = newState; + } + } + /** + * Starts the connection establishment to the proxy and destination. + * @param existingSocket Connected socket to use instead of creating a new one (internal use). + */ + connect(existingSocket) { + this.onDataReceived = (data) => this.onDataReceivedHandler(data); + this.onClose = () => this.onCloseHandler(); + this.onError = (err) => this.onErrorHandler(err); + this.onConnect = () => this.onConnectHandler(); + // Start timeout timer (defaults to 30 seconds) + const timer = setTimeout(() => this.onEstablishedTimeout(), this.options.timeout || constants_1.DEFAULT_TIMEOUT); + // check whether unref is available as it differs from browser to NodeJS (#33) + if (timer.unref && typeof timer.unref === 'function') { + timer.unref(); + } + // If an existing socket is provided, use it to negotiate SOCKS handshake. Otherwise create a new Socket. + if (existingSocket) { + this.socket = existingSocket; + } + else { + this.socket = new net.Socket(); + } + // Attach Socket error handlers. + this.socket.once('close', this.onClose); + this.socket.once('error', this.onError); + this.socket.once('connect', this.onConnect); + this.socket.on('data', this.onDataReceived); + this.setState(constants_1.SocksClientState.Connecting); + this.receiveBuffer = new receivebuffer_1.ReceiveBuffer(); + if (existingSocket) { + this.socket.emit('connect'); + } + else { + this.socket.connect(this.getSocketOptions()); + if (this.options.set_tcp_nodelay !== undefined && + this.options.set_tcp_nodelay !== null) { + this.socket.setNoDelay(!!this.options.set_tcp_nodelay); + } + } + // Listen for established event so we can re-emit any excess data received during handshakes. + this.prependOnceListener('established', (info) => { + setImmediate(() => { + if (this.receiveBuffer.length > 0) { + const excessData = this.receiveBuffer.get(this.receiveBuffer.length); + info.socket.emit('data', excessData); + } + info.socket.resume(); + }); + }); + } + // Socket options (defaults host/port to options.proxy.host/options.proxy.port) + getSocketOptions() { + return Object.assign(Object.assign({}, this.options.socket_options), { host: this.options.proxy.host || this.options.proxy.ipaddress, port: this.options.proxy.port }); + } + /** + * Handles internal Socks timeout callback. + * Note: If the Socks client is not BoundWaitingForConnection or Established, the connection will be closed. + */ + onEstablishedTimeout() { + if (this.state !== constants_1.SocksClientState.Established && + this.state !== constants_1.SocksClientState.BoundWaitingForConnection) { + this.closeSocket(constants_1.ERRORS.ProxyConnectionTimedOut); + } + } + /** + * Handles Socket connect event. + */ + onConnectHandler() { + this.setState(constants_1.SocksClientState.Connected); + // Send initial handshake. + if (this.options.proxy.type === 4) { + this.sendSocks4InitialHandshake(); + } + else { + this.sendSocks5InitialHandshake(); + } + this.setState(constants_1.SocksClientState.SentInitialHandshake); + } + /** + * Handles Socket data event. + * @param data + */ + onDataReceivedHandler(data) { + /* + All received data is appended to a ReceiveBuffer. + This makes sure that all the data we need is received before we attempt to process it. + */ + this.receiveBuffer.append(data); + // Process data that we have. + this.processData(); + } + /** + * Handles processing of the data we have received. + */ + processData() { + // If we have enough data to process the next step in the SOCKS handshake, proceed. + while (this.state !== constants_1.SocksClientState.Established && + this.state !== constants_1.SocksClientState.Error && + this.receiveBuffer.length >= this.nextRequiredPacketBufferSize) { + // Sent initial handshake, waiting for response. + if (this.state === constants_1.SocksClientState.SentInitialHandshake) { + if (this.options.proxy.type === 4) { + // Socks v4 only has one handshake response. + this.handleSocks4FinalHandshakeResponse(); + } + else { + // Socks v5 has two handshakes, handle initial one here. + this.handleInitialSocks5HandshakeResponse(); + } + // Sent auth request for Socks v5, waiting for response. + } + else if (this.state === constants_1.SocksClientState.SentAuthentication) { + this.handleInitialSocks5AuthenticationHandshakeResponse(); + // Sent final Socks v5 handshake, waiting for final response. + } + else if (this.state === constants_1.SocksClientState.SentFinalHandshake) { + this.handleSocks5FinalHandshakeResponse(); + // Socks BIND established. Waiting for remote connection via proxy. + } + else if (this.state === constants_1.SocksClientState.BoundWaitingForConnection) { + if (this.options.proxy.type === 4) { + this.handleSocks4IncomingConnectionResponse(); + } + else { + this.handleSocks5IncomingConnectionResponse(); + } + } + else { + this.closeSocket(constants_1.ERRORS.InternalError); + break; + } + } + } + /** + * Handles Socket close event. + * @param had_error + */ + onCloseHandler() { + this.closeSocket(constants_1.ERRORS.SocketClosed); + } + /** + * Handles Socket error event. + * @param err + */ + onErrorHandler(err) { + this.closeSocket(err.message); + } + /** + * Removes internal event listeners on the underlying Socket. + */ + removeInternalSocketHandlers() { + // Pauses data flow of the socket (this is internally resumed after 'established' is emitted) + this.socket.pause(); + this.socket.removeListener('data', this.onDataReceived); + this.socket.removeListener('close', this.onClose); + this.socket.removeListener('error', this.onError); + this.socket.removeListener('connect', this.onConnect); + } + /** + * Closes and destroys the underlying Socket. Emits an error event. + * @param err { String } An error string to include in error event. + */ + closeSocket(err) { + // Make sure only one 'error' event is fired for the lifetime of this SocksClient instance. + if (this.state !== constants_1.SocksClientState.Error) { + // Set internal state to Error. + this.setState(constants_1.SocksClientState.Error); + // Destroy Socket + this.socket.destroy(); + // Remove internal listeners + this.removeInternalSocketHandlers(); + // Fire 'error' event. + this.emit('error', new util_1.SocksClientError(err, this.options)); + } + } + /** + * Sends initial Socks v4 handshake request. + */ + sendSocks4InitialHandshake() { + const userId = this.options.proxy.userId || ''; + const buff = new smart_buffer_1.SmartBuffer(); + buff.writeUInt8(0x04); + buff.writeUInt8(constants_1.SocksCommand[this.options.command]); + buff.writeUInt16BE(this.options.destination.port); + // Socks 4 (IPv4) + if (net.isIPv4(this.options.destination.host)) { + buff.writeBuffer(ip.toBuffer(this.options.destination.host)); + buff.writeStringNT(userId); + // Socks 4a (hostname) + } + else { + buff.writeUInt8(0x00); + buff.writeUInt8(0x00); + buff.writeUInt8(0x00); + buff.writeUInt8(0x01); + buff.writeStringNT(userId); + buff.writeStringNT(this.options.destination.host); + } + this.nextRequiredPacketBufferSize = + constants_1.SOCKS_INCOMING_PACKET_SIZES.Socks4Response; + this.socket.write(buff.toBuffer()); + } + /** + * Handles Socks v4 handshake response. + * @param data + */ + handleSocks4FinalHandshakeResponse() { + const data = this.receiveBuffer.get(8); + if (data[1] !== constants_1.Socks4Response.Granted) { + this.closeSocket(`${constants_1.ERRORS.Socks4ProxyRejectedConnection} - (${constants_1.Socks4Response[data[1]]})`); + } + else { + // Bind response + if (constants_1.SocksCommand[this.options.command] === constants_1.SocksCommand.bind) { + const buff = smart_buffer_1.SmartBuffer.fromBuffer(data); + buff.readOffset = 2; + const remoteHost = { + port: buff.readUInt16BE(), + host: ip.fromLong(buff.readUInt32BE()), + }; + // If host is 0.0.0.0, set to proxy host. + if (remoteHost.host === '0.0.0.0') { + remoteHost.host = this.options.proxy.ipaddress; + } + this.setState(constants_1.SocksClientState.BoundWaitingForConnection); + this.emit('bound', { remoteHost, socket: this.socket }); + // Connect response + } + else { + this.setState(constants_1.SocksClientState.Established); + this.removeInternalSocketHandlers(); + this.emit('established', { socket: this.socket }); + } + } + } + /** + * Handles Socks v4 incoming connection request (BIND) + * @param data + */ + handleSocks4IncomingConnectionResponse() { + const data = this.receiveBuffer.get(8); + if (data[1] !== constants_1.Socks4Response.Granted) { + this.closeSocket(`${constants_1.ERRORS.Socks4ProxyRejectedIncomingBoundConnection} - (${constants_1.Socks4Response[data[1]]})`); + } + else { + const buff = smart_buffer_1.SmartBuffer.fromBuffer(data); + buff.readOffset = 2; + const remoteHost = { + port: buff.readUInt16BE(), + host: ip.fromLong(buff.readUInt32BE()), + }; + this.setState(constants_1.SocksClientState.Established); + this.removeInternalSocketHandlers(); + this.emit('established', { remoteHost, socket: this.socket }); + } + } + /** + * Sends initial Socks v5 handshake request. + */ + sendSocks5InitialHandshake() { + const buff = new smart_buffer_1.SmartBuffer(); + // By default we always support no auth. + const supportedAuthMethods = [constants_1.Socks5Auth.NoAuth]; + // We should only tell the proxy we support user/pass auth if auth info is actually provided. + // Note: As of Tor v0.3.5.7+, if user/pass auth is an option from the client, by default it will always take priority. + if (this.options.proxy.userId || this.options.proxy.password) { + supportedAuthMethods.push(constants_1.Socks5Auth.UserPass); + } + // Custom auth method? + if (this.options.proxy.custom_auth_method !== undefined) { + supportedAuthMethods.push(this.options.proxy.custom_auth_method); + } + // Build handshake packet + buff.writeUInt8(0x05); + buff.writeUInt8(supportedAuthMethods.length); + for (const authMethod of supportedAuthMethods) { + buff.writeUInt8(authMethod); + } + this.nextRequiredPacketBufferSize = + constants_1.SOCKS_INCOMING_PACKET_SIZES.Socks5InitialHandshakeResponse; + this.socket.write(buff.toBuffer()); + this.setState(constants_1.SocksClientState.SentInitialHandshake); + } + /** + * Handles initial Socks v5 handshake response. + * @param data + */ + handleInitialSocks5HandshakeResponse() { + const data = this.receiveBuffer.get(2); + if (data[0] !== 0x05) { + this.closeSocket(constants_1.ERRORS.InvalidSocks5IntiailHandshakeSocksVersion); + } + else if (data[1] === constants_1.SOCKS5_NO_ACCEPTABLE_AUTH) { + this.closeSocket(constants_1.ERRORS.InvalidSocks5InitialHandshakeNoAcceptedAuthType); + } + else { + // If selected Socks v5 auth method is no auth, send final handshake request. + if (data[1] === constants_1.Socks5Auth.NoAuth) { + this.socks5ChosenAuthType = constants_1.Socks5Auth.NoAuth; + this.sendSocks5CommandRequest(); + // If selected Socks v5 auth method is user/password, send auth handshake. + } + else if (data[1] === constants_1.Socks5Auth.UserPass) { + this.socks5ChosenAuthType = constants_1.Socks5Auth.UserPass; + this.sendSocks5UserPassAuthentication(); + // If selected Socks v5 auth method is the custom_auth_method, send custom handshake. + } + else if (data[1] === this.options.proxy.custom_auth_method) { + this.socks5ChosenAuthType = this.options.proxy.custom_auth_method; + this.sendSocks5CustomAuthentication(); + } + else { + this.closeSocket(constants_1.ERRORS.InvalidSocks5InitialHandshakeUnknownAuthType); + } + } + } + /** + * Sends Socks v5 user & password auth handshake. + * + * Note: No auth and user/pass are currently supported. + */ + sendSocks5UserPassAuthentication() { + const userId = this.options.proxy.userId || ''; + const password = this.options.proxy.password || ''; + const buff = new smart_buffer_1.SmartBuffer(); + buff.writeUInt8(0x01); + buff.writeUInt8(Buffer.byteLength(userId)); + buff.writeString(userId); + buff.writeUInt8(Buffer.byteLength(password)); + buff.writeString(password); + this.nextRequiredPacketBufferSize = + constants_1.SOCKS_INCOMING_PACKET_SIZES.Socks5UserPassAuthenticationResponse; + this.socket.write(buff.toBuffer()); + this.setState(constants_1.SocksClientState.SentAuthentication); + } + sendSocks5CustomAuthentication() { + return __awaiter(this, void 0, void 0, function* () { + this.nextRequiredPacketBufferSize = + this.options.proxy.custom_auth_response_size; + this.socket.write(yield this.options.proxy.custom_auth_request_handler()); + this.setState(constants_1.SocksClientState.SentAuthentication); + }); + } + handleSocks5CustomAuthHandshakeResponse(data) { + return __awaiter(this, void 0, void 0, function* () { + return yield this.options.proxy.custom_auth_response_handler(data); + }); + } + handleSocks5AuthenticationNoAuthHandshakeResponse(data) { + return __awaiter(this, void 0, void 0, function* () { + return data[1] === 0x00; + }); + } + handleSocks5AuthenticationUserPassHandshakeResponse(data) { + return __awaiter(this, void 0, void 0, function* () { + return data[1] === 0x00; + }); + } + /** + * Handles Socks v5 auth handshake response. + * @param data + */ + handleInitialSocks5AuthenticationHandshakeResponse() { + return __awaiter(this, void 0, void 0, function* () { + this.setState(constants_1.SocksClientState.ReceivedAuthenticationResponse); + let authResult = false; + if (this.socks5ChosenAuthType === constants_1.Socks5Auth.NoAuth) { + authResult = yield this.handleSocks5AuthenticationNoAuthHandshakeResponse(this.receiveBuffer.get(2)); + } + else if (this.socks5ChosenAuthType === constants_1.Socks5Auth.UserPass) { + authResult = + yield this.handleSocks5AuthenticationUserPassHandshakeResponse(this.receiveBuffer.get(2)); + } + else if (this.socks5ChosenAuthType === this.options.proxy.custom_auth_method) { + authResult = yield this.handleSocks5CustomAuthHandshakeResponse(this.receiveBuffer.get(this.options.proxy.custom_auth_response_size)); + } + if (!authResult) { + this.closeSocket(constants_1.ERRORS.Socks5AuthenticationFailed); + } + else { + this.sendSocks5CommandRequest(); + } + }); + } + /** + * Sends Socks v5 final handshake request. + */ + sendSocks5CommandRequest() { + const buff = new smart_buffer_1.SmartBuffer(); + buff.writeUInt8(0x05); + buff.writeUInt8(constants_1.SocksCommand[this.options.command]); + buff.writeUInt8(0x00); + // ipv4, ipv6, domain? + if (net.isIPv4(this.options.destination.host)) { + buff.writeUInt8(constants_1.Socks5HostType.IPv4); + buff.writeBuffer(ip.toBuffer(this.options.destination.host)); + } + else if (net.isIPv6(this.options.destination.host)) { + buff.writeUInt8(constants_1.Socks5HostType.IPv6); + buff.writeBuffer(ip.toBuffer(this.options.destination.host)); + } + else { + buff.writeUInt8(constants_1.Socks5HostType.Hostname); + buff.writeUInt8(this.options.destination.host.length); + buff.writeString(this.options.destination.host); + } + buff.writeUInt16BE(this.options.destination.port); + this.nextRequiredPacketBufferSize = + constants_1.SOCKS_INCOMING_PACKET_SIZES.Socks5ResponseHeader; + this.socket.write(buff.toBuffer()); + this.setState(constants_1.SocksClientState.SentFinalHandshake); + } + /** + * Handles Socks v5 final handshake response. + * @param data + */ + handleSocks5FinalHandshakeResponse() { + // Peek at available data (we need at least 5 bytes to get the hostname length) + const header = this.receiveBuffer.peek(5); + if (header[0] !== 0x05 || header[1] !== constants_1.Socks5Response.Granted) { + this.closeSocket(`${constants_1.ERRORS.InvalidSocks5FinalHandshakeRejected} - ${constants_1.Socks5Response[header[1]]}`); + } + else { + // Read address type + const addressType = header[3]; + let remoteHost; + let buff; + // IPv4 + if (addressType === constants_1.Socks5HostType.IPv4) { + // Check if data is available. + const dataNeeded = constants_1.SOCKS_INCOMING_PACKET_SIZES.Socks5ResponseIPv4; + if (this.receiveBuffer.length < dataNeeded) { + this.nextRequiredPacketBufferSize = dataNeeded; + return; + } + buff = smart_buffer_1.SmartBuffer.fromBuffer(this.receiveBuffer.get(dataNeeded).slice(4)); + remoteHost = { + host: ip.fromLong(buff.readUInt32BE()), + port: buff.readUInt16BE(), + }; + // If given host is 0.0.0.0, assume remote proxy ip instead. + if (remoteHost.host === '0.0.0.0') { + remoteHost.host = this.options.proxy.ipaddress; + } + // Hostname + } + else if (addressType === constants_1.Socks5HostType.Hostname) { + const hostLength = header[4]; + const dataNeeded = constants_1.SOCKS_INCOMING_PACKET_SIZES.Socks5ResponseHostname(hostLength); // header + host length + host + port + // Check if data is available. + if (this.receiveBuffer.length < dataNeeded) { + this.nextRequiredPacketBufferSize = dataNeeded; + return; + } + buff = smart_buffer_1.SmartBuffer.fromBuffer(this.receiveBuffer.get(dataNeeded).slice(5)); + remoteHost = { + host: buff.readString(hostLength), + port: buff.readUInt16BE(), + }; + // IPv6 + } + else if (addressType === constants_1.Socks5HostType.IPv6) { + // Check if data is available. + const dataNeeded = constants_1.SOCKS_INCOMING_PACKET_SIZES.Socks5ResponseIPv6; + if (this.receiveBuffer.length < dataNeeded) { + this.nextRequiredPacketBufferSize = dataNeeded; + return; + } + buff = smart_buffer_1.SmartBuffer.fromBuffer(this.receiveBuffer.get(dataNeeded).slice(4)); + remoteHost = { + host: ip.toString(buff.readBuffer(16)), + port: buff.readUInt16BE(), + }; + } + // We have everything we need + this.setState(constants_1.SocksClientState.ReceivedFinalResponse); + // If using CONNECT, the client is now in the established state. + if (constants_1.SocksCommand[this.options.command] === constants_1.SocksCommand.connect) { + this.setState(constants_1.SocksClientState.Established); + this.removeInternalSocketHandlers(); + this.emit('established', { remoteHost, socket: this.socket }); + } + else if (constants_1.SocksCommand[this.options.command] === constants_1.SocksCommand.bind) { + /* If using BIND, the Socks client is now in BoundWaitingForConnection state. + This means that the remote proxy server is waiting for a remote connection to the bound port. */ + this.setState(constants_1.SocksClientState.BoundWaitingForConnection); + this.nextRequiredPacketBufferSize = + constants_1.SOCKS_INCOMING_PACKET_SIZES.Socks5ResponseHeader; + this.emit('bound', { remoteHost, socket: this.socket }); + /* + If using Associate, the Socks client is now Established. And the proxy server is now accepting UDP packets at the + given bound port. This initial Socks TCP connection must remain open for the UDP relay to continue to work. + */ + } + else if (constants_1.SocksCommand[this.options.command] === constants_1.SocksCommand.associate) { + this.setState(constants_1.SocksClientState.Established); + this.removeInternalSocketHandlers(); + this.emit('established', { + remoteHost, + socket: this.socket, + }); + } + } + } + /** + * Handles Socks v5 incoming connection request (BIND). + */ + handleSocks5IncomingConnectionResponse() { + // Peek at available data (we need at least 5 bytes to get the hostname length) + const header = this.receiveBuffer.peek(5); + if (header[0] !== 0x05 || header[1] !== constants_1.Socks5Response.Granted) { + this.closeSocket(`${constants_1.ERRORS.Socks5ProxyRejectedIncomingBoundConnection} - ${constants_1.Socks5Response[header[1]]}`); + } + else { + // Read address type + const addressType = header[3]; + let remoteHost; + let buff; + // IPv4 + if (addressType === constants_1.Socks5HostType.IPv4) { + // Check if data is available. + const dataNeeded = constants_1.SOCKS_INCOMING_PACKET_SIZES.Socks5ResponseIPv4; + if (this.receiveBuffer.length < dataNeeded) { + this.nextRequiredPacketBufferSize = dataNeeded; + return; + } + buff = smart_buffer_1.SmartBuffer.fromBuffer(this.receiveBuffer.get(dataNeeded).slice(4)); + remoteHost = { + host: ip.fromLong(buff.readUInt32BE()), + port: buff.readUInt16BE(), + }; + // If given host is 0.0.0.0, assume remote proxy ip instead. + if (remoteHost.host === '0.0.0.0') { + remoteHost.host = this.options.proxy.ipaddress; + } + // Hostname + } + else if (addressType === constants_1.Socks5HostType.Hostname) { + const hostLength = header[4]; + const dataNeeded = constants_1.SOCKS_INCOMING_PACKET_SIZES.Socks5ResponseHostname(hostLength); // header + host length + port + // Check if data is available. + if (this.receiveBuffer.length < dataNeeded) { + this.nextRequiredPacketBufferSize = dataNeeded; + return; + } + buff = smart_buffer_1.SmartBuffer.fromBuffer(this.receiveBuffer.get(dataNeeded).slice(5)); + remoteHost = { + host: buff.readString(hostLength), + port: buff.readUInt16BE(), + }; + // IPv6 + } + else if (addressType === constants_1.Socks5HostType.IPv6) { + // Check if data is available. + const dataNeeded = constants_1.SOCKS_INCOMING_PACKET_SIZES.Socks5ResponseIPv6; + if (this.receiveBuffer.length < dataNeeded) { + this.nextRequiredPacketBufferSize = dataNeeded; + return; + } + buff = smart_buffer_1.SmartBuffer.fromBuffer(this.receiveBuffer.get(dataNeeded).slice(4)); + remoteHost = { + host: ip.toString(buff.readBuffer(16)), + port: buff.readUInt16BE(), + }; + } + this.setState(constants_1.SocksClientState.Established); + this.removeInternalSocketHandlers(); + this.emit('established', { remoteHost, socket: this.socket }); + } + } + get socksClientOptions() { + return Object.assign({}, this.options); + } +} +exports.SocksClient = SocksClient; +//# sourceMappingURL=socksclient.js.map \ No newline at end of file diff --git a/ts-ticket-office-service/node_modules/socks/build/client/socksclient.js.map b/ts-ticket-office-service/node_modules/socks/build/client/socksclient.js.map new file mode 100644 index 000000000..b39f3add4 --- /dev/null +++ b/ts-ticket-office-service/node_modules/socks/build/client/socksclient.js.map @@ -0,0 +1 @@ +{"version":3,"file":"socksclient.js","sourceRoot":"","sources":["../../src/client/socksclient.ts"],"names":[],"mappings":";;;;;;;;;;;;AAAA,mCAAoC;AACpC,2BAA2B;AAC3B,yBAAyB;AACzB,+CAAyC;AACzC,mDAkB6B;AAC7B,+CAG2B;AAC3B,2DAAsD;AACtD,yCAA8D;AA07B5D,iGA17BM,uBAAgB,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AM,GAAG,UAAU,EAAE;oBAC1C,IAAI,CAAC,4BAA4B,GAAG,UAAU,CAAC;oBAC/C,OAAO;iBACR;gBAED,IAAI,GAAG,0BAAW,CAAC,UAAU,CAC3B,IAAI,CAAC,aAAa,CAAC,GAAG,CAAC,UAAU,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC,CAC5C,CAAC;gBAEF,UAAU,GAAG;oBACX,IAAI,EAAE,EAAE,CAAC,QAAQ,CAAC,IAAI,CAAC,UAAU,CAAC,EAAE,CAAC,CAAC;oBACtC,IAAI,EAAE,IAAI,CAAC,YAAY,EAAE;iBAC1B,CAAC;aACH;YAED,IAAI,CAAC,QAAQ,CAAC,4BAAgB,CAAC,WAAW,CAAC,CAAC;YAC5C,IAAI,CAAC,4BAA4B,EAAE,CAAC;YACpC,IAAI,CAAC,IAAI,CAAC,aAAa,EAAE,EAAC,UAAU,EAAE,MAAM,EAAE,IAAI,CAAC,MAAM,EAAC,CAAC,CAAC;SAC7D;IACH,CAAC;IAED,IAAI,kBAAkB;QACpB,yBACK,IAAI,CAAC,OAAO,EACf;IACJ,CAAC;CACF;AAGC,kCAAW"} \ No newline at end of file diff --git a/ts-ticket-office-service/node_modules/socks/build/common/constants.js b/ts-ticket-office-service/node_modules/socks/build/common/constants.js new file mode 100644 index 000000000..3c9ff90ac --- /dev/null +++ b/ts-ticket-office-service/node_modules/socks/build/common/constants.js @@ -0,0 +1,114 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.SOCKS5_NO_ACCEPTABLE_AUTH = exports.SOCKS5_CUSTOM_AUTH_END = exports.SOCKS5_CUSTOM_AUTH_START = exports.SOCKS_INCOMING_PACKET_SIZES = exports.SocksClientState = exports.Socks5Response = exports.Socks5HostType = exports.Socks5Auth = exports.Socks4Response = exports.SocksCommand = exports.ERRORS = exports.DEFAULT_TIMEOUT = void 0; +const DEFAULT_TIMEOUT = 30000; +exports.DEFAULT_TIMEOUT = DEFAULT_TIMEOUT; +// prettier-ignore +const ERRORS = { + InvalidSocksCommand: 'An invalid SOCKS command was provided. Valid options are connect, bind, and associate.', + InvalidSocksCommandForOperation: 'An invalid SOCKS command was provided. Only a subset of commands are supported for this operation.', + InvalidSocksCommandChain: 'An invalid SOCKS command was provided. Chaining currently only supports the connect command.', + InvalidSocksClientOptionsDestination: 'An invalid destination host was provided.', + InvalidSocksClientOptionsExistingSocket: 'An invalid existing socket was provided. This should be an instance of stream.Duplex.', + InvalidSocksClientOptionsProxy: 'Invalid SOCKS proxy details were provided.', + InvalidSocksClientOptionsTimeout: 'An invalid timeout value was provided. Please enter a value above 0 (in ms).', + InvalidSocksClientOptionsProxiesLength: 'At least two socks proxies must be provided for chaining.', + InvalidSocksClientOptionsCustomAuthRange: 'Custom auth must be a value between 0x80 and 0xFE.', + InvalidSocksClientOptionsCustomAuthOptions: 'When a custom_auth_method is provided, custom_auth_request_handler, custom_auth_response_size, and custom_auth_response_handler must also be provided and valid.', + NegotiationError: 'Negotiation error', + SocketClosed: 'Socket closed', + ProxyConnectionTimedOut: 'Proxy connection timed out', + InternalError: 'SocksClient internal error (this should not happen)', + InvalidSocks4HandshakeResponse: 'Received invalid Socks4 handshake response', + Socks4ProxyRejectedConnection: 'Socks4 Proxy rejected connection', + InvalidSocks4IncomingConnectionResponse: 'Socks4 invalid incoming connection response', + Socks4ProxyRejectedIncomingBoundConnection: 'Socks4 Proxy rejected incoming bound connection', + InvalidSocks5InitialHandshakeResponse: 'Received invalid Socks5 initial handshake response', + InvalidSocks5IntiailHandshakeSocksVersion: 'Received invalid Socks5 initial handshake (invalid socks version)', + InvalidSocks5InitialHandshakeNoAcceptedAuthType: 'Received invalid Socks5 initial handshake (no accepted authentication type)', + InvalidSocks5InitialHandshakeUnknownAuthType: 'Received invalid Socks5 initial handshake (unknown authentication type)', + Socks5AuthenticationFailed: 'Socks5 Authentication failed', + InvalidSocks5FinalHandshake: 'Received invalid Socks5 final handshake response', + InvalidSocks5FinalHandshakeRejected: 'Socks5 proxy rejected connection', + InvalidSocks5IncomingConnectionResponse: 'Received invalid Socks5 incoming connection response', + Socks5ProxyRejectedIncomingBoundConnection: 'Socks5 Proxy rejected incoming bound connection', +}; +exports.ERRORS = ERRORS; +const SOCKS_INCOMING_PACKET_SIZES = { + Socks5InitialHandshakeResponse: 2, + Socks5UserPassAuthenticationResponse: 2, + // Command response + incoming connection (bind) + Socks5ResponseHeader: 5, + Socks5ResponseIPv4: 10, + Socks5ResponseIPv6: 22, + Socks5ResponseHostname: (hostNameLength) => hostNameLength + 7, + // Command response + incoming connection (bind) + Socks4Response: 8, // 2 header + 2 port + 4 ip +}; +exports.SOCKS_INCOMING_PACKET_SIZES = SOCKS_INCOMING_PACKET_SIZES; +var SocksCommand; +(function (SocksCommand) { + SocksCommand[SocksCommand["connect"] = 1] = "connect"; + SocksCommand[SocksCommand["bind"] = 2] = "bind"; + SocksCommand[SocksCommand["associate"] = 3] = "associate"; +})(SocksCommand || (SocksCommand = {})); +exports.SocksCommand = SocksCommand; +var Socks4Response; +(function (Socks4Response) { + Socks4Response[Socks4Response["Granted"] = 90] = "Granted"; + Socks4Response[Socks4Response["Failed"] = 91] = "Failed"; + Socks4Response[Socks4Response["Rejected"] = 92] = "Rejected"; + Socks4Response[Socks4Response["RejectedIdent"] = 93] = "RejectedIdent"; +})(Socks4Response || (Socks4Response = {})); +exports.Socks4Response = Socks4Response; +var Socks5Auth; +(function (Socks5Auth) { + Socks5Auth[Socks5Auth["NoAuth"] = 0] = "NoAuth"; + Socks5Auth[Socks5Auth["GSSApi"] = 1] = "GSSApi"; + Socks5Auth[Socks5Auth["UserPass"] = 2] = "UserPass"; +})(Socks5Auth || (Socks5Auth = {})); +exports.Socks5Auth = Socks5Auth; +const SOCKS5_CUSTOM_AUTH_START = 0x80; +exports.SOCKS5_CUSTOM_AUTH_START = SOCKS5_CUSTOM_AUTH_START; +const SOCKS5_CUSTOM_AUTH_END = 0xfe; +exports.SOCKS5_CUSTOM_AUTH_END = SOCKS5_CUSTOM_AUTH_END; +const SOCKS5_NO_ACCEPTABLE_AUTH = 0xff; +exports.SOCKS5_NO_ACCEPTABLE_AUTH = SOCKS5_NO_ACCEPTABLE_AUTH; +var Socks5Response; +(function (Socks5Response) { + Socks5Response[Socks5Response["Granted"] = 0] = "Granted"; + Socks5Response[Socks5Response["Failure"] = 1] = "Failure"; + Socks5Response[Socks5Response["NotAllowed"] = 2] = "NotAllowed"; + Socks5Response[Socks5Response["NetworkUnreachable"] = 3] = "NetworkUnreachable"; + Socks5Response[Socks5Response["HostUnreachable"] = 4] = "HostUnreachable"; + Socks5Response[Socks5Response["ConnectionRefused"] = 5] = "ConnectionRefused"; + Socks5Response[Socks5Response["TTLExpired"] = 6] = "TTLExpired"; + Socks5Response[Socks5Response["CommandNotSupported"] = 7] = "CommandNotSupported"; + Socks5Response[Socks5Response["AddressNotSupported"] = 8] = "AddressNotSupported"; +})(Socks5Response || (Socks5Response = {})); +exports.Socks5Response = Socks5Response; +var Socks5HostType; +(function (Socks5HostType) { + Socks5HostType[Socks5HostType["IPv4"] = 1] = "IPv4"; + Socks5HostType[Socks5HostType["Hostname"] = 3] = "Hostname"; + Socks5HostType[Socks5HostType["IPv6"] = 4] = "IPv6"; +})(Socks5HostType || (Socks5HostType = {})); +exports.Socks5HostType = Socks5HostType; +var SocksClientState; +(function (SocksClientState) { + SocksClientState[SocksClientState["Created"] = 0] = "Created"; + SocksClientState[SocksClientState["Connecting"] = 1] = "Connecting"; + SocksClientState[SocksClientState["Connected"] = 2] = "Connected"; + SocksClientState[SocksClientState["SentInitialHandshake"] = 3] = "SentInitialHandshake"; + SocksClientState[SocksClientState["ReceivedInitialHandshakeResponse"] = 4] = "ReceivedInitialHandshakeResponse"; + SocksClientState[SocksClientState["SentAuthentication"] = 5] = "SentAuthentication"; + SocksClientState[SocksClientState["ReceivedAuthenticationResponse"] = 6] = "ReceivedAuthenticationResponse"; + SocksClientState[SocksClientState["SentFinalHandshake"] = 7] = "SentFinalHandshake"; + SocksClientState[SocksClientState["ReceivedFinalResponse"] = 8] = "ReceivedFinalResponse"; + SocksClientState[SocksClientState["BoundWaitingForConnection"] = 9] = "BoundWaitingForConnection"; + SocksClientState[SocksClientState["Established"] = 10] = "Established"; + SocksClientState[SocksClientState["Disconnected"] = 11] = "Disconnected"; + SocksClientState[SocksClientState["Error"] = 99] = "Error"; +})(SocksClientState || (SocksClientState = {})); +exports.SocksClientState = SocksClientState; +//# sourceMappingURL=constants.js.map \ No newline at end of file diff --git a/ts-ticket-office-service/node_modules/socks/build/common/constants.js.map b/ts-ticket-office-service/node_modules/socks/build/common/constants.js.map new file mode 100644 index 000000000..c1e070dea --- /dev/null +++ b/ts-ticket-office-service/node_modules/socks/build/common/constants.js.map @@ -0,0 +1 @@ +{"version":3,"file":"constants.js","sourceRoot":"","sources":["../../src/common/constants.ts"],"names":[],"mappings":";;;AAIA,MAAM,eAAe,GAAG,KAAK,CAAC;AA4M5B,0CAAe;AAxMjB,kBAAkB;AAClB,MAAM,MAAM,GAAG;IACb,mBAAmB,EAAE,wFAAwF;IAC7G,+BAA+B,EAAE,oGAAoG;IACrI,wBAAwB,EAAE,8FAA8F;IACxH,oCAAoC,EAAE,2CAA2C;IACjF,uCAAuC,EAAE,uFAAuF;IAChI,8BAA8B,EAAE,4CAA4C;IAC5E,gCAAgC,EAAE,8EAA8E;IAChH,sCAAsC,EAAE,2DAA2D;IACnG,wCAAwC,EAAE,oDAAoD;IAC9F,0CAA0C,EAAE,kKAAkK;IAC9M,gBAAgB,EAAE,mBAAmB;IACrC,YAAY,EAAE,eAAe;IAC7B,uBAAuB,EAAE,4BAA4B;IACrD,aAAa,EAAE,qDAAqD;IACpE,8BAA8B,EAAE,4CAA4C;IAC5E,6BAA6B,EAAE,kCAAkC;IACjE,uCAAuC,EAAE,6CAA6C;IACtF,0CAA0C,EAAE,iDAAiD;IAC7F,qCAAqC,EAAE,oDAAoD;IAC3F,yCAAyC,EAAE,mEAAmE;IAC9G,+CAA+C,EAAE,6EAA6E;IA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AA;IACd,yDAAc,CAAA;IACd,+DAAiB,CAAA;IACjB,+EAAyB,CAAA;IACzB,yEAAsB,CAAA;IACtB,6EAAwB,CAAA;IACxB,+DAAiB,CAAA;IACjB,iFAA0B,CAAA;IAC1B,iFAA0B,CAAA;AAC5B,CAAC,EAVI,cAAc,KAAd,cAAc,QAUlB;AAgIC,wCAAc;AA9HhB,IAAK,cAIJ;AAJD,WAAK,cAAc;IACjB,mDAAW,CAAA;IACX,2DAAe,CAAA;IACf,mDAAW,CAAA;AACb,CAAC,EAJI,cAAc,KAAd,cAAc,QAIlB;AAyHC,wCAAc;AAvHhB,IAAK,gBAcJ;AAdD,WAAK,gBAAgB;IACnB,6DAAW,CAAA;IACX,mEAAc,CAAA;IACd,iEAAa,CAAA;IACb,uFAAwB,CAAA;IACxB,+GAAoC,CAAA;IACpC,mFAAsB,CAAA;IACtB,2GAAkC,CAAA;IAClC,mFAAsB,CAAA;IACtB,yFAAyB,CAAA;IACzB,iGAA6B,CAAA;IAC7B,sEAAgB,CAAA;IAChB,wEAAiB,CAAA;IACjB,0DAAU,CAAA;AACZ,CAAC,EAdI,gBAAgB,KAAhB,gBAAgB,QAcpB;AA2GC,4CAAgB"} \ No newline at end of file diff --git a/ts-ticket-office-service/node_modules/socks/build/common/helpers.js b/ts-ticket-office-service/node_modules/socks/build/common/helpers.js new file mode 100644 index 000000000..f84db8f67 --- /dev/null +++ b/ts-ticket-office-service/node_modules/socks/build/common/helpers.js @@ -0,0 +1,128 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.validateSocksClientChainOptions = exports.validateSocksClientOptions = void 0; +const util_1 = require("./util"); +const constants_1 = require("./constants"); +const stream = require("stream"); +/** + * Validates the provided SocksClientOptions + * @param options { SocksClientOptions } + * @param acceptedCommands { string[] } A list of accepted SocksProxy commands. + */ +function validateSocksClientOptions(options, acceptedCommands = ['connect', 'bind', 'associate']) { + // Check SOCKs command option. + if (!constants_1.SocksCommand[options.command]) { + throw new util_1.SocksClientError(constants_1.ERRORS.InvalidSocksCommand, options); + } + // Check SocksCommand for acceptable command. + if (acceptedCommands.indexOf(options.command) === -1) { + throw new util_1.SocksClientError(constants_1.ERRORS.InvalidSocksCommandForOperation, options); + } + // Check destination + if (!isValidSocksRemoteHost(options.destination)) { + throw new util_1.SocksClientError(constants_1.ERRORS.InvalidSocksClientOptionsDestination, options); + } + // Check SOCKS proxy to use + if (!isValidSocksProxy(options.proxy)) { + throw new util_1.SocksClientError(constants_1.ERRORS.InvalidSocksClientOptionsProxy, options); + } + // Validate custom auth (if set) + validateCustomProxyAuth(options.proxy, options); + // Check timeout + if (options.timeout && !isValidTimeoutValue(options.timeout)) { + throw new util_1.SocksClientError(constants_1.ERRORS.InvalidSocksClientOptionsTimeout, options); + } + // Check existing_socket (if provided) + if (options.existing_socket && + !(options.existing_socket instanceof stream.Duplex)) { + throw new util_1.SocksClientError(constants_1.ERRORS.InvalidSocksClientOptionsExistingSocket, options); + } +} +exports.validateSocksClientOptions = validateSocksClientOptions; +/** + * Validates the SocksClientChainOptions + * @param options { SocksClientChainOptions } + */ +function validateSocksClientChainOptions(options) { + // Only connect is supported when chaining. + if (options.command !== 'connect') { + throw new util_1.SocksClientError(constants_1.ERRORS.InvalidSocksCommandChain, options); + } + // Check destination + if (!isValidSocksRemoteHost(options.destination)) { + throw new util_1.SocksClientError(constants_1.ERRORS.InvalidSocksClientOptionsDestination, options); + } + // Validate proxies (length) + if (!(options.proxies && + Array.isArray(options.proxies) && + options.proxies.length >= 2)) { + throw new util_1.SocksClientError(constants_1.ERRORS.InvalidSocksClientOptionsProxiesLength, options); + } + // Validate proxies + options.proxies.forEach((proxy) => { + if (!isValidSocksProxy(proxy)) { + throw new util_1.SocksClientError(constants_1.ERRORS.InvalidSocksClientOptionsProxy, options); + } + // Validate custom auth (if set) + validateCustomProxyAuth(proxy, options); + }); + // Check timeout + if (options.timeout && !isValidTimeoutValue(options.timeout)) { + throw new util_1.SocksClientError(constants_1.ERRORS.InvalidSocksClientOptionsTimeout, options); + } +} +exports.validateSocksClientChainOptions = validateSocksClientChainOptions; +function validateCustomProxyAuth(proxy, options) { + if (proxy.custom_auth_method !== undefined) { + // Invalid auth method range + if (proxy.custom_auth_method < constants_1.SOCKS5_CUSTOM_AUTH_START || + proxy.custom_auth_method > constants_1.SOCKS5_CUSTOM_AUTH_END) { + throw new util_1.SocksClientError(constants_1.ERRORS.InvalidSocksClientOptionsCustomAuthRange, options); + } + // Missing custom_auth_request_handler + if (proxy.custom_auth_request_handler === undefined || + typeof proxy.custom_auth_request_handler !== 'function') { + throw new util_1.SocksClientError(constants_1.ERRORS.InvalidSocksClientOptionsCustomAuthOptions, options); + } + // Missing custom_auth_response_size + if (proxy.custom_auth_response_size === undefined) { + throw new util_1.SocksClientError(constants_1.ERRORS.InvalidSocksClientOptionsCustomAuthOptions, options); + } + // Missing/invalid custom_auth_response_handler + if (proxy.custom_auth_response_handler === undefined || + typeof proxy.custom_auth_response_handler !== 'function') { + throw new util_1.SocksClientError(constants_1.ERRORS.InvalidSocksClientOptionsCustomAuthOptions, options); + } + } +} +/** + * Validates a SocksRemoteHost + * @param remoteHost { SocksRemoteHost } + */ +function isValidSocksRemoteHost(remoteHost) { + return (remoteHost && + typeof remoteHost.host === 'string' && + typeof remoteHost.port === 'number' && + remoteHost.port >= 0 && + remoteHost.port <= 65535); +} +/** + * Validates a SocksProxy + * @param proxy { SocksProxy } + */ +function isValidSocksProxy(proxy) { + return (proxy && + (typeof proxy.host === 'string' || typeof proxy.ipaddress === 'string') && + typeof proxy.port === 'number' && + proxy.port >= 0 && + proxy.port <= 65535 && + (proxy.type === 4 || proxy.type === 5)); +} +/** + * Validates a timeout value. + * @param value { Number } + */ +function isValidTimeoutValue(value) { + return typeof value === 'number' && value > 0; +} +//# sourceMappingURL=helpers.js.map \ No newline at end of file diff --git a/ts-ticket-office-service/node_modules/socks/build/common/helpers.js.map b/ts-ticket-office-service/node_modules/socks/build/common/helpers.js.map new file mode 100644 index 000000000..dae124861 --- /dev/null +++ b/ts-ticket-office-service/node_modules/socks/build/common/helpers.js.map @@ -0,0 +1 @@ +{"version":3,"file":"helpers.js","sourceRoot":"","sources":["../../src/common/helpers.ts"],"names":[],"mappings":";;;AAKA,iCAAwC;AACxC,2CAMqB;AACrB,iCAAiC;AAEjC;;;;GAIG;AACH,SAAS,0BAA0B,CACjC,OAA2B,EAC3B,gBAAgB,GAAG,CAAC,SAAS,EAAE,MAAM,EAAE,WAAW,CAAC;IAEnD,8BAA8B;IAC9B,IAAI,CAAC,wBAAY,CAAC,OAAO,CAAC,OAAO,CAAC,EAAE;QAClC,MAAM,IAAI,uBAAgB,CAAC,kBAAM,CAAC,mBAAmB,EAAE,OAAO,CAAC,CAAC;KACjE;IAED,6CAA6C;IAC7C,IAAI,gBAAgB,CAAC,OAAO,CAAC,OAAO,CAAC,OAAO,CAAC,KAAK,CAAC,CAAC,EAAE;QACpD,MAAM,IAAI,uBAAgB,CAAC,kBAAM,CAAC,+BAA+B,EAAE,OAAO,CAAC,CAAC;KAC7E;IAED,oBAAoB;IACpB,IAAI,CAAC,sBAAsB,CAAC,OAAO,CAAC,WAAW,CAAC,EAAE;QAChD,MAAM,IAAI,uBAAgB,CACxB,kBAAM,CAAC,oCAAoC,EAC3C,OAAO,CACR,CAAC;KACH;IAED,2BAA2B;IAC3B,IAAI,CAAC,iBAAiB,CAAC,OAAO,CAAC,KAAK,CAAC,EAAE;QACrC,MAAM,IAAI,uBAAgB,CAAC,kBAAM,CAAC,8BAA8B,EAAE,OAAO,CAAC,CAAC;KAC5E;IAED,gCAAgC;IAChC,uBAAuB,CAAC,OAAO,CAAC,KAAK,EAAE,OAAO,CAAC,CAAC;IAEhD,gBAAgB;IAChB,IAAI,OAAO,CAAC,OAAO,IAAI,CAAC,mBAAmB,CAAC,OAAO,CAAC,OAAO,CAAC,EAAE;QAC5D,MAAM,IAAI,uBAAgB,CACxB,kBAAM,CAAC,gCAAgC,EACvC,OAAO,CACR,CAAC;KACH;I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AAiB;IAC1C,OAAO,CACL,KAAK;QACL,CAAC,OAAO,KAAK,CAAC,IAAI,KAAK,QAAQ,IAAI,OAAO,KAAK,CAAC,SAAS,KAAK,QAAQ,CAAC;QACvE,OAAO,KAAK,CAAC,IAAI,KAAK,QAAQ;QAC9B,KAAK,CAAC,IAAI,IAAI,CAAC;QACf,KAAK,CAAC,IAAI,IAAI,KAAK;QACnB,CAAC,KAAK,CAAC,IAAI,KAAK,CAAC,IAAI,KAAK,CAAC,IAAI,KAAK,CAAC,CAAC,CACvC,CAAC;AACJ,CAAC;AAED;;;GAGG;AACH,SAAS,mBAAmB,CAAC,KAAa;IACxC,OAAO,OAAO,KAAK,KAAK,QAAQ,IAAI,KAAK,GAAG,CAAC,CAAC;AAChD,CAAC"} \ No newline at end of file diff --git a/ts-ticket-office-service/node_modules/socks/build/common/receivebuffer.js b/ts-ticket-office-service/node_modules/socks/build/common/receivebuffer.js new file mode 100644 index 000000000..3dacbf9b9 --- /dev/null +++ b/ts-ticket-office-service/node_modules/socks/build/common/receivebuffer.js @@ -0,0 +1,43 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.ReceiveBuffer = void 0; +class ReceiveBuffer { + constructor(size = 4096) { + this.buffer = Buffer.allocUnsafe(size); + this.offset = 0; + this.originalSize = size; + } + get length() { + return this.offset; + } + append(data) { + if (!Buffer.isBuffer(data)) { + throw new Error('Attempted to append a non-buffer instance to ReceiveBuffer.'); + } + if (this.offset + data.length >= this.buffer.length) { + const tmp = this.buffer; + this.buffer = Buffer.allocUnsafe(Math.max(this.buffer.length + this.originalSize, this.buffer.length + data.length)); + tmp.copy(this.buffer); + } + data.copy(this.buffer, this.offset); + return (this.offset += data.length); + } + peek(length) { + if (length > this.offset) { + throw new Error('Attempted to read beyond the bounds of the managed internal data.'); + } + return this.buffer.slice(0, length); + } + get(length) { + if (length > this.offset) { + throw new Error('Attempted to read beyond the bounds of the managed internal data.'); + } + const value = Buffer.allocUnsafe(length); + this.buffer.slice(0, length).copy(value); + this.buffer.copyWithin(0, length, length + this.offset - length); + this.offset -= length; + return value; + } +} +exports.ReceiveBuffer = ReceiveBuffer; +//# sourceMappingURL=receivebuffer.js.map \ No newline at end of file diff --git a/ts-ticket-office-service/node_modules/socks/build/common/receivebuffer.js.map b/ts-ticket-office-service/node_modules/socks/build/common/receivebuffer.js.map new file mode 100644 index 000000000..af5e22090 --- /dev/null +++ b/ts-ticket-office-service/node_modules/socks/build/common/receivebuffer.js.map @@ -0,0 +1 @@ +{"version":3,"file":"receivebuffer.js","sourceRoot":"","sources":["../../src/common/receivebuffer.ts"],"names":[],"mappings":";;;AAAA,MAAM,aAAa;IAKjB,YAAY,IAAI,GAAG,IAAI;QACrB,IAAI,CAAC,MAAM,GAAG,MAAM,CAAC,WAAW,CAAC,IAAI,CAAC,CAAC;QACvC,IAAI,CAAC,MAAM,GAAG,CAAC,CAAC;QAChB,IAAI,CAAC,YAAY,GAAG,IAAI,CAAC;IAC3B,CAAC;IAED,IAAI,MAAM;QACR,OAAO,IAAI,CAAC,MAAM,CAAC;IACrB,CAAC;IAED,MAAM,CAAC,IAAY;QACjB,IAAI,CAAC,MAAM,CAAC,QAAQ,CAAC,IAAI,CAAC,EAAE;YAC1B,MAAM,IAAI,KAAK,CACb,6DAA6D,CAC9D,CAAC;SACH;QAED,IAAI,IAAI,CAAC,MAAM,GAAG,IAAI,CAAC,MAAM,IAAI,IAAI,CAAC,MAAM,CAAC,MAAM,EAAE;YACnD,MAAM,GAAG,GAAG,IAAI,CAAC,MAAM,CAAC;YACxB,IAAI,CAAC,MAAM,GAAG,MAAM,CAAC,WAAW,CAC9B,IAAI,CAAC,GAAG,CACN,IAAI,CAAC,MAAM,CAAC,MAAM,GAAG,IAAI,CAAC,YAAY,EACtC,IAAI,CAAC,MAAM,CAAC,MAAM,GAAG,IAAI,CAAC,MAAM,CACjC,CACF,CAAC;YACF,GAAG,CAAC,IAAI,CAAC,IAAI,CAAC,MAAM,CAAC,CAAC;SACvB;QAED,IAAI,CAAC,IAAI,CAAC,IAAI,CAAC,MAAM,EAAE,IAAI,CAAC,MAAM,CAAC,CAAC;QACpC,OAAO,CAAC,IAAI,CAAC,MAAM,IAAI,IAAI,CAAC,MAAM,CAAC,CAAC;IACtC,CAAC;IAED,IAAI,CAAC,MAAc;QACjB,IAAI,MAAM,GAAG,IAAI,CAAC,MAAM,EAAE;YACxB,MAAM,IAAI,KAAK,CACb,mEAAmE,CACpE,CAAC;SACH;QACD,OAAO,IAAI,CAAC,MAAM,CAAC,KAAK,CAAC,CAAC,EAAE,MAAM,CAAC,CAAC;IACtC,CAAC;IAED,GAAG,CAAC,MAAc;QAChB,IAAI,MAAM,GAAG,IAAI,CAAC,MAAM,EAAE;YACxB,MAAM,IAAI,KAAK,CACb,mEAAmE,CACpE,CAAC;SACH;QAED,MAAM,KAAK,GAAG,MAAM,CAAC,WAAW,CAAC,MAAM,CAAC,CAAC;QACzC,IAAI,CAAC,MAAM,CAAC,KAAK,CAAC,CAAC,EAAE,MAAM,CAAC,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC;QACzC,IAAI,CAAC,MAAM,CAAC,UAAU,CAAC,CAAC,EAAE,MAAM,EAAE,MAAM,GAAG,IAAI,CAAC,MAAM,GAAG,MAAM,CAAC,CAAC;QACjE,IAAI,CAAC,MAAM,IAAI,MAAM,CAAC;QAEtB,OAAO,KAAK,CAAC;IACf,CAAC;CACF;AAEO,sCAAa"} \ No newline at end of file diff --git a/ts-ticket-office-service/node_modules/socks/build/common/util.js b/ts-ticket-office-service/node_modules/socks/build/common/util.js new file mode 100644 index 000000000..f66b72e43 --- /dev/null +++ b/ts-ticket-office-service/node_modules/socks/build/common/util.js @@ -0,0 +1,25 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.shuffleArray = exports.SocksClientError = void 0; +/** + * Error wrapper for SocksClient + */ +class SocksClientError extends Error { + constructor(message, options) { + super(message); + this.options = options; + } +} +exports.SocksClientError = SocksClientError; +/** + * Shuffles a given array. + * @param array The array to shuffle. + */ +function shuffleArray(array) { + for (let i = array.length - 1; i > 0; i--) { + const j = Math.floor(Math.random() * (i + 1)); + [array[i], array[j]] = [array[j], array[i]]; + } +} +exports.shuffleArray = shuffleArray; +//# sourceMappingURL=util.js.map \ No newline at end of file diff --git a/ts-ticket-office-service/node_modules/socks/build/common/util.js.map b/ts-ticket-office-service/node_modules/socks/build/common/util.js.map new file mode 100644 index 000000000..f1993233d --- /dev/null +++ b/ts-ticket-office-service/node_modules/socks/build/common/util.js.map @@ -0,0 +1 @@ +{"version":3,"file":"util.js","sourceRoot":"","sources":["../../src/common/util.ts"],"names":[],"mappings":";;;AAEA;;GAEG;AACH,MAAM,gBAAiB,SAAQ,KAAK;IAClC,YACE,OAAe,EACR,OAAqD;QAE5D,KAAK,CAAC,OAAO,CAAC,CAAC;QAFR,YAAO,GAAP,OAAO,CAA8C;IAG9D,CAAC;CACF;AAuBuB,4CAAgB;AArBxC;;;GAGG;AACH,SAAS,YAAY,CAAC,KAAgB;IACpC,KAAK,IAAI,CAAC,GAAG,KAAK,CAAC,MAAM,GAAG,CAAC,EAAE,CAAC,GAAG,CAAC,EAAE,CAAC,EAAE,EAAE;QACzC,MAAM,CAAC,GAAG,IAAI,CAAC,KAAK,CAAC,IAAI,CAAC,MAAM,EAAE,GAAG,CAAC,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC;QAC9C,CAAC,KAAK,CAAC,CAAC,CAAC,EAAE,KAAK,CAAC,CAAC,CAAC,CAAC,GAAG,CAAC,KAAK,CAAC,CAAC,CAAC,EAAE,KAAK,CAAC,CAAC,CAAC,CAAC,CAAC;KAC7C;AACH,CAAC;AAYyC,oCAAY"} \ No newline at end of file diff --git a/ts-ticket-office-service/node_modules/socks/build/index.js b/ts-ticket-office-service/node_modules/socks/build/index.js new file mode 100644 index 000000000..05fbb1d94 --- /dev/null +++ b/ts-ticket-office-service/node_modules/socks/build/index.js @@ -0,0 +1,18 @@ +"use strict"; +var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + var desc = Object.getOwnPropertyDescriptor(m, k); + if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { return m[k]; } }; + } + Object.defineProperty(o, k2, desc); +}) : (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + o[k2] = m[k]; +})); +var __exportStar = (this && this.__exportStar) || function(m, exports) { + for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p); +}; +Object.defineProperty(exports, "__esModule", { value: true }); +__exportStar(require("./client/socksclient"), exports); +//# sourceMappingURL=index.js.map \ No newline at end of file diff --git a/ts-ticket-office-service/node_modules/socks/build/index.js.map b/ts-ticket-office-service/node_modules/socks/build/index.js.map new file mode 100644 index 000000000..0e2bcb27b --- /dev/null +++ b/ts-ticket-office-service/node_modules/socks/build/index.js.map @@ -0,0 +1 @@ +{"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;AAAA,uDAAqC"} \ No newline at end of file diff --git a/ts-ticket-office-service/node_modules/socks/docs/examples/index.md b/ts-ticket-office-service/node_modules/socks/docs/examples/index.md new file mode 100644 index 000000000..87bfe250e --- /dev/null +++ b/ts-ticket-office-service/node_modules/socks/docs/examples/index.md @@ -0,0 +1,17 @@ +# socks examples + +## TypeScript Examples + +[Connect command](typescript/connectExample.md) + +[Bind command](typescript/bindExample.md) + +[Associate command](typescript/associateExample.md) + +## JavaScript Examples + +[Connect command](javascript/connectExample.md) + +[Bind command](javascript/bindExample.md) + +[Associate command](javascript/associateExample.md) \ No newline at end of file diff --git a/ts-ticket-office-service/node_modules/socks/docs/examples/javascript/associateExample.md b/ts-ticket-office-service/node_modules/socks/docs/examples/javascript/associateExample.md new file mode 100644 index 000000000..c2c7b17b7 --- /dev/null +++ b/ts-ticket-office-service/node_modules/socks/docs/examples/javascript/associateExample.md @@ -0,0 +1,90 @@ +# socks examples + +## Example for SOCKS 'associate' command + +The associate command tells the SOCKS proxy server to establish a UDP relay. The server binds to a new UDP port and communicates the newly opened port back to the origin client. From here, any SOCKS UDP frame packets sent to this special UDP port on the Proxy server will be forwarded to the desired destination, and any responses will be forwarded back to the origin client (you). + +This can be used for things such as DNS queries, and other UDP communicates. + +**Connection Steps** + +1. Client -(associate)-> Proxy (Tells the proxy to create a UDP relay and bind on a new port) +2. Client <-(port)- Proxy (Tells the origin client which port it opened and is accepting UDP frame packets on) + +At this point the proxy is accepting UDP frames on the specified port. + +3. Client --(udp frame) -> Proxy -> Destination (The origin client sends a UDP frame to the proxy on the UDP port, and the proxy then forwards it to the destination specified in the UDP frame.) +4. Client <--(udp frame) <-- Proxy <-- Destination (The destination client responds to the udp packet sent in #3) + +## Usage + +The 'associate' command can only be used by creating a new SocksClient instance and listening for the 'established' event. + +**Note:** UDP packets relayed through the proxy servers are encompassed in a special Socks UDP frame format. SocksClient.createUDPFrame() and SocksClient.parseUDPFrame() create and parse these special UDP packets. + +```typescript +const dgram = require('dgram'); +const SocksClient = require('socks').SocksClient; + +// Create a local UDP socket for sending/receiving packets to/from the proxy. +const udpSocket = dgram.createSocket('udp4'); +udpSocket.bind(); + +// Listen for incoming UDP packets from the proxy server. +udpSocket.on('message', (message, rinfo) => { + console.log(SocksClient.parseUDPFrame(message)); + /* + { frameNumber: 0, + remoteHost: { host: '8.8.8.8', port: 53 }, // The remote host that replied with a UDP packet + data: // The data + } + */ +}); + +const options = { + proxy: { + host: '104.131.124.203', + port: 1081, + type: 5 + }, + + // This should be the ip and port of the expected client that will be sending UDP frames to the newly opened UDP port on the server. + // Most SOCKS servers accept 0.0.0.0 as a wildcard address to accept UDP frames from any source. + destination: { + host: '0.0.0.0', + port: 0 + }, + + command: 'associate' +}; + +const client = new SocksClient(options); + +// This event is fired when the SOCKS server has started listening on a new UDP port for UDP relaying. +client.on('established', info => { + console.log(info); + /* + { + socket: , + remoteHost: { // This is the remote port on the SOCKS proxy server to send UDP frame packets to. + host: '104.131.124.203', + port: 58232 + } + } + */ + + // Send a udp frame to 8.8.8.8 on port 53 through the proxy. + const packet = SocksClient.createUDPFrame({ + remoteHost: { host: '8.8.8.8', port: 53 }, + data: Buffer.from('hello') // A DNS lookup in the real world. + }); + + // Send packet. + udpSocket.send(packet, info.remoteHost.port, info.remoteHost.host); +}); + +// SOCKS proxy failed to bind. +client.on('error', () => { + // Handle errors +}); +``` diff --git a/ts-ticket-office-service/node_modules/socks/docs/examples/javascript/bindExample.md b/ts-ticket-office-service/node_modules/socks/docs/examples/javascript/bindExample.md new file mode 100644 index 000000000..be601d522 --- /dev/null +++ b/ts-ticket-office-service/node_modules/socks/docs/examples/javascript/bindExample.md @@ -0,0 +1,83 @@ +# socks examples + +## Example for SOCKS 'bind' command + +The bind command tells the SOCKS proxy server to bind and listen on a new TCP port for an incoming connection. It communicates the newly opened port back to the origin client. Once a incoming connection is accepted by the SOCKS proxy server it then communicates the remote host that connected to the SOCKS proxy back through the same initial connection via the origin client. + +This can be used for things such as FTP clients which require incoming TCP connections, etc. + +**Connection Steps** + +1. Client -(bind)-> Proxy (Tells the proxy to bind to a new port) +2. Client <-(port)- Proxy (Tells the origin client which port it opened) +3. Client2 --> Proxy (Other client connects to the proxy on this port) +4. Client <--(client2's host info) (Proxy tells the origin client who connected to it) +5. Original connection to the proxy is now a full TCP stream between client (you) and client2. +6. Client <--> Proxy <--> Client2 + + +## Usage + +The 'bind' command can only be used by creating a new SocksClient instance and listening for 'bound' and 'established' events. + + +```typescript +const SocksClient = require('socks').SocksClient; + +const options = { + proxy: { + host: '104.131.124.203', + port: 1081, + type: 5 + }, + + // This should be the ip and port of the expected client that will connect to the SOCKS proxy server on the newly bound port. + // Most SOCKS servers accept 0.0.0.0 as a wildcard address to accept any client. + destination: { + host: '0.0.0.0', + port: 0 + }, + + command: 'bind' +}; + +const client = new SocksClient(options); + +// This event is fired when the SOCKS server has started listening on a new port for incoming connections. +client.on('bound', (info) => { + console.log(info); + /* + { + socket: , + remoteHost: { // This is the remote ip and port of the SOCKS proxy that is now accepting incoming connections. + host: '104.131.124.203', + port: 49928 + } + } + */ +}); + +// This event is fired when the SOCKS server has accepted an incoming connection on the newly bound port. +client.on('established', (info) => { + console.log(info); + /* + { + socket: , + remoteHost: { // This is the remote ip and port that connected to the SOCKS proxy on the newly bound port. + host: '1.2.3.4', + port: 58232 + } + } + */ + + // At this point info.socket is a regular net.Socket TCP connection between client and client2 (1.2.3.4) (the client which connected to the proxy on the newly bound port.) + + console.log(info.socket); + // (this is a raw net.Socket that is established to the destination host through the given proxy servers) +}); + +// SOCKS proxy failed to bind. +client.on('error', () => { + // Handle errors +}); +``` \ No newline at end of file diff --git a/ts-ticket-office-service/node_modules/socks/docs/examples/javascript/connectExample.md b/ts-ticket-office-service/node_modules/socks/docs/examples/javascript/connectExample.md new file mode 100644 index 000000000..66244c5b8 --- /dev/null +++ b/ts-ticket-office-service/node_modules/socks/docs/examples/javascript/connectExample.md @@ -0,0 +1,258 @@ +# socks examples + +## Example for SOCKS 'connect' command + +The connect command is the most common use-case for a SOCKS proxy. This establishes a direct connection to a destination host through a proxy server. The destination host only has knowledge of the proxy server connecting to it and does not know about the origin client (you). + +**Origin Client (you) <-> Proxy Server <-> Destination Server** + +In this example, we are connecting to a web server on port 80, and sending a very basic HTTP request to receive a response. It's worth noting that there are many socks-http-agents that can be used with the node http module (and libraries such as request.js) to make this easier. This HTTP request is used as a simple example. + +The 'connect' command can be used via the SocksClient.createConnection() factory function as well as by creating a SocksClient instance and using event handlers. + +### Using createConnection with async/await + +Since SocksClient.createConnection returns a Promise, we can easily use async/await for flow control. + +```typescript +const SocksClient = require('socks').SocksClient; + +const options = { + proxy: { + host: '104.131.124.203', + port: 1081, + type: 5 + }, + + destination: { + host: 'ip-api.com', // host names are supported with SOCKS v4a and SOCKS v5. + port: 80 + }, + + command: 'connect' +}; + +async function start() { + try { + const info = await SocksClient.createConnection(options); + + console.log(info.socket); + // (this is a raw net.Socket that is established to the destination host through the given proxy servers) + + info.socket.write('GET /json HTTP/1.1\nHost: ip-api.com\n\n'); + info.socket.on('data', (data) => { + console.log(data.toString()); // ip-api.com sees that the last proxy (104.131.124.203) is connected to it and not the origin client (you). + /* + HTTP/1.1 200 OK + Access-Control-Allow-Origin: * + Content-Type: application/json; charset=utf-8 + Date: Sun, 24 Dec 2017 03:47:51 GMT + Content-Length: 300 + + { + "as":"AS14061 Digital Ocean, Inc.", + "city":"Clifton", + "country":"United States", + "countryCode":"US", + "isp":"Digital Ocean", + "lat":40.8326, + "lon":-74.1307, + "org":"Digital Ocean", + "query":"104.131.124.203", + "region":"NJ", + "regionName":"New Jersey", + "status":"success", + "timezone":"America/New_York", + "zip":"07014" + } + */ + } catch (err) { + // Handle errors + } +} + +start(); +``` + +### Using createConnection with Promises + +```typescript +const SocksClient = require('socks').SocksClient; + +const options = { + proxy: { + ipaddress: '104.131.124.203', + port: 1081, + type: 5 + }, + + destination: { + host: 'ip-api.com', // host names are supported with SOCKS v4a and SOCKS v5. + port: 80 + }, + + command: 'connect' +}; + +SocksClient.createConnection(options) +.then(info => { + console.log(info.socket); + // (this is a raw net.Socket that is established to the destination host through the given proxy servers) + + info.socket.write('GET /json HTTP/1.1\nHost: ip-api.com\n\n'); + info.socket.on('data', (data) => { + console.log(data.toString()); // ip-api.com sees that the last proxy (104.131.124.203) is connected to it and not the origin client (you). + /* + HTTP/1.1 200 OK + Access-Control-Allow-Origin: * + Content-Type: application/json; charset=utf-8 + Date: Sun, 24 Dec 2017 03:47:51 GMT + Content-Length: 300 + + { + "as":"AS14061 Digital Ocean, Inc.", + "city":"Clifton", + "country":"United States", + "countryCode":"US", + "isp":"Digital Ocean", + "lat":40.8326, + "lon":-74.1307, + "org":"Digital Ocean", + "query":"104.131.124.203", + "region":"NJ", + "regionName":"New Jersey", + "status":"success", + "timezone":"America/New_York", + "zip":"07014" + } + */ +}) +.catch(err => { + // handle errors +}); +``` + +### Using createConnection with callbacks + +SocksClient.createConnection() optionally accepts a callback function as a second parameter. + +**Note:** If a callback function is provided, a Promise is still returned from the function, but the promise will always resolve regardless of if there was en error. (tldr: Do not mix callbacks and Promises). + +```typescript +const SocksClient = require('socks').SocksClient; + +const options = { + proxy: { + ipaddress: '104.131.124.203', + port: 1081, + type: 5 + }, + + destination: { + host: 'ip-api.com', // host names are supported with SOCKS v4a and SOCKS v5. + port: 80 + }, + + command: 'connect' +}; + +SocksClient.createConnection(options, (err, info) => { + if (err) { + // handle errors + } else { + console.log(info.socket); + // (this is a raw net.Socket that is established to the destination host through the given proxy servers) + + info.socket.write('GET /json HTTP/1.1\nHost: ip-api.com\n\n'); + info.socket.on('data', (data) => { + console.log(data.toString()); // ip-api.com sees that the last proxy (104.131.124.203) is connected to it and not the origin client (you). + /* + HTTP/1.1 200 OK + Access-Control-Allow-Origin: * + Content-Type: application/json; charset=utf-8 + Date: Sun, 24 Dec 2017 03:47:51 GMT + Content-Length: 300 + + { + "as":"AS14061 Digital Ocean, Inc.", + "city":"Clifton", + "country":"United States", + "countryCode":"US", + "isp":"Digital Ocean", + "lat":40.8326, + "lon":-74.1307, + "org":"Digital Ocean", + "query":"104.131.124.203", + "region":"NJ", + "regionName":"New Jersey", + "status":"success", + "timezone":"America/New_York", + "zip":"07014" + } + */ + } +}) +``` + +### Using event handlers + +SocksClient also supports instance creation of a SocksClient. This allows for event based flow control. + +```typescript +const SocksClient = require('socks').SocksClient; + +const options = { + proxy: { + ipaddress: '104.131.124.203', + port: 1081, + type: 5 + }, + + destination: { + host: 'ip-api.com', // host names are supported with SOCKS v4a and SOCKS v5. + port: 80 + }, + + command: 'connect' +}; + +const client = new SocksClient(options); + +client.on('established', (info) => { + console.log(info.socket); + // (this is a raw net.Socket that is established to the destination host through the given proxy servers) + + info.socket.write('GET /json HTTP/1.1\nHost: ip-api.com\n\n'); + info.socket.on('data', (data) => { + console.log(data.toString()); // ip-api.com sees that the last proxy (104.131.124.203) is connected to it and not the origin client (you). + /* + HTTP/1.1 200 OK + Access-Control-Allow-Origin: * + Content-Type: application/json; charset=utf-8 + Date: Sun, 24 Dec 2017 03:47:51 GMT + Content-Length: 300 + + { + "as":"AS14061 Digital Ocean, Inc.", + "city":"Clifton", + "country":"United States", + "countryCode":"US", + "isp":"Digital Ocean", + "lat":40.8326, + "lon":-74.1307, + "org":"Digital Ocean", + "query":"104.131.124.203", + "region":"NJ", + "regionName":"New Jersey", + "status":"success", + "timezone":"America/New_York", + "zip":"07014" + } + */ +}); + +// Failed to establish proxy connection to destination. +client.on('error', () => { + // Handle errors +}); +``` \ No newline at end of file diff --git a/ts-ticket-office-service/node_modules/socks/docs/examples/typescript/associateExample.md b/ts-ticket-office-service/node_modules/socks/docs/examples/typescript/associateExample.md new file mode 100644 index 000000000..e8ca19344 --- /dev/null +++ b/ts-ticket-office-service/node_modules/socks/docs/examples/typescript/associateExample.md @@ -0,0 +1,93 @@ +# socks examples + +## Example for SOCKS 'associate' command + +The associate command tells the SOCKS proxy server to establish a UDP relay. The server binds to a new UDP port and communicates the newly opened port back to the origin client. From here, any SOCKS UDP frame packets sent to this special UDP port on the Proxy server will be forwarded to the desired destination, and any responses will be forwarded back to the origin client (you). + +This can be used for things such as DNS queries, and other UDP communicates. + +**Connection Steps** + +1. Client -(associate)-> Proxy (Tells the proxy to create a UDP relay and bind on a new port) +2. Client <-(port)- Proxy (Tells the origin client which port it opened and is accepting UDP frame packets on) + +At this point the proxy is accepting UDP frames on the specified port. + +3. Client --(udp frame) -> Proxy -> Destination (The origin client sends a UDP frame to the proxy on the UDP port, and the proxy then forwards it to the destination specified in the UDP frame.) +4. Client <--(udp frame) <-- Proxy <-- Destination (The destination client responds to the udp packet sent in #3) + +## Usage + +The 'associate' command can only be used by creating a new SocksClient instance and listening for the 'established' event. + +**Note:** UDP packets relayed through the proxy servers are packaged in a special Socks UDP frame format. SocksClient.createUDPFrame() and SocksClient.parseUDPFrame() create and parse these special UDP packets. + +```typescript +import * as dgram from 'dgram'; +import { SocksClient, SocksClientOptions } from 'socks'; + +// Create a local UDP socket for sending/receiving packets to/from the proxy. +const udpSocket = dgram.createSocket('udp4'); +udpSocket.bind(); + +// Listen for incoming UDP packets from the proxy server. +udpSocket.on('message', (message, rinfo) => { + console.log(SocksClient.parseUDPFrame(message)); + /* + { frameNumber: 0, + remoteHost: { host: '8.8.8.8', port: 53 }, // The remote host that replied with a UDP packet + data: // The data + } + */ +}); + +const options: SocksClientOptions = { + proxy: { + host: '104.131.124.203', + port: 1081, + type: 5 + }, + + // This should be the ip and port of the expected client that will be sending UDP frames to the newly opened UDP port on the server. + // Most SOCKS servers accept 0.0.0.0 as a wildcard address to accept UDP frames from any source. + destination: { + host: '0.0.0.0', + port: 0 + }, + + command: 'associate' +}; + +const client = new SocksClient(options); + +// This event is fired when the SOCKS server has started listening on a new UDP port for UDP relaying. +client.on('established', info => { + console.log(info); + /* + { + socket: , + remoteHost: { // This is the remote port on the SOCKS proxy server to send UDP frame packets to. + host: '104.131.124.203', + port: 58232 + } + } + */ + + // Send a udp frame to 8.8.8.8 on port 53 through the proxy. + const packet = SocksClient.createUDPFrame({ + remoteHost: { host: '8.8.8.8', port: 53 }, + data: Buffer.from('hello') // A DNS lookup in the real world. + }); + + // Send packet. + udpSocket.send(packet, info.remoteHost.port, info.remoteHost.host); +}); + +// SOCKS proxy failed to bind. +client.on('error', () => { + // Handle errors +}); + +// Start connection +client.connect(); +``` diff --git a/ts-ticket-office-service/node_modules/socks/docs/examples/typescript/bindExample.md b/ts-ticket-office-service/node_modules/socks/docs/examples/typescript/bindExample.md new file mode 100644 index 000000000..6b7607df7 --- /dev/null +++ b/ts-ticket-office-service/node_modules/socks/docs/examples/typescript/bindExample.md @@ -0,0 +1,86 @@ +# socks examples + +## Example for SOCKS 'bind' command + +The bind command tells the SOCKS proxy server to bind and listen on a new TCP port for an incoming connection. It communicates the newly opened port back to the origin client. Once a incoming connection is accepted by the SOCKS proxy server it then communicates the remote host that connected to the SOCKS proxy back through the same initial connection via the origin client. + +This can be used for things such as FTP clients which require incoming TCP connections, etc. + +**Connection Steps** + +1. Client -(bind)-> Proxy (Tells the proxy to bind to a new port) +2. Client <-(port)- Proxy (Tells the origin client which port it opened) +3. Client2 --> Proxy (Other client connects to the proxy on this port) +4. Client <--(client2's host info) (Proxy tells the origin client who connected to it) +5. Original connection to the proxy is now a full TCP stream between client (you) and client2. +6. Client <--> Proxy <--> Client2 + + +## Usage + +The 'bind' command can only be used by creating a new SocksClient instance and listening for 'bound' and 'established' events. + + +```typescript +import { SocksClient, SocksClientOptions } from 'socks'; + +const options: SocksClientOptions = { + proxy: { + host: '104.131.124.203', + port: 1081, + type: 5 + }, + + // This should be the ip and port of the expected client that will connect to the SOCKS proxy server on the newly bound port. + // Most SOCKS servers accept 0.0.0.0 as a wildcard address to accept any client. + destination: { + host: '0.0.0.0', + port: 0 + }, + + command: 'bind' +}; + +const client = new SocksClient(options); + +// This event is fired when the SOCKS server has started listening on a new port for incoming connections. +client.on('bound', (info) => { + console.log(info); + /* + { + socket: , + remoteHost: { // This is the remote ip and port of the SOCKS proxy that is now accepting incoming connections. + host: '104.131.124.203', + port: 49928 + } + } + */ +}); + +// This event is fired when the SOCKS server has accepted an incoming connection on the newly bound port. +client.on('established', (info) => { + console.log(info); + /* + { + socket: , + remoteHost: { // This is the remote ip and port that connected to the SOCKS proxy on the newly bound port. + host: '1.2.3.4', + port: 58232 + } + } + */ + + // At this point info.socket is a regular net.Socket TCP connection between client and client2 (1.2.3.4) (the client which connected to the proxy on the newly bound port.) + + console.log(info.socket); + // (this is a raw net.Socket that is established to the destination host through the given proxy servers) +}); + +// SOCKS proxy failed to bind. +client.on('error', () => { + // Handle errors +}); + +// Start connection +client.connect(); +``` \ No newline at end of file diff --git a/ts-ticket-office-service/node_modules/socks/docs/examples/typescript/connectExample.md b/ts-ticket-office-service/node_modules/socks/docs/examples/typescript/connectExample.md new file mode 100644 index 000000000..30606d0ba --- /dev/null +++ b/ts-ticket-office-service/node_modules/socks/docs/examples/typescript/connectExample.md @@ -0,0 +1,265 @@ +# socks examples + +## Example for SOCKS 'connect' command + +The connect command is the most common use-case for a SOCKS proxy. This establishes a direct connection to a destination host through a proxy server. The destination host only has knowledge of the proxy server connecting to it and does not know about the origin client (you). + +**Origin Client (you) <-> Proxy Server <-> Destination Server** + +In this example, we are connecting to a web server on port 80, and sending a very basic HTTP request to receive a response. It's worth noting that there are many socks-http-agents that can be used with the node http module (and libraries such as request.js) to make this easier. This HTTP request is used as a simple example. + +The 'connect' command can be used via the SocksClient.createConnection() factory function as well as by creating a SocksClient instance and using event handlers. + +### Using createConnection with async/await + +Since SocksClient.createConnection returns a Promise, we can easily use async/await for flow control. + +```typescript +import { SocksClient, SocksClientOptions } from 'socks'; + +const options: SocksClientOptions = { + proxy: { + host: '104.131.124.203', + port: 1081, + type: 5 + }, + + destination: { + host: 'ip-api.com', // host names are supported with SOCKS v4a and SOCKS v5. + port: 80 + }, + + command: 'connect' +}; + +async function start() { + try { + const info = await SocksClient.createConnection(options); + + console.log(info.socket); + // (this is a raw net.Socket that is established to the destination host through the given proxy servers) + + info.socket.write('GET /json HTTP/1.1\nHost: ip-api.com\n\n'); + info.socket.on('data', (data) => { + console.log(data.toString()); // ip-api.com sees that the last proxy (104.131.124.203) is connected to it and not the origin client (you). + /* + HTTP/1.1 200 OK + Access-Control-Allow-Origin: * + Content-Type: application/json; charset=utf-8 + Date: Sun, 24 Dec 2017 03:47:51 GMT + Content-Length: 300 + + { + "as":"AS14061 Digital Ocean, Inc.", + "city":"Clifton", + "country":"United States", + "countryCode":"US", + "isp":"Digital Ocean", + "lat":40.8326, + "lon":-74.1307, + "org":"Digital Ocean", + "query":"104.131.124.203", + "region":"NJ", + "regionName":"New Jersey", + "status":"success", + "timezone":"America/New_York", + "zip":"07014" + } + */ + }); + } catch (err) { + // Handle errors + } +} + +start(); +``` + +### Using createConnection with Promises + +```typescript +import { SocksClient, SocksClientOptions } from 'socks'; + +const options: SocksClientOptions = { + proxy: { + ipaddress: '104.131.124.203', + port: 1081, + type: 5 + }, + + destination: { + host: 'ip-api.com', // host names are supported with SOCKS v4a and SOCKS v5. + port: 80 + }, + + command: 'connect' +}; + +SocksClient.createConnection(options) +.then(info => { + console.log(info.socket); + // (this is a raw net.Socket that is established to the destination host through the given proxy servers) + + info.socket.write('GET /json HTTP/1.1\nHost: ip-api.com\n\n'); + info.socket.on('data', (data) => { + console.log(data.toString()); // ip-api.com sees that the last proxy (104.131.124.203) is connected to it and not the origin client (you). + /* + HTTP/1.1 200 OK + Access-Control-Allow-Origin: * + Content-Type: application/json; charset=utf-8 + Date: Sun, 24 Dec 2017 03:47:51 GMT + Content-Length: 300 + + { + "as":"AS14061 Digital Ocean, Inc.", + "city":"Clifton", + "country":"United States", + "countryCode":"US", + "isp":"Digital Ocean", + "lat":40.8326, + "lon":-74.1307, + "org":"Digital Ocean", + "query":"104.131.124.203", + "region":"NJ", + "regionName":"New Jersey", + "status":"success", + "timezone":"America/New_York", + "zip":"07014" + } + */ + }); +}) +.catch(err => { + // handle errors +}); +``` + +### Using createConnection with callbacks + +SocksClient.createConnection() optionally accepts a callback function as a second parameter. + +**Note:** If a callback function is provided, a Promise is still returned from the function, but the promise will always resolve regardless of if there was en error. (tldr: Do not mix callbacks and Promises). + +```typescript +import { SocksClient, SocksClientOptions } from 'socks'; + +const options: SocksClientOptions = { + proxy: { + ipaddress: '104.131.124.203', + port: 1081, + type: 5 + }, + + destination: { + host: 'ip-api.com', // host names are supported with SOCKS v4a and SOCKS v5. + port: 80 + }, + + command: 'connect' +}; + +SocksClient.createConnection(options, (err, info) => { + if (err) { + // handle errors + } else { + console.log(info.socket); + // (this is a raw net.Socket that is established to the destination host through the given proxy servers) + + info.socket.write('GET /json HTTP/1.1\nHost: ip-api.com\n\n'); + info.socket.on('data', (data) => { + console.log(data.toString()); // ip-api.com sees that the last proxy (104.131.124.203) is connected to it and not the origin client (you). + /* + HTTP/1.1 200 OK + Access-Control-Allow-Origin: * + Content-Type: application/json; charset=utf-8 + Date: Sun, 24 Dec 2017 03:47:51 GMT + Content-Length: 300 + + { + "as":"AS14061 Digital Ocean, Inc.", + "city":"Clifton", + "country":"United States", + "countryCode":"US", + "isp":"Digital Ocean", + "lat":40.8326, + "lon":-74.1307, + "org":"Digital Ocean", + "query":"104.131.124.203", + "region":"NJ", + "regionName":"New Jersey", + "status":"success", + "timezone":"America/New_York", + "zip":"07014" + } + */ + }); + } +}) +``` + +### Using event handlers + +SocksClient also supports instance creation of a SocksClient. This allows for event based flow control. + +```typescript +import { SocksClient, SocksClientOptions } from 'socks'; + +const options: SocksClientOptions = { + proxy: { + ipaddress: '104.131.124.203', + port: 1081, + type: 5 + }, + + destination: { + host: 'ip-api.com', // host names are supported with SOCKS v4a and SOCKS v5. + port: 80 + }, + + command: 'connect' +}; + +const client = new SocksClient(options); + +client.on('established', (info) => { + console.log(info.socket); + // (this is a raw net.Socket that is established to the destination host through the given proxy servers) + + info.socket.write('GET /json HTTP/1.1\nHost: ip-api.com\n\n'); + info.socket.on('data', (data) => { + console.log(data.toString()); // ip-api.com sees that the last proxy (104.131.124.203) is connected to it and not the origin client (you). + /* + HTTP/1.1 200 OK + Access-Control-Allow-Origin: * + Content-Type: application/json; charset=utf-8 + Date: Sun, 24 Dec 2017 03:47:51 GMT + Content-Length: 300 + + { + "as":"AS14061 Digital Ocean, Inc.", + "city":"Clifton", + "country":"United States", + "countryCode":"US", + "isp":"Digital Ocean", + "lat":40.8326, + "lon":-74.1307, + "org":"Digital Ocean", + "query":"104.131.124.203", + "region":"NJ", + "regionName":"New Jersey", + "status":"success", + "timezone":"America/New_York", + "zip":"07014" + } + */ + }); +}); + +// Failed to establish proxy connection to destination. +client.on('error', () => { + // Handle errors +}); + +// Start connection +client.connect(); +``` \ No newline at end of file diff --git a/ts-ticket-office-service/node_modules/socks/docs/index.md b/ts-ticket-office-service/node_modules/socks/docs/index.md new file mode 100644 index 000000000..3eb1d7118 --- /dev/null +++ b/ts-ticket-office-service/node_modules/socks/docs/index.md @@ -0,0 +1,5 @@ +# Documentation + +- [API Reference](https://github.com/JoshGlazebrook/socks#api-reference) + +- [Code Examples](./examples/index.md) \ No newline at end of file diff --git a/ts-ticket-office-service/node_modules/socks/docs/migratingFromV1.md b/ts-ticket-office-service/node_modules/socks/docs/migratingFromV1.md new file mode 100644 index 000000000..dd008384b --- /dev/null +++ b/ts-ticket-office-service/node_modules/socks/docs/migratingFromV1.md @@ -0,0 +1,86 @@ +# socks + +## Migrating from v1 + +For the most part, migrating from v1 takes minimal effort as v2 still supports factory creation of proxy connections with callback support. + +### Notable breaking changes + +- In an options object, the proxy 'command' is now required and does not default to 'connect'. +- **In an options object, 'target' is now known as 'destination'.** +- Sockets are no longer paused after a SOCKS connection is made, so socket.resume() is no longer required. (Please be sure to attach data handlers immediately to the Socket to avoid losing data). +- In v2, only the 'connect' command is supported via the factory SocksClient.createConnection function. (BIND and ASSOCIATE must be used with a SocksClient instance via event handlers). +- In v2, the factory SocksClient.createConnection function callback is called with a single object rather than separate socket and info object. +- A SOCKS http/https agent is no longer bundled into the library. + +For informational purposes, here is the original getting started example from v1 converted to work with v2. + +### Before (v1) + +```javascript +var Socks = require('socks'); + +var options = { + proxy: { + ipaddress: "202.101.228.108", + port: 1080, + type: 5 + }, + target: { + host: "google.com", + port: 80 + }, + command: 'connect' +}; + +Socks.createConnection(options, function(err, socket, info) { + if (err) + console.log(err); + else { + socket.write("GET / HTTP/1.1\nHost: google.com\n\n"); + socket.on('data', function(data) { + console.log(data.length); + console.log(data); + }); + + // PLEASE NOTE: sockets need to be resumed before any data will come in or out as they are paused right before this callback is fired. + socket.resume(); + + // 569 + // = 10.13.0", + "npm": ">= 3.0.0" + }, + "author": "Josh Glazebrook", + "contributors": [ + "castorw" + ], + "license": "MIT", + "readmeFilename": "README.md", + "devDependencies": { + "@types/ip": "1.1.0", + "@types/mocha": "^9.1.1", + "@types/node": "^18.0.6", + "@typescript-eslint/eslint-plugin": "^5.30.6", + "@typescript-eslint/parser": "^5.30.6", + "eslint": "^8.20.0", + "mocha": "^10.0.0", + "prettier": "^2.7.1", + "ts-node": "^10.9.1", + "typescript": "^4.7.4" + }, + "dependencies": { + "ip": "^2.0.0", + "smart-buffer": "^4.2.0" + }, + "scripts": { + "prepublish": "npm install -g typescript && npm run build", + "test": "NODE_ENV=test mocha --recursive --require ts-node/register test/**/*.ts", + "prettier": "prettier --write ./src/**/*.ts --config .prettierrc.yaml", + "lint": "eslint 'src/**/*.ts'", + "build": "rm -rf build typings && prettier --write ./src/**/*.ts --config .prettierrc.yaml && tsc -p ." + } +} diff --git a/ts-ticket-office-service/node_modules/sparse-bitfield/.npmignore b/ts-ticket-office-service/node_modules/sparse-bitfield/.npmignore new file mode 100644 index 000000000..3c3629e64 --- /dev/null +++ b/ts-ticket-office-service/node_modules/sparse-bitfield/.npmignore @@ -0,0 +1 @@ +node_modules diff --git a/ts-ticket-office-service/node_modules/sparse-bitfield/LICENSE b/ts-ticket-office-service/node_modules/sparse-bitfield/LICENSE new file mode 100644 index 000000000..bae9da7bf --- /dev/null +++ b/ts-ticket-office-service/node_modules/sparse-bitfield/LICENSE @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) 2016 Mathias Buus + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. diff --git a/ts-ticket-office-service/node_modules/sparse-bitfield/README.md b/ts-ticket-office-service/node_modules/sparse-bitfield/README.md new file mode 100644 index 000000000..7b6b8f9ed --- /dev/null +++ b/ts-ticket-office-service/node_modules/sparse-bitfield/README.md @@ -0,0 +1,62 @@ +# sparse-bitfield + +Bitfield implementation that allocates a series of 1kb buffers to support sparse bitfields +without allocating a massive buffer. If you want to simple implementation of a flat bitfield +see the [bitfield](https://github.com/fb55/bitfield) module. + +This module is mostly useful if you need a big bitfield where you won't nessecarily set every bit. + +``` +npm install sparse-bitfield +``` + +[![build status](http://img.shields.io/travis/mafintosh/sparse-bitfield.svg?style=flat)](http://travis-ci.org/mafintosh/sparse-bitfield) + +## Usage + +``` js +var bitfield = require('sparse-bitfield') +var bits = bitfield() + +bits.set(0, true) // set first bit +bits.set(1, true) // set second bit +bits.set(1000000000000, true) // set the 1.000.000.000.000th bit +``` + +Running the above example will allocate two 1kb buffers internally. +Each 1kb buffer can hold information about 8192 bits so the first one will be used to store information about the first two bits and the second will be used to store the 1.000.000.000.000th bit. + +## API + +#### `var bits = bitfield([options])` + +Create a new bitfield. Options include + +``` js +{ + pageSize: 1024, // how big should the partial buffers be + buffer: anExistingBitfield, + trackUpdates: false // track when pages are being updated in the pager +} +``` + +#### `bits.set(index, value)` + +Set a bit to true or false. + +#### `bits.get(index)` + +Get the value of a bit. + +#### `bits.pages` + +A [memory-pager](https://github.com/mafintosh/memory-pager) instance that is managing the underlying memory. +If you set `trackUpdates` to true in the constructor you can use `.lastUpdate()` on this instance to get the last updated memory page. + +#### `var buffer = bits.toBuffer()` + +Get a single buffer representing the entire bitfield. + +## License + +MIT diff --git a/ts-ticket-office-service/node_modules/sparse-bitfield/index.js b/ts-ticket-office-service/node_modules/sparse-bitfield/index.js new file mode 100644 index 000000000..ff458c974 --- /dev/null +++ b/ts-ticket-office-service/node_modules/sparse-bitfield/index.js @@ -0,0 +1,95 @@ +var pager = require('memory-pager') + +module.exports = Bitfield + +function Bitfield (opts) { + if (!(this instanceof Bitfield)) return new Bitfield(opts) + if (!opts) opts = {} + if (Buffer.isBuffer(opts)) opts = {buffer: opts} + + this.pageOffset = opts.pageOffset || 0 + this.pageSize = opts.pageSize || 1024 + this.pages = opts.pages || pager(this.pageSize) + + this.byteLength = this.pages.length * this.pageSize + this.length = 8 * this.byteLength + + if (!powerOfTwo(this.pageSize)) throw new Error('The page size should be a power of two') + + this._trackUpdates = !!opts.trackUpdates + this._pageMask = this.pageSize - 1 + + if (opts.buffer) { + for (var i = 0; i < opts.buffer.length; i += this.pageSize) { + this.pages.set(i / this.pageSize, opts.buffer.slice(i, i + this.pageSize)) + } + this.byteLength = opts.buffer.length + this.length = 8 * this.byteLength + } +} + +Bitfield.prototype.get = function (i) { + var o = i & 7 + var j = (i - o) / 8 + + return !!(this.getByte(j) & (128 >> o)) +} + +Bitfield.prototype.getByte = function (i) { + var o = i & this._pageMask + var j = (i - o) / this.pageSize + var page = this.pages.get(j, true) + + return page ? page.buffer[o + this.pageOffset] : 0 +} + +Bitfield.prototype.set = function (i, v) { + var o = i & 7 + var j = (i - o) / 8 + var b = this.getByte(j) + + return this.setByte(j, v ? b | (128 >> o) : b & (255 ^ (128 >> o))) +} + +Bitfield.prototype.toBuffer = function () { + var all = alloc(this.pages.length * this.pageSize) + + for (var i = 0; i < this.pages.length; i++) { + var next = this.pages.get(i, true) + var allOffset = i * this.pageSize + if (next) next.buffer.copy(all, allOffset, this.pageOffset, this.pageOffset + this.pageSize) + } + + return all +} + +Bitfield.prototype.setByte = function (i, b) { + var o = i & this._pageMask + var j = (i - o) / this.pageSize + var page = this.pages.get(j, false) + + o += this.pageOffset + + if (page.buffer[o] === b) return false + page.buffer[o] = b + + if (i >= this.byteLength) { + this.byteLength = i + 1 + this.length = this.byteLength * 8 + } + + if (this._trackUpdates) this.pages.updated(page) + + return true +} + +function alloc (n) { + if (Buffer.alloc) return Buffer.alloc(n) + var b = new Buffer(n) + b.fill(0) + return b +} + +function powerOfTwo (x) { + return !(x & (x - 1)) +} diff --git a/ts-ticket-office-service/node_modules/sparse-bitfield/package.json b/ts-ticket-office-service/node_modules/sparse-bitfield/package.json new file mode 100644 index 000000000..092a23f61 --- /dev/null +++ b/ts-ticket-office-service/node_modules/sparse-bitfield/package.json @@ -0,0 +1,27 @@ +{ + "name": "sparse-bitfield", + "version": "3.0.3", + "description": "Bitfield that allocates a series of small buffers to support sparse bits without allocating a massive buffer", + "main": "index.js", + "dependencies": { + "memory-pager": "^1.0.2" + }, + "devDependencies": { + "buffer-alloc": "^1.1.0", + "standard": "^9.0.0", + "tape": "^4.6.3" + }, + "scripts": { + "test": "standard && tape test.js" + }, + "repository": { + "type": "git", + "url": "https://github.com/mafintosh/sparse-bitfield.git" + }, + "author": "Mathias Buus (@mafintosh)", + "license": "MIT", + "bugs": { + "url": "https://github.com/mafintosh/sparse-bitfield/issues" + }, + "homepage": "https://github.com/mafintosh/sparse-bitfield" +} diff --git a/ts-ticket-office-service/node_modules/sparse-bitfield/test.js b/ts-ticket-office-service/node_modules/sparse-bitfield/test.js new file mode 100644 index 000000000..ae42ef467 --- /dev/null +++ b/ts-ticket-office-service/node_modules/sparse-bitfield/test.js @@ -0,0 +1,79 @@ +var alloc = require('buffer-alloc') +var tape = require('tape') +var bitfield = require('./') + +tape('set and get', function (t) { + var bits = bitfield() + + t.same(bits.get(0), false, 'first bit is false') + bits.set(0, true) + t.same(bits.get(0), true, 'first bit is true') + t.same(bits.get(1), false, 'second bit is false') + bits.set(0, false) + t.same(bits.get(0), false, 'first bit is reset') + t.end() +}) + +tape('set large and get', function (t) { + var bits = bitfield() + + t.same(bits.get(9999999999999), false, 'large bit is false') + bits.set(9999999999999, true) + t.same(bits.get(9999999999999), true, 'large bit is true') + t.same(bits.get(9999999999999 + 1), false, 'large bit + 1 is false') + bits.set(9999999999999, false) + t.same(bits.get(9999999999999), false, 'large bit is reset') + t.end() +}) + +tape('get and set buffer', function (t) { + var bits = bitfield({trackUpdates: true}) + + t.same(bits.pages.get(0, true), undefined) + t.same(bits.pages.get(Math.floor(9999999999999 / 8 / 1024), true), undefined) + bits.set(9999999999999, true) + + var bits2 = bitfield() + var upd = bits.pages.lastUpdate() + bits2.pages.set(Math.floor(upd.offset / 1024), upd.buffer) + t.same(bits2.get(9999999999999), true, 'bit is set') + t.end() +}) + +tape('toBuffer', function (t) { + var bits = bitfield() + + t.same(bits.toBuffer(), alloc(0)) + + bits.set(0, true) + + t.same(bits.toBuffer(), bits.pages.get(0).buffer) + + bits.set(9000, true) + + t.same(bits.toBuffer(), Buffer.concat([bits.pages.get(0).buffer, bits.pages.get(1).buffer])) + t.end() +}) + +tape('pass in buffer', function (t) { + var bits = bitfield() + + bits.set(0, true) + bits.set(9000, true) + + var clone = bitfield(bits.toBuffer()) + + t.same(clone.get(0), true) + t.same(clone.get(9000), true) + t.end() +}) + +tape('set small buffer', function (t) { + var buf = alloc(1) + buf[0] = 255 + var bits = bitfield(buf) + + t.same(bits.get(0), true) + t.same(bits.pages.get(0).buffer.length, bits.pageSize) + t.end() +}) diff --git a/ts-ticket-office-service/node_modules/sqlstring/HISTORY.md b/ts-ticket-office-service/node_modules/sqlstring/HISTORY.md new file mode 100644 index 000000000..e2c7e51fd --- /dev/null +++ b/ts-ticket-office-service/node_modules/sqlstring/HISTORY.md @@ -0,0 +1,43 @@ +2.3.1 / 2018-02-24 +================== + + * Fix incorrectly replacing non-placeholders in SQL + +2.3.0 / 2017-10-01 +================== + + * Add `.toSqlString()` escape overriding + * Add `raw` method to wrap raw strings for escape overriding + * Small performance improvement on `escapeId` + +2.2.0 / 2016-11-01 +================== + + * Escape invalid `Date` objects as `NULL` + +2.1.0 / 2016-09-26 +================== + + * Accept numbers and other value types in `escapeId` + * Run `buffer.toString()` through escaping + +2.0.1 / 2016-06-06 +================== + + * Fix npm package to include missing `lib/` directory + +2.0.0 / 2016-06-06 +================== + + * Bring repository up-to-date with `mysql` module changes + * Support Node.js 0.6.x + +1.0.0 / 2014-11-09 +================== + + * Support Node.js 0.8.x + +0.0.1 / 2014-02-25 +================== + + * Initial release diff --git a/ts-ticket-office-service/node_modules/sqlstring/LICENSE b/ts-ticket-office-service/node_modules/sqlstring/LICENSE new file mode 100644 index 000000000..c7ff12a2f --- /dev/null +++ b/ts-ticket-office-service/node_modules/sqlstring/LICENSE @@ -0,0 +1,19 @@ +Copyright (c) 2012 Felix Geisendörfer (felix@debuggable.com) and contributors + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated documentation files (the "Software"), to deal + in the Software without restriction, including without limitation the rights + to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + copies of the Software, and to permit persons to whom the Software is + furnished to do so, subject to the following conditions: + + The above copyright notice and this permission notice shall be included in + all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + THE SOFTWARE. diff --git a/ts-ticket-office-service/node_modules/sqlstring/README.md b/ts-ticket-office-service/node_modules/sqlstring/README.md new file mode 100644 index 000000000..fafe6f4b5 --- /dev/null +++ b/ts-ticket-office-service/node_modules/sqlstring/README.md @@ -0,0 +1,206 @@ +# sqlstring + +[![NPM Version][npm-version-image]][npm-url] +[![NPM Downloads][npm-downloads-image]][npm-url] +[![Node.js Version][node-image]][node-url] +[![Build Status][travis-image]][travis-url] +[![Coverage Status][coveralls-image]][coveralls-url] + +Simple SQL escape and format for MySQL + +## Install + +```sh +$ npm install sqlstring +``` + +## Usage + + + +```js +var SqlString = require('sqlstring'); +``` + +### Escaping query values + +**Caution** These methods of escaping values only works when the +[NO_BACKSLASH_ESCAPES](https://dev.mysql.com/doc/refman/5.7/en/sql-mode.html#sqlmode_no_backslash_escapes) +SQL mode is disabled (which is the default state for MySQL servers). + +In order to avoid SQL Injection attacks, you should always escape any user +provided data before using it inside a SQL query. You can do so using the +`SqlString.escape()` method: + +```js +var userId = 'some user provided value'; +var sql = 'SELECT * FROM users WHERE id = ' + SqlString.escape(userId); +console.log(sql); // SELECT * FROM users WHERE id = 'some user provided value' +``` + +Alternatively, you can use `?` characters as placeholders for values you would +like to have escaped like this: + +```js +var userId = 1; +var sql = SqlString.format('SELECT * FROM users WHERE id = ?', [userId]); +console.log(sql); // SELECT * FROM users WHERE id = 1 +``` + +Multiple placeholders are mapped to values in the same order as passed. For example, +in the following query `foo` equals `a`, `bar` equals `b`, `baz` equals `c`, and +`id` will be `userId`: + +```js +var userId = 1; +var sql = SqlString.format('UPDATE users SET foo = ?, bar = ?, baz = ? WHERE id = ?', + ['a', 'b', 'c', userId]); +console.log(sql); // UPDATE users SET foo = 'a', bar = 'b', baz = 'c' WHERE id = 1 +``` + +This looks similar to prepared statements in MySQL, however it really just uses +the same `SqlString.escape()` method internally. + +**Caution** This also differs from prepared statements in that all `?` are +replaced, even those contained in comments and strings. + +Different value types are escaped differently, here is how: + +* Numbers are left untouched +* Booleans are converted to `true` / `false` +* Date objects are converted to `'YYYY-mm-dd HH:ii:ss'` strings +* Buffers are converted to hex strings, e.g. `X'0fa5'` +* Strings are safely escaped +* Arrays are turned into list, e.g. `['a', 'b']` turns into `'a', 'b'` +* Nested arrays are turned into grouped lists (for bulk inserts), e.g. `[['a', + 'b'], ['c', 'd']]` turns into `('a', 'b'), ('c', 'd')` +* Objects that have a `toSqlString` method will have `.toSqlString()` called + and the returned value is used as the raw SQL. +* Objects are turned into `key = 'val'` pairs for each enumerable property on + the object. If the property's value is a function, it is skipped; if the + property's value is an object, toString() is called on it and the returned + value is used. +* `undefined` / `null` are converted to `NULL` +* `NaN` / `Infinity` are left as-is. MySQL does not support these, and trying + to insert them as values will trigger MySQL errors until they implement + support. + +You may have noticed that this escaping allows you to do neat things like this: + +```js +var post = {id: 1, title: 'Hello MySQL'}; +var sql = SqlString.format('INSERT INTO posts SET ?', post); +console.log(sql); // INSERT INTO posts SET `id` = 1, `title` = 'Hello MySQL' +``` + +And the `toSqlString` method allows you to form complex queries with functions: + +```js +var CURRENT_TIMESTAMP = { toSqlString: function() { return 'CURRENT_TIMESTAMP()'; } }; +var sql = SqlString.format('UPDATE posts SET modified = ? WHERE id = ?', [CURRENT_TIMESTAMP, 42]); +console.log(sql); // UPDATE posts SET modified = CURRENT_TIMESTAMP() WHERE id = 42 +``` + +To generate objects with a `toSqlString` method, the `SqlString.raw()` method can +be used. This creates an object that will be left un-touched when using in a `?` +placeholder, useful for using functions as dynamic values: + +**Caution** The string provided to `SqlString.raw()` will skip all escaping +functions when used, so be careful when passing in unvalidated input. + +```js +var CURRENT_TIMESTAMP = SqlString.raw('CURRENT_TIMESTAMP()'); +var sql = SqlString.format('UPDATE posts SET modified = ? WHERE id = ?', [CURRENT_TIMESTAMP, 42]); +console.log(sql); // UPDATE posts SET modified = CURRENT_TIMESTAMP() WHERE id = 42 +``` + +If you feel the need to escape queries by yourself, you can also use the escaping +function directly: + +```js +var sql = 'SELECT * FROM posts WHERE title=' + SqlString.escape('Hello MySQL'); +console.log(sql); // SELECT * FROM posts WHERE title='Hello MySQL' +``` + +### Escaping query identifiers + +If you can't trust an SQL identifier (database / table / column name) because it is +provided by a user, you should escape it with `SqlString.escapeId(identifier)` like this: + +```js +var sorter = 'date'; +var sql = 'SELECT * FROM posts ORDER BY ' + SqlString.escapeId(sorter); +console.log(sql); // SELECT * FROM posts ORDER BY `date` +``` + +It also supports adding qualified identifiers. It will escape both parts. + +```js +var sorter = 'date'; +var sql = 'SELECT * FROM posts ORDER BY ' + SqlString.escapeId('posts.' + sorter); +console.log(sql); // SELECT * FROM posts ORDER BY `posts`.`date` +``` + +If you do not want to treat `.` as qualified identifiers, you can set the second +argument to `true` in order to keep the string as a literal identifier: + +```js +var sorter = 'date.2'; +var sql = 'SELECT * FROM posts ORDER BY ' + SqlString.escapeId(sorter, true); +console.log(sql); // SELECT * FROM posts ORDER BY `date.2` +``` + +Alternatively, you can use `??` characters as placeholders for identifiers you would +like to have escaped like this: + +```js +var userId = 1; +var columns = ['username', 'email']; +var sql = SqlString.format('SELECT ?? FROM ?? WHERE id = ?', [columns, 'users', userId]); +console.log(sql); // SELECT `username`, `email` FROM `users` WHERE id = 1 +``` +**Please note that this last character sequence is experimental and syntax might change** + +When you pass an Object to `.escape()` or `.format()`, `.escapeId()` is used to avoid SQL injection in object keys. + +### Formatting queries + +You can use `SqlString.format` to prepare a query with multiple insertion points, +utilizing the proper escaping for ids and values. A simple example of this follows: + +```js +var userId = 1; +var inserts = ['users', 'id', userId]; +var sql = SqlString.format('SELECT * FROM ?? WHERE ?? = ?', inserts); +console.log(sql); // SELECT * FROM `users` WHERE `id` = 1 +``` + +Following this you then have a valid, escaped query that you can then send to the database safely. +This is useful if you are looking to prepare the query before actually sending it to the database. +You also have the option (but are not required) to pass in `stringifyObject` and `timeZone`, +allowing you provide a custom means of turning objects into strings, as well as a +location-specific/timezone-aware `Date`. + +This can be further combined with the `SqlString.raw()` helper to generate SQL +that includes MySQL functions as dynamic vales: + +```js +var userId = 1; +var data = { email: 'foobar@example.com', modified: SqlString.raw('NOW()') }; +var sql = SqlString.format('UPDATE ?? SET ? WHERE `id` = ?', ['users', data, userId]); +console.log(sql); // UPDATE `users` SET `email` = 'foobar@example.com', `modified` = NOW() WHERE `id` = 1 +``` + +## License + +[MIT](LICENSE) + +[npm-version-image]: https://img.shields.io/npm/v/sqlstring.svg +[npm-downloads-image]: https://img.shields.io/npm/dm/sqlstring.svg +[npm-url]: https://npmjs.org/package/sqlstring +[travis-image]: https://img.shields.io/travis/mysqljs/sqlstring/master.svg +[travis-url]: https://travis-ci.org/mysqljs/sqlstring +[coveralls-image]: https://img.shields.io/coveralls/mysqljs/sqlstring/master.svg +[coveralls-url]: https://coveralls.io/r/mysqljs/sqlstring?branch=master +[node-image]: https://img.shields.io/node/v/sqlstring.svg +[node-url]: https://nodejs.org/en/download diff --git a/ts-ticket-office-service/node_modules/sqlstring/index.js b/ts-ticket-office-service/node_modules/sqlstring/index.js new file mode 100644 index 000000000..4ef5944ef --- /dev/null +++ b/ts-ticket-office-service/node_modules/sqlstring/index.js @@ -0,0 +1 @@ +module.exports = require('./lib/SqlString'); diff --git a/ts-ticket-office-service/node_modules/sqlstring/lib/SqlString.js b/ts-ticket-office-service/node_modules/sqlstring/lib/SqlString.js new file mode 100644 index 000000000..419adec0d --- /dev/null +++ b/ts-ticket-office-service/node_modules/sqlstring/lib/SqlString.js @@ -0,0 +1,237 @@ +var SqlString = exports; + +var ID_GLOBAL_REGEXP = /`/g; +var QUAL_GLOBAL_REGEXP = /\./g; +var CHARS_GLOBAL_REGEXP = /[\0\b\t\n\r\x1a\"\'\\]/g; // eslint-disable-line no-control-regex +var CHARS_ESCAPE_MAP = { + '\0' : '\\0', + '\b' : '\\b', + '\t' : '\\t', + '\n' : '\\n', + '\r' : '\\r', + '\x1a' : '\\Z', + '"' : '\\"', + '\'' : '\\\'', + '\\' : '\\\\' +}; + +SqlString.escapeId = function escapeId(val, forbidQualified) { + if (Array.isArray(val)) { + var sql = ''; + + for (var i = 0; i < val.length; i++) { + sql += (i === 0 ? '' : ', ') + SqlString.escapeId(val[i], forbidQualified); + } + + return sql; + } else if (forbidQualified) { + return '`' + String(val).replace(ID_GLOBAL_REGEXP, '``') + '`'; + } else { + return '`' + String(val).replace(ID_GLOBAL_REGEXP, '``').replace(QUAL_GLOBAL_REGEXP, '`.`') + '`'; + } +}; + +SqlString.escape = function escape(val, stringifyObjects, timeZone) { + if (val === undefined || val === null) { + return 'NULL'; + } + + switch (typeof val) { + case 'boolean': return (val) ? 'true' : 'false'; + case 'number': return val + ''; + case 'object': + if (val instanceof Date) { + return SqlString.dateToString(val, timeZone || 'local'); + } else if (Array.isArray(val)) { + return SqlString.arrayToList(val, timeZone); + } else if (Buffer.isBuffer(val)) { + return SqlString.bufferToString(val); + } else if (typeof val.toSqlString === 'function') { + return String(val.toSqlString()); + } else if (stringifyObjects) { + return escapeString(val.toString()); + } else { + return SqlString.objectToValues(val, timeZone); + } + default: return escapeString(val); + } +}; + +SqlString.arrayToList = function arrayToList(array, timeZone) { + var sql = ''; + + for (var i = 0; i < array.length; i++) { + var val = array[i]; + + if (Array.isArray(val)) { + sql += (i === 0 ? '' : ', ') + '(' + SqlString.arrayToList(val, timeZone) + ')'; + } else { + sql += (i === 0 ? '' : ', ') + SqlString.escape(val, true, timeZone); + } + } + + return sql; +}; + +SqlString.format = function format(sql, values, stringifyObjects, timeZone) { + if (values == null) { + return sql; + } + + if (!(values instanceof Array || Array.isArray(values))) { + values = [values]; + } + + var chunkIndex = 0; + var placeholdersRegex = /\?+/g; + var result = ''; + var valuesIndex = 0; + var match; + + while (valuesIndex < values.length && (match = placeholdersRegex.exec(sql))) { + var len = match[0].length; + + if (len > 2) { + continue; + } + + var value = len === 2 + ? SqlString.escapeId(values[valuesIndex]) + : SqlString.escape(values[valuesIndex], stringifyObjects, timeZone); + + result += sql.slice(chunkIndex, match.index) + value; + chunkIndex = placeholdersRegex.lastIndex; + valuesIndex++; + } + + if (chunkIndex === 0) { + // Nothing was replaced + return sql; + } + + if (chunkIndex < sql.length) { + return result + sql.slice(chunkIndex); + } + + return result; +}; + +SqlString.dateToString = function dateToString(date, timeZone) { + var dt = new Date(date); + + if (isNaN(dt.getTime())) { + return 'NULL'; + } + + var year; + var month; + var day; + var hour; + var minute; + var second; + var millisecond; + + if (timeZone === 'local') { + year = dt.getFullYear(); + month = dt.getMonth() + 1; + day = dt.getDate(); + hour = dt.getHours(); + minute = dt.getMinutes(); + second = dt.getSeconds(); + millisecond = dt.getMilliseconds(); + } else { + var tz = convertTimezone(timeZone); + + if (tz !== false && tz !== 0) { + dt.setTime(dt.getTime() + (tz * 60000)); + } + + year = dt.getUTCFullYear(); + month = dt.getUTCMonth() + 1; + day = dt.getUTCDate(); + hour = dt.getUTCHours(); + minute = dt.getUTCMinutes(); + second = dt.getUTCSeconds(); + millisecond = dt.getUTCMilliseconds(); + } + + // YYYY-MM-DD HH:mm:ss.mmm + var str = zeroPad(year, 4) + '-' + zeroPad(month, 2) + '-' + zeroPad(day, 2) + ' ' + + zeroPad(hour, 2) + ':' + zeroPad(minute, 2) + ':' + zeroPad(second, 2) + '.' + + zeroPad(millisecond, 3); + + return escapeString(str); +}; + +SqlString.bufferToString = function bufferToString(buffer) { + return 'X' + escapeString(buffer.toString('hex')); +}; + +SqlString.objectToValues = function objectToValues(object, timeZone) { + var sql = ''; + + for (var key in object) { + var val = object[key]; + + if (typeof val === 'function') { + continue; + } + + sql += (sql.length === 0 ? '' : ', ') + SqlString.escapeId(key) + ' = ' + SqlString.escape(val, true, timeZone); + } + + return sql; +}; + +SqlString.raw = function raw(sql) { + if (typeof sql !== 'string') { + throw new TypeError('argument sql must be a string'); + } + + return { + toSqlString: function toSqlString() { return sql; } + }; +}; + +function escapeString(val) { + var chunkIndex = CHARS_GLOBAL_REGEXP.lastIndex = 0; + var escapedVal = ''; + var match; + + while ((match = CHARS_GLOBAL_REGEXP.exec(val))) { + escapedVal += val.slice(chunkIndex, match.index) + CHARS_ESCAPE_MAP[match[0]]; + chunkIndex = CHARS_GLOBAL_REGEXP.lastIndex; + } + + if (chunkIndex === 0) { + // Nothing was escaped + return "'" + val + "'"; + } + + if (chunkIndex < val.length) { + return "'" + escapedVal + val.slice(chunkIndex) + "'"; + } + + return "'" + escapedVal + "'"; +} + +function zeroPad(number, length) { + number = number.toString(); + while (number.length < length) { + number = '0' + number; + } + + return number; +} + +function convertTimezone(tz) { + if (tz === 'Z') { + return 0; + } + + var m = tz.match(/([\+\-\s])(\d\d):?(\d\d)?/); + if (m) { + return (m[1] === '-' ? -1 : 1) * (parseInt(m[2], 10) + ((m[3] ? parseInt(m[3], 10) : 0) / 60)) * 60; + } + return false; +} diff --git a/ts-ticket-office-service/node_modules/sqlstring/package.json b/ts-ticket-office-service/node_modules/sqlstring/package.json new file mode 100644 index 000000000..2c951a304 --- /dev/null +++ b/ts-ticket-office-service/node_modules/sqlstring/package.json @@ -0,0 +1,47 @@ +{ + "name": "sqlstring", + "description": "Simple SQL escape and format for MySQL", + "version": "2.3.1", + "contributors": [ + "Adri Van Houdt ", + "Douglas Christopher Wilson ", + "fengmk2 (http://fengmk2.github.com)", + "Kevin Jose Martin ", + "Nathan Woltman ", + "Sergej Sintschilin " + ], + "license": "MIT", + "keywords": [ + "sqlstring", + "sql", + "escape", + "sql escape" + ], + "repository": "mysqljs/sqlstring", + "devDependencies": { + "beautify-benchmark": "0.2.4", + "benchmark": "2.1.4", + "eslint": "4.18.1", + "eslint-plugin-markdown": "1.0.0-beta.6", + "nyc": "10.3.2", + "urun": "0.0.8", + "utest": "0.0.8" + }, + "files": [ + "lib/", + "HISTORY.md", + "LICENSE", + "README.md", + "index.js" + ], + "engines": { + "node": ">= 0.6" + }, + "scripts": { + "bench": "node benchmark/index.js", + "lint": "eslint --plugin markdown --ext js,md .", + "test": "node test/run.js", + "test-ci": "nyc --reporter=text npm test", + "test-cov": "nyc --reporter=html --reporter=text npm test" + } +} diff --git a/ts-ticket-office-service/node_modules/string_decoder/.npmignore b/ts-ticket-office-service/node_modules/string_decoder/.npmignore deleted file mode 100644 index 206320cc1..000000000 --- a/ts-ticket-office-service/node_modules/string_decoder/.npmignore +++ /dev/null @@ -1,2 +0,0 @@ -build -test diff --git a/ts-ticket-office-service/node_modules/string_decoder/README.md b/ts-ticket-office-service/node_modules/string_decoder/README.md deleted file mode 100644 index dc3a2d216..000000000 --- a/ts-ticket-office-service/node_modules/string_decoder/README.md +++ /dev/null @@ -1,28 +0,0 @@ -# string_decoder - -***Node-core v7.0.0 string_decoder for userland*** - - -[![NPM](https://nodei.co/npm/string_decoder.png?downloads=true&downloadRank=true)](https://nodei.co/npm/string_decoder/) -[![NPM](https://nodei.co/npm-dl/string_decoder.png?&months=6&height=3)](https://nodei.co/npm/string_decoder/) - - -```bash -npm install --save string_decoder -``` - -***Node-core string_decoderstring_decoder for userland*** - -This package is a mirror of the string_decoder implementation in Node-core. - -Full documentation may be found on the [Node.js website](https://nodejs.org/dist/v7.8.0/docs/api/). - -As of version 1.0.0 **string_decoder** uses semantic versioning. - -## Previous versions - -Previous version numbers match the versions found in Node core, e.g. 0.10.24 matches Node 0.10.24, likewise 0.11.10 matches Node 0.11.10. - -## Update - -The *build/* directory contains a build script that will scrape the source from the [nodejs/node](https://github.com/nodejs/node) repo given a specific Node version. diff --git a/ts-ticket-office-service/node_modules/string_decoder/package.json b/ts-ticket-office-service/node_modules/string_decoder/package.json deleted file mode 100644 index ed1bb4332..000000000 --- a/ts-ticket-office-service/node_modules/string_decoder/package.json +++ /dev/null @@ -1,108 +0,0 @@ -{ - "_args": [ - [ - { - "raw": "string_decoder@~1.0.0", - "scope": null, - "escapedName": "string_decoder", - "name": "string_decoder", - "rawSpec": "~1.0.0", - "spec": ">=1.0.0 <1.1.0", - "type": "range" - }, - "F:\\gitwork\\workspace_microservices\\ts-ticket-office-service\\node_modules\\readable-stream" - ] - ], - "_from": "string_decoder@>=1.0.0 <1.1.0", - "_id": "string_decoder@1.0.3", - "_inCache": true, - "_location": "/string_decoder", - "_nodeVersion": "8.1.1", - "_npmOperationalInternal": { - "host": "s3://npm-registry-packages", - "tmp": "tmp/string_decoder-1.0.3.tgz_1498156574101_0.8198789858724922" - }, - "_npmUser": { - "name": "cwmma", - "email": "calvin.metcalf@gmail.com" - }, - "_npmVersion": "5.0.3", - "_phantomChildren": {}, - "_requested": { - "raw": "string_decoder@~1.0.0", - "scope": null, - "escapedName": "string_decoder", - "name": "string_decoder", - "rawSpec": "~1.0.0", - "spec": ">=1.0.0 <1.1.0", - "type": "range" - }, - "_requiredBy": [ - "/readable-stream" - ], - "_resolved": "https://registry.npmjs.org/string_decoder/-/string_decoder-1.0.3.tgz", - "_shasum": "0fc67d7c141825de94282dd536bec6b9bce860ab", - "_shrinkwrap": null, - "_spec": "string_decoder@~1.0.0", - "_where": "F:\\gitwork\\workspace_microservices\\ts-ticket-office-service\\node_modules\\readable-stream", - "bugs": { - "url": "https://github.com/rvagg/string_decoder/issues" - }, - "dependencies": { - "safe-buffer": "~5.1.0" - }, - "description": "The string_decoder module from Node core", - "devDependencies": { - "babel-polyfill": "^6.23.0", - "tap": "~0.4.8" - }, - "directories": {}, - "dist": { - "integrity": "sha512-4AH6Z5fzNNBcH+6XDMfA/BTt87skxqJlO0lAh3Dker5zThcAxG6mKz+iGu308UKoPPQ8Dcqx/4JhujzltRa+hQ==", - "shasum": "0fc67d7c141825de94282dd536bec6b9bce860ab", - "tarball": "https://registry.npmjs.org/string_decoder/-/string_decoder-1.0.3.tgz" - }, - "gitHead": "e97f24dd3d047b72b9836518e2a0788e2a6a2fdb", - "homepage": "https://github.com/rvagg/string_decoder", - "keywords": [ - "string", - "decoder", - "browser", - "browserify" - ], - "license": "MIT", - "main": "lib/string_decoder.js", - "maintainers": [ - { - "name": "cwmma", - "email": "calvin.metcalf@gmail.com" - }, - { - "name": "matteo.collina", - "email": "hello@matteocollina.com" - }, - { - "name": "nodejs-foundation", - "email": "build@iojs.org" - }, - { - "name": "rvagg", - "email": "rod@vagg.org" - }, - { - "name": "substack", - "email": "substack@gmail.com" - } - ], - "name": "string_decoder", - "optionalDependencies": {}, - "readme": "ERROR: No README data found!", - "repository": { - "type": "git", - "url": "git://github.com/rvagg/string_decoder.git" - }, - "scripts": { - "test": "tap test/parallel/*.js && node test/verify-dependencies" - }, - "version": "1.0.3" -} diff --git a/ts-ticket-office-service/node_modules/buffer-shims/license.md b/ts-ticket-office-service/node_modules/tr46/LICENSE.md similarity index 87% rename from ts-ticket-office-service/node_modules/buffer-shims/license.md rename to ts-ticket-office-service/node_modules/tr46/LICENSE.md index 01cfaefe2..62c0de28a 100644 --- a/ts-ticket-office-service/node_modules/buffer-shims/license.md +++ b/ts-ticket-office-service/node_modules/tr46/LICENSE.md @@ -1,4 +1,6 @@ -# Copyright (c) 2016 Calvin Metcalf +The MIT License (MIT) + +Copyright (c) Sebastian Mayr Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal @@ -10,10 +12,10 @@ furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. -**THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE -SOFTWARE.** +SOFTWARE. diff --git a/ts-ticket-office-service/node_modules/tr46/README.md b/ts-ticket-office-service/node_modules/tr46/README.md new file mode 100644 index 000000000..1df7915b7 --- /dev/null +++ b/ts-ticket-office-service/node_modules/tr46/README.md @@ -0,0 +1,78 @@ +# tr46 + +An JavaScript implementation of [Unicode Technical Standard #46: Unicode IDNA Compatibility Processing](https://unicode.org/reports/tr46/). + +## Installation + +[Node.js](http://nodejs.org) ≥ 12 is required. To install, type this at the command line: + +```shell +npm install tr46 +# or +yarn add tr46 +``` + +## API + +### `toASCII(domainName[, options])` + +Converts a string of Unicode symbols to a case-folded Punycode string of ASCII symbols. + +Available options: + +* [`checkBidi`](#checkBidi) +* [`checkHyphens`](#checkHyphens) +* [`checkJoiners`](#checkJoiners) +* [`processingOption`](#processingOption) +* [`useSTD3ASCIIRules`](#useSTD3ASCIIRules) +* [`verifyDNSLength`](#verifyDNSLength) + +### `toUnicode(domainName[, options])` + +Converts a case-folded Punycode string of ASCII symbols to a string of Unicode symbols. + +Available options: + +* [`checkBidi`](#checkBidi) +* [`checkHyphens`](#checkHyphens) +* [`checkJoiners`](#checkJoiners) +* [`processingOption`](#processingOption) +* [`useSTD3ASCIIRules`](#useSTD3ASCIIRules) + +## Options + +### `checkBidi` + +Type: `boolean` +Default value: `false` +When set to `true`, any bi-directional text within the input will be checked for validation. + +### `checkHyphens` + +Type: `boolean` +Default value: `false` +When set to `true`, the positions of any hyphen characters within the input will be checked for validation. + +### `checkJoiners` + +Type: `boolean` +Default value: `false` +When set to `true`, any word joiner characters within the input will be checked for validation. + +### `processingOption` + +Type: `string` +Default value: `"nontransitional"` +When set to `"transitional"`, symbols within the input will be validated according to the older IDNA2003 protocol. When set to `"nontransitional"`, the current IDNA2008 protocol will be used. + +### `useSTD3ASCIIRules` + +Type: `boolean` +Default value: `false` +When set to `true`, input will be validated according to [STD3 Rules](http://unicode.org/reports/tr46/#STD3_Rules). + +### `verifyDNSLength` + +Type: `boolean` +Default value: `false` +When set to `true`, the length of each DNS label within the input will be checked for validation. diff --git a/ts-ticket-office-service/node_modules/tr46/index.js b/ts-ticket-office-service/node_modules/tr46/index.js new file mode 100644 index 000000000..7ce053272 --- /dev/null +++ b/ts-ticket-office-service/node_modules/tr46/index.js @@ -0,0 +1,298 @@ +"use strict"; + +const punycode = require("punycode"); +const regexes = require("./lib/regexes.js"); +const mappingTable = require("./lib/mappingTable.json"); +const { STATUS_MAPPING } = require("./lib/statusMapping.js"); + +function containsNonASCII(str) { + return /[^\x00-\x7F]/u.test(str); +} + +function findStatus(val, { useSTD3ASCIIRules }) { + let start = 0; + let end = mappingTable.length - 1; + + while (start <= end) { + const mid = Math.floor((start + end) / 2); + + const target = mappingTable[mid]; + const min = Array.isArray(target[0]) ? target[0][0] : target[0]; + const max = Array.isArray(target[0]) ? target[0][1] : target[0]; + + if (min <= val && max >= val) { + if (useSTD3ASCIIRules && + (target[1] === STATUS_MAPPING.disallowed_STD3_valid || target[1] === STATUS_MAPPING.disallowed_STD3_mapped)) { + return [STATUS_MAPPING.disallowed, ...target.slice(2)]; + } else if (target[1] === STATUS_MAPPING.disallowed_STD3_valid) { + return [STATUS_MAPPING.valid, ...target.slice(2)]; + } else if (target[1] === STATUS_MAPPING.disallowed_STD3_mapped) { + return [STATUS_MAPPING.mapped, ...target.slice(2)]; + } + + return target.slice(1); + } else if (min > val) { + end = mid - 1; + } else { + start = mid + 1; + } + } + + return null; +} + +function mapChars(domainName, { useSTD3ASCIIRules, processingOption }) { + let hasError = false; + let processed = ""; + + for (const ch of domainName) { + const [status, mapping] = findStatus(ch.codePointAt(0), { useSTD3ASCIIRules }); + + switch (status) { + case STATUS_MAPPING.disallowed: + hasError = true; + processed += ch; + break; + case STATUS_MAPPING.ignored: + break; + case STATUS_MAPPING.mapped: + processed += mapping; + break; + case STATUS_MAPPING.deviation: + if (processingOption === "transitional") { + processed += mapping; + } else { + processed += ch; + } + break; + case STATUS_MAPPING.valid: + processed += ch; + break; + } + } + + return { + string: processed, + error: hasError + }; +} + +function validateLabel(label, { checkHyphens, checkBidi, checkJoiners, processingOption, useSTD3ASCIIRules }) { + if (label.normalize("NFC") !== label) { + return false; + } + + const codePoints = Array.from(label); + + if (checkHyphens) { + if ((codePoints[2] === "-" && codePoints[3] === "-") || + (label.startsWith("-") || label.endsWith("-"))) { + return false; + } + } + + if (label.includes(".") || + (codePoints.length > 0 && regexes.combiningMarks.test(codePoints[0]))) { + return false; + } + + for (const ch of codePoints) { + const [status] = findStatus(ch.codePointAt(0), { useSTD3ASCIIRules }); + if ((processingOption === "transitional" && status !== STATUS_MAPPING.valid) || + (processingOption === "nontransitional" && + status !== STATUS_MAPPING.valid && status !== STATUS_MAPPING.deviation)) { + return false; + } + } + + // https://tools.ietf.org/html/rfc5892#appendix-A + if (checkJoiners) { + let last = 0; + for (const [i, ch] of codePoints.entries()) { + if (ch === "\u200C" || ch === "\u200D") { + if (i > 0) { + if (regexes.combiningClassVirama.test(codePoints[i - 1])) { + continue; + } + if (ch === "\u200C") { + // TODO: make this more efficient + const next = codePoints.indexOf("\u200C", i + 1); + const test = next < 0 ? codePoints.slice(last) : codePoints.slice(last, next); + if (regexes.validZWNJ.test(test.join(""))) { + last = i + 1; + continue; + } + } + } + return false; + } + } + } + + // https://tools.ietf.org/html/rfc5893#section-2 + if (checkBidi) { + let rtl; + + // 1 + if (regexes.bidiS1LTR.test(codePoints[0])) { + rtl = false; + } else if (regexes.bidiS1RTL.test(codePoints[0])) { + rtl = true; + } else { + return false; + } + + if (rtl) { + // 2-4 + if (!regexes.bidiS2.test(label) || + !regexes.bidiS3.test(label) || + (regexes.bidiS4EN.test(label) && regexes.bidiS4AN.test(label))) { + return false; + } + } else if (!regexes.bidiS5.test(label) || + !regexes.bidiS6.test(label)) { // 5-6 + return false; + } + } + + return true; +} + +function isBidiDomain(labels) { + const domain = labels.map(label => { + if (label.startsWith("xn--")) { + try { + return punycode.decode(label.substring(4)); + } catch (err) { + return ""; + } + } + return label; + }).join("."); + return regexes.bidiDomain.test(domain); +} + +function processing(domainName, options) { + const { processingOption } = options; + + // 1. Map. + let { string, error } = mapChars(domainName, options); + + // 2. Normalize. + string = string.normalize("NFC"); + + // 3. Break. + const labels = string.split("."); + const isBidi = isBidiDomain(labels); + + // 4. Convert/Validate. + for (const [i, origLabel] of labels.entries()) { + let label = origLabel; + let curProcessing = processingOption; + if (label.startsWith("xn--")) { + try { + label = punycode.decode(label.substring(4)); + labels[i] = label; + } catch (err) { + error = true; + continue; + } + curProcessing = "nontransitional"; + } + + // No need to validate if we already know there is an error. + if (error) { + continue; + } + const validation = validateLabel(label, { + ...options, + processingOption: curProcessing, + checkBidi: options.checkBidi && isBidi + }); + if (!validation) { + error = true; + } + } + + return { + string: labels.join("."), + error + }; +} + +function toASCII(domainName, { + checkHyphens = false, + checkBidi = false, + checkJoiners = false, + useSTD3ASCIIRules = false, + processingOption = "nontransitional", + verifyDNSLength = false +} = {}) { + if (processingOption !== "transitional" && processingOption !== "nontransitional") { + throw new RangeError("processingOption must be either transitional or nontransitional"); + } + + const result = processing(domainName, { + processingOption, + checkHyphens, + checkBidi, + checkJoiners, + useSTD3ASCIIRules + }); + let labels = result.string.split("."); + labels = labels.map(l => { + if (containsNonASCII(l)) { + try { + return `xn--${punycode.encode(l)}`; + } catch (e) { + result.error = true; + } + } + return l; + }); + + if (verifyDNSLength) { + const total = labels.join(".").length; + if (total > 253 || total === 0) { + result.error = true; + } + + for (let i = 0; i < labels.length; ++i) { + if (labels[i].length > 63 || labels[i].length === 0) { + result.error = true; + break; + } + } + } + + if (result.error) { + return null; + } + return labels.join("."); +} + +function toUnicode(domainName, { + checkHyphens = false, + checkBidi = false, + checkJoiners = false, + useSTD3ASCIIRules = false, + processingOption = "nontransitional" +} = {}) { + const result = processing(domainName, { + processingOption, + checkHyphens, + checkBidi, + checkJoiners, + useSTD3ASCIIRules + }); + + return { + domain: result.string, + error: result.error + }; +} + +module.exports = { + toASCII, + toUnicode +}; diff --git a/ts-ticket-office-service/node_modules/tr46/lib/mappingTable.json b/ts-ticket-office-service/node_modules/tr46/lib/mappingTable.json new file mode 100644 index 000000000..3d71a5eff --- /dev/null +++ b/ts-ticket-office-service/node_modules/tr46/lib/mappingTable.json @@ -0,0 +1 @@ +[[[0,44],4],[[45,46],2],[47,4],[[48,57],2],[[58,64],4],[65,1,"a"],[66,1,"b"],[67,1,"c"],[68,1,"d"],[69,1,"e"],[70,1,"f"],[71,1,"g"],[72,1,"h"],[73,1,"i"],[74,1,"j"],[75,1,"k"],[76,1,"l"],[77,1,"m"],[78,1,"n"],[79,1,"o"],[80,1,"p"],[81,1,"q"],[82,1,"r"],[83,1,"s"],[84,1,"t"],[85,1,"u"],[86,1,"v"],[87,1,"w"],[88,1,"x"],[89,1,"y"],[90,1,"z"],[[91,96],4],[[97,122],2],[[123,127],4],[[128,159],3],[160,5," "],[[161,167],2],[168,5," ̈"],[169,2],[170,1,"a"],[[171,172],2],[173,7],[174,2],[175,5," ̄"],[[176,177],2],[178,1,"2"],[179,1,"3"],[180,5," ́"],[181,1,"μ"],[182,2],[183,2],[184,5," ̧"],[185,1,"1"],[186,1,"o"],[187,2],[188,1,"1⁄4"],[189,1,"1⁄2"],[190,1,"3⁄4"],[191,2],[192,1,"à"],[193,1,"á"],[194,1,"â"],[195,1,"ã"],[196,1,"ä"],[197,1,"å"],[198,1,"æ"],[199,1,"ç"],[200,1,"è"],[201,1,"é"],[202,1,"ê"],[203,1,"ë"],[204,1,"ì"],[205,1,"í"],[206,1,"î"],[207,1,"ï"],[208,1,"ð"],[209,1,"ñ"],[210,1,"ò"],[211,1,"ó"],[212,1,"ô"],[213,1,"õ"],[214,1,"ö"],[215,2],[216,1,"ø"],[217,1,"ù"],[218,1,"ú"],[219,1,"û"],[220,1,"ü"],[221,1,"ý"],[222,1,"þ"],[223,6,"ss"],[[224,246],2],[247,2],[[248,255],2],[256,1,"ā"],[257,2],[258,1,"ă"],[259,2],[260,1,"ą"],[261,2],[262,1,"ć"],[263,2],[264,1,"ĉ"],[265,2],[266,1,"ċ"],[267,2],[268,1,"č"],[269,2],[270,1,"ď"],[271,2],[272,1,"đ"],[273,2],[274,1,"ē"],[275,2],[276,1,"ĕ"],[277,2],[278,1,"ė"],[279,2],[280,1,"ę"],[281,2],[282,1,"ě"],[283,2],[284,1,"ĝ"],[285,2],[286,1,"ğ"],[287,2],[288,1,"ġ"],[289,2],[290,1,"ģ"],[291,2],[292,1,"ĥ"],[293,2],[294,1,"ħ"],[295,2],[296,1,"ĩ"],[297,2],[298,1,"ī"],[299,2],[300,1,"ĭ"],[301,2],[302,1,"į"],[303,2],[304,1,"i̇"],[305,2],[[306,307],1,"ij"],[308,1,"ĵ"],[309,2],[310,1,"ķ"],[[311,312],2],[313,1,"ĺ"],[314,2],[315,1,"ļ"],[316,2],[317,1,"ľ"],[318,2],[[319,320],1,"l·"],[321,1,"ł"],[322,2],[323,1,"ń"],[324,2],[325,1,"ņ"],[326,2],[327,1,"ň"],[328,2],[329,1,"ʼn"],[330,1,"ŋ"],[331,2],[332,1,"ō"],[333,2],[334,1,"ŏ"],[335,2],[336,1,"ő"],[337,2],[338,1,"œ"],[339,2],[340,1,"ŕ"],[341,2],[342,1,"ŗ"],[343,2],[344,1,"ř"],[345,2],[346,1,"ś"],[347,2],[348,1,"ŝ"],[349,2],[350,1,"ş"],[351,2],[352,1,"š"],[353,2],[354,1,"ţ"],[355,2],[356,1,"ť"],[357,2],[358,1,"ŧ"],[359,2],[360,1,"ũ"],[361,2],[362,1,"ū"],[363,2],[364,1,"ŭ"],[365,2],[366,1,"ů"],[367,2],[368,1,"ű"],[369,2],[370,1,"ų"],[371,2],[372,1,"ŵ"],[373,2],[374,1,"ŷ"],[375,2],[376,1,"ÿ"],[377,1,"ź"],[378,2],[379,1,"ż"],[380,2],[381,1,"ž"],[382,2],[383,1,"s"],[384,2],[385,1,"ɓ"],[386,1,"ƃ"],[387,2],[388,1,"ƅ"],[389,2],[390,1,"ɔ"],[391,1,"ƈ"],[392,2],[393,1,"ɖ"],[394,1,"ɗ"],[395,1,"ƌ"],[[396,397],2],[398,1,"ǝ"],[399,1,"ə"],[400,1,"ɛ"],[401,1,"ƒ"],[402,2],[403,1,"ɠ"],[404,1,"ɣ"],[405,2],[406,1,"ɩ"],[407,1,"ɨ"],[408,1,"ƙ"],[[409,411],2],[412,1,"ɯ"],[413,1,"ɲ"],[414,2],[415,1,"ɵ"],[416,1,"ơ"],[417,2],[418,1,"ƣ"],[419,2],[420,1,"ƥ"],[421,2],[422,1,"ʀ"],[423,1,"ƨ"],[424,2],[425,1,"ʃ"],[[426,427],2],[428,1,"ƭ"],[429,2],[430,1,"ʈ"],[431,1,"ư"],[432,2],[433,1,"ʊ"],[434,1,"ʋ"],[435,1,"ƴ"],[436,2],[437,1,"ƶ"],[438,2],[439,1,"ʒ"],[440,1,"ƹ"],[[441,443],2],[444,1,"ƽ"],[[445,451],2],[[452,454],1,"dž"],[[455,457],1,"lj"],[[458,460],1,"nj"],[461,1,"ǎ"],[462,2],[463,1,"ǐ"],[464,2],[465,1,"ǒ"],[466,2],[467,1,"ǔ"],[468,2],[469,1,"ǖ"],[470,2],[471,1,"ǘ"],[472,2],[473,1,"ǚ"],[474,2],[475,1,"ǜ"],[[476,477],2],[478,1,"ǟ"],[479,2],[480,1,"ǡ"],[481,2],[482,1,"ǣ"],[483,2],[484,1,"ǥ"],[485,2],[486,1,"ǧ"],[487,2],[488,1,"ǩ"],[489,2],[490,1,"ǫ"],[491,2],[492,1,"ǭ"],[493,2],[494,1,"ǯ"],[[495,496],2],[[497,499],1,"dz"],[500,1,"ǵ"],[501,2],[502,1,"ƕ"],[503,1,"ƿ"],[504,1,"ǹ"],[505,2],[506,1,"ǻ"],[507,2],[508,1,"ǽ"],[509,2],[510,1,"ǿ"],[511,2],[512,1,"ȁ"],[513,2],[514,1,"ȃ"],[515,2],[516,1,"ȅ"],[517,2],[518,1,"ȇ"],[519,2],[520,1,"ȉ"],[521,2],[522,1,"ȋ"],[523,2],[524,1,"ȍ"],[525,2],[526,1,"ȏ"],[527,2],[528,1,"ȑ"],[529,2],[530,1,"ȓ"],[531,2],[532,1,"ȕ"],[533,2],[534,1,"ȗ"],[535,2],[536,1,"ș"],[537,2],[538,1,"ț"],[539,2],[540,1,"ȝ"],[541,2],[542,1,"ȟ"],[543,2],[544,1,"ƞ"],[545,2],[546,1,"ȣ"],[547,2],[548,1,"ȥ"],[549,2],[550,1,"ȧ"],[551,2],[552,1,"ȩ"],[553,2],[554,1,"ȫ"],[555,2],[556,1,"ȭ"],[557,2],[558,1,"ȯ"],[559,2],[560,1,"ȱ"],[561,2],[562,1,"ȳ"],[563,2],[[564,566],2],[[567,569],2],[570,1,"ⱥ"],[571,1,"ȼ"],[572,2],[573,1,"ƚ"],[574,1,"ⱦ"],[[575,576],2],[577,1,"ɂ"],[578,2],[579,1,"ƀ"],[580,1,"ʉ"],[581,1,"ʌ"],[582,1,"ɇ"],[583,2],[584,1,"ɉ"],[585,2],[586,1,"ɋ"],[587,2],[588,1,"ɍ"],[589,2],[590,1,"ɏ"],[591,2],[[592,680],2],[[681,685],2],[[686,687],2],[688,1,"h"],[689,1,"ɦ"],[690,1,"j"],[691,1,"r"],[692,1,"ɹ"],[693,1,"ɻ"],[694,1,"ʁ"],[695,1,"w"],[696,1,"y"],[[697,705],2],[[706,709],2],[[710,721],2],[[722,727],2],[728,5," ̆"],[729,5," ̇"],[730,5," ̊"],[731,5," ̨"],[732,5," ̃"],[733,5," ̋"],[734,2],[735,2],[736,1,"ɣ"],[737,1,"l"],[738,1,"s"],[739,1,"x"],[740,1,"ʕ"],[[741,745],2],[[746,747],2],[748,2],[749,2],[750,2],[[751,767],2],[[768,831],2],[832,1,"̀"],[833,1,"́"],[834,2],[835,1,"̓"],[836,1,"̈́"],[837,1,"ι"],[[838,846],2],[847,7],[[848,855],2],[[856,860],2],[[861,863],2],[[864,865],2],[866,2],[[867,879],2],[880,1,"ͱ"],[881,2],[882,1,"ͳ"],[883,2],[884,1,"ʹ"],[885,2],[886,1,"ͷ"],[887,2],[[888,889],3],[890,5," ι"],[[891,893],2],[894,5,";"],[895,1,"ϳ"],[[896,899],3],[900,5," ́"],[901,5," ̈́"],[902,1,"ά"],[903,1,"·"],[904,1,"έ"],[905,1,"ή"],[906,1,"ί"],[907,3],[908,1,"ό"],[909,3],[910,1,"ύ"],[911,1,"ώ"],[912,2],[913,1,"α"],[914,1,"β"],[915,1,"γ"],[916,1,"δ"],[917,1,"ε"],[918,1,"ζ"],[919,1,"η"],[920,1,"θ"],[921,1,"ι"],[922,1,"κ"],[923,1,"λ"],[924,1,"μ"],[925,1,"ν"],[926,1,"ξ"],[927,1,"ο"],[928,1,"π"],[929,1,"ρ"],[930,3],[931,1,"σ"],[932,1,"τ"],[933,1,"υ"],[934,1,"φ"],[935,1,"χ"],[936,1,"ψ"],[937,1,"ω"],[938,1,"ϊ"],[939,1,"ϋ"],[[940,961],2],[962,6,"σ"],[[963,974],2],[975,1,"ϗ"],[976,1,"β"],[977,1,"θ"],[978,1,"υ"],[979,1,"ύ"],[980,1,"ϋ"],[981,1,"φ"],[982,1,"π"],[983,2],[984,1,"ϙ"],[985,2],[986,1,"ϛ"],[987,2],[988,1,"ϝ"],[989,2],[990,1,"ϟ"],[991,2],[992,1,"ϡ"],[993,2],[994,1,"ϣ"],[995,2],[996,1,"ϥ"],[997,2],[998,1,"ϧ"],[999,2],[1000,1,"ϩ"],[1001,2],[1002,1,"ϫ"],[1003,2],[1004,1,"ϭ"],[1005,2],[1006,1,"ϯ"],[1007,2],[1008,1,"κ"],[1009,1,"ρ"],[1010,1,"σ"],[1011,2],[1012,1,"θ"],[1013,1,"ε"],[1014,2],[1015,1,"ϸ"],[1016,2],[1017,1,"σ"],[1018,1,"ϻ"],[1019,2],[1020,2],[1021,1,"ͻ"],[1022,1,"ͼ"],[1023,1,"ͽ"],[1024,1,"ѐ"],[1025,1,"ё"],[1026,1,"ђ"],[1027,1,"ѓ"],[1028,1,"є"],[1029,1,"ѕ"],[1030,1,"і"],[1031,1,"ї"],[1032,1,"ј"],[1033,1,"љ"],[1034,1,"њ"],[1035,1,"ћ"],[1036,1,"ќ"],[1037,1,"ѝ"],[1038,1,"ў"],[1039,1,"џ"],[1040,1,"а"],[1041,1,"б"],[1042,1,"в"],[1043,1,"г"],[1044,1,"д"],[1045,1,"е"],[1046,1,"ж"],[1047,1,"з"],[1048,1,"и"],[1049,1,"й"],[1050,1,"к"],[1051,1,"л"],[1052,1,"м"],[1053,1,"н"],[1054,1,"о"],[1055,1,"п"],[1056,1,"р"],[1057,1,"с"],[1058,1,"т"],[1059,1,"у"],[1060,1,"ф"],[1061,1,"х"],[1062,1,"ц"],[1063,1,"ч"],[1064,1,"ш"],[1065,1,"щ"],[1066,1,"ъ"],[1067,1,"ы"],[1068,1,"ь"],[1069,1,"э"],[1070,1,"ю"],[1071,1,"я"],[[1072,1103],2],[1104,2],[[1105,1116],2],[1117,2],[[1118,1119],2],[1120,1,"ѡ"],[1121,2],[1122,1,"ѣ"],[1123,2],[1124,1,"ѥ"],[1125,2],[1126,1,"ѧ"],[1127,2],[1128,1,"ѩ"],[1129,2],[1130,1,"ѫ"],[1131,2],[1132,1,"ѭ"],[1133,2],[1134,1,"ѯ"],[1135,2],[1136,1,"ѱ"],[1137,2],[1138,1,"ѳ"],[1139,2],[1140,1,"ѵ"],[1141,2],[1142,1,"ѷ"],[1143,2],[1144,1,"ѹ"],[1145,2],[1146,1,"ѻ"],[1147,2],[1148,1,"ѽ"],[1149,2],[1150,1,"ѿ"],[1151,2],[1152,1,"ҁ"],[1153,2],[1154,2],[[1155,1158],2],[1159,2],[[1160,1161],2],[1162,1,"ҋ"],[1163,2],[1164,1,"ҍ"],[1165,2],[1166,1,"ҏ"],[1167,2],[1168,1,"ґ"],[1169,2],[1170,1,"ғ"],[1171,2],[1172,1,"ҕ"],[1173,2],[1174,1,"җ"],[1175,2],[1176,1,"ҙ"],[1177,2],[1178,1,"қ"],[1179,2],[1180,1,"ҝ"],[1181,2],[1182,1,"ҟ"],[1183,2],[1184,1,"ҡ"],[1185,2],[1186,1,"ң"],[1187,2],[1188,1,"ҥ"],[1189,2],[1190,1,"ҧ"],[1191,2],[1192,1,"ҩ"],[1193,2],[1194,1,"ҫ"],[1195,2],[1196,1,"ҭ"],[1197,2],[1198,1,"ү"],[1199,2],[1200,1,"ұ"],[1201,2],[1202,1,"ҳ"],[1203,2],[1204,1,"ҵ"],[1205,2],[1206,1,"ҷ"],[1207,2],[1208,1,"ҹ"],[1209,2],[1210,1,"һ"],[1211,2],[1212,1,"ҽ"],[1213,2],[1214,1,"ҿ"],[1215,2],[1216,3],[1217,1,"ӂ"],[1218,2],[1219,1,"ӄ"],[1220,2],[1221,1,"ӆ"],[1222,2],[1223,1,"ӈ"],[1224,2],[1225,1,"ӊ"],[1226,2],[1227,1,"ӌ"],[1228,2],[1229,1,"ӎ"],[1230,2],[1231,2],[1232,1,"ӑ"],[1233,2],[1234,1,"ӓ"],[1235,2],[1236,1,"ӕ"],[1237,2],[1238,1,"ӗ"],[1239,2],[1240,1,"ә"],[1241,2],[1242,1,"ӛ"],[1243,2],[1244,1,"ӝ"],[1245,2],[1246,1,"ӟ"],[1247,2],[1248,1,"ӡ"],[1249,2],[1250,1,"ӣ"],[1251,2],[1252,1,"ӥ"],[1253,2],[1254,1,"ӧ"],[1255,2],[1256,1,"ө"],[1257,2],[1258,1,"ӫ"],[1259,2],[1260,1,"ӭ"],[1261,2],[1262,1,"ӯ"],[1263,2],[1264,1,"ӱ"],[1265,2],[1266,1,"ӳ"],[1267,2],[1268,1,"ӵ"],[1269,2],[1270,1,"ӷ"],[1271,2],[1272,1,"ӹ"],[1273,2],[1274,1,"ӻ"],[1275,2],[1276,1,"ӽ"],[1277,2],[1278,1,"ӿ"],[1279,2],[1280,1,"ԁ"],[1281,2],[1282,1,"ԃ"],[1283,2],[1284,1,"ԅ"],[1285,2],[1286,1,"ԇ"],[1287,2],[1288,1,"ԉ"],[1289,2],[1290,1,"ԋ"],[1291,2],[1292,1,"ԍ"],[1293,2],[1294,1,"ԏ"],[1295,2],[1296,1,"ԑ"],[1297,2],[1298,1,"ԓ"],[1299,2],[1300,1,"ԕ"],[1301,2],[1302,1,"ԗ"],[1303,2],[1304,1,"ԙ"],[1305,2],[1306,1,"ԛ"],[1307,2],[1308,1,"ԝ"],[1309,2],[1310,1,"ԟ"],[1311,2],[1312,1,"ԡ"],[1313,2],[1314,1,"ԣ"],[1315,2],[1316,1,"ԥ"],[1317,2],[1318,1,"ԧ"],[1319,2],[1320,1,"ԩ"],[1321,2],[1322,1,"ԫ"],[1323,2],[1324,1,"ԭ"],[1325,2],[1326,1,"ԯ"],[1327,2],[1328,3],[1329,1,"ա"],[1330,1,"բ"],[1331,1,"գ"],[1332,1,"դ"],[1333,1,"ե"],[1334,1,"զ"],[1335,1,"է"],[1336,1,"ը"],[1337,1,"թ"],[1338,1,"ժ"],[1339,1,"ի"],[1340,1,"լ"],[1341,1,"խ"],[1342,1,"ծ"],[1343,1,"կ"],[1344,1,"հ"],[1345,1,"ձ"],[1346,1,"ղ"],[1347,1,"ճ"],[1348,1,"մ"],[1349,1,"յ"],[1350,1,"ն"],[1351,1,"շ"],[1352,1,"ո"],[1353,1,"չ"],[1354,1,"պ"],[1355,1,"ջ"],[1356,1,"ռ"],[1357,1,"ս"],[1358,1,"վ"],[1359,1,"տ"],[1360,1,"ր"],[1361,1,"ց"],[1362,1,"ւ"],[1363,1,"փ"],[1364,1,"ք"],[1365,1,"օ"],[1366,1,"ֆ"],[[1367,1368],3],[1369,2],[[1370,1375],2],[1376,2],[[1377,1414],2],[1415,1,"եւ"],[1416,2],[1417,2],[1418,2],[[1419,1420],3],[[1421,1422],2],[1423,2],[1424,3],[[1425,1441],2],[1442,2],[[1443,1455],2],[[1456,1465],2],[1466,2],[[1467,1469],2],[1470,2],[1471,2],[1472,2],[[1473,1474],2],[1475,2],[1476,2],[1477,2],[1478,2],[1479,2],[[1480,1487],3],[[1488,1514],2],[[1515,1518],3],[1519,2],[[1520,1524],2],[[1525,1535],3],[[1536,1539],3],[1540,3],[1541,3],[[1542,1546],2],[1547,2],[1548,2],[[1549,1551],2],[[1552,1557],2],[[1558,1562],2],[1563,2],[1564,3],[1565,2],[1566,2],[1567,2],[1568,2],[[1569,1594],2],[[1595,1599],2],[1600,2],[[1601,1618],2],[[1619,1621],2],[[1622,1624],2],[[1625,1630],2],[1631,2],[[1632,1641],2],[[1642,1645],2],[[1646,1647],2],[[1648,1652],2],[1653,1,"اٴ"],[1654,1,"وٴ"],[1655,1,"ۇٴ"],[1656,1,"يٴ"],[[1657,1719],2],[[1720,1721],2],[[1722,1726],2],[1727,2],[[1728,1742],2],[1743,2],[[1744,1747],2],[1748,2],[[1749,1756],2],[1757,3],[1758,2],[[1759,1768],2],[1769,2],[[1770,1773],2],[[1774,1775],2],[[1776,1785],2],[[1786,1790],2],[1791,2],[[1792,1805],2],[1806,3],[1807,3],[[1808,1836],2],[[1837,1839],2],[[1840,1866],2],[[1867,1868],3],[[1869,1871],2],[[1872,1901],2],[[1902,1919],2],[[1920,1968],2],[1969,2],[[1970,1983],3],[[1984,2037],2],[[2038,2042],2],[[2043,2044],3],[2045,2],[[2046,2047],2],[[2048,2093],2],[[2094,2095],3],[[2096,2110],2],[2111,3],[[2112,2139],2],[[2140,2141],3],[2142,2],[2143,3],[[2144,2154],2],[[2155,2159],3],[[2160,2183],2],[2184,2],[[2185,2190],2],[2191,3],[[2192,2193],3],[[2194,2199],3],[[2200,2207],2],[2208,2],[2209,2],[[2210,2220],2],[[2221,2226],2],[[2227,2228],2],[2229,2],[[2230,2237],2],[[2238,2247],2],[[2248,2258],2],[2259,2],[[2260,2273],2],[2274,3],[2275,2],[[2276,2302],2],[2303,2],[2304,2],[[2305,2307],2],[2308,2],[[2309,2361],2],[[2362,2363],2],[[2364,2381],2],[2382,2],[2383,2],[[2384,2388],2],[2389,2],[[2390,2391],2],[2392,1,"क़"],[2393,1,"ख़"],[2394,1,"ग़"],[2395,1,"ज़"],[2396,1,"ड़"],[2397,1,"ढ़"],[2398,1,"फ़"],[2399,1,"य़"],[[2400,2403],2],[[2404,2405],2],[[2406,2415],2],[2416,2],[[2417,2418],2],[[2419,2423],2],[2424,2],[[2425,2426],2],[[2427,2428],2],[2429,2],[[2430,2431],2],[2432,2],[[2433,2435],2],[2436,3],[[2437,2444],2],[[2445,2446],3],[[2447,2448],2],[[2449,2450],3],[[2451,2472],2],[2473,3],[[2474,2480],2],[2481,3],[2482,2],[[2483,2485],3],[[2486,2489],2],[[2490,2491],3],[2492,2],[2493,2],[[2494,2500],2],[[2501,2502],3],[[2503,2504],2],[[2505,2506],3],[[2507,2509],2],[2510,2],[[2511,2518],3],[2519,2],[[2520,2523],3],[2524,1,"ড়"],[2525,1,"ঢ়"],[2526,3],[2527,1,"য়"],[[2528,2531],2],[[2532,2533],3],[[2534,2545],2],[[2546,2554],2],[2555,2],[2556,2],[2557,2],[2558,2],[[2559,2560],3],[2561,2],[2562,2],[2563,2],[2564,3],[[2565,2570],2],[[2571,2574],3],[[2575,2576],2],[[2577,2578],3],[[2579,2600],2],[2601,3],[[2602,2608],2],[2609,3],[2610,2],[2611,1,"ਲ਼"],[2612,3],[2613,2],[2614,1,"ਸ਼"],[2615,3],[[2616,2617],2],[[2618,2619],3],[2620,2],[2621,3],[[2622,2626],2],[[2627,2630],3],[[2631,2632],2],[[2633,2634],3],[[2635,2637],2],[[2638,2640],3],[2641,2],[[2642,2648],3],[2649,1,"ਖ਼"],[2650,1,"ਗ਼"],[2651,1,"ਜ਼"],[2652,2],[2653,3],[2654,1,"ਫ਼"],[[2655,2661],3],[[2662,2676],2],[2677,2],[2678,2],[[2679,2688],3],[[2689,2691],2],[2692,3],[[2693,2699],2],[2700,2],[2701,2],[2702,3],[[2703,2705],2],[2706,3],[[2707,2728],2],[2729,3],[[2730,2736],2],[2737,3],[[2738,2739],2],[2740,3],[[2741,2745],2],[[2746,2747],3],[[2748,2757],2],[2758,3],[[2759,2761],2],[2762,3],[[2763,2765],2],[[2766,2767],3],[2768,2],[[2769,2783],3],[2784,2],[[2785,2787],2],[[2788,2789],3],[[2790,2799],2],[2800,2],[2801,2],[[2802,2808],3],[2809,2],[[2810,2815],2],[2816,3],[[2817,2819],2],[2820,3],[[2821,2828],2],[[2829,2830],3],[[2831,2832],2],[[2833,2834],3],[[2835,2856],2],[2857,3],[[2858,2864],2],[2865,3],[[2866,2867],2],[2868,3],[2869,2],[[2870,2873],2],[[2874,2875],3],[[2876,2883],2],[2884,2],[[2885,2886],3],[[2887,2888],2],[[2889,2890],3],[[2891,2893],2],[[2894,2900],3],[2901,2],[[2902,2903],2],[[2904,2907],3],[2908,1,"ଡ଼"],[2909,1,"ଢ଼"],[2910,3],[[2911,2913],2],[[2914,2915],2],[[2916,2917],3],[[2918,2927],2],[2928,2],[2929,2],[[2930,2935],2],[[2936,2945],3],[[2946,2947],2],[2948,3],[[2949,2954],2],[[2955,2957],3],[[2958,2960],2],[2961,3],[[2962,2965],2],[[2966,2968],3],[[2969,2970],2],[2971,3],[2972,2],[2973,3],[[2974,2975],2],[[2976,2978],3],[[2979,2980],2],[[2981,2983],3],[[2984,2986],2],[[2987,2989],3],[[2990,2997],2],[2998,2],[[2999,3001],2],[[3002,3005],3],[[3006,3010],2],[[3011,3013],3],[[3014,3016],2],[3017,3],[[3018,3021],2],[[3022,3023],3],[3024,2],[[3025,3030],3],[3031,2],[[3032,3045],3],[3046,2],[[3047,3055],2],[[3056,3058],2],[[3059,3066],2],[[3067,3071],3],[3072,2],[[3073,3075],2],[3076,2],[[3077,3084],2],[3085,3],[[3086,3088],2],[3089,3],[[3090,3112],2],[3113,3],[[3114,3123],2],[3124,2],[[3125,3129],2],[[3130,3131],3],[3132,2],[3133,2],[[3134,3140],2],[3141,3],[[3142,3144],2],[3145,3],[[3146,3149],2],[[3150,3156],3],[[3157,3158],2],[3159,3],[[3160,3161],2],[3162,2],[[3163,3164],3],[3165,2],[[3166,3167],3],[[3168,3169],2],[[3170,3171],2],[[3172,3173],3],[[3174,3183],2],[[3184,3190],3],[3191,2],[[3192,3199],2],[3200,2],[3201,2],[[3202,3203],2],[3204,2],[[3205,3212],2],[3213,3],[[3214,3216],2],[3217,3],[[3218,3240],2],[3241,3],[[3242,3251],2],[3252,3],[[3253,3257],2],[[3258,3259],3],[[3260,3261],2],[[3262,3268],2],[3269,3],[[3270,3272],2],[3273,3],[[3274,3277],2],[[3278,3284],3],[[3285,3286],2],[[3287,3292],3],[3293,2],[3294,2],[3295,3],[[3296,3297],2],[[3298,3299],2],[[3300,3301],3],[[3302,3311],2],[3312,3],[[3313,3314],2],[[3315,3327],3],[3328,2],[3329,2],[[3330,3331],2],[3332,2],[[3333,3340],2],[3341,3],[[3342,3344],2],[3345,3],[[3346,3368],2],[3369,2],[[3370,3385],2],[3386,2],[[3387,3388],2],[3389,2],[[3390,3395],2],[3396,2],[3397,3],[[3398,3400],2],[3401,3],[[3402,3405],2],[3406,2],[3407,2],[[3408,3411],3],[[3412,3414],2],[3415,2],[[3416,3422],2],[3423,2],[[3424,3425],2],[[3426,3427],2],[[3428,3429],3],[[3430,3439],2],[[3440,3445],2],[[3446,3448],2],[3449,2],[[3450,3455],2],[3456,3],[3457,2],[[3458,3459],2],[3460,3],[[3461,3478],2],[[3479,3481],3],[[3482,3505],2],[3506,3],[[3507,3515],2],[3516,3],[3517,2],[[3518,3519],3],[[3520,3526],2],[[3527,3529],3],[3530,2],[[3531,3534],3],[[3535,3540],2],[3541,3],[3542,2],[3543,3],[[3544,3551],2],[[3552,3557],3],[[3558,3567],2],[[3568,3569],3],[[3570,3571],2],[3572,2],[[3573,3584],3],[[3585,3634],2],[3635,1,"ํา"],[[3636,3642],2],[[3643,3646],3],[3647,2],[[3648,3662],2],[3663,2],[[3664,3673],2],[[3674,3675],2],[[3676,3712],3],[[3713,3714],2],[3715,3],[3716,2],[3717,3],[3718,2],[[3719,3720],2],[3721,2],[3722,2],[3723,3],[3724,2],[3725,2],[[3726,3731],2],[[3732,3735],2],[3736,2],[[3737,3743],2],[3744,2],[[3745,3747],2],[3748,3],[3749,2],[3750,3],[3751,2],[[3752,3753],2],[[3754,3755],2],[3756,2],[[3757,3762],2],[3763,1,"ໍາ"],[[3764,3769],2],[3770,2],[[3771,3773],2],[[3774,3775],3],[[3776,3780],2],[3781,3],[3782,2],[3783,3],[[3784,3789],2],[[3790,3791],3],[[3792,3801],2],[[3802,3803],3],[3804,1,"ຫນ"],[3805,1,"ຫມ"],[[3806,3807],2],[[3808,3839],3],[3840,2],[[3841,3850],2],[3851,2],[3852,1,"་"],[[3853,3863],2],[[3864,3865],2],[[3866,3871],2],[[3872,3881],2],[[3882,3892],2],[3893,2],[3894,2],[3895,2],[3896,2],[3897,2],[[3898,3901],2],[[3902,3906],2],[3907,1,"གྷ"],[[3908,3911],2],[3912,3],[[3913,3916],2],[3917,1,"ཌྷ"],[[3918,3921],2],[3922,1,"དྷ"],[[3923,3926],2],[3927,1,"བྷ"],[[3928,3931],2],[3932,1,"ཛྷ"],[[3933,3944],2],[3945,1,"ཀྵ"],[3946,2],[[3947,3948],2],[[3949,3952],3],[[3953,3954],2],[3955,1,"ཱི"],[3956,2],[3957,1,"ཱུ"],[3958,1,"ྲྀ"],[3959,1,"ྲཱྀ"],[3960,1,"ླྀ"],[3961,1,"ླཱྀ"],[[3962,3968],2],[3969,1,"ཱྀ"],[[3970,3972],2],[3973,2],[[3974,3979],2],[[3980,3983],2],[[3984,3986],2],[3987,1,"ྒྷ"],[[3988,3989],2],[3990,2],[3991,2],[3992,3],[[3993,3996],2],[3997,1,"ྜྷ"],[[3998,4001],2],[4002,1,"ྡྷ"],[[4003,4006],2],[4007,1,"ྦྷ"],[[4008,4011],2],[4012,1,"ྫྷ"],[4013,2],[[4014,4016],2],[[4017,4023],2],[4024,2],[4025,1,"ྐྵ"],[[4026,4028],2],[4029,3],[[4030,4037],2],[4038,2],[[4039,4044],2],[4045,3],[4046,2],[4047,2],[[4048,4049],2],[[4050,4052],2],[[4053,4056],2],[[4057,4058],2],[[4059,4095],3],[[4096,4129],2],[4130,2],[[4131,4135],2],[4136,2],[[4137,4138],2],[4139,2],[[4140,4146],2],[[4147,4149],2],[[4150,4153],2],[[4154,4159],2],[[4160,4169],2],[[4170,4175],2],[[4176,4185],2],[[4186,4249],2],[[4250,4253],2],[[4254,4255],2],[[4256,4293],3],[4294,3],[4295,1,"ⴧ"],[[4296,4300],3],[4301,1,"ⴭ"],[[4302,4303],3],[[4304,4342],2],[[4343,4344],2],[[4345,4346],2],[4347,2],[4348,1,"ნ"],[[4349,4351],2],[[4352,4441],2],[[4442,4446],2],[[4447,4448],3],[[4449,4514],2],[[4515,4519],2],[[4520,4601],2],[[4602,4607],2],[[4608,4614],2],[4615,2],[[4616,4678],2],[4679,2],[4680,2],[4681,3],[[4682,4685],2],[[4686,4687],3],[[4688,4694],2],[4695,3],[4696,2],[4697,3],[[4698,4701],2],[[4702,4703],3],[[4704,4742],2],[4743,2],[4744,2],[4745,3],[[4746,4749],2],[[4750,4751],3],[[4752,4782],2],[4783,2],[4784,2],[4785,3],[[4786,4789],2],[[4790,4791],3],[[4792,4798],2],[4799,3],[4800,2],[4801,3],[[4802,4805],2],[[4806,4807],3],[[4808,4814],2],[4815,2],[[4816,4822],2],[4823,3],[[4824,4846],2],[4847,2],[[4848,4878],2],[4879,2],[4880,2],[4881,3],[[4882,4885],2],[[4886,4887],3],[[4888,4894],2],[4895,2],[[4896,4934],2],[4935,2],[[4936,4954],2],[[4955,4956],3],[[4957,4958],2],[4959,2],[4960,2],[[4961,4988],2],[[4989,4991],3],[[4992,5007],2],[[5008,5017],2],[[5018,5023],3],[[5024,5108],2],[5109,2],[[5110,5111],3],[5112,1,"Ᏸ"],[5113,1,"Ᏹ"],[5114,1,"Ᏺ"],[5115,1,"Ᏻ"],[5116,1,"Ᏼ"],[5117,1,"Ᏽ"],[[5118,5119],3],[5120,2],[[5121,5740],2],[[5741,5742],2],[[5743,5750],2],[[5751,5759],2],[5760,3],[[5761,5786],2],[[5787,5788],2],[[5789,5791],3],[[5792,5866],2],[[5867,5872],2],[[5873,5880],2],[[5881,5887],3],[[5888,5900],2],[5901,2],[[5902,5908],2],[5909,2],[[5910,5918],3],[5919,2],[[5920,5940],2],[[5941,5942],2],[[5943,5951],3],[[5952,5971],2],[[5972,5983],3],[[5984,5996],2],[5997,3],[[5998,6000],2],[6001,3],[[6002,6003],2],[[6004,6015],3],[[6016,6067],2],[[6068,6069],3],[[6070,6099],2],[[6100,6102],2],[6103,2],[[6104,6107],2],[6108,2],[6109,2],[[6110,6111],3],[[6112,6121],2],[[6122,6127],3],[[6128,6137],2],[[6138,6143],3],[[6144,6149],2],[6150,3],[[6151,6154],2],[[6155,6157],7],[6158,3],[6159,7],[[6160,6169],2],[[6170,6175],3],[[6176,6263],2],[6264,2],[[6265,6271],3],[[6272,6313],2],[6314,2],[[6315,6319],3],[[6320,6389],2],[[6390,6399],3],[[6400,6428],2],[[6429,6430],2],[6431,3],[[6432,6443],2],[[6444,6447],3],[[6448,6459],2],[[6460,6463],3],[6464,2],[[6465,6467],3],[[6468,6469],2],[[6470,6509],2],[[6510,6511],3],[[6512,6516],2],[[6517,6527],3],[[6528,6569],2],[[6570,6571],2],[[6572,6575],3],[[6576,6601],2],[[6602,6607],3],[[6608,6617],2],[6618,2],[[6619,6621],3],[[6622,6623],2],[[6624,6655],2],[[6656,6683],2],[[6684,6685],3],[[6686,6687],2],[[6688,6750],2],[6751,3],[[6752,6780],2],[[6781,6782],3],[[6783,6793],2],[[6794,6799],3],[[6800,6809],2],[[6810,6815],3],[[6816,6822],2],[6823,2],[[6824,6829],2],[[6830,6831],3],[[6832,6845],2],[6846,2],[[6847,6848],2],[[6849,6862],2],[[6863,6911],3],[[6912,6987],2],[6988,2],[[6989,6991],3],[[6992,7001],2],[[7002,7018],2],[[7019,7027],2],[[7028,7036],2],[[7037,7038],2],[7039,3],[[7040,7082],2],[[7083,7085],2],[[7086,7097],2],[[7098,7103],2],[[7104,7155],2],[[7156,7163],3],[[7164,7167],2],[[7168,7223],2],[[7224,7226],3],[[7227,7231],2],[[7232,7241],2],[[7242,7244],3],[[7245,7293],2],[[7294,7295],2],[7296,1,"в"],[7297,1,"д"],[7298,1,"о"],[7299,1,"с"],[[7300,7301],1,"т"],[7302,1,"ъ"],[7303,1,"ѣ"],[7304,1,"ꙋ"],[[7305,7311],3],[7312,1,"ა"],[7313,1,"ბ"],[7314,1,"გ"],[7315,1,"დ"],[7316,1,"ე"],[7317,1,"ვ"],[7318,1,"ზ"],[7319,1,"თ"],[7320,1,"ი"],[7321,1,"კ"],[7322,1,"ლ"],[7323,1,"მ"],[7324,1,"ნ"],[7325,1,"ო"],[7326,1,"პ"],[7327,1,"ჟ"],[7328,1,"რ"],[7329,1,"ს"],[7330,1,"ტ"],[7331,1,"უ"],[7332,1,"ფ"],[7333,1,"ქ"],[7334,1,"ღ"],[7335,1,"ყ"],[7336,1,"შ"],[7337,1,"ჩ"],[7338,1,"ც"],[7339,1,"ძ"],[7340,1,"წ"],[7341,1,"ჭ"],[7342,1,"ხ"],[7343,1,"ჯ"],[7344,1,"ჰ"],[7345,1,"ჱ"],[7346,1,"ჲ"],[7347,1,"ჳ"],[7348,1,"ჴ"],[7349,1,"ჵ"],[7350,1,"ჶ"],[7351,1,"ჷ"],[7352,1,"ჸ"],[7353,1,"ჹ"],[7354,1,"ჺ"],[[7355,7356],3],[7357,1,"ჽ"],[7358,1,"ჾ"],[7359,1,"ჿ"],[[7360,7367],2],[[7368,7375],3],[[7376,7378],2],[7379,2],[[7380,7410],2],[[7411,7414],2],[7415,2],[[7416,7417],2],[7418,2],[[7419,7423],3],[[7424,7467],2],[7468,1,"a"],[7469,1,"æ"],[7470,1,"b"],[7471,2],[7472,1,"d"],[7473,1,"e"],[7474,1,"ǝ"],[7475,1,"g"],[7476,1,"h"],[7477,1,"i"],[7478,1,"j"],[7479,1,"k"],[7480,1,"l"],[7481,1,"m"],[7482,1,"n"],[7483,2],[7484,1,"o"],[7485,1,"ȣ"],[7486,1,"p"],[7487,1,"r"],[7488,1,"t"],[7489,1,"u"],[7490,1,"w"],[7491,1,"a"],[7492,1,"ɐ"],[7493,1,"ɑ"],[7494,1,"ᴂ"],[7495,1,"b"],[7496,1,"d"],[7497,1,"e"],[7498,1,"ə"],[7499,1,"ɛ"],[7500,1,"ɜ"],[7501,1,"g"],[7502,2],[7503,1,"k"],[7504,1,"m"],[7505,1,"ŋ"],[7506,1,"o"],[7507,1,"ɔ"],[7508,1,"ᴖ"],[7509,1,"ᴗ"],[7510,1,"p"],[7511,1,"t"],[7512,1,"u"],[7513,1,"ᴝ"],[7514,1,"ɯ"],[7515,1,"v"],[7516,1,"ᴥ"],[7517,1,"β"],[7518,1,"γ"],[7519,1,"δ"],[7520,1,"φ"],[7521,1,"χ"],[7522,1,"i"],[7523,1,"r"],[7524,1,"u"],[7525,1,"v"],[7526,1,"β"],[7527,1,"γ"],[7528,1,"ρ"],[7529,1,"φ"],[7530,1,"χ"],[7531,2],[[7532,7543],2],[7544,1,"н"],[[7545,7578],2],[7579,1,"ɒ"],[7580,1,"c"],[7581,1,"ɕ"],[7582,1,"ð"],[7583,1,"ɜ"],[7584,1,"f"],[7585,1,"ɟ"],[7586,1,"ɡ"],[7587,1,"ɥ"],[7588,1,"ɨ"],[7589,1,"ɩ"],[7590,1,"ɪ"],[7591,1,"ᵻ"],[7592,1,"ʝ"],[7593,1,"ɭ"],[7594,1,"ᶅ"],[7595,1,"ʟ"],[7596,1,"ɱ"],[7597,1,"ɰ"],[7598,1,"ɲ"],[7599,1,"ɳ"],[7600,1,"ɴ"],[7601,1,"ɵ"],[7602,1,"ɸ"],[7603,1,"ʂ"],[7604,1,"ʃ"],[7605,1,"ƫ"],[7606,1,"ʉ"],[7607,1,"ʊ"],[7608,1,"ᴜ"],[7609,1,"ʋ"],[7610,1,"ʌ"],[7611,1,"z"],[7612,1,"ʐ"],[7613,1,"ʑ"],[7614,1,"ʒ"],[7615,1,"θ"],[[7616,7619],2],[[7620,7626],2],[[7627,7654],2],[[7655,7669],2],[[7670,7673],2],[7674,2],[7675,2],[7676,2],[7677,2],[[7678,7679],2],[7680,1,"ḁ"],[7681,2],[7682,1,"ḃ"],[7683,2],[7684,1,"ḅ"],[7685,2],[7686,1,"ḇ"],[7687,2],[7688,1,"ḉ"],[7689,2],[7690,1,"ḋ"],[7691,2],[7692,1,"ḍ"],[7693,2],[7694,1,"ḏ"],[7695,2],[7696,1,"ḑ"],[7697,2],[7698,1,"ḓ"],[7699,2],[7700,1,"ḕ"],[7701,2],[7702,1,"ḗ"],[7703,2],[7704,1,"ḙ"],[7705,2],[7706,1,"ḛ"],[7707,2],[7708,1,"ḝ"],[7709,2],[7710,1,"ḟ"],[7711,2],[7712,1,"ḡ"],[7713,2],[7714,1,"ḣ"],[7715,2],[7716,1,"ḥ"],[7717,2],[7718,1,"ḧ"],[7719,2],[7720,1,"ḩ"],[7721,2],[7722,1,"ḫ"],[7723,2],[7724,1,"ḭ"],[7725,2],[7726,1,"ḯ"],[7727,2],[7728,1,"ḱ"],[7729,2],[7730,1,"ḳ"],[7731,2],[7732,1,"ḵ"],[7733,2],[7734,1,"ḷ"],[7735,2],[7736,1,"ḹ"],[7737,2],[7738,1,"ḻ"],[7739,2],[7740,1,"ḽ"],[7741,2],[7742,1,"ḿ"],[7743,2],[7744,1,"ṁ"],[7745,2],[7746,1,"ṃ"],[7747,2],[7748,1,"ṅ"],[7749,2],[7750,1,"ṇ"],[7751,2],[7752,1,"ṉ"],[7753,2],[7754,1,"ṋ"],[7755,2],[7756,1,"ṍ"],[7757,2],[7758,1,"ṏ"],[7759,2],[7760,1,"ṑ"],[7761,2],[7762,1,"ṓ"],[7763,2],[7764,1,"ṕ"],[7765,2],[7766,1,"ṗ"],[7767,2],[7768,1,"ṙ"],[7769,2],[7770,1,"ṛ"],[7771,2],[7772,1,"ṝ"],[7773,2],[7774,1,"ṟ"],[7775,2],[7776,1,"ṡ"],[7777,2],[7778,1,"ṣ"],[7779,2],[7780,1,"ṥ"],[7781,2],[7782,1,"ṧ"],[7783,2],[7784,1,"ṩ"],[7785,2],[7786,1,"ṫ"],[7787,2],[7788,1,"ṭ"],[7789,2],[7790,1,"ṯ"],[7791,2],[7792,1,"ṱ"],[7793,2],[7794,1,"ṳ"],[7795,2],[7796,1,"ṵ"],[7797,2],[7798,1,"ṷ"],[7799,2],[7800,1,"ṹ"],[7801,2],[7802,1,"ṻ"],[7803,2],[7804,1,"ṽ"],[7805,2],[7806,1,"ṿ"],[7807,2],[7808,1,"ẁ"],[7809,2],[7810,1,"ẃ"],[7811,2],[7812,1,"ẅ"],[7813,2],[7814,1,"ẇ"],[7815,2],[7816,1,"ẉ"],[7817,2],[7818,1,"ẋ"],[7819,2],[7820,1,"ẍ"],[7821,2],[7822,1,"ẏ"],[7823,2],[7824,1,"ẑ"],[7825,2],[7826,1,"ẓ"],[7827,2],[7828,1,"ẕ"],[[7829,7833],2],[7834,1,"aʾ"],[7835,1,"ṡ"],[[7836,7837],2],[7838,1,"ss"],[7839,2],[7840,1,"ạ"],[7841,2],[7842,1,"ả"],[7843,2],[7844,1,"ấ"],[7845,2],[7846,1,"ầ"],[7847,2],[7848,1,"ẩ"],[7849,2],[7850,1,"ẫ"],[7851,2],[7852,1,"ậ"],[7853,2],[7854,1,"ắ"],[7855,2],[7856,1,"ằ"],[7857,2],[7858,1,"ẳ"],[7859,2],[7860,1,"ẵ"],[7861,2],[7862,1,"ặ"],[7863,2],[7864,1,"ẹ"],[7865,2],[7866,1,"ẻ"],[7867,2],[7868,1,"ẽ"],[7869,2],[7870,1,"ế"],[7871,2],[7872,1,"ề"],[7873,2],[7874,1,"ể"],[7875,2],[7876,1,"ễ"],[7877,2],[7878,1,"ệ"],[7879,2],[7880,1,"ỉ"],[7881,2],[7882,1,"ị"],[7883,2],[7884,1,"ọ"],[7885,2],[7886,1,"ỏ"],[7887,2],[7888,1,"ố"],[7889,2],[7890,1,"ồ"],[7891,2],[7892,1,"ổ"],[7893,2],[7894,1,"ỗ"],[7895,2],[7896,1,"ộ"],[7897,2],[7898,1,"ớ"],[7899,2],[7900,1,"ờ"],[7901,2],[7902,1,"ở"],[7903,2],[7904,1,"ỡ"],[7905,2],[7906,1,"ợ"],[7907,2],[7908,1,"ụ"],[7909,2],[7910,1,"ủ"],[7911,2],[7912,1,"ứ"],[7913,2],[7914,1,"ừ"],[7915,2],[7916,1,"ử"],[7917,2],[7918,1,"ữ"],[7919,2],[7920,1,"ự"],[7921,2],[7922,1,"ỳ"],[7923,2],[7924,1,"ỵ"],[7925,2],[7926,1,"ỷ"],[7927,2],[7928,1,"ỹ"],[7929,2],[7930,1,"ỻ"],[7931,2],[7932,1,"ỽ"],[7933,2],[7934,1,"ỿ"],[7935,2],[[7936,7943],2],[7944,1,"ἀ"],[7945,1,"ἁ"],[7946,1,"ἂ"],[7947,1,"ἃ"],[7948,1,"ἄ"],[7949,1,"ἅ"],[7950,1,"ἆ"],[7951,1,"ἇ"],[[7952,7957],2],[[7958,7959],3],[7960,1,"ἐ"],[7961,1,"ἑ"],[7962,1,"ἒ"],[7963,1,"ἓ"],[7964,1,"ἔ"],[7965,1,"ἕ"],[[7966,7967],3],[[7968,7975],2],[7976,1,"ἠ"],[7977,1,"ἡ"],[7978,1,"ἢ"],[7979,1,"ἣ"],[7980,1,"ἤ"],[7981,1,"ἥ"],[7982,1,"ἦ"],[7983,1,"ἧ"],[[7984,7991],2],[7992,1,"ἰ"],[7993,1,"ἱ"],[7994,1,"ἲ"],[7995,1,"ἳ"],[7996,1,"ἴ"],[7997,1,"ἵ"],[7998,1,"ἶ"],[7999,1,"ἷ"],[[8000,8005],2],[[8006,8007],3],[8008,1,"ὀ"],[8009,1,"ὁ"],[8010,1,"ὂ"],[8011,1,"ὃ"],[8012,1,"ὄ"],[8013,1,"ὅ"],[[8014,8015],3],[[8016,8023],2],[8024,3],[8025,1,"ὑ"],[8026,3],[8027,1,"ὓ"],[8028,3],[8029,1,"ὕ"],[8030,3],[8031,1,"ὗ"],[[8032,8039],2],[8040,1,"ὠ"],[8041,1,"ὡ"],[8042,1,"ὢ"],[8043,1,"ὣ"],[8044,1,"ὤ"],[8045,1,"ὥ"],[8046,1,"ὦ"],[8047,1,"ὧ"],[8048,2],[8049,1,"ά"],[8050,2],[8051,1,"έ"],[8052,2],[8053,1,"ή"],[8054,2],[8055,1,"ί"],[8056,2],[8057,1,"ό"],[8058,2],[8059,1,"ύ"],[8060,2],[8061,1,"ώ"],[[8062,8063],3],[8064,1,"ἀι"],[8065,1,"ἁι"],[8066,1,"ἂι"],[8067,1,"ἃι"],[8068,1,"ἄι"],[8069,1,"ἅι"],[8070,1,"ἆι"],[8071,1,"ἇι"],[8072,1,"ἀι"],[8073,1,"ἁι"],[8074,1,"ἂι"],[8075,1,"ἃι"],[8076,1,"ἄι"],[8077,1,"ἅι"],[8078,1,"ἆι"],[8079,1,"ἇι"],[8080,1,"ἠι"],[8081,1,"ἡι"],[8082,1,"ἢι"],[8083,1,"ἣι"],[8084,1,"ἤι"],[8085,1,"ἥι"],[8086,1,"ἦι"],[8087,1,"ἧι"],[8088,1,"ἠι"],[8089,1,"ἡι"],[8090,1,"ἢι"],[8091,1,"ἣι"],[8092,1,"ἤι"],[8093,1,"ἥι"],[8094,1,"ἦι"],[8095,1,"ἧι"],[8096,1,"ὠι"],[8097,1,"ὡι"],[8098,1,"ὢι"],[8099,1,"ὣι"],[8100,1,"ὤι"],[8101,1,"ὥι"],[8102,1,"ὦι"],[8103,1,"ὧι"],[8104,1,"ὠι"],[8105,1,"ὡι"],[8106,1,"ὢι"],[8107,1,"ὣι"],[8108,1,"ὤι"],[8109,1,"ὥι"],[8110,1,"ὦι"],[8111,1,"ὧι"],[[8112,8113],2],[8114,1,"ὰι"],[8115,1,"αι"],[8116,1,"άι"],[8117,3],[8118,2],[8119,1,"ᾶι"],[8120,1,"ᾰ"],[8121,1,"ᾱ"],[8122,1,"ὰ"],[8123,1,"ά"],[8124,1,"αι"],[8125,5," ̓"],[8126,1,"ι"],[8127,5," ̓"],[8128,5," ͂"],[8129,5," ̈͂"],[8130,1,"ὴι"],[8131,1,"ηι"],[8132,1,"ήι"],[8133,3],[8134,2],[8135,1,"ῆι"],[8136,1,"ὲ"],[8137,1,"έ"],[8138,1,"ὴ"],[8139,1,"ή"],[8140,1,"ηι"],[8141,5," ̓̀"],[8142,5," ̓́"],[8143,5," ̓͂"],[[8144,8146],2],[8147,1,"ΐ"],[[8148,8149],3],[[8150,8151],2],[8152,1,"ῐ"],[8153,1,"ῑ"],[8154,1,"ὶ"],[8155,1,"ί"],[8156,3],[8157,5," ̔̀"],[8158,5," ̔́"],[8159,5," ̔͂"],[[8160,8162],2],[8163,1,"ΰ"],[[8164,8167],2],[8168,1,"ῠ"],[8169,1,"ῡ"],[8170,1,"ὺ"],[8171,1,"ύ"],[8172,1,"ῥ"],[8173,5," ̈̀"],[8174,5," ̈́"],[8175,5,"`"],[[8176,8177],3],[8178,1,"ὼι"],[8179,1,"ωι"],[8180,1,"ώι"],[8181,3],[8182,2],[8183,1,"ῶι"],[8184,1,"ὸ"],[8185,1,"ό"],[8186,1,"ὼ"],[8187,1,"ώ"],[8188,1,"ωι"],[8189,5," ́"],[8190,5," ̔"],[8191,3],[[8192,8202],5," "],[8203,7],[[8204,8205],6,""],[[8206,8207],3],[8208,2],[8209,1,"‐"],[[8210,8214],2],[8215,5," ̳"],[[8216,8227],2],[[8228,8230],3],[8231,2],[[8232,8238],3],[8239,5," "],[[8240,8242],2],[8243,1,"′′"],[8244,1,"′′′"],[8245,2],[8246,1,"‵‵"],[8247,1,"‵‵‵"],[[8248,8251],2],[8252,5,"!!"],[8253,2],[8254,5," ̅"],[[8255,8262],2],[8263,5,"??"],[8264,5,"?!"],[8265,5,"!?"],[[8266,8269],2],[[8270,8274],2],[[8275,8276],2],[[8277,8278],2],[8279,1,"′′′′"],[[8280,8286],2],[8287,5," "],[8288,7],[[8289,8291],3],[8292,7],[8293,3],[[8294,8297],3],[[8298,8303],3],[8304,1,"0"],[8305,1,"i"],[[8306,8307],3],[8308,1,"4"],[8309,1,"5"],[8310,1,"6"],[8311,1,"7"],[8312,1,"8"],[8313,1,"9"],[8314,5,"+"],[8315,1,"−"],[8316,5,"="],[8317,5,"("],[8318,5,")"],[8319,1,"n"],[8320,1,"0"],[8321,1,"1"],[8322,1,"2"],[8323,1,"3"],[8324,1,"4"],[8325,1,"5"],[8326,1,"6"],[8327,1,"7"],[8328,1,"8"],[8329,1,"9"],[8330,5,"+"],[8331,1,"−"],[8332,5,"="],[8333,5,"("],[8334,5,")"],[8335,3],[8336,1,"a"],[8337,1,"e"],[8338,1,"o"],[8339,1,"x"],[8340,1,"ə"],[8341,1,"h"],[8342,1,"k"],[8343,1,"l"],[8344,1,"m"],[8345,1,"n"],[8346,1,"p"],[8347,1,"s"],[8348,1,"t"],[[8349,8351],3],[[8352,8359],2],[8360,1,"rs"],[[8361,8362],2],[8363,2],[8364,2],[[8365,8367],2],[[8368,8369],2],[[8370,8373],2],[[8374,8376],2],[8377,2],[8378,2],[[8379,8381],2],[8382,2],[8383,2],[8384,2],[[8385,8399],3],[[8400,8417],2],[[8418,8419],2],[[8420,8426],2],[8427,2],[[8428,8431],2],[8432,2],[[8433,8447],3],[8448,5,"a/c"],[8449,5,"a/s"],[8450,1,"c"],[8451,1,"°c"],[8452,2],[8453,5,"c/o"],[8454,5,"c/u"],[8455,1,"ɛ"],[8456,2],[8457,1,"°f"],[8458,1,"g"],[[8459,8462],1,"h"],[8463,1,"ħ"],[[8464,8465],1,"i"],[[8466,8467],1,"l"],[8468,2],[8469,1,"n"],[8470,1,"no"],[[8471,8472],2],[8473,1,"p"],[8474,1,"q"],[[8475,8477],1,"r"],[[8478,8479],2],[8480,1,"sm"],[8481,1,"tel"],[8482,1,"tm"],[8483,2],[8484,1,"z"],[8485,2],[8486,1,"ω"],[8487,2],[8488,1,"z"],[8489,2],[8490,1,"k"],[8491,1,"å"],[8492,1,"b"],[8493,1,"c"],[8494,2],[[8495,8496],1,"e"],[8497,1,"f"],[8498,3],[8499,1,"m"],[8500,1,"o"],[8501,1,"א"],[8502,1,"ב"],[8503,1,"ג"],[8504,1,"ד"],[8505,1,"i"],[8506,2],[8507,1,"fax"],[8508,1,"π"],[[8509,8510],1,"γ"],[8511,1,"π"],[8512,1,"∑"],[[8513,8516],2],[[8517,8518],1,"d"],[8519,1,"e"],[8520,1,"i"],[8521,1,"j"],[[8522,8523],2],[8524,2],[8525,2],[8526,2],[8527,2],[8528,1,"1⁄7"],[8529,1,"1⁄9"],[8530,1,"1⁄10"],[8531,1,"1⁄3"],[8532,1,"2⁄3"],[8533,1,"1⁄5"],[8534,1,"2⁄5"],[8535,1,"3⁄5"],[8536,1,"4⁄5"],[8537,1,"1⁄6"],[8538,1,"5⁄6"],[8539,1,"1⁄8"],[8540,1,"3⁄8"],[8541,1,"5⁄8"],[8542,1,"7⁄8"],[8543,1,"1⁄"],[8544,1,"i"],[8545,1,"ii"],[8546,1,"iii"],[8547,1,"iv"],[8548,1,"v"],[8549,1,"vi"],[8550,1,"vii"],[8551,1,"viii"],[8552,1,"ix"],[8553,1,"x"],[8554,1,"xi"],[8555,1,"xii"],[8556,1,"l"],[8557,1,"c"],[8558,1,"d"],[8559,1,"m"],[8560,1,"i"],[8561,1,"ii"],[8562,1,"iii"],[8563,1,"iv"],[8564,1,"v"],[8565,1,"vi"],[8566,1,"vii"],[8567,1,"viii"],[8568,1,"ix"],[8569,1,"x"],[8570,1,"xi"],[8571,1,"xii"],[8572,1,"l"],[8573,1,"c"],[8574,1,"d"],[8575,1,"m"],[[8576,8578],2],[8579,3],[8580,2],[[8581,8584],2],[8585,1,"0⁄3"],[[8586,8587],2],[[8588,8591],3],[[8592,8682],2],[[8683,8691],2],[[8692,8703],2],[[8704,8747],2],[8748,1,"∫∫"],[8749,1,"∫∫∫"],[8750,2],[8751,1,"∮∮"],[8752,1,"∮∮∮"],[[8753,8799],2],[8800,4],[[8801,8813],2],[[8814,8815],4],[[8816,8945],2],[[8946,8959],2],[8960,2],[8961,2],[[8962,9000],2],[9001,1,"〈"],[9002,1,"〉"],[[9003,9082],2],[9083,2],[9084,2],[[9085,9114],2],[[9115,9166],2],[[9167,9168],2],[[9169,9179],2],[[9180,9191],2],[9192,2],[[9193,9203],2],[[9204,9210],2],[[9211,9214],2],[9215,2],[[9216,9252],2],[[9253,9254],2],[[9255,9279],3],[[9280,9290],2],[[9291,9311],3],[9312,1,"1"],[9313,1,"2"],[9314,1,"3"],[9315,1,"4"],[9316,1,"5"],[9317,1,"6"],[9318,1,"7"],[9319,1,"8"],[9320,1,"9"],[9321,1,"10"],[9322,1,"11"],[9323,1,"12"],[9324,1,"13"],[9325,1,"14"],[9326,1,"15"],[9327,1,"16"],[9328,1,"17"],[9329,1,"18"],[9330,1,"19"],[9331,1,"20"],[9332,5,"(1)"],[9333,5,"(2)"],[9334,5,"(3)"],[9335,5,"(4)"],[9336,5,"(5)"],[9337,5,"(6)"],[9338,5,"(7)"],[9339,5,"(8)"],[9340,5,"(9)"],[9341,5,"(10)"],[9342,5,"(11)"],[9343,5,"(12)"],[9344,5,"(13)"],[9345,5,"(14)"],[9346,5,"(15)"],[9347,5,"(16)"],[9348,5,"(17)"],[9349,5,"(18)"],[9350,5,"(19)"],[9351,5,"(20)"],[[9352,9371],3],[9372,5,"(a)"],[9373,5,"(b)"],[9374,5,"(c)"],[9375,5,"(d)"],[9376,5,"(e)"],[9377,5,"(f)"],[9378,5,"(g)"],[9379,5,"(h)"],[9380,5,"(i)"],[9381,5,"(j)"],[9382,5,"(k)"],[9383,5,"(l)"],[9384,5,"(m)"],[9385,5,"(n)"],[9386,5,"(o)"],[9387,5,"(p)"],[9388,5,"(q)"],[9389,5,"(r)"],[9390,5,"(s)"],[9391,5,"(t)"],[9392,5,"(u)"],[9393,5,"(v)"],[9394,5,"(w)"],[9395,5,"(x)"],[9396,5,"(y)"],[9397,5,"(z)"],[9398,1,"a"],[9399,1,"b"],[9400,1,"c"],[9401,1,"d"],[9402,1,"e"],[9403,1,"f"],[9404,1,"g"],[9405,1,"h"],[9406,1,"i"],[9407,1,"j"],[9408,1,"k"],[9409,1,"l"],[9410,1,"m"],[9411,1,"n"],[9412,1,"o"],[9413,1,"p"],[9414,1,"q"],[9415,1,"r"],[9416,1,"s"],[9417,1,"t"],[9418,1,"u"],[9419,1,"v"],[9420,1,"w"],[9421,1,"x"],[9422,1,"y"],[9423,1,"z"],[9424,1,"a"],[9425,1,"b"],[9426,1,"c"],[9427,1,"d"],[9428,1,"e"],[9429,1,"f"],[9430,1,"g"],[9431,1,"h"],[9432,1,"i"],[9433,1,"j"],[9434,1,"k"],[9435,1,"l"],[9436,1,"m"],[9437,1,"n"],[9438,1,"o"],[9439,1,"p"],[9440,1,"q"],[9441,1,"r"],[9442,1,"s"],[9443,1,"t"],[9444,1,"u"],[9445,1,"v"],[9446,1,"w"],[9447,1,"x"],[9448,1,"y"],[9449,1,"z"],[9450,1,"0"],[[9451,9470],2],[9471,2],[[9472,9621],2],[[9622,9631],2],[[9632,9711],2],[[9712,9719],2],[[9720,9727],2],[[9728,9747],2],[[9748,9749],2],[[9750,9751],2],[9752,2],[9753,2],[[9754,9839],2],[[9840,9841],2],[[9842,9853],2],[[9854,9855],2],[[9856,9865],2],[[9866,9873],2],[[9874,9884],2],[9885,2],[[9886,9887],2],[[9888,9889],2],[[9890,9905],2],[9906,2],[[9907,9916],2],[[9917,9919],2],[[9920,9923],2],[[9924,9933],2],[9934,2],[[9935,9953],2],[9954,2],[9955,2],[[9956,9959],2],[[9960,9983],2],[9984,2],[[9985,9988],2],[9989,2],[[9990,9993],2],[[9994,9995],2],[[9996,10023],2],[10024,2],[[10025,10059],2],[10060,2],[10061,2],[10062,2],[[10063,10066],2],[[10067,10069],2],[10070,2],[10071,2],[[10072,10078],2],[[10079,10080],2],[[10081,10087],2],[[10088,10101],2],[[10102,10132],2],[[10133,10135],2],[[10136,10159],2],[10160,2],[[10161,10174],2],[10175,2],[[10176,10182],2],[[10183,10186],2],[10187,2],[10188,2],[10189,2],[[10190,10191],2],[[10192,10219],2],[[10220,10223],2],[[10224,10239],2],[[10240,10495],2],[[10496,10763],2],[10764,1,"∫∫∫∫"],[[10765,10867],2],[10868,5,"::="],[10869,5,"=="],[10870,5,"==="],[[10871,10971],2],[10972,1,"⫝̸"],[[10973,11007],2],[[11008,11021],2],[[11022,11027],2],[[11028,11034],2],[[11035,11039],2],[[11040,11043],2],[[11044,11084],2],[[11085,11087],2],[[11088,11092],2],[[11093,11097],2],[[11098,11123],2],[[11124,11125],3],[[11126,11157],2],[11158,3],[11159,2],[[11160,11193],2],[[11194,11196],2],[[11197,11208],2],[11209,2],[[11210,11217],2],[11218,2],[[11219,11243],2],[[11244,11247],2],[[11248,11262],2],[11263,2],[11264,1,"ⰰ"],[11265,1,"ⰱ"],[11266,1,"ⰲ"],[11267,1,"ⰳ"],[11268,1,"ⰴ"],[11269,1,"ⰵ"],[11270,1,"ⰶ"],[11271,1,"ⰷ"],[11272,1,"ⰸ"],[11273,1,"ⰹ"],[11274,1,"ⰺ"],[11275,1,"ⰻ"],[11276,1,"ⰼ"],[11277,1,"ⰽ"],[11278,1,"ⰾ"],[11279,1,"ⰿ"],[11280,1,"ⱀ"],[11281,1,"ⱁ"],[11282,1,"ⱂ"],[11283,1,"ⱃ"],[11284,1,"ⱄ"],[11285,1,"ⱅ"],[11286,1,"ⱆ"],[11287,1,"ⱇ"],[11288,1,"ⱈ"],[11289,1,"ⱉ"],[11290,1,"ⱊ"],[11291,1,"ⱋ"],[11292,1,"ⱌ"],[11293,1,"ⱍ"],[11294,1,"ⱎ"],[11295,1,"ⱏ"],[11296,1,"ⱐ"],[11297,1,"ⱑ"],[11298,1,"ⱒ"],[11299,1,"ⱓ"],[11300,1,"ⱔ"],[11301,1,"ⱕ"],[11302,1,"ⱖ"],[11303,1,"ⱗ"],[11304,1,"ⱘ"],[11305,1,"ⱙ"],[11306,1,"ⱚ"],[11307,1,"ⱛ"],[11308,1,"ⱜ"],[11309,1,"ⱝ"],[11310,1,"ⱞ"],[11311,1,"ⱟ"],[[11312,11358],2],[11359,2],[11360,1,"ⱡ"],[11361,2],[11362,1,"ɫ"],[11363,1,"ᵽ"],[11364,1,"ɽ"],[[11365,11366],2],[11367,1,"ⱨ"],[11368,2],[11369,1,"ⱪ"],[11370,2],[11371,1,"ⱬ"],[11372,2],[11373,1,"ɑ"],[11374,1,"ɱ"],[11375,1,"ɐ"],[11376,1,"ɒ"],[11377,2],[11378,1,"ⱳ"],[11379,2],[11380,2],[11381,1,"ⱶ"],[[11382,11383],2],[[11384,11387],2],[11388,1,"j"],[11389,1,"v"],[11390,1,"ȿ"],[11391,1,"ɀ"],[11392,1,"ⲁ"],[11393,2],[11394,1,"ⲃ"],[11395,2],[11396,1,"ⲅ"],[11397,2],[11398,1,"ⲇ"],[11399,2],[11400,1,"ⲉ"],[11401,2],[11402,1,"ⲋ"],[11403,2],[11404,1,"ⲍ"],[11405,2],[11406,1,"ⲏ"],[11407,2],[11408,1,"ⲑ"],[11409,2],[11410,1,"ⲓ"],[11411,2],[11412,1,"ⲕ"],[11413,2],[11414,1,"ⲗ"],[11415,2],[11416,1,"ⲙ"],[11417,2],[11418,1,"ⲛ"],[11419,2],[11420,1,"ⲝ"],[11421,2],[11422,1,"ⲟ"],[11423,2],[11424,1,"ⲡ"],[11425,2],[11426,1,"ⲣ"],[11427,2],[11428,1,"ⲥ"],[11429,2],[11430,1,"ⲧ"],[11431,2],[11432,1,"ⲩ"],[11433,2],[11434,1,"ⲫ"],[11435,2],[11436,1,"ⲭ"],[11437,2],[11438,1,"ⲯ"],[11439,2],[11440,1,"ⲱ"],[11441,2],[11442,1,"ⲳ"],[11443,2],[11444,1,"ⲵ"],[11445,2],[11446,1,"ⲷ"],[11447,2],[11448,1,"ⲹ"],[11449,2],[11450,1,"ⲻ"],[11451,2],[11452,1,"ⲽ"],[11453,2],[11454,1,"ⲿ"],[11455,2],[11456,1,"ⳁ"],[11457,2],[11458,1,"ⳃ"],[11459,2],[11460,1,"ⳅ"],[11461,2],[11462,1,"ⳇ"],[11463,2],[11464,1,"ⳉ"],[11465,2],[11466,1,"ⳋ"],[11467,2],[11468,1,"ⳍ"],[11469,2],[11470,1,"ⳏ"],[11471,2],[11472,1,"ⳑ"],[11473,2],[11474,1,"ⳓ"],[11475,2],[11476,1,"ⳕ"],[11477,2],[11478,1,"ⳗ"],[11479,2],[11480,1,"ⳙ"],[11481,2],[11482,1,"ⳛ"],[11483,2],[11484,1,"ⳝ"],[11485,2],[11486,1,"ⳟ"],[11487,2],[11488,1,"ⳡ"],[11489,2],[11490,1,"ⳣ"],[[11491,11492],2],[[11493,11498],2],[11499,1,"ⳬ"],[11500,2],[11501,1,"ⳮ"],[[11502,11505],2],[11506,1,"ⳳ"],[11507,2],[[11508,11512],3],[[11513,11519],2],[[11520,11557],2],[11558,3],[11559,2],[[11560,11564],3],[11565,2],[[11566,11567],3],[[11568,11621],2],[[11622,11623],2],[[11624,11630],3],[11631,1,"ⵡ"],[11632,2],[[11633,11646],3],[11647,2],[[11648,11670],2],[[11671,11679],3],[[11680,11686],2],[11687,3],[[11688,11694],2],[11695,3],[[11696,11702],2],[11703,3],[[11704,11710],2],[11711,3],[[11712,11718],2],[11719,3],[[11720,11726],2],[11727,3],[[11728,11734],2],[11735,3],[[11736,11742],2],[11743,3],[[11744,11775],2],[[11776,11799],2],[[11800,11803],2],[[11804,11805],2],[[11806,11822],2],[11823,2],[11824,2],[11825,2],[[11826,11835],2],[[11836,11842],2],[[11843,11844],2],[[11845,11849],2],[[11850,11854],2],[11855,2],[[11856,11858],2],[[11859,11869],2],[[11870,11903],3],[[11904,11929],2],[11930,3],[[11931,11934],2],[11935,1,"母"],[[11936,12018],2],[12019,1,"龟"],[[12020,12031],3],[12032,1,"一"],[12033,1,"丨"],[12034,1,"丶"],[12035,1,"丿"],[12036,1,"乙"],[12037,1,"亅"],[12038,1,"二"],[12039,1,"亠"],[12040,1,"人"],[12041,1,"儿"],[12042,1,"入"],[12043,1,"八"],[12044,1,"冂"],[12045,1,"冖"],[12046,1,"冫"],[12047,1,"几"],[12048,1,"凵"],[12049,1,"刀"],[12050,1,"力"],[12051,1,"勹"],[12052,1,"匕"],[12053,1,"匚"],[12054,1,"匸"],[12055,1,"十"],[12056,1,"卜"],[12057,1,"卩"],[12058,1,"厂"],[12059,1,"厶"],[12060,1,"又"],[12061,1,"口"],[12062,1,"囗"],[12063,1,"土"],[12064,1,"士"],[12065,1,"夂"],[12066,1,"夊"],[12067,1,"夕"],[12068,1,"大"],[12069,1,"女"],[12070,1,"子"],[12071,1,"宀"],[12072,1,"寸"],[12073,1,"小"],[12074,1,"尢"],[12075,1,"尸"],[12076,1,"屮"],[12077,1,"山"],[12078,1,"巛"],[12079,1,"工"],[12080,1,"己"],[12081,1,"巾"],[12082,1,"干"],[12083,1,"幺"],[12084,1,"广"],[12085,1,"廴"],[12086,1,"廾"],[12087,1,"弋"],[12088,1,"弓"],[12089,1,"彐"],[12090,1,"彡"],[12091,1,"彳"],[12092,1,"心"],[12093,1,"戈"],[12094,1,"戶"],[12095,1,"手"],[12096,1,"支"],[12097,1,"攴"],[12098,1,"文"],[12099,1,"斗"],[12100,1,"斤"],[12101,1,"方"],[12102,1,"无"],[12103,1,"日"],[12104,1,"曰"],[12105,1,"月"],[12106,1,"木"],[12107,1,"欠"],[12108,1,"止"],[12109,1,"歹"],[12110,1,"殳"],[12111,1,"毋"],[12112,1,"比"],[12113,1,"毛"],[12114,1,"氏"],[12115,1,"气"],[12116,1,"水"],[12117,1,"火"],[12118,1,"爪"],[12119,1,"父"],[12120,1,"爻"],[12121,1,"爿"],[12122,1,"片"],[12123,1,"牙"],[12124,1,"牛"],[12125,1,"犬"],[12126,1,"玄"],[12127,1,"玉"],[12128,1,"瓜"],[12129,1,"瓦"],[12130,1,"甘"],[12131,1,"生"],[12132,1,"用"],[12133,1,"田"],[12134,1,"疋"],[12135,1,"疒"],[12136,1,"癶"],[12137,1,"白"],[12138,1,"皮"],[12139,1,"皿"],[12140,1,"目"],[12141,1,"矛"],[12142,1,"矢"],[12143,1,"石"],[12144,1,"示"],[12145,1,"禸"],[12146,1,"禾"],[12147,1,"穴"],[12148,1,"立"],[12149,1,"竹"],[12150,1,"米"],[12151,1,"糸"],[12152,1,"缶"],[12153,1,"网"],[12154,1,"羊"],[12155,1,"羽"],[12156,1,"老"],[12157,1,"而"],[12158,1,"耒"],[12159,1,"耳"],[12160,1,"聿"],[12161,1,"肉"],[12162,1,"臣"],[12163,1,"自"],[12164,1,"至"],[12165,1,"臼"],[12166,1,"舌"],[12167,1,"舛"],[12168,1,"舟"],[12169,1,"艮"],[12170,1,"色"],[12171,1,"艸"],[12172,1,"虍"],[12173,1,"虫"],[12174,1,"血"],[12175,1,"行"],[12176,1,"衣"],[12177,1,"襾"],[12178,1,"見"],[12179,1,"角"],[12180,1,"言"],[12181,1,"谷"],[12182,1,"豆"],[12183,1,"豕"],[12184,1,"豸"],[12185,1,"貝"],[12186,1,"赤"],[12187,1,"走"],[12188,1,"足"],[12189,1,"身"],[12190,1,"車"],[12191,1,"辛"],[12192,1,"辰"],[12193,1,"辵"],[12194,1,"邑"],[12195,1,"酉"],[12196,1,"釆"],[12197,1,"里"],[12198,1,"金"],[12199,1,"長"],[12200,1,"門"],[12201,1,"阜"],[12202,1,"隶"],[12203,1,"隹"],[12204,1,"雨"],[12205,1,"靑"],[12206,1,"非"],[12207,1,"面"],[12208,1,"革"],[12209,1,"韋"],[12210,1,"韭"],[12211,1,"音"],[12212,1,"頁"],[12213,1,"風"],[12214,1,"飛"],[12215,1,"食"],[12216,1,"首"],[12217,1,"香"],[12218,1,"馬"],[12219,1,"骨"],[12220,1,"高"],[12221,1,"髟"],[12222,1,"鬥"],[12223,1,"鬯"],[12224,1,"鬲"],[12225,1,"鬼"],[12226,1,"魚"],[12227,1,"鳥"],[12228,1,"鹵"],[12229,1,"鹿"],[12230,1,"麥"],[12231,1,"麻"],[12232,1,"黃"],[12233,1,"黍"],[12234,1,"黑"],[12235,1,"黹"],[12236,1,"黽"],[12237,1,"鼎"],[12238,1,"鼓"],[12239,1,"鼠"],[12240,1,"鼻"],[12241,1,"齊"],[12242,1,"齒"],[12243,1,"龍"],[12244,1,"龜"],[12245,1,"龠"],[[12246,12271],3],[[12272,12283],3],[[12284,12287],3],[12288,5," "],[12289,2],[12290,1,"."],[[12291,12292],2],[[12293,12295],2],[[12296,12329],2],[[12330,12333],2],[[12334,12341],2],[12342,1,"〒"],[12343,2],[12344,1,"十"],[12345,1,"卄"],[12346,1,"卅"],[12347,2],[12348,2],[12349,2],[12350,2],[12351,2],[12352,3],[[12353,12436],2],[[12437,12438],2],[[12439,12440],3],[[12441,12442],2],[12443,5," ゙"],[12444,5," ゚"],[[12445,12446],2],[12447,1,"より"],[12448,2],[[12449,12542],2],[12543,1,"コト"],[[12544,12548],3],[[12549,12588],2],[12589,2],[12590,2],[12591,2],[12592,3],[12593,1,"ᄀ"],[12594,1,"ᄁ"],[12595,1,"ᆪ"],[12596,1,"ᄂ"],[12597,1,"ᆬ"],[12598,1,"ᆭ"],[12599,1,"ᄃ"],[12600,1,"ᄄ"],[12601,1,"ᄅ"],[12602,1,"ᆰ"],[12603,1,"ᆱ"],[12604,1,"ᆲ"],[12605,1,"ᆳ"],[12606,1,"ᆴ"],[12607,1,"ᆵ"],[12608,1,"ᄚ"],[12609,1,"ᄆ"],[12610,1,"ᄇ"],[12611,1,"ᄈ"],[12612,1,"ᄡ"],[12613,1,"ᄉ"],[12614,1,"ᄊ"],[12615,1,"ᄋ"],[12616,1,"ᄌ"],[12617,1,"ᄍ"],[12618,1,"ᄎ"],[12619,1,"ᄏ"],[12620,1,"ᄐ"],[12621,1,"ᄑ"],[12622,1,"ᄒ"],[12623,1,"ᅡ"],[12624,1,"ᅢ"],[12625,1,"ᅣ"],[12626,1,"ᅤ"],[12627,1,"ᅥ"],[12628,1,"ᅦ"],[12629,1,"ᅧ"],[12630,1,"ᅨ"],[12631,1,"ᅩ"],[12632,1,"ᅪ"],[12633,1,"ᅫ"],[12634,1,"ᅬ"],[12635,1,"ᅭ"],[12636,1,"ᅮ"],[12637,1,"ᅯ"],[12638,1,"ᅰ"],[12639,1,"ᅱ"],[12640,1,"ᅲ"],[12641,1,"ᅳ"],[12642,1,"ᅴ"],[12643,1,"ᅵ"],[12644,3],[12645,1,"ᄔ"],[12646,1,"ᄕ"],[12647,1,"ᇇ"],[12648,1,"ᇈ"],[12649,1,"ᇌ"],[12650,1,"ᇎ"],[12651,1,"ᇓ"],[12652,1,"ᇗ"],[12653,1,"ᇙ"],[12654,1,"ᄜ"],[12655,1,"ᇝ"],[12656,1,"ᇟ"],[12657,1,"ᄝ"],[12658,1,"ᄞ"],[12659,1,"ᄠ"],[12660,1,"ᄢ"],[12661,1,"ᄣ"],[12662,1,"ᄧ"],[12663,1,"ᄩ"],[12664,1,"ᄫ"],[12665,1,"ᄬ"],[12666,1,"ᄭ"],[12667,1,"ᄮ"],[12668,1,"ᄯ"],[12669,1,"ᄲ"],[12670,1,"ᄶ"],[12671,1,"ᅀ"],[12672,1,"ᅇ"],[12673,1,"ᅌ"],[12674,1,"ᇱ"],[12675,1,"ᇲ"],[12676,1,"ᅗ"],[12677,1,"ᅘ"],[12678,1,"ᅙ"],[12679,1,"ᆄ"],[12680,1,"ᆅ"],[12681,1,"ᆈ"],[12682,1,"ᆑ"],[12683,1,"ᆒ"],[12684,1,"ᆔ"],[12685,1,"ᆞ"],[12686,1,"ᆡ"],[12687,3],[[12688,12689],2],[12690,1,"一"],[12691,1,"二"],[12692,1,"三"],[12693,1,"四"],[12694,1,"上"],[12695,1,"中"],[12696,1,"下"],[12697,1,"甲"],[12698,1,"乙"],[12699,1,"丙"],[12700,1,"丁"],[12701,1,"天"],[12702,1,"地"],[12703,1,"人"],[[12704,12727],2],[[12728,12730],2],[[12731,12735],2],[[12736,12751],2],[[12752,12771],2],[[12772,12783],3],[[12784,12799],2],[12800,5,"(ᄀ)"],[12801,5,"(ᄂ)"],[12802,5,"(ᄃ)"],[12803,5,"(ᄅ)"],[12804,5,"(ᄆ)"],[12805,5,"(ᄇ)"],[12806,5,"(ᄉ)"],[12807,5,"(ᄋ)"],[12808,5,"(ᄌ)"],[12809,5,"(ᄎ)"],[12810,5,"(ᄏ)"],[12811,5,"(ᄐ)"],[12812,5,"(ᄑ)"],[12813,5,"(ᄒ)"],[12814,5,"(가)"],[12815,5,"(나)"],[12816,5,"(다)"],[12817,5,"(라)"],[12818,5,"(마)"],[12819,5,"(바)"],[12820,5,"(사)"],[12821,5,"(아)"],[12822,5,"(자)"],[12823,5,"(차)"],[12824,5,"(카)"],[12825,5,"(타)"],[12826,5,"(파)"],[12827,5,"(하)"],[12828,5,"(주)"],[12829,5,"(오전)"],[12830,5,"(오후)"],[12831,3],[12832,5,"(一)"],[12833,5,"(二)"],[12834,5,"(三)"],[12835,5,"(四)"],[12836,5,"(五)"],[12837,5,"(六)"],[12838,5,"(七)"],[12839,5,"(八)"],[12840,5,"(九)"],[12841,5,"(十)"],[12842,5,"(月)"],[12843,5,"(火)"],[12844,5,"(水)"],[12845,5,"(木)"],[12846,5,"(金)"],[12847,5,"(土)"],[12848,5,"(日)"],[12849,5,"(株)"],[12850,5,"(有)"],[12851,5,"(社)"],[12852,5,"(名)"],[12853,5,"(特)"],[12854,5,"(財)"],[12855,5,"(祝)"],[12856,5,"(労)"],[12857,5,"(代)"],[12858,5,"(呼)"],[12859,5,"(学)"],[12860,5,"(監)"],[12861,5,"(企)"],[12862,5,"(資)"],[12863,5,"(協)"],[12864,5,"(祭)"],[12865,5,"(休)"],[12866,5,"(自)"],[12867,5,"(至)"],[12868,1,"問"],[12869,1,"幼"],[12870,1,"文"],[12871,1,"箏"],[[12872,12879],2],[12880,1,"pte"],[12881,1,"21"],[12882,1,"22"],[12883,1,"23"],[12884,1,"24"],[12885,1,"25"],[12886,1,"26"],[12887,1,"27"],[12888,1,"28"],[12889,1,"29"],[12890,1,"30"],[12891,1,"31"],[12892,1,"32"],[12893,1,"33"],[12894,1,"34"],[12895,1,"35"],[12896,1,"ᄀ"],[12897,1,"ᄂ"],[12898,1,"ᄃ"],[12899,1,"ᄅ"],[12900,1,"ᄆ"],[12901,1,"ᄇ"],[12902,1,"ᄉ"],[12903,1,"ᄋ"],[12904,1,"ᄌ"],[12905,1,"ᄎ"],[12906,1,"ᄏ"],[12907,1,"ᄐ"],[12908,1,"ᄑ"],[12909,1,"ᄒ"],[12910,1,"가"],[12911,1,"나"],[12912,1,"다"],[12913,1,"라"],[12914,1,"마"],[12915,1,"바"],[12916,1,"사"],[12917,1,"아"],[12918,1,"자"],[12919,1,"차"],[12920,1,"카"],[12921,1,"타"],[12922,1,"파"],[12923,1,"하"],[12924,1,"참고"],[12925,1,"주의"],[12926,1,"우"],[12927,2],[12928,1,"一"],[12929,1,"二"],[12930,1,"三"],[12931,1,"四"],[12932,1,"五"],[12933,1,"六"],[12934,1,"七"],[12935,1,"八"],[12936,1,"九"],[12937,1,"十"],[12938,1,"月"],[12939,1,"火"],[12940,1,"水"],[12941,1,"木"],[12942,1,"金"],[12943,1,"土"],[12944,1,"日"],[12945,1,"株"],[12946,1,"有"],[12947,1,"社"],[12948,1,"名"],[12949,1,"特"],[12950,1,"財"],[12951,1,"祝"],[12952,1,"労"],[12953,1,"秘"],[12954,1,"男"],[12955,1,"女"],[12956,1,"適"],[12957,1,"優"],[12958,1,"印"],[12959,1,"注"],[12960,1,"項"],[12961,1,"休"],[12962,1,"写"],[12963,1,"正"],[12964,1,"上"],[12965,1,"中"],[12966,1,"下"],[12967,1,"左"],[12968,1,"右"],[12969,1,"医"],[12970,1,"宗"],[12971,1,"学"],[12972,1,"監"],[12973,1,"企"],[12974,1,"資"],[12975,1,"協"],[12976,1,"夜"],[12977,1,"36"],[12978,1,"37"],[12979,1,"38"],[12980,1,"39"],[12981,1,"40"],[12982,1,"41"],[12983,1,"42"],[12984,1,"43"],[12985,1,"44"],[12986,1,"45"],[12987,1,"46"],[12988,1,"47"],[12989,1,"48"],[12990,1,"49"],[12991,1,"50"],[12992,1,"1月"],[12993,1,"2月"],[12994,1,"3月"],[12995,1,"4月"],[12996,1,"5月"],[12997,1,"6月"],[12998,1,"7月"],[12999,1,"8月"],[13000,1,"9月"],[13001,1,"10月"],[13002,1,"11月"],[13003,1,"12月"],[13004,1,"hg"],[13005,1,"erg"],[13006,1,"ev"],[13007,1,"ltd"],[13008,1,"ア"],[13009,1,"イ"],[13010,1,"ウ"],[13011,1,"エ"],[13012,1,"オ"],[13013,1,"カ"],[13014,1,"キ"],[13015,1,"ク"],[13016,1,"ケ"],[13017,1,"コ"],[13018,1,"サ"],[13019,1,"シ"],[13020,1,"ス"],[13021,1,"セ"],[13022,1,"ソ"],[13023,1,"タ"],[13024,1,"チ"],[13025,1,"ツ"],[13026,1,"テ"],[13027,1,"ト"],[13028,1,"ナ"],[13029,1,"ニ"],[13030,1,"ヌ"],[13031,1,"ネ"],[13032,1,"ノ"],[13033,1,"ハ"],[13034,1,"ヒ"],[13035,1,"フ"],[13036,1,"ヘ"],[13037,1,"ホ"],[13038,1,"マ"],[13039,1,"ミ"],[13040,1,"ム"],[13041,1,"メ"],[13042,1,"モ"],[13043,1,"ヤ"],[13044,1,"ユ"],[13045,1,"ヨ"],[13046,1,"ラ"],[13047,1,"リ"],[13048,1,"ル"],[13049,1,"レ"],[13050,1,"ロ"],[13051,1,"ワ"],[13052,1,"ヰ"],[13053,1,"ヱ"],[13054,1,"ヲ"],[13055,1,"令和"],[13056,1,"アパート"],[13057,1,"アルファ"],[13058,1,"アンペア"],[13059,1,"アール"],[13060,1,"イニング"],[13061,1,"インチ"],[13062,1,"ウォン"],[13063,1,"エスクード"],[13064,1,"エーカー"],[13065,1,"オンス"],[13066,1,"オーム"],[13067,1,"カイリ"],[13068,1,"カラット"],[13069,1,"カロリー"],[13070,1,"ガロン"],[13071,1,"ガンマ"],[13072,1,"ギガ"],[13073,1,"ギニー"],[13074,1,"キュリー"],[13075,1,"ギルダー"],[13076,1,"キロ"],[13077,1,"キログラム"],[13078,1,"キロメートル"],[13079,1,"キロワット"],[13080,1,"グラム"],[13081,1,"グラムトン"],[13082,1,"クルゼイロ"],[13083,1,"クローネ"],[13084,1,"ケース"],[13085,1,"コルナ"],[13086,1,"コーポ"],[13087,1,"サイクル"],[13088,1,"サンチーム"],[13089,1,"シリング"],[13090,1,"センチ"],[13091,1,"セント"],[13092,1,"ダース"],[13093,1,"デシ"],[13094,1,"ドル"],[13095,1,"トン"],[13096,1,"ナノ"],[13097,1,"ノット"],[13098,1,"ハイツ"],[13099,1,"パーセント"],[13100,1,"パーツ"],[13101,1,"バーレル"],[13102,1,"ピアストル"],[13103,1,"ピクル"],[13104,1,"ピコ"],[13105,1,"ビル"],[13106,1,"ファラッド"],[13107,1,"フィート"],[13108,1,"ブッシェル"],[13109,1,"フラン"],[13110,1,"ヘクタール"],[13111,1,"ペソ"],[13112,1,"ペニヒ"],[13113,1,"ヘルツ"],[13114,1,"ペンス"],[13115,1,"ページ"],[13116,1,"ベータ"],[13117,1,"ポイント"],[13118,1,"ボルト"],[13119,1,"ホン"],[13120,1,"ポンド"],[13121,1,"ホール"],[13122,1,"ホーン"],[13123,1,"マイクロ"],[13124,1,"マイル"],[13125,1,"マッハ"],[13126,1,"マルク"],[13127,1,"マンション"],[13128,1,"ミクロン"],[13129,1,"ミリ"],[13130,1,"ミリバール"],[13131,1,"メガ"],[13132,1,"メガトン"],[13133,1,"メートル"],[13134,1,"ヤード"],[13135,1,"ヤール"],[13136,1,"ユアン"],[13137,1,"リットル"],[13138,1,"リラ"],[13139,1,"ルピー"],[13140,1,"ルーブル"],[13141,1,"レム"],[13142,1,"レントゲン"],[13143,1,"ワット"],[13144,1,"0点"],[13145,1,"1点"],[13146,1,"2点"],[13147,1,"3点"],[13148,1,"4点"],[13149,1,"5点"],[13150,1,"6点"],[13151,1,"7点"],[13152,1,"8点"],[13153,1,"9点"],[13154,1,"10点"],[13155,1,"11点"],[13156,1,"12点"],[13157,1,"13点"],[13158,1,"14点"],[13159,1,"15点"],[13160,1,"16点"],[13161,1,"17点"],[13162,1,"18点"],[13163,1,"19点"],[13164,1,"20点"],[13165,1,"21点"],[13166,1,"22点"],[13167,1,"23点"],[13168,1,"24点"],[13169,1,"hpa"],[13170,1,"da"],[13171,1,"au"],[13172,1,"bar"],[13173,1,"ov"],[13174,1,"pc"],[13175,1,"dm"],[13176,1,"dm2"],[13177,1,"dm3"],[13178,1,"iu"],[13179,1,"平成"],[13180,1,"昭和"],[13181,1,"大正"],[13182,1,"明治"],[13183,1,"株式会社"],[13184,1,"pa"],[13185,1,"na"],[13186,1,"μa"],[13187,1,"ma"],[13188,1,"ka"],[13189,1,"kb"],[13190,1,"mb"],[13191,1,"gb"],[13192,1,"cal"],[13193,1,"kcal"],[13194,1,"pf"],[13195,1,"nf"],[13196,1,"μf"],[13197,1,"μg"],[13198,1,"mg"],[13199,1,"kg"],[13200,1,"hz"],[13201,1,"khz"],[13202,1,"mhz"],[13203,1,"ghz"],[13204,1,"thz"],[13205,1,"μl"],[13206,1,"ml"],[13207,1,"dl"],[13208,1,"kl"],[13209,1,"fm"],[13210,1,"nm"],[13211,1,"μm"],[13212,1,"mm"],[13213,1,"cm"],[13214,1,"km"],[13215,1,"mm2"],[13216,1,"cm2"],[13217,1,"m2"],[13218,1,"km2"],[13219,1,"mm3"],[13220,1,"cm3"],[13221,1,"m3"],[13222,1,"km3"],[13223,1,"m∕s"],[13224,1,"m∕s2"],[13225,1,"pa"],[13226,1,"kpa"],[13227,1,"mpa"],[13228,1,"gpa"],[13229,1,"rad"],[13230,1,"rad∕s"],[13231,1,"rad∕s2"],[13232,1,"ps"],[13233,1,"ns"],[13234,1,"μs"],[13235,1,"ms"],[13236,1,"pv"],[13237,1,"nv"],[13238,1,"μv"],[13239,1,"mv"],[13240,1,"kv"],[13241,1,"mv"],[13242,1,"pw"],[13243,1,"nw"],[13244,1,"μw"],[13245,1,"mw"],[13246,1,"kw"],[13247,1,"mw"],[13248,1,"kω"],[13249,1,"mω"],[13250,3],[13251,1,"bq"],[13252,1,"cc"],[13253,1,"cd"],[13254,1,"c∕kg"],[13255,3],[13256,1,"db"],[13257,1,"gy"],[13258,1,"ha"],[13259,1,"hp"],[13260,1,"in"],[13261,1,"kk"],[13262,1,"km"],[13263,1,"kt"],[13264,1,"lm"],[13265,1,"ln"],[13266,1,"log"],[13267,1,"lx"],[13268,1,"mb"],[13269,1,"mil"],[13270,1,"mol"],[13271,1,"ph"],[13272,3],[13273,1,"ppm"],[13274,1,"pr"],[13275,1,"sr"],[13276,1,"sv"],[13277,1,"wb"],[13278,1,"v∕m"],[13279,1,"a∕m"],[13280,1,"1日"],[13281,1,"2日"],[13282,1,"3日"],[13283,1,"4日"],[13284,1,"5日"],[13285,1,"6日"],[13286,1,"7日"],[13287,1,"8日"],[13288,1,"9日"],[13289,1,"10日"],[13290,1,"11日"],[13291,1,"12日"],[13292,1,"13日"],[13293,1,"14日"],[13294,1,"15日"],[13295,1,"16日"],[13296,1,"17日"],[13297,1,"18日"],[13298,1,"19日"],[13299,1,"20日"],[13300,1,"21日"],[13301,1,"22日"],[13302,1,"23日"],[13303,1,"24日"],[13304,1,"25日"],[13305,1,"26日"],[13306,1,"27日"],[13307,1,"28日"],[13308,1,"29日"],[13309,1,"30日"],[13310,1,"31日"],[13311,1,"gal"],[[13312,19893],2],[[19894,19903],2],[[19904,19967],2],[[19968,40869],2],[[40870,40891],2],[[40892,40899],2],[[40900,40907],2],[40908,2],[[40909,40917],2],[[40918,40938],2],[[40939,40943],2],[[40944,40956],2],[[40957,40959],2],[[40960,42124],2],[[42125,42127],3],[[42128,42145],2],[[42146,42147],2],[[42148,42163],2],[42164,2],[[42165,42176],2],[42177,2],[[42178,42180],2],[42181,2],[42182,2],[[42183,42191],3],[[42192,42237],2],[[42238,42239],2],[[42240,42508],2],[[42509,42511],2],[[42512,42539],2],[[42540,42559],3],[42560,1,"ꙁ"],[42561,2],[42562,1,"ꙃ"],[42563,2],[42564,1,"ꙅ"],[42565,2],[42566,1,"ꙇ"],[42567,2],[42568,1,"ꙉ"],[42569,2],[42570,1,"ꙋ"],[42571,2],[42572,1,"ꙍ"],[42573,2],[42574,1,"ꙏ"],[42575,2],[42576,1,"ꙑ"],[42577,2],[42578,1,"ꙓ"],[42579,2],[42580,1,"ꙕ"],[42581,2],[42582,1,"ꙗ"],[42583,2],[42584,1,"ꙙ"],[42585,2],[42586,1,"ꙛ"],[42587,2],[42588,1,"ꙝ"],[42589,2],[42590,1,"ꙟ"],[42591,2],[42592,1,"ꙡ"],[42593,2],[42594,1,"ꙣ"],[42595,2],[42596,1,"ꙥ"],[42597,2],[42598,1,"ꙧ"],[42599,2],[42600,1,"ꙩ"],[42601,2],[42602,1,"ꙫ"],[42603,2],[42604,1,"ꙭ"],[[42605,42607],2],[[42608,42611],2],[[42612,42619],2],[[42620,42621],2],[42622,2],[42623,2],[42624,1,"ꚁ"],[42625,2],[42626,1,"ꚃ"],[42627,2],[42628,1,"ꚅ"],[42629,2],[42630,1,"ꚇ"],[42631,2],[42632,1,"ꚉ"],[42633,2],[42634,1,"ꚋ"],[42635,2],[42636,1,"ꚍ"],[42637,2],[42638,1,"ꚏ"],[42639,2],[42640,1,"ꚑ"],[42641,2],[42642,1,"ꚓ"],[42643,2],[42644,1,"ꚕ"],[42645,2],[42646,1,"ꚗ"],[42647,2],[42648,1,"ꚙ"],[42649,2],[42650,1,"ꚛ"],[42651,2],[42652,1,"ъ"],[42653,1,"ь"],[42654,2],[42655,2],[[42656,42725],2],[[42726,42735],2],[[42736,42737],2],[[42738,42743],2],[[42744,42751],3],[[42752,42774],2],[[42775,42778],2],[[42779,42783],2],[[42784,42785],2],[42786,1,"ꜣ"],[42787,2],[42788,1,"ꜥ"],[42789,2],[42790,1,"ꜧ"],[42791,2],[42792,1,"ꜩ"],[42793,2],[42794,1,"ꜫ"],[42795,2],[42796,1,"ꜭ"],[42797,2],[42798,1,"ꜯ"],[[42799,42801],2],[42802,1,"ꜳ"],[42803,2],[42804,1,"ꜵ"],[42805,2],[42806,1,"ꜷ"],[42807,2],[42808,1,"ꜹ"],[42809,2],[42810,1,"ꜻ"],[42811,2],[42812,1,"ꜽ"],[42813,2],[42814,1,"ꜿ"],[42815,2],[42816,1,"ꝁ"],[42817,2],[42818,1,"ꝃ"],[42819,2],[42820,1,"ꝅ"],[42821,2],[42822,1,"ꝇ"],[42823,2],[42824,1,"ꝉ"],[42825,2],[42826,1,"ꝋ"],[42827,2],[42828,1,"ꝍ"],[42829,2],[42830,1,"ꝏ"],[42831,2],[42832,1,"ꝑ"],[42833,2],[42834,1,"ꝓ"],[42835,2],[42836,1,"ꝕ"],[42837,2],[42838,1,"ꝗ"],[42839,2],[42840,1,"ꝙ"],[42841,2],[42842,1,"ꝛ"],[42843,2],[42844,1,"ꝝ"],[42845,2],[42846,1,"ꝟ"],[42847,2],[42848,1,"ꝡ"],[42849,2],[42850,1,"ꝣ"],[42851,2],[42852,1,"ꝥ"],[42853,2],[42854,1,"ꝧ"],[42855,2],[42856,1,"ꝩ"],[42857,2],[42858,1,"ꝫ"],[42859,2],[42860,1,"ꝭ"],[42861,2],[42862,1,"ꝯ"],[42863,2],[42864,1,"ꝯ"],[[42865,42872],2],[42873,1,"ꝺ"],[42874,2],[42875,1,"ꝼ"],[42876,2],[42877,1,"ᵹ"],[42878,1,"ꝿ"],[42879,2],[42880,1,"ꞁ"],[42881,2],[42882,1,"ꞃ"],[42883,2],[42884,1,"ꞅ"],[42885,2],[42886,1,"ꞇ"],[[42887,42888],2],[[42889,42890],2],[42891,1,"ꞌ"],[42892,2],[42893,1,"ɥ"],[42894,2],[42895,2],[42896,1,"ꞑ"],[42897,2],[42898,1,"ꞓ"],[42899,2],[[42900,42901],2],[42902,1,"ꞗ"],[42903,2],[42904,1,"ꞙ"],[42905,2],[42906,1,"ꞛ"],[42907,2],[42908,1,"ꞝ"],[42909,2],[42910,1,"ꞟ"],[42911,2],[42912,1,"ꞡ"],[42913,2],[42914,1,"ꞣ"],[42915,2],[42916,1,"ꞥ"],[42917,2],[42918,1,"ꞧ"],[42919,2],[42920,1,"ꞩ"],[42921,2],[42922,1,"ɦ"],[42923,1,"ɜ"],[42924,1,"ɡ"],[42925,1,"ɬ"],[42926,1,"ɪ"],[42927,2],[42928,1,"ʞ"],[42929,1,"ʇ"],[42930,1,"ʝ"],[42931,1,"ꭓ"],[42932,1,"ꞵ"],[42933,2],[42934,1,"ꞷ"],[42935,2],[42936,1,"ꞹ"],[42937,2],[42938,1,"ꞻ"],[42939,2],[42940,1,"ꞽ"],[42941,2],[42942,1,"ꞿ"],[42943,2],[42944,1,"ꟁ"],[42945,2],[42946,1,"ꟃ"],[42947,2],[42948,1,"ꞔ"],[42949,1,"ʂ"],[42950,1,"ᶎ"],[42951,1,"ꟈ"],[42952,2],[42953,1,"ꟊ"],[42954,2],[[42955,42959],3],[42960,1,"ꟑ"],[42961,2],[42962,3],[42963,2],[42964,3],[42965,2],[42966,1,"ꟗ"],[42967,2],[42968,1,"ꟙ"],[42969,2],[[42970,42993],3],[42994,1,"c"],[42995,1,"f"],[42996,1,"q"],[42997,1,"ꟶ"],[42998,2],[42999,2],[43000,1,"ħ"],[43001,1,"œ"],[43002,2],[[43003,43007],2],[[43008,43047],2],[[43048,43051],2],[43052,2],[[43053,43055],3],[[43056,43065],2],[[43066,43071],3],[[43072,43123],2],[[43124,43127],2],[[43128,43135],3],[[43136,43204],2],[43205,2],[[43206,43213],3],[[43214,43215],2],[[43216,43225],2],[[43226,43231],3],[[43232,43255],2],[[43256,43258],2],[43259,2],[43260,2],[43261,2],[[43262,43263],2],[[43264,43309],2],[[43310,43311],2],[[43312,43347],2],[[43348,43358],3],[43359,2],[[43360,43388],2],[[43389,43391],3],[[43392,43456],2],[[43457,43469],2],[43470,3],[[43471,43481],2],[[43482,43485],3],[[43486,43487],2],[[43488,43518],2],[43519,3],[[43520,43574],2],[[43575,43583],3],[[43584,43597],2],[[43598,43599],3],[[43600,43609],2],[[43610,43611],3],[[43612,43615],2],[[43616,43638],2],[[43639,43641],2],[[43642,43643],2],[[43644,43647],2],[[43648,43714],2],[[43715,43738],3],[[43739,43741],2],[[43742,43743],2],[[43744,43759],2],[[43760,43761],2],[[43762,43766],2],[[43767,43776],3],[[43777,43782],2],[[43783,43784],3],[[43785,43790],2],[[43791,43792],3],[[43793,43798],2],[[43799,43807],3],[[43808,43814],2],[43815,3],[[43816,43822],2],[43823,3],[[43824,43866],2],[43867,2],[43868,1,"ꜧ"],[43869,1,"ꬷ"],[43870,1,"ɫ"],[43871,1,"ꭒ"],[[43872,43875],2],[[43876,43877],2],[[43878,43879],2],[43880,2],[43881,1,"ʍ"],[[43882,43883],2],[[43884,43887],3],[43888,1,"Ꭰ"],[43889,1,"Ꭱ"],[43890,1,"Ꭲ"],[43891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Ꮷ"],[43960,1,"Ꮸ"],[43961,1,"Ꮹ"],[43962,1,"Ꮺ"],[43963,1,"Ꮻ"],[43964,1,"Ꮼ"],[43965,1,"Ꮽ"],[43966,1,"Ꮾ"],[43967,1,"Ꮿ"],[[43968,44010],2],[44011,2],[[44012,44013],2],[[44014,44015],3],[[44016,44025],2],[[44026,44031],3],[[44032,55203],2],[[55204,55215],3],[[55216,55238],2],[[55239,55242],3],[[55243,55291],2],[[55292,55295],3],[[55296,57343],3],[[57344,63743],3],[63744,1,"豈"],[63745,1,"更"],[63746,1,"車"],[63747,1,"賈"],[63748,1,"滑"],[63749,1,"串"],[63750,1,"句"],[[63751,63752],1,"龜"],[63753,1,"契"],[63754,1,"金"],[63755,1,"喇"],[63756,1,"奈"],[63757,1,"懶"],[63758,1,"癩"],[63759,1,"羅"],[63760,1,"蘿"],[63761,1,"螺"],[63762,1,"裸"],[63763,1,"邏"],[63764,1,"樂"],[63765,1,"洛"],[63766,1,"烙"],[63767,1,"珞"],[63768,1,"落"],[63769,1,"酪"],[63770,1,"駱"],[63771,1,"亂"],[63772,1,"卵"],[63773,1,"欄"],[63774,1,"爛"],[63775,1,"蘭"],[63776,1,"鸞"],[63777,1,"嵐"],[63778,1,"濫"],[63779,1,"藍"],[63780,1,"襤"],[63781,1,"拉"],[63782,1,"臘"],[63783,1,"蠟"],[63784,1,"廊"],[63785,1,"朗"],[63786,1,"浪"],[63787,1,"狼"],[63788,1,"郎"],[63789,1,"來"],[63790,1,"冷"],[63791,1,"勞"],[63792,1,"擄"],[63793,1,"櫓"],[63794,1,"爐"],[63795,1,"盧"],[63796,1,"老"],[63797,1,"蘆"],[63798,1,"虜"],[63799,1,"路"],[63800,1,"露"],[63801,1,"魯"],[63802,1,"鷺"],[63803,1,"碌"],[63804,1,"祿"],[63805,1,"綠"],[63806,1,"菉"],[63807,1,"錄"],[63808,1,"鹿"],[63809,1,"論"],[63810,1,"壟"],[63811,1,"弄"],[63812,1,"籠"],[63813,1,"聾"],[63814,1,"牢"],[63815,1,"磊"],[63816,1,"賂"],[63817,1,"雷"],[63818,1,"壘"],[63819,1,"屢"],[63820,1,"樓"],[63821,1,"淚"],[63822,1,"漏"],[63823,1,"累"],[63824,1,"縷"],[63825,1,"陋"],[63826,1,"勒"],[63827,1,"肋"],[63828,1,"凜"],[63829,1,"凌"],[63830,1,"稜"],[63831,1,"綾"],[63832,1,"菱"],[63833,1,"陵"],[63834,1,"讀"],[63835,1,"拏"],[63836,1,"樂"],[63837,1,"諾"],[63838,1,"丹"],[63839,1,"寧"],[63840,1,"怒"],[63841,1,"率"],[63842,1,"異"],[63843,1,"北"],[63844,1,"磻"],[63845,1,"便"],[63846,1,"復"],[63847,1,"不"],[63848,1,"泌"],[63849,1,"數"],[63850,1,"索"],[63851,1,"參"],[63852,1,"塞"],[63853,1,"省"],[63854,1,"葉"],[63855,1,"說"],[63856,1,"殺"],[63857,1,"辰"],[63858,1,"沈"],[63859,1,"拾"],[63860,1,"若"],[63861,1,"掠"],[63862,1,"略"],[63863,1,"亮"],[63864,1,"兩"],[63865,1,"凉"],[63866,1,"梁"],[63867,1,"糧"],[63868,1,"良"],[63869,1,"諒"],[63870,1,"量"],[63871,1,"勵"],[63872,1,"呂"],[63873,1,"女"],[63874,1,"廬"],[63875,1,"旅"],[63876,1,"濾"],[63877,1,"礪"],[63878,1,"閭"],[63879,1,"驪"],[63880,1,"麗"],[63881,1,"黎"],[63882,1,"力"],[63883,1,"曆"],[63884,1,"歷"],[63885,1,"轢"],[63886,1,"年"],[63887,1,"憐"],[63888,1,"戀"],[63889,1,"撚"],[63890,1,"漣"],[63891,1,"煉"],[63892,1,"璉"],[63893,1,"秊"],[63894,1,"練"],[63895,1,"聯"],[63896,1,"輦"],[63897,1,"蓮"],[63898,1,"連"],[63899,1,"鍊"],[63900,1,"列"],[63901,1,"劣"],[63902,1,"咽"],[63903,1,"烈"],[63904,1,"裂"],[63905,1,"說"],[63906,1,"廉"],[63907,1,"念"],[63908,1,"捻"],[63909,1,"殮"],[63910,1,"簾"],[63911,1,"獵"],[63912,1,"令"],[63913,1,"囹"],[63914,1,"寧"],[63915,1,"嶺"],[63916,1,"怜"],[63917,1,"玲"],[63918,1,"瑩"],[63919,1,"羚"],[63920,1,"聆"],[63921,1,"鈴"],[63922,1,"零"],[63923,1,"靈"],[63924,1,"領"],[63925,1,"例"],[63926,1,"禮"],[63927,1,"醴"],[63928,1,"隸"],[63929,1,"惡"],[63930,1,"了"],[63931,1,"僚"],[63932,1,"寮"],[63933,1,"尿"],[63934,1,"料"],[63935,1,"樂"],[63936,1,"燎"],[63937,1,"療"],[63938,1,"蓼"],[63939,1,"遼"],[63940,1,"龍"],[63941,1,"暈"],[63942,1,"阮"],[63943,1,"劉"],[63944,1,"杻"],[63945,1,"柳"],[63946,1,"流"],[63947,1,"溜"],[63948,1,"琉"],[63949,1,"留"],[63950,1,"硫"],[63951,1,"紐"],[63952,1,"類"],[63953,1,"六"],[63954,1,"戮"],[63955,1,"陸"],[63956,1,"倫"],[63957,1,"崙"],[63958,1,"淪"],[63959,1,"輪"],[63960,1,"律"],[63961,1,"慄"],[63962,1,"栗"],[63963,1,"率"],[63964,1,"隆"],[63965,1,"利"],[63966,1,"吏"],[63967,1,"履"],[63968,1,"易"],[63969,1,"李"],[63970,1,"梨"],[63971,1,"泥"],[63972,1,"理"],[63973,1,"痢"],[63974,1,"罹"],[63975,1,"裏"],[63976,1,"裡"],[63977,1,"里"],[63978,1,"離"],[63979,1,"匿"],[63980,1,"溺"],[63981,1,"吝"],[63982,1,"燐"],[63983,1,"璘"],[63984,1,"藺"],[63985,1,"隣"],[63986,1,"鱗"],[63987,1,"麟"],[63988,1,"林"],[63989,1,"淋"],[63990,1,"臨"],[63991,1,"立"],[63992,1,"笠"],[63993,1,"粒"],[63994,1,"狀"],[63995,1,"炙"],[63996,1,"識"],[63997,1,"什"],[63998,1,"茶"],[63999,1,"刺"],[64000,1,"切"],[64001,1,"度"],[64002,1,"拓"],[64003,1,"糖"],[64004,1,"宅"],[64005,1,"洞"],[64006,1,"暴"],[64007,1,"輻"],[64008,1,"行"],[64009,1,"降"],[64010,1,"見"],[64011,1,"廓"],[64012,1,"兀"],[64013,1,"嗀"],[[64014,64015],2],[64016,1,"塚"],[64017,2],[64018,1,"晴"],[[64019,64020],2],[64021,1,"凞"],[64022,1,"猪"],[64023,1,"益"],[64024,1,"礼"],[64025,1,"神"],[64026,1,"祥"],[64027,1,"福"],[64028,1,"靖"],[64029,1,"精"],[64030,1,"羽"],[64031,2],[64032,1,"蘒"],[64033,2],[64034,1,"諸"],[[64035,64036],2],[64037,1,"逸"],[64038,1,"都"],[[64039,64041],2],[64042,1,"飯"],[64043,1,"飼"],[64044,1,"館"],[64045,1,"鶴"],[64046,1,"郞"],[64047,1,"隷"],[64048,1,"侮"],[64049,1,"僧"],[64050,1,"免"],[64051,1,"勉"],[64052,1,"勤"],[64053,1,"卑"],[64054,1,"喝"],[64055,1,"嘆"],[64056,1,"器"],[64057,1,"塀"],[64058,1,"墨"],[64059,1,"層"],[64060,1,"屮"],[64061,1,"悔"],[64062,1,"慨"],[64063,1,"憎"],[64064,1,"懲"],[64065,1,"敏"],[64066,1,"既"],[64067,1,"暑"],[64068,1,"梅"],[64069,1,"海"],[64070,1,"渚"],[64071,1,"漢"],[64072,1,"煮"],[64073,1,"爫"],[64074,1,"琢"],[64075,1,"碑"],[64076,1,"社"],[64077,1,"祉"],[64078,1,"祈"],[64079,1,"祐"],[64080,1,"祖"],[64081,1,"祝"],[64082,1,"禍"],[64083,1,"禎"],[64084,1,"穀"],[64085,1,"突"],[64086,1,"節"],[64087,1,"練"],[64088,1,"縉"],[64089,1,"繁"],[64090,1,"署"],[64091,1,"者"],[64092,1,"臭"],[[64093,64094],1,"艹"],[64095,1,"著"],[64096,1,"褐"],[64097,1,"視"],[64098,1,"謁"],[64099,1,"謹"],[64100,1,"賓"],[64101,1,"贈"],[64102,1,"辶"],[64103,1,"逸"],[64104,1,"難"],[64105,1,"響"],[64106,1,"頻"],[64107,1,"恵"],[64108,1,"𤋮"],[64109,1,"舘"],[[64110,64111],3],[64112,1,"並"],[64113,1,"况"],[64114,1,"全"],[64115,1,"侀"],[64116,1,"充"],[64117,1,"冀"],[64118,1,"勇"],[64119,1,"勺"],[64120,1,"喝"],[64121,1,"啕"],[64122,1,"喙"],[64123,1,"嗢"],[64124,1,"塚"],[64125,1,"墳"],[64126,1,"奄"],[64127,1,"奔"],[64128,1,"婢"],[64129,1,"嬨"],[64130,1,"廒"],[64131,1,"廙"],[64132,1,"彩"],[64133,1,"徭"],[64134,1,"惘"],[64135,1,"慎"],[64136,1,"愈"],[64137,1,"憎"],[64138,1,"慠"],[64139,1,"懲"],[64140,1,"戴"],[64141,1,"揄"],[64142,1,"搜"],[64143,1,"摒"],[64144,1,"敖"],[64145,1,"晴"],[64146,1,"朗"],[64147,1,"望"],[64148,1,"杖"],[64149,1,"歹"],[64150,1,"殺"],[64151,1,"流"],[64152,1,"滛"],[64153,1,"滋"],[64154,1,"漢"],[64155,1,"瀞"],[64156,1,"煮"],[64157,1,"瞧"],[64158,1,"爵"],[64159,1,"犯"],[64160,1,"猪"],[64161,1,"瑱"],[64162,1,"甆"],[64163,1,"画"],[64164,1,"瘝"],[64165,1,"瘟"],[64166,1,"益"],[64167,1,"盛"],[64168,1,"直"],[64169,1,"睊"],[64170,1,"着"],[64171,1,"磌"],[64172,1,"窱"],[64173,1,"節"],[64174,1,"类"],[64175,1,"絛"],[64176,1,"練"],[64177,1,"缾"],[64178,1,"者"],[64179,1,"荒"],[64180,1,"華"],[64181,1,"蝹"],[64182,1,"襁"],[64183,1,"覆"],[64184,1,"視"],[64185,1,"調"],[64186,1,"諸"],[64187,1,"請"],[64188,1,"謁"],[64189,1,"諾"],[64190,1,"諭"],[64191,1,"謹"],[64192,1,"變"],[64193,1,"贈"],[64194,1,"輸"],[64195,1,"遲"],[64196,1,"醙"],[64197,1,"鉶"],[64198,1,"陼"],[64199,1,"難"],[64200,1,"靖"],[64201,1,"韛"],[64202,1,"響"],[64203,1,"頋"],[64204,1,"頻"],[64205,1,"鬒"],[64206,1,"龜"],[64207,1,"𢡊"],[64208,1,"𢡄"],[64209,1,"𣏕"],[64210,1,"㮝"],[64211,1,"䀘"],[64212,1,"䀹"],[64213,1,"𥉉"],[64214,1,"𥳐"],[64215,1,"𧻓"],[64216,1,"齃"],[64217,1,"龎"],[[64218,64255],3],[64256,1,"ff"],[64257,1,"fi"],[64258,1,"fl"],[64259,1,"ffi"],[64260,1,"ffl"],[[64261,64262],1,"st"],[[64263,64274],3],[64275,1,"մն"],[64276,1,"մե"],[64277,1,"մի"],[64278,1,"վն"],[64279,1,"մխ"],[[64280,64284],3],[64285,1,"יִ"],[64286,2],[64287,1,"ײַ"],[64288,1,"ע"],[64289,1,"א"],[64290,1,"ד"],[64291,1,"ה"],[64292,1,"כ"],[64293,1,"ל"],[64294,1,"ם"],[64295,1,"ר"],[64296,1,"ת"],[64297,5,"+"],[64298,1,"שׁ"],[64299,1,"שׂ"],[64300,1,"שּׁ"],[64301,1,"שּׂ"],[64302,1,"אַ"],[64303,1,"אָ"],[64304,1,"אּ"],[64305,1,"בּ"],[64306,1,"גּ"],[64307,1,"דּ"],[64308,1,"הּ"],[64309,1,"וּ"],[64310,1,"זּ"],[64311,3],[64312,1,"טּ"],[64313,1,"יּ"],[64314,1,"ךּ"],[64315,1,"כּ"],[64316,1,"לּ"],[64317,3],[64318,1,"מּ"],[64319,3],[64320,1,"נּ"],[64321,1,"סּ"],[64322,3],[64323,1,"ףּ"],[64324,1,"פּ"],[64325,3],[64326,1,"צּ"],[64327,1,"קּ"],[64328,1,"רּ"],[64329,1,"שּ"],[64330,1,"תּ"],[64331,1,"וֹ"],[64332,1,"בֿ"],[64333,1,"כֿ"],[64334,1,"פֿ"],[64335,1,"אל"],[[64336,64337],1,"ٱ"],[[64338,64341],1,"ٻ"],[[64342,64345],1,"پ"],[[64346,64349],1,"ڀ"],[[64350,64353],1,"ٺ"],[[64354,64357],1,"ٿ"],[[64358,64361],1,"ٹ"],[[64362,64365],1,"ڤ"],[[64366,64369],1,"ڦ"],[[64370,64373],1,"ڄ"],[[64374,64377],1,"ڃ"],[[64378,64381],1,"چ"],[[64382,64385],1,"ڇ"],[[64386,64387],1,"ڍ"],[[64388,64389],1,"ڌ"],[[64390,64391],1,"ڎ"],[[64392,64393],1,"ڈ"],[[64394,64395],1,"ژ"],[[64396,64397],1,"ڑ"],[[64398,64401],1,"ک"],[[64402,64405],1,"گ"],[[64406,64409],1,"ڳ"],[[64410,64413],1,"ڱ"],[[64414,64415],1,"ں"],[[64416,64419],1,"ڻ"],[[64420,64421],1,"ۀ"],[[64422,64425],1,"ہ"],[[64426,64429],1,"ھ"],[[64430,64431],1,"ے"],[[64432,64433],1,"ۓ"],[[64434,64449],2],[64450,2],[[64451,64466],3],[[64467,64470],1,"ڭ"],[[64471,64472],1,"ۇ"],[[64473,64474],1,"ۆ"],[[64475,64476],1,"ۈ"],[64477,1,"ۇٴ"],[[64478,64479],1,"ۋ"],[[64480,64481],1,"ۅ"],[[64482,64483],1,"ۉ"],[[64484,64487],1,"ې"],[[64488,64489],1,"ى"],[[64490,64491],1,"ئا"],[[64492,64493],1,"ئە"],[[64494,64495],1,"ئو"],[[64496,64497],1,"ئۇ"],[[64498,64499],1,"ئۆ"],[[64500,64501],1,"ئۈ"],[[64502,64504],1,"ئې"],[[64505,64507],1,"ئى"],[[64508,64511],1,"ی"],[64512,1,"ئج"],[64513,1,"ئح"],[64514,1,"ئم"],[64515,1,"ئى"],[64516,1,"ئي"],[64517,1,"بج"],[64518,1,"بح"],[64519,1,"بخ"],[64520,1,"بم"],[64521,1,"بى"],[64522,1,"بي"],[64523,1,"تج"],[64524,1,"تح"],[64525,1,"تخ"],[64526,1,"تم"],[64527,1,"تى"],[64528,1,"تي"],[64529,1,"ثج"],[64530,1,"ثم"],[64531,1,"ثى"],[64532,1,"ثي"],[64533,1,"جح"],[64534,1,"جم"],[64535,1,"حج"],[64536,1,"حم"],[64537,1,"خج"],[64538,1,"خح"],[64539,1,"خم"],[64540,1,"سج"],[64541,1,"سح"],[64542,1,"سخ"],[64543,1,"سم"],[64544,1,"صح"],[64545,1,"صم"],[64546,1,"ضج"],[64547,1,"ضح"],[64548,1,"ضخ"],[64549,1,"ضم"],[64550,1,"طح"],[64551,1,"طم"],[64552,1,"ظم"],[64553,1,"عج"],[64554,1,"عم"],[64555,1,"غج"],[64556,1,"غم"],[64557,1,"فج"],[64558,1,"فح"],[64559,1,"فخ"],[64560,1,"فم"],[64561,1,"فى"],[64562,1,"في"],[64563,1,"قح"],[64564,1,"قم"],[64565,1,"قى"],[64566,1,"قي"],[64567,1,"كا"],[64568,1,"كج"],[64569,1,"كح"],[64570,1,"كخ"],[64571,1,"كل"],[64572,1,"كم"],[64573,1,"كى"],[64574,1,"كي"],[64575,1,"لج"],[64576,1,"لح"],[64577,1,"لخ"],[64578,1,"لم"],[64579,1,"لى"],[64580,1,"لي"],[64581,1,"مج"],[64582,1,"مح"],[64583,1,"مخ"],[64584,1,"مم"],[64585,1,"مى"],[64586,1,"مي"],[64587,1,"نج"],[64588,1,"نح"],[64589,1,"نخ"],[64590,1,"نم"],[64591,1,"نى"],[64592,1,"ني"],[64593,1,"هج"],[64594,1,"هم"],[64595,1,"هى"],[64596,1,"هي"],[64597,1,"يج"],[64598,1,"يح"],[64599,1,"يخ"],[64600,1,"يم"],[64601,1,"يى"],[64602,1,"يي"],[64603,1,"ذٰ"],[64604,1,"رٰ"],[64605,1,"ىٰ"],[64606,5," ٌّ"],[64607,5," ٍّ"],[64608,5," َّ"],[64609,5," ُّ"],[64610,5," ِّ"],[64611,5," ّٰ"],[64612,1,"ئر"],[64613,1,"ئز"],[64614,1,"ئم"],[64615,1,"ئن"],[64616,1,"ئى"],[64617,1,"ئي"],[64618,1,"بر"],[64619,1,"بز"],[64620,1,"بم"],[64621,1,"بن"],[64622,1,"بى"],[64623,1,"بي"],[64624,1,"تر"],[64625,1,"تز"],[64626,1,"تم"],[64627,1,"تن"],[64628,1,"تى"],[64629,1,"تي"],[64630,1,"ثر"],[64631,1,"ثز"],[64632,1,"ثم"],[64633,1,"ثن"],[64634,1,"ثى"],[64635,1,"ثي"],[64636,1,"فى"],[64637,1,"في"],[64638,1,"قى"],[64639,1,"قي"],[64640,1,"كا"],[64641,1,"كل"],[64642,1,"كم"],[64643,1,"كى"],[64644,1,"كي"],[64645,1,"لم"],[64646,1,"لى"],[64647,1,"لي"],[64648,1,"ما"],[64649,1,"مم"],[64650,1,"نر"],[64651,1,"نز"],[64652,1,"نم"],[64653,1,"نن"],[64654,1,"نى"],[64655,1,"ني"],[64656,1,"ىٰ"],[64657,1,"ير"],[64658,1,"يز"],[64659,1,"يم"],[64660,1,"ين"],[64661,1,"يى"],[64662,1,"يي"],[64663,1,"ئج"],[64664,1,"ئح"],[64665,1,"ئخ"],[64666,1,"ئم"],[64667,1,"ئه"],[64668,1,"بج"],[64669,1,"بح"],[64670,1,"بخ"],[64671,1,"بم"],[64672,1,"به"],[64673,1,"تج"],[64674,1,"تح"],[64675,1,"تخ"],[64676,1,"تم"],[64677,1,"ته"],[64678,1,"ثم"],[64679,1,"جح"],[64680,1,"جم"],[64681,1,"حج"],[64682,1,"حم"],[64683,1,"خج"],[64684,1,"خم"],[64685,1,"سج"],[64686,1,"سح"],[64687,1,"سخ"],[64688,1,"سم"],[64689,1,"صح"],[64690,1,"صخ"],[64691,1,"صم"],[64692,1,"ضج"],[64693,1,"ضح"],[64694,1,"ضخ"],[64695,1,"ضم"],[64696,1,"طح"],[64697,1,"ظم"],[64698,1,"عج"],[64699,1,"عم"],[64700,1,"غج"],[64701,1,"غم"],[64702,1,"فج"],[64703,1,"فح"],[64704,1,"فخ"],[64705,1,"فم"],[64706,1,"قح"],[64707,1,"قم"],[64708,1,"كج"],[64709,1,"كح"],[64710,1,"كخ"],[64711,1,"كل"],[64712,1,"كم"],[64713,1,"لج"],[64714,1,"لح"],[64715,1,"لخ"],[64716,1,"لم"],[64717,1,"له"],[64718,1,"مج"],[64719,1,"مح"],[64720,1,"مخ"],[64721,1,"مم"],[64722,1,"نج"],[64723,1,"نح"],[64724,1,"نخ"],[64725,1,"نم"],[64726,1,"نه"],[64727,1,"هج"],[64728,1,"هم"],[64729,1,"هٰ"],[64730,1,"يج"],[64731,1,"يح"],[64732,1,"يخ"],[64733,1,"يم"],[64734,1,"يه"],[64735,1,"ئم"],[64736,1,"ئه"],[64737,1,"بم"],[64738,1,"به"],[64739,1,"تم"],[64740,1,"ته"],[64741,1,"ثم"],[64742,1,"ثه"],[64743,1,"سم"],[64744,1,"سه"],[64745,1,"شم"],[64746,1,"شه"],[64747,1,"كل"],[64748,1,"كم"],[64749,1,"لم"],[64750,1,"نم"],[64751,1,"نه"],[64752,1,"يم"],[64753,1,"يه"],[64754,1,"ـَّ"],[64755,1,"ـُّ"],[64756,1,"ـِّ"],[64757,1,"طى"],[64758,1,"طي"],[64759,1,"عى"],[64760,1,"عي"],[64761,1,"غى"],[64762,1,"غي"],[64763,1,"سى"],[64764,1,"سي"],[64765,1,"شى"],[64766,1,"شي"],[64767,1,"حى"],[64768,1,"حي"],[64769,1,"جى"],[64770,1,"جي"],[64771,1,"خى"],[64772,1,"خي"],[64773,1,"صى"],[64774,1,"صي"],[64775,1,"ضى"],[64776,1,"ضي"],[64777,1,"شج"],[64778,1,"شح"],[64779,1,"شخ"],[64780,1,"شم"],[64781,1,"شر"],[64782,1,"سر"],[64783,1,"صر"],[64784,1,"ضر"],[64785,1,"طى"],[64786,1,"طي"],[64787,1,"عى"],[64788,1,"عي"],[64789,1,"غى"],[64790,1,"غي"],[64791,1,"سى"],[64792,1,"سي"],[64793,1,"شى"],[64794,1,"شي"],[64795,1,"حى"],[64796,1,"حي"],[64797,1,"جى"],[64798,1,"جي"],[64799,1,"خى"],[64800,1,"خي"],[64801,1,"صى"],[64802,1,"صي"],[64803,1,"ضى"],[64804,1,"ضي"],[64805,1,"شج"],[64806,1,"شح"],[64807,1,"شخ"],[64808,1,"شم"],[64809,1,"شر"],[64810,1,"سر"],[64811,1,"صر"],[64812,1,"ضر"],[64813,1,"شج"],[64814,1,"شح"],[64815,1,"شخ"],[64816,1,"شم"],[64817,1,"سه"],[64818,1,"شه"],[64819,1,"طم"],[64820,1,"سج"],[64821,1,"سح"],[64822,1,"سخ"],[64823,1,"شج"],[64824,1,"شح"],[64825,1,"شخ"],[64826,1,"طم"],[64827,1,"ظم"],[[64828,64829],1,"اً"],[[64830,64831],2],[[64832,64847],2],[64848,1,"تجم"],[[64849,64850],1,"تحج"],[64851,1,"تحم"],[64852,1,"تخم"],[64853,1,"تمج"],[64854,1,"تمح"],[64855,1,"تمخ"],[[64856,64857],1,"جمح"],[64858,1,"حمي"],[64859,1,"حمى"],[64860,1,"سحج"],[64861,1,"سجح"],[64862,1,"سجى"],[[64863,64864],1,"سمح"],[64865,1,"سمج"],[[64866,64867],1,"سمم"],[[64868,64869],1,"صحح"],[64870,1,"صمم"],[[64871,64872],1,"شحم"],[64873,1,"شجي"],[[64874,64875],1,"شمخ"],[[64876,64877],1,"شمم"],[64878,1,"ضحى"],[[64879,64880],1,"ضخم"],[[64881,64882],1,"طمح"],[64883,1,"طمم"],[64884,1,"طمي"],[64885,1,"عجم"],[[64886,64887],1,"عمم"],[64888,1,"عمى"],[64889,1,"غمم"],[64890,1,"غمي"],[64891,1,"غمى"],[[64892,64893],1,"فخم"],[64894,1,"قمح"],[64895,1,"قمم"],[64896,1,"لحم"],[64897,1,"لحي"],[64898,1,"لحى"],[[64899,64900],1,"لجج"],[[64901,64902],1,"لخم"],[[64903,64904],1,"لمح"],[64905,1,"محج"],[64906,1,"محم"],[64907,1,"محي"],[64908,1,"مجح"],[64909,1,"مجم"],[64910,1,"مخج"],[64911,1,"مخم"],[[64912,64913],3],[64914,1,"مجخ"],[64915,1,"همج"],[64916,1,"همم"],[64917,1,"نحم"],[64918,1,"نحى"],[[64919,64920],1,"نجم"],[64921,1,"نجى"],[64922,1,"نمي"],[64923,1,"نمى"],[[64924,64925],1,"يمم"],[64926,1,"بخي"],[64927,1,"تجي"],[64928,1,"تجى"],[64929,1,"تخي"],[64930,1,"تخى"],[64931,1,"تمي"],[64932,1,"تمى"],[64933,1,"جمي"],[64934,1,"جحى"],[64935,1,"جمى"],[64936,1,"سخى"],[64937,1,"صحي"],[64938,1,"شحي"],[64939,1,"ضحي"],[64940,1,"لجي"],[64941,1,"لمي"],[64942,1,"يحي"],[64943,1,"يجي"],[64944,1,"يمي"],[64945,1,"ممي"],[64946,1,"قمي"],[64947,1,"نحي"],[64948,1,"قمح"],[64949,1,"لحم"],[64950,1,"عمي"],[64951,1,"كمي"],[64952,1,"نجح"],[64953,1,"مخي"],[64954,1,"لجم"],[64955,1,"كمم"],[64956,1,"لجم"],[64957,1,"نجح"],[64958,1,"جحي"],[64959,1,"حجي"],[64960,1,"مجي"],[64961,1,"فمي"],[64962,1,"بحي"],[64963,1,"كمم"],[64964,1,"عجم"],[64965,1,"صمم"],[64966,1,"سخي"],[64967,1,"نجي"],[[64968,64974],3],[64975,2],[[64976,65007],3],[65008,1,"صلے"],[65009,1,"قلے"],[65010,1,"الله"],[65011,1,"اكبر"],[65012,1,"محمد"],[65013,1,"صلعم"],[65014,1,"رسول"],[65015,1,"عليه"],[65016,1,"وسلم"],[65017,1,"صلى"],[65018,5,"صلى الله عليه وسلم"],[65019,5,"جل جلاله"],[65020,1,"ریال"],[65021,2],[[65022,65023],2],[[65024,65039],7],[65040,5,","],[65041,1,"、"],[65042,3],[65043,5,":"],[65044,5,";"],[65045,5,"!"],[65046,5,"?"],[65047,1,"〖"],[65048,1,"〗"],[65049,3],[[65050,65055],3],[[65056,65059],2],[[65060,65062],2],[[65063,65069],2],[[65070,65071],2],[65072,3],[65073,1,"—"],[65074,1,"–"],[[65075,65076],5,"_"],[65077,5,"("],[65078,5,")"],[65079,5,"{"],[65080,5,"}"],[65081,1,"〔"],[65082,1,"〕"],[65083,1,"【"],[65084,1,"】"],[65085,1,"《"],[65086,1,"》"],[65087,1,"〈"],[65088,1,"〉"],[65089,1,"「"],[65090,1,"」"],[65091,1,"『"],[65092,1,"』"],[[65093,65094],2],[65095,5,"["],[65096,5,"]"],[[65097,65100],5," ̅"],[[65101,65103],5,"_"],[65104,5,","],[65105,1,"、"],[65106,3],[65107,3],[65108,5,";"],[65109,5,":"],[65110,5,"?"],[65111,5,"!"],[65112,1,"—"],[65113,5,"("],[65114,5,")"],[65115,5,"{"],[65116,5,"}"],[65117,1,"〔"],[65118,1,"〕"],[65119,5,"#"],[65120,5,"&"],[65121,5,"*"],[65122,5,"+"],[65123,1,"-"],[65124,5,"<"],[65125,5,">"],[65126,5,"="],[65127,3],[65128,5,"\\"],[65129,5,"$"],[65130,5,"%"],[65131,5,"@"],[[65132,65135],3],[65136,5," ً"],[65137,1,"ـً"],[65138,5," ٌ"],[65139,2],[65140,5," ٍ"],[65141,3],[65142,5," َ"],[65143,1,"ـَ"],[65144,5," ُ"],[65145,1,"ـُ"],[65146,5," ِ"],[65147,1,"ـِ"],[65148,5," ّ"],[65149,1,"ـّ"],[65150,5," ْ"],[65151,1,"ـْ"],[65152,1,"ء"],[[65153,65154],1,"آ"],[[65155,65156],1,"أ"],[[65157,65158],1,"ؤ"],[[65159,65160],1,"إ"],[[65161,65164],1,"ئ"],[[65165,65166],1,"ا"],[[65167,65170],1,"ب"],[[65171,65172],1,"ة"],[[65173,65176],1,"ت"],[[65177,65180],1,"ث"],[[65181,65184],1,"ج"],[[65185,65188],1,"ح"],[[65189,65192],1,"خ"],[[65193,65194],1,"د"],[[65195,65196],1,"ذ"],[[65197,65198],1,"ر"],[[65199,65200],1,"ز"],[[65201,65204],1,"س"],[[65205,65208],1,"ش"],[[65209,65212],1,"ص"],[[65213,65216],1,"ض"],[[65217,65220],1,"ط"],[[65221,65224],1,"ظ"],[[65225,65228],1,"ع"],[[65229,65232],1,"غ"],[[65233,65236],1,"ف"],[[65237,65240],1,"ق"],[[65241,65244],1,"ك"],[[65245,65248],1,"ل"],[[65249,65252],1,"م"],[[65253,65256],1,"ن"],[[65257,65260],1,"ه"],[[65261,65262],1,"و"],[[65263,65264],1,"ى"],[[65265,65268],1,"ي"],[[65269,65270],1,"لآ"],[[65271,65272],1,"لأ"],[[65273,65274],1,"لإ"],[[65275,65276],1,"لا"],[[65277,65278],3],[65279,7],[65280,3],[65281,5,"!"],[65282,5,"\""],[65283,5,"#"],[65284,5,"$"],[65285,5,"%"],[65286,5,"&"],[65287,5,"'"],[65288,5,"("],[65289,5,")"],[65290,5,"*"],[65291,5,"+"],[65292,5,","],[65293,1,"-"],[65294,1,"."],[65295,5,"/"],[65296,1,"0"],[65297,1,"1"],[65298,1,"2"],[65299,1,"3"],[65300,1,"4"],[65301,1,"5"],[65302,1,"6"],[65303,1,"7"],[65304,1,"8"],[65305,1,"9"],[65306,5,":"],[65307,5,";"],[65308,5,"<"],[65309,5,"="],[65310,5,">"],[65311,5,"?"],[65312,5,"@"],[65313,1,"a"],[65314,1,"b"],[65315,1,"c"],[65316,1,"d"],[65317,1,"e"],[65318,1,"f"],[65319,1,"g"],[65320,1,"h"],[65321,1,"i"],[65322,1,"j"],[65323,1,"k"],[65324,1,"l"],[65325,1,"m"],[65326,1,"n"],[65327,1,"o"],[65328,1,"p"],[65329,1,"q"],[65330,1,"r"],[65331,1,"s"],[65332,1,"t"],[65333,1,"u"],[65334,1,"v"],[65335,1,"w"],[65336,1,"x"],[65337,1,"y"],[65338,1,"z"],[65339,5,"["],[65340,5,"\\"],[65341,5,"]"],[65342,5,"^"],[65343,5,"_"],[65344,5,"`"],[65345,1,"a"],[65346,1,"b"],[65347,1,"c"],[65348,1,"d"],[65349,1,"e"],[65350,1,"f"],[65351,1,"g"],[65352,1,"h"],[65353,1,"i"],[65354,1,"j"],[65355,1,"k"],[65356,1,"l"],[65357,1,"m"],[65358,1,"n"],[65359,1,"o"],[65360,1,"p"],[65361,1,"q"],[65362,1,"r"],[65363,1,"s"],[65364,1,"t"],[65365,1,"u"],[65366,1,"v"],[65367,1,"w"],[65368,1,"x"],[65369,1,"y"],[65370,1,"z"],[65371,5,"{"],[65372,5,"|"],[65373,5,"}"],[65374,5,"~"],[65375,1,"⦅"],[65376,1,"⦆"],[65377,1,"."],[65378,1,"「"],[65379,1,"」"],[65380,1,"、"],[65381,1,"・"],[65382,1,"ヲ"],[65383,1,"ァ"],[65384,1,"ィ"],[65385,1,"ゥ"],[65386,1,"ェ"],[65387,1,"ォ"],[65388,1,"ャ"],[65389,1,"ュ"],[65390,1,"ョ"],[65391,1,"ッ"],[65392,1,"ー"],[65393,1,"ア"],[65394,1,"イ"],[65395,1,"ウ"],[65396,1,"エ"],[65397,1,"オ"],[65398,1,"カ"],[65399,1,"キ"],[65400,1,"ク"],[65401,1,"ケ"],[65402,1,"コ"],[65403,1,"サ"],[65404,1,"シ"],[65405,1,"ス"],[65406,1,"セ"],[65407,1,"ソ"],[65408,1,"タ"],[65409,1,"チ"],[65410,1,"ツ"],[65411,1,"テ"],[65412,1,"ト"],[65413,1,"ナ"],[65414,1,"ニ"],[65415,1,"ヌ"],[65416,1,"ネ"],[65417,1,"ノ"],[65418,1,"ハ"],[65419,1,"ヒ"],[65420,1,"フ"],[65421,1,"ヘ"],[65422,1,"ホ"],[65423,1,"マ"],[65424,1,"ミ"],[65425,1,"ム"],[65426,1,"メ"],[65427,1,"モ"],[65428,1,"ヤ"],[65429,1,"ユ"],[65430,1,"ヨ"],[65431,1,"ラ"],[65432,1,"リ"],[65433,1,"ル"],[65434,1,"レ"],[65435,1,"ロ"],[65436,1,"ワ"],[65437,1,"ン"],[65438,1,"゙"],[65439,1,"゚"],[65440,3],[65441,1,"ᄀ"],[65442,1,"ᄁ"],[65443,1,"ᆪ"],[65444,1,"ᄂ"],[65445,1,"ᆬ"],[65446,1,"ᆭ"],[65447,1,"ᄃ"],[65448,1,"ᄄ"],[65449,1,"ᄅ"],[65450,1,"ᆰ"],[65451,1,"ᆱ"],[65452,1,"ᆲ"],[65453,1,"ᆳ"],[65454,1,"ᆴ"],[65455,1,"ᆵ"],[65456,1,"ᄚ"],[65457,1,"ᄆ"],[65458,1,"ᄇ"],[65459,1,"ᄈ"],[65460,1,"ᄡ"],[65461,1,"ᄉ"],[65462,1,"ᄊ"],[65463,1,"ᄋ"],[65464,1,"ᄌ"],[65465,1,"ᄍ"],[65466,1,"ᄎ"],[65467,1,"ᄏ"],[65468,1,"ᄐ"],[65469,1,"ᄑ"],[65470,1,"ᄒ"],[[65471,65473],3],[65474,1,"ᅡ"],[65475,1,"ᅢ"],[65476,1,"ᅣ"],[65477,1,"ᅤ"],[65478,1,"ᅥ"],[65479,1,"ᅦ"],[[65480,65481],3],[65482,1,"ᅧ"],[65483,1,"ᅨ"],[65484,1,"ᅩ"],[65485,1,"ᅪ"],[65486,1,"ᅫ"],[65487,1,"ᅬ"],[[65488,65489],3],[65490,1,"ᅭ"],[65491,1,"ᅮ"],[65492,1,"ᅯ"],[65493,1,"ᅰ"],[65494,1,"ᅱ"],[65495,1,"ᅲ"],[[65496,65497],3],[65498,1,"ᅳ"],[65499,1,"ᅴ"],[65500,1,"ᅵ"],[[65501,65503],3],[65504,1,"¢"],[65505,1,"£"],[65506,1,"¬"],[65507,5," ̄"],[65508,1,"¦"],[65509,1,"¥"],[65510,1,"₩"],[65511,3],[65512,1,"│"],[65513,1,"←"],[65514,1,"↑"],[65515,1,"→"],[65516,1,"↓"],[65517,1,"■"],[65518,1,"○"],[[65519,65528],3],[[65529,65531],3],[65532,3],[65533,3],[[65534,65535],3],[[65536,65547],2],[65548,3],[[65549,65574],2],[65575,3],[[65576,65594],2],[65595,3],[[65596,65597],2],[65598,3],[[65599,65613],2],[[65614,65615],3],[[65616,65629],2],[[65630,65663],3],[[65664,65786],2],[[65787,65791],3],[[65792,65794],2],[[65795,65798],3],[[65799,65843],2],[[65844,65846],3],[[65847,65855],2],[[65856,65930],2],[[65931,65932],2],[[65933,65934],2],[65935,3],[[65936,65947],2],[65948,2],[[65949,65951],3],[65952,2],[[65953,65999],3],[[66000,66044],2],[66045,2],[[66046,66175],3],[[66176,66204],2],[[66205,66207],3],[[66208,66256],2],[[66257,66271],3],[66272,2],[[66273,66299],2],[[66300,66303],3],[[66304,66334],2],[66335,2],[[66336,66339],2],[[66340,66348],3],[[66349,66351],2],[[66352,66368],2],[66369,2],[[66370,66377],2],[66378,2],[[66379,66383],3],[[66384,66426],2],[[66427,66431],3],[[66432,66461],2],[66462,3],[66463,2],[[66464,66499],2],[[66500,66503],3],[[66504,66511],2],[[66512,66517],2],[[66518,66559],3],[66560,1,"𐐨"],[66561,1,"𐐩"],[66562,1,"𐐪"],[66563,1,"𐐫"],[66564,1,"𐐬"],[66565,1,"𐐭"],[66566,1,"𐐮"],[66567,1,"𐐯"],[66568,1,"𐐰"],[66569,1,"𐐱"],[66570,1,"𐐲"],[66571,1,"𐐳"],[66572,1,"𐐴"],[66573,1,"𐐵"],[66574,1,"𐐶"],[66575,1,"𐐷"],[66576,1,"𐐸"],[66577,1,"𐐹"],[66578,1,"𐐺"],[66579,1,"𐐻"],[66580,1,"𐐼"],[66581,1,"𐐽"],[66582,1,"𐐾"],[66583,1,"𐐿"],[66584,1,"𐑀"],[66585,1,"𐑁"],[66586,1,"𐑂"],[66587,1,"𐑃"],[66588,1,"𐑄"],[66589,1,"𐑅"],[66590,1,"𐑆"],[66591,1,"𐑇"],[66592,1,"𐑈"],[66593,1,"𐑉"],[66594,1,"𐑊"],[66595,1,"𐑋"],[66596,1,"𐑌"],[66597,1,"𐑍"],[66598,1,"𐑎"],[66599,1,"𐑏"],[[66600,66637],2],[[66638,66717],2],[[66718,66719],3],[[66720,66729],2],[[66730,66735],3],[66736,1,"𐓘"],[66737,1,"𐓙"],[66738,1,"𐓚"],[66739,1,"𐓛"],[66740,1,"𐓜"],[66741,1,"𐓝"],[66742,1,"𐓞"],[66743,1,"𐓟"],[66744,1,"𐓠"],[66745,1,"𐓡"],[66746,1,"𐓢"],[66747,1,"𐓣"],[66748,1,"𐓤"],[66749,1,"𐓥"],[66750,1,"𐓦"],[66751,1,"𐓧"],[66752,1,"𐓨"],[66753,1,"𐓩"],[66754,1,"𐓪"],[66755,1,"𐓫"],[66756,1,"𐓬"],[66757,1,"𐓭"],[66758,1,"𐓮"],[66759,1,"𐓯"],[66760,1,"𐓰"],[66761,1,"𐓱"],[66762,1,"𐓲"],[66763,1,"𐓳"],[66764,1,"𐓴"],[66765,1,"𐓵"],[66766,1,"𐓶"],[66767,1,"𐓷"],[66768,1,"𐓸"],[66769,1,"𐓹"],[66770,1,"𐓺"],[66771,1,"𐓻"],[[66772,66775],3],[[66776,66811],2],[[66812,66815],3],[[66816,66855],2],[[66856,66863],3],[[66864,66915],2],[[66916,66926],3],[66927,2],[66928,1,"𐖗"],[66929,1,"𐖘"],[66930,1,"𐖙"],[66931,1,"𐖚"],[66932,1,"𐖛"],[66933,1,"𐖜"],[66934,1,"𐖝"],[66935,1,"𐖞"],[66936,1,"𐖟"],[66937,1,"𐖠"],[66938,1,"𐖡"],[66939,3],[66940,1,"𐖣"],[66941,1,"𐖤"],[66942,1,"𐖥"],[66943,1,"𐖦"],[66944,1,"𐖧"],[66945,1,"𐖨"],[66946,1,"𐖩"],[66947,1,"𐖪"],[66948,1,"𐖫"],[66949,1,"𐖬"],[66950,1,"𐖭"],[66951,1,"𐖮"],[66952,1,"𐖯"],[66953,1,"𐖰"],[66954,1,"𐖱"],[66955,3],[66956,1,"𐖳"],[66957,1,"𐖴"],[66958,1,"𐖵"],[66959,1,"𐖶"],[66960,1,"𐖷"],[66961,1,"𐖸"],[66962,1,"𐖹"],[66963,3],[66964,1,"𐖻"],[66965,1,"𐖼"],[66966,3],[[66967,66977],2],[66978,3],[[66979,66993],2],[66994,3],[[66995,67001],2],[67002,3],[[67003,67004],2],[[67005,67071],3],[[67072,67382],2],[[67383,67391],3],[[67392,67413],2],[[67414,67423],3],[[67424,67431],2],[[67432,67455],3],[67456,2],[67457,1,"ː"],[67458,1,"ˑ"],[67459,1,"æ"],[67460,1,"ʙ"],[67461,1,"ɓ"],[67462,3],[67463,1,"ʣ"],[67464,1,"ꭦ"],[67465,1,"ʥ"],[67466,1,"ʤ"],[67467,1,"ɖ"],[67468,1,"ɗ"],[67469,1,"ᶑ"],[67470,1,"ɘ"],[67471,1,"ɞ"],[67472,1,"ʩ"],[67473,1,"ɤ"],[67474,1,"ɢ"],[67475,1,"ɠ"],[67476,1,"ʛ"],[67477,1,"ħ"],[67478,1,"ʜ"],[67479,1,"ɧ"],[67480,1,"ʄ"],[67481,1,"ʪ"],[67482,1,"ʫ"],[67483,1,"ɬ"],[67484,1,"𝼄"],[67485,1,"ꞎ"],[67486,1,"ɮ"],[67487,1,"𝼅"],[67488,1,"ʎ"],[67489,1,"𝼆"],[67490,1,"ø"],[67491,1,"ɶ"],[67492,1,"ɷ"],[67493,1,"q"],[67494,1,"ɺ"],[67495,1,"𝼈"],[67496,1,"ɽ"],[67497,1,"ɾ"],[67498,1,"ʀ"],[67499,1,"ʨ"],[67500,1,"ʦ"],[67501,1,"ꭧ"],[67502,1,"ʧ"],[67503,1,"ʈ"],[67504,1,"ⱱ"],[67505,3],[67506,1,"ʏ"],[67507,1,"ʡ"],[67508,1,"ʢ"],[67509,1,"ʘ"],[67510,1,"ǀ"],[67511,1,"ǁ"],[67512,1,"ǂ"],[67513,1,"𝼊"],[67514,1,"𝼞"],[[67515,67583],3],[[67584,67589],2],[[67590,67591],3],[67592,2],[67593,3],[[67594,67637],2],[67638,3],[[67639,67640],2],[[67641,67643],3],[67644,2],[[67645,67646],3],[67647,2],[[67648,67669],2],[67670,3],[[67671,67679],2],[[67680,67702],2],[[67703,67711],2],[[67712,67742],2],[[67743,67750],3],[[67751,67759],2],[[67760,67807],3],[[67808,67826],2],[67827,3],[[67828,67829],2],[[67830,67834],3],[[67835,67839],2],[[67840,67861],2],[[67862,67865],2],[[67866,67867],2],[[67868,67870],3],[67871,2],[[67872,67897],2],[[67898,67902],3],[67903,2],[[67904,67967],3],[[67968,68023],2],[[68024,68027],3],[[68028,68029],2],[[68030,68031],2],[[68032,68047],2],[[68048,68049],3],[[68050,68095],2],[[68096,68099],2],[68100,3],[[68101,68102],2],[[68103,68107],3],[[68108,68115],2],[68116,3],[[68117,68119],2],[68120,3],[[68121,68147],2],[[68148,68149],2],[[68150,68151],3],[[68152,68154],2],[[68155,68158],3],[68159,2],[[68160,68167],2],[68168,2],[[68169,68175],3],[[68176,68184],2],[[68185,68191],3],[[68192,68220],2],[[68221,68223],2],[[68224,68252],2],[[68253,68255],2],[[68256,68287],3],[[68288,68295],2],[68296,2],[[68297,68326],2],[[68327,68330],3],[[68331,68342],2],[[68343,68351],3],[[68352,68405],2],[[68406,68408],3],[[68409,68415],2],[[68416,68437],2],[[68438,68439],3],[[68440,68447],2],[[68448,68466],2],[[68467,68471],3],[[68472,68479],2],[[68480,68497],2],[[68498,68504],3],[[68505,68508],2],[[68509,68520],3],[[68521,68527],2],[[68528,68607],3],[[68608,68680],2],[[68681,68735],3],[68736,1,"𐳀"],[68737,1,"𐳁"],[68738,1,"𐳂"],[68739,1,"𐳃"],[68740,1,"𐳄"],[68741,1,"𐳅"],[68742,1,"𐳆"],[68743,1,"𐳇"],[68744,1,"𐳈"],[68745,1,"𐳉"],[68746,1,"𐳊"],[68747,1,"𐳋"],[68748,1,"𐳌"],[68749,1,"𐳍"],[68750,1,"𐳎"],[68751,1,"𐳏"],[68752,1,"𐳐"],[68753,1,"𐳑"],[68754,1,"𐳒"],[68755,1,"𐳓"],[68756,1,"𐳔"],[68757,1,"𐳕"],[68758,1,"𐳖"],[68759,1,"𐳗"],[68760,1,"𐳘"],[68761,1,"𐳙"],[68762,1,"𐳚"],[68763,1,"𐳛"],[68764,1,"𐳜"],[68765,1,"𐳝"],[68766,1,"𐳞"],[68767,1,"𐳟"],[68768,1,"𐳠"],[68769,1,"𐳡"],[68770,1,"𐳢"],[68771,1,"𐳣"],[68772,1,"𐳤"],[68773,1,"𐳥"],[68774,1,"𐳦"],[68775,1,"𐳧"],[68776,1,"𐳨"],[68777,1,"𐳩"],[68778,1,"𐳪"],[68779,1,"𐳫"],[68780,1,"𐳬"],[68781,1,"𐳭"],[68782,1,"𐳮"],[68783,1,"𐳯"],[68784,1,"𐳰"],[68785,1,"𐳱"],[68786,1,"𐳲"],[[68787,68799],3],[[68800,68850],2],[[68851,68857],3],[[68858,68863],2],[[68864,68903],2],[[68904,68911],3],[[68912,68921],2],[[68922,69215],3],[[69216,69246],2],[69247,3],[[69248,69289],2],[69290,3],[[69291,69292],2],[69293,2],[[69294,69295],3],[[69296,69297],2],[[69298,69375],3],[[69376,69404],2],[[69405,69414],2],[69415,2],[[69416,69423],3],[[69424,69456],2],[[69457,69465],2],[[69466,69487],3],[[69488,69509],2],[[69510,69513],2],[[69514,69551],3],[[69552,69572],2],[[69573,69579],2],[[69580,69599],3],[[69600,69622],2],[[69623,69631],3],[[69632,69702],2],[[69703,69709],2],[[69710,69713],3],[[69714,69733],2],[[69734,69743],2],[[69744,69749],2],[[69750,69758],3],[69759,2],[[69760,69818],2],[[69819,69820],2],[69821,3],[[69822,69825],2],[69826,2],[[69827,69836],3],[69837,3],[[69838,69839],3],[[69840,69864],2],[[69865,69871],3],[[69872,69881],2],[[69882,69887],3],[[69888,69940],2],[69941,3],[[69942,69951],2],[[69952,69955],2],[[69956,69958],2],[69959,2],[[69960,69967],3],[[69968,70003],2],[[70004,70005],2],[70006,2],[[70007,70015],3],[[70016,70084],2],[[70085,70088],2],[[70089,70092],2],[70093,2],[[70094,70095],2],[[70096,70105],2],[70106,2],[70107,2],[70108,2],[[70109,70111],2],[70112,3],[[70113,70132],2],[[70133,70143],3],[[70144,70161],2],[70162,3],[[70163,70199],2],[[70200,70205],2],[70206,2],[[70207,70271],3],[[70272,70278],2],[70279,3],[70280,2],[70281,3],[[70282,70285],2],[70286,3],[[70287,70301],2],[70302,3],[[70303,70312],2],[70313,2],[[70314,70319],3],[[70320,70378],2],[[70379,70383],3],[[70384,70393],2],[[70394,70399],3],[70400,2],[[70401,70403],2],[70404,3],[[70405,70412],2],[[70413,70414],3],[[70415,70416],2],[[70417,70418],3],[[70419,70440],2],[70441,3],[[70442,70448],2],[70449,3],[[70450,70451],2],[70452,3],[[70453,70457],2],[70458,3],[70459,2],[[70460,70468],2],[[70469,70470],3],[[70471,70472],2],[[70473,70474],3],[[70475,70477],2],[[70478,70479],3],[70480,2],[[70481,70486],3],[70487,2],[[70488,70492],3],[[70493,70499],2],[[70500,70501],3],[[70502,70508],2],[[70509,70511],3],[[70512,70516],2],[[70517,70655],3],[[70656,70730],2],[[70731,70735],2],[[70736,70745],2],[70746,2],[70747,2],[70748,3],[70749,2],[70750,2],[70751,2],[[70752,70753],2],[[70754,70783],3],[[70784,70853],2],[70854,2],[70855,2],[[70856,70863],3],[[70864,70873],2],[[70874,71039],3],[[71040,71093],2],[[71094,71095],3],[[71096,71104],2],[[71105,71113],2],[[71114,71127],2],[[71128,71133],2],[[71134,71167],3],[[71168,71232],2],[[71233,71235],2],[71236,2],[[71237,71247],3],[[71248,71257],2],[[71258,71263],3],[[71264,71276],2],[[71277,71295],3],[[71296,71351],2],[71352,2],[71353,2],[[71354,71359],3],[[71360,71369],2],[[71370,71423],3],[[71424,71449],2],[71450,2],[[71451,71452],3],[[71453,71467],2],[[71468,71471],3],[[71472,71481],2],[[71482,71487],2],[[71488,71494],2],[[71495,71679],3],[[71680,71738],2],[71739,2],[[71740,71839],3],[71840,1,"𑣀"],[71841,1,"𑣁"],[71842,1,"𑣂"],[71843,1,"𑣃"],[71844,1,"𑣄"],[71845,1,"𑣅"],[71846,1,"𑣆"],[71847,1,"𑣇"],[71848,1,"𑣈"],[71849,1,"𑣉"],[71850,1,"𑣊"],[71851,1,"𑣋"],[71852,1,"𑣌"],[71853,1,"𑣍"],[71854,1,"𑣎"],[71855,1,"𑣏"],[71856,1,"𑣐"],[71857,1,"𑣑"],[71858,1,"𑣒"],[71859,1,"𑣓"],[71860,1,"𑣔"],[71861,1,"𑣕"],[71862,1,"𑣖"],[71863,1,"𑣗"],[71864,1,"𑣘"],[71865,1,"𑣙"],[71866,1,"𑣚"],[71867,1,"𑣛"],[71868,1,"𑣜"],[71869,1,"𑣝"],[71870,1,"𑣞"],[71871,1,"𑣟"],[[71872,71913],2],[[71914,71922],2],[[71923,71934],3],[71935,2],[[71936,71942],2],[[71943,71944],3],[71945,2],[[71946,71947],3],[[71948,71955],2],[71956,3],[[71957,71958],2],[71959,3],[[71960,71989],2],[71990,3],[[71991,71992],2],[[71993,71994],3],[[71995,72003],2],[[72004,72006],2],[[72007,72015],3],[[72016,72025],2],[[72026,72095],3],[[72096,72103],2],[[72104,72105],3],[[72106,72151],2],[[72152,72153],3],[[72154,72161],2],[72162,2],[[72163,72164],2],[[72165,72191],3],[[72192,72254],2],[[72255,72262],2],[72263,2],[[72264,72271],3],[[72272,72323],2],[[72324,72325],2],[[72326,72345],2],[[72346,72348],2],[72349,2],[[72350,72354],2],[[72355,72367],3],[[72368,72383],2],[[72384,72440],2],[[72441,72703],3],[[72704,72712],2],[72713,3],[[72714,72758],2],[72759,3],[[72760,72768],2],[[72769,72773],2],[[72774,72783],3],[[72784,72793],2],[[72794,72812],2],[[72813,72815],3],[[72816,72817],2],[[72818,72847],2],[[72848,72849],3],[[72850,72871],2],[72872,3],[[72873,72886],2],[[72887,72959],3],[[72960,72966],2],[72967,3],[[72968,72969],2],[72970,3],[[72971,73014],2],[[73015,73017],3],[73018,2],[73019,3],[[73020,73021],2],[73022,3],[[73023,73031],2],[[73032,73039],3],[[73040,73049],2],[[73050,73055],3],[[73056,73061],2],[73062,3],[[73063,73064],2],[73065,3],[[73066,73102],2],[73103,3],[[73104,73105],2],[73106,3],[[73107,73112],2],[[73113,73119],3],[[73120,73129],2],[[73130,73439],3],[[73440,73462],2],[[73463,73464],2],[[73465,73647],3],[73648,2],[[73649,73663],3],[[73664,73713],2],[[73714,73726],3],[73727,2],[[73728,74606],2],[[74607,74648],2],[74649,2],[[74650,74751],3],[[74752,74850],2],[[74851,74862],2],[74863,3],[[74864,74867],2],[74868,2],[[74869,74879],3],[[74880,75075],2],[[75076,77711],3],[[77712,77808],2],[[77809,77810],2],[[77811,77823],3],[[77824,78894],2],[78895,3],[[78896,78904],3],[[78905,82943],3],[[82944,83526],2],[[83527,92159],3],[[92160,92728],2],[[92729,92735],3],[[92736,92766],2],[92767,3],[[92768,92777],2],[[92778,92781],3],[[92782,92783],2],[[92784,92862],2],[92863,3],[[92864,92873],2],[[92874,92879],3],[[92880,92909],2],[[92910,92911],3],[[92912,92916],2],[92917,2],[[92918,92927],3],[[92928,92982],2],[[92983,92991],2],[[92992,92995],2],[[92996,92997],2],[[92998,93007],3],[[93008,93017],2],[93018,3],[[93019,93025],2],[93026,3],[[93027,93047],2],[[93048,93052],3],[[93053,93071],2],[[93072,93759],3],[93760,1,"𖹠"],[93761,1,"𖹡"],[93762,1,"𖹢"],[93763,1,"𖹣"],[93764,1,"𖹤"],[93765,1,"𖹥"],[93766,1,"𖹦"],[93767,1,"𖹧"],[93768,1,"𖹨"],[93769,1,"𖹩"],[93770,1,"𖹪"],[93771,1,"𖹫"],[93772,1,"𖹬"],[93773,1,"𖹭"],[93774,1,"𖹮"],[93775,1,"𖹯"],[93776,1,"𖹰"],[93777,1,"𖹱"],[93778,1,"𖹲"],[93779,1,"𖹳"],[93780,1,"𖹴"],[93781,1,"𖹵"],[93782,1,"𖹶"],[93783,1,"𖹷"],[93784,1,"𖹸"],[93785,1,"𖹹"],[93786,1,"𖹺"],[93787,1,"𖹻"],[93788,1,"𖹼"],[93789,1,"𖹽"],[93790,1,"𖹾"],[93791,1,"𖹿"],[[93792,93823],2],[[93824,93850],2],[[93851,93951],3],[[93952,94020],2],[[94021,94026],2],[[94027,94030],3],[94031,2],[[94032,94078],2],[[94079,94087],2],[[94088,94094],3],[[94095,94111],2],[[94112,94175],3],[94176,2],[94177,2],[94178,2],[94179,2],[94180,2],[[94181,94191],3],[[94192,94193],2],[[94194,94207],3],[[94208,100332],2],[[100333,100337],2],[[100338,100343],2],[[100344,100351],3],[[100352,101106],2],[[101107,101589],2],[[101590,101631],3],[[101632,101640],2],[[101641,110575],3],[[110576,110579],2],[110580,3],[[110581,110587],2],[110588,3],[[110589,110590],2],[110591,3],[[110592,110593],2],[[110594,110878],2],[[110879,110882],2],[[110883,110927],3],[[110928,110930],2],[[110931,110947],3],[[110948,110951],2],[[110952,110959],3],[[110960,111355],2],[[111356,113663],3],[[113664,113770],2],[[113771,113775],3],[[113776,113788],2],[[113789,113791],3],[[113792,113800],2],[[113801,113807],3],[[113808,113817],2],[[113818,113819],3],[113820,2],[[113821,113822],2],[113823,2],[[113824,113827],7],[[113828,118527],3],[[118528,118573],2],[[118574,118575],3],[[118576,118598],2],[[118599,118607],3],[[118608,118723],2],[[118724,118783],3],[[118784,119029],2],[[119030,119039],3],[[119040,119078],2],[[119079,119080],3],[119081,2],[[119082,119133],2],[119134,1,"𝅗𝅥"],[119135,1,"𝅘𝅥"],[119136,1,"𝅘𝅥𝅮"],[119137,1,"𝅘𝅥𝅯"],[119138,1,"𝅘𝅥𝅰"],[119139,1,"𝅘𝅥𝅱"],[119140,1,"𝅘𝅥𝅲"],[[119141,119154],2],[[119155,119162],3],[[119163,119226],2],[119227,1,"𝆹𝅥"],[119228,1,"𝆺𝅥"],[119229,1,"𝆹𝅥𝅮"],[119230,1,"𝆺𝅥𝅮"],[119231,1,"𝆹𝅥𝅯"],[119232,1,"𝆺𝅥𝅯"],[[119233,119261],2],[[119262,119272],2],[[119273,119274],2],[[119275,119295],3],[[119296,119365],2],[[119366,119519],3],[[119520,119539],2],[[119540,119551],3],[[119552,119638],2],[[119639,119647],3],[[119648,119665],2],[[119666,119672],2],[[119673,119807],3],[119808,1,"a"],[119809,1,"b"],[119810,1,"c"],[119811,1,"d"],[119812,1,"e"],[119813,1,"f"],[119814,1,"g"],[119815,1,"h"],[119816,1,"i"],[119817,1,"j"],[119818,1,"k"],[119819,1,"l"],[119820,1,"m"],[119821,1,"n"],[119822,1,"o"],[119823,1,"p"],[119824,1,"q"],[119825,1,"r"],[119826,1,"s"],[119827,1,"t"],[119828,1,"u"],[119829,1,"v"],[119830,1,"w"],[119831,1,"x"],[119832,1,"y"],[119833,1,"z"],[119834,1,"a"],[119835,1,"b"],[119836,1,"c"],[119837,1,"d"],[119838,1,"e"],[119839,1,"f"],[119840,1,"g"],[119841,1,"h"],[119842,1,"i"],[119843,1,"j"],[119844,1,"k"],[119845,1,"l"],[119846,1,"m"],[119847,1,"n"],[119848,1,"o"],[119849,1,"p"],[119850,1,"q"],[119851,1,"r"],[119852,1,"s"],[119853,1,"t"],[119854,1,"u"],[119855,1,"v"],[119856,1,"w"],[119857,1,"x"],[119858,1,"y"],[119859,1,"z"],[119860,1,"a"],[119861,1,"b"],[119862,1,"c"],[119863,1,"d"],[119864,1,"e"],[119865,1,"f"],[119866,1,"g"],[119867,1,"h"],[119868,1,"i"],[119869,1,"j"],[119870,1,"k"],[119871,1,"l"],[119872,1,"m"],[119873,1,"n"],[119874,1,"o"],[119875,1,"p"],[119876,1,"q"],[119877,1,"r"],[119878,1,"s"],[119879,1,"t"],[119880,1,"u"],[119881,1,"v"],[119882,1,"w"],[119883,1,"x"],[119884,1,"y"],[119885,1,"z"],[119886,1,"a"],[119887,1,"b"],[119888,1,"c"],[119889,1,"d"],[119890,1,"e"],[119891,1,"f"],[119892,1,"g"],[119893,3],[119894,1,"i"],[119895,1,"j"],[119896,1,"k"],[119897,1,"l"],[119898,1,"m"],[119899,1,"n"],[119900,1,"o"],[119901,1,"p"],[119902,1,"q"],[119903,1,"r"],[119904,1,"s"],[119905,1,"t"],[119906,1,"u"],[119907,1,"v"],[119908,1,"w"],[119909,1,"x"],[119910,1,"y"],[119911,1,"z"],[119912,1,"a"],[119913,1,"b"],[119914,1,"c"],[119915,1,"d"],[119916,1,"e"],[119917,1,"f"],[119918,1,"g"],[119919,1,"h"],[119920,1,"i"],[119921,1,"j"],[119922,1,"k"],[119923,1,"l"],[119924,1,"m"],[119925,1,"n"],[119926,1,"o"],[119927,1,"p"],[119928,1,"q"],[119929,1,"r"],[119930,1,"s"],[119931,1,"t"],[119932,1,"u"],[119933,1,"v"],[119934,1,"w"],[119935,1,"x"],[119936,1,"y"],[119937,1,"z"],[119938,1,"a"],[119939,1,"b"],[119940,1,"c"],[119941,1,"d"],[119942,1,"e"],[119943,1,"f"],[119944,1,"g"],[119945,1,"h"],[119946,1,"i"],[119947,1,"j"],[119948,1,"k"],[119949,1,"l"],[119950,1,"m"],[119951,1,"n"],[119952,1,"o"],[119953,1,"p"],[119954,1,"q"],[119955,1,"r"],[119956,1,"s"],[119957,1,"t"],[119958,1,"u"],[119959,1,"v"],[119960,1,"w"],[119961,1,"x"],[119962,1,"y"],[119963,1,"z"],[119964,1,"a"],[119965,3],[119966,1,"c"],[119967,1,"d"],[[119968,119969],3],[119970,1,"g"],[[119971,119972],3],[119973,1,"j"],[119974,1,"k"],[[119975,119976],3],[119977,1,"n"],[119978,1,"o"],[119979,1,"p"],[119980,1,"q"],[119981,3],[119982,1,"s"],[119983,1,"t"],[119984,1,"u"],[119985,1,"v"],[119986,1,"w"],[119987,1,"x"],[119988,1,"y"],[119989,1,"z"],[119990,1,"a"],[119991,1,"b"],[119992,1,"c"],[119993,1,"d"],[119994,3],[119995,1,"f"],[119996,3],[119997,1,"h"],[119998,1,"i"],[119999,1,"j"],[120000,1,"k"],[120001,1,"l"],[120002,1,"m"],[120003,1,"n"],[120004,3],[120005,1,"p"],[120006,1,"q"],[120007,1,"r"],[120008,1,"s"],[120009,1,"t"],[120010,1,"u"],[120011,1,"v"],[120012,1,"w"],[120013,1,"x"],[120014,1,"y"],[120015,1,"z"],[120016,1,"a"],[120017,1,"b"],[120018,1,"c"],[120019,1,"d"],[120020,1,"e"],[120021,1,"f"],[120022,1,"g"],[120023,1,"h"],[120024,1,"i"],[120025,1,"j"],[120026,1,"k"],[120027,1,"l"],[120028,1,"m"],[120029,1,"n"],[120030,1,"o"],[120031,1,"p"],[120032,1,"q"],[120033,1,"r"],[120034,1,"s"],[120035,1,"t"],[120036,1,"u"],[120037,1,"v"],[120038,1,"w"],[120039,1,"x"],[120040,1,"y"],[120041,1,"z"],[120042,1,"a"],[120043,1,"b"],[120044,1,"c"],[120045,1,"d"],[120046,1,"e"],[120047,1,"f"],[120048,1,"g"],[120049,1,"h"],[120050,1,"i"],[120051,1,"j"],[120052,1,"k"],[120053,1,"l"],[120054,1,"m"],[120055,1,"n"],[120056,1,"o"],[120057,1,"p"],[120058,1,"q"],[120059,1,"r"],[120060,1,"s"],[120061,1,"t"],[120062,1,"u"],[120063,1,"v"],[120064,1,"w"],[120065,1,"x"],[120066,1,"y"],[120067,1,"z"],[120068,1,"a"],[120069,1,"b"],[120070,3],[120071,1,"d"],[120072,1,"e"],[120073,1,"f"],[120074,1,"g"],[[120075,120076],3],[120077,1,"j"],[120078,1,"k"],[120079,1,"l"],[120080,1,"m"],[120081,1,"n"],[120082,1,"o"],[120083,1,"p"],[120084,1,"q"],[120085,3],[120086,1,"s"],[120087,1,"t"],[120088,1,"u"],[120089,1,"v"],[120090,1,"w"],[120091,1,"x"],[120092,1,"y"],[120093,3],[120094,1,"a"],[120095,1,"b"],[120096,1,"c"],[120097,1,"d"],[120098,1,"e"],[120099,1,"f"],[120100,1,"g"],[120101,1,"h"],[120102,1,"i"],[120103,1,"j"],[120104,1,"k"],[120105,1,"l"],[120106,1,"m"],[120107,1,"n"],[120108,1,"o"],[120109,1,"p"],[120110,1,"q"],[120111,1,"r"],[120112,1,"s"],[120113,1,"t"],[120114,1,"u"],[120115,1,"v"],[120116,1,"w"],[120117,1,"x"],[120118,1,"y"],[120119,1,"z"],[120120,1,"a"],[120121,1,"b"],[120122,3],[120123,1,"d"],[120124,1,"e"],[120125,1,"f"],[120126,1,"g"],[120127,3],[120128,1,"i"],[120129,1,"j"],[120130,1,"k"],[120131,1,"l"],[120132,1,"m"],[120133,3],[120134,1,"o"],[[120135,120137],3],[120138,1,"s"],[120139,1,"t"],[120140,1,"u"],[120141,1,"v"],[120142,1,"w"],[120143,1,"x"],[120144,1,"y"],[120145,3],[120146,1,"a"],[120147,1,"b"],[120148,1,"c"],[120149,1,"d"],[120150,1,"e"],[120151,1,"f"],[120152,1,"g"],[120153,1,"h"],[120154,1,"i"],[120155,1,"j"],[120156,1,"k"],[120157,1,"l"],[120158,1,"m"],[120159,1,"n"],[120160,1,"o"],[120161,1,"p"],[120162,1,"q"],[120163,1,"r"],[120164,1,"s"],[120165,1,"t"],[120166,1,"u"],[120167,1,"v"],[120168,1,"w"],[120169,1,"x"],[120170,1,"y"],[120171,1,"z"],[120172,1,"a"],[120173,1,"b"],[120174,1,"c"],[120175,1,"d"],[120176,1,"e"],[120177,1,"f"],[120178,1,"g"],[120179,1,"h"],[120180,1,"i"],[120181,1,"j"],[120182,1,"k"],[120183,1,"l"],[120184,1,"m"],[120185,1,"n"],[120186,1,"o"],[120187,1,"p"],[120188,1,"q"],[120189,1,"r"],[120190,1,"s"],[120191,1,"t"],[120192,1,"u"],[120193,1,"v"],[120194,1,"w"],[120195,1,"x"],[120196,1,"y"],[120197,1,"z"],[120198,1,"a"],[120199,1,"b"],[120200,1,"c"],[120201,1,"d"],[120202,1,"e"],[120203,1,"f"],[120204,1,"g"],[120205,1,"h"],[120206,1,"i"],[120207,1,"j"],[120208,1,"k"],[120209,1,"l"],[120210,1,"m"],[120211,1,"n"],[120212,1,"o"],[120213,1,"p"],[120214,1,"q"],[120215,1,"r"],[120216,1,"s"],[120217,1,"t"],[120218,1,"u"],[120219,1,"v"],[120220,1,"w"],[120221,1,"x"],[120222,1,"y"],[120223,1,"z"],[120224,1,"a"],[120225,1,"b"],[120226,1,"c"],[120227,1,"d"],[120228,1,"e"],[120229,1,"f"],[120230,1,"g"],[120231,1,"h"],[120232,1,"i"],[120233,1,"j"],[120234,1,"k"],[120235,1,"l"],[120236,1,"m"],[120237,1,"n"],[120238,1,"o"],[120239,1,"p"],[120240,1,"q"],[120241,1,"r"],[120242,1,"s"],[120243,1,"t"],[120244,1,"u"],[120245,1,"v"],[120246,1,"w"],[120247,1,"x"],[120248,1,"y"],[120249,1,"z"],[120250,1,"a"],[120251,1,"b"],[120252,1,"c"],[120253,1,"d"],[120254,1,"e"],[120255,1,"f"],[120256,1,"g"],[120257,1,"h"],[120258,1,"i"],[120259,1,"j"],[120260,1,"k"],[120261,1,"l"],[120262,1,"m"],[120263,1,"n"],[120264,1,"o"],[120265,1,"p"],[120266,1,"q"],[120267,1,"r"],[120268,1,"s"],[120269,1,"t"],[120270,1,"u"],[120271,1,"v"],[120272,1,"w"],[120273,1,"x"],[120274,1,"y"],[120275,1,"z"],[120276,1,"a"],[120277,1,"b"],[120278,1,"c"],[120279,1,"d"],[120280,1,"e"],[120281,1,"f"],[120282,1,"g"],[120283,1,"h"],[120284,1,"i"],[120285,1,"j"],[120286,1,"k"],[120287,1,"l"],[120288,1,"m"],[120289,1,"n"],[120290,1,"o"],[120291,1,"p"],[120292,1,"q"],[120293,1,"r"],[120294,1,"s"],[120295,1,"t"],[120296,1,"u"],[120297,1,"v"],[120298,1,"w"],[120299,1,"x"],[120300,1,"y"],[120301,1,"z"],[120302,1,"a"],[120303,1,"b"],[120304,1,"c"],[120305,1,"d"],[120306,1,"e"],[120307,1,"f"],[120308,1,"g"],[120309,1,"h"],[120310,1,"i"],[120311,1,"j"],[120312,1,"k"],[120313,1,"l"],[120314,1,"m"],[120315,1,"n"],[120316,1,"o"],[120317,1,"p"],[120318,1,"q"],[120319,1,"r"],[120320,1,"s"],[120321,1,"t"],[120322,1,"u"],[120323,1,"v"],[120324,1,"w"],[120325,1,"x"],[120326,1,"y"],[120327,1,"z"],[120328,1,"a"],[120329,1,"b"],[120330,1,"c"],[120331,1,"d"],[120332,1,"e"],[120333,1,"f"],[120334,1,"g"],[120335,1,"h"],[120336,1,"i"],[120337,1,"j"],[120338,1,"k"],[120339,1,"l"],[120340,1,"m"],[120341,1,"n"],[120342,1,"o"],[120343,1,"p"],[120344,1,"q"],[120345,1,"r"],[120346,1,"s"],[120347,1,"t"],[120348,1,"u"],[120349,1,"v"],[120350,1,"w"],[120351,1,"x"],[120352,1,"y"],[120353,1,"z"],[120354,1,"a"],[120355,1,"b"],[120356,1,"c"],[120357,1,"d"],[120358,1,"e"],[120359,1,"f"],[120360,1,"g"],[120361,1,"h"],[120362,1,"i"],[120363,1,"j"],[120364,1,"k"],[120365,1,"l"],[120366,1,"m"],[120367,1,"n"],[120368,1,"o"],[120369,1,"p"],[120370,1,"q"],[120371,1,"r"],[120372,1,"s"],[120373,1,"t"],[120374,1,"u"],[120375,1,"v"],[120376,1,"w"],[120377,1,"x"],[120378,1,"y"],[120379,1,"z"],[120380,1,"a"],[120381,1,"b"],[120382,1,"c"],[120383,1,"d"],[120384,1,"e"],[120385,1,"f"],[120386,1,"g"],[120387,1,"h"],[120388,1,"i"],[120389,1,"j"],[120390,1,"k"],[120391,1,"l"],[120392,1,"m"],[120393,1,"n"],[120394,1,"o"],[120395,1,"p"],[120396,1,"q"],[120397,1,"r"],[120398,1,"s"],[120399,1,"t"],[120400,1,"u"],[120401,1,"v"],[120402,1,"w"],[120403,1,"x"],[120404,1,"y"],[120405,1,"z"],[120406,1,"a"],[120407,1,"b"],[120408,1,"c"],[120409,1,"d"],[120410,1,"e"],[120411,1,"f"],[120412,1,"g"],[120413,1,"h"],[120414,1,"i"],[120415,1,"j"],[120416,1,"k"],[120417,1,"l"],[120418,1,"m"],[120419,1,"n"],[120420,1,"o"],[120421,1,"p"],[120422,1,"q"],[120423,1,"r"],[120424,1,"s"],[120425,1,"t"],[120426,1,"u"],[120427,1,"v"],[120428,1,"w"],[120429,1,"x"],[120430,1,"y"],[120431,1,"z"],[120432,1,"a"],[120433,1,"b"],[120434,1,"c"],[120435,1,"d"],[120436,1,"e"],[120437,1,"f"],[120438,1,"g"],[120439,1,"h"],[120440,1,"i"],[120441,1,"j"],[120442,1,"k"],[120443,1,"l"],[120444,1,"m"],[120445,1,"n"],[120446,1,"o"],[120447,1,"p"],[120448,1,"q"],[120449,1,"r"],[120450,1,"s"],[120451,1,"t"],[120452,1,"u"],[120453,1,"v"],[120454,1,"w"],[120455,1,"x"],[120456,1,"y"],[120457,1,"z"],[120458,1,"a"],[120459,1,"b"],[120460,1,"c"],[120461,1,"d"],[120462,1,"e"],[120463,1,"f"],[120464,1,"g"],[120465,1,"h"],[120466,1,"i"],[120467,1,"j"],[120468,1,"k"],[120469,1,"l"],[120470,1,"m"],[120471,1,"n"],[120472,1,"o"],[120473,1,"p"],[120474,1,"q"],[120475,1,"r"],[120476,1,"s"],[120477,1,"t"],[120478,1,"u"],[120479,1,"v"],[120480,1,"w"],[120481,1,"x"],[120482,1,"y"],[120483,1,"z"],[120484,1,"ı"],[120485,1,"ȷ"],[[120486,120487],3],[120488,1,"α"],[120489,1,"β"],[120490,1,"γ"],[120491,1,"δ"],[120492,1,"ε"],[120493,1,"ζ"],[120494,1,"η"],[120495,1,"θ"],[120496,1,"ι"],[120497,1,"κ"],[120498,1,"λ"],[120499,1,"μ"],[120500,1,"ν"],[120501,1,"ξ"],[120502,1,"ο"],[120503,1,"π"],[120504,1,"ρ"],[120505,1,"θ"],[120506,1,"σ"],[120507,1,"τ"],[120508,1,"υ"],[120509,1,"φ"],[120510,1,"χ"],[120511,1,"ψ"],[120512,1,"ω"],[120513,1,"∇"],[120514,1,"α"],[120515,1,"β"],[120516,1,"γ"],[120517,1,"δ"],[120518,1,"ε"],[120519,1,"ζ"],[120520,1,"η"],[120521,1,"θ"],[120522,1,"ι"],[120523,1,"κ"],[120524,1,"λ"],[120525,1,"μ"],[120526,1,"ν"],[120527,1,"ξ"],[120528,1,"ο"],[120529,1,"π"],[120530,1,"ρ"],[[120531,120532],1,"σ"],[120533,1,"τ"],[120534,1,"υ"],[120535,1,"φ"],[120536,1,"χ"],[120537,1,"ψ"],[120538,1,"ω"],[120539,1,"∂"],[120540,1,"ε"],[120541,1,"θ"],[120542,1,"κ"],[120543,1,"φ"],[120544,1,"ρ"],[120545,1,"π"],[120546,1,"α"],[120547,1,"β"],[120548,1,"γ"],[120549,1,"δ"],[120550,1,"ε"],[120551,1,"ζ"],[120552,1,"η"],[120553,1,"θ"],[120554,1,"ι"],[120555,1,"κ"],[120556,1,"λ"],[120557,1,"μ"],[120558,1,"ν"],[120559,1,"ξ"],[120560,1,"ο"],[120561,1,"π"],[120562,1,"ρ"],[120563,1,"θ"],[120564,1,"σ"],[120565,1,"τ"],[120566,1,"υ"],[120567,1,"φ"],[120568,1,"χ"],[120569,1,"ψ"],[120570,1,"ω"],[120571,1,"∇"],[120572,1,"α"],[120573,1,"β"],[120574,1,"γ"],[120575,1,"δ"],[120576,1,"ε"],[120577,1,"ζ"],[120578,1,"η"],[120579,1,"θ"],[120580,1,"ι"],[120581,1,"κ"],[120582,1,"λ"],[120583,1,"μ"],[120584,1,"ν"],[120585,1,"ξ"],[120586,1,"ο"],[120587,1,"π"],[120588,1,"ρ"],[[120589,120590],1,"σ"],[120591,1,"τ"],[120592,1,"υ"],[120593,1,"φ"],[120594,1,"χ"],[120595,1,"ψ"],[120596,1,"ω"],[120597,1,"∂"],[120598,1,"ε"],[120599,1,"θ"],[120600,1,"κ"],[120601,1,"φ"],[120602,1,"ρ"],[120603,1,"π"],[120604,1,"α"],[120605,1,"β"],[120606,1,"γ"],[120607,1,"δ"],[120608,1,"ε"],[120609,1,"ζ"],[120610,1,"η"],[120611,1,"θ"],[120612,1,"ι"],[120613,1,"κ"],[120614,1,"λ"],[120615,1,"μ"],[120616,1,"ν"],[120617,1,"ξ"],[120618,1,"ο"],[120619,1,"π"],[120620,1,"ρ"],[120621,1,"θ"],[120622,1,"σ"],[120623,1,"τ"],[120624,1,"υ"],[120625,1,"φ"],[120626,1,"χ"],[120627,1,"ψ"],[120628,1,"ω"],[120629,1,"∇"],[120630,1,"α"],[120631,1,"β"],[120632,1,"γ"],[120633,1,"δ"],[120634,1,"ε"],[120635,1,"ζ"],[120636,1,"η"],[120637,1,"θ"],[120638,1,"ι"],[120639,1,"κ"],[120640,1,"λ"],[120641,1,"μ"],[120642,1,"ν"],[120643,1,"ξ"],[120644,1,"ο"],[120645,1,"π"],[120646,1,"ρ"],[[120647,120648],1,"σ"],[120649,1,"τ"],[120650,1,"υ"],[120651,1,"φ"],[120652,1,"χ"],[120653,1,"ψ"],[120654,1,"ω"],[120655,1,"∂"],[120656,1,"ε"],[120657,1,"θ"],[120658,1,"κ"],[120659,1,"φ"],[120660,1,"ρ"],[120661,1,"π"],[120662,1,"α"],[120663,1,"β"],[120664,1,"γ"],[120665,1,"δ"],[120666,1,"ε"],[120667,1,"ζ"],[120668,1,"η"],[120669,1,"θ"],[120670,1,"ι"],[120671,1,"κ"],[120672,1,"λ"],[120673,1,"μ"],[120674,1,"ν"],[120675,1,"ξ"],[120676,1,"ο"],[120677,1,"π"],[120678,1,"ρ"],[120679,1,"θ"],[120680,1,"σ"],[120681,1,"τ"],[120682,1,"υ"],[120683,1,"φ"],[120684,1,"χ"],[120685,1,"ψ"],[120686,1,"ω"],[120687,1,"∇"],[120688,1,"α"],[120689,1,"β"],[120690,1,"γ"],[120691,1,"δ"],[120692,1,"ε"],[120693,1,"ζ"],[120694,1,"η"],[120695,1,"θ"],[120696,1,"ι"],[120697,1,"κ"],[120698,1,"λ"],[120699,1,"μ"],[120700,1,"ν"],[120701,1,"ξ"],[120702,1,"ο"],[120703,1,"π"],[120704,1,"ρ"],[[120705,120706],1,"σ"],[120707,1,"τ"],[120708,1,"υ"],[120709,1,"φ"],[120710,1,"χ"],[120711,1,"ψ"],[120712,1,"ω"],[120713,1,"∂"],[120714,1,"ε"],[120715,1,"θ"],[120716,1,"κ"],[120717,1,"φ"],[120718,1,"ρ"],[120719,1,"π"],[120720,1,"α"],[120721,1,"β"],[120722,1,"γ"],[120723,1,"δ"],[120724,1,"ε"],[120725,1,"ζ"],[120726,1,"η"],[120727,1,"θ"],[120728,1,"ι"],[120729,1,"κ"],[120730,1,"λ"],[120731,1,"μ"],[120732,1,"ν"],[120733,1,"ξ"],[120734,1,"ο"],[120735,1,"π"],[120736,1,"ρ"],[120737,1,"θ"],[120738,1,"σ"],[120739,1,"τ"],[120740,1,"υ"],[120741,1,"φ"],[120742,1,"χ"],[120743,1,"ψ"],[120744,1,"ω"],[120745,1,"∇"],[120746,1,"α"],[120747,1,"β"],[120748,1,"γ"],[120749,1,"δ"],[120750,1,"ε"],[120751,1,"ζ"],[120752,1,"η"],[120753,1,"θ"],[120754,1,"ι"],[120755,1,"κ"],[120756,1,"λ"],[120757,1,"μ"],[120758,1,"ν"],[120759,1,"ξ"],[120760,1,"ο"],[120761,1,"π"],[120762,1,"ρ"],[[120763,120764],1,"σ"],[120765,1,"τ"],[120766,1,"υ"],[120767,1,"φ"],[120768,1,"χ"],[120769,1,"ψ"],[120770,1,"ω"],[120771,1,"∂"],[120772,1,"ε"],[120773,1,"θ"],[120774,1,"κ"],[120775,1,"φ"],[120776,1,"ρ"],[120777,1,"π"],[[120778,120779],1,"ϝ"],[[120780,120781],3],[120782,1,"0"],[120783,1,"1"],[120784,1,"2"],[120785,1,"3"],[120786,1,"4"],[120787,1,"5"],[120788,1,"6"],[120789,1,"7"],[120790,1,"8"],[120791,1,"9"],[120792,1,"0"],[120793,1,"1"],[120794,1,"2"],[120795,1,"3"],[120796,1,"4"],[120797,1,"5"],[120798,1,"6"],[120799,1,"7"],[120800,1,"8"],[120801,1,"9"],[120802,1,"0"],[120803,1,"1"],[120804,1,"2"],[120805,1,"3"],[120806,1,"4"],[120807,1,"5"],[120808,1,"6"],[120809,1,"7"],[120810,1,"8"],[120811,1,"9"],[120812,1,"0"],[120813,1,"1"],[120814,1,"2"],[120815,1,"3"],[120816,1,"4"],[120817,1,"5"],[120818,1,"6"],[120819,1,"7"],[120820,1,"8"],[120821,1,"9"],[120822,1,"0"],[120823,1,"1"],[120824,1,"2"],[120825,1,"3"],[120826,1,"4"],[120827,1,"5"],[120828,1,"6"],[120829,1,"7"],[120830,1,"8"],[120831,1,"9"],[[120832,121343],2],[[121344,121398],2],[[121399,121402],2],[[121403,121452],2],[[121453,121460],2],[121461,2],[[121462,121475],2],[121476,2],[[121477,121483],2],[[121484,121498],3],[[121499,121503],2],[121504,3],[[121505,121519],2],[[121520,122623],3],[[122624,122654],2],[[122655,122879],3],[[122880,122886],2],[122887,3],[[122888,122904],2],[[122905,122906],3],[[122907,122913],2],[122914,3],[[122915,122916],2],[122917,3],[[122918,122922],2],[[122923,123135],3],[[123136,123180],2],[[123181,123183],3],[[123184,123197],2],[[123198,123199],3],[[123200,123209],2],[[123210,123213],3],[123214,2],[123215,2],[[123216,123535],3],[[123536,123566],2],[[123567,123583],3],[[123584,123641],2],[[123642,123646],3],[123647,2],[[123648,124895],3],[[124896,124902],2],[124903,3],[[124904,124907],2],[124908,3],[[124909,124910],2],[124911,3],[[124912,124926],2],[124927,3],[[124928,125124],2],[[125125,125126],3],[[125127,125135],2],[[125136,125142],2],[[125143,125183],3],[125184,1,"𞤢"],[125185,1,"𞤣"],[125186,1,"𞤤"],[125187,1,"𞤥"],[125188,1,"𞤦"],[125189,1,"𞤧"],[125190,1,"𞤨"],[125191,1,"𞤩"],[125192,1,"𞤪"],[125193,1,"𞤫"],[125194,1,"𞤬"],[125195,1,"𞤭"],[125196,1,"𞤮"],[125197,1,"𞤯"],[125198,1,"𞤰"],[125199,1,"𞤱"],[125200,1,"𞤲"],[125201,1,"𞤳"],[125202,1,"𞤴"],[125203,1,"𞤵"],[125204,1,"𞤶"],[125205,1,"𞤷"],[125206,1,"𞤸"],[125207,1,"𞤹"],[125208,1,"𞤺"],[125209,1,"𞤻"],[125210,1,"𞤼"],[125211,1,"𞤽"],[125212,1,"𞤾"],[125213,1,"𞤿"],[125214,1,"𞥀"],[125215,1,"𞥁"],[125216,1,"𞥂"],[125217,1,"𞥃"],[[125218,125258],2],[125259,2],[[125260,125263],3],[[125264,125273],2],[[125274,125277],3],[[125278,125279],2],[[125280,126064],3],[[126065,126132],2],[[126133,126208],3],[[126209,126269],2],[[126270,126463],3],[126464,1,"ا"],[126465,1,"ب"],[126466,1,"ج"],[126467,1,"د"],[126468,3],[126469,1,"و"],[126470,1,"ز"],[126471,1,"ح"],[126472,1,"ط"],[126473,1,"ي"],[126474,1,"ك"],[126475,1,"ل"],[126476,1,"م"],[126477,1,"ن"],[126478,1,"س"],[126479,1,"ع"],[126480,1,"ف"],[126481,1,"ص"],[126482,1,"ق"],[126483,1,"ر"],[126484,1,"ش"],[126485,1,"ت"],[126486,1,"ث"],[126487,1,"خ"],[126488,1,"ذ"],[126489,1,"ض"],[126490,1,"ظ"],[126491,1,"غ"],[126492,1,"ٮ"],[126493,1,"ں"],[126494,1,"ڡ"],[126495,1,"ٯ"],[126496,3],[126497,1,"ب"],[126498,1,"ج"],[126499,3],[126500,1,"ه"],[[126501,126502],3],[126503,1,"ح"],[126504,3],[126505,1,"ي"],[126506,1,"ك"],[126507,1,"ل"],[126508,1,"م"],[126509,1,"ن"],[126510,1,"س"],[126511,1,"ع"],[126512,1,"ف"],[126513,1,"ص"],[126514,1,"ق"],[126515,3],[126516,1,"ش"],[126517,1,"ت"],[126518,1,"ث"],[126519,1,"خ"],[126520,3],[126521,1,"ض"],[126522,3],[126523,1,"غ"],[[126524,126529],3],[126530,1,"ج"],[[126531,126534],3],[126535,1,"ح"],[126536,3],[126537,1,"ي"],[126538,3],[126539,1,"ل"],[126540,3],[126541,1,"ن"],[126542,1,"س"],[126543,1,"ع"],[126544,3],[126545,1,"ص"],[126546,1,"ق"],[126547,3],[126548,1,"ش"],[[126549,126550],3],[126551,1,"خ"],[126552,3],[126553,1,"ض"],[126554,3],[126555,1,"غ"],[126556,3],[126557,1,"ں"],[126558,3],[126559,1,"ٯ"],[126560,3],[126561,1,"ب"],[126562,1,"ج"],[126563,3],[126564,1,"ه"],[[126565,126566],3],[126567,1,"ح"],[126568,1,"ط"],[126569,1,"ي"],[126570,1,"ك"],[126571,3],[126572,1,"م"],[126573,1,"ن"],[126574,1,"س"],[126575,1,"ع"],[126576,1,"ف"],[126577,1,"ص"],[126578,1,"ق"],[126579,3],[126580,1,"ش"],[126581,1,"ت"],[126582,1,"ث"],[126583,1,"خ"],[126584,3],[126585,1,"ض"],[126586,1,"ظ"],[126587,1,"غ"],[126588,1,"ٮ"],[126589,3],[126590,1,"ڡ"],[126591,3],[126592,1,"ا"],[126593,1,"ب"],[126594,1,"ج"],[126595,1,"د"],[126596,1,"ه"],[126597,1,"و"],[126598,1,"ز"],[126599,1,"ح"],[126600,1,"ط"],[126601,1,"ي"],[126602,3],[126603,1,"ل"],[126604,1,"م"],[126605,1,"ن"],[126606,1,"س"],[126607,1,"ع"],[126608,1,"ف"],[126609,1,"ص"],[126610,1,"ق"],[126611,1,"ر"],[126612,1,"ش"],[126613,1,"ت"],[126614,1,"ث"],[126615,1,"خ"],[126616,1,"ذ"],[126617,1,"ض"],[126618,1,"ظ"],[126619,1,"غ"],[[126620,126624],3],[126625,1,"ب"],[126626,1,"ج"],[126627,1,"د"],[126628,3],[126629,1,"و"],[126630,1,"ز"],[126631,1,"ح"],[126632,1,"ط"],[126633,1,"ي"],[126634,3],[126635,1,"ل"],[126636,1,"م"],[126637,1,"ن"],[126638,1,"س"],[126639,1,"ع"],[126640,1,"ف"],[126641,1,"ص"],[126642,1,"ق"],[126643,1,"ر"],[126644,1,"ش"],[126645,1,"ت"],[126646,1,"ث"],[126647,1,"خ"],[126648,1,"ذ"],[126649,1,"ض"],[126650,1,"ظ"],[126651,1,"غ"],[[126652,126703],3],[[126704,126705],2],[[126706,126975],3],[[126976,127019],2],[[127020,127023],3],[[127024,127123],2],[[127124,127135],3],[[127136,127150],2],[[127151,127152],3],[[127153,127166],2],[127167,2],[127168,3],[[127169,127183],2],[127184,3],[[127185,127199],2],[[127200,127221],2],[[127222,127231],3],[127232,3],[127233,5,"0,"],[127234,5,"1,"],[127235,5,"2,"],[127236,5,"3,"],[127237,5,"4,"],[127238,5,"5,"],[127239,5,"6,"],[127240,5,"7,"],[127241,5,"8,"],[127242,5,"9,"],[[127243,127244],2],[[127245,127247],2],[127248,5,"(a)"],[127249,5,"(b)"],[127250,5,"(c)"],[127251,5,"(d)"],[127252,5,"(e)"],[127253,5,"(f)"],[127254,5,"(g)"],[127255,5,"(h)"],[127256,5,"(i)"],[127257,5,"(j)"],[127258,5,"(k)"],[127259,5,"(l)"],[127260,5,"(m)"],[127261,5,"(n)"],[127262,5,"(o)"],[127263,5,"(p)"],[127264,5,"(q)"],[127265,5,"(r)"],[127266,5,"(s)"],[127267,5,"(t)"],[127268,5,"(u)"],[127269,5,"(v)"],[127270,5,"(w)"],[127271,5,"(x)"],[127272,5,"(y)"],[127273,5,"(z)"],[127274,1,"〔s〕"],[127275,1,"c"],[127276,1,"r"],[127277,1,"cd"],[127278,1,"wz"],[127279,2],[127280,1,"a"],[127281,1,"b"],[127282,1,"c"],[127283,1,"d"],[127284,1,"e"],[127285,1,"f"],[127286,1,"g"],[127287,1,"h"],[127288,1,"i"],[127289,1,"j"],[127290,1,"k"],[127291,1,"l"],[127292,1,"m"],[127293,1,"n"],[127294,1,"o"],[127295,1,"p"],[127296,1,"q"],[127297,1,"r"],[127298,1,"s"],[127299,1,"t"],[127300,1,"u"],[127301,1,"v"],[127302,1,"w"],[127303,1,"x"],[127304,1,"y"],[127305,1,"z"],[127306,1,"hv"],[127307,1,"mv"],[127308,1,"sd"],[127309,1,"ss"],[127310,1,"ppv"],[127311,1,"wc"],[[127312,127318],2],[127319,2],[[127320,127326],2],[127327,2],[[127328,127337],2],[127338,1,"mc"],[127339,1,"md"],[127340,1,"mr"],[[127341,127343],2],[[127344,127352],2],[127353,2],[127354,2],[[127355,127356],2],[[127357,127358],2],[127359,2],[[127360,127369],2],[[127370,127373],2],[[127374,127375],2],[127376,1,"dj"],[[127377,127386],2],[[127387,127404],2],[127405,2],[[127406,127461],3],[[127462,127487],2],[127488,1,"ほか"],[127489,1,"ココ"],[127490,1,"サ"],[[127491,127503],3],[127504,1,"手"],[127505,1,"字"],[127506,1,"双"],[127507,1,"デ"],[127508,1,"二"],[127509,1,"多"],[127510,1,"解"],[127511,1,"天"],[127512,1,"交"],[127513,1,"映"],[127514,1,"無"],[127515,1,"料"],[127516,1,"前"],[127517,1,"後"],[127518,1,"再"],[127519,1,"新"],[127520,1,"初"],[127521,1,"終"],[127522,1,"生"],[127523,1,"販"],[127524,1,"声"],[127525,1,"吹"],[127526,1,"演"],[127527,1,"投"],[127528,1,"捕"],[127529,1,"一"],[127530,1,"三"],[127531,1,"遊"],[127532,1,"左"],[127533,1,"中"],[127534,1,"右"],[127535,1,"指"],[127536,1,"走"],[127537,1,"打"],[127538,1,"禁"],[127539,1,"空"],[127540,1,"合"],[127541,1,"満"],[127542,1,"有"],[127543,1,"月"],[127544,1,"申"],[127545,1,"割"],[127546,1,"営"],[127547,1,"配"],[[127548,127551],3],[127552,1,"〔本〕"],[127553,1,"〔三〕"],[127554,1,"〔二〕"],[127555,1,"〔安〕"],[127556,1,"〔点〕"],[127557,1,"〔打〕"],[127558,1,"〔盗〕"],[127559,1,"〔勝〕"],[127560,1,"〔敗〕"],[[127561,127567],3],[127568,1,"得"],[127569,1,"可"],[[127570,127583],3],[[127584,127589],2],[[127590,127743],3],[[127744,127776],2],[[127777,127788],2],[[127789,127791],2],[[127792,127797],2],[127798,2],[[127799,127868],2],[127869,2],[[127870,127871],2],[[127872,127891],2],[[127892,127903],2],[[127904,127940],2],[127941,2],[[127942,127946],2],[[127947,127950],2],[[127951,127955],2],[[127956,127967],2],[[127968,127984],2],[[127985,127991],2],[[127992,127999],2],[[128000,128062],2],[128063,2],[128064,2],[128065,2],[[128066,128247],2],[128248,2],[[128249,128252],2],[[128253,128254],2],[128255,2],[[128256,128317],2],[[128318,128319],2],[[128320,128323],2],[[128324,128330],2],[[128331,128335],2],[[128336,128359],2],[[128360,128377],2],[128378,2],[[128379,128419],2],[128420,2],[[128421,128506],2],[[128507,128511],2],[128512,2],[[128513,128528],2],[128529,2],[[128530,128532],2],[128533,2],[128534,2],[128535,2],[128536,2],[128537,2],[128538,2],[128539,2],[[128540,128542],2],[128543,2],[[128544,128549],2],[[128550,128551],2],[[128552,128555],2],[128556,2],[128557,2],[[128558,128559],2],[[128560,128563],2],[128564,2],[[128565,128576],2],[[128577,128578],2],[[128579,128580],2],[[128581,128591],2],[[128592,128639],2],[[128640,128709],2],[[128710,128719],2],[128720,2],[[128721,128722],2],[[128723,128724],2],[128725,2],[[128726,128727],2],[[128728,128732],3],[[128733,128735],2],[[128736,128748],2],[[128749,128751],3],[[128752,128755],2],[[128756,128758],2],[[128759,128760],2],[128761,2],[128762,2],[[128763,128764],2],[[128765,128767],3],[[128768,128883],2],[[128884,128895],3],[[128896,128980],2],[[128981,128984],2],[[128985,128991],3],[[128992,129003],2],[[129004,129007],3],[129008,2],[[129009,129023],3],[[129024,129035],2],[[129036,129039],3],[[129040,129095],2],[[129096,129103],3],[[129104,129113],2],[[129114,129119],3],[[129120,129159],2],[[129160,129167],3],[[129168,129197],2],[[129198,129199],3],[[129200,129201],2],[[129202,129279],3],[[129280,129291],2],[129292,2],[[129293,129295],2],[[129296,129304],2],[[129305,129310],2],[129311,2],[[129312,129319],2],[[129320,129327],2],[129328,2],[[129329,129330],2],[[129331,129342],2],[129343,2],[[129344,129355],2],[129356,2],[[129357,129359],2],[[129360,129374],2],[[129375,129387],2],[[129388,129392],2],[129393,2],[129394,2],[[129395,129398],2],[[129399,129400],2],[129401,2],[129402,2],[129403,2],[[129404,129407],2],[[129408,129412],2],[[129413,129425],2],[[129426,129431],2],[[129432,129442],2],[[129443,129444],2],[[129445,129450],2],[[129451,129453],2],[[129454,129455],2],[[129456,129465],2],[[129466,129471],2],[129472,2],[[129473,129474],2],[[129475,129482],2],[129483,2],[129484,2],[[129485,129487],2],[[129488,129510],2],[[129511,129535],2],[[129536,129619],2],[[129620,129631],3],[[129632,129645],2],[[129646,129647],3],[[129648,129651],2],[129652,2],[[129653,129655],3],[[129656,129658],2],[[129659,129660],2],[[129661,129663],3],[[129664,129666],2],[[129667,129670],2],[[129671,129679],3],[[129680,129685],2],[[129686,129704],2],[[129705,129708],2],[[129709,129711],3],[[129712,129718],2],[[129719,129722],2],[[129723,129727],3],[[129728,129730],2],[[129731,129733],2],[[129734,129743],3],[[129744,129750],2],[[129751,129753],2],[[129754,129759],3],[[129760,129767],2],[[129768,129775],3],[[129776,129782],2],[[129783,129791],3],[[129792,129938],2],[129939,3],[[129940,129994],2],[[129995,130031],3],[130032,1,"0"],[130033,1,"1"],[130034,1,"2"],[130035,1,"3"],[130036,1,"4"],[130037,1,"5"],[130038,1,"6"],[130039,1,"7"],[130040,1,"8"],[130041,1,"9"],[[130042,131069],3],[[131070,131071],3],[[131072,173782],2],[[173783,173789],2],[[173790,173791],2],[[173792,173823],3],[[173824,177972],2],[[177973,177976],2],[[177977,177983],3],[[177984,178205],2],[[178206,178207],3],[[178208,183969],2],[[183970,183983],3],[[183984,191456],2],[[191457,194559],3],[194560,1,"丽"],[194561,1,"丸"],[194562,1,"乁"],[194563,1,"𠄢"],[194564,1,"你"],[194565,1,"侮"],[194566,1,"侻"],[194567,1,"倂"],[194568,1,"偺"],[194569,1,"備"],[194570,1,"僧"],[194571,1,"像"],[194572,1,"㒞"],[194573,1,"𠘺"],[194574,1,"免"],[194575,1,"兔"],[194576,1,"兤"],[194577,1,"具"],[194578,1,"𠔜"],[194579,1,"㒹"],[194580,1,"內"],[194581,1,"再"],[194582,1,"𠕋"],[194583,1,"冗"],[194584,1,"冤"],[194585,1,"仌"],[194586,1,"冬"],[194587,1,"况"],[194588,1,"𩇟"],[194589,1,"凵"],[194590,1,"刃"],[194591,1,"㓟"],[194592,1,"刻"],[194593,1,"剆"],[194594,1,"割"],[194595,1,"剷"],[194596,1,"㔕"],[194597,1,"勇"],[194598,1,"勉"],[194599,1,"勤"],[194600,1,"勺"],[194601,1,"包"],[194602,1,"匆"],[194603,1,"北"],[194604,1,"卉"],[194605,1,"卑"],[194606,1,"博"],[194607,1,"即"],[194608,1,"卽"],[[194609,194611],1,"卿"],[194612,1,"𠨬"],[194613,1,"灰"],[194614,1,"及"],[194615,1,"叟"],[194616,1,"𠭣"],[194617,1,"叫"],[194618,1,"叱"],[194619,1,"吆"],[194620,1,"咞"],[194621,1,"吸"],[194622,1,"呈"],[194623,1,"周"],[194624,1,"咢"],[194625,1,"哶"],[194626,1,"唐"],[194627,1,"啓"],[194628,1,"啣"],[[194629,194630],1,"善"],[194631,1,"喙"],[194632,1,"喫"],[194633,1,"喳"],[194634,1,"嗂"],[194635,1,"圖"],[194636,1,"嘆"],[194637,1,"圗"],[194638,1,"噑"],[194639,1,"噴"],[194640,1,"切"],[194641,1,"壮"],[194642,1,"城"],[194643,1,"埴"],[194644,1,"堍"],[194645,1,"型"],[194646,1,"堲"],[194647,1,"報"],[194648,1,"墬"],[194649,1,"𡓤"],[194650,1,"売"],[194651,1,"壷"],[194652,1,"夆"],[194653,1,"多"],[194654,1,"夢"],[194655,1,"奢"],[194656,1,"𡚨"],[194657,1,"𡛪"],[194658,1,"姬"],[194659,1,"娛"],[194660,1,"娧"],[194661,1,"姘"],[194662,1,"婦"],[194663,1,"㛮"],[194664,3],[194665,1,"嬈"],[[194666,194667],1,"嬾"],[194668,1,"𡧈"],[194669,1,"寃"],[194670,1,"寘"],[194671,1,"寧"],[194672,1,"寳"],[194673,1,"𡬘"],[194674,1,"寿"],[194675,1,"将"],[194676,3],[194677,1,"尢"],[194678,1,"㞁"],[194679,1,"屠"],[194680,1,"屮"],[194681,1,"峀"],[194682,1,"岍"],[194683,1,"𡷤"],[194684,1,"嵃"],[194685,1,"𡷦"],[194686,1,"嵮"],[194687,1,"嵫"],[194688,1,"嵼"],[194689,1,"巡"],[194690,1,"巢"],[194691,1,"㠯"],[194692,1,"巽"],[194693,1,"帨"],[194694,1,"帽"],[194695,1,"幩"],[194696,1,"㡢"],[194697,1,"𢆃"],[194698,1,"㡼"],[194699,1,"庰"],[194700,1,"庳"],[194701,1,"庶"],[194702,1,"廊"],[194703,1,"𪎒"],[194704,1,"廾"],[[194705,194706],1,"𢌱"],[194707,1,"舁"],[[194708,194709],1,"弢"],[194710,1,"㣇"],[194711,1,"𣊸"],[194712,1,"𦇚"],[194713,1,"形"],[194714,1,"彫"],[194715,1,"㣣"],[194716,1,"徚"],[194717,1,"忍"],[194718,1,"志"],[194719,1,"忹"],[194720,1,"悁"],[194721,1,"㤺"],[194722,1,"㤜"],[194723,1,"悔"],[194724,1,"𢛔"],[194725,1,"惇"],[194726,1,"慈"],[194727,1,"慌"],[194728,1,"慎"],[194729,1,"慌"],[194730,1,"慺"],[194731,1,"憎"],[194732,1,"憲"],[194733,1,"憤"],[194734,1,"憯"],[194735,1,"懞"],[194736,1,"懲"],[194737,1,"懶"],[194738,1,"成"],[194739,1,"戛"],[194740,1,"扝"],[194741,1,"抱"],[194742,1,"拔"],[194743,1,"捐"],[194744,1,"𢬌"],[194745,1,"挽"],[194746,1,"拼"],[194747,1,"捨"],[194748,1,"掃"],[194749,1,"揤"],[194750,1,"𢯱"],[194751,1,"搢"],[194752,1,"揅"],[194753,1,"掩"],[194754,1,"㨮"],[194755,1,"摩"],[194756,1,"摾"],[194757,1,"撝"],[194758,1,"摷"],[194759,1,"㩬"],[194760,1,"敏"],[194761,1,"敬"],[194762,1,"𣀊"],[194763,1,"旣"],[194764,1,"書"],[194765,1,"晉"],[194766,1,"㬙"],[194767,1,"暑"],[194768,1,"㬈"],[194769,1,"㫤"],[194770,1,"冒"],[194771,1,"冕"],[194772,1,"最"],[194773,1,"暜"],[194774,1,"肭"],[194775,1,"䏙"],[194776,1,"朗"],[194777,1,"望"],[194778,1,"朡"],[194779,1,"杞"],[194780,1,"杓"],[194781,1,"𣏃"],[194782,1,"㭉"],[194783,1,"柺"],[194784,1,"枅"],[194785,1,"桒"],[194786,1,"梅"],[194787,1,"𣑭"],[194788,1,"梎"],[194789,1,"栟"],[194790,1,"椔"],[194791,1,"㮝"],[194792,1,"楂"],[194793,1,"榣"],[194794,1,"槪"],[194795,1,"檨"],[194796,1,"𣚣"],[194797,1,"櫛"],[194798,1,"㰘"],[194799,1,"次"],[194800,1,"𣢧"],[194801,1,"歔"],[194802,1,"㱎"],[194803,1,"歲"],[194804,1,"殟"],[194805,1,"殺"],[194806,1,"殻"],[194807,1,"𣪍"],[194808,1,"𡴋"],[194809,1,"𣫺"],[194810,1,"汎"],[194811,1,"𣲼"],[194812,1,"沿"],[194813,1,"泍"],[194814,1,"汧"],[194815,1,"洖"],[194816,1,"派"],[194817,1,"海"],[194818,1,"流"],[194819,1,"浩"],[194820,1,"浸"],[194821,1,"涅"],[194822,1,"𣴞"],[194823,1,"洴"],[194824,1,"港"],[194825,1,"湮"],[194826,1,"㴳"],[194827,1,"滋"],[194828,1,"滇"],[194829,1,"𣻑"],[194830,1,"淹"],[194831,1,"潮"],[194832,1,"𣽞"],[194833,1,"𣾎"],[194834,1,"濆"],[194835,1,"瀹"],[194836,1,"瀞"],[194837,1,"瀛"],[194838,1,"㶖"],[194839,1,"灊"],[194840,1,"災"],[194841,1,"灷"],[194842,1,"炭"],[194843,1,"𠔥"],[194844,1,"煅"],[194845,1,"𤉣"],[194846,1,"熜"],[194847,3],[194848,1,"爨"],[194849,1,"爵"],[194850,1,"牐"],[194851,1,"𤘈"],[194852,1,"犀"],[194853,1,"犕"],[194854,1,"𤜵"],[194855,1,"𤠔"],[194856,1,"獺"],[194857,1,"王"],[194858,1,"㺬"],[194859,1,"玥"],[[194860,194861],1,"㺸"],[194862,1,"瑇"],[194863,1,"瑜"],[194864,1,"瑱"],[194865,1,"璅"],[194866,1,"瓊"],[194867,1,"㼛"],[194868,1,"甤"],[194869,1,"𤰶"],[194870,1,"甾"],[194871,1,"𤲒"],[194872,1,"異"],[194873,1,"𢆟"],[194874,1,"瘐"],[194875,1,"𤾡"],[194876,1,"𤾸"],[194877,1,"𥁄"],[194878,1,"㿼"],[194879,1,"䀈"],[194880,1,"直"],[194881,1,"𥃳"],[194882,1,"𥃲"],[194883,1,"𥄙"],[194884,1,"𥄳"],[194885,1,"眞"],[[194886,194887],1,"真"],[194888,1,"睊"],[194889,1,"䀹"],[194890,1,"瞋"],[194891,1,"䁆"],[194892,1,"䂖"],[194893,1,"𥐝"],[194894,1,"硎"],[194895,1,"碌"],[194896,1,"磌"],[194897,1,"䃣"],[194898,1,"𥘦"],[194899,1,"祖"],[194900,1,"𥚚"],[194901,1,"𥛅"],[194902,1,"福"],[194903,1,"秫"],[194904,1,"䄯"],[194905,1,"穀"],[194906,1,"穊"],[194907,1,"穏"],[194908,1,"𥥼"],[[194909,194910],1,"𥪧"],[194911,3],[194912,1,"䈂"],[194913,1,"𥮫"],[194914,1,"篆"],[194915,1,"築"],[194916,1,"䈧"],[194917,1,"𥲀"],[194918,1,"糒"],[194919,1,"䊠"],[194920,1,"糨"],[194921,1,"糣"],[194922,1,"紀"],[194923,1,"𥾆"],[194924,1,"絣"],[194925,1,"䌁"],[194926,1,"緇"],[194927,1,"縂"],[194928,1,"繅"],[194929,1,"䌴"],[194930,1,"𦈨"],[194931,1,"𦉇"],[194932,1,"䍙"],[194933,1,"𦋙"],[194934,1,"罺"],[194935,1,"𦌾"],[194936,1,"羕"],[194937,1,"翺"],[194938,1,"者"],[194939,1,"𦓚"],[194940,1,"𦔣"],[194941,1,"聠"],[194942,1,"𦖨"],[194943,1,"聰"],[194944,1,"𣍟"],[194945,1,"䏕"],[194946,1,"育"],[194947,1,"脃"],[194948,1,"䐋"],[194949,1,"脾"],[194950,1,"媵"],[194951,1,"𦞧"],[194952,1,"𦞵"],[194953,1,"𣎓"],[194954,1,"𣎜"],[194955,1,"舁"],[194956,1,"舄"],[194957,1,"辞"],[194958,1,"䑫"],[194959,1,"芑"],[194960,1,"芋"],[194961,1,"芝"],[194962,1,"劳"],[194963,1,"花"],[194964,1,"芳"],[194965,1,"芽"],[194966,1,"苦"],[194967,1,"𦬼"],[194968,1,"若"],[194969,1,"茝"],[194970,1,"荣"],[194971,1,"莭"],[194972,1,"茣"],[194973,1,"莽"],[194974,1,"菧"],[194975,1,"著"],[194976,1,"荓"],[194977,1,"菊"],[194978,1,"菌"],[194979,1,"菜"],[194980,1,"𦰶"],[194981,1,"𦵫"],[194982,1,"𦳕"],[194983,1,"䔫"],[194984,1,"蓱"],[194985,1,"蓳"],[194986,1,"蔖"],[194987,1,"𧏊"],[194988,1,"蕤"],[194989,1,"𦼬"],[194990,1,"䕝"],[194991,1,"䕡"],[194992,1,"𦾱"],[194993,1,"𧃒"],[194994,1,"䕫"],[194995,1,"虐"],[194996,1,"虜"],[194997,1,"虧"],[194998,1,"虩"],[194999,1,"蚩"],[195000,1,"蚈"],[195001,1,"蜎"],[195002,1,"蛢"],[195003,1,"蝹"],[195004,1,"蜨"],[195005,1,"蝫"],[195006,1,"螆"],[195007,3],[195008,1,"蟡"],[195009,1,"蠁"],[195010,1,"䗹"],[195011,1,"衠"],[195012,1,"衣"],[195013,1,"𧙧"],[195014,1,"裗"],[195015,1,"裞"],[195016,1,"䘵"],[195017,1,"裺"],[195018,1,"㒻"],[195019,1,"𧢮"],[195020,1,"𧥦"],[195021,1,"䚾"],[195022,1,"䛇"],[195023,1,"誠"],[195024,1,"諭"],[195025,1,"變"],[195026,1,"豕"],[195027,1,"𧲨"],[195028,1,"貫"],[195029,1,"賁"],[195030,1,"贛"],[195031,1,"起"],[195032,1,"𧼯"],[195033,1,"𠠄"],[195034,1,"跋"],[195035,1,"趼"],[195036,1,"跰"],[195037,1,"𠣞"],[195038,1,"軔"],[195039,1,"輸"],[195040,1,"𨗒"],[195041,1,"𨗭"],[195042,1,"邔"],[195043,1,"郱"],[195044,1,"鄑"],[195045,1,"𨜮"],[195046,1,"鄛"],[195047,1,"鈸"],[195048,1,"鋗"],[195049,1,"鋘"],[195050,1,"鉼"],[195051,1,"鏹"],[195052,1,"鐕"],[195053,1,"𨯺"],[195054,1,"開"],[195055,1,"䦕"],[195056,1,"閷"],[195057,1,"𨵷"],[195058,1,"䧦"],[195059,1,"雃"],[195060,1,"嶲"],[195061,1,"霣"],[195062,1,"𩅅"],[195063,1,"𩈚"],[195064,1,"䩮"],[195065,1,"䩶"],[195066,1,"韠"],[195067,1,"𩐊"],[195068,1,"䪲"],[195069,1,"𩒖"],[[195070,195071],1,"頋"],[195072,1,"頩"],[195073,1,"𩖶"],[195074,1,"飢"],[195075,1,"䬳"],[195076,1,"餩"],[195077,1,"馧"],[195078,1,"駂"],[195079,1,"駾"],[195080,1,"䯎"],[195081,1,"𩬰"],[195082,1,"鬒"],[195083,1,"鱀"],[195084,1,"鳽"],[195085,1,"䳎"],[195086,1,"䳭"],[195087,1,"鵧"],[195088,1,"𪃎"],[195089,1,"䳸"],[195090,1,"𪄅"],[195091,1,"𪈎"],[195092,1,"𪊑"],[195093,1,"麻"],[195094,1,"䵖"],[195095,1,"黹"],[195096,1,"黾"],[195097,1,"鼅"],[195098,1,"鼏"],[195099,1,"鼖"],[195100,1,"鼻"],[195101,1,"𪘀"],[[195102,196605],3],[[196606,196607],3],[[196608,201546],2],[[201547,262141],3],[[262142,262143],3],[[262144,327677],3],[[327678,327679],3],[[327680,393213],3],[[393214,393215],3],[[393216,458749],3],[[458750,458751],3],[[458752,524285],3],[[524286,524287],3],[[524288,589821],3],[[589822,589823],3],[[589824,655357],3],[[655358,655359],3],[[655360,720893],3],[[720894,720895],3],[[720896,786429],3],[[786430,786431],3],[[786432,851965],3],[[851966,851967],3],[[851968,917501],3],[[917502,917503],3],[917504,3],[917505,3],[[917506,917535],3],[[917536,917631],3],[[917632,917759],3],[[917760,917999],7],[[918000,983037],3],[[983038,983039],3],[[983040,1048573],3],[[1048574,1048575],3],[[1048576,1114109],3],[[1114110,1114111],3]] \ No newline at end of file diff --git a/ts-ticket-office-service/node_modules/tr46/lib/regexes.js b/ts-ticket-office-service/node_modules/tr46/lib/regexes.js new file mode 100644 index 000000000..4dd8051e2 --- /dev/null +++ b/ts-ticket-office-service/node_modules/tr46/lib/regexes.js @@ -0,0 +1,29 @@ +"use strict"; + +const combiningMarks = /[\u0300-\u036F\u0483-\u0489\u0591-\u05BD\u05BF\u05C1\u05C2\u05C4\u05C5\u05C7\u0610-\u061A\u064B-\u065F\u0670\u06D6-\u06DC\u06DF-\u06E4\u06E7\u06E8\u06EA-\u06ED\u0711\u0730-\u074A\u07A6-\u07B0\u07EB-\u07F3\u07FD\u0816-\u0819\u081B-\u0823\u0825-\u0827\u0829-\u082D\u0859-\u085B\u0898-\u089F\u08CA-\u08E1\u08E3-\u0903\u093A-\u093C\u093E-\u094F\u0951-\u0957\u0962\u0963\u0981-\u0983\u09BC\u09BE-\u09C4\u09C7\u09C8\u09CB-\u09CD\u09D7\u09E2\u09E3\u09FE\u0A01-\u0A03\u0A3C\u0A3E-\u0A42\u0A47\u0A48\u0A4B-\u0A4D\u0A51\u0A70\u0A71\u0A75\u0A81-\u0A83\u0ABC\u0ABE-\u0AC5\u0AC7-\u0AC9\u0ACB-\u0ACD\u0AE2\u0AE3\u0AFA-\u0AFF\u0B01-\u0B03\u0B3C\u0B3E-\u0B44\u0B47\u0B48\u0B4B-\u0B4D\u0B55-\u0B57\u0B62\u0B63\u0B82\u0BBE-\u0BC2\u0BC6-\u0BC8\u0BCA-\u0BCD\u0BD7\u0C00-\u0C04\u0C3C\u0C3E-\u0C44\u0C46-\u0C48\u0C4A-\u0C4D\u0C55\u0C56\u0C62\u0C63\u0C81-\u0C83\u0CBC\u0CBE-\u0CC4\u0CC6-\u0CC8\u0CCA-\u0CCD\u0CD5\u0CD6\u0CE2\u0CE3\u0D00-\u0D03\u0D3B\u0D3C\u0D3E-\u0D44\u0D46-\u0D48\u0D4A-\u0D4D\u0D57\u0D62\u0D63\u0D81-\u0D83\u0DCA\u0DCF-\u0DD4\u0DD6\u0DD8-\u0DDF\u0DF2\u0DF3\u0E31\u0E34-\u0E3A\u0E47-\u0E4E\u0EB1\u0EB4-\u0EBC\u0EC8-\u0ECD\u0F18\u0F19\u0F35\u0F37\u0F39\u0F3E\u0F3F\u0F71-\u0F84\u0F86\u0F87\u0F8D-\u0F97\u0F99-\u0FBC\u0FC6\u102B-\u103E\u1056-\u1059\u105E-\u1060\u1062-\u1064\u1067-\u106D\u1071-\u1074\u1082-\u108D\u108F\u109A-\u109D\u135D-\u135F\u1712-\u1715\u1732-\u1734\u1752\u1753\u1772\u1773\u17B4-\u17D3\u17DD\u180B-\u180D\u180F\u1885\u1886\u18A9\u1920-\u192B\u1930-\u193B\u1A17-\u1A1B\u1A55-\u1A5E\u1A60-\u1A7C\u1A7F\u1AB0-\u1ACE\u1B00-\u1B04\u1B34-\u1B44\u1B6B-\u1B73\u1B80-\u1B82\u1BA1-\u1BAD\u1BE6-\u1BF3\u1C24-\u1C37\u1CD0-\u1CD2\u1CD4-\u1CE8\u1CED\u1CF4\u1CF7-\u1CF9\u1DC0-\u1DFF\u20D0-\u20F0\u2CEF-\u2CF1\u2D7F\u2DE0-\u2DFF\u302A-\u302F\u3099\u309A\uA66F-\uA672\uA674-\uA67D\uA69E\uA69F\uA6F0\uA6F1\uA802\uA806\uA80B\uA823-\uA827\uA82C\uA880\uA881\uA8B4-\uA8C5\uA8E0-\uA8F1\uA8FF\uA926-\uA92D\uA947-\uA953\uA980-\uA983\uA9B3-\uA9C0\uA9E5\uAA29-\uAA36\uAA43\uAA4C\uAA4D\uAA7B-\uAA7D\uAAB0\uAAB2-\uAAB4\uAAB7\uAAB8\uAABE\uAABF\uAAC1\uAAEB-\uAAEF\uAAF5\uAAF6\uABE3-\uABEA\uABEC\uABED\uFB1E\uFE00-\uFE0F\uFE20-\uFE2F\u{101FD}\u{102E0}\u{10376}-\u{1037A}\u{10A01}-\u{10A03}\u{10A05}\u{10A06}\u{10A0C}-\u{10A0F}\u{10A38}-\u{10A3A}\u{10A3F}\u{10AE5}\u{10AE6}\u{10D24}-\u{10D27}\u{10EAB}\u{10EAC}\u{10F46}-\u{10F50}\u{10F82}-\u{10F85}\u{11000}-\u{11002}\u{11038}-\u{11046}\u{11070}\u{11073}\u{11074}\u{1107F}-\u{11082}\u{110B0}-\u{110BA}\u{110C2}\u{11100}-\u{11102}\u{11127}-\u{11134}\u{11145}\u{11146}\u{11173}\u{11180}-\u{11182}\u{111B3}-\u{111C0}\u{111C9}-\u{111CC}\u{111CE}\u{111CF}\u{1122C}-\u{11237}\u{1123E}\u{112DF}-\u{112EA}\u{11300}-\u{11303}\u{1133B}\u{1133C}\u{1133E}-\u{11344}\u{11347}\u{11348}\u{1134B}-\u{1134D}\u{11357}\u{11362}\u{11363}\u{11366}-\u{1136C}\u{11370}-\u{11374}\u{11435}-\u{11446}\u{1145E}\u{114B0}-\u{114C3}\u{115AF}-\u{115B5}\u{115B8}-\u{115C0}\u{115DC}\u{115DD}\u{11630}-\u{11640}\u{116AB}-\u{116B7}\u{1171D}-\u{1172B}\u{1182C}-\u{1183A}\u{11930}-\u{11935}\u{11937}\u{11938}\u{1193B}-\u{1193E}\u{11940}\u{11942}\u{11943}\u{119D1}-\u{119D7}\u{119DA}-\u{119E0}\u{119E4}\u{11A01}-\u{11A0A}\u{11A33}-\u{11A39}\u{11A3B}-\u{11A3E}\u{11A47}\u{11A51}-\u{11A5B}\u{11A8A}-\u{11A99}\u{11C2F}-\u{11C36}\u{11C38}-\u{11C3F}\u{11C92}-\u{11CA7}\u{11CA9}-\u{11CB6}\u{11D31}-\u{11D36}\u{11D3A}\u{11D3C}\u{11D3D}\u{11D3F}-\u{11D45}\u{11D47}\u{11D8A}-\u{11D8E}\u{11D90}\u{11D91}\u{11D93}-\u{11D97}\u{11EF3}-\u{11EF6}\u{16AF0}-\u{16AF4}\u{16B30}-\u{16B36}\u{16F4F}\u{16F51}-\u{16F87}\u{16F8F}-\u{16F92}\u{16FE4}\u{16FF0}\u{16FF1}\u{1BC9D}\u{1BC9E}\u{1CF00}-\u{1CF2D}\u{1CF30}-\u{1CF46}\u{1D165}-\u{1D169}\u{1D16D}-\u{1D172}\u{1D17B}-\u{1D182}\u{1D185}-\u{1D18B}\u{1D1AA}-\u{1D1AD}\u{1D242}-\u{1D244}\u{1DA00}-\u{1DA36}\u{1DA3B}-\u{1DA6C}\u{1DA75}\u{1DA84}\u{1DA9B}-\u{1DA9F}\u{1DAA1}-\u{1DAAF}\u{1E000}-\u{1E006}\u{1E008}-\u{1E018}\u{1E01B}-\u{1E021}\u{1E023}\u{1E024}\u{1E026}-\u{1E02A}\u{1E130}-\u{1E136}\u{1E2AE}\u{1E2EC}-\u{1E2EF}\u{1E8D0}-\u{1E8D6}\u{1E944}-\u{1E94A}\u{E0100}-\u{E01EF}]/u; +const combiningClassVirama = /[\u094D\u09CD\u0A4D\u0ACD\u0B4D\u0BCD\u0C4D\u0CCD\u0D3B\u0D3C\u0D4D\u0DCA\u0E3A\u0EBA\u0F84\u1039\u103A\u1714\u1734\u17D2\u1A60\u1B44\u1BAA\u1BAB\u1BF2\u1BF3\u2D7F\uA806\uA8C4\uA953\uA9C0\uAAF6\uABED\u{10A3F}\u{11046}\u{1107F}\u{110B9}\u{11133}\u{11134}\u{111C0}\u{11235}\u{112EA}\u{1134D}\u{11442}\u{114C2}\u{115BF}\u{1163F}\u{116B6}\u{1172B}\u{11839}\u{119E0}\u{11A34}\u{11A47}\u{11A99}\u{11C3F}\u{11D44}\u{11D45}\u{11D97}]/u; +const validZWNJ = /[\u0620\u0626\u0628\u062A-\u062E\u0633-\u063F\u0641-\u0647\u0649\u064A\u066E\u066F\u0678-\u0687\u069A-\u06BF\u06C1\u06C2\u06CC\u06CE\u06D0\u06D1\u06FA-\u06FC\u06FF\u0712-\u0714\u071A-\u071D\u071F-\u0727\u0729\u072B\u072D\u072E\u074E-\u0758\u075C-\u076A\u076D-\u0770\u0772\u0775-\u0777\u077A-\u077F\u07CA-\u07EA\u0841-\u0845\u0848\u084A-\u0853\u0855\u0860\u0862-\u0865\u0868\u08A0-\u08A9\u08AF\u08B0\u08B3\u08B4\u08B6-\u08B8\u08BA-\u08BD\u1807\u1820-\u1878\u1887-\u18A8\u18AA\uA840-\uA872\u{10AC0}-\u{10AC4}\u{10ACD}\u{10AD3}-\u{10ADC}\u{10ADE}-\u{10AE0}\u{10AEB}-\u{10AEE}\u{10B80}\u{10B82}\u{10B86}-\u{10B88}\u{10B8A}\u{10B8B}\u{10B8D}\u{10B90}\u{10BAD}\u{10BAE}\u{10D00}-\u{10D21}\u{10D23}\u{10F30}-\u{10F32}\u{10F34}-\u{10F44}\u{10F51}-\u{10F53}\u{1E900}-\u{1E943}][\xAD\u0300-\u036F\u0483-\u0489\u0591-\u05BD\u05BF\u05C1\u05C2\u05C4\u05C5\u05C7\u0610-\u061A\u061C\u064B-\u065F\u0670\u06D6-\u06DC\u06DF-\u06E4\u06E7\u06E8\u06EA-\u06ED\u070F\u0711\u0730-\u074A\u07A6-\u07B0\u07EB-\u07F3\u07FD\u0816-\u0819\u081B-\u0823\u0825-\u0827\u0829-\u082D\u0859-\u085B\u08D3-\u08E1\u08E3-\u0902\u093A\u093C\u0941-\u0948\u094D\u0951-\u0957\u0962\u0963\u0981\u09BC\u09C1-\u09C4\u09CD\u09E2\u09E3\u09FE\u0A01\u0A02\u0A3C\u0A41\u0A42\u0A47\u0A48\u0A4B-\u0A4D\u0A51\u0A70\u0A71\u0A75\u0A81\u0A82\u0ABC\u0AC1-\u0AC5\u0AC7\u0AC8\u0ACD\u0AE2\u0AE3\u0AFA-\u0AFF\u0B01\u0B3C\u0B3F\u0B41-\u0B44\u0B4D\u0B56\u0B62\u0B63\u0B82\u0BC0\u0BCD\u0C00\u0C04\u0C3E-\u0C40\u0C46-\u0C48\u0C4A-\u0C4D\u0C55\u0C56\u0C62\u0C63\u0C81\u0CBC\u0CBF\u0CC6\u0CCC\u0CCD\u0CE2\u0CE3\u0D00\u0D01\u0D3B\u0D3C\u0D41-\u0D44\u0D4D\u0D62\u0D63\u0DCA\u0DD2-\u0DD4\u0DD6\u0E31\u0E34-\u0E3A\u0E47-\u0E4E\u0EB1\u0EB4-\u0EBC\u0EC8-\u0ECD\u0F18\u0F19\u0F35\u0F37\u0F39\u0F71-\u0F7E\u0F80-\u0F84\u0F86\u0F87\u0F8D-\u0F97\u0F99-\u0FBC\u0FC6\u102D-\u1030\u1032-\u1037\u1039\u103A\u103D\u103E\u1058\u1059\u105E-\u1060\u1071-\u1074\u1082\u1085\u1086\u108D\u109D\u135D-\u135F\u1712-\u1714\u1732-\u1734\u1752\u1753\u1772\u1773\u17B4\u17B5\u17B7-\u17BD\u17C6\u17C9-\u17D3\u17DD\u180B-\u180D\u1885\u1886\u18A9\u1920-\u1922\u1927\u1928\u1932\u1939-\u193B\u1A17\u1A18\u1A1B\u1A56\u1A58-\u1A5E\u1A60\u1A62\u1A65-\u1A6C\u1A73-\u1A7C\u1A7F\u1AB0-\u1ABE\u1B00-\u1B03\u1B34\u1B36-\u1B3A\u1B3C\u1B42\u1B6B-\u1B73\u1B80\u1B81\u1BA2-\u1BA5\u1BA8\u1BA9\u1BAB-\u1BAD\u1BE6\u1BE8\u1BE9\u1BED\u1BEF-\u1BF1\u1C2C-\u1C33\u1C36\u1C37\u1CD0-\u1CD2\u1CD4-\u1CE0\u1CE2-\u1CE8\u1CED\u1CF4\u1CF8\u1CF9\u1DC0-\u1DF9\u1DFB-\u1DFF\u200B\u200E\u200F\u202A-\u202E\u2060-\u2064\u206A-\u206F\u20D0-\u20F0\u2CEF-\u2CF1\u2D7F\u2DE0-\u2DFF\u302A-\u302D\u3099\u309A\uA66F-\uA672\uA674-\uA67D\uA69E\uA69F\uA6F0\uA6F1\uA802\uA806\uA80B\uA825\uA826\uA8C4\uA8C5\uA8E0-\uA8F1\uA8FF\uA926-\uA92D\uA947-\uA951\uA980-\uA982\uA9B3\uA9B6-\uA9B9\uA9BC\uA9BD\uA9E5\uAA29-\uAA2E\uAA31\uAA32\uAA35\uAA36\uAA43\uAA4C\uAA7C\uAAB0\uAAB2-\uAAB4\uAAB7\uAAB8\uAABE\uAABF\uAAC1\uAAEC\uAAED\uAAF6\uABE5\uABE8\uABED\uFB1E\uFE00-\uFE0F\uFE20-\uFE2F\uFEFF\uFFF9-\uFFFB\u{101FD}\u{102E0}\u{10376}-\u{1037A}\u{10A01}-\u{10A03}\u{10A05}\u{10A06}\u{10A0C}-\u{10A0F}\u{10A38}-\u{10A3A}\u{10A3F}\u{10AE5}\u{10AE6}\u{10D24}-\u{10D27}\u{10F46}-\u{10F50}\u{11001}\u{11038}-\u{11046}\u{1107F}-\u{11081}\u{110B3}-\u{110B6}\u{110B9}\u{110BA}\u{11100}-\u{11102}\u{11127}-\u{1112B}\u{1112D}-\u{11134}\u{11173}\u{11180}\u{11181}\u{111B6}-\u{111BE}\u{111C9}-\u{111CC}\u{1122F}-\u{11231}\u{11234}\u{11236}\u{11237}\u{1123E}\u{112DF}\u{112E3}-\u{112EA}\u{11300}\u{11301}\u{1133B}\u{1133C}\u{11340}\u{11366}-\u{1136C}\u{11370}-\u{11374}\u{11438}-\u{1143F}\u{11442}-\u{11444}\u{11446}\u{1145E}\u{114B3}-\u{114B8}\u{114BA}\u{114BF}\u{114C0}\u{114C2}\u{114C3}\u{115B2}-\u{115B5}\u{115BC}\u{115BD}\u{115BF}\u{115C0}\u{115DC}\u{115DD}\u{11633}-\u{1163A}\u{1163D}\u{1163F}\u{11640}\u{116AB}\u{116AD}\u{116B0}-\u{116B5}\u{116B7}\u{1171D}-\u{1171F}\u{11722}-\u{11725}\u{11727}-\u{1172B}\u{1182F}-\u{11837}\u{11839}\u{1183A}\u{119D4}-\u{119D7}\u{119DA}\u{119DB}\u{119E0}\u{11A01}-\u{11A0A}\u{11A33}-\u{11A38}\u{11A3B}-\u{11A3E}\u{11A47}\u{11A51}-\u{11A56}\u{11A59}-\u{11A5B}\u{11A8A}-\u{11A96}\u{11A98}\u{11A99}\u{11C30}-\u{11C36}\u{11C38}-\u{11C3D}\u{11C3F}\u{11C92}-\u{11CA7}\u{11CAA}-\u{11CB0}\u{11CB2}\u{11CB3}\u{11CB5}\u{11CB6}\u{11D31}-\u{11D36}\u{11D3A}\u{11D3C}\u{11D3D}\u{11D3F}-\u{11D45}\u{11D47}\u{11D90}\u{11D91}\u{11D95}\u{11D97}\u{11EF3}\u{11EF4}\u{13430}-\u{13438}\u{16AF0}-\u{16AF4}\u{16B30}-\u{16B36}\u{16F4F}\u{16F8F}-\u{16F92}\u{1BC9D}\u{1BC9E}\u{1BCA0}-\u{1BCA3}\u{1D167}-\u{1D169}\u{1D173}-\u{1D182}\u{1D185}-\u{1D18B}\u{1D1AA}-\u{1D1AD}\u{1D242}-\u{1D244}\u{1DA00}-\u{1DA36}\u{1DA3B}-\u{1DA6C}\u{1DA75}\u{1DA84}\u{1DA9B}-\u{1DA9F}\u{1DAA1}-\u{1DAAF}\u{1E000}-\u{1E006}\u{1E008}-\u{1E018}\u{1E01B}-\u{1E021}\u{1E023}\u{1E024}\u{1E026}-\u{1E02A}\u{1E130}-\u{1E136}\u{1E2EC}-\u{1E2EF}\u{1E8D0}-\u{1E8D6}\u{1E944}-\u{1E94B}\u{E0001}\u{E0020}-\u{E007F}\u{E0100}-\u{E01EF}]*\u200C[\xAD\u0300-\u036F\u0483-\u0489\u0591-\u05BD\u05BF\u05C1\u05C2\u05C4\u05C5\u05C7\u0610-\u061A\u061C\u064B-\u065F\u0670\u06D6-\u06DC\u06DF-\u06E4\u06E7\u06E8\u06EA-\u06ED\u070F\u0711\u0730-\u074A\u07A6-\u07B0\u07EB-\u07F3\u07FD\u0816-\u0819\u081B-\u0823\u0825-\u0827\u0829-\u082D\u0859-\u085B\u08D3-\u08E1\u08E3-\u0902\u093A\u093C\u0941-\u0948\u094D\u0951-\u0957\u0962\u0963\u0981\u09BC\u09C1-\u09C4\u09CD\u09E2\u09E3\u09FE\u0A01\u0A02\u0A3C\u0A41\u0A42\u0A47\u0A48\u0A4B-\u0A4D\u0A51\u0A70\u0A71\u0A75\u0A81\u0A82\u0ABC\u0AC1-\u0AC5\u0AC7\u0AC8\u0ACD\u0AE2\u0AE3\u0AFA-\u0AFF\u0B01\u0B3C\u0B3F\u0B41-\u0B44\u0B4D\u0B56\u0B62\u0B63\u0B82\u0BC0\u0BCD\u0C00\u0C04\u0C3E-\u0C40\u0C46-\u0C48\u0C4A-\u0C4D\u0C55\u0C56\u0C62\u0C63\u0C81\u0CBC\u0CBF\u0CC6\u0CCC\u0CCD\u0CE2\u0CE3\u0D00\u0D01\u0D3B\u0D3C\u0D41-\u0D44\u0D4D\u0D62\u0D63\u0DCA\u0DD2-\u0DD4\u0DD6\u0E31\u0E34-\u0E3A\u0E47-\u0E4E\u0EB1\u0EB4-\u0EBC\u0EC8-\u0ECD\u0F18\u0F19\u0F35\u0F37\u0F39\u0F71-\u0F7E\u0F80-\u0F84\u0F86\u0F87\u0F8D-\u0F97\u0F99-\u0FBC\u0FC6\u102D-\u1030\u1032-\u1037\u1039\u103A\u103D\u103E\u1058\u1059\u105E-\u1060\u1071-\u1074\u1082\u1085\u1086\u108D\u109D\u135D-\u135F\u1712-\u1714\u1732-\u1734\u1752\u1753\u1772\u1773\u17B4\u17B5\u17B7-\u17BD\u17C6\u17C9-\u17D3\u17DD\u180B-\u180D\u1885\u1886\u18A9\u1920-\u1922\u1927\u1928\u1932\u1939-\u193B\u1A17\u1A18\u1A1B\u1A56\u1A58-\u1A5E\u1A60\u1A62\u1A65-\u1A6C\u1A73-\u1A7C\u1A7F\u1AB0-\u1ABE\u1B00-\u1B03\u1B34\u1B36-\u1B3A\u1B3C\u1B42\u1B6B-\u1B73\u1B80\u1B81\u1BA2-\u1BA5\u1BA8\u1BA9\u1BAB-\u1BAD\u1BE6\u1BE8\u1BE9\u1BED\u1BEF-\u1BF1\u1C2C-\u1C33\u1C36\u1C37\u1CD0-\u1CD2\u1CD4-\u1CE0\u1CE2-\u1CE8\u1CED\u1CF4\u1CF8\u1CF9\u1DC0-\u1DF9\u1DFB-\u1DFF\u200B\u200E\u200F\u202A-\u202E\u2060-\u2064\u206A-\u206F\u20D0-\u20F0\u2CEF-\u2CF1\u2D7F\u2DE0-\u2DFF\u302A-\u302D\u3099\u309A\uA66F-\uA672\uA674-\uA67D\uA69E\uA69F\uA6F0\uA6F1\uA802\uA806\uA80B\uA825\uA826\uA8C4\uA8C5\uA8E0-\uA8F1\uA8FF\uA926-\uA92D\uA947-\uA951\uA980-\uA982\uA9B3\uA9B6-\uA9B9\uA9BC\uA9BD\uA9E5\uAA29-\uAA2E\uAA31\uAA32\uAA35\uAA36\uAA43\uAA4C\uAA7C\uAAB0\uAAB2-\uAAB4\uAAB7\uAAB8\uAABE\uAABF\uAAC1\uAAEC\uAAED\uAAF6\uABE5\uABE8\uABED\uFB1E\uFE00-\uFE0F\uFE20-\uFE2F\uFEFF\uFFF9-\uFFFB\u{101FD}\u{102E0}\u{10376}-\u{1037A}\u{10A01}-\u{10A03}\u{10A05}\u{10A06}\u{10A0C}-\u{10A0F}\u{10A38}-\u{10A3A}\u{10A3F}\u{10AE5}\u{10AE6}\u{10D24}-\u{10D27}\u{10F46}-\u{10F50}\u{11001}\u{11038}-\u{11046}\u{1107F}-\u{11081}\u{110B3}-\u{110B6}\u{110B9}\u{110BA}\u{11100}-\u{11102}\u{11127}-\u{1112B}\u{1112D}-\u{11134}\u{11173}\u{11180}\u{11181}\u{111B6}-\u{111BE}\u{111C9}-\u{111CC}\u{1122F}-\u{11231}\u{11234}\u{11236}\u{11237}\u{1123E}\u{112DF}\u{112E3}-\u{112EA}\u{11300}\u{11301}\u{1133B}\u{1133C}\u{11340}\u{11366}-\u{1136C}\u{11370}-\u{11374}\u{11438}-\u{1143F}\u{11442}-\u{11444}\u{11446}\u{1145E}\u{114B3}-\u{114B8}\u{114BA}\u{114BF}\u{114C0}\u{114C2}\u{114C3}\u{115B2}-\u{115B5}\u{115BC}\u{115BD}\u{115BF}\u{115C0}\u{115DC}\u{115DD}\u{11633}-\u{1163A}\u{1163D}\u{1163F}\u{11640}\u{116AB}\u{116AD}\u{116B0}-\u{116B5}\u{116B7}\u{1171D}-\u{1171F}\u{11722}-\u{11725}\u{11727}-\u{1172B}\u{1182F}-\u{11837}\u{11839}\u{1183A}\u{119D4}-\u{119D7}\u{119DA}\u{119DB}\u{119E0}\u{11A01}-\u{11A0A}\u{11A33}-\u{11A38}\u{11A3B}-\u{11A3E}\u{11A47}\u{11A51}-\u{11A56}\u{11A59}-\u{11A5B}\u{11A8A}-\u{11A96}\u{11A98}\u{11A99}\u{11C30}-\u{11C36}\u{11C38}-\u{11C3D}\u{11C3F}\u{11C92}-\u{11CA7}\u{11CAA}-\u{11CB0}\u{11CB2}\u{11CB3}\u{11CB5}\u{11CB6}\u{11D31}-\u{11D36}\u{11D3A}\u{11D3C}\u{11D3D}\u{11D3F}-\u{11D45}\u{11D47}\u{11D90}\u{11D91}\u{11D95}\u{11D97}\u{11EF3}\u{11EF4}\u{13430}-\u{13438}\u{16AF0}-\u{16AF4}\u{16B30}-\u{16B36}\u{16F4F}\u{16F8F}-\u{16F92}\u{1BC9D}\u{1BC9E}\u{1BCA0}-\u{1BCA3}\u{1D167}-\u{1D169}\u{1D173}-\u{1D182}\u{1D185}-\u{1D18B}\u{1D1AA}-\u{1D1AD}\u{1D242}-\u{1D244}\u{1DA00}-\u{1DA36}\u{1DA3B}-\u{1DA6C}\u{1DA75}\u{1DA84}\u{1DA9B}-\u{1DA9F}\u{1DAA1}-\u{1DAAF}\u{1E000}-\u{1E006}\u{1E008}-\u{1E018}\u{1E01B}-\u{1E021}\u{1E023}\u{1E024}\u{1E026}-\u{1E02A}\u{1E130}-\u{1E136}\u{1E2EC}-\u{1E2EF}\u{1E8D0}-\u{1E8D6}\u{1E944}-\u{1E94B}\u{E0001}\u{E0020}-\u{E007F}\u{E0100}-\u{E01EF}]*[\u0620\u0622-\u063F\u0641-\u064A\u066E\u066F\u0671-\u0673\u0675-\u06D3\u06D5\u06EE\u06EF\u06FA-\u06FC\u06FF\u0710\u0712-\u072F\u074D-\u077F\u07CA-\u07EA\u0840-\u0855\u0860\u0862-\u0865\u0867-\u086A\u08A0-\u08AC\u08AE-\u08B4\u08B6-\u08BD\u1807\u1820-\u1878\u1887-\u18A8\u18AA\uA840-\uA871\u{10AC0}-\u{10AC5}\u{10AC7}\u{10AC9}\u{10ACA}\u{10ACE}-\u{10AD6}\u{10AD8}-\u{10AE1}\u{10AE4}\u{10AEB}-\u{10AEF}\u{10B80}-\u{10B91}\u{10BA9}-\u{10BAE}\u{10D01}-\u{10D23}\u{10F30}-\u{10F44}\u{10F51}-\u{10F54}\u{1E900}-\u{1E943}]/u; +const bidiDomain = /[\u05BE\u05C0\u05C3\u05C6\u05D0-\u05EA\u05EF-\u05F4\u0600-\u0605\u0608\u060B\u060D\u061B-\u064A\u0660-\u0669\u066B-\u066F\u0671-\u06D5\u06DD\u06E5\u06E6\u06EE\u06EF\u06FA-\u070D\u070F\u0710\u0712-\u072F\u074D-\u07A5\u07B1\u07C0-\u07EA\u07F4\u07F5\u07FA\u07FE-\u0815\u081A\u0824\u0828\u0830-\u083E\u0840-\u0858\u085E\u0860-\u086A\u0870-\u088E\u0890\u0891\u08A0-\u08C9\u08E2\u200F\uFB1D\uFB1F-\uFB28\uFB2A-\uFB36\uFB38-\uFB3C\uFB3E\uFB40\uFB41\uFB43\uFB44\uFB46-\uFBC2\uFBD3-\uFD3D\uFD50-\uFD8F\uFD92-\uFDC7\uFDF0-\uFDFC\uFE70-\uFE74\uFE76-\uFEFC\u{10800}-\u{10805}\u{10808}\u{1080A}-\u{10835}\u{10837}\u{10838}\u{1083C}\u{1083F}-\u{10855}\u{10857}-\u{1089E}\u{108A7}-\u{108AF}\u{108E0}-\u{108F2}\u{108F4}\u{108F5}\u{108FB}-\u{1091B}\u{10920}-\u{10939}\u{1093F}\u{10980}-\u{109B7}\u{109BC}-\u{109CF}\u{109D2}-\u{10A00}\u{10A10}-\u{10A13}\u{10A15}-\u{10A17}\u{10A19}-\u{10A35}\u{10A40}-\u{10A48}\u{10A50}-\u{10A58}\u{10A60}-\u{10A9F}\u{10AC0}-\u{10AE4}\u{10AEB}-\u{10AF6}\u{10B00}-\u{10B35}\u{10B40}-\u{10B55}\u{10B58}-\u{10B72}\u{10B78}-\u{10B91}\u{10B99}-\u{10B9C}\u{10BA9}-\u{10BAF}\u{10C00}-\u{10C48}\u{10C80}-\u{10CB2}\u{10CC0}-\u{10CF2}\u{10CFA}-\u{10D23}\u{10D30}-\u{10D39}\u{10E60}-\u{10E7E}\u{10E80}-\u{10EA9}\u{10EAD}\u{10EB0}\u{10EB1}\u{10F00}-\u{10F27}\u{10F30}-\u{10F45}\u{10F51}-\u{10F59}\u{10F70}-\u{10F81}\u{10F86}-\u{10F89}\u{10FB0}-\u{10FCB}\u{10FE0}-\u{10FF6}\u{1E800}-\u{1E8C4}\u{1E8C7}-\u{1E8CF}\u{1E900}-\u{1E943}\u{1E94B}\u{1E950}-\u{1E959}\u{1E95E}\u{1E95F}\u{1EC71}-\u{1ECB4}\u{1ED01}-\u{1ED3D}\u{1EE00}-\u{1EE03}\u{1EE05}-\u{1EE1F}\u{1EE21}\u{1EE22}\u{1EE24}\u{1EE27}\u{1EE29}-\u{1EE32}\u{1EE34}-\u{1EE37}\u{1EE39}\u{1EE3B}\u{1EE42}\u{1EE47}\u{1EE49}\u{1EE4B}\u{1EE4D}-\u{1EE4F}\u{1EE51}\u{1EE52}\u{1EE54}\u{1EE57}\u{1EE59}\u{1EE5B}\u{1EE5D}\u{1EE5F}\u{1EE61}\u{1EE62}\u{1EE64}\u{1EE67}-\u{1EE6A}\u{1EE6C}-\u{1EE72}\u{1EE74}-\u{1EE77}\u{1EE79}-\u{1EE7C}\u{1EE7E}\u{1EE80}-\u{1EE89}\u{1EE8B}-\u{1EE9B}\u{1EEA1}-\u{1EEA3}\u{1EEA5}-\u{1EEA9}\u{1EEAB}-\u{1EEBB}]/u; +const bidiS1LTR = /[A-Za-z\xAA\xB5\xBA\xC0-\xD6\xD8-\xF6\xF8-\u02B8\u02BB-\u02C1\u02D0\u02D1\u02E0-\u02E4\u02EE\u0370-\u0373\u0376\u0377\u037A-\u037D\u037F\u0386\u0388-\u038A\u038C\u038E-\u03A1\u03A3-\u03F5\u03F7-\u0482\u048A-\u052F\u0531-\u0556\u0559-\u0589\u0903-\u0939\u093B\u093D-\u0940\u0949-\u094C\u094E-\u0950\u0958-\u0961\u0964-\u0980\u0982\u0983\u0985-\u098C\u098F\u0990\u0993-\u09A8\u09AA-\u09B0\u09B2\u09B6-\u09B9\u09BD-\u09C0\u09C7\u09C8\u09CB\u09CC\u09CE\u09D7\u09DC\u09DD\u09DF-\u09E1\u09E6-\u09F1\u09F4-\u09FA\u09FC\u09FD\u0A03\u0A05-\u0A0A\u0A0F\u0A10\u0A13-\u0A28\u0A2A-\u0A30\u0A32\u0A33\u0A35\u0A36\u0A38\u0A39\u0A3E-\u0A40\u0A59-\u0A5C\u0A5E\u0A66-\u0A6F\u0A72-\u0A74\u0A76\u0A83\u0A85-\u0A8D\u0A8F-\u0A91\u0A93-\u0AA8\u0AAA-\u0AB0\u0AB2\u0AB3\u0AB5-\u0AB9\u0ABD-\u0AC0\u0AC9\u0ACB\u0ACC\u0AD0\u0AE0\u0AE1\u0AE6-\u0AF0\u0AF9\u0B02\u0B03\u0B05-\u0B0C\u0B0F\u0B10\u0B13-\u0B28\u0B2A-\u0B30\u0B32\u0B33\u0B35-\u0B39\u0B3D\u0B3E\u0B40\u0B47\u0B48\u0B4B\u0B4C\u0B57\u0B5C\u0B5D\u0B5F-\u0B61\u0B66-\u0B77\u0B83\u0B85-\u0B8A\u0B8E-\u0B90\u0B92-\u0B95\u0B99\u0B9A\u0B9C\u0B9E\u0B9F\u0BA3\u0BA4\u0BA8-\u0BAA\u0BAE-\u0BB9\u0BBE\u0BBF\u0BC1\u0BC2\u0BC6-\u0BC8\u0BCA-\u0BCC\u0BD0\u0BD7\u0BE6-\u0BF2\u0C01-\u0C03\u0C05-\u0C0C\u0C0E-\u0C10\u0C12-\u0C28\u0C2A-\u0C39\u0C3D\u0C41-\u0C44\u0C58-\u0C5A\u0C5D\u0C60\u0C61\u0C66-\u0C6F\u0C77\u0C7F\u0C80\u0C82-\u0C8C\u0C8E-\u0C90\u0C92-\u0CA8\u0CAA-\u0CB3\u0CB5-\u0CB9\u0CBD-\u0CC4\u0CC6-\u0CC8\u0CCA\u0CCB\u0CD5\u0CD6\u0CDD\u0CDE\u0CE0\u0CE1\u0CE6-\u0CEF\u0CF1\u0CF2\u0D02-\u0D0C\u0D0E-\u0D10\u0D12-\u0D3A\u0D3D-\u0D40\u0D46-\u0D48\u0D4A-\u0D4C\u0D4E\u0D4F\u0D54-\u0D61\u0D66-\u0D7F\u0D82\u0D83\u0D85-\u0D96\u0D9A-\u0DB1\u0DB3-\u0DBB\u0DBD\u0DC0-\u0DC6\u0DCF-\u0DD1\u0DD8-\u0DDF\u0DE6-\u0DEF\u0DF2-\u0DF4\u0E01-\u0E30\u0E32\u0E33\u0E40-\u0E46\u0E4F-\u0E5B\u0E81\u0E82\u0E84\u0E86-\u0E8A\u0E8C-\u0EA3\u0EA5\u0EA7-\u0EB0\u0EB2\u0EB3\u0EBD\u0EC0-\u0EC4\u0EC6\u0ED0-\u0ED9\u0EDC-\u0EDF\u0F00-\u0F17\u0F1A-\u0F34\u0F36\u0F38\u0F3E-\u0F47\u0F49-\u0F6C\u0F7F\u0F85\u0F88-\u0F8C\u0FBE-\u0FC5\u0FC7-\u0FCC\u0FCE-\u0FDA\u1000-\u102C\u1031\u1038\u103B\u103C\u103F-\u1057\u105A-\u105D\u1061-\u1070\u1075-\u1081\u1083\u1084\u1087-\u108C\u108E-\u109C\u109E-\u10C5\u10C7\u10CD\u10D0-\u1248\u124A-\u124D\u1250-\u1256\u1258\u125A-\u125D\u1260-\u1288\u128A-\u128D\u1290-\u12B0\u12B2-\u12B5\u12B8-\u12BE\u12C0\u12C2-\u12C5\u12C8-\u12D6\u12D8-\u1310\u1312-\u1315\u1318-\u135A\u1360-\u137C\u1380-\u138F\u13A0-\u13F5\u13F8-\u13FD\u1401-\u167F\u1681-\u169A\u16A0-\u16F8\u1700-\u1711\u1715\u171F-\u1731\u1734-\u1736\u1740-\u1751\u1760-\u176C\u176E-\u1770\u1780-\u17B3\u17B6\u17BE-\u17C5\u17C7\u17C8\u17D4-\u17DA\u17DC\u17E0-\u17E9\u1810-\u1819\u1820-\u1878\u1880-\u1884\u1887-\u18A8\u18AA\u18B0-\u18F5\u1900-\u191E\u1923-\u1926\u1929-\u192B\u1930\u1931\u1933-\u1938\u1946-\u196D\u1970-\u1974\u1980-\u19AB\u19B0-\u19C9\u19D0-\u19DA\u1A00-\u1A16\u1A19\u1A1A\u1A1E-\u1A55\u1A57\u1A61\u1A63\u1A64\u1A6D-\u1A72\u1A80-\u1A89\u1A90-\u1A99\u1AA0-\u1AAD\u1B04-\u1B33\u1B35\u1B3B\u1B3D-\u1B41\u1B43-\u1B4C\u1B50-\u1B6A\u1B74-\u1B7E\u1B82-\u1BA1\u1BA6\u1BA7\u1BAA\u1BAE-\u1BE5\u1BE7\u1BEA-\u1BEC\u1BEE\u1BF2\u1BF3\u1BFC-\u1C2B\u1C34\u1C35\u1C3B-\u1C49\u1C4D-\u1C88\u1C90-\u1CBA\u1CBD-\u1CC7\u1CD3\u1CE1\u1CE9-\u1CEC\u1CEE-\u1CF3\u1CF5-\u1CF7\u1CFA\u1D00-\u1DBF\u1E00-\u1F15\u1F18-\u1F1D\u1F20-\u1F45\u1F48-\u1F4D\u1F50-\u1F57\u1F59\u1F5B\u1F5D\u1F5F-\u1F7D\u1F80-\u1FB4\u1FB6-\u1FBC\u1FBE\u1FC2-\u1FC4\u1FC6-\u1FCC\u1FD0-\u1FD3\u1FD6-\u1FDB\u1FE0-\u1FEC\u1FF2-\u1FF4\u1FF6-\u1FFC\u200E\u2071\u207F\u2090-\u209C\u2102\u2107\u210A-\u2113\u2115\u2119-\u211D\u2124\u2126\u2128\u212A-\u212D\u212F-\u2139\u213C-\u213F\u2145-\u2149\u214E\u214F\u2160-\u2188\u2336-\u237A\u2395\u249C-\u24E9\u26AC\u2800-\u28FF\u2C00-\u2CE4\u2CEB-\u2CEE\u2CF2\u2CF3\u2D00-\u2D25\u2D27\u2D2D\u2D30-\u2D67\u2D6F\u2D70\u2D80-\u2D96\u2DA0-\u2DA6\u2DA8-\u2DAE\u2DB0-\u2DB6\u2DB8-\u2DBE\u2DC0-\u2DC6\u2DC8-\u2DCE\u2DD0-\u2DD6\u2DD8-\u2DDE\u3005-\u3007\u3021-\u3029\u302E\u302F\u3031-\u3035\u3038-\u303C\u3041-\u3096\u309D-\u309F\u30A1-\u30FA\u30FC-\u30FF\u3105-\u312F\u3131-\u318E\u3190-\u31BF\u31F0-\u321C\u3220-\u324F\u3260-\u327B\u327F-\u32B0\u32C0-\u32CB\u32D0-\u3376\u337B-\u33DD\u33E0-\u33FE\u3400-\u4DBF\u4E00-\uA48C\uA4D0-\uA60C\uA610-\uA62B\uA640-\uA66E\uA680-\uA69D\uA6A0-\uA6EF\uA6F2-\uA6F7\uA722-\uA787\uA789-\uA7CA\uA7D0\uA7D1\uA7D3\uA7D5-\uA7D9\uA7F2-\uA801\uA803-\uA805\uA807-\uA80A\uA80C-\uA824\uA827\uA830-\uA837\uA840-\uA873\uA880-\uA8C3\uA8CE-\uA8D9\uA8F2-\uA8FE\uA900-\uA925\uA92E-\uA946\uA952\uA953\uA95F-\uA97C\uA983-\uA9B2\uA9B4\uA9B5\uA9BA\uA9BB\uA9BE-\uA9CD\uA9CF-\uA9D9\uA9DE-\uA9E4\uA9E6-\uA9FE\uAA00-\uAA28\uAA2F\uAA30\uAA33\uAA34\uAA40-\uAA42\uAA44-\uAA4B\uAA4D\uAA50-\uAA59\uAA5C-\uAA7B\uAA7D-\uAAAF\uAAB1\uAAB5\uAAB6\uAAB9-\uAABD\uAAC0\uAAC2\uAADB-\uAAEB\uAAEE-\uAAF5\uAB01-\uAB06\uAB09-\uAB0E\uAB11-\uAB16\uAB20-\uAB26\uAB28-\uAB2E\uAB30-\uAB69\uAB70-\uABE4\uABE6\uABE7\uABE9-\uABEC\uABF0-\uABF9\uAC00-\uD7A3\uD7B0-\uD7C6\uD7CB-\uD7FB\uD800-\uFA6D\uFA70-\uFAD9\uFB00-\uFB06\uFB13-\uFB17\uFF21-\uFF3A\uFF41-\uFF5A\uFF66-\uFFBE\uFFC2-\uFFC7\uFFCA-\uFFCF\uFFD2-\uFFD7\uFFDA-\uFFDC\u{10000}-\u{1000B}\u{1000D}-\u{10026}\u{10028}-\u{1003A}\u{1003C}\u{1003D}\u{1003F}-\u{1004D}\u{10050}-\u{1005D}\u{10080}-\u{100FA}\u{10100}\u{10102}\u{10107}-\u{10133}\u{10137}-\u{1013F}\u{1018D}\u{1018E}\u{101D0}-\u{101FC}\u{10280}-\u{1029C}\u{102A0}-\u{102D0}\u{10300}-\u{10323}\u{1032D}-\u{1034A}\u{10350}-\u{10375}\u{10380}-\u{1039D}\u{1039F}-\u{103C3}\u{103C8}-\u{103D5}\u{10400}-\u{1049D}\u{104A0}-\u{104A9}\u{104B0}-\u{104D3}\u{104D8}-\u{104FB}\u{10500}-\u{10527}\u{10530}-\u{10563}\u{1056F}-\u{1057A}\u{1057C}-\u{1058A}\u{1058C}-\u{10592}\u{10594}\u{10595}\u{10597}-\u{105A1}\u{105A3}-\u{105B1}\u{105B3}-\u{105B9}\u{105BB}\u{105BC}\u{10600}-\u{10736}\u{10740}-\u{10755}\u{10760}-\u{10767}\u{10780}-\u{10785}\u{10787}-\u{107B0}\u{107B2}-\u{107BA}\u{11000}\u{11002}-\u{11037}\u{11047}-\u{1104D}\u{11066}-\u{1106F}\u{11071}\u{11072}\u{11075}\u{11082}-\u{110B2}\u{110B7}\u{110B8}\u{110BB}-\u{110C1}\u{110CD}\u{110D0}-\u{110E8}\u{110F0}-\u{110F9}\u{11103}-\u{11126}\u{1112C}\u{11136}-\u{11147}\u{11150}-\u{11172}\u{11174}-\u{11176}\u{11182}-\u{111B5}\u{111BF}-\u{111C8}\u{111CD}\u{111CE}\u{111D0}-\u{111DF}\u{111E1}-\u{111F4}\u{11200}-\u{11211}\u{11213}-\u{1122E}\u{11232}\u{11233}\u{11235}\u{11238}-\u{1123D}\u{11280}-\u{11286}\u{11288}\u{1128A}-\u{1128D}\u{1128F}-\u{1129D}\u{1129F}-\u{112A9}\u{112B0}-\u{112DE}\u{112E0}-\u{112E2}\u{112F0}-\u{112F9}\u{11302}\u{11303}\u{11305}-\u{1130C}\u{1130F}\u{11310}\u{11313}-\u{11328}\u{1132A}-\u{11330}\u{11332}\u{11333}\u{11335}-\u{11339}\u{1133D}-\u{1133F}\u{11341}-\u{11344}\u{11347}\u{11348}\u{1134B}-\u{1134D}\u{11350}\u{11357}\u{1135D}-\u{11363}\u{11400}-\u{11437}\u{11440}\u{11441}\u{11445}\u{11447}-\u{1145B}\u{1145D}\u{1145F}-\u{11461}\u{11480}-\u{114B2}\u{114B9}\u{114BB}-\u{114BE}\u{114C1}\u{114C4}-\u{114C7}\u{114D0}-\u{114D9}\u{11580}-\u{115B1}\u{115B8}-\u{115BB}\u{115BE}\u{115C1}-\u{115DB}\u{11600}-\u{11632}\u{1163B}\u{1163C}\u{1163E}\u{11641}-\u{11644}\u{11650}-\u{11659}\u{11680}-\u{116AA}\u{116AC}\u{116AE}\u{116AF}\u{116B6}\u{116B8}\u{116B9}\u{116C0}-\u{116C9}\u{11700}-\u{1171A}\u{11720}\u{11721}\u{11726}\u{11730}-\u{11746}\u{11800}-\u{1182E}\u{11838}\u{1183B}\u{118A0}-\u{118F2}\u{118FF}-\u{11906}\u{11909}\u{1190C}-\u{11913}\u{11915}\u{11916}\u{11918}-\u{11935}\u{11937}\u{11938}\u{1193D}\u{1193F}-\u{11942}\u{11944}-\u{11946}\u{11950}-\u{11959}\u{119A0}-\u{119A7}\u{119AA}-\u{119D3}\u{119DC}-\u{119DF}\u{119E1}-\u{119E4}\u{11A00}\u{11A07}\u{11A08}\u{11A0B}-\u{11A32}\u{11A39}\u{11A3A}\u{11A3F}-\u{11A46}\u{11A50}\u{11A57}\u{11A58}\u{11A5C}-\u{11A89}\u{11A97}\u{11A9A}-\u{11AA2}\u{11AB0}-\u{11AF8}\u{11C00}-\u{11C08}\u{11C0A}-\u{11C2F}\u{11C3E}-\u{11C45}\u{11C50}-\u{11C6C}\u{11C70}-\u{11C8F}\u{11CA9}\u{11CB1}\u{11CB4}\u{11D00}-\u{11D06}\u{11D08}\u{11D09}\u{11D0B}-\u{11D30}\u{11D46}\u{11D50}-\u{11D59}\u{11D60}-\u{11D65}\u{11D67}\u{11D68}\u{11D6A}-\u{11D8E}\u{11D93}\u{11D94}\u{11D96}\u{11D98}\u{11DA0}-\u{11DA9}\u{11EE0}-\u{11EF2}\u{11EF5}-\u{11EF8}\u{11FB0}\u{11FC0}-\u{11FD4}\u{11FFF}-\u{12399}\u{12400}-\u{1246E}\u{12470}-\u{12474}\u{12480}-\u{12543}\u{12F90}-\u{12FF2}\u{13000}-\u{1342E}\u{13430}-\u{13438}\u{14400}-\u{14646}\u{16800}-\u{16A38}\u{16A40}-\u{16A5E}\u{16A60}-\u{16A69}\u{16A6E}-\u{16ABE}\u{16AC0}-\u{16AC9}\u{16AD0}-\u{16AED}\u{16AF5}\u{16B00}-\u{16B2F}\u{16B37}-\u{16B45}\u{16B50}-\u{16B59}\u{16B5B}-\u{16B61}\u{16B63}-\u{16B77}\u{16B7D}-\u{16B8F}\u{16E40}-\u{16E9A}\u{16F00}-\u{16F4A}\u{16F50}-\u{16F87}\u{16F93}-\u{16F9F}\u{16FE0}\u{16FE1}\u{16FE3}\u{16FF0}\u{16FF1}\u{17000}-\u{187F7}\u{18800}-\u{18CD5}\u{18D00}-\u{18D08}\u{1AFF0}-\u{1AFF3}\u{1AFF5}-\u{1AFFB}\u{1AFFD}\u{1AFFE}\u{1B000}-\u{1B122}\u{1B150}-\u{1B152}\u{1B164}-\u{1B167}\u{1B170}-\u{1B2FB}\u{1BC00}-\u{1BC6A}\u{1BC70}-\u{1BC7C}\u{1BC80}-\u{1BC88}\u{1BC90}-\u{1BC99}\u{1BC9C}\u{1BC9F}\u{1CF50}-\u{1CFC3}\u{1D000}-\u{1D0F5}\u{1D100}-\u{1D126}\u{1D129}-\u{1D166}\u{1D16A}-\u{1D172}\u{1D183}\u{1D184}\u{1D18C}-\u{1D1A9}\u{1D1AE}-\u{1D1E8}\u{1D2E0}-\u{1D2F3}\u{1D360}-\u{1D378}\u{1D400}-\u{1D454}\u{1D456}-\u{1D49C}\u{1D49E}\u{1D49F}\u{1D4A2}\u{1D4A5}\u{1D4A6}\u{1D4A9}-\u{1D4AC}\u{1D4AE}-\u{1D4B9}\u{1D4BB}\u{1D4BD}-\u{1D4C3}\u{1D4C5}-\u{1D505}\u{1D507}-\u{1D50A}\u{1D50D}-\u{1D514}\u{1D516}-\u{1D51C}\u{1D51E}-\u{1D539}\u{1D53B}-\u{1D53E}\u{1D540}-\u{1D544}\u{1D546}\u{1D54A}-\u{1D550}\u{1D552}-\u{1D6A5}\u{1D6A8}-\u{1D6DA}\u{1D6DC}-\u{1D714}\u{1D716}-\u{1D74E}\u{1D750}-\u{1D788}\u{1D78A}-\u{1D7C2}\u{1D7C4}-\u{1D7CB}\u{1D800}-\u{1D9FF}\u{1DA37}-\u{1DA3A}\u{1DA6D}-\u{1DA74}\u{1DA76}-\u{1DA83}\u{1DA85}-\u{1DA8B}\u{1DF00}-\u{1DF1E}\u{1E100}-\u{1E12C}\u{1E137}-\u{1E13D}\u{1E140}-\u{1E149}\u{1E14E}\u{1E14F}\u{1E290}-\u{1E2AD}\u{1E2C0}-\u{1E2EB}\u{1E2F0}-\u{1E2F9}\u{1E7E0}-\u{1E7E6}\u{1E7E8}-\u{1E7EB}\u{1E7ED}\u{1E7EE}\u{1E7F0}-\u{1E7FE}\u{1F110}-\u{1F12E}\u{1F130}-\u{1F169}\u{1F170}-\u{1F1AC}\u{1F1E6}-\u{1F202}\u{1F210}-\u{1F23B}\u{1F240}-\u{1F248}\u{1F250}\u{1F251}\u{20000}-\u{2A6DF}\u{2A700}-\u{2B738}\u{2B740}-\u{2B81D}\u{2B820}-\u{2CEA1}\u{2CEB0}-\u{2EBE0}\u{2F800}-\u{2FA1D}\u{30000}-\u{3134A}\u{F0000}-\u{FFFFD}\u{100000}-\u{10FFFD}]/u; +const bidiS1RTL = /[\u05BE\u05C0\u05C3\u05C6\u05D0-\u05EA\u05EF-\u05F4\u0608\u060B\u060D\u061B-\u064A\u066D-\u066F\u0671-\u06D5\u06E5\u06E6\u06EE\u06EF\u06FA-\u070D\u070F\u0710\u0712-\u072F\u074D-\u07A5\u07B1\u07C0-\u07EA\u07F4\u07F5\u07FA\u07FE-\u0815\u081A\u0824\u0828\u0830-\u083E\u0840-\u0858\u085E\u0860-\u086A\u0870-\u088E\u08A0-\u08C9\u200F\uFB1D\uFB1F-\uFB28\uFB2A-\uFB36\uFB38-\uFB3C\uFB3E\uFB40\uFB41\uFB43\uFB44\uFB46-\uFBC2\uFBD3-\uFD3D\uFD50-\uFD8F\uFD92-\uFDC7\uFDF0-\uFDFC\uFE70-\uFE74\uFE76-\uFEFC\u{10800}-\u{10805}\u{10808}\u{1080A}-\u{10835}\u{10837}\u{10838}\u{1083C}\u{1083F}-\u{10855}\u{10857}-\u{1089E}\u{108A7}-\u{108AF}\u{108E0}-\u{108F2}\u{108F4}\u{108F5}\u{108FB}-\u{1091B}\u{10920}-\u{10939}\u{1093F}\u{10980}-\u{109B7}\u{109BC}-\u{109CF}\u{109D2}-\u{10A00}\u{10A10}-\u{10A13}\u{10A15}-\u{10A17}\u{10A19}-\u{10A35}\u{10A40}-\u{10A48}\u{10A50}-\u{10A58}\u{10A60}-\u{10A9F}\u{10AC0}-\u{10AE4}\u{10AEB}-\u{10AF6}\u{10B00}-\u{10B35}\u{10B40}-\u{10B55}\u{10B58}-\u{10B72}\u{10B78}-\u{10B91}\u{10B99}-\u{10B9C}\u{10BA9}-\u{10BAF}\u{10C00}-\u{10C48}\u{10C80}-\u{10CB2}\u{10CC0}-\u{10CF2}\u{10CFA}-\u{10D23}\u{10E80}-\u{10EA9}\u{10EAD}\u{10EB0}\u{10EB1}\u{10F00}-\u{10F27}\u{10F30}-\u{10F45}\u{10F51}-\u{10F59}\u{10F70}-\u{10F81}\u{10F86}-\u{10F89}\u{10FB0}-\u{10FCB}\u{10FE0}-\u{10FF6}\u{1E800}-\u{1E8C4}\u{1E8C7}-\u{1E8CF}\u{1E900}-\u{1E943}\u{1E94B}\u{1E950}-\u{1E959}\u{1E95E}\u{1E95F}\u{1EC71}-\u{1ECB4}\u{1ED01}-\u{1ED3D}\u{1EE00}-\u{1EE03}\u{1EE05}-\u{1EE1F}\u{1EE21}\u{1EE22}\u{1EE24}\u{1EE27}\u{1EE29}-\u{1EE32}\u{1EE34}-\u{1EE37}\u{1EE39}\u{1EE3B}\u{1EE42}\u{1EE47}\u{1EE49}\u{1EE4B}\u{1EE4D}-\u{1EE4F}\u{1EE51}\u{1EE52}\u{1EE54}\u{1EE57}\u{1EE59}\u{1EE5B}\u{1EE5D}\u{1EE5F}\u{1EE61}\u{1EE62}\u{1EE64}\u{1EE67}-\u{1EE6A}\u{1EE6C}-\u{1EE72}\u{1EE74}-\u{1EE77}\u{1EE79}-\u{1EE7C}\u{1EE7E}\u{1EE80}-\u{1EE89}\u{1EE8B}-\u{1EE9B}\u{1EEA1}-\u{1EEA3}\u{1EEA5}-\u{1EEA9}\u{1EEAB}-\u{1EEBB}]/u; +const bidiS2 = /^[\0-\x08\x0E-\x1B!-@\[-`\{-\x84\x86-\xA9\xAB-\xB4\xB6-\xB9\xBB-\xBF\xD7\xF7\u02B9\u02BA\u02C2-\u02CF\u02D2-\u02DF\u02E5-\u02ED\u02EF-\u036F\u0374\u0375\u037E\u0384\u0385\u0387\u03F6\u0483-\u0489\u058A\u058D-\u058F\u0591-\u05C7\u05D0-\u05EA\u05EF-\u05F4\u0600-\u070D\u070F-\u074A\u074D-\u07B1\u07C0-\u07FA\u07FD-\u082D\u0830-\u083E\u0840-\u085B\u085E\u0860-\u086A\u0870-\u088E\u0890\u0891\u0898-\u0902\u093A\u093C\u0941-\u0948\u094D\u0951-\u0957\u0962\u0963\u0981\u09BC\u09C1-\u09C4\u09CD\u09E2\u09E3\u09F2\u09F3\u09FB\u09FE\u0A01\u0A02\u0A3C\u0A41\u0A42\u0A47\u0A48\u0A4B-\u0A4D\u0A51\u0A70\u0A71\u0A75\u0A81\u0A82\u0ABC\u0AC1-\u0AC5\u0AC7\u0AC8\u0ACD\u0AE2\u0AE3\u0AF1\u0AFA-\u0AFF\u0B01\u0B3C\u0B3F\u0B41-\u0B44\u0B4D\u0B55\u0B56\u0B62\u0B63\u0B82\u0BC0\u0BCD\u0BF3-\u0BFA\u0C00\u0C04\u0C3C\u0C3E-\u0C40\u0C46-\u0C48\u0C4A-\u0C4D\u0C55\u0C56\u0C62\u0C63\u0C78-\u0C7E\u0C81\u0CBC\u0CCC\u0CCD\u0CE2\u0CE3\u0D00\u0D01\u0D3B\u0D3C\u0D41-\u0D44\u0D4D\u0D62\u0D63\u0D81\u0DCA\u0DD2-\u0DD4\u0DD6\u0E31\u0E34-\u0E3A\u0E3F\u0E47-\u0E4E\u0EB1\u0EB4-\u0EBC\u0EC8-\u0ECD\u0F18\u0F19\u0F35\u0F37\u0F39-\u0F3D\u0F71-\u0F7E\u0F80-\u0F84\u0F86\u0F87\u0F8D-\u0F97\u0F99-\u0FBC\u0FC6\u102D-\u1030\u1032-\u1037\u1039\u103A\u103D\u103E\u1058\u1059\u105E-\u1060\u1071-\u1074\u1082\u1085\u1086\u108D\u109D\u135D-\u135F\u1390-\u1399\u1400\u169B\u169C\u1712-\u1714\u1732\u1733\u1752\u1753\u1772\u1773\u17B4\u17B5\u17B7-\u17BD\u17C6\u17C9-\u17D3\u17DB\u17DD\u17F0-\u17F9\u1800-\u180F\u1885\u1886\u18A9\u1920-\u1922\u1927\u1928\u1932\u1939-\u193B\u1940\u1944\u1945\u19DE-\u19FF\u1A17\u1A18\u1A1B\u1A56\u1A58-\u1A5E\u1A60\u1A62\u1A65-\u1A6C\u1A73-\u1A7C\u1A7F\u1AB0-\u1ACE\u1B00-\u1B03\u1B34\u1B36-\u1B3A\u1B3C\u1B42\u1B6B-\u1B73\u1B80\u1B81\u1BA2-\u1BA5\u1BA8\u1BA9\u1BAB-\u1BAD\u1BE6\u1BE8\u1BE9\u1BED\u1BEF-\u1BF1\u1C2C-\u1C33\u1C36\u1C37\u1CD0-\u1CD2\u1CD4-\u1CE0\u1CE2-\u1CE8\u1CED\u1CF4\u1CF8\u1CF9\u1DC0-\u1DFF\u1FBD\u1FBF-\u1FC1\u1FCD-\u1FCF\u1FDD-\u1FDF\u1FED-\u1FEF\u1FFD\u1FFE\u200B-\u200D\u200F-\u2027\u202F-\u205E\u2060-\u2064\u206A-\u2070\u2074-\u207E\u2080-\u208E\u20A0-\u20C0\u20D0-\u20F0\u2100\u2101\u2103-\u2106\u2108\u2109\u2114\u2116-\u2118\u211E-\u2123\u2125\u2127\u2129\u212E\u213A\u213B\u2140-\u2144\u214A-\u214D\u2150-\u215F\u2189-\u218B\u2190-\u2335\u237B-\u2394\u2396-\u2426\u2440-\u244A\u2460-\u249B\u24EA-\u26AB\u26AD-\u27FF\u2900-\u2B73\u2B76-\u2B95\u2B97-\u2BFF\u2CE5-\u2CEA\u2CEF-\u2CF1\u2CF9-\u2CFF\u2D7F\u2DE0-\u2E5D\u2E80-\u2E99\u2E9B-\u2EF3\u2F00-\u2FD5\u2FF0-\u2FFB\u3001-\u3004\u3008-\u3020\u302A-\u302D\u3030\u3036\u3037\u303D-\u303F\u3099-\u309C\u30A0\u30FB\u31C0-\u31E3\u321D\u321E\u3250-\u325F\u327C-\u327E\u32B1-\u32BF\u32CC-\u32CF\u3377-\u337A\u33DE\u33DF\u33FF\u4DC0-\u4DFF\uA490-\uA4C6\uA60D-\uA60F\uA66F-\uA67F\uA69E\uA69F\uA6F0\uA6F1\uA700-\uA721\uA788\uA802\uA806\uA80B\uA825\uA826\uA828-\uA82C\uA838\uA839\uA874-\uA877\uA8C4\uA8C5\uA8E0-\uA8F1\uA8FF\uA926-\uA92D\uA947-\uA951\uA980-\uA982\uA9B3\uA9B6-\uA9B9\uA9BC\uA9BD\uA9E5\uAA29-\uAA2E\uAA31\uAA32\uAA35\uAA36\uAA43\uAA4C\uAA7C\uAAB0\uAAB2-\uAAB4\uAAB7\uAAB8\uAABE\uAABF\uAAC1\uAAEC\uAAED\uAAF6\uAB6A\uAB6B\uABE5\uABE8\uABED\uFB1D-\uFB36\uFB38-\uFB3C\uFB3E\uFB40\uFB41\uFB43\uFB44\uFB46-\uFBC2\uFBD3-\uFD8F\uFD92-\uFDC7\uFDCF\uFDF0-\uFE19\uFE20-\uFE52\uFE54-\uFE66\uFE68-\uFE6B\uFE70-\uFE74\uFE76-\uFEFC\uFEFF\uFF01-\uFF20\uFF3B-\uFF40\uFF5B-\uFF65\uFFE0-\uFFE6\uFFE8-\uFFEE\uFFF9-\uFFFD\u{10101}\u{10140}-\u{1018C}\u{10190}-\u{1019C}\u{101A0}\u{101FD}\u{102E0}-\u{102FB}\u{10376}-\u{1037A}\u{10800}-\u{10805}\u{10808}\u{1080A}-\u{10835}\u{10837}\u{10838}\u{1083C}\u{1083F}-\u{10855}\u{10857}-\u{1089E}\u{108A7}-\u{108AF}\u{108E0}-\u{108F2}\u{108F4}\u{108F5}\u{108FB}-\u{1091B}\u{1091F}-\u{10939}\u{1093F}\u{10980}-\u{109B7}\u{109BC}-\u{109CF}\u{109D2}-\u{10A03}\u{10A05}\u{10A06}\u{10A0C}-\u{10A13}\u{10A15}-\u{10A17}\u{10A19}-\u{10A35}\u{10A38}-\u{10A3A}\u{10A3F}-\u{10A48}\u{10A50}-\u{10A58}\u{10A60}-\u{10A9F}\u{10AC0}-\u{10AE6}\u{10AEB}-\u{10AF6}\u{10B00}-\u{10B35}\u{10B39}-\u{10B55}\u{10B58}-\u{10B72}\u{10B78}-\u{10B91}\u{10B99}-\u{10B9C}\u{10BA9}-\u{10BAF}\u{10C00}-\u{10C48}\u{10C80}-\u{10CB2}\u{10CC0}-\u{10CF2}\u{10CFA}-\u{10D27}\u{10D30}-\u{10D39}\u{10E60}-\u{10E7E}\u{10E80}-\u{10EA9}\u{10EAB}-\u{10EAD}\u{10EB0}\u{10EB1}\u{10F00}-\u{10F27}\u{10F30}-\u{10F59}\u{10F70}-\u{10F89}\u{10FB0}-\u{10FCB}\u{10FE0}-\u{10FF6}\u{11001}\u{11038}-\u{11046}\u{11052}-\u{11065}\u{11070}\u{11073}\u{11074}\u{1107F}-\u{11081}\u{110B3}-\u{110B6}\u{110B9}\u{110BA}\u{110C2}\u{11100}-\u{11102}\u{11127}-\u{1112B}\u{1112D}-\u{11134}\u{11173}\u{11180}\u{11181}\u{111B6}-\u{111BE}\u{111C9}-\u{111CC}\u{111CF}\u{1122F}-\u{11231}\u{11234}\u{11236}\u{11237}\u{1123E}\u{112DF}\u{112E3}-\u{112EA}\u{11300}\u{11301}\u{1133B}\u{1133C}\u{11340}\u{11366}-\u{1136C}\u{11370}-\u{11374}\u{11438}-\u{1143F}\u{11442}-\u{11444}\u{11446}\u{1145E}\u{114B3}-\u{114B8}\u{114BA}\u{114BF}\u{114C0}\u{114C2}\u{114C3}\u{115B2}-\u{115B5}\u{115BC}\u{115BD}\u{115BF}\u{115C0}\u{115DC}\u{115DD}\u{11633}-\u{1163A}\u{1163D}\u{1163F}\u{11640}\u{11660}-\u{1166C}\u{116AB}\u{116AD}\u{116B0}-\u{116B5}\u{116B7}\u{1171D}-\u{1171F}\u{11722}-\u{11725}\u{11727}-\u{1172B}\u{1182F}-\u{11837}\u{11839}\u{1183A}\u{1193B}\u{1193C}\u{1193E}\u{11943}\u{119D4}-\u{119D7}\u{119DA}\u{119DB}\u{119E0}\u{11A01}-\u{11A06}\u{11A09}\u{11A0A}\u{11A33}-\u{11A38}\u{11A3B}-\u{11A3E}\u{11A47}\u{11A51}-\u{11A56}\u{11A59}-\u{11A5B}\u{11A8A}-\u{11A96}\u{11A98}\u{11A99}\u{11C30}-\u{11C36}\u{11C38}-\u{11C3D}\u{11C92}-\u{11CA7}\u{11CAA}-\u{11CB0}\u{11CB2}\u{11CB3}\u{11CB5}\u{11CB6}\u{11D31}-\u{11D36}\u{11D3A}\u{11D3C}\u{11D3D}\u{11D3F}-\u{11D45}\u{11D47}\u{11D90}\u{11D91}\u{11D95}\u{11D97}\u{11EF3}\u{11EF4}\u{11FD5}-\u{11FF1}\u{16AF0}-\u{16AF4}\u{16B30}-\u{16B36}\u{16F4F}\u{16F8F}-\u{16F92}\u{16FE2}\u{16FE4}\u{1BC9D}\u{1BC9E}\u{1BCA0}-\u{1BCA3}\u{1CF00}-\u{1CF2D}\u{1CF30}-\u{1CF46}\u{1D167}-\u{1D169}\u{1D173}-\u{1D182}\u{1D185}-\u{1D18B}\u{1D1AA}-\u{1D1AD}\u{1D1E9}\u{1D1EA}\u{1D200}-\u{1D245}\u{1D300}-\u{1D356}\u{1D6DB}\u{1D715}\u{1D74F}\u{1D789}\u{1D7C3}\u{1D7CE}-\u{1D7FF}\u{1DA00}-\u{1DA36}\u{1DA3B}-\u{1DA6C}\u{1DA75}\u{1DA84}\u{1DA9B}-\u{1DA9F}\u{1DAA1}-\u{1DAAF}\u{1E000}-\u{1E006}\u{1E008}-\u{1E018}\u{1E01B}-\u{1E021}\u{1E023}\u{1E024}\u{1E026}-\u{1E02A}\u{1E130}-\u{1E136}\u{1E2AE}\u{1E2EC}-\u{1E2EF}\u{1E2FF}\u{1E800}-\u{1E8C4}\u{1E8C7}-\u{1E8D6}\u{1E900}-\u{1E94B}\u{1E950}-\u{1E959}\u{1E95E}\u{1E95F}\u{1EC71}-\u{1ECB4}\u{1ED01}-\u{1ED3D}\u{1EE00}-\u{1EE03}\u{1EE05}-\u{1EE1F}\u{1EE21}\u{1EE22}\u{1EE24}\u{1EE27}\u{1EE29}-\u{1EE32}\u{1EE34}-\u{1EE37}\u{1EE39}\u{1EE3B}\u{1EE42}\u{1EE47}\u{1EE49}\u{1EE4B}\u{1EE4D}-\u{1EE4F}\u{1EE51}\u{1EE52}\u{1EE54}\u{1EE57}\u{1EE59}\u{1EE5B}\u{1EE5D}\u{1EE5F}\u{1EE61}\u{1EE62}\u{1EE64}\u{1EE67}-\u{1EE6A}\u{1EE6C}-\u{1EE72}\u{1EE74}-\u{1EE77}\u{1EE79}-\u{1EE7C}\u{1EE7E}\u{1EE80}-\u{1EE89}\u{1EE8B}-\u{1EE9B}\u{1EEA1}-\u{1EEA3}\u{1EEA5}-\u{1EEA9}\u{1EEAB}-\u{1EEBB}\u{1EEF0}\u{1EEF1}\u{1F000}-\u{1F02B}\u{1F030}-\u{1F093}\u{1F0A0}-\u{1F0AE}\u{1F0B1}-\u{1F0BF}\u{1F0C1}-\u{1F0CF}\u{1F0D1}-\u{1F0F5}\u{1F100}-\u{1F10F}\u{1F12F}\u{1F16A}-\u{1F16F}\u{1F1AD}\u{1F260}-\u{1F265}\u{1F300}-\u{1F6D7}\u{1F6DD}-\u{1F6EC}\u{1F6F0}-\u{1F6FC}\u{1F700}-\u{1F773}\u{1F780}-\u{1F7D8}\u{1F7E0}-\u{1F7EB}\u{1F7F0}\u{1F800}-\u{1F80B}\u{1F810}-\u{1F847}\u{1F850}-\u{1F859}\u{1F860}-\u{1F887}\u{1F890}-\u{1F8AD}\u{1F8B0}\u{1F8B1}\u{1F900}-\u{1FA53}\u{1FA60}-\u{1FA6D}\u{1FA70}-\u{1FA74}\u{1FA78}-\u{1FA7C}\u{1FA80}-\u{1FA86}\u{1FA90}-\u{1FAAC}\u{1FAB0}-\u{1FABA}\u{1FAC0}-\u{1FAC5}\u{1FAD0}-\u{1FAD9}\u{1FAE0}-\u{1FAE7}\u{1FAF0}-\u{1FAF6}\u{1FB00}-\u{1FB92}\u{1FB94}-\u{1FBCA}\u{1FBF0}-\u{1FBF9}\u{E0001}\u{E0020}-\u{E007F}\u{E0100}-\u{E01EF}]*$/u; +const bidiS3 = /[0-9\xB2\xB3\xB9\u05BE\u05C0\u05C3\u05C6\u05D0-\u05EA\u05EF-\u05F4\u0600-\u0605\u0608\u060B\u060D\u061B-\u064A\u0660-\u0669\u066B-\u066F\u0671-\u06D5\u06DD\u06E5\u06E6\u06EE-\u070D\u070F\u0710\u0712-\u072F\u074D-\u07A5\u07B1\u07C0-\u07EA\u07F4\u07F5\u07FA\u07FE-\u0815\u081A\u0824\u0828\u0830-\u083E\u0840-\u0858\u085E\u0860-\u086A\u0870-\u088E\u0890\u0891\u08A0-\u08C9\u08E2\u200F\u2070\u2074-\u2079\u2080-\u2089\u2488-\u249B\uFB1D\uFB1F-\uFB28\uFB2A-\uFB36\uFB38-\uFB3C\uFB3E\uFB40\uFB41\uFB43\uFB44\uFB46-\uFBC2\uFBD3-\uFD3D\uFD50-\uFD8F\uFD92-\uFDC7\uFDF0-\uFDFC\uFE70-\uFE74\uFE76-\uFEFC\uFF10-\uFF19\u{102E1}-\u{102FB}\u{10800}-\u{10805}\u{10808}\u{1080A}-\u{10835}\u{10837}\u{10838}\u{1083C}\u{1083F}-\u{10855}\u{10857}-\u{1089E}\u{108A7}-\u{108AF}\u{108E0}-\u{108F2}\u{108F4}\u{108F5}\u{108FB}-\u{1091B}\u{10920}-\u{10939}\u{1093F}\u{10980}-\u{109B7}\u{109BC}-\u{109CF}\u{109D2}-\u{10A00}\u{10A10}-\u{10A13}\u{10A15}-\u{10A17}\u{10A19}-\u{10A35}\u{10A40}-\u{10A48}\u{10A50}-\u{10A58}\u{10A60}-\u{10A9F}\u{10AC0}-\u{10AE4}\u{10AEB}-\u{10AF6}\u{10B00}-\u{10B35}\u{10B40}-\u{10B55}\u{10B58}-\u{10B72}\u{10B78}-\u{10B91}\u{10B99}-\u{10B9C}\u{10BA9}-\u{10BAF}\u{10C00}-\u{10C48}\u{10C80}-\u{10CB2}\u{10CC0}-\u{10CF2}\u{10CFA}-\u{10D23}\u{10D30}-\u{10D39}\u{10E60}-\u{10E7E}\u{10E80}-\u{10EA9}\u{10EAD}\u{10EB0}\u{10EB1}\u{10F00}-\u{10F27}\u{10F30}-\u{10F45}\u{10F51}-\u{10F59}\u{10F70}-\u{10F81}\u{10F86}-\u{10F89}\u{10FB0}-\u{10FCB}\u{10FE0}-\u{10FF6}\u{1D7CE}-\u{1D7FF}\u{1E800}-\u{1E8C4}\u{1E8C7}-\u{1E8CF}\u{1E900}-\u{1E943}\u{1E94B}\u{1E950}-\u{1E959}\u{1E95E}\u{1E95F}\u{1EC71}-\u{1ECB4}\u{1ED01}-\u{1ED3D}\u{1EE00}-\u{1EE03}\u{1EE05}-\u{1EE1F}\u{1EE21}\u{1EE22}\u{1EE24}\u{1EE27}\u{1EE29}-\u{1EE32}\u{1EE34}-\u{1EE37}\u{1EE39}\u{1EE3B}\u{1EE42}\u{1EE47}\u{1EE49}\u{1EE4B}\u{1EE4D}-\u{1EE4F}\u{1EE51}\u{1EE52}\u{1EE54}\u{1EE57}\u{1EE59}\u{1EE5B}\u{1EE5D}\u{1EE5F}\u{1EE61}\u{1EE62}\u{1EE64}\u{1EE67}-\u{1EE6A}\u{1EE6C}-\u{1EE72}\u{1EE74}-\u{1EE77}\u{1EE79}-\u{1EE7C}\u{1EE7E}\u{1EE80}-\u{1EE89}\u{1EE8B}-\u{1EE9B}\u{1EEA1}-\u{1EEA3}\u{1EEA5}-\u{1EEA9}\u{1EEAB}-\u{1EEBB}\u{1F100}-\u{1F10A}\u{1FBF0}-\u{1FBF9}][\u0300-\u036F\u0483-\u0489\u0591-\u05BD\u05BF\u05C1\u05C2\u05C4\u05C5\u05C7\u0610-\u061A\u064B-\u065F\u0670\u06D6-\u06DC\u06DF-\u06E4\u06E7\u06E8\u06EA-\u06ED\u0711\u0730-\u074A\u07A6-\u07B0\u07EB-\u07F3\u07FD\u0816-\u0819\u081B-\u0823\u0825-\u0827\u0829-\u082D\u0859-\u085B\u0898-\u089F\u08CA-\u08E1\u08E3-\u0902\u093A\u093C\u0941-\u0948\u094D\u0951-\u0957\u0962\u0963\u0981\u09BC\u09C1-\u09C4\u09CD\u09E2\u09E3\u09FE\u0A01\u0A02\u0A3C\u0A41\u0A42\u0A47\u0A48\u0A4B-\u0A4D\u0A51\u0A70\u0A71\u0A75\u0A81\u0A82\u0ABC\u0AC1-\u0AC5\u0AC7\u0AC8\u0ACD\u0AE2\u0AE3\u0AFA-\u0AFF\u0B01\u0B3C\u0B3F\u0B41-\u0B44\u0B4D\u0B55\u0B56\u0B62\u0B63\u0B82\u0BC0\u0BCD\u0C00\u0C04\u0C3C\u0C3E-\u0C40\u0C46-\u0C48\u0C4A-\u0C4D\u0C55\u0C56\u0C62\u0C63\u0C81\u0CBC\u0CCC\u0CCD\u0CE2\u0CE3\u0D00\u0D01\u0D3B\u0D3C\u0D41-\u0D44\u0D4D\u0D62\u0D63\u0D81\u0DCA\u0DD2-\u0DD4\u0DD6\u0E31\u0E34-\u0E3A\u0E47-\u0E4E\u0EB1\u0EB4-\u0EBC\u0EC8-\u0ECD\u0F18\u0F19\u0F35\u0F37\u0F39\u0F71-\u0F7E\u0F80-\u0F84\u0F86\u0F87\u0F8D-\u0F97\u0F99-\u0FBC\u0FC6\u102D-\u1030\u1032-\u1037\u1039\u103A\u103D\u103E\u1058\u1059\u105E-\u1060\u1071-\u1074\u1082\u1085\u1086\u108D\u109D\u135D-\u135F\u1712-\u1714\u1732\u1733\u1752\u1753\u1772\u1773\u17B4\u17B5\u17B7-\u17BD\u17C6\u17C9-\u17D3\u17DD\u180B-\u180D\u180F\u1885\u1886\u18A9\u1920-\u1922\u1927\u1928\u1932\u1939-\u193B\u1A17\u1A18\u1A1B\u1A56\u1A58-\u1A5E\u1A60\u1A62\u1A65-\u1A6C\u1A73-\u1A7C\u1A7F\u1AB0-\u1ACE\u1B00-\u1B03\u1B34\u1B36-\u1B3A\u1B3C\u1B42\u1B6B-\u1B73\u1B80\u1B81\u1BA2-\u1BA5\u1BA8\u1BA9\u1BAB-\u1BAD\u1BE6\u1BE8\u1BE9\u1BED\u1BEF-\u1BF1\u1C2C-\u1C33\u1C36\u1C37\u1CD0-\u1CD2\u1CD4-\u1CE0\u1CE2-\u1CE8\u1CED\u1CF4\u1CF8\u1CF9\u1DC0-\u1DFF\u20D0-\u20F0\u2CEF-\u2CF1\u2D7F\u2DE0-\u2DFF\u302A-\u302D\u3099\u309A\uA66F-\uA672\uA674-\uA67D\uA69E\uA69F\uA6F0\uA6F1\uA802\uA806\uA80B\uA825\uA826\uA82C\uA8C4\uA8C5\uA8E0-\uA8F1\uA8FF\uA926-\uA92D\uA947-\uA951\uA980-\uA982\uA9B3\uA9B6-\uA9B9\uA9BC\uA9BD\uA9E5\uAA29-\uAA2E\uAA31\uAA32\uAA35\uAA36\uAA43\uAA4C\uAA7C\uAAB0\uAAB2-\uAAB4\uAAB7\uAAB8\uAABE\uAABF\uAAC1\uAAEC\uAAED\uAAF6\uABE5\uABE8\uABED\uFB1E\uFE00-\uFE0F\uFE20-\uFE2F\u{101FD}\u{102E0}\u{10376}-\u{1037A}\u{10A01}-\u{10A03}\u{10A05}\u{10A06}\u{10A0C}-\u{10A0F}\u{10A38}-\u{10A3A}\u{10A3F}\u{10AE5}\u{10AE6}\u{10D24}-\u{10D27}\u{10EAB}\u{10EAC}\u{10F46}-\u{10F50}\u{10F82}-\u{10F85}\u{11001}\u{11038}-\u{11046}\u{11070}\u{11073}\u{11074}\u{1107F}-\u{11081}\u{110B3}-\u{110B6}\u{110B9}\u{110BA}\u{110C2}\u{11100}-\u{11102}\u{11127}-\u{1112B}\u{1112D}-\u{11134}\u{11173}\u{11180}\u{11181}\u{111B6}-\u{111BE}\u{111C9}-\u{111CC}\u{111CF}\u{1122F}-\u{11231}\u{11234}\u{11236}\u{11237}\u{1123E}\u{112DF}\u{112E3}-\u{112EA}\u{11300}\u{11301}\u{1133B}\u{1133C}\u{11340}\u{11366}-\u{1136C}\u{11370}-\u{11374}\u{11438}-\u{1143F}\u{11442}-\u{11444}\u{11446}\u{1145E}\u{114B3}-\u{114B8}\u{114BA}\u{114BF}\u{114C0}\u{114C2}\u{114C3}\u{115B2}-\u{115B5}\u{115BC}\u{115BD}\u{115BF}\u{115C0}\u{115DC}\u{115DD}\u{11633}-\u{1163A}\u{1163D}\u{1163F}\u{11640}\u{116AB}\u{116AD}\u{116B0}-\u{116B5}\u{116B7}\u{1171D}-\u{1171F}\u{11722}-\u{11725}\u{11727}-\u{1172B}\u{1182F}-\u{11837}\u{11839}\u{1183A}\u{1193B}\u{1193C}\u{1193E}\u{11943}\u{119D4}-\u{119D7}\u{119DA}\u{119DB}\u{119E0}\u{11A01}-\u{11A06}\u{11A09}\u{11A0A}\u{11A33}-\u{11A38}\u{11A3B}-\u{11A3E}\u{11A47}\u{11A51}-\u{11A56}\u{11A59}-\u{11A5B}\u{11A8A}-\u{11A96}\u{11A98}\u{11A99}\u{11C30}-\u{11C36}\u{11C38}-\u{11C3D}\u{11C92}-\u{11CA7}\u{11CAA}-\u{11CB0}\u{11CB2}\u{11CB3}\u{11CB5}\u{11CB6}\u{11D31}-\u{11D36}\u{11D3A}\u{11D3C}\u{11D3D}\u{11D3F}-\u{11D45}\u{11D47}\u{11D90}\u{11D91}\u{11D95}\u{11D97}\u{11EF3}\u{11EF4}\u{16AF0}-\u{16AF4}\u{16B30}-\u{16B36}\u{16F4F}\u{16F8F}-\u{16F92}\u{16FE4}\u{1BC9D}\u{1BC9E}\u{1CF00}-\u{1CF2D}\u{1CF30}-\u{1CF46}\u{1D167}-\u{1D169}\u{1D17B}-\u{1D182}\u{1D185}-\u{1D18B}\u{1D1AA}-\u{1D1AD}\u{1D242}-\u{1D244}\u{1DA00}-\u{1DA36}\u{1DA3B}-\u{1DA6C}\u{1DA75}\u{1DA84}\u{1DA9B}-\u{1DA9F}\u{1DAA1}-\u{1DAAF}\u{1E000}-\u{1E006}\u{1E008}-\u{1E018}\u{1E01B}-\u{1E021}\u{1E023}\u{1E024}\u{1E026}-\u{1E02A}\u{1E130}-\u{1E136}\u{1E2AE}\u{1E2EC}-\u{1E2EF}\u{1E8D0}-\u{1E8D6}\u{1E944}-\u{1E94A}\u{E0100}-\u{E01EF}]*$/u; +const bidiS4EN = /[0-9\xB2\xB3\xB9\u06F0-\u06F9\u2070\u2074-\u2079\u2080-\u2089\u2488-\u249B\uFF10-\uFF19\u{102E1}-\u{102FB}\u{1D7CE}-\u{1D7FF}\u{1F100}-\u{1F10A}\u{1FBF0}-\u{1FBF9}]/u; +const bidiS4AN = /[\u0600-\u0605\u0660-\u0669\u066B\u066C\u06DD\u0890\u0891\u08E2\u{10D30}-\u{10D39}\u{10E60}-\u{10E7E}]/u; +const bidiS5 = /^[\0-\x08\x0E-\x1B!-\x84\x86-\u0377\u037A-\u037F\u0384-\u038A\u038C\u038E-\u03A1\u03A3-\u052F\u0531-\u0556\u0559-\u058A\u058D-\u058F\u0591-\u05BD\u05BF\u05C1\u05C2\u05C4\u05C5\u05C7\u0606\u0607\u0609\u060A\u060C\u060E-\u061A\u064B-\u065F\u066A\u0670\u06D6-\u06DC\u06DE-\u06E4\u06E7-\u06ED\u06F0-\u06F9\u0711\u0730-\u074A\u07A6-\u07B0\u07EB-\u07F3\u07F6-\u07F9\u07FD\u0816-\u0819\u081B-\u0823\u0825-\u0827\u0829-\u082D\u0859-\u085B\u0898-\u089F\u08CA-\u08E1\u08E3-\u0983\u0985-\u098C\u098F\u0990\u0993-\u09A8\u09AA-\u09B0\u09B2\u09B6-\u09B9\u09BC-\u09C4\u09C7\u09C8\u09CB-\u09CE\u09D7\u09DC\u09DD\u09DF-\u09E3\u09E6-\u09FE\u0A01-\u0A03\u0A05-\u0A0A\u0A0F\u0A10\u0A13-\u0A28\u0A2A-\u0A30\u0A32\u0A33\u0A35\u0A36\u0A38\u0A39\u0A3C\u0A3E-\u0A42\u0A47\u0A48\u0A4B-\u0A4D\u0A51\u0A59-\u0A5C\u0A5E\u0A66-\u0A76\u0A81-\u0A83\u0A85-\u0A8D\u0A8F-\u0A91\u0A93-\u0AA8\u0AAA-\u0AB0\u0AB2\u0AB3\u0AB5-\u0AB9\u0ABC-\u0AC5\u0AC7-\u0AC9\u0ACB-\u0ACD\u0AD0\u0AE0-\u0AE3\u0AE6-\u0AF1\u0AF9-\u0AFF\u0B01-\u0B03\u0B05-\u0B0C\u0B0F\u0B10\u0B13-\u0B28\u0B2A-\u0B30\u0B32\u0B33\u0B35-\u0B39\u0B3C-\u0B44\u0B47\u0B48\u0B4B-\u0B4D\u0B55-\u0B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0\u12B2-\u12B5\u12B8-\u12BE\u12C0\u12C2-\u12C5\u12C8-\u12D6\u12D8-\u1310\u1312-\u1315\u1318-\u135A\u135D-\u137C\u1380-\u1399\u13A0-\u13F5\u13F8-\u13FD\u1400-\u167F\u1681-\u169C\u16A0-\u16F8\u1700-\u1715\u171F-\u1736\u1740-\u1753\u1760-\u176C\u176E-\u1770\u1772\u1773\u1780-\u17DD\u17E0-\u17E9\u17F0-\u17F9\u1800-\u1819\u1820-\u1878\u1880-\u18AA\u18B0-\u18F5\u1900-\u191E\u1920-\u192B\u1930-\u193B\u1940\u1944-\u196D\u1970-\u1974\u1980-\u19AB\u19B0-\u19C9\u19D0-\u19DA\u19DE-\u1A1B\u1A1E-\u1A5E\u1A60-\u1A7C\u1A7F-\u1A89\u1A90-\u1A99\u1AA0-\u1AAD\u1AB0-\u1ACE\u1B00-\u1B4C\u1B50-\u1B7E\u1B80-\u1BF3\u1BFC-\u1C37\u1C3B-\u1C49\u1C4D-\u1C88\u1C90-\u1CBA\u1CBD-\u1CC7\u1CD0-\u1CFA\u1D00-\u1F15\u1F18-\u1F1D\u1F20-\u1F45\u1F48-\u1F4D\u1F50-\u1F57\u1F59\u1F5B\u1F5D\u1F5F-\u1F7D\u1F80-\u1FB4\u1FB6-\u1FC4\u1FC6-\u1FD3\u1FD6-\u1FDB\u1FDD-\u1FEF\u1FF2-\u1FF4\u1FF6-\u1FFE\u200B-\u200E\u2010-\u2027\u202F-\u205E\u2060-\u2064\u206A-\u2071\u2074-\u208E\u2090-\u209C\u20A0-\u20C0\u20D0-\u20F0\u2100-\u218B\u2190-\u2426\u2440-\u244A\u2460-\u2B73\u2B76-\u2B95\u2B97-\u2CF3\u2CF9-\u2D25\u2D27\u2D2D\u2D30-\u2D67\u2D6F\u2D70\u2D7F-\u2D96\u2DA0-\u2DA6\u2DA8-\u2DAE\u2DB0-\u2DB6\u2DB8-\u2DBE\u2DC0-\u2DC6\u2DC8-\u2DCE\u2DD0-\u2DD6\u2DD8-\u2DDE\u2DE0-\u2E5D\u2E80-\u2E99\u2E9B-\u2EF3\u2F00-\u2FD5\u2FF0-\u2FFB\u3001-\u303F\u3041-\u3096\u3099-\u30FF\u3105-\u312F\u3131-\u318E\u3190-\u31E3\u31F0-\u321E\u3220-\uA48C\uA490-\uA4C6\uA4D0-\uA62B\uA640-\uA6F7\uA700-\uA7CA\uA7D0\uA7D1\uA7D3\uA7D5-\uA7D9\uA7F2-\uA82C\uA830-\uA839\uA840-\uA877\uA880-\uA8C5\uA8CE-\uA8D9\uA8E0-\uA953\uA95F-\uA97C\uA980-\uA9CD\uA9CF-\uA9D9\uA9DE-\uA9FE\uAA00-\uAA36\uAA40-\uAA4D\uAA50-\uAA59\uAA5C-\uAAC2\uAADB-\uAAF6\uAB01-\uAB06\uAB09-\uAB0E\uAB11-\uAB16\uAB20-\uAB26\uAB28-\uAB2E\uAB30-\uAB6B\uAB70-\uABED\uABF0-\uABF9\uAC00-\uD7A3\uD7B0-\uD7C6\uD7CB-\uD7FB\uD800-\uFA6D\uFA70-\uFAD9\uFB00-\uFB06\uFB13-\uFB17\uFB1E\uFB29\uFD3E-\uFD4F\uFDCF\uFDFD-\uFE19\uFE20-\uFE52\uFE54-\uFE66\uFE68-\uFE6B\uFEFF\uFF01-\uFFBE\uFFC2-\uFFC7\uFFCA-\uFFCF\uFFD2-\uFFD7\uFFDA-\uFFDC\uFFE0-\uFFE6\uFFE8-\uFFEE\uFFF9-\uFFFD\u{10000}-\u{1000B}\u{1000D}-\u{10026}\u{10028}-\u{1003A}\u{1003C}\u{1003D}\u{1003F}-\u{1004D}\u{10050}-\u{1005D}\u{10080}-\u{100FA}\u{10100}-\u{10102}\u{10107}-\u{10133}\u{10137}-\u{1018E}\u{10190}-\u{1019C}\u{101A0}\u{101D0}-\u{101FD}\u{10280}-\u{1029C}\u{102A0}-\u{102D0}\u{102E0}-\u{102FB}\u{10300}-\u{10323}\u{1032D}-\u{1034A}\u{10350}-\u{1037A}\u{10380}-\u{1039D}\u{1039F}-\u{103C3}\u{103C8}-\u{103D5}\u{10400}-\u{1049D}\u{104A0}-\u{104A9}\u{104B0}-\u{104D3}\u{104D8}-\u{104FB}\u{10500}-\u{10527}\u{10530}-\u{10563}\u{1056F}-\u{1057A}\u{1057C}-\u{1058A}\u{1058C}-\u{10592}\u{10594}\u{10595}\u{10597}-\u{105A1}\u{105A3}-\u{105B1}\u{105B3}-\u{105B9}\u{105BB}\u{105BC}\u{10600}-\u{10736}\u{10740}-\u{10755}\u{10760}-\u{10767}\u{10780}-\u{10785}\u{10787}-\u{107B0}\u{107B2}-\u{107BA}\u{1091F}\u{10A01}-\u{10A03}\u{10A05}\u{10A06}\u{10A0C}-\u{10A0F}\u{10A38}-\u{10A3A}\u{10A3F}\u{10AE5}\u{10AE6}\u{10B39}-\u{10B3F}\u{10D24}-\u{10D27}\u{10EAB}\u{10EAC}\u{10F46}-\u{10F50}\u{10F82}-\u{10F85}\u{11000}-\u{1104D}\u{11052}-\u{11075}\u{1107F}-\u{110C2}\u{110CD}\u{110D0}-\u{110E8}\u{110F0}-\u{110F9}\u{11100}-\u{11134}\u{11136}-\u{11147}\u{11150}-\u{11176}\u{11180}-\u{111DF}\u{111E1}-\u{111F4}\u{11200}-\u{11211}\u{11213}-\u{1123E}\u{11280}-\u{11286}\u{11288}\u{1128A}-\u{1128D}\u{1128F}-\u{1129D}\u{1129F}-\u{112A9}\u{112B0}-\u{112EA}\u{112F0}-\u{112F9}\u{11300}-\u{11303}\u{11305}-\u{1130C}\u{1130F}\u{11310}\u{11313}-\u{11328}\u{1132A}-\u{11330}\u{11332}\u{11333}\u{11335}-\u{11339}\u{1133B}-\u{11344}\u{11347}\u{11348}\u{1134B}-\u{1134D}\u{11350}\u{11357}\u{1135D}-\u{11363}\u{11366}-\u{1136C}\u{11370}-\u{11374}\u{11400}-\u{1145B}\u{1145D}-\u{11461}\u{11480}-\u{114C7}\u{114D0}-\u{114D9}\u{11580}-\u{115B5}\u{115B8}-\u{115DD}\u{11600}-\u{11644}\u{11650}-\u{11659}\u{11660}-\u{1166C}\u{11680}-\u{116B9}\u{116C0}-\u{116C9}\u{11700}-\u{1171A}\u{1171D}-\u{1172B}\u{11730}-\u{11746}\u{11800}-\u{1183B}\u{118A0}-\u{118F2}\u{118FF}-\u{11906}\u{11909}\u{1190C}-\u{11913}\u{11915}\u{11916}\u{11918}-\u{11935}\u{11937}\u{11938}\u{1193B}-\u{11946}\u{11950}-\u{11959}\u{119A0}-\u{119A7}\u{119AA}-\u{119D7}\u{119DA}-\u{119E4}\u{11A00}-\u{11A47}\u{11A50}-\u{11AA2}\u{11AB0}-\u{11AF8}\u{11C00}-\u{11C08}\u{11C0A}-\u{11C36}\u{11C38}-\u{11C45}\u{11C50}-\u{11C6C}\u{11C70}-\u{11C8F}\u{11C92}-\u{11CA7}\u{11CA9}-\u{11CB6}\u{11D00}-\u{11D06}\u{11D08}\u{11D09}\u{11D0B}-\u{11D36}\u{11D3A}\u{11D3C}\u{11D3D}\u{11D3F}-\u{11D47}\u{11D50}-\u{11D59}\u{11D60}-\u{11D65}\u{11D67}\u{11D68}\u{11D6A}-\u{11D8E}\u{11D90}\u{11D91}\u{11D93}-\u{11D98}\u{11DA0}-\u{11DA9}\u{11EE0}-\u{11EF8}\u{11FB0}\u{11FC0}-\u{11FF1}\u{11FFF}-\u{12399}\u{12400}-\u{1246E}\u{12470}-\u{12474}\u{12480}-\u{12543}\u{12F90}-\u{12FF2}\u{13000}-\u{1342E}\u{13430}-\u{13438}\u{14400}-\u{14646}\u{16800}-\u{16A38}\u{16A40}-\u{16A5E}\u{16A60}-\u{16A69}\u{16A6E}-\u{16ABE}\u{16AC0}-\u{16AC9}\u{16AD0}-\u{16AED}\u{16AF0}-\u{16AF5}\u{16B00}-\u{16B45}\u{16B50}-\u{16B59}\u{16B5B}-\u{16B61}\u{16B63}-\u{16B77}\u{16B7D}-\u{16B8F}\u{16E40}-\u{16E9A}\u{16F00}-\u{16F4A}\u{16F4F}-\u{16F87}\u{16F8F}-\u{16F9F}\u{16FE0}-\u{16FE4}\u{16FF0}\u{16FF1}\u{17000}-\u{187F7}\u{18800}-\u{18CD5}\u{18D00}-\u{18D08}\u{1AFF0}-\u{1AFF3}\u{1AFF5}-\u{1AFFB}\u{1AFFD}\u{1AFFE}\u{1B000}-\u{1B122}\u{1B150}-\u{1B152}\u{1B164}-\u{1B167}\u{1B170}-\u{1B2FB}\u{1BC00}-\u{1BC6A}\u{1BC70}-\u{1BC7C}\u{1BC80}-\u{1BC88}\u{1BC90}-\u{1BC99}\u{1BC9C}-\u{1BCA3}\u{1CF00}-\u{1CF2D}\u{1CF30}-\u{1CF46}\u{1CF50}-\u{1CFC3}\u{1D000}-\u{1D0F5}\u{1D100}-\u{1D126}\u{1D129}-\u{1D1EA}\u{1D200}-\u{1D245}\u{1D2E0}-\u{1D2F3}\u{1D300}-\u{1D356}\u{1D360}-\u{1D378}\u{1D400}-\u{1D454}\u{1D456}-\u{1D49C}\u{1D49E}\u{1D49F}\u{1D4A2}\u{1D4A5}\u{1D4A6}\u{1D4A9}-\u{1D4AC}\u{1D4AE}-\u{1D4B9}\u{1D4BB}\u{1D4BD}-\u{1D4C3}\u{1D4C5}-\u{1D505}\u{1D507}-\u{1D50A}\u{1D50D}-\u{1D514}\u{1D516}-\u{1D51C}\u{1D51E}-\u{1D539}\u{1D53B}-\u{1D53E}\u{1D540}-\u{1D544}\u{1D546}\u{1D54A}-\u{1D550}\u{1D552}-\u{1D6A5}\u{1D6A8}-\u{1D7CB}\u{1D7CE}-\u{1DA8B}\u{1DA9B}-\u{1DA9F}\u{1DAA1}-\u{1DAAF}\u{1DF00}-\u{1DF1E}\u{1E000}-\u{1E006}\u{1E008}-\u{1E018}\u{1E01B}-\u{1E021}\u{1E023}\u{1E024}\u{1E026}-\u{1E02A}\u{1E100}-\u{1E12C}\u{1E130}-\u{1E13D}\u{1E140}-\u{1E149}\u{1E14E}\u{1E14F}\u{1E290}-\u{1E2AE}\u{1E2C0}-\u{1E2F9}\u{1E2FF}\u{1E7E0}-\u{1E7E6}\u{1E7E8}-\u{1E7EB}\u{1E7ED}\u{1E7EE}\u{1E7F0}-\u{1E7FE}\u{1E8D0}-\u{1E8D6}\u{1E944}-\u{1E94A}\u{1EEF0}\u{1EEF1}\u{1F000}-\u{1F02B}\u{1F030}-\u{1F093}\u{1F0A0}-\u{1F0AE}\u{1F0B1}-\u{1F0BF}\u{1F0C1}-\u{1F0CF}\u{1F0D1}-\u{1F0F5}\u{1F100}-\u{1F1AD}\u{1F1E6}-\u{1F202}\u{1F210}-\u{1F23B}\u{1F240}-\u{1F248}\u{1F250}\u{1F251}\u{1F260}-\u{1F265}\u{1F300}-\u{1F6D7}\u{1F6DD}-\u{1F6EC}\u{1F6F0}-\u{1F6FC}\u{1F700}-\u{1F773}\u{1F780}-\u{1F7D8}\u{1F7E0}-\u{1F7EB}\u{1F7F0}\u{1F800}-\u{1F80B}\u{1F810}-\u{1F847}\u{1F850}-\u{1F859}\u{1F860}-\u{1F887}\u{1F890}-\u{1F8AD}\u{1F8B0}\u{1F8B1}\u{1F900}-\u{1FA53}\u{1FA60}-\u{1FA6D}\u{1FA70}-\u{1FA74}\u{1FA78}-\u{1FA7C}\u{1FA80}-\u{1FA86}\u{1FA90}-\u{1FAAC}\u{1FAB0}-\u{1FABA}\u{1FAC0}-\u{1FAC5}\u{1FAD0}-\u{1FAD9}\u{1FAE0}-\u{1FAE7}\u{1FAF0}-\u{1FAF6}\u{1FB00}-\u{1FB92}\u{1FB94}-\u{1FBCA}\u{1FBF0}-\u{1FBF9}\u{20000}-\u{2A6DF}\u{2A700}-\u{2B738}\u{2B740}-\u{2B81D}\u{2B820}-\u{2CEA1}\u{2CEB0}-\u{2EBE0}\u{2F800}-\u{2FA1D}\u{30000}-\u{3134A}\u{E0001}\u{E0020}-\u{E007F}\u{E0100}-\u{E01EF}\u{F0000}-\u{FFFFD}\u{100000}-\u{10FFFD}]*$/u; +const bidiS6 = /[0-9A-Za-z\xAA\xB2\xB3\xB5\xB9\xBA\xC0-\xD6\xD8-\xF6\xF8-\u02B8\u02BB-\u02C1\u02D0\u02D1\u02E0-\u02E4\u02EE\u0370-\u0373\u0376\u0377\u037A-\u037D\u037F\u0386\u0388-\u038A\u038C\u038E-\u03A1\u03A3-\u03F5\u03F7-\u0482\u048A-\u052F\u0531-\u0556\u0559-\u0589\u06F0-\u06F9\u0903-\u0939\u093B\u093D-\u0940\u0949-\u094C\u094E-\u0950\u0958-\u0961\u0964-\u0980\u0982\u0983\u0985-\u098C\u098F\u0990\u0993-\u09A8\u09AA-\u09B0\u09B2\u09B6-\u09B9\u09BD-\u09C0\u09C7\u09C8\u09CB\u09CC\u09CE\u09D7\u09DC\u09DD\u09DF-\u09E1\u09E6-\u09F1\u09F4-\u09FA\u09FC\u09FD\u0A03\u0A05-\u0A0A\u0A0F\u0A10\u0A13-\u0A28\u0A2A-\u0A30\u0A32\u0A33\u0A35\u0A36\u0A38\u0A39\u0A3E-\u0A40\u0A59-\u0A5C\u0A5E\u0A66-\u0A6F\u0A72-\u0A74\u0A76\u0A83\u0A85-\u0A8D\u0A8F-\u0A91\u0A93-\u0AA8\u0AAA-\u0AB0\u0AB2\u0AB3\u0AB5-\u0AB9\u0ABD-\u0AC0\u0AC9\u0ACB\u0ACC\u0AD0\u0AE0\u0AE1\u0AE6-\u0AF0\u0AF9\u0B02\u0B03\u0B05-\u0B0C\u0B0F\u0B10\u0B13-\u0B28\u0B2A-\u0B30\u0B32\u0B33\u0B35-\u0B39\u0B3D\u0B3E\u0B40\u0B47\u0B48\u0B4B\u0B4C\u0B57\u0B5C\u0B5D\u0B5F-\u0B61\u0B66-\u0B77\u0B83\u0B85-\u0B8A\u0B8E-\u0B90\u0B92-\u0B95\u0B99\u0B9A\u0B9C\u0B9E\u0B9F\u0BA3\u0BA4\u0BA8-\u0BAA\u0BAE-\u0BB9\u0BBE\u0BBF\u0BC1\u0BC2\u0BC6-\u0BC8\u0BCA-\u0BCC\u0BD0\u0BD7\u0BE6-\u0BF2\u0C01-\u0C03\u0C05-\u0C0C\u0C0E-\u0C10\u0C12-\u0C28\u0C2A-\u0C39\u0C3D\u0C41-\u0C44\u0C58-\u0C5A\u0C5D\u0C60\u0C61\u0C66-\u0C6F\u0C77\u0C7F\u0C80\u0C82-\u0C8C\u0C8E-\u0C90\u0C92-\u0CA8\u0CAA-\u0CB3\u0CB5-\u0CB9\u0CBD-\u0CC4\u0CC6-\u0CC8\u0CCA\u0CCB\u0CD5\u0CD6\u0CDD\u0CDE\u0CE0\u0CE1\u0CE6-\u0CEF\u0CF1\u0CF2\u0D02-\u0D0C\u0D0E-\u0D10\u0D12-\u0D3A\u0D3D-\u0D40\u0D46-\u0D48\u0D4A-\u0D4C\u0D4E\u0D4F\u0D54-\u0D61\u0D66-\u0D7F\u0D82\u0D83\u0D85-\u0D96\u0D9A-\u0DB1\u0DB3-\u0DBB\u0DBD\u0DC0-\u0DC6\u0DCF-\u0DD1\u0DD8-\u0DDF\u0DE6-\u0DEF\u0DF2-\u0DF4\u0E01-\u0E30\u0E32\u0E33\u0E40-\u0E46\u0E4F-\u0E5B\u0E81\u0E82\u0E84\u0E86-\u0E8A\u0E8C-\u0EA3\u0EA5\u0EA7-\u0EB0\u0EB2\u0EB3\u0EBD\u0EC0-\u0EC4\u0EC6\u0ED0-\u0ED9\u0EDC-\u0EDF\u0F00-\u0F17\u0F1A-\u0F34\u0F36\u0F38\u0F3E-\u0F47\u0F49-\u0F6C\u0F7F\u0F85\u0F88-\u0F8C\u0FBE-\u0FC5\u0FC7-\u0FCC\u0FCE-\u0FDA\u1000-\u102C\u1031\u1038\u103B\u103C\u103F-\u1057\u105A-\u105D\u1061-\u1070\u1075-\u1081\u1083\u1084\u1087-\u108C\u108E-\u109C\u109E-\u10C5\u10C7\u10CD\u10D0-\u1248\u124A-\u124D\u1250-\u1256\u1258\u125A-\u125D\u1260-\u1288\u128A-\u128D\u1290-\u12B0\u12B2-\u12B5\u12B8-\u12BE\u12C0\u12C2-\u12C5\u12C8-\u12D6\u12D8-\u1310\u1312-\u1315\u1318-\u135A\u1360-\u137C\u1380-\u138F\u13A0-\u13F5\u13F8-\u13FD\u1401-\u167F\u1681-\u169A\u16A0-\u16F8\u1700-\u1711\u1715\u171F-\u1731\u1734-\u1736\u1740-\u1751\u1760-\u176C\u176E-\u1770\u1780-\u17B3\u17B6\u17BE-\u17C5\u17C7\u17C8\u17D4-\u17DA\u17DC\u17E0-\u17E9\u1810-\u1819\u1820-\u1878\u1880-\u1884\u1887-\u18A8\u18AA\u18B0-\u18F5\u1900-\u191E\u1923-\u1926\u1929-\u192B\u1930\u1931\u1933-\u1938\u1946-\u196D\u1970-\u1974\u1980-\u19AB\u19B0-\u19C9\u19D0-\u19DA\u1A00-\u1A16\u1A19\u1A1A\u1A1E-\u1A55\u1A57\u1A61\u1A63\u1A64\u1A6D-\u1A72\u1A80-\u1A89\u1A90-\u1A99\u1AA0-\u1AAD\u1B04-\u1B33\u1B35\u1B3B\u1B3D-\u1B41\u1B43-\u1B4C\u1B50-\u1B6A\u1B74-\u1B7E\u1B82-\u1BA1\u1BA6\u1BA7\u1BAA\u1BAE-\u1BE5\u1BE7\u1BEA-\u1BEC\u1BEE\u1BF2\u1BF3\u1BFC-\u1C2B\u1C34\u1C35\u1C3B-\u1C49\u1C4D-\u1C88\u1C90-\u1CBA\u1CBD-\u1CC7\u1CD3\u1CE1\u1CE9-\u1CEC\u1CEE-\u1CF3\u1CF5-\u1CF7\u1CFA\u1D00-\u1DBF\u1E00-\u1F15\u1F18-\u1F1D\u1F20-\u1F45\u1F48-\u1F4D\u1F50-\u1F57\u1F59\u1F5B\u1F5D\u1F5F-\u1F7D\u1F80-\u1FB4\u1FB6-\u1FBC\u1FBE\u1FC2-\u1FC4\u1FC6-\u1FCC\u1FD0-\u1FD3\u1FD6-\u1FDB\u1FE0-\u1FEC\u1FF2-\u1FF4\u1FF6-\u1FFC\u200E\u2070\u2071\u2074-\u2079\u207F-\u2089\u2090-\u209C\u2102\u2107\u210A-\u2113\u2115\u2119-\u211D\u2124\u2126\u2128\u212A-\u212D\u212F-\u2139\u213C-\u213F\u2145-\u2149\u214E\u214F\u2160-\u2188\u2336-\u237A\u2395\u2488-\u24E9\u26AC\u2800-\u28FF\u2C00-\u2CE4\u2CEB-\u2CEE\u2CF2\u2CF3\u2D00-\u2D25\u2D27\u2D2D\u2D30-\u2D67\u2D6F\u2D70\u2D80-\u2D96\u2DA0-\u2DA6\u2DA8-\u2DAE\u2DB0-\u2DB6\u2DB8-\u2DBE\u2DC0-\u2DC6\u2DC8-\u2DCE\u2DD0-\u2DD6\u2DD8-\u2DDE\u3005-\u3007\u3021-\u3029\u302E\u302F\u3031-\u3035\u3038-\u303C\u3041-\u3096\u309D-\u309F\u30A1-\u30FA\u30FC-\u30FF\u3105-\u312F\u3131-\u318E\u3190-\u31BF\u31F0-\u321C\u3220-\u324F\u3260-\u327B\u327F-\u32B0\u32C0-\u32CB\u32D0-\u3376\u337B-\u33DD\u33E0-\u33FE\u3400-\u4DBF\u4E00-\uA48C\uA4D0-\uA60C\uA610-\uA62B\uA640-\uA66E\uA680-\uA69D\uA6A0-\uA6EF\uA6F2-\uA6F7\uA722-\uA787\uA789-\uA7CA\uA7D0\uA7D1\uA7D3\uA7D5-\uA7D9\uA7F2-\uA801\uA803-\uA805\uA807-\uA80A\uA80C-\uA824\uA827\uA830-\uA837\uA840-\uA873\uA880-\uA8C3\uA8CE-\uA8D9\uA8F2-\uA8FE\uA900-\uA925\uA92E-\uA946\uA952\uA953\uA95F-\uA97C\uA983-\uA9B2\uA9B4\uA9B5\uA9BA\uA9BB\uA9BE-\uA9CD\uA9CF-\uA9D9\uA9DE-\uA9E4\uA9E6-\uA9FE\uAA00-\uAA28\uAA2F\uAA30\uAA33\uAA34\uAA40-\uAA42\uAA44-\uAA4B\uAA4D\uAA50-\uAA59\uAA5C-\uAA7B\uAA7D-\uAAAF\uAAB1\uAAB5\uAAB6\uAAB9-\uAABD\uAAC0\uAAC2\uAADB-\uAAEB\uAAEE-\uAAF5\uAB01-\uAB06\uAB09-\uAB0E\uAB11-\uAB16\uAB20-\uAB26\uAB28-\uAB2E\uAB30-\uAB69\uAB70-\uABE4\uABE6\uABE7\uABE9-\uABEC\uABF0-\uABF9\uAC00-\uD7A3\uD7B0-\uD7C6\uD7CB-\uD7FB\uD800-\uFA6D\uFA70-\uFAD9\uFB00-\uFB06\uFB13-\uFB17\uFF10-\uFF19\uFF21-\uFF3A\uFF41-\uFF5A\uFF66-\uFFBE\uFFC2-\uFFC7\uFFCA-\uFFCF\uFFD2-\uFFD7\uFFDA-\uFFDC\u{10000}-\u{1000B}\u{1000D}-\u{10026}\u{10028}-\u{1003A}\u{1003C}\u{1003D}\u{1003F}-\u{1004D}\u{10050}-\u{1005D}\u{10080}-\u{100FA}\u{10100}\u{10102}\u{10107}-\u{10133}\u{10137}-\u{1013F}\u{1018D}\u{1018E}\u{101D0}-\u{101FC}\u{10280}-\u{1029C}\u{102A0}-\u{102D0}\u{102E1}-\u{102FB}\u{10300}-\u{10323}\u{1032D}-\u{1034A}\u{10350}-\u{10375}\u{10380}-\u{1039D}\u{1039F}-\u{103C3}\u{103C8}-\u{103D5}\u{10400}-\u{1049D}\u{104A0}-\u{104A9}\u{104B0}-\u{104D3}\u{104D8}-\u{104FB}\u{10500}-\u{10527}\u{10530}-\u{10563}\u{1056F}-\u{1057A}\u{1057C}-\u{1058A}\u{1058C}-\u{10592}\u{10594}\u{10595}\u{10597}-\u{105A1}\u{105A3}-\u{105B1}\u{105B3}-\u{105B9}\u{105BB}\u{105BC}\u{10600}-\u{10736}\u{10740}-\u{10755}\u{10760}-\u{10767}\u{10780}-\u{10785}\u{10787}-\u{107B0}\u{107B2}-\u{107BA}\u{11000}\u{11002}-\u{11037}\u{11047}-\u{1104D}\u{11066}-\u{1106F}\u{11071}\u{11072}\u{11075}\u{11082}-\u{110B2}\u{110B7}\u{110B8}\u{110BB}-\u{110C1}\u{110CD}\u{110D0}-\u{110E8}\u{110F0}-\u{110F9}\u{11103}-\u{11126}\u{1112C}\u{11136}-\u{11147}\u{11150}-\u{11172}\u{11174}-\u{11176}\u{11182}-\u{111B5}\u{111BF}-\u{111C8}\u{111CD}\u{111CE}\u{111D0}-\u{111DF}\u{111E1}-\u{111F4}\u{11200}-\u{11211}\u{11213}-\u{1122E}\u{11232}\u{11233}\u{11235}\u{11238}-\u{1123D}\u{11280}-\u{11286}\u{11288}\u{1128A}-\u{1128D}\u{1128F}-\u{1129D}\u{1129F}-\u{112A9}\u{112B0}-\u{112DE}\u{112E0}-\u{112E2}\u{112F0}-\u{112F9}\u{11302}\u{11303}\u{11305}-\u{1130C}\u{1130F}\u{11310}\u{11313}-\u{11328}\u{1132A}-\u{11330}\u{11332}\u{11333}\u{11335}-\u{11339}\u{1133D}-\u{1133F}\u{11341}-\u{11344}\u{11347}\u{11348}\u{1134B}-\u{1134D}\u{11350}\u{11357}\u{1135D}-\u{11363}\u{11400}-\u{11437}\u{11440}\u{11441}\u{11445}\u{11447}-\u{1145B}\u{1145D}\u{1145F}-\u{11461}\u{11480}-\u{114B2}\u{114B9}\u{114BB}-\u{114BE}\u{114C1}\u{114C4}-\u{114C7}\u{114D0}-\u{114D9}\u{11580}-\u{115B1}\u{115B8}-\u{115BB}\u{115BE}\u{115C1}-\u{115DB}\u{11600}-\u{11632}\u{1163B}\u{1163C}\u{1163E}\u{11641}-\u{11644}\u{11650}-\u{11659}\u{11680}-\u{116AA}\u{116AC}\u{116AE}\u{116AF}\u{116B6}\u{116B8}\u{116B9}\u{116C0}-\u{116C9}\u{11700}-\u{1171A}\u{11720}\u{11721}\u{11726}\u{11730}-\u{11746}\u{11800}-\u{1182E}\u{11838}\u{1183B}\u{118A0}-\u{118F2}\u{118FF}-\u{11906}\u{11909}\u{1190C}-\u{11913}\u{11915}\u{11916}\u{11918}-\u{11935}\u{11937}\u{11938}\u{1193D}\u{1193F}-\u{11942}\u{11944}-\u{11946}\u{11950}-\u{11959}\u{119A0}-\u{119A7}\u{119AA}-\u{119D3}\u{119DC}-\u{119DF}\u{119E1}-\u{119E4}\u{11A00}\u{11A07}\u{11A08}\u{11A0B}-\u{11A32}\u{11A39}\u{11A3A}\u{11A3F}-\u{11A46}\u{11A50}\u{11A57}\u{11A58}\u{11A5C}-\u{11A89}\u{11A97}\u{11A9A}-\u{11AA2}\u{11AB0}-\u{11AF8}\u{11C00}-\u{11C08}\u{11C0A}-\u{11C2F}\u{11C3E}-\u{11C45}\u{11C50}-\u{11C6C}\u{11C70}-\u{11C8F}\u{11CA9}\u{11CB1}\u{11CB4}\u{11D00}-\u{11D06}\u{11D08}\u{11D09}\u{11D0B}-\u{11D30}\u{11D46}\u{11D50}-\u{11D59}\u{11D60}-\u{11D65}\u{11D67}\u{11D68}\u{11D6A}-\u{11D8E}\u{11D93}\u{11D94}\u{11D96}\u{11D98}\u{11DA0}-\u{11DA9}\u{11EE0}-\u{11EF2}\u{11EF5}-\u{11EF8}\u{11FB0}\u{11FC0}-\u{11FD4}\u{11FFF}-\u{12399}\u{12400}-\u{1246E}\u{12470}-\u{12474}\u{12480}-\u{12543}\u{12F90}-\u{12FF2}\u{13000}-\u{1342E}\u{13430}-\u{13438}\u{14400}-\u{14646}\u{16800}-\u{16A38}\u{16A40}-\u{16A5E}\u{16A60}-\u{16A69}\u{16A6E}-\u{16ABE}\u{16AC0}-\u{16AC9}\u{16AD0}-\u{16AED}\u{16AF5}\u{16B00}-\u{16B2F}\u{16B37}-\u{16B45}\u{16B50}-\u{16B59}\u{16B5B}-\u{16B61}\u{16B63}-\u{16B77}\u{16B7D}-\u{16B8F}\u{16E40}-\u{16E9A}\u{16F00}-\u{16F4A}\u{16F50}-\u{16F87}\u{16F93}-\u{16F9F}\u{16FE0}\u{16FE1}\u{16FE3}\u{16FF0}\u{16FF1}\u{17000}-\u{187F7}\u{18800}-\u{18CD5}\u{18D00}-\u{18D08}\u{1AFF0}-\u{1AFF3}\u{1AFF5}-\u{1AFFB}\u{1AFFD}\u{1AFFE}\u{1B000}-\u{1B122}\u{1B150}-\u{1B152}\u{1B164}-\u{1B167}\u{1B170}-\u{1B2FB}\u{1BC00}-\u{1BC6A}\u{1BC70}-\u{1BC7C}\u{1BC80}-\u{1BC88}\u{1BC90}-\u{1BC99}\u{1BC9C}\u{1BC9F}\u{1CF50}-\u{1CFC3}\u{1D000}-\u{1D0F5}\u{1D100}-\u{1D126}\u{1D129}-\u{1D166}\u{1D16A}-\u{1D172}\u{1D183}\u{1D184}\u{1D18C}-\u{1D1A9}\u{1D1AE}-\u{1D1E8}\u{1D2E0}-\u{1D2F3}\u{1D360}-\u{1D378}\u{1D400}-\u{1D454}\u{1D456}-\u{1D49C}\u{1D49E}\u{1D49F}\u{1D4A2}\u{1D4A5}\u{1D4A6}\u{1D4A9}-\u{1D4AC}\u{1D4AE}-\u{1D4B9}\u{1D4BB}\u{1D4BD}-\u{1D4C3}\u{1D4C5}-\u{1D505}\u{1D507}-\u{1D50A}\u{1D50D}-\u{1D514}\u{1D516}-\u{1D51C}\u{1D51E}-\u{1D539}\u{1D53B}-\u{1D53E}\u{1D540}-\u{1D544}\u{1D546}\u{1D54A}-\u{1D550}\u{1D552}-\u{1D6A5}\u{1D6A8}-\u{1D6DA}\u{1D6DC}-\u{1D714}\u{1D716}-\u{1D74E}\u{1D750}-\u{1D788}\u{1D78A}-\u{1D7C2}\u{1D7C4}-\u{1D7CB}\u{1D7CE}-\u{1D9FF}\u{1DA37}-\u{1DA3A}\u{1DA6D}-\u{1DA74}\u{1DA76}-\u{1DA83}\u{1DA85}-\u{1DA8B}\u{1DF00}-\u{1DF1E}\u{1E100}-\u{1E12C}\u{1E137}-\u{1E13D}\u{1E140}-\u{1E149}\u{1E14E}\u{1E14F}\u{1E290}-\u{1E2AD}\u{1E2C0}-\u{1E2EB}\u{1E2F0}-\u{1E2F9}\u{1E7E0}-\u{1E7E6}\u{1E7E8}-\u{1E7EB}\u{1E7ED}\u{1E7EE}\u{1E7F0}-\u{1E7FE}\u{1F100}-\u{1F10A}\u{1F110}-\u{1F12E}\u{1F130}-\u{1F169}\u{1F170}-\u{1F1AC}\u{1F1E6}-\u{1F202}\u{1F210}-\u{1F23B}\u{1F240}-\u{1F248}\u{1F250}\u{1F251}\u{1FBF0}-\u{1FBF9}\u{20000}-\u{2A6DF}\u{2A700}-\u{2B738}\u{2B740}-\u{2B81D}\u{2B820}-\u{2CEA1}\u{2CEB0}-\u{2EBE0}\u{2F800}-\u{2FA1D}\u{30000}-\u{3134A}\u{F0000}-\u{FFFFD}\u{100000}-\u{10FFFD}][\u0300-\u036F\u0483-\u0489\u0591-\u05BD\u05BF\u05C1\u05C2\u05C4\u05C5\u05C7\u0610-\u061A\u064B-\u065F\u0670\u06D6-\u06DC\u06DF-\u06E4\u06E7\u06E8\u06EA-\u06ED\u0711\u0730-\u074A\u07A6-\u07B0\u07EB-\u07F3\u07FD\u0816-\u0819\u081B-\u0823\u0825-\u0827\u0829-\u082D\u0859-\u085B\u0898-\u089F\u08CA-\u08E1\u08E3-\u0902\u093A\u093C\u0941-\u0948\u094D\u0951-\u0957\u0962\u0963\u0981\u09BC\u09C1-\u09C4\u09CD\u09E2\u09E3\u09FE\u0A01\u0A02\u0A3C\u0A41\u0A42\u0A47\u0A48\u0A4B-\u0A4D\u0A51\u0A70\u0A71\u0A75\u0A81\u0A82\u0ABC\u0AC1-\u0AC5\u0AC7\u0AC8\u0ACD\u0AE2\u0AE3\u0AFA-\u0AFF\u0B01\u0B3C\u0B3F\u0B41-\u0B44\u0B4D\u0B55\u0B56\u0B62\u0B63\u0B82\u0BC0\u0BCD\u0C00\u0C04\u0C3C\u0C3E-\u0C40\u0C46-\u0C48\u0C4A-\u0C4D\u0C55\u0C56\u0C62\u0C63\u0C81\u0CBC\u0CCC\u0CCD\u0CE2\u0CE3\u0D00\u0D01\u0D3B\u0D3C\u0D41-\u0D44\u0D4D\u0D62\u0D63\u0D81\u0DCA\u0DD2-\u0DD4\u0DD6\u0E31\u0E34-\u0E3A\u0E47-\u0E4E\u0EB1\u0EB4-\u0EBC\u0EC8-\u0ECD\u0F18\u0F19\u0F35\u0F37\u0F39\u0F71-\u0F7E\u0F80-\u0F84\u0F86\u0F87\u0F8D-\u0F97\u0F99-\u0FBC\u0FC6\u102D-\u1030\u1032-\u1037\u1039\u103A\u103D\u103E\u1058\u1059\u105E-\u1060\u1071-\u1074\u1082\u1085\u1086\u108D\u109D\u135D-\u135F\u1712-\u1714\u1732\u1733\u1752\u1753\u1772\u1773\u17B4\u17B5\u17B7-\u17BD\u17C6\u17C9-\u17D3\u17DD\u180B-\u180D\u180F\u1885\u1886\u18A9\u1920-\u1922\u1927\u1928\u1932\u1939-\u193B\u1A17\u1A18\u1A1B\u1A56\u1A58-\u1A5E\u1A60\u1A62\u1A65-\u1A6C\u1A73-\u1A7C\u1A7F\u1AB0-\u1ACE\u1B00-\u1B03\u1B34\u1B36-\u1B3A\u1B3C\u1B42\u1B6B-\u1B73\u1B80\u1B81\u1BA2-\u1BA5\u1BA8\u1BA9\u1BAB-\u1BAD\u1BE6\u1BE8\u1BE9\u1BED\u1BEF-\u1BF1\u1C2C-\u1C33\u1C36\u1C37\u1CD0-\u1CD2\u1CD4-\u1CE0\u1CE2-\u1CE8\u1CED\u1CF4\u1CF8\u1CF9\u1DC0-\u1DFF\u20D0-\u20F0\u2CEF-\u2CF1\u2D7F\u2DE0-\u2DFF\u302A-\u302D\u3099\u309A\uA66F-\uA672\uA674-\uA67D\uA69E\uA69F\uA6F0\uA6F1\uA802\uA806\uA80B\uA825\uA826\uA82C\uA8C4\uA8C5\uA8E0-\uA8F1\uA8FF\uA926-\uA92D\uA947-\uA951\uA980-\uA982\uA9B3\uA9B6-\uA9B9\uA9BC\uA9BD\uA9E5\uAA29-\uAA2E\uAA31\uAA32\uAA35\uAA36\uAA43\uAA4C\uAA7C\uAAB0\uAAB2-\uAAB4\uAAB7\uAAB8\uAABE\uAABF\uAAC1\uAAEC\uAAED\uAAF6\uABE5\uABE8\uABED\uFB1E\uFE00-\uFE0F\uFE20-\uFE2F\u{101FD}\u{102E0}\u{10376}-\u{1037A}\u{10A01}-\u{10A03}\u{10A05}\u{10A06}\u{10A0C}-\u{10A0F}\u{10A38}-\u{10A3A}\u{10A3F}\u{10AE5}\u{10AE6}\u{10D24}-\u{10D27}\u{10EAB}\u{10EAC}\u{10F46}-\u{10F50}\u{10F82}-\u{10F85}\u{11001}\u{11038}-\u{11046}\u{11070}\u{11073}\u{11074}\u{1107F}-\u{11081}\u{110B3}-\u{110B6}\u{110B9}\u{110BA}\u{110C2}\u{11100}-\u{11102}\u{11127}-\u{1112B}\u{1112D}-\u{11134}\u{11173}\u{11180}\u{11181}\u{111B6}-\u{111BE}\u{111C9}-\u{111CC}\u{111CF}\u{1122F}-\u{11231}\u{11234}\u{11236}\u{11237}\u{1123E}\u{112DF}\u{112E3}-\u{112EA}\u{11300}\u{11301}\u{1133B}\u{1133C}\u{11340}\u{11366}-\u{1136C}\u{11370}-\u{11374}\u{11438}-\u{1143F}\u{11442}-\u{11444}\u{11446}\u{1145E}\u{114B3}-\u{114B8}\u{114BA}\u{114BF}\u{114C0}\u{114C2}\u{114C3}\u{115B2}-\u{115B5}\u{115BC}\u{115BD}\u{115BF}\u{115C0}\u{115DC}\u{115DD}\u{11633}-\u{1163A}\u{1163D}\u{1163F}\u{11640}\u{116AB}\u{116AD}\u{116B0}-\u{116B5}\u{116B7}\u{1171D}-\u{1171F}\u{11722}-\u{11725}\u{11727}-\u{1172B}\u{1182F}-\u{11837}\u{11839}\u{1183A}\u{1193B}\u{1193C}\u{1193E}\u{11943}\u{119D4}-\u{119D7}\u{119DA}\u{119DB}\u{119E0}\u{11A01}-\u{11A06}\u{11A09}\u{11A0A}\u{11A33}-\u{11A38}\u{11A3B}-\u{11A3E}\u{11A47}\u{11A51}-\u{11A56}\u{11A59}-\u{11A5B}\u{11A8A}-\u{11A96}\u{11A98}\u{11A99}\u{11C30}-\u{11C36}\u{11C38}-\u{11C3D}\u{11C92}-\u{11CA7}\u{11CAA}-\u{11CB0}\u{11CB2}\u{11CB3}\u{11CB5}\u{11CB6}\u{11D31}-\u{11D36}\u{11D3A}\u{11D3C}\u{11D3D}\u{11D3F}-\u{11D45}\u{11D47}\u{11D90}\u{11D91}\u{11D95}\u{11D97}\u{11EF3}\u{11EF4}\u{16AF0}-\u{16AF4}\u{16B30}-\u{16B36}\u{16F4F}\u{16F8F}-\u{16F92}\u{16FE4}\u{1BC9D}\u{1BC9E}\u{1CF00}-\u{1CF2D}\u{1CF30}-\u{1CF46}\u{1D167}-\u{1D169}\u{1D17B}-\u{1D182}\u{1D185}-\u{1D18B}\u{1D1AA}-\u{1D1AD}\u{1D242}-\u{1D244}\u{1DA00}-\u{1DA36}\u{1DA3B}-\u{1DA6C}\u{1DA75}\u{1DA84}\u{1DA9B}-\u{1DA9F}\u{1DAA1}-\u{1DAAF}\u{1E000}-\u{1E006}\u{1E008}-\u{1E018}\u{1E01B}-\u{1E021}\u{1E023}\u{1E024}\u{1E026}-\u{1E02A}\u{1E130}-\u{1E136}\u{1E2AE}\u{1E2EC}-\u{1E2EF}\u{1E8D0}-\u{1E8D6}\u{1E944}-\u{1E94A}\u{E0100}-\u{E01EF}]*$/u; + +module.exports = { + combiningMarks, + combiningClassVirama, + validZWNJ, + bidiDomain, + bidiS1LTR, + bidiS1RTL, + bidiS2, + bidiS3, + bidiS4EN, + bidiS4AN, + bidiS5, + bidiS6 +}; diff --git a/ts-ticket-office-service/node_modules/tr46/lib/statusMapping.js b/ts-ticket-office-service/node_modules/tr46/lib/statusMapping.js new file mode 100644 index 000000000..cfed6d6a7 --- /dev/null +++ b/ts-ticket-office-service/node_modules/tr46/lib/statusMapping.js @@ -0,0 +1,11 @@ +"use strict"; + +module.exports.STATUS_MAPPING = { + mapped: 1, + valid: 2, + disallowed: 3, + disallowed_STD3_valid: 4, + disallowed_STD3_mapped: 5, + deviation: 6, + ignored: 7 +}; diff --git a/ts-ticket-office-service/node_modules/tr46/package.json b/ts-ticket-office-service/node_modules/tr46/package.json new file mode 100644 index 000000000..8e79ba6cd --- /dev/null +++ b/ts-ticket-office-service/node_modules/tr46/package.json @@ -0,0 +1,47 @@ +{ + "name": "tr46", + "version": "3.0.0", + "engines": { + "node": ">=12" + }, + "description": "An implementation of the Unicode UTS #46: Unicode IDNA Compatibility Processing", + "main": "index.js", + "files": [ + "index.js", + "lib/mappingTable.json", + "lib/regexes.js", + "lib/statusMapping.js" + ], + "scripts": { + "test": "mocha", + "lint": "eslint .", + "pretest": "node scripts/getLatestTests.js", + "prepublish": "node scripts/generateMappingTable.js && node scripts/generateRegexes.js" + }, + "repository": "https://github.com/jsdom/tr46", + "keywords": [ + "unicode", + "tr46", + "uts46", + "punycode", + "url", + "whatwg" + ], + "author": "Sebastian Mayr ", + "contributors": [ + "Timothy Gu " + ], + "license": "MIT", + "dependencies": { + "punycode": "^2.1.1" + }, + "devDependencies": { + "@domenic/eslint-config": "^1.4.0", + "@unicode/unicode-14.0.0": "^1.2.1", + "eslint": "^7.32.0", + "minipass-fetch": "^1.4.1", + "mocha": "^9.1.1", + "regenerate": "^1.4.2" + }, + "unicodeVersion": "14.0.0" +} diff --git a/ts-ticket-office-service/node_modules/transformers/node_modules/.bin/uglifyjs b/ts-ticket-office-service/node_modules/transformers/node_modules/.bin/uglifyjs deleted file mode 100644 index de7b74f60..000000000 --- a/ts-ticket-office-service/node_modules/transformers/node_modules/.bin/uglifyjs +++ /dev/null @@ -1,15 +0,0 @@ -#!/bin/sh -basedir=$(dirname "$(echo "$0" | sed -e 's,\\,/,g')") - -case `uname` in - *CYGWIN*) basedir=`cygpath -w "$basedir"`;; -esac - -if [ -x "$basedir/node" ]; then - "$basedir/node" "$basedir/../uglify-js/bin/uglifyjs" "$@" - ret=$? -else - node "$basedir/../uglify-js/bin/uglifyjs" "$@" - ret=$? -fi -exit $ret diff --git a/ts-ticket-office-service/node_modules/transformers/node_modules/.bin/uglifyjs b/ts-ticket-office-service/node_modules/transformers/node_modules/.bin/uglifyjs new file mode 120000 index 000000000..fef3468b6 --- /dev/null +++ b/ts-ticket-office-service/node_modules/transformers/node_modules/.bin/uglifyjs @@ -0,0 +1 @@ +../uglify-js/bin/uglifyjs \ No newline at end of file diff --git a/ts-ticket-office-service/node_modules/transformers/node_modules/uglify-js/bin/uglifyjs b/ts-ticket-office-service/node_modules/transformers/node_modules/uglify-js/bin/uglifyjs old mode 100644 new mode 100755 diff --git a/ts-ticket-office-service/node_modules/uglify-js/bin/uglifyjs b/ts-ticket-office-service/node_modules/uglify-js/bin/uglifyjs old mode 100644 new mode 100755 diff --git a/ts-ticket-office-service/node_modules/webidl-conversions/LICENSE.md b/ts-ticket-office-service/node_modules/webidl-conversions/LICENSE.md new file mode 100644 index 000000000..d4a994f50 --- /dev/null +++ b/ts-ticket-office-service/node_modules/webidl-conversions/LICENSE.md @@ -0,0 +1,12 @@ +# The BSD 2-Clause License + +Copyright (c) 2014, Domenic Denicola +All rights reserved. + +Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: + +1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. + +2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. diff --git a/ts-ticket-office-service/node_modules/webidl-conversions/README.md b/ts-ticket-office-service/node_modules/webidl-conversions/README.md new file mode 100644 index 000000000..16cc39315 --- /dev/null +++ b/ts-ticket-office-service/node_modules/webidl-conversions/README.md @@ -0,0 +1,99 @@ +# Web IDL Type Conversions on JavaScript Values + +This package implements, in JavaScript, the algorithms to convert a given JavaScript value according to a given [Web IDL](http://heycam.github.io/webidl/) [type](http://heycam.github.io/webidl/#idl-types). + +The goal is that you should be able to write code like + +```js +"use strict"; +const conversions = require("webidl-conversions"); + +function doStuff(x, y) { + x = conversions["boolean"](x); + y = conversions["unsigned long"](y); + // actual algorithm code here +} +``` + +and your function `doStuff` will behave the same as a Web IDL operation declared as + +```webidl +undefined doStuff(boolean x, unsigned long y); +``` + +## API + +This package's main module's default export is an object with a variety of methods, each corresponding to a different Web IDL type. Each method, when invoked on a JavaScript value, will give back the new JavaScript value that results after passing through the Web IDL conversion rules. (See below for more details on what that means.) Alternately, the method could throw an error, if the Web IDL algorithm is specified to do so: for example `conversions["float"](NaN)` [will throw a `TypeError`](http://heycam.github.io/webidl/#es-float). + +Each method also accepts a second, optional, parameter for miscellaneous options. For conversion methods that throw errors, a string option `{ context }` may be provided to provide more information in the error message. (For example, `conversions["float"](NaN, { context: "Argument 1 of Interface's operation" })` will throw an error with message `"Argument 1 of Interface's operation is not a finite floating-point value."`) + +If we are dealing with multiple JavaScript realms (such as those created using Node.js' [vm](https://nodejs.org/api/vm.html) module or the HTML `iframe` element), and exceptions from another realm need to be thrown, one can supply an object option `globals` containing the following properties: + +```js +{ + globals: { + Number, + String, + TypeError + } +} +``` + +Those specific functions will be used when throwing exceptions. + +Specific conversions may also accept other options, the details of which can be found below. + +## Conversions implemented + +Conversions for all of the basic types from the Web IDL specification are implemented: + +- [`any`](https://heycam.github.io/webidl/#es-any) +- [`undefined`](https://heycam.github.io/webidl/#es-undefined) +- [`boolean`](https://heycam.github.io/webidl/#es-boolean) +- [Integer types](https://heycam.github.io/webidl/#es-integer-types), which can additionally be provided the boolean options `{ clamp, enforceRange }` as a second parameter +- [`float`](https://heycam.github.io/webidl/#es-float), [`unrestricted float`](https://heycam.github.io/webidl/#es-unrestricted-float) +- [`double`](https://heycam.github.io/webidl/#es-double), [`unrestricted double`](https://heycam.github.io/webidl/#es-unrestricted-double) +- [`DOMString`](https://heycam.github.io/webidl/#es-DOMString), which can additionally be provided the boolean option `{ treatNullAsEmptyString }` as a second parameter +- [`ByteString`](https://heycam.github.io/webidl/#es-ByteString), [`USVString`](https://heycam.github.io/webidl/#es-USVString) +- [`object`](https://heycam.github.io/webidl/#es-object) +- [Buffer source types](https://heycam.github.io/webidl/#es-buffer-source-types), which can additionally be provided with the boolean option `{ allowShared }` as a second parameter + +Additionally, for convenience, the following derived type definitions are implemented: + +- [`ArrayBufferView`](https://heycam.github.io/webidl/#ArrayBufferView), which can additionally be provided with the boolean option `{ allowShared }` as a second parameter +- [`BufferSource`](https://heycam.github.io/webidl/#BufferSource) +- [`DOMTimeStamp`](https://heycam.github.io/webidl/#DOMTimeStamp) + +Derived types, such as nullable types, promise types, sequences, records, etc. are not handled by this library. You may wish to investigate the [webidl2js](https://github.com/jsdom/webidl2js) project. + +### A note on the `long long` types + +The `long long` and `unsigned long long` Web IDL types can hold values that cannot be stored in JavaScript numbers. Conversions are still accurate as we make use of BigInt in the conversion process, but in the case of `unsigned long long` we simply cannot represent some possible output values in JavaScript. For example, converting the JavaScript number `-1` to a Web IDL `unsigned long long` is supposed to produce the Web IDL value `18446744073709551615`. Since we are representing our Web IDL values in JavaScript, we can't represent `18446744073709551615`, so we instead the best we could do is `18446744073709551616` as the output. + +To mitigate this, we could return the raw BigInt value from the conversion function, but right now it is not implemented. If your use case requires such precision, [file an issue](https://github.com/jsdom/webidl-conversions/issues/new). + +On the other hand, `long long` conversion is always accurate, since the input value can never be more precise than the output value. + +### A note on `BufferSource` types + +All of the `BufferSource` types will throw when the relevant `ArrayBuffer` has been detached. This technically is not part of the [specified conversion algorithm](https://heycam.github.io/webidl/#es-buffer-source-types), but instead part of the [getting a reference/getting a copy](https://heycam.github.io/webidl/#ref-for-dfn-get-buffer-source-reference%E2%91%A0) algorithms. We've consolidated them here for convenience and ease of implementation, but if there is a need to separate them in the future, please open an issue so we can investigate. + +## Background + +What's actually going on here, conceptually, is pretty weird. Let's try to explain. + +Web IDL, as part of its madness-inducing design, has its own type system. When people write algorithms in web platform specs, they usually operate on Web IDL values, i.e. instances of Web IDL types. For example, if they were specifying the algorithm for our `doStuff` operation above, they would treat `x` as a Web IDL value of [Web IDL type `boolean`](http://heycam.github.io/webidl/#idl-boolean). Crucially, they would _not_ treat `x` as a JavaScript variable whose value is either the JavaScript `true` or `false`. They're instead working in a different type system altogether, with its own rules. + +Separately from its type system, Web IDL defines a ["binding"](http://heycam.github.io/webidl/#ecmascript-binding) of the type system into JavaScript. This contains rules like: when you pass a JavaScript value to the JavaScript method that manifests a given Web IDL operation, how does that get converted into a Web IDL value? For example, a JavaScript `true` passed in the position of a Web IDL `boolean` argument becomes a Web IDL `true`. But, a JavaScript `true` passed in the position of a [Web IDL `unsigned long`](http://heycam.github.io/webidl/#idl-unsigned-long) becomes a Web IDL `1`. And so on. + +Finally, we have the actual implementation code. This is usually C++, although these days [some smart people are using Rust](https://github.com/servo/servo). The implementation, of course, has its own type system. So when they implement the Web IDL algorithms, they don't actually use Web IDL values, since those aren't "real" outside of specs. Instead, implementations apply the Web IDL binding rules in such a way as to convert incoming JavaScript values into C++ values. For example, if code in the browser called `doStuff(true, true)`, then the implementation code would eventually receive a C++ `bool` containing `true` and a C++ `uint32_t` containing `1`. + +The upside of all this is that implementations can abstract all the conversion logic away, letting Web IDL handle it, and focus on implementing the relevant methods in C++ with values of the correct type already provided. That is payoff of Web IDL, in a nutshell. + +And getting to that payoff is the goal of _this_ project—but for JavaScript implementations, instead of C++ ones. That is, this library is designed to make it easier for JavaScript developers to write functions that behave like a given Web IDL operation. So conceptually, the conversion pipeline, which in its general form is JavaScript values ↦ Web IDL values ↦ implementation-language values, in this case becomes JavaScript values ↦ Web IDL values ↦ JavaScript values. And that intermediate step is where all the logic is performed: a JavaScript `true` becomes a Web IDL `1` in an unsigned long context, which then becomes a JavaScript `1`. + +## Don't use this + +Seriously, why would you ever use this? You really shouldn't. Web IDL is … strange, and you shouldn't be emulating its semantics. If you're looking for a generic argument-processing library, you should find one with better rules than those from Web IDL. In general, your JavaScript should not be trying to become more like Web IDL; if anything, we should fix Web IDL to make it more like JavaScript. + +The _only_ people who should use this are those trying to create faithful implementations (or polyfills) of web platform interfaces defined in Web IDL. Its main consumer is the [jsdom](https://github.com/jsdom/jsdom) project. diff --git a/ts-ticket-office-service/node_modules/webidl-conversions/lib/index.js b/ts-ticket-office-service/node_modules/webidl-conversions/lib/index.js new file mode 100644 index 000000000..0229347c1 --- /dev/null +++ b/ts-ticket-office-service/node_modules/webidl-conversions/lib/index.js @@ -0,0 +1,450 @@ +"use strict"; + +function makeException(ErrorType, message, options) { + if (options.globals) { + ErrorType = options.globals[ErrorType.name]; + } + return new ErrorType(`${options.context ? options.context : "Value"} ${message}.`); +} + +function toNumber(value, options) { + if (typeof value === "bigint") { + throw makeException(TypeError, "is a BigInt which cannot be converted to a number", options); + } + if (!options.globals) { + return Number(value); + } + return options.globals.Number(value); +} + +// Round x to the nearest integer, choosing the even integer if it lies halfway between two. +function evenRound(x) { + // There are four cases for numbers with fractional part being .5: + // + // case | x | floor(x) | round(x) | expected | x <> 0 | x % 1 | x & 1 | example + // 1 | 2n + 0.5 | 2n | 2n + 1 | 2n | > | 0.5 | 0 | 0.5 -> 0 + // 2 | 2n + 1.5 | 2n + 1 | 2n + 2 | 2n + 2 | > | 0.5 | 1 | 1.5 -> 2 + // 3 | -2n - 0.5 | -2n - 1 | -2n | -2n | < | -0.5 | 0 | -0.5 -> 0 + // 4 | -2n - 1.5 | -2n - 2 | -2n - 1 | -2n - 2 | < | -0.5 | 1 | -1.5 -> -2 + // (where n is a non-negative integer) + // + // Branch here for cases 1 and 4 + if ((x > 0 && (x % 1) === +0.5 && (x & 1) === 0) || + (x < 0 && (x % 1) === -0.5 && (x & 1) === 1)) { + return censorNegativeZero(Math.floor(x)); + } + + return censorNegativeZero(Math.round(x)); +} + +function integerPart(n) { + return censorNegativeZero(Math.trunc(n)); +} + +function sign(x) { + return x < 0 ? -1 : 1; +} + +function modulo(x, y) { + // https://tc39.github.io/ecma262/#eqn-modulo + // Note that http://stackoverflow.com/a/4467559/3191 does NOT work for large modulos + const signMightNotMatch = x % y; + if (sign(y) !== sign(signMightNotMatch)) { + return signMightNotMatch + y; + } + return signMightNotMatch; +} + +function censorNegativeZero(x) { + return x === 0 ? 0 : x; +} + +function createIntegerConversion(bitLength, { unsigned }) { + let lowerBound, upperBound; + if (unsigned) { + lowerBound = 0; + upperBound = 2 ** bitLength - 1; + } else { + lowerBound = -(2 ** (bitLength - 1)); + upperBound = 2 ** (bitLength - 1) - 1; + } + + const twoToTheBitLength = 2 ** bitLength; + const twoToOneLessThanTheBitLength = 2 ** (bitLength - 1); + + return (value, options = {}) => { + let x = toNumber(value, options); + x = censorNegativeZero(x); + + if (options.enforceRange) { + if (!Number.isFinite(x)) { + throw makeException(TypeError, "is not a finite number", options); + } + + x = integerPart(x); + + if (x < lowerBound || x > upperBound) { + throw makeException( + TypeError, + `is outside the accepted range of ${lowerBound} to ${upperBound}, inclusive`, + options + ); + } + + return x; + } + + if (!Number.isNaN(x) && options.clamp) { + x = Math.min(Math.max(x, lowerBound), upperBound); + x = evenRound(x); + return x; + } + + if (!Number.isFinite(x) || x === 0) { + return 0; + } + x = integerPart(x); + + // Math.pow(2, 64) is not accurately representable in JavaScript, so try to avoid these per-spec operations if + // possible. Hopefully it's an optimization for the non-64-bitLength cases too. + if (x >= lowerBound && x <= upperBound) { + return x; + } + + // These will not work great for bitLength of 64, but oh well. See the README for more details. + x = modulo(x, twoToTheBitLength); + if (!unsigned && x >= twoToOneLessThanTheBitLength) { + return x - twoToTheBitLength; + } + return x; + }; +} + +function createLongLongConversion(bitLength, { unsigned }) { + const upperBound = Number.MAX_SAFE_INTEGER; + const lowerBound = unsigned ? 0 : Number.MIN_SAFE_INTEGER; + const asBigIntN = unsigned ? BigInt.asUintN : BigInt.asIntN; + + return (value, options = {}) => { + let x = toNumber(value, options); + x = censorNegativeZero(x); + + if (options.enforceRange) { + if (!Number.isFinite(x)) { + throw makeException(TypeError, "is not a finite number", options); + } + + x = integerPart(x); + + if (x < lowerBound || x > upperBound) { + throw makeException( + TypeError, + `is outside the accepted range of ${lowerBound} to ${upperBound}, inclusive`, + options + ); + } + + return x; + } + + if (!Number.isNaN(x) && options.clamp) { + x = Math.min(Math.max(x, lowerBound), upperBound); + x = evenRound(x); + return x; + } + + if (!Number.isFinite(x) || x === 0) { + return 0; + } + + let xBigInt = BigInt(integerPart(x)); + xBigInt = asBigIntN(bitLength, xBigInt); + return Number(xBigInt); + }; +} + +exports.any = value => { + return value; +}; + +exports.undefined = () => { + return undefined; +}; + +exports.boolean = value => { + return Boolean(value); +}; + +exports.byte = createIntegerConversion(8, { unsigned: false }); +exports.octet = createIntegerConversion(8, { unsigned: true }); + +exports.short = createIntegerConversion(16, { unsigned: false }); +exports["unsigned short"] = createIntegerConversion(16, { unsigned: true }); + +exports.long = createIntegerConversion(32, { unsigned: false }); +exports["unsigned long"] = createIntegerConversion(32, { unsigned: true }); + +exports["long long"] = createLongLongConversion(64, { unsigned: false }); +exports["unsigned long long"] = createLongLongConversion(64, { unsigned: true }); + +exports.double = (value, options = {}) => { + const x = toNumber(value, options); + + if (!Number.isFinite(x)) { + throw makeException(TypeError, "is not a finite floating-point value", options); + } + + return x; +}; + +exports["unrestricted double"] = (value, options = {}) => { + const x = toNumber(value, options); + + return x; +}; + +exports.float = (value, options = {}) => { + const x = toNumber(value, options); + + if (!Number.isFinite(x)) { + throw makeException(TypeError, "is not a finite floating-point value", options); + } + + if (Object.is(x, -0)) { + return x; + } + + const y = Math.fround(x); + + if (!Number.isFinite(y)) { + throw makeException(TypeError, "is outside the range of a single-precision floating-point value", options); + } + + return y; +}; + +exports["unrestricted float"] = (value, options = {}) => { + const x = toNumber(value, options); + + if (isNaN(x)) { + return x; + } + + if (Object.is(x, -0)) { + return x; + } + + return Math.fround(x); +}; + +exports.DOMString = (value, options = {}) => { + if (options.treatNullAsEmptyString && value === null) { + return ""; + } + + if (typeof value === "symbol") { + throw makeException(TypeError, "is a symbol, which cannot be converted to a string", options); + } + + const StringCtor = options.globals ? options.globals.String : String; + return StringCtor(value); +}; + +exports.ByteString = (value, options = {}) => { + const x = exports.DOMString(value, options); + let c; + for (let i = 0; (c = x.codePointAt(i)) !== undefined; ++i) { + if (c > 255) { + throw makeException(TypeError, "is not a valid ByteString", options); + } + } + + return x; +}; + +exports.USVString = (value, options = {}) => { + const S = exports.DOMString(value, options); + const n = S.length; + const U = []; + for (let i = 0; i < n; ++i) { + const c = S.charCodeAt(i); + if (c < 0xD800 || c > 0xDFFF) { + U.push(String.fromCodePoint(c)); + } else if (0xDC00 <= c && c <= 0xDFFF) { + U.push(String.fromCodePoint(0xFFFD)); + } else if (i === n - 1) { + U.push(String.fromCodePoint(0xFFFD)); + } else { + const d = S.charCodeAt(i + 1); + if (0xDC00 <= d && d <= 0xDFFF) { + const a = c & 0x3FF; + const b = d & 0x3FF; + U.push(String.fromCodePoint((2 << 15) + ((2 << 9) * a) + b)); + ++i; + } else { + U.push(String.fromCodePoint(0xFFFD)); + } + } + } + + return U.join(""); +}; + +exports.object = (value, options = {}) => { + if (value === null || (typeof value !== "object" && typeof value !== "function")) { + throw makeException(TypeError, "is not an object", options); + } + + return value; +}; + +const abByteLengthGetter = + Object.getOwnPropertyDescriptor(ArrayBuffer.prototype, "byteLength").get; +const sabByteLengthGetter = + typeof SharedArrayBuffer === "function" ? + Object.getOwnPropertyDescriptor(SharedArrayBuffer.prototype, "byteLength").get : + null; + +function isNonSharedArrayBuffer(value) { + try { + // This will throw on SharedArrayBuffers, but not detached ArrayBuffers. + // (The spec says it should throw, but the spec conflicts with implementations: https://github.com/tc39/ecma262/issues/678) + abByteLengthGetter.call(value); + + return true; + } catch { + return false; + } +} + +function isSharedArrayBuffer(value) { + try { + sabByteLengthGetter.call(value); + return true; + } catch { + return false; + } +} + +function isArrayBufferDetached(value) { + try { + // eslint-disable-next-line no-new + new Uint8Array(value); + return false; + } catch { + return true; + } +} + +exports.ArrayBuffer = (value, options = {}) => { + if (!isNonSharedArrayBuffer(value)) { + if (options.allowShared && !isSharedArrayBuffer(value)) { + throw makeException(TypeError, "is not an ArrayBuffer or SharedArrayBuffer", options); + } + throw makeException(TypeError, "is not an ArrayBuffer", options); + } + if (isArrayBufferDetached(value)) { + throw makeException(TypeError, "is a detached ArrayBuffer", options); + } + + return value; +}; + +const dvByteLengthGetter = + Object.getOwnPropertyDescriptor(DataView.prototype, "byteLength").get; +exports.DataView = (value, options = {}) => { + try { + dvByteLengthGetter.call(value); + } catch (e) { + throw makeException(TypeError, "is not a DataView", options); + } + + if (!options.allowShared && isSharedArrayBuffer(value.buffer)) { + throw makeException(TypeError, "is backed by a SharedArrayBuffer, which is not allowed", options); + } + if (isArrayBufferDetached(value.buffer)) { + throw makeException(TypeError, "is backed by a detached ArrayBuffer", options); + } + + return value; +}; + +// Returns the unforgeable `TypedArray` constructor name or `undefined`, +// if the `this` value isn't a valid `TypedArray` object. +// +// https://tc39.es/ecma262/#sec-get-%typedarray%.prototype-@@tostringtag +const typedArrayNameGetter = Object.getOwnPropertyDescriptor( + Object.getPrototypeOf(Uint8Array).prototype, + Symbol.toStringTag +).get; +[ + Int8Array, + Int16Array, + Int32Array, + Uint8Array, + Uint16Array, + Uint32Array, + Uint8ClampedArray, + Float32Array, + Float64Array +].forEach(func => { + const { name } = func; + const article = /^[AEIOU]/u.test(name) ? "an" : "a"; + exports[name] = (value, options = {}) => { + if (!ArrayBuffer.isView(value) || typedArrayNameGetter.call(value) !== name) { + throw makeException(TypeError, `is not ${article} ${name} object`, options); + } + if (!options.allowShared && isSharedArrayBuffer(value.buffer)) { + throw makeException(TypeError, "is a view on a SharedArrayBuffer, which is not allowed", options); + } + if (isArrayBufferDetached(value.buffer)) { + throw makeException(TypeError, "is a view on a detached ArrayBuffer", options); + } + + return value; + }; +}); + +// Common definitions + +exports.ArrayBufferView = (value, options = {}) => { + if (!ArrayBuffer.isView(value)) { + throw makeException(TypeError, "is not a view on an ArrayBuffer or SharedArrayBuffer", options); + } + + if (!options.allowShared && isSharedArrayBuffer(value.buffer)) { + throw makeException(TypeError, "is a view on a SharedArrayBuffer, which is not allowed", options); + } + + if (isArrayBufferDetached(value.buffer)) { + throw makeException(TypeError, "is a view on a detached ArrayBuffer", options); + } + return value; +}; + +exports.BufferSource = (value, options = {}) => { + if (ArrayBuffer.isView(value)) { + if (!options.allowShared && isSharedArrayBuffer(value.buffer)) { + throw makeException(TypeError, "is a view on a SharedArrayBuffer, which is not allowed", options); + } + + if (isArrayBufferDetached(value.buffer)) { + throw makeException(TypeError, "is a view on a detached ArrayBuffer", options); + } + return value; + } + + if (!options.allowShared && !isNonSharedArrayBuffer(value)) { + throw makeException(TypeError, "is not an ArrayBuffer or a view on one", options); + } + if (options.allowShared && !isSharedArrayBuffer(value) && !isNonSharedArrayBuffer(value)) { + throw makeException(TypeError, "is not an ArrayBuffer, SharedArrayBuffer, or a view on one", options); + } + if (isArrayBufferDetached(value)) { + throw makeException(TypeError, "is a detached ArrayBuffer", options); + } + + return value; +}; + +exports.DOMTimeStamp = exports["unsigned long long"]; diff --git a/ts-ticket-office-service/node_modules/webidl-conversions/package.json b/ts-ticket-office-service/node_modules/webidl-conversions/package.json new file mode 100644 index 000000000..20747bb42 --- /dev/null +++ b/ts-ticket-office-service/node_modules/webidl-conversions/package.json @@ -0,0 +1,35 @@ +{ + "name": "webidl-conversions", + "version": "7.0.0", + "description": "Implements the WebIDL algorithms for converting to and from JavaScript values", + "main": "lib/index.js", + "scripts": { + "lint": "eslint .", + "test": "mocha test/*.js", + "test-no-sab": "mocha --parallel --jobs 2 --require test/helpers/delete-sab.js test/*.js", + "coverage": "nyc mocha test/*.js" + }, + "_scripts_comments": { + "test-no-sab": "Node.js internals are broken by deleting SharedArrayBuffer if you run tests on the main thread. Using Mocha's parallel mode avoids this." + }, + "repository": "jsdom/webidl-conversions", + "keywords": [ + "webidl", + "web", + "types" + ], + "files": [ + "lib/" + ], + "author": "Domenic Denicola (https://domenic.me/)", + "license": "BSD-2-Clause", + "devDependencies": { + "@domenic/eslint-config": "^1.3.0", + "eslint": "^7.32.0", + "mocha": "^9.1.1", + "nyc": "^15.1.0" + }, + "engines": { + "node": ">=12" + } +} diff --git a/ts-ticket-office-service/node_modules/whatwg-url/LICENSE.txt b/ts-ticket-office-service/node_modules/whatwg-url/LICENSE.txt new file mode 100644 index 000000000..8e8c25c3a --- /dev/null +++ b/ts-ticket-office-service/node_modules/whatwg-url/LICENSE.txt @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) Sebastian Mayr + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. diff --git a/ts-ticket-office-service/node_modules/whatwg-url/README.md b/ts-ticket-office-service/node_modules/whatwg-url/README.md new file mode 100644 index 000000000..4d089006f --- /dev/null +++ b/ts-ticket-office-service/node_modules/whatwg-url/README.md @@ -0,0 +1,106 @@ +# whatwg-url + +whatwg-url is a full implementation of the WHATWG [URL Standard](https://url.spec.whatwg.org/). It can be used standalone, but it also exposes a lot of the internal algorithms that are useful for integrating a URL parser into a project like [jsdom](https://github.com/jsdom/jsdom). + +## Specification conformance + +whatwg-url is currently up to date with the URL spec up to commit [43c2713](https://github.com/whatwg/url/commit/43c27137a0bc82c4b800fe74be893255fbeb35f4). + +For `file:` URLs, whose [origin is left unspecified](https://url.spec.whatwg.org/#concept-url-origin), whatwg-url chooses to use a new opaque origin (which serializes to `"null"`). + +whatwg-url does not yet implement any encoding handling beyond UTF-8. That is, the _encoding override_ parameter does not exist in our API. + +## API + +### The `URL` and `URLSearchParams` classes + +The main API is provided by the [`URL`](https://url.spec.whatwg.org/#url-class) and [`URLSearchParams`](https://url.spec.whatwg.org/#interface-urlsearchparams) exports, which follows the spec's behavior in all ways (including e.g. `USVString` conversion). Most consumers of this library will want to use these. + +### Low-level URL Standard API + +The following methods are exported for use by places like jsdom that need to implement things like [`HTMLHyperlinkElementUtils`](https://html.spec.whatwg.org/#htmlhyperlinkelementutils). They mostly operate on or return an "internal URL" or ["URL record"](https://url.spec.whatwg.org/#concept-url) type. + +- [URL parser](https://url.spec.whatwg.org/#concept-url-parser): `parseURL(input, { baseURL })` +- [Basic URL parser](https://url.spec.whatwg.org/#concept-basic-url-parser): `basicURLParse(input, { baseURL, url, stateOverride })` +- [URL serializer](https://url.spec.whatwg.org/#concept-url-serializer): `serializeURL(urlRecord, excludeFragment)` +- [Host serializer](https://url.spec.whatwg.org/#concept-host-serializer): `serializeHost(hostFromURLRecord)` +- [URL path serializer](https://url.spec.whatwg.org/#url-path-serializer): `serializePath(urlRecord)` +- [Serialize an integer](https://url.spec.whatwg.org/#serialize-an-integer): `serializeInteger(number)` +- [Origin](https://url.spec.whatwg.org/#concept-url-origin) [serializer](https://html.spec.whatwg.org/multipage/origin.html#ascii-serialisation-of-an-origin): `serializeURLOrigin(urlRecord)` +- [Set the username](https://url.spec.whatwg.org/#set-the-username): `setTheUsername(urlRecord, usernameString)` +- [Set the password](https://url.spec.whatwg.org/#set-the-password): `setThePassword(urlRecord, passwordString)` +- [Has an opaque path](https://url.spec.whatwg.org/#url-opaque-path): `hasAnOpaquePath(urlRecord)` +- [Cannot have a username/password/port](https://url.spec.whatwg.org/#cannot-have-a-username-password-port): `cannotHaveAUsernamePasswordPort(urlRecord)` +- [Percent decode bytes](https://url.spec.whatwg.org/#percent-decode): `percentDecodeBytes(uint8Array)` +- [Percent decode a string](https://url.spec.whatwg.org/#percent-decode-string): `percentDecodeString(string)` + +The `stateOverride` parameter is one of the following strings: + +- [`"scheme start"`](https://url.spec.whatwg.org/#scheme-start-state) +- [`"scheme"`](https://url.spec.whatwg.org/#scheme-state) +- [`"no scheme"`](https://url.spec.whatwg.org/#no-scheme-state) +- [`"special relative or authority"`](https://url.spec.whatwg.org/#special-relative-or-authority-state) +- [`"path or authority"`](https://url.spec.whatwg.org/#path-or-authority-state) +- [`"relative"`](https://url.spec.whatwg.org/#relative-state) +- [`"relative slash"`](https://url.spec.whatwg.org/#relative-slash-state) +- [`"special authority slashes"`](https://url.spec.whatwg.org/#special-authority-slashes-state) +- [`"special authority ignore slashes"`](https://url.spec.whatwg.org/#special-authority-ignore-slashes-state) +- [`"authority"`](https://url.spec.whatwg.org/#authority-state) +- [`"host"`](https://url.spec.whatwg.org/#host-state) +- [`"hostname"`](https://url.spec.whatwg.org/#hostname-state) +- [`"port"`](https://url.spec.whatwg.org/#port-state) +- [`"file"`](https://url.spec.whatwg.org/#file-state) +- [`"file slash"`](https://url.spec.whatwg.org/#file-slash-state) +- [`"file host"`](https://url.spec.whatwg.org/#file-host-state) +- [`"path start"`](https://url.spec.whatwg.org/#path-start-state) +- [`"path"`](https://url.spec.whatwg.org/#path-state) +- [`"opaque path"`](https://url.spec.whatwg.org/#cannot-be-a-base-url-path-state) +- [`"query"`](https://url.spec.whatwg.org/#query-state) +- [`"fragment"`](https://url.spec.whatwg.org/#fragment-state) + +The URL record type has the following API: + +- [`scheme`](https://url.spec.whatwg.org/#concept-url-scheme) +- [`username`](https://url.spec.whatwg.org/#concept-url-username) +- [`password`](https://url.spec.whatwg.org/#concept-url-password) +- [`host`](https://url.spec.whatwg.org/#concept-url-host) +- [`port`](https://url.spec.whatwg.org/#concept-url-port) +- [`path`](https://url.spec.whatwg.org/#concept-url-path) (as an array of strings, or a string) +- [`query`](https://url.spec.whatwg.org/#concept-url-query) +- [`fragment`](https://url.spec.whatwg.org/#concept-url-fragment) + +These properties should be treated with care, as in general changing them will cause the URL record to be in an inconsistent state until the appropriate invocation of `basicURLParse` is used to fix it up. You can see examples of this in the URL Standard, where there are many step sequences like "4. Set context object’s url’s fragment to the empty string. 5. Basic URL parse _input_ with context object’s url as _url_ and fragment state as _state override_." In between those two steps, a URL record is in an unusable state. + +The return value of "failure" in the spec is represented by `null`. That is, functions like `parseURL` and `basicURLParse` can return _either_ a URL record _or_ `null`. + +### `whatwg-url/webidl2js-wrapper` module + +This module exports the `URL` and `URLSearchParams` [interface wrappers API](https://github.com/jsdom/webidl2js#for-interfaces) generated by [webidl2js](https://github.com/jsdom/webidl2js). + +## Development instructions + +First, install [Node.js](https://nodejs.org/). Then, fetch the dependencies of whatwg-url, by running from this directory: + + npm install + +To run tests: + + npm test + +To generate a coverage report: + + npm run coverage + +To build and run the live viewer: + + npm run prepare + npm run build-live-viewer + +Serve the contents of the `live-viewer` directory using any web server. + +## Supporting whatwg-url + +The jsdom project (including whatwg-url) is a community-driven project maintained by a team of [volunteers](https://github.com/orgs/jsdom/people). You could support us by: + +- [Getting professional support for whatwg-url](https://tidelift.com/subscription/pkg/npm-whatwg-url?utm_source=npm-whatwg-url&utm_medium=referral&utm_campaign=readme) as part of a Tidelift subscription. Tidelift helps making open source sustainable for us while giving teams assurances for maintenance, licensing, and security. +- Contributing directly to the project. diff --git a/ts-ticket-office-service/node_modules/whatwg-url/index.js b/ts-ticket-office-service/node_modules/whatwg-url/index.js new file mode 100644 index 000000000..c470e48e4 --- /dev/null +++ b/ts-ticket-office-service/node_modules/whatwg-url/index.js @@ -0,0 +1,27 @@ +"use strict"; + +const { URL, URLSearchParams } = require("./webidl2js-wrapper"); +const urlStateMachine = require("./lib/url-state-machine"); +const percentEncoding = require("./lib/percent-encoding"); + +const sharedGlobalObject = { Array, Object, Promise, String, TypeError }; +URL.install(sharedGlobalObject, ["Window"]); +URLSearchParams.install(sharedGlobalObject, ["Window"]); + +exports.URL = sharedGlobalObject.URL; +exports.URLSearchParams = sharedGlobalObject.URLSearchParams; + +exports.parseURL = urlStateMachine.parseURL; +exports.basicURLParse = urlStateMachine.basicURLParse; +exports.serializeURL = urlStateMachine.serializeURL; +exports.serializePath = urlStateMachine.serializePath; +exports.serializeHost = urlStateMachine.serializeHost; +exports.serializeInteger = urlStateMachine.serializeInteger; +exports.serializeURLOrigin = urlStateMachine.serializeURLOrigin; +exports.setTheUsername = urlStateMachine.setTheUsername; +exports.setThePassword = urlStateMachine.setThePassword; +exports.cannotHaveAUsernamePasswordPort = urlStateMachine.cannotHaveAUsernamePasswordPort; +exports.hasAnOpaquePath = urlStateMachine.hasAnOpaquePath; + +exports.percentDecodeString = percentEncoding.percentDecodeString; +exports.percentDecodeBytes = percentEncoding.percentDecodeBytes; diff --git a/ts-ticket-office-service/node_modules/whatwg-url/lib/Function.js b/ts-ticket-office-service/node_modules/whatwg-url/lib/Function.js new file mode 100644 index 000000000..ea8712fd7 --- /dev/null +++ b/ts-ticket-office-service/node_modules/whatwg-url/lib/Function.js @@ -0,0 +1,42 @@ +"use strict"; + +const conversions = require("webidl-conversions"); +const utils = require("./utils.js"); + +exports.convert = (globalObject, value, { context = "The provided value" } = {}) => { + if (typeof value !== "function") { + throw new globalObject.TypeError(context + " is not a function"); + } + + function invokeTheCallbackFunction(...args) { + const thisArg = utils.tryWrapperForImpl(this); + let callResult; + + for (let i = 0; i < args.length; i++) { + args[i] = utils.tryWrapperForImpl(args[i]); + } + + callResult = Reflect.apply(value, thisArg, args); + + callResult = conversions["any"](callResult, { context: context, globals: globalObject }); + + return callResult; + } + + invokeTheCallbackFunction.construct = (...args) => { + for (let i = 0; i < args.length; i++) { + args[i] = utils.tryWrapperForImpl(args[i]); + } + + let callResult = Reflect.construct(value, args); + + callResult = conversions["any"](callResult, { context: context, globals: globalObject }); + + return callResult; + }; + + invokeTheCallbackFunction[utils.wrapperSymbol] = value; + invokeTheCallbackFunction.objectReference = value; + + return invokeTheCallbackFunction; +}; diff --git a/ts-ticket-office-service/node_modules/whatwg-url/lib/URL-impl.js b/ts-ticket-office-service/node_modules/whatwg-url/lib/URL-impl.js new file mode 100644 index 000000000..db3a0aea0 --- /dev/null +++ b/ts-ticket-office-service/node_modules/whatwg-url/lib/URL-impl.js @@ -0,0 +1,209 @@ +"use strict"; +const usm = require("./url-state-machine"); +const urlencoded = require("./urlencoded"); +const URLSearchParams = require("./URLSearchParams"); + +exports.implementation = class URLImpl { + constructor(globalObject, constructorArgs) { + const url = constructorArgs[0]; + const base = constructorArgs[1]; + + let parsedBase = null; + if (base !== undefined) { + parsedBase = usm.basicURLParse(base); + if (parsedBase === null) { + throw new TypeError(`Invalid base URL: ${base}`); + } + } + + const parsedURL = usm.basicURLParse(url, { baseURL: parsedBase }); + if (parsedURL === null) { + throw new TypeError(`Invalid URL: ${url}`); + } + + const query = parsedURL.query !== null ? parsedURL.query : ""; + + this._url = parsedURL; + + // We cannot invoke the "new URLSearchParams object" algorithm without going through the constructor, which strips + // question mark by default. Therefore the doNotStripQMark hack is used. + this._query = URLSearchParams.createImpl(globalObject, [query], { doNotStripQMark: true }); + this._query._url = this; + } + + get href() { + return usm.serializeURL(this._url); + } + + set href(v) { + const parsedURL = usm.basicURLParse(v); + if (parsedURL === null) { + throw new TypeError(`Invalid URL: ${v}`); + } + + this._url = parsedURL; + + this._query._list.splice(0); + const { query } = parsedURL; + if (query !== null) { + this._query._list = urlencoded.parseUrlencodedString(query); + } + } + + get origin() { + return usm.serializeURLOrigin(this._url); + } + + get protocol() { + return `${this._url.scheme}:`; + } + + set protocol(v) { + usm.basicURLParse(`${v}:`, { url: this._url, stateOverride: "scheme start" }); + } + + get username() { + return this._url.username; + } + + set username(v) { + if (usm.cannotHaveAUsernamePasswordPort(this._url)) { + return; + } + + usm.setTheUsername(this._url, v); + } + + get password() { + return this._url.password; + } + + set password(v) { + if (usm.cannotHaveAUsernamePasswordPort(this._url)) { + return; + } + + usm.setThePassword(this._url, v); + } + + get host() { + const url = this._url; + + if (url.host === null) { + return ""; + } + + if (url.port === null) { + return usm.serializeHost(url.host); + } + + return `${usm.serializeHost(url.host)}:${usm.serializeInteger(url.port)}`; + } + + set host(v) { + if (usm.hasAnOpaquePath(this._url)) { + return; + } + + usm.basicURLParse(v, { url: this._url, stateOverride: "host" }); + } + + get hostname() { + if (this._url.host === null) { + return ""; + } + + return usm.serializeHost(this._url.host); + } + + set hostname(v) { + if (usm.hasAnOpaquePath(this._url)) { + return; + } + + usm.basicURLParse(v, { url: this._url, stateOverride: "hostname" }); + } + + get port() { + if (this._url.port === null) { + return ""; + } + + return usm.serializeInteger(this._url.port); + } + + set port(v) { + if (usm.cannotHaveAUsernamePasswordPort(this._url)) { + return; + } + + if (v === "") { + this._url.port = null; + } else { + usm.basicURLParse(v, { url: this._url, stateOverride: "port" }); + } + } + + get pathname() { + return usm.serializePath(this._url); + } + + set pathname(v) { + if (usm.hasAnOpaquePath(this._url)) { + return; + } + + this._url.path = []; + usm.basicURLParse(v, { url: this._url, stateOverride: "path start" }); + } + + get search() { + if (this._url.query === null || this._url.query === "") { + return ""; + } + + return `?${this._url.query}`; + } + + set search(v) { + const url = this._url; + + if (v === "") { + url.query = null; + this._query._list = []; + return; + } + + const input = v[0] === "?" ? v.substring(1) : v; + url.query = ""; + usm.basicURLParse(input, { url, stateOverride: "query" }); + this._query._list = urlencoded.parseUrlencodedString(input); + } + + get searchParams() { + return this._query; + } + + get hash() { + if (this._url.fragment === null || this._url.fragment === "") { + return ""; + } + + return `#${this._url.fragment}`; + } + + set hash(v) { + if (v === "") { + this._url.fragment = null; + return; + } + + const input = v[0] === "#" ? v.substring(1) : v; + this._url.fragment = ""; + usm.basicURLParse(input, { url: this._url, stateOverride: "fragment" }); + } + + toJSON() { + return this.href; + } +}; diff --git a/ts-ticket-office-service/node_modules/whatwg-url/lib/URL.js b/ts-ticket-office-service/node_modules/whatwg-url/lib/URL.js new file mode 100644 index 000000000..d62ac3e76 --- /dev/null +++ b/ts-ticket-office-service/node_modules/whatwg-url/lib/URL.js @@ -0,0 +1,442 @@ +"use strict"; + +const conversions = require("webidl-conversions"); +const utils = require("./utils.js"); + +const implSymbol = utils.implSymbol; +const ctorRegistrySymbol = utils.ctorRegistrySymbol; + +const interfaceName = "URL"; + +exports.is = value => { + return utils.isObject(value) && utils.hasOwn(value, implSymbol) && value[implSymbol] instanceof Impl.implementation; +}; +exports.isImpl = value => { + return utils.isObject(value) && value instanceof Impl.implementation; +}; +exports.convert = (globalObject, value, { context = "The provided value" } = {}) => { + if (exports.is(value)) { + return utils.implForWrapper(value); + } + throw new globalObject.TypeError(`${context} is not of type 'URL'.`); +}; + +function makeWrapper(globalObject, newTarget) { + let proto; + if (newTarget !== undefined) { + proto = newTarget.prototype; + } + + if (!utils.isObject(proto)) { + proto = globalObject[ctorRegistrySymbol]["URL"].prototype; + } + + return Object.create(proto); +} + +exports.create = (globalObject, constructorArgs, privateData) => { + const wrapper = makeWrapper(globalObject); + return exports.setup(wrapper, globalObject, constructorArgs, privateData); +}; + +exports.createImpl = (globalObject, constructorArgs, privateData) => { + const wrapper = exports.create(globalObject, constructorArgs, privateData); + return utils.implForWrapper(wrapper); +}; + +exports._internalSetup = (wrapper, globalObject) => {}; + +exports.setup = (wrapper, globalObject, constructorArgs = [], privateData = {}) => { + privateData.wrapper = wrapper; + + exports._internalSetup(wrapper, globalObject); + Object.defineProperty(wrapper, implSymbol, { + value: new Impl.implementation(globalObject, constructorArgs, privateData), + configurable: true + }); + + wrapper[implSymbol][utils.wrapperSymbol] = wrapper; + if (Impl.init) { + Impl.init(wrapper[implSymbol]); + } + return wrapper; +}; + +exports.new = (globalObject, newTarget) => { + const wrapper = makeWrapper(globalObject, newTarget); + + exports._internalSetup(wrapper, globalObject); + Object.defineProperty(wrapper, implSymbol, { + value: Object.create(Impl.implementation.prototype), + configurable: true + }); + + wrapper[implSymbol][utils.wrapperSymbol] = wrapper; + if (Impl.init) { + Impl.init(wrapper[implSymbol]); + } + return wrapper[implSymbol]; +}; + +const exposed = new Set(["Window", "Worker"]); + +exports.install = (globalObject, globalNames) => { + if (!globalNames.some(globalName => exposed.has(globalName))) { + return; + } + + const ctorRegistry = utils.initCtorRegistry(globalObject); + class URL { + constructor(url) { + if (arguments.length < 1) { + throw new globalObject.TypeError( + `Failed to construct 'URL': 1 argument required, but only ${arguments.length} present.` + ); + } + const args = []; + { + let curArg = arguments[0]; + curArg = conversions["USVString"](curArg, { + context: "Failed to construct 'URL': parameter 1", + globals: globalObject + }); + args.push(curArg); + } + { + let curArg = arguments[1]; + if (curArg !== undefined) { + curArg = conversions["USVString"](curArg, { + context: "Failed to construct 'URL': parameter 2", + globals: globalObject + }); + } + args.push(curArg); + } + return exports.setup(Object.create(new.target.prototype), globalObject, args); + } + + toJSON() { + const esValue = this !== null && this !== undefined ? this : globalObject; + if (!exports.is(esValue)) { + throw new globalObject.TypeError("'toJSON' called on an object that is not a valid instance of URL."); + } + + return esValue[implSymbol].toJSON(); + } + + get href() { + const esValue = this !== null && this !== undefined ? this : globalObject; + + if (!exports.is(esValue)) { + throw new globalObject.TypeError("'get href' called on an object that is not a valid instance of URL."); + } + + return esValue[implSymbol]["href"]; + } + + set href(V) { + const esValue = this !== null && this !== undefined ? this : globalObject; + + if (!exports.is(esValue)) { + throw new globalObject.TypeError("'set href' called on an object that is not a valid instance of URL."); + } + + V = conversions["USVString"](V, { + context: "Failed to set the 'href' property on 'URL': The provided value", + globals: globalObject + }); + + esValue[implSymbol]["href"] = V; + } + + toString() { + const esValue = this; + if (!exports.is(esValue)) { + throw new globalObject.TypeError("'toString' called on an object that is not a valid instance of URL."); + } + + return esValue[implSymbol]["href"]; + } + + get origin() { + const esValue = this !== null && this !== undefined ? this : globalObject; + + if (!exports.is(esValue)) { + throw new globalObject.TypeError("'get origin' called on an object that is not a valid instance of URL."); + } + + return esValue[implSymbol]["origin"]; + } + + get protocol() { + const esValue = this !== null && this !== undefined ? this : globalObject; + + if (!exports.is(esValue)) { + throw new globalObject.TypeError("'get protocol' called on an object that is not a valid instance of URL."); + } + + return esValue[implSymbol]["protocol"]; + } + + set protocol(V) { + const esValue = this !== null && this !== undefined ? this : globalObject; + + if (!exports.is(esValue)) { + throw new globalObject.TypeError("'set protocol' called on an object that is not a valid instance of URL."); + } + + V = conversions["USVString"](V, { + context: "Failed to set the 'protocol' property on 'URL': The provided value", + globals: globalObject + }); + + esValue[implSymbol]["protocol"] = V; + } + + get username() { + const esValue = this !== null && this !== undefined ? this : globalObject; + + if (!exports.is(esValue)) { + throw new globalObject.TypeError("'get username' called on an object that is not a valid instance of URL."); + } + + return esValue[implSymbol]["username"]; + } + + set username(V) { + const esValue = this !== null && this !== undefined ? this : globalObject; + + if (!exports.is(esValue)) { + throw new globalObject.TypeError("'set username' called on an object that is not a valid instance of URL."); + } + + V = conversions["USVString"](V, { + context: "Failed to set the 'username' property on 'URL': The provided value", + globals: globalObject + }); + + esValue[implSymbol]["username"] = V; + } + + get password() { + const esValue = this !== null && this !== undefined ? this : globalObject; + + if (!exports.is(esValue)) { + throw new globalObject.TypeError("'get password' called on an object that is not a valid instance of URL."); + } + + return esValue[implSymbol]["password"]; + } + + set password(V) { + const esValue = this !== null && this !== undefined ? this : globalObject; + + if (!exports.is(esValue)) { + throw new globalObject.TypeError("'set password' called on an object that is not a valid instance of URL."); + } + + V = conversions["USVString"](V, { + context: "Failed to set the 'password' property on 'URL': The provided value", + globals: globalObject + }); + + esValue[implSymbol]["password"] = V; + } + + get host() { + const esValue = this !== null && this !== undefined ? this : globalObject; + + if (!exports.is(esValue)) { + throw new globalObject.TypeError("'get host' called on an object that is not a valid instance of URL."); + } + + return esValue[implSymbol]["host"]; + } + + set host(V) { + const esValue = this !== null && this !== undefined ? this : globalObject; + + if (!exports.is(esValue)) { + throw new globalObject.TypeError("'set host' called on an object that is not a valid instance of URL."); + } + + V = conversions["USVString"](V, { + context: "Failed to set the 'host' property on 'URL': The provided value", + globals: globalObject + }); + + esValue[implSymbol]["host"] = V; + } + + get hostname() { + const esValue = this !== null && this !== undefined ? this : globalObject; + + if (!exports.is(esValue)) { + throw new globalObject.TypeError("'get hostname' called on an object that is not a valid instance of URL."); + } + + return esValue[implSymbol]["hostname"]; + } + + set hostname(V) { + const esValue = this !== null && this !== undefined ? this : globalObject; + + if (!exports.is(esValue)) { + throw new globalObject.TypeError("'set hostname' called on an object that is not a valid instance of URL."); + } + + V = conversions["USVString"](V, { + context: "Failed to set the 'hostname' property on 'URL': The provided value", + globals: globalObject + }); + + esValue[implSymbol]["hostname"] = V; + } + + get port() { + const esValue = this !== null && this !== undefined ? this : globalObject; + + if (!exports.is(esValue)) { + throw new globalObject.TypeError("'get port' called on an object that is not a valid instance of URL."); + } + + return esValue[implSymbol]["port"]; + } + + set port(V) { + const esValue = this !== null && this !== undefined ? this : globalObject; + + if (!exports.is(esValue)) { + throw new globalObject.TypeError("'set port' called on an object that is not a valid instance of URL."); + } + + V = conversions["USVString"](V, { + context: "Failed to set the 'port' property on 'URL': The provided value", + globals: globalObject + }); + + esValue[implSymbol]["port"] = V; + } + + get pathname() { + const esValue = this !== null && this !== undefined ? this : globalObject; + + if (!exports.is(esValue)) { + throw new globalObject.TypeError("'get pathname' called on an object that is not a valid instance of URL."); + } + + return esValue[implSymbol]["pathname"]; + } + + set pathname(V) { + const esValue = this !== null && this !== undefined ? this : globalObject; + + if (!exports.is(esValue)) { + throw new globalObject.TypeError("'set pathname' called on an object that is not a valid instance of URL."); + } + + V = conversions["USVString"](V, { + context: "Failed to set the 'pathname' property on 'URL': The provided value", + globals: globalObject + }); + + esValue[implSymbol]["pathname"] = V; + } + + get search() { + const esValue = this !== null && this !== undefined ? this : globalObject; + + if (!exports.is(esValue)) { + throw new globalObject.TypeError("'get search' called on an object that is not a valid instance of URL."); + } + + return esValue[implSymbol]["search"]; + } + + set search(V) { + const esValue = this !== null && this !== undefined ? this : globalObject; + + if (!exports.is(esValue)) { + throw new globalObject.TypeError("'set search' called on an object that is not a valid instance of URL."); + } + + V = conversions["USVString"](V, { + context: "Failed to set the 'search' property on 'URL': The provided value", + globals: globalObject + }); + + esValue[implSymbol]["search"] = V; + } + + get searchParams() { + const esValue = this !== null && this !== undefined ? this : globalObject; + + if (!exports.is(esValue)) { + throw new globalObject.TypeError("'get searchParams' called on an object that is not a valid instance of URL."); + } + + return utils.getSameObject(this, "searchParams", () => { + return utils.tryWrapperForImpl(esValue[implSymbol]["searchParams"]); + }); + } + + get hash() { + const esValue = this !== null && this !== undefined ? this : globalObject; + + if (!exports.is(esValue)) { + throw new globalObject.TypeError("'get hash' called on an object that is not a valid instance of URL."); + } + + return esValue[implSymbol]["hash"]; + } + + set hash(V) { + const esValue = this !== null && this !== undefined ? this : globalObject; + + if (!exports.is(esValue)) { + throw new globalObject.TypeError("'set hash' called on an object that is not a valid instance of URL."); + } + + V = conversions["USVString"](V, { + context: "Failed to set the 'hash' property on 'URL': The provided value", + globals: globalObject + }); + + esValue[implSymbol]["hash"] = V; + } + } + Object.defineProperties(URL.prototype, { + toJSON: { enumerable: true }, + href: { enumerable: true }, + toString: { enumerable: true }, + origin: { enumerable: true }, + protocol: { enumerable: true }, + username: { enumerable: true }, + password: { enumerable: true }, + host: { enumerable: true }, + hostname: { enumerable: true }, + port: { enumerable: true }, + pathname: { enumerable: true }, + search: { enumerable: true }, + searchParams: { enumerable: true }, + hash: { enumerable: true }, + [Symbol.toStringTag]: { value: "URL", configurable: true } + }); + ctorRegistry[interfaceName] = URL; + + Object.defineProperty(globalObject, interfaceName, { + configurable: true, + writable: true, + value: URL + }); + + if (globalNames.includes("Window")) { + Object.defineProperty(globalObject, "webkitURL", { + configurable: true, + writable: true, + value: URL + }); + } +}; + +const Impl = require("./URL-impl.js"); diff --git a/ts-ticket-office-service/node_modules/whatwg-url/lib/URLSearchParams-impl.js b/ts-ticket-office-service/node_modules/whatwg-url/lib/URLSearchParams-impl.js new file mode 100644 index 000000000..ef8d604ed --- /dev/null +++ b/ts-ticket-office-service/node_modules/whatwg-url/lib/URLSearchParams-impl.js @@ -0,0 +1,130 @@ +"use strict"; +const urlencoded = require("./urlencoded"); + +exports.implementation = class URLSearchParamsImpl { + constructor(globalObject, constructorArgs, { doNotStripQMark = false }) { + let init = constructorArgs[0]; + this._list = []; + this._url = null; + + if (!doNotStripQMark && typeof init === "string" && init[0] === "?") { + init = init.slice(1); + } + + if (Array.isArray(init)) { + for (const pair of init) { + if (pair.length !== 2) { + throw new TypeError("Failed to construct 'URLSearchParams': parameter 1 sequence's element does not " + + "contain exactly two elements."); + } + this._list.push([pair[0], pair[1]]); + } + } else if (typeof init === "object" && Object.getPrototypeOf(init) === null) { + for (const name of Object.keys(init)) { + const value = init[name]; + this._list.push([name, value]); + } + } else { + this._list = urlencoded.parseUrlencodedString(init); + } + } + + _updateSteps() { + if (this._url !== null) { + let query = urlencoded.serializeUrlencoded(this._list); + if (query === "") { + query = null; + } + this._url._url.query = query; + } + } + + append(name, value) { + this._list.push([name, value]); + this._updateSteps(); + } + + delete(name) { + let i = 0; + while (i < this._list.length) { + if (this._list[i][0] === name) { + this._list.splice(i, 1); + } else { + i++; + } + } + this._updateSteps(); + } + + get(name) { + for (const tuple of this._list) { + if (tuple[0] === name) { + return tuple[1]; + } + } + return null; + } + + getAll(name) { + const output = []; + for (const tuple of this._list) { + if (tuple[0] === name) { + output.push(tuple[1]); + } + } + return output; + } + + has(name) { + for (const tuple of this._list) { + if (tuple[0] === name) { + return true; + } + } + return false; + } + + set(name, value) { + let found = false; + let i = 0; + while (i < this._list.length) { + if (this._list[i][0] === name) { + if (found) { + this._list.splice(i, 1); + } else { + found = true; + this._list[i][1] = value; + i++; + } + } else { + i++; + } + } + if (!found) { + this._list.push([name, value]); + } + this._updateSteps(); + } + + sort() { + this._list.sort((a, b) => { + if (a[0] < b[0]) { + return -1; + } + if (a[0] > b[0]) { + return 1; + } + return 0; + }); + + this._updateSteps(); + } + + [Symbol.iterator]() { + return this._list[Symbol.iterator](); + } + + toString() { + return urlencoded.serializeUrlencoded(this._list); + } +}; diff --git a/ts-ticket-office-service/node_modules/whatwg-url/lib/URLSearchParams.js b/ts-ticket-office-service/node_modules/whatwg-url/lib/URLSearchParams.js new file mode 100644 index 000000000..a7c24eff8 --- /dev/null +++ b/ts-ticket-office-service/node_modules/whatwg-url/lib/URLSearchParams.js @@ -0,0 +1,472 @@ +"use strict"; + +const conversions = require("webidl-conversions"); +const utils = require("./utils.js"); + +const Function = require("./Function.js"); +const newObjectInRealm = utils.newObjectInRealm; +const implSymbol = utils.implSymbol; +const ctorRegistrySymbol = utils.ctorRegistrySymbol; + +const interfaceName = "URLSearchParams"; + +exports.is = value => { + return utils.isObject(value) && utils.hasOwn(value, implSymbol) && value[implSymbol] instanceof Impl.implementation; +}; +exports.isImpl = value => { + return utils.isObject(value) && value instanceof Impl.implementation; +}; +exports.convert = (globalObject, value, { context = "The provided value" } = {}) => { + if (exports.is(value)) { + return utils.implForWrapper(value); + } + throw new globalObject.TypeError(`${context} is not of type 'URLSearchParams'.`); +}; + +exports.createDefaultIterator = (globalObject, target, kind) => { + const ctorRegistry = globalObject[ctorRegistrySymbol]; + const iteratorPrototype = ctorRegistry["URLSearchParams Iterator"]; + const iterator = Object.create(iteratorPrototype); + Object.defineProperty(iterator, utils.iterInternalSymbol, { + value: { target, kind, index: 0 }, + configurable: true + }); + return iterator; +}; + +function makeWrapper(globalObject, newTarget) { + let proto; + if (newTarget !== undefined) { + proto = newTarget.prototype; + } + + if (!utils.isObject(proto)) { + proto = globalObject[ctorRegistrySymbol]["URLSearchParams"].prototype; + } + + return Object.create(proto); +} + +exports.create = (globalObject, constructorArgs, privateData) => { + const wrapper = makeWrapper(globalObject); + return exports.setup(wrapper, globalObject, constructorArgs, privateData); +}; + +exports.createImpl = (globalObject, constructorArgs, privateData) => { + const wrapper = exports.create(globalObject, constructorArgs, privateData); + return utils.implForWrapper(wrapper); +}; + +exports._internalSetup = (wrapper, globalObject) => {}; + +exports.setup = (wrapper, globalObject, constructorArgs = [], privateData = {}) => { + privateData.wrapper = wrapper; + + exports._internalSetup(wrapper, globalObject); + Object.defineProperty(wrapper, implSymbol, { + value: new Impl.implementation(globalObject, constructorArgs, privateData), + configurable: true + }); + + wrapper[implSymbol][utils.wrapperSymbol] = wrapper; + if (Impl.init) { + Impl.init(wrapper[implSymbol]); + } + return wrapper; +}; + +exports.new = (globalObject, newTarget) => { + const wrapper = makeWrapper(globalObject, newTarget); + + exports._internalSetup(wrapper, globalObject); + Object.defineProperty(wrapper, implSymbol, { + value: Object.create(Impl.implementation.prototype), + configurable: true + }); + + wrapper[implSymbol][utils.wrapperSymbol] = wrapper; + if (Impl.init) { + Impl.init(wrapper[implSymbol]); + } + return wrapper[implSymbol]; +}; + +const exposed = new Set(["Window", "Worker"]); + +exports.install = (globalObject, globalNames) => { + if (!globalNames.some(globalName => exposed.has(globalName))) { + return; + } + + const ctorRegistry = utils.initCtorRegistry(globalObject); + class URLSearchParams { + constructor() { + const args = []; + { + let curArg = arguments[0]; + if (curArg !== undefined) { + if (utils.isObject(curArg)) { + if (curArg[Symbol.iterator] !== undefined) { + if (!utils.isObject(curArg)) { + throw new globalObject.TypeError( + "Failed to construct 'URLSearchParams': parameter 1" + " sequence" + " is not an iterable object." + ); + } else { + const V = []; + const tmp = curArg; + for (let nextItem of tmp) { + if (!utils.isObject(nextItem)) { + throw new globalObject.TypeError( + "Failed to construct 'URLSearchParams': parameter 1" + + " sequence" + + "'s element" + + " is not an iterable object." + ); + } else { + const V = []; + const tmp = nextItem; + for (let nextItem of tmp) { + nextItem = conversions["USVString"](nextItem, { + context: + "Failed to construct 'URLSearchParams': parameter 1" + + " sequence" + + "'s element" + + "'s element", + globals: globalObject + }); + + V.push(nextItem); + } + nextItem = V; + } + + V.push(nextItem); + } + curArg = V; + } + } else { + if (!utils.isObject(curArg)) { + throw new globalObject.TypeError( + "Failed to construct 'URLSearchParams': parameter 1" + " record" + " is not an object." + ); + } else { + const result = Object.create(null); + for (const key of Reflect.ownKeys(curArg)) { + const desc = Object.getOwnPropertyDescriptor(curArg, key); + if (desc && desc.enumerable) { + let typedKey = key; + + typedKey = conversions["USVString"](typedKey, { + context: "Failed to construct 'URLSearchParams': parameter 1" + " record" + "'s key", + globals: globalObject + }); + + let typedValue = curArg[key]; + + typedValue = conversions["USVString"](typedValue, { + context: "Failed to construct 'URLSearchParams': parameter 1" + " record" + "'s value", + globals: globalObject + }); + + result[typedKey] = typedValue; + } + } + curArg = result; + } + } + } else { + curArg = conversions["USVString"](curArg, { + context: "Failed to construct 'URLSearchParams': parameter 1", + globals: globalObject + }); + } + } else { + curArg = ""; + } + args.push(curArg); + } + return exports.setup(Object.create(new.target.prototype), globalObject, args); + } + + append(name, value) { + const esValue = this !== null && this !== undefined ? this : globalObject; + if (!exports.is(esValue)) { + throw new globalObject.TypeError( + "'append' called on an object that is not a valid instance of URLSearchParams." + ); + } + + if (arguments.length < 2) { + throw new globalObject.TypeError( + `Failed to execute 'append' on 'URLSearchParams': 2 arguments required, but only ${arguments.length} present.` + ); + } + const args = []; + { + let curArg = arguments[0]; + curArg = conversions["USVString"](curArg, { + context: "Failed to execute 'append' on 'URLSearchParams': parameter 1", + globals: globalObject + }); + args.push(curArg); + } + { + let curArg = arguments[1]; + curArg = conversions["USVString"](curArg, { + context: "Failed to execute 'append' on 'URLSearchParams': parameter 2", + globals: globalObject + }); + args.push(curArg); + } + return utils.tryWrapperForImpl(esValue[implSymbol].append(...args)); + } + + delete(name) { + const esValue = this !== null && this !== undefined ? this : globalObject; + if (!exports.is(esValue)) { + throw new globalObject.TypeError( + "'delete' called on an object that is not a valid instance of URLSearchParams." + ); + } + + if (arguments.length < 1) { + throw new globalObject.TypeError( + `Failed to execute 'delete' on 'URLSearchParams': 1 argument required, but only ${arguments.length} present.` + ); + } + const args = []; + { + let curArg = arguments[0]; + curArg = conversions["USVString"](curArg, { + context: "Failed to execute 'delete' on 'URLSearchParams': parameter 1", + globals: globalObject + }); + args.push(curArg); + } + return utils.tryWrapperForImpl(esValue[implSymbol].delete(...args)); + } + + get(name) { + const esValue = this !== null && this !== undefined ? this : globalObject; + if (!exports.is(esValue)) { + throw new globalObject.TypeError("'get' called on an object that is not a valid instance of URLSearchParams."); + } + + if (arguments.length < 1) { + throw new globalObject.TypeError( + `Failed to execute 'get' on 'URLSearchParams': 1 argument required, but only ${arguments.length} present.` + ); + } + const args = []; + { + let curArg = arguments[0]; + curArg = conversions["USVString"](curArg, { + context: "Failed to execute 'get' on 'URLSearchParams': parameter 1", + globals: globalObject + }); + args.push(curArg); + } + return esValue[implSymbol].get(...args); + } + + getAll(name) { + const esValue = this !== null && this !== undefined ? this : globalObject; + if (!exports.is(esValue)) { + throw new globalObject.TypeError( + "'getAll' called on an object that is not a valid instance of URLSearchParams." + ); + } + + if (arguments.length < 1) { + throw new globalObject.TypeError( + `Failed to execute 'getAll' on 'URLSearchParams': 1 argument required, but only ${arguments.length} present.` + ); + } + const args = []; + { + let curArg = arguments[0]; + curArg = conversions["USVString"](curArg, { + context: "Failed to execute 'getAll' on 'URLSearchParams': parameter 1", + globals: globalObject + }); + args.push(curArg); + } + return utils.tryWrapperForImpl(esValue[implSymbol].getAll(...args)); + } + + has(name) { + const esValue = this !== null && this !== undefined ? this : globalObject; + if (!exports.is(esValue)) { + throw new globalObject.TypeError("'has' called on an object that is not a valid instance of URLSearchParams."); + } + + if (arguments.length < 1) { + throw new globalObject.TypeError( + `Failed to execute 'has' on 'URLSearchParams': 1 argument required, but only ${arguments.length} present.` + ); + } + const args = []; + { + let curArg = arguments[0]; + curArg = conversions["USVString"](curArg, { + context: "Failed to execute 'has' on 'URLSearchParams': parameter 1", + globals: globalObject + }); + args.push(curArg); + } + return esValue[implSymbol].has(...args); + } + + set(name, value) { + const esValue = this !== null && this !== undefined ? this : globalObject; + if (!exports.is(esValue)) { + throw new globalObject.TypeError("'set' called on an object that is not a valid instance of URLSearchParams."); + } + + if (arguments.length < 2) { + throw new globalObject.TypeError( + `Failed to execute 'set' on 'URLSearchParams': 2 arguments required, but only ${arguments.length} present.` + ); + } + const args = []; + { + let curArg = arguments[0]; + curArg = conversions["USVString"](curArg, { + context: "Failed to execute 'set' on 'URLSearchParams': parameter 1", + globals: globalObject + }); + args.push(curArg); + } + { + let curArg = arguments[1]; + curArg = conversions["USVString"](curArg, { + context: "Failed to execute 'set' on 'URLSearchParams': parameter 2", + globals: globalObject + }); + args.push(curArg); + } + return utils.tryWrapperForImpl(esValue[implSymbol].set(...args)); + } + + sort() { + const esValue = this !== null && this !== undefined ? this : globalObject; + if (!exports.is(esValue)) { + throw new globalObject.TypeError("'sort' called on an object that is not a valid instance of URLSearchParams."); + } + + return utils.tryWrapperForImpl(esValue[implSymbol].sort()); + } + + toString() { + const esValue = this !== null && this !== undefined ? this : globalObject; + if (!exports.is(esValue)) { + throw new globalObject.TypeError( + "'toString' called on an object that is not a valid instance of URLSearchParams." + ); + } + + return esValue[implSymbol].toString(); + } + + keys() { + if (!exports.is(this)) { + throw new globalObject.TypeError("'keys' called on an object that is not a valid instance of URLSearchParams."); + } + return exports.createDefaultIterator(globalObject, this, "key"); + } + + values() { + if (!exports.is(this)) { + throw new globalObject.TypeError( + "'values' called on an object that is not a valid instance of URLSearchParams." + ); + } + return exports.createDefaultIterator(globalObject, this, "value"); + } + + entries() { + if (!exports.is(this)) { + throw new globalObject.TypeError( + "'entries' called on an object that is not a valid instance of URLSearchParams." + ); + } + return exports.createDefaultIterator(globalObject, this, "key+value"); + } + + forEach(callback) { + if (!exports.is(this)) { + throw new globalObject.TypeError( + "'forEach' called on an object that is not a valid instance of URLSearchParams." + ); + } + if (arguments.length < 1) { + throw new globalObject.TypeError( + "Failed to execute 'forEach' on 'iterable': 1 argument required, but only 0 present." + ); + } + callback = Function.convert(globalObject, callback, { + context: "Failed to execute 'forEach' on 'iterable': The callback provided as parameter 1" + }); + const thisArg = arguments[1]; + let pairs = Array.from(this[implSymbol]); + let i = 0; + while (i < pairs.length) { + const [key, value] = pairs[i].map(utils.tryWrapperForImpl); + callback.call(thisArg, value, key, this); + pairs = Array.from(this[implSymbol]); + i++; + } + } + } + Object.defineProperties(URLSearchParams.prototype, { + append: { enumerable: true }, + delete: { enumerable: true }, + get: { enumerable: true }, + getAll: { enumerable: true }, + has: { enumerable: true }, + set: { enumerable: true }, + sort: { enumerable: true }, + toString: { enumerable: true }, + keys: { enumerable: true }, + values: { enumerable: true }, + entries: { enumerable: true }, + forEach: { enumerable: true }, + [Symbol.toStringTag]: { value: "URLSearchParams", configurable: true }, + [Symbol.iterator]: { value: URLSearchParams.prototype.entries, configurable: true, writable: true } + }); + ctorRegistry[interfaceName] = URLSearchParams; + + ctorRegistry["URLSearchParams Iterator"] = Object.create(ctorRegistry["%IteratorPrototype%"], { + [Symbol.toStringTag]: { + configurable: true, + value: "URLSearchParams Iterator" + } + }); + utils.define(ctorRegistry["URLSearchParams Iterator"], { + next() { + const internal = this && this[utils.iterInternalSymbol]; + if (!internal) { + throw new globalObject.TypeError("next() called on a value that is not a URLSearchParams iterator object"); + } + + const { target, kind, index } = internal; + const values = Array.from(target[implSymbol]); + const len = values.length; + if (index >= len) { + return newObjectInRealm(globalObject, { value: undefined, done: true }); + } + + const pair = values[index]; + internal.index = index + 1; + return newObjectInRealm(globalObject, utils.iteratorResult(pair.map(utils.tryWrapperForImpl), kind)); + } + }); + + Object.defineProperty(globalObject, interfaceName, { + configurable: true, + writable: true, + value: URLSearchParams + }); +}; + +const Impl = require("./URLSearchParams-impl.js"); diff --git a/ts-ticket-office-service/node_modules/whatwg-url/lib/VoidFunction.js b/ts-ticket-office-service/node_modules/whatwg-url/lib/VoidFunction.js new file mode 100644 index 000000000..9a00672a7 --- /dev/null +++ b/ts-ticket-office-service/node_modules/whatwg-url/lib/VoidFunction.js @@ -0,0 +1,26 @@ +"use strict"; + +const conversions = require("webidl-conversions"); +const utils = require("./utils.js"); + +exports.convert = (globalObject, value, { context = "The provided value" } = {}) => { + if (typeof value !== "function") { + throw new globalObject.TypeError(context + " is not a function"); + } + + function invokeTheCallbackFunction() { + const thisArg = utils.tryWrapperForImpl(this); + let callResult; + + callResult = Reflect.apply(value, thisArg, []); + } + + invokeTheCallbackFunction.construct = () => { + let callResult = Reflect.construct(value, []); + }; + + invokeTheCallbackFunction[utils.wrapperSymbol] = value; + invokeTheCallbackFunction.objectReference = value; + + return invokeTheCallbackFunction; +}; diff --git a/ts-ticket-office-service/node_modules/whatwg-url/lib/encoding.js b/ts-ticket-office-service/node_modules/whatwg-url/lib/encoding.js new file mode 100644 index 000000000..cb66b8f10 --- /dev/null +++ b/ts-ticket-office-service/node_modules/whatwg-url/lib/encoding.js @@ -0,0 +1,16 @@ +"use strict"; +const utf8Encoder = new TextEncoder(); +const utf8Decoder = new TextDecoder("utf-8", { ignoreBOM: true }); + +function utf8Encode(string) { + return utf8Encoder.encode(string); +} + +function utf8DecodeWithoutBOM(bytes) { + return utf8Decoder.decode(bytes); +} + +module.exports = { + utf8Encode, + utf8DecodeWithoutBOM +}; diff --git a/ts-ticket-office-service/node_modules/whatwg-url/lib/infra.js b/ts-ticket-office-service/node_modules/whatwg-url/lib/infra.js new file mode 100644 index 000000000..4a984a3b3 --- /dev/null +++ b/ts-ticket-office-service/node_modules/whatwg-url/lib/infra.js @@ -0,0 +1,26 @@ +"use strict"; + +// Note that we take code points as JS numbers, not JS strings. + +function isASCIIDigit(c) { + return c >= 0x30 && c <= 0x39; +} + +function isASCIIAlpha(c) { + return (c >= 0x41 && c <= 0x5A) || (c >= 0x61 && c <= 0x7A); +} + +function isASCIIAlphanumeric(c) { + return isASCIIAlpha(c) || isASCIIDigit(c); +} + +function isASCIIHex(c) { + return isASCIIDigit(c) || (c >= 0x41 && c <= 0x46) || (c >= 0x61 && c <= 0x66); +} + +module.exports = { + isASCIIDigit, + isASCIIAlpha, + isASCIIAlphanumeric, + isASCIIHex +}; diff --git a/ts-ticket-office-service/node_modules/whatwg-url/lib/percent-encoding.js b/ts-ticket-office-service/node_modules/whatwg-url/lib/percent-encoding.js new file mode 100644 index 000000000..f8308673c --- /dev/null +++ b/ts-ticket-office-service/node_modules/whatwg-url/lib/percent-encoding.js @@ -0,0 +1,142 @@ +"use strict"; +const { isASCIIHex } = require("./infra"); +const { utf8Encode } = require("./encoding"); + +function p(char) { + return char.codePointAt(0); +} + +// https://url.spec.whatwg.org/#percent-encode +function percentEncode(c) { + let hex = c.toString(16).toUpperCase(); + if (hex.length === 1) { + hex = `0${hex}`; + } + + return `%${hex}`; +} + +// https://url.spec.whatwg.org/#percent-decode +function percentDecodeBytes(input) { + const output = new Uint8Array(input.byteLength); + let outputIndex = 0; + for (let i = 0; i < input.byteLength; ++i) { + const byte = input[i]; + if (byte !== 0x25) { + output[outputIndex++] = byte; + } else if (byte === 0x25 && (!isASCIIHex(input[i + 1]) || !isASCIIHex(input[i + 2]))) { + output[outputIndex++] = byte; + } else { + const bytePoint = parseInt(String.fromCodePoint(input[i + 1], input[i + 2]), 16); + output[outputIndex++] = bytePoint; + i += 2; + } + } + + return output.slice(0, outputIndex); +} + +// https://url.spec.whatwg.org/#string-percent-decode +function percentDecodeString(input) { + const bytes = utf8Encode(input); + return percentDecodeBytes(bytes); +} + +// https://url.spec.whatwg.org/#c0-control-percent-encode-set +function isC0ControlPercentEncode(c) { + return c <= 0x1F || c > 0x7E; +} + +// https://url.spec.whatwg.org/#fragment-percent-encode-set +const extraFragmentPercentEncodeSet = new Set([p(" "), p("\""), p("<"), p(">"), p("`")]); +function isFragmentPercentEncode(c) { + return isC0ControlPercentEncode(c) || extraFragmentPercentEncodeSet.has(c); +} + +// https://url.spec.whatwg.org/#query-percent-encode-set +const extraQueryPercentEncodeSet = new Set([p(" "), p("\""), p("#"), p("<"), p(">")]); +function isQueryPercentEncode(c) { + return isC0ControlPercentEncode(c) || extraQueryPercentEncodeSet.has(c); +} + +// https://url.spec.whatwg.org/#special-query-percent-encode-set +function isSpecialQueryPercentEncode(c) { + return isQueryPercentEncode(c) || c === p("'"); +} + +// https://url.spec.whatwg.org/#path-percent-encode-set +const extraPathPercentEncodeSet = new Set([p("?"), p("`"), p("{"), p("}")]); +function isPathPercentEncode(c) { + return isQueryPercentEncode(c) || extraPathPercentEncodeSet.has(c); +} + +// https://url.spec.whatwg.org/#userinfo-percent-encode-set +const extraUserinfoPercentEncodeSet = + new Set([p("/"), p(":"), p(";"), p("="), p("@"), p("["), p("\\"), p("]"), p("^"), p("|")]); +function isUserinfoPercentEncode(c) { + return isPathPercentEncode(c) || extraUserinfoPercentEncodeSet.has(c); +} + +// https://url.spec.whatwg.org/#component-percent-encode-set +const extraComponentPercentEncodeSet = new Set([p("$"), p("%"), p("&"), p("+"), p(",")]); +function isComponentPercentEncode(c) { + return isUserinfoPercentEncode(c) || extraComponentPercentEncodeSet.has(c); +} + +// https://url.spec.whatwg.org/#application-x-www-form-urlencoded-percent-encode-set +const extraURLEncodedPercentEncodeSet = new Set([p("!"), p("'"), p("("), p(")"), p("~")]); +function isURLEncodedPercentEncode(c) { + return isComponentPercentEncode(c) || extraURLEncodedPercentEncodeSet.has(c); +} + +// https://url.spec.whatwg.org/#code-point-percent-encode-after-encoding +// https://url.spec.whatwg.org/#utf-8-percent-encode +// Assuming encoding is always utf-8 allows us to trim one of the logic branches. TODO: support encoding. +// The "-Internal" variant here has code points as JS strings. The external version used by other files has code points +// as JS numbers, like the rest of the codebase. +function utf8PercentEncodeCodePointInternal(codePoint, percentEncodePredicate) { + const bytes = utf8Encode(codePoint); + let output = ""; + for (const byte of bytes) { + // Our percentEncodePredicate operates on bytes, not code points, so this is slightly different from the spec. + if (!percentEncodePredicate(byte)) { + output += String.fromCharCode(byte); + } else { + output += percentEncode(byte); + } + } + + return output; +} + +function utf8PercentEncodeCodePoint(codePoint, percentEncodePredicate) { + return utf8PercentEncodeCodePointInternal(String.fromCodePoint(codePoint), percentEncodePredicate); +} + +// https://url.spec.whatwg.org/#string-percent-encode-after-encoding +// https://url.spec.whatwg.org/#string-utf-8-percent-encode +function utf8PercentEncodeString(input, percentEncodePredicate, spaceAsPlus = false) { + let output = ""; + for (const codePoint of input) { + if (spaceAsPlus && codePoint === " ") { + output += "+"; + } else { + output += utf8PercentEncodeCodePointInternal(codePoint, percentEncodePredicate); + } + } + return output; +} + +module.exports = { + isC0ControlPercentEncode, + isFragmentPercentEncode, + isQueryPercentEncode, + isSpecialQueryPercentEncode, + isPathPercentEncode, + isUserinfoPercentEncode, + isURLEncodedPercentEncode, + percentDecodeString, + percentDecodeBytes, + utf8PercentEncodeString, + utf8PercentEncodeCodePoint +}; diff --git a/ts-ticket-office-service/node_modules/whatwg-url/lib/url-state-machine.js b/ts-ticket-office-service/node_modules/whatwg-url/lib/url-state-machine.js new file mode 100644 index 000000000..d9ecae2e9 --- /dev/null +++ b/ts-ticket-office-service/node_modules/whatwg-url/lib/url-state-machine.js @@ -0,0 +1,1244 @@ +"use strict"; +const tr46 = require("tr46"); + +const infra = require("./infra"); +const { utf8DecodeWithoutBOM } = require("./encoding"); +const { percentDecodeString, utf8PercentEncodeCodePoint, utf8PercentEncodeString, isC0ControlPercentEncode, + isFragmentPercentEncode, isQueryPercentEncode, isSpecialQueryPercentEncode, isPathPercentEncode, + isUserinfoPercentEncode } = require("./percent-encoding"); + +function p(char) { + return char.codePointAt(0); +} + +const specialSchemes = { + ftp: 21, + file: null, + http: 80, + https: 443, + ws: 80, + wss: 443 +}; + +const failure = Symbol("failure"); + +function countSymbols(str) { + return [...str].length; +} + +function at(input, idx) { + const c = input[idx]; + return isNaN(c) ? undefined : String.fromCodePoint(c); +} + +function isSingleDot(buffer) { + return buffer === "." || buffer.toLowerCase() === "%2e"; +} + +function isDoubleDot(buffer) { + buffer = buffer.toLowerCase(); + return buffer === ".." || buffer === "%2e." || buffer === ".%2e" || buffer === "%2e%2e"; +} + +function isWindowsDriveLetterCodePoints(cp1, cp2) { + return infra.isASCIIAlpha(cp1) && (cp2 === p(":") || cp2 === p("|")); +} + +function isWindowsDriveLetterString(string) { + return string.length === 2 && infra.isASCIIAlpha(string.codePointAt(0)) && (string[1] === ":" || string[1] === "|"); +} + +function isNormalizedWindowsDriveLetterString(string) { + return string.length === 2 && infra.isASCIIAlpha(string.codePointAt(0)) && string[1] === ":"; +} + +function containsForbiddenHostCodePoint(string) { + return string.search(/\u0000|\u0009|\u000A|\u000D|\u0020|#|%|\/|:|<|>|\?|@|\[|\\|\]|\^|\|/u) !== -1; +} + +function containsForbiddenHostCodePointExcludingPercent(string) { + return string.search(/\u0000|\u0009|\u000A|\u000D|\u0020|#|\/|:|<|>|\?|@|\[|\\|\]|\^|\|/u) !== -1; +} + +function isSpecialScheme(scheme) { + return specialSchemes[scheme] !== undefined; +} + +function isSpecial(url) { + return isSpecialScheme(url.scheme); +} + +function isNotSpecial(url) { + return !isSpecialScheme(url.scheme); +} + +function defaultPort(scheme) { + return specialSchemes[scheme]; +} + +function parseIPv4Number(input) { + if (input === "") { + return failure; + } + + let R = 10; + + if (input.length >= 2 && input.charAt(0) === "0" && input.charAt(1).toLowerCase() === "x") { + input = input.substring(2); + R = 16; + } else if (input.length >= 2 && input.charAt(0) === "0") { + input = input.substring(1); + R = 8; + } + + if (input === "") { + return 0; + } + + let regex = /[^0-7]/u; + if (R === 10) { + regex = /[^0-9]/u; + } + if (R === 16) { + regex = /[^0-9A-Fa-f]/u; + } + + if (regex.test(input)) { + return failure; + } + + return parseInt(input, R); +} + +function parseIPv4(input) { + const parts = input.split("."); + if (parts[parts.length - 1] === "") { + if (parts.length > 1) { + parts.pop(); + } + } + + if (parts.length > 4) { + return failure; + } + + const numbers = []; + for (const part of parts) { + const n = parseIPv4Number(part); + if (n === failure) { + return failure; + } + + numbers.push(n); + } + + for (let i = 0; i < numbers.length - 1; ++i) { + if (numbers[i] > 255) { + return failure; + } + } + if (numbers[numbers.length - 1] >= 256 ** (5 - numbers.length)) { + return failure; + } + + let ipv4 = numbers.pop(); + let counter = 0; + + for (const n of numbers) { + ipv4 += n * 256 ** (3 - counter); + ++counter; + } + + return ipv4; +} + +function serializeIPv4(address) { + let output = ""; + let n = address; + + for (let i = 1; i <= 4; ++i) { + output = String(n % 256) + output; + if (i !== 4) { + output = `.${output}`; + } + n = Math.floor(n / 256); + } + + return output; +} + +function parseIPv6(input) { + const address = [0, 0, 0, 0, 0, 0, 0, 0]; + let pieceIndex = 0; + let compress = null; + let pointer = 0; + + input = Array.from(input, c => c.codePointAt(0)); + + if (input[pointer] === p(":")) { + if (input[pointer + 1] !== p(":")) { + return failure; + } + + pointer += 2; + ++pieceIndex; + compress = pieceIndex; + } + + while (pointer < input.length) { + if (pieceIndex === 8) { + return failure; + } + + if (input[pointer] === p(":")) { + if (compress !== null) { + return failure; + } + ++pointer; + ++pieceIndex; + compress = pieceIndex; + continue; + } + + let value = 0; + let length = 0; + + while (length < 4 && infra.isASCIIHex(input[pointer])) { + value = value * 0x10 + parseInt(at(input, pointer), 16); + ++pointer; + ++length; + } + + if (input[pointer] === p(".")) { + if (length === 0) { + return failure; + } + + pointer -= length; + + if (pieceIndex > 6) { + return failure; + } + + let numbersSeen = 0; + + while (input[pointer] !== undefined) { + let ipv4Piece = null; + + if (numbersSeen > 0) { + if (input[pointer] === p(".") && numbersSeen < 4) { + ++pointer; + } else { + return failure; + } + } + + if (!infra.isASCIIDigit(input[pointer])) { + return failure; + } + + while (infra.isASCIIDigit(input[pointer])) { + const number = parseInt(at(input, pointer)); + if (ipv4Piece === null) { + ipv4Piece = number; + } else if (ipv4Piece === 0) { + return failure; + } else { + ipv4Piece = ipv4Piece * 10 + number; + } + if (ipv4Piece > 255) { + return failure; + } + ++pointer; + } + + address[pieceIndex] = address[pieceIndex] * 0x100 + ipv4Piece; + + ++numbersSeen; + + if (numbersSeen === 2 || numbersSeen === 4) { + ++pieceIndex; + } + } + + if (numbersSeen !== 4) { + return failure; + } + + break; + } else if (input[pointer] === p(":")) { + ++pointer; + if (input[pointer] === undefined) { + return failure; + } + } else if (input[pointer] !== undefined) { + return failure; + } + + address[pieceIndex] = value; + ++pieceIndex; + } + + if (compress !== null) { + let swaps = pieceIndex - compress; + pieceIndex = 7; + while (pieceIndex !== 0 && swaps > 0) { + const temp = address[compress + swaps - 1]; + address[compress + swaps - 1] = address[pieceIndex]; + address[pieceIndex] = temp; + --pieceIndex; + --swaps; + } + } else if (compress === null && pieceIndex !== 8) { + return failure; + } + + return address; +} + +function serializeIPv6(address) { + let output = ""; + const compress = findLongestZeroSequence(address); + let ignore0 = false; + + for (let pieceIndex = 0; pieceIndex <= 7; ++pieceIndex) { + if (ignore0 && address[pieceIndex] === 0) { + continue; + } else if (ignore0) { + ignore0 = false; + } + + if (compress === pieceIndex) { + const separator = pieceIndex === 0 ? "::" : ":"; + output += separator; + ignore0 = true; + continue; + } + + output += address[pieceIndex].toString(16); + + if (pieceIndex !== 7) { + output += ":"; + } + } + + return output; +} + +function parseHost(input, isNotSpecialArg = false) { + if (input[0] === "[") { + if (input[input.length - 1] !== "]") { + return failure; + } + + return parseIPv6(input.substring(1, input.length - 1)); + } + + if (isNotSpecialArg) { + return parseOpaqueHost(input); + } + + const domain = utf8DecodeWithoutBOM(percentDecodeString(input)); + const asciiDomain = domainToASCII(domain); + if (asciiDomain === failure) { + return failure; + } + + if (containsForbiddenHostCodePoint(asciiDomain)) { + return failure; + } + + if (endsInANumber(asciiDomain)) { + return parseIPv4(asciiDomain); + } + + return asciiDomain; +} + +function endsInANumber(input) { + const parts = input.split("."); + if (parts[parts.length - 1] === "") { + if (parts.length === 1) { + return false; + } + parts.pop(); + } + + const last = parts[parts.length - 1]; + if (parseIPv4Number(last) !== failure) { + return true; + } + + if (/^[0-9]+$/u.test(last)) { + return true; + } + + return false; +} + +function parseOpaqueHost(input) { + if (containsForbiddenHostCodePointExcludingPercent(input)) { + return failure; + } + + return utf8PercentEncodeString(input, isC0ControlPercentEncode); +} + +function findLongestZeroSequence(arr) { + let maxIdx = null; + let maxLen = 1; // only find elements > 1 + let currStart = null; + let currLen = 0; + + for (let i = 0; i < arr.length; ++i) { + if (arr[i] !== 0) { + if (currLen > maxLen) { + maxIdx = currStart; + maxLen = currLen; + } + + currStart = null; + currLen = 0; + } else { + if (currStart === null) { + currStart = i; + } + ++currLen; + } + } + + // if trailing zeros + if (currLen > maxLen) { + return currStart; + } + + return maxIdx; +} + +function serializeHost(host) { + if (typeof host === "number") { + return serializeIPv4(host); + } + + // IPv6 serializer + if (host instanceof Array) { + return `[${serializeIPv6(host)}]`; + } + + return host; +} + +function domainToASCII(domain, beStrict = false) { + const result = tr46.toASCII(domain, { + checkBidi: true, + checkHyphens: false, + checkJoiners: true, + useSTD3ASCIIRules: beStrict, + verifyDNSLength: beStrict + }); + if (result === null || result === "") { + return failure; + } + return result; +} + +function trimControlChars(url) { + return url.replace(/^[\u0000-\u001F\u0020]+|[\u0000-\u001F\u0020]+$/ug, ""); +} + +function trimTabAndNewline(url) { + return url.replace(/\u0009|\u000A|\u000D/ug, ""); +} + +function shortenPath(url) { + const { path } = url; + if (path.length === 0) { + return; + } + if (url.scheme === "file" && path.length === 1 && isNormalizedWindowsDriveLetter(path[0])) { + return; + } + + path.pop(); +} + +function includesCredentials(url) { + return url.username !== "" || url.password !== ""; +} + +function cannotHaveAUsernamePasswordPort(url) { + return url.host === null || url.host === "" || hasAnOpaquePath(url) || url.scheme === "file"; +} + +function hasAnOpaquePath(url) { + return typeof url.path === "string"; +} + +function isNormalizedWindowsDriveLetter(string) { + return /^[A-Za-z]:$/u.test(string); +} + +function URLStateMachine(input, base, encodingOverride, url, stateOverride) { + this.pointer = 0; + this.input = input; + this.base = base || null; + this.encodingOverride = encodingOverride || "utf-8"; + this.stateOverride = stateOverride; + this.url = url; + this.failure = false; + this.parseError = false; + + if (!this.url) { + this.url = { + scheme: "", + username: "", + password: "", + host: null, + port: null, + path: [], + query: null, + fragment: null + }; + + const res = trimControlChars(this.input); + if (res !== this.input) { + this.parseError = true; + } + this.input = res; + } + + const res = trimTabAndNewline(this.input); + if (res !== this.input) { + this.parseError = true; + } + this.input = res; + + this.state = stateOverride || "scheme start"; + + this.buffer = ""; + this.atFlag = false; + this.arrFlag = false; + this.passwordTokenSeenFlag = false; + + this.input = Array.from(this.input, c => c.codePointAt(0)); + + for (; this.pointer <= this.input.length; ++this.pointer) { + const c = this.input[this.pointer]; + const cStr = isNaN(c) ? undefined : String.fromCodePoint(c); + + // exec state machine + const ret = this[`parse ${this.state}`](c, cStr); + if (!ret) { + break; // terminate algorithm + } else if (ret === failure) { + this.failure = true; + break; + } + } +} + +URLStateMachine.prototype["parse scheme start"] = function parseSchemeStart(c, cStr) { + if (infra.isASCIIAlpha(c)) { + this.buffer += cStr.toLowerCase(); + this.state = "scheme"; + } else if (!this.stateOverride) { + this.state = "no scheme"; + --this.pointer; + } else { + this.parseError = true; + return failure; + } + + return true; +}; + +URLStateMachine.prototype["parse scheme"] = function parseScheme(c, cStr) { + if (infra.isASCIIAlphanumeric(c) || c === p("+") || c === p("-") || c === p(".")) { + this.buffer += cStr.toLowerCase(); + } else if (c === p(":")) { + if (this.stateOverride) { + if (isSpecial(this.url) && !isSpecialScheme(this.buffer)) { + return false; + } + + if (!isSpecial(this.url) && isSpecialScheme(this.buffer)) { + return false; + } + + if ((includesCredentials(this.url) || this.url.port !== null) && this.buffer === "file") { + return false; + } + + if (this.url.scheme === "file" && this.url.host === "") { + return false; + } + } + this.url.scheme = this.buffer; + if (this.stateOverride) { + if (this.url.port === defaultPort(this.url.scheme)) { + this.url.port = null; + } + return false; + } + this.buffer = ""; + if (this.url.scheme === "file") { + if (this.input[this.pointer + 1] !== p("/") || this.input[this.pointer + 2] !== p("/")) { + this.parseError = true; + } + this.state = "file"; + } else if (isSpecial(this.url) && this.base !== null && this.base.scheme === this.url.scheme) { + this.state = "special relative or authority"; + } else if (isSpecial(this.url)) { + this.state = "special authority slashes"; + } else if (this.input[this.pointer + 1] === p("/")) { + this.state = "path or authority"; + ++this.pointer; + } else { + this.url.path = ""; + this.state = "opaque path"; + } + } else if (!this.stateOverride) { + this.buffer = ""; + this.state = "no scheme"; + this.pointer = -1; + } else { + this.parseError = true; + return failure; + } + + return true; +}; + +URLStateMachine.prototype["parse no scheme"] = function parseNoScheme(c) { + if (this.base === null || (hasAnOpaquePath(this.base) && c !== p("#"))) { + return failure; + } else if (hasAnOpaquePath(this.base) && c === p("#")) { + this.url.scheme = this.base.scheme; + this.url.path = this.base.path; + this.url.query = this.base.query; + this.url.fragment = ""; + this.state = "fragment"; + } else if (this.base.scheme === "file") { + this.state = "file"; + --this.pointer; + } else { + this.state = "relative"; + --this.pointer; + } + + return true; +}; + +URLStateMachine.prototype["parse special relative or authority"] = function parseSpecialRelativeOrAuthority(c) { + if (c === p("/") && this.input[this.pointer + 1] === p("/")) { + this.state = "special authority ignore slashes"; + ++this.pointer; + } else { + this.parseError = true; + this.state = "relative"; + --this.pointer; + } + + return true; +}; + +URLStateMachine.prototype["parse path or authority"] = function parsePathOrAuthority(c) { + if (c === p("/")) { + this.state = "authority"; + } else { + this.state = "path"; + --this.pointer; + } + + return true; +}; + +URLStateMachine.prototype["parse relative"] = function parseRelative(c) { + this.url.scheme = this.base.scheme; + if (c === p("/")) { + this.state = "relative slash"; + } else if (isSpecial(this.url) && c === p("\\")) { + this.parseError = true; + this.state = "relative slash"; + } else { + this.url.username = this.base.username; + this.url.password = this.base.password; + this.url.host = this.base.host; + this.url.port = this.base.port; + this.url.path = this.base.path.slice(); + this.url.query = this.base.query; + if (c === p("?")) { + this.url.query = ""; + this.state = "query"; + } else if (c === p("#")) { + this.url.fragment = ""; + this.state = "fragment"; + } else if (!isNaN(c)) { + this.url.query = null; + this.url.path.pop(); + this.state = "path"; + --this.pointer; + } + } + + return true; +}; + +URLStateMachine.prototype["parse relative slash"] = function parseRelativeSlash(c) { + if (isSpecial(this.url) && (c === p("/") || c === p("\\"))) { + if (c === p("\\")) { + this.parseError = true; + } + this.state = "special authority ignore slashes"; + } else if (c === p("/")) { + this.state = "authority"; + } else { + this.url.username = this.base.username; + this.url.password = this.base.password; + this.url.host = this.base.host; + this.url.port = this.base.port; + this.state = "path"; + --this.pointer; + } + + return true; +}; + +URLStateMachine.prototype["parse special authority slashes"] = function parseSpecialAuthoritySlashes(c) { + if (c === p("/") && this.input[this.pointer + 1] === p("/")) { + this.state = "special authority ignore slashes"; + ++this.pointer; + } else { + this.parseError = true; + this.state = "special authority ignore slashes"; + --this.pointer; + } + + return true; +}; + +URLStateMachine.prototype["parse special authority ignore slashes"] = function parseSpecialAuthorityIgnoreSlashes(c) { + if (c !== p("/") && c !== p("\\")) { + this.state = "authority"; + --this.pointer; + } else { + this.parseError = true; + } + + return true; +}; + +URLStateMachine.prototype["parse authority"] = function parseAuthority(c, cStr) { + if (c === p("@")) { + this.parseError = true; + if (this.atFlag) { + this.buffer = `%40${this.buffer}`; + } + this.atFlag = true; + + // careful, this is based on buffer and has its own pointer (this.pointer != pointer) and inner chars + const len = countSymbols(this.buffer); + for (let pointer = 0; pointer < len; ++pointer) { + const codePoint = this.buffer.codePointAt(pointer); + + if (codePoint === p(":") && !this.passwordTokenSeenFlag) { + this.passwordTokenSeenFlag = true; + continue; + } + const encodedCodePoints = utf8PercentEncodeCodePoint(codePoint, isUserinfoPercentEncode); + if (this.passwordTokenSeenFlag) { + this.url.password += encodedCodePoints; + } else { + this.url.username += encodedCodePoints; + } + } + this.buffer = ""; + } else if (isNaN(c) || c === p("/") || c === p("?") || c === p("#") || + (isSpecial(this.url) && c === p("\\"))) { + if (this.atFlag && this.buffer === "") { + this.parseError = true; + return failure; + } + this.pointer -= countSymbols(this.buffer) + 1; + this.buffer = ""; + this.state = "host"; + } else { + this.buffer += cStr; + } + + return true; +}; + +URLStateMachine.prototype["parse hostname"] = +URLStateMachine.prototype["parse host"] = function parseHostName(c, cStr) { + if (this.stateOverride && this.url.scheme === "file") { + --this.pointer; + this.state = "file host"; + } else if (c === p(":") && !this.arrFlag) { + if (this.buffer === "") { + this.parseError = true; + return failure; + } + + if (this.stateOverride === "hostname") { + return false; + } + + const host = parseHost(this.buffer, isNotSpecial(this.url)); + if (host === failure) { + return failure; + } + + this.url.host = host; + this.buffer = ""; + this.state = "port"; + } else if (isNaN(c) || c === p("/") || c === p("?") || c === p("#") || + (isSpecial(this.url) && c === p("\\"))) { + --this.pointer; + if (isSpecial(this.url) && this.buffer === "") { + this.parseError = true; + return failure; + } else if (this.stateOverride && this.buffer === "" && + (includesCredentials(this.url) || this.url.port !== null)) { + this.parseError = true; + return false; + } + + const host = parseHost(this.buffer, isNotSpecial(this.url)); + if (host === failure) { + return failure; + } + + this.url.host = host; + this.buffer = ""; + this.state = "path start"; + if (this.stateOverride) { + return false; + } + } else { + if (c === p("[")) { + this.arrFlag = true; + } else if (c === p("]")) { + this.arrFlag = false; + } + this.buffer += cStr; + } + + return true; +}; + +URLStateMachine.prototype["parse port"] = function parsePort(c, cStr) { + if (infra.isASCIIDigit(c)) { + this.buffer += cStr; + } else if (isNaN(c) || c === p("/") || c === p("?") || c === p("#") || + (isSpecial(this.url) && c === p("\\")) || + this.stateOverride) { + if (this.buffer !== "") { + const port = parseInt(this.buffer); + if (port > 2 ** 16 - 1) { + this.parseError = true; + return failure; + } + this.url.port = port === defaultPort(this.url.scheme) ? null : port; + this.buffer = ""; + } + if (this.stateOverride) { + return false; + } + this.state = "path start"; + --this.pointer; + } else { + this.parseError = true; + return failure; + } + + return true; +}; + +const fileOtherwiseCodePoints = new Set([p("/"), p("\\"), p("?"), p("#")]); + +function startsWithWindowsDriveLetter(input, pointer) { + const length = input.length - pointer; + return length >= 2 && + isWindowsDriveLetterCodePoints(input[pointer], input[pointer + 1]) && + (length === 2 || fileOtherwiseCodePoints.has(input[pointer + 2])); +} + +URLStateMachine.prototype["parse file"] = function parseFile(c) { + this.url.scheme = "file"; + this.url.host = ""; + + if (c === p("/") || c === p("\\")) { + if (c === p("\\")) { + this.parseError = true; + } + this.state = "file slash"; + } else if (this.base !== null && this.base.scheme === "file") { + this.url.host = this.base.host; + this.url.path = this.base.path.slice(); + this.url.query = this.base.query; + if (c === p("?")) { + this.url.query = ""; + this.state = "query"; + } else if (c === p("#")) { + this.url.fragment = ""; + this.state = "fragment"; + } else if (!isNaN(c)) { + this.url.query = null; + if (!startsWithWindowsDriveLetter(this.input, this.pointer)) { + shortenPath(this.url); + } else { + this.parseError = true; + this.url.path = []; + } + + this.state = "path"; + --this.pointer; + } + } else { + this.state = "path"; + --this.pointer; + } + + return true; +}; + +URLStateMachine.prototype["parse file slash"] = function parseFileSlash(c) { + if (c === p("/") || c === p("\\")) { + if (c === p("\\")) { + this.parseError = true; + } + this.state = "file host"; + } else { + if (this.base !== null && this.base.scheme === "file") { + if (!startsWithWindowsDriveLetter(this.input, this.pointer) && + isNormalizedWindowsDriveLetterString(this.base.path[0])) { + this.url.path.push(this.base.path[0]); + } + this.url.host = this.base.host; + } + this.state = "path"; + --this.pointer; + } + + return true; +}; + +URLStateMachine.prototype["parse file host"] = function parseFileHost(c, cStr) { + if (isNaN(c) || c === p("/") || c === p("\\") || c === p("?") || c === p("#")) { + --this.pointer; + if (!this.stateOverride && isWindowsDriveLetterString(this.buffer)) { + this.parseError = true; + this.state = "path"; + } else if (this.buffer === "") { + this.url.host = ""; + if (this.stateOverride) { + return false; + } + this.state = "path start"; + } else { + let host = parseHost(this.buffer, isNotSpecial(this.url)); + if (host === failure) { + return failure; + } + if (host === "localhost") { + host = ""; + } + this.url.host = host; + + if (this.stateOverride) { + return false; + } + + this.buffer = ""; + this.state = "path start"; + } + } else { + this.buffer += cStr; + } + + return true; +}; + +URLStateMachine.prototype["parse path start"] = function parsePathStart(c) { + if (isSpecial(this.url)) { + if (c === p("\\")) { + this.parseError = true; + } + this.state = "path"; + + if (c !== p("/") && c !== p("\\")) { + --this.pointer; + } + } else if (!this.stateOverride && c === p("?")) { + this.url.query = ""; + this.state = "query"; + } else if (!this.stateOverride && c === p("#")) { + this.url.fragment = ""; + this.state = "fragment"; + } else if (c !== undefined) { + this.state = "path"; + if (c !== p("/")) { + --this.pointer; + } + } else if (this.stateOverride && this.url.host === null) { + this.url.path.push(""); + } + + return true; +}; + +URLStateMachine.prototype["parse path"] = function parsePath(c) { + if (isNaN(c) || c === p("/") || (isSpecial(this.url) && c === p("\\")) || + (!this.stateOverride && (c === p("?") || c === p("#")))) { + if (isSpecial(this.url) && c === p("\\")) { + this.parseError = true; + } + + if (isDoubleDot(this.buffer)) { + shortenPath(this.url); + if (c !== p("/") && !(isSpecial(this.url) && c === p("\\"))) { + this.url.path.push(""); + } + } else if (isSingleDot(this.buffer) && c !== p("/") && + !(isSpecial(this.url) && c === p("\\"))) { + this.url.path.push(""); + } else if (!isSingleDot(this.buffer)) { + if (this.url.scheme === "file" && this.url.path.length === 0 && isWindowsDriveLetterString(this.buffer)) { + this.buffer = `${this.buffer[0]}:`; + } + this.url.path.push(this.buffer); + } + this.buffer = ""; + if (c === p("?")) { + this.url.query = ""; + this.state = "query"; + } + if (c === p("#")) { + this.url.fragment = ""; + this.state = "fragment"; + } + } else { + // TODO: If c is not a URL code point and not "%", parse error. + + if (c === p("%") && + (!infra.isASCIIHex(this.input[this.pointer + 1]) || + !infra.isASCIIHex(this.input[this.pointer + 2]))) { + this.parseError = true; + } + + this.buffer += utf8PercentEncodeCodePoint(c, isPathPercentEncode); + } + + return true; +}; + +URLStateMachine.prototype["parse opaque path"] = function parseOpaquePath(c) { + if (c === p("?")) { + this.url.query = ""; + this.state = "query"; + } else if (c === p("#")) { + this.url.fragment = ""; + this.state = "fragment"; + } else { + // TODO: Add: not a URL code point + if (!isNaN(c) && c !== p("%")) { + this.parseError = true; + } + + if (c === p("%") && + (!infra.isASCIIHex(this.input[this.pointer + 1]) || + !infra.isASCIIHex(this.input[this.pointer + 2]))) { + this.parseError = true; + } + + if (!isNaN(c)) { + this.url.path += utf8PercentEncodeCodePoint(c, isC0ControlPercentEncode); + } + } + + return true; +}; + +URLStateMachine.prototype["parse query"] = function parseQuery(c, cStr) { + if (!isSpecial(this.url) || this.url.scheme === "ws" || this.url.scheme === "wss") { + this.encodingOverride = "utf-8"; + } + + if ((!this.stateOverride && c === p("#")) || isNaN(c)) { + const queryPercentEncodePredicate = isSpecial(this.url) ? isSpecialQueryPercentEncode : isQueryPercentEncode; + this.url.query += utf8PercentEncodeString(this.buffer, queryPercentEncodePredicate); + + this.buffer = ""; + + if (c === p("#")) { + this.url.fragment = ""; + this.state = "fragment"; + } + } else if (!isNaN(c)) { + // TODO: If c is not a URL code point and not "%", parse error. + + if (c === p("%") && + (!infra.isASCIIHex(this.input[this.pointer + 1]) || + !infra.isASCIIHex(this.input[this.pointer + 2]))) { + this.parseError = true; + } + + this.buffer += cStr; + } + + return true; +}; + +URLStateMachine.prototype["parse fragment"] = function parseFragment(c) { + if (!isNaN(c)) { + // TODO: If c is not a URL code point and not "%", parse error. + if (c === p("%") && + (!infra.isASCIIHex(this.input[this.pointer + 1]) || + !infra.isASCIIHex(this.input[this.pointer + 2]))) { + this.parseError = true; + } + + this.url.fragment += utf8PercentEncodeCodePoint(c, isFragmentPercentEncode); + } + + return true; +}; + +function serializeURL(url, excludeFragment) { + let output = `${url.scheme}:`; + if (url.host !== null) { + output += "//"; + + if (url.username !== "" || url.password !== "") { + output += url.username; + if (url.password !== "") { + output += `:${url.password}`; + } + output += "@"; + } + + output += serializeHost(url.host); + + if (url.port !== null) { + output += `:${url.port}`; + } + } + + if (url.host === null && !hasAnOpaquePath(url) && url.path.length > 1 && url.path[0] === "") { + output += "/."; + } + output += serializePath(url); + + if (url.query !== null) { + output += `?${url.query}`; + } + + if (!excludeFragment && url.fragment !== null) { + output += `#${url.fragment}`; + } + + return output; +} + +function serializeOrigin(tuple) { + let result = `${tuple.scheme}://`; + result += serializeHost(tuple.host); + + if (tuple.port !== null) { + result += `:${tuple.port}`; + } + + return result; +} + +function serializePath(url) { + if (hasAnOpaquePath(url)) { + return url.path; + } + + let output = ""; + for (const segment of url.path) { + output += `/${segment}`; + } + return output; +} + +module.exports.serializeURL = serializeURL; + +module.exports.serializePath = serializePath; + +module.exports.serializeURLOrigin = function (url) { + // https://url.spec.whatwg.org/#concept-url-origin + switch (url.scheme) { + case "blob": + try { + return module.exports.serializeURLOrigin(module.exports.parseURL(serializePath(url))); + } catch (e) { + // serializing an opaque origin returns "null" + return "null"; + } + case "ftp": + case "http": + case "https": + case "ws": + case "wss": + return serializeOrigin({ + scheme: url.scheme, + host: url.host, + port: url.port + }); + case "file": + // The spec says: + // > Unfortunate as it is, this is left as an exercise to the reader. When in doubt, return a new opaque origin. + // Browsers tested so far: + // - Chrome says "file://", but treats file: URLs as cross-origin for most (all?) purposes; see e.g. + // https://bugs.chromium.org/p/chromium/issues/detail?id=37586 + // - Firefox says "null", but treats file: URLs as same-origin sometimes based on directory stuff; see + // https://developer.mozilla.org/en-US/docs/Archive/Misc_top_level/Same-origin_policy_for_file:_URIs + return "null"; + default: + // serializing an opaque origin returns "null" + return "null"; + } +}; + +module.exports.basicURLParse = function (input, options) { + if (options === undefined) { + options = {}; + } + + const usm = new URLStateMachine(input, options.baseURL, options.encodingOverride, options.url, options.stateOverride); + if (usm.failure) { + return null; + } + + return usm.url; +}; + +module.exports.setTheUsername = function (url, username) { + url.username = utf8PercentEncodeString(username, isUserinfoPercentEncode); +}; + +module.exports.setThePassword = function (url, password) { + url.password = utf8PercentEncodeString(password, isUserinfoPercentEncode); +}; + +module.exports.serializeHost = serializeHost; + +module.exports.cannotHaveAUsernamePasswordPort = cannotHaveAUsernamePasswordPort; + +module.exports.hasAnOpaquePath = hasAnOpaquePath; + +module.exports.serializeInteger = function (integer) { + return String(integer); +}; + +module.exports.parseURL = function (input, options) { + if (options === undefined) { + options = {}; + } + + // We don't handle blobs, so this just delegates: + return module.exports.basicURLParse(input, { baseURL: options.baseURL, encodingOverride: options.encodingOverride }); +}; diff --git a/ts-ticket-office-service/node_modules/whatwg-url/lib/urlencoded.js b/ts-ticket-office-service/node_modules/whatwg-url/lib/urlencoded.js new file mode 100644 index 000000000..e72306374 --- /dev/null +++ b/ts-ticket-office-service/node_modules/whatwg-url/lib/urlencoded.js @@ -0,0 +1,106 @@ +"use strict"; +const { utf8Encode, utf8DecodeWithoutBOM } = require("./encoding"); +const { percentDecodeBytes, utf8PercentEncodeString, isURLEncodedPercentEncode } = require("./percent-encoding"); + +function p(char) { + return char.codePointAt(0); +} + +// https://url.spec.whatwg.org/#concept-urlencoded-parser +function parseUrlencoded(input) { + const sequences = strictlySplitByteSequence(input, p("&")); + const output = []; + for (const bytes of sequences) { + if (bytes.length === 0) { + continue; + } + + let name, value; + const indexOfEqual = bytes.indexOf(p("=")); + + if (indexOfEqual >= 0) { + name = bytes.slice(0, indexOfEqual); + value = bytes.slice(indexOfEqual + 1); + } else { + name = bytes; + value = new Uint8Array(0); + } + + name = replaceByteInByteSequence(name, 0x2B, 0x20); + value = replaceByteInByteSequence(value, 0x2B, 0x20); + + const nameString = utf8DecodeWithoutBOM(percentDecodeBytes(name)); + const valueString = utf8DecodeWithoutBOM(percentDecodeBytes(value)); + + output.push([nameString, valueString]); + } + return output; +} + +// https://url.spec.whatwg.org/#concept-urlencoded-string-parser +function parseUrlencodedString(input) { + return parseUrlencoded(utf8Encode(input)); +} + +// https://url.spec.whatwg.org/#concept-urlencoded-serializer +function serializeUrlencoded(tuples, encodingOverride = undefined) { + let encoding = "utf-8"; + if (encodingOverride !== undefined) { + // TODO "get the output encoding", i.e. handle encoding labels vs. names. + encoding = encodingOverride; + } + + let output = ""; + for (const [i, tuple] of tuples.entries()) { + // TODO: handle encoding override + + const name = utf8PercentEncodeString(tuple[0], isURLEncodedPercentEncode, true); + + let value = tuple[1]; + if (tuple.length > 2 && tuple[2] !== undefined) { + if (tuple[2] === "hidden" && name === "_charset_") { + value = encoding; + } else if (tuple[2] === "file") { + // value is a File object + value = value.name; + } + } + + value = utf8PercentEncodeString(value, isURLEncodedPercentEncode, true); + + if (i !== 0) { + output += "&"; + } + output += `${name}=${value}`; + } + return output; +} + +function strictlySplitByteSequence(buf, cp) { + const list = []; + let last = 0; + let i = buf.indexOf(cp); + while (i >= 0) { + list.push(buf.slice(last, i)); + last = i + 1; + i = buf.indexOf(cp, last); + } + if (last !== buf.length) { + list.push(buf.slice(last)); + } + return list; +} + +function replaceByteInByteSequence(buf, from, to) { + let i = buf.indexOf(from); + while (i >= 0) { + buf[i] = to; + i = buf.indexOf(from, i + 1); + } + return buf; +} + +module.exports = { + parseUrlencodedString, + serializeUrlencoded +}; diff --git a/ts-ticket-office-service/node_modules/whatwg-url/lib/utils.js b/ts-ticket-office-service/node_modules/whatwg-url/lib/utils.js new file mode 100644 index 000000000..3af17706f --- /dev/null +++ b/ts-ticket-office-service/node_modules/whatwg-url/lib/utils.js @@ -0,0 +1,190 @@ +"use strict"; + +// Returns "Type(value) is Object" in ES terminology. +function isObject(value) { + return (typeof value === "object" && value !== null) || typeof value === "function"; +} + +const hasOwn = Function.prototype.call.bind(Object.prototype.hasOwnProperty); + +// Like `Object.assign`, but using `[[GetOwnProperty]]` and `[[DefineOwnProperty]]` +// instead of `[[Get]]` and `[[Set]]` and only allowing objects +function define(target, source) { + for (const key of Reflect.ownKeys(source)) { + const descriptor = Reflect.getOwnPropertyDescriptor(source, key); + if (descriptor && !Reflect.defineProperty(target, key, descriptor)) { + throw new TypeError(`Cannot redefine property: ${String(key)}`); + } + } +} + +function newObjectInRealm(globalObject, object) { + const ctorRegistry = initCtorRegistry(globalObject); + return Object.defineProperties( + Object.create(ctorRegistry["%Object.prototype%"]), + Object.getOwnPropertyDescriptors(object) + ); +} + +const wrapperSymbol = Symbol("wrapper"); +const implSymbol = Symbol("impl"); +const sameObjectCaches = Symbol("SameObject caches"); +const ctorRegistrySymbol = Symbol.for("[webidl2js] constructor registry"); + +const AsyncIteratorPrototype = Object.getPrototypeOf(Object.getPrototypeOf(async function* () {}).prototype); + +function initCtorRegistry(globalObject) { + if (hasOwn(globalObject, ctorRegistrySymbol)) { + return globalObject[ctorRegistrySymbol]; + } + + const ctorRegistry = Object.create(null); + + // In addition to registering all the WebIDL2JS-generated types in the constructor registry, + // we also register a few intrinsics that we make use of in generated code, since they are not + // easy to grab from the globalObject variable. + ctorRegistry["%Object.prototype%"] = globalObject.Object.prototype; + ctorRegistry["%IteratorPrototype%"] = Object.getPrototypeOf( + Object.getPrototypeOf(new globalObject.Array()[Symbol.iterator]()) + ); + + try { + ctorRegistry["%AsyncIteratorPrototype%"] = Object.getPrototypeOf( + Object.getPrototypeOf( + globalObject.eval("(async function* () {})").prototype + ) + ); + } catch { + ctorRegistry["%AsyncIteratorPrototype%"] = AsyncIteratorPrototype; + } + + globalObject[ctorRegistrySymbol] = ctorRegistry; + return ctorRegistry; +} + +function getSameObject(wrapper, prop, creator) { + if (!wrapper[sameObjectCaches]) { + wrapper[sameObjectCaches] = Object.create(null); + } + + if (prop in wrapper[sameObjectCaches]) { + return wrapper[sameObjectCaches][prop]; + } + + wrapper[sameObjectCaches][prop] = creator(); + return wrapper[sameObjectCaches][prop]; +} + +function wrapperForImpl(impl) { + return impl ? impl[wrapperSymbol] : null; +} + +function implForWrapper(wrapper) { + return wrapper ? wrapper[implSymbol] : null; +} + +function tryWrapperForImpl(impl) { + const wrapper = wrapperForImpl(impl); + return wrapper ? wrapper : impl; +} + +function tryImplForWrapper(wrapper) { + const impl = implForWrapper(wrapper); + return impl ? impl : wrapper; +} + +const iterInternalSymbol = Symbol("internal"); + +function isArrayIndexPropName(P) { + if (typeof P !== "string") { + return false; + } + const i = P >>> 0; + if (i === 2 ** 32 - 1) { + return false; + } + const s = `${i}`; + if (P !== s) { + return false; + } + return true; +} + +const byteLengthGetter = + Object.getOwnPropertyDescriptor(ArrayBuffer.prototype, "byteLength").get; +function isArrayBuffer(value) { + try { + byteLengthGetter.call(value); + return true; + } catch (e) { + return false; + } +} + +function iteratorResult([key, value], kind) { + let result; + switch (kind) { + case "key": + result = key; + break; + case "value": + result = value; + break; + case "key+value": + result = [key, value]; + break; + } + return { value: result, done: false }; +} + +const supportsPropertyIndex = Symbol("supports property index"); +const supportedPropertyIndices = Symbol("supported property indices"); +const supportsPropertyName = Symbol("supports property name"); +const supportedPropertyNames = Symbol("supported property names"); +const indexedGet = Symbol("indexed property get"); +const indexedSetNew = Symbol("indexed property set new"); +const indexedSetExisting = Symbol("indexed property set existing"); +const namedGet = Symbol("named property get"); +const namedSetNew = Symbol("named property set new"); +const namedSetExisting = Symbol("named property set existing"); +const namedDelete = Symbol("named property delete"); + +const asyncIteratorNext = Symbol("async iterator get the next iteration result"); +const asyncIteratorReturn = Symbol("async iterator return steps"); +const asyncIteratorInit = Symbol("async iterator initialization steps"); +const asyncIteratorEOI = Symbol("async iterator end of iteration"); + +module.exports = exports = { + isObject, + hasOwn, + define, + newObjectInRealm, + wrapperSymbol, + implSymbol, + getSameObject, + ctorRegistrySymbol, + initCtorRegistry, + wrapperForImpl, + implForWrapper, + tryWrapperForImpl, + tryImplForWrapper, + iterInternalSymbol, + isArrayBuffer, + isArrayIndexPropName, + supportsPropertyIndex, + supportedPropertyIndices, + supportsPropertyName, + supportedPropertyNames, + indexedGet, + indexedSetNew, + indexedSetExisting, + namedGet, + namedSetNew, + namedSetExisting, + namedDelete, + asyncIteratorNext, + asyncIteratorReturn, + asyncIteratorInit, + asyncIteratorEOI, + iteratorResult +}; diff --git a/ts-ticket-office-service/node_modules/whatwg-url/package.json b/ts-ticket-office-service/node_modules/whatwg-url/package.json new file mode 100644 index 000000000..9cb209f9d --- /dev/null +++ b/ts-ticket-office-service/node_modules/whatwg-url/package.json @@ -0,0 +1,58 @@ +{ + "name": "whatwg-url", + "version": "11.0.0", + "description": "An implementation of the WHATWG URL Standard's URL API and parsing machinery", + "main": "index.js", + "files": [ + "index.js", + "webidl2js-wrapper.js", + "lib/*.js" + ], + "author": "Sebastian Mayr ", + "license": "MIT", + "repository": "jsdom/whatwg-url", + "dependencies": { + "tr46": "^3.0.0", + "webidl-conversions": "^7.0.0" + }, + "devDependencies": { + "@domenic/eslint-config": "^1.4.0", + "benchmark": "^2.1.4", + "browserify": "^17.0.0", + "domexception": "^4.0.0", + "eslint": "^7.32.0", + "got": "^11.8.2", + "jest": "^27.2.4", + "webidl2js": "^17.0.0" + }, + "engines": { + "node": ">=12" + }, + "scripts": { + "coverage": "jest --coverage", + "lint": "eslint .", + "prepare": "node scripts/transform.js", + "pretest": "node scripts/get-latest-platform-tests.js && node scripts/transform.js", + "build-live-viewer": "browserify index.js --standalone whatwgURL > live-viewer/whatwg-url.js", + "test": "jest" + }, + "jest": { + "collectCoverageFrom": [ + "lib/**/*.js", + "!lib/utils.js" + ], + "coverageDirectory": "coverage", + "coverageReporters": [ + "lcov", + "text-summary" + ], + "testEnvironment": "node", + "testMatch": [ + "/test/**/*.js" + ], + "testPathIgnorePatterns": [ + "^/test/testharness.js$", + "^/test/web-platform-tests/" + ] + } +} diff --git a/ts-ticket-office-service/node_modules/whatwg-url/webidl2js-wrapper.js b/ts-ticket-office-service/node_modules/whatwg-url/webidl2js-wrapper.js new file mode 100644 index 000000000..b731ace5f --- /dev/null +++ b/ts-ticket-office-service/node_modules/whatwg-url/webidl2js-wrapper.js @@ -0,0 +1,7 @@ +"use strict"; + +const URL = require("./lib/URL"); +const URLSearchParams = require("./lib/URLSearchParams"); + +exports.URL = URL; +exports.URLSearchParams = URLSearchParams; diff --git a/ts-ticket-office-service/node_modules/with/node_modules/.bin/acorn b/ts-ticket-office-service/node_modules/with/node_modules/.bin/acorn deleted file mode 100644 index 558ebb98b..000000000 --- a/ts-ticket-office-service/node_modules/with/node_modules/.bin/acorn +++ /dev/null @@ -1,15 +0,0 @@ -#!/bin/sh -basedir=$(dirname "$(echo "$0" | sed -e 's,\\,/,g')") - -case `uname` in - *CYGWIN*) basedir=`cygpath -w "$basedir"`;; -esac - -if [ -x "$basedir/node" ]; then - "$basedir/node" "$basedir/../acorn/bin/acorn" "$@" - ret=$? -else - node "$basedir/../acorn/bin/acorn" "$@" - ret=$? -fi -exit $ret diff --git a/ts-ticket-office-service/node_modules/with/node_modules/.bin/acorn b/ts-ticket-office-service/node_modules/with/node_modules/.bin/acorn new file mode 120000 index 000000000..cf7676038 --- /dev/null +++ b/ts-ticket-office-service/node_modules/with/node_modules/.bin/acorn @@ -0,0 +1 @@ +../acorn/bin/acorn \ No newline at end of file diff --git a/ts-ticket-office-service/node_modules/with/node_modules/acorn/bin/acorn b/ts-ticket-office-service/node_modules/with/node_modules/acorn/bin/acorn old mode 100644 new mode 100755 diff --git a/ts-ticket-office-service/package-lock.json b/ts-ticket-office-service/package-lock.json new file mode 100644 index 000000000..0767dc2f8 --- /dev/null +++ b/ts-ticket-office-service/package-lock.json @@ -0,0 +1,1937 @@ +{ + "name": "ts-ticket-office-service", + "version": "0.0.0", + "lockfileVersion": 2, + "requires": true, + "packages": { + "": { + "name": "ts-ticket-office-service", + "version": "0.0.0", + "dependencies": { + "body-parser": "~1.18.2", + "cookie-parser": "~1.4.3", + "debug": "~2.6.9", + "express": "~4.15.5", + "fs": "0.0.1-security", + "jade": "~1.11.0", + "mongo": "^0.1.0", + "morgan": "~1.9.0", + "mysql": "^2.18.1", + "serve-favicon": "~2.4.5" + } + }, + "node_modules/@types/node": { + "version": "18.6.1", + "resolved": "https://registry.npmjs.org/@types/node/-/node-18.6.1.tgz", + "integrity": "sha512-z+2vB6yDt1fNwKOeGbckpmirO+VBDuQqecXkgeIqDlaOtmKn6hPR/viQ8cxCfqLU4fTlvM3+YjM367TukWdxpg==" + }, + "node_modules/@types/webidl-conversions": { + "version": "6.1.1", + "resolved": "https://registry.npmjs.org/@types/webidl-conversions/-/webidl-conversions-6.1.1.tgz", + "integrity": "sha512-XAahCdThVuCFDQLT7R7Pk/vqeObFNL3YqRyFZg+AqAP/W1/w3xHaIxuW7WszQqTbIBOPRcItYJIou3i/mppu3Q==" + }, + "node_modules/@types/whatwg-url": { + "version": "8.2.2", + "resolved": "https://registry.npmjs.org/@types/whatwg-url/-/whatwg-url-8.2.2.tgz", + "integrity": "sha512-FtQu10RWgn3D9U4aazdwIE2yzphmTJREDqNdODHrbrZmmMqI0vMheC/6NE/J1Yveaj8H+ela+YwWTjq5PGmuhA==", + "dependencies": { + "@types/node": "*", + "@types/webidl-conversions": "*" + } + }, + "node_modules/accepts": { + "version": "1.3.4", + "license": "MIT", + "dependencies": { + "mime-types": "~2.1.16", + "negotiator": "0.6.1" + }, + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/acorn": { + "version": "2.7.0", + "license": "MIT", + "bin": { + "acorn": "bin/acorn" + }, + "engines": { + "node": ">=0.4.0" + } + }, + "node_modules/acorn-globals": { + "version": "1.0.9", + "license": "MIT", + "dependencies": { + "acorn": "^2.1.0" + } + }, + "node_modules/align-text": { + "version": "0.1.4", + "license": "MIT", + "dependencies": { + "kind-of": "^3.0.2", + "longest": "^1.0.1", + "repeat-string": "^1.5.2" + }, + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/amdefine": { + "version": "1.0.1", + "license": "BSD-3-Clause OR MIT", + "engines": { + "node": ">=0.4.2" + } + }, + "node_modules/array-flatten": { + "version": "1.1.1", + "license": "MIT" + }, + "node_modules/asap": { + "version": "1.0.0" + }, + "node_modules/base64-js": { + "version": "1.5.1", + "resolved": "https://registry.npmjs.org/base64-js/-/base64-js-1.5.1.tgz", + "integrity": "sha512-AKpaYlHn8t4SVbOHCy+b5+KKgvR4vrsD8vbvrbiQJps7fKDTkjkDry6ji0rUJjC0kzbNePLwzxq8iypo41qeWA==", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/feross" + }, + { + "type": "patreon", + "url": "https://www.patreon.com/feross" + }, + { + "type": "consulting", + "url": "https://feross.org/support" + } + ] + }, + "node_modules/basic-auth": { + "version": "2.0.0", + "license": "MIT", + "dependencies": { + "safe-buffer": "5.1.1" + }, + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/bignumber.js": { + "version": "9.0.0", + "resolved": "https://registry.npmjs.org/bignumber.js/-/bignumber.js-9.0.0.tgz", + "integrity": "sha512-t/OYhhJ2SD+YGBQcjY8GzzDHEk9f3nerxjtfa6tlMXfe7frs/WozhvCNoGvpM0P3bNf3Gq5ZRMlGr5f3r4/N8A==", + "engines": { + "node": "*" + } + }, + "node_modules/body-parser": { + "version": "1.18.2", + "license": "MIT", + "dependencies": { + "bytes": "3.0.0", + "content-type": "~1.0.4", + "debug": "2.6.9", + "depd": "~1.1.1", + "http-errors": "~1.6.2", + "iconv-lite": "0.4.19", + "on-finished": "~2.3.0", + "qs": "6.5.1", + "raw-body": "2.3.2", + "type-is": "~1.6.15" + }, + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/bson": { + "version": "4.6.5", + "resolved": "https://registry.npmjs.org/bson/-/bson-4.6.5.tgz", + "integrity": "sha512-uqrgcjyOaZsHfz7ea8zLRCLe1u+QGUSzMZmvXqO24CDW7DWoW1qiN9folSwa7hSneTSgM2ykDIzF5kcQQ8cwNw==", + "dependencies": { + "buffer": "^5.6.0" + }, + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/buffer": { + "version": "5.7.1", + "resolved": "https://registry.npmjs.org/buffer/-/buffer-5.7.1.tgz", + "integrity": "sha512-EHcyIPBQ4BSGlvjB16k5KgAJ27CIsHY/2JBmCRReo48y9rQ3MaUzWX3KVlBa4U7MyX02HdVj0K7C3WaB3ju7FQ==", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/feross" + }, + { + "type": "patreon", + "url": "https://www.patreon.com/feross" + }, + { + "type": "consulting", + "url": "https://feross.org/support" + } + ], + "dependencies": { + "base64-js": "^1.3.1", + "ieee754": "^1.1.13" + } + }, + "node_modules/bytes": { + "version": "3.0.0", + "license": "MIT", + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/camelcase": { + "version": "1.2.1", + "license": "MIT", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/center-align": { + "version": "0.1.3", + "license": "MIT", + "dependencies": { + "align-text": "^0.1.3", + "lazy-cache": "^1.0.3" + }, + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/character-parser": { + "version": "1.2.1", + "license": "MIT" + }, + "node_modules/clean-css": { + "version": "3.4.28", + "license": "MIT", + "dependencies": { + "commander": "2.8.x", + "source-map": "0.4.x" + }, + "bin": { + "cleancss": "bin/cleancss" + }, + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/clean-css/node_modules/commander": { + "version": "2.8.1", + "license": "MIT", + "dependencies": { + "graceful-readlink": ">= 1.0.0" + }, + "engines": { + "node": ">= 0.6.x" + } + }, + "node_modules/cliui": { + "version": "2.1.0", + "license": "ISC", + "dependencies": { + "center-align": "^0.1.1", + "right-align": "^0.1.1", + "wordwrap": "0.0.2" + } + }, + "node_modules/cliui/node_modules/wordwrap": { + "version": "0.0.2", + "license": "MIT/X11", + "engines": { + "node": ">=0.4.0" + } + }, + "node_modules/commander": { + "version": "2.6.0", + "license": "MIT", + "engines": { + "node": ">= 0.6.x" + } + }, + "node_modules/constantinople": { + "version": "3.0.2", + "license": "MIT", + "dependencies": { + "acorn": "^2.1.0" + } + }, + "node_modules/content-disposition": { + "version": "0.5.2", + "license": "MIT", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/content-type": { + "version": "1.0.4", + "license": "MIT", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/cookie": { + "version": "0.3.1", + "license": "MIT", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/cookie-parser": { + "version": "1.4.3", + "license": "MIT", + "dependencies": { + "cookie": "0.3.1", + "cookie-signature": "1.0.6" + }, + "engines": { + "node": ">= 0.8.0" + } + }, + "node_modules/cookie-signature": { + "version": "1.0.6", + "license": "MIT" + }, + "node_modules/core-util-is": { + "version": "1.0.2", + "license": "MIT" + }, + "node_modules/css": { + "version": "1.0.8", + "dependencies": { + "css-parse": "1.0.4", + "css-stringify": "1.0.5" + } + }, + "node_modules/css-parse": { + "version": "1.0.4" + }, + "node_modules/css-stringify": { + "version": "1.0.5" + }, + "node_modules/debug": { + "version": "2.6.9", + "license": "MIT", + "dependencies": { + "ms": "2.0.0" + } + }, + "node_modules/decamelize": { + "version": "1.2.0", + "license": "MIT", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/denque": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/denque/-/denque-2.1.0.tgz", + "integrity": "sha512-HVQE3AAb/pxF8fQAoiqpvg9i3evqug3hoiwakOyZAwJm+6vZehbkYXZ0l4JxS+I3QxM97v5aaRNhj8v5oBhekw==", + "engines": { + "node": ">=0.10" + } + }, + "node_modules/depd": { + "version": "1.1.1", + "license": "MIT", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/destroy": { + "version": "1.0.4", + "license": "MIT" + }, + "node_modules/ee-first": { + "version": "1.1.1", + "license": "MIT" + }, + "node_modules/encodeurl": { + "version": "1.0.1", + "license": "MIT", + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/escape-html": { + "version": "1.0.3", + "license": "MIT" + }, + "node_modules/etag": { + "version": "1.8.1", + "license": "MIT", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/express": { + "version": "4.15.5", + "license": "MIT", + "dependencies": { + "accepts": "~1.3.3", + "array-flatten": "1.1.1", + "content-disposition": "0.5.2", + "content-type": "~1.0.2", + "cookie": "0.3.1", + "cookie-signature": "1.0.6", + "debug": "2.6.9", + "depd": "~1.1.1", + "encodeurl": "~1.0.1", + "escape-html": "~1.0.3", + "etag": "~1.8.0", + "finalhandler": "~1.0.6", + "fresh": "0.5.2", + "merge-descriptors": "1.0.1", + "methods": "~1.1.2", + "on-finished": "~2.3.0", + "parseurl": "~1.3.1", + "path-to-regexp": "0.1.7", + "proxy-addr": "~1.1.5", + "qs": "6.5.0", + "range-parser": "~1.2.0", + "send": "0.15.6", + "serve-static": "1.12.6", + "setprototypeof": "1.0.3", + "statuses": "~1.3.1", + "type-is": "~1.6.15", + "utils-merge": "1.0.0", + "vary": "~1.1.1" + }, + "engines": { + "node": ">= 0.10.0" + } + }, + "node_modules/express/node_modules/qs": { + "version": "6.5.0", + "license": "BSD-3-Clause", + "engines": { + "node": ">=0.6" + } + }, + "node_modules/finalhandler": { + "version": "1.0.6", + "license": "MIT", + "dependencies": { + "debug": "2.6.9", + "encodeurl": "~1.0.1", + "escape-html": "~1.0.3", + "on-finished": "~2.3.0", + "parseurl": "~1.3.2", + "statuses": "~1.3.1", + "unpipe": "~1.0.0" + }, + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/forwarded": { + "version": "0.1.2", + "license": "MIT", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/fresh": { + "version": "0.5.2", + "license": "MIT", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/fs": { + "version": "0.0.1-security", + "license": "ISC" + }, + "node_modules/graceful-readlink": { + "version": "1.0.1", + "license": "MIT" + }, + "node_modules/http-errors": { + "version": "1.6.2", + "license": "MIT", + "dependencies": { + "depd": "1.1.1", + "inherits": "2.0.3", + "setprototypeof": "1.0.3", + "statuses": ">= 1.3.1 < 2" + }, + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/iconv-lite": { + "version": "0.4.19", + "license": "MIT", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/ieee754": { + "version": "1.2.1", + "resolved": "https://registry.npmjs.org/ieee754/-/ieee754-1.2.1.tgz", + "integrity": "sha512-dcyqhDvX1C46lXZcVqCpK+FtMRQVdIMN6/Df5js2zouUsqG7I6sFxitIC+7KYK29KdXOLHdu9zL4sFnoVQnqaA==", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/feross" + }, + { + "type": "patreon", + "url": "https://www.patreon.com/feross" + }, + { + "type": "consulting", + "url": "https://feross.org/support" + } + ] + }, + "node_modules/inherits": { + "version": "2.0.3", + "license": "ISC" + }, + "node_modules/ip": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/ip/-/ip-2.0.0.tgz", + "integrity": "sha512-WKa+XuLG1A1R0UWhl2+1XQSi+fZWMsYKffMZTTYsiZaUD8k2yDAj5atimTUD2TZkyCkNEeYE5NhFZmupOGtjYQ==" + }, + "node_modules/ipaddr.js": { + "version": "1.4.0", + "license": "MIT", + "engines": { + "node": ">= 0.10" + } + }, + "node_modules/is-buffer": { + "version": "1.1.5", + "license": "MIT" + }, + "node_modules/is-promise": { + "version": "2.1.0", + "license": "MIT" + }, + "node_modules/isarray": { + "version": "1.0.0", + "license": "MIT" + }, + "node_modules/jade": { + "version": "1.11.0", + "deprecated": "Jade has been renamed to pug, please install the latest version of pug instead of jade", + "license": "MIT", + "dependencies": { + "character-parser": "1.2.1", + "clean-css": "^3.1.9", + "commander": "~2.6.0", + "constantinople": "~3.0.1", + "jstransformer": "0.0.2", + "mkdirp": "~0.5.0", + "transformers": "2.1.0", + "uglify-js": "^2.4.19", + "void-elements": "~2.0.1", + "with": "~4.0.0" + }, + "bin": { + "jade": "bin/jade.js" + } + }, + "node_modules/jstransformer": { + "version": "0.0.2", + "license": "MIT", + "dependencies": { + "is-promise": "^2.0.0", + "promise": "^6.0.1" + } + }, + "node_modules/kind-of": { + "version": "3.2.2", + "license": "MIT", + "dependencies": { + "is-buffer": "^1.1.5" + }, + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/lazy-cache": { + "version": "1.0.4", + "license": "MIT", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/longest": { + "version": "1.0.1", + "license": "MIT", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/media-typer": { + "version": "0.3.0", + "license": "MIT", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/memory-pager": { + "version": "1.5.0", + "resolved": "https://registry.npmjs.org/memory-pager/-/memory-pager-1.5.0.tgz", + "integrity": "sha512-ZS4Bp4r/Zoeq6+NLJpP+0Zzm0pR8whtGPf1XExKLJBAczGMnSi3It14OiNCStjQjM6NU1okjQGSxgEZN8eBYKg==", + "optional": true + }, + "node_modules/merge-descriptors": { + "version": "1.0.1", + "license": "MIT" + }, + "node_modules/methods": { + "version": "1.1.2", + "license": "MIT", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/mime": { + "version": "1.3.4", + "bin": { + "mime": "cli.js" + } + }, + "node_modules/mime-db": { + "version": "1.30.0", + "license": "MIT", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/mime-types": { + "version": "2.1.17", + "license": "MIT", + "dependencies": { + "mime-db": "~1.30.0" + }, + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/minimist": { + "version": "1.2.6", + "resolved": "https://registry.npmjs.org/minimist/-/minimist-1.2.6.tgz", + "integrity": "sha512-Jsjnk4bw3YJqYzbdyBiNsPWHPfO++UGG749Cxs6peCu5Xg4nrena6OVxOYxrQTqww0Jmwt+Ref8rggumkTLz9Q==" + }, + "node_modules/mkdirp": { + "version": "0.5.6", + "resolved": "https://registry.npmjs.org/mkdirp/-/mkdirp-0.5.6.tgz", + "integrity": "sha512-FP+p8RB8OWpF3YZBCrP5gtADmtXApB5AMLn+vdyA+PyxCjrCs00mjyUozssO33cwDeT3wNGdLxJ5M//YqtHAJw==", + "dependencies": { + "minimist": "^1.2.6" + }, + "bin": { + "mkdirp": "bin/cmd.js" + } + }, + "node_modules/mongo": { + "version": "0.1.0", + "dependencies": { + "mongodb": "*" + }, + "engines": { + "node": ">= 0.4.0" + } + }, + "node_modules/mongodb": { + "version": "4.8.0", + "resolved": "https://registry.npmjs.org/mongodb/-/mongodb-4.8.0.tgz", + "integrity": "sha512-a0eVzm1e1kxwnzJV1wZXIS54KegM2y6wXTXOGTSAxr/E2YOUkl/zGBHNSI4z+6z+YQtVdzDqy1nJ4n5MxYJRnQ==", + "dependencies": { + "bson": "^4.6.5", + "denque": "^2.0.1", + "mongodb-connection-string-url": "^2.5.2", + "socks": "^2.6.2" + }, + "engines": { + "node": ">=12.9.0" + }, + "optionalDependencies": { + "saslprep": "^1.0.3" + } + }, + "node_modules/mongodb-connection-string-url": { + "version": "2.5.3", + "resolved": "https://registry.npmjs.org/mongodb-connection-string-url/-/mongodb-connection-string-url-2.5.3.tgz", + "integrity": "sha512-f+/WsED+xF4B74l3k9V/XkTVj5/fxFH2o5ToKXd8Iyi5UhM+sO9u0Ape17Mvl/GkZaFtM0HQnzAG5OTmhKw+tQ==", + "dependencies": { + "@types/whatwg-url": "^8.2.1", + "whatwg-url": "^11.0.0" + } + }, + "node_modules/morgan": { + "version": "1.9.1", + "resolved": "https://registry.npmjs.org/morgan/-/morgan-1.9.1.tgz", + "integrity": "sha512-HQStPIV4y3afTiCYVxirakhlCfGkI161c76kKFca7Fk1JusM//Qeo1ej2XaMniiNeaZklMVrh3vTtIzpzwbpmA==", + "dependencies": { + "basic-auth": "~2.0.0", + "debug": "2.6.9", + "depd": "~1.1.2", + "on-finished": "~2.3.0", + "on-headers": "~1.0.1" + }, + "engines": { + "node": ">= 0.8.0" + } + }, + "node_modules/morgan/node_modules/depd": { + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/depd/-/depd-1.1.2.tgz", + "integrity": "sha512-7emPTl6Dpo6JRXOXjLRxck+FlLRX5847cLKEn00PLAgc3g2hTZZgr+e4c2v6QpSmLeFP3n5yUo7ft6avBK/5jQ==", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/ms": { + "version": "2.0.0", + "license": "MIT" + }, + "node_modules/mysql": { + "version": "2.18.1", + "resolved": "https://registry.npmjs.org/mysql/-/mysql-2.18.1.tgz", + "integrity": "sha512-Bca+gk2YWmqp2Uf6k5NFEurwY/0td0cpebAucFpY/3jhrwrVGuxU2uQFCHjU19SJfje0yQvi+rVWdq78hR5lig==", + "dependencies": { + "bignumber.js": "9.0.0", + "readable-stream": "2.3.7", + "safe-buffer": "5.1.2", + "sqlstring": "2.3.1" + }, + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/mysql/node_modules/process-nextick-args": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/process-nextick-args/-/process-nextick-args-2.0.1.tgz", + "integrity": "sha512-3ouUOpQhtgrbOa17J7+uxOTpITYWaGP7/AhoR3+A+/1e9skrzelGi/dXzEYyvbxubEF6Wn2ypscTKiKJFFn1ag==" + }, + "node_modules/mysql/node_modules/readable-stream": { + "version": "2.3.7", + "resolved": "https://registry.npmjs.org/readable-stream/-/readable-stream-2.3.7.tgz", + "integrity": "sha512-Ebho8K4jIbHAxnuxi7o42OrZgF/ZTNcsZj6nRKyUmkhLFq8CHItp/fy6hQZuZmP/n3yZ9VBUbp4zz/mX8hmYPw==", + "dependencies": { + "core-util-is": "~1.0.0", + "inherits": "~2.0.3", + "isarray": "~1.0.0", + "process-nextick-args": "~2.0.0", + "safe-buffer": "~5.1.1", + "string_decoder": "~1.1.1", + "util-deprecate": "~1.0.1" + } + }, + "node_modules/mysql/node_modules/safe-buffer": { + "version": "5.1.2", + "resolved": "https://registry.npmjs.org/safe-buffer/-/safe-buffer-5.1.2.tgz", + "integrity": "sha512-Gd2UZBJDkXlY7GbJxfsE8/nvKkUEU1G38c1siN6QP6a9PT9MmHB8GnpscSmMJSoF8LOIrt8ud/wPtojys4G6+g==" + }, + "node_modules/mysql/node_modules/string_decoder": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/string_decoder/-/string_decoder-1.1.1.tgz", + "integrity": "sha512-n/ShnvDi6FHbbVfviro+WojiFzv+s8MPMHBczVePfUpDJLwoLT0ht1l4YwBCbi8pJAveEEdnkHyPyTP/mzRfwg==", + "dependencies": { + "safe-buffer": "~5.1.0" + } + }, + "node_modules/negotiator": { + "version": "0.6.1", + "license": "MIT", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/on-finished": { + "version": "2.3.0", + "license": "MIT", + "dependencies": { + "ee-first": "1.1.1" + }, + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/on-headers": { + "version": "1.0.1", + "license": "MIT", + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/optimist": { + "version": "0.3.7", + "license": "MIT/X11", + "dependencies": { + "wordwrap": "~0.0.2" + } + }, + "node_modules/parseurl": { + "version": "1.3.2", + "license": "MIT", + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/path-to-regexp": { + "version": "0.1.7", + "license": "MIT" + }, + "node_modules/promise": { + "version": "6.1.0", + "license": "MIT", + "dependencies": { + "asap": "~1.0.0" + } + }, + "node_modules/proxy-addr": { + "version": "1.1.5", + "license": "MIT", + "dependencies": { + "forwarded": "~0.1.0", + "ipaddr.js": "1.4.0" + }, + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/punycode": { + "version": "2.1.1", + "resolved": "https://registry.npmjs.org/punycode/-/punycode-2.1.1.tgz", + "integrity": "sha512-XRsRjdf+j5ml+y/6GKHPZbrF/8p2Yga0JPtdqTIY2Xe5ohJPD9saDJJLPvp9+NSBprVvevdXZybnj2cv8OEd0A==", + "engines": { + "node": ">=6" + } + }, + "node_modules/qs": { + "version": "6.5.1", + "license": "BSD-3-Clause", + "engines": { + "node": ">=0.6" + } + }, + "node_modules/range-parser": { + "version": "1.2.0", + "license": "MIT", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/raw-body": { + "version": "2.3.2", + "license": "MIT", + "dependencies": { + "bytes": "3.0.0", + "http-errors": "1.6.2", + "iconv-lite": "0.4.19", + "unpipe": "1.0.0" + }, + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/repeat-string": { + "version": "1.6.1", + "license": "MIT", + "engines": { + "node": ">=0.10" + } + }, + "node_modules/right-align": { + "version": "0.1.3", + "license": "MIT", + "dependencies": { + "align-text": "^0.1.1" + }, + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/safe-buffer": { + "version": "5.1.1", + "license": "MIT" + }, + "node_modules/saslprep": { + "version": "1.0.3", + "resolved": "https://registry.npmjs.org/saslprep/-/saslprep-1.0.3.tgz", + "integrity": "sha512-/MY/PEMbk2SuY5sScONwhUDsV2p77Znkb/q3nSVstq/yQzYJOH/Azh29p9oJLsl3LnQwSvZDKagDGBsBwSooag==", + "optional": true, + "dependencies": { + "sparse-bitfield": "^3.0.3" + }, + "engines": { + "node": ">=6" + } + }, + "node_modules/send": { + "version": "0.15.6", + "license": "MIT", + "dependencies": { + "debug": "2.6.9", + "depd": "~1.1.1", + "destroy": "~1.0.4", + "encodeurl": "~1.0.1", + "escape-html": "~1.0.3", + "etag": "~1.8.1", + "fresh": "0.5.2", + "http-errors": "~1.6.2", + "mime": "1.3.4", + "ms": "2.0.0", + "on-finished": "~2.3.0", + "range-parser": "~1.2.0", + "statuses": "~1.3.1" + }, + "engines": { + "node": ">= 0.8.0" + } + }, + "node_modules/serve-favicon": { + "version": "2.4.5", + "license": "MIT", + "dependencies": { + "etag": "~1.8.1", + "fresh": "0.5.2", + "ms": "2.0.0", + "parseurl": "~1.3.2", + "safe-buffer": "5.1.1" + }, + "engines": { + "node": ">= 0.8.0" + } + }, + "node_modules/serve-static": { + "version": "1.12.6", + "license": "MIT", + "dependencies": { + "encodeurl": "~1.0.1", + "escape-html": "~1.0.3", + "parseurl": "~1.3.2", + "send": "0.15.6" + }, + "engines": { + "node": ">= 0.8.0" + } + }, + "node_modules/setprototypeof": { + "version": "1.0.3", + "license": "ISC" + }, + "node_modules/smart-buffer": { + "version": "4.2.0", + "resolved": "https://registry.npmjs.org/smart-buffer/-/smart-buffer-4.2.0.tgz", + "integrity": "sha512-94hK0Hh8rPqQl2xXc3HsaBoOXKV20MToPkcXvwbISWLEs+64sBq5kFgn2kJDHb1Pry9yrP0dxrCI9RRci7RXKg==", + "engines": { + "node": ">= 6.0.0", + "npm": ">= 3.0.0" + } + }, + "node_modules/socks": { + "version": "2.7.0", + "resolved": "https://registry.npmjs.org/socks/-/socks-2.7.0.tgz", + "integrity": "sha512-scnOe9y4VuiNUULJN72GrM26BNOjVsfPXI+j+98PkyEfsIXroa5ofyjT+FzGvn/xHs73U2JtoBYAVx9Hl4quSA==", + "dependencies": { + "ip": "^2.0.0", + "smart-buffer": "^4.2.0" + }, + "engines": { + "node": ">= 10.13.0", + "npm": ">= 3.0.0" + } + }, + "node_modules/source-map": { + "version": "0.4.4", + "license": "BSD-3-Clause", + "dependencies": { + "amdefine": ">=0.0.4" + }, + "engines": { + "node": ">=0.8.0" + } + }, + "node_modules/sparse-bitfield": { + "version": "3.0.3", + "resolved": "https://registry.npmjs.org/sparse-bitfield/-/sparse-bitfield-3.0.3.tgz", + "integrity": "sha512-kvzhi7vqKTfkh0PZU+2D2PIllw2ymqJKujUcyPMd9Y75Nv4nPbGJZXNhxsgdQab2BmlDct1YnfQCguEvHr7VsQ==", + "optional": true, + "dependencies": { + "memory-pager": "^1.0.2" + } + }, + "node_modules/sqlstring": { + "version": "2.3.1", + "resolved": "https://registry.npmjs.org/sqlstring/-/sqlstring-2.3.1.tgz", + "integrity": "sha512-ooAzh/7dxIG5+uDik1z/Rd1vli0+38izZhGzSa34FwR7IbelPWCCKSNIl8jlL/F7ERvy8CB2jNeM1E9i9mXMAQ==", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/statuses": { + "version": "1.3.1", + "license": "MIT", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/tr46": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/tr46/-/tr46-3.0.0.tgz", + "integrity": "sha512-l7FvfAHlcmulp8kr+flpQZmVwtu7nfRV7NZujtN0OqES8EL4O4e0qqzL0DC5gAvx/ZC/9lk6rhcUwYvkBnBnYA==", + "dependencies": { + "punycode": "^2.1.1" + }, + "engines": { + "node": ">=12" + } + }, + "node_modules/transformers": { + "version": "2.1.0", + "deprecated": "Deprecated, use jstransformer", + "license": "MIT", + "dependencies": { + "css": "~1.0.8", + "promise": "~2.0", + "uglify-js": "~2.2.5" + } + }, + "node_modules/transformers/node_modules/is-promise": { + "version": "1.0.1", + "license": "MIT" + }, + "node_modules/transformers/node_modules/promise": { + "version": "2.0.0", + "license": "MIT", + "dependencies": { + "is-promise": "~1" + } + }, + "node_modules/transformers/node_modules/source-map": { + "version": "0.1.43", + "dependencies": { + "amdefine": ">=0.0.4" + }, + "engines": { + "node": ">=0.8.0" + } + }, + "node_modules/transformers/node_modules/uglify-js": { + "version": "2.2.5", + "dependencies": { + "optimist": "~0.3.5", + "source-map": "~0.1.7" + }, + "bin": { + "uglifyjs": "bin/uglifyjs" + }, + "engines": { + "node": ">=0.4.0" + } + }, + "node_modules/type-is": { + "version": "1.6.15", + "license": "MIT", + "dependencies": { + "media-typer": "0.3.0", + "mime-types": "~2.1.15" + }, + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/uglify-js": { + "version": "2.8.29", + "license": "BSD-2-Clause", + "dependencies": { + "source-map": "~0.5.1", + "yargs": "~3.10.0" + }, + "bin": { + "uglifyjs": "bin/uglifyjs" + }, + "engines": { + "node": ">=0.8.0" + }, + "optionalDependencies": { + "uglify-to-browserify": "~1.0.0" + } + }, + "node_modules/uglify-js/node_modules/source-map": { + "version": "0.5.7", + "license": "BSD-3-Clause", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/uglify-to-browserify": { + "version": "1.0.2", + "license": "MIT", + "optional": true + }, + "node_modules/unpipe": { + "version": "1.0.0", + "license": "MIT", + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/util-deprecate": { + "version": "1.0.2", + "license": "MIT" + }, + "node_modules/utils-merge": { + "version": "1.0.0", + "engines": { + "node": ">= 0.4.0" + } + }, + "node_modules/vary": { + "version": "1.1.2", + "license": "MIT", + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/void-elements": { + "version": "2.0.1", + "license": "MIT", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/webidl-conversions": { + "version": "7.0.0", + "resolved": "https://registry.npmjs.org/webidl-conversions/-/webidl-conversions-7.0.0.tgz", + "integrity": "sha512-VwddBukDzu71offAQR975unBIGqfKZpM+8ZX6ySk8nYhVoo5CYaZyzt3YBvYtRtO+aoGlqxPg/B87NGVZ/fu6g==", + "engines": { + "node": ">=12" + } + }, + "node_modules/whatwg-url": { + "version": "11.0.0", + "resolved": "https://registry.npmjs.org/whatwg-url/-/whatwg-url-11.0.0.tgz", + "integrity": "sha512-RKT8HExMpoYx4igMiVMY83lN6UeITKJlBQ+vR/8ZJ8OCdSiN3RwCq+9gH0+Xzj0+5IrM6i4j/6LuvzbZIQgEcQ==", + "dependencies": { + "tr46": "^3.0.0", + "webidl-conversions": "^7.0.0" + }, + "engines": { + "node": ">=12" + } + }, + "node_modules/window-size": { + "version": "0.1.0", + "engines": { + "node": ">= 0.8.0" + } + }, + "node_modules/with": { + "version": "4.0.3", + "license": "MIT", + "dependencies": { + "acorn": "^1.0.1", + "acorn-globals": "^1.0.3" + } + }, + "node_modules/with/node_modules/acorn": { + "version": "1.2.2", + "license": "MIT", + "bin": { + "acorn": "bin/acorn" + }, + "engines": { + "node": ">=0.4.0" + } + }, + "node_modules/wordwrap": { + "version": "0.0.3", + "license": "MIT", + "engines": { + "node": ">=0.4.0" + } + }, + "node_modules/yargs": { + "version": "3.10.0", + "license": "MIT", + "dependencies": { + "camelcase": "^1.0.2", + "cliui": "^2.1.0", + "decamelize": "^1.0.0", + "window-size": "0.1.0" + } + } + }, + "dependencies": { + "@types/node": { + "version": "18.6.1", + "resolved": "https://registry.npmjs.org/@types/node/-/node-18.6.1.tgz", + "integrity": "sha512-z+2vB6yDt1fNwKOeGbckpmirO+VBDuQqecXkgeIqDlaOtmKn6hPR/viQ8cxCfqLU4fTlvM3+YjM367TukWdxpg==" + }, + "@types/webidl-conversions": { + "version": "6.1.1", + "resolved": "https://registry.npmjs.org/@types/webidl-conversions/-/webidl-conversions-6.1.1.tgz", + "integrity": "sha512-XAahCdThVuCFDQLT7R7Pk/vqeObFNL3YqRyFZg+AqAP/W1/w3xHaIxuW7WszQqTbIBOPRcItYJIou3i/mppu3Q==" + }, + "@types/whatwg-url": { + "version": "8.2.2", + "resolved": "https://registry.npmjs.org/@types/whatwg-url/-/whatwg-url-8.2.2.tgz", + "integrity": "sha512-FtQu10RWgn3D9U4aazdwIE2yzphmTJREDqNdODHrbrZmmMqI0vMheC/6NE/J1Yveaj8H+ela+YwWTjq5PGmuhA==", + "requires": { + "@types/node": "*", + "@types/webidl-conversions": "*" + } + }, + "accepts": { + "version": "1.3.4", + "requires": { + "mime-types": "~2.1.16", + "negotiator": "0.6.1" + } + }, + "acorn": { + "version": "2.7.0" + }, + "acorn-globals": { + "version": "1.0.9", + "requires": { + "acorn": "^2.1.0" + } + }, + "align-text": { + "version": "0.1.4", + "requires": { + "kind-of": "^3.0.2", + "longest": "^1.0.1", + "repeat-string": "^1.5.2" + } + }, + "amdefine": { + "version": "1.0.1" + }, + "array-flatten": { + "version": "1.1.1" + }, + "asap": { + "version": "1.0.0" + }, + "base64-js": { + "version": "1.5.1", + "resolved": "https://registry.npmjs.org/base64-js/-/base64-js-1.5.1.tgz", + "integrity": "sha512-AKpaYlHn8t4SVbOHCy+b5+KKgvR4vrsD8vbvrbiQJps7fKDTkjkDry6ji0rUJjC0kzbNePLwzxq8iypo41qeWA==" + }, + "basic-auth": { + "version": "2.0.0", + "requires": { + "safe-buffer": "5.1.1" + } + }, + "bignumber.js": { + "version": "9.0.0", + "resolved": "https://registry.npmjs.org/bignumber.js/-/bignumber.js-9.0.0.tgz", + "integrity": "sha512-t/OYhhJ2SD+YGBQcjY8GzzDHEk9f3nerxjtfa6tlMXfe7frs/WozhvCNoGvpM0P3bNf3Gq5ZRMlGr5f3r4/N8A==" + }, + "body-parser": { + "version": "1.18.2", + "requires": { + "bytes": "3.0.0", + "content-type": "~1.0.4", + "debug": "2.6.9", + "depd": "~1.1.1", + "http-errors": "~1.6.2", + "iconv-lite": "0.4.19", + "on-finished": "~2.3.0", + "qs": "6.5.1", + "raw-body": "2.3.2", + "type-is": "~1.6.15" + } + }, + "bson": { + "version": "4.6.5", + "resolved": "https://registry.npmjs.org/bson/-/bson-4.6.5.tgz", + "integrity": "sha512-uqrgcjyOaZsHfz7ea8zLRCLe1u+QGUSzMZmvXqO24CDW7DWoW1qiN9folSwa7hSneTSgM2ykDIzF5kcQQ8cwNw==", + "requires": { + "buffer": "^5.6.0" + } + }, + "buffer": { + "version": "5.7.1", + "resolved": "https://registry.npmjs.org/buffer/-/buffer-5.7.1.tgz", + "integrity": "sha512-EHcyIPBQ4BSGlvjB16k5KgAJ27CIsHY/2JBmCRReo48y9rQ3MaUzWX3KVlBa4U7MyX02HdVj0K7C3WaB3ju7FQ==", + "requires": { + "base64-js": "^1.3.1", + "ieee754": "^1.1.13" + } + }, + "bytes": { + "version": "3.0.0" + }, + "camelcase": { + "version": "1.2.1" + }, + "center-align": { + "version": "0.1.3", + "requires": { + "align-text": "^0.1.3", + "lazy-cache": "^1.0.3" + } + }, + "character-parser": { + "version": "1.2.1" + }, + "clean-css": { + "version": "3.4.28", + "requires": { + "commander": "2.8.x", + "source-map": "0.4.x" + }, + "dependencies": { + "commander": { + "version": "2.8.1", + "requires": { + "graceful-readlink": ">= 1.0.0" + } + } + } + }, + "cliui": { + "version": "2.1.0", + "requires": { + "center-align": "^0.1.1", + "right-align": "^0.1.1", + "wordwrap": "0.0.2" + }, + "dependencies": { + "wordwrap": { + "version": "0.0.2" + } + } + }, + "commander": { + "version": "2.6.0" + }, + "constantinople": { + "version": "3.0.2", + "requires": { + "acorn": "^2.1.0" + } + }, + "content-disposition": { + "version": "0.5.2" + }, + "content-type": { + "version": "1.0.4" + }, + "cookie": { + "version": "0.3.1" + }, + "cookie-parser": { + "version": "1.4.3", + "requires": { + "cookie": "0.3.1", + "cookie-signature": "1.0.6" + } + }, + "cookie-signature": { + "version": "1.0.6" + }, + "core-util-is": { + "version": "1.0.2" + }, + "css": { + "version": "1.0.8", + "requires": { + "css-parse": "1.0.4", + "css-stringify": "1.0.5" + } + }, + "css-parse": { + "version": "1.0.4" + }, + "css-stringify": { + "version": "1.0.5" + }, + "debug": { + "version": "2.6.9", + "requires": { + "ms": "2.0.0" + } + }, + "decamelize": { + "version": "1.2.0" + }, + "denque": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/denque/-/denque-2.1.0.tgz", + "integrity": "sha512-HVQE3AAb/pxF8fQAoiqpvg9i3evqug3hoiwakOyZAwJm+6vZehbkYXZ0l4JxS+I3QxM97v5aaRNhj8v5oBhekw==" + }, + "depd": { + "version": "1.1.1" + }, + "destroy": { + "version": "1.0.4" + }, + "ee-first": { + "version": "1.1.1" + }, + "encodeurl": { + "version": "1.0.1" + }, + "escape-html": { + "version": "1.0.3" + }, + "etag": { + "version": "1.8.1" + }, + "express": { + "version": "4.15.5", + "requires": { + "accepts": "~1.3.3", + "array-flatten": "1.1.1", + "content-disposition": "0.5.2", + "content-type": "~1.0.2", + "cookie": "0.3.1", + "cookie-signature": "1.0.6", + "debug": "2.6.9", + "depd": "~1.1.1", + "encodeurl": "~1.0.1", + "escape-html": "~1.0.3", + "etag": "~1.8.0", + "finalhandler": "~1.0.6", + "fresh": "0.5.2", + "merge-descriptors": "1.0.1", + "methods": "~1.1.2", + "on-finished": "~2.3.0", + "parseurl": "~1.3.1", + "path-to-regexp": "0.1.7", + "proxy-addr": "~1.1.5", + "qs": "6.5.0", + "range-parser": "~1.2.0", + "send": "0.15.6", + "serve-static": "1.12.6", + "setprototypeof": "1.0.3", + "statuses": "~1.3.1", + "type-is": "~1.6.15", + "utils-merge": "1.0.0", + "vary": "~1.1.1" + }, + "dependencies": { + "qs": { + "version": "6.5.0" + } + } + }, + "finalhandler": { + "version": "1.0.6", + "requires": { + "debug": "2.6.9", + "encodeurl": "~1.0.1", + "escape-html": "~1.0.3", + "on-finished": "~2.3.0", + "parseurl": "~1.3.2", + "statuses": "~1.3.1", + "unpipe": "~1.0.0" + } + }, + "forwarded": { + "version": "0.1.2" + }, + "fresh": { + "version": "0.5.2" + }, + "fs": { + "version": "0.0.1-security" + }, + "graceful-readlink": { + "version": "1.0.1" + }, + "http-errors": { + "version": "1.6.2", + "requires": { + "depd": "1.1.1", + "inherits": "2.0.3", + "setprototypeof": "1.0.3", + "statuses": ">= 1.3.1 < 2" + } + }, + "iconv-lite": { + "version": "0.4.19" + }, + "ieee754": { + "version": "1.2.1", + "resolved": "https://registry.npmjs.org/ieee754/-/ieee754-1.2.1.tgz", + "integrity": "sha512-dcyqhDvX1C46lXZcVqCpK+FtMRQVdIMN6/Df5js2zouUsqG7I6sFxitIC+7KYK29KdXOLHdu9zL4sFnoVQnqaA==" + }, + "inherits": { + "version": "2.0.3" + }, + "ip": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/ip/-/ip-2.0.0.tgz", + "integrity": "sha512-WKa+XuLG1A1R0UWhl2+1XQSi+fZWMsYKffMZTTYsiZaUD8k2yDAj5atimTUD2TZkyCkNEeYE5NhFZmupOGtjYQ==" + }, + "ipaddr.js": { + "version": "1.4.0" + }, + "is-buffer": { + "version": "1.1.5" + }, + "is-promise": { + "version": "2.1.0" + }, + "isarray": { + "version": "1.0.0" + }, + "jade": { + "version": "1.11.0", + "requires": { + "character-parser": "1.2.1", + "clean-css": "^3.1.9", + "commander": "~2.6.0", + "constantinople": "~3.0.1", + "jstransformer": "0.0.2", + "mkdirp": "~0.5.0", + "transformers": "2.1.0", + "uglify-js": "^2.4.19", + "void-elements": "~2.0.1", + "with": "~4.0.0" + } + }, + "jstransformer": { + "version": "0.0.2", + "requires": { + "is-promise": "^2.0.0", + "promise": "^6.0.1" + } + }, + "kind-of": { + "version": "3.2.2", + "requires": { + "is-buffer": "^1.1.5" + } + }, + "lazy-cache": { + "version": "1.0.4" + }, + "longest": { + "version": "1.0.1" + }, + "media-typer": { + "version": "0.3.0" + }, + "memory-pager": { + "version": "1.5.0", + "resolved": "https://registry.npmjs.org/memory-pager/-/memory-pager-1.5.0.tgz", + "integrity": "sha512-ZS4Bp4r/Zoeq6+NLJpP+0Zzm0pR8whtGPf1XExKLJBAczGMnSi3It14OiNCStjQjM6NU1okjQGSxgEZN8eBYKg==", + "optional": true + }, + "merge-descriptors": { + "version": "1.0.1" + }, + "methods": { + "version": "1.1.2" + }, + "mime": { + "version": "1.3.4" + }, + "mime-db": { + "version": "1.30.0" + }, + "mime-types": { + "version": "2.1.17", + "requires": { + "mime-db": "~1.30.0" + } + }, + "minimist": { + "version": "1.2.6", + "resolved": "https://registry.npmjs.org/minimist/-/minimist-1.2.6.tgz", + "integrity": "sha512-Jsjnk4bw3YJqYzbdyBiNsPWHPfO++UGG749Cxs6peCu5Xg4nrena6OVxOYxrQTqww0Jmwt+Ref8rggumkTLz9Q==" + }, + "mkdirp": { + "version": "0.5.6", + "resolved": "https://registry.npmjs.org/mkdirp/-/mkdirp-0.5.6.tgz", + "integrity": "sha512-FP+p8RB8OWpF3YZBCrP5gtADmtXApB5AMLn+vdyA+PyxCjrCs00mjyUozssO33cwDeT3wNGdLxJ5M//YqtHAJw==", + "requires": { + "minimist": "^1.2.6" + } + }, + "mongo": { + "version": "0.1.0", + "requires": { + "mongodb": "*" + } + }, + "mongodb": { + "version": "4.8.0", + "resolved": "https://registry.npmjs.org/mongodb/-/mongodb-4.8.0.tgz", + "integrity": "sha512-a0eVzm1e1kxwnzJV1wZXIS54KegM2y6wXTXOGTSAxr/E2YOUkl/zGBHNSI4z+6z+YQtVdzDqy1nJ4n5MxYJRnQ==", + "requires": { + "bson": "^4.6.5", + "denque": "^2.0.1", + "mongodb-connection-string-url": "^2.5.2", + "saslprep": "^1.0.3", + "socks": "^2.6.2" + } + }, + "mongodb-connection-string-url": { + "version": "2.5.3", + "resolved": "https://registry.npmjs.org/mongodb-connection-string-url/-/mongodb-connection-string-url-2.5.3.tgz", + "integrity": "sha512-f+/WsED+xF4B74l3k9V/XkTVj5/fxFH2o5ToKXd8Iyi5UhM+sO9u0Ape17Mvl/GkZaFtM0HQnzAG5OTmhKw+tQ==", + "requires": { + "@types/whatwg-url": "^8.2.1", + "whatwg-url": "^11.0.0" + } + }, + "morgan": { + "version": "1.9.1", + "resolved": "https://registry.npmjs.org/morgan/-/morgan-1.9.1.tgz", + "integrity": "sha512-HQStPIV4y3afTiCYVxirakhlCfGkI161c76kKFca7Fk1JusM//Qeo1ej2XaMniiNeaZklMVrh3vTtIzpzwbpmA==", + "requires": { + "basic-auth": "~2.0.0", + "debug": "2.6.9", + "depd": "~1.1.2", + "on-finished": "~2.3.0", + "on-headers": "~1.0.1" + }, + "dependencies": { + "depd": { + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/depd/-/depd-1.1.2.tgz", + "integrity": "sha512-7emPTl6Dpo6JRXOXjLRxck+FlLRX5847cLKEn00PLAgc3g2hTZZgr+e4c2v6QpSmLeFP3n5yUo7ft6avBK/5jQ==" + } + } + }, + "ms": { + "version": "2.0.0" + }, + "mysql": { + "version": "2.18.1", + "resolved": "https://registry.npmjs.org/mysql/-/mysql-2.18.1.tgz", + "integrity": "sha512-Bca+gk2YWmqp2Uf6k5NFEurwY/0td0cpebAucFpY/3jhrwrVGuxU2uQFCHjU19SJfje0yQvi+rVWdq78hR5lig==", + "requires": { + "bignumber.js": "9.0.0", + "readable-stream": "2.3.7", + "safe-buffer": "5.1.2", + "sqlstring": "2.3.1" + }, + "dependencies": { + "process-nextick-args": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/process-nextick-args/-/process-nextick-args-2.0.1.tgz", + "integrity": "sha512-3ouUOpQhtgrbOa17J7+uxOTpITYWaGP7/AhoR3+A+/1e9skrzelGi/dXzEYyvbxubEF6Wn2ypscTKiKJFFn1ag==" + }, + "readable-stream": { + "version": "2.3.7", + "resolved": "https://registry.npmjs.org/readable-stream/-/readable-stream-2.3.7.tgz", + "integrity": "sha512-Ebho8K4jIbHAxnuxi7o42OrZgF/ZTNcsZj6nRKyUmkhLFq8CHItp/fy6hQZuZmP/n3yZ9VBUbp4zz/mX8hmYPw==", + "requires": { + "core-util-is": "~1.0.0", + "inherits": "~2.0.3", + "isarray": "~1.0.0", + "process-nextick-args": "~2.0.0", + "safe-buffer": "~5.1.1", + "string_decoder": "~1.1.1", + "util-deprecate": "~1.0.1" + } + }, + "safe-buffer": { + "version": "5.1.2", + "resolved": "https://registry.npmjs.org/safe-buffer/-/safe-buffer-5.1.2.tgz", + "integrity": "sha512-Gd2UZBJDkXlY7GbJxfsE8/nvKkUEU1G38c1siN6QP6a9PT9MmHB8GnpscSmMJSoF8LOIrt8ud/wPtojys4G6+g==" + }, + "string_decoder": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/string_decoder/-/string_decoder-1.1.1.tgz", + "integrity": "sha512-n/ShnvDi6FHbbVfviro+WojiFzv+s8MPMHBczVePfUpDJLwoLT0ht1l4YwBCbi8pJAveEEdnkHyPyTP/mzRfwg==", + "requires": { + "safe-buffer": "~5.1.0" + } + } + } + }, + "negotiator": { + "version": "0.6.1" + }, + "on-finished": { + "version": "2.3.0", + "requires": { + "ee-first": "1.1.1" + } + }, + "on-headers": { + "version": "1.0.1" + }, + "optimist": { + "version": "0.3.7", + "requires": { + "wordwrap": "~0.0.2" + } + }, + "parseurl": { + "version": "1.3.2" + }, + "path-to-regexp": { + "version": "0.1.7" + }, + "promise": { + "version": "6.1.0", + "requires": { + "asap": "~1.0.0" + } + }, + "proxy-addr": { + "version": "1.1.5", + "requires": { + "forwarded": "~0.1.0", + "ipaddr.js": "1.4.0" + } + }, + "punycode": { + "version": "2.1.1", + "resolved": "https://registry.npmjs.org/punycode/-/punycode-2.1.1.tgz", + "integrity": "sha512-XRsRjdf+j5ml+y/6GKHPZbrF/8p2Yga0JPtdqTIY2Xe5ohJPD9saDJJLPvp9+NSBprVvevdXZybnj2cv8OEd0A==" + }, + "qs": { + "version": "6.5.1" + }, + "range-parser": { + "version": "1.2.0" + }, + "raw-body": { + "version": "2.3.2", + "requires": { + "bytes": "3.0.0", + "http-errors": "1.6.2", + "iconv-lite": "0.4.19", + "unpipe": "1.0.0" + } + }, + "repeat-string": { + "version": "1.6.1" + }, + "right-align": { + "version": "0.1.3", + "requires": { + "align-text": "^0.1.1" + } + }, + "safe-buffer": { + "version": "5.1.1" + }, + "saslprep": { + "version": "1.0.3", + "resolved": "https://registry.npmjs.org/saslprep/-/saslprep-1.0.3.tgz", + "integrity": "sha512-/MY/PEMbk2SuY5sScONwhUDsV2p77Znkb/q3nSVstq/yQzYJOH/Azh29p9oJLsl3LnQwSvZDKagDGBsBwSooag==", + "optional": true, + "requires": { + "sparse-bitfield": "^3.0.3" + } + }, + "send": { + "version": "0.15.6", + "requires": { + "debug": "2.6.9", + "depd": "~1.1.1", + "destroy": "~1.0.4", + "encodeurl": "~1.0.1", + "escape-html": "~1.0.3", + "etag": "~1.8.1", + "fresh": "0.5.2", + "http-errors": "~1.6.2", + "mime": "1.3.4", + "ms": "2.0.0", + "on-finished": "~2.3.0", + "range-parser": "~1.2.0", + "statuses": "~1.3.1" + } + }, + "serve-favicon": { + "version": "2.4.5", + "requires": { + "etag": "~1.8.1", + "fresh": "0.5.2", + "ms": "2.0.0", + "parseurl": "~1.3.2", + "safe-buffer": "5.1.1" + } + }, + "serve-static": { + "version": "1.12.6", + "requires": { + "encodeurl": "~1.0.1", + "escape-html": "~1.0.3", + "parseurl": "~1.3.2", + "send": "0.15.6" + } + }, + "setprototypeof": { + "version": "1.0.3" + }, + "smart-buffer": { + "version": "4.2.0", + "resolved": "https://registry.npmjs.org/smart-buffer/-/smart-buffer-4.2.0.tgz", + "integrity": "sha512-94hK0Hh8rPqQl2xXc3HsaBoOXKV20MToPkcXvwbISWLEs+64sBq5kFgn2kJDHb1Pry9yrP0dxrCI9RRci7RXKg==" + }, + "socks": { + "version": "2.7.0", + "resolved": "https://registry.npmjs.org/socks/-/socks-2.7.0.tgz", + "integrity": "sha512-scnOe9y4VuiNUULJN72GrM26BNOjVsfPXI+j+98PkyEfsIXroa5ofyjT+FzGvn/xHs73U2JtoBYAVx9Hl4quSA==", + "requires": { + "ip": "^2.0.0", + "smart-buffer": "^4.2.0" + } + }, + "source-map": { + "version": "0.4.4", + "requires": { + "amdefine": ">=0.0.4" + } + }, + "sparse-bitfield": { + "version": "3.0.3", + "resolved": "https://registry.npmjs.org/sparse-bitfield/-/sparse-bitfield-3.0.3.tgz", + "integrity": "sha512-kvzhi7vqKTfkh0PZU+2D2PIllw2ymqJKujUcyPMd9Y75Nv4nPbGJZXNhxsgdQab2BmlDct1YnfQCguEvHr7VsQ==", + "optional": true, + "requires": { + "memory-pager": "^1.0.2" + } + }, + "sqlstring": { + "version": "2.3.1", + "resolved": "https://registry.npmjs.org/sqlstring/-/sqlstring-2.3.1.tgz", + "integrity": "sha512-ooAzh/7dxIG5+uDik1z/Rd1vli0+38izZhGzSa34FwR7IbelPWCCKSNIl8jlL/F7ERvy8CB2jNeM1E9i9mXMAQ==" + }, + "statuses": { + "version": "1.3.1" + }, + "tr46": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/tr46/-/tr46-3.0.0.tgz", + "integrity": "sha512-l7FvfAHlcmulp8kr+flpQZmVwtu7nfRV7NZujtN0OqES8EL4O4e0qqzL0DC5gAvx/ZC/9lk6rhcUwYvkBnBnYA==", + "requires": { + "punycode": "^2.1.1" + } + }, + "transformers": { + "version": "2.1.0", + "requires": { + "css": "~1.0.8", + "promise": "~2.0", + "uglify-js": "~2.2.5" + }, + "dependencies": { + "is-promise": { + "version": "1.0.1" + }, + "promise": { + "version": "2.0.0", + "requires": { + "is-promise": "~1" + } + }, + "source-map": { + "version": "0.1.43", + "requires": { + "amdefine": ">=0.0.4" + } + }, + "uglify-js": { + "version": "2.2.5", + "requires": { + "optimist": "~0.3.5", + "source-map": "~0.1.7" + } + } + } + }, + "type-is": { + "version": "1.6.15", + "requires": { + "media-typer": "0.3.0", + "mime-types": "~2.1.15" + } + }, + "uglify-js": { + "version": "2.8.29", + "requires": { + "source-map": "~0.5.1", + "uglify-to-browserify": "~1.0.0", + "yargs": "~3.10.0" + }, + "dependencies": { + "source-map": { + "version": "0.5.7" + } + } + }, + "uglify-to-browserify": { + "version": "1.0.2", + "optional": true + }, + "unpipe": { + "version": "1.0.0" + }, + "util-deprecate": { + "version": "1.0.2" + }, + "utils-merge": { + "version": "1.0.0" + }, + "vary": { + "version": "1.1.2" + }, + "void-elements": { + "version": "2.0.1" + }, + "webidl-conversions": { + "version": "7.0.0", + "resolved": "https://registry.npmjs.org/webidl-conversions/-/webidl-conversions-7.0.0.tgz", + "integrity": "sha512-VwddBukDzu71offAQR975unBIGqfKZpM+8ZX6ySk8nYhVoo5CYaZyzt3YBvYtRtO+aoGlqxPg/B87NGVZ/fu6g==" + }, + "whatwg-url": { + "version": "11.0.0", + "resolved": "https://registry.npmjs.org/whatwg-url/-/whatwg-url-11.0.0.tgz", + "integrity": "sha512-RKT8HExMpoYx4igMiVMY83lN6UeITKJlBQ+vR/8ZJ8OCdSiN3RwCq+9gH0+Xzj0+5IrM6i4j/6LuvzbZIQgEcQ==", + "requires": { + "tr46": "^3.0.0", + "webidl-conversions": "^7.0.0" + } + }, + "window-size": { + "version": "0.1.0" + }, + "with": { + "version": "4.0.3", + "requires": { + "acorn": "^1.0.1", + "acorn-globals": "^1.0.3" + }, + "dependencies": { + "acorn": { + "version": "1.2.2" + } + } + }, + "wordwrap": { + "version": "0.0.3" + }, + "yargs": { + "version": "3.10.0", + "requires": { + "camelcase": "^1.0.2", + "cliui": "^2.1.0", + "decamelize": "^1.0.0", + "window-size": "0.1.0" + } + } + } +} diff --git a/ts-ticket-office-service/package.json b/ts-ticket-office-service/package.json index dcca618b9..206c0fbc9 100644 --- a/ts-ticket-office-service/package.json +++ b/ts-ticket-office-service/package.json @@ -14,6 +14,7 @@ "jade": "~1.11.0", "mongo": "^0.1.0", "morgan": "~1.9.0", + "mysql": "^2.18.1", "serve-favicon": "~2.4.5" } } diff --git a/ts-ticket-office-service/test.sh b/ts-ticket-office-service/test.sh new file mode 100755 index 000000000..d22a54b85 --- /dev/null +++ b/ts-ticket-office-service/test.sh @@ -0,0 +1,21 @@ + +curl -X POST -H "content-type: application/json" \ + http://127.0.0.1:16108/office/updateOffice \ + -d '{"province": "shanghai", "city":"shanghai", "region": "Pudong New Area", + "oldOfficeName": "test1", + "newOffice": { + "name": "test2", + "address": "address1", + "workTime": "0800-18:00", + "windowNum": 3}}' + +# curl -X POST -H "content-type: application/json" \ +# http://127.0.0.1:16108/office/addOffice \ +# -d '{"province": "shanghai", "city":"shanghai", "region": "Pudong New Area", +# "office": { +# "name": "test2", +# "address": "address1", +# "workTime": "0800-18:00", +# "windowNum": 3}}' + +#curl -X POST -H "content-type: application/json" -H "'Encodeing':'utf8'" http://127.0.0.1:16108/office/getSpecificOffices -d '{"province": "shanghai", "city":"shanghai", "region": "Pudong New Area"}' \ No newline at end of file diff --git a/ts-ticketinfo-service/src/main/java/ticketinfo/controller/TicketInfoController.java b/ts-ticketinfo-service/src/main/java/ticketinfo/controller/TicketInfoController.java deleted file mode 100644 index 762c02a30..000000000 --- a/ts-ticketinfo-service/src/main/java/ticketinfo/controller/TicketInfoController.java +++ /dev/null @@ -1,46 +0,0 @@ -package ticketinfo.controller; - -/** - * Created by Chenjie Xu on 2017/6/6. - */ - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.http.HttpEntity; -import org.springframework.http.HttpHeaders; -import org.springframework.web.bind.annotation.*; -import ticketinfo.entity.Travel; -import ticketinfo.service.TicketInfoService; - -import static org.springframework.http.ResponseEntity.ok; - -@RestController -@RequestMapping("/api/v1/ticketinfoservice") -public class TicketInfoController { - - @Autowired - TicketInfoService service; - - private static final Logger LOGGER = LoggerFactory.getLogger(TicketInfoController.class); - - @GetMapping(path = "/welcome") - public String home() { - return "Welcome to [ TicketInfo Service ] !"; - } - - @PostMapping(value = "/ticketinfo") - public HttpEntity queryForTravel(@RequestBody Travel info, @RequestHeader HttpHeaders headers) { - // TravelResult - TicketInfoController.LOGGER.info("Query ticket info for travel,Start: {},End: {}",info.getStartingPlace(),info.getEndPlace()); - return ok(service.queryForTravel(info, headers)); - } - - @GetMapping(value = "/ticketinfo/{name}") - public HttpEntity queryForStationId(@PathVariable String name, @RequestHeader HttpHeaders headers) { - // String id - TicketInfoController.LOGGER.info("Query ticket info for station id,Name: {}",name); - return ok(service.queryForStationId(name, headers)); - } - -} diff --git a/ts-ticketinfo-service/src/main/java/ticketinfo/entity/TrainType.java b/ts-ticketinfo-service/src/main/java/ticketinfo/entity/TrainType.java deleted file mode 100644 index e4a3069e8..000000000 --- a/ts-ticketinfo-service/src/main/java/ticketinfo/entity/TrainType.java +++ /dev/null @@ -1,25 +0,0 @@ -package ticketinfo.entity; - -import lombok.Data; - -@Data -public class TrainType { - - private String id; - - private int economyClass; - private int confortClass; - - private int averageSpeed; - - public TrainType(){ - - } - - public TrainType(String id, int economyClass, int confortClass) { - this.id = id; - this.economyClass = economyClass; - this.confortClass = confortClass; - } - -} diff --git a/ts-ticketinfo-service/src/main/java/ticketinfo/entity/Travel.java b/ts-ticketinfo-service/src/main/java/ticketinfo/entity/Travel.java deleted file mode 100644 index ed0f5284d..000000000 --- a/ts-ticketinfo-service/src/main/java/ticketinfo/entity/Travel.java +++ /dev/null @@ -1,22 +0,0 @@ -package ticketinfo.entity; - -import lombok.Data; - -import java.util.Date; - -@Data -public class Travel { - - private Trip trip; - - private String startingPlace; - - private String endPlace; - - private Date departureTime; - - public Travel(){ - //Default Constructor - } - -} diff --git a/ts-ticketinfo-service/src/main/java/ticketinfo/entity/TravelResult.java b/ts-ticketinfo-service/src/main/java/ticketinfo/entity/TravelResult.java deleted file mode 100644 index cb65cac69..000000000 --- a/ts-ticketinfo-service/src/main/java/ticketinfo/entity/TravelResult.java +++ /dev/null @@ -1,23 +0,0 @@ -package ticketinfo.entity; - -import java.util.Map; -import lombok.*; - -@Data -public class TravelResult { - - private boolean status; - - private double percent; - - private TrainType trainType; - - private Map prices; - - private String message; - - public TravelResult(){ - //Default Constructor - } - -} diff --git a/ts-ticketinfo-service/src/main/java/ticketinfo/entity/Trip.java b/ts-ticketinfo-service/src/main/java/ticketinfo/entity/Trip.java deleted file mode 100644 index 2787efb62..000000000 --- a/ts-ticketinfo-service/src/main/java/ticketinfo/entity/Trip.java +++ /dev/null @@ -1,70 +0,0 @@ -package ticketinfo.entity; - -import lombok.Data; - -import javax.validation.Valid; -import javax.validation.constraints.NotNull; -import java.util.Date; - -@Data -public class Trip { - @Valid - private TripId tripId; - - @Valid - @NotNull - private String trainTypeId; - - private String routeId; - - //-------------------------------The following variables are temporarily disabled----------------------- - @Valid - @NotNull - private String startingStationId; - - //Intermediate stops. In the initial version, there was only one stop, that is, only one stop and one terminal. In the later version, the stops were expanded to several stops. - @Valid - private String stationsId; - - @Valid - @NotNull - private String terminalStationId; - - @Valid - @NotNull - private Date startingTime; - - @Valid - @NotNull - private Date endTime; - - public Trip(TripId tripId, String trainTypeId, String startingStationId, String stationsId, String terminalStationId, Date startingTime, Date endTime) { - this.tripId = tripId; - this.trainTypeId = trainTypeId; - this.startingStationId = startingStationId; - this.stationsId = stationsId; - this.terminalStationId = terminalStationId; - this.startingTime = startingTime; - this.endTime = endTime; - } - - public Trip(TripId tripId, String trainTypeId, String routeId) { - this.tripId = tripId; - this.trainTypeId = trainTypeId; - this.routeId = routeId; - this.startingStationId = ""; - this.terminalStationId = ""; - this.startingTime = new Date(); - this.endTime = new Date(); - } - - public Trip(){ - //Default Constructor - this.trainTypeId = ""; - this.startingStationId = ""; - this.terminalStationId = ""; - this.startingTime = new Date(); - this.endTime = new Date(); - } - -} diff --git a/ts-ticketinfo-service/src/main/java/ticketinfo/entity/TripId.java b/ts-ticketinfo-service/src/main/java/ticketinfo/entity/TripId.java deleted file mode 100644 index 6286cddab..000000000 --- a/ts-ticketinfo-service/src/main/java/ticketinfo/entity/TripId.java +++ /dev/null @@ -1,40 +0,0 @@ -package ticketinfo.entity; - -import lombok.Data; - -import java.io.Serializable; - -@Data -public class TripId implements Serializable{ - private Type type; - private String number; - - - public TripId(){ - //Default Constructor - } - - public TripId(String trainNumber){ - char type0 = trainNumber.charAt(0); - switch(type0){ - case 'G': this.type = Type.G; - break; - case 'D': this.type = Type.D; - break; - case 'Z': this.type = Type.Z; - break; - case 'T': this.type = Type.T; - break; - case 'K': this.type = Type.K; - break; - default:break; - } - - this.number = trainNumber.substring(1); - } - - @Override - public String toString(){ - return type.getName() + number; - } -} diff --git a/ts-ticketinfo-service/src/main/java/ticketinfo/entity/Type.java b/ts-ticketinfo-service/src/main/java/ticketinfo/entity/Type.java deleted file mode 100644 index 536a5ab51..000000000 --- a/ts-ticketinfo-service/src/main/java/ticketinfo/entity/Type.java +++ /dev/null @@ -1,41 +0,0 @@ -package ticketinfo.entity; - -import java.io.Serializable; - - -public enum Type implements Serializable{ - G("G", 1), D("D", 2),Z("Z",3), T("T", 4), K("K", 5); - - private String name; - private int index; - - Type(String name, int index) { - this.name = name; - this.index = index; - } - - public static String getName(int index) { - for (Type type : Type.values()) { - if (type.getIndex() == index) { - return type.name; - } - } - return null; - } - - public String getName() { - return name; - } - - void setName(String name) { - this.name = name; - } - - public int getIndex() { - return index; - } - - void setIndex(int index) { - this.index = index; - } -} diff --git a/ts-ticketinfo-service/src/main/java/ticketinfo/service/TicketInfoService.java b/ts-ticketinfo-service/src/main/java/ticketinfo/service/TicketInfoService.java deleted file mode 100644 index 64922ce24..000000000 --- a/ts-ticketinfo-service/src/main/java/ticketinfo/service/TicketInfoService.java +++ /dev/null @@ -1,13 +0,0 @@ -package ticketinfo.service; - -import edu.fudan.common.util.Response; -import org.springframework.http.HttpHeaders; -import ticketinfo.entity.Travel; - -/** - * Created by Chenjie Xu on 2017/6/6. - */ -public interface TicketInfoService { - Response queryForTravel(Travel info, HttpHeaders headers); - Response queryForStationId(String name,HttpHeaders headers); -} diff --git a/ts-ticketinfo-service/src/main/java/ticketinfo/service/TicketInfoServiceImpl.java b/ts-ticketinfo-service/src/main/java/ticketinfo/service/TicketInfoServiceImpl.java deleted file mode 100644 index b5ef2c3bc..000000000 --- a/ts-ticketinfo-service/src/main/java/ticketinfo/service/TicketInfoServiceImpl.java +++ /dev/null @@ -1,44 +0,0 @@ -package ticketinfo.service; - -import edu.fudan.common.util.Response; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.http.HttpEntity; -import org.springframework.http.HttpHeaders; -import org.springframework.http.HttpMethod; -import org.springframework.http.ResponseEntity; -import org.springframework.stereotype.Service; -import org.springframework.web.client.RestTemplate; -import ticketinfo.entity.Travel; - -/** - * Created by Chenjie Xu on 2017/6/6. - */ -@Service -public class TicketInfoServiceImpl implements TicketInfoService { - - @Autowired - private RestTemplate restTemplate; - - @Override - public Response queryForTravel(Travel info, HttpHeaders headers) { - HttpEntity requestEntity = new HttpEntity(info, null); - ResponseEntity re = restTemplate.exchange( - "http://ts-basic-service:15680/api/v1/basicservice/basic/travel", - HttpMethod.POST, - requestEntity, - Response.class); - return re.getBody(); - } - - @Override - public Response queryForStationId(String name, HttpHeaders headers) { - HttpEntity requestEntity = new HttpEntity(null); - ResponseEntity re = restTemplate.exchange( - "http://ts-basic-service:15680/api/v1/basicservice/basic/" + name, - HttpMethod.GET, - requestEntity, - Response.class); - - return re.getBody(); - } -} diff --git a/ts-ticketinfo-service/src/main/resources/application.yml b/ts-ticketinfo-service/src/main/resources/application.yml deleted file mode 100644 index 804588808..000000000 --- a/ts-ticketinfo-service/src/main/resources/application.yml +++ /dev/null @@ -1,11 +0,0 @@ -# HTTP Server -server: - port: 15681 # HTTP (Tomcat) port - -spring: - application: - name: ts-ticketinfo-service - - -swagger: - controllerPackage: ticketinfo.controller \ No newline at end of file diff --git a/ts-ticketinfo-service/src/test/java/ticketinfo/controller/TicketInfoControllerTest.java b/ts-ticketinfo-service/src/test/java/ticketinfo/controller/TicketInfoControllerTest.java deleted file mode 100644 index 65691dfdc..000000000 --- a/ts-ticketinfo-service/src/test/java/ticketinfo/controller/TicketInfoControllerTest.java +++ /dev/null @@ -1,66 +0,0 @@ -package ticketinfo.controller; - -import com.alibaba.fastjson.JSONObject; -import edu.fudan.common.util.Response; -import org.junit.Assert; -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.JUnit4; -import org.mockito.InjectMocks; -import org.mockito.Mock; -import org.mockito.Mockito; -import org.mockito.MockitoAnnotations; -import org.springframework.http.*; -import org.springframework.test.web.servlet.MockMvc; -import org.springframework.test.web.servlet.request.MockMvcRequestBuilders; -import org.springframework.test.web.servlet.result.MockMvcResultMatchers; -import org.springframework.test.web.servlet.setup.MockMvcBuilders; -import ticketinfo.entity.Travel; -import ticketinfo.service.TicketInfoService; - -@RunWith(JUnit4.class) -public class TicketInfoControllerTest { - - @InjectMocks - private TicketInfoController ticketInfoController; - - @Mock - private TicketInfoService service; - private MockMvc mockMvc; - private Response response = new Response(); - - @Before - public void setUp() { - MockitoAnnotations.initMocks(this); - mockMvc = MockMvcBuilders.standaloneSetup(ticketInfoController).build(); - } - - @Test - public void testHome() throws Exception { - mockMvc.perform(MockMvcRequestBuilders.get("/api/v1/ticketinfoservice/welcome")) - .andExpect(MockMvcResultMatchers.status().isOk()) - .andExpect(MockMvcResultMatchers.content().string("Welcome to [ TicketInfo Service ] !")); - } - - @Test - public void testQueryForTravel() throws Exception { - Travel info = new Travel(); - Mockito.when(service.queryForTravel(Mockito.any(Travel.class), Mockito.any(HttpHeaders.class))).thenReturn(response); - String requestJson = JSONObject.toJSONString(info); - String result = mockMvc.perform(MockMvcRequestBuilders.post("/api/v1/ticketinfoservice/ticketinfo").contentType(MediaType.APPLICATION_JSON).content(requestJson)) - .andExpect(MockMvcResultMatchers.status().isOk()) - .andReturn().getResponse().getContentAsString(); - Assert.assertEquals(response, JSONObject.parseObject(result, Response.class)); - } - - @Test - public void testQueryForStationId() throws Exception { - Mockito.when(service.queryForStationId(Mockito.anyString(), Mockito.any(HttpHeaders.class))).thenReturn(response); - String result = mockMvc.perform(MockMvcRequestBuilders.get("/api/v1/ticketinfoservice/ticketinfo/name")) - .andExpect(MockMvcResultMatchers.status().isOk()) - .andReturn().getResponse().getContentAsString(); - Assert.assertEquals(response, JSONObject.parseObject(result, Response.class)); - } - -} diff --git a/ts-ticketinfo-service/src/test/java/ticketinfo/service/TicketInfoServiceImplTest.java b/ts-ticketinfo-service/src/test/java/ticketinfo/service/TicketInfoServiceImplTest.java deleted file mode 100644 index 36fce2d6a..000000000 --- a/ts-ticketinfo-service/src/test/java/ticketinfo/service/TicketInfoServiceImplTest.java +++ /dev/null @@ -1,62 +0,0 @@ -package ticketinfo.service; - -import edu.fudan.common.util.Response; -import org.junit.Assert; -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.JUnit4; -import org.mockito.InjectMocks; -import org.mockito.Mock; -import org.mockito.Mockito; -import org.mockito.MockitoAnnotations; -import org.springframework.http.*; -import org.springframework.web.client.RestTemplate; -import ticketinfo.entity.Travel; - -@RunWith(JUnit4.class) -public class TicketInfoServiceImplTest { - - @InjectMocks - private TicketInfoServiceImpl ticketInfoServiceImpl; - - @Mock - private RestTemplate restTemplate; - - private HttpHeaders headers = new HttpHeaders(); - - @Before - public void setUp() { - MockitoAnnotations.initMocks(this); - } - - @Test - public void testQueryForTravel() { - Travel info = new Travel(); - HttpEntity requestEntity = new HttpEntity(info, headers); - Response response = new Response(); - ResponseEntity re = new ResponseEntity<>(response, HttpStatus.OK); - Mockito.when(restTemplate.exchange( - "http://ts-basic-service:15680/api/v1/basicservice/basic/travel", - HttpMethod.POST, - requestEntity, - Response.class)).thenReturn(re); - Response result = ticketInfoServiceImpl.queryForTravel(info, headers); - Assert.assertEquals(new Response<>(null, null, null), result); - } - - @Test - public void testQueryForStationId() { - HttpEntity requestEntity = new HttpEntity(headers); - Response response = new Response(); - ResponseEntity re = new ResponseEntity<>(response, HttpStatus.OK); - Mockito.when( restTemplate.exchange( - "http://ts-basic-service:15680/api/v1/basicservice/basic/name", - HttpMethod.GET, - requestEntity, - Response.class)).thenReturn(re); - Response result = ticketInfoServiceImpl.queryForStationId("name", headers); - Assert.assertEquals(new Response<>(null, null, null), result); - } - -} diff --git a/ts-ticketinfo-service/Dockerfile b/ts-train-food-service/Dockerfile similarity index 50% rename from ts-ticketinfo-service/Dockerfile rename to ts-train-food-service/Dockerfile index 01d178c1d..de3c56173 100644 --- a/ts-ticketinfo-service/Dockerfile +++ b/ts-train-food-service/Dockerfile @@ -2,7 +2,7 @@ FROM java:8-jre RUN /bin/cp /usr/share/zoneinfo/Asia/Shanghai /etc/localtime && echo 'Asia/Shanghai' >/etc/timezone -ADD ./target/ts-ticketinfo-service-1.0.jar /app/ -CMD ["java", "-Xmx200m", "-jar", "/app/ts-ticketinfo-service-1.0.jar"] +ADD ./target/ts-train-food-service-1.0.jar /app/ +CMD ["java", "-Xmx200m", "-jar", "/app/ts-train-food-service-1.0.jar"] -EXPOSE 15681 \ No newline at end of file +EXPOSE 19999 diff --git a/ts-food-map-service/pom.xml b/ts-train-food-service/pom.xml similarity index 75% rename from ts-food-map-service/pom.xml rename to ts-train-food-service/pom.xml index ec47a24b7..f3bfef953 100644 --- a/ts-food-map-service/pom.xml +++ b/ts-train-food-service/pom.xml @@ -5,17 +5,38 @@ 4.0.0 fdse.microservice - ts-food-map-service + ts-train-food-service 1.0 + + + org.springframework.boot + spring-boot-starter-data-jpa + + + org.services + ts-common + 0.1.0 + + + mysql + mysql-connector-java + runtime + + + jakarta.validation + jakarta.validation-api + + + jar - ts-food-map-service + ts-train-food-service org.services ts-service 0.1.0 - ../ + ../pom.xml @@ -23,28 +44,6 @@ 1.8 - - - org.springframework.boot - spring-boot-starter-web - - - org.springframework.boot - spring-boot-starter-data-mongodb - - - org.springframework.boot - spring-boot-starter-actuator - - - org.services - ts-common - 0.1.0 - - - - - @@ -54,5 +53,4 @@ - \ No newline at end of file diff --git a/ts-train-food-service/src/main/java/trainFood/TrainFoodApplication.java b/ts-train-food-service/src/main/java/trainFood/TrainFoodApplication.java new file mode 100644 index 000000000..4c3813ca6 --- /dev/null +++ b/ts-train-food-service/src/main/java/trainFood/TrainFoodApplication.java @@ -0,0 +1,31 @@ +package trainFood; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.boot.web.client.RestTemplateBuilder; +import org.springframework.cloud.client.discovery.EnableDiscoveryClient; +import org.springframework.cloud.client.loadbalancer.LoadBalanced; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.EnableAspectJAutoProxy; +import org.springframework.integration.annotation.IntegrationComponentScan; +import org.springframework.scheduling.annotation.EnableAsync; +import org.springframework.web.client.RestTemplate; +import springfox.documentation.swagger2.annotations.EnableSwagger2; + +@SpringBootApplication +@EnableAspectJAutoProxy(proxyTargetClass = true) +@EnableAsync +@IntegrationComponentScan +@EnableSwagger2 +@EnableDiscoveryClient +public class TrainFoodApplication { + + public static void main(String[] args) { + SpringApplication.run(TrainFoodApplication.class, args); + } + @LoadBalanced + @Bean + public RestTemplate restTemplate(RestTemplateBuilder builder) { + return builder.build(); + } +} diff --git a/ts-ticketinfo-service/src/main/java/ticketinfo/config/SecurityConfig.java b/ts-train-food-service/src/main/java/trainFood/config/SecurityConfig.java similarity index 96% rename from ts-ticketinfo-service/src/main/java/ticketinfo/config/SecurityConfig.java rename to ts-train-food-service/src/main/java/trainFood/config/SecurityConfig.java index a00158bc7..086192308 100644 --- a/ts-ticketinfo-service/src/main/java/ticketinfo/config/SecurityConfig.java +++ b/ts-train-food-service/src/main/java/trainFood/config/SecurityConfig.java @@ -1,4 +1,4 @@ -package ticketinfo.config; +package trainFood.config; import edu.fudan.common.security.jwt.JWTFilter; import org.springframework.context.annotation.Bean; @@ -61,7 +61,7 @@ protected void configure(HttpSecurity httpSecurity) throws Exception { .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS) .and() .authorizeRequests() - .antMatchers("/api/v1/ticketinfoservice/**").permitAll() + .antMatchers("/api/v1/trainfoodservice/**").permitAll() .antMatchers("/swagger-ui.html", "/webjars/**", "/images/**", "/configuration/**", "/swagger-resources/**", "/v2/**").permitAll() .anyRequest().authenticated() diff --git a/ts-food-map-service/src/main/java/food/controller/TrainFoodController.java b/ts-train-food-service/src/main/java/trainFood/controller/TrainFoodController.java similarity index 79% rename from ts-food-map-service/src/main/java/food/controller/TrainFoodController.java rename to ts-train-food-service/src/main/java/trainFood/controller/TrainFoodController.java index e67eb603d..b7802175a 100644 --- a/ts-food-map-service/src/main/java/food/controller/TrainFoodController.java +++ b/ts-train-food-service/src/main/java/trainFood/controller/TrainFoodController.java @@ -1,21 +1,21 @@ -package food.controller; +package trainFood.controller; -import food.service.FoodMapService; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpEntity; import org.springframework.http.HttpHeaders; import org.springframework.web.bind.annotation.*; +import trainFood.service.TrainFoodService; import static org.springframework.http.ResponseEntity.ok; @RestController -@RequestMapping("/api/v1/foodmapservice") +@RequestMapping("/api/v1/trainfoodservice") public class TrainFoodController { @Autowired - FoodMapService foodMapService; + TrainFoodService trainFoodService; private static final Logger LOGGER = LoggerFactory.getLogger(TrainFoodController.class); @@ -28,13 +28,13 @@ public String home() { @GetMapping("/trainfoods") public HttpEntity getAllTrainFood(@RequestHeader HttpHeaders headers) { TrainFoodController.LOGGER.info("[Food Map Service][Get All TrainFoods]"); - return ok(foodMapService.listTrainFood(headers)); + return ok(trainFoodService.listTrainFood(headers)); } @CrossOrigin(origins = "*") @GetMapping("/trainfoods/{tripId}") public HttpEntity getTrainFoodOfTrip(@PathVariable String tripId, @RequestHeader HttpHeaders headers) { TrainFoodController.LOGGER.info("[Food Map Service][Get TrainFoods By TripId]"); - return ok(foodMapService.listTrainFoodByTripId(tripId, headers)); + return ok(trainFoodService.listTrainFoodByTripId(tripId, headers)); } } diff --git a/ts-train-food-service/src/main/java/trainFood/entity/TrainFood.java b/ts-train-food-service/src/main/java/trainFood/entity/TrainFood.java new file mode 100644 index 000000000..11ee09a8f --- /dev/null +++ b/ts-train-food-service/src/main/java/trainFood/entity/TrainFood.java @@ -0,0 +1,38 @@ +package trainFood.entity; + +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import edu.fudan.common.entity.Food; +import lombok.Data; +import org.hibernate.annotations.GenericGenerator; + +import javax.persistence.*; +import javax.validation.Valid; +import javax.validation.constraints.NotNull; +import java.util.List; +import java.util.UUID; + +@Data +@Entity +@GenericGenerator(name = "jpa-uuid", strategy = "org.hibernate.id.UUIDGenerator") +@JsonIgnoreProperties(ignoreUnknown = true) +public class TrainFood { + + @Id + @GeneratedValue(generator = "jpa-uuid") + @Column(length = 36) + private String id; + + @NotNull + @Column(unique = true) + private String tripId; + + @ElementCollection(targetClass = Food.class) + @CollectionTable(name = "train_food_list", joinColumns = @JoinColumn(name = "trip_id")) + private List foodList; + + public TrainFood(){ + //Default Constructor + this.tripId = ""; + } + +} diff --git a/ts-train-food-service/src/main/java/trainFood/init/InitData.java b/ts-train-food-service/src/main/java/trainFood/init/InitData.java new file mode 100644 index 000000000..635e8e813 --- /dev/null +++ b/ts-train-food-service/src/main/java/trainFood/init/InitData.java @@ -0,0 +1,67 @@ +package trainFood.init; + +import edu.fudan.common.entity.Food; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.CommandLineRunner; +import org.springframework.stereotype.Component; +import trainFood.entity.TrainFood; +import trainFood.service.TrainFoodService; + +import java.io.BufferedReader; +import java.io.InputStreamReader; +import java.util.ArrayList; +import java.util.List; +import java.util.UUID; + +@Component +public class InitData implements CommandLineRunner{ + + @Autowired + TrainFoodService trainFoodService; + + private static final Logger LOGGER = LoggerFactory.getLogger(InitData.class); + + + @Override + public void run(String... args) throws Exception { + BufferedReader br2 = new BufferedReader(new InputStreamReader(this.getClass().getResourceAsStream("/trainfood.txt"))); + try{ + String line2 = br2.readLine(); + while( line2 != null ){ + if( !line2.trim().equals("") ){ + TrainFood tf = new TrainFood(); + tf.setId(UUID.randomUUID().toString()); + String[] lineTemp = line2.trim().split("="); + tf.setTripId(lineTemp[1]); + lineTemp = br2.readLine().trim().split("="); + tf.setFoodList(toFoodList(lineTemp[1])); + trainFoodService.createTrainFood(tf,null); + } + line2 = br2.readLine(); + } + + } catch(Exception e){ + InitData.LOGGER.info("the trainfood.txt has format error!"); + InitData.LOGGER.error(e.getMessage()); + System.exit(1); + } + } + + private List toFoodList(String s){ + InitData.LOGGER.info("s= {}", s); + String[] foodstring = s.split("_"); + List foodList = new ArrayList<>(); + for(int i = 0; i< foodstring.length; i++){ + String[] foodTemp = foodstring[i].split(","); + Food food = new Food(); + food.setFoodName(foodTemp[0]); + + food.setPrice(Double.parseDouble(foodTemp[1])); + + foodList.add(food); + } + return foodList; + } +} diff --git a/ts-train-food-service/src/main/java/trainFood/repository/TrainFoodRepository.java b/ts-train-food-service/src/main/java/trainFood/repository/TrainFoodRepository.java new file mode 100644 index 000000000..36dee76b6 --- /dev/null +++ b/ts-train-food-service/src/main/java/trainFood/repository/TrainFoodRepository.java @@ -0,0 +1,22 @@ +package trainFood.repository; + +import org.springframework.data.repository.CrudRepository; +import org.springframework.stereotype.Repository; +import trainFood.entity.TrainFood; + +import java.util.List; +import java.util.UUID; + +@Repository +public interface TrainFoodRepository extends CrudRepository { + + TrainFood findById(UUID id); + + @Override + List findAll(); + + + TrainFood findByTripId(String tripId); + + void deleteById(UUID id); +} diff --git a/ts-train-food-service/src/main/java/trainFood/service/TrainFoodService.java b/ts-train-food-service/src/main/java/trainFood/service/TrainFoodService.java new file mode 100644 index 000000000..a448ce7a5 --- /dev/null +++ b/ts-train-food-service/src/main/java/trainFood/service/TrainFoodService.java @@ -0,0 +1,13 @@ +package trainFood.service; + +import edu.fudan.common.util.Response; +import org.springframework.http.HttpHeaders; +import trainFood.entity.*; + +public interface TrainFoodService { + TrainFood createTrainFood(TrainFood tf, HttpHeaders headers); + + Response listTrainFood(HttpHeaders headers); + + Response listTrainFoodByTripId(String tripId, HttpHeaders headers); +} diff --git a/ts-train-food-service/src/main/java/trainFood/service/TrainFoodServiceImpl.java b/ts-train-food-service/src/main/java/trainFood/service/TrainFoodServiceImpl.java new file mode 100644 index 000000000..5943a23c9 --- /dev/null +++ b/ts-train-food-service/src/main/java/trainFood/service/TrainFoodServiceImpl.java @@ -0,0 +1,61 @@ +package trainFood.service; + +import edu.fudan.common.util.Response; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.http.HttpHeaders; +import org.springframework.stereotype.Service; +import trainFood.entity.*; +import trainFood.repository.TrainFoodRepository; + +import java.util.List; + +@Service +public class TrainFoodServiceImpl implements TrainFoodService{ + + @Autowired + TrainFoodRepository trainFoodRepository; + + private static final Logger LOGGER = LoggerFactory.getLogger(TrainFoodServiceImpl.class); + + String success = "Success"; + String noContent = "No content"; + + @Override + public TrainFood createTrainFood(TrainFood tf, HttpHeaders headers) { + TrainFood tfTemp = trainFoodRepository.findByTripId(tf.getTripId()); + if (tfTemp != null) { + if(tfTemp.getFoodList().equals(tf.getFoodList())){ + TrainFoodServiceImpl.LOGGER.error("[Init TrainFood] Already Exists TripId: {}", tf.getTripId()); + }else{ + tfTemp.setFoodList(tf.getFoodList()); + trainFoodRepository.save(tfTemp); + } + } else { + trainFoodRepository.save(tf); + } + return tf; + } + + @Override + public Response listTrainFood(HttpHeaders headers) { + List trainFoodList = trainFoodRepository.findAll(); + if (trainFoodList != null && !trainFoodList.isEmpty()) { + return new Response<>(1, success, trainFoodList); + } else { + TrainFoodServiceImpl.LOGGER.error("List train food error: {}", noContent); + return new Response<>(0, noContent, null); + } + } + + @Override + public Response listTrainFoodByTripId(String tripId, HttpHeaders headers) { + TrainFood tf = trainFoodRepository.findByTripId(tripId); + if(tf == null){ + return new Response<>(0, noContent, null); + }else{ + return new Response<>(1, success, tf.getFoodList()); + } + } +} diff --git a/ts-train-food-service/src/main/resources/application.yml b/ts-train-food-service/src/main/resources/application.yml new file mode 100644 index 000000000..ce57be7e8 --- /dev/null +++ b/ts-train-food-service/src/main/resources/application.yml @@ -0,0 +1,25 @@ +server: + port: 19999 + +spring: + cloud: + nacos: + discovery: + server-addr: ${NACOS_ADDRS:nacos-0.nacos-headless.default.svc.cluster.local,nacos-1.nacos-headless.default.svc.cluster.local,nacos-2.nacos-headless.default.svc.cluster.local} + application: + name: ts-train-food-service + datasource: + url: jdbc:mysql://${TRAIN_FOOD_MYSQL_HOST:ts-train-food-mysql}:${TRAIN_FOOD_MYSQL_PORT:3306}/${TRAIN_FOOD_MYSQL_DATABASE:ts-train-food-mysql}?useSSL=false + username: ${TRAIN_FOOD_MYSQL_USER:root} + password: ${TRAIN_FOOD_MYSQL_PASSWORD:root} + driver-class-name: com.mysql.cj.jdbc.Driver + + jpa: + hibernate: + ddl-auto: update + properties: + hibernate: + dialect: org.hibernate.dialect.MySQL5Dialect + +swagger: + controllerPackage: trainFood.controller \ No newline at end of file diff --git a/ts-food-map-service/src/main/resources/trainfood.txt b/ts-train-food-service/src/main/resources/trainfood.txt similarity index 100% rename from ts-food-map-service/src/main/resources/trainfood.txt rename to ts-train-food-service/src/main/resources/trainfood.txt diff --git a/ts-train-service/pom.xml b/ts-train-service/pom.xml index d4e2ff2dc..9ddec2128 100644 --- a/ts-train-service/pom.xml +++ b/ts-train-service/pom.xml @@ -15,7 +15,7 @@ org.services ts-service 0.1.0 - ../ + ../pom.xml @@ -24,19 +24,28 @@ + + + + org.springframework.boot - spring-boot-starter-data-mongodb + spring-boot-starter-data-jpa + + + mysql + mysql-connector-java org.services ts-common 0.1.0 - - + + jakarta.validation + jakarta.validation-api + - diff --git a/ts-train-service/src/main/java/train/TrainApplication.java b/ts-train-service/src/main/java/train/TrainApplication.java index 4148755fc..e69943285 100644 --- a/ts-train-service/src/main/java/train/TrainApplication.java +++ b/ts-train-service/src/main/java/train/TrainApplication.java @@ -2,9 +2,14 @@ import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.boot.web.client.RestTemplateBuilder; +import org.springframework.cloud.client.discovery.EnableDiscoveryClient; +import org.springframework.cloud.client.loadbalancer.LoadBalanced; +import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.EnableAspectJAutoProxy; import org.springframework.integration.annotation.IntegrationComponentScan; import org.springframework.scheduling.annotation.EnableAsync; +import org.springframework.web.client.RestTemplate; import springfox.documentation.swagger2.annotations.EnableSwagger2; @SpringBootApplication @@ -12,10 +17,16 @@ @EnableAsync @IntegrationComponentScan @EnableSwagger2 +@EnableDiscoveryClient public class TrainApplication { public static void main(String[] args) { SpringApplication.run(TrainApplication.class, args); } + @LoadBalanced + @Bean + public RestTemplate restTemplate(RestTemplateBuilder builder) { + return builder.build(); + } } diff --git a/ts-train-service/src/main/java/train/controller/TrainController.java b/ts-train-service/src/main/java/train/controller/TrainController.java index 20bdaf641..ea7129210 100644 --- a/ts-train-service/src/main/java/train/controller/TrainController.java +++ b/ts-train-service/src/main/java/train/controller/TrainController.java @@ -33,7 +33,7 @@ public String home(@RequestHeader HttpHeaders headers) { @CrossOrigin(origins = "*") @PostMapping(value = "/trains") public HttpEntity create(@RequestBody TrainType trainType, @RequestHeader HttpHeaders headers) { - TrainController.LOGGER.info("Create train,TrainTypeId: {}",trainType.getId()); + TrainController.LOGGER.info("[create][Create train][TrainTypeId: {}]",trainType.getId()); boolean isCreateSuccess = trainService.create(trainType, headers); if (isCreateSuccess) { return ok(new Response(1, "create success", null)); @@ -45,7 +45,7 @@ public HttpEntity create(@RequestBody TrainType trainType, @RequestHeader HttpHe @CrossOrigin(origins = "*") @GetMapping(value = "/trains/{id}") public HttpEntity retrieve(@PathVariable String id, @RequestHeader HttpHeaders headers) { - TrainController.LOGGER.info("Retrieve train,TrainTypeId: {}",id); + TrainController.LOGGER.info("[retrieve][Retrieve train][TrainTypeId: {}]",id); TrainType trainType = trainService.retrieve(id, headers); if (trainType == null) { return ok(new Response(0, "here is no TrainType with the trainType id: " + id, null)); @@ -54,10 +54,34 @@ public HttpEntity retrieve(@PathVariable String id, @RequestHeader HttpHeaders h } } + @CrossOrigin(origins = "*") + @GetMapping(value = "/trains/byName/{name}") + public HttpEntity retrieveByName(@PathVariable String name, @RequestHeader HttpHeaders headers) { + TrainController.LOGGER.info("[retrieveByName][Retrieve train][TrainTypeName: {}]", name); + TrainType trainType = trainService.retrieveByName(name, headers); + if (trainType == null) { + return ok(new Response(0, "here is no TrainType with the trainType name: " + name, null)); + } else { + return ok(new Response(1, "success", trainType)); + } + } + + @CrossOrigin(origins = "*") + @PostMapping(value = "/trains/byNames") + public HttpEntity retrieveByName(@RequestBody List names, @RequestHeader HttpHeaders headers) { + TrainController.LOGGER.info("[retrieveByNames][Retrieve train][TrainTypeNames: {}]", names); + List trainTypes = trainService.retrieveByNames(names, headers); + if (trainTypes == null) { + return ok(new Response(0, "here is no TrainTypes with the trainType names: " + names, null)); + } else { + return ok(new Response(1, "success", trainTypes)); + } + } + @CrossOrigin(origins = "*") @PutMapping(value = "/trains") public HttpEntity update(@RequestBody TrainType trainType, @RequestHeader HttpHeaders headers) { - TrainController.LOGGER.info("Update train,TrainTypeId: {}",trainType.getId()); + TrainController.LOGGER.info("[update][Update train][TrainTypeId: {}]",trainType.getId()); boolean isUpdateSuccess = trainService.update(trainType, headers); if (isUpdateSuccess) { return ok(new Response(1, "update success", isUpdateSuccess)); @@ -69,7 +93,7 @@ public HttpEntity update(@RequestBody TrainType trainType, @RequestHeader HttpHe @CrossOrigin(origins = "*") @DeleteMapping(value = "/trains/{id}") public HttpEntity delete(@PathVariable String id, @RequestHeader HttpHeaders headers) { - TrainController.LOGGER.info("Delete train,TrainTypeId: {}",id); + TrainController.LOGGER.info("[delete][Delete train][TrainTypeId: {}]",id); boolean isDeleteSuccess = trainService.delete(id, headers); if (isDeleteSuccess) { return ok(new Response(1, "delete success", isDeleteSuccess)); @@ -81,7 +105,7 @@ public HttpEntity delete(@PathVariable String id, @RequestHeader HttpHeaders hea @CrossOrigin(origins = "*") @GetMapping(value = "/trains") public HttpEntity query(@RequestHeader HttpHeaders headers) { - TrainController.LOGGER.info("Query train"); + TrainController.LOGGER.info("[query][Query train]"); List trainTypes = trainService.query(headers); if (trainTypes != null && !trainTypes.isEmpty()) { return ok(new Response(1, "success", trainTypes)); diff --git a/ts-train-service/src/main/java/train/entity/TrainType.java b/ts-train-service/src/main/java/train/entity/TrainType.java index 0e23dcad9..1005010d2 100644 --- a/ts-train-service/src/main/java/train/entity/TrainType.java +++ b/ts-train-service/src/main/java/train/entity/TrainType.java @@ -1,37 +1,52 @@ package train.entity; import lombok.Data; -import org.springframework.data.annotation.Id; -import org.springframework.data.mongodb.core.mapping.Document; +import lombok.NonNull; +import org.hibernate.annotations.GenericGenerator; + +import javax.persistence.Column; +import javax.persistence.GeneratedValue; +import javax.persistence.Id; + +import javax.persistence.Entity; import javax.validation.Valid; +import javax.validation.constraints.NotNull; @Data -@Document(collection="trainType") +@Entity +@GenericGenerator(name = "jpa-uuid", strategy = "org.hibernate.id.UUIDGenerator") public class TrainType { - @Valid @Id + @GeneratedValue(generator = "jpa-uuid") + @Column(length = 36) private String id; + @NotNull + @Column(name="name", unique = true) + private String name; + @Valid + @Column(name = "economy_class") private int economyClass; @Valid + @Column(name = "confort_class") private int confortClass; - + @Column(name = "average_speed") private int averageSpeed; public TrainType(){ //Default Constructor } - public TrainType(String id, int economyClass, int confortClass) { - this.id = id; + public TrainType(String name, int economyClass, int confortClass) { + this.name = name; this.economyClass = economyClass; this.confortClass = confortClass; } - public TrainType(String id, int economyClass, int confortClass, int averageSpeed) { - this.id = id; + public TrainType(String name, int economyClass, int confortClass, int averageSpeed) { + this.name = name; this.economyClass = economyClass; this.confortClass = confortClass; this.averageSpeed = averageSpeed; diff --git a/ts-train-service/src/main/java/train/init/InitData.java b/ts-train-service/src/main/java/train/init/InitData.java index 324773ccc..f5528e41c 100644 --- a/ts-train-service/src/main/java/train/init/InitData.java +++ b/ts-train-service/src/main/java/train/init/InitData.java @@ -17,37 +17,42 @@ public class InitData implements CommandLineRunner { public void run(String... args) throws Exception { TrainType info = new TrainType(); - info.setId("GaoTieOne"); + info.setName("GaoTieOne"); info.setConfortClass(Integer.MAX_VALUE); info.setEconomyClass(Integer.MAX_VALUE); info.setAverageSpeed(250); service.create(info, null); - info.setId("GaoTieTwo"); + info = new TrainType(); + info.setName("GaoTieTwo"); info.setConfortClass(Integer.MAX_VALUE); info.setEconomyClass(Integer.MAX_VALUE); info.setAverageSpeed(200); service.create(info, null); - info.setId("DongCheOne"); + info = new TrainType(); + info.setName("DongCheOne"); info.setConfortClass(Integer.MAX_VALUE); info.setEconomyClass(Integer.MAX_VALUE); info.setAverageSpeed(180); service.create(info, null); - info.setId("ZhiDa"); + info = new TrainType(); + info.setName("ZhiDa"); info.setConfortClass(Integer.MAX_VALUE); info.setEconomyClass(Integer.MAX_VALUE); info.setAverageSpeed(120); service.create(info, null); - info.setId("TeKuai"); + info = new TrainType(); + info.setName("TeKuai"); info.setConfortClass(Integer.MAX_VALUE); info.setEconomyClass(Integer.MAX_VALUE); info.setAverageSpeed(120); service.create(info, null); - info.setId("KuaiSu"); + info = new TrainType(); + info.setName("KuaiSu"); info.setConfortClass(Integer.MAX_VALUE); info.setEconomyClass(Integer.MAX_VALUE); info.setAverageSpeed(90); diff --git a/ts-train-service/src/main/java/train/repository/TrainTypeRepository.java b/ts-train-service/src/main/java/train/repository/TrainTypeRepository.java index c5f598c5a..05305daca 100644 --- a/ts-train-service/src/main/java/train/repository/TrainTypeRepository.java +++ b/ts-train-service/src/main/java/train/repository/TrainTypeRepository.java @@ -1,15 +1,22 @@ package train.repository; +import org.springframework.data.jpa.repository.Query; import org.springframework.data.repository.CrudRepository; +import org.springframework.stereotype.Repository; import train.entity.TrainType; import java.util.List; +import java.util.Optional; +@Repository +public interface TrainTypeRepository extends CrudRepository { -public interface TrainTypeRepository extends CrudRepository{ - - TrainType findById(String id); + Optional findById(String id); @Override List findAll(); void deleteById(String id); + TrainType findByName(String name); + + @Query(value="SELECT * from train_type where name in ?1", nativeQuery = true) + List findByNames(List names); } diff --git a/ts-train-service/src/main/java/train/service/TrainService.java b/ts-train-service/src/main/java/train/service/TrainService.java index 5314296fa..cfe983309 100644 --- a/ts-train-service/src/main/java/train/service/TrainService.java +++ b/ts-train-service/src/main/java/train/service/TrainService.java @@ -11,6 +11,10 @@ public interface TrainService { TrainType retrieve(String id,HttpHeaders headers); + TrainType retrieveByName(String name,HttpHeaders headers); + + List retrieveByNames(List name,HttpHeaders headers); + boolean update(TrainType trainType,HttpHeaders headers); boolean delete(String id,HttpHeaders headers); diff --git a/ts-train-service/src/main/java/train/service/TrainServiceImpl.java b/ts-train-service/src/main/java/train/service/TrainServiceImpl.java index 7ba774f98..aa7cd2230 100644 --- a/ts-train-service/src/main/java/train/service/TrainServiceImpl.java +++ b/ts-train-service/src/main/java/train/service/TrainServiceImpl.java @@ -5,6 +5,7 @@ import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpHeaders; import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; import train.entity.TrainType; import train.repository.TrainTypeRepository; @@ -21,39 +22,66 @@ public class TrainServiceImpl implements TrainService { @Override public boolean create(TrainType trainType, HttpHeaders headers) { boolean result = false; - if (repository.findById(trainType.getId()) == null) { - TrainType type = new TrainType(trainType.getId(), trainType.getEconomyClass(), trainType.getConfortClass()); + if(trainType.getName().isEmpty()){ + TrainServiceImpl.LOGGER.error("[create][Create train error][Train Type name not specified]"); + return result; + } + if (repository.findByName(trainType.getName()) == null) { + TrainType type = new TrainType(trainType.getName(), trainType.getEconomyClass(), trainType.getConfortClass()); type.setAverageSpeed(trainType.getAverageSpeed()); repository.save(type); result = true; } else { - TrainServiceImpl.LOGGER.error("Create train error.Train already exists,TrainTypeId: {}",trainType.getId()); + TrainServiceImpl.LOGGER.error("[create][Create train error][Train already exists][TrainTypeId: {}]",trainType.getId()); } return result; } @Override public TrainType retrieve(String id, HttpHeaders headers) { - if (repository.findById(id) == null) { - TrainServiceImpl.LOGGER.error("Retrieve train error.Train not found,TrainTypeId: {}",id); + if (!repository.findById(id).isPresent()) { + TrainServiceImpl.LOGGER.error("[retrieve][Retrieve train error][Train not found][TrainTypeId: {}]",id); + return null; + } else { + return repository.findById(id).get(); + } + } + + @Override + public TrainType retrieveByName(String name, HttpHeaders headers) { + TrainType tt = repository.findByName(name); + if (tt == null) { + TrainServiceImpl.LOGGER.error("[retrieveByName][RetrieveByName error][Train not found][TrainTypeName: {}]", name); return null; } else { - return repository.findById(id); + return tt; } } @Override + public List retrieveByNames(List names, HttpHeaders headers) { + List tt = repository.findByNames(names); + if (tt == null || tt.isEmpty()) { + TrainServiceImpl.LOGGER.error("[retrieveByNames][RetrieveByNames error][Train not found][TrainTypeNames: {}]", names); + return null; + } else { + return tt; + } + } + + @Override + @Transactional public boolean update(TrainType trainType, HttpHeaders headers) { boolean result = false; - if (repository.findById(trainType.getId()) != null) { - TrainType type = new TrainType(trainType.getId(), trainType.getEconomyClass(), trainType.getConfortClass()); - type.setAverageSpeed(trainType.getAverageSpeed()); + if (repository.findById(trainType.getId()).isPresent()) { + TrainType type = new TrainType(trainType.getName(), trainType.getEconomyClass(), trainType.getConfortClass(), trainType.getAverageSpeed()); + type.setId(trainType.getId()); repository.save(type); result = true; } else { - TrainServiceImpl.LOGGER.error("Update train error.Train not found,TrainTypeId: {}",trainType.getId()); + TrainServiceImpl.LOGGER.error("[update][Update train error][Train not found][TrainTypeId: {}]",trainType.getId()); } return result; } @@ -61,12 +89,12 @@ public boolean update(TrainType trainType, HttpHeaders headers) { @Override public boolean delete(String id, HttpHeaders headers) { boolean result = false; - if (repository.findById(id) != null) { + if (repository.findById(id).isPresent()) { repository.deleteById(id); result = true; } else { - TrainServiceImpl.LOGGER.error("Delete train error.Train not found,TrainTypeId: {}",id); + TrainServiceImpl.LOGGER.error("[delete][Delete train error][Train not found][TrainTypeId: {}]",id); } return result; } diff --git a/ts-train-service/src/main/resources/application.yml b/ts-train-service/src/main/resources/application.yml index e384f7b1c..2290ce586 100644 --- a/ts-train-service/src/main/resources/application.yml +++ b/ts-train-service/src/main/resources/application.yml @@ -1,13 +1,22 @@ spring: + cloud: + nacos: + discovery: + server-addr: ${NACOS_ADDRS:nacos-0.nacos-headless.default.svc.cluster.local,nacos-1.nacos-headless.default.svc.cluster.local,nacos-2.nacos-headless.default.svc.cluster.local} application: name: ts-train-service - data: - mongodb: - host: ts-train-mongo -# username: user -# password: ${MONGODB_PASSWORD} - database: ts - port: 27017 + datasource: + url: jdbc:mysql://${TRAIN_MYSQL_HOST:ts-train-mysql}:${TRAIN_MYSQL_PORT:3306}/${TRAIN_MYSQL_DATABASE:s-train-mysql}?useSSL=false + username: ${TRAIN_MYSQL_USER:root} + password: ${TRAIN_MYSQL_PASSWORD:Abcd1234#} + driver-class-name: com.mysql.cj.jdbc.Driver + jpa: + hibernate: + ddl-auto: update + properties: + hibernate: + dialect: org.hibernate.dialect.MySQL5Dialect + # HTTP Server server: diff --git a/ts-train-service/src/test/java/train/service/TrainServiceImplTest.java b/ts-train-service/src/test/java/train/service/TrainServiceImplTest.java index 22ca51536..f38216430 100644 --- a/ts-train-service/src/test/java/train/service/TrainServiceImplTest.java +++ b/ts-train-service/src/test/java/train/service/TrainServiceImplTest.java @@ -41,7 +41,7 @@ public void testCreate1() { @Test public void testCreate2() { TrainType trainType = new TrainType(); - Mockito.when(repository.findById(Mockito.anyString())).thenReturn(trainType); + Mockito.when(repository.findById(Mockito.anyString()).get()).thenReturn(trainType); boolean result = trainServiceImpl.create(trainType, headers); Assert.assertFalse(result); } @@ -56,7 +56,7 @@ public void testRetrieve1() { @Test public void testRetrieve2() { TrainType trainType = new TrainType(); - Mockito.when(repository.findById(Mockito.anyString())).thenReturn(trainType); + Mockito.when(repository.findById(Mockito.anyString()).get()).thenReturn(trainType); TrainType result = trainServiceImpl.retrieve("id", headers); Assert.assertNotNull(result); } @@ -64,7 +64,7 @@ public void testRetrieve2() { @Test public void testUpdate1() { TrainType trainType = new TrainType(); - Mockito.when(repository.findById(Mockito.anyString())).thenReturn(trainType); + Mockito.when(repository.findById(Mockito.anyString()).get()).thenReturn(trainType); Mockito.when(repository.save(Mockito.any(TrainType.class))).thenReturn(null); boolean result = trainServiceImpl.update(trainType, headers); Assert.assertTrue(result); @@ -81,7 +81,7 @@ public void testUpdate2() { @Test public void testDelete1() { TrainType trainType = new TrainType(); - Mockito.when(repository.findById(Mockito.anyString())).thenReturn(trainType); + Mockito.when(repository.findById(Mockito.anyString()).get()).thenReturn(trainType); Mockito.doNothing().doThrow(new RuntimeException()).when(repository).deleteById(Mockito.anyString()); boolean result = trainServiceImpl.delete("id", headers); Assert.assertTrue(result); diff --git a/ts-travel-plan-service/pom.xml b/ts-travel-plan-service/pom.xml index 5f33d134c..a336496ff 100644 --- a/ts-travel-plan-service/pom.xml +++ b/ts-travel-plan-service/pom.xml @@ -16,7 +16,7 @@ org.services ts-service 0.1.0 - ../ + ../pom.xml @@ -31,10 +31,7 @@ ts-common 0.1.0 - - - diff --git a/ts-travel-plan-service/src/main/java/travelplan/TravelPlanApplication.java b/ts-travel-plan-service/src/main/java/travelplan/TravelPlanApplication.java index f5a071658..89e8c06e6 100644 --- a/ts-travel-plan-service/src/main/java/travelplan/TravelPlanApplication.java +++ b/ts-travel-plan-service/src/main/java/travelplan/TravelPlanApplication.java @@ -3,6 +3,8 @@ import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.boot.web.client.RestTemplateBuilder; +import org.springframework.cloud.client.discovery.EnableDiscoveryClient; +import org.springframework.cloud.client.loadbalancer.LoadBalanced; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.EnableAspectJAutoProxy; import org.springframework.integration.annotation.IntegrationComponentScan; @@ -18,11 +20,13 @@ @EnableAsync @IntegrationComponentScan @EnableSwagger2 +@EnableDiscoveryClient public class TravelPlanApplication { public static void main(String[] args) { SpringApplication.run(TravelPlanApplication.class, args); } + @LoadBalanced @Bean public RestTemplate restTemplate(RestTemplateBuilder builder) { return builder.build(); diff --git a/ts-travel-plan-service/src/main/java/travelplan/controller/TravelPlanController.java b/ts-travel-plan-service/src/main/java/travelplan/controller/TravelPlanController.java index 771df81be..0a0dd406b 100644 --- a/ts-travel-plan-service/src/main/java/travelplan/controller/TravelPlanController.java +++ b/ts-travel-plan-service/src/main/java/travelplan/controller/TravelPlanController.java @@ -6,7 +6,7 @@ import org.springframework.http.HttpEntity; import org.springframework.http.HttpHeaders; import org.springframework.web.bind.annotation.*; -import travelplan.entity.TripInfo; +import edu.fudan.common.entity.TripInfo; import travelplan.entity.TransferTravelInfo; import travelplan.service.TravelPlanService; @@ -31,25 +31,25 @@ public String home() { @PostMapping(value="/travelPlan/transferResult" ) public HttpEntity getTransferResult(@RequestBody TransferTravelInfo info, @RequestHeader HttpHeaders headers) { - TravelPlanController.LOGGER.info("[Search Transit],start: {},end: {}",info.getFromStationName(),info.getToStationName()); + TravelPlanController.LOGGER.info("[getTransferSearch][Search Transit][start: {},end: {}]",info.getStartStation(),info.getEndStation()); return ok(travelPlanService.getTransferSearch(info, headers)); } @PostMapping(value="/travelPlan/cheapest") public HttpEntity getByCheapest(@RequestBody TripInfo queryInfo, @RequestHeader HttpHeaders headers) { - TravelPlanController.LOGGER.info("[Search Cheapest],start: {},end: {},time: {}",queryInfo.getStartingPlace(),queryInfo.getEndPlace(),queryInfo.getDepartureTime()); + TravelPlanController.LOGGER.info("[getCheapest][Search Cheapest][start: {},end: {},time: {}]",queryInfo.getStartPlace(),queryInfo.getEndPlace(),queryInfo.getDepartureTime()); return ok(travelPlanService.getCheapest(queryInfo, headers)); } @PostMapping(value="/travelPlan/quickest") public HttpEntity getByQuickest(@RequestBody TripInfo queryInfo, @RequestHeader HttpHeaders headers) { - TravelPlanController.LOGGER.info("[Search Quickest],start: {},end: {},time: {}",queryInfo.getStartingPlace(),queryInfo.getEndPlace(),queryInfo.getDepartureTime()); + TravelPlanController.LOGGER.info("[getQuickest][Search Quickest][start: {},end: {},time: {}]",queryInfo.getStartPlace(),queryInfo.getEndPlace(),queryInfo.getDepartureTime()); return ok(travelPlanService.getQuickest(queryInfo, headers)); } @PostMapping(value="/travelPlan/minStation") public HttpEntity getByMinStation(@RequestBody TripInfo queryInfo, @RequestHeader HttpHeaders headers) { - TravelPlanController.LOGGER.info("[Search Min Station],start: {},end: {},time: {}",queryInfo.getStartingPlace(),queryInfo.getEndPlace(),queryInfo.getDepartureTime()); + TravelPlanController.LOGGER.info("[getMinStation][Search Min Station][start: {},end: {},time: {}]",queryInfo.getStartPlace(),queryInfo.getEndPlace(),queryInfo.getDepartureTime()); return ok(travelPlanService.getMinStation(queryInfo, headers)); } diff --git a/ts-travel-plan-service/src/main/java/travelplan/entity/RoutePlanInfo.java b/ts-travel-plan-service/src/main/java/travelplan/entity/RoutePlanInfo.java deleted file mode 100644 index c867b6d6f..000000000 --- a/ts-travel-plan-service/src/main/java/travelplan/entity/RoutePlanInfo.java +++ /dev/null @@ -1,32 +0,0 @@ -package travelplan.entity; - -import lombok.Data; - -import java.util.Date; - -/** - * @author fdse - */ -@Data -public class RoutePlanInfo { - - private String formStationName; - - private String toStationName; - - private Date travelDate; - - private int num; - - public RoutePlanInfo() { - //Empty Constructor - } - - public RoutePlanInfo(String formStationName, String toStationName, Date travelDate, int num) { - this.formStationName = formStationName; - this.toStationName = toStationName; - this.travelDate = travelDate; - this.num = num; - } - -} diff --git a/ts-travel-plan-service/src/main/java/travelplan/entity/RoutePlanResultUnit.java b/ts-travel-plan-service/src/main/java/travelplan/entity/RoutePlanResultUnit.java deleted file mode 100644 index a96f37821..000000000 --- a/ts-travel-plan-service/src/main/java/travelplan/entity/RoutePlanResultUnit.java +++ /dev/null @@ -1,36 +0,0 @@ -package travelplan.entity; - -import java.util.ArrayList; -import java.util.Date; -import lombok.*; - -/** - * @author fdse - */ -@Data -@AllArgsConstructor -public class RoutePlanResultUnit { - - private String tripId; - - private String trainTypeId; - - private String fromStationName; - - private String toStationName; - - private ArrayList stopStations; - - private String priceForSecondClassSeat; - - private String priceForFirstClassSeat; - - private Date startingTime; - - private Date endTime; - - public RoutePlanResultUnit() { - //Default Constructor - } - -} diff --git a/ts-travel-plan-service/src/main/java/travelplan/entity/Seat.java b/ts-travel-plan-service/src/main/java/travelplan/entity/Seat.java deleted file mode 100644 index 0e56823b5..000000000 --- a/ts-travel-plan-service/src/main/java/travelplan/entity/Seat.java +++ /dev/null @@ -1,27 +0,0 @@ -package travelplan.entity; - -import lombok.Data; - -import java.util.Date; - -/** - * @author fdse - */ -@Data -public class Seat { - - private Date travelDate; - - private String trainNumber; - - private String startStation; - - private String destStation; - - private int seatType; - - public Seat(){ - //Default Constructor - } - -} diff --git a/ts-travel-plan-service/src/main/java/travelplan/entity/SeatClass.java b/ts-travel-plan-service/src/main/java/travelplan/entity/SeatClass.java deleted file mode 100644 index dfb725ba3..000000000 --- a/ts-travel-plan-service/src/main/java/travelplan/entity/SeatClass.java +++ /dev/null @@ -1,70 +0,0 @@ -package travelplan.entity; - -/** - * @author fdse - */ -public enum SeatClass { - - /** - * no seat - */ - NONE (0,"NoSeat"), - /** - * green seat - */ - BUSINESS (1,"GreenSeat"), - /** - * first class seat - */ - FIRSTCLASS (2,"FirstClassSeat"), - /** - * second class seat - */ - SECONDCLASS (3,"SecondClassSeat"), - /** - * hard seat - */ - HARDSEAT (4,"HardSeat"), - /** - * soft seat - */ - SOFTSEAT (5,"SoftSeat"), - /** - * hard bed - */ - HARDBED (6,"HardBed"), - /** - * soft bed - */ - SOFTBED (7,"SoftBed"), - /** - * high sofr seat - */ - HIGHSOFTBED (8,"HighSoftSeat"); - - private int code; - private String name; - - SeatClass(int code, String name){ - this.code = code; - this.name = name; - } - - public int getCode(){ - return code; - } - - public String getName() { - return name; - } - - public static String getNameByCode(int code){ - SeatClass[] seatClassSet = SeatClass.values(); - for(SeatClass seatClass : seatClassSet){ - if(seatClass.getCode() == code){ - return seatClass.getName(); - } - } - return seatClassSet[0].getName(); - } -} diff --git a/ts-travel-plan-service/src/main/java/travelplan/entity/TrainTypeEnum.java b/ts-travel-plan-service/src/main/java/travelplan/entity/TrainTypeEnum.java deleted file mode 100644 index a326580c7..000000000 --- a/ts-travel-plan-service/src/main/java/travelplan/entity/TrainTypeEnum.java +++ /dev/null @@ -1,63 +0,0 @@ -package travelplan.entity; - -import java.io.Serializable; - -/** - * @author fdse - */ -public enum TrainTypeEnum implements Serializable{ - - /** - * G - */ - G("G", 1), - /** - * D - */ - D("D", 2), - /** - * Z - */ - Z("Z",3), - /** - * T - */ - T("T", 4), - /** - * K - */ - K("K", 5); - - private String name; - private int index; - - TrainTypeEnum(String name, int index) { - this.name = name; - this.index = index; - } - - public static String getName(int index) { - for (TrainTypeEnum type : TrainTypeEnum.values()) { - if (type.getIndex() == index) { - return type.name; - } - } - return null; - } - - public String getName() { - return name; - } - - void setName(String name) { - this.name = name; - } - - public int getIndex() { - return index; - } - - void setIndex(int index) { - this.index = index; - } -} diff --git a/ts-travel-plan-service/src/main/java/travelplan/entity/TransferTravelInfo.java b/ts-travel-plan-service/src/main/java/travelplan/entity/TransferTravelInfo.java index 62d5e5b84..903e54439 100644 --- a/ts-travel-plan-service/src/main/java/travelplan/entity/TransferTravelInfo.java +++ b/ts-travel-plan-service/src/main/java/travelplan/entity/TransferTravelInfo.java @@ -1,5 +1,6 @@ package travelplan.entity; +import edu.fudan.common.util.StringUtils; import lombok.Data; import java.util.Date; @@ -10,13 +11,13 @@ @Data public class TransferTravelInfo { - private String fromStationName; + private String startStation; - private String viaStationName; + private String viaStation; - private String toStationName; + private String endStation; - private Date travelDate; + private String travelDate; private String trainType; @@ -24,12 +25,15 @@ public TransferTravelInfo() { //Empty Constructor } - public TransferTravelInfo(String fromStationName, String viaStationName, String toStationName, Date travelDate, String trainType) { - this.fromStationName = fromStationName; - this.viaStationName = viaStationName; - this.toStationName = toStationName; + public TransferTravelInfo(String startStation, String viaStation, String endStation, String travelDate, String trainType) { + this.startStation = startStation; + this.viaStation = viaStation; + this.endStation = endStation; this.travelDate = travelDate; this.trainType = trainType; } + public Date getTravelDate() { + return StringUtils.String2Date(travelDate); + } } diff --git a/ts-travel-plan-service/src/main/java/travelplan/entity/TransferTravelResult.java b/ts-travel-plan-service/src/main/java/travelplan/entity/TransferTravelResult.java index 5a8895214..9f218185f 100644 --- a/ts-travel-plan-service/src/main/java/travelplan/entity/TransferTravelResult.java +++ b/ts-travel-plan-service/src/main/java/travelplan/entity/TransferTravelResult.java @@ -1,6 +1,8 @@ package travelplan.entity; +import edu.fudan.common.entity.TripResponse; import lombok.Data; +import edu.fudan.common.entity.TripResponse; import java.util.List; diff --git a/ts-travel-plan-service/src/main/java/travelplan/entity/TravelAdvanceResultUnit.java b/ts-travel-plan-service/src/main/java/travelplan/entity/TravelAdvanceResultUnit.java index d0f437396..02d297ec3 100644 --- a/ts-travel-plan-service/src/main/java/travelplan/entity/TravelAdvanceResultUnit.java +++ b/ts-travel-plan-service/src/main/java/travelplan/entity/TravelAdvanceResultUnit.java @@ -15,9 +15,9 @@ public class TravelAdvanceResultUnit { private String trainTypeId; - private String fromStationName; + private String startStation; - private String toStationName; + private String endStation; private List stopStations; @@ -29,9 +29,9 @@ public class TravelAdvanceResultUnit { private int numberOfRestTicketFirstClass; - private Date startingTime; + private String startTime; - private Date endTime; + private String endTime; public TravelAdvanceResultUnit() { //Default Constructor diff --git a/ts-travel-plan-service/src/main/java/travelplan/entity/Trip.java b/ts-travel-plan-service/src/main/java/travelplan/entity/Trip.java deleted file mode 100644 index a1dbf994e..000000000 --- a/ts-travel-plan-service/src/main/java/travelplan/entity/Trip.java +++ /dev/null @@ -1,49 +0,0 @@ -package travelplan.entity; - -import lombok.Data; - -import java.util.Date; - -/** - * @author fdse - */ -@Data -public class Trip { - - private TripId tripId; - - private String trainTypeId; - - private String routeId; - - private String startingStationId; - - private String stationsId; - - private String terminalStationId; - - private Date startingTime; - - private Date endTime; - - public Trip(TripId tripId, String trainTypeId, String startingStationId, String stationsId, String terminalStationId, Date startingTime, Date endTime) { - this.tripId = tripId; - this.trainTypeId = trainTypeId; - this.startingStationId = startingStationId; - this.stationsId = stationsId; - this.terminalStationId = terminalStationId; - this.startingTime = startingTime; - this.endTime = endTime; - } - - public Trip(TripId tripId, String trainTypeId, String routeId) { - this.tripId = tripId; - this.trainTypeId = trainTypeId; - this.routeId = routeId; - } - - public Trip(){ - //Default Constructor - } - -} diff --git a/ts-travel-plan-service/src/main/java/travelplan/entity/TripId.java b/ts-travel-plan-service/src/main/java/travelplan/entity/TripId.java deleted file mode 100644 index 39aa2700f..000000000 --- a/ts-travel-plan-service/src/main/java/travelplan/entity/TripId.java +++ /dev/null @@ -1,44 +0,0 @@ -package travelplan.entity; - -import lombok.Data; - -import java.io.Serializable; - -/** - * @author fdse - */ -@Data -public class TripId implements Serializable{ - - private TrainTypeEnum type; - - private String number; - - public TripId(){ - //Default Constructor - } - - public TripId(String trainNumber){ - char type0 = trainNumber.charAt(0); - switch(type0){ - case 'G': this.type = TrainTypeEnum.G; - break; - case 'D': this.type = TrainTypeEnum.D; - break; - case 'Z': this.type = TrainTypeEnum.Z; - break; - case 'T': this.type = TrainTypeEnum.T; - break; - case 'K': this.type = TrainTypeEnum.K; - break; - default:break; - } - - this.number = trainNumber.substring(1); - } - - @Override - public String toString(){ - return type.getName() + number; - } -} diff --git a/ts-travel-plan-service/src/main/java/travelplan/entity/TripInfo.java b/ts-travel-plan-service/src/main/java/travelplan/entity/TripInfo.java deleted file mode 100644 index 48ae2ff65..000000000 --- a/ts-travel-plan-service/src/main/java/travelplan/entity/TripInfo.java +++ /dev/null @@ -1,24 +0,0 @@ -package travelplan.entity; - -import lombok.AllArgsConstructor; -import lombok.Data; - -import java.util.Date; - -/** - * @author fdse - */ -@Data -@AllArgsConstructor -public class TripInfo { - - private String startingPlace; - - private String endPlace; - - private Date departureTime; - - public TripInfo() { - //Default Constructor - } -} diff --git a/ts-travel-plan-service/src/main/java/travelplan/entity/TripResponse.java b/ts-travel-plan-service/src/main/java/travelplan/entity/TripResponse.java deleted file mode 100644 index 6c0a332c4..000000000 --- a/ts-travel-plan-service/src/main/java/travelplan/entity/TripResponse.java +++ /dev/null @@ -1,37 +0,0 @@ -package travelplan.entity; - -import lombok.Data; - -import java.util.Date; - -/** - * @author fdse - */ -@Data -public class TripResponse { - - private TripId tripId; - - private String trainTypeId; - - private String startingStation; - - private String terminalStation; - - private Date startingTime; - - private Date endTime; - - private int economyClass; - - private int confortClass; - - private String priceForEconomyClass; - - private String priceForConfortClass; - - public TripResponse(){ - //Default Constructor - } - -} diff --git a/ts-travel-plan-service/src/main/java/travelplan/service/TravelPlanService.java b/ts-travel-plan-service/src/main/java/travelplan/service/TravelPlanService.java index 75bbc602a..174f61eb3 100644 --- a/ts-travel-plan-service/src/main/java/travelplan/service/TravelPlanService.java +++ b/ts-travel-plan-service/src/main/java/travelplan/service/TravelPlanService.java @@ -2,7 +2,8 @@ import edu.fudan.common.util.Response; import org.springframework.http.HttpHeaders; -import travelplan.entity.*; +import edu.fudan.common.entity.*; +import travelplan.entity.TransferTravelInfo; /** * @author fdse diff --git a/ts-travel-plan-service/src/main/java/travelplan/service/TravelPlanServiceImpl.java b/ts-travel-plan-service/src/main/java/travelplan/service/TravelPlanServiceImpl.java index 0a82ca711..855bb2bde 100644 --- a/ts-travel-plan-service/src/main/java/travelplan/service/TravelPlanServiceImpl.java +++ b/ts-travel-plan-service/src/main/java/travelplan/service/TravelPlanServiceImpl.java @@ -1,9 +1,14 @@ package travelplan.service; +import edu.fudan.common.util.JsonUtils; import edu.fudan.common.util.Response; +import edu.fudan.common.util.StringUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.cloud.client.ServiceInstance; +import org.springframework.cloud.client.discovery.DiscoveryClient; import org.springframework.core.ParameterizedTypeReference; import org.springframework.http.HttpEntity; import org.springframework.http.HttpHeaders; @@ -11,9 +16,13 @@ import org.springframework.http.ResponseEntity; import org.springframework.stereotype.Service; import org.springframework.web.client.RestTemplate; -import travelplan.entity.*; +import edu.fudan.common.entity.*; +import travelplan.entity.TransferTravelInfo; +import travelplan.entity.TransferTravelResult; +import travelplan.entity.TravelAdvanceResultUnit; import java.util.ArrayList; +import java.util.Arrays; import java.util.Date; import java.util.List; @@ -25,19 +34,25 @@ public class TravelPlanServiceImpl implements TravelPlanService { @Autowired private RestTemplate restTemplate; + @Autowired + private DiscoveryClient discoveryClient; private static final Logger LOGGER = LoggerFactory.getLogger(TravelPlanServiceImpl.class); String success = "Success"; String cannotFind = "Cannot Find"; + private String getServiceUrl(String serviceName) { + return "http://" + serviceName; + } + @Override public Response getTransferSearch(TransferTravelInfo info, HttpHeaders headers) { TripInfo queryInfoFirstSection = new TripInfo(); - queryInfoFirstSection.setDepartureTime(info.getTravelDate()); - queryInfoFirstSection.setStartingPlace(info.getFromStationName()); - queryInfoFirstSection.setEndPlace(info.getViaStationName()); + queryInfoFirstSection.setDepartureTime(StringUtils.Date2String(info.getTravelDate())); + queryInfoFirstSection.setStartPlace(info.getStartStation()); + queryInfoFirstSection.setEndPlace(info.getViaStation()); List firstSectionFromHighSpeed; List firstSectionFromNormal; @@ -45,9 +60,9 @@ public Response getTransferSearch(TransferTravelInfo info, HttpHeaders headers) firstSectionFromNormal = tripsFromNormal(queryInfoFirstSection, headers); TripInfo queryInfoSecondSectoin = new TripInfo(); - queryInfoSecondSectoin.setDepartureTime(info.getTravelDate()); - queryInfoSecondSectoin.setStartingPlace(info.getViaStationName()); - queryInfoSecondSectoin.setEndPlace(info.getToStationName()); + queryInfoSecondSectoin.setDepartureTime(StringUtils.Date2String(info.getTravelDate())); + queryInfoSecondSectoin.setStartPlace(info.getViaStation()); + queryInfoSecondSectoin.setEndPlace(info.getEndStation()); List secondSectionFromHighSpeed; List secondSectionFromNormal; @@ -73,8 +88,8 @@ public Response getTransferSearch(TransferTravelInfo info, HttpHeaders headers) public Response getCheapest(TripInfo info, HttpHeaders headers) { RoutePlanInfo routePlanInfo = new RoutePlanInfo(); routePlanInfo.setNum(5); - routePlanInfo.setFormStationName(info.getStartingPlace()); - routePlanInfo.setToStationName(info.getEndPlace()); + routePlanInfo.setStartStation(info.getStartPlace()); + routePlanInfo.setEndStation(info.getEndPlace()); routePlanInfo.setTravelDate(info.getDepartureTime()); ArrayList routePlanResultUnits = getRoutePlanResultCheapest(routePlanInfo, headers); @@ -84,21 +99,26 @@ public Response getCheapest(TripInfo info, HttpHeaders headers) { RoutePlanResultUnit tempUnit = routePlanResultUnits.get(i); TravelAdvanceResultUnit newUnit = new TravelAdvanceResultUnit(); newUnit.setTripId(tempUnit.getTripId()); - newUnit.setToStationName(tempUnit.getToStationName()); - newUnit.setTrainTypeId(tempUnit.getTrainTypeId()); - newUnit.setFromStationName(tempUnit.getFromStationName()); + newUnit.setEndStation(tempUnit.getEndStation()); + newUnit.setTrainTypeId(tempUnit.getTrainTypeName()); + newUnit.setStartStation(tempUnit.getStartStation()); - List stops = transferStationIdToStationName(tempUnit.getStopStations(), headers); + List stops = tempUnit.getStopStations(); newUnit.setStopStations(stops); newUnit.setPriceForFirstClassSeat(tempUnit.getPriceForFirstClassSeat()); newUnit.setPriceForSecondClassSeat(tempUnit.getPriceForSecondClassSeat()); - newUnit.setStartingTime(tempUnit.getStartingTime()); + newUnit.setStartTime(tempUnit.getStartTime()); newUnit.setEndTime(tempUnit.getEndTime()); + + TrainType trainType = queryTrainTypeByName(tempUnit.getTrainTypeName(), headers); + int firstClassTotalNum = trainType.getConfortClass(); + int secondClassTotalNum = trainType.getEconomyClass(); + int first = getRestTicketNumber(info.getDepartureTime(), tempUnit.getTripId(), - tempUnit.getFromStationName(), tempUnit.getToStationName(), SeatClass.FIRSTCLASS.getCode(), headers); + tempUnit.getStartStation(), tempUnit.getEndStation(), SeatClass.FIRSTCLASS.getCode(), firstClassTotalNum, tempUnit.getStopStations(), headers); int second = getRestTicketNumber(info.getDepartureTime(), tempUnit.getTripId(), - tempUnit.getFromStationName(), tempUnit.getToStationName(), SeatClass.SECONDCLASS.getCode(), headers); + tempUnit.getStartStation(), tempUnit.getEndStation(), SeatClass.SECONDCLASS.getCode(), secondClassTotalNum, tempUnit.getStopStations(), headers); newUnit.setNumberOfRestTicketFirstClass(first); newUnit.setNumberOfRestTicketSecondClass(second); lists.add(newUnit); @@ -106,7 +126,7 @@ public Response getCheapest(TripInfo info, HttpHeaders headers) { return new Response<>(1, success, lists); } else { - TravelPlanServiceImpl.LOGGER.warn("Get cheapest trip warn.Route Plan Result Units: {}","No Content"); + TravelPlanServiceImpl.LOGGER.warn("[getCheapest][Get cheapest trip warn][Route Plan Result Units: {}]","No Content"); return new Response<>(0, cannotFind, null); } } @@ -115,8 +135,8 @@ public Response getCheapest(TripInfo info, HttpHeaders headers) { public Response getQuickest(TripInfo info, HttpHeaders headers) { RoutePlanInfo routePlanInfo = new RoutePlanInfo(); routePlanInfo.setNum(5); - routePlanInfo.setFormStationName(info.getStartingPlace()); - routePlanInfo.setToStationName(info.getEndPlace()); + routePlanInfo.setStartStation(info.getStartPlace()); + routePlanInfo.setEndStation(info.getEndPlace()); routePlanInfo.setTravelDate(info.getDepartureTime()); ArrayList routePlanResultUnits = getRoutePlanResultQuickest(routePlanInfo, headers); @@ -128,29 +148,33 @@ public Response getQuickest(TripInfo info, HttpHeaders headers) { RoutePlanResultUnit tempUnit = routePlanResultUnits.get(i); TravelAdvanceResultUnit newUnit = new TravelAdvanceResultUnit(); newUnit.setTripId(tempUnit.getTripId()); - newUnit.setTrainTypeId(tempUnit.getTrainTypeId()); - newUnit.setToStationName(tempUnit.getToStationName()); - newUnit.setFromStationName(tempUnit.getFromStationName()); + newUnit.setTrainTypeId(tempUnit.getTrainTypeName()); + newUnit.setEndStation(tempUnit.getEndStation()); + newUnit.setStartStation(tempUnit.getStartStation()); - List stops = transferStationIdToStationName(tempUnit.getStopStations(), headers); + List stops = tempUnit.getStopStations(); newUnit.setStopStations(stops); newUnit.setPriceForFirstClassSeat(tempUnit.getPriceForFirstClassSeat()); newUnit.setPriceForSecondClassSeat(tempUnit.getPriceForSecondClassSeat()); - newUnit.setStartingTime(tempUnit.getStartingTime()); + newUnit.setStartTime(tempUnit.getStartTime()); newUnit.setEndTime(tempUnit.getEndTime()); + + TrainType trainType = queryTrainTypeByName(tempUnit.getTrainTypeName(), headers); + int firstClassTotalNum = trainType.getConfortClass(); + int secondClassTotalNum = trainType.getEconomyClass(); int first = getRestTicketNumber(info.getDepartureTime(), tempUnit.getTripId(), - tempUnit.getFromStationName(), tempUnit.getToStationName(), SeatClass.FIRSTCLASS.getCode(), headers); + tempUnit.getStartStation(), tempUnit.getEndStation(), SeatClass.FIRSTCLASS.getCode(), firstClassTotalNum, tempUnit.getStopStations(), headers); int second = getRestTicketNumber(info.getDepartureTime(), tempUnit.getTripId(), - tempUnit.getFromStationName(), tempUnit.getToStationName(), SeatClass.SECONDCLASS.getCode(), headers); + tempUnit.getStartStation(), tempUnit.getEndStation(), SeatClass.SECONDCLASS.getCode(), secondClassTotalNum, tempUnit.getStopStations(),headers); newUnit.setNumberOfRestTicketFirstClass(first); newUnit.setNumberOfRestTicketSecondClass(second); lists.add(newUnit); } return new Response<>(1, success, lists); } else { - TravelPlanServiceImpl.LOGGER.warn("Get quickest trip warn.Route Plan Result Units: {}","No Content"); + TravelPlanServiceImpl.LOGGER.warn("[getQuickest][Get quickest trip warn][Route Plan Result Units: {}]","No Content"); return new Response<>(0, cannotFind, null); } } @@ -159,8 +183,8 @@ public Response getQuickest(TripInfo info, HttpHeaders headers) { public Response getMinStation(TripInfo info, HttpHeaders headers) { RoutePlanInfo routePlanInfo = new RoutePlanInfo(); routePlanInfo.setNum(5); - routePlanInfo.setFormStationName(info.getStartingPlace()); - routePlanInfo.setToStationName(info.getEndPlace()); + routePlanInfo.setStartStation(info.getStartPlace()); + routePlanInfo.setEndStation(info.getEndPlace()); routePlanInfo.setTravelDate(info.getDepartureTime()); ArrayList routePlanResultUnits = getRoutePlanResultMinStation(routePlanInfo, headers); @@ -171,50 +195,54 @@ public Response getMinStation(TripInfo info, HttpHeaders headers) { RoutePlanResultUnit tempUnit = routePlanResultUnits.get(i); TravelAdvanceResultUnit newUnit = new TravelAdvanceResultUnit(); newUnit.setTripId(tempUnit.getTripId()); - newUnit.setTrainTypeId(tempUnit.getTrainTypeId()); - newUnit.setFromStationName(tempUnit.getFromStationName()); - newUnit.setToStationName(tempUnit.getToStationName()); + newUnit.setTrainTypeId(tempUnit.getTrainTypeName()); + newUnit.setStartStation(tempUnit.getStartStation()); + newUnit.setEndStation(tempUnit.getEndStation()); - List stops = transferStationIdToStationName(tempUnit.getStopStations(), headers); + List stops = tempUnit.getStopStations(); newUnit.setStopStations(stops); newUnit.setPriceForFirstClassSeat(tempUnit.getPriceForFirstClassSeat()); newUnit.setPriceForSecondClassSeat(tempUnit.getPriceForSecondClassSeat()); newUnit.setEndTime(tempUnit.getEndTime()); - newUnit.setStartingTime(tempUnit.getStartingTime()); + newUnit.setStartTime(tempUnit.getStartTime()); + + TrainType trainType = queryTrainTypeByName(tempUnit.getTrainTypeName(), headers); + int firstClassTotalNum = trainType.getConfortClass(); + int secondClassTotalNum = trainType.getEconomyClass(); int first = getRestTicketNumber(info.getDepartureTime(), tempUnit.getTripId(), - tempUnit.getFromStationName(), tempUnit.getToStationName(), SeatClass.FIRSTCLASS.getCode(), headers); + tempUnit.getStartStation(), tempUnit.getEndStation(), SeatClass.FIRSTCLASS.getCode(), firstClassTotalNum, tempUnit.getStopStations(), headers); int second = getRestTicketNumber(info.getDepartureTime(), tempUnit.getTripId(), - tempUnit.getFromStationName(), tempUnit.getToStationName(), SeatClass.SECONDCLASS.getCode(), headers); + tempUnit.getStartStation(), tempUnit.getEndStation(), SeatClass.SECONDCLASS.getCode(), secondClassTotalNum, tempUnit.getStopStations(), headers); newUnit.setNumberOfRestTicketFirstClass(first); newUnit.setNumberOfRestTicketSecondClass(second); lists.add(newUnit); } return new Response<>(1, success, lists); } else { - TravelPlanServiceImpl.LOGGER.warn("Get min stations trip warn.Route Plan Result Units: {}","No Content"); + TravelPlanServiceImpl.LOGGER.warn("[getMinStation][Get min stations trip warn][Route Plan Result Units: {}]","No Content"); return new Response<>(0, cannotFind, null); } } - private int getRestTicketNumber(Date travelDate, String trainNumber, String startStationName, String endStationName, int seatType, HttpHeaders headers) { + private int getRestTicketNumber(String travelDate, String trainNumber, String startStationName, String endStationName, int seatType, int totalNum, List stations, HttpHeaders headers) { Seat seatRequest = new Seat(); - String fromId = queryForStationId(startStationName, headers); - String toId = queryForStationId(endStationName, headers); - - seatRequest.setDestStation(toId); - seatRequest.setStartStation(fromId); + seatRequest.setDestStation(startStationName); + seatRequest.setStartStation(endStationName); seatRequest.setTrainNumber(trainNumber); seatRequest.setTravelDate(travelDate); seatRequest.setSeatType(seatType); + seatRequest.setStations(stations); + seatRequest.setTotalNum(totalNum); - TravelPlanServiceImpl.LOGGER.info("Seat Request is: {}", seatRequest.toString()); + TravelPlanServiceImpl.LOGGER.info("[getRestTicketNumber][Seat Request][Seat Request is: {}]", seatRequest.toString()); HttpEntity requestEntity = new HttpEntity(seatRequest, null); + String seat_service_url = getServiceUrl("ts-seat-service"); ResponseEntity> re = restTemplate.exchange( - "http://ts-seat-service:18898/api/v1/seatservice/seats/left_tickets", + seat_service_url + "/api/v1/seatservice/seats/left_tickets", HttpMethod.POST, requestEntity, new ParameterizedTypeReference>() { @@ -225,8 +253,9 @@ private int getRestTicketNumber(Date travelDate, String trainNumber, String star private ArrayList getRoutePlanResultCheapest(RoutePlanInfo info, HttpHeaders headers) { HttpEntity requestEntity = new HttpEntity(info, null); + String route_plan_service_url = getServiceUrl("ts-route-plan-service"); ResponseEntity>> re = restTemplate.exchange( - "http://ts-route-plan-service:14578/api/v1/routeplanservice/routePlan/cheapestRoute", + route_plan_service_url + "/api/v1/routeplanservice/routePlan/cheapestRoute", HttpMethod.POST, requestEntity, new ParameterizedTypeReference>>() { @@ -236,8 +265,9 @@ private ArrayList getRoutePlanResultCheapest(RoutePlanInfo private ArrayList getRoutePlanResultQuickest(RoutePlanInfo info, HttpHeaders headers) { HttpEntity requestEntity = new HttpEntity(info, null); + String route_plan_service_url = getServiceUrl("ts-route-plan-service"); ResponseEntity>> re = restTemplate.exchange( - "http://ts-route-plan-service:14578/api/v1/routeplanservice/routePlan/quickestRoute", + route_plan_service_url + "/api/v1/routeplanservice/routePlan/quickestRoute", HttpMethod.POST, requestEntity, new ParameterizedTypeReference>>() { @@ -248,8 +278,9 @@ private ArrayList getRoutePlanResultQuickest(RoutePlanInfo private ArrayList getRoutePlanResultMinStation(RoutePlanInfo info, HttpHeaders headers) { HttpEntity requestEntity = new HttpEntity(info, null); + String route_plan_service_url = getServiceUrl("ts-route-plan-service"); ResponseEntity>> re = restTemplate.exchange( - "http://ts-route-plan-service:14578/api/v1/routeplanservice/routePlan/minStopStations", + route_plan_service_url + "/api/v1/routeplanservice/routePlan/minStopStations", HttpMethod.POST, requestEntity, new ParameterizedTypeReference>>() { @@ -259,8 +290,9 @@ private ArrayList getRoutePlanResultMinStation(RoutePlanInf private List tripsFromHighSpeed(TripInfo info, HttpHeaders headers) { HttpEntity requestEntity = new HttpEntity(info, null); + String travel_service_url=getServiceUrl("ts-travel-service"); ResponseEntity>> re = restTemplate.exchange( - "http://ts-travel-service:12346/api/v1/travelservice/trips/left", + travel_service_url + "/api/v1/travelservice/trips/left", HttpMethod.POST, requestEntity, new ParameterizedTypeReference>>() { @@ -271,8 +303,9 @@ private List tripsFromHighSpeed(TripInfo info, HttpHeaders headers private ArrayList tripsFromNormal(TripInfo info, HttpHeaders headers) { HttpEntity requestEntity = new HttpEntity(info, null); + String travel2_service_url=getServiceUrl("ts-travel2-service"); ResponseEntity>> re = restTemplate.exchange( - "http://ts-travel2-service:16346/api/v1/travel2service/trips/left", + travel2_service_url + "/api/v1/travel2service/trips/left", HttpMethod.POST, requestEntity, new ParameterizedTypeReference>>() { @@ -281,28 +314,17 @@ private ArrayList tripsFromNormal(TripInfo info, HttpHeaders heade return re.getBody().getData(); } - private String queryForStationId(String stationName, HttpHeaders headers) { - + public TrainType queryTrainTypeByName(String trainTypeName, HttpHeaders headers) { HttpEntity requestEntity = new HttpEntity(null); - ResponseEntity> re = restTemplate.exchange( - "http://ts-ticketinfo-service:15681/api/v1/ticketinfoservice/ticketinfo/" + stationName, + String train_service_url=getServiceUrl("ts-train-service"); + ResponseEntity re = restTemplate.exchange( + train_service_url + "/api/v1/trainservice/trains/byName/" + trainTypeName, HttpMethod.GET, requestEntity, - new ParameterizedTypeReference>() { - }); + Response.class); + Response response = re.getBody(); - return re.getBody().getData(); + return JsonUtils.conveterObject(response.getData(), TrainType.class); } - private List transferStationIdToStationName(ArrayList stations, HttpHeaders headers) { - HttpEntity requestEntity = new HttpEntity(stations, null); - ResponseEntity>> re = restTemplate.exchange( - "http://ts-station-service:12345/api/v1/stationservice/stations/namelist", - HttpMethod.POST, - requestEntity, - new ParameterizedTypeReference>>() { - }); - - return re.getBody().getData(); - } } diff --git a/ts-travel-plan-service/src/main/resources/application.yml b/ts-travel-plan-service/src/main/resources/application.yml index 23b1d4256..2171f8727 100644 --- a/ts-travel-plan-service/src/main/resources/application.yml +++ b/ts-travel-plan-service/src/main/resources/application.yml @@ -3,9 +3,13 @@ server: port: 14322 # HTTP (Tomcat) port spring: + cloud: + nacos: + discovery: + server-addr: ${NACOS_ADDRS:nacos-0.nacos-headless.default.svc.cluster.local,nacos-1.nacos-headless.default.svc.cluster.local,nacos-2.nacos-headless.default.svc.cluster.local} application: name: ts-travel-plan-service swagger: - controllerPackage: travelplan.controller \ No newline at end of file + controllerPackage: travelplan.controller diff --git a/ts-travel-plan-service/src/test/java/travelplan/controller/TravelPlanControllerTest.java b/ts-travel-plan-service/src/test/java/travelplan/controller/TravelPlanControllerTest.java index b1952f2f2..6fce350ad 100644 --- a/ts-travel-plan-service/src/test/java/travelplan/controller/TravelPlanControllerTest.java +++ b/ts-travel-plan-service/src/test/java/travelplan/controller/TravelPlanControllerTest.java @@ -17,7 +17,7 @@ import org.springframework.test.web.servlet.result.MockMvcResultMatchers; import org.springframework.test.web.servlet.setup.MockMvcBuilders; import travelplan.entity.TransferTravelInfo; -import travelplan.entity.TripInfo; +import edu.fudan.common.entity.TripInfo; import travelplan.service.TravelPlanService; @RunWith(JUnit4.class) diff --git a/ts-travel-plan-service/src/test/java/travelplan/service/TravelPlanServiceImplTest.java b/ts-travel-plan-service/src/test/java/travelplan/service/TravelPlanServiceImplTest.java index ae8284935..053f607fc 100644 --- a/ts-travel-plan-service/src/test/java/travelplan/service/TravelPlanServiceImplTest.java +++ b/ts-travel-plan-service/src/test/java/travelplan/service/TravelPlanServiceImplTest.java @@ -13,7 +13,8 @@ import org.springframework.core.ParameterizedTypeReference; import org.springframework.http.*; import org.springframework.web.client.RestTemplate; -import travelplan.entity.*; +import edu.fudan.common.entity.*; +import travelplan.entity.TransferTravelInfo; import java.util.ArrayList; import java.util.Date; @@ -37,7 +38,7 @@ public void setUp() { @Test public void testGetTransferSearch() { - TransferTravelInfo info = new TransferTravelInfo("from_station", "", "to_station", new Date(), "G"); + TransferTravelInfo info = new TransferTravelInfo("from_station", "", "to_station", "", "G"); //mock tripsFromHighSpeed() and tripsFromNormal() List tripResponseList = new ArrayList<>(); @@ -55,10 +56,10 @@ public void testGetTransferSearch() { @Test public void testGetCheapest() { - TripInfo info = new TripInfo("start_station", "end_station", new Date()); + TripInfo info = new TripInfo("start_station", "end_station", ""); //response for getRoutePlanResultCheapest() - RoutePlanResultUnit rpru = new RoutePlanResultUnit("trip_id", "type_id", "from_station", "to_station", new ArrayList<>(), "1.0", "2.0", new Date(), new Date()); + RoutePlanResultUnit rpru = new RoutePlanResultUnit("trip_id", "type_id", "from_station", "to_station", new ArrayList<>(), "1.0", "2.0", "", ""); ArrayList routePlanResultUnits = new ArrayList(){{ add(rpru); }}; Response> response1 = new Response<>(null, null, routePlanResultUnits); ResponseEntity>> re1 = new ResponseEntity<>(response1, HttpStatus.OK); @@ -91,10 +92,10 @@ public void testGetCheapest() { @Test public void testGetQuickest() { - TripInfo info = new TripInfo("start_station", "end_station", new Date()); + TripInfo info = new TripInfo("start_station", "end_station", ""); //response for getRoutePlanResultQuickest() - RoutePlanResultUnit rpru = new RoutePlanResultUnit("trip_id", "type_id", "from_station", "to_station", new ArrayList<>(), "1.0", "2.0", new Date(), new Date()); + RoutePlanResultUnit rpru = new RoutePlanResultUnit("trip_id", "type_id", "from_station", "to_station", new ArrayList<>(), "1.0", "2.0", "", ""); ArrayList routePlanResultUnits = new ArrayList(){{ add(rpru); }}; Response> response1 = new Response<>(null, null, routePlanResultUnits); ResponseEntity>> re1 = new ResponseEntity<>(response1, HttpStatus.OK); @@ -127,10 +128,10 @@ public void testGetQuickest() { @Test public void testGetMinStation() { - TripInfo info = new TripInfo("start_station", "end_station", new Date()); + TripInfo info = new TripInfo("start_station", "end_station", ""); //response for getRoutePlanResultMinStation() - RoutePlanResultUnit rpru = new RoutePlanResultUnit("trip_id", "type_id", "from_station", "to_station", new ArrayList<>(), "1.0", "2.0", new Date(), new Date()); + RoutePlanResultUnit rpru = new RoutePlanResultUnit("trip_id", "type_id", "from_station", "to_station", new ArrayList<>(), "1.0", "2.0", "", ""); ArrayList routePlanResultUnits = new ArrayList(){{ add(rpru); }}; Response> response1 = new Response<>(null, null, routePlanResultUnits); ResponseEntity>> re1 = new ResponseEntity<>(response1, HttpStatus.OK); diff --git a/ts-travel-service/pom.xml b/ts-travel-service/pom.xml index 2d978ff31..7fc2aa375 100644 --- a/ts-travel-service/pom.xml +++ b/ts-travel-service/pom.xml @@ -15,7 +15,7 @@ org.services ts-service 0.1.0 - ../ + ../pom.xml @@ -27,7 +27,12 @@ org.springframework.boot - spring-boot-starter-data-mongodb + spring-boot-starter-data-jpa + + + mysql + mysql-connector-java + runtime org.services @@ -39,6 +44,10 @@ apm-toolkit-trace 8.6.0 + + jakarta.validation + jakarta.validation-api + diff --git a/ts-travel-service/src/main/java/travel/TravelApplication.java b/ts-travel-service/src/main/java/travel/TravelApplication.java index 0e65c4215..c82ea546c 100644 --- a/ts-travel-service/src/main/java/travel/TravelApplication.java +++ b/ts-travel-service/src/main/java/travel/TravelApplication.java @@ -3,6 +3,8 @@ import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.boot.web.client.RestTemplateBuilder; +import org.springframework.cloud.client.discovery.EnableDiscoveryClient; +import org.springframework.cloud.client.loadbalancer.LoadBalanced; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.EnableAspectJAutoProxy; import org.springframework.integration.annotation.IntegrationComponentScan; @@ -18,12 +20,14 @@ @EnableAsync @IntegrationComponentScan @EnableSwagger2 +@EnableDiscoveryClient public class TravelApplication { public static void main(String[] args) { SpringApplication.run(TravelApplication.class, args); } + @LoadBalanced @Bean public RestTemplate restTemplate(RestTemplateBuilder builder) { return builder.build(); diff --git a/ts-travel-service/src/main/java/travel/controller/TravelController.java b/ts-travel-service/src/main/java/travel/controller/TravelController.java index 7ff6b0459..314ff5848 100644 --- a/ts-travel-service/src/main/java/travel/controller/TravelController.java +++ b/ts-travel-service/src/main/java/travel/controller/TravelController.java @@ -1,5 +1,9 @@ package travel.controller; +import edu.fudan.common.entity.TravelInfo; +import edu.fudan.common.entity.TripAllDetailInfo; +import edu.fudan.common.entity.TripInfo; +import edu.fudan.common.entity.TripResponse; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; @@ -8,6 +12,8 @@ import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.*; + +import edu.fudan.common.entity.TravelInfo; import travel.entity.*; import travel.service.TravelService; @@ -37,14 +43,14 @@ public String home(@RequestHeader HttpHeaders headers) { public HttpEntity getTrainTypeByTripId(@PathVariable String tripId, @RequestHeader HttpHeaders headers) { // TrainType - TravelController.LOGGER.info("Get train Type by Trip id,TripId: {}", tripId); + TravelController.LOGGER.info("[getTrainTypeByTripId][Get train Type by Trip id][TripId: {}]", tripId); return ok(travelService.getTrainTypeByTripId(tripId, headers)); } @GetMapping(value = "/routes/{tripId}") public HttpEntity getRouteByTripId(@PathVariable String tripId, @RequestHeader HttpHeaders headers) { - TravelController.LOGGER.info("[Get Route By Trip ID], TripId: {}", tripId); + TravelController.LOGGER.info("[getRouteByTripId][Get Route By Trip ID][TripId: {}]", tripId); //Route return ok(travelService.getRouteByTripId(tripId, headers)); } @@ -53,7 +59,7 @@ public HttpEntity getRouteByTripId(@PathVariable String tripId, public HttpEntity getTripsByRouteId(@RequestBody ArrayList routeIds, @RequestHeader HttpHeaders headers) { // ArrayList> - TravelController.LOGGER.info("Get Trips by Route ids,RouteIds: {}", routeIds.size()); + TravelController.LOGGER.info("[getTripByRoute][Get Trips by Route ids][RouteIds: {}]", routeIds.size()); return ok(travelService.getTripByRoute(routeIds, headers)); } @@ -61,7 +67,7 @@ public HttpEntity getTripsByRouteId(@RequestBody ArrayList routeIds, @PostMapping(value = "/trips") public HttpEntity createTrip(@RequestBody TravelInfo routeIds, @RequestHeader HttpHeaders headers) { // null - TravelController.LOGGER.info("Create trip,TripId: {}", routeIds.getTripId()); + TravelController.LOGGER.info("[create][Create trip][TripId: {}]", routeIds.getTripId()); return new ResponseEntity<>(travelService.create(routeIds, headers), HttpStatus.CREATED); } @@ -76,7 +82,7 @@ public HttpEntity createTrip(@RequestBody TravelInfo routeIds, @RequestHeader @GetMapping(value = "/trips/{tripId}") public HttpEntity retrieve(@PathVariable String tripId, @RequestHeader HttpHeaders headers) { // Trip - TravelController.LOGGER.info("Retrieve trip,TripId: {}", tripId); + TravelController.LOGGER.info("[retrieve][Retrieve trip][TripId: {}]", tripId); return ok(travelService.retrieve(tripId, headers)); } @@ -84,7 +90,7 @@ public HttpEntity retrieve(@PathVariable String tripId, @RequestHeader HttpHeade @PutMapping(value = "/trips") public HttpEntity updateTrip(@RequestBody TravelInfo info, @RequestHeader HttpHeaders headers) { // Trip - TravelController.LOGGER.info("Update trip,TripId: {}", info.getTripId()); + TravelController.LOGGER.info("[update][Update trip][TripId: {}]", info.getTripId()); return ok(travelService.update(info, headers)); } @@ -92,7 +98,7 @@ public HttpEntity updateTrip(@RequestBody TravelInfo info, @RequestHeader HttpHe @DeleteMapping(value = "/trips/{tripId}") public HttpEntity deleteTrip(@PathVariable String tripId, @RequestHeader HttpHeaders headers) { // string - TravelController.LOGGER.info("Delete trip,TripId: {}", tripId); + TravelController.LOGGER.info("[delete][Delete trip][TripId: {}]", tripId); return ok(travelService.delete(tripId, headers)); } @@ -106,15 +112,15 @@ public HttpEntity deleteTrip(@PathVariable String tripId, @RequestHeader HttpHea @CrossOrigin(origins = "*") @PostMapping(value = "/trips/left") public HttpEntity queryInfo(@RequestBody TripInfo info, @RequestHeader HttpHeaders headers) { - if (info.getStartingPlace() == null || info.getStartingPlace().length() == 0 || + if (info.getStartPlace() == null || info.getStartPlace().length() == 0 || info.getEndPlace() == null || info.getEndPlace().length() == 0 || info.getDepartureTime() == null) { - TravelController.LOGGER.info("[[Travel Query] Fail.Something null."); + TravelController.LOGGER.info("[query][Travel Query Fail][Something null]"); ArrayList errorList = new ArrayList<>(); return ok(errorList); } - TravelController.LOGGER.info(" Query TripResponse"); - return ok(travelService.query(info, headers)); + TravelController.LOGGER.info("[query][Query TripResponse]"); + return ok(travelService.queryByBatch(info, headers)); } /** @@ -127,14 +133,14 @@ public HttpEntity queryInfo(@RequestBody TripInfo info, @RequestHeader HttpHeade @CrossOrigin(origins = "*") @PostMapping(value = "/trips/left_parallel") public HttpEntity queryInfoInparallel(@RequestBody TripInfo info, @RequestHeader HttpHeaders headers) { - if (info.getStartingPlace() == null || info.getStartingPlace().length() == 0 || + if (info.getStartPlace() == null || info.getStartPlace().length() == 0 || info.getEndPlace() == null || info.getEndPlace().length() == 0 || info.getDepartureTime() == null) { - TravelController.LOGGER.info("[[Travel Query] Fail.Something null."); + TravelController.LOGGER.info("[queryInParallel][Travel Query Fail][Something null]"); ArrayList errorList = new ArrayList<>(); return ok(errorList); } - TravelController.LOGGER.info(" Query TripResponse"); + TravelController.LOGGER.info("[queryInParallel][Query TripResponse]"); return ok(travelService.queryInParallel(info, headers)); } @@ -150,7 +156,7 @@ public HttpEntity queryInfoInparallel(@RequestBody TripInfo info, @RequestHeader public HttpEntity getTripAllDetailInfo(@RequestBody TripAllDetailInfo gtdi, @RequestHeader HttpHeaders headers) { // TripAllDetailInfo // TripAllDetail tripAllDetail - TravelController.LOGGER.info("Get trip detail,TripId: {}", gtdi.getTripId()); + TravelController.LOGGER.info("[getTripAllDetailInfo][Get trip detail][TripId: {}]", gtdi.getTripId()); return ok(travelService.getTripAllDetailInfo(gtdi, headers)); } @@ -158,7 +164,7 @@ public HttpEntity getTripAllDetailInfo(@RequestBody TripAllDetailInfo gtdi, @Req @GetMapping(value = "/trips") public HttpEntity queryAll(@RequestHeader HttpHeaders headers) { // List - TravelController.LOGGER.info("Query all trips"); + TravelController.LOGGER.info("[queryAll][Query all trips]"); return ok(travelService.queryAll(headers)); } @@ -166,7 +172,7 @@ public HttpEntity queryAll(@RequestHeader HttpHeaders headers) { @GetMapping(value = "/admin_trip") public HttpEntity adminQueryAll(@RequestHeader HttpHeaders headers) { // ArrayList - TravelController.LOGGER.info("Admin query all trips"); + TravelController.LOGGER.info("[adminQueryAll][Admin query all trips]"); return ok(travelService.adminQueryAll(headers)); } diff --git a/ts-travel-service/src/main/java/travel/entity/AdminTrip.java b/ts-travel-service/src/main/java/travel/entity/AdminTrip.java index 861850dbb..55fcbebab 100644 --- a/ts-travel-service/src/main/java/travel/entity/AdminTrip.java +++ b/ts-travel-service/src/main/java/travel/entity/AdminTrip.java @@ -1,7 +1,10 @@ package travel.entity; +import edu.fudan.common.entity.TrainType; +import edu.fudan.common.entity.Route; import lombok.Data; + /** * @author fdse */ diff --git a/ts-travel-service/src/main/java/travel/entity/Route.java b/ts-travel-service/src/main/java/travel/entity/Route.java deleted file mode 100644 index 57aaf7ddb..000000000 --- a/ts-travel-service/src/main/java/travel/entity/Route.java +++ /dev/null @@ -1,37 +0,0 @@ -package travel.entity; - -import lombok.Data; - -import java.util.List; - -/** - * @author fdse - */ -@Data -public class Route { - - private String id; - - private List stations; - - private List distances; - - private String startStationId; - - private String terminalStationId; - - public Route() { - //Default Constructor - } - - @Override - public String toString() { - return "Route{" + - "id='" + id + '\'' + - ", stations=" + stations + - ", distances=" + distances + - ", startStationId='" + startStationId + '\'' + - ", terminalStationId='" + terminalStationId + '\'' + - '}'; - } -} diff --git a/ts-travel-service/src/main/java/travel/entity/Seat.java b/ts-travel-service/src/main/java/travel/entity/Seat.java deleted file mode 100644 index 131710c07..000000000 --- a/ts-travel-service/src/main/java/travel/entity/Seat.java +++ /dev/null @@ -1,54 +0,0 @@ -package travel.entity; - -import lombok.Data; - -import javax.validation.Valid; -import javax.validation.constraints.NotNull; -import java.util.Date; - -/** - * @author fdse - */ -@Data -public class Seat { - @Valid - @NotNull - private Date travelDate; - - @Valid - @NotNull - private String trainNumber; - - - @Valid - @NotNull - private String startStation; - - @Valid - @NotNull - private String destStation; - - @Valid - @NotNull - private int seatType; - - public Seat(){ - //Default Constructor - this.travelDate = new Date(); - this.trainNumber = ""; - this.startStation = ""; - this.destStation = ""; - this.seatType = 0; - } - - @Override - public String toString() { - return "Seat{" + - "travelDate=" + travelDate + - ", trainNumber='" + trainNumber + '\'' + - ", startStation='" + startStation + '\'' + - ", destStation='" + destStation + '\'' + - ", seatType=" + seatType + - '}'; - } -} diff --git a/ts-travel-service/src/main/java/travel/entity/SeatClass.java b/ts-travel-service/src/main/java/travel/entity/SeatClass.java deleted file mode 100644 index de8d47d24..000000000 --- a/ts-travel-service/src/main/java/travel/entity/SeatClass.java +++ /dev/null @@ -1,70 +0,0 @@ -package travel.entity; - -/** - * @author fdse - */ -public enum SeatClass { - - /** - * no seat - */ - NONE (0,"NoSeat"), - /** - * green seat - */ - BUSINESS (1,"GreenSeat"), - /** - * first class seat - */ - FIRSTCLASS (2,"FirstClassSeat"), - /** - * second class seat - */ - SECONDCLASS (3,"SecondClassSeat"), - /** - * hard seat - */ - HARDSEAT (4,"HardSeat"), - /** - * hard seat - */ - SOFTSEAT (5,"SoftSeat"), - /** - * hard bed - */ - HARDBED (6,"HardBed"), - /** - * soft bed - */ - SOFTBED (7,"SoftBed"), - /** - * high soft seat - */ - HIGHSOFTBED (8,"HighSoftSeat"); - - private int code; - private String name; - - SeatClass(int code, String name){ - this.code = code; - this.name = name; - } - - public int getCode(){ - return code; - } - - public String getName() { - return name; - } - - public static String getNameByCode(int code){ - SeatClass[] seatClassSet = SeatClass.values(); - for(SeatClass seatClass : seatClassSet){ - if(seatClass.getCode() == code){ - return seatClass.getName(); - } - } - return seatClassSet[0].getName(); - } -} diff --git a/ts-travel-service/src/main/java/travel/entity/TrainType.java b/ts-travel-service/src/main/java/travel/entity/TrainType.java deleted file mode 100644 index 4d94749f0..000000000 --- a/ts-travel-service/src/main/java/travel/entity/TrainType.java +++ /dev/null @@ -1,44 +0,0 @@ -package travel.entity; - -import lombok.Data; -import org.springframework.data.annotation.Id; -import org.springframework.data.mongodb.core.mapping.Document; - -import javax.validation.Valid; - -/** - * @author fdse - */ -@Data -@Document(collection="trainType") -public class TrainType { - @Valid - @Id - private String id; - - @Valid - private int economyClass; - - @Valid - private int confortClass; - - private int averageSpeed; - - public TrainType(){ - //Default Constructor - } - - public TrainType(String id, int economyClass, int confortClass) { - this.id = id; - this.economyClass = economyClass; - this.confortClass = confortClass; - } - - public TrainType(String id, int economyClass, int confortClass, int averageSpeed) { - this.id = id; - this.economyClass = economyClass; - this.confortClass = confortClass; - this.averageSpeed = averageSpeed; - } - -} diff --git a/ts-travel-service/src/main/java/travel/entity/Travel.java b/ts-travel-service/src/main/java/travel/entity/Travel.java index b9d5bac13..754099278 100644 --- a/ts-travel-service/src/main/java/travel/entity/Travel.java +++ b/ts-travel-service/src/main/java/travel/entity/Travel.java @@ -1,7 +1,11 @@ package travel.entity; + +import edu.fudan.common.util.StringUtils; import lombok.Data; +import travel.entity.Trip; + import java.util.Date; /** @@ -12,11 +16,11 @@ public class Travel { private Trip trip; - private String startingPlace; + private String startPlace; private String endPlace; - private Date departureTime; + private String departureTime; public Travel(){ //Default Constructor diff --git a/ts-travel-service/src/main/java/travel/entity/TravelInfo.java b/ts-travel-service/src/main/java/travel/entity/TravelInfo.java deleted file mode 100644 index 9916e304a..000000000 --- a/ts-travel-service/src/main/java/travel/entity/TravelInfo.java +++ /dev/null @@ -1,33 +0,0 @@ -package travel.entity; - -import lombok.Data; - -import java.util.Date; - -/** - * @author fdse - */ -@Data -public class TravelInfo { - - private String tripId; - - private String trainTypeId; - - private String routeId; - - private String startingStationId; - - private String stationsId; - - private String terminalStationId; - - private Date startingTime; - - private Date endTime; - - public TravelInfo() { - //Default Constructor - } - -} diff --git a/ts-travel-service/src/main/java/travel/entity/TravelResult.java b/ts-travel-service/src/main/java/travel/entity/TravelResult.java deleted file mode 100644 index 389b510ff..000000000 --- a/ts-travel-service/src/main/java/travel/entity/TravelResult.java +++ /dev/null @@ -1,26 +0,0 @@ -package travel.entity; - -import java.util.Map; -import lombok.*; - -/** - * @author fdse - */ -@Data -public class TravelResult { - - private boolean status; - - private double percent; - - private TrainType trainType; - - private Map prices; - - private String message; - - public TravelResult() { - //Default Constructor - } - -} diff --git a/ts-travel-service/src/main/java/travel/entity/Trip.java b/ts-travel-service/src/main/java/travel/entity/Trip.java index 15910702a..dbbffa239 100644 --- a/ts-travel-service/src/main/java/travel/entity/Trip.java +++ b/ts-travel-service/src/main/java/travel/entity/Trip.java @@ -1,71 +1,86 @@ package travel.entity; +import edu.fudan.common.entity.TripId; +import edu.fudan.common.util.StringUtils; import lombok.Data; -import org.springframework.data.annotation.Id; -import org.springframework.data.mongodb.core.mapping.Document; +import org.hibernate.annotations.GenericGenerator; + +import javax.persistence.*; import javax.validation.Valid; import javax.validation.constraints.NotNull; import java.util.Date; +import java.util.UUID; /** * @author fdse */ @Data -@Document(collection="trip") +@Entity +@GenericGenerator(name = "jpa-uuid", strategy = "org.hibernate.id.UUIDGenerator") public class Trip { @Valid @Id + @GeneratedValue(generator = "jpa-uuid") + @Column(length = 36) + private String id; + + @Embedded private TripId tripId; @Valid @NotNull - private String trainTypeId; + private String trainTypeName; private String routeId; - private Date startingTime; @Valid @NotNull - private String startingStationId; + private String startStationName; @Valid - private String stationsId; + private String stationsName; + + @Valid + @NotNull + private String terminalStationName; @Valid @NotNull - private String terminalStationId; + private String startTime; @Valid @NotNull - private Date endTime; + private String endTime; - public Trip(TripId tripId, String trainTypeId, String startingStationId, String stationsId, String terminalStationId, Date startingTime, Date endTime) { + public Trip(edu.fudan.common.entity.TripId tripId, String trainTypeName, String startStationName, String stationsName, String terminalStationName, String startTime, String endTime) { this.tripId = tripId; - this.trainTypeId = trainTypeId; - this.startingStationId = startingStationId; - this.stationsId = stationsId; - this.terminalStationId = terminalStationId; - this.startingTime = startingTime; + this.trainTypeName = trainTypeName; + this.startStationName = StringUtils.String2Lower(startStationName); + this.stationsName = StringUtils.String2Lower(stationsName); + this.terminalStationName = StringUtils.String2Lower(terminalStationName); + this.startTime = startTime; this.endTime = endTime; } - public Trip(TripId tripId, String trainTypeId, String routeId) { + public Trip(TripId tripId, String trainTypeName, String routeId) { this.tripId = tripId; - this.trainTypeId = trainTypeId; + this.trainTypeName = trainTypeName; this.routeId = routeId; - this.startingStationId = ""; - this.terminalStationId = ""; - this.endTime = new Date(); + this.startStationName = ""; + this.terminalStationName = ""; + this.startTime = ""; + this.endTime = ""; } public Trip(){ //Default Constructor - this.trainTypeId = ""; - this.startingStationId = ""; - this.terminalStationId = ""; - this.endTime = new Date(); + this.trainTypeName = ""; + this.startStationName = ""; + this.terminalStationName = ""; + this.startTime = ""; + this.endTime = ""; } -} +} \ No newline at end of file diff --git a/ts-travel-service/src/main/java/travel/entity/TripAllDetail.java b/ts-travel-service/src/main/java/travel/entity/TripAllDetail.java index 3f505c48c..b242d7cc4 100644 --- a/ts-travel-service/src/main/java/travel/entity/TripAllDetail.java +++ b/ts-travel-service/src/main/java/travel/entity/TripAllDetail.java @@ -1,7 +1,10 @@ package travel.entity; +import edu.fudan.common.entity.TripResponse; import lombok.Data; +import edu.fudan.common.entity.TripResponse; + /** * @author fdse */ diff --git a/ts-travel-service/src/main/java/travel/entity/TripAllDetailInfo.java b/ts-travel-service/src/main/java/travel/entity/TripAllDetailInfo.java deleted file mode 100644 index 07ac28612..000000000 --- a/ts-travel-service/src/main/java/travel/entity/TripAllDetailInfo.java +++ /dev/null @@ -1,25 +0,0 @@ -package travel.entity; - -import lombok.Data; - -import java.util.Date; - -/** - * @author fdse - */ -@Data -public class TripAllDetailInfo { - - private String tripId; - - private Date travelDate; - - private String from; - - private String to; - - public TripAllDetailInfo() { - //Default Constructor - } - -} diff --git a/ts-travel-service/src/main/java/travel/entity/TripId.java b/ts-travel-service/src/main/java/travel/entity/TripId.java deleted file mode 100644 index deae826d0..000000000 --- a/ts-travel-service/src/main/java/travel/entity/TripId.java +++ /dev/null @@ -1,44 +0,0 @@ -package travel.entity; - -import lombok.Data; - -import java.io.Serializable; - -/** - * @author fdse - */ -@Data -public class TripId implements Serializable { - private Type type; - private String number; - - public TripId(Type type, String number) { - this.type = type; - this.number = number; - } - - public TripId() { - //Default Constructor - } - - public TripId(String trainNumber) { - char type0 = trainNumber.charAt(0); - switch (type0) { - case 'G': - this.type = Type.G; - break; - case 'D': - this.type = Type.D; - break; - default: - break; - } - - this.number = trainNumber.substring(1); - } - - @Override - public String toString() { - return type.getName() + number; - } -} diff --git a/ts-travel-service/src/main/java/travel/entity/TripInfo.java b/ts-travel-service/src/main/java/travel/entity/TripInfo.java deleted file mode 100644 index 46708f86f..000000000 --- a/ts-travel-service/src/main/java/travel/entity/TripInfo.java +++ /dev/null @@ -1,36 +0,0 @@ -package travel.entity; - -import lombok.AllArgsConstructor; -import lombok.Data; - -import javax.validation.Valid; -import javax.validation.constraints.NotNull; -import java.util.Date; - -/** - * @author fdse - */ -@Data -@AllArgsConstructor -public class TripInfo { - - @Valid - @NotNull - private String startingPlace; - - @Valid - @NotNull - private String endPlace; - - @Valid - @NotNull - private Date departureTime; - - public TripInfo(){ - //Default Constructor - this.startingPlace = ""; - this.endPlace = ""; - this.departureTime = new Date(); - } - -} diff --git a/ts-travel-service/src/main/java/travel/entity/TripResponse.java b/ts-travel-service/src/main/java/travel/entity/TripResponse.java deleted file mode 100644 index 1551e358f..000000000 --- a/ts-travel-service/src/main/java/travel/entity/TripResponse.java +++ /dev/null @@ -1,37 +0,0 @@ -package travel.entity; - -import lombok.Data; - -import java.util.Date; - -/** - * @author fdse - */ -@Data -public class TripResponse { - - private TripId tripId; - - private String trainTypeId; - - private String startingStation; - - private String terminalStation; - - private Date startingTime; - - private Date endTime; - - private int economyClass; - - private int confortClass; - - private String priceForEconomyClass; - - private String priceForConfortClass; - - public TripResponse(){ - //Default Constructor - } - -} diff --git a/ts-travel-service/src/main/java/travel/entity/Type.java b/ts-travel-service/src/main/java/travel/entity/Type.java deleted file mode 100644 index fd762b579..000000000 --- a/ts-travel-service/src/main/java/travel/entity/Type.java +++ /dev/null @@ -1,51 +0,0 @@ -package travel.entity; - -import java.io.Serializable; - -/** - * @author fdse - */ -public enum Type implements Serializable{ - - /** - * G - */ - G("G", 1), - /** - * D - */ - D("D", 2); - - private String name; - private int index; - - Type(String name, int index) { - this.name = name; - this.index = index; - } - - public static String getName(int index) { - for (Type type : Type.values()) { - if (type.getIndex() == index) { - return type.name; - } - } - return null; - } - - public String getName() { - return name; - } - - void setName(String name) { - this.name = name; - } - - public int getIndex() { - return index; - } - - void setIndex(int index) { - this.index = index; - } -} diff --git a/ts-travel-service/src/main/java/travel/init/InitData.java b/ts-travel-service/src/main/java/travel/init/InitData.java index 5afe50dbd..ee9f020ad 100644 --- a/ts-travel-service/src/main/java/travel/init/InitData.java +++ b/ts-travel-service/src/main/java/travel/init/InitData.java @@ -1,9 +1,9 @@ package travel.init; +import edu.fudan.common.entity.TravelInfo; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.CommandLineRunner; import org.springframework.stereotype.Component; -import travel.entity.TravelInfo; import travel.service.TravelService; import java.util.Date; @@ -27,53 +27,53 @@ public void run(String... args)throws Exception{ TravelInfo info = new TravelInfo(); info.setTripId("G1234"); - info.setTrainTypeId(gaoTieOne); + info.setTrainTypeName(gaoTieOne); info.setRouteId("92708982-77af-4318-be25-57ccb0ff69ad"); - info.setStartingStationId(shanghai); - info.setStationsId(suzhou); - info.setTerminalStationId(taiyuan); - info.setStartingTime(new Date("Mon May 04 09:00:00 GMT+0800 2013")); //NOSONAR - info.setEndTime(new Date("Mon May 04 15:51:52 GMT+0800 2013")); //NOSONAR + info.setStartStationName(shanghai); + info.setStationsName(suzhou); + info.setTerminalStationName(taiyuan); + info.setStartTime("2013-05-04 09:00:00"); //NOSONAR + info.setEndTime("2013-05-04 15:51:52"); //NOSONAR service.create(info,null); info.setTripId("G1235"); - info.setTrainTypeId(gaoTieOne); + info.setTrainTypeName(gaoTieOne); info.setRouteId("aefcef3f-3f42-46e8-afd7-6cb2a928bd3d"); - info.setStartingStationId(shanghai); - info.setStationsId(suzhou); - info.setTerminalStationId(taiyuan); - info.setStartingTime(new Date("Mon May 04 12:00:00 GMT+0800 2013")); //NOSONAR - info.setEndTime(new Date("Mon May 04 17:51:52 GMT+0800 2013")); //NOSONAR + info.setStartStationName(shanghai); + info.setStationsName(suzhou); + info.setTerminalStationName(taiyuan); + info.setStartTime("2013-05-04 12:00:00"); //NOSONAR + info.setEndTime("2013-05-04 17:51:52"); //NOSONAR service.create(info,null); info.setTripId("G1236"); - info.setTrainTypeId(gaoTieOne); + info.setTrainTypeName(gaoTieOne); info.setRouteId("a3f256c1-0e43-4f7d-9c21-121bf258101f"); - info.setStartingStationId(shanghai); - info.setStationsId(suzhou); - info.setTerminalStationId(taiyuan); - info.setStartingTime(new Date("Mon May 04 14:00:00 GMT+0800 2013")); //NOSONAR - info.setEndTime(new Date("Mon May 04 20:51:52 GMT+0800 2013")); //NOSONAR + info.setStartStationName(shanghai); + info.setStationsName(suzhou); + info.setTerminalStationName(taiyuan); + info.setStartTime("2013-05-04 14:00:00"); //NOSONAR + info.setEndTime("2013-05-04 20:51:52"); //NOSONAR service.create(info,null); info.setTripId("G1237"); - info.setTrainTypeId("GaoTieTwo"); + info.setTrainTypeName("GaoTieTwo"); info.setRouteId("084837bb-53c8-4438-87c8-0321a4d09917"); - info.setStartingStationId(shanghai); - info.setStationsId(suzhou); - info.setTerminalStationId(taiyuan); - info.setStartingTime(new Date("Mon May 04 08:00:00 GMT+0800 2013")); //NOSONAR - info.setEndTime(new Date("Mon May 04 17:21:52 GMT+0800 2013")); //NOSONAR + info.setStartStationName(shanghai); + info.setStationsName(suzhou); + info.setTerminalStationName(taiyuan); + info.setStartTime("2013-05-04 08:00:00"); //NOSONAR + info.setEndTime("2013-05-04 17:21:52"); //NOSONAR service.create(info,null); info.setTripId("D1345"); - info.setTrainTypeId("DongCheOne"); + info.setTrainTypeName("DongCheOne"); info.setRouteId("f3d4d4ef-693b-4456-8eed-59c0d717dd08"); - info.setStartingStationId(shanghai); - info.setStationsId(suzhou); - info.setTerminalStationId(taiyuan); - info.setStartingTime(new Date("Mon May 04 07:00:00 GMT+0800 2013")); //NOSONAR - info.setEndTime(new Date("Mon May 04 19:59:52 GMT+0800 2013")); //NOSONAR + info.setStartStationName(shanghai); + info.setStationsName(suzhou); + info.setTerminalStationName(taiyuan); + info.setStartTime("2013-05-04 07:00:00"); //NOSONAR + info.setEndTime("2013-05-04 19:59:52"); //NOSONAR service.create(info,null); } } diff --git a/ts-travel-service/src/main/java/travel/repository/TripRepository.java b/ts-travel-service/src/main/java/travel/repository/TripRepository.java index 5515c6447..b55e0475f 100644 --- a/ts-travel-service/src/main/java/travel/repository/TripRepository.java +++ b/ts-travel-service/src/main/java/travel/repository/TripRepository.java @@ -1,15 +1,17 @@ package travel.repository; +import edu.fudan.common.entity.TripId; import org.springframework.data.repository.CrudRepository; +import org.springframework.stereotype.Repository; import travel.entity.Trip; -import travel.entity.TripId; import java.util.ArrayList; /** * @author fdse */ -public interface TripRepository extends CrudRepository { +@Repository +public interface TripRepository extends CrudRepository { Trip findByTripId(TripId tripId); @@ -19,4 +21,4 @@ public interface TripRepository extends CrudRepository { ArrayList findAll(); ArrayList findByRouteId(String routeId); -} +} \ No newline at end of file diff --git a/ts-travel-service/src/main/java/travel/service/TravelService.java b/ts-travel-service/src/main/java/travel/service/TravelService.java index b9d366551..0de5adb65 100644 --- a/ts-travel-service/src/main/java/travel/service/TravelService.java +++ b/ts-travel-service/src/main/java/travel/service/TravelService.java @@ -1,8 +1,11 @@ package travel.service; +import edu.fudan.common.entity.TravelInfo; +import edu.fudan.common.entity.TripAllDetailInfo; +import edu.fudan.common.entity.TripInfo; import edu.fudan.common.util.Response; import org.springframework.http.HttpHeaders; -import travel.entity.*; + import java.util.ArrayList; @@ -22,6 +25,8 @@ public interface TravelService { Response query(TripInfo info, HttpHeaders headers); + Response queryByBatch(TripInfo info, HttpHeaders headers); + Response queryInParallel(TripInfo info, HttpHeaders headers); Response getTripAllDetailInfo(TripAllDetailInfo gtdi, HttpHeaders headers); diff --git a/ts-travel-service/src/main/java/travel/service/TravelServiceImpl.java b/ts-travel-service/src/main/java/travel/service/TravelServiceImpl.java index 09012aa6a..8da82f99c 100644 --- a/ts-travel-service/src/main/java/travel/service/TravelServiceImpl.java +++ b/ts-travel-service/src/main/java/travel/service/TravelServiceImpl.java @@ -1,11 +1,16 @@ package travel.service; +import com.fasterxml.jackson.core.type.TypeReference; +import com.fasterxml.jackson.databind.ObjectMapper; +import edu.fudan.common.entity.*; import edu.fudan.common.util.JsonUtils; import edu.fudan.common.util.Response; +import edu.fudan.common.util.StringUtils; import org.apache.skywalking.apm.toolkit.trace.TraceCrossThread; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.cloud.client.discovery.DiscoveryClient; import org.springframework.core.ParameterizedTypeReference; import org.springframework.http.HttpEntity; import org.springframework.http.HttpHeaders; @@ -14,9 +19,13 @@ import org.springframework.scheduling.concurrent.CustomizableThreadFactory; import org.springframework.stereotype.Service; import org.springframework.web.client.RestTemplate; -import travel.entity.*; +import travel.entity.AdminTrip; +import travel.entity.Travel; +import travel.entity.Trip; +import travel.entity.TripAllDetail; import travel.repository.TripRepository; +import javax.transaction.Transactional; import java.util.*; import java.util.concurrent.*; @@ -32,10 +41,17 @@ public class TravelServiceImpl implements TravelService { @Autowired private RestTemplate restTemplate; + @Autowired + private DiscoveryClient discoveryClient; + private static final Logger LOGGER = LoggerFactory.getLogger(TravelServiceImpl.class); private static final ExecutorService executorService = Executors.newFixedThreadPool(20, new CustomizableThreadFactory("HttpClientThreadPool-")); + private String getServiceUrl(String serviceName) { + return "http://" + serviceName; + } + String success = "Success"; String noContent = "No Content"; @@ -43,13 +59,13 @@ public class TravelServiceImpl implements TravelService { public Response create(TravelInfo info, HttpHeaders headers) { TripId ti = new TripId(info.getTripId()); if (repository.findByTripId(ti) == null) { - Trip trip = new Trip(ti, info.getTrainTypeId(), info.getStartingStationId(), - info.getStationsId(), info.getTerminalStationId(), info.getStartingTime(), info.getEndTime()); + Trip trip = new Trip(ti, info.getTrainTypeName(), info.getStartStationName(), + info.getStationsName(), info.getTerminalStationName(), info.getStartTime(), info.getEndTime()); trip.setRouteId(info.getRouteId()); repository.save(trip); return new Response<>(1, "Create trip:" + ti.toString() + ".", null); } else { - TravelServiceImpl.LOGGER.error("Create trip error.Trip already exists,TripId: {}", info.getTripId()); + TravelServiceImpl.LOGGER.error("[create][Create trip error][Trip already exists][TripId: {}]", info.getTripId()); return new Response<>(1, "Trip " + info.getTripId().toString() + " already exists", null); } } @@ -63,13 +79,13 @@ public Response getRouteByTripId(String tripId, HttpHeaders headers) { if (trip != null) { route = getRouteByRouteId(trip.getRouteId(), headers); } else { - TravelServiceImpl.LOGGER.error("Get route by Trip id error.Trip not found, TripId: {}", tripId); + TravelServiceImpl.LOGGER.error("[getRouteByTripId][Get route by Trip id error][Trip not found][TripId: {}]", tripId); } } if (route != null) { return new Response<>(1, success, route); } else { - TravelServiceImpl.LOGGER.error("Get route by Trip id error.Route not found, TripId: {}", tripId); + TravelServiceImpl.LOGGER.error("[getRouteByTripId][Get route by Trip id error][Route not found][TripId: {}]", tripId); return new Response<>(0, noContent, null); } } @@ -80,14 +96,14 @@ public Response getTrainTypeByTripId(String tripId, HttpHeaders headers) { TrainType trainType = null; Trip trip = repository.findByTripId(tripId1); if (trip != null) { - trainType = getTrainType(trip.getTrainTypeId(), headers); + trainType = getTrainTypeByName(trip.getTrainTypeName(), headers); } else { - TravelServiceImpl.LOGGER.error("Get Train Type by Trip id error.Trip not found, TripId: {}", tripId); + TravelServiceImpl.LOGGER.error("[getTrainTypeByTripId][Get Train Type by Trip id error][Trip not found][TripId: {}]", tripId); } if (trainType != null) { return new Response<>(1, success, trainType); } else { - TravelServiceImpl.LOGGER.error("Get Train Type by Trip id error.Train Type not found, TripId: {}", tripId); + TravelServiceImpl.LOGGER.error("[getTrainTypeByTripId][Get Train Type by Trip id error][Train Type not found][TripId: {}]", tripId); return new Response<>(0, noContent, null); } } @@ -105,7 +121,7 @@ public Response getTripByRoute(ArrayList routeIds, HttpHeaders headers) if (!tripList.isEmpty()) { return new Response<>(1, success, tripList); } else { - TravelServiceImpl.LOGGER.warn("Get trips by routes warn.Trip list: {}", "No content"); + TravelServiceImpl.LOGGER.warn("[getTripByRoute][Get trips by routes warn][Trip list][{}]", "No content"); return new Response<>(0, noContent, null); } } @@ -118,7 +134,7 @@ public Response retrieve(String tripId, HttpHeaders headers) { if (trip != null) { return new Response<>(1, "Search Trip Success by Trip Id " + tripId, trip); } else { - TravelServiceImpl.LOGGER.error("Retrieve trip error.Trip not found,TripId: {}", tripId); + TravelServiceImpl.LOGGER.error("[retrieve][Retrieve trip error][Trip not found][TripId: {}]", tripId); return new Response<>(0, "No Content according to tripId" + tripId, null); } } @@ -126,26 +142,32 @@ public Response retrieve(String tripId, HttpHeaders headers) { @Override public Response update(TravelInfo info, HttpHeaders headers) { TripId ti = new TripId(info.getTripId()); - if (repository.findByTripId(ti) != null) { - Trip trip = new Trip(ti, info.getTrainTypeId(), info.getStartingStationId(), - info.getStationsId(), info.getTerminalStationId(), info.getStartingTime(), info.getEndTime()); - trip.setRouteId(info.getRouteId()); - repository.save(trip); - return new Response<>(1, "Update trip:" + ti.toString(), trip); + Trip t = repository.findByTripId(ti); + if (t != null) { + t.setStartStationName(info.getTrainTypeName()); + t.setStartStationName( info.getStartStationName()); + t.setStationsName(info.getStationsName()); + t.setTerminalStationName(info.getTerminalStationName()); + t.setStartTime(info.getStartTime()); + t.setEndTime(info.getEndTime()); + t.setRouteId(info.getRouteId()); + repository.save(t); + return new Response<>(1, "Update trip:" + ti.toString(), t); } else { - TravelServiceImpl.LOGGER.error("Update trip error.Trip not found,TripId: {}", info.getTripId()); + TravelServiceImpl.LOGGER.error("[update][Update trip error][Trip not found][TripId: {}]", info.getTripId()); return new Response<>(1, "Trip" + info.getTripId().toString() + "doesn 't exists", null); } } @Override + @Transactional public Response delete(String tripId, HttpHeaders headers) { TripId ti = new TripId(tripId); if (repository.findByTripId(ti) != null) { repository.deleteByTripId(ti); return new Response<>(1, "Delete trip:" + tripId + ".", tripId); } else { - TravelServiceImpl.LOGGER.error("Delete trip error.Trip not found,TripId: {}", tripId); + TravelServiceImpl.LOGGER.error("[delete][Delete trip error][Trip not found][TripId: {}]", tripId); return new Response<>(0, "Trip " + tripId + " doesn't exist.", null); } } @@ -154,69 +176,78 @@ public Response delete(String tripId, HttpHeaders headers) { public Response query(TripInfo info, HttpHeaders headers) { //Gets the start and arrival stations of the train number to query. The originating and arriving stations received here are both station names, so two requests need to be sent to convert to station ids - String startingPlaceName = info.getStartingPlace(); + String startPlaceName = info.getStartPlace(); String endPlaceName = info.getEndPlace(); - String startingPlaceId = queryForStationId(startingPlaceName, headers); - String endPlaceId = queryForStationId(endPlaceName, headers); //This is the final result List list = new ArrayList<>(); //Check all train info List allTripList = repository.findAll(); - for (Trip tempTrip : allTripList) { - //Get the detailed route list of this train - Route tempRoute = getRouteByRouteId(tempTrip.getRouteId(), headers); - //Check the route list for this train. Check that the required start and arrival stations are in the list of stops that are not on the route, and check that the location of the start station is before the stop - //Trains that meet the above criteria are added to the return list - if (tempRoute.getStations().contains(startingPlaceId) && - tempRoute.getStations().contains(endPlaceId) && - tempRoute.getStations().indexOf(startingPlaceId) < tempRoute.getStations().indexOf(endPlaceId)) { - TripResponse response = getTickets(tempTrip, tempRoute, startingPlaceId, endPlaceId, startingPlaceName, endPlaceName, info.getDepartureTime(), headers); + if(allTripList != null) { + for (Trip tempTrip : allTripList) { + //Get the detailed route list of this train + TripResponse response = getTickets(tempTrip, null, startPlaceName, endPlaceName, info.getDepartureTime(), headers); if (response == null) { - TravelServiceImpl.LOGGER.warn("Query trip error.Tickets not found,start: {},end: {},time: {}", startingPlaceName, endPlaceName, info.getDepartureTime()); - return new Response<>(0, "No Trip info content", null); + TravelServiceImpl.LOGGER.warn("[query][Query trip error][Tickets not found][start: {},end: {},time: {}]", startPlaceName, endPlaceName, info.getDepartureTime()); + }else{ + list.add(response); } - list.add(response); } } return new Response<>(1, success, list); } + + + @Override + public Response queryByBatch(TripInfo info, HttpHeaders headers) { + + //Gets the start and arrival stations of the train number to query. The originating and arriving stations received here are both station names, so two requests need to be sent to convert to station ids + String startPlaceName = info.getStartPlace(); + String endPlaceName = info.getEndPlace(); + + //This is the final result + List list = new ArrayList<>(); + + //Check all train info + List allTripList = repository.findAll(); + list = getTicketsByBatch(allTripList, startPlaceName, endPlaceName, info.getDepartureTime(), headers); + return new Response<>(1, success, list); + } + @TraceCrossThread class MyCallable implements Callable { private TripInfo info; private Trip tempTrip; private HttpHeaders headers; - private String startingPlaceId; - private String endPlaceId; + private String startPlaceName; + private String endPlaceName; - MyCallable(TripInfo info, String startingPlaceId, String endPlaceId, Trip tempTrip, HttpHeaders headers) { + MyCallable(TripInfo info, String startPlaceName, String endPlaceName, Trip tempTrip, HttpHeaders headers) { this.info = info; this.tempTrip = tempTrip; this.headers = headers; - this.startingPlaceId = startingPlaceId; - this.endPlaceId = endPlaceId; + this.startPlaceName = startPlaceName; + this.endPlaceName = endPlaceName; } @Override public TripResponse call() throws Exception { - TravelServiceImpl.LOGGER.info("tripId: [{}], routeId: [{}]. Start to query", tempTrip.getTripId().toString(), tempTrip.getRouteId()); + TravelServiceImpl.LOGGER.debug("[call][Start to query][tripId: {}, routeId: {}] ", tempTrip.getTripId().toString(), tempTrip.getRouteId()); - String startingPlaceName = info.getStartingPlace(); + String startPlaceName = info.getStartPlace(); String endPlaceName = info.getEndPlace(); - Route tempRoute = getRouteByRouteId(tempTrip.getRouteId(), headers); + //Route tempRoute = getRouteByRouteId(tempTrip.getRouteId(), headers); TripResponse response = null; - if (tempRoute.getStations().contains(startingPlaceId) && - tempRoute.getStations().contains(endPlaceId) && - tempRoute.getStations().indexOf(startingPlaceId) < tempRoute.getStations().indexOf(endPlaceId)) { - response = getTickets(tempTrip, tempRoute, startingPlaceId, endPlaceId, startingPlaceName, endPlaceName, info.getDepartureTime(), headers); - } + + response = getTickets(tempTrip, null, startPlaceName, endPlaceName, info.getDepartureTime(), headers); + if (response == null) { - TravelServiceImpl.LOGGER.warn("tripId: [{}], routeId: [{}]. Query trip error. Tickets not found,start: {},end: {},time: {}", tempTrip.getTripId().toString(), tempTrip.getRouteId(), startingPlaceName, endPlaceName, info.getDepartureTime()); + TravelServiceImpl.LOGGER.warn("[call][Query trip error][Tickets not found][tripId: {}, routeId: {}, start: {}, end: {},time: {}]", tempTrip.getTripId().toString(), tempTrip.getRouteId(), startPlaceName, endPlaceName, info.getDepartureTime()); } else { - TravelServiceImpl.LOGGER.info("tripId: [{}], routeId: [{}]. Query success", tempTrip.getTripId().toString(), tempTrip.getRouteId()); + TravelServiceImpl.LOGGER.info("[call][Query trip success][tripId: {}, routeId: {}] ", tempTrip.getTripId().toString(), tempTrip.getRouteId()); } return response; } @@ -225,10 +256,8 @@ public TripResponse call() throws Exception { @Override public Response queryInParallel(TripInfo info, HttpHeaders headers) { //Gets the start and arrival stations of the train number to query. The originating and arriving stations received here are both station names, so two requests need to be sent to convert to station ids - String startingPlaceName = info.getStartingPlace(); + String startPlaceName = info.getStartPlace(); String endPlaceName = info.getEndPlace(); - String startingPlaceId = queryForStationId(startingPlaceName, headers); - String endPlaceId = queryForStationId(endPlaceName, headers); //This is the final result List list = new ArrayList<>(); @@ -237,10 +266,12 @@ public Response queryInParallel(TripInfo info, HttpHeaders headers) { List allTripList = repository.findAll(); List> futureList = new ArrayList<>(); - for (Trip tempTrip : allTripList) { - MyCallable callable = new MyCallable(info, startingPlaceId, endPlaceId, tempTrip, headers); - Future future = executorService.submit(callable); - futureList.add(future); + if(allTripList != null ){ + for (Trip tempTrip : allTripList) { + MyCallable callable = new MyCallable(info, startPlaceName, endPlaceName, tempTrip, headers); + Future future = executorService.submit(callable); + futureList.add(future); + } } for (Future future : futureList) { @@ -250,7 +281,7 @@ public Response queryInParallel(TripInfo info, HttpHeaders headers) { list.add(response); } } catch (Exception e) { - TravelServiceImpl.LOGGER.error(e.toString()); + TravelServiceImpl.LOGGER.error("[queryInParallel][Query error]"+e.toString()); } } @@ -264,24 +295,22 @@ public Response queryInParallel(TripInfo info, HttpHeaders headers) { @Override public Response getTripAllDetailInfo(TripAllDetailInfo gtdi, HttpHeaders headers) { TripAllDetail gtdr = new TripAllDetail(); - TravelServiceImpl.LOGGER.info("[TripAllDetailInfo] TripId: {}", gtdi.getTripId()); + TravelServiceImpl.LOGGER.debug("[getTripAllDetailInfo][TripId: {}]", gtdi.getTripId()); Trip trip = repository.findByTripId(new TripId(gtdi.getTripId())); if (trip == null) { gtdr.setTripResponse(null); gtdr.setTrip(null); - TravelServiceImpl.LOGGER.error("Get trip detail error.Trip not found,TripId: {}", gtdi.getTripId()); + TravelServiceImpl.LOGGER.error("[getTripAllDetailInfo][Get trip detail error][Trip not found][TripId: {}]", gtdi.getTripId()); + return new Response<>(0, "Trip not found", gtdr); } else { - String startingPlaceName = gtdi.getFrom(); + String startPlaceName = gtdi.getFrom(); String endPlaceName = gtdi.getTo(); - String startingPlaceId = queryForStationId(startingPlaceName, headers); - String endPlaceId = queryForStationId(endPlaceName, headers); - Route tempRoute = getRouteByRouteId(trip.getRouteId(), headers); - - TripResponse tripResponse = getTickets(trip, tempRoute, startingPlaceId, endPlaceId, gtdi.getFrom(), gtdi.getTo(), gtdi.getTravelDate(), headers); + TripResponse tripResponse = getTickets(trip, null, startPlaceName, endPlaceName, gtdi.getTravelDate(), headers); if (tripResponse == null) { gtdr.setTripResponse(null); gtdr.setTrip(null); - TravelServiceImpl.LOGGER.warn("Get trip detail error.Tickets not found,start: {},end: {},time: {}", startingPlaceName, endPlaceName, gtdi.getTravelDate()); + TravelServiceImpl.LOGGER.warn("[getTripAllDetailInfo][Get trip detail error][Tickets not found][start: {},end: {},time: {}]", startPlaceName, endPlaceName, gtdi.getTravelDate()); + return new Response<>(0, "getTickets failed", gtdr); } else { gtdr.setTripResponse(tripResponse); gtdr.setTrip(repository.findByTripId(new TripId(gtdi.getTripId()))); @@ -290,83 +319,147 @@ public Response getTripAllDetailInfo(TripAllDetailInfo gtdi, HttpHeaders headers return new Response<>(1, success, gtdr); } - private TripResponse getTickets(Trip trip, Route route, String startingPlaceId, String endPlaceId, String startingPlaceName, String endPlaceName, Date departureTime, HttpHeaders headers) { + private List getTicketsByBatch(List trips, String startPlaceName, String endPlaceName, String departureTime, HttpHeaders headers) { + List responses = new ArrayList<>(); + //Determine if the date checked is the same day and after + if (!afterToday(departureTime)) { + TravelServiceImpl.LOGGER.info("[getTickets][depaturetime not vailid][departuretime: {}]", departureTime); + return responses; + } + + List infos = new ArrayList<>(); + Map tripMap = new HashMap<>(); + for(Trip trip: trips){ + Travel query = new Travel(); + query.setTrip(trip); + query.setStartPlace(startPlaceName); + query.setEndPlace(endPlaceName); + query.setDepartureTime(departureTime); + + infos.add(query); + tripMap.put(trip.getTripId().toString(), trip); + } + + TravelServiceImpl.LOGGER.info("[getTicketsByBatch][before get basic][trips: {}]", trips); + + HttpEntity requestEntity = new HttpEntity(infos, null); + String basic_service_url = getServiceUrl("ts-basic-service"); + ResponseEntity re = restTemplate.exchange( + basic_service_url + "/api/v1/basicservice/basic/travels", + HttpMethod.POST, + requestEntity, + Response.class); + + Response r = re.getBody(); + if(r.getStatus() == 0){ + TravelServiceImpl.LOGGER.info("[getTicketsByBatch][Ts-basic-service response status is 0][response is: {}]", r); + return responses; + } + Map trMap; + ObjectMapper mapper = new ObjectMapper(); + try{ + trMap = mapper.readValue(JsonUtils.object2Json(r.getData()), new TypeReference>(){}); + }catch(Exception e) { + TravelServiceImpl.LOGGER.warn("[getTicketsByBatch][Ts-basic-service convert data failed][Fail msg: {}]", e.getMessage()); + return responses; + } + + for(Map.Entry trEntry: trMap.entrySet()){ + //Set the returned ticket information + String tripNumber = trEntry.getKey(); + TravelResult tr = trEntry.getValue(); + Trip trip = tripMap.get(tripNumber); + + TripResponse response = setResponse(trip, tr, startPlaceName, endPlaceName, departureTime, headers); + responses.add(response); + } + return responses; + } + + private TripResponse getTickets(Trip trip, Route route1, String startPlaceName, String endPlaceName, String departureTime, HttpHeaders headers) { //Determine if the date checked is the same day and after if (!afterToday(departureTime)) { + TravelServiceImpl.LOGGER.info("[getTickets][depaturetime not vailid][departuretime: {}]", departureTime); return null; } Travel query = new Travel(); query.setTrip(trip); - query.setStartingPlace(startingPlaceName); + query.setStartPlace(startPlaceName); query.setEndPlace(endPlaceName); query.setDepartureTime(departureTime); + TravelServiceImpl.LOGGER.info("[getTickets][before get basic][trip: {}]", trip); HttpEntity requestEntity = new HttpEntity(query, null); + String basic_service_url = getServiceUrl("ts-basic-service"); ResponseEntity re = restTemplate.exchange( - "http://ts-ticketinfo-service:15681/api/v1/ticketinfoservice/ticketinfo", + basic_service_url + "/api/v1/basicservice/basic/travel", HttpMethod.POST, requestEntity, Response.class); - TravelServiceImpl.LOGGER.info("Ts-basic-service ticket info is: {}", re.getBody().toString()); - TravelResult resultForTravel = JsonUtils.conveterObject(re.getBody().getData(), TravelResult.class); - //Ticket order _ high-speed train (number of tickets purchased) - requestEntity = new HttpEntity(null); - ResponseEntity> re2 = restTemplate.exchange( - "http://ts-order-service:12031/api/v1/orderservice/order/" + departureTime + "/" + trip.getTripId().toString(), - HttpMethod.GET, - requestEntity, - new ParameterizedTypeReference>() { - }); + Response r = re.getBody(); + if(r.getStatus() == 0){ + TravelServiceImpl.LOGGER.info("[getTickets][Ts-basic-service response status is 0][response is: {}]", r); + return null; + } - Response result = re2.getBody(); - TravelServiceImpl.LOGGER.info("Order info is: {}", result.toString()); + TravelResult resultForTravel = JsonUtils.conveterObject(re.getBody().getData(), TravelResult.class); + //Set the returned ticket information + return setResponse(trip, resultForTravel, startPlaceName, endPlaceName, departureTime, headers); + } + private TripResponse setResponse(Trip trip, TravelResult tr, String startPlaceName, String endPlaceName, String departureTime, HttpHeaders headers){ //Set the returned ticket information TripResponse response = new TripResponse(); response.setConfortClass(50); response.setEconomyClass(50); + Route route = tr.getRoute(); + List stationList = route.getStations(); + + int firstClassTotalNum = tr.getTrainType().getConfortClass(); + int secondClassTotalNum = tr.getTrainType().getEconomyClass(); + int first = getRestTicketNumber(departureTime, trip.getTripId().toString(), - startingPlaceName, endPlaceName, SeatClass.FIRSTCLASS.getCode(), headers); + startPlaceName, endPlaceName, SeatClass.FIRSTCLASS.getCode(), firstClassTotalNum, stationList, headers); int second = getRestTicketNumber(departureTime, trip.getTripId().toString(), - startingPlaceName, endPlaceName, SeatClass.SECONDCLASS.getCode(), headers); + startPlaceName, endPlaceName, SeatClass.SECONDCLASS.getCode(), secondClassTotalNum, stationList, headers); response.setConfortClass(first); response.setEconomyClass(second); - response.setStartingStation(startingPlaceName); + response.setStartStation(startPlaceName); response.setTerminalStation(endPlaceName); //Calculate the distance from the starting point - int indexStart = route.getStations().indexOf(startingPlaceId); - int indexEnd = route.getStations().indexOf(endPlaceId); + int indexStart = route.getStations().indexOf(startPlaceName); + int indexEnd = route.getStations().indexOf(endPlaceName); int distanceStart = route.getDistances().get(indexStart) - route.getDistances().get(0); int distanceEnd = route.getDistances().get(indexEnd) - route.getDistances().get(0); - TrainType trainType = getTrainType(trip.getTrainTypeId(), headers); + TrainType trainType = tr.getTrainType(); //Train running time is calculated according to the average running speed of the train int minutesStart = 60 * distanceStart / trainType.getAverageSpeed(); int minutesEnd = 60 * distanceEnd / trainType.getAverageSpeed(); Calendar calendarStart = Calendar.getInstance(); - calendarStart.setTime(trip.getStartingTime()); + calendarStart.setTime(StringUtils.String2Date(trip.getStartTime())); calendarStart.add(Calendar.MINUTE, minutesStart); - response.setStartingTime(calendarStart.getTime()); - TravelServiceImpl.LOGGER.info("calculate time:{} time: {}", minutesStart, calendarStart.getTime()); + response.setStartTime(StringUtils.Date2String(calendarStart.getTime())); + TravelServiceImpl.LOGGER.info("[getTickets][Calculate distance][calculate time:{} time: {}]", minutesStart, calendarStart.getTime()); Calendar calendarEnd = Calendar.getInstance(); - calendarEnd.setTime(trip.getStartingTime()); + calendarEnd.setTime(StringUtils.String2Date(trip.getStartTime())); calendarEnd.add(Calendar.MINUTE, minutesEnd); - response.setEndTime(calendarEnd.getTime()); - TravelServiceImpl.LOGGER.info("calculate time:{} time: {}", minutesEnd, calendarEnd.getTime()); + response.setEndTime(StringUtils.Date2String(calendarEnd.getTime())); + TravelServiceImpl.LOGGER.info("[getTickets][Calculate distance][calculate time:{} time: {}]", minutesEnd, calendarEnd.getTime()); - response.setTripId(new TripId(result.getData().getTrainNumber())); - response.setTrainTypeId(trip.getTrainTypeId()); - response.setPriceForConfortClass(resultForTravel.getPrices().get("confortClass")); - response.setPriceForEconomyClass(resultForTravel.getPrices().get("economyClass")); + response.setTripId(trip.getTripId()); + response.setTrainTypeName(trip.getTrainTypeName()); + response.setPriceForConfortClass(tr.getPrices().get("confortClass")); + response.setPriceForEconomyClass(tr.getPrices().get("economyClass")); return response; } @@ -375,19 +468,23 @@ private TripResponse getTickets(Trip trip, Route route, String startingPlaceId, public Response queryAll(HttpHeaders headers) { List tripList = repository.findAll(); if (tripList != null && !tripList.isEmpty()) { + TravelServiceImpl.LOGGER.info("[queryAll][Query all trips:][{}]", "tripList"); return new Response<>(1, success, tripList); } - TravelServiceImpl.LOGGER.warn("Query all trips warn: {}", "No Content"); + TravelServiceImpl.LOGGER.warn("[queryAll][Query all trips warn][{}]", "No Content"); return new Response<>(0, noContent, null); } - private static boolean afterToday(Date date) { + private static boolean afterToday(String date) { Calendar calDateA = Calendar.getInstance(); Date today = new Date(); calDateA.setTime(today); Calendar calDateB = Calendar.getInstance(); - calDateB.setTime(date); + calDateB.setTime(StringUtils.String2Date(date)); + + TravelServiceImpl.LOGGER.info("[today date][y: {}][m:{}][d: {}]",calDateA.get(Calendar.YEAR), calDateA.get(Calendar.MONTH), calDateA.get(Calendar.DATE)); + TravelServiceImpl.LOGGER.info("[departrue date][y: {}][m:{}][d: {}]",calDateB.get(Calendar.YEAR), calDateB.get(Calendar.MONTH), calDateB.get(Calendar.DATE)); if (calDateA.get(Calendar.YEAR) > calDateB.get(Calendar.YEAR)) { return false; @@ -404,10 +501,11 @@ private static boolean afterToday(Date date) { } } - private TrainType getTrainType(String trainTypeId, HttpHeaders headers) { + private TrainType getTrainTypeByName(String trainTypeName, HttpHeaders headers) { HttpEntity requestEntity = new HttpEntity(null); + String train_service_url = getServiceUrl("ts-train-service"); ResponseEntity> re = restTemplate.exchange( - "http://ts-train-service:14567/api/v1/trainservice/trains/" + trainTypeId, + train_service_url + "/api/v1/trainservice/trains/byName/" + trainTypeName, HttpMethod.GET, requestEntity, new ParameterizedTypeReference>() { @@ -416,60 +514,48 @@ private TrainType getTrainType(String trainTypeId, HttpHeaders headers) { return re.getBody().getData(); } - private String queryForStationId(String stationName, HttpHeaders headers) { - HttpEntity requestEntity = new HttpEntity(null); - ResponseEntity> re = restTemplate.exchange( - "http://ts-ticketinfo-service:15681/api/v1/ticketinfoservice/ticketinfo/" + stationName, - HttpMethod.GET, - requestEntity, - new ParameterizedTypeReference>() { - }); - TravelServiceImpl.LOGGER.info("Query for Station id is: {}", re.getBody().toString()); - - return re.getBody().getData(); - } - private Route getRouteByRouteId(String routeId, HttpHeaders headers) { - TravelServiceImpl.LOGGER.info("[Travel Service][Get Route By Id] Route ID:{}", routeId); + TravelServiceImpl.LOGGER.info("[getRouteByRouteId][Get Route By Id][Route ID:{}]", routeId); HttpEntity requestEntity = new HttpEntity(null); + String route_service_url = getServiceUrl("ts-route-service"); ResponseEntity re = restTemplate.exchange( - "http://ts-route-service:11178/api/v1/routeservice/routes/" + routeId, + route_service_url + "/api/v1/routeservice/routes/" + routeId, HttpMethod.GET, requestEntity, Response.class); Response routeRes = re.getBody(); Route route1 = new Route(); - TravelServiceImpl.LOGGER.info("Routes Response is : {}", routeRes.toString()); + TravelServiceImpl.LOGGER.info("[getRouteByRouteId][Get Route By Id][Routes Response is : {}]", routeRes.toString()); if (routeRes.getStatus() == 1) { route1 = JsonUtils.conveterObject(routeRes.getData(), Route.class); - TravelServiceImpl.LOGGER.info("Route is: {}", route1.toString()); + TravelServiceImpl.LOGGER.info("[getRouteByRouteId][Get Route By Id][Route is: {}]", route1.toString()); } return route1; } - private int getRestTicketNumber(Date travelDate, String trainNumber, String startStationName, String endStationName, int seatType, HttpHeaders headers) { + private int getRestTicketNumber(String travelDate, String trainNumber, String startStationName, String endStationName, int seatType, int totalNum, List stationList, HttpHeaders headers) { Seat seatRequest = new Seat(); - String fromId = queryForStationId(startStationName, headers); - String toId = queryForStationId(endStationName, headers); - - seatRequest.setDestStation(toId); - seatRequest.setStartStation(fromId); + seatRequest.setDestStation(endStationName); + seatRequest.setStartStation(startStationName); seatRequest.setTrainNumber(trainNumber); seatRequest.setTravelDate(travelDate); seatRequest.setSeatType(seatType); + seatRequest.setTotalNum(totalNum); + seatRequest.setStations(stationList); - TravelServiceImpl.LOGGER.info("Seat request To String: {}", seatRequest.toString()); + TravelServiceImpl.LOGGER.info("[getRestTicketNumber][Seat request][request: {}]", seatRequest.toString()); HttpEntity requestEntity = new HttpEntity(seatRequest, null); + String seat_service_url = getServiceUrl("ts-seat-service"); ResponseEntity> re = restTemplate.exchange( - "http://ts-seat-service:18898/api/v1/seatservice/seats/left_tickets", + seat_service_url + "/api/v1/seatservice/seats/left_tickets", HttpMethod.POST, requestEntity, new ParameterizedTypeReference>() { }); - TravelServiceImpl.LOGGER.info("Get Rest tickets num is: {}", re.getBody().toString()); + TravelServiceImpl.LOGGER.info("[getRestTicketNumber][Get Rest tickets num][num is: {}]", re.getBody().toString()); return re.getBody().getData(); } @@ -478,17 +564,20 @@ private int getRestTicketNumber(Date travelDate, String trainNumber, String star public Response adminQueryAll(HttpHeaders headers) { List trips = repository.findAll(); ArrayList adminTrips = new ArrayList<>(); - for (Trip trip : trips) { - AdminTrip adminTrip = new AdminTrip(); - adminTrip.setTrip(trip); - adminTrip.setRoute(getRouteByRouteId(trip.getRouteId(), headers)); - adminTrip.setTrainType(getTrainType(trip.getTrainTypeId(), headers)); - adminTrips.add(adminTrip); + if(trips != null){ + for (Trip trip : trips) { + AdminTrip adminTrip = new AdminTrip(); + adminTrip.setTrip(trip); + adminTrip.setRoute(getRouteByRouteId(trip.getRouteId(), headers)); + adminTrip.setTrainType(getTrainTypeByName(trip.getTrainTypeName(), headers)); + adminTrips.add(adminTrip); + } } + if (!adminTrips.isEmpty()) { return new Response<>(1, success, adminTrips); } else { - TravelServiceImpl.LOGGER.warn("Admin query all trips warn: {}", "No Content"); + TravelServiceImpl.LOGGER.warn("[adminQueryAll][Admin query all trips warn][{}]", "No Content"); return new Response<>(0, noContent, null); } } diff --git a/ts-travel-service/src/main/resources/application.yml b/ts-travel-service/src/main/resources/application.yml index a1ffa53d7..8425f1bd0 100644 --- a/ts-travel-service/src/main/resources/application.yml +++ b/ts-travel-service/src/main/resources/application.yml @@ -3,14 +3,39 @@ server: port: 12346 # HTTP (Tomcat) port spring: + cloud: + nacos: + discovery: + server-addr: ${NACOS_ADDRS:nacos-0.nacos-headless.default.svc.cluster.local,nacos-1.nacos-headless.default.svc.cluster.local,nacos-2.nacos-headless.default.svc.cluster.local} application: name: ts-travel-service - data: - mongodb: - host: ts-travel-mongo -# username: user -# password: ${MONGODB_PASSWORD} - database: ts - port: 27017 + datasource: + url: jdbc:mysql://${TRAVEL_MYSQL_HOST:ts-travel-mysql}:${TRAVEL_MYSQL_PORT:3306}/${TRAVEL_MYSQL_DATABASE:ts-travel-mysql}?useSSL=false + username: ${TRAVEL_MYSQL_USER:root} + password: ${TRAVEL_MYSQL_PASSWORD:root} + driver-class-name: com.mysql.cj.jdbc.Driver + + jpa: + hibernate: + ddl-auto: update + properties: + hibernate: + dialect: org.hibernate.dialect.MySQL5Dialect + swagger: - controllerPackage: travel.controller \ No newline at end of file + controllerPackage: travel.controller + +train-service: + url: http://${TRAIN_SERVICE_HOST:ts-train-service}:${TRAIN_SERVICE_PORT:14567} + +order-service: + url: http://${ORDER_SERVICE_HOST:ts-order-service}:${ORDER_SERVICE_PORT:12031} + +route-service: + url: http://${ROUTE_SERVICE_HOST:ts-route-service}:${ROUTE_SERVICE_PORT:11178} + +basic-service: + url: http://${BASIC_SERVICE_HOST:ts-basic-service}:${BASIC_SERVICE_PORT:15680} + +seat-service: + url: http://${SEAT_SERVICE_HOST:ts-seat-service}:${SEAT_SERVICE_PORT:18898} \ No newline at end of file diff --git a/ts-travel-service/src/test/java/travel/controller/TravelControllerTest.java b/ts-travel-service/src/test/java/travel/controller/TravelControllerTest.java index ba2d8d8a2..d99d9346c 100644 --- a/ts-travel-service/src/test/java/travel/controller/TravelControllerTest.java +++ b/ts-travel-service/src/test/java/travel/controller/TravelControllerTest.java @@ -1,6 +1,11 @@ package travel.controller; import com.alibaba.fastjson.JSONObject; +import edu.fudan.common.entity.*; +import edu.fudan.common.entity.TravelInfo; +import edu.fudan.common.entity.TripAllDetailInfo; +import edu.fudan.common.entity.TripInfo; +import edu.fudan.common.entity.TripResponse; import edu.fudan.common.util.Response; import org.junit.Assert; import org.junit.Before; @@ -16,7 +21,8 @@ import org.springframework.test.web.servlet.request.MockMvcRequestBuilders; import org.springframework.test.web.servlet.result.MockMvcResultMatchers; import org.springframework.test.web.servlet.setup.MockMvcBuilders; -import travel.entity.*; +import travel.entity.Travel; +import travel.entity.AdminTrip; import travel.service.TravelService; import java.util.ArrayList; @@ -128,7 +134,7 @@ public void testQueryInfo1() throws Exception { @Test public void testQueryInfo2() throws Exception { - TripInfo info = new TripInfo("startingPlace", "endPlace", new Date()); + TripInfo info = new TripInfo("startPlace", "endPlace", ""); Mockito.when(service.query(Mockito.any(TripInfo.class), Mockito.any(HttpHeaders.class))).thenReturn(response); String requestJson = JSONObject.toJSONString(info); String result = mockMvc.perform(MockMvcRequestBuilders.post("/api/v1/travelservice/trips/left").contentType(MediaType.APPLICATION_JSON).content(requestJson)) diff --git a/ts-travel-service/src/test/java/travel/service/TravelServiceImplTest.java b/ts-travel-service/src/test/java/travel/service/TravelServiceImplTest.java index a911432fc..08a2ce197 100644 --- a/ts-travel-service/src/test/java/travel/service/TravelServiceImplTest.java +++ b/ts-travel-service/src/test/java/travel/service/TravelServiceImplTest.java @@ -1,6 +1,8 @@ package travel.service; +import edu.fudan.common.entity.*; import edu.fudan.common.util.Response; +import edu.fudan.common.util.StringUtils; import org.junit.Assert; import org.junit.Before; import org.junit.Test; @@ -14,6 +16,7 @@ import org.springframework.http.*; import org.springframework.web.client.RestTemplate; import travel.entity.*; +import travel.entity.Trip; import travel.repository.TripRepository; import java.util.ArrayList; @@ -211,7 +214,7 @@ public void testGetTripAllDetailInfo() { gtdi.setTripId("Z1255"); gtdi.setFrom("from_station"); gtdi.setTo("to_station"); - gtdi.setTravelDate(new Date(System.currentTimeMillis() - 86400000)); + gtdi.setTravelDate(StringUtils.Date2String(new Date(System.currentTimeMillis() - 86400000))); Trip trip = new Trip(); trip.setRouteId("route_id"); diff --git a/ts-travel2-service/pom.xml b/ts-travel2-service/pom.xml index 63ae42c81..b6b5c381b 100644 --- a/ts-travel2-service/pom.xml +++ b/ts-travel2-service/pom.xml @@ -16,7 +16,7 @@ org.services ts-service 0.1.0 - ../ + ../pom.xml @@ -28,15 +28,22 @@ org.springframework.boot - spring-boot-starter-data-mongodb + spring-boot-starter-data-jpa + + + mysql + mysql-connector-java + runtime org.services ts-common 0.1.0 - - + + jakarta.validation + jakarta.validation-api + diff --git a/ts-travel2-service/src/main/java/travel2/Travel2Application.java b/ts-travel2-service/src/main/java/travel2/Travel2Application.java index d5d149944..6f7fd4ecd 100644 --- a/ts-travel2-service/src/main/java/travel2/Travel2Application.java +++ b/ts-travel2-service/src/main/java/travel2/Travel2Application.java @@ -3,6 +3,8 @@ import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.boot.web.client.RestTemplateBuilder; +import org.springframework.cloud.client.discovery.EnableDiscoveryClient; +import org.springframework.cloud.client.loadbalancer.LoadBalanced; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.EnableAspectJAutoProxy; import org.springframework.integration.annotation.IntegrationComponentScan; @@ -18,12 +20,14 @@ @EnableAsync @IntegrationComponentScan @EnableSwagger2 +@EnableDiscoveryClient public class Travel2Application { public static void main(String[] args) { SpringApplication.run(Travel2Application.class, args); } + @LoadBalanced @Bean public RestTemplate restTemplate(RestTemplateBuilder builder) { return builder.build(); diff --git a/ts-travel2-service/src/main/java/travel2/controller/Travel2Controller.java b/ts-travel2-service/src/main/java/travel2/controller/Travel2Controller.java index c39c2d363..148c1d84b 100644 --- a/ts-travel2-service/src/main/java/travel2/controller/Travel2Controller.java +++ b/ts-travel2-service/src/main/java/travel2/controller/Travel2Controller.java @@ -1,5 +1,6 @@ package travel2.controller; +import edu.fudan.common.entity.TripResponse; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; @@ -8,8 +9,7 @@ import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.*; -import travel2.entity.*; -import travel2.service.Travel2Service; +import travel2.service.TravelService; import java.util.ArrayList; @@ -23,7 +23,7 @@ public class Travel2Controller { @Autowired - private Travel2Service service; + private TravelService service; private static final Logger LOGGER = LoggerFactory.getLogger(Travel2Controller.class); @@ -36,14 +36,14 @@ public String home(@RequestHeader HttpHeaders headers) { public HttpEntity getTrainTypeByTripId(@PathVariable String tripId, @RequestHeader HttpHeaders headers) { // TrainType - Travel2Controller.LOGGER.info("Get train by Trip id, TripId: {}",tripId); + Travel2Controller.LOGGER.info("[getTrainTypeByTripId][Get train by Trip id][TripId: {}]",tripId); return ok(service.getTrainTypeByTripId(tripId, headers)); } @GetMapping(value = "/routes/{tripId}") public HttpEntity getRouteByTripId(@PathVariable String tripId, @RequestHeader HttpHeaders headers) { - Travel2Controller.LOGGER.info("[Get Route By Trip ID] TripId: {}", tripId); + Travel2Controller.LOGGER.info("[getRouteByTripId][Get Route By Trip ID][TripId: {}]", tripId); //Route return ok(service.getRouteByTripId(tripId, headers)); } @@ -52,15 +52,15 @@ public HttpEntity getRouteByTripId(@PathVariable String tripId, public HttpEntity getTripsByRouteId(@RequestBody ArrayList routeIds, @RequestHeader HttpHeaders headers) { // ArrayList> - Travel2Controller.LOGGER.info("Get trips by Route id, RouteIdNumber: {}",routeIds.size()); + Travel2Controller.LOGGER.info("[getTripByRoute][Get trips by Route id][RouteIdNumber: {}]",routeIds.size()); return ok(service.getTripByRoute(routeIds, headers)); } @CrossOrigin(origins = "*") @PostMapping(value = "/trips") - public HttpEntity createTrip(@RequestBody TravelInfo routeIds, @RequestHeader HttpHeaders headers) { + public HttpEntity createTrip(@RequestBody edu.fudan.common.entity.TravelInfo routeIds, @RequestHeader HttpHeaders headers) { // null - Travel2Controller.LOGGER.info("Create trip, TripId: {}", routeIds.getTripId()); + Travel2Controller.LOGGER.info("[create][Create trip][TripId: {}]", routeIds.getTripId()); return new ResponseEntity<>(service.create(routeIds, headers), HttpStatus.CREATED); } @@ -75,15 +75,15 @@ public HttpEntity createTrip(@RequestBody TravelInfo routeIds, @RequestHeader @GetMapping(value = "/trips/{tripId}") public HttpEntity retrieve(@PathVariable String tripId, @RequestHeader HttpHeaders headers) { // Trip - Travel2Controller.LOGGER.info("Retrieve trip,TripId: {}",tripId); + Travel2Controller.LOGGER.info("[retrieve][Retrieve trip][TripId: {}]",tripId); return ok(service.retrieve(tripId, headers)); } @CrossOrigin(origins = "*") @PutMapping(value = "/trips") - public HttpEntity updateTrip(@RequestBody TravelInfo info, @RequestHeader HttpHeaders headers) { + public HttpEntity updateTrip(@RequestBody edu.fudan.common.entity.TravelInfo info, @RequestHeader HttpHeaders headers) { // Trip - Travel2Controller.LOGGER.info("Update trip,TripId: {}",info.getTripId()); + Travel2Controller.LOGGER.info("[update][Update trip][TripId: {}]",info.getTripId()); return ok(service.update(info, headers)); } @@ -91,7 +91,7 @@ public HttpEntity updateTrip(@RequestBody TravelInfo info, @RequestHeader HttpHe @DeleteMapping(value = "/trips/{tripId}") public HttpEntity deleteTrip(@PathVariable String tripId, @RequestHeader HttpHeaders headers) { // string - Travel2Controller.LOGGER.info("Delete trip,TripId: {}",tripId); + Travel2Controller.LOGGER.info("[delete][Delete trip][TripId: {}]",tripId); return ok(service.delete(tripId, headers)); } @@ -104,16 +104,16 @@ public HttpEntity deleteTrip(@PathVariable String tripId, @RequestHeader HttpHea */ @CrossOrigin(origins = "*") @PostMapping(value = "/trips/left") - public HttpEntity queryInfo(@RequestBody TripInfo info, @RequestHeader HttpHeaders headers) { - if (info.getStartingPlace() == null || info.getStartingPlace().length() == 0 || + public HttpEntity queryInfo(@RequestBody edu.fudan.common.entity.TripInfo info, @RequestHeader HttpHeaders headers) { + if (info.getStartPlace() == null || info.getStartPlace().length() == 0 || info.getEndPlace() == null || info.getEndPlace().length() == 0 || info.getDepartureTime() == null) { - Travel2Controller.LOGGER.info("[Travel Query] Fail.Something null."); + Travel2Controller.LOGGER.info("[query][Travel Query Fail][Something null]"); ArrayList errorList = new ArrayList<>(); return ok(errorList); } - Travel2Controller.LOGGER.info("Query TripResponse"); - return ok(service.query(info, headers)); + Travel2Controller.LOGGER.info("[query][Query TripResponse]"); + return ok(service.queryByBatch(info, headers)); } /** @@ -125,8 +125,8 @@ public HttpEntity queryInfo(@RequestBody TripInfo info, @RequestHeader HttpHeade */ @CrossOrigin(origins = "*") @PostMapping(value = "/trip_detail") - public HttpEntity getTripAllDetailInfo(@RequestBody TripAllDetailInfo gtdi, @RequestHeader HttpHeaders headers) { - Travel2Controller.LOGGER.info("Get trip detail, TripId: {}",gtdi.getTripId()); + public HttpEntity getTripAllDetailInfo(@RequestBody edu.fudan.common.entity.TripAllDetailInfo gtdi, @RequestHeader HttpHeaders headers) { + Travel2Controller.LOGGER.info("[getTripAllDetailInfo][Get trip detail][TripId: {}]",gtdi.getTripId()); return ok(service.getTripAllDetailInfo(gtdi, headers)); } @@ -134,7 +134,7 @@ public HttpEntity getTripAllDetailInfo(@RequestBody TripAllDetailInfo gtdi, @Req @GetMapping(value = "/trips") public HttpEntity queryAll(@RequestHeader HttpHeaders headers) { // List - Travel2Controller.LOGGER.info("Query all trips"); + Travel2Controller.LOGGER.info("[queryAll][Query all trips]"); return ok(service.queryAll(headers)); } @@ -142,7 +142,7 @@ public HttpEntity queryAll(@RequestHeader HttpHeaders headers) { @GetMapping(value = "/admin_trip") public HttpEntity adminQueryAll(@RequestHeader HttpHeaders headers) { // ArrayList - Travel2Controller.LOGGER.info("Admin query all trips"); + Travel2Controller.LOGGER.info("[adminQueryAll][Admin query all trips]"); return ok(service.adminQueryAll(headers)); } diff --git a/ts-travel2-service/src/main/java/travel2/entity/AdminTrip.java b/ts-travel2-service/src/main/java/travel2/entity/AdminTrip.java index cbc38ef33..e52662451 100644 --- a/ts-travel2-service/src/main/java/travel2/entity/AdminTrip.java +++ b/ts-travel2-service/src/main/java/travel2/entity/AdminTrip.java @@ -1,5 +1,7 @@ package travel2.entity; +import edu.fudan.common.entity.Route; +import edu.fudan.common.entity.TrainType; import lombok.Data; /** diff --git a/ts-travel2-service/src/main/java/travel2/entity/Route.java b/ts-travel2-service/src/main/java/travel2/entity/Route.java deleted file mode 100644 index 06f70aadd..000000000 --- a/ts-travel2-service/src/main/java/travel2/entity/Route.java +++ /dev/null @@ -1,33 +0,0 @@ -package travel2.entity; - -import com.fasterxml.jackson.annotation.JsonIgnoreProperties; -import lombok.Data; -import org.springframework.data.annotation.Id; -import org.springframework.data.mongodb.core.mapping.Document; - -import java.util.List; - -/** - * @author fdse - */ -@Data -@Document(collection = "routes") -@JsonIgnoreProperties(ignoreUnknown = true) -public class Route { - - @Id - private String id; - - private List stations; - - private List distances; - - private String startStationId; - - private String terminalStationId; - - public Route() { - //Default Constructor - } - -} diff --git a/ts-travel2-service/src/main/java/travel2/entity/Seat.java b/ts-travel2-service/src/main/java/travel2/entity/Seat.java deleted file mode 100644 index 84d6bfc2e..000000000 --- a/ts-travel2-service/src/main/java/travel2/entity/Seat.java +++ /dev/null @@ -1,44 +0,0 @@ -package travel2.entity; - -import lombok.Data; - -import javax.validation.Valid; -import javax.validation.constraints.NotNull; -import java.util.Date; - -/** - * @author fdse - */ -@Data -public class Seat { - @Valid - @NotNull - private Date travelDate; - - @Valid - @NotNull - private String trainNumber; - - - @Valid - @NotNull - private String startStation; - - @Valid - @NotNull - private String destStation; - - @Valid - @NotNull - private int seatType; - - public Seat(){ - //Default Constructor - this.travelDate = new Date(); - this.trainNumber = ""; - this.startStation = ""; - this.destStation = ""; - this.seatType = 0; - } - -} diff --git a/ts-travel2-service/src/main/java/travel2/entity/SeatClass.java b/ts-travel2-service/src/main/java/travel2/entity/SeatClass.java deleted file mode 100644 index 0a1a10d8f..000000000 --- a/ts-travel2-service/src/main/java/travel2/entity/SeatClass.java +++ /dev/null @@ -1,70 +0,0 @@ -package travel2.entity; - -/** - * @author fdse - */ -public enum SeatClass { - - /** - * no seat - */ - NONE (0,"NoSeat"), - /** - * green seat - */ - BUSINESS (1,"GreenSeat"), - /** - * first class seat - */ - FIRSTCLASS (2,"FirstClassSeat"), - /** - * second class seat - */ - SECONDCLASS (3,"SecondClassSeat"), - /** - * hard seat - */ - HARDSEAT (4,"HardSeat"), - /** - * soft seat - */ - SOFTSEAT (5,"SoftSeat"), - /** - * hard bed - */ - HARDBED (6,"HardBed"), - /** - * soft bed - */ - SOFTBED (7,"SoftBed"), - /** - * high soft seat - */ - HIGHSOFTBED (8,"HighSoftSeat"); - - private int code; - private String name; - - SeatClass(int code, String name){ - this.code = code; - this.name = name; - } - - public int getCode(){ - return code; - } - - public String getName() { - return name; - } - - public static String getNameByCode(int code){ - SeatClass[] seatClassSet = SeatClass.values(); - for(SeatClass seatClass : seatClassSet){ - if(seatClass.getCode() == code){ - return seatClass.getName(); - } - } - return seatClassSet[0].getName(); - } -} diff --git a/ts-travel2-service/src/main/java/travel2/entity/SoldTicket.java b/ts-travel2-service/src/main/java/travel2/entity/SoldTicket.java deleted file mode 100644 index bcf40fb80..000000000 --- a/ts-travel2-service/src/main/java/travel2/entity/SoldTicket.java +++ /dev/null @@ -1,47 +0,0 @@ -package travel2.entity; - -import lombok.Data; - -import java.util.Date; - -/** - * @author fdse - */ -@Data -public class SoldTicket { - - private Date travelDate; - - private String trainNumber; - - private int noSeat; - - private int businessSeat; - - private int firstClassSeat; - - private int secondClassSeat; - - private int hardSeat; - - private int softSeat; - - private int hardBed; - - private int softBed; - - private int highSoftBed; - - public SoldTicket(){ - noSeat = 0; - businessSeat = 0; - firstClassSeat = 0; - secondClassSeat = 0; - hardSeat = 0; - softSeat = 0; - hardBed = 0; - softBed = 0; - highSoftBed = 0; - } - -} diff --git a/ts-travel2-service/src/main/java/travel2/entity/TrainType.java b/ts-travel2-service/src/main/java/travel2/entity/TrainType.java deleted file mode 100644 index 5f641e07b..000000000 --- a/ts-travel2-service/src/main/java/travel2/entity/TrainType.java +++ /dev/null @@ -1,43 +0,0 @@ -package travel2.entity; - -import lombok.Data; -import org.springframework.data.annotation.Id; -import org.springframework.data.mongodb.core.mapping.Document; - -import javax.validation.Valid; - -/** - * @author fdse - */ -@Data -@Document(collection="trainType") -public class TrainType { - @Valid - @Id - private String id; - - @Valid - private int economyClass; - @Valid - private int confortClass; - - private int averageSpeed; - - public TrainType(){ - //Default Constructor - } - - public TrainType(String id, int economyClass, int confortClass) { - this.id = id; - this.economyClass = economyClass; - this.confortClass = confortClass; - } - - public TrainType(String id, int economyClass, int confortClass, int averageSpeed) { - this.id = id; - this.economyClass = economyClass; - this.confortClass = confortClass; - this.averageSpeed = averageSpeed; - } - -} diff --git a/ts-travel2-service/src/main/java/travel2/entity/Travel.java b/ts-travel2-service/src/main/java/travel2/entity/Travel.java index 7dcc95467..08b17c962 100644 --- a/ts-travel2-service/src/main/java/travel2/entity/Travel.java +++ b/ts-travel2-service/src/main/java/travel2/entity/Travel.java @@ -1,5 +1,7 @@ package travel2.entity; +import travel2.entity.Trip; +import edu.fudan.common.util.StringUtils; import lombok.Data; import java.util.Date; @@ -12,14 +14,13 @@ public class Travel { private Trip trip; - private String startingPlace; + private String startPlace; private String endPlace; - private Date departureTime; + private String departureTime; public Travel(){ //Default Constructor } - } diff --git a/ts-travel2-service/src/main/java/travel2/entity/TravelInfo.java b/ts-travel2-service/src/main/java/travel2/entity/TravelInfo.java deleted file mode 100644 index 894ddd230..000000000 --- a/ts-travel2-service/src/main/java/travel2/entity/TravelInfo.java +++ /dev/null @@ -1,33 +0,0 @@ -package travel2.entity; - -import lombok.Data; - -import java.util.Date; - -/** - * @author fdse - */ -@Data -public class TravelInfo { - - private String tripId; - - private String trainTypeId; - - private String routeId; - - private String startingStationId; - - private String stationsId; - - private String terminalStationId; - - private Date startingTime; - - private Date endTime; - - public TravelInfo() { - //Default Constructor - } - -} diff --git a/ts-travel2-service/src/main/java/travel2/entity/TravelResult.java b/ts-travel2-service/src/main/java/travel2/entity/TravelResult.java deleted file mode 100644 index 4255b4026..000000000 --- a/ts-travel2-service/src/main/java/travel2/entity/TravelResult.java +++ /dev/null @@ -1,28 +0,0 @@ -package travel2.entity; - -import java.util.Map; -import lombok.*; - -/** - * @author fdse - */ -@Data -public class TravelResult { - - private boolean status; - - private double percent; - - private TrainType trainType; - - private Map prices; - - public TravelResult(){ - //Default Constructor - } - - public boolean isStatus() { - return status; - } - -} diff --git a/ts-travel2-service/src/main/java/travel2/entity/Trip.java b/ts-travel2-service/src/main/java/travel2/entity/Trip.java index 213491baf..5505545fb 100644 --- a/ts-travel2-service/src/main/java/travel2/entity/Trip.java +++ b/ts-travel2-service/src/main/java/travel2/entity/Trip.java @@ -1,9 +1,11 @@ package travel2.entity; +import edu.fudan.common.entity.TripId; +import edu.fudan.common.util.StringUtils; import lombok.Data; -import org.springframework.data.annotation.Id; -import org.springframework.data.mongodb.core.mapping.Document; +import org.hibernate.annotations.GenericGenerator; +import javax.persistence.*; import javax.validation.Valid; import javax.validation.constraints.NotNull; import java.util.Date; @@ -12,65 +14,73 @@ * @author fdse */ @Data -@Document(collection="trip") -public class Trip { +@Entity +@Table(name = "trip2") +@GenericGenerator(name = "jpa-uuid", strategy = "org.hibernate.id.UUIDGenerator") +public class +Trip { @Valid @Id + @GeneratedValue(generator = "jpa-uuid") + @Column(length = 36) + private String id; + + @Embedded private TripId tripId; @Valid @NotNull - private String trainTypeId; + private String trainTypeName; private String routeId; @Valid @NotNull - private String startingStationId; + private String startStationName; @Valid - private String stationsId; + private String stationsName; @Valid @NotNull - private String terminalStationId; + private String terminalStationName; @Valid @NotNull - private Date startingTime; + private String startTime; @Valid @NotNull - private Date endTime; + private String endTime; - public Trip(TripId tripId, String trainTypeId, String startingStationId, String stationsId, String terminalStationId, Date startingTime, Date endTime) { + public Trip(edu.fudan.common.entity.TripId tripId, String trainTypeName, String startStationName, String stationsName, String terminalStationName, String startTime, String endTime) { this.tripId = tripId; - this.trainTypeId = trainTypeId; - this.startingStationId = startingStationId; - this.stationsId = stationsId; - this.terminalStationId = terminalStationId; - this.startingTime = startingTime; + this.trainTypeName = trainTypeName; + this.startStationName = StringUtils.String2Lower(startStationName); + this.stationsName = StringUtils.String2Lower(stationsName); + this.terminalStationName = StringUtils.String2Lower(terminalStationName); + this.startTime = startTime; this.endTime = endTime; } - public Trip(TripId tripId, String trainTypeId, String routeId) { + public Trip(TripId tripId, String trainTypeName, String routeId) { this.tripId = tripId; - this.trainTypeId = trainTypeId; + this.trainTypeName = trainTypeName; this.routeId = routeId; - this.startingStationId = ""; - this.terminalStationId = ""; - this.startingTime = new Date(); - this.endTime = new Date(); + this.startStationName = ""; + this.terminalStationName = ""; + this.startTime = ""; + this.endTime = ""; } public Trip(){ //Default Constructor - this.trainTypeId = ""; - this.startingStationId = ""; - this.terminalStationId = ""; - this.startingTime = new Date(); - this.endTime = new Date(); + this.trainTypeName = ""; + this.startStationName = ""; + this.terminalStationName = ""; + this.startTime = ""; + this.endTime = ""; } -} +} \ No newline at end of file diff --git a/ts-travel2-service/src/main/java/travel2/entity/TripAllDetail.java b/ts-travel2-service/src/main/java/travel2/entity/TripAllDetail.java index e03432b3e..e34da6c24 100644 --- a/ts-travel2-service/src/main/java/travel2/entity/TripAllDetail.java +++ b/ts-travel2-service/src/main/java/travel2/entity/TripAllDetail.java @@ -1,11 +1,16 @@ package travel2.entity; +import edu.fudan.common.entity.TripResponse; +import lombok.AllArgsConstructor; import lombok.Data; +import lombok.NoArgsConstructor; /** * @author fdse */ @Data +@NoArgsConstructor +@AllArgsConstructor public class TripAllDetail { private boolean status; @@ -16,8 +21,4 @@ public class TripAllDetail { private Trip trip; - public TripAllDetail() { - //Default Constructor - } - } diff --git a/ts-travel2-service/src/main/java/travel2/entity/TripAllDetailInfo.java b/ts-travel2-service/src/main/java/travel2/entity/TripAllDetailInfo.java deleted file mode 100644 index 062228009..000000000 --- a/ts-travel2-service/src/main/java/travel2/entity/TripAllDetailInfo.java +++ /dev/null @@ -1,27 +0,0 @@ -package travel2.entity; - -import lombok.Data; -import lombok.ToString; - -import java.util.Date; - -/** - * @author fdse - */ -@Data -@ToString -public class TripAllDetailInfo { - - private String tripId; - - private Date travelDate; - - private String from; - - private String to; - - public TripAllDetailInfo() { - //Default Constructor - } - -} diff --git a/ts-travel2-service/src/main/java/travel2/entity/TripId.java b/ts-travel2-service/src/main/java/travel2/entity/TripId.java deleted file mode 100644 index c1a3a01d4..000000000 --- a/ts-travel2-service/src/main/java/travel2/entity/TripId.java +++ /dev/null @@ -1,39 +0,0 @@ -package travel2.entity; - -import lombok.Data; - -import java.io.Serializable; - -/** - * @author fdse - */ -@Data -public class TripId implements Serializable{ - private Type type; - private String number; - - - public TripId(){ - //Default Constructor - } - - public TripId(String trainNumber){ - char type0 = trainNumber.charAt(0); - switch(type0){ - case 'Z': this.type = Type.Z; - break; - case 'T': this.type = Type.T; - break; - case 'K': this.type = Type.K; - break; - default:break; - } - - this.number = trainNumber.substring(1); - } - - @Override - public String toString(){ - return type.getName() + number; - } -} diff --git a/ts-travel2-service/src/main/java/travel2/entity/TripInfo.java b/ts-travel2-service/src/main/java/travel2/entity/TripInfo.java deleted file mode 100644 index 03eb97c30..000000000 --- a/ts-travel2-service/src/main/java/travel2/entity/TripInfo.java +++ /dev/null @@ -1,35 +0,0 @@ -package travel2.entity; - -import lombok.AllArgsConstructor; -import lombok.Data; - -import javax.validation.Valid; -import javax.validation.constraints.NotNull; -import java.util.Date; - -/** - * @author fdse - */ -@Data -@AllArgsConstructor -public class TripInfo { - @Valid - @NotNull - private String startingPlace; - - @Valid - @NotNull - private String endPlace; - - @Valid - @NotNull - private Date departureTime; - - public TripInfo(){ - //Default Constructor - this.startingPlace = ""; - this.endPlace = ""; - this.departureTime = new Date(); - } - -} diff --git a/ts-travel2-service/src/main/java/travel2/entity/Type.java b/ts-travel2-service/src/main/java/travel2/entity/Type.java deleted file mode 100644 index 298db6b68..000000000 --- a/ts-travel2-service/src/main/java/travel2/entity/Type.java +++ /dev/null @@ -1,55 +0,0 @@ -package travel2.entity; - -import java.io.Serializable; - -/** - * @author fdse - */ -public enum Type implements Serializable{ - - /** - * Z - */ - Z("Z",3), - /** - * T - */ - T("T", 4), - /** - * K - */ - K("K", 5); - - private String name; - private int index; - - Type(String name, int index) { - this.name = name; - this.index = index; - } - - public static String getName(int index) { - for (Type type : Type.values()) { - if (type.getIndex() == index) { - return type.name; - } - } - return null; - } - - public String getName() { - return name; - } - - void setName(String name) { - this.name = name; - } - - public int getIndex() { - return index; - } - - void setIndex(int index) { - this.index = index; - } -} diff --git a/ts-travel2-service/src/main/java/travel2/init/InitData.java b/ts-travel2-service/src/main/java/travel2/init/InitData.java index 760081290..7826ef65b 100644 --- a/ts-travel2-service/src/main/java/travel2/init/InitData.java +++ b/ts-travel2-service/src/main/java/travel2/init/InitData.java @@ -3,8 +3,8 @@ import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.CommandLineRunner; import org.springframework.stereotype.Component; -import travel2.entity.TravelInfo; -import travel2.service.Travel2Service; +import edu.fudan.common.entity.TravelInfo; +import travel2.service.TravelService; import java.util.Date; /** @@ -14,7 +14,7 @@ public class InitData implements CommandLineRunner { @Autowired - Travel2Service service; + TravelService service; String zhiDa = "ZhiDa"; String shanghai = "shanghai"; @@ -26,53 +26,53 @@ public void run(String... args)throws Exception{ TravelInfo info = new TravelInfo(); info.setTripId("Z1234"); - info.setTrainTypeId(zhiDa); + info.setTrainTypeName(zhiDa); info.setRouteId("0b23bd3e-876a-4af3-b920-c50a90c90b04"); - info.setStartingStationId(shanghai); - info.setStationsId(nanjing); - info.setTerminalStationId(beijing); - info.setStartingTime(new Date("Mon May 04 09:51:52 GMT+0800 2013")); //NOSONAR - info.setEndTime(new Date("Mon May 04 15:51:52 GMT+0800 2013")); //NOSONAR + info.setStartStationName(shanghai); + info.setStationsName(nanjing); + info.setTerminalStationName(beijing); + info.setStartTime("2013-05-04 09:51:52"); //NOSONAR + info.setEndTime("2013-05-04 15:51:52"); //NOSONAR service.create(info,null); info.setTripId("Z1235"); - info.setTrainTypeId(zhiDa); + info.setTrainTypeName(zhiDa); info.setRouteId("9fc9c261-3263-4bfa-82f8-bb44e06b2f52"); - info.setStartingStationId(shanghai); - info.setStationsId(nanjing); - info.setTerminalStationId(beijing); - info.setStartingTime(new Date("Mon May 04 11:31:52 GMT+0800 2013")); //NOSONAR - info.setEndTime(new Date("Mon May 04 17:51:52 GMT+0800 2013")); //NOSONAR + info.setStartStationName(shanghai); + info.setStationsName(nanjing); + info.setTerminalStationName(beijing); + info.setStartTime("2013-05-04 11:31:52"); //NOSONAR + info.setEndTime("2013-05-04 17:51:52"); //NOSONAR service.create(info,null); info.setTripId("Z1236"); - info.setTrainTypeId(zhiDa); + info.setTrainTypeName(zhiDa); info.setRouteId("d693a2c5-ef87-4a3c-bef8-600b43f62c68"); - info.setStartingStationId(shanghai); - info.setStationsId(nanjing); - info.setTerminalStationId(beijing); - info.setStartingTime(new Date("Mon May 04 7:05:52 GMT+0800 2013")); //NOSONAR - info.setEndTime(new Date("Mon May 04 12:51:52 GMT+0800 2013")); //NOSONAR + info.setStartStationName(shanghai); + info.setStationsName(nanjing); + info.setTerminalStationName(beijing); + info.setStartTime("2013-05-04 7:05:52"); //NOSONAR + info.setEndTime("2013-05-04 12:51:52"); //NOSONAR service.create(info,null); info.setTripId("T1235"); - info.setTrainTypeId("TeKuai"); + info.setTrainTypeName("TeKuai"); info.setRouteId("20eb7122-3a11-423f-b10a-be0dc5bce7db"); - info.setStartingStationId(shanghai); - info.setStationsId(nanjing); - info.setTerminalStationId(beijing); - info.setStartingTime(new Date("Mon May 04 08:31:52 GMT+0800 2013")); //NOSONAR - info.setEndTime(new Date("Mon May 04 17:21:52 GMT+0800 2013")); //NOSONAR + info.setStartStationName(shanghai); + info.setStationsName(nanjing); + info.setTerminalStationName(beijing); + info.setStartTime("2013-05-04 08:31:52"); //NOSONAR + info.setEndTime("2013-05-04 17:21:52"); //NOSONAR service.create(info,null); info.setTripId("K1345"); - info.setTrainTypeId("KuaiSu"); + info.setTrainTypeName("KuaiSu"); info.setRouteId("1367db1f-461e-4ab7-87ad-2bcc05fd9cb7"); - info.setStartingStationId(shanghai); - info.setStationsId(nanjing); - info.setTerminalStationId(beijing); - info.setStartingTime(new Date("Mon May 04 07:51:52 GMT+0800 2013")); //NOSONAR - info.setEndTime(new Date("Mon May 04 19:59:52 GMT+0800 2013")); //NOSONAR + info.setStartStationName(shanghai); + info.setStationsName(nanjing); + info.setTerminalStationName(beijing); + info.setStartTime("2013-05-04 07:51:52"); //NOSONAR + info.setEndTime("2013-05-04 19:59:52"); //NOSONAR service.create(info,null); } } diff --git a/ts-travel2-service/src/main/java/travel2/repository/TripRepository.java b/ts-travel2-service/src/main/java/travel2/repository/TripRepository.java index 3549550fa..ef2093778 100644 --- a/ts-travel2-service/src/main/java/travel2/repository/TripRepository.java +++ b/ts-travel2-service/src/main/java/travel2/repository/TripRepository.java @@ -1,14 +1,18 @@ package travel2.repository; +import edu.fudan.common.entity.TripId; import org.springframework.data.repository.CrudRepository; +import org.springframework.stereotype.Repository; + import travel2.entity.Trip; -import travel2.entity.TripId; + import java.util.ArrayList; /** * @author fdse */ -public interface TripRepository extends CrudRepository { +@Repository +public interface TripRepository extends CrudRepository { Trip findByTripId(TripId tripId); @@ -18,4 +22,4 @@ public interface TripRepository extends CrudRepository { ArrayList findAll(); ArrayList findByRouteId(String routeId); -} +} \ No newline at end of file diff --git a/ts-travel2-service/src/main/java/travel2/service/Travel2ServiceImpl.java b/ts-travel2-service/src/main/java/travel2/service/Travel2ServiceImpl.java deleted file mode 100644 index bdf390316..000000000 --- a/ts-travel2-service/src/main/java/travel2/service/Travel2ServiceImpl.java +++ /dev/null @@ -1,431 +0,0 @@ -package travel2.service; - -import edu.fudan.common.util.JsonUtils; -import edu.fudan.common.util.Response; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.core.ParameterizedTypeReference; -import org.springframework.http.HttpEntity; -import org.springframework.http.HttpHeaders; -import org.springframework.http.HttpMethod; -import org.springframework.http.ResponseEntity; -import org.springframework.stereotype.Service; -import org.springframework.web.client.RestTemplate; -import travel2.entity.*; -import travel2.repository.TripRepository; - -import java.util.*; - -/** - * @author fdse - */ -@Service -public class Travel2ServiceImpl implements Travel2Service { - - @Autowired - TripRepository repository; - - @Autowired - private RestTemplate restTemplate; - - private static final Logger LOGGER = LoggerFactory.getLogger(Travel2ServiceImpl.class); - - String success = "Success"; - String noCnontent = "No Content"; - - @Override - public Response getRouteByTripId(String tripId, HttpHeaders headers) { - TripId tripId1 = new TripId(tripId); - - Trip trip = repository.findByTripId(tripId1); - if (trip == null) { - Travel2ServiceImpl.LOGGER.error("[Get Route By Trip ID] Trip Not Found, TripId: {}", tripId); - return new Response<>(0, "\"[Get Route By Trip ID] Trip Not Found:\" + tripId", null); - } else { - Route route = getRouteByRouteId(trip.getRouteId(), headers); - if (route == null) { - Travel2ServiceImpl.LOGGER.error("Get route by Trip id error.Route not found, RouteId: {}",trip.getRouteId()); - return new Response<>(0, "\"[Get Route By Trip ID] Route Not Found:\" + trip.getRouteId()", null); - } else { - Travel2ServiceImpl.LOGGER.info("[Get Route By Trip ID] Success"); - return new Response<>(1, "[Get Route By Trip ID] Success", route); - } - } - } - - - @Override - public Response getTrainTypeByTripId(String tripId, HttpHeaders headers) { - TripId tripId1 = new TripId(tripId); - TrainType trainType = null; - Trip trip = repository.findByTripId(tripId1); - if (trip != null) { - trainType = getTrainType(trip.getTrainTypeId(), headers); - } - else { - Travel2ServiceImpl.LOGGER.error("Get Train Type by Trip id error.Trip not found, TripId: {}",tripId); - } - if (trainType != null) { - return new Response<>(1, "Success query Train by trip id", trainType); - } else { - Travel2ServiceImpl.LOGGER.error("Get Train Type by Trip id error.Train Type not found, TripId: {}",tripId); - return new Response<>(0, noCnontent, null); - } - } - - @Override - public Response getTripByRoute(ArrayList routeIds, HttpHeaders headers) { - ArrayList> tripList = new ArrayList<>(); - for (String routeId : routeIds) { - ArrayList tempTripList = repository.findByRouteId(routeId); - if (tempTripList == null) { - tempTripList = new ArrayList<>(); - } - tripList.add(tempTripList); - } - if (!tripList.isEmpty()) { - return new Response<>(1, success, tripList); - } else { - Travel2ServiceImpl.LOGGER.warn("Get Trips by Route ids warn.Trips not found, RouteIdNumber: {}",routeIds.size()); - return new Response<>(0, noCnontent, null); - } - } - - @Override - public Response create(TravelInfo info, HttpHeaders headers) { - TripId ti = new TripId(info.getTripId()); - if (repository.findByTripId(ti) == null) { - Trip trip = new Trip(ti, info.getTrainTypeId(), info.getStartingStationId(), - info.getStationsId(), info.getTerminalStationId(), info.getStartingTime(), info.getEndTime()); - trip.setRouteId(info.getRouteId()); - repository.save(trip); - return new Response<>(1, "Create trip info:" + ti.toString() + ".", null); - } else { - Travel2ServiceImpl.LOGGER.error("Create trip error.Trip already exists,TripId: {}",info.getTripId()); - return new Response<>(1, "Trip " + info.getTripId() + " already exists", null); - } - } - - @Override - public Response retrieve(String tripId, HttpHeaders headers) { - TripId ti = new TripId(tripId); - Trip trip = repository.findByTripId(ti); - if (trip != null) { - return new Response<>(1, "Search Trip Success by Trip Id " + tripId, trip); - } else { - Travel2ServiceImpl.LOGGER.error("Retrieve trip error.Trip not found,TripId: {}",tripId); - return new Response<>(0, "No Content according to tripId" + tripId, null); - } - } - - @Override - public Response update(TravelInfo info, HttpHeaders headers) { - TripId ti = new TripId(info.getTripId()); - if (repository.findByTripId(ti) != null) { - Trip trip = new Trip(ti, info.getTrainTypeId(), info.getStartingStationId(), - info.getStationsId(), info.getTerminalStationId(), info.getStartingTime(), info.getEndTime()); - trip.setRouteId(info.getRouteId()); - repository.save(trip); - return new Response<>(1, "Update trip info:" + ti.toString(), trip); - } else { - Travel2ServiceImpl.LOGGER.error("Update trip error.Trip not found,TripId: {}",info.getTripId()); - return new Response<>(1, "Trip" + info.getTripId() + "doesn 't exists", null); - } - } - - @Override - public Response delete(String tripId, HttpHeaders headers) { - TripId ti = new TripId(tripId); - if (repository.findByTripId(ti) != null) { - repository.deleteByTripId(ti); - return new Response<>(1, "Delete trip:" + tripId + ".", tripId); - } else { - Travel2ServiceImpl.LOGGER.error("Delete trip error.Trip not found,TripId: {}",tripId); - return new Response<>(0, "Trip " + tripId + " doesn't exist.", null); - } - } - - @Override - public Response query(TripInfo info, HttpHeaders headers) { - - //Gets the start and arrival stations of the train number to query. The originating and arriving stations received here are both station names, so two requests need to be sent to convert to station ids - String startingPlaceName = info.getStartingPlace(); - String endPlaceName = info.getEndPlace(); - String startingPlaceId = queryForStationId(startingPlaceName, headers); - String endPlaceId = queryForStationId(endPlaceName, headers); - - //This is the final result - ArrayList list = new ArrayList<>(); - - //Check all train info - ArrayList allTripList = repository.findAll(); - for (Trip tempTrip : allTripList) { - //Get the detailed route list of this train - Route tempRoute = getRouteByRouteId(tempTrip.getRouteId(), headers); - //Check the route list for this train. Check that the required start and arrival stations are in the list of stops that are not on the route, and check that the location of the start station is before the stop - //Trains that meet the above criteria are added to the return list - if (tempRoute.getStations().contains(startingPlaceId) && - tempRoute.getStations().contains(endPlaceId) && - tempRoute.getStations().indexOf(startingPlaceId) < tempRoute.getStations().indexOf(endPlaceId)) { - TripResponse response = getTickets(tempTrip, tempRoute, startingPlaceId, endPlaceId, startingPlaceName, endPlaceName, info.getDepartureTime(), headers); - if (response == null) { - Travel2ServiceImpl.LOGGER.warn("Query trip error.Tickets not found,start: {},end: {},time: {}",info.getStartingPlace(),info.getEndPlace(),info.getDepartureTime()); - return new Response<>(0, noCnontent, null); - } - list.add(response); - } - } - return new Response<>(1, "Success Query", list); - } - - @Override - public Response getTripAllDetailInfo(TripAllDetailInfo gtdi, HttpHeaders headers) { - TripAllDetail gtdr = new TripAllDetail(); - Travel2ServiceImpl.LOGGER.info("[getTripAllDetailInfo] gtdi info: {}", gtdi.toString()); - Trip trip = repository.findByTripId(new TripId(gtdi.getTripId())); - if (trip == null) { - gtdr.setTripResponse(null); - gtdr.setTrip(null); - Travel2ServiceImpl.LOGGER.error("Get trip detail error.Trip not found,TripId: {}",gtdi.getTripId()); - } else { - String endPlaceName = gtdi.getTo(); - String startingPlaceName = gtdi.getFrom(); - String startingPlaceId = queryForStationId(startingPlaceName, headers); - String endPlaceId = queryForStationId(endPlaceName, headers); - Travel2ServiceImpl.LOGGER.info("[getTripAllDetailInfo] endPlaceID: {}", endPlaceId); - Route tempRoute = getRouteByRouteId(trip.getRouteId(), headers); - TripResponse tripResponse = getTickets(trip, tempRoute, startingPlaceId, endPlaceId, gtdi.getFrom(), gtdi.getTo(), gtdi.getTravelDate(), headers); - if (tripResponse == null) { - gtdr.setTrip(null); - gtdr.setTripResponse(null); - Travel2ServiceImpl.LOGGER.warn("Query trip error.Tickets not found,start: {},end: {}", gtdi.getTo(), gtdi.getFrom()); - } else { - gtdr.setTripResponse(tripResponse); - gtdr.setTrip(repository.findByTripId(new TripId(gtdi.getTripId()))); - } - } - - - return new Response<>(1, success, gtdr); - } - - - private TripResponse getTickets(Trip trip, Route route, String startingPlaceId, String endPlaceId, String startingPlaceName, String endPlaceName, Date departureTime, HttpHeaders headers) { - - //Determine if the date checked is the same day and after - if (!afterToday(departureTime)) { - return null; - } - - Travel query = new Travel(); - query.setTrip(trip); - query.setStartingPlace(startingPlaceName); - query.setEndPlace(endPlaceName); - query.setDepartureTime(departureTime); - - HttpEntity requestEntity = new HttpEntity(query, null); - ResponseEntity> re = restTemplate.exchange( - "http://ts-ticketinfo-service:15681/api/v1/ticketinfoservice/ticketinfo", - HttpMethod.POST, - requestEntity, - new ParameterizedTypeReference>() { - }); - Travel2ServiceImpl.LOGGER.info("Ticket info is: {}", re.getBody().toString()); - TravelResult resultForTravel = re.getBody().getData(); - - - - //Ticket order _ high-speed train (number of tickets purchased) - requestEntity = new HttpEntity(null); - ResponseEntity> re2 = restTemplate.exchange( - "http://ts-order-other-service:12032/api/v1/orderOtherService/orderOther/" + departureTime + "/" + trip.getTripId().toString(), - HttpMethod.GET, - requestEntity, - new ParameterizedTypeReference>() { - }); - Travel2ServiceImpl.LOGGER.info("Order other Ticket info is: {}", re.getBody().toString()); - SoldTicket result = re2.getBody().getData(); - - if (result == null) { - Travel2ServiceImpl.LOGGER.warn("Get tickets warn.Sold ticket Info doesn't exist,Departure Time: {},TripId: {}",departureTime,trip.getTripId()); - return null; - } - //Set the returned ticket information - TripResponse response = new TripResponse(); - if (queryForStationId(startingPlaceName, headers).equals(trip.getStartingStationId()) && - queryForStationId(endPlaceName, headers).equals(trip.getTerminalStationId())) { - response.setEconomyClass(50); - response.setConfortClass(50); - } else { - response.setConfortClass(50); - response.setEconomyClass(50); - } - - int first = getRestTicketNumber(departureTime, trip.getTripId().toString(), - startingPlaceName, endPlaceName, SeatClass.FIRSTCLASS.getCode(), headers); - - int second = getRestTicketNumber(departureTime, trip.getTripId().toString(), - startingPlaceName, endPlaceName, SeatClass.SECONDCLASS.getCode(), headers); - response.setConfortClass(first); - response.setEconomyClass(second); - - response.setStartingStation(startingPlaceName); - response.setTerminalStation(endPlaceName); - - //Calculate the distance from the starting point - Travel2ServiceImpl.LOGGER.info("[getTickets] route: {} station: {}", route.getId(), route.getStations()); - int indexStart = route.getStations().indexOf(startingPlaceId); - int indexEnd = route.getStations().indexOf(endPlaceId); - int distanceStart = route.getDistances().get(indexStart) - route.getDistances().get(0); - int distanceEnd = route.getDistances().get(indexEnd) - route.getDistances().get(0); - TrainType trainType = getTrainType(trip.getTrainTypeId(), headers); - //Train running time is calculated according to the average running speed of the train - int minutesStart = 60 * distanceStart / trainType.getAverageSpeed(); - int minutesEnd = 60 * distanceEnd / trainType.getAverageSpeed(); - - Calendar calendarStart = Calendar.getInstance(); - calendarStart.setTime(trip.getStartingTime()); - calendarStart.add(Calendar.MINUTE, minutesStart); - response.setStartingTime(calendarStart.getTime()); - Travel2ServiceImpl.LOGGER.info("calculate time:{} time: {}", minutesStart, calendarStart.getTime()); - - Calendar calendarEnd = Calendar.getInstance(); - calendarEnd.setTime(trip.getStartingTime()); - calendarEnd.add(Calendar.MINUTE, minutesEnd); - response.setEndTime(calendarEnd.getTime()); - Travel2ServiceImpl.LOGGER.info("calculate time:{} time: {}", minutesEnd, calendarEnd.getTime()); - - response.setTripId(new TripId(result.getTrainNumber())); - response.setTrainTypeId(trip.getTrainTypeId()); - response.setPriceForConfortClass(resultForTravel.getPrices().get("confortClass")); - response.setPriceForEconomyClass(resultForTravel.getPrices().get("economyClass")); - - return response; - } - - @Override - public Response queryAll(HttpHeaders headers) { - List tripList = repository.findAll(); - if (tripList != null && !tripList.isEmpty()) { - return new Response<>(1, success, tripList); - } - Travel2ServiceImpl.LOGGER.warn("Query all trips warn: {}","No Content"); - return new Response<>(0, noCnontent, null); - } - - private static boolean afterToday(Date date) { - Calendar calDateA = Calendar.getInstance(); - Date today = new Date(); - calDateA.setTime(today); - - Calendar calDateB = Calendar.getInstance(); - calDateB.setTime(date); - - if (calDateA.get(Calendar.YEAR) > calDateB.get(Calendar.YEAR)) { - return false; - } else if (calDateA.get(Calendar.YEAR) == calDateB.get(Calendar.YEAR)) { - if (calDateA.get(Calendar.MONTH) > calDateB.get(Calendar.MONTH)) { - return false; - } else if (calDateA.get(Calendar.MONTH) == calDateB.get(Calendar.MONTH)) { - return calDateA.get(Calendar.DAY_OF_MONTH) <= calDateB.get(Calendar.DAY_OF_MONTH); - } else { - return true; - } - } else { - return true; - } - } - - private TrainType getTrainType(String trainTypeId, HttpHeaders headers) { - - HttpEntity requestEntity = new HttpEntity(null); - ResponseEntity> re = restTemplate.exchange( - "http://ts-train-service:14567/api/v1/trainservice/trains/" + trainTypeId, - HttpMethod.GET, - requestEntity, - new ParameterizedTypeReference>() { - }); - - return re.getBody().getData(); - } - - private String queryForStationId(String stationName, HttpHeaders headers) { - HttpEntity requestEntity = new HttpEntity(null); - ResponseEntity> re = restTemplate.exchange( - "http://ts-ticketinfo-service:15681/api/v1/ticketinfoservice/ticketinfo/" + stationName, - HttpMethod.GET, - requestEntity, - new ParameterizedTypeReference>() { - }); - - - return re.getBody().getData(); - } - - private Route getRouteByRouteId(String routeId, HttpHeaders headers) { - Travel2ServiceImpl.LOGGER.info("[Get Route By Id] Route ID:{}", routeId); - HttpEntity requestEntity = new HttpEntity(null); - ResponseEntity re = restTemplate.exchange( - "http://ts-route-service:11178/api/v1/routeservice/routes/" + routeId, - HttpMethod.GET, - requestEntity, - Response.class); - Response result = re.getBody(); - - if (result.getStatus() == 0 ) { - Travel2ServiceImpl.LOGGER.error("[Get Route By Id] Fail.Route not found,RouteId: {}", routeId); - return null; - } else { - Travel2ServiceImpl.LOGGER.info("[Get Route By Id] Success."); - return JsonUtils.conveterObject(result.getData(), Route.class); - } - } - - private int getRestTicketNumber(Date travelDate, String trainNumber, String startStationName, String endStationName, int seatType, HttpHeaders headers) { - Seat seatRequest = new Seat(); - - String fromId = queryForStationId(startStationName, headers); - String toId = queryForStationId(endStationName, headers); - - seatRequest.setDestStation(toId); - seatRequest.setStartStation(fromId); - seatRequest.setTrainNumber(trainNumber); - seatRequest.setSeatType(seatType); - seatRequest.setTravelDate(travelDate); - Travel2ServiceImpl.LOGGER.info("Seat request To String: {}", seatRequest.toString()); - - HttpEntity requestEntity = new HttpEntity(seatRequest, null); - ResponseEntity> re = restTemplate.exchange( - "http://ts-seat-service:18898/api/v1/seatservice/seats/left_tickets", - HttpMethod.POST, - requestEntity, - new ParameterizedTypeReference>() { - }); - int restNumber = re.getBody().getData(); - - Travel2ServiceImpl.LOGGER.info("Get Rest tickets num is: {}", re.getBody().toString()); - return restNumber; - } - - @Override - public Response adminQueryAll(HttpHeaders headers) { - List trips = repository.findAll(); - ArrayList adminTrips = new ArrayList<>(); - for (Trip trip : trips) { - AdminTrip adminTrip = new AdminTrip(); - adminTrip.setRoute(getRouteByRouteId(trip.getRouteId(), headers)); - adminTrip.setTrainType(getTrainType(trip.getTrainTypeId(), headers)); - adminTrip.setTrip(trip); - adminTrips.add(adminTrip); - } - if (!adminTrips.isEmpty()) { - return new Response<>(1, "Travel Service Admin Query All Travel Success", adminTrips); - } else { - Travel2ServiceImpl.LOGGER.warn("Admin query all trips warn: {}","No Content"); - return new Response<>(0, noCnontent, null); - } - } - -} - diff --git a/ts-travel2-service/src/main/java/travel2/service/Travel2Service.java b/ts-travel2-service/src/main/java/travel2/service/TravelService.java similarity index 62% rename from ts-travel2-service/src/main/java/travel2/service/Travel2Service.java rename to ts-travel2-service/src/main/java/travel2/service/TravelService.java index 7edf38920..bcac7a28c 100644 --- a/ts-travel2-service/src/main/java/travel2/service/Travel2Service.java +++ b/ts-travel2-service/src/main/java/travel2/service/TravelService.java @@ -1,8 +1,8 @@ package travel2.service; +import edu.fudan.common.entity.TripInfo; import edu.fudan.common.util.Response; import org.springframework.http.HttpHeaders; -import travel2.entity.*; import java.util.ArrayList; @@ -10,18 +10,20 @@ * @author Chenjie Xu * @date 2017/6/7. */ -public interface Travel2Service { - Response create(TravelInfo info, HttpHeaders headers); +public interface TravelService { + Response create(edu.fudan.common.entity.TravelInfo info, HttpHeaders headers); Response retrieve(String tripId, HttpHeaders headers); - Response update(TravelInfo info, HttpHeaders headers); + Response update(edu.fudan.common.entity.TravelInfo info, HttpHeaders headers); Response delete(String tripId, HttpHeaders headers); Response query(TripInfo info, HttpHeaders headers); - Response getTripAllDetailInfo(TripAllDetailInfo gtdi, HttpHeaders headers); + Response queryByBatch(TripInfo info, HttpHeaders headers); + + Response getTripAllDetailInfo(edu.fudan.common.entity.TripAllDetailInfo gtdi, HttpHeaders headers); Response getRouteByTripId(String tripId, HttpHeaders headers); diff --git a/ts-travel2-service/src/main/java/travel2/service/TravelServiceImpl.java b/ts-travel2-service/src/main/java/travel2/service/TravelServiceImpl.java new file mode 100644 index 000000000..5e097f796 --- /dev/null +++ b/ts-travel2-service/src/main/java/travel2/service/TravelServiceImpl.java @@ -0,0 +1,497 @@ +package travel2.service; + +import com.fasterxml.jackson.core.type.TypeReference; +import com.fasterxml.jackson.databind.ObjectMapper; +import edu.fudan.common.entity.*; +import edu.fudan.common.util.JsonUtils; +import edu.fudan.common.util.Response; +import edu.fudan.common.util.StringUtils; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.cloud.client.discovery.DiscoveryClient; +import org.springframework.core.ParameterizedTypeReference; +import org.springframework.http.HttpEntity; +import org.springframework.http.HttpHeaders; +import org.springframework.http.HttpMethod; +import org.springframework.http.ResponseEntity; +import org.springframework.stereotype.Service; +import org.springframework.web.client.RestTemplate; +import travel2.entity.AdminTrip; +import travel2.entity.Trip; +import travel2.entity.Travel; +import travel2.entity.TripAllDetail; +import travel2.repository.TripRepository; + +import javax.transaction.Transactional; +import java.util.*; + +/** + * @author fdse + */ +@Service +public class TravelServiceImpl implements TravelService { + + @Autowired + TripRepository repository; + + @Autowired + private RestTemplate restTemplate; + + @Autowired + private DiscoveryClient discoveryClient; + + private static final Logger LOGGER = LoggerFactory.getLogger(TravelServiceImpl.class); + + private String getServiceUrl(String serviceName) { + return "http://" + serviceName; } + + String success = "Success"; + String noCnontent = "No Content"; + + @Override + public Response getRouteByTripId(String tripId, HttpHeaders headers) { + TripId tripId1 = new TripId(tripId); + + Trip trip = repository.findByTripId(tripId1); + if (trip == null) { + TravelServiceImpl.LOGGER.error("[getRouteByTripId][Get Route By Trip ID Fail][Trip Not Found][TripId: {}]", tripId); + return new Response<>(0, "\"[Get Route By Trip ID] Trip Not Found:\" + tripId", null); + } else { + Route route = getRouteByRouteId(trip.getRouteId(), headers); + if (route == null) { + TravelServiceImpl.LOGGER.error("[getRouteByTripId][Get route by Trip id error][Route not found][RouteId: {}]",trip.getRouteId()); + return new Response<>(0, "\"[Get Route By Trip ID] Route Not Found:\" + trip.getRouteId()", null); + } else { + TravelServiceImpl.LOGGER.info("[getRouteByTripId][Get Route By Trip ID Success]"); + return new Response<>(1, "[Get Route By Trip ID] Success", route); + } + } + } + + + @Override + public Response getTrainTypeByTripId(String tripId, HttpHeaders headers) { + TripId tripId1 = new TripId(tripId); + TrainType trainType = null; + Trip trip = repository.findByTripId(tripId1); + if (trip != null) { + trainType = getTrainTypeByName(trip.getTrainTypeName(), headers); + } + else { + TravelServiceImpl.LOGGER.error("[getTrainTypeByTripId[]Get Train Type by Trip id error][Trip not found][TripId: {}]",tripId); + } + if (trainType != null) { + return new Response<>(1, "Success query Train by trip id", trainType); + } else { + TravelServiceImpl.LOGGER.error("[getTrainTypeByTripId][Get Train Type by Trip id error][Train Type not found][TripId: {}]",tripId); + return new Response<>(0, noCnontent, null); + } + } + + @Override + public Response getTripByRoute(ArrayList routeIds, HttpHeaders headers) { + ArrayList> tripList = new ArrayList<>(); + for (String routeId : routeIds) { + ArrayList tempTripList = repository.findByRouteId(routeId); + if (tempTripList == null) { + tempTripList = new ArrayList<>(); + } + tripList.add(tempTripList); + } + if (!tripList.isEmpty()) { + return new Response<>(1, success, tripList); + } else { + TravelServiceImpl.LOGGER.warn("[getTripByRoute][Get Trips by Route ids warn][Trips not found][RouteIdNumber: {}]",routeIds.size()); + return new Response<>(0, noCnontent, null); + } + } + + @Override + public Response create(edu.fudan.common.entity.TravelInfo info, HttpHeaders headers) { + TripId ti = new TripId(info.getTripId()); + if (repository.findByTripId(ti) == null) { + Trip trip = new Trip(ti, info.getTrainTypeName(), info.getStartStationName(), + info.getStationsName(), info.getTerminalStationName(), info.getStartTime(), info.getEndTime()); + trip.setRouteId(info.getRouteId()); + repository.save(trip); + return new Response<>(1, "Create trip info:" + ti.toString() + ".", null); + } else { + TravelServiceImpl.LOGGER.error("[getTripByRoute][Create trip error][Trip already exists][TripId: {}]",info.getTripId()); + return new Response<>(1, "Trip " + info.getTripId() + " already exists", null); + } + } + + @Override + public Response retrieve(String tripId, HttpHeaders headers) { + TripId ti = new TripId(tripId); + Trip trip = repository.findByTripId(ti); + if (trip != null) { + return new Response<>(1, "Search Trip Success by Trip Id " + tripId, trip); + } else { + TravelServiceImpl.LOGGER.error("[retrieve][Retrieve trip error][Trip not found][TripId: {}]",tripId); + return new Response<>(0, "No Content according to tripId" + tripId, null); + } + } + + @Override + public Response update(edu.fudan.common.entity.TravelInfo info, HttpHeaders headers) { + TripId ti = new TripId(info.getTripId()); + Trip t = repository.findByTripId(ti); + if (t != null) { + t.setStartStationName(info.getTrainTypeName()); + t.setStartStationName( info.getStartStationName()); + t.setStationsName(info.getStationsName()); + t.setTerminalStationName(info.getTerminalStationName()); + t.setStartTime(info.getStartTime()); + t.setEndTime(info.getEndTime()); + t.setRouteId(info.getRouteId()); + repository.save(t); + return new Response<>(1, "Update trip info:" + ti.toString(), t); + } else { + TravelServiceImpl.LOGGER.error("[update][Update trip error][Trip not found][TripId: {}]",info.getTripId()); + return new Response<>(1, "Trip" + info.getTripId() + "doesn 't exists", null); + } + } + + @Override + @Transactional + public Response delete(String tripId, HttpHeaders headers) { + TripId ti = new TripId(tripId); + if (repository.findByTripId(ti) != null) { + repository.deleteByTripId(ti); + return new Response<>(1, "Delete trip:" + tripId + ".", tripId); + } else { + TravelServiceImpl.LOGGER.error("[delete][Delete trip error][Trip not found][TripId: {}]",tripId); + return new Response<>(0, "Trip " + tripId + " doesn't exist.", null); + } + } + + @Override + public Response queryByBatch(TripInfo info, HttpHeaders headers) { + + //Gets the start and arrival stations of the train number to query. The originating and arriving stations received here are both station names, so two requests need to be sent to convert to station ids + String startPlaceName = info.getStartPlace(); + String endPlaceName = info.getEndPlace(); + + //This is the final result + List list = new ArrayList<>(); + + //Check all train info + List allTripList = repository.findAll(); + list = getTicketsByBatch(allTripList, startPlaceName, endPlaceName, info.getDepartureTime(), headers); + return new Response<>(1, success, list); + } + + @Override + public Response query(TripInfo info, HttpHeaders headers) { + + //Gets the start and arrival stations of the train number to query. The originating and arriving stations received here are both station names, so two requests need to be sent to convert to station ids + String StartPlaceName = info.getStartPlace(); + String endPlaceName = info.getEndPlace(); + + //This is the final result + ArrayList list = new ArrayList<>(); + + //Check all train info + ArrayList allTripList = repository.findAll(); + if(allTripList != null){ + for (Trip tempTrip : allTripList) { + //Get the detailed route list of this train + TripResponse response = getTickets(tempTrip, null, StartPlaceName, endPlaceName, info.getDepartureTime(), headers); + if (response == null) { + TravelServiceImpl.LOGGER.warn("[query][Query trip error][Tickets not found][start: {},end: {},time: {}]", StartPlaceName, endPlaceName, info.getDepartureTime()); + }else{ + list.add(response); + } + } + } + return new Response<>(1, "Success Query", list); + } + + @Override + public Response getTripAllDetailInfo(TripAllDetailInfo gtdi, HttpHeaders headers) { + TripAllDetail gtdr = new TripAllDetail(); + TravelServiceImpl.LOGGER.debug("[getTripAllDetailInfo][gtdi info: {}]", gtdi.toString()); + Trip trip = repository.findByTripId(new TripId(gtdi.getTripId())); + if (trip == null) { + gtdr.setTripResponse(null); + gtdr.setTrip(null); + TravelServiceImpl.LOGGER.error("[getTripAllDetailInfo][Get trip detail error][Trip not found][TripId: {}]",gtdi.getTripId()); + return new Response<>(0, "Trip not found", gtdr); + } else { + String endPlaceName = gtdi.getTo(); + String StartPlaceName = gtdi.getFrom(); + TripResponse tripResponse = getTickets(trip, null, gtdi.getFrom(), gtdi.getTo(), gtdi.getTravelDate(), headers); + if (tripResponse == null) { + gtdr.setTrip(null); + gtdr.setTripResponse(null); + TravelServiceImpl.LOGGER.warn("[getTripAllDetailInfo][Query trip error][Tickets not found][start: {},end: {}]", gtdi.getTo(), gtdi.getFrom()); + return new Response<>(0, "getTickets failed", gtdr); + } else { + gtdr.setTripResponse(tripResponse); + gtdr.setTrip(repository.findByTripId(new TripId(gtdi.getTripId()))); + } + } + return new Response<>(1, success, gtdr); + } + + private List getTicketsByBatch(List trips, String startPlaceName, String endPlaceName, String departureTime, HttpHeaders headers) { + List responses = new ArrayList<>(); + //Determine if the date checked is the same day and after + if (!afterToday(departureTime)) { + TravelServiceImpl.LOGGER.info("[getTickets][depaturetime not vailid][departuretime: {}]", departureTime); + return responses; + } + + List infos = new ArrayList<>(); + Map tripMap = new HashMap<>(); + for(Trip trip: trips){ + Travel query = new Travel(); + query.setTrip(trip); + query.setStartPlace(startPlaceName); + query.setEndPlace(endPlaceName); + query.setDepartureTime(departureTime); + + infos.add(query); + tripMap.put(trip.getTripId().toString(), trip); + } + + TravelServiceImpl.LOGGER.info("[getTicketsByBatch][before get basic][trips: {}]", trips); + + HttpEntity requestEntity = new HttpEntity(infos, null); + String basic_service_url = getServiceUrl("ts-basic-service"); + ResponseEntity re = restTemplate.exchange( + basic_service_url + "/api/v1/basicservice/basic/travels", + HttpMethod.POST, + requestEntity, + Response.class); + + Response r = re.getBody(); + if(r.getStatus() == 0){ + TravelServiceImpl.LOGGER.info("[getTicketsByBatch][Ts-basic-service response status is 0][response is: {}]", r); + return responses; + } + Map trMap; + ObjectMapper mapper = new ObjectMapper(); + try{ + trMap = mapper.readValue(JsonUtils.object2Json(r.getData()), new TypeReference>(){}); + }catch(Exception e) { + TravelServiceImpl.LOGGER.warn("[getTicketsByBatch][Ts-basic-service convert data failed][Fail msg: {}]", e.getMessage()); + return responses; + } + + for(Map.Entry trEntry: trMap.entrySet()){ + //Set the returned ticket information + String tripNumber = trEntry.getKey(); + TravelResult tr = trEntry.getValue(); + Trip trip = tripMap.get(tripNumber); + + TripResponse response = setResponse(trip, tr, startPlaceName, endPlaceName, departureTime, headers); + responses.add(response); + } + return responses; + } + + + private TripResponse getTickets(Trip trip, Route route1, String startPlaceName, String endPlaceName, String departureTime, HttpHeaders headers) { + + //Determine if the date checked is the same day and after + if (!afterToday(departureTime)) { + return null; + } + + Travel query = new Travel(); + query.setTrip(trip); + query.setStartPlace(startPlaceName); + query.setEndPlace(endPlaceName); + query.setDepartureTime(departureTime); + + HttpEntity requestEntity = new HttpEntity(query, null); + String basic_service_url = getServiceUrl("ts-basic-service"); + ResponseEntity> re = restTemplate.exchange( + basic_service_url + "/api/v1/basicservice/basic/travel", + HttpMethod.POST, + requestEntity, + new ParameterizedTypeReference>() { + }); + Response r = re.getBody(); + if(r.getStatus() == 0){ + TravelServiceImpl.LOGGER.info("[getTickets][Ts-basic-service response status is 0][response is: {}]", r); + return null; + } + TravelResult resultForTravel = re.getBody().getData(); + + //Set the returned ticket information + return setResponse(trip, resultForTravel, startPlaceName, endPlaceName, departureTime, headers); + } + + private TripResponse setResponse(Trip trip, TravelResult tr, String startPlaceName, String endPlaceName, String departureTime, HttpHeaders headers){ + //Set the returned ticket information + TripResponse response = new TripResponse(); + response.setConfortClass(50); + response.setEconomyClass(50); + + Route route = tr.getRoute(); + List stationList = route.getStations(); + + int firstClassTotalNum = tr.getTrainType().getConfortClass(); + int secondClassTotalNum = tr.getTrainType().getEconomyClass(); + + int first = getRestTicketNumber(departureTime, trip.getTripId().toString(), + startPlaceName, endPlaceName, SeatClass.FIRSTCLASS.getCode(), firstClassTotalNum, stationList, headers); + + int second = getRestTicketNumber(departureTime, trip.getTripId().toString(), + startPlaceName, endPlaceName, SeatClass.SECONDCLASS.getCode(), secondClassTotalNum, stationList, headers); + response.setConfortClass(first); + response.setEconomyClass(second); + + response.setStartStation(startPlaceName); + response.setTerminalStation(endPlaceName); + + //Calculate the distance from the starting point + int indexStart = route.getStations().indexOf(startPlaceName); + int indexEnd = route.getStations().indexOf(endPlaceName); + int distanceStart = route.getDistances().get(indexStart) - route.getDistances().get(0); + int distanceEnd = route.getDistances().get(indexEnd) - route.getDistances().get(0); + TrainType trainType = tr.getTrainType(); + //Train running time is calculated according to the average running speed of the train + int minutesStart = 60 * distanceStart / trainType.getAverageSpeed(); + int minutesEnd = 60 * distanceEnd / trainType.getAverageSpeed(); + + Calendar calendarStart = Calendar.getInstance(); + calendarStart.setTime(StringUtils.String2Date(trip.getStartTime())); + calendarStart.add(Calendar.MINUTE, minutesStart); + response.setStartTime(StringUtils.Date2String(calendarStart.getTime())); + TravelServiceImpl.LOGGER.info("[getTickets][Calculate distance][calculate time:{} time: {}]", minutesStart, calendarStart.getTime()); + + Calendar calendarEnd = Calendar.getInstance(); + calendarEnd.setTime(StringUtils.String2Date(trip.getStartTime())); + calendarEnd.add(Calendar.MINUTE, minutesEnd); + response.setEndTime(StringUtils.Date2String(calendarEnd.getTime())); + TravelServiceImpl.LOGGER.info("[getTickets][Calculate distance][calculate time:{} time: {}]", minutesEnd, calendarEnd.getTime()); + + response.setTripId(trip.getTripId()); + response.setTrainTypeName(trip.getTrainTypeName()); + response.setPriceForConfortClass(tr.getPrices().get("confortClass")); + response.setPriceForEconomyClass(tr.getPrices().get("economyClass")); + + return response; + } + + @Override + public Response queryAll(HttpHeaders headers) { + List tripList = repository.findAll(); + if (tripList != null && !tripList.isEmpty()) { + return new Response<>(1, success, tripList); + } + TravelServiceImpl.LOGGER.warn("[queryAll][Query all trips warn][{}]","No Content"); + return new Response<>(0, noCnontent, null); + } + + private static boolean afterToday(String date) { + Calendar calDateA = Calendar.getInstance(); + Date today = new Date(); + calDateA.setTime(today); + + Calendar calDateB = Calendar.getInstance(); + calDateB.setTime(StringUtils.String2Date(date)); + + if (calDateA.get(Calendar.YEAR) > calDateB.get(Calendar.YEAR)) { + return false; + } else if (calDateA.get(Calendar.YEAR) == calDateB.get(Calendar.YEAR)) { + if (calDateA.get(Calendar.MONTH) > calDateB.get(Calendar.MONTH)) { + return false; + } else if (calDateA.get(Calendar.MONTH) == calDateB.get(Calendar.MONTH)) { + return calDateA.get(Calendar.DAY_OF_MONTH) <= calDateB.get(Calendar.DAY_OF_MONTH); + } else { + return true; + } + } else { + return true; + } + } + + private TrainType getTrainTypeByName(String trainTypeName, HttpHeaders headers) { + HttpEntity requestEntity = new HttpEntity(null); + String train_service_url = getServiceUrl("ts-train-service"); + ResponseEntity> re = restTemplate.exchange( + train_service_url + "/api/v1/trainservice/trains/byName/" + trainTypeName, + HttpMethod.GET, + requestEntity, + new ParameterizedTypeReference>() { + }); + + return re.getBody().getData(); + } + + private Route getRouteByRouteId(String routeId, HttpHeaders headers) { + TravelServiceImpl.LOGGER.debug("[getRouteByRouteId][Get Route By Id][Route ID:{}]", routeId); + HttpEntity requestEntity = new HttpEntity(null); + String route_service_url = getServiceUrl("ts-route-service"); + ResponseEntity re = restTemplate.exchange( + route_service_url + "/api/v1/routeservice/routes/" + routeId, + HttpMethod.GET, + requestEntity, + Response.class); + Response result = re.getBody(); + + if (result.getStatus() == 0 ) { + TravelServiceImpl.LOGGER.error("[getRouteByRouteId][Get Route By Id Fail][Route not found][RouteId: {}]", routeId); + return null; + } else { + TravelServiceImpl.LOGGER.info("[getRouteByRouteId][Get Route By Id Success]"); + return JsonUtils.conveterObject(result.getData(), Route.class); + } + } + + private int getRestTicketNumber(String travelDate, String trainNumber, String startStationName, String endStationName, int seatType, int totalNum, List stationList, HttpHeaders headers) { + Seat seatRequest = new Seat(); + + seatRequest.setDestStation(endStationName); + seatRequest.setStartStation(startStationName); + seatRequest.setTrainNumber(trainNumber); + seatRequest.setTravelDate(travelDate); + seatRequest.setSeatType(seatType); + seatRequest.setTotalNum(totalNum); + seatRequest.setStations(stationList); + + TravelServiceImpl.LOGGER.info("[getRestTicketNumber][Seat request][request: {}]", seatRequest.toString()); + + HttpEntity requestEntity = new HttpEntity(seatRequest, null); + String seat_service_url = getServiceUrl("ts-seat-service"); + ResponseEntity> re = restTemplate.exchange( + seat_service_url + "/api/v1/seatservice/seats/left_tickets", + HttpMethod.POST, + requestEntity, + new ParameterizedTypeReference>() { + }); + TravelServiceImpl.LOGGER.info("[getRestTicketNumber][Get Rest tickets num][num is: {}]", re.getBody().toString()); + + return re.getBody().getData(); + } + + @Override + public Response adminQueryAll(HttpHeaders headers) { + List trips = repository.findAll(); + ArrayList adminTrips = new ArrayList<>(); + if(trips != null){ + for (Trip trip : trips) { + AdminTrip adminTrip = new AdminTrip(); + adminTrip.setRoute(getRouteByRouteId(trip.getRouteId(), headers)); + adminTrip.setTrainType(getTrainTypeByName(trip.getTrainTypeName(), headers)); + adminTrip.setTrip(trip); + adminTrips.add(adminTrip); + } + } + + if (!adminTrips.isEmpty()) { + return new Response<>(1, "Travel Service Admin Query All Travel Success", adminTrips); + } else { + TravelServiceImpl.LOGGER.warn("[adminQueryAll][Admin query all trips warn][{}]","No Content"); + return new Response<>(0, noCnontent, null); + } + } + +} + diff --git a/ts-travel2-service/src/main/resources/application.yml b/ts-travel2-service/src/main/resources/application.yml index 03a5db6dd..59757ff09 100644 --- a/ts-travel2-service/src/main/resources/application.yml +++ b/ts-travel2-service/src/main/resources/application.yml @@ -3,14 +3,23 @@ server: port: 16346 # HTTP (Tomcat) port spring: + cloud: + nacos: + discovery: + server-addr: ${NACOS_ADDRS:nacos-0.nacos-headless.default.svc.cluster.local,nacos-1.nacos-headless.default.svc.cluster.local,nacos-2.nacos-headless.default.svc.cluster.local} application: name: ts-travel2-service - data: - mongodb: - host: ts-travel2-mongo -# username: user -# password: ${MONGODB_PASSWORD} - database: ts - port: 27017 + datasource: + url: jdbc:mysql://${TRAVEL2_MYSQL_HOST:ts-travel2-mysql}:${TRAVEL2_MYSQL_PORT:3306}/${TRAVEL2_MYSQL_DATABASE:ts-travel2-mysql}?useSSL=false + username: ${TRAVEL2_MYSQL_USER:root} + password: ${TRAVEL2_MYSQL_PASSWORD:Abcd1234#} + driver-class-name: com.mysql.cj.jdbc.Driver + + jpa: + hibernate: + ddl-auto: update + properties: + hibernate: + dialect: org.hibernate.dialect.MySQL5Dialect swagger: - controllerPackage: travel2.controller \ No newline at end of file + controllerPackage: travel2.controller diff --git a/ts-travel2-service/src/test/java/travel2/controller/Travel2ControllerTest.java b/ts-travel2-service/src/test/java/travel2/controller/TravelControllerTest.java similarity index 95% rename from ts-travel2-service/src/test/java/travel2/controller/Travel2ControllerTest.java rename to ts-travel2-service/src/test/java/travel2/controller/TravelControllerTest.java index 9def0b5ac..8c7f0e657 100644 --- a/ts-travel2-service/src/test/java/travel2/controller/Travel2ControllerTest.java +++ b/ts-travel2-service/src/test/java/travel2/controller/TravelControllerTest.java @@ -16,23 +16,23 @@ import org.springframework.test.web.servlet.request.MockMvcRequestBuilders; import org.springframework.test.web.servlet.result.MockMvcResultMatchers; import org.springframework.test.web.servlet.setup.MockMvcBuilders; -import travel2.entity.TravelInfo; -import travel2.entity.TripAllDetailInfo; -import travel2.entity.TripInfo; -import travel2.entity.TripResponse; -import travel2.service.Travel2Service; +import edu.fudan.common.entity.TravelInfo; +import edu.fudan.common.entity.TripAllDetailInfo; +import edu.fudan.common.entity.TripInfo; +import edu.fudan.common.entity.TripResponse; +import travel2.service.TravelService; import java.util.ArrayList; import java.util.Date; @RunWith(JUnit4.class) -public class Travel2ControllerTest { +public class TravelControllerTest { @InjectMocks private Travel2Controller travel2Controller; @Mock - private Travel2Service service; + private TravelService service; private MockMvc mockMvc; private Response response = new Response(); @@ -131,7 +131,7 @@ public void testQueryInfo1() throws Exception { @Test public void testQueryInfo2() throws Exception { - TripInfo info = new TripInfo("startingPlace", "endPlace", new Date()); + TripInfo info = new TripInfo("startPlace", "endPlace", ""); Mockito.when(service.query(Mockito.any(TripInfo.class), Mockito.any(HttpHeaders.class))).thenReturn(response); String requestJson = JSONObject.toJSONString(info); String result = mockMvc.perform(MockMvcRequestBuilders.post("/api/v1/travel2service/trips/left").contentType(MediaType.APPLICATION_JSON).content(requestJson)) diff --git a/ts-travel2-service/src/test/java/travel2/service/Travel2ServiceImplTest.java b/ts-travel2-service/src/test/java/travel2/service/TravelServiceImplTest.java similarity index 86% rename from ts-travel2-service/src/test/java/travel2/service/Travel2ServiceImplTest.java rename to ts-travel2-service/src/test/java/travel2/service/TravelServiceImplTest.java index 417cbb1e6..8323efb20 100644 --- a/ts-travel2-service/src/test/java/travel2/service/Travel2ServiceImplTest.java +++ b/ts-travel2-service/src/test/java/travel2/service/TravelServiceImplTest.java @@ -1,6 +1,10 @@ package travel2.service; +import edu.fudan.common.entity.TripId; +import edu.fudan.common.entity.TripAllDetailInfo; +import edu.fudan.common.entity.TripInfo; import edu.fudan.common.util.Response; +import edu.fudan.common.util.StringUtils; import org.junit.Assert; import org.junit.Before; import org.junit.Test; @@ -13,17 +17,17 @@ import org.springframework.core.ParameterizedTypeReference; import org.springframework.http.*; import org.springframework.web.client.RestTemplate; -import travel2.entity.*; +import travel2.entity.Trip; import travel2.repository.TripRepository; import java.util.ArrayList; import java.util.Date; @RunWith(JUnit4.class) -public class Travel2ServiceImplTest { +public class TravelServiceImplTest { @InjectMocks - private Travel2ServiceImpl travel2ServiceImpl; + private TravelServiceImpl travel2ServiceImpl; @Mock private TripRepository repository; @@ -52,7 +56,7 @@ public void testGetRouteByTripId2() { Trip trip = new Trip(); Mockito.when(repository.findByTripId(Mockito.any(TripId.class))).thenReturn(trip); //mock getRouteByRouteId() - Route route = new Route(); + edu.fudan.common.entity.Route route = new edu.fudan.common.entity.Route(); Response response = new Response(1, null, route); ResponseEntity re = new ResponseEntity<>(response, HttpStatus.OK); Mockito.when(restTemplate.exchange( @@ -70,9 +74,9 @@ public void testGetTrainTypeByTripId() { Trip trip = new Trip(); Mockito.when(repository.findByTripId(Mockito.any(TripId.class))).thenReturn(trip); //mock getTrainType() - TrainType trainType = new TrainType(); - Response response = new Response<>(null, null, trainType); - ResponseEntity> re = new ResponseEntity<>(response, HttpStatus.OK); + edu.fudan.common.entity.TrainType trainType = new edu.fudan.common.entity.TrainType(); + Response response = new Response<>(null, null, trainType); + ResponseEntity> re = new ResponseEntity<>(response, HttpStatus.OK); Mockito.when(restTemplate.exchange( Mockito.anyString(), Mockito.any(HttpMethod.class), @@ -101,7 +105,7 @@ public void testGetTripByRoute2() { @Test public void testCreate1() { - TravelInfo info = new TravelInfo(); + edu.fudan.common.entity.TravelInfo info = new edu.fudan.common.entity.TravelInfo(); info.setTripId("Z"); Mockito.when(repository.findByTripId(Mockito.any(TripId.class))).thenReturn(null); Mockito.when(repository.save(Mockito.any(Trip.class))).thenReturn(null); @@ -111,7 +115,7 @@ public void testCreate1() { @Test public void testCreate2() { - TravelInfo info = new TravelInfo(); + edu.fudan.common.entity.TravelInfo info = new edu.fudan.common.entity.TravelInfo(); info.setTripId("Z"); Trip trip = new Trip(); Mockito.when(repository.findByTripId(Mockito.any(TripId.class))).thenReturn(trip); @@ -137,7 +141,7 @@ public void testRetrieve2() { @Test public void testUpdate1() { - TravelInfo info = new TravelInfo(); + edu.fudan.common.entity.TravelInfo info = new edu.fudan.common.entity.TravelInfo(); info.setTripId("Z"); Trip trip = new Trip(); Mockito.when(repository.findByTripId(Mockito.any(TripId.class))).thenReturn(trip); @@ -148,7 +152,7 @@ public void testUpdate1() { @Test public void testUpdate2() { - TravelInfo info = new TravelInfo(); + edu.fudan.common.entity.TravelInfo info = new edu.fudan.common.entity.TravelInfo(); info.setTripId("Z"); Mockito.when(repository.findByTripId(Mockito.any(TripId.class))).thenReturn(null); Response result = travel2ServiceImpl.update(info, headers); @@ -191,7 +195,7 @@ public void testQuery() { Mockito.when(repository.findAll()).thenReturn(tripList); //mock getRouteByRouteId() - Route route = new Route(); + edu.fudan.common.entity.Route route = new edu.fudan.common.entity.Route(); route.setStations(new ArrayList<>()); Response response2 = new Response(1, null, route); ResponseEntity re2 = new ResponseEntity<>(response2, HttpStatus.OK); @@ -211,7 +215,7 @@ public void testGetTripAllDetailInfo() { gtdi.setTripId("Z1255"); gtdi.setFrom("from_station"); gtdi.setTo("to_station"); - gtdi.setTravelDate(new Date(System.currentTimeMillis() - 86400000)); + gtdi.setTravelDate(StringUtils.Date2String(new Date(System.currentTimeMillis() - 86400000))); Trip trip = new Trip(); trip.setRouteId("route_id"); @@ -228,7 +232,7 @@ public void testGetTripAllDetailInfo() { .thenReturn(re1); //mock getRouteByRouteId() - Route route = new Route(); + edu.fudan.common.entity.Route route = new edu.fudan.common.entity.Route(); route.setStations(new ArrayList<>()); Response response2 = new Response(1, null, route); ResponseEntity re2 = new ResponseEntity<>(response2, HttpStatus.OK); @@ -267,7 +271,7 @@ public void testAdminQueryAll1() { Mockito.when(repository.findAll()).thenReturn(tripList); //mock getRouteByRouteId() - Route route = new Route(); + edu.fudan.common.entity.Route route = new edu.fudan.common.entity.Route(); Response response2 = new Response(1, null, route); ResponseEntity re2 = new ResponseEntity<>(response2, HttpStatus.OK); Mockito.when(restTemplate.exchange( @@ -278,9 +282,9 @@ public void testAdminQueryAll1() { .thenReturn(re2); //mock getTrainType() - TrainType trainType = new TrainType(); - Response response = new Response<>(null, null, trainType); - ResponseEntity> re = new ResponseEntity<>(response, HttpStatus.OK); + edu.fudan.common.entity.TrainType trainType = new edu.fudan.common.entity.TrainType(); + Response response = new Response<>(null, null, trainType); + ResponseEntity> re = new ResponseEntity<>(response, HttpStatus.OK); Mockito.when(restTemplate.exchange( Mockito.anyString(), Mockito.any(HttpMethod.class), diff --git a/ts-ui-dashboard/nginx.conf b/ts-ui-dashboard/nginx.conf index 2968355d9..c9b8a6458 100644 --- a/ts-ui-dashboard/nginx.conf +++ b/ts-ui-dashboard/nginx.conf @@ -37,358 +37,9 @@ http { } - # For travel service - location /api/v1/travelservice/trips/left { - proxy_pass http://ts-travel-service:12346; - } - # For travel2 service - location /api/v1/travel2service/trips/left { - proxy_pass http://ts-travel2-service:16346; - } - - # For account and verification - location /api/v1/userservice/users { - proxy_pass http://ts-user-service:12342; - } - location /api/v1/users/auth { - proxy_pass http://ts-auth-service:12340; - } - - location /api/v1/users/login { - proxy_pass http://ts-auth-service:12340; - } - - location /api/v1/verifycode/generate { - proxy_ignore_client_abort on ; - proxy_pass http://ts-verification-code-service:15678; - } - - - # For station service - location /api/v1/stationservice { - proxy_pass http://ts-station-service:12345; - } - - # For train service - location /api/v1/trainservice { - proxy_pass http://ts-train-service:14567; - } - - # For config service - location /api/v1/configservice { - proxy_pass http://ts-config-service:15679; - } - - # For security service - - location /api/v1/securityservice { - proxy_pass http://ts-security-service:11188; - } - - # For Execute service - - location /api/v1/executeservice/execute/execute { - proxy_pass http://ts-execute-service:12386; - } - location /api/v1/executeservice/execute/collected { - proxy_pass http://ts-execute-service:12386; - } - - - # For contacts service - - location /api/v1/contactservice/contacts { - proxy_pass http://ts-contacts-service:12347; - } - - location /api/v1/contactservice/contacts/account { - proxy_pass http://ts-contacts-service:12347; - } - - - # For order service - location /api/v1/orderservice/order/refresh { - proxy_pass http://ts-order-service:12031; - } - - # For order other service - - location /api/v1/orderOtherService/orderOther/refresh { - proxy_pass http://ts-order-other-service:12032; - } - - #For preserve service - - location /api/v1/preserveservice/preserve { - proxy_pass http://ts-preserve-service:14568; - } - - #For preserve other service - - location /api/v1/preserveotherservice/preserveOther { - proxy_pass http://ts-preserve-other-service:14569; - } - - - #For price service - location /price/query { - proxy_pass http://ts-price-service:16579; - } - location /price/queryAll { - proxy_pass http://ts-price-service:16579; - } - location /price/create { - proxy_pass http://ts-price-service:16579; - } - location /price/delete { - proxy_pass http://ts-price-service:16579; - } - location /price/update { - proxy_pass http://ts-price-service:16579; - } - - #For basic information service - location /basic/queryForTravel { - proxy_pass http://ts-basic-service:15680; - } - - #For ticket information service - location /ticketinfo/queryForTravel { - proxy_pass http://ts-ticketinfo-service:15681; - } - - #For notification service - location /notification/preserve_success { - proxy_pass http://ts-notification-service:17853; - } - location /notification/order_create_success { - proxy_pass http://ts-notification-service:17853; - } - location /notification/order_changed_success { - proxy_pass http://ts-notification-service:17853; - } - - #For inside payment service - location /api/v1/inside_pay_service/inside_payment { - proxy_pass http://ts-inside-payment-service:18673; - } - - - #For payment service - location /payment/pay { - proxy_pass http://ts-payment-service:19001; - } - location /payment/addMoney { - proxy_pass http://ts-payment-service:19001; - } - location /payment/query { - proxy_pass http://ts-payment-service:19001; - } - - #For rebook service - location /rebook { - proxy_pass http://ts-rebook-service:18886; - } - - #For cancel Order - location /api/v1/cancelservice/cancel { - proxy_pass http://ts-cancel-service:18885; - } - location /api/v1/cancelservice/cancel/refound { - proxy_pass http://ts-cancel-service:18885; - } - #For station name - location /api/v1/stationservice/stations/name { - proxy_pass http://ts-station-service:12345; + location /api/v1/ { + proxy_pass http://ts-gateway-service:18888; } - #For rebook - location /api/v1/rebookservice/rebook { - proxy_pass http://ts-rebook-service:18886; - } - location /api/v1/rebookservice/rebook/difference { - proxy_pass http://ts-rebook-service:18886; - } - - #For Route - location /route/createAndModify { - proxy_pass http://ts-route-service:11178; - } - location /route/delete { - proxy_pass http://ts-route-service:11178; - } - location /route/queryAll { - proxy_pass http://ts-route-service:11178; - } - location /route/queryById { - proxy_pass http://ts-route-service:11178; - } - location /route/queryByStartAndTerminal { - proxy_pass http://ts-route-service:11178; - } - - #For Assurance - location /api/v1/assuranceservice/assurances/types { - proxy_pass http://ts-assurance-service:18888; - } - location /assurance/getAssuranceById { - proxy_pass http://ts-assurance-service:18888; - } - location /assurance/findAssuranceByOrderId { - proxy_pass http://ts-assurance-service:18888; - } - location /assurance/findAll { - proxy_pass http://ts-assurance-service:18888; - } - location /assurance/create { - proxy_pass http://ts-assurance-service:18888; - } - location /assurance/deleteAssurance { - proxy_pass http://ts-assurance-service:18888; - } - location /assurance/deleteAssuranceByOrderId { - proxy_pass http://ts-assurance-service:18888; - } - location /assurance/modifyAssurance { - proxy_pass http://ts-assurance-service:18888; - } - - #For Ticket Office - location /office/getRegionList { - proxy_pass http://ts-ticket-office-service:16108; - } - location /office/getAll { - proxy_pass http://ts-ticket-office-service:16108; - } - location /office/getSpecificOffices { - proxy_pass http://ts-ticket-office-service:16108; - } - location /office/addOffice { - proxy_pass http://ts-ticket-office-service:16108; - } - location /office/deleteOffice { - proxy_pass http://ts-ticket-office-service:16108; - } - location /office/updateOffice { - proxy_pass http://ts-ticket-office-service:16108; - } - - #For Travel Transit - location /travelPlan/getTransferResult { - proxy_pass http://ts-travel-plan-service:14322; - } - location /api/v1/travelplanservice/travelPlan/cheapest { - proxy_pass http://ts-travel-plan-service:14322; - } - location /api/v1/travelplanservice/travelPlan/quickest { - proxy_pass http://ts-travel-plan-service:14322; - } - location /api/v1/travelplanservice/travelPlan/minStation { - proxy_pass http://ts-travel-plan-service:14322; - } - - #For Consign and Voucher - location /api/v1/consignservice/consigns { - proxy_pass http://ts-consign-service:16111; - } - location /api/v1/consignservice/consigns/account { - proxy_pass http://ts-consign-service:16111; - } - location /getVoucher { - proxy_pass http://ts-voucher-service:16101; - } - - #For Route Plan - location /routePlan/minStopStations { - proxy_pass http://ts-route-plan-service:14578; - } - location /routePlan/cheapestRoute { - proxy_pass http://ts-route-plan-service:14578; - } - location /routePlan/quickestRoute { - proxy_pass http://ts-route-plan-service:14578; - } - - #For Food - location ^~ /api/v1/foodservice { - proxy_pass http://ts-food-service:18856; - } - - location /api/v1/foodservice/foods { - proxy_pass http://ts-food-service:18856; - } - location /food/createFoodOrder { - proxy_pass http://ts-food-service:18856; - } - location /food/cancelFoodOrder { - proxy_pass http://ts-food-service:18856; - } - location /food/updateFoodOrder { - proxy_pass http://ts-food-service:18856; - } - location /food/findAllFoodOrder { - proxy_pass http://ts-food-service:18856; - } - location /food/findFoodOrderByOrderId { - proxy_pass http://ts-food-service:18856; - } - - #For Food - location /news-service/news { - proxy_pass http://ts-news-service:12862; - } - - #For Admin basic info - location /api/v1/adminbasicservice/adminbasic/contacts { - proxy_pass http://ts-admin-basic-info-service:18767; - } - - location /api/v1/adminbasicservice/adminbasic/stations { - proxy_pass http://ts-admin-basic-info-service:18767; - } - - - location /api/v1/adminbasicservice/adminbasic/trains { - proxy_pass http://ts-admin-basic-info-service:18767; - } - - - location /api/v1/adminbasicservice/adminbasic/prices { - proxy_pass http://ts-admin-basic-info-service:18767; - } - - - location /api/v1/adminbasicservice/adminbasic/configs { - proxy_pass http://ts-admin-basic-info-service:18767; - } - - - #For Admin Order - location /api/v1/adminorderservice/adminorder { - proxy_pass http://ts-admin-order-service:16112; - } - - - #For Admin Route - location /api/v1/adminrouteservice/adminroute { - proxy_pass http://ts-admin-route-service:16113; - } - - - #For Admin Travel - location /api/v1/admintravelservice/admintravel { - proxy_pass http://ts-admin-travel-service:16114; - } - - - #For Admin User - location /api/v1/adminuserservice/users { - proxy_pass http://ts-admin-user-service:16115; - } - - #For Avatar Service - location /api/v1/avatar { - proxy_pass http://ts-avatar-service:17001; - } } } diff --git a/ts-ui-dashboard/static/add&delete.html b/ts-ui-dashboard/static/add&delete.html index ac8eb3511..83f802978 100644 --- a/ts-ui-dashboard/static/add&delete.html +++ b/ts-ui-dashboard/static/add&delete.html @@ -362,9 +362,9 @@

- +
- +
@@ -380,9 +380,9 @@

- +
- +
@@ -411,9 +411,9 @@

- +
- +
@@ -429,9 +429,9 @@

- +
- +
diff --git a/ts-ui-dashboard/static/admin.html b/ts-ui-dashboard/static/admin.html index 034d3891e..5ff8d4b9e 100644 --- a/ts-ui-dashboard/static/admin.html +++ b/ts-ui-dashboard/static/admin.html @@ -14,10 +14,10 @@ + - @@ -433,8 +433,7 @@
+ class="am-modal-prompt-input">
@@ -443,8 +442,7 @@
+ class="am-modal-prompt-input">
@@ -453,26 +451,26 @@
+ class="am-modal-prompt-input">
- +
- +
@@ -480,9 +478,12 @@ class="am-u-sm-5 am-form-label">Document Type:
- +
@@ -500,9 +501,10 @@ class="am-u-sm-5 am-form-label">Train Number:
- +
@@ -519,9 +521,17 @@
- +
@@ -556,9 +566,16 @@
- +
@@ -608,6 +625,8 @@ + + \ No newline at end of file diff --git a/ts-ui-dashboard/static/admin_station.html b/ts-ui-dashboard/static/admin_station.html index 4b8deeb8a..668bb172c 100644 --- a/ts-ui-dashboard/static/admin_station.html +++ b/ts-ui-dashboard/static/admin_station.html @@ -248,15 +248,6 @@
Add Station
-
-
- -
-
- -
-
diff --git a/ts-ui-dashboard/static/admin_train.html b/ts-ui-dashboard/static/admin_train.html index 74ee5d8eb..c750be761 100644 --- a/ts-ui-dashboard/static/admin_train.html +++ b/ts-ui-dashboard/static/admin_train.html @@ -171,7 +171,7 @@ - {{train.id}} + {{train.name}} {{train.economyClass}} {{train.confortClass}} {{train.averageSpeed}} @@ -224,11 +224,11 @@
Update Train
- +
- +
@@ -268,14 +268,14 @@
-
Add Train
+
Add Train Type
- +
- +
diff --git a/ts-ui-dashboard/static/admin_travel.html b/ts-ui-dashboard/static/admin_travel.html index 7bdb92dcb..fa073925f 100644 --- a/ts-ui-dashboard/static/admin_travel.html +++ b/ts-ui-dashboard/static/admin_travel.html @@ -14,10 +14,10 @@ + - @@ -182,10 +182,10 @@ Operation Id - TrainTypeId + TrainTypeName RouteId - StartingTime - StartingStation + startTime + startStation TerminalStation StationList DistanceList @@ -211,11 +211,11 @@
{{record.trip.tripId.type + "" + record.trip.tripId.number}} - {{record.trip.trainTypeId}} + {{record.trainType.name}} {{record.trip.routeId}} - {{record.trip.startingTime}} - {{record.route.startStationId}} - {{record.route.terminalStationId}} + {{record.trip.startTime}} + {{record.trip.startStationName}} + {{record.trip.terminalStationName}} {{record.route.stations}} {{record.route.distances}} {{record.trainType.economyClass}} @@ -247,9 +247,9 @@ class="am-u-sm-5 am-form-label">TrainType Id:
- +
@@ -261,6 +261,33 @@ ng-model="update_travel_route_id">
+
+ +
+ +
+
+
+ +
+ +
+
+
+ +
+ +
+
@@ -270,6 +297,15 @@ ng-model="update_travel_start_time">
+
+ +
+ +
+
@@ -314,21 +350,51 @@
- +
- + +
+
+
+ +
+ +
+
+
+ +
+ +
+
+
+ +
+
@@ -336,8 +402,15 @@ class="am-u-sm-5 am-form-label">Start Time:
+ class="am-modal-prompt-input"> +
+
+
+ +
+
@@ -378,6 +451,9 @@ + + + \ No newline at end of file diff --git a/ts-ui-dashboard/static/admin_user.html b/ts-ui-dashboard/static/admin_user.html index f8d851215..16f917744 100644 --- a/ts-ui-dashboard/static/admin_user.html +++ b/ts-ui-dashboard/static/admin_user.html @@ -345,9 +345,11 @@
- +
@@ -364,9 +366,12 @@ class="am-u-sm-5 am-form-label">Document Type:
- +
diff --git a/ts-ui-dashboard/static/assets/css/amazeui.datetimepicker.css b/ts-ui-dashboard/static/assets/css/amazeui.datetimepicker.css new file mode 100644 index 000000000..c4952e27c --- /dev/null +++ b/ts-ui-dashboard/static/assets/css/amazeui.datetimepicker.css @@ -0,0 +1,10 @@ +/*! + * Datetimepicker for Amaze UI + * + * Copyright 2012 Stefan Petre + * Improvements by Andrew Rowls + * Improvements by Sébastien Malot + * Licensed under the Apache License v2.0 + * http://www.apache.org/licenses/LICENSE-2.0 + */ +.datetimepicker{margin-top:10px;border-radius:2px;-webkit-box-shadow:0 0 6px #ccc;box-shadow:0 0 6px #ccc;text-align:center}.datetimepicker:before{content:'';display:inline-block;width:0;height:0;vertical-align:middle;border-bottom:7px solid #3bb4f2;border-right:7px solid transparent;border-left:7px solid transparent;border-top:0 dotted;-webkit-transform:rotate(360deg);-ms-transform:rotate(360deg);transform:rotate(360deg);position:absolute}.datetimepicker.datetimepicker-rtl{direction:rtl}.datetimepicker.datetimepicker-rtl table tr td span{float:right}.datetimepicker>div{display:none}.datetimepicker table{width:238px;background:#3bb4f2;border-radius:2px}.datetimepicker table th,.datetimepicker table th.next,.datetimepicker table th.prev{-webkit-transition:background-color 300ms ease-out;transition:background-color 300ms ease-out}.datetimepicker table th{width:34px;height:40px;text-align:center;font-weight:400}.datetimepicker table th.switch{width:170px;background:#3bb4f2;color:#fff;cursor:pointer}.datetimepicker table th.next:hover,.datetimepicker table th.prev:hover,.datetimepicker table th.switch:hover{background:rgba(16,160,234,.5);color:#0084c7}.datetimepicker table th.next,.datetimepicker table th.prev{background:#3bb4f2;color:#fff;cursor:pointer}.datetimepicker table th.next i,.datetimepicker table th.prev i{width:34px;height:34px;display:inline-block}.datetimepicker table th.next{border-top-right-radius:2px}.datetimepicker table th.prev{border-top-left-radius:2px}.datetimepicker table th.dow{color:#3bb4f2;background:#fff}.datetimepicker table th.today{background:#fff;color:#3bb4f2;cursor:pointer}.datetimepicker table th.today:hover,.datetimepicker-days td:hover,.datetimepicker-hours span.hour:hover,.datetimepicker-hours span.minute:hover,.datetimepicker-hours span.month:hover,.datetimepicker-hours span.year:hover,.datetimepicker-minutes span.hour:hover,.datetimepicker-minutes span.minute:hover,.datetimepicker-minutes span.month:hover,.datetimepicker-minutes span.year:hover,.datetimepicker-months span.hour:hover,.datetimepicker-months span.minute:hover,.datetimepicker-months span.month:hover,.datetimepicker-months span.year:hover,.datetimepicker-years span.hour:hover,.datetimepicker-years span.minute:hover,.datetimepicker-years span.month:hover,.datetimepicker-years span.year:hover{background:#f0f0f0}.datetimepicker table .icon-arrow-left:before,.datetimepicker table .icon-arrow-right:before{display:inline-block;font:1.6rem/1 "FontAwesome",sans-serif;font-size:inherit;text-rendering:auto;-webkit-font-smoothing:antialiased;-moz-osx-font-smoothing:grayscale;-webkit-transform:translate(0,0);-ms-transform:translate(0,0);transform:translate(0,0);content:"\f053";vertical-align:bottom}.datetimepicker table .icon-arrow-right:before{content:"\f054"}.datetimepicker table td{width:34px;height:34px;cursor:pointer;font-size:1.4rem;color:#555;background:#fff}.datetimepicker table td.today{background:rgba(16,160,234,.5);color:#fff}.datetimepicker table span.active,.datetimepicker table td.active{background:#ececec;color:#3bb4f2}.datetimepicker table .new,.datetimepicker table .old{color:#89d7ff}.datetimepicker table .disabled{background:#fafafa;color:#999;cursor:not-allowed}.datetimepicker-hours table td,.datetimepicker-minutes table td,.datetimepicker-months table td,.datetimepicker-years table td{height:auto;background:#fff}.datetimepicker-hours table td:after,.datetimepicker-hours table td:before,.datetimepicker-minutes table td:after,.datetimepicker-minutes table td:before,.datetimepicker-months table td:after,.datetimepicker-months table td:before,.datetimepicker-years table td:after,.datetimepicker-years table td:before{content:" ";display:table}.datetimepicker-hours table td:after,.datetimepicker-minutes table td:after,.datetimepicker-months table td:after,.datetimepicker-years table td:after{clear:both}.datetimepicker-hours span.hour,.datetimepicker-hours span.minute,.datetimepicker-hours span.month,.datetimepicker-hours span.year,.datetimepicker-minutes span.hour,.datetimepicker-minutes span.minute,.datetimepicker-minutes span.month,.datetimepicker-minutes span.year,.datetimepicker-months span.hour,.datetimepicker-months span.minute,.datetimepicker-months span.month,.datetimepicker-months span.year,.datetimepicker-years span.hour,.datetimepicker-years span.minute,.datetimepicker-years span.month,.datetimepicker-years span.year{float:left;height:38px;width:59.5px;line-height:38px}.datetimepicker-hours fieldset,.datetimepicker-hours legend,.datetimepicker-minutes fieldset,.datetimepicker-minutes legend{margin:0;padding:0}.datetimepicker-inline{width:238px}.datetimepicker-inline:before{content:none}.datetimepicker-dropdown-bottom-right:before{top:-7px;left:10px}.datetimepicker-dropdown-bottom-left:before{top:-7px;right:10px}.datetimepicker-dropdown-top-left,.datetimepicker-dropdown-top-right{margin-top:0}.datetimepicker-dropdown-top-left:before,.datetimepicker-dropdown-top-right:before{display:inline-block;width:0;height:0;vertical-align:middle;border-top:7px solid #fff;border-right:7px solid transparent;border-left:7px solid transparent;border-bottom:0 dotted;-webkit-transform:rotate(360deg);-ms-transform:rotate(360deg);transform:rotate(360deg);bottom:-7px;right:10px}.am-input-group.date span.add-on{cursor:pointer}.dropdown-menu{position:absolute;display:none}@media only screen and (max-width:640px){.datetimepicker{width:100%;left:0!important}.datetimepicker table{width:100%}.datetimepicker td span.hour,.datetimepicker td span.minute,.datetimepicker td span.month,.datetimepicker td span.year{width:25%}.datetimepicker:before{content:none}.next,.prev{width:44px;height:44px}} \ No newline at end of file diff --git a/ts-ui-dashboard/static/assets/js/admin_price.js b/ts-ui-dashboard/static/assets/js/admin_price.js index dd3350126..56881a6bf 100644 --- a/ts-ui-dashboard/static/assets/js/admin_price.js +++ b/ts-ui-dashboard/static/assets/js/admin_price.js @@ -46,16 +46,9 @@ priceModule.controller("priceCtrl", function ($scope, $http, loadDataService, $w onConfirm: function (options) { $http({ method: "delete", - url: "/api/v1/adminbasicservice/adminbasic/prices", + url: "/api/v1/adminbasicservice/adminbasic/prices/"+price.id, headers: {"Authorization": "Bearer " + sessionStorage.getItem("admin_token")}, withCredentials: true, - data: { - id: price.id, - routeId: price.routeId, - trainType: price.trainType, - basicPriceRate: price.basicPriceRate, - firstClassPriceRate: price.firstClassPriceRate - } }).success(function (data, status, headers, config) { if (data.status ==1) { alert("Delete price successfully!"); diff --git a/ts-ui-dashboard/static/assets/js/admin_station.js b/ts-ui-dashboard/static/assets/js/admin_station.js index c1d7d3ad3..e62fb52b7 100644 --- a/ts-ui-dashboard/static/assets/js/admin_station.js +++ b/ts-ui-dashboard/static/assets/js/admin_station.js @@ -47,14 +47,9 @@ stationModule.controller("stationCtrl", function ($scope, $http, loadDataService onConfirm: function (options) { $http({ method: "delete", - url: "/api/v1/adminbasicservice/adminbasic/stations", + url: "/api/v1/adminbasicservice/adminbasic/stations/"+station.id, headers: {"Authorization": "Bearer " + sessionStorage.getItem("admin_token")}, withCredentials: true, - data: { - id: station.id, - name: station.name, - stayTime: station.stayTime - } }).success(function (data, status, headers, config) { if (data.status ==1) { alert("Delete station successfully!"); @@ -115,7 +110,6 @@ stationModule.controller("stationCtrl", function ($scope, $http, loadDataService }; $scope.addStation = function () { - $('#add-station-id').val(""); $('#add-station-name').val(""); $('#add-station-stay-time').val(""); @@ -124,7 +118,6 @@ stationModule.controller("stationCtrl", function ($scope, $http, loadDataService onConfirm: function (options) { if (parseInt($('#add-station-stay-time').val())) { var data = new Object(); - data.id = $('#add-station-id').val(); data.name = $('#add-station-name').val(); data.stayTime = parseInt($('#add-station-stay-time').val()); // alert(JSON.stringify(data)); diff --git a/ts-ui-dashboard/static/assets/js/admin_train.js b/ts-ui-dashboard/static/assets/js/admin_train.js index b3fa57142..a3412f895 100644 --- a/ts-ui-dashboard/static/assets/js/admin_train.js +++ b/ts-ui-dashboard/static/assets/js/admin_train.js @@ -68,7 +68,7 @@ trainModule.controller("trainCtrl", function ($scope, $http, loadDataService, $w }; $scope.updateTrain = function (train) { - $('#update-train-id').val(train.id); + $('#update-train-name').val(train.name); $('#update-train-economy-class').val(train.economyClass); $('#update-train-confort-class').val(train.confortClass); $('#update-train-average-speed').val(train.averageSpeed); @@ -79,6 +79,7 @@ trainModule.controller("trainCtrl", function ($scope, $http, loadDataService, $w if (parseInt($('#update-train-economy-class').val()) && parseInt($('#update-train-confort-class').val()) && parseInt($('#update-train-average-speed').val())) { var data = new Object(); data.id = train.id; + data.name = train.name; data.economyClass = parseInt($('#update-train-economy-class').val()); data.confortClass = parseInt($('#update-train-confort-class').val()); data.averageSpeed = parseInt($('#update-train-average-speed').val()); @@ -110,7 +111,7 @@ trainModule.controller("trainCtrl", function ($scope, $http, loadDataService, $w }; $scope.addTrain = function () { - $('#add-train-id').val(""); + $('#add-train-type-name').val(""); $('#add-train-economy-class').val(""); $('#add-train-confort-class').val(""); $('#add-train-average-speed').val(""); @@ -120,7 +121,7 @@ trainModule.controller("trainCtrl", function ($scope, $http, loadDataService, $w onConfirm: function (options) { if (parseInt($('#add-train-economy-class').val()) && parseInt($('#add-train-confort-class').val()) && parseInt($('#add-train-average-speed').val())) { var data = new Object(); - data.id = $('#add-train-id').val(); + data.name = $('#add-train-type-name').val(); data.economyClass = parseInt($('#add-train-economy-class').val()); data.confortClass = parseInt($('#add-train-confort-class').val()); data.averageSpeed = parseInt($('#add-train-average-speed').val()); diff --git a/ts-ui-dashboard/static/assets/js/admin_travel.js b/ts-ui-dashboard/static/assets/js/admin_travel.js index 08971c18e..a76f3a19d 100644 --- a/ts-ui-dashboard/static/assets/js/admin_travel.js +++ b/ts-ui-dashboard/static/assets/js/admin_travel.js @@ -76,6 +76,7 @@ app.controller('indexCtrl', function ($scope, $http, $window, loadDataService) { //首次加载显示数据 loadDataService.loadRecordList(param).then(function (result) { $scope.records = result.travelRecords; + console.log(result.travelRecords) //$scope.decodeInfo(result.orderRecords[0]); }); @@ -87,6 +88,9 @@ app.controller('indexCtrl', function ($scope, $http, $window, loadDataService) { alert(des); } + //init optional table item + getOptionsData(); + //Add new travel $scope.addNewTravel = function () { $('#add_prompt').modal({ @@ -99,9 +103,13 @@ app.controller('indexCtrl', function ($scope, $http, $window, loadDataService) { withCredentials: true, data: { tripId: $scope.add_travel_id, - trainTypeId: $scope.add_travel_train_type_id, - routeId: $scope.add_travel_route_id, - startingTime: $scope.add_travel_start_time + trainTypeName: $('#add_travel_train_type_id').find("option:selected").val(), + routeId: $('#add_travel_route_id').find("option:selected").val(), + startStationName: $('#add_travel_start_station').find("option:selected").val(), + stationsName: $('#add_travel_station_name').find("option:selected").val(), + terminalStationName: $('#add_travel_terminal_station').find("option:selected").val(), + startTime: $('#add_travel_start_time').val(), + endTime: $('#add_travel_end_time').val(), } }).success(function (data, status, headers, config) { if (data.status) { @@ -126,7 +134,14 @@ app.controller('indexCtrl', function ($scope, $http, $window, loadDataService) { $scope.update_travel_id = record.trip.tripId.type + "" + record.trip.tripId.number; $scope.update_travel_train_type_id = record.trip.trainTypeId; $scope.update_travel_route_id = record.trip.routeId; - $scope.update_travel_start_time = record.trip.startingTime; + $scope.update_travel_start_station = record.trip.startStationName; + $scope.update_travel_station_name = record.trip.stationsName; + $scope.update_travel_terminal_station = record.trip.terminalStationName; + $scope.update_travel_start_time = record.trip.startTime; + $scope.update_travel_end_time = record.trip.endTime; + + $("#update_travel_start_time").datetimepicker('setDate',new Date($scope.update_travel_start_time)); + $("#update_travel_end_time").datetimepicker('setDate',new Date($scope.update_travel_end_time)); $('#update_prompt').modal({ relatedTarget: this, @@ -138,9 +153,13 @@ app.controller('indexCtrl', function ($scope, $http, $window, loadDataService) { withCredentials: true, data: { tripId: $scope.update_travel_id, - trainTypeId: $scope.update_travel_train_type_id, + trainTypeName: $('#update_travel_train_type_id').find("option:selected").val(), routeId: $scope.update_travel_route_id, - startingTime: $scope.update_travel_start_time + startStationName: $scope.update_travel_start_station, + stationsName: $scope.update_travel_station_name, + terminalStationName: $scope.update_travel_terminal_station, + startTime: $('#update_travel_start_time').val(), + endTime: $('#update_travel_end_time').val() } }).success(function (data, status, headers, config) { if (data.status == 1) { @@ -189,4 +208,175 @@ app.controller('indexCtrl', function ($scope, $http, $window, loadDataService) { } }); } -}); \ No newline at end of file +}); + +function getOptionsData(){ + getTrainTypes(); + getRouteList(); + getStationList(); +} + +function getTrainTypes(){ + $.ajax({ + type: "get", + url: "/api/v1/trainservice/trains", + contentType: "application/json", + dataType: "json", + headers: {"Authorization": "Bearer " + sessionStorage.getItem("admin_token")}, + xhrFields: { + withCredentials: true + }, + success: function (result) { + if (result.status == 1) { + var obj = result.data; + var add_travel_train_type = document.getElementById("add_travel_train_type_id"); + var update_travel_train_type = document.getElementById("update_travel_train_type_id"); + //use data to build options + for (var i = 0, l = obj.length; i < l; i++) { + var opt = document.createElement("option"); + opt.value = obj[i]["name"]; + opt.innerText = obj[i]["name"]; + add_travel_train_type.appendChild(opt); + update_travel_train_type.appendChild(opt.cloneNode(true)); + } + } else { + alert(result.msg); + } + }, error: function (e) { + var message = e.responseJSON.message; + console.log(message); + if (message.indexOf("Token") != -1) { + alert("Token is expired! please login first!"); + } + }, + complete: function () { + + } + }); +} + +function getRouteList(){ + $.ajax({ + type: "get", + url: "/api/v1/routeservice/routes", + contentType: "application/json", + dataType: "json", + headers: {"Authorization": "Bearer " + sessionStorage.getItem("admin_token")}, + xhrFields: { + withCredentials: true + }, + success: function (result) { + if (result.status == 1) { + var obj = result.data; + var types = document.getElementById("add_travel_route_id"); + //use data to build options + for (var i = 0, l = obj.length; i < l; i++) { + var opt = document.createElement("option"); + opt.value = obj[i]["id"]; + opt.innerText = obj[i]["id"]; + types.appendChild(opt); + } + } else { + alert(result.msg); + } + }, error: function (e) { + var message = e.responseJSON.message; + console.log(message); + if (message.indexOf("Token") != -1) { + alert("Token is expired! please login first!"); + } + }, + complete: function () { + + } + }); +} + +function getStationList(){ + $.ajax({ + type: "get", + url: "/api/v1/stationservice/stations", + contentType: "application/json", + dataType: "json", + headers: {"Authorization": "Bearer " + sessionStorage.getItem("admin_token")}, + xhrFields: { + withCredentials: true + }, + success: function (result) { + if (result.status == 1) { + var obj = result.data; + var start_station = document.getElementById("add_travel_start_station"); + var terminal_station = document.getElementById("add_travel_terminal_station") + var station_name = document.getElementById("add_travel_station_name") + //use data to build options + for (var i = 0, l = obj.length; i < l; i++) { + var opt = document.createElement("option"); + opt.value = obj[i]["name"]; + opt.innerText = obj[i]["name"]; + start_station.appendChild(opt); + station_name.appendChild(opt.cloneNode(true)); + terminal_station.appendChild(opt.cloneNode(true)); + } + } else { + alert(result.msg); + } + }, error: function (e) { + var message = e.responseJSON.message; + console.log(message); + if (message.indexOf("Token") != -1) { + alert("Token is expired! please login first!"); + } + }, + complete: function () { + + } + }); +} + +var add_travel_start_time=$("#add_travel_start_time") +var add_travel_end_time=$("#add_travel_end_time") +var update_travel_start_time=$("#update_travel_start_time") +var update_travel_end_time=$("#update_travel_end_time") + +add_travel_start_time.datetimepicker({ + format : 'yyyy-mm-dd hh:ii:00', + autoclose : true, + startView : 4, + minView : 0, + minuteStep: 1 +}); + +add_travel_end_time.datetimepicker({ + format : 'yyyy-mm-dd hh:ii:00', + autoclose : true, + startView : 4, + minView : 0, + minuteStep: 1 +}); + +update_travel_start_time.datetimepicker({ + format : 'yyyy-mm-dd hh:ii:00', + autoclose : true, + startView : 4, + minView : 0, + minuteStep: 1 +}); + +update_travel_end_time.datetimepicker({ + format : 'yyyy-mm-dd hh:ii:00', + autoclose : true, + startView : 4, + minView : 0, + minuteStep: 1 +}); + +add_travel_start_time.datetimepicker('setDate',new Date()); +add_travel_end_time.datetimepicker('setDate',new Date()); + +function parseTime(timeNumber){ + var temp=timeNumber.split('T'); + var date=temp[0]; + var moment=temp[1].split('.')[0]; + var result= date+ ' '+moment + return result; +} \ No newline at end of file diff --git a/ts-ui-dashboard/static/assets/js/admin_user.js b/ts-ui-dashboard/static/assets/js/admin_user.js index 48de2358a..901bd8b14 100644 --- a/ts-ui-dashboard/static/assets/js/admin_user.js +++ b/ts-ui-dashboard/static/assets/js/admin_user.js @@ -103,9 +103,9 @@ app.controller('indexCtrl', function ($scope, $http, $window, loadDataService) { data: { userName: $scope.add_user_name, password: $scope.add_user_password, - gender: $scope.add_user_gender, + gender: $('#add_user_gender').find("option:selected").val(), email: $scope.add_user_email, - documentType: $scope.add_user_document_type, + documentType: $('#add_user_document_type').find("option:selected").val(), documentNum: $scope.add_user_document_number } }).success(function (data, status, headers, config) { diff --git a/ts-ui-dashboard/static/assets/js/amazeui.datetimepicker.min.js b/ts-ui-dashboard/static/assets/js/amazeui.datetimepicker.min.js new file mode 100644 index 000000000..ae5ef8475 --- /dev/null +++ b/ts-ui-dashboard/static/assets/js/amazeui.datetimepicker.min.js @@ -0,0 +1 @@ +(function(a){if(typeof define==="function"&&define.amd){define(["jquery"],a)}else{if(typeof exports==="object"){a(require("jquery"))}else{a(jQuery)}}}(function(f,c){if(!("indexOf" in Array.prototype)){Array.prototype.indexOf=function(k,j){if(j===c){j=0}if(j<0){j+=this.length}if(j<0){j=0}for(var l=this.length;j=this.startDate&&j<=this.endDate){this.date=j;this.setValue();this.viewDate=this.date;this.fill()}else{this.element.trigger({type:"outOfRange",date:j,startDate:this.startDate,endDate:this.endDate})}},setFormat:function(k){this.format=g.parseFormat(k,this.formatType);var j;if(this.isInput){j=this.element}else{if(this.component){j=this.element.find("input")}}if(j&&j.val()){this.setValue()}},setValue:function(){var j=this.getFormattedDate();if(!this.isInput){if(this.component){this.element.find("input").val(j)}this.element.data("date",j)}else{this.element.val(j)}if(this.linkField){f("#"+this.linkField).val(this.getFormattedDate(this.linkFormat))}},getFormattedDate:function(j){if(j==c){j=this.format}return g.formatDate(this.date,j,this.language,this.formatType)},setStartDate:function(j){this.startDate=j||-Infinity;if(this.startDate!==-Infinity){this.startDate=g.parseDate(this.startDate,this.format,this.language,this.formatType)}this.update();this.updateNavArrows()},setEndDate:function(j){this.endDate=j||Infinity;if(this.endDate!==Infinity){this.endDate=g.parseDate(this.endDate,this.format,this.language,this.formatType)}this.update();this.updateNavArrows()},setDatesDisabled:function(j){this.datesDisabled=j||[];if(!f.isArray(this.datesDisabled)){this.datesDisabled=this.datesDisabled.split(/,\s*/)}this.datesDisabled=f.map(this.datesDisabled,function(k){return g.parseDate(k,this.format,this.language,this.formatType).toDateString()});this.update();this.updateNavArrows()},setTitle:function(j,k){return this.picker.find(j).find("th:eq(1)").text(this.title===false?k:this.title)},setDaysOfWeekDisabled:function(j){this.daysOfWeekDisabled=j||[];if(!f.isArray(this.daysOfWeekDisabled)){this.daysOfWeekDisabled=this.daysOfWeekDisabled.split(/,\s*/)}this.daysOfWeekDisabled=f.map(this.daysOfWeekDisabled,function(k){return parseInt(k,10)});this.update();this.updateNavArrows()},setMinutesDisabled:function(j){this.minutesDisabled=j||[];if(!f.isArray(this.minutesDisabled)){this.minutesDisabled=this.minutesDisabled.split(/,\s*/)}this.minutesDisabled=f.map(this.minutesDisabled,function(k){return parseInt(k,10)});this.update();this.updateNavArrows()},setHoursDisabled:function(j){this.hoursDisabled=j||[];if(!f.isArray(this.hoursDisabled)){this.hoursDisabled=this.hoursDisabled.split(/,\s*/)}this.hoursDisabled=f.map(this.hoursDisabled,function(k){return parseInt(k,10)});this.update();this.updateNavArrows()},place:function(){if(this.isInline){return}if(!this.zIndex){var k=0;f("div").each(function(){var p=parseInt(f(this).css("zIndex"),10);if(p>k){k=p}});this.zIndex=k+10}var o,n,m,l;if(this.container instanceof f){l=this.container.offset()}else{l=f(this.container).offset()}if(this.component){o=this.component.offset();m=o.left;if(this.pickerPosition=="bottom-left"||this.pickerPosition=="top-left"){m+=this.component.outerWidth()-this.picker.outerWidth()}}else{o=this.element.offset();m=o.left;if(this.pickerPosition=="bottom-left"||this.pickerPosition=="top-left"){m+=this.element.outerWidth()-this.picker.outerWidth()}}var j=document.body.clientWidth||window.innerWidth;if(m+220>j){m=j-220}if(this.pickerPosition=="top-left"||this.pickerPosition=="top-right"){n=o.top-this.picker.outerHeight()}else{n=o.top+this.height}n=n-l.top;m=m-l.left;this.picker.css({top:n,left:m,zIndex:this.zIndex})},update:function(){var j,k=false;if(arguments&&arguments.length&&(typeof arguments[0]==="string"||arguments[0] instanceof Date)){j=arguments[0];k=true}else{j=(this.isInput?this.element.val():this.element.find("input").val())||this.element.data("date")||this.initialDate;if(typeof j=="string"||j instanceof String){j=j.replace(/^\s+|\s+$/g,"")}}if(!j){j=new Date();k=false}this.date=g.parseDate(j,this.format,this.language,this.formatType);if(k){this.setValue()}if(this.datethis.endDate){this.viewDate=new Date(this.endDate)}else{this.viewDate=new Date(this.date)}}this.fill()},fillDow:function(){var j=this.weekStart,k="";while(j'+a[this.language].daysMin[(j++)%7]+""}k+="";this.picker.find(".datetimepicker-days thead").append(k)},fillMonths:function(){var k="",j=0;while(j<12){k+=''+a[this.language].monthsShort[j++]+""}this.picker.find(".datetimepicker-months td").html(k)},fill:function(){if(this.date==null||this.viewDate==null){return}var H=new Date(this.viewDate),u=H.getUTCFullYear(),I=H.getUTCMonth(),n=H.getUTCDate(),D=H.getUTCHours(),y=H.getUTCMinutes(),z=this.startDate!==-Infinity?this.startDate.getUTCFullYear():-Infinity,E=this.startDate!==-Infinity?this.startDate.getUTCMonth()+1:-Infinity,q=this.endDate!==Infinity?this.endDate.getUTCFullYear():Infinity,A=this.endDate!==Infinity?this.endDate.getUTCMonth()+1:Infinity,r=(new h(this.date.getUTCFullYear(),this.date.getUTCMonth(),this.date.getUTCDate())).valueOf(),G=new Date();this.setTitle(".datetimepicker-days",a[this.language].months[I]+" "+u);if(this.formatViewType=="time"){var k=this.getFormattedDate();this.setTitle(".datetimepicker-hours",k);this.setTitle(".datetimepicker-minutes",k)}else{this.setTitle(".datetimepicker-hours",n+" "+a[this.language].months[I]+" "+u);this.setTitle(".datetimepicker-minutes",n+" "+a[this.language].months[I]+" "+u)}this.picker.find("tfoot th.today").text(a[this.language].today||a.en.today).toggle(this.todayBtn!==false);this.picker.find("tfoot th.clear").text(a[this.language].clear||a.en.clear).toggle(this.clearBtn!==false);this.updateNavArrows();this.fillMonths();var K=h(u,I-1,28,0,0,0,0),C=g.getDaysInMonth(K.getUTCFullYear(),K.getUTCMonth());K.setUTCDate(C);K.setUTCDate(C-(K.getUTCDay()-this.weekStart+7)%7);var j=new Date(K);j.setUTCDate(j.getUTCDate()+42);j=j.valueOf();var s=[];var v;while(K.valueOf()")}v="";if(K.getUTCFullYear()u||(K.getUTCFullYear()==u&&K.getUTCMonth()>I)){v+=" new"}}if(this.todayHighlight&&K.getUTCFullYear()==G.getFullYear()&&K.getUTCMonth()==G.getMonth()&&K.getUTCDate()==G.getDate()){v+=" today"}if(K.valueOf()==r){v+=" active"}if((K.valueOf()+86400000)<=this.startDate||K.valueOf()>this.endDate||f.inArray(K.getUTCDay(),this.daysOfWeekDisabled)!==-1||f.inArray(K.toDateString(),this.datesDisabled)!==-1){v+=" disabled"}s.push(''+K.getUTCDate()+"");if(K.getUTCDay()==this.weekEnd){s.push("")}K.setUTCDate(K.getUTCDate()+1)}this.picker.find(".datetimepicker-days tbody").empty().append(s.join(""));s=[];var w="",F="",t="";var l=this.hoursDisabled||[];for(var B=0;B<24;B++){if(l.indexOf(B)!==-1){continue}var x=h(u,I,n,B);v="";if((x.valueOf()+3600000)<=this.startDate||x.valueOf()>this.endDate){v+=" disabled"}else{if(D==B){v+=" active"}}if(this.showMeridian&&a[this.language].meridiem.length==2){F=(B<12?a[this.language].meridiem[0]:a[this.language].meridiem[1]);if(F!=t){if(t!=""){s.push("")}s.push('
'+F.toUpperCase()+"")}t=F;w=(B%12?B%12:12);s.push(''+w+"");if(B==23){s.push("
")}}else{w=B+":00";s.push(''+w+"")}}this.picker.find(".datetimepicker-hours td").html(s.join(""));s=[];w="",F="",t="";var m=this.minutesDisabled||[];for(var B=0;B<60;B+=this.minuteStep){if(m.indexOf(B)!==-1){continue}var x=h(u,I,n,D,B,0);v="";if(x.valueOf()this.endDate){v+=" disabled"}else{if(Math.floor(y/this.minuteStep)==Math.floor(B/this.minuteStep)){v+=" active"}}if(this.showMeridian&&a[this.language].meridiem.length==2){F=(D<12?a[this.language].meridiem[0]:a[this.language].meridiem[1]);if(F!=t){if(t!=""){s.push("")}s.push('
'+F.toUpperCase()+"")}t=F;w=(D%12?D%12:12);s.push(''+w+":"+(B<10?"0"+B:B)+"");if(B==59){s.push("
")}}else{w=B+":00";s.push(''+D+":"+(B<10?"0"+B:B)+"")}}this.picker.find(".datetimepicker-minutes td").html(s.join(""));var L=this.date.getUTCFullYear();var p=this.setTitle(".datetimepicker-months",u).end().find("span").removeClass("active");if(L==u){var o=p.length-12;p.eq(this.date.getUTCMonth()+o).addClass("active")}if(uq){p.addClass("disabled")}if(u==z){p.slice(0,E+1).addClass("disabled")}if(u==q){p.slice(A).addClass("disabled")}s="";u=parseInt(u/10,10)*10;var J=this.setTitle(".datetimepicker-years",u+"-"+(u+9)).end().find("td");u-=1;for(var B=-1;B<11;B++){s+='q?" disabled":"")+'">'+u+"";u+=1}J.html(s);this.place()},updateNavArrows:function(){var n=new Date(this.viewDate),l=n.getUTCFullYear(),m=n.getUTCMonth(),k=n.getUTCDate(),j=n.getUTCHours();switch(this.viewMode){case 0:if(this.startDate!==-Infinity&&l<=this.startDate.getUTCFullYear()&&m<=this.startDate.getUTCMonth()&&k<=this.startDate.getUTCDate()&&j<=this.startDate.getUTCHours()){this.picker.find(".prev").css({visibility:"hidden"})}else{this.picker.find(".prev").css({visibility:"visible"})}if(this.endDate!==Infinity&&l>=this.endDate.getUTCFullYear()&&m>=this.endDate.getUTCMonth()&&k>=this.endDate.getUTCDate()&&j>=this.endDate.getUTCHours()){this.picker.find(".next").css({visibility:"hidden"})}else{this.picker.find(".next").css({visibility:"visible"})}break;case 1:if(this.startDate!==-Infinity&&l<=this.startDate.getUTCFullYear()&&m<=this.startDate.getUTCMonth()&&k<=this.startDate.getUTCDate()){this.picker.find(".prev").css({visibility:"hidden"})}else{this.picker.find(".prev").css({visibility:"visible"})}if(this.endDate!==Infinity&&l>=this.endDate.getUTCFullYear()&&m>=this.endDate.getUTCMonth()&&k>=this.endDate.getUTCDate()){this.picker.find(".next").css({visibility:"hidden"})}else{this.picker.find(".next").css({visibility:"visible"})}break;case 2:if(this.startDate!==-Infinity&&l<=this.startDate.getUTCFullYear()&&m<=this.startDate.getUTCMonth()){this.picker.find(".prev").css({visibility:"hidden"})}else{this.picker.find(".prev").css({visibility:"visible"})}if(this.endDate!==Infinity&&l>=this.endDate.getUTCFullYear()&&m>=this.endDate.getUTCMonth()){this.picker.find(".next").css({visibility:"hidden"})}else{this.picker.find(".next").css({visibility:"visible"})}break;case 3:case 4:if(this.startDate!==-Infinity&&l<=this.startDate.getUTCFullYear()){this.picker.find(".prev").css({visibility:"hidden"})}else{this.picker.find(".prev").css({visibility:"visible"})}if(this.endDate!==Infinity&&l>=this.endDate.getUTCFullYear()){this.picker.find(".next").css({visibility:"hidden"})}else{this.picker.find(".next").css({visibility:"visible"})}break}},mousewheel:function(k){k.preventDefault();k.stopPropagation();if(this.wheelPause){return}this.wheelPause=true;var j=k.originalEvent;var m=j.wheelDelta;var l=m>0?1:(m===0)?0:-1;if(this.wheelViewModeNavigationInverseDirection){l=-l}this.showMode(l);setTimeout(f.proxy(function(){this.wheelPause=false},this),this.wheelViewModeNavigationDelay)},click:function(n){n.stopPropagation();n.preventDefault();var o=f(n.target).closest("span, td, th, legend");if(o.is("."+this.icontype)){o=f(o).parent().closest("span, td, th, legend")}if(o.length==1){if(o.is(".disabled")){this.element.trigger({type:"outOfRange",date:this.viewDate,startDate:this.startDate,endDate:this.endDate});return}switch(o[0].nodeName.toLowerCase()){case"th":switch(o[0].className){case"switch":this.showMode(1);break;case"prev":case"next":var j=g.modes[this.viewMode].navStep*(o[0].className=="prev"?-1:1);switch(this.viewMode){case 0:this.viewDate=this.moveHour(this.viewDate,j);break;case 1:this.viewDate=this.moveDate(this.viewDate,j);break;case 2:this.viewDate=this.moveMonth(this.viewDate,j);break;case 3:case 4:this.viewDate=this.moveYear(this.viewDate,j);break}this.fill();this.element.trigger({type:o[0].className+":"+this.convertViewModeText(this.viewMode),date:this.viewDate,startDate:this.startDate,endDate:this.endDate});break;case"clear":this.reset();if(this.autoclose){this.hide()}break;case"today":var k=new Date();k=h(k.getFullYear(),k.getMonth(),k.getDate(),k.getHours(),k.getMinutes(),k.getSeconds(),0);if(kthis.endDate){k=this.endDate}}this.viewMode=this.startViewMode;this.showMode(0);this._setDate(k);this.fill();if(this.autoclose){this.hide()}break}break;case"span":if(!o.is(".disabled")){var q=this.viewDate.getUTCFullYear(),p=this.viewDate.getUTCMonth(),r=this.viewDate.getUTCDate(),s=this.viewDate.getUTCHours(),l=this.viewDate.getUTCMinutes(),t=this.viewDate.getUTCSeconds();if(o.is(".month")){this.viewDate.setUTCDate(1);p=o.parent().find("span").index(o);r=this.viewDate.getUTCDate();this.viewDate.setUTCMonth(p);this.element.trigger({type:"changeMonth",date:this.viewDate});if(this.viewSelect>=3){this._setDate(h(q,p,r,s,l,t,0))}}else{if(o.is(".year")){this.viewDate.setUTCDate(1);q=parseInt(o.text(),10)||0;this.viewDate.setUTCFullYear(q);this.element.trigger({type:"changeYear",date:this.viewDate});if(this.viewSelect>=4){this._setDate(h(q,p,r,s,l,t,0))}}else{if(o.is(".hour")){s=parseInt(o.text(),10)||0;if(o.hasClass("hour_am")||o.hasClass("hour_pm")){if(s==12&&o.hasClass("hour_am")){s=0}else{if(s!=12&&o.hasClass("hour_pm")){s+=12}}}this.viewDate.setUTCHours(s);this.element.trigger({type:"changeHour",date:this.viewDate});if(this.viewSelect>=1){this._setDate(h(q,p,r,s,l,t,0))}}else{if(o.is(".minute")){l=parseInt(o.text().substr(o.text().indexOf(":")+1),10)||0;this.viewDate.setUTCMinutes(l);this.element.trigger({type:"changeMinute",date:this.viewDate});if(this.viewSelect>=0){this._setDate(h(q,p,r,s,l,t,0))}}}}}if(this.viewMode!=0){var m=this.viewMode;this.showMode(-1);this.fill();if(m==this.viewMode&&this.autoclose){this.hide()}}else{this.fill();if(this.autoclose){this.hide()}}}break;case"td":if(o.is(".day")&&!o.is(".disabled")){var r=parseInt(o.text(),10)||1;var q=this.viewDate.getUTCFullYear(),p=this.viewDate.getUTCMonth(),s=this.viewDate.getUTCHours(),l=this.viewDate.getUTCMinutes(),t=this.viewDate.getUTCSeconds();if(o.is(".old")){if(p===0){p=11;q-=1}else{p-=1}}else{if(o.is(".new")){if(p==11){p=0;q+=1}else{p+=1}}}this.viewDate.setUTCFullYear(q);this.viewDate.setUTCMonth(p,r);this.element.trigger({type:"changeDay",date:this.viewDate});if(this.viewSelect>=2){this._setDate(h(q,p,r,s,l,t,0))}}var m=this.viewMode;this.showMode(-1);this.fill();if(m==this.viewMode&&this.autoclose){this.hide()}break}}},_setDate:function(j,l){if(!l||l=="date"){this.date=j}if(!l||l=="view"){this.viewDate=j}this.fill();this.setValue();var k;if(this.isInput){k=this.element}else{if(this.component){k=this.element.find("input")}}if(k){k.change();if(this.autoclose&&(!l||l=="date")){}}this.element.trigger({type:"changeDate",date:this.getDate()});if(j==null){this.date=this.viewDate}},moveMinute:function(k,j){if(!j){return k}var l=new Date(k.valueOf());l.setUTCMinutes(l.getUTCMinutes()+(j*this.minuteStep));return l},moveHour:function(k,j){if(!j){return k}var l=new Date(k.valueOf());l.setUTCHours(l.getUTCHours()+j);return l},moveDate:function(k,j){if(!j){return k}var l=new Date(k.valueOf());l.setUTCDate(l.getUTCDate()+j);return l},moveMonth:function(j,k){if(!k){return j}var n=new Date(j.valueOf()),r=n.getUTCDate(),o=n.getUTCMonth(),m=Math.abs(k),q,p;k=k>0?1:-1;if(m==1){p=k==-1?function(){return n.getUTCMonth()==o}:function(){return n.getUTCMonth()!=q};q=o+k;n.setUTCMonth(q);if(q<0||q>11){q=(q+12)%12}}else{for(var l=0;l=this.startDate&&j<=this.endDate},keydown:function(n){if(this.picker.is(":not(:visible)")){if(n.keyCode==27){this.show()}return}var p=false,k,q,o,r,j;switch(n.keyCode){case 27:this.hide();n.preventDefault();break;case 37:case 39:if(!this.keyboardNavigation){break}k=n.keyCode==37?-1:1;viewMode=this.viewMode;if(n.ctrlKey){viewMode+=2}else{if(n.shiftKey){viewMode+=1}}if(viewMode==4){r=this.moveYear(this.date,k);j=this.moveYear(this.viewDate,k)}else{if(viewMode==3){r=this.moveMonth(this.date,k);j=this.moveMonth(this.viewDate,k)}else{if(viewMode==2){r=this.moveDate(this.date,k);j=this.moveDate(this.viewDate,k)}else{if(viewMode==1){r=this.moveHour(this.date,k);j=this.moveHour(this.viewDate,k)}else{if(viewMode==0){r=this.moveMinute(this.date,k);j=this.moveMinute(this.viewDate,k)}}}}}if(this.dateWithinRange(r)){this.date=r;this.viewDate=j;this.setValue();this.update();n.preventDefault();p=true}break;case 38:case 40:if(!this.keyboardNavigation){break}k=n.keyCode==38?-1:1;viewMode=this.viewMode;if(n.ctrlKey){viewMode+=2}else{if(n.shiftKey){viewMode+=1}}if(viewMode==4){r=this.moveYear(this.date,k);j=this.moveYear(this.viewDate,k)}else{if(viewMode==3){r=this.moveMonth(this.date,k);j=this.moveMonth(this.viewDate,k)}else{if(viewMode==2){r=this.moveDate(this.date,k*7);j=this.moveDate(this.viewDate,k*7)}else{if(viewMode==1){if(this.showMeridian){r=this.moveHour(this.date,k*6);j=this.moveHour(this.viewDate,k*6)}else{r=this.moveHour(this.date,k*4);j=this.moveHour(this.viewDate,k*4)}}else{if(viewMode==0){r=this.moveMinute(this.date,k*4);j=this.moveMinute(this.viewDate,k*4)}}}}}if(this.dateWithinRange(r)){this.date=r;this.viewDate=j;this.setValue();this.update();n.preventDefault();p=true}break;case 13:if(this.viewMode!=0){var m=this.viewMode;this.showMode(-1);this.fill();if(m==this.viewMode&&this.autoclose){this.hide()}}else{this.fill();if(this.autoclose){this.hide()}}n.preventDefault();break;case 9:this.hide();break}if(p){var l;if(this.isInput){l=this.element}else{if(this.component){l=this.element.find("input")}}if(l){l.change()}this.element.trigger({type:"changeDate",date:this.getDate()})}},showMode:function(j){if(j){var k=Math.max(0,Math.min(g.modes.length-1,this.viewMode+j));if(k>=this.minView&&k<=this.maxView){this.element.trigger({type:"changeMode",date:this.viewDate,oldViewMode:this.viewMode,newViewMode:k});this.viewMode=k}}this.picker.find(">div").hide().filter(".datetimepicker-"+g.modes[this.viewMode].clsName).css("display","block");this.updateNavArrows()},reset:function(j){this._setDate(null,"date")},convertViewModeText:function(j){switch(j){case 4:return"decade";case 3:return"year";case 2:return"month";case 1:return"day";case 0:return"hour"}}};var b=f.fn.datetimepicker;f.fn.datetimepicker=function(l){var j=Array.apply(null,arguments);j.shift();var k;this.each(function(){var o=f(this),n=o.data("datetimepicker"),m=typeof l=="object"&&l;if(!n){o.data("datetimepicker",(n=new i(this,f.extend({},f.fn.datetimepicker.defaults,m))))}if(typeof l=="string"&&typeof n[l]=="function"){k=n[l].apply(n,j);if(k!==c){return false}}});if(k!==c){return k}else{return this}};f.fn.datetimepicker.defaults={};f.fn.datetimepicker.Constructor=i;var a=f.fn.datetimepicker.dates={en:{days:["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday","Sunday"],daysShort:["Sun","Mon","Tue","Wed","Thu","Fri","Sat","Sun"],daysMin:["Su","Mo","Tu","We","Th","Fr","Sa","Su"],months:["January","February","March","April","May","June","July","August","September","October","November","December"],monthsShort:["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"],meridiem:["am","pm"],suffix:["st","nd","rd","th"],today:"Today",clear:"Clear"}};var g={modes:[{clsName:"minutes",navFnc:"Hours",navStep:1},{clsName:"hours",navFnc:"Date",navStep:1},{clsName:"days",navFnc:"Month",navStep:1},{clsName:"months",navFnc:"FullYear",navStep:1},{clsName:"years",navFnc:"FullYear",navStep:10}],isLeapYear:function(j){return(((j%4===0)&&(j%100!==0))||(j%400===0))},getDaysInMonth:function(j,k){return[31,(g.isLeapYear(j)?29:28),31,30,31,30,31,31,30,31,30,31][k]},getDefaultFormat:function(j,k){if(j=="standard"){if(k=="input"){return"yyyy-mm-dd hh:ii"}else{return"yyyy-mm-dd hh:ii:ss"}}else{if(j=="php"){if(k=="input"){return"Y-m-d H:i"}else{return"Y-m-d H:i:s"}}else{throw new Error("Invalid format type.")}}},validParts:function(j){if(j=="standard"){return/t|hh?|HH?|p|P|ii?|ss?|dd?|DD?|mm?|MM?|yy(?:yy)?/g}else{if(j=="php"){return/[dDjlNwzFmMnStyYaABgGhHis]/g}else{throw new Error("Invalid format type.")}}},nonpunctuation:/[^ -\/:-@\[-`{-~\t\n\rTZ]+/g,parseFormat:function(m,k){var j=m.replace(this.validParts(k),"\0").split("\0"),l=m.match(this.validParts(k));if(!j||!j.length||!l||l.length==0){throw new Error("Invalid date format.")}return{separators:j,parts:l}},parseDate:function(n,w,q,u){if(n instanceof Date){var y=new Date(n.valueOf()-n.getTimezoneOffset()*60000);y.setMilliseconds(0);return y}if(/^\d{4}\-\d{1,2}\-\d{1,2}$/.test(n)){w=this.parseFormat("yyyy-mm-dd",u)}if(/^\d{4}\-\d{1,2}\-\d{1,2}[T ]\d{1,2}\:\d{1,2}$/.test(n)){w=this.parseFormat("yyyy-mm-dd hh:ii",u)}if(/^\d{4}\-\d{1,2}\-\d{1,2}[T ]\d{1,2}\:\d{1,2}\:\d{1,2}[Z]{0,1}$/.test(n)){w=this.parseFormat("yyyy-mm-dd hh:ii:ss",u)}if(/^[-+]\d+[dmwy]([\s,]+[-+]\d+[dmwy])*$/.test(n)){var z=/([-+]\d+)([dmwy])/,o=n.match(/([-+]\d+)([dmwy])/g),j,m;n=new Date();for(var p=0;p',headTemplateV3:' ',contTemplate:'',footTemplate:''};g.template='
'+g.headTemplate+g.contTemplate+g.footTemplate+'
'+g.headTemplate+g.contTemplate+g.footTemplate+'
'+g.headTemplate+""+g.footTemplate+'
'+g.headTemplate+g.contTemplate+g.footTemplate+'
'+g.headTemplate+g.contTemplate+g.footTemplate+"
";g.templateV3='
'+g.headTemplateV3+g.contTemplate+g.footTemplate+'
'+g.headTemplateV3+g.contTemplate+g.footTemplate+'
'+g.headTemplateV3+""+g.footTemplate+'
'+g.headTemplateV3+g.contTemplate+g.footTemplate+'
'+g.headTemplateV3+g.contTemplate+g.footTemplate+"
";f.fn.datetimepicker.DPGlobal=g;f.fn.datetimepicker.noConflict=function(){f.fn.datetimepicker=b;return this};f(document).on("focus.datetimepicker.data-api click.datetimepicker.data-api",'[data-provide="datetimepicker"]',function(k){var j=f(this);if(j.data("datetimepicker")){return}k.preventDefault();j.datetimepicker("show")});f(function(){f('[data-provide="datetimepicker-inline"]').datetimepicker()})})); \ No newline at end of file diff --git a/ts-ui-dashboard/static/assets/js/client_adsearch.js b/ts-ui-dashboard/static/assets/js/client_adsearch.js index 86e42720f..cc5ef5891 100644 --- a/ts-ui-dashboard/static/assets/js/client_adsearch.js +++ b/ts-ui-dashboard/static/assets/js/client_adsearch.js @@ -31,13 +31,15 @@ var adSearch = new Vue({ }, adSearchPath() { var advanceSearchInfo = new Object(); - advanceSearchInfo.startingPlace = this.startPlace; + advanceSearchInfo.startPlace = this.startPlace; advanceSearchInfo.endPlace = this.treminalPlace; advanceSearchInfo.departureTime = this.selectedDate; if (advanceSearchInfo.departureTime == null || this.checkDateFormat(advanceSearchInfo.departureTime) == false) { alert("Departure Date Format Wrong."); return; } + // add hh:mm:ss to date + advanceSearchInfo.departureTime = this.selectedDate + " 00:00:00"; var advanceSearchData = JSON.stringify(advanceSearchInfo); var selectType = this.selectedSearchType; @@ -71,7 +73,7 @@ var adSearch = new Vue({ that.adTicketSearchResult = obj; that.initSeatClaass(obj.length); for (var i = 0, l = obj.length; i < l; i++) { - that.adTicketSearchResult[i].startingTime = that.flow_advance_convertNumberToTimeString(obj[i]["startingTime"]); + that.adTicketSearchResult[i].startTime = that.flow_advance_convertNumberToTimeString(obj[i]["startTime"]); that.adTicketSearchResult[i].endTime = that.flow_advance_convertNumberToTimeString(obj[i]["endTime"]); } } @@ -112,7 +114,7 @@ var adSearch = new Vue({ that.adTicketSearchResult = obj; that.initSeatClaass(obj.length); for (var i = 0; i < obj.length; i++) { - that.adTicketSearchResult[i].startingTime = that.flow_advance_convertNumberToTimeString(obj[i]["startingTime"]); + that.adTicketSearchResult[i].startTime = that.flow_advance_convertNumberToTimeString(obj[i]["startTime"]); that.adTicketSearchResult[i].endTime = that.flow_advance_convertNumberToTimeString(obj[i]["endTime"]); } } @@ -148,7 +150,7 @@ var adSearch = new Vue({ that.adTicketSearchResult = obj; that.initSeatClaass(obj.length); for (var i = 0, l = obj.length; i < l; i++) { - that.adTicketSearchResult[i].startingTime = that.flow_advance_convertNumberToTimeString(obj[i]["startingTime"]); + that.adTicketSearchResult[i].startTime = that.flow_advance_convertNumberToTimeString(obj[i]["startTime"]); that.adTicketSearchResult[i].endTime = that.flow_advance_convertNumberToTimeString(obj[i]["endTime"]); } // flow_advance_addListenerToBookingTable(); diff --git a/ts-ui-dashboard/static/assets/js/client_order_list.js b/ts-ui-dashboard/static/assets/js/client_order_list.js index 7d984b993..86e3f30ed 100644 --- a/ts-ui-dashboard/static/assets/js/client_order_list.js +++ b/ts-ui-dashboard/static/assets/js/client_order_list.js @@ -73,7 +73,7 @@ var appConsign = new Vue({ that.tempOrderList[i] = result.data[i]; // that.tempOrderList[i].from = that.getStationNameById(that.tempOrderList[i].from); // that.tempOrderList[i].to = that.getStationNameById(that.tempOrderList[i].to); - that.tempOrderList[i].boughtDate = that.convertNumberToDateTimeString(that.tempOrderList[i].boughtDate) + // that.tempOrderList[i].boughtDate = that.convertNumberToDateTimeString(that.tempOrderList[i].boughtDate) } that.myOrderList = that.myOrderList.concat(that.tempOrderList); }, error: function (e) { @@ -435,7 +435,7 @@ var appConsign = new Vue({ }, searchRouteList() { var travelQueryInfo = new Object(); - travelQueryInfo.startingPlace = this.from; + travelQueryInfo.startPlace = this.from; travelQueryInfo.endPlace = this.to; travelQueryInfo.departureTime = this.dateOfToday; if (travelQueryInfo.departureTime == null || this.checkDateFormat(travelQueryInfo.departureTime) == false) { @@ -499,7 +499,7 @@ var appConsign = new Vue({ that.tempSearchRoutes = obj; // that.initSeatClass(size); for (var i = 0; i < size; i++) { - that.tempSearchRoutes[i].startingTime = that.convertNumberToTimeString(obj[i].startingTime); + that.tempSearchRoutes[i].startTime = that.convertNumberToTimeString(obj[i].startTime); that.tempSearchRoutes[i].endTime = that.convertNumberToTimeString(obj[i].endTime); } that.searchRoutes = that.searchRoutes.concat(that.tempSearchRoutes); @@ -537,7 +537,7 @@ var appConsign = new Vue({ var size = obj.length; for (var i = 0, l = obj.length; i < l; i++) { that.tempSearchRoutes[i] = obj[i]; - that.tempSearchRoutes[i].startingTime = that.convertNumberToTimeString(that.tempSearchRoutes[i].startingTime); + that.tempSearchRoutes[i].startTime = that.convertNumberToTimeString(that.tempSearchRoutes[i].startTime); that.tempSearchRoutes[i].endTime = that.convertNumberToTimeString(that.tempSearchRoutes[i].endTime); } that.searchRoutes = that.searchRoutes.concat(that.tempSearchRoutes); diff --git a/ts-ui-dashboard/static/assets/js/client_ticket_book.js b/ts-ui-dashboard/static/assets/js/client_ticket_book.js index b8580e682..f88ef9dea 100644 --- a/ts-ui-dashboard/static/assets/js/client_ticket_book.js +++ b/ts-ui-dashboard/static/assets/js/client_ticket_book.js @@ -125,10 +125,12 @@ function getAssuranceType() { if (result.status == 1) { var obj = result.data; var types = document.getElementById("assurance_type"); + //option0 = No Assurance var opt0 = document.createElement("option"); opt0.value = 0; opt0.innerText = "No Assurance"; types.appendChild(opt0); + //use data to build options for (var i = 0, l = obj.length; i < l; i++) { var opt = document.createElement("option"); opt.value = obj[i]["index"]; diff --git a/ts-ui-dashboard/static/assets/js/index.js b/ts-ui-dashboard/static/assets/js/index.js index 540f74555..5e626d651 100644 --- a/ts-ui-dashboard/static/assets/js/index.js +++ b/ts-ui-dashboard/static/assets/js/index.js @@ -98,13 +98,15 @@ var reserveApp = new Vue({ }, searchTravel() { var travelQueryInfo = new Object(); - travelQueryInfo.startingPlace = this.from; + travelQueryInfo.startPlace = this.from; travelQueryInfo.endPlace = this.to; travelQueryInfo.departureTime = this.selectedDate; if (travelQueryInfo.departureTime == null || this.checkDateFormat(travelQueryInfo.departureTime) == false) { alert("Departure Date Format Wrong."); return; } + // add hh:mm:ss to date + travelQueryInfo.departureTime = this.selectedDate + " 00:00:00"; var travelQueryData = JSON.stringify(travelQueryInfo); var train_type = this.selectedTrainType; this.tempTravelList = []; @@ -141,7 +143,7 @@ var reserveApp = new Vue({ that.tempTravelList = obj; that.initSeatClass(size); for (var i = 0; i < size; i++) { - that.tempTravelList[i].startingTime = that.convertNumberToTimeString(obj[i].startingTime); + that.tempTravelList[i].startTime = that.convertNumberToTimeString(obj[i].startTime); that.tempTravelList[i].endTime = that.convertNumberToTimeString(obj[i].endTime); } that.travelList = that.travelList.concat(that.tempTravelList); diff --git a/ts-ui-dashboard/static/assets/js/old_index.js b/ts-ui-dashboard/static/assets/js/old_index.js index 43bee7daa..8a4bf3556 100644 --- a/ts-ui-dashboard/static/assets/js/old_index.js +++ b/ts-ui-dashboard/static/assets/js/old_index.js @@ -88,6 +88,7 @@ app.controller('indexCtrl', function ($scope, $http, $window, loadDataService) { alert(des); } + getOptionsData(); //Add new order $scope.addNewOrder = function () { $('#add_prompt').modal({ @@ -99,20 +100,20 @@ app.controller('indexCtrl', function ($scope, $http, $window, loadDataService) { headers: {"Authorization": "Bearer " + sessionStorage.getItem("admin_token")}, withCredentials: true, data: { - boughtDate: $scope.add_order_bought_date, - travelDate: $scope.add_order_travel_date, - travelTime: $scope.add_order_travel_time, - accountId: $scope.add_order_account, - contactsName: $scope.add_order_passenger, - documentType: $scope.add_order_document_type, + boughtDate: $('#add_order_bought_date').val(), + travelDate: $('#add_order_travel_date').val(), + travelTime: $('#add_order_travel_time').val(), + accountId: $('#add_order_account').find("option:selected").val(), + contactsName: $('#add_order_passenger').find("option:selected").val(), + documentType: $('#add_order_document_type').find("option:selected").val(), contactsDocumentNumber: $scope.add_order_document_number, - trainNumber: $scope.add_order_train_number, + trainNumber: $('#add_order_train_number').find("option:selected").val(), coachNumber: $scope.add_order_coach_number, - seatClass: $scope.add_order_seat_class, + seatClass: $('#add_order_seat_class').find("option:selected").val(), seatNumber: $scope.add_order_seat_number, from: $scope.add_order_from, to: $scope.add_order_to, - status: $scope.add_order_status, + status: $('#add_order_status').find("option:selected").val(), price: $scope.add_order_price } }).success(function (data, status, headers, config) { @@ -226,4 +227,182 @@ app.controller('indexCtrl', function ($scope, $http, $window, loadDataService) { } }); } -}); \ No newline at end of file +}); + +var bought_date_selector=$("#add_order_bought_date") +var travel_date_selector=$("#add_order_travel_date") +var travel_time_selector=$("#add_order_travel_time") + + + +bought_date_selector.datetimepicker({ + format : 'yyyy-mm-dd hh:ii:00', // 展现格式 + autoclose : true, // 选择日期后关闭 + // 选择器打开之后首先显示的视图 + // 0表示分钟(默认),1表示小时,2表示天,3表示月,4表示年 + startView : 4, + // 选择器所能够提供的最精确的时间选择视图 + // 0表示分钟(默认),1表示小时,2表示天,3表示月,4表示年 + minView : 0, + minuteStep: 1 +}).on('changeDate',function(ev){ + var datetimepicker=bought_date_selector.val(); + console.log(datetimepicker); +}); +travel_date_selector.datetimepicker({ + format : 'yyyy-mm-dd hh:ii:00', + autoclose : true, + startView : 4, + minView : 0, + minuteStep: 1 +}).on('changeDate',function(ev){ + var datetimepicker=travel_date_selector.val(); + console.log(datetimepicker); +}); +travel_time_selector.datetimepicker({ + format : 'yyyy-mm-dd hh:ii:00', + autoclose : true, + startView : 4, + minView : 0, + minuteStep: 1 +}).on('changeDate',function(ev){ + var datetimepicker=travel_time_selector.val(); + console.log(datetimepicker); +}); + +bought_date_selector.datetimepicker('setDate',new Date()); +travel_date_selector.datetimepicker('setDate',new Date()); +travel_time_selector.datetimepicker('setDate',new Date()); + + +/** + * get options data + */ + + +function getOptionsData(){ + getUserList(); + getTravelOptions(); +} + + +function getUserList(){ + $.ajax({ + type: "get", + url: "/api/v1/userservice/users", + contentType: "application/json", + dataType: "json", + headers: {"Authorization": "Bearer " + sessionStorage.getItem("admin_token")}, + xhrFields: { + withCredentials: true + }, + success: function (result) { + if (result.status == 1) { + var obj = result.data; + var types = document.getElementById("add_order_account"); + //use data to build options + for (var i = 0, l = obj.length; i < l; i++) { + var opt = document.createElement("option"); + opt.value = obj[i]["userId"]; + opt.innerText = obj[i]["userName"]; + types.appendChild(opt); + } + } else { + alert(result.msg); + } + }, error: function (e) { + var message = e.responseJSON.message; + console.log(message); + if (message.indexOf("Token") != -1) { + alert("Token is expired! please login first!"); + } + }, + complete: function () { + + } + }); +} + +$("#add_order_account").on('change',function (){ + var e=document.getElementById("add_order_passenger"); + e.options.length=0; + e.style.visibility="hidden"; + getContactOptions(); +}) + +function getContactOptions(){ + var accountId=$('#add_order_account').find("option:selected").val(); + $.ajax({ + type: "get", + url: "/api/v1/contactservice/contacts/account/"+accountId, + contentType: "application/json", + dataType: "json", + headers: {"Authorization": "Bearer " + sessionStorage.getItem("admin_token")}, + xhrFields: { + withCredentials: true + }, + success: function (result) { + if (result.status == 1) { + var obj = result.data; + var types = document.getElementById("add_order_passenger"); + //display passenger options + types.style.visibility="visible" + //use data to build options + for (var i = 0, l = obj.length; i < l; i++) { + var opt = document.createElement("option"); + opt.value = obj[i]["id"]; + opt.innerText = obj[i]["name"]; + types.appendChild(opt); + } + } else { + alert(result.msg); + } + }, error: function (e) { + var message = e.responseJSON.message; + console.log(message); + if (message.indexOf("Token") != -1) { + alert("Token is expired! please login first!"); + } + }, + complete: function () { + + } + }); +} + +function getTravelOptions(){ + $.ajax({ + type: "get", + url: "/api/v1/admintravelservice/admintravel", + contentType: "application/json", + dataType: "json", + headers: {"Authorization": "Bearer " + sessionStorage.getItem("admin_token")}, + xhrFields: { + withCredentials: true + }, + success: function (result) { + if (result.status == 1) { + var obj = result.data; + var types = document.getElementById("add_order_train_number"); + //use data to build options + for (var i = 0, l = obj.length; i < l; i++) { + var opt = document.createElement("option"); + opt.value = obj[i]["trip"]["tripId"]["type"]+obj[i]["trip"]["tripId"]["number"]; + opt.innerText = obj[i]["trip"]["tripId"]["type"]+obj[i]["trip"]["tripId"]["number"]; + types.appendChild(opt); + } + } else { + alert(result.msg); + } + }, error: function (e) { + var message = e.responseJSON.message; + console.log(message); + if (message.indexOf("Token") != -1) { + alert("Token is expired! please login first!"); + } + }, + complete: function () { + + } + }); +} \ No newline at end of file diff --git a/ts-ui-dashboard/static/client_adsearch.html b/ts-ui-dashboard/static/client_adsearch.html index 3353e75f1..14bc9805c 100644 --- a/ts-ui-dashboard/static/client_adsearch.html +++ b/ts-ui-dashboard/static/client_adsearch.html @@ -232,10 +232,10 @@

{{item.trainTypeId}} - {{item.fromStationName}} - {{item.toStationName}} + {{item.startStation}} + {{item.endStation}} {{item.stopStations}} - {{item.startingTime}} + {{item.startTime}} {{item.endTime}} {{item.numberOfRestTicketSecondClass}} {{item.numberOfRestTicketFirstClass}} @@ -250,7 +250,7 @@

diff --git a/ts-ui-dashboard/static/client_order_list.html b/ts-ui-dashboard/static/client_order_list.html index 7c08bd200..ce563a129 100644 --- a/ts-ui-dashboard/static/client_order_list.html +++ b/ts-ui-dashboard/static/client_order_list.html @@ -483,9 +483,9 @@

{{item.trainTypeId}} - {{item.startingStation}} + {{item.startStation}} {{item.terminalStation}} - {{item.startingTime}} + {{item.startTime}} {{item.endTime}} {{item.economyClass}} {{item.confortClass}} diff --git a/ts-ui-dashboard/static/index.html b/ts-ui-dashboard/static/index.html index 5782cd11b..80da19601 100644 --- a/ts-ui-dashboard/static/index.html +++ b/ts-ui-dashboard/static/index.html @@ -239,9 +239,9 @@

{{item.tripId.type}}{{item.tripId.number}} {{item.trainTypeId}} - {{item.startingStation}} + {{item.startStation}} {{item.terminalStation}} - {{item.startingTime}} + {{item.startTime}} {{item.endTime}} {{item.economyClass}} {{item.confortClass}} @@ -256,7 +256,7 @@

diff --git a/ts-ui-dashboard/static/js/basicInformation.js b/ts-ui-dashboard/static/js/basicInformation.js index 13a8ead3a..29fdd989a 100644 --- a/ts-ui-dashboard/static/js/basicInformation.js +++ b/ts-ui-dashboard/static/js/basicInformation.js @@ -14,8 +14,8 @@ $("#basic_information_button").click(function(){ alert("Please input the type of the train."); return; } - travelInfo.startingStation = $("#basic_information_startingStation").val(); - if(travelInfo.startingStation == null || travelInfo.startingStation == ""){ + travelInfo.startStation = $("#basic_information_startingStation").val(); + if(travelInfo.startStation == null || travelInfo.startStation == ""){ alert("Please input the starting station."); return; } @@ -29,8 +29,8 @@ $("#basic_information_button").click(function(){ alert("Please input the terminal station."); return; } - travelInfo.startingTime = convertStringToTime($("#basic_information_startingTime").val()); - if(travelInfo.startingTime == null || travelInfo.startingTime == ""){ + travelInfo.startTime = convertStringToTime($("#basic_information_startingTime").val()); + if(travelInfo.startTime == null || travelInfo.startTime == ""){ alert("Please input the starting time."); return; } @@ -41,8 +41,8 @@ $("#basic_information_button").click(function(){ } var basicInfo = new Object(); basicInfo.trip = travelInfo; - basicInfo.startingPlace = $("#basic_information_startingPlace").val(); - if(basicInfo.startingPlace == null || basicInfo.startingPlace == ""){ + basicInfo.startPlace = $("#basic_information_startingPlace").val(); + if(basicInfo.startPlace == null || basicInfo.startPlace == ""){ alert("Please input the starting place."); return; } diff --git a/ts-ui-dashboard/static/js/bs_main.js b/ts-ui-dashboard/static/js/bs_main.js index 3effaa954..ab560a50b 100644 --- a/ts-ui-dashboard/static/js/bs_main.js +++ b/ts-ui-dashboard/static/js/bs_main.js @@ -32,7 +32,7 @@ var login = function () { $("#travel_booking_button").click(function(){ var travelQueryInfo = new Object(); - travelQueryInfo.startingPlace = $("#travel_booking_startingPlace").val(); + travelQueryInfo.startPlace = $("#travel_booking_startingPlace").val(); travelQueryInfo.endPlace = $("#travel_booking_terminalPlace").val(); travelQueryInfo.departureTime = $("#travel_booking_date").val(); if(travelQueryInfo.departureTime == null || checkDateFormat(travelQueryInfo.departureTime) == false){ @@ -74,9 +74,9 @@ function queryForTravelInfo(data,path) { "" + i + "" + "" + obj[i]["tripId"]["type"] + obj[i]["tripId"]["number"] + "" + "" + obj[i]["trainTypeId"] + "" + - "" + obj[i]["startingStation"] + "" + + "" + obj[i]["startStation"] + "" + "" + obj[i]["terminalStation"] + "" + - "" + convertNumberToTimeString(obj[i]["startingTime"]) + "" + + "" + convertNumberToTimeString(obj[i]["startTime"]) + "" + "" + convertNumberToTimeString(obj[i]["endTime"]) + "" + "" + obj[i]["economyClass"] + "" + "" + obj[i]["confortClass"] + "" + diff --git a/ts-ui-dashboard/static/js/flowAdvancedSearch.js b/ts-ui-dashboard/static/js/flowAdvancedSearch.js index ce9adbfa5..4d73371b0 100644 --- a/ts-ui-dashboard/static/js/flowAdvancedSearch.js +++ b/ts-ui-dashboard/static/js/flowAdvancedSearch.js @@ -69,7 +69,7 @@ $("#flow_advance_reserve_login_button").click(function() { $("#flow_advance_reserve_booking_button").click(function() { var advanceSearchInfo = new Object(); - advanceSearchInfo.startingPlace = $("#flow_advance_reserve_startingPlace").val(); + advanceSearchInfo.startPlace = $("#flow_advance_reserve_startingPlace").val(); advanceSearchInfo.endPlace = $("#flow_advance_reserve_terminalPlace").val(); advanceSearchInfo.departureTime = $("#flow_advance_reserve_booking_date").val(); if(advanceSearchInfo.departureTime == null || checkDateFormat(advanceSearchInfo.departureTime ) == false){ @@ -111,10 +111,10 @@ function advanceSearchForCheapestInfo(data,path) { "" + i + "" + "" + obj[i]["tripId"] + "" + "" + obj[i]["trainTypeId"] + "" + - "" + obj[i]["fromStationName"] + "" + - "" + obj[i]["toStationName"] + "" + + "" + obj[i]["startStation"] + "" + + "" + obj[i]["endStation"] + "" + "" + obj[i]["stopStations"] + "" + - "" + flow_advance_convertNumberToTimeString(obj[i]["startingTime"]) + "" + + "" + flow_advance_convertNumberToTimeString(obj[i]["startTime"]) + "" + "" + flow_advance_convertNumberToTimeString(obj[i]["endTime"]) + "" + "" + obj[i]["numberOfRestTicketSecondClass"] + "" + "" + obj[i]["numberOfRestTicketFirstClass"] + "" + @@ -159,10 +159,10 @@ function advanceSearchForQuickestInfo(data,path) { "" + i + "" + "" + obj[i]["tripId"] + "" + "" + obj[i]["trainTypeId"] + "" + - "" + obj[i]["fromStationName"] + "" + - "" + obj[i]["toStationName"] + "" + + "" + obj[i]["startStation"] + "" + + "" + obj[i]["endStation"] + "" + "" + obj[i]["stopStations"] + "" + - "" + flow_advance_convertNumberToTimeString(obj[i]["startingTime"]) + "" + + "" + flow_advance_convertNumberToTimeString(obj[i]["startTime"]) + "" + "" + flow_advance_convertNumberToTimeString(obj[i]["endTime"]) + "" + "" + obj[i]["numberOfRestTicketSecondClass"] + "" + "" + obj[i]["numberOfRestTicketFirstClass"] + "" + @@ -208,10 +208,10 @@ function advanceSearchForMinStopInfo(data,path) { "" + i + "" + "" + obj[i]["tripId"] + "" + "" + obj[i]["trainTypeId"] + "" + - "" + obj[i]["fromStationName"] + "" + - "" + obj[i]["toStationName"] + "" + + "" + obj[i]["startStation"] + "" + + "" + obj[i]["endStation"] + "" + "" + obj[i]["stopStations"] + "" + - "" + flow_advance_convertNumberToTimeString(obj[i]["startingTime"]) + "" + + "" + flow_advance_convertNumberToTimeString(obj[i]["startTime"]) + "" + "" + flow_advance_convertNumberToTimeString(obj[i]["endTime"]) + "" + "" + obj[i]["numberOfRestTicketSecondClass"] + "" + "" + obj[i]["numberOfRestTicketFirstClass"] + "" + diff --git a/ts-ui-dashboard/static/js/flowPreserve.js b/ts-ui-dashboard/static/js/flowPreserve.js index cacb5b794..fd250bb1e 100644 --- a/ts-ui-dashboard/static/js/flowPreserve.js +++ b/ts-ui-dashboard/static/js/flowPreserve.js @@ -94,7 +94,7 @@ function checkEmailFormat(email){ $("#travel_booking_button").click(function(){ var travelQueryInfo = new Object(); - travelQueryInfo.startingPlace = $("#travel_booking_startingPlace").val(); + travelQueryInfo.startPlace = $("#travel_booking_startingPlace").val(); travelQueryInfo.endPlace = $("#travel_booking_terminalPlace").val(); travelQueryInfo.departureTime = $("#travel_booking_date").val(); if(travelQueryInfo.departureTime == null || checkDateFormat(travelQueryInfo.departureTime) == false){ @@ -144,9 +144,9 @@ function queryForTravelInfo(data,path) { "" + i + "" + "" + obj[i]["tripId"]["type"] + obj[i]["tripId"]["number"] + "" + "" + obj[i]["trainTypeId"] + "" + - "" + obj[i]["startingStation"] + "" + + "" + obj[i]["startStation"] + "" + "" + obj[i]["terminalStation"] + "" + - "" + convertNumberToTimeString(obj[i]["startingTime"]) + "" + + "" + convertNumberToTimeString(obj[i]["startTime"]) + "" + "" + convertNumberToTimeString(obj[i]["endTime"]) + "" + "" + obj[i]["economyClass"] + "" + "" + obj[i]["confortClass"] + "" + diff --git a/ts-ui-dashboard/static/js/flowRebook.js b/ts-ui-dashboard/static/js/flowRebook.js index a828a865d..48c5a4c85 100644 --- a/ts-ui-dashboard/static/js/flowRebook.js +++ b/ts-ui-dashboard/static/js/flowRebook.js @@ -319,7 +319,7 @@ $("#travel_rebook_button").click(function(){ alert("Please Login"); } var travelQueryInfo = new Object(); - travelQueryInfo.startingPlace = $("#travel_rebook_startingPlace").val(); + travelQueryInfo.startPlace = $("#travel_rebook_startingPlace").val(); travelQueryInfo.endPlace = $("#travel_rebook_terminalPlace").val(); travelQueryInfo.departureTime = $("#travel_rebook_date").val(); if(travelQueryInfo.departureTime == null || checkDateFormat(travelQueryInfo.departureTime) == false){ @@ -362,9 +362,9 @@ function queryForRebookTravelInfo(data,path) { "" + i + "" + "" + obj[i]["tripId"]["type"] + obj[i]["tripId"]["number"] + "" + "" + obj[i]["trainTypeId"] + "" + - "" + obj[i]["startingStation"] + "" + + "" + obj[i]["startStation"] + "" + "" + obj[i]["terminalStation"] + "" + - "" + convertNumberToTimeString(obj[i]["startingTime"]) + "" + + "" + convertNumberToTimeString(obj[i]["startTime"]) + "" + "" + convertNumberToTimeString(obj[i]["endTime"]) + "" + "" + obj[i]["economyClass"] + "" + "" + obj[i]["confortClass"] + "" + diff --git a/ts-ui-dashboard/static/js/myflow.js b/ts-ui-dashboard/static/js/myflow.js index 0d951bc95..c3c42332b 100644 --- a/ts-ui-dashboard/static/js/myflow.js +++ b/ts-ui-dashboard/static/js/myflow.js @@ -541,7 +541,7 @@ // alert("Please Login"); // } // var travelQueryInfo = new Object(); -// travelQueryInfo.startingPlace = $("#travel_rebook_startingPlace").val(); +// travelQueryInfo.startPlace = $("#travel_rebook_startingPlace").val(); // travelQueryInfo.endPlace = $("#travel_rebook_terminalPlace").val(); // travelQueryInfo.departureTime = $("#travel_rebook_date").val(); // if(travelQueryInfo.departureTime == null || checkDateFormat(travelQueryInfo.departureTime) == false){ @@ -584,9 +584,9 @@ // "" + i + "" + // "" + obj[i]["tripId"]["type"] + obj[i]["tripId"]["number"] + "" + // "" + obj[i]["trainTypeId"] + "" + -// "" + obj[i]["startingStation"] + "" + +// "" + obj[i]["startStation"] + "" + // "" + obj[i]["terminalStation"] + "" + -// "" + convertNumberToTimeString(obj[i]["startingTime"]) + "" + +// "" + convertNumberToTimeString(obj[i]["startTime"]) + "" + // "" + convertNumberToTimeString(obj[i]["endTime"]) + "" + // "" + obj[i]["economyClass"] + "" + // "" + obj[i]["confortClass"] + "" + diff --git a/ts-ui-dashboard/static/js/notification.js b/ts-ui-dashboard/static/js/notification.js index cc9fa0ba8..bcaaae3b2 100644 --- a/ts-ui-dashboard/static/js/notification.js +++ b/ts-ui-dashboard/static/js/notification.js @@ -19,8 +19,8 @@ $("#notification_send_email_button").click(function(){ alert("Please input the username."); return; } - notificationInfo.startingPlace = $("#notification_startingPlace").val() - if(notificationInfo.startingPlace == null || notificationInfo.startingPlace == ""){ + notificationInfo.startPlace = $("#notification_startingPlace").val() + if(notificationInfo.startPlace == null || notificationInfo.startPlace == ""){ alert("Please input the starting place."); return; } @@ -29,8 +29,8 @@ $("#notification_send_email_button").click(function(){ alert("Please input the end place."); return; } - notificationInfo.startingTime = $("#notification_startingTime").val(); - if(notificationInfo.startingTime == null || notificationInfo.startingTime == ""){ + notificationInfo.startTime = $("#notification_startingTime").val(); + if(notificationInfo.startTime == null || notificationInfo.startTime == ""){ alert("Please input the starting time."); return; } diff --git a/ts-ui-dashboard/static/js/routePlan.js b/ts-ui-dashboard/static/js/routePlan.js index b70bcec93..bf7b26f68 100644 --- a/ts-ui-dashboard/static/js/routePlan.js +++ b/ts-ui-dashboard/static/js/routePlan.js @@ -1,7 +1,7 @@ $("#travel_min_stop_button").click(function(){ var minStopSearchInfo = new Object(); - minStopSearchInfo.formStationName = $("#travel_min_stop_fromPlace").val(); - minStopSearchInfo.toStationName = $("#travel_min_stop_toPlace").val(); + minStopSearchInfo.startStation = $("#travel_min_stop_fromPlace").val(); + minStopSearchInfo.endStation = $("#travel_min_stop_toPlace").val(); minStopSearchInfo.travelDate = $("#travel_min_stop_date").val(); minStopSearchInfo.num = 5; if(minStopSearchInfo.travelDate == null || checkDateFormat(minStopSearchInfo.travelDate ) == false){ @@ -33,9 +33,9 @@ function queryForMinStopInfo(data,path) { "" + i + "" + "" + obj[i]["tripId"] + "" + "" + obj[i]["trainTypeId"] + "" + - "" + obj[i]["fromStationName"] + "" + - "" + obj[i]["toStationName"] + "" + - "" + convertNumberToTimeString(obj[i]["startingTime"]) + "" + + "" + obj[i]["startStation"] + "" + + "" + obj[i]["endStation"] + "" + + "" + convertNumberToTimeString(obj[i]["startTime"]) + "" + "" + convertNumberToTimeString(obj[i]["endTime"]) + "" + "" + "" + @@ -120,8 +120,8 @@ function queryForQuickestInfo(data,path) { $("#travel_cheapest_route_button").click(function(){ var cheapestSearchInfo = new Object(); - cheapestSearchInfo.formStationName = $("#travel_cheapest_route_fromPlace").val(); - cheapestSearchInfo.toStationName = $("#travel_cheapest_route_toPlace").val(); + cheapestSearchInfo.startStation = $("#travel_cheapest_route_fromPlace").val(); + cheapestSearchInfo.endStation = $("#travel_cheapest_route_toPlace").val(); cheapestSearchInfo.travelDate = $("#travel_cheapest_route_date").val(); cheapestSearchInfo.num = 5; if(cheapestSearchInfo.travelDate == null || checkDateFormat(cheapestSearchInfo.travelDate ) == false){ @@ -153,9 +153,9 @@ function queryForCheapestInfo(data,path) { "" + i + "" + "" + obj[i]["tripId"]["type"] + obj[i]["tripId"]["number"] + "" + "" + obj[i]["trainTypeId"] + "" + - "" + obj[i]["startingStation"] + "" + + "" + obj[i]["startStation"] + "" + "" + obj[i]["terminalStation"] + "" + - "" + convertNumberToTimeString(obj[i]["startingTime"]) + "" + + "" + convertNumberToTimeString(obj[i]["startTime"]) + "" + "" + convertNumberToTimeString(obj[i]["endTime"]) + "" + "" + "

@@ -1324,10 +1324,10 @@

- +
+ name='startTime' value='11:17'>
@@ -1403,9 +1403,9 @@

- +
-
@@ -1424,10 +1424,10 @@

- +
+ name='startTime' value='11:17'>
@@ -1756,9 +1756,9 @@

- +
-
@@ -1777,10 +1777,10 @@

- +
+ name='startTime' value='09:51'>
@@ -1791,9 +1791,9 @@

- +
-
@@ -1867,9 +1867,9 @@

- +
-
@@ -1888,10 +1888,10 @@

- +
+ name='startTime' value='09:51'>
@@ -1902,9 +1902,9 @@

- +
-
@@ -1987,7 +1987,7 @@

-
@@ -2001,7 +2001,7 @@

-
diff --git a/ts-user-service/pom.xml b/ts-user-service/pom.xml index 1137050a8..85ca47613 100644 --- a/ts-user-service/pom.xml +++ b/ts-user-service/pom.xml @@ -17,20 +17,25 @@ jar + + + + org.springframework.boot - spring-boot-starter-data-mongodb + spring-boot-starter-data-jpa + + + mysql + mysql-connector-java org.services ts-common 0.1.0 - - - diff --git a/ts-user-service/src/main/java/user/UserApplication.java b/ts-user-service/src/main/java/user/UserApplication.java index eb67bffeb..9aefdb490 100644 --- a/ts-user-service/src/main/java/user/UserApplication.java +++ b/ts-user-service/src/main/java/user/UserApplication.java @@ -2,13 +2,32 @@ import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.boot.web.client.RestTemplateBuilder; +import org.springframework.cloud.client.discovery.EnableDiscoveryClient; +import org.springframework.cloud.client.loadbalancer.LoadBalanced; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.EnableAspectJAutoProxy; +import org.springframework.integration.annotation.IntegrationComponentScan; +import org.springframework.scheduling.annotation.EnableAsync; +import org.springframework.web.client.RestTemplate; +import springfox.documentation.swagger2.annotations.EnableSwagger2; /** * @author fdse */ @SpringBootApplication +@EnableAspectJAutoProxy(proxyTargetClass = true) +@EnableAsync +@IntegrationComponentScan +@EnableDiscoveryClient +@EnableSwagger2 public class UserApplication { public static void main(String[] args) { SpringApplication.run(UserApplication.class, args); } + @LoadBalanced + @Bean + public RestTemplate restTemplate(RestTemplateBuilder builder) { + return builder.build(); + } } diff --git a/ts-user-service/src/main/java/user/controller/UserController.java b/ts-user-service/src/main/java/user/controller/UserController.java index 06137a941..7c61c3486 100644 --- a/ts-user-service/src/main/java/user/controller/UserController.java +++ b/ts-user-service/src/main/java/user/controller/UserController.java @@ -34,24 +34,24 @@ public String testHello() { @GetMapping public ResponseEntity getAllUser(@RequestHeader HttpHeaders headers) { - UserController.LOGGER.info("Get all user"); + UserController.LOGGER.info("[getAllUser][Get all user]"); return ok(userService.getAllUsers(headers)); } @GetMapping("/{userName}") public ResponseEntity getUserByUserName(@PathVariable String userName, @RequestHeader HttpHeaders headers) { - UserController.LOGGER.info("Get user by user name,UserName: {}",userName); + UserController.LOGGER.info("[getUserByUserName][Get user by user name][UserName: {}]",userName); return ok(userService.findByUserName(userName, headers)); } @GetMapping("/id/{userId}") public ResponseEntity getUserByUserId(@PathVariable String userId, @RequestHeader HttpHeaders headers) { - UserController.LOGGER.info("Get user by user id,UserId: {}",userId); + UserController.LOGGER.info("[getUserByUserId][Get user by user id][UserId: {}]",userId); return ok(userService.findByUserId(userId, headers)); } @PostMapping("/register") public ResponseEntity registerUser(@RequestBody UserDto userDto, @RequestHeader HttpHeaders headers) { - UserController.LOGGER.info("Register user,User name: {}",userDto.getUserName()); + UserController.LOGGER.info("[registerUser][Register user][UserName: {}]",userDto.getUserName()); return ResponseEntity.status(HttpStatus.CREATED).body(userService.saveUser(userDto, headers)); } @@ -60,14 +60,14 @@ public ResponseEntity registerUser(@RequestBody UserDto userDto, @Requ public ResponseEntity deleteUserById(@PathVariable String userId, @RequestHeader HttpHeaders headers) { // only admin token can delete - UserController.LOGGER.info("Delete user,UserId: {}",userId); - return ok(userService.deleteUser(UUID.fromString(userId), headers)); + UserController.LOGGER.info("[deleteUserById][Delete user][UserId: {}]",userId); + return ok(userService.deleteUser(userId, headers)); } @PutMapping public ResponseEntity updateUser(@RequestBody UserDto user, @RequestHeader HttpHeaders headers) { - UserController.LOGGER.info("Update user,UserId: {}",user.getUserId()); + UserController.LOGGER.info("[updateUser][Update user][UserId: {}]",user.getUserId()); return ok(userService.updateUser(user, headers)); } diff --git a/ts-user-service/src/main/java/user/dto/UserDto.java b/ts-user-service/src/main/java/user/dto/UserDto.java index 62e0956c8..9445c04f1 100644 --- a/ts-user-service/src/main/java/user/dto/UserDto.java +++ b/ts-user-service/src/main/java/user/dto/UserDto.java @@ -14,7 +14,7 @@ @ToString public class UserDto { - private UUID userId; + private String userId; private String userName; diff --git a/ts-user-service/src/main/java/user/entity/User.java b/ts-user-service/src/main/java/user/entity/User.java index b377bc8b6..a858445ac 100644 --- a/ts-user-service/src/main/java/user/entity/User.java +++ b/ts-user-service/src/main/java/user/entity/User.java @@ -4,7 +4,12 @@ import lombok.Builder; import lombok.Data; import lombok.NoArgsConstructor; +import org.hibernate.annotations.GenericGenerator; +import javax.persistence.Column; +import javax.persistence.Entity; +import javax.persistence.GeneratedValue; +import javax.persistence.Id; import java.util.UUID; /** @@ -13,19 +18,27 @@ @Data @Builder @AllArgsConstructor -@NoArgsConstructor +@Entity public class User { - private UUID userId; + // private UUID userId; + @Id + @Column(length = 36, name = "user_id") + private String userId; + @Column(name = "user_name") private String userName; private String password; private int gender; - + @Column(name = "document_type") private int documentType; - + @Column(name = "document_num") private String documentNum; private String email; + public User() { + this.userId = UUID.randomUUID().toString(); + } + } diff --git a/ts-user-service/src/main/java/user/init/InitUser.java b/ts-user-service/src/main/java/user/init/InitUser.java index 6290d8128..5500b9b03 100644 --- a/ts-user-service/src/main/java/user/init/InitUser.java +++ b/ts-user-service/src/main/java/user/init/InitUser.java @@ -30,13 +30,14 @@ public class InitUser implements CommandLineRunner { public void run(String... strings) throws Exception { User whetherExistUser = userRepository.findByUserName("fdse_microservice"); User user = User.builder() - .userId(UUID.fromString("4d2a46c7-71cb-4cf1-b5bb-b68406d9da6f")) + .userId("4d2a46c7-71cb-4cf1-b5bb-b68406d9da6f") .userName("fdse_microservice") .password("111111") .gender(1) .documentType(1) .documentNum("2135488099312X") .email("trainticket_notify@163.com").build(); + user.setUserId("4d2a46c7-71cb-4cf1-b5bb-b68406d9da6f"); if (whetherExistUser == null) { userRepository.save(user); } diff --git a/ts-user-service/src/main/java/user/repository/UserRepository.java b/ts-user-service/src/main/java/user/repository/UserRepository.java index 0601121c8..b38813286 100644 --- a/ts-user-service/src/main/java/user/repository/UserRepository.java +++ b/ts-user-service/src/main/java/user/repository/UserRepository.java @@ -1,20 +1,24 @@ package user.repository; -import org.springframework.data.mongodb.repository.MongoRepository; +import org.springframework.data.repository.CrudRepository; import org.springframework.stereotype.Repository; import user.entity.User; +import java.util.List; import java.util.UUID; /** * @author fdse */ @Repository -public interface UserRepository extends MongoRepository { +public interface UserRepository extends CrudRepository { User findByUserName(String userName); - User findByUserId(UUID userId); + User findByUserId(String userId); - void deleteByUserId(UUID userId); + void deleteByUserId(String userId); + + @Override + List findAll(); } diff --git a/ts-user-service/src/main/java/user/service/UserService.java b/ts-user-service/src/main/java/user/service/UserService.java index 81e812777..833e55a47 100644 --- a/ts-user-service/src/main/java/user/service/UserService.java +++ b/ts-user-service/src/main/java/user/service/UserService.java @@ -18,7 +18,7 @@ public interface UserService { Response findByUserId(String userId, HttpHeaders headers); - Response deleteUser(UUID userId, HttpHeaders headers); + Response deleteUser(String userId, HttpHeaders headers); Response updateUser(UserDto user, HttpHeaders headers); } diff --git a/ts-user-service/src/main/java/user/service/impl/UserServiceImpl.java b/ts-user-service/src/main/java/user/service/impl/UserServiceImpl.java index 2cfbe527e..f015bbcf6 100644 --- a/ts-user-service/src/main/java/user/service/impl/UserServiceImpl.java +++ b/ts-user-service/src/main/java/user/service/impl/UserServiceImpl.java @@ -4,9 +4,13 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.cloud.client.ServiceInstance; +import org.springframework.cloud.client.discovery.DiscoveryClient; import org.springframework.core.ParameterizedTypeReference; import org.springframework.http.*; import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; import org.springframework.web.client.RestTemplate; import user.dto.AuthDto; import user.dto.UserDto; @@ -28,15 +32,22 @@ public class UserServiceImpl implements UserService { @Autowired private UserRepository userRepository; - private RestTemplate restTemplate = new RestTemplate(); - private static final String AUTH_SERVICE_URI = "http://ts-auth-service:12340/api/v1"; + @Autowired + private DiscoveryClient discoveryClient; + + @Autowired + private RestTemplate restTemplate; + + private String getServiceUrl(String serviceName) { + return "http://" + serviceName; + } @Override public Response saveUser(UserDto userDto, HttpHeaders headers) { - LOGGER.info("Save User Name id:" + userDto.getUserName()); - UUID userId = userDto.getUserId(); + LOGGER.info("[saveUser][Save User Name][user name: {}]", userDto.getUserName()); + String userId = userDto.getUserId(); if (userDto.getUserId() == null) { - userId = UUID.randomUUID(); + userId = UUID.randomUUID().toString(); } User user = User.builder() @@ -57,21 +68,30 @@ public Response saveUser(UserDto userDto, HttpHeaders headers) { .password(user.getPassword()).build()); User userSaveResult = userRepository.save(user); - LOGGER.info("Send authorization message to ts-auth-service...."); + LOGGER.info("[saveUser][Send authorization message to ts-auth-service....]"); return new Response<>(1, "REGISTER USER SUCCESS", userSaveResult); } else { - UserServiceImpl.LOGGER.error("Save user error.User already exists,UserId: {}",userDto.getUserId()); + UserServiceImpl.LOGGER.error("[saveUser][Save user error][User already exists][UserId: {}]",userDto.getUserId()); return new Response<>(0, "USER HAS ALREADY EXISTS", null); } } private Response createDefaultAuthUser(AuthDto dto) { - LOGGER.info("CALL TO AUTH"); - LOGGER.info("AuthDto : " + dto.toString()); + LOGGER.info("[createDefaultAuthUser][CALL TO AUTH][AuthDto: {}]", dto.toString()); HttpHeaders headers = new HttpHeaders(); HttpEntity entity = new HttpEntity<>(dto, null); - ResponseEntity> res = restTemplate.exchange("http://ts-auth-service:12340/api/v1/auth", + String auth_service_url = getServiceUrl("ts-auth-service"); + + List auth_svcs = discoveryClient.getInstances("ts-auth-service"); + if(auth_svcs.size() >0 ){ + ServiceInstance auth_svc = auth_svcs.get(0); + LOGGER.info("[createDefaultAuthUser][CALL TO AUTH][auth_svc host: {}][auth_svc port: {}]", auth_svc.getHost(), auth_svc.getPort()); + }else{ + LOGGER.info("[createDefaultAuthUser][CALL TO AUTH][can not get auth url]"); + } + + ResponseEntity> res = restTemplate.exchange(auth_service_url + "/api/v1/auth", HttpMethod.POST, entity, new ParameterizedTypeReference>() { @@ -85,7 +105,7 @@ public Response getAllUsers(HttpHeaders headers) { if (users != null && !users.isEmpty()) { return new Response<>(1, "Success", users); } - UserServiceImpl.LOGGER.warn("Get all users warn: {}","No Content"); + UserServiceImpl.LOGGER.warn("[getAllUsers][Get all users warn: {}]","No Content"); return new Response<>(0, "NO User", null); } @@ -95,40 +115,42 @@ public Response findByUserName(String userName, HttpHeaders headers) { if (user != null) { return new Response<>(1, "Find User Success", user); } - UserServiceImpl.LOGGER.warn("Get user by name warn,User Name: {}",userName); + UserServiceImpl.LOGGER.warn("[findByUserName][Get user by name warn,user is null][UserName: {}]",userName); return new Response<>(0, "No User", null); } @Override public Response findByUserId(String userId, HttpHeaders headers) { - User user = userRepository.findByUserId(UUID.fromString(userId)); + User user = userRepository.findByUserId(userId); if (user != null) { return new Response<>(1, "Find User Success", user); } - UserServiceImpl.LOGGER.error("Get user by id error,UserId: {}",userId); + UserServiceImpl.LOGGER.error("[findByUserId][Get user by id error,user is null][UserId: {}]",userId); return new Response<>(0, "No User", null); } @Override - public Response deleteUser(UUID userId, HttpHeaders headers) { - LOGGER.info("DELETE USER BY ID :" + userId); + @Transactional + public Response deleteUser(String userId, HttpHeaders headers) { + LOGGER.info("[deleteUser][DELETE USER BY ID][userId: {}]", userId); User user = userRepository.findByUserId(userId); if (user != null) { // first only admin token can delete success deleteUserAuth(userId, headers); // second userRepository.deleteByUserId(userId); - LOGGER.info("DELETE SUCCESS"); + LOGGER.info("[deleteUser][DELETE SUCCESS][userId: {}]", userId); return new Response<>(1, "DELETE SUCCESS", null); } else { - UserServiceImpl.LOGGER.error("Delete user error.User not found,UserId: {}",userId); + UserServiceImpl.LOGGER.error("[deleteUser][Delete user error][User not found][UserId: {}]",userId); return new Response<>(0, "USER NOT EXISTS", null); } } @Override + @Transactional public Response updateUser(UserDto userDto, HttpHeaders headers) { - LOGGER.info("UPDATE USER :" + userDto.toString()); + LOGGER.info("[updateUser][UPDATE USER: {}]", userDto.toString()); User oldUser = userRepository.findByUserName(userDto.getUserName()); if (oldUser != null) { User newUser = User.builder().email(userDto.getEmail()) @@ -142,19 +164,26 @@ public Response updateUser(UserDto userDto, HttpHeaders headers) { userRepository.save(newUser); return new Response<>(1, "SAVE USER SUCCESS", newUser); } else { - UserServiceImpl.LOGGER.error("Update user error.User not found,UserId: {}",userDto.getUserId()); + UserServiceImpl.LOGGER.error("[updateUser][Update user error][User not found][UserId: {}]",userDto.getUserId()); return new Response(0, "USER NOT EXISTS", null); } } - public void deleteUserAuth(UUID userId, HttpHeaders headers) { - LOGGER.info("DELETE USER BY ID :" + userId); + public void deleteUserAuth(String userId, HttpHeaders headers) { + LOGGER.info("[deleteUserAuth][DELETE USER BY ID][userId: {}]", userId); + + HttpHeaders newHeaders = new HttpHeaders(); + String token = headers.getFirst(HttpHeaders.AUTHORIZATION); + newHeaders.set(HttpHeaders.AUTHORIZATION, token); + + HttpEntity httpEntity = new HttpEntity<>(newHeaders); - HttpEntity httpEntity = new HttpEntity<>(null); + String auth_service_url = getServiceUrl("ts-auth-service"); + String AUTH_SERVICE_URI = auth_service_url + "/api/v1"; restTemplate.exchange(AUTH_SERVICE_URI + "/users/" + userId, HttpMethod.DELETE, httpEntity, Response.class); - LOGGER.info("DELETE USER AUTH SUCCESS"); + LOGGER.info("[deleteUserAuth][DELETE USER AUTH SUCCESS][userId: {}]", userId); } } diff --git a/ts-user-service/src/main/resources/application.yaml b/ts-user-service/src/main/resources/application.yaml index 671468836..b860127aa 100644 --- a/ts-user-service/src/main/resources/application.yaml +++ b/ts-user-service/src/main/resources/application.yaml @@ -2,13 +2,24 @@ server: port: 12342 spring: + cloud: + nacos: + discovery: + server-addr: ${NACOS_ADDRS:nacos-0.nacos-headless.default.svc.cluster.local,nacos-1.nacos-headless.default.svc.cluster.local,nacos-2.nacos-headless.default.svc.cluster.local} application: name: ts-user-service - data: - mongodb: - host: ts-user-mongo - database: ts-user-mongo - port: 27017 + datasource: + url: jdbc:mysql://${USER_MYSQL_HOST:ts-user-mysql}:${USER_MYSQL_PORT:3306}/${USER_MYSQL_DATABASE:ts-user-mysql}?useSSL=false + username: ${USER_MYSQL_USER:root} + password: ${USER_MYSQL_PASSWORD:Abcd1234#} + driver-class-name: com.mysql.cj.jdbc.Driver + jpa: + hibernate: + ddl-auto: update + properties: + hibernate: + dialect: org.hibernate.dialect.MySQL5Dialect + swagger: - controllerPackage: user.controller \ No newline at end of file + controllerPackage: user.controller diff --git a/ts-user-service/src/test/java/user/controller/UserControllerTest.java b/ts-user-service/src/test/java/user/controller/UserControllerTest.java index 1c2a91586..0e8de11b4 100644 --- a/ts-user-service/src/test/java/user/controller/UserControllerTest.java +++ b/ts-user-service/src/test/java/user/controller/UserControllerTest.java @@ -86,7 +86,7 @@ public void testRegisterUser() throws Exception { @Test public void testDeleteUserById() throws Exception { UUID userId = UUID.randomUUID(); - Mockito.when(userService.deleteUser(Mockito.any(UUID.class), Mockito.any(HttpHeaders.class))).thenReturn(response); + Mockito.when(userService.deleteUser(Mockito.any(UUID.class).toString(), Mockito.any(HttpHeaders.class))).thenReturn(response); String result = mockMvc.perform(MockMvcRequestBuilders.delete("/api/v1/userservice/users/" + userId.toString())) .andExpect(MockMvcResultMatchers.status().isOk()) .andReturn().getResponse().getContentAsString(); diff --git a/ts-user-service/src/test/java/user/service/UserServiceImplTest.java b/ts-user-service/src/test/java/user/service/UserServiceImplTest.java index f104dff33..f5854bf19 100644 --- a/ts-user-service/src/test/java/user/service/UserServiceImplTest.java +++ b/ts-user-service/src/test/java/user/service/UserServiceImplTest.java @@ -44,7 +44,7 @@ public void setUp() { @Test public void testSaveUser() { - UserDto userDto = new UserDto(UUID.randomUUID(), "user_name", "xxx", 0, 1, "", ""); + UserDto userDto = new UserDto(UUID.randomUUID().toString(), "user_name", "xxx", 0, 1, "", ""); Mockito.when(userRepository.findByUserName(Mockito.anyString())).thenReturn(null); //mock createDefaultAuthUser() @@ -98,7 +98,7 @@ public void testFindByUserName2() { public void testFindByUserId1() { UUID userId = UUID.randomUUID(); User user = new User(); - Mockito.when(userRepository.findByUserId(Mockito.any(UUID.class))).thenReturn(user); + Mockito.when(userRepository.findByUserId(Mockito.any(UUID.class).toString())).thenReturn(user); Response result = userServiceImpl.findByUserId(userId.toString(), headers); Assert.assertEquals(new Response<>(1, "Find User Success", user), result); } @@ -106,22 +106,22 @@ public void testFindByUserId1() { @Test public void testFindByUserId2() { UUID userId = UUID.randomUUID(); - Mockito.when(userRepository.findByUserId(Mockito.any(UUID.class))).thenReturn(null); + Mockito.when(userRepository.findByUserId(Mockito.any(UUID.class).toString())).thenReturn(null); Response result = userServiceImpl.findByUserId(userId.toString(), headers); Assert.assertEquals(new Response<>(0, "No User", null), result); } @Test public void testDeleteUser1() { - UUID userId = UUID.randomUUID(); + String userId = UUID.randomUUID().toString(); User user = new User(); - Mockito.when(userRepository.findByUserId(Mockito.any(UUID.class))).thenReturn(user); + Mockito.when(userRepository.findByUserId(Mockito.any(UUID.class).toString())).thenReturn(user); HttpEntity httpEntity = new HttpEntity<>(headers); Mockito.when(restTemplate.exchange("http://ts-auth-service:12340/api/v1" + "/users/" + userId, HttpMethod.DELETE, httpEntity, Response.class)).thenReturn(null); - Mockito.doNothing().doThrow(new RuntimeException()).when(userRepository).deleteByUserId(Mockito.any(UUID.class)); + Mockito.doNothing().doThrow(new RuntimeException()).when(userRepository).deleteByUserId(Mockito.any(UUID.class).toString()); Response result = userServiceImpl.deleteUser(userId, headers); Assert.assertEquals(new Response<>(1, "DELETE SUCCESS", null), result); } @@ -129,8 +129,8 @@ public void testDeleteUser1() { @Test public void testDeleteUser2() { UUID userId = UUID.randomUUID(); - Mockito.when(userRepository.findByUserId(Mockito.any(UUID.class))).thenReturn(null); - Response result = userServiceImpl.deleteUser(userId, headers); + Mockito.when(userRepository.findByUserId(Mockito.any(UUID.class).toString())).thenReturn(null); + Response result = userServiceImpl.deleteUser(userId.toString(), headers); Assert.assertEquals(new Response<>(0, "USER NOT EXISTS", null), result); } @@ -139,7 +139,7 @@ public void testUpdateUser1() { UserDto userDto = new UserDto(); User oldUser = new User(); Mockito.when(userRepository.findByUserName(Mockito.anyString())).thenReturn(oldUser); - Mockito.doNothing().doThrow(new RuntimeException()).when(userRepository).deleteByUserId(Mockito.any(UUID.class)); + Mockito.doNothing().doThrow(new RuntimeException()).when(userRepository).deleteByUserId(Mockito.any(UUID.class).toString()); Mockito.when(userRepository.save(Mockito.any(User.class))).thenReturn(null); Response result = userServiceImpl.updateUser(userDto, headers); Assert.assertEquals("SAVE USER SUCCESS", result.getMsg()); @@ -161,7 +161,7 @@ public void testDeleteUserAuth() { HttpMethod.DELETE, httpEntity, Response.class)).thenReturn(null); - userServiceImpl.deleteUserAuth(userId, headers); + userServiceImpl.deleteUserAuth(userId.toString(), headers); Mockito.verify(restTemplate, Mockito.times(1)) .exchange(Mockito.anyString(), Mockito.any(HttpMethod.class), Mockito.any(HttpEntity.class), Mockito.any(Class.class)); } diff --git a/ts-verification-code-service/pom.xml b/ts-verification-code-service/pom.xml index d6cd9d6ed..69a503e3a 100644 --- a/ts-verification-code-service/pom.xml +++ b/ts-verification-code-service/pom.xml @@ -14,7 +14,7 @@ org.services ts-service 0.1.0 - ../ + ../pom.xml @@ -28,16 +28,12 @@ ts-common 0.1.0 - com.google.guava guava - 18.0 + 31.0-jre - - - diff --git a/ts-verification-code-service/src/main/java/verifycode/VerifyCodeApplication.java b/ts-verification-code-service/src/main/java/verifycode/VerifyCodeApplication.java index 1b2a58a38..602937842 100644 --- a/ts-verification-code-service/src/main/java/verifycode/VerifyCodeApplication.java +++ b/ts-verification-code-service/src/main/java/verifycode/VerifyCodeApplication.java @@ -2,13 +2,24 @@ import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.boot.web.client.RestTemplateBuilder; +import org.springframework.cloud.client.discovery.EnableDiscoveryClient; +import org.springframework.cloud.client.loadbalancer.LoadBalanced; +import org.springframework.context.annotation.Bean; +import org.springframework.web.client.RestTemplate; /** * @author fdse */ @SpringBootApplication +@EnableDiscoveryClient public class VerifyCodeApplication { public static void main(String[] args) { SpringApplication.run(VerifyCodeApplication.class, args); } + @LoadBalanced + @Bean + public RestTemplate restTemplate(RestTemplateBuilder builder) { + return builder.build(); + } } diff --git a/ts-verification-code-service/src/main/java/verifycode/controller/VerifyCodeController.java b/ts-verification-code-service/src/main/java/verifycode/controller/VerifyCodeController.java index 97413354d..60f99167a 100644 --- a/ts-verification-code-service/src/main/java/verifycode/controller/VerifyCodeController.java +++ b/ts-verification-code-service/src/main/java/verifycode/controller/VerifyCodeController.java @@ -30,7 +30,7 @@ public class VerifyCodeController { public void imageCode(@RequestHeader HttpHeaders headers, HttpServletRequest request, HttpServletResponse response) throws IOException { - VerifyCodeController.LOGGER.info("Image code"); + VerifyCodeController.LOGGER.info("[imageCode][Image code]"); OutputStream os = response.getOutputStream(); Map map = verifyCodeService.getImageCode(60, 20, os, request, response, headers); String simpleCaptcha = "simpleCaptcha"; @@ -48,10 +48,10 @@ public void imageCode(@RequestHeader HttpHeaders headers, @GetMapping(value = "/verify/{verifyCode}") public boolean verifyCode(@PathVariable String verifyCode, HttpServletRequest request, HttpServletResponse response, @RequestHeader HttpHeaders headers) { - LOGGER.info("receivedCode " + verifyCode); + LOGGER.info("[verifyCode][receivedCode: {}]", verifyCode); boolean result = verifyCodeService.verifyCode(request, response, verifyCode, headers); - LOGGER.info("verify result: " + result); + LOGGER.info("[verifyCode][verify result: {}]", result); return true; } } diff --git a/ts-verification-code-service/src/main/java/verifycode/service/impl/VerifyCodeServiceImpl.java b/ts-verification-code-service/src/main/java/verifycode/service/impl/VerifyCodeServiceImpl.java index 546603090..b50c74674 100644 --- a/ts-verification-code-service/src/main/java/verifycode/service/impl/VerifyCodeServiceImpl.java +++ b/ts-verification-code-service/src/main/java/verifycode/service/impl/VerifyCodeServiceImpl.java @@ -93,7 +93,7 @@ public Map getImageCode(int width, int height, OutputStream os, Cookie cookie = CookieUtil.getCookieByName(request, ysbCaptcha); String cookieId; if (cookie == null) { - VerifyCodeServiceImpl.LOGGER.warn("Get image code warn.Cookie not found,Path Info: {}",request.getPathInfo()); + VerifyCodeServiceImpl.LOGGER.warn("[getImageCode][Get image code warn.Cookie not found][Path Info: {}]",request.getPathInfo()); cookieId = UUID.randomUUID().toString().replace("-", "").toUpperCase(); CookieUtil.addCookie(response, ysbCaptcha, cookieId, CAPTCHA_EXPIRED); } else { @@ -104,7 +104,7 @@ public Map getImageCode(int width, int height, OutputStream os, cookieId = cookie.getValue(); } } - VerifyCodeServiceImpl.LOGGER.info(" {} ___ st", strEnsure); + VerifyCodeServiceImpl.LOGGER.info("[getImageCode][strEnsure: {}]", strEnsure); cacheCode.put(cookieId, strEnsure); return returnMap; } @@ -115,7 +115,7 @@ public boolean verifyCode(HttpServletRequest request, HttpServletResponse respon Cookie cookie = CookieUtil.getCookieByName(request, ysbCaptcha); String cookieId; if (cookie == null) { - VerifyCodeServiceImpl.LOGGER.warn("Verify code warn.Cookie not found,Path Info: {}",request.getPathInfo()); + VerifyCodeServiceImpl.LOGGER.warn("[verifyCode][Verify code warn][Cookie not found][Path Info: {}]",request.getPathInfo()); cookieId = UUID.randomUUID().toString().replace("-", "").toUpperCase(); CookieUtil.addCookie(response, ysbCaptcha, cookieId, CAPTCHA_EXPIRED); } else { @@ -125,7 +125,7 @@ public boolean verifyCode(HttpServletRequest request, HttpServletResponse respon String code = cacheCode.getIfPresent(cookieId); LOGGER.info("GET Code By cookieId " + cookieId + " is :" + code); if (code == null) { - VerifyCodeServiceImpl.LOGGER.warn("Get image code warn.Code not found,CookieId: {}",cookieId); + VerifyCodeServiceImpl.LOGGER.warn("[verifyCode][Get image code warn][Code not found][CookieId: {}]",cookieId); return false; } if (code.equalsIgnoreCase(receivedCode)) { diff --git a/ts-verification-code-service/src/main/resources/application.yml b/ts-verification-code-service/src/main/resources/application.yml index fa21f611c..44f513d07 100644 --- a/ts-verification-code-service/src/main/resources/application.yml +++ b/ts-verification-code-service/src/main/resources/application.yml @@ -2,7 +2,10 @@ server: port: 15678 # HTTP (Tomcat) port spring: - + cloud: + nacos: + discovery: + server-addr: ${NACOS_ADDRS:nacos-0.nacos-headless.default.svc.cluster.local,nacos-1.nacos-headless.default.svc.cluster.local,nacos-2.nacos-headless.default.svc.cluster.local} application: name: ts-verification-code-service diff --git a/ts-voucher-service/server.py b/ts-voucher-service/server.py index 52544b558..3d325972f 100644 --- a/ts-voucher-service/server.py +++ b/ts-voucher-service/server.py @@ -2,10 +2,13 @@ import tornado.ioloop import tornado.web import json +import os import pymysql import urllib import urllib.request +mysql_config = {} + class GetVoucherHandler(tornado.web.RequestHandler): def post(self, *args, **kwargs): @@ -25,14 +28,8 @@ def post(self, *args, **kwargs): # self.write(jsonStr) #Insert vouchers table into a voucher - config = { - 'host':'ts-voucher-mysql', - 'port':3306, - 'user':'root', - 'password':'root', - 'db':'voucherservice' - } - conn = pymysql.connect(**config) + global mysql_config + conn = pymysql.connect(**mysql_config) cur = conn.cursor() #Insert statement sql = 'INSERT INTO voucher (order_id,travelDate,travelTime,contactName,trainNumber,seatClass,seatNumber,startStation,destStation,price)VALUES(%s, %s, %s, %s, %s, %s, %s, %s, %s, %s)' @@ -47,12 +44,22 @@ def post(self, *args, **kwargs): self.write(queryVoucher) def queryOrderByIdAndType(self,orderId,type): + # Because nacos-sdk-python does not support nacos 2.x yet, we still use environment variables + # to set order-service url. type = int(type) #ordinary train + order_url = 'http://ts-order-service:12031' + order_other_url = 'http://ts-order-other-service:12032' + if(os.getenv("ORDER_SERVICE_URL") is not None): + order_url = os.getenv("ORDER_SERVICE_URL") + + if(os.getenv("ORDER_OTHER_SERVICE_URL") is not None): + order_other_url = os.getenv("ORDER_OTHER_SERVICE_URL") + if(type == 0): - url='http://ts-order-other-service:12032/api/v1/orderOtherService/orderOther/' + orderId + url=order_other_url + '/api/v1/orderOtherService/orderOther/' + orderId else: - url='http://ts-order-service:12031/api/v1/orderservice/order/'+orderId + url=order_url + '/api/v1/orderservice/order/'+orderId header_dict = {'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; Trident/7.0; rv:11.0) like Gecko',"Content-Type": "application/json"} req = urllib.request.Request(url=url,headers=header_dict)# Generate the full data for the page request response = urllib.request.urlopen(req)# Send page request @@ -60,14 +67,8 @@ def queryOrderByIdAndType(self,orderId,type): def fetchVoucherByOrderId(self,orderId): #Check the voucher for reimbursement for orderId from the voucher table - config = { - 'host':'ts-voucher-mysql', - 'port':3306, - 'user':'root', - 'password':'root', - 'db':'voucherservice' - } - conn = pymysql.connect(**config) + global mysql_config + conn = pymysql.connect(**mysql_config) cur = conn.cursor() #query statement sql = 'SELECT * FROM voucher where order_id = %s' @@ -101,34 +102,14 @@ def make_app(): ]) def initDatabase(): - config = { - 'host':'ts-voucher-mysql', - 'port':3306, - 'user':'root', - 'password':'root' - } # Create a connection - connect = pymysql.connect(**config) + print(mysql_config) + connect = pymysql.connect(**mysql_config) cur = connect.cursor() - #create db - sql = "CREATE SCHEMA IF NOT EXISTS voucherservice;" - try: - cur.execute(sql) - connect.commit() - finally: - pass - - #Use the database - sql = "use voucherservice;" - try: - cur.execute(sql) - connect.commit() - finally: - pass #Create the table sql = """ - CREATE TABLE if not exists voucherservice.voucher ( + CREATE TABLE if not exists voucher ( voucher_id INT NOT NULL AUTO_INCREMENT, order_id VARCHAR(1024) NOT NULL, travelDate VARCHAR(1024) NOT NULL, @@ -147,8 +128,36 @@ def initDatabase(): finally: connect.close() +def initMysqlConfig(): + global mysql_config + host = "ts-voucher-mysql" + port = 3306 + user = "root" + password = "Abcd1234#" + db = "ts-voucher-mysql" + if(os.getenv("VOUCHER_MYSQL_HOST") is not None): + host = os.getenv("VOUCHER_MYSQL_HOST") + if(os.getenv("VOUCHER_MYSQL_PORT") is not None): + port = int(os.getenv("VOUCHER_MYSQL_PORT")) + if(os.getenv("VOUCHER_MYSQL_USER") is not None): + user = os.getenv("VOUCHER_MYSQL_USER") + if(os.getenv("VOUCHER_MYSQL_PASSWORD") is not None): + password = os.getenv("VOUCHER_MYSQL_PASSWORD") + if(os.getenv("VOUCHER_MYSQL_DATABASE") is not None): + db = os.getenv("VOUCHER_MYSQL_DATABASE") + + mysql_config = { + 'host': host, + 'port': port, + 'user': user, + 'password': password, + 'db': db + } + + if __name__ == "__main__": #Create database and tables + initMysqlConfig() initDatabase() app = make_app() app.listen(16101) diff --git a/ts-wait-order-service/pom.xml b/ts-wait-order-service/pom.xml new file mode 100644 index 000000000..c2615b8d4 --- /dev/null +++ b/ts-wait-order-service/pom.xml @@ -0,0 +1,57 @@ + + + 4.0.0 + + fdse.microservice + ts-wait-order-service + 1.0 + jar + + ts-wait-order-service + + + org.services + ts-service + 0.1.0 + ../pom.xml + + + + UTF-8 + 1.8 + + + + + org.springframework.boot + spring-boot-starter-data-jpa + + + mysql + mysql-connector-java + + + org.services + ts-common + 0.1.0 + + + jakarta.validation + jakarta.validation-api + 2.0.2 + compile + + + + + + + org.springframework.boot + spring-boot-maven-plugin + + + + + \ No newline at end of file diff --git a/ts-wait-order-service/src/main/java/waitorder/WaitOrderApplication.java b/ts-wait-order-service/src/main/java/waitorder/WaitOrderApplication.java new file mode 100644 index 000000000..6230efcf7 --- /dev/null +++ b/ts-wait-order-service/src/main/java/waitorder/WaitOrderApplication.java @@ -0,0 +1,33 @@ +package waitorder; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.boot.web.client.RestTemplateBuilder; +import org.springframework.cloud.client.discovery.EnableDiscoveryClient; +import org.springframework.cloud.client.loadbalancer.LoadBalanced; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.EnableAspectJAutoProxy; +import org.springframework.integration.annotation.IntegrationComponentScan; +import org.springframework.scheduling.annotation.EnableAsync; +import org.springframework.web.client.RestTemplate; +import springfox.documentation.swagger2.annotations.EnableSwagger2; + +@SpringBootApplication +@EnableAspectJAutoProxy(proxyTargetClass = true) +@EnableAsync +@IntegrationComponentScan +@EnableSwagger2 +@EnableDiscoveryClient +public class WaitOrderApplication { + + public static void main(String[] args) { + SpringApplication.run(WaitOrderApplication.class, args); + } + + @LoadBalanced + @Bean + public RestTemplate restTemplate(RestTemplateBuilder builder) { + return builder.build(); + } + +} diff --git a/ts-wait-order-service/src/main/java/waitorder/config/SecurityConfig.java b/ts-wait-order-service/src/main/java/waitorder/config/SecurityConfig.java new file mode 100644 index 000000000..4ba5b9d8e --- /dev/null +++ b/ts-wait-order-service/src/main/java/waitorder/config/SecurityConfig.java @@ -0,0 +1,90 @@ +package waitorder.config; + +import edu.fudan.common.security.jwt.JWTFilter; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.http.HttpMethod; +import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity; +import org.springframework.security.config.annotation.web.builders.HttpSecurity; +import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; +import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; +import org.springframework.security.config.http.SessionCreationPolicy; +import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; +import org.springframework.security.crypto.password.PasswordEncoder; +import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter; +import org.springframework.web.servlet.config.annotation.CorsRegistry; +import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; +import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter; + +import static org.springframework.web.cors.CorsConfiguration.ALL; + +/** + * @author fdse + */ +@Configuration +@EnableWebSecurity +@EnableGlobalMethodSecurity(prePostEnabled = true) +public class SecurityConfig extends WebSecurityConfigurerAdapter { + + String admin = "ADMIN"; + String order = "/api/v1/orderservice/order"; + + /** + * load password encoder + * + * @return PasswordEncoder + */ + @Bean + public PasswordEncoder passwordEncoder() { + return new BCryptPasswordEncoder(); + } + + /** + * allow cors domain + * header By default, only six fields can be taken from the header, and the other fields can only be specified in the header. + * credentials Cookies are not sent by default and can only be true if a Cookie is needed + * Validity of this request + * + * @return WebMvcConfigurer + */ + @Bean + public WebMvcConfigurer corsConfigurer() { + return new WebMvcConfigurerAdapter() { + @Override + public void addCorsMappings(CorsRegistry registry) { + registry.addMapping("/**") + .allowedOrigins(ALL) + .allowedMethods(ALL) + .allowedHeaders(ALL) + .allowCredentials(false) + .maxAge(3600); + } + }; + } + + + @Override + protected void configure(HttpSecurity httpSecurity) throws Exception { + httpSecurity.httpBasic().disable() + // close default csrf + .csrf().disable() + // close session + .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS) + .and() + .authorizeRequests() + .antMatchers(HttpMethod.POST, order).hasAnyRole(admin, "USER") + .antMatchers(HttpMethod.PUT, order).hasAnyRole(admin, "USER") + .antMatchers(HttpMethod.DELETE, order).hasAnyRole(admin, "USER") + .antMatchers(HttpMethod.POST, "/api/v1/orderservice/order/admin").hasAnyRole(admin) + .antMatchers(HttpMethod.PUT, "/api/v1/orderservice/order/admin").hasAnyRole(admin) + .antMatchers("/api/v1/orderservice/order/**").permitAll() + .antMatchers("/swagger-ui.html", "/webjars/**", "/images/**", + "/configuration/**", "/swagger-resources/**", "/v2/**").permitAll() + .anyRequest().authenticated() + .and() + .addFilterBefore(new JWTFilter(), UsernamePasswordAuthenticationFilter.class); + + // close cache + httpSecurity.headers().cacheControl(); + } +} diff --git a/ts-wait-order-service/src/main/java/waitorder/controller/WaitListOrderController.java b/ts-wait-order-service/src/main/java/waitorder/controller/WaitListOrderController.java new file mode 100644 index 000000000..82dc20a3a --- /dev/null +++ b/ts-wait-order-service/src/main/java/waitorder/controller/WaitListOrderController.java @@ -0,0 +1,52 @@ +package waitorder.controller; + + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.http.HttpEntity; +import org.springframework.http.HttpHeaders; +import org.springframework.web.bind.annotation.*; +import waitorder.entity.WaitListOrderVO; +import waitorder.service.WaitListOrderService; + + +import static org.springframework.http.ResponseEntity.ok; + +/** + * @author fdse + */ +@RestController +@RequestMapping("/api/v1/waitorderservice") +public class WaitListOrderController { + + @Autowired + private WaitListOrderService waitListOrderService; + + private static final Logger LOGGER = LoggerFactory.getLogger(WaitListOrderController.class); + + @GetMapping(path = "/welcome") + public String home() { + return "Welcome to [ Wait Order Service ] !"; + } + + @PostMapping(path = "/order") + public HttpEntity createNewOrder(@RequestBody WaitListOrderVO createOrder, @RequestHeader HttpHeaders headers) { + WaitListOrderController.LOGGER.info("[createWaitOrder][Create Wait Order][from {} to {} at {}]", createOrder.getFrom(), createOrder.getTo(), createOrder.getDate()); + return ok(waitListOrderService.create(createOrder, headers)); + } + + @GetMapping(path = "/orders") + public HttpEntity getAllOrders(@RequestHeader HttpHeaders headers){ + LOGGER.info("[getAllOrders][Get All Orders]"); + return ok(waitListOrderService.getAllOrders(headers)); + } + + @GetMapping(path = "/waitlistorders") + public HttpEntity getWaitListOrders(@RequestHeader HttpHeaders headers){ + LOGGER.info("[getWaitListOrders][Get All Wait List Orders]"); + return ok(waitListOrderService.getAllWaitListOrders(headers)); + } + + +} diff --git a/ts-wait-order-service/src/main/java/waitorder/entity/WaitListOrder.java b/ts-wait-order-service/src/main/java/waitorder/entity/WaitListOrder.java new file mode 100644 index 000000000..807bfa5c0 --- /dev/null +++ b/ts-wait-order-service/src/main/java/waitorder/entity/WaitListOrder.java @@ -0,0 +1,106 @@ +package waitorder.entity; + +import edu.fudan.common.util.StringUtils; +import lombok.AllArgsConstructor; +import lombok.Data; +import org.hibernate.annotations.GenericGenerator; + +import javax.persistence.*; +import java.util.Calendar; +import java.util.Date; + + +@Data +@AllArgsConstructor +@Entity +@GenericGenerator(name = "jpa-uuid", strategy ="uuid") +public class WaitListOrder { + @Id + @GeneratedValue(generator = "jpa-uuid") + @Column(length = 36) + private String id; + +// private String travelDate; + private String travelTime; + + @Column(length = 36) + private String accountId; + private String contactsId; + private String contactsName; + private int contactsDocumentType; + private String contactsDocumentNumber; + private String trainNumber; + private int seatType; + + @Column(name = "from_station") + private String from; + @Column(name = "to_station") + private String to; + + private String price; + private String waitUtilTime; + private String createdTime; + private int status; + + + public WaitListOrder(){ + createdTime = StringUtils.Date2String(new Date(System.currentTimeMillis())); +// trainNumber = "G1235"; +// seatType = SeatClass.FIRSTCLASS.getCode(); +// from = "shanghai"; +// to = "taiyuan"; +// price = "0.0"; + + //wait until 24 hours later + Calendar c = Calendar.getInstance(); + c.setTime(new Date(System.currentTimeMillis())); + c.add(Calendar.DAY_OF_MONTH,1); + waitUtilTime = StringUtils.Date2String(c.getTime()); + travelTime=StringUtils.Date2String(c.getTime()); + status= WaitListOrderStatus.NOTPAID.getCode(); + } + +// @Override +// public boolean equals(Object o) { +// if (this == o) return true; +// if (o == null || getClass() != o.getClass()) return false; +// WaitListOrder that = (WaitListOrder) o; +// return contactsDocumentType == that.contactsDocumentType +// && coachNumber == that.coachNumber +// && seatClass == that.seatClass +// && id.equals(that.id) +// && Objects.equals(travelTime, that.travelTime) +// && Objects.equals(accountId, that.accountId) +// && Objects.equals(contactsName, that.contactsName) +// && Objects.equals(contactsDocumentNumber, that.contactsDocumentNumber) +// && Objects.equals(trainNumber, that.trainNumber) +// && Objects.equals(seatNumber, that.seatNumber) +// && Objects.equals(fromStation, that.fromStation) +// && Objects.equals(toStation, that.toStation) +// && Objects.equals(price, that.price); +// } + + @Override + public int hashCode() { + int result = 17; + result = 31 * result + (id == null ? 0 : id.hashCode()); + return result; + } + + public Date getCreatedTime(){ return StringUtils.String2Date(createdTime); } + + public Date getTravelTime(){ return StringUtils.String2Date(createdTime); } + + public Date getWaitUtilTime(){ return StringUtils.String2Date(waitUtilTime); } + + public void setCreatedTime(Date createdTime){ + this.createdTime = StringUtils.Date2String(createdTime); + } + + public void setTravelTime(Date travelTime){ this.createdTime = StringUtils.Date2String(travelTime); } + + public void setWaitUntilTime(Date waitUntilTime){ this.waitUtilTime=StringUtils.Date2String(waitUntilTime);} + + + +} diff --git a/ts-preserve-service/src/main/java/preserve/entity/OrderStatus.java b/ts-wait-order-service/src/main/java/waitorder/entity/WaitListOrderStatus.java similarity index 75% rename from ts-preserve-service/src/main/java/preserve/entity/OrderStatus.java rename to ts-wait-order-service/src/main/java/waitorder/entity/WaitListOrderStatus.java index d33482e81..a04e46e81 100644 --- a/ts-preserve-service/src/main/java/preserve/entity/OrderStatus.java +++ b/ts-wait-order-service/src/main/java/waitorder/entity/WaitListOrderStatus.java @@ -1,10 +1,8 @@ -package preserve.entity; +package waitorder.entity; -/** - * @author fdse - */ -public enum OrderStatus { +import edu.fudan.common.entity.OrderStatus; +public enum WaitListOrderStatus { /** * not paid */ @@ -17,27 +15,25 @@ public enum OrderStatus { * collected */ COLLECTED (2,"Collected"), - /** - * rebook - */ - CHANGE (3,"Rebook"), /** * cancel */ - CANCEL (4,"Cancel"), + CANCEL (3,"Cancel"), /** * refunded */ - REFUNDS (5,"Refunded"), + REFUNDS (4,"Refunded"), /** - * used + * expired */ - USED (6,"Used"); + EXPIRED (5, "Expired"); + + private int code; private String name; - OrderStatus(int code, String name){ + WaitListOrderStatus(int code, String name){ this.code = code; this.name = name; } @@ -59,5 +55,4 @@ public static String getNameByCode(int code){ } return orderStatusSet[0].getName(); } - } diff --git a/ts-wait-order-service/src/main/java/waitorder/entity/WaitListOrderVO.java b/ts-wait-order-service/src/main/java/waitorder/entity/WaitListOrderVO.java new file mode 100644 index 000000000..e0fcbfc9c --- /dev/null +++ b/ts-wait-order-service/src/main/java/waitorder/entity/WaitListOrderVO.java @@ -0,0 +1,46 @@ +package waitorder.entity; + +import edu.fudan.common.util.StringUtils; +import lombok.AllArgsConstructor; +import lombok.Builder; +import lombok.Data; +import lombok.NoArgsConstructor; + +import java.util.Date; + +/** + * @author fdse + */ +@Data +@Builder +@NoArgsConstructor +@AllArgsConstructor +public class WaitListOrderVO { + private String accountId; + + private String contactsId; + + private String tripId; + + private int seatType; + + private String date; + + private String from; + + private String to; + + private String price; + + + public Date getDate(){ + return StringUtils.String2Date(date); + } + + public void setDate(Date date){ + this.date = StringUtils.Date2String(date); + } + + +} + diff --git a/ts-wait-order-service/src/main/java/waitorder/repository/WaitListOrderRepository.java b/ts-wait-order-service/src/main/java/waitorder/repository/WaitListOrderRepository.java new file mode 100644 index 000000000..92641e040 --- /dev/null +++ b/ts-wait-order-service/src/main/java/waitorder/repository/WaitListOrderRepository.java @@ -0,0 +1,25 @@ +package waitorder.repository; + + +import org.springframework.data.repository.CrudRepository; +import org.springframework.stereotype.Repository; +import waitorder.entity.WaitListOrder; + +import java.util.ArrayList; +import java.util.List; +import java.util.Optional; + +@Repository +public interface WaitListOrderRepository extends CrudRepository { + + @Override + Optional findById(String id); + + @Override + List findAll(); + + ArrayList findByAccountId(String accountId); + + @Override + void deleteById(String id); +} diff --git a/ts-wait-order-service/src/main/java/waitorder/service/Impl/WaitListOrderServiceImpl.java b/ts-wait-order-service/src/main/java/waitorder/service/Impl/WaitListOrderServiceImpl.java new file mode 100644 index 000000000..a8dc2056e --- /dev/null +++ b/ts-wait-order-service/src/main/java/waitorder/service/Impl/WaitListOrderServiceImpl.java @@ -0,0 +1,174 @@ +package waitorder.service.Impl; + +import edu.fudan.common.util.Response; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.BeanUtils; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.cloud.client.discovery.DiscoveryClient; +import org.springframework.http.HttpHeaders; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; +import org.springframework.web.client.RestTemplate; +import waitorder.entity.WaitListOrder; +import waitorder.entity.WaitListOrderStatus; +import waitorder.entity.WaitListOrderVO; +import waitorder.repository.WaitListOrderRepository; +import waitorder.service.WaitListOrderService; +import waitorder.utils.PollThread; + +import java.util.*; +import java.util.stream.Collectors; + +@Service +public class WaitListOrderServiceImpl implements WaitListOrderService { + + @Autowired + private WaitListOrderRepository waitListOrderRepository; + + @Autowired + private RestTemplate restTemplate; + + @Autowired + private DiscoveryClient discoveryClient; + + private static final Logger LOGGER = LoggerFactory.getLogger(WaitListOrderServiceImpl.class); + + String success = "Success"; + + @Override + public Response findOrderById(String id, HttpHeaders headers) { + Optional op = waitListOrderRepository.findById(id); + if(!op.isPresent()){ + LOGGER.warn("[findWaitOrderById][Find Order By Id Fail][No content][id: {}] ",id); + return new Response<>(0, "No Content by this id", null); + } else { + WaitListOrder wo = op.get(); + LOGGER.info("[findWaitOrderById][Find Order By Id Success][id: {}] ",id); + return new Response<>(1, success, wo); + } + } + + @Transactional + @Override + public Response create(WaitListOrderVO orderVO, HttpHeaders headers) { + LOGGER.info("[create][Create Wait Order][Ready to Create Wait Order]"); + Response response=saveNewOrder(orderVO,headers); + if(response.getStatus()==0){ + //未能正常保存到数据库 + return response; + } else { + //已保存到数据库 开始轮询 + return triggerThread(response.getData(),orderVO,headers); + } + } + + @Override + public Response getAllOrders(HttpHeaders headers) { + List orderList= waitListOrderRepository.findAll(); + if (orderList != null && !orderList.isEmpty()) { + WaitListOrderServiceImpl.LOGGER.warn("[getAllOrders][Find all orders Success][size:{}]",orderList.size()); + return new Response<>(1, "Success.", orderList); + } else { + LOGGER.warn("[getAllOrders][Find All Wait List Orders Fail][{}]","No content"); + return new Response<>(0, "No Content.", null); + } + } + + @Override + public Response getAllWaitListOrders(HttpHeaders headers) { + List orderList= waitListOrderRepository.findAll(); + if (orderList != null && !orderList.isEmpty()) { + WaitListOrderServiceImpl.LOGGER.warn("[getAllWaitListOrders][Find all orders Success][size:{}]",orderList.size()); + List filterList=new ArrayList<>(); + filterList.add(WaitListOrderStatus.NOTPAID.getCode()); + filterList.add(WaitListOrderStatus.PAID.getCode()); + //Only orders in the wait list will be selected + orderList=orderList.stream() + .filter(WaitListOrder -> filterList.contains(WaitListOrder.getStatus())) + .collect(Collectors.toList()); + return new Response<>(1, "Success.", orderList); + } else { + LOGGER.warn("[getAllWaitListOrders][Find All Wait List Orders Fail][{}]","No content"); + return new Response<>(0, "No Content.", null); + } + } + + @Transactional + @Override + public Response updateOrder(WaitListOrder order, HttpHeaders headers) { + LOGGER.info("[updateOrder][Update Wait List Order][Order Info:{}] ", order.toString()); + Optional op = waitListOrderRepository.findById(order.getId()); + if(!op.isPresent()){ + LOGGER.error("[updateOrder][Update Order Info Fail][Order not found][OrderId: {}]",order.getId()); + return new Response<>(0, "Order Not Found, Can't update", null); + } else { + WaitListOrder old = op.get(); + BeanUtils.copyProperties(old,order); + waitListOrderRepository.save(old); + LOGGER.info("[updateOrder][Update Wait List Order Info Success][OrderId: {}]",order.getId()); + return new Response<>(1, "Update Wait List Order Success", old); + } + } + + @Transactional + @Override + public Response modifyWaitListOrderStatus(int status, String orderId) { + LOGGER.info("[modifyWaitListOrderStatus][Modify Order Status][OrderId:{}] ", orderId); + Optional op = waitListOrderRepository.findById(orderId); + if(!op.isPresent()){ + LOGGER.error("[modifyWaitListOrderStatus][Modify Order Status Fail][Order not found][OrderId: {}]",orderId); + return new Response<>(0, "Order Not Found, Can't update", null); + } else { + WaitListOrder old = op.get(); + old.setStatus(status); + waitListOrderRepository.save(old); + LOGGER.info("[modifyWaitListOrderStatus][Modify Order Status Success][OrderId: {}]",orderId); + return new Response<>(1, "Modify Wait List Order Status Success", old); + } + } + + private Response saveNewOrder(WaitListOrderVO orderVO, HttpHeaders headers) { + ArrayList accountOrders= waitListOrderRepository.findByAccountId(orderVO.getAccountId()); + //if the order already exist + if(WaitListOrderExist(accountOrders,orderVO)){ + WaitListOrderServiceImpl.LOGGER.error("[create][Create Wait Order Fail][Order already exists][AccountId: {} , TripId: {}]", orderVO.getAccountId(),orderVO.getTripId()); + return new Response<>(0, "Order already exist", null); + } else { + WaitListOrder newWaitListOrder=new WaitListOrder(); + newWaitListOrder.setId(UUID.randomUUID().toString()); + BeanUtils.copyProperties(newWaitListOrder,orderVO); + newWaitListOrder.setTrainNumber(orderVO.getTripId()); + waitListOrderRepository.save(newWaitListOrder); + WaitListOrderServiceImpl.LOGGER.info("[create][Create Wait Order Success][Order Price][AccountId: {} , TripId: {}]", orderVO.getAccountId(),orderVO.getTripId()); + return new Response<>(1,success,newWaitListOrder); + } + } + + private Boolean WaitListOrderExist(List orderList,WaitListOrderVO newOrder){ + for(WaitListOrder order: orderList){ + if(Objects.equals(order.getAccountId(), newOrder.getAccountId()) + && Objects.equals(order.getContactsId(), newOrder.getContactsId()) + && Objects.equals(order.getTrainNumber(), newOrder.getTripId()) + && Objects.equals(order.getTravelTime(),newOrder.getDate()) + && Objects.equals(order.getFrom(),newOrder.getFrom()) + && Objects.equals(order.getTo(),newOrder.getTo())){ + return true; + } + } + return false; + } + + private Response triggerThread(WaitListOrder orderPO,WaitListOrderVO orderVO,HttpHeaders headers){ + PollThread pollThread; + try{ + pollThread =new PollThread(orderPO.getWaitUtilTime(),this,orderVO,restTemplate, headers); + pollThread.start(); + } catch (Exception e){ + return new Response<>(0, "Fail To Run A New Thread", null); + } + return new Response<>(1,"Thread Start Success",null); + } + + +} diff --git a/ts-wait-order-service/src/main/java/waitorder/service/WaitListOrderService.java b/ts-wait-order-service/src/main/java/waitorder/service/WaitListOrderService.java new file mode 100644 index 000000000..8b41e4228 --- /dev/null +++ b/ts-wait-order-service/src/main/java/waitorder/service/WaitListOrderService.java @@ -0,0 +1,30 @@ +package waitorder.service; + +import edu.fudan.common.util.Response; +import org.springframework.http.HttpHeaders; +import waitorder.entity.WaitListOrder; +import waitorder.entity.WaitListOrderVO; + +public interface WaitListOrderService { + + Response findOrderById(String id, HttpHeaders headers); + + Response create(WaitListOrderVO newOrder, HttpHeaders headers); + + /** + * Get all orders, including completed and expired ones + */ + Response getAllOrders(HttpHeaders headers); + + Response updateOrder(WaitListOrder order, HttpHeaders headers); + + /** + * Use when modifying order status + */ + Response modifyWaitListOrderStatus(int status, String orderId); + + /** + * Get all orders in the wait list + */ + Response getAllWaitListOrders(HttpHeaders headers); +} diff --git a/ts-wait-order-service/src/main/java/waitorder/utils/PollThread.java b/ts-wait-order-service/src/main/java/waitorder/utils/PollThread.java new file mode 100644 index 000000000..ff393d3ba --- /dev/null +++ b/ts-wait-order-service/src/main/java/waitorder/utils/PollThread.java @@ -0,0 +1,84 @@ +package waitorder.utils; + +import edu.fudan.common.entity.Contacts; +import edu.fudan.common.util.Response; +import org.springframework.core.ParameterizedTypeReference; +import org.springframework.http.HttpEntity; +import org.springframework.http.HttpHeaders; +import org.springframework.http.HttpMethod; +import org.springframework.http.ResponseEntity; +import org.springframework.web.client.RestTemplate; +import waitorder.entity.WaitListOrderStatus; +import waitorder.entity.WaitListOrderVO; +import waitorder.service.WaitListOrderService; + +import java.util.Date; +import java.util.concurrent.TimeUnit; + +public class PollThread extends Thread{ + + private Date waitUntil; + + private WaitListOrderVO waitListOrderVO; + + private HttpHeaders httpHeaders; + + private RestTemplate restTemplate; + + private WaitListOrderService waitListOrderService; + + final static Integer INTERVAL_MINUTES=5; + + public PollThread(Date waitUntilTime,WaitListOrderService service, WaitListOrderVO order, RestTemplate template, HttpHeaders headers){ + restTemplate=template; + httpHeaders=headers; + waitListOrderVO=order; + waitListOrderService =service; + waitUntil=waitUntilTime; + } + + + @Override + public void run() { + String service_url=getServiceUrl("ts-preserve-service"); + HttpEntity requestEntityPreserve = new HttpEntity(waitListOrderVO,httpHeaders); + + //TODO compare with waitUntilTime + while(true){ + long currentTime=System.currentTimeMillis(); + if(waitUntil.getTime()>currentTime){ + // expired + waitListOrderService.modifyWaitListOrderStatus(WaitListOrderStatus.EXPIRED.getCode(), waitListOrderVO.getAccountId()); + break; + } + Response postResult=doPreserve(service_url,requestEntityPreserve); + if(postResult.getStatus()==0){ + //预定失败 + try { + TimeUnit.MINUTES.sleep(INTERVAL_MINUTES); + } catch (InterruptedException e) { + e.printStackTrace(); + } + } else{ + // preserve success + waitListOrderService.modifyWaitListOrderStatus(WaitListOrderStatus.COLLECTED.getCode(),waitListOrderVO.getAccountId()); + break; + } + } + } + + private String getServiceUrl(String serviceName) { + return "http://" + serviceName; + } + + private Response doPreserve(String url, HttpEntity requestParam){ + ResponseEntity> rePostPreserveResult = restTemplate.exchange( + url + "/api/v1/contactservice/preserve", + HttpMethod.POST, + requestParam, + new ParameterizedTypeReference>() { + }); + return rePostPreserveResult.getBody(); + } + +} diff --git a/ts-wait-order-service/src/main/resources/application.yml b/ts-wait-order-service/src/main/resources/application.yml new file mode 100644 index 000000000..86facba88 --- /dev/null +++ b/ts-wait-order-service/src/main/resources/application.yml @@ -0,0 +1,25 @@ +# HTTP Server +server: + port: 17525 # HTTP (Tomcat) port + +spring: + cloud: + nacos: + discovery: + server-addr: ${NACOS_ADDRS:127.0.0.1:8848} + application: + name: ts-wait-order-service + datasource: + url: jdbc:mysql://${WAIT_ORDER_MYSQL_HOST:10.176.122.1}:${WAIT_ORDER_MYSQL_PORT:3306}/${WAIT_ORDER_MYSQL_DATABASE:ts}?useSSL=false + username: ${WAIT_ORDER_MYSQL_USER:root} + password: ${WAIT_ORDER_PASSWORD:Abcd1234#} + driver-class-name: com.mysql.cj.jdbc.Driver + jpa: + hibernate: + ddl-auto: update + properties: + hibernate: + dialect: org.hibernate.dialect.MySQL5Dialect + +swagger: + controllerPackage: waitorder.controller \ No newline at end of file diff --git a/ts-wait-order-service/src/test/java/waitorder/WaitOrderApplicationTests.java b/ts-wait-order-service/src/test/java/waitorder/WaitOrderApplicationTests.java new file mode 100644 index 000000000..df4d97550 --- /dev/null +++ b/ts-wait-order-service/src/test/java/waitorder/WaitOrderApplicationTests.java @@ -0,0 +1,13 @@ +package waitorder; + +import org.junit.jupiter.api.Test; +import org.springframework.boot.test.context.SpringBootTest; + +@SpringBootTest +class WaitOrderApplicationTests { + + @Test + void contextLoads() { + } + +} diff --git a/ts-wait-order-service/src/test/java/waitorder/service/Impl/WaitListOrderServiceImplTest.java b/ts-wait-order-service/src/test/java/waitorder/service/Impl/WaitListOrderServiceImplTest.java new file mode 100644 index 000000000..045a22b07 --- /dev/null +++ b/ts-wait-order-service/src/test/java/waitorder/service/Impl/WaitListOrderServiceImplTest.java @@ -0,0 +1,52 @@ +package waitorder.service.Impl; + +import java.util.Optional; +import edu.fudan.common.util.Response; +import org.junit.Before; +import org.junit.BeforeClass; +import org.junit.jupiter.api.Assertions; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.junit.runners.JUnit4; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.Mockito; +import org.mockito.MockitoAnnotations; +import org.springframework.http.HttpHeaders; +import waitorder.entity.WaitListOrder; +import waitorder.repository.WaitListOrderRepository; + + +@RunWith(JUnit4.class) +public class WaitListOrderServiceImplTest { + + @InjectMocks + private WaitListOrderServiceImpl waitListOrderServiceImpl; + + @Mock + private WaitListOrderRepository repository; + + private HttpHeaders headers = new HttpHeaders(); + + @Before + public void setUp() { + MockitoAnnotations.initMocks(this); + } + + @Test + public void findOrderById() { + + Mockito.when(repository.findById(Mockito.any(String.class))).thenReturn(Optional.ofNullable(null)); + Response response=waitListOrderServiceImpl.findOrderById("id",headers); + Assertions.assertEquals(new Response<>(0, "No Content by this id", null), response); + } + + @Test + public void getAllOrders() { + Mockito.when(repository.findAll()).thenReturn(null); + Response res = waitListOrderServiceImpl.getAllOrders(headers); + Assertions.assertEquals(new Response<>(0,"No Content.",null),res); + } + + +} \ No newline at end of file